{"size":499,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Day24Tests where\n\nimport Test.QuickCheck\nimport Test.Tasty\nimport Test.Tasty.Golden\nimport Test.Tasty.HUnit\nimport Test.Tasty.QuickCheck as QC\n\nimport Day24\n\ntestPart1 :: Assertion\ntestPart1 = assertEqual \"\" 377. part1 =<< getInput \"input\/day24\"\n\ntestPart2 :: Assertion\ntestPart2 = assertEqual \"\" 4231 . part2 =<< getInput \"input\/day24\"\n\ntests :: [TestTree]\ntests = [\n testCase \"part1\" testPart1,\n testCase \"part2\" testPart2\n ]\n","avg_line_length":22.6818181818,"max_line_length":66,"alphanum_fraction":0.6573146293} {"size":124,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"answer :: Int\nanswer = sum . filter (\\x -> x `mod` 5 == 0 || x `mod` 3 == 0) $ [1..1000]\n\nmain :: IO ()\nmain = print answer\n","avg_line_length":20.6666666667,"max_line_length":74,"alphanum_fraction":0.5080645161} {"size":13637,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NamedFieldPuns #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# OPTIONS_GHC -Wno-partial-type-signatures #-}\nmodule Spec.Contract(tests, loopCheckpointContract, initial, upd) where\n\nimport Control.Lens\nimport Control.Monad (forM_, forever, void)\nimport Control.Monad.Error.Lens\nimport Control.Monad.Except (catchError, throwError)\nimport Control.Monad.Freer (Eff)\nimport Control.Monad.Freer.Extras.Log (LogLevel (..))\nimport qualified Control.Monad.Freer.Extras.Log as Log\nimport Test.Tasty\n\nimport Ledger (Address, PubKey, Slot)\nimport qualified Ledger\nimport qualified Ledger.Ada as Ada\nimport qualified Ledger.Constraints as Constraints\nimport qualified Ledger.Crypto as Crypto\nimport Plutus.Contract as Con\nimport qualified Plutus.Contract.State as State\nimport Plutus.Contract.Test\nimport Plutus.Contract.Types (ResumableResult (..), responses)\nimport Plutus.Contract.Util (loopM)\nimport qualified Plutus.Trace as Trace\nimport Plutus.Trace.Emulator (ContractInstanceTag, Emulator, EmulatorTrace, activateContract,\n activeEndpoints, callEndpoint)\nimport Plutus.Trace.Emulator.Types (ContractInstanceLog (..), ContractInstanceMsg (..),\n ContractInstanceState (..), UserThreadMsg (..))\nimport qualified PlutusTx\nimport PlutusTx.Lattice\nimport Prelude hiding (not)\nimport qualified Prelude as P\nimport qualified Wallet.Emulator as EM\n\nimport Plutus.Contract.Effects (ActiveEndpoint (..))\nimport qualified Plutus.Contract.Request as Endpoint\nimport Plutus.Contract.Resumable (IterationID, Response (..))\nimport Plutus.Contract.Trace.RequestHandler (maybeToHandler)\n\ntests :: TestTree\ntests =\n let run :: Slot -> String -> TracePredicate -> EmulatorTrace () -> _\n run sl = checkPredicateOptions (defaultCheckOptions & maxSlot .~ sl & minLogLevel .~ Debug)\n\n check :: Slot -> String -> Contract () Schema ContractError () -> _ -> _\n check sl nm contract pred = run sl nm (pred contract) (void $ activateContract w1 contract tag)\n\n tag :: ContractInstanceTag\n tag = \"instance 1\"\n\n in\n testGroup \"contracts\"\n [ check 1 \"awaitSlot\" (void $ awaitSlot 10) $ \\con ->\n waitingForSlot con tag 10\n\n , check 1 \"selectEither\" (void $ selectEither (awaitSlot 10) (awaitSlot 5)) $ \\con ->\n waitingForSlot con tag 5\n\n , check 1 \"both\" (void $ Con.both (awaitSlot 10) (awaitSlot 20)) $ \\con ->\n waitingForSlot con tag 10\n\n , check 1 \"both (2)\" (void $ Con.both (awaitSlot 10) (awaitSlot 20)) $ \\con ->\n waitingForSlot con tag 20\n\n , check 1 \"watchAddressUntilSlot\" (void $ watchAddressUntilSlot someAddress 5) $ \\con ->\n waitingForSlot con tag 5\n\n , check 1 \"endpoint\" (endpoint @\"ep\") $ \\con ->\n endpointAvailable @\"ep\" con tag\n\n , check 1 \"forever\" (forever $ endpoint @\"ep\") $ \\con ->\n endpointAvailable @\"ep\" con tag\n\n , let\n oneTwo :: Contract () Schema ContractError Int = endpoint @\"1\" >> endpoint @\"2\" >> endpoint @\"4\"\n oneThree :: Contract () Schema ContractError Int = endpoint @\"1\" >> endpoint @\"3\" >> endpoint @\"4\"\n con = void (oneTwo `select` oneThree)\n in\n run 1 \"alternative\"\n (endpointAvailable @\"3\" con tag\n .&&. not (endpointAvailable @\"2\" con tag))\n $ do\n hdl <- activateContract w1 con tag\n callEndpoint @\"1\" hdl 1\n\n , let theContract :: Contract () Schema ContractError () = void $ endpoint @\"1\" @Int >> endpoint @\"2\" @Int\n in run 1 \"call endpoint (1)\"\n (endpointAvailable @\"1\" theContract tag)\n (void $ activateContract w1 theContract tag)\n\n , let theContract :: Contract () Schema ContractError () = void $ endpoint @\"1\" @Int >> endpoint @\"2\" @Int\n in run 1 \"call endpoint (2)\"\n (endpointAvailable @\"2\" theContract tag\n .&&. not (endpointAvailable @\"1\" theContract tag))\n (activateContract w1 theContract tag >>= \\hdl -> callEndpoint @\"1\" hdl 1)\n\n , let theContract :: Contract () Schema ContractError () = void $ endpoint @\"1\" @Int >> endpoint @\"2\" @Int\n in run 1 \"call endpoint (3)\"\n (not (endpointAvailable @\"2\" theContract tag)\n .&&. not (endpointAvailable @\"1\" theContract tag))\n (activateContract w1 theContract tag >>= \\hdl -> callEndpoint @\"1\" hdl 1 >> callEndpoint @\"2\" hdl 2)\n\n , let theContract :: Contract () Schema ContractError [ActiveEndpoint] = endpoint @\"5\" @[ActiveEndpoint]\n expected = ActiveEndpoint{ aeDescription = EndpointDescription \"5\", aeMetadata = Nothing}\n in run 5 \"active endpoints\"\n (assertDone theContract tag ((==) [expected]) \"should be done\")\n $ do\n hdl <- activateContract w1 theContract tag\n _ <- Trace.waitNSlots 1\n eps <- activeEndpoints hdl\n void $ callEndpoint @\"5\" hdl eps\n\n , let theContract :: Contract () Schema ContractError () = void $ submitTx mempty >> watchAddressUntilSlot someAddress 20\n in run 1 \"submit tx\"\n (waitingForSlot theContract tag 20)\n (void $ activateContract w1 theContract tag)\n\n , let smallTx = Constraints.mustPayToPubKey (Crypto.pubKeyHash $ walletPubKey (Wallet 2)) (Ada.lovelaceValueOf 10)\n theContract :: Contract () Schema ContractError () = submitTx smallTx >>= awaitTxConfirmed . Ledger.txId >> submitTx smallTx >>= awaitTxConfirmed . Ledger.txId\n in run 3 \"handle several blockchain events\"\n (walletFundsChange w1 (Ada.lovelaceValueOf (-20))\n .&&. assertNoFailedTransactions\n .&&. assertDone theContract tag (const True) \"all blockchain events should be processed\")\n (void $ activateContract w1 theContract tag >> Trace.waitUntilSlot 3)\n\n , let l = endpoint @\"1\" >> endpoint @\"2\"\n r = endpoint @\"3\" >> endpoint @\"4\"\n theContract :: Contract () Schema ContractError () = void $ selectEither l r\n in run 1 \"select either\"\n (assertDone theContract tag (const True) \"left branch should finish\")\n (activateContract w1 theContract tag >>= (\\hdl -> callEndpoint @\"1\" hdl 1 >> callEndpoint @\"2\" hdl 2))\n\n , let theContract :: Contract () Schema ContractError () = void $ loopM (\\_ -> Left <$> endpoint @\"1\" @Int) 0\n in run 1 \"loopM\"\n (endpointAvailable @\"1\" theContract tag)\n (void $ activateContract w1 theContract tag >>= \\hdl -> callEndpoint @\"1\" hdl 1)\n\n , let theContract :: Contract () Schema ContractError () = void $ throwing Con._ContractError $ OtherError \"error\"\n in run 1 \"throw an error\"\n (assertContractError theContract tag (\\case { OtherError \"error\" -> True; _ -> False}) \"failed to throw error\")\n (void $ activateContract w1 theContract tag)\n\n , run 2 \"pay to wallet\"\n (walletFundsChange w1 (Ada.lovelaceValueOf (-200))\n .&&. walletFundsChange w2 (Ada.lovelaceValueOf 200)\n .&&. assertNoFailedTransactions)\n (void $ Trace.payToWallet w1 w2 (Ada.lovelaceValueOf 200))\n\n , let theContract :: Contract () Schema ContractError PubKey = ownPubKey\n in run 1 \"own public key\"\n (assertDone theContract tag (== walletPubKey w2) \"should return the wallet's public key\")\n (void $ activateContract w2 (void theContract) tag)\n\n , let payment = Constraints.mustPayToPubKey (Crypto.pubKeyHash $ walletPubKey w2) (Ada.lovelaceValueOf 10)\n theContract :: Contract () Schema ContractError () = submitTx payment >>= awaitTxConfirmed . Ledger.txId\n in run 2 \"await tx confirmed\"\n (assertDone theContract tag (const True) \"should be done\")\n (activateContract w1 theContract tag >> void (Trace.waitNSlots 1))\n\n , run 1 \"checkpoints\"\n (not (endpointAvailable @\"2\" checkpointContract tag) .&&. endpointAvailable @\"1\" checkpointContract tag)\n (void $ activateContract w1 checkpointContract tag >>= \\hdl -> callEndpoint @\"1\" hdl 1 >> callEndpoint @\"2\" hdl 1)\n\n , run 1 \"error handling & checkpoints\"\n (assertDone errorContract tag (\\i -> i == 11) \"should finish\")\n (void $ activateContract w1 (void errorContract) tag >>= \\hdl -> callEndpoint @\"1\" hdl 1 >> callEndpoint @\"2\" hdl 10 >> callEndpoint @\"3\" hdl 11)\n\n , run 1 \"loop checkpoint\"\n (assertDone loopCheckpointContract tag (\\i -> i == 4) \"should finish\"\n .&&. assertResumableResult loopCheckpointContract tag DoShrink (null . view responses) \"should collect garbage\"\n .&&. assertResumableResult loopCheckpointContract tag DontShrink ((==) 4 . length . view responses) \"should keep everything\"\n )\n $ do\n hdl <- activateContract w1 loopCheckpointContract tag\n forM_ [1..4] (\\_ -> callEndpoint @\"1\" hdl 1)\n\n , let theContract :: Contract () Schema ContractError () = logInfo @String \"waiting for endpoint 1\" >> endpoint @\"1\" >>= logInfo . (<>) \"Received value: \" . show\n matchLogs :: [EM.EmulatorTimeEvent ContractInstanceLog] -> Bool\n matchLogs lgs =\n case _cilMessage . EM._eteEvent <$> lgs of\n [ Started, ContractLog \"waiting for endpoint 1\", CurrentRequests [_], ReceiveEndpointCall{}, ContractLog \"Received value: 27\", HandledRequest _, CurrentRequests [], StoppedNoError ] -> True\n _ -> False\n\n in run 1 \"contract logs\"\n (assertInstanceLog tag matchLogs)\n (void $ activateContract w1 theContract tag >>= \\hdl -> callEndpoint @\"1\" hdl 27)\n\n , let theContract :: Contract () Schema ContractError () = logInfo @String \"waiting for endpoint 1\" >> endpoint @\"1\" >>= logInfo . (<>) \"Received value: \" . show\n matchLogs :: [EM.EmulatorTimeEvent UserThreadMsg] -> Bool\n matchLogs lgs =\n case EM._eteEvent <$> lgs of\n [ UserLog \"Received contract state\", UserLog \"Final state: Right Nothing\"] -> True\n _ -> False\n\n in run 4 \"contract state\"\n (assertUserLog matchLogs)\n $ do\n hdl <- Trace.activateContractWallet w1 theContract\n Trace.waitNSlots 1\n ContractInstanceState{instContractState=ResumableResult{_finalState}} <- Trace.getContractState hdl\n Log.logInfo @String \"Received contract state\"\n Log.logInfo @String $ \"Final state: \" <> show _finalState\n\n ]\n\nw1 :: EM.Wallet\nw1 = EM.Wallet 1\n\nw2 :: EM.Wallet\nw2 = EM.Wallet 2\n\ncheckpointContract :: Contract () Schema ContractError ()\ncheckpointContract = void $ do\n checkpoint $ do\n endpoint @\"1\" @Int\n endpoint @\"2\" @Int\n checkpoint $ do\n endpoint @\"1\" @Int\n endpoint @\"3\" @Int\n\nloopCheckpointContract :: Contract () Schema ContractError Int\nloopCheckpointContract = do\n -- repeatedly expose the \"1\" endpoint until we get a total\n -- value greater than 3.\n -- We can call \"1\" with different values to control whether\n -- the left or right branch is chosen.\n flip checkpointLoop (0 :: Int) $ \\counter -> do\n vl <- endpoint @\"1\" @Int\n let newVal = counter + vl\n if newVal > 3\n then pure (Left newVal)\n else pure (Right newVal)\n\nerrorContract :: Contract () Schema ContractError Int\nerrorContract = do\n catchError\n (endpoint @\"1\" @Int >> throwError (OtherError \"something went wrong\"))\n (\\_ -> do { checkpoint $ endpoint @\"2\" @Int; endpoint @\"3\" @Int })\n\nsomeAddress :: Address\nsomeAddress = Ledger.scriptAddress $\n Ledger.mkValidatorScript $$(PlutusTx.compile [|| \\(_ :: PlutusTx.BuiltinData) (_ :: PlutusTx.BuiltinData) (_ :: PlutusTx.BuiltinData) -> () ||])\n\ntype Schema =\n Endpoint \"1\" Int\n .\\\/ Endpoint \"2\" Int\n .\\\/ Endpoint \"3\" Int\n .\\\/ Endpoint \"4\" Int\n .\\\/ Endpoint \"ep\" ()\n .\\\/ Endpoint \"5\" [ActiveEndpoint]\n\ninitial :: _\ninitial = State.initialiseContract loopCheckpointContract\n\nupd :: _\nupd = State.insertAndUpdateContract loopCheckpointContract\n","avg_line_length":51.074906367,"max_line_length":217,"alphanum_fraction":0.582679475} {"size":15258,"ext":"hs","lang":"Haskell","max_stars_count":10.0,"content":"module Hydra.Adapters.TermSpec where\n\nimport Hydra.Adapter\nimport Hydra.Adapters.Term\nimport Hydra.Adapters.UtilsEtc\nimport Hydra.Basics\nimport Hydra.Core\nimport Hydra.CoreLanguage\nimport Hydra.Impl.Haskell.Dsl.CoreMeta\nimport Hydra.Impl.Haskell.Dsl.Terms as Terms\nimport Hydra.Impl.Haskell.Extras\nimport Hydra.Impl.Haskell.Meta\nimport Hydra.Steps\nimport qualified Hydra.Impl.Haskell.Dsl.Types as Types\n\nimport Hydra.TestData\nimport Hydra.TestUtils\nimport Hydra.ArbitraryCore (untyped)\n\nimport qualified Test.Hspec as H\nimport qualified Data.Map as M\nimport qualified Test.QuickCheck as QC\nimport qualified Data.Set as S\nimport qualified Data.Maybe as Y\n\n\nconstraintsAreAsExpected :: H.SpecWith ()\nconstraintsAreAsExpected = H.describe \"Verify that the language constraints include\/exclude the appropriate types\" $ do\n\n H.it \"int16 and int32 are supported in the test context\" $ do\n typeIsSupported (context [TypeVariantLiteral]) Types.int16 `H.shouldBe` True\n typeIsSupported (context [TypeVariantLiteral]) Types.int32 `H.shouldBe` True\n\n H.it \"int8 and bigint are unsupported in the test context\" $ do\n typeIsSupported (context [TypeVariantLiteral]) Types.int8 `H.shouldBe` False\n typeIsSupported (context [TypeVariantLiteral]) Types.bigint `H.shouldBe` False\n\n H.it \"Records are supported, but unions are not\" $ do\n typeIsSupported (context [TypeVariantLiteral, TypeVariantRecord]) latLonType `H.shouldBe` True\n typeIsSupported (context [TypeVariantLiteral, TypeVariantRecord]) stringOrIntType `H.shouldBe` False\n\n H.it \"Records are supported if and only if each of their fields are supported\" $ do\n typeIsSupported (context [TypeVariantLiteral, TypeVariantRecord])\n (Types.record [Types.field \"first\" Types.string, Types.field \"second\" Types.int16])\n `H.shouldBe` True\n typeIsSupported (context [TypeVariantLiteral, TypeVariantRecord])\n (Types.record [Types.field \"first\" Types.string, Types.field \"second\" Types.int8])\n `H.shouldBe` False\n\n H.it \"Lists are supported if the list element type is supported\" $ do\n typeIsSupported (context [TypeVariantLiteral, TypeVariantList]) listOfStringsType `H.shouldBe` True\n typeIsSupported (context [TypeVariantLiteral, TypeVariantList]) listOfListsOfStringsType `H.shouldBe` True\n typeIsSupported (context [TypeVariantLiteral, TypeVariantList]) listOfSetOfStringsType `H.shouldBe` False\n\n where\n context = languageConstraints . adapterContextTarget . termTestContext\n\nsupportedConstructorsAreUnchanged :: H.SpecWith ()\nsupportedConstructorsAreUnchanged = H.describe \"Verify that supported term constructors are unchanged\" $ do\n\n H.it \"Strings (and other supported literal values) pass through without change\" $\n QC.property $ \\b -> checkDataAdapter\n [TypeVariantLiteral]\n Types.string\n Types.string\n False\n (string b)\n (string b)\n\n H.it \"Lists (when supported) pass through without change\" $\n QC.property $ \\strings -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantList]\n listOfStringsType\n listOfStringsType\n False\n (list $ string <$> strings)\n (list $ string <$> strings)\n\n H.it \"Maps (when supported) pass through without change\" $\n QC.property $ \\keyvals -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantMap]\n mapOfStringsToIntsType\n mapOfStringsToIntsType\n False\n (makeMap keyvals)\n (makeMap keyvals)\n\n H.it \"Optionals (when supported) pass through without change\" $\n QC.property $ \\mi -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantOptional]\n optionalInt8Type\n optionalInt16Type\n False\n (optional $ int8 <$> mi)\n (optional $ int16 . fromIntegral <$> mi)\n\n H.it \"Records (when supported) pass through without change\" $\n QC.property $ \\a1 a2 -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantRecord]\n (Types.record [Types.field \"first\" Types.string, Types.field \"second\" Types.int8])\n (Types.record [Types.field \"first\" Types.string, Types.field \"second\" Types.int16])\n False\n (record [Field (FieldName \"first\") $ string a1, Field (FieldName \"second\") $ int8 a2])\n (record [Field (FieldName \"first\") $ string a1, Field (FieldName \"second\") $ int16 $ fromIntegral a2])\n\n H.it \"Unions (when supported) pass through without change\" $\n QC.property $ \\int -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantUnion]\n stringOrIntType\n stringOrIntType\n False\n (variant (FieldName \"right\") $ int32 int)\n (variant (FieldName \"right\") $ int32 int)\n\n H.it \"Sets (when supported) pass through without change\" $\n QC.property $ \\strings -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantSet]\n setOfStringsType\n setOfStringsType\n False\n (stringSet strings)\n (stringSet strings)\n\n H.it \"Element references (when supported) pass through without change\" $\n QC.property $ \\name -> checkDataAdapter\n [TypeVariantElement]\n int32ElementType\n int32ElementType\n False\n (element name)\n (element name)\n\n H.it \"CompareTo terms (when supported) pass through without change\" $\n QC.property $ \\s -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantFunction]\n compareStringsType\n compareStringsType\n False\n (compareTo $ string s)\n (compareTo $ string s)\n\n H.it \"Term terms (when supported) pass through without change\" $\n QC.property $ \\() -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantFunction, TypeVariantElement]\n int32ElementDataType\n int32ElementDataType\n False\n delta\n delta\n\n H.it \"Primitive function references (when supported) pass through without change\" $\n QC.property $ \\name -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantFunction]\n concatType\n concatType\n False\n (primitive name)\n (primitive name)\n\n H.it \"Projections (when supported) pass through without change\" $\n QC.property $ \\fname -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantFunction, TypeVariantRecord]\n exampleProjectionType\n exampleProjectionType\n False\n (projection fname)\n (projection fname)\n\n H.it \"Nominal types (when supported) pass through without change\" $\n QC.property $ \\s -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantNominal]\n stringAliasType\n stringAliasType\n False\n (string s)\n (string s)\n\nunsupportedConstructorsAreModified :: H.SpecWith ()\nunsupportedConstructorsAreModified = H.describe \"Verify that unsupported term constructors are changed in the expected ways\" $ do\n\n H.it \"Sets (when unsupported) become lists\" $\n QC.property $ \\strings -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantList]\n setOfStringsType\n listOfStringsType\n False\n (stringSet strings)\n (stringList $ S.toList strings)\n\n H.it \"Element references (when unsupported) become strings\" $\n QC.property $ \\name@(Name nm) -> checkDataAdapter\n [TypeVariantLiteral]\n int32ElementType\n Types.string\n False\n (element name)\n (string nm) -- Note: the element name is not dereferenced\n\n H.it \"CompareTo terms (when unsupported) become variant terms\" $\n QC.property $ \\s -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantUnion, TypeVariantRecord]\n compareStringsType\n (unionTypeForFunctions Types.string)\n False\n (compareTo $ string s)\n (nominalUnion testContext _Function $ Field (FieldName \"compareTo\") $ string s)\n\n H.it \"Data terms (when unsupported) become variant terms\" $\n QC.property $ \\() -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantUnion, TypeVariantRecord]\n int32ElementDataType\n (unionTypeForFunctions Types.string)\n False\n delta\n (nominalUnion testContext _Function $ Field (FieldName \"element\") unit)\n\n H.it \"Optionals (when unsupported) become lists\" $\n QC.property $ \\ms -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantList]\n (Types.optional Types.string)\n (Types.list Types.string)\n False\n (optional $ string <$> ms)\n (list $ Y.maybe [] (\\s -> [string s]) ms)\n\n H.it \"Primitive function references (when unsupported) become variant terms\" $\n QC.property $ \\name -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantUnion, TypeVariantRecord]\n concatType\n (unionTypeForFunctions Types.string)\n False\n (primitive name)\n (nominalUnion testContext _Function $ Field (FieldName \"primitive\") $ string $ unName name) -- Note: the function name is not dereferenced\n\n H.it \"Projections (when unsupported) become variant terms\" $\n QC.property $ \\fname -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantUnion, TypeVariantRecord]\n exampleProjectionType\n (unionTypeForFunctions testTypePerson)\n False\n (projection fname)\n (nominalUnion testContext _Function $ Field (FieldName \"record\") $ string $ unFieldName fname) -- Note: the field name is not dereferenced\n\n H.it \"Nominal types (when unsupported) are dereferenced\" $\n QC.property $ \\s -> checkDataAdapter\n [TypeVariantLiteral]\n stringAliasType\n Types.string {typeMeta = Meta $\n M.fromList [(metaDescription, Terms.string \"An alias for the string type\")]}\n False\n (string s)\n (string s)\n\n H.it \"Unions (when unsupported) become records\" $\n QC.property $ \\i -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantOptional, TypeVariantRecord]\n eitherStringOrInt8Type\n (Types.record [Types.field \"context\" Types.string, Types.field \"record\" (Types.record [\n Types.field \"left\" $ Types.optional Types.string,\n Types.field \"right\" $ Types.optional Types.int16])])\n False\n (union $ Field (FieldName \"right\") $ int8 i)\n (record [\n Field (FieldName \"context\") $ string $ unName untyped,\n Field (FieldName \"record\") (record [\n Field (FieldName \"left\") $ optional Nothing,\n Field (FieldName \"right\") $ optional $ Just $ int16 $ fromIntegral i])])\n\ntermsAreAdaptedRecursively :: H.SpecWith ()\ntermsAreAdaptedRecursively = H.describe \"Verify that the adapter descends into subterms and transforms them appropriately\" $ do\n\n H.it \"A list of int8's becomes a list of int32's\" $\n QC.property $ \\ints -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantList]\n listOfInt8sType\n listOfInt16sType\n False\n (list $ int8 <$> ints)\n (list $ int16 . fromIntegral <$> ints)\n\n H.it \"A list of sets of strings becomes a list of lists of strings\" $\n QC.property $ \\lists -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantList]\n listOfSetOfStringsType\n listOfListsOfStringsType\n False\n (list $ (\\l -> set $ S.fromList $ string <$> l) <$> lists)\n (list $ (\\l -> list $ string <$> S.toList (S.fromList l)) <$> lists)\n\n H.it \"A list of sets of element references becomes a list of lists of strings\" $\n QC.property $ \\names -> checkDataAdapter\n [TypeVariantLiteral, TypeVariantList]\n listOfSetOfInt32ElementReferencesType\n listOfListsOfStringsType\n False\n (list $ (\\l -> set $ S.fromList $ element <$> l) <$> names)\n (list $ (\\l -> list $ string <$> S.toList (S.fromList $ unName <$> l)) <$> names)\n\nroundTripsPreserveSelectedTypes :: H.SpecWith ()\nroundTripsPreserveSelectedTypes = H.describe \"Verify that the adapter is information preserving, i.e. that round-trips are no-ops\" $ do\n\n H.it \"Check strings (pass-through)\" $\n QC.property $ \\s -> roundTripIsNoop Types.string (string s)\n\n H.it \"Check lists (pass-through)\" $\n QC.property $ \\strings -> roundTripIsNoop listOfStringsType (list $ string <$> strings)\n\n H.it \"Check sets (which map to lists)\" $\n QC.property $ \\strings -> roundTripIsNoop setOfStringsType (stringSet strings)\n\n H.it \"Check element references (which map to strings)\" $\n QC.property $ \\name -> roundTripIsNoop int32ElementType (element name)\n\n H.it \"Check compareTo terms (which map to variants)\" $\n QC.property $ \\s -> roundTripIsNoop compareStringsType (compareTo $ string s)\n\n H.it \"Check data terms (which map to variants)\" $\n roundTripIsNoop int32ElementDataType delta `H.shouldBe` True\n\n H.it \"Check primitive function references (which map to variants)\" $\n QC.property $ \\name -> roundTripIsNoop concatType (primitive name)\n\n H.it \"Check projection terms (which map to variants)\" $\n QC.property $ \\fname -> roundTripIsNoop exampleProjectionType (projection fname)\n\n H.it \"Check nominally typed terms (which pass through as instances of the aliased type)\" $\n QC.property $ \\s -> roundTripIsNoop stringAliasType (string s)\n\nroundTripsPreserveArbitraryTypes :: H.SpecWith ()\nroundTripsPreserveArbitraryTypes = H.describe \"Verify that the adapter is information preserving for arbitrary typed terms\" $ do\n\n H.it \"Check arbitrary type\/term pairs\" $\n QC.property $ \\(TypedTerm typ term) -> roundTripIsNoop typ term\n\nfieldAdaptersAreAsExpected :: H.SpecWith ()\nfieldAdaptersAreAsExpected = H.describe \"Check that field adapters are as expected\" $ do\n\n H.it \"An int8 field becomes an int16 field\" $\n QC.property $ \\i -> checkFieldAdapter\n [TypeVariantLiteral, TypeVariantRecord]\n (Types.field \"second\" Types.int8)\n (Types.field \"second\" Types.int16)\n False\n (Field (FieldName \"second\") $ int8 i)\n (Field (FieldName \"second\") $ int16 $ fromIntegral i)\n\nroundTripIsNoop :: Type Meta -> Term Meta -> Bool\nroundTripIsNoop typ term = (step stepOut term >>= step stepIn) == pure term\n where\n step = adapt typ\n\n -- Use a YAML-like language (but supporting unions) as the default target language\n testLanguage = Language (LanguageName \"hydra\/test\") $ LanguageConstraints {\n languageConstraintsEliminationVariants = S.empty, -- S.fromList eliminationVariants,\n languageConstraintsLiteralVariants = S.fromList [\n LiteralVariantBoolean, LiteralVariantFloat, LiteralVariantInteger, LiteralVariantString],\n languageConstraintsFloatTypes = S.fromList [FloatTypeBigfloat],\n languageConstraintsFunctionVariants = S.empty,\n languageConstraintsIntegerTypes = S.fromList [IntegerTypeBigint],\n languageConstraintsTermVariants = S.fromList termVariants,\n languageConstraintsTypeVariants = S.fromList [\n TypeVariantLiteral, TypeVariantList, TypeVariantMap, TypeVariantRecord, TypeVariantUnion],\n languageConstraintsTypes = \\typ -> case typeExpr typ of\n TypeExprOptional (Type (TypeExprOptional _) _) -> False\n _ -> True }\n\n transContext = AdapterContext testContext hydraCoreLanguage testLanguage\n\n -- Note: in a real application, you wouldn't create the adapter just to use it once;\n -- it should be created once, then applied to many terms.\n adapt typ dir term = do\n ad <- qualifiedToResult $ termAdapter transContext typ\n dir (adapterStep ad) term\n\nspec :: H.Spec\nspec = do\n constraintsAreAsExpected\n supportedConstructorsAreUnchanged\n unsupportedConstructorsAreModified\n termsAreAdaptedRecursively\n roundTripsPreserveSelectedTypes\n roundTripsPreserveArbitraryTypes\n fieldAdaptersAreAsExpected\n","avg_line_length":39.734375,"max_line_length":144,"alphanum_fraction":0.7109057544} {"size":17027,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-|\n Copyright : (C) 2019, Google Inc.\n License : BSD2 (see the file LICENSE)\n Maintainer : Christiaan Baaij \n-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-} -- needed for constraint on the Fixed instance\n{-# LANGUAGE ViewPatterns #-}\n\n#if __GLASGOW_HASKELL__ < 806\n{-# OPTIONS_GHC -Wwarn=unused-pattern-binds #-}\n#endif\n\nmodule Clash.Class.AutoReg.Internal\n ( AutoReg (..)\n , deriveAutoReg\n , deriveAutoRegTuples\n )\n where\n\nimport Data.List (nub,zipWith4)\nimport Data.Maybe (fromMaybe,isJust)\n\nimport GHC.Stack (HasCallStack)\nimport GHC.TypeNats (KnownNat,Nat,type (+))\nimport Clash.Explicit.Signal\nimport Clash.Promoted.Nat\nimport Clash.Magic\nimport Clash.XException (NFDataX, deepErrorX)\n\nimport Clash.Sized.BitVector\nimport Clash.Sized.Fixed\nimport Clash.Sized.Index\nimport Clash.Sized.RTree\nimport Clash.Sized.Signed\nimport Clash.Sized.Unsigned\nimport Clash.Sized.Vector (Vec, lazyV, smap)\n\nimport Data.Int\nimport Data.Word\nimport Foreign.C.Types (CUShort)\nimport Numeric.Half (Half)\n\nimport Language.Haskell.TH.Datatype\nimport Language.Haskell.TH.Syntax\nimport Language.Haskell.TH.Lib\nimport Language.Haskell.TH.Ppr\n\nimport Control.Lens.Internal.TH (bndrName, conAppsT)\n\n-- $setup\n-- >>> import Data.Maybe\n-- >>> import Clash.Class.BitPack (pack)\n-- >>> :set -fplugin GHC.TypeLits.Normalise\n-- >>> :set -fplugin GHC.TypeLits.KnownNat.Solver\n\n-- | 'autoReg' is a \"smart\" version of 'register'. It does two things:\n--\n-- 1. It splits product types over their fields. For example, given a 3-tuple,\n-- the corresponding HDL will end up with three instances of a register (or\n-- more if the three fields can be split up similarly).\n--\n-- 2. Given a data type where a constructor indicates (parts) of the data will\n-- (not) be updated a given cycle, it will split the data in two parts. The\n-- first part will contain the \"always interesting\" parts (the constructor\n-- bits). The second holds the \"potentially uninteresting\" data (the rest).\n-- Both parts will be stored in separate registers. The register holding the\n-- \"potentially uninteresting\" part will only be enabled if the constructor\n-- bits indicate they're interesting.\n--\n-- The most important example of this is \"Maybe\". Consider \"Maybe Byte)\";\n-- when viewed as bits, a 'Nothing' would look like:\n--\n-- >>> pack @(Maybe (Signed 16)) Nothing\n-- 0_...._...._...._....\n--\n-- and 'Just'\n--\n-- >>> pack @(Maybe (Signed 16)) (Just 3)\n-- 1_0000_0000_0000_0011\n--\n-- In the first case, Nothing, we don't particularly care about updating the\n-- register holding the \"Signed 16\" field, as they'll be unknown anyway. We\n-- can therefore deassert its enable line.\n--\n-- Making Clash lay it out like this increases the chances of synthesis tools\n-- clock gating the registers, saving energy.\n--\n-- This version of 'autoReg' will split the given data type up recursively. For\n-- example, given \"a :: Maybe (Maybe Int, Maybe Int)\", a total of five registers\n-- will be rendered. Both the \"interesting\" and \"uninteresting\" enable lines of\n-- the inner Maybe types will be controlled by the outer one, in addition to\n-- the inner parts controlling their \"uninteresting\" parts as described in (2).\n--\n-- The default implementation is just 'register'. If you don't need or want\n-- the special features of \"AutoReg\", you can use that by writing an empty instance.\n--\n-- > data MyDataType = ...\n-- > instance AutoReg MyDataType\n--\n-- If you have a product type you can use 'deriveAutoReg' to derive an instance.\n--\n-- \"Clash.Prelude\" exports an implicit version of this: 'Clash.Prelude.autoReg'\nclass NFDataX a => AutoReg a where\n autoReg\n :: (HasCallStack, KnownDomain dom)\n => Clock dom -> Reset dom -> Enable dom\n -> a -- ^ Reset value\n -> Signal dom a\n -> Signal dom a\n autoReg = register\n\ninstance AutoReg ()\ninstance AutoReg Bool\n\ninstance AutoReg Double\ninstance AutoReg Float\ninstance AutoReg CUShort\ninstance AutoReg Half\n\ninstance AutoReg Char\n\ninstance AutoReg Integer\ninstance AutoReg Int\ninstance AutoReg Int8\ninstance AutoReg Int16\ninstance AutoReg Int32\ninstance AutoReg Int64\ninstance AutoReg Word\ninstance AutoReg Word8\ninstance AutoReg Word16\ninstance AutoReg Word32\ninstance AutoReg Word64\n\ninstance AutoReg Bit\ninstance AutoReg (BitVector n)\ninstance AutoReg (Signed n)\ninstance AutoReg (Unsigned n)\ninstance AutoReg (Index n)\ninstance NFDataX (rep (int + frac)) => AutoReg (Fixed rep int frac)\n\ninstance AutoReg a => AutoReg (Maybe a) where\n autoReg clk rst en initVal input =\n createMaybe <$> tagR <*> valR\n where\n tag = isJust <$> input\n tagInit = isJust initVal\n tagR = register clk rst en tagInit tag\n\n val = fromMaybe (deepErrorX \"autoReg'.val\") <$> input\n valInit = fromMaybe (deepErrorX \"autoReg'.valInit\") initVal\n\n valR = autoReg clk rst (enable en tag) valInit val\n\n createMaybe t v = case t of\n True -> Just v\n False -> Nothing\n\ninstance (KnownNat n, AutoReg a) => AutoReg (Vec n a) where\n autoReg\n :: forall dom. (HasCallStack, KnownDomain dom)\n => Clock dom -> Reset dom -> Enable dom\n -> Vec n a -- ^ Reset value\n -> Signal dom (Vec n a)\n -> Signal dom (Vec n a)\n autoReg clk rst en initVal xs =\n bundle $ smap go (lazyV initVal) <*> unbundle xs\n where\n go :: forall (i :: Nat). SNat i -> a -> Signal dom a -> Signal dom a\n go SNat = suffixNameFromNat @i . autoReg clk rst en\n\ninstance (KnownNat d, AutoReg a) => AutoReg (RTree d a) where\n autoReg clk rst en initVal xs =\n bundle $ (autoReg clk rst en) <$> lazyT initVal <*> unbundle xs\n\n\n-- | Decompose an applied type into its individual components. For example, this:\n--\n-- @\n-- Either Int Char\n-- @\n--\n-- would be unfolded to this:\n--\n-- @\n-- ('ConT' ''Either, ['ConT' ''Int, 'ConT' ''Char])\n-- @\n--\n-- This function ignores explicit parentheses and visible kind applications.\n--\n-- NOTE: Copied from \"Control.Lens.Internal.TH\".\n-- TODO: Remove this function. Can be removed once we can upgrade to lens 4.18.\n-- TODO: This is currently difficult due to issue with nix.\nunfoldType :: Type -> (Type, [Type])\nunfoldType = go []\n where\n go :: [Type] -> Type -> (Type, [Type])\n go acc (ForallT _ _ ty) = go acc ty\n go acc (AppT ty1 ty2) = go (ty2:acc) ty1\n go acc (SigT ty _) = go acc ty\n#if MIN_VERSION_template_haskell(2,11,0)\n go acc (ParensT ty) = go acc ty\n#endif\n#if MIN_VERSION_template_haskell(2,15,0)\n go acc (AppKindT ty _) = go acc ty\n#endif\n go acc ty = (ty, acc)\n\n-- | Automatically derives an 'AutoReg' instance for a product type\n--\n-- Usage:\n--\n-- > data Pair a b = MkPair { getA :: a, getB :: b } deriving (Generic, NFDataX)\n-- > data Tup3 a b c = MkTup3 { getAB :: Pair a b, getC :: c } deriving (Generic, NFDataX)\n-- > deriveAutoReg ''Pair\n-- > deriveAutoReg ''Tup3\n--\n-- __NB__: Because of the way template haskell works the order here matters,\n-- if you try to @deriveAutoReg ''Tup3@ before @Pair@ it will complain\n-- about missing an @instance AutoReg (Pair a b)@.\nderiveAutoReg :: Name -> DecsQ\nderiveAutoReg tyNm = do\n tyInfo <- reifyDatatype tyNm\n case datatypeCons tyInfo of\n [] -> fail \"Can't deriveAutoReg for empty types\"\n [conInfo] -> deriveAutoRegProduct tyInfo conInfo\n _ -> fail \"Can't deriveAutoReg for sum types\"\n\n\n\n{-\nFor a type like:\n data Product a b .. = MkProduct { getA :: a, getB :: b, .. }\nThis generates the following instance:\n\ninstance (AutoReg a, AutoReg b, ..) => AutoReg (Product a b ..) where\n autoReg clk rst en initVal input =\n MkProduct <$> sig0 <*> sig1 ...\n where\n field0 = (\\(MkProduct x _ ...) -> x) <$> input\n field1 = (\\(MkProduct _ x ...) -> x) <$> input\n ...\n MkProduct initVal0 initVal1 ... = initVal\n sig0 = suffixName @\"getA\" autoReg clk rst en initVal0 field0\n sig1 = suffixName @\"getB\" autoReg clk rst en initVal1 field1\n ...\n-}\nderiveAutoRegProduct :: DatatypeInfo -> ConstructorInfo -> DecsQ\nderiveAutoRegProduct tyInfo conInfo = go (constructorName conInfo) fieldInfos\n where\n tyNm = datatypeName tyInfo\n tyVarBndrs = datatypeVars tyInfo\n\n#if MIN_VERSION_th_abstraction(0,3,0)\n toTyVar = VarT . bndrName\n#else\n toTyVar t = case t of\n VarT _ -> t\n SigT t' _ -> toTyVar t'\n _ -> error \"deriveAutoRegProduct.toTv\"\n#endif\n\n tyVars = map toTyVar tyVarBndrs\n ty = conAppsT tyNm tyVars\n\n fieldInfos =\n zip fieldNames (constructorFields conInfo)\n where\n fieldNames =\n case constructorVariant conInfo of\n RecordConstructor nms -> map Just nms\n _ -> repeat Nothing\n\n go :: Name -> [(Maybe Name,Type)] -> Q [Dec]\n go dcNm fields = do\n args <- mapM newName [\"clk\", \"rst\", \"en\", \"initVal\", \"input\"]\n let\n [clkE, rstE, enE, initValE, inputE] = map varE args\n argsP = map varP args\n fieldNames = map fst fields\n\n field :: Name -> Int -> DecQ\n field nm nr =\n valD (varP nm) (normalB [| $fieldSel <$> $inputE |]) []\n where\n fieldSel = do\n xNm <- newName \"x\"\n let fieldP = [ if nr == n then varP xNm else wildP\n | (n,_) <- zip [0..] fields]\n lamE [conP dcNm fieldP] (varE xNm) -- \"\\(Dc _ _ .. x _ ..) -> x\"\n\n parts <- generateNames \"field\" fields\n fieldDecls <- sequence $ zipWith field parts [0..]\n sigs <- generateNames \"sig\" fields\n initVals <- generateNames \"initVal\" fields\n let initPat = conP dcNm (map varP initVals)\n initDecl <- valD initPat (normalB initValE) []\n\n let\n genAutoRegDecl :: PatQ -> ExpQ -> ExpQ -> Maybe Name -> DecsQ\n genAutoRegDecl s v i nameM =\n [d| $s = $nameMe autoReg $clkE $rstE $enE $i $v |]\n where\n nameMe = case nameM of\n Nothing -> [| id |]\n Just nm -> let nmSym = litT $ strTyLit (nameBase nm)\n in [| suffixName @($nmSym) |]\n\n partDecls <- concat <$> (sequence $ zipWith4 genAutoRegDecl\n (varP <$> sigs)\n (varE <$> parts)\n (varE <$> initVals)\n (fieldNames)\n )\n let\n decls :: [DecQ]\n decls = map pure (initDecl : fieldDecls ++ partDecls)\n tyConE = conE dcNm\n body =\n case map varE sigs of\n (sig0:rest) -> foldl\n (\\acc sigN -> [| $acc <*> $sigN |])\n [| $tyConE <$> $sig0 |]\n rest\n [] -> [| $tyConE |]\n\n autoRegDec <- funD 'autoReg [clause argsP (normalB body) decls]\n ctx <- calculateRequiredContext conInfo\n return [InstanceD Nothing ctx (AppT (ConT ''AutoReg) ty) [autoRegDec]]\n\n-- Calculate the required constraint to call autoReg on all the fields of a\n-- given constructor\ncalculateRequiredContext :: ConstructorInfo -> Q Cxt\ncalculateRequiredContext conInfo = do\n let fieldTys = constructorFields conInfo\n wantedInstances <- mapM (\\ty -> constraintsWantedFor ''AutoReg [ty]) (nub fieldTys)\n return $ nub (concat wantedInstances)\n\nconstraintsWantedFor :: Name -> [Type] -> Q Cxt\nconstraintsWantedFor clsNm tys\n | show clsNm == \"GHC.TypeNats.KnownNat\" = do\n -- KnownNat is special, you can't just lookup instances with reifyInstances.\n -- So we just pass KnownNat constraints.\n -- This will most likely require UndecidableInstances.\n return [conAppsT clsNm tys]\n\nconstraintsWantedFor clsNm [ty] = case ty of\n VarT _ -> return [AppT (ConT clsNm) ty]\n ConT _ -> return []\n _ -> do\n insts <- reifyInstances clsNm [ty]\n case insts of\n [InstanceD _ cxtInst (AppT autoRegCls instTy) _]\n | autoRegCls == ConT clsNm -> do\n let substs = findTyVarSubsts instTy ty\n cxt2 = map (applyTyVarSubsts substs) cxtInst\n okCxt = filter isOk cxt2\n recurseCxt = filter needRecurse cxt2\n recursed <- mapM recurse recurseCxt\n return (okCxt ++ concat recursed)\n [] -> fail $ \"Missing instance \" ++ show clsNm ++ \" (\" ++ pprint ty ++ \")\"\n (_:_:_) -> fail $ \"There are multiple \" ++ show clsNm ++ \" instances for \"\n ++ pprint ty ++ \":\\n\" ++ pprint insts\n _ -> fail $ \"Got unexpected instance: \" ++ pprint insts\n where\n isOk :: Type -> Bool\n isOk (unfoldType -> (_cls,tys)) =\n case tys of\n [VarT _] -> True\n [_] -> False\n _ -> True -- see [NOTE: MultiParamTypeClasses]\n needRecurse :: Type -> Bool\n needRecurse (unfoldType -> (cls,tys)) =\n case tys of\n [VarT _] -> False\n [ConT _] -> False -- we can just drop constraints like: \"AutoReg Bool => ...\"\n [AppT _ _] -> True\n [_] -> error ( \"Error while deriveAutoReg: don't know how to handle: \"\n ++ pprint cls ++ \" (\" ++ pprint tys ++ \")\" )\n _ -> False -- see [NOTE: MultiParamTypeClasses]\n\n recurse :: Type -> Q Cxt\n recurse (unfoldType -> (ConT cls,tys)) = constraintsWantedFor cls tys\n recurse t =\n fail (\"Expected a class applied to some arguments but got \" ++ pprint t)\n\nconstraintsWantedFor clsNm tys =\n return [conAppsT clsNm tys] -- see [NOTE: MultiParamTypeClasses]\n\n-- [NOTE: MultiParamTypeClasses]\n-- The constraint calculation code doesn't handle MultiParamTypeClasses\n-- \"properly\", but it will try to pass them on, so the resulting instance should\n-- still compile with UndecidableInstances enabled.\n\n\n-- | Find tyVar substitutions between a general type and a second possibly less\n-- general type. For example:\n--\n-- @\n-- findTyVarSubsts \"Either a b\" \"Either c [Bool]\"\n-- == \"[(a,c), (b,[Bool])]\"\n-- @\nfindTyVarSubsts :: Type -> Type -> [(Name,Type)]\nfindTyVarSubsts = go\n where\n go ty1 ty2 = case (ty1,ty2) of\n (VarT nm1 , VarT nm2) | nm1 == nm2 -> []\n (VarT nm , t) -> [(nm,t)]\n (ConT _ , ConT _) -> []\n (AppT x1 y1 , AppT x2 y2) -> go x1 x2 ++ go y1 y2\n (SigT t1 k1 , SigT t2 k2) -> go t1 t2 ++ go k1 k2\n (InfixT x1 _ y1 , InfixT x2 _ y2) -> go x1 x2 ++ go y1 y2\n (UInfixT x1 _ y1, UInfixT x2 _ y2) -> go x1 x2 ++ go y1 y2\n (ParensT x1 , ParensT x2) -> go x1 x2\n\n#if __GLASGOW_HASKELL__ >= 808\n (AppKindT t1 k1 , AppKindT t2 k2) -> go t1 t2 ++ go k1 k2\n (ImplicitParamT _ x1, ImplicitParamT _ x2) -> go x1 x2\n#endif\n\n (PromotedT _ , PromotedT _ ) -> []\n (TupleT _ , TupleT _ ) -> []\n (UnboxedTupleT _ , UnboxedTupleT _ ) -> []\n (UnboxedSumT _ , UnboxedSumT _ ) -> []\n (ArrowT , ArrowT ) -> []\n (EqualityT , EqualityT ) -> []\n (ListT , ListT ) -> []\n (PromotedTupleT _ , PromotedTupleT _ ) -> []\n (PromotedNilT , PromotedNilT ) -> []\n (PromotedConsT , PromotedConsT ) -> []\n (StarT , StarT ) -> []\n (ConstraintT , ConstraintT ) -> []\n (LitT _ , LitT _ ) -> []\n (WildCardT , WildCardT ) -> []\n _ -> error $ unlines [ \"findTyVarSubsts: Unexpected types\"\n , \"ty1:\", pprint ty1,\"ty2:\", pprint ty2]\n\napplyTyVarSubsts :: [(Name,Type)] -> Type -> Type\napplyTyVarSubsts substs ty = go ty\n where\n go ty' = case ty' of\n VarT n -> case lookup n substs of\n Nothing -> ty'\n Just m -> m\n ConT _ -> ty'\n AppT ty1 ty2 -> AppT (go ty1) (go ty2)\n _ -> error $ \"TODO applyTyVarSubsts: \" ++ show ty'\n\n\n-- | Generate a list of fresh Name's:\n-- prefix0_.., prefix1_.., prefix2_.., ..\ngenerateNames :: String -> [a] -> Q [Name]\ngenerateNames prefix xs =\n sequence (zipWith (\\n _ -> newName $ prefix ++ show @Int n) [0..] xs)\n\nderiveAutoRegTuples :: [Int] -> DecsQ\nderiveAutoRegTuples xs = concat <$> mapM deriveAutoRegTuple xs\n\nderiveAutoRegTuple :: Int -> DecsQ\nderiveAutoRegTuple n\n | n < 2 = fail $ \"deriveAutoRegTuple doesn't work for \" ++ show n ++ \"-tuples\"\n | otherwise = deriveAutoReg tupN\n where\n tupN = mkName $ \"(\" ++ replicate (n-1) ',' ++ \")\"\n","avg_line_length":35.9219409283,"max_line_length":90,"alphanum_fraction":0.6019850825} {"size":271,"ext":"hs","lang":"Haskell","max_stars_count":38.0,"content":"{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\n-- Trac #3406\r\n-- A pattern signature that discards the bound variables\r\n\r\nmodule T3406 where\r\n\r\ntype ItemColID a b = Int -- Discards a,b\r\n\r\nget :: ItemColID a b -> a -> ItemColID a b\r\nget (x :: ItemColID a b) = x :: ItemColID a b","avg_line_length":24.6363636364,"max_line_length":57,"alphanum_fraction":0.6568265683} {"size":752,"ext":"hs","lang":"Haskell","max_stars_count":2.0,"content":"module Kata.SnapperSpec where\n\nimport Test.Hspec\nimport Kata.Snapper (isLightOn, Snapper(..), snapperCLI, snapAll)\n\n\nspec :: Spec\nspec = do\n\n describe \"Is ligth on?\" $ do\n\n it \"1 0 -> False\" $ do\n isLightOn (snapAll 1 0) `shouldBe` False\n \n it \"1 1 -> True\" $ do\n isLightOn (snapAll 1 1) `shouldBe` True\n \n it \"4 0 -> False\" $ do\n isLightOn (snapAll 4 0) `shouldBe` False\n\n it \"4 47 -> True\" $ do\n isLightOn (snapAll 4 47) `shouldBe` True\n\n\n describe \"IO\" $ do\n\n it \"sample 1\" $ do\n\n snapperCLI [\n \"1 0\",\n \"1 1\",\n \"4 0\",\n \"4 47\"\n ]\n `shouldBe` [\n \"Case #1: OFF\",\n \"Case #2: ON\",\n \"Case #3: OFF\",\n \"Case #4: ON\"\n ]\n\n\n","avg_line_length":17.488372093,"max_line_length":65,"alphanum_fraction":0.4920212766} {"size":445,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module RatAngle where\n\nimport Data.Ratio\n\nimport Data.Finite\nimport Linear.V2\n\ndata RatAngle int = RatAngle (Finite 4) (Ratio int)\n deriving (Eq, Ord, Show)\n\natan2r :: Integral int => V2 int -> RatAngle int\natan2r (V2 x y)\n | x > 0, y >= 0\n = RatAngle 0 (y % x)\n | x <= 0, y > 0\n = RatAngle 1 (-x % y)\n | x < 0, y <= 0\n = RatAngle 2 (y % x)\n | x >= 0, y < 0\n = RatAngle 3 (-x % y)\n | otherwise\n = error \"atan2r: input must be nonzero\"","avg_line_length":20.2272727273,"max_line_length":51,"alphanum_fraction":0.5842696629} {"size":5512,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE LambdaCase #-}\nmodule TestDetailed where\nimport Control.Exception\nimport Data.Text qualified as T\nimport GHC.IO.Handle\nimport System.Directory\nimport System.Environment\nimport System.Exit\nimport System.IO\nimport System.Process\n\nimport Distribution.TestSuite\n\nimport MAlonzo.Code.Main qualified as M\nimport MAlonzo.Code.Raw qualified as R\n\nimport Data.ByteString.Lazy.Char8 qualified as C\nimport System.IO.Extra\n\n-- this function is based on this stackoverflow answer:\n-- https:\/\/stackoverflow.com\/a\/9664017\n\ncatchOutput :: IO () -> IO String\ncatchOutput act = do\n tmpD <- getTemporaryDirectory\n (tmpFP, tmpH) <- openTempFile tmpD \"stdout\"\n stdoutDup <- hDuplicate stdout\n hDuplicateTo tmpH stdout\n hClose tmpH\n act\n hDuplicateTo stdoutDup stdout\n str <- readFile tmpFP\n removeFile tmpFP\n return str\n\n-- compare the output of plc vs plc-agda in its default (typed) mode\ncompareResult :: (C.ByteString -> C.ByteString -> Bool) -> String -> String -> IO Progress\ncompareResult eq mode test = withTempFile $ \\tmp -> do\n example <- readProcess \"plc\" [\"example\", \"-s\",test] []\n writeFile tmp example\n putStrLn $ \"test: \" ++ test\n plcOutput <- readProcess \"plc\" [mode, \"--input\",tmp] []\n plcAgdaOutput <- catchOutput $ catch\n (withArgs [mode,\"--file\",tmp] M.main)\n (\\case\n ExitFailure _ -> exitFailure\n ExitSuccess -> return ()) -- does this ever happen?\n return $ Finished $ if eq (C.pack plcOutput) (C.pack plcAgdaOutput) then Pass else Fail $ \"plc: '\" ++ plcOutput ++ \"' \" ++ \"plc-agda: '\" ++ plcAgdaOutput ++ \"'\"\n\n-- compare the output of uplc vs plc-agda in untyped mode\ncompareResultU :: (C.ByteString -> C.ByteString -> Bool) -> String -> IO Progress\ncompareResultU eq test = withTempFile $ \\tmp -> do\n example <- readProcess \"uplc\" [\"example\",\"-s\",test] []\n writeFile tmp example\n putStrLn $ \"test: \" ++ test\n plcOutput <- readProcess \"uplc\" [\"evaluate\", \"--input\",tmp] []\n plcAgdaOutput <- catchOutput $ catch\n (withArgs [\"evaluate\",\"-mU\",\"--file\",tmp] M.main)\n (\\case\n ExitFailure _ -> exitFailure\n ExitSuccess -> return ())\n return $ Finished $ if eq (C.pack plcOutput) (C.pack plcAgdaOutput) then Pass else Fail $ \"plc: '\" ++ plcOutput ++ \"' \" ++ \"plc-agda: '\" ++ plcAgdaOutput ++ \"'\"\n-- compare the results of two different (typed) plc-agda modes\ncompareResultMode :: String -> String -> (C.ByteString -> C.ByteString -> Bool) -> String -> IO Progress\ncompareResultMode mode1 mode2 eq test = withTempFile $ \\tmp -> do\n example <- readProcess \"plc\" [\"example\",\"-s\",test] []\n writeFile tmp example\n putStrLn $ \"test: \" ++ test\n plcAgdaOutput1 <- catchOutput $ catch\n (withArgs [\"evaluate\",\"--file\",tmp,\"--mode\",mode1] M.main)\n (\\case\n ExitFailure _ -> exitFailure\n ExitSuccess -> return ())\n plcAgdaOutput2 <- catchOutput $ catch\n (withArgs [\"evaluate\",\"--file\",tmp,\"--mode\",mode2] M.main)\n (\\case\n ExitFailure _ -> exitFailure\n ExitSuccess -> return ())\n return $ Finished $ if eq (C.pack plcAgdaOutput1) (C.pack plcAgdaOutput2) then Pass else Fail $ mode1 ++ \": '\" ++ plcAgdaOutput1 ++ \"' \" ++ mode2 ++ \": '\" ++ plcAgdaOutput2 ++ \"'\" ++ \" === \"++ T.unpack (M.blah (C.pack plcAgdaOutput1) (C.pack plcAgdaOutput2))\n\ntestNames = [\"succInteger\"\n ,\"unitval\"\n ,\"true\"\n ,\"false\"\n ,\"churchZero\"\n ,\"churchSucc\"\n ,\"overapplication\"\n ,\"factorial\"\n ,\"fibonacci\"\n ,\"NatRoundTrip\"\n ,\"ScottListSum\"\n ,\"IfIntegers\"\n ,\"ApplyAdd1\"\n ,\"ApplyAdd2\"\n ]\n-- test plc against plc-agda\nmkTest :: (C.ByteString -> C.ByteString -> Bool) -> String -> String -> TestInstance\nmkTest eq mode test = TestInstance\n { run = compareResult eq mode test\n , name = mode ++ \" \" ++ test\n , tags = []\n , options = []\n , setOption = \\_ _ -> Right (mkTest eq mode test)\n }\n\n-- test uplc against plc-agda untyped mode\nmkTestU :: (C.ByteString -> C.ByteString -> Bool) -> String -> TestInstance\nmkTestU eq test = TestInstance\n { run = compareResultU eq test\n , name = \"evaluate\" ++ \" \" ++ test\n , tags = []\n , options = []\n , setOption = \\_ _ -> Right (mkTestU eq test)\n }\n\n-- test different (typed) plc-agda modes against each other\nmkTestMode :: String -> String -> (C.ByteString -> C.ByteString -> Bool) -> String -> TestInstance\nmkTestMode mode1 mode2 eq test = TestInstance\n { run = compareResultMode mode1 mode2 eq test\n , name = mode1 ++ \" \" ++ mode2 ++ \" \" ++ test\n , tags = []\n , options = []\n , setOption = \\_ _ -> Right (mkTestMode mode1 mode2 eq test)\n }\n\ntests :: IO [Test]\ntests = do\n return $ map Test $\n map (mkTest M.alphaTm \"evaluate\") testNames\n ++\n\n{- -- tests against extrinisically typed interpreter disabled\nmap (mkTestMode \"L\" \"TL\" M.alphaTm) testNames\n ++\n map (mkTestMode \"L\" \"CK\" M.alphaTm) testNames\n ++\n map (mkTestMode \"CK\" \"TCK\" M.alphaTm) testNames\n ++\n-}\n map (mkTestMode \"TL\" \"TCK\" M.alphaTm) testNames\n ++\n map (mkTestMode \"TCK\" \"TCEK\" M.alphaTm) testNames\n ++\n map (mkTest M.alphaTy \"typecheck\") testNames\n ++\n map (mkTestU M.alphaU) testNames\n where\n fails = TestInstance\n { run = return $ Finished $ Fail \"Always fails!\"\n , name = \"fails\"\n , tags = []\n , options = []\n , setOption = \\_ _ -> Right fails\n }\n","avg_line_length":35.5612903226,"max_line_length":260,"alphanum_fraction":0.6157474601} {"size":133,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Telegram.BotModel where\n\ntype LastUpdateId = Int\n\ntype ChatId = Int\n\nbotUri :: String\nbotUri = \"https:\/\/api.telegram.org\/bot\"\n","avg_line_length":14.7777777778,"max_line_length":39,"alphanum_fraction":0.7443609023} {"size":18793,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule Test.Sophie.Spec.Ledger.BenchmarkFunctions\n ( ledgerSpendOneUTxO,\n ledgerSpendOneGivenUTxO,\n initUTxO, -- How to precompute env for the UTxO transactions\n ledgerEnv,\n ledgerRegisterStakeKeys,\n ledgerDeRegisterStakeKeys,\n ledgerRewardWithdrawals,\n ledgerStateWithNregisteredKeys, -- How to precompute env for the StakeKey transactions\n ledgerRegisterStakePools,\n ledgerReRegisterStakePools,\n ledgerRetireStakePools,\n ledgerStateWithNregisteredPools, -- How to precompute env for the Stake Pool transactions\n ledgerDelegateManyKeysOnePool,\n ledgerStateWithNkeysMpools, -- How to precompute env for the Stake Delegation transactions\n B, -- Era instance for Benchmarking\n B_Crypto, -- Crypto instance for Benchmarking\n )\nwhere\n\n-- Cypto and Era stuff\n\nimport Bcc.Crypto.Hash.Blake2b (Blake2b_256)\nimport Bcc.Ledger.Address (Addr)\nimport Bcc.Ledger.BaseTypes\n ( Network (..),\n StrictMaybe (..),\n )\nimport Bcc.Ledger.Coin (Coin (..))\nimport qualified Bcc.Ledger.Core as Core\nimport Bcc.Ledger.Credential (Credential (..))\nimport Bcc.Ledger.Crypto (Crypto (..))\nimport Bcc.Ledger.Keys\n ( Hash,\n KeyHash,\n KeyPair (..),\n KeyRole (..),\n VerKeyVRF,\n asWitness,\n hashKey,\n hashVerKeyVRF,\n vKey,\n )\nimport Bcc.Ledger.SafeHash (hashAnnotated)\nimport Bcc.Ledger.Sophie (SophieEra)\nimport Bcc.Ledger.Slot (EpochNo (..), SlotNo (..))\nimport Bcc.Ledger.Val (Val (inject))\nimport Control.State.Transition.Extended (TRC (..), applySTS)\nimport Data.Default.Class (def)\nimport qualified Data.Map as Map\nimport Data.Sequence.Strict (StrictSeq)\nimport qualified Data.Sequence.Strict as StrictSeq\nimport qualified Data.Set as Set\nimport Data.Word (Word64)\nimport Numeric.Natural (Natural)\nimport Sophie.Spec.Ledger.API (OptimumCrypto)\nimport Sophie.Spec.Ledger.Delegation.Certificates (DelegCert (..))\nimport Sophie.Spec.Ledger.LedgerState\n ( AccountState (..),\n DPState,\n UTxOState (..),\n )\nimport Sophie.Spec.Ledger.PParams (PParams, PParams' (..), emptyPParams)\nimport Sophie.Spec.Ledger.STS.Ledger (LEDGER, LedgerEnv (..))\nimport Sophie.Spec.Ledger.Tx (Tx (..), WitnessSetHKD (..))\nimport Sophie.Spec.Ledger.TxBody\n ( DCert (..),\n Delegation (..),\n PoolCert (..),\n PoolParams (..),\n RewardAcnt (..),\n TxBody (..),\n TxIn (..),\n TxOut (..),\n Wdrl (..),\n _poolCost,\n _poolId,\n _poolMD,\n _poolMargin,\n _poolOwners,\n _poolPledge,\n _poolRAcnt,\n _poolRelays,\n _poolVrf,\n )\nimport Sophie.Spec.Ledger.UTxO (makeWitnessesVKey)\nimport qualified Test.Sophie.Spec.Ledger.ConcreteCryptoTypes as Original\n ( C_Crypto,\n )\nimport Test.Sophie.Spec.Ledger.Generator.Core\n ( genesisCoins,\n )\nimport Test.Sophie.Spec.Ledger.Generator.EraGen (genesisId)\nimport Test.Sophie.Spec.Ledger.Generator.SophieEraGen ()\nimport Test.Sophie.Spec.Ledger.SentryUtils\n ( RawSeed (..),\n mkAddr,\n mkKeyPair,\n mkKeyPair',\n mkVRFKeyPair,\n runSophieBase,\n unsafeBoundRational,\n )\n\n-- ===============================================\n-- A special Era to run the Benchmarks in\n\ntype B = SophieEra B_Crypto\n\ndata B_Crypto\n\ninstance Bcc.Ledger.Crypto.Crypto B_Crypto where\n type KES B_Crypto = KES Original.C_Crypto\n type VRF B_Crypto = VRF Original.C_Crypto\n type DSIGN B_Crypto = DSIGN Original.C_Crypto\n type HASH B_Crypto = Blake2b_256\n type ADDRHASH B_Crypto = Blake2b_256\n\ninstance OptimumCrypto B_Crypto\n\n-- =========================================================\n\naliceStake :: KeyPair 'Staking B_Crypto\naliceStake = KeyPair vk sk\n where\n (sk, vk) = mkKeyPair (RawSeed 0 0 0 0 1)\n\nalicePay :: KeyPair 'Payment B_Crypto\nalicePay = KeyPair vk sk\n where\n (sk, vk) = mkKeyPair (RawSeed 0 0 0 0 0)\n\naliceAddr :: Addr B_Crypto\naliceAddr = mkAddr (alicePay, aliceStake)\n\n-- ==========================================================\n\ninjcoins :: Integer -> [TxOut B]\ninjcoins n = fmap (\\_ -> TxOut aliceAddr (inject $ Coin 100)) [0 .. n]\n\n-- Cretae an initial UTxO set with n-many transaction outputs\ninitUTxO :: Integer -> UTxOState B\ninitUTxO n =\n UTxOState\n (genesisCoins genesisId (injcoins n))\n (Coin 0)\n (Coin 0)\n def\n\n-- Protocal Parameters used for the benchmarknig tests.\n-- Note that the fees and deposits are set to zero for\n-- ease of creating transactions.\nppsBench :: PParams era\nppsBench =\n emptyPParams\n { _maxBBSize = 50000,\n _d = unsafeBoundRational 0.5,\n _eMax = EpochNo 10000,\n _keyDeposit = Coin 0,\n _maxBHSize = 10000,\n _maxTxSize = 1000000000,\n _minfeeA = 0,\n _minfeeB = 0,\n _minUTxOValue = Coin 10,\n _poolDeposit = Coin 0,\n _rho = unsafeBoundRational 0.0021,\n _tau = unsafeBoundRational 0.2\n }\n\nledgerEnv :: (Core.PParams era ~ PParams era) => LedgerEnv era\nledgerEnv = LedgerEnv (SlotNo 0) 0 ppsBench (AccountState (Coin 0) (Coin 0))\n\ntestLEDGER ::\n (UTxOState B, DPState B_Crypto) ->\n Tx B ->\n LedgerEnv B ->\n ()\ntestLEDGER initSt tx env = do\n let st = runSophieBase $ applySTS @(LEDGER B) (TRC (env, initSt, tx))\n case st of\n Right _ -> ()\n Left e -> error $ show e\n\ntxbSpendOneUTxO :: TxBody B\ntxbSpendOneUTxO =\n TxBody\n (Set.fromList [TxIn genesisId 0])\n (StrictSeq.fromList [TxOut aliceAddr (inject $ Coin 10), TxOut aliceAddr (inject $ Coin 89)])\n StrictSeq.empty\n (Wdrl Map.empty)\n (Coin 1)\n (SlotNo 10)\n SNothing\n SNothing\n\ntxSpendOneUTxO :: Tx B\ntxSpendOneUTxO =\n Tx\n txbSpendOneUTxO\n mempty\n { addrWits = makeWitnessesVKey (hashAnnotated txbSpendOneUTxO) [asWitness alicePay]\n }\n SNothing\n\nledgerSpendOneUTxO :: Integer -> ()\nledgerSpendOneUTxO n = testLEDGER (initUTxO n, def) txSpendOneUTxO ledgerEnv\n\nledgerSpendOneGivenUTxO :: UTxOState B -> ()\nledgerSpendOneGivenUTxO state = testLEDGER (state, def) txSpendOneUTxO ledgerEnv\n\n-- ===========================================================================\n--\n-- Register a stake keys when there are a lot of registered stake keys\n--\n\n-- Create stake key pairs, corresponding to seeds\n-- (RawSeed start 0 0 0 0) through (RawSeed end 0 0 0 0)\nstakeKeys :: Word64 -> Word64 -> [KeyPair 'Staking B_Crypto]\nstakeKeys start end = fmap (\\w -> mkKeyPair' (RawSeed w 0 0 0 0)) [start .. end]\n\nstakeKeyOne :: KeyPair 'Staking B_Crypto\nstakeKeyOne = mkKeyPair' (RawSeed 1 0 0 0 0)\n\nstakeKeyToCred :: KeyPair 'Staking B_Crypto -> Credential 'Staking B_Crypto\nstakeKeyToCred = KeyHashObj . hashKey . vKey\n\nfirstStakeKeyCred :: Credential 'Staking B_Crypto\nfirstStakeKeyCred = stakeKeyToCred stakeKeyOne\n\n-- Create stake key registration certificates\nstakeKeyRegistrations :: [KeyPair 'Staking B_Crypto] -> StrictSeq (DCert B_Crypto)\nstakeKeyRegistrations keys =\n StrictSeq.fromList $\n fmap (DCertDeleg . RegKey . (KeyHashObj . hashKey . vKey)) keys\n\n-- Create a transaction body given a sequence of certificates.\n-- It spends the genesis coin given by the index ix.\ntxbFromCerts :: Natural -> StrictSeq (DCert B_Crypto) -> TxBody B\ntxbFromCerts ix regCerts =\n TxBody\n (Set.fromList [TxIn genesisId ix])\n (StrictSeq.fromList [TxOut aliceAddr (inject $ Coin 100)])\n regCerts\n (Wdrl Map.empty)\n (Coin 0)\n (SlotNo 10)\n SNothing\n SNothing\n\nmakeSimpleTx ::\n TxBody B ->\n [KeyPair 'Witness B_Crypto] ->\n Tx B\nmakeSimpleTx txbody keysAddr =\n Tx\n txbody\n mempty\n { addrWits = makeWitnessesVKey (hashAnnotated txbody) keysAddr\n }\n SNothing\n\n-- Create a transaction that registers stake credentials.\ntxRegStakeKeys :: Natural -> [KeyPair 'Staking B_Crypto] -> Tx B\ntxRegStakeKeys ix keys =\n makeSimpleTx\n (txbFromCerts ix $ stakeKeyRegistrations keys)\n [asWitness alicePay]\n\ninitLedgerState :: Integer -> (UTxOState B, DPState B_Crypto)\ninitLedgerState n = (initUTxO n, def)\n\nmakeLEDGERState ::\n (UTxOState B, DPState B_Crypto) ->\n Tx B ->\n (UTxOState B, DPState B_Crypto)\nmakeLEDGERState start tx =\n let st = applySTS @(LEDGER B) (TRC (ledgerEnv, start, tx))\n in case runSophieBase st of\n Right st' -> st'\n Left e -> error $ show e\n\n-- Create a ledger state that has registered stake credentials that\n-- are seeded with (RawSeed n 0 0 0 0) to (RawSeed m 0 0 0 0).\n-- It is pre-populated with 2 genesis injcoins.\nledgerStateWithNregisteredKeys ::\n Word64 -> Word64 -> (UTxOState B, DPState B_Crypto)\nledgerStateWithNregisteredKeys n m =\n makeLEDGERState (initLedgerState 1) $ txRegStakeKeys 0 (stakeKeys n m)\n\n-- ===========================================================\n-- Stake Key Registration example\n\n-- Given a ledger state, presumably created by ledgerStateWithNregisteredKeys n m,\n-- so that keys (RawSeed n 0 0 0 0) through (RawSeed m 0 0 0 0) are already registered,\n-- register new keys (RawSeed x 0 0 0 0) through (RawSeed y 0 0 0 0).\n-- Note that [n, m] must be disjoint from [x, y].\nledgerRegisterStakeKeys :: Word64 -> Word64 -> (UTxOState B, DPState B_Crypto) -> ()\nledgerRegisterStakeKeys x y state =\n testLEDGER\n state\n (txRegStakeKeys 1 (stakeKeys x y))\n ledgerEnv\n\n-- ===========================================================\n-- Deregistration example\n\n-- Create a transaction body that de-registers stake credentials,\n-- corresponding to the keys seeded with (RawSeed x 0 0 0 0) to (RawSeed y 0 0 0 0)\ntxbDeRegStakeKey :: Word64 -> Word64 -> TxBody B\ntxbDeRegStakeKey x y =\n TxBody\n (Set.fromList [TxIn genesisId 1])\n (StrictSeq.fromList [TxOut aliceAddr (inject $ Coin 100)])\n ( StrictSeq.fromList $\n fmap (DCertDeleg . DeRegKey . stakeKeyToCred) (stakeKeys x y)\n )\n (Wdrl Map.empty)\n (Coin 0)\n (SlotNo 10)\n SNothing\n SNothing\n\n-- Create a transaction that deregisters stake credentials numbered x through y.\n-- It spends the genesis coin indexed by 1.\ntxDeRegStakeKeys :: Word64 -> Word64 -> Tx B\ntxDeRegStakeKeys x y =\n makeSimpleTx\n (txbDeRegStakeKey x y)\n (asWitness alicePay : fmap asWitness (stakeKeys x y))\n\n-- Given a ledger state, presumably created by ledgerStateWithNregisteredKeys n m,\n-- so that keys (RawSeed n 0 0 0 0) through (RawSeed m 0 0 0 0) are already registered,\n-- deregister keys (RawSeed x 0 0 0 0) through (RawSeed y 0 0 0 0).\n-- Note that [x, y] must be contained in [n, m].\nledgerDeRegisterStakeKeys :: Word64 -> Word64 -> (UTxOState B, DPState B_Crypto) -> ()\nledgerDeRegisterStakeKeys x y state =\n testLEDGER\n state\n (txDeRegStakeKeys x y)\n ledgerEnv\n\n-- ===========================================================\n-- Reward Withdrawal example\n\n-- Create a transaction body that withdrawls from reward accounts,\n-- corresponding to the keys seeded with (RawSeed x 0 0 0 0) to (RawSeed y 0 0 0 0).\ntxbWithdrawals :: Word64 -> Word64 -> TxBody B\ntxbWithdrawals x y =\n TxBody\n (Set.fromList [TxIn genesisId 1])\n (StrictSeq.fromList [TxOut aliceAddr (inject $ Coin 100)])\n StrictSeq.empty\n ( Wdrl $\n Map.fromList $\n fmap (\\ks -> (RewardAcnt Testnet (stakeKeyToCred ks), Coin 0)) (stakeKeys x y)\n )\n (Coin 0)\n (SlotNo 10)\n SNothing\n SNothing\n\n-- Create a transaction that withdrawls from a reward accounts.\n-- It spends the genesis coin indexed by 1.\ntxWithdrawals :: Word64 -> Word64 -> Tx B\ntxWithdrawals x y =\n makeSimpleTx\n (txbWithdrawals x y)\n (asWitness alicePay : fmap asWitness (stakeKeys x y))\n\n-- Given a ledger state, presumably created by ledgerStateWithNregisteredKeys n m,\n-- so that keys (RawSeed n 0 0 0 0) through (RawSeed m 0 0 0 0) are already registered,\n-- make reward withdrawls for keys (RawSeed x 0 0 0 0) through (RawSeed y 0 0 0 0).\n-- Note that [x, y] must be contained in [n, m].\nledgerRewardWithdrawals :: Word64 -> Word64 -> (UTxOState B, DPState B_Crypto) -> ()\nledgerRewardWithdrawals x y state = testLEDGER state (txWithdrawals x y) ledgerEnv\n\n-- ===========================================================================\n--\n-- Register a stake pool when there are a lot of registered stake pool\n--\n\n-- Create stake pool key pairs, corresponding to seeds\n-- (RawSeed start 0 0 0 0) through (RawSeed end 0 0 0 0)\npoolColdKeys :: Word64 -> Word64 -> [KeyPair 'StakePool B_Crypto]\npoolColdKeys start end = fmap (\\w -> mkKeyPair' (RawSeed w 1 0 0 0)) [start .. end]\n\nfirstStakePool :: KeyPair 'StakePool B_Crypto\nfirstStakePool = mkKeyPair' (RawSeed 1 1 0 0 0)\n\nmkPoolKeyHash :: KeyPair 'StakePool B_Crypto -> KeyHash 'StakePool B_Crypto\nmkPoolKeyHash = hashKey . vKey\n\nfirstStakePoolKeyHash :: KeyHash 'StakePool B_Crypto\nfirstStakePoolKeyHash = mkPoolKeyHash firstStakePool\n\nvrfKeyHash :: Hash B_Crypto (VerKeyVRF B_Crypto)\nvrfKeyHash = hashVerKeyVRF . snd . mkVRFKeyPair $ RawSeed 0 0 0 0 0\n\nmkPoolParameters :: KeyPair 'StakePool B_Crypto -> PoolParams B_Crypto\nmkPoolParameters keys =\n PoolParams\n { _poolId = (hashKey . vKey) keys,\n _poolVrf = vrfKeyHash,\n _poolPledge = Coin 0,\n _poolCost = Coin 0,\n _poolMargin = unsafeBoundRational 0,\n _poolRAcnt = RewardAcnt Testnet firstStakeKeyCred,\n _poolOwners = Set.singleton $ (hashKey . vKey) stakeKeyOne,\n _poolRelays = StrictSeq.empty,\n _poolMD = SNothing\n }\n\n-- Create stake pool registration certs\npoolRegCerts :: [KeyPair 'StakePool B_Crypto] -> StrictSeq (DCert B_Crypto)\npoolRegCerts = StrictSeq.fromList . fmap (DCertPool . RegPool . mkPoolParameters)\n\n-- Create a transaction that registers stake pools.\ntxRegStakePools :: Natural -> [KeyPair 'StakePool B_Crypto] -> Tx B\ntxRegStakePools ix keys =\n makeSimpleTx\n (txbFromCerts ix $ poolRegCerts keys)\n ([asWitness alicePay, asWitness stakeKeyOne] ++ fmap asWitness keys)\n\n-- Create a ledger state that has n registered stake pools.\n-- The keys are seeded with (RawSeed n 1 0 0 0) to (RawSeed m 1 0 0 0)\n-- It is pre-populated with 2 genesis injcoins.\nledgerStateWithNregisteredPools :: Word64 -> Word64 -> (UTxOState B, DPState B_Crypto)\nledgerStateWithNregisteredPools n m =\n makeLEDGERState (initLedgerState 1) $ txRegStakePools 0 (poolColdKeys n m)\n\n-- ===========================================================\n-- Stake Pool Registration example\n\n-- Given a ledger state, presumably created by ledgerStateWithNregisteredPools n m,\n-- so that pool keys (RawSeed n 1 0 0 0) through (RawSeed m 1 0 0 0) are already registered,\n-- register new pools (RawSeed x 0 0 0 0) through (RawSeed y 0 0 0 0).\n-- Note that [n, m] must be disjoint from [x, y].\nledgerRegisterStakePools :: Word64 -> Word64 -> (UTxOState B, DPState B_Crypto) -> ()\nledgerRegisterStakePools x y state =\n testLEDGER\n state\n (txRegStakePools 1 (poolColdKeys x y))\n ledgerEnv\n\n-- ===========================================================\n-- Stake Pool Re-Registration\/Update example\n\n-- Given a ledger state, presumably created by ledgerStateWithNregisteredPools n m,\n-- so that pool keys (RawSeed n 1 0 0 0) through (RawSeed m 1 0 0 0) are already registered,\n-- re-register pools (RawSeed x 0 0 0 0) through (RawSeed y 0 0 0 0).\n-- Note that [n, m] must be contained in [x, y].\nledgerReRegisterStakePools :: Word64 -> Word64 -> (UTxOState B, DPState B_Crypto) -> ()\nledgerReRegisterStakePools x y state =\n testLEDGER\n state\n (txRegStakePools 1 (poolColdKeys x y))\n ledgerEnv\n\n-- ===========================================================\n-- Stake Pool Retirement example\n\n-- Create a transaction body that retires stake pools,\n-- corresponding to the keys seeded with (RawSeed x 1 0 0 0) to (RawSeed y 1 0 0 0)\ntxbRetireStakePool :: Word64 -> Word64 -> TxBody B\ntxbRetireStakePool x y =\n TxBody\n (Set.fromList [TxIn genesisId 1])\n (StrictSeq.fromList [TxOut aliceAddr (inject $ Coin 100)])\n ( StrictSeq.fromList $\n fmap\n (\\ks -> DCertPool $ RetirePool (mkPoolKeyHash ks) (EpochNo 1))\n (poolColdKeys x y)\n )\n (Wdrl Map.empty)\n (Coin 0)\n (SlotNo 10)\n SNothing\n SNothing\n\n-- Create a transaction that retires stake pools x through y.\n-- It spends the genesis coin indexed by 1.\ntxRetireStakePool :: Word64 -> Word64 -> Tx B\ntxRetireStakePool x y =\n makeSimpleTx\n (txbRetireStakePool x y)\n (asWitness alicePay : fmap asWitness (poolColdKeys x y))\n\n-- Given a ledger state, presumably created by ledgerStateWithNregisteredPools n m,\n-- so that pool keys (RawSeed n 1 0 0 0) through (RawSeed m 1 0 0 0) are already registered,\n-- retire pools (RawSeed x 0 0 0 0) through (RawSeed y 0 0 0 0).\n-- Note that [n, m] must be contained in [x, y].\nledgerRetireStakePools :: Word64 -> Word64 -> (UTxOState B, DPState B_Crypto) -> ()\nledgerRetireStakePools x y state = testLEDGER state (txRetireStakePool x y) ledgerEnv\n\n-- ===========================================================================\n--\n-- Delegate Stake Credentials when many stake keys and stake pools are registered.\n--\n\n-- Create a ledger state that has n registered stake keys and m stake pools.\n-- The stake keys are seeded with (RawSeed 1 0 0 0 0) to (RawSeed n 0 0 0 0)\n-- The stake pools are seeded with (RawSeed 1 1 0 0 0) to (RawSeed m 1 0 0 0)\n-- It is pre-populated with 3 genesis injcoins.\nledgerStateWithNkeysMpools :: Word64 -> Word64 -> (UTxOState B, DPState B_Crypto)\nledgerStateWithNkeysMpools n m =\n makeLEDGERState\n (makeLEDGERState (initLedgerState 2) $ txRegStakeKeys 0 (stakeKeys 1 n))\n (txRegStakePools 1 (poolColdKeys 1 m))\n\n-- Create a transaction body that delegates several keys to ONE stake pool,\n-- corresponding to the keys seeded with (RawSeed n 0 0 0 0) to (RawSeed m 0 0 0 0)\ntxbDelegate :: Word64 -> Word64 -> TxBody B\ntxbDelegate n m =\n TxBody\n (Set.fromList [TxIn genesisId 2])\n (StrictSeq.fromList [TxOut aliceAddr (inject $ Coin 100)])\n ( StrictSeq.fromList $\n fmap\n (\\ks -> DCertDeleg $ Delegate (Delegation (stakeKeyToCred ks) firstStakePoolKeyHash))\n (stakeKeys n m)\n )\n (Wdrl Map.empty)\n (Coin 0)\n (SlotNo 10)\n SNothing\n SNothing\n\n-- Create a transaction that delegates stake.\ntxDelegate :: Word64 -> Word64 -> Tx B\ntxDelegate n m =\n makeSimpleTx\n (txbDelegate n m)\n (asWitness alicePay : fmap asWitness (stakeKeys n m))\n\n-- Given a ledger state, presumably created by ledgerStateWithNkeysMpools n m,\n-- so that stake keys (RawSeed 1 0 0 0 0) through (RawSeed n 0 0 0 0) are already registered\n-- and pool keys (RawSeed 1 1 0 0 0) through (RawSeed m 1 0 0 0) are already registered,\n-- delegate stake keys (RawSeed x 0 0 0 0) through (RawSeed y 0 0 0 0) to ONE pool.\n-- Note that [x, y] must be contained in [1, n].\nledgerDelegateManyKeysOnePool ::\n Word64 -> Word64 -> (UTxOState B, DPState B_Crypto) -> ()\nledgerDelegateManyKeysOnePool x y state = testLEDGER state (txDelegate x y) ledgerEnv\n","avg_line_length":34.1070780399,"max_line_length":97,"alphanum_fraction":0.680998244} {"size":13507,"ext":"hsc","lang":"Haskell","max_stars_count":7.0,"content":"{-# LANGUAGE Safe #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\n-- This file is part of zhk\n--\n-- All rights reserved.\n-- \n-- Redistribution and use in source and binary forms, with or without modification,\n-- are permitted provided that the following conditions are met:\n-- \n-- Redistributions of source code must retain the above copyright notice, this\n-- list of conditions and the following disclaimer.\n-- \n-- Redistributions in binary form must reproduce the above copyright notice, this\n-- list of conditions and the following disclaimer in the documentation and\/or\n-- other materials provided with the distribution.\n-- \n-- Neither the name of the {organization} nor the names of its\n-- contributors may be used to endorse or promote products derived from\n-- this software without specific prior written permission.\n-- \n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n-- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n-- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nmodule Database.Zookeeper.CApi\n ( -- * C to Haskell\n toStat\n , toState\n , toAclList\n , toZKError\n , allocaStat\n , toClientId\n , toStringList\n , allocaAclVec\n , allocaStrVec\n -- * Haskell to C\n , withAclList\n , wrapWatcher\n , fromLogLevel\n , fromCreateFlag\n , fromCreateFlags\n , wrapVoidCompletion\n -- * Error handling\n , tryZ\n , isZOK\n , onZOK\n , whenZOK\n -- * C functions\n , c_zooSet2\n , c_zooWGet\n , c_zooState\n , c_zooDelete\n , c_zooSetAcl\n , c_zooCreate\n , c_zooGetAcl\n , c_zooAddAuth\n , c_zooWExists\n , c_zooClientId\n , c_zookeeperInit\n , c_zooSetWatcher\n , c_zookeeperClose\n , c_zooRecvTimeout\n , c_isUnrecoverable\n , c_zooWGetChildren\n , c_zooSetDebugLevel\n ) where\n\n#include \n\nimport Foreign.C\nimport Foreign.Safe\nimport Control.Applicative\nimport Database.Zookeeper.Types\n\ntryZ :: IO CInt -> IO a -> IO (Either ZKError a)\ntryZ zkIO nextIO = do\n rc <- zkIO\n rc `onZOK` nextIO\n\nisZOK :: CInt -> Bool\nisZOK rc = rc == (#const ZOK)\n\nonZOK :: CInt -> IO a -> IO (Either ZKError a)\nonZOK rc nextIO\n | isZOK rc = fmap Right nextIO\n | otherwise = return (Left $ toZKError rc)\n\nwhenZOK :: CInt -> IO (Either ZKError a) -> IO (Either ZKError a)\nwhenZOK rc succIO\n | isZOK rc = succIO\n | otherwise = return (Left $ toZKError rc)\n\ntoStat :: Ptr CStat -> IO Stat\ntoStat ptr = Stat <$> (#peek struct Stat, czxid) ptr\n <*> (#peek struct Stat, mzxid) ptr\n <*> (#peek struct Stat, pzxid) ptr\n <*> (#peek struct Stat, ctime) ptr\n <*> (#peek struct Stat, mtime) ptr\n <*> (#peek struct Stat, version) ptr\n <*> (#peek struct Stat, cversion) ptr\n <*> (#peek struct Stat, aversion) ptr\n <*> (#peek struct Stat, dataLength) ptr\n <*> (#peek struct Stat, numChildren) ptr\n <*> liftA toEphemeralOwner ((#peek struct Stat, ephemeralOwner) ptr)\n where\n toEphemeralOwner 0 = Nothing\n toEphemeralOwner c = Just c\n\nfromCreateFlag :: CreateFlag -> CInt\nfromCreateFlag Sequence = (#const ZOO_SEQUENCE)\nfromCreateFlag Ephemeral = (#const ZOO_EPHEMERAL)\n\nfromCreateFlags :: [CreateFlag] -> CInt\nfromCreateFlags = foldr (.|.) 0 . map fromCreateFlag\n\nfromPerm :: Perm -> CInt\nfromPerm CanRead = (#const ZOO_PERM_READ)\nfromPerm CanAdmin = (#const ZOO_PERM_ADMIN)\nfromPerm CanWrite = (#const ZOO_PERM_WRITE)\nfromPerm CanCreate = (#const ZOO_PERM_CREATE)\nfromPerm CanDelete = (#const ZOO_PERM_DELETE)\n\nfromLogLevel :: ZLogLevel -> CInt\nfromLogLevel ZLogError = (#const ZOO_LOG_LEVEL_ERROR)\nfromLogLevel ZLogWarn = (#const ZOO_LOG_LEVEL_WARN)\nfromLogLevel ZLogInfo = (#const ZOO_LOG_LEVEL_INFO)\nfromLogLevel ZLogDebug = (#const ZOO_LOG_LEVEL_DEBUG)\n\nfromPerms :: [Perm] -> CInt\nfromPerms = foldr (.|.) 0 . map fromPerm\n\ntoPerms :: CInt -> [Perm]\ntoPerms n = buildList [ ((#const ZOO_PERM_READ), CanRead)\n , ((#const ZOO_PERM_ADMIN), CanAdmin)\n , ((#const ZOO_PERM_WRITE), CanWrite)\n , ((#const ZOO_PERM_CREATE), CanCreate)\n , ((#const ZOO_PERM_DELETE), CanDelete)\n ]\n where\n buildList [] = []\n buildList ((t, a):xs)\n | n .&. t == t = a : buildList xs\n | otherwise = buildList xs\n\ntoStringList :: Ptr CStrVec -> IO [String]\ntoStringList strvPtr = do\n count <- (#peek struct String_vector, count) strvPtr\n dataPtr <- (#peek struct String_vector, data) strvPtr\n buildList [] count dataPtr\n where\n buildList :: [String] -> Int32 -> Ptr CString -> IO [String]\n buildList acc 0 _ = return $ reverse acc\n buildList acc n ptr = do\n item <- peek ptr >>= peekCString\n buildList (item : acc) (n-1) (ptr `plusPtr` (sizeOf ptr))\n\ntoClientId :: Ptr CClientID -> IO Int64\ntoClientId clientPtr = (#peek clientid_t, client_id) clientPtr\n\nallocaStat :: (Ptr CStat -> IO a) -> IO a\nallocaStat fun = allocaBytes (#size struct Stat) fun\n\ntoAclList :: Ptr CAclVec -> IO AclList\ntoAclList aclvPtr = do\n count <- (#peek struct ACL_vector, count) aclvPtr\n aclPtr <- (#peek struct ACL_vector, data) aclvPtr\n fmap List (buildList [] count aclPtr)\n where\n buildList :: [Acl] -> Int32 -> Ptr CAcl -> IO [Acl]\n buildList acc 0 _ = return acc\n buildList acc n ptr = do\n acl <- Acl <$> ((#peek struct ACL, id.scheme) ptr >>= peekCString)\n <*> ((#peek struct ACL, id.id) ptr >>= peekCString)\n <*> (fmap toPerms ((#peek struct ACL, perms) ptr))\n buildList (acl : acc) (n-1) (ptr `plusPtr` (#size struct ACL))\n\nallocaStrVec :: (Ptr CStrVec -> IO a) -> IO a\nallocaStrVec = allocaBytes (#size struct String_vector)\n\nallocaAclVec :: (Ptr CAclVec -> IO a) -> IO a\nallocaAclVec = allocaBytes (#size struct ACL_vector)\n\nwithAclList :: AclList -> (Ptr CAclVec -> IO a) -> IO a\nwithAclList CreatorAll cont = cont c_zooCreatorAclAll\nwithAclList OpenAclUnsafe cont = cont c_zooOpenAclUnsafe\nwithAclList ReadAclUnsafe cont = cont c_zooReadAclUnsafe\nwithAclList (List acls) cont =\n allocaAclVec $ \\aclvPtr -> do\n (#poke struct ACL_vector, count) aclvPtr count\n allocaBytes (count * (#size struct ACL)) $ \\aclPtr -> do\n (#poke struct ACL_vector, data) aclvPtr aclPtr\n pokeAcls acls aclvPtr aclPtr\n where\n count = length acls\n\n pokeAcls [] aclvPtr _ = cont aclvPtr\n pokeAcls (acl:rest) aclvPtr aclPtr = do\n withCString (aclScheme acl) $ \\schemePtr -> do\n withCString (aclId acl) $ \\idPtr -> do\n (#poke struct ACL, id.id) aclPtr idPtr\n (#poke struct ACL, perms) aclPtr (fromPerms (aclFlags acl))\n (#poke struct ACL, id.scheme) aclPtr schemePtr\n pokeAcls rest aclvPtr (aclPtr `plusPtr` (#size struct ACL))\n\ntoZKError :: CInt -> ZKError\ntoZKError (#const ZNONODE) = NoNodeError\ntoZKError (#const ZNOAUTH) = NoAuthError\ntoZKError (#const ZCLOSING) = ClosingError\ntoZKError (#const ZNOTHING) = NothingError\ntoZKError (#const ZAPIERROR) = ApiError\ntoZKError (#const ZNOTEMPTY) = NotEmptyError\ntoZKError (#const ZBADVERSION) = BadVersionError\ntoZKError (#const ZINVALIDACL) = InvalidACLError\ntoZKError (#const ZAUTHFAILED) = AuthFailedError\ntoZKError (#const ZNODEEXISTS) = NodeExistsError\ntoZKError (#const ZSYSTEMERROR) = SystemError\ntoZKError (#const ZBADARGUMENTS) = BadArgumentsError\ntoZKError (#const ZINVALIDSTATE) = InvalidStateError\ntoZKError (#const ZSESSIONMOVED) = SessionMovedError\ntoZKError (#const ZUNIMPLEMENTED) = UnimplmenetedError\ntoZKError (#const ZCONNECTIONLOSS) = ConnectionLossError\ntoZKError (#const ZSESSIONEXPIRED) = SessionExpiredError\ntoZKError (#const ZINVALIDCALLBACK) = InvalidCallbackError\ntoZKError (#const ZMARSHALLINGERROR) = MarshallingError\ntoZKError (#const ZOPERATIONTIMEOUT) = OperationTimeoutError\ntoZKError (#const ZDATAINCONSISTENCY) = DataInconsistencyError\ntoZKError (#const ZRUNTIMEINCONSISTENCY) = RuntimeInconsistencyError\ntoZKError (#const ZNOCHILDRENFOREPHEMERALS) = NoChildrenForEphemeralsError\ntoZKError code = (UnknownError $ fromIntegral code)\n\ntoState :: CInt -> State\ntoState (#const ZOO_CONNECTED_STATE) = ConnectedState\ntoState (#const ZOO_CONNECTING_STATE) = ConnectingState\ntoState (#const ZOO_ASSOCIATING_STATE) = AssociatingState\ntoState (#const ZOO_AUTH_FAILED_STATE) = AuthFailedState\ntoState (#const ZOO_EXPIRED_SESSION_STATE) = ExpiredSessionState\ntoState code = UnknownState $ fromIntegral code\n\ntoEvent :: CInt -> Event\ntoEvent (#const ZOO_CHILD_EVENT) = ChildEvent\ntoEvent (#const ZOO_CREATED_EVENT) = CreatedEvent\ntoEvent (#const ZOO_DELETED_EVENT) = DeletedEvent\ntoEvent (#const ZOO_CHANGED_EVENT) = ChangedEvent\ntoEvent (#const ZOO_SESSION_EVENT) = SessionEvent\ntoEvent (#const ZOO_NOTWATCHING_EVENT) = NotWatchingEvent\ntoEvent code = UnknownEvent $ fromIntegral code\n\nwrapWatcher :: Maybe Watcher -> IO (FunPtr CWatcherFn)\nwrapWatcher Nothing = return nullFunPtr\nwrapWatcher (Just fn) = c_watcherFn $ \\zh cevent cstate cpath _ -> do\n let event = toEvent cevent\n state = toState cstate\n path <- if (cpath == nullPtr)\n then return Nothing\n else fmap Just (peekCString cpath)\n fn (Zookeeper zh) event state path\n\nwrapVoidCompletion :: VoidCompletion -> IO (FunPtr CVoidCompletionFn)\nwrapVoidCompletion fn =\n c_voidCompletionFn $ \\rc _ -> (fn =<< onZOK rc (return ()))\n\nforeign import ccall safe \"wrapper\"\n c_watcherFn :: CWatcherFn\n -> IO (FunPtr CWatcherFn)\n\nforeign import ccall safe \"wrapper\"\n c_voidCompletionFn :: CVoidCompletionFn\n -> IO (FunPtr CVoidCompletionFn)\n\nforeign import ccall safe \"zookeeper.h zookeeper_init\"\n c_zookeeperInit :: CString\n -> FunPtr CWatcherFn\n -> CInt\n -> Ptr CClientID\n -> Ptr ()\n -> CInt\n -> IO (Ptr CZHandle)\n\nforeign import ccall safe \"zookeeper.h zookeeper_close\"\n c_zookeeperClose :: Ptr CZHandle -> IO ()\n\nforeign import ccall safe \"zookeeper.h zoo_set_watcher\"\n c_zooSetWatcher :: Ptr CZHandle -> FunPtr CWatcherFn -> IO ()\n\nforeign import ccall safe \"zookeeper.h zoo_create\"\n c_zooCreate :: Ptr CZHandle -> CString -> CString -> CInt -> Ptr CAclVec -> CInt -> CString -> CInt -> IO CInt\n\nforeign import ccall safe \"zookeeper.h zoo_delete\"\n c_zooDelete :: Ptr CZHandle -> CString -> CInt -> IO CInt\n\nforeign import ccall safe \"zookeeper.h zoo_wexists\"\n c_zooWExists :: Ptr CZHandle -> CString -> FunPtr CWatcherFn -> Ptr () -> Ptr CStat -> IO CInt\n\nforeign import ccall safe \"zookeeper.h zoo_state\"\n c_zooState :: Ptr CZHandle -> IO CInt\n\nforeign import ccall safe \"zookeeper.h zoo_client_id\"\n c_zooClientId :: Ptr CZHandle -> IO (Ptr CClientID)\n\nforeign import ccall safe \"zookeeper.h zoo_recv_timeout\"\n c_zooRecvTimeout :: Ptr CZHandle -> IO CInt\n\nforeign import ccall safe \"zookeeper.h zoo_add_auth\"\n c_zooAddAuth :: Ptr CZHandle -> CString -> CString -> CInt -> FunPtr CVoidCompletionFn -> Ptr () -> IO CInt\n\nforeign import ccall safe \"zookeeper.h is_unrecoverable\"\n c_isUnrecoverable :: Ptr CZHandle -> IO CInt\n\nforeign import ccall safe \"zookeeper.h zoo_set_debug_level\"\n c_zooSetDebugLevel :: CInt -> IO ()\n\nforeign import ccall safe \"zookeeper.h zoo_get_acl\"\n c_zooGetAcl :: Ptr CZHandle -> CString -> Ptr CAclVec -> Ptr CStat -> IO CInt\n\nforeign import ccall safe \"zookeeper.h zoo_set_acl\"\n c_zooSetAcl :: Ptr CZHandle -> CString -> CInt -> Ptr CAclVec -> IO CInt\n\nforeign import ccall safe \"zookeeper.h zoo_wget\"\n c_zooWGet :: Ptr CZHandle -> CString -> FunPtr CWatcherFn -> Ptr () -> CString -> Ptr CInt -> Ptr CStat -> IO CInt\n\nforeign import ccall safe \"zookeeper.h zoo_set2\"\n c_zooSet2 :: Ptr CZHandle -> CString -> CString -> CInt -> CInt -> Ptr CStat -> IO CInt\n\nforeign import ccall safe \"zookeeper.h zoo_wget_children\"\n c_zooWGetChildren :: Ptr CZHandle -> CString -> FunPtr CWatcherFn -> Ptr () -> Ptr CStrVec -> IO CInt\n\nforeign import ccall safe \"zookeeper.h &ZOO_CREATOR_ALL_ACL\"\n c_zooCreatorAclAll :: Ptr CAclVec\n\nforeign import ccall safe \"zookeeper.h &ZOO_OPEN_ACL_UNSAFE\"\n c_zooOpenAclUnsafe :: Ptr CAclVec\n\nforeign import ccall safe \"zookeeper.h &ZOO_READ_ACL_UNSAFE\"\n c_zooReadAclUnsafe :: Ptr CAclVec\n","avg_line_length":39.3790087464,"max_line_length":116,"alphanum_fraction":0.6651365958} {"size":7424,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DerivingStrategies #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE StrictData #-}\n\nmodule HStream.Connector.HStore\n ( hstoreSourceConnector\n , hstoreSourceConnectorWithoutCkp\n , hstoreSinkConnector\n , transToStreamName\n , transToTempStreamName\n , transToViewStreamName\n )\nwhere\n\nimport Control.Monad (void)\nimport qualified Data.ByteString.Lazy as BL\nimport Data.Int (Int64)\nimport qualified Data.Map.Strict as M\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe (fromJust, isJust)\nimport qualified Data.Text as T\nimport Proto3.Suite (Enumerated (..))\nimport Z.Data.Vector (Bytes)\nimport Z.Foreign (toByteString)\nimport qualified Z.IO.Logger as Log\n\nimport HStream.Processing.Connector\nimport HStream.Processing.Type as HPT\nimport HStream.Server.HStreamApi (HStreamRecordHeader_Flag (..))\nimport qualified HStream.Store as S\nimport HStream.Utils\n\nhstoreSourceConnector :: S.LDClient -> S.LDSyncCkpReader -> S.StreamType -> SourceConnector\nhstoreSourceConnector ldclient reader streamType = SourceConnector {\n subscribeToStream = \\streamName ->\n subscribeToHStoreStream ldclient reader\n (S.mkStreamId streamType (textToCBytes streamName)),\n unSubscribeToStream = \\streamName ->\n unSubscribeToHStoreStream ldclient reader\n (S.mkStreamId streamType (textToCBytes streamName)),\n readRecords = readRecordsFromHStore ldclient reader 100,\n commitCheckpoint = \\streamName ->\n commitCheckpointToHStore ldclient reader\n (S.mkStreamId streamType (textToCBytes streamName))\n}\n\nhstoreSourceConnectorWithoutCkp :: S.LDClient -> S.LDReader -> SourceConnectorWithoutCkp\nhstoreSourceConnectorWithoutCkp ldclient reader = SourceConnectorWithoutCkp {\n subscribeToStreamWithoutCkp = subscribeToHStoreStream' ldclient reader,\n unSubscribeToStreamWithoutCkp = unSubscribeToHStoreStream' ldclient reader,\n readRecordsWithoutCkp = readRecordsFromHStore' ldclient reader 100\n}\n\nhstoreSinkConnector :: S.LDClient -> S.StreamType -> SinkConnector\nhstoreSinkConnector ldclient streamType = SinkConnector {\n writeRecord = writeRecordToHStore ldclient streamType\n}\n\n--------------------------------------------------------------------------------\n\ntransToStreamName :: HPT.StreamName -> S.StreamId\ntransToStreamName = S.mkStreamId S.StreamTypeStream . textToCBytes\n\ntransToTempStreamName :: HPT.StreamName -> S.StreamId\ntransToTempStreamName = S.mkStreamId S.StreamTypeTemp . textToCBytes\n\ntransToViewStreamName :: HPT.StreamName -> S.StreamId\ntransToViewStreamName = S.mkStreamId S.StreamTypeView . textToCBytes\n\n--------------------------------------------------------------------------------\n\nsubscribeToHStoreStream :: S.LDClient -> S.LDSyncCkpReader -> S.StreamId -> Offset -> IO ()\nsubscribeToHStoreStream ldclient reader streamId startOffset = do\n logId <- S.getUnderlyingLogId ldclient streamId Nothing\n startLSN <- case startOffset of\n Earlist -> return S.LSN_MIN\n Latest -> fmap (+1) (S.getTailLSN ldclient logId)\n Offset lsn -> return lsn\n S.ckpReaderStartReading reader logId startLSN S.LSN_MAX\n\nsubscribeToHStoreStream' :: S.LDClient -> S.LDReader -> HPT.StreamName -> Offset -> IO ()\nsubscribeToHStoreStream' ldclient reader stream startOffset = do\n logId <- S.getUnderlyingLogId ldclient (transToStreamName stream) Nothing\n startLSN <-\n case startOffset of\n Earlist -> return S.LSN_MIN\n Latest -> fmap (+1) (S.getTailLSN ldclient logId)\n Offset lsn -> return lsn\n S.readerStartReading reader logId startLSN S.LSN_MAX\n\nunSubscribeToHStoreStream :: S.LDClient -> S.LDSyncCkpReader -> S.StreamId -> IO ()\nunSubscribeToHStoreStream ldclient reader streamId = do\n logId <- S.getUnderlyingLogId ldclient streamId Nothing\n S.ckpReaderStopReading reader logId\n\nunSubscribeToHStoreStream' :: S.LDClient -> S.LDReader -> HPT.StreamName -> IO ()\nunSubscribeToHStoreStream' ldclient reader streamName = do\n logId <- S.getUnderlyingLogId ldclient (transToStreamName streamName) Nothing\n S.readerStopReading reader logId\n\ndataRecordToSourceRecord :: S.LDClient -> Payload -> IO SourceRecord\ndataRecordToSourceRecord ldclient Payload {..} = do\n streamName <- S.streamName . fst <$> S.getStreamIdFromLogId ldclient pLogID\n return SourceRecord\n { srcStream = cBytesToText streamName\n -- A dummy key typed Aeson.Object, for avoiding errors while processing\n -- queries with JOIN clause only. It is not used and will be removed in\n -- the future.\n , srcKey = Just \"{}\"\n , srcValue = BL.fromStrict . toByteString $ pValue\n , srcTimestamp = pTimeStamp\n , srcOffset = pLSN\n }\n\nreadRecordsFromHStore :: S.LDClient -> S.LDSyncCkpReader -> Int -> IO [SourceRecord]\nreadRecordsFromHStore ldclient reader maxlen = do\n S.ckpReaderSetTimeout reader 1000 -- 1000 milliseconds\n dataRecords <- S.ckpReaderRead reader maxlen\n let payloads = filter isJust $ map getJsonFormatRecord dataRecords\n mapM (dataRecordToSourceRecord ldclient . fromJust) payloads\n\nreadRecordsFromHStore' :: S.LDClient -> S.LDReader -> Int -> IO [SourceRecord]\nreadRecordsFromHStore' ldclient reader maxlen = do\n S.readerSetTimeout reader 1000 -- 1000 milliseconds\n dataRecords <- S.readerRead reader maxlen\n let payloads = filter isJust $ map getJsonFormatRecord dataRecords\n mapM (dataRecordToSourceRecord ldclient . fromJust) payloads\n\ngetJsonFormatRecord :: S.DataRecord Bytes -> Maybe Payload\ngetJsonFormatRecord dataRecord\n | flag == Enumerated (Right HStreamRecordHeader_FlagJSON) = Just $ Payload logid payload lsn timestamp\n | otherwise = Nothing\n where\n record = decodeRecord $ S.recordPayload dataRecord\n flag = getPayloadFlag record\n payload = getPayload record\n logid = S.recordLogID dataRecord\n lsn = S.recordLSN dataRecord\n timestamp = getTimeStamp record\n\ncommitCheckpointToHStore :: S.LDClient -> S.LDSyncCkpReader -> S.StreamId -> Offset -> IO ()\ncommitCheckpointToHStore ldclient reader streamId offset = do\n logId <- S.getUnderlyingLogId ldclient streamId Nothing\n case offset of\n Earlist -> error \"expect normal offset, but get Earlist\"\n Latest -> error \"expect normal offset, but get Latest\"\n Offset lsn -> S.writeCheckpoints reader (M.singleton logId lsn) 10{-retries-}\n\nwriteRecordToHStore :: S.LDClient -> S.StreamType -> SinkRecord -> IO ()\nwriteRecordToHStore ldclient streamType SinkRecord{..} = do\n let streamId = S.mkStreamId streamType (textToCBytes snkStream)\n Log.withDefaultLogger . Log.debug $ \"Start writeRecordToHStore...\"\n logId <- S.getUnderlyingLogId ldclient streamId Nothing\n timestamp <- getProtoTimestamp\n let header = buildRecordHeader HStreamRecordHeader_FlagJSON Map.empty timestamp T.empty\n let payload = encodeRecord $ buildRecord header (BL.toStrict snkValue)\n _ <- S.appendBS ldclient logId payload Nothing\n return ()\n\ndata Payload = Payload\n { pLogID :: S.C_LogID\n , pValue :: Bytes\n , pLSN :: S.LSN\n , pTimeStamp :: Int64\n } deriving (Show)\n","avg_line_length":43.9289940828,"max_line_length":105,"alphanum_fraction":0.7108028017} {"size":4174,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TemplateHaskell #-}\n-- | Classifying messages by severity and filtering them.\nmodule Language.Haskell.Homplexity.Message (\n Log\n , Message\n , Severity (..)\n , severityOptions\n , critical\n , warn\n , info\n , debug\n , message\n , extract\n ) where\n\nimport Control.Arrow\nimport Control.DeepSeq\nimport Data.Function (on)\nimport Data.Foldable as Foldable\nimport Data.Monoid\n#if __GLASGOW_HASKELL__ >= 800\n-- MIN_VERSION_base(4,9,0)\nimport Data.Semigroup\n#endif\nimport Data.Sequence as Seq\nimport Language.Haskell.Exts\nimport Language.Haskell.TH.Syntax (Lift(..))\nimport HFlags\n\n-- | Keeps a set of messages\nnewtype Log = Log { unLog :: Seq Message }\n deriving(Monoid\n#if __GLASGOW_HASKELL__ >= 800\n-- #if MIN_VERSION_base(4,9,0)\n ,Semigroup\n#endif\n )\n\ninstance NFData Log where\n rnf = rnf . unLog\n\n-- | Message from analysis\ndata Message = Message { msgSeverity :: !Severity\n , msgText :: !String\n , msgSrc :: !SrcLoc\n }\n deriving (Eq)\n\ninstance NFData Message where\n rnf Message {..} = rnf msgSeverity `seq` rnf msgText `seq` rnf msgSrc\n\ninstance NFData SrcLoc where\n rnf SrcLoc {..} = rnf srcFilename `seq` rnf srcLine `seq` rnf srcColumn\n\ninstance Show Message where\n showsPrec _ Message {msgSrc=loc@SrcLoc{..}, ..} = shows msgSeverity\n . (':':)\n . (srcFilename++)\n . (':':)\n . shows loc\n -- . shows srcLine\n -- . shows srcColumn\n . (':':)\n . (msgText++)\n . ('\\n':)\n\n-- | Message severity\ndata Severity = Debug\n | Info\n | Warning\n | Critical\n deriving (Eq, Ord, Read, Show, Enum, Bounded)\n\ninstance NFData Severity where\n rnf !_a = ()\n\n-- | String showing all possible values for @Severity@.\nseverityOptions :: String\nseverityOptions = unwords $ map show [minBound..(maxBound::Severity)]\n\ninstance Lift Severity where\n lift Debug = [| Debug |]\n lift Info = [| Info |]\n lift Warning = [| Warning |]\n lift Critical = [| Critical |]\n\ninstance FlagType Severity where\n defineFlag n v = defineEQFlag n [| v :: Severity |] \"{Debug|Info|Warning|Critical}\"\n\n-- | Helper for logging a message with given severity.\nmessage :: Severity -> SrcLoc -> String -> Log\nmessage msgSeverity msgSrc msgText = Log $ Seq.singleton Message {..}\n\n-- | TODO: automatic inference of the srcLine \n-- | Log a certain error\ncritical :: SrcLoc -> String -> Log\ncritical = message Critical\n\n-- | Log a warning\nwarn :: SrcLoc -> String -> Log\nwarn = message Warning\n\n-- | Log informational message\ninfo :: SrcLoc -> String -> Log\ninfo = message Info\n\n-- | Log debugging message\ndebug :: SrcLoc -> String -> Log\ndebug = message Debug\n\n-- TODO: check if this is not too slow\nmsgOrdering :: Message -> Message -> Ordering\nmsgOrdering = compare `on` ((srcFilename &&& srcLine) . msgSrc)\n\n-- | Convert @Log@ into ordered sequence (@Seq@).\norderedMessages :: Severity -> Log -> Seq Message\norderedMessages severity Log {..} = Seq.unstableSortBy msgOrdering $\n Seq.filter ((severity<=) . msgSeverity) unLog\n\n-- | Extract an ordered sequence of messages from the @Log@.\nextract :: Severity -> Log -> [Message]\nextract severity = Foldable.toList\n . orderedMessages severity\n\ninstance Show Log where\n showsPrec _ l e = Foldable.foldr shows e $\n orderedMessages Debug l\n\n","avg_line_length":31.3834586466,"max_line_length":85,"alphanum_fraction":0.5481552468} {"size":391,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Effects.Runner where\n\nimport Data.Runner\nimport Polysemy\n\n\n--------------------------------------------------------------------------------\n -- Effect Runner Model --\n--------------------------------------------------------------------------------\ndata Runner r a where\n SubmitTask :: TestId -> Test -> Runner r ()\n\nmakeSem ''Runner\n","avg_line_length":27.9285714286,"max_line_length":80,"alphanum_fraction":0.3273657289} {"size":3388,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE BangPatterns #-}\n\nmodule Day07 where\n\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Map.Strict as Map\nimport Data.Map.Strict (Map)\nimport Data.Char (isUpper)\nimport Data.Tuple (swap)\n\nparse xs = allBefore\n where\n tuppels = map (f . filter isUpper) . lines $ xs\n \n f [_,x,y] = (x,y)\n after = Map.fromListWith (++) $ (fmap . fmap) (:[]) tuppels\n before = Map.fromListWith Set.union $ fmap (fmap Set.singleton . swap) tuppels\n allBefore = Map.unionWith Set.union before $ Map.fromSet (const Set.empty) everyKey\n everyKey = Set.union (Map.keysSet after) (Map.keysSet before)\n \nsolveA before = findSteps \"\" Set.empty before\nsolveB before = findAndCount \"\" Set.empty before 0 Set.empty\n\nfindSteps :: String -> Set Char -> Map Char (Set Char) -> String\nfindSteps res current before \n | Map.null before = reverse $ Set.toDescList current ++ res\n | Set.null current = \n let \n (reached, notReached) = Map.partition check before\n check x = Set.isSubsetOf x (Set.fromList res)\n in\n findSteps res (Map.keysSet reached) notReached\n | otherwise = \n let\n (cur, delCurrent) = Set.deleteFindMin current\n newRes = cur : res\n (reached, notReached) = Map.partition check before\n check x = Set.isSubsetOf x (Set.fromList newRes)\n \n newCurrent = Set.union delCurrent (Map.keysSet reached) \n in \n findSteps newRes newCurrent notReached\n\nwlim = 5\nnegVal = 4\n\n--Horrible. But at least it does A and B in one pass\nfindAndCount :: String -> Set Char -> Map Char (Set Char) -> Int -> Set (Int,Char) -> (String,Int)\nfindAndCount res current before sec workers\n | Map.null before && Set.null workers && Set.null current = \n (reverse res,sec - 1)\n | Map.null before && Set.null workers\n , Just (cur, delCurrent) <- Set.minView current = \n let \n newWork = fromEnum cur - negVal + sec\n newWorkers = (Set.insert (newWork, cur) workers)\n in \n findAndCount res delCurrent before sec newWorkers\n | Just ((w,c),delWork) <- Set.minView workers\n , w == sec =\n let\n newRes = c : res\n (reached, notReached) = Map.partition check before\n check x = Set.isSubsetOf x (Set.fromList newRes)\n \n newCurrent = Set.union current (Map.keysSet reached) \n in\n findAndCount newRes newCurrent notReached sec delWork\n | Set.null current && Set.null workers = \n let \n (reached, notReached) = Map.partition check before\n check x = Set.isSubsetOf x (Set.fromList res)\n newSec = if Map.null reached then sec else sec+1\n in\n findAndCount res (Map.keysSet reached) notReached newSec workers\n | Just (cur, delCurrent) <- Set.minView current\n , Set.size workers < wlim =\n let \n newWork = fromEnum cur - negVal + sec\n in \n findAndCount res delCurrent before sec (Set.insert (newWork, cur) workers)\n \n | otherwise = \n findAndCount res current before (sec+1) workers\n \n\nmain :: IO ()\nmain = do\n contents <- readFile \"data\/day7.txt\"\n let parsed = parse contents\n print $ solveA parsed\n print $ solveB parsed\n","avg_line_length":36.0425531915,"max_line_length":98,"alphanum_fraction":0.6086186541} {"size":7063,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE ApplicativeDo #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE RecordWildCards #-}\n\n-- | Command line options of Cardano node.\n\nmodule Pos.Client.CLI.NodeOptions\n ( CommonNodeArgs (..)\n , SimpleNodeArgs (..)\n , NodeArgs (..)\n , commonNodeArgsParser\n , getSimpleNodeOptions\n , usageExample\n ) where\n\nimport Universum\n\nimport Data.Version (showVersion)\nimport NeatInterpolation (text)\nimport Options.Applicative (Parser, auto, execParser, footerDoc,\n fullDesc, header, help, helper, info, infoOption, long,\n metavar, option, progDesc, strOption, switch, value)\nimport Text.PrettyPrint.ANSI.Leijen (Doc)\n\nimport Paths_cardano_sl (version)\n\nimport Pos.Client.CLI.Options (CommonArgs (..), commonArgsParser,\n optionalJSONPath)\nimport Pos.Core.NetworkAddress (NetworkAddress)\nimport Pos.Infra.HealthCheck.Route53 (route53HealthCheckOption)\nimport Pos.Infra.Network.CLI (NetworkConfigOpts, networkConfigOption)\nimport Pos.Infra.Statistics (EkgParams, StatsdParams, ekgParamsOption,\n statsdParamsOption)\nimport Pos.Util.CompileInfo (CompileTimeInfo (..), HasCompileInfo,\n compileInfo)\n\ndata CommonNodeArgs = CommonNodeArgs\n { dbPath :: !(Maybe FilePath)\n , rebuildDB :: !Bool\n , cnaAssetLockPath :: !(Maybe FilePath)\n -- these two arguments are only used in development mode\n , devGenesisSecretI :: !(Maybe Int)\n , publicKeyfilePath :: !FilePath\n , keyfilePath :: !FilePath\n , networkConfigOpts :: !NetworkConfigOpts\n -- ^ Network configuration\n , jlPath :: !(Maybe FilePath)\n , commonArgs :: !CommonArgs\n , updateLatestPath :: !FilePath\n , updateWithPackage :: !Bool\n , route53Params :: !(Maybe NetworkAddress)\n , enableMetrics :: !Bool\n , ekgParams :: !(Maybe EkgParams)\n , statsdParams :: !(Maybe StatsdParams)\n , cnaDumpGenesisDataPath :: !(Maybe FilePath)\n , cnaDumpConfiguration :: !Bool\n } deriving Show\n\ncommonNodeArgsParser :: Parser CommonNodeArgs\ncommonNodeArgsParser = do\n dbPath <- optional $ strOption $\n long \"db-path\" <>\n metavar \"FILEPATH\" <>\n help \"Path to directory with all DBs used by the node. \\\n \\If specified path doesn't exist, a directory will be created.\"\n rebuildDB <- switch $\n long \"rebuild-db\" <>\n help \"If node's database already exists, discard its contents \\\n \\and create a new one from scratch.\"\n\n cnaAssetLockPath <- optional $ strOption $\n long \"asset-lock-file\" <>\n metavar \"FILEPATH\" <>\n help \"Path to list of assetLocked source addresses. Funds at these \\\n \\addresses are not able to be spent. This will only be effective \\\n \\while Cardano is centrally mined\/minted. Addresses should be listed \\\n \\one per line. Lines beginning with '#' are comments.\"\n\n devGenesisSecretI <-\n optional $ option auto $\n long \"genesis-secret\" <>\n metavar \"INT\" <>\n help \"Used genesis secret key index.\"\n publicKeyfilePath <- strOption $\n long \"pubkeyfile\" <>\n metavar \"FILEPATH\" <>\n value \"public.key\" <>\n help \"Path to file with public key (we use it for external wallets).\"\n keyfilePath <- strOption $\n long \"keyfile\" <>\n metavar \"FILEPATH\" <>\n value \"secret.key\" <>\n help \"Path to file with secret key (we use it for Daedalus).\"\n networkConfigOpts <- networkConfigOption\n jlPath <-\n optionalJSONPath\n commonArgs <- commonArgsParser\n updateLatestPath <- strOption $\n long \"update-latest-path\" <>\n metavar \"FILEPATH\" <>\n value \"update-installer.exe\" <>\n help \"Path to update installer file, \\\n \\which should be downloaded by Update System.\"\n updateWithPackage <- switch $\n long \"update-with-package\" <>\n help \"Enable updating via installer.\"\n\n route53Params <- optional route53HealthCheckOption\n\n enableMetrics <- switch $\n long \"metrics\" <>\n help \"Enable metrics (EKG, statsd)\"\n\n ekgParams <- optional ekgParamsOption\n statsdParams <- optional statsdParamsOption\n\n cnaDumpGenesisDataPath <- optional $ strOption $\n long \"dump-genesis-data-to\" <>\n help \"Dump genesis data in canonical JSON format to this file.\"\n\n cnaDumpConfiguration <- switch $\n long \"dump-configuration\" <>\n help \"Dump configuration and exit.\"\n\n pure CommonNodeArgs{..}\n\ndata SimpleNodeArgs = SimpleNodeArgs CommonNodeArgs NodeArgs\n\ndata NodeArgs = NodeArgs\n { behaviorConfigPath :: !(Maybe FilePath)\n } deriving Show\n\nsimpleNodeArgsParser :: Parser SimpleNodeArgs\nsimpleNodeArgsParser = do\n commonNodeArgs <- commonNodeArgsParser\n behaviorConfigPath <- behaviorConfigOption\n pure $ SimpleNodeArgs commonNodeArgs NodeArgs{..}\n\nbehaviorConfigOption :: Parser (Maybe FilePath)\nbehaviorConfigOption =\n optional $ strOption $\n long \"behavior\" <>\n metavar \"FILE\" <>\n help \"Path to the behavior config\"\n\ngetSimpleNodeOptions :: HasCompileInfo => IO SimpleNodeArgs\ngetSimpleNodeOptions = execParser programInfo\n where\n programInfo = info (helper <*> versionOption <*> simpleNodeArgsParser) $\n fullDesc <> progDesc \"Cardano SL main server node.\"\n <> header \"Cardano SL node.\"\n <> footerDoc usageExample\n\n versionOption = infoOption\n (\"cardano-node-\" <> showVersion version <>\n \", git revision \" <> toString (ctiGitRevision compileInfo))\n (long \"version\" <> help \"Show version.\")\n\nusageExample :: Maybe Doc\nusageExample = (Just . fromString @Doc . toString @Text) [text|\nCommand example:\n\n stack exec -- cardano-node \\\n --db-path node-db0 \\\n --rebuild-db \\\n --keyfile secrets\/secret-1.key \\\n --kademlia-id a_P8zb6fNP7I2H54FtGuhqxaMDAwMDAwMDAwMDAwMDA= \\\n --address 127.0.0.1:3000 \\\n --listen 127.0.0.1:3000 \\\n --kademlia-address 127.0.0.1:3000 \\\n --json-log=\/tmp\/logs\/2017-05-22_181224\/node0.json \\\n --logs-prefix \/tmp\/logs\/2017-05-22_181224 \\\n --log-config \/tmp\/logs\/2017-05-22_181224\/conf\/node0.log.yaml \\\n --kademlia-dump-path \/tmp\/logs\/2017-05-22_181224\/dump\/kademlia0.dump \\\n --system-start 1495462345|]\n","avg_line_length":39.9039548023,"max_line_length":86,"alphanum_fraction":0.589834348} {"size":2606,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"{-# LANGUAGE OverloadedStrings #-}\nmodule SLang.Lexer where\n\nimport SLang.Expr\n\nimport qualified Data.Text as T\nimport Text.Parsec\nimport qualified Text.Parsec.Number as PN\nimport Text.Parsec.Text\n\nslAInt :: Parser SLExpr\nslAInt = SLInt <$> PN.int\n\nslBool :: Parser SLExpr\nslBool = SLBool <$>\n (try (string \"true\" >> return True)\n <|> try (string \"false\" >> return False))\n\nparse :: String -> T.Text -> SLProgram\nparse fname input = let res = runParser slProg () fname input\n in case res of\n Left err -> error (show err)\n Right r -> r\n\nslASymbol :: Parser SLExpr\nslASymbol = SLSymbol <$> symbol\n\nsymbol :: Parser T.Text\nsymbol = T.pack <$> strSymbol\n where strSymbol = ((:[]) <$> oneOf \"=+-*\/\") <|> (many1 letter <> many alphaNum)\n\n-- TODO: fix quoted string\nescape :: Parser String\nescape = do\n d <- char '\\\\'\n c <- oneOf \"\\\\\\\"0nrvtbf\" -- all the characters which can be escaped\n return [d, c]\n\nnonEscape :: Parser Char\nnonEscape = noneOf \"\\\\\\\"\\0\\n\\r\\v\\t\\b\\f\"\n\ncharacter :: Parser String\ncharacter = fmap return nonEscape <|> escape\n\nparseString :: Parser String\nparseString = concat <$> between (char '\"') (char '\"') (many character)\n\nslString :: Parser SLExpr\nslString = SLString . T.pack <$> parseString\n\nslAtom :: Parser SLExpr\nslAtom =\n try slAInt -- if sign is matched, this will fail, so use `try`\n <|> try slBool -- if sign is matched, this will fail, so use `try`\n <|> slString\n <|> slASymbol\n\nslExprComposite :: Parser SLExpr\nslExprComposite = between (char '(') (char ')') insideExprs\n\ninsideExprs :: Parser SLExpr\ninsideExprs = symbol >>= parseBySym\n\nparseBySym :: T.Text -> Parser SLExpr\nparseBySym \"defun\" = SLFunction <$>\n (spaces *> symbol) <*>\n (spaces *> args) <*>\n (spaces *> funcBody)\nparseBySym \"if\" = SLIf <$>\n (spaces *> slExpr) <*>\n (spaces *> slExpr) <*>\n (spaces *> slExpr)\nparseBySym \"define\" = SLDefine <$>\n (spaces *> symbol) <*>\n (spaces *> slExpr)\nparseBySym \"lambda\" = SLLambda <$>\n (spaces *> args) <*>\n (spaces *> funcBody)\nparseBySym n = SLCall n <$> many slExpr\n\nwithBrackets :: Parser a -> Parser a\nwithBrackets = between (char '(') (char ')')\n\nargs :: Parser Args\nargs = withBrackets $ symbol `sepBy` spaces\n\nfuncBody :: Parser [SLExpr]\nfuncBody = slExpr `sepBy1` spaces\n\nslExpr :: Parser SLExpr\nslExpr = withSpaces $ slExprComposite <|> slAtom\n where\n withSpaces :: Parser SLExpr -> Parser SLExpr\n withSpaces expr = spaces *> expr <* spaces\n\nslProg :: Parser SLProgram\nslProg = SLProgram <$> many1 slExpr\n","avg_line_length":26.5918367347,"max_line_length":81,"alphanum_fraction":0.6327705295} {"size":374,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Day6A where\n\nimport Data.List (delete, nub)\nimport Data.List.Split (splitOn)\nimport System.Environment (getArgs)\n\n-- Usage: runghc --ghc-arg=\"-package split\" 6a.hs inputs\/day6\nmain :: IO ()\nmain = do \n args <- getArgs;\n content <- readFile $ head args;\n\n print $ sum $ map (length . delete '\\n' . nub) $ splitOn \"\\n\\n\" content;\n return ();","avg_line_length":26.7142857143,"max_line_length":80,"alphanum_fraction":0.6229946524} {"size":165,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"module Traversal.TrieSpec where\n\nimport Test.Hspec\nimport Checks\nimport qualified Traversal.Trie\n\nspec :: Spec\nspec = parallel $ genericSpec Traversal.Trie.solver 2\n","avg_line_length":18.3333333333,"max_line_length":53,"alphanum_fraction":0.8121212121} {"size":127,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Days.Day09 (part01, part02) where\n\nimport System.IO\n\npart01 :: IO ()\npart01 = pure ()\n\n\npart02 :: IO ()\npart02 = pure ()","avg_line_length":12.7,"max_line_length":40,"alphanum_fraction":0.6456692913} {"size":10362,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE CPP #-}\n-- | General parsers, functions and datatypes for all Shakespeare languages.\nmodule Text.Shakespeare.Base\n ( Deref (..)\n , Ident (..)\n , Scope\n , parseDeref\n , parseHash\n , parseVar\n , parseVarString\n , parseAt\n , parseUrl\n , parseUrlString\n , parseCaret\n , parseUnder\n , parseInt\n , parseIntString\n , derefToExp\n , flattenDeref\n , readUtf8File\n , readUtf8FileString\n , readFileQ\n , readFileRecompileQ\n ) where\n\nimport Language.Haskell.TH.Syntax\nimport Language.Haskell.TH (appE)\nimport Data.Char (isUpper, isSymbol, isPunctuation, isAscii)\nimport Text.ParserCombinators.Parsec\nimport Text.Parsec.Prim (Parsec)\nimport Data.List (intercalate)\nimport Data.Ratio (Ratio, numerator, denominator, (%))\nimport Data.Data (Data)\nimport Data.Typeable (Typeable)\nimport qualified Data.Text.Lazy as TL\nimport qualified System.IO as SIO\nimport qualified Data.Text.Lazy.IO as TIO\nimport Control.Monad (when)\n\nnewtype Ident = Ident String\n deriving (Show, Eq, Read, Data, Typeable, Ord)\n\ntype Scope = [(Ident, Exp)]\n\ndata Deref = DerefModulesIdent [String] Ident\n | DerefIdent Ident\n | DerefIntegral Integer\n | DerefRational Rational\n | DerefString String\n | DerefBranch Deref Deref\n | DerefList [Deref]\n | DerefTuple [Deref]\n deriving (Show, Eq, Read, Data, Typeable, Ord)\n\ninstance Lift Ident where\n lift (Ident s) = [|Ident|] `appE` lift s\ninstance Lift Deref where\n lift (DerefModulesIdent v s) = do\n dl <- [|DerefModulesIdent|]\n v' <- lift v\n s' <- lift s\n return $ dl `AppE` v' `AppE` s'\n lift (DerefIdent s) = do\n dl <- [|DerefIdent|]\n s' <- lift s\n return $ dl `AppE` s'\n lift (DerefBranch x y) = do\n x' <- lift x\n y' <- lift y\n db <- [|DerefBranch|]\n return $ db `AppE` x' `AppE` y'\n lift (DerefIntegral i) = [|DerefIntegral|] `appE` lift i\n lift (DerefRational r) = do\n n <- lift $ numerator r\n d <- lift $ denominator r\n per <- [|(%) :: Int -> Int -> Ratio Int|]\n dr <- [|DerefRational|]\n return $ dr `AppE` InfixE (Just n) per (Just d)\n lift (DerefString s) = [|DerefString|] `appE` lift s\n lift (DerefList x) = [|DerefList $(lift x)|]\n lift (DerefTuple x) = [|DerefTuple $(lift x)|]\n\nderefParens, derefCurlyBrackets :: UserParser a Deref\nderefParens = between (char '(') (char ')') parseDeref\nderefCurlyBrackets = between (char '{') (char '}') parseDeref\n\nderefList, derefTuple :: UserParser a Deref\nderefList = between (char '[') (char ']') (fmap DerefList $ sepBy parseDeref (char ','))\nderefTuple = try $ do\n _ <- char '('\n x <- sepBy1 parseDeref (char ',')\n when (length x < 2) $ pzero\n _ <- char ')'\n return $ DerefTuple x\n\nparseDeref :: UserParser a Deref\nparseDeref = do\n skipMany (oneOf \" \\t\")\n derefList <|> derefTuple <|> derefOther\n where\n derefOther = do\n x <- derefSingle\n derefInfix x <|> derefPrefix x\n delim = (many1 (char ' ') >> return())\n <|> lookAhead (oneOf \"(\\\"\" >> return ())\n derefOp = try $ do\n _ <- char '('\n x <- many1 $ noneOf \" \\t\\n\\r()\"\n _ <- char ')'\n return $ DerefIdent $ Ident x\n\n -- See: http:\/\/www.haskell.org\/onlinereport\/haskell2010\/haskellch2.html#x7-160002.2\n isOperatorChar c\n | isAscii c = c `elem` \"!#$%&*+.\/<=>?@\\\\^|-~:\"\n | otherwise = isSymbol c || isPunctuation c\n\n derefPrefix x = do\n res <- deref' $ (:) x\n skipMany $ oneOf \" \\t\"\n return res\n derefInfix x = try $ do\n _ <- delim\n xs <- many $ try $ derefSingle >>= \\x' -> delim >> return x'\n op <- many1 (satisfy isOperatorChar) \"operator\"\n -- special handling for $, which we don't deal with\n when (op == \"$\") $ fail \"don't handle $\"\n let op' = DerefIdent $ Ident op\n ys <- many1 $ try $ delim >> derefSingle\n skipMany $ oneOf \" \\t\"\n return $ DerefBranch (DerefBranch op' $ foldl1 DerefBranch $ x : xs) (foldl1 DerefBranch ys)\n derefSingle = derefTuple <|> derefList <|> derefOp <|> derefParens <|> numeric <|> strLit <|> ident\n deref' lhs =\n dollar <|> derefSingle'\n <|> return (foldl1 DerefBranch $ lhs [])\n where\n dollar = do\n _ <- try $ delim >> char '$'\n rhs <- parseDeref\n let lhs' = foldl1 DerefBranch $ lhs []\n return $ DerefBranch lhs' rhs\n derefSingle' = do\n x <- try $ delim >> derefSingle\n deref' $ lhs . (:) x\n numeric = do\n n <- (char '-' >> return \"-\") <|> return \"\"\n x <- many1 digit\n y <- (char '.' >> fmap Just (many1 digit)) <|> return Nothing\n return $ case y of\n Nothing -> DerefIntegral $ read' \"Integral\" $ n ++ x\n Just z -> DerefRational $ toRational\n (read' \"Rational\" $ n ++ x ++ '.' : z :: Double)\n strLit = do\n _ <- char '\"'\n chars <- many quotedChar\n _ <- char '\"'\n return $ DerefString chars\n quotedChar = (char '\\\\' >> escapedChar) <|> noneOf \"\\\"\"\n escapedChar =\n let cecs = [('n', '\\n'), ('r', '\\r'), ('b', '\\b'), ('t', '\\t')\n ,('\\\\', '\\\\'), ('\"', '\"'), ('\\'', '\\'')]\n in choice [ char c >> return ec | (c, ec) <- cecs]\n ident = do\n mods <- many modul\n func <- many1 (alphaNum <|> char '_' <|> char '\\'')\n let func' = Ident func\n return $\n if null mods\n then DerefIdent func'\n else DerefModulesIdent mods func'\n modul = try $ do\n c <- upper\n cs <- many (alphaNum <|> char '_')\n _ <- char '.'\n return $ c : cs\n\nread' :: Read a => String -> String -> a\nread' t s =\n case reads s of\n (x, _):_ -> x\n [] -> error $ t ++ \" read failed: \" ++ s\n\nexpType :: Ident -> Name -> Exp\nexpType (Ident (c:_)) = if isUpper c || c == ':' then ConE else VarE\nexpType (Ident \"\") = error \"Bad Ident\"\n\nderefToExp :: Scope -> Deref -> Exp\nderefToExp s (DerefBranch x y) = derefToExp s x `AppE` derefToExp s y\nderefToExp _ (DerefModulesIdent mods i@(Ident s)) =\n expType i $ Name (mkOccName s) (NameQ $ mkModName $ intercalate \".\" mods)\nderefToExp scope (DerefIdent i@(Ident s)) =\n case lookup i scope of\n Just e -> e\n Nothing -> expType i $ mkName s\nderefToExp _ (DerefIntegral i) = LitE $ IntegerL i\nderefToExp _ (DerefRational r) = LitE $ RationalL r\nderefToExp _ (DerefString s) = LitE $ StringL s\nderefToExp s (DerefList ds) = ListE $ map (derefToExp s) ds\nderefToExp s (DerefTuple ds) = TupE $ map (derefToExp s) ds\n\n-- FIXME shouldn't we use something besides a list here?\nflattenDeref :: Deref -> Maybe [String]\nflattenDeref (DerefIdent (Ident x)) = Just [x]\nflattenDeref (DerefBranch (DerefIdent (Ident x)) y) = do\n y' <- flattenDeref y\n Just $ y' ++ [x]\nflattenDeref _ = Nothing\n\nparseHash :: UserParser a (Either String Deref)\nparseHash = parseVar '#'\n\ncurlyBrackets :: UserParser a String\ncurlyBrackets = do\n _<- char '{'\n var <- many1 $ noneOf \"}\"\n _<- char '}'\n return $ ('{':var) ++ \"}\"\n\n\ntype UserParser a = Parsec String a\n\nparseVar :: Char -> UserParser a (Either String Deref)\nparseVar c = do\n _ <- char c\n (char '\\\\' >> return (Left [c])) <|> (do\n deref <- derefCurlyBrackets\n return $ Right deref) <|> (do\n -- Check for hash just before newline\n _ <- lookAhead (oneOf \"\\r\\n\" >> return ()) <|> eof\n return $ Left \"\"\n ) <|> return (Left [c])\n\nparseAt :: UserParser a (Either String (Deref, Bool))\nparseAt = parseUrl '@' '?'\n\nparseUrl :: Char -> Char -> UserParser a (Either String (Deref, Bool))\nparseUrl c d = do\n _ <- char c\n (char '\\\\' >> return (Left [c])) <|> (do\n x <- (char d >> return True) <|> return False\n (do\n deref <- derefCurlyBrackets\n return $ Right (deref, x))\n <|> return (Left $ if x then [c, d] else [c]))\n\nparseInterpolatedString :: Char -> UserParser a (Either String String)\nparseInterpolatedString c = do\n _ <- char c\n (char '\\\\' >> return (Left ['\\\\', c])) <|> (do\n bracketed <- curlyBrackets\n return $ Right (c:bracketed)) <|> return (Left [c])\n\nparseVarString :: Char -> UserParser a (Either String String)\nparseVarString = parseInterpolatedString\n\nparseUrlString :: Char -> Char -> UserParser a (Either String String)\nparseUrlString c d = do\n _ <- char c\n (char '\\\\' >> return (Left [c, '\\\\'])) <|> (do\n ds <- (char d >> return [d]) <|> return []\n (do bracketed <- curlyBrackets\n return $ Right (c:ds ++ bracketed))\n <|> return (Left (c:ds)))\n\nparseIntString :: Char -> UserParser a (Either String String)\nparseIntString = parseInterpolatedString\n\nparseCaret :: UserParser a (Either String Deref)\nparseCaret = parseInt '^'\n\nparseInt :: Char -> UserParser a (Either String Deref)\nparseInt c = do\n _ <- char c\n (try $ char '\\\\' >> char '{' >> return (Left [c, '{'])) <|> (do\n deref <- derefCurlyBrackets\n return $ Right deref) <|> return (Left [c])\n\nparseUnder :: UserParser a (Either String Deref)\nparseUnder = do\n _ <- char '_'\n (char '\\\\' >> return (Left \"_\")) <|> (do\n deref <- derefCurlyBrackets\n return $ Right deref) <|> return (Left \"_\")\n\n-- | Read file's content as `String`, converting newlines\n--\n-- @since 2.0.19\nreadUtf8FileString :: FilePath -> IO String\nreadUtf8FileString fp = fmap TL.unpack $ readUtf8File fp\n\nreadUtf8File :: FilePath -> IO TL.Text\nreadUtf8File fp = do\n h <- SIO.openFile fp SIO.ReadMode\n SIO.hSetEncoding h SIO.utf8_bom\n ret <- TIO.hGetContents h \n return $\n#ifdef WINDOWS\n TL.filter ('\\r'\/=) ret\n#else\n ret\n#endif\n\n-- | Embed file's content, converting newlines\n--\n-- @since 2.0.19\nreadFileQ :: FilePath -> Q String\nreadFileQ fp = qRunIO (readUtf8FileString fp)\n\n-- | Embed file's content, converting newlines\n-- and track file via ghc dependencies, recompiling on changes\n--\n-- @since 2.0.19\nreadFileRecompileQ :: FilePath -> Q String\nreadFileRecompileQ fp = addDependentFile fp >> readFileQ fp\n","avg_line_length":32.6876971609,"max_line_length":103,"alphanum_fraction":0.5780737309} {"size":3248,"ext":"hs","lang":"Haskell","max_stars_count":6.0,"content":"{- |\nModule : Frontend.Inference.Unification\nDescription : Unification of expressions\nCopyright : (c) Danil Kolikov, 2019\nLicense : MIT\n\nFunctions for unification of expressions\n-}\nmodule Frontend.Inference.Unification where\n\nimport Data.Bifunctor (bimap)\nimport qualified Data.HashMap.Lazy as HM\nimport Data.Maybe (fromJust)\n\nimport Frontend.Desugaring.Final.Ast (Ident)\nimport Frontend.Inference.AlgebraicExp\nimport Frontend.Inference.WithVariables\nimport Frontend.Inference.Substitution\n\n-- | Unifier of algebraic expression\ntype Unifier = Either UnificationError (Substitution AlgebraicExp)\n\n-- | Errors which may be encountered during substitution\ndata UnificationError\n = UnificationErrorFunctionNameMismatch Ident\n Ident -- ^ Can't unify finctions with different names\n | UnificationErrorRecursive Ident\n AlgebraicExp -- ^ Can't unfify recursive expressions\n | UnificationErrorDifferentNumberOfArgs -- ^ Functions have different number of args\n deriving (Eq, Show)\n\n-- | Raise unification error\nraiseError :: UnificationError -> Unifier\nraiseError = Left\n\n-- | Unify equalities between objects, which can be converted to AlgebraicExp\nunifyEqualities ::\n IsAlgebraicExp a => [(a, a)] -> Either UnificationError (Substitution a)\nunifyEqualities pairs =\n let equalities = map (bimap toAlgebraicExp toAlgebraicExp) pairs\n unified = unifyAlgebraicEqualities equalities\n in HM.map (fromJust . fromAlgebraicExp) <$> unified\n\n-- | Unify a list of equalities between algebraic expressions\nunifyAlgebraicEqualities :: [(AlgebraicExp, AlgebraicExp)] -> Unifier\nunifyAlgebraicEqualities [] = return HM.empty\nunifyAlgebraicEqualities ((first, second):rest) = do\n unified <- unifySingle first second\n let substitute' = substitute unified\n substitutedRest = map (bimap substitute' substitute') rest\n unifiedRest <- unifyAlgebraicEqualities substitutedRest\n return $ unified `compose` unifiedRest\n\n-- | Unfify two single algebraic expressions\nunifySingle :: AlgebraicExp -> AlgebraicExp -> Unifier\nunifySingle (AlgebraicExpVar name) e = unifyVar name e\nunifySingle e (AlgebraicExpVar name) = unifyVar name e\nunifySingle (AlgebraicExpFunc name1 args1) (AlgebraicExpFunc name2 args2)\n | name1 == name2 = unifyArgs args1 args2\n | otherwise = raiseError $ UnificationErrorFunctionNameMismatch name1 name2\n\n-- | Unify variable with an algebraic expression\nunifyVar :: Ident -> AlgebraicExp -> Unifier\nunifyVar name e\n | e == AlgebraicExpVar name = return HM.empty\n | e `contains` name = raiseError $ UnificationErrorRecursive name e\n | otherwise = return $ HM.singleton name e\n\n-- | Unify two list of arguments of a function\nunifyArgs :: [AlgebraicExp] -> [AlgebraicExp] -> Unifier\nunifyArgs [] [] = return HM.empty\nunifyArgs (e1:rest1) (e2:rest2) = do\n unifiedExps <- unifySingle e1 e2\n let substitute' = substitute unifiedExps\n substitutedRest1 = map substitute' rest1\n substitutedRest2 = map substitute' rest2\n unifiedRest <- unifyArgs substitutedRest1 substitutedRest2\n return $ unifiedExps `compose` unifiedRest\nunifyArgs _ _ = raiseError UnificationErrorDifferentNumberOfArgs\n","avg_line_length":40.6,"max_line_length":96,"alphanum_fraction":0.7475369458} {"size":925,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ViewPatterns #-}\n-- |\n-- Copyright : 2012 Eric Kow (Computational Linguistics Ltd.)\n-- License : BSD3\n-- Maintainer : eric.kow@gmail.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Cardinality constraints\nmodule NLP.Antfarm.Cardinality where\n\nimport Data.Text ( Text )\n\ndata Constraint = AtMost Int\n | Exactly Int\n | AtLeast Int\n | Unknown Text\n deriving (Show, Eq, Ord)\n\nlowerBound :: Constraint -> Maybe Int\nlowerBound (AtLeast x) = Just x\nlowerBound (Exactly x) = Just x\nlowerBound (AtMost _) = Nothing\nlowerBound (Unknown _) = Nothing\n\nupperBound :: Constraint -> Maybe Int\nupperBound (AtLeast _) = Nothing\nupperBound (Exactly x) = Just x\nupperBound (AtMost x) = Just x\nupperBound (Unknown _) = Nothing\n\nunknown :: Constraint -> Maybe Text\nunknown (Unknown t) = Just t\nunknown _ = Nothing\n","avg_line_length":25.6944444444,"max_line_length":63,"alphanum_fraction":0.6681081081} {"size":835,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module HW1.T6\n ( epart\n , mcat\n ) where\n\n-- \u041d\u0435 Foldable \u043c\u0435\u0442\u043e\u0434\u044b \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u043d\u0435\u043b\u044c\u0437\u044f, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u044f \u0432\u044b\u0440\u0430\u0437\u0438\u043b \u0438\u0445 \u0447\u0435\u0440\u0435\u0437 Foldable--\n\n_mconcat :: Monoid a => [a] -> a\n_mconcat = foldr mappend mempty\n\n_catMaybes :: [Maybe a] -> [a]\n_catMaybes = foldr combiner mempty\n where\n combiner Nothing accum = accum\n combiner (Just x) accum = x : accum\n\nmcat :: Monoid a => [Maybe a] -> a\nmcat = _mconcat . _catMaybes\n\n_lefts :: [Either a b] -> [a]\n_lefts = foldr combiner mempty\n where\n combiner (Right _) accum = accum\n combiner (Left x) accum = x : accum\n\n_rights :: [Either a b] -> [b]\n_rights = foldr combiner mempty\n where\n combiner (Left _) accum = accum\n combiner (Right x) accum = x : accum\n\nepart :: (Monoid a, Monoid b) => [Either a b] -> (a, b)\nepart eithers = ((_mconcat . _lefts) eithers, (_mconcat . _rights) eithers)\n","avg_line_length":24.5588235294,"max_line_length":80,"alphanum_fraction":0.651497006} {"size":1119,"ext":"hs","lang":"Haskell","max_stars_count":3.0,"content":"module Days.Day6 where\n\nimport Data.List.Split\n\ninitialFishes = [0, 0, 0, 0, 0, 0, 0]\n\ninitialBreededFishes = [0, 0]\n\nfirstQuestion :: String -> IO Int\nfirstQuestion = runQuestion 80\n\nsecondQuestion :: String -> IO Int\nsecondQuestion = runQuestion 256\n\nrunQuestion :: Int -> String -> IO Int\nrunQuestion n filename = do\n ls <- readFileIntoCountList filename\n let (finalFishes, finalBreeded) =\n foldl\n (\\(fish, breed) _ -> updateDay fish breed)\n (ls, initialBreededFishes)\n [1 .. n]\n return (sum (finalFishes ++ finalBreeded))\n\nupdateDay :: [Int] -> [Int] -> ([Int], [Int])\nupdateDay (h:tail) (sev:eigh:_) = (tail ++ [sev + h], [eigh, h])\nupdateDay _ _ = error \"This should not happen\"\n\nreadFileIntoCountList :: String -> IO [Int]\nreadFileIntoCountList filename = do\n contents <- readFile filename\n let ls = (map read . splitOn \",\") contents\n return (intListToCountList ls 0)\n\nintListToCountList :: [Int] -> Int -> [Int]\nintListToCountList _ 7 = []\nintListToCountList intList n =\n (length . filter (== n)) intList : intListToCountList intList (n + 1)\n","avg_line_length":28.6923076923,"max_line_length":71,"alphanum_fraction":0.6505808758} {"size":1421,"ext":"hs","lang":"Haskell","max_stars_count":11.0,"content":"{-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE OverloadedStrings #-}\nmodule Boris.Http.Representation.Scoreboard (\n GetScoreboard (..)\n , scoreboardHtml\n ) where\n\nimport Boris.Core.Data\nimport Boris.Store.Results (Result (..))\n\nimport Data.Aeson (ToJSON (..), object, (.=))\nimport Data.Aeson.Types (Value)\n\nimport P\n\nimport Text.Blaze.Html (Html, (!))\nimport qualified Text.Blaze.Html5 as H\nimport qualified Text.Blaze.Html5.Attributes as HA\n\ndata GetScoreboard =\n GetScoreboard [Result]\n\ninstance ToJSON GetScoreboard where\n toJSON (GetScoreboard rs) =\n object [\n \"builds\" .= fmap fromResult rs\n ]\n\nfromResult :: Result -> Value\nfromResult r =\n object [\n \"build_id\" .= (renderBuildId . resultBuildId) r\n , \"project\" .= (renderProject . resultProject) r\n , \"build\" .= (renderBuild . resultBuild) r\n , \"ref\" .= (fmap renderRef . resultRef) r\n , \"result\" .= (renderBuildResult . resultBuildResult) r\n ]\n\n\nscoreboardHtml :: [Result] -> Html\nscoreboardHtml rs = let\n allOk = all ((== BuildOk) . resultBuildResult) rs\n buildClass = case allOk of\n False -> \"notOk\"\n True -> \"ok\"\n in\n H.html $ do\n H.head $ do\n H.link ! HA.rel \"stylesheet\" ! HA.type_ \"text\/css\" ! HA.href \"\/assets\/css\/scoreboard.css\"\n H.script ! HA.src \"\/assets\/js\/updateSelf.js\" $ \"\"\n H.body ! HA.class_ buildClass $ \"\"\n","avg_line_length":27.3269230769,"max_line_length":97,"alphanum_fraction":0.6277269529} {"size":1470,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as CBS\nimport Network.HTTP.Client.TLS\nimport Network.HTTP.Conduit\nimport System.Environment\nimport Test.Tasty\n\nimport Coinbase.Exchange.Types\nimport Coinbase.Exchange.Types.Core\n\nimport qualified Coinbase.Exchange.MarketData.Test as MarketData\nimport qualified Coinbase.Exchange.Private.Test as Private\nimport qualified Coinbase.Exchange.Socket.Test as Socket\n\nmain :: IO ()\nmain = do\n mgr <- newManager tlsManagerSettings\n tKey <- liftM CBS.pack $ getEnv \"COINBASE_PRO_KEY\"\n tSecret <- liftM CBS.pack $ getEnv \"COINBASE_PRO_SECRET\"\n tPass <- liftM CBS.pack $ getEnv \"COINBASE_PRO_PASSPHRASE\"\n\n sbox <- getEnv \"COINBASE_PRO_SANDBOX\"\n let apiType = case sbox of\n \"FALSE\" -> Live\n \"TRUE\" -> Sandbox\n _ -> error \"Coinbase sandbox option must be either: TRUE or FALSE (all caps)\"\n\n case mkToken tKey tSecret tPass of\n Right tok -> defaultMain (tests $ ExchangeConf mgr (Just tok) apiType)\n Left er -> error $ show er\n\ntests :: ExchangeConf -> TestTree\ntests conf = testGroup \"Tests\"\n [ MarketData.tests conf\n , Private.tests conf\n , Socket.tests conf (ProductId \"ETH-BTC\") \n ]\n","avg_line_length":35.0,"max_line_length":107,"alphanum_fraction":0.619047619} {"size":819,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"module Yesod.FeedTypes\n ( Feed (..)\n , FeedEntry (..)\n ) where\n\nimport Text.Hamlet (Html)\nimport Data.Time.Clock (UTCTime)\nimport Data.Text (Text)\n\n-- | The overall feed\ndata Feed url = Feed\n { feedTitle :: Text\n , feedLinkSelf :: url\n , feedLinkHome :: url\n , feedAuthor :: Text\n\n\n -- | note: currently only used for Rss\n , feedDescription :: Html\n\n -- | note: currently only used for Rss, possible values: \n -- \n , feedLanguage :: Text\n\n , feedUpdated :: UTCTime\n , feedEntries :: [FeedEntry url]\n }\n\n-- | Each feed entry\ndata FeedEntry url = FeedEntry\n { feedEntryLink :: url\n , feedEntryUpdated :: UTCTime\n , feedEntryTitle :: Text\n , feedEntryContent :: Html\n }\n","avg_line_length":22.75,"max_line_length":61,"alphanum_fraction":0.5873015873} {"size":1335,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE TypeFamilies #-}\n\n-- | This module provides signed and unsigned binary word data types of sizes\n-- 2, 3, 4, 5, 6, 7, 24, and 48 bits.\nmodule Data.ShortWord\n ( module Data.BinaryWord\n , Word2\n , aWord2\n , Word3\n , aWord3\n , Word4\n , aWord4\n , Word5\n , aWord5\n , Word6\n , aWord6\n , Word7\n , aWord7\n , Word24\n , aWord24\n , Word48\n , aWord48\n , Int2\n , anInt2\n , Int3\n , anInt3\n , Int4\n , anInt4\n , Int5\n , anInt5\n , Int6\n , anInt6\n , Int7\n , anInt7\n , Int24\n , anInt24\n , Int48\n , anInt48\n ) where\n\nimport Data.Word\nimport Data.BinaryWord\nimport Data.ShortWord.TH\n\nmkShortWord \"Word2\" \"Word2\" \"aWord2\" \"Int2\" \"Int2\" \"anInt2\" ''Word8 2 []\nmkShortWord \"Word3\" \"Word3\" \"aWord3\" \"Int3\" \"Int3\" \"anInt3\" ''Word8 3 []\nmkShortWord \"Word4\" \"Word4\" \"aWord4\" \"Int4\" \"Int4\" \"anInt4\" ''Word8 4 []\nmkShortWord \"Word5\" \"Word5\" \"aWord5\" \"Int5\" \"Int5\" \"anInt5\" ''Word8 5 []\nmkShortWord \"Word6\" \"Word6\" \"aWord6\" \"Int6\" \"Int6\" \"anInt6\" ''Word8 6 []\nmkShortWord \"Word7\" \"Word7\" \"aWord7\" \"Int7\" \"Int7\" \"anInt7\" ''Word8 7 []\nmkShortWord \"Word24\" \"Word24\" \"aWord24\" \"Int24\" \"Int24\" \"anInt24\"\n ''Word32 24 []\nmkShortWord \"Word48\" \"Word48\" \"aWord48\" \"Int48\" \"Int48\" \"anInt48\"\n ''Word64 48 []\n","avg_line_length":23.0172413793,"max_line_length":77,"alphanum_fraction":0.6254681648} {"size":15484,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"-- | The CEK machine.\n-- Rules are the same as for the CK machine except we do not use substitution and use\n-- environments instead.\n-- The CEK machine relies on variables having non-equal 'Unique's whenever they have non-equal\n-- string names. I.e. 'Unique's are used instead of string names. This is for efficiency reasons.\n-- The type checker pass is a prerequisite.\n-- Feeding ill-typed terms to the CEK machine will likely result in a 'MachineException'.\n-- The CEK machine generates booleans along the way which might contain globally non-unique 'Unique's.\n-- This is not a problem as the CEK machines handles name capture by design.\n-- Dynamic extensions to the set of built-ins are allowed.\n-- In case an unknown dynamic built-in is encountered, an 'UnknownDynamicBuiltinNameError' is returned\n-- (wrapped in 'OtherMachineError').\n\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule Language.PlutusCore.Evaluation.Machine.Cek\n ( EvaluationResult(..)\n , EvaluationResultDef\n , ErrorWithCause(..)\n , MachineError(..)\n , CekMachineException\n , EvaluationError(..)\n , CekUserError(..)\n , CekEvaluationException\n , ExBudgetState(..)\n , ExTally(..)\n , ExBudget(..)\n , ExRestrictingBudget(..)\n , ExBudgetMode(..)\n , Plain\n , WithMemory\n , extractEvaluationResult\n , cekEnvMeans\n , cekEnvVarEnv\n , exBudgetStateTally\n , exBudgetStateBudget\n , exBudgetCPU\n , exBudgetMemory\n , runCek\n , runCekCounting\n , evaluateCek\n , unsafeEvaluateCek\n , readKnownCek\n )\nwhere\n\nimport PlutusPrelude\n\nimport Language.PlutusCore.Constant\nimport Language.PlutusCore.Core\nimport Language.PlutusCore.Error\nimport Language.PlutusCore.Evaluation.Machine.ExBudgeting\nimport Language.PlutusCore.Evaluation.Machine.Exception\nimport Language.PlutusCore.Evaluation.Machine.ExMemory\nimport Language.PlutusCore.Evaluation.Result\nimport Language.PlutusCore.Name\nimport Language.PlutusCore.Pretty\nimport Language.PlutusCore.Universe\nimport Language.PlutusCore.View\n\nimport Control.Lens.Operators\nimport Control.Lens.Setter\nimport Control.Lens.TH (makeLenses)\nimport Control.Monad.Except\nimport Control.Monad.Reader\nimport Control.Monad.State.Strict\nimport Data.HashMap.Monoidal\nimport qualified Data.Map as Map\nimport Data.Text.Prettyprint.Doc\n\ndata CekUserError\n = CekOutOfExError ExRestrictingBudget ExBudget\n | CekEvaluationFailure -- ^ Error has been called.\n deriving (Show, Eq)\n\n-- | The CEK machine-specific 'MachineException'.\ntype CekMachineException uni = MachineException uni UnknownDynamicBuiltinNameError\n\n-- | The CEK machine-specific 'EvaluationException'.\ntype CekEvaluationException uni = EvaluationException uni UnknownDynamicBuiltinNameError CekUserError\n\ninstance Pretty CekUserError where\n pretty (CekOutOfExError (ExRestrictingBudget res) b) =\n group $ \"The limit\" <+> prettyClassicDef res <+> \"was reached by the execution environment. Final state:\" <+> prettyClassicDef b\n pretty CekEvaluationFailure = \"The provided Plutus code called 'error'.\"\n\n-- | A 'Value' packed together with the environment it's defined in.\ndata Closure uni = Closure\n { _closureVarEnv :: VarEnv uni\n , _closureValue :: WithMemory Value uni\n }\n\n-- | Variable environments used by the CEK machine.\n-- Each row is a mapping from the 'Unique' representing a variable to a 'Closure'.\ntype VarEnv uni = UniqueMap TermUnique (Closure uni)\n\n-- | The environment the CEK machine runs in.\ndata CekEnv uni = CekEnv\n { _cekEnvMeans :: DynamicBuiltinNameMeanings uni\n , _cekEnvVarEnv :: VarEnv uni\n , _cekEnvBudgetMode :: ExBudgetMode\n }\n\nmakeLenses ''CekEnv\n\n-- | The monad the CEK machine runs in. State is inside the ExceptT, so we can\n-- get it back in case of error.\ntype CekM uni = ReaderT (CekEnv uni) (ExceptT (CekEvaluationException uni) (State ExBudgetState))\n\ninstance SpendBudget (CekM uni) uni where\n spendBudget key term budget = do\n modifying exBudgetStateTally\n (<> (ExTally (singleton key budget)))\n newBudget <- exBudgetStateBudget <%= (<> budget)\n mode <- view cekEnvBudgetMode\n case mode of\n Counting -> pure ()\n Restricting resb ->\n when (exceedsBudget resb newBudget) $\n throwingWithCause _EvaluationError (UserEvaluationError (CekOutOfExError resb newBudget)) (Just $ void term)\n\ndata Frame uni\n = FrameApplyFun (VarEnv uni) (WithMemory Value uni) -- ^ @[V _]@\n | FrameApplyArg (VarEnv uni) (WithMemory Term uni) -- ^ @[_ N]@\n | FrameTyInstArg (Type TyName uni ExMemory) -- ^ @{_ A}@\n | FrameUnwrap -- ^ @(unwrap _)@\n | FrameIWrap ExMemory (Type TyName uni ExMemory) (Type TyName uni ExMemory) -- ^ @(iwrap A B _)@\n\ntype Context uni = [Frame uni]\n\nrunCekM\n :: forall a uni\n . CekEnv uni\n -> ExBudgetState\n -> CekM uni a\n -> (Either (CekEvaluationException uni) a, ExBudgetState)\nrunCekM env s a = runState (runExceptT $ runReaderT a env) s\n\n-- | Get the current 'VarEnv'.\ngetVarEnv :: CekM uni (VarEnv uni)\ngetVarEnv = asks _cekEnvVarEnv\n\n-- | Set a new 'VarEnv' and proceed.\nwithVarEnv :: VarEnv uni -> CekM uni a -> CekM uni a\nwithVarEnv venv = local (set cekEnvVarEnv venv)\n\n-- | Extend an environment with a variable name, the value the variable stands for\n-- and the environment the value is defined in.\nextendVarEnv :: Name ExMemory -> WithMemory Value uni -> VarEnv uni -> VarEnv uni -> VarEnv uni\nextendVarEnv argName arg argVarEnv =\n insertByName argName $ Closure argVarEnv arg\n\n-- | Look up a variable name in the environment.\nlookupVarName :: Name ExMemory -> CekM uni (Closure uni)\nlookupVarName varName = do\n varEnv <- getVarEnv\n case lookupName varName varEnv of\n Nothing -> throwingWithCause _MachineError\n OpenTermEvaluatedMachineError\n (Just . Var () $ void varName)\n Just clos -> pure clos\n\n-- | Look up a 'DynamicBuiltinName' in the environment.\nlookupDynamicBuiltinName :: DynamicBuiltinName -> CekM uni (DynamicBuiltinNameMeaning uni)\nlookupDynamicBuiltinName dynName = do\n DynamicBuiltinNameMeanings means <- asks _cekEnvMeans\n case Map.lookup dynName means of\n Nothing -> throwingWithCause _MachineError err $ Just term where\n err = OtherMachineError $ UnknownDynamicBuiltinNameErrorE dynName\n term = Builtin () $ DynBuiltinName () dynName\n Just mean -> pure mean\n\n-- | The computing part of the CEK machine.\n-- Either\n-- 1. adds a frame to the context and calls 'computeCek' ('TyInst', 'Apply', 'IWrap', 'Unwrap')\n-- 2. calls 'returnCek' on values ('TyAbs', 'LamAbs', 'Constant')\n-- 3. returns 'EvaluationFailure' ('Error')\n-- 4. looks up a variable in the environment and calls 'returnCek' ('Var')\ncomputeCek\n :: (GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage)\n => Context uni -> WithMemory Term uni -> CekM uni (Plain Term uni)\ncomputeCek con t@(TyInst _ body ty) = do\n spendBudget BTyInst t (ExBudget 1 1) -- TODO\n computeCek (FrameTyInstArg ty : con) body\ncomputeCek con t@(Apply _ fun arg) = do\n spendBudget BApply t (ExBudget 1 1) -- TODO\n varEnv <- getVarEnv\n computeCek (FrameApplyArg varEnv arg : con) fun\ncomputeCek con t@(IWrap ann pat arg term) = do\n spendBudget BIWrap t (ExBudget 1 1) -- TODO\n computeCek (FrameIWrap ann pat arg : con) term\ncomputeCek con t@(Unwrap _ term) = do\n spendBudget BUnwrap t (ExBudget 1 1) -- TODO\n computeCek (FrameUnwrap : con) term\ncomputeCek con tyAbs@TyAbs{} = returnCek con tyAbs\ncomputeCek con lamAbs@LamAbs{} = returnCek con lamAbs\ncomputeCek con constant@Constant{} = returnCek con constant\ncomputeCek con bi@Builtin{} = returnCek con bi\ncomputeCek _ err@Error{} =\n throwingWithCause _EvaluationError (UserEvaluationError CekEvaluationFailure) $ Just (void err)\ncomputeCek con t@(Var _ varName) = do\n spendBudget BVar t (ExBudget 1 1) -- TODO\n Closure newVarEnv term <- lookupVarName varName\n withVarEnv newVarEnv $ returnCek con term\n\n-- | The returning part of the CEK machine.\n-- Returns 'EvaluationSuccess' in case the context is empty, otherwise pops up one frame\n-- from the context and either\n-- 1. performs reduction and calls 'computeCek' ('FrameTyInstArg', 'FrameApplyFun', 'FrameUnwrap')\n-- 2. performs a constant application and calls 'returnCek' ('FrameTyInstArg', 'FrameApplyFun')\n-- 3. puts 'FrameApplyFun' on top of the context and proceeds with the argument from 'FrameApplyArg'\n-- 4. grows the resulting term ('FrameWrap')\nreturnCek\n :: (GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage)\n => Context uni -> WithMemory Value uni -> CekM uni (Plain Term uni)\nreturnCek [] res = pure $ void res\nreturnCek (FrameTyInstArg ty : con) fun = instantiateEvaluate con ty fun\nreturnCek (FrameApplyArg argVarEnv arg : con) fun = do\n funVarEnv <- getVarEnv\n withVarEnv argVarEnv $ computeCek (FrameApplyFun funVarEnv fun : con) arg\nreturnCek (FrameApplyFun funVarEnv fun : con) arg = do\n argVarEnv <- getVarEnv\n applyEvaluate funVarEnv argVarEnv con fun arg\nreturnCek (FrameIWrap ann pat arg : con) val =\n returnCek con $ IWrap ann pat arg val\nreturnCek (FrameUnwrap : con) dat = case dat of\n IWrap _ _ _ term -> returnCek con term\n term ->\n throwingWithCause _MachineError NonWrapUnwrappedMachineError $ Just (void term)\n\n-- | Instantiate a term with a type and proceed.\n-- In case of 'TyAbs' just ignore the type. Otherwise check if the term is an\n-- iterated application of a 'BuiltinName' to a list of 'Value's and, if succesful,\n-- apply the term to the type via 'TyInst'.\ninstantiateEvaluate\n :: (GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage)\n => Context uni -> Type TyName uni ExMemory -> WithMemory Term uni -> CekM uni (Plain Term uni)\ninstantiateEvaluate con _ (TyAbs _ _ _ body) = computeCek con body\ninstantiateEvaluate con ty fun\n | isJust $ termAsPrimIterApp fun = returnCek con $ TyInst (memoryUsage () <> memoryUsage fun <> memoryUsage ty) fun ty\n | otherwise =\n throwingWithCause _MachineError NonPrimitiveInstantiationMachineError $ Just (void fun)\n\n-- | Apply a function to an argument and proceed.\n-- If the function is a 'LamAbs', then extend the current environment with a new variable and proceed.\n-- If the function is not a 'LamAbs', then 'Apply' it to the argument and view this\n-- as an iterated application of a 'BuiltinName' to a list of 'Value's.\n-- If succesful, proceed with either this same term or with the result of the computation\n-- depending on whether 'BuiltinName' is saturated or not.\napplyEvaluate\n :: (GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage)\n => VarEnv uni\n -> VarEnv uni\n -> Context uni\n -> WithMemory Value uni\n -> WithMemory Value uni\n -> CekM uni (Plain Term uni)\napplyEvaluate funVarEnv argVarEnv con (LamAbs _ name _ body) arg =\n withVarEnv (extendVarEnv name arg argVarEnv funVarEnv) $ computeCek con body\napplyEvaluate funVarEnv _ con fun arg =\n let term = Apply (memoryUsage () <> memoryUsage fun <> memoryUsage arg) fun arg in\n case termAsPrimIterApp term of\n Nothing ->\n throwingWithCause _MachineError NonPrimitiveApplicationMachineError $ Just (void term)\n Just (IterApp headName spine) -> do\n constAppResult <- applyStagedBuiltinName headName spine\n withVarEnv funVarEnv $ case constAppResult of\n ConstAppSuccess res -> computeCek con res\n ConstAppStuck -> returnCek con term\n\n-- | Reduce a saturated application of a builtin function in the empty context.\ncomputeInCekM\n :: (GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage)\n => EvaluateConstApp uni (CekM uni) ann -> CekM uni (ConstAppResult uni ann)\ncomputeInCekM = runEvaluateT eval where\n eval means' = local (over cekEnvMeans $ mappend means') . computeCek [] . withMemory\n\n-- | Apply a 'StagedBuiltinName' to a list of 'Value's.\napplyStagedBuiltinName\n :: (GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage)\n => StagedBuiltinName\n -> [WithMemory Value uni]\n -> CekM uni (ConstAppResult uni ExMemory)\napplyStagedBuiltinName n@(DynamicStagedBuiltinName name) args = do\n DynamicBuiltinNameMeaning sch x exX <- lookupDynamicBuiltinName name\n computeInCekM $ applyTypeSchemed\n n\n sch\n x\n exX\n args\napplyStagedBuiltinName (StaticStagedBuiltinName name) args =\n computeInCekM $ applyBuiltinName\n name\n args\n\n-- | Evaluate a term using the CEK machine and keep track of costing.\nrunCek\n :: (GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage)\n => DynamicBuiltinNameMeanings uni\n -> ExBudgetMode\n -> Plain Term uni\n -> (Either (CekEvaluationException uni) (Plain Term uni), ExBudgetState)\nrunCek means mode term =\n runCekM (CekEnv means mempty mode)\n (ExBudgetState mempty mempty)\n $ do\n spendBudget BAST memTerm (ExBudget 0 (termAnn memTerm))\n computeCek [] memTerm\n where\n memTerm = withMemory term\n\n-- | Evaluate a term using the CEK machine in the 'Counting' mode.\nrunCekCounting\n :: (GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage)\n => DynamicBuiltinNameMeanings uni\n -> Plain Term uni\n -> (Either (CekEvaluationException uni) (Plain Term uni), ExBudgetState)\nrunCekCounting means = runCek means Counting\n\n-- | Evaluate a term using the CEK machine.\nevaluateCek\n :: (GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage)\n => DynamicBuiltinNameMeanings uni\n -> Plain Term uni\n -> Either (CekEvaluationException uni) (Plain Term uni)\nevaluateCek means = fst . runCekCounting means\n\n-- | Evaluate a term using the CEK machine. May throw a 'CekMachineException'.\nunsafeEvaluateCek\n :: ( GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage\n , Typeable uni, uni `Everywhere` Pretty\n )\n => DynamicBuiltinNameMeanings uni -> Plain Term uni -> EvaluationResultDef uni\nunsafeEvaluateCek means = either throw id . extractEvaluationResult . evaluateCek means\n\n-- | Unlift a value using the CEK machine.\nreadKnownCek\n :: ( GShow uni, GEq uni, DefaultUni <: uni, Closed uni, uni `Everywhere` ExMemoryUsage\n , KnownType uni a\n )\n => DynamicBuiltinNameMeanings uni\n -> Plain Term uni\n -> Either (CekEvaluationException uni) a\nreadKnownCek = readKnownBy evaluateCek\n","avg_line_length":43.7401129944,"max_line_length":136,"alphanum_fraction":0.6903254973} {"size":2168,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE RankNTypes, ScopedTypeVariables #-}\n\nmodule Data.Foldable.Tricks where\n \nimport Prelude hiding (dropWhile, zipWith, head)\nimport Data.Foldable\nimport qualified Data.Map.Strict as Map\nimport Data.Strict.Pair\nimport Data.Strict.Counter\nimport GHC.Base (build)\nimport Data.Foldable.Safe\nimport Data.Functor.Compose\nimport Data.Bifunctor\nimport Data.Coerce.Helpers\nimport Data.Function\nimport Control.Arrow ((***), app)\nimport Data.Monoid\nimport Data.Functor.Compose\n\ndropWhile :: Foldable f => (a -> Bool) -> f a -> [a]\ndropWhile p ls = build c where\n c (-:) e = foldr f (const e) ls True where\n f a r b = if b && p a then r True else a -: r False\n\nmostFrequent :: (Ord a, Foldable f) => f a -> Maybe a\nmostFrequent = head . Compose .# fmap Compose .# foldl' f (Map.empty :!: Nothing) where\n f (m :!: b) e = Map.insert e c m :!: max b (Just (c :# e)) where\n c = maybe 1 succ (Map.lookup e m)\n\nnewtype Fold a = Fold { runFold :: forall b. (a -> b -> b) -> b -> b }\n\ntoFold :: Foldable f => f a -> Fold a\ntoFold xs = Fold (\\f b -> foldr f b xs)\n\ntoFold' :: Foldable f => f a -> UnwrappedFold a\ntoFold' xs f b = foldr f b xs\n\ntype UnwrappedFold a = forall b. (a -> b -> b) -> b -> b\n\nnewtype Zip a b = Zip { unZip :: forall w. (a -> b -> w) -> w -> w }\n\nl2 :: (a -> b -> c -> c) -> c -> UnwrappedFold a -> Fold b -> c\nl2 c b xs ys = xs f (const b) ys where\n f e r (Fold l) = unZip (l tailZip nilZip) (step e r) b\n nilZip = Zip (const id)\n step e1 r1 e2 r2 = c e1 e2 (r1 r2)\n tailZip n (Zip z) = Zip (\\a _ -> a n (Fold l)) where\n l g i = z h i where\n h t (Fold x) = g t (x g i)\n \nfoldr2 :: (Foldable f, Foldable g) => (a -> b -> c -> c) -> c -> f a -> g b -> c\nfoldr2 f b xs ys = l2 f b (toFold' xs) (toFold ys)\n\nzipWith :: (Foldable f, Foldable g) => (a -> b -> c) -> f a -> g b -> [c]\nzipWith c xs ys = build (\\cons nil -> foldr2 (\\x y -> cons (c x y)) nil xs ys)\n\nunzipWith :: Foldable f => (a -> (b,c)) -> f a -> ([b],[c])\nunzipWith f = foldr (uncurry bimap . bimap (:) (:) . f) ([],[])\n\npartitionWith :: Foldable f => (a -> Either b c) -> f a -> ([b],[c])\npartitionWith f = foldr (either first second . bimap (:) (:) . f) ([],[])","avg_line_length":35.5409836066,"max_line_length":87,"alphanum_fraction":0.5899446494} {"size":44433,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"-- |\n-- Module : Streamly.Internal.Data.Fold.Type\n-- Copyright : (c) 2019 Composewell Technologies\n-- (c) 2013 Gabriel Gonzalez\n-- License : BSD3\n-- Maintainer : streamly@composewell.com\n-- Stability : experimental\n-- Portability : GHC\n--\n-- = Stream Consumers\n--\n-- We can classify stream consumers in the following categories in order of\n-- increasing complexity and power:\n--\n-- == Accumulators\n--\n-- These are the simplest folds that never fail and never terminate, they\n-- accumulate the input values forever and can always accept new inputs (never\n-- terminate) and always have a valid result value. A\n-- 'Streamly.Internal.Data.Fold.sum' operation is an example of an accumulator.\n-- Traditional Haskell left folds like 'foldl' are accumulators.\n--\n-- We can distribute an input stream to two or more accumulators using a @tee@\n-- style composition. Accumulators cannot be applied on a stream one after the\n-- other, which we call a @serial@ append style composition of folds. This is\n-- because accumulators never terminate, since the first accumulator in a\n-- series will never terminate, the next one will never get to run.\n--\n-- == Terminating Folds\n--\n-- Terminating folds are accumulators that can terminate. Once a fold\n-- terminates it no longer accepts any more inputs. Terminating folds can be\n-- used in a @serial@ append style composition where one fold can be applied\n-- after the other on an input stream. We can apply a terminating fold\n-- repeatedly on an input stream, splitting the stream and consuming it in\n-- fragments. Terminating folds never fail, therefore, they do not need\n-- backtracking.\n--\n-- The 'Streamly.Internal.Data.Fold.take' operation is an example of a\n-- terminating fold It terminates after consuming @n@ items. Coupled with an\n-- accumulator (e.g. sum) it can be used to split and process the stream into\n-- chunks of fixed size.\n--\n-- == Terminating Folds with Leftovers\n--\n-- The next upgrade after terminating folds is terminating folds with leftover\n-- inputs. Consider the example of @takeWhile@ operation, it needs to inspect\n-- an element for termination decision. However, it does not consume the\n-- element on which it terminates. To implement @takeWhile@ a terminating fold\n-- will have to implement a way to return unconsumed input to the fold driver.\n--\n-- Single element leftover case is the most common and its easy to implement it\n-- in terminating folds using a @Done1@ constructor in the 'Step' type which\n-- indicates that the last element was not consumed by the fold. The following\n-- additional operations can be implemented as terminating folds if we do that.\n--\n-- @\n-- takeWhile\n-- groupBy\n-- wordBy\n-- @\n--\n-- However, it creates several complications. The 'many' combinator requires\n-- a @Partial1@ ('Partial' with leftover) to handle a @Done1@ from the top\n-- level fold, for efficient implementation. If the collecting fold in \"many\"\n-- returns a @Partial1@ or @Done1@ then what to do with all the elements that\n-- have been consumed?\n--\n-- Similarly, in distribute, if one fold consumes a value and others say its a\n-- leftover then what do we do? Folds like \"many\" require the leftover to be\n-- fed to it again. So in a distribute operation those folds which gave a\n-- leftover will have to be fed the leftover while the folds that consumed will\n-- have to be fed the next input. This is very complicated to implement. We\n-- have the same issue in backtracking parsers being used in a distribute\n-- operation.\n--\n-- To avoid these issues we want to enforce by typing that the collecting folds\n-- can never return a leftover. So we need a fold type without @Done1@ or\n-- @Partial1@. This leads us to design folds to never return a leftover and the\n-- use cases of single leftover are transferred to parsers where we have\n-- general backtracking mechanism and single leftover is just a special case of\n-- backtracking.\n--\n-- This means: takeWhile, groupBy, wordBy would be implemented as parsers.\n-- \"take 0\" can implemented as a fold if we make initial return @Step@ type.\n-- \"takeInterval\" can be implemented without @Done1@.\n--\n-- == Parsers\n--\n-- The next upgrade after terminating folds with a leftover are parsers.\n-- Parsers are terminating folds that can fail and backtrack. Parsers can be\n-- composed using an @alternative@ style composition where they can backtrack\n-- and apply another parser if one parser fails.\n-- 'Streamly.Internal.Data.Parser.satisfy' is a simple example of a parser, it\n-- would succeed if the condition is satisfied and it would fail otherwise, on\n-- failure an alternative parser can be used on the same input.\n--\n-- = Types for Stream Consumers\n--\n-- In streamly, there is no separate type for accumulators. Terminating folds\n-- are a superset of accumulators and to avoid too many types we represent both\n-- using the same type, 'Fold'.\n--\n-- We do not club the leftovers functionality with terminating folds because of\n-- the reasons explained earlier. Instead combinators that require leftovers\n-- are implemented as the 'Streamly.Internal.Data.Parser.Parser' type. This is\n-- a sweet spot to balance ease of use, type safety and performance. Using\n-- separate Accumulator and terminating fold types would encode more\n-- information in types but it would make ease of use, implementation,\n-- maintenance effort worse. Combining Accumulator, terminating folds and\n-- Parser into a single 'Streamly.Internal.Data.Parser.Parser' type would make\n-- ease of use even better but type safety and performance worse.\n--\n-- One of the design requirements that we have placed for better ease of use\n-- and code reuse is that 'Streamly.Internal.Data.Parser.Parser' type should be\n-- a strict superset of the 'Fold' type i.e. it can do everything that a 'Fold'\n-- can do and more. Therefore, folds can be easily upgraded to parsers and we\n-- can use parser combinators on folds as well when needed.\n--\n-- = Fold Design\n--\n-- A fold is represented by a collection of \"initial\", \"step\" and \"extract\"\n-- functions. The \"initial\" action generates the initial state of the fold. The\n-- state is internal to the fold and maintains the accumulated output. The\n-- \"step\" function is invoked using the current state and the next input value\n-- and results in a @Partial@ or @Done@. A @Partial@ returns the next intermediate\n-- state of the fold, a @Done@ indicates that the fold has terminated and\n-- returns the final value of the accumulator.\n--\n-- Every @Partial@ indicates that a new accumulated output is available. The\n-- accumulated output can be extracted from the state at any point using\n-- \"extract\". \"extract\" can never fail. A fold returns a valid output even\n-- without any input i.e. even if you call \"extract\" on \"initial\" state it\n-- provides an output. This is not true for parsers.\n--\n-- In general, \"extract\" is used in two cases:\n--\n-- * When the fold is used as a scan @extract@ is called on the intermediate\n-- state every time it is yielded by the fold, the resulting value is yielded\n-- as a stream.\n-- * When the fold is used as a regular fold, @extract@ is called once when\n-- we are done feeding input to the fold.\n--\n-- = Alternate Designs\n--\n-- An alternate and simpler design would be to return the intermediate output\n-- via @Partial@ along with the state, instead of using \"extract\" on the yielded\n-- state and remove the extract function altogether.\n--\n-- This may even facilitate more efficient implementation. Extract from the\n-- intermediate state after each yield may be more costly compared to the fold\n-- step itself yielding the output. The fold may have more efficient ways to\n-- retrieve the output rather than stuffing it in the state and using extract\n-- on the state.\n--\n-- However, removing extract altogether may lead to less optimal code in some\n-- cases because the driver of the fold needs to thread around the intermediate\n-- output to return it if the stream stops before the fold could @Done@. When\n-- using this approach, the @parseMany (FL.take filesize)@ benchmark shows a\n-- 2x worse performance even after ensuring everything fuses. So we keep the\n-- \"extract\" approach to ensure better perf in all cases.\n--\n-- But we could still yield both state and the output in @Partial@, the output\n-- can be used for the scan use case, instead of using extract. Extract would\n-- then be used only for the case when the stream stops before the fold\n-- completes.\n--\n-- = Accumulators and Terminating Folds\n--\n-- Folds in this module can be classified in two categories viz. accumulators\n-- and terminating folds. Accumulators do not have a terminating condition,\n-- they run forever and consume the entire stream, for example the 'length'\n-- fold. Terminating folds have a terminating condition and can terminate\n-- without consuming the entire stream, for example, the 'head' fold.\n--\n-- = Monoids\n--\n-- Monoids allow generalized, modular folding. The accumulators in this module\n-- can be expressed using 'mconcat' and a suitable 'Monoid'. Instead of\n-- writing folds we can write Monoids and turn them into folds.\n--\n-- = Performance Notes\n--\n-- 'Streamly.Prelude' module provides fold functions to directly fold streams\n-- e.g. Streamly.Prelude\/'Streamly.Prelude.sum' serves the same purpose as\n-- Fold\/'sum'. However, the functions in Streamly.Prelude cannot be\n-- efficiently combined together e.g. we cannot drive the input stream through\n-- @sum@ and @length@ fold functions simultaneously. Using the 'Fold' type we\n-- can efficiently split the stream across multiple folds because it allows the\n-- compiler to perform stream fusion optimizations.\n--\nmodule Streamly.Internal.Data.Fold.Type\n (\n -- * Types\n Step (..)\n , Fold (..)\n\n -- * Constructors\n , foldl'\n , foldlM'\n , foldl1'\n , foldr\n , foldrM\n , mkFold\n , mkFold_\n , mkFoldM\n , mkFoldM_\n\n -- * Folds\n , fromPure\n , fromEffect\n , drain\n , toList\n\n -- * Combinators\n\n -- ** Mapping output\n , rmapM\n\n -- ** Mapping Input\n , map\n , lmap\n , lmapM\n\n -- ** Filtering\n , filter\n , filterM\n , catMaybes\n\n -- ** Trimming\n , take\n , takeInterval\n\n -- ** Serial Append\n , serialWith\n , serial_\n\n -- ** Parallel Distribution\n , GenericRunner(..)\n , teeWith\n , teeWithFst\n , teeWithMin\n\n -- ** Parallel Alternative\n , shortest\n , longest\n\n -- ** Splitting\n , ManyState\n , many\n , manyPost\n , chunksOf\n , intervalsOf\n\n -- ** Nesting\n , concatMap\n\n -- * Running Partially\n , duplicate\n , initialize\n , runStep\n\n -- * Fold2\n , Fold2 (..)\n , simplify\n , chunksOf2\n )\nwhere\n\nimport Control.Monad (void, (>=>))\nimport Control.Concurrent (threadDelay, forkIO, killThread)\nimport Control.Concurrent.MVar (MVar, newMVar, swapMVar, readMVar)\nimport Control.Exception (SomeException(..), catch, mask)\nimport Control.Monad.IO.Class (MonadIO(..))\nimport Control.Monad.Trans.Control (control)\nimport Data.Bifunctor (Bifunctor(..))\nimport Data.Maybe (isJust, fromJust)\nimport Fusion.Plugin.Types (Fuse(..))\nimport Streamly.Internal.Data.Maybe.Strict (Maybe'(..), toMaybe)\nimport Streamly.Internal.Data.Tuple.Strict (Tuple'(..), Tuple3'(..))\nimport Streamly.Internal.Data.SVar (MonadAsync)\n\nimport Prelude hiding (concatMap, filter, foldr, map, take)\n\n-- $setup\n-- >>> :m\n-- >>> import Prelude hiding (concatMap, filter, map)\n-- >>> import qualified Streamly.Prelude as Stream\n-- >>> import qualified Streamly.Data.Fold as Fold\n-- >>> import qualified Streamly.Internal.Data.Fold as Fold\n\n------------------------------------------------------------------------------\n-- Step of a fold\n------------------------------------------------------------------------------\n\n-- The Step functor around b allows expressing early termination like a right\n-- fold. Traditional list right folds use function composition and laziness to\n-- terminate early whereas we use data constructors. It allows stream fusion in\n-- contrast to the foldr\/build fusion when composing with functions.\n\n-- | Represents the result of the @step@ of a 'Fold'. 'Partial' returns an\n-- intermediate state of the fold, the fold step can be called again with the\n-- state or the driver can use @extract@ on the state to get the result out.\n-- 'Done' returns the final result and the fold cannot be driven further.\n--\n-- \/Pre-release\/\n--\n{-# ANN type Step Fuse #-}\ndata Step s b\n = Partial !s\n | Done !b\n\n-- | 'first' maps over 'Partial' and 'second' maps over 'Done'.\n--\ninstance Bifunctor Step where\n {-# INLINE bimap #-}\n bimap f _ (Partial a) = Partial (f a)\n bimap _ g (Done b) = Done (g b)\n\n {-# INLINE first #-}\n first f (Partial a) = Partial (f a)\n first _ (Done x) = Done x\n\n {-# INLINE second #-}\n second _ (Partial x) = Partial x\n second f (Done a) = Done (f a)\n\n-- | 'fmap' maps over 'Done'.\n--\n-- @\n-- fmap = 'second'\n-- @\n--\ninstance Functor (Step s) where\n {-# INLINE fmap #-}\n fmap = second\n\n-- | Map a monadic function over the result @b@ in @Step s b@.\n--\n-- \/Internal\/\n{-# INLINE mapMStep #-}\nmapMStep :: Applicative m => (a -> m b) -> Step s a -> m (Step s b)\nmapMStep f res =\n case res of\n Partial s -> pure $ Partial s\n Done b -> Done <$> f b\n\n------------------------------------------------------------------------------\n-- The Fold type\n------------------------------------------------------------------------------\n\n-- | The type @Fold m a b@ having constructor @Fold step initial extract@\n-- represents a fold over an input stream of values of type @a@ to a final\n-- value of type @b@ in 'Monad' @m@.\n--\n-- The fold uses an intermediate state @s@ as accumulator, the type @s@ is\n-- internal to the specific fold definition. The initial value of the fold\n-- state @s@ is returned by @initial@. The @step@ function consumes an input\n-- and either returns the final result @b@ if the fold is done or the next\n-- intermediate state (see 'Step'). At any point the fold driver can extract\n-- the result from the intermediate state using the @extract@ function.\n--\n-- NOTE: The constructor is not yet exposed via exposed modules, smart\n-- constructors are provided to create folds. If you think you need the\n-- constructor of this type please consider using the smart constructors in\n-- \"Streamly.Internal.Data.Fold\" instead.\n--\n-- \/since 0.8.0 (type changed)\/\n--\n-- @since 0.7.0\n\ndata Fold m a b =\n -- | @Fold @ @ step @ @ initial @ @ extract@\n forall s. Fold (s -> a -> m (Step s b)) (m (Step s b)) (s -> m b)\n\n------------------------------------------------------------------------------\n-- Mapping on the output\n------------------------------------------------------------------------------\n\n-- | Map a monadic function on the output of a fold.\n--\n-- @since 0.8.0\n{-# INLINE rmapM #-}\nrmapM :: Monad m => (b -> m c) -> Fold m a b -> Fold m a c\nrmapM f (Fold step initial extract) = Fold step1 initial1 (extract >=> f)\n\n where\n\n initial1 = initial >>= mapMStep f\n step1 s a = step s a >>= mapMStep f\n\n------------------------------------------------------------------------------\n-- Left fold constructors\n------------------------------------------------------------------------------\n\n-- | Make a fold from a left fold style pure step function and initial value of\n-- the accumulator.\n--\n-- If your 'Fold' returns only 'Partial' (i.e. never returns a 'Done') then you\n-- can use @foldl'*@ constructors.\n--\n-- A fold with an extract function can be expressed using fmap:\n--\n-- @\n-- mkfoldlx :: Monad m => (s -> a -> s) -> s -> (s -> b) -> Fold m a b\n-- mkfoldlx step initial extract = fmap extract (foldl' step initial)\n-- @\n--\n-- See also: @Streamly.Prelude.foldl'@\n--\n-- @since 0.8.0\n--\n{-# INLINE foldl' #-}\nfoldl' :: Monad m => (b -> a -> b) -> b -> Fold m a b\nfoldl' step initial =\n Fold\n (\\s a -> return $ Partial $ step s a)\n (return (Partial initial))\n return\n\n-- | Make a fold from a left fold style monadic step function and initial value\n-- of the accumulator.\n--\n-- A fold with an extract function can be expressed using rmapM:\n--\n-- @\n-- mkFoldlxM :: Functor m => (s -> a -> m s) -> m s -> (s -> m b) -> Fold m a b\n-- mkFoldlxM step initial extract = rmapM extract (foldlM' step initial)\n-- @\n--\n-- See also: @Streamly.Prelude.foldlM'@\n--\n-- @since 0.8.0\n--\n{-# INLINE foldlM' #-}\nfoldlM' :: Monad m => (b -> a -> m b) -> m b -> Fold m a b\nfoldlM' step initial =\n Fold (\\s a -> Partial <$> step s a) (Partial <$> initial) return\n\n-- | Make a strict left fold, for non-empty streams, using first element as the\n-- starting value. Returns Nothing if the stream is empty.\n--\n-- See also: @Streamly.Prelude.foldl1'@\n--\n-- \/Pre-release\/\n{-# INLINE foldl1' #-}\nfoldl1' :: Monad m => (a -> a -> a) -> Fold m a (Maybe a)\nfoldl1' step = fmap toMaybe $ foldl' step1 Nothing'\n\n where\n\n step1 Nothing' a = Just' a\n step1 (Just' x) a = Just' $ step x a\n\n------------------------------------------------------------------------------\n-- Right fold constructors\n------------------------------------------------------------------------------\n\n-- | Make a fold using a right fold style step function and a terminal value.\n-- It performs a strict right fold via a left fold using function composition.\n-- Note that this is strict fold, it can only be useful for constructing strict\n-- structures in memory. For reductions this will be very inefficient.\n--\n-- For example,\n--\n-- > toList = foldr (:) []\n--\n-- See also: 'Streamly.Prelude.foldr'\n--\n-- @since 0.8.0\n{-# INLINE foldr #-}\nfoldr :: Monad m => (a -> b -> b) -> b -> Fold m a b\nfoldr g z = fmap ($ z) $ foldl' (\\f x -> f . g x) id\n\n-- XXX we have not seen any use of this yet, not releasing until we have a use\n-- case.\n--\n-- | Like 'foldr' but with a monadic step function.\n--\n-- For example,\n--\n-- > toList = foldrM (\\a xs -> return $ a : xs) (return [])\n--\n-- See also: 'Streamly.Prelude.foldrM'\n--\n-- \/Pre-release\/\n{-# INLINE foldrM #-}\nfoldrM :: Monad m => (a -> b -> m b) -> m b -> Fold m a b\nfoldrM g z =\n rmapM (z >>=) $ foldlM' (\\f x -> return $ g x >=> f) (return return)\n\n------------------------------------------------------------------------------\n-- General fold constructors\n------------------------------------------------------------------------------\n\n-- XXX If the Step yield gives the result each time along with the state then\n-- we can make the type of this as\n--\n-- mkFold :: Monad m => (s -> a -> Step s b) -> Step s b -> Fold m a b\n--\n-- Then similar to foldl' and foldr we can just fmap extract on it to extend\n-- it to the version where an 'extract' function is required. Or do we even\n-- need that?\n--\n-- Until we investigate this we are not releasing these.\n\n-- | Make a terminating fold using a pure step function, a pure initial state\n-- and a pure state extraction function.\n--\n-- \/Pre-release\/\n--\n{-# INLINE mkFold #-}\nmkFold :: Monad m => (s -> a -> Step s b) -> Step s b -> (s -> b) -> Fold m a b\nmkFold step initial extract =\n Fold (\\s a -> return $ step s a) (return initial) (return . extract)\n\n-- | Similar to 'mkFold' but the final state extracted is identical to the\n-- intermediate state.\n--\n-- @\n-- mkFold_ step initial = mkFold step initial id\n-- @\n--\n-- \/Pre-release\/\n--\n{-# INLINE mkFold_ #-}\nmkFold_ :: Monad m => (b -> a -> Step b b) -> Step b b -> Fold m a b\nmkFold_ step initial = mkFold step initial id\n\n-- | Make a terminating fold with an effectful step function and initial state,\n-- and a state extraction function.\n--\n-- > mkFoldM = Fold\n--\n-- We can just use 'Fold' but it is provided for completeness.\n--\n-- \/Pre-release\/\n--\n{-# INLINE mkFoldM #-}\nmkFoldM :: (s -> a -> m (Step s b)) -> m (Step s b) -> (s -> m b) -> Fold m a b\nmkFoldM = Fold\n\n-- | Similar to 'mkFoldM' but the final state extracted is identical to the\n-- intermediate state.\n--\n-- @\n-- mkFoldM_ step initial = mkFoldM step initial return\n-- @\n--\n-- \/Pre-release\/\n--\n{-# INLINE mkFoldM_ #-}\nmkFoldM_ :: Monad m => (b -> a -> m (Step b b)) -> m (Step b b) -> Fold m a b\nmkFoldM_ step initial = mkFoldM step initial return\n\n------------------------------------------------------------------------------\n-- Fold2\n------------------------------------------------------------------------------\n\n-- | Experimental type to provide a side input to the fold for generating the\n-- initial state. For example, if we have to fold chunks of a stream and write\n-- each chunk to a different file, then we can generate the file name using a\n-- monadic action. This is a generalized version of 'Fold'.\n--\n-- \/Internal\/\ndata Fold2 m c a b =\n -- | @Fold @ @ step @ @ inject @ @ extract@\n forall s. Fold2 (s -> a -> m s) (c -> m s) (s -> m b)\n\n-- | Convert more general type 'Fold2' into a simpler type 'Fold'\n--\n-- \/Internal\/\nsimplify :: Functor m => Fold2 m c a b -> c -> Fold m a b\nsimplify (Fold2 step inject extract) c =\n Fold (\\x a -> Partial <$> step x a) (Partial <$> inject c) extract\n\n------------------------------------------------------------------------------\n-- Basic Folds\n------------------------------------------------------------------------------\n\n-- | A fold that drains all its input, running the effects and discarding the\n-- results.\n--\n-- > drain = drainBy (const (return ()))\n--\n-- @since 0.7.0\n{-# INLINABLE drain #-}\ndrain :: Monad m => Fold m a ()\ndrain = foldl' (\\_ _ -> ()) ()\n\n-- | Folds the input stream to a list.\n--\n-- \/Warning!\/ working on large lists accumulated as buffers in memory could be\n-- very inefficient, consider using \"Streamly.Data.Array.Foreign\"\n-- instead.\n--\n-- > toList = foldr (:) []\n--\n-- @since 0.7.0\n{-# INLINABLE toList #-}\ntoList :: Monad m => Fold m a [a]\ntoList = foldr (:) []\n\n------------------------------------------------------------------------------\n-- Instances\n------------------------------------------------------------------------------\n\n-- | Maps a function on the output of the fold (the type @b@).\ninstance Functor m => Functor (Fold m a) where\n {-# INLINE fmap #-}\n fmap f (Fold step1 initial1 extract) = Fold step initial (fmap2 f extract)\n\n where\n\n initial = fmap2 f initial1\n step s b = fmap2 f (step1 s b)\n fmap2 g = fmap (fmap g)\n\n-- This is the dual of stream \"fromPure\".\n--\n-- | A fold that always yields a pure value without consuming any input.\n--\n-- \/Pre-release\/\n--\n{-# INLINE fromPure #-}\nfromPure :: Applicative m => b -> Fold m a b\nfromPure b = Fold undefined (pure $ Done b) pure\n\n-- This is the dual of stream \"fromEffect\".\n--\n-- | A fold that always yields the result of an effectful action without\n-- consuming any input.\n--\n-- \/Pre-release\/\n--\n{-# INLINE fromEffect #-}\nfromEffect :: Applicative m => m b -> Fold m a b\nfromEffect b = Fold undefined (Done <$> b) pure\n\n{-# ANN type Step Fuse #-}\ndata SeqFoldState sl f sr = SeqFoldL !sl | SeqFoldR !f !sr\n\n-- | Sequential fold application. Apply two folds sequentially to an input\n-- stream. The input is provided to the first fold, when it is done - the\n-- remaining input is provided to the second fold. When the second fold is done\n-- or if the input stream is over, the outputs of the two folds are combined\n-- using the supplied function.\n--\n-- >>> f = Fold.serialWith (,) (Fold.take 8 Fold.toList) (Fold.takeEndBy (== '\\n') Fold.toList)\n-- >>> Stream.fold f $ Stream.fromList \"header: hello\\n\"\n-- (\"header: \",\"hello\\n\")\n--\n-- Note: This is dual to appending streams using 'Streamly.Prelude.serial'.\n--\n-- Note: this implementation allows for stream fusion but has quadratic time\n-- complexity, because each composition adds a new branch that each subsequent\n-- fold's input element has to traverse, therefore, it cannot scale to a large\n-- number of compositions. After around 100 compositions the performance starts\n-- dipping rapidly compared to a CPS style implementation.\n--\n-- \/Time: O(n^2) where n is the number of compositions.\/\n--\n-- @since 0.8.0\n--\n{-# INLINE serialWith #-}\nserialWith :: Monad m => (a -> b -> c) -> Fold m x a -> Fold m x b -> Fold m x c\nserialWith func (Fold stepL initialL extractL) (Fold stepR initialR extractR) =\n Fold step initial extract\n\n where\n\n initial = do\n resL <- initialL\n case resL of\n Partial sl -> return $ Partial $ SeqFoldL sl\n Done bl -> do\n resR <- initialR\n return $ bimap (SeqFoldR (func bl)) (func bl) resR\n\n step (SeqFoldL st) a = do\n r <- stepL st a\n case r of\n Partial s -> return $ Partial (SeqFoldL s)\n Done b -> do\n res <- initialR\n return $ bimap (SeqFoldR (func b)) (func b) res\n step (SeqFoldR f st) a = do\n r <- stepR st a\n return\n $ case r of\n Partial s -> Partial (SeqFoldR f s)\n Done b -> Done (f b)\n\n extract (SeqFoldR f sR) = fmap f (extractR sR)\n extract (SeqFoldL sL) = do\n rL <- extractL sL\n res <- initialR\n case res of\n Partial sR -> do\n rR <- extractR sR\n return $ func rL rR\n Done rR -> return $ func rL rR\n\n-- | Same as applicative '*>'. Run two folds serially one after the other\n-- discarding the result of the first.\n--\n-- \/Unimplemented\/\n--\n{-# INLINE serial_ #-}\nserial_ :: -- Monad m =>\n Fold m x a -> Fold m x b -> Fold m x b\nserial_ _f1 _f2 = undefined\n\n{-# ANN type GenericRunner Fuse #-}\ndata GenericRunner sL sR bL bR\n = RunBoth !sL !sR\n | RunLeft !sL !bR\n | RunRight !bL !sR\n\n-- | @teeWith k f1 f2@ distributes its input to both @f1@ and @f2@ until both\n-- of them terminate and combines their output using @k@.\n--\n-- >>> avg = Fold.teeWith (\/) Fold.sum (fmap fromIntegral Fold.length)\n-- >>> Stream.fold avg $ Stream.fromList [1.0..100.0]\n-- 50.5\n--\n-- > teeWith k f1 f2 = fmap (uncurry k) ((Fold.tee f1 f2)\n--\n-- For applicative composition using this combinator see\n-- \"Streamly.Internal.Data.Fold.Tee\".\n--\n-- See also: \"Streamly.Internal.Data.Fold.Tee\"\n--\n-- @since 0.8.0\n--\n{-# INLINE teeWith #-}\nteeWith :: Monad m => (a -> b -> c) -> Fold m x a -> Fold m x b -> Fold m x c\nteeWith f (Fold stepL beginL doneL) (Fold stepR beginR doneR) =\n Fold step begin done\n\n where\n\n begin = do\n resL <- beginL\n resR <- beginR\n return\n $ case resL of\n Partial sl ->\n Partial\n $ case resR of\n Partial sr -> RunBoth sl sr\n Done br -> RunLeft sl br\n Done bl -> bimap (RunRight bl) (f bl) resR\n\n step (RunBoth sL sR) a = do\n resL <- stepL sL a\n resR <- stepR sR a\n case resL of\n Partial sL1 ->\n return\n $ Partial\n $ case resR of\n Partial sR1 -> RunBoth sL1 sR1\n Done bR -> RunLeft sL1 bR\n Done bL ->\n return\n $ case resR of\n Partial sR1 -> Partial $ RunRight bL sR1\n Done bR -> Done $ f bL bR\n step (RunLeft sL bR) a = do\n resL <- stepL sL a\n return\n $ case resL of\n Partial sL1 -> Partial $ RunLeft sL1 bR\n Done bL -> Done $ f bL bR\n step (RunRight bL sR) a = do\n resR <- stepR sR a\n return\n $ case resR of\n Partial sR1 -> Partial $ RunRight bL sR1\n Done bR -> Done $ f bL bR\n\n done (RunBoth sL sR) = do\n bL <- doneL sL\n bR <- doneR sR\n return $ f bL bR\n done (RunLeft sL bR) = do\n bL <- doneL sL\n return $ f bL bR\n done (RunRight bL sR) = do\n bR <- doneR sR\n return $ f bL bR\n\n-- | Like 'teeWith' but terminates as soon as the first fold terminates.\n--\n-- \/Unimplemented\/\n--\n{-# INLINE teeWithFst #-}\nteeWithFst :: (b -> c -> d) -> Fold m a b -> Fold m a c -> Fold m a d\nteeWithFst = undefined\n\n-- | Like 'teeWith' but terminates as soon as any one of the two folds\n-- terminates.\n--\n-- \/Unimplemented\/\n--\n{-# INLINE teeWithMin #-}\nteeWithMin :: (b -> c -> d) -> Fold m a b -> Fold m a c -> Fold m a d\nteeWithMin = undefined\n\n-- | Shortest alternative. Apply both folds in parallel but choose the result\n-- from the one which consumed least input i.e. take the shortest succeeding\n-- fold.\n--\n-- \/Unimplemented\/\n--\n{-# INLINE shortest #-}\nshortest :: -- Monad m =>\n Fold m x a -> Fold m x a -> Fold m x a\nshortest _f1 _f2 = undefined\n\n-- | Longest alternative. Apply both folds in parallel but choose the result\n-- from the one which consumed more input i.e. take the longest succeeding\n-- fold.\n--\n-- \/Unimplemented\/\n--\n{-# INLINE longest #-}\nlongest :: -- Monad m =>\n Fold m x a -> Fold m x a -> Fold m x a\nlongest _f1 _f2 = undefined\n\ndata ConcatMapState m sa a c\n = B !sa\n | forall s. C (s -> a -> m (Step s c)) !s (s -> m c)\n\n-- Compare with foldIterate.\n--\n-- | Map a 'Fold' returning function on the result of a 'Fold' and run the\n-- returned fold. This operation can be used to express data dependencies\n-- between fold operations.\n--\n-- Let's say the first element in the stream is a count of the following\n-- elements that we have to add, then:\n--\n-- >>> import Data.Maybe (fromJust)\n-- >>> count = fmap fromJust Fold.head\n-- >>> total n = Fold.take n Fold.sum\n-- >>> Stream.fold (Fold.concatMap total count) $ Stream.fromList [10,9..1]\n-- 45\n--\n-- \/Time: O(n^2) where @n@ is the number of compositions.\/\n--\n-- See also: 'Streamly.Internal.Data.Stream.IsStream.foldIterateM'\n--\n-- @since 0.8.0\n--\n{-# INLINE concatMap #-}\nconcatMap :: Monad m => (b -> Fold m a c) -> Fold m a b -> Fold m a c\nconcatMap f (Fold stepa initiala extracta) = Fold stepc initialc extractc\n where\n initialc = do\n r <- initiala\n case r of\n Partial s -> return $ Partial (B s)\n Done b -> initInnerFold (f b)\n\n stepc (B s) a = do\n r <- stepa s a\n case r of\n Partial s1 -> return $ Partial (B s1)\n Done b -> initInnerFold (f b)\n\n stepc (C stepInner s extractInner) a = do\n r <- stepInner s a\n return $ case r of\n Partial sc -> Partial (C stepInner sc extractInner)\n Done c -> Done c\n\n extractc (B s) = do\n r <- extracta s\n initExtract (f r)\n extractc (C _ sInner extractInner) = extractInner sInner\n\n initInnerFold (Fold step i e) = do\n r <- i\n return $ case r of\n Partial s -> Partial (C step s e)\n Done c -> Done c\n\n initExtract (Fold _ i e) = do\n r <- i\n case r of\n Partial s -> e s\n Done c -> return c\n\n------------------------------------------------------------------------------\n-- Mapping on input\n------------------------------------------------------------------------------\n\n-- | @lmap f fold@ maps the function @f@ on the input of the fold.\n--\n-- >>> Stream.fold (Fold.lmap (\\x -> x * x) Fold.sum) (Stream.enumerateFromTo 1 100)\n-- 338350\n--\n-- > lmap = Fold.lmapM return\n--\n-- @since 0.8.0\n{-# INLINABLE lmap #-}\nlmap :: (a -> b) -> Fold m b r -> Fold m a r\nlmap f (Fold step begin done) = Fold step' begin done\n where\n step' x a = step x (f a)\n\n-- XXX should be removed\n-- |\n-- \/Internal\/\n{-# INLINE map #-}\nmap :: (a -> b) -> Fold m b r -> Fold m a r\nmap = lmap\n\n-- | @lmapM f fold@ maps the monadic function @f@ on the input of the fold.\n--\n-- @since 0.8.0\n{-# INLINABLE lmapM #-}\nlmapM :: Monad m => (a -> m b) -> Fold m b r -> Fold m a r\nlmapM f (Fold step begin done) = Fold step' begin done\n where\n step' x a = f a >>= step x\n\n------------------------------------------------------------------------------\n-- Filtering\n------------------------------------------------------------------------------\n\n-- | Include only those elements that pass a predicate.\n--\n-- >>> Stream.fold (Fold.filter (> 5) Fold.sum) $ Stream.fromList [1..10]\n-- 40\n--\n-- > filter f = Fold.filterM (return . f)\n--\n-- @since 0.8.0\n{-# INLINABLE filter #-}\nfilter :: Monad m => (a -> Bool) -> Fold m a r -> Fold m a r\nfilter f (Fold step begin done) = Fold step' begin done\n where\n step' x a = if f a then step x a else return $ Partial x\n\n-- | Like 'filter' but with a monadic predicate.\n--\n-- @since 0.8.0\n{-# INLINABLE filterM #-}\nfilterM :: Monad m => (a -> m Bool) -> Fold m a r -> Fold m a r\nfilterM f (Fold step begin done) = Fold step' begin done\n where\n step' x a = do\n use <- f a\n if use then step x a else return $ Partial x\n\n-- | Modify a fold to receive a 'Maybe' input, the 'Just' values are unwrapped\n-- and sent to the original fold, 'Nothing' values are discarded.\n--\n-- @since 0.8.0\n{-# INLINE catMaybes #-}\ncatMaybes :: Monad m => Fold m a b -> Fold m (Maybe a) b\ncatMaybes = filter isJust . map fromJust\n\n------------------------------------------------------------------------------\n-- Parsing\n------------------------------------------------------------------------------\n\n-- | Take at most @n@ input elements and fold them using the supplied fold. A\n-- negative count is treated as 0.\n--\n-- >>> Stream.fold (Fold.take 2 Fold.toList) $ Stream.fromList [1..10]\n-- [1,2]\n--\n-- @since 0.8.0\n{-# INLINE take #-}\ntake :: Monad m => Int -> Fold m a b -> Fold m a b\ntake n (Fold fstep finitial fextract) = Fold step initial extract\n\n where\n\n initial = do\n res <- finitial\n case res of\n Partial s ->\n if n > 0\n then return $ Partial $ Tuple' 0 s\n else Done <$> fextract s\n Done b -> return $ Done b\n\n step (Tuple' i r) a = do\n res <- fstep r a\n case res of\n Partial sres -> do\n let i1 = i + 1\n s1 = Tuple' i1 sres\n if i1 < n\n then return $ Partial s1\n else Done <$> fextract sres\n Done bres -> return $ Done bres\n\n extract (Tuple' _ r) = fextract r\n\n------------------------------------------------------------------------------\n-- Nesting\n------------------------------------------------------------------------------\n\n-- | Modify the fold such that it returns a new 'Fold' instead of the output.\n-- If the fold was already done the returned fold would always yield the\n-- result. If the fold was partial, the returned fold starts from where we left\n-- i.e. it uses the last accumulator value as the initial value of the\n-- accumulator. Thus we can resume the fold later and feed it more input.\n--\n-- >>> :{\n-- do\n-- more <- Stream.fold (Fold.duplicate Fold.sum) (Stream.enumerateFromTo 1 10)\n-- evenMore <- Stream.fold (Fold.duplicate more) (Stream.enumerateFromTo 11 20)\n-- Stream.fold evenMore (Stream.enumerateFromTo 21 30)\n-- :}\n-- 465\n--\n-- \/Pre-release\/\n{-# INLINABLE duplicate #-}\nduplicate :: Monad m => Fold m a b -> Fold m a (Fold m a b)\nduplicate (Fold step1 initial1 extract1) =\n Fold step initial (\\s -> pure $ Fold step1 (pure $ Partial s) extract1)\n\n where\n\n initial = second fromPure <$> initial1\n\n step s a = second fromPure <$> step1 s a\n\n-- | Run the initialization effect of a fold. The returned fold would use the\n-- value returned by this effect as its initial value.\n--\n-- \/Pre-release\/\n{-# INLINE initialize #-}\ninitialize :: Monad m => Fold m a b -> m (Fold m a b)\ninitialize (Fold step initial extract) = do\n i <- initial\n return $ Fold step (return i) extract\n\n-- | Run one step of a fold and store the accumulator as an initial value in\n-- the returned fold.\n--\n-- \/Pre-release\/\n{-# INLINE runStep #-}\nrunStep :: Monad m => Fold m a b -> a -> m (Fold m a b)\nrunStep (Fold step initial extract) a = do\n res <- initial\n r <- case res of\n Partial fs -> step fs a\n b@(Done _) -> return b\n return $ Fold step (return r) extract\n\n------------------------------------------------------------------------------\n-- Parsing\n------------------------------------------------------------------------------\n\n-- All the grouping transformation that we apply to a stream can also be\n-- applied to a fold input stream. groupBy et al can be written as terminating\n-- folds and then we can apply \"many\" to use those repeatedly on a stream.\n\n{-# ANN type ManyState Fuse #-}\ndata ManyState s1 s2\n = ManyFirst !s1 !s2\n | ManyLoop !s1 !s2\n\n-- | Collect zero or more applications of a fold. @many split collect@ applies\n-- the @split@ fold repeatedly on the input stream and accumulates zero or more\n-- fold results using @collect@.\n--\n-- >>> two = Fold.take 2 Fold.toList\n-- >>> twos = Fold.many two Fold.toList\n-- >>> Stream.fold twos $ Stream.fromList [1..10]\n-- [[1,2],[3,4],[5,6],[7,8],[9,10]]\n--\n-- Stops when @collect@ stops.\n--\n-- See also: 'Streamly.Prelude.concatMap', 'Streamly.Prelude.foldMany'\n--\n-- @since 0.8.0\n--\n{-# INLINE many #-}\nmany :: Monad m => Fold m a b -> Fold m b c -> Fold m a c\nmany (Fold sstep sinitial sextract) (Fold cstep cinitial cextract) =\n Fold step initial extract\n\n where\n\n -- cs = collect state\n -- ss = split state\n -- cres = collect state result\n -- sres = split state result\n -- cb = collect done\n -- sb = split done\n\n -- Caution! There is mutual recursion here, inlining the right functions is\n -- important.\n\n {-# INLINE handleSplitStep #-}\n handleSplitStep branch cs sres =\n case sres of\n Partial ss1 -> return $ Partial $ branch ss1 cs\n Done sb -> runCollector ManyFirst cs sb\n\n {-# INLINE handleCollectStep #-}\n handleCollectStep branch cres =\n case cres of\n Partial cs -> do\n sres <- sinitial\n handleSplitStep branch cs sres\n Done cb -> return $ Done cb\n\n -- Do not inline this\n runCollector branch cs sb = cstep cs sb >>= handleCollectStep branch\n\n initial = cinitial >>= handleCollectStep ManyFirst\n\n {-# INLINE step_ #-}\n step_ ss cs a = do\n sres <- sstep ss a\n handleSplitStep ManyLoop cs sres\n\n {-# INLINE step #-}\n step (ManyFirst ss cs) a = step_ ss cs a\n step (ManyLoop ss cs) a = step_ ss cs a\n\n extract (ManyFirst _ cs) = cextract cs\n extract (ManyLoop ss cs) = do\n sb <- sextract ss\n cres <- cstep cs sb\n case cres of\n Partial s -> cextract s\n Done b -> return b\n\n-- | Like many, but inner fold emits an output at the end even if no input is\n-- received.\n--\n-- \/Internal\/\n--\n-- \/See also: 'Streamly.Prelude.concatMap', 'Streamly.Prelude.foldMany'\/\n--\n{-# INLINE manyPost #-}\nmanyPost :: Monad m => Fold m a b -> Fold m b c -> Fold m a c\nmanyPost (Fold sstep sinitial sextract) (Fold cstep cinitial cextract) =\n Fold step initial extract\n\n where\n\n -- cs = collect state\n -- ss = split state\n -- cres = collect state result\n -- sres = split state result\n -- cb = collect done\n -- sb = split done\n\n -- Caution! There is mutual recursion here, inlining the right functions is\n -- important.\n\n {-# INLINE handleSplitStep #-}\n handleSplitStep cs sres =\n case sres of\n Partial ss1 -> return $ Partial $ Tuple' ss1 cs\n Done sb -> runCollector cs sb\n\n {-# INLINE handleCollectStep #-}\n handleCollectStep cres =\n case cres of\n Partial cs -> do\n sres <- sinitial\n handleSplitStep cs sres\n Done cb -> return $ Done cb\n\n -- Do not inline this\n runCollector cs sb = cstep cs sb >>= handleCollectStep\n\n initial = cinitial >>= handleCollectStep\n\n {-# INLINE step #-}\n step (Tuple' ss cs) a = do\n sres <- sstep ss a\n handleSplitStep cs sres\n\n extract (Tuple' ss cs) = do\n sb <- sextract ss\n cres <- cstep cs sb\n case cres of\n Partial s -> cextract s\n Done b -> return b\n\n-- | @chunksOf n split collect@ repeatedly applies the @split@ fold to chunks\n-- of @n@ items in the input stream and supplies the result to the @collect@\n-- fold.\n--\n-- >>> twos = Fold.chunksOf 2 Fold.toList Fold.toList\n-- >>> Stream.fold twos $ Stream.fromList [1..10]\n-- [[1,2],[3,4],[5,6],[7,8],[9,10]]\n--\n-- > chunksOf n split = many (take n split)\n--\n-- Stops when @collect@ stops.\n--\n-- @since 0.8.0\n--\n{-# INLINE chunksOf #-}\nchunksOf :: Monad m => Int -> Fold m a b -> Fold m b c -> Fold m a c\nchunksOf n split = many (take n split)\n\n-- |\n--\n-- \/Internal\/\n{-# INLINE chunksOf2 #-}\nchunksOf2 :: Monad m => Int -> Fold m a b -> Fold2 m x b c -> Fold2 m x a c\nchunksOf2 n (Fold step1 initial1 extract1) (Fold2 step2 inject2 extract2) =\n Fold2 step' inject' extract'\n\n where\n\n loopUntilPartial s = do\n res <- initial1\n case res of\n Partial fs -> return $ Tuple3' 0 fs s\n Done _ -> loopUntilPartial s\n\n inject' x = inject2 x >>= loopUntilPartial\n\n step' (Tuple3' i r1 r2) a =\n if i < n\n then do\n res <- step1 r1 a\n case res of\n Partial s -> return $ Tuple3' (i + 1) s r2\n Done b -> step2 r2 b >>= loopUntilPartial\n else extract1 r1 >>= step2 r2 >>= loopUntilPartial\n\n extract' (Tuple3' _ r1 r2) = extract1 r1 >>= step2 r2 >>= extract2\n\n-- XXX We can use asyncClock here. A parser can be used to return an input that\n-- arrives after the timeout.\n-- XXX If n is 0 return immediately in initial.\n-- XXX we should probably discard the input received after the timeout like\n-- takeEndBy_.\n--\n-- | @takeInterval n fold@ uses @fold@ to fold the input items arriving within\n-- a window of first @n@ seconds.\n--\n-- >>> Stream.fold (Fold.takeInterval 1.0 Fold.toList) $ Stream.delay 0.1 $ Stream.fromList [1..]\n-- [1,2,3,4,5,6,7,8,9,10,11]\n--\n-- Stops when @fold@ stops or when the timeout occurs. Note that the fold needs\n-- an input after the timeout to stop. For example, if no input is pushed to\n-- the fold until one hour after the timeout had occurred, then the fold will\n-- be done only after consuming that input.\n--\n-- \/Pre-release\/\n--\n{-# INLINE takeInterval #-}\ntakeInterval :: MonadAsync m => Double -> Fold m a b -> Fold m a b\ntakeInterval n (Fold step initial done) = Fold step' initial' done'\n\n where\n\n initial' = do\n res <- initial\n case res of\n Partial s -> do\n mv <- liftIO $ newMVar False\n t <-\n control $ \\run ->\n mask $ \\restore -> do\n tid <-\n forkIO\n $ catch\n (restore $ void $ run (timerThread mv))\n (handleChildException mv)\n run (return tid)\n return $ Partial $ Tuple3' s mv t\n Done b -> return $ Done b\n\n step' (Tuple3' s mv t) a = do\n val <- liftIO $ readMVar mv\n if val\n then do\n res <- step s a\n case res of\n Partial sres -> Done <$> done sres\n Done bres -> return $ Done bres\n else do\n res <- step s a\n case res of\n Partial fs -> return $ Partial $ Tuple3' fs mv t\n Done b -> liftIO (killThread t) >> return (Done b)\n\n done' (Tuple3' s _ _) = done s\n\n timerThread mv = do\n liftIO $ threadDelay (round $ n * 1000000)\n -- Use IORef + CAS? instead of MVar since its a Bool?\n liftIO $ void $ swapMVar mv True\n\n handleChildException :: MVar Bool -> SomeException -> IO ()\n handleChildException mv _ = void $ swapMVar mv True\n\n-- For example, we can copy and distribute a stream to multiple folds where\n-- each fold can group the input differently e.g. by one second, one minute and\n-- one hour windows respectively and fold each resulting stream of folds.\n\n-- | Group the input stream into windows of n second each using the first fold\n-- and then fold the resulting groups using the second fold.\n--\n-- >>> intervals = Fold.intervalsOf 0.5 Fold.toList Fold.toList\n-- >>> Stream.fold intervals $ Stream.delay 0.2 $ Stream.fromList [1..10]\n-- [[1,2,3,4],[5,6,7],[8,9,10]]\n--\n-- > intervalsOf n split = many (takeInterval n split)\n--\n-- \/Pre-release\/\n--\n{-# INLINE intervalsOf #-}\nintervalsOf :: MonadAsync m => Double -> Fold m a b -> Fold m b c -> Fold m a c\nintervalsOf n split = many (takeInterval n split)\n","avg_line_length":33.4837980407,"max_line_length":97,"alphanum_fraction":0.6020525285} {"size":3383,"ext":"hs","lang":"Haskell","max_stars_count":119.0,"content":"-- |\n-- Module: Clocks\n-- Description: Clocks based on a base period and phase\n-- Copyright: (c) 2011 National Institute of Aerospace \/ Galois, Inc.\n--\n-- This library generates new clocks based on a base period and phase.\n--\n-- = Example Usage\n--\n-- Also see @examples\/Clock.hs@ in the\n-- .\n--\n-- @\n-- 'clk' ( 'period' 3 ) ( 'phase' 1 )\n-- @\n--\n-- is equivalent to a stream of values like:\n--\n-- @\n-- cycle [False, True, False]\n-- @\n--\n-- that generates a stream of values\n--\n-- @\n-- False True False False True False False True False ...\n-- 0 1 2 3 4 5 6 7 8\n-- @\n--\n-- That is true every 3 ticks (the period) starting on the 1st tick (the phase).\n\n{-# LANGUAGE NoImplicitPrelude #-}\n\nmodule Copilot.Library.Clocks\n ( clk, clk1, period, phase ) where\n\nimport Prelude ()\nimport qualified Prelude as P\nimport Copilot.Language\n\ndata ( Integral a ) => Period a = Period a\ndata ( Integral a ) => Phase a = Phase a\n\n-- | Constructor for a 'Period'. Note that period must be greater than 0.\nperiod :: ( Integral a ) => a -> Period a\nperiod = Period\n\n-- | Constructor for a 'Phase'. Note that phase must be greater than or equal\n-- to 0, and must be less than the period.\nphase :: ( Integral a ) => a -> Phase a\nphase = Phase\n\n-- | Generate a clock that counts every @n@ ticks, starting at tick @m@, by\n-- using an array of size @n@.\nclk :: ( Integral a ) =>\n Period a -- ^ Period @n@ of clock\n -> Phase a -- ^ Phase @m@ of clock\n -> Stream Bool -- ^ Clock signal - 'True' on clock ticks, 'False' otherwise\nclk ( Period period' ) ( Phase phase' ) = clk'\n where\n clk' = if period' P.< 1 then\n badUsage ( \"clk: clock period must be 1 or greater\" )\n else if phase' P.< 0 then\n badUsage ( \"clk: clock phase must be 0 or greater\" )\n else if phase' P.>= period' then\n badUsage ( \"clk: clock phase must be less than period\")\n else replicate ( fromIntegral phase' ) False\n P.++ True : replicate\n ( fromIntegral\n $ period' P.- phase' P.- 1 ) False\n ++ clk'\n\n-- | This follows the same convention as 'clk', but uses a counter variable of\n-- integral type \/a\/ rather than an array.\nclk1 :: ( Integral a, Typed a ) =>\n Period a -- ^ Period @n@ of clock\n -> Phase a -- ^ Phase @m@ of clock\n -> Stream Bool -- ^ Clock signal - 'True' on clock ticks, 'False' otherwise\nclk1 ( Period period' ) ( Phase phase' ) =\n if period' P.< 1 then\n badUsage ( \"clk1: clock period must be 1 or greater\" )\n else if phase' P.< 0 then\n badUsage ( \"clk1: clock phase must be 0 or greater\" )\n else if phase' P.>= period' then\n badUsage ( \"clk1: clock phase must be less than period\")\n else\n let counter = [ P.fromInteger 0 ]\n ++ mux ( counter \/= ( constant $\n period' P.- 1 ) )\n ( counter P.+ 1 )\n ( 0 )\n in counter == fromIntegral phase'\n","avg_line_length":36.376344086,"max_line_length":98,"alphanum_fraction":0.5379840378} {"size":5568,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-\n Copyright (c) Meta Platforms, Inc. and affiliates.\n All rights reserved.\n\n This source code is licensed under the BSD-style license found in the\n LICENSE file in the root directory of this source tree.\n-}\n\n{-# LANGUAGE TypeApplications #-}\n{-# OPTIONS_GHC -Wno-orphans #-}\n\nmodule Glean.Glass.SymbolId.Flow ( {- instances -} ) where\n\nimport Data.Text ( stripSuffix, intercalate, Text )\n\nimport qualified Glean\nimport Glean.Angle as Angle\nimport qualified Glean.Haxl.Repos as Glean\n\nimport Glean.Glass.SymbolId.Class\n\nimport qualified Glean.Schema.Flow.Types as Flow\nimport qualified Glean.Schema.Src.Types as Src\n\nimport Glean.Glass.Utils\nimport Glean.Glass.Base ( GleanPath(GleanPath) )\nimport Glean.Glass.Types ( Name(..) )\n\nimport Glean.Schema.CodeFlow.Types as Flow ( Entity(..) )\n\ninstance Symbol Flow.Entity where\n toSymbol e = case e of\n Flow.Entity_decl decl -> toSymbol decl\n Flow.Entity_module_ module_ -> toSymbolPredicate module_\n Flow.Entity_EMPTY -> return []\n\ninstance Symbol Flow.SomeDeclaration where\n toSymbol e = case e of\n Flow.SomeDeclaration_localDecl decl -> toSymbolPredicate decl\n Flow.SomeDeclaration_memberDecl member -> toSymbolPredicate member\n Flow.SomeDeclaration_typeDecl type_ -> toSymbolPredicate type_\n Flow.SomeDeclaration_EMPTY -> return []\n\ninstance Symbol Flow.Declaration_key where\n toSymbol (Flow.Declaration_key name container) = container <:> name\n\ninstance Symbol Flow.MemberDeclaration_key where\n toSymbol (Flow.MemberDeclaration_key name container) = container <:> name\n\ninstance Symbol Flow.TypeDeclaration_key where\n toSymbol (Flow.TypeDeclaration_key name container) = container <:> name\n\ninstance Symbol Flow.Range where\n toSymbol = toSymbolPredicate\n\ninstance Symbol Flow.Range_key where\n toSymbol (Flow.Range_key module_ _span) = toSymbolPredicate module_\n\ninstance Symbol Flow.Module_key where\n toSymbol m = case m of\n Flow.Module_key_file file -> runModuleNameQuery file\n Flow.Module_key_builtin _ -> return []\n Flow.Module_key_lib text -> return [text]\n Flow.Module_key_noSource _ -> return []\n Flow.Module_key_string_ text -> return [text]\n Flow.Module_key_EMPTY -> return []\n\ninstance Symbol Flow.Name where\n toSymbol k = do\n v <- Glean.keyOf k\n return [v]\n\n-- Need to encode the module as a \"container\". For most (?) cases\n-- there is a nice short string associated with the file, so we get\n-- ww\/js\/Module\/identifier and unique globally (?)\n--\n-- But in case we don't , use the file name.\n--\n-- T90301808 - Haste short names are not always present. In the case they\n-- are missing we should use the fully qualified filepath. Note: this will leak\n-- the non-relative paths used in the www indexers. TBD\n--\nrunModuleNameQuery :: Src.File -> Glean.RepoHaxl u w [Text]\nrunModuleNameQuery file = do\n mfile <- toJSFile file\n names <- case mfile of\n Nothing -> fetchData (moduleStringName $ Glean.getId file)\n Just path -> fetchData (moduleStringNameByFile path)\n case names of\n Nothing -> reverse . pathFragments <$> Glean.keyOf file\n Just n -> return [n]\n\n-- Normalize any .flow suffix of a file to its base .js file\n--\n-- A smarter way would be to reverse the SourceOfTypeExport for .flow files\n--\ntoJSFile :: Src.File -> Glean.RepoHaxl u w (Maybe GleanPath)\ntoJSFile file = do\n path <- Glean.keyOf file\n return $ GleanPath <$> stripSuffix flowSuffix path\n where\n flowSuffix :: Text\n flowSuffix = \".flow\"\n\n-- Flow module name of file id of module\nmoduleStringName :: Glean.IdOf Src.File -> Angle Text\nmoduleStringName fileid =\n vars $ \\(str :: Angle Text) (file :: Angle Src.File) ->\n str `where_` [\n file .= factId fileid,\n wild .= predicate @Flow.FileOfStringModule (\n rec $\n field @\"file\" (asPredicate file) $\n field @\"string_\" str\n end)\n ]\n\n-- Flow module name of file path of module\nmoduleStringNameByFile :: GleanPath -> Angle Text\nmoduleStringNameByFile (GleanPath path) =\n vars $ \\(str :: Angle Text) (file :: Angle Src.File) ->\n str `where_` [\n file .= predicate @Src.File (string path),\n wild .= predicate @Flow.FileOfStringModule (\n rec $\n field @\"file\" (asPredicate file) $\n field @\"string_\" str\n end)\n ]\n\ninstance ToQName Flow.Entity where\n toQName e = case e of\n Flow.Entity_decl x -> toQName x\n Flow.Entity_module_ x -> Glean.keyOf x >>= toQName\n Flow.Entity_EMPTY -> return $ Left \"unknown Entity\"\n\ninstance ToQName Flow.SomeDeclaration where\n toQName e = case e of\n Flow.SomeDeclaration_localDecl x -> Glean.keyOf x >>= toQName\n Flow.SomeDeclaration_memberDecl x -> Glean.keyOf x >>= toQName\n Flow.SomeDeclaration_typeDecl x -> Glean.keyOf x >>= toQName\n Flow.SomeDeclaration_EMPTY -> return $ Left \"unknown SomeDeclaration\"\n\ninstance ToQName Flow.Declaration_key where\n toQName (Flow.Declaration_key name container) = pairToQName name container\n\ninstance ToQName Flow.MemberDeclaration_key where\n toQName (Flow.MemberDeclaration_key name container) = pairToQName name container\n\ninstance ToQName Flow.TypeDeclaration_key where\n toQName (Flow.TypeDeclaration_key name container) = pairToQName name container\n\ninstance ToQName Flow.Module_key where\n toQName m = do\n sym <- toSymbol m\n return $ case reverse sym of\n [] -> Left \"QName not supported for this symbol\"\n (h:t) -> Right (Name h, Name (intercalate \".\" (reverse t)))\n\npairToQName\n :: (Symbol name, Symbol container)\n => name\n -> container\n -> Glean.RepoHaxl u w (Either a (Name, Name))\npairToQName a b = Right <$> symbolPairToQName \".\" a b\n","avg_line_length":33.5421686747,"max_line_length":82,"alphanum_fraction":0.7262931034} {"size":17088,"ext":"hs","lang":"Haskell","max_stars_count":6.0,"content":"{-# LANGUAGE CPP #-}\n{-\n-----------------------------------------------------------------------------\n--\n-- (c) The University of Glasgow 2015\n--\n-- ELF format tools\n--\n-----------------------------------------------------------------------------\n-}\n\nmodule Elf (\n readElfSectionByName,\n readElfNoteAsString,\n makeElfNote\n ) where\n\n#include \n#include \"HsVersions.h\"\n\nimport GhcPrelude\n\nimport AsmUtils\nimport Exception\nimport DynFlags\nimport ErrUtils\nimport Maybes (MaybeT(..),runMaybeT)\nimport Util (charToC)\nimport Outputable (text,hcat,SDoc)\n\nimport Control.Monad (when)\nimport Data.Binary.Get\nimport Data.Word\nimport Data.Char (ord)\nimport Data.ByteString.Lazy (ByteString)\nimport qualified Data.ByteString.Lazy as LBS\nimport qualified Data.ByteString.Lazy.Char8 as B8\n\n{- Note [ELF specification]\n ~~~~~~~~~~~~~~~~~~~~~~~~\n\n ELF (Executable and Linking Format) is described in the System V Application\n Binary Interface (or ABI). The latter is composed of two parts: a generic\n part and a processor specific part. The generic ABI describes the parts of\n the interface that remain constant across all hardware implementations of\n System V.\n\n The latest release of the specification of the generic ABI is the version\n 4.1 from March 18, 1997:\n\n - http:\/\/www.sco.com\/developers\/devspecs\/gabi41.pdf\n\n Since 1997, snapshots of the draft for the \"next\" version are published:\n\n - http:\/\/www.sco.com\/developers\/gabi\/\n\n Quoting the notice on the website: \"There is more than one instance of these\n chapters to permit references to older instances to remain valid. All\n modifications to these chapters are forward-compatible, so that correct use\n of an older specification will not be invalidated by a newer instance.\n Approximately on a yearly basis, a new instance will be saved, as it reaches\n what appears to be a stable state.\"\n\n Nevertheless we will see that since 1998 it is not true for Note sections.\n\n Many ELF sections\n -----------------\n\n ELF-4.1: the normal section number fields in ELF are limited to 16 bits,\n which runs out of bits when you try to cram in more sections than that. Two\n fields are concerned: the one containing the number of the sections and the\n one containing the index of the section that contains section's names. (The\n same thing applies to the field containing the number of segments, but we\n don't care about it here).\n\n ELF-next: to solve this, theses fields in the ELF header have an escape\n value (different for each case), and the actual section number is stashed\n into unused fields in the first section header.\n\n We support this extension as it is forward-compatible with ELF-4.1.\n Moreover, GHC may generate objects with a lot of sections with the\n \"function-sections\" feature (one section per function).\n\n Note sections\n -------------\n\n Sections with type \"note\" (SHT_NOTE in the specification) are used to add\n arbitrary data into an ELF file. An entry in a note section is composed of a\n name, a type and a value.\n\n ELF-4.1: \"The note information in sections and program header elements holds\n any number of entries, each of which is an array of 4-byte words in the\n format of the target processor.\" Each entry has the following format:\n | namesz | Word32: size of the name string (including the ending \\0)\n | descsz | Word32: size of the value\n | type | Word32: type of the note\n | name | Name string (with \\0 padding to ensure 4-byte alignment)\n | ... |\n | desc | Value (with \\0 padding to ensure 4-byte alignment)\n | ... |\n\n ELF-next: \"The note information in sections and program header elements\n holds a variable amount of entries. In 64-bit objects (files with\n e_ident[EI_CLASS] equal to ELFCLASS64), each entry is an array of 8-byte\n words in the format of the target processor. In 32-bit objects (files with\n e_ident[EI_CLASS] equal to ELFCLASS32), each entry is an array of 4-byte\n words in the format of the target processor.\" (from 1998-2015 snapshots)\n\n This is not forward-compatible with ELF-4.1. In practice, for almost all\n platforms namesz, descz and type fields are 4-byte words for both 32-bit and\n 64-bit objects (see elf.h and readelf source code).\n\n The only exception in readelf source code is for IA_64 machines with OpenVMS\n OS: \"This OS has so many departures from the ELF standard that we test it at\n many places\" (comment for is_ia64_vms() in readelf.c). In this case, namesz,\n descsz and type fields are 8-byte words and name and value fields are padded\n to ensure 8-byte alignment.\n\n We don't support this platform in the following code. Reading a note section\n could be done easily (by testing Machine and OS fields in the ELF header).\n Writing a note section, however, requires that we generate a different\n assembly code for GAS depending on the target platform and this is a little\n bit more involved.\n\n-}\n\n\n-- | ELF header\n--\n-- The ELF header indicates the native word size (32-bit or 64-bit) and the\n-- endianness of the target machine. We directly store getters for words of\n-- different sizes as it is more convenient to use. We also store the word size\n-- as it is useful to skip some uninteresting fields.\n--\n-- Other information such as the target machine and OS are left out as we don't\n-- use them yet. We could add them in the future if we ever need them.\ndata ElfHeader = ElfHeader\n { gw16 :: Get Word16 -- ^ Get a Word16 with the correct endianness\n , gw32 :: Get Word32 -- ^ Get a Word32 with the correct endianness\n , gwN :: Get Word64 -- ^ Get a Word with the correct word size\n -- and endianness\n , wordSize :: Int -- ^ Word size in bytes\n }\n\n\n-- | Read the ELF header\nreadElfHeader :: DynFlags -> ByteString -> IO (Maybe ElfHeader)\nreadElfHeader dflags bs = runGetOrThrow getHeader bs `catchIO` \\_ -> do\n debugTraceMsg dflags 3 $\n text (\"Unable to read ELF header\")\n return Nothing\n where\n getHeader = do\n magic <- getWord32be\n ws <- getWord8\n endian <- getWord8\n version <- getWord8\n skip 9 -- skip OSABI, ABI version and padding\n when (magic \/= 0x7F454C46 || version \/= 1) $ fail \"Invalid ELF header\"\n\n case (ws, endian) of\n -- ELF 32, little endian\n (1,1) -> return . Just $ ElfHeader\n getWord16le\n getWord32le\n (fmap fromIntegral getWord32le) 4\n -- ELF 32, big endian\n (1,2) -> return . Just $ ElfHeader\n getWord16be\n getWord32be\n (fmap fromIntegral getWord32be) 4\n -- ELF 64, little endian\n (2,1) -> return . Just $ ElfHeader\n getWord16le\n getWord32le\n (fmap fromIntegral getWord64le) 8\n -- ELF 64, big endian\n (2,2) -> return . Just $ ElfHeader\n getWord16be\n getWord32be\n (fmap fromIntegral getWord64be) 8\n _ -> fail \"Invalid ELF header\"\n\n\n------------------\n-- SECTIONS\n------------------\n\n\n-- | Description of the section table\ndata SectionTable = SectionTable\n { sectionTableOffset :: Word64 -- ^ offset of the table describing sections\n , sectionEntrySize :: Word16 -- ^ size of an entry in the section table\n , sectionEntryCount :: Word64 -- ^ number of sections\n , sectionNameIndex :: Word32 -- ^ index of a special section which\n -- contains section's names\n }\n\n-- | Read the ELF section table\nreadElfSectionTable :: DynFlags\n -> ElfHeader\n -> ByteString\n -> IO (Maybe SectionTable)\n\nreadElfSectionTable dflags hdr bs = action `catchIO` \\_ -> do\n debugTraceMsg dflags 3 $\n text (\"Unable to read ELF section table\")\n return Nothing\n where\n getSectionTable :: Get SectionTable\n getSectionTable = do\n skip (24 + 2*wordSize hdr) -- skip header and some other fields\n secTableOffset <- gwN hdr\n skip 10\n entrySize <- gw16 hdr\n entryCount <- gw16 hdr\n secNameIndex <- gw16 hdr\n return (SectionTable secTableOffset entrySize\n (fromIntegral entryCount)\n (fromIntegral secNameIndex))\n\n action = do\n secTable <- runGetOrThrow getSectionTable bs\n -- In some cases, the number of entries and the index of the section\n -- containing section's names must be found in unused fields of the first\n -- section entry (see Note [ELF specification])\n let\n offSize0 = fromIntegral $ sectionTableOffset secTable + 8\n + 3 * fromIntegral (wordSize hdr)\n offLink0 = fromIntegral $ offSize0 + fromIntegral (wordSize hdr)\n\n entryCount' <- if sectionEntryCount secTable \/= 0\n then return (sectionEntryCount secTable)\n else runGetOrThrow (gwN hdr) (LBS.drop offSize0 bs)\n entryNameIndex' <- if sectionNameIndex secTable \/= 0xffff\n then return (sectionNameIndex secTable)\n else runGetOrThrow (gw32 hdr) (LBS.drop offLink0 bs)\n return (Just $ secTable\n { sectionEntryCount = entryCount'\n , sectionNameIndex = entryNameIndex'\n })\n\n\n-- | A section\ndata Section = Section\n { entryName :: ByteString -- ^ Name of the section\n , entryBS :: ByteString -- ^ Content of the section\n }\n\n-- | Read a ELF section\nreadElfSectionByIndex :: DynFlags\n -> ElfHeader\n -> SectionTable\n -> Word64\n -> ByteString\n -> IO (Maybe Section)\n\nreadElfSectionByIndex dflags hdr secTable i bs = action `catchIO` \\_ -> do\n debugTraceMsg dflags 3 $\n text (\"Unable to read ELF section\")\n return Nothing\n where\n -- read an entry from the section table\n getEntry = do\n nameIndex <- gw32 hdr\n skip (4+2*wordSize hdr)\n offset <- fmap fromIntegral $ gwN hdr\n size <- fmap fromIntegral $ gwN hdr\n let bs' = LBS.take size (LBS.drop offset bs)\n return (nameIndex,bs')\n\n -- read the entry with the given index in the section table\n getEntryByIndex x = runGetOrThrow getEntry bs'\n where\n bs' = LBS.drop off bs\n off = fromIntegral $ sectionTableOffset secTable +\n x * fromIntegral (sectionEntrySize secTable)\n\n -- Get the name of a section\n getEntryName nameIndex = do\n let idx = fromIntegral (sectionNameIndex secTable)\n (_,nameTable) <- getEntryByIndex idx\n let bs' = LBS.drop nameIndex nameTable\n runGetOrThrow getLazyByteStringNul bs'\n\n action = do\n (nameIndex,bs') <- getEntryByIndex (fromIntegral i)\n name <- getEntryName (fromIntegral nameIndex)\n return (Just $ Section name bs')\n\n\n-- | Find a section from its name. Return the section contents.\n--\n-- We do not perform any check on the section type.\nfindSectionFromName :: DynFlags\n -> ElfHeader\n -> SectionTable\n -> String\n -> ByteString\n -> IO (Maybe ByteString)\nfindSectionFromName dflags hdr secTable name bs =\n rec [0..sectionEntryCount secTable - 1]\n where\n -- convert the required section name into a ByteString to perform\n -- ByteString comparison instead of String comparison\n name' = B8.pack name\n\n -- compare recursively each section name and return the contents of\n -- the matching one, if any\n rec [] = return Nothing\n rec (x:xs) = do\n me <- readElfSectionByIndex dflags hdr secTable x bs\n case me of\n Just e | entryName e == name' -> return (Just (entryBS e))\n _ -> rec xs\n\n\n-- | Given a section name, read its contents as a ByteString.\n--\n-- If the section isn't found or if there is any parsing error, we return\n-- Nothing\nreadElfSectionByName :: DynFlags\n -> ByteString\n -> String\n -> IO (Maybe LBS.ByteString)\n\nreadElfSectionByName dflags bs name = action `catchIO` \\_ -> do\n debugTraceMsg dflags 3 $\n text (\"Unable to read ELF section \\\"\" ++ name ++ \"\\\"\")\n return Nothing\n where\n action = runMaybeT $ do\n hdr <- MaybeT $ readElfHeader dflags bs\n secTable <- MaybeT $ readElfSectionTable dflags hdr bs\n MaybeT $ findSectionFromName dflags hdr secTable name bs\n\n------------------\n-- NOTE SECTIONS\n------------------\n\n-- | read a Note as a ByteString\n--\n-- If you try to read a note from a section which does not support the Note\n-- format, the parsing is likely to fail and Nothing will be returned\nreadElfNoteBS :: DynFlags\n -> ByteString\n -> String\n -> String\n -> IO (Maybe LBS.ByteString)\n\nreadElfNoteBS dflags bs sectionName noteId = action `catchIO` \\_ -> do\n debugTraceMsg dflags 3 $\n text (\"Unable to read ELF note \\\"\" ++ noteId ++\n \"\\\" in section \\\"\" ++ sectionName ++ \"\\\"\")\n return Nothing\n where\n -- align the getter on n bytes\n align n = do\n m <- bytesRead\n if m `mod` n == 0\n then return ()\n else skip 1 >> align n\n\n -- noteId as a bytestring\n noteId' = B8.pack noteId\n\n -- read notes recursively until the one with a valid identifier is found\n findNote hdr = do\n#if defined(aarch64_HOST_ARCH)\n align 8\n#else\n align 4\n#endif\n namesz <- gw32 hdr\n descsz <- gw32 hdr\n _ <- gw32 hdr -- we don't use the note type\n name <- if namesz == 0\n then return LBS.empty\n else getLazyByteStringNul\n#if defined(aarch64_HOST_ARCH)\n align 8\n#else\n align 4\n#endif\n desc <- if descsz == 0\n then return LBS.empty\n else getLazyByteString (fromIntegral descsz)\n if name == noteId'\n then return $ Just desc\n else findNote hdr\n\n\n action = runMaybeT $ do\n hdr <- MaybeT $ readElfHeader dflags bs\n sec <- MaybeT $ readElfSectionByName dflags bs sectionName\n MaybeT $ runGetOrThrow (findNote hdr) sec\n\n-- | read a Note as a String\n--\n-- If you try to read a note from a section which does not support the Note\n-- format, the parsing is likely to fail and Nothing will be returned\nreadElfNoteAsString :: DynFlags\n -> FilePath\n -> String\n -> String\n -> IO (Maybe String)\n\nreadElfNoteAsString dflags path sectionName noteId = action `catchIO` \\_ -> do\n debugTraceMsg dflags 3 $\n text (\"Unable to read ELF note \\\"\" ++ noteId ++\n \"\\\" in section \\\"\" ++ sectionName ++ \"\\\"\")\n return Nothing\n where\n action = do\n bs <- LBS.readFile path\n note <- readElfNoteBS dflags bs sectionName noteId\n return (fmap B8.unpack note)\n\n\n-- | Generate the GAS code to create a Note section\n--\n-- Header fields for notes are 32-bit long (see Note [ELF specification]).\n--\n-- It seems there is no easy way to force GNU AS to generate a 32-bit word in\n-- every case. Hence we use .int directive to create them: however \"The byte\n-- order and bit size of the number depends on what kind of target the assembly\n-- is for.\" (https:\/\/sourceware.org\/binutils\/docs\/as\/Int.html#Int)\n--\n-- If we add new target platforms, we need to check that the generated words\n-- are 32-bit long, otherwise we need to use platform specific directives to\n-- force 32-bit .int in asWord32.\nmakeElfNote :: String -> String -> Word32 -> String -> SDoc\nmakeElfNote sectionName noteName typ contents = hcat [\n text \"\\t.section \",\n text sectionName,\n text \",\\\"\\\",\",\n sectionType \"note\",\n text \"\\n\",\n\n -- note name length (+ 1 for ending \\0)\n asWord32 (length noteName + 1),\n\n -- note contents size\n asWord32 (length contents),\n\n -- note type\n asWord32 typ,\n\n -- note name (.asciz for \\0 ending string) + padding\n text \"\\t.asciz \\\"\",\n text noteName,\n text \"\\\"\\n\",\n text \"\\t.align 4\\n\",\n\n -- note contents (.ascii to avoid ending \\0) + padding\n text \"\\t.ascii \\\"\",\n text (escape contents),\n text \"\\\"\\n\",\n text \"\\t.align 4\\n\"]\n where\n escape :: String -> String\n escape = concatMap (charToC.fromIntegral.ord)\n\n asWord32 :: Show a => a -> SDoc\n asWord32 x = hcat [\n text \"\\t.int \",\n text (show x),\n text \"\\n\"]\n\n\n------------------\n-- Helpers\n------------------\n\n-- | runGet in IO monad that throws an IOException on failure\nrunGetOrThrow :: Get a -> LBS.ByteString -> IO a\nrunGetOrThrow g bs = case runGetOrFail g bs of\n Left _ -> fail \"Error while reading file\"\n Right (_,_,a) -> return a\n","avg_line_length":35.6,"max_line_length":79,"alphanum_fraction":0.6200257491} {"size":435,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Higher where\n\nsquare :: Int -> Int\nsquare x = x * x\n\nplus5 :: Int -> Int\nplus5 a = a + 5\n\nconst :: Int -> Int\nconst x = x\n\nfoo :: Int -> Int -> Int -> Int\nfoo a b c = if a + b < c\n then a + b\n else if c < 5\n then b + c\n else a + c\n\nfixed :: (Int -> Int) -> Int -> Bool\nfixed f x = f x == f (f x)\n\nmain = undefined\n\n\nadd :: Num n => n -> n -> n\nadd a b = a + b\n","avg_line_length":16.1111111111,"max_line_length":36,"alphanum_fraction":0.4298850575} {"size":25990,"ext":"hs","lang":"Haskell","max_stars_count":2.0,"content":"{-\nCopyrights (c) 2017. VMware, Inc. All right reserved. \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n-}\n\nmodule OpenFlow.OVSConst where\n\nimport qualified Data.Map as M\nimport Data.Word\n\nimport IR.Registers\nimport Backend\n\ndata Format = Hex\n | Dec\n | IP4\n | IP6\n | MAC\n\ndata Attributes = Attributes { attrMaskable :: Bool\n , attrFormat :: Format\n }\n\novsRegFile :: RegisterFile\novsRegFile = RegisterFile $\n [ {-Register \"metadata\" 64 [] -} -- reserve metadata register for use in packet-in messages\n Register \"xxreg0\" 128 [ RegField \"xreg0\" 64 64\n , RegField \"xreg1\" 64 0\n , RegField \"reg0\" 32 96\n , RegField \"reg1\" 32 64\n , RegField \"reg2\" 32 32\n , RegField \"reg3\" 32 0]\n , Register \"xxreg1\" 128 [ RegField \"xreg2\" 64 64\n , RegField \"xreg3\" 64 0\n , RegField \"reg4\" 32 96\n , RegField \"reg5\" 32 64\n , RegField \"reg6\" 32 32\n , RegField \"reg7\" 32 0]\n , Register \"xxreg2\" 128 [ RegField \"xreg4\" 64 64\n , RegField \"xreg5\" 64 0\n , RegField \"reg8\" 32 96\n , RegField \"reg9\" 32 64\n , RegField \"reg10\" 32 32\n , RegField \"reg11\" 32 0]\n , Register \"xxreg3\" 128 [ RegField \"xreg6\" 64 64\n , RegField \"xreg7\" 64 0\n , RegField \"reg12\" 32 96\n , RegField \"reg13\" 32 64\n , RegField \"reg14\" 32 32\n , RegField \"reg15\" 32 0]\n ]\n\novsStructReify :: StructReify\novsStructReify = StructReify ovsReifyWidth ovsReifyCons\n\novsReifyWidth = M.fromList\n [ (\"eth_pkt_t\" , 0)\n , (\"eth_payload_t\" , 16)\n , (\"ip4_pkt_t\" , 0)\n , (\"ip6_pkt_t\" , 0)\n , (\"arp_op_t\" , 16)\n , (\"arp_pkt_t\" , 0)\n , (\"ip_payload_t\" , 8)\n , (\"tcp_pkt_t\" , 0)\n , (\"udp_pkt_t\" , 0)\n , (\"icmp4_pkt_t\" , 0)\n , (\"icmp6_pkt_t\" , 0)\n , (\"icmp6_payload_t\" , 8)\n , (\"icmp6_ns_pkt_t\" , 0)\n , (\"icmp6_na_pkt_t\" , 0)\n ] \n\novsReifyCons = M.fromList\n [ (\"EthIP4\" , 0x0800)\n , (\"EthIP6\" , 0x86dd)\n , (\"EthARP\" , 0x0806)\n , (\"ARPRequest\" , 0x0001)\n , (\"ARPReply\" , 0x0002)\n , (\"IPTCP\" , 0x06)\n , (\"IPUDP\" , 0x11)\n , (\"IPICMP4\" , 0x01)\n , (\"IPICMP6\" , 0x3a)\n , (\"ICMP6NS\" , 135)\n , (\"ICMP6NA\" , 136)\n ]\n\n-- Map IR field names to names known to the backend\ntype FieldMap = M.Map String (String, Maybe (Int, Int)) \n\nmatchMap :: M.Map String (String, [String])\nmatchMap = M.fromList \n [ (\"metadata\" , (\"metadata\" , []))\n , (\"xxreg0\" , (\"xxreg0\" , []))\n , (\"xxreg1\" , (\"xxreg1\" , []))\n , (\"xxreg2\" , (\"xxreg2\" , []))\n , (\"xxreg3\" , (\"xxreg3\" , []))\n , (\"xreg0\" , (\"xreg0\" , []))\n , (\"xreg1\" , (\"xreg1\" , []))\n , (\"xreg2\" , (\"xreg2\" , []))\n , (\"xreg3\" , (\"xreg3\" , []))\n , (\"xreg4\" , (\"xreg4\" , []))\n , (\"xreg5\" , (\"xreg5\" , []))\n , (\"xreg6\" , (\"xreg6\" , []))\n , (\"xreg7\" , (\"xreg7\" , []))\n , (\"reg0\" , (\"reg0\" , []))\n , (\"reg1\" , (\"reg1\" , []))\n , (\"reg2\" , (\"reg2\" , []))\n , (\"reg3\" , (\"reg3\" , []))\n , (\"reg4\" , (\"reg4\" , []))\n , (\"reg5\" , (\"reg5\" , []))\n , (\"reg6\" , (\"reg6\" , []))\n , (\"reg7\" , (\"reg7\" , []))\n , (\"reg8\" , (\"reg8\" , []))\n , (\"reg9\" , (\"reg9\" , []))\n , (\"reg10\" , (\"reg10\" , []))\n , (\"reg11\" , (\"reg11\" , []))\n , (\"reg12\" , (\"reg12\" , []))\n , (\"reg13\" , (\"reg13\" , []))\n , (\"reg14\" , (\"reg14\" , []))\n , (\"reg15\" , (\"reg15\" , []))\n , (\"portnum\" , (\"in_port\" , []))\n , (\"portnum_oxm\" , (\"in_port_oxm\", []))\n , (\"src\" , (\"dl_src\" , []))\n , (\"dst\" , (\"dl_dst\" , []))\n , (\"vxlan.tun_dst\" , (\"tun_dst\" , []))\n , (\"vxlan.tun_id\" , (\"tun_id\" , []))\n , (\"vlan.pcp\" , (\"vlan_pcp\" , []))\n , (\"vlan.vid\" , (\"vlan_vid\" , []))\n , (\"ethtype\" , (\"dl_type\" , []))\n , (\"payload._tag\" , (\"dl_type\" , []))\n , (\"payload.ip4.dscp\" , (\"ip_dscp\" , [\"ip\"]))\n , (\"payload.ip4.ecn\" , (\"ip_ecn\" , [\"ip\"]))\n , (\"payload.ip4.ttl\" , (\"nw_ttl\" , [\"ip\"]))\n , (\"payload.ip4.proto\" , (\"ip_proto\" , [\"ip\"]))\n , (\"payload.ip4.src\" , (\"nw_src\" , [\"ip\"]))\n , (\"payload.ip4.dst\" , (\"nw_dst\" , [\"ip\"]))\n , (\"payload.ip6.dscp\" , (\"ip_dscp\" , [\"ipv6\"]))\n , (\"payload.ip6.ecn\" , (\"ip_ecn\" , [\"ipv6\"]))\n , (\"payload.ip6.ttl\" , (\"nw_ttl\" , [\"ipv6\"]))\n , (\"payload.ip6.label\" , (\"ipv6_label\" , [\"ipv6\"]))\n , (\"payload.ip6.proto\" , (\"ip_proto\" , [\"ipv6\"]))\n , (\"payload.ip6.src\" , (\"ipv6_src\" , [\"ipv6\"]))\n , (\"payload.ip6.dst\" , (\"ipv6_dst\" , [\"ipv6\"]))\n , (\"payload.arp.op._tag\" , (\"arp_op\" , [\"arp\"]))\n , (\"payload.arp.spa\" , (\"arp_spa\" , [\"arp\"]))\n , (\"payload.arp.tpa\" , (\"arp_tpa\" , [\"arp\"]))\n , (\"payload.arp.sha\" , (\"arp_sha\" , [\"arp\"]))\n , (\"payload.arp.tha\" , (\"arp_tha\" , [\"arp\"]))\n , (\"payload.ip4.payload._tag\" , (\"ip_proto\" , [\"ip\"]))\n , (\"payload.ip4.payload.tcp.src\" , (\"tcp_src\" , [\"tcp\"]))\n , (\"payload.ip4.payload.tcp.dst\" , (\"tcp_dst\" , [\"tcp\"]))\n , (\"payload.ip4.payload.tcp.flags\" , (\"tcp_flags\" , [\"tcp\"]))\n , (\"payload.ip4.payload.udp.src\" , (\"udp_src\" , [\"udp\"]))\n , (\"payload.ip4.payload.udp.dst\" , (\"udp_dst\" , [\"udp\"]))\n , (\"payload.ip4.payload.icmp4.type\" , (\"icmp_type\" , [\"icmp\"]))\n , (\"payload.ip4.payload.icmp4.code\" , (\"icmp_code\" , [\"icmp\"]))\n , (\"payload.ip4.payload.icmp6.type\" , (\"icmp_type\" , [\"icmp6\"]))\n , (\"payload.ip4.payload.icmp6.code\" , (\"icmp6_code\" , [\"icmp6\"]))\n , (\"payload.ip4.payload.icmp6.payload._tag\" , (\"icmp_type\" , [\"icmp6\"]))\n , (\"payload.ip4.payload.icmp6.payload.ns.target\" , (\"nd_target\" , [\"icmp6\",\"icmp_type=135\",\"icmp_code=0\"]))\n , (\"payload.ip4.payload.icmp6.payload.na.target\" , (\"nd_target\" , [\"icmp6\",\"icmp_type=136\",\"icmp_code=0\"]))\n , (\"payload.ip4.payload.icmp6.payload.ns.sll\" , (\"nd_sll\" , [\"icmp6\",\"icmp_type=135\",\"icmp_code=0\"]))\n , (\"payload.ip4.payload.icmp6.payload.na.tll\" , (\"nd_tll\" , [\"icmp6\",\"icmp_type=136\",\"icmp_code=0\"]))\n , (\"payload.ip6.payload._tag\" , (\"ip_proto\" , [\"ip6\"]))\n , (\"payload.ip6.payload.tcp.src\" , (\"tcp_src\" , [\"tcp6\"]))\n , (\"payload.ip6.payload.tcp.dst\" , (\"tcp_dst\" , [\"tcp6\"]))\n , (\"payload.ip6.payload.tcp.flags\" , (\"tcp_flags\" , [\"tcp6\"]))\n , (\"payload.ip6.payload.udp.src\" , (\"udp_src\" , [\"udp6\"]))\n , (\"payload.ip6.payload.udp.dst\" , (\"udp_dst\" , [\"udp6\"]))\n , (\"payload.ip6.payload.icmp4.type\" , (\"icmp_type\" , [\"icmp\"]))\n , (\"payload.ip6.payload.icmp4.code\" , (\"icmp_code\" , [\"icmp\"]))\n , (\"payload.ip6.payload.icmp6.type\" , (\"icmp_type\" , [\"icmp6\"]))\n , (\"payload.ip6.payload.icmp6.code\" , (\"icmp_code\" , [\"icmp6\"]))\n , (\"payload.ip6.payload.icmp6.payload._tag\" , (\"icmp_type\" , [\"icmp6\"]))\n , (\"payload.ip6.payload.icmp6.payload.ns.target\" , (\"nd_target\" , [\"icmp6\",\"icmp_type=135\",\"icmp_code=0\"]))\n , (\"payload.ip6.payload.icmp6.payload.na.target\" , (\"nd_target\" , [\"icmp6\",\"icmp_type=136\",\"icmp_code=0\"]))\n , (\"payload.ip6.payload.icmp6.payload.ns.sll\" , (\"nd_sll\" , [\"icmp6\",\"icmp_type=135\",\"icmp_code=0\"]))\n , (\"payload.ip6.payload.icmp6.payload.na.tll\" , (\"nd_tll\" , [\"icmp6\",\"icmp_type=136\",\"icmp_code=0\"]))\n , (\"ct_state\" , (\"ct_state\" , []))\n , (\"ct_label\" , (\"ct_label\" , []))\n ]\n\n\nassnMap :: FieldMap\nassnMap = M.fromList\n [ (\"metadata\" , (\"OXM_OF_METADATA\" , Nothing))\n , (\"xxreg0\" , (\"NXM_NX_XXREG0\" , Nothing))\n , (\"xxreg1\" , (\"NXM_NX_XXREG1\" , Nothing))\n , (\"xxreg2\" , (\"NXM_NX_XXREG2\" , Nothing))\n , (\"xxreg3\" , (\"NXM_NX_XXREG3\" , Nothing))\n , (\"xreg0\" , (\"OXM_OF_PKT_REG0\" , Nothing))\n , (\"xreg1\" , (\"OXM_OF_PKT_REG1\" , Nothing))\n , (\"xreg2\" , (\"OXM_OF_PKT_REG2\" , Nothing))\n , (\"xreg3\" , (\"OXM_OF_PKT_REG3\" , Nothing))\n , (\"xreg4\" , (\"OXM_OF_PKT_REG4\" , Nothing))\n , (\"xreg5\" , (\"OXM_OF_PKT_REG5\" , Nothing))\n , (\"xreg6\" , (\"OXM_OF_PKT_REG6\" , Nothing))\n , (\"xreg7\" , (\"OXM_OF_PKT_REG7\" , Nothing))\n , (\"reg0\" , (\"NXM_NX_REG0\" , Nothing))\n , (\"reg1\" , (\"NXM_NX_REG1\" , Nothing))\n , (\"reg2\" , (\"NXM_NX_REG2\" , Nothing))\n , (\"reg3\" , (\"NXM_NX_REG3\" , Nothing))\n , (\"reg4\" , (\"NXM_NX_REG4\" , Nothing))\n , (\"reg5\" , (\"NXM_NX_REG5\" , Nothing))\n , (\"reg6\" , (\"NXM_NX_REG6\" , Nothing))\n , (\"reg7\" , (\"NXM_NX_REG7\" , Nothing))\n , (\"reg8\" , (\"NXM_NX_REG8\" , Nothing))\n , (\"reg9\" , (\"NXM_NX_REG9\" , Nothing))\n , (\"reg10\" , (\"NXM_NX_REG10\" , Nothing))\n , (\"reg11\" , (\"NXM_NX_REG11\" , Nothing))\n , (\"reg12\" , (\"NXM_NX_REG12\" , Nothing))\n , (\"reg13\" , (\"NXM_NX_REG13\" , Nothing))\n , (\"reg14\" , (\"NXM_NX_REG14\" , Nothing))\n , (\"reg15\" , (\"NXM_NX_REG15\" , Nothing))\n , (\"portnum\" , (\"NXM_OF_IN_PORT\" , Nothing))\n , (\"portnum_oxm\" , (\"OXM_OF_IN_PORT\" , Nothing))\n , (\"src\" , (\"NXM_OF_ETH_SRC\" , Nothing))\n , (\"dst\" , (\"NXM_OF_ETH_DST\" , Nothing))\n , (\"ethtype\" , (\"NXM_OF_ETH_TYPE\" , Nothing))\n , (\"vxlan.tun_dst\" , (\"NXM_NX_TUN_IPV4_DST\", Nothing))\n , (\"vxlan.tun_id\" , (\"NXM_NX_TUN_ID\" , Nothing))\n , (\"vlan.pcp\" , (\"NXM_OF_VLAN_TCI\" , Just (15,13)))\n , (\"vlan.vid\" , (\"NXM_OF_VLAN_TCI\" , Just (11,0)))\n , (\"payload._tag\" , (\"NXM_OF_ETH_TYPE\" , Nothing))\n , (\"payload.ip4.dscp\" , (\"NXM_OF_IP_TOS\" , Just (7,2)))\n , (\"payload.ip4.ecn\" , (\"NXM_NX_IP_ECN\" , Nothing))\n , (\"payload.ip4.ttl\" , (\"NXM_NX_IP_TTL\" , Nothing))\n , (\"payload.ip4.proto\" , (\"NXM_OF_IP_PROTO\" , Nothing))\n , (\"payload.ip4.src\" , (\"NXM_OF_IP_SRC\" , Nothing))\n , (\"payload.ip4.dst\" , (\"NXM_OF_IP_DST\" , Nothing))\n , (\"payload.ip6.dscp\" , (\"NXM_OF_IP_TOS\" , Just (7,2)))\n , (\"payload.ip6.ecn\" , (\"NXM_NX_IP_ECN\" , Nothing))\n , (\"payload.ip6.ttl\" , (\"NXM_NX_IP_TTL\" , Nothing))\n , (\"payload.ip6.label\" , (\"NXM_NX_IPV6_LABEL\" , Nothing))\n , (\"payload.ip6.proto\" , (\"NXM_OF_IP_PROTO\" , Nothing))\n , (\"payload.ip6.src\" , (\"NXM_NX_IPV6_SRC\" , Nothing))\n , (\"payload.ip6.dst\" , (\"NXM_NX_IPV6_DST\" , Nothing))\n , (\"payload.arp.op._tag\" , (\"NXM_OF_ARP_OP\" , Nothing))\n , (\"payload.arp.spa\" , (\"NXM_OF_ARP_SPA\" , Nothing))\n , (\"payload.arp.tpa\" , (\"NXM_OF_ARP_TPA\" , Nothing))\n , (\"payload.arp.sha\" , (\"NXM_NX_ARP_SHA\" , Nothing))\n , (\"payload.arp.tha\" , (\"NXM_NX_ARP_THA\" , Nothing))\n , (\"payload.ip4.payload._tag\" , (\"NXM_OF_IP_PROTO\" , Nothing))\n , (\"payload.ip4.payload.tcp.src\" , (\"NXM_OF_TCP_SRC\" , Nothing))\n , (\"payload.ip4.payload.tcp.dst\" , (\"NXM_OF_TCP_DST\" , Nothing))\n , (\"payload.ip4.payload.udp.src\" , (\"NXM_OF_UDP_SRC\" , Nothing))\n , (\"payload.ip4.payload.udp.dst\" , (\"NXM_OF_UDP_DST\" , Nothing))\n , (\"payload.ip4.payload.icmp4.type\" , (\"NXM_OF_ICMP_TYPE\" , Nothing))\n , (\"payload.ip4.payload.icmp4.code\" , (\"NXM_OF_ICMP_CODE\" , Nothing))\n , (\"payload.ip4.payload.icmp6.type\" , (\"NXM_NX_ICMPV6_TYPE\" , Nothing))\n , (\"payload.ip4.payload.icmp6.code\" , (\"NXM_NX_ICMPV6_CODE\" , Nothing))\n , (\"payload.ip4.payload.icmp6.payload._tag\" , (\"NXM_NX_ICMPV6_TYPE\" , Nothing))\n , (\"payload.ip4.payload.icmp6.payload.ns.target\" , (\"OXM_OF_IPV6_ND_TARGET\" , Nothing))\n , (\"payload.ip4.payload.icmp6.payload.na.target\" , (\"OXM_OF_IPV6_ND_TARGET\" , Nothing))\n , (\"payload.ip4.payload.icmp6.payload.ns.sll\" , (\"OXM_OF_IPV6_ND_SLL\" , Nothing))\n , (\"payload.ip4.payload.icmp6.payload.na.tll\" , (\"OXM_OF_IPV6_ND_TLL\" , Nothing))\n , (\"payload.ip6.payload._tag\" , (\"NXM_OF_IP_PROTO\" , Nothing))\n , (\"payload.ip6.payload.tcp.src\" , (\"NXM_OF_TCP_SRC\" , Nothing))\n , (\"payload.ip6.payload.tcp.dst\" , (\"NXM_OF_TCP_DST\" , Nothing))\n , (\"payload.ip6.payload.udp.src\" , (\"NXM_OF_UDP_SRC\" , Nothing))\n , (\"payload.ip6.payload.udp.dst\" , (\"NXM_OF_UDP_DST\" , Nothing))\n , (\"payload.ip6.payload.icmp4.type\" , (\"NXM_OF_ICMP_TYPE\" , Nothing))\n , (\"payload.ip6.payload.icmp4.code\" , (\"NXM_OF_ICMP_CODE\" , Nothing))\n , (\"payload.ip6.payload.icmp6.type\" , (\"NXM_NX_ICMPV6_TYPE\" , Nothing))\n , (\"payload.ip6.payload.icmp6.code\" , (\"NXM_NX_ICMPV6_CODE\" , Nothing))\n , (\"payload.ip6.payload.icmp6.payload._tag\" , (\"NXM_NX_ICMPV6_TYPE\" , Nothing))\n , (\"payload.ip6.payload.icmp6.payload.ns.target\" , (\"OXM_OF_IPV6_ND_TARGET\" , Nothing))\n , (\"payload.ip6.payload.icmp6.payload.na.target\" , (\"OXM_OF_IPV6_ND_TARGET\" , Nothing))\n , (\"payload.ip6.payload.icmp6.payload.ns.sll\" , (\"OXM_OF_IPV6_ND_SLL\" , Nothing))\n , (\"payload.ip6.payload.icmp6.payload.na.tll\" , (\"OXM_OF_IPV6_ND_TLL\" , Nothing))\n , (\"ct_state\" , (\"NXM_NX_CT_STATE\" , Nothing))\n , (\"ct_label\" , (\"NXM_NX_CT_LABEL\" , Nothing))\n ]\n\nmatchAttributes :: M.Map String Attributes\nmatchAttributes = M.fromList\n [ (\"metadata\" , Attributes True Hex) \n , (\"reg0\" , Attributes True Hex)\n , (\"reg1\" , Attributes True Hex)\n , (\"reg2\" , Attributes True Hex)\n , (\"reg3\" , Attributes True Hex)\n , (\"reg4\" , Attributes True Hex)\n , (\"reg5\" , Attributes True Hex)\n , (\"reg6\" , Attributes True Hex)\n , (\"reg7\" , Attributes True Hex)\n , (\"reg8\" , Attributes True Hex)\n , (\"reg9\" , Attributes True Hex)\n , (\"reg10\" , Attributes True Hex)\n , (\"reg11\" , Attributes True Hex)\n , (\"reg12\" , Attributes True Hex)\n , (\"reg13\" , Attributes True Hex)\n , (\"reg14\" , Attributes True Hex)\n , (\"reg15\" , Attributes True Hex)\n , (\"xreg0\" , Attributes True Hex)\n , (\"xreg1\" , Attributes True Hex)\n , (\"xreg2\" , Attributes True Hex)\n , (\"xreg3\" , Attributes True Hex)\n , (\"xreg4\" , Attributes True Hex)\n , (\"xreg5\" , Attributes True Hex)\n , (\"xreg6\" , Attributes True Hex)\n , (\"xreg7\" , Attributes True Hex)\n , (\"xxreg0\" , Attributes True Hex)\n , (\"xxreg1\" , Attributes True Hex)\n , (\"xxreg2\" , Attributes True Hex)\n , (\"xxreg3\" , Attributes True Hex)\n , (\"in_port\" , Attributes False Dec)\n , (\"in_port_oxm\", Attributes False Dec)\n , (\"dl_src\" , Attributes True MAC)\n , (\"dl_dst\" , Attributes True MAC)\n , (\"dl_type\" , Attributes True Hex)\n , (\"tun_id\" , Attributes True Dec)\n , (\"tun_dst\" , Attributes True IP4)\n , (\"vlan_pcp\" , Attributes False Dec)\n , (\"vlan_vid\" , Attributes False Hex)\n , (\"dl_type\" , Attributes False Hex)\n , (\"ip_dscp\" , Attributes False Hex)\n , (\"ip_ecn\" , Attributes False Dec)\n , (\"nw_ttl\" , Attributes False Dec)\n , (\"ip_proto\" , Attributes False Dec)\n , (\"nw_src\" , Attributes True IP4)\n , (\"nw_dst\" , Attributes True IP4)\n , (\"ipv6_label\" , Attributes True Hex)\n , (\"ipv6_src\" , Attributes True IP6)\n , (\"ipv6_dst\" , Attributes True IP6)\n , (\"arp_op\" , Attributes False Dec)\n , (\"arp_spa\" , Attributes True IP4)\n , (\"arp_tpa\" , Attributes True IP4)\n , (\"arp_sha\" , Attributes True MAC)\n , (\"arp_tha\" , Attributes True MAC)\n , (\"tcp_src\" , Attributes True Dec)\n , (\"tcp_dst\" , Attributes True Dec)\n , (\"tcp_flags\" , Attributes True Hex)\n , (\"udp_src\" , Attributes True Hex)\n , (\"udp_dst\" , Attributes True Hex)\n , (\"icmp_type\" , Attributes False Dec)\n , (\"icmp_code\" , Attributes False Dec)\n , (\"nd_target\" , Attributes True IP6)\n , (\"nd_sll\" , Attributes True MAC)\n , (\"nd_tll\" , Attributes True MAC)\n , (\"ct_state\" , Attributes True Hex)\n , (\"ct_label\" , Attributes True Hex)\n ]\n\n\ndata OXKey = OInPort\n | OInPhyPort\n | OMetadata\n | OEthDst\n | OEthSrc\n | OEthType\n | OIPv4Dst\n | OIPv4Src\n | ONiciraRegister Int\n | OPacketRegister Int\n | OVLANID\n | OVLANPCP\n | OIPDSCP\n | OIPECN\n | OIPProto\n | OTCPSrc\n | OTCPDst\n | OUDPSrc\n | OUDPDst\n | OSCTPSrc\n | OSCTPDst\n | OICMPv4_Type\n | OICMPv4_Code\n | OARP_OP\n | OARP_SPA\n | OARP_TPA\n | OARP_SHA\n | OARP_THA\n | OIPv6Src\n | OIPv6Dst\n | OIPv6_FLabel\n | OICMPv6_Type\n | OICMPv6_Code\n | OIPv6_ND_Target\n | OIPv6_ND_SLL\n | OIPv6_ND_TLL\n | OMPLS_Label\n | OMPLS_TC\n | OMPLS_BOS\n | OPBB_ISID\n | OTunnelDst\n | OTunnelID\n | OIPv6_EXTHDR\n | OOXMOther Word16 Word8\n deriving (Eq, Ord)\n","avg_line_length":64.812967581,"max_line_length":123,"alphanum_fraction":0.3542131589} {"size":5495,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE BangPatterns #-}\nmodule Brick.Widgets.Internal\n ( renderFinal\n , cropToContext\n , cropResultToContext\n , renderDynBorder\n )\nwhere\n\n#if !MIN_VERSION_base(4,8,0)\nimport Control.Applicative\n#endif\n\nimport Lens.Micro ((^.), (&), (%~))\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad.Trans.Reader\nimport Data.Maybe (catMaybes)\nimport qualified Graphics.Vty as V\n\nimport Brick.Types\nimport Brick.Types.Internal\nimport Brick.AttrMap\nimport Brick.Widgets.Border.Style\nimport Brick.BorderMap (BorderMap)\nimport qualified Brick.BorderMap as BM\n\nrenderFinal :: AttrMap\n -> [Widget n]\n -> V.DisplayRegion\n -> ([CursorLocation n] -> Maybe (CursorLocation n))\n -> RenderState n\n -> (RenderState n, V.Picture, Maybe (CursorLocation n), [Extent n])\nrenderFinal aMap layerRenders sz chooseCursor rs = (newRS, picWithBg, theCursor, concat layerExtents)\n where\n (layerResults, !newRS) = flip runState rs $ sequence $\n (\\p -> runReaderT p ctx) <$>\n (render <$> cropToContext <$> layerRenders)\n ctx = Context mempty (fst sz) (snd sz) defaultBorderStyle aMap False\n pic = V.picForLayers $ uncurry V.resize sz <$> (^.imageL) <$> layerResults\n -- picWithBg is a workaround for runaway attributes.\n -- See https:\/\/github.com\/coreyoconnor\/vty\/issues\/95\n picWithBg = pic { V.picBackground = V.Background ' ' V.defAttr }\n layerCursors = (^.cursorsL) <$> layerResults\n layerExtents = reverse $ (^.extentsL) <$> layerResults\n theCursor = chooseCursor $ concat layerCursors\n\n-- | After rendering the specified widget, crop its result image to the\n-- dimensions in the rendering context.\ncropToContext :: Widget n -> Widget n\ncropToContext p =\n Widget (hSize p) (vSize p) (render p >>= cropResultToContext)\n\ncropResultToContext :: Result n -> RenderM n (Result n)\ncropResultToContext result = do\n c <- getContext\n return $ result & imageL %~ cropImage c\n & cursorsL %~ cropCursors c\n & extentsL %~ cropExtents c\n & bordersL %~ cropBorders c\n\ncropImage :: Context -> V.Image -> V.Image\ncropImage c = V.crop (max 0 $ c^.availWidthL) (max 0 $ c^.availHeightL)\n\ncropCursors :: Context -> [CursorLocation n] -> [CursorLocation n]\ncropCursors ctx cs = catMaybes $ cropCursor <$> cs\n where\n -- A cursor location is removed if it is not within the region\n -- described by the context.\n cropCursor c | outOfContext c = Nothing\n | otherwise = Just c\n outOfContext c =\n or [ c^.cursorLocationL.locationRowL < 0\n , c^.cursorLocationL.locationColumnL < 0\n , c^.cursorLocationL.locationRowL >= ctx^.availHeightL\n , c^.cursorLocationL.locationColumnL >= ctx^.availWidthL\n ]\n\ncropExtents :: Context -> [Extent n] -> [Extent n]\ncropExtents ctx es = catMaybes $ cropExtent <$> es\n where\n -- An extent is cropped in places where it is not within the\n -- region described by the context.\n --\n -- If its entirety is outside the context region, it is dropped.\n --\n -- Otherwise its size and upper left corner are adjusted so that\n -- they are contained within the context region.\n cropExtent (Extent n (Location (c, r)) (w, h) (Location (oC, oR))) =\n -- First, clamp the upper-left corner to at least (0, 0).\n let c' = max c 0\n r' = max r 0\n -- Compute deltas for the offset since if the upper-left\n -- corner moved, so should the offset.\n dc = c' - c\n dr = r' - r\n -- Then, determine the new lower-right corner based on\n -- the clamped corner.\n endCol = c' + w\n endRow = r' + h\n -- Then clamp the lower-right corner based on the\n -- context\n endCol' = min (ctx^.availWidthL) endCol\n endRow' = min (ctx^.availHeightL) endRow\n -- Then compute the new width and height from the\n -- clamped lower-right corner.\n w' = endCol' - c'\n h' = endRow' - r'\n e = Extent n (Location (c', r')) (w', h') (Location (oC + dc, oR + dr))\n in if w' < 0 || h' < 0\n then Nothing\n else Just e\n\ncropBorders :: Context -> BorderMap DynBorder -> BorderMap DynBorder\ncropBorders ctx = BM.crop Edges\n { eTop = 0\n , eBottom = availHeight ctx - 1\n , eLeft = 0\n , eRight = availWidth ctx - 1\n }\n\nrenderDynBorder :: DynBorder -> V.Image\nrenderDynBorder db = V.char (dbAttr db) . ($dbStyle db) $ case bsDraw <$> dbSegments db of\n -- top bot left right\n Edges False False False False -> const ' ' -- dunno lol (but should never happen, so who cares)\n Edges False False _ _ -> bsHorizontal\n Edges _ _ False False -> bsVertical\n Edges False True False True -> bsCornerTL\n Edges False True True False -> bsCornerTR\n Edges True False False True -> bsCornerBL\n Edges True False True False -> bsCornerBR\n Edges False True True True -> bsIntersectT\n Edges True False True True -> bsIntersectB\n Edges True True False True -> bsIntersectL\n Edges True True True False -> bsIntersectR\n Edges True True True True -> bsIntersectFull\n","avg_line_length":40.4044117647,"max_line_length":101,"alphanum_fraction":0.6029117379} {"size":59,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"{-# htermination group :: [Int] -> [[Int]] #-}\nimport List\n","avg_line_length":19.6666666667,"max_line_length":46,"alphanum_fraction":0.5593220339} {"size":6968,"ext":"hs","lang":"Haskell","max_stars_count":69.0,"content":"module Handler.Admin.Hellban where\n\nimport Import\nimport qualified Data.Text as T\nimport Handler.Admin.Modlog (addModlogEntry) \nimport Utils.YobaMarkup (makeExternalRef)\n-------------------------------------------------------------------------------------------------------------\ngetHellBanNoPageR :: Handler Html\ngetHellBanNoPageR = getHellBanR 0\n\ngetHellBanR :: Int -> Handler Html\ngetHellBanR page = do\n permissions <- ((fmap getPermissions) . getMaybeGroup) =<< maybeAuth\n group <- (fmap $ userGroup . entityVal) <$> maybeAuth\n showPosts <- getConfig configShowLatestPosts\n boards <- runDB $ selectList ([]::[Filter Board]) []\n numberOfPosts <- runDB $ count [PostDeleted ==. False, PostHellbanned ==. True]\n let boards' = mapMaybe (getIgnoredBoard' group) boards\n selectPosts = [PostBoard \/<-. boards', PostDeleted ==. False, PostHellbanned ==. True]\n pages = listPages showPosts numberOfPosts\n posts <- runDB $ selectList selectPosts [Desc PostDate, LimitTo showPosts, OffsetBy $ page*showPosts]\n postFiles <- forM posts $ \\e -> runDB $ selectList [AttachedfileParentId ==. entityKey e] []\n let postsAndFiles = zip posts postFiles\n -------------------------------------------------------------------------------------------------------------------\n AppSettings{..} <- appSettings <$> getYesod\n defaultLayout $ do\n setUltDestCurrent\n defaultTitleMsg MsgHellbanning\n $(widgetFile \"admin\/hellban\")\n------------------------------------------------------------------------------------------------------------\ndata HellbanFormAction = HellbanFormDo | HellbanFormUndo | HellbanFormDoNothing\n deriving (Show, Ord, Read, Eq, Bounded, Enum)\n\ndata HellbanFormVisibility = HellbanFormShow | HellbanFormShowAll | HellbanFormHide | HellbanFormHidelAll | HellbanFormVisibilityNothing\n deriving (Show, Ord, Read, Eq, Bounded, Enum)\n\npostHellBanActionR :: Int -> Handler TypedContent\npostHellBanActionR postId = do\n msgrender <- getMessageRender\n let postKey = (toSqlKey $ fromIntegral postId) :: Key Post\n post <- runDB $ get404 postKey\n let posterId = postPosterId post\n posterIp = postIp post\n ((result, _), _) <- runFormPost hellbanForm\n case result of\n FormFailure [] -> selectRep $ provideJson $ object [(\"error\", toJSON $ msgrender MsgBadFormData)]\n FormFailure xs -> selectRep $ provideJson $ object [(\"error\", toJSON $ msgrender (MsgError $ T.intercalate \"; \" xs))]\n FormMissing -> selectRep $ provideJson $ object [(\"error\", toJSON $ msgrender MsgNoFormData)]\n FormSuccess (ip, uid, action, visibility) -> do\n case action of\n HellbanFormDo -> do\n when (uid || ip) $ do\n addModlogEntry $ MsgModlogHellban ( (if uid then posterId else \"\") <> \" \" <> (if ip then posterIp else \"\"))\n void $ runDB $ insert $ Hellban { hellbanUid = if uid then posterId else \"\", hellbanIp = if ip then posterIp else \"\" }\n HellbanFormUndo -> do\n when (uid || ip) $ \n addModlogEntry $ MsgModlogUnhellban ((if uid then posterId else \"\") <> \" \" <> (if ip then posterIp else \"\"))\n when uid $\n runDB $ deleteWhere [HellbanUid ==. posterId]\n when ip $\n runDB $ deleteWhere [HellbanIp ==. posterIp]\n _ -> return ()\n case visibility of\n HellbanFormShow -> do\n runDB $ update postKey [PostHellbanned =. False]\n p <- makeExternalRef (postBoard post) (postLocalId post)\n addModlogEntry $ MsgModlogHellbanShowPost p\n HellbanFormShowAll -> do\n when uid $ do\n void $ runDB $ updateWhere [PostPosterId ==. posterId] [PostHellbanned =. False]\n addModlogEntry $ MsgModlogHellbanShowAllPosts posterId\n when ip $ do\n void $ runDB $ updateWhere [PostIp ==. posterIp] [PostHellbanned =. False]\n addModlogEntry $ MsgModlogHellbanShowAllPosts posterIp\n HellbanFormHide -> do\n void $ runDB $ update postKey [PostHellbanned =. True]\n p <- makeExternalRef (postBoard post) (postLocalId post)\n addModlogEntry $ MsgModlogHellbanHidePost p\n HellbanFormHidelAll -> do\n when uid $ do\n void $ runDB $ updateWhere [PostPosterId ==. posterId] [PostHellbanned =. True]\n addModlogEntry $ MsgModlogHellbanHideAllPosts posterId\n when ip $ do\n void $ runDB $ updateWhere [PostIp ==. posterIp] [PostHellbanned =. True]\n addModlogEntry $ MsgModlogHellbanHideAllPosts posterIp\n _ -> return ()\n selectRep $ provideJson $ object [(\"ok\", toJSON $ msgrender MsgSuccessEx)]\n\nhellbanForm :: Html -> -- ^ Extra token\n MForm Handler (FormResult ( Bool\n , Bool\n , HellbanFormAction\n , HellbanFormVisibility\n )\n , Widget)\nhellbanForm extra = do\n msgrender <- getMessageRender\n AppSettings{..} <- appSettings <$> getYesod\n\n let hb :: [(Text, HellbanFormAction)]\n hb = [(msgrender MsgHellbanDo, HellbanFormDo), (msgrender MsgHellbanUndo, HellbanFormUndo), (\"---\",HellbanFormDoNothing)]\n display :: [(Text, HellbanFormVisibility)]\n display = [(msgrender MsgHellbanShowPost, HellbanFormShow), (msgrender MsgHellbanHidePost, HellbanFormHide), (msgrender MsgHellbanShowAllPosts, HellbanFormShowAll), (msgrender MsgHellbanHideAllPosts, HellbanFormHidelAll), (\"---\", HellbanFormVisibilityNothing)]\n (hbIPRes , hbIPView ) <- mreq checkBoxField \"\" Nothing\n (hbUIDRes , hbUIDView ) <- mreq checkBoxField \"\" Nothing\n (hbRes , hbView ) <- mreq (selectFieldList hb ) \"\" Nothing\n (displayRes , displayView ) <- mreq (selectFieldList display) \"\" Nothing\n let result = (,,,) <$> hbIPRes <*> hbUIDRes <*> hbRes <*> displayRes\n widget = $(widgetFile \"admin\/hellban-form\")\n return (result, widget)\n\ngetHellBanGetFormR :: Int -> Handler Html\ngetHellBanGetFormR postId = do\n let postKey = (toSqlKey $ fromIntegral postId) :: Key Post\n post <- runDB $ get404 postKey\n let posterId = postPosterId post\n posterIp = postIp post\n bannedUID <- runDB $ selectFirst [HellbanUid ==. posterId] []\n bannedIP <- runDB $ selectFirst [HellbanIp ==. posterIp] []\n (form, enc) <- generateFormPost hellbanForm\n bareLayout [whamlet|
\n ^{form}\n $if isJust bannedUID || isJust bannedIP\n _{MsgHellbanUserIsBanned}: \n $maybe _ <- bannedUID\n UID \n $maybe _ <- bannedIP\n IP\n |]\n","avg_line_length":53.6,"max_line_length":266,"alphanum_fraction":0.5941446613} {"size":744,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"module Main where\n\nimport System.Environment\nimport System.Exit\nimport System.IO\nimport System.FilePath\nimport System.Process\n\nimport qualified Data.Text.IO as T\n\nimport Latte.Latte\nimport Latte.Backend.Stdlib\n\nmain :: IO ()\nmain = do\n args <- getArgs\n case args of\n file:_ -> do\n contents <- T.readFile file\n case buildX86 file contents of\n Right s -> do\n hPutStrLn stderr \"OK\"\n let asmName = file -<.> \"s\"\n binName = dropExtension file\n std <- putStdLib\n writeFile asmName (s <> \"\\n\")\n callProcess \"gcc\" [asmName, std, \"-m32\", \"-o\", binName]\n Left e -> hPutStrLn stderr (\"ERROR:\\n\" ++ e) >> exitFailure\n _ -> hPutStrLn stderr \"wtf dude\" >> exitFailure\n","avg_line_length":24.8,"max_line_length":67,"alphanum_fraction":0.622311828} {"size":1597,"ext":"hs","lang":"Haskell","max_stars_count":3.0,"content":"{-# LANGUAGE OverloadedStrings #-}\n\nmodule Html (makeView) where\n\nimport Control.Monad.Trans.Either (EitherT, left)\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Builder (toLazyByteString)\nimport qualified Data.ByteString.Char8 as BS (unpack)\nimport Data.ByteString.Lazy (toStrict)\nimport Data.Monoid ((<>))\nimport Data.Text (Text)\nimport qualified Data.Text as T (unpack)\nimport Data.Text.Encoding (decodeUtf8)\nimport Heist\nimport Heist.Interpreted (renderTemplate, bindSplices, Splice, textSplice)\nimport Lens.Family\n\nimport Types\n\n\n\ntype N = EitherT [String] IO\n\n\nmakeView :: Blog -> ByteString -> Slug Text -> Splices (Splice N) -> N File\nmakeView blog template slug context =\n let\n slices = extraContext <> context\n extraContext = do\n \"blogName\" ## textSplice (name blog)\n \"blogURL\" ## textSplice (url blog)\n in do\n content <- generatePage template slices\n return (T.unpack (fromSlug slug), content)\n\n\ngeneratePage :: ByteString -> Splices (Splice N) -> N Text\ngeneratePage template splices = do\n heist <- initHeist heistConfig\n renderResult <- renderTemplate (bindSplices splices heist) template\n (output, _) <- case renderResult of\n Nothing -> left [\"invalid template '\" <> BS.unpack template <> \"'\"]\n Just x -> return x\n return (decodeUtf8 (toStrict (toLazyByteString output)))\n\n\nheistConfig :: HeistConfig N\nheistConfig =\n emptyHeistConfig\n & hcTemplateLocations .~ [loadTemplates \"templates\"]\n & hcInterpretedSplices .~ defaultInterpretedSplices\n & hcNamespace .~ \"\"\n\n","avg_line_length":29.5740740741,"max_line_length":75,"alphanum_fraction":0.7019411396} {"size":974,"ext":"hs","lang":"Haskell","max_stars_count":623.0,"content":"\n\n Encode\/Decode\/Hash Add-on<\/title>\n\n <maps>\n <homeID>encoder<\/homeID>\n <mapref location=\"map.jhm\"\/>\n <\/maps>\n\n <view>\n <name>TOC<\/name>\n <label>Contents<\/label>\n <type>org.zaproxy.zap.extension.help.ZapTocView<\/type>\n <data>toc.xml<\/data>\n <\/view>\n\n <view>\n <name>Index<\/name>\n <label>Index<\/label>\n <type>javax.help.IndexView<\/type>\n <data>index.xml<\/data>\n <\/view>\n\n <view>\n <name>Search<\/name>\n <label>Search<\/label>\n <type>javax.help.SearchView<\/type>\n <data engine=\"com.sun.java.help.search.DefaultSearchEngine\">\n JavaHelpSearch\n <\/data>\n <\/view>\n\n <view>\n <name>Favorites<\/name>\n <label>Favorites<\/label>\n <type>javax.help.FavoritesView<\/type>\n <\/view>\n<\/helpset>","avg_line_length":25.6315789474,"max_line_length":184,"alphanum_fraction":0.6427104723} {"size":5959,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"-- | Common sub-expression elimination.\nmodule CSE (cse) where\n\nimport Theory\n\nimport MonadLib\nimport Data.Function (on)\nimport\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0Data.List (sortBy)\nimport\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0Data.Map (Map)\nimport\u00a0qualified\u00a0Data.Map as Map\n\n\n-- | Name sub-expressions, noticiing repreated ones.\ncse :: [Name] {- ^ Names that do not appear in expressions -} ->\n Map Name Expr {- ^ Definitions to be CSE-ed -} ->\n [Expr] {- ^ Expressions to be CSE-ed -} ->\n ( [(Name,Expr)] -- New definitions (sorted by definition time),\n -- shared across all expressions.\n , [Expr] -- simple expressions\n )\n\ncse ns inDefs e = (defs, map unVL e')\n where\n (e', defs) = runCSE ns inDefs (mapM nameExpr e)\n\n\n-- | A simple expression: all sub-terms should be VarLitExpr.\nnewtype SimpExpr = SE Expr deriving (Eq,Ord)\n\n-- | An expression that is a variable.\nnewtype VarExpr = VE Expr\n\n-- | An expression that is a variable or a literal)\nnewtype VarLitExpr = VL { unVL :: Expr }\n\n-- | The monad for CSE\nnewtype CSE a = CSE (StateT RW Id a)\n\ndata RW = RW\n { knownExpr :: Map SimpExpr (VarExpr, Integer)\n , knownDefs :: Map Name (Either VarLitExpr Expr)\n , names :: [Name]\n , time :: !Integer\n }\n\ninstance Functor CSE where\n fmap = liftM\n\ninstance Applicative CSE where\n pure = return\n (<*>) = ap\n\ninstance Monad CSE where\n return x = CSE (return x)\n fail x = CSE (fail x)\n CSE m >>= k = CSE (do x <- m\n let CSE m1 = k x\n m1)\n\nrunCSE :: [Name] -> Map Name Expr -> CSE a -> (a, [(Name,Expr)])\nrunCSE xs inDefs (CSE m) =\n case runId $ runStateT rw0 m of\n (a, rwFin) ->\n (a, map snd\n $ sortBy (compare `on` fst)\n $ map swap\n $ Map.toList\n $ knownExpr rwFin\n )\n where\n rw0 = RW { knownExpr = Map.empty\n , names = xs\n , time = 0\n , knownDefs = fmap Right inDefs\n }\n\n swap (SE x, (VE (Var y), t)) = (t, (y,x))\n swap (_, (VE e,_)) = error $ \"[CSE bug] non-variable VE: \" ++ show e\n\nnameExpr :: Expr -> CSE VarLitExpr\nnameExpr expr =\n case expr of\n Var x ->\n do mb <- isDefVar x\n case mb of\n Nothing -> op0\n Just (Left e) -> return e\n Just (Right e) ->\n do e' <- nameExpr e\n finishDefVar x e'\n return e'\n\n LInt {} -> op0\n LBool {} -> op0\n LTrue -> op0\n LFalse -> op0\n Wildcard -> op0\n\n Negate e -> op1 Negate e\n Cast sg si e -> op1 (Cast sg si) e\n LNot e -> op1 LNot e\n Not e -> op1 Not e\n Linked e -> op1 Linked e\n Framed e -> op1 Framed e\n Base e -> op1 Base e\n Offset e -> op1 Offset e\n SConst e -> op1 SConst e\n AddrCast e -> op1 AddrCast e\n Hardware e -> op1 Hardware e\n Region e -> op1 Region e\n\n e1 :+ e2 -> op2 (:+) e1 e2\n e1 :- e2 -> op2 (:-) e1 e2\n e1 :* e2 -> op2 (:*) e1 e2\n Div e1 e2 -> op2 Div e1 e2\n Mod e1 e2 -> op2 Mod e1 e2\n\n LAnd e1 e2 -> op2 LAnd e1 e2\n LOr e1 e2 -> op2 LOr e1 e2\n LXor e1 e2 -> op2 LXor e1 e2\n Lsr e1 e2 -> op2 Lsr e1 e2\n Lsl e1 e2 -> op2 Lsl e1 e2\n BitTestB e1 e2 -> op2 BitTestB e1 e2\n\n e1 :<= e2 -> op2 (:<=) e1 e2\n e1 := e2 -> op2 (:=) e1 e2\n e1 :&& e2 -> op2 (:&&) e1 e2\n e1 :|| e2 -> op2 (:||) e1 e2\n e1 :--> e2 -> op2 (:-->) e1 e2\n e1 :<-> e2 -> op2 (:<->) e1 e2\n BitTest e1 e2 -> op2 BitTest e1 e2\n\n Select e1 e2 -> op2 Select e1 e2\n MkAddr e1 e2 -> op2 MkAddr e1 e2\n Shift e1 e2 -> op2 Shift e1 e2\n\n Update e1 e2 e3 -> op3 Update e1 e2 e3\n Ifte e1 e2 e3 -> op3 Ifte e1 e2 e3\n\n Havoc e1 e2 e3 e4 -> op4 Havoc e1 e2 e3 e4\n\n Hole x es -> opN (Hole x) es\n Passthrough x es -> opN (Passthrough x) es\n\n MkAddrMap e1 e2 -> op2 MkAddrMap e1 e2\n Bases e -> op1 Bases e\n Offsets e -> op1 Offsets e\n TypeError t e -> op1 (TypeError t) e\n TypeNote t e -> op1 (TypeNote t) e\n\n where\n op0 = return (VL expr)\n\n op1 f e = do VL x <- nameExpr e\n nameSimpExpr $ SE $ f x\n\n op2 f e1 e2 = do VL x <- nameExpr e1\n VL y <- nameExpr e2\n nameSimpExpr $ SE $ f x y\n\n op3 f e1 e2 e3 = do VL x <- nameExpr e1\n VL y <- nameExpr e2\n VL z <- nameExpr e3\n nameSimpExpr $ SE $ f x y z\n\n op4 f e1 e2 e3 e4 = do VL x <- nameExpr e1\n VL y <- nameExpr e2\n VL z <- nameExpr e3\n VL a <- nameExpr e4\n nameSimpExpr $ SE $ f x y z a\n\n opN f xs = do ys <- mapM nameExpr xs\n nameSimpExpr $ SE $ f $ map unVL ys\n\n\nisDefVar :: Name -> CSE (Maybe (Either VarLitExpr Expr))\nisDefVar x =\n do s <- CSE get\n return (Map.lookup x (knownDefs s))\n\nfinishDefVar :: Name -> VarLitExpr -> CSE ()\nfinishDefVar x e =\n CSE $ sets_ $ \\s -> s { knownDefs = Map.insert x (Left e) (knownDefs s) }\n\n\nnameSimpExpr :: SimpExpr -> CSE VarLitExpr\nnameSimpExpr e =\n CSE $ sets $ \\s ->\n case Map.lookup e (knownExpr s) of\n Just (VE x,_) -> (VL x, s)\n Nothing ->\n let x : xs = names s\n x' = Var x\n t = time s\n in (VL x', RW { knownExpr = Map.insert e (VE x', t) (knownExpr s)\n , names = xs\n , time = t + 1\n , knownDefs = knownDefs s\n })\n\n","avg_line_length":29.6467661692,"max_line_length":75,"alphanum_fraction":0.4718912569} {"size":504,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module D14P2Spec (\n tests\n) where\n\nimport Test.Tasty\nimport Test.Tasty.HUnit\n\nimport D14P2\n\ntests :: TestTree\ntests = testGroup \"Tests\" [unitTests]\n\nunitTests :: TestTree\nunitTests = testGroup \"Unit tests\"\n [\n testCase \"D14P2.recipecount: gives correct answer to the original problem\" $ do\n 9 @=? recipecount [5,1,5,8,9] [3,7]\n 5 @=? recipecount [0,1,2,4,5] [3,7]\n 18 @=? recipecount [9,2,5,1,0] [3,7]\n 2018 @=? recipecount [5,9,4,1,4] [3,7]\n ]","avg_line_length":24.0,"max_line_length":87,"alphanum_fraction":0.5952380952} {"size":259,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module HJS.Parser(parseProgram,lexProgram,lexFile,runLexer) where\n\nimport HJS.Parser.JavaScriptParser\nimport HJS.Parser.JavaScript\n\n\nlexFile flags name = do\n input <- readFile name\n\t\t putStrLn $ show $ lexProgram input\n\n\n","avg_line_length":21.5833333333,"max_line_length":65,"alphanum_fraction":0.6756756757} {"size":7711,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"-- TODO (Karthikeyan): This file should be removed. This file hasn't been removed to help with the\n-- conflict resolution\n-- | Types that represent the raw data stored in the catalog. See also: the module documentation for\n-- \"Hasura.RQL.DDL.Schema\".\nmodule Hasura.RQL.Types.Catalog\n ( CatalogMetadata(..)\n\n , CatalogTable(..)\n , CatalogTableInfo(..)\n , CatalogForeignKey(..)\n\n , CatalogRelation(..)\n , CatalogComputedField(..)\n , CatalogPermission(..)\n , CatalogEventTrigger(..)\n , CatalogFunction(..)\n , CatalogCronTrigger(..)\n , CatalogCustomTypes(..)\n , CatalogRemoteSchemaPermission\n ) where\n\nimport Hasura.Prelude\n\nimport qualified Data.HashMap.Strict as M\n\nimport Data.Aeson\nimport Data.Aeson.Casing\nimport Data.Aeson.TH\nimport System.Cron.Types (CronSchedule (..))\n\nimport Hasura.Backends.Postgres.SQL.Types\nimport Hasura.Incremental (Cacheable)\nimport Hasura.RQL.DDL.ComputedField\nimport Hasura.RQL.Types.Action\nimport Hasura.RQL.Types.Column\nimport Hasura.RQL.Types.Common\nimport Hasura.RQL.Types.CustomTypes\nimport Hasura.RQL.Types.EventTrigger\nimport Hasura.RQL.Types.Function\nimport Hasura.RQL.Types.Permission\nimport Hasura.RQL.Types.QueryCollection\nimport Hasura.RQL.Types.RemoteRelationship\nimport Hasura.RQL.Types.RemoteSchema\nimport Hasura.RQL.Types.ScheduledTrigger\nimport Hasura.RQL.Types.SchemaCache\nimport Hasura.SQL.Backend\nimport Hasura.Session\n\nnewtype CatalogForeignKey\n = CatalogForeignKey\n { unCatalogForeignKey :: ForeignKey\n } deriving (Show, Eq, NFData, Hashable, Cacheable)\n\ninstance FromJSON CatalogForeignKey where\n parseJSON = withObject \"CatalogForeignKey\" \\o -> do\n constraint <- o .: \"constraint\"\n foreignTable <- o .: \"foreign_table\"\n\n columns <- o .: \"columns\"\n foreignColumns <- o .: \"foreign_columns\"\n unless (length columns == length foreignColumns) $\n fail \"columns and foreign_columns differ in length\"\n\n pure $ CatalogForeignKey ForeignKey\n { _fkConstraint = constraint\n , _fkForeignTable = foreignTable\n , _fkColumnMapping = M.fromList $ zip columns foreignColumns\n }\n\ndata CatalogTableInfo\n = CatalogTableInfo\n { _ctiOid :: !OID\n , _ctiColumns :: ![RawColumnInfo 'Postgres]\n , _ctiPrimaryKey :: !(Maybe (PrimaryKey PGCol))\n , _ctiUniqueConstraints :: !(HashSet Constraint)\n -- ^ Does \/not\/ include the primary key!\n , _ctiForeignKeys :: !(HashSet CatalogForeignKey)\n , _ctiViewInfo :: !(Maybe ViewInfo)\n , _ctiDescription :: !(Maybe PGDescription)\n } deriving (Eq, Generic)\ninstance NFData CatalogTableInfo\ninstance Cacheable CatalogTableInfo\n$(deriveFromJSON (aesonDrop 4 snakeCase) ''CatalogTableInfo)\n\ndata CatalogTable\n = CatalogTable\n { _ctName :: !QualifiedTable\n , _ctIsSystemDefined :: !SystemDefined\n , _ctIsEnum :: !Bool\n , _ctConfiguration :: !TableConfig\n , _ctInfo :: !(Maybe CatalogTableInfo)\n } deriving (Eq, Generic)\ninstance NFData CatalogTable\ninstance Cacheable CatalogTable\n$(deriveFromJSON (aesonDrop 3 snakeCase) ''CatalogTable)\n\ndata CatalogRelation\n = CatalogRelation\n { _crTable :: !QualifiedTable\n , _crRelName :: !RelName\n , _crRelType :: !RelType\n , _crDef :: !Value\n , _crComment :: !(Maybe Text)\n } deriving (Show, Eq, Generic)\ninstance NFData CatalogRelation\ninstance Cacheable CatalogRelation\n$(deriveFromJSON (aesonDrop 3 snakeCase) ''CatalogRelation)\n\ndata CatalogPermission\n = CatalogPermission\n { _cpTable :: !QualifiedTable\n , _cpRole :: !RoleName\n , _cpPermType :: !PermType\n , _cpDef :: !Value\n , _cpComment :: !(Maybe Text)\n } deriving (Show, Eq, Generic)\ninstance NFData CatalogPermission\ninstance Hashable CatalogPermission\ninstance Cacheable CatalogPermission\n$(deriveFromJSON (aesonDrop 3 snakeCase) ''CatalogPermission)\n\ndata CatalogComputedField\n = CatalogComputedField\n { _cccComputedField :: !AddComputedField\n , _cccFunctionInfo :: ![RawFunctionInfo] -- ^ multiple functions with same name\n } deriving (Show, Eq, Generic)\ninstance NFData CatalogComputedField\ninstance Cacheable CatalogComputedField\n$(deriveFromJSON (aesonDrop 4 snakeCase) ''CatalogComputedField)\n\ndata CatalogEventTrigger\n = CatalogEventTrigger\n { _cetTable :: !QualifiedTable\n , _cetName :: !TriggerName\n , _cetDef :: !Value\n } deriving (Show, Eq, Generic)\ninstance NFData CatalogEventTrigger\ninstance Cacheable CatalogEventTrigger\n$(deriveFromJSON (aesonDrop 4 snakeCase) ''CatalogEventTrigger)\n\ndata CatalogFunction\n = CatalogFunction\n { _cfFunction :: !QualifiedFunction\n , _cfIsSystemDefined :: !SystemDefined\n , _cfConfiguration :: !FunctionConfig\n , _cfInfo :: ![RawFunctionInfo] -- ^ multiple functions with same name\n } deriving (Show, Eq, Generic)\ninstance NFData CatalogFunction\ninstance Cacheable CatalogFunction\n$(deriveFromJSON (aesonDrop 3 snakeCase) ''CatalogFunction)\n\ndata CatalogCustomTypes (b :: BackendType)\n = CatalogCustomTypes\n { _cctCustomTypes :: !CustomTypes\n , _cctPgScalars :: !(HashSet (ScalarType b))\n -- ^ All Postgres base types, which may be referenced in custom type definitions.\n -- When we validate the custom types (see 'validateCustomTypeDefinitions'),\n -- we record which base types were referenced so that we can be sure to include them\n -- in the generated GraphQL schema.\n --\n -- These are not actually part of the Hasura metadata --- we fetch them from\n -- @pg_catalog.pg_type@ --- but they\u2019re needed when validating the custom type\n -- metadata, so we include them here.\n --\n -- See Note [Postgres scalars in custom types] for more details.\n } deriving (Generic)\ninstance NFData (CatalogCustomTypes 'Postgres)\nderiving instance Eq (CatalogCustomTypes 'Postgres)\ninstance Cacheable (CatalogCustomTypes 'Postgres)\ninstance FromJSON (CatalogCustomTypes 'Postgres) where\n parseJSON = genericParseJSON $ aesonDrop 4 snakeCase\n\ntype CatalogAction = ActionMetadata\n\ndata CatalogCronTrigger\n = CatalogCronTrigger\n { _cctName :: !TriggerName\n , _cctWebhookConf :: !InputWebhook\n , _cctCronSchedule :: !CronSchedule\n , _cctPayload :: !(Maybe Value)\n , _cctRetryConf :: !(Maybe STRetryConf)\n , _cctHeaderConf :: !(Maybe [HeaderConf])\n , _cctComment :: !(Maybe Text)\n } deriving (Show, Eq, Generic)\ninstance NFData CatalogCronTrigger\ninstance Cacheable CatalogCronTrigger\n$(deriveJSON (aesonDrop 4 snakeCase) ''CatalogCronTrigger)\n\ntype CatalogRemoteSchemaPermission = AddRemoteSchemaPermissions\n\ndata CatalogMetadata\n = CatalogMetadata\n { _cmTables :: ![CatalogTable]\n , _cmRelations :: ![CatalogRelation]\n , _cmPermissions :: ![CatalogPermission]\n , _cmEventTriggers :: ![CatalogEventTrigger]\n , _cmRemoteSchemas :: ![AddRemoteSchemaQuery]\n , _cmFunctions :: ![CatalogFunction]\n , _cmAllowlistCollections :: ![CollectionDef]\n , _cmComputedFields :: ![CatalogComputedField]\n , _cmCustomTypes :: !(CatalogCustomTypes 'Postgres)\n , _cmActions :: ![CatalogAction]\n , _cmRemoteRelationships :: ![RemoteRelationship]\n , _cmCronTriggers :: ![CatalogCronTrigger]\n , _cmRemoteSchemaPermissions :: ![CatalogRemoteSchemaPermission]\n } deriving (Eq, Generic)\ninstance NFData CatalogMetadata\ninstance Cacheable CatalogMetadata\ninstance FromJSON CatalogMetadata where\n parseJSON = genericParseJSON $ aesonDrop 3 snakeCase\n","avg_line_length":36.5450236967,"max_line_length":100,"alphanum_fraction":0.7037997666} {"size":1936,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"-- |\n-- This module implements the desugaring pass which replaces patterns in let-in\n-- expressions with appropriate case expressions.\n--\nmodule Language.PureScript.Sugar.LetPattern (desugarLetPatternModule) where\n\nimport Prelude.Compat\n\nimport Data.List (groupBy, concatMap)\nimport Data.Function (on)\n\nimport Language.PureScript.AST\nimport Language.PureScript.Crash\n\n-- | Replace every @BoundValueDeclaration@ in @Let@ expressions with @Case@\n-- expressions.\ndesugarLetPatternModule :: Module -> Module\ndesugarLetPatternModule (Module ss coms mn ds exts) = Module ss coms mn (map desugarLetPattern ds) exts\n\n-- | Desugar a single let expression\ndesugarLetPattern :: Declaration -> Declaration\ndesugarLetPattern decl =\n let (f, _, _) = everywhereOnValues id replace id\n in f decl\n where\n replace :: Expr -> Expr\n replace (Let w ds e) = go w (partitionDecls ds) e\n replace other = other\n\n go :: WhereProvenance\n -- ^ Metadata about whether the let-in was a where clause\n -> [Either [Declaration] (SourceAnn, Binder, Expr)]\n -- ^ Declarations to desugar\n -> Expr\n -- ^ The original let-in result expression\n -> Expr\n go _ [] e = e\n go w (Right ((pos, com), binder, boundE) : ds) e =\n PositionedValue pos com $ Case [boundE] [ CaseAlternative [binder] [ MkUnguarded $ go w ds e]\n ]\n go w (Left ds:dss) e = Let w ds (go w dss e)\n\n\npartitionDecls :: [Declaration] -> [Either [Declaration] (SourceAnn, Binder, Expr)]\npartitionDecls = concatMap f . groupBy ((==) `on` isBoundValueDeclaration)\n where\n f ds@(d:_)\n | isBoundValueDeclaration d = map (Right . g) ds\n f ds = [Left ds]\n\n g (BoundValueDeclaration sa binder expr) = (sa, binder, expr)\n g _ = internalError \"partitionDecls: the impossible happened.\"\n\nisBoundValueDeclaration :: Declaration -> Bool\nisBoundValueDeclaration BoundValueDeclaration{} = True\nisBoundValueDeclaration _ = False\n","avg_line_length":33.9649122807,"max_line_length":103,"alphanum_fraction":0.6983471074} {"size":5733,"ext":"hs","lang":"Haskell","max_stars_count":11.0,"content":"{-|\n[@ISO639-1@] -\n\n[@ISO639-2@] -\n\n[@ISO639-3@] kea\n\n[@Native name@] Kriolu\n\n[@English name@] Cape Verdean Creole\n-}\nmodule Text.Numeral.Language.KEA.TestData (cardinals) where\n\n\n--------------------------------------------------------------------------------\n-- Imports\n--------------------------------------------------------------------------------\n\nimport \"numerals\" Text.Numeral.Grammar ( defaultInflection )\nimport \"this\" Text.Numeral.Test ( TestData )\n\n\n--------------------------------------------------------------------------------\n-- Test data\n--------------------------------------------------------------------------------\n\n{-\nSources:\n http:\/\/www.languagesandnumbers.com\/how-to-count-in-cape-verdean-creole\/en\/kea\/\n-}\n\ncardinals :: (Num i) => TestData i\ncardinals =\n [ ( \"default\"\n , defaultInflection\n , [ (0, \"z\u00e9ru\")\n , (1, \"um\")\n , (2, \"d\u00f3s\")\n , (3, \"tr\u00e9s\")\n , (4, \"ku\u00e1tu\")\n , (5, \"sinku\")\n , (6, \"sax\")\n , (7, \"s\u00e9ti\")\n , (8, \"oitu\")\n , (9, \"n\u00f3vi\")\n , (10, \"d\u00e9s\")\n , (11, \"\u00f3nzi\")\n , (12, \"duzi\")\n , (13, \"treizi\")\n , (14, \"katorzi\")\n , (15, \"kinzi\")\n , (16, \"dizasax\")\n , (17, \"dizas\u00e9ti\")\n , (18, \"dizoitu\")\n , (19, \"dizan\u00f3vi\")\n , (20, \"vinti\")\n , (21, \"vinti-um\")\n , (22, \"vinti-d\u00f3s\")\n , (23, \"vinti-tr\u00e9s\")\n , (24, \"vinti-ku\u00e1tu\")\n , (25, \"vinti-sinku\")\n , (26, \"vinti-sax\")\n , (27, \"vinti-s\u00e9ti\")\n , (28, \"vinti-oitu\")\n , (29, \"vinti-n\u00f3vi\")\n , (30, \"trinta\")\n , (31, \"trinti-um\")\n , (32, \"trinti-d\u00f3s\")\n , (33, \"trinti-tr\u00e9s\")\n , (34, \"trinti-ku\u00e1tu\")\n , (35, \"trinti-sinku\")\n , (36, \"trinti-sax\")\n , (37, \"trinti-s\u00e9ti\")\n , (38, \"trinti-oitu\")\n , (39, \"trinti-n\u00f3vi\")\n , (40, \"kor\u00e9nta\")\n , (41, \"kor\u00e9nti-um\")\n , (42, \"kor\u00e9nti-d\u00f3s\")\n , (43, \"kor\u00e9nti-tr\u00e9s\")\n , (44, \"kor\u00e9nti-ku\u00e1tu\")\n , (45, \"kor\u00e9nti-sinku\")\n , (46, \"kor\u00e9nti-sax\")\n , (47, \"kor\u00e9nti-s\u00e9ti\")\n , (48, \"kor\u00e9nti-oitu\")\n , (49, \"kor\u00e9nti-n\u00f3vi\")\n , (50, \"sunku\u00e9nta\")\n , (51, \"sunku\u00e9nti-um\")\n , (52, \"sunku\u00e9nti-d\u00f3s\")\n , (53, \"sunku\u00e9nti-tr\u00e9s\")\n , (54, \"sunku\u00e9nti-ku\u00e1tu\")\n , (55, \"sunku\u00e9nti-sinku\")\n , (56, \"sunku\u00e9nti-sax\")\n , (57, \"sunku\u00e9nti-s\u00e9ti\")\n , (58, \"sunku\u00e9nti-oitu\")\n , (59, \"sunku\u00e9nti-n\u00f3vi\")\n , (60, \"sas\u00e9nta\")\n , (61, \"sas\u00e9nti-um\")\n , (62, \"sas\u00e9nti-d\u00f3s\")\n , (63, \"sas\u00e9nti-tr\u00e9s\")\n , (64, \"sas\u00e9nti-ku\u00e1tu\")\n , (65, \"sas\u00e9nti-sinku\")\n , (66, \"sas\u00e9nti-sax\")\n , (67, \"sas\u00e9nti-s\u00e9ti\")\n , (68, \"sas\u00e9nti-oitu\")\n , (69, \"sas\u00e9nti-n\u00f3vi\")\n , (70, \"sat\u00e9nta\")\n , (71, \"sat\u00e9nti-um\")\n , (72, \"sat\u00e9nti-d\u00f3s\")\n , (73, \"sat\u00e9nti-tr\u00e9s\")\n , (74, \"sat\u00e9nti-ku\u00e1tu\")\n , (75, \"sat\u00e9nti-sinku\")\n , (76, \"sat\u00e9nti-sax\")\n , (77, \"sat\u00e9nti-s\u00e9ti\")\n , (78, \"sat\u00e9nti-oitu\")\n , (79, \"sat\u00e9nti-n\u00f3vi\")\n , (80, \"oit\u00e9nta\")\n , (81, \"oit\u00e9nti-um\")\n , (82, \"oit\u00e9nti-d\u00f3s\")\n , (83, \"oit\u00e9nti-tr\u00e9s\")\n , (84, \"oit\u00e9nti-ku\u00e1tu\")\n , (85, \"oit\u00e9nti-sinku\")\n , (86, \"oit\u00e9nti-sax\")\n , (87, \"oit\u00e9nti-s\u00e9ti\")\n , (88, \"oit\u00e9nti-oitu\")\n , (89, \"oit\u00e9nti-n\u00f3vi\")\n , (90, \"nov\u00e9nta\")\n , (91, \"nov\u00e9nti-um\")\n , (92, \"nov\u00e9nti-d\u00f3s\")\n , (93, \"nov\u00e9nti-tr\u00e9s\")\n , (94, \"nov\u00e9nti-ku\u00e1tu\")\n , (95, \"nov\u00e9nti-sinku\")\n , (96, \"nov\u00e9nti-sax\")\n , (97, \"nov\u00e9nti-s\u00e9ti\")\n , (98, \"nov\u00e9nti-oitu\")\n , (99, \"nov\u00e9nti-n\u00f3vi\")\n , (100, \"sem\")\n , (101, \"senti-um\")\n , (102, \"senti-d\u00f3s\")\n , (103, \"senti-tr\u00e9s\")\n , (104, \"senti-ku\u00e1tu\")\n , (105, \"senti-sinku\")\n , (106, \"senti-sax\")\n , (107, \"senti-s\u00e9ti\")\n , (108, \"senti-oitu\")\n , (109, \"senti-n\u00f3vi\")\n , (110, \"senti-d\u00e9s\")\n , (123, \"senti-vinti-tr\u00e9s\")\n , (200, \"duz\u00e9ntus\")\n , (300, \"trez\u00e9ntus\")\n , (321, \"trez\u00e9ntus-i-vinti-um\")\n , (400, \"ku\u00e1tus\u00e9ntus\")\n , (500, \"kinh\u00e9ntus\")\n , (600, \"sais\u00e9ntus\")\n , (700, \"s\u00e9tus\u00e9ntus\")\n , (800, \"oitus\u00e9ntus\")\n , (900, \"n\u00f3vis\u00e9ntus\")\n , (909, \"n\u00f3vis\u00e9ntus-i-n\u00f3vi\")\n , (990, \"n\u00f3vis\u00e9ntus-i-nov\u00e9nta\")\n , (999, \"n\u00f3vis\u00e9ntus-i-nov\u00e9nti-n\u00f3vi\")\n , (1000, \"mil\")\n , (1001, \"um mili--um\")\n , (1008, \"um mili--oitu\")\n , (1234, \"um mili-duz\u00e9ntus-i-trinti-ku\u00e1tu\")\n , (2000, \"d\u00f3s mil\")\n , (3000, \"tr\u00e9s mil\")\n , (4000, \"ku\u00e1tu mil\")\n , (4321, \"ku\u00e1tu mili-trez\u00e9ntus-i-vinti-um\")\n , (5000, \"sinku mil\")\n , (6000, \"sax mil\")\n , (7000, \"s\u00e9ti mil\")\n , (8000, \"oitu mil\")\n , (9000, \"n\u00f3vi mil\")\n , (10000, \"d\u00e9s mil\")\n , (12345, \"duzi mili-trez\u00e9ntus-i-kor\u00e9nti-sinku\")\n , (20000, \"vinti mil\")\n , (30000, \"trinta mil\")\n , (40000, \"kor\u00e9nta mil\")\n , (50000, \"sunku\u00e9nta mil\")\n , (54321, \"sunku\u00e9nti-ku\u00e1tu mili-trez\u00e9ntus-i-vinti-um\")\n , (60000, \"sas\u00e9nta mil\")\n , (70000, \"sat\u00e9nta mil\")\n , (80000, \"oit\u00e9nta mil\")\n , (90000, \"nov\u00e9nta mil\")\n , (100000, \"um sem mil\")\n , (123456, \"senti-vinti-tr\u00e9s mili-ku\u00e1tus\u00e9ntus-i-sunku\u00e9nti-sax\")\n , (200000, \"duz\u00e9ntus mil\")\n , (300000, \"trez\u00e9ntus mil\")\n , (400000, \"ku\u00e1tus\u00e9ntus mil\")\n , (500000, \"kinh\u00e9ntus mil\")\n , (600000, \"sais\u00e9ntus mil\")\n , (654321, \"sais\u00e9ntus-i-sunku\u00e9nti-ku\u00e1tu mili-trez\u00e9ntus-i-vinti-um\")\n , (700000, \"s\u00e9tus\u00e9ntus mil\")\n , (800000, \"oitus\u00e9ntus mil\")\n , (900000, \"n\u00f3vis\u00e9ntus mil\")\n , (1000000, \"um miliom\")\n , (1234567, \"um miliom duz\u00e9ntus-i-trinti-ku\u00e1tu mili-kinh\u00e9ntus-i-sas\u00e9nti-s\u00e9ti\")\n , (7654321, \"s\u00e9ti miliom sais\u00e9ntus-i-sunku\u00e9nti-ku\u00e1tu mili-trez\u00e9ntus-i-vinti-um\")\n , (1000000000, \"um biliom\")\n ]\n )\n ]\n","avg_line_length":28.3811881188,"max_line_length":86,"alphanum_fraction":0.4491540206} {"size":2567,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"{-# LANGUAGE InstanceSigs #-}\n\nimport System.Random\nimport Control.Monad\n\nnewtype State s a = \n State {runState :: s -> (a,s)}\n\ninstance Functor (State s) where \n fmap :: (a-> b) -> State s a -> State s b\n -- fmap f (State g) = State (\\s -> (\\(a,s') -> (f a , s')) $ g s ) \n fmap f (State g) = State $ \\s ->\n let (a, s') = g s \n in (f a, s') \n\n-- *Main> runState ((+1) <$> (State $ \\s -> (0,s))) 0\n-- (1,0)\n\n-- (<*>) :: State s (a -> b)\n-- -> State s a\n-- -> State s b\ninstance Applicative (State s) where \n pure x = State (\\s -> (x, s))\n (<*>) :: State s (a -> b) -> State s a -> State s b\n (<*>) (State sab) (State sa) = State $ \\s ->\n let (f, s') = sab s\n (a, s'') = sa s' \n in (f a, s'') \n \n\n-- incState :: State Int Int\nincState = State $ \\s -> (s + 1, s + 1)\n\nran = runState ((,,,) <$> incState <*> incState <*> incState <*> incState) 0\n\n -- (>>=) :: State s a\n -- -> (a -> State s b)\n -- -> State s b\ninstance Monad (State s) where\n return = pure\n (>>=) :: State s a -> (a -> State s b) -> State s b\n (State f) >>= g = State $ \\s ->\n let (a, s') = f s \n ssb = g a \n in runState ssb s' \n\n -- pattern matching with State, is like what runState is doing, simply unwrapping\n -- let (a, s') = f s\n -- State ssb = g a \n -- (b, s'') = ssb s'\n -- in (b, s'') \n\n-- Yeah, I specifically chose a calculation that required Monad instead of Applicative, since the value of y is dependant on x, the result of incState. You need Monad for that.\nstatemonadexample = runState (do { x <- incState; y <- replicateM x incState; return (x, y) }) 5\n\n\n-- *Main> statemonadexample\n-- ((6,[7,8,9,10,11,12]),12)\n\nget :: State s s\nget = State $ (,) <$> id <*> id\n\nget_ = (,) <$> id <*> id \n\nget_' :: State s s\nget_' = State $ \\x -> (x,x) \ngeta = (,) <$> id \n\nput :: s -> State s ()\n-- put s = State $ (,) <$> mempty <*> id\nput s = State $ \\x -> ((), s)\n-- Prelude> runState (put \"blah\") \"woot\"\n-- ((),\"blah\")\n\n\nexec :: State s a -> s -> s\nexec (State sa) s = snd (sa s)\n\n-- Prelude> exec (put \"wilma\") \"daphne\"\n-- \"wilma\"\n-- Prelude> exec get \"scooby papu\"\n-- \"scooby papu\"\n\neval :: State s a -> s -> a\neval (State sa) = fst . sa \n\n-- Prelude> eval get \"bunnicula\"\n-- \"bunnicula\"\n-- Prelude> eval get \"stake a bunny\"\n-- \"stake a bunny\"\n\nmodify :: (s -> s) -> State s ()\nmodify f = State (\\s -> ((), f s)) \n\n-- Should behave like the following:\n-- Prelude> runState (modify (+1)) 0\n-- ((),1)\n-- Prelude> runState (modify (+1) >> modify (+1)) 0\n-- ((),2)\n\n\nrev [] = []\nrev (x:xs) = rev xs ++ [x]","avg_line_length":24.9223300971,"max_line_length":176,"alphanum_fraction":0.5099337748} {"size":284,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Root.Test.Test2SpecWE where\n\nimport Test.Hspec\nimport Test.QuickCheck\nimport Control.Exception (evaluate)\n\nmain :: IO ()\nmain = hspec spec\nspec::Spec\nspec = do\n\tdescribe \"Prelude.head\" $ do\n\t\tit \"returns the first element of a list\" $ do\n\t\t\thead [23 ..] `shouldBe` (23 :: Int)\n","avg_line_length":20.2857142857,"max_line_length":47,"alphanum_fraction":0.7077464789} {"size":74,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Problem3 where\n\ntype Delt a = [a] -> [a]\n\nnil :: Delt a\nnil xs = xs","avg_line_length":12.3333333333,"max_line_length":24,"alphanum_fraction":0.6081081081} {"size":12222,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n\nmodule ExPanda\n (\n -- * Logging into ExHentai\n LoginInfo(..)\n , promptLoginInfo\n , exCookieJar\n , ExJar\n , saveExJar\n , loadExJar\n , exSession\n , happyPanda\n\n -- * Performing a search\n , ResultPage(..)\n , search\n , nextSearchPage\n , EhId(..)\n\n -- * Querying galleries\n , EhApiRequest(..)\n , queryApi\n , fetchGalleryPage\n , EhApiResponse(..)\n , EhGallery(..)\n , Bytes(..)\n\n -- * For debugging\n , searchHtml\n , parseGalleryPage\n ) where\n\nimport Control.Exception (try)\nimport Data.Char (isDigit)\nimport Data.List (intercalate)\n\nimport Control.Lens hiding (deep, (.=), (<~))\nimport Data.Aeson\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString.Lazy.Char8 as Char8\nimport Data.Text (pack, unpack)\nimport Data.Time.Calendar (fromGregorianValid)\nimport Data.Time.Clock (UTCTime (..))\nimport Data.Time.Clock.POSIX (posixSecondsToUTCTime)\nimport Network.HTTP.Client\n (CookieJar, createCookieJar, destroyCookieJar)\nimport Network.HTTP.Client.TLS (tlsManagerSettings)\nimport Network.Wreq hiding ((:=), cookies)\nimport qualified Network.Wreq as Wreq (FormParam ((:=)))\nimport qualified Network.Wreq.Session as S\nimport System.Console.Haskeline\nimport Text.HandsomeSoup (css, parseHtml, (!))\nimport Text.Read (readMaybe)\nimport Text.Regex.Applicative\nimport Text.XML.HXT.Core hiding (when)\n\n\nplzDon't :: String -> Maybe a -> a\nplzDon't errMsg Nothing = error errMsg\nplzDon't _ (Just x) = x\n\n\ncookies :: Lens' CookieJar [Cookie]\ncookies f jar = createCookieJar <$> f (destroyCookieJar jar)\n\n\ndata LoginInfo = LoginInfo\n { username :: !String\n , password :: !String\n } deriving (Show, Read, Eq)\n\n\n-- | Asks for login info. Doesn't really care if it's valid or not.\npromptLoginInfo :: IO LoginInfo\npromptLoginInfo = runInputT defaultSettings $ do\n let\n keepGet :: InputT IO (Maybe a) -> InputT IO a\n keepGet m = m >>= \\x ->\n case x of\n Just y -> return y\n Nothing -> keepGet m\n\n usr <- keepGet $ getInputLine \"Account: \"\n pwd <- keepGet $ getPassword (Just '*') \"Password: \"\n\n return $ LoginInfo usr pwd\n\n\n-- | A 'CookieJar' that is \/supposed\/ to be able to view exhentai.\n--\n-- Its main use is to run an 'exSession'.\nnewtype ExJar = ExJar CookieJar deriving (Show, Read)\n\nexJar :: CookieJar -> ExJar\nexJar = ExJar . (cookies . traverse . cookieDomain .~ \"exhentai.org\")\n\nsaveExJar :: FilePath -> ExJar -> IO ()\nsaveExJar path jar = writeFile path (show jar)\n\nloadExJar :: FilePath -> IO (Maybe ExJar)\nloadExJar path = do\n eitherContent <- try $ readFile path :: IO (Either IOError String)\n return $ case eitherContent of\n Left _ -> Nothing\n Right content -> readMaybe content\n\n\n-- | Tries to login to exhentai.\nexCookieJar :: LoginInfo -> IO (Maybe ExJar)\nexCookieJar (LoginInfo usr pwd) = do\n let\n loginUrl = \"https:\/\/forums.e-hentai.org\/index.php?act=Login&CODE=01\"\n\n (<~) = (Wreq.:=) :: ByteString -> String -> FormParam\n formData =\n [ \"CookieDate\" <~ \"1\"\n , \"b\" <~ \"d\"\n , \"bt\" <~ \"1-1\"\n , \"UserName\" <~ usr\n , \"PassWord\" <~ pwd\n ]\n\n res <- post loginUrl formData\n let jar = res ^. responseCookieJar\n\n return $ if jar ^. cookies . to null\n then Nothing\n else Just $ exJar jar\n\n\n-- maybe put the session into a reader so we can hide the session\n-- do we\/i need to though?\nexSession :: ExJar -> (S.Session -> IO a) -> IO a\nexSession (ExJar jar) = S.withSessionControl (Just jar) tlsManagerSettings\n\n\npanda :: Response body -> Bool\npanda = all (not . isGif) . (^.. responseHeader \"content-type\")\n where isGif = (==) \"image\/gif\"\n\n-- | Checks if the exhentai homepage is accessible.\nhappyPanda :: ExJar -> IO Bool\nhappyPanda jar = exSession jar $ \\sess ->\n panda <$> S.get sess \"https:\/\/exhentai.org\/\"\n\n\ndata EhId = EhId\n { gid :: !Int\n , token :: !String\n } deriving (Show, Eq)\n\ninstance ToJSON EhId where\n toJSON (EhId gid token) = toJSON [toJSON gid, toJSON token]\n\nreadEhId :: String -> EhId\nreadEhId s = plzDon't (\"Fail to parse eh url \" ++ s) $ s =~ ehIdParser\n\nehIdParser :: RE Char EhId\nehIdParser = EhId <$> (shit *> gid) <*> slashed notSlash <* notSlash\n where\n shit = some anySym <* string \".org\/g\/\"\n gid = read <$> some (psym isDigit)\n slashed p = sym '\/' *> p <* sym '\/'\n notSlash = many (psym (\/= '\/'))\n\nehIdUrl :: EhId -> String\nehIdUrl (EhId gid token) =\n intercalate \"\/\" [\"https:\/\/ehentai.org\/g\", show gid, token, \"\"]\n\n\ndata EhCategory = Doujinshi\n | Manga\n | ArtistCg\n | GameCg\n | Western\n | NonH\n | ImageSet\n | Cosplay\n | AsainPorn\n | Misc\n deriving (Show, Eq)\n\ninstance FromJSON EhCategory where\n parseJSON (String s) = return . readCategoryJson . unpack $ s\n parseJSON _ = fail \"EhCategory JSON not a string\"\n\nreadCategory, readCategoryJson :: String -> EhCategory\nreadCategory \"doujinshi\" = Doujinshi\nreadCategory \"manga\" = Manga\nreadCategory \"artistcg\" = ArtistCg\nreadCategory \"gamecg\" = GameCg\nreadCategory \"western\" = Western\nreadCategory \"non-h\" = NonH\nreadCategory \"imageset\" = ImageSet\nreadCategory \"cosplay\" = Cosplay\nreadCategory \"asainporn\" = AsainPorn\nreadCategory _ = Misc\n\nreadCategoryJson \"Doujinshi\" = Doujinshi\nreadCategoryJson \"Manga\" = Manga\nreadCategoryJson \"Artist CG Sets\" = ArtistCg\nreadCategoryJson \"Game CG Sets\" = GameCg\nreadCategoryJson \"Western\" = Western\nreadCategoryJson \"Non-H\" = NonH\nreadCategoryJson \"Image Sets\" = ImageSet\nreadCategoryJson \"Cosplay\" = Cosplay\nreadCategoryJson \"Asain Porn\" = AsainPorn\nreadCategoryJson _ = Misc\n\n\ndata ResultPage = ResultPage\n { matches :: ![(String, EhId)] -- ^ A list of @(title, id)@s\n , nextPageUrl :: !(Maybe String) -- ^ The next search page\n } deriving (Show, Eq)\n\nsearchOpts :: String -> Options\nsearchOpts wat = defaults & params .~ pars\n where\n setTo1 = [ \"f_doujinshi\"\n , \"f_manga\"\n , \"f_artistcg\"\n , \"f_gamecg\"\n , \"f_non-h\"\n , \"f_imageset\"\n , \"f_cosplay\"\n , \"f_asainporn\"\n , \"f_misc\"]\n setTo0 = [\"f_western\"]\n cats = map (\\p -> (p, \"1\")) setTo1 ++ map (\\p -> (p, \"0\")) setTo0\n pars = cats ++ [ (\"f_search\", pack wat)\n , (\"f_apply\", \"Apply Filter\")\n , (\"inline_set\", \"dm_l\")]\n\nsearch :: S.Session -> String -> IO ResultPage\nsearch sess wat = do\n r <- S.getWith (searchOpts wat) sess \"https:\/\/exhentai.org\/\"\n searchHtml . Char8.unpack $ r ^. responseBody\n\nnextSearchPage :: S.Session -> ResultPage -> IO (Maybe ResultPage)\nnextSearchPage _ (ResultPage _ Nothing) = return Nothing\nnextSearchPage sess (ResultPage _ (Just url)) = do\n r <- S.get sess url\n page <- searchHtml . Char8.unpack $ r ^. responseBody\n return $ Just page\n\n\n-- | A \\\"pure\\\" version of 'search' that take the webpage as input.\n-- The 'IO' is only used to parse the HTML.\nsearchHtml :: String -> IO ResultPage\nsearchHtml html = do\n let\n doc = parseHtml html\n\n getHref = getAttrValue \"href\"\n getEhId = getHref >>> arr readEhId\n getMatches = css \".it5 a\" >>> deep getText &&& getEhId\n\n getNothing = arr (const Nothing)\n getLink = deep (hasAttr \"href\") >>> getHref >>> arr Just\n maybeGetLink = ifA (hasAttr \"class\") getNothing getLink\n getMaybeLinks = css \".ptb td a\" >>> maybeGetLink\n\n matches <- runX $ doc >>> getMatches\n nextPages <- runX $ doc >>> getMaybeLinks\n\n let nextPageUrl = last nextPages\n return ResultPage {..}\n\n\nnewtype Bytes = Bytes Int deriving (Show, Eq)\n\n\ndata EhGallery = EhGallery\n { englishTitle :: !String\n , japaneseTitle :: !String\n , galleryId :: !EhId\n , category :: !EhCategory\n , posted :: !UTCTime\n , fileSize :: !Bytes\n , pages :: !Int\n , rating :: !Double\n , tags :: ![String]\n } deriving Show\n\nepochToUtc :: Int -> UTCTime\nepochToUtc = posixSecondsToUTCTime . realToFrac\n\ninstance FromJSON EhGallery where\n parseJSON = withObject \"gallery\" $ \\v -> do\n englishTitle <- v .: \"title\"\n japaneseTitle <- v .: \"title_jpn\"\n galleryId <- EhId <$> v .: \"gid\" <*> v .: \"token\"\n category <- v .: \"category\"\n posted <- epochToUtc . read <$> v .: \"posted\"\n fileSize <- Bytes <$> v .: \"filesize\"\n pages <- read <$> v .: \"filecount\"\n rating <- read <$> v .: \"rating\"\n tags <- v .: \"tags\"\n return EhGallery {..}\n\n\nnewtype EhApiRequest = EhApiRequest [EhId] deriving Show\n\ninstance ToJSON EhApiRequest where\n toJSON (EhApiRequest ids) =\n object [ \"method\" .= (\"gdata\" :: String)\n , \"namespace\" .= (1 :: Int)\n , \"gidlist\" .= ids\n ]\n\n\nnewtype EhApiResponse = EhApiResponse [EhGallery] deriving Show\n\ninstance FromJSON EhApiResponse where\n parseJSON = withObject \"response\" $ \\v ->\n EhApiResponse <$> v .: \"gmetadata\"\n\n\n-- | The [API](https:\/\/ehwiki.org\/wiki\/API) allows\n-- at most 25 entries per request, and usually\n-- 5 seconds CD between 4 sequential requests.\n--\n-- The responsed gallaries are not guaranteed to be in order.\nqueryApi :: EhApiRequest -> IO [EhGallery]\nqueryApi req = do\n -- The reason of not using @asJSON =<< post ...@ is that\n -- the response content-type is fucking text\/html; charset=UTF-8\n response <- post \"https:\/\/api.e-hentai.org\/api.php\" (toJSON req)\n return $ case decode' (response ^. responseBody) of\n Nothing -> []\n Just (EhApiResponse gs) -> gs\n\n\n-- | Info parsed from the gallery page are slightly less accurate\n-- than the API, so don't use this unless hopeless or bored.\nfetchGalleryPage :: S.Session -> EhId -> IO EhGallery\nfetchGalleryPage sess ehid = do\n response <- S.get sess (ehIdUrl ehid)\n parseGalleryPage . Char8.unpack $ response ^. responseBody\n\nparseDate :: String -> Maybe UTCTime\nparseDate str = str =~ parser\n where\n secs h m = realToFrac $ (h * 60 + m) * 60\n tryRun = plzDon't \"Can't parse date\"\n toDay y m d = tryRun $ fromGregorianValid y m d\n makeTime y mon d h min' = UTCTime (toDay y mon d) (secs h min')\n\n -- we need 2 instances of the same shit cuz they have different types\n int = read <$> some (psym isDigit)\n integer' = read <$> some (psym isDigit) <* anySym\n int' = int <* anySym\n parser = makeTime <$> integer' <*> int' <*> int' <*> int' <*> int\n\nparseSize :: String -> Bytes\nparseSize str = Bytes . floor . (* mult unit) $ x\n where\n mult \"GB\" = 1024 ** 3\n mult \"MB\" = 1024 ** 2\n mult \"KB\" = 1024\n mult \"B\" = 1\n mult _ = error \"WTF\"\n [xStr, unit] = words str\n x = read xStr :: Double\n\n-- | A \\\"pure\\\" version of 'fetchGalleryPage'.\nparseGalleryPage :: String -> IO EhGallery\nparseGalleryPage html = do\n let\n doc = parseHtml html\n\n underscoreToSpace '_' = ' '\n underscoreToSpace c = c\n fmtTag = map underscoreToSpace . drop 3\n\n getId = getAttrValue \"href\" >>> arr readEhId\n getCategory = getAttrValue \"alt\" >>> arr readCategory\n getRating = getText >>> arr (read . drop 9)\n getTags = (css \".gt\" <+> css \".gtl\") ! \"id\" >>> arr fmtTag\n\n [englishTitle] <- runX $ doc \/\/> css \"#gn\" \/\/> getText\n [japaneseTitle] <- runX $ doc \/\/> css \"#gj\" \/\/> getText\n (galleryId : _) <- runX $ doc \/\/> css \".ptds a\" >>> getId\n [category] <- runX $ doc \/\/> css \"#gdc img\" >>> getCategory\n [rating] <- runX $ doc \/\/> css \"#rating_label\" \/\/> getRating\n tags <- runX $ doc \/\/> css \"#taglist\" >>> getTags\n tableShit <- runX $ doc \/\/> css \".gdt2\" \/\/> getText\n\n let\n [dateS, _, _, _, sizeS, pagesS, _] = tableShit\n Just posted = parseDate dateS\n fileSize = parseSize sizeS\n pages = read . head . words $ pagesS\n\n return EhGallery {..}\n","avg_line_length":30.7085427136,"max_line_length":74,"alphanum_fraction":0.6054655539} {"size":1254,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Ex04 where\n\n-- Q4.1\nhalve :: [a] -> ([a], [a])\nhalve xs = (take hl xs, drop hl xs)\n where hl = length xs `quot` 2\n\n-- Q4.2\nthird1 :: [a] -> a\nthird1 xs = head (tail (tail xs))\n\nthird2 :: [a] -> a\nthird2 xs = xs !! 2\n\nthird3 :: [a] -> a\nthird3 (_:_:x:_) = x\n\n-- Q4.3\nsafetail1 :: [a] -> [a]\nsafetail1 xs = if null xs then [] else tail xs\n\nsafetail2 :: [a] -> [a]\nsafetail2 xs | null xs = []\n | otherwise = tail xs\n\nsafetail3 :: [a] -> [a]\nsafetail3 [] = []\nsafetail3 xs = tail xs\n\n-- Q4.4\n-- True || True = True\n-- True || False = True\n-- False || True = True\n-- False || False = False\n\n-- False || False = False\n-- _ || _ = True\n\n-- False || b = b\n-- _ || _ = True\n\n-- b || c | b == c = b\n-- | otherwise = True\n\n-- Q4.5\n-- (&&) b c =\n-- if b == True\n-- then if c == True\n-- then True\n-- else False\n-- else False\n\n-- Q4.6\n-- (&&) b c =\n-- if b == True\n-- then c\n-- else False\n\n-- Q4.7\nmult :: Int -> Int -> Int -> Int\nmult = \\x -> (\\y -> (\\z -> x * y * z))\n\n-- Q4.8\nluhnDouble :: Int -> Int\nluhnDouble n = if n' > 9 then n' - 9 else n'\n where n' = n * 2\n\nluhn :: Int -> Int -> Int -> Int -> Bool\nluhn n m l o = sum [luhnDouble n, m, luhnDouble l, o] `div` 10 == 0\n","avg_line_length":17.9142857143,"max_line_length":67,"alphanum_fraction":0.4728867624} {"size":150,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"import NumericalMethods.Simple\n\nmain :: IO ()\nmain = do\n let v = foldr (\\x y -> insertElement x y) E [1..500]\n let a = show v\n putStrLn a\n","avg_line_length":18.75,"max_line_length":57,"alphanum_fraction":0.5933333333} {"size":238,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE OverloadedStrings #-}\nmodule Secret where\n\nimport Data.ByteString (ByteString)\n\nsecret :: ByteString\nsecret = \"host='postgres-server' port=5432 user='example-user' password='complicated-example-password' dbname='example-db'\"\n","avg_line_length":29.75,"max_line_length":123,"alphanum_fraction":0.7731092437} {"size":607,"ext":"hs","lang":"Haskell","max_stars_count":3.0,"content":"module Number where\n\nimport Prelude hiding ((*), not)\nimport Tree\n\nzero :: Tree\nzero = Node\n\none :: Tree\none = k * zero\n\nsuccessor :: Tree -> Tree\nsuccessor n = k * n\n\nisZero :: Tree\nisZero = Node * (Node * (k * (k * (k * (k * i))))) * (Node * (Node * (k * k)) * Node)\n\nisZeroN :: Tree -> Tree\nisZeroN n = Node * n * k * (k * (k * (k * i)))\n\n-- isZeroN Node\n-- Node * Node * k * (kn 3 * i)\n-- by leaf rule\n-- k\n\n-- isZeroN 1\n-- Node * (Node * Node * Node) * k * (k * (k * (k * i)))\n-- by fork rule\n-- k * (k * (k * i))) * Node * Node\n-- k * (k * (k * i * Node) * Node)\n-- k * (k * i * Node)\n-- k * i\n","avg_line_length":18.3939393939,"max_line_length":85,"alphanum_fraction":0.4810543657} {"size":8406,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE OverloadedStrings #-}\n\nmodule ProcessModule\n ( Namespace\n , ModuleName\n , processModule\n ) where\n\nimport Data.Maybe\nimport Data.Text (Text)\nimport Data.Vector (Vector)\nimport qualified Data.Text as T\nimport qualified Data.Vector as V\n\ntype ModuleName = Text\n\ntype Namespace = Text\n\nprocessModule :: Namespace -> ModuleName -> IO Text -> Vector Text -> IO (Vector Text, [ModuleName])\nprocessModule namespace modulename loadForeign ls = do\n let importSectionLoc = findImportSection ls\n exportSectionIndex = findExportSectionIndex ls\n\n (importLines, reqModules, needsForeign) = createImportSection namespace modulename ls importSectionLoc\n exportLines = createExportSection ls exportSectionIndex\n\n foreignModule <- if needsForeign then processForeign namespace modulename loadForeign\n else return V.empty\n\n let output = V.concat $\n case importSectionLoc of\n Nothing -> case exportSectionIndex of\n Nothing ->\n [ foreignModule\n , V.singleton jsModuleHeader\n , ls\n , V.singleton (jsModuleFooter namespace modulename)\n ]\n Just ei ->\n [ foreignModule\n , V.singleton jsModuleHeader\n , V.slice 0 ei ls\n , exportLines\n , V.singleton (jsModuleFooter namespace modulename)\n ]\n Just (ii, ic) -> case exportSectionIndex of\n Nothing ->\n [ foreignModule\n , V.singleton jsModuleHeader\n , V.slice 0 ii ls\n , importLines\n , V.drop (ii+ic) ls\n , V.singleton (jsModuleFooter namespace modulename)\n ]\n Just ei ->\n [ foreignModule\n , V.singleton jsModuleHeader\n , V.slice 0 ii ls\n , importLines\n , V.slice (ii+ic) (ei - (ii + ic)) ls\n , exportLines\n , V.singleton (jsModuleFooter namespace modulename)\n ]\n\n return (output, reqModules)\n\n\n-- Searches for a string formatted as:\n--\n-- var Data_Maybe = require(\"..\/Data.Maybe\");\n--\n-- In this case will return: Just (\"Data_Maybe\", \"Data.Maybe\")\n--\nparseImportStatement :: Text -> Maybe (Text, ModuleName)\nparseImportStatement l =\n case T.stripPrefix \"var \" l of\n Nothing -> Nothing\n Just r1 -> case T.breakOn \" = require(\" r1 of\n (_, \"\") -> Nothing\n (varName, r2) -> case T.breakOn \");\" (T.drop (T.length \" = require(\") r2) of\n (_, \"\") -> Nothing\n (quotedModName, _) -> case () of\n _ | isSurroundedBy '\"' quotedModName -> Just (varName, removeRelativePath (removeQuotes quotedModName))\n _ | isSurroundedBy '\\'' quotedModName -> Just (varName, removeRelativePath (removeQuotes quotedModName))\n _ | otherwise -> Nothing\n\n where\n isSurroundedBy :: Char -> Text -> Bool\n isSurroundedBy c t =\n T.head t == c && T.last t == c\n\n removeQuotes :: Text -> Text\n removeQuotes =\n T.tail . T.init\n\n removeRelativePath :: Text -> Text\n removeRelativePath t =\n fromMaybe t (T.stripPrefix \"..\/\" t)\n\nformatImport :: Namespace -> (Text, Text) -> Text\nformatImport namespace (varName, modName) =\n T.concat [\"var \", varName, \" = \", namespace, \"[\\\"\", modName, \"\\\"];\"]\n\n-- Searches for a string formatted like the following examples:\n--\n-- \">>=\": $greater$greater$eq,\n-- bind: bind,\n-- showOrdering: showOrdering\n--\nparseExportStatement :: Text -> Maybe (Text, Text)\nparseExportStatement line =\n case parseFieldName (T.stripStart line) of\n Nothing -> Nothing\n Just (fieldName, rest) -> case parseFieldValue rest of\n Nothing -> Nothing\n Just fieldValue -> Just (fieldName, fieldValue)\n\n where\n parseFieldName :: Text -> Maybe (Text, Text)\n parseFieldName l =\n case T.head l of\n '\\\"' -> case T.breakOn \"\\\"\" (T.tail l) of\n (_, \"\") -> Nothing\n (fieldName, rest) -> Just (fieldName, T.stripStart (T.tail rest))\n _ -> case T.breakOn \":\" l of\n (_, \"\") -> Nothing\n (\"\", _) -> Nothing\n (fieldName, rest) -> Just (T.stripEnd fieldName, rest)\n\n parseFieldValue :: Text -> Maybe Text\n parseFieldValue rest =\n case T.head rest of\n ':' -> case T.breakOn \",\" (T.stripStart (T.tail rest)) of\n (fieldVal, _) -> Just (T.stripEnd fieldVal)\n _ -> Nothing\n\nformatExportStatement :: (Text, Text) -> Text\nformatExportStatement (fieldName, fieldValue) =\n T.concat [\"exports[\\\"\", fieldName, \"\\\"] = \", fieldValue, \";\"]\n\n\n\njsModuleHeader :: Text\njsModuleHeader = \"(function(exports) {\"\n\njsModuleFooter :: Namespace -> ModuleName -> Text\njsModuleFooter namespace modulename = T.concat[\"})(\", namespace, \"[\\\"\", modulename, \"\\\"] = \", namespace, \"[\\\"\", modulename, \"\\\"] || {});\"]\n\n\ncreateImportSection ::\n Namespace\n -> ModuleName\n -> Vector Text\n -> Maybe (Int, Int)\n -> (Vector Text, [ModuleName], Bool) -- ^ (import lines, req modules, foreign.js module required)\ncreateImportSection _ _ _ Nothing = (V.empty, [], False)\ncreateImportSection namespace modulename ls (Just (firstIndex, numImports)) =\n let sliced = V.slice firstIndex numImports ls\n in V.foldl' next (V.empty, [], False) sliced\n where\n next :: (Vector Text, [ModuleName], Bool) -> Text -> (Vector Text, [ModuleName], Bool)\n next (createdLines, foundReqModules, needsForeign) line =\n case parseImportStatement line of\n Nothing -> (createdLines, foundReqModules, needsForeign)\n Just (varName, reqModule) -> case reqModule == \".\/foreign\" of\n True -> let newLine = formatImport namespace (varName, modulename) -- Load the `modulename` instead of trying to load \".\/foreign\"\n in (createdLines `V.snoc` newLine, foundReqModules, True)\n False -> let newLine = formatImport namespace (varName, reqModule)\n in (createdLines `V.snoc` newLine, reqModule:foundReqModules, needsForeign)\n\ncreateExportSection :: Vector Text -> Maybe Int -> Vector Text\ncreateExportSection _ Nothing = V.empty\ncreateExportSection ls (Just exportSectionIndex) =\n let sliced = V.drop exportSectionIndex ls\n in V.foldl' next V.empty sliced\n where\n next :: Vector Text -> Text -> Vector Text\n next createdLines line =\n case parseExportStatement line of\n Nothing -> createdLines\n Just (fieldName, fieldValue) ->\n let newLine = formatExportStatement (fieldName, fieldValue)\n in createdLines `V.snoc` newLine\n\n-- Loads the source code of the foreign.js file, using the supplied loader\n-- (usually from disk) and adds the necessary header and footer\nprocessForeign :: Namespace -> ModuleName -> IO Text -> IO (Vector Text)\nprocessForeign namespace modulename loadForeign = do\n let header = jsModuleHeader\n contents <- loadForeign\n let footer = jsModuleFooter namespace modulename\n return $ V.fromList [header, contents, footer]\n\n\nfindImportSection :: Vector Text -> Maybe (Int, Int)\nfindImportSection ls =\n case V.findIndex (isJust . parseImportStatement) ls of\n Nothing -> Nothing\n Just firstIndex -> case V.findIndex (isNothing . parseImportStatement) (V.drop firstIndex ls) of\n Nothing -> Nothing\n Just numImports -> Just (firstIndex, numImports)\n\nfindExportSectionIndex :: Vector Text -> Maybe Int\nfindExportSectionIndex ls = vectorFindLastIndex isExportLine ls\n where\n isExportLine l =\n let stripped = T.strip l\n in stripped == \"module.exports = {\"\n || stripped == \"module.exports = {};\"\n\nvectorFindLastIndex :: (a -> Bool) -> Vector a -> Maybe Int\nvectorFindLastIndex p v = find' ((V.length v) - 1)\n where\n find' (-1) = Nothing\n find' index =\n if p (v V.! index) then Just index\n else find' (index - 1)\n\n","avg_line_length":38.3835616438,"max_line_length":145,"alphanum_fraction":0.5881513205} {"size":1174,"ext":"hs","lang":"Haskell","max_stars_count":49.0,"content":"{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE ViewPatterns #-}\nmodule Bioshake.Cluster.GATK(reQual) where\n\nimport Bioshake\nimport Bioshake.Cluster.Torque\nimport Bioshake.Internal.GATK\nimport Data.Implicit\nimport Development.Shake\nimport Development.Shake.FilePath\nimport System.IO.Temp\n\ninstance (Implicit_ Config, Referenced a, Pathable a, IsBam a) => Buildable a ReQual where\n build (ReQual jar) a@(paths -> [input]) [out] =\n liftIO . withSystemTempDirectory \"gatk\" $ \\tmpDir -> do\n let tmpFile = tmpDir <\/> \"recal.grp\"\n () <- submit \"java\"\n [\"-jar\", jar]\n [\"-T\", \"BaseRecalibrator\"]\n [\"-R\", getRef a]\n [\"-I\", input]\n [\"-knownSites\", \"latest_dbsnp.vcf\"]\n [\"-o\", tmpFile]\n (param_ :: Config)\n () <- submit \"java\"\n [\"-jar\", jar]\n [\"-T\", \"PrintReads\"]\n [\"-R\", getRef a]\n [\"-I\", input]\n [\"-BQSR\", tmpFile]\n [\"-o\", out]\n (param_ :: Config)\n return ()\n","avg_line_length":31.7297297297,"max_line_length":90,"alphanum_fraction":0.5442930153} {"size":2813,"ext":"hs","lang":"Haskell","max_stars_count":8.0,"content":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TemplateHaskell #-}\n\n-- | This whole module is basically a huge hack that\n-- compiles a haskell module and returns the expression\n-- bound to the top-level, non-recursive `expr` binding.\nmodule Analyses.Syntax.MkCoreFromFile where\n\nimport Control.Monad.IO.Class\nimport Data.Maybe (fromMaybe)\nimport Data.Monoid (First (..))\nimport qualified Data.Text as Text\nimport Distribution.Simple.LocalBuildInfo\nimport Distribution.Simple.Toolkit (getGHCPackageDBFlags,\n localBuildInfoQ)\nimport Prelude hiding (FilePath)\nimport qualified Prelude\nimport System.Directory (canonicalizePath)\nimport System.FilePath (splitSearchPath)\nimport Turtle\n\nimport CoreSyn\nimport CoreTidy (tidyExpr)\nimport DynFlags\nimport GHC\nimport qualified GHC.Paths\nimport Id\nimport Name\nimport Packages\nimport VarEnv (emptyTidyEnv)\n\nfindTopLevelDecl :: String -> CoreProgram -> Maybe CoreExpr\nfindTopLevelDecl occ = getFirst . foldMap (First . findName)\n where\n findName (NonRec id_ rhs)\n | occNameString (occName (idName id_)) == occ\n = Just rhs\n findName _ = Nothing\n\n\ncompileCoreExpr :: Prelude.FilePath -> IO CoreExpr\ncompileCoreExpr modulePath = runGhc (Just GHC.Paths.libdir) $ do\n -- Don't generate any artifacts\n _ <- getSessionDynFlags >>= setSessionDynFlags . (\\df -> df { hscTarget = HscNothing })\n -- Set up the package database\n\n addPkgDbs $(localBuildInfoQ)\n m <- liftIO (canonicalizePath modulePath) >>= compileToCoreModule\n pure $\n tidyExpr emptyTidyEnv\n -- . pprTraceIt \"expr\"\n . fromMaybe (error \"Could not find top-level non-recursive binding `expr`\")\n . findTopLevelDecl \"expr\"\n . cm_binds\n $ m\n\n\nstackPkgDbs :: MonadIO m => m (Maybe [Prelude.FilePath])\nstackPkgDbs = do\n (ec, paths) <- procStrict \"stack\" [\"path\", \"--ghc-package-path\"] mempty\n if ec == ExitSuccess\n then pure (Just (splitSearchPath (Text.unpack paths)))\n else pure Nothing\n\n\n-- | Add a list of package databases to the Ghc monad.\naddPkgDbs :: (MonadIO m, GhcMonad m) => LocalBuildInfo -> m ()\naddPkgDbs lbi = do\n dfs <- getSessionDynFlags\n let pkgs = getGHCPackageDBFlags lbi\n#if MIN_VERSION_Cabal(2,0,0)\n let dfs' = dfs { packageDBFlags = pkgs }\n#else\n let dfs' = dfs { extraPkgConfs = (pkgs ++) . extraPkgConfs dfs }\n#endif\n _ <- setSessionDynFlags dfs'\n _ <- liftIO $ initPackages dfs'\n return ()\n","avg_line_length":35.1625,"max_line_length":89,"alphanum_fraction":0.6160682545} {"size":2224,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"module SetsWithLists\n ( Set -- Set a = Set {storage :: [a]}\n , isLegalSet -- :: (Eq a) => Set a -> Bool\n , emptySet -- :: Set a\n , singletonSet -- :: a -> Set a\n , setSize -- :: Integral b => Set a -> b\n , setEquals -- :: (Eq a) => Set a -> Set a -> Bool\n , containsElement -- :: (Eq a) => Set a -> a -> Bool\n , addElement -- :: (Eq a) => a -> Set a -> Set a\n , removeElement -- :: (Eq a) => a -> Set a -> Set a\n , setUnion -- :: (Eq a) => Set a -> Set a -> Set a\n , setIntersection -- :: (Eq a) => Set a -> Set a -> Set a\n , setDifference -- :: (Eq a) => Set a -> Set a -> Set a\n , setMap -- :: (Eq b) => (a -> b) -> Set a -> Set b\n , setFilter -- :: (a -> Bool) -> Set a -> Set a\n ) where\n\nimport Data.List\n\nnewtype Set a = Set\n { storage :: [a]\n } deriving (Show)\n\nisLegalSet :: (Eq a) => Set a -> Bool\nisLegalSet (Set list) = list == nub list\n\nemptySet :: Set a\nemptySet = Set []\n\nsingletonSet :: a -> Set a\nsingletonSet element = Set [element]\n\nsetSize :: Integral b => Set a -> b\nsetSize (Set list) =\n case list of\n [] -> 0\n _:xs -> 1 + setSize (Set xs)\n\nsetEquals :: (Eq a) => Set a -> Set a -> Bool\nsetA `setEquals` setB =\n case (storage setA, storage setB) of\n ([], []) -> True\n ([], _) -> False\n (_, []) -> False\n (x:xs, _) ->\n containsElement setB x && Set xs `setEquals` removeElement x setB\n\ncontainsElement :: (Eq a) => Set a -> a -> Bool\ncontainsElement (Set list) element = element `elem` list\n\naddElement :: (Eq a) => a -> Set a -> Set a\naddElement element set = Set (element : storage (removeElement element set))\n\nremoveElement :: (Eq a) => a -> Set a -> Set a\nremoveElement element (Set list) = Set (delete element list)\n\nsetUnion :: (Eq a) => Set a -> Set a -> Set a\nsetUnion (Set list_a) (Set list_b) = Set (list_a `union` list_b)\n\nsetIntersection :: (Eq a) => Set a -> Set a -> Set a\nsetIntersection (Set list_a) (Set list_b) = Set (list_a `intersect` list_b)\n\nsetDifference :: (Eq a) => Set a -> Set a -> Set a\nsetDifference (Set list_a) (Set list_b) = Set (list_a \\\\ list_b)\n\nsetMap :: (Eq b) => (a -> b) -> Set a -> Set b\nsetMap f (Set list) = Set (nub (map f list))\n\nsetFilter :: (a -> Bool) -> Set a -> Set a\nsetFilter f (Set list) = Set (filter f list)\n","avg_line_length":31.323943662,"max_line_length":76,"alphanum_fraction":0.5651978417} {"size":8066,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Hasura.RQL.DDL.Metadata\n ( runReplaceMetadata\n , runExportMetadata\n , runClearMetadata\n , runReloadMetadata\n , runDumpInternalState\n , runGetInconsistentMetadata\n , runDropInconsistentMetadata\n\n , module Hasura.RQL.DDL.Metadata.Types\n ) where\n\nimport Hasura.Prelude\n\nimport qualified Data.Aeson.Ordered as AO\nimport qualified Data.HashMap.Strict.InsOrd as OMap\nimport qualified Data.HashSet as HS\nimport qualified Data.List as L\nimport qualified Database.PG.Query as Q\n\nimport Control.Lens ((.~), (^?))\nimport Data.Aeson\n\nimport Hasura.RQL.DDL.Action\nimport Hasura.RQL.DDL.ComputedField\nimport Hasura.RQL.DDL.CustomTypes\nimport Hasura.RQL.DDL.EventTrigger\nimport Hasura.RQL.DDL.Permission\nimport Hasura.RQL.DDL.Relationship\nimport Hasura.RQL.DDL.RemoteRelationship\nimport Hasura.RQL.DDL.RemoteSchema\nimport Hasura.RQL.DDL.ScheduledTrigger\nimport Hasura.RQL.DDL.Schema\n\nimport Hasura.EncJSON\nimport Hasura.RQL.DDL.Metadata.Types\nimport Hasura.RQL.Types\n\nrunClearMetadata\n :: (CacheRWM m, MetadataM m, MonadIO m, QErrM m)\n => ClearMetadata -> m EncJSON\nrunClearMetadata _ = do\n metadata <- getMetadata\n -- We can infer whether the server is started with `--database-url` option\n -- (or corresponding env variable) by checking the existence of @'defaultSource'\n -- in current metadata.\n let maybeDefaultSourceMetadata = metadata ^? metaSources.ix defaultSource\n emptyMetadata' = case maybeDefaultSourceMetadata of\n Nothing -> emptyMetadata\n Just defaultSourceMetadata ->\n -- If default postgres source is defined, we need to set metadata\n -- which contains only default source without any tables and functions.\n let emptyDefaultSource = SourceMetadata defaultSource mempty mempty\n $ _smConfiguration defaultSourceMetadata\n in emptyMetadata\n & metaSources %~ OMap.insert defaultSource emptyDefaultSource\n runReplaceMetadata $ RMWithSources emptyMetadata'\n\n{- Note [Clear postgres schema for dropped triggers]\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThere was an issue (https:\/\/github.com\/hasura\/graphql-engine\/issues\/5461)\nfixed (via https:\/\/github.com\/hasura\/graphql-engine\/pull\/6137) related to\nevent triggers while replacing metadata in the catalog prior to metadata\nseparation. The metadata separation solves the issue naturally, since the\n'hdb_catalog.event_triggers' table is no more in use and new\/updated event\ntriggers are processed in building schema cache. But we need to drop the\npg trigger and archive events for dropped event triggers. This is handled\nexplicitly in @'runReplaceMetadata' function.\n-}\n\nrunReplaceMetadata\n :: ( QErrM m\n , CacheRWM m\n , MetadataM m\n , MonadIO m\n )\n => ReplaceMetadata -> m EncJSON\nrunReplaceMetadata replaceMetadata = do\n oldMetadata <- getMetadata\n metadata <- case replaceMetadata of\n RMWithSources m -> pure m\n RMWithoutSources MetadataNoSources{..} -> do\n defaultSourceMetadata <- onNothing (OMap.lookup defaultSource $ _metaSources oldMetadata) $\n throw400 NotSupported $ \"cannot import metadata without sources since no default source is defined\"\n let newDefaultSourceMetadata = defaultSourceMetadata\n { _smTables = _mnsTables\n , _smFunctions = _mnsFunctions\n }\n pure $ (metaSources.ix defaultSource .~ newDefaultSourceMetadata) oldMetadata\n putMetadata metadata\n buildSchemaCacheStrict\n -- See Note [Clear postgres schema for dropped triggers]\n for_ (OMap.toList $ _metaSources metadata) $ \\(source, newSourceCache) ->\n onJust (OMap.lookup source $ _metaSources oldMetadata) $ \\oldSourceCache -> do\n let getTriggersMap = OMap.unions . map _tmEventTriggers . OMap.elems . _smTables\n oldTriggersMap = getTriggersMap oldSourceCache\n newTriggersMap = getTriggersMap newSourceCache\n droppedTriggers = OMap.keys $ oldTriggersMap `OMap.difference` newTriggersMap\n sourceConfig <- _pcConfiguration <$> askPGSourceCache source\n for_ droppedTriggers $\n \\name -> liftEitherM $ liftIO $ runExceptT $\n runLazyTx (_pscExecCtx sourceConfig) Q.ReadWrite $\n liftTx $ delTriggerQ name >> archiveEvents name\n\n pure successMsg\n\nrunExportMetadata\n :: (MetadataM m)\n => ExportMetadata -> m EncJSON\nrunExportMetadata _ =\n AO.toEncJSON . metadataToOrdJSON <$> getMetadata\n\nrunReloadMetadata :: (QErrM m, CacheRWM m, MetadataM m) => ReloadMetadata -> m EncJSON\nrunReloadMetadata (ReloadMetadata reloadRemoteSchemas) = do\n sc <- askSchemaCache\n let remoteSchemaInvalidations =\n if reloadRemoteSchemas then HS.fromList (getAllRemoteSchemas sc) else mempty\n cacheInvalidations = CacheInvalidations\n { ciMetadata = True\n , ciRemoteSchemas = remoteSchemaInvalidations\n , ciSources = HS.singleton defaultSource\n }\n metadata <- getMetadata\n buildSchemaCacheWithOptions CatalogUpdate cacheInvalidations metadata\n pure successMsg\n\nrunDumpInternalState\n :: (QErrM m, CacheRM m)\n => DumpInternalState -> m EncJSON\nrunDumpInternalState _ =\n encJFromJValue <$> askSchemaCache\n\n\nrunGetInconsistentMetadata\n :: (QErrM m, CacheRM m)\n => GetInconsistentMetadata -> m EncJSON\nrunGetInconsistentMetadata _ = do\n inconsObjs <- scInconsistentObjs <$> askSchemaCache\n return $ encJFromJValue $ object\n [ \"is_consistent\" .= null inconsObjs\n , \"inconsistent_objects\" .= inconsObjs\n ]\n\nrunDropInconsistentMetadata\n :: (QErrM m, CacheRWM m, MetadataM m)\n => DropInconsistentMetadata -> m EncJSON\nrunDropInconsistentMetadata _ = do\n sc <- askSchemaCache\n let inconsSchObjs = L.nub . concatMap imObjectIds $ scInconsistentObjs sc\n -- Note: when building the schema cache, we try to put dependents after their dependencies in the\n -- list of inconsistent objects, so reverse the list to start with dependents first. This is not\n -- perfect \u2014 a completely accurate solution would require performing a topological sort \u2014 but it\n -- seems to work well enough for now.\n metadataModifier <- execWriterT $ mapM_ (tell . purgeMetadataObj) (reverse inconsSchObjs)\n metadata <- getMetadata\n putMetadata $ unMetadataModifier metadataModifier $ metadata\n buildSchemaCacheStrict\n return successMsg\n\npurgeMetadataObj :: MetadataObjId -> MetadataModifier\npurgeMetadataObj = \\case\n MOSource source -> MetadataModifier $ metaSources %~ OMap.delete source\n MOSourceObjId source sourceObjId -> case sourceObjId of\n SMOTable qt -> dropTableInMetadata source qt\n SMOTableObj qt tableObj -> MetadataModifier $\n tableMetadataSetter source qt %~ case tableObj of\n MTORel rn _ -> dropRelationshipInMetadata rn\n MTOPerm rn pt -> dropPermissionInMetadata rn pt\n MTOTrigger trn -> dropEventTriggerInMetadata trn\n MTOComputedField ccn -> dropComputedFieldInMetadata ccn\n MTORemoteRelationship rn -> dropRemoteRelationshipInMetadata rn\n SMOFunction qf -> dropFunctionInMetadata source qf\n MORemoteSchema rsn -> dropRemoteSchemaInMetadata rsn\n MORemoteSchemaPermissions rsName role -> dropRemoteSchemaPermissionInMetadata rsName role\n MOCustomTypes -> clearCustomTypesInMetadata\n MOAction action -> dropActionInMetadata action -- Nothing\n MOActionPermission action role -> dropActionPermissionInMetadata action role\n MOCronTrigger ctName -> dropCronTriggerInMetadata ctName\n","avg_line_length":45.061452514,"max_line_length":107,"alphanum_fraction":0.686461691} {"size":6635,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE CPP #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Sound.OpenAL.AL.Listener\n-- Copyright : (c) Sven Panne 2003-2016\n-- License : BSD3\n-- \n-- Maintainer : Sven Panne <svenpanne@gmail.com>\n-- Stability : stable\n-- Portability : portable\n--\n-- This module corresponds to sections 4.1 (Basic Listener and Source\n-- Attributes) and 4.2 (Listener Object) of the OpenAL Specification and\n-- Reference (version 1.1).\n-- \n-- The listener object defines various properties that affect processing of the\n-- sound for the actual output. The listener is unique for an OpenAL Context,\n-- and has no name. By controlling the listener, the application controls the\n-- way the user experiences the virtual world, as the listener defines the\n-- sampling\\\/pickup point and orientation, and other parameters that affect the\n-- output stream.\n-- \n-- It is entirely up to the driver and hardware configuration, i.e. the\n-- installation of OpenAL as part of the operating system and hardware setup,\n-- whether the output stream is generated for headphones or 2 speakers, 4.1\n-- speakers, or other arrangements, whether (and which) HRTFs are applied,\n-- etc...\n--\n---------------------------------------------------------------------------------\n\nmodule Sound.OpenAL.AL.Listener (\n listenerPosition, listenerVelocity, Gain, listenerGain, orientation\n) where\n\n#if __GLASGOW_HASKELL__ >= 704\n-- Make the foreign imports happy.\nimport Foreign.C.Types\n#endif\n\nimport Data.StateVar ( StateVar, makeStateVar )\nimport Foreign.Marshal.Array ( allocaArray, withArray )\nimport Foreign.Marshal.Utils ( with )\nimport Foreign.Ptr ( Ptr )\nimport Foreign.Storable ( Storable )\nimport Linear ( V3(..) )\n\nimport Sound.OpenAL.AL.BasicTypes\nimport Sound.OpenAL.AL.PeekPoke\nimport Sound.OpenAL.AL.QueryUtils\n\n--------------------------------------------------------------------------------\n\n-- | 'listenerPosition' contains the current location of the listener in the\n-- world coordinate system. Any 3-tuple of valid float values is allowed.\n-- Implementation behavior on encountering NaN and infinity is not defined. The\n-- initial position is ('V3' 0 0 0).\n\nlistenerPosition :: StateVar (V3 ALfloat)\nlistenerPosition = makeListenerVar GetPosition 3 (peek3 V3) listener3f\n\n--------------------------------------------------------------------------------\n\n-- | 'listenerVelocity' contains current velocity (speed and direction) of the\n-- listener in the world coordinate system. Any 3-tuple of valid float\n-- values is allowed, and the initial velocity is ('V3' 0 0 0).\n-- 'listenerVelocity' does not affect 'listenerPosition'. OpenAL does not\n-- calculate the velocity from subsequent position updates, nor does it\n-- adjust the position over time based on the specified velocity. Any\n-- such calculation is left to the application. For the purposes of sound\n-- processing, position and velocity are independent parameters affecting\n-- different aspects of the sounds.\n--\n-- 'listenerVelocity' is taken into account by the driver to synthesize the\n-- Doppler effect perceived by the listener for each source, based on the\n-- velocity of both source and listener, and the Doppler related parameters.\n\nlistenerVelocity :: StateVar (V3 ALfloat)\nlistenerVelocity = makeListenerVar GetVelocity 3 (peek3 V3) listener3f\n\n--------------------------------------------------------------------------------\n\n-- | A scalar amplitude multiplier.\ntype Gain = ALfloat\n\n-- | 'listenerGain' contains a scalar amplitude multiplier, which is effectively\n-- applied to all sources in the current context. The initial value 1 means\n-- that the sound is unattenuated. A 'listenerGain' value of 0.5 is equivalent\n-- to an attenuation of 6dB. The value zero equals silence (no output). Driver\n-- implementations are free to optimize this case and skip mixing and processing\n-- stages where applicable. The implementation is in charge of ensuring\n-- artifact-free (click-free) changes of gain values and is free to defer actual\n-- modification of the sound samples, within the limits of acceptable latencies.\n--\n-- A 'listenerGain' larger than 1 (amplification) is permitted. However, the\n-- implementation is free to clamp the total gain (effective gain per source\n-- times listener gain) to 1 to prevent overflow.\n\nlistenerGain :: StateVar Gain\nlistenerGain = makeListenerVar GetGain 1 (peek1 id) listenerf\n\n--------------------------------------------------------------------------------\n\n-- | 'orientation' contains an \\\"at\\\" vector and an \\\"up\\\" vector, where the\n-- \\\"at\\\" vector represents the \\\"forward\\\" direction of the listener and the\n-- orthogonal projection of the \\\"up\\\" vector into the subspace perpendicular to\n-- the \\\"at\\\" vector represents the \\\"up\\\" direction for the listener. OpenAL\n-- expects two vectors that are linearly independent. These vectors are not\n-- expected to be normalized. If the two vectors are linearly dependent,\n-- behavior is undefined. The initial orientation is ('V3' 0 0 (-1),\n-- 'V3' 0 1 0), i.e. looking down the Z axis with the Y axis pointing\n-- upwards.\n\norientation :: StateVar (V3 ALfloat, V3 ALfloat)\norientation = makeListenerVar GetOrientation 6 (peek6 V3) listenerVector6\n\n--------------------------------------------------------------------------------\n\nlistenerf :: GetPName -> ALfloat -> IO ()\nlistenerf = alListenerf . marshalGetPName\n\nforeign import ccall unsafe \"alListenerf\"\n alListenerf :: ALenum -> ALfloat -> IO ()\n\n--------------------------------------------------------------------------------\n\nlistener3f :: Storable a => GetPName -> a -> IO ()\nlistener3f n x = with x $ listenerfv n\n\nlistenerVector6 :: GetPName -> (V3 ALfloat, V3 ALfloat) -> IO ()\nlistenerVector6 n (x, y) = withArray [x, y] $ listenerfv n\n\nlistenerfv :: GetPName -> Ptr a -> IO ()\nlistenerfv = alListenerfv . marshalGetPName\n\nforeign import ccall unsafe \"alListenerfv\"\n alListenerfv :: ALenum -> Ptr a -> IO ()\n\n--------------------------------------------------------------------------------\n\ngetListenerfv :: GetPName -> Ptr ALfloat -> IO ()\ngetListenerfv = alGetListenerfv . marshalGetPName\n\nforeign import ccall unsafe \"alGetListenerfv\"\n alGetListenerfv :: ALenum -> Ptr ALfloat -> IO ()\n\n--------------------------------------------------------------------------------\n\nmakeListenerVar :: GetPName -> Int -> (Ptr ALfloat -> IO a)\n -> (GetPName -> a -> IO ()) -> StateVar a\nmakeListenerVar pname size reader writer =\n makeStateVar\n (allocaArray size $ \\buf -> do\n getListenerfv pname buf\n reader buf)\n (writer pname)\n","avg_line_length":42.5320512821,"max_line_length":81,"alphanum_fraction":0.6494348154} {"size":5459,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE OverloadedStrings #-}\n\nmodule HStream.Store.ReaderSpec (spec) where\n\nimport Control.Monad (void)\nimport Data.Bits (shiftL)\nimport Data.ByteString (ByteString)\nimport qualified Data.Map.Strict as Map\nimport qualified HStream.Store as S\nimport System.Timeout (timeout)\nimport Test.Hspec\nimport Z.Data.Vector.Base (Bytes)\n\nimport HStream.Store.SpecUtils\n\nspec :: Spec\nspec = describe \"Stream Reader\" $ do\n fileBased\n preRsmBased >> rsmBased\n misc\n\nfileBased :: Spec\nfileBased = context \"FileBasedCheckpointedReader\" $ do\n let readerName = \"reader_name_ckp_1\"\n let ckpPath = \"\/tmp\/ckp\"\n let logid = 1\n\n ckpReader <- runIO $ S.newLDFileCkpReader client readerName ckpPath 1 Nothing 10\n\n it \"the checkpoint of writing\/reading should be equal\" $ do\n checkpointStore <- S.newFileBasedCheckpointStore ckpPath\n _ <- S.append client logid \"hello\" Nothing\n until_lsn <- S.getTailLSN client logid\n S.writeCheckpoints ckpReader (Map.fromList [(logid, until_lsn)])\n S.ckpStoreGetLSN checkpointStore readerName logid `shouldReturn` until_lsn\n\n it \"read with checkpoint\" $ do\n start_lsn <- S.appendCompLSN <$> S.append client logid \"1\" Nothing\n _ <- S.append client logid \"2\" Nothing\n end_lsn <- S.appendCompLSN <$> S.append client logid \"3\" Nothing\n\n S.ckpReaderStartReading ckpReader logid start_lsn end_lsn\n [record_1] <- S.ckpReaderRead ckpReader 1\n S.recordPayload record_1 `shouldBe` (\"1\" :: Bytes)\n S.recordLSN record_1 `shouldBe` start_lsn\n\n -- last read checkpoint: start_lsn\n S.writeLastCheckpoints ckpReader [logid]\n\n [recordbs_2] <- S.ckpReaderRead ckpReader 1\n S.recordPayload recordbs_2 `shouldBe` (\"2\" :: ByteString)\n\n S.startReadingFromCheckpoint ckpReader logid end_lsn\n [record'] <- S.ckpReaderRead ckpReader 1\n S.recordPayload record' `shouldBe` (\"2\" :: Bytes)\n\n S.startReadingFromCheckpoint ckpReader logid end_lsn\n [recordbs'] <- S.ckpReaderRead ckpReader 1\n S.recordPayload recordbs' `shouldBe` (\"2\" :: ByteString)\n\npreRsmBased :: Spec\npreRsmBased = context \"Pre-RSMBasedCheckpointedReader\" $ do\n it \"get the logid for checkpointStore\" $ do\n let attrs = S.LogAttrs S.HsLogAttrs { S.logReplicationFactor = 1\n , S.logExtraAttrs = Map.empty\n }\n S.initCheckpointStoreLogID client attrs `shouldReturn` (1 `shiftL` 56)\n\nrsmBased :: Spec\nrsmBased = context \"RSMBasedCheckpointedReader\" $ do\n let readerName = \"reader_name_ckp_2\"\n let logid = 1\n ckpReader <- runIO $ S.newLDRsmCkpReader client readerName S.checkpointStoreLogID 5000 1 Nothing 10\n\n it \"the checkpoint of writing\/reading should be equal\" $ do\n _ <- S.append client logid \"hello\" Nothing\n until_lsn <- S.getTailLSN client logid\n S.writeCheckpoints ckpReader (Map.fromList [(logid, until_lsn)])\n checkpointStore <- S.newRSMBasedCheckpointStore client S.checkpointStoreLogID 5000\n S.ckpStoreGetLSN checkpointStore readerName logid `shouldReturn` until_lsn\n\n it \"read with checkpoint\" $ do\n start_lsn <- S.appendCompLSN <$> S.append client logid \"1\" Nothing\n _ <- S.append client logid \"2\" Nothing\n end_lsn <- S.appendCompLSN <$> S.append client logid \"3\" Nothing\n\n S.ckpReaderStartReading ckpReader logid start_lsn end_lsn\n [record_1] <- S.ckpReaderRead ckpReader 1\n S.recordPayload record_1 `shouldBe` (\"1\" :: Bytes)\n S.recordLSN record_1 `shouldBe` start_lsn\n\n -- last read checkpoint: start_lsn\n S.writeLastCheckpoints ckpReader [logid]\n\n [recordbs_2] <- S.ckpReaderRead ckpReader 1\n S.recordPayload recordbs_2 `shouldBe` (\"2\" :: ByteString)\n\n S.startReadingFromCheckpoint ckpReader logid end_lsn\n [record'] <- S.ckpReaderRead ckpReader 1\n S.recordPayload record' `shouldBe` (\"2\" :: Bytes)\n\n S.startReadingFromCheckpoint ckpReader logid end_lsn\n [recordbs'] <- S.ckpReaderRead ckpReader 1\n S.recordPayload recordbs' `shouldBe` (\"2\" :: ByteString)\n\nmisc :: Spec\nmisc = do\n let logid = 1\n\n it \"read timeout should return an empty results\" $ do\n reader <- S.newLDReader client 1 Nothing\n sn <- S.getTailLSN client logid\n S.readerStartReading reader logid sn sn\n void $ S.readerSetTimeout reader 0\n timeout 1000000 (S.readerRead reader 1) `shouldReturn` Just ([] :: [S.DataRecord Bytes])\n\n it \"read a gap\" $ do\n sn0 <- S.appendCompLSN <$> S.append client logid \"one\" Nothing\n sn1 <- S.appendCompLSN <$> S.append client logid \"two\" Nothing\n sn2 <- S.appendCompLSN <$> S.append client logid \"three\" Nothing\n S.trim client logid sn1\n\n reader <- S.newLDReader client 1 Nothing\n S.readerStartReading reader logid sn0 sn2\n log1 <- S.readerReadAllowGap @Bytes reader 10\n log2 <- S.readerReadAllowGap @Bytes reader 10\n log1 `shouldBe` Left (S.GapRecord logid (S.GapType 4) sn0 sn1)\n (fmap S.recordPayload <$> log2) `shouldBe` Right [\"three\" :: Bytes]\n\n -- TODO\n -- it \"Set IncludeByteOffset\" $ do\n -- reader <- S.newLDReader client 1 Nothing\n -- sn <- S.getTailLSN client logid\n -- S.readerStartReading reader logid sn sn\n -- S.recordByteOffset . head <$> S.readerRead reader 1 `shouldReturn` S.RecordByteOffsetInvalid\n\n -- S.readerSetIncludeByteOffset reader\n -- S.readerStartReading reader logid sn sn\n -- S.recordByteOffset . head <$> S.readerRead reader 1\n","avg_line_length":38.9928571429,"max_line_length":101,"alphanum_fraction":0.6960981865} {"size":9526,"ext":"hs","lang":"Haskell","max_stars_count":106.0,"content":"{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n\nmodule Eventful.Store.DynamoDB\n ( dynamoDBEventStoreReader\n , dynamoDBEventStoreWriter\n , DynamoDBEventStoreConfig (..)\n , defaultDynamoDBEventStoreConfig\n , initializeDynamoDBEventStore\n , deleteDynamoDBEventStoreTable\n , runAWSIO\n ) where\n\nimport Eventful\n\nimport Control.Exception (throw, toException)\nimport Control.Lens\nimport Control.Monad (forM_, unless, void, when)\nimport Control.Monad.Trans.AWS (runAWST)\nimport Data.Aeson\nimport Data.Conduit (($$), (=$=))\nimport qualified Data.Conduit.List as CL\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HM\nimport Data.List.NonEmpty (NonEmpty (..))\nimport Data.Maybe (fromMaybe, isJust, mapMaybe)\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Network.AWS\nimport Network.AWS.DynamoDB\nimport Safe\nimport System.IO\n\nimport Eventful.Store.DynamoDB.DynamoJSON\n\ndata DynamoDBEventStoreConfig serialized =\n DynamoDBEventStoreConfig\n { dynamoDBEventStoreConfigTableName :: Text\n , dynamoDBEventStoreConfigUUIDAttributeName :: Text\n , dynamoDBEventStoreConfigVersionAttributeName :: Text\n , dynamoDBEventStoreConfigEventAttributeName :: Text\n , dynamoDBEventStoreConfigSerializedToValue :: serialized -> AttributeValue\n , dynamoDBEventStoreConfigValueToSerialized :: AttributeValue -> serialized\n }\n\ndefaultDynamoDBEventStoreConfig :: DynamoDBEventStoreConfig Value\ndefaultDynamoDBEventStoreConfig =\n DynamoDBEventStoreConfig\n { dynamoDBEventStoreConfigTableName = \"Events\"\n , dynamoDBEventStoreConfigUUIDAttributeName = \"UUID\"\n , dynamoDBEventStoreConfigVersionAttributeName = \"Version\"\n , dynamoDBEventStoreConfigEventAttributeName = \"Event\"\n , dynamoDBEventStoreConfigSerializedToValue = valueToAttributeValue\n , dynamoDBEventStoreConfigValueToSerialized = attributeValueToValue\n }\n\n-- | An 'EventStoreReader' that uses AWS DynamoDB as the storage backend. Use a\n-- 'DynamoDBEventStoreConfig' to configure this event store.\ndynamoDBEventStoreReader\n :: DynamoDBEventStoreConfig serialized\n -> VersionedEventStoreReader AWS serialized\ndynamoDBEventStoreReader config = EventStoreReader $ getDynamoEvents config\n\ndynamoDBEventStoreWriter\n :: DynamoDBEventStoreConfig serialized\n -> VersionedEventStoreWriter AWS serialized\ndynamoDBEventStoreWriter config = EventStoreWriter $ transactionalExpectedWriteHelper getLatestVersion storeEvents'\n where\n getLatestVersion = latestEventVersion config\n storeEvents' = storeDynamoEvents config\n\ngetDynamoEvents\n :: (MonadAWS m)\n => DynamoDBEventStoreConfig serialized\n -> QueryRange UUID EventVersion\n -> m [VersionedStreamEvent serialized]\ngetDynamoEvents config@DynamoDBEventStoreConfig{..} range = do\n latestEvents <-\n paginate (queryBase config range) =$=\n CL.concatMap (view qrsItems) $$\n CL.consume\n return $ mapMaybe (decodeDynamoEvent config $ queryRangeKey range) latestEvents\n\ndecodeDynamoEvent\n :: DynamoDBEventStoreConfig serialized\n -> UUID\n -> HashMap Text AttributeValue\n -> Maybe (VersionedStreamEvent serialized)\ndecodeDynamoEvent DynamoDBEventStoreConfig{..} uuid attributeMap = do\n versionValue <- HM.lookup dynamoDBEventStoreConfigVersionAttributeName attributeMap\n versionText <- versionValue ^. avN\n version <- EventVersion <$> readMay (T.unpack versionText)\n eventAttributeValue <- HM.lookup dynamoDBEventStoreConfigEventAttributeName attributeMap\n let event = dynamoDBEventStoreConfigValueToSerialized eventAttributeValue\n return $ StreamEvent uuid version event\n\nlatestEventVersion\n :: (MonadAWS m)\n => DynamoDBEventStoreConfig serialized\n -> UUID\n -> m EventVersion\nlatestEventVersion config@DynamoDBEventStoreConfig{..} uuid = do\n latestEvents <- fmap (view qrsItems) . send $\n queryBase config (allEvents uuid)\n & qLimit ?~ 1\n & qScanIndexForward ?~ False\n return $ EventVersion $ fromMaybe (-1) $ do\n -- NB: We are in the Maybe monad here\n attributeMap <- headMay latestEvents\n versionValue <- HM.lookup dynamoDBEventStoreConfigVersionAttributeName attributeMap\n version <- versionValue ^. avN\n readMay $ T.unpack version\n\n-- | Convenience function to create a Query value for a given store config and\n-- UUID.\nqueryBase\n :: DynamoDBEventStoreConfig serialized\n -> QueryRange UUID EventVersion\n -> Query\nqueryBase DynamoDBEventStoreConfig{..} QueryRange{..} =\n query\n dynamoDBEventStoreConfigTableName\n & qKeyConditionExpression ?~ T.intercalate \" AND \" (uuidCaseExpression : versionCaseExpression)\n & qExpressionAttributeNames .~ HM.fromList (uuidAttributeName : versionAttributeName)\n & qExpressionAttributeValues .~ HM.fromList (uuidAttributeValue : versionAttributeValues)\n where\n uuidAttributeName = (\"#uuid\", dynamoDBEventStoreConfigUUIDAttributeName)\n uuidAttributeValue = (\":uuid\", attributeValue & avS ?~ uuidToText queryRangeKey)\n uuidCaseExpression = \"#uuid = :uuid\"\n\n mkStartVersionAttributeValue vers = (\":startVersion\", attributeValue & avN ?~ T.pack (show vers))\n mkEndVersionAttributeValue vers = (\":endVersion\", attributeValue & avN ?~ T.pack (show vers))\n mkJustStart (EventVersion start) = ([\"#version >= :startVersion\"], [mkStartVersionAttributeValue start])\n mkJustEnd (EventVersion end) = ([\"#version <= :endVersion\"], [mkEndVersionAttributeValue end])\n mkBoth (EventVersion start) (EventVersion end) =\n ( [\"#version BETWEEN :startVersion AND :endVersion\"]\n , [ mkStartVersionAttributeValue start\n , mkEndVersionAttributeValue end\n ]\n )\n (versionCaseExpression, versionAttributeValues) =\n case (queryRangeStart, queryRangeLimit) of\n (StartFromBeginning, NoQueryLimit) -> ([], [])\n (StartFromBeginning, MaxNumberOfEvents maxNum) -> mkJustEnd (EventVersion maxNum - 1)\n (StartFromBeginning, StopQueryAt end) -> mkJustEnd end\n (StartQueryAt start, NoQueryLimit) -> mkJustStart start\n (StartQueryAt start, MaxNumberOfEvents maxNum) -> mkBoth start (EventVersion maxNum + start - 1)\n (StartQueryAt start, StopQueryAt end) -> mkBoth start end\n versionAttributeName =\n if null versionCaseExpression then []\n else [(\"#version\", dynamoDBEventStoreConfigVersionAttributeName)]\n\nstoreDynamoEvents\n :: (MonadAWS m)\n => DynamoDBEventStoreConfig serialized\n -> UUID\n -> [serialized]\n -> m EventVersion\nstoreDynamoEvents config@DynamoDBEventStoreConfig{..} uuid events = do\n latestVersion <- latestEventVersion config uuid\n\n -- TODO: Use BatchWriteItem\n forM_ (zip events [latestVersion + 1..]) $ \\(event, EventVersion version) ->\n send $\n putItem\n dynamoDBEventStoreConfigTableName\n & piItem .~\n HM.fromList\n [ (dynamoDBEventStoreConfigUUIDAttributeName, attributeValue & avS ?~ uuidToText uuid)\n , (dynamoDBEventStoreConfigVersionAttributeName, attributeValue & avN ?~ T.pack (show version))\n , (dynamoDBEventStoreConfigEventAttributeName, dynamoDBEventStoreConfigSerializedToValue event)\n ]\n return $ latestVersion + (EventVersion $ length events)\n\n-- | Helpful function to create the events table. If a table already exists\n-- with the same name, then this function just uses that one. Note, there are\n-- no magic migrations going on here, trust this function at your own risk.\ninitializeDynamoDBEventStore\n :: (MonadAWS m)\n => DynamoDBEventStoreConfig serialized\n -> ProvisionedThroughput\n -> m ()\ninitializeDynamoDBEventStore config@DynamoDBEventStoreConfig{..} throughput = do\n eventTableExists <- getDynamoDBEventStoreTableExistence config\n unless eventTableExists $ do\n void $ send $\n createTable\n dynamoDBEventStoreConfigTableName\n (uuidKey :| [versionKey])\n throughput\n & ctAttributeDefinitions .~ attributeDefs\n void $ await tableExists (describeTable dynamoDBEventStoreConfigTableName)\n where\n uuidKey = keySchemaElement dynamoDBEventStoreConfigUUIDAttributeName Hash\n versionKey = keySchemaElement dynamoDBEventStoreConfigVersionAttributeName Range\n attributeDefs =\n [ attributeDefinition dynamoDBEventStoreConfigUUIDAttributeName S\n , attributeDefinition dynamoDBEventStoreConfigVersionAttributeName N\n ]\n\n-- | Checks if the table for the event store exists.\ngetDynamoDBEventStoreTableExistence\n :: (MonadAWS m)\n => DynamoDBEventStoreConfig serialized\n -> m Bool\ngetDynamoDBEventStoreTableExistence DynamoDBEventStoreConfig{..} = do\n tablesResponse <- trying _ServiceError $ send $\n describeTable\n dynamoDBEventStoreConfigTableName\n case tablesResponse of\n Right response' -> return $ isJust (response' ^. drsTable)\n Left err ->\n if err ^. serviceCode == ErrorCode \"ResourceNotFound\"\n then return False\n else throw $ toException (ServiceError err)\n\n-- | Convenience function to drop the event store table. Mainly used for\n-- testing this library.\ndeleteDynamoDBEventStoreTable\n :: (MonadAWS m)\n => DynamoDBEventStoreConfig serialized\n -> m ()\ndeleteDynamoDBEventStoreTable config@DynamoDBEventStoreConfig{..} = do\n eventTableExists <- getDynamoDBEventStoreTableExistence config\n when eventTableExists $ do\n void $ send $ deleteTable dynamoDBEventStoreConfigTableName\n void $ await tableNotExists (describeTable dynamoDBEventStoreConfigTableName)\n\n-- | Convenience function if you don't really care about your amazonka\n-- settings.\nrunAWSIO :: AWS a -> IO a\nrunAWSIO action = do\n lgr <- newLogger Trace stdout\n env <- newEnv Discover <&> set envLogger lgr\n runResourceT . runAWST env $ action\n","avg_line_length":40.3644067797,"max_line_length":115,"alphanum_fraction":0.7691580936} {"size":39494,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TypeFamilies #-}\n\n-- | The general Stack configuration that starts everything off. This should\n-- be smart to falback if there is no stack.yaml, instead relying on\n-- whatever files are available.\n--\n-- If there is no stack.yaml, and there is a cabal.config, we\n-- read in those constraints, and if there's a cabal.sandbox.config,\n-- we read any constraints from there and also find the package\n-- database from there, etc. And if there's nothing, we should\n-- probably default to behaving like cabal, possibly with spitting out\n-- a warning that \"you should run `stk init` to make things better\".\nmodule Stack.Config\n (loadConfig\n ,loadConfigYaml\n ,packagesParser\n ,getImplicitGlobalProjectDir\n ,getSnapshots\n ,makeConcreteResolver\n ,checkOwnership\n ,getInContainer\n ,getInNixShell\n ,defaultConfigYaml\n ,getProjectConfig\n ,withBuildConfig\n ) where\n\nimport Control.Monad.Extra (firstJustM)\nimport Stack.Prelude\nimport Pantry.Internal.AesonExtended\nimport qualified Data.ByteString as S\nimport Data.ByteString.Builder (byteString)\nimport Data.Coerce (coerce)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.Map as Map\nimport qualified Data.Map.Merge.Strict as MS\nimport qualified Data.Monoid\nimport Data.Monoid.Map (MonoidMap(..))\nimport qualified Data.Text as T\nimport Data.Text.Encoding (encodeUtf8)\nimport qualified Data.Yaml as Yaml\nimport Distribution.System (OS (..), Platform (..), buildPlatform, Arch(OtherArch))\nimport qualified Distribution.Text\nimport Distribution.Version (simplifyVersionRange, mkVersion')\nimport GHC.Conc (getNumProcessors)\nimport Lens.Micro ((.~))\nimport Network.HTTP.StackClient (httpJSON, parseUrlThrow, getResponseBody)\nimport Options.Applicative (Parser, strOption, long, help)\nimport Path\nimport Path.Extra (toFilePathNoTrailingSep)\nimport Path.Find (findInParents)\nimport Path.IO\nimport qualified Paths_stack as Meta\nimport Stack.Config.Build\nimport Stack.Config.Docker\nimport Stack.Config.Nix\nimport Stack.Constants\nimport Stack.Build.Haddock (shouldHaddockDeps)\nimport Stack.Lock (lockCachedWanted)\nimport Stack.Storage.Project (initProjectStorage)\nimport Stack.Storage.User (initUserStorage)\nimport Stack.SourceMap\nimport Stack.Types.Build\nimport Stack.Types.Compiler\nimport Stack.Types.Config\nimport Stack.Types.Docker\nimport Stack.Types.Nix\nimport Stack.Types.Resolver\nimport Stack.Types.SourceMap\nimport Stack.Types.Version\nimport System.Console.ANSI (hSupportsANSIWithoutEmulation)\nimport System.Environment\nimport System.Info.ShortPathName (getShortPathName)\nimport System.PosixCompat.Files (fileOwner, getFileStatus)\nimport System.PosixCompat.User (getEffectiveUserID)\nimport RIO.List (unzip)\nimport RIO.PrettyPrint (stylesUpdateL, useColorL)\nimport RIO.Process\n\n-- | If deprecated path exists, use it and print a warning.\n-- Otherwise, return the new path.\ntryDeprecatedPath\n :: HasLogFunc env\n => Maybe T.Text -- ^ Description of file for warning (if Nothing, no deprecation warning is displayed)\n -> (Path Abs a -> RIO env Bool) -- ^ Test for existence\n -> Path Abs a -- ^ New path\n -> Path Abs a -- ^ Deprecated path\n -> RIO env (Path Abs a, Bool) -- ^ (Path to use, whether it already exists)\ntryDeprecatedPath mWarningDesc exists new old = do\n newExists <- exists new\n if newExists\n then return (new, True)\n else do\n oldExists <- exists old\n if oldExists\n then do\n case mWarningDesc of\n Nothing -> return ()\n Just desc ->\n logWarn $\n \"Warning: Location of \" <> display desc <> \" at '\" <>\n fromString (toFilePath old) <>\n \"' is deprecated; rename it to '\" <>\n fromString (toFilePath new) <>\n \"' instead\"\n return (old, True)\n else return (new, False)\n\n-- | Get the location of the implicit global project directory.\n-- If the directory already exists at the deprecated location, its location is returned.\n-- Otherwise, the new location is returned.\ngetImplicitGlobalProjectDir\n :: HasLogFunc env\n => Config -> RIO env (Path Abs Dir)\ngetImplicitGlobalProjectDir config =\n --TEST no warning printed\n liftM fst $ tryDeprecatedPath\n Nothing\n doesDirExist\n (implicitGlobalProjectDir stackRoot)\n (implicitGlobalProjectDirDeprecated stackRoot)\n where\n stackRoot = view stackRootL config\n\n-- | Download the 'Snapshots' value from stackage.org.\ngetSnapshots :: HasConfig env => RIO env Snapshots\ngetSnapshots = do\n latestUrlText <- askLatestSnapshotUrl\n latestUrl <- parseUrlThrow (T.unpack latestUrlText)\n logDebug $ \"Downloading snapshot versions file from \" <> display latestUrlText\n result <- httpJSON latestUrl\n logDebug \"Done downloading and parsing snapshot versions file\"\n return $ getResponseBody result\n\n-- | Turn an 'AbstractResolver' into a 'Resolver'.\nmakeConcreteResolver\n :: HasConfig env\n => AbstractResolver\n -> RIO env RawSnapshotLocation\nmakeConcreteResolver (ARResolver r) = pure r\nmakeConcreteResolver ar = do\n snapshots <- getSnapshots\n r <-\n case ar of\n ARResolver r -> assert False $ makeConcreteResolver (ARResolver r)\n ARGlobal -> do\n config <- view configL\n implicitGlobalDir <- getImplicitGlobalProjectDir config\n let fp = implicitGlobalDir <\/> stackDotYaml\n iopc <- loadConfigYaml (parseProjectAndConfigMonoid (parent fp)) fp\n ProjectAndConfigMonoid project _ <- liftIO iopc\n return $ projectResolver project\n ARLatestNightly -> return $ nightlySnapshotLocation $ snapshotsNightly snapshots\n ARLatestLTSMajor x ->\n case IntMap.lookup x $ snapshotsLts snapshots of\n Nothing -> throwString $ \"No LTS release found with major version \" ++ show x\n Just y -> return $ ltsSnapshotLocation x y\n ARLatestLTS\n | IntMap.null $ snapshotsLts snapshots -> throwString \"No LTS releases found\"\n | otherwise ->\n let (x, y) = IntMap.findMax $ snapshotsLts snapshots\n in return $ ltsSnapshotLocation x y\n logInfo $ \"Selected resolver: \" <> display r\n return r\n\n-- | Get the latest snapshot resolver available.\ngetLatestResolver :: HasConfig env => RIO env RawSnapshotLocation\ngetLatestResolver = do\n snapshots <- getSnapshots\n let mlts = uncurry ltsSnapshotLocation <$>\n listToMaybe (reverse (IntMap.toList (snapshotsLts snapshots)))\n pure $ fromMaybe (nightlySnapshotLocation (snapshotsNightly snapshots)) mlts\n\n-- Interprets ConfigMonoid options.\nconfigFromConfigMonoid\n :: HasRunner env\n => Path Abs Dir -- ^ stack root, e.g. ~\/.stack\n -> Path Abs File -- ^ user config file path, e.g. ~\/.stack\/config.yaml\n -> Maybe AbstractResolver\n -> ProjectConfig (Project, Path Abs File)\n -> ConfigMonoid\n -> (Config -> RIO env a)\n -> RIO env a\nconfigFromConfigMonoid\n configStackRoot configUserConfigPath configResolver\n configProject ConfigMonoid{..} inner = do\n -- If --stack-work is passed, prefer it. Otherwise, if STACK_WORK\n -- is set, use that. If neither, use the default \".stack-work\"\n mstackWorkEnv <- liftIO $ lookupEnv stackWorkEnvVar\n let mproject =\n case configProject of\n PCProject pair -> Just pair\n PCGlobalProject -> Nothing\n PCNoProject _deps -> Nothing\n configAllowLocals =\n case configProject of\n PCProject _ -> True\n PCGlobalProject -> True\n PCNoProject _ -> False\n configWorkDir0 <- maybe (return relDirStackWork) (liftIO . parseRelDir) mstackWorkEnv\n let configWorkDir = fromFirst configWorkDir0 configMonoidWorkDir\n configLatestSnapshot = fromFirst\n \"https:\/\/s3.amazonaws.com\/haddock.stackage.org\/snapshots.json\"\n configMonoidLatestSnapshot\n clConnectionCount = fromFirst 8 configMonoidConnectionCount\n configHideTHLoading = fromFirstTrue configMonoidHideTHLoading\n configPrefixTimestamps = fromFirst False configMonoidPrefixTimestamps\n\n configGHCVariant = getFirst configMonoidGHCVariant\n configCompilerRepository = fromFirst\n defaultCompilerRepository\n configMonoidCompilerRepository\n configGHCBuild = getFirst configMonoidGHCBuild\n configInstallGHC = fromFirstTrue configMonoidInstallGHC\n configSkipGHCCheck = fromFirstFalse configMonoidSkipGHCCheck\n configSkipMsys = fromFirstFalse configMonoidSkipMsys\n\n configExtraIncludeDirs = configMonoidExtraIncludeDirs\n configExtraLibDirs = configMonoidExtraLibDirs\n configOverrideGccPath = getFirst configMonoidOverrideGccPath\n\n -- Only place in the codebase where platform is hard-coded. In theory\n -- in the future, allow it to be configured.\n (Platform defArch defOS) = buildPlatform\n arch = fromMaybe defArch\n $ getFirst configMonoidArch >>= Distribution.Text.simpleParse\n os = defOS\n configPlatform = Platform arch os\n\n configRequireStackVersion = simplifyVersionRange (getIntersectingVersionRange configMonoidRequireStackVersion)\n\n configCompilerCheck = fromFirst MatchMinor configMonoidCompilerCheck\n\n case arch of\n OtherArch \"aarch64\" -> return ()\n OtherArch unk -> logWarn $ \"Warning: Unknown value for architecture setting: \" <> displayShow unk\n _ -> return ()\n\n configPlatformVariant <- liftIO $\n maybe PlatformVariantNone PlatformVariant <$> lookupEnv platformVariantEnvVar\n\n let configBuild = buildOptsFromMonoid configMonoidBuildOpts\n configDocker <-\n dockerOptsFromMonoid (fmap fst mproject) configResolver configMonoidDockerOpts\n configNix <- nixOptsFromMonoid configMonoidNixOpts os\n\n configSystemGHC <-\n case (getFirst configMonoidSystemGHC, nixEnable configNix) of\n (Just False, True) ->\n throwM NixRequiresSystemGhc\n _ ->\n return\n (fromFirst\n (dockerEnable configDocker || nixEnable configNix)\n configMonoidSystemGHC)\n\n when (isJust configGHCVariant && configSystemGHC) $\n throwM ManualGHCVariantSettingsAreIncompatibleWithSystemGHC\n\n rawEnv <- liftIO getEnvironment\n pathsEnv <- either throwM return\n $ augmentPathMap (map toFilePath configMonoidExtraPath)\n (Map.fromList (map (T.pack *** T.pack) rawEnv))\n origEnv <- mkProcessContext pathsEnv\n let configProcessContextSettings _ = return origEnv\n\n configLocalProgramsBase <- case getFirst configMonoidLocalProgramsBase of\n Nothing -> getDefaultLocalProgramsBase configStackRoot configPlatform origEnv\n Just path -> return path\n let localProgramsFilePath = toFilePath configLocalProgramsBase\n when (osIsWindows && ' ' `elem` localProgramsFilePath) $ do\n ensureDir configLocalProgramsBase\n -- getShortPathName returns the long path name when a short name does not\n -- exist.\n shortLocalProgramsFilePath <-\n liftIO $ getShortPathName localProgramsFilePath\n when (' ' `elem` shortLocalProgramsFilePath) $ do\n logError $ \"Stack's 'programs' path contains a space character and \" <>\n \"has no alternative short ('8 dot 3') name. This will cause \" <>\n \"problems with packages that use the GNU project's 'configure' \" <>\n \"shell script. Use the 'local-programs-path' configuration option \" <>\n \"to specify an alternative path. The current path is: \" <>\n display (T.pack localProgramsFilePath)\n platformOnlyDir <- runReaderT platformOnlyRelDir (configPlatform, configPlatformVariant)\n let configLocalPrograms = configLocalProgramsBase <\/> platformOnlyDir\n\n configLocalBin <-\n case getFirst configMonoidLocalBinPath of\n Nothing -> do\n localDir <- getAppUserDataDir \"local\"\n return $ localDir <\/> relDirBin\n Just userPath ->\n (case mproject of\n -- Not in a project\n Nothing -> resolveDir' userPath\n -- Resolves to the project dir and appends the user path if it is relative\n Just (_, configYaml) -> resolveDir (parent configYaml) userPath)\n -- TODO: Either catch specific exceptions or add a\n -- parseRelAsAbsDirMaybe utility and use it along with\n -- resolveDirMaybe.\n `catchAny`\n const (throwIO (NoSuchDirectory userPath))\n\n configJobs <-\n case getFirst configMonoidJobs of\n Nothing -> liftIO getNumProcessors\n Just i -> return i\n let configConcurrentTests = fromFirst True configMonoidConcurrentTests\n\n let configTemplateParams = configMonoidTemplateParameters\n configScmInit = getFirst configMonoidScmInit\n configCabalConfigOpts = coerce configMonoidCabalConfigOpts\n configGhcOptionsByName = coerce configMonoidGhcOptionsByName\n configGhcOptionsByCat = coerce configMonoidGhcOptionsByCat\n configSetupInfoLocations = configMonoidSetupInfoLocations\n configSetupInfoInline = configMonoidSetupInfoInline\n configPvpBounds = fromFirst (PvpBounds PvpBoundsNone False) configMonoidPvpBounds\n configModifyCodePage = fromFirstTrue configMonoidModifyCodePage\n configExplicitSetupDeps = configMonoidExplicitSetupDeps\n configRebuildGhcOptions = fromFirstFalse configMonoidRebuildGhcOptions\n configApplyGhcOptions = fromFirst AGOLocals configMonoidApplyGhcOptions\n configAllowNewer = fromFirst False configMonoidAllowNewer\n configDefaultTemplate = getFirst configMonoidDefaultTemplate\n configDumpLogs = fromFirst DumpWarningLogs configMonoidDumpLogs\n configSaveHackageCreds = fromFirst True configMonoidSaveHackageCreds\n configHackageBaseUrl = fromFirst \"https:\/\/hackage.haskell.org\/\" configMonoidHackageBaseUrl\n configHideSourcePaths = fromFirstTrue configMonoidHideSourcePaths\n configRecommendUpgrade = fromFirstTrue configMonoidRecommendUpgrade\n\n configAllowDifferentUser <-\n case getFirst configMonoidAllowDifferentUser of\n Just True -> return True\n _ -> getInContainer\n\n configRunner' <- view runnerL\n\n useAnsi <- liftIO $ fromMaybe True <$>\n hSupportsANSIWithoutEmulation stderr\n\n let stylesUpdate' = (configRunner' ^. stylesUpdateL) <>\n configMonoidStyles\n useColor' = runnerUseColor configRunner'\n mUseColor = do\n colorWhen <- getFirst configMonoidColorWhen\n return $ case colorWhen of\n ColorNever -> False\n ColorAlways -> True\n ColorAuto -> useAnsi\n configRunner = configRunner'\n & processContextL .~ origEnv\n & stylesUpdateL .~ stylesUpdate'\n & useColorL .~ fromMaybe useColor' mUseColor\n\n hsc <-\n case getFirst configMonoidPackageIndices of\n Nothing -> pure defaultHackageSecurityConfig\n Just [hsc] -> pure hsc\n Just x -> error $ \"When overriding the default package index, you must provide exactly one value, received: \" ++ show x\n mpantryRoot <- liftIO $ lookupEnv \"PANTRY_ROOT\"\n pantryRoot <-\n case mpantryRoot of\n Just dir ->\n case parseAbsDir dir of\n Nothing -> throwString $ \"Failed to parse PANTRY_ROOT environment variable (expected absolute directory): \" ++ show dir\n Just x -> pure x\n Nothing -> pure $ configStackRoot <\/> relDirPantry\n withPantryConfig\n pantryRoot\n hsc\n (maybe HpackBundled HpackCommand $ getFirst configMonoidOverrideHpack)\n clConnectionCount\n (fromFirst defaultCasaRepoPrefix configMonoidCasaRepoPrefix)\n defaultCasaMaxPerRequest\n (\\configPantryConfig -> initUserStorage\n (configStackRoot <\/> relFileStorage)\n (\\configUserStorage -> inner Config {..}))\n\n-- | Get the default location of the local programs directory.\ngetDefaultLocalProgramsBase :: MonadThrow m\n => Path Abs Dir\n -> Platform\n -> ProcessContext\n -> m (Path Abs Dir)\ngetDefaultLocalProgramsBase configStackRoot configPlatform override =\n let\n defaultBase = configStackRoot <\/> relDirPrograms\n in\n case configPlatform of\n -- For historical reasons, on Windows a subdirectory of LOCALAPPDATA is\n -- used instead of a subdirectory of STACK_ROOT. Unifying the defaults would\n -- mean that Windows users would manually have to move data from the old\n -- location to the new one, which is undesirable.\n Platform _ Windows ->\n case Map.lookup \"LOCALAPPDATA\" $ view envVarsL override of\n Just t ->\n case parseAbsDir $ T.unpack t of\n Nothing -> throwM $ stringException (\"Failed to parse LOCALAPPDATA environment variable (expected absolute directory): \" ++ show t)\n Just lad ->\n return $ lad <\/> relDirUpperPrograms <\/> relDirStackProgName\n Nothing -> return defaultBase\n _ -> return defaultBase\n\n-- | Load the configuration, using current directory, environment variables,\n-- and defaults as necessary.\nloadConfig :: HasRunner env => (Config -> RIO env a) -> RIO env a\nloadConfig inner = do\n mstackYaml <- view $ globalOptsL.to globalStackYaml\n mproject <- loadProjectConfig mstackYaml\n mresolver <- view $ globalOptsL.to globalResolver\n configArgs <- view $ globalOptsL.to globalConfigMonoid\n (stackRoot, userOwnsStackRoot) <- determineStackRootAndOwnership configArgs\n\n let (mproject', addConfigMonoid) =\n case mproject of\n PCProject (proj, fp, cm) -> (PCProject (proj, fp), (cm:))\n PCGlobalProject -> (PCGlobalProject, id)\n PCNoProject deps -> (PCNoProject deps, id)\n\n userConfigPath <- getDefaultUserConfigPath stackRoot\n extraConfigs0 <- getExtraConfigs userConfigPath >>=\n mapM (\\file -> loadConfigYaml (parseConfigMonoid (parent file)) file)\n let extraConfigs =\n -- non-project config files' existence of a docker section should never default docker\n -- to enabled, so make it look like they didn't exist\n map (\\c -> c {configMonoidDockerOpts =\n (configMonoidDockerOpts c) {dockerMonoidDefaultEnable = Any False}})\n extraConfigs0\n\n let withConfig =\n configFromConfigMonoid\n stackRoot\n userConfigPath\n mresolver\n mproject'\n (mconcat $ configArgs : addConfigMonoid extraConfigs)\n\n withConfig $ \\config -> do\n unless (mkVersion' Meta.version `withinRange` configRequireStackVersion config)\n (throwM (BadStackVersionException (configRequireStackVersion config)))\n unless (configAllowDifferentUser config) $ do\n unless userOwnsStackRoot $\n throwM (UserDoesn'tOwnDirectory stackRoot)\n forM_ (configProjectRoot config) $ \\dir ->\n checkOwnership (dir <\/> configWorkDir config)\n inner config\n\n-- | Load the build configuration, adds build-specific values to config loaded by @loadConfig@.\n-- values.\nwithBuildConfig\n :: RIO BuildConfig a\n -> RIO Config a\nwithBuildConfig inner = do\n config <- ask\n\n -- If provided, turn the AbstractResolver from the command line\n -- into a Resolver that can be used below.\n\n -- The configResolver and mcompiler are provided on the command\n -- line. In order to properly deal with an AbstractResolver, we\n -- need a base directory (to deal with custom snapshot relative\n -- paths). We consider the current working directory to be the\n -- correct base. Let's calculate the mresolver first.\n mresolver <- forM (configResolver config) $ \\aresolver -> do\n logDebug (\"Using resolver: \" <> display aresolver <> \" specified on command line\")\n makeConcreteResolver aresolver\n\n (project', stackYamlFP) <- case configProject config of\n PCProject (project, fp) -> do\n forM_ (projectUserMsg project) (logWarn . fromString)\n return (project, fp)\n PCNoProject extraDeps -> do\n p <-\n case mresolver of\n Nothing -> throwIO NoResolverWhenUsingNoProject\n Just _ -> getEmptyProject mresolver extraDeps\n return (p, configUserConfigPath config)\n PCGlobalProject -> do\n logDebug \"Run from outside a project, using implicit global project config\"\n destDir <- getImplicitGlobalProjectDir config\n let dest :: Path Abs File\n dest = destDir <\/> stackDotYaml\n dest' :: FilePath\n dest' = toFilePath dest\n ensureDir destDir\n exists <- doesFileExist dest\n if exists\n then do\n iopc <- loadConfigYaml (parseProjectAndConfigMonoid destDir) dest\n ProjectAndConfigMonoid project _ <- liftIO iopc\n when (view terminalL config) $\n case configResolver config of\n Nothing ->\n logDebug $\n \"Using resolver: \" <>\n display (projectResolver project) <>\n \" from implicit global project's config file: \" <>\n fromString dest'\n Just _ -> return ()\n return (project, dest)\n else do\n logInfo (\"Writing implicit global project config file to: \" <> fromString dest')\n logInfo \"Note: You can change the snapshot via the resolver field there.\"\n p <- getEmptyProject mresolver []\n liftIO $ do\n writeBinaryFileAtomic dest $ byteString $ S.concat\n [ \"# This is the implicit global project's config file, which is only used when\\n\"\n , \"# 'stack' is run outside of a real project. Settings here do _not_ act as\\n\"\n , \"# defaults for all projects. To change stack's default settings, edit\\n\"\n , \"# '\", encodeUtf8 (T.pack $ toFilePath $ configUserConfigPath config), \"' instead.\\n\"\n , \"#\\n\"\n , \"# For more information about stack's configuration, see\\n\"\n , \"# http:\/\/docs.haskellstack.org\/en\/stable\/yaml_configuration\/\\n\"\n , \"#\\n\"\n , Yaml.encode p]\n writeBinaryFileAtomic (parent dest <\/> relFileReadmeTxt)\n \"This is the implicit global project, which is used only when 'stack' is run\\n\\\n \\outside of a real project.\\n\"\n return (p, dest)\n mcompiler <- view $ globalOptsL.to globalCompiler\n let project = project'\n { projectCompiler = mcompiler <|> projectCompiler project'\n , projectResolver = fromMaybe (projectResolver project') mresolver\n }\n extraPackageDBs <- mapM resolveDir' (projectExtraPackageDBs project)\n\n wanted <- lockCachedWanted stackYamlFP (projectResolver project) $\n fillProjectWanted stackYamlFP config project\n\n -- Unfortunately redoes getProjectWorkDir, since we don't have a BuildConfig yet\n workDir <- view workDirL\n let projectStorageFile = parent stackYamlFP <\/> workDir <\/> relFileStorage\n\n initProjectStorage projectStorageFile $ \\projectStorage -> do\n let bc = BuildConfig\n { bcConfig = config\n , bcSMWanted = wanted\n , bcExtraPackageDBs = extraPackageDBs\n , bcStackYaml = stackYamlFP\n , bcCurator = projectCurator project\n , bcProjectStorage = projectStorage\n }\n runRIO bc inner\n where\n getEmptyProject :: Maybe RawSnapshotLocation -> [PackageIdentifierRevision] -> RIO Config Project\n getEmptyProject mresolver extraDeps = do\n r <- case mresolver of\n Just resolver -> do\n logInfo (\"Using resolver: \" <> display resolver <> \" specified on command line\")\n return resolver\n Nothing -> do\n r'' <- getLatestResolver\n logInfo (\"Using latest snapshot resolver: \" <> display r'')\n return r''\n return Project\n { projectUserMsg = Nothing\n , projectPackages = []\n , projectDependencies = map (RPLImmutable . flip RPLIHackage Nothing) extraDeps\n , projectFlags = mempty\n , projectResolver = r\n , projectCompiler = Nothing\n , projectExtraPackageDBs = []\n , projectCurator = Nothing\n , projectDropPackages = mempty\n }\n\nfillProjectWanted ::\n (HasProcessContext env, HasLogFunc env, HasPantryConfig env)\n => Path Abs t\n -> Config\n -> Project\n -> Map RawPackageLocationImmutable PackageLocationImmutable\n -> WantedCompiler\n -> Map PackageName (Bool -> RIO env DepPackage)\n -> RIO env (SMWanted, [CompletedPLI])\nfillProjectWanted stackYamlFP config project locCache snapCompiler snapPackages = do\n let bopts = configBuild config\n\n packages0 <- for (projectPackages project) $ \\fp@(RelFilePath t) -> do\n abs' <- resolveDir (parent stackYamlFP) (T.unpack t)\n let resolved = ResolvedPath fp abs'\n pp <- mkProjectPackage YesPrintWarnings resolved (boptsHaddock bopts)\n pure (cpName $ ppCommon pp, pp)\n\n (deps0, mcompleted) <- fmap unzip . forM (projectDependencies project) $ \\rpl -> do\n (pl, mCompleted) <- case rpl of\n RPLImmutable rpli -> do\n compl <- maybe (completePackageLocation rpli) pure (Map.lookup rpli locCache)\n pure (PLImmutable compl, Just (CompletedPLI rpli compl))\n RPLMutable p ->\n pure (PLMutable p, Nothing)\n dp <- additionalDepPackage (shouldHaddockDeps bopts) pl\n pure ((cpName $ dpCommon dp, dp), mCompleted)\n\n checkDuplicateNames $\n map (second (PLMutable . ppResolvedDir)) packages0 ++\n map (second dpLocation) deps0\n\n let packages1 = Map.fromList packages0\n snPackages = snapPackages\n `Map.difference` packages1\n `Map.difference` Map.fromList deps0\n `Map.withoutKeys` projectDropPackages project\n\n snDeps <- for snPackages $ \\getDep -> getDep (shouldHaddockDeps bopts)\n\n let deps1 = Map.fromList deps0 `Map.union` snDeps\n\n let mergeApply m1 m2 f =\n MS.merge MS.preserveMissing MS.dropMissing (MS.zipWithMatched f) m1 m2\n pFlags = projectFlags project\n packages2 = mergeApply packages1 pFlags $\n \\_ p flags -> p{ppCommon=(ppCommon p){cpFlags=flags}}\n deps2 = mergeApply deps1 pFlags $\n \\_ d flags -> d{dpCommon=(dpCommon d){cpFlags=flags}}\n\n checkFlagsUsedThrowing pFlags FSStackYaml packages1 deps1\n\n let pkgGhcOptions = configGhcOptionsByName config\n deps = mergeApply deps2 pkgGhcOptions $\n \\_ d options -> d{dpCommon=(dpCommon d){cpGhcOptions=options}}\n packages = mergeApply packages2 pkgGhcOptions $\n \\_ p options -> p{ppCommon=(ppCommon p){cpGhcOptions=options}}\n unusedPkgGhcOptions = pkgGhcOptions `Map.restrictKeys` Map.keysSet packages2\n `Map.restrictKeys` Map.keysSet deps2\n\n unless (Map.null unusedPkgGhcOptions) $\n throwM $ InvalidGhcOptionsSpecification (Map.keys unusedPkgGhcOptions)\n\n let wanted = SMWanted\n { smwCompiler = fromMaybe snapCompiler (projectCompiler project)\n , smwProject = packages\n , smwDeps = deps\n , smwSnapshotLocation = projectResolver project\n }\n\n pure (wanted, catMaybes mcompleted)\n\n\n-- | Check if there are any duplicate package names and, if so, throw an\n-- exception.\ncheckDuplicateNames :: MonadThrow m => [(PackageName, PackageLocation)] -> m ()\ncheckDuplicateNames locals =\n case filter hasMultiples $ Map.toList $ Map.fromListWith (++) $ map (second return) locals of\n [] -> return ()\n x -> throwM $ DuplicateLocalPackageNames x\n where\n hasMultiples (_, _:_:_) = True\n hasMultiples _ = False\n\n\n-- | Get the stack root, e.g. @~\/.stack@, and determine whether the user owns it.\n--\n-- On Windows, the second value is always 'True'.\ndetermineStackRootAndOwnership\n :: (MonadIO m)\n => ConfigMonoid\n -- ^ Parsed command-line arguments\n -> m (Path Abs Dir, Bool)\ndetermineStackRootAndOwnership clArgs = liftIO $ do\n stackRoot <- do\n case getFirst (configMonoidStackRoot clArgs) of\n Just x -> return x\n Nothing -> do\n mstackRoot <- lookupEnv stackRootEnvVar\n case mstackRoot of\n Nothing -> getAppUserDataDir stackProgName\n Just x -> case parseAbsDir x of\n Nothing -> throwString (\"Failed to parse STACK_ROOT environment variable (expected absolute directory): \" ++ show x)\n Just parsed -> return parsed\n\n (existingStackRootOrParentDir, userOwnsIt) <- do\n mdirAndOwnership <- findInParents getDirAndOwnership stackRoot\n case mdirAndOwnership of\n Just x -> return x\n Nothing -> throwIO (BadStackRoot stackRoot)\n\n when (existingStackRootOrParentDir \/= stackRoot) $\n if userOwnsIt\n then ensureDir stackRoot\n else throwIO $\n Won'tCreateStackRootInDirectoryOwnedByDifferentUser\n stackRoot\n existingStackRootOrParentDir\n\n stackRoot' <- canonicalizePath stackRoot\n return (stackRoot', userOwnsIt)\n\n-- | @'checkOwnership' dir@ throws 'UserDoesn'tOwnDirectory' if @dir@\n-- isn't owned by the current user.\n--\n-- If @dir@ doesn't exist, its parent directory is checked instead.\n-- If the parent directory doesn't exist either, @'NoSuchDirectory' ('parent' dir)@\n-- is thrown.\ncheckOwnership :: (MonadIO m) => Path Abs Dir -> m ()\ncheckOwnership dir = do\n mdirAndOwnership <- firstJustM getDirAndOwnership [dir, parent dir]\n case mdirAndOwnership of\n Just (_, True) -> return ()\n Just (dir', False) -> throwIO (UserDoesn'tOwnDirectory dir')\n Nothing ->\n (throwIO . NoSuchDirectory) $ (toFilePathNoTrailingSep . parent) dir\n\n-- | @'getDirAndOwnership' dir@ returns @'Just' (dir, 'True')@ when @dir@\n-- exists and the current user owns it in the sense of 'isOwnedByUser'.\ngetDirAndOwnership\n :: (MonadIO m)\n => Path Abs Dir\n -> m (Maybe (Path Abs Dir, Bool))\ngetDirAndOwnership dir = liftIO $ forgivingAbsence $ do\n ownership <- isOwnedByUser dir\n return (dir, ownership)\n\n-- | Check whether the current user (determined with 'getEffectiveUserId') is\n-- the owner for the given path.\n--\n-- Will always return 'True' on Windows.\nisOwnedByUser :: MonadIO m => Path Abs t -> m Bool\nisOwnedByUser path = liftIO $ do\n if osIsWindows\n then return True\n else do\n fileStatus <- getFileStatus (toFilePath path)\n user <- getEffectiveUserID\n return (user == fileOwner fileStatus)\n\n-- | 'True' if we are currently running inside a Docker container.\ngetInContainer :: (MonadIO m) => m Bool\ngetInContainer = liftIO (isJust <$> lookupEnv inContainerEnvVar)\n\n-- | 'True' if we are currently running inside a Nix.\ngetInNixShell :: (MonadIO m) => m Bool\ngetInNixShell = liftIO (isJust <$> lookupEnv inNixShellEnvVar)\n\n-- | Determine the extra config file locations which exist.\n--\n-- Returns most local first\ngetExtraConfigs :: HasLogFunc env\n => Path Abs File -- ^ use config path\n -> RIO env [Path Abs File]\ngetExtraConfigs userConfigPath = do\n defaultStackGlobalConfigPath <- getDefaultGlobalConfigPath\n liftIO $ do\n env <- getEnvironment\n mstackConfig <-\n maybe (return Nothing) (fmap Just . parseAbsFile)\n $ lookup \"STACK_CONFIG\" env\n mstackGlobalConfig <-\n maybe (return Nothing) (fmap Just . parseAbsFile)\n $ lookup \"STACK_GLOBAL_CONFIG\" env\n filterM doesFileExist\n $ fromMaybe userConfigPath mstackConfig\n : maybe [] return (mstackGlobalConfig <|> defaultStackGlobalConfigPath)\n\n-- | Load and parse YAML from the given config file. Throws\n-- 'ParseConfigFileException' when there's a decoding error.\nloadConfigYaml\n :: HasLogFunc env\n => (Value -> Yaml.Parser (WithJSONWarnings a)) -> Path Abs File -> RIO env a\nloadConfigYaml parser path = do\n eres <- loadYaml parser path\n case eres of\n Left err -> liftIO $ throwM (ParseConfigFileException path err)\n Right res -> return res\n\n-- | Load and parse YAML from the given file.\nloadYaml\n :: HasLogFunc env\n => (Value -> Yaml.Parser (WithJSONWarnings a)) -> Path Abs File -> RIO env (Either Yaml.ParseException a)\nloadYaml parser path = do\n eres <- liftIO $ Yaml.decodeFileEither (toFilePath path)\n case eres of\n Left err -> return (Left err)\n Right val ->\n case Yaml.parseEither parser val of\n Left err -> return (Left (Yaml.AesonException err))\n Right (WithJSONWarnings res warnings) -> do\n logJSONWarnings (toFilePath path) warnings\n return (Right res)\n\n-- | Get the location of the project config file, if it exists.\ngetProjectConfig :: HasLogFunc env\n => StackYamlLoc\n -- ^ Override stack.yaml\n -> RIO env (ProjectConfig (Path Abs File))\ngetProjectConfig (SYLOverride stackYaml) = return $ PCProject stackYaml\ngetProjectConfig SYLGlobalProject = return PCGlobalProject\ngetProjectConfig SYLDefault = do\n env <- liftIO getEnvironment\n case lookup \"STACK_YAML\" env of\n Just fp -> do\n logInfo \"Getting project config file from STACK_YAML environment\"\n liftM PCProject $ resolveFile' fp\n Nothing -> do\n currDir <- getCurrentDir\n maybe PCGlobalProject PCProject <$> findInParents getStackDotYaml currDir\n where\n getStackDotYaml dir = do\n let fp = dir <\/> stackDotYaml\n fp' = toFilePath fp\n logDebug $ \"Checking for project config at: \" <> fromString fp'\n exists <- doesFileExist fp\n if exists\n then return $ Just fp\n else return Nothing\ngetProjectConfig (SYLNoProject extraDeps) = return $ PCNoProject extraDeps\n\n-- | Find the project config file location, respecting environment variables\n-- and otherwise traversing parents. If no config is found, we supply a default\n-- based on current directory.\nloadProjectConfig :: HasLogFunc env\n => StackYamlLoc\n -- ^ Override stack.yaml\n -> RIO env (ProjectConfig (Project, Path Abs File, ConfigMonoid))\nloadProjectConfig mstackYaml = do\n mfp <- getProjectConfig mstackYaml\n case mfp of\n PCProject fp -> do\n currDir <- getCurrentDir\n logDebug $ \"Loading project config file \" <>\n fromString (maybe (toFilePath fp) toFilePath (stripProperPrefix currDir fp))\n PCProject <$> load fp\n PCGlobalProject -> do\n logDebug \"No project config file found, using defaults.\"\n return PCGlobalProject\n PCNoProject extraDeps -> do\n logDebug \"Ignoring config files\"\n return $ PCNoProject extraDeps\n where\n load fp = do\n iopc <- loadConfigYaml (parseProjectAndConfigMonoid (parent fp)) fp\n ProjectAndConfigMonoid project config <- liftIO iopc\n return (project, fp, config)\n\n-- | Get the location of the default stack configuration file.\n-- If a file already exists at the deprecated location, its location is returned.\n-- Otherwise, the new location is returned.\ngetDefaultGlobalConfigPath\n :: HasLogFunc env\n => RIO env (Maybe (Path Abs File))\ngetDefaultGlobalConfigPath =\n case (defaultGlobalConfigPath, defaultGlobalConfigPathDeprecated) of\n (Just new,Just old) ->\n liftM (Just . fst ) $\n tryDeprecatedPath\n (Just \"non-project global configuration file\")\n doesFileExist\n new\n old\n (Just new,Nothing) -> return (Just new)\n _ -> return Nothing\n\n-- | Get the location of the default user configuration file.\n-- If a file already exists at the deprecated location, its location is returned.\n-- Otherwise, the new location is returned.\ngetDefaultUserConfigPath\n :: HasLogFunc env\n => Path Abs Dir -> RIO env (Path Abs File)\ngetDefaultUserConfigPath stackRoot = do\n (path, exists) <- tryDeprecatedPath\n (Just \"non-project configuration file\")\n doesFileExist\n (defaultUserConfigPath stackRoot)\n (defaultUserConfigPathDeprecated stackRoot)\n unless exists $ do\n ensureDir (parent path)\n liftIO $ writeBinaryFileAtomic path defaultConfigYaml\n return path\n\npackagesParser :: Parser [String]\npackagesParser = many (strOption (long \"package\" <> help \"Additional packages that must be installed\"))\n\ndefaultConfigYaml :: IsString s => s\ndefaultConfigYaml =\n \"# This file contains default non-project-specific settings for 'stack', used\\n\\\n \\# in all projects. For more information about stack's configuration, see\\n\\\n \\# http:\/\/docs.haskellstack.org\/en\/stable\/yaml_configuration\/\\n\\\n \\\\n\\\n \\# The following parameters are used by \\\"stack new\\\" to automatically fill fields\\n\\\n \\# in the cabal config. We recommend uncommenting them and filling them out if\\n\\\n \\# you intend to use 'stack new'.\\n\\\n \\# See https:\/\/docs.haskellstack.org\/en\/stable\/yaml_configuration\/#templates\\n\\\n \\templates:\\n\\\n \\ params:\\n\\\n \\# author-name:\\n\\\n \\# author-email:\\n\\\n \\# copyright:\\n\\\n \\# github-username:\\n\\\n \\\\n\\\n \\# The following parameter specifies stack's output styles; STYLES is a\\n\\\n \\# colon-delimited sequence of key=value, where 'key' is a style name and\\n\\\n \\# 'value' is a semicolon-delimited list of 'ANSI' SGR (Select Graphic\\n\\\n \\# Rendition) control codes (in decimal). Use \\\"stack ls stack-colors --basic\\\"\\n\\\n \\# to see the current sequence.\\n\\\n \\# stack-colors: STYLES\\n\"\n","avg_line_length":43.7849223947,"max_line_length":145,"alphanum_fraction":0.6511368816} {"size":7300,"ext":"hs","lang":"Haskell","max_stars_count":31.0,"content":"{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE CPP #-}\n{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}\n#if __GLASGOW_HASKELL__ >= 800\n{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}\n#endif\n{-# OPTIONS_GHC -fno-warn-dodgy-exports #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports #-}\n\nmodule Text.RE.PCRE\n (\n -- * Tutorial\n -- $tutorial\n\n -- * About this Module\n -- $about\n\n -- * The 'Matches' and 'Match' Operators\n (*=~)\n , (?=~)\n -- * The 'SearchReplace' Operators\n , (*=~\/)\n , (?=~\/)\n -- * The 'Matches' Type\n , Matches\n , matchesSource\n , allMatches\n , anyMatches\n , countMatches\n , matches\n -- * The 'Match' Type\n , Match\n , matchSource\n , matched\n , matchedText\n -- * The Macros and Parsers\n -- $macros\n , module Text.RE.TestBench.Parsers\n -- * The 'RE' Type\n , RE\n , regexType\n , reOptions\n , reSource\n , reCaptureNames\n , reRegex\n -- * Options\n -- $options\n , SimpleREOptions(..)\n , IsOption(..)\n , REOptions\n , defaultREOptions\n , noPreludeREOptions\n , unpackSimpleREOptions\n -- * Compiling and Escaping REs\n , SearchReplace(..)\n , compileRegex\n , compileRegexWith\n , compileRegexWithOptions\n , compileSearchReplace\n , compileSearchReplaceWith\n , compileSearchReplaceWithOptions\n , escape\n , escapeWith\n , escapeWithOptions\n , escapeREString\n -- * The Classic regex-base Match Operators\n , (=~)\n , (=~~)\n -- * The re Quasi Quoters\n -- $re\n , re\n , reMultilineSensitive\n , reMultilineInsensitive\n , reBlockSensitive\n , reBlockInsensitive\n , reMS\n , reMI\n , reBS\n , reBI\n , re_\n -- * The Ed Quasi Quoters\n -- $ed\n , ed\n , edMultilineSensitive\n , edMultilineInsensitive\n , edBlockSensitive\n , edBlockInsensitive\n , edMS\n , edMI\n , edBS\n , edBI\n , ed_\n -- * The cp Quasi Quoters\n , cp\n -- * RE Macros Standard Environment\n -- $prelude\n , prelude\n , preludeEnv\n , preludeTestsFailing\n , preludeTable\n , preludeSummary\n , preludeSources\n , preludeSource\n -- * IsRegex\n -- $isregex\n , module Text.RE.Tools.IsRegex\n -- * The IsRegex Instances\n -- $instances\n , module Text.RE.PCRE.ByteString\n , module Text.RE.PCRE.ByteString.Lazy\n , module Text.RE.PCRE.Sequence\n , module Text.RE.PCRE.String\n ) where\n\nimport Control.Monad.Fail\nimport Text.RE.PCRE.ByteString()\nimport Text.RE.PCRE.ByteString.Lazy()\nimport Text.RE.PCRE.Sequence()\nimport Text.RE.PCRE.String()\nimport Text.RE.REOptions\nimport Text.RE.Replace\nimport Text.RE.TestBench.Parsers\nimport Text.RE.Tools.IsRegex\nimport Text.RE.ZeInternals\nimport Text.RE.ZeInternals.PCRE\nimport Text.RE.ZeInternals.SearchReplace.PCRE\nimport qualified Text.Regex.Base as B\nimport qualified Text.Regex.PCRE as PCRE\n\n\n-- | find all the matches in the argument text; e.g., to count the number\n-- of naturals in s:\n--\n-- @countMatches $ s *=~ [re|[0-9]+|]@\n--\n(*=~) :: IsRegex RE s\n => s\n -> RE\n -> Matches s\n(*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ matchMany rex bs\n\n-- | find the first match in the argument text; e.g., to test if there\n-- is a natural number in the input text:\n--\n-- @matched $ s ?=~ [re|[0-9]+|]@\n--\n(?=~) :: IsRegex RE s\n => s\n -> RE\n -> Match s\n(?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ matchOnce rex bs\n\n-- | search and replace all matches in the argument text; e.g., this section\n-- will convert every YYYY-MM-DD format date in its argument text into a\n-- DD\\\/MM\\\/YYYY date:\n--\n-- @(*=~\\\/ [ed|${y}([0-9]{4})-0*${m}([0-9]{2})-0*${d}([0-9]{2})\\\/\\\/\\\/${d}\\\/${m}\\\/${y}|])@\n--\n(*=~\/) :: IsRegex RE s => s -> SearchReplace RE s -> s\n(*=~\/) = flip searchReplaceAll\n\n-- | search and replace the first occurrence only (if any) in the input text\n-- e.g., to prefix the first string of four hex digits in the imput text,\n-- if any, with @0x@:\n--\n-- @(?=~\\\/ [ed|[0-9A-Fa-f]{4}\\\/\\\/\\\/0x$0|])\n--\n(?=~\/) :: IsRegex RE s => s -> SearchReplace RE s -> s\n(?=~\/) = flip searchReplaceFirst\n\n-- | the regex-base polymorphic match operator\n(=~) :: ( B.RegexContext PCRE.Regex s a\n , B.RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption s\n )\n => s\n -> RE\n -> a\n(=~) bs rex = B.match (reRegex rex) bs\n\n-- | the regex-base monadic, polymorphic match operator\n(=~~) :: ( Monad m, MonadFail m\n , B.RegexContext PCRE.Regex s a\n , B.RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption s\n )\n => s\n -> RE\n -> m a\n(=~~) bs rex = B.matchM (reRegex rex) bs\n\n-- $tutorial\n-- We have a regex tutorial at <http:\/\/tutorial.regex.uk>.\n\n-- $about\n-- This module provides access to the back end through polymorphic functions\n-- that operate over all of the String\\\/Text\\\/ByteString types supported by the\n-- back end. The module also provides all of the specialised back-end functionality\n-- that will not be needed by most regex clientts. If you don't need this generality\n-- then you might want to consider using one of the simpler modules that have been\n-- specialised for each of these types:\n--\n-- * \"Text.RE.PCRE.ByteString\"\n-- * \"Text.RE.PCRE.ByteString.Lazy\"\n-- * \"Text.RE.PCRE.Sequence\"\n-- * \"Text.RE.PCRE.String\"\n\n-- $macros\n-- There are a number of RE macros and corresponding Haskell parsers\n-- for parsing the matched text into appropriate Haskell types. See\n-- the [Macros Tables](http:\/\/regex.uk\/macros) for details.\n\n-- $options\n-- You can specify different compilation options by appending a\n-- to the name of an [re| ... |] or [ed| ... \\\/\\\/\\\/ ... |] quasi quoter\n-- to select the corresponding compilation option. For example, the\n-- section,\n--\n-- @(?=~\/ [edBlockInsensitive|foo$\\\/\\\/\\\/bar|])@\n--\n-- will replace a @foo@ suffix of the argument text, of any\n-- capitalisation, with a (lower case) @bar@. If you need to specify the\n-- options dynamically, use the @[re_| ... |]@ and @[ed_| ... \\\/\\\/\\\/ ... |]@\n-- quasi quoters, which generate functions that take an 'IsOption' option\n-- (e.g., a 'SimpleReOptions' value) and yields a 'RE' or 'SearchReplace'\n-- as apropriate. For example if you have a 'SimpleReOptions' value in\n-- @sro@ then\n--\n-- @(?=~\/ [ed_|foo$\\\/\\\/\\\/bar|] sro)@\n--\n-- will compile the @foo$@ RE according to the value of @sro@. For more\n-- on specifying RE options see \"Text.RE.REOptions\".\n\n-- $re\n-- The @[re|.*|]@ quasi quoters, with variants for specifing different\n-- options to the RE compiler (see \"Text.RE.REOptions\"), and the\n-- specialised back-end types and functions.\n\n-- $ed\n-- The -- | the @[ed| ... \\\/\\\/\\\/ ... |]@ quasi quoters; for example,\n--\n-- @[ed|${y}([0-9]{4})-0*${m}([0-9]{2})-0*${d}([0-9]{2})\\\/\\\/\\\/${d}\\\/${m}\\\/${y}|])@\n--\n-- represents a @SearchReplace@ that will convert a YYYY-MM-DD format date\n-- into a DD\\\/MM\\\/YYYY format date.\n--\n-- The only difference betweem these quasi quoters is the RE options that are set,\n-- using the same conventions as the @[re| ... |]@ quasi quoters.\n--\n\n-- $isregex\n-- The 'IsRegex' class is used to abstact over the different regex back ends and\n-- the text types they work with -- see \"Text.RE.Tools.IsRegex\" for details.\n\n-- $instances\n-- These module exportss merely provide the 'IsRegex' instances.\n","avg_line_length":28.6274509804,"max_line_length":91,"alphanum_fraction":0.6250684932} {"size":2456,"ext":"hs","lang":"Haskell","max_stars_count":2723.0,"content":"-- Copyright (c) 2016-present, Facebook, Inc.\n-- All rights reserved.\n--\n-- This source code is licensed under the BSD-style license found in the\n-- LICENSE file in the root directory of this source tree.\n\n\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Duckling.Quantity.ES.Corpus\n ( corpus\n ) where\n\nimport Prelude\nimport Data.String\n\nimport Duckling.Locale\nimport Duckling.Quantity.Types\nimport Duckling.Resolve\nimport Duckling.Testing.Types\n\ncontext :: Context\ncontext = testContext { locale = makeLocale ES Nothing }\n\ncorpus :: Corpus\ncorpus = (context, testOptions, allExamples)\n\nallExamples :: [Example]\nallExamples = concat\n [ examples (simple Pound 2 (Just \"carne\"))\n [ \"dos libras de carne\"\n ]\n , examples (simple Gram 2 Nothing)\n [ \"dos gramos\"\n , \"0,002 kg\"\n , \"2\/1000 kilogramos\"\n , \"2000 miligramos\"\n ]\n , examples (simple Gram 1000 Nothing)\n [ \"un kilogramo\"\n , \"un kg\"\n ]\n , examples (simple Pound 1 Nothing)\n [ \"una libra\"\n , \"1 lb\"\n , \"una lb\"\n ]\n , examples (simple Ounce 2 Nothing)\n [ \"2 onzas\"\n , \"2oz\"\n ]\n , examples (simple Cup 3 (Just \"azucar\"))\n [ \"tres tazas de azucar\"\n , \"3 tazas de AzUcAr\"\n ]\n , examples (simple Cup 0.75 Nothing)\n [ \"3\/4 taza\"\n , \"0,75 taza\"\n , \",75 tazas\"\n ]\n , examples (simple Gram 500 (Just \"fresas\"))\n [ \"500 gramos de fresas\"\n , \"500g de fresas\"\n , \"0,5 kilogramos de fresas\"\n , \"0,5 kg de fresas\"\n , \"500000mg de fresas\"\n ]\n , examples (under Pound 6 (Just \"carne\"))\n [ \"menos que seis libras de carne\"\n , \"no m\u00e1s que 6 lbs de carne\"\n , \"por debajo de 6,0 libras de carne\"\n , \"a lo sumo seis libras de carne\"\n ]\n , examples (above Cup 2 Nothing)\n [ \"excesivo 2 tazas\"\n , \"como m\u00ednimo dos tazas\"\n , \"mayor de 2 tazas\"\n , \"m\u00e1s de 2 tazas\"\n ]\n , examples (above Ounce 4 (Just \"chocolate\"))\n [ \"excesivo 4 oz de chocolate\"\n , \"al menos 4,0 oz de chocolate\"\n , \"mayor de cuatro onzas de chocolate\"\n , \"m\u00e1s de cuatro onzas de chocolate\"\n ]\n ]\n","avg_line_length":28.2298850575,"max_line_length":72,"alphanum_fraction":0.5150651466} {"size":647,"ext":"hs","lang":"Haskell","max_stars_count":25.0,"content":"{-# LANGUAGE PatternSynonyms #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Graphics.GL.EXT.VertexArrayBGRA\n-- Copyright : (c) Sven Panne 2019\n-- License : BSD3\n--\n-- Maintainer : Sven Panne <svenpanne@gmail.com>\n-- Stability : stable\n-- Portability : portable\n--\n--------------------------------------------------------------------------------\n\nmodule Graphics.GL.EXT.VertexArrayBGRA (\n -- * Extension Support\n glGetEXTVertexArrayBGRA,\n gl_EXT_vertex_array_bgra,\n -- * Enums\n pattern GL_BGRA\n) where\n\nimport Graphics.GL.ExtensionPredicates\nimport Graphics.GL.Tokens\n","avg_line_length":26.9583333333,"max_line_length":80,"alphanum_fraction":0.5239567233} {"size":2386,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule Git.Stale.FunctionalSpec\n ( spec,\n )\nwhere\n\nimport App\nimport Common.Utils\nimport qualified Control.Monad.Reader as R\nimport qualified Data.Time.Calendar as Cal\nimport qualified Data.Time.Clock as Clock\nimport Git.Stale.Core.MonadFindBranches\nimport Git.Stale.Parsing\nimport Git.Stale.Types.Env\nimport qualified System.IO as IO\nimport qualified System.IO.Silently as Shh\nimport qualified System.Process as P\nimport Test.Hspec\n\nspec :: Spec\nspec = afterAll_ tearDown $ beforeAll_ setup $ do\n describe \"Git.Stale.FunctionalSpec\" $ do\n it \"Should have 0 Errors, 20 Merged, and 14 Unmerged\" $ do\n env <- mkEnv\n output <- Shh.capture_ (runTest env)\n lines output `shouldSatisfy` verifyOutput\n\nrunTest :: Env -> IO ()\nrunTest env = R.runReaderT (runAppT runFindBranches) env\n\nmkEnv :: IO Env\nmkEnv = do\n d <- currDay\n let args =\n [ \"--grep=1\",\n \"--path=.\/scripts\/testing\/git-fs\",\n \"--branch-type=local\",\n \"--master=master\",\n \"--limit=0\"\n ]\n case parseArgs d args of\n Right env -> pure env\n Left e -> error (\"Error parsing args: \" <> show e)\n\nsetup :: IO ()\nsetup =\n let proc = (P.shell \".\/setup_git_fs.sh\") {P.cwd = (Just \".\/scripts\/testing\/\")}\n in Shh.hSilence [IO.stderr] $ P.readCreateProcess proc \"\" *> pure ()\n\ntearDown :: IO ()\ntearDown =\n let proc = (P.shell \".\/teardown_git_fs.sh\") {P.cwd = (Just \".\/scripts\/testing\/\")}\n in P.readCreateProcess proc \"\" *> pure ()\n\ncurrDay :: IO Cal.Day\ncurrDay = fmap Clock.utctDay Clock.getCurrentTime\n\nverifyOutput :: [String] -> Bool\nverifyOutput = allTrue . toVerifier\n\nnewtype Verifier = Verifier (Bool, Bool, Bool)\n\ninstance Semigroup Verifier where\n (Verifier (x, y, z)) <> (Verifier (x', y', z')) = Verifier ((x || x'), (y || y'), (z || z'))\n\ninstance Monoid Verifier where\n mempty = Verifier (False, False, False)\n\nallTrue :: Verifier -> Bool\nallTrue (Verifier (True, True, True)) = True\nallTrue _ = False\n\ntoVerifier :: [String] -> Verifier\ntoVerifier = foldr ((<>) . f) mempty\n where\n f (matchAndStrip \"ERRORS: \" -> Just res) =\n Verifier ((res == \"0\"), False, False)\n f (matchAndStrip \"MERGED: \" -> Just res) =\n Verifier (False, (res == \"20\"), False)\n f (matchAndStrip \"UNMERGED: \" -> Just res) =\n Verifier (False, False, (res == \"14\"))\n f _ = mempty\n","avg_line_length":28.0705882353,"max_line_length":94,"alphanum_fraction":0.6512992456} {"size":303,"ext":"hs","lang":"Haskell","max_stars_count":417.0,"content":"module Listing2 where\n\ndata SensorType\n = TemperatureSensor\n | PressureSensor\n | PropellantDepletionSensor\n\ndata DeviceType\n = Sensor SensorType\n | Controller\n | Booster\n | RotaryEngine\n | FuelTank\n\ntype Name = String\n\ntype Components = [Device]\n\ndata Device = Device Name DeviceType Components\n","avg_line_length":15.15,"max_line_length":47,"alphanum_fraction":0.7590759076} {"size":40988,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"{-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TypeFamilies #-}\n\n-- | The general Stack configuration that starts everything off. This should\n-- be smart to falback if there is no stack.yaml, instead relying on\n-- whatever files are available.\n--\n-- If there is no stack.yaml, and there is a cabal.config, we\n-- read in those constraints, and if there's a cabal.sandbox.config,\n-- we read any constraints from there and also find the package\n-- database from there, etc. And if there's nothing, we should\n-- probably default to behaving like cabal, possibly with spitting out\n-- a warning that \"you should run `stk init` to make things better\".\nmodule Stack.Config\n (MiniConfig\n ,loadConfig\n ,loadConfigMaybeProject\n ,loadMiniConfig\n ,loadConfigYaml\n ,packagesParser\n ,getImplicitGlobalProjectDir\n ,getStackYaml\n ,getSnapshots\n ,makeConcreteResolver\n ,checkOwnership\n ,getInContainer\n ,getInNixShell\n ,defaultConfigYaml\n ,getProjectConfig\n ,LocalConfigStatus(..)\n ) where\n\nimport Control.Monad.Extra (firstJustM)\nimport Stack.Prelude\nimport Data.Aeson.Extended\nimport qualified Data.ByteString as S\nimport Data.ByteString.Builder (toLazyByteString)\nimport Data.Coerce (coerce)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.Map as Map\nimport qualified Data.Map.Merge.Strict as MS\nimport qualified Data.Monoid\nimport Data.Monoid.Map (MonoidMap(..))\nimport qualified Data.Text as T\nimport Data.Text.Encoding (encodeUtf8)\nimport qualified Data.Yaml as Yaml\nimport Distribution.System (OS (..), Platform (..), buildPlatform, Arch(OtherArch))\nimport qualified Distribution.Text\nimport Distribution.Version (simplifyVersionRange, mkVersion')\nimport GHC.Conc (getNumProcessors)\nimport Lens.Micro ((.~), lens)\nimport Network.HTTP.StackClient (httpJSON, parseUrlThrow, getResponseBody)\nimport Options.Applicative (Parser, strOption, long, help)\nimport Pantry\nimport qualified Pantry.SHA256 as SHA256\nimport Path\nimport Path.Extra (toFilePathNoTrailingSep)\nimport Path.Find (findInParents)\nimport Path.IO\nimport qualified Paths_stack as Meta\nimport Stack.Config.Build\nimport Stack.Config.Docker\nimport Stack.Config.Nix\nimport Stack.Constants\nimport Stack.Build.Haddock (shouldHaddockDeps)\nimport qualified Stack.Image as Image\nimport Stack.SourceMap\nimport Stack.Types.Build\nimport Stack.Types.Config\nimport Stack.Types.Docker\nimport Stack.Types.Nix\nimport Stack.Types.Resolver\nimport Stack.Types.Runner\nimport Stack.Types.SourceMap\nimport Stack.Types.Version\nimport System.Console.ANSI (hSupportsANSIWithoutEmulation)\nimport System.Environment\nimport System.PosixCompat.Files (fileOwner, getFileStatus)\nimport System.PosixCompat.User (getEffectiveUserID)\nimport RIO.Process\n\n-- | If deprecated path exists, use it and print a warning.\n-- Otherwise, return the new path.\ntryDeprecatedPath\n :: HasLogFunc env\n => Maybe T.Text -- ^ Description of file for warning (if Nothing, no deprecation warning is displayed)\n -> (Path Abs a -> RIO env Bool) -- ^ Test for existence\n -> Path Abs a -- ^ New path\n -> Path Abs a -- ^ Deprecated path\n -> RIO env (Path Abs a, Bool) -- ^ (Path to use, whether it already exists)\ntryDeprecatedPath mWarningDesc exists new old = do\n newExists <- exists new\n if newExists\n then return (new, True)\n else do\n oldExists <- exists old\n if oldExists\n then do\n case mWarningDesc of\n Nothing -> return ()\n Just desc ->\n logWarn $\n \"Warning: Location of \" <> display desc <> \" at '\" <>\n fromString (toFilePath old) <>\n \"' is deprecated; rename it to '\" <>\n fromString (toFilePath new) <>\n \"' instead\"\n return (old, True)\n else return (new, False)\n\n-- | Get the location of the implicit global project directory.\n-- If the directory already exists at the deprecated location, its location is returned.\n-- Otherwise, the new location is returned.\ngetImplicitGlobalProjectDir\n :: HasLogFunc env\n => Config -> RIO env (Path Abs Dir)\ngetImplicitGlobalProjectDir config =\n --TEST no warning printed\n liftM fst $ tryDeprecatedPath\n Nothing\n doesDirExist\n (implicitGlobalProjectDir stackRoot)\n (implicitGlobalProjectDirDeprecated stackRoot)\n where\n stackRoot = view stackRootL config\n\n-- | This is slightly more expensive than @'asks' ('bcStackYaml' '.' 'getBuildConfig')@\n-- and should only be used when no 'BuildConfig' is at hand.\ngetStackYaml :: HasConfig env => RIO env (Path Abs File)\ngetStackYaml = do\n config <- view configL\n case configMaybeProject config of\n Just (_project, stackYaml) -> return stackYaml\n Nothing -> liftM (<\/> stackDotYaml) (getImplicitGlobalProjectDir config)\n\n-- | Download the 'Snapshots' value from stackage.org.\ngetSnapshots :: HasConfig env => RIO env Snapshots\ngetSnapshots = do\n latestUrlText <- askLatestSnapshotUrl\n latestUrl <- parseUrlThrow (T.unpack latestUrlText)\n logDebug $ \"Downloading snapshot versions file from \" <> display latestUrlText\n result <- httpJSON latestUrl\n logDebug \"Done downloading and parsing snapshot versions file\"\n return $ getResponseBody result\n\n-- | Turn an 'AbstractResolver' into a 'Resolver'.\nmakeConcreteResolver\n :: HasConfig env\n => AbstractResolver\n -> RIO env SnapshotLocation\nmakeConcreteResolver (ARResolver r) = pure r\nmakeConcreteResolver ar = do\n snapshots <- getSnapshots\n r <-\n case ar of\n ARResolver r -> assert False $ makeConcreteResolver (ARResolver r)\n ARGlobal -> do\n config <- view configL\n implicitGlobalDir <- getImplicitGlobalProjectDir config\n let fp = implicitGlobalDir <\/> stackDotYaml\n iopc <- loadConfigYaml (parseProjectAndConfigMonoid (parent fp)) fp\n ProjectAndConfigMonoid project _ <- liftIO iopc\n return $ projectResolver project\n ARLatestNightly -> return $ nightlySnapshotLocation $ snapshotsNightly snapshots\n ARLatestLTSMajor x ->\n case IntMap.lookup x $ snapshotsLts snapshots of\n Nothing -> throwString $ \"No LTS release found with major version \" ++ show x\n Just y -> return $ ltsSnapshotLocation x y\n ARLatestLTS\n | IntMap.null $ snapshotsLts snapshots -> throwString \"No LTS releases found\"\n | otherwise ->\n let (x, y) = IntMap.findMax $ snapshotsLts snapshots\n in return $ ltsSnapshotLocation x y\n logInfo $ \"Selected resolver: \" <> display r\n return r\n\n-- | Get the latest snapshot resolver available.\ngetLatestResolver :: HasConfig env => RIO env SnapshotLocation\ngetLatestResolver = do\n snapshots <- getSnapshots\n let mlts = uncurry ltsSnapshotLocation <$>\n listToMaybe (reverse (IntMap.toList (snapshotsLts snapshots)))\n pure $ fromMaybe (nightlySnapshotLocation (snapshotsNightly snapshots)) mlts\n\n-- | Create a 'Config' value when we're not using any local\n-- configuration files (e.g., the script command)\nconfigNoLocalConfig\n :: HasRunner env\n => Path Abs Dir -- ^ stack root\n -> Maybe AbstractResolver\n -> ConfigMonoid\n -> (Config -> RIO env a)\n -> RIO env a\nconfigNoLocalConfig _ Nothing _ _ = throwIO NoResolverWhenUsingNoLocalConfig\nconfigNoLocalConfig stackRoot (Just resolver) configMonoid inner = do\n userConfigPath <- liftIO $ getFakeConfigPath stackRoot resolver\n configFromConfigMonoid\n stackRoot\n userConfigPath\n False\n (Just resolver)\n Nothing -- project\n configMonoid\n inner\n\n-- Interprets ConfigMonoid options.\nconfigFromConfigMonoid\n :: HasRunner env\n => Path Abs Dir -- ^ stack root, e.g. ~\/.stack\n -> Path Abs File -- ^ user config file path, e.g. ~\/.stack\/config.yaml\n -> Bool -- ^ allow locals?\n -> Maybe AbstractResolver\n -> Maybe (Project, Path Abs File)\n -> ConfigMonoid\n -> (Config -> RIO env a)\n -> RIO env a\nconfigFromConfigMonoid\n configStackRoot configUserConfigPath configAllowLocals mresolver\n mproject ConfigMonoid{..} inner = do\n -- If --stack-work is passed, prefer it. Otherwise, if STACK_WORK\n -- is set, use that. If neither, use the default \".stack-work\"\n mstackWorkEnv <- liftIO $ lookupEnv stackWorkEnvVar\n configWorkDir0 <- maybe (return relDirStackWork) (liftIO . parseRelDir) mstackWorkEnv\n let configWorkDir = fromFirst configWorkDir0 configMonoidWorkDir\n configLatestSnapshot = fromFirst\n \"https:\/\/s3.amazonaws.com\/haddock.stackage.org\/snapshots.json\"\n configMonoidLatestSnapshot\n clConnectionCount = fromFirst 8 configMonoidConnectionCount\n configHideTHLoading = fromFirst True configMonoidHideTHLoading\n\n configGHCVariant0 = getFirst configMonoidGHCVariant\n configGHCBuild = getFirst configMonoidGHCBuild\n configInstallGHC = fromFirst True configMonoidInstallGHC\n configSkipGHCCheck = fromFirst False configMonoidSkipGHCCheck\n configSkipMsys = fromFirst False configMonoidSkipMsys\n\n configExtraIncludeDirs = configMonoidExtraIncludeDirs\n configExtraLibDirs = configMonoidExtraLibDirs\n configOverrideGccPath = getFirst configMonoidOverrideGccPath\n\n -- Only place in the codebase where platform is hard-coded. In theory\n -- in the future, allow it to be configured.\n (Platform defArch defOS) = buildPlatform\n arch = fromMaybe defArch\n $ getFirst configMonoidArch >>= Distribution.Text.simpleParse\n os = defOS\n configPlatform = Platform arch os\n\n configRequireStackVersion = simplifyVersionRange (getIntersectingVersionRange configMonoidRequireStackVersion)\n\n configImage = Image.imgOptsFromMonoid configMonoidImageOpts\n\n configCompilerCheck = fromFirst MatchMinor configMonoidCompilerCheck\n\n case arch of\n OtherArch \"aarch64\" -> return ()\n OtherArch unk -> logWarn $ \"Warning: Unknown value for architecture setting: \" <> displayShow unk\n _ -> return ()\n\n configPlatformVariant <- liftIO $\n maybe PlatformVariantNone PlatformVariant <$> lookupEnv platformVariantEnvVar\n\n let configBuild = buildOptsFromMonoid configMonoidBuildOpts\n configDocker <-\n dockerOptsFromMonoid (fmap fst mproject) configStackRoot mresolver configMonoidDockerOpts\n configNix <- nixOptsFromMonoid configMonoidNixOpts os\n\n configSystemGHC <-\n case (getFirst configMonoidSystemGHC, nixEnable configNix) of\n (Just False, True) ->\n throwM NixRequiresSystemGhc\n _ ->\n return\n (fromFirst\n (dockerEnable configDocker || nixEnable configNix)\n configMonoidSystemGHC)\n\n when (isJust configGHCVariant0 && configSystemGHC) $\n throwM ManualGHCVariantSettingsAreIncompatibleWithSystemGHC\n\n rawEnv <- liftIO getEnvironment\n pathsEnv <- either throwM return\n $ augmentPathMap (map toFilePath configMonoidExtraPath)\n (Map.fromList (map (T.pack *** T.pack) rawEnv))\n origEnv <- mkProcessContext pathsEnv\n let configProcessContextSettings _ = return origEnv\n\n configLocalProgramsBase <- case getFirst configMonoidLocalProgramsBase of\n Nothing -> getDefaultLocalProgramsBase configStackRoot configPlatform origEnv\n Just path -> return path\n platformOnlyDir <- runReaderT platformOnlyRelDir (configPlatform, configPlatformVariant)\n let configLocalPrograms = configLocalProgramsBase <\/> platformOnlyDir\n\n configLocalBin <-\n case getFirst configMonoidLocalBinPath of\n Nothing -> do\n localDir <- getAppUserDataDir \"local\"\n return $ localDir <\/> relDirBin\n Just userPath ->\n (case mproject of\n -- Not in a project\n Nothing -> resolveDir' userPath\n -- Resolves to the project dir and appends the user path if it is relative\n Just (_, configYaml) -> resolveDir (parent configYaml) userPath)\n -- TODO: Either catch specific exceptions or add a\n -- parseRelAsAbsDirMaybe utility and use it along with\n -- resolveDirMaybe.\n `catchAny`\n const (throwIO (NoSuchDirectory userPath))\n\n configJobs <-\n case getFirst configMonoidJobs of\n Nothing -> liftIO getNumProcessors\n Just i -> return i\n let configConcurrentTests = fromFirst True configMonoidConcurrentTests\n\n let configTemplateParams = configMonoidTemplateParameters\n configScmInit = getFirst configMonoidScmInit\n configGhcOptionsByName = coerce configMonoidGhcOptionsByName\n configGhcOptionsByCat = coerce configMonoidGhcOptionsByCat\n configSetupInfoLocations = configMonoidSetupInfoLocations\n configPvpBounds = fromFirst (PvpBounds PvpBoundsNone False) configMonoidPvpBounds\n configModifyCodePage = fromFirst True configMonoidModifyCodePage\n configExplicitSetupDeps = configMonoidExplicitSetupDeps\n configRebuildGhcOptions = fromFirst False configMonoidRebuildGhcOptions\n configApplyGhcOptions = fromFirst AGOLocals configMonoidApplyGhcOptions\n configAllowNewer = fromFirst False configMonoidAllowNewer\n configDefaultTemplate = getFirst configMonoidDefaultTemplate\n configDumpLogs = fromFirst DumpWarningLogs configMonoidDumpLogs\n configSaveHackageCreds = fromFirst True configMonoidSaveHackageCreds\n configHackageBaseUrl = fromFirst \"https:\/\/hackage.haskell.org\/\" configMonoidHackageBaseUrl\n\n configAllowDifferentUser <-\n case getFirst configMonoidAllowDifferentUser of\n Just True -> return True\n _ -> getInContainer\n\n let configMaybeProject = mproject\n\n configRunner' <- view runnerL\n\n useAnsi <- liftIO $ fromMaybe True <$>\n hSupportsANSIWithoutEmulation stderr\n\n let stylesUpdate' = runnerStylesUpdate configRunner' <>\n configMonoidStyles\n useColor' = runnerUseColor configRunner'\n mUseColor = do\n colorWhen <- getFirst configMonoidColorWhen\n return $ case colorWhen of\n ColorNever -> False\n ColorAlways -> True\n ColorAuto -> useAnsi\n configRunner = configRunner'\n & processContextL .~ origEnv\n & stylesUpdateL .~ stylesUpdate'\n & useColorL .~ fromMaybe useColor' mUseColor\n\n hsc <-\n case getFirst configMonoidPackageIndices of\n Nothing -> pure defaultHackageSecurityConfig\n Just [hsc] -> pure hsc\n Just x -> error $ \"When overriding the default package index, you must provide exactly one value, received: \" ++ show x\n withPantryConfig\n (configStackRoot <\/> relDirPantry)\n hsc\n (maybe HpackBundled HpackCommand $ getFirst configMonoidOverrideHpack)\n clConnectionCount\n (\\configPantryConfig -> inner Config {..})\n\n-- | Get the default location of the local programs directory.\ngetDefaultLocalProgramsBase :: MonadThrow m\n => Path Abs Dir\n -> Platform\n -> ProcessContext\n -> m (Path Abs Dir)\ngetDefaultLocalProgramsBase configStackRoot configPlatform override =\n let\n defaultBase = configStackRoot <\/> relDirPrograms\n in\n case configPlatform of\n -- For historical reasons, on Windows a subdirectory of LOCALAPPDATA is\n -- used instead of a subdirectory of STACK_ROOT. Unifying the defaults would\n -- mean that Windows users would manually have to move data from the old\n -- location to the new one, which is undesirable.\n Platform _ Windows ->\n case Map.lookup \"LOCALAPPDATA\" $ view envVarsL override of\n Just t ->\n case parseAbsDir $ T.unpack t of\n Nothing -> throwM $ stringException (\"Failed to parse LOCALAPPDATA environment variable (expected absolute directory): \" ++ show t)\n Just lad ->\n return $ lad <\/> relDirUpperPrograms <\/> relDirStackProgName\n Nothing -> return defaultBase\n _ -> return defaultBase\n\n-- | An environment with a subset of BuildConfig used for setup.\ndata MiniConfig = MiniConfig -- TODO do we really need a whole extra data type?\n { mcGHCVariant :: !GHCVariant\n , mcConfig :: !Config\n }\ninstance HasConfig MiniConfig where\n configL = lens mcConfig (\\x y -> x { mcConfig = y })\ninstance HasProcessContext MiniConfig where\n processContextL = configL.processContextL\ninstance HasPantryConfig MiniConfig where\n pantryConfigL = configL.pantryConfigL\ninstance HasPlatform MiniConfig\ninstance HasGHCVariant MiniConfig where\n ghcVariantL = lens mcGHCVariant (\\x y -> x { mcGHCVariant = y })\ninstance HasRunner MiniConfig where\n runnerL = configL.runnerL\ninstance HasLogFunc MiniConfig where\n logFuncL = configL.logFuncL\n\n-- | Load the 'MiniConfig'.\nloadMiniConfig :: Config -> MiniConfig\nloadMiniConfig config = MiniConfig\n { mcGHCVariant = configGHCVariantDefault config\n , mcConfig = config\n }\n\nconfigGHCVariantDefault :: Config -> GHCVariant -- FIXME why not just use this as the HasGHCVariant instance for Config?\nconfigGHCVariantDefault = fromMaybe GHCStandard . configGHCVariant0\n\n-- Load the configuration, using environment variables, and defaults as\n-- necessary.\nloadConfigMaybeProject\n :: HasRunner env\n => ConfigMonoid\n -- ^ Config monoid from parsed command-line arguments\n -> Maybe AbstractResolver\n -- ^ Override resolver\n -> LocalConfigStatus (Project, Path Abs File, ConfigMonoid)\n -- ^ Project config to use, if any\n -> (LoadConfig -> RIO env a)\n -> RIO env a\nloadConfigMaybeProject configArgs mresolver mproject inner = do\n (stackRoot, userOwnsStackRoot) <- determineStackRootAndOwnership configArgs\n\n let loadHelper mproject' inner2 = do\n userConfigPath <- getDefaultUserConfigPath stackRoot\n extraConfigs0 <- getExtraConfigs userConfigPath >>=\n mapM (\\file -> loadConfigYaml (parseConfigMonoid (parent file)) file)\n let extraConfigs =\n -- non-project config files' existence of a docker section should never default docker\n -- to enabled, so make it look like they didn't exist\n map (\\c -> c {configMonoidDockerOpts =\n (configMonoidDockerOpts c) {dockerMonoidDefaultEnable = Any False}})\n extraConfigs0\n\n configFromConfigMonoid\n stackRoot\n userConfigPath\n True -- allow locals\n mresolver\n (fmap (\\(x, y, _) -> (x, y)) mproject')\n (mconcat $ configArgs\n : maybe id (\\(_, _, projectConfig) -> (projectConfig:)) mproject' extraConfigs)\n inner2\n\n let withConfig = case mproject of\n LCSNoConfig _ -> configNoLocalConfig stackRoot mresolver configArgs\n LCSProject project -> loadHelper $ Just project\n LCSNoProject -> loadHelper Nothing\n\n withConfig $ \\config -> do\n unless (mkVersion' Meta.version `withinRange` configRequireStackVersion config)\n (throwM (BadStackVersionException (configRequireStackVersion config)))\n\n let mprojectRoot = fmap (\\(_, fp, _) -> parent fp) mproject\n unless (configAllowDifferentUser config) $ do\n unless userOwnsStackRoot $\n throwM (UserDoesn'tOwnDirectory stackRoot)\n forM_ mprojectRoot $ \\dir ->\n checkOwnership (dir <\/> configWorkDir config)\n\n inner LoadConfig\n { lcConfig = config\n , lcLoadBuildConfig = runRIO config . loadBuildConfig mproject mresolver\n , lcProjectRoot =\n case mprojectRoot of\n LCSProject fp -> Just fp\n LCSNoProject -> Nothing\n LCSNoConfig _ -> Nothing\n }\n\n-- | Load the configuration, using current directory, environment variables,\n-- and defaults as necessary. The passed @Maybe (Path Abs File)@ is an\n-- override for the location of the project's stack.yaml.\nloadConfig :: HasRunner env\n => ConfigMonoid\n -- ^ Config monoid from parsed command-line arguments\n -> Maybe AbstractResolver\n -- ^ Override resolver\n -> StackYamlLoc (Path Abs File)\n -- ^ Override stack.yaml\n -> (LoadConfig -> RIO env a)\n -> RIO env a\nloadConfig configArgs mresolver mstackYaml inner =\n loadProjectConfig mstackYaml >>= \\x -> loadConfigMaybeProject configArgs mresolver x inner\n\n-- | Load the build configuration, adds build-specific values to config loaded by @loadConfig@.\n-- values.\nloadBuildConfig :: LocalConfigStatus (Project, Path Abs File, ConfigMonoid)\n -> Maybe AbstractResolver -- override resolver\n -> Maybe WantedCompiler -- override compiler\n -> RIO Config BuildConfig\nloadBuildConfig mproject maresolver mcompiler = do\n config <- ask\n\n -- If provided, turn the AbstractResolver from the command line\n -- into a Resolver that can be used below.\n\n -- The maresolver and mcompiler are provided on the command\n -- line. In order to properly deal with an AbstractResolver, we\n -- need a base directory (to deal with custom snapshot relative\n -- paths). We consider the current working directory to be the\n -- correct base. Let's calculate the mresolver first.\n mresolver <- forM maresolver $ \\aresolver -> do\n logDebug (\"Using resolver: \" <> display aresolver <> \" specified on command line\")\n makeConcreteResolver aresolver\n\n (project', stackYamlFP) <- case mproject of\n LCSProject (project, fp, _) -> do\n forM_ (projectUserMsg project) (logWarn . fromString)\n return (project, fp)\n LCSNoConfig _ -> do\n p <- assert (isJust mresolver) (getEmptyProject mresolver)\n return (p, configUserConfigPath config)\n LCSNoProject -> do\n logDebug \"Run from outside a project, using implicit global project config\"\n destDir <- getImplicitGlobalProjectDir config\n let dest :: Path Abs File\n dest = destDir <\/> stackDotYaml\n dest' :: FilePath\n dest' = toFilePath dest\n ensureDir destDir\n exists <- doesFileExist dest\n if exists\n then do\n iopc <- loadConfigYaml (parseProjectAndConfigMonoid destDir) dest\n ProjectAndConfigMonoid project _ <- liftIO iopc\n when (view terminalL config) $\n case maresolver of\n Nothing ->\n logDebug $\n \"Using resolver: \" <>\n display (projectResolver project) <>\n \" from implicit global project's config file: \" <>\n fromString dest'\n Just _ -> return ()\n return (project, dest)\n else do\n logInfo (\"Writing implicit global project config file to: \" <> fromString dest')\n logInfo \"Note: You can change the snapshot via the resolver field there.\"\n p <- getEmptyProject mresolver\n liftIO $ do\n S.writeFile dest' $ S.concat\n [ \"# This is the implicit global project's config file, which is only used when\\n\"\n , \"# 'stack' is run outside of a real project. Settings here do _not_ act as\\n\"\n , \"# defaults for all projects. To change stack's default settings, edit\\n\"\n , \"# '\", encodeUtf8 (T.pack $ toFilePath $ configUserConfigPath config), \"' instead.\\n\"\n , \"#\\n\"\n , \"# For more information about stack's configuration, see\\n\"\n , \"# http:\/\/docs.haskellstack.org\/en\/stable\/yaml_configuration\/\\n\"\n , \"#\\n\"\n , Yaml.encode p]\n S.writeFile (toFilePath $ parent dest <\/> relFileReadmeTxt) $ S.concat\n [ \"This is the implicit global project, which is used only when 'stack' is run\\n\"\n , \"outside of a real project.\\n\" ]\n return (p, dest)\n let project = project'\n { projectResolver = fromMaybe (projectResolver project') mresolver\n }\n\n snapshot <- loadSnapshot (projectResolver project)\n\n extraPackageDBs <- mapM resolveDir' (projectExtraPackageDBs project)\n\n let bopts = configBuild config\n\n packages0 <- for (projectPackages project) $ \\fp@(RelFilePath t) -> do\n abs' <- resolveDir (parent stackYamlFP) (T.unpack t)\n let resolved = ResolvedPath fp abs'\n pp <- mkProjectPackage YesPrintWarnings resolved (boptsHaddock bopts)\n pure (cpName $ ppCommon pp, pp)\n\n deps0 <- forM (projectDependencies project) $ \\plp -> do\n dp <- additionalDepPackage (shouldHaddockDeps bopts) plp\n pure (cpName $ dpCommon dp, dp)\n\n checkDuplicateNames $\n map (second (PLMutable . ppResolvedDir)) packages0 ++\n map (second dpLocation) deps0\n\n let packages1 = Map.fromList packages0\n snPackages = snapshotPackages snapshot `Map.difference` packages1\n `Map.difference` Map.fromList deps0\n\n snDeps <- Map.traverseWithKey (snapToDepPackage (shouldHaddockDeps bopts)) snPackages\n\n let deps1 = Map.fromList deps0 `Map.union` snDeps\n\n let mergeApply m1 m2 f =\n MS.merge MS.preserveMissing MS.dropMissing (MS.zipWithMatched f) m1 m2\n pFlags = projectFlags project\n packages2 = mergeApply packages1 pFlags $\n \\_ p flags -> p{ppCommon=(ppCommon p){cpFlags=flags}}\n deps2 = mergeApply deps1 pFlags $\n \\_ d flags -> d{dpCommon=(dpCommon d){cpFlags=flags}}\n\n checkFlagsUsedThrowing pFlags FSStackYaml packages1 deps1\n\n let pkgGhcOptions = configGhcOptionsByName config\n deps = mergeApply deps2 pkgGhcOptions $\n \\_ d options -> d{dpCommon=(dpCommon d){cpGhcOptions=options}}\n packages = mergeApply packages2 pkgGhcOptions $\n \\_ p options -> p{ppCommon=(ppCommon p){cpGhcOptions=options}}\n unusedPkgGhcOptions = pkgGhcOptions `Map.restrictKeys` Map.keysSet packages2\n `Map.restrictKeys` Map.keysSet deps2\n\n unless (Map.null unusedPkgGhcOptions) $\n throwM $ InvalidGhcOptionsSpecification (Map.keys unusedPkgGhcOptions)\n\n let wanted = SMWanted\n { smwCompiler = fromMaybe (snapshotCompiler snapshot) mcompiler\n , smwProject = packages\n , smwDeps = deps\n }\n\n return BuildConfig\n { bcConfig = config\n , bcSMWanted = wanted\n , bcGHCVariant = configGHCVariantDefault config\n , bcExtraPackageDBs = extraPackageDBs\n , bcStackYaml = stackYamlFP\n , bcImplicitGlobal =\n case mproject of\n LCSNoProject -> True\n LCSProject _ -> False\n LCSNoConfig _ -> False\n , bcCurator = projectCurator project\n , bcDownloadCompiler = WithDownloadCompiler\n }\n where\n getEmptyProject :: Maybe SnapshotLocation -> RIO Config Project\n getEmptyProject mresolver = do\n r <- case mresolver of\n Just resolver -> do\n logInfo (\"Using resolver: \" <> display resolver <> \" specified on command line\")\n return resolver\n Nothing -> do\n r'' <- getLatestResolver\n logInfo (\"Using latest snapshot resolver: \" <> display r'')\n return r''\n return Project\n { projectUserMsg = Nothing\n , projectPackages = []\n , projectDependencies = []\n , projectFlags = mempty\n , projectResolver = r\n , projectCompiler = Nothing\n , projectExtraPackageDBs = []\n , projectCurator = Nothing\n }\n\n-- | Check if there are any duplicate package names and, if so, throw an\n-- exception.\ncheckDuplicateNames :: MonadThrow m => [(PackageName, PackageLocation)] -> m ()\ncheckDuplicateNames locals =\n case filter hasMultiples $ Map.toList $ Map.fromListWith (++) $ map (second return) locals of\n [] -> return ()\n x -> throwM $ DuplicateLocalPackageNames x\n where\n hasMultiples (_, _:_:_) = True\n hasMultiples _ = False\n\n\n-- | Get the stack root, e.g. @~\/.stack@, and determine whether the user owns it.\n--\n-- On Windows, the second value is always 'True'.\ndetermineStackRootAndOwnership\n :: (MonadIO m)\n => ConfigMonoid\n -- ^ Parsed command-line arguments\n -> m (Path Abs Dir, Bool)\ndetermineStackRootAndOwnership clArgs = liftIO $ do\n stackRoot <- do\n case getFirst (configMonoidStackRoot clArgs) of\n Just x -> return x\n Nothing -> do\n mstackRoot <- lookupEnv stackRootEnvVar\n case mstackRoot of\n Nothing -> getAppUserDataDir stackProgName\n Just x -> case parseAbsDir x of\n Nothing -> throwString (\"Failed to parse STACK_ROOT environment variable (expected absolute directory): \" ++ show x)\n Just parsed -> return parsed\n\n (existingStackRootOrParentDir, userOwnsIt) <- do\n mdirAndOwnership <- findInParents getDirAndOwnership stackRoot\n case mdirAndOwnership of\n Just x -> return x\n Nothing -> throwIO (BadStackRoot stackRoot)\n\n when (existingStackRootOrParentDir \/= stackRoot) $\n if userOwnsIt\n then ensureDir stackRoot\n else throwIO $\n Won'tCreateStackRootInDirectoryOwnedByDifferentUser\n stackRoot\n existingStackRootOrParentDir\n\n stackRoot' <- canonicalizePath stackRoot\n return (stackRoot', userOwnsIt)\n\n-- | @'checkOwnership' dir@ throws 'UserDoesn'tOwnDirectory' if @dir@\n-- isn't owned by the current user.\n--\n-- If @dir@ doesn't exist, its parent directory is checked instead.\n-- If the parent directory doesn't exist either, @'NoSuchDirectory' ('parent' dir)@\n-- is thrown.\ncheckOwnership :: (MonadIO m) => Path Abs Dir -> m ()\ncheckOwnership dir = do\n mdirAndOwnership <- firstJustM getDirAndOwnership [dir, parent dir]\n case mdirAndOwnership of\n Just (_, True) -> return ()\n Just (dir', False) -> throwIO (UserDoesn'tOwnDirectory dir')\n Nothing ->\n (throwIO . NoSuchDirectory) $ (toFilePathNoTrailingSep . parent) dir\n\n-- | @'getDirAndOwnership' dir@ returns @'Just' (dir, 'True')@ when @dir@\n-- exists and the current user owns it in the sense of 'isOwnedByUser'.\ngetDirAndOwnership\n :: (MonadIO m)\n => Path Abs Dir\n -> m (Maybe (Path Abs Dir, Bool))\ngetDirAndOwnership dir = liftIO $ forgivingAbsence $ do\n ownership <- isOwnedByUser dir\n return (dir, ownership)\n\n-- | Check whether the current user (determined with 'getEffectiveUserId') is\n-- the owner for the given path.\n--\n-- Will always return 'True' on Windows.\nisOwnedByUser :: MonadIO m => Path Abs t -> m Bool\nisOwnedByUser path = liftIO $ do\n if osIsWindows\n then return True\n else do\n fileStatus <- getFileStatus (toFilePath path)\n user <- getEffectiveUserID\n return (user == fileOwner fileStatus)\n\n-- | 'True' if we are currently running inside a Docker container.\ngetInContainer :: (MonadIO m) => m Bool\ngetInContainer = liftIO (isJust <$> lookupEnv inContainerEnvVar)\n\n-- | 'True' if we are currently running inside a Nix.\ngetInNixShell :: (MonadIO m) => m Bool\ngetInNixShell = liftIO (isJust <$> lookupEnv inNixShellEnvVar)\n\n-- | Determine the extra config file locations which exist.\n--\n-- Returns most local first\ngetExtraConfigs :: HasLogFunc env\n => Path Abs File -- ^ use config path\n -> RIO env [Path Abs File]\ngetExtraConfigs userConfigPath = do\n defaultStackGlobalConfigPath <- getDefaultGlobalConfigPath\n liftIO $ do\n env <- getEnvironment\n mstackConfig <-\n maybe (return Nothing) (fmap Just . parseAbsFile)\n $ lookup \"STACK_CONFIG\" env\n mstackGlobalConfig <-\n maybe (return Nothing) (fmap Just . parseAbsFile)\n $ lookup \"STACK_GLOBAL_CONFIG\" env\n filterM doesFileExist\n $ fromMaybe userConfigPath mstackConfig\n : maybe [] return (mstackGlobalConfig <|> defaultStackGlobalConfigPath)\n\n-- | Load and parse YAML from the given config file. Throws\n-- 'ParseConfigFileException' when there's a decoding error.\nloadConfigYaml\n :: HasLogFunc env\n => (Value -> Yaml.Parser (WithJSONWarnings a)) -> Path Abs File -> RIO env a\nloadConfigYaml parser path = do\n eres <- loadYaml parser path\n case eres of\n Left err -> liftIO $ throwM (ParseConfigFileException path err)\n Right res -> return res\n\n-- | Load and parse YAML from the given file.\nloadYaml\n :: HasLogFunc env\n => (Value -> Yaml.Parser (WithJSONWarnings a)) -> Path Abs File -> RIO env (Either Yaml.ParseException a)\nloadYaml parser path = do\n eres <- liftIO $ Yaml.decodeFileEither (toFilePath path)\n case eres of\n Left err -> return (Left err)\n Right val ->\n case Yaml.parseEither parser val of\n Left err -> return (Left (Yaml.AesonException err))\n Right (WithJSONWarnings res warnings) -> do\n logJSONWarnings (toFilePath path) warnings\n return (Right res)\n\n-- | Get the location of the project config file, if it exists.\ngetProjectConfig :: HasLogFunc env\n => StackYamlLoc (Path Abs File)\n -- ^ Override stack.yaml\n -> RIO env (LocalConfigStatus (Path Abs File))\ngetProjectConfig (SYLOverride stackYaml) = return $ LCSProject stackYaml\ngetProjectConfig SYLDefault = do\n env <- liftIO getEnvironment\n case lookup \"STACK_YAML\" env of\n Just fp -> do\n logInfo \"Getting project config file from STACK_YAML environment\"\n liftM LCSProject $ resolveFile' fp\n Nothing -> do\n currDir <- getCurrentDir\n maybe LCSNoProject LCSProject <$> findInParents getStackDotYaml currDir\n where\n getStackDotYaml dir = do\n let fp = dir <\/> stackDotYaml\n fp' = toFilePath fp\n logDebug $ \"Checking for project config at: \" <> fromString fp'\n exists <- doesFileExist fp\n if exists\n then return $ Just fp\n else return Nothing\ngetProjectConfig (SYLNoConfig parentDir) = return (LCSNoConfig parentDir)\n\ndata LocalConfigStatus a\n = LCSNoProject\n | LCSProject a\n | LCSNoConfig !(Path Abs Dir)\n -- ^ parent directory for making a concrete resolving\n deriving (Show,Functor,Foldable,Traversable)\n\n-- | Find the project config file location, respecting environment variables\n-- and otherwise traversing parents. If no config is found, we supply a default\n-- based on current directory.\nloadProjectConfig :: HasLogFunc env\n => StackYamlLoc (Path Abs File)\n -- ^ Override stack.yaml\n -> RIO env (LocalConfigStatus (Project, Path Abs File, ConfigMonoid))\nloadProjectConfig mstackYaml = do\n mfp <- getProjectConfig mstackYaml\n case mfp of\n LCSProject fp -> do\n currDir <- getCurrentDir\n logDebug $ \"Loading project config file \" <>\n fromString (maybe (toFilePath fp) toFilePath (stripProperPrefix currDir fp))\n LCSProject <$> load fp\n LCSNoProject -> do\n logDebug \"No project config file found, using defaults.\"\n return LCSNoProject\n LCSNoConfig mparentDir -> do\n logDebug \"Ignoring config files\"\n return (LCSNoConfig mparentDir)\n where\n load fp = do\n iopc <- loadConfigYaml (parseProjectAndConfigMonoid (parent fp)) fp\n ProjectAndConfigMonoid project config <- liftIO iopc\n return (project, fp, config)\n\n-- | Get the location of the default stack configuration file.\n-- If a file already exists at the deprecated location, its location is returned.\n-- Otherwise, the new location is returned.\ngetDefaultGlobalConfigPath\n :: HasLogFunc env\n => RIO env (Maybe (Path Abs File))\ngetDefaultGlobalConfigPath =\n case (defaultGlobalConfigPath, defaultGlobalConfigPathDeprecated) of\n (Just new,Just old) ->\n liftM (Just . fst ) $\n tryDeprecatedPath\n (Just \"non-project global configuration file\")\n doesFileExist\n new\n old\n (Just new,Nothing) -> return (Just new)\n _ -> return Nothing\n\n-- | Get the location of the default user configuration file.\n-- If a file already exists at the deprecated location, its location is returned.\n-- Otherwise, the new location is returned.\ngetDefaultUserConfigPath\n :: HasLogFunc env\n => Path Abs Dir -> RIO env (Path Abs File)\ngetDefaultUserConfigPath stackRoot = do\n (path, exists) <- tryDeprecatedPath\n (Just \"non-project configuration file\")\n doesFileExist\n (defaultUserConfigPath stackRoot)\n (defaultUserConfigPathDeprecated stackRoot)\n unless exists $ do\n ensureDir (parent path)\n liftIO $ S.writeFile (toFilePath path) defaultConfigYaml\n return path\n\n-- | Get a fake configuration file location, used when doing a \"no\n-- config\" run (the script command).\ngetFakeConfigPath\n :: (MonadIO m, MonadThrow m)\n => Path Abs Dir -- ^ stack root\n -> AbstractResolver\n -> m (Path Abs File)\ngetFakeConfigPath stackRoot ar = do\n asString <-\n case ar of\n ARResolver r -> pure $ T.unpack $ SHA256.toHexText $ SHA256.hashLazyBytes $ toLazyByteString $ getUtf8Builder $ display r\n _ -> throwM $ InvalidResolverForNoLocalConfig $ show ar\n -- This takeWhile is an ugly hack. We don't actually need this\n -- path for anything useful. But if we take the raw value for\n -- a custom snapshot, it will be unparseable in a PATH.\n -- Therefore, we add in this silly \"strip up to :\".\n -- Better would be to defer figuring out this value until\n -- after we have a fully loaded snapshot with a hash.\n asDir <- parseRelDir $ takeWhile (\/= ':') asString\n let full = stackRoot <\/> relDirScript <\/> asDir <\/> relFileConfigYaml\n ensureDir (parent full)\n return full\n\npackagesParser :: Parser [String]\npackagesParser = many (strOption (long \"package\" <> help \"Additional packages that must be installed\"))\n\ndefaultConfigYaml :: S.ByteString\ndefaultConfigYaml = S.intercalate \"\\n\"\n [ \"# This file contains default non-project-specific settings for 'stack', used\"\n , \"# in all projects. For more information about stack's configuration, see\"\n , \"# http:\/\/docs.haskellstack.org\/en\/stable\/yaml_configuration\/\"\n , \"\"\n , \"# The following parameters are used by \\\"stack new\\\" to automatically fill fields\"\n , \"# in the cabal config. We recommend uncommenting them and filling them out if\"\n , \"# you intend to use 'stack new'.\"\n , \"# See https:\/\/docs.haskellstack.org\/en\/stable\/yaml_configuration\/#templates\"\n , \"templates:\"\n , \" params:\"\n , \"# author-name:\"\n , \"# author-email:\"\n , \"# copyright:\"\n , \"# github-username:\"\n , \"\"\n , \"# The following parameter specifies stack's output styles; STYLES is a\"\n , \"# colon-delimited sequence of key=value, where 'key' is a style name and\"\n , \"# 'value' is a semicolon-delimited list of 'ANSI' SGR (Select Graphic\"\n , \"# Rendition) control codes (in decimal). Use \\\"stack ls stack-colors --basic\\\"\"\n , \"# to see the current sequence.\"\n , \"# stack-colors: STYLES\"\n , \"\"\n ]\n","avg_line_length":42.5628245067,"max_line_length":145,"alphanum_fraction":0.6502390944} {"size":968,"ext":"hs","lang":"Haskell","max_stars_count":54.0,"content":"{-# LANGUAGE OverloadedStrings #-}\n\nmodule Nihil.Syntax.Concrete.Parser.Pattern.Tuple where\n\nimport Nihil.Syntax.Common (Parser)\nimport Nihil.Syntax.Concrete.Core\nimport Nihil.Syntax.Concrete.Parser\nimport Nihil.Syntax.Concrete.Parser.Enclosed\nimport Nihil.Syntax.Concrete.Parser.Identifier\nimport Nihil.Syntax.Concrete.Debug\nimport {-# SOURCE #-} Nihil.Syntax.Concrete.Parser.Pattern\nimport Control.Applicative ((<|>))\nimport qualified Text.Megaparsec as MP\n\npTuple :: Parser Pattern\npTuple = debug \"p[Pattern]Tuple\" $ do\n MP.try unit <|> tuple\n where unit = PTuple [] <$ pParens (pure ())\n tuple = PTuple <$>\n pParens (lexeme pPattern `sepBy2` lexeme (pSymbol' \",\"))\n\n sepBy2 p sep = do\n (:) <$> (p <* sep) <*> (p `MP.sepBy1` sep)\n\n -- pParens ((:) <$> sameLineOrIndented pos pPattern\n -- <*> MP.some (sameLineOrIndented pos (pSymbol \",\") *> sameLineOrIndented pos pPattern))\n","avg_line_length":35.8518518519,"max_line_length":133,"alphanum_fraction":0.6570247934} {"size":1754,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeApplications #-}\nimport Control.Monad.Classes hiding (exec)\nimport Control.Monad.Classes.Log\nimport Control.Monad.Log (LoggingT, runLoggingT)\nimport Control.Monad.Trans.Reader (ReaderT(..))\nimport Control.Monad.Trans.State (State, execState)\n\nimport Test.Tasty\nimport Test.Tasty.HUnit\n\nmain :: IO ()\nmain = defaultMain $ testGroup \"tests\" [testCase \"should compile\" testcase\n ,testCase \"writer impl\" writecase]\n where testcase = assertEqual \"correct results\" opresults (exec op)\n writecase = assertEqual \"correct writes\" opresults (exec opw)\n opresults = [RRes \"bar\", LRes \"foo\"]\n\ndata Foo = Foo String\ndata Bar = Bar String\n\ndata Res = LRes String | RRes String\n deriving (Eq, Ord, Show)\n\nlogit :: (MonadReader a m, MonadLog a m) => (a -> a) -> m ()\nlogit f = ask >>= logMessage . f\n\n-- | This is the operation that will not compile under mtl\n-- | due to functional dependencies.\nop :: (MonadReader Foo m, MonadReader Bar m, MonadLog Foo m, MonadLog Bar m) => m ()\nop = logit (id @Foo) >> logit (id @Bar)\n\n-- | handler for Foo\nfoo :: MonadState [Res] m => Foo -> m ()\nfoo (Foo s) = modify $ \\r -> LRes s : r\n\n-- | Handler for Bar\nbar :: MonadState [Res] m => Bar -> m ()\nbar (Bar s) = modify $ \\r -> RRes s : r\n\nexec :: ReaderT Foo (ReaderT Bar (LoggingT Foo (LoggingT Bar (State [Res])))) () -> [Res]\nexec m = execState (runLoggingT (runLoggingT (runReaderT (runReaderT m (Foo \"foo\")) (Bar \"bar\")) foo) bar) []\n\nwriteit :: (MonadReader a m, MonadWriter a m) => (a -> a) -> m ()\nwriteit f = ask >>= tell . f\n\nopw :: (MonadReader Foo m, MonadReader Bar m, MonadWriter Foo m, MonadWriter Bar m) => m ()\nopw = writeit (id @Foo) >> writeit (id @Bar)\n","avg_line_length":35.7959183673,"max_line_length":109,"alphanum_fraction":0.6499429875} {"size":1165,"ext":"hs","lang":"Haskell","max_stars_count":2.0,"content":"import Control.Applicative ((<$>))\nimport qualified Data.ByteString.Lazy as L\nimport qualified Data.Foldable as F\nimport Data.Int (Int32, Int64)\nimport Data.Monoid ((<>))\nimport Data.Text (Text)\n\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Unboxed as U\n\nimport Data.Hadoop.SequenceFile\n\nmain :: IO ()\nmain = do\n printKeys \".\/tests\/long-double.seq\"\n recordCount \".\/tests\/text-int.seq\"\n\n-- | Print all the keys in a sequence file.\nprintKeys :: FilePath -> IO ()\nprintKeys path = do\n bs <- L.readFile path\n let records = failOnError (decode bs) :: Stream (RecordBlock Int64 Double)\n F.for_ records $ \\rb -> do\n print (U.take 10 $ rbKeys rb)\n F.for_ records $ \\rb -> do\n print (U.take 10 $ rbValues rb)\n\n-- | Count the number of records in a sequence file.\nrecordCount :: FilePath -> IO ()\nrecordCount path = do\n bs <- L.readFile path\n let records = decode bs :: Stream (RecordBlock Text Int32)\n putStrLn $ \"Records = \" <> show (F.sum $ rbCount <$> records)\n\nfailOnError :: Stream a -> Stream a\nfailOnError (Error err) = error err\nfailOnError x = x\n","avg_line_length":30.6578947368,"max_line_length":78,"alphanum_fraction":0.643776824} {"size":2549,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Daedalus.VM.FreeVars where\n\nimport Data.Set(Set)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport Daedalus.VM\n\ndefines :: Instr -> [BV]\ndefines instr =\n case instr of\n Say {} -> []\n Output {} -> []\n Notify {} -> []\n CallPrim v _ _ -> [v]\n Spawn v _ -> [v]\n NoteFail _ -> []\n Free {} -> []\n Let v _ -> [v]\n\ndefineSet :: Instr -> Set BV\ndefineSet = Set.fromList . defines\n\nfreeVars :: FreeVars t => t -> [VMVar]\nfreeVars t = freeVars' t []\n\nfreeVarSet :: FreeVars t => t -> Set VMVar\nfreeVarSet = Set.fromList . freeVars\n\n\n\nclass FreeVars t where\n -- | We return a list rather than a set so that we can notice\n -- multiple uses of the same variable\n freeVars' :: t -> [VMVar] -> [VMVar]\n\ninstance FreeVars t => FreeVars [t] where\n freeVars' xs = foldr (\\x rest -> freeVars' x . rest) id xs\n\ninstance FreeVars t => FreeVars (Set t) where\n freeVars' = freeVars' . Set.toList\n\ninstance (FreeVars a, FreeVars b) => FreeVars (a,b) where\n freeVars' (a,b) = freeVars' a . freeVars' b\n\ninstance FreeVars a => FreeVars (Maybe a) where\n freeVars' = maybe id freeVars'\n\ninstance FreeVars E where\n freeVars' expr =\n case expr of\n EUnit -> id\n ENum {} -> id\n EBool {} -> id\n EMapEmpty {} -> id\n ENothing {} -> id\n\n EBlockArg ba -> (ArgVar ba :)\n EVar bv -> (LocalVar bv :)\n\ninstance FreeVars JumpPoint where\n freeVars' (JumpPoint _ es) = freeVars' es\n\ninstance FreeVars JumpWithFree where\n freeVars' jf = freeVars' (freeFirst jf, jumpTarget jf)\n\ninstance FreeVars JumpChoice where\n freeVars' (JumpCase opts) = freeVars' (Map.elems opts)\n\ninstance FreeVars VMVar where\n freeVars' = (:)\n\ninstance FreeVars CInstr where\n freeVars' cinstr =\n case cinstr of\n Jump l -> freeVars' l\n JumpIf e ls -> freeVars' (e, ls)\n Yield -> id\n ReturnNo -> id\n ReturnYes e i -> freeVars' (e,i)\n Call _ _ no yes es -> freeVars' (es,(no,yes))\n CallPure _ l es -> freeVars' (l,es)\n TailCall _ _ es -> freeVars' es\n ReturnPure e -> freeVars' e\n\n\ninstance FreeVars Instr where\n freeVars' instr =\n case instr of\n Say {} -> id\n Output e -> freeVars' e\n Notify e -> freeVars' e\n CallPrim _ _ es -> freeVars' es\n Spawn _ l -> freeVars' l\n NoteFail e -> freeVars' e\n Free xs -> freeVars' xs\n Let _ e -> freeVars' e\n\n","avg_line_length":25.7474747475,"max_line_length":63,"alphanum_fraction":0.575127501} {"size":1304,"ext":"hs","lang":"Haskell","max_stars_count":142.0,"content":"module Yesod.Auth.OAuth2.GitHubStudents\n ( oauth2GitHubStudents\n , pluginName\n ) where\n\nimport Prelude\n\nimport qualified Data.Text as T\nimport Yesod.Auth.OAuth2.Prelude\n\nnewtype User = User Int\n\ninstance FromJSON User where\n parseJSON = withObject \"User\" $ \\o -> User <$> o .: \"id\"\n\npluginName :: Text\npluginName = \"github-students\"\n\ndefaultScopes :: [Text]\ndefaultScopes = [\"user:email\"]\n\noauth2GitHubStudents :: YesodAuth m => Text -> Text -> AuthPlugin m\noauth2GitHubStudents clientId clientSecret =\n authOAuth2 pluginName oauth2 $ \\manager token -> do\n (User userId, userResponse) <- authGetProfile\n pluginName\n manager\n token\n \"https:\/\/api.github.com\/user\"\n\n pure Creds\n { credsPlugin = pluginName\n , credsIdent = T.pack $ show userId\n , credsExtra = setExtra token userResponse\n }\n where\n oauth2 = OAuth2\n { oauthClientId = clientId\n , oauthClientSecret = Just clientSecret\n , oauthOAuthorizeEndpoint =\n \"https:\/\/github.com\/login\/oauth\/authorize\"\n `withQuery` [scopeParam \",\" defaultScopes]\n , oauthAccessTokenEndpoint =\n \"https:\/\/github.com\/login\/oauth\/access_token\"\n , oauthCallback = Nothing\n }\n","avg_line_length":27.7446808511,"max_line_length":67,"alphanum_fraction":0.6326687117} {"size":1682,"ext":"hs","lang":"Haskell","max_stars_count":941.0,"content":"{-# LANGUAGE Unsafe #-}\n{-# LANGUAGE CPP, NoImplicitPrelude #-}\n\n-----------------------------------------------------------------------------\n-- |\n-- Module : System.IO.Unsafe\n-- Copyright : (c) The University of Glasgow 2001\n-- License : BSD-style (see the file libraries\/base\/LICENSE)\n-- \n-- Maintainer : libraries@haskell.org\n-- Stability : provisional\n-- Portability : portable\n--\n-- \\\"Unsafe\\\" IO operations.\n--\n-----------------------------------------------------------------------------\n\nmodule System.IO.Unsafe (\n -- * Unsafe 'System.IO.IO' operations\n unsafePerformIO, -- :: IO a -> a\n unsafeDupablePerformIO, -- :: IO a -> a\n unsafeInterleaveIO, -- :: IO a -> IO a\n unsafeFixIO,\n ) where\n\n#ifdef __GLASGOW_HASKELL__\nimport GHC.Base\nimport GHC.IO\nimport GHC.IORef\nimport GHC.Exception\nimport Control.Exception\n#endif\n\n#ifdef __HUGS__\nimport Hugs.IOExts (unsafePerformIO, unsafeInterleaveIO)\nunsafeDupablePerformIO = unsafePerformIO\n#endif\n\n#ifdef __NHC__\nimport NHC.Internal (unsafePerformIO, unsafeInterleaveIO)\nunsafeDupablePerformIO = unsafePerformIO\n#endif\n\n-- | A slightly faster version of `System.IO.fixIO` that may not be\n-- safe to use with multiple threads. The unsafety arises when used\n-- like this:\n--\n-- > unsafeFixIO $ \\r ->\n-- > forkIO (print r)\n-- > return (...)\n--\n-- In this case, the child thread will receive a @NonTermination@\n-- exception instead of waiting for the value of @r@ to be computed.\n--\nunsafeFixIO :: (a -> IO a) -> IO a\nunsafeFixIO k = do\n ref <- newIORef (throw NonTermination)\n ans <- unsafeDupableInterleaveIO (readIORef ref)\n result <- k ans\n writeIORef ref result\n return result\n","avg_line_length":27.1290322581,"max_line_length":77,"alphanum_fraction":0.62960761} {"size":1429,"ext":"hs","lang":"Haskell","max_stars_count":133.0,"content":"\r\nmodule DoorMaker where\r\nimport Rumpus\r\n\r\ntileW = 2\r\ntileH = 0.1\r\n\r\nstart :: Start\r\nstart = do\r\n setPlayerPosition 0\r\n sceneNames <- listScenes\r\n\r\n let sceneNamesWithNewScene = map Just sceneNames ++ [Nothing]\r\n numItems = fromIntegral $ length sceneNamesWithNewScene\r\n tileColors = cycle [0,1,1,0]\r\n forM_ (zip3 [0..] tileColors sceneNamesWithNewScene) $ \\(i, t, mSceneName) -> do\r\n let hue = fromIntegral i \/ numItems\r\n zI = i `div` 2\r\n xI = i `mod` 2\r\n x = fromIntegral xI * 2 - tileW\/2\r\n z = -fromIntegral zI * 2 + tileW\/2\r\n r = if xI == 0 then pi\/2 else -pi\/2\r\n platShift = if xI == 0 then -1 else 1\r\n tileColor = if t == 0 then 1 else 0.15\r\n spawnChild $ do\r\n myBody ==> Animated\r\n myBodyFlags ==> [Teleportable]\r\n myShape ==> Cube\r\n myPose ==> position (V3 x (-tileH \/ 2) z)\r\n mySize ==> V3 tileW tileH tileW\r\n myColor ==> tileColor\r\n spawnChild $ do\r\n myBody ==> Animated\r\n myStartCodeFile ==> (\"Door.hs\", \"start\")\r\n myPose ==> positionRotation\r\n (V3 (x+platShift) 1 z)\r\n (axisAngle (V3 0 1 0) r)\r\n setState (mSceneName, hue::Float)\r\n\r\n\r\n","avg_line_length":34.8536585366,"max_line_length":85,"alphanum_fraction":0.4744576627} {"size":2906,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"module IHP.IDE.PortConfig\n( PortConfig (..)\n, defaultAppPort\n, findAvailablePortConfig\n)\nwhere\n\nimport ClassyPrelude\nimport qualified Network.Socket as Socket\nimport qualified UnliftIO.Exception as Exception\nimport Foreign.C.Error (Errno (..), eCONNREFUSED)\nimport GHC.IO.Exception (IOException(..))\nimport IHP.FrameworkConfig (defaultPort)\n\n-- | Port configuration used for starting the different app services\ndata PortConfig = PortConfig\n { appPort :: !Socket.PortNumber\n , toolServerPort :: !Socket.PortNumber\n , liveReloadNotificationPort :: !Socket.PortNumber\n } deriving (Show, Eq)\n\ndefaultAppPort :: Socket.PortNumber\ndefaultAppPort = fromIntegral defaultPort\n\nallPorts :: PortConfig -> [Socket.PortNumber]\nallPorts PortConfig { .. } = [appPort, toolServerPort, liveReloadNotificationPort]\n\ninstance Enum PortConfig where\n fromEnum PortConfig { .. } = fromIntegral $ toInteger (appPort - defaultAppPort)\n toEnum i = PortConfig { .. }\n where\n port = fromIntegral i\n appPort = port + defaultAppPort\n toolServerPort = port + defaultAppPort + 1\n liveReloadNotificationPort = port + defaultAppPort + 2\n\n-- | Returns True when the given port looks to be free.\n-- Used to e.g. detect which port the dev server should use.\nisPortAvailable :: Socket.PortNumber -> IO Bool\nisPortAvailable port = do\n let address = Socket.SockAddrInet port (Socket.tupleToHostAddress (127, 0, 0, 1))\n Exception.bracket (Socket.socket Socket.AF_INET Socket.Stream 6) Socket.close' $ \\socket -> do\n res <- Exception.try (Socket.connect socket address)\n case res of\n Left e -> if (Errno <$> ioe_errno e) == Just eCONNREFUSED\n then pure True\n else throwIO e\n Right _ -> pure False\n\n-- | Returns True when all ports in port config are available.\n-- \n-- Example:\n--\n-- >>> let portConfig = PortConfig { appPort = 8000, toolServerPort = 8001, liveReloadNotificationPort = 8002 }\n-- >>> isPortConfigAvailable portConfig\n-- True\nisPortConfigAvailable :: PortConfig -> IO Bool\nisPortConfigAvailable portConfig = do\n available <- mapM isPortAvailable (allPorts portConfig)\n pure (and available)\n\n-- | Returns a port config where all ports are available\n--\n-- When e.g. port 8000, 8001 and 80002 are not used:\n--\n-- >>> portConfig <- findAvailablePortConfig\n-- PortConfig { appPort = 8000, toolServerPort = 8001, liveReloadNotificationPort = 8002 }\nfindAvailablePortConfig :: IO PortConfig\nfindAvailablePortConfig = do\n let portConfigs :: [PortConfig] = take 100 (map toEnum [0..])\n go portConfigs\n where\n go (portConfig : rest) = do\n available <- isPortConfigAvailable portConfig\n if available\n then pure portConfig\n else go rest\n go [] = error \"findAvailablePortConfig: No port configuration found\"\n","avg_line_length":36.7848101266,"max_line_length":111,"alphanum_fraction":0.69339298} {"size":1022,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"import System.Random (randomRIO)\nimport Control.Monad\n\npick :: [a] -> IO a\npick xs = randomRIO (0, length xs - 1) >>= return . (xs !!)\n\nfirstPart :: [[Char]]\nfirstPart = [\"lazy\", \"stupid\", \"insecure\", \"idiotic\", \"slimy\", \"slutty\", \"smelly\", \"pompous\", \"communist\", \"dicknose\", \"pie-eating\", \"racist\", \"elitist\", \"trashy\", \"drug-loving\", \"butterface\", \"tone deaf\", \"ugly\", \"creepy\"]\n\nsecondPart :: [[Char]]\nsecondPart = [\"douche\", \"ass\", \"turd\", \"rectum\", \"butt\", \"cock\",\"shit\",\"crotch\",\"bitch\",\"prick\",\"slut\",\"taint\",\"fuck\",\"dick\",\"boner\",\"shart\",\"nut\",\"sphincter\"]\n\nthirdPart :: [[Char]]\nthirdPart = [\"pilot\",\"canoe\",\"captain\",\"pirate\",\"hammer\",\"knob\",\"box\",\"jockey\",\"nazi\",\"waffle\",\"goblin\",\"blossum\",\"biscuit\",\"clown\",\"socket\",\"monster\",\"hound\",\"dragon\",\"balloon\"]\n\nmakeInsult :: IO [Char]\nmakeInsult = do\n fp <- pick firstPart\n sp <- pick secondPart\n tp <- pick thirdPart\n return $ fp ++ \" \" ++ sp ++ \" \" ++ tp\n\nmain = do\n insult <- makeInsult\n putStrLn $ \"You are a \" ++ insult ++ \"!\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","avg_line_length":25.55,"max_line_length":223,"alphanum_fraction":0.595890411} {"size":63,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"let val = 600851475143\n\nn_primes :: Int -> [Int]\nn_primes n = \n","avg_line_length":12.6,"max_line_length":24,"alphanum_fraction":0.6507936508} {"size":5225,"ext":"hs","lang":"Haskell","max_stars_count":191.0,"content":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Certificate\n ( arbitraryX509\n , arbitraryX509WithKey\n , arbitraryX509WithKeyAndUsage\n , arbitraryDN\n , arbitraryKeyUsage\n , simpleCertificate\n , simpleX509\n , toPubKeyEC\n , toPrivKeyEC\n ) where\n\nimport Control.Applicative\nimport Test.Tasty.QuickCheck\nimport Data.ASN1.OID\nimport Data.X509\nimport Data.Hourglass\nimport Crypto.Number.Serialize (i2ospOf_)\nimport qualified Crypto.PubKey.ECC.ECDSA as ECDSA\nimport qualified Crypto.PubKey.ECC.Types as ECC\nimport qualified Data.ByteString as B\n\nimport PubKey\n\narbitraryDN :: Gen DistinguishedName\narbitraryDN = return $ DistinguishedName []\n\ninstance Arbitrary Date where\n arbitrary = do\n y <- choose (1971, 2035)\n m <- elements [ January .. December]\n d <- choose (1, 30)\n return $ normalizeDate $ Date y m d\n\nnormalizeDate :: Date -> Date\nnormalizeDate d = timeConvert (timeConvert d :: Elapsed)\n\ninstance Arbitrary TimeOfDay where\n arbitrary = do\n h <- choose (0, 23)\n mi <- choose (0, 59)\n se <- choose (0, 59)\n nsec <- return 0\n return $ TimeOfDay (Hours h) (Minutes mi) (Seconds se) nsec\n\ninstance Arbitrary DateTime where\n arbitrary = DateTime <$> arbitrary <*> arbitrary\n\nmaxSerial :: Integer\nmaxSerial = 16777216\n\narbitraryCertificate :: [ExtKeyUsageFlag] -> PubKey -> Gen Certificate\narbitraryCertificate usageFlags pubKey = do\n serial <- choose (0,maxSerial)\n subjectdn <- arbitraryDN\n validity <- (,) <$> arbitrary <*> arbitrary\n let sigalg = getSignatureALG pubKey\n return $ Certificate\n { certVersion = 3\n , certSerial = serial\n , certSignatureAlg = sigalg\n , certIssuerDN = issuerdn\n , certSubjectDN = subjectdn\n , certValidity = validity\n , certPubKey = pubKey\n , certExtensions = Extensions $ Just\n [ extensionEncode True $ ExtKeyUsage usageFlags\n ]\n }\n where issuerdn = DistinguishedName [(getObjectID DnCommonName, \"Root CA\")]\n\nsimpleCertificate :: PubKey -> Certificate\nsimpleCertificate pubKey =\n Certificate\n { certVersion = 3\n , certSerial = 0\n , certSignatureAlg = getSignatureALG pubKey\n , certIssuerDN = simpleDN\n , certSubjectDN = simpleDN\n , certValidity = (time1, time2)\n , certPubKey = pubKey\n , certExtensions = Extensions $ Just\n [ extensionEncode True $ ExtKeyUsage [KeyUsage_digitalSignature,KeyUsage_keyEncipherment]\n ]\n }\n where time1 = DateTime (Date 1999 January 1) (TimeOfDay 0 0 0 0)\n time2 = DateTime (Date 2049 January 1) (TimeOfDay 0 0 0 0)\n simpleDN = DistinguishedName []\n\nsimpleX509 :: PubKey -> SignedCertificate\nsimpleX509 pubKey =\n let cert = simpleCertificate pubKey\n sig = replicate 40 1\n sigalg = getSignatureALG pubKey\n (signedExact, ()) = objectToSignedExact (\\_ -> (B.pack sig,sigalg,())) cert\n in signedExact\n\narbitraryX509WithKey :: (PubKey, t) -> Gen SignedCertificate\narbitraryX509WithKey = arbitraryX509WithKeyAndUsage knownKeyUsage\n\narbitraryX509WithKeyAndUsage :: [ExtKeyUsageFlag] -> (PubKey, t) -> Gen SignedCertificate\narbitraryX509WithKeyAndUsage usageFlags (pubKey, _) = do\n cert <- arbitraryCertificate usageFlags pubKey\n sig <- resize 40 $ listOf1 arbitrary\n let sigalg = getSignatureALG pubKey\n let (signedExact, ()) = objectToSignedExact (\\(!(_)) -> (B.pack sig,sigalg,())) cert\n return signedExact\n\narbitraryX509 :: Gen SignedCertificate\narbitraryX509 = do\n let (pubKey, privKey) = getGlobalRSAPair\n arbitraryX509WithKey (PubKeyRSA pubKey, PrivKeyRSA privKey)\n\narbitraryKeyUsage :: Gen [ExtKeyUsageFlag]\narbitraryKeyUsage = sublistOf knownKeyUsage\n\nknownKeyUsage :: [ExtKeyUsageFlag]\nknownKeyUsage = [ KeyUsage_digitalSignature\n , KeyUsage_keyEncipherment\n , KeyUsage_keyAgreement\n ]\n\ngetSignatureALG :: PubKey -> SignatureALG\ngetSignatureALG (PubKeyRSA _) = SignatureALG HashSHA1 PubKeyALG_RSA\ngetSignatureALG (PubKeyDSA _) = SignatureALG HashSHA1 PubKeyALG_DSA\ngetSignatureALG (PubKeyEC _) = SignatureALG HashSHA256 PubKeyALG_EC\ngetSignatureALG (PubKeyEd25519 _) = SignatureALG_IntrinsicHash PubKeyALG_Ed25519\ngetSignatureALG (PubKeyEd448 _) = SignatureALG_IntrinsicHash PubKeyALG_Ed448\ngetSignatureALG pubKey = error $ \"getSignatureALG: unsupported public key: \" ++ show pubKey\n\ntoPubKeyEC :: ECC.CurveName -> ECDSA.PublicKey -> PubKey\ntoPubKeyEC curveName key =\n let ECC.Point x y = ECDSA.public_q key\n pub = SerializedPoint bs\n bs = B.cons 4 (i2ospOf_ bytes x `B.append` i2ospOf_ bytes y)\n bits = ECC.curveSizeBits (ECC.getCurveByName curveName)\n bytes = (bits + 7) `div` 8\n in PubKeyEC (PubKeyEC_Named curveName pub)\n\ntoPrivKeyEC :: ECC.CurveName -> ECDSA.PrivateKey -> PrivKey\ntoPrivKeyEC curveName key =\n let priv = ECDSA.private_d key\n in PrivKeyEC (PrivKeyEC_Named curveName priv)\n","avg_line_length":35.5442176871,"max_line_length":105,"alphanum_fraction":0.6775119617} {"size":3023,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE TypeOperators #-}\n\n-- |\n-- Module : Codec.Scale.Generic\n-- Copyright : Alexander Krupenkin 2016\n-- License : Apache-2.0\n--\n-- Maintainer : mail@akru.me\n-- Stability : experimental\n-- Portability : unportable\n--\n-- This module defines generic codec instances for data structures (including tuples)\n-- and enums (tagged-unions in Rust).\n--\n\nmodule Codec.Scale.Generic () where\n\nimport Data.Serialize.Get (Get, getWord8)\nimport Data.Serialize.Put (PutM, putWord8)\nimport Data.Word (Word8)\nimport Generics.SOP (All, Compose, I (..), NP (..), NS (..),\n SOP (..), unSOP, unZ)\n\nimport Codec.Scale.Class (Decode (..), Encode (..), GDecode (..),\n GEncode (..))\n\n-- Enum has multiple sum types.\ninstance ( GEncode (NP f xs)\n , GEncode (NP f ys)\n , All (GEncode `Compose` NP f) xss\n ) => GEncode (SOP f (xs ': ys ': xss)) where\n gPut = go 0 . unSOP\n where\n go :: forall f as . All (GEncode `Compose` f) as => Word8 -> NS f as -> PutM ()\n go !acc (Z x) = putWord8 acc >> gPut x\n go !acc (S x) = go (acc + 1) x\n\n-- Structures has only one sum type.\ninstance GEncode (NP f xs) => GEncode (SOP f '[xs]) where\n gPut = gPut . unZ . unSOP\n\n-- Product serialization is just encode each field step by step.\ninstance (Encode a, GEncode (NP I as)) => GEncode (NP I (a ': as)) where\n gPut (I a :* as) = put a >> gPut as\n\n-- Finish when all fields handled.\ninstance GEncode (NP I '[]) where\n gPut _ = mempty\n\n-- | Enum parser definition.\n--\n-- The index of sum type to parse given as an argument.\nclass EnumParser xs where\n enumParser :: All (GDecode `Compose` NP f) xs => Word8 -> Get (NS (NP f) xs)\n\n-- Enumerate enum index, zero means that we reach the goal.\ninstance EnumParser as => EnumParser (a ': as) where\n enumParser !i | i > 0 = S <$> enumParser (i - 1)\n | otherwise = Z <$> gGet\n\n-- When index out of type scope raise the error.\ninstance EnumParser '[] where\n enumParser _ = fail \"wrong prefix during enum decoding\"\n\n-- Decode enum when multiple sum types.\ninstance ( GDecode (NP f xs)\n , GDecode (NP f ys)\n , All (GDecode `Compose` NP f) xss\n , EnumParser xss\n ) => GDecode (SOP f (xs ': ys ': xss)) where\n gGet = SOP <$> (enumParser =<< getWord8)\n\n-- Decode plain structure when only one sum type.\ninstance GDecode (NP f as) => GDecode (SOP f '[as]) where\n gGet = SOP . Z <$> gGet\n\n-- Decode each field in sequence.\ninstance (Decode a, GDecode (NP I as)) => GDecode (NP I (a ': as)) where\n gGet = (:*) <$> (I <$> get) <*> gGet\n\n-- Finish decoding when empty.\ninstance GDecode (NP I '[]) where\n gGet = return Nil\n","avg_line_length":33.5888888889,"max_line_length":87,"alphanum_fraction":0.5831955012} {"size":10782,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE PatternSynonyms #-}\n\n-- |\n-- Module : Jikka.RestrictedPython.Convert.ParseMain\n-- Description : analyze @main@ function into input formats. \/ @main@ \u95a2\u6570\u3092\u5206\u6790\u3057\u3066\u5165\u529b\u30d5\u30a9\u30fc\u30de\u30c3\u30c8\u3092\u5f97\u307e\u3059\u3002\n-- Copyright : (c) Kimiyuki Onaka, 2021\n-- License : Apache License 2.0\n-- Maintainer : kimiyuki95@gmail.com\n-- Stability : experimental\n-- Portability : portable\nmodule Jikka.RestrictedPython.Convert.ParseMain\n ( run,\n )\nwhere\n\nimport Control.Arrow\nimport Data.Maybe\nimport Jikka.Common.Alpha\nimport Jikka.Common.Error\nimport Jikka.Common.IOFormat\nimport Jikka.RestrictedPython.Format (formatExpr, formatTarget)\nimport Jikka.RestrictedPython.Language.Expr\nimport Jikka.RestrictedPython.Language.Util\n\ntype MainFunction = (Maybe Loc, [(VarName', Type)], Type, [Statement])\n\nsplitMain :: Program -> (Maybe MainFunction, Program)\nsplitMain = \\case\n [] -> (Nothing, [])\n ToplevelFunctionDef (WithLoc' loc (VarName (Just \"main\") Nothing)) args ret body : stmts -> (Just (loc, args, ret, body), stmts)\n stmt : stmts -> second (stmt :) $ splitMain stmts\n\ncheckMainType :: MonadError Error m => MainFunction -> m ()\ncheckMainType (loc, args, ret, _) = wrapAt' loc $ case args of\n _ : _ -> throwTypeError \"main function must not take arguments\"\n [] -> case ret of\n VarTy _ -> return ()\n NoneTy -> return ()\n _ -> throwTypeError \"main function must return None\"\n\npattern CallBuiltin b args <- WithLoc' _ (Call (WithLoc' _ (Constant (ConstBuiltin b))) args)\n\npattern CallMethod e a args <- WithLoc' _ (Call (WithLoc' _ (Attribute e a)) args)\n\npattern IntInput <-\n CallBuiltin (BuiltinInt _) [CallBuiltin BuiltinInput []]\n\npattern MapIntInputSplit <-\n CallBuiltin\n (BuiltinMap [_] _)\n [ WithLoc' _ (Constant (ConstBuiltin (BuiltinInt _))),\n CallMethod\n (CallBuiltin BuiltinInput [])\n (WithLoc' _ BuiltinSplit)\n []\n ]\n\npattern ListMapIntInputSplit <-\n CallBuiltin\n (BuiltinList _)\n [ CallBuiltin\n (BuiltinMap [_] _)\n [ WithLoc' _ (Constant (ConstBuiltin (BuiltinInt _))),\n CallMethod\n (CallBuiltin BuiltinInput [])\n (WithLoc' _ BuiltinSplit)\n []\n ]\n ]\n\npattern ListRange n <-\n CallBuiltin\n (BuiltinList _)\n [CallBuiltin BuiltinRange1 [WithLoc' _ (Name (WithLoc' _ n))]]\n\nparseAnnAssign :: (MonadAlpha m, MonadError Error m) => Target' -> Type -> Expr' -> [Statement] -> m (FormatTree, Maybe ([String], Either String [String]), [Statement])\nparseAnnAssign x _ e cont = do\n let subscriptTrg x = case value' x of\n NameTrg x -> return (formatVarName (value' x), [])\n SubscriptTrg x (WithLoc' _ (Name i)) -> second (++ [formatVarName (value' i)]) <$> subscriptTrg x\n _ -> throwSemanticErrorAt' (loc' x) $ \"name target or subscript target is expected, but got: \" ++ formatTarget x\n let subscriptTupleTrg x = case value' x of\n TupleTrg xs -> mapM subscriptTrg xs\n _ -> throwSemanticErrorAt' (loc' x) $ \"tuple target is expected, but got: \" ++ formatTarget x\n let nameTrg x = case value' x of\n NameTrg x -> return $ formatVarName (value' x)\n _ -> throwSemanticErrorAt' (loc' x) $ \"name target is expected, but got: \" ++ formatTarget x\n let nameOrTupleTrg x = case value' x of\n NameTrg x -> return . Left $ formatVarName (value' x)\n TupleTrg xs -> Right <$> mapM nameTrg xs\n _ -> throwSemanticErrorAt' (loc' x) $ \"name target or tuple target is expected, but got: \" ++ formatTarget x\n let nameExpr e = case value' e of\n Name x -> return $ formatVarName (value' x)\n _ -> throwSemanticErrorAt' (loc' e) $ \"variable is expected, but got: \" ++ formatExpr e\n case e of\n -- int(input())\n IntInput -> do\n (x, indices) <- subscriptTrg x\n return (Seq [packSubscriptedVar' x indices, Newline], Nothing, cont)\n -- map(int, input().split())\n MapIntInputSplit -> do\n outputs <- subscriptTupleTrg x\n return (Seq (map (uncurry packSubscriptedVar') outputs ++ [Newline]), Nothing, cont)\n -- list(map(int, input().split()))\n ListMapIntInputSplit -> do\n (x, indices) <- subscriptTrg x\n case cont of\n Assert (WithLoc' _ (Compare (CallBuiltin (BuiltinLen _) [WithLoc' _ (Name x')]) (CmpOp' Eq' _) n)) : cont | formatVarName (value' x') == x -> do\n i <- formatVarName . value' <$> genVarName'\n n <- nameExpr n\n return (Seq [Loop i (Var n) (Exp (At (packSubscriptedVar x indices) i)), Newline], Nothing, cont)\n _ -> throwSemanticErrorAt' (loc' e) \"after `xs = list(map(int, input().split()))', we need to write `assert len(xs) == n`\"\n -- list(range(n))\n ListRange n -> do\n let isListRange = \\case\n AnnAssign _ _ (ListRange n') | n' == n -> True\n _ -> False\n cont <- return $ dropWhile isListRange cont\n case cont of\n For _ (CallBuiltin BuiltinRange1 [WithLoc' _ (Name n')]) _ : _ | value' n' == n -> return (Seq [], Nothing, cont) -- TODO: add more strict checks\n _ -> throwSemanticErrorAt' (loc' e) \"after some repetition of `xs = list(range(n))', we need to write `for i in range(n):`\"\n -- solve(...)\n WithLoc' _ (Call (WithLoc' _ (Name (WithLoc' _ (VarName (Just \"solve\") Nothing)))) args) -> do\n inputs <- mapM nameExpr args\n output <- nameOrTupleTrg x\n return (Seq [], Just (inputs, output), cont)\n _ -> throwSemanticErrorAt' (loc' e) \"assignments in main function must be `x = int(input())', `x, y, z = map(int, input().split())', `xs = list(map(int, input().split()))', `xs = list(range(n))' or `x, y, z = solve(a, b, c)'\"\n\nparseFor :: MonadError Error m => ([Statement] -> m (FormatTree, Maybe ([String], Either String [String]), FormatTree)) -> Target' -> Expr' -> [Statement] -> m (FormatTree, FormatTree)\nparseFor go x e body = do\n x <- case value' x of\n NameTrg x -> return x\n _ -> throwSemanticErrorAt' (loc' x) $ \"for loops in main function must use `range' like `for i in range(n): ...'\" ++ formatTarget x\n n <- case e of\n CallBuiltin BuiltinRange1 [n] -> return n\n _ -> throwSemanticErrorAt' (loc' e) $ \"for loops in main function must use `range' like `for i in range(n): ...': \" ++ formatExpr e\n n <- case value' n of\n Name n -> return $ Right (n, 0)\n BinOp (WithLoc' _ (Name n)) Add (WithLoc' _ (Constant (ConstInt k))) -> return $ Right (n, k)\n BinOp (WithLoc' _ (Name n)) Sub (WithLoc' _ (Constant (ConstInt k))) -> return $ Right (n, - k)\n Call (WithLoc' _ (Constant (ConstBuiltin (BuiltinLen _)))) [WithLoc' _ (Name xs)] -> return $ Left xs\n _ -> throwSemanticErrorAt' (loc' n) $ \"for loops in main function must use `range(x)', `range(x + k)', `range(x - k)', `range(len(xs))`: \" ++ formatExpr n\n n <- return $ case n of\n Right (n, k) ->\n let n' = Var (formatVarName (value' n))\n in if k == 0 then n' else Plus n' k\n Left xs -> Len (Var (formatVarName (value' xs)))\n (input, solve, output) <- go body\n when (isJust solve) $ do\n throwSemanticError \"cannot call `solve(...)' in for loop\"\n let x' = formatVarName (value' x)\n return (Loop x' n input, Loop x' n output)\n\nparseExprStatement :: (MonadAlpha m, MonadError Error m) => Expr' -> m FormatTree\nparseExprStatement e = do\n let subscriptExpr e = case value' e of\n Name x -> return (formatVarName (value' x), [])\n Subscript e (WithLoc' _ (Name i)) -> second (++ [formatVarName (value' i)]) <$> subscriptExpr e\n _ -> throwSemanticErrorAt' (loc' e) $ \"subscripted variable is expected, but got: \" ++ formatExpr e\n let starredExpr e = do\n (e, starred) <- return $ case value' e of\n Starred e -> (e, True)\n _ -> (e, False)\n (x, indices) <- subscriptExpr e\n return (x, indices, starred)\n let pack (x, indices, starred)\n | not starred = return $ packSubscriptedVar' x indices\n | otherwise = do\n let xs = packSubscriptedVar x indices\n i <- formatVarName . value' <$> genVarName'\n return $ Loop i (Len xs) (packSubscriptedVar' x (indices ++ [i]))\n case e of\n CallBuiltin (BuiltinPrint _) args -> do\n outputs <- mapM starredExpr args\n outputs <- mapM pack outputs\n return $ Seq (outputs ++ [Newline])\n _ -> throwSemanticErrorAt' (loc' e) \"only `print(...)' is allowed for expr statements in main function\"\n\nparseMain :: (MonadAlpha m, MonadError Error m) => MainFunction -> m IOFormat\nparseMain (loc, _, _, body) = wrapAt' loc $ pack =<< go [] body\n where\n pack :: MonadError Error m => (FormatTree, Maybe ([String], Either String [String]), FormatTree) -> m IOFormat\n pack (_, Nothing, _) = throwSemanticError \"main function must call solve function\"\n pack (inputTree, Just (inputVariables, outputVariables), outputTree) =\n return $\n IOFormat\n { inputTree = inputTree,\n inputVariables = inputVariables,\n outputVariables = outputVariables,\n outputTree = outputTree\n }\n go :: (MonadAlpha m, MonadError Error m) => [(FormatTree, Maybe ([String], Either String [String]), FormatTree)] -> [Statement] -> m (FormatTree, Maybe ([String], Either String [String]), FormatTree)\n go formats = \\case\n Return _ : _ -> throwSemanticError \"return statement is not allowd in main function\"\n AugAssign _ _ _ : _ -> throwSemanticError \"augumented assignment statement is not allowd in main function\"\n AnnAssign x t e : cont -> do\n (inputs, solve, cont) <- parseAnnAssign x t e cont\n go (formats ++ [(inputs, solve, Seq [])]) cont\n For x e body : cont -> do\n (inputs, outputs) <- parseFor (go []) x e body\n go (formats ++ [(inputs, Nothing, outputs)]) cont\n If _ _ _ : _ -> throwSemanticError \"if statement is not allowd in main function\"\n Assert _ : _ -> throwSemanticError \"assert statement is allowd only after `xs = list(map(int, input().split()))` in main function\"\n Expr' e : cont -> do\n output <- parseExprStatement e\n go (formats ++ [(Seq [], Nothing, output)]) cont\n [] -> do\n let input = Seq (map (\\(x, _, _) -> x) formats)\n let outputs = Seq (map (\\(_, _, z) -> z) formats)\n solve <- case mapMaybe (\\(_, y, _) -> y) formats of\n [] -> return Nothing\n [solve] -> return $ Just solve\n _ -> throwSemanticError \"cannot call solve function twice\"\n return (input, solve, outputs)\n\nrun :: (MonadAlpha m, MonadError Error m) => Program -> m (Maybe IOFormat, Program)\nrun prog = wrapError' \"Jikka.RestrictedPython.Convert.ParseMain\" $ do\n (main, prog) <- return $ splitMain prog\n main <- forM main $ \\main -> do\n checkMainType main\n main <- parseMain main\n return $ normalizeIOFormat main\n return (main, prog)\n","avg_line_length":47.7079646018,"max_line_length":229,"alphanum_fraction":0.6278056019} {"size":9662,"ext":"hs","lang":"Haskell","max_stars_count":5.0,"content":"-- Hoff -- A gatekeeper for your commits\n-- Copyright 2016 Ruud van Asseldonk\n--\n-- Licensed under the Apache License, Version 2.0 (the \"License\");\n-- you may not use this file except in compliance with the License.\n-- A copy of the License has been included in the root of the repository.\n\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Project\n(\n BuildStatus (..),\n IntegrationStatus (..),\n ProjectInfo (..),\n ProjectState (..),\n PullRequest (..),\n PullRequestId (..),\n PullRequestStatus (..),\n approvedPullRequests,\n candidatePullRequests,\n classifyPullRequest,\n classifyPullRequests,\n deletePullRequest,\n emptyProjectState,\n existsPullRequest,\n getIntegrationCandidate,\n insertPullRequest,\n loadProjectState,\n lookupPullRequest,\n saveProjectState,\n setApproval,\n setBuildStatus,\n setIntegrationCandidate,\n setIntegrationStatus,\n updatePullRequest\n)\nwhere\n\nimport Data.Aeson\nimport Data.Aeson.Encode.Pretty (encodePretty)\nimport Data.ByteString (readFile)\nimport Data.ByteString.Lazy (writeFile)\nimport Data.IntMap.Strict (IntMap)\nimport Data.List (intersect)\nimport Data.Maybe (isJust)\nimport Data.Text (Text)\nimport GHC.Generics\nimport Git (Branch (..), Sha (..))\nimport Prelude hiding (readFile, writeFile)\nimport System.Directory (renameFile)\n\nimport qualified Data.IntMap.Strict as IntMap\n\n-- TODO: Move to Github module?\n-- A pull request is identified by its number.\ndata PullRequestId = PullRequestId Int deriving (Eq, Show, Generic)\n\ndata BuildStatus\n = BuildNotStarted\n | BuildPending\n | BuildSucceeded\n | BuildFailed\n deriving (Eq, Show, Generic)\n\n-- When attempting to integrated changes, there can be three states: no attempt\n-- has been made to integrate; integration (e.g. merge or rebase) was successful\n-- and the new commit has the given sha; and an attempt to integrate was made,\n-- but it resulted in merge conflicts.\ndata IntegrationStatus\n = NotIntegrated\n | Integrated Sha\n | Conflicted\n deriving (Eq, Show, Generic)\n\ndata PullRequestStatus\n = PrStatusAwaitingApproval -- New, awaiting review.\n | PrStatusApproved -- Approved, but not yet integrated or built.\n | PrStatusBuildPending -- Integrated, and build pending or in progress.\n | PrStatusIntegrated -- Integrated, build passed, merged into target branch.\n | PrStatusFailedConflict -- Failed to integrate due to merge conflict.\n | PrStatusFailedBuild -- Integrated, but the build failed.\n deriving (Eq)\n\ndata PullRequest = PullRequest\n {\n sha :: Sha,\n branch :: Branch,\n title :: Text,\n author :: Text,\n approvedBy :: Maybe Text,\n buildStatus :: BuildStatus,\n integrationStatus :: IntegrationStatus\n }\n deriving (Eq, Show, Generic)\n\ndata ProjectState = ProjectState\n {\n pullRequests :: IntMap PullRequest,\n integrationCandidate :: Maybe PullRequestId\n }\n deriving (Eq, Show, Generic)\n\n-- Static information about a project, which does not change while the program\n-- is running.\ndata ProjectInfo = ProjectInfo\n {\n owner :: Text,\n repository :: Text\n }\n deriving (Eq, Show)\n\n-- TODO: These default instances produce ugly json. Write a custom\n-- implementation. For now this will suffice.\ninstance FromJSON BuildStatus\ninstance FromJSON IntegrationStatus\ninstance FromJSON ProjectState\ninstance FromJSON PullRequest\ninstance FromJSON PullRequestId\n\ninstance ToJSON BuildStatus where toEncoding = genericToEncoding defaultOptions\ninstance ToJSON IntegrationStatus where toEncoding = genericToEncoding defaultOptions\ninstance ToJSON ProjectState where toEncoding = genericToEncoding defaultOptions\ninstance ToJSON PullRequest where toEncoding = genericToEncoding defaultOptions\ninstance ToJSON PullRequestId where toEncoding = genericToEncoding defaultOptions\n\n-- Reads and parses the state. Returns Nothing if parsing failed, but crashes if\n-- the file could not be read.\nloadProjectState :: FilePath -> IO (Maybe ProjectState)\nloadProjectState = fmap decodeStrict' . readFile\n\nsaveProjectState :: FilePath -> ProjectState -> IO ()\nsaveProjectState fname state = do\n -- First write the file entirely, afterwards atomically move the new file over\n -- the old one. This way, the state file is never incomplete if the\n -- application is killed or crashes during a write.\n writeFile (fname ++ \".new\") $ encodePretty state\n renameFile (fname ++ \".new\") fname\n\nemptyProjectState :: ProjectState\nemptyProjectState = ProjectState {\n pullRequests = IntMap.empty,\n integrationCandidate = Nothing\n}\n\n-- Inserts a new pull request into the project, with approval set to Nothing,\n-- build status to BuildNotStarted, and integration status to NotIntegrated.\ninsertPullRequest\n :: PullRequestId\n -> Branch\n -> Sha\n -> Text\n -> Text\n -> ProjectState\n -> ProjectState\ninsertPullRequest (PullRequestId n) prBranch prSha prTitle prAuthor state =\n let pullRequest = PullRequest {\n sha = prSha,\n branch = prBranch,\n title = prTitle,\n author = prAuthor,\n approvedBy = Nothing,\n buildStatus = BuildNotStarted,\n integrationStatus = NotIntegrated\n }\n in state { pullRequests = IntMap.insert n pullRequest $ pullRequests state }\n\n-- Removes the pull request detail from the project. This does not change the\n-- integration candidate, which can be equal to the deleted pull request.\ndeletePullRequest :: PullRequestId -> ProjectState -> ProjectState\ndeletePullRequest (PullRequestId n) state = state {\n pullRequests = IntMap.delete n $ pullRequests state\n}\n\n-- Returns whether the pull request is part of the set of open pull requests.\nexistsPullRequest :: PullRequestId -> ProjectState -> Bool\nexistsPullRequest (PullRequestId n) = IntMap.member n . pullRequests\n\nlookupPullRequest :: PullRequestId -> ProjectState -> Maybe PullRequest\nlookupPullRequest (PullRequestId n) = IntMap.lookup n . pullRequests\n\nupdatePullRequest :: PullRequestId -> (PullRequest -> PullRequest) -> ProjectState -> ProjectState\nupdatePullRequest (PullRequestId n) f state = state {\n pullRequests = IntMap.adjust f n $ pullRequests state\n}\n\n-- Marks the pull request as approved by somebody or nobody.\nsetApproval :: PullRequestId -> Maybe Text -> ProjectState -> ProjectState\nsetApproval pr newApprovedBy = updatePullRequest pr changeApproval\n where changeApproval pullRequest = pullRequest { approvedBy = newApprovedBy }\n\n-- Sets the build status for a pull request.\nsetBuildStatus :: PullRequestId -> BuildStatus -> ProjectState -> ProjectState\nsetBuildStatus pr newStatus = updatePullRequest pr changeBuildStatus\n where changeBuildStatus pullRequest = pullRequest { buildStatus = newStatus }\n\n-- Sets the integration status for a pull request.\nsetIntegrationStatus :: PullRequestId -> IntegrationStatus -> ProjectState -> ProjectState\nsetIntegrationStatus pr newStatus = updatePullRequest pr changeIntegrationStatus\n where changeIntegrationStatus pullRequest = pullRequest { integrationStatus = newStatus }\n\ngetIntegrationCandidate :: ProjectState -> Maybe (PullRequestId, PullRequest)\ngetIntegrationCandidate state = do\n pullRequestId <- integrationCandidate state\n candidate <- lookupPullRequest pullRequestId state\n return (pullRequestId, candidate)\n\nsetIntegrationCandidate :: Maybe PullRequestId -> ProjectState -> ProjectState\nsetIntegrationCandidate pr state = state {\n integrationCandidate = pr\n}\n\nclassifyPullRequest :: PullRequest -> PullRequestStatus\nclassifyPullRequest pr = case approvedBy pr of\n Nothing -> PrStatusAwaitingApproval\n Just _ -> case integrationStatus pr of\n NotIntegrated -> PrStatusApproved\n Conflicted -> PrStatusFailedConflict\n Integrated _ -> case buildStatus pr of\n BuildNotStarted -> PrStatusApproved\n BuildPending -> PrStatusBuildPending\n BuildSucceeded -> PrStatusIntegrated\n BuildFailed -> PrStatusFailedBuild\n\n-- Classify every pull request into one status. Orders pull requests by id in\n-- ascending order.\nclassifyPullRequests :: ProjectState -> [(PullRequestId, PullRequestStatus)]\nclassifyPullRequests state = IntMap.foldMapWithKey aux (pullRequests state)\n where\n aux i pr = [(PullRequestId i, classifyPullRequest pr)]\n\n-- Returns the ids of the pull requests that satisfy the predicate, in ascending\n-- order.\nfilterPullRequestsBy :: (PullRequest -> Bool) -> ProjectState -> [PullRequestId]\nfilterPullRequestsBy p =\n fmap PullRequestId . IntMap.keys . IntMap.filter p . pullRequests\n\n-- Returns the pull requests that have been approved, in order of ascending id.\napprovedPullRequests :: ProjectState -> [PullRequestId]\napprovedPullRequests = filterPullRequestsBy $ isJust . approvedBy\n\n-- Returns the pull requests that have not been integrated yet, in order of\n-- ascending id.\nunintegratedPullRequests :: ProjectState -> [PullRequestId]\nunintegratedPullRequests = filterPullRequestsBy $ (== NotIntegrated) . integrationStatus\n\n-- Returns the pull requests that have not been built yet, in order of ascending\n-- id.\nunbuiltPullRequests :: ProjectState -> [PullRequestId]\nunbuiltPullRequests = filterPullRequestsBy $ (== BuildNotStarted) . buildStatus\n\n-- Returns the pull requests that have been approved, but for which integration\n-- and building has not yet been attempted.\ncandidatePullRequests :: ProjectState -> [PullRequestId]\ncandidatePullRequests state =\n let\n approved = approvedPullRequests state\n unintegrated = unintegratedPullRequests state\n unbuilt = unbuiltPullRequests state\n in\n approved `intersect` unintegrated `intersect` unbuilt\n","avg_line_length":36.8778625954,"max_line_length":98,"alphanum_fraction":0.7522252122} {"size":1906,"ext":"hs","lang":"Haskell","max_stars_count":16.0,"content":"-----------------------------------------------------------------------------\n-- | License : GPL\n-- \n-- Maintainer : helium@cs.uu.nl\n-- Stability : provisional\n-- Portability : portable\n-----------------------------------------------------------------------------\n\nmodule Top.Solver.PartitionCombinator where\n\nimport Top.Types\nimport Top.Solver\nimport Top.Ordering.Tree\nimport qualified Data.Map as M\n\ntype Chunks constraint = [Chunk constraint]\ntype Chunk constraint = (ChunkID, Tree constraint)\ntype ChunkID = Int\n\nsolveChunkConstraints ::\n (M.Map Int (Scheme Predicates) -> constraint -> constraint) -> -- function to update the type scheme variables\n ConstraintSolver constraint info -> -- constraint solver to solve the constraints in a chunk\n (Tree constraint -> [constraint]) -> -- function to flatten the constraint tree\n Chunks constraint -> ConstraintSolver constraint info\n \nsolveChunkConstraints update (ConstraintSolver f) flattening chunks =\n ConstraintSolver (\\os _ -> \n let rec options [] = (emptyResult (uniqueCounter options), noLogEntries)\n rec options ((_, tree) : rest) =\n let constraintList = flattening tree\n (result, entries)\n | null constraintList = \n (emptyResult (uniqueCounter options), noLogEntries)\n | otherwise = \n f options constraintList\n newOption = options { uniqueCounter = uniqueFromResult result }\n schemeMap = typeschemesFromResult result\n newRest = [ (chunkID, fmap (update schemeMap) t) | (chunkID, t) <- rest ]\n (resultRec, entriesRec) = rec newOption newRest\n in (result `combineResults` resultRec, entries `mappend` entriesRec)\n in rec os chunks)","avg_line_length":46.487804878,"max_line_length":126,"alphanum_fraction":0.5687303253} {"size":1036,"ext":"hs","lang":"Haskell","max_stars_count":88.0,"content":"{-# LANGUAGE OverloadedStrings, DeriveDataTypeable, DeriveGeneric #-}\nmodule Ros.Test_srvs.EmptyResponse where\nimport qualified Prelude as P\nimport Prelude ((.), (+), (*))\nimport qualified Data.Typeable as T\nimport Control.Applicative\nimport Ros.Internal.RosBinary\nimport Ros.Internal.Msg.MsgInfo\nimport qualified GHC.Generics as G\nimport qualified Data.Default.Generics as D\nimport Ros.Internal.Msg.SrvInfo\nimport Foreign.Storable (Storable(..))\n\ndata EmptyResponse = EmptyResponse deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)\n\ninstance RosBinary EmptyResponse where\n put _ = pure ()\n get = pure EmptyResponse\n\ninstance Storable EmptyResponse where\n sizeOf _ = 1\n alignment _ = 1\n peek _ = pure EmptyResponse\n poke _ _ = pure ()\n\ninstance MsgInfo EmptyResponse where\n sourceMD5 _ = \"d41d8cd98f00b204e9800998ecf8427e\"\n msgTypeName _ = \"test_srvs\/EmptyResponse\"\n\ninstance D.Default EmptyResponse\n\ninstance SrvInfo EmptyResponse where\n srvMD5 _ = \"d41d8cd98f00b204e9800998ecf8427e\"\n srvTypeName _ = \"test_srvs\/Empty\"\n\n","avg_line_length":28.7777777778,"max_line_length":88,"alphanum_fraction":0.7818532819} {"size":7794,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE CPP #-}\n\n{-|\n\nThis implements a common DSL for regular expression replacement text. This\nis represented with the 'Replace' data type. It also implements the\n'IsString' interface, so if 'OverloadedStrings' is on, you can use a raw\nstring to build the replacement.\n\n-}\n\n\nmodule Data.Text.ICU.Replace\n (\n -- * @OverloadedStrings@ Syntax\n -- $doc\n\n -- * Types\n Replace\n\n -- * High-level interface\n , replace\n , replace'\n , replaceAll\n , replaceAll'\n\n -- * Low-level interface\n , rgroup\n , rtext\n , rstring\n , rfn\n , rtfn\n , rbuilder\n ) where\n\n\nimport Control.Applicative\nimport Data.Attoparsec.Text\nimport Data.Foldable\n#if __GLASGOW_HASKELL__ >= 804\nimport Data.Semigroup (Semigroup)\n#endif\nimport Data.Monoid\nimport Data.String\nimport qualified Data.Text as T\nimport Data.Text.ICU\nimport qualified Data.Text.ICU as ICU\nimport qualified Data.Text.Lazy as TL\nimport qualified Data.Text.Lazy.Builder as TB\nimport Data.Tuple\nimport Prelude hiding (span)\n\n\n\n-- | A 'Replace' instance is a function from a regular expression match to\n-- a 'Data.Text.Lazy.Builder.Builder'. This naturally forms a 'Monoid', so\n-- they're easy to combine.\n--\n-- 'Replace' also implements 'IsString', so raw strings can be used to\n-- construct them.\nnewtype Replace = Replace { unReplace :: Match -> TB.Builder } deriving\n ( Monoid\n#if __GLASGOW_HASKELL__ >= 804\n , Semigroup\n#endif\n )\n\ninstance IsString Replace where\n fromString = parseReplace . T.pack\n\ntype MatchState = (Match, Int)\n\n-- | Execute a regular expression on a 'Data.Text.Text' and replace the\n-- first match.\nreplace :: Regex -- ^ The regular expression to match.\n -> Replace -- ^ The specification to replace it with.\n -> T.Text -- ^ The text to operate on.\n -> T.Text -- ^ The text with the first match replaced.\nreplace re r t = maybe t (replace' r) $ ICU.find re t\n\n-- | Replace one regular expression match with the 'Replace'.\nreplace' :: Replace -- ^ The specification to replace it with.\n -> Match -- ^ The match to replace.\n -> T.Text -- ^ The text with the match replaced.\nreplace' r m =\n finish (Last (Just (m, 0))) . (p <>) $ unReplace r m\n where\n p = foldMap TB.fromText $ prefix 0 m\n\n-- | Execute a regular expression on a 'Data.Text.Text' and replace all\n-- matches.\nreplaceAll :: Regex -- ^ The regular expression to match.\n -> Replace -- ^ The specification to replace it with.\n -> T.Text -- ^ The text to operate on.\n -> T.Text -- ^ The text with all matches replaced.\nreplaceAll re r t = case ICU.findAll re t of\n [] -> t\n ms -> replaceAll' r ms\n\n-- | Replace all regular expression matches with the 'Replace'.\nreplaceAll' :: Replace -- ^ The specification to replace it with.\n -> [Match] -- ^ The matches to replace.\n -> T.Text -- ^ The text with all matches replaced.\nreplaceAll' r =\n uncurry finish . foldl' step (Last Nothing, mempty)\n where\n step :: (Last MatchState, TB.Builder)\n -> Match\n -> (Last MatchState, TB.Builder)\n step (Last prev, buffer) m =\n let s = span m\n g = fold $ group 0 m\n offset = (+ T.length s) . (+ T.length g) $ maybe 0 snd prev\n in ( Last $ Just (m, offset)\n , buffer <> TB.fromText s <> unReplace r m\n )\n\n-- | This handles the last match by including not only the match's prefix\n-- and the replacement text, but also the suffix trailing the match.\nfinish :: Last MatchState -- ^ The state of the match to get the prefix\n -- and suffix from.\n -> TB.Builder -- ^ The current replacement's output.\n -> T.Text\nfinish m b = TL.toStrict\n . TB.toLazyText\n . mappend b\n . TB.fromText\n . fold\n $ suffix 0\n . fst\n =<< getLast m\n\n-- | Create a 'Replace' that inserts a regular expression group.\nrgroup :: Int -- ^ The number of the group in a regular expression.\n -> Replace -- ^ The 'Replace' that inserts a group's match.\nrgroup g = Replace $ fold . fmap TB.fromText . group g\n\n-- | Create a 'Replace' that inserts static 'Data.Text.Text'.\nrtext :: T.Text -- ^ The static 'Data.Text.Text' to insert.\n -> Replace -- ^ The 'Replace' that inserts the static 'Data.Text.Text'.\nrtext = rbuilder . TB.fromText\n\n-- | Create a 'Replace' that inserts a static 'String'.\nrstring :: String -- ^ The static 'String' to insert.\n -> Replace -- ^ The 'Replace' that inserts the static 'String'.\nrstring = rbuilder . TB.fromString\n\n-- | Create a 'Replace' from a function that transforms a 'Match' into\n-- a 'Data.Text.Lazy.Builder.Builder'.\nrfn :: (Match -> TB.Builder) -- ^ The function that creates the replacement text.\n -> Replace -- ^ The 'Replace' based off that function.\nrfn = Replace\n\n-- | Create a 'Replace' From a function that transforms a 'Match' into\n-- a 'Data.Text.Text'.\nrtfn :: (Match -> T.Text) -- ^ The function that creates the replacement text.\n -> Replace -- ^ The 'Replace' based off that function.\nrtfn = Replace . (TB.fromText .)\n\n-- | Create a 'Replace' that inserts a static 'Data.Text.Lazy.Builder.Builder'.\nrbuilder :: TB.Builder -- ^ The 'Data.Text.Lazy.Builder.Builder' to insert.\n -> Replace -- ^ The 'Replace' that inserts the static\n -- 'Data.Text.Lazy.Builder.Builder'.\nrbuilder = Replace . const\n\n-- | This parses a 'Data.Text.Text' into a 'Replace' structure.\n--\n-- Generally, input text is considered to be static.\n--\n-- However, groups from the regular expression's matches can be insert\n-- using @$1@ (to insert the first group) or @${7}@ (to insert the seventh\n-- group).\n--\n-- Dollar signs can be included in the output by doubling them (@$$@).\nparseReplace :: T.Text -> Replace\nparseReplace t = either (const $ rtext t) id\n $ parseOnly (replacement <* endOfInput) t\n\n-- A replacement.\nreplacement :: Parser Replace\nreplacement = mconcat <$> many (dollarGroup <|> raw)\n\n-- A @\\$\\d+@ or @\\$\\{\\d+\\}@ group. This could also be an escaped dollar\n-- sign (@$$@).\ndollarGroup :: Parser Replace\ndollarGroup = char '$' *> (grp <|> escaped)\n where curly = char '{' *> decimal <* char '}'\n grp = rgroup <$> (decimal <|> curly)\n escaped = rtext . T.singleton <$> char '$'\n\n-- A raw input string. It must contain no dollar signs (@$@).\nraw :: Parser Replace\nraw = rtext <$> takeWhile1 (\/= '$')\n\n\n-- $doc\n--\n-- The syntax used with 'OverloadedStrings' is meant to be similar to that\n-- used in other regular expression libraries in other programming\n-- languages.\n--\n-- Generally, input text is considered to be static.\n--\n-- >>> replaceAll \"a\" \"b\" \"aaa\"\n-- \"bbb\"\n-- >>> replaceAll \"ab\" \"ba\" \"cdababcd\"\n-- \"cdbabacd\"\n--\n-- However, groups from the regular expression's matches can be insert\n-- using @$1@ (to insert the first group) or @${7}@ (to insert the seventh\n-- group).\n--\n-- >>> replaceAll \"(.*), (.*)\" \"$2 $1\" \"Beeblebrox, Zaphod\"\n-- \"Zaphod Beeblebrox\"\n-- >>> replaceAll \"4(\\\\d)\" \"${1}4\" \"7458\"\n-- \"7548\"\n--\n-- Dollar signs can be included in the output by doubling them (@$$@).\n--\n-- >>> replaceAll \"(\\\\d+\\\\.\\\\d+)\" \"$$$1\" \"9.99\"\n-- \"$9.99\"\n","avg_line_length":34.64,"max_line_length":84,"alphanum_fraction":0.5963561714} {"size":6723,"ext":"hs","lang":"Haskell","max_stars_count":1.0,"content":"{-# LANGUAGE CPP #-}\nmodule Stackage.Util where\n\nimport qualified Codec.Archive.Tar as Tar\nimport qualified Codec.Archive.Tar.Entry as TarEntry\nimport Control.Monad (guard, when)\nimport Data.Char (isSpace, toUpper)\nimport Data.List (stripPrefix)\nimport qualified Data.Map as Map\nimport Data.Maybe (mapMaybe)\nimport qualified Data.Set as Set\nimport Data.Version (showVersion)\nimport Distribution.License (License (..))\nimport qualified Distribution.Package as P\nimport qualified Distribution.PackageDescription as PD\nimport Distribution.Text (display, simpleParse)\nimport Distribution.Version (thisVersion)\nimport Stackage.Types\nimport System.Directory (doesDirectoryExist,\n removeDirectoryRecursive)\nimport System.Directory (getAppUserDataDirectory\n ,canonicalizePath,\n createDirectoryIfMissing, doesFileExist)\nimport System.Environment (getEnvironment)\nimport System.FilePath ((<\/>), (<.>))\n\n-- | Allow only packages with permissive licenses.\nallowPermissive :: [String] -- ^ list of explicitly allowed packages\n -> PD.GenericPackageDescription\n -> Either String ()\nallowPermissive allowed gpd\n | P.pkgName (PD.package $ PD.packageDescription gpd) `elem` map PackageName allowed = Right ()\n | otherwise =\n case PD.license $ PD.packageDescription gpd of\n BSD3 -> Right ()\n MIT -> Right ()\n PublicDomain -> Right ()\n l -> Left $ \"Non-permissive license: \" ++ display l\n\nidentsToRanges :: Set PackageIdentifier -> Map PackageName (VersionRange, Maintainer)\nidentsToRanges =\n Map.unions . map go . Set.toList\n where\n go (PackageIdentifier package version) = Map.singleton package (thisVersion version, Maintainer \"Haskell Platform\")\n\npackageVersionString :: (PackageName, Version) -> String\npackageVersionString (PackageName p, v) = concat [p, \"-\", showVersion v]\n\nrm_r :: FilePath -> IO ()\nrm_r fp = do\n exists <- doesDirectoryExist fp\n when exists $ removeDirectoryRecursive fp\n\ngetCabalRoot :: IO FilePath\ngetCabalRoot = getAppUserDataDirectory \"cabal\"\n\n-- | Name of the 00-index.tar downloaded from Hackage.\ngetTarballName :: IO FilePath\ngetTarballName = do\n c <- getCabalRoot\n configLines <- fmap lines $ readFile (c <\/> \"config\")\n case mapMaybe getRemoteCache configLines of\n [x] -> return $ x <\/> \"hackage.haskell.org\" <\/> \"00-index.tar\"\n [] -> error $ \"No remote-repo-cache found in Cabal config file\"\n _ -> error $ \"Multiple remote-repo-cache entries found in Cabal config file\"\n where\n getRemoteCache s = do\n (\"remote-repo-cache\", ':':v) <- Just $ break (== ':') s\n Just $ reverse $ dropWhile isSpace $ reverse $ dropWhile isSpace v\n\nstableRepoName, extraRepoName :: String\nstableRepoName = \"stackage\"\nextraRepoName = \"stackage-extra\"\n\n-- | Locations for the stackage and stackage-extra tarballs\ngetStackageTarballNames :: IO (FilePath, FilePath)\ngetStackageTarballNames = do\n c <- getCabalRoot\n let f x = c <\/> \"packages\" <\/> x <\/> \"00-index.tar\"\n return (f stableRepoName, f extraRepoName)\n\ngetPackageVersion :: Tar.Entry -> Maybe (PackageName, Version)\ngetPackageVersion e = do\n let (package', s1) = break (== '\/') fp\n package = PackageName package'\n s2 <- stripPrefix \"\/\" s1\n let (version', s3) = break (== '\/') s2\n version <- simpleParse version'\n s4 <- stripPrefix \"\/\" s3\n guard $ s4 == package' ++ \".cabal\"\n Just (package, version)\n where\n fp = TarEntry.fromTarPathToPosixPath $ TarEntry.entryTarPath e\n\n-- | If a package cannot be parsed or is not found, the default value for\n-- whether it has a test suite. We default to @True@ since, worst case\n-- scenario, this just means a little extra time trying to run a suite that's\n-- not there. Defaulting to @False@ would result in silent failures.\ndefaultHasTestSuites :: Bool\ndefaultHasTestSuites = True\n\npackageDir, libDir, binDir, dataDir, docDir :: BuildSettings -> FilePath\npackageDir = (<\/> \"package-db\") . sandboxRoot\nlibDir = (<\/> \"lib\") . sandboxRoot\nbinDir = (<\/> \"bin\") . sandboxRoot\ndataDir = (<\/> \"share\") . sandboxRoot\ndocDir x = sandboxRoot x <\/> \"share\" <\/> \"doc\" <\/> \"$pkgid\"\n\naddCabalArgsOnlyGlobal :: [String] -> [String]\naddCabalArgsOnlyGlobal rest\n = \"--package-db=clear\"\n : \"--package-db=global\"\n : rest\n\naddCabalArgs :: BuildSettings -> BuildStage -> [String] -> [String]\naddCabalArgs settings bs rest\n = addCabalArgsOnlyGlobal\n $ (\"--package-db=\" ++ packageDir settings ++ toolsSuffix)\n : (\"--libdir=\" ++ libDir settings ++ toolsSuffix)\n : (\"--bindir=\" ++ binDir settings)\n : (\"--datadir=\" ++ dataDir settings)\n : (\"--docdir=\" ++ docDir settings ++ toolsSuffix)\n : extraArgs settings bs ++ rest\n where\n toolsSuffix =\n case bs of\n BSTools -> \"-tools\"\n _ -> \"\"\n\n-- | Modified environment that adds our sandboxed bin folder to PATH.\ngetModifiedEnv :: BuildSettings -> IO [(String, String)]\ngetModifiedEnv settings = do\n fmap (map $ fixEnv $ binDir settings) getEnvironment\n where\n fixEnv :: FilePath -> (String, String) -> (String, String)\n fixEnv bin (p, x)\n -- Thank you Windows having case-insensitive environment variables...\n | map toUpper p == \"PATH\" = (p, bin ++ pathSep : x)\n | otherwise = (p, x)\n\n -- | Separate for the PATH environment variable\n pathSep :: Char\n#ifdef mingw32_HOST_OS\n pathSep = ';'\n#else\n pathSep = ':'\n#endif\n\n-- | Minor fixes, such as making paths absolute.\n--\n-- Note: creates the sandbox root in the process.\nfixBuildSettings :: BuildSettings -> IO BuildSettings\nfixBuildSettings settings' = do\n let root' = sandboxRoot settings'\n createDirectoryIfMissing True root'\n root <- canonicalizePath root'\n return settings' { sandboxRoot = root }\n\n-- | Check if a tarball exists in the tarball directory and, if so, use that\n-- instead of the given name.\nreplaceTarball :: FilePath -- ^ tarball directory\n -> String\n -> IO String\nreplaceTarball tarballdir pkgname = do\n exists <- doesFileExist fp\n if exists\n then canonicalizePath fp\n else return pkgname\n where\n fp = tarballdir <\/> pkgname <.> \"tar.gz\"\n","avg_line_length":39.3157894737,"max_line_length":119,"alphanum_fraction":0.6268035103} {"size":9861,"ext":"hs","lang":"Haskell","max_stars_count":280.0,"content":"{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving,\n ScopedTypeVariables, TypeFamilies, BangPatterns, CPP,\n RecordWildCards #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Distribution.Server.BlobStorage\n-- Copyright : Duncan Coutts <duncan@haskell.org>\n--\n-- Maintainer : Duncan Coutts <duncan@haskell.org>\n-- Stability : alpha\n-- Portability : portable\n--\n-- Persistent storage for blobs of data.\n--\nmodule Distribution.Server.Framework.BlobStorage (\n BlobStorage,\n BlobId,\n blobMd5,\n readBlobId,\n blobETag,\n blobMd5Digest,\n open,\n add,\n addWith,\n consumeFile,\n consumeFileWith,\n fetch,\n filepath,\n BlobId_v0,\n BlobStores(..),\n find,\n ) where\n\nimport Distribution.Server.Prelude\n\nimport Distribution.Server.Features.Security.MD5\nimport Distribution.Server.Framework.MemSize\nimport Distribution.Server.Framework.Instances ()\nimport Distribution.Server.Framework.CacheControl (ETag(..))\nimport Distribution.Server.Util.ReadDigest\n\nimport qualified Data.ByteString as BSS\nimport qualified Data.ByteString.Lazy as BSL\nimport Data.Serialize\nimport System.FilePath ((<\/>))\nimport Control.Exception (handle, throwIO, evaluate, bracket)\nimport Data.SafeCopy\nimport System.Directory\nimport System.IO\nimport Data.Aeson\nimport System.Posix.Files as Posix (createLink)\n\n-- For fsync\nimport System.Posix.Types (Fd(..))\n#ifndef mingw32_HOST_OS\nimport Foreign.C.Error (throwErrnoIfMinus1_)\nimport Foreign.C.Types (CInt(..))\nimport System.Posix.IO (\n handleToFd\n , openFd\n , closeFd\n , defaultFileFlags\n , OpenMode(ReadOnly)\n )\n#endif\n\n-- | An id for a blob. The content of the blob is stable.\n--\nnewtype BlobId = BlobId MD5Digest\n deriving (Eq, Ord, Show, Typeable, MemSize)\n\ninstance ToJSON BlobId where\n toJSON = toJSON . blobMd5\n\nblobMd5Digest :: BlobId -> MD5Digest\nblobMd5Digest (BlobId digest) = digest\n\nblobMd5 :: BlobId -> String\nblobMd5 (BlobId digest) = show digest\n\nblobETag :: BlobId -> ETag\nblobETag = ETag . blobMd5\n\nreadBlobId :: String -> Either String BlobId\nreadBlobId = either Left (Right . BlobId) . readDigest\n\ninstance SafeCopy BlobId where\n version = 2\n kind = extension\n putCopy (BlobId x) = contain $ put x\n getCopy = contain $ BlobId <$> get\n\n-- | A persistent blob storage area. Blobs can be added and retrieved but\n-- not removed or modified.\n--\nnewtype BlobStorage = BlobStorage FilePath -- ^ location of the store\n\n-- | Which directory do we store a blob ID in?\ndirectory :: BlobStorage -> BlobId -> FilePath\ndirectory (BlobStorage storeDir) (BlobId hash) = storeDir <\/> take 2 str\n where str = show hash\n\nfilepath :: BlobStorage -> BlobId -> FilePath\nfilepath store bid@(BlobId hash) = directory store bid <\/> str\n where str = show hash\n\nincomingDir :: BlobStorage -> FilePath\nincomingDir (BlobStorage storeDir) = storeDir <\/> \"incoming\"\n\n-- | Add a blob into the store. The result is a 'BlobId' that can be used\n-- later with 'fetch' to retrieve the blob content.\n--\n-- * This operation is idempotent. That is, adding the same content again\n-- gives the same 'BlobId'.\n--\nadd :: BlobStorage -> BSL.ByteString -> IO BlobId\nadd store content =\n withIncoming store content $ \\_ blobId -> return (blobId, True)\n\n-- | Like 'add' but we get another chance to make another pass over the input\n-- 'ByteString'.\n--\n-- What happens is that we stream the input into a temp file in an incoming\n-- area. Then we can make a second pass over it to do some validation or\n-- processing. If the validator decides to reject then we rollback and the\n-- blob is not entered into the store. If it accepts then the blob is added\n-- and the 'BlobId' is returned.\n--\naddWith :: BlobStorage -> BSL.ByteString\n -> (BSL.ByteString -> IO (Either error result))\n -> IO (Either error (result, BlobId))\naddWith store content check =\n withIncoming store content $ \\file blobId -> do\n content' <- BSL.readFile file\n result <- check content'\n case result of\n Left err -> return (Left err, False)\n Right res -> return (Right (res, blobId), True)\n\n-- | Similar to 'add' but by \/moving\/ a file into the blob store. So this\n-- is a destructive operation. Since it works by renaming the file, the input\n-- file must live in the same file system as the blob store.\n--\nconsumeFile :: BlobStorage -> FilePath -> IO BlobId\nconsumeFile store filePath =\n withIncomingFile store filePath $ \\_ blobId -> return (blobId, True)\n\nconsumeFileWith :: BlobStorage -> FilePath\n -> (BSL.ByteString -> IO (Either error result))\n -> IO (Either error (result, BlobId))\nconsumeFileWith store filePath check =\n withIncomingFile store filePath $ \\file blobId -> do\n content' <- BSL.readFile file\n result <- check content'\n case result of\n Left err -> return (Left err, False)\n Right res -> return (Right (res, blobId), True)\n\nhBlobId :: Handle -> IO BlobId\nhBlobId hnd = evaluate . BlobId . md5 =<< BSL.hGetContents hnd\n\nfileBlobId :: FilePath -> IO BlobId\nfileBlobId file = bracket (openBinaryFile file ReadMode) hClose hBlobId\n\nwithIncoming :: BlobStorage -> BSL.ByteString\n -> (FilePath -> BlobId -> IO (a, Bool))\n -> IO a\nwithIncoming store content action = do\n (file, hnd) <- openBinaryTempFile (incomingDir store) \"new\"\n handleExceptions file hnd $ do\n blobId <- BlobId <$> hPutGetMd5 hnd content\n fd <- handleToFd hnd -- This closes the handle, see docs for handleToFd\n fsync fd\n closeFd fd\n withIncoming' store file blobId action\n where\n hPutGetMd5 hnd = go . lazyMD5\n where\n go (BsChunk bs cs) = BSS.hPut hnd bs >> go cs\n go (BsEndMd5 md5val) = return md5val\n\n handleExceptions tmpFile tmpHandle =\n handle $ \\err -> do\n hClose tmpHandle\n removeFile tmpFile\n throwIO (err :: IOError)\n\nwithIncomingFile :: BlobStorage\n -> FilePath\n -> (FilePath -> BlobId -> IO (a, Bool))\n -> IO a\nwithIncomingFile store file action =\n do blobId <- fileBlobId file\n withIncoming' store file blobId action\n\nwithIncoming' :: BlobStorage -> FilePath -> BlobId -> (FilePath -> BlobId -> IO (a, Bool)) -> IO a\nwithIncoming' store file blobId action = do\n (res, commit) <- action file blobId\n if commit\n then do\n#ifndef mingw32_HOST_OS\n fd <- openFd (directory store blobId) ReadOnly Nothing defaultFileFlags\n#endif\n -- TODO: if the target already exists then there is no need to overwrite\n -- it since it will have the same content. Checking and then renaming\n -- would give a race condition but that's ok since they have the same\n -- content.\n renameFile file (filepath store blobId)\n#ifndef mingw32_HOST_OS\n -- fsync the directory so that the new directory entry becomes 'durable'\n fsync fd\n closeFd fd\n#endif\n else removeFile file\n return res\n\n\n-- | Retrieve a blob from the store given its 'BlobId'.\n--\n-- * The content corresponding to a given 'BlobId' never changes.\n--\n-- * The blob must exist in the store or it is an error.\n--\nfetch :: BlobStorage -> BlobId -> IO BSL.ByteString\nfetch store blobid = BSL.readFile (filepath store blobid)\n\n-- | Opens an existing or new blob storage area.\n--\nopen :: FilePath -> IO BlobStorage\nopen storeDir = do\n let store = BlobStorage storeDir\n chars = ['0' .. '9'] ++ ['a' .. 'f']\n subdirs = incomingDir store\n : [storeDir <\/> [x, y] | x <- chars, y <- chars]\n\n exists <- doesDirectoryExist storeDir\n if not exists\n then do\n createDirectory storeDir\n forM_ subdirs createDirectory\n else\n forM_ subdirs $ \\d -> do\n subdirExists <- doesDirectoryExist d\n unless subdirExists $\n fail $ \"Store directory \\\"\"\n ++ storeDir\n ++ \"\\\" exists but \\\"\"\n ++ d\n ++ \"\\\" does not\"\n return store\n\n-- | Binding to the C @fsync@ function\nfsync :: Fd -> IO ()\nfsync (Fd fd) =\n#ifdef mingw32_HOST_OS\n return ()\n#else\n throwErrnoIfMinus1_ \"fsync\" $ c_fsync fd\n\nforeign import ccall \"fsync\" c_fsync :: CInt -> IO CInt\n#endif\n\n--------------------------\n-- Old SafeCopy versions\n--\n\nnewtype BlobId_v0 = BlobId_v0 MD5Digest deriving Serialize\n\ninstance SafeCopy BlobId_v0 where\n getCopy = contain get\n putCopy = contain . put\n\ninstance Migrate BlobId where\n type MigrateFrom BlobId = BlobId_v0\n migrate (BlobId_v0 digest) = BlobId digest\n\n{-------------------------------------------------------------------------------\n Multiple blob stores\n-------------------------------------------------------------------------------}\n\ndata BlobStores = BlobStores {\n -- | Main blob store\n blobStoresMain :: BlobStorage\n\n -- | Auxiliary blob stores\n --\n -- These are used only when adding new blobs into the main blob store\n , blobStoresAux :: [BlobStorage]\n }\n\n-- | Check if a blob with the specified ID exists in any of the stores, and if\n-- exists, hardlink it to the main store.\nfind :: BlobStores -> BlobId -> IO Bool\nfind BlobStores{..} blobId = do\n existsInMainStore <- doesFileExist $ filepath blobStoresMain blobId\n if existsInMainStore\n then return True\n else checkAux blobStoresAux\n where\n checkAux :: [BlobStorage] -> IO Bool\n checkAux [] = return False\n checkAux (store:stores) = do\n existsHere <- doesFileExist pathHere\n if existsHere\n then createLink pathHere pathMain >> return True\n else checkAux stores\n where\n pathHere = filepath store blobId\n pathMain = filepath blobStoresMain blobId\n","avg_line_length":31.8096774194,"max_line_length":98,"alphanum_fraction":0.6486157591} {"size":148,"ext":"hs","lang":"Haskell","max_stars_count":2497.0,"content":"module ShouldSucceed where\n\n-- From a bug report by Sven Panne.\n\nfoo = bar\n where bar = \\_ -> (truncate boing, truncate boing)\n boing = 0\n","avg_line_length":18.5,"max_line_length":53,"alphanum_fraction":0.6486486486} {"size":5989,"ext":"hs","lang":"Haskell","max_stars_count":594.0,"content":"{-# OPTIONS_HADDOCK hide #-}\n-- | Terminal control and text helper functions. Internal QuickCheck module.\nmodule Test.QuickCheck.Text\n ( Str(..)\n , ranges\n\n , number\n , short\n , showErr\n , oneLine\n , isOneLine\n , bold\n , ljust, rjust, centre, lpercent, rpercent, lpercentage, rpercentage\n , drawTable, Cell(..)\n , paragraphs\n\n , newTerminal\n , withStdioTerminal\n , withHandleTerminal\n , withNullTerminal\n , terminalOutput\n , handle\n , Terminal\n , putTemp\n , putPart\n , putLine\n )\n where\n\n--------------------------------------------------------------------------\n-- imports\n\nimport System.IO\n ( hFlush\n , hPutStr\n , stdout\n , stderr\n , Handle\n , BufferMode (..)\n , hGetBuffering\n , hSetBuffering\n , hIsTerminalDevice\n )\n\nimport Data.IORef\nimport Data.List (intersperse, transpose)\nimport Text.Printf\nimport Test.QuickCheck.Exception\n\n--------------------------------------------------------------------------\n-- literal string\n\nnewtype Str = MkStr String\n\ninstance Show Str where\n show (MkStr s) = s\n\nranges :: (Show a, Integral a) => a -> a -> Str\nranges k n = MkStr (show n' ++ \" -- \" ++ show (n'+k-1))\n where\n n' = k * (n `div` k)\n\n--------------------------------------------------------------------------\n-- formatting\n\nnumber :: Int -> String -> String\nnumber n s = show n ++ \" \" ++ s ++ if n == 1 then \"\" else \"s\"\n\nshort :: Int -> String -> String\nshort n s\n | n < k = take (n-2-i) s ++ \"..\" ++ drop (k-i) s\n | otherwise = s\n where\n k = length s\n i = if n >= 5 then 3 else 0\n\nshowErr :: Show a => a -> String\nshowErr = unwords . words . show\n\noneLine :: String -> String\noneLine = unwords . words\n\nisOneLine :: String -> Bool\nisOneLine xs = '\\n' `notElem` xs\n\nljust n xs = xs ++ replicate (n - length xs) ' '\nrjust n xs = replicate (n - length xs) ' ' ++ xs\ncentre n xs =\n ljust n $\n replicate ((n - length xs) `div` 2) ' ' ++ xs\n\nlpercent, rpercent :: (Integral a, Integral b) => a -> b -> String\nlpercent n k =\n lpercentage (fromIntegral n \/ fromIntegral k) k\n\nrpercent n k =\n rpercentage (fromIntegral n \/ fromIntegral k) k\n\nlpercentage, rpercentage :: Integral a => Double -> a -> String\nlpercentage p n =\n printf \"%.*f\" places (100*p) ++ \"%\"\n where\n -- Show no decimal places if k <= 100,\n -- one decimal place if k <= 1000,\n -- two decimal places if k <= 10000, and so on.\n places :: Integer\n places =\n ceiling (logBase 10 (fromIntegral n) - 2 :: Double) `max` 0\n\nrpercentage p n = padding ++ lpercentage p n\n where\n padding = if p < 0.1 then \" \" else \"\"\n\ndata Cell = LJust String | RJust String | Centred String deriving Show\n\ntext :: Cell -> String\ntext (LJust xs) = xs\ntext (RJust xs) = xs\ntext (Centred xs) = xs\n\n-- Flatten a table into a list of rows\nflattenRows :: [[Cell]] -> [String]\nflattenRows rows = map row rows\n where\n cols = transpose rows\n widths = map (maximum . map (length . text)) cols\n\n row cells = concat (intersperse \" \" (zipWith cell widths cells))\n cell n (LJust xs) = ljust n xs\n cell n (RJust xs) = rjust n xs\n cell n (Centred xs) = centre n xs\n\n-- Draw a table given a header and contents\ndrawTable :: [String] -> [[Cell]] -> [String]\ndrawTable headers table =\n [line] ++\n [border '|' ' ' header | header <- headers] ++\n [line | not (null headers) && not (null rows)] ++\n [border '|' ' ' row | row <- rows] ++\n [line]\n where\n rows = flattenRows table\n\n headerwidth = maximum (0:map length headers)\n bodywidth = maximum (0:map length rows)\n width = max headerwidth bodywidth\n\n line = border '+' '-' $ replicate width '-'\n border x y xs = [x, y] ++ centre width xs ++ [y, x]\n\nparagraphs :: [[String]] -> [String]\nparagraphs = concat . intersperse [\"\"] . filter (not . null)\n\nbold :: String -> String\n-- not portable:\n--bold s = \"\\ESC[1m\" ++ s ++ \"\\ESC[0m\"\nbold s = s -- for now\n\n--------------------------------------------------------------------------\n-- putting strings\n\ndata Terminal\n = MkTerminal (IORef ShowS) (IORef Int) (String -> IO ()) (String -> IO ())\n\nnewTerminal :: (String -> IO ()) -> (String -> IO ()) -> IO Terminal\nnewTerminal out err =\n do res <- newIORef (showString \"\")\n tmp <- newIORef 0\n return (MkTerminal res tmp out err)\n\nwithBuffering :: IO a -> IO a\nwithBuffering action = do\n mode <- hGetBuffering stderr\n -- By default stderr is unbuffered. This is very slow, hence we explicitly\n -- enable line buffering.\n hSetBuffering stderr LineBuffering\n action `finally` hSetBuffering stderr mode\n\nwithHandleTerminal :: Handle -> Maybe Handle -> (Terminal -> IO a) -> IO a\nwithHandleTerminal outh merrh action = do\n let\n err =\n case merrh of\n Nothing -> const (return ())\n Just errh -> handle errh\n newTerminal (handle outh) err >>= action\n\nwithStdioTerminal :: (Terminal -> IO a) -> IO a\nwithStdioTerminal action = do\n isatty <- hIsTerminalDevice stderr\n if isatty then\n withBuffering (withHandleTerminal stdout (Just stderr) action)\n else\n withBuffering (withHandleTerminal stdout Nothing action)\n\nwithNullTerminal :: (Terminal -> IO a) -> IO a\nwithNullTerminal action =\n newTerminal (const (return ())) (const (return ())) >>= action\n\nterminalOutput :: Terminal -> IO String\nterminalOutput (MkTerminal res _ _ _) = fmap ($ \"\") (readIORef res)\n\nhandle :: Handle -> String -> IO ()\nhandle h s = do\n hPutStr h s\n hFlush h\n\nputPart, putTemp, putLine :: Terminal -> String -> IO ()\nputPart tm@(MkTerminal res _ out _) s =\n do putTemp tm \"\"\n force s\n out s\n modifyIORef res (. showString s)\n where\n force :: [a] -> IO ()\n force = evaluate . seqList\n\n seqList :: [a] -> ()\n seqList [] = ()\n seqList (x:xs) = x `seq` seqList xs\n\nputLine tm s = putPart tm (s ++ \"\\n\")\n\nputTemp tm@(MkTerminal _ tmp _ err) s =\n do n <- readIORef tmp\n err $\n replicate n ' ' ++ replicate n '\\b' ++\n s ++ [ '\\b' | _ <- s ]\n writeIORef tmp (length s)\n\n--------------------------------------------------------------------------\n-- the end.\n","avg_line_length":25.7038626609,"max_line_length":77,"alphanum_fraction":0.5857405243} {"size":14095,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE UndecidableInstances #-}\n\n#if HAVE_QUANTIFIED_CONSTRAINTS\n{-# LANGUAGE QuantifiedConstraints #-}\n#endif\n\n{-# OPTIONS_GHC -Wall #-}\n\nmodule Test.QuickCheck.Classes.Common\n ( Laws(..)\n , foldMapA \n , myForAllShrink \n \n -- only used for higher-kinded types\n , Apply(..)\n#if HAVE_BINARY_LAWS\n , Apply2(..)\n#endif\n , Triple(..)\n , ChooseFirst(..)\n , ChooseSecond(..)\n , LastNothing(..)\n , Bottom(..)\n , LinearEquation(..)\n#if HAVE_UNARY_LAWS\n , LinearEquationM(..)\n#endif\n , QuadraticEquation(..)\n , LinearEquationTwo(..)\n#if HAVE_UNARY_LAWS\n , nestedEq1\n , propNestedEq1\n , toSpecialApplicative\n#endif\n , flipPair\n#if HAVE_UNARY_LAWS\n , apTrans\n#endif\n , func1\n , func2\n , func3\n#if HAVE_UNARY_LAWS\n , func4\n#endif\n , func5\n , func6\n , reverseTriple\n , runLinearEquation\n#if HAVE_UNARY_LAWS\n , runLinearEquationM\n#endif\n , runQuadraticEquation\n , runLinearEquationTwo\n ) where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Foldable\nimport Data.Traversable\nimport Data.Monoid\n#if defined(HAVE_UNARY_LAWS)\nimport Data.Functor.Classes (Eq1(..),Show1(..),eq1,showsPrec1)\nimport Data.Functor.Compose\n#endif\n#if defined(HAVE_BINARY_LAWS)\nimport Data.Functor.Classes (Eq2(..),Show2(..),eq2,showsPrec2)\n#endif\nimport Data.Semigroup (Semigroup)\nimport Test.QuickCheck hiding ((.&.))\nimport Test.QuickCheck.Property (Property(..))\n\nimport qualified Control.Monad.Trans.Writer.Lazy as WL\nimport qualified Data.List as L\nimport qualified Data.Monoid as MND\nimport qualified Data.Semigroup as SG\nimport qualified Data.Set as S\n\n-- | A set of laws associated with a typeclass.\ndata Laws = Laws\n { lawsTypeclass :: String\n -- ^ Name of the typeclass whose laws are tested\n , lawsProperties :: [(String,Property)]\n -- ^ Pairs of law name and property\n }\n\nmyForAllShrink :: (Arbitrary a, Show b, Eq b)\n => Bool -- Should we show the RHS. It's better not to show it\n -- if the RHS is equal to the input.\n -> (a -> Bool) -- is the value a valid input\n -> (a -> [String])\n -> String\n -> (a -> b)\n -> String\n -> (a -> b)\n -> Property\nmyForAllShrink displayRhs isValid showInputs name1 calc1 name2 calc2 =\n#if MIN_VERSION_QuickCheck(2,9,0)\n again $\n#endif\n MkProperty $\n arbitrary >>= \\x ->\n unProperty $\n shrinking shrink x $ \\x' ->\n let b1 = calc1 x'\n b2 = calc2 x'\n sb1 = show b1\n sb2 = show b2\n description = \" Description: \" ++ name1 ++ \" = \" ++ name2\n err = description ++ \"\\n\" ++ unlines (map (\" \" ++) (showInputs x')) ++ \" \" ++ name1 ++ \" = \" ++ sb1 ++ (if displayRhs then \"\\n \" ++ name2 ++ \" = \" ++ sb2 else \"\")\n in isValid x' ==> counterexample err (b1 == b2)\n\n#if HAVE_UNARY_LAWS\n-- the Functor constraint is needed for transformers-0.4\n#if HAVE_QUANTIFIED_CONSTRAINTS\nnestedEq1 :: (forall x. Eq x => Eq (f x), forall x. Eq x => Eq (g x), Eq a) => f (g a) -> f (g a) -> Bool\nnestedEq1 = (==)\n#else\nnestedEq1 :: (Eq1 f, Eq1 g, Eq a, Functor f) => f (g a) -> f (g a) -> Bool\nnestedEq1 x y = eq1 (Compose x) (Compose y)\n#endif\n\n#if HAVE_QUANTIFIED_CONSTRAINTS\npropNestedEq1 :: (forall x. Eq x => Eq (f x), forall x. Eq x => Eq (g x), Eq a, forall x. Show x => Show (f x), forall x. Show x => Show (g x), Show a)\n => f (g a) -> f (g a) -> Property\npropNestedEq1 = (===)\n#else\npropNestedEq1 :: (Eq1 f, Eq1 g, Eq a, Show1 f, Show1 g, Show a, Functor f)\n => f (g a) -> f (g a) -> Property\npropNestedEq1 x y = Compose x === Compose y\n#endif\n\ntoSpecialApplicative ::\n Compose Triple ((,) (S.Set Integer)) Integer\n -> Compose Triple (WL.Writer (S.Set Integer)) Integer\ntoSpecialApplicative (Compose (Triple a b c)) =\n Compose (Triple (WL.writer (flipPair a)) (WL.writer (flipPair b)) (WL.writer (flipPair c)))\n#endif\n\nflipPair :: (a,b) -> (b,a)\nflipPair (x,y) = (y,x)\n\n#if HAVE_UNARY_LAWS\n-- Reverse the list and accumulate the writers. We cannot\n-- use Sum or Product or else it wont actually be a valid\n-- applicative transformation.\napTrans ::\n Compose Triple (WL.Writer (S.Set Integer)) a\n -> Compose (WL.Writer (S.Set Integer)) Triple a\napTrans (Compose xs) = Compose (sequenceA (reverseTriple xs))\n#endif\n\nfunc1 :: Integer -> (Integer,Integer)\nfunc1 i = (div (i + 5) 3, i * i - 2 * i + 1)\n\nfunc2 :: (Integer,Integer) -> (Bool,Either Ordering Integer)\nfunc2 (a,b) = (odd a, if even a then Left (compare a b) else Right (b + 2))\n\nfunc3 :: Integer -> SG.Sum Integer\nfunc3 i = SG.Sum (3 * i * i - 7 * i + 4)\n\n#if HAVE_UNARY_LAWS\nfunc4 :: Integer -> Compose Triple (WL.Writer (S.Set Integer)) Integer\nfunc4 i = Compose $ Triple\n (WL.writer (i * i, S.singleton (i * 7 + 5)))\n (WL.writer (i + 2, S.singleton (i * i + 3)))\n (WL.writer (i * 7, S.singleton 4))\n#endif\n\nfunc5 :: Integer -> Triple Integer\nfunc5 i = Triple (i + 2) (i * 3) (i * i)\n\nfunc6 :: Integer -> Triple Integer\nfunc6 i = Triple (i * i * i) (4 * i - 7) (i * i * i)\n\ndata Triple a = Triple a a a\n deriving (Show,Eq)\n\ntripleLiftEq :: (a -> b -> Bool) -> Triple a -> Triple b -> Bool\ntripleLiftEq p (Triple a1 b1 c1) (Triple a2 b2 c2) =\n p a1 a2 && p b1 b2 && p c1 c2\n\n#if HAVE_UNARY_LAWS\ninstance Eq1 Triple where\n#if MIN_VERSION_base(4,9,0) || MIN_VERSION_transformers(0,5,0)\n liftEq = tripleLiftEq\n#else\n eq1 = tripleLiftEq (==)\n#endif\n#endif\n\ntripleLiftShowsPrec :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> Int -> Triple a -> ShowS\ntripleLiftShowsPrec elemShowsPrec _ p (Triple a b c) = showParen (p > 10)\n $ showString \"Triple \"\n . elemShowsPrec 11 a\n . showString \" \"\n . elemShowsPrec 11 b\n . showString \" \"\n . elemShowsPrec 11 c\n\n#if HAVE_UNARY_LAWS\ninstance Show1 Triple where\n#if MIN_VERSION_base(4,9,0) || MIN_VERSION_transformers(0,5,0)\n liftShowsPrec = tripleLiftShowsPrec\n#else\n showsPrec1 = tripleLiftShowsPrec showsPrec showList\n#endif\n#endif\n\n#if HAVE_UNARY_LAWS\ninstance Arbitrary1 Triple where\n liftArbitrary x = Triple <$> x <*> x <*> x\n\ninstance Arbitrary a => Arbitrary (Triple a) where\n arbitrary = liftArbitrary arbitrary\n#else\ninstance Arbitrary a => Arbitrary (Triple a) where\n arbitrary = Triple <$> arbitrary <*> arbitrary <*> arbitrary\n#endif\n\ninstance Functor Triple where\n fmap f (Triple a b c) = Triple (f a) (f b) (f c)\n\ninstance Applicative Triple where\n pure a = Triple a a a\n Triple f g h <*> Triple a b c = Triple (f a) (g b) (h c)\n\ninstance Foldable Triple where\n foldMap f (Triple a b c) = f a MND.<> f b MND.<> f c\n\ninstance Traversable Triple where\n traverse f (Triple a b c) = Triple <$> f a <*> f b <*> f c\n\nreverseTriple :: Triple a -> Triple a\nreverseTriple (Triple a b c) = Triple c b a\n\ndata ChooseSecond = ChooseSecond\n deriving (Eq)\n\ndata ChooseFirst = ChooseFirst\n deriving (Eq)\n\ndata LastNothing = LastNothing\n deriving (Eq)\n\ndata Bottom a = BottomUndefined | BottomValue a\n deriving (Eq)\n\ninstance Show ChooseFirst where\n show ChooseFirst = \"\\\\a b -> if even a then a else b\"\n\ninstance Show ChooseSecond where\n show ChooseSecond = \"\\\\a b -> if even b then a else b\"\n\ninstance Show LastNothing where\n show LastNothing = \"0\"\n\ninstance Show a => Show (Bottom a) where\n show x = case x of\n BottomUndefined -> \"undefined\"\n BottomValue a -> show a\n\ninstance Arbitrary ChooseSecond where\n arbitrary = pure ChooseSecond\n\ninstance Arbitrary ChooseFirst where\n arbitrary = pure ChooseFirst\n\ninstance Arbitrary LastNothing where\n arbitrary = pure LastNothing\n\ninstance Arbitrary a => Arbitrary (Bottom a) where\n arbitrary = fmap maybeToBottom arbitrary\n shrink x = map maybeToBottom (shrink (bottomToMaybe x))\n\nbottomToMaybe :: Bottom a -> Maybe a\nbottomToMaybe BottomUndefined = Nothing\nbottomToMaybe (BottomValue a) = Just a\n\nmaybeToBottom :: Maybe a -> Bottom a\nmaybeToBottom Nothing = BottomUndefined\nmaybeToBottom (Just a) = BottomValue a\n\nnewtype Apply f a = Apply { getApply :: f a }\n\ninstance (Applicative f, Monoid a) => Semigroup (Apply f a) where\n Apply x <> Apply y = Apply $ liftA2 mappend x y\n\ninstance (Applicative f, Monoid a) => Monoid (Apply f a) where\n mempty = Apply $ pure mempty\n mappend = (SG.<>)\n\n#if HAVE_UNARY_LAWS\n#if HAVE_QUANTIFIED_CONSTRAINTS\nderiving instance (forall x. Eq x => Eq (f x), Eq a) => Eq (Apply f a)\nderiving instance (forall x. Arbitrary x => Arbitrary (f x), Arbitrary a) => Arbitrary (Apply f a)\nderiving instance (forall x. Show x => Show (f x), Show a) => Show (Apply f a)\n#else\ninstance (Eq1 f, Eq a) => Eq (Apply f a) where\n Apply a == Apply b = eq1 a b\n\n-- This show instance is intentionally a little bit wrong.\n-- We don't wrap the result in Apply since the end user\n-- should not be made aware of the Apply wrapper anyway.\ninstance (Show1 f, Show a) => Show (Apply f a) where\n showsPrec p = showsPrec1 p . getApply\n\ninstance (Arbitrary1 f, Arbitrary a) => Arbitrary (Apply f a) where\n arbitrary = fmap Apply arbitrary1\n shrink = map Apply . shrink1 . getApply\n#endif\n#endif\n\nfoldMapA :: (Foldable t, Monoid m, Semigroup m, Applicative f) => (a -> f m) -> t a -> f m\nfoldMapA f = getApply . foldMap (Apply . f)\n\n\n#if HAVE_BINARY_LAWS\nnewtype Apply2 f a b = Apply2 { getApply2 :: f a b }\n\n#if HAVE_QUANTIFIED_CONSTRAINTS\nderiving instance (forall x y. (Eq x, Eq y) => Eq (f x y), Eq a, Eq b) => Eq (Apply2 f a b)\nderiving instance (forall x y. (Arbitrary x, Arbitrary y) => Arbitrary (f x y), Arbitrary a, Arbitrary b) => Arbitrary (Apply2 f a b)\nderiving instance (forall x y. (Show x, Show y) => Show (f x y), Show a, Show b) => Show (Apply2 f a b)\n#else\ninstance (Eq2 f, Eq a, Eq b) => Eq (Apply2 f a b) where\n Apply2 a == Apply2 b = eq2 a b\n\ninstance (Show2 f, Show a, Show b) => Show (Apply2 f a b) where\n showsPrec p = showsPrec2 p . getApply2\n\ninstance (Arbitrary2 f, Arbitrary a, Arbitrary b) => Arbitrary (Apply2 f a b) where\n arbitrary = fmap Apply2 arbitrary2\n shrink = fmap Apply2 . shrink2 . getApply2\n#endif\n#endif\n\ndata LinearEquation = LinearEquation\n { _linearEquationLinear :: Integer\n , _linearEquationConstant :: Integer\n } deriving (Eq)\n\ninstance Show LinearEquation where\n showsPrec = showLinear\n showList = showLinearList\n\nrunLinearEquation :: LinearEquation -> Integer -> Integer\nrunLinearEquation (LinearEquation a b) x = a * x + b\n\nshowLinear :: Int -> LinearEquation -> ShowS\nshowLinear _ (LinearEquation a b) = shows a . showString \" * x + \" . shows b\n\nshowLinearList :: [LinearEquation] -> ShowS\nshowLinearList xs = SG.appEndo $ mconcat\n $ [SG.Endo (showChar '[')]\n ++ L.intersperse (SG.Endo (showChar ',')) (map (SG.Endo . showLinear 0) xs)\n ++ [SG.Endo (showChar ']')]\n\n#if HAVE_UNARY_LAWS\ndata LinearEquationM m = LinearEquationM (m LinearEquation) (m LinearEquation)\n\nrunLinearEquationM :: Monad m => LinearEquationM m -> Integer -> m Integer\nrunLinearEquationM (LinearEquationM e1 e2) i = if odd i\n then liftM (flip runLinearEquation i) e1\n else liftM (flip runLinearEquation i) e2\n\n#if HAVE_QUANTIFIED_CONSTRAINTS\nderiving instance (forall x. Eq x => Eq (m x)) => Eq (LinearEquationM m)\ninstance (forall a. Show a => Show (m a)) => Show (LinearEquationM m) where\n show (LinearEquationM a b) = (\\f -> f \"\")\n $ showString \"\\\\x -> if odd x then \"\n . showsPrec 0 a\n . showString \" else \"\n . showsPrec 0 b\ninstance (forall a. Arbitrary a => Arbitrary (m a)) => Arbitrary (LinearEquationM m) where\n arbitrary = liftA2 LinearEquationM arbitrary arbitrary\n shrink (LinearEquationM a b) = L.concat\n [ map (\\x -> LinearEquationM x b) (shrink a)\n , map (\\x -> LinearEquationM a x) (shrink b)\n ]\n#else\ninstance Eq1 m => Eq (LinearEquationM m) where\n LinearEquationM a1 b1 == LinearEquationM a2 b2 = eq1 a1 a2 && eq1 b1 b2\n\ninstance Show1 m => Show (LinearEquationM m) where\n show (LinearEquationM a b) = (\\f -> f \"\")\n $ showString \"\\\\x -> if odd x then \"\n . showsPrec1 0 a\n . showString \" else \"\n . showsPrec1 0 b\n\ninstance Arbitrary1 m => Arbitrary (LinearEquationM m) where\n arbitrary = liftA2 LinearEquationM arbitrary1 arbitrary1\n shrink (LinearEquationM a b) = L.concat\n [ map (\\x -> LinearEquationM x b) (shrink1 a)\n , map (\\x -> LinearEquationM a x) (shrink1 b)\n ]\n#endif\n#endif\n\ninstance Arbitrary LinearEquation where\n arbitrary = do\n (a,b) <- arbitrary\n return (LinearEquation (abs a) (abs b))\n shrink (LinearEquation a b) =\n let xs = shrink (a,b)\n in map (\\(x,y) -> LinearEquation (abs x) (abs y)) xs\n\n-- this is a quadratic equation\ndata QuadraticEquation = QuadraticEquation\n { _quadraticEquationQuadratic :: Integer\n , _quadraticEquationLinear :: Integer\n , _quadraticEquationConstant :: Integer\n }\n deriving (Eq)\n\n-- This show instance is does not actually provide a\n-- way to create an equation. Instead, it makes it look\n-- like a lambda.\ninstance Show QuadraticEquation where\n show (QuadraticEquation a b c) = \"\\\\x -> \" ++ show a ++ \" * x ^ 2 + \" ++ show b ++ \" * x + \" ++ show c\n\ninstance Arbitrary QuadraticEquation where\n arbitrary = do\n (a,b,c) <- arbitrary\n return (QuadraticEquation (abs a) (abs b) (abs c))\n shrink (QuadraticEquation a b c) =\n let xs = shrink (a,b,c)\n in map (\\(x,y,z) -> QuadraticEquation (abs x) (abs y) (abs z)) xs\n\nrunQuadraticEquation :: QuadraticEquation -> Integer -> Integer\nrunQuadraticEquation (QuadraticEquation a b c) x = a * x ^ (2 :: Integer) + b * x + c\n\ndata LinearEquationTwo = LinearEquationTwo\n { _linearEquationTwoX :: Integer\n , _linearEquationTwoY :: Integer\n }\n deriving (Eq)\n\n-- This show instance does not actually provide a\n-- way to create a LinearEquationTwo. Instead, it makes it look\n-- like a lambda that takes two variables.\ninstance Show LinearEquationTwo where\n show (LinearEquationTwo a b) = \"\\\\x y -> \" ++ show a ++ \" * x + \" ++ show b ++ \" * y\"\n\ninstance Arbitrary LinearEquationTwo where\n arbitrary = do\n (a,b) <- arbitrary\n return (LinearEquationTwo (abs a) (abs b))\n shrink (LinearEquationTwo a b) =\n let xs = shrink (a,b)\n in map (\\(x,y) -> LinearEquationTwo (abs x) (abs y)) xs\n\nrunLinearEquationTwo :: LinearEquationTwo -> Integer -> Integer -> Integer\nrunLinearEquationTwo (LinearEquationTwo a b) x y = a * x + b * y\n","avg_line_length":30.7751091703,"max_line_length":175,"alphanum_fraction":0.6745654487} {"size":236,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"{-@ LIQUID \"--reflection\" @-}\n\n-- not ok\ndata Thing0 m = Thing\n { t0 :: (m Int -> Int) -> Int\n }\n\n-- not ok\ndata Thing1 m = Thing1\n { t1 :: (Int -> m Int) -> Int\n }\n\n-- ok\ndata Thing2 m = Thing2\n { t2 :: Int -> m Int -> Int\n }","avg_line_length":14.75,"max_line_length":33,"alphanum_fraction":0.4830508475} {"size":7623,"ext":"hs","lang":"Haskell","max_stars_count":15.0,"content":"{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE TupleSections #-}\n\nmodule PolyKinds.Type where\n\nimport Data.Foldable (toList)\nimport Data.Functor.Identity (Identity(..))\nimport Data.Maybe (mapMaybe)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\n\ndata Type\n = Star\n | Lit\n | Arrow\n | Constraint\n | ConstraintArrow\n | TypeUnknown Unknown\n | TypeVar Var\n | TypeName Name\n | TypeApp Type Type\n | KindApp Type Type\n | Forall BinderList Type\n deriving (Show, Eq)\n\ntype BinderList = [(Var, Maybe Type)]\n\ntype KindBinderList = [(Unknown, Type)]\n\nnewtype Name = Name { getName :: String }\n deriving (Show, Eq, Ord)\n\nnewtype Var = Var { getVar :: String }\n deriving (Show, Eq, Ord)\n\nnewtype Unknown = Unknown { getUnknown :: Int }\n deriving (Show, Eq, Ord)\n\ndata Decl\n = Sig Name Type\n | Data Name BinderList [Ctr]\n | Class [Type] Name BinderList [ClassMember]\n deriving (Show, Eq)\n\ndata Ctr = Ctr\n { ctrExists :: BinderList\n , ctrConstraints :: [Type]\n , ctrName :: Name\n , ctrArgs :: [Type]\n } deriving (Show, Eq)\n\ndata ClassMember = ClassMember\n { memName :: Name\n , memType :: Type\n } deriving (Show, Eq)\n\nisSig :: Decl -> Bool\nisSig = \\case\n Sig _ _ -> True\n _ -> False\n\ndeclName :: Decl -> Name\ndeclName = \\case\n Sig n _ -> n\n Data n _ _ -> n\n Class _ n _ _ -> n\n\ndeclTypes :: Decl -> [Type]\ndeclTypes = \\case\n Sig _ t -> [t]\n Data _ vs cs ->\n foldMap (foldMap pure . snd) vs <>\n foldMap (\\(Ctr bs cns _ as) -> foldMap (foldMap pure . snd) bs <> cns <> as) cs\n Class ss _ vs cs ->\n ss <>\n foldMap (foldMap pure . snd) vs <>\n foldMap (pure . memType) cs\n\n{-# INLINE foldTypeWithScope #-}\nfoldTypeWithScope :: Semigroup m => (S.Set Var -> Type -> m) -> S.Set Var -> Type -> m\nfoldTypeWithScope k = go\n where\n go seen ty = case ty of\n Forall bs ty' ->\n k seen ty <> goBinders seen ty' bs\n TypeApp a b ->\n k seen ty <> (go seen a <> go seen b)\n KindApp a b ->\n k seen ty <> (go seen a <> go seen b)\n _ ->\n k seen ty\n\n goBinders seen ty = \\case\n [] -> go seen ty\n (var, mbK) : bs -> do\n let rest = goBinders (S.insert var seen) ty bs\n maybe rest ((<> rest) . go seen) mbK\n\n{-# INLINE foldType #-}\nfoldType :: Semigroup m => (Type -> m) -> Type -> m\nfoldType k = go\n where\n go ty = case ty of\n Forall bs ty' ->\n k ty <> goBinders ty' bs\n TypeApp a b ->\n k ty <> (go a <> go b)\n KindApp a b ->\n k ty <> (go a <> go b)\n _ ->\n k ty\n\n goBinders ty = \\case\n [] -> go ty\n (_, mbK) : bs ->\n case mbK of\n Just ty' ->\n go ty' <> goBinders ty bs\n Nothing ->\n goBinders ty bs\n\n{-# INLINE rewrite #-}\nrewrite :: (Type -> Type) -> Type -> Type\nrewrite k = runIdentity . rewriteM (Identity . k)\n\n{-# INLINE rewriteM #-}\nrewriteM :: Monad m => (Type -> m Type) -> Type -> m Type\nrewriteM k = go\n where\n go = \\case\n Forall bs ty -> do\n bs' <- traverse (traverse (traverse go)) bs\n ty' <- go ty\n k (Forall bs' ty')\n TypeApp a b -> do\n a' <- go a\n b' <- go b\n k $ TypeApp a' b'\n KindApp a b -> do\n a' <- go a\n b' <- go b\n k $ KindApp a' b'\n ty ->\n k ty\n\n{-# INLINE rewriteWithScope #-}\nrewriteWithScope :: (S.Set Var -> Type -> Type) -> S.Set Var -> Type -> Type\nrewriteWithScope k vars = runIdentity . rewriteWithScopeM ((Identity .) . k) vars\n\n{-# INLINE rewriteWithScopeM #-}\nrewriteWithScopeM :: Monad m => (S.Set Var -> Type -> m Type) -> S.Set Var -> Type -> m Type\nrewriteWithScopeM k = go\n where\n go seen ty = case ty of\n Forall bs ty' ->\n k seen =<< goForall seen ty' [] bs\n TypeApp a b -> do\n a' <- go seen a\n b' <- go seen b\n k seen $ TypeApp a' b'\n KindApp a b -> do\n a' <- go seen a\n b' <- go seen b\n k seen $ KindApp a' b'\n _ ->\n k seen ty\n\n goForall seen ty bs' = \\case\n [] ->\n Forall (reverse bs') <$> go seen ty\n (var, mbK) : bs ->\n case mbK of\n Just ty' -> do\n ty'' <- go seen ty'\n goForall (S.insert var seen) ty ((var, Just ty'') : bs') bs\n Nothing ->\n goForall (S.insert var seen) ty ((var, Nothing) : bs') bs\n\nnames :: Type -> S.Set Name\nnames = foldType $ \\case\n TypeName n ->\n S.singleton n\n _ ->\n mempty\n\nvarsAndUnknowns :: Type -> S.Set (Either Var Unknown)\nvarsAndUnknowns = flip foldTypeWithScope mempty $ \\scope ty ->\n case ty of\n TypeUnknown unk ->\n S.singleton (Right unk)\n TypeVar var | not (S.member var scope) ->\n S.singleton (Left var)\n _ ->\n mempty\n\nfreeVars :: Type -> S.Set Var\nfreeVars = S.fromDistinctAscList . mapMaybe go . toList . varsAndUnknowns\n where\n go = \\case\n Left var -> Just var\n _ -> Nothing\n\nsubstUnknowns :: IM.IntMap Type -> Type -> Type\nsubstUnknowns unks = rewrite $ \\case\n TypeUnknown (Unknown i)\n | Just ty <- IM.lookup i unks -> ty\n ty -> ty\n\nsubstTypeNames :: M.Map Name Type -> Type -> Type\nsubstTypeNames ns = rewrite $ \\case\n TypeName name\n | Just ty <- M.lookup name ns -> ty\n ty -> ty\n\nsubstVar :: Var -> Type -> Type -> Type\nsubstVar var ty = rewriteWithScope go mempty\n where\n go scope = \\case\n TypeVar var'\n | var' == var && not (S.member var scope) -> ty\n ty' -> ty'\n\nsubstVars :: M.Map Var Type -> Type -> Type\nsubstVars vars = rewriteWithScope go mempty\n where\n go scope = \\case\n TypeVar var\n | S.notMember var scope\n , Just ty <- M.lookup var vars -> ty\n ty -> ty\n\nmkForall :: BinderList -> Type -> Type\nmkForall = curry $ \\case\n ([], ty) -> ty\n (bs, Forall bs' ty) -> Forall (bs <> bs') ty\n (bs, ty) -> Forall bs ty\n\nunconsForall :: Type -> Maybe ((Var, Maybe Type), Type)\nunconsForall = \\case\n Forall (b : bs) ty -> Just (b, mkForall bs ty)\n _ -> Nothing\n\nconsForall :: (Var, Maybe Type) -> Type -> Type\nconsForall b = \\case\n Forall bs ty' -> Forall (b : bs) ty'\n ty' -> Forall [b] ty'\n\nmkTypeApp :: Type -> [Type] -> Type\nmkTypeApp = foldl TypeApp\n\nmkConstraintArrow :: Name -> [Type] -> Type -> Type\nmkConstraintArrow n = TypeApp . TypeApp ConstraintArrow . mkTypeApp (TypeName n)\n\ncompleteBinderList :: Type -> Maybe ([(Var, Type)], Type)\ncompleteBinderList = go []\n where\n go bs ty =\n case unconsForall ty of\n Just ((_, Nothing), _) ->\n Nothing\n Just ((var, Just k), ty') ->\n go ((var, k) : bs) ty'\n Nothing ->\n Just ((reverse bs), ty)\n\nunknownVar :: Unknown -> Var\nunknownVar = Var . (\"u\" <>) . show . getUnknown\n\nunknowns :: Type -> IS.IntSet\nunknowns = foldType $ \\case\n TypeUnknown (Unknown i) ->\n IS.singleton i\n _ ->\n mempty\n\nisType :: Type -> Bool\nisType = go\n where\n go = \\case\n Lit -> True\n Arrow -> True\n ConstraintArrow -> True\n TypeVar _ -> True\n TypeName _ -> True\n TypeApp a b -> go a && go b\n KindApp a b -> go a && isKind b\n Forall bs ty -> goBinders bs && go ty\n _ -> False\n\n goBinders = \\case\n (_, Just a) : bs -> isKind a && goBinders bs\n _ : bs -> goBinders bs\n _ -> True\n\nisKind :: Type -> Bool\nisKind = \\case\n Star -> True\n Constraint -> True\n Lit -> True\n Arrow -> True\n TypeVar _ -> True\n TypeName _ -> True\n TypeApp a b -> isKind a && isKind b\n KindApp a b -> isKind a && isKind b\n _ -> False\n\nisKindDecl :: Type -> Bool\nisKindDecl = go\n where\n go = \\case\n Forall bs kd -> goBinders bs && go kd\n kd -> isKind kd\n\n goBinders = \\case\n (_, Just a) : bs -> isKind a && goBinders bs\n _ : bs -> goBinders bs\n _ -> True\n","avg_line_length":23.6739130435,"max_line_length":92,"alphanum_fraction":0.582841401} {"size":113,"ext":"hs","lang":"Haskell","max_stars_count":3.0,"content":"module Foo where\n factorial :: Integer -> Integer\n factorial 0 = 1\n factorial x = x * factorial (x - 1)\n","avg_line_length":22.6,"max_line_length":39,"alphanum_fraction":0.6194690265} {"size":7071,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Settings\n ( Settings (..)\n , sProgramName\n , sProjectVersion\n , sGhcUsagePath\n , sGhciUsagePath\n , sToolDir\n , sTopDir\n , sTmpDir\n , sSystemPackageConfig\n , sLdSupportsCompactUnwind\n , sLdSupportsBuildId\n , sLdSupportsFilelist\n , sLdIsGnuLd\n , sGccSupportsNoPie\n , sPgm_L\n , sPgm_P\n , sPgm_F\n , sPgm_c\n , sPgm_a\n , sPgm_l\n , sPgm_lm\n , sPgm_dll\n , sPgm_T\n , sPgm_windres\n , sPgm_libtool\n , sPgm_ar\n , sPgm_ranlib\n , sPgm_lo\n , sPgm_lc\n , sPgm_lcc\n , sPgm_i\n , sOpt_L\n , sOpt_P\n , sOpt_P_fingerprint\n , sOpt_F\n , sOpt_c\n , sOpt_cxx\n , sOpt_a\n , sOpt_l\n , sOpt_lm\n , sOpt_windres\n , sOpt_lo\n , sOpt_lc\n , sOpt_lcc\n , sOpt_i\n , sExtraGccViaCFlags\n , sTargetPlatformString\n , sIntegerLibrary\n , sIntegerLibraryType\n , sGhcWithInterpreter\n , sGhcWithNativeCodeGen\n , sGhcWithSMP\n , sGhcRTSWays\n , sTablesNextToCode\n , sLeadingUnderscore\n , sLibFFI\n , sGhcThreaded\n , sGhcDebugged\n , sGhcRtsWithLibdw\n ) where\n\nimport GhcPrelude\n\nimport CliOption\nimport Fingerprint\nimport FileSettings\nimport GhcNameVersion\nimport GHC.Platform\nimport PlatformConstants\nimport ToolSettings\n\ndata Settings = Settings\n { sGhcNameVersion :: {-# UNPACk #-} !GhcNameVersion\n , sFileSettings :: {-# UNPACK #-} !FileSettings\n , sTargetPlatform :: Platform -- Filled in by SysTools\n , sToolSettings :: {-# UNPACK #-} !ToolSettings\n , sPlatformMisc :: {-# UNPACK #-} !PlatformMisc\n , sPlatformConstants :: PlatformConstants\n\n -- You shouldn't need to look things up in rawSettings directly.\n -- They should have their own fields instead.\n , sRawSettings :: [(String, String)]\n }\n\n-----------------------------------------------------------------------------\n-- Accessessors from 'Settings'\n\nsProgramName :: Settings -> String\nsProgramName = ghcNameVersion_programName . sGhcNameVersion\nsProjectVersion :: Settings -> String\nsProjectVersion = ghcNameVersion_projectVersion . sGhcNameVersion\n\nsGhcUsagePath :: Settings -> FilePath\nsGhcUsagePath = fileSettings_ghcUsagePath . sFileSettings\nsGhciUsagePath :: Settings -> FilePath\nsGhciUsagePath = fileSettings_ghciUsagePath . sFileSettings\nsToolDir :: Settings -> Maybe FilePath\nsToolDir = fileSettings_toolDir . sFileSettings\nsTopDir :: Settings -> FilePath\nsTopDir = fileSettings_topDir . sFileSettings\nsTmpDir :: Settings -> String\nsTmpDir = fileSettings_tmpDir . sFileSettings\nsSystemPackageConfig :: Settings -> FilePath\nsSystemPackageConfig = fileSettings_systemPackageConfig . sFileSettings\n\nsLdSupportsCompactUnwind :: Settings -> Bool\nsLdSupportsCompactUnwind = toolSettings_ldSupportsCompactUnwind . sToolSettings\nsLdSupportsBuildId :: Settings -> Bool\nsLdSupportsBuildId = toolSettings_ldSupportsBuildId . sToolSettings\nsLdSupportsFilelist :: Settings -> Bool\nsLdSupportsFilelist = toolSettings_ldSupportsFilelist . sToolSettings\nsLdIsGnuLd :: Settings -> Bool\nsLdIsGnuLd = toolSettings_ldIsGnuLd . sToolSettings\nsGccSupportsNoPie :: Settings -> Bool\nsGccSupportsNoPie = toolSettings_ccSupportsNoPie . sToolSettings\n\nsPgm_L :: Settings -> String\nsPgm_L = toolSettings_pgm_L . sToolSettings\nsPgm_P :: Settings -> (String, [Option])\nsPgm_P = toolSettings_pgm_P . sToolSettings\nsPgm_F :: Settings -> String\nsPgm_F = toolSettings_pgm_F . sToolSettings\nsPgm_c :: Settings -> String\nsPgm_c = toolSettings_pgm_c . sToolSettings\nsPgm_a :: Settings -> (String, [Option])\nsPgm_a = toolSettings_pgm_a . sToolSettings\nsPgm_l :: Settings -> (String, [Option])\nsPgm_l = toolSettings_pgm_l . sToolSettings\nsPgm_lm :: Settings -> (String, [Option])\nsPgm_lm = toolSettings_pgm_lm . sToolSettings\nsPgm_dll :: Settings -> (String, [Option])\nsPgm_dll = toolSettings_pgm_dll . sToolSettings\nsPgm_T :: Settings -> String\nsPgm_T = toolSettings_pgm_T . sToolSettings\nsPgm_windres :: Settings -> String\nsPgm_windres = toolSettings_pgm_windres . sToolSettings\nsPgm_libtool :: Settings -> String\nsPgm_libtool = toolSettings_pgm_libtool . sToolSettings\nsPgm_ar :: Settings -> String\nsPgm_ar = toolSettings_pgm_ar . sToolSettings\nsPgm_ranlib :: Settings -> String\nsPgm_ranlib = toolSettings_pgm_ranlib . sToolSettings\nsPgm_lo :: Settings -> (String, [Option])\nsPgm_lo = toolSettings_pgm_lo . sToolSettings\nsPgm_lc :: Settings -> (String, [Option])\nsPgm_lc = toolSettings_pgm_lc . sToolSettings\nsPgm_lcc :: Settings -> (String, [Option])\nsPgm_lcc = toolSettings_pgm_lcc . sToolSettings\nsPgm_i :: Settings -> String\nsPgm_i = toolSettings_pgm_i . sToolSettings\nsOpt_L :: Settings -> [String]\nsOpt_L = toolSettings_opt_L . sToolSettings\nsOpt_P :: Settings -> [String]\nsOpt_P = toolSettings_opt_P . sToolSettings\nsOpt_P_fingerprint :: Settings -> Fingerprint\nsOpt_P_fingerprint = toolSettings_opt_P_fingerprint . sToolSettings\nsOpt_F :: Settings -> [String]\nsOpt_F = toolSettings_opt_F . sToolSettings\nsOpt_c :: Settings -> [String]\nsOpt_c = toolSettings_opt_c . sToolSettings\nsOpt_cxx :: Settings -> [String]\nsOpt_cxx = toolSettings_opt_cxx . sToolSettings\nsOpt_a :: Settings -> [String]\nsOpt_a = toolSettings_opt_a . sToolSettings\nsOpt_l :: Settings -> [String]\nsOpt_l = toolSettings_opt_l . sToolSettings\nsOpt_lm :: Settings -> [String]\nsOpt_lm = toolSettings_opt_lm . sToolSettings\nsOpt_windres :: Settings -> [String]\nsOpt_windres = toolSettings_opt_windres . sToolSettings\nsOpt_lo :: Settings -> [String]\nsOpt_lo = toolSettings_opt_lo . sToolSettings\nsOpt_lc :: Settings -> [String]\nsOpt_lc = toolSettings_opt_lc . sToolSettings\nsOpt_lcc :: Settings -> [String]\nsOpt_lcc = toolSettings_opt_lcc . sToolSettings\nsOpt_i :: Settings -> [String]\nsOpt_i = toolSettings_opt_i . sToolSettings\n\nsExtraGccViaCFlags :: Settings -> [String]\nsExtraGccViaCFlags = toolSettings_extraGccViaCFlags . sToolSettings\n\nsTargetPlatformString :: Settings -> String\nsTargetPlatformString = platformMisc_targetPlatformString . sPlatformMisc\nsIntegerLibrary :: Settings -> String\nsIntegerLibrary = platformMisc_integerLibrary . sPlatformMisc\nsIntegerLibraryType :: Settings -> IntegerLibrary\nsIntegerLibraryType = platformMisc_integerLibraryType . sPlatformMisc\nsGhcWithInterpreter :: Settings -> Bool\nsGhcWithInterpreter = platformMisc_ghcWithInterpreter . sPlatformMisc\nsGhcWithNativeCodeGen :: Settings -> Bool\nsGhcWithNativeCodeGen = platformMisc_ghcWithNativeCodeGen . sPlatformMisc\nsGhcWithSMP :: Settings -> Bool\nsGhcWithSMP = platformMisc_ghcWithSMP . sPlatformMisc\nsGhcRTSWays :: Settings -> String\nsGhcRTSWays = platformMisc_ghcRTSWays . sPlatformMisc\nsTablesNextToCode :: Settings -> Bool\nsTablesNextToCode = platformMisc_tablesNextToCode . sPlatformMisc\nsLeadingUnderscore :: Settings -> Bool\nsLeadingUnderscore = platformMisc_leadingUnderscore . sPlatformMisc\nsLibFFI :: Settings -> Bool\nsLibFFI = platformMisc_libFFI . sPlatformMisc\nsGhcThreaded :: Settings -> Bool\nsGhcThreaded = platformMisc_ghcThreaded . sPlatformMisc\nsGhcDebugged :: Settings -> Bool\nsGhcDebugged = platformMisc_ghcDebugged . sPlatformMisc\nsGhcRtsWithLibdw :: Settings -> Bool\nsGhcRtsWithLibdw = platformMisc_ghcRtsWithLibdw . sPlatformMisc\n","avg_line_length":33.6714285714,"max_line_length":79,"alphanum_fraction":0.7626926884} {"size":193,"ext":"hs","lang":"Haskell","max_stars_count":null,"content":"module Cereal.Uuid.Put\nwhere\n\nimport Cereal.Uuid.Prelude\n\n\nuuid :: Putter Word32 -> Putter UUID\nuuid word32 x = case toWords x of\n (a, b, c, d) -> word32 a <> word32 b <> word32 c <> word32 d\n","avg_line_length":19.3,"max_line_length":62,"alphanum_fraction":0.6735751295}