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
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Time.UK.Corpus ( corpus , negativeCorpus ) where import Data.String import Prelude import Duckling.Locale import Duckling.Resolve import Duckling.Testing.Types hiding (examples) import Duckling.Time.Corpus import Duckling.Time.Types hiding (Month) import Duckling.TimeGrain.Types hiding (add) context :: Context context = testContext {locale = makeLocale UK Nothing} corpus :: Corpus corpus = (context, testOptions, allExamples) negativeCorpus :: NegativeCorpus negativeCorpus = (context, testOptions, examples) where examples = [ "1 готель" , "1 пропозиція" , "наступний 5" ] allExamples :: [Example] allExamples = concat [examples (datetime (2013, 2, 12, 0, 0, 0) Day) [ "сьогодні" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Day) [ "вчора" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "завтра" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "понеділок" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "Понеділок, 18 лютого" , "18 лютого" ] , examples (datetime (2013, 2, 19, 0, 0, 0) Day) [ "вівторок" ] , examples (datetime (2013, 2, 14, 0, 0, 0) Day) [ "четвер" ] , examples (datetime (2013, 2, 15, 0, 0, 0) Day) [ "п'ятниця" ] , examples (datetime (2013, 2, 16, 0, 0, 0) Day) [ "субота" ] , examples (datetime (2013, 2, 17, 0, 0, 0) Day) [ "неділя" ] , examples (datetime (2013, 3, 1, 0, 0, 0) Day) [ "1 березня" , "перше березня" , "1 бер." ] , examples (datetime (2015, 3, 3, 0, 0, 0) Day) [ "3 березня 2015" , "3 бер. 2015" ] , examples (datetime (2013, 2, 15, 0, 0, 0) Day) [ "15 лютого" , "15.2" , "15 Лют" ] , examples (datetime (2013, 8, 8, 0, 0, 0) Day) [ "8 серпня" , "8 Сер" ] , examples (datetime (2014, 10, 0, 0, 0, 0) Month) [ "Жовтень 2014" ] , examples (datetime (2014, 11, 0, 0, 0, 0) Month) [ "Листопад 2014" ] , examples (datetime (1974, 10, 31, 0, 0, 0) Day) [ "31.10.1974" , "31.10.74" ] , examples (datetime (2015, 4, 14, 0, 0, 0) Day) [ "14 квітня 2015" ] , examples (datetime (2013, 2, 10, 0, 0, 0) Day) [ "Неділя, 10 лют." ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "Середа, 13 лютого" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "Понеділок, 18 лют" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Week) [ "цей тиждень" ] , examples (datetime (2013, 2, 4, 0, 0, 0) Week) [ "минулий тиждень" , "минулого тижня" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Week) [ "наступний тиждень" , "на наступному тижні" ] , examples (datetime (2013, 1, 0, 0, 0, 0) Month) [ "минулого місяця" ] , examples (datetime (2013, 3, 0, 0, 0, 0) Month) [ "наступного місяця" ] , examples (datetime (2013, 1, 1, 0, 0, 0) Quarter) [ "цей квартал" ] , examples (datetime (2013, 4, 1, 0, 0, 0) Quarter) [ "наступний квартал" ] , examples (datetime (2013, 7, 1, 0, 0, 0) Quarter) [ "третій квартал" ] , examples (datetime (2018, 10, 1, 0, 0, 0) Quarter) [ "четвертий квартал 2018" ] , examples (datetime (2012, 0, 0, 0, 0, 0) Year) [ "в минулому році" ] , examples (datetime (2013, 0, 0, 0, 0, 0) Year) [ "цей рік" ] , examples (datetime (2014, 0, 0, 0, 0, 0) Year) [ "наступний рік" , "в наступному році" ] , examples (datetime (2013, 2, 10, 0, 0, 0) Day) [ "минулої неділі" , "в минулу неділю" , "неділю на минулому тижні" ] , examples (datetime (2013, 2, 5, 0, 0, 0) Day) [ "в минулий вівторок" ] , examples (datetime (2013, 2, 19, 0, 0, 0) Day) [ "наступного вівторка" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "наступна середа" ] , examples (datetime (2013, 2, 20, 0, 0, 0) Day) [ "середа наступного тижня" , "середу після наступної" ] , examples (datetime (2013, 2, 22, 0, 0, 0) Day) [ "п'ятниця після наступного" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Day) [ "понеділок цього тижня" ] , examples (datetime (2013, 2, 12, 0, 0, 0) Day) [ "вівторок цього тижня" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "середа цього тижня" ] , examples (datetime (2013, 2, 14, 0, 0, 0) Day) [ "післязавтра" ] , examples (datetime (2013, 2, 10, 0, 0, 0) Day) [ "позавчора" ] , examples (datetime (2013, 3, 25, 0, 0, 0) Day) [ "останній понеділок у березні" ] , examples (datetime (2014, 3, 30, 0, 0, 0) Day) [ "останній неділю в березні 2014" ] , examples (datetime (2013, 10, 3, 0, 0, 0) Day) [ "третій день у жовтні" ] , examples (datetime (2014, 10, 6, 0, 0, 0) Week) [ "перший тиждень у жовтні 2014" ] , examples (datetime (2015, 10, 31, 0, 0, 0) Day) [ "останній день у жовтні 2015" ] , examples (datetime (2014, 9, 22, 0, 0, 0) Week) [ "останній тиждень вересня 2014" ] , examples (datetime (2013, 10, 1, 0, 0, 0) Day) [ "перший вівторок у жовтні" ] , examples (datetime (2014, 9, 16, 0, 0, 0) Day) [ "третій вівторок у вересні 2014" ] , examples (datetime (2014, 10, 1, 0, 0, 0) Day) [ "перша середа жовтня 2014" ] , examples (datetime (2014, 10, 8, 0, 0, 0) Day) [ "друга середа жовтня 2014" ] , examples (datetime (2015, 1, 13, 0, 0, 0) Day) [ "третій вівторок після католицького різдва 2014" ] , examples (datetime (2013, 2, 12, 4, 0, 0) Hour) [ "о 4 ранку" ] , examples (datetime (2013, 2, 12, 15, 0, 0) Hour) [ "о 3" , "3 години" , "о три" ] , examples (datetime (2013, 2, 12, 3, 18, 0) Minute) [ "3:18 ранку" ] , examples (datetime (2013, 2, 13, 3, 18, 0) Minute) [ "3:18" ] , examples (datetime (2013, 2, 12, 15, 0, 0) Hour) [ "о 3 годині дня" , "о 15" , "о 15 годині" , "15 години" , "о 15ч" ] , examples (datetime (2013, 4, 1, 18, 0, 0) Hour) [ "01.04. о 18 годині" ] , examples (datetime (2013, 2, 13, 17, 0, 0) Hour) [ "о 17 годині завтра" ] , examples (datetime (2013, 2, 12, 15, 15, 0) Minute) ["15:15" ] , examples (datetime (2013, 2, 12, 20, 0, 0) Hour) [ "8 години вечора" , "сьогодні о 8 вечора" ] , examples (datetime (2013, 2, 12, 20, 0, 0) Minute) [ "сьогодні о 20:00" ] , examples (datetime (2013, 9, 20, 19, 30, 0) Minute) [ "о 19:30 20 вер." ] , examples (datetime (2013, 2, 16, 9, 0, 0) Hour) [ "в суботу о 9 годині" ] , examples (datetime (2014, 7, 18, 19, 0, 0) Hour) [ "п'ятниця, 18 липня 2014 7 година вечора" ] , examples (datetime (2014, 7, 18, 0, 0, 0) Day) [ "Пт, 18 липня 2014" , "П'ятниця, 18.07.14" ] , examples (datetime (2013, 2, 12, 4, 30, 1) Second) [ "через 1 секунду" ] , examples (datetime (2013, 2, 12, 4, 31, 0) Second) [ "через 1 хвилину" ] , examples (datetime (2013, 2, 12, 4, 32, 0) Second) [ "через 2 хвилини" ] , examples (datetime (2013, 2, 12, 5, 30, 0) Second) [ "через 60 хвилин" ] , examples (datetime (2013, 2, 12, 5, 0, 0) Second) [ "через 30 хвилин" ] , examples (datetime (2013, 2, 12, 5, 30, 0) Minute) [ "через 1 годину" ] , examples (datetime (2013, 2, 12, 6, 30, 0) Minute) [ "через дві години" ] , examples (datetime (2013, 2, 13, 4, 30, 0) Minute) [ "через 24 години" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "завтра" ] , examples (datetime (2016, 2, 0, 0, 0, 0) Month) [ "через 3 роки" ] , examples (datetime (2013, 2, 19, 4, 0, 0) Hour) [ "через 7 днів" ] , examples (datetime (2013, 2, 19, 0, 0, 0) Day) [ "через 1 тиждень" ] , examples (datetime (2013, 2, 5, 4, 0, 0) Hour) [ "7 днів тому" ] , examples (datetime (2013, 1, 29, 4, 0, 0) Hour) [ "14 днів тому" ] , examples (datetime (2013, 1, 29, 0, 0, 0) Day) [ "два тижні тому" ] , examples (datetime (2013, 2, 5, 0, 0, 0) Day) [ "1 тиждень тому" ] , examples (datetime (2013, 1, 22, 0, 0, 0) Day) [ "три тижні тому" ] , examples (datetime (2012, 11, 12, 0, 0, 0) Day) [ "три місяці тому" ] , examples (datetime (2011, 2, 0, 0, 0, 0) Month) [ "два роки тому" ] , examples (datetime (2014, 1, 7, 0, 0, 0) Day) [ "1 рік після різдва" ] , examples (datetimeInterval ((2013, 6, 1, 0, 0, 0), (2013, 9, 1, 0, 0, 0)) Day) [ "це літо" ] , examples (datetimeInterval ((2013, 3, 1, 0, 0, 0), (2013, 6, 1, 0, 0, 0)) Day) [ "ця весна" ] , examples (datetimeInterval ((2012, 12, 1, 0, 0, 0), (2013, 3, 1, 0, 0, 0)) Day) [ "ця зима" ] , examples (datetimeHoliday (2014, 1, 7, 0, 0, 0) Day "Різдво Христове") [ "різдво" ] , examples (datetimeHoliday (2014, 1, 1, 0, 0, 0) Day "Новий рік") [ "Новий рік" ] , examples (datetimeInterval ((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour) [ "сьогодні ввечері" ] , examples (datetimeInterval ((2013, 2, 13, 18, 0, 0), (2013, 2, 14, 0, 0, 0)) Hour) [ "завтра ввечері" ] , examples (datetimeInterval ((2013, 2, 13, 12, 0, 0), (2013, 2, 13, 14, 0, 0)) Hour) [ "завтра в обід" ] , examples (datetimeInterval ((2013, 2, 11, 18, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour) [ "вчора ввечері" ] , examples (datetimeInterval ((2013, 2, 15, 18, 0, 0), (2013, 2, 18, 0, 0, 0)) Hour) [ "в ці вихідні" ] , examples (datetimeInterval ((2013, 2, 18, 3, 0, 0), (2013, 2, 18, 12, 0, 0)) Hour) [ "в понеділок вранці" ] , examples (datetimeInterval ((2013, 2, 15, 3, 0, 0), (2013, 2, 15, 12, 0, 0)) Hour) [ "вранці 15 лютого" ] , examples (datetimeInterval ((2013, 2, 12, 4, 29, 58), (2013, 2, 12, 4, 30, 0)) Second) [ "останні 2 секунди" , "останні дві секунди" ] , examples (datetimeInterval ((2013, 2, 12, 4, 30, 1), (2013, 2, 12, 4, 30, 4)) Second) [ "наступні 3 секунди" , "наступні три секунди" ] , examples (datetimeInterval ((2013, 2, 12, 4, 28, 0), (2013, 2, 12, 4, 30, 0)) Minute) [ "останні 2 хвилини" , "останні дві хвилини" ] , examples (datetimeInterval ((2013, 2, 12, 4, 31, 0), (2013, 2, 12, 4, 34, 0)) Minute) [ "наступні 3 хвилини" , "наступні три хвилини" ] , examples (datetimeInterval ((2013, 2, 12, 5, 0, 0), (2013, 2, 12, 8, 0, 0)) Hour) [ "наступні 3 години" , "наступні три години" ] , examples (datetimeInterval ((2013, 2, 10, 0, 0, 0), (2013, 2, 12, 0, 0, 0)) Day) [ "останні 2 дні" , "останні дві дні" ] , examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day) [ "наступні 3 дні" , "наступні три дня" ] , examples (datetimeInterval ((2013, 1, 28, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Week) [ "останні 2 тижні" , "останні два тижні" ] , examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 3, 11, 0, 0, 0)) Week) [ "наступні 3 тижні" , "наступні три тижні" ] , examples (datetimeInterval ((2012, 12, 0, 0, 0, 0), (2013, 2, 0, 0, 0, 0)) Month) [ "останні 2 місяці" , "останні два місяці" ] , examples (datetimeInterval ((2013, 3, 0, 0, 0, 0), (2013, 6, 0, 0, 0, 0)) Month) [ "наступні 3 місяці" , "наступні три місяці" ] , examples (datetimeInterval ((2011, 0, 0, 0, 0, 0), (2013, 0, 0, 0, 0, 0)) Year) [ "останні 2 роки" , "останні два роки" ] , examples (datetimeInterval ((2014, 0, 0, 0, 0, 0), (2017, 0, 0, 0, 0, 0)) Year) [ "наступні 3 роки" , "наступні три роки" ] , examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day) [ "13 - 15 липня" , "з 13 по 15 липня" , "13 липня - 15 липня" ] , examples (datetimeInterval ((2013, 8, 8, 0, 0, 0), (2013, 8, 13, 0, 0, 0)) Day) [ "8 сер - 12 сер" ] , examples (datetimeInterval ((2013, 2, 12, 9, 30, 0), (2013, 2, 12, 11, 1, 0)) Minute) [ "9:30 - 11:00" ] , examples (datetimeInterval ((2013, 2, 14, 9, 30, 0), (2013, 2, 14, 11, 1, 0)) Minute) [ "в четвер з 9:30 до 11:00" , "Четвер 9:30 - 11:00" , "четвер з 9:30 до 11:00" ] , examples (datetimeInterval ((2013, 2, 14, 9, 0, 0), (2013, 2, 14, 12, 0, 0)) Hour) [ "Четвер вранці з 9 до 11" ] , examples (datetimeInterval ((2013, 2, 12, 11, 30, 0), (2013, 2, 12, 13, 31, 0)) Minute) [ "11:30-13:30" ] , examples (datetime (2013, 9, 21, 1, 30, 0) Minute) [ "1:30 ночі сб, 21 вер." ] , examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 26, 0, 0, 0)) Second) [ "протягом 2 тижнів" ] , examples (datetimeOpenInterval Before (2013, 2, 12, 14, 0, 0) Hour) [ "до 2 годин дня" ] , examples (datetimeOpenInterval Before (2013, 2, 13, 0, 0, 0) Hour) [ "до кінця дня" ] , examples (datetimeOpenInterval Before (2013, 3, 1, 0, 0, 0) Month) [ "до кінця місяця" ] , examples (datetime (2013, 2, 12, 13, 0, 0) Minute) [ "16:00 CET" ] , examples (datetime (2013, 2, 14, 6, 0, 0) Minute) [ "четвер 8:00 GMT" , "четвер 8:00 gmt" ] , examples (datetime (2013, 2, 12, 14, 0, 0) Hour) [ "сьогодні о 14 годині" , "о 2" ] , examples (datetime (2013, 2, 13, 15, 0, 0) Hour) [ "завтра о 15 годині" ] , examples (datetimeOpenInterval After (2013, 2, 12, 14, 0, 0) Hour) [ "після 14 годин" , "після 14ч" , "після 2 годин" ] , examples (datetimeOpenInterval Before (2013, 2, 12, 11, 0, 0) Hour) [ "до 11 години" , "до 11 години ранку" ] , examples (datetimeInterval ((2013, 2, 12, 12, 0, 0), (2013, 2, 12, 19, 0, 0)) Hour) [ "сьогодні днем" ] , examples (datetime (2013, 2, 12, 13, 30, 0) Minute) [ "о 13:30 дня" , "13:30" ] , examples (datetime (2013, 2, 12, 4, 45, 0) Second) [ "через 15 хвилин" ] , examples (datetime (2013, 2, 12, 10, 30, 0) Minute) [ "10:30" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "наступного понеділка" ] , examples (datetime (2013, 12, 10, 0, 0, 0) Day) [ "10.12." ]   , examples (datetimeInterval ((2013, 2, 12, 18, 30, 0), (2013, 2, 12, 19, 1, 0)) Minute) [ "18:30ч - 19:00ч" , "18:30ч/19:00ч" ] , examples (datetimeInterval ((2013, 10, 14, 0, 0, 0), (2013, 10, 16, 0, 0, 0)) Day) [ "14. - 15.10." , "14 - 15.10." , "14. - 15.10" , "14.10. - 15.10." , "14. - 15.10.2013" , "14./15.10." ] , examples (datetimeInterval ((2018, 10, 14, 0, 0, 0), (2018, 10, 16, 0, 0, 0)) Day) [ "14. - 15.10.18" , "14 - 15.10.18" , "14./15.10.2018" , "з 14.10. - 15.10.2018" , "14.10. по 15.10.2018" , "з 14.10. по 15.10.2018" ] , examples (datetime (2013, 10, 10, 0, 0, 0) Day) ["10.10.2013" ] , examples (datetime (2013, 2, 12, 10, 10, 0) Minute) [ "о 10.10" ] , examples (datetime (2013, 2, 12, 17, 10, 0) Minute) [ "17ч10" ] ]
facebookincubator/duckling
Duckling/Time/UK/Corpus.hs
bsd-3-clause
20,404
2
11
7,430
6,464
3,921
2,543
366
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveTraversable #-} module Jade.Middle.SubModuleRed where -- import GHC.Generics -- import Data.Aeson -- import Control.Monad -- import Jade.Common -- import Text.Format -- import qualified Data.List as DL -- import qualified Data.Map as DM -- import qualified Data.Set as DS -- import qualified Data.Vector as V -- import qualified Jade.Decode as Decode -- import qualified Jade.Net as Net -- import qualified Jade.Module as Module -- import qualified Jade.MemUnit as MemUnit -- import qualified Jade.Val as Val -- import qualified Jade.TopLevel as TopLevel -- import qualified Jade.Bundle as Bundle -- data SubModuleRep = SubModuleRep { smrTermMapInput :: [TermMap] -- , smrTermMapOutput :: [TermMap] -- , smrSubModule :: SubModule -- , smrZIndex :: Int -- } deriving (Generic, ToJSON, Show, Eq) -- getWireWithName smr = "SubModuleRep.getWireWithName" <? do -- smrTermMapInput
drhodes/jade2hdl
src/Jade/Middle/SubModuleRep.hs
bsd-3-clause
1,134
0
3
283
34
32
2
5
0
-------------------------------------------------------------------------------- -- BitTicker - A program to periodically fetch and display Bitcoin stats. -- -- Copyright (C) 2013 Sam Fredrickson <kinghajj@gmail.com> -- -- -- -------------------------------------------------------------------------------- module Main where import System.IO ( hSetBuffering, BufferMode(..), stdout) import System.Console.CmdArgs ( cmdArgs) import BitTicker.Config ( Cfg(..), cmdCfg) import BitTicker.Text ( launchText) import BitTicker.UI ( launchUI) chooseLauncher :: Cfg -> IO () chooseLauncher cfg = (if gui cfg then launchUI else launchText) cfg main :: IO () main = hSetBuffering stdout NoBuffering >> cmdArgs cmdCfg >>= chooseLauncher
kinghajj/BitTicker
src/Main.hs
bsd-3-clause
874
0
8
231
147
86
61
10
2
-- | -- Copyright : (c) 2011 Duncan Coutts -- -- test-framework stub API -- -- Currently we cannot use the nice test-framework package for this testsuite -- since test-framework indirectly depends on bytestring and this makes cabal -- think we've got a circular dependency. -- -- On the other hand, it's very nice to have the testsuite run automatically -- rather than being a totally separate package (which would fix). -- -- So until we can fix that we implement our own trivial layer. -- module TestFramework where import Test.QuickCheck (Testable(..)) import Test.QuickCheck.Test import Text.Printf import System.Environment import Control.Monad import Control.Exception -- Ideally we'd be using: --import Test.Framework --import Test.Framework.Providers.QuickCheck2 type TestName = String type Test = [(TestName, Int -> IO (Bool, Int))] testGroup :: String -> [Test] -> Test testGroup _ = concat testProperty :: Testable a => String -> a -> Test testProperty name p = [(name, runQcTest)] where runQcTest n = do result <- quickCheckWithResult testArgs p case result of Success {} -> return (True, numTests result) _ -> return (False, numTests result) where testArgs = stdArgs { maxSuccess = n --chatty = ... if we want to increase verbosity } testCase :: String -> Bool -> Test testCase name tst = [(name, runPlainTest)] where runPlainTest _ = do r <- evaluate tst putStrLn "+++ OK, passed test." return (r, 1) defaultMain :: [Test] -> IO () defaultMain = runTests . concat runTests :: [(String, Int -> IO (Bool,Int))] -> IO () runTests tests = do x <- getArgs let n = if null x then 100 else read . head $ x (results, passed) <- liftM unzip $ mapM (\(s,a) -> printf "%-40s: " s >> a n) tests _ <- printf "Passed %d tests!\n" (sum passed) when (not . and $ results) $ fail "Not all tests passed!"
markflorisson/hpack
testrepo/bytestring-0.10.2.0/tests/TestFramework.hs
bsd-3-clause
1,991
0
14
494
511
278
233
35
2
module Logic.Link ( LinkType(..), Link,--(..), -- Do not expose type constructor for link; use constructor function constructLink, isLeftLink, isRightLink, numberOfTentacles, linkType, premises , conclusions, mainFormula, getAllPremises, getAllConclusions, isConclusionOfAnyLink, isPremiseOfAnyLink ) where import Logic.Node -- Links: Tensor or cotensor links that connect a number of formulae. -- -- Definition of Moortgat & Moot 2012, p5: -- -- A link is a tuple <t, p, c, m> where -- • t is the type of the link — tensor or cotensor -- • p is the list of premises of the link, -- • c is the list of conclusions of the link, -- • m, the main vertex/formula of the link, is either a member of p, a member -- of c or the constant “nil” -- -- NOTE: We could think of sets instead of lists for our premises and conclusions data LinkType = Tensor | CoTensor | NoLink deriving (Show, Eq) data LinkDirection = LeftLink | RightLink | DirectionLess deriving (Show, Eq) data Link a = Link { linkType :: LinkType, premises :: [Node a], conclusions :: [Node a], mainFormula :: Node a } deriving (Eq) instance (Show a) => Show (Link a) where show l = (show (premises l)) ++ "\n" ++ " "++ (showLinkType (linkType l))++ "\n" ++ (show (conclusions l)) where showLinkType lt = if lt == Tensor then "O" else if lt == CoTensor then "*" else "-" constructLink :: (Eq a) => LinkType -> [Node a] -> [Node a] -> (Node a) -> (Link a) constructLink linkType premises conclusions mainFormula = if (ld == LeftLink) || (ld == RightLink) || (linkDirection link == DirectionLess) -- trivial, but this performs an error check then link else error "Main formula must be an element of premises or an element of conclusions or nil" where link = Link linkType premises conclusions mainFormula ld = linkDirection link -- Returns whether formula has a main link assigned hasMainFormula :: (Eq a) => (Link a) -> Bool hasMainFormula link = if (mainFormula link) == NilNode then False else True -- Moortgat & Moot 2012, p5: "In case m[ainFormula] is a member of p[remises] we speak of a left link -- (corresponding to the left rules of the sequent calculus, where the main formula of the link occurs in the antecedent)" isLeftLink :: (Eq a) => (Link a) -> Bool isLeftLink link = (mainFormula link) `elem` (premises link) -- "...and in case m[ainFormula] is a member of c[onclusions] we speak of a right link." isRightLink :: (Eq a) => (Link a) -> Bool isRightLink link = (mainFormula link) `elem` (conclusions link) linkDirection :: (Eq a) => (Link a) -> LinkDirection linkDirection link = if not (hasMainFormula link) then DirectionLess else if isLeftLink link then LeftLink else if isRightLink link then RightLink else error "Link is neither a left link nor a right link: mainFormula must be a member of the premises, or the conclusions, or the node equivalent of nil" -- Moortgat & Moot 2012, p5: -- "when we need to refer to the connections between the central node and the vertices, we will call them its tentacles" numberOfTentacles :: (Link a) -> Int numberOfTentacles link = length (premises link) + length (conclusions link) --Some utility functions: getAllPremises :: [Link a] -> [Node a] getAllPremises [] = [] getAllPremises (link:links) = premises link ++ getAllPremises links getAllConclusions :: [Link a] -> [Node a] getAllConclusions [] = [] getAllConclusions (link:links) = conclusions link ++ getAllConclusions links isConclusionOfAnyLink :: (Eq a) => (Node a) -> [Link a] -> Bool isConclusionOfAnyLink formula [] = False isConclusionOfAnyLink formula (l:links) = if formula `elem` (conclusions l) then True else isConclusionOfAnyLink formula links isPremiseOfAnyLink :: (Eq a) => (Node a) -> [Link a] -> Bool isPremiseOfAnyLink formula [] = False isPremiseOfAnyLink formula (l:links) = if formula `elem` (premises l) then True else isPremiseOfAnyLink formula links
digitalheir/net-prove
src/Logic/Link.hs
bsd-3-clause
4,143
0
14
921
1,001
548
453
79
4
{-- --- Day 1: Not Quite Lisp --- Santa was hoping for a white Christmas, but his weather machine's "snow" function is powered by stars, and he's fresh out! To save Christmas, he needs you to collect fifty stars by December 25th. Collect stars by helping Santa solve puzzles. Two puzzles will be made available on each day in the advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! Here's an easy puzzle to warm you up. Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time. An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor. The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors. For example: (()) and ()() both result in floor 0. ((( and (()(()( both result in floor 3. ))((((( also results in floor 3. ()) and ))( both result in floor -1 (the first basement level). ))) and )())()) both result in floor -3. To what floor do the instructions take Santa? --- Part Two --- Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). The first character in the instructions has position 1, the second character has position 2, and so on. For example: ) causes him to enter the basement at character position 1. ()()) causes him to enter the basement at character position 5. What is the position of the character that causes Santa to first enter the basement? --} module Day1 ( answers ) where toNum :: Char -> Int toNum '(' = 1 toNum ')' = -1 toNum _ = 0 part1, part2 :: String -> Int part1 chars = sum $ map toNum chars part2 chars = findIndex chars 0 0 where findIndex _ index (-1) = index findIndex (x:xs) index acc = findIndex xs (index + 1) (acc + toNum x) answers :: String -> IO () answers chars = do putStrLn $ "day 1 part 1 = " ++ show (part1 chars) putStrLn $ "day 1 part 2 = " ++ show (part2 chars)
hlmerscher/advent-of-code-2015
src/Day1.hs
bsd-3-clause
2,269
0
10
515
212
108
104
15
2
{-# LANGUAGE OverloadedStrings #-} module Sensit where import Network.Wreq import Control.Lens import Data.Map as Map import Data.Aeson (Value) import Data.Aeson.Lens (key) type Resp = Response (Map String Value)
julienXX/sensit-haskell
src/Sensit.hs
bsd-3-clause
216
0
7
31
60
37
23
8
0
module Dalvik.Types where import qualified Data.ByteString as BS import qualified Data.Map as Map import Data.Int import Data.Map (Map) import Data.Word import Dalvik.AccessFlags data DexHeader = DexHeader { dexMagic :: BS.ByteString , dexVersion :: BS.ByteString , dexChecksum :: Word32 , dexSHA1 :: [Word8] , dexFileLen :: Word32 , dexHdrLen :: Word32 , dexLinkSize :: Word32 , dexLinkOff :: Word32 , dexMapOff :: Word32 , dexNumStrings :: Word32 , dexOffStrings :: Word32 , dexNumTypes :: Word32 , dexOffTypes :: Word32 , dexNumProtos :: Word32 , dexOffProtos :: Word32 , dexNumFields :: Word32 , dexOffFields :: Word32 , dexNumMethods :: Word32 , dexOffMethods :: Word32 , dexNumClassDefs :: Word32 , dexOffClassDefs :: Word32 , dexDataSize :: Word32 , dexDataOff :: Word32 } deriving (Show) type ProtoId = Word16 type ParamListId = Word32 type FieldId = Word16 type MethodId = Word16 type StringId = Word32 type StringIdJumbo = Word32 type TypeId = Word16 type Word4 = Word8 type Reg4 = Word4 type Reg8 = Word8 type Reg16 = Word16 data MapItem = MapItem { itemType :: Word16 , itemSize :: Word32 , itemOff :: Word32 } deriving (Show) data Field = Field { fieldClassId :: TypeId , fieldTypeId :: TypeId , fieldNameId :: StringId } deriving (Show) data EncodedField = EncodedField { fieldId :: FieldId , fieldAccessFlags :: AccessFlags } deriving (Show) data Proto = Proto { protoShortDesc :: StringId , protoRet :: TypeId , protoParams :: [TypeId] } deriving (Show) data Method = Method { methClassId :: TypeId , methProtoId :: ProtoId , methNameId :: StringId } deriving (Show) data EncodedMethod = EncodedMethod { methId :: MethodId , methAccessFlags :: AccessFlags , methCode :: Maybe CodeItem } deriving (Show) data Class = Class { classId :: TypeId , classAccessFlags :: AccessFlags , classSuperId :: TypeId , classInterfacesOff :: Word32 , classInterfaces :: [TypeId] , classSourceNameId :: StringId , classAnnotsOff :: Word32 , classStaticFields :: [EncodedField] , classInstanceFields :: [EncodedField] , classDirectMethods :: [EncodedMethod] , classVirtualMethods :: [EncodedMethod] , classDataOff :: Word32 , classStaticValuesOff :: Word32 } deriving (Show) data TryItem = TryItem { tryStartAddr :: Word32 , tryInsnCount :: Word16 , tryHandlerOff :: Word16 } deriving (Show) data CatchHandler = CatchHandler { chHandlerOff :: Word32 , chHandlers :: [(TypeId, Word32)] , chAllAddr :: Maybe Word32 } deriving (Show) data CodeItem = CodeItem { codeRegs :: Word16 , codeInSize :: Word16 , codeOutSize :: Word16 , codeDebugInfo :: Maybe DebugInfo , codeInsnOff :: Word32 , codeInsns :: [Word16] , codeTryItems :: [TryItem] , codeHandlers :: [CatchHandler] } deriving (Show) data DexFile = DexFile { dexHeader :: DexHeader , dexMap :: Map Word32 MapItem , dexStrings :: Map StringId BS.ByteString , dexTypeNames :: Map TypeId StringId , dexProtos :: Map ProtoId Proto , dexFields :: Map FieldId Field , dexMethods :: Map MethodId Method , dexClasses :: Map TypeId Class , dexThisId :: StringId } deriving (Show) data DebugByteCode = DBG_END_SEQUENCE | DBG_ADVANCE_PC | DBG_ADVANCE_LINE | DBG_START_LOCAL | DBG_START_LOCAL_EXTENDED | DBG_END_LOCAL | DBG_RESTART_LOCAL | DBG_SET_PROLOGUE_END | DBG_SET_EPILOGUE_BEGIN | DBG_SET_FILE | DBG_FIRST_SPECIAL deriving (Eq, Enum) data DebugInstruction = EndSequence | AdvancePC Word32 | AdvanceLine Int32 | StartLocal Word32 Int32 Int32 --(Maybe Word32) (Maybe Word32) | StartLocalExt Word32 Int32 Int32 Int32 --(Maybe Word32) (Maybe Word32) (Maybe Word32) | EndLocal Word32 | RestartLocal Word32 | SetPrologueEnd | SetEpilogueBegin | SetFile Int32 --(Maybe Word32) | SpecialAdjust Word8 deriving (Show) data DebugInfo = DebugInfo { dbgLineStart :: Word32 , dbgParamNames :: [Int32] , dbgByteCodes :: [DebugInstruction] } deriving (Show) data DebugState = DebugState { dbgAddr :: Word32 , dbgLine :: Word32 , dbgSourceFile :: Int32 , dbgPrologueEnd :: Bool , dbgEpilogueBegin :: Bool , dbgLocals :: Map Word32 [LocalInfo] , dbgPositions :: [PositionInfo] , dbgSeqNo :: Word32 } deriving (Show) data PositionInfo = PositionInfo { pAddr :: Word32 , pLine :: Word32 } deriving (Show) data LocalInfo = LocalInfo { lSeqNo :: Word32 , lStartAddr :: Word32 , lEndAddr :: Word32 , lNameID :: Int32 , lTypeID :: Int32 , lTypeSig :: Int32 } deriving (Eq, Ord, Show) {- Utility functions -} getStr :: DexFile -> StringId -> Maybe BS.ByteString getStr dex i = Map.lookup i (dexStrings dex) getTypeName :: DexFile -> TypeId -> Maybe BS.ByteString getTypeName dex i = getStr dex =<< Map.lookup i (dexTypeNames dex) getField :: DexFile -> FieldId -> Maybe Field getField dex i = Map.lookup i (dexFields dex) getMethod :: DexFile -> MethodId -> Maybe Method getMethod dex i = Map.lookup i (dexMethods dex) getProto :: DexFile -> ProtoId -> Maybe Proto getProto dex i = Map.lookup i (dexProtos dex) getClass :: DexFile -> TypeId -> Maybe Class getClass dex i = Map.lookup i (dexClasses dex) findString :: DexFile -> BS.ByteString -> Maybe StringId findString dex t = case filter isThis (Map.toList (dexStrings dex)) of [(sid, _)] -> Just sid _ -> Nothing where isThis (_, t') = t == t'
atomb/dalvik
Dalvik/Types.hs
bsd-3-clause
5,872
0
10
1,551
1,515
902
613
206
2
module Main where import Lib main :: IO () main = defMain
thulishuang/Compiler
app/Main.hs
bsd-3-clause
60
0
6
14
22
13
9
4
1
{-# LANGUAGE DeriveDataTypeable #-} module Parser.AST where import Control.Lens (Plated) import Data.Data data AST = IntLit Integer | DoubleLit Double | AST :+ AST | AST :- AST | AST :* AST | AST :/ AST | AST :^ AST deriving (Eq, Ord, Read, Show, Data, Typeable) instance Plated AST data BinaryOp = Add | Subtract | Multiply | Divide deriving (Eq, Ord, Read, Show) data UnaryOp = Negate | Sqrt deriving (Eq, Ord, Read, Show)
lightquake/sym
src/Parser/AST.hs
bsd-3-clause
487
0
6
138
169
95
74
18
0
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE Rank2Types #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Database.Persist.Sql.Orphan.PersistStore ( withRawQuery , BackendKey(..) , toSqlKey , fromSqlKey , getFieldName , getTableName , tableDBName , fieldDBName ) where import Database.Persist import Database.Persist.Sql.Types import Database.Persist.Sql.Raw import Database.Persist.Sql.Util ( dbIdColumns, keyAndEntityColumnNames, parseEntityValues, entityColumnNames , updatePersistValue, mkUpdateText, commaSeparated) import Data.Conduit (ConduitM, (=$=), (.|), runConduit) import qualified Data.Conduit.List as CL import qualified Data.Text as T import Data.Text (Text, unpack) import Data.Monoid (mappend, (<>)) import Control.Monad.IO.Class import Data.ByteString.Char8 (readInteger) import Data.Maybe (isJust) import Data.List (find) import Data.Void (Void) import Control.Monad.Trans.Reader (ReaderT, ask, withReaderT) import Data.Acquire (with) import Data.Int (Int64) import Web.PathPieces (PathPiece) import Web.HttpApiData (ToHttpApiData, FromHttpApiData) import Database.Persist.Sql.Class (PersistFieldSql) import qualified Data.Aeson as A import Control.Exception (throwIO) import Database.Persist.Class () import qualified Data.Map as Map import qualified Data.Foldable as Foldable withRawQuery :: MonadIO m => Text -> [PersistValue] -> ConduitM [PersistValue] Void IO a -> ReaderT SqlBackend m a withRawQuery sql vals sink = do srcRes <- rawQueryRes sql vals liftIO $ with srcRes (\src -> runConduit $ src .| sink) toSqlKey :: ToBackendKey SqlBackend record => Int64 -> Key record toSqlKey = fromBackendKey . SqlBackendKey fromSqlKey :: ToBackendKey SqlBackend record => Key record -> Int64 fromSqlKey = unSqlBackendKey . toBackendKey whereStmtForKey :: PersistEntity record => SqlBackend -> Key record -> Text whereStmtForKey conn k = T.intercalate " AND " $ map (<> "=? ") $ dbIdColumns conn entDef where entDef = entityDef $ dummyFromKey k whereStmtForKeys :: PersistEntity record => SqlBackend -> [Key record] -> Text whereStmtForKeys conn ks = T.intercalate " OR " $ whereStmtForKey conn `fmap` ks -- | get the SQL string for the table that a PeristEntity represents -- Useful for raw SQL queries -- -- Your backend may provide a more convenient tableName function -- which does not operate in a Monad getTableName :: forall record m backend. ( PersistEntity record , PersistEntityBackend record ~ SqlBackend , IsSqlBackend backend , Monad m ) => record -> ReaderT backend m Text getTableName rec = withReaderT persistBackend $ do conn <- ask return $ connEscapeName conn $ tableDBName rec -- | useful for a backend to implement tableName by adding escaping tableDBName :: (PersistEntity record) => record -> DBName tableDBName rec = entityDB $ entityDef (Just rec) -- | get the SQL string for the field that an EntityField represents -- Useful for raw SQL queries -- -- Your backend may provide a more convenient fieldName function -- which does not operate in a Monad getFieldName :: forall record typ m backend. ( PersistEntity record , PersistEntityBackend record ~ SqlBackend , IsSqlBackend backend , Monad m ) => EntityField record typ -> ReaderT backend m Text getFieldName rec = withReaderT persistBackend $ do conn <- ask return $ connEscapeName conn $ fieldDBName rec -- | useful for a backend to implement fieldName by adding escaping fieldDBName :: forall record typ. (PersistEntity record) => EntityField record typ -> DBName fieldDBName = fieldDB . persistFieldDef instance PersistCore SqlBackend where newtype BackendKey SqlBackend = SqlBackendKey { unSqlBackendKey :: Int64 } deriving (Show, Read, Eq, Ord, Num, Integral, PersistField, PersistFieldSql, PathPiece, ToHttpApiData, FromHttpApiData, Real, Enum, Bounded, A.ToJSON, A.FromJSON) instance PersistCore SqlReadBackend where newtype BackendKey SqlReadBackend = SqlReadBackendKey { unSqlReadBackendKey :: Int64 } deriving (Show, Read, Eq, Ord, Num, Integral, PersistField, PersistFieldSql, PathPiece, ToHttpApiData, FromHttpApiData, Real, Enum, Bounded, A.ToJSON, A.FromJSON) instance PersistCore SqlWriteBackend where newtype BackendKey SqlWriteBackend = SqlWriteBackendKey { unSqlWriteBackendKey :: Int64 } deriving (Show, Read, Eq, Ord, Num, Integral, PersistField, PersistFieldSql, PathPiece, ToHttpApiData, FromHttpApiData, Real, Enum, Bounded, A.ToJSON, A.FromJSON) instance BackendCompatible SqlBackend SqlBackend where projectBackend = id instance BackendCompatible SqlBackend SqlReadBackend where projectBackend = unSqlReadBackend instance BackendCompatible SqlBackend SqlWriteBackend where projectBackend = unSqlWriteBackend instance PersistStoreWrite SqlBackend where update _ [] = return () update k upds = do conn <- ask let wher = whereStmtForKey conn k let sql = T.concat [ "UPDATE " , connEscapeName conn $ tableDBName $ recordTypeFromKey k , " SET " , T.intercalate "," $ map (mkUpdateText conn) upds , " WHERE " , wher ] rawExecute sql $ map updatePersistValue upds `mappend` keyToValues k insert val = do conn <- ask let esql = connInsertSql conn t vals key <- case esql of ISRSingle sql -> withRawQuery sql vals $ do x <- CL.head case x of Just [PersistInt64 i] -> case keyFromValues [PersistInt64 i] of Left err -> error $ "SQL insert: keyFromValues: PersistInt64 " `mappend` show i `mappend` " " `mappend` unpack err Right k -> return k Nothing -> error $ "SQL insert did not return a result giving the generated ID" Just vals' -> case keyFromValues vals' of Left e -> error $ "Invalid result from a SQL insert, got: " ++ show vals' ++ ". Error was: " ++ unpack e Right k -> return k ISRInsertGet sql1 sql2 -> do rawExecute sql1 vals withRawQuery sql2 [] $ do mm <- CL.head let m = maybe (Left $ "No results from ISRInsertGet: " `mappend` tshow (sql1, sql2)) Right mm -- TODO: figure out something better for MySQL let convert x = case x of [PersistByteString i] -> case readInteger i of -- mssql Just (ret,"") -> [PersistInt64 $ fromIntegral ret] _ -> x _ -> x -- Yes, it's just <|>. Older bases don't have the -- instance for Either. onLeft Left{} x = x onLeft x _ = x case m >>= (\x -> keyFromValues x `onLeft` keyFromValues (convert x)) of Right k -> return k Left err -> throw $ "ISRInsertGet: keyFromValues failed: " `mappend` err ISRManyKeys sql fs -> do rawExecute sql vals case entityPrimary t of Nothing -> error $ "ISRManyKeys is used when Primary is defined " ++ show sql Just pdef -> let pks = map fieldHaskell $ compositeFields pdef keyvals = map snd $ filter (\(a, _) -> let ret=isJust (find (== a) pks) in ret) $ zip (map fieldHaskell $ entityFields t) fs in case keyFromValues keyvals of Right k -> return k Left e -> error $ "ISRManyKeys: unexpected keyvals result: " `mappend` unpack e return key where tshow :: Show a => a -> Text tshow = T.pack . show throw = liftIO . throwIO . userError . T.unpack t = entityDef $ Just val vals = map toPersistValue $ toPersistFields val insertMany [] = return [] insertMany vals = do conn <- ask case connInsertManySql conn of Nothing -> mapM insert vals Just insertManyFn -> do case insertManyFn ent valss of ISRSingle sql -> rawSql sql (concat valss) _ -> error "ISRSingle is expected from the connInsertManySql function" where ent = entityDef vals valss = map (map toPersistValue . toPersistFields) vals insertMany_ vals0 = runChunked (length $ entityFields t) insertMany_' vals0 where t = entityDef vals0 insertMany_' vals = do conn <- ask let valss = map (map toPersistValue . toPersistFields) vals let sql = T.concat [ "INSERT INTO " , connEscapeName conn (entityDB t) , "(" , T.intercalate "," $ map (connEscapeName conn . fieldDB) $ entityFields t , ") VALUES (" , T.intercalate "),(" $ replicate (length valss) $ T.intercalate "," $ map (const "?") (entityFields t) , ")" ] rawExecute sql (concat valss) replace k val = do conn <- ask let t = entityDef $ Just val let wher = whereStmtForKey conn k let sql = T.concat [ "UPDATE " , connEscapeName conn (entityDB t) , " SET " , T.intercalate "," (map (go conn . fieldDB) $ entityFields t) , " WHERE " , wher ] vals = map toPersistValue (toPersistFields val) `mappend` keyToValues k rawExecute sql vals where go conn x = connEscapeName conn x `T.append` "=?" insertKey k v = insrepHelper "INSERT" [Entity k v] insertEntityMany es' = do conn <- ask let entDef = entityDef $ map entityVal es' let columnNames = keyAndEntityColumnNames entDef conn runChunked (length columnNames) go es' where go es = insrepHelper "INSERT" es repsert key value = do mExisting <- get key case mExisting of Nothing -> insertKey key value Just _ -> replace key value repsertMany krs = do let es = (uncurry Entity) `fmap` krs let ks = entityKey `fmap` es let mEs = Map.fromList $ zip ks es mRsExisting <- getMany ks let mEsNew = Map.difference mEs mRsExisting let esNew = snd `fmap` Map.toList mEsNew insertEntityMany esNew delete k = do conn <- ask rawExecute (sql conn) (keyToValues k) where wher conn = whereStmtForKey conn k sql conn = T.concat [ "DELETE FROM " , connEscapeName conn $ tableDBName $ recordTypeFromKey k , " WHERE " , wher conn ] instance PersistStoreWrite SqlWriteBackend where insert v = withReaderT persistBackend $ insert v insertMany vs = withReaderT persistBackend $ insertMany vs insertMany_ vs = withReaderT persistBackend $ insertMany_ vs insertEntityMany vs = withReaderT persistBackend $ insertEntityMany vs insertKey k v = withReaderT persistBackend $ insertKey k v repsert k v = withReaderT persistBackend $ repsert k v replace k v = withReaderT persistBackend $ replace k v delete k = withReaderT persistBackend $ delete k update k upds = withReaderT persistBackend $ update k upds repsertMany krs = withReaderT persistBackend $ repsertMany krs instance PersistStoreRead SqlBackend where get k = do mEs <- getMany [k] return $ Map.lookup k mEs -- inspired by Database.Persist.Sql.Orphan.PersistQuery.selectSourceRes getMany [] = return Map.empty getMany ks@(k:_)= do conn <- ask let t = entityDef . dummyFromKey $ k let cols = commaSeparated . entityColumnNames t let wher = whereStmtForKeys conn ks let sql = T.concat [ "SELECT " , cols conn , " FROM " , connEscapeName conn $ entityDB t , " WHERE " , wher ] let parse vals = case parseEntityValues t vals of Left s -> liftIO $ throwIO $ PersistMarshalError s Right row -> return row withRawQuery sql (Foldable.foldMap keyToValues ks) $ do es <- CL.mapM parse =$= CL.consume return $ Map.fromList $ fmap (\e -> (entityKey e, entityVal e)) es instance PersistStoreRead SqlReadBackend where get k = withReaderT persistBackend $ get k getMany ks = withReaderT persistBackend $ getMany ks instance PersistStoreRead SqlWriteBackend where get k = withReaderT persistBackend $ get k getMany ks = withReaderT persistBackend $ getMany ks dummyFromKey :: Key record -> Maybe record dummyFromKey = Just . recordTypeFromKey recordTypeFromKey :: Key record -> record recordTypeFromKey _ = error "dummyFromKey" insrepHelper :: (MonadIO m, PersistEntity val) => Text -> [Entity val] -> ReaderT SqlBackend m () insrepHelper _ [] = return () insrepHelper command es = do conn <- ask let columnNames = keyAndEntityColumnNames entDef conn rawExecute (sql conn columnNames) vals where entDef = entityDef $ map entityVal es sql conn columnNames = T.concat [ command , " INTO " , connEscapeName conn (entityDB entDef) , "(" , T.intercalate "," columnNames , ") VALUES (" , T.intercalate "),(" $ replicate (length es) $ T.intercalate "," $ map (const "?") columnNames , ")" ] vals = Foldable.foldMap entityValues es runChunked :: (Monad m) => Int -> ([a] -> ReaderT SqlBackend m ()) -> [a] -> ReaderT SqlBackend m () runChunked _ _ [] = return () runChunked width m xs = do conn <- ask case connMaxParams conn of Nothing -> m xs Just maxParams -> let chunkSize = maxParams `div` width in mapM_ m (chunksOf chunkSize xs) -- Implement this here to avoid depending on the split package chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf size xs = let (chunk, rest) = splitAt size xs in chunk : chunksOf size rest
plow-technologies/persistent
persistent/Database/Persist/Sql/Orphan/PersistStore.hs
mit
15,385
60
37
5,023
2,918
1,646
1,272
316
2
{-# LANGUAGE QuasiQuotes #-} module Examples.First where import HarmLang.Interpreter import HarmLang.Types import HarmLang.InitialBasis import HarmLang.QuasiQuoter import HarmLang.Expression import HarmLang.Probability import HarmLang.HarmonyDistributionModel import HarmLang.Priors import Test.HUnit hiding (test) test = runTestTT tests tests = TestList [ TestLabel "Note test" testNote, TestLabel "TimedChord test" testTimedChord, TestLabel "TimedChord Progression test" testTimedChordProgression, TestLabel "Chord test" testChord, TestLabel "Transpose Chord test" testTransposeChord, TestLabel "Quasi quoting: Pitch Class" testQuasiQuotingPitchClass, TestLabel "Quasi quoting: Pitch" testQuasiQuotingPitch, TestLabel "Quasi quoting: Timed Chord" testQuasiQuotingTimedChord, TestLabel "Quasi quoting: Note" testQuasiQuotingNote, TestLabel "Quasi quoting: Chord" testQuasiQuotingChord, TestLabel "Quasi quoting: Note Progression" testQuasiQuotingNoteProgression, TestLabel "Quasi quoting: Timed Chord Progression" testQuasiQuotingTimedChordProgression, TestLabel "Quasi quoting: Interval" testQuasiQuotingInterval, TestLabel "Quasi quoting: Whitespace 1" testQuasiQuotingInterval, TestLabel "Quasi quoting: Whitespace 2" testQuasiQuotingInterval, TestLabel "Show: Test 1" testShow1, TestLabel "Show: Test 2" testShow2, TestLabel "Show: Test 3" testShow3, TestLabel "Test Chord Enum 1" testChordEnum1, TestLabel "Test Chord Enum 2" testChordEnum2, TestLabel "Test Chord Enum 3" testChordEnum3, TestLabel "Test Chord Enum 4" testChordEnum4, TestLabel "HarmonyDistributionModel Tests" testHarmonyDistributionModel, TestLabel "Test Inference" testInference, TestLabel "Key Agnosticism" testKeyAgnosticism, TestLabel "Laplacian Prior" testLaplacianPrior ] -- parse tests testNote = let got = interpretNote "A@5:4" should = Note (Pitch (PitchClass 0) (Octave 5)) (Time 4 4) in TestCase $ assertEqual "Note test" should got testChord = let got = interpretChord "C#[G# B]" should = Harmony (PitchClass 4) [Interval 7,Interval 10] in TestCase $ assertEqual "Chord test" should got testTimedChord = let got = interpretTimedChord("Am7:4/3") should = TimedChord (Harmony (PitchClass 0) [Interval 3,Interval 7,Interval 10]) (Time 4 3) in TestCase $ assertEqual "TimedChord test" should got testTimedChordProgression = let got = interpretTimedChordProgression "[FMa7:4 F#o7:4/2]" should = [TimedChord (Harmony (PitchClass 8) [Interval 4,Interval 7,Interval 11]) (Time 4 4),TimedChord (Harmony (PitchClass 9) [Interval 3,Interval 6,Interval 9]) (Time 4 2)] in TestCase $ assertEqual "TimedChord Progression test" should got -- transposeChord testTransposeChord = let got = transpose (interpretChord "C#[G# B]") (Interval 7) should = Harmony (PitchClass 11) [Interval 7,Interval 10] in TestCase $ assertEqual "Chord test" should got -- Quasiquoting on pitchclasses testQuasiQuotingPitchClass = let got = [[hl|'A'|], [hl|'Ab'|]] should = [PitchClass 0, PitchClass 11] in TestCase $ assertEqual "Quasi quoting PitchClass test" should got -- Quasiquoting on pitches testQuasiQuotingPitch = let got = [[hl|'A@5'|], [hl|'C#@6'|]] should = [Pitch (PitchClass 0) (Octave 5), Pitch (PitchClass 4) (Octave 6)] in TestCase $ assertEqual "Quasi quoting Pitch test" should got -- Quasiquoting on timed chords testQuasiQuotingTimedChord = let got = [[hl|'AM:4'|], [hl|'C#m7b5:7'|]] should = [TimedChord (Harmony (PitchClass 0) [(Interval 4), (Interval 7)]) (Time 4 4), TimedChord (Harmony (PitchClass 4) [(Interval 3), (Interval 6), (Interval 10)]) (Time 7 4)] in TestCase $ assertEqual "Quasi quoting TimedChord test" should got -- Quasiquoting on notes testQuasiQuotingNote = let got = [[hl|'B@5:3'|], [hl|'D@6:3/2'|]] should = [Note (Pitch (PitchClass 2) (Octave 5)) (Time 3 4), Note (Pitch (PitchClass 5) (Octave 6)) (Time 3 2)] in TestCase $ assertEqual "Quasi quoting TimedChord test" should got -- Quasiquoting on chords testQuasiQuotingChord = let got = [[hl|'AM'|], [hl|'C#m7b5'|]] should = [Harmony (PitchClass 0) [(Interval 4), (Interval 7)], Harmony (PitchClass 4) [(Interval 3), (Interval 6), (Interval 10)]] in TestCase $ assertEqual "Quasi quoting Chord test" should got -- testQuasiQuotingNoteProgression = let got = [hl|[B@5:3 D@6:3/2]|] should = [Note (Pitch (PitchClass 2) (Octave 5)) (Time 3 4), Note (Pitch (PitchClass 5) (Octave 6)) (Time 3 2)] in TestCase $ assertEqual "Quasi quoting NoteProgression test" should got -- testQuasiQuotingTimedChordProgression = let got = [hl|[FMa7:4 F#o7:4/2]|] should = [TimedChord (Harmony (PitchClass 8) [Interval 4,Interval 7,Interval 11]) (Time 4 4),TimedChord (Harmony (PitchClass 9) [Interval 3,Interval 6,Interval 9]) (Time 4 2)] in TestCase $ assertEqual "Quasi quoting TimedChord Progression test" should got -- Quasiquoting on intervals testQuasiQuotingInterval = let got = [[hl|'4'|], [hl|'8'|]] should = [Interval 4, Interval 8] in TestCase $ assertEqual "Quasi quoting Interval test" should got -- Quasiquoting with whitespace testQuasiQuotingWhitespace1 = let got = [hl| 'A' |] should = PitchClass 0 in TestCase $ assertEqual "QuasiQuoting Whitespace" should got testQuasiQuotingWhitespace2 = let got = [hl| [A@7:4] |] should = [Note (Pitch (PitchClass 0) (Octave 4)) (Time 7 4)] in TestCase $ assertEqual "QuasiQuoting Whitespace 2" should got -- Test show -- Test show testShow1 = let original = [hl|'C#'|] reparsed = interpretPitchClass (show original) in TestCase $ assertEqual "Show identity 1" original reparsed testShow2 = let original = [hl| [C#m7:4/4 REST:4/4] |] reparsed = interpretTimedChordProgression (show original) in TestCase $ assertEqual "Show identity 2" original reparsed testShow3 = let original = [hl| [A@4:2/4 B@4:1/4 C@4:1/4] |] reparsed = interpretNoteProgression (show original) in TestCase $ assertEqual "Show identity 2" original reparsed --Test chord enum testChordEnum1 = let original = map Interval [1..11] new = (toEnum . fromEnum) original in TestCase $ assertEqual "Test Chord Enum 1" original new testChordEnum2 = let original = Harmony (PitchClass 0) (map Interval [1..11]) new = (toEnum . fromEnum) original in TestCase $ assertEqual "Test Chord Enum 2" original new testChordEnum3 = TestCase $ assertEqual "Test Chord Enum 3" (length allChordTypes) numChordTypes testChordEnum4 = TestCase $ assertEqual "Test Chord Enum 4" (length allChords) numChords --HDM testHarmonyDistributionModel = let k = 2 hdm = buildHarmonyDistributionModel k [[hl|[Dm GM CM Dm GM CM]|], [hl|[Dm GM FM]|], [hl|[Dm GM E7]|]] got = [probv (distAfter hdm [hl|[Dm GM]|]) [hl|'CM'|], probv (distAfter hdm [hl|[Dm GM]|]) [hl|'FM'|], probv (distAfter hdm [hl|[Dm GM]|]) [hl|'CM7'|]] should = [0.5, 0.25, 0] in TestCase $ assertEqual "Harmony Distribution Model" should got --Inference problem testInference = let k = 3 hdm1 = buildHarmonyDistributionModel k [[hl|[FM7 CM EM Am7 Dm7 G7 CM7]|], [hl|[FM7 CM EM Am7 D7 D#o7 CM7]|], [hl|[EbM7 Dm7 G7 A7]|]] hdm2 = buildHarmonyDistributionModel k [[hl|[FM7 CM EM Am7 Dm7 G7 CM7]|], [hl|[E7 FMa7 F#o7 Gm7 C7 Am7 Dm7 Gm7 C7]|], [hl|[E7 FMa7 F#o7 Gm7 C7 Am7 Dm7 Cm7 F7]|], [hl|[F7 BbMa7 Abm7 Db7 GbMa7 Em7 A7 DMa7 Abm7 Db7 GbMa7 Gm7 C7]|], [hl|[E7 FMa7 F#o7 Gm7 C7 Bb7 Am7 D7 Gm7 C7 FMa7 Gm7 C7]|]] prog = [hl|[CM EM Am7 Dm7 G7 CM7]|] -- prog = [hl|[CM EM Am7 Dm7]|] got = inferStyle [hdm1, hdm2] prog should = [0.5, 1] in TestCase $ assertEqual "Inference test" should got --Key Agnosticism testKeyAgnosticism = let k = 2 hdm = buildHarmonyDistributionModel k [[hl| [AM BM CM] |], [hl| [A#M B#M C#M] |], [hl| [BM C#M Dm] |]] query = [hl| [BM C#M] |] probs = [([hl| 'DM' |], 2.0 / 3.0), ([hl| 'Dm' |], 1.0 / 3.0) ] dist = distAfter hdm query in TestCase $ assertEqual "Key agnosticism" True (all (\ (val, theProb) -> (==) theProb (probv dist val)) probs)--TODO probably a better way than assertEqual {- --Intractable. testLaplacianPrior = let k = 2 hdm = buildHarmonyDistributionModelWithPrior k laplacianPrior 1.0 [[hl| [AM BM CM] |], [hl| [AM BM Cm] |]] query = [hl| [AM BM] |] dist = distAfter hdm query should = (0.5 + (1.0 / (fromIntegral numChords))) / 2.0 got = probv dist [hl| 'CM' |] in TestCase $ assertEqual ("Laplacian Prior Test: should = " ++ (show should) ++ ", got = " ++ (show got)) should got -} testLaplacianPrior = let k = 2 prior = chordLimitedLaplacianPrior [map Interval [4, 7]] hdm = buildHarmonyDistributionModelWithPrior k prior 2.0 [[hl| [AM BM CM] |], [hl| [AM BM Cm] |]] queries = [ [hl| [AM BM] |], [hl| [Bbm7b5 EmMa7] |] ] dists = map (distAfter hdm) queries should = [(0.5 + (1.0 / 12.0)) / 2.0, 1.0 / 12.0] got = map (\dist -> probv dist [hl| 'CM' |]) dists in TestCase $ assertEqual ("Laplacian Prior Test: should = " ++ (show should) ++ ", got = " ++ (show got)) should got
lrassaby/harmlang
examples/first.hs
mit
9,787
0
15
2,323
2,592
1,438
1,154
151
1
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : $Header$ Description : Signatures for DL logics, as extension of CASL signatures Copyright : (c) Klaus Luettich, Uni Bremen 2004 License : GPLv2 or higher, see LICENSE.txt Maintainer : luecke@informatik.uni-bremen.de Stability : provisional Portability : portable Signatures for DL logics, as extension of CASL signatures. -} module CASL_DL.Sign where import Data.Data import qualified Data.Map as Map import Common.Id import Common.Doc import Common.DocUtils import CASL.AS_Basic_CASL import CASL_DL.AS_CASL_DL import CASL_DL.Print_AS () import Data.List (union, (\\), isPrefixOf) import Control.Exception data CASL_DLSign = CASL_DLSign { annoProperties :: Map.Map SIMPLE_ID PropertyType , annoPropertySens :: [AnnoAppl] } deriving (Show, Eq, Ord, Typeable, Data) data PropertyType = AnnoProperty | OntoProperty deriving (Show, Eq, Ord, Typeable, Data) data AnnoAppl = AnnoAppl SIMPLE_ID Id AnnoLiteral deriving (Show, Eq, Ord, Typeable, Data) data AnnoLiteral = AL_Term (TERM DL_FORMULA) | AL_Id Id deriving (Show, Eq, Ord, Typeable, Data) emptyCASL_DLSign :: CASL_DLSign emptyCASL_DLSign = CASL_DLSign Map.empty [] addCASL_DLSign :: CASL_DLSign -> CASL_DLSign -> CASL_DLSign addCASL_DLSign a b = a { annoProperties = Map.unionWithKey (throwAnnoError "CASL_DL.Sign.addCASL_DLSign:") (annoProperties a) (annoProperties b) , annoPropertySens = union (annoPropertySens a) (annoPropertySens b) } throwAnnoError :: String -> SIMPLE_ID -> PropertyType -> PropertyType -> PropertyType throwAnnoError s k e1 e2 = if e1 == e2 then e1 else error $ s ++ " Annotation Properties and Ontology Properties " ++ "must have distinct names! (" ++ show k ++ ")" diffCASL_DLSign :: CASL_DLSign -> CASL_DLSign -> CASL_DLSign diffCASL_DLSign a b = a { annoProperties = Map.difference (annoProperties a) (annoProperties b) , annoPropertySens = annoPropertySens a \\ annoPropertySens b } isSubCASL_DLSign :: CASL_DLSign -> CASL_DLSign -> Bool isSubCASL_DLSign a b = Map.isSubmapOf (annoProperties a) (annoProperties b) && (annoPropertySens a `isSublistOf` annoPropertySens b) instance Pretty CASL_DLSign where pretty dlSign = if Map.null $ annoProperties dlSign then assert (null $ annoPropertySens dlSign) empty else printPropertyList AnnoProperty "%OWLAnnoProperties(" $+$ printPropertyList OntoProperty "%OWLOntologyProperties(" $+$ if null (annoPropertySens dlSign) then empty else text "%OWLAnnotations(" <+> vcat (punctuate (text "; ") $ map pretty (annoPropertySens dlSign)) <+> text ")%" where propertyList ty = filter (\ (_, x) -> x == ty) $ Map.toList $ annoProperties dlSign printPropertyList ty str = case propertyList ty of [] -> empty l -> text str <+> fcat (punctuate comma $ map (pretty . fst) l) <+> text ")%" instance Pretty AnnoAppl where pretty (AnnoAppl rel subj obj) = pretty rel <> parens (pretty subj <> comma <> pretty obj) instance Pretty AnnoLiteral where pretty annoLit = case annoLit of AL_Term t -> pretty t AL_Id i -> pretty i isSublistOf :: (Eq a) => [a] -> [a] -> Bool isSublistOf ys l = case l of [] -> null ys _ : l' -> isPrefixOf ys l || isSublistOf ys l'
mariefarrell/Hets
CASL_DL/Sign.hs
gpl-2.0
4,089
0
18
1,419
955
494
461
82
2
----------------------------------------------------------------------------- -- -- Module : IDE.Utils.GtkBindings -- Copyright : 2007-2014 Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GPL -- -- Maintainer : maintainer@leksah.org -- Stability : provisional -- Portability : -- -- | -- ----------------------------------------------------------------------------- module IDE.Utils.GtkBindings ( treeViewSetActiveOnSingleClick ) where import Foreign.Ptr (Ptr) import Graphics.UI.Gtk (toToolbar, TreeViewClass, TreeView) import Foreign.ForeignPtr (withForeignPtr) import Graphics.UI.GtkInternals (toTreeView, unTreeView) import Foreign.C.Types (CInt(..)) import Foreign.Marshal.Utils (fromBool) foreign import ccall safe "gtk_tree_view_set_activate_on_single_click" gtk_tree_view_set_activate_on_single_click :: Ptr TreeView -> CInt -> IO () treeViewSetActiveOnSingleClick :: TreeViewClass self => self -> Bool -> IO () treeViewSetActiveOnSingleClick self singleClick = withForeignPtr (unTreeView $ toTreeView self) $ \selfPtr -> gtk_tree_view_set_activate_on_single_click selfPtr (fromIntegral $ fromBool singleClick)
jaccokrijnen/leksah
src/IDE/Utils/GtkBindings.hs
gpl-2.0
1,167
0
10
144
204
120
84
14
1
{-| Description: Main module for testing. Module that acts as interface for testing multiple test suites using cabal. -} module Main ( main ) where import qualified System.Exit as Exit import ParserTests.ParserTests( reqTestSuite ) import Test.HUnit ( runTestTT, Test(..), failures ) -- Single test encompassing all test suites tests :: Test tests = TestList $ [reqTestSuite] main :: IO () main = do count <- runTestTT tests if failures count > 0 then Exit.exitFailure else return ()
hermish/courseography
app/ParserTests/tests.hs
gpl-3.0
504
0
9
97
116
67
49
11
2
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Network.XmlRpc.Internals -- Copyright : (c) Bjorn Bringert 2003 -- License : BSD-style -- -- Maintainer : bjorn@bringert.net -- Stability : experimental -- Portability : non-portable (requires extensions and non-portable libraries) -- -- This module contains the core functionality of the XML-RPC library. -- Most applications should not need to use this module. Client -- applications should use "Network.XmlRpc.Client" and server applications should -- use "Network.XmlRpc.Server". -- -- The XML-RPC specifcation is available at <http://www.xmlrpc.com/spec>. -- ----------------------------------------------------------------------------- module Network.XmlRpc.Internals ( -- * Method calls and repsonses MethodCall(..), MethodResponse(..), -- * XML-RPC types Value(..), Type(..), XmlRpcType(..), -- * Converting from XML parseResponse, parseCall, getField, getFieldMaybe, -- * Converting to XML renderCall, renderResponse, -- * Converting to and from DTD types toXRValue, fromXRValue, toXRMethodCall, fromXRMethodCall, toXRMethodResponse, fromXRMethodResponse, toXRParams, fromXRParams, toXRMember, fromXRMember, -- * Error monad Err, maybeToM, handleError, ioErrorToErr ) where import Control.Exception import Control.Monad import Control.Monad.Except import Data.Char import Data.List import Data.Maybe import Data.Time.Calendar import Data.Time.Calendar.OrdinalDate (toOrdinalDate) import Data.Time.Calendar.WeekDate (toWeekDate) import Data.Time.Format import Data.Time.LocalTime import Numeric (showFFloat) import Prelude hiding (showString, catch) import System.IO.Unsafe (unsafePerformIO) import System.Time (CalendarTime(..)) #if ! MIN_VERSION_time(1,5,0) import System.Locale (defaultTimeLocale) #endif import qualified Data.ByteString.Char8 as BS (ByteString, pack, unpack) import qualified Data.ByteString.Lazy.Char8 as BSL (ByteString, pack) import qualified Network.XmlRpc.Base64 as Base64 import qualified Network.XmlRpc.DTD_XMLRPC as XR import Network.XmlRpc.Pretty import Text.XML.HaXml.XmlContent -- -- General utilities -- -- | Replaces all occurances of a sublist in a list with another list. -- If the list to replace is the empty list, does nothing. replace :: Eq a => [a] -- ^ The sublist to replace when found -> [a] -- ^ The list to replace it with -> [a] -- ^ The list to replace in -> [a] -- ^ The result replace [] _ xs = xs replace _ _ [] = [] replace ys zs xs@(x:xs') | isPrefixOf ys xs = zs ++ replace ys zs (drop (length ys) xs) | otherwise = x : replace ys zs xs' -- | Convert a 'Maybe' value to a value in any monad maybeToM :: Monad m => String -- ^ Error message to fail with for 'Nothing' -> Maybe a -- ^ The 'Maybe' value. -> m a -- ^ The resulting value in the monad. maybeToM err Nothing = fail err maybeToM _ (Just x) = return x -- | Convert a 'Maybe' value to a value in any monad eitherToM :: Monad m => String -- ^ Error message to fail with for 'Nothing' -> Either String a -- ^ The 'Maybe' value. -> m a -- ^ The resulting value in the monad. eitherToM err (Left s) = fail (err ++ ": " ++ s) eitherToM _ (Right x) = return x -- | The format for \"dateTime.iso8601\" xmlRpcDateFormat :: String xmlRpcDateFormat = "%Y%m%dT%H:%M:%S" -- -- Error monad stuff -- type Err m a = ExceptT String m a -- | Evaluate the argument and catch error call exceptions errorToErr :: (Show e, MonadError e m) => a -> Err m a errorToErr x = unsafePerformIO (liftM return (evaluate x) `catch` handleErr) where handleErr :: Monad m => SomeException -> IO (Err m a) handleErr = return . throwError . show -- | Catch IO errors in the error monad. ioErrorToErr :: IO a -> Err IO a ioErrorToErr x = (liftIO x >>= return) `catchError` \e -> throwError (show e) -- | Handle errors from the error monad. handleError :: Monad m => (String -> m a) -> Err m a -> m a handleError h m = do Right x <- runExceptT (catchError m (lift . h)) return x errorRead :: (Monad m, Read a) => ReadS a -- ^ Parser -> String -- ^ Error message -> String -- ^ String to parse -> Err m a errorRead r err s = case [x | (x,t) <- r s, ("","") <- lex t] of [x] -> return x _ -> fail (err ++ ": '" ++ s ++ "'") -- -- Types for methods calls and responses -- -- | An XML-RPC method call. Consists of a method name and a list of -- parameters. data MethodCall = MethodCall String [Value] deriving (Eq, Show) -- for debugging -- | An XML-RPC response. data MethodResponse = Return Value -- ^ A method response returning a value | Fault Int String -- ^ A fault response deriving (Eq, Show) -- for debugging -- | An XML-RPC value. data Value = ValueInt Int -- ^ int, i4, or i8 | ValueBool Bool -- ^ bool | ValueString String -- ^ string | ValueUnwrapped String -- ^ no inner element | ValueDouble Double -- ^ double | ValueDateTime LocalTime -- ^ dateTime.iso8601 | ValueBase64 BS.ByteString -- ^ base 64. NOTE that you should provide the raw data; the haxr library takes care of doing the base-64 encoding. | ValueStruct [(String,Value)] -- ^ struct | ValueArray [Value] -- ^ array deriving (Eq, Show) -- for debugging -- | An XML-RPC value. Use for error messages and introspection. data Type = TInt | TBool | TString | TDouble | TDateTime | TBase64 | TStruct | TArray | TUnknown deriving (Eq) instance Show Type where show TInt = "int" show TBool = "bool" show TString = "string" show TDouble = "double" show TDateTime = "dateTime.iso8601" show TBase64 = "base64" show TStruct = "struct" show TArray = "array" show TUnknown = "unknown" instance Read Type where readsPrec _ s = case break isSpace (dropWhile isSpace s) of ("int",r) -> [(TInt,r)] ("bool",r) -> [(TBool,r)] ("string",r) -> [(TString,r)] ("double",r) -> [(TDouble,r)] ("dateTime.iso8601",r) -> [(TDateTime,r)] ("base64",r) -> [(TBase64,r)] ("struct",r) -> [(TStruct,r)] ("array",r) -> [(TArray,r)] -- | Gets the value of a struct member structGetValue :: Monad m => String -> Value -> Err m Value structGetValue n (ValueStruct t) = maybeToM ("Unknown member '" ++ n ++ "'") (lookup n t) structGetValue _ _ = fail "Value is not a struct" -- | Builds a fault struct faultStruct :: Int -> String -> Value faultStruct code str = ValueStruct [("faultCode",ValueInt code), ("faultString",ValueString str)] -- XML-RPC specification: -- "The body of the response is a single XML structure, a -- <methodResponse>, which can contain a single <params> which contains a -- single <param> which contains a single <value>." onlyOneResult :: Monad m => [Value] -> Err m Value onlyOneResult [] = fail "Method returned no result" onlyOneResult [x] = return x onlyOneResult _ = fail "Method returned more than one result" -- -- Converting to and from XML-RPC types -- -- | A class for mapping Haskell types to XML-RPC types. class XmlRpcType a where -- | Convert from this type to a 'Value' toValue :: a -> Value -- | Convert from a 'Value' to this type. May fail if -- if there is a type error. fromValue :: Monad m => Value -> Err m a getType :: a -> Type typeError :: (XmlRpcType a, Monad m) => Value -> Err m a typeError v = withType $ \t -> fail ("Wanted: " ++ show (getType t) ++ "', got: '" ++ showXml False (toXRValue v) ++ "'") `asTypeOf` return t -- a type hack for use in 'typeError' withType :: (a -> Err m a) -> Err m a withType f = f undefined simpleFromValue :: (Monad m, XmlRpcType a) => (Value -> Maybe a) -> Value -> Err m a simpleFromValue f v = maybe (typeError v) return (f v) -- | Exists to allow explicit type conversions. instance XmlRpcType Value where toValue = id fromValue = return . id getType _ = TUnknown -- FIXME: instance for ()? instance XmlRpcType Int where toValue = ValueInt fromValue = simpleFromValue f where f (ValueInt x) = Just x f _ = Nothing getType _ = TInt instance XmlRpcType Bool where toValue = ValueBool fromValue = simpleFromValue f where f (ValueBool x) = Just x f _ = Nothing getType _ = TBool instance XmlRpcType String where toValue = ValueString fromValue = simpleFromValue f where f (ValueString x) = Just x f (ValueUnwrapped x) = Just x f _ = Nothing getType _ = TString instance XmlRpcType BS.ByteString where toValue = ValueBase64 fromValue = simpleFromValue f where f (ValueBase64 x) = Just x f _ = Nothing getType _ = TBase64 instance XmlRpcType Double where toValue = ValueDouble fromValue = simpleFromValue f where f (ValueDouble x) = Just x f _ = Nothing getType _ = TDouble instance XmlRpcType LocalTime where toValue = ValueDateTime fromValue = simpleFromValue f where f (ValueDateTime x) = Just x f _ = Nothing getType _ = TDateTime instance XmlRpcType CalendarTime where toValue = toValue . calendarTimeToLocalTime fromValue = liftM localTimeToCalendarTime . fromValue getType _ = TDateTime -- FIXME: array elements may have different types instance XmlRpcType a => XmlRpcType [a] where toValue = ValueArray . map toValue fromValue v = case v of ValueArray xs -> mapM fromValue xs _ -> typeError v getType _ = TArray -- FIXME: struct elements may have different types instance XmlRpcType a => XmlRpcType [(String,a)] where toValue xs = ValueStruct [(n, toValue v) | (n,v) <- xs] fromValue v = case v of ValueStruct xs -> mapM (\ (n,v') -> liftM ((,) n) (fromValue v')) xs _ -> typeError v getType _ = TStruct -- Tuple instances may be used for heterogenous array types. instance (XmlRpcType a, XmlRpcType b, XmlRpcType c, XmlRpcType d, XmlRpcType e) => XmlRpcType (a,b,c,d,e) where toValue (v,w,x,y,z) = ValueArray [toValue v, toValue w, toValue x, toValue y, toValue z] fromValue (ValueArray [v,w,x,y,z]) = liftM5 (,,,,) (fromValue v) (fromValue w) (fromValue x) (fromValue y) (fromValue z) fromValue _ = throwError "Expected 5-element tuple!" getType _ = TArray instance (XmlRpcType a, XmlRpcType b, XmlRpcType c, XmlRpcType d) => XmlRpcType (a,b,c,d) where toValue (w,x,y,z) = ValueArray [toValue w, toValue x, toValue y, toValue z] fromValue (ValueArray [w,x,y,z]) = liftM4 (,,,) (fromValue w) (fromValue x) (fromValue y) (fromValue z) fromValue _ = throwError "Expected 4-element tuple!" getType _ = TArray instance (XmlRpcType a, XmlRpcType b, XmlRpcType c) => XmlRpcType (a,b,c) where toValue (x,y,z) = ValueArray [toValue x, toValue y, toValue z] fromValue (ValueArray [x,y,z]) = liftM3 (,,) (fromValue x) (fromValue y) (fromValue z) fromValue _ = throwError "Expected 3-element tuple!" getType _ = TArray instance (XmlRpcType a, XmlRpcType b) => XmlRpcType (a,b) where toValue (x,y) = ValueArray [toValue x, toValue y] fromValue (ValueArray [x,y]) = liftM2 (,) (fromValue x) (fromValue y) fromValue _ = throwError "Expected 2-element tuple." getType _ = TArray -- | Get a field value from a (possibly heterogeneous) struct. getField :: (Monad m, XmlRpcType a) => String -- ^ Field name -> [(String,Value)] -- ^ Struct -> Err m a getField x xs = maybeToM ("struct member " ++ show x ++ " not found") (lookup x xs) >>= fromValue -- | Get a field value from a (possibly heterogeneous) struct. getFieldMaybe :: (Monad m, XmlRpcType a) => String -- ^ Field name -> [(String,Value)] -- ^ Struct -> Err m (Maybe a) getFieldMaybe x xs = case lookup x xs of Nothing -> return Nothing Just v -> liftM Just (fromValue v) -- -- Converting to XR types -- toXRValue :: Value -> XR.Value toXRValue (ValueInt x) = XR.Value [XR.Value_AInt (XR.AInt (showInt x))] toXRValue (ValueBool b) = XR.Value [XR.Value_Boolean (XR.Boolean (showBool b))] toXRValue (ValueString s) = XR.Value [XR.Value_AString (XR.AString (showString s))] toXRValue (ValueUnwrapped s) = XR.Value [XR.Value_Str s] toXRValue (ValueDouble d) = XR.Value [XR.Value_ADouble (XR.ADouble (showDouble d))] toXRValue (ValueDateTime t) = XR.Value [ XR.Value_DateTime_iso8601 (XR.DateTime_iso8601 (showDateTime t))] toXRValue (ValueBase64 s) = XR.Value [XR.Value_Base64 (XR.Base64 (showBase64 s))] toXRValue (ValueStruct xs) = XR.Value [XR.Value_Struct (XR.Struct (map toXRMember xs))] toXRValue (ValueArray xs) = XR.Value [XR.Value_Array (XR.Array (XR.Data (map toXRValue xs)))] showInt :: Int -> String showInt = show showBool :: Bool -> String showBool b = if b then "1" else "0" -- escapes & and < showString :: String -> String showString s = replace ">" "&gt;" $ replace "<" "&lt;" (replace "&" "&amp;" s) -- | Shows a double in signed decimal point notation. showDouble :: Double -> String showDouble d = showFFloat Nothing d "" -- | Shows a date and time on the format: YYYYMMDDTHH:mm:SS showDateTime :: LocalTime -> String showDateTime t = formatTime defaultTimeLocale xmlRpcDateFormat t showBase64 :: BS.ByteString -> String showBase64 = BS.unpack . Base64.encode toXRMethodCall :: MethodCall -> XR.MethodCall toXRMethodCall (MethodCall name vs) = XR.MethodCall (XR.MethodName name) (Just (toXRParams vs)) toXRMethodResponse :: MethodResponse -> XR.MethodResponse toXRMethodResponse (Return val) = XR.MethodResponseParams (toXRParams [val]) toXRMethodResponse (Fault code str) = XR.MethodResponseFault (XR.Fault (toXRValue (faultStruct code str))) toXRParams :: [Value] -> XR.Params toXRParams vs = XR.Params (map (XR.Param . toXRValue) vs) toXRMember :: (String, Value) -> XR.Member toXRMember (n, v) = XR.Member (XR.Name n) (toXRValue v) -- -- Converting from XR types -- fromXRValue :: Monad m => XR.Value -> Err m Value fromXRValue (XR.Value vs) = case (filter notstr vs) of [] -> liftM (ValueUnwrapped . concat) (mapM (readString . unstr) vs) (v:_) -> f v where notstr (XR.Value_Str _) = False notstr _ = True unstr (XR.Value_Str x) = x f (XR.Value_I4 (XR.I4 x)) = liftM ValueInt (readInt x) f (XR.Value_I8 (XR.I8 x)) = liftM ValueInt (readInt x) f (XR.Value_AInt (XR.AInt x)) = liftM ValueInt (readInt x) f (XR.Value_Boolean (XR.Boolean x)) = liftM ValueBool (readBool x) f (XR.Value_ADouble (XR.ADouble x)) = liftM ValueDouble (readDouble x) f (XR.Value_AString (XR.AString x)) = liftM ValueString (readString x) f (XR.Value_DateTime_iso8601 (XR.DateTime_iso8601 x)) = liftM ValueDateTime (readDateTime x) f (XR.Value_Base64 (XR.Base64 x)) = liftM ValueBase64 (readBase64 x) f (XR.Value_Struct (XR.Struct ms)) = liftM ValueStruct (mapM fromXRMember ms) f (XR.Value_Array (XR.Array (XR.Data xs))) = liftM ValueArray (mapM fromXRValue xs) fromXRMember :: Monad m => XR.Member -> Err m (String,Value) fromXRMember (XR.Member (XR.Name n) xv) = liftM (\v -> (n,v)) (fromXRValue xv) -- | From the XML-RPC specification: -- -- \"An integer is a 32-bit signed number. You can include a plus or -- minus at the beginning of a string of numeric characters. Leading -- zeros are collapsed. Whitespace is not permitted. Just numeric -- characters preceeded by a plus or minus.\" readInt :: Monad m => String -> Err m Int readInt s = errorRead reads "Error parsing integer" s -- | From the XML-RPC specification: -- -- \"0 (false) or 1 (true)\" readBool :: Monad m => String -> Err m Bool readBool s = errorRead readsBool "Error parsing boolean" s where readsBool "true" = [(True,"")] readsBool "false" = [(False,"")] readsBool "1" = [(True,"")] readsBool "0" = [(False,"")] readsBool _ = [] -- | From the XML-RPC specification: -- -- \"Any characters are allowed in a string except \< and &, which are -- encoded as &lt; and &amp;. A string can be used to encode binary data.\" -- -- To work with implementations (such as some Python bindings for example) -- which also escape \>, &gt; is unescaped. This is non-standard, but -- seems unlikely to cause problems. readString :: Monad m => String -> Err m String readString = return . replace "&amp;" "&" . replace "&lt;" "<" . replace "&gt;" ">" -- | From the XML-RPC specification: -- -- There is no representation for infinity or negative infinity or \"not -- a number\". At this time, only decimal point notation is allowed, a -- plus or a minus, followed by any number of numeric characters, -- followed by a period and any number of numeric -- characters. Whitespace is not allowed. The range of allowable values -- is implementation-dependent, is not specified. -- -- FIXME: accepts more than decimal point notation readDouble :: Monad m => String -> Err m Double readDouble s = errorRead reads "Error parsing double" s -- | From <http://groups.yahoo.com/group/xml-rpc/message/4733>: -- -- \"Essentially \"dateTime.iso8601\" is a misnomer and the format of the -- content of this element should not be assumed to comply with the -- variants of the ISO8601 standard. Only assume YYYYMMDDTHH:mm:SS\" -- FIXME: make more robust readDateTime :: Monad m => String -> Err m LocalTime readDateTime dt = maybe (fail $ "Error parsing dateTime '" ++ dt ++ "'") return (parseTime defaultTimeLocale xmlRpcDateFormat dt) localTimeToCalendarTime :: LocalTime -> CalendarTime localTimeToCalendarTime l = let (y,mo,d) = toGregorian (localDay l) TimeOfDay { todHour = h, todMin = mi, todSec = s } = localTimeOfDay l (_,_,wd) = toWeekDate (localDay l) (_,yd) = toOrdinalDate (localDay l) in CalendarTime { ctYear = fromIntegral y, ctMonth = toEnum (mo-1), ctDay = d, ctHour = h, ctMin = mi, ctSec = truncate s, ctPicosec = 0, ctWDay = toEnum (wd `mod` 7), ctYDay = yd, ctTZName = "UTC", ctTZ = 0, ctIsDST = False } calendarTimeToLocalTime :: CalendarTime -> LocalTime calendarTimeToLocalTime ct = let (y,mo,d) = (ctYear ct, ctMonth ct, ctDay ct) (h,mi,s) = (ctHour ct, ctMin ct, ctSec ct) in LocalTime { localDay = fromGregorian (fromIntegral y) (fromEnum mo + 1) d, localTimeOfDay = TimeOfDay { todHour = h, todMin = mi, todSec = fromIntegral s } } -- FIXME: what if data contains non-base64 characters? readBase64 :: Monad m => String -> Err m BS.ByteString readBase64 = return . Base64.decode . BS.pack fromXRParams :: Monad m => XR.Params -> Err m [Value] fromXRParams (XR.Params xps) = mapM (\(XR.Param v) -> fromXRValue v) xps fromXRMethodCall :: Monad m => XR.MethodCall -> Err m MethodCall fromXRMethodCall (XR.MethodCall (XR.MethodName name) params) = liftM (MethodCall name) (fromXRParams (fromMaybe (XR.Params []) params)) fromXRMethodResponse :: Monad m => XR.MethodResponse -> Err m MethodResponse fromXRMethodResponse (XR.MethodResponseParams xps) = liftM Return (fromXRParams xps >>= onlyOneResult) fromXRMethodResponse (XR.MethodResponseFault (XR.Fault v)) = do struct <- fromXRValue v vcode <- structGetValue "faultCode" struct code <- fromValue vcode vstr <- structGetValue "faultString" struct str <- fromValue vstr return (Fault code str) -- -- Parsing calls and reponses from XML -- -- | Parses a method call from XML. parseCall :: (Show e, MonadError e m) => String -> Err m MethodCall parseCall c = do mxc <- errorToErr (readXml c) xc <- eitherToM "Error parsing method call" mxc fromXRMethodCall xc -- | Parses a method response from XML. parseResponse :: (Show e, MonadError e m) => String -> Err m MethodResponse parseResponse c = do mxr <- errorToErr (readXml c) xr <- eitherToM "Error parsing method response" mxr fromXRMethodResponse xr -- -- Rendering calls and reponses to XML -- -- | Makes an XML-representation of a method call. -- FIXME: pretty prints ugly XML renderCall :: MethodCall -> BSL.ByteString renderCall = showXml' False . toXRMethodCall -- | Makes an XML-representation of a method response. -- FIXME: pretty prints ugly XML renderResponse :: MethodResponse -> BSL.ByteString renderResponse = showXml' False . toXRMethodResponse showXml' :: XmlContent a => Bool -> a -> BSL.ByteString showXml' dtd x = case toContents x of [CElem _ _] -> (document . toXml dtd) x _ -> BSL.pack ""
laurencer/confluence-sync
vendor/haxr/Network/XmlRpc/Internals.hs
bsd-3-clause
20,916
448
34
4,686
6,022
3,285
2,737
391
12
----------------------------------------------------------------------------- -- | -- License : BSD-3-Clause -- Maintainer : Oleg Grenrus <oleg.grenrus@iki.fi> -- module GitHub.Data.Enterprise.Organizations where import GitHub.Data.Definitions import GitHub.Data.Name (Name) import GitHub.Data.URL (URL) import GitHub.Internal.Prelude import Prelude () data CreateOrganization = CreateOrganization { createOrganizationLogin :: !(Name Organization) , createOrganizationAdmin :: !(Name User) , createOrganizationProfileName :: !(Maybe Text) } deriving (Show, Data, Typeable, Eq, Ord, Generic) instance NFData CreateOrganization where rnf = genericRnf instance Binary CreateOrganization data RenameOrganization = RenameOrganization { renameOrganizationLogin :: !(Name Organization) } deriving (Show, Data, Typeable, Eq, Ord, Generic) instance NFData RenameOrganization where rnf = genericRnf instance Binary RenameOrganization data RenameOrganizationResponse = RenameOrganizationResponse { renameOrganizationResponseMessage :: !Text , renameOrganizationResponseUrl :: !URL } deriving (Show, Data, Typeable, Eq, Ord, Generic) instance NFData RenameOrganizationResponse where rnf = genericRnf instance Binary RenameOrganizationResponse -- JSON Instances instance ToJSON CreateOrganization where toJSON (CreateOrganization login admin profileName) = object $ filter notNull [ "login" .= login , "admin" .= admin , "profile_name" .= profileName ] where notNull (_, Null) = False notNull (_, _) = True instance ToJSON RenameOrganization where toJSON (RenameOrganization login) = object [ "login" .= login ] instance FromJSON RenameOrganizationResponse where parseJSON = withObject "RenameOrganizationResponse" $ \o -> RenameOrganizationResponse <$> o .: "message" <*> o .: "url"
jwiegley/github
src/GitHub/Data/Enterprise/Organizations.hs
bsd-3-clause
2,021
0
11
449
447
244
203
53
0
-- demonstrates an old bug with joins without a restrict import Database.HaskellDB import Database.HaskellDB.Sql import Database.HaskellDB.Query import Database.HaskellDB.Optimize import Database.HaskellDB.HDBRec import Database.HaskellDB.PrimQuery import TestConnect import Dp037.D3proj_time_reports hiding (xid) import qualified Dp037.D3proj_time_reports import Dp037.D3proj_users -- join and project, but no restrict q1 = do reports <- table d3proj_time_reports users <- table d3proj_users project (userid << reports!userid # first_name << users!first_name # last_name << users!last_name # activity << reports!activity) -- has restrict, but does not join on any fields q2 = do r <- q1 restrict (r!userid .==. constant "d00bring") return r showRow :: ShowRecRow r => r -> String showRow = unwords . map (($ "") . snd) . showRecRow showUnoptSql = ppSql . toSql . runQuery testQuery db q = do putStrLn "-- PrimQuery:" putStrLn $ show $ showQ q putStrLn "-- Optimized PrimQuery:" putStrLn $ show $ showOpt q putStrLn "-- SQL:" putStrLn $ show $ showUnoptSql q putStrLn "-- Optimized SQL:" putStrLn $ show $ showSql q rs <- query db q mapM_ (putStrLn . showRow) rs test db = do testQuery db q1 testQuery db q2 main = argConnect test
m4dc4p/haskelldb
test/old/join-without-restrict.hs
bsd-3-clause
1,324
0
19
276
385
189
196
39
1
module Model.ResourceEdit ( fetchAllEditAddCollectionsDB , fetchAllEditAddTagsDB , fetchAllEditAuthorsDB , fetchAllEditPublishedDB , fetchAllEditRemoveCollectionsDB , fetchAllEditRemoveTagsDB , fetchAllEditTitlesDB , fetchAllEditTypesDB , fetchEditAddCollectionsDB , fetchEditAddTagsDB , fetchEditAuthorsDB , fetchEditPublishedDB , fetchEditRemoveCollectionsDB , fetchEditRemoveTagsDB , fetchEditTitlesDB , fetchEditTypesDB , fetchNumRequestedEditsDB ) where import Import import qualified Data.Foldable as F import qualified Data.Map as M import Database.Esqueleto import Data.Monoid (Sum(..), getSum) fetchEditDB :: (PersistEntity val, PersistEntityBackend val ~ SqlBackend) => EntityField val ResourceId -> UserId -> YesodDB App (Map (Entity Resource) [Entity val]) fetchEditDB resIdField uid = fmap makeEditMap $ select $ from $ \(u `InnerJoin` r `InnerJoin` e) -> do on (u^.UserId ==. r^.ResourceUserId) on (r^.ResourceId ==. e^.resIdField) where_ (u^.UserId ==. val uid) return (r,e) fetchAllEditsDB :: (PersistEntity val, PersistEntityBackend val ~ SqlBackend) => EntityField val ResourceId -> YesodDB App (Map (Entity Resource) [Entity val]) fetchAllEditsDB resIdField = fmap makeEditMap $ select $ from $ \(r `InnerJoin` e) -> do on (r^.ResourceId ==. e^.resIdField) return (r,e) -- Not quite M.fromListWith, but close. makeEditMap :: Ord k => [(k,a)] -> Map k [a] makeEditMap = foldr (\(k,a) -> M.insertWith (++) k [a]) M.empty fetchEditAddCollectionsDB :: UserId -> YesodDB App (Map (Entity Resource) [Entity EditAddCollection]) fetchEditAddTagsDB :: UserId -> YesodDB App (Map (Entity Resource) [Entity EditAddTag]) fetchEditAuthorsDB :: UserId -> YesodDB App (Map (Entity Resource) [Entity EditAuthors]) fetchEditPublishedDB :: UserId -> YesodDB App (Map (Entity Resource) [Entity EditPublished]) fetchEditRemoveCollectionsDB :: UserId -> YesodDB App (Map (Entity Resource) [Entity EditRemoveCollection]) fetchEditRemoveTagsDB :: UserId -> YesodDB App (Map (Entity Resource) [Entity EditRemoveTag]) fetchEditTitlesDB :: UserId -> YesodDB App (Map (Entity Resource) [Entity EditTitle]) fetchEditTypesDB :: UserId -> YesodDB App (Map (Entity Resource) [Entity EditType]) fetchEditAddCollectionsDB = fetchEditDB EditAddCollectionResId fetchEditAddTagsDB = fetchEditDB EditAddTagResId fetchEditAuthorsDB = fetchEditDB EditAuthorsResId fetchEditPublishedDB = fetchEditDB EditPublishedResId fetchEditRemoveCollectionsDB = fetchEditDB EditRemoveCollectionResId fetchEditRemoveTagsDB = fetchEditDB EditRemoveTagResId fetchEditTitlesDB = fetchEditDB EditTitleResId fetchEditTypesDB = fetchEditDB EditTypeResId fetchAllEditAddCollectionsDB :: YesodDB App (Map (Entity Resource) [Entity EditAddCollection]) fetchAllEditAddTagsDB :: YesodDB App (Map (Entity Resource) [Entity EditAddTag]) fetchAllEditAuthorsDB :: YesodDB App (Map (Entity Resource) [Entity EditAuthors]) fetchAllEditPublishedDB :: YesodDB App (Map (Entity Resource) [Entity EditPublished]) fetchAllEditRemoveCollectionsDB :: YesodDB App (Map (Entity Resource) [Entity EditRemoveCollection]) fetchAllEditRemoveTagsDB :: YesodDB App (Map (Entity Resource) [Entity EditRemoveTag]) fetchAllEditTitlesDB :: YesodDB App (Map (Entity Resource) [Entity EditTitle]) fetchAllEditTypesDB :: YesodDB App (Map (Entity Resource) [Entity EditType]) fetchAllEditAddCollectionsDB = fetchAllEditsDB EditAddCollectionResId fetchAllEditAddTagsDB = fetchAllEditsDB EditAddTagResId fetchAllEditAuthorsDB = fetchAllEditsDB EditAuthorsResId fetchAllEditPublishedDB = fetchAllEditsDB EditPublishedResId fetchAllEditRemoveCollectionsDB = fetchAllEditsDB EditRemoveCollectionResId fetchAllEditRemoveTagsDB = fetchAllEditsDB EditRemoveTagResId fetchAllEditTitlesDB = fetchAllEditsDB EditTitleResId fetchAllEditTypesDB = fetchAllEditsDB EditTypeResId -- TODO: Should probably select count(*) ? fetchNumRequestedEditsDB :: UserId -> YesodDB App Int fetchNumRequestedEditsDB uid = getSum . mconcat <$> sequence [ adjust <$> fetchEditAddCollectionsDB uid , adjust <$> fetchEditAddTagsDB uid , adjust <$> fetchEditAuthorsDB uid , adjust <$> fetchEditPublishedDB uid , adjust <$> fetchEditRemoveCollectionsDB uid , adjust <$> fetchEditRemoveTagsDB uid , adjust <$> fetchEditTitlesDB uid , adjust <$> fetchEditTypesDB uid ] where adjust :: Map k [a] -> Sum Int adjust = F.foldMap (Sum . length)
mitchellwrosen/dohaskell
src/Model/ResourceEdit.hs
bsd-3-clause
4,943
0
13
1,095
1,278
662
616
91
1
{-# LANGUAGE CPP, DeriveDataTypeable, FlexibleInstances, ScopedTypeVariables #-} #if __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Trustworthy #-} #endif -- | -- Maintainer : judah.jacobson@gmail.com -- Stability : experimental -- Portability : portable (FFI) -- -- This module provides a low-level interface to the C functions of the -- terminfo library. -- -- NOTE: Since this library is built on top of the curses interface, it is not thread-safe. module System.Console.Terminfo.Base( -- * Initialization Terminal(), setupTerm, setupTermFromEnv, SetupTermError, -- * Capabilities Capability, getCapability, tiGetFlag, tiGuardFlag, tiGetNum, tiGetStr, -- * Output -- $outputdoc tiGetOutput1, OutputCap, TermStr, -- ** TermOutput TermOutput(), runTermOutput, hRunTermOutput, termText, tiGetOutput, LinesAffected, -- ** Monoid functions Monoid(..), (<#>), ) where import Control.Applicative import Control.Monad import Data.Monoid import Foreign.C import Foreign.ForeignPtr import Foreign.Ptr import Foreign.Marshal import Foreign.Storable (peek,poke) import System.Environment (getEnv) import System.IO.Unsafe (unsafePerformIO) import System.IO import Control.Exception import Data.Typeable data TERMINAL newtype Terminal = Terminal (ForeignPtr TERMINAL) foreign import ccall "&" cur_term :: Ptr (Ptr TERMINAL) foreign import ccall set_curterm :: Ptr TERMINAL -> IO (Ptr TERMINAL) foreign import ccall "&" del_curterm :: FunPtr (Ptr TERMINAL -> IO ()) foreign import ccall setupterm :: CString -> CInt -> Ptr CInt -> IO () -- | Initialize the terminfo library to the given terminal entry. -- -- Throws a 'SetupTermError' if the terminfo database could not be read. setupTerm :: String -> IO Terminal setupTerm term = bracket (peek cur_term) (poke cur_term) $ \_ -> withCString term $ \c_term -> with 0 $ \ret_ptr -> do -- NOTE: I believe that for the way we use terminfo -- (i.e. custom output function) -- this parameter does not affect anything. let stdOutput = 1 {-- Force ncurses to return a new struct rather than a copy of the current one (which it would do if the terminal names are the same). This prevents problems when calling del_term on a struct shared by more than one Terminal. --} poke cur_term nullPtr -- Call setupterm and check the return value. setupterm c_term stdOutput ret_ptr ret <- peek ret_ptr if (ret /=1) then throwIO $ SetupTermError $ "Couldn't look up terminfo entry " ++ show term else do cterm <- peek cur_term fmap Terminal $ newForeignPtr del_curterm cterm data SetupTermError = SetupTermError String deriving Typeable instance Show SetupTermError where show (SetupTermError str) = "setupTerm: " ++ str instance Exception SetupTermError where -- | Initialize the terminfo library, using the @TERM@ environmental variable. -- If @TERM@ is not set, we use the generic, minimal entry @dumb@. -- -- Throws a 'SetupTermError' if the terminfo database could not be read. setupTermFromEnv :: IO Terminal setupTermFromEnv = do env_term <- handle handleBadEnv $ getEnv "TERM" let term = if null env_term then "dumb" else env_term setupTerm term where handleBadEnv :: IOException -> IO String handleBadEnv _ = return "" -- TODO: this isn't really thread-safe... withCurTerm :: Terminal -> IO a -> IO a withCurTerm (Terminal term) f = withForeignPtr term $ \cterm -> do old_term <- peek cur_term if old_term /= cterm then do _ <- set_curterm cterm x <- f _ <- set_curterm old_term return x else f ---------------------- -- Note I'm relying on this working even for strings with unset parameters. strHasPadding :: String -> Bool strHasPadding [] = False strHasPadding ('$':'<':_) = True strHasPadding (_:cs) = strHasPadding cs -- | An action which sends output to the terminal. That output may mix plain text with control -- characters and escape sequences, along with delays (called \"padding\") required by some older -- terminals. -- We structure this similarly to ShowS, so that appends don't cause space leaks. newtype TermOutput = TermOutput ([TermOutputType] -> [TermOutputType]) data TermOutputType = TOCmd LinesAffected String | TOStr String instance Monoid TermOutput where mempty = TermOutput id TermOutput xs `mappend` TermOutput ys = TermOutput (xs . ys) termText :: String -> TermOutput termText str = TermOutput (TOStr str :) -- | Write the terminal output to the standard output device. runTermOutput :: Terminal -> TermOutput -> IO () runTermOutput = hRunTermOutput stdout -- | Write the terminal output to the terminal or file managed by the given -- 'Handle'. hRunTermOutput :: Handle -> Terminal -> TermOutput -> IO () hRunTermOutput h term (TermOutput to) = do putc_ptr <- mkCallback putc withCurTerm term $ mapM_ (writeToTerm putc_ptr h) (to []) freeHaskellFunPtr putc_ptr hFlush h where putc c = let c' = toEnum $ fromEnum c in hPutChar h c' >> hFlush h >> return c -- NOTE: Currently, the output is checked every time tparm is called. -- It might be faster to check for padding once in tiGetOutput1. writeToTerm :: FunPtr CharOutput -> Handle -> TermOutputType -> IO () writeToTerm putc h (TOCmd numLines s) | strHasPadding s = tPuts s numLines putc | otherwise = hPutStr h s writeToTerm _ h (TOStr s) = hPutStr h s infixl 2 <#> -- | An operator version of 'mappend'. (<#>) :: Monoid m => m -> m -> m (<#>) = mappend --------------------------------- -- | A feature or operation which a 'Terminal' may define. newtype Capability a = Capability (Terminal -> IO (Maybe a)) getCapability :: Terminal -> Capability a -> Maybe a getCapability term (Capability f) = unsafePerformIO $ withCurTerm term (f term) -- Note that the instances for Capability of Functor, Monad and MonadPlus -- use the corresponding instances for Maybe. instance Functor Capability where fmap f (Capability g) = Capability $ \t -> fmap (fmap f) (g t) instance Applicative Capability where pure = return (<*>) = ap instance Monad Capability where return = Capability . const . return . Just Capability f >>= g = Capability $ \t -> do mx <- f t case mx of Nothing -> return Nothing Just x -> let Capability g' = g x in g' t instance Alternative Capability where (<|>) = mplus empty = mzero instance MonadPlus Capability where mzero = Capability (const $ return Nothing) Capability f `mplus` Capability g = Capability $ \t -> do mx <- f t case mx of Nothing -> g t _ -> return mx foreign import ccall tigetnum :: CString -> IO CInt -- | Look up a numeric capability in the terminfo database. tiGetNum :: String -> Capability Int tiGetNum cap = Capability $ const $ do n <- fmap fromEnum (withCString cap tigetnum) if n >= 0 then return (Just n) else return Nothing foreign import ccall tigetflag :: CString -> IO CInt -- | Look up a boolean capability in the terminfo database. -- -- Unlike 'tiGuardFlag', this capability never fails; it returns 'False' if the -- capability is absent or set to false, and returns 'True' otherwise. -- tiGetFlag :: String -> Capability Bool tiGetFlag cap = Capability $ const $ fmap (Just . (>0)) $ withCString cap tigetflag -- | Look up a boolean capability in the terminfo database, and fail if -- it\'s not defined. tiGuardFlag :: String -> Capability () tiGuardFlag cap = tiGetFlag cap >>= guard foreign import ccall tigetstr :: CString -> IO CString {-# DEPRECATED tiGetStr "use tiGetOutput instead." #-} -- | Look up a string capability in the terminfo database. NOTE: This function is deprecated; use -- 'tiGetOutput1' instead. tiGetStr :: String -> Capability String tiGetStr cap = Capability $ const $ do result <- withCString cap tigetstr if result == nullPtr || result == neg1Ptr then return Nothing else fmap Just (peekCString result) where -- hack; tigetstr sometimes returns (-1) neg1Ptr = nullPtr `plusPtr` (-1) --------------- foreign import ccall tparm :: CString -> CLong -> CLong -> CLong -> CLong -> CLong -> CLong -> CLong -> CLong -> CLong -- p1,...,p9 -> IO CString -- Note: I may want to cut out the middleman and pipe tGoto/tGetStr together -- with tput without a String marshall in the middle. -- directly without tParm :: String -> Capability ([Int] -> String) tParm cap = Capability $ \t -> return $ Just $ \ps -> unsafePerformIO $ withCurTerm t $ tparm' (map toEnum ps ++ repeat 0) where tparm' (p1:p2:p3:p4:p5:p6:p7:p8:p9:_) = withCString cap $ \c_cap -> do result <- tparm c_cap p1 p2 p3 p4 p5 p6 p7 p8 p9 if result == nullPtr then return "" else peekCString result tparm' _ = fail "tParm: List too short" -- | Look up an output capability in the terminfo database. tiGetOutput :: String -> Capability ([Int] -> LinesAffected -> TermOutput) tiGetOutput cap = do str <- tiGetStr cap f <- tParm str return $ \ps la -> fromStr la $ f ps fromStr :: LinesAffected -> String -> TermOutput fromStr la s = TermOutput (TOCmd la s :) type CharOutput = CInt -> IO CInt foreign import ccall "wrapper" mkCallback :: CharOutput -> IO (FunPtr CharOutput) foreign import ccall tputs :: CString -> CInt -> FunPtr CharOutput -> IO () -- | A parameter to specify the number of lines affected. Some capabilities -- (e.g., @clear@ and @dch1@) use -- this parameter on some terminals to compute variable-length padding. type LinesAffected = Int -- | Output a string capability. Applys padding information to the string if -- necessary. tPuts :: String -> LinesAffected -> FunPtr CharOutput -> IO () tPuts s n putc = withCString s $ \c_str -> tputs c_str (toEnum n) putc -- | Look up an output capability which takes a fixed number of parameters -- (for example, @Int -> Int -> TermOutput@). -- -- For capabilities which may contain variable-length -- padding, use 'tiGetOutput' instead. tiGetOutput1 :: forall f . OutputCap f => String -> Capability f tiGetOutput1 str = do cap <- tiGetStr str guard (hasOkPadding (undefined :: f) cap) f <- tParm cap return $ outputCap f [] -- OK, this is the structure that I want: class OutputCap f where hasOkPadding :: f -> String -> Bool outputCap :: ([Int] -> String) -> [Int] -> f instance OutputCap [Char] where hasOkPadding _ = not . strHasPadding outputCap f xs = f (reverse xs) instance OutputCap TermOutput where hasOkPadding _ = const True outputCap f xs = fromStr 1 $ f $ reverse xs instance (Enum p, OutputCap f) => OutputCap (p -> f) where outputCap f xs = \x -> outputCap f (fromEnum x:xs) hasOkPadding _ = hasOkPadding (undefined :: f) {- $outputdoc Terminfo contains many string capabilities for special effects. For example, the @cuu1@ capability moves the cursor up one line; on ANSI terminals this is accomplished by printing the control sequence @\"\\ESC[A\"@. However, some older terminals also require \"padding\", or short pauses, after certain commands. For example, when @TERM=vt100@ the @cuu1@ capability is @\"\\ESC[A$\<2\>\"@, which instructs terminfo to pause for two milliseconds after outputting the control sequence. The 'TermOutput' monoid abstracts away all padding and control sequence output. Unfortunately, that datatype is difficult to integrate into existing 'String'-based APIs such as pretty-printers. Thus, as a workaround, 'tiGetOutput1' also lets us access the control sequences as 'String's. The one caveat is that it will not allow you to access padded control sequences as Strings. For example: > > t <- setupTerm "vt100" > > isJust (getCapability t (tiGetOutput1 "cuu1") :: Maybe String) > False > > isJust (getCapability t (tiGetOutput1 "cuu1") :: Maybe TermOutput) > True 'String' capabilities will work with software-based terminal types such as @xterm@ and @linux@. However, you should use 'TermOutput' if compatibility with older terminals is important. Additionally, the @visualBell@ capability which flashes the screen usually produces its effect with a padding directive, so it will only work with 'TermOutput'. -} class (Monoid s, OutputCap s) => TermStr s instance TermStr [Char] instance TermStr TermOutput
jwiegley/ghc-release
libraries/terminfo/System/Console/Terminfo/Base.hs
gpl-3.0
13,647
0
17
3,807
2,730
1,411
1,319
-1
-1
-- Setup file for a Gtk2Hs module. Contains only adjustments specific to this module, -- all Gtk2Hs-specific boilerplate is stored in Gtk2HsSetup.hs which should be kept -- identical across all modules. import Gtk2HsSetup ( gtk2hsUserHooks, checkGtk2hsBuildtools ) import Distribution.Simple ( defaultMainWithHooks ) main = do checkGtk2hsBuildtools ["gtk2hsC2hs", "gtk2hsTypeGen", "gtk2hsHookGenerator"] defaultMainWithHooks gtk2hsUserHooks
YoEight/poppler_bak
Setup.hs
lgpl-2.1
449
0
8
59
51
29
22
5
1
module Main where import Lib (ourAdd) import Text.Printf (printf) main :: IO () main = printf "2 + 3 = %d\n" (ourAdd 2 3)
emaphis/Haskell-Practice
testing-project/app/Main.hs
bsd-3-clause
125
0
7
27
50
28
22
5
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module Lazyfoo.Lesson05 (main) where import Control.Monad import Foreign.C.Types import Linear import qualified SDL import Paths_sdl2 (getDataFileName) #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif screenWidth, screenHeight :: CInt (screenWidth, screenHeight) = (640, 480) loadSurface :: SDL.Surface -> FilePath -> IO SDL.Surface loadSurface screenSurface path = do loadedSurface <- getDataFileName path >>= SDL.loadBMP desiredFormat <- SDL.surfaceFormat screenSurface SDL.convertSurface loadedSurface desiredFormat <* SDL.freeSurface loadedSurface main :: IO () main = do SDL.initialize [SDL.InitVideo] window <- SDL.createWindow "SDL Tutorial" SDL.defaultWindow { SDL.windowInitialSize = V2 screenWidth screenHeight } SDL.showWindow window screenSurface <- SDL.getWindowSurface window stretchedSurface <- loadSurface screenSurface "examples/lazyfoo/stretch.bmp" let loop = do let collectEvents = do e <- SDL.pollEvent case e of Nothing -> return [] Just e' -> (e' :) <$> collectEvents events <- collectEvents let quit = any (== SDL.QuitEvent) $ map SDL.eventPayload events SDL.surfaceBlitScaled stretchedSurface Nothing screenSurface Nothing SDL.updateWindowSurface window unless quit loop loop SDL.freeSurface stretchedSurface SDL.destroyWindow window SDL.quit
dalaing/sdl2
examples/lazyfoo/Lesson05.hs
bsd-3-clause
1,468
0
21
285
391
191
200
39
2
{-# LANGUAGE FlexibleContexts #-} module Opaleye.SQLite.RunQuery (module Opaleye.SQLite.RunQuery, QueryRunner, IRQ.QueryRunnerColumn, IRQ.fieldQueryRunnerColumn) where import qualified Database.SQLite.Simple as PGS import qualified Database.SQLite.Simple.FromRow as FR import qualified Data.String as String import Opaleye.SQLite.Column (Column) import qualified Opaleye.SQLite.Sql as S import Opaleye.SQLite.QueryArr (Query) import Opaleye.SQLite.Internal.RunQuery (QueryRunner(QueryRunner)) import qualified Opaleye.SQLite.Internal.RunQuery as IRQ import qualified Opaleye.SQLite.Internal.QueryArr as Q import qualified Data.Profunctor as P import qualified Data.Profunctor.Product.Default as D import Control.Applicative ((*>)) -- | @runQuery@'s use of the 'D.Default' typeclass means that the -- compiler will have trouble inferring types. It is strongly -- recommended that you provide full type signatures when using -- @runQuery@. -- -- Example type specialization: -- -- @ -- runQuery :: Query (Column 'Opaleye.PGTypes.PGInt4', Column 'Opaleye.PGTypes.PGText') -> IO [(Column Int, Column String)] -- @ -- -- Assuming the @makeAdaptorAndInstance@ splice has been run for the product type @Foo@: -- -- @ -- runQuery :: Query (Foo (Column 'Opaleye.PGTypes.PGInt4') (Column 'Opaleye.PGTypes.PGText') (Column 'Opaleye.PGTypes.PGBool') -- -> IO [(Foo (Column Int) (Column String) (Column Bool)] -- @ -- -- Opaleye types are converted to Haskell types based on instances of -- the 'Opaleye.Internal.RunQuery.QueryRunnerColumnDefault' typeclass. runQuery :: D.Default QueryRunner columns haskells => PGS.Connection -> Query columns -> IO [haskells] runQuery = runQueryExplicit D.def runQueryExplicit :: QueryRunner columns haskells -> PGS.Connection -> Query columns -> IO [haskells] runQueryExplicit (QueryRunner u rowParser nonZeroColumns) conn q = PGS.queryWith_ parser conn sql where sql :: PGS.Query sql = String.fromString (S.showSqlForPostgresExplicit u q) -- FIXME: We're doing work twice here (b, _, _) = Q.runSimpleQueryArrStart q () parser = if nonZeroColumns b then rowParser b else (FR.fromRow :: FR.RowParser (PGS.Only Int)) *> rowParser b -- If we are selecting zero columns then the SQL -- generator will have to put a dummy 0 into the -- SELECT statement, since we can't select zero -- columns. In that case we have to make sure we -- read a single Int. -- | Use 'queryRunnerColumn' to make an instance to allow you to run queries on -- your own datatypes. For example: -- -- @ -- newtype Foo = Foo Int -- instance Default QueryRunnerColumn Foo Foo where -- def = queryRunnerColumn ('Opaleye.Column.unsafeCoerce' :: Column Foo -> Column PGInt4) Foo def -- @ queryRunnerColumn :: (Column a' -> Column a) -> (b -> b') -> IRQ.QueryRunnerColumn a b -> IRQ.QueryRunnerColumn a' b' queryRunnerColumn colF haskellF qrc = IRQ.QueryRunnerColumn (P.lmap colF u) (fmapFP haskellF fp) where IRQ.QueryRunnerColumn u fp = qrc fmapFP = fmap . fmap
bergmark/haskell-opaleye
opaleye-sqlite/src/Opaleye/SQLite/RunQuery.hs
bsd-3-clause
3,411
0
13
862
511
306
205
40
2
{-# LANGUAGE DeriveGeneric #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Verbosity -- Copyright : Ian Lynagh 2007 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- A simple 'Verbosity' type with associated utilities. There are 4 standard -- verbosity levels from 'silent', 'normal', 'verbose' up to 'deafening'. This -- is used for deciding what logging messages to print. -- Verbosity for Cabal functions. module Distribution.Verbosity ( -- * Verbosity Verbosity, silent, normal, verbose, deafening, moreVerbose, lessVerbose, intToVerbosity, flagToVerbosity, showForCabal, showForGHC ) where import Distribution.Compat.Binary (Binary) import Data.List (elemIndex) import Distribution.ReadE import GHC.Generics data Verbosity = Silent | Normal | Verbose | Deafening deriving (Generic, Show, Read, Eq, Ord, Enum, Bounded) instance Binary Verbosity -- We shouldn't print /anything/ unless an error occurs in silent mode silent :: Verbosity silent = Silent -- Print stuff we want to see by default normal :: Verbosity normal = Normal -- Be more verbose about what's going on verbose :: Verbosity verbose = Verbose -- Not only are we verbose ourselves (perhaps even noisier than when -- being "verbose"), but we tell everything we run to be verbose too deafening :: Verbosity deafening = Deafening moreVerbose :: Verbosity -> Verbosity moreVerbose Silent = Silent --silent should stay silent moreVerbose Normal = Verbose moreVerbose Verbose = Deafening moreVerbose Deafening = Deafening lessVerbose :: Verbosity -> Verbosity lessVerbose Deafening = Deafening lessVerbose Verbose = Normal lessVerbose Normal = Silent lessVerbose Silent = Silent intToVerbosity :: Int -> Maybe Verbosity intToVerbosity 0 = Just Silent intToVerbosity 1 = Just Normal intToVerbosity 2 = Just Verbose intToVerbosity 3 = Just Deafening intToVerbosity _ = Nothing flagToVerbosity :: ReadE Verbosity flagToVerbosity = ReadE $ \s -> case reads s of [(i, "")] -> case intToVerbosity i of Just v -> Right v Nothing -> Left ("Bad verbosity: " ++ show i ++ ". Valid values are 0..3") _ -> Left ("Can't parse verbosity " ++ s) showForCabal, showForGHC :: Verbosity -> String showForCabal v = maybe (error "unknown verbosity") show $ elemIndex v [silent,normal,verbose,deafening] showForGHC v = maybe (error "unknown verbosity") show $ elemIndex v [silent,normal,__,verbose,deafening] where __ = silent -- this will be always ignored by elemIndex
DavidAlphaFox/ghc
libraries/Cabal/Cabal/Distribution/Verbosity.hs
bsd-3-clause
2,702
0
17
547
537
299
238
53
3
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeFamilies #-} module Language.Rowling.Common ( module ClassyPrelude, module Control.Applicative, module Control.Exception.ErrorList, module Control.Monad, module Control.Monad.Except, module Control.Monad.Identity, module Control.Monad.State.Strict, module Control.Monad.Reader, module Control.Monad.Trans, module Data.Char, module Data.Default, module Data.HashMap.Strict, module Data.Maybe, module GHC.Exts, module Text.Render, Name, Record, for, tuple ) where import ClassyPrelude hiding (assert, asList, find, for, keys) import qualified Prelude as P import Control.Exception.ErrorList import Control.Monad (when) import Control.Monad.Trans (MonadIO(..), lift) import Control.Monad.Reader (ReaderT(..), MonadReader(..), (<=<), (>=>), ask, asks) import Control.Monad.State.Strict (MonadState, StateT, State, get, gets, modify, put, liftM, liftIO, runState, runStateT, execState, execStateT, evalState, evalStateT) import Control.Monad.Except (ExceptT, MonadError(..), throwError, runExceptT) import Control.Monad.Identity (Identity(..)) import Control.Applicative hiding (empty) import Data.Char (isDigit) import Data.Default import Data.HashMap.Strict (HashMap, keys, (!)) import qualified Data.HashMap.Strict as H import Data.Maybe (fromJust, isJust, isNothing) import qualified Data.Text as T import GHC.Exts (IsList) import Text.Render -- | Indicates that the text is some identifier. type Name = Text -- | A record is a lookup table with string keys. type Record = HashMap Name -- | Map reversed. for :: Functor f => f a -> (a -> b) -> f b for = flip map -- | Takes two applicative actions and returns their result as a 2-tuple. tuple :: Applicative f => f a -> f b -> f (a, b) tuple action1 action2 = (,) <$> action1 <*> action2
thinkpad20/rowling
src/Language/Rowling/Common.hs
mit
2,237
0
9
457
527
342
185
54
1
{-# htermination (head :: (List a) -> a) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil head :: (List a) -> a; head (Cons x vv) = x;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/head_1.hs
mit
191
0
8
49
70
40
30
5
1
{-# OPTIONS_GHC -funbox-strict-fields #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} module Database.Mongodb.Connection ( Host, Port , ConnectionInfo(..) , Connection(..) , connect, close , withConnection ) where #include "protocol.h" import Control.Monad (forever, void) import Control.Applicative ((<$>)) import Control.Concurrent (ThreadId, forkIO, killThread) import Control.Concurrent.MVar (MVar, newMVar, newEmptyMVar, withMVar, putMVar) import Control.Exception (bracket) import Data.Binary.Get (runGet) import Data.Binary.Put (runPut) import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef) import Data.Map (Map) import Data.Monoid ((<>)) import Data.Word (Word16) import qualified Data.Map as Map import qualified Data.ByteString.Lazy as LazyByteString import qualified Data.ByteString.Char8 as StrictByteString import qualified System.IO as IO import Data.Tagged (Tagged, untag) import qualified Network.Socket as Socket import Database.Mongodb.Internal (StrictByteString, LazyByteString, RequestIdCounter, ObjectIdCounter, newRequestIdCounter, newObjectIdCounter, newRequestId) import Database.Mongodb.Protocol (Request(..), RequestId, OpCode, MessageHeader(..), Reply, getMessageHeader, putMessageHeader, getReply) type Host = StrictByteString type Port = Word16 -- FIXME(lebedev): why only 16 bits? type ReplyMapRef = IORef (Map RequestId (MVar Reply)) data ConnectionInfo = ConnectionInfoInet !Host !Port | ConnectionInfoUnix !StrictByteString {- Note(lebedev): how about a phantom type, representing connection state, i. e. data Open data Closed data Connection phantom = ... This is a classical phantom types example, but it's still useful one. -} data Connection = Connection { conRidCounter :: !RequestIdCounter , conOidCounter :: !ObjectIdCounter , conHandle :: !IO.Handle , conRequestMVar :: !(MVar Bool) , conReplyMapRef :: !ReplyMapRef , conReplyReader :: !ThreadId } connect :: ConnectionInfo -> IO Connection connect info = do conSocket <- case info of ConnectionInfoInet host port -> do (Socket.AddrInfo { .. }:_) <- Socket.getAddrInfo Nothing (Just $ StrictByteString.unpack host) (Just $ show port) socket <- Socket.socket addrFamily addrSocketType addrProtocol Socket.connect socket addrAddress return socket ConnectionInfoUnix path -> do socket <- Socket.socket Socket.AF_UNIX Socket.Stream Socket.defaultProtocol Socket.connect socket $ Socket.SockAddrUnix $ StrictByteString.unpack path return socket conHandle <- Socket.socketToHandle conSocket IO.ReadWriteMode conRidCounter <- newRequestIdCounter conOidCounter <- newObjectIdCounter conRequestMVar <- newMVar undefined conReplyMapRef <- newIORef Map.empty conReplyReader <- forkIO $ replyReader conHandle conReplyMapRef return Connection { .. } close :: Connection -> IO () close (Connection { conHandle, conReplyReader }) = do -- FIXME(lebedev): how to deal with unfilled MVars in 'conReplyMap'? killThread conReplyReader IO.hClose conHandle withConnection :: ConnectionInfo -> (Connection -> IO a) -> IO a withConnection info = bracket (connect info) close -- | A per-connection worker thread, which reads MongoDB messages from -- the handle and fills @MVar@s for the corresponding @RequestId@s. replyReader :: IO.Handle -> ReplyMapRef -> IO () replyReader h replyMapRef = forever $ do -- FIXME(lebedev): this is unsafe, since 'fail == error' in the -- IO monad. (MessageHeader { .. }) <- runGet getMessageHeader <$> LazyByteString.hGet h headerSize reply <- runGet getReply <$> (LazyByteString.hGet h $ fromIntegral rhMessageLength - headerSize) replyMap <- readIORef replyMapRef case Map.lookup rhResponseTo replyMap of Just replyMVar -> putMVar replyMVar reply Nothing -> return () -- Ignore unknown requests. where headerSize = 4 * 4 -- sizeof(int32) * 4. withRequestLock :: Connection -> IO a -> IO a withRequestLock Connection { conRequestMVar } = withMVar conRequestMVar . const {-# INLINE withRequestLock #-} sendRequestWithReply :: forall rq. (Request rq, ReplyExpected rq ~ True) => Connection -> rq -> IO (MVar Reply) sendRequestWithReply connection@(Connection { conReplyMapRef }) request = do replyMVar <- newEmptyMVar requestId <- sendRequest connection request atomicModifyIORef' conReplyMapRef $ \m -> (Map.insert requestId replyMVar m, ()) return replyMVar {-# INLINE sendRequestWithReply #-} sendRequestNoReply :: forall rq. (Request rq, ReplyExpected rq ~ False) => Connection -> rq -> IO () sendRequestNoReply connection request = void $ sendRequest connection request {-# INLINE sendRequestNoReply #-} sendRequest :: forall rq. Request rq => Connection -> rq -> IO RequestId sendRequest (Connection { .. }) request = do requestId <- newRequestId conRidCounter LazyByteString.hPut conHandle $ formatRequest request requestId return requestId {-# INLINE sendRequest #-} formatRequest :: forall rq. Request rq => rq -> RequestId -> LazyByteString formatRequest request rhRequestId = header <> body where body = runPut $ putRequest request bodySize = fromIntegral $ LazyByteString.length body headerSize = 4 * 4 -- sizeof(int32) * 4. rhOpCode = untag (opCode :: Tagged rq OpCode) rhMessageLength = bodySize + headerSize header = runPut $ putMessageHeader $ MessageHeader { rhResponseTo = 0, .. } {-# INLINE formatRequest #-}
lambda-llama/mnogo
src/Database/Mongodb/Connection.hs
mit
6,134
0
18
1,422
1,398
745
653
139
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} module Main where import Control.Applicative import Control.Monad import Haste import Haste.Ajax import Haste.Foreign import Haste.JSON import Haste.Prim import Unsafe.Coerce instance Marshal JSAny where pack = toPtr . unsafeCoerce unpack = unsafeCoerce . fromPtr foreign import ccall jsStrSet :: JSAny -> JSString -> JSString -> IO () foreign import ccall jsObjSet :: JSAny -> JSString -> JSAny -> IO () foreign import ccall jsNumSet :: JSAny -> JSString -> Double -> IO () foreign import ccall jsBoolSet :: JSAny -> JSString -> Bool -> IO () foreign import ccall jsStrArrayPush :: JSAny -> JSString -> IO () foreign import ccall jsNumArrayPush :: JSAny -> Double -> IO () foreign import ccall jsBoolArrayPush :: JSAny -> Bool -> IO () foreign import ccall jsObjArrayPush :: JSAny -> JSAny -> IO () foreign import ccall jsNewArray :: IO JSAny foreign import ccall jsNewObject :: IO JSAny foreign import ccall jsCallMethod :: JSAny -> JSString -> JSString -> IO JSAny foreign import ccall jsCallCBMethod :: JSAny -> JSString -> JSFun a -> IO JSAny foreign import ccall jsSetFun :: JSAny -> JSString -> JSFun a -> IO () -- Getters, setters, and so on. -- These cry out for a type class. The issue is that foreign imported -- functions must have concrete types --- so we need separate functions --- for each type we want to set, even though they all do the same thing. strArray :: [JSString] -> IO JSAny strArray str = do arr <- jsNewArray forM_ str $ jsStrArrayPush arr return arr objArray :: [JSAny] -> IO JSAny objArray objs = do arr <- jsNewArray forM_ objs $ jsObjArrayPush arr return arr strObj :: [(JSString, JSString)] -> IO JSAny strObj assoc = do obj <- jsNewObject forM_ assoc $ uncurry (jsStrSet obj) return obj assignJSON :: JSON -> IO JSAny -- See Note: [Traversable JSON?] assignJSON = \case Arr jsons -> do arr <- jsNewArray go arr `mapM_` jsons return arr Dict jsons -> do o <- jsNewObject goObj o `mapM_` jsons return o _ -> error "The top level JSON must be an array or an object" where go a (Num n) = jsNumArrayPush a n go a (Str s) = jsStrArrayPush a s go a (Bool b) = jsBoolArrayPush a b go a (Arr xs) = do a' <- jsNewArray forM_ xs $ go a' jsObjArrayPush a a' go a (Dict ls) = do o <- jsNewObject forM_ ls $ goObj o jsObjArrayPush a o goObj :: JSAny -> (JSString, JSON) -> IO () goObj o (k, Num n) = jsNumSet o k n goObj o (k, Str s) = jsStrSet o k s goObj o (k, Bool b) = jsBoolSet o k b goObj o (k, Arr vs) = do a'' <- jsNewArray forM_ vs $ go a'' jsObjSet o k a'' goObj o (k, Dict vs) = do o' <- jsNewObject forM_ vs $ goObj o' jsObjSet o k o' -------------------------------------------------------------------- -- Note: Traversable JSON ? -------------------------------------------------------------------- -- The by-hand treewalking in assignJSON is a bit painful. -- It seems like it ought to be Traversable, but of course it's not: -- it's not paramterized by anything. -- -- But we might be able to make it one, if we separate out the -- data-structure part from the value part. We'd have a type -- -- data JSPrimitive = Num n | Str s | Bool b | Null -- -- representing pure values. Then the data structure bit is -- just a tree with two sorts of branches, tagged and untagged: -- -- data JSTree a = Arr [JSTree a] -- | Dict [(JSString, JSTree a)] -- | Val a -- -- JSTree ought to be a Functor, Traversable, etc. A JSON value, or -- really any Javascript value, would just be -- -- type JS = JSTree JSPrimitive -- -- Surely someone's done this already? If not, is there something -- wrong with it? -------------------------------------------------------------------- setPhones :: JSAny -> JSAny -> IO () setPhones scope http = do service <- jsCallMethod http "get" "/phones/phones.json" -- test <- strObj [("name", "Andromeda") ,("snippet", "A galaxy") ,("age", "1")] jsCallCBMethod service "success" . mkCallback $ jsObjSet scope "phones" -- \_ -> jsObjSet scope "phones" =<< objArray [test] jsStrSet scope "orderProp" "age" main = do export "setPhones" setPhones
zopa/aghast
app/hask/aghast.hs
mit
4,523
0
11
1,078
1,110
560
550
87
11
{-# LANGUAGE FlexibleContexts #-} module Level where import Control.Monad import Control.Monad.State import qualified Player as P import qualified Platform as Platform import qualified Switch as Switch import qualified Base.InputHandler as IH import qualified Base.AudioManager as AM import qualified Base.GraphicsManager as G import qualified Base.Camera as C import qualified Base.Geometry as Geo import qualified Graphics.UI.SDL as SDL import Graphics.UI.SDL.Mixer as SDL import Config import Timer import Foreign(touchForeignPtr) import Control.Lens((^.)) data LevelConfig = LevelConfig { lId :: Int, startPos :: [(Int,Int)], goal :: Geo.Shape, staticObstacles :: [Platform.Platform], holdSwitches :: [Switch.Switch LevelData], currMusic :: SDL.Music } data LevelData = LevelData { movingObstacles :: [Platform.Platform], camera :: C.FixedCamera, players :: [P.Player], curPlayer :: Int, levelHistory :: [LevelData] } data Level = Level { lC :: LevelConfig, lD :: LevelData } initialize :: Int -> IO Level initialize 0 = do m <- SDL.loadMUS "../assets/music/Aalborn_Pulse.mp3" let l = Level (LevelConfig 0 sPos (Geo.Rectangle 350 240 20 20) platforms [(Switch.Hold (Geo.Rectangle 250 290 30 10) id (\l@(LevelData _ fc@(C.FixedCamera (x,y) _ _) _ _ _) -> l { camera=(fc { C.corner=(x+1,y) } ) }))] m) (LevelData mPlatforms (C.FixedCamera (0,0) height width) (map P.initialize sPos) 0 []) AM.playMusic m return l where sPos = [(0,200), (100,200)] mPlatforms = [(Platform.moveableInitialize (10,200) (100,250) 30 10 5 (0,0,0) )] platforms = [(Platform.Platform (Geo.Rectangle 0 300 400 30) (0,0,0)),(Platform.Platform (Geo.Rectangle 450 290 300 30) (0,0,0)), (Platform.Platform (Geo.Rectangle 300 260 95 10) (0,0,0)),(Platform.Platform (Geo.Rectangle (-10) 10 300 30) (0,0,0))] {-update :: IH.KeyboardState -> Level -> (Bool,Level) update kS l@(Level lC lev) = if IH.isDown kS SDL.SDLK_LSHIFT then (False,l { lD=(head (levelHistory lev)) }) else (not . (elem False) . (map (Geo.collides (goal lC))) $ pObs, l { lD=nL }) where nL = map (Switch.update nL' newPlayers) (holdSwitches lC) nL' = lev { players=newPlayers, levelHistory=(lev:(levelHistory lev)), curPlayer=playInd, movingObstacles=newObstacles } playInd = max 0 (min pI ((length (players lev)) - 1)) pI = (curPlayer lev) + (if IH.isDown kS SDL.SDLK_q then (-1) else 0) + (if IH.isDown kS SDL.SDLK_e then 1 else 0) sObs = (map Platform.bounding $ staticObstacles lC) pObs = (map P.bounding $ players lev) -- lengthy way to exclude players from hitting themselves newPlayers = [ P.update (if n == playInd then kS else []) (sObs ++ mObs ++ (skip n pObs)) newObstacles ((players lev)!!n) | n <- [0..((length . players $ lev) - 1)] ] mObs = (map Platform.mBounding $ newObstacles) newObstacles = map Platform.update (movingObstacles lev) -} update :: IH.KeyboardState -> Level -> (Bool,Level) update kS l@(Level lC lev) = (won,l { lD=nLD }) where (won,nLD) = runState (updateS kS lC) lev updateS :: IH.KeyboardState -> LevelConfig -> State LevelData Bool updateS kS lC = do prev <- gets levelHistory if ((IH.isDown kS SDL.SDLK_LSHIFT) && (not . null $ prev)) then do put . head $ prev return False else do obs <- gets $ (map Platform.update) . movingObstacles modify $ \s -> s { movingObstacles=obs } let mObs = map Platform._bounding obs let sObs = (map Platform._bounding) . staticObstacles $ lC pObs <- gets $ (map P._bounding) . players pls <- gets players currP <- gets curPlayer let playInd = max 0 (min (currP + (if IH.isDown kS SDL.SDLK_q then (-1) else 0) + (if IH.isDown kS SDL.SDLK_e then 1 else 0)) ((length pls) - 1)) lev <- get let newPlayers = [ P.update (if n == playInd then kS else []) (sObs ++ mObs ++ (skip n pObs)) obs ((players lev)!!n) | n <- [0..((length . players $ lev) - 1)] ] modify $ \t -> t { players=newPlayers, levelHistory=(t:(levelHistory t)), curPlayer=playInd, movingObstacles=obs } modify $ \t -> swUpdate t (holdSwitches lC) return $ not . (elem False) . (map (Geo.collides (goal lC))) $ pObs swUpdate :: LevelData -> [Switch.Switch LevelData] -> LevelData swUpdate x [] = x swUpdate lev (x:xs) = swUpdate (snd $ Switch.update lev (players lev) x) xs draw :: SDL.Surface -> Level -> IO () draw screen (Level lC lev) = do -- last will force evaluation, and keep type IO () sequence $ map (Platform.draw screen (camera lev)) (staticObstacles lC) sequence $ map (P.draw screen (camera lev)) (players lev) sequence $ map (Platform.draw screen (camera lev)) (movingObstacles lev) sequence $ map (Switch.draw screen (camera lev)) (holdSwitches lC) let camRect = C.shapeToScreen (camera lev) (goal lC) 640 480 case camRect of Just r -> G.drawRect screen (r^.Geo.x,r^.Geo.y) (r^.Geo.width) (r^.Geo.height) (50,100,50) Nothing -> return () -- Need to tell the GC to not free the music (SDL should really do this) touchForeignPtr . currMusic $ lC return () -- Helper function skip :: Int -> [a] -> [a] skip _ [] = [] skip 0 (x:xs) = xs skip n (x:xs) = x : (skip (n-1) xs)
mdietz94/haskellgame
src/Level.hs
mit
5,419
8
24
1,237
1,832
992
840
86
5
module Main ( main ) where import GhostLang.Node (runNode) import System.Environment (getArgs) main :: IO () main = do [listenPort] <- getArgs runNode $ read listenPort
kosmoskatten/ghost-lang
ghost-node/src/Main.hs
mit
183
0
8
40
64
35
29
8
1
module CastInsertion where import System.IO.Unsafe import Data.Unique import qualified Data.Map as HM import Data.List import TypeSystem import FinalType import Static import TypeSystemForCC labelPrefix :: String labelPrefix = "L" typeOfCI :: String typeOfCI = "typeOfCI" sig_typeOfCI :: Signature sig_typeOfCI = [Decl typeOfCI "o" Nothing Nothing [Simple "term", Simple "term", Simple "typ"]] encodingSuffix :: String encodingSuffix = "'" castInsertion :: TypeSystem -> TypeSystem castInsertion ts = castInsertion_ (toGradual ts) castInsertion_ :: TypeSystem -> TypeSystem castInsertion_ (Ts sig rules) = (Ts sig (map (castInsertion_rule sig) rules)) castInsertion_rule :: Signature -> Rule -> Rule castInsertion_rule sig (Rule premises' conclusion) = (Rule (map castInsertion_prem premises) (castInsertion_concl pkg conclusion)) where premises = concat (map subtypeUnfold premises') pkg = (sig, (Rule premises conclusion)) castInsertion_prem :: Premise -> Premise castInsertion_prem (Formula pred strings interms outterms) = if pred == typeOfGradual || pred == typeOfCC then (Formula typeOfCI strings interms ((enc pred (head interms)):outterms)) else (Formula pred strings interms outterms) castInsertion_prem (Hypothetical premise1 premise2) = (Hypothetical (castInsertion_prem premise1) (castInsertion_prem premise2)) castInsertion_concl :: Package -> Premise -> Premise castInsertion_concl pkg (Formula pred strings interms outterms) = if pred == typeOfGradual || pred == typeOfCC then (Formula typeOfCI strings interms ((encWithCasts pkg pred (head interms)):outterms)) else (Formula pred strings interms outterms) -- At the moment, we have applications (R x) that will turn into (R' x). Therefore term2 in Application is left not encoded. enc :: String -> Term -> Term enc pred (Var varterm) = if pred == typeOfCC then (Var varterm) else (Var (varterm ++ encodingSuffix)) enc pred (Application term1 term2) = (Application (enc pred term1) term2) enc pred (Constructor c terms) = (Constructor c (map (enc pred) terms)) enc pred other = other -- To do: when you add parsing signatures, you have to query for term variables, only those are searched for casts. encWithCasts :: Package -> String -> Term -> Term encWithCasts pkg pred (Var varterm) = case assignedTypeByVar (pkg_getRule pkg) (Var varterm) of Just typ -> (castWrap pkg pred (Var varterm) typ (destinationType pkg typ)) Nothing -> (Var varterm) -- error ("ERROR: notfound" ++ varterm ++ (show (pkg_getRule pkg))) -- encWithCasts pkg pred (Constructor c terms) = (Constructor c (map (encWithCasts pkg pred) terms)) castWrap :: Package -> String -> Term -> Term -> Term -> Term castWrap pkg pred (Var variable) source target = if (isAbstraction pkg (Var variable)) then (Lambda "x" (cast (Application (Var variable) (appliedTermTo (pkg_getRule pkg) (Var variable)) ))) else cast (Var variable) where cast = \x -> makeCastTerm (enc pred x) source target makeCastTerm :: Term -> Term -> Term -> Term makeCastTerm term source target = if source == target then term else (Constructor "cast" [term, source, (Var labelPrefix), target]) assignedTypeByVar :: Rule -> Term -> Maybe Term assignedTypeByVar rule term = case searchPremiseByPredAndVar rule typeOf term of { Nothing -> Nothing ; Just (Formula pred strings interms outterms) -> Just (head outterms) } appliedTermTo :: Rule -> Term -> Term appliedTermTo rule term = case searchPremiseByPredAndVar rule typeOf term of { Nothing -> error "impossible case because assignedTypeByVar succeded" ; Just (Formula pred strings interms outterms) -> case head interms of (Application t1 t2) -> t2 } subtypeUnfold :: Premise -> [Premise] subtypeUnfold (Formula pred strings interms outterms) = if pred == "subtypeG" then [Formula "subtypeCI" [] interms [freshvar], Formula "flow" [] [interms !! 0, freshvar] []] else [(Formula pred strings interms outterms)] where freshvar = Var (head strings) subtypeUnfold other = [other]
mcimini/Gradualizer
CastInsertion.hs
mit
4,016
5
15
652
1,316
688
628
51
2
import Control.Monad (foldM) import System.Console.GetOpt import System.Environment (getArgs,getProgName) import YML.Dataset (parse, R) import YML.LinearGradient (cost, gradientDescent, nullF , Parameters (..) ) -- | Our main function takes a file as parameter -- and try to read it and put its values inside a dataset data structure main :: IO () main = do (opts,file) <- parseArgs fileContent <- readFile file let trainingSet = parse fileContent -- print trainingSet putStr "Cost of training set using the null function: " print $ cost trainingSet (nullF trainingSet) putStr "Function minimizing the cost: " print $ gradientDescent (optionsToParameters opts) trainingSet where optionsToParameters :: Options -> Parameters optionsToParameters (Options valAlpha valThreshold) = Parameters valAlpha valThreshold data Options = Options { optAlpha :: R , optThreshold :: R} deriving Show defaultOptions :: Options defaultOptions = Options { optAlpha = 0.01, optThreshold = 10**(-10) } parseArgs :: IO (Options,String) parseArgs = do argv <- getArgs progName <- getProgName let header = "Usage: " ++ progName ++ " [OPTIONS...] file" let helpMessage = usageInfo header options case getOpt RequireOrder options argv of (opts, [file], []) -> case foldM (flip id) defaultOptions opts of Right option -> return (option,file) Left errorMessage -> ioError (userError (errorMessage ++ "\n" ++ helpMessage)) (_,_,errs) -> ioError (userError (concat errs ++ helpMessage)) options :: [OptDescr (Options -> Either String Options)] options = [ Option ['a'] ["alpha"] (ReqArg (\str opts -> case reads str of [(a, "")] | a>0 -> Right opts { optAlpha = a } _ -> Left "--alpha must be >0" ) "alpha") "set alpha value" , Option ['t'] ["threshold"] (ReqArg (\str opts -> case reads str of [(t, "")] | t>0 -> Right opts { optThreshold = t } _ -> Left "--threshold must be >0" ) "threshold") "set threshold value" ]
yogsototh/YML
src/Main.hs
mit
2,428
0
18
828
656
344
312
42
3
to_tens :: Integer -> [Integer] to_tens 0 = [] to_tens n = to_tens (n `div` 10) ++ [n `mod` 10] ans = sum $ to_tens (2^1000)
stefan-j/ProjectEuler
q16.hs
mit
130
0
8
31
75
41
34
4
1
{-# LANGUAGE DeriveDataTypeable,DeriveGeneric,TemplateHaskell #-} module Database.Toxic.Query.AST where import GHC.Generics import Control.DeepSeq import Control.Exception import Control.Lens import qualified Data.Map as M import qualified Data.Text as T import Data.Typeable import qualified Data.Vector as V import Database.Toxic.Types type Condition = Expression data Literal = LBool Bool | LInt Integer | LNull | LValue Value deriving (Eq, Show) data QueryAggregate = QAggBoolOr | QAggSum | QAggFailIfAggregated deriving (Eq, Show) data Unop = UnopNot deriving (Eq, Show) data Binop = BinopPlus | BinopMinus | BinopTimes | BinopDividedBy | BinopGreaterOrEqual | BinopGreater | BinopEqual | BinopLessOrEqual | BinopLess | BinopUnequal deriving (Eq, Show) data Expression = ELiteral Literal | ERename Expression T.Text | ECase (ArrayOf (Condition, Expression)) (Maybe Expression) | EVariable T.Text | EAggregate QueryAggregate Expression | EPlaceholder Int | EUnop Unop Expression | EBinop Binop Expression Expression deriving (Eq, Show) data Query = SingleQuery { queryGroupBy :: Maybe (ArrayOf Expression), queryOrderBy :: Maybe (ArrayOf (Expression, StreamOrder)), queryProject :: ArrayOf Expression, querySource :: Maybe Query, queryWhere :: Maybe Expression } | SumQuery { queryCombineOperation :: QuerySumOperation, queryConstituentQueries :: ArrayOf Query } | ProductQuery { queryFactors :: ArrayOf Query } deriving (Eq, Show) data TableSpec = TableSpec { tableSpecColumns :: ArrayOf Column } deriving (Eq, Show) data Table = Table { tableName :: T.Text, tableSpec :: TableSpec } deriving (Eq, Show) data Environment = Environment { _environmentTables :: M.Map T.Text Table } deriving (Eq, Show) data Statement = SQuery Query | SCreateTable T.Text TableSpec deriving (Eq, Show) data QueryError = ErrorParseError T.Text | ErrorUnknownVariable T.Text deriving (Eq, Show, Typeable, Generic) instance Exception QueryError instance NFData QueryError makeLenses ''Environment singleton_query :: Expression -> Query singleton_query expression = SingleQuery { queryGroupBy = Nothing, queryProject = V.singleton expression, querySource = Nothing, queryOrderBy = Nothing, queryWhere = Nothing } singleton_statement :: Expression -> Statement singleton_statement = SQuery . singleton_query
MichaelBurge/ToxicSludgeDB
src/Database/Toxic/Query/AST.hs
mit
2,449
0
12
459
654
377
277
90
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE OverloadedStrings #-} module Clingo.Internal.AST where import Control.Monad import Data.Text (Text, unpack, pack) import Data.Text.Lazy (fromStrict) import Data.Bifunctor import Data.Bifoldable import Data.Bitraversable import Numeric.Natural import Foreign hiding (Pool, freePool) import Foreign.C import Text.PrettyPrint.Leijen.Text hiding ((<$>)) import Clingo.Internal.Types (Location, rawLocation, freeRawLocation, fromRawLocation, Symbol (..), Signature (..)) import Clingo.Internal.Symbol (pureSymbol, pureSignature) import Clingo.Raw.AST newArray' :: Storable a => [a] -> IO (Ptr a) newArray' [] = pure nullPtr newArray' xs = newArray xs freeArray :: Storable a => Ptr a -> CSize -> (a -> IO ()) -> IO () freeArray p n f = unless (p == nullPtr) $ do p' <- peekArray (fromIntegral n) p mapM_ f p' free p freeIndirection :: Storable a => Ptr a -> (a -> IO ()) -> IO () freeIndirection p f = unless (p == nullPtr) $ do p' <- peek p f p' free p peekMaybe :: Storable a => Ptr a -> IO (Maybe a) peekMaybe p | p == nullPtr = return Nothing | otherwise = Just <$> peek p fromIndirect :: Storable a => Ptr a -> (a -> IO b) -> IO b fromIndirect p f = peek p >>= f data Sign = NoSign | NegationSign | DoubleNegationSign deriving (Eq, Show, Ord) instance Pretty Sign where pretty NoSign = empty pretty NegationSign = text "not" pretty DoubleNegationSign = text "not not" rawSign :: Sign -> AstSign rawSign s = case s of NoSign -> AstSignNone NegationSign -> AstSignNegation DoubleNegationSign -> AstSignDoubleNegation fromRawSign :: AstSign -> Sign fromRawSign s = case s of AstSignNone -> NoSign AstSignNegation -> NegationSign AstSignDoubleNegation -> DoubleNegationSign _ -> error "Invalid clingo_ast_sign_t" data UnaryOperation a = UnaryOperation UnaryOperator (Term a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (UnaryOperation a) where pretty (UnaryOperation o t) = pretty o <+> pretty t rawUnaryOperation :: UnaryOperation (Symbol s) -> IO AstUnaryOperation rawUnaryOperation (UnaryOperation o t) = AstUnaryOperation <$> pure (rawUnaryOperator o) <*> rawTerm t freeUnaryOperation :: AstUnaryOperation -> IO () freeUnaryOperation (AstUnaryOperation _ t) = freeTerm t fromRawUnaryOperation :: AstUnaryOperation -> IO (UnaryOperation (Symbol s)) fromRawUnaryOperation (AstUnaryOperation o t) = UnaryOperation <$> pure (fromRawUnaryOperator o) <*> fromRawTerm t data UnaryOperator = UnaryMinus | Negation | Absolute deriving (Eq, Show, Ord) instance Pretty UnaryOperator where pretty UnaryMinus = text "-" pretty _ = text "<unaryOp>" -- TODO rawUnaryOperator :: UnaryOperator -> AstUnaryOperator rawUnaryOperator o = case o of UnaryMinus -> AstUnaryOperatorMinus Negation -> AstUnaryOperatorNegation Absolute -> AstUnaryOperatorAbsolute fromRawUnaryOperator :: AstUnaryOperator -> UnaryOperator fromRawUnaryOperator o = case o of AstUnaryOperatorMinus -> UnaryMinus AstUnaryOperatorNegation -> Negation AstUnaryOperatorAbsolute -> Absolute _ -> error "Invalid clingo_ast_unary_operator_t" data BinaryOperation a = BinaryOperation BinaryOperator (Term a) (Term a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (BinaryOperation a) where pretty (BinaryOperation o a b) = pretty a <+> pretty o <+> pretty b rawBinaryOperation :: BinaryOperation (Symbol s) -> IO AstBinaryOperation rawBinaryOperation (BinaryOperation o l r) = AstBinaryOperation <$> pure (rawBinaryOperator o) <*> rawTerm l <*> rawTerm r freeBinaryOperation :: AstBinaryOperation -> IO () freeBinaryOperation (AstBinaryOperation _ a b) = freeTerm a >> freeTerm b fromRawBinaryOperation :: AstBinaryOperation -> IO (BinaryOperation (Symbol s)) fromRawBinaryOperation (AstBinaryOperation o a b) = BinaryOperation <$> pure (fromRawBinaryOperator o) <*> fromRawTerm a <*> fromRawTerm b data BinaryOperator = Xor | Or | And | Plus | Minus | Mult | Div | Mod deriving (Eq, Show, Ord) instance Pretty BinaryOperator where pretty o = text $ case o of Xor -> "^" Or -> "|" And -> "&" Plus -> "+" Minus -> "-" Mult -> "*" Div -> "/" Mod -> "%" rawBinaryOperator :: BinaryOperator -> AstBinaryOperator rawBinaryOperator o = case o of Xor -> AstBinaryOperatorXor Or -> AstBinaryOperatorOr And -> AstBinaryOperatorAnd Plus -> AstBinaryOperatorPlus Minus -> AstBinaryOperatorMinus Mult -> AstBinaryOperatorMultiplication Div -> AstBinaryOperatorDivision Mod -> AstBinaryOperatorModulo fromRawBinaryOperator :: AstBinaryOperator -> BinaryOperator fromRawBinaryOperator o = case o of AstBinaryOperatorXor -> Xor AstBinaryOperatorOr -> Or AstBinaryOperatorAnd -> And AstBinaryOperatorPlus -> Plus AstBinaryOperatorMinus -> Minus AstBinaryOperatorMultiplication -> Mult AstBinaryOperatorDivision -> Div AstBinaryOperatorModulo -> Mod _ -> error "Invalid clingo_ast_binary_operator_t" data Interval a = Interval (Term a) (Term a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (Interval a) where pretty (Interval a b) = pretty a <> text ".." <> pretty b rawInterval :: Interval (Symbol s) -> IO AstInterval rawInterval (Interval a b) = AstInterval <$> rawTerm a <*> rawTerm b freeInterval :: AstInterval -> IO () freeInterval (AstInterval a b) = freeTerm a >> freeTerm b fromRawInterval :: AstInterval -> IO (Interval (Symbol s)) fromRawInterval (AstInterval a b) = Interval <$> fromRawTerm a <*> fromRawTerm b data Function a = Function Text [Term a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (Function a) where pretty (Function t []) = text . fromStrict $ t pretty (Function t xs) = (text . fromStrict $ t) <> tupled (map pretty xs) rawFunction :: Function (Symbol s) -> IO AstFunction rawFunction (Function n ts) = do n' <- newCString (unpack n) ts' <- newArray' =<< mapM rawTerm ts return $ AstFunction n' ts' (fromIntegral . length $ ts) freeFunction :: AstFunction -> IO () freeFunction (AstFunction s ts n) = do free s freeArray ts n freeTerm fromRawFunction :: AstFunction -> IO (Function (Symbol s)) fromRawFunction (AstFunction s ts n) = Function <$> fmap pack (peekCString s) <*> (mapM fromRawTerm =<< peekArray (fromIntegral n) ts) data Pool a = Pool [Term a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (Pool a) where pretty (Pool _) = text "<pool>" -- TODO! rawPool :: Pool (Symbol s) -> IO AstPool rawPool (Pool ts) = do ts' <- newArray' =<< mapM rawTerm ts return $ AstPool ts' (fromIntegral . length $ ts) freePool :: AstPool -> IO () freePool (AstPool ts n) = freeArray ts n freeTerm fromRawPool :: AstPool -> IO (Pool (Symbol s)) fromRawPool (AstPool ts n) = Pool <$> (mapM fromRawTerm =<< peekArray (fromIntegral n) ts) data Term a = TermSymbol Location a | TermVariable Location Text | TermUOp Location (UnaryOperation a) | TermBOp Location (BinaryOperation a) | TermInterval Location (Interval a) | TermFunction Location (Function a) | TermExtFunction Location (Function a) | TermPool Location (Pool a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (Term a) where pretty (TermSymbol _ a) = pretty a pretty (TermVariable _ t) = text . fromStrict $ t pretty (TermUOp _ o) = pretty o pretty (TermBOp _ o) = pretty o pretty (TermInterval _ i) = pretty i pretty (TermFunction _ f) = pretty f pretty (TermExtFunction _ f) = pretty f pretty (TermPool _ p) = pretty p rawTerm :: Term (Symbol s) -> IO AstTerm rawTerm (TermSymbol l s) = AstTermSymbol <$> rawLocation l <*> pure (rawSymbol s) rawTerm (TermVariable l n) = AstTermVariable <$> rawLocation l <*> newCString (unpack n) rawTerm (TermUOp l u) = AstTermUOp <$> rawLocation l <*> (new =<< rawUnaryOperation u) rawTerm (TermBOp l u) = AstTermBOp <$> rawLocation l <*> (new =<< rawBinaryOperation u) rawTerm (TermInterval l i) = AstTermInterval <$> rawLocation l <*> (new =<< rawInterval i) rawTerm (TermFunction l f) = AstTermFunction <$> rawLocation l <*> (new =<< rawFunction f) rawTerm (TermExtFunction l f) = AstTermExtFunction <$> rawLocation l <*> (new =<< rawFunction f) rawTerm (TermPool l p) = AstTermPool <$> rawLocation l <*> (new =<< rawPool p) freeTerm :: AstTerm -> IO () freeTerm (AstTermSymbol l _) = freeRawLocation l freeTerm (AstTermVariable l _) = freeRawLocation l freeTerm (AstTermUOp l o) = freeRawLocation l >> freeIndirection o freeUnaryOperation freeTerm (AstTermBOp l o) = freeRawLocation l >> freeIndirection o freeBinaryOperation freeTerm (AstTermInterval l i) = freeRawLocation l >> freeIndirection i freeInterval freeTerm (AstTermFunction l f) = freeRawLocation l >> freeIndirection f freeFunction freeTerm (AstTermExtFunction l f) = freeRawLocation l >> freeIndirection f freeFunction freeTerm (AstTermPool l p) = freeRawLocation l >> freeIndirection p freePool fromRawTerm :: AstTerm -> IO (Term (Symbol s)) fromRawTerm (AstTermSymbol l s) = TermSymbol <$> fromRawLocation l <*> pureSymbol s fromRawTerm (AstTermVariable l s) = TermVariable <$> fromRawLocation l <*> fmap pack (peekCString s) fromRawTerm (AstTermUOp l o) = TermUOp <$> fromRawLocation l <*> fromIndirect o fromRawUnaryOperation fromRawTerm (AstTermBOp l o) = TermBOp <$> fromRawLocation l <*> fromIndirect o fromRawBinaryOperation fromRawTerm (AstTermInterval l i) = TermInterval <$> fromRawLocation l <*> fromIndirect i fromRawInterval fromRawTerm (AstTermFunction l f) = TermFunction <$> fromRawLocation l <*> fromIndirect f fromRawFunction fromRawTerm (AstTermExtFunction l f) = TermExtFunction <$> fromRawLocation l <*> fromIndirect f fromRawFunction fromRawTerm (AstTermPool l p) = TermPool <$> fromRawLocation l <*> fromIndirect p fromRawPool data CspProductTerm a = CspProductTerm Location (Term a) (Maybe (Term a)) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawCspProductTerm :: CspProductTerm (Symbol s) -> IO AstCspProductTerm rawCspProductTerm (CspProductTerm l t m) = AstCspProductTerm <$> rawLocation l <*> rawTerm t <*> maybe (return nullPtr) (new <=< rawTerm) m freeCspProductTerm :: AstCspProductTerm -> IO () freeCspProductTerm (AstCspProductTerm l t p) = do freeRawLocation l freeTerm t freeIndirection p freeTerm fromRawCspProductTerm :: AstCspProductTerm -> IO (CspProductTerm (Symbol s)) fromRawCspProductTerm (AstCspProductTerm l t x) = CspProductTerm <$> fromRawLocation l <*> fromRawTerm t <*> (mapM fromRawTerm =<< peekMaybe x) data CspSumTerm a = CspSumTerm Location [CspProductTerm a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawCspSumTerm :: CspSumTerm (Symbol s) -> IO AstCspSumTerm rawCspSumTerm (CspSumTerm l ts) = do l' <- rawLocation l ts' <- newArray' =<< mapM rawCspProductTerm ts return $ AstCspSumTerm l' ts' (fromIntegral . length $ ts) freeCspSumTerm :: AstCspSumTerm -> IO () freeCspSumTerm (AstCspSumTerm l ts n) = do freeRawLocation l freeArray ts n freeCspProductTerm fromRawCspSumTerm :: AstCspSumTerm -> IO (CspSumTerm (Symbol s)) fromRawCspSumTerm (AstCspSumTerm l ts n) = CspSumTerm <$> fromRawLocation l <*> (mapM fromRawCspProductTerm =<< peekArray (fromIntegral n) ts) data CspGuard a = CspGuard ComparisonOperator (CspSumTerm a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawCspGuard :: CspGuard (Symbol s) -> IO AstCspGuard rawCspGuard (CspGuard o t) = AstCspGuard <$> pure (rawComparisonOperator o) <*> rawCspSumTerm t freeCspGuard :: AstCspGuard -> IO () freeCspGuard (AstCspGuard _ t) = freeCspSumTerm t fromRawCspGuard :: AstCspGuard -> IO (CspGuard (Symbol s)) fromRawCspGuard (AstCspGuard o t) = CspGuard <$> pure (fromRawComparisonOperator o) <*> fromRawCspSumTerm t data ComparisonOperator = GreaterThan | LessThan | LessEqual | GreaterEqual | NotEqual | Equal deriving (Eq, Show, Ord) instance Pretty ComparisonOperator where pretty c = text $ case c of GreaterThan -> ">" LessThan -> "<" LessEqual -> "<=" GreaterEqual -> ">=" NotEqual -> "!=" Equal -> "=" rawComparisonOperator :: ComparisonOperator -> AstComparisonOperator rawComparisonOperator o = case o of GreaterThan -> AstComparisonOperatorGreaterThan LessThan -> AstComparisonOperatorLessThan LessEqual -> AstComparisonOperatorLessEqual GreaterEqual -> AstComparisonOperatorGreaterEqual NotEqual -> AstComparisonOperatorNotEqual Equal -> AstComparisonOperatorEqual fromRawComparisonOperator :: AstComparisonOperator -> ComparisonOperator fromRawComparisonOperator o = case o of AstComparisonOperatorGreaterThan -> GreaterThan AstComparisonOperatorLessThan -> LessThan AstComparisonOperatorLessEqual -> LessEqual AstComparisonOperatorGreaterEqual -> GreaterEqual AstComparisonOperatorNotEqual -> NotEqual AstComparisonOperatorEqual -> Equal _ -> error "Invalid clingo_ast_comparison_operator_type_t" data CspLiteral a = CspLiteral (CspSumTerm a) [CspGuard a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawCspLiteral :: CspLiteral (Symbol s) -> IO AstCspLiteral rawCspLiteral (CspLiteral t gs) = do gs' <- newArray' =<< mapM rawCspGuard gs t' <- rawCspSumTerm t return $ AstCspLiteral t' gs' (fromIntegral . length $ gs) freeCspLiteral :: AstCspLiteral -> IO () freeCspLiteral (AstCspLiteral t p n) = do freeCspSumTerm t freeArray p n freeCspGuard fromRawCspLiteral :: AstCspLiteral -> IO (CspLiteral (Symbol s)) fromRawCspLiteral (AstCspLiteral t gs n) = CspLiteral <$> fromRawCspSumTerm t <*> (mapM fromRawCspGuard =<< peekArray (fromIntegral n) gs) data Identifier = Identifier Location Text deriving (Eq, Show, Ord) instance Pretty Identifier where pretty (Identifier _ t) = text . fromStrict $ t rawIdentifier :: Identifier -> IO AstId rawIdentifier (Identifier l t) = do l' <- rawLocation l t' <- newCString (unpack t) return $ AstId l' t' freeIdentifier :: AstId -> IO () freeIdentifier (AstId l t) = freeRawLocation l >> free t fromRawIdentifier :: AstId -> IO Identifier fromRawIdentifier (AstId l n) = Identifier <$> fromRawLocation l <*> fmap pack (peekCString n) data Comparison a = Comparison ComparisonOperator (Term a) (Term a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (Comparison a) where pretty (Comparison o a b) = pretty a <+> pretty o <+> pretty b rawComparison :: Comparison (Symbol s) -> IO AstComparison rawComparison (Comparison o a b) = AstComparison <$> pure (rawComparisonOperator o) <*> rawTerm a <*> rawTerm b freeComparison :: AstComparison -> IO () freeComparison (AstComparison _ a b) = freeTerm a >> freeTerm b fromRawComparison :: AstComparison -> IO (Comparison (Symbol s)) fromRawComparison (AstComparison o a b) = Comparison <$> pure (fromRawComparisonOperator o) <*> fromRawTerm a <*> fromRawTerm b data Literal a = LiteralBool Location Sign Bool | LiteralTerm Location Sign (Term a) | LiteralComp Location Sign (Comparison a) | LiteralCSPL Location Sign (CspLiteral a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (Literal a) where pretty (LiteralBool _ s b) = pretty s <+> if b then text "true" else empty pretty (LiteralTerm _ s t) = pretty s <+> pretty t pretty (LiteralComp _ s c) = pretty s <+> pretty c pretty _ = undefined -- TODO rawLiteral :: Literal (Symbol s) -> IO AstLiteral rawLiteral (LiteralBool l s b) = AstLiteralBool <$> rawLocation l <*> pure (rawSign s) <*> pure (fromBool b) rawLiteral (LiteralTerm l s t) = AstLiteralTerm <$> rawLocation l <*> pure (rawSign s) <*> (new =<< rawTerm t) rawLiteral (LiteralComp l s c) = AstLiteralComp <$> rawLocation l <*> pure (rawSign s) <*> (new =<< rawComparison c) rawLiteral (LiteralCSPL l s x) = AstLiteralCSPL <$> rawLocation l <*> pure (rawSign s) <*> (new =<< rawCspLiteral x) freeLiteral :: AstLiteral -> IO () freeLiteral (AstLiteralBool l _ _) = freeRawLocation l freeLiteral (AstLiteralTerm l _ t) = freeRawLocation l >> freeIndirection t freeTerm freeLiteral (AstLiteralComp l _ c) = freeRawLocation l >> freeIndirection c freeComparison freeLiteral (AstLiteralCSPL l _ x) = freeRawLocation l >> freeIndirection x freeCspLiteral fromRawLiteral :: AstLiteral -> IO (Literal (Symbol s)) fromRawLiteral (AstLiteralBool l s b) = LiteralBool <$> fromRawLocation l <*> pure (fromRawSign s) <*> pure (toBool b) fromRawLiteral (AstLiteralTerm l s b) = LiteralTerm <$> fromRawLocation l <*> pure (fromRawSign s) <*> fromIndirect b fromRawTerm fromRawLiteral (AstLiteralComp l s b) = LiteralComp <$> fromRawLocation l <*> pure (fromRawSign s) <*> fromIndirect b fromRawComparison fromRawLiteral (AstLiteralCSPL l s b) = LiteralCSPL <$> fromRawLocation l <*> pure (fromRawSign s) <*> fromIndirect b fromRawCspLiteral data AggregateGuard a = AggregateGuard ComparisonOperator (Term a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) -- | Instance describing left-guards. instance Pretty a => Pretty (AggregateGuard a) where pretty (AggregateGuard o t) = pretty t <+> pretty o aguardPRight :: Pretty a => AggregateGuard a -> Doc aguardPRight (AggregateGuard o t) = pretty o <+> pretty t aguardPLeft :: Pretty a => AggregateGuard a -> Doc aguardPLeft = pretty rawAggregateGuard :: AggregateGuard (Symbol s) -> IO AstAggregateGuard rawAggregateGuard (AggregateGuard o t) = AstAggregateGuard <$> pure (rawComparisonOperator o) <*> rawTerm t rawAggregateGuardM :: Maybe (AggregateGuard (Symbol s)) -> IO (Ptr AstAggregateGuard) rawAggregateGuardM Nothing = return nullPtr rawAggregateGuardM (Just g) = new =<< rawAggregateGuard g freeAggregateGuard :: AstAggregateGuard -> IO () freeAggregateGuard (AstAggregateGuard _ t) = freeTerm t fromRawAggregateGuard :: AstAggregateGuard -> IO (AggregateGuard (Symbol s)) fromRawAggregateGuard (AstAggregateGuard o t) = AggregateGuard <$> pure (fromRawComparisonOperator o) <*> fromRawTerm t data ConditionalLiteral a = ConditionalLiteral (Literal a) [Literal a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (ConditionalLiteral a) where pretty (ConditionalLiteral l []) = pretty l pretty (ConditionalLiteral l xs) = pretty l <+> colon <+> cat (punctuate (comma <> space) (map pretty xs)) rawConditionalLiteral :: ConditionalLiteral (Symbol s) -> IO AstConditionalLiteral rawConditionalLiteral (ConditionalLiteral l ls) = do l' <- rawLiteral l ls' <- newArray' =<< mapM rawLiteral ls return $ AstConditionalLiteral l' ls' (fromIntegral . length $ ls) freeConditionalLiteral :: AstConditionalLiteral -> IO () freeConditionalLiteral (AstConditionalLiteral l ls n) = do freeLiteral l freeArray ls n freeLiteral fromRawConditionalLiteral :: AstConditionalLiteral -> IO (ConditionalLiteral (Symbol s)) fromRawConditionalLiteral (AstConditionalLiteral l ls n) = ConditionalLiteral <$> fromRawLiteral l <*> (mapM fromRawLiteral =<< peekArray (fromIntegral n) ls) data Aggregate a = Aggregate [ConditionalLiteral a] (Maybe (AggregateGuard a)) (Maybe (AggregateGuard a)) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (Aggregate a) where pretty (Aggregate xs l r) = pretty l <+> body <+> pretty (fmap aguardPRight r) where body = braces . align . cat $ punctuate (semi <> space) (map pretty xs) rawAggregate :: Aggregate (Symbol s) -> IO AstAggregate rawAggregate (Aggregate ls a b) = do ls' <- newArray' =<< mapM rawConditionalLiteral ls a' <- rawAggregateGuardM a b' <- rawAggregateGuardM b return $ AstAggregate ls' (fromIntegral . length $ ls) a' b' freeAggregate :: AstAggregate -> IO () freeAggregate (AstAggregate ls n a b) = do freeIndirection a freeAggregateGuard freeIndirection b freeAggregateGuard freeArray ls n freeConditionalLiteral fromRawAggregate :: AstAggregate -> IO (Aggregate (Symbol s)) fromRawAggregate (AstAggregate ls n a b) = Aggregate <$> (mapM fromRawConditionalLiteral =<< peekArray (fromIntegral n) ls) <*> (mapM fromRawAggregateGuard =<< peekMaybe a) <*> (mapM fromRawAggregateGuard =<< peekMaybe b) data BodyAggregateElement a = BodyAggregateElement [Term a] [Literal a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (BodyAggregateElement a) where pretty (BodyAggregateElement ts ls) = let ts' = map pretty ts ls' = map pretty ls in hcat (punctuate comma ts') <+> colon <+> hcat (punctuate comma ls') rawBodyAggregateElement :: BodyAggregateElement (Symbol s) -> IO AstBodyAggregateElement rawBodyAggregateElement (BodyAggregateElement ts ls) = do ts' <- newArray' =<< mapM rawTerm ts ls' <- newArray' =<< mapM rawLiteral ls return $ AstBodyAggregateElement ts' (fromIntegral . length $ ts) ls' (fromIntegral . length $ ls) freeBodyAggregateElement :: AstBodyAggregateElement -> IO () freeBodyAggregateElement (AstBodyAggregateElement ts nt ls nl) = do freeArray ts nt freeTerm freeArray ls nl freeLiteral fromRawBodyAggregateElement :: AstBodyAggregateElement -> IO (BodyAggregateElement (Symbol s)) fromRawBodyAggregateElement (AstBodyAggregateElement ts nt ls nl) = BodyAggregateElement <$> (mapM fromRawTerm =<< peekArray (fromIntegral nt) ts) <*> (mapM fromRawLiteral =<< peekArray (fromIntegral nl) ls) data BodyAggregate a = BodyAggregate AggregateFunction [BodyAggregateElement a] (Maybe (AggregateGuard a)) (Maybe (AggregateGuard a)) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (BodyAggregate a) where pretty (BodyAggregate f xs l r) = pretty f <+> pretty l <+> body <+> pretty (fmap aguardPRight r) where body = braces . align . cat $ punctuate semi (map pretty xs) rawBodyAggregate :: BodyAggregate (Symbol s) -> IO AstBodyAggregate rawBodyAggregate (BodyAggregate f es a b) = AstBodyAggregate <$> pure (rawAggregateFunction f) <*> (newArray' =<< mapM rawBodyAggregateElement es) <*> pure (fromIntegral . length $ es) <*> rawAggregateGuardM a <*> rawAggregateGuardM b freeBodyAggregate :: AstBodyAggregate -> IO () freeBodyAggregate (AstBodyAggregate _ es n a b) = do freeArray es n freeBodyAggregateElement freeIndirection a freeAggregateGuard freeIndirection b freeAggregateGuard fromRawBodyAggregate :: AstBodyAggregate -> IO (BodyAggregate (Symbol s)) fromRawBodyAggregate (AstBodyAggregate f es n a b) = BodyAggregate <$> pure (fromRawAggregateFunction f) <*> (mapM fromRawBodyAggregateElement =<< peekArray (fromIntegral n) es) <*> (mapM fromRawAggregateGuard =<< peekMaybe a) <*> (mapM fromRawAggregateGuard =<< peekMaybe b) data AggregateFunction = Count | Sum | Sump | Min | Max deriving (Eq, Show, Ord) instance Pretty AggregateFunction where pretty c = text $ case c of Count -> "#count" Sum -> "#sum" Sump -> "#sump" Min -> "#min" Max -> "#max" rawAggregateFunction :: AggregateFunction -> AstAggregateFunction rawAggregateFunction f = case f of Count -> AstAggregateFunctionCount Sum -> AstAggregateFunctionSum Sump -> AstAggregateFunctionSump Min -> AstAggregateFunctionMin Max -> AstAggregateFunctionMax fromRawAggregateFunction :: AstAggregateFunction -> AggregateFunction fromRawAggregateFunction f = case f of AstAggregateFunctionCount -> Count AstAggregateFunctionSum -> Sum AstAggregateFunctionSump -> Sump AstAggregateFunctionMin -> Min AstAggregateFunctionMax -> Max _ -> error "Invalid clingo_ast_aggregate_function_t" data HeadAggregateElement a = HeadAggregateElement [Term a] (ConditionalLiteral a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (HeadAggregateElement a) where pretty (HeadAggregateElement ts l) = let ts' = map pretty ts in hcat (punctuate comma ts') <+> colon <+> pretty l rawHeadAggregateElement :: HeadAggregateElement (Symbol s) -> IO AstHeadAggregateElement rawHeadAggregateElement (HeadAggregateElement ts l) = AstHeadAggregateElement <$> (newArray' =<< mapM rawTerm ts) <*> pure (fromIntegral . length $ ts) <*> rawConditionalLiteral l freeHeadAggregateElement :: AstHeadAggregateElement -> IO () freeHeadAggregateElement (AstHeadAggregateElement p n l) = do freeArray p n freeTerm freeConditionalLiteral l fromRawHeadAggregateElement :: AstHeadAggregateElement -> IO (HeadAggregateElement (Symbol s)) fromRawHeadAggregateElement (AstHeadAggregateElement ts n l) = HeadAggregateElement <$> (mapM fromRawTerm =<< peekArray (fromIntegral n) ts) <*> fromRawConditionalLiteral l data HeadAggregate a = HeadAggregate AggregateFunction [HeadAggregateElement a] (Maybe (AggregateGuard a)) (Maybe (AggregateGuard a)) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (HeadAggregate a) where pretty (HeadAggregate f xs l r) = pretty f <+> pretty l <+> body <+> pretty (fmap aguardPRight r) where body = braces . align . sep $ punctuate semi (map pretty xs) rawHeadAggregate :: HeadAggregate (Symbol s) -> IO AstHeadAggregate rawHeadAggregate (HeadAggregate f es a b) = AstHeadAggregate <$> pure (rawAggregateFunction f) <*> (newArray' =<< mapM rawHeadAggregateElement es) <*> pure (fromIntegral . length $ es) <*> rawAggregateGuardM a <*> rawAggregateGuardM b freeHeadAggregate :: AstHeadAggregate -> IO () freeHeadAggregate (AstHeadAggregate _ es n a b) = do freeArray es n freeHeadAggregateElement freeIndirection a freeAggregateGuard freeIndirection b freeAggregateGuard fromRawHeadAggregate :: AstHeadAggregate -> IO (HeadAggregate (Symbol s)) fromRawHeadAggregate (AstHeadAggregate f es n a b) = HeadAggregate <$> pure (fromRawAggregateFunction f) <*> (mapM fromRawHeadAggregateElement =<< peekArray (fromIntegral n) es) <*> (mapM fromRawAggregateGuard =<< peekMaybe a) <*> (mapM fromRawAggregateGuard =<< peekMaybe b) data Disjunction a = Disjunction [ConditionalLiteral a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (Disjunction a) where pretty (Disjunction xs) = hcat (punctuate (char '|') $ map pretty xs) rawDisjunction :: Disjunction (Symbol s) -> IO AstDisjunction rawDisjunction (Disjunction ls) = AstDisjunction <$> (newArray' =<< mapM rawConditionalLiteral ls) <*> pure (fromIntegral . length $ ls) freeDisjunction :: AstDisjunction -> IO () freeDisjunction (AstDisjunction ls n) = freeArray ls n freeConditionalLiteral fromRawDisjunction :: AstDisjunction -> IO (Disjunction (Symbol s)) fromRawDisjunction (AstDisjunction ls n) = Disjunction <$> (mapM fromRawConditionalLiteral =<< peekArray (fromIntegral n) ls) data DisjointElement a = DisjointElement Location [Term a] (CspSumTerm a) [Literal a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawDisjointElement :: DisjointElement (Symbol s) -> IO AstDisjointElement rawDisjointElement (DisjointElement l ts s ls) = AstDisjointElement <$> rawLocation l <*> (newArray' =<< mapM rawTerm ts) <*> pure (fromIntegral . length $ ts) <*> rawCspSumTerm s <*> (newArray' =<< mapM rawLiteral ls) <*> pure (fromIntegral . length $ ls) freeDisjointElement :: AstDisjointElement -> IO () freeDisjointElement (AstDisjointElement l ts nt s ls nl) = do freeRawLocation l freeCspSumTerm s freeArray ts nt freeTerm freeArray ls nl freeLiteral fromRawDisjointElement :: AstDisjointElement -> IO (DisjointElement (Symbol s)) fromRawDisjointElement (AstDisjointElement l ts nt s ls nl) = DisjointElement <$> fromRawLocation l <*> (mapM fromRawTerm =<< peekArray (fromIntegral nt) ts) <*> fromRawCspSumTerm s <*> (mapM fromRawLiteral =<< peekArray (fromIntegral nl) ls) data Disjoint a = Disjoint [DisjointElement a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawDisjoint :: Disjoint (Symbol s) -> IO AstDisjoint rawDisjoint (Disjoint es) = AstDisjoint <$> (newArray' =<< mapM rawDisjointElement es) <*> pure (fromIntegral . length $ es) freeDisjoint :: AstDisjoint -> IO () freeDisjoint (AstDisjoint ls n) = freeArray ls n freeDisjointElement fromRawDisjoint :: AstDisjoint -> IO (Disjoint (Symbol s)) fromRawDisjoint (AstDisjoint es n) = Disjoint <$> (mapM fromRawDisjointElement =<< peekArray (fromIntegral n) es) data TheoryTermArray a = TheoryTermArray [TheoryTerm a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawTheoryTermArray :: TheoryTermArray (Symbol s) -> IO AstTheoryTermArray rawTheoryTermArray (TheoryTermArray ts) = AstTheoryTermArray <$> (newArray' =<< mapM rawTheoryTerm ts) <*> pure (fromIntegral . length $ ts) freeTheoryTermArray :: AstTheoryTermArray -> IO () freeTheoryTermArray (AstTheoryTermArray ts n) = freeArray ts n freeTheoryTerm fromRawTheoryTermArray :: AstTheoryTermArray -> IO (TheoryTermArray (Symbol s)) fromRawTheoryTermArray (AstTheoryTermArray ts n) = TheoryTermArray <$> (mapM fromRawTheoryTerm =<< peekArray (fromIntegral n) ts) data TheoryFunction a = TheoryFunction Text [TheoryTerm a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawTheoryFunction :: TheoryFunction (Symbol s) -> IO AstTheoryFunction rawTheoryFunction (TheoryFunction t ts) = AstTheoryFunction <$> newCString (unpack t) <*> (newArray' =<< mapM rawTheoryTerm ts) <*> pure (fromIntegral . length $ ts) freeTheoryFunction :: AstTheoryFunction -> IO () freeTheoryFunction (AstTheoryFunction s p n) = do free s freeArray p n freeTheoryTerm fromRawTheoryFunction :: AstTheoryFunction -> IO (TheoryFunction (Symbol s)) fromRawTheoryFunction (AstTheoryFunction s ts n) = TheoryFunction <$> fmap pack (peekCString s) <*> (mapM fromRawTheoryTerm =<< peekArray (fromIntegral n) ts) data TheoryUnparsedTermElement a = TheoryUnparsedTermElement [Text] (TheoryTerm a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawTheoryUnparsedTermElement :: TheoryUnparsedTermElement (Symbol s) -> IO AstTheoryUnparsedTermElement rawTheoryUnparsedTermElement (TheoryUnparsedTermElement ts t) = AstTheoryUnparsedTermElement <$> (newArray' =<< mapM (newCString . unpack) ts) <*> pure (fromIntegral . length $ ts) <*> rawTheoryTerm t freeTheoryUnparsedTermElement :: AstTheoryUnparsedTermElement -> IO () freeTheoryUnparsedTermElement (AstTheoryUnparsedTermElement ss n t) = do freeTheoryTerm t freeArray ss n free fromRawTheoryUnparsedTermElement :: AstTheoryUnparsedTermElement -> IO (TheoryUnparsedTermElement (Symbol s)) fromRawTheoryUnparsedTermElement (AstTheoryUnparsedTermElement ns n t) = TheoryUnparsedTermElement <$> (mapM (fmap pack . peekCString) =<< peekArray (fromIntegral n) ns) <*> fromRawTheoryTerm t data TheoryUnparsedTerm a = TheoryUnparsedTerm [TheoryUnparsedTermElement a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawTheoryUnparsedTerm :: TheoryUnparsedTerm (Symbol s) -> IO AstTheoryUnparsedTerm rawTheoryUnparsedTerm (TheoryUnparsedTerm es) = AstTheoryUnparsedTerm <$> (newArray' =<< mapM rawTheoryUnparsedTermElement es) <*> pure (fromIntegral . length $ es) freeTheoryUnparsedTerm :: AstTheoryUnparsedTerm -> IO () freeTheoryUnparsedTerm (AstTheoryUnparsedTerm es n) = freeArray es n freeTheoryUnparsedTermElement fromRawTheoryUnparsedTerm :: AstTheoryUnparsedTerm -> IO (TheoryUnparsedTerm (Symbol s)) fromRawTheoryUnparsedTerm (AstTheoryUnparsedTerm es n) = TheoryUnparsedTerm <$> (mapM fromRawTheoryUnparsedTermElement =<< peekArray (fromIntegral n) es) data TheoryTerm a = TheoryTermSymbol Location a | TheoryTermVariable Location Text | TheoryTermTuple Location (TheoryTermArray a) | TheoryTermList Location (TheoryTermArray a) | TheoryTermSet Location (TheoryTermArray a) | TheoryTermFunction Location (TheoryFunction a) | TheoryTermUnparsed Location (TheoryUnparsedTerm a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawTheoryTerm :: TheoryTerm (Symbol s) -> IO AstTheoryTerm rawTheoryTerm (TheoryTermSymbol l s) = AstTheoryTermSymbol <$> rawLocation l <*> pure (rawSymbol s) rawTheoryTerm (TheoryTermVariable l t) = AstTheoryTermVariable <$> rawLocation l <*> newCString (unpack t) rawTheoryTerm (TheoryTermTuple l a) = AstTheoryTermTuple <$> rawLocation l <*> (new =<< rawTheoryTermArray a) rawTheoryTerm (TheoryTermList l a) = AstTheoryTermList <$> rawLocation l <*> (new =<< rawTheoryTermArray a) rawTheoryTerm (TheoryTermSet l a) = AstTheoryTermSet <$> rawLocation l <*> (new =<< rawTheoryTermArray a) rawTheoryTerm (TheoryTermFunction l f) = AstTheoryTermFunction <$> rawLocation l <*> (new =<< rawTheoryFunction f) rawTheoryTerm (TheoryTermUnparsed l t) = AstTheoryTermUnparsed <$> rawLocation l <*> (new =<< rawTheoryUnparsedTerm t) freeTheoryTerm :: AstTheoryTerm -> IO () freeTheoryTerm (AstTheoryTermSymbol l _) = freeRawLocation l freeTheoryTerm (AstTheoryTermVariable l _) = freeRawLocation l freeTheoryTerm (AstTheoryTermTuple l a) = do freeRawLocation l freeIndirection a freeTheoryTermArray freeTheoryTerm (AstTheoryTermList l a) = do freeRawLocation l freeIndirection a freeTheoryTermArray freeTheoryTerm (AstTheoryTermSet l a) = do freeRawLocation l freeIndirection a freeTheoryTermArray freeTheoryTerm (AstTheoryTermFunction l f) = do freeRawLocation l freeIndirection f freeTheoryFunction freeTheoryTerm (AstTheoryTermUnparsed l t) = do freeRawLocation l freeIndirection t freeTheoryUnparsedTerm fromRawTheoryTerm :: AstTheoryTerm -> IO (TheoryTerm (Symbol s)) fromRawTheoryTerm (AstTheoryTermSymbol l s) = TheoryTermSymbol <$> fromRawLocation l <*> pureSymbol s fromRawTheoryTerm (AstTheoryTermVariable l t) = TheoryTermVariable <$> fromRawLocation l <*> fmap pack (peekCString t) fromRawTheoryTerm (AstTheoryTermTuple l a) = TheoryTermTuple <$> fromRawLocation l <*> fromIndirect a fromRawTheoryTermArray fromRawTheoryTerm (AstTheoryTermList l a) = TheoryTermList <$> fromRawLocation l <*> fromIndirect a fromRawTheoryTermArray fromRawTheoryTerm (AstTheoryTermSet l a) = TheoryTermSet <$> fromRawLocation l <*> fromIndirect a fromRawTheoryTermArray fromRawTheoryTerm (AstTheoryTermFunction l f) = TheoryTermFunction <$> fromRawLocation l <*> fromIndirect f fromRawTheoryFunction fromRawTheoryTerm (AstTheoryTermUnparsed l t) = TheoryTermUnparsed <$> fromRawLocation l <*> fromIndirect t fromRawTheoryUnparsedTerm data TheoryAtomElement a = TheoryAtomElement [TheoryTerm a] [Literal a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawTheoryAtomElement :: TheoryAtomElement (Symbol s) -> IO AstTheoryAtomElement rawTheoryAtomElement (TheoryAtomElement ts ls) = AstTheoryAtomElement <$> (newArray' =<< mapM rawTheoryTerm ts) <*> pure (fromIntegral . length $ ts) <*> (newArray' =<< mapM rawLiteral ls) <*> pure (fromIntegral . length $ ls) freeTheoryAtomElement :: AstTheoryAtomElement -> IO () freeTheoryAtomElement (AstTheoryAtomElement ts nt ls nl) = do freeArray ts nt freeTheoryTerm freeArray ls nl freeLiteral fromRawTheoryAtomElement :: AstTheoryAtomElement -> IO (TheoryAtomElement (Symbol s)) fromRawTheoryAtomElement (AstTheoryAtomElement ts nt ls nl) = TheoryAtomElement <$> (mapM fromRawTheoryTerm =<< peekArray (fromIntegral nt) ts) <*> (mapM fromRawLiteral =<< peekArray (fromIntegral nl) ls) data TheoryGuard a = TheoryGuard Text (TheoryTerm a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawTheoryGuard :: TheoryGuard (Symbol s) -> IO AstTheoryGuard rawTheoryGuard (TheoryGuard s t) = AstTheoryGuard <$> newCString (unpack s) <*> rawTheoryTerm t freeTheoryGuard :: AstTheoryGuard -> IO () freeTheoryGuard (AstTheoryGuard s t) = free s >> freeTheoryTerm t fromRawTheoryGuard :: AstTheoryGuard -> IO (TheoryGuard (Symbol s)) fromRawTheoryGuard (AstTheoryGuard n t) = TheoryGuard <$> fmap pack (peekCString n) <*> fromRawTheoryTerm t data TheoryAtom a = TheoryAtom (Term a) [TheoryAtomElement a] (TheoryGuard a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawTheoryAtom :: TheoryAtom (Symbol s) -> IO AstTheoryAtom rawTheoryAtom (TheoryAtom t es g) = AstTheoryAtom <$> rawTerm t <*> (newArray' =<< mapM rawTheoryAtomElement es) <*> pure (fromIntegral . length $ es) <*> rawTheoryGuard g freeTheoryAtom :: AstTheoryAtom -> IO () freeTheoryAtom (AstTheoryAtom t es n g) = do freeTerm t freeTheoryGuard g freeArray es n freeTheoryAtomElement fromRawTheoryAtom :: AstTheoryAtom -> IO (TheoryAtom (Symbol s)) fromRawTheoryAtom (AstTheoryAtom t es n g) = TheoryAtom <$> fromRawTerm t <*> (mapM fromRawTheoryAtomElement =<< peekArray (fromIntegral n) es) <*> fromRawTheoryGuard g data HeadLiteral a = HeadLiteral Location (Literal a) | HeadDisjunction Location (Disjunction a) | HeadLitAggregate Location (Aggregate a) | HeadHeadAggregate Location (HeadAggregate a) | HeadTheoryAtom Location (TheoryAtom a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (HeadLiteral a) where pretty (HeadLiteral _ l) = pretty l pretty (HeadDisjunction _ d) = pretty d pretty (HeadLitAggregate _ a) = pretty a pretty (HeadHeadAggregate _ a) = pretty a pretty (HeadTheoryAtom _ _) = text "<theoryAtom>" -- TODO! rawHeadLiteral :: HeadLiteral (Symbol s) -> IO AstHeadLiteral rawHeadLiteral (HeadLiteral l x) = AstHeadLiteral <$> rawLocation l <*> (new =<< rawLiteral x) rawHeadLiteral (HeadDisjunction l d) = AstHeadDisjunction <$> rawLocation l <*> (new =<< rawDisjunction d) rawHeadLiteral (HeadLitAggregate l d) = AstHeadLitAggregate <$> rawLocation l <*> (new =<< rawAggregate d) rawHeadLiteral (HeadHeadAggregate l d) = AstHeadHeadAggregate <$> rawLocation l <*> (new =<< rawHeadAggregate d) rawHeadLiteral (HeadTheoryAtom l d) = AstHeadTheoryAtom <$> rawLocation l <*> (new =<< rawTheoryAtom d) freeHeadLiteral :: AstHeadLiteral -> IO () freeHeadLiteral (AstHeadLiteral l x) = do freeRawLocation l freeIndirection x freeLiteral freeHeadLiteral (AstHeadDisjunction l x) = do freeRawLocation l freeIndirection x freeDisjunction freeHeadLiteral (AstHeadLitAggregate l x) = do freeRawLocation l freeIndirection x freeAggregate freeHeadLiteral (AstHeadHeadAggregate l x) = do freeRawLocation l freeIndirection x freeHeadAggregate freeHeadLiteral (AstHeadTheoryAtom l x) = do freeRawLocation l freeIndirection x freeTheoryAtom fromRawHeadLiteral :: AstHeadLiteral -> IO (HeadLiteral (Symbol s)) fromRawHeadLiteral (AstHeadLiteral l x) = HeadLiteral <$> fromRawLocation l <*> fromIndirect x fromRawLiteral fromRawHeadLiteral (AstHeadDisjunction l x) = HeadDisjunction <$> fromRawLocation l <*> fromIndirect x fromRawDisjunction fromRawHeadLiteral (AstHeadLitAggregate l x) = HeadLitAggregate <$> fromRawLocation l <*> fromIndirect x fromRawAggregate fromRawHeadLiteral (AstHeadHeadAggregate l x) = HeadHeadAggregate <$> fromRawLocation l <*> fromIndirect x fromRawHeadAggregate fromRawHeadLiteral (AstHeadTheoryAtom l x) = HeadTheoryAtom <$> fromRawLocation l <*> fromIndirect x fromRawTheoryAtom data BodyLiteral a = BodyLiteral Location Sign (Literal a) | BodyConditional Location (ConditionalLiteral a) | BodyLitAggregate Location Sign (Aggregate a) | BodyBodyAggregate Location Sign (BodyAggregate a) | BodyTheoryAtom Location Sign (TheoryAtom a) | BodyDisjoint Location Sign (Disjoint a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (BodyLiteral a) where pretty (BodyLiteral _ s l) = pretty s <+> pretty l pretty (BodyConditional _ c) = pretty c pretty (BodyLitAggregate _ s a) = pretty s <+> pretty a pretty (BodyBodyAggregate _ s a) = pretty s <+> pretty a pretty (BodyTheoryAtom _ s _) = pretty s <+> text "<theoryAtom>" -- TODO pretty (BodyDisjoint _ s _) = pretty s <+> text "<disjoint>" -- TODO rawBodyLiteral :: BodyLiteral (Symbol s) -> IO AstBodyLiteral rawBodyLiteral (BodyLiteral l s x) = AstBodyLiteral <$> rawLocation l <*> pure (rawSign s) <*> (new =<< rawLiteral x) rawBodyLiteral (BodyConditional l x) = AstBodyConditional <$> rawLocation l <*> (new =<< rawConditionalLiteral x) rawBodyLiteral (BodyLitAggregate l s x) = AstBodyLitAggregate <$> rawLocation l <*> pure (rawSign s) <*> (new =<< rawAggregate x) rawBodyLiteral (BodyBodyAggregate l s x) = AstBodyBodyAggregate <$> rawLocation l <*> pure (rawSign s) <*> (new =<< rawBodyAggregate x) rawBodyLiteral (BodyTheoryAtom l s x) = AstBodyTheoryAtom <$> rawLocation l <*> pure (rawSign s) <*> (new =<< rawTheoryAtom x) rawBodyLiteral (BodyDisjoint l s x) = AstBodyDisjoint <$> rawLocation l <*> pure (rawSign s) <*> (new =<< rawDisjoint x) freeBodyLiteral :: AstBodyLiteral -> IO () freeBodyLiteral (AstBodyLiteral l _ x) = do freeRawLocation l freeIndirection x freeLiteral freeBodyLiteral (AstBodyConditional l x) = do freeRawLocation l freeIndirection x freeConditionalLiteral freeBodyLiteral (AstBodyLitAggregate l _ x) = do freeRawLocation l freeIndirection x freeAggregate freeBodyLiteral (AstBodyBodyAggregate l _ x) = do freeRawLocation l freeIndirection x freeBodyAggregate freeBodyLiteral (AstBodyTheoryAtom l _ x) = do freeRawLocation l freeIndirection x freeTheoryAtom freeBodyLiteral (AstBodyDisjoint l _ x) = do freeRawLocation l freeIndirection x freeDisjoint fromRawBodyLiteral :: AstBodyLiteral -> IO (BodyLiteral (Symbol s)) fromRawBodyLiteral (AstBodyLiteral l s x) = BodyLiteral <$> fromRawLocation l <*> pure (fromRawSign s) <*> fromIndirect x fromRawLiteral fromRawBodyLiteral (AstBodyConditional l x) = BodyConditional <$> fromRawLocation l <*> fromIndirect x fromRawConditionalLiteral fromRawBodyLiteral (AstBodyLitAggregate l s x) = BodyLitAggregate <$> fromRawLocation l <*> pure (fromRawSign s) <*> fromIndirect x fromRawAggregate fromRawBodyLiteral (AstBodyBodyAggregate l s x) = BodyBodyAggregate <$> fromRawLocation l <*> pure (fromRawSign s) <*> fromIndirect x fromRawBodyAggregate fromRawBodyLiteral (AstBodyTheoryAtom l s x) = BodyTheoryAtom <$> fromRawLocation l <*> pure (fromRawSign s) <*> fromIndirect x fromRawTheoryAtom fromRawBodyLiteral (AstBodyDisjoint l s x) = BodyDisjoint <$> fromRawLocation l <*> pure (fromRawSign s) <*> fromIndirect x fromRawDisjoint data TheoryOperatorDefinition = TheoryOperatorDefinition Location Text Natural TheoryOperatorType deriving (Eq, Show, Ord) rawTheoryOperatorDefinition :: TheoryOperatorDefinition -> IO AstTheoryOperatorDefinition rawTheoryOperatorDefinition (TheoryOperatorDefinition l s x t) = AstTheoryOperatorDefinition <$> rawLocation l <*> newCString (unpack s) <*> pure (fromIntegral x) <*> pure (rawTheoryOperatorType t) freeTheoryOperatorDefinition :: AstTheoryOperatorDefinition -> IO () freeTheoryOperatorDefinition (AstTheoryOperatorDefinition l s _ _) = freeRawLocation l >> free s fromRawTheoryOperatorDefinition :: AstTheoryOperatorDefinition -> IO TheoryOperatorDefinition fromRawTheoryOperatorDefinition (AstTheoryOperatorDefinition l s i t) = TheoryOperatorDefinition <$> fromRawLocation l <*> fmap pack (peekCString s) <*> pure (fromIntegral i) <*> pure (fromRawTheoryOperatorType t) data TheoryOperatorType = Unary | BinLeft | BinRight deriving (Eq, Show, Ord) rawTheoryOperatorType :: TheoryOperatorType -> AstTheoryOperatorType rawTheoryOperatorType t = case t of Unary -> AstTheoryOperatorTypeUnary BinLeft -> AstTheoryOperatorTypeBinaryLeft BinRight -> AstTheoryOperatorTypeBinaryRight fromRawTheoryOperatorType :: AstTheoryOperatorType -> TheoryOperatorType fromRawTheoryOperatorType t = case t of AstTheoryOperatorTypeUnary -> Unary AstTheoryOperatorTypeBinaryLeft -> BinLeft AstTheoryOperatorTypeBinaryRight -> BinRight _ -> error "Invalid clingo_ast_theory_operator_type_t" data TheoryTermDefinition = TheoryTermDefinition Location Text [TheoryOperatorDefinition] deriving (Eq, Show, Ord) rawTheoryTermDefinition :: TheoryTermDefinition -> IO AstTheoryTermDefinition rawTheoryTermDefinition (TheoryTermDefinition l s xs) = AstTheoryTermDefinition <$> rawLocation l <*> newCString (unpack s) <*> (newArray' =<< mapM rawTheoryOperatorDefinition xs) <*> pure (fromIntegral . length $ xs) freeTheoryTermDefinition :: AstTheoryTermDefinition -> IO () freeTheoryTermDefinition (AstTheoryTermDefinition l s xs n) = do freeRawLocation l free s freeArray xs n freeTheoryOperatorDefinition fromRawTheoryTermDefinition :: AstTheoryTermDefinition -> IO TheoryTermDefinition fromRawTheoryTermDefinition (AstTheoryTermDefinition l s es n) = TheoryTermDefinition <$> fromRawLocation l <*> fmap pack (peekCString s) <*> (mapM fromRawTheoryOperatorDefinition =<< peekArray (fromIntegral n) es) data TheoryGuardDefinition = TheoryGuardDefinition Text [Text] deriving (Eq, Show, Ord) rawTheoryGuardDefinition :: TheoryGuardDefinition -> IO AstTheoryGuardDefinition rawTheoryGuardDefinition (TheoryGuardDefinition t ts) = AstTheoryGuardDefinition <$> newCString (unpack t) <*> (newArray' =<< mapM (newCString . unpack) ts) <*> pure (fromIntegral . length $ ts) freeTheoryGuardDefinition :: AstTheoryGuardDefinition -> IO () freeTheoryGuardDefinition (AstTheoryGuardDefinition s ss n) = do free s freeArray ss n free fromRawTheoryGuardDefinition :: AstTheoryGuardDefinition -> IO TheoryGuardDefinition fromRawTheoryGuardDefinition (AstTheoryGuardDefinition t ts n) = TheoryGuardDefinition <$> fmap pack (peekCString t) <*> (mapM (fmap pack . peekCString) =<< peekArray (fromIntegral n) ts) data TheoryAtomDefinition = TheoryAtomDefinition Location TheoryAtomDefinitionType Text Int Text TheoryGuardDefinition deriving (Eq, Show, Ord) rawTheoryAtomDefinition :: TheoryAtomDefinition -> IO AstTheoryAtomDefinition rawTheoryAtomDefinition (TheoryAtomDefinition l t a i b d) = AstTheoryAtomDefinition <$> rawLocation l <*> pure (rawTheoryAtomDefinitionType t) <*> newCString (unpack a) <*> pure (fromIntegral i) <*> newCString (unpack b) <*> (new =<< rawTheoryGuardDefinition d) freeTheoryAtomDefinition :: AstTheoryAtomDefinition -> IO () freeTheoryAtomDefinition (AstTheoryAtomDefinition l _ a _ b p) = do freeRawLocation l free a free b freeIndirection p freeTheoryGuardDefinition fromRawTheoryAtomDefinition :: AstTheoryAtomDefinition -> IO TheoryAtomDefinition fromRawTheoryAtomDefinition (AstTheoryAtomDefinition l t a i b g) = TheoryAtomDefinition <$> fromRawLocation l <*> pure (fromRawTheoryAtomDefinitionType t) <*> fmap pack (peekCString a) <*> pure (fromIntegral i) <*> fmap pack (peekCString b) <*> fromIndirect g fromRawTheoryGuardDefinition data TheoryAtomDefinitionType = Head | Body | Any | Directive deriving (Eq, Show, Ord) rawTheoryAtomDefinitionType :: TheoryAtomDefinitionType -> AstTheoryAtomDefType rawTheoryAtomDefinitionType t = case t of Head -> AstTheoryAtomDefinitionTypeHead Body -> AstTheoryAtomDefinitionTypeBody Any -> AstTheoryAtomDefinitionTypeAny Directive -> AstTheoryAtomDefinitionTypeDirective fromRawTheoryAtomDefinitionType :: AstTheoryAtomDefType -> TheoryAtomDefinitionType fromRawTheoryAtomDefinitionType t = case t of AstTheoryAtomDefinitionTypeHead -> Head AstTheoryAtomDefinitionTypeBody -> Body AstTheoryAtomDefinitionTypeAny -> Any AstTheoryAtomDefinitionTypeDirective -> Directive _ -> error "Invalid clingo_ast_theory_atom_definition_type_t" data TheoryDefinition = TheoryDefinition Text [TheoryTermDefinition] [TheoryAtomDefinition] deriving (Eq, Show, Ord) rawTheoryDefinition :: TheoryDefinition -> IO AstTheoryDefinition rawTheoryDefinition (TheoryDefinition t ts as) = AstTheoryDefinition <$> newCString (unpack t) <*> (newArray' =<< mapM rawTheoryTermDefinition ts) <*> pure (fromIntegral . length $ ts) <*> (newArray' =<< mapM rawTheoryAtomDefinition as) <*> pure (fromIntegral . length $ as) freeTheoryDefinition :: AstTheoryDefinition -> IO () freeTheoryDefinition (AstTheoryDefinition t ts nt as na) = do free t freeArray ts nt freeTheoryTermDefinition freeArray as na freeTheoryAtomDefinition fromRawTheoryDefinition :: AstTheoryDefinition -> IO TheoryDefinition fromRawTheoryDefinition (AstTheoryDefinition s ts nt as na) = TheoryDefinition <$> fmap pack (peekCString s) <*> (mapM fromRawTheoryTermDefinition =<< peekArray (fromIntegral nt) ts) <*> (mapM fromRawTheoryAtomDefinition =<< peekArray (fromIntegral na) as) data Rule a = Rule (HeadLiteral a) [BodyLiteral a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (Rule a) where pretty (Rule h []) = pretty h pretty (Rule h bs) = pretty h <+> text ":-" <+> align (sep (punctuate comma (map pretty bs))) rawRule :: Rule (Symbol s) -> IO AstRule rawRule (Rule h bs) = AstRule <$> rawHeadLiteral h <*> (newArray' =<< mapM rawBodyLiteral bs) <*> pure (fromIntegral . length $ bs) freeRule :: AstRule -> IO () freeRule (AstRule h bs n) = do freeHeadLiteral h freeArray bs n freeBodyLiteral fromRawRule :: AstRule -> IO (Rule (Symbol s)) fromRawRule (AstRule h bs n) = Rule <$> fromRawHeadLiteral h <*> (mapM fromRawBodyLiteral =<< peekArray (fromIntegral n) bs) data Definition a = Definition Text (Term a) Bool deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawDefinition :: Definition (Symbol s) -> IO AstDefinition rawDefinition (Definition s t b) = AstDefinition <$> newCString (unpack s) <*> rawTerm t <*> pure (fromBool b) freeDefinition :: AstDefinition -> IO () freeDefinition (AstDefinition s t _) = free s >> freeTerm t fromRawDefinition :: AstDefinition -> IO (Definition (Symbol s)) fromRawDefinition (AstDefinition s t b) = Definition <$> fmap pack (peekCString s) <*> fromRawTerm t <*> pure (toBool b) data ShowSignature b = ShowSignature b Bool deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawShowSignature :: ShowSignature (Signature b) -> IO AstShowSignature rawShowSignature (ShowSignature s b) = AstShowSignature <$> pure (rawSignature s) <*> pure (fromBool b) freeShowSignature :: AstShowSignature -> IO () freeShowSignature (AstShowSignature _ _) = return () fromRawShowSignature :: AstShowSignature -> IO (ShowSignature (Signature s)) fromRawShowSignature (AstShowSignature s b) = ShowSignature <$> pureSignature s <*> pure (toBool b) data ShowTerm a = ShowTerm (Term a) [BodyLiteral a] Bool deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawShowTerm :: ShowTerm (Symbol s) -> IO AstShowTerm rawShowTerm (ShowTerm t ls b) = AstShowTerm <$> rawTerm t <*> (newArray' =<< mapM rawBodyLiteral ls) <*> pure (fromIntegral . length $ ls) <*> pure (fromBool b) freeShowTerm :: AstShowTerm -> IO () freeShowTerm (AstShowTerm t ls n _) = do freeTerm t freeArray ls n freeBodyLiteral fromRawShowTerm :: AstShowTerm -> IO (ShowTerm (Symbol s)) fromRawShowTerm (AstShowTerm t ls n b) = ShowTerm <$> fromRawTerm t <*> (mapM fromRawBodyLiteral =<< peekArray (fromIntegral n) ls) <*> pure (toBool b) data Minimize a = Minimize (Term a) (Term a) [Term a] [BodyLiteral a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawMinimize :: Minimize (Symbol s) -> IO AstMinimize rawMinimize (Minimize a b ts ls) = AstMinimize <$> rawTerm a <*> rawTerm b <*> (newArray' =<< mapM rawTerm ts) <*> pure (fromIntegral . length $ ts) <*> (newArray' =<< mapM rawBodyLiteral ls) <*> pure (fromIntegral . length $ ls) freeMinimize :: AstMinimize -> IO () freeMinimize (AstMinimize a b ts nt ls nl) = do freeTerm a freeTerm b freeArray ts nt freeTerm freeArray ls nl freeBodyLiteral fromRawMinimize :: AstMinimize -> IO (Minimize (Symbol s)) fromRawMinimize (AstMinimize a b ts nt ls nl) = Minimize <$> fromRawTerm a <*> fromRawTerm b <*> (mapM fromRawTerm =<< peekArray (fromIntegral nt) ts) <*> (mapM fromRawBodyLiteral =<< peekArray (fromIntegral nl) ls) data Script = Script ScriptType Text deriving (Eq, Show, Ord) rawScript :: Script -> IO AstScript rawScript (Script t s) = AstScript <$> pure (rawScriptType t) <*> newCString (unpack s) freeScript :: AstScript -> IO () freeScript (AstScript _ s) = free s fromRawScript :: AstScript -> IO Script fromRawScript (AstScript t s) = Script <$> pure (fromRawScriptType t) <*> fmap pack (peekCString s) data ScriptType = Lua | Python deriving (Eq, Show, Ord) rawScriptType :: ScriptType -> AstScriptType rawScriptType t = case t of Lua -> AstScriptTypeLua Python -> AstScriptTypePython fromRawScriptType :: AstScriptType -> ScriptType fromRawScriptType t = case t of AstScriptTypeLua -> Lua AstScriptTypePython -> Python _ -> error "Invalid clingo_ast_script_type_t" data Program = Program Text [Identifier] deriving (Eq, Show, Ord) instance Pretty Program where pretty (Program n []) = text "#program" <+> text (fromStrict n) pretty (Program n is) = text "#program" <+> text (fromStrict n) <> tupled (map pretty is) rawProgram :: Program -> IO AstProgram rawProgram (Program n is) = AstProgram <$> newCString (unpack n) <*> (newArray' =<< mapM rawIdentifier is) <*> pure (fromIntegral . length $ is) freeProgram :: AstProgram -> IO () freeProgram (AstProgram s xs n) = free s >> freeArray xs n freeIdentifier fromRawProgram :: AstProgram -> IO Program fromRawProgram (AstProgram s es n) = Program <$> fmap pack (peekCString s) <*> (mapM fromRawIdentifier =<< peekArray (fromIntegral n) es) data External a = External (Term a) [BodyLiteral a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (External a) where pretty (External n []) = text "#external" <+> pretty n pretty (External n is) = text "#external" <+> pretty n <> tupled (map pretty is) rawExternal :: External (Symbol s) -> IO AstExternal rawExternal (External t ls) = AstExternal <$> rawTerm t <*> (newArray' =<< mapM rawBodyLiteral ls) <*> pure (fromIntegral . length $ ls) freeExternal :: AstExternal -> IO () freeExternal (AstExternal t ls n) = freeTerm t >> freeArray ls n freeBodyLiteral fromRawExternal :: AstExternal -> IO (External (Symbol s)) fromRawExternal (AstExternal t ls n) = External <$> fromRawTerm t <*> (mapM fromRawBodyLiteral =<< peekArray (fromIntegral n) ls) data Edge a = Edge (Term a) (Term a) [BodyLiteral a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawEdge :: Edge (Symbol s) -> IO AstEdge rawEdge (Edge a b ls) = AstEdge <$> rawTerm a <*> rawTerm b <*> (newArray' =<< mapM rawBodyLiteral ls) <*> pure (fromIntegral . length $ ls) freeEdge :: AstEdge -> IO () freeEdge (AstEdge a b ls n) = do freeTerm a freeTerm b freeArray ls n freeBodyLiteral fromRawEdge :: AstEdge -> IO (Edge (Symbol s)) fromRawEdge (AstEdge a b ls n) = Edge <$> fromRawTerm a <*> fromRawTerm b <*> (mapM fromRawBodyLiteral =<< peekArray (fromIntegral n) ls) data Heuristic a = Heuristic (Term a) [BodyLiteral a] (Term a) (Term a) (Term a) deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance Pretty a => Pretty (Heuristic a) where pretty (Heuristic t1 [] t2 t3 t4) = text "#heuristic" <+> pretty t1 <> dot <+> char '[' <+> pretty t2 <> char '@' <> pretty t3 <+> comma <+> pretty t4 <+> char ']' pretty (Heuristic t1 cs t2 t3 t4) = text "#heuristic" <+> pretty t1 <+> colon <+> list (map pretty cs) <> dot <+> char '[' <+> pretty t2 <> char '@' <> pretty t3 <+> comma <+> pretty t4 <+> char ']' rawHeuristic :: Heuristic (Symbol s) -> IO AstHeuristic rawHeuristic (Heuristic a ls b c d) = AstHeuristic <$> rawTerm a <*> (newArray' =<< mapM rawBodyLiteral ls) <*> pure (fromIntegral . length $ ls) <*> rawTerm b <*> rawTerm c <*> rawTerm d freeHeuristic :: AstHeuristic -> IO () freeHeuristic (AstHeuristic a ls n b c d) = do freeTerm a freeTerm b freeTerm c freeTerm d freeArray ls n freeBodyLiteral fromRawHeuristic :: AstHeuristic -> IO (Heuristic (Symbol s)) fromRawHeuristic (AstHeuristic t ls n a b c) = Heuristic <$> fromRawTerm t <*> (mapM fromRawBodyLiteral =<< peekArray (fromIntegral n) ls) <*> fromRawTerm a <*> fromRawTerm b <*> fromRawTerm c data Project a = Project (Term a) [BodyLiteral a] deriving (Eq, Show, Ord, Functor, Foldable, Traversable) rawProject :: Project (Symbol s) -> IO AstProject rawProject (Project t ls) = AstProject <$> rawTerm t <*> (newArray' =<< mapM rawBodyLiteral ls) <*> pure (fromIntegral . length $ ls) freeProject :: AstProject -> IO () freeProject (AstProject t ls n) = do freeTerm t freeArray ls n freeBodyLiteral fromRawProject :: AstProject -> IO (Project (Symbol s)) fromRawProject (AstProject t ls n) = Project <$> fromRawTerm t <*> (mapM fromRawBodyLiteral =<< peekArray (fromIntegral n) ls) data Statement a b = StmtRule Location (Rule a) | StmtDefinition Location (Definition a) | StmtShowSignature Location (ShowSignature b) | StmtShowTerm Location (ShowTerm a) | StmtMinimize Location (Minimize a) | StmtScript Location Script | StmtProgram Location Program | StmtExternal Location (External a) | StmtEdge Location (Edge a) | StmtHeuristic Location (Heuristic a) | StmtProject Location (Project a) | StmtSignature Location b | StmtTheoryDefinition Location TheoryDefinition deriving (Eq, Show, Ord, Functor, Foldable, Traversable) instance (Pretty a, Pretty b) => Pretty (Statement a b) where pretty (StmtRule _ r) = pretty r <> dot pretty (StmtSignature _ s) = pretty s <> dot pretty (StmtProgram _ p) = pretty p <> dot pretty (StmtExternal _ p) = pretty p <> dot pretty (StmtHeuristic _ p) = pretty p pretty _ = text "<stmt>" -- TODO instance Bifunctor Statement where bimap f g s = case s of StmtRule l x -> StmtRule l (fmap f x) StmtDefinition l x -> StmtDefinition l (fmap f x) StmtShowSignature l x -> StmtShowSignature l (fmap g x) StmtShowTerm l x -> StmtShowTerm l (fmap f x) StmtMinimize l x -> StmtMinimize l (fmap f x) StmtScript l x -> StmtScript l x StmtProgram l x -> StmtProgram l x StmtExternal l x -> StmtExternal l (fmap f x) StmtEdge l x -> StmtEdge l (fmap f x) StmtHeuristic l x -> StmtHeuristic l (fmap f x) StmtProject l x -> StmtProject l (fmap f x) StmtSignature l x -> StmtSignature l (g x) StmtTheoryDefinition l x -> StmtTheoryDefinition l x instance Bifoldable Statement where bifoldr f g z s = case s of StmtRule _ x -> foldr f z x StmtDefinition _ x -> foldr f z x StmtShowSignature _ x -> foldr g z x StmtShowTerm _ x -> foldr f z x StmtMinimize _ x -> foldr f z x StmtScript _ _ -> z StmtProgram _ _ -> z StmtExternal _ x -> foldr f z x StmtEdge _ x -> foldr f z x StmtHeuristic _ x -> foldr f z x StmtProject _ x -> foldr f z x StmtSignature _ x -> g x z StmtTheoryDefinition _ _ -> z instance Bitraversable Statement where bitraverse f g s = case s of StmtRule l x -> StmtRule l <$> traverse f x StmtDefinition l x -> StmtDefinition l <$> traverse f x StmtShowSignature l x -> StmtShowSignature l <$> traverse g x StmtShowTerm l x -> StmtShowTerm l <$> traverse f x StmtMinimize l x -> StmtMinimize l <$> traverse f x StmtScript l x -> pure $ StmtScript l x StmtProgram l x -> pure $ StmtProgram l x StmtExternal l x -> StmtExternal l <$> traverse f x StmtEdge l x -> StmtEdge l <$> traverse f x StmtHeuristic l x -> StmtHeuristic l <$> traverse f x StmtProject l x -> StmtProject l <$> traverse f x StmtSignature l x -> StmtSignature l <$> g x StmtTheoryDefinition l x -> pure $ StmtTheoryDefinition l x rawStatement :: Statement (Symbol s) (Signature s) -> IO AstStatement rawStatement (StmtRule l x) = AstStmtRule <$> rawLocation l <*> (new =<< rawRule x) rawStatement (StmtDefinition l x) = AstStmtDefinition <$> rawLocation l <*> (new =<< rawDefinition x) rawStatement (StmtShowSignature l x) = AstStmtShowSignature <$> rawLocation l <*> (new =<< rawShowSignature x) rawStatement (StmtShowTerm l x) = AstStmtShowTerm <$> rawLocation l <*> (new =<< rawShowTerm x) rawStatement (StmtMinimize l x) = AstStmtMinimize <$> rawLocation l <*> (new =<< rawMinimize x) rawStatement (StmtScript l x) = AstStmtScript <$> rawLocation l <*> (new =<< rawScript x) rawStatement (StmtProgram l x) = AstStmtProgram <$> rawLocation l <*> (new =<< rawProgram x) rawStatement (StmtExternal l x) = AstStmtExternal <$> rawLocation l <*> (new =<< rawExternal x) rawStatement (StmtEdge l x) = AstStmtEdge <$> rawLocation l <*> (new =<< rawEdge x) rawStatement (StmtHeuristic l x) = AstStmtHeuristic <$> rawLocation l <*> (new =<< rawHeuristic x) rawStatement (StmtProject l x) = AstStmtProject <$> rawLocation l <*> (new =<< rawProject x) rawStatement (StmtSignature l x) = AstStmtSignature <$> rawLocation l <*> pure (rawSignature x) rawStatement (StmtTheoryDefinition l x) = AstStmtTheoryDefn <$> rawLocation l <*> (new =<< rawTheoryDefinition x) freeStatement :: AstStatement -> IO () freeStatement (AstStmtRule l x) = freeRawLocation l >> freeIndirection x freeRule freeStatement (AstStmtDefinition l x) = freeRawLocation l >> freeIndirection x freeDefinition freeStatement (AstStmtShowSignature l x) = freeRawLocation l >> freeIndirection x freeShowSignature freeStatement (AstStmtShowTerm l x) = freeRawLocation l >> freeIndirection x freeShowTerm freeStatement (AstStmtMinimize l x) = freeRawLocation l >> freeIndirection x freeMinimize freeStatement (AstStmtScript l x) = freeRawLocation l >> freeIndirection x freeScript freeStatement (AstStmtProgram l x) = freeRawLocation l >> freeIndirection x freeProgram freeStatement (AstStmtExternal l x) = freeRawLocation l >> freeIndirection x freeExternal freeStatement (AstStmtEdge l x) = freeRawLocation l >> freeIndirection x freeEdge freeStatement (AstStmtHeuristic l x) = freeRawLocation l >> freeIndirection x freeHeuristic freeStatement (AstStmtProject l x) = freeRawLocation l >> freeIndirection x freeProject freeStatement (AstStmtSignature l _) = freeRawLocation l freeStatement (AstStmtTheoryDefn l x) = freeRawLocation l >> freeIndirection x freeTheoryDefinition fromRawStatement :: AstStatement -> IO (Statement (Symbol s) (Signature s)) fromRawStatement (AstStmtRule l x) = StmtRule <$> fromRawLocation l <*> fromIndirect x fromRawRule fromRawStatement (AstStmtDefinition l x) = StmtDefinition <$> fromRawLocation l <*> fromIndirect x fromRawDefinition fromRawStatement (AstStmtShowSignature l x) = StmtShowSignature <$> fromRawLocation l <*> fromIndirect x fromRawShowSignature fromRawStatement (AstStmtShowTerm l x) = StmtShowTerm <$> fromRawLocation l <*> fromIndirect x fromRawShowTerm fromRawStatement (AstStmtMinimize l x) = StmtMinimize <$> fromRawLocation l <*> fromIndirect x fromRawMinimize fromRawStatement (AstStmtScript l x) = StmtScript <$> fromRawLocation l <*> fromIndirect x fromRawScript fromRawStatement (AstStmtProgram l x) = StmtProgram <$> fromRawLocation l <*> fromIndirect x fromRawProgram fromRawStatement (AstStmtExternal l x) = StmtExternal <$> fromRawLocation l <*> fromIndirect x fromRawExternal fromRawStatement (AstStmtEdge l x) = StmtEdge <$> fromRawLocation l <*> fromIndirect x fromRawEdge fromRawStatement (AstStmtHeuristic l x) = StmtHeuristic <$> fromRawLocation l <*> fromIndirect x fromRawHeuristic fromRawStatement (AstStmtProject l x) = StmtProject <$> fromRawLocation l <*> fromIndirect x fromRawProject fromRawStatement (AstStmtSignature l x) = StmtSignature <$> fromRawLocation l <*> pureSignature x fromRawStatement (AstStmtTheoryDefn l x) = StmtTheoryDefinition <$> fromRawLocation l <*> fromIndirect x fromRawTheoryDefinition
tsahyt/clingo-haskell
src/Clingo/Internal/AST.hs
mit
67,391
0
17
13,976
21,938
10,655
11,283
1,422
9
{-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE FlexibleContexts #-} module Yage.Rendering.Mesh ( module Yage.Rendering.Mesh , module E ) where import Yage.Prelude hiding (Index, toList) import Yage.Lens hiding (snoc) import qualified Data.Vector.Storable as VS import qualified Data.Vector as V import Data.Foldable (toList) import Data.List (mapAccumL) import qualified Data.Digest.XXHash as XH import qualified Data.Vector.Storable.ByteString as BS import Data.Bits import Yage.Geometry import Yage.Geometry.Elements as E (Triangle(..)) --------------------------------------------------------------------------------------------------- type MeshHash = XH.XXHash type MeshId = ByteString -- TODO: Materials to component data MeshComponent = MeshComponent { _componentId :: MeshId , _componentIndexBuffer :: (VS.Vector Int) , _componentHash :: MeshHash } deriving ( Typeable, Generic ) -- TODO: smart vertex book-keeping? data Mesh v = Mesh { _meshId :: MeshId , _meshVertexBuffer :: (VS.Vector v) , _meshComponents :: (Map MeshId MeshComponent) , _meshHash :: MeshHash } deriving ( Typeable, Generic ) makeLenses ''MeshComponent makeLenses ''Mesh instance (Storable v) => Show (Mesh v) where show Mesh{..} = show $ format "Mesh { id = {}, #vertexBuffer = {}, meshHash = {}, components = {} }" ( Shown _meshId , Shown $ VS.length _meshVertexBuffer --, Shown $ _meshVertexBuffer , hex _meshHash , Shown $ _meshComponents^..traverse ) instance Show MeshComponent where show MeshComponent{..} = show $ format "MeshComponent { id = {}, #indexBuffer = {}-{}, hash = {} }" ( Shown _componentId , Shown $ VS.length _componentIndexBuffer , Shown $ _componentIndexBuffer , hex _componentHash ) instance Eq (Mesh v) where a == b = _meshId a == _meshId b instance Ord (Mesh v) where compare a b = compare (_meshId a) (_meshId b) instance NFData v => NFData (Mesh v) where rnf = genericRnf instance NFData MeshComponent where rnf = genericRnf vertexCount :: Storable v => Getter (Mesh v) Int vertexCount = meshVertexBuffer.to VS.length {-# INLINE vertexCount #-} componentCount :: Getter (Mesh v) Int componentCount = meshComponents.to (lengthOf traverse) {-# INLINE componentCount #-} indexCount :: Getter MeshComponent Int indexCount = componentIndexBuffer.to (VS.length) {-# INLINE indexCount #-} meshComponentsHash :: Getter (Mesh v) MeshHash meshComponentsHash = meshComponents.to compHashes where compHashes compMap = XH.xxHash . pack $ concatMap octets $ compMap^..traverse.componentHash {-# INLINE meshComponentsHash #-} -- | concat of the indices of all `MeshComponent`s concatedMeshIndices :: Getter (Mesh v) (VS.Vector Int) concatedMeshIndices = meshComponents.to concatIndices where concatIndices compMap = VS.concat $ compMap^..traverse.componentIndexBuffer {-# INLINE concatedMeshIndices #-} meshIndexRanges :: Getter (Mesh v) [(Int, Int)] meshIndexRanges = meshComponents.to ranges where ranges compMap = snd $ mapAccumL (\pos len -> (pos+len, (pos, pos+len-1))) 0 $ filter (>0) $ compMap^..traverse.componentIndexBuffer.to VS.length {-# INLINE meshIndexRanges #-} --------------------------------------------------------------------------------------------------- meshVertices :: Storable v => Lens' (Mesh v) (VS.Vector v) meshVertices = lens _meshVertexBuffer setter where setter mesh verts = mesh & meshVertexBuffer .~ verts & meshHash .~ hashVector verts {-# INLINE meshVertices #-} mkFromVerticesF :: ( Storable v, Foldable f ) => MeshId -> f v -> Mesh v mkFromVerticesF ident = mkFromVertices ident . VS.fromList . toList -- | mesh with single component with trivial indices mkFromVertices :: Storable v => MeshId -> VS.Vector v -> Mesh v mkFromVertices ident verts = emptyMesh & meshId .~ ident & meshVertices .~ verts & meshComponents.at "" ?~ (makeComponent "" ( VS.generate (VS.length verts) id )) makeComponent :: MeshId -> VS.Vector Int -> MeshComponent makeComponent ident indices = MeshComponent ident indices (hashVector indices) {-# INLINE makeComponent #-} componentIndices :: Lens' MeshComponent (VS.Vector Int) componentIndices = lens _componentIndexBuffer setter where setter comp idxs = comp & componentIndexBuffer .~ idxs & componentHash .~ (hashVector idxs) {-# INLINE componentIndices #-} -- | builds a mesh from geometry -- preserving the elements but flattens the surfaces -- a component for the indices is created at the root ("") meshFromTriGeo :: (Storable v) => MeshId -> TriGeo v -> Mesh v meshFromTriGeo ident geo@Geometry{..} = emptyMesh & meshId .~ ident & meshVertices .~ (VS.convert _geoVertices) & meshComponents.at "" ?~ makeComponent "" (geo^.flattenIndices) -- | unified empty mesh with "" identifier emptyMesh :: Storable v => Mesh v emptyMesh = Mesh "" VS.empty mempty 0 {-# INLINE emptyMesh #-} -- | appends a new component to a mesh -- -- keeps id -- hash is recalculated -- component indices are recalculated -- component id is prepended with meshId and a dot `.` (meshId.componentId) -- component indices aren't bound-checked against the given vertices appendComponent :: Storable v => Mesh v -> ( MeshComponent, VS.Vector v ) -> Mesh v appendComponent mesh (comp, verts) = mesh & meshVertices <>~ verts & meshComponents.at (comp^.componentId) ?~ componentToAdd where componentToAdd = comp & componentIndices %~ VS.map (+ VS.length (mesh^.meshVertices) ) {-# INLINE appendComponent #-} appendGeometry :: ( Storable v ) => Mesh v -> (MeshId, TriGeo v) -> Mesh v appendGeometry mesh (ident, geo) = let idxs = geo^.flattenIndices verts = VS.convert $ geo^.geoVertices in mesh `appendComponent` (makeComponent ident idxs, verts) {-# INLINE appendGeometry #-} {-- Utilities --} -- | colapse surfaces flattenIndices :: Getter (TriGeo v) (VS.Vector Int) flattenIndices = to $ VS.concatMap (VS.fromList . toList) . VS.convert . flatten . _geoSurfaces where flatten = V.foldl' (\accum (GeoSurface surf) -> accum V.++ surf) V.empty {-# INLINE flattenIndices #-} hashVector :: Storable a => VS.Vector a -> XH.XXHash hashVector = XH.xxHash' . BS.vectorToByteString {-# INLINE hashVector #-} -- stolen from http://www.haskell.org/pipermail/beginners/2010-October/005571.html octets :: Word32 -> [Word8] octets w = [ fromIntegral (w `shiftR` 24) , fromIntegral (w `shiftR` 16) , fromIntegral (w `shiftR` 8) , fromIntegral w ] {-# INLINE octets #-}
MaxDaten/yage-rendering
src/Yage/Rendering/Mesh.hs
mit
7,285
0
17
1,742
1,761
945
816
-1
-1
module Main where import Options.Declarative import CLI main :: IO () main = run_ ski
todays-mitsui/lambda2ski
app/Main.hs
mit
91
0
6
20
30
17
13
5
1
{-# LANGUAGE TypeSynonymInstances, MultiParamTypeClasses #-} module Hafer.Metric.ClassDiagram.Coupling ( evaluate , coupling ) where import Hafer.Data.ClassDiagram evaluate g = coupling g coupling :: CDGraph -> Int coupling g = let vs = vertices g es' = filter (\(Edge e d a b) -> case e of PkgContain -> False _ -> True) $ edges g g' = MathGraph vs es' in maxDegree g'
ooz/Hafer
src/Hafer/Metric/ClassDiagram/Coupling.hs
mit
560
0
15
252
129
68
61
14
2
{-# LANGUAGE FlexibleInstances, UndecidableInstances, OverloadedStrings, TypeFamilies, RankNTypes, DeriveDataTypeable, FlexibleContexts, ScopedTypeVariables, GADTs, GeneralizedNewtypeDeriving, DeriveGeneric #-} ----------------------------------------------------------------------------- {- | Module : Language.Javascript.JMacro.Base Copyright : (c) Gershom Bazerman, 2009 License : BSD 3 Clause Maintainer : gershomb@gmail.com Stability : experimental Simple DSL for lightweight (untyped) programmatic generation of Javascript. -} ----------------------------------------------------------------------------- module Compiler.JMacro.Base ( -- * ADT JStat(..), JExpr(..), JVal(..), JOp(..), JUOp(..), Ident(..), IdentSupply(..), JsLabel, -- * Generic traversal (via compos) JMacro(..), JMGadt(..), Compos(..), composOp, composOpM, composOpM_, composOpFold, -- * Hygienic transformation withHygiene, scopify, -- * Display/Output renderJs, renderJs', renderPrefixJs, renderPrefixJs', JsToDoc(..), defaultRenderJs, RenderJs(..), jsToDoc, -- * Ad-hoc data marshalling ToJExpr(..), -- * Literals jsv, -- * Occasionally helpful combinators jLam, jVar, jFor, jForIn, jForEachIn, jTryCatchFinally, expr2stat, expr2ident, ToStat(..), nullStat, -- * Hash combinators jhEmpty, jhSingle, jhAdd, jhFromList, -- * Utility jsSaturate, SaneDouble(..), encodeJson ) where import Prelude hiding (tail, init, head, last, minimum, maximum, foldr1, foldl1, (!!), read) -- import Control.Applicative hiding (empty) import Control.Arrow (second, (***)) import Control.DeepSeq import Control.Monad.State.Strict import Control.Monad.Identity import Data.Function import Data.Bits ((.&.), shiftR) import Data.Binary (Binary) import Data.Char (toLower, isControl, ord) import qualified Data.Map as M import qualified Data.Text.Lazy as TL import Data.Text (Text) import qualified Data.Text as T import Data.Data import Data.Hashable (Hashable) import GHC.Generics import Numeric(showHex) import Safe import Data.Aeson import qualified Data.Vector as V import qualified Data.HashMap.Strict as HM import Text.PrettyPrint.Leijen.Text hiding ((<$>)) import qualified Text.PrettyPrint.Leijen.Text as PP -- wl-pprint-text compatibility with pretty infixl 5 $$, $+$ ($+$), ($$), ($$$) :: Doc -> Doc -> Doc x $+$ y = x PP.<$> y x $$ y = align (x $+$ y) x $$$ y = align (nest 2 $ x $+$ y) {-------------------------------------------------------------------- ADTs --------------------------------------------------------------------} newtype IdentSupply a = IS {runIdentSupply :: State [Ident] a} deriving Typeable instance NFData (IdentSupply a) where rnf IS{} = () inIdentSupply :: (State [Ident] a -> State [Ident] b) -> IdentSupply a -> IdentSupply b inIdentSupply f x = IS $ f (runIdentSupply x) instance Data a => Data (IdentSupply a) where gunfold _ _ _ = error "gunfold IdentSupply" toConstr _ = error "toConstr IdentSupply" dataTypeOf _ = mkNoRepType "IdentSupply" instance Functor IdentSupply where fmap f x = inIdentSupply (fmap f) x takeOne :: State [Ident] Ident takeOne = do xxs <- get case xxs of (x:xs) -> do put xs return x _ -> error "takeOne: empty list" newIdentSupply :: Maybe Text -> [Ident] newIdentSupply Nothing = newIdentSupply (Just "jmId") newIdentSupply (Just pfx') = [TxtI (pfx `mappend` T.pack (show x)) | x <- [(0::Integer)..]] where pfx = pfx' `mappend` "_" sat_ :: IdentSupply a -> a sat_ x = evalState (runIdentSupply x) $ newIdentSupply (Just "<<unsatId>>") instance Eq a => Eq (IdentSupply a) where (==) = (==) `on` sat_ instance Ord a => Ord (IdentSupply a) where compare = compare `on` sat_ instance Show a => Show (IdentSupply a) where show x = "(" ++ show (sat_ x) ++ ")" -- array comprehensions/generators? -- | Statements data JStat = DeclStat Ident | ReturnStat JExpr | IfStat JExpr JStat JStat | WhileStat Bool JExpr JStat -- bool is "do" | ForInStat Bool Ident JExpr JStat -- bool is "each" | SwitchStat JExpr [(JExpr, JStat)] JStat | TryStat JStat Ident JStat JStat | BlockStat [JStat] | ApplStat JExpr [JExpr] | UOpStat JUOp JExpr | AssignStat JExpr JExpr | UnsatBlock (IdentSupply JStat) | LabelStat JsLabel JStat | BreakStat (Maybe JsLabel) | ContinueStat (Maybe JsLabel) deriving (Eq, Ord, Show, Data, Typeable, Generic) instance NFData JStat type JsLabel = Text instance Semigroup JStat where (BlockStat []) <> x = x x <> (BlockStat []) = x (BlockStat xs) <> (BlockStat ys) = BlockStat $ xs ++ ys (BlockStat xs) <> ys = BlockStat $ xs ++ [ys] xs <> (BlockStat ys) = BlockStat $ xs : ys xs <> ys = BlockStat [xs,ys] instance Monoid JStat where mempty = BlockStat [] mappend = (<>) -- TODO: annotate expressions with type -- | Expressions data JExpr = ValExpr JVal | SelExpr JExpr Ident | IdxExpr JExpr JExpr | InfixExpr JOp JExpr JExpr | UOpExpr JUOp JExpr | IfExpr JExpr JExpr JExpr | ApplExpr JExpr [JExpr] | UnsatExpr (IdentSupply JExpr) deriving (Eq, Ord, Show, Data, Typeable, Generic) instance NFData JExpr -- | Values data JVal = JVar Ident | JList [JExpr] | JDouble SaneDouble | JInt Integer | JStr Text | JRegEx Text | JHash (M.Map Text JExpr) | JFunc [Ident] JStat | UnsatVal (IdentSupply JVal) deriving (Eq, Ord, Show, Data, Typeable, Generic) instance NFData JVal data JOp = EqOp -- == | StrictEqOp -- === | NeqOp -- != | StrictNeqOp -- !== | GtOp -- > | GeOp -- >= | LtOp -- < | LeOp -- <= | AddOp -- + | SubOp -- - | MulOp -- "*" | DivOp -- / | ModOp -- % | LeftShiftOp -- << | RightShiftOp -- >> | ZRightShiftOp -- >>> | BAndOp -- & | BOrOp -- | | BXorOp -- ^ | LAndOp -- && | LOrOp -- || | InstanceofOp -- instanceof | InOp -- in deriving (Show, Eq, Ord, Enum, Data, Typeable, Generic) instance NFData JOp opText :: JOp -> TL.Text opText EqOp = "==" opText StrictEqOp = "===" opText NeqOp = "!=" opText StrictNeqOp = "!==" opText GtOp = ">" opText GeOp = ">=" opText LtOp = "<" opText LeOp = "<=" opText AddOp = "+" opText SubOp = "-" opText MulOp = "*" opText DivOp = "/" opText ModOp = "%" opText LeftShiftOp = "<<" opText RightShiftOp = ">>" opText ZRightShiftOp = ">>>" opText BAndOp = "&" opText BOrOp = "|" opText BXorOp = "^" opText LAndOp = "&&" opText LOrOp = "||" opText InstanceofOp = "instanceof" opText InOp = "in" data JUOp = NotOp -- ! | BNotOp -- ~ | NegOp -- - | PlusOp -- +x | NewOp -- new x | TypeofOp -- typeof x | DeleteOp -- delete x | YieldOp -- yield x | VoidOp -- void x | PreInc -- ++x | PostInc -- x++ | PreDec -- --x | PostDec -- x-- deriving (Show, Eq, Ord, Enum, Data, Typeable, Generic) instance NFData JUOp isPre :: JUOp -> Bool isPre PostInc = False isPre PostDec = False isPre _ = True isAlphaOp :: JUOp -> Bool isAlphaOp NewOp = True isAlphaOp TypeofOp = True isAlphaOp DeleteOp = True isAlphaOp YieldOp = True isAlphaOp VoidOp = True isAlphaOp _ = False uOpText :: JUOp -> TL.Text uOpText NotOp = "!" uOpText BNotOp = "~" uOpText NegOp = "-" uOpText PlusOp = "+" uOpText NewOp = "new" uOpText TypeofOp = "typeof" uOpText DeleteOp = "delete" uOpText YieldOp = "yield" uOpText VoidOp = "void" uOpText PreInc = "++" uOpText PostInc = "++" uOpText PreDec = "--" uOpText PostDec = "--" newtype SaneDouble = SaneDouble { unSaneDouble :: Double } deriving (Data, Typeable, Fractional, Num, Generic, NFData) instance Eq SaneDouble where (SaneDouble x) == (SaneDouble y) = x == y || (isNaN x && isNaN y) instance Ord SaneDouble where compare (SaneDouble x) (SaneDouble y) = compare (fromNaN x) (fromNaN y) where fromNaN z | isNaN z = Nothing | otherwise = Just z instance Show SaneDouble where show (SaneDouble x) = show x -- | Identifiers newtype Ident = TxtI Text deriving (Show, Data, Typeable, Hashable, Eq, Ord, Binary, Generic, NFData) expr2stat :: JExpr -> JStat expr2stat (ApplExpr x y) = (ApplStat x y) expr2stat (IfExpr x y z) = IfStat x (expr2stat y) (expr2stat z) expr2stat (UOpExpr o x) = UOpStat o x expr2stat _ = nullStat {-------------------------------------------------------------------- Compos --------------------------------------------------------------------} -- | Compos and ops for generic traversal as defined over -- the JMacro ADT. -- | Utility class to coerce the ADT into a regular structure. class JMacro a where jtoGADT :: a -> JMGadt a jfromGADT :: JMGadt a -> a instance JMacro Ident where jtoGADT = JMGId jfromGADT (JMGId x) = x instance JMacro JStat where jtoGADT = JMGStat jfromGADT (JMGStat x) = x instance JMacro JExpr where jtoGADT = JMGExpr jfromGADT (JMGExpr x) = x instance JMacro JVal where jtoGADT = JMGVal jfromGADT (JMGVal x) = x -- | Union type to allow regular traversal by compos. data JMGadt a where JMGId :: Ident -> JMGadt Ident JMGStat :: JStat -> JMGadt JStat JMGExpr :: JExpr -> JMGadt JExpr JMGVal :: JVal -> JMGadt JVal composOp :: Compos t => (forall a. t a -> t a) -> t b -> t b composOp f = runIdentity . composOpM (Identity . f) composOpM :: (Compos t, Monad m) => (forall a. t a -> m (t a)) -> t b -> m (t b) composOpM = compos return ap composOpM_ :: (Compos t, Monad m) => (forall a. t a -> m ()) -> t b -> m () composOpM_ = composOpFold (return ()) (>>) composOpFold :: Compos t => b -> (b -> b -> b) -> (forall a. t a -> b) -> t c -> b composOpFold z c f = unC . compos (\_ -> C z) (\(C x) (C y) -> C (c x y)) (C . f) newtype C b a = C { unC :: b } class Compos t where compos :: (forall a. a -> m a) -> (forall a b. m (a -> b) -> m a -> m b) -> (forall a. t a -> m (t a)) -> t c -> m (t c) instance Compos JMGadt where compos = jmcompos jmcompos :: forall m c. (forall a. a -> m a) -> (forall a b. m (a -> b) -> m a -> m b) -> (forall a. JMGadt a -> m (JMGadt a)) -> JMGadt c -> m (JMGadt c) jmcompos ret app f' v = case v of JMGId _ -> ret v JMGStat v' -> ret JMGStat `app` case v' of DeclStat i -> ret DeclStat `app` f i ReturnStat i -> ret ReturnStat `app` f i IfStat e s s' -> ret IfStat `app` f e `app` f s `app` f s' WhileStat b e s -> ret (WhileStat b) `app` f e `app` f s ForInStat b i e s -> ret (ForInStat b) `app` f i `app` f e `app` f s SwitchStat e l d -> ret SwitchStat `app` f e `app` l' `app` f d where l' = mapM' (\(c,s) -> ret (,) `app` f c `app` f s) l BlockStat xs -> ret BlockStat `app` mapM' f xs ApplStat e xs -> ret ApplStat `app` f e `app` mapM' f xs TryStat s i s1 s2 -> ret TryStat `app` f s `app` f i `app` f s1 `app` f s2 UOpStat o e -> ret (UOpStat o) `app` f e AssignStat e e' -> ret AssignStat `app` f e `app` f e' UnsatBlock _ -> ret v' ContinueStat l -> ret (ContinueStat l) BreakStat l -> ret (BreakStat l) LabelStat l s -> ret (LabelStat l) `app` f s JMGExpr v' -> ret JMGExpr `app` case v' of ValExpr e -> ret ValExpr `app` f e SelExpr e e' -> ret SelExpr `app` f e `app` f e' IdxExpr e e' -> ret IdxExpr `app` f e `app` f e' InfixExpr o e e' -> ret (InfixExpr o) `app` f e `app` f e' UOpExpr o e -> ret (UOpExpr o) `app` f e IfExpr e e' e'' -> ret IfExpr `app` f e `app` f e' `app` f e'' ApplExpr e xs -> ret ApplExpr `app` f e `app` mapM' f xs UnsatExpr _ -> ret v' JMGVal v' -> ret JMGVal `app` case v' of JVar i -> ret JVar `app` f i JList xs -> ret JList `app` mapM' f xs JDouble _ -> ret v' JInt _ -> ret v' JStr _ -> ret v' JRegEx _ -> ret v' JHash m -> ret JHash `app` m' where (ls, vs) = unzip (M.toList m) m' = ret (M.fromAscList . zip ls) `app` mapM' f vs JFunc xs s -> ret JFunc `app` mapM' f xs `app` f s UnsatVal _ -> ret v' where mapM' :: forall a. (a -> m a) -> [a] -> m [a] mapM' g = foldr (app . app (ret (:)) . g) (ret []) f :: forall b. JMacro b => b -> m b f x = ret jfromGADT `app` f' (jtoGADT x) {-------------------------------------------------------------------- New Identifiers --------------------------------------------------------------------} class ToSat a where toSat_ :: a -> [Ident] -> IdentSupply (JStat, [Ident]) instance ToSat [JStat] where toSat_ f vs = IS $ return $ (BlockStat f, reverse vs) instance ToSat JStat where toSat_ f vs = IS $ return $ (f, reverse vs) instance ToSat JExpr where toSat_ f vs = IS $ return $ (expr2stat f, reverse vs) instance ToSat [JExpr] where toSat_ f vs = IS $ return $ (BlockStat $ map expr2stat f, reverse vs) instance (ToSat a, b ~ JExpr) => ToSat (b -> a) where toSat_ f vs = IS $ do x <- takeOne runIdentSupply $ toSat_ (f (ValExpr $ JVar x)) (x:vs) {- splitIdentSupply :: ([Ident] -> ([Ident], [Ident])) splitIdentSupply is = (takeAlt is, takeAlt (drop 1 is)) where takeAlt (x:_:xs) = x : takeAlt xs takeAlt _ = error "splitIdentSupply: stream is not infinite" -} {-------------------------------------------------------------------- Saturation --------------------------------------------------------------------} -- | Given an optional prefix, fills in all free variable names with a supply -- of names generated by the prefix. jsSaturate :: (JMacro a) => Maybe Text -> a -> a jsSaturate str x = evalState (runIdentSupply $ jsSaturate_ x) (newIdentSupply str) jsSaturate_ :: (JMacro a) => a -> IdentSupply a jsSaturate_ e = IS $ jfromGADT <$> go (jtoGADT e) where go :: forall a. JMGadt a -> State [Ident] (JMGadt a) go v = case v of JMGStat (UnsatBlock us) -> go =<< (JMGStat <$> runIdentSupply us) JMGExpr (UnsatExpr us) -> go =<< (JMGExpr <$> runIdentSupply us) JMGVal (UnsatVal us) -> go =<< (JMGVal <$> runIdentSupply us) _ -> composOpM go v {-------------------------------------------------------------------- Transformation --------------------------------------------------------------------} -- doesn't apply to unsaturated bits jsReplace_ :: JMacro a => [(Ident, Ident)] -> a -> a jsReplace_ xs e = jfromGADT $ go (jtoGADT e) where go :: forall a. JMGadt a -> JMGadt a go v = case v of JMGId i -> maybe v JMGId (M.lookup i mp) _ -> composOp go v mp = M.fromList xs -- only works on fully saturated things jsUnsat_ :: JMacro a => [Ident] -> a -> IdentSupply a jsUnsat_ xs e = IS $ do (idents,is') <- splitAt (length xs) <$> get put is' return $ jsReplace_ (zip xs idents) e -- | Apply a transformation to a fully saturated syntax tree, -- taking care to return any free variables back to their free state -- following the transformation. As the transformation preserves -- free variables, it is hygienic. withHygiene :: JMacro a => (a -> a) -> a -> a withHygiene f x = jfromGADT $ case jtoGADT x of JMGExpr z -> JMGExpr $ UnsatExpr $ inScope z JMGStat z -> JMGStat $ UnsatBlock $ inScope z JMGVal z -> JMGVal $ UnsatVal $ inScope z JMGId _ -> jtoGADT $ f x where inScope z = IS $ do ti <- get case ti of ((TxtI a):b) -> do put b return $ withHygiene_ a f z _ -> error "withHygiene: empty list" withHygiene_ :: JMacro a => Text -> (a -> a) -> a -> a withHygiene_ un f x = jfromGADT $ case jtoGADT x of JMGStat _ -> jtoGADT $ UnsatBlock (jsUnsat_ is' x'') JMGExpr _ -> jtoGADT $ UnsatExpr (jsUnsat_ is' x'') JMGVal _ -> jtoGADT $ UnsatVal (jsUnsat_ is' x'') JMGId _ -> jtoGADT $ f x where (x', (TxtI l : _)) = runState (runIdentSupply $ jsSaturate_ x) is is' = take lastVal is x'' = f x' lastVal = readNote ("inSat" ++ T.unpack un) (reverse . takeWhile (/= '_') . reverse $ T.unpack l) :: Int is = newIdentSupply $ Just ("inSat" `mappend` un) -- | Takes a fully saturated expression and transforms it to use unique variables that respect scope. scopify :: JStat -> JStat scopify x = evalState (jfromGADT <$> go (jtoGADT x)) (newIdentSupply Nothing) where go :: forall a. JMGadt a -> State [Ident] (JMGadt a) go v = case v of (JMGStat (BlockStat ss)) -> JMGStat . BlockStat <$> blocks ss where blocks [] = return [] blocks (DeclStat (TxtI i) : xs) | "!!" `T.isPrefixOf` i = (DeclStat (TxtI (T.drop 2 i)):) <$> blocks xs | "!" `T.isPrefixOf` i = (DeclStat (TxtI $ T.tail i):) <$> blocks xs | otherwise = do xx <- get case xx of (newI:st) -> do put st rest <- blocks xs return $ [DeclStat newI `mappend` jsReplace_ [(TxtI i, newI)] (BlockStat rest)] _ -> error "scopify: empty list" blocks (x':xs) = (jfromGADT <$> go (jtoGADT x')) <:> blocks xs (<:>) = liftM2 (:) (JMGStat (TryStat s (TxtI i) s1 s2)) -> do xx <- get case xx of (newI:st) -> do put st t <- jfromGADT <$> go (jtoGADT s) c <- jfromGADT <$> go (jtoGADT s1) f <- jfromGADT <$> go (jtoGADT s2) return . JMGStat . TryStat t newI (jsReplace_ [(TxtI i, newI)] c) $ f _ -> error "scopify: empty list" (JMGExpr (ValExpr (JFunc is s))) -> do st <- get let (newIs,newSt) = splitAt (length is) st put newSt rest <- jfromGADT <$> go (jtoGADT s) return . JMGExpr . ValExpr $ JFunc newIs $ (jsReplace_ $ zip is newIs) rest _ -> composOpM go v {-------------------------------------------------------------------- Pretty Printing --------------------------------------------------------------------} -- | Render a syntax tree as a pretty-printable document -- (simply showing the resultant doc produces a nice, -- well formatted String). renderJs :: (JsToDoc a, JMacro a) => a -> Doc renderJs = renderJs' defaultRenderJs renderJs' :: (JsToDoc a, JMacro a) => RenderJs -> a -> Doc renderJs' r = jsToDocR r . jsSaturate Nothing data RenderJs = RenderJs { renderJsS :: RenderJs -> JStat -> Doc , renderJsE :: RenderJs -> JExpr -> Doc , renderJsV :: RenderJs -> JVal -> Doc , renderJsI :: RenderJs -> Ident -> Doc } defaultRenderJs :: RenderJs defaultRenderJs = RenderJs defRenderJsS defRenderJsE defRenderJsV defRenderJsI jsToDoc :: JsToDoc a => a -> Doc jsToDoc = jsToDocR defaultRenderJs -- | Render a syntax tree as a pretty-printable document, using a given prefix to all generated names. Use this with distinct prefixes to ensure distinct generated names between independent calls to render(Prefix)Js. renderPrefixJs :: (JsToDoc a, JMacro a) => Text -> a -> Doc renderPrefixJs pfx = renderPrefixJs' defaultRenderJs pfx renderPrefixJs' :: (JsToDoc a, JMacro a) => RenderJs -> Text -> a -> Doc renderPrefixJs' r pfx = jsToDocR r . jsSaturate (Just $ "jmId_" `mappend` pfx) braceNest :: Doc -> Doc braceNest x = char '{' <+> nest 2 x $$ char '}' braceNest' :: Doc -> Doc braceNest' x = nest 2 (char '{' $+$ x) $$ char '}' class JsToDoc a where jsToDocR :: RenderJs -> a -> Doc instance JsToDoc JStat where jsToDocR r = renderJsS r r instance JsToDoc JExpr where jsToDocR r = renderJsE r r instance JsToDoc JVal where jsToDocR r = renderJsV r r instance JsToDoc Ident where jsToDocR r = renderJsI r r instance JsToDoc [JExpr] where jsToDocR r = vcat . map ((<> semi) . jsToDocR r) instance JsToDoc [JStat] where jsToDocR r = vcat . map ((<> semi) . jsToDocR r) defRenderJsS :: RenderJs -> JStat -> Doc defRenderJsS r (IfStat cond x y) = text "if" <> parens (jsToDocR r cond) $$ braceNest' (jsToDocR r x) $$ mbElse where mbElse | y == BlockStat [] = PP.empty | otherwise = text "else" $$ braceNest' (jsToDocR r y) defRenderJsS r (DeclStat x) = text "var" <+> jsToDocR r x defRenderJsS r (WhileStat False p b) = text "while" <> parens (jsToDocR r p) $$ braceNest' (jsToDocR r b) defRenderJsS r (WhileStat True p b) = (text "do" $$ braceNest' (jsToDocR r b)) $+$ text "while" <+> parens (jsToDocR r p) defRenderJsS r (UnsatBlock e) = jsToDocR r $ sat_ e defRenderJsS _ (BreakStat l) = maybe (text "break") (((<+>) `on` text) "break" . TL.fromStrict) l defRenderJsS _ (ContinueStat l) = maybe (text "continue") (((<+>) `on` text) "continue" . TL.fromStrict) l defRenderJsS r (LabelStat l s) = text (TL.fromStrict l) <> char ':' $$ printBS s where printBS (BlockStat ss) = vcat $ interSemi $ flattenBlocks ss printBS x = jsToDocR r x interSemi [x] = [jsToDocR r x] interSemi [] = [] interSemi (x:xs) = (jsToDocR r x <> semi) : interSemi xs defRenderJsS r (ForInStat each i e b) = text txt <> parens (jsToDocR r i <+> text "in" <+> jsToDocR r e) $$ braceNest' (jsToDocR r b) where txt | each = "for each" | otherwise = "for" defRenderJsS r (SwitchStat e l d) = text "switch" <+> parens (jsToDocR r e) $$ braceNest' cases where l' = map (\(c,s) -> (text "case" <+> parens (jsToDocR r c) <> char ':') $$$ (jsToDocR r s)) l ++ [text "default:" $$$ (jsToDocR r d)] cases = vcat l' defRenderJsS r (ReturnStat e) = text "return" <+> jsToDocR r e defRenderJsS r (ApplStat e es) = jsToDocR r e <> (parens . fillSep . punctuate comma $ map (jsToDocR r) es) defRenderJsS r (TryStat s i s1 s2) = text "try" $$ braceNest' (jsToDocR r s) $$ mbCatch $$ mbFinally where mbCatch | s1 == BlockStat [] = PP.empty | otherwise = text "catch" <> parens (jsToDocR r i) $$ braceNest' (jsToDocR r s1) mbFinally | s2 == BlockStat [] = PP.empty | otherwise = text "finally" $$ braceNest' (jsToDocR r s2) defRenderJsS r (AssignStat i x) = jsToDocR r i <+> char '=' <+> jsToDocR r x defRenderJsS r (UOpStat op x) | isPre op && isAlphaOp op = text (uOpText op) <+> optParens r x | isPre op = text (uOpText op) <> optParens r x | otherwise = optParens r x <> text (uOpText op) defRenderJsS r (BlockStat xs) = jsToDocR r (flattenBlocks xs) flattenBlocks :: [JStat] -> [JStat] flattenBlocks (BlockStat y:ys) = flattenBlocks y ++ flattenBlocks ys flattenBlocks (y:ys) = y : flattenBlocks ys flattenBlocks [] = [] optParens :: RenderJs -> JExpr -> Doc optParens r x = case x of (UOpExpr _ _) -> parens (jsToDocR r x) _ -> jsToDocR r x defRenderJsE :: RenderJs -> JExpr -> Doc defRenderJsE r (ValExpr x) = jsToDocR r x defRenderJsE r (SelExpr x y) = cat [jsToDocR r x <> char '.', jsToDocR r y] defRenderJsE r (IdxExpr x y) = jsToDocR r x <> brackets (jsToDocR r y) defRenderJsE r (IfExpr x y z) = parens (jsToDocR r x <+> char '?' <+> jsToDocR r y <+> char ':' <+> jsToDocR r z) defRenderJsE r (InfixExpr op x y) = parens $ hsep [jsToDocR r x, text (opText op), jsToDocR r y] defRenderJsE r (UOpExpr op x) | isPre op && isAlphaOp op = text (uOpText op) <+> optParens r x | isPre op = text (uOpText op) <> optParens r x | otherwise = optParens r x <> text (uOpText op) defRenderJsE r (ApplExpr je xs) = jsToDocR r je <> (parens . fillSep . punctuate comma $ map (jsToDocR r) xs) defRenderJsE r (UnsatExpr e) = jsToDocR r $ sat_ e defRenderJsV :: RenderJs -> JVal -> Doc defRenderJsV r (JVar i) = jsToDocR r i defRenderJsV r (JList xs) = brackets . fillSep . punctuate comma $ map (jsToDocR r) xs defRenderJsV _ (JDouble (SaneDouble d)) | d < 0 || isNegativeZero d = parens (double d) | otherwise = double d defRenderJsV _ (JInt i) | i < 0 = parens (integer i) | otherwise = integer i defRenderJsV _ (JStr s) = text . TL.fromChunks $ ["\"",encodeJson s,"\""] defRenderJsV _ (JRegEx s) = text . TL.fromChunks $ ["/",s,"/"] defRenderJsV r (JHash m) | M.null m = text "{}" | otherwise = braceNest . fillSep . punctuate comma . map (\(x,y) -> squotes (text (TL.fromStrict x)) <> colon <+> jsToDocR r y) $ M.toList m defRenderJsV r (JFunc is b) = parens $ text "function" <> parens (fillSep . punctuate comma . map (jsToDocR r) $ is) $$ braceNest' (jsToDocR r b) defRenderJsV r (UnsatVal f) = jsToDocR r $ sat_ f defRenderJsI :: RenderJs -> Ident -> Doc defRenderJsI _ (TxtI t) = text (TL.fromStrict t) {-------------------------------------------------------------------- ToJExpr Class --------------------------------------------------------------------} -- | Things that can be marshalled into javascript values. -- Instantiate for any necessary data structures. class ToJExpr a where toJExpr :: a -> JExpr toJExprFromList :: [a] -> JExpr toJExprFromList = ValExpr . JList . map toJExpr instance ToJExpr a => ToJExpr [a] where toJExpr = toJExprFromList instance ToJExpr JExpr where toJExpr = id instance ToJExpr () where toJExpr _ = ValExpr $ JList [] instance ToJExpr Bool where toJExpr True = jsv "true" toJExpr False = jsv "false" instance ToJExpr JVal where toJExpr = ValExpr instance ToJExpr a => ToJExpr (M.Map Text a) where toJExpr = ValExpr . JHash . M.map toJExpr instance ToJExpr a => ToJExpr (M.Map String a) where toJExpr = ValExpr . JHash . M.fromList . map (T.pack *** toJExpr) . M.toList instance ToJExpr Double where toJExpr = ValExpr . JDouble . SaneDouble instance ToJExpr Int where toJExpr = ValExpr . JInt . fromIntegral instance ToJExpr Integer where toJExpr = ValExpr . JInt instance ToJExpr Char where toJExpr = ValExpr . JStr . T.pack . (:[]) toJExprFromList = ValExpr . JStr . T.pack -- where escQuotes = tailDef "" . initDef "" . show instance ToJExpr Ident where toJExpr = ValExpr . JVar instance ToJExpr T.Text where toJExpr = ValExpr . JStr instance ToJExpr TL.Text where toJExpr = ValExpr . JStr . TL.toStrict instance (ToJExpr a, ToJExpr b) => ToJExpr (a,b) where toJExpr (a,b) = ValExpr . JList $ [toJExpr a, toJExpr b] instance (ToJExpr a, ToJExpr b, ToJExpr c) => ToJExpr (a,b,c) where toJExpr (a,b,c) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c] instance (ToJExpr a, ToJExpr b, ToJExpr c, ToJExpr d) => ToJExpr (a,b,c,d) where toJExpr (a,b,c,d) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c, toJExpr d] instance (ToJExpr a, ToJExpr b, ToJExpr c, ToJExpr d, ToJExpr e) => ToJExpr (a,b,c,d,e) where toJExpr (a,b,c,d,e) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c, toJExpr d, toJExpr e] instance (ToJExpr a, ToJExpr b, ToJExpr c, ToJExpr d, ToJExpr e, ToJExpr f) => ToJExpr (a,b,c,d,e,f) where toJExpr (a,b,c,d,e,f) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c, toJExpr d, toJExpr e, toJExpr f] {-------------------------------------------------------------------- Block Sugar --------------------------------------------------------------------} class ToStat a where toStat :: a -> JStat instance ToStat JStat where toStat = id instance ToStat [JStat] where toStat = BlockStat instance ToStat JExpr where toStat = expr2stat instance ToStat [JExpr] where toStat = BlockStat . map expr2stat {-------------------------------------------------------------------- Combinators --------------------------------------------------------------------} -- | Create a new anonymous function. The result is an expression. -- Usage: -- @jLam $ \ x y -> {JExpr involving x and y}@ jLam :: ToSat a => a -> JExpr jLam f = ValExpr . UnsatVal . IS $ do (block,is) <- runIdentSupply $ toSat_ f [] return $ JFunc is block -- | Introduce a new variable into scope for the duration -- of the enclosed expression. The result is a block statement. -- Usage: -- @jVar $ \ x y -> {JExpr involving x and y}@ jVar :: ToSat a => a -> JStat jVar f = UnsatBlock . IS $ do (block, is) <- runIdentSupply $ toSat_ f [] let addDecls (BlockStat ss) = BlockStat $ map DeclStat is ++ ss addDecls x = x return $ addDecls block -- | Create a for in statement. -- Usage: -- @jForIn {expression} $ \x -> {block involving x}@ jForIn :: ToSat a => JExpr -> (JExpr -> a) -> JStat jForIn e f = UnsatBlock . IS $ do (block, is) <- runIdentSupply $ toSat_ f [] let i = headNote "jForIn" is return $ DeclStat i `mappend` ForInStat False i e block -- | As with "jForIn" but creating a \"for each in\" statement. jForEachIn :: ToSat a => JExpr -> (JExpr -> a) -> JStat jForEachIn e f = UnsatBlock . IS $ do (block, is) <- runIdentSupply $ toSat_ f [] let i = headNote "jForEachIn" is return $ DeclStat i `mappend` ForInStat True i e block jTryCatchFinally :: (ToSat a) => JStat -> a -> JStat -> JStat jTryCatchFinally s f s2 = UnsatBlock . IS $ do (block, is) <- runIdentSupply $ toSat_ f [] let i = headNote "jTryCatchFinally" is return $ TryStat s i block s2 jsv :: Text -> JExpr jsv = ValExpr . JVar . TxtI jFor :: (ToJExpr a, ToStat b) => JStat -> a -> JStat -> b -> JStat jFor before p after b = BlockStat [before, WhileStat False (toJExpr p) b'] where b' = case toStat b of BlockStat xs -> BlockStat $ xs ++ [after] x -> BlockStat [x,after] jhEmpty :: M.Map Text JExpr jhEmpty = M.empty jhSingle :: ToJExpr a => Text -> a -> M.Map Text JExpr jhSingle k v = jhAdd k v $ jhEmpty jhAdd :: ToJExpr a => Text -> a -> M.Map Text JExpr -> M.Map Text JExpr jhAdd k v m = M.insert k (toJExpr v) m jhFromList :: [(Text, JExpr)] -> JVal jhFromList = JHash . M.fromList nullStat :: JStat nullStat = BlockStat [] expr2ident :: JExpr -> Ident expr2ident (ValExpr (JVar i)) = i expr2ident e = error ("expr2ident: expected (ValExpr (JVar _)), got: " ++ show e) -- Aeson instance instance ToJExpr Value where toJExpr Null = ValExpr $ JVar $ TxtI "null" toJExpr (Bool b) = ValExpr $ JVar $ TxtI $ T.pack $ map toLower (show b) toJExpr (Number n) = ValExpr $ JDouble $ realToFrac n toJExpr (String s) = ValExpr $ JStr $ s toJExpr (Array vs) = ValExpr $ JList $ map toJExpr $ V.toList vs toJExpr (Object obj) = ValExpr $ JHash $ M.fromList $ map (second toJExpr) $ HM.toList obj encodeJson :: Text -> Text encodeJson = T.concatMap encodeJsonChar encodeJsonChar :: Char -> Text encodeJsonChar '/' = "\\/" encodeJsonChar '\b' = "\\b" encodeJsonChar '\f' = "\\f" encodeJsonChar '\n' = "\\n" encodeJsonChar '\r' = "\\r" encodeJsonChar '\t' = "\\t" encodeJsonChar '"' = "\\\"" encodeJsonChar '\\' = "\\\\" encodeJsonChar c | not (isControl c) && ord c <= 127 = T.singleton c | ord c <= 0xff = hexxs "\\x" 2 (ord c) | ord c <= 0xffff = hexxs "\\u" 4 (ord c) | otherwise = let cp0 = ord c - 0x10000 -- output surrogate pair in hexxs "\\u" 4 ((cp0 `shiftR` 10) + 0xd800) `mappend` hexxs "\\u" 4 ((cp0 .&. 0x3ff) + 0xdc00) where hexxs prefix pad cp = let h = showHex cp "" in T.pack (prefix ++ replicate (pad - length h) '0' ++ h)
ghcjs/ghcjs
src/Compiler/JMacro/Base.hs
mit
33,343
0
26
9,697
11,798
6,039
5,759
639
33
module ArrayBonn.Type where import Autolib.TES.Identifier import Autolib.Reader import Autolib.ToDoc data Statement = Assign Access Exp data Exp = Reference Access | Literal Integer | Binary Op Exp Exp data Op = Add | Subtract | Multiply | Divide -- | access to array element data Access = Access Identifier [ Exp ]
Erdwolf/autotool-bonn
src/ArrayBonn/Type.hs
gpl-2.0
326
0
7
62
87
52
35
10
0
module Darcs.Repository.Flags ( Compression (..) , RemoteDarcs (..) , Reorder (..) , Verbosity (..) , UpdateWorking (..) , UseCache (..) , DryRun (..) , UMask (..) , LookForAdds (..) , LookForReplaces (..) , DiffAlgorithm (..) , LookForMoves (..) , RunTest (..) , SetScriptsExecutable (..) , LeaveTestDir (..) , RemoteRepos (..) , SetDefault (..) , UseIndex (..) , ScanKnown (..) , CloneKind (..) , AllowConflicts (..) , ExternalMerge (..) , WorkRepo (..) , WantGuiPause (..) , WithPatchIndex (..) , WithWorkingDir (..) , ForgetParent (..) ) where import Darcs.Util.Diff ( DiffAlgorithm(..) ) data Verbosity = Quiet | NormalVerbosity | Verbose deriving ( Eq, Show ) data Compression = NoCompression | GzipCompression deriving ( Eq, Show ) data WithPatchIndex = YesPatchIndex | NoPatchIndex deriving ( Eq, Show ) data RemoteDarcs = RemoteDarcs String | DefaultRemoteDarcs deriving ( Eq, Show ) data Reorder = NoReorder | Reorder deriving ( Eq ) data UpdateWorking = YesUpdateWorking | NoUpdateWorking deriving ( Eq, Show ) data UseCache = YesUseCache | NoUseCache deriving ( Eq, Show ) data DryRun = YesDryRun | NoDryRun deriving ( Eq, Show ) data UMask = YesUMask String | NoUMask deriving ( Eq, Show ) data LookForAdds = YesLookForAdds | NoLookForAdds deriving ( Eq, Show ) data LookForReplaces = YesLookForReplaces | NoLookForReplaces deriving ( Eq, Show ) data LookForMoves = YesLookForMoves | NoLookForMoves deriving ( Eq, Show ) data RunTest = YesRunTest | NoRunTest deriving ( Eq, Show ) data SetScriptsExecutable = YesSetScriptsExecutable | NoSetScriptsExecutable deriving ( Eq, Show ) data LeaveTestDir = YesLeaveTestDir | NoLeaveTestDir deriving ( Eq, Show ) data RemoteRepos = RemoteRepos [String] deriving ( Eq, Show ) data SetDefault = YesSetDefault Bool | NoSetDefault Bool deriving ( Eq, Show ) data UseIndex = UseIndex | IgnoreIndex deriving ( Eq, Show ) data ScanKnown = ScanKnown -- ^Just files already known to darcs | ScanAll -- ^All files, i.e. look for new ones | ScanBoring -- ^All files, even boring ones -- Various kinds of getting repositories data CloneKind = LazyClone -- ^Just copy pristine and inventories | NormalClone -- ^First do a lazy clone then copy everything | CompleteClone -- ^Same as Normal but omit telling user they can interrumpt deriving ( Eq, Show ) data AllowConflicts = NoAllowConflicts | YesAllowConflicts | YesAllowConflictsAndMark deriving ( Eq, Show ) data ExternalMerge = YesExternalMerge String | NoExternalMerge deriving ( Eq, Show ) data WorkRepo = WorkRepoDir String | WorkRepoPossibleURL String | WorkRepoCurrentDir deriving ( Eq, Show ) data WantGuiPause = YesWantGuiPause | NoWantGuiPause deriving ( Eq, Show ) data WithWorkingDir = WithWorkingDir | NoWorkingDir deriving ( Eq, Show ) data ForgetParent = YesForgetParent | NoForgetParent deriving ( Eq, Show )
DavidAlphaFox/darcs
src/Darcs/Repository/Flags.hs
gpl-2.0
3,166
0
7
786
782
480
302
86
0
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs, FlexibleContexts, MultiParamTypeClasses #-} module Main where import Yesod import Yesod.Static import Yesod.Form import Yesod.Form.Jquery import MercadosCampesinos.Model.Market (MarketType(..), marketTypeLabel) import Data.Maybe (fromMaybe, fromJust) import Control.Applicative import Control.Arrow ((&&&)) import Control.Monad.Trans.Resource (runResourceT) import Control.Monad.Logger (runStderrLoggingT) import Control.Monad.IO.Class (liftIO) import Database.Persist import Database.Persist.Postgresql import Database.Persist.TH import Data.Time (Day, UTCTime, getCurrentTime) import Text.Hamlet (hamletFile) import Text.Julius (juliusFile) import Text.Lucius (luciusFile) import Data.Aeson import Data.Aeson.Types import qualified Data.Text as T import Text.Read (readMaybe) connStr :: ConnectionString connStr = "host=localhost dbname=mc user=arpunk password='' port=5432" share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Market title T.Text description Textarea date Day whatType MarketType address T.Text credibility Int verified Bool lat Double lng Double Wishlist market MarketId what Textarea |] data MercadosCampesinos = MercadosCampesinos { connPool :: ConnectionPool , getStatic :: Static } staticFiles "static/" mkYesod "MercadosCampesinos" [parseRoutes| /static StaticR Static getStatic / HomeR GET /mercados MarketsR GET /mercado/!new NewMarketR GET POST /mercado/#MarketId MarketR GET /mercado/#MarketId/pedidos NewWishlistR POST -- -- API JSON -- /api/mercados MarketsJsonR GET /api/mercado/#MarketId MarketJsonR GET |] instance Yesod MercadosCampesinos where defaultLayout widget = do master <- getYesod mmsg <- getMessage pc <- widgetToPageContent $ do $(whamletFile "templates/layout.hamlet") addScript $ StaticR js_angular_min_js addScript $ StaticR js_jquery_min_js addScript $ StaticR js_bootstrap_min_js giveUrlRenderer $(hamletFile "templates/wrapper.hamlet") instance YesodPersist MercadosCampesinos where type YesodPersistBackend MercadosCampesinos = SqlPersistT runDB action = do MercadosCampesinos pool _ <- getYesod runSqlPool action pool instance YesodJquery MercadosCampesinos instance RenderMessage MercadosCampesinos FormMessage where renderMessage _ _ = defaultFormMessage navbarWidget :: Widget navbarWidget = $(whamletFile "templates/widget/navbar.hamlet") newMarketForm :: Html -> MForm Handler (FormResult Market, Widget) newMarketForm = do renderDivs $ Market <$> areq textField "Titulo" Nothing <*> areq textareaField "Descripcion" Nothing <*> areq (jqueryDayField def { jdsChangeYear = False }) "Fecha de apertura" Nothing <*> areq (selectFieldList marketTypes) "Tipo de mercado" Nothing <*> areq textField "Direccion" Nothing <*> pure 0 <*> pure False <*> areq doubleField (FieldSettings (SomeMessage $ T.pack "Latitud") Nothing (Just "lat") Nothing []) Nothing <*> areq doubleField (FieldSettings (SomeMessage $ T.pack "Longitud") Nothing (Just "lng") Nothing []) Nothing where marketTypes = map (T.pack . marketTypeLabel &&& id) [DirectBuy .. ] newWishlistForm :: MarketId -> Html -> MForm Handler (FormResult Wishlist, Widget) newWishlistForm mid = do renderDivs $ Wishlist <$> pure mid <*> areq textareaField "¿Que desearías encontrar?" Nothing postNewMarketR :: Handler Html postNewMarketR = do ((form, _), _) <- runFormPost newMarketForm case form of FormSuccess market -> do newMarketId <- runDB $ insert market redirect $ MarketR newMarketId _ -> redirect HomeR getNewMarketR :: Handler Html getNewMarketR = do (newMarketWidget, enctype) <- generateFormPost newMarketForm defaultLayout $ do setTitle "Nuevo mercado" toWidget $(juliusFile "templates/new-market.julius") toWidget $(luciusFile "templates/new-market.lucius") $(whamletFile "templates/new-market.hamlet") getMarketsR :: Handler Html getMarketsR = do page <- lookupGetWithDefault "page" 0 per_page <- lookupGetWithDefault "count" 20 markets <- runDB $ selectList [] [Asc MarketDate, LimitTo per_page, OffsetBy page] defaultLayout $ do setTitle "Mercados" toWidget $(juliusFile "templates/markets.julius") toWidget $(luciusFile "templates/markets.lucius") $(whamletFile "templates/markets.hamlet") getMarketR :: MarketId -> Handler Html getMarketR mid = do market <- runDB $ get404 mid wishlists <- runDB $ selectList [WishlistMarket ==. mid] [] (newWishlistWidget, wlEncType) <- generateFormPost $ newWishlistForm mid defaultLayout $ do setTitle "Mercado" toWidget $(juliusFile "templates/market.julius") toWidget $(luciusFile "templates/market.lucius") $(whamletFile "templates/market.hamlet") postNewWishlistR :: MarketId -> Handler Html postNewWishlistR mid = do ((form, _), _) <- runFormPost $ newWishlistForm mid case form of FormSuccess nw -> do _ <- runDB $ insert nw redirect $ MarketR mid _ -> redirect $ MarketR mid getHomeR :: Handler Html getHomeR = do markets <- runDB $ selectList [] [Asc MarketDate] defaultLayout $ do setTitle "Inicio" toWidget $(juliusFile "templates/home.julius") toWidget $(luciusFile "templates/home.lucius") $(whamletFile "templates/home.hamlet") getMarketsJsonR :: Handler Value getMarketsJsonR = do markets <- runDB $ selectList [] [Asc MarketDate, LimitTo 6] returnJson $ fmap marketToGeoJSON markets getMarketJsonR :: MarketId -> Handler Value getMarketJsonR mid = do market <- runDB $ get404 mid returnJson $ object [("latitude" .= (marketLat market)) ,("longitude" .= (marketLng market))] marketToGeoJSON :: Entity Market -> Value marketToGeoJSON (Entity _ m) = object [("type" .= ("Feature" :: String)) ,("properties" .= object [("name" .= marketTitle m) ,("credibility" .= marketCredibility m) ,("verified" .= marketVerified m) ,("popupContent" .= (show $ marketDescription m))]) ,("geometry" .= object [("type" .= ("Point" :: String)) ,("coordinates" .= [ (marketLng m) , (marketLat m) ]) ]) ] lookupGetWithDefault :: Read a => T.Text -> a -> Handler a lookupGetWithDefault name def = do mval <- lookupGetParam name return $ fromMaybe def $ mval >>= readMaybe . T.unpack shortenTitle = shortenText 30 shortenDesc d = shortenText 200 $ unTextarea d shortenText :: Int -> T.Text -> T.Text shortenText num text | T.length text > num = (T.take num text) `T.append` "..." | otherwise = text main :: IO () main = withPostgresqlPool connStr 10 $ \pool -> do flip runSqlPersistMPool pool $ do runMigration migrateAll static@(Static settings) <- static "static" warp 3000 $ MercadosCampesinos pool static
arpunk/MercadosCampesinos
src/Main.hs
gpl-3.0
7,600
0
18
1,897
1,905
945
960
-1
-1
module Hob.Command.ReplaceText ( createMatcherForReplace, replaceCommandHandler, replaceNextCommandHandler, ) where import Data.Monoid (mconcat) import Graphics.UI.Gtk import Hob.Command.FindText import Hob.Context import Hob.Ui.Editor import Hob.Ui.Editor.Search createMatcherForReplace :: Char -> (String -> String -> CommandHandler) -> CommandMatcher createMatcherForReplace prefix handler = CommandMatcher (const Nothing) match where match [] = Nothing match (p:ps) | p == prefix = matchSearchAndReplaceFromStart ps | otherwise = Nothing matchSearchAndReplaceFromStart [] = Nothing matchSearchAndReplaceFromStart (separator:xs) = matchSearchAndReplaceFromSearch separator xs "" matchSearchAndReplaceFromSearch _ [] _ = Nothing matchSearchAndReplaceFromSearch separator (x:xs) accumSearch | '\\' == x = case xs of [] -> Nothing (s:xss) -> if s == separator then matchSearchAndReplaceFromSearch separator xss (accumSearch++[separator]) else matchSearchAndReplaceFromSearch separator xs (accumSearch++[x]) | separator == x = matchSearchAndReplaceFromReplace separator xs accumSearch "" | otherwise = matchSearchAndReplaceFromSearch separator xs (accumSearch++[x]) matchSearchAndReplaceFromReplace _ [] search accumReplace = Just $ handler search accumReplace matchSearchAndReplaceFromReplace separator (x:xs) search accumReplace | '\\' == x = case xs of [] -> Just $ handler search (accumReplace++[x]) (s:xss) -> if s == separator then matchSearchAndReplaceFromReplace separator xss search (accumReplace++[separator]) else matchSearchAndReplaceFromReplace separator xs search (accumReplace++[x]) | separator == x = Just $ handler search accumReplace | otherwise = matchSearchAndReplaceFromReplace separator xs search (accumReplace++[x]) replaceCommandHandler :: String -> String -> CommandHandler replaceCommandHandler searchText replaceText = CommandHandler (Just $ PreviewCommandHandler (searchPreview searchText) searchResetPreview) (replaceStart searchText replaceText) replaceNextCommandHandler :: CommandHandler replaceNextCommandHandler = CommandHandler Nothing invokeReplaceNext replaceStart :: String -> String -> App() replaceStart searchText replaceText = do enterMode replaceMode invokeOnActiveEditor $ \editor -> do startReplace editor searchText replaceText widgetGrabFocus editor invokeReplaceNext :: App() invokeReplaceNext = invokeOnActiveEditor replaceNext replaceReset :: App() replaceReset = invokeOnActiveEditor resetReplace replaceMode :: Mode replaceMode = Mode "replace" matcher replaceReset where matcher = mconcat [ commandMatcher searchMode , createMatcherForKeyBinding ([Shift, Control], "Down") replaceNextCommandHandler ]
svalaskevicius/hob
src/lib/Hob/Command/ReplaceText.hs
gpl-3.0
3,134
0
15
762
767
394
373
52
9
module Jumpie.MoveableObject where import Jumpie.TileIncrement class MoveableObject p where moveObject :: p -> TileIncrement -> p
pmiddend/jumpie
lib/Jumpie/MoveableObject.hs
gpl-3.0
134
0
8
20
33
18
15
4
0
module SIR.Model where import SIR.API data SIRState = Susceptible | Infected | Recovered deriving (Show, Eq) data SIREvent = MakeContact | Contact !AgentId !SIRState | Recover deriving (Show, Eq) createSIRStates :: Int -> Int -> Int -> [SIRState] createSIRStates s i r = ss ++ is ++ rs where ss = replicate s Susceptible is = replicate i Infected rs = replicate r Recovered
thalerjonathan/phd
thesis/code/taglessfinal/src/SIR/Model.hs
gpl-3.0
411
0
8
101
137
74
63
21
1
{-# LANGUAGE OverloadedStrings #-} module Blog.Forms where import Blog.Core import Blog.Templates import Data.Monoid import Data.Text (Text) import Text.Blaze.Html5 (Html, toHtml, (!), toValue) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Text.Digestive hiding (required) import Text.Digestive.Blaze.Html5 import Text.Digestive.Forms.Happstack import Happstack.Server (finishWith) type AppForm a = HappstackForm App Html BlazeFormHtml a mkRequired :: (Eq a, Monoid a) => String -> AppForm a -> AppForm a mkRequired msg = flip validate (required $ toHtml msg) required :: (Monoid a, Eq a, Monad m) => errMsg -> Validator m errMsg a required e = check e (/= mempty) -- | Either display the given form to the client -- in a single response, or return the posted -- form value. handleForm :: Text -- ^ page title -> AppForm a -> App a handleForm title form = do r <- eitherHappstackForm form "form" case r of Left formV -> do let (renderedForm,_) = renderFormHtml formV response <- renderBlaze [("pageTitle", title)] "_layout" $ H.form ! A.method (toValue ("POST"::String)) $ do renderedForm H.input ! A.type_ "submit" finishWith response Right val -> return val
aslatter/blog
Blog/Forms.hs
gpl-3.0
1,416
0
18
386
402
218
184
39
2
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} -- | The handlers in this modules manage the sign in and sign out. module Account.Auth (getSignInR, getSignOutR, postSignInR, signInForm) where import Prelude import Control.Applicative as Import ((<$>), (<*>)) import Data.Text (Text) import Yesod import Account.Foundation import Account.Util (validateUser, setUserId, unsetUserId, redirectNoAuth) import Settings (widgetFile) -- | Displays the sign in form in the default layout. getSignInR :: YesodAccount parent => AccountHandler parent Html getSignInR = do lift redirectNoAuth lift (generateFormPost signInForm) >>= showForm -- | Tries to sign in the user. postSignInR :: YesodAccount parent => AccountHandler parent Html postSignInR = do lift redirectNoAuth ((res, widget), enctype) <- lift (runFormPost signInForm) case res of FormSuccess userId -> lift $ do setUserId userId getYesod >>= redirect . signInDest _ -> showForm (widget, enctype) -- | Removes the session value so the user is then signed out. Then redirects. getSignOutR :: YesodAccount parent => AccountHandler parent () getSignOutR = lift $ do unsetUserId getYesod >>= redirect . signOutDest -- | Responds with the sign in and the register forms in the default layout. showForm :: YesodAccount parent => (ParentWidget parent (), Enctype) -> AccountHandler parent Html showForm (widget, enctype) = do toParent <- getRouteToParent lift $ defaultLayout $ do setTitle "Sign in | getwebb" $(widgetFile "account-signin") -- | Generates a form which returns the username and the password. signInForm :: YesodAccount parent => Html -> MForm (ParentHandler parent) (FormResult (Key (AccountUser parent)) , ParentWidget parent ()) signInForm html = do let form = (,) <$> areq textField usernameSettings Nothing <*> areq passwordField passwordSettings Nothing (res, widget) <- renderDivs form html -- Checks the validity of the credentials. case res of FormSuccess (name, pass) -> do mUserId <- lift $ runDB $ validateUser name pass return $! case mUserId of Just userId -> (FormSuccess userId, widget) Nothing -> let msg = "Invalid username/email or password." :: Text widget' = [whamlet| <p .errors>#{msg} ^{widget} |] in (FormFailure [msg], widget') FormFailure errs -> return (FormFailure errs, widget) FormMissing -> return (FormMissing, widget) where usernameSettings = FieldSettings { fsLabel = "Username or email address", fsTooltip = Nothing , fsId = Nothing, fsName = Just "username", fsAttrs = [] } passwordSettings = FieldSettings { fsLabel = "Password", fsTooltip = Nothing, fsId = Nothing , fsName = Just "password", fsAttrs = [] }
RaphaelJ/getwebb.org
Account/Auth.hs
gpl-3.0
3,130
0
20
898
720
381
339
-1
-1
module Shape.Sphere where import Core.Constants import Core.Types import Core.Transform import Core.Geometry import Core.Intersection import Core.DifferentialGeometry import Data.Maybe (isJust) type Radius = DFloat data Sphere = Sphere {sphereToWorld :: Transform, worldToSphere :: Transform, radius :: Radius, zBounds :: Range, thetaBounds :: Range, phiMax :: Radians, objectBBox :: BBox, worldBBox :: BBox, revNormals :: Bool, revOrientation :: Bool, swapHands :: Bool} instance Shape Sphere where objectToWorld = sphereToWorld worldToObject = worldToSphere objectBound = objectBBox worldBound = worldBBox reverseNormals = revNormals reverseOrientation = revOrientation swapsHandedness = swapHands area = sphereArea instance Intersectable Sphere where intersect = sphereIntersect intersectP = sphereIntersectP sphere :: Transform -- | Object to world -> Transform -- | World to object -> Bool -- | Reverse orientation? -> Radius -- | Radius -> DFloat -- | Z min -> DFloat -- | Z max -> Degrees -- | Phi max -> Sphere sphere o2w w2o ro rad zMin zMax phiMax = Sphere {sphereToWorld = o2w, worldToSphere = w2o, radius = rad, zBounds = (zMin', zMax'), thetaBounds = (tMin', tMax'), phiMax = pMax', objectBBox = oBox, worldBBox = wBox, revNormals = False, revOrientation = ro, swapHands = undefined} where zMin' = clamp (-rad, rad) (min zMin zMax) zMax' = clamp (-rad, rad) (max zMin zMax) tMin' = acos (clamp (-1,1) (zMin/rad)) tMax' = acos (clamp (-1,1) (zMax/rad)) pMax' = toRadians (clamp (0,360) phiMax) oBox = BBox (Point (-rad) (-rad) zMin') (Point rad rad zMax') wBox = o2w `appTrans` oBox sphereIntersect :: Sphere -> Ray -> Maybe Intersection sphereIntersect sphere worldRay = sols >>= processSols sphere ray where ray = (worldToSphere sphere) `appTrans` worldRay rad = radius sphere a = normsq (direction ray) origin' = vecOfPoint $ origin ray b = 2 * (direction ray `dot` origin') c = normsq origin' - rad*rad sols = solveQuadratic (a,b,c) -- TODO: Make this more efficient sphereIntersectP :: Sphere -> Ray -> Bool sphereIntersectP sphere = isJust . sphereIntersect sphere processSols :: Sphere -> Ray -> QuadraticSol -> Maybe Intersection processSols sphere ray (t0, t1) | t0 > rMinT || t1 < rMinT || t0 < rMinT && t1 > rMaxT = Nothing | clipped = processClipped sphere ray tHit (t0,t1) | otherwise = succeed where (rMinT, rMaxT) = bounds ray tHit = if t0 < rMinT then t1 else t0 p@(Point px' py' pz') = stepRay ray tHit rad = radius sphere biasX = 1e-5 * rad pHit@(Point px py pz) = if px' == 0 && py' == 0 then Point biasX py' pz' else p phi' = atan2 py px phi = if phi' < 0 then phi' + 2*pi else phi (zMin, zMax) = zBounds sphere pMax = phiMax sphere clipped = zMin > -rad && pz < zMin || zMax < rad && pz > zMax || phi > pMax tHit' = if clipped then t1 else tHit pHit' = if clipped then stepRay ray tHit' else pHit succeed = processDiffGeom sphere ray pHit' phi tHit' processClipped :: Sphere -> Ray -> DFloat -> QuadraticSol -> Maybe Intersection processClipped sphere ray tHit (t0, t1) | tHit == t1 = Nothing | t1 > rMaxT = Nothing | outOfBounds = Nothing | otherwise = succeed where (rMinT, rMaxT) = bounds ray (zMin, zMax) = zBounds sphere rad = radius sphere checkIntPoint p@(Point x y z) | x == 0 && y == 0 = Point (1e-5 * rad) 0 z | otherwise = p pHit@(Point x y z) = checkIntPoint $ stepRay ray t1 phi = let phi' = atan2 y z in if phi' < 0 then phi' + 2*pi else phi' outOfBounds = (zMin > -rad && z < zMin) || (zMax < rad && z > zMax) || (phi > phiMax sphere) succeed = processDiffGeom sphere ray pHit phi tHit processDiffGeom :: Sphere -- | Sphere intersected -> Ray -- | Ray cast -> Point -- | Intersection point (phit) -> DFloat -- | Intersection angle (phi) -> DFloat -- | Parameter of intersection (thit) -> Maybe Intersection processDiffGeom sphere ray phit phi thit = Just res where (Point pHitX pHitY pHitZ) = phit (thetaMin, thetaMax) = thetaBounds sphere thetaRange = thetaMax - thetaMin rad = radius sphere pMax = phiMax sphere u = phi / pMax theta = acos(clamp (-1, 1) (pHitZ / rad)) v = (theta - thetaMin) / thetaRange zRadius = sqrt (pHitX*pHitX + pHitY*pHitY) invZRadius = 1/zRadius cosPhi = pHitX * invZRadius sinPhi = pHitY * invZRadius dpdu = Vector (-pMax * pHitY) (pMax * pHitX) 0 dpdv = thetaRange *^ Vector (pHitZ * cosPhi) (pHitZ * sinPhi) (-rad * sin theta) d2Pduu = (-pMax * pMax) *^ Vector pHitX pHitY 0 d2Pduv = (thetaRange * pHitZ * pMax) *^ Vector (-sinPhi) cosPhi 0 d2Pdvv = (-thetaRange * thetaRange) *^ Vector pHitX pHitY pHitZ ffE = dpdu `dot` dpdu ffF = dpdu `dot` dpdv ffG = dpdv `dot` dpdv ffN = hat $ dpdu `cross` dpdv ffe = ffN `dot` d2Pduu fff = ffN `dot` d2Pduv ffg = ffN `dot` d2Pdvv invEGF2 = 1 / (ffE*ffG - ffF*ffF) dndu = normalOfVec $ (((fff*ffF - ffe*ffG) * invEGF2) *^ dpdu) ^+^ (((ffe*ffF - fff*ffE) * invEGF2) *^ dpdv) dndv = normalOfVec $ (((ffg*ffF - fff*ffG) * invEGF2) *^ dpdu) ^+^ (((fff*ffF - ffg*ffE) * invEGF2) *^ dpdv) dg = defaultDiffGeom {p = phit, u = u, v = v, dpdu = dpdu, dpdv = dpdv, dndu = dndu, dndv = dndv, shape = Intersectable sphere} res = Intersection {tHit = thit, diffGeom = computeNormalFor dg, worldToInter = worldToObject sphere, interToWorld = objectToWorld sphere, rayEpsilon = thit * 5e-4} sphereArea :: Sphere -> DFloat sphereArea s = (phiMax s) * (radius s) * (zMax-zMin) where (zMin, zMax) = (zBounds s) sphereSample :: Sphere -> Point -> Range -> Normal -> Point sphereSample sphere p (u1,u2) ns | inside = uniformSample (u1,u2) ns | otherwise = sampleCone sphere p pCenter (u1,u2) ns where pCenter = objectToWorld sphere `appTrans` (Point 0 0 0) wc = hat (pCenter .-. p) (wcX,wcY) = coordinateSystem wc rad = radius sphere inside = distsq p pCenter - rad*rad < 1e-4 sampleCone = undefined -- sampleCone :: Sphere -> Point -> Point -> Range -> Normal -> Point -- sampleCone sphere p (u1,u2) ns = undefined -- where rad = radius sphere -- pCenter = objectToWorld sphere `appTrans` (Point 0 0 0) -- sinThetaMax2 = rad*rad / (distsq p pCenter) -- cosThetaMax = sqrt (max 0 (1 - sinThetaMax2)) -- TODO: Finish this uniformSample = undefined -- TODO: Remove this spherePDF :: Sphere -> Point -> Vector -> DFloat spherePDF = undefined
dsj36/dropray
src/Shape/Sphere.hs
gpl-3.0
8,804
0
16
3,758
2,391
1,310
1,081
171
6
module Example.Eg09 (eg09) where import Graphics.Radian import ExampleUtils eg09 :: IO Html eg09 = do d <- readCSV "vic2012ooa2.csv" ["date", "tmp", "prc"] #+ M.fromList [ ("date", [format.="date", dateFormat.= "%b"]) , ("tmp", [label.="Temperature", units.= "&deg;C"]) , ("prc", [label.="Rainfall", units.= "mm/day"]) ] let plot = Plot [Lines (d.^"date") (d.^"tmp")] # [height.=300, aspect.=3, strokeWidth.=2, stroke.="red", axisXLabel.="off"] source = exampleSource "Eg09.hs" return [shamlet| <h3> Example 9 (date handling) ^{plot} ^{source} |]
openbrainsrc/hRadian
examples/Example/Eg09.hs
mpl-2.0
647
8
15
167
230
125
105
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} -- | -- Module : Network.AWS.Data.Time -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : provisional -- Portability : non-portable (GHC extensions) -- module Network.AWS.Data.Time ( -- * Time Format (..) , Time (..) , _Time -- ** Formats , UTCTime , RFC822 , ISO8601 , BasicTime , AWSTime , POSIX ) where import Control.Applicative import Control.Lens import Data.Aeson import Data.Attoparsec.Text (Parser) import qualified Data.Attoparsec.Text as AText import qualified Data.ByteString.Char8 as BS import Data.Data (Data, Typeable) import Data.Monoid import Data.Scientific import Data.Tagged import qualified Data.Text as Text import Data.Time (UTCTime) import Data.Time.Clock.POSIX import Data.Time.Format (formatTime) import GHC.Generics (Generic) import Network.AWS.Compat.Locale import Network.AWS.Compat.Time import Network.AWS.Data.ByteString import Network.AWS.Data.JSON import Network.AWS.Data.Query import Network.AWS.Data.Text import Network.AWS.Data.XML import Prelude data Format = RFC822Format | ISO8601Format | BasicFormat | AWSFormat | POSIXFormat deriving (Eq, Read, Show, Data, Typeable, Generic) deriving instance Typeable 'RFC822Format deriving instance Typeable 'ISO8601Format deriving instance Typeable 'BasicFormat deriving instance Typeable 'AWSFormat deriving instance Typeable 'POSIXFormat data Time :: Format -> * where Time :: UTCTime -> Time a deriving (Data, Typeable, Generic) deriving instance Eq (Time a) deriving instance Ord (Time a) deriving instance Read (Time a) deriving instance Show (Time a) _Time :: Iso' (Time a) UTCTime _Time = iso (\(Time t) -> t) Time convert :: Time a -> Time b convert (Time t) = Time t type RFC822 = Time 'RFC822Format type ISO8601 = Time 'ISO8601Format type BasicTime = Time 'BasicFormat type AWSTime = Time 'AWSFormat type POSIX = Time 'POSIXFormat class TimeFormat a where format :: Tagged a String instance TimeFormat RFC822 where format = Tagged "%a, %d %b %Y %H:%M:%S GMT" instance TimeFormat ISO8601 where format = Tagged (iso8601DateFormat (Just "%X%QZ")) instance TimeFormat BasicTime where format = Tagged "%Y%m%d" instance TimeFormat AWSTime where format = Tagged "%Y%m%dT%H%M%SZ" instance FromText BasicTime where parser = parseFormattedTime instance FromText AWSTime where parser = parseFormattedTime instance FromText RFC822 where parser = (convert :: ISO8601 -> RFC822) <$> parseFormattedTime <|> parseFormattedTime instance FromText ISO8601 where parser = (convert :: RFC822 -> ISO8601) <$> parseFormattedTime <|> parseFormattedTime -- Deprecated, but ensure compatibility with examples until further investigation can be done <|> parseFormattedTime' (Tagged $ iso8601DateFormat (Just "%X%Q%Z")) instance FromText POSIX where parser = Time . posixSecondsToUTCTime . realToFrac <$> (parser :: Parser Scientific) parseFormattedTime :: forall a. TimeFormat (Time a) => Parser (Time a) parseFormattedTime = parseFormattedTime' format parseFormattedTime' :: Tagged (Time a) String -> Parser (Time a) parseFormattedTime' f = do x <- Text.unpack <$> AText.takeText p (parseTime defaultTimeLocale (untag f) x) x where p :: Maybe UTCTime -> String -> Parser (Time a) p (Just x) _ = return (Time x) p Nothing s = fail $ mconcat [ "Failure parsing Date format " , untag f , " from value: '" , s , "'" ] instance ToText RFC822 where toText = Text.pack . renderFormattedTime instance ToText ISO8601 where toText = Text.pack . renderFormattedTime instance ToText BasicTime where toText = Text.pack . renderFormattedTime instance ToText AWSTime where toText = Text.pack . renderFormattedTime instance ToText POSIX where toText (Time t) = toText (truncate (utcTimeToPOSIXSeconds t) :: Integer) renderFormattedTime :: forall a. TimeFormat (Time a) => Time a -> String renderFormattedTime (Time t) = formatTime defaultTimeLocale (untag f) t where f :: Tagged (Time a) String f = format instance FromXML RFC822 where parseXML = parseXMLText "RFC822" instance FromXML ISO8601 where parseXML = parseXMLText "ISO8601" instance FromXML AWSTime where parseXML = parseXMLText "AWSTime" instance FromXML BasicTime where parseXML = parseXMLText "BasicTime" instance FromXML POSIX where parseXML = parseXMLText "POSIX" instance FromJSON RFC822 where parseJSON = parseJSONText "RFC822" instance FromJSON ISO8601 where parseJSON = parseJSONText "ISO8601" instance FromJSON AWSTime where parseJSON = parseJSONText "AWSTime" instance FromJSON BasicTime where parseJSON = parseJSONText "BasicTime" instance FromJSON POSIX where parseJSON = withScientific "POSIX" $ pure . Time . posixSecondsToUTCTime . realToFrac instance ToByteString RFC822 where toBS = BS.pack . renderFormattedTime instance ToByteString ISO8601 where toBS = BS.pack . renderFormattedTime instance ToByteString BasicTime where toBS = BS.pack . renderFormattedTime instance ToByteString AWSTime where toBS = BS.pack . renderFormattedTime instance ToQuery RFC822 where toQuery = toQuery . toBS instance ToQuery ISO8601 where toQuery = toQuery . toBS instance ToQuery BasicTime where toQuery = toQuery . toBS instance ToQuery AWSTime where toQuery = toQuery . toBS instance ToXML RFC822 where toXML = toXMLText instance ToXML ISO8601 where toXML = toXMLText instance ToXML AWSTime where toXML = toXMLText instance ToXML BasicTime where toXML = toXMLText instance ToXML POSIX where toXML = toXMLText instance ToJSON RFC822 where toJSON = toJSONText instance ToJSON ISO8601 where toJSON = toJSONText instance ToJSON AWSTime where toJSON = toJSONText instance ToJSON BasicTime where toJSON = toJSONText instance ToJSON POSIX where toJSON (Time t) = Number $ scientific (truncate (utcTimeToPOSIXSeconds t) :: Integer) 0
olorin/amazonka
core/src/Network/AWS/Data/Time.hs
mpl-2.0
6,974
1
12
1,678
1,678
908
770
151
2
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} module Data.Swagger.Build.Resource ( Data.Swagger.Build.Resource.resources , Data.Swagger.Build.Resource.api , Data.Swagger.Build.Resource.apiVersion , Data.Swagger.Build.Resource.info , Data.Swagger.Build.Resource.termsOfServiceUrl , Data.Swagger.Build.Resource.contact , Data.Swagger.Build.Resource.license , Data.Swagger.Build.Resource.licenseUrl , Data.Swagger.Build.Resource.authorisation , Data.Swagger.Build.Util.end -- * builder types , ResourcesBuilder , InfoBuilder ) where import Control.Monad.Trans.State.Strict import Data.Text (Text) import Data.Swagger.Build.Util hiding (authorisation) import Data.Swagger.Model.Authorisation as A import Data.Swagger.Model.Resource as R type ResourcesBuilder = State Resources () -- | Construct a resource listing object given a swagger version and some -- resource objects. resources :: Text -> ResourcesBuilder -> Resources resources v s = execState s start where start = Resources v [] Nothing Nothing Nothing type ResourceSt = Common '["description"] Resource type ResourceBuilder = State ResourceSt () -- | Add one resource object to a resource listing given a path and some -- resource specific values. api :: Text -> ResourceBuilder -> ResourcesBuilder api p s = modify $ \r -> r { apis = value (execState s start) : apis r } where start = common $ Resource p Nothing value c = (other c) { R.description = descr c } apiVersion :: Text -> ResourcesBuilder apiVersion v = modify $ \r -> r { R.apiVersion = Just v } type InfoSt = Common '["description"] Info type InfoBuilder = State InfoSt () -- | Set the info object of a resource listing object given a title and -- other infor object specific values. info :: Text -> InfoBuilder -> ResourcesBuilder info t s = modify $ \r -> r { R.info = Just $ value (execState s start) } where start = common $ Info t Nothing Nothing Nothing Nothing Nothing value c = (other c) { infoDescription = descr c } termsOfServiceUrl :: Text -> InfoBuilder termsOfServiceUrl u = modify $ \c -> c { other = (other c) { R.termsOfServiceUrl = Just u } } contact :: Text -> InfoBuilder contact u = modify $ \c -> c { other = (other c) { R.contact = Just u } } license :: Text -> InfoBuilder license u = modify $ \c -> c { other = (other c) { R.license = Just u } } licenseUrl :: Text -> InfoBuilder licenseUrl u = modify $ \c -> c { other = (other c) { R.licenseUrl = Just u } } -- | Add a authorisation object to a resource listing with the given name. authorisation :: Text -> Authorisation -> ResourcesBuilder authorisation n a = modify $ \r -> let x = (n, a) in r { authorisations = maybe (Just [x]) (Just . (x:)) (authorisations r) }
twittner/swagger
src/Data/Swagger/Build/Resource.hs
mpl-2.0
3,032
0
14
594
826
476
350
52
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.Classroom.Courses.CourseWorkMaterials.Patch -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates one or more fields of a course work material. This method -- returns the following error codes: * \`PERMISSION_DENIED\` if the -- requesting developer project for access errors. * \`INVALID_ARGUMENT\` -- if the request is malformed. * \`FAILED_PRECONDITION\` if the requested -- course work material has already been deleted. * \`NOT_FOUND\` if the -- requested course or course work material does not exist -- -- /See:/ <https://developers.google.com/classroom/ Google Classroom API Reference> for @classroom.courses.courseWorkMaterials.patch@. module Network.Google.Resource.Classroom.Courses.CourseWorkMaterials.Patch ( -- * REST Resource CoursesCourseWorkMaterialsPatchResource -- * Creating a Request , coursesCourseWorkMaterialsPatch , CoursesCourseWorkMaterialsPatch -- * Request Lenses , ccwmpXgafv , ccwmpUploadProtocol , ccwmpUpdateMask , ccwmpCourseId , ccwmpAccessToken , ccwmpUploadType , ccwmpPayload , ccwmpId , ccwmpCallback ) where import Network.Google.Classroom.Types import Network.Google.Prelude -- | A resource alias for @classroom.courses.courseWorkMaterials.patch@ method which the -- 'CoursesCourseWorkMaterialsPatch' request conforms to. type CoursesCourseWorkMaterialsPatchResource = "v1" :> "courses" :> Capture "courseId" Text :> "courseWorkMaterials" :> Capture "id" 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] CourseWorkMaterial :> Patch '[JSON] CourseWorkMaterial -- | Updates one or more fields of a course work material. This method -- returns the following error codes: * \`PERMISSION_DENIED\` if the -- requesting developer project for access errors. * \`INVALID_ARGUMENT\` -- if the request is malformed. * \`FAILED_PRECONDITION\` if the requested -- course work material has already been deleted. * \`NOT_FOUND\` if the -- requested course or course work material does not exist -- -- /See:/ 'coursesCourseWorkMaterialsPatch' smart constructor. data CoursesCourseWorkMaterialsPatch = CoursesCourseWorkMaterialsPatch' { _ccwmpXgafv :: !(Maybe Xgafv) , _ccwmpUploadProtocol :: !(Maybe Text) , _ccwmpUpdateMask :: !(Maybe GFieldMask) , _ccwmpCourseId :: !Text , _ccwmpAccessToken :: !(Maybe Text) , _ccwmpUploadType :: !(Maybe Text) , _ccwmpPayload :: !CourseWorkMaterial , _ccwmpId :: !Text , _ccwmpCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CoursesCourseWorkMaterialsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccwmpXgafv' -- -- * 'ccwmpUploadProtocol' -- -- * 'ccwmpUpdateMask' -- -- * 'ccwmpCourseId' -- -- * 'ccwmpAccessToken' -- -- * 'ccwmpUploadType' -- -- * 'ccwmpPayload' -- -- * 'ccwmpId' -- -- * 'ccwmpCallback' coursesCourseWorkMaterialsPatch :: Text -- ^ 'ccwmpCourseId' -> CourseWorkMaterial -- ^ 'ccwmpPayload' -> Text -- ^ 'ccwmpId' -> CoursesCourseWorkMaterialsPatch coursesCourseWorkMaterialsPatch pCcwmpCourseId_ pCcwmpPayload_ pCcwmpId_ = CoursesCourseWorkMaterialsPatch' { _ccwmpXgafv = Nothing , _ccwmpUploadProtocol = Nothing , _ccwmpUpdateMask = Nothing , _ccwmpCourseId = pCcwmpCourseId_ , _ccwmpAccessToken = Nothing , _ccwmpUploadType = Nothing , _ccwmpPayload = pCcwmpPayload_ , _ccwmpId = pCcwmpId_ , _ccwmpCallback = Nothing } -- | V1 error format. ccwmpXgafv :: Lens' CoursesCourseWorkMaterialsPatch (Maybe Xgafv) ccwmpXgafv = lens _ccwmpXgafv (\ s a -> s{_ccwmpXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ccwmpUploadProtocol :: Lens' CoursesCourseWorkMaterialsPatch (Maybe Text) ccwmpUploadProtocol = lens _ccwmpUploadProtocol (\ s a -> s{_ccwmpUploadProtocol = a}) -- | Mask that identifies which fields on the course work material to update. -- This field is required to do an update. The update fails if invalid -- fields are specified. If a field supports empty values, it can be -- cleared by specifying it in the update mask and not in the course work -- material object. If a field that does not support empty values is -- included in the update mask and not set in the course work material -- object, an \`INVALID_ARGUMENT\` error is returned. The following fields -- may be specified by teachers: * \`title\` * \`description\` * \`state\` -- * \`scheduled_time\` * \`topic_id\` ccwmpUpdateMask :: Lens' CoursesCourseWorkMaterialsPatch (Maybe GFieldMask) ccwmpUpdateMask = lens _ccwmpUpdateMask (\ s a -> s{_ccwmpUpdateMask = a}) -- | Identifier of the course. This identifier can be either the -- Classroom-assigned identifier or an alias. ccwmpCourseId :: Lens' CoursesCourseWorkMaterialsPatch Text ccwmpCourseId = lens _ccwmpCourseId (\ s a -> s{_ccwmpCourseId = a}) -- | OAuth access token. ccwmpAccessToken :: Lens' CoursesCourseWorkMaterialsPatch (Maybe Text) ccwmpAccessToken = lens _ccwmpAccessToken (\ s a -> s{_ccwmpAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ccwmpUploadType :: Lens' CoursesCourseWorkMaterialsPatch (Maybe Text) ccwmpUploadType = lens _ccwmpUploadType (\ s a -> s{_ccwmpUploadType = a}) -- | Multipart request metadata. ccwmpPayload :: Lens' CoursesCourseWorkMaterialsPatch CourseWorkMaterial ccwmpPayload = lens _ccwmpPayload (\ s a -> s{_ccwmpPayload = a}) -- | Identifier of the course work material. ccwmpId :: Lens' CoursesCourseWorkMaterialsPatch Text ccwmpId = lens _ccwmpId (\ s a -> s{_ccwmpId = a}) -- | JSONP ccwmpCallback :: Lens' CoursesCourseWorkMaterialsPatch (Maybe Text) ccwmpCallback = lens _ccwmpCallback (\ s a -> s{_ccwmpCallback = a}) instance GoogleRequest CoursesCourseWorkMaterialsPatch where type Rs CoursesCourseWorkMaterialsPatch = CourseWorkMaterial type Scopes CoursesCourseWorkMaterialsPatch = '["https://www.googleapis.com/auth/classroom.courseworkmaterials"] requestClient CoursesCourseWorkMaterialsPatch'{..} = go _ccwmpCourseId _ccwmpId _ccwmpXgafv _ccwmpUploadProtocol _ccwmpUpdateMask _ccwmpAccessToken _ccwmpUploadType _ccwmpCallback (Just AltJSON) _ccwmpPayload classroomService where go = buildClient (Proxy :: Proxy CoursesCourseWorkMaterialsPatchResource) mempty
brendanhay/gogol
gogol-classroom/gen/Network/Google/Resource/Classroom/Courses/CourseWorkMaterials/Patch.hs
mpl-2.0
7,827
0
20
1,725
957
563
394
142
1
-- | Low-level messaging between this client and the MongoDB server, see Mongo -- Wire Protocol (<http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol>). -- -- This module is not intended for direct use. Use the high-level interface at -- "Database.MongoDB.Query" and "Database.MongoDB.Connection" instead. {-# LANGUAGE RecordWildCards, StandaloneDeriving, OverloadedStrings #-} {-# LANGUAGE CPP, FlexibleContexts, TupleSections, TypeSynonymInstances #-} {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, UndecidableInstances #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE NamedFieldPuns, ScopedTypeVariables #-} #if (__GLASGOW_HASKELL__ >= 706) {-# LANGUAGE RecursiveDo #-} #else {-# LANGUAGE DoRec #-} #endif module Database.MongoDB.Internal.Protocol ( FullCollection, -- * Pipe Pipe, newPipe, newPipeWith, send, call, -- ** Notice Notice(..), InsertOption(..), UpdateOption(..), DeleteOption(..), CursorId, -- ** Request Request(..), QueryOption(..), -- ** Reply Reply(..), ResponseFlag(..), -- * Authentication Username, Password, Nonce, pwHash, pwKey, isClosed, close, ServerData(..), Pipeline(..) ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>)) #endif import Control.Monad (forM, replicateM, unless) import Data.Binary.Get (Get, runGet) import Data.Binary.Put (Put, runPut) import Data.Bits (bit, testBit) import Data.Int (Int32, Int64) import Data.IORef (IORef, newIORef, atomicModifyIORef) import System.IO (Handle) import System.IO.Error (doesNotExistErrorType, mkIOError) import System.IO.Unsafe (unsafePerformIO) import Data.Maybe (maybeToList) import GHC.Conc (ThreadStatus(..), threadStatus) import Control.Monad (forever) import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan, isEmptyChan) import Control.Concurrent (ThreadId, killThread, forkFinally) import Control.Exception.Lifted (onException, throwIO, try) import qualified Data.ByteString.Lazy as L import Control.Monad.Trans (MonadIO, liftIO) import Data.Bson (Document) import Data.Bson.Binary (getDocument, putDocument, getInt32, putInt32, getInt64, putInt64, putCString) import Data.Text (Text) import qualified Crypto.Hash.MD5 as MD5 import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Database.MongoDB.Internal.Util (bitOr, byteStringHex) import Database.MongoDB.Transport (Transport) import qualified Database.MongoDB.Transport as Tr #if MIN_VERSION_base(4,6,0) import Control.Concurrent.MVar.Lifted (MVar, newEmptyMVar, newMVar, withMVar, putMVar, readMVar, mkWeakMVar, isEmptyMVar) #else import Control.Concurrent.MVar.Lifted (MVar, newEmptyMVar, newMVar, withMVar, putMVar, readMVar, addMVarFinalizer) #endif #if !MIN_VERSION_base(4,6,0) mkWeakMVar :: MVar a -> IO () -> IO () mkWeakMVar = addMVarFinalizer #endif -- * Pipeline -- | Thread-safe and pipelined connection data Pipeline = Pipeline { vStream :: MVar Transport -- ^ Mutex on handle, so only one thread at a time can write to it , responseQueue :: Chan (MVar (Either IOError Response)) -- ^ Queue of threads waiting for responses. Every time a response arrive we pop the next thread and give it the response. , listenThread :: ThreadId , finished :: MVar () , serverData :: ServerData } data ServerData = ServerData { isMaster :: Bool , minWireVersion :: Int , maxWireVersion :: Int , maxMessageSizeBytes :: Int , maxBsonObjectSize :: Int , maxWriteBatchSize :: Int } -- | Create new Pipeline over given handle. You should 'close' pipeline when finished, which will also close handle. If pipeline is not closed but eventually garbage collected, it will be closed along with handle. newPipeline :: ServerData -> Transport -> IO Pipeline newPipeline serverData stream = do vStream <- newMVar stream responseQueue <- newChan finished <- newEmptyMVar let drainReplies = do chanEmpty <- isEmptyChan responseQueue if chanEmpty then return () else do var <- readChan responseQueue putMVar var $ Left $ mkIOError doesNotExistErrorType "Handle has been closed" Nothing Nothing drainReplies rec let pipe = Pipeline{..} listenThread <- forkFinally (listen pipe) $ \_ -> do putMVar finished () drainReplies _ <- mkWeakMVar vStream $ do killThread listenThread Tr.close stream return pipe isFinished :: Pipeline -> IO Bool isFinished Pipeline {finished} = do empty <- isEmptyMVar finished return $ not empty close :: Pipeline -> IO () -- ^ Close pipe and underlying connection close Pipeline{..} = do killThread listenThread Tr.close =<< readMVar vStream isClosed :: Pipeline -> IO Bool isClosed Pipeline{listenThread} = do status <- threadStatus listenThread return $ case status of ThreadRunning -> False ThreadFinished -> True ThreadBlocked _ -> False ThreadDied -> True --isPipeClosed Pipeline{..} = isClosed =<< readMVar vHandle -- isClosed hangs while listen loop is waiting on read listen :: Pipeline -> IO () -- ^ Listen for responses and supply them to waiting threads in order listen Pipeline{..} = do stream <- readMVar vStream forever $ do e <- try $ readMessage stream var <- readChan responseQueue putMVar var e case e of Left err -> Tr.close stream >> ioError err -- close and stop looping Right _ -> return () psend :: Pipeline -> Message -> IO () -- ^ Send message to destination; the destination must not response (otherwise future 'call's will get these responses instead of their own). -- Throw IOError and close pipeline if send fails psend p@Pipeline{..} !message = withMVar vStream (flip writeMessage message) `onException` close p pcall :: Pipeline -> Message -> IO (IO Response) -- ^ Send message to destination and return /promise/ of response from one message only. The destination must reply to the message (otherwise promises will have the wrong responses in them). -- Throw IOError and closes pipeline if send fails, likewise for promised response. pcall p@Pipeline{..} message = do listenerStopped <- isFinished p if listenerStopped then ioError $ mkIOError doesNotExistErrorType "Handle has been closed" Nothing Nothing else withMVar vStream doCall `onException` close p where doCall stream = do writeMessage stream message var <- newEmptyMVar liftIO $ writeChan responseQueue var return $ readMVar var >>= either throwIO return -- return promise -- * Pipe type Pipe = Pipeline -- ^ Thread-safe TCP connection with pipelined requests newPipe :: ServerData -> Handle -> IO Pipe -- ^ Create pipe over handle newPipe sd handle = Tr.fromHandle handle >>= (newPipeWith sd) newPipeWith :: ServerData -> Transport -> IO Pipe -- ^ Create pipe over connection newPipeWith sd conn = newPipeline sd conn send :: Pipe -> [Notice] -> IO () -- ^ Send notices as a contiguous batch to server with no reply. Throw IOError if connection fails. send pipe notices = psend pipe (notices, Nothing) call :: Pipe -> [Notice] -> Request -> IO (IO Reply) -- ^ Send notices and request as a contiguous batch to server and return reply promise, which will block when invoked until reply arrives. This call and resulting promise will throw IOError if connection fails. call pipe notices request = do requestId <- genRequestId promise <- pcall pipe (notices, Just (request, requestId)) return $ check requestId <$> promise where check requestId (responseTo, reply) = if requestId == responseTo then reply else error $ "expected response id (" ++ show responseTo ++ ") to match request id (" ++ show requestId ++ ")" -- * Message type Message = ([Notice], Maybe (Request, RequestId)) -- ^ A write notice(s) with getLastError request, or just query request. -- Note, that requestId will be out of order because request ids will be generated for notices after the request id supplied was generated. This is ok because the mongo server does not care about order just uniqueness. writeMessage :: Transport -> Message -> IO () -- ^ Write message to connection writeMessage conn (notices, mRequest) = do noticeStrings <- forM notices $ \n -> do requestId <- genRequestId let s = runPut $ putNotice n requestId return $ (lenBytes s) `L.append` s let requestString = do (request, requestId) <- mRequest let s = runPut $ putRequest request requestId return $ (lenBytes s) `L.append` s Tr.write conn $ L.toStrict $ L.concat $ noticeStrings ++ (maybeToList requestString) Tr.flush conn where lenBytes bytes = encodeSize . toEnum . fromEnum $ L.length bytes encodeSize = runPut . putInt32 . (+ 4) type Response = (ResponseTo, Reply) -- ^ Message received from a Mongo server in response to a Request readMessage :: Transport -> IO Response -- ^ read response from a connection readMessage conn = readResp where readResp = do len <- fromEnum . decodeSize . L.fromStrict <$> Tr.read conn 4 runGet getReply . L.fromStrict <$> Tr.read conn len decodeSize = subtract 4 . runGet getInt32 type FullCollection = Text -- ^ Database name and collection name with period (.) in between. Eg. \"myDb.myCollection\" -- ** Header type Opcode = Int32 type RequestId = Int32 -- ^ A fresh request id is generated for every message type ResponseTo = RequestId genRequestId :: (MonadIO m) => m RequestId -- ^ Generate fresh request id genRequestId = liftIO $ atomicModifyIORef counter $ \n -> (n + 1, n) where counter :: IORef RequestId counter = unsafePerformIO (newIORef 0) {-# NOINLINE counter #-} -- *** Binary format putHeader :: Opcode -> RequestId -> Put -- ^ Note, does not write message length (first int32), assumes caller will write it putHeader opcode requestId = do putInt32 requestId putInt32 0 putInt32 opcode getHeader :: Get (Opcode, ResponseTo) -- ^ Note, does not read message length (first int32), assumes it was already read getHeader = do _requestId <- getInt32 responseTo <- getInt32 opcode <- getInt32 return (opcode, responseTo) -- ** Notice -- | A notice is a message that is sent with no reply data Notice = Insert { iFullCollection :: FullCollection, iOptions :: [InsertOption], iDocuments :: [Document]} | Update { uFullCollection :: FullCollection, uOptions :: [UpdateOption], uSelector :: Document, uUpdater :: Document} | Delete { dFullCollection :: FullCollection, dOptions :: [DeleteOption], dSelector :: Document} | KillCursors { kCursorIds :: [CursorId]} deriving (Show, Eq) data InsertOption = KeepGoing -- ^ If set, the database will not stop processing a bulk insert if one fails (eg due to duplicate IDs). This makes bulk insert behave similarly to a series of single inserts, except lastError will be set if any insert fails, not just the last one. (new in 1.9.1) deriving (Show, Eq) data UpdateOption = Upsert -- ^ If set, the database will insert the supplied object into the collection if no matching document is found | MultiUpdate -- ^ If set, the database will update all matching objects in the collection. Otherwise only updates first matching doc deriving (Show, Eq) data DeleteOption = SingleRemove -- ^ If set, the database will remove only the first matching document in the collection. Otherwise all matching documents will be removed deriving (Show, Eq) type CursorId = Int64 -- *** Binary format nOpcode :: Notice -> Opcode nOpcode Update{} = 2001 nOpcode Insert{} = 2002 nOpcode Delete{} = 2006 nOpcode KillCursors{} = 2007 putNotice :: Notice -> RequestId -> Put putNotice notice requestId = do putHeader (nOpcode notice) requestId case notice of Insert{..} -> do putInt32 (iBits iOptions) putCString iFullCollection mapM_ putDocument iDocuments Update{..} -> do putInt32 0 putCString uFullCollection putInt32 (uBits uOptions) putDocument uSelector putDocument uUpdater Delete{..} -> do putInt32 0 putCString dFullCollection putInt32 (dBits dOptions) putDocument dSelector KillCursors{..} -> do putInt32 0 putInt32 $ toEnum (length kCursorIds) mapM_ putInt64 kCursorIds iBit :: InsertOption -> Int32 iBit KeepGoing = bit 0 iBits :: [InsertOption] -> Int32 iBits = bitOr . map iBit uBit :: UpdateOption -> Int32 uBit Upsert = bit 0 uBit MultiUpdate = bit 1 uBits :: [UpdateOption] -> Int32 uBits = bitOr . map uBit dBit :: DeleteOption -> Int32 dBit SingleRemove = bit 0 dBits :: [DeleteOption] -> Int32 dBits = bitOr . map dBit -- ** Request -- | A request is a message that is sent with a 'Reply' expected in return data Request = Query { qOptions :: [QueryOption], qFullCollection :: FullCollection, qSkip :: Int32, -- ^ Number of initial matching documents to skip qBatchSize :: Int32, -- ^ The number of document to return in each batch response from the server. 0 means use Mongo default. Negative means close cursor after first batch and use absolute value as batch size. qSelector :: Document, -- ^ \[\] = return all documents in collection qProjector :: Document -- ^ \[\] = return whole document } | GetMore { gFullCollection :: FullCollection, gBatchSize :: Int32, gCursorId :: CursorId} deriving (Show, Eq) data QueryOption = TailableCursor -- ^ Tailable means cursor is not closed when the last data is retrieved. Rather, the cursor marks the final object's position. You can resume using the cursor later, from where it was located, if more data were received. Like any "latent cursor", the cursor may become invalid at some point – for example if the final object it references were deleted. Thus, you should be prepared to requery on CursorNotFound exception. | SlaveOK -- ^ Allow query of replica slave. Normally these return an error except for namespace "local". | NoCursorTimeout -- ^ The server normally times out idle cursors after 10 minutes to prevent a memory leak in case a client forgets to close a cursor. Set this option to allow a cursor to live forever until it is closed. | AwaitData -- ^ Use with TailableCursor. If we are at the end of the data, block for a while rather than returning no data. After a timeout period, we do return as normal. -- | Exhaust -- ^ Stream the data down full blast in multiple "more" packages, on the assumption that the client will fully read all data queried. Faster when you are pulling a lot of data and know you want to pull it all down. Note: the client is not allowed to not read all the data unless it closes the connection. -- Exhaust commented out because not compatible with current `Pipeline` implementation | Partial -- ^ Get partial results from a _mongos_ if some shards are down, instead of throwing an error. deriving (Show, Eq) -- *** Binary format qOpcode :: Request -> Opcode qOpcode Query{} = 2004 qOpcode GetMore{} = 2005 putRequest :: Request -> RequestId -> Put putRequest request requestId = do putHeader (qOpcode request) requestId case request of Query{..} -> do putInt32 (qBits qOptions) putCString qFullCollection putInt32 qSkip putInt32 qBatchSize putDocument qSelector unless (null qProjector) (putDocument qProjector) GetMore{..} -> do putInt32 0 putCString gFullCollection putInt32 gBatchSize putInt64 gCursorId qBit :: QueryOption -> Int32 qBit TailableCursor = bit 1 qBit SlaveOK = bit 2 qBit NoCursorTimeout = bit 4 qBit AwaitData = bit 5 --qBit Exhaust = bit 6 qBit Partial = bit 7 qBits :: [QueryOption] -> Int32 qBits = bitOr . map qBit -- ** Reply -- | A reply is a message received in response to a 'Request' data Reply = Reply { rResponseFlags :: [ResponseFlag], rCursorId :: CursorId, -- ^ 0 = cursor finished rStartingFrom :: Int32, rDocuments :: [Document] } deriving (Show, Eq) data ResponseFlag = CursorNotFound -- ^ Set when getMore is called but the cursor id is not valid at the server. Returned with zero results. | QueryError -- ^ Query error. Returned with one document containing an "$err" field holding the error message. | AwaitCapable -- ^ For backward compatability: Set when the server supports the AwaitData query option. if it doesn't, a replica slave client should sleep a little between getMore's deriving (Show, Eq, Enum) -- * Binary format replyOpcode :: Opcode replyOpcode = 1 getReply :: Get (ResponseTo, Reply) getReply = do (opcode, responseTo) <- getHeader unless (opcode == replyOpcode) $ fail $ "expected reply opcode (1) but got " ++ show opcode rResponseFlags <- rFlags <$> getInt32 rCursorId <- getInt64 rStartingFrom <- getInt32 numDocs <- fromIntegral <$> getInt32 rDocuments <- replicateM numDocs getDocument return (responseTo, Reply{..}) rFlags :: Int32 -> [ResponseFlag] rFlags bits = filter (testBit bits . rBit) [CursorNotFound ..] rBit :: ResponseFlag -> Int rBit CursorNotFound = 0 rBit QueryError = 1 rBit AwaitCapable = 3 -- * Authentication type Username = Text type Password = Text type Nonce = Text pwHash :: Username -> Password -> Text pwHash u p = T.pack . byteStringHex . MD5.hash . TE.encodeUtf8 $ u `T.append` ":mongo:" `T.append` p pwKey :: Nonce -> Username -> Password -> Text pwKey n u p = T.pack . byteStringHex . MD5.hash . TE.encodeUtf8 . T.append n . T.append u $ pwHash u p {- Authors: Tony Hannan <tony@10gen.com> Copyright 2011 10gen 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. -}
Yuras/mongodb
Database/MongoDB/Internal/Protocol.hs
apache-2.0
19,023
0
17
4,499
3,686
1,981
1,705
330
4
module Problem066 where main = print $ maximum [(pell n, n) | n <- [1 .. 1000]] pell n | s * s == n = 0 | otherwise = pell' (0, 1, s) (s, 1) (1, 0) where s = sqrt' n pell' (m, d, a) (n0, n1) (d0, d1) | n0 * n0 - n * d0 * d0 == 1 = abs n0 | otherwise = let m' = d * a - m d' = (n - m' * m') `div` d a' = (s + m') `div` d' n0' = a' * n0 + n1 d0' = a' * d0 + d1 in pell' (m', d', a') (n0', n0) (d0', d0) sqrt' = round . sqrt . fromIntegral
vasily-kartashov/playground
euler/problem-066.hs
apache-2.0
612
0
15
298
308
168
140
16
1
module Kata02.Chop1 (chop) where import Data.List import Kata02.Utils chop :: Int -> [Int] -> Int chop _ [] = -1 chop x [y] | x == y = 0 | otherwise = -1 chop x xs = let start = 0 end = (length xs) - 1 in chop' x xs start end chop' :: Int -> [Int] -> Int -> Int -> Int chop' x xs start end | start == end = if x == (xs !! start) then start else -1 | otherwise = let mid = middle $ [start..end] first = xs !! mid second = xs !! (mid + 1) in if x <= first then chop' x xs start mid else chop' x xs (mid + 1) end
safwank/HaskellKata
src/Kata02/Chop1.hs
apache-2.0
624
0
12
238
290
150
140
24
3
{- Copyright 2015 Tristan Aubrey-Jones 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. -} {-| Copyright : (c) Tristan Aubrey-Jones, 2015 License : Apache-2 Maintainer : developer@flocc.net Stability : experimental For more information please see <http://www.flocc.net/> -} module Compiler.Types.Builder where import Compiler.Front.Common (delimList, maybeError) import Compiler.Front.Indices (Idx, IdxSet, IdxMonad) import Compiler.Front.ExprTree (Expr(Let, Lit, Tup, Rel, If, App, Fun), renewIdAndExprIds, StructEq(..), showExprTree) import qualified Compiler.Front.ExprTree as ExprTree (Expr(Var)) import Compiler.Types.TermLanguage (Term(..), Constr(..), Subst(..), MonadicUnifierExtension, Scheme(..), SchemeEx(..), getIdsInIdTree, IdTree(..), forAllSubs, subInTerm, FunctionToken(..), Subst, monadicUnifyTrans, emptyTermEnv, applyVarSubstsToConstr, bindTermInState, instantiateScheme, generalizeTerm, bindNewTermVarInState, instantiateSchemeEx, instantiateSchemeEx2, schemeEnvToSchemeExEnv, lookupTermMaybe, unifyConstraints) import Compiler.Types.TermBuilder (buildForIdxTree, fun, tup) import Compiler.Types.TypeAssignment (TyToken(..), TyTerm, TyConstr, TyScheme, TySchemeEx, TyEnv, typeOfVal, rel, relNonOrd, showExprWithTypes) import Compiler.Types.Variables (VarSubsts, VarsIn(..), emptyVarSubsts, composeVarSubsts) import qualified Compiler.Types.Variables as Variables (fromList) import Compiler.Types.EmbeddedFunctions import Control.Monad.Identity (Identity, runIdentity) import Control.Monad.State.Strict (StateT, runStateT, evalStateT, lift, get, modify) import qualified Data.IntMap.Strict as IM import qualified Data.Map.Strict as M import Data.Set (Set, unions, intersection, null) import Data.IntMap.Strict ((\\)) import Debug.Trace (trace) -- |trace is used to display or hide debugging -- |info depending on its implementation trace' :: String -> a -> a --trace' s = trace s trace' s a = a type ExpMap a = IM.IntMap a type VarMap v = IM.IntMap v -- |expMapFromList takes an associative array and returns -- |the ExpMap equivalent. expMapFromList :: [(Idx,v)] -> VarMap v expMapFromList l = IM.fromList l -- |varMapLookup returns the value stored under the key given -- |in the VarMap provided. varMapLookup :: VarMap a -> Idx -> Maybe a varMapLookup mp idx = IM.lookup idx mp -- |varMapFromList takes an associative array and returns -- |the VarMap equivalent. varMapFromList :: [(Idx,v)] -> VarMap v varMapFromList l = IM.fromList l varMapFromSchemeEnv :: [(Idx, Scheme t)] -> VarMap (Term t) varMapFromSchemeEnv l = varMapFromList $ map (\(i, Scheme l t) -> if length l /= 0 then error $ "varMapFromSchemeEnv:non empty var list:" ++ (show l) else (i,t)) l -- |composeVarMaps creates the left biased union of -- |VarMaps a and b. composeVarMaps :: VarMap a -> VarMap a -> VarMap a composeVarMaps a b = a `IM.union` b -- |Pretty print type scheme showDepTyScheme :: TyScheme -> String showDepTyScheme (Scheme [] term) = showEmbeddedFuns term showDepTyScheme (Scheme vars term) = "forall " ++ (delimList "," $ map (\i -> ("v" ++ show i)) vars) ++ " => " ++ (showEmbeddedFuns term) showDepExprTy :: TyEnv -> Idx -> String showDepExprTy env idx = case lookupTermMaybe env idx of Just v -> " :: " ++ (showDepTyScheme v) Nothing -> " :: ERROR: no type term exists in env with idx " ++ (show idx) showExprWithDepTypes :: TyEnv -> Expr -> String showExprWithDepTypes env exp = showExprTree env showDepExprTy 2 exp -- |lookupVar takes two var maps and an id and tries to -- |lookup the value in the first map, or failing that in -- |the second map. lookupVar :: VarMap a -> VarMap a -> Idx -> Maybe a lookupVar globals locals id = case varMapLookup locals id of Just v -> Just v Nothing -> case varMapLookup globals id of Just v -> Just v Nothing -> Nothing -- |getIdExprPairs zips together an IdTree and a tuple expression tree -- |returning a lift of pairs of id tree ids to expressions. getIdExprPairs :: (IdTree, Expr) -> [(Idx, Expr)] getIdExprPairs ab = case ab of ((IdTup al),(Tup _ bl)) | length al == length bl -> concat $ map getIdExprPairs $ zip al bl ((IdLeaf ai),expr) -> [(ai, expr)] ((IdBlank),_) -> [] other -> error $ "DepTyAss:getIdExprPairs: IdTree and Expr tuple tree are not isomorphic: " ++ (show ab) -- |Instantiates a term SchemeEx by replacing every qualified term variable -- |with a new variable, and every function application qualified variable -- |with a ref to that var id (or expression id). instantiateSchemeEx3 :: Monad m => TySchemeEx -> Expr -> IdxMonad m TyTerm instantiateSchemeEx3 (SchemeEx it inner) expr = do term <- instantiateScheme inner let varPairs = getIdExprPairs (it, expr) varSubs <- mapM (\(from,to) -> embedFun [] to >>= (\t -> return $ trace ("Embed: " ++ (show to) ++ " => \n" ++ (show t) ++ "\n") $ (Var from) :|-> t)) varPairs let term' = forAllSubs subInTerm varSubs term return term' -- |For a given expression sets up the type environment, constraints, -- |and expandable expression map. buildConstrs :: Monad m => VarMap TySchemeEx -> -- global var types VarMap TySchemeEx -> -- local var types Expr -> StateT TyEnv (IdxMonad m) ([TyConstr], TyTerm) buildConstrs globalEnv localEnv exp = case exp of -- standard constraint building (Lit i vl) -> do let ty = typeOfVal vl bindTermInState (Scheme [] ty) i return ([], ty) -- look for var binding in local var env (ExprTree.Var i vi s) -> case lookupVar globalEnv localEnv vi of (Just scheme) -> do term <- lift $ instantiateSchemeEx2 scheme bindTermInState (Scheme [] term) i return ([], term) (Nothing) -> error $ "Unbound var " ++ (show vi) ++ " " ++ s ++ " when building dep type constraints." (Tup i l) -> do -- new tup term l' <- mapM (buildConstrs globalEnv localEnv) l let (cl,tl) = unzip l' let term = tup tl bindTermInState (Scheme [] term) i return (concat cl, term) (Rel i l) -> case l of -- empty list: just a term var [] -> do v <- bindNewTermVarInState i return ([], v) -- non empty list: all children same type _ -> do l' <- mapM (\e -> buildConstrs globalEnv localEnv e) l let (cl,tl) = unzip l' let (headTy:tail) = tl let cl' = map (\ty -> headTy :=: ty) tail let ty = rel headTy (relNonOrd) bindTermInState (Scheme [] ty) i -- TODO: change so not just non ord return (cl' ++ (concat cl), ty) (If i pe te ee) -> do v <- bindNewTermVarInState i (c1,t1) <- buildConstrs globalEnv localEnv pe (c2,t2) <- buildConstrs globalEnv localEnv te (c3,t3) <- buildConstrs globalEnv localEnv ee return ((v :=: t2):(v :=: t3):(c1 ++ c2 ++ c3), v) (Let i it be ie) -> do (c1,t1) <- buildConstrs globalEnv localEnv be (newVarEnv, t1') <- buildForIdxTree it let newVarEnv' = varMapFromList $ schemeEnvToSchemeExEnv newVarEnv (c2, t2) <- buildConstrs globalEnv (newVarEnv' `composeVarMaps` localEnv) ie bindTermInState (Scheme [] t2) i return ((t1 :=: t1'):(c1 ++ c2), t2) -- check if application of function with pi type (App i fe ae) -> do v <- bindNewTermVarInState i (c2,t2) <- buildConstrs globalEnv localEnv ae case fe of -- if application of function var (check if has a dep type) (ExprTree.Var fi vi s) -> do -- instantiate dependent type scheme using -- func app argument expression case lookupVar globalEnv localEnv vi of (Just schemeEx) -> do t1 <- lift $ instantiateSchemeEx3 schemeEx ae bindTermInState (Scheme [] t1) fi let constr = (t1 :=: fun t2 v) return $ trace ("AppConstr: " ++ s ++ ": " ++ (show constr) ++ "\n") $ (constr:c2, v) (Nothing) -> error $ "Unbound function var " ++ (show vi) ++ " " ++ s ++ " when building dep type constraints." -- otherwise treat like any other function typed valueassignDepTypes _ -> do (c1,t1) <- buildConstrs globalEnv localEnv fe return ((t1 :=: fun t2 v):(c1 ++ c2), v) -- dive another level down (Fun i it e) -> do (newVarEnv, t1) <- buildForIdxTree it let newVarEnv' = varMapFromList $ schemeEnvToSchemeExEnv newVarEnv (cl, t2) <- buildConstrs globalEnv (newVarEnv' `composeVarMaps` localEnv) e let term = (fun t1 t2) bindTermInState (Scheme [] term) i return (cl, term) -- |Check that the constraints are all disjoint (no circular variables) checkConstraints :: [TyConstr] -> [TyConstr] checkConstraints l = l' where l' = map (\(a :=: b) -> if (not $ Data.Set.null $ (getVars a) `intersection` (getVars b)) then error $ "circle: " ++ (show (a,b)) ++ "\n" else (a :=: b) ) l
flocc-net/flocc
v0.1/Compiler/Types/Builder.hs
apache-2.0
9,318
15
30
1,963
2,735
1,466
1,269
144
12
module Regression (tests) where import Control.Exception (bracket) import Test.HUnit (Assertion) import qualified System.Event as E import qualified Test.Framework as F import qualified Test.Framework.Providers.HUnit as F startupShutdown :: Assertion startupShutdown = E.new >>= E.shutdown doubleRegister :: Assertion doubleRegister = bracket E.new E.shutdown $ \mgr -> do let cb _ _ = return () _ <- E.registerFd_ mgr cb 1 E.evtRead _ <- E.registerFd_ mgr cb 1 E.evtRead return () tests :: F.Test tests = F.testGroup "Regression" [ F.testCase "doubleRegister" doubleRegister , F.testCase "startupShutdown" startupShutdown ]
tibbe/event
tests/Regression.hs
bsd-2-clause
663
0
13
122
207
112
95
18
1
{-# LANGUAGE Haskell2010 #-} {-# LANGUAGE DataKinds, TypeFamilies, StarIsType #-} module Bug466 where class Cl a where type Fam a :: [*] data X = X instance Cl X where type Fam X = '[Char]
haskell/haddock
html-test/src/Bug466.hs
bsd-2-clause
195
0
7
41
54
32
22
8
0
{-# LANGUAGE ScopedTypeVariables #-} module Handler.Document ( getDocListR , getDocNewR , postDocNewR , getDocR , postDocR , getDocEditR , getDocDeleteR , postDocDeleteR , docAForm , docForm ) where import Data.Maybe import Data.Monoid import Data.Time import Database.Index (indexDocs) import Import import Text.Blaze (Markup) import Yesod.Auth import Utils.Auth -- DocListR getDocListR :: Handler RepHtml getDocListR = do docs <- runDB $ selectList [] [Asc DocumentTitle] canAdd <- visible DocNewR True defaultLayout $ do setTitle "What is DH? Documents" $(widgetFile "doclist") -- DocNewR getDocNewR :: Handler RepHtml getDocNewR = do let action = DocNewR mdoc = Nothing ((result, form), enctype) <- runFormPost $ docForm Nothing defaultLayout $(widgetFile "docedit") postDocNewR :: Handler RepHtml postDocNewR = do let action = DocNewR mdoc = Nothing ((result, form), enctype) <- runFormPost $ docForm Nothing case result of FormSuccess docInfo -> do userId <- requireAuthId now <- liftIO getCurrentTime let (content, hash) = getContent docInfo doc = Document (diTitle docInfo) (getSource docInfo) userId now hash content Nothing docId <- runDB $ do did <- insert doc _ <- indexDocs [Entity did doc] return did redirect $ DocR docId FormFailure msgs -> do setMessage $ listToUl msgs defaultLayout $(widgetFile "docedit") FormMissing -> defaultLayout $(widgetFile "docedit") -- DocR getDocR :: DocumentId -> Handler RepHtml getDocR docId = do currentUserId <- maybeAuthId doc <- runDB $ get404 docId uploadingUser <- runDB . get $ documentUploadedBy doc admin <- (== Authorized) <$> isAdmin defaultLayout $ do setTitle . (mappend "What is DH? ") . toHtml $ documentTitle doc $(widgetFile "doc") postDocR :: DocumentId -> Handler RepHtml postDocR docId = do mdoc <- Just <$> (runDB $ get404 docId) ((result, form), enctype) <- runFormPost $ docForm mdoc case result of FormSuccess updated -> do let (content, hash) = getContent updated runDB $ update docId [ DocumentTitle =. diTitle updated , DocumentSource =. getSource updated , DocumentHash =. hash , DocumentContent =. content ] redirect $ DocR docId _ -> do let action = DocR docId defaultLayout $(widgetFile "docedit") -- DocEditR getDocEditR :: DocumentId -> Handler RepHtml getDocEditR docId = do mdoc <- Just <$> (runDB $ get404 docId) let action = DocR docId ((result, form), enctype) <- runFormPost $ docForm mdoc defaultLayout $(widgetFile "docedit") -- DocDeleteR getDocDeleteR :: DocumentId -> Handler RepHtml getDocDeleteR docId = do doc <- runDB $ get404 docId defaultLayout $(widgetFile "docdelete") postDocDeleteR :: DocumentId -> Handler RepHtml postDocDeleteR docId = do sure :: Int <- runInputPost $ ireq intField "sure" case sure of 1 -> do runDB $ delete docId setMessage "Document deleted." redirect DocListR _ -> redirect $ DocR docId -- Forms docAForm :: (Yesod m, RenderMessage m FormMessage) => Maybe Document -> AForm s m DocumentInfo docAForm mdoc = DocumentInfo <$> areq textField "Title" (documentTitle <$> mdoc) <*> aopt textField "Source" (documentSource <$> mdoc) <*> aopt textareaField "Content" (content mdoc) <*> fileAFormOpt "Upload File" where content :: Maybe Document -> Maybe (Maybe Textarea) content = maybe Nothing (Just . Just . Textarea . documentContent) docForm :: (Yesod m, RenderMessage m FormMessage) => Maybe Document -> Markup -> MForm s m (FormResult DocumentInfo, GWidget s m ()) docForm = renderBootstrap . docAForm
erochest/whatisdh
Handler/Document.hs
bsd-2-clause
4,511
0
19
1,599
1,221
592
629
-1
-1
{-# LANGUAGE UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-} import Control.Monad.Reader import Control.Monad.State import Control.Monad.Identity import Control.Monad.Random import Control.Monad.Random.Class -- * fair coin fair :: MonadRandom m => m Bool fair = (flip (<=) 0.5) <$> getRandomR (0,1 :: Double) -- * how do i run this bar :: (MonadState Int m, MonadRandom m) => m Bool bar = fair >>= (\h -> put 404 >> return h) bar' :: (Monad m, MonadRandom (StateT Int m)) => m Bool bar' = evalStateT bar 0 -- evalRandIO = getStdRandom . runRand bar'' :: IO Bool bar'' = evalRandIO bar' fairs :: MonadRandom m => Int -> m [Bool] fairs n = (take n) <$> (flip (<=) 0.5) `ffmap` getRandomRs (0,1 :: Double) where ffmap = fmap . fmap --instance MonadState s m => MonadState s (RVarT m) where -- get = lift get -- put = lift . put -- state = lift . state --foo :: (MonadState s m, MonadRandom m) => s -> RVarT m () --foo s = do -- x <- (uniformT 0 1 :: RVarT m Double) -- if x < 0.5 then put s else return () --foo' :: (MonadState String m, MonadRandom m) => RVarT m () --foo' = foo "hello" --foo'' :: (MonadState String m, MonadRandom m) => m () --foo'' = undefined ----foo''= runRVarT foo' StdRandom -- * desired behavior with state and ranndomness baz :: (MonadState s m, MonadReader t m) => m () baz = get >> ask >> return () baz1 :: MonadReader t m => m ((),Int) baz1 = runStateT baz 0 baz1' :: Identity ((),Int) baz1' = runReaderT baz1 (1,"hello") baz2 :: MonadState s m => m () baz2 = runReaderT baz "hello" baz2' :: Identity ((),[Int]) baz2' = runStateT baz2 [1..10] cat :: (MonadState String m, MonadReader String m) => m String cat = do x <- get y <- ask return $ x ++ y cat1 :: Identity String cat1 = evalStateT (runReaderT cat "world") "hello" cat2 :: Identity String cat2 = runReaderT (evalStateT cat "hello") "world" bar :: (MonadTrans t1, MonadState t m, MonadState s (t1 m)) => s -> RVarT (t1 m) () bar s = do x <- (uniformT 0 1 :: RVarT m Double) a <- lift . lift $ get if x < 0.5 then put s else return ()
lingxiao/CIS700
depricated/Tbd.hs
bsd-3-clause
2,121
0
9
473
692
370
322
41
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} module River.Fresh ( MonadFresh(..) , Fresh , runFresh , runFreshFrom , FreshT , runFreshT , runFreshFromT , FreshName(..) ) where import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (ContT) import Control.Monad.Trans.Except (ExceptT) import Control.Monad.Trans.Identity (IdentityT) import Control.Monad.Trans.List (ListT) import Control.Monad.Trans.Maybe (MaybeT) import qualified Control.Monad.Trans.RWS.Lazy as Lazy (RWST) import qualified Control.Monad.Trans.RWS.Strict as Strict (RWST) import Control.Monad.Trans.Reader (ReaderT) import qualified Control.Monad.Trans.State.Lazy as Lazy (StateT) import Control.Monad.Trans.State.Strict (evalStateT, get, put) import qualified Control.Monad.Trans.State.Strict as Strict (StateT) import qualified Control.Monad.Trans.Writer.Lazy as Lazy import qualified Control.Monad.Trans.Writer.Strict as Strict import Data.Functor.Identity (Identity, runIdentity) import River.Name ------------------------------------------------------------------------ type Fresh = FreshT Identity newtype FreshT m a = FreshT { unFreshT :: Strict.StateT FreshContext m a } deriving (Functor, Applicative, Monad) newtype FreshContext = FreshContext { _freshSupply :: [Int] } ------------------------------------------------------------------------ runFresh :: Fresh a -> a runFresh = runIdentity . runFreshT runFreshFrom :: Int -> Fresh a -> a runFreshFrom n = runIdentity . runFreshFromT n runFreshT :: Monad m => FreshT m a -> m a runFreshT = runFreshFromT 1 runFreshFromT :: Monad m => Int -> FreshT m a -> m a runFreshFromT n = flip evalStateT (FreshContext [n..]) . unFreshT ------------------------------------------------------------------------ class FreshName n where nextName :: n -> Int freshen :: MonadFresh m => n -> m n newFresh :: MonadFresh m => m n instance FreshName (Name n) where nextName = \case Name _ -> 1 NameMod _ n -> n + 1 NameNew n -> n + 1 freshen = \case Name n -> NameMod n <$> nextFresh NameMod n _ -> NameMod n <$> nextFresh NameNew _ -> newFresh newFresh = NameNew <$> nextFresh ------------------------------------------------------------------------ class Monad m => MonadFresh m where nextFresh :: m Int instance Monad m => MonadFresh (FreshT m) where nextFresh = FreshT $ do FreshContext (x : xs) <- get put $ FreshContext xs pure x instance MonadFresh m => MonadFresh (ContT r m) where nextFresh = lift nextFresh instance MonadFresh m => MonadFresh (ExceptT e m) where nextFresh = lift nextFresh instance MonadFresh m => MonadFresh (IdentityT m) where nextFresh = lift nextFresh instance MonadFresh m => MonadFresh (ListT m) where nextFresh = lift nextFresh instance MonadFresh m => MonadFresh (MaybeT m) where nextFresh = lift nextFresh instance MonadFresh m => MonadFresh (ReaderT r m) where nextFresh = lift nextFresh instance (MonadFresh m, Monoid w) => MonadFresh (Lazy.WriterT w m) where nextFresh = lift nextFresh instance (MonadFresh m, Monoid w) => MonadFresh (Strict.WriterT w m) where nextFresh = lift nextFresh instance MonadFresh m => MonadFresh (Lazy.StateT s m) where nextFresh = lift nextFresh instance MonadFresh m => MonadFresh (Strict.StateT s m) where nextFresh = lift nextFresh instance (MonadFresh m, Monoid w) => MonadFresh (Lazy.RWST r w s m) where nextFresh = lift nextFresh instance (MonadFresh m, Monoid w) => MonadFresh (Strict.RWST r w s m) where nextFresh = lift nextFresh
jystic/river
src/River/Fresh.hs
bsd-3-clause
3,821
0
12
834
1,130
614
516
113
1
module Pipes.Combinators where import Control.Monad import Pipes import Pipes.Internal import Pipes.Prelude as P ----------------------------------------------------------------------------- interleaveRequests :: Monad m => Proxy () a () b m r -> Proxy () a () b m r -> Proxy () a () b m r interleaveRequests p1 p2 = goL p1 p2 Nothing where goL p1' p2' mv = case p1' of Request a' fa -> mv & maybe (Request a' (\a -> goL (fa a) p2' (Just a))) (goR p1' p2' . Just) Respond b fb' -> Respond b (\b' -> goL (fb' b') p2' mv) M m -> M (m >>= \p -> return (goL p p2' mv)) Pure _ -> p1' goR p1' p2' mv = case p2' of Request _ fa -> mv & maybe (goL p1' p2' Nothing) (\v -> goR p1' (fa v) Nothing) Respond b fb' -> Respond b (\b' -> goR p1' (fb' b') mv) M m -> M (m >>= \p -> return (goR p1' p mv)) Pure _ -> p2' interleaveRequestsL :: Monad m => [Proxy () a () b m r] -> Proxy () a () b m r interleaveRequestsL = foldr interleaveRequests drain ----------------------------------------------------------------------------- interleaveResponses :: Monad m => Proxy () a () b m r -> Proxy () a () b m r -> Proxy () a () b m r interleaveResponses p1 p2 = goL p1 p2 Nothing where goL p1' p2' mv = case p1' of Request a' fa -> mv & maybe (Request a' (\a -> goL (fa a) p2' (Just a))) (goR p1' p2' . Just) Respond b fb' -> Respond b (\b' -> goR (fb' b') p2' mv) M m -> M (m >>= \p -> return (goL p p2' mv)) Pure _ -> p1' goR p1' p2' mv = case p2' of Request _ fa -> mv & maybe (goL p1' p2' Nothing) (\v -> goR p1' (fa v) Nothing) Respond b fb' -> Respond b (\b' -> goL p1' (fb' b') mv) M m -> M (m >>= \p -> return (goL p1' p mv)) Pure _ -> p2' interleaveResponsesL :: Monad m => [Proxy () a () b m r] -> Proxy () a () b m r interleaveResponsesL = foldr interleaveResponses drain ----------------------------------------------------------------------------- loop :: Monad m => Proxy () a () (Either a b) m r -> Proxy () a () b m r loop p = go p [] where go p' as = case p' of Request () fa -> case as of [] -> Request () (\a -> go (fa a) []) (a':as') -> go (fa a') as' Respond b fb -> case b of Left a' -> go (fb ()) (as ++ [a']) Right b' -> Respond b' (\() -> go (fb ()) as) M m -> M (m >>= \p'' -> return (go p'' as)) Pure r -> Pure r ----------------------------------------------------------------------------- (&) :: a -> (a -> b) -> b (&) = flip ($) ----------------------------------------------------------------------------- test :: IO () test = runEffect $ each [1..3::Int] >-> interleaveResponsesL [ P.map (+1) , cat , P.map (+3) , drain , replicateM_ 2 (await >>= yield) , forever (await >>= replicateM_ 2 . yield) ] >-> loop (P.map $ \x -> if odd x then Left (x+1) else Right (x+2)) >-> interleaveRequestsL [ P.print , P.scan (+) 0 id >-> P.print ]
cmahon/pipes-combinators
src/Pipes/Combinators.hs
bsd-3-clause
3,240
0
19
1,050
1,486
742
744
68
7
module ETA.CodeGen.Utils where import ETA.Main.DynFlags -- import ETA.Types.Type import ETA.BasicTypes.Name import ETA.Types.TyCon import ETA.BasicTypes.Literal import Codec.JVM import Data.Char (ord) import Control.Arrow(first) import ETA.CodeGen.Name import ETA.CodeGen.Rts import ETA.Debug -- import Data.Text (Text) import Data.Text.Encoding (decodeUtf8) import Data.Monoid ((<>)) cgLit :: Literal -> (FieldType, Code) cgLit (MachChar c) = (jint, iconst jint . fromIntegral $ ord c) cgLit (MachInt i) = (jint, iconst jint $ fromIntegral i) cgLit (MachWord i) = (jint, iconst jint $ fromIntegral i) cgLit (MachInt64 i) = (jlong, lconst $ fromIntegral i) -- TODO: Verify that fromIntegral converts well cgLit (MachWord64 i) = (jlong, lconst $ fromIntegral i) cgLit (MachFloat r) = (jfloat, fconst $ fromRational r) cgLit (MachDouble r) = (jdouble, dconst $ fromRational r) -- TODO: Remove this literal variant? cgLit MachNullAddr = (jobject, nullAddr) cgLit (MachStr s) = (jstring, sconst $ decodeUtf8 s) -- TODO: Implement MachLabel cgLit MachLabel {} = error "cgLit: MachLabel" cgLit other = pprPanic "mkSimpleLit" (ppr other) litToInt :: Literal -> Int litToInt (MachInt i) = fromInteger i litToInt (MachWord i) = fromInteger i litToInt (MachChar c) = ord c litToInt _ = error "litToInt: not integer" intSwitch :: Code -> [(Int, Code)] -> Maybe Code -> Code intSwitch = gswitch litSwitch :: FieldType -> Code -> [(Literal, Code)] -> Code -> Code litSwitch ft expr branches deflt -- | isObjectFt ft = deflt -- ASSERT (length branches == 0) -- TODO: When switching on an object, perform a checkcast -- TODO: When switching on long/float/double, use an if-else tree | null branches = deflt | ft `notElem` [jint, jbool, jbyte, jshort, jchar] = error $ "litSwitch[" ++ show ft ++ "]: " ++ "primitive cases not supported for non-integer values" | otherwise = intSwitch expr intBranches (Just deflt) where intBranches = map (first litToInt) branches tagToClosure :: DynFlags -> TyCon -> Code -> (FieldType, Code) tagToClosure dflags tyCon loadArg = (elemFt, enumCode) where enumCode = invokestatic (mkMethodRef modClass fieldName [] (Just arrayFt)) <> loadArg <> gaload elemFt tyName = tyConName tyCon modClass = moduleJavaClass $ nameModule tyName fieldName = nameTypeTable dflags $ tyConName tyCon tyConCl = tyConClass dflags tyCon elemFt = obj tyConCl arrayFt = jarray elemFt
AlexeyRaga/eta
compiler/ETA/CodeGen/Utils.hs
bsd-3-clause
2,614
0
13
594
786
419
367
50
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad.Except (runExceptT) import Data.Monoid ((<>)) import Options.Applicative (Parser, execParser, strOption, long, value, info, helper, fullDesc) import System.Exit (exitWith, ExitCode(..)) import Network.Wai.Handler.Warp (run) import Config import WebApp main :: IO () main = do cfg <- execParser opts >>= runExceptT . loadConfig case cfg of Left err -> print err >> exitWith (ExitFailure 1) Right cfg_ -> do print cfg_ ctx <- newContext cfg_ case ctx of Left err -> print err >> exitWith (ExitFailure 1) Right ctx_ -> run (port cfg_) (webapp ctx_) where opts = info (helper <*> cliOptions) fullDesc cliOptions :: Parser FilePath cliOptions = strOption (long "config" <> value "config.yml")
savannidgerinel/health
app/Main.hs
bsd-3-clause
974
0
18
292
291
153
138
24
3
module GameMap where import Data.Map.Strict type Point = (Int, Int) type Size = Point data Cell = Floor | Wall | Space deriving (Show, Eq) data GameMap a = GameMap { mapData :: Map Point a , mapSize :: Point } type GameCellMap = GameMap Cell class ShowANSI a where showANSI :: a -> Char instance ShowANSI Cell where showANSI Floor = '.' showANSI Wall = '#' showANSI Space = ' '
lexical-works/LittleRogue
src/GameMap.hs
bsd-3-clause
426
0
9
120
138
79
59
15
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Main where import Control.Exception import Data.Bugs import Data.Char import Data.Text (Text, pack) import Prelude hiding (log) import Test.Hspec tryAny :: IO a -> IO (Either SomeException a) tryAny = try main :: IO () main = hspec $ do describe "" $ do it "" $ True `shouldBe` True
jwiegley/bugs
test/main.hs
bsd-3-clause
370
0
13
74
121
67
54
15
1
{-# LANGUAGE TemplateHaskell #-} module Client.ParticleTGlobals where import Control.Lens (makeLenses) import qualified Data.Vector.Storable.Mutable as MSV import qualified Data.Vector.Unboxed as UV import System.IO.Unsafe (unsafePerformIO) import qualified Constants import Types makeLenses ''ParticleTGlobals initialParticleTGlobals :: ParticleTGlobals initialParticleTGlobals = ParticleTGlobals { _pColorTable = UV.replicate 256 0 , _pVertexArray = unsafePerformIO (MSV.new (Constants.maxParticles * 3)) , _pColorArray = unsafePerformIO (MSV.new Constants.maxParticles) }
ksaveljev/hake-2
src/Client/ParticleTGlobals.hs
bsd-3-clause
664
0
12
146
132
79
53
14
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.EXT.FogCoord -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/EXT/fog_coord.txt EXT_fog_coord> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.EXT.FogCoord ( -- * Enums gl_CURRENT_FOG_COORDINATE_EXT, gl_FOG_COORDINATE_ARRAY_EXT, gl_FOG_COORDINATE_ARRAY_POINTER_EXT, gl_FOG_COORDINATE_ARRAY_STRIDE_EXT, gl_FOG_COORDINATE_ARRAY_TYPE_EXT, gl_FOG_COORDINATE_EXT, gl_FOG_COORDINATE_SOURCE_EXT, gl_FRAGMENT_DEPTH_EXT, -- * Functions glFogCoordPointerEXT, glFogCoorddEXT, glFogCoorddvEXT, glFogCoordfEXT, glFogCoordfvEXT ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/EXT/FogCoord.hs
bsd-3-clause
1,030
0
4
121
82
62
20
16
0
module Graphics.X11.Turtle.Input(TurtleInput(..), turtleSeries) where import Graphics.X11.Turtle.State(TurtleState(..), initTurtleState, makeShape) import Text.XML.YJSVG(SVG(..), Color(..), Position(..), Font(..), FontWeight(..)) import Control.Concurrent.Chan (Chan) -------------------------------------------------------------------------------- data TurtleInput = Goto Position | Forward Double | RotateRad Double | Rotate Double | TurnLeft Double | Dot Double | Stamp | Write String Double String | PutImage FilePath Double Double | Undo | Undonum Int | SilentUndo Int | Clear | Sleep Int | Flush | Shape [(Double, Double)] | Shapesize Double Double | Pensize Double | Pencolor Color | Bgcolor Color | SetPendown Bool | SetVisible Bool | SetFill Bool | SetPoly Bool | SetFlush Bool | PositionStep (Maybe Double) | DirectionStep (Maybe Double) | Degrees Double | FinishSign (Chan ()) turtleSeries :: [TurtleInput] -> [TurtleState] turtleSeries tis = let ts0 = initTurtleState in ts0 : ts0 : turtles [] ts0 tis turtles :: [TurtleState] -> TurtleState -> [TurtleInput] -> [TurtleState] turtles [] ts0 (Undo : tis) = ts0 : turtles [] ts0 tis turtles (tsb : tsbs) _ (Undo : tis) = let ts1 = tsb{undo = True} in ts1 : turtles tsbs ts1 tis turtles tsbs _ (SilentUndo n : tis) = let ts1_ : tsbs' = drop (n - 1) tsbs ts1 = ts1_{ silentundo = Just n } in ts1 : turtles tsbs' ts1 tis turtles tsbs ts0 (Forward len : tis) = case position ts0 of Center x0 y0 -> let x = x0 + len * cos (direction ts0) y = y0 + len * sin (direction ts0) in turtles tsbs ts0 $ Goto (Center x y) : tis TopLeft x0 y0 -> let x = x0 + len * cos (direction ts0) y = y0 - len * sin (direction ts0) in turtles tsbs ts0 $ Goto (TopLeft x y) : tis turtles tsbs ts0 (Rotate dir : tis) = turtles tsbs ts0 $ RotateRad (dir * 2 * pi / degrees ts0) : tis turtles tsbs ts0 (TurnLeft dd : tis) = turtles tsbs ts0 $ RotateRad (direction ts0 + dd * 2 * pi / degrees ts0) : tis turtles tsbs ts0 (ti : tis) = let ts1 = nextTurtle ts0 ti in ts1 : turtles (ts0 : tsbs) ts1 tis turtles _ _ [] = error "no more input" reset :: TurtleState -> TurtleState reset t = t{draw = Nothing, clear = False, undo = False, silentundo = Nothing, undonum = 1, sleep = Nothing, flush = False, finishSign = Nothing} set :: TurtleState -> Maybe SVG -> TurtleState set t drw = t{draw = drw, drawed = maybe id (:) drw $ drawed t} nextTurtle :: TurtleState -> TurtleInput -> TurtleState nextTurtle t (Goto pos) = (reset t){position = pos, fillPoints = (if fill t then (pos :) else id) $ fillPoints t, polyPoints = (if poly t then (pos :) else id) $ polyPoints t} `set` if not $ pendown t then Nothing else Just $ Line pos (position t) (pencolor t) (pensize t) nextTurtle t (RotateRad dir) = (reset t){direction = dir} nextTurtle t@TurtleState{pencolor = clr} (Dot sz) = reset t `set` Just (Rect (position t) sz sz 0 clr clr) nextTurtle t@TurtleState{pencolor = clr} Stamp = reset t `set` Just (Polyline (makeShape t (direction t) (position t)) clr clr 0) nextTurtle t@TurtleState{pencolor = clr} (Write fnt sz str) = reset t `set` Just (Text (position t) sz clr (Font fnt Normal) str) nextTurtle t (PutImage fp w h) = reset t `set` Just (Image (position t) w h fp) nextTurtle t (Undonum un) = (reset t){undonum = un} nextTurtle t Clear = (reset t){clear = True, drawed = [last $ drawed t]} nextTurtle t (Sleep time) = (reset t){sleep = Just time} nextTurtle t Flush = (reset t){flush = True} nextTurtle t (Shape sh) = (reset t){shape = sh} nextTurtle t (Shapesize sx sy) = (reset t){shapesize = (sx, sy)} nextTurtle t (Pensize ps) = (reset t){pensize = ps} nextTurtle t (Pencolor clr) = (reset t){pencolor = clr} nextTurtle t (Bgcolor clr) = (reset t){ draw = Just $ Fill clr, drawed = init (drawed t) ++ [Fill clr]} nextTurtle t (SetPendown pd) = (reset t){pendown = pd} nextTurtle t (SetVisible v) = (reset t){visible = v} nextTurtle t (SetFill fl) = (reset t){fill = fl, fillPoints = [position t | fl]} `set` (if not (fill t) || fl then Nothing else Just $ Polyline (fillPoints t) (pencolor t) (pencolor t) 0) nextTurtle t (SetPoly p) = (reset t){ poly = p, polyPoints = if p then [position t] else polyPoints t} nextTurtle t (SetFlush ss) = (reset t){stepbystep = ss} nextTurtle t (PositionStep ps) = (reset t){positionStep = ps} nextTurtle t (DirectionStep ds) = (reset t){directionStep = ds} nextTurtle t (Degrees ds) = (reset t){degrees = ds} nextTurtle t (FinishSign c) = (reset t){finishSign = Just c} nextTurtle _ _ = error "not defined"
YoshikuniJujo/xturtle_haskell
src/Graphics/X11/Turtle/Input.hs
bsd-3-clause
4,548
38
15
871
2,212
1,179
1,033
101
6
-- | -- Module : Network.TLS.Imports -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- {-# LANGUAGE NoImplicitPrelude #-} module Network.TLS.Imports ( -- generic exports Control.Applicative.Applicative(..) , (Control.Applicative.<$>) , Data.Monoid.Monoid(..) -- project definition , Bytes , showBytesHex ) where import qualified Control.Applicative import qualified Data.Monoid import qualified Data.ByteString as B import Data.ByteArray.Encoding as B import qualified Prelude type Bytes = B.ByteString showBytesHex :: Bytes -> Prelude.String showBytesHex bs = Prelude.show (B.convertToBase B.Base16 bs :: Bytes)
tolysz/hs-tls
core/Network/TLS/Imports.hs
bsd-3-clause
758
0
8
149
132
88
44
16
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE OverloadedStrings #-} module Duckling.Volume.GA.Corpus ( corpus ) where import Data.String import Prelude import Duckling.Lang import Duckling.Resolve import Duckling.Volume.Types import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {lang = GA}, allExamples) allExamples :: [Example] allExamples = concat [ examples (VolumeValue Millilitre 250) [ "250 millilítir" , "250 millilitir" , "250ml" , "250 ml" ] , examples (VolumeValue Litre 2) [ "2 lítir" ] , examples (VolumeValue Gallon 5) [ "5 galúin" ] ]
rfranek/duckling
Duckling/Volume/GA/Corpus.hs
bsd-3-clause
971
0
9
261
156
95
61
22
1
{-# LANGUAGE GeneralizedNewtypeDeriving, PatternGuards #-} module PTS.Dynamics.Evaluation where import Control.Applicative hiding (Const) import Control.Monad.Environment import Control.Monad.State import Data.Maybe (fromMaybe) import qualified Data.Set as Set import qualified Data.Map as Map import PTS.Dynamics.Binding import PTS.Dynamics.Value import PTS.Syntax import PTS.Syntax.Names newtype Eval a = Eval (EnvironmentT Name (Binding Eval) (State NamesMap) a) deriving (Functor, Applicative, Monad, MonadState NamesMap, MonadEnvironment Name (Binding Eval)) runEval :: Bindings Eval -> Eval a -> a runEval env (Eval p) = evalState (runEnvironmentT p env) (envToNamesMap env) close :: Name -> Value Eval -> Maybe C -> Value Eval -> Eval (Function Eval) close name typ sort value = do term <- reify value abstract (\arg -> do withEnvironment [] $ do bind name (Binding False arg typ sort) $ do eval term) equivTerm :: Bindings Eval -> TypedTerm Eval -> TypedTerm Eval -> Bool equivTerm env t1 t2 = runEval env $ do v1 <- eval t1 v2 <- eval t2 equiv v1 v2 equiv :: Value Eval -> Value Eval -> Eval Bool equiv (Function n v1 f) (Function _ v1' f') = do r1 <- equiv v1 v1' n' <- fresh n v2 <- open f (ResidualVar n') v2' <- open f' (ResidualVar n') r2 <- equiv v2 v2' return (r1 && r2) equiv (Number n) (Number n') = do return (n == n') equiv (Constant c) (Constant c') = do return (c == c') equiv (PiType n v1 f s1) (PiType _ v1' f' s2) = do r1 <- equiv v1 v1' n' <- fresh n v2 <- open f (ResidualVar n') v2' <- open f' (ResidualVar n') r2 <- equiv v2 v2' return (r1 && r2 && s1 == s2) equiv (ResidualIntOp op v1 v2) (ResidualIntOp op' v1' v2') = do let r1 = op == op' r2 <- equiv v1 v1' r3 <- equiv v2 v2' return (r1 && r2 && r3) equiv (ResidualIfZero v1 v2 v3) (ResidualIfZero v1' v2' v3') = do r1 <- equiv v1 v1' r2 <- equiv v2 v2' r3 <- equiv v3 v3' return (r1 && r2 && r3) equiv (ResidualVar n) (ResidualVar n') = do return (n == n') equiv (ResidualApp v1 v2) (ResidualApp v1' v2') = do r1 <- equiv v1 v1' r2 <- equiv v2 v2' return (r1 && r2) equiv _ _ = do return False nbe :: Structure t => Bindings Eval -> t -> Term nbe env e = runEval env $ do v <- eval e e' <- reify v return e' fresh :: Name -> Eval Name fresh n = do ns <- get let (n', ns') = freshvarlMap ns n put ns' return n' reify :: Value Eval -> Eval Term reify (Function n v1 f) = do e1 <- reify v1 n' <- fresh n v2 <- open f (ResidualVar n') e2 <- reify v2 return (mkLam n' e1 e2) reify (Number n) = do return (mkInt n) reify (Constant c) = do return (mkConst c) reify (PiType n v1 f s) = do e1 <- reify v1 n' <- fresh n v2 <- open f (ResidualVar n') e2 <- reify v2 return (mkSortedPi n' e1 e2 (Just s)) reify (ResidualIntOp op v1 v2) = do e1 <- reify v1 e2 <- reify v2 return (mkIntOp op e1 e2) reify (ResidualIfZero v1 v2 v3) = do e1 <- reify v1 e2 <- reify v2 e3 <- reify v3 return (mkIfZero e1 e2 e3) reify (ResidualVar n) = do return (mkVar n) reify (ResidualApp v1 v2) = do e1 <- reify v1 e2 <- reify v2 return (mkApp e1 e2) evalTerm :: Bindings Eval -> TypedTerm Eval -> Value Eval evalTerm env t = runEval env $ do eval t apply :: Monad m => Value m -> Value m -> m (Value m) apply (Function n t f) v2 = open f v2 apply v1 v2 = return (ResidualApp v1 v2) eval :: Structure t => t -> Eval (Value Eval) eval t = case structure t of Int n -> do return (Number n) IntOp op e1 e2 -> do v1 <- eval e1 v2 <- eval e2 case (v1, v2) of (Number n1, Number n2) | Just n3 <- evalOp op n1 n2 -> do return (Number n3) _ -> return (ResidualIntOp op v1 v2) IfZero e1 e2 e3 -> do v1 <- eval e1 case v1 of Number 0 -> do eval e2 Number _ -> do eval e3 _ -> do v2 <- eval e2 v3 <- eval e3 return (ResidualIfZero v1 v2 v3) Var n -> do binding <- lookupValue n case binding of Just v -> return v Nothing -> return (ResidualVar n) Const c -> do return (Constant c) App e1 e2 -> do v1 <- eval e1 v2 <- eval e2 apply v1 v2 Lam n e1 e2 -> do v1 <- eval e1 env <- getEnvironment f <- abstract (\v -> do withEnvironment env $ do bind n (Binding False v v1 Nothing) $ do eval e2) return (Function n v1 f) Pi n e1 e2 (Just s) -> do v1 <- eval e1 env <- getEnvironment f <- abstract (\v -> do withEnvironment env $ do bind n (Binding False v v1 Nothing) $ do eval e2) return (PiType n v1 f s) Pos _ e -> do eval e Infer _ -> error "Encountered type inference marker during evaluation. You either have an underscore in your code that cannnot be decided or you have discovered a bug in the interpreter." Unquote _ -> error "During evaluation, there should be no unquote left."
Toxaris/pts
src-lib/PTS/Dynamics/Evaluation.hs
bsd-3-clause
4,956
0
22
1,357
2,342
1,077
1,265
167
15
module CodeGen (showDIMACS, showCNF) where import DataStructures import Data.List (foldl') showDIMACS :: CNF -> Int -> String showDIMACS cnf nVars = "p cnf " ++ show nVars ++ " " ++ show (length cnf) ++ "\n" ++ showCNF cnf showCNF :: CNF -> String showCNF = foldl' (\acc andClause -> showOrClause andClause ++ acc) "" -- bizarre head/tail splitting because want no leading space showOrClause :: [Int] -> String showOrClause andClause = foldl' (\acc or1 -> acc ++ " " ++ show or1) (show $ head andClause) (tail andClause) ++ " 0\n"
anniecherk/pyschocnf
src/CodeGen.hs
bsd-3-clause
539
0
10
100
188
99
89
11
1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Prompt.Input -- Copyright : (c) 2007 Brent Yorgey -- License : BSD-style (see LICENSE) -- -- Maintainer : <byorgey@gmail.com> -- Stability : stable -- Portability : unportable -- -- A generic framework for prompting the user for input and passing it -- along to some other action. -- ----------------------------------------------------------------------------- module XMonad.Prompt.Input ( -- * Usage -- $usage inputPrompt, inputPromptWithCompl, (?+) ) where import XMonad.Core import XMonad.Prompt -- $usage -- -- To use this module, import it along with "XMonad.Prompt": -- -- > import XMonad.Prompt -- > import XMonad.Prompt.Input -- -- This module provides no useful functionality in isolation, but -- is intended for use in building other actions which require user -- input. -- -- For example, suppose Mr. Big wants a way to easily fire his -- employees. We'll assume that he already has a function -- -- > fireEmployee :: String -> X () -- -- which takes as input the name of an employee, and fires them. He -- just wants a convenient way to provide the input for this function -- from within xmonad. Here is where the "XMonad.Prompt.Input" module -- comes into play. He can use the 'inputPrompt' function to create a -- prompt, and the '?+' operator to compose the prompt with the -- @fireEmployee@ action, like so: -- -- > firingPrompt :: X () -- > firingPrompt = inputPrompt defaultXPConfig \"Fire\" ?+ fireEmployee -- -- If @employees@ contains a list of all his employees, he could also -- create an autocompleting version, like this: -- -- > firingPrompt' = inputPromptWithCompl defaultXPConfig \"Fire\" -- > (mkComplFunFromList employees) ?+ fireEmployee -- -- Now all he has to do is add a keybinding to @firingPrompt@ (or -- @firingPrompt'@), such as -- -- > , ((modm .|. controlMask, xK_f), firingPrompt) -- -- Now when Mr. Big hits mod-ctrl-f, a prompt will pop up saying -- \"Fire: \", waiting for him to type the name of someone to fire. -- If he thinks better of it after hitting mod-ctrl-f and cancels the -- prompt (e.g. by hitting Esc), the @fireEmployee@ action will not be -- invoked. -- -- (For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings".) -- -- "XMonad.Prompt.Input" is also intended to ease the process of -- developing other modules which require user input. For an example -- of a module developed using this functionality, see -- "XMonad.Prompt.Email", which prompts the user for a recipient, -- subject, and one-line body, and sends a quick email. data InputPrompt = InputPrompt String instance XPrompt InputPrompt where showXPrompt (InputPrompt s) = s ++ ": " -- | Given a prompt configuration and some prompt text, create an X -- action which pops up a prompt waiting for user input, and returns -- whatever they type. Note that the type of the action is @X -- (Maybe String)@, which reflects the fact that the user might -- cancel the prompt (resulting in @Nothing@), or enter an input -- string @s@ (resulting in @Just s@). inputPrompt :: XPConfig -> String -> X (Maybe String) inputPrompt c p = inputPromptWithCompl c p (const (return [])) -- | The same as 'inputPrompt', but with a completion function. The -- type @ComplFunction@ is @String -> IO [String]@, as defined in -- "XMonad.Prompt". The 'mkComplFunFromList' utility function, also -- defined in "XMonad.Prompt", is useful for creating such a -- function from a known list of possibilities. inputPromptWithCompl :: XPConfig -> String -> ComplFunction -> X (Maybe String) inputPromptWithCompl c p compl = mkXPromptWithReturn (InputPrompt p) c compl return infixr 1 ?+ -- | A combinator for hooking up an input prompt action to a function -- which can take the result of the input prompt and produce another -- action. If the user cancels the input prompt, the -- second function will not be run. -- -- The astute student of types will note that this is actually a -- very general combinator and has nothing in particular to do -- with input prompts. If you find a more general use for it and -- want to move it to a different module, be my guest. (?+) :: (Monad m) => m (Maybe a) -> (a -> m ()) -> m () x ?+ k = x >>= maybe (return ()) k
MasseR/xmonadcontrib
XMonad/Prompt/Input.hs
bsd-3-clause
4,560
0
11
977
341
219
122
16
1
module JDec.Class.Raw.Field ( Field(Field), fieldAccessFlags, fieldNameIndex, fieldDescriptorIndex, fieldAttributes ) where import JDec.Class.Raw.FieldModifier(FieldModifier) import JDec.Class.Raw.Attribute(Attribute) import JDec.Class.Raw.ConstantPoolIndex (ConstantPoolIndex) import Data.Set -- | Field decription. No two fields in one class file may have the same name and descriptor. data Field = Field { fieldAccessFlags :: Set FieldModifier, -- ^ The value is a set of flags used to denote access permission to and properties of the field. fieldNameIndex :: ConstantPoolIndex, -- ^ The value must be a valid index into the constant pool table. The constant pool entry at that index must be a UTF8ConstantPoolEntry which must represent a valid unqualified name denoting a field. fieldDescriptorIndex :: ConstantPoolIndex, -- ^ The value must be a valid index into the constant pool table. The constant pool entry at that index must be a UTF8ConstantPoolEntry that must represent a valid field descriptor. fieldAttributes :: [Attribute] -- ^ Attributes of this field. ConstantValueAttribute, SyntheticAttribute, SignatureAttribute, DeprecatedAttribute, RuntimeVisibleAnnotationsAttribute, RuntimeInvisibleAnnotationsAttribute attributes may appear here. } deriving Show
rel-eng/jdec
src/JDec/Class/Raw/Field.hs
bsd-3-clause
1,285
0
9
172
117
78
39
18
0
-- | -- This helper module exports elements from the basic libraries: -- XPathEval, XPathToString and XPathParser -- -- Author : Torben Kuseler module Yuuko.Text.XML.HXT.XPath ( module Yuuko.Text.XML.HXT.XPath.XPathEval , module Yuuko.Text.XML.HXT.XPath.XPathToString , module Yuuko.Text.XML.HXT.XPath.XPathParser ) where import Yuuko.Text.XML.HXT.XPath.XPathEval import Yuuko.Text.XML.HXT.XPath.XPathToString import Yuuko.Text.XML.HXT.XPath.XPathParser
nfjinjing/yuuko
src/Yuuko/Text/XML/HXT/XPath.hs
bsd-3-clause
491
0
5
79
73
58
15
7
0
{-# LANGUAGE QuasiQuotes #-} module ConventionTest ( module Convention , conventionCorrect ) where import Convention import Commandline import Data.ByteString.Builder import Data.List (intersperse, mapAccumL) import qualified Data.ByteString.Lazy.Char8 as L import Str import Test.QuickCheck import Test.QuickCheck.Monadic -- |Proposition that calling convention correctly passes arguments conventionCorrect :: Options -> ([L.ByteString] -> IO Bool) -> [Signature] -> Property conventionCorrect opts runScript sigs = monadicIO $ do result <- run $ runScript [tst, drv] assert result where tst = toLazyByteString $ testProgram (optPointer64 opts) sigs drv = toLazyByteString $ driverProgram (optPointer64 opts) sigs -- |Build program-part containing all test functions testProgram :: Bool -> [Signature] -> Builder testProgram p64 sigs = testPrefix <> newlineSeparated functions where functions = mapi (testFunction p64) sigs testPrefix :: Builder testPrefix = string8 [str| #include <string.h> #ifdef DEBUG # include <stdio.h> #endif #define BSIZE 65536 static unsigned char data_r [BSIZE]; extern unsigned char data_s [BSIZE]; #define BYTE_IN(x,n) (((unsigned long long)(x) >> ((n) << 3)) & 0xff) #define BYTE_FN(x,n) (((unsigned char *)(&(x))) [sizeof(x) - 1 - (n)]) |] -- |Generate the code for a test function 'n' with a given signature testFunction :: Bool -> Int -> Signature -> Builder testFunction p64 n s = signature n s <> string8 "\n{\n int n = 0;\n\n" <> argbytes s <> testFunctionSuffix where argbytes (Signature args) = newlineSeparated $ mapi (extractBytes p64) args testFunctionSuffix :: Builder testFunctionSuffix = string8 [str| # ifdef DEBUG if (memcmp(data_s, data_r, n) != 0) { int i; for (i=0; i<n; i++) { printf("%3d: %02x %02x%s\n", i, data_s[i], data_r[i], data_s[i]!=data_r[i] ? " <---" : ""); } } # endif return (memcmp(data_s, data_r, n) != 0); } |] -- |Generate C signature for test function 'n' signature :: Int -> Signature -> Builder signature n (Signature args) = string8 "int test" <> intDec n <> char8 '(' <> commaSeparated (mapi argument args) <> char8 ')' where argument i t = printArgumentType t <> string8 " a" <> intDec i -- |Generate statements that copy all bytes of argument 'n' with type 't' into the comparison buffer extractBytes :: Bool -> Int -> ArgumentType -> Builder extractBytes p64 n t = let go byte | byte >= 0 = (string8 " data_r[n++] = " <> string8 (if t==F32 || t==F64 then "BYTE_FN(a" else "BYTE_IN(a") <> intDec n <> string8 ", " <> intDec byte) <> string8 ");" : go (byte - 1) | otherwise = [] in newlineSeparated $ go $ argumentByteSize p64 t - 1 -- |Build program-part containing the driver function with calls to all test functions driverProgram :: Bool -> [Signature] -> Builder driverProgram p64 sigs = driverPrefix <> prototypes <> mainPrefix <> functions <> mainSuffix where prototypes = newlineSeparated $ mapi (\i s -> signature i s <> char8 ';') sigs functions = newlineSeparated $ mapi (callTestFunction p64) sigs driverPrefix :: Builder driverPrefix = string8 [str| #include <stdlib.h> #ifndef __COMPCERT__ # define __builtin_ais_annot(X) do {} while(0) #endif #define BSIZE 65536 unsigned char data_s [BSIZE]; #ifdef CVAL_BARE_METAL // Valid bare metal mode - functions provided by startup code void exit_ok(void); void exit_evil(int status); #else void exit_ok(void) { __builtin_ais_annot("instruction %here assert reachable: true;"); exit(EXIT_SUCCESS); } void exit_evil(int status) { # ifdef ENABLE_PRINT_ERROR_STATUS printf("Test %d failed.\n", status); # endif # ifndef DISABLE_STATUS_MASKING if (status & 0xff == EXIT_SUCCESS) { status = EXIT_FAILURE; } # endif # ifndef DISABLE_ASSERT_REACHABLE_FALSE __builtin_ais_annot("instruction %here assert reachable: false;"); # endif exit(status); } #endif // CVAL_BARE_METAL |] mainPrefix :: Builder mainPrefix = string8 [str| int main(void) { int n, m; unsigned char data_fp [8]; |] mainSuffix :: Builder mainSuffix = string8 [str| exit_ok(); return 0; }|] -- |Generate statements to call test function 'n' with a given signature callTestFunction :: Bool -> Int -> Signature -> Builder callTestFunction p64 n (Signature args) = string8 " {\n n = 0;\n" <> mconcat (mapi vardecl args) <> mconcat (mapiAccumL_ setup bytes args) <> string8 " if (test" <> intDec n <> string8 "(" <> commaSeparated (mapiAccumL_ argument bytes args) <> string8 ") != 0) exit_evil(" <> intDec n <> string8 ");\n }\n" where -- sequence of data bytes used to build the argument values bytes = drop (n*13) $ cycle [16..128] -- sequence of variable declarations for fp parameters vardecl i t | t==F32 || t==F64 = string8 " " <> printArgumentType t <> string8 " a" <> intDec i <> string8 ";\n" | otherwise = mempty -- sequence of statements to setup data for one argument setup i bs t = let (prefix, suffix) = splitAt (argumentByteSize p64 t) bs in (suffix, setup' i prefix t) setup' i bs t | t==F32 || t==F64 = string8 " m = 0;\n" <> mconcat (map initFByte bs) <> string8 " a" <> intDec i <> string8 " = *((" <> printArgumentType t <> string8 "*)data_fp);\n" | otherwise = mconcat (map initIByte bs) initFByte b = string8 " data_s [n++] = data_fp [m++] = 0x" <> wordHex b <> string8 ";\n" initIByte b = string8 " data_s [n++] = 0x" <> wordHex b <> string8 ";\n" -- the actual arguments for the call to the test function argument i bs t = let (prefix, suffix) = splitAt (argumentByteSize p64 t) bs in (suffix, argument' i prefix t) argument' i bs t | t==F32 || t==F64 = string8 "a" <> intDec i | t==Pointer = string8 "(void *)0x" <> wordHex (accumulate bs) | otherwise = string8 "0x" <> wordHex (accumulate bs) accumulate = foldl (\acc a -> acc*256 + a) 0 -- |Like map but with an additional counter argument mapi :: (Int -> a -> b) -> [a] -> [b] mapi f = zipWith f [1..] -- |Like mapAccumL map but with an additional counter argument, also the final accumulator value is ignored mapiAccumL_ :: (Int -> a -> b -> (a, c)) -> a -> [b] -> [c] mapiAccumL_ f acc bs = snd $ mapAccumL f' acc bs' where bs' = zip [1..] bs f' a (i, b) = f i a b -- |Like Data.List.intercalate but by monoidal concat of Builders. intercalate :: Builder -> [Builder] -> Builder intercalate b bs = mconcat $ intersperse b bs newlineSeparated :: [Builder] -> Builder newlineSeparated = intercalate (char8 '\n') commaSeparated :: [Builder] -> Builder commaSeparated = intercalate (string8 ", ")
m-schmidt/fuzzer
src/ConventionTest.hs
bsd-3-clause
7,120
0
22
1,791
1,622
823
799
99
2
-------------------------------------------------------------------------------- module Copilot.Kind.Misc.Type ( Type (..) , U (..) ) where import Copilot.Core.Type.Equality -------------------------------------------------------------------------------- data Type a where Bool :: Type Bool Integer :: Type Integer Real :: Type Double instance EqualType Type where Bool =~= Bool = Just Refl Integer =~= Integer = Just Refl Real =~= Real = Just Refl _ =~= _ = Nothing -------------------------------------------------------------------------------- -- For instance, 'U Expr' is the type of an expression of unknown type data U f = forall t . U (f t) -------------------------------------------------------------------------------- instance Show (Type t) where show Integer = "Int" show Bool = "Bool" show Real = "Real" --------------------------------------------------------------------------------
jonathan-laurent/copilot-kind
src/Copilot/Kind/Misc/Type.hs
bsd-3-clause
986
0
8
188
186
102
84
-1
-1
module Data.Traversable.Fair ( foldMapBoth , traverseBoth , foldMapWithKeyBoth , traverseWithKeyBoth , foldMapBoth1 , traverseBoth1 , foldMapWithKeyBoth1 , traverseWithKeyBoth1 ) where import Control.Applicative import Control.Arrow import Data.Key import Data.Functor.Apply import Data.Foldable import Data.Traversable import Data.Semigroup import Data.Semigroup.Foldable import Data.Semigroup.Traversable import Data.List.NonEmpty as NonEmpty hiding (toList) refill :: Traversable t => t a -> [b] -> t b refill t l = snd (mapAccumL (\xs _ -> (Prelude.tail xs, Prelude.head xs)) l t) toNonEmptyList :: Foldable1 f => f a -> NonEmpty a toNonEmptyList = NonEmpty.fromList . toList toKeyedNonEmptyList :: FoldableWithKey1 f => f a -> NonEmpty (Key f, a) toKeyedNonEmptyList = NonEmpty.fromList . toKeyedList foldMapBoth :: (Foldable f, Foldable g, Monoid m) => (a -> m) -> f a -> g a -> m foldMapBoth f as bs = go (toList as) (toList bs) where go [] [] = mempty go xs [] = foldMap f xs go [] ys = foldMap f ys go (x:xs) (y:ys) = f x `mappend` f y `mappend` go xs ys -- | traverse both containers, interleaving effects for fairness traverseBoth :: (Traversable f, Traversable g, Applicative m) => (a -> m b) -> f a -> g a -> m (f b, g b) traverseBoth f as bs = (refill as *** refill bs) <$> go (toList as) (toList bs) where go [] [] = pure ([],[]) go xs [] = flip (,) [] <$> traverse f xs go [] ys = (,) [] <$> traverse f ys go (x:xs) (y:ys) = (\x' y' (xs',ys') -> (x':xs',y':ys')) <$> f x <*> f y <*> go xs ys -- | fold both containers, interleaving results for fairness foldMapBoth1 :: (Foldable1 f, Foldable1 g, Semigroup m) => (a -> m) -> f a -> g a -> m foldMapBoth1 f as bs = go (toNonEmptyList as) (toNonEmptyList bs) where go (x:|[]) (y:|[]) = f x <> f y go (x:|z:zs) (y:|[]) = f x <> f y <> foldMap1 f (z:|zs) go (x:|[]) ys = f x <> foldMap1 f ys go (x:|z:zs) (y:|w:ws) = f x <> f y <> go (z:|zs) (w:|ws) -- | traverse both containers, interleaving effects for fairness traverseBoth1 :: (Traversable1 f, Traversable1 g, Apply m) => (a -> m b) -> f a -> g a -> m (f b, g b) traverseBoth1 f as bs = (refill as *** refill bs) <$> go (toNonEmptyList as) (toNonEmptyList bs) where go (x:|[]) (y:|[]) = (\x' y' -> ([x'], [y'] )) <$> f x <.> f y go (x:|z:zs) (y:|[]) = (\x' y' (x'':|xs') -> (x':x'':xs', [y'] )) <$> f x <.> f y <.> traverse1 f (z:|zs) go (x:|[]) ys = (\x' (y':|ys') -> ([x'], y':ys')) <$> f x <.> traverse1 f ys go (x:|z:zs) (y:|w:ws) = (\x' y' (xs', ys') -> (x':xs', y':ys')) <$> f x <.> f y <.> go (z:|zs) (w:|ws) foldMapWithKeyBoth :: (FoldableWithKey f, FoldableWithKey g, Monoid m) => (Key f -> a -> m) -> (Key g -> a -> m) -> f a -> g a -> m foldMapWithKeyBoth f g as bs = go (toKeyedList as) (toKeyedList bs) where f' = uncurry f g' = uncurry g go [] [] = mempty go xs [] = foldMap f' xs go [] ys = foldMap g' ys go (x:xs) (y:ys) = f' x `mappend` g' y `mappend` go xs ys -- | traverse both containers, interleaving effects for fairness traverseWithKeyBoth :: (TraversableWithKey f, TraversableWithKey g, Applicative m) => (Key f -> a -> m b) -> (Key g -> a -> m b) -> f a -> g a -> m (f b, g b) traverseWithKeyBoth f g as bs = (refill as *** refill bs) <$> go (toKeyedList as) (toKeyedList bs) where f' = uncurry f g' = uncurry g go [] [] = pure ([],[]) go xs [] = flip (,) [] <$> traverse f' xs go [] ys = (,) [] <$> traverse g' ys go (x:xs) (y:ys) = (\x' y' (xs',ys') -> (x':xs',y':ys')) <$> f' x <*> g' y <*> go xs ys -- | fold both containers, interleaving results for fairness foldMapWithKeyBoth1 :: (FoldableWithKey1 f, FoldableWithKey1 g, Semigroup m) => (Key f -> a -> m) -> (Key g -> a -> m) -> f a -> g a -> m foldMapWithKeyBoth1 f g as bs = go (toKeyedNonEmptyList as) (toKeyedNonEmptyList bs) where f' = uncurry f g' = uncurry g go (x:|[]) (y:|[]) = f' x <> g' y go (x:|z:zs) (y:|[]) = f' x <> g' y <> foldMap1 f' (z:|zs) go (x:|[]) ys = f' x <> foldMap1 g' ys go (x:|z:zs) (y:|w:ws) = f' x <> g' y <> go (z:|zs) (w:|ws) -- | traverse both containers, interleaving effects for fairness traverseWithKeyBoth1 :: (TraversableWithKey1 f, TraversableWithKey1 g, Apply m) => (Key f -> a -> m b) -> (Key g -> a -> m b) -> f a -> g a -> m (f b, g b) traverseWithKeyBoth1 f g as bs = (refill as *** refill bs) <$> go (toKeyedNonEmptyList as) (toKeyedNonEmptyList bs) where f' = uncurry f g' = uncurry g go (x:|[]) (y:|[]) = (\x' y' -> ([x'], [y'] )) <$> f' x <.> g' y go (x:|z:zs) (y:|[]) = (\x' y' (z':|zs') -> (x':z':zs', [y'] )) <$> f' x <.> g' y <.> traverse1 f' (z:|zs) go (x:|[]) ys = (\x' (y':|ys') -> ([x'], y':ys')) <$> f' x <.> traverse1 g' ys go (x:|z:zs) (y:|w:ws) = (\x' y' (xs', ys') -> (x':xs', y':ys')) <$> f' x <.> g' y <.> go (z:|zs) (w:|ws)
ekmett/representable-tries
src/Data/Traversable/Fair.hs
bsd-3-clause
5,052
0
14
1,287
2,782
1,428
1,354
105
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Distributed.Process.Extras.Internal.Primitives -- Copyright : (c) Tim Watson 2013, Parallel Scientific (Jeff Epstein) 2012 -- License : BSD3 (see the file LICENSE) -- -- Maintainers : Jeff Epstein, Tim Watson -- Stability : experimental -- Portability : non-portable (requires concurrency) -- -- This module provides a set of additional primitives that add functionality -- to the basic Cloud Haskell APIs. ----------------------------------------------------------------------------- module Control.Distributed.Process.Extras.Internal.Primitives ( -- * General Purpose Process Addressing Addressable , Routable(..) , Resolvable(..) , Linkable(..) , Killable(..) -- * Spawning and Linking , spawnSignalled , spawnLinkLocal , spawnMonitorLocal , linkOnFailure -- * Registered Processes , whereisRemote , whereisOrStart , whereisOrStartRemote -- * Selective Receive/Matching , matchCond , awaitResponse -- * General Utilities , times , monitor , awaitExit , isProcessAlive , forever' , deliver -- * Remote Table , __remoteTable ) where import Control.Concurrent (myThreadId, throwTo) import Control.Distributed.Process hiding (monitor) import qualified Control.Distributed.Process as P (monitor) import Control.Distributed.Process.Closure (seqCP, remotable, mkClosure) import Control.Distributed.Process.Serializable (Serializable) import Control.Distributed.Process.Extras.Internal.Types ( Addressable , Linkable(..) , Killable(..) , Resolvable(..) , Routable(..) , RegisterSelf(..) , ExitReason(ExitOther) , whereisRemote ) import Control.Monad (void) import Data.Maybe (isJust, fromJust) -- utility -- | Monitor any @Resolvable@ object. -- monitor :: Resolvable a => a -> Process (Maybe MonitorRef) monitor addr = do mPid <- resolve addr case mPid of Nothing -> return Nothing Just p -> return . Just =<< P.monitor p awaitExit :: Resolvable a => a -> Process () awaitExit addr = do mPid <- resolve addr case mPid of Nothing -> return () Just p -> do mRef <- P.monitor p receiveWait [ matchIf (\(ProcessMonitorNotification r p' _) -> r == mRef && p == p') (\_ -> return ()) ] deliver :: (Addressable a, Serializable m) => m -> a -> Process () deliver = flip sendTo isProcessAlive :: ProcessId -> Process Bool isProcessAlive pid = getProcessInfo pid >>= \info -> return $ info /= Nothing -- | Apply the supplied expression /n/ times times :: Int -> Process () -> Process () n `times` proc = runP proc n where runP :: Process () -> Int -> Process () runP _ 0 = return () runP p n' = p >> runP p (n' - 1) -- | Like 'Control.Monad.forever' but sans space leak forever' :: Monad m => m a -> m b forever' a = let a' = a >> a' in a' {-# INLINE forever' #-} -- spawning, linking and generic server startup -- | Spawn a new (local) process. This variant takes an initialisation -- action and a secondary expression from the result of the initialisation -- to @Process ()@. The spawn operation synchronises on the completion of the -- @before@ action, such that the calling process is guaranteed to only see -- the newly spawned @ProcessId@ once the initialisation has successfully -- completed. spawnSignalled :: Process a -> (a -> Process ()) -> Process ProcessId spawnSignalled before after = do (sigStart, recvStart) <- newChan (pid, mRef) <- spawnMonitorLocal $ do initProc <- before sendChan sigStart () after initProc receiveWait [ matchIf (\(ProcessMonitorNotification ref _ _) -> ref == mRef) (\(ProcessMonitorNotification _ _ dr) -> die $ ExitOther (show dr)) , matchChan recvStart (\() -> return pid) ] -- | Node local version of 'Control.Distributed.Process.spawnLink'. -- Note that this is just the sequential composition of 'spawn' and 'link'. -- (The "Unified" semantics that underlies Cloud Haskell does not even support -- a synchronous link operation) spawnLinkLocal :: Process () -> Process ProcessId spawnLinkLocal p = do pid <- spawnLocal p link pid return pid -- | Like 'spawnLinkLocal', but monitors the spawned process. -- spawnMonitorLocal :: Process () -> Process (ProcessId, MonitorRef) spawnMonitorLocal p = do pid <- spawnLocal p ref <- P.monitor pid return (pid, ref) -- | CH's 'link' primitive, unlike Erlang's, will trigger when the target -- process dies for any reason. This function has semantics like Erlang's: -- it will trigger 'ProcessLinkException' only when the target dies abnormally. -- linkOnFailure :: ProcessId -> Process () linkOnFailure them = do us <- getSelfPid tid <- liftIO $ myThreadId void $ spawnLocal $ do callerRef <- P.monitor us calleeRef <- P.monitor them reason <- receiveWait [ matchIf (\(ProcessMonitorNotification mRef _ _) -> mRef == callerRef) -- nothing left to do (\_ -> return DiedNormal) , matchIf (\(ProcessMonitorNotification mRef' _ _) -> mRef' == calleeRef) (\(ProcessMonitorNotification _ _ r') -> return r') ] case reason of DiedNormal -> return () _ -> liftIO $ throwTo tid (ProcessLinkException us reason) -- | Returns the pid of the process that has been registered -- under the given name. This refers to a local, per-node registration, -- not @global@ registration. If that name is unregistered, a process -- is started. This is a handy way to start per-node named servers. -- whereisOrStart :: String -> Process () -> Process ProcessId whereisOrStart name proc = do mpid <- whereis name case mpid of Just pid -> return pid Nothing -> do caller <- getSelfPid pid <- spawnLocal $ do self <- getSelfPid register name self send caller (RegisterSelf,self) () <- expect proc ref <- P.monitor pid ret <- receiveWait [ matchIf (\(ProcessMonitorNotification aref _ _) -> ref == aref) (\(ProcessMonitorNotification _ _ _) -> return Nothing), matchIf (\(RegisterSelf,apid) -> apid == pid) (\(RegisterSelf,_) -> return $ Just pid) ] case ret of Nothing -> whereisOrStart name proc Just somepid -> do unmonitor ref send somepid () return somepid registerSelf :: (String, ProcessId) -> Process () registerSelf (name,target) = do self <- getSelfPid register name self send target (RegisterSelf, self) () <- expect return () $(remotable ['registerSelf]) -- | A remote equivalent of 'whereisOrStart'. It deals with the -- node registry on the given node, and the process, if it needs to be started, -- will run on that node. If the node is inaccessible, Nothing will be returned. -- whereisOrStartRemote :: NodeId -> String -> Closure (Process ()) -> Process (Maybe ProcessId) whereisOrStartRemote nid name proc = do mRef <- monitorNode nid whereisRemoteAsync nid name res <- receiveWait [ matchIf (\(WhereIsReply label _) -> label == name) (\(WhereIsReply _ mPid) -> return (Just mPid)), matchIf (\(NodeMonitorNotification aref _ _) -> aref == mRef) (\(NodeMonitorNotification _ _ _) -> return Nothing) ] case res of Nothing -> return Nothing Just (Just pid) -> unmonitor mRef >> return (Just pid) Just Nothing -> do self <- getSelfPid sRef <- spawnAsync nid ($(mkClosure 'registerSelf) (name,self) `seqCP` proc) ret <- receiveWait [ matchIf (\(NodeMonitorNotification ref _ _) -> ref == mRef) (\(NodeMonitorNotification _ _ _) -> return Nothing), matchIf (\(DidSpawn ref _) -> ref==sRef ) (\(DidSpawn _ pid) -> do pRef <- P.monitor pid receiveWait [ matchIf (\(RegisterSelf, apid) -> apid == pid) (\(RegisterSelf, _) -> do unmonitor pRef send pid () return $ Just pid), matchIf (\(NodeMonitorNotification aref _ _) -> aref == mRef) (\(NodeMonitorNotification _aref _ _) -> return Nothing), matchIf (\(ProcessMonitorNotification ref _ _) -> ref==pRef) (\(ProcessMonitorNotification _ _ _) -> return Nothing) ] ) ] unmonitor mRef case ret of Nothing -> whereisOrStartRemote nid name proc Just pid -> return $ Just pid -- advanced messaging/matching -- | An alternative to 'matchIf' that allows both predicate and action -- to be expressed in one parameter. matchCond :: (Serializable a) => (a -> Maybe (Process b)) -> Match b matchCond cond = let v n = (isJust n, fromJust n) res = v . cond in matchIf (fst . res) (snd . res) -- | Safe (i.e., monitored) waiting on an expected response/message. awaitResponse :: Addressable a => a -> [Match (Either ExitReason b)] -> Process (Either ExitReason b) awaitResponse addr matches = do mPid <- resolve addr case mPid of Nothing -> return $ Left $ ExitOther "UnresolvedAddress" Just p -> do mRef <- P.monitor p receiveWait ((matchRef mRef):matches) where matchRef :: MonitorRef -> Match (Either ExitReason b) matchRef r = matchIf (\(ProcessMonitorNotification r' _ _) -> r == r') (\(ProcessMonitorNotification _ _ d) -> do return (Left (ExitOther (show d))))
qnikst/distributed-process-extras
src/Control/Distributed/Process/Extras/Internal/Primitives.hs
bsd-3-clause
10,699
0
28
3,246
2,596
1,341
1,255
199
4
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module Monto.Broker ( empty , printBroker , registerService , deregisterService , registerProductDep , Broker(..) , newVersion , newProduct , Response (..) , Message (..) , Dependency(..) , Server(..) , Service(..) , ServerDependency , ProductDependency(..) ) where import Prelude hiding (product) #if __GLASGOW_HASKELL__ < 710 import Control.Applicative hiding (empty) #endif import Control.Monad (guard) import Data.Aeson (Value) import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import qualified Data.List as List import Data.Map (Map) import qualified Data.Map as M import Data.Set (Set) import qualified Data.Set as S import Data.Graph.Inductive (Gr,Node) import qualified Data.Graph.Inductive as G import qualified Data.Vector as Vector import Monto.Automaton (Automaton(..),L,Process) import qualified Monto.Automaton as A import Monto.Types (Source,Language,Product,Port,ServiceID) import Monto.VersionMessage (VersionMessage) import Monto.ProductMessage (ProductMessage) import Monto.ResourceManager (ResourceManager) import qualified Monto.ResourceManager as R import Monto.DependencyGraph (DependencyGraph,Dependency(..)) import qualified Monto.DependencyGraph as DG import qualified Monto.VersionMessage as V import qualified Monto.ProductMessage as P import Monto.RegisterServiceRequest (RegisterServiceRequest) import qualified Monto.RegisterServiceRequest as RQ data ProductDependency = Version Source | Product (Source,Language,Product) deriving (Eq,Ord) data Print = Print Text instance Show Print where show (Print s) = T.unpack s instance Show ProductDependency where show (Version src) = T.unpack src show (Product (src,prod,lang)) = show (Print src,Print prod,Print lang) data Server = Server Product Language deriving (Eq,Ord) instance Show Server where show (Server pr l) = concat [ T.unpack pr, "/", T.unpack l ] instance Read Server where readsPrec _ r = do (a,r') <- lex r (b,r'') <- lex r' (c,r''') <- lex r'' guard $ b == "/" return (Server (T.pack a) (T.pack c),r''') data Service = Service { serviceID :: ServiceID , label :: Text , description :: Text , language :: Language , product :: Product , port :: Port , options :: Maybe Value } deriving (Eq) instance Show Service where show (Service serviceID' _ _ language' product' port' _) = concat [T.unpack product', "/", T.unpack language', "/", T.unpack serviceID', "/", show port'] type ServerDependency = Dependency Server data Message = VersionMessage VersionMessage | ProductMessage ProductMessage deriving (Eq,Show) data Response = Response Source Server [Message] deriving (Eq,Show) data Broker = Broker { resourceMgr :: ResourceManager , serviceDependencies :: DependencyGraph Server , productDependencies :: DependencyGraph ProductDependency , automaton :: Automaton (Map ServerDependency L) ServerDependency (Set ServerDependency) , processes :: Map Source (Process (Map ServerDependency L) ServerDependency (Set ServerDependency)) , services :: Map ServiceID Service , portPool :: [Port] } deriving (Eq,Show) empty :: Int -> Int -> Broker {-# INLINE empty #-} empty from to = Broker { resourceMgr = R.empty , serviceDependencies = DG.empty , productDependencies = DG.empty , automaton = Automaton { initialState = M.empty , transitions = [] , accepting = [] } , processes = M.empty , services = M.empty , portPool = [from..to] } printBroker :: Broker -> IO() printBroker broker = do print (services broker) print (portPool broker) registerService :: RegisterServiceRequest -> Broker -> Broker {-# INLINE registerService #-} registerService register broker = let serviceID' = RQ.serviceID register server' = Server (RQ.product register) (RQ.language register) deps = (map read $ Vector.toList $ fromJust $ RQ.dependencies register) portPool' = tail (portPool broker) service = Service serviceID' (RQ.label register) (RQ.description register) (RQ.language register) (RQ.product register) (head (portPool broker)) (RQ.options register) services' = M.insert serviceID' service (services broker) serviceDependencies' = DG.register server' deps (serviceDependencies broker) in broker { serviceDependencies = serviceDependencies' , automaton = updateAutomaton (DG.dependencies serviceDependencies') , services = services' , portPool = portPool' } deregisterService :: ServiceID -> Broker -> Broker {-# INLINE deregisterService #-} deregisterService serviceID' broker = fromMaybe broker $ do service <- M.lookup serviceID' (services broker) let server = Server (product service) (language service) return broker { services = M.delete serviceID' (services broker) , portPool = List.insert (port service) (portPool broker) -- , serviceDependencies = DG.deregister server (serviceDependencies broker) } registerProductDep :: ProductDependency -> [ProductDependency] -> Broker -> ([Source],Broker) registerProductDep from to broker = let productDependencies' = DG.register from (map Dependency to) (productDependencies broker) srcs = flip map to $ \dep -> case dep of Version src -> src Product (src,_,_) -> src broker' = broker { productDependencies = productDependencies' } srcs' = flip filter srcs $ \src -> isNothing $ R.lookupVersionMessage src (resourceMgr broker) in (srcs',broker') updateAutomaton :: Ord dep => Gr dep () -> Automaton (Map dep L) dep (Set dep) {-# INLINE updateAutomaton #-} updateAutomaton gr = foldr1 A.merge $ map (uncurry A.buildAutomaton . outEdges) $ G.bfs 0 $ G.grev gr where outEdges n = let (Just (_,_,a,out),_) = G.match n gr in (a,[ fromJust (G.lab gr o) | (_,o) <- out ]) lookupDependencies :: Ord dep => Dependency dep -> DependencyGraph dep -> [Dependency dep] lookupDependencies = lookupDeps G.suc lookupReverseDependencies :: Ord dep => Dependency dep -> DependencyGraph dep -> [Dependency dep] lookupReverseDependencies = lookupDeps G.pre lookupDeps :: Ord dep => (Gr (Dependency dep) () -> Node -> [Node]) -> Dependency dep -> DependencyGraph dep -> [Dependency dep] lookupDeps direction dep dg = case M.lookup dep (DG.nodeMap dg) of Just depNode -> do nodes <- direction (DG.dependencies dg) depNode return $ fromJust $ G.lab (DG.dependencies dg) nodes Nothing -> [] newVersion :: VersionMessage -> Broker -> ([Response],Broker) {-# INLINE newVersion #-} newVersion version broker = let process = A.start (A.compileAutomaton (automaton broker)) (res,process') = fromMaybe (S.empty,process) $ A.runProcess Bottom process broker' = broker { processes = M.insert (V.source version) process' (processes broker) , resourceMgr = snd $ R.updateVersion version $ resourceMgr broker } in (mapMaybe (\(Dependency (Server prod lang)) -> makeResponse broker' (V.source version) prod lang) (S.toList res),broker') newProduct :: ProductMessage -> Broker -> ([Response],Broker) {-# INLINE newProduct #-} newProduct pr broker | R.isOutdated pr (resourceMgr broker) = ([],broker) | otherwise = let process = fromMaybe (A.start (A.compileAutomaton (automaton broker))) $ M.lookup (P.source pr) $ processes broker (res,process') = fromMaybe (S.empty,process) $ A.runProcess (Dependency (Server (P.product pr) (P.language pr))) process res' = lookupReverseDependencies (Dependency (Product (P.source pr, P.language pr,P.product pr))) (productDependencies broker) broker' = broker { resourceMgr = snd $ R.updateProduct' pr $ resourceMgr broker , processes = M.insert (P.product pr) process' (processes broker) } staticResponse = map (\(Dependency (Server prod lang)) -> makeResponse broker' (P.source pr) prod lang) (S.toList res) dynamicResponse = map (\(Dependency (Product (src,lang,prod))) -> makeResponse broker' src prod lang) res' in (catMaybes (staticResponse ++ dynamicResponse),broker') makeResponse :: Broker -> Source -> Product -> Language -> Maybe Response {-# INLINE makeResponse #-} makeResponse broker source product' language' = let sdeps = lookupDependencies (Dependency (Server product' language')) (serviceDependencies broker) pdeps = lookupDependencies (Dependency (Product (source,language',product'))) (productDependencies broker) deps = map (depForServer source) sdeps ++ map (\(Dependency p) -> p) pdeps msgs = mapMaybe (lookupDependency broker) deps in if all isJust $ map (\(Dependency p) -> lookupDependency broker p) pdeps then Just $ Response source (Server product' language') msgs else Nothing depForServer :: Source -> ServerDependency -> ProductDependency depForServer source (Dependency (Server prod lang)) = Product (source,lang,prod) depForServer source Bottom = Version source depForServer _ Top = error "top is no dependency" lookupDependency :: Broker -> ProductDependency -> Maybe Message lookupDependency broker dep = case dep of (Version source) -> VersionMessage <$> R.lookupVersionMessage source (resourceMgr broker) (Product p) -> ProductMessage <$> R.lookupProductMessage p (resourceMgr broker)
wpmp/monto-broker
src/Monto/Broker.hs
bsd-3-clause
9,904
0
18
2,226
3,185
1,702
1,483
212
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-| Allocate resources which are guaranteed to be released. One point to note: all register cleanup actions live in IO, not the main monad. This allows both more efficient code, and for monads to be transformed. -} module Control.Monad.Resource ( -- * The @ResourceT@ monad transformer ResourceT -- ** Running , runResourceT -- ** Monad transformation , mapResourceT -- * The @MonadResource@ type class , MonadResource (..) , ReleaseKey ) where import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.IORef (IORef, newIORef, writeIORef, atomicModifyIORef) import Data.Word (Word) import Control.Applicative (Applicative (..), Alternative (..)) import Control.Exception (SomeException, mask, mask_, try, finally) import Control.Monad (MonadPlus (..), ap, liftM, when) import Control.Monad.Base (MonadBase (..)) import Control.Monad.Fork.Class (MonadFork (..)) import Control.Monad.Instances.Evil () import Control.Monad.IO.Class (MonadIO) import Control.Monad.Trans.Class (MonadTrans (..)) import Control.Monad.Trans.Control ( MonadBaseControl (..) , MonadTransControl (..) , control ) ------------------------------------------------------------------------------ -- | A lookup key for a specific release action. This value is returned by -- 'register' and 'with' and is passed to 'release'. newtype ReleaseKey = ReleaseKey Int ------------------------------------------------------------------------------ data ReleaseMap = ReleaseMap !Int !Word !(IntMap (IO ())) ------------------------------------------------------------------------------ -- | The Resource transformer. This transformer keeps track of all registered -- actions, and calls them upon exit (via 'runResourceT'). Actions may be -- registered via 'register', or resources may be allocated atomically via -- 'with'. The 'with' function corresponds closely to @bracket@. These -- functions are provided by 'ResourceT'\'s 'MonadResource' instance. -- -- Releasing may be performed before exit via the 'release' function. This is -- a highly recommended optimization, as it will ensure that scarce resources -- are freed early. Note that calling @release@ will deregister the action, so -- that a release action will only ever be called once. -- -- Pass-through instances for the @mtl@ type classes are provided -- automatically by the @mtl-evil-instances@ package. newtype ResourceT m a = ResourceT (IORef ReleaseMap -> m a) ------------------------------------------------------------------------------ instance MonadTrans ResourceT where lift = ResourceT . const ------------------------------------------------------------------------------ instance MonadTransControl ResourceT where newtype StT ResourceT a = StReader {unStReader :: a} liftWith f = ResourceT $ \r -> f $ \(ResourceT t) -> liftM StReader $ t r restoreT = ResourceT . const . liftM unStReader ------------------------------------------------------------------------------ instance Monad m => Functor (ResourceT m) where fmap = liftM ------------------------------------------------------------------------------ instance Monad m => Applicative (ResourceT m) where pure = return (<*>) = ap ------------------------------------------------------------------------------ instance MonadPlus m => Alternative (ResourceT m) where empty = mzero (<|>) = mplus ------------------------------------------------------------------------------ instance Monad m => Monad (ResourceT m) where return = ResourceT . const . return ResourceT m >>= f = ResourceT $ \r -> m r >>= \a -> let ResourceT m' = f a in m' r ------------------------------------------------------------------------------ instance MonadPlus m => MonadPlus (ResourceT m) where mzero = ResourceT $ const mzero mplus (ResourceT m) (ResourceT m') = ResourceT $ \r -> mplus (m r) (m' r) ------------------------------------------------------------------------------ instance MonadBaseControl b m => MonadBaseControl b (ResourceT m) where newtype StM (ResourceT m) a = StMT (StM m a) liftBaseWith f = ResourceT $ \reader -> liftBaseWith $ \runInBase -> f $ liftM StMT . runInBase . (\(ResourceT r) -> r reader) restoreM (StMT base) = ResourceT $ const $ restoreM base ------------------------------------------------------------------------------ instance (MonadFork m, MonadBaseControl IO m) => MonadFork (ResourceT m) where fork (ResourceT f) = ResourceT $ \istate -> control $ \run -> mask $ \unmask -> do stateAlloc istate run . fork $ control $ \run' -> do unmask (run' $ f istate) `finally` stateCleanup istate ------------------------------------------------------------------------------ -- | Transform the monad a @ResourceT@ lives in. This is most often used to -- strip or add new transformers to a stack, e.g. to run a @ReaderT@. mapResourceT :: (m a -> n b) -> ResourceT m a -> ResourceT n b mapResourceT f (ResourceT m) = ResourceT $ f . m ------------------------------------------------------------------------------ -- | Unwrap a 'ResourceT' transformer, and call all registered release -- actions. -- -- Note that there is some reference counting involved due to the -- implementation of 'fork' used in the 'MonadFork' instance. If multiple -- threads are sharing the same collection of resources, only the last call -- to @runResourceT@ will deallocate the resources. runResourceT :: MonadBaseControl IO m => ResourceT m a -> m a runResourceT (ResourceT r) = do istate <- liftBase $ newIORef $ ReleaseMap 0 0 IntMap.empty control $ \run -> mask $ \unmask -> do stateAlloc istate unmask (run $ r istate) `finally` stateCleanup istate ------------------------------------------------------------------------------ stateAlloc :: IORef ReleaseMap -> IO () stateAlloc istate = atomicModifyIORef istate $ \(ReleaseMap key ref im) -> (ReleaseMap key (ref + 1) im, ()) ------------------------------------------------------------------------------ stateCleanup :: IORef ReleaseMap -> IO () stateCleanup istate = mask_ $ do (ref, im) <- atomicModifyIORef istate $ \(ReleaseMap key ref im) -> (ReleaseMap key (ref - 1) im, (ref - 1, im)) when (ref == 0) $ do mapM_ (\x -> try' x >> return ()) $ IntMap.elems im writeIORef istate $ error "Control.Monad.Resource.stateCleanup: There\ \ is a bug in the implementation. The mutable state is being\ \ accessed after cleanup. Please contact the maintainers." where try' = try :: IO a -> IO (Either SomeException a) ------------------------------------------------------------------------------ register' :: IORef ReleaseMap -> IO () -> IO ReleaseKey register' istate m = atomicModifyIORef istate $ \(ReleaseMap key ref im) -> (ReleaseMap (key + 1) ref (IntMap.insert key m im), ReleaseKey key) ------------------------------------------------------------------------------ release' :: IORef ReleaseMap -> ReleaseKey -> IO () release' istate (ReleaseKey key) = mask $ \unmask -> do atomicModifyIORef istate lookupAction >>= maybe (return ()) unmask where lookupAction rm@(ReleaseMap key' ref im) = case IntMap.lookup key im of Nothing -> (rm, Nothing) Just m -> (ReleaseMap key' ref $ IntMap.delete key im, Just m) ------------------------------------------------------------------------------ -- | The 'MonadResource' type class. This provides the 'with', 'register' and -- 'release' functions, which are the main functionality of this package. The -- main instance of this class is 'ResourceT'. -- -- The others instances are overlapping instances (in the spirit of -- @mtl-evil-instances@), which provide automatic pass-through instances for -- 'MonadResource' for every monad transformer. This means that you don't have -- to provide a pass-through instance of 'MonadResource' for every monad -- transformer you write. class MonadIO m => MonadResource m where -- | Perform some allocation, and automatically register a cleanup action. with :: IO a -> (a -> IO ()) -> m (ReleaseKey, a) -- | Register some action that will be run precisely once, either when -- 'runResourceT' is called, or when the 'ReleaseKey' is passed to -- 'release'. register :: IO () -> m ReleaseKey -- | Call a release action early, and deregister it from the list of -- cleanup actions to be performed. release :: ReleaseKey -> m () ------------------------------------------------------------------------------ instance MonadBaseControl IO m => MonadResource (ResourceT m) where with acquire m = ResourceT $ \istate -> liftBase . mask $ \unmask -> do a <- unmask acquire key <- register' istate $ m a return (key, a) register m = ResourceT $ \istate -> liftBase $ register' istate m release key = ResourceT $ \istate -> liftBase $ release' istate key ------------------------------------------------------------------------------ instance (MonadTrans t, Monad (t m), MonadResource m) => MonadResource (t m) where with = (lift .) . with register = lift . register release = lift . release ------------------------------------------------------------------------------ instance (MonadBase b m, MonadResource b) => MonadResource m where with = (liftBase .) . with register = liftBase . register release = liftBase . release
duairc/resource-simple
src/Control/Monad/Resource.hs
bsd-3-clause
9,954
0
22
1,936
2,025
1,087
938
119
2
{- | Module : $Id: GUI.hs 13959 2010-08-31 22:15:26Z cprodescu $ Description : graphical user interface modules Copyright : (c) Uni Bremen 2005-2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : raider@informatik.uni-bremen.de Stability : provisional Portability : non-portable (uses uni and development graphs) Graphical user interface for Hets. The GUI is based on the UniForM Workbench <http://www.informatik.uni-bremen.de/uniform/wb>. The UniForm Workbench provides an event system and encapsulations of TclTk <http://www.informatik.uni-bremen.de/htk/> and uDraw(Graph) <http://www.informatik.uni-bremen.de/uDrawGraph/en/index.html> (see module "GraphDisp"). "GUI.AbstractGraphView" is a graph interface, based on the Workbench encapsulation of uDraw(Graph). Provides additional functions for hiding and redisplaying (groups of) nodes and edges. (Obsolete, use GraphAbstraction instead) "GUI.ConsoleUtils" are similar utilities for using without "HTk" (only console). "GUI.GenericATP" is a generic graphical interface for automatic theorem provers. Decides between Gtk and HTk implementation. "GUI.GraphAbstraction" provides an interface to uDrawGraph. "GUI.GraphDisplay" provides functions to display a DevGraph in a new window. "GUI.GraphLogic" provides the functionality for the menus created with "GUI.GraphMenu" "GUI.GraphMenu" creates the File and the Edit menu of uDrawGraph, as well as the local node and edge menus and types. "GUI.GraphTypes" defines the types used in "GUI.GraphDisplay", "GUI.GraphLogic" and "GUI.GraphMenu". "GUI.GtkConsistencyChecker" gui for checking consistency. "GUI.GtkGenericATP" gtk version of generic prove gui. "GUI.GtkLinkTypeChoice" small window letting the user select the link types that should be displayed or hidden. "GUI.GtkProverGUI" prover gui implementation in gtk. "GUI.GtkUtils" a bunch of utility functions for use in and outside of gtk. "GUI.HTkGenericATP" htk version of generic prove gui. "GUI.HTkProofDetails" sets an additional window used by "GUI.ProverGUI" for displaying and saving proof details (prover output, tactic script, proof tree). "GUI.HTkProverGUI" is a goal management GUI for the structured level. "GUI.HTkUtils" provides some utilities on top of "HTk". "GUI.ProverGUI" is a goal management GUI for the structured level. Decides between Gtk and HTk implementation. "GUI.ShowGraph" displays the final graph. "GUI.ShowLibGraph" displays the library graph. "GUI.ShowLogicGraph" displays the logic graph. "GUI.Taxonomy" displays a subsort relation (taxonomy). "GUI.Utils" are either "GUI.HTkUtils", "GUI.GtkUtils" or "GUI.ConsoleUtils". "GUI.UDGUtils" just imports and exports uDrawGraph modules. -} module GUI where
nevrenato/HetsAlloy
GUI.hs
gpl-2.0
2,745
0
2
383
5
4
1
1
0
{-# OPTIONS_GHC -cpp #-} ------------------------------------------------------------------------------------------- -- | -- Module : Control.Arrow.BiKleisli -- Copyright : 2008 Edward Kmett -- License : BSD3 -- -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------------------- module Control.Arrow.BiKleisli ( BiKleisli(..) ) where import Prelude hiding (id,(.)) import Control.Category import Control.Monad (liftM) import Control.Comonad import Control.Arrow import Control.Functor.Extras newtype BiKleisli w m a b = BiKleisli { runBiKleisli :: w a -> m b } instance Monad m => Functor (BiKleisli w m a) where fmap f (BiKleisli g) = BiKleisli (liftM f . g) instance (Comonad w, Monad m, Distributes w m) => Arrow (BiKleisli w m) where arr f = BiKleisli (return . f . extract) first (BiKleisli f) = BiKleisli $ \x -> do u <- f (fmap fst x) return (u, extract (fmap snd x)) #if __GLASGOW_HASKELL__ < 609 BiKleisli g >>> BiKleisli f = BiKleisli ((>>= f) . dist . extend g) #endif instance (Comonad w, Monad m, Distributes w m) => Category (BiKleisli w m) where BiKleisli f . BiKleisli g = BiKleisli ((>>=f) . dist . extend g) id = BiKleisli (return . extract)
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
Control/Arrow/BiKleisli.hs
apache-2.0
1,309
4
14
211
415
225
190
21
0
{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} -- | Provide a notion of fanout wherein a single input is passed to -- several consumers. module Data.Machine.Fanout (fanout, fanoutSteps) where import Data.List.NonEmpty (NonEmpty (..)) import Data.Machine import Data.Semigroup (Semigroup (sconcat)) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid (Monoid (..)) import Data.Traversable (traverse) #endif continue :: ([b] -> r) -> [(a -> b, b)] -> Step (Is a) o r continue _ [] = Stop continue f ws = Await (f . traverse fst ws) Refl (f $ map snd ws) semigroupDlist :: Semigroup a => ([a] -> [a]) -> Maybe a semigroupDlist f = case f [] of [] -> Nothing x:xs -> Just $ sconcat (x:|xs) -- | Share inputs with each of a list of processes in lockstep. Any -- values yielded by the processes are combined into a single yield -- from the composite process. fanout :: (Functor m, Monad m, Semigroup r) => [ProcessT m a r] -> ProcessT m a r fanout = MachineT . go id id where go waiting acc [] = case waiting [] of ws -> return . maybe k (\x -> Yield x $ encased k) $ semigroupDlist acc where k = continue fanout ws go waiting acc (m:ms) = runMachineT m >>= \v -> case v of Stop -> go waiting acc ms Yield x k -> go waiting (acc . (x:)) (k:ms) Await f Refl k -> go (waiting . ((f, k):)) acc ms -- | Share inputs with each of a list of processes in lockstep. If -- none of the processes yields a value, the composite process will -- itself yield 'mempty'. The idea is to provide a handle on steps -- only executed for their side effects. For instance, if you want to -- run a collection of 'ProcessT's that await but don't yield some -- number of times, you can use 'fanOutSteps . map (fmap (const ()))' -- followed by a 'taking' process. fanoutSteps :: (Functor m, Monad m, Monoid r) => [ProcessT m a r] -> ProcessT m a r fanoutSteps = MachineT . go id id where go waiting acc [] = case (waiting [], mconcat (acc [])) of (ws, xs) -> return . Yield xs $ encased (continue fanoutSteps ws) go waiting acc (m:ms) = runMachineT m >>= \v -> case v of Stop -> go waiting acc ms Yield x k -> go waiting (acc . (x:)) (k:ms) Await f Refl k -> go (waiting . ((f, k):)) acc ms
bitemyapp/machines
src/Data/Machine/Fanout.hs
bsd-3-clause
2,352
0
16
618
789
420
369
34
4
{-# LANGUAGE CPP #-} module Distribution.Client.Dependency.Modular.Builder (buildTree) where -- Building the search tree. -- -- In this phase, we build a search tree that is too large, i.e, it contains -- invalid solutions. We keep track of the open goals at each point. We -- nondeterministically pick an open goal (via a goal choice node), create -- subtrees according to the index and the available solutions, and extend the -- set of open goals by superficially looking at the dependencies recorded in -- the index. -- -- For each goal, we keep track of all the *reasons* why it is being -- introduced. These are for debugging and error messages, mainly. A little bit -- of care has to be taken due to the way we treat flags. If a package has -- flag-guarded dependencies, we cannot introduce them immediately. Instead, we -- store the entire dependency. import Data.List as L import Data.Map as M import Prelude hiding (sequence, mapM) import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Index import Distribution.Client.Dependency.Modular.Package import Distribution.Client.Dependency.Modular.PSQ (PSQ) import qualified Distribution.Client.Dependency.Modular.PSQ as P import Distribution.Client.Dependency.Modular.Tree import Distribution.Client.ComponentDeps (Component) -- | The state needed during the build phase of the search tree. data BuildState = BS { index :: Index, -- ^ information about packages and their dependencies rdeps :: RevDepMap, -- ^ set of all package goals, completed and open, with reverse dependencies open :: PSQ (OpenGoal ()) (), -- ^ set of still open goals (flag and package goals) next :: BuildType, -- ^ kind of node to generate next qualifyOptions :: QualifyOptions -- ^ qualification options } -- | Extend the set of open goals with the new goals listed. -- -- We also adjust the map of overall goals, and keep track of the -- reverse dependencies of each of the goals. extendOpen :: QPN -> [OpenGoal Component] -> BuildState -> BuildState extendOpen qpn' gs s@(BS { rdeps = gs', open = o' }) = go gs' o' gs where go :: RevDepMap -> PSQ (OpenGoal ()) () -> [OpenGoal Component] -> BuildState go g o [] = s { rdeps = g, open = o } go g o (ng@(OpenGoal (Flagged _ _ _ _) _gr) : ngs) = go g (cons' ng () o) ngs -- Note: for 'Flagged' goals, we always insert, so later additions win. -- This is important, because in general, if a goal is inserted twice, -- the later addition will have better dependency information. go g o (ng@(OpenGoal (Stanza _ _ ) _gr) : ngs) = go g (cons' ng () o) ngs go g o (ng@(OpenGoal (Simple (Dep qpn _) c) _gr) : ngs) | qpn == qpn' = go g o ngs -- we ignore self-dependencies at this point; TODO: more care may be needed | qpn `M.member` g = go (M.adjust ((c, qpn'):) qpn g) o ngs | otherwise = go (M.insert qpn [(c, qpn')] g) (cons' ng () o) ngs -- code above is correct; insert/adjust have different arg order go g o ( (OpenGoal (Simple (Ext _ext ) _) _gr) : ngs) = go g o ngs go g o ( (OpenGoal (Simple (Lang _lang)_) _gr) : ngs) = go g o ngs go g o ( (OpenGoal (Simple (Pkg _pn _vr)_) _gr) : ngs)= go g o ngs cons' = P.cons . forgetCompOpenGoal -- | Given the current scope, qualify all the package names in the given set of -- dependencies and then extend the set of open goals accordingly. scopedExtendOpen :: QPN -> I -> QGoalReason -> FlaggedDeps Component PN -> FlagInfo -> BuildState -> BuildState scopedExtendOpen qpn i gr fdeps fdefs s = extendOpen qpn gs s where -- Qualify all package names qfdeps = qualifyDeps (qualifyOptions s) qpn fdeps -- Introduce all package flags qfdefs = L.map (\ (fn, b) -> Flagged (FN (PI qpn i) fn) b [] []) $ M.toList fdefs -- Combine new package and flag goals gs = L.map (flip OpenGoal gr) (qfdefs ++ qfdeps) -- NOTE: -- -- In the expression @qfdefs ++ qfdeps@ above, flags occur potentially -- multiple times, both via the flag declaration and via dependencies. -- The order is potentially important, because the occurrences via -- dependencies may record flag-dependency information. After a number -- of bugs involving computing this information incorrectly, however, -- we're currently not using carefully computed inter-flag dependencies -- anymore, but instead use 'simplifyVar' when computing conflict sets -- to map all flags of one package to a single flag for conflict set -- purposes, thereby treating them all as interdependent. -- -- If we ever move to a more clever algorithm again, then the line above -- needs to be looked at very carefully, and probably be replaced by -- more systematically computed flag dependency information. -- | Datatype that encodes what to build next data BuildType = Goals -- ^ build a goal choice node | OneGoal (OpenGoal ()) -- ^ build a node for this goal | Instance QPN I PInfo QGoalReason -- ^ build a tree for a concrete instance deriving Show build :: BuildState -> Tree QGoalReason build = ana go where go :: BuildState -> TreeF QGoalReason BuildState -- If we have a choice between many goals, we just record the choice in -- the tree. We select each open goal in turn, and before we descend, remove -- it from the queue of open goals. go bs@(BS { rdeps = rds, open = gs, next = Goals }) | P.null gs = DoneF rds | otherwise = GoalChoiceF (P.mapWithKey (\ g (_sc, gs') -> bs { next = OneGoal g, open = gs' }) (P.splits gs)) -- If we have already picked a goal, then the choice depends on the kind -- of goal. -- -- For a package, we look up the instances available in the global info, -- and then handle each instance in turn. go (BS { index = _ , next = OneGoal (OpenGoal (Simple (Ext _ ) _) _ ) }) = error "Distribution.Client.Dependency.Modular.Builder: build.go called with Ext goal" go (BS { index = _ , next = OneGoal (OpenGoal (Simple (Lang _ ) _) _ ) }) = error "Distribution.Client.Dependency.Modular.Builder: build.go called with Lang goal" go (BS { index = _ , next = OneGoal (OpenGoal (Simple (Pkg _ _ ) _) _ ) }) = error "Distribution.Client.Dependency.Modular.Builder: build.go called with Pkg goal" go bs@(BS { index = idx, next = OneGoal (OpenGoal (Simple (Dep qpn@(Q _ pn) _) _) gr) }) = -- If the package does not exist in the index, we construct an emty PChoiceF node for it -- After all, we have no choices here. Alternatively, we could immediately construct -- a Fail node here, but that would complicate the construction of conflict sets. -- We will probably want to give this case special treatment when generating error -- messages though. case M.lookup pn idx of Nothing -> PChoiceF qpn gr (P.fromList []) Just pis -> PChoiceF qpn gr (P.fromList (L.map (\ (i, info) -> (POption i Nothing, bs { next = Instance qpn i info gr })) (M.toList pis))) -- TODO: data structure conversion is rather ugly here -- For a flag, we create only two subtrees, and we create them in the order -- that is indicated by the flag default. -- -- TODO: Should we include the flag default in the tree? go bs@(BS { next = OneGoal (OpenGoal (Flagged qfn@(FN (PI qpn _) _) (FInfo b m w) t f) gr) }) = FChoiceF qfn gr (w || trivial) m (P.fromList (reorder b [(True, (extendOpen qpn (L.map (flip OpenGoal (FDependency qfn True )) t) bs) { next = Goals }), (False, (extendOpen qpn (L.map (flip OpenGoal (FDependency qfn False)) f) bs) { next = Goals })])) where reorder True = id reorder False = reverse trivial = L.null t && L.null f -- For a stanza, we also create only two subtrees. The order is initially -- False, True. This can be changed later by constraints (force enabling -- the stanza by replacing the False branch with failure) or preferences -- (try enabling the stanza if possible by moving the True branch first). go bs@(BS { next = OneGoal (OpenGoal (Stanza qsn@(SN (PI qpn _) _) t) gr) }) = SChoiceF qsn gr trivial (P.fromList [(False, bs { next = Goals }), (True, (extendOpen qpn (L.map (flip OpenGoal (SDependency qsn)) t) bs) { next = Goals })]) where trivial = L.null t -- For a particular instance, we change the state: we update the scope, -- and furthermore we update the set of goals. -- -- TODO: We could inline this above. go bs@(BS { next = Instance qpn i (PInfo fdeps fdefs _) _gr }) = go ((scopedExtendOpen qpn i (PDependency (PI qpn i)) fdeps fdefs bs) { next = Goals }) -- | Interface to the tree builder. Just takes an index and a list of package names, -- and computes the initial state and then the tree from there. buildTree :: Index -> Bool -> [PN] -> Tree QGoalReason buildTree idx ind igs = build BS { index = idx , rdeps = M.fromList (L.map (\ qpn -> (qpn, [])) qpns) , open = P.fromList (L.map (\ qpn -> (topLevelGoal qpn, ())) qpns) , next = Goals , qualifyOptions = defaultQualifyOptions idx } where topLevelGoal qpn = OpenGoal (Simple (Dep qpn (Constrained [])) ()) UserGoal qpns | ind = makeIndependent igs | otherwise = L.map (Q (PP DefaultNamespace Unqualified)) igs
tolysz/prepare-ghcjs
spec-lts8/cabal/cabal-install/Distribution/Client/Dependency/Modular/Builder.hs
bsd-3-clause
10,016
0
22
2,721
2,233
1,228
1,005
89
10
{-# OPTIONS_GHC -fno-implicit-prelude #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Either -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : portable -- -- The Either type, and associated operations. -- ----------------------------------------------------------------------------- module Data.Either ( Either(..), either -- :: (a -> c) -> (b -> c) -> Either a b -> c ) where #ifdef __GLASGOW_HASKELL__ import GHC.Base {-| The 'Either' type represents values with two possibilities: a value of type @'Either' a b@ is either @'Left' a@ or @'Right' b@. The 'Either' type is sometimes used to represent a value which is either correct or an error; by convention, the 'Left' constructor is used to hold an error value and the 'Right' constructor is used to hold a correct value (mnemonic: \"right\" also means \"correct\"). -} data Either a b = Left a | Right b deriving (Eq, Ord ) -- | Case analysis for the 'Either' type. -- If the value is @'Left' a@, apply the first function to @a@; -- if it is @'Right' b@, apply the second function to @b@. either :: (a -> c) -> (b -> c) -> Either a b -> c either f _ (Left x) = f x either _ g (Right y) = g y #endif /* __GLASGOW_HASKELL__ */
FranklinChen/hugs98-plus-Sep2006
packages/base/Data/Either.hs
bsd-3-clause
1,447
2
8
292
151
92
59
4
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | -- Copyright : (c) 2011 Simon Meier -- License : GPL v3 (see LICENSE) -- -- Maintainer : Simon Meier <iridcode@gmail.com> -- Portability : portable -- -- Pretty-printing with support for HTML markup and proper HTML escaping. module Text.PrettyPrint.Html ( -- * HtmlDocument class HtmlDocument(..) , withTag , withTagNonEmpty , closedTag , module Text.PrettyPrint.Highlight -- * HtmlDoc: adding HTML markup , HtmlDoc , htmlDoc , getHtmlDoc , postprocessHtmlDoc , renderHtmlDoc -- * NoHtmlDoc: ignoring HTML markup , noHtmlDoc , getNoHtmlDoc ) where import Data.Char (isSpace) -- import Data.Traversable (sequenceA) -- import Data.Monoid import Control.Arrow (first) import Control.Applicative import Control.Monad.Identity import Control.DeepSeq import Text.PrettyPrint.Class import Text.PrettyPrint.Highlight ------------------------------------------------------------------------------ -- HtmlDocument class ------------------------------------------------------------------------------ class HighlightDocument d => HtmlDocument d where -- | @unescapedText str@ converts the 'String' @str@ to a document without -- performing any escaping. unescapedText :: String -> d -- | @unescapedZeroWidthText str@ converts the 'String' @str@ to a document -- with zero width without performing any escaping. unescapedZeroWidthText :: String -> d -- | @withTag tag attrs inner@ adds the tag @tag@ with the attributes -- @attrs@ around the @inner@ document. withTag :: HtmlDocument d => String -> [(String,String)] -> d -> d withTag tag attrs inner = unescapedZeroWidthText open <> inner <> unescapedZeroWidthText close where open = "<" ++ tag ++ concatMap attribute attrs ++ ">" close = "</" ++ tag ++ ">" -- | @closedTag tag attrs@ builds the closed tag @tag@ with the attributes -- @attrs@; e.g., -- -- > closedTag "img" "href" "here" = HtmlDoc (text "<img href=\"here\"/>) -- closedTag :: HtmlDocument d => String -> [(String,String)] -> d closedTag tag attrs = unescapedZeroWidthText $ "<" ++ tag ++ concatMap attribute attrs ++ "/>" -- | @withTagNonEmpty tag attrs inner@ adds the tag @tag@ with the attributes -- @attrs@ around the @inner@ document iff @inner@ is a non-empty document. withTagNonEmpty :: HtmlDocument d => String -> [(String,String)] -> d -> d withTagNonEmpty tag attrs inner = caseEmptyDoc inner emptyDoc $ withTag tag attrs inner -- | Render an attribute. attribute :: (String, String) -> String attribute (key,value) = " " ++ key ++ "=\"" ++ escapeHtmlEntities value ++ "\"" ------------------------------------------------------------------------------ -- HtmlDoc: adding HTML markup ------------------------------------------------------------------------------ -- | A 'Document' transformer that adds proper HTML escaping. newtype HtmlDoc d = HtmlDoc { getHtmlDoc :: d } deriving( Monoid, Semigroup ) -- | Wrap a document such that HTML markup can be added without disturbing the -- layout. htmlDoc :: d -> HtmlDoc d htmlDoc = HtmlDoc instance NFData d => NFData (HtmlDoc d) where rnf = rnf . getHtmlDoc instance Document d => Document (HtmlDoc d) where char = HtmlDoc . text . escapeHtmlEntities . return text = HtmlDoc . text . escapeHtmlEntities zeroWidthText = HtmlDoc . zeroWidthText . escapeHtmlEntities HtmlDoc d1 <-> HtmlDoc d2 = HtmlDoc $ d1 <-> d2 hcat = HtmlDoc . hcat . map getHtmlDoc hsep = HtmlDoc . hsep . map getHtmlDoc HtmlDoc d1 $$ HtmlDoc d2 = HtmlDoc $ d1 $$ d2 HtmlDoc d1 $-$ HtmlDoc d2 = HtmlDoc $ d1 $-$ d2 vcat = HtmlDoc . vcat . map getHtmlDoc sep = HtmlDoc . sep . map getHtmlDoc cat = HtmlDoc . cat . map getHtmlDoc fsep = HtmlDoc . fsep . map getHtmlDoc fcat = HtmlDoc . fcat . map getHtmlDoc nest i = HtmlDoc . nest i . getHtmlDoc caseEmptyDoc (HtmlDoc d1) (HtmlDoc d2) (HtmlDoc d3) = HtmlDoc $ caseEmptyDoc d1 d2 d3 instance Document d => HtmlDocument (HtmlDoc d) where unescapedText = HtmlDoc . text unescapedZeroWidthText = HtmlDoc . zeroWidthText instance Document d => HighlightDocument (HtmlDoc d) where highlight hlStyle = withTag "span" [("class", hlClass hlStyle)] where hlClass Comment = "hl_comment" hlClass Keyword = "hl_keyword" hlClass Operator = "hl_operator" -- | Escape HTML entities in a string -- -- Copied from 'blaze-html'. escapeHtmlEntities :: String -- ^ String to escape -> String -- ^ Resulting string escapeHtmlEntities [] = [] escapeHtmlEntities (c:cs) = case c of '<' -> "&lt;" ++ escapeHtmlEntities cs '>' -> "&gt;" ++ escapeHtmlEntities cs '&' -> "&amp;" ++ escapeHtmlEntities cs '"' -> "&quot;" ++ escapeHtmlEntities cs '\'' -> "&#39;" ++ escapeHtmlEntities cs x -> x : escapeHtmlEntities cs -- | @renderHtmlDoc = 'postprocessHtmlDoc' . 'render' . 'getHtmlDoc'@ renderHtmlDoc :: HtmlDoc Doc -> String renderHtmlDoc = postprocessHtmlDoc . render . getHtmlDoc -- | @postprocessHtmlDoc cs@ converts the line-breaks of @cs@ to @<br>@ tags and -- the prefixed spaces in every line of @cs@ by non-breaing HTML spaces @&nbsp;@. postprocessHtmlDoc :: String -> String postprocessHtmlDoc = unlines . map (addBreak . indent) . lines where addBreak = (++"<br/>") indent = uncurry (++) . (first $ concatMap (const "&nbsp;")) . span isSpace ------------------------------------------------------------------------------ -- NoHtmlDoc: ignoring HTML markup ------------------------------------------------------------------------------ -- | A 'Document' transformer that ignores all 'HtmlDocument' specific methods. newtype NoHtmlDoc d = NoHtmlDoc { unNoHtmlDoc :: Identity d } deriving( Functor, Applicative ) -- | Wrap a document such that all 'HtmlDocument' specific methods are ignored. noHtmlDoc :: d -> NoHtmlDoc d noHtmlDoc = NoHtmlDoc . Identity -- | Extract the wrapped document. getNoHtmlDoc :: NoHtmlDoc d -> d getNoHtmlDoc = runIdentity . unNoHtmlDoc instance NFData d => NFData (NoHtmlDoc d) where rnf = rnf . getNoHtmlDoc instance Semigroup d => Semigroup (NoHtmlDoc d) where (<>) = liftA2 (<>) instance Monoid d => Monoid (NoHtmlDoc d) where mempty = pure mempty instance Document d => Document (NoHtmlDoc d) where char = pure . char text = pure . text zeroWidthText = pure . zeroWidthText (<->) = liftA2 (<->) hcat = liftA hcat . sequenceA hsep = liftA hsep . sequenceA ($$) = liftA2 ($$) ($-$) = liftA2 ($-$) vcat = liftA vcat . sequenceA sep = liftA sep . sequenceA cat = liftA cat . sequenceA fsep = liftA fsep . sequenceA fcat = liftA fcat . sequenceA nest = liftA2 nest . pure caseEmptyDoc = liftA3 caseEmptyDoc instance Document d => HtmlDocument (NoHtmlDoc d) where unescapedText = noHtmlDoc . text unescapedZeroWidthText = noHtmlDoc . zeroWidthText instance Document d => HighlightDocument (NoHtmlDoc d) where highlight _ = id
rsasse/tamarin-prover
lib/utils/src/Text/PrettyPrint/Html.hs
gpl-3.0
7,106
0
13
1,442
1,586
852
734
119
6
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="pl-PL"> <title>AJAX Spider | ZAP Extensions</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Zawartość</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Szukaj</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Ulubione</label> <type>javax.help.FavoritesView</type> </view> </helpset>
rnehra01/zap-extensions
src/org/zaproxy/zap/extension/spiderAjax/resources/help_pl_PL/helpset_pl_PL.hs
apache-2.0
977
80
66
160
420
212
208
-1
-1
{-# LANGUAGE OverloadedStrings, RecordWildCards, EmptyDataDecls, FlexibleInstances, FlexibleContexts #-} module Database.Redis.PubSub ( publish, pubSub, Message(..), PubSub(), subscribe, unsubscribe, psubscribe, punsubscribe ) where import Control.Applicative import Control.Monad import Control.Monad.State import Data.ByteString.Char8 (ByteString) import Data.Monoid import qualified Database.Redis.Core as Core import Database.Redis.Protocol (Reply(..)) import Database.Redis.Types -- |While in PubSub mode, we keep track of the number of current subscriptions -- (as reported by Redis replies) and the number of messages we expect to -- receive after a SUBSCRIBE or PSUBSCRIBE command. We can safely leave the -- PubSub mode when both these numbers are zero. data PubSubState = PubSubState { subCnt, pending :: Int } modifyPending :: (MonadState PubSubState m) => (Int -> Int) -> m () modifyPending f = modify $ \s -> s{ pending = f (pending s) } putSubCnt :: (MonadState PubSubState m) => Int -> m () putSubCnt n = modify $ \s -> s{ subCnt = n } data Subscribe data Unsubscribe data Channel data Pattern -- |Encapsulates subscription changes. Use 'subscribe', 'unsubscribe', -- 'psubscribe', 'punsubscribe' or 'mempty' to construct a value. Combine -- values by using the 'Monoid' interface, i.e. 'mappend' and 'mconcat'. data PubSub = PubSub { subs :: Cmd Subscribe Channel , unsubs :: Cmd Unsubscribe Channel , psubs :: Cmd Subscribe Pattern , punsubs :: Cmd Unsubscribe Pattern } deriving (Eq) instance Monoid PubSub where mempty = PubSub mempty mempty mempty mempty mappend p1 p2 = PubSub { subs = subs p1 `mappend` subs p2 , unsubs = unsubs p1 `mappend` unsubs p2 , psubs = psubs p1 `mappend` psubs p2 , punsubs = punsubs p1 `mappend` punsubs p2 } data Cmd a b = DoNothing | Cmd { changes :: [ByteString] } deriving (Eq) instance Monoid (Cmd Subscribe a) where mempty = DoNothing mappend DoNothing x = x mappend x DoNothing = x mappend (Cmd xs) (Cmd ys) = Cmd (xs ++ ys) instance Monoid (Cmd Unsubscribe a) where mempty = DoNothing mappend DoNothing x = x mappend x DoNothing = x -- empty subscription list => unsubscribe all channels and patterns mappend (Cmd []) _ = Cmd [] mappend _ (Cmd []) = Cmd [] mappend (Cmd xs) (Cmd ys) = Cmd (xs ++ ys) class Command a where redisCmd :: a -> ByteString updatePending :: a -> Int -> Int sendCmd :: (Command (Cmd a b)) => Cmd a b -> StateT PubSubState Core.Redis () sendCmd DoNothing = return () sendCmd cmd = do lift $ Core.send (redisCmd cmd : changes cmd) modifyPending (updatePending cmd) plusChangeCnt :: Cmd a b -> Int -> Int plusChangeCnt DoNothing = id plusChangeCnt (Cmd cs) = (+ length cs) instance Command (Cmd Subscribe Channel) where redisCmd = const "SUBSCRIBE" updatePending = plusChangeCnt instance Command (Cmd Subscribe Pattern) where redisCmd = const "PSUBSCRIBE" updatePending = plusChangeCnt instance Command (Cmd Unsubscribe Channel) where redisCmd = const "UNSUBSCRIBE" updatePending = const id instance Command (Cmd Unsubscribe Pattern) where redisCmd = const "PUNSUBSCRIBE" updatePending = const id data Message = Message { msgChannel, msgMessage :: ByteString} | PMessage { msgPattern, msgChannel, msgMessage :: ByteString} deriving (Show) data PubSubReply = Subscribed | Unsubscribed Int | Msg Message ------------------------------------------------------------------------------ -- Public Interface -- -- |Post a message to a channel (<http://redis.io/commands/publish>). publish :: (Core.RedisCtx m f) => ByteString -- ^ channel -> ByteString -- ^ message -> m (f Integer) publish channel message = Core.sendRequest ["PUBLISH", channel, message] -- |Listen for messages published to the given channels -- (<http://redis.io/commands/subscribe>). subscribe :: [ByteString] -- ^ channel -> PubSub subscribe [] = mempty subscribe cs = mempty{ subs = Cmd cs } -- |Stop listening for messages posted to the given channels -- (<http://redis.io/commands/unsubscribe>). unsubscribe :: [ByteString] -- ^ channel -> PubSub unsubscribe cs = mempty{ unsubs = Cmd cs } -- |Listen for messages published to channels matching the given patterns -- (<http://redis.io/commands/psubscribe>). psubscribe :: [ByteString] -- ^ pattern -> PubSub psubscribe [] = mempty psubscribe ps = mempty{ psubs = Cmd ps } -- |Stop listening for messages posted to channels matching the given patterns -- (<http://redis.io/commands/punsubscribe>). punsubscribe :: [ByteString] -- ^ pattern -> PubSub punsubscribe ps = mempty{ punsubs = Cmd ps } -- |Listens to published messages on subscribed channels and channels matching -- the subscribed patterns. For documentation on the semantics of Redis -- Pub\/Sub see <http://redis.io/topics/pubsub>. -- -- The given callback function is called for each received message. -- Subscription changes are triggered by the returned 'PubSub'. To keep -- subscriptions unchanged, the callback can return 'mempty'. -- -- Example: Subscribe to the \"news\" channel indefinitely. -- -- @ -- pubSub (subscribe [\"news\"]) $ \\msg -> do -- putStrLn $ \"Message from \" ++ show (msgChannel msg) -- return mempty -- @ -- -- Example: Receive a single message from the \"chat\" channel. -- -- @ -- pubSub (subscribe [\"chat\"]) $ \\msg -> do -- putStrLn $ \"Message from \" ++ show (msgChannel msg) -- return $ unsubscribe [\"chat\"] -- @ -- pubSub :: PubSub -- ^ Initial subscriptions. -> (Message -> IO PubSub) -- ^ Callback function. -> Core.Redis () pubSub initial callback | initial == mempty = return () | otherwise = evalStateT (send initial) (PubSubState 0 0) where send :: PubSub -> StateT PubSubState Core.Redis () send PubSub{..} = do sendCmd subs sendCmd unsubs sendCmd psubs sendCmd punsubs recv recv :: StateT PubSubState Core.Redis () recv = do reply <- lift Core.recv case decodeMsg reply of Msg msg -> liftIO (callback msg) >>= send Subscribed -> modifyPending (subtract 1) >> recv Unsubscribed n -> do putSubCnt n PubSubState{..} <- get unless (subCnt == 0 && pending == 0) recv ------------------------------------------------------------------------------ -- Helpers -- decodeMsg :: Reply -> PubSubReply decodeMsg r@(MultiBulk (Just (r0:r1:r2:rs))) = either (errMsg r) id $ do kind <- decode r0 case kind :: ByteString of "message" -> Msg <$> decodeMessage "pmessage" -> Msg <$> decodePMessage "subscribe" -> return Subscribed "psubscribe" -> return Subscribed "unsubscribe" -> Unsubscribed <$> decodeCnt "punsubscribe" -> Unsubscribed <$> decodeCnt _ -> errMsg r where decodeMessage = Message <$> decode r1 <*> decode r2 decodePMessage = PMessage <$> decode r1 <*> decode r2 <*> decode (head rs) decodeCnt = fromInteger <$> decode r2 decodeMsg r = errMsg r errMsg :: Reply -> a errMsg r = error $ "Hedis: expected pub/sub-message but got: " ++ show r
MaxGabriel/hedis
src/Database/Redis/PubSub.hs
bsd-3-clause
7,653
0
18
1,947
1,784
955
829
-1
-1
-- A simple let expression, to ensure the layout is detected module Layout.LetExpr where foo = let x = 1 y = 2 in x + y
RefactoringTools/HaRe
test/testdata/Layout/LetExpr.hs
bsd-3-clause
139
0
8
46
32
18
14
4
1
{-# LANGUAGE Unsafe #-} {-# LANGUAGE CPP #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.ST.Imp -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (requires universal quantification for runST) -- -- This library provides support for /strict/ state threads, as -- described in the PLDI \'94 paper by John Launchbury and Simon Peyton -- Jones /Lazy Functional State Threads/. -- ----------------------------------------------------------------------------- -- #hide module Control.Monad.ST.Imp ( -- * The 'ST' Monad ST, -- abstract, instance of Functor, Monad, Typeable. runST, -- :: (forall s. ST s a) -> a fixST, -- :: (a -> ST s a) -> ST s a -- * Converting 'ST' to 'IO' RealWorld, -- abstract stToIO, -- :: ST RealWorld a -> IO a -- * Unsafe operations unsafeInterleaveST, -- :: ST s a -> ST s a unsafeIOToST, -- :: IO a -> ST s a unsafeSTToIO -- :: ST s a -> IO a ) where #if defined(__GLASGOW_HASKELL__) import Control.Monad.Fix () #else import Control.Monad.Fix #endif #include "Typeable.h" #if defined(__GLASGOW_HASKELL__) import GHC.ST ( ST, runST, fixST, unsafeInterleaveST ) import GHC.Base ( RealWorld ) import GHC.IO ( stToIO, unsafeIOToST, unsafeSTToIO ) #elif defined(__HUGS__) import Data.Typeable import Hugs.ST import qualified Hugs.LazyST as LazyST #endif #if defined(__HUGS__) INSTANCE_TYPEABLE2(ST,sTTc,"ST") INSTANCE_TYPEABLE0(RealWorld,realWorldTc,"RealWorld") fixST :: (a -> ST s a) -> ST s a fixST f = LazyST.lazyToStrictST (LazyST.fixST (LazyST.strictToLazyST . f)) unsafeInterleaveST :: ST s a -> ST s a unsafeInterleaveST = LazyST.lazyToStrictST . LazyST.unsafeInterleaveST . LazyST.strictToLazyST #endif #if !defined(__GLASGOW_HASKELL__) instance MonadFix (ST s) where mfix = fixST #endif
mightymoose/liquidhaskell
benchmarks/base-4.5.1.0/Control/Monad/ST/Imp.hs
bsd-3-clause
2,219
0
10
524
272
171
101
15
0
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="zh-CN"> <title>AJAX Spider | ZAP Extensions</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>搜索</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
msrader/zap-extensions
src/org/zaproxy/zap/extension/spiderAjax/resources/help_zh_CN/helpset_zh_CN.hs
apache-2.0
974
82
65
160
413
209
204
-1
-1
-- | This module defines a generator for @getopt@ based command -- line argument parsing. Each option is associated with arbitrary -- Python code that will perform side effects, usually by setting some -- global variables. module Futhark.CodeGen.Backends.GenericPython.Options ( Option (..) , OptionArgument (..) , generateOptionParser ) where import Futhark.CodeGen.Backends.GenericPython.AST -- | Specification if a single command line option. The option must -- have a long name, and may also have a short name. -- -- When the statement is being executed, the argument (if any) will be -- stored in the variable @optarg@. data Option = Option { optionLongName :: String , optionShortName :: Maybe Char , optionArgument :: OptionArgument , optionAction :: [PyStmt] } -- | Whether an option accepts an argument. data OptionArgument = NoArgument | RequiredArgument | OptionalArgument -- | Generate option parsing code that accepts the given command line options. Will read from @sys.argv@. -- -- If option parsing fails for any reason, the entire process will -- terminate with error code 1. generateOptionParser :: [Option] -> [PyStmt] generateOptionParser options = [Assign (Var "parser") (Call (Var "argparse.ArgumentParser") [ArgKeyword "description" $ String "A compiled Futhark program."])] ++ map parseOption options ++ [Assign (Var "parser_result") $ Call (Var "vars") [Arg $ Call (Var "parser.parse_args") [Arg $ Var "sys.argv[1:]"]]] ++ map executeOption options where parseOption option = Exp $ Call (Var "parser.add_argument") $ map (Arg . String) name_args ++ argument_args where name_args = maybe id ((:) . ('-':) . (:[])) (optionShortName option) ["--" ++ optionLongName option] argument_args = case optionArgument option of RequiredArgument -> [ArgKeyword "action" (String "append"), ArgKeyword "default" $ List []] NoArgument -> [ArgKeyword "action" (String "append_const"), ArgKeyword "default" $ List [], ArgKeyword "const" None] OptionalArgument -> [ArgKeyword "action" (String "append"), ArgKeyword "default" $ List [], ArgKeyword "nargs" $ String "?"] executeOption option = For "optarg" (Index (Var "parser_result") $ IdxExp $ String $ fieldName option) $ optionAction option fieldName = map escape . optionLongName where escape '-' = '_' escape c = c
ihc/futhark
src/Futhark/CodeGen/Backends/GenericPython/Options.hs
isc
2,851
0
15
904
556
298
258
46
4
----------------------------------------------------------------------------- -- -- Module : SGC.Object.SomeObject -- Copyright : -- License : MIT -- -- Maintainer : -- Stability : -- Portability : -- -- | -- {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} module SGC.Object.SomeObject( ObjectValueType(..), Const, Var , ObjectHas, Has, NoCtx , SomeObject(..), HasConstraints , CreateSomeObject(..) , withObjectBase, withObject -- * Internal , MergeConstraints, MergeConstraints', ValueForEach ) where import SGC.Object.Definitions import TypeNum.TypeFunctions ( type (++) ) import GHC.Exts (Constraint) ----------------------------------------------------------------------------- data ObjectValueType = Consts | Vars | Any type Const = Consts type Var = Vars type ObjectHas obj m (t :: ObjectValueType) (ks :: [*]) = MergeConstraints (ValueForEach t obj ks m) type Has (t :: ObjectValueType) (ks :: [*]) = '(t, ks) class NoCtx a instance NoCtx a ----------------------------------------------------------------------------- data SomeObject (baseC :: * -> Constraint) m (has :: [(ObjectValueType, [*])]) = forall obj base . ( HasConstraints obj m has, baseC base ) => SomeObject obj (obj -> base) class CreateSomeObject obj base | obj -> base where someObject :: (HasConstraints obj m has, baseC base) => obj -> SomeObject baseC m has ----------------------------------------------------------------------------- withObject :: (forall obj . HasConstraints obj m has => obj -> r) -> SomeObject c m has -> r withObject f (SomeObject obj _) = f obj withObjectBase :: (forall base . c base => base -> r) -> SomeObject c m has -> r withObjectBase f (SomeObject obj getBase) = f $ getBase obj ----------------------------------------------------------------------------- type family MergeConstraints (cs :: [Constraint]) :: Constraint where MergeConstraints cs = MergeConstraints' cs () type family MergeConstraints' (cs :: [Constraint]) (acc :: Constraint) :: Constraint where MergeConstraints' (c ': cs) acc = (c, acc) MergeConstraints' '[] acc = acc type family ValueForEach (t :: ObjectValueType) obj (ks :: [*]) m :: [Constraint] where ValueForEach t obj '[] m = '[] ValueForEach t obj (k ': ks) m = ValueConstraint t obj k m ': ValueForEach t obj ks m type family ValueConstraint (t :: ObjectValueType) obj k m :: Constraint where ValueConstraint Consts obj k m = ObjectConst obj k ValueConstraint Vars obj k m = ObjectVar obj k m ValueConstraint Any obj k m = ObjectValue obj k m type HasConstraints obj m has = MergeConstraints (HasConstraints' obj m has) type family HasConstraints' obj m (has :: [(ObjectValueType, [*])]) :: [Constraint] where HasConstraints' obj m '[] = '[] HasConstraints' obj m ('(t, ks) ': tks) = ValueForEach t obj ks m ++ HasConstraints' obj m tks -----------------------------------------------------------------------------
fehu/hsgc
SGC/Object/SomeObject.hs
mit
3,296
0
10
697
884
519
365
-1
-1
module Unison.Test.BlockStore.MemBlockStore where import System.Random import Test.QuickCheck import Test.Tasty import Test.Tasty.HUnit import Unison.Runtime.Address import Unison.Test.BlockStore import qualified Control.Concurrent.MVar as MVar import qualified Data.IORef as IORef import qualified Unison.BlockStore.MemBlockStore as MBS ioTests :: IO TestTree ioTests = do store <- MBS.make' makeRandomAddress makeAddress pure . testGroup "MemBlockStore" $ makeExhaustiveCases store justQuickcheck :: IO [Property] justQuickcheck = do store <- MBS.make' makeRandomAddress makeAddress pure [ prop_lastKeyIsValid store , prop_SomeoneHasAValidKey store , prop_allSeriesHashesAreValid store]
nightscape/platform
node/tests/Unison/Test/BlockStore/MemBlockStore.hs
mit
714
0
9
96
165
93
72
20
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoMonomorphismRestriction #-} module KV where import qualified Solar.Data.KV as K import System.IO.Unsafe(unsafePerformIO) import Data.Time.Clock import Data.Text(pack) import Data.Typeable import Data.Serialize as S import GHC.Generics as G import Solar.Data.KV.Cereal import Solar.Storage.FS as FS import Solar.Storage as St import Data.Map as Map import qualified Data.ByteString.Lazy.UTF8 as U import Text.Read(readMaybe) import qualified Data.ByteString.Lazy as BL data Color = Red | Green | Blue | Yellow deriving (Show, Read, Typeable, Generic) data Vehicle = Car | Truck | Semi | Van deriving (Show, Read, Typeable, Generic) data Ponies = Fluttershy | TwilightSparkle | Rarity | Applejack | PinkiePie | RainbowDash deriving (Show, Read, Typeable, Generic) data Forum n r c = Forum r deriving (Show, Typeable, Generic, Read) instance Serialize Ponies where instance Serialize Vehicle where instance Serialize Color where instance (Serialize r) => Serialize (Forum n r c) where time = unsafePerformIO $ getCurrentTime ident = K.KVIdentifier Red (pack "Hai") ident2 = K.KVIdentifier Blue (pack "Potatoes") arel = K.KVLink ident2 [Car, Van] [Rarity] K.In time False met = K.KVMeta ident [RainbowDash, Fluttershy] [arel] time time time False type TestKV = K.KV Color Vehicle Ponies Forum K.KVNoCache kv :: TestKV kv = K.KV met (Forum Truck) K.kvNoCache kvToBS :: (Show n, Show r, Show c, Show (d n r c), Show (c' n r c)) => K.KV n r c d c' -> BL.ByteString kvToBS kv = U.fromString $ show kv kvFromBS :: (Read n, Read r, Read c, Read (d n r c), Read (c' n r c)) => BL.ByteString -> Maybe (K.KV n r c d c') kvFromBS b = readMaybe $ U.toString $ b fs = FSMethod { fsExt = "txt" , fsRead = kvFromBS , fsWrite = kvToBS } path = KFilePath "/tmp" cont = noContext ~+=: path
Cordite-Studios/solar
playground/KV.hs
mit
2,001
0
10
387
707
400
307
55
1
module Food ( FoodType (..) , Food (..) , food ) where -------------------- -- Global Imports -- import Prelude hiding ((.)) import System.Random import Control.Wire import Linear.V2 ------------------- -- Local Imports -- import Assets import Config import Render ---------- -- Code -- -- | The types of food. data FoodType = Apple | Cherry | Lemon | Mouse -- | An enum type to convert between ints and @'FoodType'@s. instance Enum FoodType where fromEnum Apple = 0 fromEnum Cherry = 1 fromEnum Lemon = 2 fromEnum Mouse = 3 toEnum 0 = Apple toEnum 1 = Cherry toEnum 2 = Lemon toEnum 3 = Mouse toEnum n = error $ "Invalid index: " ++ show n -- | The position of the food. data Food = Food FoodType (V2 Int) -- | Rendering the Food. instance Renderable Food where render appinfo assets (Food t p) = renderTexturedQuad (textures assets ! toPath t) (shaders assets ! "game2d") appinfo (fmap realToFrac p * blockSize) (blockSize / 2) where toPath :: FoodType -> String toPath Apple = "apple.png" toPath Cherry = "cherry.png" toPath Lemon = "lemon.png" toPath Mouse = "mouse.png" -- | Generating a random @'FoodType'@. randomFoodType :: IO FoodType randomFoodType = do n <- randomRIO (0, 3) return $ toEnum n -- | Generating a random position. randomPosition :: IO (V2 Int) randomPosition = do x <- randomRIO (0, gridWidth) y <- randomRIO (0, gridHeight) return $ V2 x y -- | Generating a new piece of food. randomFood :: IO Food randomFood = do ft <- randomFoodType pos <- randomPosition return $ Food ft pos -- | The back end of the food. food' :: Food -> Wire s () IO Bool Food food' f = mkGenN $ \regen -> do f' <- if regen then randomFood else return f f' `seq` return (Right f, food' f') -- | The front-end of the food. food :: Wire s () IO Bool Food food = (mkGenN $ \_ -> do f <- randomFood f `seq` return (Right f, food' f)) . delay False
crockeo/netwire-vinyl
src/Food.hs
mit
2,166
0
14
664
616
326
290
63
2
module Ch10Types where import Prelude hiding (Bool) type Pos = (Int,Int) -- type synonym origin :: Pos origin = (0,0) left :: Pos -> Pos left (x,y) = (x-1,y) -- *Ch10Types> left (1,1) -- (0,1) ---------------------- type Pair a = (a,a) mult :: Pair Int -> Int mult (m,n) = m * n copy :: a -> Pair a copy x = (x,x) -- *Ch10Types> copy (1,1) -- ((1,1),(1,1)) -- *Ch10Types> mult (1,1) -- 1 -- type level value level ----------------------------------- -- Pair Int | pair a -- = | = -- (Int,Int) | (a,a) -- | -- type Pair a = | pair 13 -- = | = -- (a,a) | (13,13) -- | -- syntax | syntax -- of | of -- types | values -- functions on types thus resemble functions on values -- Erik predicts that by about now Haskell will have evolved into a fully dependent type language where types and terms are fully intertwined. -- copy function has type -- a -> (a,a) -- this dictates what the function will be. -- -- "Theorems for free" -- type declarations can be nested but are not recursive -- type Pos = (Int,Int) type Tran = Pos -> Pos -- however -- type Tree = (Int,[Tree]) -- wont compile -- ADT a new type defined interms of other types data Bool = False | True
HaskellForCats/HaskellForCats
MenaBeginning/Ch010/2014-0331Ch10Types.hs
mit
1,351
0
6
424
196
130
66
15
1