code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module TCompile where
import Utils
import Parser
import qualified Data.Map as HashTable
type HashTable a = HashTable.Map String a
type FuncTable = HashTable (Type, [Type])
data Op = OpOp String | OpFunc | OpParam Int Bool | OpCall | OpRet | OpEnd | OpJr | OpPAt | OpGet | OpAloc Int
| OpAt | OpJp | OpLb | OpIfFalse | OpIfFalseDe | OpPrint | OpPrintLC | OpRd
| OpSc | OpDeSc Bool deriving (Show)
data Value = Const ValueType | UVar String | Label String | TVar (String, Type) | Null deriving (Show)
type Code = (Op, Value, Value, Value)
compile :: [Func] -> [Code]
compile fs = (OpCall, TVar ("0t", TInt), UVar main, Null) : (OpEnd, Null, Null, Null) : (compileFuncs fMap hs fs1)
where (fs1, fMap) = renameFuncs HashTable.empty 1 fs
hs = buildFuncMap fs1
main = fromJust ("function main not defined") (HashTable.lookup "main" fMap)
renameFuncs :: HashTable String -> Int -> [Func] -> ([Func], HashTable String)
renameFuncs fMap _ [] = ([], fMap)
renameFuncs fMap vl ((Func (nm, tp1) ls cmd):fs) = ((Func (fname, tp1) ls cmd) : funcs, fMap1)
where fname = "F" ++ (show vl)
(funcs, fMap1) = renameFuncs (HashTable.insert nm fname fMap) (vl + 1) fs
buildFuncMap :: [Func] -> FuncTable
buildFuncMap [] = HashTable.empty
buildFuncMap ((Func (nm, tp1) ls _):fs) = HashTable.insert nm (tp1, getArgTypes ls) (buildFuncMap fs)
getArgTypes :: [(String, Type)] -> [Type]
getArgTypes [] = []
getArgTypes ((_, tp):xs) = tp : (getArgTypes xs)
compileFuncs :: HashTable String -> FuncTable -> [Func] -> [Code]
compileFuncs _ _ [] = []
compileFuncs fMap hs (f:fs) = (compileFunc fMap hs f) ++ (compileFuncs fMap hs fs)
compileFunc :: HashTable String -> FuncTable -> Func -> [Code]
compileFunc fMap hs (Func nm args cmd) = [(OpSc, UVar "0j", Null, Null)]
++ [(OpFunc, TVar nm, Null, Null)]
++ paramsCode
++ code
++ [(OpDeSc True, Null, Null, Null)]
where paramsCode = compileParamsDef args 0
code = compileCmds fMap hs (snd nm) cmd
compileParamsDef :: [(String, Type)] -> Int -> [Code]
compileParamsDef [] _ = []
compileParamsDef (x:xs) curPar = [(OpParam curPar True, TVar x, Null, Null)] ++ (compileParamsDef xs (curPar + 1))
compileParamsCall :: HashTable String -> FuncTable -> [Expr] -> [Type] -> Int -> Int -> ([Code], Int)
compileParamsCall _ _ [] _ nx _ = ([], nx)
compileParamsCall fMap hs (x:xs) (tp:ts) nx curPar = (expCode
++ [(OpParam curPar False, TVar (var, tp), Null, Null)]
++ paramsCode, nx2)
where (var, expCode, nx1) = compileExp fMap hs nx x
(paramsCode, nx2) = (compileParamsCall fMap hs xs ts nx1 (curPar + 1))
compileCmds :: HashTable String -> FuncTable -> Type -> Command -> [Code]
compileCmds fMap hs ftp cmd = (fst (compileCmd fMap hs ftp 0 cmd))
compileCmd :: HashTable String -> FuncTable -> Type -> Int -> Command -> ([Code], Int)
compileCmd fMap hs ftp lbNum (While exp cmd) = ([(OpLb, Label (show lbNum), Null, Null)]
++ [(OpSc, Null, Null, Null)]
++ expCode
++ [(OpIfFalseDe, UVar expVar, Label (show (lbNum + 1)), Null)]
++ [(OpSc, Null, Null, Null)]
++ code
++ [(OpDeSc True, Null, Null, Null)]
++ [(OpJp, Label (show lbNum), Null, Null)]
++ [(OpLb, Label (show (lbNum + 1)), Null, Null)], lbNum1 + 1)
where (expVar, expCode, _) = compileExp fMap hs 0 exp
(code, lbNum1) = compileCmd fMap hs ftp (lbNum + 2) cmd
compileCmd fMap hs ftp lbNum (Attr (SVar var) exp) = (expCode ++ [(OpAt, UVar var, UVar expVar, Null)], lbNum)
where (expVar, expCode, _) = compileExp fMap hs 0 exp
compileCmd fMap hs ftp lbNum (Attr (PVar var exp1) exp2) = (expCode1 ++ expCode2 ++ [(OpPAt, UVar var, UVar expVar1, UVar expVar2)], lbNum)
where (expVar1, expCode1, v1) = compileExp fMap hs 0 exp1
(expVar2, expCode2, _) = compileExp fMap hs v1 exp2
compileCmd fMap hs ftp lbNum (Aloc var tp sz) = ([(OpAloc sz, TVar (var, TPointer tp), Null, Null)], lbNum)
compileCmd fMap hs ftp lbNum (Print ls) = ((compilePrint fMap hs ls) ++ [(OpPrintLC, Null, Null, Null)], lbNum)
compileCmd fMap hs ftp lbNum (IfCmd iflist) = compileIfList fMap hs ftp lbNum iflist
compileCmd fMap hs ftp lbNum (Ret exp) = (expCode ++ [(OpRet, TVar (expVar, ftp), Null, Null)] ++ [(OpDeSc False, Null, Null, Null)] ++ [(OpJr, Null, Null, Null)], lbNum)
where (expVar, expCode, _) = compileExp fMap hs 0 exp
compileCmd fMap hs ftp lbNum (Seq cmd1 cmd2) = (code1 ++ code2, lbNum2)
where (code1, lbNum1) = compileCmd fMap hs ftp lbNum cmd1
(code2, lbNum2) = compileCmd fMap hs ftp lbNum1 cmd2
compileCmd _ _ ftp lbNum None = ([], lbNum)
compilePrint :: HashTable String -> FuncTable -> [Expr] -> [Code]
compilePrint _ _ [] = []
compilePrint fMap hs (exp:xs) = expCode ++ [(OpPrint, UVar expVar, Null, Null)] ++ (compilePrint fMap hs xs)
where (expVar, expCode, _) = compileExp fMap hs 0 exp
compileIfList :: HashTable String -> FuncTable -> Type -> Int -> IfList -> ([Code], Int)
compileIfList fMap hs ftp lbNum (If ifArr elseCmd) = (ifsCode
++ [(OpSc, Null, Null, Null)]
++ elseCode
++ [(OpDeSc True, Null, Null, Null)]
++ [(OpLb, Label (show lbNum), Null, Null)], lbNum2)
where (ifsCode, lbNum1) = compileIfs fMap hs ftp lbNum ifArr (lbNum + 1)
(elseCode, lbNum2) = compileCmd fMap hs ftp lbNum1 elseCmd
compileIfs :: HashTable String -> FuncTable -> Type -> Int -> [(Expr, Command)] -> Int -> ([Code], Int)
compileIfs fMap hs _ endLb [] lbNum = ([], lbNum)
compileIfs fMap hs ftp endLb (x:xs) lbNum = ([(OpSc, Null, Null, Null)]
++ expCode
++ [(OpIfFalseDe, UVar expVar, Label (show lbNum), Null)]
++ [(OpSc, Null, Null, Null)]
++ cmdCode
++ [(OpDeSc True, Null, Null, Null)]
++ [(OpJp, Label (show endLb), Null, Null)]
++ [(OpLb, Label (show lbNum), Null, Null)]
++ ifsCode, lbNumF)
where (expVar, expCode, _) = compileExp fMap hs 0 (fst x)
(cmdCode, lbNum1) = compileCmd fMap hs ftp (lbNum + 1) (snd x)
(ifsCode, lbNumF) = compileIfs fMap hs ftp endLb xs lbNum1
newVar :: Int -> String
newVar nx = (show nx) ++ "t"
compileExp :: HashTable String -> FuncTable -> Int -> Expr -> (String, [Code], Int)
compileExp _ _ nx (EConst bl) = (var, [(OpAt, UVar var, Const bl, Null)], nx + 1)
where var = newVar nx
compileExp _ _ nx (EVar (SVar var)) = (var, [], nx)
compileExp fMap hs nx (EVar (PVar var exp)) = (nvar, expCode ++ [(OpGet, UVar nvar, UVar expVar, UVar var)], nx1)
where nvar = newVar nx
(expVar, expCode, nx1) = compileExp fMap hs (nx + 1) exp
compileExp fMap hs nx (FCall str1 args) = (var, paramsCode
++ [(OpCall, TVar (var, fType), UVar str, Null)], nx1 + 1)
where str = fromJust ("function " ++ str1 ++ " not defined") (HashTable.lookup str1 fMap)
(fType, argTypes) = fromJust ("function " ++ str ++ " not defined") (HashTable.lookup str hs)
(paramsCode, nx1) = compileParamsCall fMap hs args argTypes nx 0
var = newVar nx1
compileExp _ _ nx (Read tp) = (var, [(OpRd, TVar (var, tp), Null, Null)], nx + 1)
where var = newVar nx
compileExp fMap hs nx (BiOperation exp1 opBi exp2) = (var, cexp1
++ cexp2
++ [(OpOp opBi, UVar var, UVar var1, UVar var2)], nx2 + 1)
where (var1, cexp1, nx1) = compileExp fMap hs nx exp1
(var2, cexp2, nx2) = compileExp fMap hs nx1 exp2
var = newVar nx2
compileExp fMap hs nx (UnOperation opUn exp1) = (var, cexp1
++ [(OpOp opUn, UVar var, UVar var1, Null)], nx1 + 1)
where (var1, cexp1, nx1) = compileExp fMap hs nx exp1
var = newVar nx1
|
gangsterveggies/julia-pinheiro-compiler
|
TCompile.hs
|
gpl-2.0
| 8,721 | 0 | 18 | 2,815 | 3,557 | 1,958 | 1,599 | 129 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.LevelPuzzle.Helpers.Make
(
loadLevelPuzzleWorld,
levelpuzzleSetLevelNext,
levelpuzzleSetLevelIx,
) where
import MyPrelude
import Game
import Game.LevelPuzzle.LevelPuzzleWorld
import Game.LevelPuzzle.LevelPuzzleWorld.OutputState
import Game.LevelPuzzle.Helpers
import Game.LevelPuzzle.File
import System.IO
import File.Binary
-- | load LevelPuzzleWorld from path, starting at level ix
loadLevelPuzzleWorld :: FilePath -> UInt -> MEnv' LevelPuzzleWorld
loadLevelPuzzleWorld path ix = do
(creator, name) <- io $ readBinary' rLevelPuzzleWorld path
filesize <- io $ withBinaryFile path ReadMode $ \h -> fI `fmap` hFileSize h
off <- io $ readBinary' (rLevelOffset ix) path
if off == filesize
-- make complete LevelPuzzleWorld
then do
let level = makeLevelEmpty
cnt <- makeContentEmpty
cnt' <- makeContentEmpty
state <- makeOutputState
return LevelPuzzleWorld
{
levelpuzzleCreator = creator,
levelpuzzleName = name,
levelpuzzleLevelIx = ix,
levelpuzzleLevel = level,
levelpuzzleOldContent = cnt,
levelpuzzleContent = cnt',
levelpuzzleRefOldContent = mempty,
levelpuzzleRefSpace = mempty,
levelpuzzleIsPuzzle = False,
levelpuzzleEvents = [],
levelpuzzleSegmentsCount = 0,
levelpuzzleIsComplete = True,
levelpuzzleFailureEvent = EventEmpty,
levelpuzzleOutputState = state,
levelpuzzleFile = path,
levelpuzzleFileSize = filesize,
levelpuzzleFileDefOffset = off,
levelpuzzleFileDefNextOffset = off
}
-- make LevelPuzzleWorld at level ix
else do
-- parse file
(level, ixrooms, off') <- io $ readBinaryAt' rLevel path off
cnt <- makeContentEmpty
bonusAdd <- countBonusAdd (map snd ixrooms)
cnt' <- makeContentCamera (levelSegments level + bonusAdd) ixrooms $
makeCameraView valueLevelPuzzleGridView
state <- makeOutputState
return LevelPuzzleWorld
{
levelpuzzleCreator = creator,
levelpuzzleName = name,
levelpuzzleLevelIx = ix,
levelpuzzleLevel = level,
levelpuzzleOldContent = cnt,
levelpuzzleContent = cnt',
levelpuzzleRefOldContent = mempty,
levelpuzzleRefSpace = mempty,
levelpuzzleIsPuzzle = False,
levelpuzzleEvents = [],
levelpuzzleSegmentsCount = levelSegments level,
levelpuzzleIsComplete = False,
levelpuzzleFailureEvent = EventEmpty,
levelpuzzleOutputState = state,
levelpuzzleFile = path,
levelpuzzleFileSize = filesize,
levelpuzzleFileDefOffset = off,
levelpuzzleFileDefNextOffset = off'
}
--------------------------------------------------------------------------------
-- destroy
destroyLevelPuzzleWorld :: LevelPuzzleWorld -> MEnv' ()
destroyLevelPuzzleWorld lvl =
io $ fixme "destroyLevelPuzzleWorld"
--------------------------------------------------------------------------------
--
-- | load next level from levelpuzzleFileXXX
levelpuzzleSetLevelNext :: LevelPuzzleWorld -> MEnv' LevelPuzzleWorld
levelpuzzleSetLevelNext lvl = do
-- next level exists?
if levelpuzzleFileDefNextOffset lvl == levelpuzzleFileSize lvl
-- complete
then do
destroyContent $ levelpuzzleOldContent lvl
let cnt = levelpuzzleContent lvl
cnt' <- makeContentEmpty
return lvl
{
levelpuzzleLevelIx = levelpuzzleLevelIx lvl + 1,
levelpuzzleOldContent = cnt,
levelpuzzleContent = cnt',
levelpuzzleRefOldContent = refOldContent lvl,
levelpuzzleRefSpace = refSpace lvl,
levelpuzzleIsComplete = True
}
else do
-- parse file at offset
(level, ixrooms, off') <- io $ readBinaryAt' rLevel
(levelpuzzleFile lvl)
(levelpuzzleFileDefNextOffset lvl)
-- make Content
destroyContent $ levelpuzzleOldContent lvl
let cnt = levelpuzzleContent lvl
bonusAdd <- countBonusAdd (map snd ixrooms)
cnt' <- makeContentCamera (levelSegments level + bonusAdd) ixrooms $
gridCamera $ contentGrid cnt
return lvl
{
levelpuzzleLevelIx = levelpuzzleLevelIx lvl + 1,
levelpuzzleLevel = level,
levelpuzzleOldContent = cnt,
levelpuzzleContent = contentCopySpeed cnt' cnt,
levelpuzzleRefOldContent = refOldContent lvl,
levelpuzzleRefSpace = refSpace lvl,
levelpuzzleSegmentsCount = levelSegments level,
levelpuzzleFileDefOffset = levelpuzzleFileDefNextOffset lvl,
levelpuzzleFileDefNextOffset = off'
}
where
contentCopySpeed new old =
let speed = pathSpeed $ gridPath $ contentGrid $ old
in contentModifyGrid new $ \grid -> gridModifyPath grid $ \path ->
path { pathSpeed = speed }
-- | load level ix from levelpuzzleFileXXX
levelpuzzleSetLevelIx :: LevelPuzzleWorld -> UInt -> MEnv' LevelPuzzleWorld
levelpuzzleSetLevelIx lvl ix = do
off <- io $ readBinary' (rLevelOffset ix) (levelpuzzleFile lvl)
if off == levelpuzzleFileSize lvl
-- complete
then do
return lvl
{
levelpuzzleIsComplete = True,
levelpuzzleLevelIx = ix
}
else do
-- parse file
(level, ixrooms, off') <- io $ readBinaryAt' rLevel (levelpuzzleFile lvl) off
-- make
destroyContent $ levelpuzzleContent lvl
destroyContent $ levelpuzzleOldContent lvl
cnt <- makeContentEmpty
bonusAdd <- countBonusAdd (map snd ixrooms)
cnt' <- makeContentCamera (levelSegments level + bonusAdd) ixrooms $
makeCameraView valueLevelPuzzleGridView
return lvl
{
levelpuzzleLevelIx = ix,
levelpuzzleLevel = level,
levelpuzzleOldContent = cnt,
levelpuzzleContent = cnt',
levelpuzzleRefOldContent = refOldContent lvl,
levelpuzzleRefSpace = refSpace lvl,
levelpuzzleIsComplete = False,
levelpuzzleEvents = [],
levelpuzzleSegmentsCount = levelSegments level,
levelpuzzleFileDefOffset = off,
levelpuzzleFileDefNextOffset = off'
}
--------------------------------------------------------------------------------
--
countBonusAdd :: [Room] -> MEnv' UInt
countBonusAdd rooms = io $ do
add <- helper 0 rooms
return add
where
helper n [] =
return n
helper n (r:rs) = do
let arr = roomDotBonus r
size = roomDotBonusSize r
n' <- foldM (step arr) n (range 0 size)
helper n' rs
step arr = \n ix -> do
dot <- dotbonusarrayAt arr ix
return $ n + dotbonusCount dot * dotbonusAdd dot
refOldContent :: LevelPuzzleWorld -> Segment
refOldContent lvl =
segmentInverse $ pathCurrent $ levelpuzzlePath lvl
refSpace :: LevelPuzzleWorld -> Turn
refSpace lvl =
levelpuzzleRefSpace lvl `mappend` (turnInverse $ pathTurn $ levelpuzzlePath lvl)
|
karamellpelle/grid
|
source/Game/LevelPuzzle/Helpers/Make.hs
|
gpl-3.0
| 8,891 | 0 | 16 | 3,080 | 1,530 | 822 | 708 | 157 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudWatchLogs.DescribeLogGroups
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns all the log groups that are associated with the AWS account making
-- the request. The list returned in the response is ASCII-sorted by log group
-- name.
--
-- By default, this operation returns up to 50 log groups. If there are more
-- log groups to list, the response would contain a 'nextToken' value in the
-- response body. You can also limit the number of log groups returned in the
-- response by specifying the 'limit' parameter in the request.
--
-- <http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogGroups.html>
module Network.AWS.CloudWatchLogs.DescribeLogGroups
(
-- * Request
DescribeLogGroups
-- ** Request constructor
, describeLogGroups
-- ** Request lenses
, dlgLimit
, dlgLogGroupNamePrefix
, dlgNextToken
-- * Response
, DescribeLogGroupsResponse
-- ** Response constructor
, describeLogGroupsResponse
-- ** Response lenses
, dlgrLogGroups
, dlgrNextToken
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CloudWatchLogs.Types
import qualified GHC.Exts
data DescribeLogGroups = DescribeLogGroups
{ _dlgLimit :: Maybe Nat
, _dlgLogGroupNamePrefix :: Maybe Text
, _dlgNextToken :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'DescribeLogGroups' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dlgLimit' @::@ 'Maybe' 'Natural'
--
-- * 'dlgLogGroupNamePrefix' @::@ 'Maybe' 'Text'
--
-- * 'dlgNextToken' @::@ 'Maybe' 'Text'
--
describeLogGroups :: DescribeLogGroups
describeLogGroups = DescribeLogGroups
{ _dlgLogGroupNamePrefix = Nothing
, _dlgNextToken = Nothing
, _dlgLimit = Nothing
}
-- | The maximum number of items returned in the response. If you don't specify a
-- value, the request would return up to 50 items.
dlgLimit :: Lens' DescribeLogGroups (Maybe Natural)
dlgLimit = lens _dlgLimit (\s a -> s { _dlgLimit = a }) . mapping _Nat
dlgLogGroupNamePrefix :: Lens' DescribeLogGroups (Maybe Text)
dlgLogGroupNamePrefix =
lens _dlgLogGroupNamePrefix (\s a -> s { _dlgLogGroupNamePrefix = a })
-- | A string token used for pagination that points to the next page of results.
-- It must be a value obtained from the response of the previous 'DescribeLogGroups' request.
dlgNextToken :: Lens' DescribeLogGroups (Maybe Text)
dlgNextToken = lens _dlgNextToken (\s a -> s { _dlgNextToken = a })
data DescribeLogGroupsResponse = DescribeLogGroupsResponse
{ _dlgrLogGroups :: List "logGroups" LogGroup
, _dlgrNextToken :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'DescribeLogGroupsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dlgrLogGroups' @::@ ['LogGroup']
--
-- * 'dlgrNextToken' @::@ 'Maybe' 'Text'
--
describeLogGroupsResponse :: DescribeLogGroupsResponse
describeLogGroupsResponse = DescribeLogGroupsResponse
{ _dlgrLogGroups = mempty
, _dlgrNextToken = Nothing
}
dlgrLogGroups :: Lens' DescribeLogGroupsResponse [LogGroup]
dlgrLogGroups = lens _dlgrLogGroups (\s a -> s { _dlgrLogGroups = a }) . _List
dlgrNextToken :: Lens' DescribeLogGroupsResponse (Maybe Text)
dlgrNextToken = lens _dlgrNextToken (\s a -> s { _dlgrNextToken = a })
instance ToPath DescribeLogGroups where
toPath = const "/"
instance ToQuery DescribeLogGroups where
toQuery = const mempty
instance ToHeaders DescribeLogGroups
instance ToJSON DescribeLogGroups where
toJSON DescribeLogGroups{..} = object
[ "logGroupNamePrefix" .= _dlgLogGroupNamePrefix
, "nextToken" .= _dlgNextToken
, "limit" .= _dlgLimit
]
instance AWSRequest DescribeLogGroups where
type Sv DescribeLogGroups = CloudWatchLogs
type Rs DescribeLogGroups = DescribeLogGroupsResponse
request = post "DescribeLogGroups"
response = jsonResponse
instance FromJSON DescribeLogGroupsResponse where
parseJSON = withObject "DescribeLogGroupsResponse" $ \o -> DescribeLogGroupsResponse
<$> o .:? "logGroups" .!= mempty
<*> o .:? "nextToken"
|
dysinger/amazonka
|
amazonka-cloudwatch-logs/gen/Network/AWS/CloudWatchLogs/DescribeLogGroups.hs
|
mpl-2.0
| 5,207 | 0 | 12 | 1,103 | 672 | 401 | 271 | 73 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.HTTPSHealthChecks.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)
--
-- Retrieves the list of HttpsHealthCheck resources available to the
-- specified project.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.httpsHealthChecks.list@.
module Network.Google.Resource.Compute.HTTPSHealthChecks.List
(
-- * REST Resource
HTTPSHealthChecksListResource
-- * Creating a Request
, httpsHealthChecksList
, HTTPSHealthChecksList
-- * Request Lenses
, hhclOrderBy
, hhclProject
, hhclFilter
, hhclPageToken
, hhclMaxResults
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.httpsHealthChecks.list@ method which the
-- 'HTTPSHealthChecksList' request conforms to.
type HTTPSHealthChecksListResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"httpsHealthChecks" :>
QueryParam "orderBy" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] HTTPSHealthCheckList
-- | Retrieves the list of HttpsHealthCheck resources available to the
-- specified project.
--
-- /See:/ 'httpsHealthChecksList' smart constructor.
data HTTPSHealthChecksList = HTTPSHealthChecksList'
{ _hhclOrderBy :: !(Maybe Text)
, _hhclProject :: !Text
, _hhclFilter :: !(Maybe Text)
, _hhclPageToken :: !(Maybe Text)
, _hhclMaxResults :: !(Textual Word32)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'HTTPSHealthChecksList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hhclOrderBy'
--
-- * 'hhclProject'
--
-- * 'hhclFilter'
--
-- * 'hhclPageToken'
--
-- * 'hhclMaxResults'
httpsHealthChecksList
:: Text -- ^ 'hhclProject'
-> HTTPSHealthChecksList
httpsHealthChecksList pHhclProject_ =
HTTPSHealthChecksList'
{ _hhclOrderBy = Nothing
, _hhclProject = pHhclProject_
, _hhclFilter = Nothing
, _hhclPageToken = Nothing
, _hhclMaxResults = 500
}
-- | Sorts list results by a certain order. By default, results are returned
-- in alphanumerical order based on the resource name. You can also sort
-- results in descending order based on the creation timestamp using
-- orderBy=\"creationTimestamp desc\". This sorts results based on the
-- creationTimestamp field in reverse chronological order (newest result
-- first). Use this to sort resources like operations so that the newest
-- operation is returned first. Currently, only sorting by name or
-- creationTimestamp desc is supported.
hhclOrderBy :: Lens' HTTPSHealthChecksList (Maybe Text)
hhclOrderBy
= lens _hhclOrderBy (\ s a -> s{_hhclOrderBy = a})
-- | Project ID for this request.
hhclProject :: Lens' HTTPSHealthChecksList Text
hhclProject
= lens _hhclProject (\ s a -> s{_hhclProject = a})
-- | Sets a filter expression for filtering listed resources, in the form
-- filter={expression}. Your {expression} must be in the format: field_name
-- comparison_string literal_string. The field_name is the name of the
-- field you want to compare. Only atomic field types are supported
-- (string, number, boolean). The comparison_string must be either eq
-- (equals) or ne (not equals). The literal_string is the string value to
-- filter to. The literal value must be valid for the type of field you are
-- filtering by (string, number, boolean). For string fields, the literal
-- value is interpreted as a regular expression using RE2 syntax. The
-- literal value must match the entire field. For example, to filter for
-- instances that do not have a name of example-instance, you would use
-- filter=name ne example-instance. You can filter on nested fields. For
-- example, you could filter on instances that have set the
-- scheduling.automaticRestart field to true. Use filtering on nested
-- fields to take advantage of labels to organize and search for results
-- based on label values. To filter on multiple expressions, provide each
-- separate expression within parentheses. For example,
-- (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple
-- expressions are treated as AND expressions, meaning that resources must
-- match all expressions to pass the filters.
hhclFilter :: Lens' HTTPSHealthChecksList (Maybe Text)
hhclFilter
= lens _hhclFilter (\ s a -> s{_hhclFilter = a})
-- | Specifies a page token to use. Set pageToken to the nextPageToken
-- returned by a previous list request to get the next page of results.
hhclPageToken :: Lens' HTTPSHealthChecksList (Maybe Text)
hhclPageToken
= lens _hhclPageToken
(\ s a -> s{_hhclPageToken = a})
-- | The maximum number of results per page that should be returned. If the
-- number of available results is larger than maxResults, Compute Engine
-- returns a nextPageToken that can be used to get the next page of results
-- in subsequent list requests.
hhclMaxResults :: Lens' HTTPSHealthChecksList Word32
hhclMaxResults
= lens _hhclMaxResults
(\ s a -> s{_hhclMaxResults = a})
. _Coerce
instance GoogleRequest HTTPSHealthChecksList where
type Rs HTTPSHealthChecksList = HTTPSHealthCheckList
type Scopes HTTPSHealthChecksList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient HTTPSHealthChecksList'{..}
= go _hhclProject _hhclOrderBy _hhclFilter
_hhclPageToken
(Just _hhclMaxResults)
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy HTTPSHealthChecksListResource)
mempty
|
rueshyna/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/HTTPSHealthChecks/List.hs
|
mpl-2.0
| 6,854 | 0 | 18 | 1,484 | 678 | 409 | 269 | 98 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.ServiceBroker.SetIAMPolicy
-- 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)
--
-- Sets the access control policy on the specified resource. Replaces any
-- existing policy. Can return Public Errors: NOT_FOUND, INVALID_ARGUMENT
-- and PERMISSION_DENIED
--
-- /See:/ <https://cloud.google.com/kubernetes-engine/docs/concepts/add-on/service-broker Service Broker API Reference> for @servicebroker.setIamPolicy@.
module Network.Google.Resource.ServiceBroker.SetIAMPolicy
(
-- * REST Resource
SetIAMPolicyResource
-- * Creating a Request
, setIAMPolicy
, SetIAMPolicy
-- * Request Lenses
, sipXgafv
, sipUploadProtocol
, sipAccessToken
, sipUploadType
, sipPayload
, sipResource
, sipCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceBroker.Types
-- | A resource alias for @servicebroker.setIamPolicy@ method which the
-- 'SetIAMPolicy' request conforms to.
type SetIAMPolicyResource =
"v1" :>
CaptureMode "resource" "setIamPolicy" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] GoogleIAMV1__SetIAMPolicyRequest :>
Post '[JSON] GoogleIAMV1__Policy
-- | Sets the access control policy on the specified resource. Replaces any
-- existing policy. Can return Public Errors: NOT_FOUND, INVALID_ARGUMENT
-- and PERMISSION_DENIED
--
-- /See:/ 'setIAMPolicy' smart constructor.
data SetIAMPolicy =
SetIAMPolicy'
{ _sipXgafv :: !(Maybe Xgafv)
, _sipUploadProtocol :: !(Maybe Text)
, _sipAccessToken :: !(Maybe Text)
, _sipUploadType :: !(Maybe Text)
, _sipPayload :: !GoogleIAMV1__SetIAMPolicyRequest
, _sipResource :: !Text
, _sipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SetIAMPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sipXgafv'
--
-- * 'sipUploadProtocol'
--
-- * 'sipAccessToken'
--
-- * 'sipUploadType'
--
-- * 'sipPayload'
--
-- * 'sipResource'
--
-- * 'sipCallback'
setIAMPolicy
:: GoogleIAMV1__SetIAMPolicyRequest -- ^ 'sipPayload'
-> Text -- ^ 'sipResource'
-> SetIAMPolicy
setIAMPolicy pSipPayload_ pSipResource_ =
SetIAMPolicy'
{ _sipXgafv = Nothing
, _sipUploadProtocol = Nothing
, _sipAccessToken = Nothing
, _sipUploadType = Nothing
, _sipPayload = pSipPayload_
, _sipResource = pSipResource_
, _sipCallback = Nothing
}
-- | V1 error format.
sipXgafv :: Lens' SetIAMPolicy (Maybe Xgafv)
sipXgafv = lens _sipXgafv (\ s a -> s{_sipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
sipUploadProtocol :: Lens' SetIAMPolicy (Maybe Text)
sipUploadProtocol
= lens _sipUploadProtocol
(\ s a -> s{_sipUploadProtocol = a})
-- | OAuth access token.
sipAccessToken :: Lens' SetIAMPolicy (Maybe Text)
sipAccessToken
= lens _sipAccessToken
(\ s a -> s{_sipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
sipUploadType :: Lens' SetIAMPolicy (Maybe Text)
sipUploadType
= lens _sipUploadType
(\ s a -> s{_sipUploadType = a})
-- | Multipart request metadata.
sipPayload :: Lens' SetIAMPolicy GoogleIAMV1__SetIAMPolicyRequest
sipPayload
= lens _sipPayload (\ s a -> s{_sipPayload = a})
-- | REQUIRED: The resource for which the policy is being specified. See the
-- operation documentation for the appropriate value for this field.
sipResource :: Lens' SetIAMPolicy Text
sipResource
= lens _sipResource (\ s a -> s{_sipResource = a})
-- | JSONP
sipCallback :: Lens' SetIAMPolicy (Maybe Text)
sipCallback
= lens _sipCallback (\ s a -> s{_sipCallback = a})
instance GoogleRequest SetIAMPolicy where
type Rs SetIAMPolicy = GoogleIAMV1__Policy
type Scopes SetIAMPolicy =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient SetIAMPolicy'{..}
= go _sipResource _sipXgafv _sipUploadProtocol
_sipAccessToken
_sipUploadType
_sipCallback
(Just AltJSON)
_sipPayload
serviceBrokerService
where go
= buildClient (Proxy :: Proxy SetIAMPolicyResource)
mempty
|
brendanhay/gogol
|
gogol-servicebroker/gen/Network/Google/Resource/ServiceBroker/SetIAMPolicy.hs
|
mpl-2.0
| 5,258 | 0 | 16 | 1,178 | 780 | 456 | 324 | 112 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Dataproc.Projects.Regions.Jobs.Patch
-- 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)
--
-- Updates a job in a project.
--
-- /See:/ <https://cloud.google.com/dataproc/ Cloud Dataproc API Reference> for @dataproc.projects.regions.jobs.patch@.
module Network.Google.Resource.Dataproc.Projects.Regions.Jobs.Patch
(
-- * REST Resource
ProjectsRegionsJobsPatchResource
-- * Creating a Request
, projectsRegionsJobsPatch
, ProjectsRegionsJobsPatch
-- * Request Lenses
, prjpXgafv
, prjpJobId
, prjpUploadProtocol
, prjpUpdateMask
, prjpAccessToken
, prjpUploadType
, prjpPayload
, prjpRegion
, prjpProjectId
, prjpCallback
) where
import Network.Google.Dataproc.Types
import Network.Google.Prelude
-- | A resource alias for @dataproc.projects.regions.jobs.patch@ method which the
-- 'ProjectsRegionsJobsPatch' request conforms to.
type ProjectsRegionsJobsPatchResource =
"v1" :>
"projects" :>
Capture "projectId" Text :>
"regions" :>
Capture "region" Text :>
"jobs" :>
Capture "jobId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "updateMask" GFieldMask :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Job :> Patch '[JSON] Job
-- | Updates a job in a project.
--
-- /See:/ 'projectsRegionsJobsPatch' smart constructor.
data ProjectsRegionsJobsPatch =
ProjectsRegionsJobsPatch'
{ _prjpXgafv :: !(Maybe Xgafv)
, _prjpJobId :: !Text
, _prjpUploadProtocol :: !(Maybe Text)
, _prjpUpdateMask :: !(Maybe GFieldMask)
, _prjpAccessToken :: !(Maybe Text)
, _prjpUploadType :: !(Maybe Text)
, _prjpPayload :: !Job
, _prjpRegion :: !Text
, _prjpProjectId :: !Text
, _prjpCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsRegionsJobsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'prjpXgafv'
--
-- * 'prjpJobId'
--
-- * 'prjpUploadProtocol'
--
-- * 'prjpUpdateMask'
--
-- * 'prjpAccessToken'
--
-- * 'prjpUploadType'
--
-- * 'prjpPayload'
--
-- * 'prjpRegion'
--
-- * 'prjpProjectId'
--
-- * 'prjpCallback'
projectsRegionsJobsPatch
:: Text -- ^ 'prjpJobId'
-> Job -- ^ 'prjpPayload'
-> Text -- ^ 'prjpRegion'
-> Text -- ^ 'prjpProjectId'
-> ProjectsRegionsJobsPatch
projectsRegionsJobsPatch pPrjpJobId_ pPrjpPayload_ pPrjpRegion_ pPrjpProjectId_ =
ProjectsRegionsJobsPatch'
{ _prjpXgafv = Nothing
, _prjpJobId = pPrjpJobId_
, _prjpUploadProtocol = Nothing
, _prjpUpdateMask = Nothing
, _prjpAccessToken = Nothing
, _prjpUploadType = Nothing
, _prjpPayload = pPrjpPayload_
, _prjpRegion = pPrjpRegion_
, _prjpProjectId = pPrjpProjectId_
, _prjpCallback = Nothing
}
-- | V1 error format.
prjpXgafv :: Lens' ProjectsRegionsJobsPatch (Maybe Xgafv)
prjpXgafv
= lens _prjpXgafv (\ s a -> s{_prjpXgafv = a})
-- | Required. The job ID.
prjpJobId :: Lens' ProjectsRegionsJobsPatch Text
prjpJobId
= lens _prjpJobId (\ s a -> s{_prjpJobId = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
prjpUploadProtocol :: Lens' ProjectsRegionsJobsPatch (Maybe Text)
prjpUploadProtocol
= lens _prjpUploadProtocol
(\ s a -> s{_prjpUploadProtocol = a})
-- | Required. Specifies the path, relative to Job, of the field to update.
-- For example, to update the labels of a Job the update_mask parameter
-- would be specified as labels, and the PATCH request body would specify
-- the new value. *Note:* Currently, labels is the only field that can be
-- updated.
prjpUpdateMask :: Lens' ProjectsRegionsJobsPatch (Maybe GFieldMask)
prjpUpdateMask
= lens _prjpUpdateMask
(\ s a -> s{_prjpUpdateMask = a})
-- | OAuth access token.
prjpAccessToken :: Lens' ProjectsRegionsJobsPatch (Maybe Text)
prjpAccessToken
= lens _prjpAccessToken
(\ s a -> s{_prjpAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
prjpUploadType :: Lens' ProjectsRegionsJobsPatch (Maybe Text)
prjpUploadType
= lens _prjpUploadType
(\ s a -> s{_prjpUploadType = a})
-- | Multipart request metadata.
prjpPayload :: Lens' ProjectsRegionsJobsPatch Job
prjpPayload
= lens _prjpPayload (\ s a -> s{_prjpPayload = a})
-- | Required. The Dataproc region in which to handle the request.
prjpRegion :: Lens' ProjectsRegionsJobsPatch Text
prjpRegion
= lens _prjpRegion (\ s a -> s{_prjpRegion = a})
-- | Required. The ID of the Google Cloud Platform project that the job
-- belongs to.
prjpProjectId :: Lens' ProjectsRegionsJobsPatch Text
prjpProjectId
= lens _prjpProjectId
(\ s a -> s{_prjpProjectId = a})
-- | JSONP
prjpCallback :: Lens' ProjectsRegionsJobsPatch (Maybe Text)
prjpCallback
= lens _prjpCallback (\ s a -> s{_prjpCallback = a})
instance GoogleRequest ProjectsRegionsJobsPatch where
type Rs ProjectsRegionsJobsPatch = Job
type Scopes ProjectsRegionsJobsPatch =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsRegionsJobsPatch'{..}
= go _prjpProjectId _prjpRegion _prjpJobId _prjpXgafv
_prjpUploadProtocol
_prjpUpdateMask
_prjpAccessToken
_prjpUploadType
_prjpCallback
(Just AltJSON)
_prjpPayload
dataprocService
where go
= buildClient
(Proxy :: Proxy ProjectsRegionsJobsPatchResource)
mempty
|
brendanhay/gogol
|
gogol-dataproc/gen/Network/Google/Resource/Dataproc/Projects/Regions/Jobs/Patch.hs
|
mpl-2.0
| 6,654 | 0 | 22 | 1,597 | 1,023 | 595 | 428 | 149 | 1 |
{-# LANGUAGE FlexibleInstances, GADTs, MultiParamTypeClasses #-}
{-
Copyright (C) 2010, 2011, 2012 Jeroen Ketema and Jakob Grue Simonsen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
-- This module defines rewrite rules and steps and rewrite system.
module RuleAndSystem (
RewriteRule(Rule), Step,
rewriteStep, rewriteSteps,
descendantsAcrossStep, descendantsAcrossSteps,
originsAcrossStep, originsAcrossSteps,
RewriteSystem(rules),
System(SystemCons)
) where
import SignatureAndVariables
import Term
import PositionAndSubterm
import Substitution
import Prelude
import Data.List
-- Rules consist of a left-hand side and a right-hand side.
data RewriteRule s v where
Rule :: (Signature s, Variables v)
=> Term s v -> Term s v -> RewriteRule s v
instance (Show s, Show v, Signature s, Variables v)
=> Show (RewriteRule s v) where
show (Rule l r) = show l ++ " -> " ++ show r
-- Rewrite steps are (position, rewrite rule)-pairs.
type Step s v = (Position, RewriteRule s v)
-- Apply a rewrite rule l -> r to a term t at position p.
rewriteStep :: (Signature s, Variables v)
=> Term s v -> Step s v -> Term s v
rewriteStep t (p, Rule l r)
| p `positionOf` t = replaceSubterm t sigma_r p
| otherwise = error "Rewrite step applied at invalid position"
where sigma_r = substitute (match l $ subterm t p) r
-- Apply multiple rewrite steps in sequence, yielding a list of terms.
rewriteSteps :: (Signature s, Variables v)
=> Term s v -> [Step s v] -> [Term s v]
rewriteSteps t steps = t : rewriteSteps' t steps
where rewriteSteps' _ [] = []
rewriteSteps' s (x:xs) = rewriteSteps (rewriteStep s x) xs
-- Helper function for descendantsAcrossStep which computes the descendants
-- of a single position across a rewrite step.
descendantsOfPosition :: (Signature s, Variables v)
=> Step s v -> Position -> PositionFunction
descendantsOfPosition (p, Rule l r) q
| not (p `prefixOf` q) = pos2PosFun q
| q' `funPositionOf` l = posFunEmpty
| otherwise = posFunPad (p_len + positionLength q'') pf_new
where q' = genericDrop (positionLength p) q
p_len = positionLength p
pf_new = [[p ++ p' ++ q'' | p' <- ps'] | ps' <- varPosFun r x]
(x, q'') = getVarAndPos l q'
-- Helper function for descendantsAcrossStep which merges a list of position
-- functions. The function assumes that all positions in the ith position
-- function of the list occur at positions >= i - (term_height l).
descendantsMerge :: (Signature s, Variables v)
=> Step s v -> [PositionFunction] -> PositionFunction
descendantsMerge (_, Rule l _) pfs = merge' (termHeight l + 1) pfs
where merge' n qfs = head start : merge' 2 (map tail (start : unused))
where start = posFunMerge (genericTake n qfs)
unused = genericDrop n qfs
-- Descendants across a rewrite step.
descendantsAcrossStep :: (Signature s, Variables v)
=> Step s v -> PositionFunction -> PositionFunction
descendantsAcrossStep step pf
= descendantsMerge step $ map (posFunMerge . map descendants) pf
where descendants = descendantsOfPosition step
-- Descendants across a finite number of rewrite steps.
descendantsAcrossSteps :: (Signature s, Variables v)
=> [Step s v] -> PositionFunction -> PositionFunction
descendantsAcrossSteps steps pf
= foldl (flip descendantsAcrossStep) pf steps
-- Helper function for originsAcrossStep which computes the origins of a
-- single position across a rewrite step.
originsOfPosition :: (Signature s, Variables v)
=> Step s v -> Position -> Positions
originsOfPosition (p, Rule l r) q
| not (p `prefixOf` q) = [q]
| q' `funPositionOf` r = [p ++ p' | p' <- nonVarPos l]
| r `hasRootVariable` x = [p ++ p' | p' <- nonVarPos l]
++ [p ++ p' ++ q'' | p' <- varPos l x]
| otherwise = [p ++ p' ++ q'' | p' <- varPos l x]
where q' = genericDrop (positionLength p) q
(x, q'') = getVarAndPos r q'
-- Origins across a rewrite step.
originsAcrossStep :: (Signature s, Variables v)
=> Step s v -> Positions -> Positions
originsAcrossStep step ps
= nub (concatMap (originsOfPosition step) ps)
-- Origins across a finite number of rewrite steps.
originsAcrossSteps :: (Signature s, Variables v)
=> [Step s v] -> Positions -> Positions
originsAcrossSteps steps ps
= foldr originsAcrossStep ps steps
-- A rewrite system is a singleton set with an associated rule function.
class (Signature s, Variables v) => RewriteSystem s v r where
rules :: r -> [RewriteRule s v]
-- Default data type for a rewrite system.
data System s v where
SystemCons :: (Signature s, Variables v) => [RewriteRule s v] -> System s v
instance (Signature s, Variables v)
=> RewriteSystem s v (System s v) where
rules (SystemCons rs) = rs
|
jeroenk/iTRSsImplemented
|
RuleAndSystem.hs
|
agpl-3.0
| 5,538 | 0 | 12 | 1,273 | 1,422 | 743 | 679 | 89 | 2 |
module Stack where
import Data.Maybe;
push :: [a] -> a -> [a]
push xs x = x:xs
pop :: [a] -> (Maybe a, [a])
pop [] = (Nothing, [])
pop (x:xs) = (Just x, xs)
back :: [a] -> Maybe a
back [] = Nothing
back (x:xs) = Just x
size :: [a] -> Int
size = length
clear :: [a] -> [a]
clear xs = []
exit :: [a] -> Int
exit xs = 0
execute :: (Show a, Eq a, Read a) => [String] -> [a] -> ([a], String, Int)
execute cmd stack =
case (head cmd) of
"push" -> ((push stack ((read . head . tail) cmd)), "ok", 1)
"pop" ->
if((fst . pop) stack==Nothing)
then
((snd . pop) stack, "error", 1)
else
((snd . pop) stack, (show . fromJust . fst . pop) stack, 1)
"back" ->
if(back stack==Nothing)
then
(stack, "error", 1)
else
(stack, (show . fromJust . back) stack, 1)
"size" -> (stack, (show .size) stack, 1)
"clear" -> (clear stack, "ok", 1)
"exit" -> (stack, "bye", 0)
getAndExecuteCommand :: (Show a, Eq a, Read a) => [a] -> IO ()
getAndExecuteCommand xs = do
command <- getLine
printSecond (result command)
if(getThird (result command)==1)
then (getAndExecuteCommand . getFirst) (result command)
else return ()
where
printSecond = putStrLn . getSecond
getFirst (a, b, c) = a
getSecond (a, b, c) = b
getThird (a, b, c) = c
result command = execute (words command) xs
nullIntList :: Int -> [Int]
nullIntList arg = []
main :: IO ()
main = (getAndExecuteCommand . nullIntList) 0
|
SeTSeR/Structures
|
Stack/Stack.hs
|
lgpl-2.1
| 1,517 | 31 | 16 | 424 | 796 | 433 | 363 | 47 | 8 |
{-# OPTIONS_GHC -Wno-unused-do-bind #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -Wno-missing-pattern-synonym-signatures #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE TypeOperators #-}
module HMF where
import Common
------------------------------------------------------------------------------
import Control.Applicative
import Control.Monad.Free
import Data.Attoparsec.ByteString.Char8
import Data.ByteString hiding (foldr1, getLine)
import Data.Functor
data Ex a = forall i. Wrap (a i)
-- | runtime representation of type parameter
data Ty a where
ListIntTy :: Ty [Int]
UnitTy :: Ty ()
-- | Pairs up two type constructors.
-- Ensures their parameters are equal.
-- Pattern match on Ty.
data (a :*: b) i = a i :&: b i
-- | Sig(ma) type (i.e., dependent pair)
-- type of second component depends on value of first
type Sig a b = Ex (a :*: b)
pattern Sig x y = Wrap (x :&: y)
data HmfCmdF a
= FlushPage [Int] a
| PageMisses ([Int] -> a)
deriving Functor
type HmfCmd = Free HmfCmdF
fp :: [Int] -> HmfCmd ()
fp is = liftF $ FlushPage is ()
pm :: HmfCmd [Int]
pm = liftF $ PageMisses id
parseList :: Parser [Int]
parseList = do char '['; t <- decimal `sepBy` char ','; char ']'; return t
parseFP :: Parser (HmfCmd ())
parseFP = skipSpace >> string "flushPage" *> skipSpace *> fmap fp parseList
parsePM :: Parser (HmfCmd [Int])
parsePM = skipSpace >> string "pageMisses" $> pm
parseFPPM :: Parser (Sig Ty HmfCmd)
parseFPPM = fmap (Sig UnitTy) parseFP
<|> fmap (Sig ListIntTy) parsePM
parseSeparator :: Parser Char
parseSeparator = skipSpace >> char ';'
parseHmfParser :: Parser (Sig Ty HmfCmd)
parseHmfParser = fmap (foldr1 combine) $ parseFPPM `sepBy1` parseSeparator
where combine (Sig _ val) (Sig ty acc) = Sig ty (val >> acc)
combine _ _ = error "parseHmf"
eatTheRest :: Parser ()
eatTheRest = skipWhile stuff >> endOfInput
where stuff w = isSpace w || w == ';'
parseHmf :: ByteString -> Result (Sig Ty HmfCmd)
parseHmf = parse (parseHmfParser <* eatTheRest)
------------------------------------------------------------------------------
ioHmf :: ByteString -> Either String (IO ())
ioHmf s = do
(_u, r) <- parseFully (parseHmf s)
let a = ioHmfAux r
return a
ioHmfAux :: Sig Ty HmfCmd -> IO ()
ioHmfAux (Sig _ f) = do doHmf f; return ()
ioHmfAux _ = return ()
doHmf :: HmfCmd a -> IO a
doHmf =
foldFree $ \case
FlushPage ps next -> do
print ps
return next
PageMisses next -> do
i <- read <$> getLine
print [i]
return $ next [i]
{-
:set -XOverloadedStrings
let x = ioHmf "pageMisses"
let x = ioHmf "flushPage [1,2]"
let x = ioHmf "flushPage [1,2];pageMisses;"
case x of (Right a) -> a
-}
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/topic/fix-free/2016-01-benjamin-hodgson-parsing-to-free-monads/HMF.hs
|
unlicense
| 3,104 | 64 | 13 | 781 | 816 | 442 | 374 | 71 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
-- | This module contains API handlers pertaining to the 'Account' object
module Handlers.Account (
-- * API handlers
listAccountsHandler,
showAccountHandler,
createAccountHandler,
updateAccountHandler,
deleteAccountHandler,
-- * Utility functions
accountUrl
) where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C
import Database.Persist (Key)
import Snap.Core (modifyResponse, redirect,
setResponseCode)
import Text.Printf (printf)
import Application (AppHandler)
import Helpers.Params (getKeyParam, getPageParam,
getRequestBody, getTextParam,
requireParam)
import Helpers.Responses (writeJSON)
import Models.Account (deleteAccount, getAccount,
insertAccount, newAccount,
selectAccounts, updateAccount)
import Schema
-- | Get an account link
accountUrl :: Key Account -- ^ Account ID
-> BS.ByteString -- ^ Returns a link to the account
accountUrl accountId = C.pack $ printf "/accounts/%v" accountId
-- | The API handler for GET /accounts
listAccountsHandler :: AppHandler ()
listAccountsHandler = do
filterName <- getTextParam "name"
page <- getPageParam
accounts <- selectAccounts filterName page
writeJSON accounts
-- | The API handler for GET /accounts/:account_id
showAccountHandler :: AppHandler ()
showAccountHandler = do
accountId <- requireParam getKeyParam "account_id"
account <- getAccount accountId
writeJSON account
-- | The API handler for POST/PUT /accounts
createAccountHandler :: AppHandler ()
createAccountHandler = do
params <- getRequestBody
accountId <- newAccount params >>= insertAccount
redirect $ accountUrl accountId
-- | The API handler for POST/PUT /accounts/:account_id
updateAccountHandler :: AppHandler ()
updateAccountHandler = do
accountId <- requireParam getKeyParam "account_id"
params <- getRequestBody
_ <- getAccount accountId
updateAccount accountId params
modifyResponse $ setResponseCode 204
-- | The API handler for DELETE /accounts/:account_id
deleteAccountHandler :: AppHandler ()
deleteAccountHandler = do
accountId <- requireParam getKeyParam "account_id"
_ <- getAccount accountId
deleteAccount accountId
modifyResponse $ setResponseCode 204
|
b0d0nne11/hauth
|
src/Handlers/Account.hs
|
apache-2.0
| 2,670 | 0 | 9 | 735 | 447 | 236 | 211 | 56 | 1 |
{- © Utrecht University (Department of Information and Computing Sciences) -}
module Domain.Scenarios.Parser where
import Data.Char
import Data.Either
import qualified Data.Foldable as F
import Data.List
import qualified Data.List.NonEmpty as N
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid hiding (Sum)
import Ideas.Common.Library
import Ideas.Text.XML hiding (Name, BuildXML(..))
import Domain.Scenarios.Condition
import Domain.Scenarios.Expression
import Domain.Scenarios.ScenarioState
import Domain.Scenarios.Globals
import Domain.Scenarios.Scenario
import qualified Domain.Scenarios.DomainData as DD
-- Functions to be exposed as an interface
----------------------------------------------------------------------------------------------------
-- | Parses a scenario from a scenario element
parseScenario :: XML -> Scenario
parseScenario scenarioEl = Scenario
{ scenarioDefinitions = defs
, scenarioExpressions = parseExpressions defs scenarioEl
, scenarioMetaData = parseMetaData defs scenarioEl
, scenarioTopDialogue = parseDialogue defs scenarioEl
}
where defs = parseDefinitions scenarioEl
parseDefinitions :: XML -> Definitions
parseDefinitions scenarioEl = Definitions
{ definitionsCharacters = map parseCharacterDefinition (children (getChild "characters" defsEl))
, definitionsProperties = parseDefinitionList (getChild "properties" defsEl)
, definitionsParameters = (fmap fst paramDefs, F.fold (fmap snd paramDefs))
}
where paramDefs = Usered
{ useredUserDefined = parseDefinitionList (getChild "userDefined" paramDefsEl)
, useredFixed = parseDefinitionList (getChild "fixed" paramDefsEl)
}
paramDefsEl = getChild "parameters" defsEl
defsEl = fromMaybe (error "Definitions not found") $
findChild "definitions" scenarioEl
parseDefinitionList :: XML -> ([Definition ()], TypeMap)
parseDefinitionList el = (defs, M.fromList (map toTypePair defs))
where toTypePair def = (definitionId def, definitionType def)
defs = map (parseDefinition (const (const ()))) (children el)
parseDefinition :: (DD.Type -> XML -> a) -> XML -> Definition a
parseDefinition parseContent defEl = Definition
{ definitionId = getAttribute "id" defEl
, definitionName = getAttribute "name" defEl
, definitionDescription = getData <$> findChild "description" defEl
, definitionType = ty
, definitionDefault = parseDomainDataValue ty <$> maybeDefaultEl
, definitionContent = parseContent ty defEl
}
where (ty, maybeDefaultEl) = parseDomainDataType (getChild "type" defEl)
parseCharacterDefinition :: XML -> CharacterDefinition
parseCharacterDefinition defEl = CharacterDefinition
{ characterDefinitionId = getAttribute "id" defEl
, characterDefinitionName = findAttribute "name" defEl
}
parseDomainDataType :: XML -> (DD.Type, Maybe XML)
parseDomainDataType typeContainerEl = case name typeEl of
"list" -> (DD.TList (fst (parseDomainDataType (getChild "itemType" typeEl))), simpleDefault)
"attributeRecord" ->
( DD.TAttributeRecord
(processItem <$> findChild "content" typeEl)
(map processItem (findChildren "attribute" typeEl))
, simpleDefault)
where processItem itemEl =
( getAttribute "name" itemEl
, fst (parseDomainDataType (getChild "type" itemEl))
)
"extension" -> parseDomainDataType (getChild "equivalentType" typeEl)
_ -> (DD.TSimple (parseSimpleDomainDataType typeEl), simpleDefault)
where typeEl = getExactlyOneChild typeContainerEl
simpleDefault = findChild "default" typeEl
parseSimpleDomainDataType :: XML -> DD.SimpleType
parseSimpleDomainDataType typeEl = case name typeEl of
"boolean" -> DD.TBoolean
"integer" -> DD.TInteger mmin mmax
where mmin = read <$> findAttribute "minimum" typeEl
mmax = read <$> findAttribute "maximum" typeEl
"string" -> DD.TString
"enumeration" -> DD.TString
n -> error ("Could not parse " ++ n)
----------------------------------------------------------------------------------------------------
-- Functions to be used internally
----------------------------------------------------------------------------------------------------
parseExpressions :: Definitions -> XML -> [Definition Expression]
parseExpressions defs = maybe [] (map (parseDefinition parseExpression) . children) .
findChild "typedExpressions"
where parseExpression ty = parseExpressionTyped defs ty .
getExactlyOneChild .getChild "expression"
-- MetaData Parser ---------------------------------------------------------------------------------
parseMetaData :: Definitions -> XML -> MetaData
parseMetaData defs scenarioEl = MetaData
{ scenarioName = parseScenarioName metadataEl
, scenarioLanguage = parseScenarioLanguage metadataEl
, scenarioDescription = parseScenarioDescription metadataEl
, scenarioDifficulty = parseScenarioDifficulty metadataEl
, scenarioVersion = parseScenarioVersion scenarioEl
, scenarioInitialParameterValues = parseScenarioInitialParameterValues defs metadataEl
, scenarioPropertyValues = parsePropertyValues defs metadataEl
}
where metadataEl = getChild "metadata" scenarioEl
parseScenarioName :: XML -> Name
parseScenarioName = getData . getChild "name"
parseScenarioLanguage :: XML -> Maybe String
parseScenarioLanguage metadataEl = getAttribute "code" <$> findChild "language" metadataEl
parseScenarioDescription :: XML -> String
parseScenarioDescription = getData . getChild "description"
parseScenarioDifficulty :: XML -> Maybe Difficulty
parseScenarioDifficulty metadataEl = fromMaybe (error "parseScenarioDifficulty: no parse") . readDifficulty .
getData <$> findChild "difficulty" metadataEl
parseScenarioVersion :: XML -> Maybe Int
parseScenarioVersion scenarioEl = read <$> findAttribute "version" scenarioEl
parseScenarioInitialParameterValues :: Definitions -> XML -> ParameterState
parseScenarioInitialParameterValues defs metadataEl = Usered
{ useredUserDefined = parseCharactereds valueParser M.fromList (getChild "userDefined" valsElem)
, useredFixed = parseCharactereds valueParser M.fromList (getChild "fixed" valsElem)
}
where valsElem = fromMaybe (error "Initial parameter values not found") $
findChild "initialParameterValues" metadataEl
valueParser = parseNamedDomainDataValue "parameter" (snd (definitionsParameters defs))
-- MetaData Parser END -----------------------------------------------------------------------------
-- Dialogue Parser ---------------------------------------------------------------------------------
parseDialogue :: Definitions -> XML -> TopDialogue
parseDialogue defs scenarioEl = map (parseInterleaveLevel defs) interleaveElems
where
sequenceElem = getChild "sequence" scenarioEl
interleaveElems = findChildren "interleave" sequenceElem
parseInterleaveLevel :: Definitions -> XML -> InterleaveLevel
parseInterleaveLevel defs interleaveElem = map (parseTree defs) diaElems
where
diaElems = findChildren "dialogue" interleaveElem
parseTree :: Definitions -> XML -> Dialogue
parseTree defs diaElem =
Dialogue
{ diaID = getAttribute "id" diaElem
, diaStartIDs = map (getAttribute "idref") (children (getChild "starts" diaElem))
, diaAtomic = not (any statAllowInterleave statements)
, diaOptional = tryParseBool (findAttribute "optional" diaElem)
, diaStatements = statements
}
where statements = map (parseStatement defs) (children (getChild "statements" diaElem))
parseStatement :: Definitions -> XML -> Statement
parseStatement defs statElem =
Statement
{ statID = getAttribute "id" statElem
, statInfo = parseStatementInfo defs statElem
, statPrecondition = parseMaybePrecondition defs statElem
, statParamEffects = parseParameterEffects defs statElem
, statAllowInterleave = parseAllowInterleave statElem
, statAllowDialogueEnd = parseAllowDialogueEnd statElem
, statEnd = parseEnd statElem
, statNextStatIDs = parseNextStatIDs statElem
}
parseStatementInfo :: Definitions -> XML -> StatementInfo
parseStatementInfo defs statElem =
StatementInfo
{ statType = parseType statElem
, statText = parseText statElem
, statCharacterIdref = parseCharacterIdref statElem
, statPropertyValues = parsePropertyValues defs statElem
}
-- | Takes a statement and returns its type
parseType :: XML -> StatementType
parseType statElem = takeWhile isLower (name statElem)
-- | Takes a statement and returns its text
parseText :: XML -> StatementText
parseText statElem = getData (getChild "text" statElem)
-- | Takes a statement element and returns its precondition, if it has one
parseMaybePrecondition :: Definitions -> XML -> Maybe Condition
parseMaybePrecondition defs statElem =
fmap (parseCondition defs . getExactlyOneChild) conditionElem
where conditionElem = findChild "preconditions" statElem
-- | Takes a statement element and returns its effects
parseParameterEffects :: Definitions -> XML -> Usered (Charactered [Effect])
parseParameterEffects defs statElem = Usered
{ useredUserDefined = Charactered
(map (parseParameterEffect defs) (children (getChild "userDefined" effectsElem)))
M.empty
, useredFixed = parseCharactereds (parseParameterEffect defs) id (getChild "fixed" effectsElem)
}
where effectsElem = getChild "parameterEffects" statElem
parseParameterEffect :: Definitions -> XML -> Effect
parseParameterEffect defs effectElem = Effect
{ effectIdref = idref
, effectAssignmentOp = parseAssignmentOperator effectElem
, effectValue = value
}
where idref = getAttribute "idref" effectElem
errorDefault = error ("Value for unknown parameter " ++ idref)
value = parseDomainDataValue
(DD.unrestrictType (M.findWithDefault errorDefault idref (snd (definitionsParameters defs))))
effectElem
-- | Parses an element to a Changetype
parseAssignmentOperator :: XML -> AssignmentOperator
parseAssignmentOperator effectElem = read (applyToFirst toUpper operatorStr)
where operatorStr = getAttribute "operator" effectElem
parseAllowInterleave :: XML -> Bool
parseAllowInterleave statElem = maybe False parseBool . getFirst $
First (findAttribute "allowInterleave" statElem) <> First (findAttribute "jumpPoint" statElem)
parseAllowDialogueEnd :: XML -> Bool
parseAllowDialogueEnd statElem = maybe False parseBool . getFirst $
First (findAttribute "allowDialogueEnd" statElem) <> First (findAttribute "inits" statElem)
parseEnd :: XML -> Bool
parseEnd statElem = tryParseBool (findAttribute "end" statElem)
-- | Takes a statement and returns the IDs of the statements following it
parseNextStatIDs :: XML -> [ID]
parseNextStatIDs element = errorOnFail errorMsg nextIDs
where
errorMsg = "Failed to get the nextIDs of: " ++ name element
nextIDs = getResponses >>= getIdrefs
where getIdrefs = mapM (findAttribute "idref")
getResponses = children <$> findChild "responses" element
-- Dialogue Parser END -----------------------------------------------------------------------------
-- | Parses a Bool
parseBool :: String -> Bool
parseBool boolStr = read (applyToFirst toUpper boolStr) :: Bool
-- | Tries to parse bool from a string
tryParseBool :: Maybe String -> Bool
tryParseBool (Just boolStr) = parseBool boolStr
tryParseBool _ = False
-- | Parses a condition and recursively parses ands and ors. Used in both parsers (metadata and dialogue)
parseCondition :: Definitions -> XML -> Condition
parseCondition defs conditionElem = case stripCharacterPrefix (name conditionElem) of
"and" -> And (map (parseCondition defs) (children conditionElem))
"or" -> Or (map (parseCondition defs) (children conditionElem))
"condition" -> Condition
ComparisonCondition
{ conditionIdref = idref
, conditionCharacterIdref = parseCharacterIdref conditionElem
, conditionTest = parseOperator conditionElem
, conditionValue = value
}
where idref = getAttribute "idref" conditionElem
errorDefault = error ("Condition for unknown parameter " ++ idref)
ty = M.findWithDefault errorDefault idref (snd (definitionsParameters defs))
value = parseDomainDataValue (DD.unrestrictType ty) conditionElem
"referenceCondition" -> ReferenceCondition
UnaryCondition
{ unaryConditionIdref = idref
, unaryConditionCharacterIdref = parseCharacterIdref conditionElem
, unaryConditionTest = parseOperator conditionElem
}
where idref = getAttribute "idref" conditionElem
_ -> error "no parse condition"
-- | Parses an operator. Gives an exception on invalid input.
parseOperator :: Read a => XML -> a
parseOperator conditionElem = read (applyToFirst toUpper (getAttribute "operator" conditionElem))
parseExpressionTyped :: Definitions -> DD.Type -> XML -> Expression
parseExpressionTyped defs ty el = case stripCharacterPrefix (name el) of
"literal" -> Literal (parseDomainDataValue ty el)
"parameterReference" -> ParameterReference
(getAttribute "idref" el)
(parseCharacterIdref el)
(maybe CalculateValue parseCalculation (findAttribute "calculate" el))
"sum" -> Sum (map (parseExpressionTyped defs ty) (children el))
"scale" -> Scale
(maybe 1 read (findAttribute "scalar" el))
(maybe 1 read (findAttribute "divisor" el))
(parseExpressionTyped defs ty (getExactlyOneChild el))
"choose" -> Choose
(map parseWhen (findChildren "when" el))
(parseExpressionTyped defs ty (getExactlyOneChild (getChild "otherwise" el)))
where
parseWhen whenEl =
( parseCondition defs (getExactlyOneChild (getChild "condition" whenEl))
, parseExpressionTyped defs ty (getExactlyOneChild (getChild "expression" whenEl))
)
n -> error ("parseExpressionTyped: not supported: " ++ n)
parseCalculation :: String -> Calculation
parseCalculation "value" = CalculateValue
parseCalculation "percentage" = CalculatePercentage
parseCalculation c = error ("parseCalculation: not supported: " ++ c)
-- | Parses property values from an element that has them
parsePropertyValues :: Definitions -> XML -> PropertyValues
parsePropertyValues defs propsElem = parseCharactereds
(parseNamedDomainDataValue "property" (snd (definitionsProperties defs)))
Assocs (getChild "propertyValues" propsElem)
parseNamedDomainDataValue :: String -> TypeMap -> XML -> (String, DD.Value)
parseNamedDomainDataValue valueKind typeMap propValEl = (idref, value)
where
idref = getAttribute "idref" propValEl
errorDefault = error ("Value for unknown " ++ valueKind ++ " " ++ idref)
value = parseDomainDataValue
(M.findWithDefault errorDefault idref typeMap)
propValEl
parseDomainDataValue :: DD.Type -> XML -> DD.Value
parseDomainDataValue ty el = case ty of
DD.TSimple simpleType -> parseSimpleDomainDataValue simpleType (getData el)
DD.TList itemType -> DD.VList (map (parseDomainDataValue itemType) (children el))
DD.TAttributeRecord contentInfo attrs -> DD.VAttributeRecord
(maybeToList (getContentValue <$> contentInfo) ++ map parseAttribute attrs)
where getContentValue (contentName, contentType) =
(contentName, parseDomainDataValue contentType el)
parseAttribute (attrName, DD.TSimple attrType) =
(attrName, parseSimpleDomainDataValue attrType (getAttribute attrName el))
parseAttribute (attrName, attrType) =
error ("Attribute " ++ attrName ++ " has invalid non-simple type " ++ show attrType)
parseSimpleDomainDataValue :: DD.SimpleType -> String -> DD.Value
parseSimpleDomainDataValue ty s = case ty of
DD.TBoolean -> DD.VBoolean (read (applyToFirst toUpper s))
DD.TInteger mmin mmax -> DD.VInteger (DD.clamp mmin mmax (read s))
DD.TString -> DD.VString s
parseCharactereds :: (XML -> a) -> ([a] -> b) -> XML -> Charactered b
parseCharactereds parseSub mkCollection valsElem = Charactered
{ characteredIndependent = mkCollection civs
, characteredPerCharacter = M.fromList (map toPC (N.groupAllWith fst pcvs))
}
where
vals = map (parseCharactered parseSub) (children valsElem)
(civs, pcvs) = partitionEithers vals
toPC vs = (fst (N.head vs), mkCollection (map snd (N.toList vs)))
parseCharactered :: (XML -> a) -> XML -> Either a (String, a)
parseCharactered parseSub valEl = case parseCharacterIdref valEl of
Just characteridref -> Right (characteridref, val)
Nothing -> Left val
where
val = parseSub valEl
parseCharacterIdref :: XML -> Maybe String
parseCharacterIdref = findAttribute "characteridref"
-- Functions that extend the XML parser
----------------------------------------------------------------------------------------------------
-- | Returns the child element with the given name out of the Monad defined in the framework
getChild :: Name -> XML -> XML
getChild elemName element = errorOnFail errorMsg mChild
where
errorMsg = "Failed to find child: " ++ elemName
mChild = findChild elemName element
-- | Finds an attribute and gets it out of the Monad defined in the framework
getAttribute :: String -> XML -> String
getAttribute attributeName element = errorOnFail errorMsg mAttribute
where
errorMsg = "Failed to find attribute: " ++ attributeName
mAttribute = findAttribute attributeName element
getExactlyOneChild :: XML -> XML
getExactlyOneChild element = case children element of
[] -> error "no children found"
[child] -> child
_ -> error "multiple children found"
stripCharacterPrefix :: String -> String
stripCharacterPrefix s = maybe s (applyToFirst toLower) (stripPrefix "character" s)
|
UURAGE/ScenarioReasoner
|
src/Domain/Scenarios/Parser.hs
|
apache-2.0
| 18,580 | 1 | 15 | 3,843 | 4,159 | 2,154 | 2,005 | 293 | 6 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
-- | Pretty printing class and instances for CoreHW
module CLaSH.Core.Pretty
( Pretty (..)
, showDoc
)
where
import Data.Char (isSymbol, isUpper, ord)
import Data.Traversable (sequenceA)
import Data.Text (unpack)
import GHC.Show (showMultiLineString)
import Text.PrettyPrint (Doc, char, comma, empty, equals, hang,
hsep, int, integer, parens, punctuate,
render, sep, text, vcat, ($$), ($+$),
(<+>), (<>), rational, nest)
import Unbound.Generics.LocallyNameless (Embed (..), LFresh, Name, lunbind,
name2String, runLFreshM, unembed,
unrebind, unrec)
import CLaSH.Core.DataCon (DataCon (..))
import CLaSH.Core.Literal (Literal (..))
import CLaSH.Core.Term (Pat (..), Term (..))
import CLaSH.Core.TyCon (TyCon (..), TyConName, isTupleTyConLike)
import CLaSH.Core.Type (ConstTy (..), Kind, LitTy (..),
Type (..), TypeView (..), tyView)
import CLaSH.Core.Var (Id, TyVar, Var, varKind, varName,
varType)
import CLaSH.Util
-- | Pretty printing Show-like typeclass
class Pretty p where
ppr :: (Applicative m, LFresh m) => p -> m Doc
ppr = pprPrec 0
pprPrec :: (Applicative m, LFresh m) => Rational -> p -> m Doc
noPrec, opPrec, appPrec :: Num a => a
noPrec = 0
opPrec = 1
appPrec = 2
-- | Print a Pretty thing to a String
showDoc :: Pretty p => p -> String
showDoc = render . runLFreshM . ppr
prettyParen :: Bool -> Doc -> Doc
prettyParen False = id
prettyParen True = parens
instance Pretty (Name a) where
pprPrec _ = return . text . show
instance Pretty a => Pretty [a] where
pprPrec prec xs = do
xs' <- mapM (pprPrec prec) xs
return $ vcat xs'
instance Pretty (Id, Term) where
pprPrec _ = pprTopLevelBndr
pprTopLevelBndr :: (Applicative m, LFresh m) => (Id,Term) -> m Doc
pprTopLevelBndr (bndr,expr) = do
bndr' <- ppr bndr
bndrName <- ppr (varName bndr)
expr' <- ppr expr
return $ bndr' $$ hang (bndrName <+> equals) 2 expr' <> text "\n"
dcolon :: Doc
dcolon = text "::"
period :: Doc
period = char '.'
rarrow :: Doc
rarrow = text "->"
instance Pretty Type where
pprPrec _ = pprType
instance Pretty (Var Type) where
pprPrec _ v = ppr $ varName v
instance Pretty TyCon where
pprPrec _ tc = return . text . name2String $ tyConName tc
instance Pretty LitTy where
pprPrec _ (NumTy i) = return $ int i
pprPrec _ (SymTy s) = return $ text s
instance Pretty Term where
pprPrec prec e = case e of
Var _ x -> pprPrec prec x
Data dc -> pprPrec prec dc
Literal l -> pprPrec prec l
Prim nm _ -> return $ text $ unpack nm
Lam b -> lunbind b $ \(v,e') -> pprPrecLam prec [v] e'
TyLam b -> lunbind b $ \(tv,e') -> pprPrecTyLam prec [tv] e'
App fun arg -> pprPrecApp prec fun arg
TyApp e' ty -> pprPrecTyApp prec e' ty
Letrec b -> lunbind b $ \(xes,e') -> pprPrecLetrec prec (unrec xes) e'
Case e' _ alts -> pprPrecCase prec e' =<< mapM (`lunbind` return) alts
data BindingSite
= LambdaBind
| CaseBind
| LetBind
instance Pretty (Var Term) where
pprPrec _ v = do
v' <- ppr (varName v)
ty' <- ppr (unembed $ varType v)
return $ v' <+> dcolon <+> ty'
instance Pretty DataCon where
pprPrec _ dc = return . text . name2String $ dcName dc
instance Pretty Literal where
pprPrec _ l = case l of
IntegerLiteral i
| i < 0 -> return $ parens (integer i)
| otherwise -> return $ integer i
RationalLiteral r -> return $ rational r
StringLiteral s -> return $ vcat $ map text $ showMultiLineString s
instance Pretty Pat where
pprPrec prec pat = case pat of
DataPat dc pxs -> do
let (txs,xs) = unrebind pxs
dc' <- ppr (unembed dc)
txs' <- mapM (pprBndr LetBind) txs
xs' <- mapM (pprBndr CaseBind) xs
return $ prettyParen (prec >= appPrec) $ dc' <+> hsep txs' $$ (nest 2 (vcat xs'))
LitPat l -> ppr (unembed l)
DefaultPat -> return $ char '_'
pprPrecLam :: (Applicative m, LFresh m) => Rational -> [Id] -> Term -> m Doc
pprPrecLam prec xs e = do
xs' <- mapM (pprBndr LambdaBind) xs
e' <- pprPrec noPrec e
return $ prettyParen (prec > noPrec) $
char 'λ' <> hsep xs' <+> rarrow $+$ e'
pprPrecTyLam :: (Applicative m, LFresh m) => Rational -> [TyVar] -> Term -> m Doc
pprPrecTyLam prec tvs e = do
tvs' <- mapM ppr tvs
e' <- pprPrec noPrec e
return $ prettyParen (prec > noPrec) $
char 'Λ' <> hsep tvs' <+> rarrow $+$ e'
pprPrecApp :: (Applicative m, LFresh m) => Rational -> Term -> Term -> m Doc
pprPrecApp prec e1 e2 = do
e1' <- pprPrec opPrec e1
e2' <- pprPrec appPrec e2
return $ prettyParen (prec >= appPrec) $ e1' $$ (nest 2 e2')
pprPrecTyApp :: (Applicative m, LFresh m) => Rational -> Term -> Type -> m Doc
pprPrecTyApp prec e ty = do
e' <- pprPrec opPrec e
ty' <- pprParendType ty
return $ prettyParen (prec >= appPrec) $ e' $$ (char '@' <> ty')
pprPrecLetrec :: (Applicative m, LFresh m) => Rational -> [(Id, Embed Term)] -> Term
-> m Doc
pprPrecLetrec prec xes body
| [] <- xes = pprPrec prec body
| otherwise = do
body' <- pprPrec noPrec body
xes' <- mapM (\(x,e) -> do
x' <- pprBndr LetBind x
e' <- pprPrec noPrec (unembed e)
return $ x' $$ equals <+> e'
) xes
return $ prettyParen (prec > noPrec) $
hang (text "letrec") 2 (vcat xes') $$ text "in" <+> body'
pprPrecCase :: (Applicative m, LFresh m) => Rational -> Term -> [(Pat,Term)] -> m Doc
pprPrecCase prec e alts = do
e' <- pprPrec prec e
alts' <- mapM (pprPrecAlt noPrec) alts
return $ prettyParen (prec > noPrec) $
hang (text "case" <+> e' <+> text "of") 2 $ vcat alts'
pprPrecAlt :: (Applicative m, LFresh m) => Rational -> (Pat,Term) -> m Doc
pprPrecAlt _ (altPat, altE) = do
altPat' <- pprPrec noPrec altPat
altE' <- pprPrec noPrec altE
return $ hang (altPat' <+> rarrow) 2 altE'
pprBndr :: (Applicative m, LFresh m, Pretty a) => BindingSite -> a -> m Doc
pprBndr bs x = prettyParen needsParen <$> ppr x
where
needsParen = case bs of
LambdaBind -> True
CaseBind -> True
LetBind -> False
data TypePrec
= TopPrec
| FunPrec
| TyConPrec
deriving (Eq,Ord)
maybeParen :: TypePrec -> TypePrec -> Doc -> Doc
maybeParen ctxt_prec inner_prec = prettyParen (ctxt_prec >= inner_prec)
pprType :: (Applicative m, LFresh m) => Type -> m Doc
pprType = ppr_type TopPrec
pprParendType :: (Applicative m, LFresh m) => Type -> m Doc
pprParendType = ppr_type TyConPrec
ppr_type :: (Applicative m, LFresh m) => TypePrec -> Type -> m Doc
ppr_type _ (VarTy _ tv) = ppr tv
ppr_type _ (LitTy tyLit) = ppr tyLit
ppr_type p ty@(ForAllTy _) = pprForAllType p ty
ppr_type p (ConstTy (TyCon tc)) = pprTcApp p ppr_type tc []
ppr_type p (tyView -> TyConApp tc args) = pprTcApp p ppr_type tc args
ppr_type p (tyView -> FunTy ty1 ty2) = pprArrowChain p <$> ppr_type FunPrec ty1 <:> pprFunTail ty2
where
pprFunTail (tyView -> FunTy ty1' ty2') = ppr_type FunPrec ty1' <:> pprFunTail ty2'
pprFunTail otherTy = ppr_type TopPrec otherTy <:> pure []
ppr_type p (AppTy ty1 ty2) = maybeParen p TyConPrec <$> ((<+>) <$> pprType ty1 <*> ppr_type TyConPrec ty2)
ppr_type _ (ConstTy Arrow) = return (parens rarrow)
pprForAllType :: (Applicative m, LFresh m) => TypePrec -> Type -> m Doc
pprForAllType p ty = maybeParen p FunPrec <$> pprSigmaType True ty
pprSigmaType :: (Applicative m, LFresh m) => Bool -> Type -> m Doc
pprSigmaType showForalls ty = do
(tvs, rho) <- split1 [] ty
sep <$> sequenceA [ if showForalls then pprForAll tvs else pure empty
, pprType rho
]
where
split1 tvs (ForAllTy b) =
lunbind b $ \(tv,resTy) -> split1 (tv:tvs) resTy
split1 tvs resTy = return (reverse tvs,resTy)
pprForAll :: (Applicative m, LFresh m) => [TyVar] -> m Doc
pprForAll [] = return empty
pprForAll tvs = do
tvs' <- mapM pprTvBndr tvs
return $ char '∀' <+> sep tvs' <> period
pprTvBndr :: (Applicative m, LFresh m) => TyVar -> m Doc
pprTvBndr tv
= do
tv' <- ppr tv
kind' <- pprKind kind
return $ parens (tv' <+> dcolon <+> kind')
where
kind = unembed $ varKind tv
pprKind :: (Applicative m, LFresh m) => Kind -> m Doc
pprKind = pprType
pprTcApp :: (Applicative m, LFresh m) => TypePrec -> (TypePrec -> Type -> m Doc)
-> TyConName -> [Type] -> m Doc
pprTcApp _ _ tc []
= return . text $ name2String tc
pprTcApp p pp tc tys
| isTupleTyConLike tc
= do
tys' <- mapM (pp TopPrec) tys
return $ parens $ sep $ punctuate comma tys'
| otherwise
= pprTypeNameApp p pp tc tys
pprTypeNameApp :: LFresh m => TypePrec -> (TypePrec -> Type -> m Doc)
-> Name a -> [Type] -> m Doc
pprTypeNameApp p pp name tys
| isSym
, [ty1,ty2] <- tys
= pprInfixApp p pp name ty1 ty2
| otherwise
= do
tys' <- mapM (pp TyConPrec) tys
let name' = text $ name2String name
return $ pprPrefixApp p (pprPrefixVar isSym name') tys'
where
isSym = isSymName name
pprInfixApp :: LFresh m => TypePrec -> (TypePrec -> Type -> m Doc)
-> Name a -> Type -> Type -> m Doc
pprInfixApp p pp name ty1 ty2 = do
ty1' <- pp FunPrec ty1
ty2' <- pp FunPrec ty2
let name' = text $ name2String name
return $ maybeParen p FunPrec $ sep [ty1', pprInfixVar True name' <+> ty2']
pprPrefixApp :: TypePrec -> Doc -> [Doc] -> Doc
pprPrefixApp p pp_fun pp_tys = maybeParen p TyConPrec $
hang pp_fun 2 (sep pp_tys)
pprPrefixVar :: Bool -> Doc -> Doc
pprPrefixVar is_operator pp_v
| is_operator = parens pp_v
| otherwise = pp_v
pprInfixVar :: Bool -> Doc -> Doc
pprInfixVar is_operator pp_v
| is_operator = pp_v
| otherwise = char '`' <> pp_v <> char '`'
pprArrowChain :: TypePrec -> [Doc] -> Doc
pprArrowChain _ [] = empty
pprArrowChain p (arg:args) = maybeParen p FunPrec $
sep [arg, sep (map (rarrow <+>) args)]
isSymName :: Name a -> Bool
isSymName n = go (name2String n)
where
go s | null s = False
| isUpper $ head s = isLexConSym s
| otherwise = isLexSym s
isLexSym :: String -> Bool
isLexSym cs = isLexConSym cs || isLexVarSym cs
isLexConSym :: String -> Bool
isLexConSym "->" = True
isLexConSym cs = startsConSym (head cs)
isLexVarSym :: String -> Bool
isLexVarSym cs = startsVarSym (head cs)
startsConSym :: Char -> Bool
startsConSym c = c == ':'
startsVarSym :: Char -> Bool
startsVarSym c = isSymbolASCII c || (ord c > 0x7f && isSymbol c)
isSymbolASCII :: Char -> Bool
isSymbolASCII c = c `elem` "!#$%&*+./<=>?@\\^|~-"
|
christiaanb/clash-compiler
|
clash-lib/src/CLaSH/Core/Pretty.hs
|
bsd-2-clause
| 11,233 | 0 | 17 | 3,164 | 4,396 | 2,202 | 2,194 | 270 | 3 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module ULCPretty (
ppexpr
) where
import Text.PrettyPrint
import ULCSyntax
class Pretty p where
ppr :: Int -> p -> Doc
pp :: p -> Doc
pp = ppr 0
viewVars :: Expr -> [Name]
viewVars (Lam n a) = n : viewVars a
viewVars _ = []
viewBody :: Expr -> Expr
viewBody (Lam _ a) = viewBody a
viewBody x = x
parensIf :: Bool -> Doc -> Doc
parensIf True = parens
parensIf False = id
instance Pretty Name where
ppr _ = text
instance Pretty Expr where
ppr p e = case e of
Lit (LInt a) -> text (show a)
Lit (LBool b) -> text (show b)
Var x -> text x
App a b -> parensIf (p>0) $ ppr (p+1) a <+> ppr p b
Lam x a -> parensIf (p>0) $
char '\\'
<> hsep (fmap pp (viewVars e))
<+> text "->"
<+> ppr (p+1) (viewBody e)
ppexpr :: Expr -> String
ppexpr = render . ppr 0
|
toonn/wyah
|
src/ULCPretty.hs
|
bsd-2-clause
| 978 | 0 | 16 | 333 | 411 | 205 | 206 | 34 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTextDocumentFragment.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:16
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTextDocumentFragment (
QqTextDocumentFragment(..)
,QqTextDocumentFragment_nf(..)
,QqTextDocumentFragmentFromHtml(..)
,qTextDocumentFragmentFromPlainText
,qTextDocumentFragment_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqTextDocumentFragment x1 where
qTextDocumentFragment :: x1 -> IO (QTextDocumentFragment ())
instance QqTextDocumentFragment (()) where
qTextDocumentFragment ()
= withQTextDocumentFragmentResult $
qtc_QTextDocumentFragment
foreign import ccall "qtc_QTextDocumentFragment" qtc_QTextDocumentFragment :: IO (Ptr (TQTextDocumentFragment ()))
instance QqTextDocumentFragment ((QTextCursor t1)) where
qTextDocumentFragment (x1)
= withQTextDocumentFragmentResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextDocumentFragment1 cobj_x1
foreign import ccall "qtc_QTextDocumentFragment1" qtc_QTextDocumentFragment1 :: Ptr (TQTextCursor t1) -> IO (Ptr (TQTextDocumentFragment ()))
instance QqTextDocumentFragment ((QTextDocumentFragment t1)) where
qTextDocumentFragment (x1)
= withQTextDocumentFragmentResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextDocumentFragment2 cobj_x1
foreign import ccall "qtc_QTextDocumentFragment2" qtc_QTextDocumentFragment2 :: Ptr (TQTextDocumentFragment t1) -> IO (Ptr (TQTextDocumentFragment ()))
class QqTextDocumentFragment_nf x1 where
qTextDocumentFragment_nf :: x1 -> IO (QTextDocumentFragment ())
instance QqTextDocumentFragment_nf (()) where
qTextDocumentFragment_nf ()
= withObjectRefResult $
qtc_QTextDocumentFragment
instance QqTextDocumentFragment_nf ((QTextCursor t1)) where
qTextDocumentFragment_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextDocumentFragment1 cobj_x1
instance QqTextDocumentFragment_nf ((QTextDocumentFragment t1)) where
qTextDocumentFragment_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextDocumentFragment2 cobj_x1
class QqTextDocumentFragmentFromHtml x1 where
qTextDocumentFragmentFromHtml :: x1 -> IO (QTextDocumentFragment ())
instance QqTextDocumentFragmentFromHtml ((String)) where
qTextDocumentFragmentFromHtml (x1)
= withQTextDocumentFragmentResult $
withCWString x1 $ \cstr_x1 ->
qtc_QTextDocumentFragment_fromHtml cstr_x1
foreign import ccall "qtc_QTextDocumentFragment_fromHtml" qtc_QTextDocumentFragment_fromHtml :: CWString -> IO (Ptr (TQTextDocumentFragment ()))
instance QqTextDocumentFragmentFromHtml ((String, QTextDocument t2)) where
qTextDocumentFragmentFromHtml (x1, x2)
= withQTextDocumentFragmentResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextDocumentFragment_fromHtml1 cstr_x1 cobj_x2
foreign import ccall "qtc_QTextDocumentFragment_fromHtml1" qtc_QTextDocumentFragment_fromHtml1 :: CWString -> Ptr (TQTextDocument t2) -> IO (Ptr (TQTextDocumentFragment ()))
qTextDocumentFragmentFromPlainText :: ((String)) -> IO (QTextDocumentFragment ())
qTextDocumentFragmentFromPlainText (x1)
= withQTextDocumentFragmentResult $
withCWString x1 $ \cstr_x1 ->
qtc_QTextDocumentFragment_fromPlainText cstr_x1
foreign import ccall "qtc_QTextDocumentFragment_fromPlainText" qtc_QTextDocumentFragment_fromPlainText :: CWString -> IO (Ptr (TQTextDocumentFragment ()))
instance QqisEmpty (QTextDocumentFragment a) (()) where
qisEmpty x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextDocumentFragment_isEmpty cobj_x0
foreign import ccall "qtc_QTextDocumentFragment_isEmpty" qtc_QTextDocumentFragment_isEmpty :: Ptr (TQTextDocumentFragment a) -> IO CBool
instance QtoHtml (QTextDocumentFragment a) (()) where
toHtml x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextDocumentFragment_toHtml cobj_x0
foreign import ccall "qtc_QTextDocumentFragment_toHtml" qtc_QTextDocumentFragment_toHtml :: Ptr (TQTextDocumentFragment a) -> IO (Ptr (TQString ()))
instance QtoHtml (QTextDocumentFragment a) ((String)) where
toHtml x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTextDocumentFragment_toHtml1 cobj_x0 cstr_x1
foreign import ccall "qtc_QTextDocumentFragment_toHtml1" qtc_QTextDocumentFragment_toHtml1 :: Ptr (TQTextDocumentFragment a) -> CWString -> IO (Ptr (TQString ()))
instance QtoPlainText (QTextDocumentFragment a) (()) where
toPlainText x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextDocumentFragment_toPlainText cobj_x0
foreign import ccall "qtc_QTextDocumentFragment_toPlainText" qtc_QTextDocumentFragment_toPlainText :: Ptr (TQTextDocumentFragment a) -> IO (Ptr (TQString ()))
qTextDocumentFragment_delete :: QTextDocumentFragment a -> IO ()
qTextDocumentFragment_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextDocumentFragment_delete cobj_x0
foreign import ccall "qtc_QTextDocumentFragment_delete" qtc_QTextDocumentFragment_delete :: Ptr (TQTextDocumentFragment a) -> IO ()
|
uduki/hsQt
|
Qtc/Gui/QTextDocumentFragment.hs
|
bsd-2-clause
| 5,577 | 0 | 13 | 726 | 1,267 | 658 | 609 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Utils.Vigilance.TypesSpec (spec) where
import Test.QuickCheck.Property.Common.Internal (Equal) -- bah no
import Data.Aeson
import SpecHelper
spec :: Spec
spec = parallel $ do
describe "Monoid WatchState" $ do
prop "obeys the law" $
property $ eq $ prop_Monoid (T :: T WatchState)
prop "chooses the latter unless paused" $ \a b ->
let result = a <> b
in case b of
Paused -> result == a
_ -> result == b
describe "Monoid Config" $ do
it "has reasonable defaults" $
mempty `shouldBe` Config "$(HOME)/.vigilance/state/AppState"
Nothing
3000
(LogCfg "$(HOME)/.vigilance/vigilance.log" False)
[]
3
prop "obeys the law" $
property $ eq $ prop_Monoid (T :: T Config)
prop "it chooses explicit acid path over nothing" $ \path ->
let config' = mempty <> mempty & configAcidPath .~ path :: Config
in config' ^. configAcidPath == path
prop "it chooses explicit email over nothing" $ \email ->
let config' = mempty <> mempty & configFromEmail .~ Just email :: Config
in config' ^. configFromEmail == Just email
prop "it chooses left non-default log path over default right" $ \path ->
let config' = mempty & configLogCfg . logCfgPath .~ path <> mempty :: Config
in config' ^. configLogCfg . logCfgPath == path
prop "it chooses right non-default log path over default left" $ \path ->
let config' = mempty <> mempty & configLogCfg . logCfgPath .~ path :: Config
in config' ^. configLogCfg . logCfgPath == path
describe "json parsing" $ do
prop "parses NewWatch roundtrip" $
property $ eq $ propJSONParsing (T :: T NewWatch)
prop "parses EWatch roundtrip" $
property $ eq $ propJSONParsing (T :: T EWatch)
prop "parses FailedNotification roundtrip" $
property $ eq $ propJSONParsing (T :: T FailedNotification)
prop "parses NotificationError roundtrip" $
property $ eq $ propJSONParsing (T :: T NotificationError)
describe "WatchInterval FromJSON" $ do
it "parses correct values" $ do
"[5, \"minutes\"]" `shouldParseJSON` Every 5 Minutes
it "refuses to parse 0 values" $
eitherDecode' "[0, \"minutes\"]" `shouldBe` (Left "interval must be > 0" :: Either String WatchInterval)
it "refuses to parse negative values" $
eitherDecode' "[-1, \"minutes\"]" `shouldBe` (Left "interval must be > 0" :: Either String WatchInterval)
propJSONParsing :: (Show a, FromJSON a, ToJSON a) => T a -> a -> Equal (Either String a)
propJSONParsing T x = parsed .==. Right x
where parsed = eitherDecode' str
str = encode x
|
MichaelXavier/vigilance
|
test/Utils/Vigilance/TypesSpec.hs
|
bsd-2-clause
| 2,821 | 0 | 20 | 787 | 755 | 368 | 387 | -1 | -1 |
{-# LANGUAGE PatternGuards #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Convert
-- Copyright : (c) Isaac Dupree 2009,
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Conversion between TyThing and HsDecl. This functionality may be moved into
-- GHC at some point.
-----------------------------------------------------------------------------
module Haddock.Convert where
-- Some other functions turned out to be useful for converting
-- instance heads, which aren't TyThings, so just export everything.
import HsSyn
import TcType ( tcSplitSigmaTy )
import TypeRep
#if __GLASGOW_HASKELL__ == 612
import Type ( splitKindFunTys )
import BasicTypes
#else
import Coercion ( splitKindFunTys, synTyConResKind )
#endif
import Name
import Var
import Class
import TyCon
import DataCon
import TysPrim ( alphaTyVars )
import TysWiredIn ( listTyConName )
import Bag ( emptyBag )
import SrcLoc ( Located, noLoc, unLoc )
-- the main function here! yay!
tyThingToLHsDecl :: TyThing -> LHsDecl Name
tyThingToLHsDecl t = noLoc $ case t of
-- ids (functions and zero-argument a.k.a. CAFs) get a type signature.
-- Including built-in functions like seq.
-- foreign-imported functions could be represented with ForD
-- instead of SigD if we wanted...
--
-- in a future code version we could turn idVarDetails = foreign-call
-- into a ForD instead of a SigD if we wanted. Haddock doesn't
-- need to care.
AnId i -> SigD (synifyIdSig ImplicitizeForAll i)
-- type-constructors (e.g. Maybe) are complicated, put the definition
-- later in the file (also it's used for class associated-types too.)
ATyCon tc -> TyClD (synifyTyCon tc)
-- a data-constructor alone just gets rendered as a function:
ADataCon dc -> SigD (TypeSig (synifyName dc)
(synifyType ImplicitizeForAll (dataConUserType dc)))
-- classes are just a little tedious
AClass cl ->
TyClD $ ClassDecl
(synifyCtx (classSCTheta cl))
(synifyName cl)
(synifyTyVars (classTyVars cl))
(map (\ (l,r) -> noLoc
(map getName l, map getName r) ) $
snd $ classTvsFds cl)
(map (noLoc . synifyIdSig DeleteTopLevelQuantification)
(classMethods cl))
emptyBag --ignore default method definitions, they don't affect signature
(map synifyClassAT (classATs cl))
[] --we don't have any docs at this point
-- class associated-types are a subset of TyCon
-- (mainly only type/data-families)
synifyClassAT :: TyCon -> LTyClDecl Name
synifyClassAT = noLoc . synifyTyCon
synifyTyCon :: TyCon -> TyClDecl Name
synifyTyCon tc
| isFunTyCon tc || isPrimTyCon tc =
TyData
-- arbitrary lie, they are neither algebraic data nor newtype:
DataType
-- no built-in type has any stupidTheta:
(noLoc [])
(synifyName tc)
-- tyConTyVars doesn't work on fun/prim, but we can make them up:
(zipWith
(\fakeTyVar realKind -> noLoc $
KindedTyVar (getName fakeTyVar) realKind)
alphaTyVars --a, b, c... which are unfortunately all kind *
(fst . splitKindFunTys $ tyConKind tc)
)
-- assume primitive types aren't members of data/newtype families:
Nothing
-- we have their kind accurately:
(Just (tyConKind tc))
-- no algebraic constructors:
[]
-- "deriving" needn't be specified:
Nothing
| isSynFamilyTyCon tc =
case synTyConRhs tc of
SynFamilyTyCon ->
TyFamily TypeFamily (synifyName tc) (synifyTyVars (tyConTyVars tc))
(Just (synTyConResKind tc))
_ -> error "synifyTyCon: impossible open type synonym?"
| isDataFamilyTyCon tc = --(why no "isOpenAlgTyCon"?)
case algTyConRhs tc of
DataFamilyTyCon ->
TyFamily DataFamily (synifyName tc) (synifyTyVars (tyConTyVars tc))
Nothing --always kind '*'
_ -> error "synifyTyCon: impossible open data type?"
| otherwise =
-- (closed) type, newtype, and data
let
-- alg_ only applies to newtype/data
-- syn_ only applies to type
-- others apply to both
alg_nd = if isNewTyCon tc then NewType else DataType
alg_ctx = synifyCtx (tyConStupidTheta tc)
name = synifyName tc
tyvars = synifyTyVars (tyConTyVars tc)
typats = case tyConFamInst_maybe tc of
Nothing -> Nothing
Just (_, indexes) -> Just (map (synifyType WithinType) indexes)
alg_kindSig = Just (tyConKind tc)
-- The data constructors.
--
-- Any data-constructors not exported from the module that *defines* the
-- type will not (cannot) be included.
--
-- Very simple constructors, Haskell98 with no existentials or anything,
-- probably look nicer in non-GADT syntax. In source code, all constructors
-- must be declared with the same (GADT vs. not) syntax, and it probably
-- is less confusing to follow that principle for the documentation as well.
--
-- There is no sensible infix-representation for GADT-syntax constructor
-- declarations. They cannot be made in source code, but we could end up
-- with some here in the case where some constructors use existentials.
-- That seems like an acceptable compromise (they'll just be documented
-- in prefix position), since, otherwise, the logic (at best) gets much more
-- complicated. (would use dataConIsInfix.)
alg_use_gadt_syntax = any (not . isVanillaDataCon) (tyConDataCons tc)
alg_cons = map (synifyDataCon alg_use_gadt_syntax) (tyConDataCons tc)
-- "deriving" doesn't affect the signature, no need to specify any.
alg_deriv = Nothing
syn_type = synifyType WithinType (synTyConType tc)
in if isSynTyCon tc
then TySynonym name tyvars typats syn_type
else TyData alg_nd alg_ctx name tyvars typats alg_kindSig alg_cons alg_deriv
-- User beware: it is your responsibility to pass True (use_gadt_syntax)
-- for any constructor that would be misrepresented by omitting its
-- result-type.
-- But you might want pass False in simple enough cases,
-- if you think it looks better.
synifyDataCon :: Bool -> DataCon -> LConDecl Name
synifyDataCon use_gadt_syntax dc = noLoc $
let
-- dataConIsInfix allegedly tells us whether it was declared with
-- infix *syntax*.
use_infix_syntax = dataConIsInfix dc
use_named_field_syntax = not (null field_tys)
name = synifyName dc
-- con_qvars means a different thing depending on gadt-syntax
qvars = if use_gadt_syntax
then synifyTyVars (dataConAllTyVars dc)
else synifyTyVars (dataConExTyVars dc)
-- skip any EqTheta, use 'orig'inal syntax
ctx = synifyCtx (dataConDictTheta dc)
linear_tys = zipWith (\ty bang ->
let tySyn = synifyType WithinType ty
in case bang of
#if __GLASGOW_HASKELL__ >= 613
HsUnpackFailed -> noLoc $ HsBangTy HsStrict tySyn
HsNoBang -> tySyn
-- HsNoBang never appears, it's implied instead.
_ -> noLoc $ HsBangTy bang tySyn
#else
MarkedStrict -> noLoc $ HsBangTy HsStrict tySyn
MarkedUnboxed -> noLoc $ HsBangTy HsUnbox tySyn
NotMarkedStrict -> tySyn
-- HsNoBang never appears, it's implied instead.
#endif
)
(dataConOrigArgTys dc) (dataConStrictMarks dc)
field_tys = zipWith (\field synTy -> ConDeclField
(synifyName field) synTy Nothing)
(dataConFieldLabels dc) linear_tys
tys = case (use_named_field_syntax, use_infix_syntax) of
(True,True) -> error "synifyDataCon: contradiction!"
(True,False) -> RecCon field_tys
(False,False) -> PrefixCon linear_tys
(False,True) -> case linear_tys of
[a,b] -> InfixCon a b
_ -> error "synifyDataCon: infix with non-2 args?"
res_ty = if use_gadt_syntax
then ResTyGADT (synifyType WithinType (dataConOrigResTy dc))
else ResTyH98
-- finally we get synifyDataCon's result!
in ConDecl name Implicit{-we don't know nor care-}
qvars ctx tys res_ty Nothing
False --we don't want any "deprecated GADT syntax" warnings!
synifyName :: NamedThing n => n -> Located Name
synifyName = noLoc . getName
synifyIdSig :: SynifyTypeState -> Id -> Sig Name
synifyIdSig s i = TypeSig (synifyName i) (synifyType s (varType i))
synifyCtx :: [PredType] -> LHsContext Name
synifyCtx = noLoc . map synifyPred
synifyPred :: PredType -> LHsPred Name
synifyPred (ClassP cls tys) =
let sTys = map (synifyType WithinType) tys
in noLoc $
HsClassP (getName cls) sTys
synifyPred (IParam ip ty) =
let sTy = synifyType WithinType ty
-- IPName should be in class NamedThing...
in noLoc $
HsIParam ip sTy
synifyPred (EqPred ty1 ty2) =
let
s1 = synifyType WithinType ty1
s2 = synifyType WithinType ty2
in noLoc $
HsEqualP s1 s2
synifyTyVars :: [TyVar] -> [LHsTyVarBndr Name]
synifyTyVars = map synifyTyVar
where
synifyTyVar tv = noLoc $ let
kind = tyVarKind tv
name = getName tv
in if isLiftedTypeKind kind
#if __GLASGOW_HASKELL__ == 612
then UserTyVar name
#else
then UserTyVar name placeHolderKind
#endif
else KindedTyVar name kind
--states of what to do with foralls:
data SynifyTypeState
= WithinType
-- ^ normal situation. This is the safe one to use if you don't
-- quite understand what's going on.
| ImplicitizeForAll
-- ^ beginning of a function definition, in which, to make it look
-- less ugly, those rank-1 foralls are made implicit.
| DeleteTopLevelQuantification
-- ^ because in class methods the context is added to the type
-- (e.g. adding @forall a. Num a =>@ to @(+) :: a -> a -> a@)
-- which is rather sensible,
-- but we want to restore things to the source-syntax situation where
-- the defining class gets to quantify all its functions for free!
synifyType :: SynifyTypeState -> Type -> LHsType Name
synifyType _ (PredTy{}) = --should never happen.
error "synifyType: PredTys are not, in themselves, source-level types."
synifyType _ (TyVarTy tv) = noLoc $ HsTyVar (getName tv)
synifyType _ (TyConApp tc tys)
-- Use non-prefix tuple syntax where possible, because it looks nicer.
| isTupleTyCon tc, tyConArity tc == length tys =
noLoc $ HsTupleTy (tupleTyConBoxity tc) (map (synifyType WithinType) tys)
-- ditto for lists
| getName tc == listTyConName, [ty] <- tys =
noLoc $ HsListTy (synifyType WithinType ty)
-- Most TyCons:
| otherwise =
foldl (\t1 t2 -> noLoc (HsAppTy t1 t2))
(noLoc $ HsTyVar (getName tc))
(map (synifyType WithinType) tys)
synifyType _ (AppTy t1 t2) = let
s1 = synifyType WithinType t1
s2 = synifyType WithinType t2
in noLoc $ HsAppTy s1 s2
synifyType _ (FunTy t1 t2) = let
s1 = synifyType WithinType t1
s2 = synifyType WithinType t2
in noLoc $ HsFunTy s1 s2
synifyType s forallty@(ForAllTy _tv _ty) =
let (tvs, ctx, tau) = tcSplitSigmaTy forallty
in case s of
DeleteTopLevelQuantification -> synifyType ImplicitizeForAll tau
_ -> let
forallPlicitness = case s of
WithinType -> Explicit
ImplicitizeForAll -> Implicit
_ -> error "synifyType: impossible case!!!"
sTvs = synifyTyVars tvs
sCtx = synifyCtx ctx
sTau = synifyType WithinType tau
in noLoc $
HsForAllTy forallPlicitness sTvs sCtx sTau
synifyInstHead :: ([TyVar], [PredType], Class, [Type]) ->
([HsPred Name], Name, [HsType Name])
synifyInstHead (_, preds, cls, ts) =
( map (unLoc . synifyPred) preds
, getName cls
, map (unLoc . synifyType WithinType) ts
)
|
nominolo/haddock2
|
src/Haddock/Convert.hs
|
bsd-2-clause
| 11,829 | 0 | 19 | 2,844 | 2,309 | 1,206 | 1,103 | 188 | 9 |
{- |
Module : SAWScript.Crucible.JVM.ResolveSetupValue
License : BSD3
Maintainer : atomb
Stability : provisional
-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
module SAWScript.Crucible.JVM.ResolveSetupValue
( JVMVal(..)
, JVMRefVal
, resolveSetupVal
-- , typeOfJVMVal
, typeOfSetupValue
, lookupAllocIndex
, toJVMType
, resolveTypedTerm
, resolveBoolTerm
, resolveSAWPred
-- , resolveSetupFieldIndex
, equalValsPred
, JVMTypeOfError(..)
) where
import Control.Lens
import qualified Control.Monad.Catch as X
import qualified Data.BitVector.Sized as BV
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Void (absurd)
import qualified Cryptol.Eval.Type as Cryptol (TValue(..), evalValType)
import qualified Cryptol.TypeCheck.AST as Cryptol (Type, Schema(..))
import qualified Cryptol.Utils.PP as Cryptol (pp)
import qualified What4.BaseTypes as W4
import qualified What4.Interface as W4
import qualified What4.ProgramLoc as W4
import Verifier.SAW.SharedTerm
import Verifier.SAW.TypedTerm
import qualified Verifier.SAW.Prim as Prim
import qualified Verifier.SAW.Simulator.Concrete as Concrete
import Verifier.SAW.Simulator.What4.ReturnTrip
-- crucible
import qualified Lang.Crucible.Simulator as Crucible (RegValue)
-- what4
import qualified What4.Partial as W4
-- crucible-jvm
import qualified Lang.Crucible.JVM as CJ
-- jvm-parser
import qualified Language.JVM.Parser as J
import SAWScript.Crucible.Common
import SAWScript.Crucible.Common.MethodSpec (AllocIndex(..))
import SAWScript.Panic
import SAWScript.Crucible.JVM.MethodSpecIR
import qualified SAWScript.Crucible.Common.MethodSpec as MS
data JVMVal
= RVal (Crucible.RegValue Sym CJ.JVMRefType)
| IVal (Crucible.RegValue Sym CJ.JVMIntType)
| LVal (Crucible.RegValue Sym CJ.JVMLongType)
instance Show JVMVal where
show (RVal _) = "RVal"
show (IVal _) = "IVal"
show (LVal _) = "LVal"
type JVMRefVal = Crucible.RegValue Sym CJ.JVMRefType
type SetupValue = MS.SetupValue CJ.JVM
data JVMTypeOfError
= JVMPolymorphicType Cryptol.Schema
| JVMNonRepresentableType Cryptol.Type
| JVMInvalidTypedTerm TypedTermType
instance Show JVMTypeOfError where
show (JVMPolymorphicType s) =
unlines
[ "Expected monomorphic term"
, "instead got:"
, show (Cryptol.pp s)
]
show (JVMNonRepresentableType ty) =
unlines
[ "Type not representable in JVM:"
, show (Cryptol.pp ty)
]
show (JVMInvalidTypedTerm tp) =
unlines
[ "Expected typed term with Cryptol represnentable type, but got"
, show (MS.ppTypedTermType tp)
]
instance X.Exception JVMTypeOfError
typeOfSetupValue ::
X.MonadThrow m =>
JVMCrucibleContext ->
Map AllocIndex (W4.ProgramLoc, Allocation) ->
Map AllocIndex JIdent ->
SetupValue ->
m J.Type
typeOfSetupValue _cc env _nameEnv val =
case val of
MS.SetupVar i ->
case Map.lookup i env of
Nothing -> panic "JVMSetup" ["typeOfSetupValue", "Unresolved prestate variable:" ++ show i]
Just (_, alloc) -> return (allocationType alloc)
MS.SetupTerm tt ->
case ttType tt of
TypedTermSchema (Cryptol.Forall [] [] ty) ->
case toJVMType (Cryptol.evalValType mempty ty) of
Nothing -> X.throwM (JVMNonRepresentableType ty)
Just jty -> return jty
TypedTermSchema s -> X.throwM (JVMPolymorphicType s)
tp -> X.throwM (JVMInvalidTypedTerm tp)
MS.SetupNull () ->
-- We arbitrarily set the type of NULL to java.lang.Object,
-- because a) it is memory-compatible with any type that NULL
-- can be used at, and b) it prevents us from doing any
-- type-safe field accesses.
return (J.ClassType (J.mkClassName "java/lang/Object"))
MS.SetupGlobal empty _ -> absurd empty
MS.SetupStruct empty _ _ -> absurd empty
MS.SetupArray empty _ -> absurd empty
MS.SetupElem empty _ _ -> absurd empty
MS.SetupField empty _ _ -> absurd empty
MS.SetupCast empty _ _ -> absurd empty
MS.SetupUnion empty _ _ -> absurd empty
MS.SetupGlobalInitializer empty _ -> absurd empty
lookupAllocIndex :: Map AllocIndex a -> AllocIndex -> a
lookupAllocIndex env i =
case Map.lookup i env of
Nothing -> panic "JVMSetup" ["Unresolved prestate variable:" ++ show i]
Just x -> x
-- | Translate a SetupValue into a Crucible JVM value, resolving
-- references
resolveSetupVal ::
JVMCrucibleContext ->
Map AllocIndex JVMRefVal ->
Map AllocIndex (W4.ProgramLoc, Allocation) ->
Map AllocIndex JIdent ->
SetupValue ->
IO JVMVal
resolveSetupVal cc env _tyenv _nameEnv val =
case val of
MS.SetupVar i ->
pure (RVal (lookupAllocIndex env i))
MS.SetupTerm tm -> resolveTypedTerm cc tm
MS.SetupNull () ->
return (RVal (W4.maybePartExpr sym Nothing))
MS.SetupGlobal empty _ -> absurd empty
MS.SetupStruct empty _ _ -> absurd empty
MS.SetupArray empty _ -> absurd empty
MS.SetupElem empty _ _ -> absurd empty
MS.SetupField empty _ _ -> absurd empty
MS.SetupCast empty _ _ -> absurd empty
MS.SetupUnion empty _ _ -> absurd empty
MS.SetupGlobalInitializer empty _ -> absurd empty
where
sym = cc^.jccSym
resolveTypedTerm ::
JVMCrucibleContext ->
TypedTerm ->
IO JVMVal
resolveTypedTerm cc tm =
case ttType tm of
TypedTermSchema (Cryptol.Forall [] [] ty) ->
resolveSAWTerm cc (Cryptol.evalValType mempty ty) (ttTerm tm)
tp -> fail $ unlines
[ "resolveSetupVal: expected monomorphic term"
, "but got a term of type"
, show (MS.ppTypedTermType tp)
]
resolveSAWPred ::
JVMCrucibleContext ->
Term ->
IO (W4.Pred Sym)
resolveSAWPred cc tm =
do let sym = cc^.jccSym
st <- sawCoreState sym
bindSAWTerm sym st W4.BaseBoolRepr tm
resolveSAWTerm ::
JVMCrucibleContext ->
Cryptol.TValue ->
Term ->
IO JVMVal
resolveSAWTerm cc tp tm =
case tp of
Cryptol.TVBit ->
do b <- resolveBoolTerm sym tm
x0 <- W4.bvLit sym W4.knownNat (BV.zero W4.knownNat)
x1 <- W4.bvLit sym W4.knownNat (BV.one W4.knownNat)
x <- W4.bvIte sym b x1 x0
return (IVal x)
Cryptol.TVInteger ->
fail "resolveSAWTerm: unimplemented type Integer (FIXME)"
Cryptol.TVIntMod _ ->
fail "resolveSAWTerm: unimplemented type Z n (FIXME)"
Cryptol.TVFloat{} ->
fail "resolveSAWTerm: unimplemented type Float e p (FIXME)"
Cryptol.TVArray{} ->
fail "resolveSAWTerm: unimplemented type Array a b (FIXME)"
Cryptol.TVRational ->
fail "resolveSAWTerm: unimplemented type Rational (FIXME)"
Cryptol.TVSeq sz Cryptol.TVBit ->
case sz of
8 -> do x <- resolveBitvectorTerm sym (W4.knownNat @8) tm
IVal <$> W4.bvSext sym W4.knownNat x
16 -> do x <- resolveBitvectorTerm sym (W4.knownNat @16) tm
IVal <$> W4.bvSext sym W4.knownNat x
32 -> IVal <$> resolveBitvectorTerm sym W4.knownNat tm
64 -> LVal <$> resolveBitvectorTerm sym W4.knownNat tm
_ -> fail ("Invalid bitvector width: " ++ show sz)
Cryptol.TVSeq _sz _tp' ->
fail "resolveSAWTerm: unimplemented sequence type"
Cryptol.TVStream _tp' ->
fail "resolveSAWTerm: unsupported infinite stream type"
Cryptol.TVTuple _tps ->
fail "resolveSAWTerm: unsupported tuple type"
Cryptol.TVRec _flds ->
fail "resolveSAWTerm: unsupported record type"
Cryptol.TVFun _ _ ->
fail "resolveSAWTerm: unsupported function type"
Cryptol.TVAbstract _ _ ->
fail "resolveSAWTerm: unsupported abstract type"
Cryptol.TVNewtype{} ->
fail "resolveSAWTerm: unsupported newtype"
where
sym = cc^.jccSym
resolveBitvectorTerm ::
forall w.
(1 W4.<= w) =>
Sym ->
W4.NatRepr w ->
Term ->
IO (W4.SymBV Sym w)
resolveBitvectorTerm sym w tm =
do st <- sawCoreState sym
let sc = saw_ctx st
mx <- case getAllExts tm of
-- concretely evaluate if it is a closed term
[] ->
do modmap <- scGetModuleMap sc
let v = Concrete.evalSharedTerm modmap mempty mempty tm
pure (Just (Prim.unsigned (Concrete.toWord v)))
_ -> return Nothing
case mx of
Just x -> W4.bvLit sym w (BV.mkBV w x)
Nothing -> bindSAWTerm sym st (W4.BaseBVRepr w) tm
resolveBoolTerm :: Sym -> Term -> IO (W4.Pred Sym)
resolveBoolTerm sym tm =
do st <- sawCoreState sym
let sc = saw_ctx st
mx <- case getAllExts tm of
-- concretely evaluate if it is a closed term
[] ->
do modmap <- scGetModuleMap sc
let v = Concrete.evalSharedTerm modmap mempty mempty tm
pure (Just (Concrete.toBool v))
_ -> return Nothing
case mx of
Just x -> return (W4.backendPred sym x)
Nothing -> bindSAWTerm sym st W4.BaseBoolRepr tm
toJVMType :: Cryptol.TValue -> Maybe J.Type
toJVMType tp =
case tp of
Cryptol.TVBit -> Just J.BooleanType
Cryptol.TVInteger -> Nothing
Cryptol.TVIntMod _ -> Nothing
Cryptol.TVFloat{} -> Nothing
Cryptol.TVArray{} -> Nothing
Cryptol.TVRational -> Nothing
Cryptol.TVSeq n Cryptol.TVBit ->
case n of
8 -> Just J.ByteType
16 -> Just J.ShortType
32 -> Just J.IntType
64 -> Just J.LongType
_ -> Nothing
Cryptol.TVSeq _n t ->
do t' <- toJVMType t
Just (J.ArrayType t')
Cryptol.TVStream _tp' -> Nothing
Cryptol.TVTuple _tps -> Nothing
Cryptol.TVRec _flds -> Nothing
Cryptol.TVFun _ _ -> Nothing
Cryptol.TVAbstract _ _ -> Nothing
Cryptol.TVNewtype{} -> Nothing
equalValsPred ::
JVMCrucibleContext ->
JVMVal ->
JVMVal ->
IO (W4.Pred Sym)
equalValsPred cc v1 v2 = go (v1, v2)
where
go :: (JVMVal, JVMVal) -> IO (W4.Pred Sym)
go (RVal r1, RVal r2) = CJ.refIsEqual sym r1 r2
go (IVal i1, IVal i2) = W4.bvEq sym i1 i2
go (LVal l1, LVal l2) = W4.bvEq sym l1 l2
go _ = return (W4.falsePred sym)
sym = cc^.jccSym
|
GaloisInc/saw-script
|
src/SAWScript/Crucible/JVM/ResolveSetupValue.hs
|
bsd-3-clause
| 10,385 | 0 | 20 | 2,639 | 2,967 | 1,487 | 1,480 | -1 | -1 |
-- Copyright : Daan Leijen (c) 1999, [email protected]
-- HWT Group (c) 2003, [email protected]
-- License : BSD-style
module Opaleye.Internal.HaskellDB.PrimQuery where
import qualified Opaleye.Internal.Tag as T
import Data.ByteString (ByteString)
type TableName = String
type Attribute = String
type Name = String
type Scheme = [Attribute]
type Assoc = [(Attribute,PrimExpr)]
data Symbol = Symbol String T.Tag deriving (Read, Show)
data PrimExpr = AttrExpr Symbol
| BaseTableAttrExpr Attribute
| CompositeExpr PrimExpr Attribute -- ^ Composite Type Query
| BinExpr BinOp PrimExpr PrimExpr
| UnExpr UnOp PrimExpr
| AggrExpr AggrOp PrimExpr
| ConstExpr Literal
| CaseExpr [(PrimExpr,PrimExpr)] PrimExpr
| ListExpr [PrimExpr]
| ArrayExpr [PrimExpr]
| ParamExpr (Maybe Name) PrimExpr
| FunExpr Name [PrimExpr]
| CastExpr Name PrimExpr -- ^ Cast an expression to a given type.
| DefaultInsertExpr -- Indicate that we want to insert the
-- default value into a column.
-- TODO: I'm not sure this belongs
-- here. Perhaps a special type is
-- needed for insert expressions.
deriving (Read,Show)
data Literal = NullLit
| DefaultLit -- ^ represents a default value
| BoolLit Bool
| StringLit String
| ByteStringLit ByteString
| IntegerLit Integer
| DoubleLit Double
| OtherLit String -- ^ used for hacking in custom SQL
deriving (Read,Show)
data BinOp = OpEq | OpLt | OpLtEq | OpGt | OpGtEq | OpNotEq
| OpAnd | OpOr
| OpLike | OpIn
| OpOther String
| OpCat
| OpPlus | OpMinus | OpMul | OpDiv | OpMod
| OpBitNot | OpBitAnd | OpBitOr | OpBitXor
| OpAsg
| OpContains
deriving (Show,Read)
data UnOp = OpNot
| OpIsNull
| OpIsNotNull
| OpLength
| OpAbs
| OpNegate
| OpLower
| OpUpper
| UnOpOther String
deriving (Show,Read)
data AggrOp = AggrCount | AggrSum | AggrAvg | AggrMin | AggrMax
| AggrStdDev | AggrStdDevP | AggrVar | AggrVarP
| AggrBoolOr | AggrBoolAnd | AggrArr | AggrStringAggr PrimExpr
| AggrOther String
deriving (Show,Read)
data OrderExpr = OrderExpr OrderOp PrimExpr
deriving (Show)
data OrderNulls = NullsFirst | NullsLast
deriving Show
data OrderDirection = OpAsc | OpDesc
deriving Show
data OrderOp = OrderOp { orderDirection :: OrderDirection
, orderNulls :: OrderNulls }
deriving (Show)
|
benkolera/haskell-opaleye
|
src/Opaleye/Internal/HaskellDB/PrimQuery.hs
|
bsd-3-clause
| 3,182 | 0 | 8 | 1,319 | 544 | 338 | 206 | 67 | 0 |
{-# LANGUAGE FlexibleContexts #-}
module Mapping -- (DBMapping, mappingFind, findRowIO, getColValueFromRow)
where
import Database.HDBC
import Database.HDBC.ODBC
import Data.Maybe
--import Data.Convertible.Base
import Database.HDBC.SqlValue
{-| This is a first pass attempt at creating a mapping that can
load/modify/save records from tblUsers (or `users` while we test)
-}
-- | Group together all the ORM like functionality, find, save, new etc.
class DBMapping n where
-- | Find and instantiate a record based on the supplied identity
mappingFind :: Connection -> Integer -> IO (Maybe n)
-- | Return the mapping's unique identity. This shouldn't be a
-- database lookup, but simply returning the identity value if it
-- exists.
getId :: n -> Integer
-- | Populate the data record with the supplied database row
--populate :: Maybe [SqlValue] -> n
-- | The name of the under lying table
tableName :: n -> String
-- | The identity column name
idColumn :: n -> String
-- | Underlying database type
--dbType :: n -> String
-- | Save a row
save :: Connection -> n -> IO Integer
save connection n = do
let id = getId n
existCnt <- doesIdExist connection (tableName n) (idColumn n) id
if existCnt > 0
then saveExisting connection n
else saveNew connection n
saveExisting :: Connection -> n -> IO Integer
saveNew :: Connection -> n -> IO Integer
-- | Delete a row
--delete :: Connection -> n -> IO Integer
-- | Try and find a row from the specified table based on the supplied
-- id. Returns a Maybe [SqlValue]
findRowIO :: IConnection conn => conn -> String -> String -> Integer -> IO (Maybe [(String, SqlValue)])
findRowIO dbh tableName columnName id = do
let query = "SELECT * FROM " ++ tableName ++ " WHERE " ++ columnName ++ " = " ++ (show id)
putStrLn query
stmt <- prepare dbh query
execute stmt []
res <- fetchRowAL stmt
finish stmt
return res
--findRowById :: IConnection conn => conn -> String -> String -> Integer -> IO Integer
doesIdExist dbh tableName columnName id = do
let query = "SELECT COUNT(*) FROM " ++ tableName ++ " WHERE " ++ columnName ++ " = " ++ (show id)
executeScalarInt dbh query 0
-- | Retrieve the named column value for a list of tuples
getColValueFromRow columnName [] = error $ columnName ++ " not found"
getColValueFromRow columnName ((name,val): nvs) = if columnName == name
then val
else getColValueFromRow columnName nvs
getValue v def =
case v of
Nothing -> def
Just x -> fromSql $ head x
-- | Execute a query that returns a single scalar and return that
executeScalarInt :: IConnection conn => conn -> String -> Integer -> IO Integer
--executeScalarInt :: (Convertible SqlValue a, IConnection b) => b -> String -> a -> IO a
executeScalarInt dbh query defValue = do
stmt <- prepare dbh query
execute stmt []
rows <- fetchRow stmt
let res = getValue rows defValue
finish stmt
return res
|
timmyw/lapputils
|
src/Mapping.hs
|
bsd-3-clause
| 3,268 | 0 | 14 | 945 | 628 | 316 | 312 | 48 | 2 |
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude #-}
module Talks.Free.LanguageExample where
import Control.Monad.Free
import Data.Maybe
import Data.Text
import Talks.Free.Prelude
import Talks.Free.Language
program :: Free Language (Maybe Text, Maybe Text, Maybe Text)
program =
do genPw Nothing "p1"
genPw (Just 3) "p2"
genPw Nothing "p3"
genPw Nothing "p4"
setPw "p5" "p4"
p1 <- getPw "p1"
p2 <- getPw "p2"
p3 <- getPw "p3"
return (p1, p2, p3)
runLanguageInterpret :: IO ()
runLanguageInterpret =
do r <- interpret program
print r
runLanguageDescribe :: IO ()
runLanguageDescribe = putStrLn . unpack . intercalate "\n" . describe $ program
|
markhibberd/fp-syd-free
|
src/Talks/Free/LanguageExample.hs
|
bsd-3-clause
| 696 | 0 | 9 | 145 | 225 | 110 | 115 | 24 | 1 |
-- !!! Testing Ptr arithmetic and shows
import Foreign.Ptr
testShowAndPlus :: IO ()
testShowAndPlus = sequence_ [putStrLn (show64 (nullPtr `plusPtr` i)) | i <- [-100..100]]
show64 :: Ptr a -> String
show64 p =
case show p of
'0':'x':xs -> '0':'x':pseudoSignExtend xs
pseudoSignExtend :: String -> String
pseudoSignExtend xs =
case length xs of
8 -> replicate 8 (head xs) ++ xs
16 -> xs
|
FranklinChen/Hugs
|
tests/libs/testPtr.hs
|
bsd-3-clause
| 413 | 0 | 11 | 92 | 164 | 83 | 81 | 12 | 2 |
-- | Generate profiles and cross sections of solid models.
module Language.Mecha.Profile
( profile
, crossSection
, Point
, Line
) where
import System.Directory
import System.Process
import Language.Mecha.Export
import Language.Mecha.Solid (Solid)
-- | Project profile to x-y plane and extract line data from OpenSCAD.
profile :: Solid -> IO [Line]
profile = cut False
-- | Capture cross section at x-y plane and extract line data form OpenSCAD.
crossSection :: Solid -> IO [Line]
crossSection = cut True
cut :: Bool -> Solid -> IO [Line]
cut cut a = do
writeFile scad $ "projection(cut=" ++ (if cut then "true" else "false") ++ ")\n" ++ openSCAD a
readProcess "OpenSCAD" ["-o", dxf, scad] ""
f <- readFile dxf
if length f < 0 then undefined else return ()
removeFile scad
removeFile dxf
return $ parseDXF f
where
dxf = "__mecha_input.dxf"
scad = "__mecha_output.scad"
type Point = (Double, Double)
type Line = (Point, Point)
-- | Extract the lines from an OpenSCAD DXF file.
parseDXF :: String -> [Line]
parseDXF = parse . lines
where
parse :: [String] -> [Line]
parse a = case a of
[] -> []
"LINE" : _ : _ : _ : x0 : _ : x1 : _ : y0 : _ : y1 : rest -> ((read x0, read y0), (read x1, read y1)) : parse rest
_ : rest -> parse rest
|
tomahawkins/mecha
|
Language/Mecha/Profile.hs
|
bsd-3-clause
| 1,289 | 0 | 20 | 286 | 433 | 231 | 202 | 33 | 3 |
module Categorizer.Util.Maybe
( readSafe ) where
readSafe :: Read a => String -> Maybe a
readSafe s =
case reads s of
[(x, _)] -> Just x
_ -> Nothing
|
ameingast/categorizer
|
src/Categorizer/Util/Maybe.hs
|
bsd-3-clause
| 177 | 0 | 9 | 57 | 70 | 37 | 33 | 7 | 2 |
module Blockchain.Data.Code where
import Blockchain.Data.RLP
import qualified Data.ByteString as B
newtype Code = Code{codeBytes::B.ByteString} deriving (Show, Eq)
instance RLPSerializable Code where
rlpEncode (Code bytes) = rlpEncode bytes
rlpDecode = Code . rlpDecode
|
jamshidh/ethereum-data-leveldb
|
src/Blockchain/Data/Code.hs
|
bsd-3-clause
| 284 | 0 | 8 | 46 | 81 | 48 | 33 | 7 | 0 |
module Mime
( combineParts
) where
combineParts :: String -> String -> String
combineParts textContent htmlContent =
textContent ++ htmlContent
|
jdagilliland/md2multipart
|
Mime.hs
|
bsd-3-clause
| 150 | 0 | 6 | 26 | 36 | 20 | 16 | 5 | 1 |
module Main where
import AikatsuTypes
import Smile
main :: IO ()
main = do
print "ai!katsu!"
|
spinningfire/aikatsu
|
app/Main.hs
|
bsd-3-clause
| 103 | 0 | 7 | 26 | 31 | 17 | 14 | 6 | 1 |
{-# LANGUAGE CPP #-}
module Options.Applicative.Builder (
-- * Parser builders
--
-- | This module contains utility functions and combinators to create parsers
-- for individual options.
--
-- Each parser builder takes an option modifier. A modifier can be created by
-- composing the basic modifiers provided by this module using the 'Monoid'
-- operations 'mempty' and 'mappend', or their aliases 'idm' and '<>'.
--
-- For example:
--
-- > out = strOption
-- > ( long "output"
-- > <> short 'o'
-- > <> metavar "FILENAME" )
--
-- creates a parser for an option called \"output\".
subparser,
strArgument,
argument,
flag,
flag',
switch,
abortOption,
infoOption,
strOption,
option,
nullOption,
-- * Modifiers
short,
long,
help,
helpDoc,
value,
showDefaultWith,
showDefault,
metavar,
eitherReader,
noArgError,
ParseError(..),
hidden,
internal,
command,
command',
completeWith,
action,
completer,
idm,
#if __GLASGOW_HASKELL__ > 702
(<>),
#endif
mappend,
-- * Readers
--
-- | A collection of basic 'Option' readers.
auto,
str,
disabled,
readerAbort,
readerError,
-- * Builder for 'ParserInfo'
InfoMod,
fullDesc,
briefDesc,
header,
headerDoc,
footer,
footerDoc,
progDesc,
progDescDoc,
failureCode,
noIntersperse,
info,
-- * Builder for 'ParserPrefs'
PrefsMod,
multiSuffix,
disambiguate,
showHelpOnError,
noBacktrack,
columns,
prefs,
-- * Types
Mod,
ReadM,
OptionFields,
FlagFields,
ArgumentFields,
CommandFields
) where
import Control.Applicative (pure, (<|>))
import Data.Monoid (Monoid (..)
#if __GLASGOW_HASKELL__ > 702
, (<>)
#endif
)
import Options.Applicative.Builder.Completer
import Options.Applicative.Builder.Internal
import Options.Applicative.Common
import Options.Applicative.Types
import Options.Applicative.Help.Pretty
import Options.Applicative.Help.Chunk
import Data.List (intercalate)
-- readers --
-- | 'Option' reader based on the 'Read' type class.
auto :: Read a => ReadM a
auto = eitherReader $ \arg -> case reads arg of
[(r, "")] -> return r
_ -> Left $ "cannot parse value `" ++ arg ++ "'"
-- | String 'Option' reader.
str :: ReadM String
str = readerAsk
-- | Null 'Option' reader. All arguments will fail validation.
disabled :: ReadM a
disabled = readerError "disabled option"
-- modifiers --
-- | Specify a short name for an option.
short :: HasName f => Char -> Mod f a
short = fieldMod . name . OptShort
-- | Specify a long name for an option.
long :: HasName f => String -> Mod f a
long = fieldMod . name . OptLong
-- | Specify a default value for an option.
value :: HasValue f => a -> Mod f a
value x = Mod id (DefaultProp (Just x) Nothing) id
-- | Specify a function to show the default value for an option.
showDefaultWith :: (a -> String) -> Mod f a
showDefaultWith s = Mod id (DefaultProp Nothing (Just s)) id
-- | Show the default value for this option using its 'Show' instance.
showDefault :: Show a => Mod f a
showDefault = showDefaultWith show
-- | Specify the help text for an option.
help :: String -> Mod f a
help s = optionMod $ \p -> p { propHelp = paragraph s }
-- | Specify the help text for an option as a 'Text.PrettyPrint.ANSI.Leijen.Doc'
-- value.
helpDoc :: Maybe Doc -> Mod f a
helpDoc doc = optionMod $ \p -> p { propHelp = Chunk doc }
-- | Convert a function in the 'Either' monad to a reader.
eitherReader :: (String -> Either String a) -> ReadM a
eitherReader f = readerAsk >>= either readerError return . f
-- | Specify the error to display when no argument is provided to this option.
noArgError :: ParseError -> Mod OptionFields a
noArgError e = fieldMod $ \p -> p { optNoArgError = e }
-- | Specify a metavariable for the argument.
--
-- Metavariables have no effect on the actual parser, and only serve to specify
-- the symbolic name for an argument to be displayed in the help text.
metavar :: HasMetavar f => String -> Mod f a
metavar var = optionMod $ \p -> p { propMetaVar = var }
-- | Hide this option from the brief description.
hidden :: Mod f a
hidden = optionMod $ \p ->
p { propVisibility = min Hidden (propVisibility p) }
-- | Add a command to a subparser option.
command :: String -> ParserInfo a -> Mod CommandFields a
command cmd pinfo = fieldMod $ \p ->
p { cmdCommands = (cmd, pinfo) : cmdCommands p }
-- | Add a command to a subparser option with specified list of aliases.
command' :: String -> [String] -> ParserInfo a -> Mod CommandFields a
command' cmd [] pinfo = command cmd pinfo
command' cmd as pinfo = foldl (\c a -> commandAlias a pinfo `mappend` c) (command cmd pinfo') as
where pinfo' = pinfo { infoProgDesc = desc }
desc = vcatChunks [infoProgDesc pinfo, paragraph $ "Aliases: " ++ intercalate ", " as ++ "."]
-- | Add a commandAlias to a subparser option.
commandAlias :: String -> ParserInfo a -> Mod CommandFields a
commandAlias cmd pinfo = fieldMod $ \p ->
p { cmdCommands = (cmd, pinfo { isHidden = True }) : cmdCommands p }
-- | Add a list of possible completion values.
completeWith :: HasCompleter f => [String] -> Mod f a
completeWith xs = completer (listCompleter xs)
-- | Add a bash completion action. Common actions include @file@ and
-- @directory@. See
-- http://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html#Programmable-Completion-Builtins
-- for a complete list.
action :: HasCompleter f => String -> Mod f a
action act = completer (bashCompleter act)
-- | Add a completer to an argument.
--
-- A completer is a function String -> IO String which, given a partial
-- argument, returns all possible completions for that argument.
completer :: HasCompleter f => Completer -> Mod f a
completer f = fieldMod $ modCompleter (`mappend` f)
-- parsers --
-- | Builder for a command parser. The 'command' modifier can be used to
-- specify individual commands.
subparser :: Mod CommandFields a -> Parser a
subparser m = mkParser d g rdr
where
Mod _ d g = metavar "COMMAND" `mappend` m
rdr = uncurry CmdReader (mkCommand m)
-- | Builder for an argument parser.
argument :: ReadM a -> Mod ArgumentFields a -> Parser a
argument p (Mod f d g) = mkParser d g (ArgReader rdr)
where
ArgumentFields compl = f (ArgumentFields mempty)
rdr = CReader compl p
-- | Builder for a 'String' argument.
strArgument :: Mod ArgumentFields String -> Parser String
strArgument = argument str
-- | Builder for a flag parser.
--
-- A flag that switches from a \"default value\" to an \"active value\" when
-- encountered. For a simple boolean value, use `switch` instead.
flag :: a -- ^ default value
-> a -- ^ active value
-> Mod FlagFields a -- ^ option modifier
-> Parser a
flag defv actv m = flag' actv m <|> pure defv
-- | Builder for a flag parser without a default value.
--
-- Same as 'flag', but with no default value. In particular, this flag will
-- never parse successfully by itself.
--
-- It still makes sense to use it as part of a composite parser. For example
--
-- > length <$> many (flag' () (short 't'))
--
-- is a parser that counts the number of "-t" arguments on the command line.
flag' :: a -- ^ active value
-> Mod FlagFields a -- ^ option modifier
-> Parser a
flag' actv (Mod f d g) = mkParser d g rdr
where
rdr = let fields = f (FlagFields [] actv)
in FlagReader (flagNames fields)
(flagActive fields)
-- | Builder for a boolean flag.
--
-- > switch = flag False True
switch :: Mod FlagFields Bool -> Parser Bool
switch = flag False True
-- | An option that always fails.
--
-- When this option is encountered, the option parser immediately aborts with
-- the given parse error. If you simply want to output a message, use
-- 'infoOption' instead.
abortOption :: ParseError -> Mod OptionFields (a -> a) -> Parser (a -> a)
abortOption err m = option (readerAbort err) . (`mappend` m) $ mconcat
[ noArgError err
, value id
, metavar "" ]
-- | An option that always fails and displays a message.
infoOption :: String -> Mod OptionFields (a -> a) -> Parser (a -> a)
infoOption = abortOption . InfoMsg
-- | Builder for an option taking a 'String' argument.
strOption :: Mod OptionFields String -> Parser String
strOption = option str
-- | Same as 'option'.
{-# DEPRECATED nullOption "Use 'option' instead" #-}
nullOption :: ReadM a -> Mod OptionFields a -> Parser a
nullOption = option
-- | Builder for an option using the 'auto' reader.
option :: ReadM a -> Mod OptionFields a -> Parser a
option r m = mkParser d g rdr
where
Mod f d g = metavar "ARG" `mappend` m
fields = f (OptionFields [] mempty (ErrorMsg ""))
crdr = CReader (optCompleter fields) r
rdr = OptReader (optNames fields) crdr (optNoArgError fields)
-- | Modifier for 'ParserInfo'.
newtype InfoMod a = InfoMod
{ applyInfoMod :: ParserInfo a -> ParserInfo a }
instance Monoid (InfoMod a) where
mempty = InfoMod id
mappend m1 m2 = InfoMod $ applyInfoMod m2 . applyInfoMod m1
-- | Show a full description in the help text of this parser.
fullDesc :: InfoMod a
fullDesc = InfoMod $ \i -> i { infoFullDesc = True }
-- | Only show a brief description in the help text of this parser.
briefDesc :: InfoMod a
briefDesc = InfoMod $ \i -> i { infoFullDesc = False }
-- | Specify a header for this parser.
header :: String -> InfoMod a
header s = InfoMod $ \i -> i { infoHeader = paragraph s }
-- | Specify a header for this parser as a 'Text.PrettyPrint.ANSI.Leijen.Doc'
-- value.
headerDoc :: Maybe Doc -> InfoMod a
headerDoc doc = InfoMod $ \i -> i { infoHeader = Chunk doc }
-- | Specify a footer for this parser.
footer :: String -> InfoMod a
footer s = InfoMod $ \i -> i { infoFooter = paragraph s }
-- | Specify a footer for this parser as a 'Text.PrettyPrint.ANSI.Leijen.Doc'
-- value.
footerDoc :: Maybe Doc -> InfoMod a
footerDoc doc = InfoMod $ \i -> i { infoFooter = Chunk doc }
-- | Specify a short program description.
progDesc :: String -> InfoMod a
progDesc s = InfoMod $ \i -> i { infoProgDesc = paragraph s }
-- | Specify a short program description as a 'Text.PrettyPrint.ANSI.Leijen.Doc'
-- value.
progDescDoc :: Maybe Doc -> InfoMod a
progDescDoc doc = InfoMod $ \i -> i { infoProgDesc = Chunk doc }
-- | Specify an exit code if a parse error occurs.
failureCode :: Int -> InfoMod a
failureCode n = InfoMod $ \i -> i { infoFailureCode = n }
-- | Disable parsing of regular options after arguments
noIntersperse :: InfoMod a
noIntersperse = InfoMod $ \p -> p { infoIntersperse = False }
-- | Create a 'ParserInfo' given a 'Parser' and a modifier.
info :: Parser a -> InfoMod a -> ParserInfo a
info parser m = applyInfoMod m base
where
base = ParserInfo
{ infoParser = parser
, infoFullDesc = True
, infoProgDesc = mempty
, infoHeader = mempty
, infoFooter = mempty
, infoFailureCode = 1
, infoIntersperse = True
, isHidden = False }
newtype PrefsMod = PrefsMod
{ applyPrefsMod :: ParserPrefs -> ParserPrefs }
instance Monoid PrefsMod where
mempty = PrefsMod id
mappend m1 m2 = PrefsMod $ applyPrefsMod m2 . applyPrefsMod m1
multiSuffix :: String -> PrefsMod
multiSuffix s = PrefsMod $ \p -> p { prefMultiSuffix = s }
disambiguate :: PrefsMod
disambiguate = PrefsMod $ \p -> p { prefDisambiguate = True }
showHelpOnError :: PrefsMod
showHelpOnError = PrefsMod $ \p -> p { prefShowHelpOnError = True }
noBacktrack :: PrefsMod
noBacktrack = PrefsMod $ \p -> p { prefBacktrack = False }
columns :: Int -> PrefsMod
columns cols = PrefsMod $ \p -> p { prefColumns = cols }
prefs :: PrefsMod -> ParserPrefs
prefs m = applyPrefsMod m base
where
base = ParserPrefs
{ prefMultiSuffix = ""
, prefDisambiguate = False
, prefShowHelpOnError = False
, prefBacktrack = True
, prefColumns = 80 }
-- convenience shortcuts
-- | Trivial option modifier.
idm :: Monoid m => m
idm = mempty
|
d12frosted/optparse-applicative-kb
|
Options/Applicative/Builder.hs
|
bsd-3-clause
| 12,057 | 0 | 14 | 2,630 | 2,847 | 1,572 | 1,275 | 223 | 2 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
module Main where
import Debug.Trace
import Control.Monad.State
import Data.Dynamic hiding (typeOf)
import Data.Maybe
import qualified Data.Map as Map
import Data.Map (Map)
import Data
import Data.Type
import Execute
import Refs
import Run
import Storage
b (A _ b') = b'
test = do
store $ A "AA" (Ref "B")
a <- find (refA "AA")
b <- find $ b (fromJust a)
find (refA "AA") >>= execute . MkExecutable . fromJust
find (refB "B") >>= execute . MkExecutable . fromJust
find (refC "A") >>= execute . MkExecutable . fromJust
main :: IO ()
main = runInit "D:\\Work\\Haskell\\refs\\refs.db" test >>= print
|
showpoint/refs
|
src/Main.hs
|
bsd-3-clause
| 971 | 0 | 12 | 193 | 249 | 134 | 115 | 32 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Matrix.Class.IMatrix
-- Copyright : Copyright (c) , Patrick Perry <[email protected]>
-- License : BSD3
-- Maintainer : Patrick Perry <[email protected]>
-- Stability : experimental
--
-- An overloaded interface for immutable matrices. The matrices provide
-- access to rows and columns, and can operate via multiplication on
-- immutable dense vectors and matrices.
--
module Data.Matrix.Class.IMatrix (
-- * The IMatrix type class
IMatrix,
-- * Operators
(<*>),
(<**>),
-- * Rows and columns
row,
col,
rows,
cols,
-- * Multiplication
applyVector,
applyMatrix,
sapplyVector,
sapplyMatrix,
) where
import Data.Matrix.Class.IMatrixBase
|
patperry/hs-linear-algebra
|
lib/Data/Matrix/Class/IMatrix.hs
|
bsd-3-clause
| 823 | 0 | 4 | 175 | 71 | 55 | 16 | 13 | 0 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------------------
import Text.Pandoc.JSON
import Text.Pandoc
( writeLaTeX )
import Text.Pandoc.Options
( def )
import Utils
import Data.List
( intercalate
, elem )
--------------------------------------------------------------------------------
main :: IO ()
main = toJSONFilter cvList
cvList :: Maybe Format -> Block -> [Block]
cvList (Just "latex") (Div (_, cs, _) contents)
| "aside" `elem` cs
= [ latexBlock "\\begin{aside}" ]
++ contents
++ [ latexBlock $ unlines
[ "\\end{aside}"
, "\\hspace{0.5cm}"
, "\\begin{minipage}[t]{\\linewidth-0.5\\asidewidth}"
, "\\minipageopentrue"
, "\\vspace*{0.9\\baselineskip}"
]
]
cvList (Just "latex") (DefinitionList contents)
= [latexBlock "\\begin{entrylist}"]
++ map toEntry contents
++ [latexBlock "\\end{entrylist}"]
cvList (Just "latex") (RawBlock "html" "<!-- break -->")
= return
$ latexBlock $ unlines
[ "\\ifminipageopen"
, "\\end{minipage}"
, "\\fi"
, "\\minipageopenfalse"
]
cvList _ x = [x]
toEntry :: ([Inline], [[Block]]) -> Block
toEntry (date, definitions)
= latexBlock
$ "\\entry{"
++ intercalate
"}{"
(addBreaks (map (writeLaTeX def . Pandoc nullMeta)
(take 4 $ [Plain date] : definitions ++ repeat [Null]) ))
++ "}"
where
addBreaks
= zipWith (\ i e -> if i == 3 && not (null e) then "\\\\" ++ e else e)
[0..]
--------------------------------------------------------------------------------
|
dfaligertwood/pandoc-filters
|
pandoc-cv.hs
|
bsd-3-clause
| 1,926 | 0 | 17 | 579 | 443 | 240 | 203 | 47 | 2 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.Selection
-- Copyright : (c) Sven Panne 2002-2005
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- This module corresponds to section 5.2 (Selection) of the OpenGL 1.5 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Selection (
HitRecord(..), getHitRecords,
Name(..), withName, loadName, maxNameStackDepth, nameStackDepth,
RenderMode(..), renderMode
) where
import Foreign.Marshal.Array ( allocaArray )
import Foreign.Ptr ( Ptr )
import Graphics.Rendering.OpenGL.GL.BasicTypes (
GLint, GLsizei, GLuint, GLfloat )
import Graphics.Rendering.OpenGL.GL.Exception ( bracket_ )
import Graphics.Rendering.OpenGL.GL.IOState (
IOState, peekIOState, evalIOState, nTimes )
import Graphics.Rendering.OpenGL.GL.QueryUtils (
GetPName(GetMaxNameStackDepth,GetNameStackDepth), getSizei1 )
import Graphics.Rendering.OpenGL.GL.RenderMode (
RenderMode(..), withRenderMode, renderMode )
import Graphics.Rendering.OpenGL.GL.StateVar (
GettableStateVar, makeGettableStateVar )
--------------------------------------------------------------------------------
data HitRecord = HitRecord GLfloat GLfloat [Name]
deriving ( Eq, Ord, Show )
--------------------------------------------------------------------------------
getHitRecords :: GLsizei -> IO a -> IO (a, Maybe [HitRecord])
getHitRecords bufSize action =
allocaArray (fromIntegral bufSize) $ \buf -> do
glSelectBuffer bufSize buf
(value, numHits) <- withRenderMode Select $ do
glInitNames
action
hits <- parseSelectionBuffer numHits buf
return (value, hits)
foreign import CALLCONV unsafe "glInitNames" glInitNames :: IO ()
foreign import CALLCONV unsafe "glSelectBuffer" glSelectBuffer ::
GLsizei -> Ptr GLuint -> IO ()
--------------------------------------------------------------------------------
parseSelectionBuffer :: GLint -> Ptr GLuint -> IO (Maybe [HitRecord])
parseSelectionBuffer numHits buf
| numHits < 0 = return Nothing
| otherwise = fmap Just $ evalIOState (nTimes numHits parseSelectionHit) buf
type Parser a = IOState GLuint a
parseSelectionHit :: Parser HitRecord
parseSelectionHit = do
numNames <- parseGLuint
minZ <- parseGLfloat
maxZ <- parseGLfloat
nameStack <- nTimes numNames parseName
return $ HitRecord minZ maxZ nameStack
parseGLuint :: Parser GLuint
parseGLuint = peekIOState
parseGLfloat :: Parser GLfloat
parseGLfloat = fmap (\x -> fromIntegral x / 0xffffffff) parseGLuint
parseName :: Parser Name
parseName = fmap Name parseGLuint
--------------------------------------------------------------------------------
newtype Name = Name GLuint
deriving ( Eq, Ord, Show )
withName :: Name -> IO a -> IO a
withName name = bracket_ (glPushName name) glPopName
foreign import CALLCONV unsafe "glPopName" glPopName :: IO ()
foreign import CALLCONV unsafe "glPushName" glPushName :: Name -> IO ()
foreign import CALLCONV unsafe "glLoadName" loadName :: Name -> IO ()
maxNameStackDepth :: GettableStateVar GLsizei
maxNameStackDepth = makeGettableStateVar (getSizei1 id GetMaxNameStackDepth)
nameStackDepth :: GettableStateVar GLsizei
nameStackDepth = makeGettableStateVar (getSizei1 id GetNameStackDepth)
|
FranklinChen/hugs98-plus-Sep2006
|
packages/OpenGL/Graphics/Rendering/OpenGL/GL/Selection.hs
|
bsd-3-clause
| 3,520 | 4 | 12 | 513 | 799 | 438 | 361 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Test.Tasty.Runners.HPC where
------------------------------------------------------------------------------
import Control.Concurrent.MVar
import Control.Exception
import Control.Monad
import qualified Data.Map as Map
import Data.Monoid
import Data.Typeable
import qualified System.Process as P
------------------------------------------------------------------------------
import qualified Test.Tasty.Options as Tasty
import qualified Test.Tasty.Providers as Tasty
import qualified Test.Tasty.Runners as Tasty
import qualified Trace.Hpc.Tix as Hpc
import qualified Trace.Hpc.Mix as Hpc
------------------------------------------------------------------------------
import Test.Tasty.Runners.HPC.Internal
import Test.Tasty.Runners.HPC.Render
------------------------------------------------------------------------------
hpcRunner :: Tasty.Ingredient
hpcRunner = Tasty.TestReporter optionDescriptions runner
where
optionDescriptions = [ Tasty.Option (Proxy :: Proxy RunHPC)
, Tasty.Option (Proxy :: Proxy MixPath)
, Tasty.Option (Proxy :: Proxy TixPath)
]
----------------------------------------------------------------------------
runner :: Tasty.OptionSet -> Tasty.TestTree
-> Maybe (Tasty.StatusMap -> IO Bool)
runner options testTree = case Tasty.lookupOption options of
RunHPC False -> Nothing
RunHPC True -> Just $ \_ -> do
print "Running!"
talkingStick <- newMVar ()
-- talkingStick is passed among tests to prevent contention over their
-- single tix count file. Is this the best way?
let hpcFold = Tasty.trivialFold {
Tasty.foldSingle = runSingle talkingStick
}
cm@(CodeTests m) <- Tasty.getApp $
Tasty.foldTestTree hpcFold options testTree
putStrLn $ show cm -- TODO replace with real output format
testsReports cm
return (not . Map.null $ m) -- TODO check all tests passed?
----------------------------------------------------------------------------
runSingle :: forall t. Tasty.IsTest t => MVar ()
-> Tasty.OptionSet -> Tasty.TestName -> t
-> Tasty.Ap IO CodeTests
runSingle mv opts name test = Tasty.Ap . withMVar mv $ \_ -> do
print "Running!!"
let cmd = "dist/build/testsuite/testsuite --quiet -p '" ++ name ++ "'"
codeFile = "src/Fib.hs" -- TODO Temporary
res <- Tasty.run opts test (print . Tasty.progressText)
-- Tix files are only written when a process finishes. So we must spawn
-- a new tasty process to run each test & get the single-test tix counts
tix' <- touchTixWith "testsuite.tix" cmd
tests <- case tix' of
Nothing -> return mempty
Just (Hpc.Tix moduleEntries) ->
codeMapOfTest codeFile moduleEntries name res
testsReports tests
return tests
------------------------------------------------------------------------------
codeMapOfTest :: FilePath
-> [Hpc.TixModule]
-> String
-> Tasty.Result
-> IO CodeTests
codeMapOfTest codeFile tixMods testName testResult = do
moduleMappings <- forM tixMods $ \tixMod@(Hpc.TixModule _ _ _ counts) -> do
--rMix <- try $ Hpc.readMix ["dist/hpc/mix/fib-0.1.0.0/fib-0.1.0.0"] (Right tixMod)
rMix <- try $ Hpc.readMix ["dist/hpc/mix/fib-0.1.0.0"] (Right tixMod)
case rMix of
-- TODO: What do do when tix file mentions nonexistent mix? For me, tix
-- marks happen for Tasty itself for some reason, but I don't have mix
-- files for tasty. So for now, tix module entries w/ no mix file
Left (e :: SomeException) -> print "Exception!" >> return mempty
Right (Hpc.Mix _ _ _ _ mixEntries) -> do
print "Got a mix!"
let mixEntriesWithCounts = zip mixEntries counts
touched :: [Hpc.MixEntry]
touched = map fst . filter ((>0) . snd) $ mixEntriesWithCounts
return . CodeTests $ Map.fromList [((codeFile,e), [(testName,testResult)]) | e <- touched]
return $ mconcat moduleMappings
------------------------------------------------------------------------------
touchTixWith :: FilePath -> String -> IO (Maybe Hpc.Tix)
touchTixWith tixFilePath cmd = do
Hpc.writeTix tixFilePath emptyTix
h <- P.runCommand cmd
_ <- P.waitForProcess h
Hpc.readTix tixFilePath
------------------------------------------------------------------------------
emptyTix :: Hpc.Tix
emptyTix = Hpc.Tix []
|
imalsogreg/tasty-hpc
|
src/Test/Tasty/Runners/HPC.hs
|
bsd-3-clause
| 4,838 | 0 | 25 | 1,212 | 982 | 514 | 468 | 77 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE PolyKinds #-}
#endif
#ifdef TRUSTWORTHY
{-# LANGUAGE Trustworthy #-}
#endif
#if __GLASGOW_HASKELL__ >= 710
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
#endif
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
#ifndef MIN_VERSION_base
#define MIN_VERSION_base(x,y,z) 1
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Wrapped
-- Copyright : (C) 2012-15 Edward Kmett, Michael Sloan
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : Rank2, MPTCs, fundeps
--
-- The 'Wrapped' class provides similar functionality as @Control.Newtype@,
-- from the @newtype@ package, but in a more convenient and efficient form.
--
-- There are a few functions from @newtype@ that are not provided here, because
-- they can be done with the 'Iso' directly:
--
-- @
-- Control.Newtype.over 'Sum' f ≡ '_Unwrapping' 'Sum' 'Control.Lens.Setter.%~' f
-- Control.Newtype.under 'Sum' f ≡ '_Wrapping' 'Sum' 'Control.Lens.Setter.%~' f
-- Control.Newtype.overF 'Sum' f ≡ 'mapping' ('_Unwrapping' 'Sum') 'Control.Lens.Setter.%~' f
-- Control.Newtype.underF 'Sum' f ≡ 'mapping' ('_Wrapping' 'Sum') 'Control.Lens.Setter.%~' f
-- @
--
-- 'under' can also be used with '_Unwrapping' to provide the equivalent of
-- @Control.Newtype.under@. Also, most use cases don't need full polymorphism,
-- so only the single constructor '_Wrapping' functions would be needed.
--
-- These equivalences aren't 100% honest, because @newtype@'s operators
-- need to rely on two @Newtype@ constraints. This means that the wrapper used
-- for the output is not necessarily the same as the input.
--
----------------------------------------------------------------------------
module Control.Lens.Wrapped
(
-- * Wrapping and Unwrapping monomorphically
Wrapped(..)
, _Unwrapped'
, _Wrapping', _Unwrapping'
-- * Wrapping and unwrapping polymorphically
, Rewrapped, Rewrapping
, _Wrapped, _Unwrapped
, _Wrapping, _Unwrapping
-- * Operations
, op
, ala, alaf
#if __GLASGOW_HASKELL__ >= 710
-- * Pattern Synonyms
, pattern Wrapped
, pattern Unwrapped
#endif
) where
import Control.Applicative
import Control.Arrow
import Control.Applicative.Backwards
import Control.Comonad.Trans.Traced
import Control.Exception
import Control.Lens.Getter
import Control.Lens.Iso
#if __GLASGOW_HASKELL__ >= 710
import Control.Lens.Review
#endif
import Control.Monad.Trans.Cont
import Control.Monad.Trans.Error
import Control.Monad.Trans.Identity
import Control.Monad.Trans.List
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Reader
import qualified Control.Monad.Trans.RWS.Lazy as Lazy
import qualified Control.Monad.Trans.RWS.Strict as Strict
import qualified Control.Monad.Trans.State.Lazy as Lazy
import qualified Control.Monad.Trans.State.Strict as Strict
import qualified Control.Monad.Trans.Writer.Lazy as Lazy
import qualified Control.Monad.Trans.Writer.Strict as Strict
import Data.Foldable as Foldable
import Data.Functor.Compose
import Data.Functor.Contravariant
import qualified Data.Functor.Contravariant.Compose as Contravariant
import Data.Functor.Constant
import Data.Functor.Coproduct
import Data.Functor.Identity
import Data.Functor.Reverse
import Data.Hashable
import Data.IntSet as IntSet
import Data.IntMap as IntMap
import Data.HashSet as HashSet
import Data.HashMap.Lazy as HashMap
import Data.List.NonEmpty
import Data.Map as Map
import Data.Monoid
import qualified Data.Semigroup as S
import Data.Sequence as Seq hiding (length)
import Data.Set as Set
import Data.Tagged
import Data.Vector as Vector
import Data.Vector.Primitive as Prim
import Data.Vector.Unboxed as Unboxed
import Data.Vector.Storable as Storable
#if MIN_VERSION_base(4,6,0)
import Data.Ord (Down(Down))
#else
import GHC.Exts (Down(Down))
#endif
#ifdef HLINT
{-# ANN module "HLint: ignore Use uncurry" #-}
#endif
-- $setup
-- >>> :set -XNoOverloadedStrings
-- >>> import Control.Lens
-- | 'Wrapped' provides isomorphisms to wrap and unwrap newtypes or
-- data types with one constructor.
class Wrapped s where
type Unwrapped s :: *
-- | An isomorphism between @s@ and @a@.
_Wrapped' :: Iso' s (Unwrapped s)
#if __GLASGOW_HASKELL__ >= 710
pattern Wrapped a <- (view _Wrapped -> a) where
Wrapped a = review _Wrapped a
pattern Unwrapped a <- (view _Unwrapped -> a) where
Unwrapped a = review _Unwrapped a
#endif
-- This can be used to help inference between the wrappers
class Wrapped s => Rewrapped (s :: *) (t :: *)
class (Rewrapped s t, Rewrapped t s) => Rewrapping s t
instance (Rewrapped s t, Rewrapped t s) => Rewrapping s t
_Unwrapped' :: Wrapped s => Iso' (Unwrapped s) s
_Unwrapped' = from _Wrapped'
{-# INLINE _Unwrapped' #-}
-- | Work under a newtype wrapper.
--
-- >>> Const "hello" & _Wrapped %~ Prelude.length & getConst
-- 5
--
-- @
-- '_Wrapped' ≡ 'from' '_Unwrapped'
-- '_Unwrapped' ≡ 'from' '_Wrapped'
-- @
_Wrapped :: Rewrapping s t => Iso s t (Unwrapped s) (Unwrapped t)
_Wrapped = withIso _Wrapped' $ \ sa _ -> withIso _Wrapped' $ \ _ bt -> iso sa bt
{-# INLINE _Wrapped #-}
_Unwrapped :: Rewrapping s t => Iso (Unwrapped t) (Unwrapped s) t s
_Unwrapped = from _Wrapped
{-# INLINE _Unwrapped #-}
-- * base
instance (t ~ All) => Rewrapped All t
instance Wrapped All where
type Unwrapped All = Bool
_Wrapped' = iso getAll All
{-# INLINE _Wrapped' #-}
instance (t ~ Any) => Rewrapped Any t
instance Wrapped Any where
type Unwrapped Any = Bool
_Wrapped' = iso getAny Any
{-# INLINE _Wrapped' #-}
instance (t ~ Sum b) => Rewrapped (Sum a) t
instance Wrapped (Sum a) where
type Unwrapped (Sum a) = a
_Wrapped' = iso getSum Sum
{-# INLINE _Wrapped' #-}
instance (t ~ Product b) => Rewrapped (Product a) t
instance Wrapped (Product a) where
type Unwrapped (Product a) = a
_Wrapped' = iso getProduct Product
{-# INLINE _Wrapped' #-}
instance (t ~ Kleisli m' a' b') => Rewrapped (Kleisli m a b) t
instance Wrapped (Kleisli m a b) where
type Unwrapped (Kleisli m a b) = a -> m b
_Wrapped' = iso runKleisli Kleisli
{-# INLINE _Wrapped' #-}
instance (t ~ WrappedMonad m' a') => Rewrapped (WrappedMonad m a) t
instance Wrapped (WrappedMonad m a) where
type Unwrapped (WrappedMonad m a) = m a
_Wrapped' = iso unwrapMonad WrapMonad
{-# INLINE _Wrapped' #-}
instance (t ~ WrappedArrow a' b' c') => Rewrapped (WrappedArrow a b c) t
instance Wrapped (WrappedArrow a b c) where
type Unwrapped (WrappedArrow a b c) = a b c
_Wrapped' = iso unwrapArrow WrapArrow
{-# INLINE _Wrapped' #-}
instance (t ~ ZipList b) => Rewrapped (ZipList a) t
instance Wrapped (ZipList a) where
type Unwrapped (ZipList a) = [a]
_Wrapped' = iso getZipList ZipList
{-# INLINE _Wrapped' #-}
instance (t ~ NonEmpty b) => Rewrapped (NonEmpty a) t
instance Wrapped (NonEmpty a) where
type Unwrapped (NonEmpty a) = (a, [a])
_Wrapped' = iso (\(a :| as) -> (a, as)) (\(a,as) -> a :| as)
{-# INLINE _Wrapped' #-}
instance (t ~ Const a' x') => Rewrapped (Const a x) t
instance Wrapped (Const a x) where
type Unwrapped (Const a x) = a
_Wrapped' = iso getConst Const
{-# INLINE _Wrapped' #-}
instance (t ~ Dual b) => Rewrapped (Dual a) t
instance Wrapped (Dual a) where
type Unwrapped (Dual a) = a
_Wrapped' = iso getDual Dual
{-# INLINE _Wrapped' #-}
instance (t ~ Endo b) => Rewrapped (Endo b) t
instance Wrapped (Endo a) where
type Unwrapped (Endo a) = a -> a
_Wrapped' = iso appEndo Endo
{-# INLINE _Wrapped' #-}
instance (t ~ First b) => Rewrapped (First a) t
instance Wrapped (First a) where
type Unwrapped (First a) = Maybe a
_Wrapped' = iso getFirst First
{-# INLINE _Wrapped' #-}
instance (t ~ Last b) => Rewrapped (Last a) t
instance Wrapped (Last a) where
type Unwrapped (Last a) = Maybe a
_Wrapped' = iso getLast Last
{-# INLINE _Wrapped' #-}
#if MIN_VERSION_base(4,8,0)
instance (t ~ Alt g b) => Rewrapped (Alt f a) t
instance Wrapped (Alt f a) where
type Unwrapped (Alt f a) = f a
_Wrapped' = iso getAlt Alt
{-# INLINE _Wrapped' #-}
#endif
instance (t ~ ArrowMonad m' a', ArrowApply m) => Rewrapped (ArrowMonad m a) t
instance Wrapped (ArrowMonad m a) where
type Unwrapped (ArrowMonad m a) = m () a
_Wrapped' = iso getArrowMonad ArrowMonad
{-# INLINE _Wrapped' #-}
instance t ~ Down a => Rewrapped (Down a) t
instance Wrapped (Down a) where
type Unwrapped (Down a) = a
_Wrapped' = iso (\(Down a) -> a) Down
-- * transformers
instance (t ~ Backwards g b) => Rewrapped (Backwards f a) t
instance Wrapped (Backwards f a) where
type Unwrapped (Backwards f a) = f a
_Wrapped' = iso forwards Backwards
instance (t ~ Compose f' g' a') => Rewrapped (Compose f g a) t
instance Wrapped (Compose f g a) where
type Unwrapped (Compose f g a) = f (g a)
_Wrapped' = iso getCompose Compose
instance (t ~ Constant a' b') => Rewrapped (Constant a b) t
instance Wrapped (Constant a b) where
type Unwrapped (Constant a b) = a
_Wrapped' = iso getConstant Constant
instance (t ~ ContT r' m' a') => Rewrapped (ContT r m a) t
instance Wrapped (ContT r m a) where
type Unwrapped (ContT r m a) = (a -> m r) -> m r
_Wrapped' = iso runContT ContT
instance (t ~ ErrorT e' m' a') => Rewrapped (ErrorT e m a) t
instance Wrapped (ErrorT e m a) where
type Unwrapped (ErrorT e m a) = m (Either e a)
_Wrapped' = iso runErrorT ErrorT
{-# INLINE _Wrapped' #-}
instance (t ~ Identity b) => Rewrapped (Identity a) t
instance Wrapped (Identity a) where
type Unwrapped (Identity a) = a
_Wrapped' = iso runIdentity Identity
{-# INLINE _Wrapped' #-}
instance (t ~ IdentityT n b) => Rewrapped (IdentityT m a) t
instance Wrapped (IdentityT m a) where
type Unwrapped (IdentityT m a) = m a
_Wrapped' = iso runIdentityT IdentityT
{-# INLINE _Wrapped' #-}
instance (t ~ ListT n b) => Rewrapped (ListT m a) t
instance Wrapped (ListT m a) where
type Unwrapped (ListT m a) = m [a]
_Wrapped' = iso runListT ListT
{-# INLINE _Wrapped' #-}
instance (t ~ MaybeT n b) => Rewrapped (MaybeT m a) t
instance Wrapped (MaybeT m a) where
type Unwrapped (MaybeT m a) = m (Maybe a)
_Wrapped' = iso runMaybeT MaybeT
{-# INLINE _Wrapped' #-}
instance (t ~ ReaderT r n b) => Rewrapped (ReaderT r m a) t
instance Wrapped (ReaderT r m a) where
type Unwrapped (ReaderT r m a) = r -> m a
_Wrapped' = iso runReaderT ReaderT
{-# INLINE _Wrapped' #-}
instance (t ~ Reverse g b) => Rewrapped (Reverse f a) t
instance Wrapped (Reverse f a) where
type Unwrapped (Reverse f a) = f a
_Wrapped' = iso getReverse Reverse
{-# INLINE _Wrapped' #-}
instance (t ~ Lazy.RWST r' w' s' m' a') => Rewrapped (Lazy.RWST r w s m a) t
instance Wrapped (Lazy.RWST r w s m a) where
type Unwrapped (Lazy.RWST r w s m a) = r -> s -> m (a, s, w)
_Wrapped' = iso Lazy.runRWST Lazy.RWST
{-# INLINE _Wrapped' #-}
instance (t ~ Strict.RWST r' w' s' m' a') => Rewrapped (Strict.RWST r w s m a) t
instance Wrapped (Strict.RWST r w s m a) where
type Unwrapped (Strict.RWST r w s m a) = r -> s -> m (a, s, w)
_Wrapped' = iso Strict.runRWST Strict.RWST
{-# INLINE _Wrapped' #-}
instance (t ~ Lazy.StateT s' m' a') => Rewrapped (Lazy.StateT s m a) t
instance Wrapped (Lazy.StateT s m a) where
type Unwrapped (Lazy.StateT s m a) = s -> m (a, s)
_Wrapped' = iso Lazy.runStateT Lazy.StateT
{-# INLINE _Wrapped' #-}
instance (t ~ Strict.StateT s' m' a') => Rewrapped (Strict.StateT s m a) t
instance Wrapped (Strict.StateT s m a) where
type Unwrapped (Strict.StateT s m a) = s -> m (a, s)
_Wrapped' = iso Strict.runStateT Strict.StateT
{-# INLINE _Wrapped' #-}
instance (t ~ Lazy.WriterT w' m' a') => Rewrapped (Lazy.WriterT w m a) t
instance Wrapped (Lazy.WriterT w m a) where
type Unwrapped (Lazy.WriterT w m a) = m (a, w)
_Wrapped' = iso Lazy.runWriterT Lazy.WriterT
{-# INLINE _Wrapped' #-}
instance (t ~ Strict.WriterT w' m' a') => Rewrapped (Strict.WriterT w m a) t
instance Wrapped (Strict.WriterT w m a) where
type Unwrapped (Strict.WriterT w m a) = m (a, w)
_Wrapped' = iso Strict.runWriterT Strict.WriterT
{-# INLINE _Wrapped' #-}
-- * comonad-transformers
instance (t ~ Coproduct f' g' a') => Rewrapped (Coproduct f g a) t
instance Wrapped (Coproduct f g a) where
type Unwrapped (Coproduct f g a) = Either (f a) (g a)
_Wrapped' = iso getCoproduct Coproduct
{-# INLINE _Wrapped' #-}
instance (t ~ TracedT m' w' a') => Rewrapped (TracedT m w a) t
instance Wrapped (TracedT m w a) where
type Unwrapped (TracedT m w a) = w (m -> a)
_Wrapped' = iso runTracedT TracedT
{-# INLINE _Wrapped' #-}
-- * unordered-containers
-- | Use @'wrapping' 'HashMap.fromList'@. Unwrapping returns some permutation of the list.
instance (t ~ HashMap k' a', Hashable k, Eq k) => Rewrapped (HashMap k a) t
instance (Hashable k, Eq k) => Wrapped (HashMap k a) where
type Unwrapped (HashMap k a) = [(k, a)]
_Wrapped' = iso HashMap.toList HashMap.fromList
{-# INLINE _Wrapped' #-}
-- | Use @'wrapping' 'HashSet.fromList'@. Unwrapping returns some permutation of the list.
instance (t ~ HashSet a', Hashable a, Eq a) => Rewrapped (HashSet a) t
instance (Hashable a, Eq a) => Wrapped (HashSet a) where
type Unwrapped (HashSet a) = [a]
_Wrapped' = iso HashSet.toList HashSet.fromList
{-# INLINE _Wrapped' #-}
-- * containers
-- | Use @'wrapping' 'IntMap.fromList'@. unwrapping returns a /sorted/ list.
instance (t ~ IntMap a') => Rewrapped (IntMap a) t
instance Wrapped (IntMap a) where
type Unwrapped (IntMap a) = [(Int, a)]
_Wrapped' = iso IntMap.toAscList IntMap.fromList
{-# INLINE _Wrapped' #-}
-- | Use @'wrapping' 'IntSet.fromList'@. unwrapping returns a /sorted/ list.
instance (t ~ IntSet) => Rewrapped IntSet t
instance Wrapped IntSet where
type Unwrapped IntSet = [Int]
_Wrapped' = iso IntSet.toAscList IntSet.fromList
{-# INLINE _Wrapped' #-}
-- | Use @'wrapping' 'Map.fromList'@. unwrapping returns a /sorted/ list.
instance (t ~ Map k' a', Ord k) => Rewrapped (Map k a) t
instance Ord k => Wrapped (Map k a) where
type Unwrapped (Map k a) = [(k, a)]
_Wrapped' = iso Map.toAscList Map.fromList
{-# INLINE _Wrapped' #-}
-- | Use @'wrapping' 'Set.fromList'@. unwrapping returns a /sorted/ list.
instance (t ~ Set a', Ord a) => Rewrapped (Set a) t
instance Ord a => Wrapped (Set a) where
type Unwrapped (Set a) = [a]
_Wrapped' = iso Set.toAscList Set.fromList
{-# INLINE _Wrapped' #-}
instance (t ~ Seq a') => Rewrapped (Seq a) t
instance Wrapped (Seq a) where
type Unwrapped (Seq a) = [a]
_Wrapped' = iso Foldable.toList Seq.fromList
{-# INLINE _Wrapped' #-}
-- * vector
instance (t ~ Vector.Vector a') => Rewrapped (Vector.Vector a) t
instance Wrapped (Vector.Vector a) where
type Unwrapped (Vector.Vector a) = [a]
_Wrapped' = iso Vector.toList Vector.fromList
{-# INLINE _Wrapped' #-}
instance (Prim a, t ~ Prim.Vector a') => Rewrapped (Prim.Vector a) t
instance Prim a => Wrapped (Prim.Vector a) where
type Unwrapped (Prim.Vector a) = [a]
_Wrapped' = iso Prim.toList Prim.fromList
{-# INLINE _Wrapped' #-}
instance (Unbox a, t ~ Unboxed.Vector a') => Rewrapped (Unboxed.Vector a) t
instance Unbox a => Wrapped (Unboxed.Vector a) where
type Unwrapped (Unboxed.Vector a) = [a]
_Wrapped' = iso Unboxed.toList Unboxed.fromList
{-# INLINE _Wrapped' #-}
instance (Storable a, t ~ Storable.Vector a') => Rewrapped (Storable.Vector a) t
instance Storable a => Wrapped (Storable.Vector a) where
type Unwrapped (Storable.Vector a) = [a]
_Wrapped' = iso Storable.toList Storable.fromList
{-# INLINE _Wrapped' #-}
-- * semigroups
instance (t ~ S.Min b) => Rewrapped (S.Min a) t
instance Wrapped (S.Min a) where
type Unwrapped (S.Min a) = a
_Wrapped' = iso S.getMin S.Min
{-# INLINE _Wrapped' #-}
instance (t ~ S.Max b) => Rewrapped (S.Max a) t
instance Wrapped (S.Max a) where
type Unwrapped (S.Max a) = a
_Wrapped' = iso S.getMax S.Max
{-# INLINE _Wrapped' #-}
instance (t ~ S.First b) => Rewrapped (S.First a) t
instance Wrapped (S.First a) where
type Unwrapped (S.First a) = a
_Wrapped' = iso S.getFirst S.First
{-# INLINE _Wrapped' #-}
instance (t ~ S.Last b) => Rewrapped (S.Last a) t
instance Wrapped (S.Last a) where
type Unwrapped (S.Last a) = a
_Wrapped' = iso S.getLast S.Last
{-# INLINE _Wrapped' #-}
instance (t ~ S.WrappedMonoid b) => Rewrapped (S.WrappedMonoid a) t
instance Wrapped (S.WrappedMonoid a) where
type Unwrapped (S.WrappedMonoid a) = a
_Wrapped' = iso S.unwrapMonoid S.WrapMonoid
{-# INLINE _Wrapped' #-}
instance (t ~ S.Option b) => Rewrapped (S.Option a) t
instance Wrapped (S.Option a) where
type Unwrapped (S.Option a) = Maybe a
_Wrapped' = iso S.getOption S.Option
{-# INLINE _Wrapped' #-}
-- * contravariant
instance (t ~ Predicate b) => Rewrapped (Predicate a) t
instance Wrapped (Predicate a) where
type Unwrapped (Predicate a) = a -> Bool
_Wrapped' = iso getPredicate Predicate
{-# INLINE _Wrapped' #-}
instance (t ~ Comparison b) => Rewrapped (Comparison a) t
instance Wrapped (Comparison a) where
type Unwrapped (Comparison a) = a -> a -> Ordering
_Wrapped' = iso getComparison Comparison
{-# INLINE _Wrapped' #-}
instance (t ~ Equivalence b) => Rewrapped (Equivalence a) t
instance Wrapped (Equivalence a) where
type Unwrapped (Equivalence a) = a -> a -> Bool
_Wrapped' = iso getEquivalence Equivalence
{-# INLINE _Wrapped' #-}
instance (t ~ Op a' b') => Rewrapped (Op a b) t
instance Wrapped (Op a b) where
type Unwrapped (Op a b) = b -> a
_Wrapped' = iso getOp Op
{-# INLINE _Wrapped' #-}
instance (t ~ Contravariant.Compose f' g' a') => Rewrapped (Contravariant.Compose f g a) t
instance Wrapped (Contravariant.Compose f g a) where
type Unwrapped (Contravariant.Compose f g a) = f (g a)
_Wrapped' = iso Contravariant.getCompose Contravariant.Compose
{-# INLINE _Wrapped' #-}
instance (t ~ Contravariant.ComposeFC f' g' a') => Rewrapped (Contravariant.ComposeFC f g a) t
instance Wrapped (Contravariant.ComposeFC f g a) where
type Unwrapped (Contravariant.ComposeFC f g a) = f (g a)
_Wrapped' = iso Contravariant.getComposeFC Contravariant.ComposeFC
{-# INLINE _Wrapped' #-}
instance (t ~ Contravariant.ComposeCF f' g' a') => Rewrapped (Contravariant.ComposeCF f g a) t
instance Wrapped (Contravariant.ComposeCF f g a) where
type Unwrapped (Contravariant.ComposeCF f g a) = f (g a)
_Wrapped' = iso Contravariant.getComposeCF Contravariant.ComposeCF
{-# INLINE _Wrapped' #-}
-- * tagged
instance (t ~ Tagged s' a') => Rewrapped (Tagged s a) t
instance Wrapped (Tagged s a) where
type Unwrapped (Tagged s a) = a
_Wrapped' = iso unTagged Tagged
{-# INLINE _Wrapped' #-}
-- * Control.Exception
instance (t ~ AssertionFailed) => Rewrapped AssertionFailed t
instance Wrapped AssertionFailed where
type Unwrapped AssertionFailed = String
_Wrapped' = iso failedAssertion AssertionFailed
{-# INLINE _Wrapped' #-}
instance (t ~ NoMethodError) => Rewrapped NoMethodError t
instance Wrapped NoMethodError where
type Unwrapped NoMethodError = String
_Wrapped' = iso getNoMethodError NoMethodError
{-# INLINE _Wrapped' #-}
instance (t ~ PatternMatchFail) => Rewrapped PatternMatchFail t
instance Wrapped PatternMatchFail where
type Unwrapped PatternMatchFail = String
_Wrapped' = iso getPatternMatchFail PatternMatchFail
{-# INLINE _Wrapped' #-}
instance (t ~ RecConError) => Rewrapped RecConError t
instance Wrapped RecConError where
type Unwrapped RecConError = String
_Wrapped' = iso getRecConError RecConError
{-# INLINE _Wrapped' #-}
instance (t ~ RecSelError) => Rewrapped RecSelError t
instance Wrapped RecSelError where
type Unwrapped RecSelError = String
_Wrapped' = iso getRecSelError RecSelError
{-# INLINE _Wrapped' #-}
instance (t ~ RecUpdError) => Rewrapped RecUpdError t
instance Wrapped RecUpdError where
type Unwrapped RecUpdError = String
_Wrapped' = iso getRecUpdError RecUpdError
{-# INLINE _Wrapped' #-}
instance (t ~ ErrorCall) => Rewrapped ErrorCall t
instance Wrapped ErrorCall where
type Unwrapped ErrorCall = String
_Wrapped' = iso getErrorCall ErrorCall
{-# INLINE _Wrapped' #-}
getErrorCall :: ErrorCall -> String
getErrorCall (ErrorCall x) = x
{-# INLINE getErrorCall #-}
getRecUpdError :: RecUpdError -> String
getRecUpdError (RecUpdError x) = x
{-# INLINE getRecUpdError #-}
getRecSelError :: RecSelError -> String
getRecSelError (RecSelError x) = x
{-# INLINE getRecSelError #-}
getRecConError :: RecConError -> String
getRecConError (RecConError x) = x
{-# INLINE getRecConError #-}
getPatternMatchFail :: PatternMatchFail -> String
getPatternMatchFail (PatternMatchFail x) = x
{-# INLINE getPatternMatchFail #-}
getNoMethodError :: NoMethodError -> String
getNoMethodError (NoMethodError x) = x
{-# INLINE getNoMethodError #-}
failedAssertion :: AssertionFailed -> String
failedAssertion (AssertionFailed x) = x
{-# INLINE failedAssertion #-}
getArrowMonad :: ArrowMonad m a -> m () a
getArrowMonad (ArrowMonad x) = x
{-# INLINE getArrowMonad #-}
-- | Given the constructor for a 'Wrapped' type, return a
-- deconstructor that is its inverse.
--
-- Assuming the 'Wrapped' instance is legal, these laws hold:
--
-- @
-- 'op' f '.' f ≡ 'id'
-- f '.' 'op' f ≡ 'id'
-- @
--
--
-- >>> op Identity (Identity 4)
-- 4
--
-- >>> op Const (Const "hello")
-- "hello"
op :: Wrapped s => (Unwrapped s -> s) -> s -> Unwrapped s
op _ = view _Wrapped'
{-# INLINE op #-}
-- | This is a convenient version of '_Wrapped' with an argument that's ignored.
--
-- The user supplied function is /ignored/, merely its type is used.
_Wrapping' :: Wrapped s => (Unwrapped s -> s) -> Iso' s (Unwrapped s)
_Wrapping' _ = _Wrapped'
{-# INLINE _Wrapping' #-}
-- | This is a convenient version of '_Wrapped' with an argument that's ignored.
--
-- The user supplied function is /ignored/, merely its type is used.
_Unwrapping' :: Wrapped s => (Unwrapped s -> s) -> Iso' (Unwrapped s) s
_Unwrapping' _ = from _Wrapped'
{-# INLINE _Unwrapping' #-}
-- | This is a convenient version of '_Wrapped' with an argument that's ignored.
--
-- The user supplied function is /ignored/, merely its types are used.
_Wrapping :: Rewrapping s t => (Unwrapped s -> s) -> Iso s t (Unwrapped s) (Unwrapped t)
_Wrapping _ = _Wrapped
{-# INLINE _Wrapping #-}
-- | This is a convenient version of '_Unwrapped' with an argument that's ignored.
--
-- The user supplied function is /ignored/, merely its types are used.
_Unwrapping :: Rewrapping s t => (Unwrapped s -> s) -> Iso (Unwrapped t) (Unwrapped s) t s
_Unwrapping _ = from _Wrapped
{-# INLINE _Unwrapping #-}
-- | This combinator is based on @ala@ from Conor McBride's work on Epigram.
--
-- As with '_Wrapping', the user supplied function for the newtype is /ignored/.
--
-- >>> ala Sum foldMap [1,2,3,4]
-- 10
--
-- >>> ala All foldMap [True,True]
-- True
--
-- >>> ala All foldMap [True,False]
-- False
--
-- >>> ala Any foldMap [False,False]
-- False
--
-- >>> ala Any foldMap [True,False]
-- True
--
-- >>> ala Sum foldMap [1,2,3,4]
-- 10
--
-- >>> ala Product foldMap [1,2,3,4]
-- 24
--
--
-- You may want to think of this combinator as having the following, simpler, type.
--
-- @
-- ala :: Rewrapping s t => (Unwrapped s -> s) -> ((Unwrapped t -> t) -> e -> s) -> e -> Unwrapped s
-- @
ala :: (Functor f, Rewrapping s t) => (Unwrapped s -> s) -> ((Unwrapped t -> t) -> f s) -> f (Unwrapped s)
ala = au . _Wrapping
{-# INLINE ala #-}
-- | This combinator is based on @ala'@ from Conor McBride's work on Epigram.
--
-- As with '_Wrapping', the user supplied function for the newtype is /ignored/.
--
-- @
-- alaf :: Rewrapping s t => (Unwrapped s -> s) -> ((r -> t) -> e -> s) -> (r -> Unwrapped t) -> e -> Unwrapped s
-- @
--
-- >>> alaf Sum foldMap Prelude.length ["hello","world"]
-- 10
alaf :: (Functor f, Functor g, Rewrapping s t) => (Unwrapped s -> s) -> (f t -> g s) -> f (Unwrapped t) -> g (Unwrapped s)
alaf = auf . _Unwrapping
{-# INLINE alaf #-}
|
omefire/lens
|
src/Control/Lens/Wrapped.hs
|
bsd-3-clause
| 24,672 | 0 | 12 | 4,832 | 7,196 | 3,820 | 3,376 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Text.Pandoc.Lordown
( module Text.Pandoc.Writers.Lorcode
, markdownOptions
, markdownExtensions
, toLorcode
, fromMarkdown
, convert
)
where
import Text.Pandoc
import Text.Pandoc.Walk
import Text.Pandoc.Writers.Lorcode
import qualified Data.Set as S
-- | Converts from Markdown to Pandoc
fromMarkdown :: String -> Pandoc
fromMarkdown = either (error . show) id . readCommonMark markdownOptions
-- | Markdown reader options
markdownOptions :: ReaderOptions
markdownOptions = def { readerSmart = True
, readerExtensions = markdownExtensions }
-- | Markdown reader extensions
markdownExtensions :: S.Set Extension
markdownExtensions = S.fromList
[Ext_backtick_code_blocks
,Ext_strikeout
,Ext_fancy_lists]
-- | Converts from Pandoc to Lorcode
toLorcode :: Pandoc -> String
toLorcode = writeLorcode def
-- | Replaces headers with strong text
behead :: Block -> Block
behead (Header _ _ xs) = Para [Strong xs]
behead x = x
-- | StackOverflow-like user casts
handleCast :: Inline -> Inline
handleCast (Str ('@' : user)) = Str $ "[user]" ++ user ++ "[/user]"
handleCast x = x
-- | Converts text from Markdown to Lorcode
convert :: String -> String
convert = toLorcode . (walk handleCast) . (walk behead) . fromMarkdown
|
smaximov/lordown
|
src/Text/Pandoc/Lordown.hs
|
bsd-3-clause
| 1,361 | 0 | 9 | 289 | 301 | 173 | 128 | 32 | 1 |
{-# LANGUAGE GADTs, NoMonomorphismRestriction, ScopedTypeVariables #-}
------------------------------
-- | special actor for IO action
------------------------------
module Control.Monad.Trans.Crtn.IOActor where
import Control.Monad.Reader
--
import Control.Monad.Trans.Crtn
-- import Control.Monad.Trans.Crtn.Event
import Control.Monad.Trans.Crtn.Object
-- | first is
data IOOp e i o where
DoIOAction :: IOOp e ((e -> IO ()) -> IO ()) (Either String ())
type IOActor e m r = SObjT (IOOp e) m r
-- |
doIOAction :: (Monad m) => ((e -> IO ()) -> IO ())
-> CObjT (IOOp e) m (Either String ())
doIOAction act = do ans <- request (Arg DoIOAction act)
case ans of
Res DoIOAction r -> return r
Ign -> return (Left "error in doing doIOAction")
-- |
ioactorgen :: (MonadIO m) => (e -> IO ()) -> SObjT (IOOp e) m ()
ioactorgen evhandler = ReaderT ioactorW
where ioactorW (Arg DoIOAction act) = do
liftIO (act evhandler)
req <- request (Res DoIOAction (Right ()))
ioactorW req
|
wavewave/coroutine-object
|
src/Control/Monad/Trans/Crtn/IOActor.hs
|
bsd-3-clause
| 1,103 | 0 | 15 | 290 | 359 | 190 | 169 | 20 | 2 |
{-# 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.CodeCommit.CreateBranch
-- 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)
--
-- Creates a new branch in a repository and points the branch to a commit.
--
-- Calling the create branch operation does not set a repository\'s default
-- branch. To do this, call the update default branch operation.
--
-- /See:/ <http://docs.aws.amazon.com/codecommit/latest/APIReference/API_CreateBranch.html AWS API Reference> for CreateBranch.
module Network.AWS.CodeCommit.CreateBranch
(
-- * Creating a Request
createBranch
, CreateBranch
-- * Request Lenses
, cbRepositoryName
, cbBranchName
, cbCommitId
-- * Destructuring the Response
, createBranchResponse
, CreateBranchResponse
) where
import Network.AWS.CodeCommit.Types
import Network.AWS.CodeCommit.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Represents the input of a create branch operation.
--
-- /See:/ 'createBranch' smart constructor.
data CreateBranch = CreateBranch'
{ _cbRepositoryName :: !Text
, _cbBranchName :: !Text
, _cbCommitId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateBranch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cbRepositoryName'
--
-- * 'cbBranchName'
--
-- * 'cbCommitId'
createBranch
:: Text -- ^ 'cbRepositoryName'
-> Text -- ^ 'cbBranchName'
-> Text -- ^ 'cbCommitId'
-> CreateBranch
createBranch pRepositoryName_ pBranchName_ pCommitId_ =
CreateBranch'
{ _cbRepositoryName = pRepositoryName_
, _cbBranchName = pBranchName_
, _cbCommitId = pCommitId_
}
-- | The name of the repository in which you want to create the new branch.
cbRepositoryName :: Lens' CreateBranch Text
cbRepositoryName = lens _cbRepositoryName (\ s a -> s{_cbRepositoryName = a});
-- | The name of the new branch to create.
cbBranchName :: Lens' CreateBranch Text
cbBranchName = lens _cbBranchName (\ s a -> s{_cbBranchName = a});
-- | The ID of the commit to point the new branch to.
--
-- If this commit ID is not specified, the new branch will point to the
-- commit that is pointed to by the repository\'s default branch.
cbCommitId :: Lens' CreateBranch Text
cbCommitId = lens _cbCommitId (\ s a -> s{_cbCommitId = a});
instance AWSRequest CreateBranch where
type Rs CreateBranch = CreateBranchResponse
request = postJSON codeCommit
response = receiveNull CreateBranchResponse'
instance ToHeaders CreateBranch where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("CodeCommit_20150413.CreateBranch" :: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON CreateBranch where
toJSON CreateBranch'{..}
= object
(catMaybes
[Just ("repositoryName" .= _cbRepositoryName),
Just ("branchName" .= _cbBranchName),
Just ("commitId" .= _cbCommitId)])
instance ToPath CreateBranch where
toPath = const "/"
instance ToQuery CreateBranch where
toQuery = const mempty
-- | /See:/ 'createBranchResponse' smart constructor.
data CreateBranchResponse =
CreateBranchResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateBranchResponse' with the minimum fields required to make a request.
--
createBranchResponse
:: CreateBranchResponse
createBranchResponse = CreateBranchResponse'
|
fmapfmapfmap/amazonka
|
amazonka-codecommit/gen/Network/AWS/CodeCommit/CreateBranch.hs
|
mpl-2.0
| 4,294 | 0 | 12 | 959 | 564 | 339 | 225 | 78 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-cse #-}
{-@ LIQUID "--cabaldir" @-}
{-@ LIQUID "--diff" @-}
-- | This module contains all the code needed to output the result which
-- is either: `SAFE` or `WARNING` with some reasonable error message when
-- something goes wrong. All forms of errors/exceptions should go through
-- here. The idea should be to report the error, the source position that
-- causes it, generate a suitable .json file and then exit.
module Language.Haskell.Liquid.CmdLine (
-- * Get Command Line Configuration
getOpts, mkOpts
-- * Update Configuration With Pragma
, withPragmas
, withCabal
-- * Exit Function
, exitWithResult
-- * Diff check mode
, diffcheck
) where
import Control.Applicative ((<$>))
import Control.Monad
import Data.Maybe
import System.Directory
import System.Exit
import System.Environment
import System.Console.CmdArgs.Explicit
import System.Console.CmdArgs.Implicit hiding (Loud)
import System.Console.CmdArgs.Text
import Data.List (intercalate, nub)
import Data.Monoid
import System.FilePath (dropFileName, isAbsolute,
takeDirectory, (</>))
import Language.Fixpoint.Config hiding (Config, real, native, getOpts)
import Language.Fixpoint.Files
import Language.Fixpoint.Misc
import Language.Fixpoint.Names (dropModuleNames)
import Language.Fixpoint.Types hiding (Result)
import Language.Haskell.Liquid.Annotate
import Language.Haskell.Liquid.GhcMisc
import Language.Haskell.Liquid.Misc
import Language.Haskell.Liquid.PrettyPrint
import Language.Haskell.Liquid.Types hiding (config, name, typ)
import Language.Haskell.Liquid.Errors
import Language.Haskell.Liquid.Cabal
import Text.Parsec.Pos (newPos)
import Text.PrettyPrint.HughesPJ hiding (Mode)
---------------------------------------------------------------------------------
-- Parsing Command Line----------------------------------------------------------
---------------------------------------------------------------------------------
config = cmdArgsMode $ Config {
files
= def &= typ "TARGET"
&= args
&= typFile
, idirs
= def &= typDir
&= help "Paths to Spec Include Directory "
, fullcheck
= def
&= help "Full Checking: check all binders (DEFAULT)"
, diffcheck
= def
&= help "Incremental Checking: only check changed binders"
, real
= def
&= help "Supports real number arithmetic"
, native
= def &= help "Use native (Haskell) fixpoint constraint solver"
, binders
= def &= help "Check a specific set of binders"
, noPrune
= def &= help "Disable prunning unsorted Predicates"
&= name "no-prune-unsorted"
, notermination
= def &= help "Disable Termination Check"
&= name "no-termination-check"
, nowarnings
= def &= help "Don't display warnings, only show errors"
&= name "no-warnings"
, trustinternals
= def &= help "Trust all ghc auto generated code"
&= name "trust-interals"
, nocaseexpand
= def &= help "Disable Termination Check"
&= name "no-case-expand"
, strata
= def &= help "Enable Strata Analysis"
, notruetypes
= def &= help "Disable Trueing Top Level Types"
&= name "no-true-types"
, totality
= def &= help "Check totality"
, smtsolver
= def &= help "Name of SMT-Solver"
, noCheckUnknown
= def &= explicit
&= name "no-check-unknown"
&= help "Don't complain about specifications for unexported and unused values "
, maxParams
= 2 &= help "Restrict qualifier mining to those taking at most `m' parameters (2 by default)"
, shortNames
= def &= name "short-names"
&= help "Print shortened names, i.e. drop all module qualifiers."
, shortErrors
= def &= name "short-errors"
&= help "Don't show long error messages, just line numbers."
, cabalDir
= def &= name "cabal-dir"
&= help "Find and use .cabal to add paths to sources for imported files"
, ghcOptions
= def &= name "ghc-option"
&= typ "OPTION"
&= help "Pass this option to GHC"
, cFiles
= def &= name "c-files"
&= typ "OPTION"
&= help "Tell GHC to compile and link against these files"
} &= verbosity
&= program "liquid"
&= help "Refinement Types for Haskell"
&= summary copyright
&= details [ "LiquidHaskell is a Refinement Type based verifier for Haskell"
, ""
, "To check a Haskell file foo.hs, type:"
, " liquid foo.hs "
]
getOpts :: IO Config
getOpts = do
cfg0 <- envCfg
cfg1 <- mkOpts =<< cmdArgsRun' config
cfg <- fixConfig $ mconcat [cfg0, cfg1]
whenNormal $ putStrLn copyright
case smtsolver cfg of
Just _ -> return cfg
Nothing -> do smts <- mapM findSmtSolver [Z3, Cvc4, Mathsat]
case catMaybes smts of
(s:_) -> return (cfg {smtsolver = Just s})
_ -> exitWithPanic noSmtError
where
noSmtError = "LiquidHaskell requires an SMT Solver, i.e. z3, cvc4, or mathsat to be installed."
cmdArgsRun' :: Mode (CmdArgs a) -> IO a
cmdArgsRun' mode
= do parseResult <- process mode <$> getArgs
case parseResult of
Left err ->
putStrLn (help err) >> exitFailure
Right args ->
cmdArgsApply args
where
help err = showText defaultWrap $ helpText [err] HelpFormatDefault mode
findSmtSolver :: SMTSolver -> IO (Maybe SMTSolver)
findSmtSolver smt = maybe Nothing (const $ Just smt) <$> findExecutable (show smt)
fixConfig :: Config -> IO Config
fixConfig cfg = do
pwd <- getCurrentDirectory
cfg <- canonicalizePaths pwd cfg
-- cfg <- withCabal cfg
return $ fixDiffCheck cfg
-- | Attempt to canonicalize all `FilePath's in the `Config' so we don't have
-- to worry about relative paths.
canonicalizePaths :: FilePath -> Config -> IO Config
canonicalizePaths pwd cfg = do
tgt <- canonicalizePath pwd
isdir <- doesDirectoryExist tgt
is <- mapM (canonicalize tgt isdir) $ idirs cfg
cs <- mapM (canonicalize tgt isdir) $ cFiles cfg
return $ cfg { idirs = is, cFiles = cs }
canonicalize :: FilePath -> Bool -> FilePath -> IO FilePath
canonicalize tgt isdir f
| isAbsolute f = return f
| isdir = canonicalizePath (tgt </> f)
| otherwise = canonicalizePath (takeDirectory tgt </> f)
fixDiffCheck :: Config -> Config
fixDiffCheck cfg = cfg { diffcheck = diffcheck cfg && not (fullcheck cfg) }
envCfg = do so <- lookupEnv "LIQUIDHASKELL_OPTS"
case so of
Nothing -> return mempty
Just s -> parsePragma $ envLoc s
where
envLoc = Loc l l
l = newPos "ENVIRONMENT" 0 0
copyright = "LiquidHaskell Copyright 2009-15 Regents of the University of California. All Rights Reserved.\n"
mkOpts :: Config -> IO Config
mkOpts cfg
= do let files' = sortNub $ files cfg
id0 <- getIncludeDir
return $ cfg { files = files' }
{ idirs = (dropFileName <$> files') ++ [id0 </> gHC_VERSION, id0] ++ idirs cfg }
-- tests fail if you flip order of idirs'
---------------------------------------------------------------------------------------
-- | Updating options
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
withPragmas :: Config -> FilePath -> [Located String] -> IO Config
---------------------------------------------------------------------------------------
withPragmas cfg fp ps = foldM withPragma cfg ps >>= canonicalizePaths fp
withPragma :: Config -> Located String -> IO Config
withPragma c s = (c `mappend`) <$> parsePragma s
parsePragma :: Located String -> IO Config
parsePragma s = withArgs [val s] $ cmdArgsRun config
---------------------------------------------------------------------------------------
withCabal :: Config -> IO Config
---------------------------------------------------------------------------------------
withCabal cfg
| cabalDir cfg = withCabal' cfg
| otherwise = return cfg
withCabal' cfg = do
whenLoud $ putStrLn $ "addCabalDirs: " ++ tgt
io <- cabalInfo tgt
case io of
Just i -> return $ fixCabalDirs' cfg i
Nothing -> exitWithPanic "Cannot find .cabal information!"
where
tgt = case files cfg of
f:_ -> f
_ -> exitWithPanic "Please provide a target file to verify."
fixCabalDirs' :: Config -> Info -> Config
fixCabalDirs' cfg i = cfg { idirs = nub $ idirs cfg ++ sourceDirs i ++ buildDirs i }
{ ghcOptions = ghcOptions cfg ++ dbOpts ++ pkOpts
++ ["-optP-include", "-optP" ++ macroPath i]}
where
dbOpts = ["-package-db " ++ db | db <- packageDbs i]
pkOpts = ["-package " ++ n | n <- packageDeps i] -- SPEED HIT for smaller benchmarks
---------------------------------------------------------------------------------------
-- | Monoid instances for updating options
---------------------------------------------------------------------------------------
instance Monoid Config where
mempty = Config def def def def def def def def def def def def def def def def 2 def def def def def def
mappend c1 c2 = Config { files = sortNub $ files c1 ++ files c2
, idirs = sortNub $ idirs c1 ++ idirs c2
, fullcheck = fullcheck c1 || fullcheck c2
, real = real c1 || real c2
, diffcheck = diffcheck c1 || diffcheck c2
, native = native c1 || native c2
, binders = sortNub $ binders c1 ++ binders c2
, noCheckUnknown = noCheckUnknown c1 || noCheckUnknown c2
, notermination = notermination c1 || notermination c2
, nowarnings = nowarnings c1 || nowarnings c2
, trustinternals = trustinternals c1 || trustinternals c2
, nocaseexpand = nocaseexpand c1 || nocaseexpand c2
, strata = strata c1 || strata c2
, notruetypes = notruetypes c1 || notruetypes c2
, totality = totality c1 || totality c2
, noPrune = noPrune c1 || noPrune c2
, maxParams = maxParams c1 `max` maxParams c2
, smtsolver = smtsolver c1 `mappend` smtsolver c2
, shortNames = shortNames c1 || shortNames c2
, shortErrors = shortErrors c1 || shortErrors c2
, cabalDir = cabalDir c1 || cabalDir c2
, ghcOptions = ghcOptions c1 ++ ghcOptions c2
, cFiles = cFiles c1 ++ cFiles c2
}
instance Monoid SMTSolver where
mempty = def
mappend s1 s2
| s1 == s2 = s1
| s2 == def = s1
| otherwise = s2
------------------------------------------------------------------------
-- | Exit Function -----------------------------------------------------
------------------------------------------------------------------------
------------------------------------------------------------------------
exitWithResult :: Config -> FilePath -> Output Doc -> IO (Output Doc)
------------------------------------------------------------------------
exitWithResult cfg target out
= do {-# SCC "annotate" #-} annotate cfg target out
donePhase Loud "annotate"
writeCheckVars $ o_vars out
writeResult cfg (colorResult r) r
writeFile (extFileName Result target) (showFix r)
return $ out { o_result = r }
where
r = o_result out `addErrors` o_errors out
writeCheckVars Nothing = return ()
writeCheckVars (Just []) = colorPhaseLn Loud "Checked Binders: None" ""
writeCheckVars (Just ns) = colorPhaseLn Loud "Checked Binders:" "" >> forM_ ns (putStrLn . symbolString . dropModuleNames . symbol)
writeResult cfg c = mapM_ (writeDoc c) . zip [0..] . resDocs tidy
where
tidy = if shortErrors cfg then Lossy else Full
writeDoc c (i, d) = writeBlock c i $ lines $ render d
writeBlock _ _ [] = return ()
writeBlock c 0 ss = forM_ ss (colorPhaseLn c "")
writeBlock _ _ ss = forM_ ("\n" : ss) putStrLn
resDocs _ Safe = [text "SAFE"]
resDocs k (Crash xs s) = text ("ERROR: " ++ s) : pprManyOrdered k "" (errToFCrash <$> xs)
resDocs k (Unsafe xs) = text "UNSAFE" : pprManyOrdered k "" (nub xs)
resDocs _ (UnknownError d) = [text $ "PANIC: Unexpected Error: " ++ d, reportUrl]
reportUrl = text "Please submit a bug report at: https://github.com/ucsd-progsys/liquidhaskell"
addErrors r [] = r
addErrors Safe errs = Unsafe errs
addErrors (Unsafe xs) errs = Unsafe (xs ++ errs)
addErrors r _ = r
instance Fixpoint (FixResult Error) where
toFix = vcat . resDocs Full
|
mightymoose/liquidhaskell
|
src/Language/Haskell/Liquid/CmdLine.hs
|
bsd-3-clause
| 14,075 | 0 | 19 | 4,259 | 3,092 | 1,588 | 1,504 | 256 | 4 |
{-# OPTIONS_GHC -Wall #-}
module Optimize.DecisionTree where
{- To learn more about how this works, definitely read through:
"When Do Match-Compilation Heuristics Matter?"
by Kevin Scott and Norman Ramsey. The rough idea is that we start with a simple
list of patterns and expressions, and then turn that into a "decision tree"
that requires as few tests as possible to make it to a leaf. Read the paper, it
explains this extraordinarily well! We are currently using the same heuristics
as SML/NJ to get nice trees.
-}
import Control.Arrow (second)
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Maybe as Maybe
import qualified AST.Helpers as Help
import qualified AST.Literal as L
import qualified AST.Pattern as P
import qualified AST.Variable as Var
import qualified Reporting.Annotation as A
type CPattern = P.Canonical
-- COMPILE CASES
{-| Users of this module will mainly interact with this function. It takes
some normal branches and gives out a decision tree that has "labels" at all
the leafs and a dictionary that maps these "labels" to the code that should
run.
If 2 or more leaves point to the same label, we need to do some tricks in JS to
make that work nicely. When is JS getting goto?! ;) That is outside the scope
of this module though.
-}
compile :: VariantDict -> [(CPattern, Int)] -> DecisionTree
compile variantDict rawBranches =
let
format (pattern, index) =
Branch index [(Empty, pattern)]
in
toDecisionTree variantDict (map format rawBranches)
{-| When a certain union type is defined, you specify a certain number of tags.
This helps us do a few optimizations:
* If there is only one possible tag, we can always skip checking what it is.
Tuples are a common example of this.
* If we use all possible tags, we can skip doing the last test. If we have
checked N-1 of N tags, there is no need to test the Nth, we know its the
one we want
So this dictionary maps tags to the number of variants that exist, so it'll
contain things like [ ("Just", 2), ("Nothing", 2), ("_Tuple2", 1), ... ] which
we can use for these optimizations.
-}
type VariantDict =
Map.Map Var.Home (Map.Map String Int)
-- DECISION TREES
data DecisionTree
= Match Int
| Decision
{ _test :: Path
, _edges :: [(Test, DecisionTree)]
, _default :: Maybe DecisionTree
}
deriving (Eq)
data Test
= Constructor Var.Canonical
| Literal L.Literal
deriving (Eq, Ord)
data Path
= Position Int Path
| Field String Path
| Empty
| Alias
deriving (Eq)
-- PATH HELPERS
add :: Path -> Path -> Path
add path finalLink =
case path of
Empty ->
finalLink
Alias ->
error "nothing should be added to an alias path"
Position index subpath ->
Position index (add subpath finalLink)
Field name subpath ->
Field name (add subpath finalLink)
subPositions :: Path -> [CPattern] -> [(Path, CPattern)]
subPositions path patterns =
zipWith
(\index pattern -> (add path (Position index Empty), pattern))
[0..]
patterns
-- ACTUALLY BUILD DECISION TREES
data Branch =
Branch
{ _goal :: Int
, _patterns :: [(Path, CPattern)]
}
toDecisionTree :: VariantDict -> [Branch] -> DecisionTree
toDecisionTree variantDict rawBranches =
let
branches =
map (flattenPatterns variantDict) rawBranches
in
case checkForMatch branches of
Just goal ->
Match goal
Nothing ->
let
path =
pickPath variantDict branches
(edges, fallback) =
gatherEdges variantDict branches path
decisionEdges =
map (second (toDecisionTree variantDict)) edges
in
case (decisionEdges, fallback) of
([(_tag, decisionTree)], []) ->
decisionTree
(_, []) ->
Decision path decisionEdges Nothing
([], _ : _) ->
toDecisionTree variantDict fallback
(_, _) ->
Decision path decisionEdges (Just (toDecisionTree variantDict fallback))
isComplete :: VariantDict -> [Test] -> Bool
isComplete variantDict tests =
case head tests of
Constructor var ->
getArity variantDict var == length tests
Literal (L.Boolean _) ->
length tests == 2
_ ->
False
getArity :: VariantDict -> Var.Canonical -> Int
getArity variantDict (Var.Canonical home name) =
case Map.lookup name =<< Map.lookup home variantDict of
Just arity ->
arity
Nothing ->
if Help.isTuple name then
read (drop 6 name)
else
error
"Since the Optimize phase happens after canonicalization and type \
\inference, it is impossible that a pattern cannot be found."
-- FLATTEN PATTERNS
{-| Flatten type aliases and use the VariantDict to figure out when a tag is
the only variant so we can skip doing any tests on it.
-}
flattenPatterns :: VariantDict -> Branch -> Branch
flattenPatterns variantDict (Branch goal pathPatterns) =
Branch goal (concatMap (flatten variantDict) pathPatterns)
flatten :: VariantDict -> (Path, CPattern) -> [(Path, CPattern)]
flatten variantDict pathPattern@(path, A.A ann pattern) =
case pattern of
P.Var _ ->
[pathPattern]
P.Anything ->
[pathPattern]
P.Alias alias realPattern ->
(add path Alias, A.A ann (P.Var alias))
:
flatten variantDict (path, realPattern)
P.Record _ ->
[pathPattern]
P.Data tag patterns ->
if getArity variantDict tag == 1 then
concatMap (flatten variantDict) (subPositions path patterns)
else
[pathPattern]
P.Literal _ ->
[pathPattern]
-- SUCCESSFULLY MATCH
{-| If the first branch has no more "decision points" we can finally take that
path. If that is the case we give the resulting label and a mapping from free
variables to "how to get their value". So a pattern like (Just (x,_)) will give
us something like ("x" => value.0.0)
-}
checkForMatch :: [Branch] -> Maybe Int
checkForMatch branches =
case branches of
Branch goal patterns : _ | all (not . needsTests . snd) patterns ->
Just goal
_ ->
Nothing
-- GATHER OUTGOING EDGES
gatherEdges :: VariantDict -> [Branch] -> Path -> ([(Test, [Branch])], [Branch])
gatherEdges variantDict branches path =
let
relevantTests =
testsAtPath path branches
allEdges =
map (edgesFor path branches) relevantTests
fallbacks =
if isComplete variantDict relevantTests then
[]
else
filter (isIrrelevantTo path) branches
in
( allEdges, fallbacks )
-- FIND RELEVANT TESTS
testsAtPath :: Path -> [Branch] -> [Test]
testsAtPath selectedPath branches =
let
allTests =
Maybe.mapMaybe (testAtPath selectedPath) branches
skipVisited test curr@(uniqueTests, visitedTests) =
if Set.member test visitedTests then
curr
else
( test : uniqueTests
, Set.insert test visitedTests
)
in
fst (foldr skipVisited ([], Set.empty) allTests)
testAtPath :: Path -> Branch -> Maybe Test
testAtPath selectedPath (Branch _ pathPatterns) =
case List.lookup selectedPath pathPatterns of
Nothing ->
Nothing
Just (A.A _ pattern) ->
case pattern of
P.Data name _ ->
Just (Constructor name)
P.Literal lit ->
Just (Literal lit)
P.Var _ ->
Nothing
P.Alias _ _ ->
error "aliases should never reach 'testAtPath' function"
P.Anything ->
Nothing
P.Record _ ->
Nothing
-- BUILD EDGES
edgesFor :: Path -> [Branch] -> Test -> (Test, [Branch])
edgesFor path branches test =
( test
, Maybe.mapMaybe (toRelevantBranch test path) branches
)
toRelevantBranch :: Test -> Path -> Branch -> Maybe Branch
toRelevantBranch test path branch@(Branch goal pathPatterns) =
case extract path pathPatterns of
Just (start, A.A _ pattern, end) ->
case pattern of
P.Data name patterns ->
if test == Constructor name then
Just (Branch goal (start ++ subPositions path patterns ++ end))
else
Nothing
P.Literal lit ->
if test == Literal lit then
Just (Branch goal (start ++ end))
else
Nothing
_ ->
Just branch
_ ->
Just branch
extract
:: Path
-> [(Path, CPattern)]
-> Maybe ([(Path, CPattern)], CPattern, [(Path, CPattern)])
extract selectedPath pathPatterns =
case pathPatterns of
[] ->
Nothing
first@(path, pattern) : rest ->
if path == selectedPath then
Just ([], pattern, rest)
else
case extract selectedPath rest of
Nothing ->
Nothing
Just (start, foundPattern, end) ->
Just (first : start, foundPattern, end)
-- FIND IRRELEVANT BRANCHES
isIrrelevantTo :: Path -> Branch -> Bool
isIrrelevantTo selectedPath (Branch _ pathPatterns) =
case List.lookup selectedPath pathPatterns of
Nothing ->
True
Just pattern ->
not (needsTests pattern)
needsTests :: CPattern -> Bool
needsTests (A.A _ pattern) =
case pattern of
P.Var _ ->
False
P.Anything ->
False
P.Alias _ _ ->
error "aliases should never reach 'isIrrelevantTo' function"
P.Record _ ->
False
P.Data _ _ ->
True
P.Literal _ ->
True
-- PICK A PATH
pickPath :: VariantDict -> [Branch] -> Path
pickPath variantDict branches =
let
allPaths =
Maybe.mapMaybe isChoicePath (concatMap _patterns branches)
in
case bests (addWeights (smallDefaults branches) allPaths) of
[path] ->
path
tiedPaths ->
head (bests (addWeights (smallBranchingFactor variantDict branches) tiedPaths))
isChoicePath :: (Path, CPattern) -> Maybe Path
isChoicePath (path, pattern) =
if needsTests pattern then
Just path
else
Nothing
addWeights :: (Path -> Int) -> [Path] -> [(Path, Int)]
addWeights toWeight paths =
map (\path -> (path, toWeight path)) paths
bests :: [(Path, Int)] -> [Path]
bests allPaths =
case allPaths of
[] ->
error "Cannot choose the best of zero paths. This should never happen."
(headPath, headWeight) : weightedPaths ->
let
gatherMinimum acc@(minWeight, paths) (path, weight) =
if weight == minWeight then
(minWeight, path : paths)
else if weight < minWeight then
(weight, [path])
else
acc
in
snd (List.foldl' gatherMinimum (headWeight, [headPath]) weightedPaths)
-- PATH PICKING HEURISTICS
smallDefaults :: [Branch] -> Path -> Int
smallDefaults branches path =
length (filter (isIrrelevantTo path) branches)
smallBranchingFactor :: VariantDict -> [Branch] -> Path -> Int
smallBranchingFactor variantDict branches path =
let
(edges, fallback) =
gatherEdges variantDict branches path
in
length edges + (if null fallback then 0 else 1)
|
mgold/Elm
|
src/Optimize/DecisionTree.hs
|
bsd-3-clause
| 11,433 | 0 | 19 | 3,311 | 2,794 | 1,478 | 1,316 | 274 | 7 |
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Layout.Tree
-- Copyright : (c) 2011 Brent Yorgey
-- License : BSD-style (see LICENSE)
-- Maintainer : [email protected]
--
-- A collection of methods for laying out various kinds of trees.
-- This module is still experimental, and more layout methods will
-- probably be added over time.
--
-- Laying out a rose tree using a symmetric layout:
--
-- > import Data.Tree
-- > import Diagrams.TwoD.Layout.Tree
-- >
-- > t1 = Node 'A' [Node 'B' (map lf "CDE"), Node 'F' [Node 'G' (map lf "HIJ")]]
-- > where lf x = Node x []
-- >
-- > exampleSymmTree =
-- > renderTree ((<> circle 1 # fc white) . text . (:[]))
-- > (~~)
-- > (symmLayout' (with & slHSep .~ 4 & slVSep .~ 4) t1)
-- > # centerXY # pad 1.1
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Tree_exampleSymmTree.svg#diagram=exampleSymmTree&width=300>>
--
-- Laying out a rose tree of diagrams, with spacing automatically
-- adjusted for the size of the diagrams:
--
-- > import Data.Tree
-- > import Data.Maybe (fromMaybe)
-- > import Diagrams.TwoD.Layout.Tree
-- >
-- > tD = Node (rect 1 3)
-- > [ Node (circle 0.2) []
-- > , Node (hcat . replicate 3 $ circle 1) []
-- > , Node (eqTriangle 5) []
-- > ]
-- >
-- > exampleSymmTreeWithDs =
-- > renderTree id (~~)
-- > (symmLayout' (with & slWidth .~ fromMaybe (0,0) . extentX
-- > & slHeight .~ fromMaybe (0,0) . extentY)
-- > tD)
-- > # centerXY # pad 1.1
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Tree_exampleSymmTreeWithDs.svg#diagram=exampleSymmTreeWithDs&width=300>>
--
-- Using a variant symmetric layout algorithm specifically for binary trees:
--
-- > import Diagrams.TwoD.Layout.Tree
-- >
-- > drawT = maybe mempty (renderTree (const (circle 0.05 # fc black)) (~~))
-- > . symmLayoutBin' (with & slVSep .~ 0.5)
-- >
-- > tree500 = drawT t # centerXY # pad 1.1
-- > where t = genTree 500 0.05
-- > -- genTree 500 0.05 randomly generates trees of size 500 +/- 5%,
-- > -- definition not shown
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Tree_tree500.svg#diagram=tree500&width=400>>
--
-- Using force-based layout on a binary tree:
--
-- > {-# LANGUAGE NoMonomorphismRestriction #-}
-- > import Diagrams.Prelude
-- > import Diagrams.TwoD.Layout.Tree
-- >
-- > t 0 = Empty
-- > t n = BNode n (t (n-1)) (t (n-1))
-- >
-- > Just t' = uniqueXLayout 1 1 (t 4)
-- >
-- > fblEx = renderTree (\n -> (text (show n) # fontSizeL 0.5
-- > <> circle 0.3 # fc white))
-- > (~~)
-- > (forceLayoutTree t')
-- > # centerXY # pad 1.1
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Tree_fblEx.svg#diagram=fblEx&width=300>>
--
-- > import Diagrams.Prelude
-- > import Diagrams.TwoD.Layout.Tree
-- > import Data.Tree
-- >
-- > t = Node 'A' [Node 'B' [], Node 'C'[], Node 'D'[], Node 'E'[], Node 'F'[], Node 'G'[], Node 'H'[], Node 'I'[] ]
-- >
-- > example =
-- > renderTree (\n -> (text (show n) # fontSizeG 0.5
-- > <> circle 0.5 # fc white))
-- > (~~) (radialLayout t)
-- > # centerXY # pad 1.1
--
--
module Diagrams.TwoD.Layout.Tree
( -- * Binary trees
-- $BTree
BTree(..)
, leaf
-- * Layout algorithms
-- ** Unique-x layout
, uniqueXLayout
-- ** Radial-Layout
, radialLayout
-- ** Symmetric layout
-- $symmetric
, symmLayout
, symmLayout'
, symmLayoutBin
, symmLayoutBin'
, SymmLayoutOpts(..), slHSep, slVSep, slWidth, slHeight
-- ** Force-directed layout
-- $forcedirected
, forceLayoutTree
, forceLayoutTree'
, ForceLayoutTreeOpts(..), forceLayoutOpts, edgeLen, springK, staticK
, treeToEnsemble
, label
, reconstruct
-- * Rendering
, renderTree
, renderTree'
) where
import Physics.ForceLayout
import Control.Arrow (first, second, (&&&), (***))
import Control.Monad.State
import Data.Default
import qualified Data.Foldable as F
import Data.Function (on)
import Data.List (mapAccumL)
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Traversable as T
import Data.Tree
import Diagrams.Prelude
import Diagrams.TwoD.Vector()
import Diagrams.TwoD.Transform()
import Diagrams.TwoD.Types()
------------------------------------------------------------
-- Binary trees
------------------------------------------------------------
-- $BTree
-- There is a standard type of rose trees ('Tree') defined in the
-- @containers@ package, but there is no standard type for binary
-- trees, so we define one here. Note, if you want to draw binary
-- trees with data of type @a@ at the leaves, you can use something
-- like @BTree (Maybe a)@ with @Nothing@ at internal nodes;
-- 'renderTree' lets you specify how to draw each node.
-- | Binary trees with data at internal nodes.
data BTree a = Empty | BNode a (BTree a) (BTree a)
deriving (Eq, Ord, Read, Show, Functor, F.Foldable, T.Traversable)
-- | Convenient constructor for leaves.
leaf :: a -> BTree a
leaf a = BNode a Empty Empty
------------------------------------------------------------
-- Layout algorithms
------------------------------------------------------------
--------------------------------------------------
-- Unique X layout for binary trees. No
-- two nodes share the same X coordinate.
data Pos = Pos { _level :: Int
, _horiz :: Int
}
deriving (Eq, Show)
makeLenses ''Pos
pos2Point :: Num n => n -> n -> Pos -> P2 n
pos2Point cSep lSep (Pos l h) = p2 (fromIntegral h * cSep, -fromIntegral l * lSep)
-- | @uniqueXLayout xSep ySep t@ lays out the binary tree @t@ using a
-- simple recursive algorithm with the following properties:
--
-- * Every left subtree is completely to the left of its parent, and
-- similarly for right subtrees.
--
-- * All the nodes at a given depth in the tree have the same
-- y-coordinate. The separation distance between levels is given by
-- @ySep@.
--
-- * Every node has a unique x-coordinate. The separation between
-- successive nodes from left to right is given by @xSep@.
uniqueXLayout :: Num n => n -> n -> BTree a -> Maybe (Tree (a, P2 n))
uniqueXLayout cSep lSep t = (fmap . fmap . second) (pos2Point cSep lSep)
$ evalState (uniqueXLayout' t) (Pos 0 0)
where uniqueXLayout' Empty = return Nothing
uniqueXLayout' (BNode a l r) = do
down
l' <- uniqueXLayout' l
up
p <- mkNode
down
r' <- uniqueXLayout' r
up
return $ Just (Node (a,p) (catMaybes [l', r']))
mkNode = get <* (horiz += 1)
down = level += 1
up = level -= 1
--------------------------------------------------
-- "Symmetric" layout of rose trees.
-- $symmetric
-- \"Symmetric\" layout of rose trees, based on the algorithm described in:
--
-- Andrew J. Kennedy. /Drawing Trees/, J Func. Prog. 6 (3): 527-534,
-- May 1996.
--
-- Trees laid out using this algorithm satisfy:
--
-- 1. Nodes at a given level are always separated by at least a
-- given minimum distance.
--
-- 2. Parent nodes are centered with respect to their immediate
-- offspring (though /not/ necessarily with respect to the entire
-- subtrees under them).
--
-- 3. Layout commutes with mirroring: that is, the layout of a given
-- tree is the mirror image of the layout of the tree's mirror
-- image. Put another way, there is no inherent left or right bias.
--
-- 4. Identical subtrees are always rendered identically. Put
-- another way, the layout of any subtree is independent of the rest
-- of the tree.
--
-- 5. The layouts are as narrow as possible while satisfying all the
-- above constraints.
-- | A tree with /relative/ positioning information. The @n@
-- at each node is the horizontal /offset/ from its parent.
type Rel t n a = t (a, n)
-- | Shift a RelTree horizontally.
moveTree :: Num n => n -> Rel Tree n a -> Rel Tree n a
moveTree x' (Node (a, x) ts) = Node (a, x+x') ts
-- | An /extent/ is a list of pairs, recording the leftmost and
-- rightmost (absolute) horizontal positions of a tree at each
-- depth.
newtype Extent n = Extent { getExtent :: [(n, n)] }
extent :: ([(n, n)] -> [(n, n)]) -> Extent n -> Extent n
extent f = Extent . f . getExtent
consExtent :: (n, n) -> Extent n -> Extent n
consExtent = extent . (:)
-- | Shift an extent horizontally.
moveExtent :: Num n => n -> Extent n -> Extent n
moveExtent x = (extent . map) ((+x) *** (+x))
-- | Reflect an extent about the vertical axis.
flipExtent :: Num n => Extent n -> Extent n
flipExtent = (extent . map) (\(p,q) -> (-q, -p))
-- | Merge two non-overlapping extents.
mergeExtents :: Extent n -> Extent n -> Extent n
mergeExtents (Extent e1) (Extent e2) = Extent $ mergeExtents' e1 e2
where
mergeExtents' [] qs = qs
mergeExtents' ps [] = ps
mergeExtents' ((p,_) : ps) ((_,q) : qs) = (p,q) : mergeExtents' ps qs
instance Semigroup (Extent n) where
(<>) = mergeExtents
instance Monoid (Extent n) where
mempty = Extent []
mappend = (<>)
-- | Determine the amount to shift in order to \"fit\" two extents
-- next to one another. The first argument is the separation to
-- leave between them.
fit :: (Num n, Ord n) => n -> Extent n -> Extent n -> n
fit hSep (Extent ps) (Extent qs) = maximum (0 : zipWith (\(_,p) (q,_) -> p - q + hSep) ps qs)
-- | Fit a list of subtree extents together using a left-biased
-- algorithm. Compute a list of positions (relative to the leftmost
-- subtree which is considered to have position 0).
fitListL :: (Num n, Ord n) => n -> [Extent n] -> [n]
fitListL hSep = snd . mapAccumL fitOne mempty
where
fitOne acc e =
let x = fit hSep acc e
in (acc <> moveExtent x e, x)
-- | Fit a list of subtree extents together with a right bias.
fitListR :: (Num n, Ord n) => n -> [Extent n] -> [n]
fitListR hSep = reverse . map negate . fitListL hSep . map flipExtent . reverse
-- | Compute a symmetric fitting by averaging the results of left- and
-- right-biased fitting.
fitList :: (Fractional n, Ord n) => n -> [Extent n] -> [n]
fitList hSep = uncurry (zipWith mean) . (fitListL hSep &&& fitListR hSep)
where mean x y = (x+y)/2
-- | Options for controlling the symmetric tree layout algorithm.
data SymmLayoutOpts n a =
SLOpts { _slHSep :: n -- ^ Minimum horizontal
-- separation between sibling
-- nodes. The default is 1.
, _slVSep :: n -- ^ Vertical separation
-- between adjacent levels of
-- the tree. The default is 1.
, _slWidth :: a -> (n, n)
-- ^ A function for measuring the horizontal extent (a pair
-- of x-coordinates) of an item in the tree. The default
-- is @const (0,0)@, that is, the nodes are considered as
-- taking up no space, so the centers of the nodes will
-- be separated according to the @slHSep@ and @slVSep@.
-- However, this can be useful, /e.g./ if you have a tree
-- of diagrams of irregular size and want to make sure no
-- diagrams overlap. In that case you could use
-- @fromMaybe (0,0) . extentX@.
, _slHeight :: a -> (n, n)
-- ^ A function for measuring the vertical extent of an
-- item in the tree. The default is @const (0,0)@. See
-- the documentation for 'slWidth' for more information.
}
makeLenses ''SymmLayoutOpts
instance Num n => Default (SymmLayoutOpts n a) where
def = SLOpts
{ _slHSep = 1
, _slVSep = 1
, _slWidth = const (0,0)
, _slHeight = const (0,0)
}
-- | Actual recursive tree layout algorithm, which returns a tree
-- layout as well as an extent.
symmLayoutR :: (Fractional n, Ord n) => SymmLayoutOpts n a -> Tree a -> (Rel Tree n a, Extent n)
symmLayoutR opts (Node a ts) = (rt, ext)
where (trees, extents) = unzip (map (symmLayoutR opts) ts)
positions = fitList (opts ^. slHSep) extents
pTrees = zipWith moveTree positions trees
pExtents = zipWith moveExtent positions extents
ext = (opts^.slWidth) a `consExtent` mconcat pExtents
rt = Node (a, 0) pTrees
-- | Symmetric tree layout algorithm specialized to binary trees.
-- Returns a tree layout as well as an extent.
symmLayoutBinR :: (Fractional n, Ord n) =>
SymmLayoutOpts n a -> BTree a -> (Maybe (Rel Tree n a), Extent n)
symmLayoutBinR _ Empty = (Nothing, mempty)
symmLayoutBinR opts (BNode a l r) = (Just rt, ext)
where (l', extL) = symmLayoutBinR opts l
(r', extR) = symmLayoutBinR opts r
positions = case (l', r') of
(Nothing, _) -> [0, opts ^. slHSep / 2]
(_, Nothing) -> [-(opts ^. slHSep) / 2, 0]
_ -> fitList (opts ^. slHSep) [extL, extR]
pTrees = catMaybes $ zipWith (fmap . moveTree) positions [l',r']
pExtents = zipWith moveExtent positions [extL, extR]
ext = (opts^.slWidth) a `consExtent` mconcat pExtents
rt = Node (a, 0) pTrees
-- | Run the symmetric rose tree layout algorithm on a given tree,
-- resulting in the same tree annotated with node positions.
symmLayout' :: (Fractional n, Ord n) => SymmLayoutOpts n a -> Tree a -> Tree (a, P2 n)
symmLayout' opts = unRelativize opts origin . fst . symmLayoutR opts
-- | Run the symmetric rose tree layout algorithm on a given tree
-- using default options, resulting in the same tree annotated with
-- node positions.
symmLayout :: (Fractional n, Ord n) => Tree a -> Tree (a, P2 n)
symmLayout = symmLayout' def
-- | Lay out a binary tree using a slight variant of the symmetric
-- layout algorithm. In particular, if a node has only a left child
-- but no right child (or vice versa), the child will be offset from
-- the parent horizontally by half the horizontal separation
-- parameter. Note that the result will be @Nothing@ if and only if
-- the input tree is @Empty@.
symmLayoutBin' :: (Fractional n, Ord n) => SymmLayoutOpts n a -> BTree a -> Maybe (Tree (a,P2 n))
symmLayoutBin' opts = fmap (unRelativize opts origin) . fst . symmLayoutBinR opts
-- | Lay out a binary tree using a slight variant of the symmetric
-- layout algorithm, using default options. In particular, if a
-- node has only a left child but no right child (or vice versa),
-- the child will be offset from the parent horizontally by half the
-- horizontal separation parameter. Note that the result will be
-- @Nothing@ if and only if the input tree is @Empty@.
symmLayoutBin :: (Fractional n, Ord n) => BTree a -> Maybe (Tree (a,P2 n))
symmLayoutBin = symmLayoutBin' def
-- | Given a fixed location for the root, turn a tree with
-- \"relative\" positioning into one with absolute locations
-- associated to all the nodes.
unRelativize :: (Num n, Ord n) =>
SymmLayoutOpts n a -> P2 n -> Rel Tree n a -> Tree (a, P2 n)
unRelativize opts curPt (Node (a,hOffs) ts)
= Node (a, rootPt) (map (unRelativize opts (rootPt .+^ (vOffs *^ unit_Y))) ts)
where rootPt = curPt .+^ (hOffs *^ unitX)
vOffs = - fst ((opts^.slHeight) a)
+ (maximum . map (snd . (opts^.slHeight) . fst . rootLabel) $ ts)
+ (opts ^. slVSep)
--------------------------------------------------
-- Force-directed layout of rose trees
-- $forcedirected
-- Force-directed layout of rose trees.
data ForceLayoutTreeOpts n =
FLTOpts
{ _forceLayoutOpts :: ForceLayoutOpts n -- ^ Options to the force layout simulator, including damping.
, _edgeLen :: n -- ^ How long edges should be, ideally.
-- This will be the resting length for
-- the springs.
, _springK :: n -- ^ Spring constant. The
-- bigger the constant,
-- the more the edges
-- push/pull towards their
-- resting length.
, _staticK :: n -- ^ Coulomb constant. The
-- bigger the constant, the
-- more sibling nodes repel
-- each other.
}
makeLenses ''ForceLayoutTreeOpts
instance Floating n => Default (ForceLayoutTreeOpts n) where
def = FLTOpts
{ _forceLayoutOpts = def
, _edgeLen = sqrt 2
, _springK = 0.05
, _staticK = 0.1
}
-- | Assign unique ID numbers to the nodes of a tree, and generate an
-- 'Ensemble' suitable for simulating in order to do force-directed
-- layout of the tree. In particular,
--
-- * edges are modeled as springs
--
-- * nodes are modeled as point charges
--
-- * nodes are constrained to keep the same y-coordinate.
--
-- The input to @treeToEnsemble@ could be a tree already laid out by
-- some other method, such as 'uniqueXLayout'.
treeToEnsemble :: forall a n. Floating n => ForceLayoutTreeOpts n
-> Tree (a, P2 n) -> (Tree (a, PID), Ensemble V2 n)
treeToEnsemble opts t =
( fmap (first fst) lt
, Ensemble
[ (edges, \pt1 pt2 -> project unitX (hookeForce (opts ^. springK) (opts ^. edgeLen) pt1 pt2))
, (sibs, \pt1 pt2 -> project unitX (coulombForce (opts ^. staticK) pt1 pt2))
]
particleMap
)
where lt :: Tree ((a,P2 n), PID)
lt = label t
particleMap :: M.Map PID (Particle V2 n)
particleMap = M.fromList
. map (second initParticle)
. F.toList
. fmap (swap . first snd)
$ lt
swap (x,y) = (y,x)
edges, sibs :: [Edge]
edges = extractEdges (fmap snd lt)
sibs = extractSibs [fmap snd lt]
extractEdges :: Tree PID -> [Edge]
extractEdges (Node i cs) = map (((,) i) . rootLabel) cs
++ concatMap extractEdges cs
extractSibs :: Forest PID -> [Edge]
extractSibs [] = []
extractSibs ts = (\is -> zip is (tail is)) (map rootLabel ts)
++ extractSibs (concatMap subForest ts)
-- sz = ala Sum foldMap . fmap (const 1) $ t
-- sibs = [(x,y) | x <- [0..sz-2], y <- [x+1 .. sz-1]]
-- | Assign unique IDs to every node in a tree (or other traversable structure).
label :: (T.Traversable t) => t a -> t (a, PID)
label = flip evalState 0 . T.mapM (\a -> get >>= \i -> modify (+1) >> return (a,i))
-- | Reconstruct a tree (or any traversable structure) from an
-- 'Ensemble', given unique identifier annotations matching the
-- identifiers used in the 'Ensemble'.
reconstruct :: (Functor t, Num n) => Ensemble V2 n -> t (a, PID) -> t (a, P2 n)
reconstruct e = (fmap . second)
(fromMaybe origin . fmap (view pos) . flip M.lookup (e^.particles))
-- | Force-directed layout of rose trees, with default parameters (for
-- more options, see 'forceLayoutTree''). In particular,
--
-- * edges are modeled as springs
--
-- * nodes are modeled as point charges
--
-- * nodes are constrained to keep the same y-coordinate.
--
-- The input could be a tree already laid out by some other method,
-- such as 'uniqueXLayout'.
forceLayoutTree :: (Floating n, Ord n) => Tree (a, P2 n) -> Tree (a, P2 n)
forceLayoutTree = forceLayoutTree' def
-- | Force-directed layout of rose trees, with configurable parameters.
forceLayoutTree' :: (Floating n, Ord n) =>
ForceLayoutTreeOpts n -> Tree (a, P2 n) -> Tree (a, P2 n)
forceLayoutTree' opts t = reconstruct (forceLayout (opts^.forceLayoutOpts) e) ti
where (ti, e) = treeToEnsemble opts t
--------------------------------------------------------------------
-- Radial Layout Implementation
--
-- alpha beta defines annulus wedge of a vertex
-- d is the depth of any vertex from root
-- k is #leaves of root and lambda is #leaves of vertex
-- weight assigns the length of radius wrt the number of
-- number of children to avoid node overlapping
-- Extension of Algotihm 1, Page 18 http://www.cs.cmu.edu/~pavlo/static/papers/APavloThesis032006.pdf
-- Example: https://drive.google.com/file/d/0B3el1oMKFsOIVGVRYzJzWGwzWDA/view
-------------------------------------------------------------------
radialLayout :: Tree a -> Tree (a, P2 Double)
radialLayout t = finalTree $
radialLayout' 0 pi 0 (countLeaves $ decorateDepth 0 t) (weight t) (decorateDepth 0 t)
radialLayout' :: Double -> Double -> Double -> Int -> Double -> Tree (a, P2 Double, Int) -> Tree (a, P2 Double, Int)
radialLayout' alpha beta theta k w (Node (a, pt, d) ts) = Node (a, pt, d) (assignPos alpha beta theta k w ts)
assignPos :: Double -> Double -> Double -> Int -> Double -> [Tree (a, P2 Double, Int)] -> [Tree (a, P2 Double, Int)]
assignPos _ _ _ _ _ [] = []
assignPos alpha beta theta k w (Node (a, pt, d) ts1:ts2)
= Node (a, pt2, d) (assignPos theta u theta lambda w ts1) : assignPos alpha beta u k w ts2
where
lambda = countLeaves (Node (a, pt, d) ts1)
u = theta + (beta - alpha) * fromIntegral lambda / fromIntegral k
pt2 = mkP2 (w * fromIntegral d * cos (theta + u)/2) (w * fromIntegral d * sin (theta + u)/2)
decorateDepth:: Int -> Tree a -> Tree (a, P2 Double, Int)
decorateDepth d (Node a ts) = Node (a, mkP2 0 0, d) $ map (decorateDepth (d+1)) ts
countLeaves :: Tree (a, P2 Double, Int) -> Int
countLeaves (Node _ []) = 1
countLeaves (Node _ ts) = sum (map countLeaves ts)
weight :: Tree a -> Double
weight t = maximum $
map (((\ x -> fromIntegral x / 2) . length) . map rootLabel)
(takeWhile (not . null) $ iterate (concatMap subForest) [t])
finalTree :: Tree (a, P2 Double, Int) -> Tree (a, P2 Double)
finalTree (Node (a, pt, _) ts) = Node (a, pt) $ map finalTree ts
------------------------------------------------------------
-- Rendering
------------------------------------------------------------
-- | Draw a tree annotated with node positions, given functions
-- specifying how to draw nodes and edges.
renderTree :: (Monoid' m, Floating n, Ord n)
=> (a -> QDiagram b V2 n m) -> (P2 n -> P2 n -> QDiagram b V2 n m)
-> Tree (a, P2 n) -> QDiagram b V2 n m
renderTree n e = renderTree' n (e `on` snd)
-- | Draw a tree annotated with node positions, given functions
-- specifying how to draw nodes and edges. Unlike 'renderTree',
-- this version gives the edge-drawing function access to the actual
-- values stored at the nodes rather than just their positions.
renderTree' :: (Monoid' m, Floating n, Ord n)
=> (a -> QDiagram b V2 n m) -> ((a,P2 n) -> (a,P2 n) -> QDiagram b V2 n m)
-> Tree (a, P2 n) -> QDiagram b V2 n m
renderTree' renderNode renderEdge = alignT . centerX . renderTreeR
where
renderTreeR (Node (a,p) cs) =
renderNode a # moveTo p
<> mconcat (map renderTreeR cs)
<> mconcat (map (renderEdge (a,p) . rootLabel) cs)
-- > -- Critical size-limited Boltzmann generator for binary trees (used in example)
-- >
-- > import Control.Applicative
-- > import Control.Lens hiding (( # ))
-- > import Control.Monad.Random
-- > import Control.Monad.Reader
-- > import Control.Monad.State
-- > import Control.Monad.Trans.Maybe
-- >
-- > genTreeCrit :: ReaderT Int (StateT Int (MaybeT (Rand StdGen))) (BTree ())
-- > genTreeCrit = do
-- > r <- getRandom
-- > if r <= (1/2 :: Double)
-- > then return Empty
-- > else atom >> (BNode () <$> genTreeCrit <*> genTreeCrit)
-- >
-- > atom :: ReaderT Int (StateT Int (MaybeT (Rand StdGen))) ()
-- > atom = do
-- > targetSize <- ask
-- > curSize <- get
-- > when (curSize >= targetSize) mzero
-- > put (curSize + 1)
-- >
-- > genOneTree :: Int -> Int -> Double -> Maybe (BTree ())
-- > genOneTree seed size eps =
-- > case mt of
-- > Nothing -> Nothing
-- > Just (t,sz) -> if sz >= minSz then Just t else Nothing
-- >
-- > where
-- > g = mkStdGen seed
-- > sizeWiggle = floor $ fromIntegral size * eps
-- > maxSz = size + sizeWiggle
-- > minSz = size - sizeWiggle
-- > mt = (evalRand ?? g) . runMaybeT . (runStateT ?? 0) . (runReaderT ?? maxSz)
-- > $ genTreeCrit
-- >
-- > genTree' :: Int -> Int -> Double -> BTree ()
-- > genTree' seed size eps =
-- > case (genOneTree seed size eps) of
-- > Nothing -> genTree' (seed+1) size eps
-- > Just t -> t
-- >
-- > genTree :: Int -> Double -> BTree ()
-- > genTree = genTree' 0
|
wherkendell/diagrams-contrib
|
src/Diagrams/TwoD/Layout/Tree.hs
|
bsd-3-clause
| 25,710 | 1 | 18 | 7,103 | 5,110 | 2,864 | 2,246 | 237 | 3 |
-----------------------------------------------------------------------------
-- Standard Library: Array operations
--
-- Suitable for use with Hugs 98
-----------------------------------------------------------------------------
module Hugs.Array (
module Data.Ix, -- export all of Ix
unsafeIndex,
Array, array, listArray, (!), bounds, indices, elems, assocs,
accumArray, (//), accum, ixmap,
unsafeArray, unsafeAt, unsafeReplace, unsafeAccum, unsafeAccumArray
) where
import Data.Ix
import Hugs.Prelude( unsafeIndex )
infixl 9 !, //
data Array a b -- Arrays are implemented as a primitive type
array :: Ix a => (a,a) -> [(a,b)] -> Array a b
listArray :: Ix a => (a,a) -> [b] -> Array a b
(!) :: Ix a => Array a b -> a -> b
bounds :: Ix a => Array a b -> (a,a)
indices :: Ix a => Array a b -> [a]
elems :: Ix a => Array a b -> [b]
assocs :: Ix a => Array a b -> [(a,b)]
(//) :: Ix a => Array a b -> [(a,b)] -> Array a b
accum :: Ix a => (b -> c -> b) -> Array a b -> [(a,c)] -> Array a b
accumArray :: Ix a => (b -> c -> b) -> b -> (a,a) -> [(a,c)] -> Array a b
ixmap :: (Ix a, Ix b) => (a,a) -> (a -> b) -> Array b c -> Array a c
primitive primArray :: (a,a) -> Int -> [(Int,b)] -> Array a b
primitive primUpdate :: [(Int,b)] -> Array a b -> Array a b
primitive primAccum :: [(Int,c)] -> Array a b -> (b -> c -> b) -> Array a b
primitive primAccumArray
:: (a,a) -> Int -> (b -> c -> b) -> b -> [(Int,c)] -> Array a b
primitive primSubscript :: Array a b -> Int -> b
primitive primBounds :: Array a b -> (a,a)
primitive primElems :: Array a b -> [b]
primitive primAmap :: (b -> c) -> Array a b -> Array a c
unsafeArray :: Ix i => (i,i) -> [(Int, e)] -> Array i e
unsafeArray bnds = primArray bnds (rangeSize bnds)
unsafeAt :: Ix i => Array i e -> Int -> e
unsafeAt = primSubscript
unsafeReplace :: Ix i => Array i e -> [(Int, e)] -> Array i e
unsafeReplace iarr ies = primUpdate ies iarr
unsafeAccum :: Ix i => (e -> a -> e) -> Array i e -> [(Int, a)] -> Array i e
unsafeAccum f iarr ies = primAccum ies iarr f
unsafeAccumArray :: Ix i => (e -> a -> e) -> e -> (i,i) -> [(Int, a)] -> Array i e
unsafeAccumArray f z bnds = primAccumArray bnds (rangeSize bnds) f z
indexAll :: Ix i => (i,i) -> [(i, a)] -> [(Int, a)]
indexAll bnds ivs = [(index bnds i,v) | (i,v) <- ivs]
array bnds = unsafeArray bnds . indexAll bnds
listArray bnds vs = unsafeArray bnds (zip [0..rangeSize bnds-1] vs)
arr!i = unsafeAt arr (index (bounds arr) i)
bounds = primBounds
indices = range . bounds
elems = primElems
assocs a = zip (indices a) (elems a)
accumArray f z bnds = unsafeAccumArray f z bnds . indexAll bnds
a // ivs = unsafeReplace a (indexAll (bounds a) ivs)
accum f a ivs = unsafeAccum f a (indexAll (bounds a) ivs)
ixmap bnds f arr =
unsafeArray bnds [(unsafeIndex bnds i, arr ! f i) | i <- range bnds]
instance (Ix a) => Functor (Array a) where
fmap = primAmap
instance (Ix a, Eq b) => Eq (Array a b) where
a == a' = assocs a == assocs a'
instance (Ix a, Ord b) => Ord (Array a b) where
a <= a' = assocs a <= assocs a'
instance (Ix a, Show a, Show b) => Show (Array a b) where
showsPrec p a = showParen (p > 9) (
showString "array " .
shows (bounds a) . showChar ' ' .
shows (assocs a) )
instance (Ix a, Read a, Read b) => Read (Array a b) where
readsPrec p = readParen (p > 9)
(\r -> [(array b as, u) | ("array",s) <- lex r,
(b,t) <- reads s,
(as,u) <- reads t ])
-----------------------------------------------------------------------------
|
kaoskorobase/mescaline
|
resources/hugs/packages/hugsbase/Hugs/Array.hs
|
gpl-3.0
| 3,775 | 59 | 13 | 1,033 | 1,827 | 965 | 862 | -1 | -1 |
{-|
Module : Idris.Elab.Utils
Description : Elaborator utilities.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE FlexibleContexts, PatternGuards #-}
module Idris.Elab.Utils where
import Idris.AbsSyntax
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.TT
import Idris.Core.Typecheck
import Idris.Core.WHNF
import Idris.DeepSeq
import Idris.Delaborate
import Idris.Docstrings
import Idris.Error
import Idris.Output
import Util.Pretty
import Control.Applicative hiding (Const)
import Control.Monad
import Control.Monad.State
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Traversable as Traversable
import Debug.Trace
recheckC = recheckC_borrowing False True []
recheckC_borrowing uniq_check addConstrs bs tcns fc mkerr env t
= do -- t' <- applyOpts (forget t) (doesn't work, or speed things up...)
ctxt <- getContext
t' <- case safeForget t of
Just ft -> return ft
Nothing -> tclift $ tfail $ mkerr (At fc (IncompleteTerm t))
(tm, ty, cs) <- tclift $ case recheck_borrowing uniq_check bs tcns ctxt env t' t of
Error e -> tfail (At fc (mkerr e))
OK x -> return x
logElab 6 $ "CONSTRAINTS ADDED: " ++ show (tm, ty, cs)
tit <- typeInType
when (not tit && addConstrs) $
do addConstraints fc cs
mapM_ (\c -> addIBC (IBCConstraint fc c)) (snd cs)
mapM_ (checkDeprecated fc) (allTTNames tm)
mapM_ (checkDeprecated fc) (allTTNames ty)
mapM_ (checkFragile fc) (allTTNames tm)
mapM_ (checkFragile fc) (allTTNames ty)
return (tm, ty)
checkDeprecated :: FC -> Name -> Idris ()
checkDeprecated fc n
= do r <- getDeprecated n
case r of
Nothing -> return ()
Just r -> do iWarn fc $ text "Use of deprecated name " <> annName n
<> case r of
"" -> Util.Pretty.empty
_ -> line <> text r
checkFragile :: FC -> Name -> Idris ()
checkFragile fc n = do
r <- getFragile n
case r of
Nothing -> return ()
Just r -> do
iWarn fc $ text "Use of a fragile construct "
<> annName n
<> case r of
"" -> Util.Pretty.empty
_ -> line <> text r
iderr :: Name -> Err -> Err
iderr _ e = e
checkDef :: ElabInfo -> FC -> (Name -> Err -> Err) -> Bool ->
[(Name, (Int, Maybe Name, Type, [Name]))] ->
Idris [(Name, (Int, Maybe Name, Type, [Name]))]
checkDef info fc mkerr definable ns
= checkAddDef False True info fc mkerr definable ns
checkAddDef :: Bool -> Bool -> ElabInfo -> FC -> (Name -> Err -> Err) -> Bool
-> [(Name, (Int, Maybe Name, Type, [Name]))]
-> Idris [(Name, (Int, Maybe Name, Type, [Name]))]
checkAddDef add toplvl info fc mkerr def [] = return []
checkAddDef add toplvl info fc mkerr definable ((n, (i, top, t, psns)) : ns)
= do ctxt <- getContext
logElab 5 $ "Rechecking deferred name " ++ show (n, t, definable)
(t', _) <- recheckC (constraintNS info) fc (mkerr n) [] t
when add $ do addDeferred [(n, (i, top, t, psns, toplvl, definable))]
addIBC (IBCDef n)
ns' <- checkAddDef add toplvl info fc mkerr definable ns
return ((n, (i, top, t', psns)) : ns')
-- | Get the list of (index, name) of inaccessible arguments from an elaborated
-- type
inaccessibleImps :: Int -> Type -> [Bool] -> [(Int, Name)]
inaccessibleImps i (Bind n (Pi _ _ t _) sc) (inacc : ins)
| inacc = (i, n) : inaccessibleImps (i + 1) sc ins
| otherwise = inaccessibleImps (i + 1) sc ins
inaccessibleImps _ _ _ = []
-- | Get the list of (index, name) of inaccessible arguments from the type.
inaccessibleArgs :: Int -> PTerm -> [(Int, Name)]
inaccessibleArgs i (PPi plicity n _ ty t)
| InaccessibleArg `elem` pargopts plicity
= (i,n) : inaccessibleArgs (i+1) t -- an .{erased : Implicit}
| otherwise
= inaccessibleArgs (i+1) t -- a {regular : Implicit}
inaccessibleArgs _ _ = []
elabCaseBlock :: ElabInfo -> FnOpts -> PDecl -> Idris ()
elabCaseBlock info opts d@(PClauses f o n ps)
= do addIBC (IBCDef n)
logElab 5 $ "CASE BLOCK: " ++ show (n, d)
let opts' = nub (o ++ opts)
-- propagate totality assertion to the new definitions
let opts' = filter propagatable opts
setFlags n opts'
rec_elabDecl info EAll info (PClauses f opts' n ps )
where
propagatable AssertTotal = True
propagatable Inlinable = True
propagatable _ = False
-- | Check that the result of type checking matches what the programmer wrote
-- (i.e. - if we inferred any arguments that the user provided, make sure
-- they are the same!)
checkInferred :: FC -> PTerm -> PTerm -> Idris ()
checkInferred fc inf user =
do logElab 6 $ "Checked to\n" ++ showTmImpls inf ++ "\n\nFROM\n\n" ++
showTmImpls user
logElab 10 $ "Checking match"
i <- getIState
tclift $ case matchClause' True i user inf of
_ -> return ()
-- Left (x, y) -> tfail $ At fc
-- (Msg $ "The type-checked term and given term do not match: "
-- ++ show x ++ " and " ++ show y)
logElab 10 $ "Checked match"
-- ++ "\n" ++ showImp True inf ++ "\n" ++ showImp True user)
-- | Return whether inferred term is different from given term
-- (as above, but return a Bool)
inferredDiff :: FC -> PTerm -> PTerm -> Idris Bool
inferredDiff fc inf user =
do i <- getIState
logElab 6 $ "Checked to\n" ++ showTmImpls inf ++ "\n" ++
showTmImpls user
tclift $ case matchClause' True i user inf of
Right vs -> return False
Left (x, y) -> return True
-- | Check a PTerm against documentation and ensure that every documented
-- argument actually exists. This must be run _after_ implicits have been
-- found, or it will give spurious errors.
checkDocs :: FC -> [(Name, Docstring a)] -> PTerm -> Idris ()
checkDocs fc args tm = cd (Map.fromList args) tm
where cd as (PPi _ n _ _ sc) = cd (Map.delete n as) sc
cd as _ | Map.null as = return ()
| otherwise = ierror . At fc . Msg $
"There is documentation for argument(s) "
++ (concat . intersperse ", " . map show . Map.keys) as
++ " but they were not found."
decorateid decorate (PTy doc argdocs s f o n nfc t) = PTy doc argdocs s f o (decorate n) nfc t
decorateid decorate (PClauses f o n cs)
= PClauses f o (decorate n) (map dc cs)
where dc (PClause fc n t as w ds) = PClause fc (decorate n) (dappname t) as w ds
dc (PWith fc n t as w pn ds)
= PWith fc (decorate n) (dappname t) as w pn
(map (decorateid decorate) ds)
dappname (PApp fc (PRef fc' hl n) as) = PApp fc (PRef fc' hl (decorate n)) as
dappname t = t
-- if 't' is an interface application, assume its arguments are injective
pbinds :: IState -> Term -> ElabD ()
pbinds i (Bind n (PVar rig t) sc)
= do attack; patbind n rig
env <- get_env
case unApply (normalise (tt_ctxt i) env t) of
(P _ c _, args) -> case lookupCtxt c (idris_interfaces i) of
[] -> return ()
_ -> -- interface, set as injective
mapM_ setinjArg args
_ -> return ()
pbinds i sc
where setinjArg (P _ n _) = setinj n
setinjArg _ = return ()
pbinds i tm = return ()
pbty (Bind n (PVar _ t) sc) tm = Bind n (PVTy t) (pbty sc tm)
pbty _ tm = tm
getPBtys (Bind n (PVar _ t) sc) = (n, t) : getPBtys sc
getPBtys (Bind n (PVTy t) sc) = (n, t) : getPBtys sc
getPBtys _ = []
psolve (Bind n (PVar _ t) sc) = do solve; psolve sc
psolve tm = return ()
pvars ist tm = pv' [] tm
where
pv' env (Bind n (PVar _ t) sc)
= (n, delabWithEnv ist env t) : pv' ((n, t) : env) sc
pv' env _ = []
getFixedInType i env (PExp _ _ _ _ : is) (Bind n (Pi _ _ t _) sc)
= nub $ getFixedInType i env [] t ++
getFixedInType i (n : env) is (instantiate (P Bound n t) sc)
++ case unApply t of
(P _ n _, _) -> if n `elem` env then [n] else []
_ -> []
getFixedInType i env (_ : is) (Bind n (Pi _ _ t _) sc)
= getFixedInType i (n : env) is (instantiate (P Bound n t) sc)
getFixedInType i env is tm@(App _ f a)
| (P _ tn _, args) <- unApply tm
= case lookupCtxtExact tn (idris_datatypes i) of
Just t -> nub $ paramNames args env (param_pos t) ++
getFixedInType i env is f ++
getFixedInType i env is a
Nothing -> nub $ getFixedInType i env is f ++
getFixedInType i env is a
| otherwise = nub $ getFixedInType i env is f ++
getFixedInType i env is a
getFixedInType i _ _ _ = []
getFlexInType i env ps (Bind n (Pi _ _ t _) sc)
= nub $ (if (not (n `elem` ps)) then getFlexInType i env ps t else []) ++
getFlexInType i (n : env) ps (instantiate (P Bound n t) sc)
getFlexInType i env ps tm@(App _ f a)
| (P nt tn _, args) <- unApply tm, nt /= Bound
= case lookupCtxtExact tn (idris_datatypes i) of
Just t -> nub $ paramNames args env [x | x <- [0..length args],
not (x `elem` param_pos t)]
++ getFlexInType i env ps f ++
getFlexInType i env ps a
Nothing -> let ppos = case lookupCtxtExact tn (idris_fninfo i) of
Just fi -> fn_params fi
Nothing -> []
in nub $ paramNames args env [x | x <- [0..length args],
not (x `elem` ppos)]
++ getFlexInType i env ps f ++
getFlexInType i env ps a
| otherwise = nub $ getFlexInType i env ps f ++
getFlexInType i env ps a
getFlexInType i _ _ _ = []
-- | Treat a name as a parameter if it appears in parameter positions in
-- types, and never in a non-parameter position in a (non-param) argument type.
getParamsInType :: IState -> [Name] -> [PArg] -> Type -> [Name]
getParamsInType i env ps t = let fix = getFixedInType i env ps t
flex = getFlexInType i env fix t in
[x | x <- fix, not (x `elem` flex)]
getTCinj i (Bind n (Pi _ _ t _) sc)
= getTCinj i t ++ getTCinj i (instantiate (P Bound n t) sc)
getTCinj i ap@(App _ f a)
| (P _ n _, args) <- unApply ap,
isTCName n = mapMaybe getInjName args
| otherwise = []
where
isTCName n = case lookupCtxtExact n (idris_interfaces i) of
Just _ -> True
_ -> False
getInjName t | (P _ x _, _) <- unApply t = Just x
| otherwise = Nothing
getTCinj _ _ = []
getTCParamsInType :: IState -> [Name] -> [PArg] -> Type -> [Name]
getTCParamsInType i env ps t = let params = getParamsInType i env ps t
tcs = nub $ getTCinj i t in
filter (flip elem tcs) params
paramNames args env [] = []
paramNames args env (p : ps)
| length args > p = case args!!p of
P _ n _ -> if n `elem` env
then n : paramNames args env ps
else paramNames args env ps
_ -> paramNames args env ps
| otherwise = paramNames args env ps
getUniqueUsed :: Context -> Term -> [Name]
getUniqueUsed ctxt tm = execState (getUniq [] [] tm) []
where
getUniq :: Env -> [(Name, Bool)] -> Term -> State [Name] ()
getUniq env us (Bind n b sc)
= let uniq = case check ctxt env (forgetEnv (map fstEnv env) (binderTy b)) of
OK (_, UType UniqueType) -> True
OK (_, UType NullType) -> True
OK (_, UType AllTypes) -> True
_ -> False in
do getUniqB env us b
getUniq ((n, RigW, b):env) ((n, uniq):us) sc
getUniq env us (App _ f a) = do getUniq env us f; getUniq env us a
getUniq env us (V i)
| i < length us = if snd (us!!i) then use (fst (us!!i)) else return ()
getUniq env us (P _ n _)
| Just u <- lookup n us = if u then use n else return ()
getUniq env us _ = return ()
use n = do ns <- get; put (n : ns)
getUniqB env us (Let t v) = getUniq env us v
getUniqB env us (Guess t v) = getUniq env us v
-- getUniqB env us (Pi _ _ t v) = do getUniq env us t; getUniq env us v
getUniqB env us (NLet t v) = getUniq env us v
getUniqB env us b = return () -- getUniq env us (binderTy b)
-- In a functional application, return the names which are used
-- directly in a static position
getStaticNames :: IState -> Term -> [Name]
getStaticNames ist (Bind n (PVar _ _) sc)
= getStaticNames ist (instantiate (P Bound n Erased) sc)
getStaticNames ist tm
| (P _ fn _, args) <- unApply tm
= case lookupCtxtExact fn (idris_statics ist) of
Just stpos -> getStatics args stpos
_ -> []
where
getStatics (P _ n _ : as) (True : ss) = n : getStatics as ss
getStatics (_ : as) (_ : ss) = getStatics as ss
getStatics _ _ = []
getStaticNames _ _ = []
getStatics :: [Name] -> Term -> [Bool]
getStatics ns (Bind n (Pi _ _ _ _) t)
| n `elem` ns = True : getStatics ns t
| otherwise = False : getStatics ns t
getStatics _ _ = []
mkStatic :: [Name] -> PDecl -> PDecl
mkStatic ns (PTy doc argdocs syn fc o n nfc ty)
= PTy doc argdocs syn fc o n nfc (mkStaticTy ns ty)
mkStatic ns t = t
mkStaticTy :: [Name] -> PTerm -> PTerm
mkStaticTy ns (PPi p n fc ty sc)
| n `elem` ns = PPi (p { pstatic = Static }) n fc ty (mkStaticTy ns sc)
| otherwise = PPi p n fc ty (mkStaticTy ns sc)
mkStaticTy ns t = t
-- Check that a name has the minimum required accessibility
checkVisibility :: FC -> Name -> Accessibility -> Accessibility -> Name -> Idris ()
checkVisibility fc n minAcc acc ref
= do nvis <- getFromHideList ref
case nvis of
Nothing -> return ()
Just acc' -> if acc' > minAcc
then tclift $ tfail (At fc
(Msg $ show acc ++ " " ++ show n ++
" can't refer to " ++
show acc' ++ " " ++ show ref))
else return ()
-- | Find the type constructor arguments that are parameters, given a
-- list of constructor types.
--
-- Parameters are names which are unchanged across the structure.
-- They appear at least once in every constructor type, always appear
-- in the same argument position(s), and nothing else ever appears in those
-- argument positions.
findParams :: Name -- ^ the name of the family that we are finding parameters for
-> Type -- ^ the type of the type constructor (normalised already)
-> [Type] -- ^ the declared constructor types
-> [Int]
findParams tyn famty ts =
let allapps = map getDataApp ts
-- do each constructor separately, then merge the results (names
-- may change between constructors)
conParams = map paramPos allapps
in inAll conParams
where
inAll :: [[Int]] -> [Int]
inAll [] = []
inAll (x : xs) = filter (\p -> all (\ps -> p `elem` ps) xs) x
paramPos [] = []
paramPos (args : rest)
= dropNothing $ keepSame (zip [0..] args) rest
dropNothing [] = []
dropNothing ((x, Nothing) : ts) = dropNothing ts
dropNothing ((x, _) : ts) = x : dropNothing ts
keepSame :: [(Int, Maybe Name)] -> [[Maybe Name]] ->
[(Int, Maybe Name)]
keepSame as [] = as
keepSame as (args : rest) = keepSame (update as args) rest
where
update [] _ = []
update _ [] = []
update ((n, Just x) : as) (Just x' : args)
| x == x' = (n, Just x) : update as args
update ((n, _) : as) (_ : args) = (n, Nothing) : update as args
getDataApp :: Type -> [[Maybe Name]]
getDataApp f@(App _ _ _)
| (P _ d _, args) <- unApply f
= if (d == tyn) then [mParam args args] else []
getDataApp (Bind n (Pi _ _ t _) sc)
= getDataApp t ++ getDataApp (instantiate (P Bound n t) sc)
getDataApp _ = []
-- keep the arguments which are single names, which appear
-- in the return type, counting only the first time they appear in
-- the return type as the parameter position
mParam args [] = []
mParam args (P Bound n _ : rest)
| paramIn False n args = Just n : mParam (filter (noN n) args) rest
where paramIn ok n [] = ok
paramIn ok n (P _ t _ : ts)
= paramIn (ok || n == t) n ts
paramIn ok n (t : ts)
| n `elem` freeNames t = False -- not a single name
| otherwise = paramIn ok n ts
-- If the name appears again later, don't count that appearance
-- as a parameter position
noN n (P _ t _) = n /= t
noN n _ = False
mParam args (_ : rest) = Nothing : mParam args rest
-- | Mark a name as detaggable in the global state (should be called
-- for type and constructor names of single-constructor datatypes)
setDetaggable :: Name -> Idris ()
setDetaggable n = do
ist <- getIState
let opt = idris_optimisation ist
case lookupCtxt n opt of
[oi] -> putIState ist { idris_optimisation = addDef n oi { detaggable = True } opt }
_ -> putIState ist { idris_optimisation = addDef n (Optimise [] True []) opt }
displayWarnings :: EState -> Idris ()
displayWarnings est
= mapM_ displayImpWarning (implicit_warnings est)
where
displayImpWarning :: (FC, Name) -> Idris ()
displayImpWarning (fc, n) = do
ist <- getIState
let msg = show (nsroot n)
++ " is bound as an implicit\n"
++ "\tDid you mean to refer to " ++ show n ++ "?"
iWarn fc (pprintErr ist (Msg msg))
propagateParams :: IState -> [Name] -> Type -> [Name] -> PTerm -> PTerm
propagateParams i ps t bound tm@(PApp _ (PRef fc hls n) args)
= PApp fc (PRef fc hls n) (addP t args)
where addP (Bind n _ sc) (t : ts)
| Placeholder <- getTm t,
n `elem` ps,
not (n `elem` bound)
= t { getTm = PPatvar NoFC n } : addP sc ts
addP (Bind n _ sc) (t : ts) = t : addP sc ts
addP _ ts = ts
propagateParams i ps t bound (PApp fc ap args)
= PApp fc (propagateParams i ps t bound ap) args
propagateParams i ps t bound (PRef fc hls n)
= case lookupCtxt n (idris_implicits i) of
[is] -> let ps' = filter (isImplicit is) ps in
PApp fc (PRef fc hls n) (map (\x -> pimp x (PRef fc [] x) True) ps')
_ -> PRef fc hls n
where isImplicit [] n = False
isImplicit (PImp _ _ _ x _ : is) n | x == n = True
isImplicit (_ : is) n = isImplicit is n
propagateParams i ps t bound x = x
-- | Gather up all the outer 'PVar's and 'Hole's in an expression and reintroduce
-- them in a canonical order
orderPats :: Term -> Term
orderPats tm = op [] tm
where
op [] (App s f a) = App s f (op [] a) -- for Infer terms
op ps (Bind n (PVar r t) sc) = op ((n, PVar r t) : ps) sc
op ps (Bind n (Hole t) sc) = op ((n, Hole t) : ps) sc
op ps (Bind n (Pi rig i t k) sc) = op ((n, Pi rig i t k) : ps) sc
op ps sc = bindAll (sortP ps) sc
-- Keep explicit Pi in the same order, insert others as necessary,
-- Pi as early as possible, Hole as late as possible
sortP ps = let (exps, imps) = partition isExp ps in
pick (reverse exps) imps
isExp (_, Pi rig Nothing _ _) = True
isExp (_, Pi rig (Just i) _ _) = toplevel_imp i && not (machine_gen i)
isExp _ = False
pick acc [] = acc
pick acc ((n, t) : ps) = pick (insert n t acc) ps
insert n t [] = [(n, t)]
-- if 't' uses any of the names which appear later, insert it later
insert n t rest@((n', t') : ps)
| any (\x -> x `elem` refsIn (binderTy t)) (n' : map fst ps)
= (n', t') : insert n t ps
-- otherwise it's fine where it is (preserve ordering)
| otherwise = (n, t) : rest
-- Make sure all the pattern bindings are as far out as possible
liftPats :: Term -> Term
liftPats tm = let (tm', ps) = runState (getPats tm) [] in
orderPats $ bindPats (reverse ps) tm'
where
bindPats [] tm = tm
bindPats ((n, t):ps) tm
| n `notElem` map fst ps = Bind n (PVar RigW t) (bindPats ps tm)
| otherwise = bindPats ps tm
getPats :: Term -> State [(Name, Type)] Term
getPats (Bind n (PVar _ t) sc) = do ps <- get
put ((n, t) : ps)
getPats sc
getPats (Bind n (Guess t v) sc) = do t' <- getPats t
v' <- getPats v
sc' <- getPats sc
return (Bind n (Guess t' v') sc')
getPats (Bind n (Let t v) sc) = do t' <- getPats t
v' <- getPats v
sc' <- getPats sc
return (Bind n (Let t' v') sc')
getPats (Bind n (Pi rig i t k) sc) = do t' <- getPats t
k' <- getPats k
sc' <- getPats sc
return (Bind n (Pi rig i t' k') sc')
getPats (Bind n (Lam r t) sc) = do t' <- getPats t
sc' <- getPats sc
return (Bind n (Lam r t') sc')
getPats (Bind n (Hole t) sc) = do t' <- getPats t
sc' <- getPats sc
return (Bind n (Hole t') sc')
getPats (App s f a) = do f' <- getPats f
a' <- getPats a
return (App s f' a')
getPats t = return t
isEmpty :: Context -> Ctxt TypeInfo -> Type -> Bool
isEmpty ctxt tyctxt ty
| (P _ tyname _, args) <- unApply ty,
Just tyinfo <- lookupCtxtExact tyname tyctxt
-- Compare all the constructor types against the type we need
-- If they *all* have an argument position where some constructor
-- clashes with the needed type, then the type we're looking for must
-- be empty
= let neededty = getRetTy ty
contys = mapMaybe getConType (con_names tyinfo) in
all (findClash neededty) contys
where
getConType n = do t <- lookupTyExact n ctxt
return (getRetTy (normalise ctxt [] t))
findClash l r
| (P _ n _, _) <- unApply l,
(P _ n' _, _) <- unApply r,
isConName n ctxt && isConName n' ctxt, n /= n'
= True
findClash (App _ f a) (App _ f' a') = findClash f f' || findClash a a'
findClash l r = False
isEmpty ctxt tyinfo ty = False
hasEmptyPat :: Context -> Ctxt TypeInfo -> Term -> Bool
hasEmptyPat ctxt tyctxt (Bind n (PVar _ ty) sc)
= isEmpty ctxt tyctxt ty || hasEmptyPat ctxt tyctxt sc
hasEmptyPat ctxt tyctxt _ = False
-- Find names which are applied to a function in a Rig1 position
findLinear :: IState -> [Name] -> Term -> [(Name, RigCount)]
findLinear ist env tm | (P _ f _, args) <- unApply tm,
f `notElem` env,
Just ty_in <- lookupTyExact f (tt_ctxt ist)
= let ty = whnfArgs (tt_ctxt ist) [] ty_in in
nub $ concatMap (findLinear ist env) args ++ findLinArg ty args
where
findLinArg (Bind n (Pi c _ _ _) sc) (P _ a _ : as)
| Rig0 <- c = (a, c) : findLinArg sc as
| Rig1 <- c = (a, c) : findLinArg sc as
findLinArg (Bind n (Pi _ _ _ _) sc) (a : as)
= findLinArg (whnf (tt_ctxt ist) [] (substV a sc)) as
findLinArg _ _ = []
findLinear ist env (App _ f a)
= nub $ findLinear ist env f ++ findLinear ist env a
findLinear ist env (Bind n b sc) = findLinear ist (n : env) sc
findLinear ist _ _ = []
setLinear :: [(Name, RigCount)] -> Term -> Term
setLinear ns (Bind n b@(PVar r t) sc)
| Just r <- lookup n ns = Bind n (PVar r t) (setLinear ns sc)
| otherwise = Bind n b (setLinear ns sc)
setLinear ns tm = tm
linearArg :: Type -> Bool
linearArg (Bind n (Pi Rig1 _ _ _) sc) = True
linearArg (Bind n (Pi _ _ _ _) sc) = linearArg sc
linearArg _ = False
-- Rule out alternatives that don't return the same type as the head of the goal
-- (If there are none left as a result, do nothing)
pruneByType :: Bool -> -- In an impossible clause
Env -> Term -> -- head of the goal
Type -> -- goal
IState -> [PTerm] -> [PTerm]
-- if an alternative has a locally bound name at the head, take it
pruneByType imp env t goalty c as
| Just a <- locallyBound as = [a]
where
locallyBound [] = Nothing
locallyBound (t:ts)
| Just n <- getName t,
n `elem` map fstEnv env = Just t
| otherwise = locallyBound ts
getName (PRef _ _ n) = Just n
getName (PApp _ (PRef _ _ (UN l)) [_, _, arg]) -- ignore Delays
| l == txt "Delay" = getName (getTm arg)
getName (PApp _ f _) = getName f
getName (PHidden t) = getName t
getName _ = Nothing
-- 'n' is the name at the head of the goal type
pruneByType imp env (P _ n _) goalty ist as
-- if the goal type is polymorphic, keep everything
| Nothing <- lookupTyExact n ctxt = as
-- if the goal type is a ?metavariable, keep everything
| Just _ <- lookup n (idris_metavars ist) = as
| otherwise
= let asV = filter (headIs True n) as
as' = filter (headIs False n) as in
case as' of
[] -> asV
_ -> as'
where
ctxt = tt_ctxt ist
-- Get the function at the head of the alternative and see if it's
-- a plausible match against the goal type. Keep if so. Also keep if
-- there is a possible coercion to the goal type.
headIs var f (PRef _ _ f') = typeHead var f f'
headIs var f (PApp _ (PRef _ _ (UN l)) [_, _, arg])
| l == txt "Delay" = headIs var f (getTm arg)
headIs var f (PApp _ (PRef _ _ f') _) = typeHead var f f'
headIs var f (PApp _ f' _) = headIs var f f'
headIs var f (PPi _ _ _ _ sc) = headIs var f sc
headIs var f (PHidden t) = headIs var f t
headIs var f t = True -- keep if it's not an application
typeHead var f f'
= -- trace ("Trying " ++ show f' ++ " for " ++ show n) $
case lookupTyExact f' ctxt of
Just ty -> case unApply (getRetTy ty) of
(P _ ctyn _, _) | isTConName ctyn ctxt && not (ctyn == f)
-> False
_ -> let ty' = normalise ctxt [] ty in
-- trace ("Trying " ++ show f' ++ " : " ++ show (getRetTy ty') ++ " for " ++ show goalty
-- ++ "\nMATCH: " ++ show (pat, matching (getRetTy ty') goalty)) $
case unApply (getRetTy ty') of
(V _, _) ->
isPlausible ist var env n ty
_ -> matchingTypes imp (getRetTy ty') goalty
|| isCoercion (getRetTy ty') goalty
-- May be useful to keep for debugging purposes for a bit:
-- let res = matching (getRetTy ty') goalty in
-- traceWhen (not res)
-- ("Rejecting " ++ show (getRetTy ty', goalty)) res
_ -> False
matchingTypes True = matchingHead
matchingTypes False = matching
-- If the goal is a constructor, it must match the suggested function type
matching (P _ ctyn _) (P _ n' _)
| isTConName n' ctxt && isTConName ctyn ctxt = ctyn == n'
| otherwise = True
-- Variables match anything
matching (V _) _ = True
matching _ (V _) = True
matching _ (P _ n _) = not (isTConName n ctxt)
matching (P _ n _) _ = not (isTConName n ctxt)
-- Binders are a plausible match, so keep them
matching (Bind n _ sc) _ = True
matching _ (Bind n _ sc) = True
-- If we hit a function name, it's a plausible match
matching apl@(App _ _ _) apr@(App _ _ _)
| (P _ fl _, argsl) <- unApply apl,
(P _ fr _, argsr) <- unApply apr
= fl == fr && and (zipWith matching argsl argsr)
|| (not (isConName fl ctxt && isConName fr ctxt))
-- If the application structures aren't easily comparable, it's a
-- plausible match
matching (App _ f a) (App _ f' a') = True
matching (TType _) (TType _) = True
matching (UType _) (UType _) = True
matching l r = l == r
-- In impossible-case mode, only look at the heads (this is to account for
-- the non type-directed case with 'impossible' - we'd be ruling out
-- too much and wouldn't find the mismatch we're looking for)
matchingHead apl@(App _ _ _) apr@(App _ _ _)
| (P _ fl _, argsl) <- unApply apl,
(P _ fr _, argsr) <- unApply apr,
isConName fl ctxt && isConName fr ctxt
= fl == fr
matchingHead _ _ = True
-- Return whether there is a possible coercion between the return type
-- of an alternative and the goal type
isCoercion rty gty | (P _ r _, _) <- unApply rty
= not (null (getCoercionsBetween r gty))
isCoercion _ _ = False
getCoercionsBetween :: Name -> Type -> [Name]
getCoercionsBetween r goal
= let cs = getCoercionsTo ist goal in
findCoercions r cs
where findCoercions t [] = []
findCoercions t (n : ns) =
let ps = case lookupTy n (tt_ctxt ist) of
[ty'] -> let as = map snd (getArgTys (normalise (tt_ctxt ist) [] ty')) in
[n | any useR as]
_ -> [] in
ps ++ findCoercions t ns
useR ty =
case unApply (getRetTy ty) of
(P _ t _, _) -> t == r
_ -> False
pruneByType _ _ t _ _ as = as
-- Could the name feasibly be the return type?
-- If there is an interface constraint on the return type, and no implementation
-- in the environment or globally for that name, then no
-- Otherwise, yes
-- (FIXME: This isn't complete, but I'm leaving it here and coming back
-- to it later - just returns 'var' for now. EB)
isPlausible :: IState -> Bool -> Env -> Name -> Type -> Bool
isPlausible ist var env n ty
= let (hvar, interfaces) = collectConstraints [] [] ty in
case hvar of
Nothing -> True
Just rth -> var -- trace (show (rth, interfaces)) var
where
collectConstraints :: [Name] -> [(Term, [Name])] -> Type ->
(Maybe Name, [(Term, [Name])])
collectConstraints env tcs (Bind n (Pi _ _ ty _) sc)
= let tcs' = case unApply ty of
(P _ c _, _) ->
case lookupCtxtExact c (idris_interfaces ist) of
Just tc -> ((ty, map fst (interface_implementations tc))
: tcs)
Nothing -> tcs
_ -> tcs
in
collectConstraints (n : env) tcs' sc
collectConstraints env tcs t
| (V i, _) <- unApply t = (Just (env !! i), tcs)
| otherwise = (Nothing, tcs)
|
markuspf/Idris-dev
|
src/Idris/Elab/Utils.hs
|
bsd-3-clause
| 32,940 | 40 | 23 | 12,078 | 11,651 | 5,820 | 5,831 | 583 | 33 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module TestHpcCoverallsLix where
import Test.HUnit
import Trace.Hpc.Coveralls.Lix
import Trace.Hpc.Coveralls.Types
testToHit = "toHit" ~: [
Irrelevant @=? toHit [],
None @=? toHit [False],
None @=? toHit [False, False],
Partial @=? toHit [False, True],
Partial @=? toHit [True, False],
Partial @=? toHit [False, False, True],
Partial @=? toHit [False, True, False],
Partial @=? toHit [True, False, False],
Full @=? toHit [True],
Full @=? toHit [True, True]]
testLix = "Lix" ~: [testToHit]
|
jdnavarro/hpc-coveralls
|
test/TestHpcCoverallsLix.hs
|
bsd-3-clause
| 665 | 0 | 9 | 160 | 205 | 119 | 86 | 18 | 1 |
-- |
-- Language.Haskell.TH.Lib contains lots of useful helper functions for
-- generating and manipulating Template Haskell terms
-- Note: this module mostly re-exports functions from
-- Language.Haskell.TH.Lib.Internal, but if a change occurs to Template
-- Haskell which requires breaking the API offered in this module, we opt to
-- copy the old definition here, and make the changes in
-- Language.Haskell.TH.Lib.Internal. This way, we can retain backwards
-- compatibility while still allowing GHC to make changes as it needs.
module Language.Haskell.TH.Lib (
-- All of the exports from this module should
-- be "public" functions. The main module TH
-- re-exports them all.
-- * Library functions
-- ** Abbreviations
InfoQ, ExpQ, TExpQ, DecQ, DecsQ, ConQ, TypeQ, KindQ, TyVarBndrQ,
TyLitQ, CxtQ, PredQ, DerivClauseQ, MatchQ, ClauseQ, BodyQ, GuardQ,
StmtQ, RangeQ, SourceStrictnessQ, SourceUnpackednessQ, BangQ,
BangTypeQ, VarBangTypeQ, StrictTypeQ, VarStrictTypeQ, FieldExpQ, PatQ,
FieldPatQ, RuleBndrQ, TySynEqnQ, PatSynDirQ, PatSynArgsQ,
FamilyResultSigQ,
-- ** Constructors lifted to 'Q'
-- *** Literals
intPrimL, wordPrimL, floatPrimL, doublePrimL, integerL, rationalL,
charL, stringL, stringPrimL, charPrimL,
-- *** Patterns
litP, varP, tupP, unboxedTupP, unboxedSumP, conP, uInfixP, parensP,
infixP, tildeP, bangP, asP, wildP, recP,
listP, sigP, viewP,
fieldPat,
-- *** Pattern Guards
normalB, guardedB, normalG, normalGE, patG, patGE, match, clause,
-- *** Expressions
dyn, varE, unboundVarE, labelE, conE, litE, appE, appTypeE, uInfixE, parensE,
staticE, infixE, infixApp, sectionL, sectionR,
lamE, lam1E, lamCaseE, tupE, unboxedTupE, unboxedSumE, condE, multiIfE,
letE, caseE, appsE, listE, sigE, recConE, recUpdE, stringE, fieldExp,
-- **** Ranges
fromE, fromThenE, fromToE, fromThenToE,
-- ***** Ranges with more indirection
arithSeqE,
fromR, fromThenR, fromToR, fromThenToR,
-- **** Statements
doE, compE,
bindS, letS, noBindS, parS,
-- *** Types
forallT, varT, conT, appT, arrowT, infixT, uInfixT, parensT, equalityT,
listT, tupleT, unboxedTupleT, unboxedSumT, sigT, litT, wildCardT,
promotedT, promotedTupleT, promotedNilT, promotedConsT,
-- **** Type literals
numTyLit, strTyLit,
-- **** Strictness
noSourceUnpackedness, sourceNoUnpack, sourceUnpack,
noSourceStrictness, sourceLazy, sourceStrict,
isStrict, notStrict, unpacked,
bang, bangType, varBangType, strictType, varStrictType,
-- **** Class Contexts
cxt, classP, equalP,
-- **** Constructors
normalC, recC, infixC, forallC, gadtC, recGadtC,
-- *** Kinds
varK, conK, tupleK, arrowK, listK, appK, starK, constraintK,
-- *** Type variable binders
plainTV, kindedTV,
-- *** Roles
nominalR, representationalR, phantomR, inferR,
-- *** Top Level Declarations
-- **** Data
valD, funD, tySynD, dataD, newtypeD,
derivClause, DerivClause(..), DerivStrategy(..),
-- **** Class
classD, instanceD, instanceWithOverlapD, Overlap(..),
sigD, standaloneDerivD, standaloneDerivWithStrategyD, defaultSigD,
-- **** Role annotations
roleAnnotD,
-- **** Type Family / Data Family
dataFamilyD, openTypeFamilyD, closedTypeFamilyD, dataInstD,
newtypeInstD, tySynInstD,
tySynEqn, injectivityAnn, noSig, kindSig, tyVarSig,
-- **** Fixity
infixLD, infixRD, infixND,
-- **** Foreign Function Interface (FFI)
cCall, stdCall, cApi, prim, javaScript,
unsafe, safe, interruptible, forImpD,
-- **** Functional dependencies
funDep,
-- **** Pragmas
ruleVar, typedRuleVar,
valueAnnotation, typeAnnotation, moduleAnnotation,
pragInlD, pragSpecD, pragSpecInlD, pragSpecInstD, pragRuleD, pragAnnD,
pragLineD, pragCompleteD,
-- **** Pattern Synonyms
patSynD, patSynSigD, unidir, implBidir, explBidir, prefixPatSyn,
infixPatSyn, recordPatSyn,
-- ** Reify
thisModule
) where
import Language.Haskell.TH.Lib.Internal hiding
( tySynD
, dataD
, newtypeD
, classD
, dataInstD
, newtypeInstD
, dataFamilyD
, openTypeFamilyD
, closedTypeFamilyD
, forallC
, forallT
, sigT
, plainTV
, kindedTV
, starK
, constraintK
, noSig
, kindSig
, tyVarSig
, Role
, InjectivityAnn
)
import Language.Haskell.TH.Syntax
import Control.Monad (liftM2)
-- All definitions below represent the "old" API, since their definitions are
-- different in Language.Haskell.TH.Lib.Internal. Please think carefully before
-- deciding to change the APIs of the functions below, as they represent the
-- public API (as opposed to the Internal module, which has no API promises.)
-------------------------------------------------------------------------------
-- * Dec
tySynD :: Name -> [TyVarBndr] -> TypeQ -> DecQ
tySynD tc tvs rhs = do { rhs1 <- rhs; return (TySynD tc tvs rhs1) }
dataD :: CxtQ -> Name -> [TyVarBndr] -> Maybe Kind -> [ConQ] -> [DerivClauseQ]
-> DecQ
dataD ctxt tc tvs ksig cons derivs =
do
ctxt1 <- ctxt
cons1 <- sequence cons
derivs1 <- sequence derivs
return (DataD ctxt1 tc tvs ksig cons1 derivs1)
newtypeD :: CxtQ -> Name -> [TyVarBndr] -> Maybe Kind -> ConQ -> [DerivClauseQ]
-> DecQ
newtypeD ctxt tc tvs ksig con derivs =
do
ctxt1 <- ctxt
con1 <- con
derivs1 <- sequence derivs
return (NewtypeD ctxt1 tc tvs ksig con1 derivs1)
classD :: CxtQ -> Name -> [TyVarBndr] -> [FunDep] -> [DecQ] -> DecQ
classD ctxt cls tvs fds decs =
do
decs1 <- sequence decs
ctxt1 <- ctxt
return $ ClassD ctxt1 cls tvs fds decs1
dataInstD :: CxtQ -> Name -> [TypeQ] -> Maybe Kind -> [ConQ] -> [DerivClauseQ]
-> DecQ
dataInstD ctxt tc tys ksig cons derivs =
do
ctxt1 <- ctxt
tys1 <- sequence tys
cons1 <- sequence cons
derivs1 <- sequence derivs
return (DataInstD ctxt1 tc tys1 ksig cons1 derivs1)
newtypeInstD :: CxtQ -> Name -> [TypeQ] -> Maybe Kind -> ConQ -> [DerivClauseQ]
-> DecQ
newtypeInstD ctxt tc tys ksig con derivs =
do
ctxt1 <- ctxt
tys1 <- sequence tys
con1 <- con
derivs1 <- sequence derivs
return (NewtypeInstD ctxt1 tc tys1 ksig con1 derivs1)
dataFamilyD :: Name -> [TyVarBndr] -> Maybe Kind -> DecQ
dataFamilyD tc tvs kind
= return $ DataFamilyD tc tvs kind
openTypeFamilyD :: Name -> [TyVarBndr] -> FamilyResultSig
-> Maybe InjectivityAnn -> DecQ
openTypeFamilyD tc tvs res inj
= return $ OpenTypeFamilyD (TypeFamilyHead tc tvs res inj)
closedTypeFamilyD :: Name -> [TyVarBndr] -> FamilyResultSig
-> Maybe InjectivityAnn -> [TySynEqnQ] -> DecQ
closedTypeFamilyD tc tvs result injectivity eqns =
do eqns1 <- sequence eqns
return (ClosedTypeFamilyD (TypeFamilyHead tc tvs result injectivity) eqns1)
forallC :: [TyVarBndr] -> CxtQ -> ConQ -> ConQ
forallC ns ctxt con = liftM2 (ForallC ns) ctxt con
-------------------------------------------------------------------------------
-- * Type
forallT :: [TyVarBndr] -> CxtQ -> TypeQ -> TypeQ
forallT tvars ctxt ty = do
ctxt1 <- ctxt
ty1 <- ty
return $ ForallT tvars ctxt1 ty1
sigT :: TypeQ -> Kind -> TypeQ
sigT t k
= do
t' <- t
return $ SigT t' k
-------------------------------------------------------------------------------
-- * Kind
plainTV :: Name -> TyVarBndr
plainTV = PlainTV
kindedTV :: Name -> Kind -> TyVarBndr
kindedTV = KindedTV
starK :: Kind
starK = StarT
constraintK :: Kind
constraintK = ConstraintT
-------------------------------------------------------------------------------
-- * Type family result
noSig :: FamilyResultSig
noSig = NoSig
kindSig :: Kind -> FamilyResultSig
kindSig = KindSig
tyVarSig :: TyVarBndr -> FamilyResultSig
tyVarSig = TyVarSig
|
shlevy/ghc
|
libraries/template-haskell/Language/Haskell/TH/Lib.hs
|
bsd-3-clause
| 7,977 | 0 | 11 | 1,758 | 1,895 | 1,109 | 786 | 159 | 1 |
{-# LANGUAGE PackageImports, CPP, LambdaCase, TupleSections, RecordWildCards #-}
import Data.IORef
import Data.Maybe
import Data.Char (toLower)
import qualified Data.Map as Map
import Control.Concurrent
import Control.Monad
import System.Environment
import System.FilePath
import System.Directory
import System.IO
import System.Exit
import qualified System.Mem
import "GLFW-b" Graphics.UI.GLFW as GLFW
import Graphics.GL.Core33
import FRP.Elerea.Param
import LambdaCube.GL as GL
import Sound.ProteaAudio
import Camera
import Engine
import GameEngine.Loader.Zip
import qualified Data.ByteString.Char8 as SB8
#ifdef CAPTURE
import Codec.Image.DevIL
import Text.Printf
import Foreign
#endif
type Sink a = a -> IO ()
#ifdef CAPTURE
-- framebuffer capture function
withFrameBuffer :: Int -> Int -> Int -> Int -> (Ptr Word8 -> IO ()) -> IO ()
withFrameBuffer x y w h fn = allocaBytes (w*h*4) $ \p -> do
glReadPixels (fromIntegral x) (fromIntegral y) (fromIntegral w) (fromIntegral h) GL_RGBA GL_UNSIGNED_BYTE $ castPtr p
fn p
#endif
captureRate :: Double
captureRate = 30
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
--hSetBuffering stdin NoBuffering
#ifdef CAPTURE
ilInit
#endif
noPak0_pk3 <- null . filter (\n -> "pak0.pk3" == map toLower n) <$> getDirectoryContents "."
when noPak0_pk3 $ die "Could not find pak0.pk3. See how to run: https://github.com/lambdacube3d/lambdacube-quake3/blob/master/README.md"
pk3Data <- loadPK3
args <- getArgs
let bspNames = [n | n <- Map.keys pk3Data, ".bsp" == takeExtension n]
fullBSPName <- head <$> case args of
(n:xs) -> return $ filter ((== n) . takeBaseName) bspNames
_ -> do
let maps = map takeBaseName bspNames
putStrLn $ "Available maps:"
putStrLn $ unwords maps
putStrLn "Enter map name:"
name <- getLine
return $ filter ((name ==) . takeBaseName) bspNames
let bspName = takeBaseName fullBSPName
win <- initWindow "LC DSL Quake 3 Demo" 800 600
-- loading screen
loadingScreen <- createLoadingScreen
(w,h) <- getFramebufferSize win
drawLoadingScreen w h loadingScreen pk3Data bspName
swapBuffers win
pollEvents
initAudio 64 44100 1024
(inputSchema,levelData) <- engineInit pk3Data fullBSPName
-- compile graphics pipeline
let pplName = bspName ++ "_ppl.json"
compileRequest <- newIORef False
compileReady <- newIORef False
_ <- forkIO $ forever $ do -- start compile thread
putStrLn "start to compile"
writeIORef compileRequest False
writeIORef compileReady False
compileQuake3GraphicsCached pplName >>= writeIORef compileReady
putStrLn "compile finished"
let loop = do
req <- readIORef compileRequest
threadDelay 100000 -- 10 / sec
unless req loop
loop
-- upload graphics data to GPU
storage <- allocStorage inputSchema
graphicsData <- setupStorage pk3Data levelData storage
putStrLn "storage created"
simpleRenderer <- fromJust <$> loadQuake3Graphics storage "SimpleGraphics.json"
setStorage simpleRenderer storage
rendererRef <- newIORef =<< fromJust <$> loadQuake3Graphics storage "SimpleGraphics.json"
-- play level music
case getMusicFile levelData of
Nothing -> return ()
Just musicFName' -> let musicFName = map f musicFName'
f '\\' = '/'
f c = c
in case Map.lookup musicFName pk3Data of
Nothing -> return ()
Just e -> do
buf <- readEntry e
-- load from memory buffer
smp' <- case takeExtension musicFName of
".ogg" -> sampleFromMemoryOgg buf 1
".wav" -> sampleFromMemoryWav buf 1
soundPlay smp' 1 1 0 1
(mousePosition,mousePositionSink) <- unsafeExternal (0,0)
(fblrPress,fblrPressSink) <- unsafeExternal (False,False,False,False,False,False)
(capturePress,capturePressSink) <- unsafeExternal False
(waypointPress,waypointPressSink) <- unsafeExternal []
let draw (captureA,debugRender) = do
if debugRender
then renderFrame simpleRenderer
else readIORef rendererRef >>= renderFrame
captureA
swapBuffers win
System.Mem.performMinorGC
pollEvents
cleanupResources = do
-- render the first frame to force resource loading
renderFrame simpleRenderer
readIORef rendererRef >>= renderFrame
-- cleanup dead data
System.Mem.performGC
capRef <- newIORef False
sc <- start $ do
u <- scene win levelData graphicsData mousePosition fblrPress capturePress waypointPress capRef
return $ (draw <$> u)
s <- fpsState
-- finish up resource loading
cleanupResources
setTime 0
driveNetwork sc (readInput compileRequest compileReady pplName rendererRef storage win s mousePositionSink fblrPressSink capturePressSink waypointPressSink capRef)
disposeRenderer =<< readIORef rendererRef
putStrLn "storage destroyed"
finishAudio
destroyWindow win
edge :: Signal Bool -> SignalGen p (Signal Bool)
edge s = transfer2 False (\_ cur prev _ -> cur && not prev) s =<< delay False s
upEdge :: Signal Bool -> SignalGen p (Signal Bool)
upEdge s = transfer2 False (\_ cur prev _ -> cur && prev == False) s =<< delay False s
scene win levelData graphicsData mousePosition fblrPress capturePress waypointPress capRef = do
time <- stateful 0 (+)
last2 <- transfer ((0,0),(0,0)) (\_ n (_,b) -> (b,n)) mousePosition
let mouseMove = (\((ox,oy),(nx,ny)) -> (nx-ox,ny-oy)) <$> last2
bsp = getBSP levelData
p0 = head . drop 1 . cycle $ getSpawnPoints levelData
fblrPress' <- do
j' <- upEdge $ (\(w,a,s,d,t,j) -> j) <$> fblrPress
return $ (\(w,a,s,d,t,_) j' -> (w,a,s,d,t,j')) <$> fblrPress <*> j'
controlledCamera <- userCamera (getTeleportFun levelData) bsp p0 mouseMove fblrPress'
frameCount <- stateful (0 :: Int) (\_ c -> c + 1)
capture <- transfer2 False (\_ cap cap' on -> on /= (cap && not cap')) capturePress =<< delay False capturePress
{-
[clearWaypoints, setWaypoint, stopPlayback, startPlayback, incPlaybackSpeed, decPlaybackSpeed] <-
forM (zip [edge, edge, edge, edge, return, return] [0..]) $ \(process, i) -> process (fmap (!! i) waypointPress)
waypoints <- recordSignalSamples setWaypoint clearWaypoints ((\(camPos, targetPos, _, _) -> (camPos, targetPos)) <$> controlledCamera)
playbackSpeed <- transfer2 100 (\dt inc dec speed -> speed + 10*dt*(if inc then 1 else if dec then -1 else 0)) incPlaybackSpeed decPlaybackSpeed
splineCamera <- playbackCamera startPlayback stopPlayback playbackSpeed waypoints
let activeCamera = do
camData <- splineCamera
case camData of
Nothing -> controlledCamera
Just camData -> return camData
-}
let activeCamera = controlledCamera
let setupGFX (camPos,camTarget,camUp,brushIndex) time (capturing,frameCount) = do
(w,h) <- getFramebufferSize win
-- hack
let keyIsPressed k = fmap (==KeyState'Pressed) $ getKey win k
noBSPCull <- keyIsPressed (Key'X)
debugRender <- keyIsPressed (Key'C)
updateRenderInput graphicsData (camPos,camTarget,camUp) w h time noBSPCull
{-
when (not $ null brushIndex) $ do
putStrLn $ "brush collision: " ++ show (map (getModelIndexFromBrushIndex levelData) brushIndex)
-}
let captureA = do
#ifdef CAPTURE
when capturing $ do
glFinish
withFrameBuffer 0 0 w h $ \p -> writeImageFromPtr (printf "frame%08d.jpg" frameCount) (h,w) p
writeIORef capRef capturing
#endif
return ()
return (captureA,debugRender)
r <- effectful3 setupGFX activeCamera time ((,) <$> capture <*> frameCount)
return r
readInput compileRequest compileReady pplName rendererRef storage win s mousePos fblrPress capturePress waypointPress capRef = do
let keyIsPressed k = fmap (==KeyState'Pressed) $ getKey win k
t <- maybe 0 id <$> getTime
setTime 0
(x,y) <- getCursorPos win
mousePos (realToFrac x,realToFrac y)
fblrPress =<< ((,,,,,) <$> keyIsPressed Key'A <*> keyIsPressed Key'W <*> keyIsPressed Key'S <*> keyIsPressed Key'D
<*> keyIsPressed Key'RightShift <*> keyIsPressed Key'Space)
capturePress =<< keyIsPressed Key'P
waypointPress =<< mapM keyIsPressed [Key'R,Key'E,Key'1,Key'2,Key'F,Key'G]
isCapturing <- readIORef capRef
let dt = if isCapturing then recip captureRate else realToFrac t
updateFPS s dt
reload <- keyIsPressed Key'L
when reload $ writeIORef compileRequest True
readIORef compileReady >>= \case
False -> return ()
True -> do
writeIORef compileReady False
loadQuake3Graphics storage pplName >>= \case
Nothing -> return ()
Just a -> do
readIORef rendererRef >>= disposeRenderer
writeIORef rendererRef a
k <- keyIsPressed Key'Escape
return $ if k then Nothing else Just (min 0.1 $ realToFrac dt) -- simulation must run at least 10 FPS, under 10 FPS won't be realtime
-- FRP boilerplate
driveNetwork :: (p -> IO (IO a)) -> IO (Maybe p) -> IO ()
driveNetwork network driver = do
dt <- driver
case dt of
Just dt -> do
join $ network dt
driveNetwork network driver
Nothing -> return ()
-- OpenGL/GLFW boilerplate
initWindow :: String -> Int -> Int -> IO Window
initWindow title width height = do
GLFW.init
defaultWindowHints
mapM_ windowHint
[ WindowHint'ContextVersionMajor 3
, WindowHint'ContextVersionMinor 3
, WindowHint'OpenGLProfile OpenGLProfile'Core
, WindowHint'OpenGLForwardCompat True
]
Just win <- createWindow width height title Nothing Nothing
makeContextCurrent $ Just win
glEnable GL_FRAMEBUFFER_SRGB
swapInterval 0
return win
-- FPS tracking
data State = State { frames :: IORef Int, t0 :: IORef Double }
fpsState :: IO State
fpsState = State <$> newIORef 0 <*> newIORef 0
updateFPS :: State -> Double -> IO ()
updateFPS state t1 = do
let t = 1000*t1
fR = frames state
tR = t0 state
modifyIORef fR (+1)
t0' <- readIORef tR
writeIORef tR $ t0' + t
when (t + t0' >= 5000) $ do
f <- readIORef fR
let seconds = (t + t0') / 1000
fps = fromIntegral f / seconds
putStrLn (show (round fps) ++ " FPS - " ++ show f ++ " frames in " ++ show seconds)
writeIORef tR 0
writeIORef fR 0
|
csabahruska/quake3
|
mapviewer/Main.hs
|
bsd-3-clause
| 10,835 | 9 | 24 | 2,817 | 3,086 | 1,486 | 1,600 | 206 | 7 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_HADDOCK hide #-}
module Distribution.Compat.Internal.TempFile (
openTempFile,
openBinaryTempFile,
openNewBinaryFile,
createTempDirectory,
) where
import System.FilePath ((</>))
import Foreign.C (eEXIST)
import System.IO (Handle, openTempFile, openBinaryTempFile)
import Data.Bits ((.|.))
import System.Posix.Internals (c_open, c_close, o_CREAT, o_EXCL, o_RDWR,
o_BINARY, o_NONBLOCK, o_NOCTTY)
import System.IO.Error (isAlreadyExistsError)
import System.Posix.Internals (withFilePath)
import Foreign.C (CInt)
import GHC.IO.Handle.FD (fdToHandle)
import Distribution.Compat.Exception (tryIO)
import Control.Exception (onException)
import Foreign.C (getErrno, errnoToIOError)
import System.Posix.Internals (c_getpid)
#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS)
import System.Directory ( createDirectory )
#else
import qualified System.Posix
#endif
-- ------------------------------------------------------------
-- * temporary files
-- ------------------------------------------------------------
-- This is here for Haskell implementations that do not come with
-- System.IO.openTempFile. This includes nhc-1.20, hugs-2006.9.
-- TODO: Not sure about JHC
-- TODO: This file should probably be removed.
-- This is a copy/paste of the openBinaryTempFile definition, but
-- if uses 666 rather than 600 for the permissions. The base library
-- needs to be changed to make this better.
openNewBinaryFile :: FilePath -> String -> IO (FilePath, Handle)
openNewBinaryFile dir template = do
pid <- c_getpid
findTempName pid
where
-- We split off the last extension, so we can use .foo.ext files
-- for temporary files (hidden on Unix OSes). Unfortunately we're
-- below file path in the hierarchy here.
(prefix,suffix) =
case break (== '.') $ reverse template of
-- First case: template contains no '.'s. Just re-reverse it.
(rev_suffix, "") -> (reverse rev_suffix, "")
-- Second case: template contains at least one '.'. Strip the
-- dot from the prefix and prepend it to the suffix (if we don't
-- do this, the unique number will get added after the '.' and
-- thus be part of the extension, which is wrong.)
(rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
-- Otherwise, something is wrong, because (break (== '.')) should
-- always return a pair with either the empty string or a string
-- beginning with '.' as the second component.
_ -> error "bug in System.IO.openTempFile"
oflags = rw_flags .|. o_EXCL .|. o_BINARY
findTempName x = do
fd <- withFilePath filepath $ \ f ->
c_open f oflags 0o666
if fd < 0
then do
errno <- getErrno
if errno == eEXIST
then findTempName (x+1)
else ioError (errnoToIOError "openNewBinaryFile" errno Nothing (Just dir))
else do
-- TODO: We want to tell fdToHandle what the file path is,
-- as any exceptions etc will only be able to report the
-- FD currently
h <- fdToHandle fd `onException` c_close fd
return (filepath, h)
where
filename = prefix ++ show x ++ suffix
filepath = dir `combine` filename
-- FIXME: bits copied from System.FilePath
combine a b
| null b = a
| null a = b
| last a == pathSeparator = a ++ b
| otherwise = a ++ [pathSeparator] ++ b
-- FIXME: Should use System.FilePath library
pathSeparator :: Char
#ifdef mingw32_HOST_OS
pathSeparator = '\\'
#else
pathSeparator = '/'
#endif
-- FIXME: Copied from GHC.Handle
std_flags, output_flags, rw_flags :: CInt
std_flags = o_NONBLOCK .|. o_NOCTTY
output_flags = std_flags .|. o_CREAT
rw_flags = output_flags .|. o_RDWR
createTempDirectory :: FilePath -> String -> IO FilePath
createTempDirectory dir template = do
pid <- c_getpid
findTempName pid
where
findTempName x = do
let dirpath = dir </> template ++ "-" ++ show x
r <- tryIO $ mkPrivateDir dirpath
case r of
Right _ -> return dirpath
Left e | isAlreadyExistsError e -> findTempName (x+1)
| otherwise -> ioError e
mkPrivateDir :: String -> IO ()
#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS)
mkPrivateDir s = createDirectory s
#else
mkPrivateDir s = System.Posix.createDirectory s 0o700
#endif
|
thoughtpolice/cabal
|
Cabal/Distribution/Compat/Internal/TempFile.hs
|
bsd-3-clause
| 4,660 | 0 | 17 | 1,235 | 844 | 466 | 378 | 70 | 5 |
{-# LANGUAGE DataKinds, GADTs, KindSignatures, RebindableSyntax #-}
module Inhabitants (Inhabitable(..), Nat'(..)) where
import qualified Prelude as P
import Prelude (Show (..), Bool (..), ($), error, undefined, const, (.), flip)
import Data.List
data Nat' = Z' | S' Nat'
class Inhabitable (ent :: Bool -> Nat' -> *) where
starN :: ent True (S' (S' n))
(^) :: ent o (S' l) -> ent o' (S' l) -> ent o (S' l) -- exponent
inhabit :: ent True (S' l) -> (ent True l -> ent o l') -> ent False l'
isle :: ent o l -> ent False (S' l)
descope :: ent o l -> ent False l
class LC (ent :: Bool -> Nat' -> *) where
lam :: (ent False l -> ent False l) -> ent False l
(&) :: ent o l -> ent p l -> ent False l
-- #### Implement these in terms of the Lambda-Pi calculus
--
data Lam open lev where
App :: Lam o l -> Lam p l -> Lam False l
Inh :: Lam True (S' l) -> (Lam True l -> Lam o l') -> Lam False l'
Star :: Lam True (S' (S' n))
(:~>) :: Lam o' l -> Lam o l -> Lam o l -- FIXME: this should be some Pi!
Close :: Lam True l -> Lam False l
Habitant :: Lam True (S' l) -> Lam True l -- needed for concretising
Univar :: P.String -> Lam o (S' l) -> Lam True l -- later this will be location based
Lam :: (Lam False l -> Lam False l) -> Lam False l
Pi :: (Lam False l -> Lam False (S' l)) -> Lam False (S' l)
instance Show (Lam o l) where
show Star = "*"
show (a :~> b) = show a ++ " :~> " ++ show b
show (Close a) = '[' : (show a ++ "]")
show (Habitant a) = "habitant of " ++ show a
show (Univar n a) = "|" ++ n ++ "| of " ++ show a
show (Inh isle f) = "Below " ++ show isle ++ " is a " ++ show (f (Habitant isle))
show (f `App` a) = "(" ++ show f ++ " & " ++show a ++ ")"
show (Lam f) = "(\\" ++ show inp ++ " . " ++ show (f inp) ++ ")"
where inp = Close (Univar "var" $ Habitant Star) -- FIXME
--where inp = Close (Habitant $ Habitant Star) -- FIXME
instance Inhabitable Lam where
starN = Star
(^) = flip (:~>)
inhabit = Inh
isle Star = Close Star
isle (Close a) = isle a
isle (Habitant a) = Close a
isle (Lam f) = Pi $ isle . f
isle (Pi f) = Close Star
descope (Inh isle f) = descope $ f $ Habitant isle
descope (f `App` a) = descope f `App` descope a
descope cs@Close{} = cs
descope ho@Habitant{} = Close ho
descope (Lam f) = Lam $ \x -> descope $ f x -- inefficient!
descope whatever = error $ " ##### how to descope this: ### " ++ show whatever
star :: Inhabitable ent => ent True (S' (S' Z'))
star = starN
(>>=) :: Inhabitable ent => ent True (S' l) -> (ent True l -> ent o l') -> ent False l'
isle >>= scope = descope $ inhabit isle scope
instance LC Lam where
lam = Lam
(&) = App
--return :: Inhabitable ent => ent o l -> ent False l
return = undefined
fail = error
knoth :: (Inhabitable ent, LC ent) => ent False Z'
knoth = do int <- star
i <- int
j <- int
-- k <- int & int -- Error: not open, good
-- sub <- i -- Error: cannot descend below zero, good
i & j
exp :: Inhabitable ent => ent False (S' Z')
exp = do maybe <- star^star
maybe
regain :: Inhabitable ent => ent False (S' Z')
regain = do int <- star
i <- int
isle i
func :: (Inhabitable ent, LC ent) => ent False Z'
func = do int <- star
i <- int
j <- int
let k = lam (\c -> lam (const c))
k & i & j
|
cartazio/omega
|
mosaic/Inhabitants.hs
|
bsd-3-clause
| 3,399 | 0 | 15 | 968 | 1,558 | 792 | 766 | 77 | 1 |
test y = let x = 1
in (x, y, y)
|
themattchan/tandoori
|
input/class-cascade-let.hs
|
bsd-3-clause
| 41 | 1 | 8 | 20 | 32 | 15 | 17 | 2 | 1 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE ImplicitParams, RankNTypes #-}
-- #1445
module Bug where
f :: () -> (?p :: ()) => () -> ()
f _ _ = ()
g :: (?p :: ()) => ()
g = f () ()
|
sdiehl/ghc
|
testsuite/tests/typecheck/should_compile/tc230.hs
|
bsd-3-clause
| 205 | 0 | 8 | 46 | 81 | 47 | 34 | 7 | 1 |
module Opaleye.SQLite.Internal.Optimize where
import Prelude hiding (product)
import qualified Opaleye.SQLite.Internal.PrimQuery as PQ
import qualified Data.List.NonEmpty as NEL
optimize :: PQ.PrimQuery -> PQ.PrimQuery
optimize = mergeProduct . removeUnit
removeUnit :: PQ.PrimQuery -> PQ.PrimQuery
removeUnit = PQ.foldPrimQuery (PQ.Unit, PQ.BaseTable, product, PQ.Aggregate,
PQ.Order, PQ.Limit, PQ.Join, PQ.Values,
PQ.Binary)
where product pqs pes = PQ.Product pqs' pes
where pqs' = case NEL.filter (not . PQ.isUnit) pqs of
[] -> return PQ.Unit
xs -> NEL.fromList xs
mergeProduct :: PQ.PrimQuery -> PQ.PrimQuery
mergeProduct = PQ.foldPrimQuery (PQ.Unit, PQ.BaseTable, product, PQ.Aggregate,
PQ.Order, PQ.Limit, PQ.Join, PQ.Values,
PQ.Binary)
where product pqs pes = PQ.Product pqs' (pes ++ pes')
where pqs' = pqs >>= queries
queries (PQ.Product qs _) = qs
queries q = return q
pes' = NEL.toList pqs >>= conds
conds (PQ.Product _ cs) = cs
conds _ = []
|
bergmark/haskell-opaleye
|
opaleye-sqlite/src/Opaleye/SQLite/Internal/Optimize.hs
|
bsd-3-clause
| 1,250 | 0 | 13 | 428 | 368 | 203 | 165 | 25 | 3 |
{-# LANGUAGE CPP, Rank2Types, FlexibleContexts, MultiParamTypeClasses #-}
-- |
-- Module : Data.Vector.Generic.New
-- Copyright : (c) Roman Leshchinskiy 2008-2010
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Purely functional interface to initialisation of mutable vectors
--
module Data.Vector.Generic.New (
New(..), create, run, runPrim, apply, modify, modifyWithBundle,
unstream, transform, unstreamR, transformR,
slice, init, tail, take, drop,
unsafeSlice, unsafeInit, unsafeTail
) where
import qualified Data.Vector.Generic.Mutable as MVector
import Data.Vector.Generic.Base ( Vector, Mutable )
import Data.Vector.Fusion.Bundle ( Bundle )
import qualified Data.Vector.Fusion.Bundle as Bundle
import Data.Vector.Fusion.Stream.Monadic ( Stream )
import Data.Vector.Fusion.Bundle.Size
import Control.Monad.Primitive
import Control.Monad.ST ( ST )
import Control.Monad ( liftM )
import Prelude hiding ( init, tail, take, drop, reverse, map, filter )
-- Data.Vector.Internal.Check is unused
#define NOT_VECTOR_MODULE
#include "vector.h"
data New v a = New (forall s. ST s (Mutable v s a))
create :: (forall s. ST s (Mutable v s a)) -> New v a
{-# INLINE create #-}
create p = New p
run :: New v a -> ST s (Mutable v s a)
{-# INLINE run #-}
run (New p) = p
runPrim :: PrimMonad m => New v a -> m (Mutable v (PrimState m) a)
{-# INLINE runPrim #-}
runPrim (New p) = primToPrim p
apply :: (forall s. Mutable v s a -> Mutable v s a) -> New v a -> New v a
{-# INLINE apply #-}
apply f (New p) = New (liftM f p)
modify :: (forall s. Mutable v s a -> ST s ()) -> New v a -> New v a
{-# INLINE modify #-}
modify f (New p) = New (do { v <- p; f v; return v })
modifyWithBundle :: (forall s. Mutable v s a -> Bundle u b -> ST s ())
-> New v a -> Bundle u b -> New v a
{-# INLINE_FUSED modifyWithBundle #-}
modifyWithBundle f (New p) s = s `seq` New (do { v <- p; f v s; return v })
unstream :: Vector v a => Bundle v a -> New v a
{-# INLINE_FUSED unstream #-}
unstream s = s `seq` New (MVector.vunstream s)
transform
:: Vector v a => (forall m. Monad m => Stream m a -> Stream m a)
-> (Size -> Size) -> New v a -> New v a
{-# INLINE_FUSED transform #-}
transform f _ (New p) = New (MVector.transform f =<< p)
{-# RULES
"transform/transform [New]"
forall (f1 :: forall m. Monad m => Stream m a -> Stream m a)
(f2 :: forall m. Monad m => Stream m a -> Stream m a)
g1 g2 p .
transform f1 g1 (transform f2 g2 p) = transform (f1 . f2) (g1 . g2) p
"transform/unstream [New]"
forall (f :: forall m. Monad m => Stream m a -> Stream m a)
g s.
transform f g (unstream s) = unstream (Bundle.inplace f g s) #-}
unstreamR :: Vector v a => Bundle v a -> New v a
{-# INLINE_FUSED unstreamR #-}
unstreamR s = s `seq` New (MVector.unstreamR s)
transformR
:: Vector v a => (forall m. Monad m => Stream m a -> Stream m a)
-> (Size -> Size) -> New v a -> New v a
{-# INLINE_FUSED transformR #-}
transformR f _ (New p) = New (MVector.transformR f =<< p)
{-# RULES
"transformR/transformR [New]"
forall (f1 :: forall m. Monad m => Stream m a -> Stream m a)
(f2 :: forall m. Monad m => Stream m a -> Stream m a)
g1 g2
p .
transformR f1 g1 (transformR f2 g2 p) = transformR (f1 . f2) (g1 . g2) p
"transformR/unstreamR [New]"
forall (f :: forall m. Monad m => Stream m a -> Stream m a)
g s.
transformR f g (unstreamR s) = unstreamR (Bundle.inplace f g s) #-}
slice :: Vector v a => Int -> Int -> New v a -> New v a
{-# INLINE_FUSED slice #-}
slice i n m = apply (MVector.slice i n) m
init :: Vector v a => New v a -> New v a
{-# INLINE_FUSED init #-}
init m = apply MVector.init m
tail :: Vector v a => New v a -> New v a
{-# INLINE_FUSED tail #-}
tail m = apply MVector.tail m
take :: Vector v a => Int -> New v a -> New v a
{-# INLINE_FUSED take #-}
take n m = apply (MVector.take n) m
drop :: Vector v a => Int -> New v a -> New v a
{-# INLINE_FUSED drop #-}
drop n m = apply (MVector.drop n) m
unsafeSlice :: Vector v a => Int -> Int -> New v a -> New v a
{-# INLINE_FUSED unsafeSlice #-}
unsafeSlice i n m = apply (MVector.unsafeSlice i n) m
unsafeInit :: Vector v a => New v a -> New v a
{-# INLINE_FUSED unsafeInit #-}
unsafeInit m = apply MVector.unsafeInit m
unsafeTail :: Vector v a => New v a -> New v a
{-# INLINE_FUSED unsafeTail #-}
unsafeTail m = apply MVector.unsafeTail m
{-# RULES
"slice/unstream [New]" forall i n s.
slice i n (unstream s) = unstream (Bundle.slice i n s)
"init/unstream [New]" forall s.
init (unstream s) = unstream (Bundle.init s)
"tail/unstream [New]" forall s.
tail (unstream s) = unstream (Bundle.tail s)
"take/unstream [New]" forall n s.
take n (unstream s) = unstream (Bundle.take n s)
"drop/unstream [New]" forall n s.
drop n (unstream s) = unstream (Bundle.drop n s)
"unsafeSlice/unstream [New]" forall i n s.
unsafeSlice i n (unstream s) = unstream (Bundle.slice i n s)
"unsafeInit/unstream [New]" forall s.
unsafeInit (unstream s) = unstream (Bundle.init s)
"unsafeTail/unstream [New]" forall s.
unsafeTail (unstream s) = unstream (Bundle.tail s) #-}
|
dolio/vector
|
Data/Vector/Generic/New.hs
|
bsd-3-clause
| 5,326 | 0 | 11 | 1,232 | 1,427 | 748 | 679 | 101 | 1 |
-----------------------------------------------------------------------------
--
-- Module : IDE.Command.VCS.Common.GUI
-- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL Nothing
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.Command.VCS.Common.GUI (
-- addMenuForPackage
) where
--import IDE.Core.Types
--import IDE.Core.State
--
--import Graphics.UI.Gtk (
-- menuNew, menuItemNewWithLabel, onActivateLeaf, menuShellAppend, menuItemSetSubmenu
-- ,widgetShowAll, menuItemNewWithMnemonic, menuItemGetSubmenu, widgetHideAll, widgetDestroy)
--import Control.Monad.Reader(liftIO,ask,when)
--vcsMenu from
-- vcsItem <- GUIUtils.getVCS
-- vcsMenu <- liftIO $ menuNew
-- ideR from ask
-- setupRepoAction actionContext packageMenuOperations from common
--addMenuForPackage cabalFp = do
-- packageItem <- liftIO $ menuItemNewWithLabel cabalFp
-- packageMenu <- liftIO $ menuNew
--
-- -- set-up repo action
-- actionItem <- liftIO $ menuItemNewWithMnemonic "_Setup Repo"
-- liftIO $ actionItem `onActivateLeaf` (
-- reflectIDE (
-- setupRepoAction cabalFp
-- ) ideR)
-- liftIO $ menuShellAppend packageMenu actionItem
--
-- -- other actions if repo set
-- liftIO $ addActions cabalFp packageMenu ideR packageMenuOperations actionContext
--
-- liftIO $ menuItemSetSubmenu packageItem packageMenu
-- liftIO $ menuShellAppend vcsMenu packageItem
-- where
-- addActions cabalFp packageMenu ideR actions runner = mapM_ (\(name,action) -> do
-- -- for each operation add it to menu and connect action
-- actionItem <- menuItemNewWithMnemonic name
-- actionItem `onActivateLeaf` (reflectIDE (runner action cabalFp) ideR)
-- menuShellAppend packageMenu actionItem
-- ) actions
|
573/leksah
|
src/IDE/Command/VCS/Common/GUI.hs
|
gpl-2.0
| 2,322 | 0 | 3 | 705 | 62 | 59 | 3 | 1 | 0 |
{-# LANGUAGE TypeFamilies #-}
module ShouldCompile where
import Data.Kind (Type)
class C1 a where
data S1 a :: Type
-- instance of data families can be data or newtypes
instance C1 Char where
newtype S1 Char = S1Char ()
|
sdiehl/ghc
|
testsuite/tests/indexed-types/should_compile/Simple7.hs
|
bsd-3-clause
| 228 | 0 | 7 | 47 | 54 | 31 | 23 | -1 | -1 |
module ListWatched where
import qualified Github.Repos.Watching as Github
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
main = do
possibleRepos <- Github.reposWatchedBy "mike-burns"
putStrLn $ either (("Error: "++) . show)
(intercalate "\n\n" . map formatRepo)
possibleRepos
formatRepo repo =
(Github.repoName repo) ++ "\t" ++
(fromMaybe "" $ Github.repoDescription repo) ++ "\n" ++
(Github.repoHtmlUrl repo) ++ "\n" ++
(Github.repoCloneUrl repo) ++ "\t" ++
(formatDate $ Github.repoUpdatedAt repo) ++ "\n" ++
formatLanguage (Github.repoLanguage repo) ++
"watchers: " ++ (show $ Github.repoWatchers repo) ++ "\t" ++
"forks: " ++ (show $ Github.repoForks repo)
formatDate = show . Github.fromGithubDate
formatLanguage (Just language) = "language: " ++ language ++ "\t"
formatLanguage Nothing = ""
|
mavenraven/github
|
samples/Repos/Watching/ListWatched.hs
|
bsd-3-clause
| 890 | 0 | 22 | 186 | 283 | 146 | 137 | 21 | 1 |
module HAD.Y2014.M02.D26.Solution where
-- | Sum the value inside the maybe if there aren't any Nothing,
-- otherwise return Nothing
--
-- Examples
--
-- >>> sumIfAll [Just 1, Just 2]
-- Just 3
--
-- >>> sumIfAll [Just 1, Nothing]
-- Nothing
--
sumIfAll :: Num a => [Maybe a] -> Maybe a
sumIfAll = fmap sum . sequence
|
1HaskellADay/1HAD
|
exercises/HAD/Y2014/M02/D26/Solution.hs
|
mit
| 321 | 0 | 8 | 63 | 57 | 36 | 21 | 3 | 1 |
{-# LANGUAGE GADTs #-}
-- Involves an equality that is not an existential
module Foo2 where
data T t a where
T :: a -> T () a
foo :: (a -> a) -> T t a -> T t a
foo f (T x) = T (f x)
bar :: T t Int -> T t Int
bar t@(T _) = foo (+1) t
|
shlevy/ghc
|
testsuite/tests/gadt/gadt19.hs
|
bsd-3-clause
| 242 | 0 | 8 | 74 | 128 | 68 | 60 | 8 | 1 |
module ShouldCompile where
import Foreign
-- !!! test that a recursive newtype can be used as an argument or result
-- type of a foreign import.
newtype T = T (Ptr T)
foreign import ccall foo :: T -> IO T
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/ffi/should_compile/cc011.hs
|
bsd-3-clause
| 209 | 0 | 7 | 45 | 40 | 24 | 16 | 4 | 0 |
module JoinList where
import Data.Monoid
import Sized
import Scrabble
data JoinList m a = Empty
| Single m a
| Append m (JoinList m a) (JoinList m a)
deriving (Eq, Show)
-- exercise 1
tag :: Monoid m => JoinList m a -> m
tag Empty = mempty
tag (Single m _) = m
tag (Append m _ _) = m
(+++) :: Monoid m => JoinList m a -> JoinList m a -> JoinList m a
l +++ Empty = l
Empty +++ l = l
left +++ right = Append (m1 <> m2) left right
where m1 = tag left
m2 = tag right
-- exercise 2
(!!?) :: [a] -> Int -> Maybe a
[] !!? _ = Nothing
_ !!? i | i < 0 = Nothing
(x:xs) !!? 0 = Just x
(x:xs) !!? i = xs !!? (i-1)
jlToList :: JoinList m a -> [a]
jlToList Empty = []
jlToList (Single _ a) = [a]
jlToList (Append _ l1 l2) = jlToList l1 ++ jlToList l2
getSizeInt :: Sized a => a -> Int
getSizeInt = getSize . size
indexJ :: (Sized b, Monoid b) => Int -> JoinList b a -> Maybe a
indexJ _ Empty = Nothing
indexJ n (Single m a)
| n == 0 = Just a
| otherwise = Nothing
indexJ n (Append m l1 l2)
| n >= getSizeInt m = Nothing
| otherwise =
let s1 = getSizeInt $ tag l1
s2 = getSizeInt $ tag l2
in
if n < s1 then indexJ n l1
else if n < (s1 + s2) then indexJ (n - s1) l2
else Nothing
dropJ :: (Sized b, Monoid b) => Int -> JoinList b a -> JoinList b a
dropJ _ Empty = Empty
dropJ n s@(Single _ _)
| n == 0 = s
| otherwise = Empty
dropJ n (Append m l1 l2)
| n >= sizeM = Empty
| n == sizeL1 = l2
| n < sizeL1 = (dropJ n l1) +++ l2
| otherwise = (dropJ (n - sizeL1) l2) +++ Empty
where sizeM = getSizeInt m
sizeL1 = getSizeInt $ tag l1
takeJ :: (Sized b, Monoid b) => Int -> JoinList b a -> JoinList b a
takeJ _ Empty = Empty
takeJ n l | n <= 0 = Empty
takeJ n s@(Single _ _) | n >= 1 = s
takeJ n all@(Append m l1 l2)
| n >= sizeM = all
| n == sizeL1 = l1
| n > sizeL1 = l1 +++ (takeJ (n - sizeL1) l2)
| n < sizeL1 = takeJ n l1
where sizeM = getSizeInt m
sizeL1 = getSizeInt $ tag l1
-- exercise 3
scoreLine :: String -> JoinList Score String
scoreLine s = Single (scoreString s) s
|
dirkz/haskell-cis-194
|
07/JoinList.hs
|
isc
| 2,157 | 0 | 12 | 663 | 1,101 | 545 | 556 | 67 | 3 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TupleSections #-}
-- | C code generator framework.
module Futhark.CodeGen.Backends.GenericC
( compileProg,
CParts (..),
asLibrary,
asExecutable,
asServer,
-- * Pluggable compiler
Operations (..),
defaultOperations,
OpCompiler,
ErrorCompiler,
CallCompiler,
PointerQuals,
MemoryType,
WriteScalar,
writeScalarPointerWithQuals,
ReadScalar,
readScalarPointerWithQuals,
Allocate,
Deallocate,
Copy,
StaticArray,
-- * Monadic compiler interface
CompilerM,
CompilerState (compUserState, compNameSrc),
getUserState,
modifyUserState,
contextContents,
contextFinalInits,
runCompilerM,
inNewFunction,
cachingMemory,
blockScope,
compileFun,
compileCode,
compileExp,
compilePrimExp,
compileExpToName,
rawMem,
item,
items,
stm,
stms,
decl,
atInit,
headerDecl,
publicDef,
publicDef_,
profileReport,
onClear,
HeaderSection (..),
libDecl,
earlyDecl,
publicName,
contextType,
contextField,
contextFieldDyn,
memToCType,
cacheMem,
fatMemory,
rawMemCType,
cproduct,
fatMemType,
freeAllocatedMem,
-- * Building Blocks
primTypeToCType,
intTypeToCType,
copyMemoryDefaultSpace,
)
where
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import Data.Bifunctor (first)
import qualified Data.DList as DL
import Data.List (unzip4)
import Data.Loc
import qualified Data.Map.Strict as M
import Data.Maybe
import qualified Data.Text as T
import Futhark.CodeGen.Backends.GenericC.CLI (cliDefs)
import qualified Futhark.CodeGen.Backends.GenericC.Manifest as Manifest
import Futhark.CodeGen.Backends.GenericC.Options
import Futhark.CodeGen.Backends.GenericC.Server (serverDefs)
import Futhark.CodeGen.Backends.SimpleRep
import Futhark.CodeGen.ImpCode
import Futhark.CodeGen.RTS.C (halfH, lockH, timingH, utilH)
import Futhark.IR.Prop (isBuiltInFunction)
import Futhark.MonadFreshNames
import Futhark.Util.Pretty (prettyText)
import qualified Language.C.Quote.OpenCL as C
import qualified Language.C.Syntax as C
import NeatInterpolation (untrimming)
-- How public an array type definition sould be. Public types show up
-- in the generated API, while private types are used only to
-- implement the members of opaques.
data Publicness = Private | Public
deriving (Eq, Ord, Show)
type ArrayType = (Space, Signedness, PrimType, Int)
data CompilerState s = CompilerState
{ compArrayTypes :: M.Map ArrayType Publicness,
compOpaqueTypes :: M.Map String [ValueDesc],
compEarlyDecls :: DL.DList C.Definition,
compInit :: [C.Stm],
compNameSrc :: VNameSource,
compUserState :: s,
compHeaderDecls :: M.Map HeaderSection (DL.DList C.Definition),
compLibDecls :: DL.DList C.Definition,
compCtxFields :: DL.DList (C.Id, C.Type, Maybe C.Exp, Maybe C.Stm),
compProfileItems :: DL.DList C.BlockItem,
compClearItems :: DL.DList C.BlockItem,
compDeclaredMem :: [(VName, Space)],
compItems :: DL.DList C.BlockItem
}
newCompilerState :: VNameSource -> s -> CompilerState s
newCompilerState src s =
CompilerState
{ compArrayTypes = mempty,
compOpaqueTypes = mempty,
compEarlyDecls = mempty,
compInit = [],
compNameSrc = src,
compUserState = s,
compHeaderDecls = mempty,
compLibDecls = mempty,
compCtxFields = mempty,
compProfileItems = mempty,
compClearItems = mempty,
compDeclaredMem = mempty,
compItems = mempty
}
-- | In which part of the header file we put the declaration. This is
-- to ensure that the header file remains structured and readable.
data HeaderSection
= ArrayDecl String
| OpaqueDecl String
| EntryDecl
| MiscDecl
| InitDecl
deriving (Eq, Ord)
-- | A substitute expression compiler, tried before the main
-- compilation function.
type OpCompiler op s = op -> CompilerM op s ()
type ErrorCompiler op s = ErrorMsg Exp -> String -> CompilerM op s ()
-- | The address space qualifiers for a pointer of the given type with
-- the given annotation.
type PointerQuals op s = String -> CompilerM op s [C.TypeQual]
-- | The type of a memory block in the given memory space.
type MemoryType op s = SpaceId -> CompilerM op s C.Type
-- | Write a scalar to the given memory block with the given element
-- index and in the given memory space.
type WriteScalar op s =
C.Exp -> C.Exp -> C.Type -> SpaceId -> Volatility -> C.Exp -> CompilerM op s ()
-- | Read a scalar from the given memory block with the given element
-- index and in the given memory space.
type ReadScalar op s =
C.Exp -> C.Exp -> C.Type -> SpaceId -> Volatility -> CompilerM op s C.Exp
-- | Allocate a memory block of the given size and with the given tag
-- in the given memory space, saving a reference in the given variable
-- name.
type Allocate op s =
C.Exp ->
C.Exp ->
C.Exp ->
SpaceId ->
CompilerM op s ()
-- | De-allocate the given memory block with the given tag, which is
-- in the given memory space.
type Deallocate op s = C.Exp -> C.Exp -> SpaceId -> CompilerM op s ()
-- | Create a static array of values - initialised at load time.
type StaticArray op s = VName -> SpaceId -> PrimType -> ArrayContents -> CompilerM op s ()
-- | Copy from one memory block to another.
type Copy op s =
C.Exp ->
C.Exp ->
Space ->
C.Exp ->
C.Exp ->
Space ->
C.Exp ->
CompilerM op s ()
-- | Call a function.
type CallCompiler op s = [VName] -> Name -> [C.Exp] -> CompilerM op s ()
data Operations op s = Operations
{ opsWriteScalar :: WriteScalar op s,
opsReadScalar :: ReadScalar op s,
opsAllocate :: Allocate op s,
opsDeallocate :: Deallocate op s,
opsCopy :: Copy op s,
opsStaticArray :: StaticArray op s,
opsMemoryType :: MemoryType op s,
opsCompiler :: OpCompiler op s,
opsError :: ErrorCompiler op s,
opsCall :: CallCompiler op s,
-- | If true, use reference counting. Otherwise, bare
-- pointers.
opsFatMemory :: Bool,
-- | Code to bracket critical sections.
opsCritical :: ([C.BlockItem], [C.BlockItem])
}
errorMsgString :: ErrorMsg Exp -> CompilerM op s (String, [C.Exp])
errorMsgString (ErrorMsg parts) = do
let boolStr e = [C.cexp|($exp:e) ? "true" : "false"|]
asLongLong e = [C.cexp|(long long int)$exp:e|]
asDouble e = [C.cexp|(double)$exp:e|]
onPart (ErrorString s) = return ("%s", [C.cexp|$string:s|])
onPart (ErrorVal Bool x) = ("%s",) . boolStr <$> compileExp x
onPart (ErrorVal Unit _) = pure ("%s", [C.cexp|"()"|])
onPart (ErrorVal (IntType Int8) x) = ("%hhd",) <$> compileExp x
onPart (ErrorVal (IntType Int16) x) = ("%hd",) <$> compileExp x
onPart (ErrorVal (IntType Int32) x) = ("%d",) <$> compileExp x
onPart (ErrorVal (IntType Int64) x) = ("%lld",) . asLongLong <$> compileExp x
onPart (ErrorVal (FloatType Float16) x) = ("%f",) . asDouble <$> compileExp x
onPart (ErrorVal (FloatType Float32) x) = ("%f",) . asDouble <$> compileExp x
onPart (ErrorVal (FloatType Float64) x) = ("%f",) <$> compileExp x
(formatstrs, formatargs) <- unzip <$> mapM onPart parts
pure (mconcat formatstrs, formatargs)
freeAllocatedMem :: CompilerM op s [C.BlockItem]
freeAllocatedMem = collect $ mapM_ (uncurry unRefMem) =<< gets compDeclaredMem
defError :: ErrorCompiler op s
defError msg stacktrace = do
free_all_mem <- freeAllocatedMem
(formatstr, formatargs) <- errorMsgString msg
let formatstr' = "Error: " <> formatstr <> "\n\nBacktrace:\n%s"
items
[C.citems|ctx->error = msgprintf($string:formatstr', $args:formatargs, $string:stacktrace);
$items:free_all_mem
err = 1;
goto cleanup;|]
defCall :: CallCompiler op s
defCall dests fname args = do
let out_args = [[C.cexp|&$id:d|] | d <- dests]
args'
| isBuiltInFunction fname = args
| otherwise = [C.cexp|ctx|] : out_args ++ args
case dests of
[dest]
| isBuiltInFunction fname ->
stm [C.cstm|$id:dest = $id:(funName fname)($args:args');|]
_ -> do
free_all_mem <- freeAllocatedMem
item [C.citem|if ($id:(funName fname)($args:args') != 0) { $items:free_all_mem err = 1; goto cleanup; }|]
-- | A set of operations that fail for every operation involving
-- non-default memory spaces. Uses plain pointers and @malloc@ for
-- memory management.
defaultOperations :: Operations op s
defaultOperations =
Operations
{ opsWriteScalar = defWriteScalar,
opsReadScalar = defReadScalar,
opsAllocate = defAllocate,
opsDeallocate = defDeallocate,
opsCopy = defCopy,
opsStaticArray = defStaticArray,
opsMemoryType = defMemoryType,
opsCompiler = defCompiler,
opsFatMemory = True,
opsError = defError,
opsCall = defCall,
opsCritical = mempty
}
where
defWriteScalar _ _ _ _ _ =
error "Cannot write to non-default memory space because I am dumb"
defReadScalar _ _ _ _ =
error "Cannot read from non-default memory space"
defAllocate _ _ _ =
error "Cannot allocate in non-default memory space"
defDeallocate _ _ =
error "Cannot deallocate in non-default memory space"
defCopy destmem destoffset DefaultSpace srcmem srcoffset DefaultSpace size =
copyMemoryDefaultSpace destmem destoffset srcmem srcoffset size
defCopy _ _ _ _ _ _ _ =
error "Cannot copy to or from non-default memory space"
defStaticArray _ _ _ _ =
error "Cannot create static array in non-default memory space"
defMemoryType _ =
error "Has no type for non-default memory space"
defCompiler _ =
error "The default compiler cannot compile extended operations"
data CompilerEnv op s = CompilerEnv
{ envOperations :: Operations op s,
-- | Mapping memory blocks to sizes. These memory blocks are CPU
-- memory that we know are used in particularly simple ways (no
-- reference counting necessary). To cut down on allocator
-- pressure, we keep these allocations around for a long time, and
-- record their sizes so we can reuse them if possible (and
-- realloc() when needed).
envCachedMem :: M.Map C.Exp VName
}
envOpCompiler :: CompilerEnv op s -> OpCompiler op s
envOpCompiler = opsCompiler . envOperations
envMemoryType :: CompilerEnv op s -> MemoryType op s
envMemoryType = opsMemoryType . envOperations
envReadScalar :: CompilerEnv op s -> ReadScalar op s
envReadScalar = opsReadScalar . envOperations
envWriteScalar :: CompilerEnv op s -> WriteScalar op s
envWriteScalar = opsWriteScalar . envOperations
envAllocate :: CompilerEnv op s -> Allocate op s
envAllocate = opsAllocate . envOperations
envDeallocate :: CompilerEnv op s -> Deallocate op s
envDeallocate = opsDeallocate . envOperations
envCopy :: CompilerEnv op s -> Copy op s
envCopy = opsCopy . envOperations
envStaticArray :: CompilerEnv op s -> StaticArray op s
envStaticArray = opsStaticArray . envOperations
envFatMemory :: CompilerEnv op s -> Bool
envFatMemory = opsFatMemory . envOperations
declsCode :: (HeaderSection -> Bool) -> CompilerState s -> T.Text
declsCode p =
T.unlines
. map prettyText
. concatMap (DL.toList . snd)
. filter (p . fst)
. M.toList
. compHeaderDecls
initDecls, arrayDecls, opaqueDecls, entryDecls, miscDecls :: CompilerState s -> T.Text
initDecls = declsCode (== InitDecl)
arrayDecls = declsCode isArrayDecl
where
isArrayDecl ArrayDecl {} = True
isArrayDecl _ = False
opaqueDecls = declsCode isOpaqueDecl
where
isOpaqueDecl OpaqueDecl {} = True
isOpaqueDecl _ = False
entryDecls = declsCode (== EntryDecl)
miscDecls = declsCode (== MiscDecl)
contextContents :: CompilerM op s ([C.FieldGroup], [C.Stm], [C.Stm])
contextContents = do
(field_names, field_types, field_values, field_frees) <-
gets $ unzip4 . DL.toList . compCtxFields
let fields =
[ [C.csdecl|$ty:ty $id:name;|]
| (name, ty) <- zip field_names field_types
]
init_fields =
[ [C.cstm|ctx->$id:name = $exp:e;|]
| (name, Just e) <- zip field_names field_values
]
return (fields, init_fields, catMaybes field_frees)
contextFinalInits :: CompilerM op s [C.Stm]
contextFinalInits = gets compInit
newtype CompilerM op s a
= CompilerM (ReaderT (CompilerEnv op s) (State (CompilerState s)) a)
deriving
( Functor,
Applicative,
Monad,
MonadState (CompilerState s),
MonadReader (CompilerEnv op s)
)
instance MonadFreshNames (CompilerM op s) where
getNameSource = gets compNameSrc
putNameSource src = modify $ \s -> s {compNameSrc = src}
runCompilerM ::
Operations op s ->
VNameSource ->
s ->
CompilerM op s a ->
(a, CompilerState s)
runCompilerM ops src userstate (CompilerM m) =
runState
(runReaderT m (CompilerEnv ops mempty))
(newCompilerState src userstate)
getUserState :: CompilerM op s s
getUserState = gets compUserState
modifyUserState :: (s -> s) -> CompilerM op s ()
modifyUserState f = modify $ \compstate ->
compstate {compUserState = f $ compUserState compstate}
atInit :: C.Stm -> CompilerM op s ()
atInit x = modify $ \s ->
s {compInit = compInit s ++ [x]}
collect :: CompilerM op s () -> CompilerM op s [C.BlockItem]
collect m = snd <$> collect' m
collect' :: CompilerM op s a -> CompilerM op s (a, [C.BlockItem])
collect' m = do
old <- gets compItems
modify $ \s -> s {compItems = mempty}
x <- m
new <- gets compItems
modify $ \s -> s {compItems = old}
pure (x, DL.toList new)
-- | Used when we, inside an existing 'CompilerM' action, want to
-- generate code for a new function. Use this so that the compiler
-- understands that previously declared memory doesn't need to be
-- freed inside this action.
inNewFunction :: Bool -> CompilerM op s a -> CompilerM op s a
inNewFunction keep_cached m = do
old_mem <- gets compDeclaredMem
modify $ \s -> s {compDeclaredMem = mempty}
x <- local noCached m
modify $ \s -> s {compDeclaredMem = old_mem}
return x
where
noCached env
| keep_cached = env
| otherwise = env {envCachedMem = mempty}
item :: C.BlockItem -> CompilerM op s ()
item x = modify $ \s -> s {compItems = DL.snoc (compItems s) x}
items :: [C.BlockItem] -> CompilerM op s ()
items xs = modify $ \s -> s {compItems = DL.append (compItems s) (DL.fromList xs)}
fatMemory :: Space -> CompilerM op s Bool
fatMemory ScalarSpace {} = return False
fatMemory _ = asks envFatMemory
cacheMem :: C.ToExp a => a -> CompilerM op s (Maybe VName)
cacheMem a = asks $ M.lookup (C.toExp a noLoc) . envCachedMem
-- | Construct a publicly visible definition using the specified name
-- as the template. The first returned definition is put in the
-- header file, and the second is the implementation. Returns the public
-- name.
publicDef ::
String ->
HeaderSection ->
(String -> (C.Definition, C.Definition)) ->
CompilerM op s String
publicDef s h f = do
s' <- publicName s
let (pub, priv) = f s'
headerDecl h pub
earlyDecl priv
return s'
-- | As 'publicDef', but ignores the public name.
publicDef_ ::
String ->
HeaderSection ->
(String -> (C.Definition, C.Definition)) ->
CompilerM op s ()
publicDef_ s h f = void $ publicDef s h f
headerDecl :: HeaderSection -> C.Definition -> CompilerM op s ()
headerDecl sec def = modify $ \s ->
s
{ compHeaderDecls =
M.unionWith
(<>)
(compHeaderDecls s)
(M.singleton sec (DL.singleton def))
}
libDecl :: C.Definition -> CompilerM op s ()
libDecl def = modify $ \s ->
s {compLibDecls = compLibDecls s <> DL.singleton def}
earlyDecl :: C.Definition -> CompilerM op s ()
earlyDecl def = modify $ \s ->
s {compEarlyDecls = compEarlyDecls s <> DL.singleton def}
contextField :: C.Id -> C.Type -> Maybe C.Exp -> CompilerM op s ()
contextField name ty initial = modify $ \s ->
s {compCtxFields = compCtxFields s <> DL.singleton (name, ty, initial, Nothing)}
contextFieldDyn :: C.Id -> C.Type -> C.Exp -> C.Stm -> CompilerM op s ()
contextFieldDyn name ty initial free = modify $ \s ->
s {compCtxFields = compCtxFields s <> DL.singleton (name, ty, Just initial, Just free)}
profileReport :: C.BlockItem -> CompilerM op s ()
profileReport x = modify $ \s ->
s {compProfileItems = compProfileItems s <> DL.singleton x}
onClear :: C.BlockItem -> CompilerM op s ()
onClear x = modify $ \s ->
s {compClearItems = compClearItems s <> DL.singleton x}
stm :: C.Stm -> CompilerM op s ()
stm s = item [C.citem|$stm:s|]
stms :: [C.Stm] -> CompilerM op s ()
stms = mapM_ stm
decl :: C.InitGroup -> CompilerM op s ()
decl x = item [C.citem|$decl:x;|]
-- | Public names must have a consitent prefix.
publicName :: String -> CompilerM op s String
publicName s = return $ "futhark_" ++ s
-- | The generated code must define a struct with this name.
contextType :: CompilerM op s C.Type
contextType = do
name <- publicName "context"
return [C.cty|struct $id:name|]
memToCType :: VName -> Space -> CompilerM op s C.Type
memToCType v space = do
refcount <- fatMemory space
cached <- isJust <$> cacheMem v
if refcount && not cached
then return $ fatMemType space
else rawMemCType space
rawMemCType :: Space -> CompilerM op s C.Type
rawMemCType DefaultSpace = return defaultMemBlockType
rawMemCType (Space sid) = join $ asks envMemoryType <*> pure sid
rawMemCType (ScalarSpace [] t) =
return [C.cty|$ty:(primTypeToCType t)[1]|]
rawMemCType (ScalarSpace ds t) =
return [C.cty|$ty:(primTypeToCType t)[$exp:(cproduct ds')]|]
where
ds' = map (`C.toExp` noLoc) ds
fatMemType :: Space -> C.Type
fatMemType space =
[C.cty|struct $id:name|]
where
name = case space of
Space sid -> "memblock_" ++ sid
_ -> "memblock"
fatMemSet :: Space -> String
fatMemSet (Space sid) = "memblock_set_" ++ sid
fatMemSet _ = "memblock_set"
fatMemAlloc :: Space -> String
fatMemAlloc (Space sid) = "memblock_alloc_" ++ sid
fatMemAlloc _ = "memblock_alloc"
fatMemUnRef :: Space -> String
fatMemUnRef (Space sid) = "memblock_unref_" ++ sid
fatMemUnRef _ = "memblock_unref"
rawMem :: VName -> CompilerM op s C.Exp
rawMem v = rawMem' <$> fat <*> pure v
where
fat = asks ((&&) . envFatMemory) <*> (isNothing <$> cacheMem v)
rawMem' :: C.ToExp a => Bool -> a -> C.Exp
rawMem' True e = [C.cexp|$exp:e.mem|]
rawMem' False e = [C.cexp|$exp:e|]
allocRawMem ::
(C.ToExp a, C.ToExp b, C.ToExp c) =>
a ->
b ->
Space ->
c ->
CompilerM op s ()
allocRawMem dest size space desc = case space of
Space sid ->
join $
asks envAllocate <*> pure [C.cexp|$exp:dest|]
<*> pure [C.cexp|$exp:size|]
<*> pure [C.cexp|$exp:desc|]
<*> pure sid
_ ->
stm [C.cstm|$exp:dest = (unsigned char*) malloc((size_t)$exp:size);|]
freeRawMem ::
(C.ToExp a, C.ToExp b) =>
a ->
Space ->
b ->
CompilerM op s ()
freeRawMem mem space desc =
case space of
Space sid -> do
free_mem <- asks envDeallocate
free_mem [C.cexp|$exp:mem|] [C.cexp|$exp:desc|] sid
_ -> item [C.citem|free($exp:mem);|]
defineMemorySpace :: Space -> CompilerM op s (C.Definition, [C.Definition], C.BlockItem)
defineMemorySpace space = do
rm <- rawMemCType space
let structdef =
[C.cedecl|struct $id:sname { int *references;
$ty:rm mem;
typename int64_t size;
const char *desc; };|]
contextField peakname [C.cty|typename int64_t|] $ Just [C.cexp|0|]
contextField usagename [C.cty|typename int64_t|] $ Just [C.cexp|0|]
-- Unreferencing a memory block consists of decreasing its reference
-- count and freeing the corresponding memory if the count reaches
-- zero.
free <- collect $ freeRawMem [C.cexp|block->mem|] space [C.cexp|desc|]
ctx_ty <- contextType
let unrefdef =
[C.cedecl|static int $id:(fatMemUnRef space) ($ty:ctx_ty *ctx, $ty:mty *block, const char *desc) {
if (block->references != NULL) {
*(block->references) -= 1;
if (ctx->detail_memory) {
fprintf(ctx->log, "Unreferencing block %s (allocated as %s) in %s: %d references remaining.\n",
desc, block->desc, $string:spacedesc, *(block->references));
}
if (*(block->references) == 0) {
ctx->$id:usagename -= block->size;
$items:free
free(block->references);
if (ctx->detail_memory) {
fprintf(ctx->log, "%lld bytes freed (now allocated: %lld bytes)\n",
(long long) block->size, (long long) ctx->$id:usagename);
}
}
block->references = NULL;
}
return 0;
}|]
-- When allocating a memory block we initialise the reference count to 1.
alloc <-
collect $
allocRawMem [C.cexp|block->mem|] [C.cexp|size|] space [C.cexp|desc|]
let allocdef =
[C.cedecl|static int $id:(fatMemAlloc space) ($ty:ctx_ty *ctx, $ty:mty *block, typename int64_t size, const char *desc) {
if (size < 0) {
futhark_panic(1, "Negative allocation of %lld bytes attempted for %s in %s.\n",
(long long)size, desc, $string:spacedesc, ctx->$id:usagename);
}
int ret = $id:(fatMemUnRef space)(ctx, block, desc);
ctx->$id:usagename += size;
if (ctx->detail_memory) {
fprintf(ctx->log, "Allocating %lld bytes for %s in %s (then allocated: %lld bytes)",
(long long) size,
desc, $string:spacedesc,
(long long) ctx->$id:usagename);
}
if (ctx->$id:usagename > ctx->$id:peakname) {
ctx->$id:peakname = ctx->$id:usagename;
if (ctx->detail_memory) {
fprintf(ctx->log, " (new peak).\n");
}
} else if (ctx->detail_memory) {
fprintf(ctx->log, ".\n");
}
$items:alloc
block->references = (int*) malloc(sizeof(int));
*(block->references) = 1;
block->size = size;
block->desc = desc;
return ret;
}|]
-- Memory setting - unreference the destination and increase the
-- count of the source by one.
let setdef =
[C.cedecl|static int $id:(fatMemSet space) ($ty:ctx_ty *ctx, $ty:mty *lhs, $ty:mty *rhs, const char *lhs_desc) {
int ret = $id:(fatMemUnRef space)(ctx, lhs, lhs_desc);
if (rhs->references != NULL) {
(*(rhs->references))++;
}
*lhs = *rhs;
return ret;
}
|]
onClear [C.citem|ctx->$id:peakname = 0;|]
let peakmsg = "Peak memory usage for " ++ spacedesc ++ ": %lld bytes.\n"
return
( structdef,
[unrefdef, allocdef, setdef],
-- Do not report memory usage for DefaultSpace (CPU memory),
-- because it would not be accurate anyway. This whole
-- tracking probably needs to be rethought.
if space == DefaultSpace
then [C.citem|{}|]
else [C.citem|str_builder(&builder, $string:peakmsg, (long long) ctx->$id:peakname);|]
)
where
mty = fatMemType space
(peakname, usagename, sname, spacedesc) = case space of
Space sid ->
( C.toIdent ("peak_mem_usage_" ++ sid) noLoc,
C.toIdent ("cur_mem_usage_" ++ sid) noLoc,
C.toIdent ("memblock_" ++ sid) noLoc,
"space '" ++ sid ++ "'"
)
_ ->
( "peak_mem_usage_default",
"cur_mem_usage_default",
"memblock",
"default space"
)
declMem :: VName -> Space -> CompilerM op s ()
declMem name space = do
cached <- isJust <$> cacheMem name
unless cached $ do
ty <- memToCType name space
decl [C.cdecl|$ty:ty $id:name;|]
resetMem name space
modify $ \s -> s {compDeclaredMem = (name, space) : compDeclaredMem s}
resetMem :: C.ToExp a => a -> Space -> CompilerM op s ()
resetMem mem space = do
refcount <- fatMemory space
cached <- isJust <$> cacheMem mem
if cached
then stm [C.cstm|$exp:mem = NULL;|]
else
when refcount $
stm [C.cstm|$exp:mem.references = NULL;|]
setMem :: (C.ToExp a, C.ToExp b) => a -> b -> Space -> CompilerM op s ()
setMem dest src space = do
refcount <- fatMemory space
let src_s = pretty $ C.toExp src noLoc
if refcount
then
stm
[C.cstm|if ($id:(fatMemSet space)(ctx, &$exp:dest, &$exp:src,
$string:src_s) != 0) {
return 1;
}|]
else case space of
ScalarSpace ds _ -> do
i' <- newVName "i"
let i = C.toIdent i'
it = primTypeToCType $ IntType Int32
ds' = map (`C.toExp` noLoc) ds
bound = cproduct ds'
stm
[C.cstm|for ($ty:it $id:i = 0; $id:i < $exp:bound; $id:i++) {
$exp:dest[$id:i] = $exp:src[$id:i];
}|]
_ -> stm [C.cstm|$exp:dest = $exp:src;|]
unRefMem :: C.ToExp a => a -> Space -> CompilerM op s ()
unRefMem mem space = do
refcount <- fatMemory space
cached <- isJust <$> cacheMem mem
let mem_s = pretty $ C.toExp mem noLoc
when (refcount && not cached) $
stm
[C.cstm|if ($id:(fatMemUnRef space)(ctx, &$exp:mem, $string:mem_s) != 0) {
return 1;
}|]
allocMem ::
(C.ToExp a, C.ToExp b) =>
a ->
b ->
Space ->
C.Stm ->
CompilerM op s ()
allocMem mem size space on_failure = do
refcount <- fatMemory space
let mem_s = pretty $ C.toExp mem noLoc
if refcount
then
stm
[C.cstm|if ($id:(fatMemAlloc space)(ctx, &$exp:mem, $exp:size,
$string:mem_s)) {
$stm:on_failure
}|]
else do
freeRawMem mem space mem_s
allocRawMem mem size space [C.cexp|desc|]
copyMemoryDefaultSpace ::
C.Exp ->
C.Exp ->
C.Exp ->
C.Exp ->
C.Exp ->
CompilerM op s ()
copyMemoryDefaultSpace destmem destidx srcmem srcidx nbytes =
stm
[C.cstm|if ($exp:nbytes > 0) {
memmove($exp:destmem + $exp:destidx,
$exp:srcmem + $exp:srcidx,
$exp:nbytes);
}|]
--- Entry points.
criticalSection :: Operations op s -> [C.BlockItem] -> [C.BlockItem]
criticalSection ops x =
[C.citems|lock_lock(&ctx->lock);
$items:(fst (opsCritical ops))
$items:x
$items:(snd (opsCritical ops))
lock_unlock(&ctx->lock);
|]
arrayLibraryFunctions ::
Publicness ->
Space ->
PrimType ->
Signedness ->
Int ->
CompilerM op s Manifest.ArrayOps
arrayLibraryFunctions pub space pt signed rank = do
let pt' = primAPIType signed pt
name = arrayName pt signed rank
arr_name = "futhark_" ++ name
array_type = [C.cty|struct $id:arr_name|]
new_array <- publicName $ "new_" ++ name
new_raw_array <- publicName $ "new_raw_" ++ name
free_array <- publicName $ "free_" ++ name
values_array <- publicName $ "values_" ++ name
values_raw_array <- publicName $ "values_raw_" ++ name
shape_array <- publicName $ "shape_" ++ name
let shape_names = ["dim" ++ show i | i <- [0 .. rank - 1]]
shape_params = [[C.cparam|typename int64_t $id:k|] | k <- shape_names]
arr_size = cproduct [[C.cexp|$id:k|] | k <- shape_names]
arr_size_array = cproduct [[C.cexp|arr->shape[$int:i]|] | i <- [0 .. rank - 1]]
copy <- asks envCopy
memty <- rawMemCType space
let prepare_new = do
resetMem [C.cexp|arr->mem|] space
allocMem
[C.cexp|arr->mem|]
[C.cexp|$exp:arr_size * $int:(primByteSize pt::Int)|]
space
[C.cstm|return NULL;|]
forM_ [0 .. rank - 1] $ \i ->
let dim_s = "dim" ++ show i
in stm [C.cstm|arr->shape[$int:i] = $id:dim_s;|]
new_body <- collect $ do
prepare_new
copy
[C.cexp|arr->mem.mem|]
[C.cexp|0|]
space
[C.cexp|data|]
[C.cexp|0|]
DefaultSpace
[C.cexp|((size_t)$exp:arr_size) * $int:(primByteSize pt::Int)|]
new_raw_body <- collect $ do
prepare_new
copy
[C.cexp|arr->mem.mem|]
[C.cexp|0|]
space
[C.cexp|data|]
[C.cexp|offset|]
space
[C.cexp|((size_t)$exp:arr_size) * $int:(primByteSize pt::Int)|]
free_body <- collect $ unRefMem [C.cexp|arr->mem|] space
values_body <-
collect $
copy
[C.cexp|data|]
[C.cexp|0|]
DefaultSpace
[C.cexp|arr->mem.mem|]
[C.cexp|0|]
space
[C.cexp|((size_t)$exp:arr_size_array) * $int:(primByteSize pt::Int)|]
ctx_ty <- contextType
ops <- asks envOperations
let proto = case pub of
Public -> headerDecl (ArrayDecl name)
Private -> libDecl
proto
[C.cedecl|struct $id:arr_name;|]
proto
[C.cedecl|$ty:array_type* $id:new_array($ty:ctx_ty *ctx, const $ty:pt' *data, $params:shape_params);|]
proto
[C.cedecl|$ty:array_type* $id:new_raw_array($ty:ctx_ty *ctx, const $ty:memty data, typename int64_t offset, $params:shape_params);|]
proto
[C.cedecl|int $id:free_array($ty:ctx_ty *ctx, $ty:array_type *arr);|]
proto
[C.cedecl|int $id:values_array($ty:ctx_ty *ctx, $ty:array_type *arr, $ty:pt' *data);|]
proto
[C.cedecl|$ty:memty $id:values_raw_array($ty:ctx_ty *ctx, $ty:array_type *arr);|]
proto
[C.cedecl|const typename int64_t* $id:shape_array($ty:ctx_ty *ctx, $ty:array_type *arr);|]
mapM_
libDecl
[C.cunit|
$ty:array_type* $id:new_array($ty:ctx_ty *ctx, const $ty:pt' *data, $params:shape_params) {
$ty:array_type* bad = NULL;
$ty:array_type *arr = ($ty:array_type*) malloc(sizeof($ty:array_type));
if (arr == NULL) {
return bad;
}
$items:(criticalSection ops new_body)
return arr;
}
$ty:array_type* $id:new_raw_array($ty:ctx_ty *ctx, const $ty:memty data, typename int64_t offset,
$params:shape_params) {
$ty:array_type* bad = NULL;
$ty:array_type *arr = ($ty:array_type*) malloc(sizeof($ty:array_type));
if (arr == NULL) {
return bad;
}
$items:(criticalSection ops new_raw_body)
return arr;
}
int $id:free_array($ty:ctx_ty *ctx, $ty:array_type *arr) {
$items:(criticalSection ops free_body)
free(arr);
return 0;
}
int $id:values_array($ty:ctx_ty *ctx, $ty:array_type *arr, $ty:pt' *data) {
$items:(criticalSection ops values_body)
return 0;
}
$ty:memty $id:values_raw_array($ty:ctx_ty *ctx, $ty:array_type *arr) {
(void)ctx;
return arr->mem.mem;
}
const typename int64_t* $id:shape_array($ty:ctx_ty *ctx, $ty:array_type *arr) {
(void)ctx;
return arr->shape;
}
|]
pure $
Manifest.ArrayOps
{ Manifest.arrayFree = T.pack free_array,
Manifest.arrayShape = T.pack shape_array,
Manifest.arrayValues = T.pack values_array,
Manifest.arrayNew = T.pack new_array
}
opaqueLibraryFunctions ::
String ->
[ValueDesc] ->
CompilerM op s Manifest.OpaqueOps
opaqueLibraryFunctions desc vds = do
name <- publicName $ opaqueName desc vds
free_opaque <- publicName $ "free_" ++ opaqueName desc vds
store_opaque <- publicName $ "store_" ++ opaqueName desc vds
restore_opaque <- publicName $ "restore_" ++ opaqueName desc vds
let opaque_type = [C.cty|struct $id:name|]
freeComponent _ ScalarValue {} =
return ()
freeComponent i (ArrayValue _ _ pt signed shape) = do
let rank = length shape
field = tupleField i
free_array <- publicName $ "free_" ++ arrayName pt signed rank
-- Protect against NULL here, because we also want to use this
-- to free partially loaded opaques.
stm
[C.cstm|if (obj->$id:field != NULL && (tmp = $id:free_array(ctx, obj->$id:field)) != 0) {
ret = tmp;
}|]
storeComponent i (ScalarValue pt sign _) =
let field = tupleField i
in ( storageSize pt 0 [C.cexp|NULL|],
storeValueHeader sign pt 0 [C.cexp|NULL|] [C.cexp|out|]
++ [C.cstms|memcpy(out, &obj->$id:field, sizeof(obj->$id:field));
out += sizeof(obj->$id:field);|]
)
storeComponent i (ArrayValue _ _ pt sign shape) =
let rank = length shape
arr_name = arrayName pt sign rank
field = tupleField i
shape_array = "futhark_shape_" ++ arr_name
values_array = "futhark_values_" ++ arr_name
shape' = [C.cexp|$id:shape_array(ctx, obj->$id:field)|]
num_elems = cproduct [[C.cexp|$exp:shape'[$int:j]|] | j <- [0 .. rank - 1]]
in ( storageSize pt rank shape',
storeValueHeader sign pt rank shape' [C.cexp|out|]
++ [C.cstms|ret |= $id:values_array(ctx, obj->$id:field, (void*)out);
out += $exp:num_elems * $int:(primByteSize pt::Int);|]
)
ctx_ty <- contextType
free_body <- collect $ zipWithM_ freeComponent [0 ..] vds
store_body <- collect $ do
let (sizes, stores) = unzip $ zipWith storeComponent [0 ..] vds
size_vars = map (("size_" ++) . show) [0 .. length sizes - 1]
size_sum = csum [[C.cexp|$id:size|] | size <- size_vars]
forM_ (zip size_vars sizes) $ \(v, e) ->
item [C.citem|typename int64_t $id:v = $exp:e;|]
stm [C.cstm|*n = $exp:size_sum;|]
stm [C.cstm|if (p != NULL && *p == NULL) { *p = malloc(*n); }|]
stm [C.cstm|if (p != NULL) { unsigned char *out = *p; $stms:(concat stores) }|]
let restoreComponent i (ScalarValue pt sign _) = do
let field = tupleField i
dataptr = "data_" ++ show i
stms $ loadValueHeader sign pt 0 [C.cexp|NULL|] [C.cexp|src|]
item [C.citem|const void* $id:dataptr = src;|]
stm [C.cstm|src += sizeof(obj->$id:field);|]
pure [C.cstms|memcpy(&obj->$id:field, $id:dataptr, sizeof(obj->$id:field));|]
restoreComponent i (ArrayValue _ _ pt sign shape) = do
let field = tupleField i
rank = length shape
arr_name = arrayName pt sign rank
new_array = "futhark_new_" ++ arr_name
dataptr = "data_" ++ show i
shapearr = "shape_" ++ show i
dims = [[C.cexp|$id:shapearr[$int:j]|] | j <- [0 .. rank - 1]]
num_elems = cproduct dims
item [C.citem|typename int64_t $id:shapearr[$int:rank];|]
stms $ loadValueHeader sign pt rank [C.cexp|$id:shapearr|] [C.cexp|src|]
item [C.citem|const void* $id:dataptr = src;|]
stm [C.cstm|obj->$id:field = NULL;|]
stm [C.cstm|src += $exp:num_elems * $int:(primByteSize pt::Int);|]
pure
[C.cstms|
obj->$id:field = $id:new_array(ctx, $id:dataptr, $args:dims);
if (obj->$id:field == NULL) { err = 1; }|]
load_body <- collect $ do
loads <- concat <$> zipWithM restoreComponent [0 ..] vds
stm
[C.cstm|if (err == 0) {
$stms:loads
}|]
headerDecl
(OpaqueDecl desc)
[C.cedecl|struct $id:name;|]
headerDecl
(OpaqueDecl desc)
[C.cedecl|int $id:free_opaque($ty:ctx_ty *ctx, $ty:opaque_type *obj);|]
headerDecl
(OpaqueDecl desc)
[C.cedecl|int $id:store_opaque($ty:ctx_ty *ctx, const $ty:opaque_type *obj, void **p, size_t *n);|]
headerDecl
(OpaqueDecl desc)
[C.cedecl|$ty:opaque_type* $id:restore_opaque($ty:ctx_ty *ctx, const void *p);|]
-- We do not need to enclose the body in a critical section, because
-- when we operate on the components of the opaque, we are calling
-- public API functions that do their own locking.
mapM_
libDecl
[C.cunit|
int $id:free_opaque($ty:ctx_ty *ctx, $ty:opaque_type *obj) {
int ret = 0, tmp;
$items:free_body
free(obj);
return ret;
}
int $id:store_opaque($ty:ctx_ty *ctx,
const $ty:opaque_type *obj, void **p, size_t *n) {
int ret = 0;
$items:store_body
return ret;
}
$ty:opaque_type* $id:restore_opaque($ty:ctx_ty *ctx,
const void *p) {
int err = 0;
const unsigned char *src = p;
$ty:opaque_type* obj = malloc(sizeof($ty:opaque_type));
$items:load_body
if (err != 0) {
int ret = 0, tmp;
$items:free_body
free(obj);
obj = NULL;
}
return obj;
}
|]
pure $
Manifest.OpaqueOps
{ Manifest.opaqueFree = T.pack free_opaque,
Manifest.opaqueStore = T.pack store_opaque,
Manifest.opaqueRestore = T.pack restore_opaque
}
valueDescToCType :: Publicness -> ValueDesc -> CompilerM op s C.Type
valueDescToCType _ (ScalarValue pt signed _) =
return $ primAPIType signed pt
valueDescToCType pub (ArrayValue _ space pt signed shape) = do
let rank = length shape
name <- publicName $ arrayName pt signed rank
let add = M.insertWith max (space, signed, pt, rank) pub
modify $ \s -> s {compArrayTypes = add $ compArrayTypes s}
pure [C.cty|struct $id:name|]
opaqueToCType :: String -> [ValueDesc] -> CompilerM op s C.Type
opaqueToCType desc vds = do
name <- publicName $ opaqueName desc vds
let add = M.insert desc vds
modify $ \s -> s {compOpaqueTypes = add $ compOpaqueTypes s}
-- Now ensure that the constituent array types will exist.
mapM_ (valueDescToCType Private) vds
pure [C.cty|struct $id:name|]
generateAPITypes :: CompilerM op s (M.Map T.Text Manifest.Type)
generateAPITypes = do
array_ts <- mapM generateArray . M.toList =<< gets compArrayTypes
opaque_ts <- mapM generateOpaque . M.toList =<< gets compOpaqueTypes
pure $ M.fromList $ catMaybes array_ts <> opaque_ts
where
generateArray ((space, signed, pt, rank), pub) = do
name <- publicName $ arrayName pt signed rank
let memty = fatMemType space
libDecl [C.cedecl|struct $id:name { $ty:memty mem; typename int64_t shape[$int:rank]; };|]
ops <- arrayLibraryFunctions pub space pt signed rank
let pt_name = T.pack $ prettySigned (signed == TypeUnsigned) pt
pretty_name = mconcat (replicate rank "[]") <> pt_name
arr_type = [C.cty|struct $id:name*|]
case pub of
Public ->
pure $
Just
( pretty_name,
Manifest.TypeArray (prettyText arr_type) pt_name rank ops
)
Private ->
pure Nothing
generateOpaque (desc, vds) = do
name <- publicName $ opaqueName desc vds
members <- zipWithM field vds [(0 :: Int) ..]
libDecl [C.cedecl|struct $id:name { $sdecls:members };|]
ops <- opaqueLibraryFunctions desc vds
let opaque_type = [C.cty|struct $id:name*|]
pure (T.pack desc, Manifest.TypeOpaque (prettyText opaque_type) ops)
field vd@ScalarValue {} i = do
ct <- valueDescToCType Private vd
return [C.csdecl|$ty:ct $id:(tupleField i);|]
field vd i = do
ct <- valueDescToCType Private vd
return [C.csdecl|$ty:ct *$id:(tupleField i);|]
allTrue :: [C.Exp] -> C.Exp
allTrue [] = [C.cexp|true|]
allTrue [x] = x
allTrue (x : xs) = [C.cexp|$exp:x && $exp:(allTrue xs)|]
prepareEntryInputs ::
[ExternalValue] ->
CompilerM op s ([(C.Param, Maybe C.Exp)], [C.BlockItem])
prepareEntryInputs args = collect' $ zipWithM prepare [(0 :: Int) ..] args
where
arg_names = namesFromList $ concatMap evNames args
evNames (OpaqueValue _ _ vds) = map vdName vds
evNames (TransparentValue _ vd) = [vdName vd]
vdName (ArrayValue v _ _ _ _) = v
vdName (ScalarValue _ _ v) = v
prepare pno (TransparentValue _ vd) = do
let pname = "in" ++ show pno
(ty, check) <- prepareValue Public [C.cexp|$id:pname|] vd
return
( [C.cparam|const $ty:ty $id:pname|],
if null check then Nothing else Just $ allTrue check
)
prepare pno (OpaqueValue _ desc vds) = do
ty <- opaqueToCType desc vds
let pname = "in" ++ show pno
field i ScalarValue {} = [C.cexp|$id:pname->$id:(tupleField i)|]
field i ArrayValue {} = [C.cexp|$id:pname->$id:(tupleField i)|]
checks <- map snd <$> zipWithM (prepareValue Private) (zipWith field [0 ..] vds) vds
return
( [C.cparam|const $ty:ty *$id:pname|],
if all null checks
then Nothing
else Just $ allTrue $ concat checks
)
prepareValue _ src (ScalarValue pt signed name) = do
let pt' = primAPIType signed pt
src' = fromStorage pt $ C.toExp src mempty
stm [C.cstm|$id:name = $exp:src';|]
return (pt', [])
prepareValue pub src vd@(ArrayValue mem _ _ _ shape) = do
ty <- valueDescToCType pub vd
stm [C.cstm|$exp:mem = $exp:src->mem;|]
let rank = length shape
maybeCopyDim (Var d) i
| not $ d `nameIn` arg_names =
( Just [C.cstm|$id:d = $exp:src->shape[$int:i];|],
[C.cexp|$id:d == $exp:src->shape[$int:i]|]
)
maybeCopyDim x i =
( Nothing,
[C.cexp|$exp:x == $exp:src->shape[$int:i]|]
)
let (sets, checks) =
unzip $ zipWith maybeCopyDim shape [0 .. rank - 1]
stms $ catMaybes sets
return ([C.cty|$ty:ty*|], checks)
prepareEntryOutputs :: [ExternalValue] -> CompilerM op s ([C.Param], [C.BlockItem])
prepareEntryOutputs = collect' . zipWithM prepare [(0 :: Int) ..]
where
prepare pno (TransparentValue _ vd) = do
let pname = "out" ++ show pno
ty <- valueDescToCType Public vd
case vd of
ArrayValue {} -> do
stm [C.cstm|assert((*$id:pname = ($ty:ty*) malloc(sizeof($ty:ty))) != NULL);|]
prepareValue [C.cexp|*$id:pname|] vd
return [C.cparam|$ty:ty **$id:pname|]
ScalarValue {} -> do
prepareValue [C.cexp|*$id:pname|] vd
return [C.cparam|$ty:ty *$id:pname|]
prepare pno (OpaqueValue _ desc vds) = do
let pname = "out" ++ show pno
ty <- opaqueToCType desc vds
vd_ts <- mapM (valueDescToCType Private) vds
stm [C.cstm|assert((*$id:pname = ($ty:ty*) malloc(sizeof($ty:ty))) != NULL);|]
forM_ (zip3 [0 ..] vd_ts vds) $ \(i, ct, vd) -> do
let field = [C.cexp|(*$id:pname)->$id:(tupleField i)|]
case vd of
ScalarValue {} -> return ()
_ -> stm [C.cstm|assert(($exp:field = ($ty:ct*) malloc(sizeof($ty:ct))) != NULL);|]
prepareValue field vd
return [C.cparam|$ty:ty **$id:pname|]
prepareValue dest (ScalarValue t _ name) =
let name' = toStorage t $ C.toExp name mempty
in stm [C.cstm|$exp:dest = $exp:name';|]
prepareValue dest (ArrayValue mem _ _ _ shape) = do
stm [C.cstm|$exp:dest->mem = $id:mem;|]
let rank = length shape
maybeCopyDim (Constant x) i =
[C.cstm|$exp:dest->shape[$int:i] = $exp:x;|]
maybeCopyDim (Var d) i =
[C.cstm|$exp:dest->shape[$int:i] = $id:d;|]
stms $ zipWith maybeCopyDim shape [0 .. rank - 1]
onEntryPoint ::
[C.BlockItem] ->
Name ->
Function op ->
CompilerM op s (Maybe (C.Definition, (T.Text, Manifest.EntryPoint)))
onEntryPoint _ _ (Function Nothing _ _ _ _ _) = pure Nothing
onEntryPoint get_consts fname (Function (Just ename) outputs inputs _ results args) = do
let out_args = map (\p -> [C.cexp|&$id:(paramName p)|]) outputs
in_args = map (\p -> [C.cexp|$id:(paramName p)|]) inputs
inputdecls <- collect $ mapM_ stubParam inputs
outputdecls <- collect $ mapM_ stubParam outputs
entry_point_function_name <- publicName $ "entry_" ++ nameToString ename
(inputs', unpack_entry_inputs) <- prepareEntryInputs $ map snd args
let (entry_point_input_params, entry_point_input_checks) = unzip inputs'
(entry_point_output_params, pack_entry_outputs) <-
prepareEntryOutputs results
ctx_ty <- contextType
headerDecl
EntryDecl
[C.cedecl|int $id:entry_point_function_name
($ty:ctx_ty *ctx,
$params:entry_point_output_params,
$params:entry_point_input_params);|]
let checks = catMaybes entry_point_input_checks
check_input =
if null checks
then []
else
[C.citems|
if (!($exp:(allTrue (catMaybes entry_point_input_checks)))) {
ret = 1;
if (!ctx->error) {
ctx->error = msgprintf("Error: entry point arguments have invalid sizes.\n");
}
}|]
critical =
[C.citems|
$items:unpack_entry_inputs
$items:check_input
if (ret == 0) {
ret = $id:(funName fname)(ctx, $args:out_args, $args:in_args);
if (ret == 0) {
$items:get_consts
$items:pack_entry_outputs
}
}
|]
ops <- asks envOperations
let cdef =
[C.cedecl|
int $id:entry_point_function_name
($ty:ctx_ty *ctx,
$params:entry_point_output_params,
$params:entry_point_input_params) {
$items:inputdecls
$items:outputdecls
int ret = 0;
$items:(criticalSection ops critical)
return ret;
}|]
manifest =
Manifest.EntryPoint
{ Manifest.entryPointCFun = T.pack entry_point_function_name,
-- Note that our convention about what is "input/output"
-- and what is "results/args" is different between the
-- manifest and ImpCode.
Manifest.entryPointOutputs = map outputManifest results,
Manifest.entryPointInputs = map inputManifest args
}
pure $ Just (cdef, (nameToText ename, manifest))
where
stubParam (MemParam name space) =
declMem name space
stubParam (ScalarParam name ty) = do
let ty' = primTypeToCType ty
decl [C.cdecl|$ty:ty' $id:name;|]
vdTypeAndUnique (TransparentValue _ (ScalarValue pt signed _)) =
( T.pack $ prettySigned (signed == TypeUnsigned) pt,
False
)
vdTypeAndUnique (TransparentValue u (ArrayValue _ _ pt signed shape)) =
( T.pack $
mconcat (replicate (length shape) "[]")
<> prettySigned (signed == TypeUnsigned) pt,
u == Unique
)
vdTypeAndUnique (OpaqueValue u name _) =
(T.pack name, u == Unique)
outputManifest vd =
let (t, u) = vdTypeAndUnique vd
in Manifest.Output
{ Manifest.outputType = t,
Manifest.outputUnique = u
}
inputManifest (v, vd) =
let (t, u) = vdTypeAndUnique vd
in Manifest.Input
{ Manifest.inputName = nameToText v,
Manifest.inputType = t,
Manifest.inputUnique = u
}
-- | The result of compilation to C is multiple parts, which can be
-- put together in various ways. The obvious way is to concatenate
-- all of them, which yields a CLI program. Another is to compile the
-- library part by itself, and use the header file to call into it.
data CParts = CParts
{ cHeader :: T.Text,
-- | Utility definitions that must be visible
-- to both CLI and library parts.
cUtils :: T.Text,
cCLI :: T.Text,
cServer :: T.Text,
cLib :: T.Text,
-- | The manifest, in JSON format.
cJsonManifest :: T.Text
}
gnuSource :: T.Text
gnuSource =
[untrimming|
// We need to define _GNU_SOURCE before
// _any_ headers files are imported to get
// the usage statistics of a thread (i.e. have RUSAGE_THREAD) on GNU/Linux
// https://manpages.courier-mta.org/htmlman2/getrusage.2.html
#ifndef _GNU_SOURCE // Avoid possible double-definition warning.
#define _GNU_SOURCE
#endif
|]
-- We may generate variables that are never used (e.g. for
-- certificates) or functions that are never called (e.g. unused
-- intrinsics), and generated code may have other cosmetic issues that
-- compilers warn about. We disable these warnings to not clutter the
-- compilation logs.
disableWarnings :: T.Text
disableWarnings =
[untrimming|
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wunused-variable"
#pragma clang diagnostic ignored "-Wparentheses"
#pragma clang diagnostic ignored "-Wunused-label"
#elif __GNUC__
#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wparentheses"
#pragma GCC diagnostic ignored "-Wunused-label"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
|]
-- | Produce header, implementation, and manifest files.
asLibrary :: CParts -> (T.Text, T.Text, T.Text)
asLibrary parts =
( "#pragma once\n\n" <> cHeader parts,
gnuSource <> disableWarnings <> cHeader parts <> cUtils parts <> cLib parts,
cJsonManifest parts
)
-- | As executable with command-line interface.
asExecutable :: CParts -> T.Text
asExecutable parts =
gnuSource <> disableWarnings <> cHeader parts <> cUtils parts <> cCLI parts <> cLib parts
-- | As server executable.
asServer :: CParts -> T.Text
asServer parts =
gnuSource <> disableWarnings <> cHeader parts <> cUtils parts <> cServer parts <> cLib parts
-- | Compile imperative program to a C program. Always uses the
-- function named "main" as entry point, so make sure it is defined.
compileProg ::
MonadFreshNames m =>
T.Text ->
Operations op () ->
CompilerM op () () ->
T.Text ->
[Space] ->
[Option] ->
Definitions op ->
m CParts
compileProg backend ops extra header_extra spaces options prog = do
src <- getNameSource
let ((prototypes, definitions, entry_point_decls, manifest), endstate) =
runCompilerM ops src () compileProg'
initdecls = initDecls endstate
entrydecls = entryDecls endstate
arraydecls = arrayDecls endstate
opaquedecls = opaqueDecls endstate
miscdecls = miscDecls endstate
let headerdefs =
[untrimming|
// Headers\n")
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdio.h>
#include <float.h>
$header_extra
#ifdef __cplusplus
extern "C" {
#endif
// Initialisation
$initdecls
// Arrays
$arraydecls
// Opaque values
$opaquedecls
// Entry points
$entrydecls
// Miscellaneous
$miscdecls
#define FUTHARK_BACKEND_$backend
#ifdef __cplusplus
}
#endif
|]
let utildefs =
[untrimming|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <stdint.h>
// If NDEBUG is set, the assert() macro will do nothing. Since Futhark
// (unfortunately) makes use of assert() for error detection (and even some
// side effects), we want to avoid that.
#undef NDEBUG
#include <assert.h>
#include <stdarg.h>
$utilH
$halfH
$timingH
|]
let early_decls = T.unlines $ map prettyText $ DL.toList $ compEarlyDecls endstate
lib_decls = T.unlines $ map prettyText $ DL.toList $ compLibDecls endstate
clidefs = cliDefs options manifest
serverdefs = serverDefs options manifest
libdefs =
[untrimming|
#ifdef _MSC_VER
#define inline __inline
#endif
#include <string.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <ctype.h>
$header_extra
$lockH
#define FUTHARK_F64_ENABLED
$cScalarDefs
$early_decls
$prototypes
$lib_decls
$definitions
$entry_point_decls
|]
return
CParts
{ cHeader = headerdefs,
cUtils = utildefs,
cCLI = clidefs,
cServer = serverdefs,
cLib = libdefs,
cJsonManifest = Manifest.manifestToJSON manifest
}
where
Definitions consts (Functions funs) = prog
compileProg' = do
(memstructs, memfuns, memreport) <- unzip3 <$> mapM defineMemorySpace spaces
get_consts <- compileConstants consts
ctx_ty <- contextType
(prototypes, functions) <-
unzip <$> mapM (compileFun get_consts [[C.cparam|$ty:ctx_ty *ctx|]]) funs
mapM_ earlyDecl memstructs
(entry_points, entry_points_manifest) <-
unzip . catMaybes <$> mapM (uncurry (onEntryPoint get_consts)) funs
extra
mapM_ earlyDecl $ concat memfuns
types <- commonLibFuns memreport
return
( T.unlines $ map prettyText prototypes,
T.unlines $ map (prettyText . funcToDef) functions,
T.unlines $ map prettyText entry_points,
Manifest.Manifest (M.fromList entry_points_manifest) types backend
)
funcToDef func = C.FuncDef func loc
where
loc = case func of
C.OldFunc _ _ _ _ _ _ l -> l
C.Func _ _ _ _ _ l -> l
commonLibFuns :: [C.BlockItem] -> CompilerM op s (M.Map T.Text Manifest.Type)
commonLibFuns memreport = do
types <- generateAPITypes
ctx <- contextType
ops <- asks envOperations
profilereport <- gets $ DL.toList . compProfileItems
publicDef_ "get_tuning_param_count" InitDecl $ \s ->
( [C.cedecl|int $id:s(void);|],
[C.cedecl|int $id:s(void) {
return sizeof(tuning_param_names)/sizeof(tuning_param_names[0]);
}|]
)
publicDef_ "get_tuning_param_name" InitDecl $ \s ->
( [C.cedecl|const char* $id:s(int);|],
[C.cedecl|const char* $id:s(int i) {
return tuning_param_names[i];
}|]
)
publicDef_ "get_tuning_param_class" InitDecl $ \s ->
( [C.cedecl|const char* $id:s(int);|],
[C.cedecl|const char* $id:s(int i) {
return tuning_param_classes[i];
}|]
)
sync <- publicName "context_sync"
publicDef_ "context_report" MiscDecl $ \s ->
( [C.cedecl|char* $id:s($ty:ctx *ctx);|],
[C.cedecl|char* $id:s($ty:ctx *ctx) {
if ($id:sync(ctx) != 0) {
return NULL;
}
struct str_builder builder;
str_builder_init(&builder);
if (ctx->detail_memory || ctx->profiling || ctx->logging) {
$items:memreport
}
if (ctx->profiling) {
$items:profilereport
}
return builder.str;
}|]
)
publicDef_ "context_get_error" MiscDecl $ \s ->
( [C.cedecl|char* $id:s($ty:ctx* ctx);|],
[C.cedecl|char* $id:s($ty:ctx* ctx) {
char* error = ctx->error;
ctx->error = NULL;
return error;
}|]
)
publicDef_ "context_set_logging_file" MiscDecl $ \s ->
( [C.cedecl|void $id:s($ty:ctx* ctx, typename FILE* f);|],
[C.cedecl|void $id:s($ty:ctx* ctx, typename FILE* f) {
ctx->log = f;
}|]
)
publicDef_ "context_pause_profiling" MiscDecl $ \s ->
( [C.cedecl|void $id:s($ty:ctx* ctx);|],
[C.cedecl|void $id:s($ty:ctx* ctx) {
ctx->profiling_paused = 1;
}|]
)
publicDef_ "context_unpause_profiling" MiscDecl $ \s ->
( [C.cedecl|void $id:s($ty:ctx* ctx);|],
[C.cedecl|void $id:s($ty:ctx* ctx) {
ctx->profiling_paused = 0;
}|]
)
clears <- gets $ DL.toList . compClearItems
publicDef_ "context_clear_caches" MiscDecl $ \s ->
( [C.cedecl|int $id:s($ty:ctx* ctx);|],
[C.cedecl|int $id:s($ty:ctx* ctx) {
$items:(criticalSection ops clears)
return ctx->error != NULL;
}|]
)
pure types
compileConstants :: Constants op -> CompilerM op s [C.BlockItem]
compileConstants (Constants ps init_consts) = do
ctx_ty <- contextType
const_fields <- mapM constParamField ps
-- Avoid an empty struct, as that is apparently undefined behaviour.
let const_fields'
| null const_fields = [[C.csdecl|int dummy;|]]
| otherwise = const_fields
contextField "constants" [C.cty|struct { $sdecls:const_fields' }|] Nothing
earlyDecl [C.cedecl|static int init_constants($ty:ctx_ty*);|]
earlyDecl [C.cedecl|static int free_constants($ty:ctx_ty*);|]
-- We locally define macros for the constants, so that when we
-- generate assignments to local variables, we actually assign into
-- the constants struct. This is not needed for functions, because
-- they can only read constants, not write them.
let (defs, undefs) = unzip $ map constMacro ps
init_consts' <- blockScope $ do
mapM_ resetMemConst ps
compileCode init_consts
libDecl
[C.cedecl|static int init_constants($ty:ctx_ty *ctx) {
(void)ctx;
int err = 0;
$items:defs
$items:init_consts'
$items:undefs
cleanup:
return err;
}|]
free_consts <- collect $ mapM_ freeConst ps
libDecl
[C.cedecl|static int free_constants($ty:ctx_ty *ctx) {
(void)ctx;
$items:free_consts
return 0;
}|]
mapM getConst ps
where
constParamField (ScalarParam name bt) = do
let ctp = primTypeToCType bt
return [C.csdecl|$ty:ctp $id:name;|]
constParamField (MemParam name space) = do
ty <- memToCType name space
return [C.csdecl|$ty:ty $id:name;|]
constMacro p = ([C.citem|$escstm:def|], [C.citem|$escstm:undef|])
where
p' = pretty (C.toIdent (paramName p) mempty)
def = "#define " ++ p' ++ " (" ++ "ctx->constants." ++ p' ++ ")"
undef = "#undef " ++ p'
resetMemConst ScalarParam {} = return ()
resetMemConst (MemParam name space) = resetMem name space
freeConst ScalarParam {} = return ()
freeConst (MemParam name space) = unRefMem [C.cexp|ctx->constants.$id:name|] space
getConst (ScalarParam name bt) = do
let ctp = primTypeToCType bt
return [C.citem|$ty:ctp $id:name = ctx->constants.$id:name;|]
getConst (MemParam name space) = do
ty <- memToCType name space
return [C.citem|$ty:ty $id:name = ctx->constants.$id:name;|]
cachingMemory ::
M.Map VName Space ->
([C.BlockItem] -> [C.Stm] -> CompilerM op s a) ->
CompilerM op s a
cachingMemory lexical f = do
-- We only consider lexical 'DefaultSpace' memory blocks to be
-- cached. This is not a deep technical restriction, but merely a
-- heuristic based on GPU memory usually involving larger
-- allocations, that do not suffer from the overhead of reference
-- counting.
let cached = M.keys $ M.filter (== DefaultSpace) lexical
cached' <- forM cached $ \mem -> do
size <- newVName $ pretty mem <> "_cached_size"
return (mem, size)
let lexMem env =
env
{ envCachedMem =
M.fromList (map (first (`C.toExp` noLoc)) cached')
<> envCachedMem env
}
declCached (mem, size) =
[ [C.citem|size_t $id:size = 0;|],
[C.citem|$ty:defaultMemBlockType $id:mem = NULL;|]
]
freeCached (mem, _) =
[C.cstm|free($id:mem);|]
local lexMem $ f (concatMap declCached cached') (map freeCached cached')
compileFun :: [C.BlockItem] -> [C.Param] -> (Name, Function op) -> CompilerM op s (C.Definition, C.Func)
compileFun get_constants extra (fname, func@(Function _ outputs inputs body _ _)) = do
(outparams, out_ptrs) <- unzip <$> mapM compileOutput outputs
inparams <- mapM compileInput inputs
cachingMemory (lexicalMemoryUsage func) $ \decl_cached free_cached -> do
body' <- blockScope $ compileFunBody out_ptrs outputs body
return
( [C.cedecl|static int $id:(funName fname)($params:extra, $params:outparams, $params:inparams);|],
[C.cfun|static int $id:(funName fname)($params:extra, $params:outparams, $params:inparams) {
$stms:ignores
int err = 0;
$items:decl_cached
$items:get_constants
$items:body'
cleanup:
{}
$stms:free_cached
return err;
}|]
)
where
-- Ignore all the boilerplate parameters, just in case we don't
-- actually need to use them.
ignores = [[C.cstm|(void)$id:p;|] | C.Param (Just p) _ _ _ <- extra]
compileInput (ScalarParam name bt) = do
let ctp = primTypeToCType bt
return [C.cparam|$ty:ctp $id:name|]
compileInput (MemParam name space) = do
ty <- memToCType name space
return [C.cparam|$ty:ty $id:name|]
compileOutput (ScalarParam name bt) = do
let ctp = primTypeToCType bt
p_name <- newVName $ "out_" ++ baseString name
return ([C.cparam|$ty:ctp *$id:p_name|], [C.cexp|$id:p_name|])
compileOutput (MemParam name space) = do
ty <- memToCType name space
p_name <- newVName $ baseString name ++ "_p"
return ([C.cparam|$ty:ty *$id:p_name|], [C.cexp|$id:p_name|])
derefPointer :: C.Exp -> C.Exp -> C.Type -> C.Exp
derefPointer ptr i res_t =
[C.cexp|(($ty:res_t)$exp:ptr)[$exp:i]|]
volQuals :: Volatility -> [C.TypeQual]
volQuals Volatile = [C.ctyquals|volatile|]
volQuals Nonvolatile = []
writeScalarPointerWithQuals :: PointerQuals op s -> WriteScalar op s
writeScalarPointerWithQuals quals_f dest i elemtype space vol v = do
quals <- quals_f space
let quals' = volQuals vol ++ quals
deref =
derefPointer
dest
i
[C.cty|$tyquals:quals' $ty:elemtype*|]
stm [C.cstm|$exp:deref = $exp:v;|]
readScalarPointerWithQuals :: PointerQuals op s -> ReadScalar op s
readScalarPointerWithQuals quals_f dest i elemtype space vol = do
quals <- quals_f space
let quals' = volQuals vol ++ quals
return $ derefPointer dest i [C.cty|$tyquals:quals' $ty:elemtype*|]
compileExpToName :: String -> PrimType -> Exp -> CompilerM op s VName
compileExpToName _ _ (LeafExp v _) =
return v
compileExpToName desc t e = do
desc' <- newVName desc
e' <- compileExp e
decl [C.cdecl|$ty:(primTypeToCType t) $id:desc' = $e';|]
return desc'
compileExp :: Exp -> CompilerM op s C.Exp
compileExp = compilePrimExp $ \v -> pure [C.cexp|$id:v|]
-- | Tell me how to compile a @v@, and I'll Compile any @PrimExp v@ for you.
compilePrimExp :: Monad m => (v -> m C.Exp) -> PrimExp v -> m C.Exp
compilePrimExp _ (ValueExp val) =
pure $ C.toExp val mempty
compilePrimExp f (LeafExp v _) =
f v
compilePrimExp f (UnOpExp Complement {} x) = do
x' <- compilePrimExp f x
return [C.cexp|~$exp:x'|]
compilePrimExp f (UnOpExp Not {} x) = do
x' <- compilePrimExp f x
return [C.cexp|!$exp:x'|]
compilePrimExp f (UnOpExp (FAbs Float32) x) = do
x' <- compilePrimExp f x
return [C.cexp|(float)fabs($exp:x')|]
compilePrimExp f (UnOpExp (FAbs Float64) x) = do
x' <- compilePrimExp f x
return [C.cexp|fabs($exp:x')|]
compilePrimExp f (UnOpExp SSignum {} x) = do
x' <- compilePrimExp f x
return [C.cexp|($exp:x' > 0) - ($exp:x' < 0)|]
compilePrimExp f (UnOpExp USignum {} x) = do
x' <- compilePrimExp f x
return [C.cexp|($exp:x' > 0) - ($exp:x' < 0) != 0|]
compilePrimExp f (UnOpExp op x) = do
x' <- compilePrimExp f x
return [C.cexp|$id:(pretty op)($exp:x')|]
compilePrimExp f (CmpOpExp cmp x y) = do
x' <- compilePrimExp f x
y' <- compilePrimExp f y
return $ case cmp of
CmpEq {} -> [C.cexp|$exp:x' == $exp:y'|]
FCmpLt {} -> [C.cexp|$exp:x' < $exp:y'|]
FCmpLe {} -> [C.cexp|$exp:x' <= $exp:y'|]
CmpLlt {} -> [C.cexp|$exp:x' < $exp:y'|]
CmpLle {} -> [C.cexp|$exp:x' <= $exp:y'|]
_ -> [C.cexp|$id:(pretty cmp)($exp:x', $exp:y')|]
compilePrimExp f (ConvOpExp conv x) = do
x' <- compilePrimExp f x
return [C.cexp|$id:(pretty conv)($exp:x')|]
compilePrimExp f (BinOpExp bop x y) = do
x' <- compilePrimExp f x
y' <- compilePrimExp f y
-- Note that integer addition, subtraction, and multiplication with
-- OverflowWrap are not handled by explicit operators, but rather by
-- functions. This is because we want to implicitly convert them to
-- unsigned numbers, so we can do overflow without invoking
-- undefined behaviour.
return $ case bop of
Add _ OverflowUndef -> [C.cexp|$exp:x' + $exp:y'|]
Sub _ OverflowUndef -> [C.cexp|$exp:x' - $exp:y'|]
Mul _ OverflowUndef -> [C.cexp|$exp:x' * $exp:y'|]
FAdd {} -> [C.cexp|$exp:x' + $exp:y'|]
FSub {} -> [C.cexp|$exp:x' - $exp:y'|]
FMul {} -> [C.cexp|$exp:x' * $exp:y'|]
FDiv {} -> [C.cexp|$exp:x' / $exp:y'|]
Xor {} -> [C.cexp|$exp:x' ^ $exp:y'|]
And {} -> [C.cexp|$exp:x' & $exp:y'|]
Or {} -> [C.cexp|$exp:x' | $exp:y'|]
LogAnd {} -> [C.cexp|$exp:x' && $exp:y'|]
LogOr {} -> [C.cexp|$exp:x' || $exp:y'|]
_ -> [C.cexp|$id:(pretty bop)($exp:x', $exp:y')|]
compilePrimExp f (FunExp h args _) = do
args' <- mapM (compilePrimExp f) args
return [C.cexp|$id:(funName (nameFromString h))($args:args')|]
linearCode :: Code op -> [Code op]
linearCode = reverse . go []
where
go acc (x :>>: y) =
go (go acc x) y
go acc x = x : acc
compileCode :: Code op -> CompilerM op s ()
compileCode (Op op) =
join $ asks envOpCompiler <*> pure op
compileCode Skip = return ()
compileCode (Comment s code) = do
xs <- blockScope $ compileCode code
let comment = "// " ++ s
stm
[C.cstm|$comment:comment
{ $items:xs }
|]
compileCode (TracePrint msg) = do
(formatstr, formatargs) <- errorMsgString msg
stm [C.cstm|fprintf(ctx->log, $string:formatstr, $args:formatargs);|]
compileCode (DebugPrint s (Just e)) = do
e' <- compileExp e
stm
[C.cstm|if (ctx->debugging) {
fprintf(ctx->log, $string:fmtstr, $exp:s, ($ty:ety)$exp:e', '\n');
}|]
where
(fmt, ety) = case primExpType e of
IntType _ -> ("llu", [C.cty|long long int|])
FloatType _ -> ("f", [C.cty|double|])
_ -> ("d", [C.cty|int|])
fmtstr = "%s: %" ++ fmt ++ "%c"
compileCode (DebugPrint s Nothing) =
stm
[C.cstm|if (ctx->debugging) {
fprintf(ctx->log, "%s\n", $exp:s);
}|]
-- :>>: is treated in a special way to detect declare-set pairs in
-- order to generate prettier code.
compileCode (c1 :>>: c2) = go (linearCode (c1 :>>: c2))
where
go (DeclareScalar name vol t : SetScalar dest e : code)
| name == dest = do
let ct = primTypeToCType t
e' <- compileExp e
item [C.citem|$tyquals:(volQuals vol) $ty:ct $id:name = $exp:e';|]
go code
go (x : xs) = compileCode x >> go xs
go [] = pure ()
compileCode (Assert e msg (loc, locs)) = do
e' <- compileExp e
err <-
collect . join $
asks (opsError . envOperations) <*> pure msg <*> pure stacktrace
stm [C.cstm|if (!$exp:e') { $items:err }|]
where
stacktrace = prettyStacktrace 0 $ map locStr $ loc : locs
compileCode (Allocate _ _ ScalarSpace {}) =
-- Handled by the declaration of the memory block, which is
-- translated to an actual array.
return ()
compileCode (Allocate name (Count (TPrimExp e)) space) = do
size <- compileExp e
cached <- cacheMem name
case cached of
Just cur_size ->
stm
[C.cstm|if ($exp:cur_size < (size_t)$exp:size) {
$exp:name = realloc($exp:name, $exp:size);
$exp:cur_size = $exp:size;
}|]
_ ->
allocMem name size space [C.cstm|{err = 1; goto cleanup;}|]
compileCode (Free name space) = do
cached <- isJust <$> cacheMem name
unless cached $ unRefMem name space
compileCode (For i bound body) = do
let i' = C.toIdent i
t = primTypeToCType $ primExpType bound
bound' <- compileExp bound
body' <- blockScope $ compileCode body
stm
[C.cstm|for ($ty:t $id:i' = 0; $id:i' < $exp:bound'; $id:i'++) {
$items:body'
}|]
compileCode (While cond body) = do
cond' <- compileExp $ untyped cond
body' <- blockScope $ compileCode body
stm
[C.cstm|while ($exp:cond') {
$items:body'
}|]
compileCode (If cond tbranch fbranch) = do
cond' <- compileExp $ untyped cond
tbranch' <- blockScope $ compileCode tbranch
fbranch' <- blockScope $ compileCode fbranch
stm $ case (tbranch', fbranch') of
(_, []) ->
[C.cstm|if ($exp:cond') { $items:tbranch' }|]
([], _) ->
[C.cstm|if (!($exp:cond')) { $items:fbranch' }|]
_ ->
[C.cstm|if ($exp:cond') { $items:tbranch' } else { $items:fbranch' }|]
compileCode (Copy dest (Count destoffset) DefaultSpace src (Count srcoffset) DefaultSpace (Count size)) =
join $
copyMemoryDefaultSpace
<$> rawMem dest
<*> compileExp (untyped destoffset)
<*> rawMem src
<*> compileExp (untyped srcoffset)
<*> compileExp (untyped size)
compileCode (Copy dest (Count destoffset) destspace src (Count srcoffset) srcspace (Count size)) = do
copy <- asks envCopy
join $
copy
<$> rawMem dest
<*> compileExp (untyped destoffset)
<*> pure destspace
<*> rawMem src
<*> compileExp (untyped srcoffset)
<*> pure srcspace
<*> compileExp (untyped size)
compileCode (Write _ _ Unit _ _ _) = pure ()
compileCode (Write dest (Count idx) elemtype DefaultSpace vol elemexp) = do
dest' <- rawMem dest
deref <-
derefPointer dest'
<$> compileExp (untyped idx)
<*> pure [C.cty|$tyquals:(volQuals vol) $ty:(primStorageType elemtype)*|]
elemexp' <- toStorage elemtype <$> compileExp elemexp
stm [C.cstm|$exp:deref = $exp:elemexp';|]
compileCode (Write dest (Count idx) _ ScalarSpace {} _ elemexp) = do
idx' <- compileExp (untyped idx)
elemexp' <- compileExp elemexp
stm [C.cstm|$id:dest[$exp:idx'] = $exp:elemexp';|]
compileCode (Write dest (Count idx) elemtype (Space space) vol elemexp) =
join $
asks envWriteScalar
<*> rawMem dest
<*> compileExp (untyped idx)
<*> pure (primStorageType elemtype)
<*> pure space
<*> pure vol
<*> (toStorage elemtype <$> compileExp elemexp)
compileCode (Read x _ _ Unit __ _) =
stm [C.cstm|$id:x = $exp:(UnitValue);|]
compileCode (Read x src (Count iexp) restype DefaultSpace vol) = do
src' <- rawMem src
e <-
fmap (fromStorage restype) $
derefPointer src'
<$> compileExp (untyped iexp)
<*> pure [C.cty|$tyquals:(volQuals vol) $ty:(primStorageType restype)*|]
stm [C.cstm|$id:x = $exp:e;|]
compileCode (Read x src (Count iexp) restype (Space space) vol) = do
e <-
fmap (fromStorage restype) . join $
asks envReadScalar
<*> rawMem src
<*> compileExp (untyped iexp)
<*> pure (primStorageType restype)
<*> pure space
<*> pure vol
stm [C.cstm|$id:x = $exp:e;|]
compileCode (Read x src (Count iexp) _ ScalarSpace {} _) = do
iexp' <- compileExp $ untyped iexp
stm [C.cstm|$id:x = $id:src[$exp:iexp'];|]
compileCode (DeclareMem name space) =
declMem name space
compileCode (DeclareScalar name vol t) = do
let ct = primTypeToCType t
decl [C.cdecl|$tyquals:(volQuals vol) $ty:ct $id:name;|]
compileCode (DeclareArray name ScalarSpace {} _ _) =
error $ "Cannot declare array " ++ pretty name ++ " in scalar space."
compileCode (DeclareArray name DefaultSpace t vs) = do
name_realtype <- newVName $ baseString name ++ "_realtype"
let ct = primTypeToCType t
case vs of
ArrayValues vs' -> do
let vs'' = [[C.cinit|$exp:v|] | v <- vs']
earlyDecl [C.cedecl|static $ty:ct $id:name_realtype[$int:(length vs')] = {$inits:vs''};|]
ArrayZeros n ->
earlyDecl [C.cedecl|static $ty:ct $id:name_realtype[$int:n];|]
-- Fake a memory block.
contextField
(C.toIdent name noLoc)
[C.cty|struct memblock|]
$ Just [C.cexp|(struct memblock){NULL, (char*)$id:name_realtype, 0}|]
item [C.citem|struct memblock $id:name = ctx->$id:name;|]
compileCode (DeclareArray name (Space space) t vs) =
join $
asks envStaticArray
<*> pure name
<*> pure space
<*> pure t
<*> pure vs
-- For assignments of the form 'x = x OP e', we generate C assignment
-- operators to make the resulting code slightly nicer. This has no
-- effect on performance.
compileCode (SetScalar dest (BinOpExp op (LeafExp x _) y))
| dest == x,
Just f <- assignmentOperator op = do
y' <- compileExp y
stm [C.cstm|$exp:(f dest y');|]
compileCode (SetScalar dest src) = do
src' <- compileExp src
stm [C.cstm|$id:dest = $exp:src';|]
compileCode (SetMem dest src space) =
setMem dest src space
compileCode (Call dests fname args) =
join $
asks (opsCall . envOperations)
<*> pure dests
<*> pure fname
<*> mapM compileArg args
where
compileArg (MemArg m) = return [C.cexp|$exp:m|]
compileArg (ExpArg e) = compileExp e
blockScope :: CompilerM op s () -> CompilerM op s [C.BlockItem]
blockScope = fmap snd . blockScope'
blockScope' :: CompilerM op s a -> CompilerM op s (a, [C.BlockItem])
blockScope' m = do
old_allocs <- gets compDeclaredMem
(x, xs) <- collect' m
new_allocs <- gets $ filter (`notElem` old_allocs) . compDeclaredMem
modify $ \s -> s {compDeclaredMem = old_allocs}
releases <- collect $ mapM_ (uncurry unRefMem) new_allocs
return (x, xs <> releases)
compileFunBody :: [C.Exp] -> [Param] -> Code op -> CompilerM op s ()
compileFunBody output_ptrs outputs code = do
mapM_ declareOutput outputs
compileCode code
zipWithM_ setRetVal' output_ptrs outputs
where
declareOutput (MemParam name space) =
declMem name space
declareOutput (ScalarParam name pt) = do
let ctp = primTypeToCType pt
decl [C.cdecl|$ty:ctp $id:name;|]
setRetVal' p (MemParam name space) = do
resetMem [C.cexp|*$exp:p|] space
setMem [C.cexp|*$exp:p|] name space
setRetVal' p (ScalarParam name _) =
stm [C.cstm|*$exp:p = $id:name;|]
assignmentOperator :: BinOp -> Maybe (VName -> C.Exp -> C.Exp)
assignmentOperator Add {} = Just $ \d e -> [C.cexp|$id:d += $exp:e|]
assignmentOperator Sub {} = Just $ \d e -> [C.cexp|$id:d -= $exp:e|]
assignmentOperator Mul {} = Just $ \d e -> [C.cexp|$id:d *= $exp:e|]
assignmentOperator _ = Nothing
|
HIPERFIT/futhark
|
src/Futhark/CodeGen/Backends/GenericC.hs
|
isc
| 74,170 | 0 | 19 | 18,827 | 18,834 | 9,979 | 8,855 | 1,484 | 18 |
module Main where
import Debug.Trace (trace)
import System.Environment
import Parser
import Quote
import Data.Matrix as M hiding (trace)
import Data.List as L
import Data.List.Split
import Data.Vector as V hiding (foldl)
[agpl_f|ttt.agpl|]
--[agpl_f|chess.agpl|]
--[agpl_f|connect4.agpl|]
getMove :: GameState -> IO Move
getMove gs = do {
putStrLn ("Player " L.++ (show (currentTurn gs)) L.++ "'s turn." L.++
"Please enter a move:");
m <- getLine;
return (fromString m);
}
won :: Player -> IO ()
won p = do {
putStrLn ("Player " L.++ (show p) L.++ " has won!");
return ();
}
tie :: IO ()
tie = do {
putStrLn "The game has ended in a tie.";
return ();
}
playGame :: GameState -> IO ()
playGame gs = do {
m <- getMove gs;
if isValid gs m then
let (result, i) = outcome gs m
in (case result of
(Win p) -> (won p)
(Tie) -> tie
x -> (trace (show (board x)) (playGame x)))
else do {
putStrLn "Invalid move, try again.";
(playGame gs);
}
}
main :: IO ()
main = let gs = GameState{board = (boardInitF), currentTurn=turn} in
do{
playGame gs;
return ();
}
|
matthew-eads/agpl
|
Main.hs
|
isc
| 1,442 | 0 | 19 | 584 | 470 | 254 | 216 | -1 | -1 |
data Tuple a b c d = One a
| Two a b
| Three a b c
| Four a b c d
tuple1 :: Tuple a b c d -> Maybe a
tuple1 (One a) = Just a
tuple1 (Two a b) = Just a
tuple1 (Three a b c) = Just a
tuple1 (Four a b c d) = Just a
tuple2 :: Tuple a b c d -> Maybe b
tuple2 (One a) = Nothing
tuple2 (Two a b) = Just b
tuple2 (Three a b c) = Just b
tuple2 (Four a b c d) = Just b
tuple3 :: Tuple a b c d -> Maybe c
tuple3 (One a) = Nothing
tuple3 (Two a b) = Nothing
tuple3 (Three a b c) = Just c
tuple3 (Four a b c d) = Just c
tuple4 :: Tuple a b c d -> Maybe d
tuple4 (One a) = Nothing
tuple4 (Two a b) = Nothing
tuple4 (Three a b c) = Nothing
tuple4 (Four a b c d) = Just d
to_haskell_tuple :: Tuple a b c d -> Either (Either a (a, b)) (Either (a, b, c) (a, b, c, d))
to_haskell_tuple (One a) = Left (Left a )
to_haskell_tuple (Two a b) = Left (Right (a, b) )
to_haskell_tuple (Three a b c) = Right (Left (a, b, c) )
to_haskell_tuple (Four a b c d) = Right (Right (a, b, c, d))
|
fossilet/yaht
|
ex_4.6_4.7.hs
|
mit
| 1,128 | 0 | 9 | 410 | 624 | 315 | 309 | 29 | 1 |
{- Part of possum4
Copyright (c) 2014 darkf
Licensed under the terms of the MIT license
See LICENSE.txt for details -}
module IntegrationTests where
import Test.HUnit
import AST
import Parser
import Interpreter
runSource :: String -> IO Value
runSource = interpret . parseStringWith builtinArities
actual @??= expected = actual >>= (@?= expected)
source $$= expected = runSource source @??= expected
-- Empty test
empty_test = TestCase $ "" $$= Nil
-- Literals
literals_test = TestCase $ do
"123" $$= Number 123.0
"123.0" $$= Number 123.0
"123.5" $$= Number 123.5
"nil" $$= Nil
-- Built-in application
app_bif_test = TestCase $ do
"id 123" $$= Number 123.0
"+ 1 4" $$= Number 5.0
-- def
def_test = TestCase $ do
"def x 123" $$= Number 123.0
"def x 123\nx" $$= Number 123.0
"def x + 1 4\n" $$= Number 5.0
-- defun
defun_test = TestCase $ do
"defun f is end" $$= Fn [] []
"defun f x is end" $$= Fn [Var "x"] []
"defun f x is + 1 2 end" $$= Fn [Var "x"] [Apply (Var "+") [NumLit 1.0, NumLit 2.0]]
-- function test
fn_test = TestCase $ do
"defun f is end\nf" $$= Nil
"defun f x is end\nf 1" $$= Nil
"defun f x is + 1 2 end\nf 1" $$= Number 3.0
"defun f x is + 1 x end\nf 4" $$= Number 5.0
integrationTests = TestList [
TestLabel "empty_test" empty_test,
TestLabel "literals_test" literals_test,
TestLabel "app_bif_test" app_bif_test,
TestLabel "def_test" def_test,
TestLabel "defun_test" defun_test,
TestLabel "fn_test" fn_test
]
|
darkf/possum4
|
IntegrationTests.hs
|
mit
| 1,483 | 14 | 13 | 308 | 415 | 202 | 213 | 38 | 1 |
{-# LANGUAGE NoStarIsType #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}
{-# OPTIONS_GHC -fconstraint-solver-iterations=20 #-}
module AI.Funn.CL.Flat (
reluDiff, sigmoidDiff, tanhDiff,
fcDiff, quadraticCost, splitDiff, mergeDiff,
softmaxCost
) where
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import Data.Proxy
import qualified Data.Vector.Generic as V
import qualified Data.Vector.Storable as S
import Debug.Trace
import qualified Foreign.OpenCL.Bindings as CL
import GHC.Float
import GHC.TypeLits
import System.IO.Unsafe
import AI.Funn.CL.Blob
import qualified AI.Funn.CL.Blob as Blob
import AI.Funn.CL.DSL.Array
import AI.Funn.CL.DSL.Code as C
import AI.Funn.CL.Function
import AI.Funn.CL.MonadCL
import AI.Funn.Diff.Diff (Derivable(..), Diff(..))
import AI.Funn.Space
import AI.Funn.TypeLits
data KName = ReluF Precision
| ReluB Precision
| SigmoidF Precision
| SigmoidB Precision
| TanhF Precision
| TanhB Precision
| FCForward Precision
| FCBackWS Precision
| FCBackXS Precision
| FCBackBS Precision
| SoftmaxF Precision
| SoftmaxB Precision
deriving (Show, Eq, Ord)
{-# NOINLINE memoTable #-}
memoTable :: KTable KName
memoTable = newKTable unsafePerformIO
reluDiff :: forall n m a. (MonadIO m, KnownNat n, Relational a, CLFloats a) => Diff m (Blob a n) (Blob a n)
reluDiff = Diff run
where
run xs = do
ys <- relu xs
return (ys, reluBack xs)
relu = mapBlob' memoTable (ReluF (precision @a)) (\x -> fmax 0 x)
reluBack = zipWithBlob' memoTable (ReluB (precision @a)) (\x dy -> fstep 0 x * dy)
sigmoidDiff :: forall n m a. (MonadIO m, KnownNat n, CLFloats a) => Diff m (Blob a n) (Blob a n)
sigmoidDiff = Diff run
where
run xs = do
ys <- sigmoid xs
return (ys, sigmoidBack xs)
sigmoid = mapBlob memoTable (SigmoidF (precision @a)) $ \x -> do
z <- eval (exp x)
return $ z / (1 + z)
sigmoidBack = zipWithBlob memoTable (SigmoidB (precision @a)) $ \x dy -> do
z <- eval $ exp (-abs x)
return $ dy * z / (1 + z)^2
tanhDiff :: forall n m a. (MonadIO m, KnownNat n, CLFloats a) => Diff m (Blob a n) (Blob a n)
tanhDiff = Diff run
where
run xs = do
ys <- tanhForward xs
return (ys, tanhBack xs)
tanhForward = mapBlob memoTable (TanhF (precision @a)) $ \x -> do
zp <- eval (exp x)
zm <- eval (exp (-x))
return $ (zp - zm) / (zp + zm)
tanhBack = zipWithBlob memoTable (TanhB (precision @a)) $ \x dy -> do
zp <- eval $ exp x
zm <- eval $ exp (-x)
z <- eval $ 2 / (zp + zm)
return $ dy * z^2
quadraticCost :: forall n m a. (MonadIO m, KnownNat n, CLFloats a) => Diff m (Blob a n, Blob a n) Double
quadraticCost = Diff run
where
run (xs, ys) = do
ds <- subBlob xs ys
rs <- Blob.toList ds
let o = sum [x^2 | x <- rs]
return (o, backward ds)
backward ds δ = do
dx <- scaleBlob (2 * δ) ds
dy <- scaleBlob (-2 * δ) ds
return (dx, dy)
softmaxCost :: forall n m a. (MonadIO m, KnownNat n, CLFloats a) => Diff m (Blob a n, Int) Double
softmaxCost = Diff run
where run (bo, target) = do
o <- Blob.createBlob @ 2
liftIO (forwardKernel n target bo o)
~[s, cost] <- Blob.toList o
return (cost, backward target s bo)
backward target s bo dcost = do
dbo <- Blob.createBlob
liftIO (backwardKernel target s bo dbo)
db' <- Blob.unsafeFreeze dbo
return (db', ())
forwardKernel :: Int -> Int -> Blob a n -> MBlob a 2 -> IO ()
forwardKernel = memoc memoTable (SoftmaxF (precision @a)) forwardSrc [1]
forwardSrc :: Expr Int -> Expr Int -> ArrayR a -> ArrayW a -> CL ()
forwardSrc n t os out = do
total <- initvar 0
forEach 0 n $ \i -> do
total .= total + exp (at os i)
at out 0 .= total
at out 1 .= log total - at os t
delta i j = cond (feq i j) 1 0
backwardKernel :: Int -> Double -> Blob a n -> MBlob a n -> IO ()
backwardKernel = memoc memoTable (SoftmaxB (precision @a)) backwardSrc [n]
backwardSrc :: Expr Int -> Expr Double -> ArrayR a -> ArrayW a -> CL ()
backwardSrc t s os out = do
i <- get_global_id 0
at out i .= exp (at os i) / castFloat s - delta i t
castFloat :: forall a b. (CLFloats a, CLFloats b) => Expr a -> Expr b
castFloat (Expr a) = (Expr a)
n = fromIntegral $ natVal (Proxy @ n)
fcDiff :: forall α β a m. (MonadIO m, KnownNat α, KnownNat β, CLFloats a) =>
Diff m (Blob a (α * β + β), Blob a α) (Blob a β)
fcDiff = Diff run
where
run (pars, xs) = do
ys <- createBlob
liftIO $ forwardK [β] α β pars xs ys
frozen_ys <- unsafeFreeze ys
return (frozen_ys, backward pars xs)
backward pars xs dys = do
dpars <- createBlob
dxs <- createBlob
let (dws :: MBlob a (α * β), dbs :: MBlob a β) = splitBlob dpars
liftIO $ do
backwardwsK [α, β] α xs dys dws
backwardxsK [α] α β pars dys dxs
backwardbsK [β] dys dbs
frozen_dpars <- unsafeFreeze dpars
frozen_dxs <- unsafeFreeze dxs
return (frozen_dpars, frozen_dxs)
kahan :: Expr a -> (Expr Int -> Expr a) -> Expr Int -> CL (Expr a)
kahan initial inputs count = do
total <- eval initial
comp <- eval 0
forEach 0 count $ \x -> do
input <- eval (inputs x)
add <- eval (input - comp)
t <- eval (total + add)
comp .= (t - total) - add;
total .= t;
return total
forwardK :: [Int] -> Int -> Int -> Blob a (α * β + β) -> Blob a α -> MBlob a β -> IO ()
forwardK = memoc memoTable (FCForward (precision @a)) forwardSrc
forwardSrc :: Expr Int -> Expr Int -> ArrayR a -> ArrayR a -> ArrayW a -> CL ()
forwardSrc α β pars xs ys = do
y <- get_global_id 0
let
inputs x = (pars `at` (α * y + x)) * (xs `at` x)
total <- kahan (pars `at` (α*β + y)) inputs α
at ys y .= total
backwardwsK :: [Int] -> Int -> Blob a α -> Blob a β -> MBlob a (α * β) -> IO ()
backwardwsK = memoc memoTable (FCBackWS (precision @a)) backwardwsSrc
backwardwsSrc :: Expr Int -> ArrayR a -> ArrayR a -> ArrayW a -> CL ()
backwardwsSrc α xs dys dws = do
x <- get_global_id 0
y <- get_global_id 1
at dws (y * α + x) .= (xs `at` x) * (dys `at` y)
backwardxsK :: [Int] -> Int -> Int -> Blob a (α * β + β) -> Blob a β -> MBlob a α -> IO ()
backwardxsK = memoc memoTable (FCBackXS (precision @a)) backwardxsSrc
backwardxsSrc :: Expr Int -> Expr Int -> ArrayR a -> ArrayR a -> ArrayW a -> CL ()
backwardxsSrc α β pars dys dxs = do
x <- get_global_id 0
let
inputs y = at pars (α * y + x) * at dys y
total <- kahan 0 inputs β
at dxs x .= total
backwardbsK :: [Int] -> Blob a β -> MBlob a β -> IO ()
backwardbsK = memoc memoTable (FCBackBS (precision @a)) backwardbsSrc
backwardbsSrc :: ArrayR a -> ArrayW a -> CL ()
backwardbsSrc dys dbs = do
y <- get_global_id 0
at dbs y .= at dys y
α = fromIntegral $ natVal (Proxy :: Proxy α)
β = fromIntegral $ natVal (Proxy :: Proxy β)
splitDiff :: forall α β a m. (MonadIO m, KnownNat α, KnownNat β, CLFloats a) =>
Diff m (Blob a (α + β)) (Blob a α, Blob a β)
splitDiff = Diff run
where
run ab = pure (splitBlob ab, backward)
backward (da, db) = pure (catBlob da db)
mergeDiff :: forall α β a m. (MonadIO m, KnownNat α, KnownNat β, CLFloats a) =>
Diff m (Blob a α, Blob a β) (Blob a (α + β))
mergeDiff = Diff run
where
run (a,b) = pure (catBlob a b, backward)
backward dab = pure (splitBlob dab)
|
nshepperd/funn
|
AI/Funn/CL/Flat.hs
|
mit
| 8,356 | 1 | 17 | 2,550 | 3,530 | 1,779 | 1,751 | 197 | 1 |
{-# LANGUAGE JavaScriptFFI #-}
-- | An implementation of the NodeJS elliptic-curve Diffie-Hellman API, as
-- documented <https://nodejs.org/api/crypto.html#crypto_class_ecdh here>.
module GHCJS.Node.Crypto.ECDH
( module GHCJS.Node.Crypto.ECDH -- FIXME: specific export list
) where
import GHCJS.Array
import GHCJS.Foreign.Callback
import GHCJS.Types
-- | An Elliptic Curve Diffie-Hellman (ECDH) key exchange object.
newtype ECDH
= MkECDH JSVal
-- | Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a
-- predefined curve specified by the given string. Use 'unsafeGetCurves' to
-- obtain a list of available curve names.
--
-- On recent OpenSSL releases, @openssl ecparam -list_curves@ will also
-- display the name and description of each available elliptic curve.
foreign import javascript safe
"$r = crypto.createECDH($1);"
unsafeCreateECDH :: JSString -- ^ @curve_name@
-> IO ECDH
-- | Get a list of supported elliptic curve names.
foreign import javascript safe
"$r = crypto.getCurves();"
unsafeGetCurves :: IO (Array JSString)
-- FIXME: implement <ECDH>.computeSecret
-- FIXME: implement <ECDH>.generateKeys
-- FIXME: implement <ECDH>.getPrivateKey
-- FIXME: implement <ECDH>.getPublicKey
-- FIXME: implement <ECDH>.setPrivateKey
|
taktoa/ghcjs-electron
|
src/GHCJS/Node/Crypto/ECDH.hs
|
mit
| 1,338 | 5 | 7 | 243 | 106 | 69 | 37 | 13 | 0 |
module Quark.Debug where
import System.Directory ( getHomeDirectory )
import System.FilePath ( joinPath )
dbgFile :: IO FilePath
dbgFile = (\h -> joinPath [h, "quarkDebug.log"]) <$> getHomeDirectory
dbgClear :: IO ()
dbgClear = (\p -> writeFile p "") =<< dbgFile
dbg :: String -> IO ()
dbg s = (\p -> appendFile p s) =<< dbgFile
|
sjpet/quark
|
src/Quark/Debug.hs
|
mit
| 334 | 0 | 9 | 60 | 131 | 72 | 59 | 9 | 1 |
import qualified System.Environment as Env
import qualified System.IO as IO
import qualified Data.Maybe as Maybe
import qualified Calcul
main :: IO ()
main = do
args <- Env.getArgs
pure_main args
where
pure_main :: [String] -> IO ()
pure_main args
| length args == 1 = inner
| otherwise = IO.hPutStrLn IO.stderr ".."
where
inner :: IO ()
inner
| n == Nothing = IO.hPutStrLn IO.stderr "..."
| otherwise = putStr calculs
where
n = readMaybe (args!!0)
calculs = Calcul.calcul (Maybe.fromJust n)
readMaybe :: (Read r) => String -> Maybe r
readMaybe s =
case reads s of
[(i, "")] -> Just i
_ -> Nothing
|
Engil/Integ
|
haskell/main.hs
|
mit
| 816 | 0 | 14 | 323 | 260 | 133 | 127 | 23 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE IncoherentInstances #-}
{-# LANGUAGE LambdaCase #-}
--------------------------------------------------------------------
-- |
-- Module : Data.Ruby.Marshal.RubyObject
-- Copyright : (c) Philip Cunningham, 2015
-- License : MIT
--
-- Maintainer: [email protected]
-- Stability : experimental
-- Portability: portable
--
-- Core RubyObject data representation.
--
--------------------------------------------------------------------
module Data.Ruby.Marshal.RubyObject where
import Control.Applicative
import Control.Arrow ((***))
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as DM
import Data.Ruby.Marshal.Encoding (RubyStringEncoding (..))
import qualified Data.Vector as V
import Prelude
-- | Representation of a Ruby object.
data RubyObject
= RNil
-- ^ represents @nil@
| RBool !Bool
-- ^ represents @true@ or @false@
| RFixnum {-# UNPACK #-} !Int
-- ^ represents a @Fixnum@
| RArray !(V.Vector RubyObject)
-- ^ represents an @Array@
| RHash !(V.Vector (RubyObject, RubyObject))
-- ^ represents an @Hash@
| RIVar !(RubyObject, RubyStringEncoding)
-- ^ represents an @IVar@
| RString !BS.ByteString
-- ^ represents a @String@
| RFloat {-# UNPACK #-} !Float
-- ^ represents a @Float@
| RSymbol !BS.ByteString
-- ^ represents a @Symbol@
| Unsupported
-- ^ represents an invalid object
deriving (Eq, Ord, Show)
-- | Transform plain Haskell values to RubyObjects and back.
class Rubyable a where
-- | Takes a plain Haskell value and lifts into RubyObject
toRuby :: a -> RubyObject
-- | Takes a RubyObject transforms it into a more general Haskell value.
fromRuby :: RubyObject -> Maybe a
-- core instances
instance Rubyable RubyObject where
toRuby = id
fromRuby = Just
instance Rubyable () where
toRuby _ = RNil
fromRuby = \case
RNil -> Just ()
_ -> Nothing
instance Rubyable Bool where
toRuby = RBool
fromRuby = \case
RBool x -> Just x
_ -> Nothing
instance Rubyable Int where
toRuby = RFixnum
fromRuby = \case
RFixnum x -> Just x
_ -> Nothing
instance Rubyable a => Rubyable (V.Vector a) where
toRuby = RArray . V.map toRuby
fromRuby = \case
RArray x -> V.mapM fromRuby x
_ -> Nothing
instance (Rubyable a, Rubyable b) => Rubyable (V.Vector (a, b)) where
toRuby x = RHash $ V.map (toRuby *** toRuby) x
fromRuby = \case
RHash x -> V.mapM (\(k, v) -> (,) <$> fromRuby k <*> fromRuby v) x
_ -> Nothing
instance Rubyable BS.ByteString where
toRuby = RSymbol
fromRuby = \case
RSymbol x -> Just x
_ -> Nothing
instance Rubyable Float where
toRuby = RFloat
fromRuby = \case
RFloat x -> Just x
_ -> Nothing
instance Rubyable (BS.ByteString, RubyStringEncoding) where
toRuby (x, y) = RIVar (RString x, y)
fromRuby = \case
RIVar (RString x, y) -> Just (x, y)
_ -> Nothing
-- nil like
instance Rubyable a => Rubyable (Maybe a) where
toRuby = \case
Just x -> toRuby x
Nothing -> RNil
fromRuby = \case
RNil -> Just Nothing
x -> fromRuby x
-- array like
instance Rubyable a => Rubyable [a] where
toRuby = toRuby . V.fromList
fromRuby x = V.toList <$> fromRuby x
-- map like
instance (Rubyable a, Rubyable b) => Rubyable [(a, b)] where
toRuby = toRuby . V.fromList
fromRuby x = V.toList <$> fromRuby x
instance (Rubyable a, Rubyable b, Ord a) => Rubyable (DM.Map a b) where
toRuby = toRuby . DM.toList
fromRuby x = DM.fromList <$> fromRuby x
|
filib/ruby-marshal
|
src/Data/Ruby/Marshal/RubyObject.hs
|
mit
| 3,796 | 0 | 14 | 1,030 | 969 | 527 | 442 | 97 | 0 |
module TypeInference1 where
f :: Num a => a -> a -> a
f x y = x + y + 3
g x y = x + y + 3
-- Intermission: Exercises
-- Look at these pairs of functions. One function is unapplied, so the compiler
-- will infer maximally polymorphic type. The second func- tion has been applied
-- to a value, so the inferred type signature may have become concrete, or at
-- least less polymorphic. Figure out how the type would change and why, make a
-- note of what you think the new inferred type would be and then check your
-- work in GHCi.
-- 1. -- Type signature of general function (++) :: [a] -> [a] -> [a] How might
-- that change when we apply it to the following value?
myConcat x = x ++ " yo"
myConcat :: [Char] -> [Char]
-- 2. -- General function
-- (*) :: Num a => a -> a -> a
-- Applied to a value
myMult x = (x / 3) * 5
myMult :: (Fractional a) => a -> a
-- 3. take :: Int -> [a] -> [a]
myTake x = take x "hey you"
myTake :: Int -> [Char]
-- 4. (>) :: Ord a => a -> a -> Bool
myCom x = x > (length [1..10])
myCom :: Int -> Bool
-- 5. (<) :: Ord a => a -> a -> Bool
myAlph x = x < 'z'
myAlph :: Char -> Bool
|
diminishedprime/.org
|
reading-list/haskell_programming_from_first_principles/05_07.hs
|
mit
| 1,121 | 0 | 8 | 269 | 217 | 122 | 95 | 14 | 1 |
{-# LANGUAGE NamedFieldPuns #-}
module Sajson
( Value
, Array
, Object
, ParseError (..)
, Type (..)
, parse
, typeOf
, asArray
, asObject
, asInt
, asDouble
, asNumber
, asString
, asByteString
, getArrayElement
, Sajson.length
, numKeys
, getObjectKey
, getObjectValue
, indexOfObjectKey
, getObjectWithKey
) where
import Prelude hiding (length)
import Control.DeepSeq (force)
import System.IO.Unsafe (unsafePerformIO)
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Marshal.Alloc (alloca)
import Foreign.C.Types (CChar)
import Foreign.Storable
import Data.Text (Text)
import Data.Text.Foreign
import Data.Word
import Data.Text.Encoding
import Data.ByteString (ByteString)
import qualified Data.ByteString.Internal as BS
import qualified Data.ByteString.Unsafe as BS
data CppParser
data CppDocument
data CppValue
-- I am not sure if this is correct.
-- The lifetime of documents and values is dependent on the lifetime of the parser, so
-- all Values retain the ForeignPtr.
data Value = Value !(ForeignPtr CppParser) !(ForeignPtr CppValue)
vParser :: Value -> ForeignPtr CppParser
vParser (Value p _) = p
newtype Array = Array Value
deriving (Eq, Show)
newtype Object = Object Value
deriving (Eq, Show)
data ParseError = ParseError Int Int Text
deriving (Show, Eq)
data Type = TInteger | TDouble | TNull | TFalse | TTrue | TString | TArray | TObject
deriving (Show, Eq)
typeFromInt :: (Show i, Integral i) => i -> Type
typeFromInt p =
case p of
0 -> TInteger
1 -> TDouble
2 -> TNull
3 -> TFalse
4 -> TTrue
5 -> TString
6 -> TArray
7 -> TObject
_ -> error $ "Unexpected type from sajson: " ++ (show p)
{-
intFromType :: Integral i => Type -> i
intFromType ty = case ty of
TInteger -> 0
TDouble -> 1
TNull -> 2
TFalse -> 3
TTrue -> 4
TString -> 5
TArray -> 6
TObject -> 7
-}
foreign import ccall unsafe "sj_parser" sj_parser :: Word -> (Ptr CChar) -> IO (Ptr CppParser)
foreign import ccall unsafe "&sj_parser_free" sj_parser_free :: FunPtr (Ptr CppParser -> IO ())
foreign import ccall unsafe "sj_parser_get_document" sj_parser_get_document :: Ptr CppParser -> IO (Ptr CppDocument)
foreign import ccall unsafe "&sj_document_free" sj_document_free :: FunPtr (Ptr CppDocument -> IO ())
foreign import ccall unsafe "sj_document_is_valid" sj_document_is_valid :: Ptr CppDocument -> IO Bool
foreign import ccall unsafe "sj_document_get_error_line" sj_document_get_error_line :: Ptr CppDocument -> IO Int
foreign import ccall unsafe "sj_document_get_error_column" sj_document_get_error_column :: Ptr CppDocument -> IO Int
foreign import ccall unsafe "sj_document_get_error_message" sj_document_get_error_message :: Ptr CppDocument -> IO (Ptr CChar)
foreign import ccall unsafe "sj_document_get_root" sj_document_get_root :: Ptr CppDocument -> IO (Ptr CppValue)
foreign import ccall unsafe "&sj_value_free" sj_value_free :: FunPtr (Ptr CppValue -> IO ())
foreign import ccall unsafe "sj_value_get_type" sj_value_get_type :: Ptr CppValue -> IO Int
foreign import ccall unsafe "sj_value_get_length" sj_value_get_length :: Ptr CppValue -> IO Word
foreign import ccall unsafe "sj_value_get_array_element" sj_value_get_array_element :: Ptr CppValue -> Word -> IO (Ptr CppValue)
foreign import ccall unsafe "sj_value_get_integer_value" sj_value_get_integer_value :: Ptr CppValue -> IO Int
foreign import ccall unsafe "sj_value_get_number_value" sj_value_get_number_value :: Ptr CppValue -> IO Double
foreign import ccall unsafe "sj_value_get_double_value" sj_value_get_double_value :: Ptr CppValue -> IO Double
foreign import ccall unsafe "sj_value_get_string_value" sj_value_get_string_value :: Ptr CppValue -> Ptr (Ptr CChar) -> Ptr Word -> IO ()
foreign import ccall unsafe "sj_value_get_object_key" sj_value_get_object_key :: Ptr CppValue -> Word -> Ptr (Ptr CChar) -> Ptr Word -> IO ()
foreign import ccall unsafe "sj_value_get_object_value" sj_value_get_object_value :: Ptr CppValue -> Word -> IO (Ptr CppValue)
foreign import ccall unsafe "sj_value_find_object_key" sj_value_find_object_key :: Ptr CppValue -> Ptr CChar -> Word -> IO Word
foreign import ccall unsafe "sj_value_get_object_with_key" sj_value_get_object_with_key :: Ptr CppValue -> Ptr CChar -> Word -> IO (Ptr CppValue)
parse :: Text -> Either ParseError Value
parse t = unsafePerformIO $ do
parserPtr <- withCStringLen t $ \(ptr, len) ->
sj_parser (fromIntegral len) ptr
p <- newForeignPtr sj_parser_free $ parserPtr
withForeignPtr p $ \ptr -> do
d <- sj_parser_get_document ptr
isValid <- sj_document_is_valid d
docPtr <- newForeignPtr sj_document_free d
withForeignPtr docPtr $ \dp ->
if isValid
then do
vp <- sj_document_get_root dp
fmap Right $ mkValue p vp
else do
lineNo <- sj_document_get_error_line dp
colNo <- sj_document_get_error_column dp
errPtr <- sj_document_get_error_message dp
errMsg <- BS.unsafePackCString errPtr
return $ Left $ ParseError lineNo colNo (force $ decodeUtf8 errMsg)
mkValue :: ForeignPtr CppParser -> Ptr CppValue -> IO Value
mkValue pp vp = do
fp <- newForeignPtr sj_value_free vp
return $ Value pp fp
withValPtr :: Value -> (Ptr CppValue -> IO a) -> IO a
withValPtr (Value _ valPtr) f =
withForeignPtr valPtr f
typeOf :: Value -> Type
typeOf (Value _ valPtr) = unsafePerformIO $
withForeignPtr valPtr $ \vp -> do
fmap typeFromInt $ sj_value_get_type vp
asArray :: Value -> Maybe Array
asArray val =
case typeOf val of
TArray -> Just $ Array val
_ -> Nothing
asObject :: Value -> Maybe Object
asObject val =
case typeOf val of
TObject -> Just $ Object val
_ -> Nothing
asInt :: Value -> Maybe Int
asInt val =
case typeOf val of
TInteger -> unsafePerformIO $
fmap Just $ withValPtr val sj_value_get_integer_value
_ ->
Nothing
asNumber :: Value -> Maybe Double
asNumber val =
case typeOf val of
TDouble -> go
TInteger -> go
_ -> Nothing
where
go = unsafePerformIO $
fmap Just $ withValPtr val sj_value_get_number_value
asDouble :: Value -> Maybe Double
asDouble val =
case typeOf val of
TDouble -> unsafePerformIO $
fmap Just $ withValPtr val sj_value_get_double_value
_ ->
Nothing
unsafeAsString :: Value -> Text
unsafeAsString val = unsafePerformIO $ do
alloca $ \cpp ->
alloca $ \lp -> do
withValPtr val $ \vp -> sj_value_get_string_value vp cpp lp
cp <- peek cpp
l <- peek lp
bs <- BS.unsafePackCStringLen (cp, fromIntegral l)
return $ force $ decodeUtf8 bs
unsafeAsByteString :: Value -> ByteString
unsafeAsByteString val = unsafePerformIO $ do
let parserPtr = vParser val
alloca $ \cpp -> do
alloca $ \lp -> do
withValPtr val $ \vp -> sj_value_get_string_value vp cpp lp
cp <- peek cpp
l <- peek lp
offset <- withForeignPtr parserPtr $ \vp ->
return $ cp `minusPtr` (castPtr vp)
return $ BS.fromForeignPtr (castForeignPtr parserPtr) offset (fromIntegral l)
asString :: Value -> Maybe Text
asString val =
case typeOf val of
TString -> Just $ unsafeAsString val
_ -> Nothing
asByteString :: Value -> Maybe ByteString
asByteString val =
case typeOf val of
TString -> Just $ unsafeAsByteString val
_ -> Nothing
getArrayElement :: Array -> Word -> Value
getArrayElement (Array (Value parserPtr valPtr)) index = unsafePerformIO $
withForeignPtr valPtr $ \vp -> do
result <- sj_value_get_array_element vp index
mkValue parserPtr result
unsafeLength :: Value -> Word
unsafeLength val = unsafePerformIO $
withValPtr val $ \vp ->
sj_value_get_length vp
length :: Array -> Word
length (Array v) = unsafeLength v
numKeys :: Object -> Word
numKeys (Object o) = unsafeLength o
mkText :: Ptr (Ptr CChar) -> Ptr Word -> IO Text
mkText ccp lp = do
cp <- peek ccp
l <- peek lp
bs <- BS.unsafePackCStringLen (cp, fromIntegral l)
return $ force $ decodeUtf8 bs
getObjectKey :: Object -> Word -> Text
getObjectKey (Object o) index = unsafePerformIO $
withValPtr o $ \op ->
alloca $ \ccp ->
alloca $ \lp -> do
sj_value_get_object_key op index ccp lp
mkText ccp lp
getObjectValue :: Object -> Word -> Value
getObjectValue (Object (Value parserPtr valPtr)) index = unsafePerformIO $
withForeignPtr valPtr $ \vp -> do
result <- sj_value_get_object_value vp index
mkValue parserPtr result
indexOfObjectKey :: Object -> Text -> Maybe Word
indexOfObjectKey (Object (Value _ valPtr)) key = unsafePerformIO $
withForeignPtr valPtr $ \vp -> do
withCStringLen key $ \(cp, l) -> do
result <- sj_value_find_object_key vp cp $ fromIntegral l
nk <- sj_value_get_length vp
return $ if result < nk then Just result else Nothing
getObjectWithKey :: Object -> Text -> Maybe Value
getObjectWithKey (Object (Value parserPtr valPtr)) key = unsafePerformIO $
withForeignPtr valPtr $ \vp -> do
withCStringLen key $ \(cp, l) -> do
result <- sj_value_get_object_with_key vp cp (fromIntegral l)
if nullPtr /= result
then fmap Just $ mkValue parserPtr result
else return Nothing
instance Show Value where
show v = case typeOf v of
TNull -> "null"
TTrue -> "true"
TFalse -> "false"
TInteger -> show i where Just i = asInt v
TDouble -> show d where Just d = asDouble v
TString -> show t where t = unsafeAsString v
TArray -> "{Array length=" ++ (show $ unsafeLength v) ++ "}"
TObject -> "{Object length=" ++ (show $ unsafeLength v) ++ "}"
instance Eq Value where
-- This could be more efficient by delegating the work to C.
a == b
| typeOf a /= typeOf b = False
| otherwise =
case typeOf a of
TNull -> True
TTrue -> True
TFalse -> True
TInteger -> asInt a == asInt b
TDouble -> asDouble a == asDouble b
TString -> unsafeAsString a == unsafeAsString b
TArray -> eqArrays (Array a) (Array b)
TObject -> eqObjects (Object a) (Object b)
eqArrays :: Array -> Array -> Bool
eqArrays a b
| length a /= length b = False
| otherwise =
let cmpElement i = (getArrayElement a i) == (getArrayElement b i)
in and (map cmpElement [0..length a - 1])
eqObjects :: Object -> Object -> Bool
eqObjects a b
| numKeys a /= numKeys b = False
| otherwise =
let cmpElement i =
((getObjectKey a i) == (getObjectKey b i)) &&
((getObjectValue a i) == (getObjectValue b i))
in and (map cmpElement [0..numKeys a - 1])
|
andyfriesen/hs-sajson
|
src/Sajson.hs
|
mit
| 11,691 | 0 | 21 | 3,394 | 3,397 | 1,680 | 1,717 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-deprecations #-}
module Network.Wai.Handler.Warp.Internal (
-- * Settings
Settings (..)
, ProxyProtocol(..)
-- * Low level run functions
, runSettingsConnection
, runSettingsConnectionMaker
, runSettingsConnectionMakerSecure
, Transport (..)
-- * Connection
, Connection (..)
, socketConnection
-- ** Receive
, Recv
, RecvBuf
, makePlainReceiveN
-- ** Buffer
, Buffer
, BufSize
, bufferSize
, allocateBuffer
, freeBuffer
, copy
-- ** Sendfile
, FileId (..)
, SendFile
, sendFile
, readSendFile
-- * Version
, warpVersion
-- * Data types
, InternalInfo (..)
, HeaderValue
, IndexedHeader
, requestMaxIndex
-- * Time out manager
-- |
--
-- In order to provide slowloris protection, Warp provides timeout handlers. We
-- follow these rules:
--
-- * A timeout is created when a connection is opened.
--
-- * When all request headers are read, the timeout is tickled.
--
-- * Every time at least 2048 bytes of the request body are read, the timeout
-- is tickled.
--
-- * The timeout is paused while executing user code. This will apply to both
-- the application itself, and a ResponseSource response. The timeout is
-- resumed as soon as we return from user code.
--
-- * Every time data is successfully sent to the client, the timeout is tickled.
, module Network.Wai.Handler.Warp.Timeout
-- * File descriptor cache
, module Network.Wai.Handler.Warp.FdCache
-- * Date
, module Network.Wai.Handler.Warp.Date
-- * Request and response
, Source
, recvRequest
, sendResponse
) where
import Network.Wai.Handler.Warp.Buffer
import Network.Wai.Handler.Warp.Date
import Network.Wai.Handler.Warp.FdCache
import Network.Wai.Handler.Warp.Header
import Network.Wai.Handler.Warp.Recv
import Network.Wai.Handler.Warp.Request
import Network.Wai.Handler.Warp.Response
import Network.Wai.Handler.Warp.Run
import Network.Wai.Handler.Warp.SendFile
import Network.Wai.Handler.Warp.Settings
import Network.Wai.Handler.Warp.Timeout
import Network.Wai.Handler.Warp.Types
|
mfine/wai
|
warp/Network/Wai/Handler/Warp/Internal.hs
|
mit
| 2,164 | 0 | 5 | 459 | 275 | 207 | 68 | 46 | 0 |
import System.IO
import System.Directory(getTemporaryDirectory, removeFile)
import System.IO.Error(catchIOError)
import Control.Exception(finally)
main :: IO ()
main = withTempFile "mytemp.txt" myAction
myAction :: FilePath -> Handle -> IO ()
myAction tempname temph =
do
putStrLn "Welcome to tempfile.hs"
putStrLn $ "I have a temporary file at " ++ tempname
pos <- hTell temph
putStrLn $ "My initial position is " ++ show pos
let tempdata = show [1..10]
putStrLn $ "Writing one line containing " ++
show (length tempdata) ++ " bytes: " ++
tempdata
hPutStrLn temph tempdata
pos <- hTell temph
putStrLn $ "After writing, my new pos is " ++ show pos
putStrLn $ "The file content is: "
hSeek temph AbsoluteSeek 0
c <- hGetContents temph
putStrLn c
putStrLn $ "Haskell literal: "
print c
withTempFile :: String -> (FilePath -> Handle IO a) -> IO a
withTempFile pattern func =
do
tempdir <- catchIOError (getTemporaryDirectory) (\_ -> return ".")
(tempfile, temph) <- openTempFile tempdir pattern
finally (func tempfile temph)
(do hClose temph
removeFile tempFile)
|
Bolt64/my_code
|
haskell/tempfile.hs
|
mit
| 1,299 | 0 | 12 | 404 | 365 | 171 | 194 | 34 | 1 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GADTs #-}
module WhySomeException where
import Control.Exception
( ArithException(..)
, AsyncException(..))
import Data.Typeable
data MyException =
forall e . (Show e, Typeable e) => MyException e
instance Show MyException where
showsPrec p (MyException e) = showsPrec p e
---
multiError :: Int -> Either MyException Int
multiError n =
case n of
0 -> Left (MyException DivideByZero)
1 -> Left (MyException StackOverflow)
_ -> Right n
data SomeError =
Arith ArithException
| Async AsyncException
| SomethingElse
deriving (Show)
discriminateError :: MyException -> SomeError
discriminateError (MyException e) =
case cast e of
(Just arith) -> Arith arith
Nothing ->
case cast e of
(Just async) -> Async async
Nothing -> SomethingElse
runDisc n =
either discriminateError (const SomethingElse) (multiError n)
|
NickAger/LearningHaskell
|
HaskellProgrammingFromFirstPrinciples/Chapter30.hsproj/WhySomeException.hs
|
mit
| 960 | 0 | 12 | 224 | 286 | 149 | 137 | 32 | 3 |
{-# LANGUAGE QuasiQuotes #-}
module CSPMTypeChecker.TCTests (testHarness, runtests) where
import Prelude
import CSPMTypeChecker.TCCommon
import CSPMTypeChecker.TCBuiltInFunctions
import CSPMTypeChecker.TCDependencies
import CSPMTypeChecker.TCModule
import CSPMTypeChecker.TCMonad
import CSPMDataStructures
import CSPMParser
import Util
{- Things I don't allow for my typechecker:
General use of dots
Pattern matching on channels, e.g.:
channel p
channel q
gen(p) =
gen(q) =
Functions that have a union type such as:
gen(true) = false
gen(1) = 0
See cspmGavin
-}
testHarness :: String -> IO ()
testHarness exp = (runTyger $
do
(modules @ [Annotated _ _ (GlobalModule ds)]) <- stringParser exp []
runTypeChecker (
do
injectBuiltInFunctions
-- We add an extra scope layer here to allow the
-- built in functions to be overloaded.
local [] (
do
typeCheck modules
names <- concatMapM namesBoundByDecl ds
mapM_ (\n ->
do
t <- getType n
let (Name s) = n
debugOutput (s++" :: "
++show (prettyPrintTypeScheme t))
) names)
))
>>= (\ res -> case res of
Left err -> putStrLn (show err)
Right _ -> return ())
tests = [cspmChannels, cspmFinSeq, cspmListComp,cspmSetEnum,
cspmComplexFunc, cspmFinSeq', cspmMutualRecursion, cspmSetTest,
cspmDataTypes, cspmFlatMap, cspmOrdTest, cspmTakeWhile,
cspmEqTest, cspmFoldl, cspmPartialFunctions, cspmZip,
cspmFoldr, cspmRecursivePattern,
cspmEqualityTest, cspmGavin, cspmRemdups,
cspmFilter, cspmInfiniteUnification, cspmScanr,
cspmTree, cspmBillFunctionalProgramming, cspmListLength]
runtests = mapM_ testHarness tests
-- *************************************************************************
-- Tests
-- *************************************************************************
cspmZip = [$multilineLiteral|
zip(<>, _) = <>
zip(_, <>) = <>
zip(<x>^xs, <y>^ys) = <(x,y)>^zip(xs, ys)
|]
cspmFlatMap = [$multilineLiteral|
flatmap(f,<>) = <>
flatmap(f,<x>^xs) = f(x)^flatmap(f,xs)
|]
cspmRemdups = [$multilineLiteral|
remdups(x) =
let
iter(<>,X) = <>
iter(<x>^xs,X) =
if member(x,X) then iter(xs,X)
else <x>^iter(xs,union(X,{x}))
within
iter(x, {})
|]
cspmFoldr = [$multilineLiteral|
foldr(f, e, <>) = e
foldr(f, e, <x>^xs) = f(x, foldr(f, e, xs))
|]
cspmFoldl = [$multilineLiteral|
foldl(f, e, <>) = e
foldl(f, e, <x>^xs) = foldl(f, f(e, x), xs)
|]
cspmScanr = [$multilineLiteral|
scanr(f, q0, <>) = <q0>
scanr(f, q0, <x>^xs) =
let
(qs @@ <q>^_) = scanr(f, q0, xs)
within
f(x, q)^qs
|]
cspmTakeWhile = [$multilineLiteral|
takeWhile(p, <>) = <>
takeWhile(p, <x>^xs) =
if p(x) then <x>^takeWhile(p, xs)
else <>
|]
cspmFinSeq = [$multilineLiteral|
FinSeq(t, length) =
let
Gen(0) = {<>}
Gen(n) = {<x>^xs, xs | x <-t, xs <- Gen(n-1)}
within
Gen(length)
|]
cspmFinSeq' = [$multilineLiteral|
FinSeq'(t, length) =
let
Gen(0) = <<>>
Gen(n) = concat(< <<x>^xs,xs> | xs <- Gen(n-1), x <- t>)
within
Gen(length)
|]
cspmChannels = [$multilineLiteral|
channel test : {0..1}.{{0}}
P(x) = test.x -- :: Channel [t]
Q(x,y) = x.y -- This is hard to type, the type:
-- forall a, b : (a, b) -> (a.b)
-- is not restrictive enough. Really we want a type
-- TDotable b c where TDotable b c means that
-- x.b :: c . Consider how this interacts with the rest
-- E.g. TChannel (t1:ts) == TDotable t1 (TChannel ts)
-- The type of this would then be:
-- forall b, c : (TDotable b c, b) -> c
-- P(x) :: Int -> TDotable (TSet Int) (TChannel [])
-- Q(x,y) :: forall a b : (TDotable a b, a) -> b
-- R'() :: TDotable (TSet Int) (TChannel [])
-- R() :: TChannel []
-- R''() :: TChannel []
R'() = Q(test,0)
R() = Q(test.0,{0}) -- = test.0.{0}
R''() = R'().{0}
S() = test.0.{0}
|]
cspmDataTypes = [$multilineLiteral|
datatype T =
A.{0..1}
f(A.0) = 0
g(x) = x.0
r() = g(A)
datatype T2 = A2.Int | B2.Int.{0..1} | C2.{0..1}
gen(A2.0) = 1
gen(B2.0.0) = 1
gen(C2.0) = 1
somePat = union(T2, {A2.0})
|]
cspmComplexFunc = [$multilineLiteral|
channel p : {0..5}.{0..5}
channel q : {0..5}
put(p) = <p.i.j | i<-<0..5>, j<-<0..5>>
-- put(q) = <q.i | i<-<0..5>>
|]
cspmListComp = [$multilineLiteral|
channel p : {0..1}
P() = <p.i | i <- <0..100>>
|]
cspmFilter = [$multilineLiteral|
filter(f, <>) = <>
filter(f, <x>^xs) =
if f(x) then <x>^filter(f,xs) else filter(f,xs)
|]
cspmEqualityTest = [$multilineLiteral|
P(T) = <i | i <- T, j <- T, i != j>
Q() = P(<1..2>)
|]
cspmOrdTest = [$multilineLiteral|
P(T) = <i | i <- T, j <- T, i < j>
Q() = P(<0,1>)
|]
cspmSetTest = [$multilineLiteral|
P(T) = {i | i <- T}
Q(xs) = {xs}
|]
cspmEqTest = [$multilineLiteral|
applySeq(f, x) =
let
extract(<x>) = x
within
extract(<a | (x', a) <- f, x == x'>)
|]
cspmPartialFunctions = [$multilineLiteral|
functionDomain(f) = {x | (x,_) <- f}
functionDomainSeq(f) = <x | (x,_) <- f>
functionImage(f) = {x | (_,x) <- f}
functionImageSeq(f) = <x | (_,x) <- f>
identityFunction(domain) = {(x,x) | x <- domain}
identityFunctionSeq(domain) = <(x,x) | x <- domain>
invert(f) = {(a,b) | (b,a) <- f}
invertSeq(f) = <(a,b) | (b,a) <- f>
apply(f, x) =
let
extract({x}) = x
within
extract({a | (x', a) <- f, x == x'})
applySeq(f, x) =
let extract(<x>) = x
within
extract(<a | (x', a) <- f, x == x'>)
composeFunctions(fs1, fs2) = {(a, apply(fs1, b)) | (a, b) <- fs2}
composeFunctionsSeq(fs1, fs2) = <(a,applySeq(fs1,b)) | (a,b) <- fs2>
mapOverSet(f, X) =
{apply(f, x) | x <- X}
mapOverSeq(f, <>) = <>
mapOverSeq(f, <x>^xs) = <applySeq(f,x)>^mapOverSeq(f,xs)
seqDiff(xs, ys) = <x | x <- xs, not elem(x,ys)>
seqInter(xs, ys) = <x | x <- xs, elem(x, ys)>
seqUnion(xs, ys) = remdups(xs^ys)
remdups(x) =
let
iter(<>,X) = <>
iter(<x>^xs,X) =
if member(x,X) then iter(xs,X)
else <x>^iter(xs,union(X,{x}))
within
iter(x, {})
|]
cspmSetEnum = [$multilineLiteral|
channel p : {0..1}.{0..1}
P(x) = {| p.x |}
Q(chan,x) = chan.x.0
|]
cspmRecursivePattern = [$multilineLiteral|
x = <0>^x
|]
cspmGavin =[$multilineLiteral|
-- Haskell bails on this too interestingly
-- (or rather infers the same type)
fst((x,y)) = x
m() = fst(f(true))
f(x) = (x,m())
|]
cspmMutualRecursion = [$multilineLiteral|
even(a) = (<a>^odd(a))
odd(a) = (<a>^even(a))
someOtherFunc(a) = <>
|]
cspmInfiniteUnification = [$multilineLiteral|
someFunc(a) = someFunc(<a>)
|]
cspmTypeExps = [$multilineLiteral|
channel funnyChannel : (Int, Bool)
datatype funnytype = SomeType.(Int, Bool)
|]
cspmBadType = [$multilineLiteral|
someFunc(x) = x+1
test(y) =
let
f = someFunc(<0>)
within
f
|]
cspmTree = [$multilineLiteral|
datatype IntTree = Leaf.Int | Node.IntTree.IntTree
flatten(Leaf.n) = <n>
flatten(Node.t1.t2) = flatten(t1)^flatten(t2)
|]
cspmPolymorphicPatterns = [$multilineLiteral|
id(a) = a
(somePat1, somePat2) = (id, id)
(someRecursivePattern, b) =
(someRecursivePattern^b,someRecursivePattern^b)
|]
cspmCurying = [$multilineLiteral|
curry(x)(y) = curry(0)(1)
|]
cspmListLength = [$multilineLiteral|
test=#s
|]
cspmBillFunctionalProgramming = [$multilineLiteral|
take(n)(xs) =
if n==0 then <> else <head(xs)>^take(n-1)(tail(xs))
cnth(i,xs) = if i==0 then head(xs)
else cnth(i-1,tail(xs))
fst((x,y)) = x
snd((x,y)) = y
-- The following function can be useful for partitioning a process list
-- into roughly equal-sized pieces for structured compression
groupsof(n)(xs) = let xl=#xs within
if xl==0 then <> else
if xl<=n or n==0 then <xs>
else let
m=if (xl/n)*n==xl then n else (n+1)
within
<take(m)(xs)>^groupsof(n)(drop(m)(xs))
drop(n)(xs) = if n==0 then xs else drop(n-1)(tail(xs))
|]
-- TODO: test for process data types
cspmListEnums = [$multilineLiteral|
someSeq = <0..>
someSet = {1..}
someSeq1 = <0..12>
someSet1 = {1..12}
channel a, b, c
someEnumSet = {| a,b,c |}
someEnumSet1 = {| x | x <- {a,b,c} |}
|]
-- Proper type checker cannot handle this
cspmFails = [$multilineLiteral|
datatype B = A
channel a : {0}.{0}.{0}
channel b : B
f(x,y) = {| x.y |}
x = f(a,0)
y = f(b,A)
|]
|
tomgr/tyger
|
src/CSPMTypeChecker/TCTests.hs
|
mit
| 8,314 | 588 | 28 | 1,790 | 4,073 | 2,319 | 1,754 | 74 | 2 |
{-|
Module : Graphics.Shine.Image
Description : Short description
Copyright : (c) Francesco Gazzetta, 2016
License : MIT
Maintainer : [email protected]
Stability : experimental
Handling of external image (.png, .svg and all browser-supported formats).
-}
{-# LANGUAGE ForeignFunctionInterface #-}
module Graphics.Shine.Image (
makeImage,
ImageSize (..),
ImageData (..),
) where
import GHCJS.DOM.HTMLImageElement
-- | Just a wrapper around the 'HTMLImageElement' type. Needed for the Show instance.
newtype ImageData = ImageData { unImageData :: HTMLImageElement } deriving Eq
-- we need this to show Pictures
instance Show ImageData where
show _ = "ImageData"
-- | How big (and how stretched/cropped) the Image is drawn
data ImageSize =
-- | The orizinal size of the image
Original
-- | Scale the image to the given dimensions
| Stretched Float Float
-- | Clip the image from the given coordinates to the given width and height
| Clipped Float Float Float Float
-- | Clip (x,y,width,height) and scale (width, height) the image
| ClippedStretched Float Float Float Float Float Float
deriving (Eq, Show)
foreign import javascript unsafe "$r = new Image();"
js_newImage :: IO HTMLImageElement
-- | Makes an image element from an URL
makeImage :: FilePath -> IO ImageData
makeImage url = do
img <- js_newImage
setSrc img url
return $ ImageData img
|
fgaz/shine
|
src/Graphics/Shine/Image.hs
|
mit
| 1,440 | 8 | 7 | 302 | 182 | 109 | 73 | 22 | 1 |
{-# Language BangPatterns #-}
module HaskellCourse.UntypedLC.StrictInterp (interp, Value(..)) where
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import HaskellCourse.Prim
import HaskellCourse.UntypedLC.AST
data Value = IntV Int | Closure Var Exp Env deriving (Show)
type Env = Map Var Value
interp :: Exp -> Env -> Value
interp (LitInt i) _ = IntV i
interp (Var v) env = fromMaybe (error $ "unbound var: " ++ v) (Map.lookup v env)
interp (Let v e b) env = let !re = interp e env in interp b (Map.insert v re env)
interp (PrimApp p a b) env =
let IntV l = interp a env
IntV r = interp b env
in let !res = runPrim p l r in IntV res
interp (Lambda v b) env = Closure v b env
interp (App f a) env =
let (Closure v exp env') = interp f env
!arg = interp a env
in interp exp (Map.insert v arg env')
|
joshcough/HaskellCourse
|
src/HaskellCourse/UntypedLC/StrictInterp.hs
|
mit
| 905 | 0 | 11 | 232 | 400 | 200 | 200 | 22 | 1 |
module Reverse where
rvrs :: String -> String
rvrs x = drop 9 x ++ (drop 5 (take 9 x)) ++ take 5 x
main :: IO ()
main = print $ rvrs "Curry is awesome"
|
rasheedja/HaskellFromFirstPrinciples
|
Chapter3/reverse.hs
|
mit
| 154 | 0 | 10 | 38 | 77 | 39 | 38 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Criterion.Main
import qualified Data.ByteString.Lazy as L
import Pipes
setupProduce :: IO (L.ByteString, L.ByteString, L.ByteString)
setupProduce = return ("", "", "")
main :: IO ()
main = defaultMain [
env setupProduce $ \ ~(small, medium, large) ->
bgroup "small" []
, bgroup "medium" []
, bgroup "large" []
]
|
iand675/pipes-wai
|
bench/Bench.hs
|
mit
| 388 | 0 | 10 | 72 | 132 | 75 | 57 | 13 | 1 |
-- -*- mode: haskell -*-
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Graph.Col.Config where
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
data Config = Config
{ nodes :: Int -- ^ number of nodes
, edges :: Int -- ^ number of edges
, chi :: Integer -- ^ chromatic number
}
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''Config])
rc :: Config
rc = Config { nodes = 10
, edges = 20
, chi = 4
}
|
Erdwolf/autotool-bonn
|
src/Graph/Col/Config.hs
|
gpl-2.0
| 485 | 6 | 9 | 125 | 120 | 74 | 46 | 15 | 1 |
{-# LANGUAGE CPP, TypeFamilies, DeriveDataTypeable #-}
module PGIP.GraphQL.Result.Sentence where
import qualified PGIP.GraphQL.Result.Axiom as GraphQLResultAxiom
import qualified PGIP.GraphQL.Result.Conjecture as GraphQLResultConjecture
import Data.Data
data Sentence = Axiom GraphQLResultAxiom.Axiom
| Conjecture GraphQLResultConjecture.Conjecture
deriving (Show, Typeable, Data)
|
spechub/Hets
|
PGIP/GraphQL/Result/Sentence.hs
|
gpl-2.0
| 415 | 0 | 7 | 67 | 67 | 44 | 23 | 8 | 0 |
{-# LANGUAGE FlexibleInstances #-}
module SMCDEL.Examples.RussianCards where
import Control.Monad (replicateM)
import Data.HasCacBDD hiding (Top,Bot)
import Data.List ((\\),delete,intersect,nub,sort)
import Data.Map.Strict (fromList)
import SMCDEL.Internal.Help (powerset)
import SMCDEL.Language
import SMCDEL.Other.Planning
import SMCDEL.Symbolic.S5
import qualified SMCDEL.Symbolic.K as K
rcPlayers :: [Agent]
rcPlayers = [alice,bob,carol]
rcNumOf :: Agent -> Int
rcNumOf "Alice" = 0
rcNumOf "Bob" = 1
rcNumOf "Carol" = 2
rcNumOf _ = error "Unknown Agent"
rcCards :: [Int]
rcCards = [0..6]
rcProps :: [Prp]
rcProps = [ P k | k <-[0..((length rcPlayers * length rcCards)-1)] ]
hasCard :: Agent -> Int -> Form
hasCard i n = PrpF (P (3 * n + rcNumOf i))
hasHand :: Agent -> [Int] -> Form
hasHand i ns = Conj $ map (i `hasCard`) ns
rcExplain :: Prp -> String
rcExplain (P k) = (rcPlayers !! i) ++ " has card " ++ show n where (n,i) = divMod k 3
allCardsGiven, allCardsUnique :: Form
allCardsGiven = Conj [ Disj [ i `hasCard` n | i <- rcPlayers ] | n <- rcCards ]
allCardsUnique = Conj [ Neg $ isDouble n | n <- rcCards ] where
isDouble n = Disj [ Conj [ x `hasCard` n, y `hasCard` n ] | x <- rcPlayers, y <- rcPlayers, x < y ]
distribute331 :: Form
distribute331 = Conj [ aliceAtLeastThree, bobAtLeastThree, carolAtLeastOne ] where
triples = [ [x, y, z] | x <- rcCards, y <- delete x rcCards, z <- rcCards \\ [x,y] ]
aliceAtLeastThree = Disj [ Conj (map (alice `hasCard`) t) | t <- triples ]
bobAtLeastThree = Disj [ Conj (map (bob `hasCard`) t) | t <- triples ]
carolAtLeastOne = Disj [ carol `hasCard` k | k<-[0..6] ]
rusSCN :: KnowScene
rusKNS :: KnowStruct
rusSCN@(rusKNS,_) = (KnS rcProps law [ (i, obs i) | i <- rcPlayers ], defaultDeal) where
law = boolBddOf $ Conj [ allCardsGiven, allCardsUnique, distribute331 ]
obs i = [ P (3 * k + rcNumOf i) | k<-[0..6] ]
defaultDeal = [P 0,P 3,P 6,P 10,P 13,P 16,P 20]
aAnnounce :: Form
aAnnounce = K alice $ Disj [ Conj (map (alice `hasCard`) hand) |
hand <- [ [0,1,2], [0,3,4], [0,5,6], [1,3,5], [2,4,6] ] ]
bAnnounce :: Form
bAnnounce = K bob (carol `hasCard` 6)
aKnowsBs, bKnowsAs, cIgnorant :: Form
aKnowsBs = Conj [ alice `Kw` (bob `hasCard` k) | k<-rcCards ]
bKnowsAs = Conj [ bob `Kw` (alice `hasCard` k) | k<-rcCards ]
cIgnorant = Conj $ concat [ [ Neg $ K carol $ alice `hasCard` i
, Neg $ K carol $ bob `hasCard` i ] | i<-rcCards ]
rcCheck :: Int -> Form
rcCheck 0 = aAnnounce
rcCheck 1 = PubAnnounce aAnnounce bKnowsAs
rcCheck 2 = PubAnnounce aAnnounce (Ck [alice,bob] bKnowsAs)
rcCheck 3 = PubAnnounce aAnnounce (K bob (PrpF (P 20)))
rcCheck 4 = PubAnnounce aAnnounce (Ck [alice,bob,carol] cIgnorant)
rcCheck 5 = PubAnnounce aAnnounce (PubAnnounce bAnnounce (Ck [alice,bob] aKnowsBs))
rcCheck 6 = PubAnnounce aAnnounce (PubAnnounce bAnnounce (Ck [alice,bob] bKnowsAs))
rcCheck _ = PubAnnounce aAnnounce (PubAnnounce bAnnounce (Ck rcPlayers cIgnorant))
rcAllChecks :: Bool
rcAllChecks = evalViaBdd rusSCN (Conj (map rcCheck [0..7]))
checkSet :: [[Int]] -> Bool
checkSet set = all (evalViaBdd rusSCN) fs where
aliceSays = K alice (Disj [ Conj $ map (alice `hasCard`) h | h <- set ])
bobSays = K bob (carol `hasCard` 6)
fs = [ aliceSays
, PubAnnounce aliceSays bKnowsAs
, PubAnnounce aliceSays (Ck [alice,bob] bKnowsAs)
, PubAnnounce aliceSays (Ck [alice,bob,carol] cIgnorant)
, PubAnnounce aliceSays (PubAnnounce bobSays (Ck [alice,bob] $ Conj [aKnowsBs, bKnowsAs]))
, PubAnnounce aliceSays (PubAnnounce bobSays (Ck rcPlayers cIgnorant)) ]
possibleHands :: [[Int]]
possibleHands = [ [x,y,z] | x <- rcCards, y <- filter (> x) rcCards, z <-filter (> y) rcCards ]
pickHandsNoCrossing :: [ [Int] ] -> Int -> [ [ [Int] ] ]
pickHandsNoCrossing _ 0 = [ [ [ ] ] ]
pickHandsNoCrossing unused 1 = [ [h] | h <- unused ]
pickHandsNoCrossing unused n = concat [ [ h:hs | hs <- pickHandsNoCrossing (myfilter h unused) (n-1) ] | h <- unused ] where
myfilter h = filter (\xs -> length (h `intersect` xs) < 2 && h < xs) -- do not allow intersection > 2
allHandLists, safeHandLists :: [ [ [Int] ] ]
allHandLists = concatMap (pickHandsNoCrossing possibleHands) [5,6,7]
safeHandLists = sort (filter checkSet allHandLists)
alicesActions :: [Form]
alicesActions = [ Disj $ map (alice `hasHand`) ([0,1,2]:otherHands) | otherHands <- handLists ] where
handLists :: [ [ [Int] ] ]
handLists = pickHands (delete [0,1,2] possibleHands) 4
pickHands :: [ [Int] ] -> Int -> [ [ [Int] ] ]
pickHands _ 0 = [ [ [ ] ] ]
pickHands hands 1 = [ [ h ] | h <- hands ]
pickHands hands n = [ h:hs | h <- hands, hs <- pickHands (filter (h <) hands) (n-1) ]
bobsActions :: [Form]
bobsActions = [ carol `hasCard` n | n <- reverse [4..6] ]
rcSolutions :: [ [Form] ]
rcSolutions = [ [a, b] | a <- alicesActions, b <- bobsActions, testPlan a b ] where
testPlan :: Form -> Form -> Bool
testPlan aSays bSays = all (evalViaBdd rusSCN)
-- NOTE: increasing checks are faster than one big conjunction!
[ aSays
, PubAnnounce aSays bKnowsAs
, PubAnnounce aSays cIgnorant
, PubAnnounce aSays bSays
, PubAnnounce aSays (PubAnnounce bSays aKnowsBs)
, PubAnnounce aSays (PubAnnounce bSays (Ck [alice,bob] $ Conj [cIgnorant,aKnowsBs,bKnowsAs])) ]
rcPlan :: OfflinePlan
rcPlan = [ aAnnounce, bAnnounce ]
rcGoal :: Form
rcGoal = Conj [ aKnowsBs
, bKnowsAs
, Ck [alice,bob] (Conj [aKnowsBs, bKnowsAs])
, Ck [alice,bob,carol] cIgnorant ]
rcSolutionsViaPlanning :: [OfflinePlan]
rcSolutionsViaPlanning = offlineSearch maxSteps start actions constraints goal where
maxSteps = 2 -- We need two steps!
start = rusSCNfor (3,3,1)
actions = alicesActions ++ bobsActions
constraints = [cIgnorant,bKnowsAs]
goal = Conj [aKnowsBs, bKnowsAs]
type RusCardProblem = (Int,Int,Int)
distribute :: RusCardProblem -> Form
distribute (na,nb,nc) = Conj [ alice `hasAtLeast` na
, bob `hasAtLeast` nb
, carol `hasAtLeast` nc ] where
n = na + nb + nc
hasAtLeast :: Agent -> Int -> Form
hasAtLeast _ 0 = Top
hasAtLeast i 1 = Disj [ i `hasCard` k | k <- nCards n ]
hasAtLeast i k = Disj [ Conj (map (i `hasCard`) (sort set))
| set <- powerset (nCards n), length set == k ]
nCards :: Int -> [Int]
nCards n = [0..(n-1)]
nCardsGiven, nCardsUnique :: Int -> Form
nCardsGiven n = Conj [ Disj [ i `hasCard` k | i <- rcPlayers ] | k <- nCards n ]
nCardsUnique n = Conj [ Neg $ isDouble k | k <- nCards n ] where
isDouble k = Disj [ Conj [ x `hasCard` k, y `hasCard` k ] | x <- rcPlayers, y <- rcPlayers, x/=y, x < y ]
rusSCNfor :: RusCardProblem -> KnowScene
rusSCNfor (na,nb,nc) = (KnS props law [ (i, obs i) | i <- rcPlayers ], defaultDeal) where
n = na + nb + nc
props = [ P k | k <-[0..((length rcPlayers * n)-1)] ]
law = boolBddOf $ Conj [ nCardsGiven n, nCardsUnique n, distribute (na,nb,nc) ]
obs i = [ P (3 * k + rcNumOf i) | k<-[0..6] ]
defaultDeal = [ let (PrpF p) = i `hasCard` k in p | i <- rcPlayers, k <- cardsFor i ]
cardsFor "Alice" = [0..(na-1)]
cardsFor "Bob" = [na..(na+nb-1)]
cardsFor "Carol" = [(na+nb)..(na+nb+nc-1)]
cardsFor _ = error "Who is that?"
possibleHandsN :: Int -> Int -> [[Int]]
possibleHandsN n na = filter alldiff $ nub $ map sort $ replicateM na (nCards n) where
alldiff [] = True
alldiff (x:xs) = x `notElem` xs && alldiff xs
allHandListsN :: Int -> Int -> [ [ [Int] ] ]
allHandListsN n na = concatMap (pickHandsNoCrossing (possibleHandsN n na)) [5,6,7] -- FIXME how to adapt the number of hands for larger n?
aKnowsBsN, bKnowsAsN, cIgnorantN :: Int -> Form
aKnowsBsN n = Conj [ alice `Kw` (bob `hasCard` k) | k <- nCards n ]
bKnowsAsN n = Conj [ bob `Kw` (alice `hasCard` k) | k <- nCards n ]
cIgnorantN n = Conj $ concat [ [ Neg $ K carol $ alice `hasCard` i
, Neg $ K carol $ bob `hasCard` i ] | i <- nCards n ]
checkSetFor :: RusCardProblem -> [[Int]] -> Bool
checkSetFor (na,nb,nc) set = reachesOn plan rcGoal (rusSCNfor (na,nb,nc)) where
n = na + nb + nc
aliceSays = K alice (Disj [ Conj $ map (alice `hasCard`) h | h <- set ])
bobSays = K bob (carol `hasCard` last (nCards n))
plan = [ aliceSays, bobSays ]
checkHandsFor :: RusCardProblem -> [ ( [[Int]], Bool) ]
checkHandsFor (na,nb,nc) = map (\hs -> (hs, checkSetFor (na,nb,nc) hs)) (allHandListsN n na) where
n = na + nb + nc
allCasesUpTo :: Int -> [RusCardProblem]
allCasesUpTo bound = [ (na,nb,nc) | na <- [1..bound]
, nb <- [1..(bound-na)]
, nc <- [1..(bound-(na+nb))]
-- these restrictions are only proven
-- for two announcement plans!
, nc < (na - 1)
, nc < nb ]
dontChange :: [Form] -> K.RelBDD
dontChange fs = conSet <$> sequence [ equ <$> K.mvBdd b <*> K.cpBdd b | b <- map boolBddOf fs ]
noDoubles :: Int -> Form
noDoubles n = Neg $ Disj [ notDouble k | k <- nCards n ] where
notDouble k = Conj [alice `hasCard` k, bob `hasCard` k]
rusBelScnfor :: RusCardProblem -> K.BelScene
rusBelScnfor (na,nb,nc) = (K.BlS props law (fromList [ (i, obsbdd i) | i <- rcPlayers ]), defaultDeal) where
n = na + nb + nc
props = [ P k | k <-[0..((2 * n)-1)] ]
law = boolBddOf $ Conj [ noDoubles n, distribute (na,nb,nc) ]
obsbdd "Alice" = dontChange [ PrpF (P $ 2*k) | k <- [0..(n-1)] ]
obsbdd "Bob" = dontChange [ PrpF (P $ (2*k) + 1) | k <- [0..(n-1)] ]
obsbdd "Carol" = dontChange [ Disj [PrpF (P $ 2*k), PrpF (P $ (2*k) + 1)] | k <- [0..(n-1)] ]
obsbdd _ = error "Unkown Agent"
defaultDeal = [ let (PrpF p) = i `hasCard` k in p | i <- [alice,bob], k <- cardsFor i ] where
cardsFor "Alice" = [0..(na-1)]
cardsFor "Bob" = [na..(na+nb-1)]
cardsFor "Carol" = [(na+nb)..(na+nb+nc-1)]
cardsFor _ = error "Unkown Agent"
|
jrclogic/SMCDEL
|
src/SMCDEL/Examples/RussianCards.hs
|
gpl-2.0
| 10,075 | 0 | 16 | 2,413 | 4,577 | 2,512 | 2,065 | 192 | 7 |
import Data.List (nub)
main :: IO ()
main = readLn >>= print . solve
-- Explicitly calculate every one of the powers and count them
solve :: Int -> Int
solve p = (length . nub) [ a^b | a <- as p, b <- bs p]
-- Define the range for the a and b
as, bs :: Int -> [Integer]
as p = [2.. fromIntegral p]
bs p = [2.. fromIntegral p]
|
NorfairKing/project-euler
|
029/haskell/solution.hs
|
gpl-2.0
| 339 | 0 | 9 | 87 | 138 | 73 | 65 | 8 | 1 |
module Main where
import API (API, RunAPI, runAPI)
import Config (Config (..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO (..))
import Data.Aeson (eitherDecode)
import qualified Data.ByteString.Lazy as BS
import Data.Data (Proxy (..))
import Data.List (isSuffixOf)
import Network.Wai.Handler.Warp (defaultSettings, runSettings, setLogger, setPort)
import Routes (routes)
import Servant.Server (serve)
import State (newAPIState, statefulCacheFile, statefulUnCacheFile)
import System.Directory (createDirectoryIfMissing)
import System.FSNotify (Event (..), eventPath, watchTree, withManager)
import System.FilePath (takeDirectory)
api :: Config -> RunAPI ()
api config = do
let mediaDir = configMediaDir config
let uploadDir = configUploadDir config
-- create the directory to contain uploads if it doesn’t exist yet
liftIO (createDirectoryIfMissing True uploadDir)
-- create the API state
apiState <- newAPIState config
-- start a notify thread to listen for file changes
liftIO . withManager $ \mgr -> do
putStrLn $ "watching " <> mediaDir
void . watchTree mgr mediaDir (const True) $ \event -> do
putStrLn $ "event: " <> show event
let path = eventPath event
let parentDir = takeDirectory path
if uploadDir `isSuffixOf` parentDir
then case event of
Added {} -> statefulCacheFile path apiState
Removed {} -> statefulUnCacheFile path apiState
_ -> pure ()
else pure ()
let serverSettings = setLogger logger . setPort (fromIntegral $ configPort config) $ defaultSettings
logger req st _ = putStrLn $ show st ++ " | " ++ show req ++ "\n"
liftIO . runSettings serverSettings $
serve (Proxy :: Proxy API) (routes config apiState)
main :: IO ()
main = do
eitherConfig <- fmap eitherDecode (BS.readFile "backend.json")
case eitherConfig of
Left err -> do
putStrLn "cannot read configuration"
print err
Right config -> do
runAPI (api config) >>= \case
Left err -> do
putStrLn $ "API failed with: " <> show err
Right _ -> putStrLn "bye"
|
phaazon/phaazon.net
|
backend/src/Main.hs
|
gpl-3.0
| 2,134 | 0 | 20 | 464 | 657 | 339 | 318 | -1 | -1 |
{-
This file is part of ChaosFlight.
ChaosFlight is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ChaosFlight 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 ChaosFlight. If not, see <http://www.gnu.org/licenses/>.
-}
module Util
(addV,negV,subV
,distV
) where
import Graphics.Gloss.Data.Vector
addV :: Vector -> Vector -> Vector
addV (x0,y0) (x1,y1) = (x0+x1,y0+y1)
negV :: Vector -> Vector
negV = mulSV (-1)
subV :: Vector -> Vector -> Vector
subV v0 v1 = addV v0 (negV v1)
distV :: Vector -> Vector -> Float
distV a b = magV (a `subV` b)
|
Marthog/ld34
|
src/Util.hs
|
gpl-3.0
| 1,026 | 0 | 7 | 221 | 166 | 94 | 72 | 12 | 1 |
{-|
Description : Rearranging the actual code (not the comments)
-}
module Language.Haskell.Formatter.Process.FormatActualCode (formatActualCode)
where
import qualified Control.Applicative as Applicative
import qualified Language.Haskell.Formatter.Process.Code as Code
import qualified Language.Haskell.Formatter.Process.CodeOrdering as CodeOrdering
import qualified Language.Haskell.Formatter.Result as Result
import qualified Language.Haskell.Formatter.Source as Source
import qualified Language.Haskell.Formatter.Style as Style
import qualified Language.Haskell.Formatter.Toolkit.Visit as Visit
formatActualCode ::
Style.Style ->
Code.LocatableCommentableCode ->
Result.Result Code.LocatableCommentableCode
formatActualCode style locatableCommentable
= do locatable <- prettyPrint style locatableCommentable'
Code.tryZipLocationsComments locatable commentable
where locatableCommentable' = prepare style locatableCommentable
commentable = Code.dropLocations locatableCommentable'
prettyPrint ::
Style.Style ->
Code.LocatableCommentableCode -> Result.Result Code.LocatableCode
prettyPrint style locatableCommentable
= case parseResult of
Source.ParseFailed _ _ -> Result.fatalAssertionError message
where message = "Formatting the actual code failed to parse."
Source.ParseOk possiblyChanged -> tryUnwrap maybeLocatable'
where maybeLocatable'
= Visit.halfZipWith (const id) locatable possiblyChanged
where parseResult
= Source.parseFileContents $ defaultPrettyPrint style locatable
locatable = Code.dropComments locatableCommentable
tryUnwrap maybeLocatable'
= case maybeLocatable' of
Nothing -> Result.fatalAssertionError message
where message = "Formatting the actual code failed to zip."
Just locatable' -> return locatable'
defaultPrettyPrint :: Source.Pretty a => Style.Style -> a -> String
defaultPrettyPrint
= Applicative.liftA2 Source.prettyPrintStyleMode renderingStyle mode
renderingStyle :: Style.Style -> Source.Style
renderingStyle style
= Source.style{Source.lineLength = Style.lineLengthLimit style,
Source.ribbonsPerLine = Style.ribbonsPerLine style}
mode :: Style.Style -> Source.PPHsMode
mode style
= Source.defaultMode{Source.classIndent = Style.classIndentation style,
Source.doIndent = Style.doIndentation style,
Source.caseIndent = Style.caseIndentation style,
Source.letIndent = Style.letIndentation style,
Source.whereIndent = Style.whereIndentation style,
Source.onsideIndent = Style.onsideIndentation style}
prepare ::
Style.Style ->
Code.LocatableCommentableCode -> Code.LocatableCommentableCode
prepare style = Visit.compose preparations
where preparations
= [preparation | (isApplied, preparation) <- applications,
isApplied style]
applications
= [(Style.orderImportDeclarations,
CodeOrdering.orderImportDeclarations),
(Style.orderImportEntities, orderImportEntities)]
orderImportEntities ::
Code.LocatableCommentableCode ->
Code.LocatableCommentableCode
orderImportEntities
= CodeOrdering.orderRootImportEntities .
CodeOrdering.orderNestedImportEntities
|
evolutics/haskell-formatter
|
src/library/Language/Haskell/Formatter/Process/FormatActualCode.hs
|
gpl-3.0
| 3,522 | 0 | 12 | 801 | 645 | 354 | 291 | 67 | 3 |
{-# LANGUAGE OverloadedStrings #-}
-- Copyright (C) 2011 John Millikin <[email protected]>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module Anansi.HsColour.LaTeX (loomLaTeX) where
import Control.Monad (forM_)
import Control.Monad.Reader (asks)
import Control.Monad.Writer (tell)
import qualified Data.ByteString.Char8 as ByteString
import Data.ByteString.Char8 (ByteString)
import Data.Monoid (mappend, mconcat)
import qualified Data.Text
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Anansi hiding (loomLaTeX)
import qualified Language.Haskell.HsColour as HsColour
import Language.Haskell.HsColour.Colourise (defaultColourPrefs)
loomLaTeX :: Loom
loomLaTeX = mapM_ putBlock . documentBlocks where
putBlock b = case b of
BlockText text -> tell (encodeUtf8 text)
BlockFile path content -> do
epath <- escape path
let label = mconcat ["{\\bf\\(\\gg\\) ", epath, "}\n"]
putContent label content
BlockDefine name content -> do
ename <- escape name
let label = mconcat ["{\\bf\\(\\ll\\) ", ename, "\\(\\gg\\)}\n"]
putContent label content
putContent label cs = do
tell "\\begin{quotation}\n"
tell "\\noindent{}"
tell label
tell "\n\n"
forM_ cs $ \c -> case c of
ContentText _ text -> do
expanded <- expandTabs text
tell "\\noindent{}"
tell (colorize (expanded `mappend` "\n"))
ContentMacro _ indent name -> do
tell "\\noindent{}"
formatMacro indent name >>= tell
tell "\n"
tell "\\end{quotation}\n"
formatMacro indent name = do
escIndent <- escape indent
escName <- escape name
return (mconcat [escIndent, "$|$\\emph{", escName, "}$|$\n"])
escape :: Text -> LoomM ByteString
escape text = do
tabSize <- asks loomOptionTabSize
return $ encodeUtf8 $ Data.Text.concatMap (\c -> case c of
'\t' -> Data.Text.replicate (fromInteger tabSize) " "
'\\' -> "\\textbackslash{}"
'{' -> "\\{"
'}' -> "\\}"
'_' -> "\\_"
_ -> Data.Text.singleton c) text
expandTabs :: Text -> LoomM Text
expandTabs txt = do
tabSize <- asks loomOptionTabSize
return $ Data.Text.concatMap (\c -> case c of
'\t' -> Data.Text.replicate (fromInteger tabSize) " "
_ -> Data.Text.singleton c) txt
colorize :: Text -> ByteString
colorize = ByteString.pack
. HsColour.hscolour HsColour.LaTeX defaultColourPrefs False True "" False
. ByteString.unpack
. encodeUtf8
|
jmillikin/anansi-hscolour
|
lib/Anansi/HsColour/LaTeX.hs
|
gpl-3.0
| 3,059 | 9 | 20 | 630 | 758 | 392 | 366 | 66 | 6 |
{-# 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.AdSense.Accounts.AdClients.CustomChannels.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)
--
-- Lists all the custom channels available in an ad client.
--
-- /See:/ <http://code.google.com/apis/adsense/management/ AdSense Management API Reference> for @adsense.accounts.adclients.customchannels.list@.
module Network.Google.Resource.AdSense.Accounts.AdClients.CustomChannels.List
(
-- * REST Resource
AccountsAdClientsCustomChannelsListResource
-- * Creating a Request
, accountsAdClientsCustomChannelsList
, AccountsAdClientsCustomChannelsList
-- * Request Lenses
, aaccclParent
, aaccclXgafv
, aaccclUploadProtocol
, aaccclAccessToken
, aaccclUploadType
, aaccclPageToken
, aaccclPageSize
, aaccclCallback
) where
import Network.Google.AdSense.Types
import Network.Google.Prelude
-- | A resource alias for @adsense.accounts.adclients.customchannels.list@ method which the
-- 'AccountsAdClientsCustomChannelsList' request conforms to.
type AccountsAdClientsCustomChannelsListResource =
"v2" :>
Capture "parent" Text :>
"customchannels" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListCustomChannelsResponse
-- | Lists all the custom channels available in an ad client.
--
-- /See:/ 'accountsAdClientsCustomChannelsList' smart constructor.
data AccountsAdClientsCustomChannelsList =
AccountsAdClientsCustomChannelsList'
{ _aaccclParent :: !Text
, _aaccclXgafv :: !(Maybe Xgafv)
, _aaccclUploadProtocol :: !(Maybe Text)
, _aaccclAccessToken :: !(Maybe Text)
, _aaccclUploadType :: !(Maybe Text)
, _aaccclPageToken :: !(Maybe Text)
, _aaccclPageSize :: !(Maybe (Textual Int32))
, _aaccclCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsAdClientsCustomChannelsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aaccclParent'
--
-- * 'aaccclXgafv'
--
-- * 'aaccclUploadProtocol'
--
-- * 'aaccclAccessToken'
--
-- * 'aaccclUploadType'
--
-- * 'aaccclPageToken'
--
-- * 'aaccclPageSize'
--
-- * 'aaccclCallback'
accountsAdClientsCustomChannelsList
:: Text -- ^ 'aaccclParent'
-> AccountsAdClientsCustomChannelsList
accountsAdClientsCustomChannelsList pAaccclParent_ =
AccountsAdClientsCustomChannelsList'
{ _aaccclParent = pAaccclParent_
, _aaccclXgafv = Nothing
, _aaccclUploadProtocol = Nothing
, _aaccclAccessToken = Nothing
, _aaccclUploadType = Nothing
, _aaccclPageToken = Nothing
, _aaccclPageSize = Nothing
, _aaccclCallback = Nothing
}
-- | Required. The ad client which owns the collection of custom channels.
-- Format: accounts\/{account}\/adclients\/{adclient}
aaccclParent :: Lens' AccountsAdClientsCustomChannelsList Text
aaccclParent
= lens _aaccclParent (\ s a -> s{_aaccclParent = a})
-- | V1 error format.
aaccclXgafv :: Lens' AccountsAdClientsCustomChannelsList (Maybe Xgafv)
aaccclXgafv
= lens _aaccclXgafv (\ s a -> s{_aaccclXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
aaccclUploadProtocol :: Lens' AccountsAdClientsCustomChannelsList (Maybe Text)
aaccclUploadProtocol
= lens _aaccclUploadProtocol
(\ s a -> s{_aaccclUploadProtocol = a})
-- | OAuth access token.
aaccclAccessToken :: Lens' AccountsAdClientsCustomChannelsList (Maybe Text)
aaccclAccessToken
= lens _aaccclAccessToken
(\ s a -> s{_aaccclAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
aaccclUploadType :: Lens' AccountsAdClientsCustomChannelsList (Maybe Text)
aaccclUploadType
= lens _aaccclUploadType
(\ s a -> s{_aaccclUploadType = a})
-- | A page token, received from a previous \`ListCustomChannels\` call.
-- Provide this to retrieve the subsequent page. When paginating, all other
-- parameters provided to \`ListCustomChannels\` must match the call that
-- provided the page token.
aaccclPageToken :: Lens' AccountsAdClientsCustomChannelsList (Maybe Text)
aaccclPageToken
= lens _aaccclPageToken
(\ s a -> s{_aaccclPageToken = a})
-- | The maximum number of custom channels to include in the response, used
-- for paging. If unspecified, at most 10000 custom channels will be
-- returned. The maximum value is 10000; values above 10000 will be coerced
-- to 10000.
aaccclPageSize :: Lens' AccountsAdClientsCustomChannelsList (Maybe Int32)
aaccclPageSize
= lens _aaccclPageSize
(\ s a -> s{_aaccclPageSize = a})
. mapping _Coerce
-- | JSONP
aaccclCallback :: Lens' AccountsAdClientsCustomChannelsList (Maybe Text)
aaccclCallback
= lens _aaccclCallback
(\ s a -> s{_aaccclCallback = a})
instance GoogleRequest
AccountsAdClientsCustomChannelsList
where
type Rs AccountsAdClientsCustomChannelsList =
ListCustomChannelsResponse
type Scopes AccountsAdClientsCustomChannelsList =
'["https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/adsense.readonly"]
requestClient
AccountsAdClientsCustomChannelsList'{..}
= go _aaccclParent _aaccclXgafv _aaccclUploadProtocol
_aaccclAccessToken
_aaccclUploadType
_aaccclPageToken
_aaccclPageSize
_aaccclCallback
(Just AltJSON)
adSenseService
where go
= buildClient
(Proxy ::
Proxy AccountsAdClientsCustomChannelsListResource)
mempty
|
brendanhay/gogol
|
gogol-adsense/gen/Network/Google/Resource/AdSense/Accounts/AdClients/CustomChannels/List.hs
|
mpl-2.0
| 6,744 | 0 | 18 | 1,467 | 889 | 517 | 372 | 133 | 1 |
module Data.GI.CodeGen.GObject
( isGObject
, apiIsGObject
, nameIsGObject
, isInitiallyUnowned
, apiIsInitiallyUnowned
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Data.GI.CodeGen.API
import Data.GI.CodeGen.Code
import Data.GI.CodeGen.Type
-- Returns whether the given type is a descendant of the given parent.
typeDoParentSearch :: Name -> Type -> CodeGen Bool
typeDoParentSearch parent (TInterface ns n) = findAPIByName name >>=
apiDoParentSearch parent name
where name = Name ns n
typeDoParentSearch _ _ = return False
apiDoParentSearch :: Name -> Name -> API -> CodeGen Bool
apiDoParentSearch parent n api
| parent == n = return True
| otherwise = case api of
APIObject o ->
case objParent o of
Just (Name pns pn) -> typeDoParentSearch parent (TInterface pns pn)
Nothing -> return False
APIInterface iface ->
do let prs = ifPrerequisites iface
prereqs <- zip prs <$> mapM findAPIByName prs
or <$> mapM (uncurry (apiDoParentSearch parent)) prereqs
_ -> return False
isGObject :: Type -> CodeGen Bool
isGObject = typeDoParentSearch $ Name "GObject" "Object"
-- | Check whether the given name descends from GObject.
nameIsGObject :: Name -> CodeGen Bool
nameIsGObject n = findAPIByName n >>= apiIsGObject n
apiIsGObject :: Name -> API -> CodeGen Bool
apiIsGObject = apiDoParentSearch $ Name "GObject" "Object"
isInitiallyUnowned :: Type -> CodeGen Bool
isInitiallyUnowned = typeDoParentSearch $ Name "GObject" "InitiallyUnowned"
apiIsInitiallyUnowned :: Name -> API -> CodeGen Bool
apiIsInitiallyUnowned = apiDoParentSearch $ Name "GObject" "InitiallyUnowned"
|
hamishmack/haskell-gi
|
lib/Data/GI/CodeGen/GObject.hs
|
lgpl-2.1
| 1,817 | 0 | 16 | 442 | 461 | 232 | 229 | 38 | 4 |
-- one
import Control.Distributed.Process
import Control.Distributed.Process.Node
import Network.Transport.TCP (createTransport, defaultTCPParameters)
-- two
import Control.Concurrent (threadDelay)
import Control.Distributed.Process
import Control.Distributed.Process.Node
import Control.Monad (forever)
import Network.Transport.TCP (createTransport, defaultTCPParameters)
-- misc
import System.Environment
import System.Exit
main :: IO ()
main = getArgs >>= run
run ["1"] = one
run ["2"] = two
run _ = one
one :: IO ()
one = do
Right transport <- createTransport "127.0.0.1" "10501" defaultTCPParameters
-- start a running local node
node <- newLocalNode transport initRemoteTable
-- start new process
_ <- forkProcess node $ do
self <- getSelfPid
send self "hello world" -- send message to ourself
hello <- expect :: Process String -- receive the message
liftIO $ putStrLn hello -- print the message to the console
return ()
replyBack :: (ProcessId, String) -> Process ()
replyBack (sender, msg) = send sender msg
logMessage :: String -> Process ()
logMessage msg = say $ "handling " ++ msg
two :: IO ()
two = do
Right t <- createTransport "127.0.0.1" "10501" defaultTCPParameters
node <- newLocalNode t initRemoteTable
-- Spawn a new process on a local node
forkProcess node $ do
-- Spawn worker inside one more process on the local node
echoPid <- spawnLocal $ forever $ do
-- Test the matches in order against each message in the queue
receiveWait [match logMessage, match replyBack]
-- `say` sends a message to the process registered as logger.
-- By default, this process simply sends the string to stderr.
say "send some messages"
send echoPid "hello"
self <- getSelfPid
send echoPid (self, "hello world")
-- like `expect` (waits for a message), but with timeout
m <- expectTimeout 1000000
case m of
-- Die immediately - throws a ProcessExitException with the given reason.
Nothing -> die "nothing came back!"
(Just s) -> say $ "got back " ++ s
return ()
-- A 1 second wait. Otherwise the main thread can terminate before
-- our messages reach the logging process or get flushed to stdio
liftIO $ threadDelay (1*1000000)
return ()
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/topic/distributed/tutorials/tutorial1.hs
|
unlicense
| 2,422 | 0 | 16 | 614 | 525 | 267 | 258 | 47 | 2 |
--
-- Minio Haskell SDK, (C) 2017 Minio, Inc.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
module Network.Minio.XmlParser
( parseListBuckets
, parseLocation
, parseNewMultipartUpload
, parseCompleteMultipartUploadResponse
, parseCopyObjectResponse
, parseListObjectsResponse
, parseListObjectsV1Response
, parseListUploadsResponse
, parseListPartsResponse
, parseErrResponse
, parseNotification
) where
import Control.Monad.Trans.Resource
import Data.List (zip3, zip4)
import qualified Data.Text as T
import Data.Text.Read (decimal)
import Data.Time
import Text.XML
import Text.XML.Cursor hiding (bool)
import Lib.Prelude
import Network.Minio.Data
import Network.Minio.Errors
-- | Represent the time format string returned by S3 API calls.
s3TimeFormat :: [Char]
s3TimeFormat = iso8601DateFormat $ Just "%T%QZ"
-- | Helper functions.
uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e
uncurry4 f (a, b, c, d) = f a b c d
-- | Parse time strings from XML
parseS3XMLTime :: (MonadThrow m) => Text -> m UTCTime
parseS3XMLTime = either (throwM . MErrVXmlParse) return
. parseTimeM True defaultTimeLocale s3TimeFormat
. T.unpack
parseDecimal :: (MonadThrow m, Integral a) => Text -> m a
parseDecimal numStr = either (throwM . MErrVXmlParse . show) return $
fst <$> decimal numStr
parseDecimals :: (MonadThrow m, Integral a) => [Text] -> m [a]
parseDecimals numStr = forM numStr parseDecimal
s3Elem :: Text -> Axis
s3Elem = element . s3Name
parseRoot :: (MonadThrow m) => LByteString -> m Cursor
parseRoot = either (throwM . MErrVXmlParse . show) (return . fromDocument)
. parseLBS def
-- | Parse the response XML of a list buckets call.
parseListBuckets :: (MonadThrow m) => LByteString -> m [BucketInfo]
parseListBuckets xmldata = do
r <- parseRoot xmldata
let
names = r $// s3Elem "Bucket" &// s3Elem "Name" &/ content
timeStrings = r $// s3Elem "Bucket" &// s3Elem "CreationDate" &/ content
times <- mapM parseS3XMLTime timeStrings
return $ zipWith BucketInfo names times
-- | Parse the response XML of a location request.
parseLocation :: (MonadThrow m) => LByteString -> m Region
parseLocation xmldata = do
r <- parseRoot xmldata
let region = T.concat $ r $/ content
return $ bool "us-east-1" region $ region /= ""
-- | Parse the response XML of an newMultipartUpload call.
parseNewMultipartUpload :: (MonadThrow m) => LByteString -> m UploadId
parseNewMultipartUpload xmldata = do
r <- parseRoot xmldata
return $ T.concat $ r $// s3Elem "UploadId" &/ content
-- | Parse the response XML of completeMultipartUpload call.
parseCompleteMultipartUploadResponse :: (MonadThrow m) => LByteString -> m ETag
parseCompleteMultipartUploadResponse xmldata = do
r <- parseRoot xmldata
return $ T.concat $ r $// s3Elem "ETag" &/ content
-- | Parse the response XML of copyObject and copyObjectPart
parseCopyObjectResponse :: (MonadThrow m) => LByteString -> m (ETag, UTCTime)
parseCopyObjectResponse xmldata = do
r <- parseRoot xmldata
let
mtimeStr = T.concat $ r $// s3Elem "LastModified" &/ content
mtime <- parseS3XMLTime mtimeStr
return (T.concat $ r $// s3Elem "ETag" &/ content, mtime)
-- | Parse the response XML of a list objects v1 call.
parseListObjectsV1Response :: (MonadThrow m)
=> LByteString -> m ListObjectsV1Result
parseListObjectsV1Response xmldata = do
r <- parseRoot xmldata
let
hasMore = ["true"] == (r $/ s3Elem "IsTruncated" &/ content)
nextMarker = headMay $ r $/ s3Elem "NextMarker" &/ content
prefixes = r $/ s3Elem "CommonPrefixes" &/ s3Elem "Prefix" &/ content
keys = r $/ s3Elem "Contents" &/ s3Elem "Key" &/ content
modTimeStr = r $/ s3Elem "Contents" &/ s3Elem "LastModified" &/ content
etagsList = r $/ s3Elem "Contents" &/ s3Elem "ETag" &/ content
-- if response xml contains empty etag response fill them with as
-- many empty Text for the zip4 below to work as intended.
etags = etagsList ++ repeat ""
sizeStr = r $/ s3Elem "Contents" &/ s3Elem "Size" &/ content
modTimes <- mapM parseS3XMLTime modTimeStr
sizes <- parseDecimals sizeStr
let
objects = map (uncurry4 ObjectInfo) $ zip4 keys modTimes etags sizes
return $ ListObjectsV1Result hasMore nextMarker objects prefixes
-- | Parse the response XML of a list objects call.
parseListObjectsResponse :: (MonadThrow m) => LByteString -> m ListObjectsResult
parseListObjectsResponse xmldata = do
r <- parseRoot xmldata
let
hasMore = ["true"] == (r $/ s3Elem "IsTruncated" &/ content)
nextToken = headMay $ r $/ s3Elem "NextContinuationToken" &/ content
prefixes = r $/ s3Elem "CommonPrefixes" &/ s3Elem "Prefix" &/ content
keys = r $/ s3Elem "Contents" &/ s3Elem "Key" &/ content
modTimeStr = r $/ s3Elem "Contents" &/ s3Elem "LastModified" &/ content
etagsList = r $/ s3Elem "Contents" &/ s3Elem "ETag" &/ content
-- if response xml contains empty etag response fill them with as
-- many empty Text for the zip4 below to work as intended.
etags = etagsList ++ repeat ""
sizeStr = r $/ s3Elem "Contents" &/ s3Elem "Size" &/ content
modTimes <- mapM parseS3XMLTime modTimeStr
sizes <- parseDecimals sizeStr
let
objects = map (uncurry4 ObjectInfo) $ zip4 keys modTimes etags sizes
return $ ListObjectsResult hasMore nextToken objects prefixes
-- | Parse the response XML of a list incomplete multipart upload call.
parseListUploadsResponse :: (MonadThrow m) => LByteString -> m ListUploadsResult
parseListUploadsResponse xmldata = do
r <- parseRoot xmldata
let
hasMore = ["true"] == (r $/ s3Elem "IsTruncated" &/ content)
prefixes = r $/ s3Elem "CommonPrefixes" &/ s3Elem "Prefix" &/ content
nextKey = headMay $ r $/ s3Elem "NextKeyMarker" &/ content
nextUpload = headMay $ r $/ s3Elem "NextUploadIdMarker" &/ content
uploadKeys = r $/ s3Elem "Upload" &/ s3Elem "Key" &/ content
uploadIds = r $/ s3Elem "Upload" &/ s3Elem "UploadId" &/ content
uploadInitTimeStr = r $/ s3Elem "Upload" &/ s3Elem "Initiated" &/ content
uploadInitTimes <- mapM parseS3XMLTime uploadInitTimeStr
let
uploads = zip3 uploadKeys uploadIds uploadInitTimes
return $ ListUploadsResult hasMore nextKey nextUpload uploads prefixes
parseListPartsResponse :: (MonadThrow m) => LByteString -> m ListPartsResult
parseListPartsResponse xmldata = do
r <- parseRoot xmldata
let
hasMore = ["true"] == (r $/ s3Elem "IsTruncated" &/ content)
nextPartNumStr = headMay $ r $/ s3Elem "NextPartNumberMarker" &/ content
partNumberStr = r $/ s3Elem "Part" &/ s3Elem "PartNumber" &/ content
partModTimeStr = r $/ s3Elem "Part" &/ s3Elem "LastModified" &/ content
partETags = r $/ s3Elem "Part" &/ s3Elem "ETag" &/ content
partSizeStr = r $/ s3Elem "Part" &/ s3Elem "Size" &/ content
partModTimes <- mapM parseS3XMLTime partModTimeStr
partSizes <- parseDecimals partSizeStr
partNumbers <- parseDecimals partNumberStr
nextPartNum <- parseDecimals $ maybeToList nextPartNumStr
let
partInfos = map (uncurry4 ObjectPartInfo) $
zip4 partNumbers partETags partSizes partModTimes
return $ ListPartsResult hasMore (listToMaybe nextPartNum) partInfos
parseErrResponse :: (MonadThrow m) => LByteString -> m ServiceErr
parseErrResponse xmldata = do
r <- parseRoot xmldata
let code = T.concat $ r $/ element "Code" &/ content
message = T.concat $ r $/ element "Message" &/ content
return $ toServiceErr code message
parseNotification :: (MonadThrow m) => LByteString -> m Notification
parseNotification xmldata = do
r <- parseRoot xmldata
let qcfg = map node $ r $/ s3Elem "QueueConfiguration"
tcfg = map node $ r $/ s3Elem "TopicConfiguration"
lcfg = map node $ r $/ s3Elem "CloudFunctionConfiguration"
Notification <$> (mapM (parseNode "Queue") qcfg)
<*> (mapM (parseNode "Topic") tcfg)
<*> (mapM (parseNode "CloudFunction") lcfg)
where
getFilterRule c =
let name = T.concat $ c $/ s3Elem "Name" &/ content
value = T.concat $ c $/ s3Elem "Value" &/ content
in FilterRule name value
parseNode arnName nodeData = do
let c = fromNode nodeData
id = T.concat $ c $/ s3Elem "Id" &/ content
arn = T.concat $ c $/ s3Elem arnName &/ content
events = catMaybes $ map textToEvent $ c $/ s3Elem "Event" &/ content
rules = c $/ s3Elem "Filter" &/ s3Elem "S3Key" &/
s3Elem "FilterRule" &| getFilterRule
return $ NotificationConfig id arn events
(Filter $ FilterKey $ FilterRules rules)
|
donatello/minio-hs
|
src/Network/Minio/XmlParser.hs
|
apache-2.0
| 9,324 | 0 | 16 | 2,039 | 2,483 | 1,233 | 1,250 | 164 | 1 |
parity :: Bit -> Bit
parity input = output
where
output = xor (delay output) input
-- deep embedding
data Bit = Xor Bit Bit
| Delay Bit
| Input [Bool]
| Var String deriving Show
xor = Xor
delay = Delay
run :: (Bit -> Bit) -> [Bool] -> [Bool]
run f bs = interp (f (Input bs))
interp :: Bit -> [Bool]
interp (Xor b1 b2) = zipWith (/=) (interp b1) (interp b2)
interp (Delay b) = False : interp b
interp (Input bs) = bs
inputer (Var v) = error $ "Var not supported"
smth :: [Int] -> [Int]
smth xs = 0:xs
binop :: [Int] -> [Int] -> [Int]
binop xs ys = zipWith (+) xs ys
-- > run parity (replicate 10 True)
-- [True,False,True,False,True,False,True,False,True,False]
-- > parity (Var "x")
-- Xor (Delay (Xor (Delay (Xor (Delay (Xor
{- digression: recursion -}
f :: [Int] -> [Int]
f x = map (+100) (1:(f x))
-- > zip (f [1]) [1..10]
-- [(101,1),(201,2),(301,3),(401,4),(501,5),(601,6),(701,7),(801,8),(901,9),(1001,10)]
{-
f [1] =
== map (+100) (1:(f [1]))
== 101 : map (+100) (f [1]) <<<-----
== 101 : map(+100) (map (+100) 1:(f [1]))
== 101 : map(+200) (1 : (f [1]))
== 101 : 201 : map (+200) (f [1]) <<<-------
== 101 : 201 : map (+200) (map (+100) (1:(f [1])))
== 101 : 201 : map (+300) (1:(f [1]))
== 101 : 201 : 301 : map (+300) (f [1]) <<<-------
...
-}
zw :: (Int->Int->Int) -> [Int] -> [Int] -> [Int]
zw f (x:xs) (y:ys) = f x y : zw f xs ys
zw f _ _ = []
g :: [Int] -> [Int]
g x = zw (+) (0:(g x)) x
g' :: [Int] -> [Int]
g' x = zw (+) (0:(g' x)) (0:(init x))
g'' :: [Int] -> [Int]
g'' x = zw (+) (g'' x) x
-- > g [10..14]
-- [10,21,33,46,60]
--
-- > take 3 $ g [10..14]
-- [10,21,33]
-- > take 3 $ g' [10..14]
-- [Hang] ^C
{-
g [10..14]
== zw (+) (0:(g [10..14]) [10..14]
== 10 : zw (+) (g [10..14]) [11..14]
zw (+) (g [10..14]) [11..14]
== zw (+) (10 : zw (+) (g [10..14]) [11..14]) [11..14]
== 21 : zw (+) (zw (+) (g [10..14]) [11..14]) [12..14]
zw (+) (zw (+) (g [10..14]) [11..14]) [12..14]
== zw (+) (21 : zw (+) (zw (+) (g [10..14]) [11..14]) [12..14]) [12..14]
== 33 : zw (+) (zw (+) (zw (+) (g [10..14]) [11..14]) [12..14]) [13,14]
zw (+) (zw (+) (zw (+) (g [10..14]) [11..14]) [12..14]) [13,14]
== zw (+) (33 : zw (+) (zw (+) (zw (+) (g [10..14]) [11..14]) [12..14])) [13,14]
== 46 : zw (+) (zw (+) (zw (+) (zw (+) (g [10..14]) [11..14]) [12..14])) [14]
== zw (+) (zw (+) (zw (+) (zw (+) (g [10..14]) [11..14]) [12..14])) [14]
== zw (+) (46: zw (+) (zw (+) (zw (+) (zw (+) (g [10..14]) [11..14]) [12..14]))) [14]
== 60 : zw (+) (zw (+) (zw (+) (zw (+) (zw (+) (g [10..14]) [11..14]) [12..14]))) []
== 60
g [10..14] = 10:21:33:46:60[]
g'' [10..14]
== zw (+) (g'' [10..14]) [10..14]
== zw (+) (zw' (+) (g'' [10..14]) [10..14]) [10..14]
== zw (+) (zw (+) (zw (+) (g'' [10..14]) [10..14]) [10..14]) [10..14]
== [Hang]
-}
|
egaburov/funstuff
|
Haskell/sharing/observable1.hs
|
apache-2.0
| 2,828 | 0 | 9 | 648 | 595 | 329 | 266 | 31 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fsimpl-tick-factor=200 #-}
module RandomDates.Random
( randomDate
, generateData
) where
import Control.Applicative
import Control.Monad
import qualified Data.HashMap.Strict as M
import qualified Data.Text as T
import Data.Thyme
import System.Random.MWC
import System.Random.MWC.Distributions
import RandomDates.Text
import RandomDates.Types
randomDate :: GenIO -> Day -> Int -> IO Day
randomDate g (ModifiedJulianDay d) stdev =
ModifiedJulianDay . truncate <$> normal (fromIntegral d) (fromIntegral stdev) g
generateData :: Int -> Day -> Int -> MarkovChains -> IO [DateRow]
generateData n mean stdev mc = withSystemRandom $ go n (createStartTable mc) M.empty
where
go 0 _ _ _ = return []
go n table cache g = do
(cache', title) <- fmap (fmap T.unwords . lastCache)
. generateText_ g table cache mc
. pos
. truncate
=<< normal 8 3 g
(cache'', descr) <- fmap (fmap unparas . lastCache)
. generateParagraphs g mc 50 10
. pos
. truncate
=<< normal 10 7 g
date <- randomDate g mean stdev
print (n, title, date, T.length descr)
(DateRow title descr date:) <$> go (pred n) table cache'' g
unparas = T.intercalate "\n\n" . map T.unwords
|
erochest/random-dates
|
src/RandomDates/Random.hs
|
apache-2.0
| 1,654 | 0 | 18 | 655 | 438 | 227 | 211 | 35 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Spark.Core.Internal.ProtoUtils(ToProto(..), FromProto(..), extractMaybe, extractMaybe') where
import Data.ProtoLens.Message(Message(descriptor), MessageDescriptor(messageName))
import Lens.Family2 ((^.), FoldLike)
import Data.ProtoLens.TextFormat(showMessageShort)
import Formatting
import GHC.Stack(HasCallStack)
import Data.Text(Text)
import Spark.Core.Try(Try, tryError)
{-| The class of types that can be read from a proto description. -}
class FromProto p x | x -> p where
fromProto :: (Message p, HasCallStack) => p -> Try x
{-| The class of types that can be exported to a proto type. -}
class ToProto p x | x -> p where
toProto :: (Message p) => x -> p
extractMaybe :: forall m a1 a' b. (Message m, HasCallStack) => m -> FoldLike (Maybe a1) m a' (Maybe a1) b -> Text -> Try a1
extractMaybe msg fun ctx =
case msg ^. fun of
Just x' -> return x'
Nothing -> tryError $ sformat ("extractMaybe: extraction failed in context "%shown%" for message of type:"%shown%" value:"%shown) ctx txt msg' where
d = descriptor :: MessageDescriptor m
txt = messageName d
msg' = showMessageShort msg
extractMaybe' :: (Message m, Message m1, FromProto m1 a1, HasCallStack) => m -> FoldLike (Maybe m1) m a' (Maybe m1) b -> Text -> Try a1
extractMaybe' msg fun ctx = extractMaybe msg fun ctx >>= fromProto
|
tjhunter/karps
|
haskell/src/Spark/Core/Internal/ProtoUtils.hs
|
apache-2.0
| 1,448 | 0 | 15 | 251 | 457 | 253 | 204 | -1 | -1 |
{-# LANGUAGE TypeFamilies, StandaloneDeriving, RecordWildCards, MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Hoodle.BBox
-- Copyright : (c) 2011, 2012 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module Data.Hoodle.BBox
( BBox (..)
, GetBBoxable (..)
, MakeBBoxedable (..)
, BBoxed (..)
-- , StrokeBBox (..)
-- , strkbbx_strk
-- , strkbbx_bbx
-- , mkStrokeBBox
-- , ImageBBox (..)
-- , imgbbx_img
-- , imgbbx_bbx
-- , mkImageBBox
-- , SVGBBox (..)
-- , mkSVGBBox
, mkbbox
, mkbboxF
, bboxFromStroke
, bboxFromImage
, bboxFromSVG
, dimToBBox
, bboxToDim
, xformBBox
, inflate
, moveBBoxToOrigin
, moveBBoxByOffset
, moveBBoxULCornerTo
, intersectBBox
, unionBBox
, ULMaybe (..)
, IntersectBBox (..)
, UnionBBox (..)
, Maybeable (..)
, bbox4All
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Identity
import qualified Data.Foldable as F
import Data.Monoid
import Data.Serialize
import Data.Strict.Tuple
-- from this package
import Data.Hoodle.Simple
import Data.Hoodle.Util
--
import Prelude hiding (fst,snd)
import qualified Prelude as Prelude (fst,snd)
-- | bounding box type
data BBox = BBox { bbox_upperleft :: (Double,Double)
, bbox_lowerright :: (Double,Double) }
deriving (Show,Eq,Ord)
-- |
instance Serialize BBox where
put BBox{..} = put bbox_upperleft >> put bbox_lowerright
get = liftM2 BBox get get
data BBoxed a = BBoxed { bbxed_content :: a
, bbxed_bbx :: BBox }
deriving instance (Show a) => Show (BBoxed a)
deriving instance (Eq a) => Eq (BBoxed a)
deriving instance (Ord a) => Ord (BBoxed a)
-- |
class GetBBoxable a where
getBBox :: a -> BBox
instance GetBBoxable (BBoxed a) where
getBBox = bbxed_bbx
-- |
class (Monad m) => MakeBBoxedable m a where
makeBBoxed :: a -> m (BBoxed a)
instance MakeBBoxedable Identity Stroke where
makeBBoxed strk = return (BBoxed strk (bboxFromStroke strk))
instance MakeBBoxedable Identity Image where
makeBBoxed img = return (BBoxed img (bboxFromImage img))
instance MakeBBoxedable Identity SVG where
makeBBoxed svg = return (BBoxed svg (bboxFromSVG svg))
instance MakeBBoxedable Identity Link where
makeBBoxed lnk = return (BBoxed lnk (bboxFromLink lnk))
-- |
mkbbox :: [Pair Double Double] -> BBox
mkbbox lst = let xs = map fst lst
ys = map snd lst
in BBox { bbox_upperleft = (minimum xs, minimum ys)
, bbox_lowerright = (maximum xs, maximum ys) }
-- |
mkbboxF :: (F.Foldable m, Functor m) => m (Double,Double) -> BBox
mkbboxF lst =
let xs = fmap Prelude.fst lst
ys = fmap Prelude.snd lst
in BBox{bbox_upperleft=(F.minimum xs, F.minimum ys)
,bbox_lowerright=(F.maximum xs, F.maximum ys)}
-- |
bboxFromStroke :: Stroke -> BBox
bboxFromStroke (Stroke _ _ w dat) = inflate (mkbbox dat) w
bboxFromStroke (VWStroke _ _ dat) =
let dat' = map ((,) <$> fst3 <*> snd3) dat
widthmax = F.maximum (map trd3 dat)
in inflate (mkbboxF dat') widthmax
-- |
dimToBBox :: Dimension -> BBox
dimToBBox (Dim w h) = BBox (0,0) (w,h)
-- |
-- |
bboxToDim :: BBox -> Dimension
bboxToDim (BBox (x1,y1) (x2,y2)) = Dim (x2-x1) (y2-y1)
-- |
bboxFromImage :: Image -> BBox
bboxFromImage (Image _ (x,y) d) = moveBBoxULCornerTo (x,y) (dimToBBox d)
-- |
bboxFromSVG :: SVG -> BBox
bboxFromSVG (SVG _ _ _ (x,y) d) = moveBBoxULCornerTo (x,y) (dimToBBox d)
-- |
bboxFromLink :: Link -> BBox
bboxFromLink (Link _ _ _ _ _ _ (x,y) d) = moveBBoxULCornerTo (x,y) (dimToBBox d)
bboxFromLink (LinkDocID _ _ _ _ _ _ (x,y) d) = moveBBoxULCornerTo (x,y) (dimToBBox d)
-- | general transform BBox
xformBBox :: ((Double,Double) -> (Double,Double)) -> BBox -> BBox
xformBBox f (BBox c1 c2) = BBox (f c1) (f c2)
-- | inflate bbox by amount r
inflate :: BBox -> Double -> BBox
inflate (BBox (x1,y1) (x2,y2)) r = BBox (x1-r,y1-r) (x2+r,y2+r)
-- |
moveBBoxToOrigin :: BBox -> BBox
moveBBoxToOrigin (BBox (x0,y0) (x1,y1)) = BBox (0,0) (x1-x0,y1-y0)
-- |
moveBBoxByOffset :: (Double,Double) -> BBox -> BBox
moveBBoxByOffset (xoff,yoff) (BBox (x0,y0) (x1,y1)) = BBox (x0+xoff,y0+yoff) (x1+xoff,y1+yoff)
-- |
moveBBoxULCornerTo :: (Double,Double) -> BBox -> BBox
moveBBoxULCornerTo (x,y) b@(BBox (x0,y0) _) = moveBBoxByOffset (x-x0,y-y0) b
-- |
intersectBBox :: BBox -> BBox -> Maybe BBox
intersectBBox (BBox (x1,y1) (x2,y2)) (BBox (x3,y3) (x4,y4)) = do
guard $ (x1 <= x3 && x3 <= x2) || (x3 <= x1 && x1 <= x4 )
guard $ (y1 <= y3 && y3 <= y2) || (y3 <= y1 && y1 <= y4 )
let x5 = if x1 <= x3 then x3 else x1
y5 = if y1 <= y3 then y3 else y1
x6 = min x2 x4
y6 = min y2 y4
return (BBox (x5,y5) (x6,y6))
-- |
unionBBox :: BBox -> BBox -> BBox
unionBBox (BBox (x1,y1) (x2,y2)) (BBox (x3,y3) (x4,y4)) =
let x5 = if x1 < x3 then x1 else x3
y5 = if y1 < y3 then y1 else y3
x6 = if x2 < x4 then x4 else x2
y6 = if y2 < y4 then y4 else y2
in BBox (x5,y5) (x6,y6)
-- |
data ULMaybe a = Bottom | Middle a | Top
deriving instance Show a => Show (ULMaybe a)
deriving instance Eq a => Eq (ULMaybe a)
-- |
newtype IntersectBBox = Intersect { unIntersect :: ULMaybe BBox }
deriving (Show,Eq)
-- |
newtype UnionBBox = Union { unUnion :: ULMaybe BBox }
deriving (Show,Eq)
instance Monoid (IntersectBBox) where
(Intersect Bottom) `mappend` _ = Intersect Bottom
_ `mappend` (Intersect Bottom) = Intersect Bottom
(Intersect Top) `mappend` x = x
x `mappend` (Intersect Top) = x
(Intersect (Middle x)) `mappend` (Intersect (Middle y)) =
maybe (Intersect Bottom) (Intersect . Middle) (x `intersectBBox` y)
mempty = Intersect Top
instance Monoid (UnionBBox) where
(Union Bottom) `mappend` x = x
x `mappend` (Union Bottom) = x
(Union Top) `mappend` _ = Union Top
_ `mappend` (Union Top) = Union Top
(Union (Middle x)) `mappend` (Union (Middle y)) = Union (Middle (x `unionBBox` y))
mempty = Union Bottom
-- |
class Maybeable a where
type ElemType a :: *
toMaybe :: a -> Maybe (ElemType a)
fromMaybe :: Maybe (ElemType a) -> a
instance Maybeable IntersectBBox where
type ElemType IntersectBBox = BBox
toMaybe (Intersect Bottom) = Nothing
toMaybe (Intersect Top) = Nothing
toMaybe (Intersect (Middle x)) = Just x
fromMaybe Nothing = Intersect Top
fromMaybe (Just x) = Intersect (Middle x)
instance Maybeable UnionBBox where
type ElemType UnionBBox = BBox
toMaybe (Union Bottom) = Nothing
toMaybe (Union Top) = Nothing
toMaybe (Union (Middle x)) = Just x
fromMaybe Nothing = Union Top
fromMaybe (Just x) = Union (Middle x)
-- |
bbox4All :: (F.Foldable t, Functor t, GetBBoxable a) => t a -> ULMaybe BBox
bbox4All = unUnion . F.fold . fmap (Union . Middle . getBBox)
|
wavewave/hoodle-types
|
src/Data/Hoodle/BBox.hs
|
bsd-2-clause
| 7,256 | 0 | 13 | 1,744 | 2,781 | 1,524 | 1,257 | 157 | 5 |
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_HADDOCK hide #-}
module Network.HTTP.Client.Lens.Internal where
import Control.Applicative
import Control.Exception (Exception(..), SomeException)
import Data.Profunctor (Profunctor(..), Choice(..))
type Prism s t a b = forall p f. (Choice p, Applicative f) => p a (f b) -> p s (f t)
type Prism' s a = Prism s s a a
type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
type Lens' s a = Lens s s a a
view :: Lens' s a -> s -> a
view l = getConst . l Const
{-# INLINE view #-}
prism :: (b -> t) -> (s -> Either t a) -> Prism s t a b
prism bt seta = dimap seta (either pure (fmap bt)) . right'
{-# INLINE prism #-}
prism' :: (b -> s) -> (s -> Maybe a) -> Prism s s a b
prism' bs sma = prism bs (\s -> maybe (Left s) Right (sma s))
{-# INLINE prism' #-}
exception :: Exception a => Prism' SomeException a
exception = prism' toException fromException
{-# INLINE exception #-}
infixl 1 <&>
(<&>) :: Functor f => f a -> (a -> b) -> f b
(<&>) = flip fmap
{-# INLINE (<&>) #-}
|
supki/libjenkins
|
src/Network/HTTP/Client/Lens/Internal.hs
|
bsd-2-clause
| 1,033 | 0 | 10 | 227 | 458 | 252 | 206 | 26 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Database.SqlServer.Definition.Database where
import Database.SqlServer.Definition.Identifier (RegularIdentifier)
import Database.SqlServer.Definition.Table (Table)
import Database.SqlServer.Definition.View (View)
import Database.SqlServer.Definition.Sequence (Sequence)
import Database.SqlServer.Definition.Procedure (Procedure)
import Database.SqlServer.Definition.User (User,Role)
import Database.SqlServer.Definition.FullTextCatalog (FullTextCatalog)
import Database.SqlServer.Definition.FullTextStopList (FullTextStopList)
import Database.SqlServer.Definition.Function (Function)
import Database.SqlServer.Definition.Credential (Credential)
import Database.SqlServer.Definition.MessageType (MessageType)
import Database.SqlServer.Definition.BrokerPriority (BrokerPriority)
import Database.SqlServer.Definition.PartitionFunction (PartitionFunction)
import Database.SqlServer.Definition.Contract (Contract)
import Database.SqlServer.Definition.Login (Login)
import Database.SqlServer.Definition.Entity
import Test.QuickCheck
import Test.QuickCheck.Gen
import Test.QuickCheck.Random
import Text.PrettyPrint
import Data.DeriveTH
data MasterKey = MasterKey
derive makeArbitrary ''MasterKey
renderMasterKey :: MasterKey -> Doc
renderMasterKey _ = text "CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'weKKjwehg252t!!'"
$+$ text "GO"
data Database = Database
{
databaseName :: RegularIdentifier
, tables :: [Table]
, views :: [View]
, sequences :: [Sequence]
, procedures :: [Procedure]
, functions :: [Function]
, users :: [User]
, roles :: [Role]
, fullTextCatalogs :: [FullTextCatalog]
, fullTextStopLists :: [FullTextStopList]
, credentials :: [Credential]
, messages :: [MessageType]
, brokerPriorities :: [BrokerPriority]
, partitionFunctions :: [PartitionFunction]
, logins :: [Login]
, contracts :: [Contract]
, masterKey :: MasterKey
}
instance Entity Database where
name = databaseName
toDoc = renderDatabase
renderNamedEntities :: Entity a => [a] -> Doc
renderNamedEntities xs = vcat (map toDoc xs)
-- Note that some parts aren't rendered to avoid bloat
renderDatabase :: Database -> Doc
renderDatabase dd = text "USE master" $+$
text "GO" $+$
text "CREATE DATABASE" <+> dbName $+$
text "GO" $+$
text "USE" <+> dbName $+$
renderMasterKey (masterKey dd) $+$
renderNamedEntities (tables dd) $+$
renderNamedEntities (views dd) $+$
renderNamedEntities (sequences dd) $+$
renderNamedEntities (procedures dd) $+$
renderNamedEntities (functions dd) $+$
renderNamedEntities (users dd) $+$
renderNamedEntities (roles dd) $+$
renderNamedEntities (fullTextCatalogs dd) $+$
renderNamedEntities (fullTextStopLists dd) $+$
renderNamedEntities (credentials dd) $+$
renderNamedEntities (messages dd) $+$
renderNamedEntities (brokerPriorities dd) $+$
renderNamedEntities (partitionFunctions dd) $+$
text "GO"
where
dbName = renderName dd
derive makeArbitrary ''Database
generateExamples :: (Show a) => Int -> Gen a -> IO [a]
generateExamples m a = generate (sequence [resize n a | n <- [0..m] ])
saveExamples :: (Show a) => FilePath -> [a] -> IO ()
saveExamples p xs = writeFile p (unlines $ map show xs)
instance Show Database where
show = render . renderDatabase
data GenerateOptions = GenerateOptions
{
size :: Int
, seed :: Int
}
generateEntity :: (Arbitrary a, Entity a) => GenerateOptions -> a
generateEntity go = unGen arbitrary (mkQCGen (seed go)) (size go)
|
SuperDrew/sql-server-gen
|
src/Database/SqlServer/Definition/Database.hs
|
bsd-2-clause
| 3,915 | 0 | 26 | 879 | 972 | 544 | 428 | 86 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE UndecidableInstances #-}
module Language.Haskell.Liquid.Types.PredType (
PrType
, TyConP (..), DataConP (..)
, dataConTy
, dataConPSpecType
, makeTyConInfo
, replacePreds
, replacePredsWithRefs
, pVartoRConc
-- * Dummy `Type` that represents _all_ abstract-predicates
, predType
-- * Compute @RType@ of a given @PVar@
, pvarRType
, substParg
, pApp
, pappSort, pappArity
) where
import Prelude hiding (error)
import DataCon
import Text.PrettyPrint.HughesPJ
import qualified TyCon as TC
import Type
import TypeRep
import qualified Data.HashMap.Strict as M
import Data.List (foldl', partition)
import Language.Fixpoint.Misc
import Language.Fixpoint.Types hiding (Expr, Predicate)
import qualified Language.Fixpoint.Types as F
import Language.Haskell.Liquid.GHC.Misc
import Language.Haskell.Liquid.Misc
import Language.Haskell.Liquid.Types.RefType hiding (generalize)
import Language.Haskell.Liquid.Types
import Data.List (nub)
import Data.Default
makeTyConInfo = hashMapMapWithKey mkRTyCon . M.fromList
mkRTyCon :: TC.TyCon -> TyConP -> RTyCon
mkRTyCon tc (TyConP αs' ps _ tyvariance predvariance size) = RTyCon tc pvs' (mkTyConInfo tc tyvariance predvariance size)
where τs = [rVar α :: RSort | α <- tyConTyVarsDef tc]
pvs' = subts (zip αs' τs) <$> ps
dataConPSpecType :: DataCon -> DataConP -> SpecType
dataConPSpecType dc (DataConP _ vs ps ls cs yts rt _) = mkArrow vs ps ls ts' rt'
where
(xs, ts) = unzip $ reverse yts
-- mkDSym = (`mappend` symbol dc) . (`mappend` "_") . symbol
mkDSym z = (symbol z) `suffixSymbol` (symbol dc)
ys = mkDSym <$> xs
tx _ [] [] [] = []
tx su (x:xs) (y:ys) (t:ts) = (y, subst (F.mkSubst su) t, mempty)
: tx ((x, F.EVar y):su) xs ys ts
tx _ _ _ _ = panic Nothing "PredType.dataConPSpecType.tx called on invalid inputs"
yts' = tx [] xs ys ts
ts' = map ("" , , mempty) cs ++ yts'
su = F.mkSubst [(x, F.EVar y) | (x, y) <- zip xs ys]
rt' = subst su rt
instance PPrint TyConP where
pprintTidy k (TyConP vs ps ls _ _ _)
= (parens $ hsep (punctuate comma (map (pprintTidy k) vs))) <+>
(parens $ hsep (punctuate comma (map (pprintTidy k) ps))) <+>
(parens $ hsep (punctuate comma (map (pprintTidy k) ls)))
instance Show TyConP where
show = showpp -- showSDoc . ppr
instance PPrint DataConP where
pprintTidy k (DataConP _ vs ps ls cs yts t _)
= (parens $ hsep (punctuate comma (map (pprintTidy k) vs))) <+>
(parens $ hsep (punctuate comma (map (pprintTidy k) ps))) <+>
(parens $ hsep (punctuate comma (map (pprintTidy k) ls))) <+>
(parens $ hsep (punctuate comma (map (pprintTidy k) cs))) <+>
(parens $ hsep (punctuate comma (map (pprintTidy k) yts))) <+>
pprintTidy k t
instance Show DataConP where
show = showpp
dataConTy m (TyVarTy v)
= M.lookupDefault (rVar v) (RTV v) m
dataConTy m (FunTy t1 t2)
= rFun dummySymbol (dataConTy m t1) (dataConTy m t2)
dataConTy m (ForAllTy α t)
= RAllT (rTyVar α) (dataConTy m t)
dataConTy m (TyConApp c ts)
= rApp c (dataConTy m <$> ts) [] mempty
dataConTy _ _
= panic Nothing "ofTypePAppTy"
----------------------------------------------------------------------------
----- Interface: Replace Predicate With Uninterprented Function Symbol -----
----------------------------------------------------------------------------
replacePredsWithRefs (p, r) (MkUReft (Reft(v, rs)) (Pr ps) s)
= MkUReft (Reft (v, rs'')) (Pr ps2) s
where
rs'' = mconcat $ rs : rs'
rs' = r . (v,) . pargs <$> ps1
(ps1, ps2) = partition (== p) ps
pVartoRConc p (v, args) | length args == length (pargs p)
= pApp (pname p) $ EVar v : (thd3 <$> args)
pVartoRConc p (v, args)
= pApp (pname p) $ EVar v : args'
where
args' = (thd3 <$> args) ++ (drop (length args) (thd3 <$> pargs p))
-----------------------------------------------------------------------
-- | @pvarRType π@ returns a trivial @RType@ corresponding to the
-- function signature for a @PVar@ @π@. For example, if
-- @π :: T1 -> T2 -> T3 -> Prop@
-- then @pvarRType π@ returns an @RType@ with an @RTycon@ called
-- @predRTyCon@ `RApp predRTyCon [T1, T2, T3]`
-----------------------------------------------------------------------
pvarRType :: (PPrint r, Reftable r) => PVar RSort -> RRType r
-----------------------------------------------------------------------
pvarRType (PV _ k {- (PVProp τ) -} _ args) = rpredType k (fst3 <$> args) -- (ty:tys)
-- where
-- ty = uRTypeGen τ
-- tys = uRTypeGen . fst3 <$> args
-- rpredType :: (PPrint r, Reftable r) => PVKind (RRType r) -> [RRType r] -> RRType r
rpredType (PVProp t) ts = RApp predRTyCon (uRTypeGen <$> t : ts) [] mempty
rpredType PVHProp ts = RApp wpredRTyCon (uRTypeGen <$> ts) [] mempty
predRTyCon :: RTyCon
predRTyCon = symbolRTyCon predName
wpredRTyCon :: RTyCon
wpredRTyCon = symbolRTyCon wpredName
symbolRTyCon :: Symbol -> RTyCon
symbolRTyCon n = RTyCon (stringTyCon 'x' 42 $ symbolString n) [] def
-------------------------------------------------------------------------------------
-- | Instantiate `PVar` with `RTProp` -----------------------------------------------
-------------------------------------------------------------------------------------
-- | @replacePreds@ is the main function used to substitute an (abstract)
-- predicate with a concrete Ref, that is either an `RProp` or `RHProp`
-- type. The substitution is invoked to obtain the `SpecType` resulting
-- at /predicate application/ sites in 'Language.Haskell.Liquid.Constraint'.
-- The range of the `PVar` substitutions are /fresh/ or /true/ `RefType`.
-- That is, there are no further _quantified_ `PVar` in the target.
-------------------------------------------------------------------------------------
replacePreds :: String -> SpecType -> [(RPVar, SpecProp)] -> SpecType
-------------------------------------------------------------------------------------
replacePreds msg = foldl' go
where
go _ (_, RProp _ (RHole _)) = panic Nothing "replacePreds on RProp _ (RHole _)"
go z (π, t) = substPred msg (π, t) z
-- TODO: replace `replacePreds` with
-- instance SubsTy RPVar (Ref RReft SpecType) SpecType where
-- subt (pv, r) t = replacePreds "replacePred" t (pv, r)
-- replacePreds :: String -> SpecType -> [(RPVar, Ref Reft RefType)] -> SpecType
-- replacePreds msg = foldl' go
-- where go z (π, RProp t) = substPred msg (π, t) z
-- go z (π, RPropP r) = replacePVarReft (π, r) <$> z
-------------------------------------------------------------------------------
substPred :: String -> (RPVar, SpecProp) -> SpecType -> SpecType
-------------------------------------------------------------------------------
substPred _ (π, RProp ss (RVar a1 r1)) t@(RVar a2 r2)
| isPredInReft && a1 == a2 = RVar a1 $ meetListWithPSubs πs ss r1 r2'
| isPredInReft = panic Nothing ("substPred RVar Var Mismatch" ++ show (a1, a2))
| otherwise = t
where
(r2', πs) = splitRPvar π r2
isPredInReft = not $ null πs
substPred msg su@(π, _ ) (RApp c ts rs r)
| null πs = t'
| otherwise = substRCon msg su t' πs r2'
where
t' = RApp c (substPred msg su <$> ts) (substPredP msg su <$> rs) r
(r2', πs) = splitRPvar π r
substPred msg (p, tp) (RAllP (q@(PV _ _ _ _)) t)
| p /= q = RAllP q $ substPred msg (p, tp) t
| otherwise = RAllP q t
substPred msg su (RAllT a t) = RAllT a (substPred msg su t)
substPred msg su@(π,_ ) (RFun x t t' r)
| null πs = RFun x (substPred msg su t) (substPred msg su t') r
| otherwise = {-meetListWithPSubs πs πt -}(RFun x t t' r')
where (r', πs) = splitRPvar π r
substPred msg su (RRTy e r o t) = RRTy (mapSnd (substPred msg su) <$> e) r o (substPred msg su t)
substPred msg su (RAllE x t t') = RAllE x (substPred msg su t) (substPred msg su t')
substPred msg su (REx x t t') = REx x (substPred msg su t) (substPred msg su t')
substPred _ _ t = t
-- | Requires: @not $ null πs@
-- substRCon :: String -> (RPVar, SpecType) -> SpecType -> SpecType
substRCon msg (_, RProp ss t1@(RApp c1 ts1 rs1 r1)) t2@(RApp c2 ts2 rs2 _) πs r2'
| rtc_tc c1 == rtc_tc c2 = RApp c1 ts rs $ meetListWithPSubs πs ss r1 r2'
where
ts = subst su $ safeZipWith (msg ++ ": substRCon") strSub ts1 ts2
rs = subst su $ safeZipWith (msg ++ ": substRCon2") strSubR rs1' rs2'
(rs1', rs2') = pad "substRCon" top rs1 rs2
strSub r1 r2 = meetListWithPSubs πs ss r1 r2
strSubR r1 r2 = meetListWithPSubsRef πs ss r1 r2
su = mkSubst $ zipWith (\s1 s2 -> (s1, EVar s2)) (rvs t1) (rvs t2)
rvs = foldReft (\_ r acc -> rvReft r : acc) []
rvReft r = let Reft(s,_) = toReft r in s
substRCon msg su t _ _ = panic Nothing $ msg ++ " substRCon " ++ showpp (su, t)
pad _ f [] ys = (f <$> ys, ys)
pad _ f xs [] = (xs, f <$> xs)
pad msg _ xs ys
| nxs == nys = (xs, ys)
| otherwise = panic Nothing $ "pad: " ++ msg
where
nxs = length xs
nys = length ys
substPredP _ su p@(RProp _ (RHole _))
= panic Nothing ("PredType.substPredP1 called on invalid inputs: " ++ showpp (su, p))
substPredP msg su@(p, RProp ss _) (RProp s t)
= RProp ss' $ substPred (msg ++ ": substPredP") su t
where
ss' = drop n ss ++ s
n = length ss - length (freeArgsPs p t)
splitRPvar pv (MkUReft x (Pr pvs) s) = (MkUReft x (Pr pvs') s, epvs)
where
(epvs, pvs') = partition (uPVar pv ==) pvs
-- TODO: rewrite using foldReft
freeArgsPs p (RVar _ r)
= freeArgsPsRef p r
freeArgsPs p (RFun _ t1 t2 r)
= nub $ freeArgsPsRef p r ++ freeArgsPs p t1 ++ freeArgsPs p t2
freeArgsPs p (RAllT _ t)
= freeArgsPs p t
freeArgsPs p (RAllS _ t)
= freeArgsPs p t
freeArgsPs p (RAllP p' t)
| p == p' = []
| otherwise = freeArgsPs p t
freeArgsPs p (RApp _ ts _ r)
= nub $ freeArgsPsRef p r ++ concatMap (freeArgsPs p) ts
freeArgsPs p (RAllE _ t1 t2)
= nub $ freeArgsPs p t1 ++ freeArgsPs p t2
freeArgsPs p (REx _ t1 t2)
= nub $ freeArgsPs p t1 ++ freeArgsPs p t2
freeArgsPs p (RAppTy t1 t2 r)
= nub $ freeArgsPsRef p r ++ freeArgsPs p t1 ++ freeArgsPs p t2
freeArgsPs _ (RExprArg _)
= []
freeArgsPs p (RHole r)
= freeArgsPsRef p r
freeArgsPs p (RRTy env r _ t)
= nub $ concatMap (freeArgsPs p) (snd <$> env) ++ freeArgsPsRef p r ++ freeArgsPs p t
freeArgsPsRef p (MkUReft _ (Pr ps) _) = [x | (_, x, w) <- (concatMap pargs ps'), (EVar x) == w]
where
ps' = f <$> filter (uPVar p ==) ps
f q = q {pargs = pargs q ++ drop (length (pargs q)) (pargs $ uPVar p)}
meetListWithPSubs πs ss r1 r2 = foldl' (meetListWithPSub ss r1) r2 πs
meetListWithPSubsRef πs ss r1 r2 = foldl' ((meetListWithPSubRef ss) r1) r2 πs
meetListWithPSub :: (Reftable r, PPrint t) => [(Symbol, RSort)]-> r -> r -> PVar t -> r
meetListWithPSub ss r1 r2 π
| all (\(_, x, EVar y) -> x == y) (pargs π)
= r2 `meet` r1
| all (\(_, x, EVar y) -> x /= y) (pargs π)
= r2 `meet` (subst su r1)
| otherwise
= panic Nothing $ "PredType.meetListWithPSub partial application to " ++ showpp π
where
su = mkSubst [(x, y) | (x, (_, _, y)) <- zip (fst <$> ss) (pargs π)]
meetListWithPSubRef _ (RProp _ (RHole _)) _ _ -- TODO: Is this correct?
= panic Nothing "PredType.meetListWithPSubRef called with invalid input"
meetListWithPSubRef _ _ (RProp _ (RHole _)) _
= panic Nothing "PredType.meetListWithPSubRef called with invalid input"
meetListWithPSubRef ss (RProp s1 r1) (RProp s2 r2) π
| all (\(_, x, EVar y) -> x == y) (pargs π)
= RProp s1 $ (subst su' r2) `meet` r1
| all (\(_, x, EVar y) -> x /= y) (pargs π)
= RProp s2 $ r2 `meet` (subst su r1)
| otherwise
= panic Nothing $ "PredType.meetListWithPSubRef partial application to " ++ showpp π
where
su = mkSubst [(x, y) | (x, (_, _, y)) <- zip (fst <$> ss) (pargs π)]
su' = mkSubst [(x, EVar y) | (x, y) <- zip (fst <$> s2) (fst <$> s1)]
----------------------------------------------------------------------------
-- | Interface: Modified CoreSyn.exprType due to predApp -------------------
----------------------------------------------------------------------------
predType :: Type
predType = symbolType predName
wpredName, predName :: Symbol
predName = "Pred"
wpredName = "WPred"
symbolType = TyVarTy . symbolTyVar
substParg :: Functor f => (Symbol, F.Expr) -> f Predicate -> f Predicate
substParg (x, y) = fmap fp
where
fxy s = if (s == EVar x) then y else s
fp = subvPredicate (\pv -> pv { pargs = mapThd3 fxy <$> pargs pv })
-------------------------------------------------------------------------------
----------------------------- Predicate Application --------------------------
-------------------------------------------------------------------------------
pappArity :: Int
pappArity = 7
pappSort :: Int -> Sort
pappSort n = mkFFunc (2 * n) $ [ptycon] ++ args ++ [boolSort]
where
ptycon = fAppTC predFTyCon $ FVar <$> [0..n-1]
args = FVar <$> [n..(2*n-1)]
predFTyCon = symbolFTycon $ dummyLoc predName
|
ssaavedra/liquidhaskell
|
src/Language/Haskell/Liquid/Types/PredType.hs
|
bsd-3-clause
| 13,989 | 0 | 19 | 3,521 | 4,724 | 2,459 | 2,265 | 225 | 3 |
{-# LANGUAGE NamedFieldPuns, RecordWildCards, ViewPatterns #-}
module Network.RMV.Output (ppTime,ppResult,ppRoute) where
import Network.RMV.Types
import qualified Data.ByteString.Lazy as B
import qualified Data.Map as M
import Control.Applicative
import Control.Arrow
import Control.Monad
import Data.List
import Data.Maybe
import Text.Template
ppTime :: Int -> String
ppTime mins = pad (mins `div` 60) ++ ":" ++ pad (mins `mod` 60)
where pad (show -> m) = replicate (2 - length m) '0' ++ m
ppRoute :: Options -> RouteInfo -> String
ppRoute (Options{..}) (RouteInfo {..}) =
map (toEnum . fromEnum) . B.unpack . substitute (fromString opTemplate) .
M.fromList . map (fromString *** fromString) $
[ ("duration", maybe " " ppTime riDuration)
, ("start_time", fromMaybe " " riStartTime)
, ("start", riStartPoint)
, ("end", riEndPoint)
, ("line", riLine)
, ("end_time", fromMaybe "" riEndTime)
, ("newline","\n")
]
where fromString = B.pack . map (toEnum . fromEnum)
ppResult :: Options -> [[RouteInfo]] -> IO ()
ppResult opts = mapM_ printDetails . zip [1..]
where printDetails (n,rs) = do
putStrLn ("Route "++show n++":")
mapM_ printRoute rs
when (length rs > 1) $
let totDur = fmap (ppTime . sum) . sequence . map riDuration $ rs
in maybe (return ()) (putStrLn . ("Total duration: "++)) totDur
printRoute = putStrLn . ppRoute opts
|
dschoepe/rmv-query
|
Network/RMV/Output.hs
|
bsd-3-clause
| 1,563 | 0 | 19 | 434 | 537 | 292 | 245 | 35 | 1 |
difference maxNumber = squareofsums - sumofsqares where
sumofsqares = foldr (\x -> (+) (x * x)) 0 [1..maxNumber]
squareofsums = (sum [1..maxNumber])^2
main :: IO ()
main = print $ difference 100
|
stulli/projectEuler
|
eu06.hs
|
bsd-3-clause
| 205 | 0 | 12 | 42 | 94 | 50 | 44 | 5 | 1 |
{-# LANGUAGE TemplateHaskell, TypeOperators #-}
-- | An implementation of a zipper-like non-empty list structure that tracks
-- an index position in the list (the 'focus').
module Data.List.PointedList where
import Prelude hiding (foldl, foldr, elem)
import Control.Applicative
import Control.Monad
-- import Control.Lens (set)
import Data.Binary
import Data.DeriveTH
import Data.Foldable hiding (find)
import Data.List hiding (length, foldl, foldr, find, elem)
import qualified Data.List as List
import Data.Maybe
import Data.Traversable
-- | The implementation of the pointed list structure which tracks the current
-- position in the list structure.
data PointedList a = PointedList
{ _reversedPrefix :: [a]
, _focus :: a
, _suffix :: [a]
} deriving (Eq)
$(derive makeBinary ''PointedList)
-- | Lens compatible with Control.Lens.
reversedPrefix :: Functor f => ([a] -> f [a]) -> PointedList a -> f (PointedList a)
reversedPrefix f (PointedList ls x rs) = (\ls' -> PointedList ls' x rs) <$> f ls
-- | Lens compatible with Control.Lens.
focus :: Functor f => (a -> f a) -> PointedList a -> f (PointedList a)
focus f (PointedList ls x rs) = (\x' -> PointedList ls x' rs) <$> f x
-- | Lens compatible with Control.Lens.
suffix :: Functor f => ([a] -> f [a]) -> PointedList a -> f (PointedList a)
suffix f (PointedList ls x rs) = (\rs' -> PointedList ls x rs') <$> f rs
-- | Lens compatible with Control.Lens.
-- Internally reversing the prefix list.
prefix :: Functor f => ([a] -> f [a]) -> PointedList a -> f (PointedList a)
prefix f (PointedList ls x rs) = (\ls' -> PointedList (reverse ls') x rs) <$> f (reverse ls)
instance (Show a) => Show (PointedList a) where
show (PointedList ls x rs) = show (reverse ls) ++ " " ++ show x ++ " " ++ show rs
instance Functor PointedList where
fmap f (PointedList ls x rs) = PointedList (map f ls) (f x) (map f rs)
instance Foldable PointedList where
foldr f z (PointedList ls x rs) = foldl (flip f) (foldr f z (x:rs)) ls
instance Traversable PointedList where
traverse f (PointedList ls x rs) = PointedList <$>
(reverse <$> traverse f (reverse ls)) <*> f x <*> traverse f rs
-- | Create a 'PointedList' with a single element.
singleton :: a -> PointedList a
singleton x = PointedList [] x []
-- | Possibly create a @'Just' 'PointedList'@ if the provided list has at least
-- one element; otherwise, return Nothing.
--
-- The provided list's head will be the focus of the list, and the rest of
-- list will follow on the right side.
fromList :: [a] -> Maybe (PointedList a)
fromList [] = Nothing
fromList (x:xs) = Just $ PointedList [] x xs
-- | Possibly create a @'Just' 'PointedList'@ if the provided list has at least
-- one element; otherwise, return Nothing.
--
-- The provided list's last element will be the focus of the list, following
-- the rest of the list in order, to the left.
fromListEnd :: [a] -> Maybe (PointedList a)
fromListEnd [] = Nothing
fromListEnd xs = Just $ PointedList xs' x []
where (x:xs') = reverse xs
-- | Replace the focus of the list, retaining the prefix and suffix.
replace :: a -> PointedList a -> PointedList a
replace x (PointedList ls _ rs) = PointedList ls x rs
-- replace = set focus
-- | Possibly move the focus to the next element in the list.
next :: PointedList a -> Maybe (PointedList a)
next (PointedList _ _ []) = Nothing
next p = (Just . tryNext) p -- GHC doesn't allow PL form here
-- | Attempt to move the focus to the next element, or 'error' if there are
-- no more elements.
tryNext :: PointedList a -> PointedList a
tryNext p@(PointedList _ _ [] ) = error "cannot move to next element"
tryNext (PointedList ls x (r:rs)) = PointedList (x:ls) r rs
-- | Possibly move the focus to the previous element in the list.
previous :: PointedList a -> Maybe (PointedList a)
previous (PointedList [] _ _ ) = Nothing
previous p = (Just . tryPrevious) p
-- | Attempt to move the focus to the previous element, or 'error' if there are
-- no more elements.
tryPrevious :: PointedList a -> PointedList a
tryPrevious p@(PointedList [] _ _ ) =
error "cannot move to previous element"
tryPrevious (PointedList (l:ls) x rs) = PointedList ls l (x:rs)
-- | An alias for 'insertRight'.
insert :: a -> PointedList a -> PointedList a
insert = insertRight
-- | Insert an element to the left of the focus, then move the focus to the new
-- element.
insertLeft :: a -> PointedList a -> PointedList a
insertLeft y (PointedList ls x rs) = PointedList ls y (x:rs)
-- | Insert an element to the right of the focus, then move the focus to the
-- new element.
insertRight :: a -> PointedList a -> PointedList a
insertRight y (PointedList ls x rs) = PointedList (x:ls) y rs
-- | An alias of 'deleteRight'.
delete :: PointedList a -> Maybe (PointedList a)
delete = deleteRight
-- | Possibly delete the element at the focus, then move the element on the
-- left to the focus. If no element is on the left, focus on the element to
-- the right. If the deletion will cause the list to be empty, return
-- 'Nothing'.
deleteLeft :: PointedList a -> Maybe (PointedList a)
deleteLeft (PointedList [] _ [] ) = Nothing
deleteLeft (PointedList (l:ls) _ rs) = Just $ PointedList ls l rs
deleteLeft (PointedList [] _ (r:rs)) = Just $ PointedList [] r rs
-- | Possibly delete the element at the focus, then move the element on the
-- right to the focus. If no element is on the right, focus on the element to
-- the left. If the deletion will cause the list to be empty, return
-- 'Nothing'.
deleteRight :: PointedList a -> Maybe (PointedList a)
deleteRight (PointedList [] _ [] ) = Nothing
deleteRight (PointedList ls _ (r:rs)) = Just $ PointedList ls r rs
deleteRight (PointedList (l:ls) _ []) = Just $ PointedList ls l []
-- | Delete all elements in the list except the focus.
deleteOthers :: PointedList a -> PointedList a
deleteOthers (PointedList _ b _) = PointedList [] b []
-- | The length of the list.
length :: PointedList a -> Int
length = foldr (const (+1)) 0
-- | Whether the focus is the first element.
atStart :: PointedList a -> Bool
atStart (PointedList [] _ _) = True
atStart _ = False
-- | Whether the focus is the last element.
atEnd :: PointedList a -> Bool
atEnd (PointedList _ _ []) = True
atEnd _ = False
-- | Create a 'PointedList' of variations of the provided 'PointedList', in
-- which each element is focused, with the provided 'PointedList' as the
-- focus of the sets.
positions :: PointedList a -> PointedList (PointedList a)
positions p@(PointedList ls x rs) = PointedList left p right
where left = unfoldr (\p -> fmap (join (,)) $ previous p) p
right = unfoldr (\p -> fmap (join (,)) $ next p) p
-- | Map over the 'PointedList's created via 'positions', such that @f@ is
-- called with each element of the list focused in the provided
-- 'PointedList'. An example makes this easier to understand:
--
-- > contextMap atStart (fromJust $ fromList [1..5])
contextMap :: (PointedList a -> b) -> PointedList a -> PointedList b
contextMap f z = fmap f $ positions z
-- | Create a @'PointedList' a@ of @(a, 'Bool')@, in which the boolean values
-- specify whether the current element has the focus. That is, all of the
-- booleans will be 'False', except the focused element.
withFocus :: PointedList a -> PointedList (a, Bool)
withFocus (PointedList a b c) =
PointedList (zip a (repeat False)) (b, True) (zip c (repeat False))
-- | Move the focus to the specified index. The first element is at index 0.
moveTo :: Int -> PointedList a -> Maybe (PointedList a)
moveTo n pl = moveN (n - (index pl)) pl
-- | Move the focus by @n@, relative to the current index. Negative values move
-- the focus backwards, positive values more forwards through the list.
moveN :: Int -> PointedList a -> Maybe (PointedList a)
moveN n pl@(PointedList left x right) = go n left x right
where
go n left x right = case compare n 0 of
GT -> case right of
[] -> Nothing
(r:rs) -> go (n-1) (x:left) r rs
LT -> case left of
[] -> Nothing
(l:ls) -> go (n+1) ls l (x:right)
EQ -> Just $ PointedList left x right
-- | Move the focus to the specified element, if it is present.
--
-- Patch with much faster algorithm provided by Runar Bjarnason for version
-- 0.3.2. Improved again by Runar Bjarnason for version 0.3.3 to support
-- infinite lists on both sides of the focus.
find :: Eq a => a -> PointedList a -> Maybe (PointedList a)
find x pl = find' ((x ==) . _focus) $ positions pl
where find' pred (PointedList a b c) =
if pred b then Just b
else List.find pred (merge a c)
merge [] ys = ys
merge (x:xs) ys = x : merge ys xs
-- | The index of the focus, leftmost is 0.
index :: PointedList a -> Int
index (PointedList a _ _) = Prelude.length a
|
jeffwheeler/pointedlist
|
Data/List/PointedList.hs
|
bsd-3-clause
| 8,848 | 0 | 15 | 1,848 | 2,574 | 1,331 | 1,243 | 115 | 5 |
-- |
-- Module : Crypto.Hash.SHA1
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
-- module containing the binding functions to work with the
-- SHA1 cryptographic hash.
--
{-# LANGUAGE ForeignFunctionInterface #-}
module Crypto.Hash.SHA1 ( SHA1 (..) ) where
import Crypto.Hash.Types
import Foreign.Ptr (Ptr)
import Data.Word (Word8, Word32)
-- | SHA1 cryptographic hash algorithm
data SHA1 = SHA1
deriving (Show)
instance HashAlgorithm SHA1 where
hashBlockSize _ = 64
hashDigestSize _ = 20
hashInternalContextSize _ = 96
hashInternalInit = c_sha1_init
hashInternalUpdate = c_sha1_update
hashInternalFinalize = c_sha1_finalize
foreign import ccall unsafe "cryptonite_sha1_init"
c_sha1_init :: Ptr (Context a)-> IO ()
foreign import ccall "cryptonite_sha1_update"
c_sha1_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO ()
foreign import ccall unsafe "cryptonite_sha1_finalize"
c_sha1_finalize :: Ptr (Context a) -> Ptr (Digest a) -> IO ()
|
nomeata/cryptonite
|
Crypto/Hash/SHA1.hs
|
bsd-3-clause
| 1,156 | 0 | 10 | 271 | 236 | 132 | 104 | 20 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module Base.Job where
import Base.App
import Base.Context
import Base.Import
import Base.Logger
import Control.Concurrent (killThread)
import Control.Monad.Catch (MonadMask, finally)
import Control.Monad.Trans.State (get, gets, modify')
import qualified Data.Map as Map
import Servant
import System.Cron
type JobDetail = AppM IO ()
type AppMJob = (Text, Text, JobDetail)
runJob :: (MonadIO m, MonadCatch m) => [AppMJob] -> AppM m ()
runJob jobs = withLogName "job" $ do
mapM_ showJob jobs
infoLn $ "Job scheduling, count " <> showText (length jobs) <> "..."
context <- get
threads <- liftIO $ execSchedule $ mapM_ (go context) jobs
modify' $ \c -> c {baseJobs=baseJobs c `Map.union` Map.fromList (zipWith merge jobs threads)}
where merge (name,_,_) id = (id,name)
showJob (name,cron,_) = debugLn $ "Register job " <> name <> " with cron '" <> cron <> "'"
go :: BaseContext -> AppMJob -> Schedule ()
go context (name,cron,action) = flip addJob cron $ runAppM context $ do
reqId <- liftIO $ randomHex 8
withLogName (reqId <> " job." <> name) $ do
infoLn $ "Start Job " <> name
action
infoLn $ "End Job " <> name
killJobs :: (MonadIO m, MonadCatch m) => AppM m ()
killJobs = gets baseJobs >>= mapM_ kill . Map.toList
where kill (id,name) = do infoLn $ "Stop job " <> name <> "..."
liftIO $ killThread id
withJob :: (MonadIO m, MonadMask m) => [AppMJob] -> AppM m () -> AppM m ()
withJob jobs m = runJob jobs >> m `finally` killJobs
newJob :: (MonadIO m, MonadMask m) => AppMJob -> AppM m () -> AppM m ()
newJob job = withJob [job]
data JobResponse = JobResponse {
jobId :: Text
, jobName :: Text
} deriving (Show, Generic, ToSchema, FromJSON, ToJSON)
-- Administration API
type JobAdminApi = CheckAdminToken :> "jobs" :> Get '[JSON] [JobResponse]
jobAdminService :: ServerT JobAdminApi App
jobAdminService = getJobs
getJobs :: Token -> App [JobResponse]
getJobs _ = gets $ Map.elems . Map.mapWithKey toJobRes . baseJobs
where toJobRes = JobResponse . showText
|
leptonyu/mint
|
corn/src/Base/Job.hs
|
bsd-3-clause
| 2,569 | 0 | 15 | 802 | 807 | 427 | 380 | 52 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.