code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
{-# LANGUAGE ConstraintKinds #-} module Mem where import Control.Applicative import Data.Traversable import SplitEval memInt :: (Int -> a) -> (Int -> a) memInt f = (map f [0..] !!) memIntA :: (Applicative m) => (Int -> m a) -> m (Int -> a) memIntA f = (!!) <$> traverse f [0..] memIntS :: (Applicative n, MonadEval s n, Functor m, MonadSplit s m) => (Int -> n a) -> m (Int -> a) memIntS = evalS . memIntA
vladfi1/hs-misc
PFP/Mem.hs
Haskell
mit
416
{-# LANGUAGE CPP #-} module Stackage.Config where import Control.Monad (when, unless) import Control.Monad.Trans.Writer (Writer, execWriter, tell) import Data.Char (toLower) import qualified Data.Map as Map import Data.Maybe (fromMaybe) import Data.Set (fromList, singleton) import Distribution.Text (simpleParse) import Stackage.Types -- | Packages which are shipped with GHC but are not included in the -- Haskell Platform list of core packages. defaultExtraCore :: GhcMajorVersion -> Set PackageName defaultExtraCore _ = fromList $ map PackageName $ words "binary Win32 ghc-prim integer-gmp" -- | Test suites which are expected to fail for some reason. The test suite -- will still be run and logs kept, but a failure will not indicate an -- error in our package combination. defaultExpectedFailures :: GhcMajorVersion -> Bool -- ^ haskell platform -> Set PackageName defaultExpectedFailures ghcVer requireHP = execWriter $ do -- Requires an old version of WAI and Warp for tests add "HTTP" -- text and setenv have recursive dependencies in their tests, which -- cabal can't (yet) handle add "text" add "setenv" -- The version of GLUT included with the HP does not generate -- documentation correctly. add "GLUT" -- https://github.com/bos/statistics/issues/42 add "statistics" -- https://github.com/kazu-yamamoto/simple-sendfile/pull/10 add "simple-sendfile" -- http://hackage.haskell.org/trac/hackage/ticket/954 add "diagrams" -- https://github.com/fpco/stackage/issues/24 add "unix-time" -- With transformers 0.3, it doesn't provide any modules add "transformers-compat" -- Tests require shell script and are incompatible with sandboxed package -- databases add "HTF" -- https://github.com/simonmar/monad-par/issues/28 add "monad-par" -- Unfortunately network failures seem to happen haphazardly add "network" -- https://github.com/ekmett/hyphenation/issues/1 add "hyphenation" -- Test suite takes too long to run on some systems add "punycode" -- http://hub.darcs.net/stepcut/happstack/issue/1 add "happstack-server" -- Requires a Facebook app. add "fb" -- https://github.com/tibbe/hashable/issues/64 add "hashable" -- https://github.com/vincenthz/language-java/issues/10 add "language-java" add "threads" add "crypto-conduit" add "pandoc" add "language-ecmascript" add "hspec" add "alex" -- https://github.com/basvandijk/concurrent-extra/issues/ add "concurrent-extra" -- https://github.com/skogsbaer/xmlgen/issues/2 add "xmlgen" -- Something very strange going on with the test suite, I can't figure -- out how to fix it add "bson" -- Requires a locally running PostgreSQL server with appropriate users add "postgresql-simple" -- Missing files add "websockets" -- Some kind of Cabal bug when trying to run tests add "thyme" add "shake" -- https://github.com/jgm/pandoc-citeproc/issues/5 add "pandoc-citeproc" -- Problems with doctest and sandboxing add "warp" add "wai-logger" -- https://github.com/fpco/stackage/issues/163 add "hTalos" add "seqloc" -- https://github.com/bos/math-functions/issues/25 add "math-functions" -- FIXME the test suite fails fairly regularly in builds, though I haven't -- discovered why yet add "crypto-numbers" -- Test suite is currently failing regularly, needs to be worked out still. add "lens" -- Requires too old a version of test-framework add "time" -- No code included any more, therefore Haddock fails mapM_ add $ words =<< [ "comonad-transformers comonads-fd groupoids" , "profunctor-extras semigroupoid-extras" , "hamlet shakespeare-css shakespeare-i18n" , "shakespeare-js shakespeare-text" , "attoparsec-conduit blaze-builder-conduit http-client-conduit" , "network-conduit zlib-conduit http-client-multipart" , "wai-eventsource wai-test" , "hspec-discover" ] -- Cloud Haskell tests seem to be unreliable mapM_ add $ words =<< [ "distributed-process lockfree-queue network-transport-tcp" ] -- Pulls in monad-peel which does not compile when (ghcVer >= GhcMajorVersion 7 8) $ add "monad-control" -- https://github.com/fpco/stackage/issues/226 add "options" -- https://github.com/gtk2hs/gtk2hs/issues/36 add "glib" add "pango" -- https://github.com/acw/bytestring-progress/issues/3 add "bytestring-progress" -- Seems to require 32-bit functions add "nettle" -- Depends on a missing graphviz executable add "graphviz" -- https://github.com/silkapp/json-schema/issues/8 when (ghcVer <= GhcMajorVersion 7 6) $ add "json-schema" -- No AWS creds available add "aws" -- Not sure why... add "singletons" add "hspec2" add "hspec-wai" -- Requires too new a version of time when (ghcVer < GhcMajorVersion 7 8) $ add "cookie" -- https://github.com/fpco/stackage/issues/285 add "diagrams-haddock" add "scientific" add "json-schema" -- https://github.com/BioHaskell/octree/issues/4 add "Octree" -- No code until we upgrade to network 2.6 add "network-uri" -- https://github.com/goldfirere/th-desugar/issues/12 add "th-desugar" -- https://github.com/haskell/c2hs/issues/108 add "c2hs" -- https://github.com/jmillikin/haskell-filesystem/issues/3 add "system-filepath" -- For some unknown reason, doctest has trouble on GHC 7.6. This only -- happens during a Stackage test. -- -- See: http://www.reddit.com/r/haskell/comments/2go92u/beginner_error_messages_in_c_vs_haskell/cklaspk when (ghcVer == GhcMajorVersion 7 6) $ add "http-types" -- Requires a running webdriver server add "webdriver" add "webdriver-snoy" -- Weird conflicts with sandboxing add "ghc-mod" add "ghcid" -- Requires locally running server add "bloodhound" -- Requires PostgreSQL running add "postgresql-binary" add "hasql" add "hasql-postgres" -- https://github.com/gtk2hs/gtk2hs/issues/79 add "gio" add "gtk" -- Requires SAT solver and old QuickCheck add "ersatz" when (ghcVer == GhcMajorVersion 7 8 && requireHP) $ do -- https://github.com/vincenthz/hs-asn1/issues/11 add "asn1-encoding" -- https://github.com/vincenthz/hs-tls/issues/84 add "tls" add "x509" where add = tell . singleton . PackageName -- | List of packages for our stable Hackage. All dependencies will be -- included as well. Please indicate who will be maintaining the package -- via comments. defaultStablePackages :: GhcMajorVersion -> Bool -- ^ using haskell platform? -> Map PackageName (VersionRange, Maintainer) defaultStablePackages ghcVer requireHP = unPackageMap $ execWriter $ do when (ghcVer == GhcMajorVersion 7 8 && requireHP) haskellPlatform78 mapM_ (add "michael@snoyman.com") $ words =<< [ "yesod yesod-newsfeed yesod-sitemap yesod-static yesod-test yesod-bin" , "markdown mime-mail-ses" , "persistent persistent-template persistent-sqlite persistent-postgresql persistent-mysql" , "network-conduit-tls yackage warp-tls keter" , "process-conduit stm-conduit" , "classy-prelude-yesod yesod-fay yesod-eventsource wai-websockets" , "random-shuffle hebrew-time" , "bzlib-conduit case-insensitive" , "conduit-extra conduit-combinators yesod-websockets" , "cabal-src" , "yesod-auth-deskcom monadcryptorandom sphinx" , "yesod-gitrepo" ] -- https://github.com/fpco/stackage/issues/261 addRange "Michael Snoyman" "cabal-install" $ case () of () | ghcVer <= GhcMajorVersion 7 6 -> "< 1.17" | ghcVer <= GhcMajorVersion 7 8 -> "< 1.19" | otherwise -> "-any" mapM_ (add "FP Complete <michael@fpcomplete.com>") $ words =<< [ "web-fpco th-expand-syns configurator smtLib" , "fixed-list indents language-c pretty-class" , "csv-conduit cassava" , "async shelly thyme" , "hxt hxt-relaxng dimensional" , "cairo diagrams-cairo gtk2hs-buildtools" , "base16-bytestring convertible" , "compdata hybrid-vectors" , "executable-path formatting quandl-api" , "fgl hmatrix hmatrix-gsl" , "alex happy c2hs" , "fpco-api aws persistent-mongoDB" , "random-fu lhs2tex" , "Chart Chart-diagrams histogram-fill random-source" , "webdriver" , "foreign-store" , "statistics-linreg" -- https://github.com/Soostone/retry/issues/18 -- , "retry" ] when (ghcVer < GhcMajorVersion 7 8) $ do -- No GHC 7.8 support mapM_ (add "FP Complete <michael@fpcomplete.com>") $ words =<< [ "" -- too unreliable for the moment "distributed-process distributed-process-simplelocalnet" -- https://github.com/fpco/stackage/issues/295 --, "threepenny-gui unification-fd" ] addRange "FP Complete <michael@fpcomplete.com>" "compdata" "< 0.8" when (ghcVer >= GhcMajorVersion 7 8 && not requireHP) $ mapM_ (add "FP Complete <michael@fpcomplete.com>") $ words =<< [ "criterion" , "th-lift singletons th-desugar quickcheck-assertions" ] addRange "FP Complete <michael@fpcomplete.com>" "kure" "<= 2.4.10" mapM_ (add "Omari Norman <omari@smileystation.com>") $ words "barecheck rainbow rainbow-tests" when (ghcVer >= GhcMajorVersion 7 8 && not requireHP) $ mapM_ (add "Omari Norman <omari@smileystation.com>") $ words "quickpull" mapM_ (add "Neil Mitchell") $ words "hlint hoogle shake derive tagsoup cmdargs safe uniplate nsis js-jquery js-flot extra bake ghcid" mapM_ (add "Alan Zimmerman") $ words "hjsmin language-javascript" {- https://github.com/fpco/stackage/issues/320 when (ghcVer >= GhcMajorVersion 7 8 && not requireHP) $ mapM_ (add "Alfredo Di Napoli <alfredo.dinapoli@gmail.com>") $ words "mandrill" -} mapM_ (add "Jasper Van der Jeugt") $ words "blaze-html blaze-markup stylish-haskell" mapM_ (add "Antoine Latter") $ words "uuid byteorder" mapM_ (add "Philipp Middendorf <pmidden@secure.mailbox.org>") $ words "clock" mapM_ (add "Stefan Wehr <wehr@factisresearch.com>") $ words "HTF xmlgen stm-stats" when (ghcVer < GhcMajorVersion 7 8) $ add "Stefan Wehr <wehr@factisresearch.com>" "hscurses" mapM_ (add "Bart Massey <bart.massey+stackage@gmail.com>") $ words "parseargs" mapM_ (add "Vincent Hanquez") $ words =<< [ "bytedump certificate cipher-aes cipher-rc4 connection" , "cprng-aes cpu crypto-pubkey-types crypto-random-api cryptocipher" , "cryptohash hit language-java libgit pem siphash socks tls" , "tls-debug vhd language-java" ] mapM_ (add "Chris Done") $ words =<< [ "ace check-email freenect gd" , "hostname-validate ini lucid osdkeys pdfinfo" , "pure-io sourcemap frisby" -- https://github.com/nominolo/atto-lisp/issues/15 -- , "present" ] -- Requires older haddock currently when (ghcVer == GhcMajorVersion 7 8 && requireHP) $ mapM_ (add "Chris Done") $ words =<< [ "haskell-docs" ] -- https://github.com/jgoerzen/testpack/issues/10 when (ghcVer >= GhcMajorVersion 7 8 && not requireHP) $ mapM_ (add "Chris Done") $ words =<< [ "scrobble" ] -- Requires too new a process for GHC 7.6 when (ghcVer >= GhcMajorVersion 7 8) $ mapM_ (add "Chris Done") $ words =<< [ "shell-conduit" ] -- TODO: Add hindent and structured-haskell-mode once they've been ported to HSE 1.16. #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) -- Does not compile on Windows mapM_ (add "Vincent Hanquez") $ words "udbus xenstore" #endif when (ghcVer < GhcMajorVersion 7 8) $ mapM_ (add "Alberto G. Corona <agocorona@gmail.com>") $ words "RefSerialize TCache Workflow MFlow" mapM_ (add "Edward Kmett <ekmett@gmail.com>") $ words =<< [ "ad adjunctions bifunctors bound charset comonad comonad-transformers" , "comonads-fd compressed concurrent-supply constraints contravariant" , "distributive either eq free groupoids heaps hyphenation" , "integration intervals kan-extensions lca lens linear monadic-arrays machines" , "mtl profunctors profunctor-extras reducers reflection" , "semigroups semigroupoids semigroupoid-extras speculation tagged void" , "graphs monad-products monad-st wl-pprint-extras wl-pprint-terminfo" , "numeric-extras parsers pointed prelude-extras reducers" , "streams vector-instances" , "approximate bits bytes compensated exceptions fixed gl" , "half linear-accelerate log-domain" , "monad-products monad-st nats" , "ersatz" -- hyperloglog ] when (ghcVer < GhcMajorVersion 7 8) $ mapM_ (add "Edward Kmett <ekmett@gmail.com>") $ words =<< [ "categories comonad-extras recursion-schemes syb-extras" ] when (ghcVer >= GhcMajorVersion 7 8 && not requireHP) $ mapM_ (add "Edward Kmett <ekmett@gmail.com>") $ words =<< [ "lens-aeson quickpull zlib-lens" ] -- Temporary upper bound for some of the above packages addRange "Edward Kmett <ekmett@gmail.com>" "generic-deriving" "< 1.7" mapM_ (add "Andrew Farmer <afarmer@ittc.ku.edu>") $ words "scotty wai-middleware-static" mapM_ (add "Simon Hengel <sol@typeful.net>") $ words "hspec hspec-wai hspec-wai-json aeson-qq interpolate doctest base-compat" mapM_ (add "Mario Blazevic <blamario@yahoo.com>") $ words "monad-parallel monad-coroutine incremental-parser monoid-subclasses" mapM_ (add "Brent Yorgey <byorgey@gmail.com>") $ words =<< [ "monoid-extras dual-tree vector-space-points active force-layout" , "diagrams diagrams-contrib diagrams-core diagrams-lib diagrams-svg" , "diagrams-postscript haxr" , "BlogLiterately" , "MonadRandom" , "diagrams-builder diagrams-haddock BlogLiterately-diagrams" ] mapM_ (add "Vincent Berthoux <vincent.berthoux@gmail.com>") $ words "JuicyPixels" mapM_ (add "Patrick Brisbin") $ words "gravatar" -- https://github.com/fpco/stackage/issues/299 -- mapM_ (add "Paul Harper <benekastah@gmail.com>") $ words "yesod-auth-oauth2" mapM_ (add "Felipe Lessa <felipe.lessa@gmail.com>") $ words "esqueleto fb fb-persistent yesod-fb yesod-auth-fb" mapM_ (add "Alexander Altman <alexanderaltman@me.com>") $ words "base-unicode-symbols containers-unicode-symbols" if ghcVer >= GhcMajorVersion 7 8 then add "Ryan Newton <ryan.newton@alum.mit.edu>" "accelerate" else addRange "Ryan Newton <ryan.newton@alum.mit.edu>" "accelerate" "< 0.15" mapM_ (add "Dan Burton <danburton.email@gmail.com>") $ words =<< [ "basic-prelude composition io-memoize numbers rev-state runmemo" , "tardis lens-family-th" ] mapM_ (add "Daniel Díaz <dhelta.diaz@gmail.com>") $ words "HaTeX matrix" when (ghcVer >= GhcMajorVersion 7 8) $ mapM_ (add "Daniel Díaz <dhelta.diaz@gmail.com>") $ words "binary-list" mapM_ (add "Gabriel Gonzalez <Gabriel439@gmail.com>") ["pipes", "pipes-parse", "pipes-concurrency"] when (ghcVer >= GhcMajorVersion 7 8) $ mapM_ (add "Chris Allen <cma@bitemyapp.com>") ["bloodhound"] mapM_ (add "Adam Bergmark <adam@bergmark.nl>") $ words "fay fay-base fay-dom fay-jquery fay-text fay-uri snaplet-fay" when (ghcVer >= GhcMajorVersion 7 8 && not requireHP) $ mapM_ (add "Rodrigo Setti <rodrigosetti@gmail.com>") $ words "messagepack messagepack-rpc" mapM_ (add "Boris Lykah <lykahb@gmail.com>") $ words "groundhog groundhog-th groundhog-sqlite groundhog-postgresql groundhog-mysql" mapM_ (add "Janne Hellsten <jjhellst@gmail.com>") $ words "sqlite-simple" mapM_ (add "Michal J. Gajda") $ words "iterable Octree FenwickTree" -- https://github.com/BioHaskell/hPDB/issues/2 when (ghcVer >= GhcMajorVersion 7 8) $ do mapM_ (add "Michal J. Gajda") $ words "hPDB hPDB-examples" mapM_ (add "Roman Cheplyaka <roma@ro-che.info>") $ words =<< [ "smallcheck tasty tasty-smallcheck tasty-quickcheck tasty-hunit tasty-golden" , "traverse-with-class regex-applicative time-lens" , "haskell-names haskell-packages hse-cpp" ] mapM_ (add "George Giorgidze <giorgidze@gmail.com>") $ words "HCodecs YampaSynth" mapM_ (add "Phil Hargett <phil@haphazardhouse.net>") $ words "courier" #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) mapM_ (add "Aycan iRiCAN <iricanaycan@gmail.com>") $ words "hdaemonize hsyslog hweblib" #else mapM_ (add "Aycan iRiCAN <iricanaycan@gmail.com>") $ words "hweblib" #endif mapM_ (add "Joachim Breitner <mail@joachim-breitner.de>") $ words "circle-packing arbtt" when (ghcVer >= GhcMajorVersion 7 8) $ mapM_ (add "Joachim Breitner <mail@joachim-breitner.de>") $ words "ghc-heap-view" when (ghcVer < GhcMajorVersion 7 8) $ mapM_ (add "John Wiegley") $ words =<< [ "bindings-DSL github monad-extras numbers" ] mapM_ (add "Aditya Bhargava <adit@adit.io") $ words "HandsomeSoup" mapM_ (add "Clint Adams <clint@debian.org>") $ words "hOpenPGP openpgp-asciiarmor MusicBrainz DAV hopenpgp-tools" -- https://github.com/fpco/stackage/issues/160 mapM_ (add "Ketil Malde") $ words =<< [ "biocore biofasta biofastq biosff" , "blastxml bioace biophd" , "biopsl" -- https://github.com/ingolia/SamTools/issues/3 samtools , "seqloc bioalign BlastHTTP" -- The following have out-of-date dependencies currently -- biostockholm memexml RNAwolf -- , "Biobase BiobaseDotP BiobaseFR3D BiobaseInfernal BiobaseMAF" -- , "BiobaseTrainingData BiobaseTurner BiobaseXNA BiobaseVienna" -- , "BiobaseTypes BiobaseFasta" -- MC-Fold-DP ] -- https://github.com/fpco/stackage/issues/163 addRange "Michael Snoyman" "biophd" "< 0.0.6 || > 0.0.6" mapM_ (add "Silk <code@silk.co>") $ words =<< [ "arrow-list attoparsec-expr bumper code-builder fay-builder" , "hxt-pickle-utils multipart regular-xmlpickler" , "tostring uri-encode imagesize-conduit" ] when (ghcVer >= GhcMajorVersion 7 8 && not requireHP) $ do mapM_ (add "Silk <code@silk.co>") $ words =<< [ "aeson-utils generic-aeson json-schema" , "rest-client rest-core rest-gen rest-happstack rest-snap rest-stringmap" , "rest-types rest-wai tostring uri-encode imagesize-conduit" ] mapM_ (add "Simon Michael <simon@joyful.com>") $ words "hledger" mapM_ (add "Mihai Maruseac <mihai.maruseac@gmail.com>") $ words "io-manager" mapM_ (add "Dimitri Sabadie <dimitri.sabadie@gmail.com") $ words "monad-journal" mapM_ (add "Thomas Schilling <nominolo@googlemail.com>") $ words "ghc-syb-utils" mapM_ (add "Boris Buliga <d12frosted@icloud.com>") $ words "ghc-mod io-choice" when (ghcVer >= GhcMajorVersion 7 8) $ mapM_ (add "Boris Buliga <d12frosted@icloud.com>") $ words "system-canonicalpath" when (ghcVer >= GhcMajorVersion 7 8) $ mapM_ (add "Yann Esposito <yann.esposito@gmail.com>") $ words "holy-project" when requireHP $ addRange "Yann Esposito <yann.esposito@gmail.com>" "holy-project" "< 0.1.1.1" mapM_ (add "Paul Rouse <pgr@doynton.org>") $ words "yesod-auth-hashdb" add "Toralf Wittner <tw@dtex.org>" "zeromq4-haskell" mapM_ (add "trupill@gmail.com") $ words "djinn-lib djinn-ghc" mapM_ (add "Arash Rouhani <miffoljud@gmail.com>") $ words "yesod-text-markdown" mapM_ (add "Matvey Aksenov <matvey.aksenov@gmail.com") $ words "terminal-size" mapM_ (add "Luis G. Torres <lgtorres42@gmail.com") $ words "kdt" {- https://github.com/fpco/stackage/pull/331 mapM_ (add "Jyotirmoy Bhattacharya <jyotirmoy@jyotirmoy.net") $ words "hakyll" -} mapM_ (add "Emanuel Borsobom <manny@fpcomplete.com>") $ words "text-binary" when (ghcVer >= GhcMajorVersion 7 8) $ mapM_ (add "Emanuel Borsobom <manny@fpcomplete.com>") $ words "haddock-api" mapM_ (add "Michael Sloan <mgsloan@gmail.com") $ words "th-orphans th-reify-many" when (ghcVer == GhcMajorVersion 7 8 && not requireHP) $ mapM_ (add "Michael Snoyman") $ words =<< [ "repa repa-io repa-algorithms repa-devil JuicyPixels-repa" ] when (ghcVer >= GhcMajorVersion 7 8 && not requireHP) $ do mapM_ (add "Nikita Volkov <nikita.y.volkov@mail.ru>") $ words "hasql hasql-postgres hasql-backend postgresql-binary" ++ words "stm-containers focus list-t slave-thread partial-handler" ++ words "neat-interpolation cases" ++ words "base-prelude mtl-prelude" addRange "Nikita Volkov <nikita.y.volkov@mail.ru>" "mtl-prelude" "< 2" mapM_ (add "Iustin Pop <iustin@k1024.org>") $ words "prefix-units" -- https://github.com/fpco/stackage/issues/217 addRange "Michael Snoyman" "transformers" "< 0.4" addRange "Michael Snoyman" "mtl" "< 2.2" addRange "Michael Snoyman" "lifted-base" "< 0.2.2.2" -- https://github.com/fpco/stackage/issues/224 when (ghcVer <= GhcMajorVersion 7 6) $ do addRange "Michael Snoyman" "zip-archive" "== 0.2.2.1" addRange "Michael Snoyman" "pandoc" "== 1.12.4.2" addRange "Michael Snoyman" "texmath" "<= 0.6.6.3" addRange "Michael Snoyman" "attoparsec" "== 0.11.3.1" addRange "Michael Snoyman" "parsers" "< 0.11" addRange "Michael Snoyman" "scientific" "< 0.3" addRange "Michael Snoyman" "aeson" "< 0.7.0.5" addRange "Michael Snoyman" "aeson-utils" "< 0.2.2" addRange "Michael Snoyman" "formatting" "< 5" addRange "Michael Snoyman" "aws" "< 0.10" addRange "Michael Snoyman" "network" "< 2.6" addRange "Michael Snoyman" "network-uri" "< 2.6" -- 0.16.2 fixes dependency issues with different version of GHC -- and Haskell Platform. Now builds on GHC 7.4-7.8. Version 1.0 is -- guaranteed to break the API. See -- https://travis-ci.org/jswebtools/language-ecmascript for -- current build status. addRange "Andrey Chudnov <oss@chudnov.com>" "language-ecmascript" ">= 0.16.2 && < 1.0" -- https://github.com/fpco/stackage/issues/271 when (ghcVer < GhcMajorVersion 7 8) $ addRange "Michael Snoyman" "aeson" "< 0.8" -- https://github.com/fpco/stackage/issues/279 addRange "Michael Snoyman" "MonadRandom" "< 0.2" -- https://github.com/fpco/stackage/issues/288 addRange "Michael Snoyman" "text" "< 1.2" -- Force a specific version that's compatible with transformers 0.3 addRange "Michael Snoyman" "transformers-compat" "== 0.3.3.3" -- https://github.com/fpco/stackage/issues/291 addRange "Michael Snoyman" "random" "< 1.0.1.3" -- https://github.com/fpco/stackage/issues/314 addRange "Michael Snoyman" "hxt" "< 9.3.1.9" -- https://github.com/fpco/stackage/issues/318 addRange "Michael Snoyman" "HaXml" "< 1.25" -- https://github.com/fpco/stackage/issues/319 addRange "Michael Snoyman" "polyparse" "< 1.10" -- https://github.com/fpco/stackage/issues/341 addRange "Michael Snoyman" "haskell-names" "< 0.5" when (ghcVer == GhcMajorVersion 7 8 && requireHP) $ do -- Yay workarounds for unnecessarily old versions let peg x y = addRange "Haskell Platform" x y peg "aeson" "== 0.7.0.4" peg "scientific" "== 0.2.0.2" peg "criterion" "<= 0.8.1.0" peg "tasty-quickcheck" "< 0.8.0.3" peg "formatting" "< 5.0" peg "parsers" "< 0.11" peg "lens" "< 4.2" peg "contravariant" "< 1" peg "adjunctions" "< 4.2" peg "kan-extensions" "< 4.1" peg "semigroupoids" "< 4.1" peg "aws" "< 0.10" peg "pandoc" "< 1.13" peg "texmath" "<= 0.6.6.3" peg "checkers" "== 0.3.2" peg "HandsomeSoup" "< 0.3.3" peg "network-uri" "< 2.6" add :: String -> String -> Writer PackageMap () add maintainer package = addRange maintainer package "-any" addRange :: String -> String -> String -> Writer PackageMap () addRange maintainer package range = case simpleParse range of Nothing -> error $ "Invalid range " ++ show range ++ " for " ++ package Just range' -> tell $ PackageMap $ Map.singleton (PackageName package) (range', Maintainer maintainer) -- | Hard coded Haskell Platform versions haskellPlatform78 :: Writer PackageMap () haskellPlatform78 = do addRange "Haskell Platform" "ghc" "== 7.8.3" addRange "Haskell Platform" "haddock" "== 2.14.3" addRange "Haskell Platform" "array" "== 0.5.0.0" addRange "Haskell Platform" "base" "== 4.7.0.1" addRange "Haskell Platform" "bytestring" "== 0.10.4.0" addRange "Haskell Platform" "Cabal" "== 1.18.1.3" addRange "Haskell Platform" "containers" "== 0.5.5.1" addRange "Haskell Platform" "deepseq" "== 1.3.0.2" addRange "Haskell Platform" "directory" "== 1.2.1.0" addRange "Haskell Platform" "filepath" "== 1.3.0.2" addRange "Haskell Platform" "haskell2010" "== 1.1.2.0" addRange "Haskell Platform" "haskell98" "== 2.0.0.3" addRange "Haskell Platform" "hpc" "== 0.6.0.1" addRange "Haskell Platform" "old-locale" "== 1.0.0.6" addRange "Haskell Platform" "old-time" "== 1.1.0.2" addRange "Haskell Platform" "pretty" "== 1.1.1.1" addRange "Haskell Platform" "process" "== 1.2.0.0" addRange "Haskell Platform" "template-haskell" "== 2.9.0.0" addRange "Haskell Platform" "time" "== 1.4.2" addRange "Haskell Platform" "transformers" "== 0.3.0.0" addRange "Haskell Platform" "unix" "== 2.7.0.1" addRange "Haskell Platform" "xhtml" "== 3000.2.1" addRange "Haskell Platform" "async" "== 2.0.1.5" addRange "Haskell Platform" "attoparsec" "== 0.10.4.0" addRange "Haskell Platform" "case-insensitive" "== 1.1.0.3" addRange "Haskell Platform" "fgl" "== 5.5.0.1" addRange "Haskell Platform" "GLURaw" "== 1.4.0.1" addRange "Haskell Platform" "GLUT" "== 2.5.1.1" addRange "Haskell Platform" "hashable" "== 1.2.2.0" addRange "Haskell Platform" "haskell-src" "== 1.0.1.6" addRange "Haskell Platform" "html" "== 1.0.1.2" addRange "Haskell Platform" "HTTP" "== 4000.2.10" addRange "Haskell Platform" "HUnit" "== 1.2.5.2" addRange "Haskell Platform" "mtl" "== 2.1.3.1" addRange "Haskell Platform" "network" "== 2.4.2.3" addRange "Haskell Platform" "OpenGL" "== 2.9.2.0" addRange "Haskell Platform" "OpenGLRaw" "== 1.5.0.0" addRange "Haskell Platform" "parallel" "== 3.2.0.4" addRange "Haskell Platform" "parsec" "== 3.1.5" addRange "Haskell Platform" "primitive" "== 0.5.2.1" addRange "Haskell Platform" "QuickCheck" "== 2.6" addRange "Haskell Platform" "random" "== 1.0.1.1" addRange "Haskell Platform" "regex-base" "== 0.93.2" addRange "Haskell Platform" "regex-compat" "== 0.95.1" addRange "Haskell Platform" "regex-posix" "== 0.95.2" addRange "Haskell Platform" "split" "== 0.2.2" addRange "Haskell Platform" "stm" "== 2.4.2" addRange "Haskell Platform" "syb" "== 0.4.1" addRange "Haskell Platform" "text" "== 1.1.0.0" addRange "Haskell Platform" "transformers" "== 0.3.0.0" addRange "Haskell Platform" "unordered-containers" "== 0.2.4.0" addRange "Haskell Platform" "vector" "== 0.10.9.1" addRange "Haskell Platform" "xhtml" "== 3000.2.1" addRange "Haskell Platform" "zlib" "== 0.5.4.1" addRange "Haskell Platform" "alex" "== 3.1.3" addRange "Haskell Platform" "cabal-install" "== 1.18.0.5" addRange "Haskell Platform" "happy" "== 1.19.4" addRange "Haskell Platform" "hscolour" "== 1.20.3" -- | Replacement Github users. This is useful when a project is owned by an -- organization. It also lets you ping multiple users. -- -- Note that cross organization team mentions aren't allowed by Github. convertGithubUser :: String -> [String] convertGithubUser x = fromMaybe [x] $ Map.lookup (map toLower x) pairs where pairs = Map.fromList [ ("diagrams", ["byorgey", "fryguybob", "jeffreyrosenbluth", "bergey"]) , ("yesodweb", ["snoyberg"]) , ("fpco", ["snoyberg"]) , ("faylang", ["bergmark"]) , ("silkapp", ["bergmark", "hesselink"]) , ("snapframework",["mightybyte"]) , ("haskell-ro", ["mihaimaruseac"]) ]
feuerbach/stackage
Stackage/Config.hs
Haskell
mit
29,848
{-# LANGUAGE OverloadedStrings #-} module Day15 where import Data.Either (rights) import Data.List (sortOn) import Text.Parsec ((<|>) , Parsec , ParseError) import qualified Text.Parsec as P data Disc = Disc { discIndex :: Int , discPositions :: Int , discOffset :: Int } deriving (Eq, Show) parseInput :: String -> [Disc] parseInput = rights . map (P.parse parseDisc "") . lines parseDisc :: Parsec String () Disc parseDisc = Disc <$> (P.string "Disc #" *> number) <*> (P.string " has " *> number) <*> (P.string " positions; at time=0, it is at position " *> number <* P.char '.') where number = read <$> P.many1 P.digit makeRequirement :: Disc -> Requirement makeRequirement (Disc i p o) = Requirement p ((-(i + o)) `mod` p) data Requirement = Requirement { reqBase :: Int , reqRemainder :: Int } deriving (Eq, Ord, Show) doesSatisfy :: Requirement -> Int -> Bool doesSatisfy (Requirement p r) i = (i `mod` p) == r combine :: Requirement -> Requirement -> Requirement combine r@(Requirement p _) r'@(Requirement p' _) = Requirement (p * p') (satisfy [r, r']) satisfy :: [Requirement] -> Int satisfy [] = 0 satisfy (r : []) = reqRemainder r satisfy ((Requirement p r) : r' : []) = head . filter (doesSatisfy r') $ map (\i -> (i * p) + r) [0..] satisfy (r : rs) = reqRemainder $ foldl combine r rs addDisc :: Int -> Int -> [Disc] -> [Disc] addDisc position offset ds = (Disc (maxIndex + 1) position offset) : ds where maxIndex = maximum $ map discIndex ds -- Final, top-level exports day15 :: String -> Int day15 = satisfy . reverse . sortOn reqBase . map makeRequirement . parseInput day15' :: String -> Int day15' = satisfy . reverse . sortOn reqBase . map makeRequirement . addDisc 11 0 . parseInput -- Input run :: IO () run = do putStrLn "Day 15 results: " input <- readFile "inputs/day15.txt" putStrLn $ " " ++ show (day15 input) putStrLn $ " " ++ show (day15' input)
brianshourd/adventOfCode2016
src/Day15.hs
Haskell
mit
1,957
-- This file is part of the 'union-find-array' library. It is licensed -- under an MIT license. See the accompanying 'LICENSE' file for details. -- -- Authors: Bertram Felgenhauer {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances, UndecidableInstances #-} module Control.Monad.Union.Class ( MonadUnion (..), ) where import Data.Union.Type (Node (..), Union (..)) import Control.Monad.Trans (MonadTrans (..)) import Prelude hiding (lookup) class Monad m => MonadUnion l m | m -> l where -- | Add a new node, with a given label. new :: l -> m Node -- | Find the node representing a given node, and its label. lookup :: Node -> m (Node, l) -- | Merge two sets. The first argument is a function that takes the labels -- of the corresponding sets' representatives and computes a new label for -- the joined set. Returns Nothing if the given nodes are in the same set -- already. merge :: (l -> l -> (l, a)) -> Node -> Node -> m (Maybe a) -- | Re-label a node. annotate :: Node -> l -> m () -- | Flatten the disjoint set forest for faster lookups. flatten :: m () instance (MonadUnion l m, MonadTrans t, Monad (t m)) => MonadUnion l (t m) where new a = lift $ new a lookup a = lift $ lookup a merge a b c = lift $ merge a b c annotate a b = lift $ annotate a b flatten = lift $ flatten
haskell-rewriting/union-find-array
src/Control/Monad/Union/Class.hs
Haskell
mit
1,408
module Data.Smashy.Types where import Control.Concurrent.STM (TVar, newTVarIO) import Control.Concurrent.STM.TQueue (TQueue, newTQueueIO) import Data.Hashable (Hashable, hashWithSalt) import Data.Vector.Storable (Vector) import Data.Vector.Storable.MMap import Data.Vector.Storable.Mutable as VM (IOVector, new) import qualified STMContainers.Set as S (Set, newIO) import Data.Word (Word8, Word32) numBuckets :: Int numBuckets = 200000 bucketSize :: Int bucketSize = 1024 newtype Bucket = Bucket (VM.IOVector Word8) newtype BucketData = BucketData (Vector Word8) deriving Show data State = State { resizing :: TVar Bool, hashTableSize :: TVar Int, hashTable :: IOVector Word32, bucketList :: IOVector Word8, takenHashes :: S.Set Hash, nextFreeBucket :: TVar BucketId, freeStore :: TQueue BucketId } newState :: IO State newState = do let htSize = 200000 buckListSize = numBuckets * bucketSize resz <- newTVarIO False hts <- newTVarIO htSize ht <- VM.new htSize --ht <- unsafeMMapMVector "./hashtable" ReadWriteEx (Just (0, htSize)) bl <- VM.new buckListSize --bl <- unsafeMMapMVector "./bucketList" ReadWriteEx (Just (0, buckListSize)) h <- S.newIO nfb <- newTVarIO 1 fs <- newTQueueIO return $ State resz hts ht bl h nfb fs newtype Escaped = Escaped (Vector Word8) deriving Show newtype Hash = Hash Int deriving (Eq, Show) --This could be interesting. It's its own hash! instance Hashable Hash where hashWithSalt _ (Hash h) = h type Key = Escaped type Val = Escaped type Position = Int type BucketId = Int
jahaynes/smashy2
src/Data/Smashy/Types.hs
Haskell
mit
1,760
module AST where import qualified Data.Map as Map import Data.Semigroup type Name = String type Form = String data Pattern = Binding Name | Succ Pattern deriving (Show, Eq) data Param = FreeParam Name | LiteralParam Int | PatternParam Pattern | WildcardParam deriving (Show, Eq) data Expr = Number Int | Constant Name | Call Name [Expr] | Inc Expr deriving (Show, Eq) type Instance = ([Param], Expr, Form) data Definition = ConstDef Name Expr Form | FuncDef Name [Instance] deriving Show instance Semigroup Definition where (FuncDef x xinsts) <> (FuncDef _ yinsts) = FuncDef x (yinsts ++ xinsts) x <> _ = x newtype Environment = Environment (Map.Map Name Definition) deriving Show instance Monoid Environment where mempty = Environment Map.empty (Environment a) `mappend` (Environment b) = Environment (Map.unionWith (<>) a b) instance Semigroup Environment where (<>) = mappend showIntAsNat :: Int -> String showIntAsNat 0 = "0" showIntAsNat n = 'S' : showIntAsNat (pred n) singletonEnv :: Name -> Definition -> Environment singletonEnv n d = Environment $ Map.singleton n d lookupEnv :: Name -> Environment -> Maybe Definition lookupEnv n (Environment env) = Map.lookup n env insertEnv :: Definition -> Environment -> Environment insertEnv def@(ConstDef n _ _) env = singletonEnv n def <> env insertEnv def@(FuncDef n _) env = singletonEnv n def <> env defForm :: Definition -> [Form] defForm (ConstDef _ _ f) = [f] defForm (FuncDef _ is) = go is where go [] = [] go ((_, _, f) : is') = f : go is' type Program = [Definition]
andreasfrom/natlang
AST.hs
Haskell
mit
1,674
import Data.List takemax n (x:xs) = if x > n then [] else x: (takemax n xs) main = print (foldl1 (+) (filter even (takemax 4000000 fibonacci))) where fibonacci = unfoldr (\(a, b) -> Just (a + b, (b, a + b))) (1, 1)
cptroot/ProjectEuler-Haskell
Euler2.hs
Haskell
mit
218
{-# LANGUAGE ForeignFunctionInterface #-} module System.Random.SplitMix.MathOperations ( c_mix32 , c_mix64 , c_mixGamma , xorShift33 ,) where import Data.Word (Word32, Word64) import Data.Bits (xor, shiftR) -- | Mixing fuction to produce 32 bit values as per the paper foreign import ccall unsafe "mix32" c_mix32 :: Word64 -> Word32 -- | Mixing function to produce 64 bit values as per the paper foreign import ccall unsafe "mix64" c_mix64 :: Word64 -> Word64 -- | Mixing fuction to produce gamma values as per the paper -- always produces odd values foreign import ccall unsafe "mix_gamma" c_mixGamma :: Word64 -> Word64 -- | Bitwise operation equivalent to f n v = (v >> n) ^ v xorShift :: Int -> Word64 -> Word64 xorShift bits value = xor value $ shiftR value bits -- | Bitwise operation equivalent to f v = (v >> 33) ^ v xorShift33 :: Word64 -> Word64 xorShift33 = xorShift 33
nkartashov/SplitMix
src/System/Random/SplitMix/MathOperations.hs
Haskell
mit
895
{-# LANGUAGE ScopedTypeVariables, ViewPatterns, FlexibleContexts #-} {-| Module : Labyrinth.Pathing.Util Description : pathfinding utilities Copyright : (c) deweyvm 2014 License : MIT Maintainer : deweyvm Stability : experimental Portability : unknown Functions shared across different pathfinding algorithms. -} module Labyrinth.Pathing.Util where import Control.Applicative import Control.Arrow import Data.Maybe import qualified Data.PSQueue as Q import qualified Data.Map as Map import Labyrinth.Util expandPath :: (a -> a -> [a]) -> [a] -> [a] expandPath _ [] = [] expandPath f xs = concat $ uncurry f <$> zip xs (tail xs) expand :: Point -> Point -> [Point] expand (px, py) (qx, qy) = let dx = qx - px dy = qy - py sx = signum dx sy = signum dy n = max (abs dx) (abs dy) iter s = (take (n+1) $ iterate (+s) 0) in ((+px) *** (+py)) <$> zip (iter sx) (iter sy) rewindPath :: Ord a => Map.Map a a -> a -> [a] -> [a] rewindPath path end sofar = case Map.lookup end path of Just next -> rewindPath path next (end:sofar) Nothing -> sofar euclid :: Point -> Point -> Float euclid (i, j) (x, y) = (sqrt (xx + yy)) where xx = sq (x - i) yy = sq (y - j) sq = (** 2) . fromIntegral qMember :: (Ord a, Ord b) => a -> Q.PSQ a b -> Bool qMember = isJust .: Q.lookup
deweyvm/labyrinth
src/Labyrinth/Pathing/Util.hs
Haskell
mit
1,385
main = print getProblem15Value getProblem15Value :: Integer getProblem15Value = getNumberOfPaths 20 20 getNumberOfPaths :: Integer -> Integer -> Integer getNumberOfPaths x y = (fact (x+y)) `div` ((fact x) * (fact y)) fact :: Integer -> Integer fact 0 = 1 fact 1 = 1 fact x = x * (fact (x-1))
jchitel/ProjectEuler.hs
Problems/Problem0015.hs
Haskell
mit
296
{-# LANGUAGE CPP #-} {- ghcjs-run runs a program compiled by ghcjs with node.js -} module Main where import Control.Applicative import Data.Char import System.Directory import System.Environment import System.Exit import System.FilePath import System.Process main = do args <- getArgs path <- getExecutablePath cd <- getCurrentDirectory let jsExe = dropExeExtension path <.> "jsexe" script = jsExe </> "all" <.> "js" node <- trim <$> readFile (jsExe </> "node") ph <- runProcess node (script:args) (Just cd) Nothing Nothing Nothing Nothing exitWith =<< waitForProcess ph trim :: String -> String trim = let f = reverse . dropWhile isSpace in f . f dropExeExtension :: FilePath -> FilePath dropExeExtension x | not (null exeExtension) && map toLower (takeExtension x) == exeExtension = dropExtension x | otherwise = x #if !MIN_VERSION_directory(1,2,4) exeExtension :: String #ifdef WINDOWS exeExtension = ".exe" #else exeExtension = "" #endif #endif
ghcjs/ghcjs
src-bin/Run.hs
Haskell
mit
993
{-# LANGUAGE OverloadedStrings #-} {- | Module : $Header$ Description : Author : Nils 'bash0r' Jonsson Copyright : (c) 2015 Nils 'bash0r' Jonsson License : MIT Maintainer : aka.bash0r@gmail.com Stability : unstable Portability : non-portable (Portability is untested.) The 'Configuration' module contains all relevant information -} module Headergen.Configuration ( Configuration (..) , createDictionary ) where import Control.Applicative import Control.Monad import Data.Aeson import Headergen.Template -- | The configuration is used to read / write configuration to JSON. data Configuration = Configuration { getModule :: String , getDescription :: String , getAuthor :: String , getCopyright :: String , getLicense :: String , getMaintainer :: String , getStability :: String , getPortability :: String } deriving (Show, Eq) instance ToJSON Configuration where toJSON (Configuration mod desc auth copyr lic maint stab portab) = object [ "module" .= mod , "author" .= auth , "description" .= desc , "copyright" .= copyr , "license" .= lic , "maintainer" .= maint , "stability" .= stab , "portability" .= portab ] instance FromJSON Configuration where parseJSON (Object o) = Configuration <$> o .: "module" <*> o .: "description" <*> o .: "author" <*> o .: "copyright" <*> o .: "license" <*> o .: "maintainer" <*> o .: "stability" <*> o .: "portability" parseJSON _ = empty createDictionary :: Configuration -> Dictionary createDictionary (Configuration mod des aut cop lic mai sta por) = [ ("module" , mod) , ("description", des) , ("author" , aut) , ("copyright" , cop) , ("license" , lic) , ("maintainer" , mai) , ("stability" , sta) , ("portability", por) ]
aka-bash0r/headergen
src/Headergen/Configuration.hs
Haskell
mit
2,034
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referenceschema.html module Stratosphere.ResourceProperties.KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.KinesisAnalyticsApplicationReferenceDataSourceRecordColumn import Stratosphere.ResourceProperties.KinesisAnalyticsApplicationReferenceDataSourceRecordFormat -- | Full data type definition for -- KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema. See -- 'kinesisAnalyticsApplicationReferenceDataSourceReferenceSchema' for a -- more convenient constructor. data KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema = KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema { _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordColumns :: [KinesisAnalyticsApplicationReferenceDataSourceRecordColumn] , _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordEncoding :: Maybe (Val Text) , _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordFormat :: KinesisAnalyticsApplicationReferenceDataSourceRecordFormat } deriving (Show, Eq) instance ToJSON KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema where toJSON KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema{..} = object $ catMaybes [ (Just . ("RecordColumns",) . toJSON) _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordColumns , fmap (("RecordEncoding",) . toJSON) _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordEncoding , (Just . ("RecordFormat",) . toJSON) _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordFormat ] -- | Constructor for -- 'KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema' -- containing required fields as arguments. kinesisAnalyticsApplicationReferenceDataSourceReferenceSchema :: [KinesisAnalyticsApplicationReferenceDataSourceRecordColumn] -- ^ 'kaardsrsRecordColumns' -> KinesisAnalyticsApplicationReferenceDataSourceRecordFormat -- ^ 'kaardsrsRecordFormat' -> KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema kinesisAnalyticsApplicationReferenceDataSourceReferenceSchema recordColumnsarg recordFormatarg = KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema { _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordColumns = recordColumnsarg , _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordEncoding = Nothing , _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordFormat = recordFormatarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referenceschema.html#cfn-kinesisanalytics-applicationreferencedatasource-referenceschema-recordcolumns kaardsrsRecordColumns :: Lens' KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema [KinesisAnalyticsApplicationReferenceDataSourceRecordColumn] kaardsrsRecordColumns = lens _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordColumns (\s a -> s { _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordColumns = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referenceschema.html#cfn-kinesisanalytics-applicationreferencedatasource-referenceschema-recordencoding kaardsrsRecordEncoding :: Lens' KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema (Maybe (Val Text)) kaardsrsRecordEncoding = lens _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordEncoding (\s a -> s { _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordEncoding = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referenceschema.html#cfn-kinesisanalytics-applicationreferencedatasource-referenceschema-recordformat kaardsrsRecordFormat :: Lens' KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema KinesisAnalyticsApplicationReferenceDataSourceRecordFormat kaardsrsRecordFormat = lens _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordFormat (\s a -> s { _kinesisAnalyticsApplicationReferenceDataSourceReferenceSchemaRecordFormat = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/KinesisAnalyticsApplicationReferenceDataSourceReferenceSchema.hs
Haskell
mit
4,548
module Ternary.Core.Kernel ( Kernel, FirstTwoSteps (Step0, Step1), serial, chain, zipKernelsWith, transformFirstTwo, iterateKernel) where -- A kernel is a machine with an internal state. This state is such a -- fundamental type here, that I decided not to hide it. type Kernel input output state = input -> state -> (output, state) -- Sequential composition serial :: Kernel a b s -> Kernel b c t -> Kernel a c (s,t) serial f g a (s,t) = let (b,u) = f a s (c,v) = b `seq` g b t in c `seq` (c,(u,v)) -- Parallel composition zipKernelsWith :: (b -> d -> z) -> Kernel a b s -> Kernel c d t -> Kernel (a,c) z (s,t) zipKernelsWith op f g (a,c) (s,t) = f a s `op1` g c t where (b,s) `op1` (d,t) = (b `op` d, (s,t)) -- We need a state machine that transforms its input only during the -- first two cycles. data FirstTwoSteps = Step0 | Step1 | After deriving (Show, Eq, Ord) transformFirstTwo :: (a -> a) -> (a -> a) -> Kernel a a FirstTwoSteps transformFirstTwo f _ a Step0 = (f a, Step1) transformFirstTwo _ g a Step1 = (g a, After) transformFirstTwo _ _ a After = (a, After) -- With the chain function below, we define sequential composition of -- a list of kernels, combining states into a list of states. -- The first argument generates a kernel from a parameter. So a list -- of such parameters implicitly defines the list of kernels to be -- chained. But this list of kernels is not materialized: they are -- applied as we stream through the list of parameters. chain :: (p -> Kernel a a s) -> [p] -> Kernel a a [s] chain gen (p:ps) a (u:us) = let (b,v) = gen p a u (c,vs) = b `seq` chain gen ps b us in v `seq` (c,v:vs) chain _ [] a [] = (a,[]) iterateKernel :: Kernel a a s -> Int -> Kernel a a [s] iterateKernel k n = chain (const k) [1..n]
jeroennoels/exact-real
src/Ternary/Core/Kernel.hs
Haskell
mit
1,843
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QInputContext.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QInputContext ( StandardFormat, ePreeditFormat, eSelectionFormat ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CStandardFormat a = CStandardFormat a type StandardFormat = QEnum(CStandardFormat Int) ieStandardFormat :: Int -> StandardFormat ieStandardFormat x = QEnum (CStandardFormat x) instance QEnumC (CStandardFormat Int) where qEnum_toInt (QEnum (CStandardFormat x)) = x qEnum_fromInt x = QEnum (CStandardFormat x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> StandardFormat -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () ePreeditFormat :: StandardFormat ePreeditFormat = ieStandardFormat $ 0 eSelectionFormat :: StandardFormat eSelectionFormat = ieStandardFormat $ 1
keera-studios/hsQt
Qtc/Enums/Gui/QInputContext.hs
Haskell
bsd-2-clause
2,471
-- -- Copyright © 2014-2015 Anchor Systems, Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is -- made available to you by its authors as open source software: -- you can redistribute it and/or modify it under the terms of -- the 3-clause BSD licence. -- -- | Description: Run /Synchronise/ as a server. module Synchronise.Program.Daemon where import System.Log.Logger import Synchronise.Configuration import Synchronise.Network.Server -- | Start the synchronise daemon. synchronise :: Configuration -> IO () synchronise cfg = do let (_, pri, _) = configServer cfg updateGlobalLogger rootLoggerName (setLevel pri) spawnServer cfg 1
anchor/synchronise
lib/Synchronise/Program/Daemon.hs
Haskell
bsd-3-clause
690
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} module Api.Admin.UserAdmin ( UserAdminApi , userAdminHandlers ) where import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString.Char8 as B import Data.Pool (Pool, withResource) import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.Types (Query (..)) import Servant import Servant.Server.Experimental.Auth.Cookie import Api.Errors (appJson404) import Api.Login import Api.Types (ResultResp(..)) import Models.Author (Author (..)) import Types type UserAdminApi = "admin" :> "user" :> AuthProtect "cookie-auth" :> Get '[JSON] [Author] :<|> "admin" :> "user" :> Capture "id" Int :> AuthProtect "cookie-auth" :> Get '[JSON] Author :<|> "admin" :> "user" :> ReqBody '[JSON] Author :> AuthProtect "cookie-auth" :> Post '[JSON] Author :<|> "admin" :> "user" :> Capture "id" Int :> ReqBody '[JSON] Author :> AuthProtect "cookie-auth" :> Put '[JSON] ResultResp :<|> "admin" :> "user" :> Capture "id" Int :> AuthProtect "cookie-auth" :> Delete '[JSON] ResultResp userAdminHandlers :: ServerT UserAdminApi SimpleHandler userAdminHandlers = getUsersH :<|> userDetailH :<|> userAddH :<|> userUpdateH :<|> userDeleteH getUsersH :: WithMetadata Username -> SimpleHandler [Author] getUsersH uname = runHandlerDbHelper $ \conn -> do let q = "select * from author" liftIO $ query_ conn q userDetailH :: Int -> WithMetadata Username -> SimpleHandler Author userDetailH userId uname = runHandlerDbHelper $ \conn -> do let q = "select * from author where id = ?" res <- liftIO $ query conn q (Only userId) case res of (x:_) -> return x _ -> throwError $ appJson404 "Unknown author" userAddH :: Author -> WithMetadata Username -> SimpleHandler Author userAddH newAuthor uname = runHandlerDbHelper $ \conn -> do let q = "insert into author (firstname, lastname) values (?, ?) returning id" res <- liftIO $ query conn q (firstName newAuthor , lastName newAuthor) :: SimpleHandler [Only Int] case res of [] -> throwError err400 (uid:_) -> do author <- liftIO $ query conn "select * from author where id = ?" uid if null author then throwError err400 else return $ Prelude.head author userUpdateH :: Int -> Author -> WithMetadata Username -> SimpleHandler ResultResp userUpdateH userId author uname = runHandlerDbHelper $ \conn -> do let q = Query $ B.unwords ["update author set firstname = ?, lastname = ? " , "where id = ?"] result <- liftIO $ execute conn q (firstName author , lastName author , aid author) case result of 0 -> throwError err400 _ -> return $ ResultResp "success" "user updated" userDeleteH :: Int -> WithMetadata Username -> SimpleHandler ResultResp userDeleteH authorId uname = runHandlerDbHelper $ \conn -> do let q = "delete from author where id = ?" result <- liftIO $ execute conn q (Only authorId) case result of 0 -> throwError err400 _ -> return $ ResultResp "success" "user deleted"
pellagic-puffbomb/simpleservantblog
src/Api/Admin/UserAdmin.hs
Haskell
bsd-3-clause
3,471
-- | A type lattice for Python 3. module Language.Python.TypeInference.Analysis.TypeLattice ( UnionType (..), ValueType (..), BuiltinType (..), FunctionType (..), ClassType (..), InstanceType (..), HasClassId (..), Env, nabla, check, AType (..), oneType, filterType, filterOr, isBuiltin, isFunction, isClass, isInstance, orInstance, isNum, isIntegral, isSequence, isTuple, isList, allTypes, updateType, applyFunctionType ) where import Control.DeepSeq import Control.Monad (zipWithM) import Data.List (groupBy, intercalate, partition, sortBy) import Data.Map (Map) import Data.Maybe (catMaybes, fromMaybe, isNothing) import Data.Ord (comparing) import Data.Set (Set) import Language.Analysis.DFA.Lattice import Language.Python.TypeInference.Common import Text.Printf import qualified Data.Map as Map import qualified Data.Set as Set -- | Union type: models types of variables. data UnionType = -- | A set of types that the variable may have. UTy (Set ValueType) -- | Top element: we don't know anything about the type. | UTyTop -- | Type variable. Only to be used within function types ('FunTy'). | TypeVariable String deriving (Eq, Ord) instance NFData UnionType where rnf (UTy s) = rnf $ Set.toList s rnf UTyTop = () rnf (TypeVariable v) = rnf v -- | Value type: models types that values can have at runtime. data ValueType = BuiltinType BuiltinType | FunctionType FunctionType | ClassType ClassType | InstanceType InstanceType deriving (Eq, Ord) instance NFData ValueType where rnf (BuiltinType t) = rnf t rnf (FunctionType t) = rnf t rnf (ClassType t) = rnf t rnf (InstanceType t) = rnf t -- | Builtin Python type. See section 3.2 of the language reference. data BuiltinType = NoneType | NotImplementedType | EllipsisType | IntType | BoolType | FloatType | ComplexType | StrType | BytesType | BytearrayType -- unparameterized collection types | TupleType | ListType | SetType | FrozensetType | DictType -- parameterized collection types | TupleOf [UnionType] | ListOf UnionType | SetOf UnionType | FrozensetOf UnionType | DictOf UnionType UnionType deriving (Eq, Ord) instance NFData BuiltinType where rnf bt = case bt of (TupleOf ts) -> rnf ts (ListOf t) -> rnf t (SetOf t) -> rnf t (FrozensetOf t) -> rnf t (DictOf k v) -> rnf (k, v) _ -> () -- | Function type. data FunctionType = -- | Function id identifying a function in the code under analysis. FunId FunctionId -- | Function type with types of arguments and type of return value. | FunTy [UnionType] UnionType deriving (Eq, Ord) instance NFData FunctionType where rnf (FunId i) = rnf i rnf (FunTy a r) = rnf (a, r) -- | Class type. data ClassType = -- | Class with class id, superclasses and class attributes. ClsTy ClassId [ClassType] Env | -- | Reference to a global class type, used when class types -- are flow-insensitive. ClsRef ClassId deriving (Eq, Ord) instance NFData ClassType where rnf (ClsTy t sup e) = rnf (t, sup, Map.toList e) rnf (ClsRef i) = rnf i -- | Class instance type. data InstanceType = -- | Instance with class and instance attributes. InstTy ClassType Env | -- | Reference to a global instance type, used when -- instance types are flow-insensitive. InstRef ClassId deriving (Eq, Ord) instance NFData InstanceType where rnf (InstTy t e) = rnf (t, Map.toList e) rnf (InstRef i) = rnf i -- | Type class for types from which a class id can be extracted. class HasClassId a where getClassId :: a -> ClassId instance HasClassId ClassType where getClassId (ClsTy classId _ _) = classId getClassId (ClsRef classId) = classId instance HasClassId InstanceType where getClassId (InstTy classType _) = getClassId classType getClassId (InstRef classId) = classId -- | An environment, eg, the attributes of a class or object. type Env = Map String UnionType instance Lattice UnionType where bot = UTy Set.empty join UTyTop _ = UTyTop join _ UTyTop = UTyTop join (UTy a) (UTy b) = joinTypes $ Set.toList (a `Set.union` b) join a b = error $ "cannot join types " ++ show a ++ " and " ++ show b joinTypes :: [ValueType] -> UnionType joinTypes types = let joinClasses l = map (ClassType . foldl1 mergeClassTypes) (groupByClassId [t | ClassType t <- l]) joinInstances l = map (InstanceType . foldl1 mergeInstanceTypes) (groupByClassId [t | InstanceType t <- l]) isTupleOf (BuiltinType (TupleOf _)) = True isTupleOf _ = False isTuple (BuiltinType (TupleOf _)) = True isTuple (BuiltinType TupleType) = True isTuple _ = False joinTuples l = if all isTupleOf l then map (BuiltinType . foldl1 mergeTupleTypes) (groupByTupleSize [t | BuiltinType t <- l]) else [BuiltinType TupleType] isListOf (BuiltinType (ListOf _)) = True isListOf _ = False joinListOfTypes ts = [BuiltinType $ ListOf $ joinAll [t | BuiltinType (ListOf t) <- ts]] isSetOf (BuiltinType (SetOf _)) = True isSetOf _ = False joinSetOfTypes ts = [BuiltinType $ SetOf $ joinAll [t | BuiltinType (SetOf t) <- ts]] isFrozensetOf (BuiltinType (FrozensetOf _)) = True isFrozensetOf _ = False joinFrozensetOfTypes ts = [BuiltinType $ FrozensetOf $ joinAll [t | BuiltinType (FrozensetOf t) <- ts]] isDictOf (BuiltinType (DictOf _ _)) = True isDictOf _ = False joinDictOfTypes ts = [BuiltinType $ DictOf (joinAll [t | BuiltinType (DictOf t _) <- ts]) (joinAll [t | BuiltinType (DictOf _ t) <- ts])] pairs = [ (isClass, joinClasses) , (isInstance, joinInstances) , (isTuple, joinTuples) , (isListOf, joinListOfTypes) , (isSetOf, joinSetOfTypes) , (isFrozensetOf, joinFrozensetOfTypes) , (isDictOf, joinDictOfTypes) ] in UTy $ Set.fromList (splitAndMerge pairs types) splitAndMerge :: [(a -> Bool, [a] -> [a])] -> [a] -> [a] splitAndMerge _ [] = [] splitAndMerge [] l = l splitAndMerge ((p, f) : pairs) l = let (yes, no) = partition p l current = if null yes then [] else f yes in current ++ splitAndMerge pairs no -- | Group a list of class or instance types by class id. groupByClassId :: HasClassId a => [a] -> [[a]] groupByClassId list = let sorted = sortBy (comparing getClassId) list in groupBy (\a b -> getClassId a == getClassId b) sorted -- | Group a list of 'TupleOf' types by tuple size. groupByTupleSize :: [BuiltinType] -> [[BuiltinType]] groupByTupleSize list = let sorted = sortBy (comparing (\(TupleOf l) -> length l)) list in groupBy (\(TupleOf a) (TupleOf b) -> length a == length b) sorted -- | Merge two class types that refer to the same class. mergeClassTypes :: ClassType -> ClassType -> ClassType mergeClassTypes (ClsRef classId) _ = ClsRef classId mergeClassTypes _ (ClsRef classId) = ClsRef classId mergeClassTypes (ClsTy classId s1 e1) (ClsTy _ s2 e2) = ClsTy classId (mergeSuperClasses s1 s2) (mergeEnv e1 e2) -- | Merge two instance types that refer to the same class. mergeInstanceTypes :: InstanceType -> InstanceType -> InstanceType mergeInstanceTypes (InstRef classId) _ = InstRef classId mergeInstanceTypes _ (InstRef classId) = InstRef classId mergeInstanceTypes (InstTy c1 e1) (InstTy c2 e2) = InstTy (mergeClassTypes c1 c2) (mergeEnv e1 e2) mergeSuperClasses :: [ClassType] -> [ClassType] -> [ClassType] mergeSuperClasses sup [] = sup mergeSuperClasses [] sup = sup mergeSuperClasses (a:as) (b:bs) | getClassId a == getClassId b = mergeClassTypes a b : mergeSuperClasses as bs | otherwise = a : mergeSuperClasses as (b:bs) mergeEnv :: Env -> Env -> Env mergeEnv = Map.unionWith join -- | Merge two tuple types with the same size (number of elements). mergeTupleTypes :: BuiltinType -> BuiltinType -> BuiltinType mergeTupleTypes (TupleOf a) (TupleOf b) = TupleOf (zipWith join a b) -- | Widening operator: joins two 'UnionType's and jumps to 'UTyTop' if the -- result is too large. Parameterized with three numbers /n/, /m/ and /o/, -- where /n/ is the maximum size of a set of types, /m/ is the maximum nesting -- depth and /o/ is the maximum number of attributes of a class or object. nabla :: Int -> Int -> Int -> UnionType -> UnionType -> UnionType nabla n m o t1 t2 = limitUnionType n m o (t1 `join` t2) -- | Limit the size of a union type; return 'UTyTop' if it is too large. The -- parameters are the same as for 'nabla'. limitUnionType :: Int -> Int -> Int -> UnionType -> UnionType limitUnionType _ _ 0 _ = UTyTop limitUnionType _ _ _ UTyTop = UTyTop limitUnionType n m o (UTy s) | Set.size s > n = UTyTop | otherwise = maybe UTyTop UTy (do let l = Set.toList s l' <- mapM (limitValueType n m (o-1)) l return $ Set.fromList l') -- | Limit the size of a value type; return 'Nothing' if it is too large. The -- parameters are the same as for 'nabla'. limitValueType :: Int -> Int -> Int -> ValueType -> Maybe ValueType limitValueType _ _ 0 _ = Nothing limitValueType n m o t = case t of BuiltinType (TupleOf l) -> if length l > o then Just $ BuiltinType TupleType else Just $ BuiltinType $ TupleOf $ map lu l BuiltinType (ListOf u) -> Just $ BuiltinType $ ListOf (lu u) BuiltinType (SetOf u) -> Just $ BuiltinType $ SetOf (lu u) BuiltinType (FrozensetOf u) -> Just $ BuiltinType $ FrozensetOf (lu u) BuiltinType (DictOf k v) -> Just $ BuiltinType $ DictOf (lu k) (lu v) ClassType c -> do c' <- limitClassType n m o c return $ ClassType c' InstanceType (InstTy cls env) | Map.size env > o -> Nothing | otherwise -> do cls' <- limitClassType n m (o-1) cls let env' = Map.map lu env return $ InstanceType (InstTy cls' env') _ -> Just t where lu = limitUnionType n m (o - 1) -- | Limit the size of a class type; return 'Nothing' if it is too large. The -- parameters are the same as for 'nabla'. limitClassType :: Int -> Int -> Int -> ClassType -> Maybe ClassType limitClassType _ _ _ (ClsRef classId) = Just $ ClsRef classId limitClassType n m o (ClsTy classId sup env) | length sup > o = Nothing | Map.size env > o = Nothing | otherwise = do sup' <- mapM (limitClassType n m (o-1)) sup let env' = Map.map (limitUnionType n m (o-1)) env return $ ClsTy classId sup' env' instance Show UnionType where show (UTy ts) | Set.null ts = "bot" | otherwise = "{" ++ commas (Set.toAscList ts) ++ "}" show UTyTop = "top" show (TypeVariable a) = '!' : a instance Read UnionType where readsPrec _ r = case lex r of [("!", r1)] -> case lex r1 of [(a, r2)] -> [(TypeVariable a, r2)] _ -> [] [("bot", r1)] -> [(UTy Set.empty, r1)] [("top", r1)] -> [(UTyTop, r1)] [("{", r1)] -> case (readCommaList :: ReadS [ValueType]) r1 of [(ts, r2)] -> case lex r2 of [("}", r3)] -> [(UTy (Set.fromList ts), r3)] _ -> [] _ -> [] _ -> [] readCommaList :: Read a => ReadS [a] readCommaList = readSimpleList "," readSemicolonList :: Read a => ReadS [a] readSemicolonList = readSimpleList ";" readSimpleList :: Read a => String -> ReadS [a] readSimpleList sep r = case reads r of [(t, r1)] -> case lex r1 of [(token, r2)] | token == sep -> case readSimpleList sep r2 of [(ts, r3)] -> [(t : ts, r3)] _ -> [] _ -> [([t], r1)] _ -> [([], r)] instance Show ValueType where show (BuiltinType t) = show t show (FunctionType t) = show t show (ClassType t) = show t show (InstanceType t) = show t instance Read ValueType where readsPrec _ r = case (reads :: ReadS BuiltinType) r of [(t, r')] -> [(BuiltinType t, r')] _ -> case (reads :: ReadS FunctionType) r of [(t, r')] -> [(FunctionType t, r')] _ -> case (reads :: ReadS ClassType) r of [(t, r')] -> [(ClassType t, r')] _ -> case (reads :: ReadS InstanceType) r of [(t, r')] -> [(InstanceType t, r')] _ -> [] instance Show BuiltinType where show NotImplementedType = "NotImplementedType" show NoneType = "NoneType" show EllipsisType = "ellipsis" show IntType = "int" show BoolType = "bool" show FloatType = "float" show ComplexType = "complex" show StrType = "str" show BytesType = "bytes" show BytearrayType = "bytearray" show TupleType = "tuple" show ListType = "list" show SetType = "set" show FrozensetType = "frozenset" show DictType = "dict" show (TupleOf ts) = "tuple<" ++ intercalate "; " (map show ts) ++ ">" show (ListOf t) = "list<" ++ show t ++ ">" show (SetOf t) = "set<" ++ show t ++ ">" show (FrozensetOf t) = "frozenset<" ++ show t ++ ">" show (DictOf k v) = "dict<" ++ show k ++ "; " ++ show v ++ ">" instance Read BuiltinType where readsPrec _ r = case lex r of [("NotImplementedType", r')] -> [(NotImplementedType, r')] [("NoneType", r')] -> [(NoneType, r')] [("ellipsis", r')] -> [(EllipsisType, r')] [("int", r')] -> [(IntType, r')] [("bool", r')] -> [(BoolType, r')] [("float", r')] -> [(FloatType, r')] [("complex", r')] -> [(ComplexType, r')] [("str", r')] -> [(StrType, r')] [("bytes", r')] -> [(BytesType, r')] [("bytearray", r')] -> [(BytearrayType, r')] [("tuple", r')] -> case readOfList r' of [(ts, r2)] -> [(TupleOf ts, r2)] _ -> [(TupleType, r')] [("list", r')] -> parameterized ListType ListOf r' [("set", r')] -> parameterized SetType SetOf r' [("frozenset", r')] -> parameterized FrozensetType FrozensetOf r' [("dict", r')] -> case readOfList r' of [([k, v], r2)] -> [(DictOf k v, r2)] _ -> [(DictType, r')] _ -> [] where parameterized :: BuiltinType -> (UnionType -> BuiltinType) -> ReadS BuiltinType parameterized bt bto r = case readOf r of [(t, r')] -> [(bto t, r')] _ -> [(bt, r)] readOf :: ReadS UnionType readOf r = case lex r of [("<", r1)] -> case (reads :: ReadS UnionType) r1 of [(t, r2)] -> case lex r2 of [(">", r3)] -> [(t, r3)] [] -> [] _ -> [] _ -> [] readOfList :: ReadS [UnionType] readOfList r = case lex r of [("<", r1)] -> case (readSemicolonList :: ReadS [UnionType]) r1 of [(ts, r2)] -> case lex r2 of [(">", r3)] -> [(ts, r3)] _ -> [] _ -> [] _ -> [] instance Show FunctionType where show (FunId i) = "fun" ++ show i show (FunTy a r) = "lamba " ++ commas a ++ " -> " ++ show r instance Read FunctionType where readsPrec _ r | r `startsWith` "fun" = let r1 = drop 3 r in case (reads :: ReadS Int) r1 of [(n, r2)] -> [(FunId n, r2)] _ -> [] | r `startsWith` "lambda " = let r1 = drop 7 r in case (readCommaList :: ReadS [UnionType]) r1 of [(argTypes, r2)] -> case lex r2 of [("->", r3)] -> case (reads :: ReadS UnionType) r3 of [(returnType, r4)] -> [(FunTy argTypes returnType, r4)] _ -> [] _ -> [] _ -> [] | otherwise = [] instance Show ClassType where show (ClsTy classId sup env) = printf "class<%d; %s; %s>" classId (show sup) (showMapping env) show (ClsRef classId) = printf "class<%d>" classId instance Read ClassType where readsPrec _ r = case lex r of [("class", r1)] -> case lex r1 of [("<", r2)] -> case (reads :: ReadS Int) r2 of [(classId, r3)] -> case lex r3 of [(">", r4)] -> [(ClsRef classId, r4)] [(";", r4)] -> case (reads :: ReadS [ClassType]) r4 of [(sup, r5)] -> case lex r5 of [(";", r6)] -> case readMapping r6 of [(attrs, r7)] -> case lex r7 of [(">", r8)] -> [(ClsTy classId sup attrs, r8)] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] instance Show InstanceType where show (InstTy cls env) = printf "inst<%s; %s>" (show cls) (showMapping env) show (InstRef classId) = printf "inst<%d>" classId instance Read InstanceType where readsPrec _ r = case lex r of [("inst", r1)] -> case lex r1 of [("<", r2)] -> case (reads :: ReadS Int) r2 of [(classId, r3)] -> case lex r3 of [(">", r4)] -> [(InstRef classId, r4)] _ -> [] _ -> case (reads :: ReadS ClassType) r2 of [(cls, r3)] -> case lex r3 of [(";", r4)] -> case readMapping r4 of [(attrs, r5)] -> case lex r5 of [(">", r6)] -> [(InstTy cls attrs, r6)] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] check :: (Read a, Show a, Eq a) => a -> Bool check a = a == read (show a) -- | Typeclass for types that describe a single Python type. class AType a where toValueType :: a -> ValueType instance AType ValueType where toValueType = id instance AType BuiltinType where toValueType = BuiltinType instance AType FunctionType where toValueType = FunctionType instance AType ClassType where toValueType = ClassType instance AType InstanceType where toValueType = InstanceType -- | Create a union type containing just one value type. oneType :: AType a => a -> UnionType oneType t = UTy $ Set.singleton $ toValueType t -- | Modify the given union type so that it only contains value types for which -- the predicate is true. filterType :: (ValueType -> Bool) -> UnionType -> UnionType filterType _ UTyTop = UTyTop filterType predicate (UTy s) = UTy $ Set.filter predicate s -- | Modify the given union type so that it only contains value types for which -- at least one of the predicates is true. filterOr :: [ValueType -> Bool] -> UnionType -> UnionType filterOr predicates = filterType (isAny predicates) -- | Is it an instance type? isInstance :: ValueType -> Bool isInstance (InstanceType _) = True isInstance _ = False -- | Is it a builtin type? isBuiltin :: ValueType -> Bool isBuiltin (BuiltinType _) = True isBuiltin _ = False -- | Is it a function type? isFunction :: ValueType -> Bool isFunction (FunctionType _) = True isFunction _ = False -- | Is it a class type? isClass :: ValueType -> Bool isClass (ClassType _) = True isClass _ = False -- | Modify the given predicate so that it is true for all instance types. orInstance :: (ValueType -> Bool) -> ValueType -> Bool orInstance f t = f t || isInstance t -- | Is it a built-in numeric type? isNum :: ValueType -> Bool isNum (BuiltinType t) = t `elem` [IntType, BoolType, FloatType, ComplexType] isNum _ = False -- | Is it a built-in integral type? isIntegral :: ValueType -> Bool isIntegral (BuiltinType t) = t `elem` [IntType, BoolType] isIntegral _ = False -- | Is it a built-in sequence type (string, tuple, list)? isSequence :: ValueType -> Bool isSequence (BuiltinType t) = case t of TupleOf _ -> True ListOf _ -> True _ -> t `elem` [StrType, TupleType, ListType] isSequence _ = False -- | Is it a tuple? isTuple :: ValueType -> Bool isTuple (BuiltinType TupleType) = True isTuple (BuiltinType (TupleOf _)) = True isTuple _ = False -- | Is it a list? isList :: ValueType -> Bool isList (BuiltinType ListType) = True isList (BuiltinType (ListOf _)) = True isList _ = False -- | Is any of the predicates true for the value? isAny :: [a -> Bool] -> a -> Bool isAny predicates value = or [p value | p <- predicates] -- | Check if the predicate holds for all value types in the union type. Always -- false for @UTyTop@. allTypes :: (ValueType -> Bool) -> UnionType -> Bool allTypes _ UTyTop = False allTypes p (UTy s) = all p (Set.toList s) -- | Apply the function to all value types in the union type and join the -- results. updateType :: (ValueType -> UnionType) -> UnionType -> UnionType updateType f (UTy s) = joinAll $ map f (Set.toList s) updateType _ t = t -- | Apply a function type ('FunTy') to a list of argument types. applyFunctionType :: [UnionType] -> UnionType -> [UnionType] -> UnionType applyFunctionType argTypes _ arguments | length argTypes /= length arguments = bot applyFunctionType argTypes returnType arguments = let match :: UnionType -> UnionType -> Maybe (Map String UnionType) match UTyTop _ = Just Map.empty match (TypeVariable a) t = Just $ Map.singleton a t match (UTy a) (UTy b) | Set.null (a `Set.intersection` b) = Just Map.empty match _ _ = Nothing in case zipWithM match argTypes arguments of Nothing -> bot Just matched -> fromMaybe bot (replace (Map.unions matched) returnType) class ReplaceVariables a where replace :: Map String UnionType -> a -> Maybe a instance ReplaceVariables UnionType where replace _ UTyTop = Just UTyTop replace m (TypeVariable a) = Map.lookup a m replace m (UTy s) = case mapM (replace m) (Set.toList s) of Nothing -> Nothing Just l -> Just $ UTy $ Set.fromList l instance ReplaceVariables ValueType where replace m (BuiltinType t) = do t' <- replace m t return $ BuiltinType t' replace m (FunctionType t) = do t' <- replace m t return $ FunctionType t' replace m (ClassType t) = do t' <- replace m t return $ ClassType t' replace m (InstanceType t) = do t' <- replace m t return $ InstanceType t' instance ReplaceVariables BuiltinType where replace m (TupleOf ts) = do ts' <- mapM (replace m) ts return $ TupleOf ts' replace m (ListOf t) = do t' <- replace m t return $ ListOf t' replace m (SetOf t) = do t' <- replace m t return $ SetOf t' replace m (FrozensetOf t) = do t' <- replace m t return $ FrozensetOf t' replace m (DictOf k v) = do k' <- replace m k v' <- replace m v return $ DictOf k' v' replace _ t = Just t instance ReplaceVariables FunctionType where replace _ (FunId i) = Just $ FunId i replace m (FunTy a r) = do -- XXX: deal with shadowed type variables a' <- mapM (replace m) a r' <- replace m r return $ FunTy a' r' instance ReplaceVariables ClassType where replace m (ClsTy classId sup env) = do sup' <- mapM (replace m) sup env' <- replaceEnv m env return $ ClsTy classId sup' env' replace _ (ClsRef classId) = Just $ ClsRef classId instance ReplaceVariables InstanceType where replace m (InstTy classId env) = do env' <- replaceEnv m env return $ InstTy classId env' replace _ (InstRef classId) = Just $ InstRef classId replaceEnv :: Map String UnionType -> Env -> Maybe Env replaceEnv m = mapMapM (replace m)
lfritz/python-type-inference
python-type-inference/src/Language/Python/TypeInference/Analysis/TypeLattice.hs
Haskell
bsd-3-clause
27,942
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ViewPatterns #-} -- due to TypeDiff being a synonym: {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Render where import Control.Arrow ( second ) import Control.Applicative import Control.Monad.Trans.Reader import Data.Monoid import Data.Void ( Void, absurd ) import Data.Functor.Foldable ( cata, embed ) import Data.Interface import Data.Interface.Change import Data.Interface.Type.Diff import System.IO ( stdout ) import Text.PrettyPrint.ANSI.Leijen hiding ( (<>), (<$>), (<+>), (</>) ) import qualified Text.PrettyPrint.ANSI.Leijen as L type Indent = Int data REnv = REnv { reQualContext :: QualContext } deriving (Show) newtype RDoc = RDoc (Reader REnv Doc) instance Monoid RDoc where mempty = RDoc $ pure mempty mappend (RDoc a) (RDoc b) = RDoc $ liftA2 mappend a b unRDoc :: QualContext -> RDoc -> Doc unRDoc qc (RDoc m) = runReader m $ REnv qc withQC :: (QualContext -> Doc) -> RDoc withQC f = RDoc $ f <$> asks reQualContext liftDocOp :: (Doc -> Doc -> Doc) -> RDoc -> RDoc -> RDoc liftDocOp f a b = withQC $ \qc -> f (unRDoc qc a) (unRDoc qc b) (<+>), (</>), (<//>), (<#>) :: RDoc -> RDoc -> RDoc (<+>) = liftDocOp (L.<+>) (</>) = liftDocOp (L.</>) (<//>) = liftDocOp (L.<//>) (<#>) = liftDocOp (L.<$>) infixr 5 </>,<//>,<#> infixr 6 <+> renderToString :: (Render a) => Indent -> QualContext -> a -> String renderToString i qc = ($ "") . renders i qc renders :: (Render a) => Indent -> QualContext -> a -> ShowS renders i qc a = displayS $ renderPretty 0.8 78 $ indent i $ unRDoc qc $ doc a renderStdout :: (Render a) => Indent -> QualContext -> a -> IO () renderStdout i qc a = displayIO stdout $ renderPretty 0.8 78 $ indent i $ unRDoc qc $ doc a -- (Deprecated) node :: RDoc -> [RDoc] -> RDoc node n xs = combine vcat $ n : map (style $ indent 2) xs node' :: String -> [RDoc] -> RDoc node' = node . text' style :: (Doc -> Doc) -> RDoc -> RDoc style f (RDoc m) = RDoc $ fmap f m combine :: (Functor f) => (f Doc -> Doc) -> f RDoc -> RDoc combine f ds = withQC $ \qc -> f $ fmap (unRDoc qc) ds text' :: String -> RDoc text' = doc . text char' :: Char -> RDoc char' = doc . char qual :: Qual String -> RDoc qual q = RDoc $ do qc <- asks reQualContext pure $ text $ resolveQual qc q class Render a where doc :: a -> RDoc doc = RDoc . pure . doc' doc' :: a -> Doc doc' = unRDoc qualifyAll . doc namedDoc :: Named a -> RDoc namedDoc (Named n a) = text' n <#> style (indent 2) (doc a) {-# MINIMAL doc | doc' #-} instance Render RDoc where doc = id {-# INLINABLE doc #-} instance Render Doc where doc' = id {-# INLINABLE doc' #-} instance Render Void where doc = absurd instance Render TypeConInfo where doc i = text' $ case i of ConAlgebraic -> "[algebraic]" ConSynonym -> "[synonym]" ConClass -> "[class]" instance Render TypeCon where doc (TypeCon name origin kind info) = -- TODO node (text' name <+> prefixSig (doc kind)) [ doc info , node (text' $ formatOrigin origin) [] ] formatOrigin :: Origin -> String formatOrigin o = case o of WiredIn -> "[built-in]" UnknownSource -> "[??? source unknown]" KnownSource (Source path (SrcSpan loc0 loc1)) -> '[' : path ++ ':' : showLoc loc0 ++ '-' : showLoc loc1 ++ "]" where showLoc (SrcLoc l c) = show l ++ ":" ++ show c formatPred :: (Render a) => Pred a -> RDoc formatPred p = case p of ClassPred ts -> combine hsep $ map doc ts EqPred{} -> undefined --text' (show p) -- TODO instance Render Export where doc (Named n e) = case e of LocalValue vd -> namedDoc $ Named n vd LocalType td -> namedDoc $ Named n td ReExport m _ns -> qual (Qual m n) <> style (indent 2) (text' "(re-export)") renderIfChanged :: (Diff a c, Render c) => c -> RDoc renderIfChanged d | isChanged d = doc d | otherwise = mempty -- Declarations instance Render ModuleInterface where doc iface = combine vcat [ text' $ "Module: " ++ moduleName iface ] instance Render ValueDecl where doc (ValueDecl t i) = doc i <#> prefixSig (doc t) <> doc line instance Render ValueDeclDiff where doc (ValueDeclDiff t i) = doc i <#> prefixSig (doc t) <> doc line instance Render ValueDeclInfo where doc i = case i of Identifier -> text' "[id]" PatternSyn -> text' "[pattern]" DataCon fields -> node' "[data con]" (map (text' . rawName) fields) instance Render TypeDecl where doc (TypeDecl k i) = doc i <#> prefixSig (doc k) <> doc line instance Render TypeDeclDiff where doc (TypeDeclDiff k i) = doc i <#> prefixSig (doc k) <> doc line instance Render TypeDeclInfo where doc i = case i of DataType Abstract -> text' "[abstract data type]" DataType (DataConList dataCons) -> node' "[data type]" (map (text' . rawName) dataCons) TypeSyn s -> node' "[synonym]" [ text' s ] TypeClass -> text' "[class]" instance Render Kind where doc k = case k of KindVar s -> text' s StarKind -> char' '*' HashKind -> char' '#' SuperKind -> text' "BOX" ConstraintKind -> text' "Constraint" PromotedType q -> qual q FunKind a b -> doc a <+> text' "->" </> doc b {- instance Render ExportDiff where doc ed = case ed of LocalValueDiff dv -> namedDoc dv LocalTypeDiff dt -> namedDoc dt ExportDiff c -> doc c -} -- TODO: make ExportDiff an instance of Diff: --renderChangedExportDiff = renderIfChanged prefixSig :: RDoc -> RDoc prefixSig d = text' "::" <+> style align d instance (Render c, Render a) => Render (Elem c a) where doc e = case e of Added a -> style green $ doc a Removed b -> style red $ doc b Elem c -> doc c namedDoc (Named n e) = case e of Added a -> style green $ namedDoc (Named n a) Removed b -> style red $ namedDoc (Named n b) Elem c -> namedDoc (Named n c) instance (Render a) => Render (Change a) where doc c = case c of NoChange a -> doc a Change a b -> combine vcat [ style red $ text' "-" <+> style align (doc a) , style green $ text' "+" <+> style align (doc b) ] instance (Render a) => Render (Replace a) where doc = doc . toChange instance Render Type where doc = snd . renderTypePrec instance Render TypeDiff where doc = snd . renderTypeDiffPrec data Prec = TopPrec | FunPrec | AppPrec | ConPrec deriving (Show, Eq, Ord) renderTypePrec :: Type -> (Prec, RDoc) renderTypePrec = cata renderTypeAlg renderTypeAlg :: (Render a) => TypeF (Prec, a) -> (Prec, RDoc) renderTypeAlg = undefined -- XXX TODO {- renderTypeAlg t0 = case t0 of VarF (TypeVar s _) -> (ConPrec, text' s) ConF q -> (ConPrec, qual q) ApplyF c a -> (,) AppPrec $ docPrec TopPrec c <+> docPrec AppPrec a FunF a b -> (,) FunPrec $ docPrec FunPrec a <+> text' "->" </> docPrec TopPrec b ForallF vs (_, t) -> (,) TopPrec $ if showForall then doc (renderForall vs) <#> doc t else doc t ContextF ps (_, t) -> (,) TopPrec $ combine tupled (map formatPred ps) <+> text' "=>" </> doc t where showForall = False docPrec :: (Render a) => Prec -> (Prec, a) -> RDoc docPrec prec0 (prec, d) | prec <= prec0 = style parens (doc d) | otherwise = doc d -} renderForall :: [TypeVar] -> Doc renderForall vs = hsep (map text $ "forall" : varNames) <> dot where varNames = map varName vs renderTypeDiffPrec :: TypeDiff -> (Prec, RDoc) renderTypeDiffPrec = cata renderTypeDiffAlg renderTypeDiffAlg :: (Render a) => DiffTypeF Type (Prec, a) -> (Prec, RDoc) renderTypeDiffAlg td0 = case td0 of NoDiffTypeF t -> (ConPrec, doc $ embed t) ReplaceTypeF t0 t1 -> (,) ConPrec $ style braces $ style red (doc $ embed t0) <+> text' "/" <+> style green (doc $ embed t1) SameTypeF fc -> renderTypeAlg $ fmap (second doc) fc where replaceDoc :: Replace Type -> RDoc replaceDoc (Replace t0 t1) = style braces $ style red (doc t0) <+> text' "/" <+> style green (doc t1)
cdxr/haskell-interface
module-diff/Render.hs
Haskell
bsd-3-clause
8,749
{-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module CmmCallConv ( ParamLocation(..), assignArgumentsPos, globalArgRegs ) where #include "HsVersions.h" import CmmExpr import SMRep import Cmm (Convention(..)) import PprCmm () import Constants import qualified Data.List as L import DynFlags import Outputable -- Calculate the 'GlobalReg' or stack locations for function call -- parameters as used by the Cmm calling convention. data ParamLocation = RegisterParam GlobalReg | StackParam ByteOff instance Outputable ParamLocation where ppr (RegisterParam g) = ppr g ppr (StackParam p) = ppr p -- | JD: For the new stack story, I want arguments passed on the stack to manifest as -- positive offsets in a CallArea, not negative offsets from the stack pointer. -- Also, I want byte offsets, not word offsets. assignArgumentsPos :: DynFlags -> Convention -> (a -> CmmType) -> [a] -> [(a, ParamLocation)] -- Given a list of arguments, and a function that tells their types, -- return a list showing where each argument is passed assignArgumentsPos dflags conv arg_ty reps = assignments where -- The calling conventions (CgCallConv.hs) are complicated, to say the least regs = case (reps, conv) of (_, NativeNodeCall) -> getRegsWithNode dflags (_, NativeDirectCall) -> getRegsWithoutNode dflags ([_], NativeReturn) -> allRegs (_, NativeReturn) -> getRegsWithNode dflags -- GC calling convention *must* put values in registers (_, GC) -> allRegs (_, PrimOpCall) -> allRegs ([_], PrimOpReturn) -> allRegs (_, PrimOpReturn) -> getRegsWithNode dflags (_, Slow) -> noRegs -- The calling conventions first assign arguments to registers, -- then switch to the stack when we first run out of registers -- (even if there are still available registers for args of a different type). -- When returning an unboxed tuple, we also separate the stack -- arguments by pointerhood. (reg_assts, stk_args) = assign_regs [] reps regs stk_args' = case conv of NativeReturn -> part PrimOpReturn -> part GC | length stk_args /= 0 -> panic "Failed to allocate registers for GC call" _ -> stk_args where part = uncurry (++) (L.partition (not . isGcPtrType . arg_ty) stk_args) stk_assts = assign_stk 0 [] (reverse stk_args') assignments = reg_assts ++ stk_assts assign_regs assts [] _ = (assts, []) assign_regs assts (r:rs) regs = if isFloatType ty then float else int where float = case (w, regs) of (W32, (vs, f:fs, ds, ls)) -> k (RegisterParam f, (vs, fs, ds, ls)) (W64, (vs, fs, d:ds, ls)) -> k (RegisterParam d, (vs, fs, ds, ls)) (W80, _) -> panic "F80 unsupported register type" _ -> (assts, (r:rs)) int = case (w, regs) of (W128, _) -> panic "W128 unsupported register type" (_, (v:vs, fs, ds, ls)) | widthInBits w <= widthInBits wordWidth -> k (RegisterParam (v gcp), (vs, fs, ds, ls)) (_, (vs, fs, ds, l:ls)) | widthInBits w > widthInBits wordWidth -> k (RegisterParam l, (vs, fs, ds, ls)) _ -> (assts, (r:rs)) k (asst, regs') = assign_regs ((r, asst) : assts) rs regs' ty = arg_ty r w = typeWidth ty gcp | isGcPtrType ty = VGcPtr | otherwise = VNonGcPtr assign_stk _ assts [] = assts assign_stk offset assts (r:rs) = assign_stk off' ((r, StackParam off') : assts) rs where w = typeWidth (arg_ty r) size = (((widthInBytes w - 1) `div` wORD_SIZE) + 1) * wORD_SIZE off' = offset + size ----------------------------------------------------------------------------- -- Local information about the registers available type AvailRegs = ( [VGcPtr -> GlobalReg] -- available vanilla regs. , [GlobalReg] -- floats , [GlobalReg] -- doubles , [GlobalReg] -- longs (int64 and word64) ) -- Vanilla registers can contain pointers, Ints, Chars. -- Floats and doubles have separate register supplies. -- -- We take these register supplies from the *real* registers, i.e. those -- that are guaranteed to map to machine registers. getRegsWithoutNode, getRegsWithNode :: DynFlags -> AvailRegs getRegsWithoutNode _dflags = ( filter (\r -> r VGcPtr /= node) realVanillaRegs , realFloatRegs , realDoubleRegs , realLongRegs ) -- getRegsWithNode uses R1/node even if it isn't a register getRegsWithNode _dflags = ( if null realVanillaRegs then [VanillaReg 1] else realVanillaRegs , realFloatRegs , realDoubleRegs , realLongRegs ) allFloatRegs, allDoubleRegs, allLongRegs :: [GlobalReg] allVanillaRegs :: [VGcPtr -> GlobalReg] allVanillaRegs = map VanillaReg $ regList mAX_Vanilla_REG allFloatRegs = map FloatReg $ regList mAX_Float_REG allDoubleRegs = map DoubleReg $ regList mAX_Double_REG allLongRegs = map LongReg $ regList mAX_Long_REG realFloatRegs, realDoubleRegs, realLongRegs :: [GlobalReg] realVanillaRegs :: [VGcPtr -> GlobalReg] realVanillaRegs = map VanillaReg $ regList mAX_Real_Vanilla_REG realFloatRegs = map FloatReg $ regList mAX_Real_Float_REG realDoubleRegs = map DoubleReg $ regList mAX_Real_Double_REG realLongRegs = map LongReg $ regList mAX_Real_Long_REG regList :: Int -> [Int] regList n = [1 .. n] allRegs :: AvailRegs allRegs = (allVanillaRegs, allFloatRegs, allDoubleRegs, allLongRegs) noRegs :: AvailRegs noRegs = ([], [], [], []) globalArgRegs :: [GlobalReg] globalArgRegs = map ($VGcPtr) allVanillaRegs ++ allFloatRegs ++ allDoubleRegs ++ allLongRegs
nomeata/ghc
compiler/cmm/CmmCallConv.hs
Haskell
bsd-3-clause
6,497
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} -- {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE AllowAmbiguousTypes #-} -- The following is needed to define MonadPlus instance. It is decidable -- (there is no recursion!), but GHC cannot see that. {-# LANGUAGE UndecidableInstances #-} -- The framework of extensible effects module Eff1 where import Control.Monad import Control.Applicative import OpenUnion41 -- import Data.FastTCQueue -- old? -- import Data.TASequence.FastQueue hiding (tmap) import Data.TASequence.FastCatQueue hiding (tmap) import Data.IORef -- For demonstration of lifting import Data.Monoid -- For demos -- ------------------------------------------------------------------------ -- A monadic library for communication between a handler and -- its client, the administered computation -- Effectful arrow type: a function from a to b that also does effects -- denoted by r newtype Arr r a b = Arr{unArr:: a -> Eff r b} -- An effectful function from 'a' to 'b' that is a composition -- of several effectful functions. The paremeter r describes the overall -- effect. -- The composition members are accumulated in a type-aligned queue type GenArr r a b = FastTCQueue (Arr r) a b -- The Eff monad (not a transformer!) -- It is a fairly standard coroutine monad -- It is NOT a Free monad! There are no Functor constraints -- Status of a coroutine (client): done with the value of type w, -- or sending a request of type Union r with the continuation -- Gen r b a. data Eff r a = Val a | forall b. E !(Union r b) (GenArr r b a) -- Application to the `generalized effectful function' GenArr r b w qApp :: b -> GenArr r b w -> Eff r w qApp x q = case tviewl q of TAEmptyL -> Val x k :< t -> case unArr k x of Val y -> qApp y t E u q -> E u (q >< t) -- Compose effectful arrows (and possibly change the effect!) qComp :: GenArr r a b -> (Eff r b -> Eff r' c) -> Arr r' a c qComp q loop = Arr (\a -> loop $ qApp a q) -- Eff is still a monad and a functor (and Applicative) -- (despite the lack of the Functor constraint) instance Functor (Eff r) where fmap f (Val x) = Val (f x) fmap f (E u q) = E u (q |> Arr (Val . f)) -- does no mapping yet! instance Applicative (Eff r) where pure = Val Val f <*> Val x = Val $ f x Val f <*> E u q = E u (q |> Arr (Val . f)) E u q <*> Val x = E u (q |> Arr (Val . ($ x))) E u q <*> m = E u (q |> Arr (\f -> fmap f m)) instance Monad (Eff r) where {-# INLINE return #-} {-# INLINE (>>=) #-} return = Val Val x >>= k = k x E u q >>= k = E u (q |> Arr k) -- just accumulates continuations -- send a request and wait for a reply send :: Member t r => t v -> Eff r v send t = E (inj t) tempty {- -- A specialization of send useful for explanation send_req :: (Functor req, Typeable req, Member req r) => (forall w. (a -> VE w r) -> req (VE w r)) -> Eff r a send_req req = send (inj . req) -- administer a client: launch a coroutine and wait for it -- to send a request or terminate with a value admin :: Eff r w -> VE w r admin (Eff m) = m Val -- The opposite of admin, occasionally useful -- See the soft-cut for an example -- It is currently quite inefficient. There are better ways reflect :: VE a r -> Eff r a reflect (Val x) = return x reflect (E u) = Eff (\k -> E $ fmap (loop k) u) where loop :: (a -> VE w r) -> VE a r -> VE w r loop k (Val x) = k x loop k (E u) = E $ fmap (loop k) u -} -- ------------------------------------------------------------------------ -- The initial case, no effects -- The type of run ensures that all effects must be handled: -- only pure computations may be run. run :: Eff '[] w -> w run (Val x) = x -- the other case is unreachable since Union [] a cannot be -- constructed. -- Therefore, run is a total function if its argument terminates. -- A convenient pattern: given a request (open union), either -- handle it or relay it. handle_relay :: (a -> Eff r w) -> (forall v. t v -> Arr r v w -> Eff r w) -> Eff (t ': r) a -> Eff r w handle_relay ret _ (Val x) = ret x handle_relay ret h (E u q) = case decomp u of Right x -> h x k Left u -> E u (tsingleton k) where k = qComp q (handle_relay ret h) -- Add something like Control.Exception.catches? It could be useful -- for control with cut. -- Intercept the request and possibly reply to it, but leave it unhandled -- (that's why we use the same r all throuout) interpose :: Member t r => (a -> Eff r w) -> (forall v. t v -> Arr r v w -> Eff r w) -> Eff r a -> Eff r w interpose ret _ (Val x) = ret x interpose ret h (E u q) = case prj u of Just x -> h x k _ -> E u (tsingleton k) where k = qComp q (interpose ret h) -- ------------------------------------------------------------------------ -- The Reader monad -- The request for a value of type e from the current environment -- This is a GADT because the type of values -- returned in response to a (Reader e a) request is not any a; -- we expect in reply the value of type 'e', the value from the -- environment. So, the return type is restricted: 'a ~ e' data Reader e v where Reader :: Reader e e -- One can also define this as -- data Reader e v = (e ~ v) => Reader -- and even without GADTs, using explicit coercion: -- newtype Reader e v = Reader (e->v) -- In the latter case, when we make the request, we make it as Reader id. -- So, strictly speaking, GADTs are not really necessary. -- The signature is inferred ask :: (Member (Reader e) r) => Eff r e ask = send Reader -- The handler of Reader requests. The return type shows that -- all Reader requests are fully handled. runReader' :: Eff (Reader e ': r) w -> e -> Eff r w runReader' m e = loop m where loop (Val x) = return x loop (E u q) = case decomp u of Right Reader -> loop $ qApp e q Left u -> E u (tsingleton (qComp q loop)) -- A different way of writing the above runReader :: Eff (Reader e ': r) w -> e -> Eff r w runReader m e = handle_relay return (\Reader k -> unArr k e) m -- Locally rebind the value in the dynamic environment -- This function is like a relay; it is both an admin for Reader requests, -- and a requestor of them local :: forall e a r. Member (Reader e) r => (e -> e) -> Eff r a -> Eff r a local f m = do e0 <- ask let e = f e0 -- Local signature is needed, as always with GADTs let h :: Reader e v -> Arr r v a -> Eff r a h Reader (Arr g) = g e interpose return h m -- Examples add :: Monad m => m Int -> m Int -> m Int add = liftM2 (+) -- The type is inferred -- t1 :: Member (Reader Int) r => Eff r Int t1 = ask `add` return (1::Int) t1' :: Member (Reader Int) r => Eff r Int t1' = do v <- ask; return (v + 1 :: Int) -- t1r :: Eff r Int t1r = runReader t1 (10::Int) t1rr = 11 == run t1r {- t1rr' = run t1 No instance for (Member (Reader Int) Void) arising from a use of `t1' -} -- Inferred type -- t2 :: (Member (Reader Int) r, Member (Reader Float) r) => Eff r Float t2 = do v1 <- ask v2 <- ask return $ fromIntegral (v1 + (1::Int)) + (v2 + (2::Float)) -- t2r :: Member (Reader Float) r => Eff r Float t2r = runReader t2 (10::Int) -- t2rr :: Eff r Float t2rr = flip runReader (20::Float) . flip runReader (10::Int) $ t2 t2rrr = 33.0 == run t2rr -- The opposite order of layers {- If we mess up, we get an error t2rrr1' = run $ runReader (runReader t2 (20::Float)) (10::Float) No instance for (Member (Reader Int) []) arising from a use of `t2' -} t2rrr' = (33.0 ==) $ run $ runReader (runReader t2 (20::Float)) (10::Int) -- The type is inferred t3 :: Member (Reader Int) r => Eff r Int t3 = t1 `add` local (+ (10::Int)) t1 t3r = (212 ==) $ run $ runReader t3 (100::Int) -- The following example demonstrates true interleaving of Reader Int -- and Reader Float layers {- t4 :: (Member (Reader Int) r, Member (Reader Float) r) => () -> Eff r Float -} t4 = liftM2 (+) (local (+ (10::Int)) t2) (local (+ (30::Float)) t2) t4rr = (106.0 ==) $ run $ runReader (runReader t4 (10::Int)) (20::Float) -- The opposite order of layers gives the same result t4rr' = (106.0 ==) $ run $ runReader (runReader t4 (20::Float)) (10::Int) -- Map an effectful function -- The type is inferred tmap :: Member (Reader Int) r => Eff r [Int] tmap = mapM f [1..5] where f x = ask `add` return x tmapr = ([11,12,13,14,15] ==) $ run $ runReader tmap (10::Int) -- ------------------------------------------------------------------------ -- Exceptions -- exceptions of the type e; no resumption newtype Exc e v = Exc e -- The type is inferred throwError :: (Member (Exc e) r) => e -> Eff r a throwError e = send (Exc e) runError :: Eff (Exc e ': r) a -> Eff r (Either e a) runError = handle_relay (return . Right) (\ (Exc e) _k -> return (Left e)) -- The handler is allowed to rethrow the exception catchError :: Member (Exc e) r => Eff r a -> (e -> Eff r a) -> Eff r a catchError m handle = interpose return (\(Exc e) _k -> handle e) m -- The type is inferred et1 :: Eff r Int et1 = return 1 `add` return 2 et1r = 3 == run et1 -- The type is inferred et2 :: Member (Exc Int) r => Eff r Int et2 = return 1 `add` throwError (2::Int) -- The following won't type: unhandled exception! -- ex2rw = run et2 {- No instance for (Member (Exc Int) Void) arising from a use of `et2' -} -- The inferred type shows that ex21 is now pure et21 :: Eff r (Either Int Int) et21 = runError et2 et21r = Left 2 == run et21 -- The example from the paper newtype TooBig = TooBig Int deriving (Eq, Show) -- The type is inferred ex2 :: Member (Exc TooBig) r => Eff r Int -> Eff r Int ex2 m = do v <- m if v > 5 then throwError (TooBig v) else return v -- specialization to tell the type of the exception runErrBig :: Eff (Exc TooBig ': r) a -> Eff r (Either TooBig a) runErrBig = runError ex2r = runReader (runErrBig (ex2 ask)) (5::Int) ex2rr = Right 5 == run ex2r ex2rr1 = (Left (TooBig 7) ==) $ run $ runReader (runErrBig (ex2 ask)) (7::Int) -- Different order of handlers (layers) ex2rr2 = (Left (TooBig 7) ==) $ run $ runErrBig (runReader (ex2 ask) (7::Int)) -- Implementing the operator <|> from Alternative: -- a <|> b does -- -- tries a, and if succeeds, returns its result -- -- otherwise, tries b, and if succeeds, returns its result -- -- otherwise, throws mappend of exceptions of a and b -- We use MemberU2 in the signature rather than Member to -- ensure that the computation throws only one type of exceptions. -- Otherwise, this construction is not very useful. alttry :: forall e r a. (Monoid e, MemberU2 Exc (Exc e) r) => Eff r a -> Eff r a -> Eff r a alttry ma mb = catchError ma $ \ea -> catchError mb $ \eb -> throwError (mappend (ea::e) eb) -- Test case t_alttry = ([Right 10,Right 10,Right 10,Left "bummer1bummer2"] ==) $ [ run . runError $ (return 1 `add` throwError "bummer1") `alttry` (return 10), run . runError $ (return 10) `alttry` (return 1 `add` throwError "bummer2"), run . runError $ (return 10) `alttry` return 20, run . runError $ (return 1 `add` throwError "bummer1") `alttry` (return 1 `add` throwError "bummer2") ] -- ------------------------------------------------------------------------ -- Non-determinism (choice) -- choose lst non-deterministically chooses one value from the lst -- choose [] thus corresponds to failure -- Unlike Reader, Choose is not a GADT because the type of values -- returned in response to a (Choose a) request is just a, without -- any contraints. newtype Choose a = Choose [a] choose :: Member Choose r => [a] -> Eff r a choose lst = send (Choose lst) -- MonadPlus-like operators are expressible via choose instance Member Choose r => Alternative (Eff r) where empty = choose [] m1 <|> m2 = choose [m1,m2] >>= id instance Member Choose r => MonadPlus (Eff r) where mzero = empty mplus = (<|>) -- The interpreter makeChoice :: forall a r. Eff (Choose ': r) a -> Eff r [a] makeChoice = handle_relay (return . (:[])) (\ (Choose lst) (Arr k) -> handle lst k) where -- Need the signature since local bindings aren't polymorphic any more handle :: [t] -> (t -> Eff r [a]) -> Eff r [a] handle [] _ = return [] handle [x] k = k x handle lst k = fmap concat $ mapM k lst exc1 :: Member Choose r => Eff r Int exc1 = return 1 `add` choose [1,2] exc11 = makeChoice exc1 exc11r = ([2,3] ==) $ run exc11 {- -- ------------------------------------------------------------------------ -- Soft-cut: non-deterministic if-then-else, aka Prolog's *-> -- Declaratively, -- ifte t th el = (t >>= th) `mplus` ((not t) >> el) -- However, t is evaluated only once. In other words, ifte t th el -- is equivalent to t >>= th if t has at least one solution. -- If t fails, ifte t th el is the same as el. ifte :: forall r a b. Member Choose r => Eff r a -> (a -> Eff r b) -> Eff r b -> Eff r b ifte t th el = loop [] (admin t) where loop [] (Val x) = th x -- add all other latent choices of t to th x -- this is like reflection of t loop jq (Val x) = choose ((th x) : map (\t -> reflect t >>= th) jq) >>= id loop jq (E u) = interpose u (loop jq) (\(Choose lst k) -> handle jq lst k) -- Need the signature since local bindings aren't polymorphic any more handle :: [VE a r] -> [t] -> (t -> VE a r) -> Eff r b handle [] [] _ = el -- no more choices left handle (j:jq) [] _ = loop jq j handle jq [x] k = loop jq (k x) handle jq (x:rest) k = loop (map k rest ++ jq) (k x) -- DFS guard' :: Member Choose r => Bool -> Eff r () guard' True = return () guard' False = mzero' -- primes (very inefficiently -- but a good example of ifte) test_ifte = do n <- gen guard' $ n > 1 ifte (do d <- gen guard' $ d < n && d > 1 && n `mod` d == 0 -- _ <- trace ("d: " ++ show d) (return ()) return d) (\_->mzero') (return n) where gen = choose [1..30] test_ifte_run = run . makeChoice $ test_ifte -- [2,3,5,7,11,13,17,19,23,29] -} -- ------------------------------------------------------------------------ -- Combining exceptions and non-determinism -- Example from the paper ex2_2 = ([Right 5,Left (TooBig 7),Right 1] ==) $ run . makeChoice . runErrBig $ ex2 (choose [5,7,1]) -- just like ex1_1 in transf.hs but not at all like ex2_1 in transf.hs -- with different order of handlers, obtain the desired result of -- a high-priority exception ex2_1 = (Left (TooBig 7) ==) $ run . runErrBig . makeChoice $ ex2 (choose [5,7,1]) -- Errror recovery part -- The code is the same as in transf1.hs. The inferred signatures differ -- Was: exRec :: MonadError TooBig m => m Int -> m Int -- exRec :: Member (Exc TooBig) r => Eff r Int -> Eff r Int exRec m = catchError m handler where handler (TooBig n) | n <= 7 = return n handler e = throwError e ex2r_2 = (Right [5,7,1] ==) $ run . runErrBig . makeChoice $ exRec (ex2 (choose [5,7,1])) -- Compare with ex2r_1 from transf1.hs ex2r_2' = ([Right 5,Right 7,Right 1] ==) $ run . makeChoice . runErrBig $ exRec (ex2 (choose [5,7,1])) -- Again, all three choices are accounted for. ex2r_1 = (Left (TooBig 11) ==) $ run . runErrBig . makeChoice $ exRec (ex2 (choose [5,7,11,1])) -- Compare with ex2r_2 from transf1.hs -- ------------------------------------------------------------------------ -- State, strict -- The state request carries with it the state mutator function -- We can use this request both for mutating and getting the state. -- But see below for a better design! data State s v where State :: (s->s) -> State s s -- Use Reader to get the state. So we decompose State into Reader -- and Mutator! -- The signature is inferred put :: Member (State s) r => s -> Eff r () put s = send (State (const s)) >> return () modify :: Member (State s) r => (s -> s) -> Eff r s modify f = send (State f) -- The signature is inferred get :: Member (State s) r => Eff r s get = send (State id) -- Parameterized handle_relay handle_relay_s :: s -> (s -> a -> Eff r w) -> (forall v. s -> t v -> (s -> Arr r v w) -> Eff r w) -> Eff (t ': r) a -> Eff r w handle_relay_s s ret _ (Val x) = ret s x handle_relay_s s ret h (E u q) = case decomp u of Right x -> h s x k Left u -> E u (tsingleton (k s)) where k s = qComp q (handle_relay_s s ret h) runState :: Eff (State s ': r) w -> s -> Eff r (w,s) runState m s = handle_relay_s s (\s x -> return (x,s)) (\s (State t) k -> let s' = t s in unArr (k $! s') $! s') m -- Examples ts1 :: Member (State Int) r => Eff r Int ts1 = do put (10 ::Int) x <- get return (x::Int) ts1r = ((10,10) ==) $ run (runState ts1 (0::Int)) ts2 :: Member (State Int) r => Eff r Int ts2 = do put (10::Int) x <- get put (20::Int) y <- get return (x+y) ts2r = ((30,20) ==) $ run (runState ts2 (0::Int)) -- A different representation of State: decomposing State into mutation -- and Reading. We don't define any new effects: we just handle the -- existing ones. We use State for modification and Reader for inquiring. -- Thus we define a handler for two effects. runStateR :: Eff (State s ': Reader s ': r) w -> s -> Eff r (w,s) runStateR m s = loop s m where loop :: s -> Eff (State s ': Reader s ': r) w -> Eff r (w,s) loop s (Val x) = return (x,s) loop s (E u q) = case decomp u of Right (State t) -> let s' = t s in unArr (k $! s') $! s' Left u -> case decomp u of Right Reader -> unArr (k s) s Left u -> E u (tsingleton (k s)) where k s = qComp q (loop s) -- If we had a Writer, we could have decomposed State into Writer and Reader -- requests. ts11 :: (Member (Reader Int) r, Member (State Int) r) => Eff r Int ts11 = do put (10 ::Int) x <- ask return (x::Int) ts11r = ((10,10) ==) $ run (runStateR ts1 (0::Int)) ts21 :: (Member (Reader Int) r, Member (State Int) r) => Eff r Int ts21 = do put (10::Int) x <- ask put (20::Int) y <- ask return (x+y) ts21r = ((30,20) ==) $ run (runStateR ts2 (0::Int)) -- exceptions and state incr :: Member (State Int) r => Eff r () incr = get >>= put . (+ (1::Int)) tes1 :: (Member (State Int) r, Member (Exc [Char]) r) => Eff r b tes1 = do incr throwError "exc" ter1 = ((Left "exc" :: Either String Int,2) ==) $ run $ runState (runError tes1) (1::Int) ter2 = ((Left "exc" :: Either String (Int,Int)) ==) $ run $ runError (runState tes1 (1::Int)) teCatch :: Member (Exc String) r => Eff r a -> Eff r [Char] teCatch m = catchError (m >> return "done") (\e -> return (e::String)) ter3 = ((Right "exc" :: Either String String,2) ==) $ run $ runState (runError (teCatch tes1)) (1::Int) ter4 = ((Right ("exc",2) :: Either String (String,Int)) ==) $ run $ runError (runState (teCatch tes1) (1::Int)) -- Encapsulation of effects -- The example suggested by a reviewer {- The reviewer outlined an MTL implementation below, writing ``This hides the state effect and I can layer another state effect on top without getting into conflict with the class system.'' class Monad m => MonadFresh m where fresh :: m Int newtype FreshT m a = FreshT { unFreshT :: State Int m a } deriving (Functor, Monad, MonadTrans) instance Monad m => MonadFresh (FreshT m) where fresh = FreshT $ do n <- get; put (n+1); return n See EncapsMTL.hs for the complete code. -} -- There are three possible implementations -- The first one uses State Fresh where -- newtype Fresh = Fresh Int -- We get the `private' effect layer (State Fresh) that does not interfere -- with with other layers. -- This is the easiest implementation. -- The second implementation defines a new effect Fresh data Fresh v where Fresh :: Fresh Int fresh :: Member Fresh r => Eff r Int fresh = send Fresh -- And a handler for it runFresh' :: Eff (Fresh ': r) w -> Int -> Eff r w runFresh' m s = handle_relay_s s (\_s x -> return x) (\s Fresh k -> unArr (k $! s+1) s) m -- Test tfresh' = runTrace $ flip runFresh' 0 $ do n <- fresh trace $ "Fresh " ++ show n n <- fresh trace $ "Fresh " ++ show n {- Fresh 0 Fresh 1 -} {- -- Finally, the worst implementation but the one that answers -- reviewer's question: implementing Fresh in terms of State -- but not revealing that fact. runFresh :: Eff (Fresh :> r) w -> Int -> Eff r w runFresh m s = runState m' s >>= return . fst where m' = loop m loop (Val x) = return x loop (E u q) = case decomp u of Right Fresh -> do n <- get put (n+1::Int) unArr k n Left u -> send (\k -> weaken $ fmap k u) >>= loop tfresh = runTrace $ flip runFresh 0 $ do n <- fresh -- (x::Int) <- get trace $ "Fresh " ++ show n n <- fresh trace $ "Fresh " ++ show n {- If we try to meddle with the encapsulated state, by uncommenting the get statement above, we get: No instance for (Member (State Int) Void) arising from a use of `get' -} -} -- ------------------------------------------------------------------------ -- Tracing (debug printing) data Trace v where Trace :: String -> Trace () -- Printing a string in a trace trace :: Member Trace r => String -> Eff r () trace = send . Trace -- The handler for IO request: a terminal handler runTrace :: Eff '[Trace] w -> IO w runTrace (Val x) = return x runTrace (E u q) = case decomp u of Right (Trace s) -> putStrLn s >> runTrace (qApp () q) -- Nothing more can occur -- Higher-order effectful function -- The inferred type shows that the Trace affect is added to the effects -- of r mapMdebug:: (Show a, Member Trace r) => (a -> Eff r b) -> [a] -> Eff r [b] mapMdebug f [] = return [] mapMdebug f (h:t) = do trace $ "mapMdebug: " ++ show h h' <- f h t' <- mapMdebug f t return (h':t') tMd = runTrace $ runReader (mapMdebug f [1..5]) (10::Int) where f x = ask `add` return x {- mapMdebug: 1 mapMdebug: 2 mapMdebug: 3 mapMdebug: 4 mapMdebug: 5 [11,12,13,14,15] -} -- duplicate layers tdup = runTrace $ runReader m (10::Int) where m = do runReader tr (20::Int) tr tr = do v <- ask trace $ "Asked: " ++ show (v::Int) {- Asked: 20 Asked: 10 -} -- ------------------------------------------------------------------------ -- Lifting: emulating monad transformers newtype Lift m a = Lift (m a) -- We make the Lift layer to be unique, using MemberU2 lift :: (MemberU2 Lift (Lift m) r) => m a -> Eff r a lift = send . Lift -- The handler of Lift requests. It is meant to be terminal runLift :: Monad m => Eff '[Lift m] w -> m w runLift (Val x) = return x runLift (E u q) = case prj u of Just (Lift m) -> m >>= \x -> runLift (qApp x q) -- Nothing cannot occur tl1 = ask >>= \(x::Int) -> lift . print $ x -- tl1r :: IO () tl1r = runLift (runReader tl1 (5::Int)) -- 5 -- Re-implemenation of mapMdebug using Lifting -- The signature is inferred mapMdebug' :: (Show a, MemberU2 Lift (Lift IO) r) => (a -> Eff r b) -> [a] -> Eff r [b] mapMdebug' f [] = return [] mapMdebug' f (h:t) = do lift $ print h h' <- f h t' <- mapMdebug' f t return (h':t') tMd' = runLift $ runReader (mapMdebug' f [1..5]) (10::Int) where f x = ask `add` return x {- 1 2 3 4 5 [11,12,13,14,15] -} {- -- ------------------------------------------------------------------------ -- Co-routines -- The interface is intentionally chosen to be the same as in transf.hs -- The yield request: reporting the value of type a and suspending -- the coroutine. Resuming with the value of type b data Yield a b v = Yield a (b -> v) deriving (Typeable, Functor) -- The signature is inferred yield :: (Typeable a, Typeable b, Member (Yield a b) r) => a -> Eff r b yield x = send (inj . Yield x) -- Status of a thread: done or reporting the value of the type a -- and resuming with the value of type b data Y r a b = Done | Y a (b -> Eff r (Y r a b)) -- Launch a thread and report its status runC :: (Typeable a, Typeable b) => Eff (Yield a b :> r) w -> Eff r (Y r a b) runC m = loop (admin m) where loop (Val x) = return Done loop (E u) = handle_relay u loop $ \(Yield x k) -> return (Y x (loop . k)) -- First example of coroutines yieldInt :: Member (Yield Int ()) r => Int -> Eff r () yieldInt = yield th1 :: Member (Yield Int ()) r => Eff r () th1 = yieldInt 1 >> yieldInt 2 c1 = runTrace (loop =<< runC th1) where loop (Y x k) = trace (show (x::Int)) >> k () >>= loop loop Done = trace "Done" {- 1 2 Done -} -- Add dynamic variables -- The code is essentially the same as that in transf.hs (only added -- a type specializtion on yield). The inferred signature is different though. -- Before it was -- th2 :: MonadReader Int m => CoT Int m () -- Now it is more general: th2 :: (Member (Yield Int ()) r, Member (Reader Int) r) => Eff r () th2 = ask >>= yieldInt >> (ask >>= yieldInt) -- Code is essentially the same as in transf.hs; no liftIO though c2 = runTrace $ runReader (loop =<< runC th2) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> k () >>= loop loop Done = trace "Done" {- 10 10 Done -} -- locally changing the dynamic environment for the suspension c21 = runTrace $ runReader (loop =<< runC th2) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> local (+(1::Int)) (k ()) >>= loop loop Done = trace "Done" {- 10 11 Done -} -- Real example, with two sorts of local rebinding th3 :: (Member (Yield Int ()) r, Member (Reader Int) r) => Eff r () th3 = ay >> ay >> local (+(10::Int)) (ay >> ay) where ay = ask >>= yieldInt c3 = runTrace $ runReader (loop =<< runC th3) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> k () >>= loop loop Done = trace "Done" {- 10 10 20 20 Done -} -- locally changing the dynamic environment for the suspension c31 = runTrace $ runReader (loop =<< runC th3) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> local (+(1::Int)) (k ()) >>= loop loop Done = trace "Done" {- 10 11 21 21 Done -} -- The result is exactly as expected and desired: the coroutine shares the -- dynamic environment with its parent; however, when the environment -- is locally rebound, it becomes private to coroutine. -- We now make explicit that the client computation, run by th4, -- is abstract. We abstract it out of th4 c4 = runTrace $ runReader (loop =<< runC (th4 client)) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> local (+(1::Int)) (k ()) >>= loop loop Done = trace "Done" -- cl, client, ay are monomorphic bindings th4 cl = cl >> local (+(10::Int)) cl client = ay >> ay ay = ask >>= yieldInt {- 10 11 21 21 Done -} -- Even more dynamic example c5 = runTrace $ runReader (loop =<< runC (th client)) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> local (\y->x+1) (k ()) >>= loop loop Done = trace "Done" -- cl, client, ay are monomorphic bindings client = ay >> ay >> ay ay = ask >>= yieldInt -- There is no polymorphic recursion here th cl = do cl v <- ask (if v > (20::Int) then id else local (+(5::Int))) cl if v > (20::Int) then return () else local (+(10::Int)) (th cl) {- 10 11 12 18 18 18 29 29 29 29 29 29 Done -} -- And even more c7 = runTrace $ runReader (runReader (loop =<< runC (th client)) (10::Int)) (1000::Double) where loop (Y x k) = trace (show (x::Int)) >> local (\y->fromIntegral (x+1)::Double) (k ()) >>= loop loop Done = trace "Done" -- cl, client, ay are monomorphic bindings client = ay >> ay >> ay ay = ask >>= \x -> ask >>= \y -> yieldInt (x + round (y::Double)) -- There is no polymorphic recursion here th cl = do cl v <- ask (if v > (20::Int) then id else local (+(5::Int))) cl if v > (20::Int) then return () else local (+(10::Int)) (th cl) {- 1010 1021 1032 1048 1064 1080 1101 1122 1143 1169 1195 1221 1252 1283 1314 1345 1376 1407 Done -} c7' = runTrace $ runReader (runReader (loop =<< runC (th client)) (10::Int)) (1000::Double) where loop (Y x k) = trace (show (x::Int)) >> local (\y->fromIntegral (x+1)::Double) (k ()) >>= loop loop Done = trace "Done" -- cl, client, ay are monomorphic bindings client = ay >> ay >> ay ay = ask >>= \x -> ask >>= \y -> yieldInt (x + round (y::Double)) -- There is no polymorphic recursion here th cl = do cl v <- ask (if v > (20::Int) then id else local (+(5::Double))) cl if v > (20::Int) then return () else local (+(10::Int)) (th cl) {- 1010 1021 1032 1048 1048 1048 1069 1090 1111 1137 1137 1137 1168 1199 1230 1261 1292 1323 Done -} -- ------------------------------------------------------------------------ -- An example of non-trivial interaction of effects, handling of two -- effects together -- Non-determinism with control (cut) -- For the explanation of cut, see Section 5 of Hinze ICFP 2000 paper. -- Hinze suggests expressing cut in terms of cutfalse -- ! = return () `mplus` cutfalse -- where -- cutfalse :: m a -- satisfies the following laws -- cutfalse >>= k = cutfalse (F1) -- cutfalse | m = cutfalse (F2) -- (note: m `mplus` cutfalse is different from cutfalse `mplus` m) -- In other words, cutfalse is the left zero of both bind and mplus. -- -- Hinze also introduces the operation call :: m a -> m a that -- delimits the effect of cut: call m executes m. If the cut is -- invoked in m, it discards only the choices made since m was called. -- Hinze postulates the axioms of call: -- -- call false = false (C1) -- call (return a | m) = return a | call m (C2) -- call (m | cutfalse) = call m (C3) -- call (lift m >>= k) = lift m >>= (call . k) (C4) -- -- call m behaves like m except any cut inside m has only a local effect, -- he says. -- Hinze noted a problem with the `mechanical' derivation of backtracing -- monad transformer with cut: no axiom specifying the interaction of -- call with bind; no way to simplify nested invocations of call. -- We use exceptions for cutfalse -- Therefore, the law ``cutfalse >>= k = cutfalse'' -- is satisfied automatically since all exceptions have the above property. data CutFalse = CutFalse deriving Typeable cutfalse = throwError CutFalse -- The interpreter -- it is like reify . reflect with a twist -- Compare this implementation with the huge implementation of call -- in Hinze 2000 (Figure 9) -- Each clause corresponds to the axiom of call or cutfalse. -- All axioms are covered. -- The code clearly expresses the intuition that call watches the choice points -- of its argument computation. When it encounteres a cutfalse request, -- it discards the remaining choicepoints. -- It completely handles CutFalse effects but not non-determinism call :: Member Choose r => Eff (Exc CutFalse :> r) a -> Eff r a call m = loop [] (admin m) where loop jq (Val x) = return x `mplus'` next jq -- (C2) loop jq (E u) = case decomp u of Right (Exc CutFalse) -> mzero' -- drop jq (F2) Left u -> check jq u check jq u | Just (Choose [] _) <- prj u = next jq -- (C1) check jq u | Just (Choose [x] k) <- prj u = loop jq (k x) -- (C3), optim check jq u | Just (Choose lst k) <- prj u = next $ map k lst ++ jq -- (C3) check jq u = send (\k -> fmap k u) >>= loop jq -- (C4) next [] = mzero' next (h:t) = loop t h -- The signature is inferred tcut1 :: (Member Choose r, Member (Exc CutFalse) r) => Eff r Int tcut1 = (return (1::Int) `mplus'` return 2) `mplus'` ((cutfalse `mplus'` return 4) `mplus'` return 5) tcut1r = run . makeChoice $ call tcut1 -- [1,2] tcut2 = return (1::Int) `mplus'` call (return 2 `mplus'` (cutfalse `mplus'` return 3) `mplus'` return 4) `mplus'` return 5 -- Here we see nested call. It poses no problems... tcut2r = run . makeChoice $ call tcut2 -- [1,2,5] -- More nested calls tcut3 = call tcut1 `mplus'` call (tcut2 `mplus'` cutfalse) tcut3r = run . makeChoice $ call tcut3 -- [1,2,1,2,5] tcut4 = call tcut1 `mplus'` (tcut2 `mplus'` cutfalse) tcut4r = run . makeChoice $ call tcut4 -- [1,2,1,2,5] -}
iu-parfunc/AutoObsidian
interface_brainstorming/06_ExtensibleEffects/newVer/Eff1.hs
Haskell
bsd-3-clause
32,804
module Common.NonBlockingQueueSpec (main, spec) where import Test.Hspec import Test.QuickCheck import qualified PolyGraph.Common.NonBlockingQueue.Properties as QProp spec :: Spec spec = do describe "NonBlockingQueue" $ do it "isFifo" $ property $ (QProp.isFifo :: [QProp.QueueInstruction Int] -> Bool) it "dequeues with something unless queue is empty" $ property $ (QProp.dequeuesUnlessEmpty :: [QProp.QueueInstruction Int] -> Bool) main :: IO () main = hspec spec
rpeszek/GraphPlay
test/Common/NonBlockingQueueSpec.hs
Haskell
bsd-3-clause
500
module D_Types where import Data.Word import Data.Int import Data.ByteString.Lazy import Data.Binary.Get data TypeDesc = TD (Int, String, [FieldDescTest], [TypeDesc]) -- id, name, fieldDescs, subtypes type FieldDesc = (String, [Something]) --name, data type FieldDescTest = (String, [Something], ByteString) --name, data, rawData type FieldData = ByteString type Pointer = (Int, Int) -- skill name 'Annotation' type UserType = String data Something = CInt8 Int8 -- 0 | CInt16 Int16 -- 1 | CInt32 Int32 -- 2 | CInt64 Int64 -- 3 | CV64 Int64 -- 4 | GPointer Pointer -- 5 | GBool Bool -- 6 | GInt8 Int8 -- 7 | GInt16 Int16 -- 8 | GInt32 Int32 -- 9 | GInt64 Int64 -- 10 | GV64 Int64 -- 11 | GFloat Float -- 12 | GDouble Double -- 13 | GString String -- 14 | GFArray [Something] -- 15 | GVArray [Something] -- 17 | GList [Something] -- 18 | GSet [Something] -- 19 | GMap [(Something, Something)] -- 20 | GUserType Int Int deriving (Show)
skill-lang/skill
src/main/resources/haskell/D_Types.hs
Haskell
bsd-3-clause
1,599
module Data.GeoJSON ( module Data.GeoJSON.Classes , module Data.GeoJSON.Position , module Data.GeoJSON.Geometries , module Data.GeoJSON.Features ) where import Data.GeoJSON.Classes import Data.GeoJSON.Features import Data.GeoJSON.Geometries import Data.GeoJSON.Position
alios/geojson-types
src/Data/GeoJSON.hs
Haskell
bsd-3-clause
316
{-# OPTIONS -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances #-} module Fay.Exts.NoAnnotation where import Fay.Compiler.Prelude import Data.List.Split (splitOn) import Data.String import qualified Language.Haskell.Exts.Annotated as A type Alt = A.Alt () type BangType = A.BangType () type ClassDecl = A.ClassDecl () type Decl = A.Decl () type DeclHead = A.DeclHead () type Ex = A.Exp () type Exp = A.Exp () type ExportSpec = A.ExportSpec () type FieldDecl = A.FieldDecl () type FieldUpdate = A.FieldUpdate () type GadtDecl = A.GadtDecl () type GuardedRhs = A.GuardedRhs () type ImportDecl = A.ImportDecl () type ImportSpec = A.ImportSpec () type Literal = A.Literal () type Match = A.Match () type Module = A.Module () type ModuleName = A.ModuleName () type ModulePragma = A.ModulePragma () type Name = A.Name () type Pat = A.Pat () type PatField = A.PatField () type QName = A.QName () type QOp = A.QOp () type QualConDecl = A.QualConDecl () type QualStmt = A.QualStmt () type Rhs = A.Rhs () type Sign = A.Sign () type SpecialCon = A.SpecialCon () type SrcLoc = A.SrcLoc type SrcSpan = A.SrcSpan type SrcSpanInfo = A.SrcSpanInfo type Stmt = A.Stmt () type TyVarBind = A.TyVarBind () type Type = A.Type () unAnn :: Functor f => f a -> f () unAnn = void -- | Helpful for some things. instance IsString (A.Name ()) where fromString n@(c:_) | isAlpha c || c == '_' = A.Ident () n | otherwise = A.Symbol () n fromString [] = error "Name fromString: empty string" -- | Helpful for some things. instance IsString (A.QName ()) where fromString s = case splitOn "." s of [] -> error "QName fromString: empty string" [x] -> A.UnQual () $ fromString x xs -> A.Qual () (fromString $ intercalate "." $ init xs) $ fromString (last xs) -- | Helpful for writing qualified symbols (Fay.*). instance IsString (A.ModuleName ()) where fromString = A.ModuleName ()
beni55/fay
src/Fay/Exts/NoAnnotation.hs
Haskell
bsd-3-clause
1,946
{-# LANGUAGE OverloadedStrings #-} module Bead.View.Content.Notifications.Page ( notifications ) where import Control.Monad (forM_) import Data.String (fromString) import Text.Printf (printf) import qualified Bead.Controller.Pages as Pages import Bead.View.Content import Bead.Domain.Entity.Notification import qualified Bead.View.Content.Bootstrap as Bootstrap import qualified Bead.Controller.UserStories as Story (notifications) import Text.Blaze.Html5 as H hiding (link, map) data PageData = PageData { pdNotifications :: [(Notification, NotificationState, NotificationReference)] , pdUserTime :: UserTimeConverter } notifications :: ViewHandler notifications = ViewHandler notificationsPage notificationsPage :: GETContentHandler notificationsPage = do pd <- PageData <$> (userStory Story.notifications) <*> userTimeZoneToLocalTimeConverter return $ notificationsContent pd notificationsContent :: PageData -> IHtml notificationsContent p = do msg <- getI18N return $ do let notifs = pdNotifications p if (null notifs) then do H.p $ fromString $ msg $ msg_Notifications_NoNotifications "There are no notifications." else do Bootstrap.row $ Bootstrap.colMd12 $ do Bootstrap.listGroup $ forM_ notifs $ \(notif, state, ref) -> (if state == Seen then Bootstrap.listGroupLinkItem else Bootstrap.listGroupAlertLinkItem Bootstrap.Info ) (linkFromNotif ref) . fromString $ unwords [ "[" ++ (showDate . pdUserTime p $ notifDate notif) ++ "]" , translateEvent msg $ notifEvent notif ] linkFromNotif :: NotificationReference -> String linkFromNotif = notificationReference (\ak sk ck -> routeWithAnchor (Pages.submissionDetails ak sk ()) ck) (\ak sk _ek -> routeWithAnchor (Pages.submissionDetails ak sk ()) SubmissionDetailsEvaluationDiv) (\sk _ek -> routeOf $ Pages.viewUserScore sk ()) (\ak -> routeOf $ Pages.submissionList ak ()) (\ak -> routeOf $ Pages.viewAssessment ak ()) (routeOf $ Pages.notifications ()) -- System notifications are one liners -- Resolve a notification event to an actual message through the I18N layer. translateEvent :: I18N -> NotificationEvent -> String translateEvent i18n e = case e of NE_CourseAdminCreated course -> printf (i18n $ msg_NE_CourseAdminCreated "A course has been assigned: %s") course NE_CourseAdminAssigned course assignee -> printf (i18n $ msg_NE_CourseAdminAssigned "An administrator has been added to course \"%s\": %s") course assignee NE_TestScriptCreated creator course -> printf (i18n $ msg_NE_TestScriptCreated "%s created a new test script for course \"%s\"") creator course NE_TestScriptUpdated editor script course -> printf (i18n $ msg_NE_TestScriptUpdated "%s modified test script \"%s\" for course \"%s\"") editor script course NE_RemovedFromGroup group deletor -> printf (i18n $ msg_NE_RemovedFromGroup "Removed from group \"%s\" by %s") group deletor NE_GroupAdminCreated course creator group -> printf (i18n $ msg_NE_GroupAdminCreated "A group of course \"%s\" has been assigned by %s: %s") course creator group NE_GroupAssigned group course assignor assignee -> printf (i18n $ msg_NE_GroupAssigned "Group \"%s\" of course \"%s\" has been assigned to %s by %s") group course assignor assignee NE_GroupCreated course creator group -> printf (i18n $ msg_NE_GroupCreated "A group has been created for course \"%s\" by %s: %s") course creator group NE_GroupAssignmentCreated creator group course assignment -> printf (i18n $ msg_NE_GroupAssignmentCreated "%s created a new assignment for group \"%s\" (\"%s\"): %s") creator group course assignment NE_CourseAssignmentCreated creator course assignment -> printf (i18n $ msg_NE_CourseAssignmentCreated "%s created a new assignment for course \"%s\": %s") creator course assignment NE_GroupAssessmentCreated creator group course assessment -> printf (i18n $ msg_NE_GroupAssessmentCreated "%s created a new assessment for group \"%s\" (\"%s\"): %s") creator group course assessment NE_CourseAssessmentCreated creator course assessment -> printf (i18n $ msg_NE_CourseAssessmentCreated "%s created a new assessment for course \"%s\": %s") creator course assessment NE_AssessmentUpdated editor assessment -> printf (i18n $ msg_NE_AssessmentUpdated "%s modified assessment: %s") editor assessment NE_AssignmentUpdated editor assignment -> printf (i18n $ msg_NE_AssignmentUpdated "%s modified assignment: %s") editor assignment NE_EvaluationCreated evaluator submission -> printf (i18n $ msg_NE_EvaluationCreated "%s evaluated submission: %s") evaluator submission NE_AssessmentEvaluationUpdated editor assessment -> printf (i18n $ msg_NE_AssessmentEvaluationUpdated "%s modified evaluation of score: %s") editor assessment NE_AssignmentEvaluationUpdated editor submission -> printf (i18n $ msg_NE_AssignmentEvaluationUpdated "%s modified evaluation of submission: %s") editor submission NE_CommentCreated commenter submission body -> printf (i18n $ msg_NE_CommentCreated "%s commented on submission %s: \"%s\"") commenter submission body
andorp/bead
src/Bead/View/Content/Notifications/Page.hs
Haskell
bsd-3-clause
5,478
{-# LANGUAGE FlexibleContexts, OverloadedStrings, RecordWildCards, ScopedTypeVariables, ConstraintKinds, PatternGuards #-} -- |The HTTP/JSON plumbing used to implement the 'WD' monad. -- -- These functions can be used to create your own 'WebDriver' instances, providing extra functionality for your application if desired. All exports -- of this module are subject to change at any point. module Test.WebDriver.Internal ( mkRequest, sendHTTPRequest , getJSONResult, handleJSONErr, handleRespSessionId , WDResponse(..) ) where import Test.WebDriver.Class import Test.WebDriver.JSON import Test.WebDriver.Session import Test.WebDriver.Exceptions.Internal import Network.HTTP.Client (httpLbs, Request(..), RequestBody(..), Response(..), HttpException(ResponseTimeout)) import Network.HTTP.Types.Header import Network.HTTP.Types.Status (Status(..)) import Data.Aeson import Data.Aeson.Types (typeMismatch) import Data.Text as T (Text, splitOn, null) import qualified Data.Text.Encoding as TE import Data.ByteString.Lazy.Char8 (ByteString) import Data.ByteString.Lazy.Char8 as LBS (length, unpack, null, fromStrict) import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Base64.Lazy as B64 import Control.Monad.Base import Control.Exception.Lifted (throwIO) import Control.Applicative import Control.Exception (Exception, SomeException(..), toException, fromException, try) import Data.String (fromString) import Data.Word (Word8) import Data.Default.Class import Prelude -- hides some "unused import" warnings -- |Constructs an HTTP 'Request' value when given a list of headers, HTTP request method, and URL fragment mkRequest :: (WDSessionState s, ToJSON a) => Method -> Text -> a -> s Request mkRequest meth wdPath args = do WDSession {..} <- getSession let body = case toJSON args of Null -> "" --passing Null as the argument indicates no request body other -> encode other return def { host = wdSessHost , port = wdSessPort , path = wdSessBasePath `BS.append` TE.encodeUtf8 wdPath , requestBody = RequestBodyLBS body , requestHeaders = wdSessRequestHeaders ++ [ (hAccept, "application/json;charset=UTF-8") , (hContentType, "application/json;charset=UTF-8") , (hContentLength, fromString . show . LBS.length $ body) ] , checkStatus = \_ _ _ -> Nothing -- all status codes handled by getJSONResult , method = meth } -- |Sends an HTTP request to the remote WebDriver server sendHTTPRequest :: (WDSessionStateIO s) => Request -> s (Either SomeException (Response ByteString)) sendHTTPRequest req = do s@WDSession{..} <- getSession (nRetries, tryRes) <- liftBase . retryOnTimeout wdSessHTTPRetryCount $ httpLbs req wdSessHTTPManager let h = SessionHistory { histRequest = req , histResponse = tryRes , histRetryCount = nRetries } putSession s { wdSessHist = wdSessHistUpdate h wdSessHist } return tryRes retryOnTimeout :: Int -> IO a -> IO (Int, (Either SomeException a)) retryOnTimeout maxRetry go = retry' 0 where retry' nRetries = do eitherV <- try go case eitherV of (Left e) | Just ResponseTimeout <- fromException e , maxRetry > nRetries -> retry' (succ nRetries) other -> return (nRetries, other) -- |Parses a 'WDResponse' object from a given HTTP response. getJSONResult :: (WDSessionStateControl s, FromJSON a) => Response ByteString -> s (Either SomeException a) getJSONResult r --malformed request errors | code >= 400 && code < 500 = do lastReq <- mostRecentHTTPRequest <$> getSession returnErr . UnknownCommand . maybe reason show $ lastReq --server-side errors | code >= 500 && code < 600 = case lookup hContentType headers of Just ct | "application/json" `BS.isInfixOf` ct -> parseJSON' (maybe body LBS.fromStrict $ lookup "X-Response-Body-Start" headers) >>= handleJSONErr >>= maybe noReturn returnErr | otherwise -> returnHTTPErr ServerError Nothing -> returnHTTPErr (ServerError . ("HTTP response missing content type. Server reason was: "++)) --redirect case (used as a response to createSession requests) | code == 302 || code == 303 = case lookup hLocation headers of Nothing -> returnErr . HTTPStatusUnknown code $ LBS.unpack body Just loc -> do let sessId = last . filter (not . T.null) . splitOn "/" . fromString $ BS.unpack loc modifySession $ \sess -> sess {wdSessId = Just (SessionId sessId)} noReturn -- No Content response | code == 204 = noReturn -- HTTP Success | code >= 200 && code < 300 = if LBS.null body then noReturn else do rsp@WDResponse {rspVal = val} <- parseJSON' body handleJSONErr rsp >>= maybe (handleRespSessionId rsp >> Right <$> fromJSON' val) returnErr -- other status codes: return error | otherwise = returnHTTPErr (HTTPStatusUnknown code) where --helper functions returnErr :: (Exception e, Monad m) => e -> m (Either SomeException a) returnErr = return . Left . toException returnHTTPErr errType = returnErr . errType $ reason noReturn = Right <$> fromJSON' Null --HTTP response variables code = statusCode status reason = BS.unpack $ statusMessage status status = responseStatus r body = responseBody r headers = responseHeaders r handleRespSessionId :: (WDSessionStateIO s) => WDResponse -> s () handleRespSessionId WDResponse{rspSessId = sessId'} = do sess@WDSession { wdSessId = sessId} <- getSession case (sessId, (==) <$> sessId <*> sessId') of -- if our monad has an uninitialized session ID, initialize it from the response object (Nothing, _) -> putSession sess { wdSessId = sessId' } -- if the response ID doesn't match our local ID, throw an error. (_, Just False) -> throwIO . ServerError $ "Server response session ID (" ++ show sessId' ++ ") does not match local session ID (" ++ show sessId ++ ")" _ -> return () handleJSONErr :: (WDSessionStateControl s) => WDResponse -> s (Maybe SomeException) handleJSONErr WDResponse{rspStatus = 0} = return Nothing handleJSONErr WDResponse{rspVal = val, rspStatus = status} = do sess <- getSession errInfo <- fromJSON' val let screen = B64.decodeLenient <$> errScreen errInfo errInfo' = errInfo { errSess = Just sess , errScreen = screen } e errType = toException $ FailedCommand errType errInfo' return . Just $ case status of 7 -> e NoSuchElement 8 -> e NoSuchFrame 9 -> toException . UnknownCommand . errMsg $ errInfo 10 -> e StaleElementReference 11 -> e ElementNotVisible 12 -> e InvalidElementState 13 -> e UnknownError 15 -> e ElementIsNotSelectable 17 -> e JavascriptError 19 -> e XPathLookupError 21 -> e Timeout 23 -> e NoSuchWindow 24 -> e InvalidCookieDomain 25 -> e UnableToSetCookie 26 -> e UnexpectedAlertOpen 27 -> e NoAlertOpen 28 -> e ScriptTimeout 29 -> e InvalidElementCoordinates 30 -> e IMENotAvailable 31 -> e IMEEngineActivationFailed 32 -> e InvalidSelector 33 -> e SessionNotCreated 34 -> e MoveTargetOutOfBounds 51 -> e InvalidXPathSelector 52 -> e InvalidXPathSelectorReturnType _ -> e UnknownError -- |Internal type representing the JSON response object data WDResponse = WDResponse { rspSessId :: Maybe SessionId , rspStatus :: Word8 , rspVal :: Value } deriving (Eq, Show) instance FromJSON WDResponse where parseJSON (Object o) = WDResponse <$> o .:?? "sessionId" .!= Nothing <*> o .: "status" <*> o .:?? "value" .!= Null parseJSON v = typeMismatch "WDResponse" v
wuzzeb/hs-webdriver
src/Test/WebDriver/Internal.hs
Haskell
bsd-3-clause
8,292
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE BangPatterns #-} module Constraints.Set.Implementation ( ConstraintError(..), Variance(..), Inclusion, SetExpression(..), SolvedSystem, emptySet, universalSet, setVariable, atom, term, (<=!), solveSystem, leastSolution ) where import Control.Exception import Control.Failure import qualified Data.Foldable as F import Data.Function ( on ) import qualified Data.List as L import Data.Map ( Map ) import qualified Data.Map as M import Data.Maybe ( fromMaybe ) import Data.Monoid import Data.Set ( Set ) import qualified Data.Set as S import Data.Typeable type Worklist v c = Set (PredSegment v c) -- | The type used to represent that inductive form constraint graph -- during saturation. This form is more efficient to saturate. type IFGraph v c = Map (SetExpression v c) (Edges v c) data Edges v c = Edges { predecessors :: Set (SetExpression v c) , successors :: Set (SetExpression v c) } deriving (Eq, Ord) -- | The solved constraint system data SolvedSystem v c = SolvedSystem { systemIFGraph :: IFGraph v c } instance (Eq v, Eq c) => Eq (SolvedSystem v c) where (==) = (==) `on` systemIFGraph -- | A type describing an edge added in one iteration of the -- transitive closure. These let us know which nodes need to be -- revisited in the next iteration (and in which direction - -- predecessor or successor) data PredSegment v c = PSPred (SetExpression v c) (SetExpression v c) | PSSucc (SetExpression v c) (SetExpression v c) deriving (Eq, Ord) -- | Create a set expression representing the empty set emptySet :: SetExpression v c emptySet = EmptySet -- | Create a set expression representing the universal set universalSet :: SetExpression v c universalSet = UniversalSet -- | Create a new set variable with the given label setVariable :: (Ord v) => v -> SetExpression v c setVariable = SetVariable -- | Atomic terms have a label and arity zero. This is a shortcut for -- -- > term conLabel [] [] atom :: (Ord c) => c -> SetExpression v c atom conLabel = ConstructedTerm conLabel [] [] -- | This returns a function to create terms from lists of -- SetExpressions. It is meant to be partially applied so that as -- many terms as possible can share the same reference to a label and -- signature. -- -- The list of variances specifies the variance (Covariant or -- Contravariant) for each argument of the term. A mismatch in the -- length of the variance descriptor and the arguments to the term -- will result in a run-time error. term :: (Ord v, Ord c) => c -> [Variance] -> ([SetExpression v c] -> SetExpression v c) term = ConstructedTerm -- | Construct an inclusion relation between two set expressions. -- -- This is equivalent to @se1 ⊆ se2@. (<=!) :: (Ord c, Ord v) => SetExpression v c -> SetExpression v c -> Inclusion v c (<=!) = Inclusion -- | Tags to mark term arguments as covariant or contravariant. data Variance = Covariant | Contravariant deriving (Eq, Ord, Show) -- | Expressions in the language of set constraints. data SetExpression v c = EmptySet | UniversalSet | SetVariable v | ConstructedTerm c [Variance] [SetExpression v c] deriving (Eq, Ord) instance (Show v, Show c) => Show (SetExpression v c) where show EmptySet = "∅" show UniversalSet = "U" show (SetVariable v) = show v show (ConstructedTerm c _ es) = concat [ show c, "(" , L.intercalate ", " (map show es) , ")" ] -- | An inclusion is a constraint of the form @se1 ⊆ se2@ data Inclusion v c = Inclusion (SetExpression v c) (SetExpression v c) deriving (Eq, Ord) instance (Show v, Show c) => Show (Inclusion v c) where show (Inclusion lhs rhs) = concat [ show lhs, " ⊆ ", show rhs ] -- | The types of errors that can be encountered during constraint -- resolution data ConstraintError v c = NoSolution (Inclusion v c) -- ^ The system has no solution because of the given inclusion constraint | NoVariableLabel v -- ^ When searching for a solution, the requested variable was not present in the constraint graph deriving (Eq, Ord, Show, Typeable) instance (Typeable v, Typeable c, Show v, Show c) => Exception (ConstraintError v c) -- | Simplify one set expression. The expression may be eliminated, -- passed through unchanged, or split into multiple new expressions. simplifyInclusion :: (Ord c, Ord v, Eq v, Eq c) => Inclusion v c -- ^ The inclusion to be simplified -> [Inclusion v c] simplifyInclusion i = case i of -- Eliminate constraints of the form A ⊆ A Inclusion (SetVariable v1) (SetVariable v2) -> if v1 == v2 then [] else [i] Inclusion UniversalSet EmptySet -> error "Malformed constraint univ < emptyset" Inclusion (ConstructedTerm c1 s1 ses1) (ConstructedTerm c2 s2 ses2) -> let sigLen = length s1 triples = zip3 s1 ses1 ses2 in case c1 == c2 && s1 == s2 && sigLen == length ses1 && sigLen == length ses2 of False -> error "Malformed constraint cterm mismatch" True -> concatMap simplifyWithVariance triples Inclusion UniversalSet (ConstructedTerm _ _ _) -> error "Malformed constraint univ < cterm" Inclusion (ConstructedTerm _ _ _) EmptySet -> error "Malformed constraint cterm < emptyset" -- Eliminate constraints of the form A ⊆ 1 Inclusion _ UniversalSet -> [] -- 0 ⊆ A Inclusion EmptySet _ -> [] -- Keep anything else (atomic forms) _ -> [i] -- | Simplifies an inclusion taking variance into account; this is a -- helper for 'simplifyInclusion' that deals with the variance of -- constructed terms. The key here is that contravariant inclusions -- are /flipped/. simplifyWithVariance :: (Ord c, Ord v, Eq v, Eq c) => (Variance, SetExpression v c, SetExpression v c) -> [Inclusion v c] simplifyWithVariance (Covariant, se1, se2) = simplifyInclusion (Inclusion se1 se2) simplifyWithVariance (Contravariant, se1, se2) = simplifyInclusion (Inclusion se2 se1) -- | Simplify all of the inclusions in the initial constraint system. simplifySystem :: (Ord c, Ord v, Eq v, Eq c) => [Inclusion v c] -> [Inclusion v c] simplifySystem = concatMap simplifyInclusion dfs :: (Ord c, Ord v) => IFGraph v c -> SetExpression v c -> Set (SetExpression v c) dfs g = go mempty where go !visited v | S.member v visited = visited | otherwise = case M.lookup v g of Nothing -> S.insert v visited Just Edges { predecessors = ps } -> F.foldl' go (S.insert v visited) ps -- | Compute the least solution for the given variable. This can fail -- if the requested variable is not present in the constraint system -- (see 'ConstraintError'). -- -- LS(y) = All source nodes with a predecessor edge to y, plus LS(x) -- for all x where x has a predecessor edge to y. leastSolution :: (Failure (ConstraintError v c) m, Ord v, Ord c) => SolvedSystem v c -> v -> m [SetExpression v c] leastSolution (SolvedSystem g0) varLabel = do let reached = dfs g0 (SetVariable varLabel) return $ F.foldr addTerm [] reached where -- ex :: ConstraintError v c -- ex = NoVariableLabel varLabel addTerm v acc = case v of ConstructedTerm _ _ _ -> v : acc _ -> acc -- | Simplify and solve the system of set constraints solveSystem :: (Failure (ConstraintError v c) m, Eq c, Eq v, Ord c, Ord v) => [Inclusion v c] -> m (SolvedSystem v c) solveSystem = return . constraintsToIFGraph . simplifySystem -- | The real worker to solve the system and convert from an IFGraph -- to a SolvedGraph. constraintsToIFGraph :: (Ord v, Ord c) => [Inclusion v c] -> SolvedSystem v c constraintsToIFGraph is = SolvedSystem { systemIFGraph = saturateGraph g0 wl } where (g0, wl) = buildInitialGraph is -- | Build an initial IF constraint graph that contains all of the -- vertices and the edges induced by the initial simplified constraint -- system. buildInitialGraph :: (Ord v, Ord c) => [Inclusion v c] -> (IFGraph v c, Worklist v c) buildInitialGraph is = L.foldl' addInclusion (mempty, mempty) is -- | Adds an inclusion to the constraint graph (adding vertices if -- necessary). Returns the set of nodes that are affected (and will -- need more transitive edges). addInclusion :: (Eq c, Ord v, Ord c) => (IFGraph v c, Worklist v c) -> Inclusion v c -> (IFGraph v c, Worklist v c) addInclusion acc i = case i of -- This is the key to an inductive form graph (rather than -- standard form) Inclusion e1@(SetVariable v1) e2@(SetVariable v2) | v1 < v2 -> addSuccEdge acc e1 e2 | otherwise -> addPredEdge acc e1 e2 Inclusion e1@(ConstructedTerm _ _ _) e2@(SetVariable _) -> addPredEdge acc e1 e2 Inclusion e1@(SetVariable _) e2@(ConstructedTerm _ _ _) -> addSuccEdge acc e1 e2 _ -> error "Constraints.Set.Solver.addInclusion: unexpected expression" -- | Add a predecessor edge (l is a predecessor of r) addPredEdge :: (Ord c, Ord v) => (IFGraph v c, Worklist v c) -> SetExpression v c -> SetExpression v c -> (IFGraph v c, Worklist v c) addPredEdge acc@(!g, !work) l r = case M.lookup r g of Nothing -> let es = Edges { predecessors = S.singleton l, successors = S.empty } in (M.insert r es g, S.insert (PSPred l r) work) Just es | S.member l (predecessors es) -> acc | otherwise -> let es' = es { predecessors = S.insert l (predecessors es) } in (M.insert r es' g, S.insert (PSPred l r) work) addSuccEdge :: (Ord c, Ord v) => (IFGraph v c, Worklist v c) -> SetExpression v c -> SetExpression v c -> (IFGraph v c, Worklist v c) addSuccEdge acc@(!g, !work) l r = case M.lookup l g of Nothing -> let es = Edges { predecessors = S.empty, successors = S.singleton r } in (M.insert l es g, S.insert (PSSucc l r) work) Just es | S.member r (successors es) -> acc | otherwise -> let es' = es { successors = S.insert r (successors es) } in (M.insert l es' g, S.insert (PSSucc l r) work) -- | For each node L in the graph, follow its predecessor edges to -- obtain set X. For each ndoe in X, follow its successor edges -- giving a list of R. Generate L ⊆ R and simplify it with -- 'simplifyInclusion'. These are new edges (collect them all in a -- set, discarding existing edges). -- -- After a pass, insert all of the new edges -- -- Repeat until no new edges are found. -- -- An easy optimization is to base the next iteration only on the -- newly-added edges (since any additions in the next iteration must -- be due to those new edges). It would require searching forward -- (for pred edges) and backward (for succ edges). -- -- Also perform online cycle detection per FFSA98 -- -- This function can fail if a constraint generated by the saturation -- implies that no solution is possible. I think that probably -- shouldn't ever happen but I have no proof. saturateGraph :: (Ord v, Ord c, Eq c) => IFGraph v c -> Worklist v c -> IFGraph v c saturateGraph g0 wl0 = let (g1, wl1) = F.foldl' addNewEdges (g0, mempty) wl0 in if S.null wl1 then g1 else saturateGraph g1 wl1 addNewEdges :: (Ord v, Ord c) => (IFGraph v c, Worklist v c) -> PredSegment v c -> (IFGraph v c, Worklist v c) addNewEdges acc@(!g0, _) (PSPred l r) = fromMaybe acc $ do Edges { successors = ss } <- M.lookup r g0 return $ F.foldl' (addNewInclusions l) acc ss where addNewInclusions lhs a rhs = F.foldl' addInclusion a $ simplifyInclusion (Inclusion lhs rhs) addNewEdges acc@(!g0, _) (PSSucc l r) = fromMaybe acc $ do Edges { predecessors = ps } <- M.lookup l g0 return $ F.foldl' (addNewInclusions r) acc ps where addNewInclusions rhs a lhs = F.foldl' addInclusion a $ simplifyInclusion (Inclusion lhs rhs) -- Cycle detection {- -- Track both a visited set and a "the nodes on the cycle" set checkChain :: Bool -> ConstraintEdge -> IFGraph -> Int -> Int -> Maybe IntSet checkChain False _ _ _ _ = Nothing checkChain True tgt g from to = do chain <- snd $ checkChainWorker (mempty, Nothing) tgt g from to return $ IS.insert from chain -- Only checkChainWorker adds things to the visited set checkChainWorker :: (IntSet, Maybe IntSet) -> ConstraintEdge -> IFGraph -> Int -> Int -> (IntSet, Maybe IntSet) checkChainWorker (visited, chain) tgt g from to | from == to = (visited, Just (IS.singleton to)) | otherwise = let visited' = IS.insert from visited in G.foldPre (checkChainEdges tgt g to) (visited', chain) g from -- Once we have a branch of the DFS that succeeds, just keep that -- value. This manages augmenting the set of nodes on the chain checkChainEdges :: ConstraintEdge -> IFGraph -> Int -> Int -> ConstraintEdge -> (IntSet, Maybe IntSet) -> (IntSet, Maybe IntSet) checkChainEdges _ _ _ _ _ acc@(_, Just _) = acc checkChainEdges tgt g to v lbl acc@(visited, Nothing) | tgt /= lbl = acc | IS.member v visited = acc | otherwise = -- If there was no hit on this branch, just return the accumulator -- from the recursive call (which has an updated visited set) case checkChainWorker acc tgt g v to of acc'@(_, Nothing) -> acc' (visited', Just chain) -> (visited', Just (IS.insert v chain)) -- | Ask if we should bother to check for cycles this iteration checkCycles :: BuilderMonad v c Bool checkCycles = do BuilderState _ _ cnt <- get case cnt of Nothing -> return True Just c -> return $ c <= 1000 -- FIXME: Maybe try to mark nodes as "exhausted" after they can't induce -- any new edges? -- -- Also, perhaps use bitmasks instead of sets for something? -- | Try to detect cycles as in FFSA98. Note that this is currently -- broken somehow. It detects cycles just fine, but removing them -- seems to damage the constraint graph somehow making the solving -- phase much slower. tryCycleDetection :: (Ord c, Ord v) => Bool -> IFGraph -> Worklist -> ConstraintEdge -> Int -> Int -> BuilderMonad v c (IFGraph, Worklist) tryCycleDetection _ g2 affected Succ eid1 eid2 = simpleAddEdge g2 affected Succ eid1 eid2 tryCycleDetection removeCycles g2 affected etype eid1 eid2 = case checkChain removeCycles (otherLabel etype) g2 eid1 eid2 of Just chain | not (IS.null chain) -> do -- Make all of the nodes in the cycle refer to the min element -- (the reference bit is taken care of in the node lookup and in -- the result lookup). -- -- For each of the nodes in @rest@, repoint their incoming and -- outgoing edges. BuilderState m v c <- get -- Find all of the edges from any node pointing to a node in -- @rest@. Also find all edges from @rest@ out into the rest of -- the graph. Then resolve those back to inclusions using @v@ -- and call addInclusion over these new inclusions (after -- blowing away the old ones) let (representative, rest) = IS.deleteFindMin chain thisExp = V.unsafeIndex v representative newIncoming = IS.foldr' (srcsOf g2 v chain thisExp) [] rest newInclusions = IS.foldr' (destsOf g2 v chain thisExp) newIncoming rest g3 = IS.foldr' G.removeVertex g2 rest m' = IS.foldr' (replaceWith v representative) m rest put $! BuilderState m' v (fmap (+1) c) foldM (addInclusion False) (g3, affected) newInclusions -- `debug` -- ("Removing " ++ show (IS.size chain) ++ " cycle (" ++ show eid1 ++ -- " to " ++ show eid2 ++ "). " ++ show (CG.numNodes g3) ++ -- " nodes left in the graph.") -- Nothing was affected because we didn't add any edges _ -> simpleAddEdge g2 affected etype eid1 eid2 where otherLabel Succ = Pred otherLabel Pred = Succ srcsOf :: IFGraph -> Vector (SetExpression v c) -> IntSet -> SetExpression v c -> Int -> [Inclusion v c] -> [Inclusion v c] srcsOf g v chain newDst oldId acc = G.foldPre (\srcId _ a -> case IS.member srcId chain of True -> a False -> (V.unsafeIndex v srcId :<= newDst) : a) acc g oldId destsOf :: IFGraph -> Vector (SetExpression v c) -> IntSet -> SetExpression v c -> Int -> [Inclusion v c] -> [Inclusion v c] destsOf g v chain newSrc oldId acc = G.foldSuc (\dstId _ a -> case IS.member dstId chain of True -> a False -> (newSrc :<= V.unsafeIndex v dstId) : a) acc g oldId -- | Change the ID of the node with ID @i@ to @repr@ replaceWith :: (Ord k) => Vector k -> a -> Int -> Map k a -> Map k a replaceWith v repr i m = case M.lookup se m of Nothing -> m Just _ -> M.insert se repr m where se = V.unsafeIndex v i -}
travitch/ifscs
src/Constraints/Set/Implementation.hs
Haskell
bsd-3-clause
17,569
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} -- | Parses strings into a set of tokens using the given rules. module Youtan.Lexical.Tokenizer ( tokenize , tokenizeDrops , tokenizeT , tokenizeTDrops , Rules , Wrapper ) where import Control.Monad.State import Control.Monad.Except import Youtan.Regex.DFM ( DFM, fromString, longestMatchDFM ) -- | Represents a set of parsing rules. type Rules a = [ ( String, String -> a ) ] -- | Same as 'Rules' with prepared 'DFM' per each rule. data ParsingRules a = ParsingRules { dfm :: !DFM , matches :: ![ String -> a ] , rulesCount :: !Int } -- | Build 'DFM' per each rule. buildParingRules :: Rules a -> [ String ] -> ParsingRules a buildParingRules rules drops = ParsingRules { dfm = mconcat ( map fromString ( map fst rules ++ drops ) ) , matches = map snd rules , rulesCount = length rules } -- | Applies a set of parsing rules to split the input string -- into a set of tokens. tokenize :: MonadPlus m => Rules a -> String -> m a tokenize r = tokenizeDrops r [] -- | Monadic version of 'tokenize' wrappers errors into a monad. tokenizeT :: ( Wrapper w, MonadPlus m ) => Rules a -> String -> w ( m a ) tokenizeT rules = tokenizeTDrops rules [] -- | Applies a set of parsing rules to split the input string -- into a set of tokens. tokenizeDrops :: MonadPlus m => Rules a -> [ String ] -> String -> m a tokenizeDrops r d s = either error id ( tokenizeTDrops r d s ) -- | Monadic version of 'tokenize' wrappers errors into a monad. tokenizeTDrops :: ( Wrapper w, MonadPlus m ) => Rules a -> [ String ] -> String -> w ( m a ) tokenizeTDrops rules drops = evalStateT ( parse mzero ( buildParingRules rules drops ) ) -- | Shortcut for types. type P w a = StateT String w a -- | Shortcut for monad error. type Wrapper w = MonadError String w -- | Chooses the longest match and applis related modifier to it. choice :: Wrapper w => ParsingRules a -> P w ( Maybe a ) choice ParsingRules{..} = do inp <- get case longestMatchDFM dfm inp of Nothing -> failMessage Just ( x, mID ) -> if x > 0 then do modify ( drop x ) return $ if use mID then Just ( ( matches !! mID ) ( take x inp ) ) else Nothing else failMessage where use mDI = mDI < rulesCount failMessage = ( take 10 <$> get ) >>= throwError . (++) "All options failed " -- | Checks if the whole input is consumed. done :: Wrapper w => P w Bool done = null <$> get -- | Splits the input into a set of tokens. parse :: ( MonadPlus m, Wrapper w ) => m a -> ParsingRules a -> P w ( m a ) parse stack rules = do status <- done if status then return stack else do x <- choice rules case x of Just y -> parse ( mplus stack ( pure y ) ) rules Nothing -> parse stack rules
triplepointfive/Youtan
src/Youtan/Lexical/Tokenizer.hs
Haskell
bsd-3-clause
2,884
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RecordWildCards #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Distributed.Process.FSM.Internal.Process -- Copyright : (c) Tim Watson 2017 -- License : BSD3 (see the file LICENSE) -- -- Maintainer : Tim Watson <watson.timothy@gmail.com> -- Stability : experimental -- Portability : non-portable (requires concurrency) -- -- The /Managed Process/ implementation of an FSM process. -- -- See "Control.Distributed.Process.ManagedProcess". ----------------------------------------------------------------------------- module Control.Distributed.Process.FSM.Internal.Process ( start , run ) where import Control.Distributed.Process ( Process , ProcessId , SendPort , sendChan , spawnLocal , handleMessage , wrapMessage ) import qualified Control.Distributed.Process as P ( Message ) import Control.Distributed.Process.Extras (ExitReason) import Control.Distributed.Process.Extras.Time (Delay(Infinity)) import Control.Distributed.Process.FSM.Internal.Types hiding (liftIO) import Control.Distributed.Process.ManagedProcess ( ProcessDefinition(..) , PrioritisedProcessDefinition(filters) , Action , ProcessAction , InitHandler , InitResult(..) , DispatchFilter , ExitState(..) , defaultProcess , prioritised ) import qualified Control.Distributed.Process.ManagedProcess as MP (pserve) import Control.Distributed.Process.ManagedProcess.Server.Priority ( safely ) import Control.Distributed.Process.ManagedProcess.Server ( handleRaw , handleInfo , continue ) import Control.Distributed.Process.ManagedProcess.Internal.Types ( ExitSignalDispatcher(..) , DispatchPriority(PrioritiseInfo) ) import Control.Monad (void) import Data.Maybe (isJust) import qualified Data.Sequence as Q (empty) -- | Start an FSM process start :: forall s d . (Show s, Eq s) => s -> d -> (Step s d) -> Process ProcessId start s d p = spawnLocal $ run s d p -- | Run an FSM process. NB: this is a /managed process listen-loop/ -- and will not evaluate to its result until the server process stops. run :: forall s d . (Show s, Eq s) => s -> d -> (Step s d) -> Process () run s d p = MP.pserve (s, d, p) fsmInit (processDefinition p) fsmInit :: forall s d . (Show s, Eq s) => InitHandler (s, d, Step s d) (State s d) fsmInit (st, sd, prog) = let st' = State st sd prog Nothing (const $ return ()) Q.empty Q.empty in return $ InitOk st' Infinity processDefinition :: forall s d . (Show s) => Step s d -> PrioritisedProcessDefinition (State s d) processDefinition prog = (prioritised defaultProcess { infoHandlers = [ handleInfo handleRpcRawInputs , handleRaw handleAllRawInputs ] , exitHandlers = [ ExitSignalDispatcher (\s _ m -> handleExitReason s m) ] , shutdownHandler = handleShutdown } (walkPFSM prog [])) { filters = (walkFSM prog []) } -- we should probably make a Foldable (Step s d) for these walkFSM :: forall s d . Step s d -> [DispatchFilter (State s d)] -> [DispatchFilter (State s d)] walkFSM st acc | SafeWait evt act <- st = walkFSM act $ safely (\_ m -> isJust $ decodeToEvent evt m) : acc | Await _ act <- st = walkFSM act acc | Sequence ac1 ac2 <- st = walkFSM ac1 $ walkFSM ac2 acc | Init ac1 ac2 <- st = walkFSM ac1 $ walkFSM ac2 acc | Alternate ac1 ac2 <- st = walkFSM ac1 $ walkFSM ac2 acc -- both branches need filter defs | otherwise = acc walkPFSM :: forall s d . Step s d -> [DispatchPriority (State s d)] -> [DispatchPriority (State s d)] walkPFSM st acc | SafeWait evt act <- st = walkPFSM act (checkPrio evt acc) | Await evt act <- st = walkPFSM act (checkPrio evt acc) | Sequence ac1 ac2 <- st = walkPFSM ac1 $ walkPFSM ac2 acc | Init ac1 ac2 <- st = walkPFSM ac1 $ walkPFSM ac2 acc | Alternate ac1 ac2 <- st = walkPFSM ac1 $ walkPFSM ac2 acc -- both branches need filter defs | otherwise = acc where checkPrio ev acc' = (mkPrio ev):acc' mkPrio ev' = PrioritiseInfo $ \s m -> handleMessage m (resolveEvent ev' m s) handleRpcRawInputs :: forall s d . (Show s) => State s d -> (P.Message, SendPort P.Message) -> Action (State s d) handleRpcRawInputs st@State{..} (msg, port) = handleInput msg $ st { stReply = (sendChan port), stTrans = Q.empty, stInput = Just msg } handleAllRawInputs :: forall s d. (Show s) => State s d -> P.Message -> Action (State s d) handleAllRawInputs st@State{..} msg = handleInput msg $ st { stReply = noOp, stTrans = Q.empty, stInput = Just msg } handleExitReason :: forall s d. (Show s) => State s d -> P.Message -> Process (Maybe (ProcessAction (State s d))) handleExitReason st@State{..} msg = let st' = st { stReply = noOp, stTrans = Q.empty, stInput = Just msg } in tryHandleInput st' msg handleShutdown :: forall s d . ExitState (State s d) -> ExitReason -> Process () handleShutdown es er | (CleanShutdown s) <- es = shutdownAux s False | (LastKnown s) <- es = shutdownAux s True where shutdownAux st@State{..} ef = void $ tryHandleInput st (wrapMessage $ Stopping er ef) noOp :: P.Message -> Process () noOp = const $ return () handleInput :: forall s d . (Show s) => P.Message -> State s d -> Action (State s d) handleInput msg st = do res <- tryHandleInput st msg case res of Just act -> return act Nothing -> continue st tryHandleInput :: forall s d. (Show s) => State s d -> P.Message -> Process (Maybe (ProcessAction (State s d))) tryHandleInput st@State{..} msg = do res <- apply st msg stProg case res of Just res' -> applyTransitions res' [] >>= return . Just Nothing -> return Nothing
haskell-distributed/distributed-process-fsm
src/Control/Distributed/Process/FSM/Internal/Process.hs
Haskell
bsd-3-clause
6,071
module H99.Arithmetic where import Data.List {- Problem 31 (**) Determine whether a given integer number is prime. Example: * (is-prime 7) T Example in Haskell: P31> isPrime 7 True -} isPrime :: Int -> Bool isPrime n = n `elem` (take n primes) where primes = filterPrime [2..] filterPrime (x:xs) = x : filterPrime [x' | x' <- xs, x' `mod` x /= 0] {- Problem 32 (**) Determine the greatest common divisor of two positive integer numbers. Use Euclid's algorithm. Example: * (gcd 36 63) 9 Example in Haskell: [myGCD 36 63, myGCD (-3) (-6), myGCD (-3) 6] [9,3,3] -} myGCD :: Integral t => t -> t -> t myGCD a b | b == 0 = abs a | r == 0 = abs b | otherwise = myGCD b r where r = a `mod` b {- Problem 33 (*) Determine whether two positive integer numbers are coprime. Two numbers are coprime if their greatest common divisor equals 1. Example: * (coprime 35 64) T Example in Haskell: * coprime 35 64 True -} coprime :: Integral a => a -> a -> Bool coprime a b = myGCD a b == 1 {- Problem 34 (**) Calculate Euler's totient function phi(m). Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m. Example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1. Example: * (totient-phi 10) 4 Example in Haskell: * totient 10 4 -} totient :: Int -> Int totient 1 = 1 totient n = length $ filter (coprime n) [1..n-1] {- Problem 35 (**) Determine the prime factors of a given positive integer. Construct a flat list containing the prime factors in ascending order. Example: * (prime-factors 315) (3 3 5 7) Example in Haskell: > primeFactors 315 [3, 3, 5, 7] -} primeFactors :: Int -> [Int] primeFactors 1 = [] primeFactors n = spf : primeFactors (n `div` spf) where spf = smallestPrimeFactor primes n smallestPrimeFactor (p:ps) n = if n `mod` p == 0 then p else smallestPrimeFactor ps n primes = filterPrime [2..] filterPrime (x:xs) = x : filterPrime [x' | x' <- xs, x' `mod` x /= 0] primeFactors _ = error "invalid input" {- Problem 36 (**) Determine the prime factors of a given positive integer. Construct a list containing the prime factors and their multiplicity. Example: * (prime-factors-mult 315) ((3 2) (5 1) (7 1)) Example in Haskell: *Main> prime_factors_mult 315 [(3,2),(5,1),(7,1)] -} primeFactorsMult :: Int -> [(Int, Int)] primeFactorsMult = toPair . group . primeFactors where toPair = map (\x -> (head x, length x)) {- Problem 37 (**) Calculate Euler's totient function phi(m) (improved). See problem 34 for the definition of Euler's totient function. If the list of the prime factors of a number m is known in the form of problem 36 then the function phi(m) can be efficiently calculated as follows: Let ((p1 m1) (p2 m2) (p3 m3) ...) be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula: phi(m) = (p1 - 1) * p1 ** (m1 - 1) * (p2 - 1) * p2 ** (m2 - 1) * (p3 - 1) * p3 ** (m3 - 1) * ... Note that a ** b stands for the b'th power of a. -} totientImproved :: Int -> Int totientImproved m = product [(p - 1) * p ^ (m' - 1) | (p, m') <- primeFactorsMult m] {- Problem 38 (*) Compare the two methods of calculating Euler's totient function. Use the solutions of problems 34 and 37 to compare the algorithms. Take the number of reductions as a measure for efficiency. Try to calculate phi(10090) as an example. (no solution required) -} {- Problem 39 (*) A list of prime numbers. Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range. Example in Haskell: P29> primesR 10 20 [11,13,17,19] -} primesR :: Int -> Int -> [Int] primesR l u = takeWhile (u>) $ dropWhile (l>) primes where primes = filterPrime [2..] filterPrime (x:xs) = x : filterPrime [x' | x' <- xs, x' `mod` x /= 0] {- Problem 40 (**) Goldbach's conjecture. Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers (much larger than we can go with our Prolog system). Write a predicate to find the two prime numbers that sum up to a given even integer. Example: * (goldbach 28) (5 23) Example in Haskell: *goldbach 28 (5, 23) -} goldbach :: Int -> (Int, Int) goldbach n | odd n || n <= 2 = error "Input should be even and greater than 2!" | otherwise = doGoldbach primeRange where primeRange = primesR 2 n doGoldbach range | r == 0 = (h, l) | r > 0 = doGoldbach $ take (length range - 1) range | r < 0 = doGoldbach $ tail range where h = head range l = last range r = h + l - n {- Problem 41 (**) Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition. In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than say 50. Try to find out how many such cases there are in the range 2..3000. Example: * (goldbach-list 9 20) 10 = 3 + 7 12 = 5 + 7 14 = 3 + 11 16 = 3 + 13 18 = 5 + 13 20 = 3 + 17 * (goldbach-list 1 2000 50) 992 = 73 + 919 1382 = 61 + 1321 1856 = 67 + 1789 1928 = 61 + 1867 Example in Haskell: *Exercises> goldbachList 9 20 [(3,7),(5,7),(3,11),(3,13),(5,13),(3,17)] *Exercises> goldbachList' 4 2000 50 [(73,919),(61,1321),(67,1789),(61,1867)] -} goldbachList :: Int -> Int -> [(Int, Int)] goldbachList l u = map goldbach . filter even $ [l..u] goldbachList' :: Int -> Int -> Int -> [(Int, Int)] goldbachList' l u threshold = filter ((threshold<) . fst) $ goldbachList l u
1yefuwang1/haskell99problems
src/H99/Arithmetic.hs
Haskell
bsd-3-clause
5,883
{-# OPTIONS_GHC -fdefer-typed-holes #-} ---------------------------------------------------------------------------------------------------- -- | -- Module : Numeric.Algebra.Elementary.Pretty -- Copyright : William Knop 2015 -- License : BSD3 -- -- Maintainer : william.knop.nospam@gmail.com -- Portability : portable -- -- Pretty printer for elementary algebraic expressions. -- -- __/TODO:/__ Everything. -- -- __/TODO:/__ Write exports. module Numeric.Algebra.Elementary.Pretty where import Numeric.Algebra.Elementary.AST import qualified Text.Nicify as N prettyPrint :: Expr -> String prettyPrint e = N.nicify (show e)
altaic/algebra-elementary
src/Numeric/Algebra/Elementary/Pretty.hs
Haskell
bsd-3-clause
677
{-# LANGUAGE TypeFamilies #-} module QueryArrow.ElasticSearch.ESQL where -- http://swizec.com/blog/writing-a-rest-client-in-haskell/swizec/6152 import Prelude hiding (lookup) import Data.Map.Strict (lookup, fromList, Map, keys) import Data.Text (Text) import Data.Set (toAscList) import QueryArrow.Syntax.Term import QueryArrow.Semantics.TypeChecker import QueryArrow.Syntax.Type import QueryArrow.DB.GenericDatabase import Debug.Trace data ElasticSearchQueryExpr = ElasticSearchQueryParam Var | ElasticSearchQueryVar Var | ElasticSearchQueryIntVal Integer | ElasticSearchQueryStrVal Text deriving (Show, Read) data ElasticSearchQuery = ElasticSearchQuery Text (Map Text ElasticSearchQueryExpr) | ElasticSearchInsert Text (Map Text ElasticSearchQueryExpr) | ElasticSearchUpdateProperty Text (Map Text ElasticSearchQueryExpr) (Map Text ElasticSearchQueryExpr) | ElasticSearchDelete Text (Map Text ElasticSearchQueryExpr) | ElasticSearchDeleteProperty Text (Map Text ElasticSearchQueryExpr) [Text] deriving (Show, Read) data ESTrans = ESTrans PredTypeMap (Map PredName (Text, [Text])) translateQueryArg :: [Var] -> Expr -> ([ElasticSearchQueryExpr], [Var]) translateQueryArg env (VarExpr var) = if elem var env then ([ElasticSearchQueryParam var], [var]) else ([ElasticSearchQueryVar var], [var]) translateQueryArg _ (IntExpr i) = ([ElasticSearchQueryIntVal i], []) translateQueryArg _ (StringExpr i) = ([ElasticSearchQueryStrVal i], []) translateQueryArg _ _ = error "unsupported" translateQueryToElasticSearch :: ESTrans -> [Var] -> PredName -> [Expr] -> [Var] -> (ElasticSearchQuery, [Var]) translateQueryToElasticSearch (ESTrans ptm map1) _ pred0 args env = let (args2, params) = mconcat (map (translateQueryArg env) args) (type0, props) = case lookup pred0 map1 of Just props0 -> props0 Nothing -> error "cannot find predicate" in (ElasticSearchQuery type0 (fromList (zip props args2)), params) translateInsertToElasticSearch :: ESTrans -> PredName -> [Expr] -> [Var] -> (ElasticSearchQuery, [Var]) translateInsertToElasticSearch (ESTrans ptm map1) pred0 args env = case lookup pred0 ptm of Nothing -> error ("translateInsertToElasticSearch: cannot find predicate " ++ show pred0) Just (PredType ObjectPred _) -> let (args2, params) = mconcat (map (translateQueryArg env) args) (type0, props) = case lookup pred0 map1 of Just props0 -> props0 Nothing -> error "cannot find predicate" in (ElasticSearchInsert type0 (fromList (zip props args2)), params) Just pt@(PredType PropertyPred _) -> let (args2, params) = mconcat (map (translateQueryArg env) args) keyargs = keyComponents pt args2 propargs = propComponents pt args2 (type0, props) = case lookup pred0 map1 of Just props0 -> props0 Nothing -> error "cannot find predicate" keyprops = keyComponents pt props propprops = propComponents pt props in (ElasticSearchUpdateProperty type0 (fromList (zip keyprops keyargs)) (fromList (zip propprops propargs)), params) translateDeleteToElasticSearch :: ESTrans -> PredName -> [Expr] -> [Var] -> (ElasticSearchQuery, [Var]) translateDeleteToElasticSearch (ESTrans ptm map1) pred0 args env = case lookup pred0 ptm of Nothing -> error ("translateInsertToElasticSearch: cannot find predicate " ++ show pred0) Just (PredType ObjectPred _) -> let (args2, params) = mconcat (map (translateQueryArg env) args) (type0, props) = case lookup pred0 map1 of Just props0 -> props0 Nothing -> error "cannot find predicate" in (ElasticSearchDelete type0 (fromList (zip props args2)), params) Just pt@(PredType PropertyPred _) -> let (args2, params) = mconcat (map (translateQueryArg env) args) keyargs = keyComponents pt args2 propargs = propComponents pt args2 (type0, props) = case lookup pred0 map1 of Just props0 -> props0 Nothing -> error "cannot find predicate" keyprops = keyComponents pt props propprops = propComponents pt props in (ElasticSearchDeleteProperty type0 (fromList (zip keyprops keyargs)) propprops, params) instance IGenericDatabase01 ESTrans where type GDBQueryType ESTrans = (ElasticSearchQuery, [Var]) type GDBFormulaType ESTrans = FormulaT gTranslateQuery trans vars (FAtomicA _ (Atom pred1 args)) env = return (translateQueryToElasticSearch trans (toAscList vars) pred1 args (toAscList env)) gTranslateQuery trans vars (FInsertA _ (Lit Pos (Atom pred1 args))) env = return (translateInsertToElasticSearch trans pred1 args (toAscList env)) gTranslateQuery trans vars (FInsertA _ (Lit Neg (Atom pred1 args))) env = return (translateDeleteToElasticSearch trans pred1 args (toAscList env)) gTranslateQuery _ _ _ _ = error "unsupported" gSupported _ _ (FAtomicA _ _) _ = True gSupported _ _ (FInsertA _ _) _ = True gSupported _ _ _ _ = False
xu-hao/QueryArrow
QueryArrow-db-elastic/src/QueryArrow/ElasticSearch/ESQL.hs
Haskell
bsd-3-clause
5,342
module Main (main) where import Test.Tasty import qualified TChunkedQueue import qualified TMChunkedQueue main :: IO () main = defaultMain $ testGroup "STM ChunkedQueues" [ testGroup "TChunkedQueue" TChunkedQueue.tests , testGroup "TMChunkedQueue" TMChunkedQueue.tests ]
KholdStare/stm-chunked-queues
tests/UnitTests.hs
Haskell
bsd-3-clause
301
module Capsir.Runtime where import Capsir import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromJust) -- | An instance of a continuation. Binds an environment to the -- continuation itself. data ContInst v = ContInst (Env v) Cont -- | A runtime value. Each variable is bound to one during continuation -- execution data RuntimeValue v -- | A continuation instance value = InstRuntimeValue (ContInst v) -- | A constant value | ConstRuntimeValue v -- | A variable binding environment. data Env v -- | The empty binding environment. = EmptyEnv -- | A single environment frame. Contains the mappings from variables to -- runtime values for this frame, and references the next environment in -- the chain. | FrameEnv (Map String (RuntimeValue v)) (Env v) -- | A function implementing a single instruction of our code. @m@ is a monad -- that allows a change of state during execution, and @v@ is the value type of -- our instruction set. -- -- The function is passed in a list of values, and returns a continuation index -- and a result list of values. For an instruction CpsExpr, the int is the index -- into the continuation list, and the result is applied to that continuation. type InstFunc m v = [v] -> m (Int, [v]) -- | The concrete parameter type to a value constructor. Can either be an -- int, string, double, or another value. data LitParamVal v = LitParamValConst v | LitParamValInt !Int | LitParamValString !String | LitParamValFloat !Double -- | Type type of a user-defined literal function. Takes a list of literal -- parameters, and returns a value of type a, which is the user-defined runtime -- value type. type LitFunc v = [LitParamVal v] -> v data InstructionSet m v = InstructionSet { instructions :: Map String (InstFunc m v) , literals :: Map String (LitFunc v) } -- | Looks up a variable in the environment. lookupEnv :: String -- ^ The variable to look up -> Env v -- ^ The environment to look it up in -> Maybe (RuntimeValue v) -- ^ Nothing if that value is not bound, -- otherwise @Just value@ where value is the bound -- value. lookupEnv _ EmptyEnv = Nothing lookupEnv name (FrameEnv envMap child) = case Map.lookup name envMap of Just val -> Just val Nothing -> lookupEnv name child -- | Evaluates a literal into a runtime constant. evalLit :: InstructionSet m v -> Literal -> v evalLit instSet (Literal name params) = let litFunc = literals instSet Map.! name evalParam (LitParamLit literal) = LitParamValConst $ evalLit instSet literal evalParam (LitParamInt i) = LitParamValInt i evalParam (LitParamString s) = LitParamValString s evalParam (LitParamFloat f) = LitParamValFloat f evaluatedParams = map evalParam params in litFunc evaluatedParams -- | Evaluates a syntactic Value to a RuntimeValue in the given environment eval :: InstructionSet m v -> Value -> Env v -> RuntimeValue v eval _ (ContValue cont) env = InstRuntimeValue (ContInst env cont) eval _ (VarValue name) env = fromJust (lookupEnv name env) eval instSet (LitValue lit) _ = ConstRuntimeValue $ evalLit instSet lit -- | Evalues a syntactic value as eval, but forces it to be a Continuation -- Instance evalAsCont :: InstructionSet m v -> Value -> Env v -> ContInst v evalAsCont instSet val env = case eval instSet val env of InstRuntimeValue inst -> inst _ -> error "Expected a continuation; Got something else" zipOrError :: [a] -> [b] -> [(a, b)] zipOrError (a:ax) (b:bx) = (a, b) : zipOrError ax bx zipOrError [] [] = [] zipOrError _ _ = error "Mismatched input length in zip" data ExecState v = ExecState (Env v) CpsExpr -- | Applies a set of actual parameters to a continuation to -- generate a new execution state. applyCont :: RuntimeValue v -> [RuntimeValue v] -> ExecState v applyCont (InstRuntimeValue inst) args = let ContInst contEnv (Cont params nextExpr) = inst newFrame = Map.fromList $ zipOrError params args newEnv = FrameEnv newFrame contEnv in ExecState newEnv nextExpr applyCont _ _ = error "Expected a continuation instance" -- | Applies a function to the second item in a pair. applySecond :: (a -> b) -> (c, a) -> (c, b) applySecond f (c, a) = (c, f a) fromConst :: RuntimeValue v -> v fromConst (ConstRuntimeValue v) = v fromConst (InstRuntimeValue _) = error "Expected a constant value." -- | Given a mapping from names to continuations, create a new -- environment where each name is mapped to the instantiation of -- its continuation with the same environment. -- -- [example needed] makeFixedEnv :: [(String, Cont)] -> Env v -> Env v makeFixedEnv bindings env = let newEnv = FrameEnv contMap env -- Instantiates a Cont createContInst c = InstRuntimeValue $ ContInst newEnv c runtimeValPairs = map (applySecond createContInst) bindings contMap = Map.fromList runtimeValPairs in newEnv -- | Takes a single step through the given execution state. Returns either a -- new execution state, or a single runtime value if the program exited. step :: Monad m => InstructionSet m v -> ExecState v -> m (Either (ExecState v) (RuntimeValue v)) step instSet (ExecState env expr) = let stepEval v = eval instSet v env in case expr of Exit val -> return $ Right $ stepEval val Apply args val -> let runtimeArgs = map stepEval args in return $ Left $ applyCont (stepEval val) runtimeArgs Fix bindings nextExpr -> return $ Left $ ExecState (makeFixedEnv bindings env) nextExpr Inst instName args conts -> let instFunc = instructions instSet Map.! instName runtimeArgs = map stepEval args values = map fromConst runtimeArgs in do (branchIndex, results) <- instFunc values let nextCont = conts !! branchIndex let nextContInst = eval instSet nextCont env return $ Left $ applyCont nextContInst (map ConstRuntimeValue results) -- | Calls the function on the init, and loops while the output is left, -- feeding the value back into the function. When it returns Right, yields the -- value. eitherLoop :: Monad m => (a -> m (Either a b)) -> a -> m b eitherLoop stepFunc initVal = let go (Left a) = stepFunc a >>= go go (Right b) = return b in stepFunc initVal >>= go -- | A function that given a user-defined instruction set and an initial -- expression, evaluates it until completion. runCont :: Monad m => InstructionSet m v -> CpsExpr -> m (RuntimeValue v) runCont instSet expr = eitherLoop (step instSet) (ExecState EmptyEnv expr)
naerbnic/capsir
src/Capsir/Runtime.hs
Haskell
bsd-3-clause
6,892
{-# LANGUAGE UnicodeSyntax #-} module System.Linux.Netlink.Internal ( align4 ) where import Data.Bits align4 ∷ (Num n, Bits n) ⇒ n → n align4 n = (n + 3) .&. complement 3 {-# INLINE align4 #-}
mvv/system-linux
src/System/Linux/Netlink/Internal.hs
Haskell
bsd-3-clause
209
{-# LANGUAGE OverloadedStrings #-} module Db.Mapper where import Control.Applicative import Database.MongoDB import Text.Read (readMaybe) import Types budgetToDocument :: Budget -> Document budgetToDocument (Budget bid uid i d f ds ob cb) = (idFieldIfExists bid) ++ [ "userId" =: uid , "income" =: (incomeToDocuments i) , "demands" =: (demandsToDocuments d) , "fills" =: (fillsToDocuments f) , "demandSummaries" =: (summariesToDocuments ds) , "openingBalance" =: ob , "closingBalance" =: cb ] where idFieldIfExists Nothing = [] idFieldIfExists (Just bid') = ["_id" =: bid'] demandsToDocuments [] = [] demandsToDocuments (x:xs) = demandToDocument x : demandsToDocuments xs fillsToDocuments [] = [] fillsToDocuments (x:xs) = fillToDocument x : fillsToDocuments xs incomeToDocuments [] = [] incomeToDocuments (x:xs) = incomeToDocument x : incomeToDocuments xs summariesToDocuments [] = [] summariesToDocuments (x:xs) = summaryToDocument x : summariesToDocuments xs documentToBudget :: Document -> Maybe Budget documentToBudget d = Budget <$> d !? "_id" <*> at "userId" d <*> (documentsToIncome <$> d !? "income") <*> (documentsToDemands <$> d !? "demands") <*> (documentsToFills <$> d !? "fills") <*> (documentsToSummaries <$> d !? "demandSummaries") <*> at "openingBalance" d <*> at "closingBalance" d where documentsToDemands [] = [] documentsToDemands (x:xs) = documentToDemand x : documentsToDemands xs documentsToFills [] = [] documentsToFills (x:xs) = documentToFill x : documentsToFills xs documentsToIncome [] = [] documentsToIncome (x:xs) = documentToIncome x : documentsToIncome xs documentsToSummaries [] = [] documentsToSummaries (x:xs) = documentToSummary x : documentsToSummaries xs documentToDemand :: Document -> Demand documentToDemand d = Demand (documentToPeriod $ at "period" d) (at "envelope" d) (at "amount" d) documentToFill :: Document -> Fill documentToFill d = Fill (at "date" d) (documentToDemand $ at "demand" d) (at "amount" d) documentToIncome :: Document -> Income documentToIncome d = Income (at "date" d) (at "amount" d) documentToPeriod :: Document -> Period documentToPeriod d = Period (at "start" d) (at "end" d) documentToSummary :: Document -> DemandSummary documentToSummary d = DemandSummary (documentToDemand $ at "demand" d) (at "fillAmount" d) (read $ at "colour" d) demandToDocument :: Demand -> Document demandToDocument (Demand p e a) = [ "period" =: (periodToDocument p) , "envelope" =: e , "amount" =: a ] fillToDocument :: Fill -> Document fillToDocument (Fill d dem a) = [ "date" =: d , "demand" =: (demandToDocument dem) , "amount" =: a ] incomeToDocument :: Income -> Document incomeToDocument (Income d a) = ["date" =: d, "amount" =: a] maybeDocumentToBudget :: Maybe Document -> Maybe Budget maybeDocumentToBudget doc = case doc of Just d -> documentToBudget d Nothing -> Nothing periodToDocument :: Period -> Document periodToDocument (Period s e) = ["start" =: s, "end" =: e] stringToObjectId :: String -> Maybe ObjectId stringToObjectId s = readMaybe s summaryToDocument :: DemandSummary -> Document summaryToDocument (DemandSummary d a c) = [ "demand" =: (demandToDocument d) , "fillAmount" =: a , "colour" =: show c ]
Geeroar/ut-haskell
src/Db/Mapper.hs
Haskell
apache-2.0
4,130
module Main where import VSimR.Timeline import VSimR.Memory import VSimR.Signal import VSimR.Variable -- main = do -- elab
ierton/vsim
Main.hs
Haskell
bsd-3-clause
142
{-# LANGUAGE OverloadedStrings #-} module Mimir.Bitfinex.Instances() where import Mimir.Types import Mimir.Bitfinex.Types import Control.Applicative ((<$>), (<*>)) import Control.Monad import Data.Aeson import Data.Aeson.Types (Parser) import Data.Char (toUpper) import qualified Data.HashMap.Strict as HM import Data.Maybe (catMaybes) import qualified Data.Text as T instance FromJSON Ticker where parseJSON (Object v) = Ticker <$> fmap (round . (* 1000) . read) (v .: "timestamp") <*> (readSafe =<< v .: "ask") <*> (readSafe =<< v .: "bid") <*> (readSafe =<< v .: "last_price") parseJSON _ = mzero instance FromJSON BFBalance where parseJSON (Object v) = BFBalance <$> v .: "type" <*> v .: "currency" <*> (readSafe =<< v .: "available") parseJSON _ = mzero instance FromJSON Order where parseJSON (Object v) = Order <$> parseType v <*> v .: "id" <*> (round <$> parseDouble v "timestamp") <*> parseDouble v "original_amount" <*> parseDouble v "price" parseJSON _ = mzero parseType :: HM.HashMap T.Text Value -> Parser OrderType parseType m = do t <- (m .: "type" :: Parser String) s <- (m .: "side" :: Parser String) case (t,s) of ("exchange limit", "buy") -> return LIMIT_BUY ("exchange limit", "sell") -> return LIMIT_SELL ("exchange market", "buy") -> return MARKET_BUY ("exchange market", "sell") -> return MARKET_SELL otherwise -> mzero parseDouble :: HM.HashMap T.Text Value -> T.Text -> Parser Double parseDouble m k = do s <- m .: k case (readsPrec 0 s) of [(v,_)] -> return v _ -> mzero readSafe :: Read a => String -> Parser a readSafe s = case readsPrec 0 s of [(a, _)] -> return a _ -> mzero
ralphmorton/Mimir
src/Mimir/Bitfinex/Instances.hs
Haskell
bsd-3-clause
1,915
{-# OPTIONS_GHC -F -pgmF hspec-discover -optF --nested #-} -- import qualified FindSpec -- main :: IO () -- main = FindSpec.main
mkrauskopf/doh
test/main.hs
Haskell
bsd-3-clause
129
-- The @FamInst@ type: family instance heads {-# LANGUAGE CPP, GADTs #-} module FamInst ( FamInstEnvs, tcGetFamInstEnvs, checkFamInstConsistency, tcExtendLocalFamInstEnv, tcLookupFamInst, tcLookupDataFamInst, tcLookupDataFamInst_maybe, tcInstNewTyCon_maybe, tcTopNormaliseNewTypeTF_maybe, newFamInst ) where import HscTypes import FamInstEnv import InstEnv( roughMatchTcs ) import Coercion hiding ( substTy ) import TcEvidence import LoadIface import TcRnMonad import TyCon import CoAxiom import DynFlags import Module import Outputable import UniqFM import FastString import Util import RdrName import DataCon ( dataConName ) import Maybes import TcMType import TcType import Name import Control.Monad import Data.Map (Map) import qualified Data.Map as Map import Control.Arrow ( first, second ) #include "HsVersions.h" {- ************************************************************************ * * Making a FamInst * * ************************************************************************ -} -- All type variables in a FamInst must be fresh. This function -- creates the fresh variables and applies the necessary substitution -- It is defined here to avoid a dependency from FamInstEnv on the monad -- code. newFamInst :: FamFlavor -> CoAxiom Unbranched -> TcRnIf gbl lcl FamInst -- Freshen the type variables of the FamInst branches -- Called from the vectoriser monad too, hence the rather general type newFamInst flavor axiom@(CoAxiom { co_ax_branches = FirstBranch branch , co_ax_tc = fam_tc }) | CoAxBranch { cab_tvs = tvs , cab_lhs = lhs , cab_rhs = rhs } <- branch = do { (subst, tvs') <- freshenTyVarBndrs tvs ; return (FamInst { fi_fam = tyConName fam_tc , fi_flavor = flavor , fi_tcs = roughMatchTcs lhs , fi_tvs = tvs' , fi_tys = substTys subst lhs , fi_rhs = substTy subst rhs , fi_axiom = axiom }) } {- ************************************************************************ * * Optimised overlap checking for family instances * * ************************************************************************ For any two family instance modules that we import directly or indirectly, we check whether the instances in the two modules are consistent, *unless* we can be certain that the instances of the two modules have already been checked for consistency during the compilation of modules that we import. Why do we need to check? Consider module X1 where module X2 where data T1 data T2 type instance F T1 b = Int type instance F a T2 = Char f1 :: F T1 a -> Int f2 :: Char -> F a T2 f1 x = x f2 x = x Now if we import both X1 and X2 we could make (f2 . f1) :: Int -> Char. Notice that neither instance is an orphan. How do we know which pairs of modules have already been checked? Any pair of modules where both modules occur in the `HscTypes.dep_finsts' set (of the `HscTypes.Dependencies') of one of our directly imported modules must have already been checked. Everything else, we check now. (So that we can be certain that the modules in our `HscTypes.dep_finsts' are consistent.) -} -- The optimisation of overlap tests is based on determining pairs of modules -- whose family instances need to be checked for consistency. -- data ModulePair = ModulePair Module Module -- canonical order of the components of a module pair -- canon :: ModulePair -> (Module, Module) canon (ModulePair m1 m2) | m1 < m2 = (m1, m2) | otherwise = (m2, m1) instance Eq ModulePair where mp1 == mp2 = canon mp1 == canon mp2 instance Ord ModulePair where mp1 `compare` mp2 = canon mp1 `compare` canon mp2 instance Outputable ModulePair where ppr (ModulePair m1 m2) = angleBrackets (ppr m1 <> comma <+> ppr m2) -- Sets of module pairs -- type ModulePairSet = Map ModulePair () listToSet :: [ModulePair] -> ModulePairSet listToSet l = Map.fromList (zip l (repeat ())) checkFamInstConsistency :: [Module] -> [Module] -> TcM () checkFamInstConsistency famInstMods directlyImpMods = do { dflags <- getDynFlags ; (eps, hpt) <- getEpsAndHpt ; let { -- Fetch the iface of a given module. Must succeed as -- all directly imported modules must already have been loaded. modIface mod = case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of Nothing -> panic "FamInst.checkFamInstConsistency" Just iface -> iface ; hmiModule = mi_module . hm_iface ; hmiFamInstEnv = extendFamInstEnvList emptyFamInstEnv . md_fam_insts . hm_details ; hpt_fam_insts = mkModuleEnv [ (hmiModule hmi, hmiFamInstEnv hmi) | hmi <- eltsUFM hpt] ; groups = map (dep_finsts . mi_deps . modIface) directlyImpMods ; okPairs = listToSet $ concatMap allPairs groups -- instances of okPairs are consistent ; criticalPairs = listToSet $ allPairs famInstMods -- all pairs that we need to consider ; toCheckPairs = Map.keys $ criticalPairs `Map.difference` okPairs -- the difference gives us the pairs we need to check now } ; mapM_ (check hpt_fam_insts) toCheckPairs } where allPairs [] = [] allPairs (m:ms) = map (ModulePair m) ms ++ allPairs ms check hpt_fam_insts (ModulePair m1 m2) = do { env1 <- getFamInsts hpt_fam_insts m1 ; env2 <- getFamInsts hpt_fam_insts m2 ; mapM_ (checkForConflicts (emptyFamInstEnv, env2)) (famInstEnvElts env1) } getFamInsts :: ModuleEnv FamInstEnv -> Module -> TcM FamInstEnv getFamInsts hpt_fam_insts mod | Just env <- lookupModuleEnv hpt_fam_insts mod = return env | otherwise = do { _ <- initIfaceTcRn (loadSysInterface doc mod) ; eps <- getEps ; return (expectJust "checkFamInstConsistency" $ lookupModuleEnv (eps_mod_fam_inst_env eps) mod) } where doc = ppr mod <+> ptext (sLit "is a family-instance module") {- ************************************************************************ * * Lookup * * ************************************************************************ Look up the instance tycon of a family instance. The match may be ambiguous (as we know that overlapping instances have identical right-hand sides under overlapping substitutions - see 'FamInstEnv.lookupFamInstEnvConflicts'). However, the type arguments used for matching must be equal to or be more specific than those of the family instance declaration. We pick one of the matches in case of ambiguity; as the right-hand sides are identical under the match substitution, the choice does not matter. Return the instance tycon and its type instance. For example, if we have tcLookupFamInst 'T' '[Int]' yields (':R42T', 'Int') then we have a coercion (ie, type instance of family instance coercion) :Co:R42T Int :: T [Int] ~ :R42T Int which implies that :R42T was declared as 'data instance T [a]'. -} tcLookupFamInst :: FamInstEnvs -> TyCon -> [Type] -> Maybe FamInstMatch tcLookupFamInst fam_envs tycon tys | not (isOpenFamilyTyCon tycon) = Nothing | otherwise = case lookupFamInstEnv fam_envs tycon tys of match : _ -> Just match [] -> Nothing -- | If @co :: T ts ~ rep_ty@ then: -- -- > instNewTyCon_maybe T ts = Just (rep_ty, co) -- -- Checks for a newtype, and for being saturated -- Just like Coercion.instNewTyCon_maybe, but returns a TcCoercion tcInstNewTyCon_maybe :: TyCon -> [TcType] -> Maybe (TcType, TcCoercion) tcInstNewTyCon_maybe tc tys = fmap (second TcCoercion) $ instNewTyCon_maybe tc tys -- | Like 'tcLookupDataFamInst_maybe', but returns the arguments back if -- there is no data family to unwrap. tcLookupDataFamInst :: FamInstEnvs -> TyCon -> [TcType] -> (TyCon, [TcType], TcCoercion) tcLookupDataFamInst fam_inst_envs tc tc_args | Just (rep_tc, rep_args, co) <- tcLookupDataFamInst_maybe fam_inst_envs tc tc_args = (rep_tc, rep_args, TcCoercion co) | otherwise = (tc, tc_args, mkTcRepReflCo (mkTyConApp tc tc_args)) tcLookupDataFamInst_maybe :: FamInstEnvs -> TyCon -> [TcType] -> Maybe (TyCon, [TcType], Coercion) -- ^ Converts a data family type (eg F [a]) to its representation type (eg FList a) -- and returns a coercion between the two: co :: F [a] ~R FList a tcLookupDataFamInst_maybe fam_inst_envs tc tc_args | isDataFamilyTyCon tc , match : _ <- lookupFamInstEnv fam_inst_envs tc tc_args , FamInstMatch { fim_instance = rep_fam , fim_tys = rep_args } <- match , let co_tc = famInstAxiom rep_fam rep_tc = dataFamInstRepTyCon rep_fam co = mkUnbranchedAxInstCo Representational co_tc rep_args = Just (rep_tc, rep_args, co) | otherwise = Nothing -- | Get rid of top-level newtypes, potentially looking through newtype -- instances. Only unwraps newtypes that are in scope. This is used -- for solving for `Coercible` in the solver. This version is careful -- not to unwrap data/newtype instances if it can't continue unwrapping. -- Such care is necessary for proper error messages. -- -- Does not look through type families. Does not normalise arguments to a -- tycon. -- -- Always produces a representational coercion. tcTopNormaliseNewTypeTF_maybe :: FamInstEnvs -> GlobalRdrEnv -> Type -> Maybe (TcCoercion, Type) tcTopNormaliseNewTypeTF_maybe faminsts rdr_env ty -- cf. FamInstEnv.topNormaliseType_maybe and Coercion.topNormaliseNewType_maybe = fmap (first TcCoercion) $ topNormaliseTypeX_maybe stepper ty where stepper = unwrap_newtype `composeSteppers` \ rec_nts tc tys -> case tcLookupDataFamInst_maybe faminsts tc tys of Just (tc', tys', co) -> modifyStepResultCo (co `mkTransCo`) (unwrap_newtype rec_nts tc' tys') Nothing -> NS_Done unwrap_newtype rec_nts tc tys | data_cons_in_scope tc = unwrapNewTypeStepper rec_nts tc tys | otherwise = NS_Done data_cons_in_scope :: TyCon -> Bool data_cons_in_scope tc = isWiredInName (tyConName tc) || (not (isAbstractTyCon tc) && all in_scope data_con_names) where data_con_names = map dataConName (tyConDataCons tc) in_scope dc = not $ null $ lookupGRE_Name rdr_env dc {- ************************************************************************ * * Extending the family instance environment * * ************************************************************************ -} -- Add new locally-defined family instances tcExtendLocalFamInstEnv :: [FamInst] -> TcM a -> TcM a tcExtendLocalFamInstEnv fam_insts thing_inside = do { env <- getGblEnv ; (inst_env', fam_insts') <- foldlM addLocalFamInst (tcg_fam_inst_env env, tcg_fam_insts env) fam_insts ; let env' = env { tcg_fam_insts = fam_insts' , tcg_fam_inst_env = inst_env' } ; setGblEnv env' thing_inside } -- Check that the proposed new instance is OK, -- and then add it to the home inst env -- This must be lazy in the fam_inst arguments, see Note [Lazy axiom match] -- in FamInstEnv.lhs addLocalFamInst :: (FamInstEnv,[FamInst]) -> FamInst -> TcM (FamInstEnv, [FamInst]) addLocalFamInst (home_fie, my_fis) fam_inst -- home_fie includes home package and this module -- my_fies is just the ones from this module = do { traceTc "addLocalFamInst" (ppr fam_inst) ; isGHCi <- getIsGHCi ; mod <- getModule ; traceTc "alfi" (ppr mod $$ ppr isGHCi) -- In GHCi, we *override* any identical instances -- that are also defined in the interactive context -- See Note [Override identical instances in GHCi] in HscTypes ; let home_fie' | isGHCi = deleteFromFamInstEnv home_fie fam_inst | otherwise = home_fie -- Load imported instances, so that we report -- overlaps correctly ; eps <- getEps ; let inst_envs = (eps_fam_inst_env eps, home_fie') home_fie'' = extendFamInstEnv home_fie fam_inst -- Check for conflicting instance decls ; no_conflict <- checkForConflicts inst_envs fam_inst ; if no_conflict then return (home_fie'', fam_inst : my_fis) else return (home_fie, my_fis) } {- ************************************************************************ * * Checking an instance against conflicts with an instance env * * ************************************************************************ Check whether a single family instance conflicts with those in two instance environments (one for the EPS and one for the HPT). -} checkForConflicts :: FamInstEnvs -> FamInst -> TcM Bool checkForConflicts inst_envs fam_inst = do { let conflicts = lookupFamInstEnvConflicts inst_envs fam_inst no_conflicts = null conflicts ; traceTc "checkForConflicts" $ vcat [ ppr (map fim_instance conflicts) , ppr fam_inst -- , ppr inst_envs ] ; unless no_conflicts $ conflictInstErr fam_inst conflicts ; return no_conflicts } conflictInstErr :: FamInst -> [FamInstMatch] -> TcRn () conflictInstErr fam_inst conflictingMatch | (FamInstMatch { fim_instance = confInst }) : _ <- conflictingMatch = addFamInstsErr (ptext (sLit "Conflicting family instance declarations:")) [fam_inst, confInst] | otherwise = panic "conflictInstErr" addFamInstsErr :: SDoc -> [FamInst] -> TcRn () addFamInstsErr herald insts = ASSERT( not (null insts) ) setSrcSpan srcSpan $ addErr $ hang herald 2 (vcat [ pprCoAxBranchHdr (famInstAxiom fi) 0 | fi <- sorted ]) where getSpan = getSrcLoc . famInstAxiom sorted = sortWith getSpan insts fi1 = head sorted srcSpan = coAxBranchSpan (coAxiomSingleBranch (famInstAxiom fi1)) -- The sortWith just arranges that instances are dislayed in order -- of source location, which reduced wobbling in error messages, -- and is better for users tcGetFamInstEnvs :: TcM FamInstEnvs -- Gets both the external-package inst-env -- and the home-pkg inst env (includes module being compiled) tcGetFamInstEnvs = do { eps <- getEps; env <- getGblEnv ; return (eps_fam_inst_env eps, tcg_fam_inst_env env) }
forked-upstream-packages-for-ghcjs/ghc
compiler/typecheck/FamInst.hs
Haskell
bsd-3-clause
15,844
module A2 where data T a = C1 a | C2 Int addedC2 = error "added C2 Int to T" over :: (T b) -> b over (C1 x) = x over (C2 a) = addedC2
SAdams601/HaRe
old/testing/addCon/A2AST.hs
Haskell
bsd-3-clause
141
{-# Language RankNTypes #-} {-# Language DataKinds #-} {-# Language PolyKinds #-} {-# Language GADTs #-} {-# Language TypeFamilies #-} module T15874 where import Data.Kind data Var where Op :: Var Id :: Var type Varianced = (forall (var :: Var). Type) data family Parser :: Varianced data instance Parser = P
sdiehl/ghc
testsuite/tests/polykinds/T15874.hs
Haskell
bsd-3-clause
335
module Complex_Vectors (ComplexF, rootsOfUnity,thetas, norm,distance) where import Complex -- --import Strategies -- import Parallel type ComplexF = Complex Double rootsOfUnity:: Int -> [ComplexF] rootsOfUnity n =( zipWith (:+) cvar svar) -- (map cos (thetas n))- (map sin (thetas n)) where cvar = (map cos (thetas n)) svar = (map sin (thetas n)) thetas:: Int -> [Double] thetas n = --[(2*pi/fromInt n)*fromInt k | k<-[0 .. n-1]] (map(\k -> ((2*pi/fromInt n)*fromInt k)) [k | k<-[0 .. n-1]]) --`using` parListChunk 20 rnf fromInt :: (Num a) => Int -> a fromInt i = fromInteger (toInteger i) norm:: [ComplexF] -> Double norm = sqrt.sum.map((^2).magnitude) distance:: [ComplexF] -> [ComplexF] -> Double distance z w = norm(zipWith (-) z w)
RefactoringTools/HaRe
old/testing/evalMonad/Complex_Vectors.hs
Haskell
bsd-3-clause
800
{-# LANGUAGE GADTs #-} module Main where data T t a where T :: (Foldable t, Eq a) => t a -> T t a {-# NOINLINE go #-} go :: T [] a -> Int -> Int go (T _) i = foldr (+) 0 [1..i] main = print (go (T [1::Int]) 20000)
ezyang/ghc
testsuite/tests/perf/should_run/T5835.hs
Haskell
bsd-3-clause
219
{-# LANGUAGE TypeInType #-} module T9632 where import Data.Kind data B = T | F data P :: B -> * type B' = B data P' :: B' -> *
olsner/ghc
testsuite/tests/dependent/should_compile/T9632.hs
Haskell
bsd-3-clause
131
-- !!! Class and instance decl module Test where class K a where op1 :: a -> a -> a op2 :: Int -> a instance K Int where op1 a b = a+b op2 x = x instance K Bool where op1 a b = a -- Pick up the default decl for op2 instance K [a] where op3 a = a -- Oops! Isn't a class op of K
ezyang/ghc
testsuite/tests/rename/should_fail/rnfail008.hs
Haskell
bsd-3-clause
348
------------------- -- This module defines the following common monads: -- -- SR - state reader monad -- State - (strict) state transformer monad -- IOS - IO monad with state -- Output - output monad -- CPS - continuation passing monad -- -- Most of these monads can be found in Wadler's papers about monads. ---------------------------------------------------------------- module Monads( -- exports a Monad and Functor instance for each of these types: SR, runSR, getSR, State, runS, getS, setS, modS, IOS, runIOS, getIOS, setIOS, modIOS, Output, runO, outO, CPS, runCPS, callcc, getcc ) where ---------------------------------------------------------------- -- For each type defined in this module we provide: -- -- o A Functor instance -- o A Monad instance -- o A function -- -- run<M> :: <M> a -> T a -- -- which executes a computation of type M. This function usually takes -- extra parameters (eg an input state) and returns the value of the -- computation and some output values (eg an output state) -- -- o State monads (ie SR, State and IOS) also provide: -- -- get<M> :: <M> s -- set<M> :: s -> <M> () -- not SR -- mod<M> :: (s -> s) -> <M> () -- not SR -- -- which get the current state, set the state to a new value and apply -- a function to the state, respectively. ---------------------------------------------------------------- ---------------------------------------------------------------- -- The state reader monad ---------------------------------------------------------------- newtype SR s a = SR (s -> a) runSR :: SR s a -> s -> a getSR :: SR s s instance Functor (SR s) where fmap f xs = do x <- xs; return (f x) instance Monad (SR s) where m >>= k = SR (\s -> case (unSR m) s of a -> (unSR (k a)) s) m >> k = SR (\s -> case (unSR m) s of _ -> (unSR k) s) return a = SR (\s -> a) runSR = unSR getSR = SR (\s -> s) -- left inverse of S (not exported) unSR :: SR s a -> (s -> a) unSR (SR m) = m ---------------------------------------------------------------- -- A strict state monad ---------------------------------------------------------------- newtype State s a = S (s -> (a,s)) runS :: State s a -> s -> (a,s) modS :: (s -> s) -> State s () setS :: s -> State s () getS :: State s s instance Functor (State s) where fmap f xs = do x <- xs; return (f x) instance Monad (State s) where m >>= k = S (\s -> case (unS m) s of (a,s') -> (unS (k a)) s') m >> k = S (\s -> case (unS m) s of (_,s') -> (unS k) s') return a = S (\s -> (a,s)) runS = unS modS f = S (\s -> ((),f s)) setS s' = S (\s -> ((),s')) getS = S (\s -> (s,s)) -- left inverse of S (not exported) unS :: State s a -> (s -> (a,s)) unS (S m) = m ---------------------------------------------------------------- -- A standard IO + state monad ---------------------------------------------------------------- newtype IOS s a = IOS (s -> IO (a, s)) runIOS :: IOS s a -> s -> IO (a, s) getIOS :: IOS s s setIOS :: s -> IOS s () modIOS :: (s -> s) -> IOS s s instance Functor (IOS s) where fmap f xs = do x <- xs; return (f x) instance Monad (IOS s) where m >>= k = IOS (\s -> unIOS m s >>= \(a,s') -> unIOS (k a) s') m >> k = IOS (\s -> unIOS m s >>= \(_,s') -> unIOS k s') return a = IOS (\s -> return (a,s)) runIOS = unIOS modIOS f = IOS (\s -> return (s, f s)) setIOS s' = IOS (\s -> return ((),s')) getIOS = IOS (\s -> return (s,s)) -- left inverse of IOS (not exported) unIOS :: IOS s a -> (s -> IO (a, s)) unIOS (IOS m) = m ---------------------------------------------------------------- -- An "output" monad - like that in Wadler's "Essence of Functional -- Programming". ---------------------------------------------------------------- newtype Output s a = O (a, [s] -> [s]) runO :: Output s a -> (a, [s]) outO :: [s] -> Output s () instance Functor (Output s) where fmap f xs = do x <- xs; return (f x) instance Monad (Output s) where m >>= k = O (let (a,r) = unO m; (b,s) = unO (k a) in (b, r . s)) m >> k = O (let (a,r) = unO m; (b,s) = unO k in (b, r . s)) return a = O (a, \s -> s) runO (O (a,s)) = (a, s []) outO s = O ((), (s ++)) -- left inverse of O (not exported) unO :: Output s a -> (a, [s] -> [s]) unO (O m) = m ---------------------------------------------------------------- -- A CPS monad - parameterised over the type of the continuation ---------------------------------------------------------------- newtype CPS r a = CPS ((a -> r) -> r) runCPS :: CPS r a -> (a -> r) -> r callcc :: r -> CPS r a getcc :: ((a -> r) -> CPS r a) -> CPS r a instance Functor (CPS s) where fmap f xs = do x <- xs; return (f x) instance Monad (CPS r) where m >>= k = CPS (\c -> unCPS m (\a -> unCPS (k a) c)) m >> k = CPS (\c -> unCPS m (\a -> unCPS k c)) return a = CPS (\c -> c a) runCPS = unCPS callcc cc = CPS (\c -> cc) getcc m = CPS (\c -> unCPS (m c) c) unCPS :: CPS r a -> ((a -> r) -> r) unCPS (CPS m) = m
jtestard/cse230Winter2015
SOE/haskore/src/Monads.hs
Haskell
mit
5,122
module Statistics.SGT.Util where sq :: (Num a) => a -> a sq n = n * n -- for use with non-Double args (//) :: Integral a => a -> a -> Double (//) a b = fromIntegral a / fromIntegral b dbl :: Integral a => a -> Double dbl = fromIntegral dblLog :: Integral a => a -> Double dblLog = log . dbl
marklar/Statistics.SGT
Statistics/SGT/Util.hs
Haskell
mit
295
{- Using textures instead of surfaces -} {-# LANGUAGE OverloadedStrings #-} module Lesson07 where -- import qualified SDL import Linear.V4 (V4(..)) -- import Control.Concurrent (threadDelay) import Control.Monad (unless,when) -- import qualified Config -- lesson07 :: IO () lesson07 = do SDL.initialize [SDL.InitVideo] window <- SDL.createWindow "Lesson07" Config.winConfig renderer <- SDL.createRenderer window (-1) Config.rdrConfig -- using Hint, comment out for seeing the effects -- reference: https://en.wikipedia.org/wiki/Image_scaling#Scaling_methods -- *************** SDL.HintRenderScaleQuality SDL.$= SDL.ScaleLinear -- *************** -- set a color for renderer SDL.rendererDrawColor renderer SDL.$= V4 minBound minBound maxBound maxBound -- load image into main memory (as a surface) imgSf <- SDL.loadBMP "./img/07/Potion.bmp" -- translate a surface to a texture -- i.e. load image into video memory imgTx <- SDL.createTextureFromSurface renderer imgSf SDL.freeSurface imgSf SDL.showWindow window let loop = do events <- SDL.pollEvents let quit = any (== SDL.QuitEvent) $ map SDL.eventPayload events -- clear(i.e. fill) renderer with the color we set SDL.clear renderer -- copy(blit) image texture onto renderer SDL.copy renderer imgTx Nothing Nothing -- A renderer in SDL is basically a buffer -- the present function forces a renderer to flush SDL.present renderer -- threadDelay 20000 unless quit loop loop -- releasing resources SDL.destroyWindow window SDL.destroyRenderer renderer SDL.destroyTexture imgTx SDL.quit
jaiyalas/sdl2-examples
src/Lesson07.hs
Haskell
mit
1,730
module Main where import Test.QuickCheck import Tictactoe.Base import Tictactoe.Move.Base import Tictactoe.Def.Move as DefMove import Tictactoe.Att.Move as AttMove import Tictactoe.Bencode.Encoder as Bencode import Tictactoe.Bencode.Decoder as Bencode import Tictactoe.BencodeDict.Encoder as BencodeDict import Tictactoe.BencodeDict.Decoder as BencodeDict testCase :: (Eq a) => a -> a -> Bool testCase res exp = res == exp main :: IO () main = do quickCheck $ testCase (DefMove.moveByScenario DefMove.First [(1, 1, 'x')]) (Just ((0, 0, 'o'), ExpOppositeCorner (2, 2))) quickCheck $ testCase (DefMove.moveByScenario DefMove.First [(0, 2, 'x')]) (Just ((1, 1, 'o'), ExpOppositeSelfCorner (2, 0))) quickCheck $ testCase (DefMove.moveByScenario (ExpOppositeCorner (0, 2)) [(0, 0, 'x'), (1, 1, 'x'), (0, 2, 'o')]) (Just ((2, 0, 'o'), DefMove.NoExp)) quickCheck $ testCase (DefMove.moveByScenario (ExpOppositeSelfCorner (2, 2)) [(0, 0, 'x'), (1, 1, 'o'), (2, 2, 'o')]) (Just ((0, 1, 'o'), DefMove.NoExp)) quickCheck $ testCase (finishingMove [(1, 1, 'x'), (2, 2, 'x')] 'x') (Just (0,0)) quickCheck $ testCase (finishingMove [(1, 1, 'x'), (2, 2, 'x')] 'o') Nothing quickCheck $ testCase (finishingMove [(1,1,'x'),(2,2,'o'),(0,0,'o')] 'x') Nothing quickCheck $ testCase (finishingMove [(1,0,'x'),(1,1,'x')] 'x') (Just (1,2)) quickCheck $ testCase (finishingMove [(1,0,'x'),(1,1,'x')] 'o') Nothing quickCheck $ testCase (finishingMove [(0,0,'x'),(1,1,'x'),(2,2,'o'),(2,0,'x'),(1,0,'o'),(1,2,'o')] 'o') (Just (0,2)) quickCheck $ testCase (finishingMove [(0,0,'x'),(1,1,'x'),(2,2,'o'),(2,0,'x'),(1,0,'o'),(1,2,'o'),(0,2,'x')] 'o') Nothing quickCheck $ testCase (finishingMove [(0,0,'x'),(1,1,'x'),(2,2,'o'),(2,0,'x'),(1,0,'o'),(1,2,'o'),(0,2,'x')] 'x') (Just (0,1)) quickCheck $ testCase (Bencode.parseBoard "ld1:v1:o1:xi2e1:yi1eed1:v1:x1:xi0e1:yi1eed1:v1:o1:xi1e1:yi0eed1:v1:x1:xi2e1:yi0eee") [(2,0,'x'),(1,0,'o'),(0,1,'x'),(2,1,'o')] quickCheck $ testCase (Bencode.stringifyBoard [(2,1,'o'),(0,1,'x'),(1,0,'o'),(2,0,'x')]) "ld1:v1:o1:xi2e1:yi1eed1:v1:x1:xi0e1:yi1eed1:v1:o1:xi1e1:yi0eed1:v1:x1:xi2e1:yi0eee" quickCheck $ testCase (BencodeDict.parseBoard "d1:0d1:v1:x1:xi1e1:yi1ee1:1d1:v1:o1:xi1e1:yi0ee1:2d1:v1:x1:xi0e1:yi2ee1:3d1:v1:o1:xi0e1:yi0eee") [(0,0,'o'),(0,2,'x'),(1,0,'o'),(1,1,'x')] quickCheck $ testCase (BencodeDict.stringifyBoard [(1,1,'x'),(1,0,'o'),(0,2,'x'),(0,0,'o')]) "d1:0d1:v1:x1:xi1e1:yi1ee1:1d1:v1:o1:xi1e1:yi0ee1:2d1:v1:x1:xi0e1:yi2ee1:3d1:v1:o1:xi0e1:yi0eee" quickCheck $ testCase (gameState [] 'x') Ongoing quickCheck $ testCase (gameState [(1,1,'x'),(2,2,'x'),(0,0,'o')] 'x') Ongoing quickCheck $ testCase (gameState [(1,1,'x'),(2,2,'x'),(0,0,'x')] 'x') Won quickCheck $ testCase (gameState [(1,1,'x'),(2,2,'x'),(0,0,'x')] 'o') Lost quickCheck $ testCase (gameState [(0,0,'x'),(0,1,'x'),(0,2,'o'),(1,0,'o'),(1,1,'o'),(1,2,'x'),(2,0,'x'),(2,1,'x'),(2,2,'o')] 'x') Tie
viktorasl/tictactoe-bot
tests/Tictactoe/Tests.hs
Haskell
mit
2,972
----------------------------------------------------------- -- | -- module: C2HS.C.Extra.Marshal -- copyright: (c) 2016 Tao He -- license: MIT -- maintainer: sighingnow@gmail.com -- -- Convenient marshallers for complicate C types. -- {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 709 {-# LANGUAGE Safe #-} #elif __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Trustworthy #-} #endif module C2HS.C.Extra.Marshal ( peekIntegral , peekString , peekStringArray , withStringArray , peekIntegralArray , withIntegralArray ) where import Foreign.C.String ( peekCString, withCString ) import Foreign.C.Types ( CChar, CInt, CUInt ) import Foreign.Marshal.Array ( peekArray, withArray ) import Foreign.Ptr ( Ptr, nullPtr ) import Foreign.Storable ( Storable, peek ) -- | Peek from pointer then cast to another integral type. peekIntegral :: (Integral a, Storable a, Integral b) => Ptr a -> IO b peekIntegral p = if p == nullPtr then return 0 else fromIntegral <$> peek p {-# SPECIALIZE peekIntegral :: Ptr CInt -> IO Int #-} -- | Peek string from a two-dimension pointer of CChar. peekString :: Ptr (Ptr CChar) -> IO String peekString p = if p == nullPtr then return "" else peek p >>= \p' -> if p' == nullPtr then return "" else peekCString p' -- | Peek an array of String and the result's length is given. peekStringArray :: Integral n => n -> Ptr (Ptr CChar) -> IO [String] peekStringArray 0 _ = return [] peekStringArray n p = if p == nullPtr then return [] else peekArray (fromIntegral n) p >>= mapM (\p' -> if p' == nullPtr then return "" else peekCString p') {-# SPECIALIZE peekStringArray :: Int -> Ptr (Ptr CChar) -> IO [String] #-} {-# SPECIALIZE peekStringArray :: CUInt -> Ptr (Ptr CChar) -> IO [String] #-} -- | Use an array of String as argument, usually used to pass multiple names to C -- functions. withStringArray :: [String] -> (Ptr (Ptr CChar) -> IO a) -> IO a withStringArray [] f = f nullPtr withStringArray ss f = do ps <- mapM (\s -> withCString s return) ss withArray ps f -- | Peek an array of integral values and the result's length is given. peekIntegralArray :: (Integral n, Integral m, Storable m) => Int -> Ptr m -> IO [n] peekIntegralArray n p = (map fromIntegral) <$> peekArray n p {-# SPECIALIZE peekIntegralArray :: Int -> Ptr CInt -> IO [Int] #-} {-# SPECIALIZE peekIntegralArray :: Int -> Ptr CUInt -> IO [Int] #-} -- | Use an array of Integral as argument. withIntegralArray :: (Integral a, Integral b, Storable b) => [a] -> (Ptr b -> IO c) -> IO c withIntegralArray ns f = do let ns' = fmap fromIntegral ns withArray ns' f {-# SPECIALIZE withIntegralArray :: [Int] -> (Ptr CInt -> IO c) -> IO c #-} {-# SPECIALIZE withIntegralArray :: [CInt] -> (Ptr CInt -> IO c) -> IO c #-} {-# SPECIALIZE withIntegralArray :: [CUInt] -> (Ptr CUInt -> IO c) -> IO c #-}
sighingnow/mxnet-haskell
c2hs-extra/src/C2HS/C/Extra/Marshal.hs
Haskell
mit
3,227
import qualified Data.ByteString.Lazy as LB import HaxParse.Parser import HaxParse.Options import HaxParse.Output import Options.Applicative import System.Exit import System.IO main :: IO () main = do opts <- execParser fullOpts res <- parseFile $ file opts let newOpts = if null (eventTypes opts) then opts else opts { showEvents = True } case res of Left m -> do hPutStrLn stderr $ "Parsing failed: " ++ show m exitFailure Right s -> outputWith newOpts s
pikajude/haxparse
src/Main.hs
Haskell
mit
607
module Main (main) where import Data.List (genericLength) import Data.Maybe (catMaybes) import System.Directory (doesFileExist) import System.Exit (exitFailure, exitSuccess) import System.Process (readProcess) import Text.Regex (matchRegex, mkRegex) average :: (Fractional a, Real b) => [b] -> a average xs = realToFrac (sum xs) / genericLength xs expected :: Fractional a => a expected = 90 main :: IO () main = do file <- tix let arguments = ["report", file] output <- readProcess "hpc" arguments "" if average (match output) >= (expected :: Float) then exitSuccess else putStr output >> exitFailure match :: String -> [Int] match = fmap read . concat . catMaybes . fmap (matchRegex regex) . lines where regex = mkRegex "^ *([0-9]*)% " -- The location of the TIX file changed between versions of cabal-install. -- See <https://github.com/tfausak/haskeleton/issues/31> for details. tix :: IO FilePath tix = do let newFile = "tests.tix" oldFile = "dist/hpc/tix/tests/tests.tix" newFileExists <- doesFileExist newFile let file = if newFileExists then newFile else oldFile return file
tfausak/haskeleton
package-name/test-suite/HPC.hs
Haskell
mit
1,152
{-# LANGUAGE NoImplicitPrelude #-} module Advent.Day1Spec (main, spec) where import Advent.Day1 import BasePrelude import Test.Hspec import Test.QuickCheck main :: IO () main = hspec spec spec :: Spec spec = do describe "day1Part1" $ do it "equal delimiters cancel out" $ do day1Part1 "(())" `shouldBe` 0 day1Part1 "()()" `shouldBe` 0 it "equal delimiters QC" $ property $ let charCount char = genericLength . filter (==char) in \x -> charCount '(' x - charCount ')' x == day1Part1 x it "excess open parens goes to upper floor" $ do day1Part1 "(((" `shouldBe` 3 day1Part1 "(()(()(" `shouldBe` 3 day1Part1 "))(((((" `shouldBe` 3 it "excess close parens goes to basement" $ do day1Part1 "())" `shouldBe` negate 1 day1Part1 "))(" `shouldBe` negate 1 day1Part1 ")))" `shouldBe` negate 3 day1Part1 ")())())" `shouldBe` negate 3 describe "day1Part2" $ do it "initial close paren reaches the basement immediately" $ do day1Part2 (negate 1) ")" `shouldBe` Just 1 it "()()) enters the basement at position 5" $ do day1Part2 (negate 1) "()())" `shouldBe` Just 5 it "should return Nothing for strings that don't reach the target floor" $ do day1Part2 (negate 1) "(((" `shouldBe` Nothing day1Part2 1 ")))" `shouldBe` Nothing day1Part2 1 "" `shouldBe` Nothing
jhenahan/adventofcode
test/Advent/Day1Spec.hs
Haskell
mit
1,419
{-# LANGUAGE OverloadedStrings #-} module Y2021.M02.D18.Exercise where {-- We uploaded the reviews yesterday, but the unicoded wine-reviews also have an (optional) score and an (optional) price-point. We need to upload those data now, as well. --} import qualified Data.Text as T import Y2021.M02.D03.Solution (Review, Review(Review)) import Graph.Query (graphEndpoint, getGraphResponse) import Graph.JSON.Cypher (showAttribs, Cypher) import Data.Relation import Y2021.M02.D08.Solution (extractReviews, fetchWineContext) import qualified Y2021.M02.D15.Solution as Fixed -- so, from a review, we need a set of attributes: rev2attribs :: Review -> [Attribute Integer] rev2attribs = undefined -- recall that these attributes are of type Maybe Int -- now, the matcher is interesting, because we're matching the relation, -- not the node matchQuery :: Review -> Cypher matchQuery rev@(Review rx wx _rev _mbsc _mbpr) = T.pack (unwords ["MATCH (t:Taster)-[r:RATES_WINE]->(w:Wine)", "WHERE id(t) =", show rx, "AND id(w)=", show wx, "SET r +=", showAttribs (rev2attribs rev)]) -- with the above, you should be able to update all the unicoded wine-reviews -- with prices and scores. {-- >>> snd <$> (graphEndpoint >>= fetchWineContext >>= extractReviews (Fixed.thisDir ++ Fixed.fixedFile)) >>> let unis = it >>> graphEndpoint >>= flip getGraphResponse (map matchQuery unis) "...{\"columns\":[],\"data\":[]}],\"errors\":[]}\n" --}
geophf/1HaskellADay
exercises/HAD/Y2021/M02/D18/Exercise.hs
Haskell
mit
1,478
module Main where import Puzzle import Solver import System.TimeIt main :: IO () main = analyzeAndSolve oscarsPuzzle --main = analyzeAndSolve mediumPuzzle analyzeAndSolve :: Puzzle -> IO () analyzeAndSolve p = do analyzePuzzle p timeIt $ putStrLn $ show $ solve p timeIt $ putStrLn $ show $ take 100 $ solveAll p -- timeIt $ putStrLn $ show $ length $ solveAll p
johwerm/cube-solver
src/Main.hs
Haskell
mit
381
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, InstanceSigs #-} module LinterUtility (linterSettings) where import Control.Applicative import Data.List.Utils import System.IO import Data.ConfigFile import CompilationUtility import qualified ConfigFile import Printer import Utility data LINTER_SETTINGS = LINTER_SETTINGS { ls_executable :: FilePath, ls_flags :: [String], ls_files :: [FilePath], ls_verbose :: Bool } linterSettings :: ConfigParser -> [FilePath] -> EitherT String IO LINTER_SETTINGS linterSettings cp files = LINTER_SETTINGS <$> ConfigFile.getFile cp "DEFAULT" "utility.linter.executable" <*> (fmap words $ hoistEither $ ConfigFile.get cp "DEFAULT" "utility.linter.flags") <*> pure files <*> (hoistEither $ ConfigFile.getBool cp "DEFAULT" "verbose") instance UtilitySettings LINTER_SETTINGS where executable = ls_executable toStringList ls = concat [ls_flags ls, ls_files ls] utitle _ = Just "Linter" verbose = ls_verbose instance CompilationUtility LINTER_SETTINGS () where defaultValue :: LINTER_SETTINGS -> () defaultValue _ = () failure :: UtilityResult LINTER_SETTINGS -> EitherT String IO () failure r = do dPut [Failure] output <- catchIO $ hGetContents $ ur_stdout r report <- if "" == output then catchIO $ hGetContents $ ur_stderr r else return $ cleanStdout output dPut [Str report, Ln $ "Exit code: " ++ (show $ ur_exit_code r)] throwT "LinterUtility failure" where cleanStdout x = unlines $ (take $ (length $ lines x) - 6) $ lines x success :: UtilityResult LINTER_SETTINGS -> EitherT String IO () success r = do report <- catchIO $ hGetLine $ ur_stdout r dPut [Str " ", Str report, Success]
Prinhotels/goog-closure
src/LinterUtility.hs
Haskell
mit
1,748
import System.Random import Control.Monad(when) main = do gen <- getStdGen askForNumber gen askForNumber :: StdGen -> IO () askForNumber gen = do let (randNumber, newGen) = randomR (1,10) gen :: (Int, StdGen) putStr "Which number in the range from 1 to 10 am I thinking of? " numberString <- getLine when (not $ null numberString) $ do let number = read numberString if randNumber == number then putStrLn "You are correct!" else putStrLn $ "Sorry, it was " ++ show randNumber askForNumber newGen
KHs000/haskellToys
src/scripts/guess_the_number.hs
Haskell
mit
604
module AlecSequences.A279966 (a279966) where import Tables.A274080 (a274080_row) import Data.List (genericIndex, genericLength) a279966 :: Integer -> Integer a279966 1 = 1 a279966 n = genericIndex a279966_list (n - 1) a279966_list :: [Integer] a279966_list = 1 : map count [2..] where count n = genericLength $ filter isFactorOf adjacentLabels where adjacentLabels = map a279966 (a274080_row n) isFactorOf a_i = a_i > 0 && n `mod` a_i == 0
peterokagey/haskellOEIS
src/AlecSequences/A279966.hs
Haskell
apache-2.0
452
import Test.Tasty import Test.Tasty.HUnit import Text.ChordPro.Parser import Text.ChordPro.Types import Text.Trifecta main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [unitTests] simpleLyric :: String simpleLyric = concat [ "[C]Cecilia, you're [F]breaking my [C]heart, you're " , "[F]shaking my [C]confidence [G7]daily.\n" ] parseSimpleLyric :: Result [Lyric] parseSimpleLyric = parseString parseLyricLine mempty simpleLyric isSuccess :: Result a -> Bool isSuccess (Success _) = True isSuccess _ = False resultToMaybe :: Result a -> Maybe a resultToMaybe (Success a) = Just a resultToMaybe _ = Nothing unitTests = testGroup "Unit tests" [ testCase "Parse a simple lyric line successfully" $ isSuccess parseSimpleLyric @?= True , testCase "Parse a simple lyric line into correct length" $ (length <$> (resultToMaybe parseSimpleLyric)) @?= Just 12 ]
relrod/chordpro
test/test.hs
Haskell
bsd-2-clause
950
{-# LANGUAGE TypeFamilies, RankNTypes, ScopedTypeVariables, ViewPatterns, BangPatterns #-} module OffLattice.HPChain where import OffLattice.Util import LA import qualified LA.Transform as T import qualified LA.Matrix as M import qualified OffLattice.Chain as C import qualified OffLattice.Shape as S import qualified OffLattice.Geo as G import qualified Data.Vector.Fixed as F import qualified Data.Vector as V import qualified Data.Vector.Generic as VG import qualified Data.MonoTraversable as MT import qualified Data.HashSet as HS import qualified Data.Vector.Algorithms.Intro as VSORT type Index = Int type Id = Int type Angle n = n type Radius n = n type Potential n = n type Energy n = n type Range n = n type Vec n = F.ContVec F.N3 n type Pos n = Vec n type Bond n = (Index, Pos n, Vec n) type Matrix n = Vec (Vec n) type Transform n = (Matrix n, Vec n) data HP = H | P deriving (Show, Read, Eq) data HPN = H' | P' | N' deriving Eq instance Show HPN where show H' = "H" show P' = "P" show N' = "N" data HPConfig n = HPConfig { hRadius :: Radius n , pRadius :: Radius n , nRadius :: Radius n , hpPotential :: Potential n , ppPotential :: Potential n , hhPotential :: Potential n , hpRange :: Range n -- Interaction range , bondAngle :: Angle n } deriving (Show, Read, Eq) radius H' = hRadius radius P' = pRadius radius N' = nRadius data HPChain n = HPChain { positions :: !(V.Vector (Pos n)) , residues :: !(V.Vector HPN) , bonds :: !(V.Vector (Bond n)) , indices :: !(V.Vector Index) , config :: !(HPConfig n) } instance forall n. Show n => Show (HPChain n) where show (HPChain ps rs bs is c) = "HPChain {" ++ "\n - positions:" ++ show ps' ++ "\n - residues:" ++ show (V.toList rs) ++ "\n - bonds:" ++ show bs' ++ "\n - indices:" ++ show (V.toList is) ++ "\n - config:" ++ show c where ps' :: [F.Tuple3 n] ps' = V.toList $ V.map F.convert ps bs' = V.toList $ V.map f bs f :: Bond n -> (Index, F.Tuple3 n, F.Tuple3 n) f (i, a, b) = (i, F.convert a, F.convert b) instance ( Ord n , Additive n , Multiplicative n , Floating n , Epsilon n , Show n ) => C.Chain (HPChain n) where type Index (HPChain n) = Index type Angle (HPChain n) = Angle n type Energy (HPChain n) = Energy n indices = indices move = updateChain energy = energy mkHPChain :: forall n. ( Additive n , Multiplicative n , Floating n , Epsilon n , Show n ) => [HP] -> HPConfig n -> HPChain n mkHPChain !hps !hpc = HPChain ps rs bs is hpc where n = length hps * 2 m = length hps !rs = V.fromList $ f hps !ps = V.generate n place !bs = V.generate (m-1) g !is = V.generate (m-1) id (c, s) = let a = bondAngle hpc / 2 in (cos a, sin a) place i = F.mk3 (s * x) (c * y) z where x = fromIntegral (i `div` 2) y | i `mod` 4 > 1 = 1 | otherwise = 0 z | 1 <- i `mod` 4 = 1 | 3 <- i `mod` 4 = (-1) | otherwise = 0 f [] = [] f (H:xs) = N' : H' : f xs f (P:xs) = N' : P' : f xs g i | j <- 2*i = (j, place j, normalize $ place (2 + j) .- place j) rotChain :: forall n. ( Additive n , Multiplicative n , Floating n , Epsilon n ) => Index -> Angle n -> HPChain n -> HPChain n rotChain _ a hpc | a ~= 0 = hpc rotChain i a (HPChain !ps !rs !bs !is !hpc) | i >= V.length is || i < 0 = error "Index out of bounds" | otherwise = HPChain ps' rs bs' is hpc where (!j,!p,!b) = bs V.! i !bs' = V.imap f bs !ps' = V.imap g ps !lng = V.length bs `div` 2 < i || True f j (!k, !p, !b) | j <= i = (k, p, b) | j > i = (k, T.vtmulG p t, M.vmmulG b r) --g i r | i <= j = r -- | i > j = T.vtmulG r t g !i !r | i <= j + 1 = r | i > j + 1 = T.vtmulG r t !t = T.rotAboutG p b a :: Transform n !r = T.rot3 b a :: Matrix n {- updateChain :: forall n. ( Ord n , Additive n , Multiplicative n , Floating n , Epsilon n ) => Int -> Angle n -> HPChain n -> Maybe (HPChain n) updateChain i a c | valid = Just c' | otherwise = Nothing where valid = validShapes s c' = rotChain i a c rs = residues c' ps = positions c ps' = positions c' hpc = config c s = VG.izipWith f ps (positions c') f i a b = let r = radius (rs V.! i) hpc in if r /= 0 then S.capsule i r a b else error "radius is 0!" -} updateChain :: forall n. ( Ord n , Additive n , Multiplicative n , Floating n , Epsilon n ) => Int -> Angle n -> HPChain n -> Maybe (HPChain n) updateChain !i !a c@(HPChain !ps !rs !bs !is !hpc) | valid = Just c' | otherwise = Nothing where !valid = validShapes2 s (j+1) (!j,!_,!_) = bonds c V.! i !c' = rotChain i a c !rs = residues c' !ps = positions c !ps' = positions c' hpc = config c !s = VG.izipWith f ps (positions c') f !i !a !b = let r = radius (rs V.! i) hpc in if r /= 0 then S.capsule i r a b else error "radius is 0!" validShapes :: forall n. ( Ord n , Additive n , Multiplicative n , Epsilon n , Floating n ) => V.Vector (S.Shape Id (Vec n)) -> Bool validShapes !s = MT.oall intersects overlaps where intervals :: Vec (V.Vector (G.Point n Id)) !intervals = F.map (V.modify VSORT.sort) $ G.intervals s !overlaps = HS.filter (\(i,j) -> abs (i-j) > 1) $ G.overlappings intervals intersects (!i,!j) = maybe True (const False) $ G.intersects (s V.! i) (s V.! j) validShapes2 :: forall n. ( Ord n , Additive n , Multiplicative n , Epsilon n , Floating n ) => V.Vector (S.Shape Id (Vec n)) -> Int -> Bool validShapes2 !s !i = MT.oall intersects overlaps where (!a,!b) = V.splitAt i s is, js :: Vec (V.Vector (G.Point n Id)) !is = F.map (V.modify VSORT.sort) $ G.intervals a !js = F.map (V.modify VSORT.sort) $ G.intervals b !overlaps = HS.filter (\(i,j) -> abs (i-j) > 1) $ G.overlappings2 is js intersects (!i,!j) = maybe True (const False) $ G.intersects (s V.! i) (s V.! j) energy :: forall n. ( Ord n , Additive n , Multiplicative n , Epsilon n , Floating n , Show n ) => HPChain n -> Energy n energy !ch@(HPChain !ps !rs !bs !is !hpc) = MT.ofoldr ((+) . enrgy) 0 overlaps where !rng = hpRange $ hpc !pp = ppPotential $ hpc !hp = hpPotential $ hpc !hh = hhPotential $ hpc !xs = V.map f $ V.filter (isHP . snd) $ V.indexed rs f (!i, !_) = if rng /= 0 then S.Sphere rng (ps V.! i) i else error "rng == 0" isHP N' = False isHP _ = True intervals :: Vec (V.Vector (G.Point n Id)) !intervals = F.map (V.modify VSORT.sort) $ G.intervals xs !overlaps = G.overlappings intervals enrgy (!i,!j) = let !d = dist (ps V.! i) (ps V.! j) !e = if d >= rng then (0,0) else pot i j d in fst e pot !i !j !d = let e H' H' = hh e H' P' = hp e P' H' = hp e P' P' = pp p = e (rs V.! i) (rs V.! j) in (min 0 $ ljPotential p 1 d, p)
chalmers-kandidat14/off-lattice
OffLattice/HPChain.hs
Haskell
bsd-3-clause
8,233
module Main where import System.Environment import System.Exit import System.FilePath import System.FilePath.GlobPattern (GlobPattern, (~~)) import System.IO import System.FSNotify import Control.Monad (forever) import Control.Concurrent (threadDelay) import Data.Text (pack) import Data.Bits ((.&.)) main :: IO () main = do hSetBuffering stdout NoBuffering getArgs >>= parse >>= runWatcher parse :: [String] -> IO FilePath parse ["-h"] = usage >> exitSuccess parse [] = return "." parse (path:_) = return path usage :: IO () usage = putStrLn "Usage: hobbes [path]" runWatcher :: FilePath -> IO () runWatcher path = let (dir, glob) = splitFileName path in withManager $ \m -> do watchTree m dir (globModified glob) printPath forever $ threadDelay 1000000 globModified :: GlobPattern -> Event -> Bool globModified glob evt@(Added _ _) = matchesGlob glob evt globModified glob evt@(Modified _ _) = matchesGlob glob evt globModified _ (Removed _ _) = False matchesGlob :: GlobPattern -> Event -> Bool matchesGlob glob = fileMatchesGlob glob . takeFileName . eventPath printPath :: Event -> IO () printPath = putStrLn . eventPath fileMatchesGlob :: GlobPattern -> FilePath -> Bool fileMatchesGlob [] _ = True fileMatchesGlob "." _ = True fileMatchesGlob glob fp = fp ~~ glob
rob-b/hobbes
Hobbes.hs
Haskell
bsd-3-clause
1,327
module Evol.Algo.SGA ( ) where -- evil import Evil.EvoAlgorithm import Evil.Individual import Evil.Spaces import Evil.PPrintable import Evil.RandUtils -- vector import qualified Data.Vector as V newtype SGA = SGA instance EvoAlgorithm SGA () where initialize () gen = undefined nextGen = undefined
kgadek/evil-pareto-tests
src_old/Evol/Algo/SGA.hs
Haskell
bsd-3-clause
314
module YouTube.Services ( browseChannel , browseMyChannel , createPlaylist , createPlaylists , deletePlaylist , findChannel , insertVideo , listPlaylist , listVideos ) where import GoogleAPIsClient import Helpers (hashURL) import Model (Tournament(..)) import YouTube.Models import Data.Foldable (toList) import Data.List (find, intercalate) import Data.Map as M (empty, fromList, (!)) browseChannel :: YouTubeId -> Int -> Client [Playlist] browseChannel cId count = unwrap <$> listChannelPlaylists cId count where unwrap (Playlists playlists) = playlists browseMyChannel :: Int -> Client [Playlist] browseMyChannel count = do requireOAuth2 myChannel <- channelId <$> findMyChannel browseChannel myChannel count createPlaylist :: Tournament -> Client Playlist createPlaylist t = do requireOAuth2 playlists <- browseMyChannel 1000 findOrCreatePlaylist playlists t createPlaylists :: [Tournament] -> Client (Tournament -> Playlist) createPlaylists [] = return (M.empty M.!) createPlaylists ts = do requireOAuth2 playlists <- browseMyChannel 1000 findOrCreatePlaylists playlists ts deletePlaylist :: YouTubeId -> Client Bool deletePlaylist pId = do requireOAuth2 delete "/playlists" [ ("id", pId) ] findChannel :: String -> Client Channel findChannel name = firstChannel <$> get "/channels" parameters where parameters = [ ("part", "id,contentDetails") , ("forUsername", name ) ] insertVideo :: Video -> Int -> Playlist -> Client Success insertVideo v pos pl = do requireOAuth2 post "/playlistItems" parameters body where parameters = [ ("part", "snippet") ] body = Just (PlaylistItem "" vId pId pos) vId = videoId v pId = playlistId pl listPlaylist :: YouTubeId -> Int -> Client Videos listPlaylist pId count = do requireOAuth2 listPlaylistVideosIds pId count >>= listVideos where listPlaylistVideosIds i c = extractVideosIds <$> listPlaylistContent i c extractVideosIds = map playlistItemVideoId . toList listPlaylistContent :: YouTubeId -> PageSize -> Client PlaylistContent listPlaylistContent pId = getMany "/playlistItems" parameters where part = "contentDetails,snippet" parameters = [ ("part" , part) , ("playlistId", pId ) ] listVideos :: [YouTubeId] -> Client Videos listVideos vIds = toList <$> listVideosBatch (take 50 vIds) (drop 50 vIds) listVideosBatch :: [YouTubeId] -> [YouTubeId] -> Client (Items Video) listVideosBatch [] _ = return mempty listVideosBatch ids otherIds = do let part = "contentDetails,snippet" parameters = [ ("part", part ) , ("id", intercalate "," ids) ] batch <- get "/videos" parameters mappend batch <$> listVideosBatch (take 50 otherIds) (drop 50 otherIds) findMyChannel :: Client Channel findMyChannel = firstChannel <$> get "/channels" parameters where parameters = [ ("part", "id,contentDetails"), ("mine", "true") ] firstChannel :: Items Channel -> Channel firstChannel (Items cs) = head cs listChannelPlaylists :: YouTubeId -> PageSize -> Client Playlists listChannelPlaylists cId = getMany "/playlists" parameters where part = "contentDetails,snippet" parameters = [ ("part" , part) , ("channelId" , cId ) ] findOrCreatePlaylists :: [Playlist] -> [Tournament] -> Client (Tournament -> Playlist) findOrCreatePlaylists _ [] = return (\_ -> error "no tournament") findOrCreatePlaylists ps ts = ((M.!) . M.fromList) <$> mapM (\t -> (,) t <$> findOrCreatePlaylist ps t) ts findOrCreatePlaylist :: [Playlist] -> Tournament -> Client Playlist findOrCreatePlaylist ps tournament = do let previous = find (samePlaylist playlist) ps case previous of Just found -> return found Nothing -> post "/playlists" parameters body where parameters = [ ("part", "contentDetails,snippet,status") ] body = Just playlist where playlist = mkPlaylist tournament samePlaylist :: Playlist -> Playlist -> Bool samePlaylist p1 p2 = playlistTags p1 == playlistTags p2 mkPlaylist :: Tournament -> Playlist mkPlaylist tournament = Playlist "" title description tags where title = tournamentName tournament description = tournamentURL tournament tag = hashURL $ tournamentURL tournament tags = Tags [tag]
ptitfred/ftv-vods
src/YouTube/Services.hs
Haskell
bsd-3-clause
4,534
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# OPTIONS_HADDOCK -ignore-exports #-} -- | A simple OAuth2 Haskell binding. (This is supposed to be -- independent of the http client used.) module Network.OAuth.OAuth2.Internal where import Data.Aeson import Data.Aeson.Types import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Data.Maybe import Data.Text.Encoding import Data.Text (Text) import GHC.Generics import URI.ByteString import Lens.Micro import Lens.Micro.Extras import Network.HTTP.Conduit as C import Control.Monad.Catch import qualified Network.HTTP.Types as H -------------------------------------------------- -- * Data Types -------------------------------------------------- -- | Query Parameter Representation data OAuth2 = OAuth2 { oauthClientId :: Text , oauthClientSecret :: Text , oauthOAuthorizeEndpoint :: URI , oauthAccessTokenEndpoint :: URI , oauthCallback :: Maybe (URI) } deriving (Show, Eq) newtype AccessToken = AccessToken { atoken :: Text } deriving (Show, FromJSON, ToJSON) newtype RefreshToken = RefreshToken { rtoken :: Text } deriving (Show, FromJSON, ToJSON) newtype IdToken = IdToken { idtoken :: Text } deriving (Show, FromJSON, ToJSON) newtype ExchangeToken = ExchangeToken { extoken :: Text } deriving (Show, FromJSON, ToJSON) -- | The gained Access Token. Use @Data.Aeson.decode@ to -- decode string to @AccessToken@. The @refreshToken@ is -- special in some cases, -- e.g. <https://developers.google.com/accounts/docs/OAuth2> data OAuth2Token = OAuth2Token { accessToken :: AccessToken , refreshToken :: Maybe RefreshToken , expiresIn :: Maybe Int , tokenType :: Maybe Text , idToken :: Maybe IdToken } deriving (Show, Generic) -- | Parse JSON data into 'OAuth2Token' instance FromJSON OAuth2Token where parseJSON = (genericParseJSON defaultOptions { fieldLabelModifier = camelTo2 '_' }) instance ToJSON OAuth2Token where toEncoding = (genericToEncoding defaultOptions { fieldLabelModifier = camelTo2 '_' }) -------------------------------------------------- -- * Types Synonym -------------------------------------------------- -- | Is either 'Left' containing an error or 'Right' containg a result type OAuth2Result a = Either BSL.ByteString a -- | type synonym of post body content type PostBody = [(BS.ByteString, BS.ByteString)] type QueryParams = [(BS.ByteString, BS.ByteString)] -------------------------------------------------- -- * URLs -------------------------------------------------- -- | Prepare the authorization URL. Redirect to this URL -- asking for user interactive authentication. authorizationUrl :: OAuth2 -> URI authorizationUrl oa = over (queryL . queryPairsL) (\l -> l ++ queryParts) (oauthOAuthorizeEndpoint oa) where queryParts = catMaybes [ Just ("client_id", encodeUtf8 $ oauthClientId oa) , Just ("response_type", "code") , fmap ("redirect_uri",) (fmap serializeURIRef' $ oauthCallback oa) ] -- | Prepare the URL and the request body query for fetching an access token. accessTokenUrl :: OAuth2 -> ExchangeToken -- ^ access code gained via authorization URL -> (URI, PostBody) -- ^ access token request URL plus the request body. accessTokenUrl oa code = accessTokenUrl' oa code (Just "authorization_code") -- | Prepare the URL and the request body query for fetching an access token, with -- optional grant type. accessTokenUrl' :: OAuth2 -> ExchangeToken -- ^ access code gained via authorization URL -> Maybe Text -- ^ Grant Type -> (URI, PostBody) -- ^ access token request URL plus the request body. accessTokenUrl' oa code gt = (uri, body) where uri = oauthAccessTokenEndpoint oa body = catMaybes [ Just ("code", encodeUtf8 $ extoken code) , fmap (("redirect_uri",) . serializeURIRef') $ oauthCallback oa , fmap (("grant_type",) . encodeUtf8) gt ] -- | Using a Refresh Token. Obtain a new access token by -- sending a refresh token to the Authorization server. refreshAccessTokenUrl :: OAuth2 -> RefreshToken -- ^ refresh token gained via authorization URL -> (URI, PostBody) -- ^ refresh token request URL plus the request body. refreshAccessTokenUrl oa token = (uri, body) where uri = oauthAccessTokenEndpoint oa body = [ ("grant_type", "refresh_token") , ("refresh_token", encodeUtf8 $ rtoken token) ] -- | For `GET` method API. appendAccessToken :: URIRef a -- ^ Base URI -> AccessToken -- ^ Authorized Access Token -> URIRef a -- ^ Combined Result appendAccessToken uri t = over (queryL . queryPairsL) (\query -> query ++ (accessTokenToParam t)) uri -- | Create 'QueryParams' with given access token value. accessTokenToParam :: AccessToken -> [(BS.ByteString, BS.ByteString)] accessTokenToParam t = [("access_token", encodeUtf8 $ atoken t)] appendQueryParams :: [(BS.ByteString, BS.ByteString)] -> URIRef a -> URIRef a appendQueryParams params = over (queryL . queryPairsL) (params ++ ) uriToRequest :: MonadThrow m => URI -> m Request uriToRequest uri = do ssl <- case (view (uriSchemeL . schemeBSL) uri) of "http" -> return False "https" -> return True s -> throwM $ InvalidUrlException (show uri) ("Invalid scheme: " ++ show s) let query = fmap (\(a, b) -> (a, Just b)) (view (queryL . queryPairsL) uri) hostL = (authorityL . _Just . authorityHostL . hostBSL) portL = (authorityL . _Just . authorityPortL . _Just . portNumberL) defaultPort = (if ssl then 443 else 80) :: Int req = (setQueryString query) $ defaultRequest { secure = ssl, path = (view pathL uri) } req2 = (over hostLens . maybe id const . preview hostL) uri req req3 = (over portLens . maybe (\_ -> defaultPort) const . preview portL) uri req2 return $ req3 requestToUri :: Request -> URI requestToUri req = URI (Scheme (if secure req then "https" else "http")) (Just (Authority Nothing (Host $ host req) (Just $ Port $ port req))) (path req) (Query $ H.parseSimpleQuery $ queryString req) Nothing hostLens :: Lens' Request BS.ByteString hostLens f req = f (C.host req) <&> \h' -> req { C.host = h' } {-# INLINE hostLens #-} portLens :: Lens' Request Int portLens f req = f (C.port req) <&> \p' -> req { C.port = p' } {-# INLINE portLens #-}
reactormonk/hoauth2
src/Network/OAuth/OAuth2/Internal.hs
Haskell
bsd-3-clause
6,949
--------------------------------------------------------- -- -- Module : ErrorHandling -- Copyright : Bartosz Wójcik (2010) -- License : BSD3 -- -- Maintainer : bartek@sudety.it -- Stability : Unstable -- Portability : portable -- -- Error handling data structures, functions, etc. --------------------------------------------------------- -- | Provides data types and basic functions allowing better and direct error handling. module Haslo.ErrorHandling (module Control.Monad.Error ,module Haslo.BasicType ,ValidationError (..) ,ValidMonad ) where import Control.Monad.Error.Class import Control.Monad.Error import Haslo.BasicType import Haslo.InstalmentPlan import Text.PrettyShow import Data.Time (Day ,fromGregorian) -- | Error handlig data type. data ValidationError = -- | Instalment discrepancy: -- Instalment amount, Repayment, Interest paid InstalmentDiscrepancy !Amount !Amount !Amount -- | Incorect interest: -- Principal before, Late interest before, Interest calculated (incorectly), -- Interest rate | IPLInterest !Amount !Interest !Interest !Rate -- | Simple follow up interest mismatch (a1 + a2 - a3 /= a4): -- Error description, a1, a2, a3, a4 | FollowUpInterestError String !Interest !Interest !Amount !Interest -- | Simple follow up mismatch (a1 - a /= a2): -- Error description, a1, a, a2 | FollowUpError String !Amount !Amount !Amount -- | Simpler follow up mismatch (a /= b): -- Error description, a, b | SimplerFollowUpError String !Amount !Amount -- | Deffered interest cannot be paid. | NotPaidDefferedInterest !Interest InstalmentPlan -- | Capital doesn't amortize. This is due to rounding error if happens. | NotAmortized !Amount InstalmentPlan | OtherError String -- Any error can occur independently before and after financing. -- Errors after financing usually are linked to date. -- | FinancingError Day ValidationError -- | We make ValidationError an instance of the Error class -- to be able to throw it as an exception. instance Error ValidationError where noMsg = OtherError "(!)" strMsg s = OtherError s instance Show ValidationError where show (InstalmentDiscrepancy a p iP) = "Instalment discrepancy:\ \instalment amount /= repayment + interest paid (" ++ (showAmtWithLen 8 a) ++ "/=" ++ (showAmtWithLen 8 p) ++ "+" ++ (showAmtWithLen 8 iP) ++ ")" show (IPLInterest p iL i r) = "IPL interest discrepancy: \ \ recalculated interest=" ++ show iR ++ ", given interest=" ++ show i ++ " (principal:" ++ showAmtWithLen 8 p ++ " (late interest:" ++ showWithLenDec 11 6 iL ++ " (interest rate:" ++ show r ++ ")" where iR = (fromIntegral p + iL) * r show (FollowUpInterestError msg a1 a2 a3 a4) = msg ++ show (a1 / 100) ++ " - " ++ show (a2 / 100) ++ " + " ++ showAmtWithLen 8 a3 ++ " /= " ++ show (a4 / 100) show (FollowUpError msg a1 a a2) = msg ++ showAmtWithLen 8 a1 ++ " - " ++ showAmtWithLen 8 a ++ " /= " ++ showAmtWithLen 8 a2 show (SimplerFollowUpError msg a b) = msg ++ showAmtWithLen 8 a ++ " /= " ++ showAmtWithLen 8 b show (NotPaidDefferedInterest iL ip) = "Deferred interest not paid off. Remains:" ++ show (iL / 100) ++ " " ++ show ip show (NotAmortized c ip) = "Principal doesn't amortize fully. Remains:" ++ showAmtWithLen 8 c ++ " " ++ show ip show (OtherError msg) = msg -- show (FinancingError d err) = show d ++ " " ++ show err maybeShow Nothing = "" maybeShow (Just a) = show a ++ " " -- | Monad wrapping error message or correct value. Broadly used. type ValidMonad = Either ValidationError --errMsg moduleName functionName msg = throwError $ OtherError $ -- moduleName ++ " " ++ -- functionName ++ " " ++ -- msg {-errDate :: Day -> ValidMonad a -> ValidMonad a errDate d (Left (FollowUpError w x y z _)) = Left $ FollowUpError w x y z (Just d) errDate d (Left (InstalmentDiscrepancy w x y z _)) = Left $ InstalmentDiscrepancy w x y z (Just d) errDate d (Left (IPLInterest w x y z _)) = Left $ IPLInterest w x y z (Just d) errDate _ x = x-} --data FinancingError = SFinancingError Day ValidationError -- | Allows adding date to any error of @ValidationError@ type. --liftDate :: MonadError ValidationError m => Day -- -> ValidationError -- -> m a --liftDate date err = throwError $ FinancingError date err
bartoszw/haslo
Haslo/ErrorHandling.hs
Haskell
bsd-3-clause
5,551
{-# LANGUAGE FlexibleInstances, OverloadedStrings #-} module Data.Document ( FromDocument (..) , ToDocument (..) ) where import qualified Database.MongoDB as D import qualified Data.Time.Clock as T class FromDocument a where fromDocument :: D.Document -> a instance FromDocument a => FromDocument (a, T.UTCTime) where fromDocument d = (fromDocument d, D.timestamp $ D.typed $ D.valueAt "_id" d) class ToDocument a where toDocument :: a -> D.Document
RobinKrom/BtcExchanges
src/Data/Document.hs
Haskell
bsd-3-clause
492
-- | Creating and rendering dot graphs that correspond to expression graphs. -- Each node has a single output and zero or more inputs. module Dot where import Language.Dot -- cabal install language-dot -- To generate an SVG file: -- -- dot -Tsvg file.dot -o file.svg -- -- Requires `graphviz` to be installed. -- | Identifier type ID = Int -- | Node Label (will be shown in the rendering) type Label = String -- | Input index (first input has index 0) type Input = Int -- | Node color (e.g. \"#AAA\") type Color = String -- | Number of inputs for a node type Arity = Int -- | Expression graph type ExpGraph = [Statement] -- Create a node node :: ID -> Label -> Color -> Arity -> ExpGraph node id lab col ar = return $ NodeStatement (NodeId (NameId (show id)) Nothing) [ AttributeSetValue (NameId "fillcolor") (NameId col) , AttributeSetValue (NameId "label") (NameId labStr) ] where labStr = concat [ "<" , "<TABLE BORDER=\"0\" CELLBORDER=\"0\" CELLSPACING=\"0\">" , "<TR>" , "<TD>" , lab , "</TD>" , concatMap mkInp [0 .. ar-1] , "</TR>" , "</TABLE>" , ">" ] mkInp inp = concat [ "<TD PORT=\"inp" , show inp , "\"> &nbsp;&nbsp;" , "</TD>" ] -- Create an edge edge :: ID -- ^ Downstream node -> Input -- ^ Input index of downstream node -> ID -- ^ Upstream node -> ExpGraph edge from inp to = [ NodeStatement ( NodeId (NameId (show from)) (Just (PortI (NameId ("inp" ++ show inp ++ ":c")) Nothing)) -- ":c" is a hack because the `Compass` type doesn't include a -- center direction ) [] , EdgeStatement [ENodeId DirectedEdge (NodeId (NameId (show to)) Nothing)] [] ] -- | Create a sub-graph subGraph :: ID -> ExpGraph -> ExpGraph subGraph id = return . SubgraphStatement . NewSubgraph (Just (StringId ("cluster_" ++ show id))) . (dotted :) where dotted = NodeStatement (NodeId (NameId "graph") Nothing) [ AttributeSetValue (NameId "style") (NameId "dotted")] setRoundedNode :: ExpGraph setRoundedNode = return $ NodeStatement (NodeId (NameId "node") Nothing) [ AttributeSetValue (NameId "style") (StringId "rounded,filled") , AttributeSetValue (NameId "shape") (NameId "box") ] setEdgeStyle :: ExpGraph setEdgeStyle = return $ NodeStatement (NodeId (NameId "edge") Nothing) [ AttributeSetValue (NameId "dir") (NameId "both") , AttributeSetValue (NameId "arrowtail") (NameId "dot") , AttributeSetValue (NameId "tailclip") (NameId "false") ] renderGraph :: ExpGraph -> FilePath -> IO () renderGraph g file = writeFile file $ renderDot $ Graph UnstrictGraph DirectedGraph Nothing $ concat [ setRoundedNode , setEdgeStyle , g ]
emilaxelsson/ag-graph
src/Dot.hs
Haskell
bsd-3-clause
2,914
module SimulationDSL ( module SimulationDSL.Language.EquationsDescription , module SimulationDSL.Language.Exp , module SimulationDSL.Data.ExpType , module SimulationDSL.Data.Scalar , module SimulationDSL.Data.Vector3 , module SimulationDSL.Data.Array , module SimulationDSL.Interpreter.SimMachine , module SimulationDSL.Interpreter.Machine , module SimulationDSL.Compiler.SimMachine ) where import SimulationDSL.Data.ExpType import SimulationDSL.Data.Scalar import SimulationDSL.Data.Vector3 import SimulationDSL.Data.Array import SimulationDSL.Language.Exp hiding ( isIntegral, isSigma , containIntegral, containSigma ) import SimulationDSL.Language.EquationsDescription import SimulationDSL.Interpreter.SimMachine import SimulationDSL.Interpreter.Machine ( Machine, machineRegisterValue ) import SimulationDSL.Compiler.SimMachine
takagi/SimulationDSL
SimulationDSL/SimulationDSL.hs
Haskell
bsd-3-clause
894
module Main where import Test.Hspec import Test.Hspec.HUnit import Test.HUnit import Data.Char import Data.Either import Data.Maybe import Chess import Chess.FEN import Control.Monad.Instances import Control.Monad assertNothing msg x = assertEqual msg Nothing x assertJust msg (Just x) = return () assertJust msg (Nothing) = assertFailure msg assertEmpty lst = assertEqual "" [] lst must_eq actual expected = assertEqual "" expected actual defaultFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -" begpos = describe "on the beginposition" $ do it "should not allow moving a white piece in blacks turn" $ do (let brd = allowedMove "b1c3" defaultBoard in move "b2b3" brd `must_eq` Left WrongTurn) it "should not allow moving a nonexistent piece" $ do move "a3a4" defaultBoard `must_eq` Left NoPiece brutepos = "8/3k1p2/8/8/4NB2/8/1RP5/4K3 w - -" brutemoves = ["b2b1", "b2b3", "b2b4", "b2b5", "b2b6", "b2b7", "b2b8", "b2a2", "c2c3", "c2c4", "e1d1", "e1d2", "e1e2", "e1f2", "e1f1", "e4d2", "e4c3", "e4c5", "e4d6", "e4f6", "e4g5", "e4g3", "e4f2", "f4e3", "f4d2", "f4c1", "f4e5", "f4d6", "f4c7", "f4b8", "f4g5", "f4h6", "f4g3", "f4h2"] pieces = ["b2", "c2", "e4", "e1", "f4"] enumpos = let Just brd = fromFEN brutepos in describe "brute force" $ do it "should accept all moves" $ do assertEmpty (filter (\x -> not $ valid x brd) brutemoves) it "shouldn't accept any other move" $ do assertEmpty (filter (\x -> valid x brd) (mulMovesExcept pieces brutemoves)) pawnmovepos = "8/8/8/4P3/8/8/8/8 w - -" pawnCapturePosA = "8/8/8/8/8/2pppp2/2PPPP2/8 w - -" pawnCaptureAAllowed = ["c2d3", "d2c3", "d2e3", "e2d3", "e2f3", "f2e3"] piecesA = ["c2", "d2", "e2", "f2"] pawnCapturePosB = "8/8/8/8/8/2pppp2/2PPPP2/8 b - -" pawnCaptureBAllowed = ["d3c2", "c3d2", "e3d2", "d3e2", "f3e2", "e3f2"] piecesB = ["c3", "d3", "e3", "f3"] enPassantPos = "8/3p4/8/8/4P3/8/8/8 w - -" pawn = describe "a pawn" $ do it "can move forward" $ do let Just brd = fromFEN pawnmovepos in case move "e5e6" brd of Right a -> pieceAtStr "e5" a == Nothing && pieceAtStr "e6" a == Just (Piece White Pawn) Left a -> error (show a) it "can't move anywhere else" $ do let Just brd = fromFEN pawnmovepos in assertEmpty $ filter (\x -> valid x brd) (movesExcept "e5" ["e5e6"]) it "can capture pieces 1" $ do let Just brd = fromFEN pawnCapturePosA in assertEmpty $ filter (\x -> not $ valid x brd) pawnCaptureAAllowed it "can't do anything else 1" $ do let Just brd = fromFEN pawnCapturePosA in assertEmpty $ filter (\x -> valid x brd) (mulMovesExcept pieces pawnCaptureAAllowed) it "can capture pieces 2" $ do let Just brd = fromFEN pawnCapturePosB in assertEmpty $ filter (\x -> not $ valid x brd) pawnCaptureBAllowed it "can't do anything else 2" $ do let Just brd = fromFEN pawnCapturePosB in assertEmpty $ filter (\x -> valid x brd) (mulMovesExcept pieces pawnCaptureBAllowed) it "can do an enpassant capture" $ do let brd = allowedMoves ["e4e5", "d7d5", "e5d6"] (unsafeFromFEN enPassantPos) in pieceAt 3 4 brd == Nothing && pieceAt 3 5 brd /= Nothing rookmovepos = "8/8/8/4R3/8/8/8/8 w - -" rookPos = "e5" rookAllowed = ["e5e1", "e5e2", "e5e3", "e5e4", "e5e6", "e5e7", "e5e8", "e5a5", "e5b5", "e5c5", "e5d5", "e5f5", "e5g5", "e5h5"] rook = let Just brd = fromFEN rookmovepos in describe "a rook" $ do it "can move straight" $ do and $ map (\x -> valid x brd) rookAllowed it "can't move anywhere else" $ do and $ map (\x -> not $ valid x brd) (movesExcept rookPos rookAllowed) knightpos = "8/8/8/3n4/8/8/8/8 b - -" knightallowed = ["d5c3", "d5b4", "d5b6", "d5c7", "d5e7", "d5f6", "d5f4", "d5e3"] knight = let Just brd = fromFEN knightpos in describe "a knight" $ do it "can move like a knight" $ do and $ map (\x -> valid x brd) knightallowed it "can't move anywhere else" $ do and $ map (\x -> not $ valid x brd) (movesExcept "d5" knightallowed) bishoppos = "8/8/8/3b4/8/8/8/8 b - -" bishopallowed = ["d5a2", "d5b3", "d5c4", "d5e6", "d5f7", "d5g8", "d5h1", "d5g2", "d5f3", "d5e4", "d5c6", "d5b7", "d5a8"] bishop = let Just brd = fromFEN bishoppos in describe "a bishop" $ do it "can move diagonally" $ do and $ map (\x -> valid x brd) bishopallowed it "can't move anywhere else" $ do and $ map (\x -> not $ valid x brd) (movesExcept "d5" bishopallowed) queenpos = "8/8/8/3q4/8/8/8/8 b - -" queenallowed = ["d5a2", "d5b3", "d5c4", "d5e6", "d5f7", "d5g8", "d5h1", "d5g2", "d5f3", "d5e4", "d5c6", "d5b7", "d5a8", "d5d1", "d5d2", "d5d3", "d5d4", "d5d6", "d5d7", "d5d8", "d5a5", "d5b5", "d5c5", "d5e5", "d5f5", "d5g5", "d5h5"] queen = let Just brd = fromFEN queenpos in describe "a queen" $ do it "can move" $ do and $ map (\x -> valid x brd) queenallowed it "can't move anywhere else" $ do and $ map (\x -> not $ valid x brd) (movesExcept "d5" queenallowed) kingpos = "8/8/8/3k4/8/8/8/8 b - - 0 1" kingallowed = ["d5d4", "d5c4", "d5c5", "d5c6", "d5d6", "d5e6", "d5e5", "d5e4"] king = let Just brd = fromFEN kingpos in describe "a king" $ do it "can move exactly one square" $ do and $ map (\x -> valid x brd) kingallowed it "can't move anywhere else" $ do and $ map (\x -> not $ valid x brd) (movesExcept "d5" kingallowed) kingcastlepos = "8/8/8/8/8/8/8/4K2R w KQkq - " kingCastleInbetweenPos = "8/8/8/8/8/8/8/4K1NR w KQkq -" kingCastleCheckPosA = "8/8/8/5r2/8/8/8/4K2R w KQkq -" kingCastleCheckPosB = "8/8/8/6r1/8/8/8/4K2R w KQkq -" kingcastletest = describe "a kingside castle" $ do it "must be accepted" $ do let Just brd = fromFEN kingcastlepos in case move "O-O" brd of Right brd -> do pieceAt 4 0 brd `must_eq` Nothing pieceAt 7 0 brd `must_eq` Nothing pieceAt 5 0 brd `must_eq` Just (Piece White Rook) pieceAt 6 0 brd `must_eq` Just (Piece White King) Left err -> return () it "must not be allowed when piece inbetween" $ do let Just brd = fromFEN kingCastleInbetweenPos in not $ valid "O-O" brd it "must not be allowed when causes check" $ do let Just brd = fromFEN kingCastleCheckPosA in not $ valid "O-O" brd it "must not be allowed when check inbetween" $ do let Just brd = fromFEN kingCastleCheckPosA in not $ valid "O-O" brd queenCastlePos = "8/8/8/8/8/8/8/R3K3 w KQkq -" queenCastleInbetweenPos = "8/8/8/8/8/8/8/R2BK3 w KQkq -" queenCastleCheckPosA = "8/8/8/8/6b1/8/8/R3K3 w KQkq -" queenCastleCheckPosB = "8/8/8/8/5b2/8/8/R3K3 w KQkq -" queencastletest = describe "a queenside castle" $ do it "must be accepted" $ do let Just brd = fromFEN queenCastlePos in case move "O-O-O" brd of Right brd -> pieceAt 4 0 brd == Nothing && pieceAt 7 0 brd == Nothing && pieceAt 3 0 brd == Just (Piece White Rook) && pieceAt 2 0 brd == Just (Piece White King) Left err -> error $ show err it "must not be allowed when piece inbetween" $ do let Just brd = fromFEN queenCastleInbetweenPos in not $ valid "O-O-O" brd it "must not be allowed when causes check" $ do let Just brd = fromFEN queenCastleCheckPosA in not $ valid "O-O-O" brd it "must not be allowed when check inbetween" $ do let Just brd = fromFEN queenCastleCheckPosA in not $ valid "O-O-O" brd checkMoveA = "8/4r3/8/8/3p4/4P3/4K3/8 w - -" checkMoveB = "8/8/8/8/8/8/3KR2r/8 w - -" checkmoves = describe "moves causing check" $ do it "must not be allowed A" $ do let Just brd = fromFEN checkMoveA in move "e3d4" brd == Left CausesCheck it "must not be allowed B" $ do let Just brd = fromFEN checkMoveB in move "e2e3" brd == Left CausesCheck kingCastle = "8/p7/8/8/8/8/8/4K2R w KQkq -" queenCastle = "8/p7/8/8/8/8/8/R3K3 w KQkq -" castletest = describe "castling" $ do it "must not be allowed kingside when kingrook moved" $ do let brd = allowedMoves ["h1h2", "a7a6", "h2h1", "a6a5"] $ unsafeFromFEN kingCastle in move "O-O" brd `must_eq` Left InvalidMove it "must not be allowed queenside when queenrook has moved" $ do let brd = allowedMoves ["a1a2", "a7a6", "a2a1", "a6a5"] $ unsafeFromFEN queenCastle in move "O-O-O" brd `must_eq` Left InvalidMove it "must not be allowed when king has moved" $ do let brd = allowedMoves ["e1e2", "a7a6", "e2e1"] $ unsafeFromFEN kingCastle in move "O-O" brd `must_eq` Left InvalidMove pawnPromotionPos = "8/P7/8/8/8/8/8/8 w KQkq -" pawnPromotionCheck = "8/2K3Pr/8/8/8/8/8/8 w KQkq -" promotion = describe "promotion" $ do it "must be allowed when pawn on last row" $ do let Just brd = fromFEN pawnPromotionPos in case move "a7a8q" brd of Right b -> pieceAt 0 7 b == Just (Piece White Queen) && pieceAt 0 6 b == Nothing _ -> False it "must not be allowed when it causes check" $ do let Just brd = fromFEN pawnPromotionCheck in move "g7g8q" brd == Left CausesCheck fentest = describe "fen" $ do it "must be equal to input fen" $ do toFEN (unsafeFromFEN pawnPromotionPos) `must_eq` pawnPromotionPos toFEN (unsafeFromFEN pawnPromotionCheck) `must_eq` pawnPromotionCheck toFEN (unsafeFromFEN checkMoveA) `must_eq` checkMoveA toFEN (unsafeFromFEN checkMoveB) `must_eq` checkMoveB toFEN (unsafeFromFEN kingCastle) `must_eq` kingCastle toFEN (unsafeFromFEN queenCastle) `must_eq` queenCastle toFEN (unsafeFromFEN staleMatePos) `must_eq` staleMatePos toFEN (unsafeFromFEN queenCastleCheckPosA) `must_eq` queenCastleCheckPosA toFEN (unsafeFromFEN queenCastleCheckPosB) `must_eq` queenCastleCheckPosB toFEN (unsafeFromFEN enpasPos) `must_eq` enpasPos staleMatePos = "7k/8/6r1/4K3/6r1/3r1r2/8/8 w - -" stalematetest = describe "stalemate" $ do it "should be detected" $ do stalemate White $ unsafeFromFEN staleMatePos matePos = "3K2r1/6r1/8/8/8/8/8/2k5 w - -" matetest = describe "mate" $ do it "should be detected" $ do mate White $ unsafeFromFEN matePos enpasPos = "rnbqkbnr/ppp2ppp/8/3pP3/8/8/PPP1PPPP/RNBQKBNR w KQkq d6" enpasTest = describe "read enpassant" $ do it "Must accept e5d6 on rnbqkbnr/ppp2ppp/8/3pP3/8/8/PPP1PPPP/RNBQKBNR w KQkq d6" $ do let Just brd = fromFEN enpasPos in valid "e5d6" brd mulMovesExcept pcs lst = concat $ map (\x -> movesExcept x lst) pcs movesExcept pc lst = (filter (not . flip elem lst) (allMoves pc)) allMoves pc = [pc ++ [(chr (x+97)), (intToDigit (y+1))] | x<-[0..7], y<-[0..7]] tests = describe "The move validator" $ do begpos enumpos pawn rook knight bishop queen king kingcastletest queencastletest checkmoves castletest promotion fentest stalematetest matetest enpasTest unsafeFromFEN = fromJust . fromFEN main = do hspec tests valid a brd = case move a brd of Right brd -> True _ -> False allowedMove a brd = case move a brd of Right brd -> brd Left f -> error ("Move " ++ (show a) ++ " not allowed: " ++ (show f)) allowedMoves mvs brd = foldl (\x y -> allowedMove y x) brd mvs moveSequence brd mvs = foldM (flip moveVerbose) brd mvs moveVerbose mv brd = case move mv brd of Right b -> Right b Left er -> Left (mv, er)
ArnoVanLumig/chesshs
ChessTest.hs
Haskell
bsd-3-clause
11,303
{-# OPTIONS_HADDOCK hide #-} -- | -- Module : Data.ByteString.Fusion -- License : BSD-style -- Maintainer : dons@cse.unsw.edu.au -- Stability : experimental -- Portability : portable -- -- Stream fusion for ByteStrings. -- -- See the paper /Stream Fusion: From Lists to Streams to Nothing at All/, -- Coutts, Leshchinskiy and Stewart, 2007. -- module Data.ByteString.Fusion ( -- A place holder for Stream Fusion ) where
markflorisson/hpack
testrepo/bytestring-0.9.1.9/Data/ByteString/Fusion.hs
Haskell
bsd-3-clause
445
module SudokuParser(parseMatrix) where import Text.ParserCombinators.Parsec import Data.Char parseMatrix :: Parser [[Int]] parseMatrix = do result <- count 9 parseLine _ <- eof return result parseLine :: Parser [Int] parseLine = do result <- count 9 parseDigit _ <- eol return result parseDigit :: Parser Int parseDigit = do result <- digit return (digitToInt result) eol :: Parser String eol = try (string "\n\r") <|> try (string "\r\n") <|> string "\n" <|> string "\r" <?> "end of line"
jaapterwoerds/algorithmx
src/SudokuParser.hs
Haskell
bsd-3-clause
576
module Game.Data( Game(..) ) where import GHC.Generics import Control.DeepSeq data Game = Game { gameExit :: Bool } deriving (Generic) instance NFData Game
Teaspot-Studio/gore-and-ash-game
src/client/Game/Data.hs
Haskell
bsd-3-clause
176
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Criterion.Collection.Internal.Types ( Workload(..) , WorkloadGenerator , WorkloadMonad(..) , runWorkloadMonad , getRNG , DataStructure(..) , setupData , setupDataIO ) where ------------------------------------------------------------------------------ import Control.DeepSeq import Control.Monad.Reader import Data.Vector (Vector) import System.Random.MWC ------------------------------------------------------------------------------ -- Some thoughts on benchmarking modes -- -- * pre-fill data structure, test an operation workload without modifying the -- data structure, measure time for each operation -- -- ---> allows you to get fine-grained per-operation times with distributions -- -- * pre-fill data structure, get a bunch of work to do (cumulatively modifying -- the data structure), measure time per-operation OR for the whole batch and -- divide out -- -- -- Maybe it will look like this? -- > data MeasurementMode = PerBatch | PerOperation -- > data WorkloadMode = Pure | Mutating ------------------------------------------------------------------------------ newtype WorkloadMonad a = WM (ReaderT GenIO IO a) deriving (Monad, MonadIO) ------------------------------------------------------------------------------ runWorkloadMonad :: WorkloadMonad a -> GenIO -> IO a runWorkloadMonad (WM m) gen = runReaderT m gen ------------------------------------------------------------------------------ getRNG :: WorkloadMonad GenIO getRNG = WM ask ------------------------------------------------------------------------------ -- | Given an 'Int' representing \"input size\", a 'WorkloadGenerator' makes a -- 'Workload'. @Workload@s generate operations to prepopulate data structures -- with /O(n)/ data items, then generate operations on-demand to benchmark your -- data structure according to some interesting distribution. type WorkloadGenerator op = Int -> WorkloadMonad (Workload op) ------------------------------------------------------------------------------ data Workload op = Workload { -- | \"Setup work\" is work that you do to prepopulate a data structure -- to a certain size before testing begins. setupWork :: !(Vector op) -- | Given the number of operations to produce, 'genWorkload' spits out a -- randomly-distributed workload simulation to be used in the benchmark. -- -- | Some kinds of skewed workload distributions (the canonical example -- being \"frequent lookups for a small set of keys and infrequent -- lookups for the others\") need a certain minimum number of operations -- to be generated to be statistically valid, which only the -- 'WorkloadGenerator' would know how to decide. In these cases, you are -- free to return more than @N@ samples from 'genWorkload', and -- @criterion-collection@ will run them all for you. -- -- Otherwise, @criterion-collection@ is free to bootstrap your benchmark -- using as many sample points as it would take to make the results -- statistically relevant. , genWorkload :: !(Int -> WorkloadMonad (Vector op)) } ------------------------------------------------------------------------------ data DataStructure op = forall m . DataStructure { emptyData :: !(Int -> IO m) , runOperation :: !(m -> op -> IO m) } ------------------------------------------------------------------------------ setupData :: m -> (m -> op -> m) -> DataStructure op setupData e r = DataStructure (const $ return e) (\m o -> return $ r m o) ------------------------------------------------------------------------------ setupDataIO :: (Int -> IO m) -> (m -> op -> IO m) -> DataStructure op setupDataIO = DataStructure
cornell-pl/HsAdapton
weak-hashtables/benchmark/src/Criterion/Collection/Internal/Types.hs
Haskell
bsd-3-clause
3,932
module EventLoop ( eventLoop ) where import Control.Monad (unless) import Graphics.UI.GLFW (Key (..), KeyState (..), Window, getKey, pollEvents, swapBuffers, windowShouldClose) -- | A simple rendering event loop which repeats the provided action until ESC is -- pressed or that a close event is created otherwise. eventLoop :: Window -> IO () -> IO () eventLoop window action = go where go :: IO () go = do pollEvents action swapBuffers window escState <- getKey window Key'Escape shouldClose <- windowShouldClose window unless (shouldClose || escState == KeyState'Pressed) go
psandahl/outdoor-terrain
src/EventLoop.hs
Haskell
bsd-3-clause
754
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TupleSections #-} module Language.Haskell.Liquid.Bare.DataType ( makeConTypes , makeTyConEmbeds , dataConSpec , meetDataConSpec ) where import DataCon import TyCon import Var import Control.Applicative ((<$>)) import Data.Maybe import Data.Monoid import qualified Data.List as L import qualified Data.HashMap.Strict as M import Language.Fixpoint.Misc (errorstar) import Language.Fixpoint.Types (Symbol, TCEmb, meet) import Language.Haskell.Liquid.GHC.Misc (symbolTyVar) import Language.Haskell.Liquid.Types.PredType (dataConPSpecType) import Language.Haskell.Liquid.Types.RefType (mkDataConIdsTy, ofType, rApp, rVar, uPVar) import Language.Haskell.Liquid.Types import Language.Haskell.Liquid.Misc (mapSnd) import Language.Haskell.Liquid.Types.Variance import Language.Haskell.Liquid.WiredIn import qualified Language.Haskell.Liquid.Measure as Ms import Language.Haskell.Liquid.Bare.Env import Language.Haskell.Liquid.Bare.Lookup import Language.Haskell.Liquid.Bare.OfType ----------------------------------------------------------------------- -- Bare Predicate: DataCon Definitions -------------------------------- ----------------------------------------------------------------------- makeConTypes (name,spec) = inModule name $ makeConTypes' (Ms.dataDecls spec) (Ms.dvariance spec) makeConTypes' :: [DataDecl] -> [(LocSymbol, [Variance])] -> BareM ([(TyCon, TyConP)], [[(DataCon, Located DataConP)]]) makeConTypes' dcs vdcs = unzip <$> mapM (uncurry ofBDataDecl) (group dcs vdcs) where group ds vs = merge (L.sort ds) (L.sortBy (\x y -> compare (fst x) (fst y)) vs) merge (d:ds) (v:vs) | tycName d == fst v = (Just d, Just v) : merge ds vs | tycName d < fst v = (Just d, Nothing) : merge ds (v:vs) | otherwise = (Nothing, Just v) : merge (d:ds) vs merge [] vs = ((Nothing,) . Just) <$> vs merge ds [] = ((,Nothing) . Just) <$> ds dataConSpec :: [(DataCon, DataConP)]-> [(Var, (RType RTyCon RTyVar RReft))] dataConSpec dcs = concatMap mkDataConIdsTy [(dc, dataConPSpecType dc t) | (dc, t) <- dcs] meetDataConSpec xts dcs = M.toList $ L.foldl' upd dcm xts where dcm = M.fromList $ dataConSpec dcs upd dcm (x, t) = M.insert x (maybe t (meet t) (M.lookup x dcm)) dcm ofBDataDecl :: Maybe DataDecl -> (Maybe (LocSymbol, [Variance])) -> BareM ((TyCon, TyConP), [(DataCon, Located DataConP)]) ofBDataDecl (Just (D tc as ps ls cts _ sfun)) maybe_invariance_info = do πs <- mapM ofBPVar ps tc' <- lookupGhcTyCon tc cts' <- mapM (ofBDataCon lc lc' tc' αs ps ls πs) cts let tys = [t | (_, dcp) <- cts', (_, t) <- tyArgs dcp] let initmap = zip (uPVar <$> πs) [0..] let varInfo = L.nub $ concatMap (getPsSig initmap True) tys let defaultPs = varSignToVariance varInfo <$> [0 .. (length πs - 1)] let (tvarinfo, pvarinfo) = f defaultPs return ((tc', TyConP αs πs ls tvarinfo pvarinfo sfun), (mapSnd (Loc lc lc') <$> cts')) where αs = RTV . symbolTyVar <$> as n = length αs lc = loc tc lc' = locE tc f defaultPs = case maybe_invariance_info of {Nothing -> ([], defaultPs); Just (_,is) -> (take n is, if null (drop n is) then defaultPs else (drop n is))} varSignToVariance varsigns i = case filter (\p -> fst p == i) varsigns of [] -> Invariant [(_, b)] -> if b then Covariant else Contravariant _ -> Bivariant ofBDataDecl Nothing (Just (tc, is)) = do tc' <- lookupGhcTyCon tc return ((tc', TyConP [] [] [] tcov tcontr Nothing), []) where (tcov, tcontr) = (is, []) ofBDataDecl Nothing Nothing = errorstar $ "Bare.DataType.ofBDataDecl called on invalid inputs" getPsSig m pos (RAllT _ t) = getPsSig m pos t getPsSig m pos (RApp _ ts rs r) = addps m pos r ++ concatMap (getPsSig m pos) ts ++ concatMap (getPsSigPs m pos) rs getPsSig m pos (RVar _ r) = addps m pos r getPsSig m pos (RAppTy t1 t2 r) = addps m pos r ++ getPsSig m pos t1 ++ getPsSig m pos t2 getPsSig m pos (RFun _ t1 t2 r) = addps m pos r ++ getPsSig m pos t2 ++ getPsSig m (not pos) t1 getPsSig m pos (RHole r) = addps m pos r getPsSig _ _ z = error $ "getPsSig" ++ show z getPsSigPs m pos (RProp _ (RHole r)) = addps m pos r getPsSigPs m pos (RProp _ t) = getPsSig m pos t addps m pos (MkUReft _ ps _) = (flip (,)) pos . f <$> pvars ps where f = fromMaybe (error "Bare.addPs: notfound") . (`L.lookup` m) . uPVar -- TODO:EFFECTS:ofBDataCon ofBDataCon l l' tc αs ps ls πs (c, xts) = do c' <- lookupGhcDataCon c ts' <- mapM (mkSpecType' l ps) ts let cs = map ofType (dataConStupidTheta c') let t0 = rApp tc rs (rPropP [] . pdVarReft <$> πs) mempty return $ (c', DataConP l αs πs ls cs (reverse (zip xs ts')) t0 l') where (xs, ts) = unzip xts rs = [rVar α | RTV α <- αs] makeTyConEmbeds (mod, spec) = inModule mod $ makeTyConEmbeds' $ Ms.embeds spec makeTyConEmbeds' :: TCEmb (Located Symbol) -> BareM (TCEmb TyCon) makeTyConEmbeds' z = M.fromList <$> mapM tx (M.toList z) where tx (c, y) = (, y) <$> lookupGhcTyCon c
abakst/liquidhaskell
src/Language/Haskell/Liquid/Bare/DataType.hs
Haskell
bsd-3-clause
5,429
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeOperators #-} module Plowtech.Service.Types where import Control.Applicative import Control.Lens import Control.Lens.TH import Control.Monad (mzero) import Control.Monad.Trans.Either import Data.Aeson import Data.Map (Map()) import qualified Data.Map as Map import Data.Maybe import Data.Proxy import Data.Serialize hiding (encode, decode, Get) import Data.Text (Text) import Data.Vinyl import Data.Vinyl.Aeson import Data.Vinyl.Lens import Data.Vinyl.Functor (Const(..), Identity(..), Compose(..)) import GHC.TypeLits import Plowtech.Records.FullTagKey import Servant.API import Data.Vinyl.TypeLevel import Data.Master.Template import Data.Master.Examples (Generatable(..)) -- Orphan instances :\ instance (Eq (f (g x))) => Eq (Compose f g x) where (Compose a) == (Compose b) = a == b instance (Show (f (g x))) => Show (Compose f g x) where show (Compose x) = show x instance (Bounded a) => Bounded (Maybe a) where minBound = Nothing maxBound = Just maxBound instance (Enum a) => Enum (Maybe a) where toEnum x = if x == 0 then Nothing else Just $ toEnum $ x -1 fromEnum Nothing = 0 fromEnum (Just x) = fromEnum x + 1 -- | A newtype for JSON-encoding FullTagKey records newtype FullTagKeyJSON = FullTagKeyJSON { _fullTagKeyJSON :: FullTagKey } fullTagKeyJSON :: Iso' FullTagKey FullTagKeyJSON fullTagKeyJSON = iso FullTagKeyJSON _fullTagKeyJSON instance Checkable FullTagKeyJSON where type Template FullTagKeyJSON = FullTagKeyTemplateJSON type Result FullTagKeyJSON = FullTagKeyValidationJSON checkTemplate template candidate = checkTemplate (template ^. from fullTagKeyTemplateJSON) (candidate ^. from fullTagKeyJSON) ^. fullTagKeyValidationJSON success _ = success (Proxy :: Proxy FullTagKeyValidation) . (^. from fullTagKeyValidationJSON) newtype FullTagKeyValidationJSON = FullTagKeyValidationJSON { _fullTagKeyValidationJSON :: FullTagKeyValidation } fullTagKeyValidationJSON :: Iso' FullTagKeyValidation FullTagKeyValidationJSON fullTagKeyValidationJSON = iso FullTagKeyValidationJSON _fullTagKeyValidationJSON newtype FullTagKeyExamplesJSON = FullTagKeyExamplesJSON { _fullTagKeyExamplesJSON :: FullTagKeyExamples } deriving instance (RecAll (Compose [] FullTagKeyAttr) FullTagKeyFields Show) => Show FullTagKeyExamplesJSON fullTagKeyExamplesJSON :: Iso' FullTagKeyExamples FullTagKeyExamplesJSON fullTagKeyExamplesJSON = iso FullTagKeyExamplesJSON _fullTagKeyExamplesJSON instance Generatable FullTagKeyJSON where type Examples FullTagKeyJSON = FullTagKeyExamplesJSON generateExamples _ template = generateExamples (Proxy :: Proxy FullTagKey) (template ^. from fullTagKeyTemplateJSON) ^. fullTagKeyExamplesJSON instance FromJSON FullTagKeyExamplesJSON where parseJSON = (FullTagKeyExamplesJSON <$>) . recordFromJSON instance ToJSON FullTagKeyExamplesJSON where toJSON = recordToJSON . _fullTagKeyExamplesJSON -- | Fields for the Named record type family NamedField a (field :: Symbol) where NamedField a "name" = Text NamedField a "record" = a -- | Attribute type for the Named record newtype NamedAttr a (field :: Symbol) = NamedAttr { _namedAttr :: NamedField a field } deriving instance (Eq (NamedField a field)) => Eq (NamedAttr a field) namedAttr :: Iso' (NamedField a field) (NamedAttr a field) namedAttr = iso NamedAttr _namedAttr -- | The Named record type Named a = Rec (NamedAttr a) '["name", "record"] -- | A newtype for JSON-encoding Named records newtype NamedJSON a = NamedJSON { _namedJSON :: Named a } deriving instance (Eq (Named a)) => Eq (NamedJSON a) namedJSON :: Iso' (Named a) (NamedJSON a) namedJSON = iso NamedJSON _namedJSON -- | A newtype for JSON-encoding FullTagKeyTemplate records newtype FullTagKeyTemplateJSON = FullTagKeyTemplateJSON { _fullTagKeyTemplateJSON :: FullTagKeyTemplate } fullTagKeyTemplateJSON :: Iso' FullTagKeyTemplate FullTagKeyTemplateJSON fullTagKeyTemplateJSON = iso FullTagKeyTemplateJSON _fullTagKeyTemplateJSON instance Eq FullTagKeyTemplateJSON where (FullTagKeyTemplateJSON a) == (FullTagKeyTemplateJSON b) = (eqReqOn (Proxy :: Proxy "pc") a b) && (eqReqOn (Proxy :: Proxy "slave_id") a b) && (eqReqOn (Proxy :: Proxy "tag_name") a b) && (eqReqOn (Proxy :: Proxy "index") a b) eqReqOn :: (RElem r FullTagKeyFields (RIndex r FullTagKeyFields), (Eq (FullTagKeyField r))) => sing r -> Rec (TemplatesFor Normalized Disjunction FullTagKeyAttr) FullTagKeyFields -> Rec (TemplatesFor Normalized Disjunction FullTagKeyAttr) FullTagKeyFields -> Bool eqReqOn rl template1 template2 = (getCompose $ template1 ^. (rlens rl)) == (getCompose $ template2 ^. (rlens rl)) -- | The Servant API for validation type FullTagKeyValidatorAPI = "templates" :> Get '[JSON] [NamedJSON (Map Text (Has FullTagKeyTemplateJSON))] :<|> "templates" :> ReqBody '[JSON] (NamedJSON (Map Text (Has FullTagKeyTemplateJSON))) :> Post '[JSON] () :<|> "templates" :> Capture "name" Text :> Get '[JSON] (Map Text (Has FullTagKeyTemplateJSON)) :<|> "validate" :> Capture "name" Text :> ReqBody '[JSON] (Map Text FullTagKeyJSON) :> Post '[JSON] (Map Text (MapCheckResult FullTagKeyTemplateJSON FullTagKeyJSON FullTagKeyValidationJSON)) :<|> "examples" :> Capture "name" Text :> Get '[JSON] (Map Text (Has FullTagKeyExamplesJSON)) :<|> Raw instance ToJSON FullTagKeyJSON where toJSON = recordToJSON . _fullTagKeyJSON instance FromJSON FullTagKeyJSON where parseJSON = (FullTagKeyJSON <$>) . recordFromJSON instance (ToJSON a) => ToJSON (NamedJSON a) where toJSON = recordToJSON . _namedJSON instance (FromJSON a) => FromJSON (NamedJSON a) where parseJSON = (NamedJSON <$>) . recordFromJSON instance ToJSON FullTagKeyTemplateJSON where toJSON = recordToJSON . _fullTagKeyTemplateJSON instance FromJSON FullTagKeyTemplateJSON where parseJSON = (FullTagKeyTemplateJSON <$>) . recordFromJSON instance ToJSON FullTagKeyValidationJSON where toJSON = recordToJSON . _fullTagKeyValidationJSON instance FromJSON FullTagKeyValidationJSON where parseJSON = (FullTagKeyValidationJSON <$>) . recordFromJSON instance (ToJSON (NamedField a field)) => ToJSON (NamedAttr a field) where toJSON = toJSON . _namedAttr instance (FromJSON (NamedField a field)) => FromJSON (NamedAttr a field) where parseJSON = (NamedAttr <$>) . parseJSON instance (FromJSON a, ToJSON a) => Serialize (NamedJSON a) where put = put . encode get = get >>= maybe mzero return . decode -- | The proxy for the validation Servant API type fullTagKeyValidatorAPI :: Proxy FullTagKeyValidatorAPI fullTagKeyValidatorAPI = Proxy
plow-technologies/template-service
src/Plowtech/Service/Types.hs
Haskell
bsd-3-clause
7,042
module Data.LLVM.Types.Identifiers ( -- * Types Identifier, -- * Accessor identifierAsString, identifierContent, isAnonymousIdentifier, -- * Builders makeAnonymousLocal, makeLocalIdentifier, makeGlobalIdentifier, makeMetaIdentifier ) where import Control.DeepSeq import Data.Hashable import Data.Text ( Text, unpack, pack ) data Identifier = LocalIdentifier { _identifierContent :: !Text , _identifierHash :: !Int } | AnonymousLocalIdentifier { _identifierNumber :: !Int } | GlobalIdentifier { _identifierContent :: !Text , _identifierHash :: !Int } | MetaIdentifier { _identifierContent :: !Text , _identifierHash :: !Int } deriving (Eq, Ord) instance Show Identifier where show LocalIdentifier { _identifierContent = t } = '%' : unpack t show AnonymousLocalIdentifier { _identifierNumber = n } = '%' : show n show GlobalIdentifier { _identifierContent = t } = '@' : unpack t show MetaIdentifier { _identifierContent = t } = '!' : unpack t instance Hashable Identifier where hashWithSalt s (AnonymousLocalIdentifier n) = s `hashWithSalt` n hashWithSalt s i = s `hashWithSalt` _identifierHash i instance NFData Identifier where rnf AnonymousLocalIdentifier {} = () rnf i = _identifierContent i `seq` _identifierHash i `seq` () makeAnonymousLocal :: Int -> Identifier makeAnonymousLocal = AnonymousLocalIdentifier makeLocalIdentifier :: Text -> Identifier makeLocalIdentifier t = LocalIdentifier { _identifierContent = t , _identifierHash = hash t } makeGlobalIdentifier :: Text -> Identifier makeGlobalIdentifier t = GlobalIdentifier { _identifierContent = t , _identifierHash = hash t } makeMetaIdentifier :: Text -> Identifier makeMetaIdentifier t = MetaIdentifier { _identifierContent = t , _identifierHash = hash t } identifierAsString :: Identifier -> String identifierAsString (AnonymousLocalIdentifier n) = show n identifierAsString i = unpack (identifierContent i) identifierContent :: Identifier -> Text identifierContent (AnonymousLocalIdentifier n) = pack (show n) identifierContent i = _identifierContent i isAnonymousIdentifier :: Identifier -> Bool isAnonymousIdentifier AnonymousLocalIdentifier {} = True isAnonymousIdentifier _ = False
travitch/llvm-base-types
src/Data/LLVM/Types/Identifiers.hs
Haskell
bsd-3-clause
2,587
module Main ( (|>) , (>>>) ) where import Operators ((|>), (>>>)) test :: [Int] -> Int test = foldr 1.0 (*) test2 :: a -> a -> ( a, a ) test2 = (,) (|>) :: a -> (a -> b) -> b (|>) v f = f v
hecrj/haskell-format
test/specs/operators/output.hs
Haskell
bsd-3-clause
221
{-# LANGUAGE ScopedTypeVariables, TypeFamilies, TupleSections #-} module Fuml.Core where import qualified Data.Vector.Storable as VS import Numeric.LinearAlgebra import Data.List (nub) import Lens.Micro import Control.Monad.Identity data Weighted o = Weighted Double o -- |The result of running a predictive model data Predict p a = Predict { model :: p -- ^ the internal state of the model , predict :: Vector Double -> a -- ^ the prediction function } instance Functor (Predict p) where fmap f (Predict m predf) = Predict m (f . predf) newtype Supervisor m o p a = Supervisor { runSupervisor :: Maybe p -> [(Vector Double, o)] -> m (Predict p a) } instance Functor m => Functor (Supervisor m o p) where fmap f (Supervisor sf) = Supervisor $ \mp d -> fmap (fmap f) $ sf mp d -- | Helper function for running simple Supervisors in the Identity monad runSupervisor' :: Supervisor Identity o p a -- ^ the 'Supervisor' value -> [(Vector Double, o)] -- ^ the dataset -> Predict p a -- ^ the 'Predict' value runSupervisor' (Supervisor sf) = runIdentity . sf Nothing oneVsRest :: (Monad m, Eq a, Functor m) => Supervisor m Bool p b -> Supervisor m a [(a,p)] [(a,b)] oneVsRest subsuper = Supervisor $ \_ theData -> do let classes = nub $ map snd theData boolize c (v, c1) = (v, c == c1) train c = fmap (c,) $ runSupervisor subsuper Nothing $ map (boolize c) theData models <- mapM train classes return $ Predict (map (over _2 model) models) $ \v -> map (\(c,pr) -> (c, predict pr v)) models (~~) :: (a -> o) -> [a -> Double] -> [a] -> [(Vector Double, o)] fy ~~ fxs = let f w = (VS.fromList (map ($w) fxs) , fy w) in map f --prepare :: (a -> o) -> [a -> Double] -> [a] -> [(Vector Double, o)] --prepare fo fxs d = fo ~~ fxs $ d
diffusionkinetics/open
fuml/lib/Fuml/Core.hs
Haskell
mit
1,869
-- HACKERRANK: Super Digit -- https://www.hackerrank.com/challenges/super-digit module Main where digits :: Integer -> [Integer] digits 0 = [] digits n = m : rest where m = mod n 10 rest = digits (div n 10) solve :: Integer -> Integer solve n = if n < 10 then n else solve $ sum $ digits n main :: IO () main = do nkStr <- getLine let (n:k:_) = map (read :: String -> Integer) $ words nkStr let input = sum (digits n) * k putStrLn $ show (solve input)
everyevery/programming_study
hackerrank/functional/super-digit/super-digit.hs
Haskell
mit
516
{-# LANGUAGE DeriveDataTypeable, CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Signal -- Copyright : (c) Andrea Rosatto -- : (c) Jose A. Ortega Ruiz -- : (c) Jochen Keil -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org> -- Stability : unstable -- Portability : unportable -- -- Signal handling, including DBUS when available -- ----------------------------------------------------------------------------- module Signal where import Data.Typeable (Typeable) import Control.Concurrent.STM import Control.Exception hiding (handle) import System.Posix.Signals import Graphics.X11.Xlib.Types (Position) #ifdef DBUS import DBus (IsVariant(..)) import Control.Monad ((>=>)) #endif import Plugins.Utils (safeHead) data WakeUp = WakeUp deriving (Show,Typeable) instance Exception WakeUp data SignalType = Wakeup | Reposition | ChangeScreen | Hide Int | Reveal Int | Toggle Int | TogglePersistent | Action Position deriving (Read, Show) #ifdef DBUS instance IsVariant SignalType where toVariant = toVariant . show fromVariant = fromVariant >=> parseSignalType #endif parseSignalType :: String -> Maybe SignalType parseSignalType = fmap fst . safeHead . reads -- | Signal handling setupSignalHandler :: IO (TMVar SignalType) setupSignalHandler = do tid <- newEmptyTMVarIO installHandler sigUSR2 (Catch $ updatePosHandler tid) Nothing installHandler sigUSR1 (Catch $ changeScreenHandler tid) Nothing return tid updatePosHandler :: TMVar SignalType -> IO () updatePosHandler sig = do atomically $ putTMVar sig Reposition return () changeScreenHandler :: TMVar SignalType -> IO () changeScreenHandler sig = do atomically $ putTMVar sig ChangeScreen return ()
tsiliakis/xmobar
src/Signal.hs
Haskell
bsd-3-clause
1,955
{-# LANGUAGE OverloadedStrings #-} module Site.Blog ( rules ) where import Control.Monad import Data.Monoid import Hakyll import System.FilePath import Site.Config import Site.Compilers -- | Blog post page blogPostPage :: Tags -> Pipeline String String blogPostPage tags = prePandoc >=> pandoc >=> saveSnapshot "content" >=> postRender >=> postPandoc cxt where postRender = loadAndApplyTemplate postT cxt cxt = postContext <> tagsField "postTags" tags -- | Blog archive page. blogArchivePage :: Tags -- ^ classify based on year -> Tags -- ^ classify based on tags. -> Pipeline String String blogArchivePage yearlyPosts tags = prePandoc >=> pandoc >=> archiveRender >=> postPandoc cxt where archiveRender = loadAndApplyTemplate archiveIndexT cxt cxt = constField "title" "Posts Archive" <> siteContext <> tagCloudField "tagcloud" tagCloudMin tagCloudMax tags <> tagListField "oldPosts" yearlyPosts tagListField key tgs = field key $ \ _ -> renderTagList tgs -- | Generating feeds. compileFeeds :: Compiler [Item String] compileFeeds = loadAllSnapshots postsPat "content" >>= fmap (take postsOnFeed) . recentFirst >>= mapM relativizeUrls -- | Generating a tags page makeTagRules :: Identifier -> String -> Pattern -> Rules () makeTagRules template tag pat = do route idRoute compile $ makeItem "" >>= prePandoc >>= pandoc >>= loadAndApplyTemplate template tagContext >>= postPandoc tagContext where tagContext = postContext <> constField "tag" tag <> listField "posts" postContext tagPosts tagPosts = loadPosts pat -- | This function generates the year of the post from its -- identifier. This is used in building the archives. getYear :: Identifier -> String getYear = takeWhile (/= '-') . takeFileName . toFilePath rules :: Rules () rules = do -- -- Classify posts based on tags. -- postTags <- buildTags "posts/*" $ fromCapture "posts/tags/*.html" -- Generate the tags page tagsRules postTags $ makeTagRules tagT -- -- Compiling individual posts. -- match postsPat $ do route $ setExtension "html" compilePipeline $ blogPostPage postTags -- -- Create atom/rss feeds feeds. -- let feedContext = postContext <> bodyField "description" in do create ["posts/feeds/atom.xml"] $ do route idRoute compile $ compileFeeds >>= renderAtom feedConfig feedContext create ["posts/feeds/rss.xml"] $ do route idRoute compile $ compileFeeds >>= renderRss feedConfig feedContext -- -- Creating the archive. -- let yearTag ident = return [getYear ident] in do dateTags <- buildTagsWith yearTag "posts/*" $ fromCapture "posts/archive/*.html" tagsRules dateTags $ makeTagRules archiveT -- Creating the index page of the archive create ["posts/archive/index.html"] $ do route idRoute compile $ makeItem "" >>= blogArchivePage dateTags postTags
piyush-kurur-pages/website
Site/Blog.hs
Haskell
bsd-3-clause
3,238
----------------------------------------------------------------------------- -- | -- Module : Data.Permute.IO -- Copyright : Copyright (c) , Patrick Perry <patperry@stanford.edu> -- License : BSD3 -- Maintainer : Patrick Perry <patperry@stanford.edu> -- Stability : experimental -- -- Mutable permutations in the 'IO' monad. module Data.Permute.IO ( -- * Permutations IOPermute, -- * Overloaded mutable permutation interface module Data.Permute.MPermute ) where import Data.Permute.IOBase( IOPermute ) import Data.Permute.MPermute
patperry/permutation
lib/Data/Permute/IO.hs
Haskell
bsd-3-clause
568
-- Copyright (c) 2015-2020 Rudy Matela. -- Distributed under the 3-Clause BSD licence (see the file LICENSE). {-# LANGUAGE TemplateHaskell, CPP #-} import Test -- import Test.LeanCheck -- already exported by Test import Test.LeanCheck.Derive import System.Exit (exitFailure) import Data.List (elemIndices,sort) import Test.LeanCheck.Utils data D0 = D0 deriving Show data D1 a = D1 a deriving Show data D2 a b = D2 a b deriving Show data D3 a b c = D3 a b c deriving Show data C1 a = C11 a | C10 deriving Show data C2 a b = C22 a b | C21 a | C20 deriving Show data I a b = a :+ b deriving Show deriveListable ''D0 deriveListable ''D1 deriveListable ''D2 deriveListable ''D3 deriveListable ''C1 deriveListable ''C2 deriveListable ''I -- recursive datatypes data Peano = Zero | Succ Peano deriving Show data List a = a :- List a | Nil deriving Show data Bush a = Bush a :-: Bush a | Leaf a deriving (Show, Eq) data Tree a = Node (Tree a) a (Tree a) | Null deriving (Show, Eq) deriveListable ''Peano deriveListable ''List deriveListable ''Bush deriveListable ''Tree -- Nested datatype cascade data Nested = Nested N0 (N1 Int) (N2 Int Int) data N0 = R0 Int data N1 a = R1 a data N2 a b = R2 a b deriveListableCascading ''Nested -- Recursive nested datatype cascade data RN = RN RN0 (RN1 Int) (RN2 Int RN) data RN0 = Nest0 Int | Recurse0 RN data RN1 a = Nest1 a | Recurse1 RN data RN2 a b = Nest2 a b | Recurse2 RN deriveListableCascading ''RN -- Type synonyms data Pair a = Pair a a type Alias a = Pair a -- deriveListable ''Alias -- this will fail deriveListableCascading ''Alias deriveListableIfNeeded ''Alias -- only works because instance already exists -- Nested type synonyms data Triple a = Triple a a a type Tralias a = Triple a data Pairiple a = Pairriple (Tralias a) (Tralias a) deriveListableCascading ''Pairiple -- Those should have no effect (instance already exists): {- uncommenting those should generate warnings deriveListable ''Bool deriveListable ''Maybe deriveListable ''Either -} -- Those should not generate warnings deriveListableIfNeeded ''Bool deriveListableIfNeeded ''Maybe deriveListableIfNeeded ''Either main :: IO () main = do max <- getMaxTestsFromArgs 200 case elemIndices False (tests max) of [] -> putStrLn "Tests passed!" is -> do putStrLn ("Failed tests:" ++ show is) exitFailure tests :: Int -> [Bool] tests n = [ True , map unD0 list =| n |= list , map unD1 list =| n |= (list :: [Int]) , map unD2 list =| n |= (list :: [(Int,Int)]) , map unD3 list =| n |= (list :: [(Int,Int,Int)]) , map unD1 list == (list :: [()]) , map unD2 list == (list :: [((),())]) , map unD3 list == (list :: [((),(),())]) , map unD1 list == (list :: [Bool]) , map unD2 list == (list :: [(Bool,Bool)]) , map unD3 list == (list :: [(Bool,Bool,Bool)]) , map peanoToNat list =| n |= list , map listToList list =| n |= (list :: [[Bool]]) , map listToList list =| n |= (list :: [[Int]]) , mapT peanoToNat tiers =| 6 |= tiers , mapT listToList tiers =| 6 |= (tiers :: [[ [Bool] ]]) , mapT listToList tiers =| 6 |= (tiers :: [[ [Int] ]]) , take 6 (list :: [Bush Bool]) == [ Leaf False , Leaf True , Leaf False :-: Leaf False , Leaf False :-: Leaf True , Leaf True :-: Leaf False , Leaf True :-: Leaf True ] , take 6 (list :: [Tree Bool]) == [ Null , Node Null False Null , Node Null True Null , Node Null False (Node Null False Null) , Node Null False (Node Null True Null) , Node Null True (Node Null False Null) ] , (tiers :: [[ Bool ]]) =| 6 |= $(deriveTiers ''Bool) , (tiers :: [[ [Int] ]]) =| 6 |= $(deriveTiers ''[]) , (tiers :: [[ [Bool] ]]) =| 6 |= $(deriveTiers ''[]) , (tiers :: [[ Maybe Int ]]) =| 6 |= $(deriveTiers ''Maybe) , (tiers :: [[ Maybe Bool ]]) =| 6 |= $(deriveTiers ''Maybe) , ([]:tiers :: [[Either Bool Int]]) =$ map sort . take 6 $= $(deriveTiers ''Either) , (list :: [ Bool ]) =| n |= $(deriveList ''Bool) , (list :: [ [Int] ]) =| n |= $(deriveList ''[]) , (list :: [ [Bool] ]) =| n |= $(deriveList ''[]) , (list :: [ Maybe Int ]) =| n |= $(deriveList ''Maybe) , (list :: [ Maybe Bool ]) =| n |= $(deriveList ''Maybe) ] where unD0 (D0) = () unD1 (D1 x) = (x) unD2 (D2 x y) = (x,y) unD3 (D3 x y z) = (x,y,z) peanoToNat :: Peano -> Nat peanoToNat Zero = 0 peanoToNat (Succ n) = 1 + peanoToNat n listToList :: List a -> [a] listToList Nil = [] listToList (x :- xs) = x : listToList xs
rudymatela/leancheck
test/derive.hs
Haskell
bsd-3-clause
4,696
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ur-PK"> <title>Plug-n-Hack | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_ur_PK/helpset_ur_PK.hs
Haskell
apache-2.0
972
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ViewPatterns #-} module Stack.Types.Compiler where import Control.DeepSeq import Control.DeepSeq.Generics (genericRnf) import Data.Aeson import Data.Binary (Binary) import Data.Monoid ((<>)) import qualified Data.Text as T import GHC.Generics (Generic) import Stack.Types.Version -- | Variety of compiler to use. data WhichCompiler = Ghc | Ghcjs deriving (Show, Eq, Ord) -- | Specifies a compiler and its version number(s). -- -- Note that despite having this datatype, stack isn't in a hurry to -- support compilers other than GHC. -- -- NOTE: updating this will change its binary serialization. The -- version number in the 'BinarySchema' instance for 'MiniBuildPlan' -- should be updated. data CompilerVersion = GhcVersion {-# UNPACK #-} !Version | GhcjsVersion {-# UNPACK #-} !Version -- GHCJS version {-# UNPACK #-} !Version -- GHC version deriving (Generic, Show, Eq, Ord) instance Binary CompilerVersion instance NFData CompilerVersion where rnf = genericRnf instance ToJSON CompilerVersion where toJSON = toJSON . compilerVersionName instance FromJSON CompilerVersion where parseJSON (String t) = maybe (fail "Failed to parse compiler version") return (parseCompilerVersion t) parseJSON _ = fail "Invalid CompilerVersion, must be String" parseCompilerVersion :: T.Text -> Maybe CompilerVersion parseCompilerVersion t | Just t' <- T.stripPrefix "ghc-" t , Just v <- parseVersionFromString $ T.unpack t' = Just (GhcVersion v) | Just t' <- T.stripPrefix "ghcjs-" t , [tghcjs, tghc] <- T.splitOn "_ghc-" t' , Just vghcjs <- parseVersionFromString $ T.unpack tghcjs , Just vghc <- parseVersionFromString $ T.unpack tghc = Just (GhcjsVersion vghcjs vghc) | otherwise = Nothing compilerVersionName :: CompilerVersion -> T.Text compilerVersionName (GhcVersion vghc) = "ghc-" <> versionText vghc compilerVersionName (GhcjsVersion vghcjs vghc) = "ghcjs-" <> versionText vghcjs <> "_ghc-" <> versionText vghc whichCompiler :: CompilerVersion -> WhichCompiler whichCompiler GhcVersion {} = Ghc whichCompiler GhcjsVersion {} = Ghcjs isWantedCompiler :: VersionCheck -> CompilerVersion -> CompilerVersion -> Bool isWantedCompiler check (GhcVersion wanted) (GhcVersion actual) = checkVersion check wanted actual isWantedCompiler check (GhcjsVersion wanted wantedGhc) (GhcjsVersion actual actualGhc) = checkVersion check wanted actual && checkVersion check wantedGhc actualGhc isWantedCompiler _ _ _ = False compilerExeName :: WhichCompiler -> String compilerExeName Ghc = "ghc" compilerExeName Ghcjs = "ghcjs" haddockExeName :: WhichCompiler -> String haddockExeName Ghc = "haddock" haddockExeName Ghcjs = "haddock-ghcjs"
akhileshs/stack
src/Stack/Types/Compiler.hs
Haskell
bsd-3-clause
2,898
module E.Eta( ArityType(ATop,ABottom), etaExpandAp, annotateArity, deleteArity, etaExpandDef, etaExpandDef', etaExpandProgram, getArityInfo, etaAnnotateProgram, etaReduce ) where import Control.Monad.Identity import Control.Monad.State import Control.Monad.Writer import Data.Typeable import DataConstructors import E.Annotate import E.E import E.Inline import E.Program import E.Subst import E.TypeCheck import E.Values import GenUtil hiding(replicateM_) import Info.Types import Name.Id import Support.FreeVars import Util.NameMonad import Util.SetLike import qualified Info.Info as Info import qualified Stats data ArityType = AFun Bool ArityType | ABottom | ATop deriving(Eq,Ord,Typeable) instance Show ArityType where showsPrec _ ATop = ("ArT" ++) showsPrec _ ABottom = ("ArB" ++) showsPrec _ (AFun False r) = ('\\':) . shows r showsPrec _ (AFun True r) = ("\\o" ++) . shows r arity at = f at 0 where f (AFun _ a) n = f a $! (1 + n) f x n | n `seq` x `seq` True = (x,n) f _ _ = error "Eta.arity: bad." getArityInfo tvr | Just at <- Info.lookup (tvrInfo tvr) = arity at | otherwise = (ATop,0) isOneShot x = getProperty prop_ONESHOT x arityType :: E -> ArityType arityType e = f e where f EError {} = ABottom f (ELam x e) = AFun (isOneShot x) (f e) f (EAp a b) = case f a of AFun _ xs | isCheap b -> xs _ -> ATop f ec@ECase { eCaseScrutinee = scrut } = case foldr1 andArityType (map f $ caseBodies ec) of xs@(AFun True _) -> xs xs | isCheap scrut -> xs _ -> ATop f (ELetRec ds e) = case f e of xs@(AFun True _) -> xs xs | all isCheap (snds ds) -> xs _ -> ATop f (EVar tvr) | Just at <- Info.lookup (tvrInfo tvr) = at f _ = ATop andArityType ABottom at2 = at2 andArityType ATop at2 = ATop andArityType (AFun t1 at1) (AFun t2 at2) = AFun (t1 && t2) (andArityType at1 at2) andArityType at1 at2 = andArityType at2 at1 annotateArity e nfo = annotateArity' (arityType e) nfo annotateArity' at nfo = Info.insert (Arity n (b == ABottom)) $ Info.insert at nfo where (b,n) = arity at -- delety any arity information deleteArity nfo = Info.delete (undefined :: Arity) $ Info.delete (undefined :: Arity) nfo expandPis :: DataTable -> E -> E expandPis dataTable e = f (followAliases dataTable e) where f (EPi v r) = EPi v (f (followAliases dataTable r)) f e = e {- fromPi' :: DataTable -> E -> (E,[TVr]) fromPi' dataTable e = f [] (followAliases dataTable e) where f as (EPi v e) = f (v:as) (followAliases dataTable e) f as e = (e,reverse as) -} -- this annotates, but only expands top-level definitions etaExpandProgram :: Stats.MonadStats m => Program -> m Program --etaExpandProgram prog = runNameMT (programMapDs f (etaAnnotateProgram prog)) where etaExpandProgram prog = runNameMT (programMapDs f prog) where f (t,e) = do etaExpandDef' (progDataTable prog) 0 t e -- this annotates a program with its arity information, iterating until a fixpoint is reached. etaAnnotateProgram :: Program -> Program etaAnnotateProgram prog = runIdentity $ programMapRecGroups mempty pass iletann pass f prog where pass _ = return iletann e nfo = return $ annotateArity e nfo letann e nfo = case Info.lookup nfo of Nothing -> put True >> return (annotateArity e nfo) Just at -> do let at' = arityType e when (at /= at') (put True) return $ annotateArity' at' nfo f (rg,ts) = do let (ts',fs) = runState (annotateCombs mempty pass letann pass ts) False if fs then f (rg,ts') else return ts' -- | eta reduce as much as possible etaReduce :: E -> E etaReduce e = f e where f (ELam t (EAp x (EVar t'))) | t == t' && (tvrIdent t `notMember` (freeVars x :: IdSet)) = f x f e = e -- | only reduce if all lambdas can be discarded. otherwise leave them in place {- etaReduce' :: E -> (E,Int) etaReduce' e = case f e 0 of (ELam {},_) -> (e,0) x -> x where f (ELam t (EAp x (EVar t'))) n | n `seq` True, t == t' && (tvrIdent t `notMember` (freeVars x :: IdSet)) = f x (n + 1) f e n = (e,n) -} etaExpandDef' dataTable n t e = etaExpandDef dataTable n t e >>= \x -> case x of Nothing -> return (tvrInfo_u (annotateArity e) t,e) Just x -> return x --collectIds :: E -> IdSet --collectIds e = execWriter $ annotate mempty (\id nfo -> tell (singleton id) >> return nfo) (\_ -> return) (\_ -> return) e -- | eta expand a definition etaExpandDef :: (NameMonad Id m,Stats.MonadStats m) => DataTable -> Int -- ^ eta expand at least this far, independent of calculated amount -> TVr -> E -> m (Maybe (TVr,E)) etaExpandDef _ _ _ e | isAtomic e = return Nothing -- will be inlined etaExpandDef dataTable min t e = ans where --fvs = foldr insert (freeVars (b,map getType rs,(tvrType t,e))) (map tvrIdent rs) `mappend` collectIds e --(b,rs) = fromLam e at = arityType e zeroName = case fromAp e of (EVar v,_) -> "use.{" ++ tvrShowName v _ -> "random" --nameSupply = [ n | n <- [2,4 :: Int ..], n `notMember` fvs ] nameSupply = undefined ans = do -- note that we can't use the type in the tvr, because it will not have the right free typevars. (ne,flag) <- f min at e (expandPis dataTable $ infertype dataTable e) nameSupply if flag then return (Just (tvrInfo_u (annotateArity' at) t,ne)) else return Nothing f min (AFun _ a) (ELam tvr e) (EPi tvr' rt) _ns = do (ne,flag) <- f (min - 1) a e (subst tvr' (EVar tvr) rt) _ns return (ELam tvr ne,flag) f min (AFun _ a) e (EPi tt rt) _nns = do if tvrIdent t == emptyId then Stats.mtick ("EtaExpand." ++ zeroName) else Stats.mtick ("EtaExpand.def.{" ++ tvrShowName t) n <- newName let nv = tt { tvrIdent = n } eb = EAp e (EVar nv) (ne,_) <- f (min - 1) a eb (subst tt (EVar nv) rt) _nns return (ELam nv ne,True) f min a e (EPi tt rt) _nns | min > 0 = do if tvrIdent t == emptyId then Stats.mtick ("EtaExpand.min." ++ zeroName) else Stats.mtick ("EtaExpand.min.def.{" ++ tvrShowName t) n <- newName let nv = tt { tvrIdent = n } eb = EAp e (EVar nv) (ne,_) <- f (min - 1) a eb (subst tt (EVar nv) rt) _nns return (ELam nv ne,True) f _ _ e _ _ = do return (e,False) -- | eta expand a use of a value etaExpandAp :: (NameMonad Id m,Stats.MonadStats m) => DataTable -> TVr -> [E] -> m (Maybe E) etaExpandAp dataTable tvr xs = do r <- etaExpandDef dataTable 0 tvr { tvrIdent = emptyId} (foldl EAp (EVar tvr) xs) return (fmap snd r) {- etaExpandAp _ _ [] = return Nothing -- so simple renames don't get eta-expanded etaExpandAp dataTable t as | Just (Arity n err) <- Info.lookup (tvrInfo t) = case () of () | n > length as -> do let e = foldl EAp (EVar t) as let (_,ts) = fromPi' dataTable (infertype dataTable e) ets = (take (n - length as) ts) mticks (length ets) ("EtaExpand.use.{" ++ tvrShowName t) let tvrs = f mempty [ (tvrIdent t,t { tvrIdent = n }) | n <- [2,4 :: Int ..], not $ n `Set.member` freeVars (e,ets) | t <- ets ] f map ((n,t):rs) = t { tvrType = substMap map (tvrType t)} : f (Map.insert n (EVar t) map) rs f _ [] = [] return (Just $ foldr ELam (foldl EAp e (map EVar tvrs)) tvrs) | err && length as > n -> do let ot = infertype dataTable (foldl EAp (EVar t) as) mticks (length as - n) ("EtaExpand.bottoming.{" ++ tvrShowName t) return $ Just (prim_unsafeCoerce ot (foldl EAp (EVar t) (take n as))) -- we can drop any extra arguments applied to something that bottoms out. | otherwise -> return Nothing etaExpandAp _ t as = return Nothing -}
m-alvarez/jhc
src/E/Eta.hs
Haskell
mit
7,993
module LiftOneLevel.LetIn1 where --A definition can be lifted from a where or let into the surronding binding group. --Lifting a definition widens the scope of the definition. --In this example, lift 'sq' in 'sumSquares' --This example aims to test lifting a definition from a let clause to a where clause, --and the elimination of the keywords 'let' and 'in' sumSquares x y = let sq 0=0 sq z=z^pow in sq x + sq y where pow=2 anotherFun 0 y = sq y where sq x = x^2
RefactoringTools/HaRe
test/testdata/LiftOneLevel/LetIn1.hs
Haskell
bsd-3-clause
536
{-# LANGUAGE PatternGuards #-} module Idris.Elab.Transform where import Idris.AbsSyntax import Idris.ASTUtils import Idris.DSL import Idris.Error import Idris.Delaborate import Idris.Imports import Idris.Coverage import Idris.DataOpts import Idris.Providers import Idris.Primitives import Idris.Inliner import Idris.PartialEval import Idris.DeepSeq import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting) import IRTS.Lang import Idris.Elab.Utils import Idris.Elab.Term import Idris.Core.TT import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.Typecheck import Idris.Core.CaseTree import Idris.Docstrings import Prelude hiding (id, (.)) import Control.Category import Control.Applicative hiding (Const) import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import Data.List import Data.Maybe import Debug.Trace import qualified Data.Map as Map import qualified Data.Set as S import qualified Data.Text as T import Data.Char(isLetter, toLower) import Data.List.Split (splitOn) import Util.Pretty(pretty, text) elabTransform :: ElabInfo -> FC -> Bool -> PTerm -> PTerm -> Idris (Term, Term) elabTransform info fc safe lhs_in@(PApp _ (PRef _ _ tf) _) rhs_in = do ctxt <- getContext i <- getIState let lhs = addImplPat i lhs_in logLvl 5 ("Transform LHS input: " ++ showTmImpls lhs) (ElabResult lhs' dlhs [] ctxt' newDecls highlights, _) <- tclift $ elaborate ctxt (idris_datatypes i) (sMN 0 "transLHS") infP initEState (erun fc (buildTC i info ETransLHS [] (sUN "transform") (infTerm lhs))) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights let lhs_tm = orderPats (getInferTerm lhs') let lhs_ty = getInferType lhs' let newargs = pvars i lhs_tm (clhs_tm_in, clhs_ty) <- recheckC_borrowing False False [] fc id [] lhs_tm let clhs_tm = renamepats pnames clhs_tm_in logLvl 3 ("Transform LHS " ++ show clhs_tm) logLvl 3 ("Transform type " ++ show clhs_ty) let rhs = addImplBound i (map fst newargs) rhs_in logLvl 5 ("Transform RHS input: " ++ showTmImpls rhs) ((rhs', defer, ctxt', newDecls), _) <- tclift $ elaborate ctxt (idris_datatypes i) (sMN 0 "transRHS") clhs_ty initEState (do pbinds i lhs_tm setNextName (ElabResult _ _ _ ctxt' newDecls highlights) <- erun fc (build i info ERHS [] (sUN "transform") rhs) erun fc $ psolve lhs_tm tt <- get_term let (rhs', defer) = runState (collectDeferred Nothing [] ctxt tt) [] return (rhs', defer, ctxt', newDecls)) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights (crhs_tm_in, crhs_ty) <- recheckC_borrowing False False [] fc id [] rhs' let crhs_tm = renamepats pnames crhs_tm_in logLvl 3 ("Transform RHS " ++ show crhs_tm) -- Types must always convert case converts ctxt [] clhs_ty crhs_ty of OK _ -> return () Error e -> ierror (At fc (CantUnify False (clhs_tm, Nothing) (crhs_tm, Nothing) e [] 0)) -- In safe mode, values must convert (Thinks: This is probably not -- useful as is, perhaps it should require a proof of equality instead) when safe $ case converts ctxt [] clhs_tm crhs_tm of OK _ -> return () Error e -> ierror (At fc (CantUnify False (clhs_tm, Nothing) (crhs_tm, Nothing) e [] 0)) case unApply (depat clhs_tm) of (P _ tfname _, _) -> do addTrans tfname (clhs_tm, crhs_tm) addIBC (IBCTrans tf (clhs_tm, crhs_tm)) _ -> ierror (At fc (Msg "Invalid transformation rule (must be function application)")) return (clhs_tm, crhs_tm) where depat (Bind n (PVar t) sc) = depat (instantiate (P Bound n t) sc) depat x = x renamepats (n' : ns) (Bind n (PVar t) sc) = Bind n' (PVar t) (renamepats ns sc) -- all Vs renamepats _ sc = sc -- names for transformation variables. Need to ensure these don't clash -- with any other names when applying rules, so rename here. pnames = map (\i -> sMN i ("tvar" ++ show i)) [0..] elabTransform info fc safe lhs_in rhs_in = ierror (At fc (Msg "Invalid transformation rule (must be function application)"))
osa1/Idris-dev
src/Idris/Elab/Transform.hs
Haskell
bsd-3-clause
4,686
{- | Module : Orville.PostgreSQL.Internal.EntityOperations Copyright : Flipstone Technology Partners 2021 License : MIT -} module Orville.PostgreSQL.Internal.EntityOperations ( insertEntity, insertAndReturnEntity, insertEntities, insertAndReturnEntities, updateEntity, updateAndReturnEntity, deleteEntity, deleteAndReturnEntity, findEntitiesBy, findFirstEntityBy, findEntity, ) where import Control.Exception (Exception, throwIO) import Control.Monad.IO.Class (MonadIO (liftIO)) import Data.List.NonEmpty (NonEmpty ((:|))) import Data.Maybe (listToMaybe) import qualified Orville.PostgreSQL.Internal.Execute as Execute import qualified Orville.PostgreSQL.Internal.Insert as Insert import qualified Orville.PostgreSQL.Internal.MonadOrville as MonadOrville import qualified Orville.PostgreSQL.Internal.PrimaryKey as PrimaryKey import qualified Orville.PostgreSQL.Internal.ReturningOption as ReturningOption import qualified Orville.PostgreSQL.Internal.Select as Select import qualified Orville.PostgreSQL.Internal.SelectOptions as SelectOptions import qualified Orville.PostgreSQL.Internal.TableDefinition as TableDef import qualified Orville.PostgreSQL.Internal.Update as Update {- | Inserts a entity into the specified table. -} insertEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> writeEntity -> m () insertEntity entityTable entity = insertEntities entityTable (entity :| []) {- | Inserts a entity into the specified table, returning the data inserted into the database. You can use this function to obtain any column values filled in by the database, such as auto-incrementing ids. -} insertAndReturnEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> writeEntity -> m readEntity insertAndReturnEntity entityTable entity = do returnedEntities <- insertAndReturnEntities entityTable (entity :| []) case returnedEntities of [returnedEntity] -> pure returnedEntity _ -> liftIO . throwIO . RowCountExpectationError $ "Expected exactly one row to be returned in RETURNING clause, but got " <> show (length returnedEntities) {- | Inserts a non-empty list of entities into the specified table -} insertEntities :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> NonEmpty writeEntity -> m () insertEntities tableDef = Insert.executeInsert . Insert.insertToTable tableDef {- | Inserts a non-empty list of entities into the specified table, returning the data that was inserted into the database. You can use this function to obtain any column values filled in by the database, such as auto-incrementing ids. -} insertAndReturnEntities :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> NonEmpty writeEntity -> m [readEntity] insertAndReturnEntities tableDef = Insert.executeInsertReturnEntities . Insert.insertToTableReturning tableDef {- | Updates the row with the given key in with the data given by 'writeEntity' -} updateEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition (TableDef.HasKey key) writeEntity readEntity -> key -> writeEntity -> m () updateEntity tableDef key = Update.executeUpdate . Update.updateToTable tableDef key {- | Updates the row with the given key in with the data given by 'writeEntity', returning updated row from the database. If no row matches the given key, 'Nothing' will be returned. You can use this function to obtain any column values computer by the database during update, including columns with triggers attached to them. -} updateAndReturnEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition (TableDef.HasKey key) writeEntity readEntity -> key -> writeEntity -> m (Maybe readEntity) updateAndReturnEntity tableDef key = Update.executeUpdateReturnEntity . Update.updateToTableReturning tableDef key {- | Deletes the row with the given key -} deleteEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition (TableDef.HasKey key) writeEntity readEntity -> key -> m () deleteEntity tableDef key = Execute.executeVoid $ TableDef.mkDeleteExpr ReturningOption.WithoutReturning tableDef key {- | Deletes the row with the given key, returning the row that was deleted. If no row matches the given key, 'Nothing' is returned. -} deleteAndReturnEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition (TableDef.HasKey key) writeEntity readEntity -> key -> m (Maybe readEntity) deleteAndReturnEntity tableDef key = fmap listToMaybe $ Execute.executeAndDecode (TableDef.mkDeleteExpr ReturningOption.WithReturning tableDef key) (TableDef.tableMarshaller tableDef) {- | Finds all the entities in the given table according to the specified 'SelectOptions.SelectOptions', which may include where conditions to match, ordering specifications, etc. -} findEntitiesBy :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> SelectOptions.SelectOptions -> m [readEntity] findEntitiesBy entityTable selectOptions = Select.executeSelect $ Select.selectTable entityTable selectOptions {- | Like 'findEntitiesBy, but adds a 'LIMIT 1' to the query and then returns the first item from the list. Usually when you use this you will want to provide an order by clause in the 'SelectOptions.SelectOptions' because the database will not guarantee ordering. -} findFirstEntityBy :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> SelectOptions.SelectOptions -> m (Maybe readEntity) findFirstEntityBy entityTable selectOptions = listToMaybe <$> findEntitiesBy entityTable (SelectOptions.limit 1 <> selectOptions) {- | Finds a single entity by the table's primary key value. -} findEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition (TableDef.HasKey key) writeEntity readEntity -> key -> m (Maybe readEntity) findEntity entityTable key = let primaryKeyCondition = PrimaryKey.primaryKeyEquals (TableDef.tablePrimaryKey entityTable) key in findFirstEntityBy entityTable (SelectOptions.where_ primaryKeyCondition) {- | INTERNAL: This should really never get thrown in the real world. It would be thrown if the returning clause from an insert statement for a single record returned 0 records or more than 1 record. -} newtype RowCountExpectationError = RowCountExpectationError String deriving (Show) instance Exception RowCountExpectationError
flipstone/orville
orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/EntityOperations.hs
Haskell
mit
6,679
import qualified Data.Array.Unboxed as A import Data.Char ones :: A.Array Int String ones = A.listArray (0,9) ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] tens :: A.Array Int String tens = A.listArray (1,9) ["ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] teens :: A.Array Int String teens = A.listArray (11,19) ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] oneThousand :: String oneThousand = "one thousand" writeOut :: Int -> String writeOut n | length showN == 1 = ones A.! n | length showN == 2 = writeOutDouble showN | length showN == 3 = writeOutTriple showN | n == 1000 = oneThousand where showN = show n writeOutDouble num@(a:b:[]) | a == '0' = ones A.! (read $ return b) | b == '0' = tens A.! (read $ return a) | a == '1' = teens A.! read num | otherwise = tens A.! (read $ return a) ++ "-" ++ ones A.! (read $ return b) writeOutTriple (a:b:c:[]) = ones A.! (read $ return a) ++ " hundred" ++ if b /= '0' || c /= '0' then " and " ++ writeOutDouble (b:c:[]) else "" solve m n = sum $ map (length . filter isAlpha . writeOut) [m..n]
jwtouron/haskell-play
ProjectEuler/Problem17.hs
Haskell
mit
1,455
module MyHttp (RequestType (..), Request(..), Response(..), Context(..), ServerPart, choose) where --import Control.Monad --import Control.Applicative data RequestType = Get | Post deriving (Eq) data Request = Request { route :: String , reqtype :: RequestType } data Response = Response { content :: String , statusCode :: Int } instance Show Response where show (Response cntnt stts) = "Status Code: " ++ show stts ++ "\n" ++ "Content: " ++ cntnt data Context = Context { request :: Request , response :: Response } type ServerPart = Context -> Maybe Context choose :: [ServerPart] -> ServerPart choose [] _ = Nothing choose (x:xs) context = case x context of Just c -> Just c Nothing -> choose xs context {-- instance MonadPlus (ServerPart m) where mzero = Nothing mplus = choose --}
nicolocodev/learnhappstack
4_Filters/MyHttp.hs
Haskell
mit
845
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {- | Module : Database.Couch.Explicit.Database Description : Database-oriented requests to CouchDB, with explicit parameters Copyright : Copyright (c) 2015, Michael Alan Dorman License : MIT Maintainer : mdorman@jaunder.io Stability : experimental Portability : POSIX This module is intended to be @import qualified@. /No attempt/ has been made to keep names of types or functions from clashing with obvious or otherwise commonly-used names, or even other modules within this package. The functions here are derived from (and presented in the same order as) the <http://docs.couchdb.org/en/1.6.1/api/database/index.html Database API documentation>. For each function, we attempt to link back to the original documentation, as well as make a notation as to how complete and correct we feel our implementation is. Each function takes a 'Database.Couch.Types.Context'---which, among other things, holds the name of the database---as its final parameter, and returns a 'Database.Couch.Types.Result'. -} module Database.Couch.Explicit.Database where import Control.Monad (return, when) import Control.Monad.IO.Class (MonadIO) import Control.Monad.Trans.Except (throwE) import Data.Aeson (FromJSON, ToJSON, Value (Object), object, toJSON) import Data.Bool (Bool (True)) import Data.Function (($), (.)) import Data.Functor (fmap) import Data.HashMap.Strict (fromList) import Data.Int (Int) import Data.Maybe (Maybe (Just), catMaybes, fromJust, isJust) import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import Database.Couch.Internal (standardRequest, structureRequest) import Database.Couch.RequestBuilder (RequestBuilder, addPath, selectDb, selectDoc, setHeaders, setJsonBody, setMethod, setQueryParam) import Database.Couch.ResponseParser (responseStatus, toOutputType) import Database.Couch.Types (Context, DbAllDocs, DbBulkDocs, DbChanges, DocId, DocRevMap, Error (NotFound, Unknown), Result, ToQueryParameters, bdAllOrNothing, bdFullCommit, bdNewEdits, cLastEvent, toQueryParameters) import Network.HTTP.Types (statusCode) {- | <http://docs.couchdb.org/en/1.6.1/api/database/common.html#head--db Check that the requested database exists> The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.exists ctx >>= asBool Status: __Complete__ -} exists :: (FromJSON a, MonadIO m) => Context -> m (Result a) exists = structureRequest request parse where request = do selectDb setMethod "HEAD" parse = do -- Check status codes by hand because we don't want 404 to be an error, just False s <- responseStatus case statusCode s of 200 -> toOutputType $ object [("ok", toJSON True)] 404 -> throwE NotFound _ -> throwE Unknown {- | <http://docs.couchdb.org/en/1.6.1/api/database/common.html#get--db Get most basic meta-information> The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.meta ctx Status: __Complete__ -} meta :: (FromJSON a, MonadIO m) => Context -> m (Result a) meta = standardRequest request where request = selectDb {- | <http://docs.couchdb.org/en/1.6.1/api/database/common.html#put--db Create a database> The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.meta ctx Status: __Complete__ -} create :: (FromJSON a, MonadIO m) => Context -> m (Result a) create = standardRequest request where request = do selectDb setMethod "PUT" {- | <http://docs.couchdb.org/en/1.6.1/api/database/common.html#delete--db Delete a database> The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.delete ctx >>= asBool Status: __Complete__ -} delete :: (FromJSON a, MonadIO m) => Context -> m (Result a) delete = standardRequest request where request = do selectDb setMethod "DELETE" {- | <http://docs.couchdb.org/en/1.6.1/api/database/common.html#post--db Create a new document in a database> The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.createDoc True someObject ctx >>= asBool Status: __Complete__ -} createDoc :: (FromJSON a, MonadIO m, ToJSON b) => Bool -- ^ Whether to create the document in batch mode -> b -- ^ The document to create -> Context -> m (Result a) createDoc batch doc = standardRequest request where request = do selectDb setMethod "POST" when batch (setQueryParam [("batch", Just "ok")]) setJsonBody doc {- | <http://docs.couchdb.org/en/1.6.1/api/database/bulk-api.html#get--db-_all_docs Get a list of all database documents> The return value is a list of objects whose fields often vary, so it is easily decoded as a 'Data.List.List' of 'Data.Aeson.Value': >>> value :: Result [Value] <- Database.allDocs dbAllDocs ctx Status: __Complete__ -} allDocs :: (FromJSON a, MonadIO m) => DbAllDocs -- ^ Parameters governing retrieval ('Database.Couch.Types.dbAllDocs' is an empty default) -> Context -> m (Result a) allDocs = standardRequest . allDocsBase {- | <http://docs.couchdb.org/en/1.6.1/api/database/bulk-api.html#post--db-_all_docs Get a list of some database documents> The return value is a list of objects whose fields often vary, so it is easily decoded as a 'Data.List.List' of 'Data.Aeson.Value': >>> value :: Result [Value] <- Database.someDocs ["a", "b", "c"] ctx Status: __Complete__ -} someDocs :: (FromJSON a, MonadIO m) => DbAllDocs -- ^ Parameters governing retrieval ('Database.Couch.Types.dbAllDocs' is an empty default) -> [DocId] -- ^ List of ids documents to retrieve -> Context -> m (Result a) someDocs param ids = standardRequest request where request = do setMethod "POST" allDocsBase param let parameters = Object (fromList [("keys", toJSON ids)]) setJsonBody parameters {- | <http://docs.couchdb.org/en/1.6.1/api/database/bulk-api.html#post--db-_bulk_docs Create or update a list of documents> The return value is a list of objects whose fields often vary, so it is easily decoded as a 'Data.List.List' of 'Data.Aeson.Value': >>> value :: Result [Value] <- Database.bulkDocs dbBulkDocs ["a", "b", "c"] ctx Status: __Complete__ -} bulkDocs :: (FromJSON a, MonadIO m, ToJSON a) => DbBulkDocs -- ^ Parameters coverning retrieval ('Database.Couch.Types.dbBulkDocs' is an empty default) -> [a] -- ^ List of documents to add or update -> Context -> m (Result a) bulkDocs param docs = standardRequest request where request = do setMethod "POST" -- TODO: We need a way to set a header when we have a value for it [refactor] when (isJust $ bdFullCommit param) (setHeaders [("X-Couch-Full-Commit", if fromJust $ bdFullCommit param then "true" else "false")]) selectDb addPath "_bulk_docs" -- TODO: We need a way to construct a json body from parameters [refactor] let parameters = Object ((fromList . catMaybes) [ Just ("docs", toJSON docs) , boolToParam "all_or_nothing" bdAllOrNothing , boolToParam "new_edits" bdNewEdits ]) setJsonBody parameters boolToParam k s = do v <- s param return (k, if v then "true" else "false") {- | <http://docs.couchdb.org/en/1.6.1/api/database/changes.html#get--db-_changes Get a list of all document modifications> This call does not stream out results; so while it allows you to specify parameters for streaming, it's a dirty, dirty lie. The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.changes ctx Status: __Limited__ -} changes :: (FromJSON a, MonadIO m) => DbChanges -- ^ Arguments governing changes contents ('Database.Couch.Types.dbChanges' is an empty default) -> Context -> m (Result a) changes param = standardRequest request where request = do -- TODO: We need a way to set a header when we have a value for it [refactor] when (isJust $ cLastEvent param) (setHeaders [("Last-Event-Id", encodeUtf8 . fromJust $ cLastEvent param)]) selectDb addPath "_changes" {- | <http://docs.couchdb.org/en/1.6.1/api/database/compact.html#post--db-_compact Compact a database> The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.compact ctx >>= asBool Status: __Complete__ -} compact :: (FromJSON a, MonadIO m) => Context -> m (Result a) compact = standardRequest compactBase {- | <http://docs.couchdb.org/en/1.6.1/api/database/compact.html#post--db-_compact-ddoc Compact the views attached to a particular design document> The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.compactDesignDoc "ddoc" ctx >>= asBool Status: __Complete__ -} compactDesignDoc :: (FromJSON a, MonadIO m) => DocId -- ^ The 'DocId' of the design document to compact -> Context -> m (Result a) compactDesignDoc doc = standardRequest request where request = do compactBase selectDoc doc {- | <http://docs.couchdb.org/en/1.6.1/api/database/compact.html#post--db-_ensure_full_commit Ensure that all changes to the database have made it to disk> The return value is an object that can hold an "instance_start_time" key, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.sync ctx >>= asBool Status: __Complete__ -} sync :: (FromJSON a, MonadIO m) => Context -> m (Result a) sync = standardRequest request where request = do setMethod "POST" selectDb addPath "_ensure_full_commit" {- | <http://docs.couchdb.org/en/1.6.1/api/database/compact.html#post--db-_view_cleanup Cleanup any stray view definitions> The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.cleanup ctx >>= asBool Status: __Complete__ -} cleanup :: (FromJSON a, MonadIO m) => Context -> m (Result a) cleanup = standardRequest request where request = do setMethod "POST" selectDb addPath "_view_cleanup" {- | <http://docs.couchdb.org/en/1.6.1/api/database/security.html#get--db-_security Get security information for database> The return value is an object that has with a standard set of fields ("admin" and "members" keys, which each contain "users" and "roles"), the system does not prevent you from adding (and even using in validation functions) additional fields, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.getSecurity ctx Status: __Complete__ -} getSecurity :: (FromJSON a, MonadIO m) => Context -> m (Result a) getSecurity = standardRequest securityBase {- | <http://docs.couchdb.org/en/1.6.1/api/database/security.html#post--db-_security Set security information for database> The input value is an object that has with a standard set of fields ("admin" and "members" keys, which each contain "users" and "roles"), but the system does not prevent you from adding (and even using in validation functions) additional fields, so we don't specify a specific type, and you can roll your own: The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Value <- Database.setSecurity (object [("users", object [("harry")])]) ctx >>= asBool Status: __Complete__ -} setSecurity :: (FromJSON b, MonadIO m, ToJSON a) => a -- ^ The security document content -> Context -> m (Result b) setSecurity doc = standardRequest request where request = do setMethod "PUT" securityBase setJsonBody doc {- | <http://docs.couchdb.org/en/1.6.1/api/database/temp-views.html#post--db-_temp_view Create a temporary view> The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.tempView "function (doc) { emit (1); }" (Just "_count") Nothing ctx Status: __Complete__ -} tempView :: (FromJSON a, MonadIO m) => Text -- ^ The text of your map function -> Maybe Text -- ^ The text of your optional reduce function -> Context -> m (Result a) tempView map reduce = standardRequest request where request = do setMethod "POST" selectDb -- TODO: We need a way to construct a json body from parameters [refactor] let parameters = Object (fromList $ catMaybes [ Just ("map", toJSON map) , fmap (("reduce",) . toJSON) reduce ]) addPath "_temp_view" setJsonBody parameters {- | <http://docs.couchdb.org/en/1.6.1/api/database/misc.html#post--db-_purge Purge document revisions from the database> The return value is an object with two fields "purge_seq" and "purged", which contains an object with no fixed keys, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.purge $ DocRevMap [(DocId "junebug", [DocRev "1-1"])] Nothing ctx However, the content of "purged" is effectively a 'Database.Couch.Types.DocRevMap', so the output can be parsed into an (Int, DocRevMap) pair using: >>> (,) <$> (getKey "purge_seq" >>= toOutputType) <*> (getKey "purged" >>= toOutputType) Status: __Complete__ -} purge :: (FromJSON a, MonadIO m) => DocRevMap -- ^ A 'Database.Couch.Types.DocRevMap' of documents and versions to purge -> Context -> m (Result a) purge docRevs = standardRequest request where request = do docRevBase docRevs addPath "_purge" {- | <http://docs.couchdb.org/en/1.6.1/api/database/misc.html#post--db-_missing_revs Find document revisions not present in the database> The return value is an object with one field "missed_revs", which contains an object with no fixed keys, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.missingRevs $ DocRevMap [(DocId "junebug", [DocRev "1-1"])] ctx However, the content of "missed_revs" is effectively a 'Database.Couch.Types.DocRevMap', so it can be parsed into a 'Database.Couch.Types.DocRevMap' using: >>> getKey "missed_revs" >>= toOutputType Status: __Complete__ -} missingRevs :: (FromJSON a, MonadIO m) => DocRevMap -- ^ A 'Database.Couch.Types.DocRevMap' of documents and versions available -> Context -> m (Result a) missingRevs docRevs = standardRequest request where request = do docRevBase docRevs addPath "_missing_revs" {- | <http://docs.couchdb.org/en/1.6.1/api/database/misc.html#post--db-_revs_diff Find document revisions not present in the database> The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.revsDiff $ DocRevMap [(DocId "junebug", [DocRev "1-1"])] ctx Status: __Complete__ -} revsDiff :: (FromJSON a, MonadIO m) => DocRevMap -- ^ A 'Database.Couch.Types.DocRevMap' of documents and versions available -> Context -> m (Result a) revsDiff docRevs = standardRequest request where request = do docRevBase docRevs addPath "_revs_diff" {- | <http://docs.couchdb.org/en/1.6.1/api/database/misc.html#get--db-_revs_limit Get the revision limit setting> The return value is a JSON numeric value that can easily be decoded to an 'Int': >>> value :: Result Integer <- Database.getRevsLimit ctx Status: __Complete__ -} getRevsLimit :: (FromJSON a, MonadIO m) => Context -> m (Result a) getRevsLimit = standardRequest revsLimitBase {- | <http://docs.couchdb.org/en/1.6.1/api/database/misc.html#put--db-_revs_limit Set the revision limit> Status: __Complete__ -} setRevsLimit :: (FromJSON a, MonadIO m) => Int -- ^ The value at which to set the limit -> Context -> m (Result a) setRevsLimit limit = standardRequest request where request = do setMethod "PUT" revsLimitBase setJsonBody limit -- * Internal combinators -- | Base bits for all _all_docs requests allDocsBase :: ToQueryParameters a => a -> RequestBuilder () allDocsBase param = do selectDb addPath "_all_docs" setQueryParam $ toQueryParameters param -- | Base bits for all our _compact requests compactBase :: RequestBuilder () compactBase = do setMethod "POST" selectDb addPath "_compact" -- | Base bits for our revision examination functions docRevBase :: ToJSON a => a -> RequestBuilder () docRevBase docRevs = do setMethod "POST" selectDb let parameters = toJSON docRevs setJsonBody parameters -- | Base bits for our revisions limit functions revsLimitBase :: RequestBuilder () revsLimitBase = do selectDb addPath "_revs_limit" -- | Base bits for our security functions securityBase :: RequestBuilder () securityBase = do selectDb addPath "_security"
mdorman/couch-simple
src/lib/Database/Couch/Explicit/Database.hs
Haskell
mit
19,367
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, ScopedTypeVariables #-} module Main (main) where import ClassyPrelude import Network.HTTP.Types (status400) import Network.Wai (Application, responseLBS) import Network.Wai.Handler.Warp (run) import Network.Wai.Handler.WebSockets (websocketsOr) import qualified Control.Concurrent.Chan.Unagi as Unagi import qualified Data.Aeson as Aeson import qualified Network.WebSockets as Ws data Msg = Echo | Broadcast LByteString parseMsg :: LByteString -> Maybe Msg parseMsg msg = do Aeson.Object obj <- Aeson.decode msg Aeson.String typ <- lookup "type" obj case typ of "echo" -> Just Echo "broadcast" -> let res = Aeson.encode (insertMap "type" "broadcastResult" obj) in Just (Broadcast res) _ -> Nothing -- Don't flood stdout after the benchmark silentLoop :: IO () -> IO () silentLoop = handleAny (const $ pure ()) . forever wsApp :: Unagi.InChan LByteString -> Ws.ServerApp wsApp writeEnd pconn = do conn <- Ws.acceptRequest pconn readEnd <- Unagi.dupChan writeEnd void $ fork $ silentLoop (Unagi.readChan readEnd >>= Ws.sendTextData conn) silentLoop $ do msg <- Ws.receiveData conn case parseMsg msg of Nothing -> Ws.sendClose conn ("Invalid message" :: LByteString) Just Echo -> Ws.sendTextData conn msg Just (Broadcast res) -> do Unagi.writeChan writeEnd msg Ws.sendTextData conn res backupApp :: Application backupApp _ resp = resp $ responseLBS status400 [] "Not a WebSocket request" main :: IO () main = do (writeEnd, _) <- Unagi.newChan run 3000 $ websocketsOr Ws.defaultConnectionOptions (wsApp writeEnd) backupApp
palkan/websocket-shootout
haskell/warp/Main.hs
Haskell
mit
1,672
{-# LANGUAGE DeriveLift #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} module Luck.Template ( mkGenQ , TProxy (..) , tProxy1 , tProxy2 , tProxy3 , Flags (..) , defFlags ) where import Common.SrcLoc (SrcLoc(..)) import Common.Types import Outer.AST import Luck.Main import Language.Haskell.TH.Syntax (Lift(..), Q, runIO) import qualified Language.Haskell.TH as TH import System.Random import Data.Data (Data) import Data.Functor.Identity import qualified Test.QuickCheck.Gen as QC import Paths_luck import qualified Data.ByteString as BS -- * Luck to Haskell -- | Import a Luck generator as a Haskell value generator at compile time. -- -- > {-# LANGUAGE TemplateHaskell #-} -- > {- - @MyType@ should be an instance of @Data@; -- > - the definitions of types involved in @MyType@ -- > should match those in the Luck program; -- > - The target predicate (i.e., the last function) should have type -- > @MyType -> Bool@. -- > -} -- > luckyGen :: QC.Gen (Maybe MyType) -- > luckyGen = $(mkGenQ defFlags{_fileName="path/to/MyLuckPrg.luck"}) tProxy1 -- -- Depending on the arity of the predicate, use 'tProxy1', 'tProxy2', 'tProxy3', -- or the 'TProxy' constructors. (The type of the 'TProxy' argument -- contains the result type of the generator.) -- -- For example, for a 4-ary predicate of type -- @A -> B -> C -> D -> Bool@, -- we can create the following generator: -- -- > luckGen :: QC.Gen (A, (B, (C, (D, ())))) -- > luckGen = $(mkGenQ defFlags{_fileName="path/to/MyLuckPrg.luck"}) -- > (TProxyS . TProxyS . TProxyS . TProxyS $ TProxy0) mkGenQ :: Flags -> Q TH.Exp mkGenQ flags = do ast <- runIO $ getOAST flags [| \proxy -> stdGenToGen (runIdentity (parse $(lift flags) $(lift ast) (Cont proxy))) |] stdGenToGen :: (StdGen -> a) -> QC.Gen a stdGenToGen f = QC.MkGen $ \qcGen _ -> f' qcGen where f' = f . mkStdGen . fst . next tProxy1 :: Data a => TProxy a tProxy1 = TProxyF (\(a, ()) -> a) (TProxyS TProxy0) tProxy2 :: (Data a, Data b) => TProxy (a, b) tProxy2 = TProxyF (\(a, (b, ())) -> (a, b)) (TProxyS . TProxyS $ TProxy0) tProxy3 :: (Data a, Data b, Data c) => TProxy (a, b, c) tProxy3 = TProxyF (\(a, (b, (c, ()))) -> (a, b, c)) (TProxyS . TProxyS . TProxyS $ TProxy0) deriving instance Lift RunMode deriving instance Lift Flags deriving instance Lift ConDecl deriving instance Lift Decl deriving instance Lift Exp deriving instance Lift TyVarId' deriving instance Lift Pat deriving instance Lift Literal deriving instance Lift Alt deriving instance Lift Op1 deriving instance Lift Op2 deriving instance Lift SrcLoc deriving instance (Lift c, Lift v) => Lift (TcType c v)
QuickChick/Luck
luck/src/Luck/Template.hs
Haskell
mit
2,723
module Parse ( program , expr ) where import Control.Applicative hiding (many, (<|>)) import Data.Char import Text.ParserCombinators.Parsec import qualified PowAST as Ast -- We have many fun !! program :: Parser Ast.Program program = do funs <- many fun _ <- eof return funs fun :: Parser Ast.Fun fun = do sc <- lexeme scoping fn <- lexeme $ funName _ <- lexeme $ char '⊂' ps <- lexeme $ params _ <- lexeme $ char '⊃' bd <- lexeme compoundStatement return $ Ast.Fun fn sc ps bd scoping :: Parser Ast.Scoping scoping = (symbol "static" >> return Ast.StaticScoping) <|> (symbol "dynamic" >> return Ast.DynamicScoping) name :: Parser String name = do -- NOTE: Maybe allow name to start with numbers -- [a-zA-Z_][a-zA-Z0-9_]* first <- satisfy (orUnderscore isAlpha) rest <- many $ satisfy (orUnderscore isAlphaNum) return $ [first] ++ rest funName :: Parser Ast.FunName funName = name lexeme :: Parser a -> Parser a lexeme parser = parser <* spaces symbol :: String -> Parser String symbol = lexeme . string params :: Parser [Ast.Param] params = sepByCommas identifier arguments :: Parser Ast.Args arguments = sepByCommas expr sepByCommas :: Parser a -> Parser [a] sepByCommas = (flip sepBy) (symbol ",") identifier :: Parser Ast.Id identifier = lexeme $ do _ <- char '~' id <- name return id statement :: Parser Ast.Statement statement = try statement' <|> conditional <|> loop where statement' = do e <- expr _ <- symbol ":" return e parens :: Parser a -> Parser a parens p = symbol "(" *> p <* symbol ")" expr :: Parser Ast.Expr expr = giveback <|> write <|> conditional <|> loop <|> binOpChain where binOpChain = assignment assignment = chainr1 equal (symbol "←" >> return Ast.Assign) equal = chainl1 notEqual (symbol "=" >> return Ast.Equal) notEqual = chainl1 lessgreater (symbol "≠" >> return Ast.NotEqual) lessgreater = chainl1 strConcat binOp where binOp = (try $ (symbol ">=" <|> symbol "≥") >> return Ast.GreaterEq) <|> (try $ (symbol "<=" <|> symbol "≤") >> return Ast.LessEq) <|> (symbol "<" >> return Ast.Less) <|> (symbol ">" >> return Ast.Greater) strConcat = chainl1 plusminus binOp where binOp = symbol "↔" >> return Ast.StrConcat plusminus = chainl1 timesdivide binOp where binOp = (symbol "+" >> return Ast.Plus) <|> (symbol "-" >> return Ast.Minus) timesdivide = chainl1 parseRealThing binOp where binOp = (symbol "*" >> return Ast.Times) <|> (symbol "/" >> return Ast.Divide) parseRealThing = try arrayIndex <|> (parens expr) <|> arrayLit <|> numbers <|> trool <|> string <|> variable <|> call trool = (symbol "⊥" >> return (Ast.TroolLit Ast.No)) <|> (symbol "⊤" >> return (Ast.TroolLit Ast.Yes)) <|> (symbol "⟛" >> return (Ast.TroolLit Ast.CouldHappen)) -- TODO: Add escaping?! string = do char '|' s <- many $ noneOf "|" symbol "|" return $ Ast.StrLit s arrayIndex = do ns <- numbers e <- parens expr return $ Ast.ArrayIndex ns e arrayLit = do symbol "#" exprs <- sepByCommas expr return $ Ast.ArrayLit exprs write = do symbol "✎" e <- expr return $ Ast.Write e variable = do id <- identifier return $ Ast.Var id numbers = do ns <- lexeme $ many1 digit return $ Ast.IntLit (read ns) giveback = do _ <- symbol "giveback" <|> symbol "↜" expr' <- expr return $ Ast.GiveBack expr' call = do symbol "⊂" args <- arguments symbol "⊃" symbol "↝" funName <- lexeme name return $ Ast.Call args funName loop :: Parser Ast.Expr loop = do symbol "⟳" condition <- expr symbol "?" body <- compoundStatement return $ Ast.While condition body -- TODO: Make this less ugly! conditional :: Parser Ast.Expr conditional = try conditionalWithElse <|> conditionalWithoutElse where conditionalWithoutElse = do symbol "¿" condition <- expr symbol "?" thenBranch <- compoundStatement return $ Ast.If condition thenBranch [] conditionalWithElse = do symbol "¿" condition <- expr symbol "?" thenBranch <- compoundStatement symbol "!" elseBranch <- compoundStatement return $ Ast.If condition thenBranch elseBranch compoundStatement :: Parser [Ast.Statement] compoundStatement = do symbol "/" body <- many statement symbol "\\" return body orUnderscore :: (Char -> Bool) -> Char -> Bool orUnderscore f c = f c || c == '_'
rloewe/petulant-octo-wallhack
Parse.hs
Haskell
mit
4,931
module HelperSequences.A000037Spec (main, spec) where import Test.Hspec import HelperSequences.A000037 (a000037) main :: IO () main = hspec spec spec :: Spec spec = describe "A000037" $ it "correctly computes the first 20 elements" $ take 20 (map a000037 [1..]) `shouldBe` expectedValue where expectedValue = [2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24]
peterokagey/haskellOEIS
test/HelperSequences/A000037Spec.hs
Haskell
apache-2.0
379
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-} module Language.C.Obfuscate.CPS where import Data.Char import Data.List (nubBy) import Data.Maybe import qualified Data.Map as M import qualified Data.Set as S import qualified Language.C.Syntax.AST as AST import qualified Language.C.Data.Node as N import Language.C.Syntax.Constants import Language.C.Data.Ident import Language.C.Obfuscate.Var import Language.C.Obfuscate.ASTUtils import Language.C.Obfuscate.CFG import Language.C.Obfuscate.SSA -- import for testing import Language.C (parseCFile, parseCFilePre) import Language.C.System.GCC (newGCC) import Language.C.Pretty (pretty) import Text.PrettyPrint.HughesPJ (render, text, (<+>), hsep) import System.IO.Unsafe (unsafePerformIO) -- TODO LIST: -- 1. check whether k vs kParam (done) -- 2. id, loop an loop lambda (done) -- 3. pop and push (done) -- 4. function signatures (done) -- 5. max stack size -- 6. curr_stack_size + 1 or - 1 testCPS = do { let opts = [] ; ast <- errorOnLeftM "Parse Error" $ parseCFile (newGCC "gcc") Nothing opts "test/sort.c" -- -} "test/fibiter.c" ; case ast of { AST.CTranslUnit (AST.CFDefExt fundef:_) nodeInfo -> case runCFG fundef of { CFGOk (_, state) -> do { -- putStrLn $ show $ buildDTree (cfg state) ; -- putStrLn $ show $ buildDF (cfg state) ; let (SSA scopedDecls labelledBlocks sdom _ _) = buildSSA (cfg state) (formalArgs state) visitors = allVisitors sdom labelledBlocks exits = allExits labelledBlocks -- ; putStrLn $ show $ visitors -- ; putStrLn $ show $ exits ; let cps = ssa2cps fundef (buildSSA (cfg state) (formalArgs state)) ; putStrLn $ prettyCPS $ cps ; -- putStrLn $ render $ pretty (cps_ctxt cps) ; -- mapM_ (\d -> putStrLn $ render $ pretty d) (cps_funcsigs cps) ; -- mapM_ (\f -> putStrLn $ render $ pretty f) ((cps_funcs cps) ++ [cps_main cps]) } ; CFGError s -> error s } ; _ -> error "not fundec" } } prettyCPS :: CPS -> String prettyCPS cps = let declExts = map (\d -> AST.CDeclExt d) ([(cps_ctxt cps)] ++ (cps_funcsigs cps)) funDeclExts = map (\f -> AST.CFDefExt f) ((cps_funcs cps) ++ [cps_main cps]) in render $ pretty (AST.CTranslUnit (declExts ++ funDeclExts) N.undefNode) {- Source Language SSA (Prog) p ::= t x (\bar{t x}) {\bar{d}; \bar{b} } (Decl) d ::= t x (Block) b ::= l: {s} | l: {\bar{i} ; s} (Stmts) s ::= x = e; s | goto l; | return e; | e; s | if e { s } else { s } (Phi) i ::= x = \phi(\bar{g}) (Exp) e ::= v | e (\bar{e}) (Labelled argument) g ::= (l:e) (Label) l ::= l0 | ... | ln (Value) v ::= x | c (Type) t ::= int | bool | t* | t[] | | void (Loop environment) \Delta ::= (l_if, e_cond, l_true, l_false) -} -- was imported from SSA {- Target Language CPS (Prog) P ::= T X (\bar{T X}) {\bar{D}; \bar{B} } (Block) B ::= S (Decl) D ::= T X | P /* nested functions */ (Stmts) S ::= X = E ; S | return E; | E; S | if E { S } else { S } (Exp) E ::= V | E(\bar{E}) (Value) V :: = X | C | (\bar{T X}):T => {\bar{D}; \bar{B}} (Variable) X ::= x | y | k | ... (Type) T :: = int | bool | T * | T => T | T[] | void -} -- ^ a CPS function declaration AST data CPS = CPS { cps_decls :: [AST.CCompoundBlockItem N.NodeInfo] -- ^ main function decls , cps_stmts :: [AST.CCompoundBlockItem N.NodeInfo] -- ^ main function stmts , cps_funcsigs :: [AST.CDeclaration N.NodeInfo] -- ^ the signatures decls of the auxillary functions , cps_funcs :: [AST.CFunctionDef N.NodeInfo] -- ^ the auxillary functions , cps_ctxt :: AST.CDeclaration N.NodeInfo -- ^ the context for the closure , cps_main :: AST.CFunctionDef N.NodeInfo -- ^ the main function } deriving Show -- global names kParamName = "kParam" ctxtParamName = "ctxtParam" condParamName = "condParam" visitorParamName = "visitorParam" exitParamName = "exitParam" currStackSizeName = "curr_stack_size" {- class CPSize ssa cps where cps_trans :: ssa -> cps instance CPSize a b => CPSize [a] [b] where cps_trans as = map cps_trans as instance CPSize (Ident, LabeledBlock) (AST.CFunctionDef N.NodeInfo) where cps_trans (label, lb) = undefined {- translation d => D t => T x => X ---------------------- t x => T X -} instance CPSize (AST.CDeclaration N.NodeInfo) (AST.CDeclaration N.NodeInfo) where cps_trans decl = case decl of { AST.CDecl tyspec tripls nodeInfo -> let tyspec' = cps_trans tyspec tripls' = map (\(mb_decltr, mb_init, mb_size) -> let mb_decltr' = case mb_decltr of { Nothing -> Nothing ; Just decltr -> Just decltr -- todo } mb_init' = case mb_init of { Nothing -> Nothing ; Just init -> Just init -- todo } mb_size' = case mb_size of { Nothing -> Nothing ; Just size -> Just size -- todo } in (mb_decltr', mb_init', mb_size') ) tripls in AST.CDecl tyspec' tripls' nodeInfo -- ; AST.CStaticAssert e lit nodeInfo -> undefined } -} {- translation t => T ----------- int => int ----------- bool => bool t => t ------------- t* => T* t => T ------------ t[] => T* ------------- void => void -} {- instance CPSize (AST.CDeclarationSpecifier N.NodeInfo) (AST.CDeclarationSpecifier N.NodeInfo) where cps_trans tyspec = tyspec -- todo: unroll it -} {- data CDeclarationSpecifier a = CStorageSpec (CStorageSpecifier a) -- ^ storage-class specifier or typedef | CTypeSpec (CTypeSpecifier a) -- ^ type name | CTypeQual (CTypeQualifier a) -- ^ type qualifier | CFunSpec (CFunctionSpecifier a) -- ^ function specifier | CAlignSpec (CAlignmentSpecifier a) -- ^ alignment specifier deriving (Show, Data,Typeable {-! ,CNode ,Functor, Annotated !-}) -} {- --------- (Var) x => X -} {- instance CPSize (AST.CDeclarator N.NodeInfo) (AST.CDeclarator N.NodeInfo) where cps_trans declr@(AST.CDeclr mb_ident derivedDecltrs mb_cstrLtr attrs nodeInfo) = declr -} -- fn, K, \bar{\Delta} |- \bar{b} => \bar{P} --translating the labeled blocks to function decls {- fn, K, \bar{\Delta}, \bar{b} |- b_i => P_i --------------------------------------------- fn, K, \bar{\Delta} |- \bar{b} => \bar{P} -} type ContextName = String type Visitors = M.Map Ident Ident -- ^ last label of the visitor -> label of the loop type Exits = M.Map Ident Ident -- ^ label of the exit -> label of the loop cps_trans_lbs :: Bool -> -- ^ is return void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ top level function name -- ^ \bar{\Delta} become part of the labelled block flag (loop) Visitors -> Exits -> M.Map Ident LabeledBlock -> -- ^ \bar{b} [AST.CFunctionDef N.NodeInfo] cps_trans_lbs isReturnVoid localVars fargs ctxtName fname visitors exits lb_map = map (\(id,lb) -> cps_trans_lb isReturnVoid localVars fargs ctxtName fname lb_map id visitors exits lb) (M.toList lb_map) {- fn, \bar{\Delta}, \bar{b} |- b => P -} cps_trans_lb :: Bool -> -- ^ is return void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ top level function name -- ^ \bar{\Delta} become part of the labelled block flag (loop) M.Map Ident LabeledBlock -> -- ^ \bar{b} Ident -> -- ^ label for the current block Visitors -> Exits -> LabeledBlock -> -- ^ the block AST.CFunctionDef N.NodeInfo {- fn, k, \bar{\Delta}, \bar{b} |- s => S ----------------------------------------------------------------- (LabBlk) fn, \bar{\Delta}, \bar{b} |- l_i : {s} => void fn_i(void => void k) { S } fn, k, \bar{\Delta}, \bar{b} |- s => S --------------------------------------------------------------------------- (PhiBlk) fn, \bar{\Delta}, \bar{b} |- l_i : {\bar{i}; s} => void fn_i(void => void k) { S } -} cps_trans_lb isReturnVoid localVars fargs ctxtName fname lb_map ident visitors exits lb = let fname' = fname `app` ident tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)] declrs = [] k = iid kParamName paramK = AST.CDecl tyVoid -- void (*k)(ctxt *) [(Just (AST.CDeclr (Just k) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode paramCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode paramDeclr = [paramK, paramCtxt] decltrs = [AST.CFunDeclr (Right ([paramK, paramCtxt],False)) [] N.undefNode] mb_strLitr = Nothing attrs = [] pop | ident `M.member` exits = [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid "pop"))) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) ] | otherwise = [] stmt' = AST.CCompound [] (pop ++ (cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k lb_map ident (lb_loop lb) visitors exits (lb_stmts lb))) N.undefNode in AST.CFunDef tyVoid (AST.CDeclr (Just fname') decltrs mb_strLitr attrs N.undefNode) declrs stmt' N.undefNode cps_trans_stmts :: Bool -> -- ^ is return type void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ fname Ident -> -- ^ K -- ^ \bar{\Delta} become part of the labelled block flag (loop) M.Map Ident LabeledBlock -> -- ^ \bar{b} Ident -> -- ^ label for the current block Bool -> -- ^ whether label \in \Delta (is it a loop block) Visitors -> Exits -> [AST.CCompoundBlockItem N.NodeInfo] -> -- ^ stmts [AST.CCompoundBlockItem N.NodeInfo] cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits stmts = -- todo: maybe pattern match the CCompound constructor here? concatMap (\stmt -> cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits stmt) stmts -- fn, K, \bar{\Delta}, \bar{b} |-_l s => S cps_trans_stmt :: Bool -> -- ^ is return type void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ fname Ident -> -- ^ K -- ^ \bar{\Delta} become part of the labelled block flag (loop) M.Map Ident LabeledBlock -> -- ^ \bar{b} Ident -> -- ^ label for the current block Bool -> -- ^ whether label \in \Delta (is it a loop block) Visitors -> Exits -> AST.CCompoundBlockItem N.NodeInfo -> [AST.CCompoundBlockItem N.NodeInfo] {- l_i : { \bar{i} ; s } \in \bar{b} l, l_i |- \bar{i} => x1 = e1; ...; xn =en; ----------------------------------------------------------------------------- (GT1) fn, K, \bar{\Delta}, \bar{b} |-_l goto l_i => x1 = e1; ...; xn = en ; fnl_{i}(k) -} -- note that our target is C, hence besides k, the function call include argument such as context cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CGoto li nodeInfo)) = case M.lookup li lb_map of { Just lb | not (null (lb_phis lb)) -> let asgmts = cps_trans_phis ctxtName ident li (lb_phis lb) fname' = fname `app` li args = [ cvar k , cvar (iid ctxtParamName)] funcall = case M.lookup ident visitors of -- in case it is the last block of descending from the loop-if then branch, we call (*k)(ctxt) instead { Just loop_lbl | li == loop_lbl -> AST.CBlockStmt (AST.CExpr (Just (AST.CCall (ind $ cvar k) [cvar (iid ctxtParamName)] N.undefNode)) N.undefNode) ; _ -> AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar fname') args N.undefNode)) N.undefNode) } in asgmts ++ [ funcall ] {- l_i : { s } \in \bar{b} ----------------------------------------------------------------------------- (GT2) fn, K, \bar{\Delta}, \bar{b} |-_l goto l_i => fnl_{i}(k) -} | otherwise -> let fname' = fname `app` li args = [ cvar k , cvar (iid ctxtParamName) ] funcall = case M.lookup ident visitors of -- in case it is the last block of descending from the loop-if then branch, we call (*k)(ctxt) instead { Just loop_lbl | li == loop_lbl -> AST.CBlockStmt (AST.CExpr (Just (AST.CCall (ind $ cvar k) [cvar (iid ctxtParamName)] N.undefNode)) N.undefNode) ; _ -> AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar fname') args N.undefNode)) N.undefNode) } in [ funcall ] ; Nothing -> error "cps_trans_stmt failed at a non existent label." } cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CExpr (Just e) nodeInfo)) = case e of -- todo: deal with array element assignment, we need to assign the array first. we should do it at the block level { AST.CAssign op lval rval ni -> {- x => X; e => E; fn, K, \bar{\Delta}, \bar{b} |-_l s => S ----------------------------------------------------------------------------- (SeqAssign) fn, K, \bar{\Delta}, \bar{b} |-_l x = e;s => X = E;S -} let e' = cps_trans_exp localVars fargs ctxtName e in [AST.CBlockStmt (AST.CExpr (Just e') nodeInfo)] ; _ -> {- e => E; fn, K, \bar{\Delta}, \bar{b} |-_l s => S ----------------------------------------------------------------------------- (SeqE) fn, K, \bar{\Delta}, \bar{b} |-_l e;s => E;S -} let e' = cps_trans_exp localVars fargs ctxtName e in [AST.CBlockStmt (AST.CExpr (Just e') nodeInfo)] } {- ----------------------------------------------------------------------------- (returnNil) fn, K, \bar{\Delta}, \bar{b} |-_l return; => id(); -} -- C does not support higher order function. -- K is passed in as a formal arg -- K is a pointer to function -- updated: change from K(); to id(); because of return in a loop, (see noreturn.c) cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CReturn Nothing nodeInfo)) = let funcall = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid "id"))) [(cvar (iid ctxtParamName))] N.undefNode)) N.undefNode) in [ funcall ] {- e => E ----------------------------------------------------------------------------- (returnE) fn, K, \bar{\Delta}, \bar{b} |-_l return e; => x_r = E; id() -} -- C does not support higher order function. -- x_r and K belong to the contxt -- K is a pointer to function cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CReturn (Just e) nodeInfo)) | isReturnVoid = let funcall = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid "id"))) [(cvar (iid ctxtParamName))] N.undefNode)) N.undefNode) in [ funcall ] | otherwise = let funcall = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid "id"))) [(cvar (iid ctxtParamName))] N.undefNode)) N.undefNode) e' = cps_trans_exp localVars fargs ctxtName e assign = ((cvar (iid ctxtParamName)) .->. (iid "func_result")) .=. e' in [ AST.CBlockStmt (AST.CExpr (Just assign) nodeInfo), funcall ] cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CIf exp trueStmt mbFalseStmt nodeInfo)) {- l \in \Delta e => E ------------------------------------------------------------------------------------------------------- (IfLoop) fn, K, \bar{\Delta}, \bar{b} |-_l if (e) { goto l1 } else { goto l2 } => loop(() => E, f_l1 ,f_l2, k) ; -} -- in C, f_l1 and f_l2 need to be passed in as address & -- we need to 1. insert pop(ctxt) in f_l2 -- 2. let f_l3 be the closest descendant of f_l1 that call f_l(k,ctxt), replace the call by (*k)(ctxt) -- for 1, we can create a map to keep track of all the l2 -- for 2, we can perform a check at any l3 where it contains a "goto l;", look up l we find l1 is the true branch visitor -- we need to check whether l1 sdom l3, if so, replace "goto l" by (*k()) | inDelta = let exp' = cps_trans_exp localVars fargs ctxtName exp (lbl_tr, lb_tr) = case trueStmt of { AST.CGoto lbl _ -> case M.lookup lbl lb_map of { Nothing -> error "cps_trans_stmt error: label block is not found in the true statement in a loop." ; Just lb -> (lbl, lb) } ; _ -> error "cps_trans_stmt error: the true statement in a looping if statement does not contain goto" } asgmts_tr = cps_trans_phis ctxtName ident lbl_tr (lb_phis lb_tr) (lbl_fl, lb_fl) = case mbFalseStmt of { Just (AST.CGoto lbl _) -> case M.lookup lbl lb_map of { Nothing -> error "cps_trans_stmt error: label block is not found in the false statement in a loop." ; Just lb -> (lbl, lb) } ; _ -> error "cps_trans_stmt error: the false statement in a looping if statement does not contain goto" } asgmts_fl = cps_trans_phis ctxtName ident lbl_fl (lb_phis lb_fl) -- supposed to push asgmts_tr and asgmnts_fl to before f_l1 and f_l2, but does not work here. push_args :: [AST.CExpression N.NodeInfo] push_args = [ AST.CUnary AST.CAdrOp (cvar $ fname `app` (iid "cond") `app` ident) N.undefNode , AST.CUnary AST.CAdrOp (cvar (fname `app` lbl_tr)) N.undefNode , AST.CUnary AST.CAdrOp (cvar (fname `app` lbl_fl)) N.undefNode , cvar k , cvar (iid ctxtParamName) ] push = fname `app` (iid "push") call_push = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar push) push_args N.undefNode)) N.undefNode) loop = fname `app` iid "loop__entry" loop_args = [ (cvar (iid ctxtParamName) .->. (iid "loop_conds")) .!!. (cvar (iid ctxtParamName) .->. (iid currStackSizeName)) , (cvar (iid ctxtParamName) .->. (iid "loop_visitors")) .!!. (cvar (iid ctxtParamName) .->. (iid currStackSizeName)) , (cvar (iid ctxtParamName) .->. (iid "loop_exits")) .!!. (cvar (iid ctxtParamName) .->. (iid currStackSizeName)) , (cvar (iid ctxtParamName) .->. (iid "loop_ks")) .!!. (cvar (iid ctxtParamName) .->. (iid currStackSizeName)) , cvar (iid ctxtParamName) ] call_loop = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar loop) loop_args N.undefNode)) N.undefNode) in [ call_push, call_loop ] {- l \not \in \Delta e => E fn, K, \bar{\Delta}, \bar{b} |-_l s1 => S1 fn, K, \bar{\Delta}, \bar{b} |-_l s2 => S2 --------------------------------------------------------------------------------------------- (IfNotLoop) fn, K, \bar{\Delta}, \bar{b} |-_l if (e) { s1 } else { s2 } => if (E) { S1 } else { S2 } ; -} | otherwise = let trueStmt' = case trueStmt of { AST.CCompound ids items ni -> AST.CCompound ids (cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits items) ni ; _ -> case cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt trueStmt) of { [ AST.CBlockStmt trueStmt'' ] -> trueStmt'' ; items -> AST.CCompound [] items N.undefNode } } mbFalseStmt' = case mbFalseStmt of { Nothing -> Nothing ; Just (AST.CCompound ids items ni) -> Just $ AST.CCompound ids (cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits items) ni ; Just falseStmt -> Just $ case cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt falseStmt) of { [ AST.CBlockStmt falseStmt'' ] -> falseStmt'' ; items -> AST.CCompound [] items N.undefNode } } exp' = cps_trans_exp localVars fargs ctxtName exp in [AST.CBlockStmt (AST.CIf exp' trueStmt' mbFalseStmt' nodeInfo)] cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CCompound ids stmts nodeInfo)) = -- todo: do we need to do anything with the ids (local labels)? let stmts' = cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits stmts in [AST.CBlockStmt (AST.CCompound ids stmts' nodeInfo)] cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits stmt = error ("cps_trans_stmt error: unhandled case" ++ (show stmt)) -- (render $ pretty stmt)) cps_trans_phis :: ContextName -> Ident -> -- ^ source block label (where goto is invoked) Ident -> -- ^ destination block label (where goto is jumping to) [( Ident -- ^ var being redefined , [(Ident, Maybe Ident)])] -> -- ^ incoming block x renamed variables [AST.CCompoundBlockItem N.NodeInfo] cps_trans_phis ctxtName src_lb dest_lb ps = map (cps_trans_phi ctxtName src_lb dest_lb) ps {- --------------------------------------- l_s, l_d |- \bar{i} => \bar{x = e} -} cps_trans_phi :: ContextName -> Ident -> -- ^ source block label (where goto is invoked) Ident -> -- ^ destination block label (where goto is jumping to) (Ident, [(Ident, Maybe Ident)]) -> AST.CCompoundBlockItem N.NodeInfo cps_trans_phi ctxtName src_lb dest_lb (var, pairs) = case lookup src_lb pairs of -- look for the matching label according to the source label { Nothing -> error "cps_trans_phi failed: can't find the source label from the incoming block labels." ; Just redefined_lb -> -- lbl in which the var is redefined (it could be the precedence of src_lb) let lhs = (cvar (iid ctxtParamName)) .->. (var `app` dest_lb) rhs = (cvar (iid ctxtParamName)) .->. case redefined_lb of { Just l -> (var `app` l) ; Nothing -> var } in AST.CBlockStmt (AST.CExpr (Just (lhs .=. rhs)) N.undefNode) -- todo check var has been renamed with label } -- e => E {- --------- (ExpVal) v => V e => E, e_i => E_i -------------------------- (ExpApp) e(\bar{e}) => E(\bar{E}) -} -- it seems just to be identical -- for C target, we need to rename x to ctxt->x cps_trans_exp :: S.Set Ident -> S.Set Ident -> ContextName -> AST.CExpression N.NodeInfo -> AST.CExpression N.NodeInfo cps_trans_exp localVars fargs ctxtName (AST.CAssign op lhs rhs nodeInfo) = AST.CAssign op (cps_trans_exp localVars fargs ctxtName lhs) (cps_trans_exp localVars fargs ctxtName rhs) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CComma es nodeInfo) = AST.CComma (map (cps_trans_exp localVars fargs ctxtName) es) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCond e1 Nothing e3 nodeInfo) = AST.CCond (cps_trans_exp localVars fargs ctxtName e1) Nothing (cps_trans_exp localVars fargs ctxtName e3) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCond e1 (Just e2) e3 nodeInfo) = AST.CCond (cps_trans_exp localVars fargs ctxtName e1) (Just $ cps_trans_exp localVars fargs ctxtName e2) (cps_trans_exp localVars fargs ctxtName e3) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CBinary op e1 e2 nodeInfo) = AST.CBinary op (cps_trans_exp localVars fargs ctxtName e1) (cps_trans_exp localVars fargs ctxtName e2) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCast decl e nodeInfo) = AST.CCast decl (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CUnary op e nodeInfo) = AST.CUnary op (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CSizeofExpr e nodeInfo) = AST.CSizeofExpr (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CSizeofType decl nodeInfo) = AST.CSizeofType decl nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CAlignofExpr e nodeInfo) = AST.CAlignofExpr (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CAlignofType decl nodeInfo) = AST.CAlignofType decl nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CComplexReal e nodeInfo) = AST.CComplexReal (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CComplexImag e nodeInfo) = AST.CComplexImag (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CIndex arr idx nodeInfo) = AST.CIndex (cps_trans_exp localVars fargs ctxtName arr) (cps_trans_exp localVars fargs ctxtName idx) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCall f args nodeInfo) = AST.CCall (cps_trans_exp localVars fargs ctxtName f) (map (cps_trans_exp localVars fargs ctxtName) args) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CMember e ident deref nodeInfo) = AST.CMember (cps_trans_exp localVars fargs ctxtName e) ident deref nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CVar id _) = case unApp id of { Nothing -> cvar id ; Just id' | id' `S.member` (localVars `S.union` fargs) -> -- let io = unsafePerformIO $ print (localVars `S.union` fargs) >> print id' -- in io `seq` (cvar (iid ctxtParamName)) .->. id | otherwise -> cvar id -- global } cps_trans_exp localVars fargs ctxtName (AST.CConst c) = AST.CConst c cps_trans_exp localVars fargs ctxtName (AST.CCompoundLit decl initList nodeInfo) = AST.CCompoundLit decl initList nodeInfo -- todo check this cps_trans_exp localVars fargs ctxtName (AST.CStatExpr stmt nodeInfo ) = AST.CStatExpr stmt nodeInfo -- todo GNU C compount statement as expr cps_trans_exp localVars fargs ctxtName (AST.CLabAddrExpr ident nodeInfo ) = AST.CLabAddrExpr ident nodeInfo -- todo cps_trans_exp localVars fargs ctxtName (AST.CBuiltinExpr builtin ) = AST.CBuiltinExpr builtin -- todo build in expression {- top level translation p => P t => T x => X ti => Ti xi => Xi di => Di \bar{b} |- \bar{\Delta} k, \bar{\Delta} |- \bar{b} => \bar{P} P1 = void f1 (void => void k) { B1 } ------------------------------------------------------------------------ |- t x (\bar{t x}) {\bar{d};\bar{b}} => T X (\bar{T X}) {\bar{D}; T rx; \bar{P}; f1(id); return rx; } -} -- our target language C differs from the above specification. -- 1. the top function's type signature is not captured within SSA -- 2. \Delta is captured as the loop flag in LabaledBlock -- 3. there is no lambda expression, closure needs to be created as a context -- aux function that has type (void => void) => void should be in fact -- (void => void, ctxt*) => void -- 4. \bar{D} should be the context malloc and initialization -- 5. all the formal args should be copied to context ssa2cps :: (AST.CFunctionDef N.NodeInfo) -> SSA -> CPS ssa2cps fundef (SSA scopedDecls labelledBlocks sdom local_decl_vars fargs) = let -- scraping the information from the top level function under obfuscation funName = case getFunName fundef of { Just s -> s ; Nothing -> "unanmed" } formalArgDecls :: [AST.CDeclaration N.NodeInfo] formalArgDecls = getFormalArgs fundef formalArgIds :: [Ident] formalArgIds = concatMap (\declaration -> getFormalArgIds declaration) formalArgDecls (returnTy,ptrArrs) = getFunReturnTy fundef isReturnVoid = isVoidDeclSpec returnTy ctxtStructName = funName ++ "Ctxt" -- the context struct declaration context = mkContext ctxtStructName labelledBlocks formalArgDecls scopedDecls returnTy ptrArrs local_decl_vars fargs ctxtName = map toLower ctxtStructName -- alias name is inlower case and will be used in the the rest of the code -- finding the visitor labels and the exit labels visitors = allVisitors sdom labelledBlocks exits = allExits labelledBlocks -- all the conditional function conds = allLoopConds local_decl_vars fargs ctxtName funName labelledBlocks -- loop_cps, loop_lambda, id and pop and push loop_cps = loopCPS ctxtName funName lambda_loop_cps = lambdaLoopCPS ctxtName funName id_cps = idCPS ctxtName funName push_cps = pushCPS ctxtName funName pop_cps = popCPS ctxtName funName -- all the "nested/helper" function declarations -- todo: packing all the variable into a record ps = cps_trans_lbs isReturnVoid local_decl_vars fargs ctxtName (iid funName) {- (iid "id") -} visitors exits labelledBlocks -- all function signatures funcSignatures = map funSig (ps ++ conds ++ [loop_cps, lambda_loop_cps, id_cps, push_cps, pop_cps, fundef]) -- include the source func, in case of recursion main_decls = -- 1. malloc the context obj in the main func -- ctxtTy * ctxt = (ctxtTy *) malloc(sizeof(ctxtTy)); [ AST.CBlockDecl (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode), Just (AST.CInitExpr (AST.CCast (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode) (AST.CCall (AST.CVar (iid "malloc") N.undefNode) [AST.CSizeofType (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [] N.undefNode) N.undefNode] N.undefNode) N.undefNode) N.undefNode),Nothing)] N.undefNode) ] main_stmts = -- 2. initialize the counter-part in the context of the formal args -- forall arg. ctxt->arg_label0 = arg [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (arg `app` (iid $ labPref ++ "0" ))) .=. (AST.CVar arg N.undefNode))) N.undefNode) | arg <- formalArgIds] ++ -- 3. initialize the collection which are the local vars, e.g. a locally declared array -- int a[3]; -- will be reinitialized as ctxt->a_0 = (int *)malloc(sizeof(int)*3); [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (var `app` (iid $ labPref ++ "0" ))) .=. rhs)) N.undefNode) | scopedDecl <- scopedDecls , isJust (containerDeclToInit scopedDecl) , let (Just (var,rhs)) = containerDeclToInit scopedDecl ] ++ -- 4. initialize the context->curr_stack_size = 0; [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (iid currStackSizeName) .=. (AST.CConst (AST.CIntConst (cInteger 0) N.undefNode))))) N.undefNode) ] ++ -- 3. calling block 0 [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (AST.CVar ((iid funName) `app` (iid (labPref ++ "0" ))) N.undefNode) [ AST.CUnary AST.CAdrOp (AST.CVar ((iid funName) `app` (iid "id")) N.undefNode) N.undefNode , AST.CVar (iid ctxtParamName) N.undefNode ] N.undefNode)) N.undefNode) , if isReturnVoid then AST.CBlockStmt (AST.CReturn Nothing N.undefNode) else AST.CBlockStmt (AST.CReturn (Just $ (cvar (iid ctxtParamName)) .->. (iid "func_result")) N.undefNode) ] main_func = case fundef of { AST.CFunDef tySpecfs declarator decls _ nodeInfo -> AST.CFunDef tySpecfs declarator decls (AST.CCompound [] (main_decls ++ main_stmts) N.undefNode) nodeInfo } in CPS main_decls main_stmts funcSignatures (ps ++ conds ++ [loop_cps, lambda_loop_cps, id_cps, push_cps, pop_cps]) context main_func -- ^ turn a scope declaration into a rhs initalization. -- ^ refer to local_array.c containerDeclToInit :: AST.CDeclaration N.NodeInfo -> Maybe (Ident, AST.CExpression N.NodeInfo) containerDeclToInit (AST.CDecl typespecs tripls nodeInfo0) = case tripls of { (Just decl@(AST.CDeclr (Just arrName) [arrDecl] _ _ _), _, _):_ -> case arrDecl of { AST.CArrDeclr _ (AST.CArrSize _ size) _ -> let ptrToTy = AST.CDecl typespecs [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode malloc = AST.CCall (AST.CVar (iid "malloc") N.undefNode) [AST.CBinary AST.CMulOp (AST.CSizeofType (AST.CDecl typespecs [] N.undefNode) N.undefNode) size N.undefNode] N.undefNode cast = AST.CCast ptrToTy malloc N.undefNode in Just (arrName, cast) ; _ -> Nothing } ; _ -> Nothing } -- ^ get all visitor labels from te labeledblocks map allVisitors :: SDom -> M.Map NodeId LabeledBlock -> M.Map NodeId NodeId allVisitors sdom lbs = M.fromList $ -- l is a visitor label if (1) succ of l, say l1 is loop, (2) l2, the then-branch label of l1 is sdom'ing l [ (l, succ) | (l, lblk) <- M.toList lbs , succ <- lb_succs lblk , case M.lookup succ lbs of { Nothing -> False ; Just lblk' -> (lb_loop lblk') && (domBy sdom (lb_succs lblk' !! 0) l) } ] -- ^ get all exit labels from the labeledblocks map allExits :: M.Map NodeId LabeledBlock -> M.Map NodeId NodeId allExits lbs = M.fromList $ [ ((lb_succs lblk) !! 1, l) | (l, lblk) <- M.toList lbs , (lb_loop lblk) && (length (lb_succs lblk) > 1) ] -- ^ retrieve all condional test from the loops and turn them into functions allLoopConds :: S.Set Ident -> S.Set Ident -> ContextName -> String -> M.Map NodeId LabeledBlock -> [AST.CFunctionDef N.NodeInfo] allLoopConds local_vars fargs ctxtName fname lbs = concatMap (\(id,lb) -> loopCond local_vars fargs ctxtName fname (id,lb)) (M.toList lbs) loopCond :: S.Set Ident -> S.Set Ident -> ContextName -> String -> (NodeId, LabeledBlock) -> [AST.CFunctionDef N.NodeInfo] loopCond local_vars fargs ctxtName fname (l,blk) | lb_loop blk = let stmts = lb_stmts blk conds = [ cps_trans_exp local_vars fargs ctxtName e | AST.CBlockStmt (AST.CIf e tt ff _) <- stmts ] formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode decls = [ fun [AST.CTypeSpec boolTy] (iid fname `app` iid "cond" `app` l) [formalArgCtxt] [AST.CBlockStmt (AST.CReturn (Just cond) N.undefNode)] | cond <- conds ] in decls | otherwise = [] -- ^ push {- void push(int (*cond)(struct SortCtxt *), void (*visitor)(void (*k)(struct SortCtxt*), struct SortCtxt*), void (*exit)(void (*k)(struct SortCtxt*), struct SortCtxt*), void (*k)(struct SortCtxt*), sortctxt *ctxt) { ctxt->curr_stack_size = ctxt->curr_stack_size + 1; ctxt->loop_conds[ctxt->curr_stack_size] = cond; ctxt->loop_visitors[ctxt->curr_stack_size] = visitor; ctxt->loop_exits[ctxt->curr_stack_size] = exit; ctxt->loop_ks[ctxt->curr_stack_size] = k; } -} pushCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo pushCPS ctxtName fname = let cond = iid condParamName formalArgCond = AST.CDecl [AST.CTypeSpec intTy] -- int (*cond)(ctxt *) [(Just (AST.CDeclr (Just cond) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode visitor = iid visitorParamName formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*X)(void (*k)(ctxt*), ctxt*) [(Just (AST.CDeclr (Just x) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([ AST.CDecl [AST.CTypeSpec voidTy] [(Just (AST.CDeclr (Just k) [AST.CPtrDeclr [] N.undefNode ,AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False)) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode , AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode ],False)) [] N.undefNode ] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode formalArgVisitor = formalArgX visitor exit = iid exitParamName formalArgExit = formalArgX exit k = iid kParamName formalArgK = AST.CDecl [AST.CTypeSpec voidTy] -- void (*k)(ctxt *) [(Just (AST.CDeclr (Just k) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid "push") [formalArgCond, formalArgVisitor, formalArgExit, formalArgK, formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid currStackSizeName)) .=. (AST.CBinary AST.CAddOp (cvar ctxt .->. (iid currStackSizeName)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid "loop_conds")) .!!. (cvar ctxt .->. (iid currStackSizeName))) .=. (cvar cond))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid "loop_visitors")) .!!. (cvar ctxt .->. (iid currStackSizeName))) .=. (cvar visitor))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid "loop_exits")) .!!. (cvar ctxt .->. (iid currStackSizeName))) .=. (cvar exit))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid "loop_ks")) .!!. (cvar ctxt .->. (iid currStackSizeName))) .=. (cvar k))) N.undefNode) ] {- void pop(sortctxt *ctxt) { ctxt->curr_stack_size = ctxt->curr_stack_size - 1; } -} popCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo popCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid "pop") [formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid currStackSizeName)) .=. (AST.CBinary AST.CSubOp (cvar ctxt .->. (iid currStackSizeName)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode) ] -- ^ loop_cps {- void loop_cps(int (*cond)(sortctxt*), void (*visitor)(void (*k)(sortctxt*), sortctxt*), void (*exit)(void (*k)(sortctxt*), sortctxt*), void (*k)(sortctxt *), sortctxt* ctxt) { if ((*cond)(ctxt)) { (*visitor)(&lambda_loop_cps, ctxt); } else { (*exit)(k,ctxt); } } -} loopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo loopCPS ctxtName fname = let cond = iid condParamName formalArgCond = AST.CDecl [AST.CTypeSpec intTy] -- int (*cond)(ctxt *) [(Just (AST.CDeclr (Just cond) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode visitor = iid visitorParamName formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*X)(void (*k)(ctxt*), ctxt*) [(Just (AST.CDeclr (Just x) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([ AST.CDecl [AST.CTypeSpec voidTy] [(Just (AST.CDeclr (Just k) [AST.CPtrDeclr [] N.undefNode ,AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False)) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode , AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode ],False)) [] N.undefNode ] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode formalArgVisitor = formalArgX visitor exit = iid exitParamName formalArgExit = formalArgX exit k = iid kParamName formalArgK = AST.CDecl [AST.CTypeSpec voidTy] -- void (*k)(ctxt *) [(Just (AST.CDeclr (Just k) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid "loop__entry") [formalArgCond, formalArgVisitor, formalArgExit, formalArgK, formalArgCtxt] [ AST.CBlockStmt (AST.CIf (funCall (ind (cvar cond)) [(cvar ctxt)]) (AST.CCompound [] [AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar visitor)) [ adr (cvar (iid fname `app` iid "lambda_loop")) , cvar ctxt ]) N.undefNode ) ] N.undefNode) (Just (AST.CCompound [] [AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar exit)) [ cvar k , cvar ctxt ]) N.undefNode) ] N.undefNode)) N.undefNode) ] {- void lambda_loop_cps(sortctxt* ctxt) { loop_cps(ctxt->loop_conds[ctxt->loop_stack_size], ctxt->loop_visitors[ctxt->loop_stack_size], ctxt->loop_exits[ctxt->loop_stack_size], ctxt->loop_ks[ctxt->loop_stack_size], ctxt); } -} lambdaLoopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo lambdaLoopCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid "lambda_loop") [formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (iid fname `app` iid "loop__entry")) [ ((cvar ctxt) .->. (iid "loop_conds")) .!!. ((cvar ctxt) .->. (iid currStackSizeName)) , ((cvar ctxt) .->. (iid "loop_visitors")) .!!. ((cvar ctxt) .->. (iid currStackSizeName)) , ((cvar ctxt) .->. (iid "loop_exits")) .!!. ((cvar ctxt) .->. (iid currStackSizeName)) , ((cvar ctxt) .->. (iid "loop_ks")) .!!. ((cvar ctxt) .->. (iid currStackSizeName)) , (cvar ctxt) ] N.undefNode)) N.undefNode) ] {- void id(sortctxt *ctxt) { return; } -} idCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo idCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid "id") [formalArgCtxt] [ AST.CBlockStmt (AST.CReturn Nothing N.undefNode) ] -- ^ generate function signature declaration from function definition funSig :: AST.CFunctionDef N.NodeInfo -> AST.CDeclaration N.NodeInfo funSig (AST.CFunDef tySpecfs declarator op_decls stmt nodeInfo) = AST.CDecl tySpecfs [(Just declarator, Nothing, Nothing)] N.undefNode -- ^ making the context struct declaration mkContext :: String -> -- ^ context name M.Map Ident LabeledBlock -> -- ^ labeled blocks [AST.CDeclaration N.NodeInfo] -> -- ^ formal arguments [AST.CDeclaration N.NodeInfo] -> -- ^ local variable declarations [AST.CDeclarationSpecifier N.NodeInfo] -> -- ^ return Type [AST.CDerivedDeclarator N.NodeInfo] -> -- ^ the pointer or array postfix S.Set Ident -> S.Set Ident -> AST.CDeclaration N.NodeInfo mkContext name labeledBlocks formal_arg_decls local_var_decls returnType ptrArrs local_decl_vars fargs = let structName = iid name ctxtAlias = AST.CDeclr (Just (internalIdent (map toLower name))) [] Nothing [] N.undefNode attrs = [] stackSize = 20 isReturnVoid = isVoidDeclSpec returnType unaryFuncStack ty fname = AST.CDecl [AST.CTypeSpec ty] -- void (*loop_ks[2])(struct FuncCtxt*); -- todo : these are horrible to read, can be simplified via some combinators [(Just (AST.CDeclr (Just $ iid fname) [ AST.CArrDeclr [] (AST.CArrSize False (AST.CConst (AST.CIntConst (cInteger stackSize) N.undefNode))) N.undefNode , AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) Nothing [] N.undefNode) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode) ,Nothing,Nothing)] N.undefNode binaryFuncStack fname = AST.CDecl [AST.CTypeSpec voidTy] [(Just (AST.CDeclr (Just $ iid fname) [ AST.CArrDeclr [] (AST.CArrSize False (AST.CConst (AST.CIntConst (cInteger stackSize) N.undefNode))) N.undefNode , AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CVoidType N.undefNode)] [(Just (AST.CDeclr (Just (iid kParamName)) [AST.CPtrDeclr [] N.undefNode, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) Nothing [] N.undefNode) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode, AST.CDecl [AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) Nothing [] N.undefNode) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode) ,Nothing,Nothing)] N.undefNode ksStack = unaryFuncStack voidTy "loop_ks" condStack = unaryFuncStack intTy "loop_conds" visitorStack = binaryFuncStack "loop_visitors" exitStack = binaryFuncStack "loop_exits" currStackSize = AST.CDecl [AST.CTypeSpec intTy] [(Just (AST.CDeclr (Just $ iid currStackSizeName) [] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode funcResult | isReturnVoid = [] | otherwise = [AST.CDecl returnType [(Just (AST.CDeclr (Just $ iid "func_result") ptrArrs Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode] decls' = -- formal_arg_decls ++ -- note: we remove local decl duplicate, maybe we should let different label block to have different type decl in the ctxt, see test/scoped_dup_var.c concatMap (\d -> renameDeclWithLabeledBlocks d labeledBlocks local_decl_vars fargs) (nubBy declLHSEq $ map (cps_trans_declaration . dropConstTyQual) (formal_arg_decls ++ local_var_decls)) ++ [ksStack, condStack, visitorStack, exitStack, currStackSize] ++ funcResult tyDef = AST.CStorageSpec (AST.CTypedef N.undefNode) structDef = AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) (Just decls') attrs N.undefNode) N.undefNode) in AST.CDecl [tyDef, structDef] [(Just ctxtAlias, Nothing, Nothing)] N.undefNode -- eq for the declaration nub, see the above declLHSEq (AST.CDecl declSpecifiers1 trips1 _) (AST.CDecl declSpecifiers2 trips2 _) = let getIds trips = map (\(mb_decl, mb_init, mb_size) -> case mb_decl of { Just (AST.CDeclr mb_id derivedDeclarators mb_strLit attrs nInfo) -> mb_id ; Nothing -> Nothing }) trips in (getIds trips1) == (getIds trips2) -- we need to drop the constant type specifier since we need to initialize them in block 0, see test/const.c dropConstTyQual :: AST.CDeclaration N.NodeInfo -> AST.CDeclaration N.NodeInfo dropConstTyQual decl = case decl of { AST.CDecl declSpecifiers trips ni -> AST.CDecl (filter (not . isConst) declSpecifiers) trips ni } where isConst (AST.CTypeQual (AST.CConstQual _)) = True isConst _ = False -- renameDeclWithLabels :: AST.CDeclaration N.NodeInfo -> [Ident] -> [AST.CDeclaration N.NodeInfo] -- renameDeclWithLabels decl labels = map (renameDeclWithLabel decl) labels renameDeclWithLabeledBlocks :: AST.CDeclaration N.NodeInfo -> M.Map Ident LabeledBlock -> S.Set Ident -> S.Set Ident -> [AST.CDeclaration N.NodeInfo] renameDeclWithLabeledBlocks decl labeledBlocks local_decl_vars fargs = let idents = getFormalArgIds decl in do { ident <- idents ; (lb,blk) <- M.toList labeledBlocks ; if (null (lb_preds blk)) || -- it's the entry block (ident `elem` (lb_lvars blk)) || -- the var is in the lvars (ident `elem` (map fst (lb_phis blk))) || -- the var is in the phi (ident `elem` (lb_containers blk)) -- the var is one of the lhs container ids such as array or members then return (renameDeclWithLabel decl lb local_decl_vars fargs) else [] } renameDeclWithLabel decl label local_decl_vars fargs = let rnState = RSt label M.empty [] [] local_decl_vars fargs in case renamePure rnState decl of { (decl', rstate', containers) -> decl' } {- translation t => T ----------- int => int ----------- bool => bool t => t ------------- t* => T* t => T ------------ t[] => T* ------------- void => void -} cps_trans_declaration :: AST.CDeclaration N.NodeInfo -> AST.CDeclaration N.NodeInfo cps_trans_declaration (AST.CDecl declSpecifiers trips ni) = AST.CDecl (map cps_trans_declspec declSpecifiers) (map (\(mb_decl, mb_init, mb_size) -> let mb_decl' = case mb_decl of { Nothing -> Nothing ; Just decl -> Just (cps_trans_decltr decl) } in (mb_decl', mb_init, mb_size)) trips) ni -- lhs of a declaration cps_trans_declspec :: AST.CDeclarationSpecifier N.NodeInfo -> AST.CDeclarationSpecifier N.NodeInfo cps_trans_declspec (AST.CStorageSpec storageSpec) = AST.CStorageSpec storageSpec -- auto, register, static, extern etc cps_trans_declspec (AST.CTypeSpec tySpec) = AST.CTypeSpec tySpec -- simple type, void, int, bool etc cps_trans_declspec (AST.CTypeQual tyQual) = AST.CTypeQual tyQual -- qual, CTypeQual, CVolatQual, etc -- cps_trans_declspec (AST.CFunSpec funSpec) = AST.CFunSpec funSpec -- todo -- cps_trans_declspec (AST.CAlignSpec alignSpec) = AST.CAlignSpec alignSpec -- todo -- rhs (after the variable) cps_trans_decltr :: AST.CDeclarator N.NodeInfo -> AST.CDeclarator N.NodeInfo cps_trans_decltr (AST.CDeclr mb_id derivedDeclarators mb_strLit attrs nInfo) = AST.CDeclr mb_id (map cps_trans_derived_decltr derivedDeclarators) mb_strLit attrs nInfo cps_trans_derived_decltr :: AST.CDerivedDeclarator N.NodeInfo -> AST.CDerivedDeclarator N.NodeInfo cps_trans_derived_decltr (AST.CPtrDeclr tyQuals ni) = AST.CPtrDeclr tyQuals ni cps_trans_derived_decltr (AST.CArrDeclr tyQuals arrSize ni) = AST.CPtrDeclr tyQuals ni cps_trans_derived_decltr (AST.CFunDeclr either_id_decls attrs ni) = AST.CFunDeclr either_id_decls attrs ni {- data CDeclarationSpecifier a = CStorageSpec (CStorageSpecifier a) -- ^ storage-class specifier or typedef | CTypeSpec (CTypeSpecifier a) -- ^ type name | CTypeQual (CTypeQualifier a) -- ^ type qualifier | CFunSpec (CFunctionSpecifier a) -- ^ function specifier | CAlignSpec (CAlignmentSpecifier a) -- ^ alignment specifier deriving (Show, Data,Typeable {-! ,CNode ,Functor, Annotated !-}) -}
luzhuomi/cpp-obs
Language/C/Obfuscate/CPS_old.hs
Haskell
apache-2.0
58,743