code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
niceGreeting :: String niceGreeting = "Hello! So very nice to see you," greet :: String -> String greet "Juan" = niceGreeting ++ " Juan!" greet "Fernando" = niceGreeting ++ " Fernando!" greet name = badGreeting ++ " " ++ name badGreeting :: String badGreeting = "Oh! Pfft. It's you." initials :: String -> String -> String initials firstName lastName = [f] ++ ". " ++ [l] ++ "." where (f:_) = firstName (l:_) = lastName calcBmis :: [(Double, Double)] -> [Double] calcBmis xs = [ bmi w h | (w, h) <- xs] where bmi w h = w / h ^ 2
EricYT/Haskell
src/valibe.hs
apache-2.0
555
0
8
129
210
113
97
15
1
-- Copyright 2017 Google Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Language.Haskell.Indexer.Backend.Ghc.Test.BasicTestBase (allTests) where import Control.Monad ((>=>), unless, void) import Control.Monad.Trans.Reader (ReaderT, runReaderT) import Language.Haskell.Indexer.Backend.Ghc.Test.TestHelper import Test.Framework (Test) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertFailure) type AssertionInEnv = ReaderT TestEnv IO () -- | Tests that arguments of top-level functions, and their references, are -- extracted. The argument references happen in various common syntactic -- environments, such as if-then-else, case, etc. testArgRef :: AssertionInEnv testArgRef = assertXRefsFrom ["basic/ArgRef.hs"] $ do declAt (3,3) >>= singleUsage >>= includesPos (3,7) declAt (5,3) >>= singleUsage >>= includesPos (5,7) declAt (7,3) >>= singleUsage >>= includesPos (7,22) declAt (7,5) >>= singleUsage >>= includesPos (7,29) -- | Tests recursive references in various contexts. testRecursiveRef :: AssertionInEnv testRecursiveRef = assertXRefsFrom ["basic/RecursiveRef.hs"] $ do -- Recursive function call without type signature targets the -- monomorphic binding. Test that we detect this. declAt (4,1) >>= singleUsage >>= includesPos (4,14) declAt (8,5) >>= usages >>= \case [u1, u2] -> do includesPos (6,9) u1 includesPos (8,23) u2 us -> checking $ assertFailure $ "Usage count differs: " ++ show us -- Recursive fun with type signature should target using the -- polymorphic binding. declAt (11,1) >>= usages >>= \case [u1, u2] -> do -- Note: first one is the ref from the type signature (see #25). includesPos (10,1) u1 includesPos (11,16) u2 us -> checking $ assertFailure $ "Usage count differs " ++ show us -- Other interesting cases. declAt (13,1) >>= singleUsage >>= includesPos (14,16) declAt (14,1) >>= singleUsage >>= includesPos (13,16) declAt (16,1) >>= singleUsage >>= includesPos (16,12) testDataDecl :: AssertionInEnv testDataDecl = assertXRefsFrom ["basic/DataDecl.hs"] $ do -- Plain data type. -- Ctor references. declAt (3,11) >>= singleUsage >>= includesPos (6,3) declAt (3,15) >>= singleUsage >>= includesPos (7,4) -- Record constructor reference. -- Based on the AST there would be a reference from the compiler-generated -- implementation of the field accessor, but we filter the body of such -- generated functions (see GhcAnalyser.hs for reasons). declAt (9,15) >>= singleUsage >>= includesPos (12,4) -- Accessor function reference. declAt (9,24) >>= singleUsage >>= includesPos (14,5) -- TODO(robinpalotai): datatype ref (once supported). -- TODO(robinpalotai): ctor arg references (once supported). -- | Test that function applications are emitted as calls. testFunCall :: AssertionInEnv testFunCall = assertXRefsFrom ["basic/FunCall.hs"] $ do declAt (3,1) >>= singleUsage >>= assertAll [ refKindIs Call , includesPos (4,11) , refContextIs `funk` declAt (4,1) ] declAt (6,1) >>= singleUsage >>= assertAll [ refKindIs Ref , includesPos (7,13) , refContextIs `funk` declAt (7,1) ] declAt (9,1) >>= usages >>= \case [u1, u2] -> do flip assertAll u1 [ includesPos (10,10) , refKindIs Call ] flip assertAll u2 [ includesPos (10,12) , refKindIs Ref ] us -> checking $ assertFailure $ "Usage count differs: " ++ show us -- | Tests that typeclass method usages are extracted. -- Also includes test for types, as typeclass/instance types are trickier to -- gather - but this test should be deeper + moved to type tests eventually. testTypeClass :: AssertionInEnv testTypeClass = assertXRefsFrom ["basic/TypeClass.hs"] $ do -- TODO(robinpalotai): have a separate set of tests where we only -- test the reported types of things. For type constructor-like things -- maybe we should report their kind instead. declAt (5,5) >>= assertAll [ singleUsage >=> includesPos (17,5) -- Unfortunately class method signatures come from the renamed -- (but not typechecked) source, so no fancy forall / contexts. -- Could synthetise them if needed, see 'top_matter' in GHC's -- HsDecls. , userFriendlyTypeIs "a" ] declAt (9,5) >>= userFriendlyTypeIs "Int" declAt (11,1) >>= userFriendlyTypeIs "forall a. Foo a => a -> String" -- Test the extracted relations. instanceDecl <- declAt (7,10) extraAlternateIdSpanContainsPos (7,1) instanceDecl declAt (3,7) >>= hasRelation InstantiatesClass instanceDecl bind2 (hasRelation ImplementsMethod) (declAt (9,5)) (declAt (5,5)) -- TODO(robinpalotai): default method support -- | Tests that calls in instance method bodies are emitted. -- Also tests that instance methods have an identifier which includes the -- class + instance name, to make it distinguishable from other instances' -- method in the caller list. testTypeClassRef :: AssertionInEnv testTypeClassRef = assertXRefsFrom ["basic/TypeClassRef.hs"] $ do declAt (3,1) >>= singleUsage >>= assertAll [ refKindIs Call , includesPos (9,13) , refContextIs `funk` declAt (9,5) ] declAt (9,5) >>= extraMethodForInstanceIs "Foo ()" -- | Tests that C-preprocessed files can be processed, and that declaration -- locations refer to the original location (not offset by includes etc). -- This is a smoke test, doesn't check declarations/references originating -- to/from included files. testCppInclude :: AssertionInEnv testCppInclude = assertXRefsFromExtra ["basic/DummyInclude.hs"] ["basic/CppInclude.hs"] $ declAt (4,1) >>= singleUsage >>= assertAll [ includesPos (8,30) , refContextIs `funk` declAt (8,1) ] -- | Smoke test that TemplateHaskell works and references to TH-decls are -- found. See also b/26456233. testTemplateHaskellQuotation :: AssertionInEnv testTemplateHaskellQuotation = assertXRefsFrom ["basic/TemplateHaskellQuotation.hs"] $ -- Location for TH-generated decls is just the whole span of the runQ -- block - can live with that. declsAt (6, 3) >>= \case [f, v] -> do singleUsage f >>= includesPos (11,11) singleUsage v >>= includesPos (11,17) decls -> checking $ assertFailure $ "Expected two decls from TH, but got " ++ show decls testTemplateHaskellCodeExec :: AssertionInEnv testTemplateHaskellCodeExec = assertXRefsFrom ["basic/TemplateHaskellCodeExec.hs", "basic/UsedByTH.hs"] $ void $ declAt (8,1) testTemplateHaskellWerrorOpt :: AssertionInEnv testTemplateHaskellWerrorOpt = assertXRefsFrom ["-O2", "-Werror", "basic/TemplateHaskellQuotation.hs"] $ return () testTemplateHaskellCodeExecFFI :: AssertionInEnv testTemplateHaskellCodeExecFFI = assertXRefsFrom [ "basic/TemplateHaskellCodeExecFFI.hs" , "basic/ForeignImport.hs" , "basic/ffi.c" ] $ void $ declAt (8,1) -- TODO(https://github.com/google/haskell-indexer/issues/70): more infra tests. testForeignImport :: AssertionInEnv testForeignImport = assertXRefsFrom ["basic/ForeignImport.hs", "basic/ffi.c"] $ -- If we get this far it compiles. -- TODO(robinpalotai): assert declaration once supported. return () testForeignExport :: AssertionInEnv testForeignExport = assertXRefsFrom ["basic/ForeignExport.hs"] $ void $ declAt (7,1) testRtsArgsSkipped :: AssertionInEnv testRtsArgsSkipped = assertXRefsFrom ["+RTS", "-A128M", "-RTS", "basic/ArgRef.hs"] $ return () -- | Contains same name on type and term level, checks if usages go to the -- correct one. testDisambiguateTermType :: AssertionInEnv testDisambiguateTermType = assertXRefsFrom ["basic/TypeVsTerm.hs"] $ do declAt (3,10) >>= singleUsage >>= includesPos (6,10) declAt (3,6) >>= singleUsage >>= includesPos (5,11) -- | Checks that an executable (which usually has package 'main' in GHC) gets a -- more specific package by including the fallback (set as "dummyPkg" in -- TestHelper). testExecutableTickPackage :: AssertionInEnv testExecutableTickPackage = assertXRefsFrom ["basic/ExecutableMain.hs"] $ declAt (3,1) >>= declPropEquals (getPackage . tickPkgModule . declTick) "dummyPkg_main" testLocalRef :: AssertionInEnv testLocalRef = assertXRefsFrom ["basic/LocalRef.hs"] $ do declAt (8,5) >>= singleUsage >>= includesPos (6,32) declAt (16,5) >>= singleUsage >>= includesPos (14,34) testRecordRead :: AssertionInEnv testRecordRead = assertXRefsFrom ["basic/RecordRead.hs"] $ do declAt (4,12) >>= usages >>= \case -- Don't really caring about this, just a smoke check. u1:u2:_ -> do includesPos (6,9) u1 includesPos (10,10) u2 us -> checking $ assertFailure $ "Different use count for ctor read: " ++ show us declAt (4,18) >>= usages >>= \case [u1, u2, u3, u4, u5, u6, u7, u8] -> do -- Simple accessor. includesPos (8,12) u1 -- Unpacked field using record wildcards. includesPos (10,14) u2 -- Dotdots. includesPos (10,20) u3 -- Unpacked ref. -- Unpacked using punning. includesPos (12,12) u4 -- The pun. includesPos (12,21) u5 -- Unpacked ref. -- Unpacked using normal reassignment. includesPos (14,16) u6 -- Wildcard mixed with normal extracted field. includesPos (19,20) u7 -- Dotdot. includesPos (19,26) u8 -- Unpacked ref. other -> checking $ assertFailure ( "Different use count for field read: " ++ show other) -- The reassigned field. declAt (14,22) >>= singleUsage >>= includesPos (14, 29) -- Complex deconstructed fields should emit a reference from the place -- of deconstruction. declAt (16,26) >>= singleUsage >>= includesPos (17,24) testRecordWrite :: AssertionInEnv testRecordWrite = assertXRefsFrom ["basic/RecordWrite.hs"] $ do declAt (4,12) >>= usages >>= \case [u1, u2, u3, u4, u5, u6] -> do includesPos (9,10) u1 includesPos (11,26) u2 includesPos (16,8) u3 includesPos (21,8) u4 includesPos (25,14) u5 includesPos (25,24) u6 xs -> checking $ assertFailure ("Different use count for ctor ref: " ++ show (length xs)) declAt (5,7) >>= usages >>= \case [u1, u2, u3, u4, u5, u6, u7] -> do includesPos (11,41) u1 -- Explicit record field assignment. -- includesPos (14,9) u2 -- Wildcard preparation. includesPos (16,12) u3 -- Wildcard dots. -- includesPos (19,9) u4 -- Pun preparation. includesPos (21,12) u5 -- Pun record write. -- Wildcard unpack without use + write with assignment. includesPos (25,18) u6 -- Unpack (not really a write). includesPos (26,7) u7 -- Assignment. xs -> checking $ assertFailure ("Different use count for 'foo' write: " ++ show (length xs)) declAt (6,7) >>= usages >>= \case [u1, u2, u3, u4, u5, u6, u7, u8, u9] -> do -- Normal field write. includesPos (11,32) u1 -- Wildcard write. includesPos (15,9) u2 -- Preparation. includesPos (16,12) u3 -- Dots. -- Trailing wildcard write. includesPos (20,9) u4 -- Preparation. includesPos (21,16) u5 -- Trailing wildcard dots. -- Record update. includesPos (23,16) u6 -- Unpack from wildcard and write value. includesPos (25,18) u7 -- Dots. includesPos (27,7) u8 -- Field specifier. includesPos (27,13) u9 -- Assigned value. xs -> checking $ assertFailure ("Different use count for 'bar' write: " ++ show (length xs)) -- Multi-ctor field update. -- TODO(robinpalotai): the non-first ctor's fields should refer that of the -- first instead of introducing a decl (as happens in the AST). declAt (30,18) >>= singleUsage >>= includesPos (32,23) -- | Banging fields (and some other things) makes the Wrapper Id to be used -- instead of the Worker / DataCon Id. If we don't handle this, we wouldn't -- be able to refer the data constructor. testDataConWrap :: AssertionInEnv testDataConWrap = assertXRefsFrom ["basic/DataConWrap.hs"] $ declAt (3,12) >>= singleUsage >>= includesPos (5,8) -- | Test that source locations are reported in characters and not bytes. Also -- verifies that GHC accepts UTF-8 encoding errors as long as those are just in -- the comments. -- -- Warning: as the source file contains encoding error, take care if editing it. -- For example, some text editors refuse to open it at all, and some will -- replace the bad sequence with something else. Please verify with a hexeditor. testUtf8 :: AssertionInEnv testUtf8 = assertXRefsFrom ["basic/Utf8.hs"] $ declAt (6,1) >>= usages >>= \case [u1, u2] -> do spanIs (8,7) (8,10) u1 spanIs (8,14) (8,17) u2 xs -> checking $ assertFailure ("Different use count for unicodey var: " ++ show (length xs)) -- | Test that the module imports are emitted. testImports :: AssertionInEnv testImports = assertXRefsFrom ["basic/Imports.hs"] $ do importAt (3, 8) "Data.Int" importAt (4, 8) "Data.List" assertRefKind :: ReferenceKind -> TickReference -> ReaderT XRef IO () assertRefKind expected tick = let actual = refKind tick in unless (actual == expected) $ checking $ assertFailure $ show expected ++ " expected; got " ++ show actual testImpExpRefs :: AssertionInEnv testImpExpRefs = assertXRefsFrom ["basic/ImpExpDefs.hs", "basic/ImportRefs.hs"] $ do -- foo declAt (9, 1) >>= usages >>= \case [u1, u2, u3] -> do includesPos (3, 25) u1 -- import statement in ImportRefs.hs assertRefKind Import u1 includesPos (4, 5) u2 -- export list in ImpExpDefs.hs includesPos (8, 1) u3 -- type signature in ImpExpDefs.hs us -> checking $ assertFailure $ "Usage count differs for foo: " ++ show us -- bar declAt (12, 1) >>= usages >>= \case [u1, u2, u3] -> do includesPos (3, 5) u1 -- export list in ImpExpDefs.hs includesPos (3, 20) u2 -- import statement in ImportRefs.hs assertRefKind Import u2 includesPos (11, 1) u3 -- type signature in ImpExpDefs.hs us -> checking $ assertFailure $ "Usage count differs for bar: " ++ show us -- FooBar declAt (14, 6) >>= usages >>= \case [u1, u2, u3, u4] -> do includesPos (2, 5) u1 -- export list in ImpExpDefs.h includesPos (4, 20) u2 includesPos (5, 20) u3 includesPos (6, 20) u4 us -> checking $ assertFailure $ "Usage count differs for FooBar: " ++ show us -- MkFooBar declAt (15, 5) >>= usages >>= \case [u1, u2] -> do includesPos (2, 13) u1 -- export list in ImpExpDefs.h includesPos (6, 28) u2 us -> checking $ assertFailure $ "Usage count differs for MkFooBar: " ++ show us -- fbFoo declAt (16, 9) >>= usages >>= \case [u1, u2] -> do includesPos (2, 23) u1 -- export list in ImpExpDefs.h includesPos (6, 38) u2 us -> checking $ assertFailure $ "Usage count differs for fbFoo: " ++ show us -- fbBar declAt (17, 9) >>= usages >>= \case [u1, u2] -> do includesPos (2, 30) u1 -- export list in ImpExpDefs.h includesPos (6, 45) u2 us -> checking $ assertFailure $ "Usage count differs for fbBar: " ++ show us testImportRefsHiding :: AssertionInEnv testImportRefsHiding = assertXRefsFrom ["basic/ImpExpDefs.hs", "basic/ImportRefsHiding.hs"] $ do declAt (12, 1) >>= usages >>= \case [u1, u2, u3] -> do includesPos (3, 5) u1 -- export list in ImpExpDefs.hs includesPos (3, 27) u2 -- import statement in ImportRefsHiding.hs assertRefKind Ref u2 includesPos (11, 1) u3 -- type signature in ImpExpDefs.hs us -> checking $ assertFailure $ "Usage count differs for bar: " ++ show us testDocUri :: AssertionInEnv testDocUri = assertXRefsFrom ["basic/DocUri.hs"] $ do moduleDocUriDecl "base" "Data.Maybe.html" >>= singleModuleDocUriDeclImport -- Data.Maybe >>= includesPos (3, 8) docUriDecl "base" "GHC.Maybe.html" "#Maybe" >>= singleDocUriDeclUsage -- Maybe >>= includesPos (5, 7) docUriDecl "base" "Data.Maybe.html" "#catMaybes" >>= docUriDeclUsages -- catMaybes >>= \case [u1, u2] -> do includesPos (3, 20) u1 includesPos (6, 5) u2 us -> checking $ assertFailure $ "Usage count differs for catMaybes: " ++ show us testPatternSynonyms :: AssertionInEnv testPatternSynonyms = assertXRefsFrom ["basic/PatSyn.hs"] $ do declAt (4, 9) >>= singleUsage >>= includesPos (6, 15) declAt (8, 9) >>= usages >>= \case [u1, u2] -> do includesPos (10, 14) u1 includesPos (12, 14) u2 us -> checking $ assertFailure $ "Usage count differs for BiSingle: " ++ show us testTypeOperators :: AssertionInEnv testTypeOperators = assertXRefsFrom ["basic/TypeOperators.hs"] $ do declAt (5, 8) >>= singleUsage >>= includesPos (7, 22) -- | Prepares the tests to run with the given test environment. allTests :: TestEnv -> [Test] allTests env = [ envTestCase "arg-ref" testArgRef , envTestCase "recursive-ref" testRecursiveRef , envTestCase "data-decl" testDataDecl , envTestCase "fun-call" testFunCall , envTestCase "typeclass" testTypeClass , envTestCase "typeclass-ref" testTypeClassRef , envTestCase "cpp-include" testCppInclude , envTestCase "th-quotation" testTemplateHaskellQuotation , envTestCase "th-code-exec" testTemplateHaskellCodeExec , envTestCase "th-code-exec-ffi" testTemplateHaskellCodeExecFFI , envTestCase "th-werror-opt" testTemplateHaskellWerrorOpt , envTestCase "foreign-import" testForeignImport , envTestCase "foreign-export" testForeignExport , envTestCase "rts-args-skipped" testRtsArgsSkipped , envTestCase "disambiguate-term-type" testDisambiguateTermType , envTestCase "executable-package" testExecutableTickPackage , envTestCase "local-ref" testLocalRef , envTestCase "record-read" testRecordRead , envTestCase "record-write" testRecordWrite , envTestCase "data-con-wrap" testDataConWrap , envTestCase "utf8" testUtf8 , envTestCase "imports" testImports , envTestCase "import-export-refs" testImpExpRefs , envTestCase "import-refs-hiding" testImportRefsHiding , envTestCase "doc-uri" testDocUri , envTestCase "pattern-synonyms" testPatternSynonyms , envTestCase "type-operators" testTypeOperators ] where envTestCase name test = testCase name (runReaderT test env)
google/haskell-indexer
haskell-indexer-backend-ghc/tests/Language/Haskell/Indexer/Backend/Ghc/Test/BasicTestBase.hs
apache-2.0
19,934
0
18
4,850
4,520
2,420
2,100
326
7
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TypeFamilies #-} module Main where import Criterion.Main import Criterion.Types import Data.Int import Data.IORef import Data.Atomics (atomicModifyIORefCAS) import Data.Concurrent.LinkedMap as LM import Data.Concurrent.SkipListMap as SLM import Data.Concurrent.Map.Bench import Data.Concurrent.Map.Class -- import Control.Concurrent import qualified Data.Map as M cvt :: PreBench -> Benchmark cvt PreBench{name,batchRunner} = bench name (Benchmarkable batchRunner) -- Based on vanilla atomicModifyIORef. -- BAD! This is a SPACE LEAKING VERSION. newtype IOMap1 k v = IOMap1 (IORef (M.Map k v)) instance ConcurrentInsertMap IOMap1 where type Key IOMap1 k = Ord k -- FIXME: use safe cast new = do x <- newIORef M.empty; return $! IOMap1 x insert (IOMap1 r) k v = atomicModifyIORef r (\ m -> (M.insert k v m, ())) lookup (IOMap1 r) k = do m <- readIORef r return $! M.lookup k m estimateSize (IOMap1 r) = do m <- readIORef r return $! M.size m -- WHNF strict version: newtype IOMap2 k v = IOMap2 (IORef (M.Map k v)) instance ConcurrentInsertMap IOMap2 where type Key IOMap2 k = Ord k -- FIXME: use safe cast new = do x <- newIORef M.empty; return $! IOMap2 x insert (IOMap2 r) k v = atomicModifyIORef' r (\ m -> (M.insert k v m, ())) lookup (IOMap2 r) k = do m <- readIORef r return $! M.lookup k m estimateSize (IOMap2 r) = do m <- readIORef r return $! M.size m -- This version tries the speculative replacement for atomicModifyIORefCAS: newtype IOMap3 k v = IOMap3 (IORef (M.Map k v)) instance ConcurrentInsertMap IOMap3 where type Key IOMap3 k = Ord k new = do x <- newIORef M.empty; return $! IOMap3 x insert (IOMap3 r) k v = atomicModifyIORefCAS r (\ m -> (M.insert k v m, ())) lookup (IOMap3 r) k = do m <- readIORef r return $! M.lookup k m estimateSize (IOMap3 r) = do m <- readIORef r return $! M.size m main :: IO () main = do suite0 <- mkBenchSuite "SLMap" (Proxy:: Proxy(SLMap Int64 Int64)) suite1 <- mkBenchSuite "LMap" (Proxy:: Proxy(LM.LMap Int64 Int64)) suite2 <- mkBenchSuite "PureMap1" (Proxy:: Proxy(IOMap1 Int64 Int64)) suite3 <- mkBenchSuite "PureMap2" (Proxy:: Proxy(IOMap2 Int64 Int64)) suite4 <- mkBenchSuite "PureMap3" (Proxy:: Proxy(IOMap3 Int64 Int64)) defaultMain $ Prelude.map cvt suite0 ++ Prelude.map cvt suite1 ++ Prelude.map cvt suite2 ++ Prelude.map cvt suite3 ++ Prelude.map cvt suite4 ++ -- Retain RAW benchmarks to make sure the extra class abstraction -- isn't costing us anything: [ bgroup "RAW:linkedMap" [ bench "new" $ nfIO $ newLMap >> return () , bench "insert" $ nfIO $ do lm <- newLMap res <- LM.find lm "key" case res of NotFound tok -> tryInsert tok (42 :: Int) >> return () _ -> return () , bench "fromList10" $ nfIO $ fromList (zip [1..10] [1..10]) >> return () , bench "fillN" $ Benchmarkable $ \num -> do lm <- newLMap for_ 1 (fromIntegral num) $ \i -> do res <- LM.find lm (show i) case res of NotFound tok -> tryInsert tok i >> return () _ -> return () ] , bgroup "RAW:skipListMap" [ bench "new" $ nfIO $ newSLMap 10 >> return () , bench "insert" $ nfIO $ do slm <- newSLMap 10 putIfAbsent slm "key" $ return (42 :: Int) return () , bench "fillN" $ Benchmarkable $ \num -> do slm <- newSLMap 10 for_ 1 (fromIntegral num) $ \i -> do putIfAbsent slm (show i) (return i) return () ] ] for_ :: Monad m => Int -> Int -> (Int -> m ()) -> m () for_ start end _ | start > end = error "start greater than end" for_ start end fn = loop start where loop !i | i > end = return () | otherwise = fn i >> loop (i+1) {-# INLINE for_ #-}
rrnewton/concurrent-skiplist
tests/RunBench.hs
apache-2.0
4,049
0
24
1,136
1,515
747
768
94
3
module Data.Constraints where import Data.Constraint type family Constraints (cs :: [Constraint]) :: Constraint where Constraints '[] = () Constraints (c ': cs) = (c , Constraints cs)
wdanilo/typelevel
src/Data/Constraints.hs
apache-2.0
201
0
8
44
70
41
29
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QLayout_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QLayout_h where import Foreign.C.Types import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QLayout ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QLayout_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QLayout_unSetUserMethod" qtc_QLayout_unSetUserMethod :: Ptr (TQLayout a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QLayoutSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QLayout_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QLayout ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QLayout_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QLayoutSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QLayout_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QLayout ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QLayout_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QLayoutSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QLayout_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QLayout ()) (QLayout x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QLayout_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setUserMethod" qtc_QLayout_setUserMethod :: Ptr (TQLayout a) -> CInt -> Ptr (Ptr (TQLayout x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QLayout :: (Ptr (TQLayout x0) -> IO ()) -> IO (FunPtr (Ptr (TQLayout x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QLayout_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QLayoutSc a) (QLayout x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QLayout_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QLayout ()) (QLayout x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QLayout_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setUserMethodVariant" qtc_QLayout_setUserMethodVariant :: Ptr (TQLayout a) -> CInt -> Ptr (Ptr (TQLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QLayout :: (Ptr (TQLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QLayout_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QLayoutSc a) (QLayout x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QLayout_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QLayout ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QLayout_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QLayout_unSetHandler" qtc_QLayout_unSetHandler :: Ptr (TQLayout a) -> CWString -> IO (CBool) instance QunSetHandler (QLayoutSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QLayout_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QLayout ()) (QLayout x0 -> QLayoutItem t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQLayoutItem t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler1" qtc_QLayout_setHandler1 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> Ptr (TQLayoutItem t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout1 :: (Ptr (TQLayout x0) -> Ptr (TQLayoutItem t1) -> IO ()) -> IO (FunPtr (Ptr (TQLayout x0) -> Ptr (TQLayoutItem t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QLayout1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> QLayoutItem t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQLayoutItem t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QaddItem_h (QLayout ()) ((QLayoutItem t1)) where addItem_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLayout_addItem cobj_x0 cobj_x1 foreign import ccall "qtc_QLayout_addItem" qtc_QLayout_addItem :: Ptr (TQLayout a) -> Ptr (TQLayoutItem t1) -> IO () instance QaddItem_h (QLayoutSc a) ((QLayoutItem t1)) where addItem_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLayout_addItem cobj_x0 cobj_x1 instance QsetHandler (QLayout ()) (QLayout x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler2" qtc_QLayout_setHandler2 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout2 :: (Ptr (TQLayout x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQLayout x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QLayout2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qcount_h (QLayout ()) (()) where count_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_count cobj_x0 foreign import ccall "qtc_QLayout_count" qtc_QLayout_count :: Ptr (TQLayout a) -> IO CInt instance Qcount_h (QLayoutSc a) (()) where count_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_count cobj_x0 instance QsetHandler (QLayout ()) (QLayout x0 -> IO (Orientations)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (CLong) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then withQFlagsResult $ return $ toCLong 0 else _handler x0obj rvf <- rv return (toCLong $ qFlags_toInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler3" qtc_QLayout_setHandler3 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> IO (CLong)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout3 :: (Ptr (TQLayout x0) -> IO (CLong)) -> IO (FunPtr (Ptr (TQLayout x0) -> IO (CLong))) foreign import ccall "wrapper" wrapSetHandler_QLayout3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> IO (Orientations)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (CLong) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then withQFlagsResult $ return $ toCLong 0 else _handler x0obj rvf <- rv return (toCLong $ qFlags_toInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QexpandingDirections_h (QLayout ()) (()) where expandingDirections_h x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_expandingDirections cobj_x0 foreign import ccall "qtc_QLayout_expandingDirections" qtc_QLayout_expandingDirections :: Ptr (TQLayout a) -> IO CLong instance QexpandingDirections_h (QLayoutSc a) (()) where expandingDirections_h x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_expandingDirections cobj_x0 instance QsetHandler (QLayout ()) (QLayout x0 -> QObject t1 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQObject t1) -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler4" qtc_QLayout_setHandler4 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> Ptr (TQObject t1) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout4 :: (Ptr (TQLayout x0) -> Ptr (TQObject t1) -> IO (CInt)) -> IO (FunPtr (Ptr (TQLayout x0) -> Ptr (TQObject t1) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QLayout4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> QObject t1 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQObject t1) -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QindexOf_h (QLayout ()) ((QWidget t1)) where indexOf_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLayout_indexOf cobj_x0 cobj_x1 foreign import ccall "qtc_QLayout_indexOf" qtc_QLayout_indexOf :: Ptr (TQLayout a) -> Ptr (TQWidget t1) -> IO CInt instance QindexOf_h (QLayoutSc a) ((QWidget t1)) where indexOf_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLayout_indexOf cobj_x0 cobj_x1 instance QsetHandler (QLayout ()) (QLayout x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler5" qtc_QLayout_setHandler5 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout5 :: (Ptr (TQLayout x0) -> IO ()) -> IO (FunPtr (Ptr (TQLayout x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QLayout5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qinvalidate_h (QLayout ()) (()) where invalidate_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_invalidate cobj_x0 foreign import ccall "qtc_QLayout_invalidate" qtc_QLayout_invalidate :: Ptr (TQLayout a) -> IO () instance Qinvalidate_h (QLayoutSc a) (()) where invalidate_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_invalidate cobj_x0 instance QsetHandler (QLayout ()) (QLayout x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler6" qtc_QLayout_setHandler6 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout6 :: (Ptr (TQLayout x0) -> IO (CBool)) -> IO (FunPtr (Ptr (TQLayout x0) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QLayout6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqisEmpty_h (QLayout ()) (()) where qisEmpty_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_isEmpty cobj_x0 foreign import ccall "qtc_QLayout_isEmpty" qtc_QLayout_isEmpty :: Ptr (TQLayout a) -> IO CBool instance QqisEmpty_h (QLayoutSc a) (()) where qisEmpty_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_isEmpty cobj_x0 instance QsetHandler (QLayout ()) (QLayout x0 -> Int -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler7" qtc_QLayout_setHandler7 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout7 :: (Ptr (TQLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0))) -> IO (FunPtr (Ptr (TQLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0)))) foreign import ccall "wrapper" wrapSetHandler_QLayout7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> Int -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QitemAt_h (QLayout ()) ((Int)) where itemAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_itemAt cobj_x0 (toCInt x1) foreign import ccall "qtc_QLayout_itemAt" qtc_QLayout_itemAt :: Ptr (TQLayout a) -> CInt -> IO (Ptr (TQLayoutItem ())) instance QitemAt_h (QLayoutSc a) ((Int)) where itemAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_itemAt cobj_x0 (toCInt x1) instance QsetHandler (QLayout ()) (QLayout x0 -> IO (QObject t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (Ptr (TQObject t0)) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler8" qtc_QLayout_setHandler8 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> IO (Ptr (TQObject t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout8 :: (Ptr (TQLayout x0) -> IO (Ptr (TQObject t0))) -> IO (FunPtr (Ptr (TQLayout x0) -> IO (Ptr (TQObject t0)))) foreign import ccall "wrapper" wrapSetHandler_QLayout8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> IO (QObject t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (Ptr (TQObject t0)) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qlayout_h (QLayout ()) (()) where layout_h x0 () = withQLayoutResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_layout cobj_x0 foreign import ccall "qtc_QLayout_layout" qtc_QLayout_layout :: Ptr (TQLayout a) -> IO (Ptr (TQLayout ())) instance Qlayout_h (QLayoutSc a) (()) where layout_h x0 () = withQLayoutResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_layout cobj_x0 instance QsetHandler (QLayout ()) (QLayout x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler9" qtc_QLayout_setHandler9 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout9 :: (Ptr (TQLayout x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQLayout x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QLayout9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqmaximumSize_h (QLayout ()) (()) where qmaximumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_maximumSize cobj_x0 foreign import ccall "qtc_QLayout_maximumSize" qtc_QLayout_maximumSize :: Ptr (TQLayout a) -> IO (Ptr (TQSize ())) instance QqmaximumSize_h (QLayoutSc a) (()) where qmaximumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_maximumSize cobj_x0 instance QmaximumSize_h (QLayout ()) (()) where maximumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_maximumSize_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QLayout_maximumSize_qth" qtc_QLayout_maximumSize_qth :: Ptr (TQLayout a) -> Ptr CInt -> Ptr CInt -> IO () instance QmaximumSize_h (QLayoutSc a) (()) where maximumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_maximumSize_qth cobj_x0 csize_ret_w csize_ret_h instance QqminimumSize_h (QLayout ()) (()) where qminimumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_minimumSize cobj_x0 foreign import ccall "qtc_QLayout_minimumSize" qtc_QLayout_minimumSize :: Ptr (TQLayout a) -> IO (Ptr (TQSize ())) instance QqminimumSize_h (QLayoutSc a) (()) where qminimumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_minimumSize cobj_x0 instance QminimumSize_h (QLayout ()) (()) where minimumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_minimumSize_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QLayout_minimumSize_qth" qtc_QLayout_minimumSize_qth :: Ptr (TQLayout a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSize_h (QLayoutSc a) (()) where minimumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_minimumSize_qth cobj_x0 csize_ret_w csize_ret_h instance QsetHandler (QLayout ()) (QLayout x0 -> QRect t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQRect t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler10" qtc_QLayout_setHandler10 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> Ptr (TQRect t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout10 :: (Ptr (TQLayout x0) -> Ptr (TQRect t1) -> IO ()) -> IO (FunPtr (Ptr (TQLayout x0) -> Ptr (TQRect t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QLayout10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> QRect t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQRect t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqsetGeometry_h (QLayout ()) ((QRect t1)) where qsetGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLayout_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QLayout_setGeometry" qtc_QLayout_setGeometry :: Ptr (TQLayout a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry_h (QLayoutSc a) ((QRect t1)) where qsetGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLayout_setGeometry cobj_x0 cobj_x1 instance QsetGeometry_h (QLayout ()) ((Rect)) where setGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QLayout_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QLayout_setGeometry_qth" qtc_QLayout_setGeometry_qth :: Ptr (TQLayout a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry_h (QLayoutSc a) ((Rect)) where setGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QLayout_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QtakeAt_h (QLayout ()) ((Int)) where takeAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_takeAt cobj_x0 (toCInt x1) foreign import ccall "qtc_QLayout_takeAt" qtc_QLayout_takeAt :: Ptr (TQLayout a) -> CInt -> IO (Ptr (TQLayoutItem ())) instance QtakeAt_h (QLayoutSc a) ((Int)) where takeAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_takeAt cobj_x0 (toCInt x1) instance QhasHeightForWidth_h (QLayout ()) (()) where hasHeightForWidth_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_hasHeightForWidth cobj_x0 foreign import ccall "qtc_QLayout_hasHeightForWidth" qtc_QLayout_hasHeightForWidth :: Ptr (TQLayout a) -> IO CBool instance QhasHeightForWidth_h (QLayoutSc a) (()) where hasHeightForWidth_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_hasHeightForWidth cobj_x0 instance QsetHandler (QLayout ()) (QLayout x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler11" qtc_QLayout_setHandler11 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout11 :: (Ptr (TQLayout x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQLayout x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QLayout11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QheightForWidth_h (QLayout ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QLayout_heightForWidth" qtc_QLayout_heightForWidth :: Ptr (TQLayout a) -> CInt -> IO CInt instance QheightForWidth_h (QLayoutSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_heightForWidth cobj_x0 (toCInt x1) instance QminimumHeightForWidth_h (QLayout ()) ((Int)) where minimumHeightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_minimumHeightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QLayout_minimumHeightForWidth" qtc_QLayout_minimumHeightForWidth :: Ptr (TQLayout a) -> CInt -> IO CInt instance QminimumHeightForWidth_h (QLayoutSc a) ((Int)) where minimumHeightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_minimumHeightForWidth cobj_x0 (toCInt x1) instance QqsizeHint_h (QLayout ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_sizeHint cobj_x0 foreign import ccall "qtc_QLayout_sizeHint" qtc_QLayout_sizeHint :: Ptr (TQLayout a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QLayoutSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_sizeHint cobj_x0 instance QsizeHint_h (QLayout ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QLayout_sizeHint_qth" qtc_QLayout_sizeHint_qth :: Ptr (TQLayout a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QLayoutSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QsetHandler (QLayout ()) (QLayout x0 -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout12 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout12_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler12" qtc_QLayout_setHandler12 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> IO (Ptr (TQLayoutItem t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout12 :: (Ptr (TQLayout x0) -> IO (Ptr (TQLayoutItem t0))) -> IO (FunPtr (Ptr (TQLayout x0) -> IO (Ptr (TQLayoutItem t0)))) foreign import ccall "wrapper" wrapSetHandler_QLayout12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout12 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout12_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 = do x0obj <- qLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QspacerItem_h (QLayout ()) (()) where spacerItem_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_spacerItem cobj_x0 foreign import ccall "qtc_QLayout_spacerItem" qtc_QLayout_spacerItem :: Ptr (TQLayout a) -> IO (Ptr (TQSpacerItem ())) instance QspacerItem_h (QLayoutSc a) (()) where spacerItem_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_spacerItem cobj_x0 instance Qwidget_h (QLayout ()) (()) where widget_h x0 () = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_widget cobj_x0 foreign import ccall "qtc_QLayout_widget" qtc_QLayout_widget :: Ptr (TQLayout a) -> IO (Ptr (TQWidget ())) instance Qwidget_h (QLayoutSc a) (()) where widget_h x0 () = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLayout_widget cobj_x0 instance QsetHandler (QLayout ()) (QLayout x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout13 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout13_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler13" qtc_QLayout_setHandler13 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout13 :: (Ptr (TQLayout x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQLayout x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QLayout13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout13 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout13_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QLayout ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLayout_event cobj_x0 cobj_x1 foreign import ccall "qtc_QLayout_event" qtc_QLayout_event :: Ptr (TQLayout a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QLayoutSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLayout_event cobj_x0 cobj_x1 instance QsetHandler (QLayout ()) (QLayout x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout14 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout14_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QLayout_setHandler14" qtc_QLayout_setHandler14 :: Ptr (TQLayout a) -> CWString -> Ptr (Ptr (TQLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QLayout14 :: (Ptr (TQLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QLayout14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QLayoutSc a) (QLayout x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QLayout14 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QLayout14_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QLayout_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QLayout ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QLayout_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QLayout_eventFilter" qtc_QLayout_eventFilter :: Ptr (TQLayout a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QLayoutSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QLayout_eventFilter cobj_x0 cobj_x1 cobj_x2
keera-studios/hsQt
Qtc/Gui/QLayout_h.hs
bsd-2-clause
63,123
142
19
15,016
21,581
10,307
11,274
-1
-1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE KindSignatures #-} module Control.Unification.Kernel ( Kernel(..) , unify , zonk ) where import Control.Applicative import Control.Monad.Free import Control.Monad (join) import Control.Unification.Class import Data.Foldable as F import Data.Traversable -- Tim Sheard's generic unification via two level types data Kernel (m :: * -> *) (v :: (* -> *) -> *) (f :: * -> *) = Kernel { newVar :: m (v f) , readVar :: v f -> m (Maybe (Free f (v f))) , writeVar :: v f -> Free f (v f) -> m () , eqVar :: v f -> v f -> Bool , occurs :: forall a. m a , mismatch :: forall a. m a } unifyVar :: (Monad m, Alternative m, Unified f) => Kernel m v f -> v f -> Free f (v f) -> m (Free f (v f)) unifyVar k a x = readVar k a >>= \mt -> case mt of Nothing -> do x' <- zonk k x if F.any (eqVar k a) x' then occurs k else x' <$ writeVar k a x' Just y -> do y' <- unify k x y y' <$ writeVar k a y' unify :: (Monad m, Alternative m, Unified f) => Kernel m v f -> Free f (v f) -> Free f (v f) -> m (Free f (v f)) unify k t@(Pure v) (Pure u) | eqVar k v u = return t unify k (Pure a) y = unifyVar k a y unify k x (Pure a) = unifyVar k a x unify k (Free xs) (Free ys) = Free <$> unified (unify k) xs ys <|> mismatch k -- | Eliminate substitutions zonk :: (Monad m, Applicative m, Traversable f) => Kernel m v f -> Free f (v f) -> m (Free f (v f)) zonk k = fmap join . traverse go where go v = readVar k v >>= \mv -> case mv of Nothing -> return $ Pure v Just t -> do t' <- zonk k t t' <$ writeVar k v t' -- path compression
ekmett/unification
src/Control/Unification/Kernel.hs
bsd-3-clause
1,692
0
16
505
836
423
413
41
3
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Main where import Network import System.IO import System.Exit (exitSuccess) import Text.Printf import Control.Monad (forever, when) import Control.Monad.Reader import qualified Network.IRC as IRC import Dice import DBParser -- DiceBot configuration data DBCfg = DBCfg { cfgServer :: IRC.ServerName , cfgPort :: PortNumber , cfgChannel :: IRC.Channel , cfgNickname :: IRC.UserName , cfgHandle :: Handle , cfgDebug :: Bool } deriving Show defaultDBCfg = DBCfg { cfgServer = "irc.freenode.org" , cfgPort = 6667 , cfgChannel = "#haskell-ro" , cfgNickname = "hsDiceBot" , cfgHandle = error "No default socket available" , cfgDebug = False } hostname = cfgNickname defaultDBCfg servername = "*" realname = "A Haskell Dice Bot" -- useful structures for the DiceBot app data DBMsg = DBMsg { msgFrom :: IRC.UserName , msgCmd :: DiceBotCmd , msgPriv :: Bool } deriving (Show, Eq) -- XXX: is it safe to use generalized newtype deriving? newtype DiceBot a = DiceBot { runDiceBot :: ReaderT DBCfg IO a } deriving (Functor, Monad, MonadIO, MonadReader DBCfg) evalDiceBot :: DBCfg -> DiceBot a -> IO a evalDiceBot cfg = flip runReaderT cfg . runDiceBot -- TODO: get config from command line arguments main :: IO () main = do let server = cfgServer defaultDBCfg port = cfgPort defaultDBCfg h <- connectTo server (PortNumber port) hSetBuffering h NoBuffering -- set up handle and run let cfg = defaultDBCfg { cfgHandle = h } evalDiceBot cfg dbmain dbmain :: DiceBot () dbmain = do cfg <- ask let nick = cfgNickname cfg chan = cfgChannel cfg h = cfgHandle cfg write $ IRC.nick nick write $ IRC.user nick hostname servername realname write $ IRC.joinChan chan listen listen :: DiceBot () listen = forever $ do s <- dbGetLine dbgIn s --dbgIn $ show $ IRC.decode s case IRC.decode s of Nothing -> return () Just m -> case IRC.msg_command m of "PRIVMSG" -> do n <- fmap cfgNickname ask let msg = mkDBMsg n m respond msg -- TODO: use a library pong command "PING" -> do let srv = head . IRC.msg_params $ m msg = IRC.Message Nothing "PONG" [srv] write msg _ -> return () respond :: DBMsg -> DiceBot () respond m = do case msgCmd m of Start -> respStart Quit -> respQuit Roll ds -> respRoll ds Bad cmd -> respBad cmd _ -> return () where toNick = if msgPriv m then writeNick $ msgFrom m else writeChan who = if msgPriv m then "You" else msgFrom m -- response functions respStart = writeChan "--- Session start ---" respQuit = do writeChan "--- Session quit ---" write $ IRC.quit (Just "You and your friends are dead.") dbexit respRoll ds = do rs <- roll ds toNick $ who ++ " " ++ "rolled " ++ showDice ds ++ ": " ++ showResult rs ++ " = " ++ show (sum rs) respBad cmd = toNick $ who ++ " " ++ "sent " ++ cmd ++ ": bad command" -- auxiliary functions writeChan :: String -> DiceBot () writeChan s = fmap cfgChannel ask >>= write . flip IRC.privmsg s writeNick :: IRC.UserName -> String -> DiceBot () writeNick n s = write . IRC.privmsg n $ s write :: IRC.Message -> DiceBot () write m = do let raw = IRC.encode m h <- fmap cfgHandle ask liftIO $ hPrintf h "%s\r\n" raw dbgOut raw roll :: [Die] -> DiceBot [Int] roll = liftIO . rollDice dbGetLine :: DiceBot String dbGetLine = fmap cfgHandle ask >>= liftIO . hGetLine dbexit :: DiceBot () dbexit = liftIO $ exitSuccess mkDBMsg :: IRC.UserName -> IRC.Message -> DBMsg mkDBMsg n m = DBMsg usr cmd prv where IRC.NickName usr _ _ = maybe unknown id $ IRC.msg_prefix m cmd = parseCmd . (!! 1) . IRC.msg_params $ m prv = if (head . IRC.msg_params) m == n then True else False unknown = IRC.NickName "(unknown)" Nothing Nothing -- debugging utilities dbgOut :: String -> DiceBot () dbgOut s = do debug <- fmap cfgDebug ask when debug $ liftIO . putStrLn $ "out> " ++ s dbgIn :: String -> DiceBot () dbgIn s = do debug <- fmap cfgDebug ask when debug $ liftIO . putStrLn $ "in> " ++ s
haskell-ro/hs-dicebot
DiceBot.hs
bsd-3-clause
4,259
0
21
1,111
1,387
699
688
124
7
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module Data.Tuple.Quotient where import Data.Proxy import Data.Quotient import Data.List data Permutation instance Ord a => Equiv Permutation (a, a) where type EquivClass Permutation (a, a) = (a, a) toEquivClass _ = normalizeEquivClass (Proxy :: Proxy ((a, a) :/ Permutation)) fromEquivClass _ = id normalizeEquivClass _ (x, y) | x <= y = (x, y) | otherwise = (y, x) instance Ord a => Equiv Permutation (a, a, a) where type EquivClass Permutation (a, a, a) = (a, a, a) toEquivClass _ = normalizeEquivClass (Proxy :: Proxy ((a, a, a) :/ Permutation)) fromEquivClass _ = id normalizeEquivClass _ (x, y, z) = case sort [x,y,z] of [x',y',z'] -> (x', y', z') _ -> error "Unexpected result of sort" instance Ord a => Equiv Permutation (a, a, a, a) where type EquivClass Permutation (a, a, a, a) = (a, a, a, a) toEquivClass _ = normalizeEquivClass (Proxy :: Proxy ((a, a, a, a) :/ Permutation)) fromEquivClass _ = id normalizeEquivClass _ (x, y, z, r) = case sort [x,y,z,r] of [x',y',z',r'] -> (x', y', z', r') _ -> error "Unexpected result of sort" data Cycle instance Ord a => Equiv Cycle (a, a) where type EquivClass Cycle (a, a) = (a, a) toEquivClass _ = normalizeEquivClass (Proxy :: Proxy ((a, a) :/ Cycle)) fromEquivClass _ = id normalizeEquivClass _ (x, y) | x <= y = (x, y) | otherwise = (y, x) instance Ord a => Equiv Cycle (a, a, a) where type EquivClass Cycle (a, a, a) = (a, a, a) toEquivClass _ = normalizeEquivClass (Proxy :: Proxy ((a, a, a) :/ Cycle)) fromEquivClass _ = id normalizeEquivClass _ (x, y, z) | x <= y && x <= z = (x, y, z) | y <= x && y <= z = (y, z, x) | otherwise = (z, x, y) instance Ord a => Equiv Cycle (a, a, a, a) where type EquivClass Cycle (a, a, a, a) = (a, a, a, a) toEquivClass _ = normalizeEquivClass (Proxy :: Proxy ((a, a, a, a) :/ Cycle)) fromEquivClass _ = id normalizeEquivClass _ (x, y, z, r) | x <= y && x <= z && x <= r = (x, y, z, r) | y <= x && y <= z && y <= r = (y, z, r, x) | z <= x && z <= y && z <= r = (z, r, x, y) | otherwise = (r, x, y, z)
mstksg/quotiented
src/Data/Tuple/Quotient.hs
bsd-3-clause
2,438
0
13
730
1,125
634
491
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent.QSemN -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (concurrency) -- -- Quantity semaphores in which each thread may wait for an arbitrary -- \"amount\". -- ----------------------------------------------------------------------------- module Control.Concurrent.QSemN ( -- * General Quantity Semaphores QSemN, -- abstract newQSemN, -- :: Int -> IO QSemN waitQSemN, -- :: QSemN -> Int -> IO () signalQSemN -- :: QSemN -> Int -> IO () ) where import Prelude import Control.Concurrent.MVar -- |A 'QSemN' is a quantity semaphore, in which the available -- \"quantity\" may be signalled or waited for in arbitrary amounts. newtype QSemN = QSemN (MVar (Int,[(Int,MVar ())])) -- |Build a new 'QSemN' with a supplied initial quantity. newQSemN :: Int -> IO QSemN newQSemN init = do sem <- newMVar (init,[]) return (QSemN sem) -- |Wait for the specified quantity to become available waitQSemN :: QSemN -> Int -> IO () waitQSemN (QSemN sem) sz = do (avail,blocked) <- takeMVar sem -- gain ex. access if (avail - sz) >= 0 then -- discharging 'sz' still leaves the semaphore -- in an 'unblocked' state. putMVar sem (avail-sz,blocked) else do block <- newEmptyMVar putMVar sem (avail, blocked++[(sz,block)]) takeMVar block -- |Signal that a given quantity is now available from the 'QSemN'. signalQSemN :: QSemN -> Int -> IO () signalQSemN (QSemN sem) n = do (avail,blocked) <- takeMVar sem (avail',blocked') <- free (avail+n) blocked putMVar sem (avail',blocked') where free avail [] = return (avail,[]) free avail ((req,block):blocked) | avail >= req = do putMVar block () free (avail-req) blocked | otherwise = do (avail',blocked') <- free avail blocked return (avail',(req,block):blocked')
OS2World/DEV-UTIL-HUGS
libraries/Control/Concurrent/QSemN.hs
bsd-3-clause
2,104
10
14
434
497
272
225
35
2
{-# LANGUAGE FlexibleContexts #-} module Competition.Generic where import Data.IntMap as IntMap import Data.STRef import Data.Foldable import Data.Monoid import Control.Monad.ST import Control.Monad.STM import Control.Monad.Reader import Control.Monad.Base import Control.Concurrent.STM.TVar foldableToIntMap :: Foldable f => f a -> IntMap a foldableToIntMap xs = runST $ do k <- newSTRef 0 runReaderT (foldlM go mempty xs) k where go :: ( MonadReader (STRef s Int) m , MonadBase (ST s) m ) => IntMap a -> a -> m (IntMap a) go acc x = do k <- ask i <- liftBase $ readSTRef k liftBase $ modifySTRef k (+1) return $ IntMap.insert i x acc foldableToIntMap' :: Foldable f => f a -> IntMap a foldableToIntMap' xs = runST $ do k <- newSTRef 0 runReaderT (foldlM go mempty xs) k where go :: ( MonadReader (STRef s Int) m , MonadBase (ST s) m ) => IntMap a -> a -> m (IntMap a) go acc x = do k <- ask i <- liftBase $ readSTRef k liftBase $ modifySTRef' k (+1) return $ IntMap.insert i x acc foldableToIntMapSTM :: Foldable f => f a -> IO (IntMap a) foldableToIntMapSTM xs = atomically $ do k <- newTVar 0 runReaderT (foldlM go mempty xs) k where go :: ( MonadReader (TVar Int) m , MonadBase STM m ) => IntMap a -> a -> m (IntMap a) go acc x = do k <- ask i <- liftBase $ readTVar k liftBase $ modifyTVar' k (+1) return $ IntMap.insert i x acc
athanclark/listvsgeneric
src/Competition/Generic.hs
bsd-3-clause
1,523
0
12
439
613
300
313
48
1
-- | -- Module : $Header$ -- Copyright : (c) 2013-2014 Galois, Inc. -- License : BSD3 -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable {-# LANGUAGE ScopedTypeVariables #-} module Cryptol.Symbolic where import Control.Applicative import Control.Monad (foldM, liftM2, replicateM, when) import Control.Monad.Fix (mfix) import Control.Monad.IO.Class import Control.Monad.Reader (ask, local) import qualified Data.Map as Map import Data.Maybe (fromJust) import Data.Monoid (Monoid(..)) import Data.Traversable (traverse) import qualified Control.Exception as X import qualified Data.SBV as SBV import Data.SBV (SBool) import qualified Cryptol.ModuleSystem as M import qualified Cryptol.ModuleSystem.Env as M import Cryptol.Symbolic.BitVector import Cryptol.Symbolic.Prims import Cryptol.Symbolic.Value import qualified Cryptol.Eval.Value as Eval import Cryptol.Eval.Value (TValue, isTSeq) import qualified Cryptol.Eval.Type (evalType) import qualified Cryptol.Eval.Env (EvalEnv(..)) import Cryptol.TypeCheck.AST import Cryptol.Utils.PP import Cryptol.Utils.Panic(panic) -- External interface ---------------------------------------------------------- lookupProver :: String -> SBV.SMTConfig lookupProver "cvc4" = SBV.cvc4 lookupProver "yices" = SBV.yices lookupProver "z3" = SBV.z3 lookupProver s = error $ "invalid prover: " ++ s prove :: (String, Bool, Bool, String) -> (Expr, Schema) -> M.ModuleCmd () prove (proverName, useSolverIte, verbose, input) (expr, schema) = protectStack useSolverIte $ \modEnv -> do let extDgs = allDeclGroups modEnv let prover = lookupProver proverName case predArgTypes schema of Left msg -> do putStrLn msg return (Right ((), modEnv), []) Right ts -> do when verbose $ putStrLn "Simulating..." let runE = do args <- mapM forallFinType ts env <- evalDecls emptyEnv extDgs v <- evalExpr env expr b <- foldM vApply v args return (fromVBit b) let simenv = SimEnv { simConfig = prover , simPath = SBV.true , simIteSolver = useSolverIte , simVerbose = verbose } result <- SBV.proveWith prover $ do b <- runTheMonad runE simenv when verbose $ liftIO $ putStrLn $ "Calling " ++ proverName ++ "..." return b case result of SBV.ThmResult (SBV.Satisfiable {}) -> do let Right (_, cws) = SBV.getModel result let (vs, _) = parseValues ts cws let ppOpts = Eval.defaultPPOpts let doc = hsep (text input : map (pp . Eval.WithBase ppOpts) vs) print $ doc <+> text "= False" SBV.ThmResult (SBV.Unsatisfiable {}) -> do putStrLn "Q.E.D." SBV.ThmResult _ -> do print result return (Right ((), modEnv), []) sat :: (String, Bool, Bool, String) -> (Expr, Schema) -> M.ModuleCmd () sat (proverName, useSolverIte, verbose, input) (expr, schema) = protectStack useSolverIte $ \modEnv -> do let extDgs = allDeclGroups modEnv let prover = lookupProver proverName case predArgTypes schema of Left msg -> do putStrLn msg return (Right ((), modEnv), []) Right ts -> do when verbose $ putStrLn "Simulating..." let runE = do args <- mapM existsFinType ts env <- evalDecls emptyEnv extDgs v <- evalExpr env expr b <- foldM vApply v args return (fromVBit b) let simenv = SimEnv { simConfig = prover , simPath = SBV.true , simIteSolver = useSolverIte , simVerbose = verbose } result <- SBV.satWith prover $ do b <- runTheMonad runE simenv when verbose $ liftIO $ putStrLn $ "Calling " ++ proverName ++ "..." return b case result of SBV.SatResult (SBV.Satisfiable {}) -> do let Right (_, cws) = SBV.getModel result let (vs, _) = parseValues ts cws let ppOpts = Eval.defaultPPOpts let doc = hsep (text input : map (pp . Eval.WithBase ppOpts) vs) print $ doc <+> text "= True" SBV.SatResult (SBV.Unsatisfiable {}) -> do putStrLn "Unsatisfiable." SBV.SatResult _ -> do print result return (Right ((), modEnv), []) protectStack :: Bool -> M.ModuleCmd () -> M.ModuleCmd () protectStack usingITE cmd modEnv = X.catchJust isOverflow (cmd modEnv) handler where isOverflow X.StackOverflow = Just () isOverflow _ = Nothing msg | usingITE = msgBase | otherwise = msgBase ++ "\n" ++ "Using ':set iteSolver=on' might help." msgBase = "Symbolic evaluation failed to terminate." handler () = do putStrLn msg return (Right ((), modEnv), []) parseValues :: [FinType] -> [SBV.CW] -> ([Eval.Value], [SBV.CW]) parseValues [] cws = ([], cws) parseValues (t : ts) cws = (v : vs, cws'') where (v, cws') = parseValue t cws (vs, cws'') = parseValues ts cws' parseValue :: FinType -> [SBV.CW] -> (Eval.Value, [SBV.CW]) parseValue FTBit [] = error "parseValue" parseValue FTBit (cw : cws) = (Eval.VBit (SBV.fromCW cw), cws) parseValue (FTSeq n FTBit) (cw : cws) | SBV.isBounded cw = (Eval.VWord (toInteger n) (SBV.fromCW cw), cws) | otherwise = error "parseValue" parseValue (FTSeq n FTBit) cws = (Eval.VSeq True vs, cws') where (vs, cws') = parseValues (replicate n FTBit) cws parseValue (FTSeq n t) cws = (Eval.VSeq False vs, cws') where (vs, cws') = parseValues (replicate n t) cws parseValue (FTTuple ts) cws = (Eval.VTuple (length vs) vs, cws') where (vs, cws') = parseValues ts cws parseValue (FTRecord fs) cws = (Eval.VRecord (zip ns vs), cws') where (ns, ts) = unzip fs (vs, cws') = parseValues ts cws allDeclGroups :: M.ModuleEnv -> [DeclGroup] allDeclGroups = concatMap mDecls . M.loadedModules data FinType = FTBit | FTSeq Int FinType | FTTuple [FinType] | FTRecord [(Name, FinType)] numType :: Type -> Maybe Int numType (TCon (TC (TCNum n)) []) | 0 <= n && n <= toInteger (maxBound :: Int) = Just (fromInteger n) numType (TUser _ _ t) = numType t numType _ = Nothing finType :: Type -> Maybe FinType finType ty = case ty of TCon (TC TCBit) [] -> Just FTBit TCon (TC TCSeq) [n, t] -> FTSeq <$> numType n <*> finType t TCon (TC (TCTuple _)) ts -> FTTuple <$> traverse finType ts TRec fields -> FTRecord <$> traverse (traverseSnd finType) fields TUser _ _ t -> finType t _ -> Nothing predArgTypes :: Schema -> Either String [FinType] predArgTypes schema@(Forall ts ps ty) | null ts && null ps = case go ty of Just fts -> Right fts Nothing -> Left $ "Not a valid predicate type:\n" ++ show (pp schema) | otherwise = Left $ "Not a monomorphic type:\n" ++ show (pp schema) where go (TCon (TC TCBit) []) = Just [] go (TCon (TC TCFun) [ty1, ty2]) = (:) <$> finType ty1 <*> go ty2 go (TUser _ _ t) = go t go _ = Nothing forallFinType :: FinType -> TheMonad Value forallFinType ty = case ty of FTBit -> VBit <$> liftSymbolic SBV.forall_ FTSeq n FTBit -> VWord <$> liftSymbolic (forallBV_ n) FTSeq n t -> vSeq <$> replicateM n (mkThunk t) FTTuple ts -> VTuple <$> mapM mkThunk ts FTRecord fs -> VRecord <$> mapM (traverseSnd mkThunk) fs where mkThunk :: FinType -> TheMonad Thunk mkThunk t = Ready <$> forallFinType t existsFinType :: FinType -> TheMonad Value existsFinType ty = case ty of FTBit -> VBit <$> liftSymbolic SBV.exists_ FTSeq n FTBit -> VWord <$> liftSymbolic (existsBV_ n) FTSeq n t -> vSeq <$> replicateM n (mkThunk t) FTTuple ts -> VTuple <$> mapM mkThunk ts FTRecord fs -> VRecord <$> mapM (traverseSnd mkThunk) fs where mkThunk :: FinType -> TheMonad Thunk mkThunk t = Ready <$> existsFinType t -- Simulation environment ------------------------------------------------------ data Env = Env { envVars :: Map.Map QName Thunk , envTypes :: Map.Map TVar TValue } instance Monoid Env where mempty = Env { envVars = Map.empty , envTypes = Map.empty } mappend l r = Env { envVars = Map.union (envVars l) (envVars r) , envTypes = Map.union (envTypes l) (envTypes r) } emptyEnv :: Env emptyEnv = Env Map.empty Map.empty -- | Bind a variable in the evaluation environment. bindVar :: (QName, Thunk) -> Env -> Env bindVar (n, thunk) env = env { envVars = Map.insert n thunk (envVars env) } -- | Lookup a variable in the environment. lookupVar :: QName -> Env -> Maybe Thunk lookupVar n env = Map.lookup n (envVars env) -- | Bind a type variable of kind *. bindType :: TVar -> TValue -> Env -> Env bindType p ty env = env { envTypes = Map.insert p ty (envTypes env) } -- | Lookup a type variable. lookupType :: TVar -> Env -> Maybe TValue lookupType p env = Map.lookup p (envTypes env) -- Path conditions ------------------------------------------------------------- thenBranch :: SBool -> TheMonad a -> TheMonad a thenBranch s = local $ \e -> e { simPath = (SBV.&&&) s (simPath e) } elseBranch :: SBool -> TheMonad a -> TheMonad a elseBranch s = thenBranch (SBV.bnot s) isFeasible :: SBool -> TheMonad Bool isFeasible path | path `SBV.isConcretely` (== False) = return False | path `SBV.isConcretely` (== True) = return True | otherwise = do useSolverIte <- simIteSolver <$> ask verbose <- simVerbose <$> ask config <- simConfig <$> ask if useSolverIte then do when verbose $ liftIO $ putStrLn "Testing branch condition with solver..." res <- liftSymbolic $ SBV.internalIsTheoremWith config (Just 5) (SBV.bnot path) case res of Just isThm -> do let msg = if isThm then "Infeasible." else "Feasible." when verbose $ liftIO $ putStrLn msg return (not isThm) Nothing -> do when verbose $ liftIO $ putStrLn "Undetermined." return True else return True evalIf :: SBool -> TheMonad Value -> TheMonad Value -> TheMonad Value evalIf s m1 m2 = do path <- simPath <$> ask let path1 = (SBV.&&&) path s let path2 = (SBV.&&&) path (SBV.bnot s) c1 <- isFeasible path1 if not c1 then elseBranch s m2 else do c2 <- isFeasible path2 if not c2 then thenBranch s m1 else do v1 <- thenBranch s m1 v2 <- elseBranch s m2 ite s v1 v2 -- Expressions ----------------------------------------------------------------- evalExpr :: Env -> Expr -> TheMonad Value evalExpr env expr = case expr of ECon econ -> return $ evalECon econ EList es _ty -> vSeq <$> traverse eval' es ETuple es -> VTuple <$> traverse eval' es ERec fields -> VRecord <$> traverse (traverseSnd eval') fields ESel e sel -> evalSel sel =<< eval e EIf b e1 e2 -> do VBit s <- evalExpr env b evalIf s (evalExpr env e1) (evalExpr env e2) EComp ty e mss -> evalComp env (evalType env ty) e mss EVar n -> force $ fromJust (lookupVar n env) -- TODO: how to deal with uninterpreted functions? ETAbs tv e -> return $ VPoly $ \ty -> evalExpr (bindType (tpVar tv) ty env) e ETApp e ty -> do VPoly f <- eval e f (evalType env ty) EApp e1 e2 -> do VFun f <- eval e1 f =<< eval' e2 EAbs n _ty e -> return $ VFun $ \th -> evalExpr (bindVar (n, th) env) e EProofAbs _prop e -> eval e EProofApp e -> eval e ECast e _ty -> eval e EWhere e ds -> do env' <- evalDecls env ds evalExpr env' e where eval e = evalExpr env e eval' e = delay (evalExpr env e) evalType :: Env -> Type -> TValue evalType env ty = Cryptol.Eval.Type.evalType env' ty where env' = Cryptol.Eval.Env.EvalEnv Map.empty (envTypes env) evalSel :: Selector -> Value -> TheMonad Value evalSel sel v = case sel of TupleSel n _ -> case v of VTuple xs -> force $ xs !! (n - 1) -- 1-based indexing VNil -> return VNil VCons {} -> liftList v VFun f -> return $ VFun $ \x -> evalSel sel =<< f x RecordSel n _ -> case v of VRecord bs -> force $ fromJust (lookup n bs) VNil -> return VNil VCons {} -> liftList v VFun f -> return $ VFun $ \x -> evalSel sel =<< f x ListSel n _ -> case v of --VSeq xs -> force $ xs !! n -- 0-based indexing VWord s -> return $ VBit (SBV.sbvTestBit s n) _ -> let go :: Int -> Value -> TheMonad Thunk go 0 (VCons x _) = return x go i (VCons _ y) = go (i - 1) =<< force y go _ _ = error "internal error" in force =<< go n v where liftList VNil = return VNil liftList (VCons x xs) = do x' <- delay (evalSel sel =<< force x) xs' <- delay (liftList =<< force xs) return (VCons x' xs') liftList _ = panic "Cryptol.Symbolic.evalSel" ["Malformed list, while lifting selector"] -- Declarations ---------------------------------------------------------------- evalDecls :: Env -> [DeclGroup] -> TheMonad Env evalDecls = foldM evalDeclGroup evalDeclGroup :: Env -> DeclGroup -> TheMonad Env evalDeclGroup env dg = case dg of NonRecursive d -> do binding <- evalDecl env d return $ bindVar binding env Recursive ds -> mfix $ \env' -> do bindings <- traverse (evalDecl env') ds return $ foldr bindVar env bindings evalDecl :: Env -> Decl -> TheMonad (QName, Thunk) evalDecl env d = do thunk <- delay $ evalExpr env (dDefinition d) return (dName d, thunk) -- List Comprehensions --------------------------------------------------------- data LazySeq a = LSNil | LSCons a (MLazySeq a) type MLazySeq a = TheMonad (LazySeq a) instance Functor LazySeq where fmap _ LSNil = LSNil fmap f (LSCons x xs) = LSCons (f x) (fmap f <$> xs) singleLS :: a -> LazySeq a singleLS x = LSCons x (return LSNil) zipWithLS :: (a -> b -> c) -> LazySeq a -> LazySeq b -> LazySeq c zipWithLS f (LSCons x xs) (LSCons y ys) = LSCons (f x y) (liftM2 (zipWithLS f) xs ys) zipWithLS _ _ _ = LSNil repeatLS :: a -> LazySeq a repeatLS x = xs where xs = LSCons x (return xs) transposeLS :: [LazySeq a] -> LazySeq [a] transposeLS = foldr (zipWithLS (:)) (repeatLS []) appendLS :: LazySeq a -> LazySeq a -> LazySeq a appendLS LSNil ys = ys appendLS (LSCons x xs') ys = LSCons x $ do xs <- xs' return (appendLS xs ys) appendMLS :: MLazySeq a -> MLazySeq a -> MLazySeq a appendMLS xs ys = do l <- xs case l of LSNil -> ys LSCons x xs' -> return (LSCons x (appendMLS xs' ys)) bindMLS :: MLazySeq a -> (a -> MLazySeq b) -> MLazySeq b bindMLS xs k = do l <- xs case l of LSNil -> return LSNil LSCons x xs' -> appendMLS (k x) (bindMLS xs' k) toLazySeq :: Value -> LazySeq Thunk toLazySeq (VCons th1 th2) = LSCons th1 (toLazySeq <$> force th2) toLazySeq VNil = LSNil toLazySeq (VWord w) = go (SBV.bitSize w - 1) where go i | i < 0 = LSNil | otherwise = LSCons (Ready (VBit (SBV.sbvTestBit w i))) (return (go (i - 1))) toLazySeq _ = error "toLazySeq" toSeq :: LazySeq Thunk -> TheMonad Value toSeq LSNil = return VNil toSeq (LSCons x xs) = VCons x <$> delay (toSeq =<< xs) evalComp :: Env -> TValue -> Expr -> [[Match]] -> TheMonad Value evalComp env seqty body ms = case isTSeq seqty of Nothing -> evalPanic "Cryptol.Eval" [ "evalComp given a non sequence", show seqty ] Just (_len, _el) -> do -- generate a new environment for each iteration of each parallel branch (benvs :: [LazySeq Env]) <- mapM (branchEnvs env) ms -- take parallel slices of each environment. let slices :: LazySeq [Env] slices = transposeLS benvs -- join environments to produce environments at each step through the process. let envs :: LazySeq Env envs = fmap mconcat slices thunks <- bindMLS (return envs) (\e -> singleLS <$> delay (evalExpr e body)) toSeq thunks -- | Turn a list of matches into the final environments for each iteration of -- the branch. branchEnvs :: Env -> [Match] -> MLazySeq Env branchEnvs env matches = case matches of [] -> return (singleLS env) m : ms -> bindMLS (evalMatch env m) (\env' -> branchEnvs env' ms) -- | Turn a match into the list of environments it represents. evalMatch :: Env -> Match -> MLazySeq Env evalMatch env m = case m of From n _ty expr -> do ths <- toLazySeq <$> evalExpr env expr return $ fmap (\th -> bindVar (n, th) env) ths Let d -> do binding <- evalDecl env d return $ singleLS (bindVar binding env)
dylanmc/cryptol
src/Cryptol/Symbolic.hs
bsd-3-clause
18,131
0
29
5,842
6,293
3,106
3,187
377
16
{-# LANGUAGE OverloadedStrings, RecordWildCards #-} {-# LANGUAGE OverloadedStrings, RecordWildCards, ScopedTypeVariables, FlexibleInstances #-} module Main where import Control.Applicative ((*>)) import Data.Conduit import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import Data.Conduit.Process (ClosedStream (..), streamingProcess, proc, waitForStreamingProcess) import System.IO (stdin) import qualified Data.ByteString.Char8 as B8 import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Text.Encoding as T import Data.Map (Map) import qualified Data.Map as M import Data.Monoid main = do conduitQuery "select * from users" >>= T.putStrLn conduitQuery :: String -> IO Text conduitQuery query = do (ClosedStream, fromProcess, ClosedStream, cph) <- streamingProcess (proc "mysql" $ [ "-uroot" , "redesign" , "-t" , "-e" , query ]) output <- runConduit $ fromProcess =$= CL.map T.decodeUtf8 =$ CL.consume return $ T.unlines output
spacewaffle/ether
haskell/exp.hs
bsd-3-clause
1,305
0
11
412
267
163
104
33
1
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings #-} module Utils where import System.IO import System.Environment import Data.Time.Clock import Data.Time.Calendar import qualified Control.Exception as E import Control.Exception.Base (try) import qualified Data.Text as T import qualified Filesystem as FS import qualified Filesystem.Path.CurrentOS as FP import Filesystem.Path ((</>), (<.>)) errorsToStderr :: IO () -> IO () errorsToStderr action = E.catch action (\(e :: E.SomeException) -> appPutStrLn stderr (show e)) appPutStrLn :: Handle -> String -> IO () appPutStrLn handle string = do progName <- normalizedProgName hPutStrLn handle ("\n" ++ T.unpack progName ++ ": " ++ string) normalizedProgName :: IO T.Text normalizedProgName = do pn <- getProgName return (T.pack $ takeWhile (/= '.') pn) appDataDirectory = do pn <- normalizedProgName hd <- FS.getHomeDirectory return $ hd </> FP.fromText (T.append "." pn) trashDirectory = do ad <- appDataDirectory return $ ad </> "trash" defaultDiff = "gvimdiff -f" getCurrentDate :: IO (Integer,Int,Int) -- :: (year,month,day) getCurrentDate = getCurrentTime >>= return . toGregorian . utctDay getEnvOrDefault :: String -> String -> IO String getEnvOrDefault envVar defaultValue = do result <- try $ getEnv envVar case result of Right value -> return value Left (_ :: IOError) -> return defaultValue toText :: FP.FilePath -> T.Text toText filePath = either id id (FP.toText filePath) toString :: FP.FilePath -> String toString = T.unpack . toText -- splits filePath into (directory, baseName, extension) splitFilePath :: FP.FilePath -> (FP.FilePath, FP.FilePath, T.Text) splitFilePath filePath = (dir, bname, ext) where dir = FP.directory filePath bname = FP.basename filePath ext = allExtensions filePath allExtensions :: FP.FilePath -> T.Text allExtensions = (T.intercalate ".") . FP.extensions replaceBaseName :: FP.FilePath -> FP.FilePath -> FP.FilePath replaceBaseName filePath newBaseName | T.null ext = dir </> newBaseName | otherwise = dir </> newBaseName <.> ext where dir = FP.directory filePath ext = allExtensions filePath
dan-t/confsolve
Utils.hs
bsd-3-clause
2,201
0
13
402
690
364
326
57
2
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.ViewportArray -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.ViewportArray ( -- * Extension Support glGetARBViewportArray, gl_ARB_viewport_array, -- * Enums pattern GL_DEPTH_RANGE, pattern GL_FIRST_VERTEX_CONVENTION, pattern GL_LAST_VERTEX_CONVENTION, pattern GL_LAYER_PROVOKING_VERTEX, pattern GL_MAX_VIEWPORTS, pattern GL_PROVOKING_VERTEX, pattern GL_SCISSOR_BOX, pattern GL_SCISSOR_TEST, pattern GL_UNDEFINED_VERTEX, pattern GL_VIEWPORT, pattern GL_VIEWPORT_BOUNDS_RANGE, pattern GL_VIEWPORT_INDEX_PROVOKING_VERTEX, pattern GL_VIEWPORT_SUBPIXEL_BITS, -- * Functions glDepthRangeArrayv, glDepthRangeIndexed, glGetDoublei_v, glGetFloati_v, glScissorArrayv, glScissorIndexed, glScissorIndexedv, glViewportArrayv, glViewportIndexedf, glViewportIndexedfv ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/ARB/ViewportArray.hs
bsd-3-clause
1,293
0
5
176
144
97
47
30
0
-- -- Copyright © 2013-2015 Anchor Systems, Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is -- made available to you by its authors as open source software: -- you can redistribute it and/or modify it under the terms of -- the 3-clause BSD licence. -- -- | Description: Check with "cabal check". module Main where import Control.Applicative import Control.Monad import Data.Char import Data.Foldable import Data.List hiding (and, notElem) import Data.Maybe import Data.Monoid import Data.Traversable import Git.Vogue.PluginCommon import Language.Haskell.GhcMod import Prelude hiding (and, notElem) import System.Exit main :: IO () main = f =<< getPluginCommand "Check your Haskell project for ghc-mod problems." "git-vogue-ghc-mod - check for ghc-mod problems" where f CmdName = putStrLn "ghc-mod" f (CmdCheck check_fs all_fs) = do -- Have to change to the project directory for each ghc-mod run or it -- will be sad. -- -- We run ghcModCheck in each, which will exit on the first failure. rs <- forProjects (hsProjects check_fs all_fs) $ \fs -> -- HLint.hs is weird and more of a config file than a source file, so -- ghc-mod doesn't like it. -- -- Setup.hs can import cabal things magically, without requiring it to -- be mentioned in cabal (which ghc-mod hates) ghcModCheck $ filter (\x -> not ("HLint.hs" `isSuffixOf` x) && not ("Setup.hs" `isSuffixOf` x) && ".hs" `isSuffixOf` x) fs unless (and rs) exitFailure f CmdFix{} = do outputBad $ "There are outstanding ghc-mod failures, you need to fix this " <> "manually and then re-run check" exitFailure -- | Try to help the user out with some munging of error messages explain :: String -> String explain s -- A terrible heuristic, but it may help some people | "test" `isInfixOf` fmap toLower s && "hidden package" `isInfixOf` s = s <> "\n\tSuggestion: cabal configure --enable-tests\n" | "bench" `isInfixOf` fmap toLower s && "hidden package" `isInfixOf` s = s <> "\n\tSuggestion: cabal configure --enable-benchmarks\n" | "hGetContents: invalid argument" `isInfixOf` s = s <> "\n\tSuggestion: use cabal < 1.22\n" | otherwise = s -- | ghc-mod check all of the given files from the current directory -- -- This will print out output, and return a bool representing success. ghcModCheck :: [FilePath] -> IO Bool ghcModCheck files = do -- We can't actually check all at once, or ghc-mod gets confused, so we -- traverse (r,_) <- runGhcModT defaultOptions (traverse (check . pure) files) -- Seriously guys? Eithers within eithers? warn_errs <- case r of -- This is some kind of outer-error, we don't fail on it. Left e -> do outputUnfortunate . lineWrap 74 $ show e return [] -- And these are the warnings and errors. Right rs -> return rs -- Traverse the errors, picking errors and warnings out maybe_ws <- for warn_errs $ \warn_err -> case warn_err of -- Errors in files Left e -> return . Just $ explain e -- Warnings, sometimes empty strings Right warn -> return $ if null warn then Nothing else Just warn let warns = catMaybes maybe_ws if null warns then do outputGood $ "Checked " <> show (length files) <> " file(s)" return True else do traverse_ outputBad warns return False
olorin/git-vogue
src/git-vogue-ghc-mod.hs
bsd-3-clause
3,937
0
21
1,301
651
344
307
61
5
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE OverloadedStrings #-} import Prelude import Control.Applicative import Control.Arrow ((***)) import Control.Monad.IO.Class import Data.Aeson import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LBS import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.Maybe import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time.LocalTime.TimeZone.Series import Data.String import TextShow import Text.Read (readMaybe) import Snap.Core import Snap.Http.Server import Duckling.Core import Duckling.Data.TimeZone main :: IO () main = do tzs <- loadTimeZoneSeries "/usr/share/zoneinfo/" quickHttpServe $ ifTop (writeBS "quack!") <|> route [ ("targets", method GET targetsHandler) , ("parse", method POST $ parseHandler tzs) ] -- | Return which languages have which dimensions targetsHandler :: Snap () targetsHandler = do modifyResponse $ setHeader "Content-Type" "application/json" writeLBS $ encode $ HashMap.fromList . map dimText $ HashMap.toList supportedDimensions where dimText :: (Lang, [Some Dimension]) -> (Text, [Text]) dimText = (Text.toLower . showt) *** map (\(This d) -> toName d) -- | Parse some text into the given dimensions parseHandler :: HashMap Text TimeZoneSeries -> Snap () parseHandler tzs = do modifyResponse $ setHeader "Content-Type" "application/json" t <- getPostParam "text" l <- getPostParam "lang" ds <- getPostParam "dims" tz <- getPostParam "tz" case t of Nothing -> do modifyResponse $ setResponseStatus 422 "Bad Input" writeBS "Need a 'text' parameter to parse" Just tx -> do refTime <- liftIO $ currentReftime tzs $ fromMaybe defaultTimeZone $ Text.decodeUtf8 <$> tz let context = Context { referenceTime = refTime , lang = parseLang l } dimParse = fromMaybe [] $ decode $ LBS.fromStrict $ fromMaybe "" ds dims = mapMaybe fromName dimParse parsedResult = parse (Text.decodeUtf8 tx) context dims writeLBS $ encode parsedResult where defaultLang = EN defaultTimeZone = "America/Los_Angeles" parseLang :: Maybe ByteString -> Lang parseLang l = fromMaybe defaultLang $ l >>= readMaybe . Text.unpack . Text.toUpper . Text.decodeUtf8
rfranek/duckling
exe/ExampleMain.hs
bsd-3-clause
2,710
0
19
564
687
360
327
64
2
{-# LANGUAGE TypeOperators #-} -- | This is the top level namespace for the API. module PureFlowy.Api where import qualified Network.Wai.Handler.Warp as Warp import Servant import qualified PureFlowy.Api.Files as Files import qualified PureFlowy.Api.Todos as Todos type Api = Todos.Api :<|> Files.Endpoint application :: Application application = serve (Proxy :: Proxy Api) (Todos.handler :<|> Files.handler) main :: IO () main = Warp.run 8081 application
parsonsmatt/pureflowy
src/PureFlowy/Api.hs
bsd-3-clause
480
0
8
87
110
68
42
13
1
module Codex.Lib.Network.TCP.EchoServer ( runEchoServer ) where import Codex.Lib.Network.TCP.Server import Prelude hiding (catch) import Network import System.IO import Control.Monad import Control.Exception as E import Control.Concurrent import Control.Concurrent.MVar runEchoServer :: IO TCPServer runEchoServer = do let serv = buildTCPServer 7 (-1) cb'echo runTCPServer serv cb'echo :: Handle -> Int -> IO () cb'echo h id' = do l <- hGetLine h hPutStrLn h l cb'echo h id'
adarqui/Codex
src/Codex/Lib/Network/TCP/EchoServer.hs
bsd-3-clause
485
0
12
75
156
85
71
19
1
module Game.Step.Internal where data Dirs a = Dirs { dirUp :: !a , dirRight :: !a , dirDown :: !a , dirLeft :: !a }
mutantmell/StepItUp
src/Game/Step/Internal.hs
bsd-3-clause
193
0
9
102
45
27
18
13
0
{-# LANGUAGE OverloadedStrings #-} import Music.Prelude -- A simple subject subj = times 20 $ scat [c,d,e,f]|/8 |> scat [g,fs]|/2 -- The music = id $ title "Dynamics" $ composer "Anonymous" $ fmap (over dynamics (! 0)) $  rcat $ map (\phase -> level (stretch phase sine*fff) $ subj) [5.0,5.2..6.0] main = open music
music-suite/music-preludes
examples/dynamics.hs
bsd-3-clause
337
13
12
75
165
80
85
10
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DataKinds #-} module LDrive.Serialize ( adcSender , dccalSender , encoderSender , svmSender , currentControlSender , sampleSender , Sender , serializeTowerDeps , rateDivider ) where import Ivory.Language import Ivory.Stdlib import Ivory.Tower import Data.Char (ord) import Ivory.Tower.HAL.Bus.Interface import Ivory.Serialize import qualified HXStream.Ivory as HX import LDrive.Types serializeTowerDeps :: Tower e () serializeTowerDeps = do towerDepends ldriveTypes towerModule ldriveTypes towerDepends serializeModule towerModule serializeModule mapM_ towerArtifact serializeArtifacts -- divide rate of incoming messages by `r` rateDivider :: (IvoryArea a, IvoryZero a) => Integer -> ChanOutput a -> Tower e (ChanOutput a) rateDivider r c = do c' <- channel monitor "halfRate" $ do st <- stateInit "s" (ival (0 :: Uint32)) handler c "halfRate" $ do e <- emitter (fst c') 1 callback $ \v -> do s <- deref st ifte_ (s >=? fromIntegral (r - 1)) (emit e v >> store st 0) (store st (s + 1)) return (snd c') type Sender e a = ChanOutput a -> BackpressureTransmit UARTBuffer ('Stored IBool) -> Monitor e () -- pack and marshal samples to backpressure transmit sampleSender :: (ANat len, IvoryArea a, IvoryZero a, Packable a) => Char -> Proxy len -> Sender e a sampleSender tag len c out = do buf <- stateInit "buf" $ izerolen len handler c "sender" $ do e <- emitter (backpressureTransmit out) 1 callback $ \ sample -> do packInto buf 0 sample str <- local izero HX.encodeString (fromIntegral $ ord tag) (constRef buf) str emit e $ constRef str adcSender :: Sender e ('Struct "adc") adcSender = sampleSender 'A' (Proxy :: Proxy 12) dccalSender :: Sender e ('Struct "dccal") dccalSender = sampleSender 'D' (Proxy :: Proxy 8) encoderSender :: Sender e ('Struct "encoder") encoderSender = sampleSender 'E' (Proxy :: Proxy 17) svmSender :: Sender e ('Struct "svm") svmSender = sampleSender 'S' (Proxy :: Proxy 16) currentControlSender :: Sender e ('Struct "current_control") currentControlSender = sampleSender 'C' (Proxy :: Proxy 85)
sorki/odrive
src/LDrive/Serialize.hs
bsd-3-clause
2,285
0
23
530
762
380
382
67
1
{-# OPTIONS_HADDOCK hide #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.DataType -- Copyright : (c) Sven Panne 2002-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- This is a purely internal module for (un-)marshaling DataType. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.DataType ( DataType(..), marshalDataType, unmarshalDataType, DataTypeType(..), marshalDataTypeType, unmarshalDataTypeType ) where import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- -- basically table 3.2 (pixel data type parameter) plus a few additions data DataType = UnsignedByte | Byte | UnsignedShort | Short | UnsignedInt | Int | HalfFloat | Float | UnsignedByte332 | UnsignedByte233Rev | UnsignedShort565 | UnsignedShort565Rev | UnsignedShort4444 | UnsignedShort4444Rev | UnsignedShort5551 | UnsignedShort1555Rev | UnsignedInt8888 | UnsignedInt8888Rev | UnsignedInt1010102 | UnsignedInt2101010Rev | UnsignedInt248 | UnsignedInt10f11f11fRev | UnsignedInt5999Rev | Float32UnsignedInt248Rev | Bitmap -- pixel data, deprecated in 3.1 | UnsignedShort88 -- MESA_ycbcr_texture/APPLE_ycbcr_422 | UnsignedShort88Rev -- MESA_ycbcr_texture/APPLE_ycbcr_422 | Double -- vertex arrays (EXT_vertex_array, now core) | TwoBytes -- CallLists | ThreeBytes -- CallLists | FourBytes -- CallLists deriving ( Eq, Ord, Show ) marshalDataType :: DataType -> GLenum marshalDataType x = case x of UnsignedByte -> gl_UNSIGNED_BYTE Byte -> gl_BYTE UnsignedShort -> gl_UNSIGNED_SHORT Short -> gl_SHORT UnsignedInt -> gl_UNSIGNED_INT Int -> gl_INT HalfFloat -> gl_HALF_FLOAT Float -> gl_FLOAT UnsignedByte332 -> gl_UNSIGNED_BYTE_3_3_2 UnsignedByte233Rev -> gl_UNSIGNED_BYTE_2_3_3_REV UnsignedShort565 -> gl_UNSIGNED_SHORT_5_6_5 UnsignedShort565Rev -> gl_UNSIGNED_SHORT_5_6_5_REV UnsignedShort4444 -> gl_UNSIGNED_SHORT_4_4_4_4 UnsignedShort4444Rev -> gl_UNSIGNED_SHORT_4_4_4_4_REV UnsignedShort5551 -> gl_UNSIGNED_SHORT_5_5_5_1 UnsignedShort1555Rev -> gl_UNSIGNED_SHORT_1_5_5_5_REV UnsignedInt8888 -> gl_UNSIGNED_INT_8_8_8_8 UnsignedInt8888Rev -> gl_UNSIGNED_INT_8_8_8_8_REV UnsignedInt1010102 -> gl_UNSIGNED_INT_10_10_10_2 UnsignedInt2101010Rev -> gl_UNSIGNED_INT_2_10_10_10_REV UnsignedInt248 -> gl_UNSIGNED_INT_24_8 UnsignedInt10f11f11fRev -> gl_UNSIGNED_INT_10F_11F_11F_REV UnsignedInt5999Rev -> gl_UNSIGNED_INT_5_9_9_9_REV Float32UnsignedInt248Rev -> gl_FLOAT_32_UNSIGNED_INT_24_8_REV Bitmap -> gl_BITMAP UnsignedShort88 -> gl_UNSIGNED_SHORT_8_8_APPLE UnsignedShort88Rev -> gl_UNSIGNED_SHORT_8_8_REV_APPLE Double -> gl_DOUBLE TwoBytes -> gl_2_BYTES ThreeBytes -> gl_3_BYTES FourBytes -> gl_4_BYTES unmarshalDataType :: GLenum -> DataType unmarshalDataType x | x == gl_UNSIGNED_BYTE = UnsignedByte | x == gl_BYTE = Byte | x == gl_UNSIGNED_SHORT = UnsignedShort | x == gl_SHORT = Short | x == gl_UNSIGNED_INT = UnsignedInt | x == gl_INT = Int | x == gl_HALF_FLOAT = HalfFloat | x == gl_FLOAT = Float | x == gl_UNSIGNED_BYTE_3_3_2 = UnsignedByte332 | x == gl_UNSIGNED_BYTE_2_3_3_REV = UnsignedByte233Rev | x == gl_UNSIGNED_SHORT_5_6_5 = UnsignedShort565 | x == gl_UNSIGNED_SHORT_5_6_5_REV = UnsignedShort565Rev | x == gl_UNSIGNED_SHORT_4_4_4_4 = UnsignedShort4444 | x == gl_UNSIGNED_SHORT_4_4_4_4_REV = UnsignedShort4444Rev | x == gl_UNSIGNED_SHORT_5_5_5_1 = UnsignedShort5551 | x == gl_UNSIGNED_SHORT_1_5_5_5_REV = UnsignedShort1555Rev | x == gl_UNSIGNED_INT_8_8_8_8 = UnsignedInt8888 | x == gl_UNSIGNED_INT_8_8_8_8_REV = UnsignedInt8888Rev | x == gl_UNSIGNED_INT_10_10_10_2 = UnsignedInt1010102 | x == gl_UNSIGNED_INT_2_10_10_10_REV = UnsignedInt2101010Rev | x == gl_UNSIGNED_INT_24_8 = UnsignedInt248 | x == gl_UNSIGNED_INT_10F_11F_11F_REV = UnsignedInt10f11f11fRev | x == gl_UNSIGNED_INT_5_9_9_9_REV = UnsignedInt5999Rev | x == gl_FLOAT_32_UNSIGNED_INT_24_8_REV = Float32UnsignedInt248Rev | x == gl_BITMAP = Bitmap | x == gl_UNSIGNED_SHORT_8_8_APPLE = UnsignedShort88 | x == gl_UNSIGNED_SHORT_8_8_REV_APPLE = UnsignedShort88Rev | x == gl_DOUBLE = Double | x == gl_2_BYTES = TwoBytes | x == gl_3_BYTES = ThreeBytes | x == gl_4_BYTES = FourBytes | otherwise = error ("unmarshalDataType: illegal value " ++ show x) data DataTypeType = TNone | TSignedNormalized | TUnsignedNormalized | TFloat | TInt | TUnsignedInt marshalDataTypeType :: DataTypeType -> GLenum marshalDataTypeType x = case x of TNone -> gl_NONE TSignedNormalized -> gl_SIGNED_NORMALIZED TUnsignedNormalized -> gl_UNSIGNED_NORMALIZED TFloat -> gl_FLOAT TInt -> gl_INT TUnsignedInt -> gl_UNSIGNED_INT unmarshalDataTypeType :: GLenum -> DataTypeType unmarshalDataTypeType x | x == gl_NONE = TNone | x == gl_SIGNED_NORMALIZED = TSignedNormalized | x == gl_UNSIGNED_NORMALIZED = TUnsignedNormalized | x == gl_FLOAT = TFloat | x == gl_INT = TInt | x == gl_UNSIGNED_INT = TUnsignedInt | otherwise = error $ "unmarshalDataTypeType: illegal value " ++ show x
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/DataType.hs
bsd-3-clause
5,554
0
9
1,056
1,016
528
488
129
31
{-# LANGUAGE BangPatterns, MagicHash, UnboxedTuples #-} {-# OPTIONS_GHC -O #-} -- We always optimise this, otherwise performance of a non-optimised -- compiler is severely affected -- ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow, 1997-2006 -- -- Character encodings -- -- ----------------------------------------------------------------------------- module ETA.Utils.Encoding ( -- * UTF-8 utf8DecodeChar#, utf8PrevChar, utf8CharStart, utf8DecodeChar, utf8DecodeString, utf8EncodeChar, utf8EncodeString, utf8EncodedLength, countUTF8Chars, -- * Z-encoding zEncodeString, zDecodeString ) where import Foreign import Data.Char import Numeric import ETA.Utils.ExtsCompat46 -- ----------------------------------------------------------------------------- -- UTF-8 -- We can't write the decoder as efficiently as we'd like without -- resorting to unboxed extensions, unfortunately. I tried to write -- an IO version of this function, but GHC can't eliminate boxed -- results from an IO-returning function. -- -- We assume we can ignore overflow when parsing a multibyte character here. -- To make this safe, we add extra sentinel bytes to unparsed UTF-8 sequences -- before decoding them (see StringBuffer.hs). {-# INLINE utf8DecodeChar# #-} utf8DecodeChar# :: Addr# -> (# Char#, Int# #) utf8DecodeChar# a# = let !ch0 = word2Int# (indexWord8OffAddr# a# 0#) in case () of _ | ch0 <=# 0x7F# -> (# chr# ch0, 1# #) | ch0 >=# 0xC0# && ch0 <=# 0xDF# -> let !ch1 = word2Int# (indexWord8OffAddr# a# 1#) in if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else (# chr# (((ch0 -# 0xC0#) `uncheckedIShiftL#` 6#) +# (ch1 -# 0x80#)), 2# #) | ch0 >=# 0xE0# && ch0 <=# 0xEF# -> let !ch1 = word2Int# (indexWord8OffAddr# a# 1#) in if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else let !ch2 = word2Int# (indexWord8OffAddr# a# 2#) in if ch2 <# 0x80# || ch2 >=# 0xC0# then fail 2# else (# chr# (((ch0 -# 0xE0#) `uncheckedIShiftL#` 12#) +# ((ch1 -# 0x80#) `uncheckedIShiftL#` 6#) +# (ch2 -# 0x80#)), 3# #) | ch0 >=# 0xF0# && ch0 <=# 0xF8# -> let !ch1 = word2Int# (indexWord8OffAddr# a# 1#) in if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else let !ch2 = word2Int# (indexWord8OffAddr# a# 2#) in if ch2 <# 0x80# || ch2 >=# 0xC0# then fail 2# else let !ch3 = word2Int# (indexWord8OffAddr# a# 3#) in if ch3 <# 0x80# || ch3 >=# 0xC0# then fail 3# else (# chr# (((ch0 -# 0xF0#) `uncheckedIShiftL#` 18#) +# ((ch1 -# 0x80#) `uncheckedIShiftL#` 12#) +# ((ch2 -# 0x80#) `uncheckedIShiftL#` 6#) +# (ch3 -# 0x80#)), 4# #) | otherwise -> fail 1# where -- all invalid sequences end up here: fail :: Int# -> (# Char#, Int# #) fail nBytes# = (# '\0'#, nBytes# #) -- '\xFFFD' would be the usual replacement character, but -- that's a valid symbol in Haskell, so will result in a -- confusing parse error later on. Instead we use '\0' which -- will signal a lexer error immediately. utf8DecodeChar :: Ptr Word8 -> (Char, Int) utf8DecodeChar (Ptr a#) = case utf8DecodeChar# a# of (# c#, nBytes# #) -> ( C# c#, I# nBytes# ) -- UTF-8 is cleverly designed so that we can always figure out where -- the start of the current character is, given any position in a -- stream. This function finds the start of the previous character, -- assuming there *is* a previous character. utf8PrevChar :: Ptr Word8 -> IO (Ptr Word8) utf8PrevChar p = utf8CharStart (p `plusPtr` (-1)) utf8CharStart :: Ptr Word8 -> IO (Ptr Word8) utf8CharStart p = go p where go p = do w <- peek p if w >= 0x80 && w < 0xC0 then go (p `plusPtr` (-1)) else return p utf8DecodeString :: Ptr Word8 -> Int -> IO [Char] utf8DecodeString ptr len = unpack ptr where !end = ptr `plusPtr` len unpack p | p >= end = return [] | otherwise = case utf8DecodeChar# (unPtr p) of (# c#, nBytes# #) -> do chs <- unpack (p `plusPtr#` nBytes#) return (C# c# : chs) countUTF8Chars :: Ptr Word8 -> Int -> IO Int countUTF8Chars ptr len = go ptr 0 where !end = ptr `plusPtr` len go p !n | p >= end = return n | otherwise = do case utf8DecodeChar# (unPtr p) of (# _, nBytes# #) -> go (p `plusPtr#` nBytes#) (n+1) unPtr :: Ptr a -> Addr# unPtr (Ptr a) = a plusPtr# :: Ptr a -> Int# -> Ptr a plusPtr# ptr nBytes# = ptr `plusPtr` (I# nBytes#) utf8EncodeChar :: Char -> Ptr Word8 -> IO (Ptr Word8) utf8EncodeChar c ptr = let x = ord c in case () of _ | x >= 0 && x <= 0x007f -> do poke ptr (fromIntegral x) return (ptr `plusPtr` 1) | x <= 0x07ff -> do poke ptr (fromIntegral (0xC0 .|. ((x `shiftR` 6) .&. 0x1F))) pokeElemOff ptr 1 (fromIntegral (0x80 .|. (x .&. 0x3F))) return (ptr `plusPtr` 2) | x <= 0xffff -> do poke ptr (fromIntegral (0xE0 .|. (x `shiftR` 12) .&. 0x0F)) pokeElemOff ptr 1 (fromIntegral (0x80 .|. (x `shiftR` 6) .&. 0x3F)) pokeElemOff ptr 2 (fromIntegral (0x80 .|. (x .&. 0x3F))) return (ptr `plusPtr` 3) | otherwise -> do poke ptr (fromIntegral (0xF0 .|. (x `shiftR` 18))) pokeElemOff ptr 1 (fromIntegral (0x80 .|. ((x `shiftR` 12) .&. 0x3F))) pokeElemOff ptr 2 (fromIntegral (0x80 .|. ((x `shiftR` 6) .&. 0x3F))) pokeElemOff ptr 3 (fromIntegral (0x80 .|. (x .&. 0x3F))) return (ptr `plusPtr` 4) utf8EncodeString :: Ptr Word8 -> String -> IO () utf8EncodeString ptr str = go ptr str where go !_ [] = return () go ptr (c:cs) = do ptr' <- utf8EncodeChar c ptr go ptr' cs utf8EncodedLength :: String -> Int utf8EncodedLength str = go 0 str where go !n [] = n go n (c:cs) | ord c >= 0 && ord c <= 0x007f = go (n+1) cs | ord c <= 0x07ff = go (n+2) cs | ord c <= 0xffff = go (n+3) cs | otherwise = go (n+4) cs -- ----------------------------------------------------------------------------- -- The Z-encoding {- This is the main name-encoding and decoding function. It encodes any string into a string that is acceptable as a C name. This is done right before we emit a symbol name into the compiled C or asm code. Z-encoding of strings is cached in the FastString interface, so we never encode the same string more than once. The basic encoding scheme is this. * Tuples (,,,) are coded as Z3T * Alphabetic characters (upper and lower) and digits all translate to themselves; except 'Z', which translates to 'ZZ' and 'z', which translates to 'zz' We need both so that we can preserve the variable/tycon distinction * Most other printable characters translate to 'zx' or 'Zx' for some alphabetic character x * The others translate as 'znnnU' where 'nnn' is the decimal number of the character Before After -------------------------- Trak Trak foo_wib foozuwib > zg >1 zg1 foo# foozh foo## foozhzh foo##1 foozhzh1 fooZ fooZZ :+ ZCzp () Z0T 0-tuple (,,,,) Z5T 5-tuple (# #) Z1H unboxed 1-tuple (note the space) (#,,,,#) Z5H unboxed 5-tuple (NB: There is no Z1T nor Z0H.) -} type UserString = String -- As the user typed it type EncodedString = String -- Encoded form zEncodeString :: UserString -> EncodedString zEncodeString cs = case maybe_tuple cs of Just n -> n -- Tuples go to Z2T etc Nothing -> go cs where go [] = [] go (c:cs) = encode_digit_ch c ++ go' cs go' [] = [] go' (c:cs) = encode_ch c ++ go' cs unencodedChar :: Char -> Bool -- True for chars that don't need encoding unencodedChar 'Z' = False unencodedChar 'z' = False unencodedChar c = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' -- If a digit is at the start of a symbol then we need to encode it. -- Otherwise package names like 9pH-0.1 give linker errors. encode_digit_ch :: Char -> EncodedString encode_digit_ch c | c >= '0' && c <= '9' = encode_as_unicode_char c encode_digit_ch c | otherwise = encode_ch c encode_ch :: Char -> EncodedString encode_ch c | unencodedChar c = [c] -- Common case first -- Constructors encode_ch '(' = "ZL" -- Needed for things like (,), and (->) encode_ch ')' = "ZR" -- For symmetry with ( encode_ch '[' = "ZM" encode_ch ']' = "ZN" encode_ch ':' = "ZC" encode_ch 'Z' = "ZZ" -- Variables encode_ch 'z' = "zz" encode_ch '&' = "za" encode_ch '|' = "zb" encode_ch '^' = "zc" encode_ch '$' = "zd" encode_ch '=' = "ze" encode_ch '>' = "zg" encode_ch '#' = "zh" encode_ch '.' = "zi" encode_ch '<' = "zl" encode_ch '-' = "zm" encode_ch '!' = "zn" encode_ch '+' = "zp" encode_ch '\'' = "zq" encode_ch '\\' = "zr" encode_ch '/' = "zs" encode_ch '*' = "zt" encode_ch '_' = "zu" encode_ch '%' = "zv" encode_ch c = encode_as_unicode_char c encode_as_unicode_char :: Char -> EncodedString encode_as_unicode_char c = 'z' : if isDigit (head hex_str) then hex_str else '0':hex_str where hex_str = showHex (ord c) "U" -- ToDo: we could improve the encoding here in various ways. -- eg. strings of unicode characters come out as 'z1234Uz5678U', we -- could remove the 'U' in the middle (the 'z' works as a separator). zDecodeString :: EncodedString -> UserString zDecodeString [] = [] zDecodeString ('Z' : d : rest) | isDigit d = decode_tuple d rest | otherwise = decode_upper d : zDecodeString rest zDecodeString ('z' : d : rest) | isDigit d = decode_num_esc d rest | otherwise = decode_lower d : zDecodeString rest zDecodeString (c : rest) = c : zDecodeString rest decode_upper, decode_lower :: Char -> Char decode_upper 'L' = '(' decode_upper 'R' = ')' decode_upper 'M' = '[' decode_upper 'N' = ']' decode_upper 'C' = ':' decode_upper 'Z' = 'Z' decode_upper ch = {-pprTrace "decode_upper" (char ch)-} ch decode_lower 'z' = 'z' decode_lower 'a' = '&' decode_lower 'b' = '|' decode_lower 'c' = '^' decode_lower 'd' = '$' decode_lower 'e' = '=' decode_lower 'g' = '>' decode_lower 'h' = '#' decode_lower 'i' = '.' decode_lower 'l' = '<' decode_lower 'm' = '-' decode_lower 'n' = '!' decode_lower 'p' = '+' decode_lower 'q' = '\'' decode_lower 'r' = '\\' decode_lower 's' = '/' decode_lower 't' = '*' decode_lower 'u' = '_' decode_lower 'v' = '%' decode_lower ch = {-pprTrace "decode_lower" (char ch)-} ch -- Characters not having a specific code are coded as z224U (in hex) decode_num_esc :: Char -> EncodedString -> UserString decode_num_esc d rest = go (digitToInt d) rest where go n (c : rest) | isHexDigit c = go (16*n + digitToInt c) rest go n ('U' : rest) = chr n : zDecodeString rest go n other = error ("decode_num_esc: " ++ show n ++ ' ':other) decode_tuple :: Char -> EncodedString -> UserString decode_tuple d rest = go (digitToInt d) rest where -- NB. recurse back to zDecodeString after decoding the tuple, because -- the tuple might be embedded in a longer name. go n (c : rest) | isDigit c = go (10*n + digitToInt c) rest go 0 ('T':rest) = "()" ++ zDecodeString rest go n ('T':rest) = '(' : replicate (n-1) ',' ++ ")" ++ zDecodeString rest go 1 ('H':rest) = "(# #)" ++ zDecodeString rest go n ('H':rest) = '(' : '#' : replicate (n-1) ',' ++ "#)" ++ zDecodeString rest go n other = error ("decode_tuple: " ++ show n ++ ' ':other) {- Tuples are encoded as Z3T or Z3H for 3-tuples or unboxed 3-tuples respectively. No other encoding starts Z<digit> * "(# #)" is the tycon for an unboxed 1-tuple (not 0-tuple) There are no unboxed 0-tuples. * "()" is the tycon for a boxed 0-tuple. There are no boxed 1-tuples. -} maybe_tuple :: UserString -> Maybe EncodedString maybe_tuple "(# #)" = Just("Z1H") maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H") _ -> Nothing maybe_tuple "()" = Just("Z0T") maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of (n, ')' : _) -> Just ('Z' : shows (n+1) "T") _ -> Nothing maybe_tuple _ = Nothing count_commas :: Int -> String -> (Int, String) count_commas n (',' : cs) = count_commas (n+1) cs count_commas n cs = (n,cs)
alexander-at-github/eta
compiler/ETA/Utils/Encoding.hs
bsd-3-clause
13,350
0
29
3,970
3,640
1,851
1,789
240
7
import Data.Char (ord, chr) -- A pythagorean number pyths :: Int -> [(Int,Int,Int)] pyths n = [(x,y,z) | x<-[1..n], y<-[1..n], z<-[1..n], x^2+y^2 == z^2] -- Factors!!!! factors :: Int -> [Int] factors x = [n | n <- [1..x], x `mod` n == 0] -- A positive integer is perfect if it equals the -- sum of all its factores excluding the number itself. perfect :: Int -> Bool perfect x | x<=0 = False | otherwise = x == sum (tail (reverse (factors x))) -- perfects returns the list of all perfect numbers up to a certain number perfects :: Int -> [Int] perfects x = [n | n <- [1..x], perfect n] -- scalar product between two lists --scalarProduct :: [Int] -> [Int] -> Int scalarProduct xs = \ys -> sum [x*y | (x,y) <- zip xs ys] -- Book exercises -- -- A list comprehension for the sum of many integers -- sumMany :: Int -> Int sumMany limit = sum [x*x | x <- [1..limit]] -- -- Replicate with list comprehensions -- replicateC :: Int -> a -> [a] replicateC times element = [element | _ <- [1..times]] -- -- Implement find and then implement positions using find -- find :: Eq a => a -> [(a,b)] -> [b] find n h = [pos | (x,pos) <- h, x == n] positions :: Eq a => a -> [a] -> [Int] positions n h = find n (zip h [1..(length h)]) -- -- Ceaser's cipher -- letter2digit :: Char -> Int letter2digit c = ord c - ord 'a' digit2letter :: Int -> Char digit2letter d = chr (d + ord 'a') shift :: Int -> Char -> Char shift offset = \char -> digit2letter ((letter2digit char + offset) `mod` 26) {- both versions, with map and with comprehension, work! :-) -} encode :: Int -> [Char] -> [Char] --encode offset = \s -> [shift offset c | c <- s] encode offset = \s -> map (shift offset) s decode :: Int -> [Char] -> [Char] decode offset = \string -> [shift (-offset) c | c <- string] count :: Char -> [Char] -> Int count c string = length [1 | c' <- string, c == c'] countAll :: Fractional a => [Char] -> [a] countAll string = map (\y -> y * 100) (map (\x -> (fromIntegral x) / fromIntegral (length string)) [count letter string | letter <- ['a'..'z']]) generateFrequencies :: Fractional a => [Char] -> [(Char, a)] generateFrequencies string = zip ['a'..'z'] (countAll string) table :: [Float] table = [8.2, 1.5, 2.8, 4.3, 12.7, 2.2, 2.0, 6.1, 7.0, 0.2, 0.8, 4.0, 2.4, 6.7, 7.5, 1.9, 0.1, 6.0, 6.3, 9.1, 2.8, 1.0, 2.4, 0.2, 2.0, 0.1]
decomputed/haskellLaboratory
programmingInHaskell/chapter05.hs
mit
2,429
7
12
572
1,104
592
512
45
1
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : $Header$ Description : Tern for HolLight logic Copyright : (c) Jonathan von Schroeder, DFKI GmbH 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable Definition of terms for HolLight logic Ref. <http://www.cl.cam.ac.uk/~jrh13/hol-light/> -} module HolLight.Term where import Data.Data data HolType = TyVar String | TyApp String [HolType] deriving (Eq, Ord, Show, Read, Typeable, Data) data HolProof = NoProof deriving (Eq, Ord, Show, Typeable, Data) data HolParseType = Normal | PrefixT | InfixL Int | InfixR Int | Binder deriving (Eq, Ord, Show, Read, Typeable, Data) data HolTermInfo = HolTermInfo (HolParseType, Maybe (String, HolParseType)) deriving (Eq, Ord, Show, Read, Typeable, Data) data Term = Var String HolType HolTermInfo | Const String HolType HolTermInfo | Comb Term Term | Abs Term Term deriving (Eq, Ord, Show, Read, Typeable, Data)
keithodulaigh/Hets
HolLight/Term.hs
gpl-2.0
1,045
0
9
201
253
140
113
15
0
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings where import Prelude import Text.Shakespeare.Text (st) import Language.Haskell.TH.Syntax import Yesod.Default.Config import Yesod.Default.Util import Data.Text (Text) import Data.Yaml import Control.Applicative import Settings.Development import Data.Default (def) import Text.Hamlet -- Static setting below. Changing these requires a recompile -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticDir :: FilePath staticDir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticRoot :: AppConfig DefaultEnv x -> Text staticRoot conf = [st|#{appRoot conf}/static|] -- | Settings for 'widgetFile', such as which template languages to support and -- default Hamlet settings. -- -- For more information on modifying behavior, see: -- -- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile widgetFileSettings :: WidgetFileSettings widgetFileSettings = def { wfsHamletSettings = defaultHamletSettings { hamletNewlines = AlwaysNewlines } } -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = (if development then widgetFileReload else widgetFileNoReload) widgetFileSettings data Extra = Extra { extraCopyright :: Text , extraAnalytics :: Maybe Text -- ^ Google Analytics } deriving Show parseExtra :: DefaultEnv -> Object -> Parser Extra parseExtra _ o = Extra <$> o .: "copyright" <*> o .:? "analytics"
carlohamalainen/rapid-connect-yesod-demo
Settings.hs
bsd-2-clause
2,609
0
9
466
269
170
99
-1
-1
{-# LANGUAGE CPP #-} -- | Cabal. module Haskell.Docs.Cabal where import Haskell.Docs.Ghc import Data.Char (isSpace) import Data.List import Data.Maybe import Distribution.InstalledPackageInfo import Distribution.ModuleName import Distribution.Simple.Compiler import Distribution.Simple.PackageIndex import DynFlags import GHC import Module #if __GLASGOW_HASKELL__ >= 710 import PackageConfig hiding (InstalledPackageInfo(..)) #else import PackageConfig #endif -- * Cabal getGhcOpsPackageDB :: [String] -> [PackageDB] getGhcOpsPackageDB gs = map (SpecificPackageDB . trim) pkgDBOps where pkgDBOps = filter ("--package-db" `isPrefixOf`) gs trim = (drop 1) . snd . (break isSpace) -- | Get all installed packages, filtering out the given package. getAllPackages :: [String] -> Ghc [PackageConfig.PackageConfig] getAllPackages _gs = do flags <- getSessionDynFlags return (fromMaybe [] (pkgDB flags)) pkgDB :: DynFlags -> Maybe [PackageConfig] #if __GLASGOW_HASKELL__ >= 800 pkgDB = fmap (concatMap snd) . pkgDatabase #else pkgDB = pkgDatabase #endif -- | Version-portable version of allPackagesByName. #if MIN_VERSION_Cabal (1,22,0) packagesByName :: InstalledPackageIndex -> [[InstalledPackageInfo]] #else packagesByName :: PackageIndex -> [[InstalledPackageInfo]] #endif #if MIN_VERSION_Cabal(1,16,0) packagesByName = map snd . allPackagesByName #else packagesByName = allPackagesByName #endif -- * Internal modules -- | Convert a Cabal module name to a GHC module name. convModule :: Distribution.ModuleName.ModuleName -> Module.ModuleName convModule = makeModuleName . intercalate "." . components
chrisdone/haskell-docs
src/Haskell/Docs/Cabal.hs
bsd-3-clause
1,661
0
13
254
322
188
134
28
1
module Sing where import Data.List -- fstString :: [Char] -> [Char] -- fstString x = x ++ " in the rain" -- sndString :: [Char] -> [Char] -- sndString x = x ++ " over the rainbow" -- sing = if (x < y) then fstString x else sndString y -- where x = "Singin" -- y = "Somewhere" -- main :: IO () -- main = -- do -- print (1 + 2) -- putStrLn "10" -- print (negate 1) -- print ((+) 0 blah) -- where blah = negate 1 -- divideThenAdd :: (Fractional a, Num a) => a -> a -> a -- divideThenAdd x y = (x / y ) + 1 -- data Mood = Blah -- instance Show Mood where -- show _ = "Blah" -- data Trivial = Trivial' deriving Show -- instance Eq Trivial where -- (==) Trivial' Trivial' = True data DayOfWeek = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving (Show, Ord) data Date = Date DayOfWeek Int instance Eq DayOfWeek where (==) Mon Mon = True (==) Tue Tue = True (==) Wed Wed = True (==) Thu Thu = True (==) Fri Fri = True (==) Sat Sat = True (==) Sun Sun = True (==) _ _ = False instance Eq Date where (==) (Date dayOfWeek day) (Date dayOfWeek' day') = (dayOfWeek' == dayOfWeek) && (day == day') data TisAnInteger = TisAn Integer instance Eq TisAnInteger where (==) (TisAn i) (TisAn i') = (i == i') data TwoIntegers = Two Integer Integer instance Eq TwoIntegers where (==) (Two i1 i2) (Two i1' i2') = (i1 == i1') && (i2 == i2') data StringOrInt = TisAnInt Int | TisAString String instance Eq StringOrInt where (==) (TisAnInt i) (TisAnInt i') = (i == i') (==) (TisAString s) (TisAString s') = (s == s') (==) _ _ = False data Pair a = Pair a a instance Eq a => Eq (Pair a) where (==) (Pair a b) (Pair a' b') = (a == a') && (b == b') data Tuple a b = Tuple a b deriving Show instance (Eq a, Eq b) => Eq (Tuple a b) where (==) (Tuple a b) (Tuple a' b') = (a == a') && (b == b') data EitherOr a b = Hello a | Goodbye b instance (Eq a, Eq b) => Eq (EitherOr a b) where (==) (Hello a) (Hello a') = (a == a') (==) (Goodbye b) (Goodbye b') = (b == b') (==) _ _ = False --- tychecking exercises data Person = Person Bool deriving Show printPerson :: Person -> IO () printPerson person = putStrLn (show person) data Mood = Blah | Woot deriving (Show, Ord, Eq) settleDown x = if x == Woot then Blah else x type Subject = String type Verb = String type Object = String data Sentence = Sentence Subject Verb Object deriving (Eq, Show) s1 = Sentence "punit" "rathore" "reads" data Rocks = Rocks String deriving (Eq, Show) data Yeah = Yeah Bool deriving (Eq, Show) data Papu = Papu Rocks Yeah deriving (Eq, Show) s4 = Papu (Rocks "foo") (Yeah True) f:: Int -> Int f x = x mySort :: [Char] -> [Char] mySort = sort -- signifier :: Ord a => [a] -> a -- signifier xs = head (mySort xs) chk::Eq b => (a -> b) -> a -> b -> Bool chk f a b = (f a) == b -- foo:: (a -> a) -> a -> a -- foo f x = f(x) -- arith :: Num b => ( a -> b) -> Integer -> a -> b -- arith :: Num a => ( a -> b) -> b -> a -> b arith f i a = (f a) * i -- mTh x y = \z -> x * y * z mTh x = (\y -> \z -> x * y * z) addOne = (\x -> x+1)::Integer -> Integer addOneIfOdd n = case odd n of True -> f n False -> n where f = \n -> n + 1 addFive::Integer->Integer -> Integer addFive = \x -> \y -> (if x > y then y else x)+5 data WherePenguinsLive = India | SouthAfrica | Zimbabwe data Penguin = Peng WherePenguinsLive gimmeWhereTheyLive :: Penguin -> WherePenguinsLive gimmeWhereTheyLive (Peng whereitlives) = whereitlives f2::(a,b,c)->(d,e,f)->((a,d),(c,f)) f2 (a,b,c) (d,e,f) = ((a,d),(c,f)) myAbs::Integer -> Integer myAbs x = case (x > 0) of True -> x _ -> -x myAbs2::Integer -> Integer myAbs2 x | x > 0 = x | x < 0 = -x
punitrathore/haskell-first-principles
src/Sing.hs
bsd-3-clause
3,774
0
10
995
1,455
817
638
86
2
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 HsTypes: Abstract syntax: user-defined types -} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE CPP #-} module HsTypes ( HsType(..), LHsType, HsKind, LHsKind, HsTyVarBndr(..), LHsTyVarBndr, LHsQTyVars(..), HsImplicitBndrs(..), HsWildCardBndrs(..), LHsSigType, LHsSigWcType, LHsWcType, HsTupleSort(..), Promoted(..), HsContext, LHsContext, HsTyLit(..), HsIPName(..), hsIPNameFS, HsAppType(..),LHsAppType, LBangType, BangType, HsSrcBang(..), HsImplBang(..), SrcStrictness(..), SrcUnpackedness(..), getBangType, getBangStrictness, ConDeclField(..), LConDeclField, pprConDeclFields, updateGadtResult, HsConDetails(..), FieldOcc(..), LFieldOcc, mkFieldOcc, AmbiguousFieldOcc(..), mkAmbiguousFieldOcc, rdrNameAmbiguousFieldOcc, selectorAmbiguousFieldOcc, unambiguousFieldOcc, ambiguousFieldOcc, HsWildCardInfo(..), mkAnonWildCardTy, wildCardName, sameWildCard, mkHsImplicitBndrs, mkHsWildCardBndrs, hsImplicitBody, mkEmptyImplicitBndrs, mkEmptyWildCardBndrs, mkHsQTvs, hsQTvExplicit, emptyLHsQTvs, isEmptyLHsQTvs, isHsKindedTyVar, hsTvbAllKinded, hsScopedTvs, hsWcScopedTvs, dropWildCards, hsTyVarName, hsAllLTyVarNames, hsLTyVarLocNames, hsLTyVarName, hsLTyVarLocName, hsExplicitLTyVarNames, splitLHsInstDeclTy, getLHsInstDeclHead, getLHsInstDeclClass_maybe, splitLHsPatSynTy, splitLHsForAllTy, splitLHsQualTy, splitLHsSigmaTy, splitHsFunType, splitHsAppsTy, splitHsAppTys, getAppsTyHead_maybe, hsTyGetAppHead_maybe, mkHsOpTy, mkHsAppTy, mkHsAppTys, ignoreParens, hsSigType, hsSigWcType, hsLTyVarBndrToType, hsLTyVarBndrsToTypes, -- Printing pprParendHsType, pprHsForAll, pprHsForAllTvs, pprHsForAllExtra, pprHsContext, pprHsContextNoArrow, pprHsContextMaybe ) where import {-# SOURCE #-} HsExpr ( HsSplice, pprSplice ) import PlaceHolder ( PostTc,PostRn,DataId,PlaceHolder(..), OutputableBndrId ) import Id ( Id ) import Name( Name ) import RdrName ( RdrName ) import NameSet ( NameSet, emptyNameSet ) import DataCon( HsSrcBang(..), HsImplBang(..), SrcStrictness(..), SrcUnpackedness(..) ) import TysPrim( funTyConName ) import Type import HsDoc import BasicTypes import SrcLoc import StaticFlags import Outputable import FastString import Maybes( isJust ) import Data.Data hiding ( Fixity, Prefix, Infix ) import Data.Maybe ( fromMaybe ) import Control.Monad ( unless ) {- ************************************************************************ * * \subsection{Bang annotations} * * ************************************************************************ -} -- | Located Bang Type type LBangType name = Located (BangType name) -- | Bang Type type BangType name = HsType name -- Bangs are in the HsType data type getBangType :: LHsType a -> LHsType a getBangType (L _ (HsBangTy _ ty)) = ty getBangType ty = ty getBangStrictness :: LHsType a -> HsSrcBang getBangStrictness (L _ (HsBangTy s _)) = s getBangStrictness _ = (HsSrcBang NoSourceText NoSrcUnpack NoSrcStrict) {- ************************************************************************ * * \subsection{Data types} * * ************************************************************************ This is the syntax for types as seen in type signatures. Note [HsBSig binder lists] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider a binder (or pattern) decorated with a type or kind, \ (x :: a -> a). blah forall (a :: k -> *) (b :: k). blah Then we use a LHsBndrSig on the binder, so that the renamer can decorate it with the variables bound by the pattern ('a' in the first example, 'k' in the second), assuming that neither of them is in scope already See also Note [Kind and type-variable binders] in RnTypes Note [HsType binders] ~~~~~~~~~~~~~~~~~~~~~ The system for recording type and kind-variable binders in HsTypes is a bit complicated. Here's how it works. * In a HsType, HsForAllTy represents an /explicit, user-written/ 'forall' e.g. forall a b. ... HsQualTy represents an /explicit, user-written/ context e.g. (Eq a, Show a) => ... The context can be empty if that's what the user wrote These constructors represent what the user wrote, no more and no less. * HsTyVarBndr describes a quantified type variable written by the user. For example f :: forall a (b :: *). blah here 'a' and '(b::*)' are each a HsTyVarBndr. A HsForAllTy has a list of LHsTyVarBndrs. * HsImplicitBndrs is a wrapper that gives the implicitly-quantified kind and type variables of the wrapped thing. It is filled in by the renamer. For example, if the user writes f :: a -> a the HsImplicitBinders binds the 'a' (not a HsForAllTy!). NB: this implicit quantification is purely lexical: we bind any type or kind variables that are not in scope. The type checker may subsequently quantify over further kind variables. * HsWildCardBndrs is a wrapper that binds the wildcard variables of the wrapped thing. It is filled in by the renamer f :: _a -> _ The enclosing HsWildCardBndrs binds the wildcards _a and _. * The explicit presence of these wrappers specifies, in the HsSyn, exactly where implicit quantification is allowed, and where wildcards are allowed. * LHsQTyVars is used in data/class declarations, where the user gives explicit *type* variable bindings, but we need to implicitly bind *kind* variables. For example class C (a :: k -> *) where ... The 'k' is implicitly bound in the hsq_tvs field of LHsQTyVars Note [The wildcard story for types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Types can have wildcards in them, to support partial type signatures, like f :: Int -> (_ , _a) -> _a A wildcard in a type can be * An anonymous wildcard, written '_' In HsType this is represented by HsWildCardTy. After the renamer, this contains a Name which uniquely identifies this particular occurrence. * A named wildcard, written '_a', '_foo', etc In HsType this is represented by (HsTyVar "_a") i.e. a perfectly ordinary type variable that happens to start with an underscore Note carefully: * When NamedWildCards is off, type variables that start with an underscore really /are/ ordinary type variables. And indeed, even when NamedWildCards is on you can bind _a explicitly as an ordinary type variable: data T _a _b = MkT _b _a Or even: f :: forall _a. _a -> _b Here _a is an ordinary forall'd binder, but (With NamedWildCards) _b is a named wildcard. (See the comments in Trac #10982) * All wildcards, whether named or anonymous, are bound by the HsWildCardBndrs construct, which wraps types that are allowed to have wildcards. * After type checking is done, we report what types the wildcards got unified with. -} -- | Located Haskell Context type LHsContext name = Located (HsContext name) -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnUnit' -- For details on above see note [Api annotations] in ApiAnnotation -- | Haskell Context type HsContext name = [LHsType name] -- | Located Haskell Type type LHsType name = Located (HsType name) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when -- in a list -- For details on above see note [Api annotations] in ApiAnnotation -- | Haskell Kind type HsKind name = HsType name -- | Located Haskell Kind type LHsKind name = Located (HsKind name) -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation -------------------------------------------------- -- LHsQTyVars -- The explicitly-quantified binders in a data/type declaration -- | Located Haskell Type Variable Binder type LHsTyVarBndr name = Located (HsTyVarBndr name) -- See Note [HsType binders] -- | Located Haskell Quantified Type Variables data LHsQTyVars name -- See Note [HsType binders] = HsQTvs { hsq_implicit :: PostRn name [Name] -- implicit (dependent) variables , hsq_explicit :: [LHsTyVarBndr name] -- explicit variables -- See Note [HsForAllTy tyvar binders] , hsq_dependent :: PostRn name NameSet -- which explicit vars are dependent -- See Note [Dependent LHsQTyVars] in TcHsType } deriving instance (DataId name) => Data (LHsQTyVars name) mkHsQTvs :: [LHsTyVarBndr RdrName] -> LHsQTyVars RdrName mkHsQTvs tvs = HsQTvs { hsq_implicit = PlaceHolder, hsq_explicit = tvs , hsq_dependent = PlaceHolder } hsQTvExplicit :: LHsQTyVars name -> [LHsTyVarBndr name] hsQTvExplicit = hsq_explicit emptyLHsQTvs :: LHsQTyVars Name emptyLHsQTvs = HsQTvs [] [] emptyNameSet isEmptyLHsQTvs :: LHsQTyVars Name -> Bool isEmptyLHsQTvs (HsQTvs [] [] _) = True isEmptyLHsQTvs _ = False ------------------------------------------------ -- HsImplicitBndrs -- Used to quantify the binders of a type in cases -- when a HsForAll isn't appropriate: -- * Patterns in a type/data family instance (HsTyPats) -- * Type of a rule binder (RuleBndr) -- * Pattern type signatures (SigPatIn) -- In the last of these, wildcards can happen, so we must accommodate them -- | Haskell Implicit Binders data HsImplicitBndrs name thing -- See Note [HsType binders] = HsIB { hsib_vars :: PostRn name [Name] -- Implicitly-bound kind & type vars , hsib_body :: thing -- Main payload (type or list of types) } -- | Haskell Wildcard Binders data HsWildCardBndrs name thing -- See Note [HsType binders] -- See Note [The wildcard story for types] = HsWC { hswc_wcs :: PostRn name [Name] -- Wild cards, both named and anonymous -- after the renamer , hswc_body :: thing -- Main payload (type or list of types) -- If there is an extra-constraints wildcard, -- it's still there in the hsc_body. } deriving instance (Data name, Data thing, Data (PostRn name [Name])) => Data (HsImplicitBndrs name thing) deriving instance (Data name, Data thing, Data (PostRn name [Name])) => Data (HsWildCardBndrs name thing) -- | Located Haskell Signature Type type LHsSigType name = HsImplicitBndrs name (LHsType name) -- Implicit only -- | Located Haskell Wildcard Type type LHsWcType name = HsWildCardBndrs name (LHsType name) -- Wildcard only -- | Located Haskell Signature Wildcard Type type LHsSigWcType name = HsWildCardBndrs name (LHsSigType name) -- Both -- See Note [Representing type signatures] hsImplicitBody :: HsImplicitBndrs name thing -> thing hsImplicitBody (HsIB { hsib_body = body }) = body hsSigType :: LHsSigType name -> LHsType name hsSigType = hsImplicitBody hsSigWcType :: LHsSigWcType name -> LHsType name hsSigWcType sig_ty = hsib_body (hswc_body sig_ty) dropWildCards :: LHsSigWcType name -> LHsSigType name -- Drop the wildcard part of a LHsSigWcType dropWildCards sig_ty = hswc_body sig_ty {- Note [Representing type signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HsSigType is used to represent an explicit user type signature such as f :: a -> a or g (x :: a -> a) = x A HsSigType is just a HsImplicitBndrs wrapping a LHsType. * The HsImplicitBndrs binds the /implicitly/ quantified tyvars * The LHsType binds the /explictly/ quantified tyvars E.g. For a signature like f :: forall (a::k). blah we get HsIB { hsib_vars = [k] , hsib_body = HsForAllTy { hst_bndrs = [(a::*)] , hst_body = blah } The implicit kind variable 'k' is bound by the HsIB; the explictly forall'd tyvar 'a' is bounnd by the HsForAllTy -} mkHsImplicitBndrs :: thing -> HsImplicitBndrs RdrName thing mkHsImplicitBndrs x = HsIB { hsib_body = x , hsib_vars = PlaceHolder } mkHsWildCardBndrs :: thing -> HsWildCardBndrs RdrName thing mkHsWildCardBndrs x = HsWC { hswc_body = x , hswc_wcs = PlaceHolder } -- Add empty binders. This is a bit suspicious; what if -- the wrapped thing had free type variables? mkEmptyImplicitBndrs :: thing -> HsImplicitBndrs Name thing mkEmptyImplicitBndrs x = HsIB { hsib_body = x , hsib_vars = [] } mkEmptyWildCardBndrs :: thing -> HsWildCardBndrs Name thing mkEmptyWildCardBndrs x = HsWC { hswc_body = x , hswc_wcs = [] } -------------------------------------------------- -- | These names are used early on to store the names of implicit -- parameters. They completely disappear after type-checking. newtype HsIPName = HsIPName FastString deriving( Eq, Data ) hsIPNameFS :: HsIPName -> FastString hsIPNameFS (HsIPName n) = n instance Outputable HsIPName where ppr (HsIPName n) = char '?' <> ftext n -- Ordinary implicit parameters instance OutputableBndr HsIPName where pprBndr _ n = ppr n -- Simple for now pprInfixOcc n = ppr n pprPrefixOcc n = ppr n -------------------------------------------------- -- | Haskell Type Variable Binder data HsTyVarBndr name = UserTyVar -- no explicit kinding (Located name) -- See Note [Located RdrNames] in HsExpr | KindedTyVar (Located name) (LHsKind name) -- The user-supplied kind signature -- ^ -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnDcolon', 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation deriving instance (DataId name) => Data (HsTyVarBndr name) -- | Does this 'HsTyVarBndr' come with an explicit kind annotation? isHsKindedTyVar :: HsTyVarBndr name -> Bool isHsKindedTyVar (UserTyVar {}) = False isHsKindedTyVar (KindedTyVar {}) = True -- | Do all type variables in this 'LHsQTyVars' come with kind annotations? hsTvbAllKinded :: LHsQTyVars name -> Bool hsTvbAllKinded = all (isHsKindedTyVar . unLoc) . hsQTvExplicit -- | Haskell Type data HsType name = HsForAllTy -- See Note [HsType binders] { hst_bndrs :: [LHsTyVarBndr name] -- Explicit, user-supplied 'forall a b c' , hst_body :: LHsType name -- body type } -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForall', -- 'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow' -- For details on above see note [Api annotations] in ApiAnnotation | HsQualTy -- See Note [HsType binders] { hst_ctxt :: LHsContext name -- Context C => blah , hst_body :: LHsType name } | HsTyVar Promoted -- whether explictly promoted, for the pretty -- printer (Located name) -- Type variable, type constructor, or data constructor -- see Note [Promotions (HsTyVar)] -- See Note [Located RdrNames] in HsExpr -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsAppsTy [LHsAppType name] -- Used only before renaming, -- Note [HsAppsTy] -- ^ - 'ApiAnnotation.AnnKeywordId' : None | HsAppTy (LHsType name) (LHsType name) -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsFunTy (LHsType name) -- function type (LHsType name) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsListTy (LHsType name) -- Element type -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsPArrTy (LHsType name) -- Elem. type of parallel array: [:t:] -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsTupleTy HsTupleSort [LHsType name] -- Element types (length gives arity) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(' or '(#'@, -- 'ApiAnnotation.AnnClose' @')' or '#)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsSumTy [LHsType name] -- Element types (length gives arity) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@, -- 'ApiAnnotation.AnnClose' '#)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsOpTy (LHsType name) (Located name) (LHsType name) -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsParTy (LHsType name) -- See Note [Parens in HsSyn] in HsExpr -- Parenthesis preserved for the precedence re-arrangement in RnTypes -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c! -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsIParamTy HsIPName -- (?x :: ty) (LHsType name) -- Implicit parameters as they occur in contexts -- ^ -- > (?x :: ty) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation | HsEqTy (LHsType name) -- ty1 ~ ty2 (LHsType name) -- Always allowed even without TypeOperators, and has special kinding rule -- ^ -- > ty1 ~ ty2 -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde' -- For details on above see note [Api annotations] in ApiAnnotation | HsKindSig (LHsType name) -- (ty :: kind) (LHsKind name) -- A type with a kind signature -- ^ -- > (ty :: kind) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsSpliceTy (HsSplice name) -- Includes quasi-quotes (PostTc name Kind) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsDocTy (LHsType name) LHsDocString -- A documented type -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsBangTy HsSrcBang (LHsType name) -- Bang-style type annotations -- ^ - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnOpen' @'{-\# UNPACK' or '{-\# NOUNPACK'@, -- 'ApiAnnotation.AnnClose' @'#-}'@ -- 'ApiAnnotation.AnnBang' @\'!\'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsRecTy [LConDeclField name] -- Only in data type declarations -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCoreTy Type -- An escape hatch for tunnelling a *closed* -- Core Type through HsSyn. -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsExplicitListTy -- A promoted explicit list Promoted -- whether explcitly promoted, for pretty printer (PostTc name Kind) -- See Note [Promoted lists and tuples] [LHsType name] -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'["@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsExplicitTupleTy -- A promoted explicit tuple [PostTc name Kind] -- See Note [Promoted lists and tuples] [LHsType name] -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'("@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsTyLit HsTyLit -- A promoted numeric literal. -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsWildCardTy (HsWildCardInfo name) -- A type wildcard -- See Note [The wildcard story for types] -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation deriving instance (DataId name) => Data (HsType name) -- Note [Literal source text] in BasicTypes for SourceText fields in -- the following -- | Haskell Type Literal data HsTyLit = HsNumTy SourceText Integer | HsStrTy SourceText FastString deriving Data newtype HsWildCardInfo name -- See Note [The wildcard story for types] = AnonWildCard (PostRn name (Located Name)) -- A anonymous wild card ('_'). A fresh Name is generated for -- each individual anonymous wildcard during renaming deriving instance (DataId name) => Data (HsWildCardInfo name) -- | Located Haskell Application Type type LHsAppType name = Located (HsAppType name) -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSimpleQuote' -- | Haskell Application Type data HsAppType name = HsAppInfix (Located name) -- either a symbol or an id in backticks | HsAppPrefix (LHsType name) -- anything else, including things like (+) deriving instance (DataId name) => Data (HsAppType name) instance (OutputableBndrId name) => Outputable (HsAppType name) where ppr = ppr_app_ty TopPrec {- Note [HsForAllTy tyvar binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After parsing: * Implicit => empty Explicit => the variables the user wrote After renaming * Implicit => the *type* variables free in the type Explicit => the variables the user wrote (renamed) Qualified currently behaves exactly as Implicit, but it is deprecated to use it for implicit quantification. In this case, GHC 7.10 gives a warning; see Note [Context quantification] in RnTypes, and Trac #4426. In GHC 8.0, Qualified will no longer bind variables and this will become an error. The kind variables bound in the hsq_implicit field come both a) from the kind signatures on the kind vars (eg k1) b) from the scope of the forall (eg k2) Example: f :: forall (a::k1) b. T a (b::k2) Note [Unit tuples] ~~~~~~~~~~~~~~~~~~ Consider the type type instance F Int = () We want to parse that "()" as HsTupleTy HsBoxedOrConstraintTuple [], NOT as HsTyVar unitTyCon Why? Because F might have kind (* -> Constraint), so we when parsing we don't know if that tuple is going to be a constraint tuple or an ordinary unit tuple. The HsTupleSort flag is specifically designed to deal with that, but it has to work for unit tuples too. Note [Promotions (HsTyVar)] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ HsTyVar: A name in a type or kind. Here are the allowed namespaces for the name. In a type: Var: not allowed Data: promoted data constructor Tv: type variable TcCls before renamer: type constructor, class constructor, or promoted data constructor TcCls after renamer: type constructor or class constructor In a kind: Var, Data: not allowed Tv: kind variable TcCls: kind constructor or promoted type constructor The 'Promoted' field in an HsTyVar captures whether the type was promoted in the source code by prefixing an apostrophe. Note [HsAppsTy] ~~~~~~~~~~~~~~~ How to parse Foo * Int ? Is it `(*) Foo Int` or `Foo GHC.Types.* Int`? There's no way to know until renaming. So we just take type expressions like this and put each component in a list, so be sorted out in the renamer. The sorting out is done by RnTypes.mkHsOpTyRn. This means that the parser should never produce HsAppTy or HsOpTy. Note [Promoted lists and tuples] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Notice the difference between HsListTy HsExplicitListTy HsTupleTy HsExplicitListTupleTy E.g. f :: [Int] HsListTy g3 :: T '[] All these use g2 :: T '[True] HsExplicitListTy g1 :: T '[True,False] g1a :: T [True,False] (can omit ' where unambiguous) kind of T :: [Bool] -> * This kind uses HsListTy! E.g. h :: (Int,Bool) HsTupleTy; f is a pair k :: S '(True,False) HsExplicitTypleTy; S is indexed by a type-level pair of booleans kind of S :: (Bool,Bool) -> * This kind uses HsExplicitTupleTy Note [Distinguishing tuple kinds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Apart from promotion, tuples can have one of three different kinds: x :: (Int, Bool) -- Regular boxed tuples f :: Int# -> (# Int#, Int# #) -- Unboxed tuples g :: (Eq a, Ord a) => a -- Constraint tuples For convenience, internally we use a single constructor for all of these, namely HsTupleTy, but keep track of the tuple kind (in the first argument to HsTupleTy, a HsTupleSort). We can tell if a tuple is unboxed while parsing, because of the #. However, with -XConstraintKinds we can only distinguish between constraint and boxed tuples during type checking, in general. Hence the four constructors of HsTupleSort: HsUnboxedTuple -> Produced by the parser HsBoxedTuple -> Certainly a boxed tuple HsConstraintTuple -> Certainly a constraint tuple HsBoxedOrConstraintTuple -> Could be a boxed or a constraint tuple. Produced by the parser only, disappears after type checking -} -- | Haskell Tuple Sort data HsTupleSort = HsUnboxedTuple | HsBoxedTuple | HsConstraintTuple | HsBoxedOrConstraintTuple deriving Data -- | Promoted data types. data Promoted = Promoted | NotPromoted deriving (Data, Eq, Show) -- | Located Constructor Declaration Field type LConDeclField name = Located (ConDeclField name) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when -- in a list -- For details on above see note [Api annotations] in ApiAnnotation -- | Constructor Declaration Field data ConDeclField name -- Record fields have Haddoc docs on them = ConDeclField { cd_fld_names :: [LFieldOcc name], -- ^ See Note [ConDeclField names] cd_fld_type :: LBangType name, cd_fld_doc :: Maybe LHsDocString } -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation deriving instance (DataId name) => Data (ConDeclField name) instance (OutputableBndrId name) => Outputable (ConDeclField name) where ppr (ConDeclField fld_n fld_ty _) = ppr fld_n <+> dcolon <+> ppr fld_ty -- HsConDetails is used for patterns/expressions *and* for data type -- declarations -- | Haskell Constructor Details data HsConDetails arg rec = PrefixCon [arg] -- C p1 p2 p3 | RecCon rec -- C { x = p1, y = p2 } | InfixCon arg arg -- p1 `C` p2 deriving Data instance (Outputable arg, Outputable rec) => Outputable (HsConDetails arg rec) where ppr (PrefixCon args) = text "PrefixCon" <+> ppr args ppr (RecCon rec) = text "RecCon:" <+> ppr rec ppr (InfixCon l r) = text "InfixCon:" <+> ppr [l, r] -- Takes details and result type of a GADT data constructor as created by the -- parser and rejigs them using information about fixities from the renamer. -- See Note [Sorting out the result type] in RdrHsSyn updateGadtResult :: (Monad m) => (SDoc -> m ()) -> SDoc -> HsConDetails (LHsType Name) (Located [LConDeclField Name]) -- ^ Original details -> LHsType Name -- ^ Original result type -> m (HsConDetails (LHsType Name) (Located [LConDeclField Name]), LHsType Name) updateGadtResult failWith doc details ty = do { let (arg_tys, res_ty) = splitHsFunType ty badConSig = text "Malformed constructor signature" ; case details of InfixCon {} -> pprPanic "updateGadtResult" (ppr ty) RecCon {} -> do { unless (null arg_tys) (failWith (doc <+> badConSig)) ; return (details, res_ty) } PrefixCon {} -> return (PrefixCon arg_tys, res_ty)} {- Note [ConDeclField names] ~~~~~~~~~~~~~~~~~~~~~~~~~ A ConDeclField contains a list of field occurrences: these always include the field label as the user wrote it. After the renamer, it will additionally contain the identity of the selector function in the second component. Due to DuplicateRecordFields, the OccName of the selector function may have been mangled, which is why we keep the original field label separately. For example, when DuplicateRecordFields is enabled data T = MkT { x :: Int } gives ConDeclField { cd_fld_names = [L _ (FieldOcc "x" $sel:x:MkT)], ... }. -} ----------------------- -- A valid type must have a for-all at the top of the type, or of the fn arg -- types --------------------- hsWcScopedTvs :: LHsSigWcType Name -> [Name] -- Get the lexically-scoped type variables of a HsSigType -- - the explicitly-given forall'd type variables -- - the implicitly-bound kind variables -- - the named wildcars; see Note [Scoping of named wildcards] -- because they scope in the same way hsWcScopedTvs sig_ty | HsWC { hswc_wcs = nwcs, hswc_body = sig_ty1 } <- sig_ty , HsIB { hsib_vars = vars, hsib_body = sig_ty2 } <- sig_ty1 = case sig_ty2 of L _ (HsForAllTy { hst_bndrs = tvs }) -> vars ++ nwcs ++ map hsLTyVarName tvs -- include kind variables only if the type is headed by forall -- (this is consistent with GHC 7 behaviour) _ -> nwcs hsScopedTvs :: LHsSigType Name -> [Name] -- Same as hsWcScopedTvs, but for a LHsSigType hsScopedTvs sig_ty | HsIB { hsib_vars = vars, hsib_body = sig_ty2 } <- sig_ty , L _ (HsForAllTy { hst_bndrs = tvs }) <- sig_ty2 = vars ++ map hsLTyVarName tvs | otherwise = [] {- Note [Scoping of named wildcards] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: _a -> _a f x = let g :: _a -> _a g = ... in ... Currently, for better or worse, the "_a" variables are all the same. So although there is no explicit forall, the "_a" scopes over the definition. I don't know if this is a good idea, but there it is. -} --------------------- hsTyVarName :: HsTyVarBndr name -> name hsTyVarName (UserTyVar (L _ n)) = n hsTyVarName (KindedTyVar (L _ n) _) = n hsLTyVarName :: LHsTyVarBndr name -> name hsLTyVarName = hsTyVarName . unLoc hsExplicitLTyVarNames :: LHsQTyVars name -> [name] -- Explicit variables only hsExplicitLTyVarNames qtvs = map hsLTyVarName (hsQTvExplicit qtvs) hsAllLTyVarNames :: LHsQTyVars Name -> [Name] -- All variables hsAllLTyVarNames (HsQTvs { hsq_implicit = kvs, hsq_explicit = tvs }) = kvs ++ map hsLTyVarName tvs hsLTyVarLocName :: LHsTyVarBndr name -> Located name hsLTyVarLocName = fmap hsTyVarName hsLTyVarLocNames :: LHsQTyVars name -> [Located name] hsLTyVarLocNames qtvs = map hsLTyVarLocName (hsQTvExplicit qtvs) -- | Convert a LHsTyVarBndr to an equivalent LHsType. hsLTyVarBndrToType :: LHsTyVarBndr name -> LHsType name hsLTyVarBndrToType = fmap cvt where cvt (UserTyVar n) = HsTyVar NotPromoted n cvt (KindedTyVar (L name_loc n) kind) = HsKindSig (L name_loc (HsTyVar NotPromoted (L name_loc n))) kind -- | Convert a LHsTyVarBndrs to a list of types. -- Works on *type* variable only, no kind vars. hsLTyVarBndrsToTypes :: LHsQTyVars name -> [LHsType name] hsLTyVarBndrsToTypes (HsQTvs { hsq_explicit = tvbs }) = map hsLTyVarBndrToType tvbs --------------------- wildCardName :: HsWildCardInfo Name -> Name wildCardName (AnonWildCard (L _ n)) = n -- Two wild cards are the same when they have the same location sameWildCard :: Located (HsWildCardInfo name) -> Located (HsWildCardInfo name) -> Bool sameWildCard (L l1 (AnonWildCard _)) (L l2 (AnonWildCard _)) = l1 == l2 ignoreParens :: LHsType name -> LHsType name ignoreParens (L _ (HsParTy ty)) = ignoreParens ty ignoreParens (L _ (HsAppsTy [L _ (HsAppPrefix ty)])) = ignoreParens ty ignoreParens ty = ty {- ************************************************************************ * * Building types * * ************************************************************************ -} mkAnonWildCardTy :: HsType RdrName mkAnonWildCardTy = HsWildCardTy (AnonWildCard PlaceHolder) mkHsOpTy :: LHsType name -> Located name -> LHsType name -> HsType name mkHsOpTy ty1 op ty2 = HsOpTy ty1 op ty2 mkHsAppTy :: LHsType name -> LHsType name -> LHsType name mkHsAppTy t1 t2 = addCLoc t1 t2 (HsAppTy t1 t2) mkHsAppTys :: LHsType name -> [LHsType name] -> LHsType name mkHsAppTys = foldl mkHsAppTy {- ************************************************************************ * * Decomposing HsTypes * * ************************************************************************ -} --------------------------------- -- splitHsFunType decomposes a type (t1 -> t2 ... -> tn) -- Breaks up any parens in the result type: -- splitHsFunType (a -> (b -> c)) = ([a,b], c) -- Also deals with (->) t1 t2; that is why it only works on LHsType Name -- (see Trac #9096) splitHsFunType :: LHsType Name -> ([LHsType Name], LHsType Name) splitHsFunType (L _ (HsParTy ty)) = splitHsFunType ty splitHsFunType (L _ (HsFunTy x y)) | (args, res) <- splitHsFunType y = (x:args, res) splitHsFunType orig_ty@(L _ (HsAppTy t1 t2)) = go t1 [t2] where -- Look for (->) t1 t2, possibly with parenthesisation go (L _ (HsTyVar _ (L _ fn))) tys | fn == funTyConName , [t1,t2] <- tys , (args, res) <- splitHsFunType t2 = (t1:args, res) go (L _ (HsAppTy t1 t2)) tys = go t1 (t2:tys) go (L _ (HsParTy ty)) tys = go ty tys go _ _ = ([], orig_ty) -- Failure to match splitHsFunType other = ([], other) -------------------------------- -- | Retrieves the head of an HsAppsTy, if this can be done unambiguously, -- without consulting fixities. getAppsTyHead_maybe :: [LHsAppType name] -> Maybe (LHsType name, [LHsType name], LexicalFixity) getAppsTyHead_maybe tys = case splitHsAppsTy tys of ([app1:apps], []) -> -- no symbols, some normal types Just (mkHsAppTys app1 apps, [], Prefix) ([app1l:appsl, app1r:appsr], [L loc op]) -> -- one operator Just ( L loc (HsTyVar NotPromoted (L loc op)) , [mkHsAppTys app1l appsl, mkHsAppTys app1r appsr], Infix) _ -> -- can't figure it out Nothing -- | Splits a [HsAppType name] (the payload of an HsAppsTy) into regions of prefix -- types (normal types) and infix operators. -- If @splitHsAppsTy tys = (non_syms, syms)@, then @tys@ starts with the first -- element of @non_syms@ followed by the first element of @syms@ followed by -- the next element of @non_syms@, etc. It is guaranteed that the non_syms list -- has one more element than the syms list. splitHsAppsTy :: [LHsAppType name] -> ([[LHsType name]], [Located name]) splitHsAppsTy = go [] [] [] where go acc acc_non acc_sym [] = (reverse (reverse acc : acc_non), reverse acc_sym) go acc acc_non acc_sym (L _ (HsAppPrefix ty) : rest) = go (ty : acc) acc_non acc_sym rest go acc acc_non acc_sym (L _ (HsAppInfix op) : rest) = go [] (reverse acc : acc_non) (op : acc_sym) rest -- Retrieve the name of the "head" of a nested type application -- somewhat like splitHsAppTys, but a little more thorough -- used to examine the result of a GADT-like datacon, so it doesn't handle -- *all* cases (like lists, tuples, (~), etc.) hsTyGetAppHead_maybe :: LHsType name -> Maybe (Located name, [LHsType name]) hsTyGetAppHead_maybe = go [] where go tys (L _ (HsTyVar _ ln)) = Just (ln, tys) go tys (L _ (HsAppsTy apps)) | Just (head, args, _) <- getAppsTyHead_maybe apps = go (args ++ tys) head go tys (L _ (HsAppTy l r)) = go (r : tys) l go tys (L _ (HsOpTy l (L loc n) r)) = Just (L loc n, l : r : tys) go tys (L _ (HsParTy t)) = go tys t go tys (L _ (HsKindSig t _)) = go tys t go _ _ = Nothing splitHsAppTys :: LHsType Name -> [LHsType Name] -> (LHsType Name, [LHsType Name]) -- no need to worry about HsAppsTy here splitHsAppTys (L _ (HsAppTy f a)) as = splitHsAppTys f (a:as) splitHsAppTys (L _ (HsParTy f)) as = splitHsAppTys f as splitHsAppTys f as = (f,as) -------------------------------- splitLHsPatSynTy :: LHsType name -> ( [LHsTyVarBndr name] -- universals , LHsContext name -- required constraints , [LHsTyVarBndr name] -- existentials , LHsContext name -- provided constraints , LHsType name) -- body type splitLHsPatSynTy ty = (univs, reqs, exis, provs, ty4) where (univs, ty1) = splitLHsForAllTy ty (reqs, ty2) = splitLHsQualTy ty1 (exis, ty3) = splitLHsForAllTy ty2 (provs, ty4) = splitLHsQualTy ty3 splitLHsSigmaTy :: LHsType name -> ([LHsTyVarBndr name], LHsContext name, LHsType name) splitLHsSigmaTy ty | (tvs, ty1) <- splitLHsForAllTy ty , (ctxt, ty2) <- splitLHsQualTy ty1 = (tvs, ctxt, ty2) splitLHsForAllTy :: LHsType name -> ([LHsTyVarBndr name], LHsType name) splitLHsForAllTy (L _ (HsForAllTy { hst_bndrs = tvs, hst_body = body })) = (tvs, body) splitLHsForAllTy body = ([], body) splitLHsQualTy :: LHsType name -> (LHsContext name, LHsType name) splitLHsQualTy (L _ (HsQualTy { hst_ctxt = ctxt, hst_body = body })) = (ctxt, body) splitLHsQualTy body = (noLoc [], body) splitLHsInstDeclTy :: LHsSigType Name -> ([Name], LHsContext Name, LHsType Name) -- Split up an instance decl type, returning the pieces splitLHsInstDeclTy (HsIB { hsib_vars = itkvs , hsib_body = inst_ty }) | (tvs, cxt, body_ty) <- splitLHsSigmaTy inst_ty = (itkvs ++ map hsLTyVarName tvs, cxt, body_ty) -- Return implicitly bound type and kind vars -- For an instance decl, all of them are in scope where getLHsInstDeclHead :: LHsSigType name -> LHsType name getLHsInstDeclHead inst_ty | (_tvs, _cxt, body_ty) <- splitLHsSigmaTy (hsSigType inst_ty) = body_ty getLHsInstDeclClass_maybe :: LHsSigType name -> Maybe (Located name) -- Works on (HsSigType RdrName) getLHsInstDeclClass_maybe inst_ty = do { let head_ty = getLHsInstDeclHead inst_ty ; (cls, _) <- hsTyGetAppHead_maybe head_ty ; return cls } {- ************************************************************************ * * FieldOcc * * ************************************************************************ -} -- | Located Field Occurrence type LFieldOcc name = Located (FieldOcc name) -- | Field Occurrence -- -- Represents an *occurrence* of an unambiguous field. We store -- both the 'RdrName' the user originally wrote, and after the -- renamer, the selector function. data FieldOcc name = FieldOcc { rdrNameFieldOcc :: Located RdrName -- ^ See Note [Located RdrNames] in HsExpr , selectorFieldOcc :: PostRn name name } deriving instance Eq (PostRn name name) => Eq (FieldOcc name) deriving instance Ord (PostRn name name) => Ord (FieldOcc name) deriving instance (Data name, Data (PostRn name name)) => Data (FieldOcc name) instance Outputable (FieldOcc name) where ppr = ppr . rdrNameFieldOcc mkFieldOcc :: Located RdrName -> FieldOcc RdrName mkFieldOcc rdr = FieldOcc rdr PlaceHolder -- | Ambiguous Field Occurrence -- -- Represents an *occurrence* of a field that is potentially -- ambiguous after the renamer, with the ambiguity resolved by the -- typechecker. We always store the 'RdrName' that the user -- originally wrote, and store the selector function after the renamer -- (for unambiguous occurrences) or the typechecker (for ambiguous -- occurrences). -- -- See Note [HsRecField and HsRecUpdField] in HsPat and -- Note [Disambiguating record fields] in TcExpr. -- See Note [Located RdrNames] in HsExpr data AmbiguousFieldOcc name = Unambiguous (Located RdrName) (PostRn name name) | Ambiguous (Located RdrName) (PostTc name name) deriving instance ( Data name , Data (PostRn name name) , Data (PostTc name name)) => Data (AmbiguousFieldOcc name) instance Outputable (AmbiguousFieldOcc name) where ppr = ppr . rdrNameAmbiguousFieldOcc instance OutputableBndr (AmbiguousFieldOcc name) where pprInfixOcc = pprInfixOcc . rdrNameAmbiguousFieldOcc pprPrefixOcc = pprPrefixOcc . rdrNameAmbiguousFieldOcc mkAmbiguousFieldOcc :: Located RdrName -> AmbiguousFieldOcc RdrName mkAmbiguousFieldOcc rdr = Unambiguous rdr PlaceHolder rdrNameAmbiguousFieldOcc :: AmbiguousFieldOcc name -> RdrName rdrNameAmbiguousFieldOcc (Unambiguous (L _ rdr) _) = rdr rdrNameAmbiguousFieldOcc (Ambiguous (L _ rdr) _) = rdr selectorAmbiguousFieldOcc :: AmbiguousFieldOcc Id -> Id selectorAmbiguousFieldOcc (Unambiguous _ sel) = sel selectorAmbiguousFieldOcc (Ambiguous _ sel) = sel unambiguousFieldOcc :: AmbiguousFieldOcc Id -> FieldOcc Id unambiguousFieldOcc (Unambiguous rdr sel) = FieldOcc rdr sel unambiguousFieldOcc (Ambiguous rdr sel) = FieldOcc rdr sel ambiguousFieldOcc :: FieldOcc name -> AmbiguousFieldOcc name ambiguousFieldOcc (FieldOcc rdr sel) = Unambiguous rdr sel {- ************************************************************************ * * \subsection{Pretty printing} * * ************************************************************************ -} instance (OutputableBndrId name) => Outputable (HsType name) where ppr ty = pprHsType ty instance Outputable HsTyLit where ppr = ppr_tylit instance (OutputableBndrId name) => Outputable (LHsQTyVars name) where ppr (HsQTvs { hsq_explicit = tvs }) = interppSP tvs instance (OutputableBndrId name) => Outputable (HsTyVarBndr name) where ppr (UserTyVar n) = ppr n ppr (KindedTyVar n k) = parens $ hsep [ppr n, dcolon, ppr k] instance (Outputable thing) => Outputable (HsImplicitBndrs name thing) where ppr (HsIB { hsib_body = ty }) = ppr ty instance (Outputable thing) => Outputable (HsWildCardBndrs name thing) where ppr (HsWC { hswc_body = ty }) = ppr ty instance Outputable (HsWildCardInfo name) where ppr (AnonWildCard _) = char '_' pprHsForAll :: (OutputableBndrId name) => [LHsTyVarBndr name] -> LHsContext name -> SDoc pprHsForAll = pprHsForAllExtra Nothing -- | Version of 'pprHsForAll' that can also print an extra-constraints -- wildcard, e.g. @_ => a -> Bool@ or @(Show a, _) => a -> String@. This -- underscore will be printed when the 'Maybe SrcSpan' argument is a 'Just' -- containing the location of the extra-constraints wildcard. A special -- function for this is needed, as the extra-constraints wildcard is removed -- from the actual context and type, and stored in a separate field, thus just -- printing the type will not print the extra-constraints wildcard. pprHsForAllExtra :: (OutputableBndrId name) => Maybe SrcSpan -> [LHsTyVarBndr name] -> LHsContext name -> SDoc pprHsForAllExtra extra qtvs cxt = pprHsForAllTvs qtvs <+> pprHsContextExtra show_extra (unLoc cxt) where show_extra = isJust extra pprHsForAllTvs :: (OutputableBndrId name) => [LHsTyVarBndr name] -> SDoc pprHsForAllTvs qtvs | show_forall = forAllLit <+> interppSP qtvs <> dot | otherwise = empty where show_forall = opt_PprStyle_Debug || not (null qtvs) pprHsContext :: (OutputableBndrId name) => HsContext name -> SDoc pprHsContext = maybe empty (<+> darrow) . pprHsContextMaybe pprHsContextNoArrow :: (OutputableBndrId name) => HsContext name -> SDoc pprHsContextNoArrow = fromMaybe empty . pprHsContextMaybe pprHsContextMaybe :: (OutputableBndrId name) => HsContext name -> Maybe SDoc pprHsContextMaybe [] = Nothing pprHsContextMaybe [L _ pred] = Just $ ppr_mono_ty FunPrec pred pprHsContextMaybe cxt = Just $ parens (interpp'SP cxt) -- For use in a HsQualTy, which always gets printed if it exists. pprHsContextAlways :: (OutputableBndrId name) => HsContext name -> SDoc pprHsContextAlways [] = parens empty <+> darrow pprHsContextAlways [L _ ty] = ppr_mono_ty FunPrec ty <+> darrow pprHsContextAlways cxt = parens (interpp'SP cxt) <+> darrow -- True <=> print an extra-constraints wildcard, e.g. @(Show a, _) =>@ pprHsContextExtra :: (OutputableBndrId name) => Bool -> HsContext name -> SDoc pprHsContextExtra show_extra ctxt | not show_extra = pprHsContext ctxt | null ctxt = char '_' <+> darrow | otherwise = parens (sep (punctuate comma ctxt')) <+> darrow where ctxt' = map ppr ctxt ++ [char '_'] pprConDeclFields :: (OutputableBndrId name) => [LConDeclField name] -> SDoc pprConDeclFields fields = braces (sep (punctuate comma (map ppr_fld fields))) where ppr_fld (L _ (ConDeclField { cd_fld_names = ns, cd_fld_type = ty, cd_fld_doc = doc })) = ppr_names ns <+> dcolon <+> ppr ty <+> ppr_mbDoc doc ppr_names [n] = ppr n ppr_names ns = sep (punctuate comma (map ppr ns)) {- Note [Printing KindedTyVars] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Trac #3830 reminded me that we should really only print the kind signature on a KindedTyVar if the kind signature was put there by the programmer. During kind inference GHC now adds a PostTcKind to UserTyVars, rather than converting to KindedTyVars as before. (As it happens, the message in #3830 comes out a different way now, and the problem doesn't show up; but having the flag on a KindedTyVar seems like the Right Thing anyway.) -} -- Printing works more-or-less as for Types pprHsType, pprParendHsType :: (OutputableBndrId name) => HsType name -> SDoc pprHsType ty = ppr_mono_ty TopPrec ty pprParendHsType ty = ppr_mono_ty TyConPrec ty ppr_mono_lty :: (OutputableBndrId name) => TyPrec -> LHsType name -> SDoc ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty) ppr_mono_ty :: (OutputableBndrId name) => TyPrec -> HsType name -> SDoc ppr_mono_ty ctxt_prec (HsForAllTy { hst_bndrs = tvs, hst_body = ty }) = maybeParen ctxt_prec FunPrec $ sep [pprHsForAllTvs tvs, ppr_mono_lty TopPrec ty] ppr_mono_ty _ctxt_prec (HsQualTy { hst_ctxt = L _ ctxt, hst_body = ty }) = sep [pprHsContextAlways ctxt, ppr_mono_lty TopPrec ty] ppr_mono_ty _ (HsBangTy b ty) = ppr b <> ppr_mono_lty TyConPrec ty ppr_mono_ty _ (HsRecTy flds) = pprConDeclFields flds ppr_mono_ty _ (HsTyVar NotPromoted (L _ name))= pprPrefixOcc name ppr_mono_ty _ (HsTyVar Promoted (L _ name)) = space <> quote (pprPrefixOcc name) -- We need a space before the ' above, so the parser -- does not attach it to the previous symbol ppr_mono_ty prec (HsFunTy ty1 ty2) = ppr_fun_ty prec ty1 ty2 ppr_mono_ty _ (HsTupleTy con tys) = tupleParens std_con (pprWithCommas ppr tys) where std_con = case con of HsUnboxedTuple -> UnboxedTuple _ -> BoxedTuple ppr_mono_ty _ (HsSumTy tys) = tupleParens UnboxedTuple (pprWithBars ppr tys) ppr_mono_ty _ (HsKindSig ty kind) = parens (ppr_mono_lty TopPrec ty <+> dcolon <+> ppr kind) ppr_mono_ty _ (HsListTy ty) = brackets (ppr_mono_lty TopPrec ty) ppr_mono_ty _ (HsPArrTy ty) = paBrackets (ppr_mono_lty TopPrec ty) ppr_mono_ty prec (HsIParamTy n ty) = maybeParen prec FunPrec (ppr n <+> dcolon <+> ppr_mono_lty TopPrec ty) ppr_mono_ty _ (HsSpliceTy s _) = pprSplice s ppr_mono_ty _ (HsCoreTy ty) = ppr ty ppr_mono_ty _ (HsExplicitListTy Promoted _ tys) = quote $ brackets (interpp'SP tys) ppr_mono_ty _ (HsExplicitListTy NotPromoted _ tys) = brackets (interpp'SP tys) ppr_mono_ty _ (HsExplicitTupleTy _ tys) = quote $ parens (interpp'SP tys) ppr_mono_ty _ (HsTyLit t) = ppr_tylit t ppr_mono_ty _ (HsWildCardTy {}) = char '_' ppr_mono_ty ctxt_prec (HsEqTy ty1 ty2) = maybeParen ctxt_prec TyOpPrec $ ppr_mono_lty TyOpPrec ty1 <+> char '~' <+> ppr_mono_lty TyOpPrec ty2 ppr_mono_ty _ctxt_prec (HsAppsTy tys) = hsep (map (ppr_app_ty TopPrec . unLoc) tys) ppr_mono_ty _ctxt_prec (HsAppTy fun_ty arg_ty) = hsep [ppr_mono_lty FunPrec fun_ty, ppr_mono_lty TyConPrec arg_ty] ppr_mono_ty ctxt_prec (HsOpTy ty1 (L _ op) ty2) = maybeParen ctxt_prec TyOpPrec $ sep [ ppr_mono_lty TyOpPrec ty1 , sep [pprInfixOcc op, ppr_mono_lty TyOpPrec ty2 ] ] ppr_mono_ty _ (HsParTy ty) = parens (ppr_mono_lty TopPrec ty) -- Put the parens in where the user did -- But we still use the precedence stuff to add parens because -- toHsType doesn't put in any HsParTys, so we may still need them ppr_mono_ty ctxt_prec (HsDocTy ty doc) = maybeParen ctxt_prec TyOpPrec $ ppr_mono_lty TyOpPrec ty <+> ppr (unLoc doc) -- we pretty print Haddock comments on types as if they were -- postfix operators -------------------------- ppr_fun_ty :: (OutputableBndrId name) => TyPrec -> LHsType name -> LHsType name -> SDoc ppr_fun_ty ctxt_prec ty1 ty2 = let p1 = ppr_mono_lty FunPrec ty1 p2 = ppr_mono_lty TopPrec ty2 in maybeParen ctxt_prec FunPrec $ sep [p1, text "->" <+> p2] -------------------------- ppr_app_ty :: (OutputableBndrId name) => TyPrec -> HsAppType name -> SDoc ppr_app_ty _ (HsAppInfix (L _ n)) = pprInfixOcc n ppr_app_ty _ (HsAppPrefix (L _ (HsTyVar NotPromoted (L _ n)))) = pprPrefixOcc n ppr_app_ty _ (HsAppPrefix (L _ (HsTyVar Promoted (L _ n)))) = space <> quote (pprPrefixOcc n) -- We need a space before the ' above, so -- the parser does not attach it to the -- previous symbol ppr_app_ty ctxt (HsAppPrefix ty) = ppr_mono_lty ctxt ty -------------------------- ppr_tylit :: HsTyLit -> SDoc ppr_tylit (HsNumTy _ i) = integer i ppr_tylit (HsStrTy _ s) = text (show s)
olsner/ghc
compiler/hsSyn/HsTypes.hs
bsd-3-clause
53,102
1
17
13,611
8,712
4,700
4,012
553
7
{-# LANGUAGE CPP #-} #include "a.h" #include "b.h" bar :: Int -> Int bar = id
begriffs/hscope
t/files/CPP2.hs
bsd-3-clause
80
0
7
18
24
12
12
3
1
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "Network/HPACK/Table/Dynamic.hs" #-} {-# LANGUAGE TupleSections, RecordWildCards, FlexibleContexts #-} {-# LANGUAGE BangPatterns, CPP #-} module Network.HPACK.Table.Dynamic ( DynamicTable(..) , newDynamicTableForEncoding , newDynamicTableForDecoding , renewDynamicTable , huffmanDecoder , printDynamicTable , isDynamicTableEmpty , isSuitableSize , TableSizeAction(..) , needChangeTableSize , setLimitForEncoding , resetLimitForEncoding , insertEntry , toDynamicEntry , CodeInfo(..) , clearDynamicTable , withDynamicTableForEncoding , withDynamicTableForDecoding , toIndexedEntry , fromHIndexToIndex , getRevIndex ) where import Control.Exception (bracket, throwIO) import Control.Monad (forM, when, (>=>)) import Data.Array.Base (unsafeRead, unsafeWrite) import Data.Array.IO (IOArray, newArray) import qualified Data.ByteString.Char8 as BS import Data.IORef import Foreign.Marshal.Alloc import Network.HPACK.Huffman import Network.HPACK.Table.Entry import Network.HPACK.Table.RevIndex import Network.HPACK.Table.Static import Network.HPACK.Types ---------------------------------------------------------------- -- For decoder {-# INLINE toIndexedEntry #-} toIndexedEntry :: DynamicTable -> Index -> IO Entry toIndexedEntry dyntbl idx | idx <= 0 = throwIO $ IndexOverrun idx | idx <= staticTableSize = return $! toStaticEntry idx | otherwise = toDynamicEntry dyntbl idx -- For encoder {-# INLINE fromHIndexToIndex #-} fromHIndexToIndex :: DynamicTable -> HIndex -> IO Index fromHIndexToIndex _ (SIndex idx) = return idx fromHIndexToIndex DynamicTable{..} (DIndex didx) = do maxN <- readIORef maxNumOfEntries off <- readIORef offset x <- adj maxN (didx - off) return $! x + staticTableSize ---------------------------------------------------------------- type Table = IOArray Index Entry {- offset v +-+-+-+-+-+-+-+-+ | | | |z|y|x| | | +-+-+-+-+-+-+-+-+ 1 2 3 (numOfEntries = 3) After insertion: offset v +-+-+-+-+-+-+-+-+ | | |w|z|y|x| | | +-+-+-+-+-+-+-+-+ 1 2 3 4 (numOfEntries = 4) -} data CodeInfo = EncodeInfo !RevIndex -- Reverse index -- The value informed by SETTINGS_HEADER_TABLE_SIZE. -- If 'Nothing', dynamic table size update is not necessary. -- Otherwise, dynamic table size update is sent -- and this value should be set to 'Nothing'. !(IORef (Maybe Size)) | DecodeInfo !HuffmanDecoding !(IORef Size) -- The limit size !(IO ()) -- Action to free the buffer -- | Type for dynamic table. data DynamicTable = DynamicTable { codeInfo :: !CodeInfo -- | An array , circularTable :: !(IORef Table) -- | Start point , offset :: !(IORef Index) -- | The current number of entries , numOfEntries :: !(IORef Int) -- | The size of the array , maxNumOfEntries :: !(IORef Int) -- | The current dynamic table size (defined in HPACK) , dynamicTableSize :: !(IORef Size) -- | The max dynamic table size (defined in HPACK) , maxDynamicTableSize :: !(IORef Size) } {-# INLINE adj #-} adj :: Int -> Int -> IO Int adj maxN x | maxN == 0 = throwIO TooSmallTableSize | otherwise = let !ret = (x + maxN) `mod` maxN in return ret huffmanDecoder :: DynamicTable -> HuffmanDecoding huffmanDecoder DynamicTable{..} = dec where DecodeInfo dec _ _ = codeInfo ---------------------------------------------------------------- -- | Printing 'DynamicTable'. printDynamicTable :: DynamicTable -> IO () printDynamicTable DynamicTable{..} = do maxN <- readIORef maxNumOfEntries off <- readIORef offset n <- readIORef numOfEntries let !beg = off + 1 !end = off + n tbl <- readIORef circularTable es <- mapM (adj maxN >=> unsafeRead tbl) [beg .. end] let !ts = zip [1..] es mapM_ printEntry ts dsize <- readIORef dynamicTableSize maxdsize <- readIORef maxDynamicTableSize putStrLn $ " Table size: " ++ show dsize ++ "/" ++ show maxdsize printEntry :: (Index,Entry) -> IO () printEntry (i,e) = do putStr "[ " putStr $ show i putStr "] (s = " putStr $ show $ entrySize e putStr ") " BS.putStr $ entryHeaderName e putStr ": " BS.putStrLn $ entryHeaderValue e ---------------------------------------------------------------- isDynamicTableEmpty :: DynamicTable -> IO Bool isDynamicTableEmpty DynamicTable{..} = do n <- readIORef numOfEntries return $! n == 0 isSuitableSize :: Size -> DynamicTable -> IO Bool isSuitableSize siz DynamicTable{..} = do let DecodeInfo _ limref _ = codeInfo lim <- readIORef limref return $! siz <= lim data TableSizeAction = Keep | Change !Size | Ignore !Size needChangeTableSize :: DynamicTable -> IO TableSizeAction needChangeTableSize DynamicTable{..} = do let EncodeInfo _ limref = codeInfo mlim <- readIORef limref maxsiz <- readIORef maxDynamicTableSize return $ case mlim of Nothing -> Keep Just lim | lim < maxsiz -> Change lim | otherwise -> Ignore maxsiz -- | When SETTINGS_HEADER_TABLE_SIZE is received from a peer, -- its value should be set by this function. setLimitForEncoding :: Size -> DynamicTable -> IO () setLimitForEncoding siz DynamicTable{..} = do let EncodeInfo _ limref = codeInfo writeIORef limref $ Just siz resetLimitForEncoding :: DynamicTable -> IO () resetLimitForEncoding DynamicTable{..} = do let EncodeInfo _ limref = codeInfo writeIORef limref Nothing ---------------------------------------------------------------- -- | Creating 'DynamicTable' for encoding. newDynamicTableForEncoding :: Size -- ^ The dynamic table size -> IO DynamicTable newDynamicTableForEncoding maxsiz = do rev <- newRevIndex lim <- newIORef Nothing let !info = EncodeInfo rev lim newDynamicTable maxsiz info -- | Creating 'DynamicTable' for decoding. newDynamicTableForDecoding :: Size -- ^ The dynamic table size -> Size -- ^ The size of temporary buffer for Huffman decoding -> IO DynamicTable newDynamicTableForDecoding maxsiz huftmpsiz = do lim <- newIORef maxsiz buf <- mallocBytes huftmpsiz let !decoder = decode buf huftmpsiz !clear = free buf !info = DecodeInfo decoder lim clear newDynamicTable maxsiz info newDynamicTable :: Size -> CodeInfo -> IO DynamicTable newDynamicTable maxsiz info = do tbl <- newArray (0,end) dummyEntry DynamicTable info <$> newIORef tbl -- circularTable <*> newIORef end -- offset <*> newIORef 0 -- numOfEntries <*> newIORef maxN -- maxNumOfEntries <*> newIORef 0 -- dynamicTableSize <*> newIORef maxsiz -- maxDynamicTableSize where !maxN = maxNumbers maxsiz !end = maxN - 1 -- | Renewing 'DynamicTable' with necessary entries copied. renewDynamicTable :: Size -> DynamicTable -> IO () renewDynamicTable maxsiz dyntbl@DynamicTable{..} = do renew <- shouldRenew dyntbl maxsiz when renew $ do !entries <- getEntries dyntbl let !maxN = maxNumbers maxsiz !end = maxN - 1 newtbl <- newArray (0,end) dummyEntry writeIORef circularTable newtbl writeIORef offset end writeIORef numOfEntries 0 writeIORef maxNumOfEntries maxN writeIORef dynamicTableSize 0 writeIORef maxDynamicTableSize maxsiz case codeInfo of EncodeInfo rev _ -> renewRevIndex rev _ -> return () copyEntries dyntbl entries getEntries :: DynamicTable -> IO [Entry] getEntries DynamicTable{..} = do maxN <- readIORef maxNumOfEntries off <- readIORef offset n <- readIORef numOfEntries table <- readIORef circularTable let readTable i = adj maxN (off + i) >>= unsafeRead table forM [1 .. n] readTable copyEntries :: DynamicTable -> [Entry] -> IO () copyEntries _ [] = return () copyEntries dyntbl@DynamicTable{..} (e:es) = do dsize <- readIORef dynamicTableSize maxdsize <- readIORef maxDynamicTableSize when (dsize + entrySize e <= maxdsize) $ do insertEnd e dyntbl copyEntries dyntbl es -- | Is the size of 'DynamicTable' really changed? shouldRenew :: DynamicTable -> Size -> IO Bool shouldRenew DynamicTable{..} maxsiz = do maxdsize <- readIORef maxDynamicTableSize return $! maxdsize /= maxsiz ---------------------------------------------------------------- -- | Creating 'DynamicTable' for encoding, -- performing the action and -- clearing the 'DynamicTable'. withDynamicTableForEncoding :: Size -- ^ The dynamic table size -> (DynamicTable -> IO a) -> IO a withDynamicTableForEncoding maxsiz action = bracket (newDynamicTableForEncoding maxsiz) clearDynamicTable action -- | Creating 'DynamicTable' for decoding, -- performing the action and -- clearing the 'DynamicTable'. withDynamicTableForDecoding :: Size -- ^ The dynamic table size -> Size -- ^ The size of temporary buffer for Huffman -> (DynamicTable -> IO a) -> IO a withDynamicTableForDecoding maxsiz huftmpsiz action = bracket (newDynamicTableForDecoding maxsiz huftmpsiz) clearDynamicTable action -- | Clearing 'DynamicTable'. -- Currently, this frees the temporary buffer for Huffman decoding. clearDynamicTable :: DynamicTable -> IO () clearDynamicTable DynamicTable{..} = case codeInfo of EncodeInfo _ _ -> return () DecodeInfo _ _ clear -> clear ---------------------------------------------------------------- -- | Inserting 'Entry' to 'DynamicTable'. -- New 'DynamicTable', the largest new 'Index' -- and a set of dropped OLD 'Index' -- are returned. insertEntry :: Entry -> DynamicTable -> IO () insertEntry e dyntbl@DynamicTable{..} = do insertFront e dyntbl es <- adjustTableSize dyntbl case codeInfo of EncodeInfo rev _ -> deleteRevIndexList es rev _ -> return () insertFront :: Entry -> DynamicTable -> IO () insertFront e DynamicTable{..} = do maxN <- readIORef maxNumOfEntries off <- readIORef offset n <- readIORef numOfEntries dsize <- readIORef dynamicTableSize table <- readIORef circularTable let i = off !dsize' = dsize + entrySize e !off' <- adj maxN (off - 1) unsafeWrite table i e writeIORef offset off' writeIORef numOfEntries $ n + 1 writeIORef dynamicTableSize dsize' case codeInfo of EncodeInfo rev _ -> insertRevIndex e (DIndex i) rev _ -> return () adjustTableSize :: DynamicTable -> IO [Entry] adjustTableSize dyntbl@DynamicTable{..} = adjust [] where adjust :: [Entry] -> IO [Entry] adjust !es = do dsize <- readIORef dynamicTableSize maxdsize <- readIORef maxDynamicTableSize if dsize <= maxdsize then return es else do e <- removeEnd dyntbl adjust (e:es) ---------------------------------------------------------------- insertEnd :: Entry -> DynamicTable -> IO () insertEnd e DynamicTable{..} = do maxN <- readIORef maxNumOfEntries off <- readIORef offset n <- readIORef numOfEntries dsize <- readIORef dynamicTableSize table <- readIORef circularTable !i <- adj maxN (off + n + 1) let !dsize' = dsize + entrySize e unsafeWrite table i e writeIORef numOfEntries $ n + 1 writeIORef dynamicTableSize dsize' case codeInfo of EncodeInfo rev _ -> insertRevIndex e (DIndex i) rev _ -> return () ---------------------------------------------------------------- removeEnd :: DynamicTable -> IO Entry removeEnd DynamicTable{..} = do maxN <- readIORef maxNumOfEntries off <- readIORef offset n <- readIORef numOfEntries !i <- adj maxN (off + n) table <- readIORef circularTable e <- unsafeRead table i unsafeWrite table i dummyEntry -- let the entry GCed dsize <- readIORef dynamicTableSize let !dsize' = dsize - entrySize e writeIORef numOfEntries (n - 1) writeIORef dynamicTableSize dsize' return e ---------------------------------------------------------------- {-# INLINE toDynamicEntry #-} toDynamicEntry :: DynamicTable -> Index -> IO Entry toDynamicEntry DynamicTable{..} idx = do !maxN <- readIORef maxNumOfEntries !off <- readIORef offset !n <- readIORef numOfEntries when (idx > n + staticTableSize) $ throwIO $ IndexOverrun idx !didx <- adj maxN (idx + off - staticTableSize) !table <- readIORef circularTable unsafeRead table didx ---------------------------------------------------------------- {-# INLINE getRevIndex #-} getRevIndex :: DynamicTable-> RevIndex getRevIndex DynamicTable{..} = rev where EncodeInfo rev _ = codeInfo
phischu/fragnix
tests/packages/scotty/Network.HPACK.Table.Dynamic.hs
bsd-3-clause
13,289
0
14
3,340
3,276
1,567
1,709
315
2
-------------------------------------------------------------------------------- -- | -- Module : Environments.Gym.ClassicControl.MountainCarContinuousV0 -- Copyright : (c) Sentenai 2017 -- License : BSD3 -- Maintainer: [email protected] -- Stability : experimental -- -- Environment description: -- > A car is on a one-dimensional track, positioned between two "mountains". -- > The goal is to drive up the mountain on the right; however, the car's -- > engine is not strong enough to scale the mountain in a single pass. -- > Therefore, the only way to succeed is to drive back and forth to build up -- > momentum. Here, the reward is greater if you spend less energy to reach the -- > goal. -- > -- > MountainCarContinuous-v0 defines "solving" as getting average reward of -- > 90.0 over 100 consecutive trials. -- > -- > This problem was first described by Andrew Moore in his PhD thesis [Moore90]. -- > -- > Here, this is the continuous version. -- -- https://gym.openai.com/envs/MountainCarContinuous-v0 -------------------------------------------------------------------------------- module Environments.Gym.ClassicControl.MountainCarContinuousV0 ( Env.Action(..) , Env.Runner , Env.State(..) , Env.Environment , Env.EnvironmentT , runEnvironment , runEnvironmentT , runDefaultEnvironment , runDefaultEnvironmentT ) where -- import Reinforce.Prelude hiding (State) import Control.Monad.IO.Class import OpenAI.Gym (GymEnv(MountainCarContinuousV0)) import Servant.Client (BaseUrl) import Network.HTTP.Client (Manager) import Environments.Gym.ClassicControl.MountainCarV0 as Env hiding ( runEnvironment , runDefaultEnvironment , runEnvironmentT , runDefaultEnvironmentT ) import qualified Environments.Gym.Internal as I -- | Alias to 'Environments.Gym.Internal.runEnvironmentT' runEnvironmentT :: MonadIO t => Manager -> BaseUrl -> I.RunnerT State Action t x runEnvironmentT = I.runEnvironmentT MountainCarContinuousV0 -- | Alias to 'Environments.Gym.Internal.runEnvironment' in IO runEnvironment :: Manager -> BaseUrl -> I.RunnerT State Action IO x runEnvironment = I.runEnvironmentT MountainCarContinuousV0 -- | Alias to 'Environments.Gym.Internal.runDefaultEnvironmentT' runDefaultEnvironmentT :: MonadIO t => I.RunnerT State Action t x runDefaultEnvironmentT = I.runDefaultEnvironmentT MountainCarContinuousV0 -- | Alias to 'Environments.Gym.Internal.runDefaultEnvironment' in IO runDefaultEnvironment :: I.RunnerT State Action IO x runDefaultEnvironment = I.runDefaultEnvironmentT MountainCarContinuousV0
stites/reinforce
reinforce-environments-gym/src/Environments/Gym/ClassicControl/MountainCarContinuousV0.hs
bsd-3-clause
2,559
0
9
343
294
183
111
28
1
{-# LANGUAGE OverloadedStrings #-} module Vimus.Command.CompletionSpec (main, spec) where import Test.Hspec import Vimus.WindowLayout import Vimus.Type (Vimus) import Vimus.Command.Core import Vimus.Command.Completion main :: IO () main = hspec spec spec :: Spec spec = do describe "parseCommand" $ do it "parses a command" $ do parseCommand "add" `shouldBe` ("add", "") it "parses a command with arguments" $ do parseCommand "add some arguments" `shouldBe` ("add", "some arguments") it "ignores leading whitespace" $ do parseCommand " add" `shouldBe` ("add", "") it "parses an exclamation mark as command" $ do parseCommand "!" `shouldBe` ("!", "") it "parses an exclamation mark with arguments as command" $ do parseCommand "!foo bar baz" `shouldBe` ("!", "foo bar baz") it "ignores whitespace before and after an exclamation mark" $ do parseCommand " ! \t foo bar baz" `shouldBe` ("!", "foo bar baz") describe "completeCommand" $ do context "with a list of commands that take no arguments" $ do let complete = completeCommand [ command0 "foo" , command0 "bar" , command0 "baz" ] it "completes a command" $ do complete "f" `shouldBe` Right "foo " it "partially completes a command, on multiple matches with a common prefix" $ do complete "b" `shouldBe` Right "ba" it "gives suggestions, on multiple matches with no common prefix" $ do complete "ba" `shouldBe` Left ["bar", "baz"] it "tolerates whitespace in front of a command" $ do complete " f" `shouldBe` Right " foo " context "with two commands, where one is a prefix of the otehr" $ do let complete = completeCommand [command0 "foo", command0 "foobar"] it "completes only the common prefix" $ do complete "f" `shouldBe` Right "foo" context "given the common prefix as input" $ do it "suggests both command names" $ do complete "foo" `shouldBe` Left ["foo", "foobar"] context "with a command that takes arguments" $ do let complete = completeCommand [command "color" "" (undefined :: WindowColor -> Color -> Color -> Vimus ())] it "completes an argument" $ do complete "color m" `shouldBe` Right "color main " it "completes a second argument" $ do complete "color main r" `shouldBe` Right "color main red " it "completes a third argument" $ do complete "color main red gr" `shouldBe` Right "color main red green " it "gives suggestions for arguments" $ do complete "color main bl" `shouldBe` Left ["black", "blue"] it "tolerates whitespace" $ do complete " color main red gr" `shouldBe` Right " color main red green " context "with several commands with the same name" $ do let complete = completeCommand [ command "foo" "" (undefined :: Int -> Vimus ()) , command "foo" "" (undefined :: WindowColor -> Vimus ()) , command "foo" "" (undefined :: Color -> Vimus ()) ] it "completes arguments for the last command" $ do complete "foo r" `shouldBe` Right "foo red " where command0 name = command name "" (undefined :: Vimus ())
vimus/vimus
test/Vimus/Command/CompletionSpec.hs
mit
3,365
0
24
955
847
407
440
65
1
-- -- Copyright (c) 2012 Citrix Systems, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- {-# LANGUAGE ViewPatterns #-} module Perms ( Qualifier(..) , PermMode(..) , Perm(..) , Perms , PermTree(..) , PermPatchs(..) -- * IO , readPerms , writePerms -- * tree , emptyPermTree , initPermTree , addPermsToTree , getPerms , addPerm , rmPerm , chPerm , parsePermPatchs ) where import Path import Control.Applicative ((<$>)) import Data.Char (isDigit) import Utils (Uuid(..), parseJSON, pretty, readFileSafely, writeFileSafely) import Text.JSON import qualified Data.Map as M data Qualifier = QualDomid Int | QualUuid Uuid | QualName String | QualPropertyEq String String deriving (Eq) data PermMode = Read | Write | ReadWrite deriving (Eq) instance Show PermMode where show Read = "r" show Write = "w" show ReadWrite = "b" data Perm = Perm Qualifier PermMode deriving (Eq) instance Show Qualifier where show (QualUuid (Uuid uuid)) = uuid show (QualDomid domid) = show domid show (QualName n) = "@" ++ n show (QualPropertyEq s1 s2) = "{" ++ s1 ++ "==" ++ s2 ++ "}" instance Show Perm where show (Perm qual mode) = show mode ++ ":" ++ show qual data PermModification = PermAdd | PermDel deriving (Show,Eq) -- | a permpatch is a modification to apply to a tree. type PermPatch = (PermModification, Perm) -- | patches to apply to a tree. data PermPatchs = PermPatchs [PermPatch] deriving (Show,Eq) type Perms = M.Map Path [Perm] data PermTree = PermTree { treePerms :: M.Map Path Perms , rootPerms :: Perms } deriving (Show,Eq) pathFindLongest :: M.Map Path a -> Path -> Maybe (Path, a) pathFindLongest m iniPath = loop iniPath where loop path | isNullPath path = Nothing | otherwise = case M.lookup path m of Nothing -> loop (parentPath path) Just a -> Just (path, a) readPerms :: FilePath -> IO Perms readPerms filepath = either (const M.empty) toPerms . parseJSON <$> readFileSafely "{}" filepath where toPerms :: JSValue -> Perms toPerms (JSObject (fromJSObject -> ents)) = foldl add M.empty ents toPerms _ = M.empty -- very lenient parsing add :: Perms -> (String, JSValue) -> Perms add acc (k,JSArray a) = M.insert (pathOf k) (reverse $ foldl accPerm [] a) acc add acc (k,JSString (fromJSString -> s)) = case parsePerm s of Nothing -> acc Just p -> M.insert (pathOf k) [p] acc add acc _ = acc -- accumulate only string that are valid permission string accPerm :: [Perm] -> JSValue -> [Perm] accPerm acc (JSString (fromJSString -> s)) = case parsePerm s of Nothing -> acc Just p -> p : acc accPerm acc _ = acc writePerms :: FilePath -> Perms -> IO () writePerms filepath perms = writeFileSafely filepath $ pretty (JSObject (toJSObject $ map toJSON $ M.toList perms)) where toJSON (path, ps) = case ps of [x] -> (showPath path, toPermString x) _ -> (showPath path, JSArray $ map toPermString ps) toPermString perm = JSString $ toJSString $ show perm emptyPermTree :: PermTree emptyPermTree = initPermTree M.empty initPermTree :: Perms -> PermTree initPermTree root = PermTree M.empty root addPermsToTree :: (Path, Perms) -> PermTree -> PermTree addPermsToTree (x,y) (PermTree trees root) = PermTree (M.insert x y trees) root getPerms :: Path -> PermTree -> [Perm] getPerms path (PermTree other root) = case pathFindLongest other path of Nothing -> maybe [] snd $ pathFindLongest root path Just (prefix, tree) -> case pathFindLongest tree (prefix `substractPrefix` path) of Nothing -> getPerms path (PermTree M.empty root) Just (_,perm) -> perm addPerm :: Path -> Perm -> PermTree -> PermTree addPerm path perm pt@(PermTree other root) | origPerm == patchedPerm = pt | otherwise = case pathFindLongest other path of Nothing -> let newTree = M.alter updateOrInsertPerm path root in PermTree other newTree Just (prefix, tree) -> let subpath = prefix `substractPrefix` path newTree = M.alter updateOrInsertPerm subpath tree in PermTree (M.insert prefix newTree other) root where updateOrInsertPerm _ = Just patchedPerm origPerm = getPerms path pt patchedPerm = if perm `elem` origPerm then origPerm else perm:origPerm rmPerm :: Path -> Perm -> PermTree -> PermTree rmPerm path perm pt@(PermTree other root) | origPerm == patchedPerm = pt | otherwise = case pathFindLongest other path of Nothing -> let newTree = M.alter doRemove path root in PermTree other newTree Just (prefix, tree) -> let subpath = prefix `substractPrefix` path newTree = M.alter doRemove subpath tree in PermTree (M.insert prefix newTree other) root where doRemove _ = if null patchedPerm then Nothing else Just patchedPerm origPerm = getPerms path pt patchedPerm = filter (/= perm) origPerm chPerm :: Path -> PermPatchs -> PermTree -> PermTree chPerm path (PermPatchs permpatch) pt = loop pt permpatch where loop permtree [] = permtree loop permtree (x:xs) = let newPT = case x of (PermAdd, z) -> addPerm path z permtree (PermDel, z) -> rmPerm path z permtree in loop newPT xs -- permission string is one of "rwb" followed by : followed by an uuid parsePerm s | isPermModeChar (s !! 0) && (s !! 1 == ':') = case parseQualifier (drop 2 s) of Nothing -> Nothing Just qual -> Just (Perm qual (toPermMode $ head s)) | otherwise = Nothing where parseQualifier :: String -> Maybe Qualifier parseQualifier q | length q == 36 = Just $ QualUuid $ Uuid q | (all isDigit q) = Just $ QualDomid (read q) | q !! 0 == '@' = Just $ QualName (drop 1 q) | q !! 0 == '{' && q !! (length q - 1) == '}' = Just $ QualPropertyEq "" "" -- FIXME | otherwise = Nothing isPermModeChar c = elem c "rwb" toPermMode 'r' = Read toPermMode 'w' = Write toPermMode 'b' = ReadWrite toPermMode _ = error "not a valid perm mode" parsePermPatch s | length s == 39 && (s !! 0 == '+') = (\p -> (PermAdd,p)) `fmap` parsePerm (tail s) | length s == 39 && (s !! 0 == '-') = (\p -> (PermDel,p)) `fmap` parsePerm (tail s) | otherwise = Nothing parsePermPatchs = PermPatchs . loop where loop s | null s = [] | length s < 39 = [] | otherwise = let (s1, s2) = splitAt 39 s in case parsePermPatch s1 of Nothing -> loop s2 Just p -> p : loop s2
jean-edouard/manager
dbd2/Perms.hs
gpl-2.0
8,642
0
14
3,170
2,428
1,254
1,174
164
7
module OpenSSL.Utils ( failIfNull , failIfNull_ , failIf , failIf_ , raiseOpenSSLError , toHex , fromHex , peekCStringCLen ) where import Foreign.C.String import Foreign.C.Types import Foreign.Ptr import OpenSSL.ERR import Data.Bits import Data.List failIfNull :: Ptr a -> IO (Ptr a) failIfNull ptr = if ptr == nullPtr then raiseOpenSSLError else return ptr failIfNull_ :: Ptr a -> IO () failIfNull_ ptr = failIfNull ptr >> return () failIf :: (a -> Bool) -> a -> IO a failIf f a | f a = raiseOpenSSLError | otherwise = return a failIf_ :: (a -> Bool) -> a -> IO () failIf_ f a = failIf f a >> return () raiseOpenSSLError :: IO a raiseOpenSSLError = getError >>= errorString >>= fail -- | Convert an integer to a hex string toHex :: (Num i, Bits i) => i -> String toHex = reverse . map hexByte . unfoldr step where step 0 = Nothing step i = Just (i .&. 0xf, i `shiftR` 4) hexByte 0 = '0' hexByte 1 = '1' hexByte 2 = '2' hexByte 3 = '3' hexByte 4 = '4' hexByte 5 = '5' hexByte 6 = '6' hexByte 7 = '7' hexByte 8 = '8' hexByte 9 = '9' hexByte 10 = 'a' hexByte 11 = 'b' hexByte 12 = 'c' hexByte 13 = 'd' hexByte 14 = 'e' hexByte 15 = 'f' hexByte _ = undefined -- | Convert a hex string to an integer fromHex :: (Num i, Bits i) => String -> i fromHex = foldl step 0 where step acc hexchar = (acc `shiftL` 4) .|. byteHex hexchar byteHex '0' = 0 byteHex '1' = 1 byteHex '2' = 2 byteHex '3' = 3 byteHex '4' = 4 byteHex '5' = 5 byteHex '6' = 6 byteHex '7' = 7 byteHex '8' = 8 byteHex '9' = 9 byteHex 'a' = 10 byteHex 'b' = 11 byteHex 'c' = 12 byteHex 'd' = 13 byteHex 'e' = 14 byteHex 'f' = 15 byteHex 'A' = 10 byteHex 'B' = 11 byteHex 'C' = 12 byteHex 'D' = 13 byteHex 'E' = 14 byteHex 'F' = 15 byteHex _ = undefined peekCStringCLen :: (Ptr CChar, CInt) -> IO String peekCStringCLen (p, n) = peekCStringLen (p, fromIntegral n)
phonohawk/HsOpenSSL
OpenSSL/Utils.hs
cc0-1.0
2,016
0
9
572
780
402
378
82
23
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE TypeOperators#-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UnboxedTuples #-} module Fun00004 where -- | A record with options for explicit passing in rewrite rules. data FeldOpts = FeldOpts { targets :: [Target] } -- | Default options. defaultFeldOpts :: FeldOpts defaultFeldOpts = FeldOpts { targets = [] } -- | Insert a variable into the environment localVar :: Typeable b => VarId -> Info b -> Opt a -> Opt a localVar v info = local $ \env -> env {varEnv = (v, SomeInfo info):varEnv env} -- | It the expression is a literal, its value is returned, otherwise 'Nothing' viewLiteral :: forall info dom a. ((Literal :|| Type) :<: dom) => ASTF (Decor info (dom :|| Typeable)) a -> Maybe a viewLiteral (prjF -> Just (C' (Literal a))) = Just a viewLiteral _ = Nothing g = (# #)
charleso/intellij-haskforce
tests/gold/parser/Fun00004.hs
apache-2.0
877
0
12
177
230
127
103
17
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Фильтры предупреждений | Расширение ZAP </title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>СОДЕРЖАНИЕ </label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Избранное</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/alertFilters/src/main/javahelp/org/zaproxy/zap/extension/alertFilters/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
1,049
83
52
161
508
263
245
-1
-1
{-# OPTIONS_GHC -g -O #-} {-# OPTIONS -fno-strictness -fno-case-merge -fno-call-arity -fno-case-folding -fno-cse -fno-do-eta-reduction -fno-do-lambda-eta-expansion -fno-float-in -ffull-laziness -fno-enable-rewrite-rules #-} -- This used to fail with: -- -- *** Core Lint errors : in result of Simplifier *** -- <no location info>: warning: -- [RHS of str_sZr :: Addr#] -- Recursive or top-level binder has strict demand info: str_sZr -- Binder's demand info: <L,U> module T14779a where mkConstr :: String -> String mkConstr str = r where r = idx `seq` str idx = eqS r str `seq` [r] conMkFixed :: String conMkFixed = mkConstr "MkFixed" eqS :: String -> String -> Bool eqS [] [] = True eqS _ _ = False
sdiehl/ghc
testsuite/tests/simplCore/should_compile/T14779a.hs
bsd-3-clause
745
0
8
156
112
66
46
12
1
{-# LANGUAGE TypeFamilies #-} module C where import A data C type instance F (a,C) = ()
ezyang/ghc
testsuite/tests/driver/recomp017/C.hs
bsd-3-clause
88
0
5
17
29
19
10
-1
-1
{-# LANGUAGE ParallelArrays #-} {-# OPTIONS -fvectorise #-} module Types ( Point , Line , makePoints, makePointsPA , xsOf, xsOfPA , ysOf, ysOfPA) where import Data.Array.Parallel import Data.Array.Parallel.Prelude.Double import qualified Data.Array.Parallel.Prelude.Double as D import qualified Prelude as P type Point = (Double, Double) type Line = (Point, Point) -- | Make some points from their components. makePoints :: [:Double:] -> [:Double:] -> [:Point:] makePoints = zipP -- | Make some points from their components, as a `PArray`. makePointsPA :: PArray Double -> PArray Double -> PArray Point {-# NOINLINE makePointsPA #-} makePointsPA xs ys = toPArrayP (makePoints (fromPArrayP xs) (fromPArrayP ys)) -- | Take the x values of some points. xsOf :: [:Point:] -> [:Double:] xsOf ps = [: x | (x, _) <- ps :] -- | Take the x values of some points as a `PArray`. xsOfPA :: PArray Point -> PArray Double {-# NOINLINE xsOfPA #-} xsOfPA ps = toPArrayP (xsOf (fromPArrayP ps)) -- | Take the y values of some points. ysOf :: [:Point:] -> [:Double:] ysOf ps = [: y | (_, y) <- ps :] -- | Take the y values of some points as a `PArray`. ysOfPA :: PArray Point -> PArray Double {-# NOINLINE ysOfPA #-} ysOfPA ps = toPArrayP (ysOf (fromPArrayP ps))
urbanslug/ghc
testsuite/tests/dph/nbody/Types.hs
bsd-3-clause
1,310
27
9
276
370
213
157
30
1
-- !!! test multiple-reader single-writer locking semantics import System.IO import System.IO.Error file1 = "openFile005.out1" file2 = "openFile005.out2" main = do putStrLn "two writes (should fail)" h <- openFile file1 WriteMode tryIOError (openFile file1 WriteMode) >>= print hClose h putStrLn "write and an append (should fail)" h <- openFile file1 WriteMode tryIOError (openFile file1 AppendMode) >>= print hClose h putStrLn "read/write and a write (should fail)" h <- openFile file1 ReadWriteMode tryIOError (openFile file1 WriteMode) >>= print hClose h putStrLn "read and a read/write (should fail)" h <- openFile file1 ReadMode tryIOError (openFile file1 ReadWriteMode) >>= print hClose h putStrLn "write and a read (should fail)" h <- openFile file1 WriteMode tryIOError (openFile file1 ReadMode) >>= print hClose h putStrLn "two writes, different files (silly, but should succeed)" h1 <- openFile file1 WriteMode h2 <- openFile file2 WriteMode hClose h1 hClose h2 putStrLn "two reads, should succeed" h1 <- openFile file1 ReadMode h2 <- openFile file1 ReadMode hClose h1 hClose h2
ryantm/ghc
libraries/base/tests/IO/openFile005.hs
bsd-3-clause
1,159
0
10
229
322
134
188
35
1
module T8639_api_a where it = True
ghc-android/ghc
testsuite/tests/ghc-api/T8639_api_a.hs
bsd-3-clause
36
0
4
7
9
6
3
2
1
{-# LANGUAGE FlexibleContexts #-} module CommandParsers where import Data.Carthage.TargetPlatform import Data.Char ( isLetter ) import Data.Either.Extra ( maybeToEither ) import Data.List ( nub ) import Data.List.Split ( wordsBy ) import Data.Monoid ( (<>) ) import Data.Romefile import Options.Applicative as Opts import Text.Read ( readMaybe ) import Types.Commands {- Command line arguments parsing -} -- verifyParser :: Parser VerifyFlag -- verifyParser = VerifyFlag <$> Opts.switch ( Opts.long "verify" <> Opts.help "Verify that the framework has the same hash as specified in the Cartfile.resolved.") cachePrefixParser :: Opts.Parser String cachePrefixParser = Opts.strOption ( Opts.value "" <> Opts.metavar "PREFIX" <> Opts.long "cache-prefix" <> Opts.help "A prefix appended to the top level directories inside the caches. Usefull to separate artifacts between Swift versions." ) skipLocalCacheParser :: Opts.Parser SkipLocalCacheFlag skipLocalCacheParser = SkipLocalCacheFlag <$> Opts.switch (Opts.long "skip-local-cache" <> Opts.help "Ignore the local cache when performing the operation.") noIgnoreParser :: Opts.Parser NoIgnoreFlag noIgnoreParser = NoIgnoreFlag <$> Opts.switch (Opts.long "no-ignore" <> Opts.help "Ignore the `ignoreMap` section in the Romefile when performing the operation.") noSkipCurrentParser :: Opts.Parser NoSkipCurrentFlag noSkipCurrentParser = NoSkipCurrentFlag <$> Opts.switch ( Opts.long "no-skip-current" <> Opts.help "Do not skip the `currentMap` section in the Romefile when performing the operation." ) concurrentlyParser :: Opts.Parser ConcurrentlyFlag concurrentlyParser = ConcurrentlyFlag <$> Opts.switch ( Opts.long "concurrently" <> Opts.help "Maximise concurrency while performing the operation. Might make verbose output hard to follow." ) reposParser :: Opts.Parser [ProjectName] reposParser = Opts.many (Opts.argument (ProjectName <$> str) ( Opts.metavar "FRAMEWORKS..." <> Opts.help "Zero or more framework names. If zero, all frameworks and dSYMs are uploaded." ) ) platformsParser :: Opts.Parser [TargetPlatform] platformsParser = (nub . concat <$> Opts.some (Opts.option (eitherReader platformListOrError) ( Opts.metavar "PLATFORMS" <> Opts.long "platform" <> Opts.help "Applicable platforms for the command. One of iOS, MacOS, tvOS, watchOS, or a comma-separated list of any of these values." ) ) ) <|> pure allTargetPlatforms where platformOrError s = maybeToEither ("Unrecognized platform '" ++ s ++ "'") (readMaybe s) splitPlatforms s = filter (not . null) $ filter isLetter <$> wordsBy (not . isLetter) s platformListOrError s = mapM platformOrError $ splitPlatforms s udcPayloadParser :: Opts.Parser RomeUDCPayload udcPayloadParser = RomeUDCPayload <$> reposParser <*> platformsParser <*> cachePrefixParser <*> skipLocalCacheParser <*> noIgnoreParser <*> noSkipCurrentParser <*> concurrentlyParser uploadParser :: Opts.Parser RomeCommand uploadParser = pure Upload <*> udcPayloadParser downloadParser :: Opts.Parser RomeCommand downloadParser = pure Download <*> udcPayloadParser listModeParser :: Opts.Parser ListMode listModeParser = ( Opts.flag' Missing (Opts.long "missing" <> Opts.help "List frameworks missing from the cache. Ignores dSYMs") <|> Opts.flag' Present (Opts.long "present" <> Opts.help "List frameworks present in the cache. Ignores dSYMs.") ) <|> Opts.flag All All (Opts.help "Reports missing or present status of frameworks in the cache. Ignores dSYMs.") printFormatParser :: Opts.Parser PrintFormat printFormatParser = Opts.option Opts.auto (Opts.value Text <> Opts.long "print-format" <> Opts.metavar "FORMATS" <> Opts.help "Available print formats: JSON or if omitted, default to Text" ) listPayloadParser :: Opts.Parser RomeListPayload listPayloadParser = RomeListPayload <$> listModeParser <*> platformsParser <*> cachePrefixParser <*> printFormatParser <*> noIgnoreParser <*> noSkipCurrentParser listParser :: Opts.Parser RomeCommand listParser = List <$> listPayloadParser utilsPayloadParser :: Opts.Parser RomeUtilsPayload utilsPayloadParser = RomeUtilsPayload <$> romeUtilsSubcommandParser romeUtilsSubcommandParser :: Opts.Parser RomeUtilsSubcommand romeUtilsSubcommandParser = Opts.subparser $ Opts.command "migrate-romefile" (pure MigrateRomefile `withInfo` "Migrates a Romefile from INI to YAML.") utilsParser :: Opts.Parser RomeCommand utilsParser = Utils <$> utilsPayloadParser parseRomefilePath :: Opts.Parser String parseRomefilePath = Opts.strOption (Opts.value canonicalRomefileName <> Opts.metavar "PATH" <> Opts.long "romefile" <> Opts.help "The path to the Romefile to use. Defaults to the \"Romefile\" in the current directory." ) parseRomeCommand :: Opts.Parser RomeCommand parseRomeCommand = Opts.subparser $ Opts.command "upload" (uploadParser `withInfo` "Uploads frameworks and dSYMs contained in the local Carthage/Build/<platform> to S3, according to the local Cartfile.resolved" ) <> Opts.command "download" (downloadParser `withInfo` "Downloads and unpacks in Carthage/Build/<platform> frameworks and dSYMs found in S3, according to the local Cartfile.resolved" ) <> Opts.command "list" (listParser `withInfo` "Lists frameworks in the cache and reports cache misses/hits, according to the local Cartfile.resolved. Ignores dSYMs." ) <> Opts.command "utils" (utilsParser `withInfo` "A series of utilities to make life easier. `rome utils --help` to know more") parseRomeOptions :: Opts.Parser RomeOptions parseRomeOptions = RomeOptions <$> parseRomeCommand <*> parseRomefilePath <*> Opts.switch (Opts.short 'v' <> help "Show verbose output") withInfo :: Opts.Parser a -> String -> Opts.ParserInfo a withInfo opts desc = Opts.info (Opts.helper <*> opts) $ Opts.progDesc desc
blender/Rome
src/CommandParsers.hs
mit
6,373
0
15
1,378
1,173
598
575
121
1
module Wobsurv.Response where import BasePrelude hiding (bracket, for, yield, head) import Pipes import Pipes.Safe import Control.Monad.Trans.Reader import qualified Wobsurv.Util.HTTP.Renderer as ProtocolRenderer import qualified Wobsurv.Util.HTTP.Model as Protocol import qualified Wobsurv.Util.HTTP.URLEncoding as URLEncoding import qualified Wobsurv.Util.Mustache.Renderer as TemplatesRenderer import qualified Wobsurv.TemplateModels.NotFound as NotFound import qualified Wobsurv.TemplateModels.Index as Index import qualified Pipes.ByteString import qualified Pipes.Text import qualified Data.ByteString import qualified Data.ByteString.Builder import qualified Data.Text import qualified Data.Text.Encoding import qualified Data.Text.Lazy import qualified Data.HashMap.Strict import qualified Filesystem.Path as Path import qualified Filesystem.Path.CurrentOS as Path.CurrentOS import qualified Filesystem.Path.Rules as Path.Rules import qualified Filesystem type BS = Data.ByteString.ByteString type FilePath = Path.CurrentOS.FilePath type Text = Data.Text.Text type LazyText = Data.Text.Lazy.Text type KeepAliveTimeout = Word type MimeMappings = Data.HashMap.Strict.HashMap Text BS type Env = TemplatesRenderer.Renderer type Response r = ReaderT Env (Producer BS (SafeT IO)) r runInProducer :: Response a -> Env -> Producer BS (SafeT IO) a runInProducer = runReaderT -- * Responses ------------------------- serviceUnavailable :: Response () serviceUnavailable = do statusLine Protocol.serviceUnavailable connectionHeader False contentTypeHeader ("text/html", Just Protocol.UTF8) newLine template "service-unavailable" () badRequest :: Response () badRequest = do statusLine Protocol.badRequest connectionHeader False contentTypeHeader ("text/html", Just Protocol.UTF8) newLine template "bad-request" () notImplemented :: Response () notImplemented = do statusLine Protocol.notImplemented connectionHeader False contentTypeHeader ("text/html", Just Protocol.UTF8) newLine template "not-implemented" () entityTooLarge :: Response () entityTooLarge = do statusLine Protocol.entityTooLarge connectionHeader False contentTypeHeader ("text/html", Just Protocol.UTF8) newLine template "entity-too-large" () notFound :: Protocol.RelativeURI -> Response () notFound uri = do statusLine Protocol.notFound connectionHeader False contentTypeHeader ("text/html", Just Protocol.UTF8) newLine template "not-found" $ NotFound.NotFound { NotFound.uri = URLEncoding.toText $ ProtocolRenderer.toByteString $ ProtocolRenderer.relativeURI uri } okFile :: FilePath -> Maybe KeepAliveTimeout -> MimeMappings -> Response () okFile path keepAliveTimeout mimeMappings = do statusLine Protocol.ok case keepAliveTimeout of Nothing -> do connectionHeader False Just v -> do connectionHeader True keepAliveHeader (v, Nothing) forM_ contentType $ \x -> contentTypeHeader (x, Nothing) newLine file path where contentType = Path.extension path >>= \e -> Data.HashMap.Strict.lookup e mimeMappings okIndex :: FilePath -> FilePath -> Maybe KeepAliveTimeout -> Response () okIndex uriPath path keepAliveTimeout = do statusLine Protocol.ok case keepAliveTimeout of Nothing -> do connectionHeader False Just v -> do connectionHeader True keepAliveHeader (v, Nothing) contentTypeHeader ("text/html", Just Protocol.UTF8) newLine contents <- do files <- do paths <- liftIO $ Filesystem.listDirectory path return $ map Path.filename paths if publicPath /= "/" then return $ ".." : files else return files template "index" $ Index.Index (pathRepr publicPath) (map pathRepr contents) where publicPath = Path.parent $ "/" <> uriPath <> "./" pathRepr = fromString . Path.CurrentOS.encodeString -- * Headers ------------------------- contentTypeHeader :: Protocol.ContentTypeHeader -> Response () contentTypeHeader = liftBSBuilder . ProtocolRenderer.contentTypeHeader connectionHeader :: Protocol.ConnectionHeader -> Response () connectionHeader = liftBSBuilder . ProtocolRenderer.connectionHeader keepAliveHeader :: Protocol.KeepAliveHeader -> Response () keepAliveHeader = liftBSBuilder . ProtocolRenderer.keepAliveHeader contentLengthHeader :: Protocol.ContentLengthHeader -> Response () contentLengthHeader = liftBSBuilder . ProtocolRenderer.contentLengthHeader -- * Other ------------------------- newLine :: Response () newLine = liftBSBuilder ProtocolRenderer.newLine template :: (Data model) => Text -> model -> Response () template name model = do templatesRenderer <- ask traverse_ lazyText $ TemplatesRenderer.render model name templatesRenderer lazyText :: LazyText -> Response () lazyText t = lift $ for (Pipes.Text.fromLazy t) (yield . Data.Text.Encoding.encodeUtf8) file :: FilePath -> Response () file path = lift $ bracket (liftIO $ Filesystem.openFile path Filesystem.ReadMode) (liftIO . hClose) Pipes.ByteString.fromHandle statusLine :: Protocol.Status -> Response () statusLine status = liftBSBuilder $ ProtocolRenderer.statusLine (1, 1) status liftBSBuilder :: Data.ByteString.Builder.Builder -> Response () liftBSBuilder = lift . Pipes.ByteString.fromLazy . Data.ByteString.Builder.toLazyByteString
nikita-volkov/wobsurv
library/Wobsurv/Response.hs
mit
5,547
0
16
1,028
1,429
745
684
161
3
{-# LANGUAGE CPP #-} module Data.Streaming.Network.Internal ( ServerSettings (..) , ClientSettings (..) , HostPreference (..) , Message (..) , AppData (..) #if !WINDOWS , ServerSettingsUnix (..) , ClientSettingsUnix (..) , AppDataUnix (..) #endif ) where import Data.String (IsString (..)) import Data.ByteString (ByteString) import Network.Socket (Socket, SockAddr, Family) -- | Settings for a TCP server. It takes a port to listen on, and an optional -- hostname to bind to. data ServerSettings = ServerSettings { serverPort :: !Int , serverHost :: !HostPreference , serverSocket :: !(Maybe Socket) -- ^ listening socket , serverAfterBind :: !(Socket -> IO ()) , serverNeedLocalAddr :: !Bool } -- | Settings for a TCP client, specifying how to connect to the server. data ClientSettings = ClientSettings { clientPort :: !Int , clientHost :: !ByteString , clientAddrFamily :: !Family } -- | Which host to bind. -- -- Note: The @IsString@ instance recognizes the following special values: -- -- * @*@ means @HostAny@ -- -- * @*4@ means @HostIPv4@ -- -- * @!4@ means @HostIPv4Only@ -- -- * @*6@ means @HostIPv6@ -- -- * @!6@ means @HostIPv6Only@ -- -- Any other values is treated as a hostname. As an example, to bind to the -- IPv4 local host only, use \"127.0.0.1\". data HostPreference = HostAny | HostIPv4 | HostIPv4Only | HostIPv6 | HostIPv6Only | Host String deriving (Eq, Ord, Show, Read) instance IsString HostPreference where fromString "*" = HostAny fromString "*4" = HostIPv4 fromString "!4" = HostIPv4Only fromString "*6" = HostIPv6 fromString "!6" = HostIPv6Only fromString s = Host s #if !WINDOWS -- | Settings for a Unix domain sockets server. data ServerSettingsUnix = ServerSettingsUnix { serverPath :: !FilePath , serverAfterBindUnix :: !(Socket -> IO ()) } -- | Settings for a Unix domain sockets client. data ClientSettingsUnix = ClientSettingsUnix { clientPath :: !FilePath } -- | The data passed to a Unix domain sockets @Application@. data AppDataUnix = AppDataUnix { appReadUnix :: !(IO ByteString) , appWriteUnix :: !(ByteString -> IO ()) } #endif -- | Representation of a single UDP message data Message = Message { msgData :: {-# UNPACK #-} !ByteString , msgSender :: !SockAddr } -- | The data passed to an @Application@. data AppData = AppData { appRead' :: !(IO ByteString) , appWrite' :: !(ByteString -> IO ()) , appSockAddr' :: !SockAddr , appLocalAddr' :: !(Maybe SockAddr) , appCloseConnection' :: !(IO ()) , appRawSocket' :: Maybe Socket }
kdkeyser/streaming-commons
Data/Streaming/Network/Internal.hs
mit
2,707
0
13
629
531
317
214
93
0
{-# OPTIONS_HADDOCK hide, prune #-} {-# LANGUAGE RecordWildCards #-} module Handler.Mooc.Comment ( postWriteReviewR , viewComments ) where import Import import Import.Util import Control.Monad.Trans.Except import Database.Persist.Sql (fromSqlKey, rawSql, Single(..)) import qualified Data.Text as Text -- | Get post params: -- * criterion - id -- * val - criterion good or bad (1 or 0) -- * comment - textual comment postWriteReviewR :: ScenarioId -> Handler Value postWriteReviewR scenarioId = runJSONExceptT $ do userId <- maybeE "You must login to review." maybeAuthId criterionId <- maybeE "You must specify one criterion you review." $ (>>= parseSqlKey) <$> lookupPostParam "criterion" criterionVal <- fmap ("1" ==) $ maybeE "You must specify one criterion you review." $ lookupPostParam "val" comment <- lift $ fromMaybe "" <$> lookupPostParam "comment" t <- liftIO getCurrentTime ExceptT $ runDB $ runExceptT $ do scenario <- maybeE "Cannot find a correcsponding scenario." $ get scenarioId when (userId == scenarioAuthorId scenario) $ throwE "You cannot review yourself!" oreview <- lift $ getBy (ReviewOf userId scenarioId criterionId) when (isJust oreview) $ throwE "You have already voted on this exact design according w.r.t. this criterion." lift $ insert_ $ Review userId scenarioId criterionId criterionVal comment t return $ object [ "criterion" .= fromSqlKey criterionId , "val" .= Number (if criterionVal then 1 else 0) , "comment" .= comment , "timestamp" .= t] viewComments :: ScenarioId -> Handler Widget viewComments scId = do muserId <- maybeAuthId runDB $ do mscenario <- get scId case mscenario of Nothing -> return mempty Just sc -> do authorName <- get (scenarioAuthorId sc) >>= \mu -> case mu of Nothing -> return "anonymous" Just u -> return $ userName u let scUpdateTime = scenarioLastUpdate sc canComment = case muserId of Nothing -> False Just uId -> uId /= scenarioAuthorId sc criteria <- currentCriteria $ scenarioTaskId sc wrapIt authorName scUpdateTime (scenarioDescription sc) canComment criteria . foldl' ( \w (Single icon, Single name, Entity _ r) -> w <> commentW icon name r ) mempty <$> getReviews scId where wrapIt authorName scUpdateTime desc canComment criteria w = do toWidgetHead [cassius| div.card-comment.card padding: 0 div.card-comment.card-main padding: 0 margin: 0 div.card-comment.card-inner padding: 2px margin: 0 min-height: 40px p.small-p > span.icon24 height: 24px width: 24px font-size: 16px padding: 4px td.small-td > p.small-p margin: 2px padding: 0px line-height: 24px tr > td.small-td margin: 2px padding: 2px tr.small-tr.small-tr-please padding: 2px margin: 2px .comment-table margin: 5px 5px 5px 20px padding: 0px #commentContainer overflow-x: visible overflow-y: auto margin: -1px padding: 1px |] toWidgetHead [julius| $(document).ready(function() { var nh = $(window).height() - $('#commentContainer').offset().top, oh = $('#commentContainer').height(); if (nh < oh) { $('#commentContainer').css("margin-right", "-8px"); $('#commentContainer').height(nh); } }); |] [whamlet| <div.comment-table> <div.card-comment.card> <div.card-comment.card-main> <div.card-comment.card-inner> <p style="margin: 6px; color: #b71c1c; float: left;"> #{authorName} <p style="margin: 6px; color: #b71c1c; float: right;"> #{show $ utctDay $ scUpdateTime} <p style="margin: 8px;">&nbsp; <p style="white-space: pre-line; margin: 2px;"> #{desc} $if canComment ^{writeCommentFormW scId criteria} <div #commentContainer> <table.table style="margin-top: 0px;"> ^{w} |] type Icon = Text type UserName = Text writeCommentFormW :: ScenarioId -> [Entity Criterion] -> Widget writeCommentFormW scId criteria = do toWidgetHead [cassius| div.card-comment.card-action padding: 4px margin: 0 min-height: 28px span.card-comment.card-criterion height: 24px width: 24px margin: 0px 4px 0px 4px padding: 0px float: left opacity: 0.3 span.card-comment.card-criterion:hover opacity: 1.0 cursor: pointer span.card-comment.icon height: 24px width: 24px font-size: 16px padding: 4px margin: 0px 2px 0px 2px float: left opacity: 0.3 span.card-comment height: 24px width: 24px font-size: 16px padding: 4px margin: 0px 2px 0px 2px float: left span.card-comment:hover opacity: 1.0 span.card-comment.icon:hover opacity: 1.0 cursor: pointer a.card-comment.btn height: 24px padding: 4px font-size: 16px float: right display: none div.card-comment.form-group margin: 16px 4px 4px 4px #voteinfo margin: 2px padding: 2px |] toWidgetHead [julius| function submitComment(){ $.post( { url: '@{WriteReviewR scId}' , data: $('#commentForm').serialize() , success: function(result){ resetAllComment(); $("body").snackbar({ content: (result.error ? result.error : "Review sent. Refresh the page to see it.") }); } }); } var voteSet = false, critSet = false; function resetAllComment() { voteSet = false; critSet = false; $('#criterionIdI').val(undefined); $('#criterionValI').val(undefined); $('#commentI').val(''); $('#voteCName').text(''); $('#voteIndication').text(''); $('span.card-comment.card-criterion').css('opacity','0.3'); $('#downvoteSpan').css('opacity','0.3'); $('#upvoteSpan').css('opacity','0.3'); checkVote(); } function voteCriterion(criterionId, criterionName) { $('#criterionIdI').val(criterionId); $('#voteCName').text(criterionName); $('span.card-comment.card-criterion').css('opacity','0.3'); $('#cspan' + criterionId).css('opacity','1.0'); critSet = true; checkVote(); } function setUpvote() { $('#criterionValI').val(1); $('#voteIndication').text('Upvote '); $('#downvoteSpan').css('opacity','0.3'); $('#upvoteSpan').css('opacity','1.0'); voteSet = true; checkVote(); } function setDownvote() { $('#criterionValI').val(0); $('#voteIndication').text('Downvote '); $('#downvoteSpan').css('opacity','1.0'); $('#upvoteSpan').css('opacity','0.3'); voteSet = true; checkVote(); } function checkVote() { if(voteSet && critSet) { $('#voteSubmit').show(); } else { $('#voteSubmit').hide(); } } |] toWidgetBody [hamlet| <div.card-comment.card> <div.card-comment.card-main> <div.card-comment.card-inner> <form #commentForm method="post"> <input type="hidden" #criterionIdI name="criterion"> <input type="hidden" #criterionValI name="val"> <div.card-comment.form-group.form-group-label> <label.floating-label for="commentI">Write a review <textarea.form-control.textarea-autosize form="commentForm" id="commentI" rows="1" name="comment"> <p.card-comment #voteinfo> <span #voteIndication> <span #voteCName> <div.card-comment.card-action> $forall (Entity cId criterion) <- criteria <span.card-comment.card-criterion onclick="voteCriterion(#{fromSqlKey cId},'#{criterionName criterion}')" id="cspan#{fromSqlKey cId}"> #{preEscapedToMarkup $ criterionIcon criterion} <span.card-comment>&nbsp; <span.card-comment.icon #upvoteSpan onclick="setUpvote()">thumb_up <span.card-comment.icon #downvoteSpan onclick="setDownvote()">thumb_down <a.card-comment.btn.btn-flat.btn-brand-accent.waves-attach.waves-effect #voteSubmit onclick="submitComment()"> <span.icon>check Send |] commentW :: Icon -> UserName -> Review -> Widget commentW ico uname Review{..} = [whamlet| <tr.small-tr.small-tr-please> <td.small-td> <p.small-p> <span.icon.icon24.text-brand-accent> $if reviewPositive thumb_up $else thumb_down <p.small-p style="height:24px"> #{preEscapedToMarkup ico} <td.small-td> <p.small-p.text-brand-accent> #{formatTime defaultTimeLocale "%Y.%m.%d - %H:%M" reviewTimestamp} - #{uname} <p.small-p> #{reviewComment} |] getReviews :: ScenarioId -> ReaderT SqlBackend Handler [(Single Icon, Single UserName, Entity Review)] getReviews scId = rawSql query [toPersistValue scId] where query = Text.unlines ["SELECT \"criterion\".icon, \"user\".name, ??" ,"FROM review" ,"INNER JOIN \"user\"" ," ON \"user\".id = review.reviewer_id" ,"INNER JOIN \"criterion\"" ," ON \"criterion\".id = review.criterion_id" ,"WHERE review.scenario_id IN (" ," SELECT scenario.id FROM scenario" ," INNER JOIN (SELECT scenario.author_id, scenario.task_id FROM scenario WHERE scenario.id = ?) t" ," ON scenario.task_id = t.task_id AND scenario.author_id = t.author_id)" ,"ORDER BY review.timestamp DESC;" ] currentCriteria :: ScenarioProblemId -> ReaderT SqlBackend Handler [Entity Criterion] currentCriteria scp_id = rawSql query [toPersistValue scp_id] where query = unlines ["SELECT ?? FROM criterion,problem_criterion" ," WHERE problem_criterion.problem_id = ?" ," AND problem_criterion.criterion_id = criterion.id;" ]
mb21/qua-kit
apps/hs/qua-server/src/Handler/Mooc/Comment.hs
mit
10,682
0
22
3,207
937
480
457
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module Configuration.DotenvSpec (main, spec) where import Configuration.Dotenv (load, loadFile, onMissingFile, parseFile) import Configuration.Dotenv.Environment (getEnvironment, lookupEnv, setEnv, unsetEnv) import Configuration.Dotenv.Types (Config (..)) import Test.Hspec import Control.Monad (liftM, void) import Data.Maybe (fromMaybe) import System.Process (readCreateProcess, shell) main :: IO () main = hspec spec spec :: Spec spec = do describe "load" $ after_ clearEnvs $ do it "loads the given list of configuration options to the environment" $ do lookupEnv "foo" `shouldReturn` Nothing load False [("foo", "bar")] lookupEnv "foo" `shouldReturn` Just "bar" it "preserves existing settings when overload is false" $ do setEnv "foo" "preset" load False [("foo", "new setting")] lookupEnv "foo" `shouldReturn` Just "preset" it "overrides existing settings when overload is true" $ do setEnv "foo" "preset" load True [("foo", "new setting")] lookupEnv "foo" `shouldReturn` Just "new setting" describe "loadFile" $ before_ setupEnv $ after_ clearEnvs $ do it "loads the configuration options to the environment from a file" $ do lookupEnv "DOTENV" `shouldReturn` Nothing void $ loadFile $ Config ["spec/fixtures/.dotenv"] [] False lookupEnv "DOTENV" `shouldReturn` Just "true" it "respects predefined settings when overload is false" $ do setEnv "DOTENV" "preset" void $ loadFile $ Config ["spec/fixtures/.dotenv"] [] False lookupEnv "DOTENV" `shouldReturn` Just "preset" it "overrides predefined settings when overload is true" $ do setEnv "DOTENV" "preset" void $ loadFile $ Config ["spec/fixtures/.dotenv"] [] True lookupEnv "DOTENV" `shouldReturn` Just "true" context "when the .env.example is present" $ do let config = Config ["spec/fixtures/.dotenv"] ["spec/fixtures/.dotenv.example"] False context "when the needed env vars are missing" $ it "should fail with an error call" $ do unsetEnv "ANOTHER_ENV" void $ loadFile config `shouldThrow` anyErrorCall context "when the needed env vars are not missing" $ it "should succeed when loading all of the needed env vars" $ do -- Load extra information me <- init <$> readCreateProcess (shell "whoami") "" home <- fromMaybe "" <$> lookupEnv "HOME" -- Load envs void $ loadFile config -- Check existing envs lookupEnv "ENVIRONMENT" `shouldReturn` Just home lookupEnv "ME" `shouldReturn` Just me lookupEnv "DOTENV" `shouldReturn` Just "true" lookupEnv "UNICODE_TEST" `shouldReturn` Just "Manabí" lookupEnv "ANOTHER_ENV" `shouldReturn` Just "hello" describe "parseFile" $ after_ clearEnvs $ do it "returns variables from a file without changing the environment" $ do lookupEnv "DOTENV" `shouldReturn` Nothing liftM head (parseFile "spec/fixtures/.dotenv") `shouldReturn` ("DOTENV", "true") lookupEnv "DOTENV" `shouldReturn` Nothing it "recognizes unicode characters" $ liftM (!! 1) (parseFile "spec/fixtures/.dotenv") `shouldReturn` ("UNICODE_TEST", "Manabí") it "recognises environment variables" $ do home <- fromMaybe "" <$> lookupEnv "HOME" liftM (!! 2) (parseFile "spec/fixtures/.dotenv") `shouldReturn` ("ENVIRONMENT", home) it "recognises previous variables" $ liftM (!! 3) (parseFile "spec/fixtures/.dotenv") `shouldReturn` ("PREVIOUS", "true") it "recognises commands" $ do me <- init <$> readCreateProcess (shell "whoami") "" liftM (!! 4) (parseFile "spec/fixtures/.dotenv") `shouldReturn` ("ME", me) #if MIN_VERSION_base(4,11,0) it "recognizes blank variable" $ liftM (!! 5) (parseFile "spec/fixtures/.dotenv") `shouldReturn` ("BLANK", "") #endif describe "onMissingFile" $ after_ clearEnvs $ do context "when target file is present" $ it "loading works as usual" $ do void $ onMissingFile (loadFile $ Config ["spec/fixtures/.dotenv"] [] True) (return []) lookupEnv "DOTENV" `shouldReturn` Just "true" context "when target file is missing" $ it "executes supplied handler instead" $ onMissingFile (True <$ loadFile (Config ["spec/fixtures/foo"] [] True)) (return False) `shouldReturn` False clearEnvs :: IO () clearEnvs = fmap (fmap fst) getEnvironment >>= mapM_ unsetEnv setupEnv :: IO () setupEnv = do setEnv "ANOTHER_ENV" "hello" setEnv "HOME" "/home/me"
stackbuilders/dotenv-hs
spec/Configuration/DotenvSpec.hs
mit
4,987
0
20
1,359
1,241
608
633
94
1
{- ISO C99 grammar, represented as Haskell datatypes. - - Source: http://slps.github.io/zoo/c/iso-9899-tc3.html - - Also, you'll notice that many of the types have pretty ugly names. I'm not - really sure how to get around this--it seems built into the problem of - turning the C grammar into semantically-named Haskell types. If you have - a way of avoiding this, please contact me immediately via email or - carrier pigeon. - - [email protected] - - - - Here's the type naming scheme: - * Types are given the same names as in the grammars, with some - abbreviations (see below). - * Value constructors are prefixed with the capital letters of the type - they construct, eg an ExtDecl value constructor in the TransUnit type - will be called TUExtDecl. - (i) In general, value constructors' names will indicate which fields - they expect. However, - (ii) If a type only has one value constructor, it will be named - the same thing as the type (but with a prefix as described above). - (iii) If a value constructor has no parameters (ie is a fixed string - in the grammar), it will just be named after the important - bits of the string it is. - * The following substitutions are made in all type names and value - constructors: - - Translation -> Trans - - External -> Ext - - Declaration -> Decl # "Declarator" will always be written in full - - Function -> Func - - Definion -> Def - - Specifier -> Spec - - Qualifier -> Qual - - Expression -> Exp - - Logical -> Log - - Argument -> Arg - - Parameter -> Param - - Constant -> Const - - Identifier -> Ident - - Enumerator -> Enum - - Enumeration -> Enum - - Statement -> Stmt - - Assignment -> Assign - - Conditional -> Cond - - Initializer -> Init - - Assignment -> Assign - - Iteration -> Iter - -} module CHa.Types.Grammar where import Data.Maybe type Ident = String type StringLiteral = String type CEnumConst = String data Const = CInt Integer | CFloat Double | CChar Char deriving (Show, Eq) data TransUnit = TUExtDecl ExtDecl | TUTransUnitExtDecl TransUnit ExtDecl deriving (Show, Eq) data ExtDecl = EDFuncDef FuncDef | EDDecl Decl deriving (Show, Eq) data FuncDef = FDFuncDef DeclSpecs Declarator (Maybe DeclList) CompoundStmt deriving (Show, Eq) data DeclSpecs = DSStorageClassSpecDeclSpecs StorageClassSpec (Maybe DeclSpecs) | DSTypeSpecifierDeclSpecs TypeSpec (Maybe DeclSpecs) | DSTypeQualDeclSpecs TypeQual (Maybe DeclSpecs) | DSFuncSpecDeclSpecs FuncSpec (Maybe DeclSpecs) deriving (Show, Eq) data StorageClassSpec = Typedef | Extern | Static | Auto | Register deriving (Show, Eq) data TypeSpec = Void | Char | Short | Int | Long | Float | Double | Signed | Unsigned | Bool | Complex | TSStructOrUnionSpec StructOrUnionSpec | TSCEnumSpec CEnumSpec | TSTypedefName TypedefName deriving (Show, Eq) data StructOrUnionSpec = SOUSStructOrUnionIdentStructDeclList StructOrUnion (Maybe Ident) StructDeclList | SOUSStructOrUnionIdent StructOrUnion Ident deriving (Show, Eq) data StructOrUnion = Struct | Union deriving (Show, Eq) data StructDeclList = SDLStructDecl StructDecl | SDLStructDeclStructDeclList StructDecl StructDeclList deriving (Show, Eq) data StructDecl = SDStructDecl SpecQualList StructDeclaratorList deriving (Show, Eq) data SpecQualList = SQLTypeSpecSpecQualList TypeSpec (Maybe SpecQualList) | SQLTypeQualSpecQualList TypeQual (Maybe SpecQualList) deriving (Show, Eq) data TypeQual = Const | Restrict | Volatile deriving (Show, Eq) data StructDeclaratorList = SDLStructDeclarator StructDeclarator | SDLStructDeclaratorStructDeclaratorList StructDeclarator StructDeclaratorList deriving (Show, Eq) data StructDeclarator = SDDeclarator Declarator | SDDeclaratorConstExpr (Maybe Declarator) ConstExpr deriving (Show, Eq) data Declarator = DDeclarator (Maybe Pointer) DirectDeclarator deriving (Show, Eq) data Pointer = PTypeQualList (Maybe TypeQualList) | PTypeQualListPointer (Maybe TypeQualList) Pointer deriving (Show, Eq) data TypeQualList = TQLTypeQual TypeQual | TQLTypeQualTypeQualList TypeQual TypeQualList deriving (Show, Eq) data DirectDeclarator = DDIdent Ident | DDDeclarator Declarator | DDDirectDeclaratorTypeQualListAssignExpr DirectDeclarator (Maybe TypeQualList) (Maybe AssignExpr) | DDDirectDeclaratorStaticTypeQualListAssignExpr DirectDeclarator (Maybe TypeQualList) AssignExpr | DDDirectDeclaratorTypeQualListStaticAssignExpr DirectDeclarator TypeQualList AssignExpr | DDDirectDeclaratorTypeQualList DirectDeclarator (Maybe TypeQualList) | DDDirectDeclaratorParamTypeList DirectDeclarator ParamTypeList | DDDirectDeclarator IdentList DirectDeclarator (Maybe IdentList) deriving (Show, Eq) data AssignExpr = AECondExpr CondExpr | AEUnaryExprAssignOpAssignExpr UnaryExpr AssignOp AssignExpr deriving (Show, Eq) data CondExpr = CELogOrExpr LogOrExpr | CELogOrExprExprCondExpr LogOrExpr Expr CondExpr deriving (Show, Eq) data LogOrExpr = LOELogAndExpr LogAndExpr | LOELogOrExprLogAndExpr LogOrExpr LogAndExpr deriving (Show, Eq) data LogAndExpr = LAEInclusiveOrExpr InclusiveOrExpr | LAELogAndExprInclusiveOrExpr LogAndExpr InclusiveOrExpr deriving (Show, Eq) data InclusiveOrExpr = IOEExclusiveOrExpr ExclusiveOrExpr | IOEInclusiveOrExprExclusiveOrExpr InclusiveOrExpr ExclusiveOrExpr deriving (Show, Eq) data ExclusiveOrExpr = EOEAndExpr AndExpr | EOEExclusiveOrExprEqualityExpr ExclusiveOrExpr EqualityExpr deriving (Show, Eq) data AndExpr = AEEqualityExpr EqualityExpr | AEAndExprEqualityExpr AndExpr EqualityExpr deriving (Show, Eq) data EqualityExpr = EERelationalExpr RelationalExpr | EEEqualityExprEqualityOpShiftExpr EqualityExpr EqualityOp ShiftExpr deriving (Show, Eq) data EqualityOp -- Not in the grammar, simplifies EqualityExpr def = EOEquals | EONotEquals deriving (Show, Eq) data RelationalExpr = REShiftExpr ShiftExpr | RERelationalExprRelationalOpShiftExpr RelationalExpr RelationalOp ShiftExpr deriving (Show, Eq) data RelationalOp -- Not in the grammar = ROLessThan | ROGreaterThan | ROLessEq | ROGreaterEq deriving (Show, Eq) data ShiftExpr = SEAdditiveExpr AdditiveExpr | SEShiftExprShiftDirectionAdditiveExpr ShiftExpr ShiftDirection AdditiveExpr deriving (Show, Eq) data ShiftDirection -- Not in the grammar = SDRight | SDLeft deriving (Show, Eq) data AdditiveExpr = AEMultiplicativeExpr MultiplicativeExpr | AEAdditiveExprAdditiveOpMultiplicativeExpr AdditiveExpr AdditiveOp MultiplicativeExpr deriving (Show, Eq) data AdditiveOp -- Not in the grammar = AOPlus | AOMinus deriving (Show, Eq) data MultiplicativeExpr = MECastExpr CastExpr | MEMultiplicativeExprMultiplicativeOpCastExpr MultiplicativeExpr MultiplicativeOp CastExpr deriving (Show, Eq) data MultiplicativeOp = MOTimes | MODivide | MOMod deriving (Show, Eq) data CastExpr = CEUnaryExpr UnaryExpr | CETypeNameCastExpr TypeName CastExpr deriving (Show, Eq) data UnaryExpr = UEPostfixExpr PostfixExpr | UEPlusPlusUnaryExpr UnaryExpr | UEMinusMinusUnaryExpr UnaryExpr | UEUnaryExprCastExpr UnaryExpr CastExpr | UESizeofUnaryExpr UnaryExpr | UESizeOfTypeName TypeName deriving (Show, Eq) data PostfixExpr = PEPrimaryExpr PrimaryExpr | PEPostfixExpr Expr PostfixExpr Expr | PEPostfixExprArgExprList PostfixExpr (Maybe ArgExprList) | PEPostfixExprDotIdent PostfixExpr Ident | PEPostfixExprArrowIdent PostfixExpr Ident | PEPostfixExprPlusPlus PostfixExpr | PEPostfixExprMinusMinus PostfixExpr | PETypeNameInitList TypeName InitList deriving (Show, Eq) data PrimaryExpr = PEIdent Ident | PEConst Const | PEStringLiteral String | PEExpr Expr deriving (Show, Eq) data Expr = EAssignExpr AssignExpr | EExprAssignExpr Expr AssignExpr deriving (Show, Eq) data ArgExprList = AELAssignExpr AssignExpr | AELArgExprListAssignExpr ArgExprList AssignExpr deriving (Show, Eq) data TypeName = TNTypeName SpecQualList (Maybe AbstractDeclarator) deriving (Show, Eq) data AbstractDeclarator = ADPointer Pointer | ADPointerDirectAbstractDeclarator (Maybe Pointer) DirectAbstractDeclarator deriving (Show, Eq) data DirectAbstractDeclarator = DADAbstractDeclarator AbstractDeclarator | DADDirectAbstractDeclaratorTypeQualListAssignExpr (Maybe DirectAbstractDeclarator) (Maybe TypeQualList) (Maybe AssignExpr) | DADDirectAbstractDeclaratorStaticTypeQualListAssignExpr (Maybe DirectAbstractDeclarator) (Maybe TypeQualList) AssignExpr | DADDirectAbstractDeclaratorTypeQualListStaticAssignExpr (Maybe DirectAbstractDeclarator) TypeQualList AssignExpr | DADDirectAbstractDeclaratorStar (Maybe DirectAbstractDeclarator) | DADDirectAbstractDeclaratorParamTypeList (Maybe DirectAbstractDeclarator) (Maybe ParamTypeList) deriving (Show, Eq) data ParamTypeList = PTLParamList ParamList Bool -- Bool is whether there's a "..." at the end deriving (Show, Eq) data ParamList = PLParamDecl ParamDecl | PLParamListParamDecl ParamList ParamDecl deriving (Show, Eq) data ParamDecl = PDDeclSpecsDeclarator DeclSpecs Declarator | PDDeclSpecsAbstractDeclarator DeclSpecs AbstractDeclarator deriving (Show, Eq) data InitList = ILDesignationInit (Maybe Designation) Init | IDInitListDesignationInit InitList (Maybe Designation) Init deriving (Show, Eq) data Designation = DDesignation DesignatorList deriving (Show, Eq) data DesignatorList = DLDesignator Designator | DLDesignatorListDesignator DesignatorList Designator deriving (Show, Eq) data Designator = DConstExpr ConstExpr | DDotIdent Ident deriving (Show, Eq) data ConstExpr = CECondExpr CondExpr deriving (Show, Eq) data Init = IAssignExpr AssignExpr | IInitList InitList deriving (Show, Eq) data UnaryOp = UOAmpersand | UOStar | UOPlus | UOMinus | UOTilde | UOBang deriving (Show, Eq) data AssignOp = AOEquals | AOTimesEquals | AODivideEquals | AOModEquals | AOPlusEquals | AOMinusEquals | AOLeftShiftEquals | AORightShiftEquals | AOBitAndEquals | AOBitXorEquals | AOBitOrEquals deriving (Show, Eq) data IdentList = ILIdent Ident | ILIdentListIdent IdentList Ident deriving (Show, Eq) data CEnumSpec = CESIdentCEnumList (Maybe Ident) CEnumList | CESIdent Ident deriving (Show, Eq) data CEnumList = CELEnum CEnum | CELEnumListCEnum CEnumList CEnum deriving (Show, Eq) data CEnum = CEEnumConst CEnumConst | CEEnumConstEqualsConstExpr CEnumConst ConstExpr deriving (Show, Eq) data TypedefName = TNIdent Ident deriving (Show, Eq) data FuncSpec = FSInline deriving (Show, Eq) data DeclList = DLDecl Decl | DLDeclListDecl DeclList Decl deriving (Show, Eq) data Decl = DDecl DeclSpecs (Maybe InitDeclList) deriving (Show, Eq) data InitDeclList = IDLInitDecl InitDecl | IDLInitDeclListInitDecl InitDeclList InitDecl deriving (Show, Eq) data InitDecl = IDDecl Decl | IDDeclEqualsInit Decl Init deriving (Show, Eq) data CompoundStmt = CSCompoundStmt (Maybe BlockItemList) deriving (Show, Eq) data BlockItemList = BILBlockItem BlockItem | BILBlockItemListBlockItem BlockItemList BlockItem deriving (Show, Eq) data BlockItem = BIDecl Decl | BIStmt Stmt deriving (Show, Eq) data Stmt = SLabeledStmt LabeledStmt | SCompoundStmt CompoundStmt | SExprStmt ExprStmt | SSelectionStmt SelectionStmt | SIterStmt IterStmt | SJumpStmt JumpStmt deriving (Show, Eq) data LabeledStmt = LSIdentStmt Ident Stmt | LSCaseConstExprStmt ConstExpr Stmt | LSDefaultStmt Stmt deriving (Show, Eq) data ExprStmt = ESExprStmt (Maybe ExprStmt) deriving (Show, Eq) data SelectionStmt = SSIfExprStmt Expr Stmt | SSIfExprStmtElseStmt Expr Stmt Stmt | SSSwitchExprStmt Expr Stmt deriving (Show, Eq) data IterStmt = ISWhileExprStmt Expr Stmt | ISDoStmtWhileExpr Stmt Expr | ISForExprExprExprStmt (Maybe Expr) (Maybe Expr) (Maybe Expr) Stmt | ISForDeclExprExprStmt Decl (Maybe Expr) (Maybe Expr) Stmt deriving (Show, Eq) data JumpStmt = JSGotoIdent Ident | JSContinue | JSBreak | JSReturnExpr Expr deriving (Show, Eq)
BenedictEggers/cha
src/CHa/Types/Grammar.hs
mit
14,456
0
8
4,346
2,516
1,406
1,110
508
0
import Data.List (sort) import Data.Word (Word32) import Network.Address import Test.QuickCheck import Test.QuickCheck.Monadic prop_ifindex :: Property prop_ifindex = monadicIO $ do ifindexes <- run getIfindexes interfaces <- run getNetworkInterfaces let ifindexes2 = map ifindex interfaces assert $ sort ifindexes == sort ifindexes2 assert $ length ifindexes == length ifindexes2 prop_random_ifindex :: Word32 -> Property prop_random_ifindex n = monadicIO $ do ifindexes <- run getIfindexes interfaces <- run getNetworkInterfaces let ifindexes2 = map ifindex interfaces case n `elem` ifindexes of True -> assert $ n `elem` ifindexes2 False -> assert $ not $ n `elem` ifindexes2 prop_all_ipv4_address :: Property prop_all_ipv4_address = monadicIO $ do allipv4s <- fmap (map fst) (run getAllIPv4Address) ipv4s <- fmap (concat . map ipv4) (run getNetworkInterfaces) mapM (\a -> assert $ a `elem` ipv4s) allipv4s mapM (\b -> assert $ b `elem` allipv4s) ipv4s assert $ length allipv4s == length ipv4s prop_all_ipv6_address :: Property prop_all_ipv6_address = monadicIO $ do allipv6s <- fmap (map fst) (run getAllIPv6Address) ipv6s <- fmap (concat . map ipv6) (run getNetworkInterfaces) mapM (\a -> assert $ a `elem` ipv6s) allipv6s mapM (\b -> assert $ b `elem` allipv6s) ipv6s assert $ length allipv6s == length ipv6s main = do quickCheck prop_ifindex quickCheck prop_random_ifindex quickCheck prop_all_ipv4_address quickCheck prop_all_ipv6_address
ldx/network-address
tests/Main.hs
mit
1,560
0
13
317
522
255
267
39
2
import Test.HUnit calc operator a b = (operator a b) testSum = TestCase (assertEqual "Sum" 5 (calc (+) 2 3)) testSub = TestCase (assertEqual "Substraction" 3 (calc (-) 5 2)) testDiv = TestCase (assertEqual "Division" 3 (calc (/) 6 2)) testMult = TestCase (assertEqual "Multiplication" 6 (calc (*) 3 2)) myTests = TestList [testSum, testSub, testDiv, testMult]
jefersonm/sandbox
languages/haskell/calculator.hs
mit
377
16
9
74
182
97
85
7
1
module DBGrader.Types where -- A view question asks a student to defined a view. -- Example: -- Define a view that returns all agents from the agent table. Name the view q1. -- -- A table question asks a student to create a table -- Example: -- Create a table named "books", insert at least 4 rows. -- -- A query question asks a student to define their database in such a way that a certain query will return some value. -- Example: -- Insert rows into the tables "books" and "authors" such that the following query will return nonempty -- SELECT * FROM books NATURAL JOIN authors; data Question = ViewQuestion { nm :: String -- Name of question (Eg. Question 1) , schema :: String -- Schema to find view , view :: String -- View name , solution :: SQLQuery -- Example solution , points :: Float -- Points question is worth. } | TableQuestion { nm :: String -- Name of question , schema :: String -- Schema to find table , table :: String -- Table name , rows :: Int -- The amount of rows that should be present in table , solution :: String -- , points :: Float -- Points question is worth } | QueryQuestion { nm :: String -- Name of question , schema :: String -- Schema to run query , query :: String -- Query to run , solution :: String -- , points :: Float -- Points question is worth } deriving (Show) -- Type synonym for a sql query. type SQLQuery = String data Student = Student { name :: String -- Student name , dbname :: String -- Student's database name } deriving (Ord, Eq, Show) data Flag = Flag { flag :: Char -- Character to denote flag , subPoints :: Float -- Amount of points to subtract , flagNote :: String -- Explanation for student } | FlagAllPts { flag :: Char -- Character to denote flag , flagNote :: String -- Explanation for student } data Config = Config { hostname :: String -- Hostname of database , database :: String -- Database for logging in , username :: String -- Username for logging in , password :: String -- Password for logging in , conninfo :: String -- Connection string, needed for HDBC }
GarrisonJ/DBGrader
DBGrader/Types.hs
mit
2,912
0
8
1,272
294
202
92
33
0
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, OverloadedLists #-} module Equal where import Foundation (Applicative,($),(.),pure,(<>),Bool(True,False),(==),Maybe(Just,Nothing),compare,undefined) import qualified Foundation ((&&)) import Prelude (Show) import qualified Prelude as P (show) import Control.Applicative (liftA2) import Control.Monad.Logger.CallStack (logDebug, MonadLogger) import Data.Foldable (foldl) import Data.Text.Lazy (Text,pack,toStrict) import Control.Monad.Morph () import Control.Monad.Logger.CallStack () import Syntax (TName,Term(Var,Lam,Pi,Sig,Def),ETerm(EType,EVar,ELam,EApp,EPi,ELet,EDef,ESig,ESigma,EProd),EType) import Environment (Env,lookupDef,extendCtxSig,extendCtxDef) import Substitution (subst) import Error(ResultM,Error(ExpectedFunctionType,DefinitionNotFound),throwErr) -- $setup -- >>> :set -XOverloadedStrings -- >>> import Environment show :: Show a => a -> Text show = pack . P.show -- lift 'and' to applicatives (&&) :: Applicative f => f Bool -> f Bool -> f Bool a && b = liftA2 (Foundation.&&) a b equate :: MonadLogger m => Env -> ETerm -> ETerm -> ResultM m Bool equate _ eterm1 eterm2 | eterm1 == eterm2 = pure True equate env eterm1 eterm2 = let equate_ = equate env defOrdering (EDef (Def name1 _) _ _) (EDef (Def name2 _) _ _) = compare name1 name2 recEquate variable expected = case lookupDef env variable of Just def -> equate_ def expected Nothing -> throwErr $ DefinitionNotFound env variable expected equateMaybe (Just a) (Just b) = equate_ a b equateMaybe ma mb = pure (ma == mb) in do logDebug $ toStrict $ "Equating\n " <> show eterm1 <> "\n " <> show eterm2 let whnf1 = whnf' env eterm1 let whnf2 = whnf' env eterm2 logDebug $ toStrict $ "in WHNF:\n " <> show whnf1 <> "\n " <> show whnf2 res <- case (whnf1, whnf2) of (EType{} , EType{}) -> pure True (EVar (Var name1) _ , EVar (Var name2) _) -> pure $ name1 == name2 (EVar (Var name) _ , otherETerm) -> recEquate name otherETerm (otherETerm , EVar (Var name) _) -> recEquate name otherETerm (ELam _ _ body1 _ , ELam _ _ body2 _) -> equate_ body1 body2 (EApp _ f1 arg1 _ , EApp _ f2 arg2 _) -> equate_ f1 f2 && equate_ arg1 arg2 (EPi _ type1A type1B , EPi _ type2A type2B) -> equate_ type1A type2A && equate_ type1B type2B (ESigma _ type1A type1B , ESigma _ type2A type2B) -> equateMaybe type1A type2A && equateMaybe type1B type2B (EProd _ val1A val1B _ , EProd _ val2A val2B _) -> equateMaybe val1A val2A && equateMaybe val1B val2B _ -> pure False logDebug $ toStrict $ "Equating done: " <> show res pure res ensurePi :: MonadLogger m => Env -> EType -> ResultM m (Maybe TName, EType, EType) ensurePi env etype = case whnf env etype of Whnf (EPi (Pi mname _ _) typeA typeB) -> pure (mname, typeA, typeB) Whnf nf -> throwErr $ ExpectedFunctionType env etype nf newtype Whnf = Whnf ETerm deriving Show whnf :: Env -> ETerm -> Whnf whnf env eterm = Whnf $ whnf' env eterm whnf' :: Env -> ETerm -> ETerm whnf' env eterm@(EVar (Var name) _) = case lookupDef env name of Just vardef -> whnf' env vardef _ -> eterm whnf' env (EApp term f arg etype) = let whnf_f = whnf' env f whnf_arg = whnf' env arg in case whnf_f of ELam (Lam name _ _) _ body _ -> whnf' env $ subst (Just name) arg body EVar (Var name) _ -> case lookupDef env name of Just vardef -> whnf' env $ EApp term vardef whnf_arg etype _ -> EApp term whnf_f whnf_arg etype _ -> EApp term whnf_f whnf_arg etype whnf' env (ELet _ xs body _) = let extendCtx e (ESig (Sig name _) etype) = extendCtxSig name (whnf' e etype) e extendCtx e (EDef (Def name _) eterm _) = extendCtxDef name (whnf' e eterm) e newEnv = foldl extendCtx env xs in whnf' newEnv body whnf' _ tm = tm
jyrimatti/alava
src-lib/Equal.hs
mit
4,208
29
20
1,183
1,556
818
738
75
12
module Operators ( findoperator ) where import Control.Monad.State (modify) import Data.Bits ((.&.), (.|.), xor, shiftL, shiftR) import Data.List (genericLength) import qualified Data.Map as Map import Stack (Symbol(Int, Frac, Real, Bool, Variable, String, List), Stack, ctxStack, modCtxStack, CalcError(OtherError), tonum) import {-# SOURCE #-} Core (calc, contextFromStack, CoreFct) type HelpString = String type Fct = [Symbol] -> [Symbol] {- Stack operator - Number of inputs (elements removed from the stack) * non-negative: the number of elements really removed from the stack * -1: removes a number of elements that depend on the parameters * -2: the operators uses the entire stack - Number of outputs (elements pushed back on the stack) * non-negative: the number of elements really pushed on the stack * -1: pushes a number of elements that depend on the parameters - Function to run - Description -} type Operator = (Int, Int, Fct, HelpString) run :: Operator -> Stack -> Stack run (argc,_,f,_) ys | length argv == n = f argv ++ zs where (n,ys') = case argc of -1 -> (round.tonum $ head ys, tail ys) -2 -> (length ys, ys) _ -> (argc, ys) (argv,zs) = splitAt n ys' findoperator :: String -> Maybe CoreFct findoperator name = modify . modCtxStack . run <$> Map.lookup name operators op_neg :: Fct op_neg [a] = case a of Int n -> [Int (-n)] Frac (n,d) -> [Frac (-n,d)] Real x -> [Real (-x)] op_add :: Fct op_add [a,b] = case (a,b) of (Int n, Int n') -> [Int $ n+n'] (Int n, Frac (n',d')) -> do_frac (n,1) (n',d') (Int n, Real x') -> [Real $ (+) (fromIntegral n) x'] (Frac (n,d), Int n') -> do_frac (n,d) (n',1) (Frac (n,d), Frac (n',d')) -> do_frac (n,d) (n',d') (Frac (n,d), Real x') -> [Real $ (+) ((fromIntegral n)/(fromIntegral d)) x'] (Real x, Int n') -> [Real $ (+) x (fromIntegral n')] (Real x, Frac (n',d')) -> [Real $ (+) x ((fromIntegral n')/(fromIntegral d'))] (Real x, Real x') -> [Real $ (+) x x'] where do_frac (n,d) (n',d') = op_rnd $ [Frac (n*d' + n'*d, d*d')] op_min :: Fct op_min [b,a] = case (a,b) of (Int n, Int n') -> [Int $ n-n'] (Int n, Frac (n',d')) -> do_frac (n,1) (n',d') (Int n, Real x') -> [Real $ (-) (fromIntegral n) x'] (Frac (n,d), Int n') -> do_frac (n,d) (n',1) (Frac (n,d), Frac (n',d')) -> do_frac (n,d) (n',d') (Frac (n,d), Real x') -> [Real $ (-) ((fromIntegral n)/(fromIntegral d)) x'] (Real x, Int n') -> [Real $ (-) x (fromIntegral n')] (Real x, Frac (n',d')) -> [Real $ (-) x ((fromIntegral n')/(fromIntegral d'))] (Real x, Real x') -> [Real $ (-) x x'] where do_frac (n,d) (n',d') = op_rnd $ [Frac (n*d' - n'*d, d*d')] op_mult :: Fct op_mult [a,b] = case (a,b) of (Int n, Int n') -> [Int $ n*n'] (Int n, Frac (n',d')) -> do_frac (n,1) (n',d') (Int n, Real x') -> [Real $ (*) (fromIntegral n) x'] (Frac (n,d), Int n') -> do_frac (n,d) (n',1) (Frac (n,d), Frac (n',d')) -> do_frac (n,d) (n',d') (Frac (n,d), Real x') -> [Real $ (*) ((fromIntegral n)/(fromIntegral d)) x'] (Real x, Int n') -> [Real $ (*) x (fromIntegral n')] (Real x, Frac (n',d')) -> [Real $ (*) x ((fromIntegral n')/(fromIntegral d'))] (Real x, Real x') -> [Real $ (*) x x'] where do_frac (n,d) (n',d') = op_rnd $ [Frac (n*n',d*d')] op_div :: Fct op_div [b,a] = case (a,b) of (Int n, Int n') -> do_frac (n,1) (n',1) (Int n, Frac (n',d')) -> do_frac (n,1) (n',d') (Int n, Real x') -> [Real $ (/) (fromIntegral n) x'] (Frac (n,d), Int n') -> do_frac (n,d) (n',1) (Frac (n,d), Frac (n',d')) -> do_frac (n,d) (n',d') (Frac (n,d), Real x') -> [Real $ (/) ((fromIntegral n)/(fromIntegral d)) x'] (Real x, Int n') -> [Real $ (/) x (fromIntegral n')] (Real x, Frac (n',d')) -> [Real $ (/) x ((fromIntegral n')/(fromIntegral d'))] (Real x, Real x') -> [Real $ (/) x x'] where do_frac (n,d) (n',d') = op_rnd $ [Frac (n*d',d*n')] op_mod :: Fct op_mod [Int b, Int a] = [Int $ mod a b] op_pow :: Fct op_pow [b,a] = case (a,b) of (Int n, Int n') -> [Int $ n^n'] (Frac (n,d), Int n') -> do_frac (n,d) n' (Int n, Frac (n',d')) -> do_real (fromIntegral n) ((fromIntegral n')/(fromIntegral d')) (Int n, Real x') -> do_real (fromIntegral n) x' (Frac (n,d), Frac (n',d')) -> do_real ((fromIntegral n)/(fromIntegral d)) ((fromIntegral n')/(fromIntegral d')) (Frac (n,d), Real x') -> do_real ((fromIntegral n)/(fromIntegral d)) x' (Real x, Int n') -> do_real x (fromIntegral n') (Real x, Frac (n',d')) -> do_real x ((fromIntegral n')/(fromIntegral d')) (Real x, Real x') -> do_real x x' where do_frac (n,d) n' = op_rnd $ [Frac (n^n',d^n')] do_real x y = [Real $ x**y] op_inv :: Fct op_inv [a] = case a of Int n -> do_frac (n,1) Frac (n,d) -> do_frac (n,d) Real x -> [Real $ 1/x] where do_frac (n,d) = op_rnd $ [Frac (d,n)] op_num :: Fct op_num [a] = case a of Int n -> [Real $ fromIntegral n] Frac (n,d) -> [Real $ (fromIntegral n) / (fromIntegral d)] Real x -> [Real x] List xs -> [List $ map (\x -> head $ op_num [x]) xs] op_rnd :: Fct op_rnd [Int n] = [Int n] op_rnd [Frac (n,d)] = let (g,u,v) = (gcd n d, div n g, div d g) in if v == 1 then [Int u] else [Frac (u,v)] op_rnd [Real x] = [Int $ round x] op_rnd [List xs] = [List $ map (\x -> head $ op_rnd [x]) xs] op_floor :: Fct op_floor [Int n] = [Int n] op_floor [Frac (n,d)] = [Int $ floor $ (intToDouble n)/(intToDouble d)] op_floor [Real x] = [Int $ floor x] op_floor [List xs] = [List $ map (\x -> head $ op_floor [x]) xs] op_ceil :: Fct op_ceil [Int n] = [Int n] op_ceil [Frac (n,d)] = [Int $ ceiling $ (intToDouble n)/(intToDouble d)] op_ceil [Real x] = [Int $ ceiling x] op_ceil [List xs] = [List $ map (\x -> head $ op_ceil [x]) xs] op_abs :: Fct op_abs [Int n] = [Int $ abs n] op_abs [Frac (n,d)] = [Frac (abs n,d)] op_abs [Real x] = [Real $ abs x] op_abs [List xs] = [List $ map (\x -> head $ op_abs [x]) xs] intToDouble :: Integer -> Double intToDouble = fromIntegral -- units/dimensions data Dimension = Mass | Length | Time | Temperature | Volume | Pressure | Speed | Force deriving (Show,Eq) -- | Intensity | LightIntensity | ... type Unit = (Dimension,(String,String)) --units_prefix = [("T", Int 1000000000000), ("P", Int 1000000000000000), ("G", Int 1000000000), ("M", Int 1000000), ("k",Int 1000),("h",Int 100),("m",Frac (1,1000)),("µ",Frac(1,1000000)),("n",Frac (1,1000000000)),("p",Frac (1,1000000000000)),("f",Frac (1,1000000000000000))] units :: Map.Map String Unit units = Map.fromList $ [ ("m",(Length,("",""))), ("inch",(Length,("254 10000 / *","254 10000 / /"))), ("foot",(Length,("3048 10000 / *","3048 10000 / /"))), ("yd",(Length,("9144 10000 / *","9144 10000 / /"))), ("mile",(Length,("1609344 1000 / *", "1609344 1000 / /"))), ("l",(Volume,("",""))), ("gal",(Volume,("3785472 1000000 / *", "3785472 1000000 / /"))), ("floz",(Volume,("29574 1000000 / *", "29574 1000000 / /"))), ("Pa",(Pressure,("",""))), ("bar",(Pressure,("100000 *","100000 /"))), ("psi",(Pressure,("6894.757 *", "6894.757 /"))), ("kg",(Mass,("",""))),("lb",(Mass,("0.45359237 *","0.45359237 /"))), ("k",(Temperature,("",""))), ("dC",(Temperature,("273.15 +","273.15 -"))), ("dF",(Temperature,("459.67 + 5 * 9 /","9 * 5 / 459.67 -"))) ] unit_get :: String -> Either CalcError (String,Unit) unit_get unit = case Map.lookup unit units of Just u -> Right (unit,u) Nothing -> Left $ OtherError $ "unit not found " ++ unit unit_scriptfrom :: (a, (b, c)) -> b unit_scriptfrom = fst.snd unit_scriptto :: (a, (b, c)) -> c unit_scriptto = snd.snd unit_convert :: Fct unit_convert [String to, String from, value] = case dims of Left err -> [String $ show err] Right _ -> eitherToStack $ unitPair >>= convert where unit_from :: Either CalcError (String, Unit) unit_from = unit_get from unit_to :: Either CalcError (String, Unit) unit_to = unit_get to dims :: Either CalcError (Unit, Unit) dims = unitPair >>= check_dims check_dims :: ((String,Unit),(String,Unit)) -> Either CalcError (Unit,Unit) check_dims (a,b) = check_dimensions a b unitPair :: Either CalcError ((String,Unit),(String,Unit)) unitPair = do uf <- unit_from ut <- unit_to return (uf,ut) convert :: ((String,Unit),(String,Unit)) -> Either CalcError Stack convert (u_from, u_to) = runscript script [value] where script = unit_scriptfrom (snd u_from) ++ " " ++ unit_scriptto (snd u_to) -- TODO add dimension equivalence for compound dimensions such as Speed, Force or Volume check_dimensions :: (String,Unit) -> (String,Unit) -> Either CalcError (Unit, Unit) check_dimensions (str1,unit1) (str2,unit2) = if dim unit1 == dim unit2 then Right (unit1, unit2) else Left $ OtherError $ "units " ++ str1 ++ " and " ++ str2 ++ " don't match (" ++ (show $ dim unit1) ++ "/" ++ (show $ dim unit2) ++ ")" where dim unit = fst unit op_unit = [("convert",(3,1,unit_convert, "Unit converter"))] -- a script here is supposed to contain only basic operators, not core functions, so it has no effect on variables, only the stack runscript :: String -> Stack -> Either CalcError Stack runscript script stack = h $ calc script $ contextFromStack stack where h (Just err, _) = Left err h (Nothing, ctx) = Right $ ctxStack ctx eitherToStack :: Either CalcError Stack -> Stack eitherToStack (Left err) = [String $ show err] eitherToStack (Right ss) = ss -- lists op_sum :: [Symbol] -> Stack op_sum [List xs] = let (n,ps) = (length xs,concat $ replicate (n-1) "+ ") in eitherToStack $ runscript ps xs op_mean :: [Symbol] -> Stack op_mean [List xs] = let (n,ps) = (length xs,concat $ replicate (n-1) "+ ") in eitherToStack $ runscript (ps ++ show n ++ " /") xs op_concat, op_addhead, op_reverse, op_length :: Fct op_head, op_tail, op_last, op_init :: Fct op_drop, op_take, op_range :: Fct op_concat [List b,List a] = [List $ a ++ b] op_concat [String b,String a] = [String $ a ++ b] op_addhead [List xs, x] = [List $ x : xs] op_addhead [x, List xs] = [List $ x : xs] op_reverse [List a] = [List $ reverse a] op_reverse [String a] = [String $ reverse a] op_length [List a] = [Int $ genericLength a] op_length [String a] = [Int $ genericLength a] op_head [List xs] = [head xs] op_head [String xs] = [String $ head xs : []] op_tail [List xs] = [List $ tail xs] op_tail [String xs] = [String $ tail xs] op_last [List xs] = [last xs] op_last [String xs] = [String $ last xs : []] op_init [List xs] = [List $ init xs] op_init [String xs] = [String $ init xs] op_drop [Int n, List xs] = [List $ drop (fromIntegral n) xs] op_drop [Int n, String xs] = [String $ drop (fromIntegral n) xs] op_take [Int n, List xs] = [List $ take (fromIntegral n) xs] op_take [Int n, String xs] = [String $ take (fromIntegral n) xs] op_range [end,start] = case (start,end) of (Int a,Int b) -> [List $ map Int [a..b]] ( _ , _ ) -> [List $ map Real [(tonum start)..(tonum end)]] -- stack op_swap, op_del, op_dup, op_rep, op_get, op_clear, op_type :: Fct op_swap [a,b] = [b,a] op_del [_] = [] op_dup [a] = [a,a] op_rep [Int n,a] = replicate (fromIntegral n) a op_get xs = last xs : init xs op_clear _ = [] op_type [a] = case a of Int _ -> [String "Integer", a] Frac _ -> [String "Frac", a] Real _ -> [String "Real", a] Bool _ -> [String "Bool", a] Variable _ -> [String "Variable", a] String _ -> [String "String", a] List _ -> [String "List", a] -- logic/boolean operators logic_and, logic_or, logic_xor :: Fct logic_not, logic_nor, logic_nand :: Fct logic_lshift, logic_rshift :: Fct logic_swap2, logic_swap4, logic_swap8 :: Fct logic_and [Bool a, Bool b] = [Bool $ a && b] logic_and [Int a, Int b] = [Int $ a .&. b] logic_or [Bool a, Bool b] = [Bool $ a || b] logic_or [Int a, Int b] = [Int $ a .|. b] logic_xor [Bool a, Bool b] = [Bool $ (a || b) && not (a && b)] logic_xor [Int a, Int b] = [Int $ a `xor` b] logic_not [Bool a] = [Bool $ not a] logic_nor = logic_not . logic_or logic_nand = logic_not . logic_and logic_lshift [Int n, Int a] | a >= 0 && n >= 0 = [Int $ shiftL a (fromInteger n)] logic_rshift [Int n, Int a] | a >= 0 && n >= 0 = [Int $ shiftR a (fromInteger n)] logic_swap2 [Int a] | a >= 0 = [Int $ do_swap 2 a] logic_swap4 [Int a] | a >= 0 = [Int $ do_swap 4 a] logic_swap8 [Int a] | a >= 0 = [Int $ do_swap 8 a] do_swap :: Int -> Integer -> Integer do_swap bytes = foldl (.|.) 0 . zipWith (flip shiftLB) [0..] . as_bytes bytes where shiftLB x = shiftL x . (*8) shiftRB x = shiftR x . (*8) as_bytes b x = map h $ reverse [0..b-1] where h i = (x `shiftRB` i) .&. 0xff -- comparison tests test_eq, test_ne, test_lt, test_gt, test_le, test_ge :: Ord a => [a] -> [Symbol] test_eq [b,a] = [Bool $ a == b] test_ne [b,a] = [Bool $ a /= b] test_lt [b,a] = [Bool $ a < b] test_gt [b,a] = [Bool $ a > b] test_le [b,a] = [Bool $ a <= b] test_ge [b,a] = [Bool $ a >= b] -- math functions mathfct :: (Double -> Double) -> [Symbol] -> [Symbol] mathfct f [a] = case a of Int n -> [Real (f $ fromIntegral n)] Frac (n,d) -> [Real (f $ (fromIntegral n)/(fromIntegral d))] Real x -> [Real (f $ x)] operators :: Map.Map String Operator operators = Map.fromList $ op_stack ++ op_math ++ op_fct ++ op_logic ++ op_test ++ op_list ++ cst {-++ op_abstract-} ++ op_unit cst, op_list, op_stack, op_math, op_fct, op_logic, op_test, op_unit :: [(String, Operator)] cst = [("pi", (0,1,\_ -> [Real pi], "Pi constant"))] op_list = [("++", (2,1,op_concat, "Concatenate two lists")), (":", (2,1,op_addhead, "Add an element at the head of a list")), ("reverse", (1,1,op_reverse, "Reverse a list")), ("length", (1,1,op_length, "Length of a list")), ("head", (1,1,op_head, "Head of a list")), ("tail", (1,1,op_tail, "Tail of a list")), ("last", (1,1,op_last, "Last element of a list")), ("init", (1,1,op_init, "First elements of a list")), ("drop", (2,1,op_drop, "Drop the first n elements from a list")), ("take", (2,1,op_take, "Take the first n elements from a list")), ("range", (2,1,op_range, "Creates a range of numbers")), ("sum", (1,1,op_sum, "Sum all elements in a list")), ("mean", (1,1,op_mean, "Computes the mean value of a list"))] op_stack = [("swap", (2,2,op_swap, "Swap the first two elements on the stack")), ("del", (1,0,op_del, "Remove the first element from the stack")), ("dup", (1,2,op_dup, "Duplicate the first stack element")), ("rep", (2,-1,op_rep, "Repeat the second element n times, where n is the first element on the stack")), ("get", (-1,-1,op_get, "Puts the n-th element at the top of the stack, where n is the first element on the stack")), ("cls", (-2,0,op_clear, "Clears the stack")), ("type", (1,2,op_type, "Prints the type of the first stack element"))] op_math = [("n", (1,1,op_neg, "Changes the sign of the first stack element")), ("+", (2,1,op_add, "Adds the first two elements")), ("-", (2,1,op_min, "Substracts the first element from the second")), ("*", (2,1,op_mult, "Multiplies the first two elements")), ("/", (2,1,op_div, "Divides the second element by the first")), ("%", (2,1,op_mod, "Remainder of the division of the second element by the first")), ("^", (2,1,op_pow, "Elevates the second element to the first")), ("inv", (1,1,op_inv, "Inverses the first element on the stack")), ("num", (1,1,op_num, "Replaces the first element by its numerical value")), ("rnd", (1,1,op_rnd, "Rounds a numerical value")), ("floor", (1,1,op_floor, "Rounds a numerical value to the integer immediately smaller")), ("ceil", (1,1,op_ceil, "Rounds a numerical value to the integer immediately larger")), ("abs", (1,1,op_abs, "Absolute value"))] op_fct = [("cos", (1,1,mathfct cos, "Cosine, parameter in radians")), ("sin", (1,1,mathfct sin, "Sine, parameter in radians")), ("tan", (1,1,mathfct tan, "Tangent, parameter in radians")), ("exp", (1,1,mathfct exp, "Exponential")), ("log", (1,1,mathfct log, "Logarithm (base e))")), ("sqrt", (1,1,mathfct sqrt, "Square root"))] op_logic = [("and", (2,1,logic_and, "Logical AND")), ("or", (2,1,logic_or, "Logical OR")), ("xor", (2,1,logic_xor, "Logical XOR")), ("nand", (2,1,logic_nand, "Logical NAND")), ("not", (1,1,logic_not, "Logical NOT")), ("nor", (2,1,logic_nor, "Logical NOR")), ("<<", (2,1,logic_lshift, "Bitwise left shift")), (">>", (2,1,logic_rshift, "Bitwise right shift")), ("swap2", (1,1,logic_swap2, "Swap two-byte int")), ("swap4", (1,1,logic_swap4, "Swap four-byte int")), ("swap8", (1,1,logic_swap8, "Swap eight-byte int"))] op_test = [("==", (2,1,test_eq, "Equality test")), ("<", (2,1,test_lt, "Inequality test, true if second < first")), (">", (2,1,test_gt, "Inequality test, true if second > first")), ("/=", (2,1,test_ne, "Difference test")), ("<=", (2,1,test_le, "Inequality test, true if second <= first")), (">=", (2,1,test_ge, "Inequality test, true if second >= first"))] {- op_abstract = [("solve", (1,1,abs_solve, "Simple solver"))] abs_solve [String eq] = case parse $ rmquotes eq of Just [a, [_], "*", b, "+"] -> let expr = b ++ " " ++ a ++ " / n" in fst $ calc expr ([],Map.empty) Just [a, [_], "*", b, "-"] -> let expr = b ++ " " ++ a ++ " /" in fst $ calc expr ([],Map.empty) Nothing -> [String "no parse", String eq] _ -> [String $ "invalid/unsolvable equation: " ++ eq, String eq] -}
qsn/rhcalc
src/Operators.hs
mit
18,559
0
15
4,652
8,305
4,680
3,625
321
9
module Main where import Hqdsl main :: IO () main = do let t = table "clients" [ "first_name", "middle_name", "last_name", "birthdate" ] s = select (\[t, j0, j1] -> [ column t "first_name", column j0 "last_name", column j1 "first_namex", column j1 "last_name" ]) $ from t [ innerJoin t (\t0 t1 -> equals (column t0 "first_name") (column t1 "last_name")), innerJoin t (\t0 t1 -> equals (column t0 "first_name") (column t1 "last_name")) ] putStrLn $ show $ render s
rcook/hqdsl
src/app/Main.hs
mit
583
0
18
198
206
108
98
20
1
module Calculus ( integrate ) where -- | Integrate function of one variable -- | f - function -- | l - Left (lower) bound -- | r - Right (upper) bound -- | n - Number of steps integrate :: (Fractional a, Ord a, Integral b) => (a -> a) -> a -> a -> b -> a integrate f l r n | l < r = f l * d + integrate f (l + d) r (n - 1) | otherwise = 0 where d = (r - l) / fromIntegral n
korczis/haskell-world
lib/Calculus.hs
mit
387
0
9
109
151
80
71
7
1
{-# LANGUAGE BangPatterns #-} module Util (foldLines, transformLines) where import System.IO transformLines :: (String -> String) -> (IO ()) transformLines f = do iseof <- isEOF if iseof then return () else getLine >>= putStrLn . f >> transformLines f foldLines :: (a -> String -> a) -> a -> (IO a) foldLines f a = do iseof <- isEOF if iseof then return a else getLine >>= (\s -> foldLines f (sf a s)) where sf !a' !s' = f a' s'
nlim/haskell-playground
src/Util.hs
mit
612
0
13
266
193
99
94
14
2
import Data.Array factoChar :: Array Char Int factoChar = array ('0', '9') (('0' , 1):[(d2c i, i*factoChar!(d2c (i-1))) | i <- [1..9]]) where d2c = head.show step :: Int -> Int step n = sum $ map (\d -> factoChar ! d) $ show n seqEuler :: Int -> [Int] seqEuler n = iter (step n) [n] where iter n acc = if (elem n acc) then acc else iter (step n) (n:acc) validNumbers = filter ((60 ==) . length . seqEuler) [((((a*10+b)*10+c)*10+d)*10+e)*10+f | a <- [0..9], b <- [0..9], c <- [0..9], d <- [0..9], e <- [0..9], f <- [0..9]] main = print $ length validNumbers
dpieroux/euler
0/0074.hs
mit
576
4
19
127
400
213
187
14
2
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.XPathException (toString, toString_, pattern INVALID_EXPRESSION_ERR, pattern TYPE_ERR, getCode, getName, getMessage, XPathException(..), gTypeXPathException) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathException.toString Mozilla XPathException.toString documentation> toString :: (MonadDOM m, FromJSString result) => XPathException -> m result toString self = liftDOM ((self ^. jsf "toString" ()) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathException.toString Mozilla XPathException.toString documentation> toString_ :: (MonadDOM m) => XPathException -> m () toString_ self = liftDOM (void (self ^. jsf "toString" ())) pattern INVALID_EXPRESSION_ERR = 51 pattern TYPE_ERR = 52 -- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathException.code Mozilla XPathException.code documentation> getCode :: (MonadDOM m) => XPathException -> m Word getCode self = liftDOM (round <$> ((self ^. js "code") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathException.name Mozilla XPathException.name documentation> getName :: (MonadDOM m, FromJSString result) => XPathException -> m result getName self = liftDOM ((self ^. js "name") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathException.message Mozilla XPathException.message documentation> getMessage :: (MonadDOM m, FromJSString result) => XPathException -> m result getMessage self = liftDOM ((self ^. js "message") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/XPathException.hs
mit
2,530
0
12
326
617
367
250
38
1
main = interact wordCount where wordCount input = show (foldr (\x acc -> acc + characterCount (words x)) 0 (lines input)) ++ "\n" characterCount = foldr (\x acc -> acc + length x) 0
aksswami/learning-haskell
ch01/CC.hs
mit
193
1
14
45
93
46
47
3
1
module GHCJS.DOM.SVGCircleElement ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGCircleElement.hs
mit
46
0
3
7
10
7
3
1
0
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} module Infernu.Infer ( runTypeInference , test , getAnnotations , minifyVars , TypeError ) where import Control.Monad (foldM, forM) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Set (Set) import qualified Data.Set as Set import Data.Char (isUpper) import Text.PrettyPrint.ANSI.Leijen (Pretty (..), align, text, (<+>), vsep, align, indent) import Infernu.Prelude import qualified Infernu.Builtins as Builtins import Infernu.InferState import Infernu.Lib (safeLookup) import Infernu.Log import Infernu.Pretty() import Infernu.Types import Infernu.Source (Source(..), TypeError(..)) import Infernu.Expr (Exp(..), LitVal(..), EVarName(..), EPropName(..)) import Infernu.Unify (unify, unifyAll, unifyPending, unifyPredsL, unifyl, tryMakeRow) getAnnotations :: Exp a -> [a] getAnnotations = foldr (:) [] ---------------------------------------------------------------------- closeRowList :: Bool -> Source -> TRowList Type -> Infer (TRowList Type) closeRowList unrollRec a (TRowProp p t l) = TRowProp p t <$> closeRowList unrollRec a l closeRowList _ _ (TRowEnd _) = return $ TRowEnd Nothing closeRowList unrollRec a r@(TRowRec tid ts) = if not unrollRec then return $ r else do qt <- unrollName a tid ts case qualType qt of Fix (TRow _ r') -> closeRowList False a r' _ -> error $ show $ text "Expected row type, got: " <+> pretty qt -- | Replaces a top-level open row type with the closed equivalent. -- >>> pretty $ closeRow (Fix $ TRow $ TRowProp "a" (schemeEmpty $ Fix $ TRow $ TRowProp "aa" (schemeEmpty $ Fix $ TBody TNumber) (TRowEnd (Just $ RowTVar 1))) (TRowEnd (Just $ RowTVar 2))) -- "{a: {aa: Number, ..b}}" -- >>> pretty $ closeRow (Fix $ TFunc [Fix $ TRow $ TRowProp "a" (schemeEmpty $ Fix $ TRow $ TRowProp "aa" (schemeEmpty $ Fix $ TBody TNumber) (TRowEnd Nothing)) (TRowEnd Nothing)] (Fix $ TBody TString)) -- "{a: {aa: Number}}.(() -> String)" -- >>> pretty $ closeRow (Fix $ TFunc [Fix $ TRow $ TRowProp "a" (schemeEmpty $ Fix $ TRow $ TRowProp "a.a" (schemeEmpty $ Fix $ TBody TNumber) (TRowEnd (Just $ RowTVar 1))) (TRowEnd (Just $ RowTVar 2))] (Fix $ TBody TString)) -- "{a: {a.a: Number, ..b}, ..c}.(() -> String)" closeRow :: Source -> Type -> Infer Type closeRow a (Fix (TRow l r)) = Fix . TRow (fmap (++"*") l) <$> closeRowList True a r closeRow _ t = return t ---------------------------------------------------------------------- -- For efficiency reasons, types list is returned in reverse order. accumInfer :: TypeEnv -> [Exp Source] -> Infer [(QualType, Exp (Source, QualType))] accumInfer env = do traceLog $ text "accumInfer: env: " <+> pretty env foldM accumInfer' [] where accumInfer' types expr = do (t, e) <- inferType env expr return ((t,e):types) -- wrapInferError :: Exp Source -> Infer a -> Infer a -- wrapInferError exp act = wrapError format' s act -- where format' te = vsep [text "During type inference for:" -- , indent 4 $ pretty exp -- , text "Failed with:" -- , indent 4 $ pretty te -- ] -- s = head $ getAnnotations exp inferType :: TypeEnv -> Exp Source -> Infer (QualType, Exp (Source, QualType)) inferType env expr = do traceLog $ text ">> " <+> pretty expr <+> text " -- env: " <+> pretty env -- (t, e) <- wrapInferError expr $ inferType' env expr (t, e) <- inferType' env expr unifyPending s <- getMainSubst st <- getState traceLog $ text ">> " <+> pretty expr <+> text " -- inferred :: " <+> pretty (applySubst s t) traceLog $ indent 4 $ text "infer state: " <+> pretty st return (applySubst s t, fmap (applySubst s) e) inferType' :: TypeEnv -> Exp Source -> Infer (QualType, Exp (Source, QualType)) inferType' _ (ELit a lit) = do let t = Fix $ TBody $ case lit of LitNumber _ -> TNumber LitBoolean _ -> TBoolean LitString _ -> TString LitRegex{} -> TRegex LitUndefined -> TUndefined LitNull -> TNull LitEmptyThis -> TEmptyThis return (qualEmpty t, ELit (a, qualEmpty t) lit) inferType' env (EVar a n) = do t <- instantiateVar a n env return (t, EVar (a, t) n) inferType' env (EAbs a argNames e2) = do argTypes <- forM argNames (const $ Fix . TBody . TVar <$> freshFlex) env' <- foldM (\e (n, t) -> addVarScheme e n $ schemeEmpty t) env $ zip argNames argTypes (t1, e2') <- inferType env' e2 pred' <- unifyPredsL a $ qualPred t1 let t = TQual pred' $ Fix $ TFunc argTypes (qualType t1) return (t, EAbs (a, t) argNames e2') inferType' env (EApp a e1 eArgs) = do tvar <- Fix . TBody . TVar <$> freshFlex (t1, e1') <- inferType env e1 traceLog $ text "EApp: Inferred type for func expr: " <+> pretty t1 argsTE <- accumInfer env eArgs traceLog $ text "EApp: Inferred types for func args: " <+> pretty argsTE let rargsTE = reverse argsTE tArgs = map fst rargsTE eArgs' = map snd rargsTE preds = concatMap qualPred $ t1:tArgs unify a (Fix $ TFunc (map qualType tArgs) tvar) (qualType t1) traceLog $ text "Inferred preds: " <+> pretty preds tvar' <- do pred' <- unifyPredsL a preds tvarSubsted <- applyMainSubst tvar return $ TQual pred' tvarSubsted traceLog $ text "Inferred func application: " <+> pretty tvar' return (tvar', EApp (a, tvar') e1' eArgs') inferType' env (ENew a e1 eArgs) = do (t1, e1') <- inferType env e1 let label e' = case e' of EVar _ n -> Just n ELet _ _ _ e'' -> label e'' _ -> Nothing argsTE <- accumInfer env eArgs thisT <- Fix . TBody . TVar <$> freshFlex resT <- Fix . TBody . TVar <$> freshFlex let rargsTE = reverse argsTE tArgs = thisT : map (qualType . fst) rargsTE eArgs' = map snd rargsTE preds = concatMap qualPred $ t1 : map fst argsTE unify a (Fix $ TFunc tArgs resT) (qualType t1) -- constrain 'this' to be a row type: rowConstraintVar <- RowTVar <$> freshFlex unify a (Fix . TRow Nothing . TRowEnd $ Just rowConstraintVar) thisT -- close the row type resolvedThisT <- applyMainSubst thisT -- otherwise closeRow will not do what we want. -- unify a thisT (closeRow resolvedThisT) -- TODO: If the function returns a row type, it should be the resulting type; other it should be 'thisT' preds' <- unifyPredsL a preds let thisT' = TQual preds' thisTLabeled thisTLabeled = case resolvedThisT of Fix (TRow Nothing rl) -> Fix $ TRow (label e1) rl _ -> resolvedThisT return (thisT', ENew (a, thisT') e1' eArgs') inferType' env (ELet a n e1 e2) = do recType <- Fix . TBody . TVar <$> freshFlex recEnv <- addVarScheme env n $ schemeEmpty recType (t1, e1') <- inferType recEnv e1 unify a (qualType t1) recType recType' <- applyMainSubst recType -- TODO hacky special treatment of names that start with uppercase letters. should perhaps be -- moved to translation layer. t1' <- case (isUpper $ head n, unFix recType') of (True, TFunc (thisT:argsT) resT) -> do closedThisT <- closeRow a thisT traceLog $ vsep [ text "Closing 'this' row type: " <+> align (pretty thisT) , text "while inferring type of" <+> align (pretty n) , text "which has type: " <+> align (pretty recType') ] traceLog $ text "\tClosed: " <+> align (pretty closedThisT) unify a thisT closedThisT return $ t1 { qualType = Fix $ TFunc (closedThisT:argsT) resT } _ -> return $ t1 (t', preds) <- generalize e1 env t1' env' <- addVarScheme env n t' (t2, e2') <- inferType env' e2 preds' <- unifyPredsL a $ preds ++ concatMap qualPred [t1', t2] let resT = TQual preds' $ qualType t2 return (resT, ELet (a, resT) n e1' e2') -- | Handling of mutable variable assignment. -- | Prevent mutable variables from being polymorphic. inferType' env (EPropAssign a objExpr prop expr1 expr2) = do (objT, objExpr') <- inferType env objExpr (rvalueT, expr1') <- inferType env expr1 rowTailVar <- RowTVar <$> freshFlex -- Don't generalize prop assignments, because it causes inference of too-polymorphic types that -- the user may not have meant to use, and later cause errors when another assignment is not as -- polymorphic. In the future, type annotations could be used to make the prop assignment -- polymorphic. let rvalueSchemeFloated = TScheme [] TQual { qualPred = [], qualType = qualType rvalueT } rvalueRowType = Fix . TRow Nothing . TRowProp (TPropGetName prop) rvalueSchemeFloated . TRowProp (TPropSetName prop) rvalueSchemeFloated $ TRowEnd (Just rowTailVar) unify a (qualType objT) rvalueRowType (expr2T, expr2') <- inferType env expr2 -- TODO what about the pred preds <- unifyPredsL a $ concatMap qualPred [objT, rvalueT, expr2T] -- TODO review let tRes = TQual preds $ qualType expr2T return (tRes, EPropAssign (a, tRes) objExpr' prop expr1' expr2') inferType' env (EArray a exprs) = do tv <- Fix . TBody . TVar <$> freshFlex te <- accumInfer env exprs let types = map (qualType . fst) te unifyl unify a $ zip (tv:types) types let t = qualEmpty $ Fix $ TCons TArray [tv] return (t, EArray (a,t) $ map snd te) inferType' env (ETuple a exprs) = do te <- accumInfer env exprs let t = TQual (concatMap (qualPred . fst) te) $ Fix . TCons TTuple . reverse $ map (qualType . fst) te return (t, ETuple (a,t) $ map snd te) inferType' env (EStringMap a exprs') = do let exprs = map snd exprs' elemType <- Fix . TBody . TVar <$> freshFlex te <- accumInfer env exprs let types = map (qualType . fst) te unifyAll a $ elemType:types allPreds <- unifyPredsL a . concatMap qualPred $ map fst te let t = TQual { qualPred = allPreds, qualType = Fix $ TCons TStringMap [elemType] } return (t, EStringMap (a,t) $ zip (map fst exprs') (map snd te)) inferType' env (ERow a isOpen propExprs) = do te <- accumInfer env $ map snd propExprs endVar <- RowTVar <$> freshFlex let propNamesTypes = zip propExprs (reverse $ map fst te) rowEnd' = TRowEnd $ if isOpen then Just endVar else Nothing accumRowProp' (row, floatedPs') ((propName, propExpr), propType) = do (ts, floatedPs) <- generalize propExpr env propType -- TODO use unfloated predicates return (TRowProp (TPropGetName propName) ts $ TRowProp (TPropSetName propName) ts $ row, floatedPs' ++ floatedPs) (rowType', floatedPreds) <- foldM accumRowProp' (rowEnd', []) propNamesTypes let rowType = TQual { qualPred = floatedPreds, qualType = Fix . TRow Nothing $ rowType' } return (rowType, ERow (a,rowType) isOpen $ zip (map fst propExprs) (map snd te)) inferType' env (ECase a eTest eBranches) = do (eType, eTest') <- inferType env eTest infPatterns <- accumInfer env $ map (ELit a . fst) eBranches let patternTypes = map (qualType . fst) infPatterns unifyAll a $ qualType eType : patternTypes infBranches <- accumInfer env $ map snd eBranches let branchTypes = map (qualType . fst) infBranches unifyAll a branchTypes allPreds <- unifyPredsL a . concatMap qualPred $ eType : map fst infPatterns ++ map fst infBranches let tRes = TQual { qualPred = allPreds, qualType = qualType . fst $ head infBranches } -- TODO unsafe head return (tRes, ECase (a, tRes) eTest' $ zip (map fst eBranches) (map snd infBranches)) inferType' env (EProp a eObj propName) = do (tObj, eObj') <- inferType env eObj -- This is a hack to make it easier to support higher-rank row properties. We require to have -- determined the type of eObj "good enough" for us to find if it has the required property or -- not. Otherwise we must assume the property is a monotype. let propTypeIfMono = do traceLog $ text "Failed to find prop: " <+> pretty propName <+> text " in type: " <+> pretty tObj rowTail <- TRowEnd . Just . RowTVar <$> freshFlex propTypeScheme <- schemeEmpty . Fix . TBody . TVar <$> freshFlex unify a (Fix . TRow Nothing $ TRowProp (TPropGetName propName) propTypeScheme rowTail) (qualType tObj) instantiate propTypeScheme propTypefromTRow tRowList = case Map.lookup (TPropGetName propName) . fst $ flattenRow tRowList of Just knownPropTypeScheme -> instantiate knownPropTypeScheme Nothing -> propTypeIfMono rowType <- case unFix (qualType tObj) of TRow _ tRowList -> return $ Just tRowList _ -> tryMakeRow $ unFix (qualType tObj) propType <- case rowType of Just tRowList -> propTypefromTRow tRowList _ -> propTypeIfMono return (propType, EProp (a,propType) eObj' propName) createEnv :: Map EVarName TypeScheme -> Infer (Map EVarName VarId) createEnv builtins = foldM addVarScheme' Map.empty $ Map.toList builtins where allTVars :: TypeScheme -> Set TVarName allTVars (TScheme qvars t) = freeTypeVars t `Set.union` Set.fromList qvars addVarScheme' :: Map EVarName VarId -> (EVarName, TypeScheme) -> Infer (Map EVarName VarId) addVarScheme' m (name, tscheme) = do allocNames <- forM (Set.toList $ allTVars tscheme) $ \tvName -> (tvName,) <$> freshFlex addVarScheme m name $ mapVarNames (safeLookup allocNames) tscheme typeInference :: Map EVarName TypeScheme -> Exp Source -> Infer (Exp (Source, QualType)) typeInference builtins e = do env <- createEnv builtins (_t, e') <- inferType env e return e' ---------------------------------------------------------------------- -- -- | Mutable variable being assigned incompatible types: -- -- >>> let p = emptySource -- >>> let fun args = EAbs p ("this":args) -- >>> let var = EVar p -- >>> let let' = ELet p -- >>> let tuple = ETuple p -- >>> let lit = ELit p -- >>> let app a b = EApp p a [lit LitUndefined, b] -- >>> let assign = EAssign p -- >>> let array = EArray p -- -- x is known to have type forall a. a -> a, and to have been used in a context requiring bool -> bool (e.g. `x True`) -- -- we now try to assign x := \y -> 2 -- -- This should fail because it "collapses" x to be Number -> Number which is not compatible with bool -> bool -- -- >>> test $ let' "x" (fun ["z"] (var "z")) (let' "y" (tuple [app (var "x") (lit (LitNumber 2)), app (var "x") (lit (LitBoolean True))]) (assign "x" (fun ["y"] (lit (LitNumber 0))) (tuple [var "x", var "y"]))) -- ":1:1*: Error: Could not unify: Number with Boolean" -- -- The following should succeed because x is immutable and thus polymorphic: -- -- >>> test $ let' "x" (fun ["z"] (var "z")) (let' "y" (tuple [app (var "x") (lit (LitNumber 2)), app (var "x") (lit (LitBoolean True))]) (tuple [var "x", var "y"])) -- "(c.(d -> d), (Number, Boolean))" -- -- The following should fail because x is mutable and therefore a monotype: -- -- >>> test $ let' "x" (fun ["z"] (var "z")) (let' "y" (tuple [app (var "x") (lit (LitNumber 2)), app (var "x") (lit (LitBoolean True))]) (assign "x" (fun ["z1"] (var "z1")) (tuple [var "x", var "y"]))) -- ":1:1*: Error: Could not unify: Number with Boolean" -- -- The following should also succeed because "x" is only ever used like this: (x True). The second assignment to x is: x := \z1 -> False, which is specific but matches the usage. Note that x's type is collapsed to: Boolean -> Boolean. -- -- >>> test $ let' "x" (fun ["z"] (var "z")) (let' "y" (app (var "x") (lit (LitBoolean True))) (assign "x" (fun ["z1"] (lit (LitBoolean False))) (tuple [var "x", var "y"]))) -- "((Boolean -> Boolean), Boolean)" -- -- | Tests a setter for x being called with something more specific than x's original definition: -- >>> :{ -- >>> test $ let' -- >>> "x" (fun ["a"] (var "a")) -- >>> (let' "setX" -- >>> (fun ["v"] -- >>> (let' -- >>> "_" (assign "x" (var "v") (var "x")) (lit (LitBoolean False)))) -- >>> (let' -- >>> "_" (app (var "setX") (fun ["a"] (lit (LitString "a")))) -- >>> (app (var "x") (lit (LitBoolean True))))) -- >>> :} -- ":1:1*: Error: Could not unify: String with Boolean" -- -- >>> test $ tuple [lit (LitBoolean True), lit (LitNumber 2)] -- "(Boolean, Number)" -- -- >>> test $ let' "id" (fun ["x"] (var "x")) (assign "id" (fun ["y"] (var "y")) (var "id")) -- "a.(b -> b)" -- -- >>> test $ let' "id" (fun ["x"] (var "x")) (assign "id" (lit (LitBoolean True)) (var "id")) -- ":1:1*: Error: Could not unify: a.(b -> b) with Boolean" -- -- >>> test $ let' "x" (lit (LitBoolean True)) (assign "x" (lit (LitBoolean False)) (var "x")) -- "Boolean" -- -- >>> test $ let' "x" (lit (LitBoolean True)) (assign "x" (lit (LitNumber 3)) (var "x")) -- ":1:1*: Error: Could not unify: Boolean with Number" -- -- >>> test $ let' "x" (array [lit (LitBoolean True)]) (var "x") -- "[Boolean]" -- -- >>> test $ let' "x" (array [lit $ LitBoolean True, lit $ LitBoolean False]) (var "x") -- "[Boolean]" -- -- >>> test $ let' "x" (array []) (assign "x" (array []) (var "x")) -- "[a]" -- -- >>> test $ let' "x" (array [lit $ LitBoolean True, lit $ LitNumber 2]) (var "x") -- ":1:1*: Error: Could not unify: Number with Boolean" -- -- >>> test $ let' "id" (fun ["x"] (let' "y" (var "x") (var "y"))) (app (var "id") (var "id")) -- "c.(d -> d)" -- -- >>> test $ let' "id" (fun ["x"] (let' "y" (var "x") (var "y"))) (app (app (var "id") (var "id")) (lit (LitNumber 2))) -- "Number" -- -- >>> test $ let' "id" (fun ["x"] (app (var "x") (var "x"))) (var "id") -- ":1:1*: Error: Occurs check failed: a in (a -> b)" -- -- >>> test $ fun ["m"] (let' "y" (var "m") (let' "x" (app (var "y") (lit (LitBoolean True))) (var "x"))) -- "a.((Boolean -> b) -> b)" -- -- >>> test $ app (lit (LitNumber 2)) (lit (LitNumber 2)) -- ":1:1*: Error: Could not unify: Number with (Number -> a)" -- -- EAssign tests -- >>> test $ let' "x" (fun ["y"] (lit (LitNumber 0))) (assign "x" (fun ["y"] (var "y")) (var "x")) -- "a.(Number -> Number)" -- -- >>> test $ let' "x" (fun ["y"] (var "y")) (assign "x" (fun ["y"] (lit (LitNumber 0))) (var "x")) -- "a.(Number -> Number)" -- -- >>> test $ let' "x" (fun ["y"] (var "y")) (tuple [app (var "x") (lit (LitNumber 2)), app (var "x") (lit (LitBoolean True))]) -- "(Number, Boolean)" -- -- >>> test $ let' "x" (fun ["y"] (var "y")) (app (var "x") (var "x")) -- "c.(d -> d)" -- -- >>> test $ let' "x" (fun ["a"] (var "a")) (let' "getX" (fun ["v"] (var "x")) (let' "setX" (fun ["v"] (let' "_" (assign "x" (var "v") (var "x")) (lit (LitBoolean True)))) (let' "_" (app (var "setX") (fun ["a"] (lit (LitString "a")))) (var "getX")))) -- "e.(f -> d.(String -> String))" test :: Exp Source -> String test e = case runTypeInference e of Left err -> show $ pretty err Right expr -> show $ pretty $ snd . head . getAnnotations . minifyVars $ expr runTypeInference :: Exp Source -> Either TypeError (Exp (Source, QualType)) runTypeInference e = runInfer $ typeInference Builtins.builtins e
sinelaw/infernu
src/Infernu/Infer.hs
gpl-2.0
19,981
0
19
5,229
4,606
2,327
2,279
236
15
{-# LANGUAGE StandaloneDeriving, ExistentialQuantification, DeriveDataTypeable #-} {- | Module : $Header$ License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable Description : Abstract syntax for an hybridized logic. Declaration of the basic specification. Underlying Spec; Declaration of nominals and modalities, and axioms. -} module TopHybrid.AS_TopHybrid where import Common.Id import Common.AS_Annotation import Data.Typeable import ATerm.Lib import Logic.Logic import Unsafe.Coerce -- DrIFT command {-! global: GetRange !-} -- Union of the the declaration of nominals/modalities and the spec correspondent -- to the underlying logic data TH_BSPEC s = Bspec { bitems :: [TH_BASIC_ITEM], und :: s } deriving Show -- Declaration of nominals/modalities data TH_BASIC_ITEM = Simple_mod_decl [MODALITY] | Simple_nom_decl [NOMINAL] deriving Show type MODALITY = SIMPLE_ID type NOMINAL = SIMPLE_ID -- The strucuture of an hybridized sentence, where f correponds to the -- underlying logic data TH_FORMULA f = At NOMINAL (TH_FORMULA f) | Uni NOMINAL (TH_FORMULA f) | Exist NOMINAL (TH_FORMULA f) | Box MODALITY (TH_FORMULA f) | Dia MODALITY (TH_FORMULA f) | UnderLogic f | Conjunction (TH_FORMULA f) (TH_FORMULA f) | Disjunction (TH_FORMULA f) (TH_FORMULA f) | Implication (TH_FORMULA f) (TH_FORMULA f) | BiImplication (TH_FORMULA f) (TH_FORMULA f) | Here NOMINAL | Neg (TH_FORMULA f) | Par (TH_FORMULA f) | TrueA | FalseA deriving (Show, Eq, Ord) -- Existential quantification is used, in the Sentences, Spec and Signature -- because, we need to hide that these datatypes are polymorphic, or else, -- haskell will complain that their types will vary with the same logic. Which -- is forbidden in Logic class by using functional dependencies. -- An hybridized formula has the hybrid constructors; the constructors -- of the hybridized logic and the logic identifier, so that we can -- identify the underlying logic, by only looking to the sentence. data Frm_Wrap = forall l sub bs f s sm si mo sy rw pf. (Logic l sub bs f s sm si mo sy rw pf) => Frm_Wrap l (TH_FORMULA f) -- An hybridized specification has the basic specification; The declararation -- of nominals and modalities, and the axioms; data Spc_Wrap = forall l sub bs sen si smi sign mor symb raw pf. (Logic l sub bs sen si smi sign mor symb raw pf) => Spc_Wrap l (TH_BSPEC bs) [Annoted Frm_Wrap] ----- instances data Mor = Mor deriving instance Ord Mor deriving instance Eq Mor deriving instance Show Mor deriving instance Show Frm_Wrap deriving instance Show Spc_Wrap deriving instance Typeable Frm_Wrap deriving instance Typeable Spc_Wrap -- Why do we need to compare specifications ? instance Ord Spc_Wrap where compare _ _ = GT instance Eq Spc_Wrap where (==) _ _ = False ---------------- -- Who do we need to order formulas ? instance Ord Frm_Wrap where compare a b = if a == b then EQ else GT -- Need to use unsafe coerce here, as the typechecker as no way to know -- that if l == l' then type f == type f'. However, we know. instance Eq Frm_Wrap where (==) (Frm_Wrap l f) (Frm_Wrap l' f') = if (show l == (show l')) then (unsafeCoerce f == f') else False -- Why do we need range ? instance GetRange Frm_Wrap where getRange (Frm_Wrap _ f) = getRange f rangeSpan (Frm_Wrap _ f) = rangeSpan f instance GetRange Spc_Wrap where getRange (Spc_Wrap _ s _) = getRange s rangeSpan (Spc_Wrap _ s _) = rangeSpan s -- Generated by DrIFT, look but don't touch! instance GetRange s => GetRange (TH_BSPEC s) where getRange = const nullRange rangeSpan x = case x of Bspec a b -> joinRanges [rangeSpan a, rangeSpan b] instance GetRange TH_BASIC_ITEM where getRange = const nullRange rangeSpan x = case x of Simple_mod_decl a -> joinRanges [rangeSpan a] Simple_nom_decl a -> joinRanges [rangeSpan a] instance GetRange f => GetRange (TH_FORMULA f) where getRange = const nullRange rangeSpan x = case x of At a b -> joinRanges [rangeSpan a, rangeSpan b] Uni a b -> joinRanges [rangeSpan a, rangeSpan b] Exist a b -> joinRanges [rangeSpan a, rangeSpan b] Box a b -> joinRanges [rangeSpan a, rangeSpan b] Dia a b -> joinRanges [rangeSpan a, rangeSpan b] UnderLogic a -> joinRanges [rangeSpan a] Conjunction a b -> joinRanges [rangeSpan a, rangeSpan b] Disjunction a b -> joinRanges [rangeSpan a, rangeSpan b] Implication a b -> joinRanges [rangeSpan a, rangeSpan b] BiImplication a b -> joinRanges [rangeSpan a, rangeSpan b] Here a -> joinRanges [rangeSpan a] Neg a -> joinRanges [rangeSpan a] Par a -> joinRanges [rangeSpan a] TrueA -> [] FalseA -> [] instance GetRange Mor where getRange = const nullRange rangeSpan x = case x of Mor -> []
nevrenato/Hets_Fork
TopHybrid/AS_TopHybrid.hs
gpl-2.0
5,320
0
11
1,441
1,281
673
608
91
0
{-# LANGUAGE TemplateHaskell, RankNTypes, ScopedTypeVariables, FlexibleContexts #-} module RegFile(RegFile(..), RegisterIndex(..), initialRegFile, interpretRegAct) where import Control.Monad.State import Control.Lens data Register o = Pull | Push o deriving Show data RegFile o = RegFile {_alpha :: Register o, _beta :: Register o, _gamma :: Register o, _delta :: Register o} deriving Show initialRegFile :: RegFile o initialRegFile = RegFile Pull Pull Pull Pull makeLenses ''RegFile type RegisterIndexer o = Lens' (RegFile o) (Register o) data RegisterIndex = Alpha | Beta | Gamma | Delta deriving (Show, Eq) getReg :: RegisterIndex -> RegisterIndexer o getReg Alpha = alpha getReg Beta = beta getReg Gamma = gamma getReg Delta = delta interpretRegAct :: (Monad m, MonadState (e, RegFile o) m) => m o -> (o -> m a) -> RegisterIndex -> m () interpretRegAct pop push loc = do file <- get let reg = file ^. _2 . getReg loc case reg of Push o -> do push o _2 . getReg loc .= Pull Pull -> case loc of Alpha -> do top <- pop _2 . getReg loc .= Push top Beta -> do top <- pop push top _2 . getReg loc .= Push top Gamma -> do top <- pop second <- pop push top _2 . getReg loc .= Push second Delta -> do top <- pop second <- pop push second push top _2 . getReg loc .= Push second
kavigupta/N-programming-language
src/RegFile.hs
gpl-3.0
1,618
0
17
578
532
264
268
-1
-1
--16-02 Solve the n-queens problem for an arbitrary board size import Data.Maybe import System.Environment import Control.Applicative import Control.Monad import Control.Monad.Logic type Queen = (Int,Int) type Board = [Queen] queens :: MonadPlus m => Int -> m Board queens n = placeQueens n n placeQueens :: MonadPlus m => Int -> Int -> m Board placeQueens _ 0 = return mzero placeQueens size k = do queens' <- placeQueens size (k-1) col <- msum [return x | x <-[1..size]] let queen = (k,col) guard $ queen `safeOn` queens' return (queen:queens') safeOn :: Queen -> Board -> Bool safeOn q = not . any (inCheck q) inCheck :: Queen -> Queen -> Bool inCheck p1@(x1,y1) p2@(x2,y2) = x1 == x2 || y1 == y2 || p1 `isDiagonalTo` p2 isDiagonalTo :: Queen -> Queen -> Bool isDiagonalTo (x1,y1) (x2,y2) = abs (x1 - x2) == abs (y1 - y2) main :: IO () main = do size <- maybe 8 read . listToMaybe <$> getArgs printLines (queens size :: [Board]) printLines . observeAll $ (queens size :: Logic Board) where printLines :: Show a => [a] -> IO () printLines = putStrLn . unlines . fmap show
cem3394/EPI-Haskell
16-02_nQueens.hs
gpl-3.0
1,108
0
12
228
490
255
235
30
1
module Instructions where import qualified Data.Map as M import Control.Monad.State import Data.Bits import qualified Data.Char as C import qualified Data.Bits.Bitwise as B import qualified Data.ByteString.Lazy as BS import GHC.Word import qualified GHC.Int as I import Data.Binary.Put import Data.Binary.Get import Unsafe.Coerce import Data.List data Op = Byte Word8 | Char I.Int8 | UShort Word16 | Short I.Int16 | UInt Word32 | Int I.Int32 | Str String | Ref String | Label String deriving (Show) data Program = Program [Op] deriving (Show) emptyProg = Program [] data Table = Table String (State Program ()) stage1 prog = let (_, p) = runState prog emptyProg in p stage2 :: [Op] -> (M.Map String Word32) -> Word32 -> (M.Map String Word32) stage2 ((Byte b):bs) m d = stage2 bs m (d+1) stage2 ((Char b):bs) m d = stage2 bs m (d+1) stage2 ((UShort b):bs) m d = stage2 bs m (d+2) stage2 ((Short b):bs) m d = stage2 bs m (d+2) stage2 ((UInt b):bs) m d = stage2 bs m (d+4) stage2 ((Int b):bs) m d = stage2 bs m (d+4) stage2 ((Label b):bs) m d = stage2 bs (M.insert b d m) d stage2 ((Ref b):bs) m d = stage2 bs m (d+4) stage2 ((Str b):bs) m d = stage2 bs m (d+(fromIntegral $ length b)) stage2 [] m d = m stage3 :: [Op] -> (M.Map String Word32) -> [Op] stage3 ((Ref b):bs) m = (UInt (m M.! b)):(stage3 bs m) stage3 ((Label b):bs) m = stage3 bs m stage3 (b:bs) m = b:(stage3 bs m) stage3 [] m = [] stage4 ((Byte b):bs) = do putWord8 b ; stage4 bs stage4 ((Char b):bs) = do putWord8 $ unsafeCoerce b ; stage4 bs stage4 ((UShort b):bs) = do putWord16be b ; stage4 bs stage4 ((Short b):bs) = do putWord16be $ unsafeCoerce b ; stage4 bs stage4 ((UInt b):bs) = do putWord32be b ; stage4 bs stage4 ((Int b):bs) = do putWord32be $ unsafeCoerce b ; stage4 bs stage4 ((Str b):bs) = do mapM (\c -> putWord8 $ fromIntegral $ C.ord c) b ; stage4 bs stage4 [] = do flush compile prog = let (Program bs) = stage1 prog m = stage2 bs (M.fromList []) 0 reduced = stage3 bs m final = runPut $ stage4 reduced in (final, m) compileTables tables head = let check1 = foldl (\a (Table _ code) -> a + (tableChecksum $ fst $ compile code)) 0 ((Table "head" (head 0)):tables) check2 = tableChecksum $ fst $ compile $ compileFinal $ (Table "head" (head check1)):tables in compileFinal $ (Table "head" (head $ 0xb1b0afba - check2)):tables compileFinal tables = let tcomp = sortBy (\(a,_,_) (b,_,_) -> a `compare` b) $ map (\(Table name code) -> (name, code, (compile code))) tables compose ((name, _, (code, _)):ts) offs = do tableEntry name code offs let l = fromIntegral $ BS.length code compose ts (offs + l + (4 - l `mod` 4)) compose [] offs = do return () numTables = length tables pad (_, code, (compiled, _)) = do code bytes $ take (4 - (fromIntegral $ BS.length compiled) `mod` 4) (repeat 0) in do offset $ fromIntegral $ numTables compose tcomp ((fromIntegral numTables)*16+12) sequence $ map pad tcomp ops :: [Op] -> State Program () ops x = do (Program a) <- get put $ Program (a ++ x) op x = ops [x] byte x = op $ Byte x bytes x = ops $ map (\e -> Byte e) x int i = op $ Int i uint i = op $ UInt i short i = op $ Short i ushort i = op $ UShort i char i = op $ Char i ref name = op $ Ref name string s = op $ Str s label name = op $ Label name slen p = let (_, (Program e)) = runState p emptyProg in fromIntegral $ length e _offset scalarType numTables searchRange entrySelector rangeShift = do uint scalarType ushort numTables ushort searchRange ushort entrySelector ushort rangeShift offset numTables = let largest2 n = if 2^n > numTables then n else largest2 $ n+1 eSel = largest2 1 sRange = 2^eSel in _offset 0x10000 numTables (sRange*16) eSel (numTables*16 - sRange*16) _tableDef tag checkSum offset len | (length tag == 4) = do string tag uint checkSum uint offset uint len tableChecksum table = let tc = do e <- remaining if e < 4 then return 0 else do w <- getWord32be r <- tc return $ w + r in runGet tc $ table tableEntry tag table offset = _tableDef tag (tableChecksum table) offset (fromIntegral $ BS.length table) _cmapTable version nSub tables = do ushort version ushort nSub tables cmapTable tables = do let n = slen tables _cmapTable 0 n tables cmapEnc pID pSpecID offset = do ushort pID ushort pSpecID ushort offset cmapFormat format length language = do ushort format ushort length ushort language cmapFormat0 language glyphIndices | (length glyphIndices) == 262 = do cmapFormat 0 262 language bytes glyphIndices glyphDesc nContours xMin yMin xMax yMax = do ushort nContours short xMin short yMin short xMax short yMax _simpleGlyph endPts iLength instrs flags xs ys = do mapM_ ushort endPts ushort iLength instrs bytes flags bytes xs bytes ys data GlyphPoint = GPoint Word16 Word8 Int Int -- TODO: full glyph support simpleGlyph :: [Word16] -> (State Program ()) -> [Word8] -> [Word8] -> [Word8] -> (State Program ()) simpleGlyph endPts instrs flags xs ys =_simpleGlyph endPts (slen instrs) instrs flags xs ys glyph xMin yMin xMax yMax endPts instrs flags xs ys = let g = do glyphDesc (fromIntegral $ length endPts) xMin yMin xMax yMax ; simpleGlyph endPts instrs flags xs ys in if ((length endPts) == (length xs)) && ((length endPts) == (length ys) && ((length endPts) == (length flags))) then g else error "Mismatched lengths" _head version revision magic flags unitsPerEm created modified xMin yMin xMax yMax macStyle lowestRec direction iToLoc format csAdjust = do uint version -- Fixed uint revision -- Fixed uint csAdjust uint magic ushort flags ushort unitsPerEm uint 0 ; uint 0 -- longDateTime uint 0 ; uint 0 -- longDateTime short xMin short yMin short xMax short yMax ushort macStyle ushort lowestRec short direction short iToLoc short format headTable = _head 0x00010000 0 0x5f0f3cf5 _hhea version ascent descent lineGap aWidthMax minLeft minRight xMaxExtent cSlopeRise cSlopeRun cOffset r0 r1 r2 r3 mDataFormat nMetrics = do uint version -- Fixed short ascent short descent short lineGap ushort aWidthMax short minLeft short minRight short xMaxExtent short cSlopeRise short cSlopeRun short cOffset short r0 ; short r1 ; short r2 ; short r3 short mDataFormat ushort nMetrics hhea ascent descent lineGap aWidthMax minLeft minRight cSlopeRise cSlopeRun cOffset nMetrics = _hhea 0x00010000 ascent descent lineGap aWidthMax minLeft minRight 0 cSlopeRise cSlopeRun cOffset 0 0 0 0 0 nMetrics hmtxEntry advanceWidth leftSideBearing = do ushort advanceWidth short leftSideBearing hmtx entries = do entries -- sequence bearings -- TODO short version _loca entries = do mapM_ uint entries -- TODO ordering loca m = _loca $ map (\(k,v) -> v) (M.toList m) _maxp version numGlyphs maxPoints maxContours maxComponentPoints maxComponentContours maxZones maxTwilightPoints maxStorage maxFunctionDefs maxInstructionDefs maxStackElements maxSizeOfInstructions maxComponentElements maxComponentDepth = do uint version -- fixed ushort numGlyphs ushort maxPoints ushort maxContours ushort maxComponentPoints ushort maxComponentContours ushort maxZones ushort maxTwilightPoints ushort maxStorage ushort maxFunctionDefs ushort maxInstructionDefs ushort maxStackElements ushort maxSizeOfInstructions ushort maxComponentElements ushort maxComponentDepth maxp numGlyphs maxPoints maxContours maxComponentPoints maxComponentContours = _maxp 0x00010000 numGlyphs maxPoints maxContours maxComponentPoints maxComponentContours _name format count strOffset nameRecords names = do ushort format ushort count ushort strOffset nameRecords names name nameRecords names count = _name 0 count (count*12+6) nameRecords names data NameRecord = NRecord Word16 Word16 Word16 Word16 String data MSNameRecord = MSNRecord NameID String data NameID = Copyright | Family | Subfamily | UUID | Fullname | Version | Postscript | Trademark deriving Enum nameRecord pID psID lID nID length offset = do ushort pID ushort psID ushort lID ushort nID ushort length ushort offset string16 s = '\00' : (intersperse '\00' s) nameHeaderMS records = nameHeader $ map (\(MSNRecord nid str) -> NRecord 3 1 0x409 (fromIntegral $ fromEnum nid) (string16 str)) records nameHeader records = let nh ((NRecord pid psid lid nid str):rs) c = (pid, psid, lid, fromIntegral $ fromEnum nid, fromIntegral (length str), c):(nh rs (c + fromIntegral(length str))) nh [] c = [] recs = nh records 0 names = map (\(NRecord _ _ _ _ s) -> s) records in name (do mapM_ (\(pid, psid, lid, nid, len, off) -> nameRecord pid psid lid nid len off) recs) (do mapM_ string names) (fromIntegral $ length records) _post format iAngle uPos uThick fixed minMemT42 maxMemT42 minMemT1 maxMemT1 = do uint format -- fixed uint iAngle -- fixed short uPos short uThick uint fixed uint minMemT42 uint maxMemT42 uint minMemT1 uint maxMemT1 post format iAngle uPos uThick fixed = _post format iAngle uPos uThick (if fixed then 1 else 0) 0 0 0 0 post3 iAngle uPos uThick fixed = post 0x00030000 iAngle uPos uThick fixed aa = byte 0x7f abs = byte 0x64 add = byte 0x60 alignpts = byte 0x27 alignrp = byte 0x3c and = byte 0x5a call = byte 0x2b ceiling = byte 0x67 cindex = byte 0x25 clear = byte 0x22 debug = byte 0x5f deltac1 = byte 0x73 deltac2 = byte 0x74 deltac3 = byte 0x75 deltap1 = byte 0x5d deltap2 = byte 0x71 deltap3 = byte 0x72 depth = byte 0x24 div = byte 0x67 dup = byte 0x20 eif = byte 0x59 elset = byte 0x1b endf = byte 0x2d eq = byte 0x54 even = byte 0x57 fdef = byte 0x2c flipoff = byte 0x4e flipon = byte 0x4d flippt = byte 0x80 fliprgoff= byte 0x82 fliprgon = byte 0x81 floor = byte 0x66 gc orig = byte $ if orig then 0x47 else 0x46 getinfo = byte 0x88 gvf = byte 0x0d gpf = byte 0x0c gt = byte 0x52 gteq = byte 0x53 idef = byte 0x89 ift = byte 0x58 instctrl = byte 0x8e ip = byte 0x39 isect = byte 0x0f iup x = byte $ if x then 0x31 else 0x30 jmpr = byte 0x1c jrof = byte 0x79 jrot = byte 0x78 lobytecall = byte 0x2a lt = byte 0x50 lteq = byte 0x51 max = byte 0x8b md orig = byte $ if orig then 0x4a else 0x49 mdap round = byte $ if round then 0x2f else 0x2e mdrp reset min round dtype = byte $ (B.fromListBE [reset, min, round, dtype]) .|. 0xc0 miap round = byte $ if round then 0x3f else 0x3e min = byte 0x8c mindex = byte 0x26 mirp reset min round dtype = byte $ (B.fromListBE [reset, min, round, dtype]) .|. 0xe0 mppem = byte 0x4b mps = byte 0x4c msirp reset = byte $ if reset then 0x3b else 0x3a nround dtype = byte $ dtype .|. 0x6f pushb n | n < 8 = byte $ n .|. 0xb0 pushbs l | (length l) < 9 = bytes $ (((fromIntegral $ length l) - 1) .|. 0xb0):l pushi l = do let f = sequence l pushb (slen f) f pushw n | n < 8 = byte $ n .|. 0xb8 pushws l | (length l) < 9 = do pushw $ fromIntegral $ (length l) - 1 mapM_ short l odd = byte 0x56 or = byte 0x5b pbyte = byte 0x21 rcvt = byte 0x45 rdtg = byte 0x7d roff = byte 0x7a roll = byte 0x8a round dtype = byte $ dtype .|. 0x68 rs = byte 0x43 rtdg = byte 0x3d rtg = byte 0x18 rthg = byte 0x19 rutg = byte 0x7c s45round = byte 0x77 sangw = byte 0x7e scanctrl = byte 0x85 scantype = byte 0x8d scfs = byte 0x48 scvtci = byte 0x1d sdb = byte 0x5e sdpvtl perp = byte $ if perp then 0x87 else 0x86 sds = byte 0x5f sfvfs = byte 0x0b sfvtca x = byte $ if x then 0x05 else 0x04 sfvtl perp = byte $ if perp then 0x09 else 0x08 sfvtpv = byte 0x0e shc rp = byte $ if rp then 0x35 else 0x34 shp rp = byte $ if rp then 0x33 else 0x32 shpix = byte 0x38 shz rp = byte $ if rp then 0x37 else 0x36 slobyte = byte 0x17 smd = byte 0x1a spvfs = byte 0x0a spvtca x = byte $ if x then 0x03 else 0x02 spvtl perp = byte $ if perp then 0x07 else 0x06 sround = byte 0x76 srp0 = byte 0x10 srp1 = byte 0x11 srp2 = byte 0x12 ssw = byte 0x1f sswci = byte 0x1e sub = byte 0x61 svtca x = byte $ if x then 0x01 else 0x00 swap = byte 0x23 szp0 = byte 0x13 szp1 = byte 0x14 szp2 = byte 0x15 szps = byte 0x16 utp = byte 0x29 wcvtf = byte 0x70 wcvtp = byte 0x44 ws = byte 0x42
jseaton/ttasm
Instructions.hs
gpl-3.0
13,000
0
19
3,453
5,408
2,655
2,753
-1
-1
{- This file is part of the Haskell Qlogic Library. The Haskell Qlogic Library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Haskell Qlogic Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the Haskell Qlogic Library. If not, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Qlogic.MiniSat where import qualified Control.Monad.State.Lazy as State import Control.Concurrent.Utils (spawn) import Control.Exception (evaluate, finally, AsyncException(..)) import Control.Monad (liftM) import Data.Time.Clock (getCurrentTime, diffUTCTime) import System.IO (hClose, hGetContents, hFlush, hPutStrLn, hPutStr, stderr) import qualified Data.IntSet as Set import qualified Data.List as List import Qlogic.SatSolver import System.Exit (ExitCode(..)) import System.Process (CreateProcess(..), createProcess, proc, readProcessWithExitCode, StdStream(..), terminateProcess, waitForProcess) type MiniSatSolver = State.StateT St IO data St = St { lastLit :: MiniSatLiteral , clauseCount :: Int , addedFormula :: String , assign :: Set.IntSet , cmd :: String , debug :: Bool} emptySt :: St emptySt = St { lastLit = 0, clauseCount = 0, addedFormula = "", assign = Set.empty, cmd = "minisat2", debug=False } type MiniSatLiteral = Int type MiniSat r = SatSolver MiniSatSolver MiniSatLiteral r instance Solver MiniSatSolver MiniSatLiteral where solve = do st <- State.get starttime <- liftIO getCurrentTime let hd = "p cnf " ++ show (clauseCount st) ++ " " ++ show (lastLit st) ++ "\n" if debug st then liftIO $ hPutStr stderr hd else return () out <- liftIO $ spawn (cmd st) ["/dev/stdin","/dev/stdout"] $ hd ++ addedFormula st if debug st then do endtime <- liftIO getCurrentTime let satlength = diffUTCTime endtime starttime liftIO $ hPutStr stderr ("Time to SAT solve: " ++ show satlength ++ "\n") else return () -- return False case (lines . snd) `liftM` out of Just ("SAT" : satassign : _) -> mapM_ add poslits >> return True where poslits = filter ((<) 0) $ [(read :: String -> Int) l | l <- words satassign] add l = State.modify (\ st -> st{assign = Set.insert l $ assign st}) Just _ -> return False Nothing -> return False where snd (_, x, _) = x run m = State.evalStateT m emptySt newLit = do st <- State.get State.put st{lastLit = lastLit st + 1} return $ lastLit st + 1 negate l = return $ l * (-1) addClause (Clause ls) = do st <- State.get State.put st{clauseCount = clauseCount st + 1, addedFormula = concat (List.intersperse " " (map show ls)) ++ (" 0 " ++ addedFormula st)} return True getModelValue l = do st <- State.get return $ Set.member l $ assign st setCmd :: String -> MiniSat () setCmd command = liftS $ State.modify (\ st -> st {cmd = command}) setDebug :: MiniSat () setDebug = liftS $ State.modify (\ st -> st {debug = True}) unsetDebug :: MiniSat () unsetDebug = liftS $ State.modify (\ st -> st {debug = False})
mzini/qlogic
Qlogic/MiniSat.hs
gpl-3.0
4,337
0
20
1,494
1,040
561
479
59
1
{-# LANGUAGE OverloadedStrings #-} module Css.Graph (graphStyles) where import Clay import Prelude hiding ((**)) import Data.Monoid import Css.Constants {- graphStyles - Generates all CSS for the graph page. -} graphStyles :: Css graphStyles = do graphContainer sidebarCSS nodeCSS pathCSS resetCSS titleCSS regionCSS {- nodeCSS - Generates CSS for nodes in the graph. -} nodeCSS :: Css nodeCSS = "g" ? do "text" ? do userSelect none "-webkit-touch-callout" -: "none" "-webkit-user-select" -: "none" "-khtml-user-select" -: "none" "-moz-user-select" -: "none" "-ms-user-select" -: "none" ".node" & do cursor pointer "text" ? do fontSize (pt nodeFontSize) faded stroke "none" "text-anchor" -: "middle" "data-active" @= "active" & do "rect" <? do wideStroke "text" <? do fullyVisible "data-active" @= "overridden" & do "rect" <? do wideStroke strokeRed "text" <? do fullyVisible "data-active" @= "inactive" & do "rect" <? do faded strokeDashed "data-active" @= "takeable" & do "rect" <? do semiVisible "text" <? do semiVisible "data-active" @= "missing" & do "rect" <> "ellipse" <? do wideStroke strokeRed "text" <? do fullyVisible "data-active" @= "unlit" & do "rect" <? faded "data-active" @= "unselected" & do "rect" <? do wideStroke faded -- For nodes in draw tab "data-group" @= "red" & do "rect" <? do fill dRed "data-group" @= "blue" & do "rect" <? do fill dBlue "data-group" @= "green" & do "rect" <? do fill dGreen "data-group" @= "purple" & do "rect" <? do fill dPurple "rect" <? do stroke "black" ".hybrid" & do cursor cursorDefault "text" <? do stroke "none" fill "white" fontSize (pt hybridFontSize) "text-anchor" -: "middle" "rect" <? do fill "#888888" stroke "black" ".bool" & do cursor cursorDefault "data-active" @= "active" & do "ellipse" <? do fill "none" stroke "black" "data-active" @= "overridden" & do "ellipse" <? do fill "white" strokeRed "data-active" @= "inactive" & do "ellipse" <? do fill lightGrey faded strokeDashed stroke "black" "data-active" @= "takeable" & do "ellipse" <? do fill lightGrey stroke "black" "data-active" @= "missing" & do "ellipse" <? do fill "white" strokeRed "data-active" @= "unlit" & do wideStroke strokeRed "text" <? do fontFamily ["Trebuchet MS", "Arial"] [sansSerif] fontWeight bold stroke "none" fontSize (pt boolFontSize) "text-anchor" -: "middle" {- pathCSS - Generates CSS for paths between nodes - in the graph. -} pathCSS :: Css pathCSS = "path" ? do fill "none" "data-active" @= "takeable" & do strokeDashed "data-active" @= "inactive" & do faded strokeDashed "data-active" @= "active" & do opacity 1 "stroke-width" -: "2px" "data-active" @= "missing" & do strokeRed strokeDashed "data-active" @= "drawn" & do faded wideStroke {- resetCSS - Generates CSS for the reset feature - in the graph. -} resetCSS :: Css resetCSS = "#resetButton" ? do fill "#990000" cursor pointer wideStroke "stroke" -: "#404040" "text" <? do fill "white" {- graphContainer - Generates CSS for the main division of - the page containing the graph. -} graphContainer :: Css graphContainer = do "#graph" ? do width (px 1195) minHeight (px 700) height (px 700) overflow hidden margin (px 10) (px 10) (px 10) (px 10) display inlineBlock position absolute textAlign $ alignSide sideCenter "left" -: "40px" "#graphRootSVG" ? do width100 height100 stroke "black" "stroke-linecap" -: "square" "stroke-miterlimit" -: "10" "shape-rendering" -: "geometricPrecision" sidebarCSS :: Css sidebarCSS = do "#fce" ? do height (px 40) width (pct 100) border solid (px 1) black "#fcecount" ? do width (pct 53) height (px 40) float floatLeft backgroundColor purple7 display none textAlign $ alignSide sideCenter paddingLeft (px 15) paddingTop (px 5) fontSize (px 18) "#reset" ? do textAlign $ alignSide sideCenter float floatLeft width (pct 47) height (px 40) display none border solid (px 1) black cursor pointer ":hover" & do backgroundColor grey1 fontColor white "#container" ? do width (pct 100) height (px 700) position relative "#sidebar" ? do display inlineBlock width (px 40) height (pct 100) float floatLeft backgroundColor purple8 position absolute paddingLeft (px 23) "#sidebar-button" ? do cursor pointer display inlineBlock width (px 40) height100 float floatLeft backgroundColor purple10 position absolute border solid (px 1) black ":hover" & do backgroundColor purple6 "#sidebar-icon" ? do width (px 30) height (px 50) paddingTop (px 20) paddingLeft (px 2) position absolute top (pct 40) left (px 4) "#focuses-nav, #graph-nav" ? do cursor pointer "#sidebar-nav" ? do width100 fontSize (px 13) backgroundColor purple6 border solid (px 1) grey2 "box-shadow" -: "0 2px 2px -1px rgba(0, 0, 0, 0.055)" display block overflow hidden ul ? do width100 margin0 li ? do "list-style-type" -: "none" display inlineBlock width (pct 48) "-webkit-transition" -: "all 0.2s" "-moz-transition" -: "all 0.2s" "-ms-transition" -: "all 0.2s" "-o-transition" -: "all 0.2s" "transition" -: "all 0.2s" ":hover" & do "background-color" -: "#5C497E !important" a ? do "color" -: "white !important" a ? do color black display inlineBlock lineHeight (px 30) alignCenter width (pct 95) textDecoration none "#focuses, #graphs" ? do marginTop (px 25) marginLeft (px 25) height100 width100 display none ".focus" ? do display block cursor pointer fontSize (px 20) border solid (px 1) black alignCenter width (pct 90) backgroundColor white "border-radius" -: "6px" ":hover" & do backgroundColor grey2 "#close-focus" ? do display block cursor pointer backgroundColor purple6 fontSize (px 20) border solid (px 1) black textAlign $ alignSide sideCenter width (pct 90) ".spotlight" & do semiVisible fill "white" stroke "none" ".details" & do border solid (px 1) black width (pct 90) height (px 0) marginBottom (px 7) overflow auto fontSize (px 14) fontColor white paddingLeft (px 5) paddingRight (px 5) ".active" & do backgroundColor purple8 ".graph-button" & do display block cursor pointer fontSize (px 20) border solid (px 1) black "border-radius" -: "6px" textAlign $ alignSide sideCenter width (pct 90) backgroundColor white marginBottom (px 20) ":hover" & do backgroundColor grey2 ".flip" & do transform $ scaleX (-1) {- titleCSS - Generates CSS for the title. -} titleCSS :: Css titleCSS = "#svgTitle" ? do fontSize $ em 2.5 fontWeight bold fontFamily ["Bitter"] [serif] fontStyle italic fill titleColour {- regionCSS - Generates CSS for focus regions in the graph. -} regionCSS :: Css regionCSS = do "#region-labels > text" ? do fontSize (pt regionFontSize) ".region" ? do "fill-opacity" -: "0.25"
arkon/courseography
hs/Css/Graph.hs
gpl-3.0
9,382
0
22
3,873
2,449
1,022
1,427
325
1
{-#LANGUAGE DeriveGeneric, StandaloneDeriving, FlexibleContexts, UndecidableInstances, FlexibleInstances, OverloadedStrings#-} module Carnap.GHCJS.SharedTypes ( GHCJSCommand(..), ProblemSource(..), ProblemType(..), ProblemData(..), DerivedRule(..) , derivedRuleToSequent, decodeRule, SomeRule(..), inspectPrems, inspectConclusion ) where import Prelude import Data.Aeson (ToJSON(..), FromJSON(..), Value(..), object, (.=), (.:), decodeStrict) import Data.Tree (Tree) import Text.Read import Data.Text (Text) import Data.ByteString (ByteString) import Text.Parsec (parse, eof) import GHC.Generics import Carnap.Core.Data.Types (FixLang, Form) import Carnap.Languages.ClassicalSequent.Syntax import Carnap.Languages.PurePropositional.Syntax import Carnap.Languages.Util.LanguageClasses import Carnap.Languages.PureFirstOrder.Syntax import Carnap.Languages.PurePropositional.Parser import Carnap.Languages.PureFirstOrder.Parser data ProblemSource = Book | Assignment String deriving (Show, Read, Eq, Generic) instance ToJSON ProblemSource instance FromJSON ProblemSource data ProblemType = Derivation | TruthTable | Translation | SyntaxCheck | CounterModel | Qualitative | SequentCalc | DeductionTree deriving (Show, Read, Eq, Generic) instance ToJSON ProblemType instance FromJSON ProblemType type TruthTable = [[Maybe Bool]] type Options = [(String,String)] type CounterModelFields = [(String,String)] data ProblemData = DerivationData Text Text | DerivationDataOpts Text Text Options | SequentCalcData Text (Tree (String,String)) Options | DeductionTreeData Text (Tree (String,String)) Options | TruthTableData Text TruthTable | TruthTableDataOpts Text TruthTable Options | TranslationData Text Text | TranslationDataOpts Text Text Options | CounterModelDataOpts Text CounterModelFields Options | QualitativeProblemDataOpts Text Text Options | ProblemContent Text deriving (Show, Read, Eq, Generic) instance ToJSON ProblemData instance FromJSON ProblemData data DerivedRule lex sem = DerivedRule { conclusion :: FixLang lex sem, premises :: [FixLang lex sem] } deriving instance Show (FixLang lex sem) => Show (DerivedRule lex sem) deriving instance Read (FixLang lex sem) => Read (DerivedRule lex sem) deriving instance Eq (FixLang lex sem) => Eq (DerivedRule lex sem) derivedRuleToSequent (DerivedRule c ps) = antecedent :|-: SS (liftToSequent c) where antecedent = foldr (:+:) Top (map (SA . liftToSequent) ps) data GHCJSCommand = Submit ProblemType String ProblemData ProblemSource Bool (Maybe Int) String | SaveRule String SomeRule | RequestDerivedRulesForUser deriving (Generic, Show) instance ToJSON GHCJSCommand instance FromJSON GHCJSCommand instance Show (FixLang lex sem) => ToJSON (DerivedRule lex sem) where toJSON (DerivedRule conclusion prems) = object [ "conclusion" .= show conclusion , "premises" .= map show prems ] instance Read (FixLang lex sem) => FromJSON (DerivedRule lex sem) where parseJSON (Object v) = do c <- v .: "conclusion" ps <- v .: "premises" let ps' = mapM toForm ps case (toForm c, ps') of (Just f, Just ps'') -> return $ DerivedRule f ps'' _ -> mempty where toForm x = readMaybe x parseJSON _ = mempty decodeRule :: ByteString -> Maybe (DerivedRule PurePropLexicon (Form Bool)) decodeRule = decodeStrict --naming convention: _Rule is assocated with _Calc data SomeRule = PropRule (DerivedRule PurePropLexicon (Form Bool)) | FOLRule (DerivedRule PureLexiconFOL (Form Bool)) deriving (Show, Read, Eq, Generic) inspectPrems (PropRule r) = map show $ premises r inspectPrems (FOLRule r) = map show $ premises r inspectConclusion (PropRule r) = show $ conclusion r inspectConclusion (FOLRule r) = show $ conclusion r instance ToJSON SomeRule instance FromJSON SomeRule
opentower/carnap
Carnap-Client/src/Carnap/GHCJS/SharedTypes.hs
gpl-3.0
4,301
0
12
1,057
1,193
651
542
88
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AdSense.Accounts.AdClients.CustomChannels.ListLinkedAdUnits -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists all the ad units available for a custom channel. -- -- /See:/ <http://code.google.com/apis/adsense/management/ AdSense Management API Reference> for @adsense.accounts.adclients.customchannels.listLinkedAdUnits@. module Network.Google.Resource.AdSense.Accounts.AdClients.CustomChannels.ListLinkedAdUnits ( -- * REST Resource AccountsAdClientsCustomChannelsListLinkedAdUnitsResource -- * Creating a Request , accountsAdClientsCustomChannelsListLinkedAdUnits , AccountsAdClientsCustomChannelsListLinkedAdUnits -- * Request Lenses , aacccllauParent , aacccllauXgafv , aacccllauUploadProtocol , aacccllauAccessToken , aacccllauUploadType , aacccllauPageToken , aacccllauPageSize , aacccllauCallback ) where import Network.Google.AdSense.Types import Network.Google.Prelude -- | A resource alias for @adsense.accounts.adclients.customchannels.listLinkedAdUnits@ method which the -- 'AccountsAdClientsCustomChannelsListLinkedAdUnits' request conforms to. type AccountsAdClientsCustomChannelsListLinkedAdUnitsResource = "v2" :> CaptureMode "parent" "listLinkedAdUnits" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListLinkedAdUnitsResponse -- | Lists all the ad units available for a custom channel. -- -- /See:/ 'accountsAdClientsCustomChannelsListLinkedAdUnits' smart constructor. data AccountsAdClientsCustomChannelsListLinkedAdUnits = AccountsAdClientsCustomChannelsListLinkedAdUnits' { _aacccllauParent :: !Text , _aacccllauXgafv :: !(Maybe Xgafv) , _aacccllauUploadProtocol :: !(Maybe Text) , _aacccllauAccessToken :: !(Maybe Text) , _aacccllauUploadType :: !(Maybe Text) , _aacccllauPageToken :: !(Maybe Text) , _aacccllauPageSize :: !(Maybe (Textual Int32)) , _aacccllauCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsAdClientsCustomChannelsListLinkedAdUnits' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aacccllauParent' -- -- * 'aacccllauXgafv' -- -- * 'aacccllauUploadProtocol' -- -- * 'aacccllauAccessToken' -- -- * 'aacccllauUploadType' -- -- * 'aacccllauPageToken' -- -- * 'aacccllauPageSize' -- -- * 'aacccllauCallback' accountsAdClientsCustomChannelsListLinkedAdUnits :: Text -- ^ 'aacccllauParent' -> AccountsAdClientsCustomChannelsListLinkedAdUnits accountsAdClientsCustomChannelsListLinkedAdUnits pAacccllauParent_ = AccountsAdClientsCustomChannelsListLinkedAdUnits' { _aacccllauParent = pAacccllauParent_ , _aacccllauXgafv = Nothing , _aacccllauUploadProtocol = Nothing , _aacccllauAccessToken = Nothing , _aacccllauUploadType = Nothing , _aacccllauPageToken = Nothing , _aacccllauPageSize = Nothing , _aacccllauCallback = Nothing } -- | Required. The custom channel which owns the collection of ad units. -- Format: -- accounts\/{account}\/adclients\/{adclient}\/customchannels\/{customchannel} aacccllauParent :: Lens' AccountsAdClientsCustomChannelsListLinkedAdUnits Text aacccllauParent = lens _aacccllauParent (\ s a -> s{_aacccllauParent = a}) -- | V1 error format. aacccllauXgafv :: Lens' AccountsAdClientsCustomChannelsListLinkedAdUnits (Maybe Xgafv) aacccllauXgafv = lens _aacccllauXgafv (\ s a -> s{_aacccllauXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). aacccllauUploadProtocol :: Lens' AccountsAdClientsCustomChannelsListLinkedAdUnits (Maybe Text) aacccllauUploadProtocol = lens _aacccllauUploadProtocol (\ s a -> s{_aacccllauUploadProtocol = a}) -- | OAuth access token. aacccllauAccessToken :: Lens' AccountsAdClientsCustomChannelsListLinkedAdUnits (Maybe Text) aacccllauAccessToken = lens _aacccllauAccessToken (\ s a -> s{_aacccllauAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). aacccllauUploadType :: Lens' AccountsAdClientsCustomChannelsListLinkedAdUnits (Maybe Text) aacccllauUploadType = lens _aacccllauUploadType (\ s a -> s{_aacccllauUploadType = a}) -- | A page token, received from a previous \`ListLinkedAdUnits\` call. -- Provide this to retrieve the subsequent page. When paginating, all other -- parameters provided to \`ListLinkedAdUnits\` must match the call that -- provided the page token. aacccllauPageToken :: Lens' AccountsAdClientsCustomChannelsListLinkedAdUnits (Maybe Text) aacccllauPageToken = lens _aacccllauPageToken (\ s a -> s{_aacccllauPageToken = a}) -- | The maximum number of ad units to include in the response, used for -- paging. If unspecified, at most 10000 ad units will be returned. The -- maximum value is 10000; values above 10000 will be coerced to 10000. aacccllauPageSize :: Lens' AccountsAdClientsCustomChannelsListLinkedAdUnits (Maybe Int32) aacccllauPageSize = lens _aacccllauPageSize (\ s a -> s{_aacccllauPageSize = a}) . mapping _Coerce -- | JSONP aacccllauCallback :: Lens' AccountsAdClientsCustomChannelsListLinkedAdUnits (Maybe Text) aacccllauCallback = lens _aacccllauCallback (\ s a -> s{_aacccllauCallback = a}) instance GoogleRequest AccountsAdClientsCustomChannelsListLinkedAdUnits where type Rs AccountsAdClientsCustomChannelsListLinkedAdUnits = ListLinkedAdUnitsResponse type Scopes AccountsAdClientsCustomChannelsListLinkedAdUnits = '["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"] requestClient AccountsAdClientsCustomChannelsListLinkedAdUnits'{..} = go _aacccllauParent _aacccllauXgafv _aacccllauUploadProtocol _aacccllauAccessToken _aacccllauUploadType _aacccllauPageToken _aacccllauPageSize _aacccllauCallback (Just AltJSON) adSenseService where go = buildClient (Proxy :: Proxy AccountsAdClientsCustomChannelsListLinkedAdUnitsResource) mempty
brendanhay/gogol
gogol-adsense/gen/Network/Google/Resource/AdSense/Accounts/AdClients/CustomChannels/ListLinkedAdUnits.hs
mpl-2.0
7,446
0
17
1,540
887
516
371
138
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AppEngine.Apps.Locations.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Get information about a location. -- -- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ Google App Engine Admin API Reference> for @appengine.apps.locations.get@. module Network.Google.Resource.AppEngine.Apps.Locations.Get ( -- * REST Resource AppsLocationsGetResource -- * Creating a Request , appsLocationsGet , AppsLocationsGet -- * Request Lenses , algXgafv , algUploadProtocol , algPp , algAccessToken , algUploadType , algBearerToken , algAppsId , algLocationsId , algCallback ) where import Network.Google.AppEngine.Types import Network.Google.Prelude -- | A resource alias for @appengine.apps.locations.get@ method which the -- 'AppsLocationsGet' request conforms to. type AppsLocationsGetResource = "v1" :> "apps" :> Capture "appsId" Text :> "locations" :> Capture "locationsId" Text :> QueryParam "$.xgafv" Text :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Location -- | Get information about a location. -- -- /See:/ 'appsLocationsGet' smart constructor. data AppsLocationsGet = AppsLocationsGet' { _algXgafv :: !(Maybe Text) , _algUploadProtocol :: !(Maybe Text) , _algPp :: !Bool , _algAccessToken :: !(Maybe Text) , _algUploadType :: !(Maybe Text) , _algBearerToken :: !(Maybe Text) , _algAppsId :: !Text , _algLocationsId :: !Text , _algCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AppsLocationsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'algXgafv' -- -- * 'algUploadProtocol' -- -- * 'algPp' -- -- * 'algAccessToken' -- -- * 'algUploadType' -- -- * 'algBearerToken' -- -- * 'algAppsId' -- -- * 'algLocationsId' -- -- * 'algCallback' appsLocationsGet :: Text -- ^ 'algAppsId' -> Text -- ^ 'algLocationsId' -> AppsLocationsGet appsLocationsGet pAlgAppsId_ pAlgLocationsId_ = AppsLocationsGet' { _algXgafv = Nothing , _algUploadProtocol = Nothing , _algPp = True , _algAccessToken = Nothing , _algUploadType = Nothing , _algBearerToken = Nothing , _algAppsId = pAlgAppsId_ , _algLocationsId = pAlgLocationsId_ , _algCallback = Nothing } -- | V1 error format. algXgafv :: Lens' AppsLocationsGet (Maybe Text) algXgafv = lens _algXgafv (\ s a -> s{_algXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). algUploadProtocol :: Lens' AppsLocationsGet (Maybe Text) algUploadProtocol = lens _algUploadProtocol (\ s a -> s{_algUploadProtocol = a}) -- | Pretty-print response. algPp :: Lens' AppsLocationsGet Bool algPp = lens _algPp (\ s a -> s{_algPp = a}) -- | OAuth access token. algAccessToken :: Lens' AppsLocationsGet (Maybe Text) algAccessToken = lens _algAccessToken (\ s a -> s{_algAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). algUploadType :: Lens' AppsLocationsGet (Maybe Text) algUploadType = lens _algUploadType (\ s a -> s{_algUploadType = a}) -- | OAuth bearer token. algBearerToken :: Lens' AppsLocationsGet (Maybe Text) algBearerToken = lens _algBearerToken (\ s a -> s{_algBearerToken = a}) -- | Part of \`name\`. Resource name for the location. algAppsId :: Lens' AppsLocationsGet Text algAppsId = lens _algAppsId (\ s a -> s{_algAppsId = a}) -- | Part of \`name\`. See documentation of \`appsId\`. algLocationsId :: Lens' AppsLocationsGet Text algLocationsId = lens _algLocationsId (\ s a -> s{_algLocationsId = a}) -- | JSONP algCallback :: Lens' AppsLocationsGet (Maybe Text) algCallback = lens _algCallback (\ s a -> s{_algCallback = a}) instance GoogleRequest AppsLocationsGet where type Rs AppsLocationsGet = Location type Scopes AppsLocationsGet = '["https://www.googleapis.com/auth/appengine.admin", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only"] requestClient AppsLocationsGet'{..} = go _algAppsId _algLocationsId _algXgafv _algUploadProtocol (Just _algPp) _algAccessToken _algUploadType _algBearerToken _algCallback (Just AltJSON) appEngineService where go = buildClient (Proxy :: Proxy AppsLocationsGetResource) mempty
rueshyna/gogol
gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/Locations/Get.hs
mpl-2.0
5,779
0
20
1,482
938
544
394
136
1
{-# LANGUAGE ApplicativeDo #-} module Strings where import Control.Applicative import Control.Monad import Parsers import LexicalStructure import {-# SOURCE #-} Expressions stringTemplateP :: Parser String stringTemplateP = do charP '"' e <- option0 [] $ some stringTemplateElementP reservedLP [ '"' ] return $ '"' : join e ++ [ '"' ] -- stringTemplateElementP :: Parser String stringTemplateElementP = longTemplateP <|> shortTemplateEmtryStartP <|> escapeSequenceP <|> regularStringPartP -- longTemplateP :: Parser String longTemplateP = do stringP "${" e <- expressionP newLines0P charP '}' return $ "${" ++ e ++ "}" --
ice1000/Kt2Dart
src/Strings.hs
agpl-3.0
652
0
10
118
171
86
85
25
1
module ObjD.Link.Option ( nonOpt, nullDot, linkOptionCall, linkOptionAlt, optChecking, compareWithNil, compareOptions, compareOptionWithNonOption, linkNullDot )where import ObjD.Link.Struct import ObjD.Link.Env import ObjD.Link.DataType import ObjD.Link.Conversion import ObjD.Link.Call import Ex.String import qualified ObjD.Struct as D nonOpt :: Env -> Bool -> Exp -> Exp nonOpt _ False e = NonOpt False e e nonOpt env True e = let tp = exprDataType e tp' = unoptionHard $ tp rt w = If (BoolOp Eq w (None tp')) NPE w val = tmpVal env "n" tp e in NonOpt True e $ if isElementaryExpression e then rt e else Braces [Val False val, rt (callRef val)] nullDot :: Env -> Exp -> Exp -> Exp nullDot env l r = let ltp = exprDataType l ltp' = unoptionHard ltp rtp = exprDataType r val = tmpVal env "u" ltp l f l' = If (BoolOp NotEq l' (None ltp')) (Some True $ Dot (nonOpt env False l') r) (None rtp) uw | isElementaryExpression l = f l | otherwise = Braces [Val False val, f (callRef val)] in NullDot l r uw linkOptionCall :: Env -> (D.Exp, Exp) -> D.Exp -> Exp linkOptionCall env (_, leftExp) (D.Call "get" Nothing []) = nonOpt env True $ leftExp linkOptionCall env (_ ,leftExp) e@(D.Call "cast" Nothing [tp]) = case tp of D.DataTypeOption{} -> Cast (dataType env tp) leftExp _ -> ExpDError ("Cast option to non-option: " ++ show tp) e linkOptionCall env (l, _) (D.Call "getOr" (Just [(_, alt)]) []) = let l' = envExprCompile env{envVarSuffix = envVarSuffix env ++ "_e1"} l tp = unoptionHard $ exprDataType l' alt'' = linkOptionAlt env alt tp in linkOrElse env (tp, False) (l, l') alt'' linkOptionCall env (l, _) (D.Call "or" (Just [(_, alt)]) []) = let l' = envExprCompile env{envVarSuffix = envVarSuffix env ++ "_e1"} l tp = unoptionHard $ exprDataType l' alt'' = linkOptionAlt env alt (option False tp) in linkOrElse env (tp, True) (l, l') alt'' linkOptionCall env (_, l') (D.Call fname (Just [(_, e)]) []) | fname == "map" || fname == "for" || fname == "flatMap" = let aTp = unoptionHard $ exprDataType l' tmp :: Def tmp = localValE mapVarName (option True aTp) l' mapVarName = case e of D.Lambda [(name, _)] _ -> name _ -> "_" mapExpr = case e of D.Lambda _ le -> le _ -> e mapExpr' = envExprCompile (envAddVals [tmp] env) mapExpr mapExpr'' = case unwrapGeneric $ exprDataType mapExpr' of TPFun{}-> case mapExpr' of Lambda{} -> mapExpr' _ -> dotCall env mapExpr' "apply" [] [callRef tmp] _ -> mapExpr' bTp = case fname of "for" -> TPVoid "map" -> exprDataType mapExpr'' "flatMap" -> unoptionHard $ exprDataType mapExpr'' in Braces [ declareVal env tmp, (case unwrapGeneric $ envTp env of TPVoid -> If (BoolOp NotEq (callRef tmp) (None aTp) ) mapExpr'' Nop _ -> If (BoolOp NotEq (callRef tmp) (None aTp) ) (implicitConvertsion env (option False bTp) mapExpr'') (None $ wrapGeneric $ bTp)) ] linkOptionCall _ _ e = ExpDError ("Unknown option operation: " ++ show e) e linkOptionAlt :: Env -> D.Exp -> DataType -> Exp linkOptionAlt env alt tp = implicitConvertsion env tp $ envExprCompile env{envVarSuffix = envVarSuffix env ++ "_e2"} alt' where alt' = case alt of (D.Lambda [] a) -> a _ -> alt linkOrElse :: Env -> (DataType, Bool) -> (D.Exp, Exp) -> Exp -> Exp linkOrElse env _ ((D.NullDot dl dr), (NullDot dl' dr' _)) alt = let l'' = Dot (nonOpt env False dl') dr' dltp = exprDataType dl' tmp = tmpVal env "" dltp dl' in if isElementaryExpression dl' then If (BoolOp NotEq dl' (None dltp) ) (envExprCompile env (D.Dot (D.Dot dl (D.Call "get" Nothing [])) dr)) alt else Braces[ declareVal env tmp, If (BoolOp NotEq (callRef tmp) (None dltp)) l'' alt ] linkOrElse env (tp, isOptionAlt) (_, l') alt = let tmp = tmpVal env "" (option False tp) $ implicitConvertsion env (option False tp) l' e r = If (BoolOp NotEq r (None tp)) ((if isOptionAlt then id else nonOpt env False) r) alt in if isElementaryExpression l' then e l' else Braces[declareVal env tmp, e (callRef tmp)] linkNullDot :: Env -> D.Exp -> Exp linkNullDot env d@(D.NullDot a b) = let aa = case a of D.Call {} -> exprCall (envAddSuffix env "l") Nothing a _ -> envExprCompileToSome (envAddSuffix env "l") a aTp = exprDataType aa bb = case aTp of TPOption _ tp -> exprCall (envAddSuffix env "r") (Just tp) b TPGenericWrap _ (TPOption _ tp) -> exprCall (envAddSuffix env "r") (Just tp) b tp -> ExpDError ("Null safe operation for the non-nullable datatype " ++ show tp) b in case aa of ExpDError s _ -> ExpDError s d _ -> case bb of Dot l r -> nullDot env (nullDot (envAddSuffix env "i") aa l) r _ -> nullDot env aa bb optChecking :: Env -> Exp -> (Env, Env) optChecking env e = rec (env, env) e where mapEnvDef en d = case unwrapGeneric $ defType d of TPOption False tp -> envChangeDefTp en d (TPOption True tp) _ -> en mapEnv en (Call d _ [] _) = mapEnvDef en d mapEnv en (Dot (Self _) (Call d _ [] _)) = mapEnvDef en d mapEnv en _ = en rec :: (Env, Env) -> Exp -> (Env, Env) rec en (BoolOp And a b) = rec (rec en a) b rec (l, r) (BoolOp Eq ee (None _)) = (l, mapEnv r ee) rec (l, r) (BoolOp NotEq ee (None _)) = (mapEnv l ee, r) rec (l, r) (BoolOp Eq (None _) ee) = (l, mapEnv r ee) rec (l, r) (BoolOp NotEq (None _) ee) = (mapEnv l ee, r) rec en _ = en compareWithNil :: Env -> BoolTp -> (Exp, DataType) -> Exp compareWithNil _ btp (e, etp) = case etp of TPOption _ tp -> BoolOp btp e (None tp) _ -> ExpLError "Non-option compares with nil" e compareOptions :: Env -> BoolTp -> (Exp, DataType) -> (Exp, DataType) -> Exp compareOptions env btp (l, ltp) (r, rtp) = let comp l' r' = case btp of Eq -> BoolOp Or (BoolOp ExactEq l' r') (BoolOp And (BoolOp And (BoolOp NotEq l' (None $ unoptionHard ltp)) (BoolOp NotEq r' (None $ unoptionHard rtp))) (BoolOp Eq l' r') ) NotEq -> BoolOp And (BoolOp ExactNotEq l' r') (BoolOp Or (BoolOp Or (BoolOp Eq l' (None $ unoptionHard ltp)) (BoolOp Eq r' (None $ unoptionHard rtp))) (BoolOp NotEq l' r') ) isSimpleL = isElementaryExpression l isSimpleR = isElementaryExpression r lval = tmpVal env "_l" ltp l rval = tmpVal env "_r" rtp r ml = Braces $ [Val False lval | not isSimpleL] ++ [Val False rval | not isSimpleR] ++ [comp (if isSimpleL then l else callRef lval) (if isSimpleR then r else callRef rval)] in if isSimpleL && isSimpleR then comp l r else ml compareOptionWithNonOption :: Env -> BoolTp -> (Exp, DataType) -> (Exp, DataType) -> Exp compareOptionWithNonOption env btp (opt, optTp) (nonopt, _) = let comp opt' nonopt' = case btp of Eq -> BoolOp And (BoolOp NotEq opt' (None $ unoptionHard optTp)) (BoolOp Eq opt' nonopt') NotEq -> BoolOp Or (BoolOp Eq opt' (None $ unoptionHard optTp)) (BoolOp NotEq opt' nonopt') isSimpleOpt = isElementaryExpression opt val = tmpVal env "" optTp opt ml = Braces [Val False val, comp (callRef val) nonopt] in if isSimpleOpt then comp opt nonopt else ml
antonzherdev/objd
src/ObjD/Link/Option.hs
lgpl-3.0
7,032
170
19
1,563
3,308
1,707
1,601
161
9
-- -- Copyright 2014, NICTA -- -- This software may be distributed and modified according to the terms of -- the BSD 2-Clause license. Note that NO WARRANTY is provided. -- See "LICENSE_BSD2.txt" for details. -- -- @TAG(NICTA_BSD) -- module Main where import CapDL.Parser import CapDL.DumpParser import CapDL.ParserUtils (emptyMaps) import CapDL.MakeModel import CapDL.PrintModel import CapDL.Model import CapDL.State import CapDL.PrintDot import CapDL.PrintXml import CapDL.PrintIsabelle import CapDL.PrintC import CapDL.Matrix import CapDL.STCC import System.Environment import System.IO import Text.ParserCombinators.Parsec import Control.Monad import Control.Monad.State import Control.Monad.Writer import Data.Word import System.Console.GetOpt import qualified Data.Map as Map import qualified Data.Set as Set data Options = Options { optOutputIsabelle :: Maybe String, optOutputXml :: Maybe String, optOutputDot :: Maybe String, optOutputHeader :: Maybe String, optOutputText :: Maybe String, optOutputAnalysis :: Maybe String } -- Default options. defaultOptions :: Options defaultOptions = Options { optOutputIsabelle = Nothing, optOutputXml = Nothing, optOutputDot = Nothing, optOutputHeader = Nothing, optOutputText = Nothing, optOutputAnalysis = Nothing } -- -- Options our program supports. -- options = [ Option ['i'] ["isabelle"] (ReqArg (\arg -> \o -> o {optOutputIsabelle = Just arg }) "FILE") "output isabelle to FILE", Option ['d'] ["dot"] (ReqArg (\arg -> \o -> o {optOutputDot = Just arg }) "FILE") "output dot to FILE", Option ['c'] ["code"] (ReqArg (\arg -> \o -> o {optOutputHeader = Just arg}) "FILE") "output C initialiser source to FILE", Option ['x'] ["xml"] (ReqArg (\arg -> \o -> o {optOutputXml = Just arg }) "FILE") "output XML to FILE", Option ['t'] ["text"] (ReqArg (\arg -> \o -> o {optOutputText = Just arg }) "FILE") "output text to FILE", Option ['a'] ["analysis"] (ReqArg (\arg o -> o {optOutputAnalysis = Just arg }) "FILE") "perform analysis and output cap leak and info flow .dot files and capDL text" ] -- -- Usage information -- usageHeader = "usage: parse-capDL [options] <input file>" -- -- The result of "getOpt" returns a list of functions that transforms -- a "Options", returning a new "Options" object with the option applied. This -- fucnction applies all these generated option functions together. -- processOpts :: [Options -> Options] -> Options processOpts [] = defaultOptions processOpts (action:actions) = action (processOpts actions) genparseFromFile :: GenParser Char s a -> s -> String -> IO (Either ParseError a) genparseFromFile p st fname = do input <- readFile fname return $ runParser p st fname input isDump :: String -> IO Bool isDump fname = do input <- openFile fname ReadMode first <- hGetLine input hClose input if first == "-- Dump " then return True else return False main = do -- Parse command line arguments. args <- getArgs let (actions, nonOpts, msgs) = getOpt RequireOrder options args when (length msgs > 0) $ error (concat msgs ++ usageInfo usageHeader options) when (length nonOpts < 1) $ error ("input file not specified\n" ++ usageInfo usageHeader options) when (length nonOpts > 1) $ error ("unrecognised arguments: " ++ unwords nonOpts ++ "\n" ++ usageInfo usageHeader options) let opt = foldr ($) defaultOptions actions -- Parse the file. let inputFile = nonOpts !! 0 dump <- isDump inputFile res <- if dump then genparseFromFile capDLDumpModule emptyMaps inputFile else genparseFromFile capDLModule emptyMaps inputFile -- Get the parse result (or show an error if it failed). res <- case res of Left e -> error (show e) Right t -> return t let (m, i, c) = makeModel res let (valid, log) = runWriter (checkModel m) if valid then do -- Output model in any requested format. let optActions = [(optOutputIsabelle, \f -> writeFile f $ show $ printIsabelle f m), (optOutputXml, \f -> writeFile f $ show $ printXml inputFile m), (optOutputDot, \f -> writeFile f $ show $ printDot inputFile m), (optOutputHeader, \f -> writeFile f $ show $ printC m i c), (optOutputText, \f -> writeFile f $ show $ pretty m), (optOutputAnalysis, \f -> do (leakDot, flowDot, newM) <- leakMatrix m writeFile (f ++ "-leak.dot") leakDot writeFile (f ++ "-flow.dot") flowDot writeFile (f ++ "-saturation.txt") $ show $ pretty newM)] condDoOpt (projection, action) = maybe (return ()) action (projection opt) mapM_ condDoOpt optActions else putStr $ show log
smaccm/capDL-tool
Main.hs
bsd-2-clause
5,144
0
22
1,408
1,391
744
647
108
4
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1998 \section[TyCoRep]{Type and Coercion - friends' interface} Note [The Type-related module hierarchy] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Class CoAxiom TyCon imports Class, CoAxiom TyCoRep imports Class, CoAxiom, TyCon TysPrim imports TyCoRep ( including mkTyConTy ) Kind imports TysPrim ( mainly for primitive kinds ) Type imports Kind Coercion imports Type -} -- We expose the relevant stuff from this module via the Type module {-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable, MultiWayIf #-} {-# LANGUAGE ImplicitParams #-} module TyCoRep ( TyThing(..), tyThingCategory, pprTyThingCategory, pprShortTyThing, -- * Types Type(..), TyLit(..), KindOrType, Kind, PredType, ThetaType, -- Synonyms ArgFlag(..), -- * Coercions Coercion(..), LeftOrRight(..), UnivCoProvenance(..), CoercionHole(..), CoercionN, CoercionR, CoercionP, KindCoercion, -- * Functions over types mkTyConTy, mkTyVarTy, mkTyVarTys, mkFunTy, mkFunTys, mkForAllTy, mkForAllTys, mkPiTy, mkPiTys, isLiftedTypeKind, isUnliftedTypeKind, isCoercionType, isRuntimeRepTy, isRuntimeRepVar, isRuntimeRepKindedTy, dropRuntimeRepArgs, sameVis, -- * Functions over binders TyBinder(..), TyVarBinder, binderVar, binderVars, binderKind, binderArgFlag, delBinderVar, isInvisibleArgFlag, isVisibleArgFlag, isInvisibleBinder, isVisibleBinder, -- * Functions over coercions pickLR, -- * Pretty-printing pprType, pprParendType, pprTypeApp, pprTvBndr, pprTvBndrs, pprSigmaType, pprTheta, pprForAll, pprForAllImplicit, pprUserForAll, pprThetaArrowTy, pprClassPred, pprKind, pprParendKind, pprTyLit, TyPrec(..), maybeParen, pprTcAppCo, pprTcAppTy, pprPrefixApp, pprArrowChain, ppr_type, pprDataCons, ppSuggestExplicitKinds, -- * Free variables tyCoVarsOfType, tyCoVarsOfTypeDSet, tyCoVarsOfTypes, tyCoVarsOfTypesDSet, tyCoFVsBndr, tyCoFVsOfType, tyCoVarsOfTypeList, tyCoFVsOfTypes, tyCoVarsOfTypesList, closeOverKindsDSet, closeOverKindsFV, closeOverKindsList, coVarsOfType, coVarsOfTypes, coVarsOfCo, coVarsOfCos, tyCoVarsOfCo, tyCoVarsOfCos, tyCoVarsOfCoDSet, tyCoFVsOfCo, tyCoFVsOfCos, tyCoVarsOfCoList, tyCoVarsOfProv, closeOverKinds, -- * Substitutions TCvSubst(..), TvSubstEnv, CvSubstEnv, emptyTvSubstEnv, emptyCvSubstEnv, composeTCvSubstEnv, composeTCvSubst, emptyTCvSubst, mkEmptyTCvSubst, isEmptyTCvSubst, mkTCvSubst, mkTvSubst, getTvSubstEnv, getCvSubstEnv, getTCvInScope, getTCvSubstRangeFVs, isInScope, notElemTCvSubst, setTvSubstEnv, setCvSubstEnv, zapTCvSubst, extendTCvInScope, extendTCvInScopeList, extendTCvInScopeSet, extendTCvSubst, extendCvSubst, extendCvSubstWithClone, extendTvSubst, extendTvSubstBinder, extendTvSubstWithClone, extendTvSubstList, extendTvSubstAndInScope, unionTCvSubst, zipTyEnv, zipCoEnv, mkTyCoInScopeSet, zipTvSubst, zipCvSubst, mkTvSubstPrs, substTyWith, substTyWithCoVars, substTysWith, substTysWithCoVars, substCoWith, substTy, substTyAddInScope, substTyUnchecked, substTysUnchecked, substThetaUnchecked, substTyWithUnchecked, substCoUnchecked, substCoWithUnchecked, substTyWithInScope, substTys, substTheta, lookupTyVar, substTyVarBndr, substCo, substCos, substCoVar, substCoVars, lookupCoVar, substCoVarBndr, cloneTyVarBndr, cloneTyVarBndrs, substTyVar, substTyVars, substForAllCoBndr, substTyVarBndrCallback, substForAllCoBndrCallback, substCoVarBndrCallback, -- * Tidying type related things up for printing tidyType, tidyTypes, tidyOpenType, tidyOpenTypes, tidyOpenKind, tidyTyCoVarBndr, tidyTyCoVarBndrs, tidyFreeTyCoVars, tidyOpenTyCoVar, tidyOpenTyCoVars, tidyTyVarOcc, tidyTopType, tidyKind, tidyCo, tidyCos, tidyTyVarBinder, tidyTyVarBinders ) where #include "HsVersions.h" import {-# SOURCE #-} DataCon( dataConTyCon, dataConFullSig , dataConUnivTyVarBinders, dataConExTyVarBinders , DataCon, filterEqSpec ) import {-# SOURCE #-} Type( isPredTy, isCoercionTy, mkAppTy , tyCoVarsOfTypesWellScoped , partitionInvisibles, coreView, typeKind , eqType ) -- Transitively pulls in a LOT of stuff, better to break the loop import {-# SOURCE #-} Coercion import {-# SOURCE #-} ConLike ( ConLike(..), conLikeName ) import {-# SOURCE #-} TysWiredIn ( ptrRepLiftedTy ) -- friends: import Var import VarEnv import VarSet import Name hiding ( varName ) import BasicTypes import TyCon import Class import CoAxiom import FV -- others import PrelNames import Binary import Outputable import DynFlags import StaticFlags ( opt_PprStyle_Debug ) import FastString import Pair import UniqSupply import Util import UniqFM -- libraries import qualified Data.Data as Data hiding ( TyCon ) import Data.List import Data.IORef ( IORef ) -- for CoercionHole {- %************************************************************************ %* * TyThing %* * %************************************************************************ Despite the fact that DataCon has to be imported via a hi-boot route, this module seems the right place for TyThing, because it's needed for funTyCon and all the types in TysPrim. It is also SOURCE-imported into Name.hs Note [ATyCon for classes] ~~~~~~~~~~~~~~~~~~~~~~~~~ Both classes and type constructors are represented in the type environment as ATyCon. You can tell the difference, and get to the class, with isClassTyCon :: TyCon -> Bool tyConClass_maybe :: TyCon -> Maybe Class The Class and its associated TyCon have the same Name. -} -- | A global typecheckable-thing, essentially anything that has a name. -- Not to be confused with a 'TcTyThing', which is also a typecheckable -- thing but in the *local* context. See 'TcEnv' for how to retrieve -- a 'TyThing' given a 'Name'. data TyThing = AnId Id | AConLike ConLike | ATyCon TyCon -- TyCons and classes; see Note [ATyCon for classes] | ACoAxiom (CoAxiom Branched) instance Outputable TyThing where ppr = pprShortTyThing instance NamedThing TyThing where -- Can't put this with the type getName (AnId id) = getName id -- decl, because the DataCon instance getName (ATyCon tc) = getName tc -- isn't visible there getName (ACoAxiom cc) = getName cc getName (AConLike cl) = conLikeName cl pprShortTyThing :: TyThing -> SDoc -- c.f. PprTyThing.pprTyThing, which prints all the details pprShortTyThing thing = pprTyThingCategory thing <+> quotes (ppr (getName thing)) pprTyThingCategory :: TyThing -> SDoc pprTyThingCategory = text . capitalise . tyThingCategory tyThingCategory :: TyThing -> String tyThingCategory (ATyCon tc) | isClassTyCon tc = "class" | otherwise = "type constructor" tyThingCategory (ACoAxiom _) = "coercion axiom" tyThingCategory (AnId _) = "identifier" tyThingCategory (AConLike (RealDataCon _)) = "data constructor" tyThingCategory (AConLike (PatSynCon _)) = "pattern synonym" {- ********************************************************************** * * Type * * ********************************************************************** -} -- | The key representation of types within the compiler type KindOrType = Type -- See Note [Arguments to type constructors] -- | The key type representing kinds in the compiler. type Kind = Type -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data Type -- See Note [Non-trivial definitional equality] = TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable) | AppTy -- See Note [AppTy rep] Type Type -- ^ Type application to something other than a 'TyCon'. Parameters: -- -- 1) Function: must /not/ be a 'TyConApp', -- must be another 'AppTy', or 'TyVarTy' -- -- 2) Argument type | TyConApp -- See Note [AppTy rep] TyCon [KindOrType] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms. -- Invariant: saturated applications of 'FunTyCon' must -- use 'FunTy' and saturated synonyms must use their own -- constructors. However, /unsaturated/ 'FunTyCon's -- do appear as 'TyConApp's. -- Parameters: -- -- 1) Type constructor being applied to. -- -- 2) Type arguments. Might not have enough type arguments -- here to saturate the constructor. -- Even type synonyms are not necessarily saturated; -- for example unsaturated type synonyms -- can appear as the right hand side of a type synonym. | ForAllTy {-# UNPACK #-} !TyVarBinder Type -- ^ A Π type. | FunTy Type Type -- ^ t1 -> t2 Very common, so an important special case | LitTy TyLit -- ^ Type literals are similar to type constructors. | CastTy Type KindCoercion -- ^ A kind cast. The coercion is always nominal. -- INVARIANT: The cast is never refl. -- INVARIANT: The cast is "pushed down" as far as it -- can go. See Note [Pushing down casts] | CoercionTy Coercion -- ^ Injection of a Coercion into a type -- This should only ever be used in the RHS of an AppTy, -- in the list of a TyConApp, when applying a promoted -- GADT data constructor deriving Data.Data -- NOTE: Other parts of the code assume that type literals do not contain -- types or type variables. data TyLit = NumTyLit Integer | StrTyLit FastString deriving (Eq, Ord, Data.Data) {- Note [The kind invariant] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The kinds # UnliftedTypeKind OpenKind super-kind of *, # can never appear under an arrow or type constructor in a kind; they can only be at the top level of a kind. It follows that primitive TyCons, which have a naughty pseudo-kind State# :: * -> # must always be saturated, so that we can never get a type whose kind has a UnliftedTypeKind or ArgTypeKind underneath an arrow. Nor can we abstract over a type variable with any of these kinds. k :: = kk | # | ArgKind | (#) | OpenKind kk :: = * | kk -> kk | T kk1 ... kkn So a type variable can only be abstracted kk. Note [AppTy rep] ~~~~~~~~~~~~~~~~ Types of the form 'f a' must be of kind *, not #, so we are guaranteed that they are represented by pointers. The reason is that f must have kind (kk -> kk) and kk cannot be unlifted; see Note [The kind invariant] in TyCoRep. Note [Arguments to type constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Because of kind polymorphism, in addition to type application we now have kind instantiation. We reuse the same notations to do so. For example: Just (* -> *) Maybe Right * Nat Zero are represented by: TyConApp (PromotedDataCon Just) [* -> *, Maybe] TyConApp (PromotedDataCon Right) [*, Nat, (PromotedDataCon Zero)] Important note: Nat is used as a *kind* and not as a type. This can be confusing, since type-level Nat and kind-level Nat are identical. We use the kind of (PromotedDataCon Right) to know if its arguments are kinds or types. This kind instantiation only happens in TyConApp currently. Note [Pushing down casts] ~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have (a :: k1 -> *), (b :: k1), and (co :: * ~ q). The type (a b |> co) is `eqType` to ((a |> co') b), where co' = (->) <k1> co. Thus, to make this visible to functions that inspect types, we always push down coercions, preferring the second form. Note that this also applies to TyConApps! Note [Non-trivial definitional equality] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Is Int |> <*> the same as Int? YES! In order to reduce headaches, we decide that any reflexive casts in types are just ignored. More generally, the `eqType` function, which defines Core's type equality relation, ignores casts and coercion arguments, as long as the two types have the same kind. This allows us to be a little sloppier in keeping track of coercions, which is a good thing. It also means that eqType does not depend on eqCoercion, which is also a good thing. Why is this sensible? That is, why is something different than α-equivalence appropriate for the implementation of eqType? Anything smaller than ~ and homogeneous is an appropriate definition for equality. The type safety of FC depends only on ~. Let's say η : τ ~ σ. Any expression of type τ can be transmuted to one of type σ at any point by casting. The same is true of types of type τ. So in some sense, τ and σ are interchangeable. But let's be more precise. If we examine the typing rules of FC (say, those in http://www.cis.upenn.edu/~eir/papers/2015/equalities/equalities-extended.pdf) there are several places where the same metavariable is used in two different premises to a rule. (For example, see Ty_App.) There is an implicit equality check here. What definition of equality should we use? By convention, we use α-equivalence. Take any rule with one (or more) of these implicit equality checks. Then there is an admissible rule that uses ~ instead of the implicit check, adding in casts as appropriate. The only problem here is that ~ is heterogeneous. To make the kinds work out in the admissible rule that uses ~, it is necessary to homogenize the coercions. That is, if we have η : (τ : κ1) ~ (σ : κ2), then we don't use η; we use η |> kind η, which is homogeneous. The effect of this all is that eqType, the implementation of the implicit equality check, can use any homogeneous relation that is smaller than ~, as those rules must also be admissible. What would go wrong if we insisted on the casts matching? See the beginning of Section 8 in the unpublished paper above. Theoretically, nothing at all goes wrong. But in practical terms, getting the coercions right proved to be nightmarish. And types would explode: during kind-checking, we often produce reflexive kind coercions. When we try to cast by these, mkCastTy just discards them. But if we used an eqType that distinguished between Int and Int |> <*>, then we couldn't discard -- the output of kind-checking would be enormous, and we would need enormous casts with lots of CoherenceCo's to straighten them out. Would anything go wrong if eqType respected type families? No, not at all. But that makes eqType rather hard to implement. Thus, the guideline for eqType is that it should be the largest easy-to-implement relation that is still smaller than ~ and homogeneous. The precise choice of relation is somewhat incidental, as long as the smart constructors and destructors in Type respect whatever relation is chosen. Another helpful principle with eqType is this: ** If (t1 eqType t2) then I can replace t1 by t2 anywhere. ** This principle also tells us that eqType must relate only types with the same kinds. -} {- ********************************************************************** * * TyBinder and ArgFlag * * ********************************************************************** -} -- | A 'TyBinder' represents an argument to a function. TyBinders can be dependent -- ('Named') or nondependent ('Anon'). They may also be visible or not. -- See Note [TyBinders] data TyBinder = Named TyVarBinder | Anon Type -- Visibility is determined by the type (Constraint vs. *) deriving Data.Data -- | Remove the binder's variable from the set, if the binder has -- a variable. delBinderVar :: VarSet -> TyVarBinder -> VarSet delBinderVar vars (TvBndr tv _) = vars `delVarSet` tv -- | Does this binder bind an invisible argument? isInvisibleBinder :: TyBinder -> Bool isInvisibleBinder (Named (TvBndr _ vis)) = isInvisibleArgFlag vis isInvisibleBinder (Anon ty) = isPredTy ty -- | Does this binder bind a visible argument? isVisibleBinder :: TyBinder -> Bool isVisibleBinder = not . isInvisibleBinder {- Note [TyBinders] ~~~~~~~~~~~~~~~~~~~ A ForAllTy contains a TyVarBinder. But a type can be decomposed to a telescope consisting of a [TyBinder] A TyBinder represents the type of binders -- that is, the type of an argument to a Pi-type. GHC Core currently supports two different Pi-types: * A non-dependent function, written with ->, e.g. ty1 -> ty2 represented as FunTy ty1 ty2 * A dependent compile-time-only polytype, written with forall, e.g. forall (a:*). ty represented as ForAllTy (TvBndr a v) ty Both Pi-types classify terms/types that take an argument. In other words, if `x` is either a function or a polytype, `x arg` makes sense (for an appropriate `arg`). It is thus often convenient to group Pi-types together. This is ForAllTy. The two constructors for TyBinder sort out the two different possibilities. `Named` builds a polytype, while `Anon` builds an ordinary function. (ForAllTy (Anon arg) res used to be called FunTy arg res.) Note [TyBinders and ArgFlags] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A ForAllTy contains a TyVarBinder. Each TyVarBinder is equipped with a ArgFlag, which says whether or not arguments for this binder should be visible (explicit) in source Haskell. ----------------------------------------------------------------------- Occurrences look like this TyBinder GHC displays type as in Haskell souce code ----------------------------------------------------------------------- In the type of a term Anon: f :: type -> type Arg required: f x Named Inferred: f :: forall {a}. type Arg not allowed: f Named Specified: f :: forall a. type Arg optional: f or f @Int Named Required: Illegal: See Note [No Required TyBinder in terms] In the kind of a type Anon: T :: kind -> kind Required: T * Named Inferred: T :: forall {k}. kind Arg not allowed: T Named Specified: T :: forall k. kind Arg not allowed[1]: T Named Required: T :: forall k -> kind Required: T * ------------------------------------------------------------------------ [1] In types, in the Specified case, it would make sense to allow optional kind applications, thus (T @*), but we have not yet implemented that ---- Examples of where the different visiblities come from ----- In term declarations: * Inferred. Function defn, with no signature: f1 x = x We infer f1 :: forall {a}. a -> a, with 'a' Inferred It's Inferred because it doesn't appear in any user-written signature for f1 * Specified. Function defn, with signature (implicit forall): f2 :: a -> a; f2 x = x So f2 gets the type f2 :: forall a. a->a, with 'a' Specified even though 'a' is not bound in the source code by an explicit forall * Specified. Function defn, with signature (explicit forall): f3 :: forall a. a -> a; f3 x = x So f3 gets the type f3 :: forall a. a->a, with 'a' Specified * Inferred/Specified. Function signature with inferred kind polymorphism. f4 :: a b -> Int So 'f4' gets the type f4 :: forall {k} (a:k->*) (b:k). a b -> Int Here 'k' is Inferred (it's not mentioned in the type), but 'a' and 'b' are Specified. * Specified. Function signature with explicit kind polymorphism f5 :: a (b :: k) -> Int This time 'k' is Specified, because it is mentioned explicitly, so we get f5 :: forall (k:*) (a:k->*) (b:k). a b -> Int * Similarly pattern synonyms: Inferred - from inferred types (e.g. no pattern type signature) - or from inferred kind polymorphism In type declarations: * Inferred (k) data T1 a b = MkT1 (a b) Here T1's kind is T1 :: forall {k:*}. (k->*) -> k -> * The kind variable 'k' is Inferred, since it is not mentioned Note that 'a' and 'b' correspond to /Anon/ TyBinders in T1's kind, and Anon binders don't have a visibility flag. (Or you could think of Anon having an implicit Required flag.) * Specified (k) data T2 (a::k->*) b = MkT (a b) Here T's kind is T :: forall (k:*). (k->*) -> k -> * The kind variable 'k' is Specified, since it is mentioned in the signature. * Required (k) data T k (a::k->*) b = MkT (a b) Here T's kind is T :: forall k:* -> (k->*) -> k -> * The kind is Required, since it bound in a positional way in T's declaration Every use of T must be explicitly applied to a kind * Inferred (k1), Specified (k) data T a b (c :: k) = MkT (a b) (Proxy c) Here T's kind is T :: forall {k1:*} (k:*). (k1->*) -> k1 -> k -> * So 'k' is Specified, because it appears explicitly, but 'k1' is Inferred, because it does not ---- Printing ----- We print forall types with enough syntax to tell you their visiblity flag. But this is not source Haskell, and these types may not all be parsable. Specified: a list of Specified binders is written between `forall` and `.`: const :: forall a b. a -> b -> a Inferred: with -fprint-explicit-foralls, Inferred binders are written in braces: f :: forall {k} (a:k). S k a -> Int Otherwise, they are printed like Specified binders. Required: binders are put between `forall` and `->`: T :: forall k -> * ---- Other points ----- * In classic Haskell, all named binders (that is, the type variables in a polymorphic function type f :: forall a. a -> a) have been Inferred. * Inferred variables correspond to "generalized" variables from the Visible Type Applications paper (ESOP'16). Note [No Required TyBinder in terms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't allow Required foralls for term variables, including pattern synonyms and data constructors. Why? Because then an application would need a /compulsory/ type argument (possibly without an "@"?), thus (f Int); and we don't have concrete syntax for that. We could change this decision, but Required, Named TyBinders are rare anyway. (Most are Anons.) -} {- ********************************************************************** * * PredType * * ********************************************************************** -} -- | A type of the form @p@ of kind @Constraint@ represents a value whose type is -- the Haskell predicate @p@, where a predicate is what occurs before -- the @=>@ in a Haskell type. -- -- We use 'PredType' as documentation to mark those types that we guarantee to have -- this kind. -- -- It can be expanded into its representation, but: -- -- * The type checker must treat it as opaque -- -- * The rest of the compiler treats it as transparent -- -- Consider these examples: -- -- > f :: (Eq a) => a -> Int -- > g :: (?x :: Int -> Int) => a -> Int -- > h :: (r\l) => {r} => {l::Int | r} -- -- Here the @Eq a@ and @?x :: Int -> Int@ and @r\l@ are all called \"predicates\" type PredType = Type -- | A collection of 'PredType's type ThetaType = [PredType] {- (We don't support TREX records yet, but the setup is designed to expand to allow them.) A Haskell qualified type, such as that for f,g,h above, is represented using * a FunTy for the double arrow * with a type of kind Constraint as the function argument The predicate really does turn into a real extra argument to the function. If the argument has type (p :: Constraint) then the predicate p is represented by evidence of type p. %************************************************************************ %* * Simple constructors %* * %************************************************************************ These functions are here so that they can be used by TysPrim, which in turn is imported by Type -} -- named with "Only" to prevent naive use of mkTyVarTy mkTyVarTy :: TyVar -> Type mkTyVarTy v = ASSERT2( isTyVar v, ppr v <+> dcolon <+> ppr (tyVarKind v) ) TyVarTy v mkTyVarTys :: [TyVar] -> [Type] mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy infixr 3 `mkFunTy` -- Associates to the right -- | Make an arrow type mkFunTy :: Type -> Type -> Type mkFunTy arg res = FunTy arg res -- | Make nested arrow types mkFunTys :: [Type] -> Type -> Type mkFunTys tys ty = foldr mkFunTy ty tys mkForAllTy :: TyVar -> ArgFlag -> Type -> Type mkForAllTy tv vis ty = ForAllTy (TvBndr tv vis) ty -- | Wraps foralls over the type using the provided 'TyVar's from left to right mkForAllTys :: [TyVarBinder] -> Type -> Type mkForAllTys tyvars ty = foldr ForAllTy ty tyvars mkPiTy :: TyBinder -> Type -> Type mkPiTy (Anon ty1) ty2 = FunTy ty1 ty2 mkPiTy (Named tvb) ty = ForAllTy tvb ty mkPiTys :: [TyBinder] -> Type -> Type mkPiTys tbs ty = foldr mkPiTy ty tbs -- | Does this type classify a core (unlifted) Coercion? -- At either role nominal or reprsentational -- (t1 ~# t2) or (t1 ~R# t2) isCoercionType :: Type -> Bool isCoercionType (TyConApp tc tys) | (tc `hasKey` eqPrimTyConKey) || (tc `hasKey` eqReprPrimTyConKey) , length tys == 4 = True isCoercionType _ = False -- | Create the plain type constructor type which has been applied to no type arguments at all. mkTyConTy :: TyCon -> Type mkTyConTy tycon = TyConApp tycon [] {- Some basic functions, put here to break loops eg with the pretty printer -} -- | This version considers Constraint to be distinct from *. isLiftedTypeKind :: Kind -> Bool isLiftedTypeKind ki | Just ki' <- coreView ki = isLiftedTypeKind ki' isLiftedTypeKind (TyConApp tc [TyConApp ptr_rep []]) = tc `hasKey` tYPETyConKey && ptr_rep `hasKey` ptrRepLiftedDataConKey isLiftedTypeKind _ = False isUnliftedTypeKind :: Kind -> Bool isUnliftedTypeKind ki | Just ki' <- coreView ki = isUnliftedTypeKind ki' isUnliftedTypeKind (TyConApp tc [TyConApp ptr_rep []]) | tc `hasKey` tYPETyConKey , ptr_rep `hasKey` ptrRepLiftedDataConKey = False isUnliftedTypeKind (TyConApp tc [arg]) = tc `hasKey` tYPETyConKey && isEmptyVarSet (tyCoVarsOfType arg) -- all other possibilities are unlifted isUnliftedTypeKind _ = False -- | Is this the type 'RuntimeRep'? isRuntimeRepTy :: Type -> Bool isRuntimeRepTy ty | Just ty' <- coreView ty = isRuntimeRepTy ty' isRuntimeRepTy (TyConApp tc []) = tc `hasKey` runtimeRepTyConKey isRuntimeRepTy _ = False -- | Is this a type of kind RuntimeRep? (e.g. PtrRep) isRuntimeRepKindedTy :: Type -> Bool isRuntimeRepKindedTy = isRuntimeRepTy . typeKind -- | Is a tyvar of type 'RuntimeRep'? isRuntimeRepVar :: TyVar -> Bool isRuntimeRepVar = isRuntimeRepTy . tyVarKind -- | Drops prefix of RuntimeRep constructors in 'TyConApp's. Useful for e.g. -- dropping 'PtrRep arguments of unboxed tuple TyCon applications: -- -- dropRuntimeRepArgs [ 'PtrRepLifted, 'PtrRepUnlifted -- , String, Int# ] == [String, Int#] -- dropRuntimeRepArgs :: [Type] -> [Type] dropRuntimeRepArgs = dropWhile isRuntimeRepKindedTy {- %************************************************************************ %* * Coercions %* * %************************************************************************ -} -- | A 'Coercion' is concrete evidence of the equality/convertibility -- of two types. -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data Coercion -- Each constructor has a "role signature", indicating the way roles are -- propagated through coercions. -- - P, N, and R stand for coercions of the given role -- - e stands for a coercion of a specific unknown role -- (think "role polymorphism") -- - "e" stands for an explicit role parameter indicating role e. -- - _ stands for a parameter that is not a Role or Coercion. -- These ones mirror the shape of types = -- Refl :: "e" -> _ -> e Refl Role Type -- See Note [Refl invariant] -- Invariant: applications of (Refl T) to a bunch of identity coercions -- always show up as Refl. -- For example (Refl T) (Refl a) (Refl b) shows up as (Refl (T a b)). -- Applications of (Refl T) to some coercions, at least one of -- which is NOT the identity, show up as TyConAppCo. -- (They may not be fully saturated however.) -- ConAppCo coercions (like all coercions other than Refl) -- are NEVER the identity. -- Use (Refl Representational _), not (SubCo (Refl Nominal _)) -- These ones simply lift the correspondingly-named -- Type constructors into Coercions -- TyConAppCo :: "e" -> _ -> ?? -> e -- See Note [TyConAppCo roles] | TyConAppCo Role TyCon [Coercion] -- lift TyConApp -- The TyCon is never a synonym; -- we expand synonyms eagerly -- But it can be a type function | AppCo Coercion CoercionN -- lift AppTy -- AppCo :: e -> N -> e -- See Note [Forall coercions] | ForAllCo TyVar KindCoercion Coercion -- ForAllCo :: _ -> N -> e -> e -- These are special | CoVarCo CoVar -- :: _ -> (N or R) -- result role depends on the tycon of the variable's type -- AxiomInstCo :: e -> _ -> [N] -> e | AxiomInstCo (CoAxiom Branched) BranchIndex [Coercion] -- See also [CoAxiom index] -- The coercion arguments always *precisely* saturate -- arity of (that branch of) the CoAxiom. If there are -- any left over, we use AppCo. -- See [Coercion axioms applied to coercions] | UnivCo UnivCoProvenance Role Type Type -- :: _ -> "e" -> _ -> _ -> e | SymCo Coercion -- :: e -> e | TransCo Coercion Coercion -- :: e -> e -> e -- The number coercions should match exactly the expectations -- of the CoAxiomRule (i.e., the rule is fully saturated). | AxiomRuleCo CoAxiomRule [Coercion] | NthCo Int Coercion -- Zero-indexed; decomposes (T t0 ... tn) -- :: _ -> e -> ?? (inverse of TyConAppCo, see Note [TyConAppCo roles]) -- Using NthCo on a ForAllCo gives an N coercion always -- See Note [NthCo and newtypes] | LRCo LeftOrRight CoercionN -- Decomposes (t_left t_right) -- :: _ -> N -> N | InstCo Coercion CoercionN -- :: e -> N -> e -- See Note [InstCo roles] -- Coherence applies a coercion to the left-hand type of another coercion -- See Note [Coherence] | CoherenceCo Coercion KindCoercion -- :: e -> N -> e -- Extract a kind coercion from a (heterogeneous) type coercion -- NB: all kind coercions are Nominal | KindCo Coercion -- :: e -> N | SubCo CoercionN -- Turns a ~N into a ~R -- :: N -> R deriving Data.Data type CoercionN = Coercion -- always nominal type CoercionR = Coercion -- always representational type CoercionP = Coercion -- always phantom type KindCoercion = CoercionN -- always nominal -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data LeftOrRight = CLeft | CRight deriving( Eq, Data.Data ) instance Binary LeftOrRight where put_ bh CLeft = putByte bh 0 put_ bh CRight = putByte bh 1 get bh = do { h <- getByte bh ; case h of 0 -> return CLeft _ -> return CRight } pickLR :: LeftOrRight -> (a,a) -> a pickLR CLeft (l,_) = l pickLR CRight (_,r) = r {- Note [Refl invariant] ~~~~~~~~~~~~~~~~~~~~~ Invariant 1: Coercions have the following invariant Refl is always lifted as far as possible. You might think that a consequencs is: Every identity coercions has Refl at the root But that's not quite true because of coercion variables. Consider g where g :: Int~Int Left h where h :: Maybe Int ~ Maybe Int etc. So the consequence is only true of coercions that have no coercion variables. Note [Coercion axioms applied to coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The reason coercion axioms can be applied to coercions and not just types is to allow for better optimization. There are some cases where we need to be able to "push transitivity inside" an axiom in order to expose further opportunities for optimization. For example, suppose we have C a : t[a] ~ F a g : b ~ c and we want to optimize sym (C b) ; t[g] ; C c which has the kind F b ~ F c (stopping through t[b] and t[c] along the way). We'd like to optimize this to just F g -- but how? The key is that we need to allow axioms to be instantiated by *coercions*, not just by types. Then we can (in certain cases) push transitivity inside the axiom instantiations, and then react opposite-polarity instantiations of the same axiom. In this case, e.g., we match t[g] against the LHS of (C c)'s kind, to obtain the substitution a |-> g (note this operation is sort of the dual of lifting!) and hence end up with C g : t[b] ~ F c which indeed has the same kind as t[g] ; C c. Now we have sym (C b) ; C g which can be optimized to F g. Note [CoAxiom index] ~~~~~~~~~~~~~~~~~~~~ A CoAxiom has 1 or more branches. Each branch has contains a list of the free type variables in that branch, the LHS type patterns, and the RHS type for that branch. When we apply an axiom to a list of coercions, we must choose which branch of the axiom we wish to use, as the different branches may have different numbers of free type variables. (The number of type patterns is always the same among branches, but that doesn't quite concern us here.) The Int in the AxiomInstCo constructor is the 0-indexed number of the chosen branch. Note [Forall coercions] ~~~~~~~~~~~~~~~~~~~~~~~ Constructing coercions between forall-types can be a bit tricky, because the kinds of the bound tyvars can be different. The typing rule is: kind_co : k1 ~ k2 tv1:k1 |- co : t1 ~ t2 ------------------------------------------------------------------- ForAllCo tv1 kind_co co : all tv1:k1. t1 ~ all tv1:k2. (t2[tv1 |-> tv1 |> sym kind_co]) First, the TyVar stored in a ForAllCo is really an optimisation: this field should be a Name, as its kind is redundant. Thinking of the field as a Name is helpful in understanding what a ForAllCo means. The idea is that kind_co gives the two kinds of the tyvar. See how, in the conclusion, tv1 is assigned kind k1 on the left but kind k2 on the right. Of course, a type variable can't have different kinds at the same time. So, we arbitrarily prefer the first kind when using tv1 in the inner coercion co, which shows that t1 equals t2. The last wrinkle is that we need to fix the kinds in the conclusion. In t2, tv1 is assumed to have kind k1, but it has kind k2 in the conclusion of the rule. So we do a kind-fixing substitution, replacing (tv1:k1) with (tv1:k2) |> sym kind_co. This substitution is slightly bizarre, because it mentions the same name with different kinds, but it *is* well-kinded, noting that `(tv1:k2) |> sym kind_co` has kind k1. This all really would work storing just a Name in the ForAllCo. But we can't add Names to, e.g., VarSets, and there generally is just an impedence mismatch in a bunch of places. So we use tv1. When we need tv2, we can use setTyVarKind. Note [Coherence] ~~~~~~~~~~~~~~~~ The Coherence typing rule is thus: g1 : s ~ t s : k1 g2 : k1 ~ k2 ------------------------------------ CoherenceCo g1 g2 : (s |> g2) ~ t While this looks (and is) unsymmetric, a combination of other coercion combinators can make the symmetric version. For role information, see Note [Roles and kind coercions]. Note [Predicate coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have g :: a~b How can we coerce between types ([c]~a) => [a] -> c and ([c]~b) => [b] -> c where the equality predicate *itself* differs? Answer: we simply treat (~) as an ordinary type constructor, so these types really look like ((~) [c] a) -> [a] -> c ((~) [c] b) -> [b] -> c So the coercion between the two is obviously ((~) [c] g) -> [g] -> c Another way to see this to say that we simply collapse predicates to their representation type (see Type.coreView and Type.predTypeRep). This collapse is done by mkPredCo; there is no PredCo constructor in Coercion. This is important because we need Nth to work on predicates too: Nth 1 ((~) [c] g) = g See Simplify.simplCoercionF, which generates such selections. Note [Roles] ~~~~~~~~~~~~ Roles are a solution to the GeneralizedNewtypeDeriving problem, articulated in Trac #1496. The full story is in docs/core-spec/core-spec.pdf. Also, see http://ghc.haskell.org/trac/ghc/wiki/RolesImplementation Here is one way to phrase the problem: Given: newtype Age = MkAge Int type family F x type instance F Age = Bool type instance F Int = Char This compiles down to: axAge :: Age ~ Int axF1 :: F Age ~ Bool axF2 :: F Int ~ Char Then, we can make: (sym (axF1) ; F axAge ; axF2) :: Bool ~ Char Yikes! The solution is _roles_, as articulated in "Generative Type Abstraction and Type-level Computation" (POPL 2010), available at http://www.seas.upenn.edu/~sweirich/papers/popl163af-weirich.pdf The specification for roles has evolved somewhat since that paper. For the current full details, see the documentation in docs/core-spec. Here are some highlights. We label every equality with a notion of type equivalence, of which there are three options: Nominal, Representational, and Phantom. A ground type is nominally equivalent only with itself. A newtype (which is considered a ground type in Haskell) is representationally equivalent to its representation. Anything is "phantomly" equivalent to anything else. We use "N", "R", and "P" to denote the equivalences. The axioms above would be: axAge :: Age ~R Int axF1 :: F Age ~N Bool axF2 :: F Age ~N Char Then, because transitivity applies only to coercions proving the same notion of equivalence, the above construction is impossible. However, there is still an escape hatch: we know that any two types that are nominally equivalent are representationally equivalent as well. This is what the form SubCo proves -- it "demotes" a nominal equivalence into a representational equivalence. So, it would seem the following is possible: sub (sym axF1) ; F axAge ; sub axF2 :: Bool ~R Char -- WRONG What saves us here is that the arguments to a type function F, lifted into a coercion, *must* prove nominal equivalence. So, (F axAge) is ill-formed, and we are safe. Roles are attached to parameters to TyCons. When lifting a TyCon into a coercion (through TyConAppCo), we need to ensure that the arguments to the TyCon respect their roles. For example: data T a b = MkT a (F b) If we know that a1 ~R a2, then we know (T a1 b) ~R (T a2 b). But, if we know that b1 ~R b2, we know nothing about (T a b1) and (T a b2)! This is because the type function F branches on b's *name*, not representation. So, we say that 'a' has role Representational and 'b' has role Nominal. The third role, Phantom, is for parameters not used in the type's definition. Given the following definition data Q a = MkQ Int the Phantom role allows us to say that (Q Bool) ~R (Q Char), because we can construct the coercion Bool ~P Char (using UnivCo). See the paper cited above for more examples and information. Note [TyConAppCo roles] ~~~~~~~~~~~~~~~~~~~~~~~ The TyConAppCo constructor has a role parameter, indicating the role at which the coercion proves equality. The choice of this parameter affects the required roles of the arguments of the TyConAppCo. To help explain it, assume the following definition: type instance F Int = Bool -- Axiom axF : F Int ~N Bool newtype Age = MkAge Int -- Axiom axAge : Age ~R Int data Foo a = MkFoo a -- Role on Foo's parameter is Representational TyConAppCo Nominal Foo axF : Foo (F Int) ~N Foo Bool For (TyConAppCo Nominal) all arguments must have role Nominal. Why? So that Foo Age ~N Foo Int does *not* hold. TyConAppCo Representational Foo (SubCo axF) : Foo (F Int) ~R Foo Bool TyConAppCo Representational Foo axAge : Foo Age ~R Foo Int For (TyConAppCo Representational), all arguments must have the roles corresponding to the result of tyConRoles on the TyCon. This is the whole point of having roles on the TyCon to begin with. So, we can have Foo Age ~R Foo Int, if Foo's parameter has role R. If a Representational TyConAppCo is over-saturated (which is otherwise fine), the spill-over arguments must all be at Nominal. This corresponds to the behavior for AppCo. TyConAppCo Phantom Foo (UnivCo Phantom Int Bool) : Foo Int ~P Foo Bool All arguments must have role Phantom. This one isn't strictly necessary for soundness, but this choice removes ambiguity. The rules here dictate the roles of the parameters to mkTyConAppCo (should be checked by Lint). Note [NthCo and newtypes] ~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have newtype N a = MkN Int type role N representational This yields axiom NTCo:N :: forall a. N a ~R Int We can then build co :: forall a b. N a ~R N b co = NTCo:N a ; sym (NTCo:N b) for any `a` and `b`. Because of the role annotation on N, if we use NthCo, we'll get out a representational coercion. That is: NthCo 0 co :: forall a b. a ~R b Yikes! Clearly, this is terrible. The solution is simple: forbid NthCo to be used on newtypes if the internal coercion is representational. This is not just some corner case discovered by a segfault somewhere; it was discovered in the proof of soundness of roles and described in the "Safe Coercions" paper (ICFP '14). Note [InstCo roles] ~~~~~~~~~~~~~~~~~~~ Here is (essentially) the typing rule for InstCo: g :: (forall a. t1) ~r (forall a. t2) w :: s1 ~N s2 ------------------------------- InstCo InstCo g w :: (t1 [a |-> s1]) ~r (t2 [a |-> s2]) Note that the Coercion w *must* be nominal. This is necessary because the variable a might be used in a "nominal position" (that is, a place where role inference would require a nominal role) in t1 or t2. If we allowed w to be representational, we could get bogus equalities. A more nuanced treatment might be able to relax this condition somewhat, by checking if t1 and/or t2 use their bound variables in nominal ways. If not, having w be representational is OK. %************************************************************************ %* * UnivCoProvenance %* * %************************************************************************ A UnivCo is a coercion whose proof does not directly express its role and kind (indeed for some UnivCos, like UnsafeCoerceProv, there /is/ no proof). The different kinds of UnivCo are described by UnivCoProvenance. Really each is entirely separate, but they all share the need to represent their role and kind, which is done in the UnivCo constructor. -} -- | For simplicity, we have just one UnivCo that represents a coercion from -- some type to some other type, with (in general) no restrictions on the -- type. The UnivCoProvenance specifies more exactly what the coercion really -- is and why a program should (or shouldn't!) trust the coercion. -- It is reasonable to consider each constructor of 'UnivCoProvenance' -- as a totally independent coercion form; their only commonality is -- that they don't tell you what types they coercion between. (That info -- is in the 'UnivCo' constructor of 'Coercion'. data UnivCoProvenance = UnsafeCoerceProv -- ^ From @unsafeCoerce#@. These are unsound. | PhantomProv KindCoercion -- ^ See Note [Phantom coercions]. Only in Phantom -- roled coercions | ProofIrrelProv KindCoercion -- ^ From the fact that any two coercions are -- considered equivalent. See Note [ProofIrrelProv]. -- Can be used in Nominal or Representational coercions | PluginProv String -- ^ From a plugin, which asserts that this coercion -- is sound. The string is for the use of the plugin. | HoleProv CoercionHole -- ^ See Note [Coercion holes] deriving Data.Data instance Outputable UnivCoProvenance where ppr UnsafeCoerceProv = text "(unsafeCoerce#)" ppr (PhantomProv _) = text "(phantom)" ppr (ProofIrrelProv _) = text "(proof irrel.)" ppr (PluginProv str) = parens (text "plugin" <+> brackets (text str)) ppr (HoleProv hole) = parens (text "hole" <> ppr hole) -- | A coercion to be filled in by the type-checker. See Note [Coercion holes] data CoercionHole = CoercionHole { chUnique :: Unique -- ^ used only for debugging , chCoercion :: IORef (Maybe Coercion) } instance Data.Data CoercionHole where -- don't traverse? toConstr _ = abstractConstr "CoercionHole" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "CoercionHole" instance Outputable CoercionHole where ppr (CoercionHole u _) = braces (ppr u) {- Note [Phantom coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T a = T1 | T2 Then we have T s ~R T t for any old s,t. The witness for this is (TyConAppCo T Rep co), where (co :: s ~P t) is a phantom coercion built with PhantomProv. The role of the UnivCo is always Phantom. The Coercion stored is the (nominal) kind coercion between the types kind(s) ~N kind (t) Note [Coercion holes] ~~~~~~~~~~~~~~~~~~~~~~~~ During typechecking, constraint solving for type classes works by - Generate an evidence Id, d7 :: Num a - Wrap it in a Wanted constraint, [W] d7 :: Num a - Use the evidence Id where the evidence is needed - Solve the constraint later - When solved, add an enclosing let-binding let d7 = .... in .... which actually binds d7 to the (Num a) evidence For equality constraints we use a different strategy. See Note [The equality types story] in TysPrim for background on equality constraints. - For boxed equality constraints, (t1 ~N t2) and (t1 ~R t2), it's just like type classes above. (Indeed, boxed equality constraints *are* classes.) - But for /unboxed/ equality constraints (t1 ~R# t2) and (t1 ~N# t2) we use a different plan For unboxed equalities: - Generate a CoercionHole, a mutable variable just like a unification variable - Wrap the CoercionHole in a Wanted constraint; see TcRnTypes.TcEvDest - Use the CoercionHole in a Coercion, via HoleProv - Solve the constraint later - When solved, fill in the CoercionHole by side effect, instead of doing the let-binding thing The main reason for all this is that there may be no good place to let-bind the evidence for unboxed equalities: - We emit constraints for kind coercions, to be used to cast a type's kind. These coercions then must be used in types. Because they might appear in a top-level type, there is no place to bind these (unlifted) coercions in the usual way. - A coercion for (forall a. t1) ~ forall a. t2) will look like forall a. (coercion for t1~t2) But the coercion for (t1~t2) may mention 'a', and we don't have let-bindings within coercions. We could add them, but coercion holes are easier. Other notes about HoleCo: * INVARIANT: CoercionHole and HoleProv are used only during type checking, and should never appear in Core. Just like unification variables; a Type can contain a TcTyVar, but only during type checking. If, one day, we use type-level information to separate out forms that can appear during type-checking vs forms that can appear in core proper, holes in Core will be ruled out. * The Unique carried with a coercion hole is used solely for debugging. * Coercion holes can be compared for equality only like other coercions: only by looking at the types coerced. * We don't use holes for other evidence because other evidence wants to be /shared/. But coercions are entirely erased, so there's little benefit to sharing. Note [ProofIrrelProv] ~~~~~~~~~~~~~~~~~~~~~ A ProofIrrelProv is a coercion between coercions. For example: data G a where MkG :: G Bool In core, we get G :: * -> * MkG :: forall (a :: *). (a ~ Bool) -> G a Now, consider 'MkG -- that is, MkG used in a type -- and suppose we want a proof that ('MkG co1 a1) ~ ('MkG co2 a2). This will have to be TyConAppCo Nominal MkG [co3, co4] where co3 :: co1 ~ co2 co4 :: a1 ~ a2 Note that co1 :: a1 ~ Bool co2 :: a2 ~ Bool Here, co3 = UnivCo (ProofIrrelProv co5) Nominal (CoercionTy co1) (CoercionTy co2) where co5 :: (a1 ~ Bool) ~ (a2 ~ Bool) co5 = TyConAppCo Nominal (~) [<*>, <*>, co4, <Bool>] %************************************************************************ %* * Free variables of types and coercions %* * %************************************************************************ -} {- Note [Free variables of types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The family of functions tyCoVarsOfType, tyCoVarsOfTypes etc, returns a VarSet that is closed over the types of its variables. More precisely, if S = tyCoVarsOfType( t ) and (a:k) is in S then tyCoVarsOftype( k ) is a subset of S Example: The tyCoVars of this ((a:* -> k) Int) is {a, k}. We could /not/ close over the kinds of the variable occurrences, and instead do so at call sites, but it seems that we always want to do so, so it's easiest to do it here. -} -- | Returns free variables of a type, including kind variables as -- a non-deterministic set. For type synonyms it does /not/ expand the -- synonym. tyCoVarsOfType :: Type -> TyCoVarSet -- See Note [Free variables of types] tyCoVarsOfType ty = fvVarSet $ tyCoFVsOfType ty -- | `tyVarsOfType` that returns free variables of a type in a deterministic -- set. For explanation of why using `VarSet` is not deterministic see -- Note [Deterministic FV] in FV. tyCoVarsOfTypeDSet :: Type -> DTyCoVarSet -- See Note [Free variables of types] tyCoVarsOfTypeDSet ty = fvDVarSet $ tyCoFVsOfType ty -- | `tyVarsOfType` that returns free variables of a type in deterministic -- order. For explanation of why using `VarSet` is not deterministic see -- Note [Deterministic FV] in FV. tyCoVarsOfTypeList :: Type -> [TyCoVar] -- See Note [Free variables of types] tyCoVarsOfTypeList ty = fvVarList $ tyCoFVsOfType ty -- | The worker for `tyVarsOfType` and `tyVarsOfTypeList`. -- The previous implementation used `unionVarSet` which is O(n+m) and can -- make the function quadratic. -- It's exported, so that it can be composed with -- other functions that compute free variables. -- See Note [FV naming conventions] in FV. -- -- Eta-expanded because that makes it run faster (apparently) -- See Note [FV eta expansion] in FV for explanation. tyCoFVsOfType :: Type -> FV -- See Note [Free variables of types] tyCoFVsOfType (TyVarTy v) a b c = (unitFV v `unionFV` tyCoFVsOfType (tyVarKind v)) a b c tyCoFVsOfType (TyConApp _ tys) a b c = tyCoFVsOfTypes tys a b c tyCoFVsOfType (LitTy {}) a b c = emptyFV a b c tyCoFVsOfType (AppTy fun arg) a b c = (tyCoFVsOfType fun `unionFV` tyCoFVsOfType arg) a b c tyCoFVsOfType (FunTy arg res) a b c = (tyCoFVsOfType arg `unionFV` tyCoFVsOfType res) a b c tyCoFVsOfType (ForAllTy bndr ty) a b c = tyCoFVsBndr bndr (tyCoFVsOfType ty) a b c tyCoFVsOfType (CastTy ty co) a b c = (tyCoFVsOfType ty `unionFV` tyCoFVsOfCo co) a b c tyCoFVsOfType (CoercionTy co) a b c = tyCoFVsOfCo co a b c tyCoFVsBndr :: TyVarBinder -> FV -> FV -- Free vars of (forall b. <thing with fvs>) tyCoFVsBndr (TvBndr tv _) fvs = (delFV tv fvs) `unionFV` tyCoFVsOfType (tyVarKind tv) -- | Returns free variables of types, including kind variables as -- a non-deterministic set. For type synonyms it does /not/ expand the -- synonym. tyCoVarsOfTypes :: [Type] -> TyCoVarSet -- See Note [Free variables of types] tyCoVarsOfTypes tys = fvVarSet $ tyCoFVsOfTypes tys -- | Returns free variables of types, including kind variables as -- a non-deterministic set. For type synonyms it does /not/ expand the -- synonym. tyCoVarsOfTypesSet :: TyVarEnv Type -> TyCoVarSet -- See Note [Free variables of types] tyCoVarsOfTypesSet tys = fvVarSet $ tyCoFVsOfTypes $ nonDetEltsUFM tys -- It's OK to use nonDetEltsUFM here because we immediately forget the -- ordering by returning a set -- | Returns free variables of types, including kind variables as -- a deterministic set. For type synonyms it does /not/ expand the -- synonym. tyCoVarsOfTypesDSet :: [Type] -> DTyCoVarSet -- See Note [Free variables of types] tyCoVarsOfTypesDSet tys = fvDVarSet $ tyCoFVsOfTypes tys -- | Returns free variables of types, including kind variables as -- a deterministically ordered list. For type synonyms it does /not/ expand the -- synonym. tyCoVarsOfTypesList :: [Type] -> [TyCoVar] -- See Note [Free variables of types] tyCoVarsOfTypesList tys = fvVarList $ tyCoFVsOfTypes tys tyCoFVsOfTypes :: [Type] -> FV -- See Note [Free variables of types] tyCoFVsOfTypes (ty:tys) fv_cand in_scope acc = (tyCoFVsOfType ty `unionFV` tyCoFVsOfTypes tys) fv_cand in_scope acc tyCoFVsOfTypes [] fv_cand in_scope acc = emptyFV fv_cand in_scope acc tyCoVarsOfCo :: Coercion -> TyCoVarSet -- See Note [Free variables of types] tyCoVarsOfCo co = fvVarSet $ tyCoFVsOfCo co -- | Get a deterministic set of the vars free in a coercion tyCoVarsOfCoDSet :: Coercion -> DTyCoVarSet -- See Note [Free variables of types] tyCoVarsOfCoDSet co = fvDVarSet $ tyCoFVsOfCo co tyCoVarsOfCoList :: Coercion -> [TyCoVar] -- See Note [Free variables of types] tyCoVarsOfCoList co = fvVarList $ tyCoFVsOfCo co tyCoFVsOfCo :: Coercion -> FV -- Extracts type and coercion variables from a coercion -- See Note [Free variables of types] tyCoFVsOfCo (Refl _ ty) fv_cand in_scope acc = tyCoFVsOfType ty fv_cand in_scope acc tyCoFVsOfCo (TyConAppCo _ _ cos) fv_cand in_scope acc = tyCoFVsOfCos cos fv_cand in_scope acc tyCoFVsOfCo (AppCo co arg) fv_cand in_scope acc = (tyCoFVsOfCo co `unionFV` tyCoFVsOfCo arg) fv_cand in_scope acc tyCoFVsOfCo (ForAllCo tv kind_co co) fv_cand in_scope acc = (delFV tv (tyCoFVsOfCo co) `unionFV` tyCoFVsOfCo kind_co) fv_cand in_scope acc tyCoFVsOfCo (CoVarCo v) fv_cand in_scope acc = (unitFV v `unionFV` tyCoFVsOfType (varType v)) fv_cand in_scope acc tyCoFVsOfCo (AxiomInstCo _ _ cos) fv_cand in_scope acc = tyCoFVsOfCos cos fv_cand in_scope acc tyCoFVsOfCo (UnivCo p _ t1 t2) fv_cand in_scope acc = (tyCoFVsOfProv p `unionFV` tyCoFVsOfType t1 `unionFV` tyCoFVsOfType t2) fv_cand in_scope acc tyCoFVsOfCo (SymCo co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfCo (TransCo co1 co2) fv_cand in_scope acc = (tyCoFVsOfCo co1 `unionFV` tyCoFVsOfCo co2) fv_cand in_scope acc tyCoFVsOfCo (NthCo _ co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfCo (LRCo _ co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfCo (InstCo co arg) fv_cand in_scope acc = (tyCoFVsOfCo co `unionFV` tyCoFVsOfCo arg) fv_cand in_scope acc tyCoFVsOfCo (CoherenceCo c1 c2) fv_cand in_scope acc = (tyCoFVsOfCo c1 `unionFV` tyCoFVsOfCo c2) fv_cand in_scope acc tyCoFVsOfCo (KindCo co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfCo (SubCo co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfCo (AxiomRuleCo _ cs) fv_cand in_scope acc = tyCoFVsOfCos cs fv_cand in_scope acc tyCoVarsOfProv :: UnivCoProvenance -> TyCoVarSet tyCoVarsOfProv prov = fvVarSet $ tyCoFVsOfProv prov tyCoFVsOfProv :: UnivCoProvenance -> FV tyCoFVsOfProv UnsafeCoerceProv fv_cand in_scope acc = emptyFV fv_cand in_scope acc tyCoFVsOfProv (PhantomProv co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfProv (ProofIrrelProv co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfProv (PluginProv _) fv_cand in_scope acc = emptyFV fv_cand in_scope acc tyCoFVsOfProv (HoleProv _) fv_cand in_scope acc = emptyFV fv_cand in_scope acc tyCoVarsOfCos :: [Coercion] -> TyCoVarSet tyCoVarsOfCos cos = fvVarSet $ tyCoFVsOfCos cos tyCoVarsOfCosSet :: CoVarEnv Coercion -> TyCoVarSet tyCoVarsOfCosSet cos = fvVarSet $ tyCoFVsOfCos $ nonDetEltsUFM cos -- It's OK to use nonDetEltsUFM here because we immediately forget the -- ordering by returning a set tyCoFVsOfCos :: [Coercion] -> FV tyCoFVsOfCos [] fv_cand in_scope acc = emptyFV fv_cand in_scope acc tyCoFVsOfCos (co:cos) fv_cand in_scope acc = (tyCoFVsOfCo co `unionFV` tyCoFVsOfCos cos) fv_cand in_scope acc coVarsOfType :: Type -> CoVarSet coVarsOfType (TyVarTy v) = coVarsOfType (tyVarKind v) coVarsOfType (TyConApp _ tys) = coVarsOfTypes tys coVarsOfType (LitTy {}) = emptyVarSet coVarsOfType (AppTy fun arg) = coVarsOfType fun `unionVarSet` coVarsOfType arg coVarsOfType (FunTy arg res) = coVarsOfType arg `unionVarSet` coVarsOfType res coVarsOfType (ForAllTy (TvBndr tv _) ty) = (coVarsOfType ty `delVarSet` tv) `unionVarSet` coVarsOfType (tyVarKind tv) coVarsOfType (CastTy ty co) = coVarsOfType ty `unionVarSet` coVarsOfCo co coVarsOfType (CoercionTy co) = coVarsOfCo co coVarsOfTypes :: [Type] -> TyCoVarSet coVarsOfTypes tys = mapUnionVarSet coVarsOfType tys coVarsOfCo :: Coercion -> CoVarSet -- Extract *coercion* variables only. Tiresome to repeat the code, but easy. coVarsOfCo (Refl _ ty) = coVarsOfType ty coVarsOfCo (TyConAppCo _ _ args) = coVarsOfCos args coVarsOfCo (AppCo co arg) = coVarsOfCo co `unionVarSet` coVarsOfCo arg coVarsOfCo (ForAllCo tv kind_co co) = coVarsOfCo co `delVarSet` tv `unionVarSet` coVarsOfCo kind_co coVarsOfCo (CoVarCo v) = unitVarSet v `unionVarSet` coVarsOfType (varType v) coVarsOfCo (AxiomInstCo _ _ args) = coVarsOfCos args coVarsOfCo (UnivCo p _ t1 t2) = coVarsOfProv p `unionVarSet` coVarsOfTypes [t1, t2] coVarsOfCo (SymCo co) = coVarsOfCo co coVarsOfCo (TransCo co1 co2) = coVarsOfCo co1 `unionVarSet` coVarsOfCo co2 coVarsOfCo (NthCo _ co) = coVarsOfCo co coVarsOfCo (LRCo _ co) = coVarsOfCo co coVarsOfCo (InstCo co arg) = coVarsOfCo co `unionVarSet` coVarsOfCo arg coVarsOfCo (CoherenceCo c1 c2) = coVarsOfCos [c1, c2] coVarsOfCo (KindCo co) = coVarsOfCo co coVarsOfCo (SubCo co) = coVarsOfCo co coVarsOfCo (AxiomRuleCo _ cs) = coVarsOfCos cs coVarsOfProv :: UnivCoProvenance -> CoVarSet coVarsOfProv UnsafeCoerceProv = emptyVarSet coVarsOfProv (PhantomProv co) = coVarsOfCo co coVarsOfProv (ProofIrrelProv co) = coVarsOfCo co coVarsOfProv (PluginProv _) = emptyVarSet coVarsOfProv (HoleProv _) = emptyVarSet coVarsOfCos :: [Coercion] -> CoVarSet coVarsOfCos cos = mapUnionVarSet coVarsOfCo cos -- | Add the kind variables free in the kinds of the tyvars in the given set. -- Returns a non-deterministic set. closeOverKinds :: TyVarSet -> TyVarSet closeOverKinds = fvVarSet . closeOverKindsFV . nonDetEltsUFM -- It's OK to use nonDetEltsUFM here because we immediately forget -- about the ordering by returning a set. -- | Given a list of tyvars returns a deterministic FV computation that -- returns the given tyvars with the kind variables free in the kinds of the -- given tyvars. closeOverKindsFV :: [TyVar] -> FV closeOverKindsFV tvs = mapUnionFV (tyCoFVsOfType . tyVarKind) tvs `unionFV` mkFVs tvs -- | Add the kind variables free in the kinds of the tyvars in the given set. -- Returns a deterministically ordered list. closeOverKindsList :: [TyVar] -> [TyVar] closeOverKindsList tvs = fvVarList $ closeOverKindsFV tvs -- | Add the kind variables free in the kinds of the tyvars in the given set. -- Returns a deterministic set. closeOverKindsDSet :: DTyVarSet -> DTyVarSet closeOverKindsDSet = fvDVarSet . closeOverKindsFV . dVarSetElems {- %************************************************************************ %* * Substitutions Data type defined here to avoid unnecessary mutual recursion %* * %************************************************************************ -} -- | Type & coercion substitution -- -- #tcvsubst_invariant# -- The following invariants must hold of a 'TCvSubst': -- -- 1. The in-scope set is needed /only/ to -- guide the generation of fresh uniques -- -- 2. In particular, the /kind/ of the type variables in -- the in-scope set is not relevant -- -- 3. The substitution is only applied ONCE! This is because -- in general such application will not reach a fixed point. data TCvSubst = TCvSubst InScopeSet -- The in-scope type and kind variables TvSubstEnv -- Substitutes both type and kind variables CvSubstEnv -- Substitutes coercion variables -- See Note [Apply Once] -- and Note [Extending the TvSubstEnv] -- and Note [Substituting types and coercions] -- and Note [The substitution invariant] -- | A substitution of 'Type's for 'TyVar's -- and 'Kind's for 'KindVar's type TvSubstEnv = TyVarEnv Type -- A TvSubstEnv is used both inside a TCvSubst (with the apply-once -- invariant discussed in Note [Apply Once]), and also independently -- in the middle of matching, and unification (see Types.Unify) -- So you have to look at the context to know if it's idempotent or -- apply-once or whatever -- | A substitution of 'Coercion's for 'CoVar's type CvSubstEnv = CoVarEnv Coercion {- Note [Apply Once] ~~~~~~~~~~~~~~~~~ We use TCvSubsts to instantiate things, and we might instantiate forall a b. ty \with the types [a, b], or [b, a]. So the substitution might go [a->b, b->a]. A similar situation arises in Core when we find a beta redex like (/\ a /\ b -> e) b a Then we also end up with a substitution that permutes type variables. Other variations happen to; for example [a -> (a, b)]. **************************************************** *** So a TCvSubst must be applied precisely once *** **************************************************** A TCvSubst is not idempotent, but, unlike the non-idempotent substitution we use during unifications, it must not be repeatedly applied. Note [Extending the TvSubstEnv] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See #tcvsubst_invariant# for the invariants that must hold. This invariant allows a short-cut when the subst envs are empty: if the TvSubstEnv and CvSubstEnv are empty --- i.e. (isEmptyTCvSubst subst) holds --- then (substTy subst ty) does nothing. For example, consider: (/\a. /\b:(a~Int). ...b..) Int We substitute Int for 'a'. The Unique of 'b' does not change, but nevertheless we add 'b' to the TvSubstEnv, because b's kind does change This invariant has several crucial consequences: * In substTyVarBndr, we need extend the TvSubstEnv - if the unique has changed - or if the kind has changed * In substTyVar, we do not need to consult the in-scope set; the TvSubstEnv is enough * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty Note [Substituting types and coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Types and coercions are mutually recursive, and either may have variables "belonging" to the other. Thus, every time we wish to substitute in a type, we may also need to substitute in a coercion, and vice versa. However, the constructor used to create type variables is distinct from that of coercion variables, so we carry two VarEnvs in a TCvSubst. Note that it would be possible to use the CoercionTy constructor to combine these environments, but that seems like a false economy. Note that the TvSubstEnv should *never* map a CoVar (built with the Id constructor) and the CvSubstEnv should *never* map a TyVar. Furthermore, the range of the TvSubstEnv should *never* include a type headed with CoercionTy. Note [The substitution invariant] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When calling (substTy subst ty) it should be the case that the in-scope set in the substitution is a superset of both: * The free vars of the range of the substitution * The free vars of ty minus the domain of the substitution If we want to substitute [a -> ty1, b -> ty2] I used to think it was enough to generate an in-scope set that includes fv(ty1,ty2). But that's not enough; we really should also take the free vars of the type we are substituting into! Example: (forall b. (a,b,x)) [a -> List b] Then if we use the in-scope set {b}, there is a danger we will rename the forall'd variable to 'x' by mistake, getting this: (forall x. (List b, x, x)) Breaking this invariant caused the bug from #11371. -} emptyTvSubstEnv :: TvSubstEnv emptyTvSubstEnv = emptyVarEnv emptyCvSubstEnv :: CvSubstEnv emptyCvSubstEnv = emptyVarEnv composeTCvSubstEnv :: InScopeSet -> (TvSubstEnv, CvSubstEnv) -> (TvSubstEnv, CvSubstEnv) -> (TvSubstEnv, CvSubstEnv) -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@. -- It assumes that both are idempotent. -- Typically, @env1@ is the refinement to a base substitution @env2@ composeTCvSubstEnv in_scope (tenv1, cenv1) (tenv2, cenv2) = ( tenv1 `plusVarEnv` mapVarEnv (substTy subst1) tenv2 , cenv1 `plusVarEnv` mapVarEnv (substCo subst1) cenv2 ) -- First apply env1 to the range of env2 -- Then combine the two, making sure that env1 loses if -- both bind the same variable; that's why env1 is the -- *left* argument to plusVarEnv, because the right arg wins where subst1 = TCvSubst in_scope tenv1 cenv1 -- | Composes two substitutions, applying the second one provided first, -- like in function composition. composeTCvSubst :: TCvSubst -> TCvSubst -> TCvSubst composeTCvSubst (TCvSubst is1 tenv1 cenv1) (TCvSubst is2 tenv2 cenv2) = TCvSubst is3 tenv3 cenv3 where is3 = is1 `unionInScope` is2 (tenv3, cenv3) = composeTCvSubstEnv is3 (tenv1, cenv1) (tenv2, cenv2) emptyTCvSubst :: TCvSubst emptyTCvSubst = TCvSubst emptyInScopeSet emptyTvSubstEnv emptyCvSubstEnv mkEmptyTCvSubst :: InScopeSet -> TCvSubst mkEmptyTCvSubst is = TCvSubst is emptyTvSubstEnv emptyCvSubstEnv isEmptyTCvSubst :: TCvSubst -> Bool -- See Note [Extending the TvSubstEnv] isEmptyTCvSubst (TCvSubst _ tenv cenv) = isEmptyVarEnv tenv && isEmptyVarEnv cenv mkTCvSubst :: InScopeSet -> (TvSubstEnv, CvSubstEnv) -> TCvSubst mkTCvSubst in_scope (tenv, cenv) = TCvSubst in_scope tenv cenv mkTvSubst :: InScopeSet -> TvSubstEnv -> TCvSubst -- ^ Make a TCvSubst with specified tyvar subst and empty covar subst mkTvSubst in_scope tenv = TCvSubst in_scope tenv emptyCvSubstEnv getTvSubstEnv :: TCvSubst -> TvSubstEnv getTvSubstEnv (TCvSubst _ env _) = env getCvSubstEnv :: TCvSubst -> CvSubstEnv getCvSubstEnv (TCvSubst _ _ env) = env getTCvInScope :: TCvSubst -> InScopeSet getTCvInScope (TCvSubst in_scope _ _) = in_scope -- | Returns the free variables of the types in the range of a substitution as -- a non-deterministic set. getTCvSubstRangeFVs :: TCvSubst -> VarSet getTCvSubstRangeFVs (TCvSubst _ tenv cenv) = unionVarSet tenvFVs cenvFVs where tenvFVs = tyCoVarsOfTypesSet tenv cenvFVs = tyCoVarsOfCosSet cenv isInScope :: Var -> TCvSubst -> Bool isInScope v (TCvSubst in_scope _ _) = v `elemInScopeSet` in_scope notElemTCvSubst :: Var -> TCvSubst -> Bool notElemTCvSubst v (TCvSubst _ tenv cenv) | isTyVar v = not (v `elemVarEnv` tenv) | otherwise = not (v `elemVarEnv` cenv) setTvSubstEnv :: TCvSubst -> TvSubstEnv -> TCvSubst setTvSubstEnv (TCvSubst in_scope _ cenv) tenv = TCvSubst in_scope tenv cenv setCvSubstEnv :: TCvSubst -> CvSubstEnv -> TCvSubst setCvSubstEnv (TCvSubst in_scope tenv _) cenv = TCvSubst in_scope tenv cenv zapTCvSubst :: TCvSubst -> TCvSubst zapTCvSubst (TCvSubst in_scope _ _) = TCvSubst in_scope emptyVarEnv emptyVarEnv extendTCvInScope :: TCvSubst -> Var -> TCvSubst extendTCvInScope (TCvSubst in_scope tenv cenv) var = TCvSubst (extendInScopeSet in_scope var) tenv cenv extendTCvInScopeList :: TCvSubst -> [Var] -> TCvSubst extendTCvInScopeList (TCvSubst in_scope tenv cenv) vars = TCvSubst (extendInScopeSetList in_scope vars) tenv cenv extendTCvInScopeSet :: TCvSubst -> VarSet -> TCvSubst extendTCvInScopeSet (TCvSubst in_scope tenv cenv) vars = TCvSubst (extendInScopeSetSet in_scope vars) tenv cenv extendTCvSubst :: TCvSubst -> TyCoVar -> Type -> TCvSubst extendTCvSubst subst v ty | isTyVar v = extendTvSubst subst v ty | CoercionTy co <- ty = extendCvSubst subst v co | otherwise = pprPanic "extendTCvSubst" (ppr v <+> text "|->" <+> ppr ty) extendTvSubst :: TCvSubst -> TyVar -> Type -> TCvSubst extendTvSubst (TCvSubst in_scope tenv cenv) tv ty = TCvSubst in_scope (extendVarEnv tenv tv ty) cenv extendTvSubstBinder :: TCvSubst -> TyBinder -> Type -> TCvSubst extendTvSubstBinder subst (Named bndr) ty = extendTvSubst subst (binderVar bndr) ty extendTvSubstBinder subst (Anon _) _ = subst extendTvSubstWithClone :: TCvSubst -> TyVar -> TyVar -> TCvSubst -- Adds a new tv -> tv mapping, /and/ extends the in-scope set extendTvSubstWithClone (TCvSubst in_scope tenv cenv) tv tv' = TCvSubst (extendInScopeSetSet in_scope new_in_scope) (extendVarEnv tenv tv (mkTyVarTy tv')) cenv where new_in_scope = tyCoVarsOfType (tyVarKind tv') `extendVarSet` tv' extendCvSubst :: TCvSubst -> CoVar -> Coercion -> TCvSubst extendCvSubst (TCvSubst in_scope tenv cenv) v co = TCvSubst in_scope tenv (extendVarEnv cenv v co) extendCvSubstWithClone :: TCvSubst -> CoVar -> CoVar -> TCvSubst extendCvSubstWithClone (TCvSubst in_scope tenv cenv) cv cv' = TCvSubst (extendInScopeSetSet in_scope new_in_scope) tenv (extendVarEnv cenv cv (mkCoVarCo cv')) where new_in_scope = tyCoVarsOfType (varType cv') `extendVarSet` cv' extendTvSubstAndInScope :: TCvSubst -> TyVar -> Type -> TCvSubst -- Also extends the in-scope set extendTvSubstAndInScope (TCvSubst in_scope tenv cenv) tv ty = TCvSubst (in_scope `extendInScopeSetSet` tyCoVarsOfType ty) (extendVarEnv tenv tv ty) cenv extendTvSubstList :: TCvSubst -> [Var] -> [Type] -> TCvSubst extendTvSubstList subst tvs tys = foldl2 extendTvSubst subst tvs tys unionTCvSubst :: TCvSubst -> TCvSubst -> TCvSubst -- Works when the ranges are disjoint unionTCvSubst (TCvSubst in_scope1 tenv1 cenv1) (TCvSubst in_scope2 tenv2 cenv2) = ASSERT( not (tenv1 `intersectsVarEnv` tenv2) && not (cenv1 `intersectsVarEnv` cenv2) ) TCvSubst (in_scope1 `unionInScope` in_scope2) (tenv1 `plusVarEnv` tenv2) (cenv1 `plusVarEnv` cenv2) -- mkTvSubstPrs and zipTvSubst generate the in-scope set from -- the types given; but it's just a thunk so with a bit of luck -- it'll never be evaluated -- | Generates an in-scope set from the free variables in a list of types -- and a list of coercions mkTyCoInScopeSet :: [Type] -> [Coercion] -> InScopeSet mkTyCoInScopeSet tys cos = mkInScopeSet (tyCoVarsOfTypes tys `unionVarSet` tyCoVarsOfCos cos) -- | Generates the in-scope set for the 'TCvSubst' from the types in the incoming -- environment. No CoVars, please! zipTvSubst :: [TyVar] -> [Type] -> TCvSubst zipTvSubst tvs tys | debugIsOn , not (all isTyVar tvs) || length tvs /= length tys = pprTrace "zipTvSubst" (ppr tvs $$ ppr tys) emptyTCvSubst | otherwise = mkTvSubst (mkInScopeSet (tyCoVarsOfTypes tys)) tenv where tenv = zipTyEnv tvs tys -- | Generates the in-scope set for the 'TCvSubst' from the types in the incoming -- environment. No TyVars, please! zipCvSubst :: [CoVar] -> [Coercion] -> TCvSubst zipCvSubst cvs cos | debugIsOn , not (all isCoVar cvs) || length cvs /= length cos = pprTrace "zipCvSubst" (ppr cvs $$ ppr cos) emptyTCvSubst | otherwise = TCvSubst (mkInScopeSet (tyCoVarsOfCos cos)) emptyTvSubstEnv cenv where cenv = zipCoEnv cvs cos -- | Generates the in-scope set for the 'TCvSubst' from the types in the -- incoming environment. No CoVars, please! mkTvSubstPrs :: [(TyVar, Type)] -> TCvSubst mkTvSubstPrs prs = ASSERT2( onlyTyVarsAndNoCoercionTy, text "prs" <+> ppr prs ) mkTvSubst in_scope tenv where tenv = mkVarEnv prs in_scope = mkInScopeSet $ tyCoVarsOfTypes $ map snd prs onlyTyVarsAndNoCoercionTy = and [ isTyVar tv && not (isCoercionTy ty) | (tv, ty) <- prs ] zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv zipTyEnv tyvars tys = ASSERT( all (not . isCoercionTy) tys ) mkVarEnv (zipEqual "zipTyEnv" tyvars tys) -- There used to be a special case for when -- ty == TyVarTy tv -- (a not-uncommon case) in which case the substitution was dropped. -- But the type-tidier changes the print-name of a type variable without -- changing the unique, and that led to a bug. Why? Pre-tidying, we had -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype. -- And it happened that t was the type variable of the class. Post-tiding, -- it got turned into {Foo t2}. The ext-core printer expanded this using -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique, -- and so generated a rep type mentioning t not t2. -- -- Simplest fix is to nuke the "optimisation" zipCoEnv :: [CoVar] -> [Coercion] -> CvSubstEnv zipCoEnv cvs cos = mkVarEnv (zipEqual "zipCoEnv" cvs cos) instance Outputable TCvSubst where ppr (TCvSubst ins tenv cenv) = brackets $ sep[ text "TCvSubst", nest 2 (text "In scope:" <+> ppr ins), nest 2 (text "Type env:" <+> ppr tenv), nest 2 (text "Co env:" <+> ppr cenv) ] {- %************************************************************************ %* * Performing type or kind substitutions %* * %************************************************************************ Note [Sym and ForAllCo] ~~~~~~~~~~~~~~~~~~~~~~~ In OptCoercion, we try to push "sym" out to the leaves of a coercion. But, how do we push sym into a ForAllCo? It's a little ugly. Here is the typing rule: h : k1 ~# k2 (tv : k1) |- g : ty1 ~# ty2 ---------------------------- ForAllCo tv h g : (ForAllTy (tv : k1) ty1) ~# (ForAllTy (tv : k2) (ty2[tv |-> tv |> sym h])) Here is what we want: ForAllCo tv h' g' : (ForAllTy (tv : k2) (ty2[tv |-> tv |> sym h])) ~# (ForAllTy (tv : k1) ty1) Because the kinds of the type variables to the right of the colon are the kinds coerced by h', we know (h' : k2 ~# k1). Thus, (h' = sym h). Now, we can rewrite ty1 to be (ty1[tv |-> tv |> sym h' |> h']). We thus want ForAllCo tv h' g' : (ForAllTy (tv : k2) (ty2[tv |-> tv |> h'])) ~# (ForAllTy (tv : k1) (ty1[tv |-> tv |> h'][tv |-> tv |> sym h'])) We thus see that we want g' : ty2[tv |-> tv |> h'] ~# ty1[tv |-> tv |> h'] and thus g' = sym (g[tv |-> tv |> h']). Putting it all together, we get this: sym (ForAllCo tv h g) ==> ForAllCo tv (sym h) (sym g[tv |-> tv |> sym h]) -} -- | Type substitution, see 'zipTvSubst' substTyWith :: HasCallStack => [TyVar] -> [Type] -> Type -> Type -- Works only if the domain of the substitution is a -- superset of the type being substituted into substTyWith tvs tys = ASSERT( length tvs == length tys ) substTy (zipTvSubst tvs tys) -- | Type substitution, see 'zipTvSubst'. Disables sanity checks. -- The problems that the sanity checks in substTy catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substTyUnchecked to -- substTy and remove this function. Please don't use in new code. substTyWithUnchecked :: [TyVar] -> [Type] -> Type -> Type substTyWithUnchecked tvs tys = ASSERT( length tvs == length tys ) substTyUnchecked (zipTvSubst tvs tys) -- | Substitute tyvars within a type using a known 'InScopeSet'. -- Pre-condition: the 'in_scope' set should satisfy Note [The substitution -- invariant]; specifically it should include the free vars of 'tys', -- and of 'ty' minus the domain of the subst. substTyWithInScope :: InScopeSet -> [TyVar] -> [Type] -> Type -> Type substTyWithInScope in_scope tvs tys ty = ASSERT( length tvs == length tys ) substTy (mkTvSubst in_scope tenv) ty where tenv = zipTyEnv tvs tys -- | Coercion substitution, see 'zipTvSubst' substCoWith :: HasCallStack => [TyVar] -> [Type] -> Coercion -> Coercion substCoWith tvs tys = ASSERT( length tvs == length tys ) substCo (zipTvSubst tvs tys) -- | Coercion substitution, see 'zipTvSubst'. Disables sanity checks. -- The problems that the sanity checks in substCo catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substCoUnchecked to -- substCo and remove this function. Please don't use in new code. substCoWithUnchecked :: [TyVar] -> [Type] -> Coercion -> Coercion substCoWithUnchecked tvs tys = ASSERT( length tvs == length tys ) substCoUnchecked (zipTvSubst tvs tys) -- | Substitute covars within a type substTyWithCoVars :: [CoVar] -> [Coercion] -> Type -> Type substTyWithCoVars cvs cos = substTy (zipCvSubst cvs cos) -- | Type substitution, see 'zipTvSubst' substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type] substTysWith tvs tys = ASSERT( length tvs == length tys ) substTys (zipTvSubst tvs tys) -- | Type substitution, see 'zipTvSubst' substTysWithCoVars :: [CoVar] -> [Coercion] -> [Type] -> [Type] substTysWithCoVars cvs cos = ASSERT( length cvs == length cos ) substTys (zipCvSubst cvs cos) -- | Substitute within a 'Type' after adding the free variables of the type -- to the in-scope set. This is useful for the case when the free variables -- aren't already in the in-scope set or easily available. -- See also Note [The substitution invariant]. substTyAddInScope :: TCvSubst -> Type -> Type substTyAddInScope subst ty = substTy (extendTCvInScopeSet subst $ tyCoVarsOfType ty) ty -- | When calling `substTy` it should be the case that the in-scope set in -- the substitution is a superset of the free vars of the range of the -- substitution. -- See also Note [The substitution invariant]. isValidTCvSubst :: TCvSubst -> Bool isValidTCvSubst (TCvSubst in_scope tenv cenv) = (tenvFVs `varSetInScope` in_scope) && (cenvFVs `varSetInScope` in_scope) where tenvFVs = tyCoVarsOfTypesSet tenv cenvFVs = tyCoVarsOfCosSet cenv -- | This checks if the substitution satisfies the invariant from -- Note [The substitution invariant]. checkValidSubst :: HasCallStack => TCvSubst -> [Type] -> [Coercion] -> a -> a checkValidSubst subst@(TCvSubst in_scope tenv cenv) tys cos a = ASSERT2( isValidTCvSubst subst, text "in_scope" <+> ppr in_scope $$ text "tenv" <+> ppr tenv $$ text "tenvFVs" <+> ppr (tyCoVarsOfTypesSet tenv) $$ text "cenv" <+> ppr cenv $$ text "cenvFVs" <+> ppr (tyCoVarsOfCosSet cenv) $$ text "tys" <+> ppr tys $$ text "cos" <+> ppr cos ) ASSERT2( tysCosFVsInScope, text "in_scope" <+> ppr in_scope $$ text "tenv" <+> ppr tenv $$ text "cenv" <+> ppr cenv $$ text "tys" <+> ppr tys $$ text "cos" <+> ppr cos $$ text "needInScope" <+> ppr needInScope ) a where substDomain = nonDetKeysUFM tenv ++ nonDetKeysUFM cenv -- It's OK to use nonDetKeysUFM here, because we only use this list to -- remove some elements from a set needInScope = (tyCoVarsOfTypes tys `unionVarSet` tyCoVarsOfCos cos) `delListFromUFM_Directly` substDomain tysCosFVsInScope = needInScope `varSetInScope` in_scope -- | Substitute within a 'Type' -- The substitution has to satisfy the invariants described in -- Note [The substitution invariant]. substTy :: HasCallStack => TCvSubst -> Type -> Type substTy subst ty | isEmptyTCvSubst subst = ty | otherwise = checkValidSubst subst [ty] [] $ subst_ty subst ty -- | Substitute within a 'Type' disabling the sanity checks. -- The problems that the sanity checks in substTy catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substTyUnchecked to -- substTy and remove this function. Please don't use in new code. substTyUnchecked :: TCvSubst -> Type -> Type substTyUnchecked subst ty | isEmptyTCvSubst subst = ty | otherwise = subst_ty subst ty -- | Substitute within several 'Type's -- The substitution has to satisfy the invariants described in -- Note [The substitution invariant]. substTys :: HasCallStack => TCvSubst -> [Type] -> [Type] substTys subst tys | isEmptyTCvSubst subst = tys | otherwise = checkValidSubst subst tys [] $ map (subst_ty subst) tys -- | Substitute within several 'Type's disabling the sanity checks. -- The problems that the sanity checks in substTys catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substTysUnchecked to -- substTys and remove this function. Please don't use in new code. substTysUnchecked :: TCvSubst -> [Type] -> [Type] substTysUnchecked subst tys | isEmptyTCvSubst subst = tys | otherwise = map (subst_ty subst) tys -- | Substitute within a 'ThetaType' -- The substitution has to satisfy the invariants described in -- Note [The substitution invariant]. substTheta :: HasCallStack => TCvSubst -> ThetaType -> ThetaType substTheta = substTys -- | Substitute within a 'ThetaType' disabling the sanity checks. -- The problems that the sanity checks in substTys catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substThetaUnchecked to -- substTheta and remove this function. Please don't use in new code. substThetaUnchecked :: TCvSubst -> ThetaType -> ThetaType substThetaUnchecked = substTysUnchecked subst_ty :: TCvSubst -> Type -> Type -- subst_ty is the main workhorse for type substitution -- -- Note that the in_scope set is poked only if we hit a forall -- so it may often never be fully computed subst_ty subst ty = go ty where go (TyVarTy tv) = substTyVar subst tv go (AppTy fun arg) = mkAppTy (go fun) $! (go arg) -- The mkAppTy smart constructor is important -- we might be replacing (a Int), represented with App -- by [Int], represented with TyConApp go (TyConApp tc tys) = let args = map go tys in args `seqList` TyConApp tc args go (FunTy arg res) = (FunTy $! go arg) $! go res go (ForAllTy (TvBndr tv vis) ty) = case substTyVarBndrUnchecked subst tv of (subst', tv') -> (ForAllTy $! ((TvBndr $! tv') vis)) $! (subst_ty subst' ty) go (LitTy n) = LitTy $! n go (CastTy ty co) = (CastTy $! (go ty)) $! (subst_co subst co) go (CoercionTy co) = CoercionTy $! (subst_co subst co) substTyVar :: TCvSubst -> TyVar -> Type substTyVar (TCvSubst _ tenv _) tv = ASSERT( isTyVar tv ) case lookupVarEnv tenv tv of Just ty -> ty Nothing -> TyVarTy tv substTyVars :: TCvSubst -> [TyVar] -> [Type] substTyVars subst = map $ substTyVar subst lookupTyVar :: TCvSubst -> TyVar -> Maybe Type -- See Note [Extending the TCvSubst] lookupTyVar (TCvSubst _ tenv _) tv = ASSERT( isTyVar tv ) lookupVarEnv tenv tv -- | Substitute within a 'Coercion' -- The substitution has to satisfy the invariants described in -- Note [The substitution invariant]. substCo :: HasCallStack => TCvSubst -> Coercion -> Coercion substCo subst co | isEmptyTCvSubst subst = co | otherwise = checkValidSubst subst [] [co] $ subst_co subst co -- | Substitute within a 'Coercion' disabling sanity checks. -- The problems that the sanity checks in substCo catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substCoUnchecked to -- substCo and remove this function. Please don't use in new code. substCoUnchecked :: TCvSubst -> Coercion -> Coercion substCoUnchecked subst co | isEmptyTCvSubst subst = co | otherwise = subst_co subst co -- | Substitute within several 'Coercion's -- The substitution has to satisfy the invariants described in -- Note [The substitution invariant]. substCos :: HasCallStack => TCvSubst -> [Coercion] -> [Coercion] substCos subst cos | isEmptyTCvSubst subst = cos | otherwise = checkValidSubst subst [] cos $ map (subst_co subst) cos subst_co :: TCvSubst -> Coercion -> Coercion subst_co subst co = go co where go_ty :: Type -> Type go_ty = subst_ty subst go :: Coercion -> Coercion go (Refl r ty) = mkReflCo r $! go_ty ty go (TyConAppCo r tc args)= let args' = map go args in args' `seqList` mkTyConAppCo r tc args' go (AppCo co arg) = (mkAppCo $! go co) $! go arg go (ForAllCo tv kind_co co) = case substForAllCoBndrUnchecked subst tv kind_co of { (subst', tv', kind_co') -> ((mkForAllCo $! tv') $! kind_co') $! subst_co subst' co } go (CoVarCo cv) = substCoVar subst cv go (AxiomInstCo con ind cos) = mkAxiomInstCo con ind $! map go cos go (UnivCo p r t1 t2) = (((mkUnivCo $! go_prov p) $! r) $! (go_ty t1)) $! (go_ty t2) go (SymCo co) = mkSymCo $! (go co) go (TransCo co1 co2) = (mkTransCo $! (go co1)) $! (go co2) go (NthCo d co) = mkNthCo d $! (go co) go (LRCo lr co) = mkLRCo lr $! (go co) go (InstCo co arg) = (mkInstCo $! (go co)) $! go arg go (CoherenceCo co1 co2) = (mkCoherenceCo $! (go co1)) $! (go co2) go (KindCo co) = mkKindCo $! (go co) go (SubCo co) = mkSubCo $! (go co) go (AxiomRuleCo c cs) = let cs1 = map go cs in cs1 `seqList` AxiomRuleCo c cs1 go_prov UnsafeCoerceProv = UnsafeCoerceProv go_prov (PhantomProv kco) = PhantomProv (go kco) go_prov (ProofIrrelProv kco) = ProofIrrelProv (go kco) go_prov p@(PluginProv _) = p go_prov p@(HoleProv _) = p -- NB: this last case is a little suspicious, but we need it. Originally, -- there was a panic here, but it triggered from deeplySkolemise. Because -- we only skolemise tyvars that are manually bound, this operation makes -- sense, even over a coercion with holes. substForAllCoBndr :: TCvSubst -> TyVar -> Coercion -> (TCvSubst, TyVar, Coercion) substForAllCoBndr subst = substForAllCoBndrCallback False (substCo subst) subst -- | Like 'substForAllCoBndr', but disables sanity checks. -- The problems that the sanity checks in substCo catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substCoUnchecked to -- substCo and remove this function. Please don't use in new code. substForAllCoBndrUnchecked :: TCvSubst -> TyVar -> Coercion -> (TCvSubst, TyVar, Coercion) substForAllCoBndrUnchecked subst = substForAllCoBndrCallback False (substCoUnchecked subst) subst -- See Note [Sym and ForAllCo] substForAllCoBndrCallback :: Bool -- apply sym to binder? -> (Coercion -> Coercion) -- transformation to kind co -> TCvSubst -> TyVar -> Coercion -> (TCvSubst, TyVar, Coercion) substForAllCoBndrCallback sym sco (TCvSubst in_scope tenv cenv) old_var old_kind_co = ( TCvSubst (in_scope `extendInScopeSet` new_var) new_env cenv , new_var, new_kind_co ) where new_env | no_change && not sym = delVarEnv tenv old_var | sym = extendVarEnv tenv old_var $ TyVarTy new_var `CastTy` new_kind_co | otherwise = extendVarEnv tenv old_var (TyVarTy new_var) no_kind_change = isEmptyVarSet (tyCoVarsOfCo old_kind_co) no_change = no_kind_change && (new_var == old_var) new_kind_co | no_kind_change = old_kind_co | otherwise = sco old_kind_co Pair new_ki1 _ = coercionKind new_kind_co new_var = uniqAway in_scope (setTyVarKind old_var new_ki1) substCoVar :: TCvSubst -> CoVar -> Coercion substCoVar (TCvSubst _ _ cenv) cv = case lookupVarEnv cenv cv of Just co -> co Nothing -> CoVarCo cv substCoVars :: TCvSubst -> [CoVar] -> [Coercion] substCoVars subst cvs = map (substCoVar subst) cvs lookupCoVar :: TCvSubst -> Var -> Maybe Coercion lookupCoVar (TCvSubst _ _ cenv) v = lookupVarEnv cenv v substTyVarBndr :: HasCallStack => TCvSubst -> TyVar -> (TCvSubst, TyVar) substTyVarBndr = substTyVarBndrCallback substTy -- | Like 'substTyVarBndr' but disables sanity checks. -- The problems that the sanity checks in substTy catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substTyUnchecked to -- substTy and remove this function. Please don't use in new code. substTyVarBndrUnchecked :: TCvSubst -> TyVar -> (TCvSubst, TyVar) substTyVarBndrUnchecked = substTyVarBndrCallback substTyUnchecked -- | Substitute a tyvar in a binding position, returning an -- extended subst and a new tyvar. substTyVarBndrCallback :: (TCvSubst -> Type -> Type) -- ^ the subst function -> TCvSubst -> TyVar -> (TCvSubst, TyVar) substTyVarBndrCallback subst_fn subst@(TCvSubst in_scope tenv cenv) old_var = ASSERT2( _no_capture, pprTvBndr old_var $$ pprTvBndr new_var $$ ppr subst ) ASSERT( isTyVar old_var ) (TCvSubst (in_scope `extendInScopeSet` new_var) new_env cenv, new_var) where new_env | no_change = delVarEnv tenv old_var | otherwise = extendVarEnv tenv old_var (TyVarTy new_var) _no_capture = not (new_var `elemVarSet` tyCoVarsOfTypesSet tenv) -- Assertion check that we are not capturing something in the substitution old_ki = tyVarKind old_var no_kind_change = isEmptyVarSet (tyCoVarsOfType old_ki) -- verify that kind is closed no_change = no_kind_change && (new_var == old_var) -- no_change means that the new_var is identical in -- all respects to the old_var (same unique, same kind) -- See Note [Extending the TCvSubst] -- -- In that case we don't need to extend the substitution -- to map old to new. But instead we must zap any -- current substitution for the variable. For example: -- (\x.e) with id_subst = [x |-> e'] -- Here we must simply zap the substitution for x new_var | no_kind_change = uniqAway in_scope old_var | otherwise = uniqAway in_scope $ setTyVarKind old_var (subst_fn subst old_ki) -- The uniqAway part makes sure the new variable is not already in scope substCoVarBndr :: TCvSubst -> CoVar -> (TCvSubst, CoVar) substCoVarBndr = substCoVarBndrCallback False substTy substCoVarBndrCallback :: Bool -- apply "sym" to the covar? -> (TCvSubst -> Type -> Type) -> TCvSubst -> CoVar -> (TCvSubst, CoVar) substCoVarBndrCallback sym subst_fun subst@(TCvSubst in_scope tenv cenv) old_var = ASSERT( isCoVar old_var ) (TCvSubst (in_scope `extendInScopeSet` new_var) tenv new_cenv, new_var) where -- When we substitute (co :: t1 ~ t2) we may get the identity (co :: t ~ t) -- In that case, mkCoVarCo will return a ReflCoercion, and -- we want to substitute that (not new_var) for old_var new_co = (if sym then mkSymCo else id) $ mkCoVarCo new_var no_kind_change = isEmptyVarSet (tyCoVarsOfTypes [t1, t2]) no_change = new_var == old_var && not (isReflCo new_co) && no_kind_change new_cenv | no_change = delVarEnv cenv old_var | otherwise = extendVarEnv cenv old_var new_co new_var = uniqAway in_scope subst_old_var subst_old_var = mkCoVar (varName old_var) new_var_type (_, _, t1, t2, role) = coVarKindsTypesRole old_var t1' = subst_fun subst t1 t2' = subst_fun subst t2 new_var_type = uncurry (mkCoercionType role) (if sym then (t2', t1') else (t1', t2')) -- It's important to do the substitution for coercions, -- because they can have free type variables cloneTyVarBndr :: TCvSubst -> TyVar -> Unique -> (TCvSubst, TyVar) cloneTyVarBndr subst@(TCvSubst in_scope tv_env cv_env) tv uniq = ASSERT2( isTyVar tv, ppr tv ) -- I think it's only called on TyVars (TCvSubst (extendInScopeSet in_scope tv') (extendVarEnv tv_env tv (mkTyVarTy tv')) cv_env, tv') where old_ki = tyVarKind tv no_kind_change = isEmptyVarSet (tyCoVarsOfType old_ki) -- verify that kind is closed tv1 | no_kind_change = tv | otherwise = setTyVarKind tv (substTy subst old_ki) tv' = setVarUnique tv1 uniq cloneTyVarBndrs :: TCvSubst -> [TyVar] -> UniqSupply -> (TCvSubst, [TyVar]) cloneTyVarBndrs subst [] _usupply = (subst, []) cloneTyVarBndrs subst (t:ts) usupply = (subst'', tv:tvs) where (uniq, usupply') = takeUniqFromSupply usupply (subst' , tv ) = cloneTyVarBndr subst t uniq (subst'', tvs) = cloneTyVarBndrs subst' ts usupply' {- %************************************************************************ %* * Pretty-printing types Defined very early because of debug printing in assertions %* * %************************************************************************ @pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is defined to use this. @pprParendType@ is the same, except it puts parens around the type, except for the atomic cases. @pprParendType@ works just by setting the initial context precedence very high. Note [Precedence in types] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't keep the fixity of type operators in the operator. So the pretty printer operates the following precedene structre: Type constructor application binds more tightly than Operator applications which bind more tightly than Function arrow So we might see a :+: T b -> c meaning (a :+: (T b)) -> c Maybe operator applications should bind a bit less tightly? Anyway, that's the current story, and it is used consistently for Type and HsType -} data TyPrec -- See Note [Prededence in types] = TopPrec -- No parens | FunPrec -- Function args; no parens for tycon apps | TyOpPrec -- Infix operator | TyConPrec -- Tycon args; no parens for atomic deriving( Eq, Ord ) maybeParen :: TyPrec -> TyPrec -> SDoc -> SDoc maybeParen ctxt_prec inner_prec pretty | ctxt_prec < inner_prec = pretty | otherwise = parens pretty ------------------ {- Note [Defaulting RuntimeRep variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RuntimeRep variables are considered by many (most?) users to be little more than syntactic noise. When the notion was introduced there was a signficant and understandable push-back from those with pedagogy in mind, which argued that RuntimeRep variables would throw a wrench into nearly any teach approach since they appear in even the lowly ($) function's type, ($) :: forall (w :: RuntimeRep) a (b :: TYPE w). (a -> b) -> a -> b which is significantly less readable than its non RuntimeRep-polymorphic type of ($) :: (a -> b) -> a -> b Moreover, unboxed types don't appear all that often in run-of-the-mill Haskell programs, so it makes little sense to make all users pay this syntactic overhead. For this reason it was decided that we would hide RuntimeRep variables for now (see #11549). We do this by defaulting all type variables of kind RuntimeRep to PtrLiftedRep. This is done in a pass right before pretty-printing (defaultRuntimeRepVars, controlled by -fprint-explicit-runtime-reps) -} -- | Default 'RuntimeRep' variables to 'LiftedPtr'. e.g. -- -- @ -- ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r). -- (a -> b) -> a -> b -- @ -- -- turns in to, -- -- @ ($) :: forall a (b :: *). (a -> b) -> a -> b @ -- -- We do this to prevent RuntimeRep variables from incurring a significant -- syntactic overhead in otherwise simple type signatures (e.g. ($)). See -- Note [Defaulting RuntimeRep variables] and #11549 for further discussion. -- defaultRuntimeRepVars :: Type -> Type defaultRuntimeRepVars = defaultRuntimeRepVars' emptyVarSet defaultRuntimeRepVars' :: TyVarSet -- ^ the binders which we should default -> Type -> Type -- TODO: Eventually we should just eliminate the Type pretty-printer -- entirely and simply use IfaceType; this task is tracked as #11660. defaultRuntimeRepVars' subs (ForAllTy (TvBndr var vis) ty) | isRuntimeRepVar var = let subs' = extendVarSet subs var in defaultRuntimeRepVars' subs' ty | otherwise = let var' = var { varType = defaultRuntimeRepVars' subs (varType var) } in ForAllTy (TvBndr var' vis) (defaultRuntimeRepVars' subs ty) defaultRuntimeRepVars' subs (FunTy kind ty) = FunTy (defaultRuntimeRepVars' subs kind) (defaultRuntimeRepVars' subs ty) defaultRuntimeRepVars' subs (TyVarTy var) | var `elemVarSet` subs = ptrRepLiftedTy defaultRuntimeRepVars' subs (TyConApp tc args) = TyConApp tc $ map (defaultRuntimeRepVars' subs) args defaultRuntimeRepVars' subs (AppTy x y) = defaultRuntimeRepVars' subs x `AppTy` defaultRuntimeRepVars' subs y defaultRuntimeRepVars' subs (CastTy ty co) = CastTy (defaultRuntimeRepVars' subs ty) co defaultRuntimeRepVars' _ other = other eliminateRuntimeRep :: (Type -> SDoc) -> Type -> SDoc eliminateRuntimeRep f ty = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitRuntimeReps dflags then f ty else f (defaultRuntimeRepVars ty) pprType, pprParendType :: Type -> SDoc pprType ty = eliminateRuntimeRep (ppr_type TopPrec) ty pprParendType ty = eliminateRuntimeRep (ppr_type TyConPrec) ty pprTyLit :: TyLit -> SDoc pprTyLit = ppr_tylit TopPrec pprKind, pprParendKind :: Kind -> SDoc pprKind = pprType pprParendKind = pprParendType ------------ pprClassPred :: Class -> [Type] -> SDoc pprClassPred clas tys = pprTypeApp (classTyCon clas) tys ------------ pprTheta :: ThetaType -> SDoc pprTheta [pred] = ppr_type TopPrec pred -- I'm in two minds about this pprTheta theta = parens (sep (punctuate comma (map (ppr_type TopPrec) theta))) pprThetaArrowTy :: ThetaType -> SDoc pprThetaArrowTy [] = empty pprThetaArrowTy [pred] = ppr_type TyOpPrec pred <+> darrow -- TyOpPrec: Num a => a -> a does not need parens -- bug (a :~: b) => a -> b currently does -- Trac # 9658 pprThetaArrowTy preds = parens (fsep (punctuate comma (map (ppr_type TopPrec) preds))) <+> darrow -- Notice 'fsep' here rather that 'sep', so that -- type contexts don't get displayed in a giant column -- Rather than -- instance (Eq a, -- Eq b, -- Eq c, -- Eq d, -- Eq e, -- Eq f, -- Eq g, -- Eq h, -- Eq i, -- Eq j, -- Eq k, -- Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- we get -- -- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, -- Eq j, Eq k, Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) ------------------ instance Outputable Type where ppr ty = pprType ty instance Outputable TyLit where ppr = pprTyLit ------------------ -- OK, here's the main printer ppr_type :: TyPrec -> Type -> SDoc ppr_type _ (TyVarTy tv) = ppr_tvar tv ppr_type p (TyConApp tc tys) = pprTyTcApp p tc tys ppr_type p (LitTy l) = ppr_tylit p l ppr_type p ty@(ForAllTy {}) = ppr_forall_type p ty ppr_type p ty@(FunTy {}) = ppr_forall_type p ty ppr_type p (AppTy t1 t2) = if_print_coercions ppr_app_ty (case split_app_tys t1 [t2] of (CastTy head _, args) -> ppr_type p (mk_app_tys head args) _ -> ppr_app_ty) where ppr_app_ty = maybeParen p TyConPrec $ ppr_type FunPrec t1 <+> ppr_type TyConPrec t2 split_app_tys (AppTy ty1 ty2) args = split_app_tys ty1 (ty2:args) split_app_tys head args = (head, args) mk_app_tys (TyConApp tc tys1) tys2 = TyConApp tc (tys1 ++ tys2) mk_app_tys ty1 tys2 = foldl AppTy ty1 tys2 ppr_type p (CastTy ty co) = if_print_coercions (parens (ppr_type TopPrec ty <+> text "|>" <+> ppr co)) (ppr_type p ty) ppr_type _ (CoercionTy co) = if_print_coercions (parens (ppr co)) (text "<>") ppr_forall_type :: TyPrec -> Type -> SDoc -- Used for types starting with ForAllTy or FunTy ppr_forall_type p ty = maybeParen p FunPrec $ sdocWithDynFlags $ \dflags -> ppr_sigma_type dflags True ty -- True <=> we always print the foralls on *nested* quantifiers -- Opt_PrintExplicitForalls only affects top-level quantifiers ppr_tvar :: TyVar -> SDoc ppr_tvar tv -- Note [Infix type variables] = parenSymOcc (getOccName tv) (ppr tv) ppr_tylit :: TyPrec -> TyLit -> SDoc ppr_tylit _ tl = case tl of NumTyLit n -> integer n StrTyLit s -> text (show s) if_print_coercions :: SDoc -- if printing coercions -> SDoc -- otherwise -> SDoc if_print_coercions yes no = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> if gopt Opt_PrintExplicitCoercions dflags || dumpStyle style || debugStyle style then yes else no ------------------- ppr_sigma_type :: DynFlags -> Bool -- ^ True <=> Show the foralls unconditionally -> Type -> SDoc -- Used for types starting with ForAllTy or FunTy -- Suppose we have (forall a. Show a => forall b. a -> b). When we're not -- printing foralls, we want to drop both the (forall a) and the (forall b). -- This logic does so. ppr_sigma_type dflags False orig_ty | not (gopt Opt_PrintExplicitForalls dflags) , all (isEmptyVarSet . tyCoVarsOfType . tyVarKind) tv_bndrs -- See Note [When to print foralls] = sep [ pprThetaArrowTy theta , pprArrowChain TopPrec (ppr_fun_tail tau) ] where (tv_bndrs, theta, tau) = split [] [] orig_ty split :: [TyVar] -> [PredType] -> Type -> ([TyVar], [PredType], Type) split bndr_acc theta_acc (ForAllTy (TvBndr tv vis) ty) | isInvisibleArgFlag vis = split (tv : bndr_acc) theta_acc ty split bndr_acc theta_acc (FunTy ty1 ty2) | isPredTy ty1 = split bndr_acc (ty1 : theta_acc) ty2 split bndr_acc theta_acc ty = (reverse bndr_acc, reverse theta_acc, ty) ppr_sigma_type _ _ ty = sep [ pprForAll bndrs , pprThetaArrowTy ctxt , pprArrowChain TopPrec (ppr_fun_tail tau) ] where (bndrs, rho) = split1 [] ty (ctxt, tau) = split2 [] rho split1 bndrs (ForAllTy bndr ty) = split1 (bndr:bndrs) ty split1 bndrs ty = (reverse bndrs, ty) split2 ps (FunTy ty1 ty2) | isPredTy ty1 = split2 (ty1:ps) ty2 split2 ps ty = (reverse ps, ty) -- We don't want to lose synonyms, so we mustn't use splitFunTys here. ppr_fun_tail :: Type -> [SDoc] ppr_fun_tail (FunTy ty1 ty2) | not (isPredTy ty1) = ppr_type FunPrec ty1 : ppr_fun_tail ty2 ppr_fun_tail other_ty = [ppr_type TopPrec other_ty] pprSigmaType :: Type -> SDoc -- Prints a top-level type for the user; in particular -- top-level foralls are omitted unless you use -fprint-explicit-foralls pprSigmaType ty = sdocWithDynFlags $ \dflags -> eliminateRuntimeRep (ppr_sigma_type dflags False) ty pprUserForAll :: [TyVarBinder] -> SDoc -- Print a user-level forall; see Note [When to print foralls] pprUserForAll bndrs = sdocWithDynFlags $ \dflags -> ppWhen (any bndr_has_kind_var bndrs || gopt Opt_PrintExplicitForalls dflags) $ pprForAll bndrs where bndr_has_kind_var bndr = not (isEmptyVarSet (tyCoVarsOfType (binderKind bndr))) pprForAllImplicit :: [TyVar] -> SDoc pprForAllImplicit tvs = pprForAll [ TvBndr tv Specified | tv <- tvs ] -- | Render the "forall ... ." or "forall ... ->" bit of a type. -- Do not pass in anonymous binders! pprForAll :: [TyVarBinder] -> SDoc pprForAll [] = empty pprForAll bndrs@(TvBndr _ vis : _) = add_separator (forAllLit <+> doc) <+> pprForAll bndrs' where (bndrs', doc) = ppr_tv_bndrs bndrs vis add_separator stuff = case vis of Required -> stuff <+> arrow _inv -> stuff <> dot pprTvBndrs :: [TyVar] -> SDoc pprTvBndrs tvs = sep (map pprTvBndr tvs) -- | Render the ... in @(forall ... .)@ or @(forall ... ->)@. -- Returns both the list of not-yet-rendered binders and the doc. ppr_tv_bndrs :: [TyVarBinder] -> ArgFlag -- ^ visibility of the first binder in the list -> ([TyVarBinder], SDoc) ppr_tv_bndrs all_bndrs@(TvBndr tv vis : bndrs) vis1 | vis `sameVis` vis1 = let (bndrs', doc) = ppr_tv_bndrs bndrs vis1 pp_tv = sdocWithDynFlags $ \dflags -> if Inferred == vis && gopt Opt_PrintExplicitForalls dflags then braces (pprTvBndrNoParens tv) else pprTvBndr tv in (bndrs', pp_tv <+> doc) | otherwise = (all_bndrs, empty) ppr_tv_bndrs [] _ = ([], empty) pprTvBndr :: TyVar -> SDoc pprTvBndr tv | isLiftedTypeKind kind = ppr_tvar tv | otherwise = parens (ppr_tvar tv <+> dcolon <+> pprKind kind) where kind = tyVarKind tv pprTvBndrNoParens :: TyVar -> SDoc pprTvBndrNoParens tv | isLiftedTypeKind kind = ppr_tvar tv | otherwise = ppr_tvar tv <+> dcolon <+> pprKind kind where kind = tyVarKind tv instance Outputable TyBinder where ppr (Anon ty) = text "[anon]" <+> ppr ty ppr (Named (TvBndr v Required)) = ppr v ppr (Named (TvBndr v Specified)) = char '@' <> ppr v ppr (Named (TvBndr v Inferred)) = braces (ppr v) ----------------- instance Outputable Coercion where -- defined here to avoid orphans ppr = pprCo instance Outputable LeftOrRight where ppr CLeft = text "Left" ppr CRight = text "Right" {- Note [When to print foralls] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mostly we want to print top-level foralls when (and only when) the user specifies -fprint-explicit-foralls. But when kind polymorphism is at work, that suppresses too much information; see Trac #9018. So I'm trying out this rule: print explicit foralls if a) User specifies -fprint-explicit-foralls, or b) Any of the quantified type variables has a kind that mentions a kind variable This catches common situations, such as a type siguature f :: m a which means f :: forall k. forall (m :: k->*) (a :: k). m a We really want to see both the "forall k" and the kind signatures on m and a. The latter comes from pprTvBndr. Note [Infix type variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ With TypeOperators you can say f :: (a ~> b) -> b and the (~>) is considered a type variable. However, the type pretty-printer in this module will just see (a ~> b) as App (App (TyVarTy "~>") (TyVarTy "a")) (TyVarTy "b") So it'll print the type in prefix form. To avoid confusion we must remember to parenthesise the operator, thus (~>) a b -> b See Trac #2766. -} pprDataCons :: TyCon -> SDoc pprDataCons = sepWithVBars . fmap pprDataConWithArgs . tyConDataCons where sepWithVBars [] = empty sepWithVBars docs = sep (punctuate (space <> vbar) docs) pprDataConWithArgs :: DataCon -> SDoc pprDataConWithArgs dc = sep [forAllDoc, thetaDoc, ppr dc <+> argsDoc] where (_univ_tvs, _ex_tvs, eq_spec, theta, arg_tys, _res_ty) = dataConFullSig dc univ_bndrs = dataConUnivTyVarBinders dc ex_bndrs = dataConExTyVarBinders dc forAllDoc = pprUserForAll $ (filterEqSpec eq_spec univ_bndrs ++ ex_bndrs) thetaDoc = pprThetaArrowTy theta argsDoc = hsep (fmap pprParendType arg_tys) pprTypeApp :: TyCon -> [Type] -> SDoc pprTypeApp tc tys = pprTyTcApp TopPrec tc tys -- We have to use ppr on the TyCon (not its name) -- so that we get promotion quotes in the right place pprTyTcApp :: TyPrec -> TyCon -> [Type] -> SDoc -- Used for types only; so that we can make a -- special case for type-level lists pprTyTcApp p tc tys | tc `hasKey` ipClassKey , [LitTy (StrTyLit n),ty] <- tys = maybeParen p FunPrec $ char '?' <> ftext n <> text "::" <> ppr_type TopPrec ty | tc `hasKey` consDataConKey , [_kind,ty1,ty2] <- tys = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitKinds dflags then ppr_deflt else pprTyList p ty1 ty2 | not opt_PprStyle_Debug , tc `hasKey` errorMessageTypeErrorFamKey = text "(TypeError ...)" -- Suppress detail unles you _really_ want to see | tc `hasKey` tYPETyConKey , [TyConApp ptr_rep []] <- tys , ptr_rep `hasKey` ptrRepLiftedDataConKey = unicodeSyntax (char '★') (char '*') | tc `hasKey` tYPETyConKey , [TyConApp ptr_rep []] <- tys , ptr_rep `hasKey` ptrRepUnliftedDataConKey = char '#' | otherwise = ppr_deflt where ppr_deflt = pprTcAppTy p ppr_type tc tys pprTcAppTy :: TyPrec -> (TyPrec -> Type -> SDoc) -> TyCon -> [Type] -> SDoc pprTcAppTy p pp tc tys = getPprStyle $ \style -> pprTcApp style id p pp tc tys pprTcAppCo :: TyPrec -> (TyPrec -> Coercion -> SDoc) -> TyCon -> [Coercion] -> SDoc pprTcAppCo p pp tc cos = getPprStyle $ \style -> pprTcApp style (pFst . coercionKind) p pp tc cos pprTcApp :: PprStyle -> (a -> Type) -> TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> SDoc -- Used for both types and coercions, hence polymorphism pprTcApp _ _ _ pp tc [ty] | tc `hasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp TopPrec ty) | tc `hasKey` parrTyConKey = pprPromotionQuote tc <> paBrackets (pp TopPrec ty) pprTcApp style to_type p pp tc tys | not (debugStyle style) , Just sort <- tyConTuple_maybe tc , let arity = tyConArity tc , arity == length tys , let num_to_drop = case sort of UnboxedTuple -> arity `div` 2 _ -> 0 = pprTupleApp p pp tc sort (drop num_to_drop tys) | not (debugStyle style) , Just dc <- isPromotedDataCon_maybe tc , let dc_tc = dataConTyCon dc , Just tup_sort <- tyConTuple_maybe dc_tc , let arity = tyConArity dc_tc -- E.g. 3 for (,,) k1 k2 k3 t1 t2 t3 ty_args = drop arity tys -- Drop the kind args , ty_args `lengthIs` arity -- Result is saturated = pprPromotionQuote tc <> (tupleParens tup_sort $ pprWithCommas (pp TopPrec) ty_args) | not (debugStyle style) , isUnboxedSumTyCon tc , let arity = tyConArity tc ty_args = drop (arity `div` 2) tys -- Drop the kind args , tys `lengthIs` arity -- Not a partial application = pprSumApp pp tc ty_args | otherwise = sdocWithDynFlags $ \dflags -> pprTcApp_help to_type p pp tc tys dflags style pprTupleApp :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> TupleSort -> [a] -> SDoc -- Print a saturated tuple pprTupleApp p pp tc sort tys | null tys , ConstraintTuple <- sort = if opt_PprStyle_Debug then text "(%%)" else maybeParen p FunPrec $ text "() :: Constraint" | otherwise = pprPromotionQuote tc <> tupleParens sort (pprWithCommas (pp TopPrec) tys) pprSumApp :: (TyPrec -> a -> SDoc) -> TyCon -> [a] -> SDoc pprSumApp pp tc tys = pprPromotionQuote tc <> sumParens (pprWithBars (pp TopPrec) tys) pprTcApp_help :: (a -> Type) -> TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> DynFlags -> PprStyle -> SDoc -- This one has accss to the DynFlags pprTcApp_help to_type p pp tc tys dflags style | not (isSymOcc (nameOccName tc_name)) -- Print prefix = pprPrefixApp p pp_tc (map (pp TyConPrec) tys_wo_kinds) | Just args <- mb_saturated_equality = print_equality args -- So we have an operator symbol of some kind | [ty1,ty2] <- tys_wo_kinds -- Infix, two arguments; -- we know nothing of precedence though = pprInfixApp p pp pp_tc ty1 ty2 | tc_name `hasKey` starKindTyConKey || tc_name `hasKey` unicodeStarKindTyConKey || tc_name `hasKey` unliftedTypeKindTyConKey = pp_tc -- Do not wrap *, # in parens | otherwise -- Unsaturated operator = pprPrefixApp p (parens (pp_tc)) (map (pp TyConPrec) tys_wo_kinds) where tc_name = tyConName tc pp_tc = ppr tc tys_wo_kinds = suppressInvisibles to_type dflags tc tys -- See Note [Printing equality constraints] mb_saturated_equality | hetero_eq_tc , [k1, k2, t1, t2] <- tys = Just (k1, k2, t1, t2) | homo_eq_tc , [k, t1, t2] <- tys -- we must have (~) = Just (k, k, t1, t2) | otherwise = Nothing -- See Note [Printing equality constraints] homo_eq_tc = tc `hasKey` eqTyConKey -- ~ hetero_eq_tc = tc `hasKey` eqPrimTyConKey -- ~# || tc `hasKey` eqReprPrimTyConKey -- ~R# || tc `hasKey` heqTyConKey -- ~~ -- See Note [Printing equality constraints] print_equality (ki1, ki2, ty1, ty2) | print_eqs = ppr_infix_eq pp_tc | hetero_eq_tc , print_kinds || not (to_type ki1 `eqType` to_type ki2) = ppr_infix_eq $ if tc `hasKey` eqPrimTyConKey then text "~~" else pp_tc | otherwise = if tc `hasKey` eqReprPrimTyConKey then text "Coercible" <+> (sep [ pp TyConPrec ty1 , pp TyConPrec ty2 ]) else sep [pp TyOpPrec ty1, text "~", pp TyOpPrec ty2] where ppr_infix_eq eq_op = sep [ parens (pp TyOpPrec ty1 <+> dcolon <+> pp TyOpPrec ki1) , eq_op , parens (pp TyOpPrec ty2 <+> dcolon <+> pp TyOpPrec ki2)] print_kinds = gopt Opt_PrintExplicitKinds dflags print_eqs = gopt Opt_PrintEqualityRelations dflags || dumpStyle style || debugStyle style {- Note [Printing equality constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC has a lot of differnent equalities: ~ Boxed homogeneous Nominal ~~ Boxed heterogeneous Nominal ~# Unboxed heterogeneous Nominal ~R# Unboxed heterogeneous Representational This is cofusing to the user, so when priting we usse this strategy: If -fprint-equality-relations or -dppr-debug or we are in "dump style", then print the relation as-is, which distinguishes the various different equalities listed above If ...something about heterogeneous equalities Ohherwise print 'Coercible' for (~#), and "~" for the others. This is all a bit ad-hoc, trying to print out the best representation of equalities. If you see a better design, go for it. -} ------------------ -- | Given a 'TyCon',and the args to which it is applied, -- suppress the args that are implicit suppressInvisibles :: (a -> Type) -> DynFlags -> TyCon -> [a] -> [a] suppressInvisibles to_type dflags tc xs | gopt Opt_PrintExplicitKinds dflags = xs | otherwise = snd $ partitionInvisibles tc to_type xs ---------------- pprTyList :: TyPrec -> Type -> Type -> SDoc -- Given a type-level list (t1 ': t2), see if we can print -- it in list notation [t1, ...]. pprTyList p ty1 ty2 = case gather ty2 of (arg_tys, Nothing) -> char '\'' <> brackets (fsep (punctuate comma (map (ppr_type TopPrec) (ty1:arg_tys)))) (arg_tys, Just tl) -> maybeParen p FunPrec $ hang (ppr_type FunPrec ty1) 2 (fsep [ colon <+> ppr_type FunPrec ty | ty <- arg_tys ++ [tl]]) where gather :: Type -> ([Type], Maybe Type) -- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn] -- = (tys, Just tl) means ty is of form t1:t2:...tn:tl gather (TyConApp tc tys) | tc `hasKey` consDataConKey , [_kind, ty1,ty2] <- tys , (args, tl) <- gather ty2 = (ty1:args, tl) | tc `hasKey` nilDataConKey = ([], Nothing) gather ty = ([], Just ty) ---------------- pprInfixApp :: TyPrec -> (TyPrec -> a -> SDoc) -> SDoc -> a -> a -> SDoc pprInfixApp p pp pp_tc ty1 ty2 = maybeParen p TyOpPrec $ sep [pp TyOpPrec ty1, pprInfixVar True pp_tc <+> pp TyOpPrec ty2] pprPrefixApp :: TyPrec -> SDoc -> [SDoc] -> SDoc pprPrefixApp p pp_fun pp_tys | null pp_tys = pp_fun | otherwise = maybeParen p TyConPrec $ hang pp_fun 2 (sep pp_tys) ---------------- pprArrowChain :: TyPrec -> [SDoc] -> SDoc -- pprArrowChain p [a,b,c] generates a -> b -> c pprArrowChain _ [] = empty pprArrowChain p (arg:args) = maybeParen p FunPrec $ sep [arg, sep (map (arrow <+>) args)] ppSuggestExplicitKinds :: SDoc -- Print a helpful suggstion about -fprint-explicit-kinds, -- if it is not already on ppSuggestExplicitKinds = sdocWithDynFlags $ \ dflags -> ppUnless (gopt Opt_PrintExplicitKinds dflags) $ text "Use -fprint-explicit-kinds to see the kind arguments" {- %************************************************************************ %* * \subsection{TidyType} %* * %************************************************************************ -} -- | This tidies up a type for printing in an error message, or in -- an interface file. -- -- It doesn't change the uniques at all, just the print names. tidyTyCoVarBndrs :: TidyEnv -> [TyCoVar] -> (TidyEnv, [TyCoVar]) tidyTyCoVarBndrs (occ_env, subst) tvs = mapAccumL tidyTyCoVarBndr tidy_env' tvs where -- Seed the occ_env with clashes among the names, see -- Node [Tidying multiple names at once] in OccName -- Se still go through tidyTyCoVarBndr so that each kind variable is tidied -- with the correct tidy_env occs = map getHelpfulOccName tvs tidy_env' = (avoidClashesOccEnv occ_env occs, subst) tidyTyCoVarBndr :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar) tidyTyCoVarBndr tidy_env@(occ_env, subst) tyvar = case tidyOccName occ_env (getHelpfulOccName tyvar) of (occ_env', occ') -> ((occ_env', subst'), tyvar') where subst' = extendVarEnv subst tyvar tyvar' tyvar' = setTyVarKind (setTyVarName tyvar name') kind' kind' = tidyKind tidy_env (tyVarKind tyvar) name' = tidyNameOcc name occ' name = tyVarName tyvar getHelpfulOccName :: TyCoVar -> OccName getHelpfulOccName tyvar = occ1 where name = tyVarName tyvar occ = getOccName name -- System Names are for unification variables; -- when we tidy them we give them a trailing "0" (or 1 etc) -- so that they don't take precedence for the un-modified name -- Plus, indicating a unification variable in this way is a -- helpful clue for users occ1 | isSystemName name = if isTyVar tyvar then mkTyVarOcc (occNameString occ ++ "0") else mkVarOcc (occNameString occ ++ "0") | otherwise = occ tidyTyVarBinder :: TidyEnv -> TyVarBndr TyVar vis -> (TidyEnv, TyVarBndr TyVar vis) tidyTyVarBinder tidy_env (TvBndr tv vis) = (tidy_env', TvBndr tv' vis) where (tidy_env', tv') = tidyTyCoVarBndr tidy_env tv tidyTyVarBinders :: TidyEnv -> [TyVarBndr TyVar vis] -> (TidyEnv, [TyVarBndr TyVar vis]) tidyTyVarBinders = mapAccumL tidyTyVarBinder --------------- tidyFreeTyCoVars :: TidyEnv -> [TyCoVar] -> TidyEnv -- ^ Add the free 'TyVar's to the env in tidy form, -- so that we can tidy the type they are free in tidyFreeTyCoVars (full_occ_env, var_env) tyvars = fst (tidyOpenTyCoVars (full_occ_env, var_env) tyvars) --------------- tidyOpenTyCoVars :: TidyEnv -> [TyCoVar] -> (TidyEnv, [TyCoVar]) tidyOpenTyCoVars env tyvars = mapAccumL tidyOpenTyCoVar env tyvars --------------- tidyOpenTyCoVar :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar) -- ^ Treat a new 'TyCoVar' as a binder, and give it a fresh tidy name -- using the environment if one has not already been allocated. See -- also 'tidyTyCoVarBndr' tidyOpenTyCoVar env@(_, subst) tyvar = case lookupVarEnv subst tyvar of Just tyvar' -> (env, tyvar') -- Already substituted Nothing -> let env' = tidyFreeTyCoVars env (tyCoVarsOfTypeList (tyVarKind tyvar)) in tidyTyCoVarBndr env' tyvar -- Treat it as a binder --------------- tidyTyVarOcc :: TidyEnv -> TyVar -> TyVar tidyTyVarOcc env@(_, subst) tv = case lookupVarEnv subst tv of Nothing -> updateTyVarKind (tidyType env) tv Just tv' -> tv' --------------- tidyTypes :: TidyEnv -> [Type] -> [Type] tidyTypes env tys = map (tidyType env) tys --------------- tidyType :: TidyEnv -> Type -> Type tidyType _ (LitTy n) = LitTy n tidyType env (TyVarTy tv) = TyVarTy (tidyTyVarOcc env tv) tidyType env (TyConApp tycon tys) = let args = tidyTypes env tys in args `seqList` TyConApp tycon args tidyType env (AppTy fun arg) = (AppTy $! (tidyType env fun)) $! (tidyType env arg) tidyType env (FunTy fun arg) = (FunTy $! (tidyType env fun)) $! (tidyType env arg) tidyType env (ty@(ForAllTy{})) = mkForAllTys' (zip tvs' vis) $! tidyType env' body_ty where (tvs, vis, body_ty) = splitForAllTys' ty (env', tvs') = tidyTyCoVarBndrs env tvs tidyType env (CastTy ty co) = (CastTy $! tidyType env ty) $! (tidyCo env co) tidyType env (CoercionTy co) = CoercionTy $! (tidyCo env co) -- The following two functions differ from mkForAllTys and splitForAllTys in that -- they expect/preserve the ArgFlag argument. Thes belong to types/Type.hs, but -- how should they be named? mkForAllTys' :: [(TyVar, ArgFlag)] -> Type -> Type mkForAllTys' tvvs ty = foldr strictMkForAllTy ty tvvs where strictMkForAllTy (tv,vis) ty = (ForAllTy $! ((TvBndr $! tv) $! vis)) $! ty splitForAllTys' :: Type -> ([TyVar], [ArgFlag], Type) splitForAllTys' ty = go ty [] [] where go (ForAllTy (TvBndr tv vis) ty) tvs viss = go ty (tv:tvs) (vis:viss) go ty tvs viss = (reverse tvs, reverse viss, ty) --------------- -- | Grabs the free type variables, tidies them -- and then uses 'tidyType' to work over the type itself tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type]) tidyOpenTypes env tys = (env', tidyTypes (trimmed_occ_env, var_env) tys) where (env'@(_, var_env), tvs') = tidyOpenTyCoVars env $ tyCoVarsOfTypesWellScoped tys trimmed_occ_env = initTidyOccEnv (map getOccName tvs') -- The idea here was that we restrict the new TidyEnv to the -- _free_ vars of the types, so that we don't gratuitously rename -- the _bound_ variables of the types. --------------- tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type) tidyOpenType env ty = let (env', [ty']) = tidyOpenTypes env [ty] in (env', ty') --------------- -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment) tidyTopType :: Type -> Type tidyTopType ty = tidyType emptyTidyEnv ty --------------- tidyOpenKind :: TidyEnv -> Kind -> (TidyEnv, Kind) tidyOpenKind = tidyOpenType tidyKind :: TidyEnv -> Kind -> Kind tidyKind = tidyType ---------------- tidyCo :: TidyEnv -> Coercion -> Coercion tidyCo env@(_, subst) co = go co where go (Refl r ty) = Refl r (tidyType env ty) go (TyConAppCo r tc cos) = let args = map go cos in args `seqList` TyConAppCo r tc args go (AppCo co1 co2) = (AppCo $! go co1) $! go co2 go (ForAllCo tv h co) = ((ForAllCo $! tvp) $! (go h)) $! (tidyCo envp co) where (envp, tvp) = tidyTyCoVarBndr env tv -- the case above duplicates a bit of work in tidying h and the kind -- of tv. But the alternative is to use coercionKind, which seems worse. go (CoVarCo cv) = case lookupVarEnv subst cv of Nothing -> CoVarCo cv Just cv' -> CoVarCo cv' go (AxiomInstCo con ind cos) = let args = map go cos in args `seqList` AxiomInstCo con ind args go (UnivCo p r t1 t2) = (((UnivCo $! (go_prov p)) $! r) $! tidyType env t1) $! tidyType env t2 go (SymCo co) = SymCo $! go co go (TransCo co1 co2) = (TransCo $! go co1) $! go co2 go (NthCo d co) = NthCo d $! go co go (LRCo lr co) = LRCo lr $! go co go (InstCo co ty) = (InstCo $! go co) $! go ty go (CoherenceCo co1 co2) = (CoherenceCo $! go co1) $! go co2 go (KindCo co) = KindCo $! go co go (SubCo co) = SubCo $! go co go (AxiomRuleCo ax cos) = let cos1 = tidyCos env cos in cos1 `seqList` AxiomRuleCo ax cos1 go_prov UnsafeCoerceProv = UnsafeCoerceProv go_prov (PhantomProv co) = PhantomProv (go co) go_prov (ProofIrrelProv co) = ProofIrrelProv (go co) go_prov p@(PluginProv _) = p go_prov p@(HoleProv _) = p tidyCos :: TidyEnv -> [Coercion] -> [Coercion] tidyCos env = map (tidyCo env)
snoyberg/ghc
compiler/types/TyCoRep.hs
bsd-3-clause
128,844
20
20
31,479
19,731
10,446
9,285
-1
-1
module HSync.Common.Types where import Data.Aeson.TH import Data.Char(isAlphaNum) import ClassyPrelude.Yesod import Data.SafeCopy(base, deriveSafeCopy) import Text.Blaze(ToMarkup(..)) import Data.SafeCopy(SafeCopy(..)) import Control.Lens import qualified Crypto.Hash as Hash import qualified Data.Text as T import qualified Data.ByteString.Char8 as B import qualified Data.List as L import Text.Printf(printf) import Data.Serialize(encode,decode) import Crypto.Conduit(hashFile) import qualified Crypto.Hash.CryptoAPI as CryptoAPI -------------------------------------------------------------------------------- type ErrorMessage = Text -------------------------------------------------------------------------------- newtype FileName = FileName { _unFileName :: Text } deriving (Show,Read,Eq,Ord,IsString,ToMarkup,PathPiece,Typeable ,ToJSON,FromJSON) $(deriveSafeCopy 0 'base ''FileName) makeLenses ''FileName newtype Path = Path { _pathParts :: [FileName] } deriving (Show,Read,Eq,Ord,Typeable) $(deriveSafeCopy 0 'base ''Path) $(deriveJSON defaultOptions ''Path) makeLenses ''Path fileNameOf :: Path -> FileName fileNameOf (Path []) = "root" fileNameOf (Path ps) = L.last ps -- | Parent of the root is the root itself parentOf :: Path -> Path parentOf (Path []) = Path [] parentOf (Path p) = Path . L.init $ p isSubPathOf :: Path -> Path -> Bool (Path p) `isSubPathOf` (Path q) = p `isPrefixOf` q instance PathMultiPiece Path where fromPathMultiPiece xs = Path <$> mapM fromPathPiece xs toPathMultiPiece (Path fs) = map toPathPiece fs instance ToMarkup Path where toMarkup = mconcat . L.intersperse slash . map toMarkup . _pathParts where slash = toMarkup ("/" :: Text) -------------------------------------------------------------------------------- newtype ClientId = ClientId { _unClientId :: Integer } deriving ( Show,Read,Eq,Ord,ToMarkup,Enum , Typeable,PathPiece,ToJSON,FromJSON) $(deriveSafeCopy 0 'base ''ClientId) makeLenses ''ClientId newtype ClientName = ClientName { _unClientName :: Text } deriving (Show,Read,Eq,Ord,ToMarkup,Typeable,ToJSON,FromJSON,PathPiece) $(deriveSafeCopy 0 'base ''ClientName) makeLenses ''ClientName -------------------------------------------------------------------------------- newtype RealmId = RealmId Integer deriving ( Show,Read,Eq,Ord,Enum , Typeable,ToMarkup,PathPiece,FromJSON,ToJSON) $(deriveSafeCopy 0 'base ''RealmId) type RealmName = FileName -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- newtype UserId = UserId { _unUserId :: Integer } deriving ( Show,Read,Eq,Ord,Enum , ToMarkup,Typeable,FromJSON,ToJSON,PathPiece) $(deriveSafeCopy 0 'base ''UserId) makeLenses ''UserId newtype UserName = UserName { _unUserName :: Text } deriving (Show,Read,Eq,Ord,ToMarkup,Typeable,FromJSON,ToJSON) $(deriveSafeCopy 0 'base ''UserName) makeLenses ''UserName instance PathPiece UserName where toPathPiece = _unUserName fromPathPiece = either (const Nothing) Just . validateUserName validateUserName :: Text -> Either ErrorMessage UserName validateUserName t | T.all userNameChar t = Right $ UserName t | otherwise = Left "Invalid UserName. Only alphanumeric characters allowed." userNameChar :: Char -> Bool userNameChar = isAlphaNum newtype RealName = RealName { _unRealName :: Text } deriving (Show,Read,Eq,Ord,ToMarkup,Typeable,FromJSON,ToJSON) $(deriveSafeCopy 0 'base ''RealName) makeLenses ''RealName -- $(deriveJSON defaultOptions ''RealName) -------------------------------------------------------------------------------- newtype Password = Password { _unPassword :: Text } deriving (Show,Read,Eq,Ord, PathPiece,FromJSON,ToJSON,Typeable) $(deriveSafeCopy 0 'base ''Password) makeLenses ''Password newtype HashedPassword = HashedPassword { _unHashedPassword :: Text } deriving (Show,Read,Eq,Ord, PathPiece,FromJSON,ToJSON,ToMarkup) $(deriveSafeCopy 0 'base ''HashedPassword) makeLenses ''HashedPassword sha1 :: ByteString -> Hash.Digest Hash.SHA1 sha1 = Hash.hash hash' :: Text -> Text hash' = T.pack . show . sha1 . B.pack . T.unpack hashPassword :: Password -> HashedPassword hashPassword = HashedPassword . hash' . _unPassword -------------------------------------------------------------------------------- newtype Signature = Signature { _signatureData :: Text } deriving (Show,Read,Eq,Ord,ToJSON,FromJSON,PathPiece,ToMarkup) $(deriveSafeCopy 0 'base ''Signature) makeLenses ''Signature -- instance ToJSON Signature where -- toJSON = String . T.pack . showSignatureData -- instance FromJSON Signature where -- parseJSON (String t) = pure . Signature . B.pack . T.unpack $ t -- parseJSON _ = mzero -- instance PathPiece Signature where -- toPathPiece = T.pack . B.unpack . _signatureData -- fromPathPiece = Just . Signature . B.pack . T.unpack fileSignature :: MonadIO m => FilePath -> m Signature fileSignature fp = f <$> hashFile fp where f :: CryptoAPI.SHA1 -> Signature f = Signature . T.pack . concatMap (printf "%02x") . B.unpack . encode -- showSignatureData :: Signature -> String -- showSignatureData (Signature b) = decodeSignatureData b -- decodeSignatureData :: ByteString -> String -- decodeSignatureData b = case decode b of -- Left _ -> B.unpack b -- -- failed to decode, so as a best effort show and treat as Char8 -- Right x -> show (x :: CryptoAPI.SHA1)
noinia/hsync-common
src/HSync/Common/Types.hs
bsd-3-clause
5,903
0
12
1,167
1,515
814
701
-1
-1
{-# LANGUAGE RankNTypes, NamedFieldPuns, RecordWildCards, PatternGuards, OverloadedStrings #-} module Distribution.Server.Features.PreferredVersions ( VersionsFeature(..), VersionsResource(..), initVersionsFeature, PreferredInfo(..), VersionStatus(..), classifyVersions, PreferredRender(..), ) where import Distribution.Server.Framework import Distribution.Server.Features.PreferredVersions.State import Distribution.Server.Features.PreferredVersions.Backup import Distribution.Server.Features.Core import Distribution.Server.Features.Upload import Distribution.Server.Features.Tags import qualified Distribution.Server.Packages.PackageIndex as PackageIndex import Distribution.Server.Packages.Types import Distribution.Package import Distribution.Version import Distribution.Text import Data.Either (rights) import Data.Function (fix) import Data.List (intercalate, find) import Data.Maybe (isJust, fromMaybe, catMaybes) import Data.Time.Clock (getCurrentTime) import Control.Arrow (second) import Control.Applicative (optional) import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.ByteString.Lazy.Char8 as BS (pack) -- Only used for ASCII data import Data.Aeson (Value(..)) import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Text import qualified Data.Vector as Vector data VersionsFeature = VersionsFeature { versionsFeatureInterface :: HackageFeature, queryGetPreferredInfo :: forall m. MonadIO m => PackageName -> m PreferredInfo, queryGetDeprecatedFor :: forall m. MonadIO m => PackageName -> m (Maybe [PackageName]), versionsResource :: VersionsResource, preferredHook :: Hook (PackageName, PreferredInfo) (), deprecatedHook :: Hook (PackageName, Maybe [PackageName]) (), putDeprecated :: PackageName -> ServerPartE Bool, putPreferred :: PackageName -> ServerPartE (), updateDeprecatedTags :: IO (), doPreferredRender :: PackageName -> ServerPartE PreferredRender, doDeprecatedRender :: PackageName -> ServerPartE (Maybe [PackageName]), doPreferredsRender :: forall m. MonadIO m => m [(PackageName, PreferredRender)], doDeprecatedsRender :: forall m. MonadIO m => m [(PackageName, [PackageName])], makePreferredVersions :: forall m. MonadIO m => m String, withPackagePreferred :: forall a. PackageId -> (PkgInfo -> [PkgInfo] -> ServerPartE a) -> ServerPartE a, withPackagePreferredPath :: forall a. DynamicPath -> (PkgInfo -> [PkgInfo] -> ServerPartE a) -> ServerPartE a } instance IsHackageFeature VersionsFeature where getFeatureInterface = versionsFeatureInterface data VersionsResource = VersionsResource { preferredResource :: Resource, preferredText :: Resource, preferredPackageResource :: Resource, deprecatedResource :: Resource, deprecatedPackageResource :: Resource, preferredUri :: String -> String, preferredPackageUri :: String -> PackageName -> String, deprecatedUri :: String -> String, deprecatedPackageUri :: String -> PackageName -> String } data PreferredRender = PreferredRender { rendSumRange :: String, rendRanges :: [String], rendVersions :: [Version] } deriving (Show, Eq) initVersionsFeature :: ServerEnv -> IO (CoreFeature -> UploadFeature -> TagsFeature -> IO VersionsFeature) initVersionsFeature ServerEnv{serverStateDir} = do preferredState <- preferredStateComponent serverStateDir preferredHook <- newHook deprecatedHook <- newHook return $ \core upload tags -> do let feature = versionsFeature core upload tags preferredState preferredHook deprecatedHook return feature preferredStateComponent :: FilePath -> IO (StateComponent AcidState PreferredVersions) preferredStateComponent stateDir = do st <- openLocalStateFrom (stateDir </> "db" </> "PreferredVersions") initialPreferredVersions return StateComponent { stateDesc = "Preferred package versions" , stateHandle = st , getState = query st GetPreferredVersions , putState = update st . ReplacePreferredVersions , resetState = preferredStateComponent , backupState = \_ -> backupPreferredVersions , restoreState = restorePreferredVersions } versionsFeature :: CoreFeature -> UploadFeature -> TagsFeature -> StateComponent AcidState PreferredVersions -> Hook (PackageName, PreferredInfo) () -> Hook (PackageName, Maybe [PackageName]) () -> VersionsFeature -- FIXME this packageInPath punning and shadowing makes -- things harder to understand and modify later versionsFeature CoreFeature{ coreResource=CoreResource{ packageInPath , guardValidPackageName , lookupPackageName } , queryGetPackageIndex , updateArchiveIndexEntry } UploadFeature{..} TagsFeature{..} preferredState preferredHook deprecatedHook = VersionsFeature{..} where versionsFeatureInterface = (emptyHackageFeature "versions") { featureResources = map ($ versionsResource) [ preferredResource , preferredPackageResource , deprecatedResource , deprecatedPackageResource , preferredText ] , featurePostInit = do updateDeprecatedTags updateIndexPreferredState , featureState = [abstractAcidStateComponent preferredState] } queryGetPreferredInfo :: MonadIO m => PackageName -> m PreferredInfo queryGetPreferredInfo name = queryState preferredState (GetPreferredInfo name) queryGetDeprecatedFor :: MonadIO m => PackageName -> m (Maybe [PackageName]) queryGetDeprecatedFor name = queryState preferredState (GetDeprecatedFor name) updateDeprecatedTags = do pkgs <- fmap (Map.keys . deprecatedMap) $ queryState preferredState GetPreferredVersions setCalculatedTag (Tag "deprecated") (Set.fromDistinctAscList pkgs) updatePackageDeprecation :: MonadIO m => PackageName -> Maybe [PackageName] -> m () updatePackageDeprecation pkgname deprs = liftIO $ do updateState preferredState $ SetDeprecatedFor pkgname deprs runHook_ deprecatedHook (pkgname, deprs) updateDeprecatedTags versionsResource = fix $ \r -> VersionsResource { preferredResource = resourceAt "/packages/preferred.:format" , preferredPackageResource = (resourceAt "/package/:package/preferred.:format") { resourceDesc = [(GET, "List package's versions divided by type: normal, unpreferred, and deprecated")], resourceGet = [("json", handlePreferredPackageGet)] } , preferredText = (resourceAt "/packages/preferred-versions") { resourceGet = [("txt", \_ -> textPreferred)] } , deprecatedResource = (resourceAt "/packages/deprecated.:format") { resourceGet = [("json", handlePackagesDeprecatedGet)] } , deprecatedPackageResource = (resourceAt "/package/:package/deprecated.:format") { resourceGet = [("json", handlePackageDeprecatedGet) ], resourcePut = [("json", handlePackageDeprecatedPut) ] } , preferredUri = \format -> renderResource (preferredResource r) [format] , preferredPackageUri = \format pkgid -> renderResource (preferredPackageResource r) [display pkgid, format] , deprecatedUri = \format -> renderResource (deprecatedResource r) [format] , deprecatedPackageUri = \format pkgid -> renderResource (deprecatedPackageResource r) [display pkgid, format] } textPreferred = fmap toResponse makePreferredVersions handlePreferredPackageGet :: DynamicPath -> ServerPartE Response handlePreferredPackageGet dpath = do pkgname <- packageInPath dpath pkgs <- lookupPackageName pkgname prefInfo <- queryGetPreferredInfo pkgname let classifiedVersions = Map.fromListWith (++) $ map (\(v, i) -> (i, [v])) $ classifyVersions prefInfo $ map packageVersion pkgs versionType NormalVersion = "normal-version" versionType DeprecatedVersion = "deprecated-version" versionType UnpreferredVersion = "unpreferred-version" return . toResponse . object $ map (\(i, vs) -> (Text.pack . versionType $ i, array $ map (string . display) vs)) $ Map.toList classifiedVersions handlePackagesDeprecatedGet :: DynamicPath -> ServerPartE Response handlePackagesDeprecatedGet _ = do deprPkgs <- deprecatedMap <$> queryState preferredState GetPreferredVersions return $ toResponse $ array [ object [ ("deprecated-package", string $ display deprPkg) , ("in-favour-of", array [ string $ display pkg | pkg <- replacementPkgs ]) ] | (deprPkg, replacementPkgs) <- Map.toList deprPkgs ] handlePackageDeprecatedGet :: DynamicPath -> ServerPartE Response handlePackageDeprecatedGet dpath = do pkgname <- packageInPath dpath guardValidPackageName pkgname mdep <- queryState preferredState (GetDeprecatedFor pkgname) return $ toResponse $ object [ ("is-deprecated", Bool (isJust mdep)) , ("in-favour-of", array [ string $ display pkg | pkg <- fromMaybe [] mdep ]) ] handlePackageDeprecatedPut :: DynamicPath -> ServerPartE Response handlePackageDeprecatedPut dpath = do pkgname <- packageInPath dpath guardValidPackageName pkgname guardAuthorisedAsMaintainerOrTrustee pkgname jv <- expectAesonContent case jv of Object o -- FIXME should just be a nested case -- or something more human friendly | fields <- HashMap.toList o , Just (Bool deprecated) <- lookup "is-deprecated" fields , Just (Array strs) <- lookup "in-favour-of" fields -- FIXME Audit this parsing -> PackageName code, suspiciously -- reliant on MonomorphismRestriction to resolve ambiguity , let asPackage (String s) = simpleParse (Text.unpack s) asPackage _ = Nothing mpkgs :: [Maybe PackageName] mpkgs = map asPackage (Vector.toList strs) , all isJust mpkgs -> do let deprecatedInfo | deprecated = Just (catMaybes mpkgs) | otherwise = Nothing updatePackageDeprecation pkgname deprecatedInfo ok $ toResponse () _ -> errBadRequest "bad json format or content" [] --------------------------- -- This is a function used by the HTML feature to select the version to display. -- It could be enhanced by displaying a search page in the case of failure, -- which is outside of the scope of this feature. withPackagePreferred :: PackageId -> (PkgInfo -> [PkgInfo] -> ServerPartE a) -> ServerPartE a withPackagePreferred pkgid func = do pkgIndex <- queryGetPackageIndex case PackageIndex.lookupPackageName pkgIndex (packageName pkgid) of [] -> packageError [MText "No such package in package index"] pkgs | pkgVersion pkgid == Version [] [] -> queryState preferredState (GetPreferredInfo $ packageName pkgid) >>= \info -> do let rangeToCheck = sumRange info case maybe id (\r -> filter (flip withinRange r . packageVersion)) rangeToCheck pkgs of -- no preferred version available, choose latest from list ordered by version [] -> func (last pkgs) pkgs -- return latest preferred version pkgs' -> func (last pkgs') pkgs pkgs -> case find ((== packageVersion pkgid) . packageVersion) pkgs of Nothing -> packageError [MText $ "No such package version for " ++ display (packageName pkgid)] Just pkg -> func pkg pkgs where packageError = errNotFound "Package not found" withPackagePreferredPath :: DynamicPath -> (PkgInfo -> [PkgInfo] -> ServerPartE a) -> ServerPartE a withPackagePreferredPath dpath func = do pkgid <- packageInPath dpath withPackagePreferred pkgid func putPreferred :: PackageName -> ServerPartE () putPreferred pkgname = do pkgs <- lookupPackageName pkgname guardAuthorisedAsMaintainerOrTrustee pkgname pref <- optional $ fmap lines $ look "preferred" depr <- optional $ fmap (rights . map snd . filter ((=="deprecated") . fst)) $ lookPairs case sequence . map simpleParse =<< pref of Just prefs -> case sequence . map simpleParse =<< depr of Just deprs -> case all (`elem` map packageVersion pkgs) deprs of True -> do void $ updateState preferredState $ SetPreferredRanges pkgname prefs void $ updateState preferredState $ SetDeprecatedVersions pkgname deprs liftIO updateIndexPreferredState newInfo <- queryState preferredState $ GetPreferredInfo pkgname runHook_ preferredHook (pkgname, newInfo) return () False -> preferredError "Not all of the selected versions are in the main index." Nothing -> preferredError "Version could not be parsed." Nothing -> preferredError "Expected format of the preferred ranges field is one version range per line, e.g. '<2.3 || 3.*' (see Cabal documentation for the syntax)." where preferredError = errBadRequest "Preferred ranges failed" . return . MText putDeprecated :: PackageName -> ServerPartE Bool putDeprecated pkgname = do guardValidPackageName pkgname guardAuthorisedAsMaintainerOrTrustee pkgname index <- queryGetPackageIndex isDepr <- optional $ look "deprecated" case isDepr of Just {} -> do depr <- optional $ fmap words $ look "by" case sequence . map simpleParse =<< depr of Just deprs -> case filter (null . PackageIndex.lookupPackageName index) deprs of [] -> case any (== pkgname) deprs of True -> deprecatedError $ "You can not deprecate a package in favor of itself!" _ -> do doUpdates (Just deprs) return True pkgs -> deprecatedError $ "Some superseding packages aren't in the main index: " ++ intercalate ", " (map display pkgs) Nothing -> deprecatedError "Expected format of the 'superseded by' field is a list of package names separated by spaces." Nothing -> do doUpdates Nothing return False where deprecatedError = errBadRequest "Deprecation failed" . return . MText doUpdates deprs = do void $ updateState preferredState $ SetDeprecatedFor pkgname deprs runHook_ deprecatedHook (pkgname, deprs) liftIO $ updateDeprecatedTags renderPrefInfo :: PreferredInfo -> PreferredRender renderPrefInfo pref = PreferredRender { rendSumRange = maybe "-any" display $ sumRange pref, rendRanges = map display $ preferredRanges pref, rendVersions = deprecatedVersions pref } doPreferredRender :: PackageName -> ServerPartE PreferredRender doPreferredRender pkgname = do guardValidPackageName pkgname pref <- queryState preferredState $ GetPreferredInfo pkgname return $ renderPrefInfo pref doDeprecatedRender :: PackageName -> ServerPartE (Maybe [PackageName]) doDeprecatedRender pkgname = do guardValidPackageName pkgname queryState preferredState $ GetDeprecatedFor pkgname doPreferredsRender :: MonadIO m => m [(PackageName, PreferredRender)] doPreferredsRender = queryState preferredState GetPreferredVersions >>= return . map (second renderPrefInfo) . Map.toList . preferredMap doDeprecatedsRender :: MonadIO m => m [(PackageName, [PackageName])] doDeprecatedsRender = queryState preferredState GetPreferredVersions >>= return . Map.toList . deprecatedMap updateIndexPreferredState :: IO () updateIndexPreferredState = do prefVersions <- makePreferredVersions now <- getCurrentTime updateArchiveIndexEntry "preferred-versions" (BS.pack prefVersions, now) makePreferredVersions :: MonadIO m => m String makePreferredVersions = queryState preferredState GetPreferredVersions >>= \(PreferredVersions prefs _) -> do return . unlines . (topText++) . map (display . uncurry Dependency) . Map.toList $ Map.mapMaybe sumRange prefs -- note: setting noVersion is kind of useless.. -- $ unionWith const (Map.mapMaybe sumRange deprs) (Map.map (const noVersion) prefs) where -- hard coded.. topText = [ "-- A global set of preferred versions." , "--" , "-- This is to indicate a current recommended version, to allow stable and" , "-- experimental versions to co-exist on hackage and to help transitions" , "-- between major API versions." , "--" , "-- Tools like cabal-install take these preferences into account when" , "-- constructing install plans." , "--" ] {------------------------------------------------------------------------------ Some aeson auxiliary functions ------------------------------------------------------------------------------} array :: [Value] -> Value array = Array . Vector.fromList object :: [(Text.Text, Value)] -> Value object = Object . HashMap.fromList string :: String -> Value string = String . Text.pack
chrisdotcode/hackage-server
Distribution/Server/Features/PreferredVersions.hs
bsd-3-clause
18,434
27
28
5,000
3,406
1,879
1,527
319
16
----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Dimitri Sabadie -- License : BSD3 -- -- Maintainer : Dimitri Sabadie <[email protected]> -- Stability : experimental -- Portability : portable -- -- This module enhances a little bit "Control.Monad" by adding a few useful -- functions. ---------------------------------------------------------------------------- module Quaazar.Control.Monad ( -- * Filters partitionM ) where -- |Monadic version of 'partition'. partitionM :: (Monad m) => (a -> m Bool) -> [a] -> m ([a],[a]) partitionM p l = sel l ([],[]) where sel [] a = return a sel (x:xs) (ts,fs) = do r <- p x sel xs $ if r then (x:ts,fs) else (ts,x:fs)
phaazon/quaazar
src/Quaazar/Control/Monad.hs
bsd-3-clause
771
0
12
153
189
109
80
8
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Network.Kafka.Primitive ( fetch , groupCoordinator , metadata , offset , offsetCommit , offsetFetch , produce ) where import Control.Exception import Control.Concurrent.MVar import Control.Lens import Control.Monad.Trans import Control.Monad.Trans.State import Data.Int import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Vector as V import Network.Kafka.Internal.Connection import Network.Kafka.Protocol import Network.Kafka.Primitive.Fetch import Network.Kafka.Primitive.GroupCoordinator import Network.Kafka.Primitive.Metadata import Network.Kafka.Primitive.Offset import Network.Kafka.Primitive.OffsetCommit import Network.Kafka.Primitive.OffsetFetch import Network.Kafka.Primitive.Produce import Network.Kafka.Types hiding (offset) internal :: KafkaAction req resp => KafkaContext -> req -> IO resp internal c = send (kafkaContextConnection c) (kafkaContextConfig c) groupCoordinator :: KafkaContext -> T.Text -> IO GroupCoordinatorResponseV0 groupCoordinator c t = internal c $ GroupCoordinatorRequestV0 $ Utf8 (T.encodeUtf8 t) fetch :: KafkaContext -> V.Vector TopicFetch -> IO (V.Vector FetchResult) fetch ctxt fs = do let c = kafkaContextConfig ctxt fetchResponseV0_Data <$> internal ctxt (FetchRequestV0 (NodeId (-1)) -- -1 is a specific value for non-brokers (fromIntegral $ c ^. fetchMaxWaitTime) (fromIntegral $ c ^. fetchMinBytes) fs) metadata :: KafkaContext -> V.Vector Utf8 -> IO MetadataResponseV0 metadata c = internal c . MetadataRequestV0 offset :: KafkaContext -> NodeId -> V.Vector TopicPartition -> IO (V.Vector PartitionOffsetResponseInfo) offset c n ps = offsetResponseV0Offsets <$> internal c (OffsetRequestV0 n ps) offsetCommit :: KafkaContext -> OffsetCommitRequestV2 -> IO (V.Vector CommitTopicResult) offsetCommit c = fmap offsetCommitResponseV2Results . internal c offsetFetch :: KafkaContext -> T.Text -> V.Vector TopicOffset -> IO (V.Vector TopicOffsetResponse) offsetFetch c cg ts = do let g = Utf8 $ T.encodeUtf8 cg offsetFetchResponseV1Topics <$> internal c (OffsetFetchRequestV1 g ts) produce :: KafkaContext -> V.Vector TopicPublish -> IO (V.Vector PublishResult) produce ctxt ts = do let c = kafkaContextConfig ctxt req = ProduceRequestV0 { produceRequestV0RequiredAcks = fromIntegral $ fromEnum $ c ^. acks , produceRequestV0Timeout = fromIntegral $ c ^. timeoutMs , produceRequestV0TopicPublishes = ts } produceResponseV0Results <$> internal ctxt req
iand675/hs-kafka
src/Network/Kafka/Primitive.hs
bsd-3-clause
2,855
0
14
611
708
380
328
62
1
module Backend.InductiveGraph.Example where import Backend.InductiveGraph.Draw import Backend.InductiveGraph.DrawTIKZ import Backend.InductiveGraph.InductiveGraph import Backend.InductiveGraph.PrintLatex import Backend.InductiveGraph.Probability import Data.Graph.Inductive.Graph import Language.Operators import Utils.Plot x = var "x" y = var "y" z = var "z" e0 = x .+ y be0 :: BDD be0 = bddFrom e0 pe0 = bddToPDF "finalGV" $ buildBDD ["x","y","z"] (unE e0) bddFrom :: E (V n) -> BDD bddFrom e = buildBDD ["x","y","z"] (unE e) v1 = neg x .+ y .& z .<> var "x" .<> ((neg x .+ y .+ z) .& x) main = pe0 f :: String -> Float f "x" = 0.5 f "y" = 0.5 f "z" = 0.5 exdraw e = drawPdfInfoSheet e ["x", "y", "z"] (Just f) "prova.pdf" drawp e = drawPdfInfoSheet e ["x", "y", "z"] (Just f) drawnp e = drawPdfInfoSheet e ["x", "y", "z"] Nothing
vzaccaria/bddtool
src/Backend/InductiveGraph/Example.hs
bsd-3-clause
943
0
11
246
350
191
159
30
1
module Life.Life ( Life , fromCells , generation , isLive , shift , together ) where import Control.Arrow ((&&&), (***)) import Data.Function.Blackbird ((...)) import qualified Data.Map as M type Life = M.Map Cell Int fromCells :: [Cell] -> Life fromCells = M.fromList ... fmap $ id &&& const 1 generation :: Life -> Life generation = M.union <$> survived <*> born isLive :: Cell -> Life -> Bool isLive = M.member shift :: Cell -> Life -> Life shift (dx, dy) = M.mapKeysMonotonic $ (+ dx) *** (+ dy) together :: Life -> Life -> Life together = M.union -- Private type Cell = (Int, Int) fromFile :: FilePath -> IO Life fromFile = fmap readLife . readFile readLife :: String -> Life readLife = fromCells . concatMap liveCells . indexed . boardLines where liveCells (y, cs) = map (const y <$>) . filter snd . indexed $ map (== live) cs indexed = zipWith (,) [0..] boardLines = filter isBoardLine . lines isBoardLine = and . sequenceA [not . null, (`elem` [live, dead]) . head] (live, dead) = ('O', '.') survived, born :: Life -> Life survived = M.intersection <*> M.filter (==2) . neighborCounts born = M.map (const 1) . M.filter (==3) . neighborCounts neighborCounts :: Life -> Life neighborCounts = M.unionsWith (+) . sequenceA [ shift (-1, 1), shift (0, 1), shift (1, 1) , shift (-1, 0), shift (1, 0) , shift (-1,-1), shift (0,-1), shift (1,-1) ]
amar47shah/game-of-life
src/Life/Life.hs
bsd-3-clause
1,503
0
12
397
624
355
269
38
1
-- -- @file -- -- @brief Data types for the translation process -- -- @copyright BSD License (see LICENSE.md or https://www.libelektra.org) -- module Elektra.Specifications ( Path, Implementation, FunctionCandidate (..), TypeName, PathVariable (..), Function (..), TypeSpecification (..), TypeSignature (..), RegexTypeParam (..), RegexType (..), RegexConstraint (..), KeySpecification (..), functionBaseName ) where import Data.Function (on) type Path = String type Implementation = String type TypeName = String data FunctionCandidate = FunctionCandidate { fncFun :: Function, fncPath :: Path, fncStr :: String } deriving (Show, Eq) data Function = ArrayFunction TypeName String | Function TypeName deriving Eq instance Show Function where show (ArrayFunction s i) = s ++ i show (Function s) = s functionBaseName :: Function -> String functionBaseName (ArrayFunction s _) = s functionBaseName (Function s) = s data PathVariable = Self | Path Path | Dispatched Path deriving Eq instance Show PathVariable where show Self = "self" show (Path p) = "@PATH@" ++ p show (Dispatched d) = "@DISPATCHED@" ++ d data KeySpecification = KeySpecification { path :: Path, defaultValue :: Maybe String, keyType :: Either Path String, functionCandidates :: [FunctionCandidate], typeSpecification :: TypeSpecification } deriving (Show, Eq) instance Ord KeySpecification where compare = compare `on` typeSpecification data TypeSignature = TypeSignature [RegexConstraint] [RegexTypeParam] deriving (Show, Eq) data RegexTypeParam = RegexTypeParam RegexType PathVariable deriving (Show, Eq) data RegexConstraint = RegexConstraint String RegexType deriving (Show, Eq) data RegexType = RegexType String | RegexTypeApp RegexType RegexType | Regex String deriving (Show, Eq) data TypeSpecification = TypeSpecification { tySpecName :: String, tyPathVar :: Maybe Path, signature :: Maybe TypeSignature, implementation :: Maybe [Implementation], order :: Int, rename :: Maybe String } deriving (Show, Eq) instance Ord TypeSpecification where compare = compare `on` order
e1528532/libelektra
src/libs/typesystem/spectranslator/Elektra/Specifications.hs
bsd-3-clause
2,336
0
10
570
602
353
249
56
1
module Problem114 where import Data.Array main :: IO () -- a(n) → row of length n ending in red block -- b(n) → same, but ending in black block -- f(n) = a(n) + b(n) → total rows of length n -- we can add red block to a(n-1) or add a new block of length 3 to b(n-3) -- a(n) = a(n-1) + b(n-3) -- we can add black block to b(n-1) or to a(n-1) -- b(n) = a(n-1) + b(n-1) = f(n-1) -- solving -- ⇒ a(n) = b(n) - b(n-1) + b(n-3) -- ⇒ b(n) = 2*b(n-1) - b(n-2) + b(n-4) -- ⇒ f(n) = 2*f(n-1) - f(n-2) + f(n-4) -- n 1 2 3 4 -- a 0 0 1 2 -- b 1 1 1 2 -- f 1 1 2 4 main = print $ f ! 50 where f = array (1, 50) [ (i, f' i) | i <- [1 .. 50] ] :: Array Int Integer f' 1 = 1 f' 2 = 1 f' 3 = 2 f' 4 = 4 f' x = 2 * f ! (x - 1) - f ! (x - 2) + f ! (x - 4)
adityagupta1089/Project-Euler-Haskell
src/problems/Problem114.hs
bsd-3-clause
777
0
13
231
184
106
78
10
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} module TensorFlow.Operators ( (^+) , (^-) , (^*) , (^/) ) where import Data.Int (Int8, Int16, Int32, Int64) import Data.Word (Word8, Word16) import Data.Complex (Complex) import qualified TensorFlow.Core as TF (Tensor, Build, OneOf) import qualified TensorFlow.GenOps.Core as TF (add, sub, mul, realDiv) infixl 6 ^+, ^- infixl 7 ^*, ^/ (^+) :: TF.OneOf '[Complex Double, Complex Float, Int16, Int32, Int64, Int8, Word16, Word8, Double, Float] t => TF.Tensor v'1 t -> TF.Tensor v'2 t -> TF.Tensor TF.Build t a ^+ b = a `TF.add` b (^-) :: TF.OneOf '[Complex Double, Complex Float, Int32, Int64, Word16, Double, Float] t => TF.Tensor v'1 t -> TF.Tensor v'2 t -> TF.Tensor TF.Build t a ^- b = a `TF.sub` b (^*) :: TF.OneOf '[Complex Double, Complex Float, Int16, Int32, Int64, Int8, Word16, Word8, Double, Float] t => TF.Tensor v'1 t -> TF.Tensor v'2 t -> TF.Tensor TF.Build t a ^* b = a `TF.mul` b (^/) :: TF.OneOf '[Complex Double, Complex Float, Int16, Int32, Int64, Int8, Word16, Word8, Double, Float] t => TF.Tensor v'1 t -> TF.Tensor v'2 t -> TF.Tensor TF.Build t a ^/ b = a `TF.realDiv` b
bjoeris/orbits-haskell-tensorflow
src/TensorFlow/Operators.hs
bsd-3-clause
1,229
0
9
271
545
310
235
34
1
-- |Interact with metasploit sessions. e.g. once a host has -- successfully been exploited, use 'session_shell_read' to send -- commands to its terminal. These functions often need an extra -- newline as if you typed them on the terminal. module RPC.Session ( module Types.Session , session_list , session_stop , session_compatible_modules , session_shell_read , session_shell_write , session_shell_upgrade , session_meterpreter_write , session_meterpreter_read , session_meterpreter_run_single , session_meterpreter_script , session_meterpreter_session_detach , session_meterpreter_session_kill , session_meterpreter_tabs , session_meterpreter_directory_separator ) where import MSF.Host (Con,Server) import Types.Session -- | Silent operation. session_list :: Con Server -> Token -> IO SessionMap session_list addr auth = send_request "session.list" addr [ toObject auth ] -- | Quiet operation. session_stop :: Con Server -> Token -> SessionId -> IO () session_stop addr auth sessionID = success "session.stop" =<< send_request "session.stop" addr [ toObject auth , toObject sessionID ] -- | Silent operaiton, though how it determines compatibility is not clear. session_compatible_modules :: Con Server -> Token -> SessionId -> IO Modules session_compatible_modules addr auth sessionID = send_request "session.compatible_modules" addr [ toObject auth , toObject sessionID ] -- |Quiet operation. session_shell_read :: Con Server -> Token -> SessionId -> Maybe String -> IO ShellRead session_shell_read addr auth sessionID mb = send_request "session.shell_read" addr (req ++ extra) where req = [ toObject auth , toObject sessionID ] -- wrap the optional parameter extra = maybe [] (return . toObject) mb -- |Loud operation. session_shell_write :: Con Server -> Token -> SessionId -> String -> IO WriteCount session_shell_write addr auth sessionID input = field "session.shell_write" "write_count" =<< send_request "session.shell_write" addr [ toObject auth , toObject sessionID , toObject input ] -- | Loud operation. session_shell_upgrade :: Con Server -> Token -> SessionId -> HostName -> PortNumber -> IO () session_shell_upgrade addr auth sessionID connectHost connectPort = success "session.shell_upgrade" =<< send_request "session.shell_upgrade" addr [ toObject auth , toObject sessionID , toObject connectHost , toObject connectPort ] -- Let's assume that all interactions with meterpreter are loud. -- |Loud operation. session_meterpreter_write :: Con Server -> Token -> SessionId -> String -> IO () session_meterpreter_write addr auth sessionID input = success "session.meterpreter_write" =<< send_request "session.meterpreter_write" addr [ toObject auth , toObject sessionID , toObject input ] -- NOTE KC: actually quiet? or are we assuming that all interactions with meterpreter are loud? -- |Quiet operation. session_meterpreter_read :: Con Server -> Token -> SessionId -> IO String session_meterpreter_read addr auth sessionID = field "session.meterpreter_read" "data" =<< send_request "session.meterpreter_read" addr [ toObject auth , toObject sessionID ] -- |Loud operation. session_meterpreter_run_single :: Con Server -> Token -> SessionId -> String -> IO () session_meterpreter_run_single addr auth sessionID command = success "session.meterpreter_run_single" =<< send_request "session.meterpreter_run_single" addr [ toObject auth , toObject sessionID , toObject command ] -- |Loud operation. session_meterpreter_script :: Con Server -> Token -> SessionId -> String -> IO () session_meterpreter_script addr auth sessionID scriptName = success "session.meterpreter_script" =<< send_request "session.meterpreter_script" addr [ toObject auth , toObject sessionID , toObject scriptName ] -- |Quiet operation. session_meterpreter_session_detach :: Con Server -> Token -> SessionId -> IO Result session_meterpreter_session_detach addr auth sessionID = send_request "session.meterpreter_session_detach" addr [ toObject auth , toObject sessionID ] -- |Quiet operation. session_meterpreter_session_kill :: Con Server -> Token -> SessionId -> IO Result session_meterpreter_session_kill addr auth sessionID = send_request "session.meterpreter_session_kill" addr [ toObject auth , toObject sessionID ] -- |Silent operation, probably. session_meterpreter_tabs :: Con Server -> Token -> SessionId -> String -> IO Tabs session_meterpreter_tabs addr auth sessionID line = field "session.meterpreter_tabs" "tabs" =<< send_request "session.meterpreter_tabs" addr [ toObject auth , toObject sessionID , toObject line ] -- |Silent operation, probably. session_meterpreter_directory_separator :: Con Server -> Token -> SessionId -> IO DirSep session_meterpreter_directory_separator addr auth sessionID = field "session.meterpreter_directory_separator" "separator" =<< send_request "session.meterpreter_directory_separator" addr [ toObject auth , toObject sessionID ] -------------------------------------------------------------------------------- {- ring_clear :: Con Server -> Token -> SessionId -> IO Success ring_clear addr auth sessionID = send_request "session.ring_clear" addr [ toObject auth , toObject sessionID ] data RingLast = RingLast { getRingLast :: Int } deriving (Show) instance FromObject RingLast where fromObject obj = do m <- fromObject obj RingLast <$> (fromObject =<< Map.lookup "seq" m) ring_last :: Con Server -> Token -> String -> IO RingLast ring_last addr auth sessionID = send_request "session.ring_last" addr [ toObject auth , toObject sessionID ] data Ring_PutReturn = Ring_PutSuccess String | Ring_PutError -- XXX is this the right call? ring_put :: Con Server -> Token -> String -> String -> IO Ring_PutReturn ring_put addr auth sessionID input = let request = arr [str "session.shell_write", str auth, str sessionID, str input] in do response <- send_request request return (if hasKey response (str "write_count") then Ring_PutSuccess (str' . fromJust $ (lookup response (str "write_count"))) else Ring_PutError) data Ring_ReadReturn = Ring_ReadSuccess (Maybe String) String | Ring_ReadError -- XXX is this the right call? ring_read :: Con Server -> Token -> String -> Maybe String -> IO Ring_ReadReturn ring_read addr auth sessionID (Just readPointer) = let request = arr [str "session.shell_read", str auth, str sessionID, str readPointer] in do response <- send_request request return (if hasKey response (str "data") then let seq = str' <$> lookup response (str "seq") output = str' . fromJust $ (lookup response (str "data")) in Ring_ReadSuccess seq output else Ring_ReadError) -- XXX is this the right call? ring_read addr auth sessionID Nothing = let request = arr [str "session.shell_read", str auth, str sessionID] in do response <- send_request request return (if hasKey response (str "data") then let seq = str' <$> lookup response (str "seq") output = str' . fromJust $ (lookup response (str "data")) in Ring_ReadSuccess seq output else Ring_ReadError) -}
GaloisInc/msf-haskell
src/RPC/Session.hs
bsd-3-clause
7,301
0
11
1,318
1,050
530
520
82
1
module Day4Spec(main, spec) where import Test.Hspec import Test.QuickCheck import Data.List.Split import Day4 main :: IO () main = hspec spec spec :: Spec spec = do describe "Part A - count real rooms" $ do it "Adds up the sector ids of real rooms" $ do rooms <- readFile "test/day4.input.txt" sumRealRooms rooms `shouldBe` 158835 describe "Part B - decipher North Pole Objects" $ do it "Finds the sector ID for NPO room" $ do rooms <- readFile "test/day4.input.txt" findNPO rooms `shouldBe` 993
amirci/aoc2016-hs
test/Day4Spec.hs
bsd-3-clause
542
0
14
128
143
71
72
17
1
{-# LANGUAGE TypeFamilies, DeriveDataTypeable #-} module Data.Graphics.Class where import Data.Typeable import Linear data PrimitiveMode = LineStrip | TriangleFan | TriangleStrip | LineLoop deriving (Enum, Eq, Ord, Read, Show, Typeable) class Affine a where type Vec a :: * type Normal a :: * rotateOn :: Normal a -> a -> a scale :: Vec a -> a -> a translate :: Vec a -> a -> a class Affine a => Figure a where primitive :: PrimitiveMode -> [Vec a] -> a color :: V4 Float -> a -> a line :: [Vec a] -> a polygon :: [Vec a] -> a polygonOutline :: [Vec a] -> a circle :: Normal a -> a circleOutline :: Normal a -> a opacity :: Figure a => Float -> a -> a opacity p = color (V4 1 1 1 p) data BlendMode = Normal | Inverse | Add | Multiply | Screen deriving (Enum, Eq, Ord, Read, Show, Typeable)
fumieval/audiovisual
src/Data/Graphics/Class.hs
bsd-3-clause
839
0
10
207
339
181
158
27
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE InstanceSigs #-} module Lib where import Data.VectorSpace import Data.Maybe (fromJust) import Control.Applicative import Data.List import Utils -- Me being pretentious type ℤ = Int data EqClass v = EqClass [v] deriving Show -- TODO move the second argument to type level so adding two quotient spaces -- only makes sense when they have the same quotient -- Also we store a lot of redundant information with current setup data QuotientSpace a b where QuotientSpace :: VectorSpace a => { getElem :: a, getQuotient :: EqClass a } -> QuotientSpace a (EqClass a) instance AdditiveGroup (QuotientSpace a b) where zeroV = zeroV (^+^) (QuotientSpace x y) (QuotientSpace x' y') = QuotientSpace (x ^+^ x') y negateV (QuotientSpace x y) = QuotientSpace (negateV x) y instance VectorSpace (QuotientSpace a b) where type Scalar (QuotientSpace a b) = Scalar a (*^) λ (QuotientSpace x y) = QuotientSpace (λ *^ x) y -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- type Pitch = QuotientSpace ℤ (EqClass ℤ) type Chord = [Pitch] newtype PitchDist = PitchDist ℤ deriving (Num, Ord, Eq, Show) newtype ChordDisplace = ChordDisplace [PitchDist] deriving Show -- Measure the distance from a given note to the closest C note pitchClosestZero :: Pitch -> PitchDist pitchClosestZero p = min dist dist' where note = getElem p EqClass octaves = getQuotient p below = fromJust $ firstBelow octaves note above = fromJust $ firstAbove octaves note dist = PitchDist $ note - below dist' = PitchDist $ above - note -- Get distance between notes modulo octave pitchDist :: Pitch -> Pitch -> PitchDist pitchDist p p' = abs $ pitchClosestZero p - pitchClosestZero p' -- Get the displacement multiset from the two chords chordDist :: Chord -> Chord -> ChordDisplace chordDist = (ChordDisplace .) . (<*>) . (pitchDist <$>) type VoiceLeadMetric = Chord -> Chord -> PitchDist -- type Metric = -- forall a t. (Ord a, Num a, Functor t, Foldable t) => t a -> t a -> a voSmooth :: VoiceLeadMetric voSmooth c c' = sum $ zipWith pitchDist c c' -- Defined only for n ∈ ℤ+ -- Add L∞? (Max) voVectorNorm :: ℤ -> VoiceLeadMetric voVectorNorm n c c' = if n > 0 then sum $ zipWith (\x y-> (pitchDist x y) ^ n) c c' else undefined -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- octaves :: EqClass ℤ octaves = EqClass $ iterate (+12) 0 note :: ℤ -> Pitch note = (flip QuotientSpace) octaves middleC = note (4 * 12) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- type Progression = (Chord, Chord) minProgression :: VoiceLeadMetric -> Chord -> Chord -> Progression minProgression m c c' = foldl f start ccs where start = ([], []) f p = (bestProgression m) . (uncurry (buildColRow p)) cs = tail $ inits c cs' = tail $ inits c' ccs = zip cs cs' bestProgression :: VoiceLeadMetric -> [Progression] -> Progression bestProgression m ps = snd $ foldl f startProgression list where startProgression = (10000, ([], [])) list = zip (map (uncurry m) ps) ps f (d, x) (d', y) = if d < d' then (d, x) else (d', y) buildColRow :: Progression -> Chord -> Chord -> [Progression] buildColRow (progFrom, progTo) c c' = col ++ rowRest where col :: [Progression] col = map (\n -> (progFrom ++ [n], progTo ++ [last c'])) c (_ : rowRest) = map (\n -> (progFrom ++ [last c], progTo ++ [n])) c' -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Debug -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- testProg :: Progression testProg = (map (note . (+48)) [4, 7, 0, 11], map (note . (+48)) [4, 8, 11, 3]) test = (map (note . (+48)) [4, 7], map (note . (+48)) [4, 8]) showProg :: Progression -> String showProg (from, to) = "(" ++ fst ++ ") -> (" ++ snd ++ ")" where fst = intercalate ", " $ map shw from snd = intercalate ", " $ map shw to shw :: (Show a) => QuotientSpace a (EqClass a) -> String shw = show . getElem
danslocombe/music-geometry
src/Lib.hs
bsd-3-clause
4,121
0
13
902
1,330
738
592
-1
-1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE RebindableSyntax #-} module Live where import Control.Monad import Data.Bifunctor import Control.Concurrent import Data.Word (Word8) import Data.Function ((&)) import Prelude import Data.String import qualified Sound.ALSA.Sequencer.Event as MIDIEvent import qualified Vivid.OSC as OSC import Syzygy.Core import Syzygy.Signal import Syzygy.MIDI setup :: IO (CoreConfig Word8) setup = do signalRef <- newMVar mempty beatRef <- newMVar 0 bpmRef <- newMVar 120 let coreConfig = MkCoreConfig { bpmRef, signalRef, beatRef } midiBackend <- makeEasyMIDIBackend MkMIDIConfig { midiPortName = "VirMIDI 2-0"} _ <- forkIO $ runBackend midiBackend coreConfig return coreConfig makeEasyMIDIBackend :: MIDIConfig -> IO (Backend Word8) makeEasyMIDIBackend config = do midiBackend <- makeMIDIBackend config return $ \MkEnv{bpm, interval=(beat, _),clock, events} -> events & (>>=makeNoteEvents) & fmap (makeTimestamp bpm beat clock) & midiBackend where makeNoteEvents :: Event Word8 -> [Event MIDIEvent.Data] makeNoteEvents MkEvent{interval=(start, dur), payload} = [ MkEvent {interval=(start, 0), payload=makeNoteOnData payload} , MkEvent {interval=(start + dur, 0), payload=makeNoteOffData payload} ] main :: IO () main = do MkCoreConfig {signalRef, bpmRef} <- runOnce setup modifyMVar_ bpmRef $ const . return $ 160 modifyMVar_ signalRef $ const . return $ mempty & sigMod with :: Functor f => (f a -> a) -> f (a -> a) -> a -> a with cat mods sig = cat $ ($sig) <$> mods infixl 4 `tt` tt :: Rational -> (Signal a -> Signal a) -> Signal a -> Signal a tt i mod sig = sig & slow i & mod & fast i fracture :: Int -> (Signal a -> Signal a) -> Signal a -> Signal a fracture n f = foldr (flip (.)) id ([tt (1/(2^i)) f | i <- [0..n]]) overlay :: (Signal a -> Signal a) -> (Signal a -> Signal a) overlay f = with mconcat [id, f] filterSig :: (a -> Bool) -> Signal a -> Signal a filterSig pred sig = MkSignal $ \query -> signal sig query & filter (\MkEvent{payload}-> pred payload) staccato :: Signal a -> Signal a staccato sig = sig & (mapInterval . mapDur) (/4) legato:: Signal a -> Signal a legato sig = sig & (mapInterval . mapDur) (*4) s :: [Signal a -> Signal a] -> Signal a -> Signal a s = with switch c :: [Signal a -> Signal a] -> Signal a -> Signal a c = with cat n :: [Signal a -> Signal a] -> Signal a -> Signal a n = with nest m :: [Signal a -> Signal a] -> Signal a -> Signal a m = with mconcat ml :: (Functor f, Bifunctor g) => (a -> a) -> f (g a b) -> f (g a b) ml = fmap . first mr :: (Functor f, Bifunctor g) => (b -> b) -> f (g a b) -> f (g a b) mr = fmap . second rgb :: Float -> Float -> Float -> [OSC.OSC] rgb r g b = [ OSC.OSC "/1/fader1" [OSC.OSC_F r] , OSC.OSC "/1/fader2" [OSC.OSC_F g] , OSC.OSC "/1/fader3" [OSC.OSC_F b] ] ttsml :: Rational -> [Word8] -> Signal (Either Word8 b) -> Signal (Either Word8 b) ttsml x fs = tt x $ with switch (fs & fmap (\x -> ml (+x))) tts :: Rational -> [Signal Word8 -> Signal Word8] -> Signal Word8 -> Signal Word8 tts x fs = tt x $ with switch fs ttsf :: Rational -> [Word8] -> Signal Word8 -> Signal Word8 ttsf x fs = tt x $ with switch (fs & fmap (\x -> fmap (+x))) rep :: Rational -> Signal a -> Signal a rep n = tt n $ with switch [id, shift 1 ] tc :: Rational -> [Signal a -> Signal a] -> Signal a -> Signal a tc n fs = tt (1/n) $ with cat $ fmap (\f -> tt n f) fs glisten :: Signal Word8 -> Signal Word8 glisten = fmap $ \x -> (x + ((x `mod` 4) * 12)) sigMod1 :: Signal Word8 -> Signal Word8 sigMod1 = let (>>) = (flip (.)) in do const (embed $ 60) staccato fast 4 tt (2) $ do ttsf 2 [0, 3, 10, 12] ttsf (1/8) [17, 12, 10, 12] ttsf (1/2) [-12,-24] sigMod2 :: Signal Word8 -> Signal Word8 sigMod2 = let (>>) = (flip (.)) in do const (embed $ 48) fmap (+24) fast 4 -- tc (4) $ -- [ ttsf 2 [-27, 0, -1, 7] -- , ttsf 2 [-27, -1, -8, 7] -- ] -- tts (1) [id, id, fmap (+(12)), id] -- tts (1/16) [id, fmap (+(-12))] -- tts (1/32) [id, fmap (+(-2))] sigMod3 :: Signal Word8 -> Signal Word8 sigMod3 = let (>>) = (flip (.)) in do const (embed 60) tts 1 [ fmap (+(x)) | x <- [0, 4, 7, 11, 16, 18, 19, 21, 23]] fast 6 tts (2) [ fmap (+(x)) | x <- [0, 0, 0, 0, 0,0, 12]] overlay $ do const (embed 36) -- s [fmap (+0), fmap (+2), fmap (+7), fmap (subtract 5)] & tt (1/16) -- fmap (+(-24)) sigMod4 :: Signal Word8 -> Signal Word8 sigMod4 = let (>>) = (flip (.)) in do const (embed 48) -- tts 1 [ fmap (+(x)) | x <- [0, 4, 7, 11, 16, 18, 19, 21, 23]] s [ fmap (+(x)) | x <- [0, 3, 10, 12, 19, 3]] fast 4 tt 2 $ s [id, fmap (+12)] -- overlay $ do -- const (embed (120)) sigMod5 :: Signal Word8 -> Signal Word8 sigMod5 = let (>>) = (flip (.)) in do const (embed 48) s [fast 4] fmap (+24) tt 4 $ c [fmap (+3), fmap (+0)] tt 4 $ s [fmap (+0), fmap (+2), fmap (+0)] overlay $ do const $ embed 24 -- tt (1/16) $ s [id, fmap (+(-2)), fmap (+(-4)), fmap (+(-7))] -- overlay $ do -- fmap (+12) -- overlay $ do -- fmap (+(7)) . shift 0.5 -- s [fmap (+12), fmap (+24)] -- overlay $ s [tt (1/16) $ s [fmap (+10), fmap (+10), fmap (+14), fmap (+14)], fmap (+24)] . shift 0.5 sigMod :: Signal Word8 -> Signal Word8 sigMod = let (>>) = (flip (.)) in do const (embed 60) s [ fmap (+(x)) | x <- [0, 3, 10, 12, 19, 3]] s [fast 4] tt (1/4) $ s [id, fmap (+12)] tt (2/4) $ s [id, fmap (+12)] tt (4/4) $ s [id, fmap (+12)] glisten
sleexyz/syzygy
src/Live.hs
bsd-3-clause
5,542
0
14
1,331
2,641
1,366
1,275
-1
-1
{-# LANGUAGE FlexibleContexts, PatternGuards #-} module Text.Keepalived.Parser ( -- * Top-level parsers pKeepalivedConf , pKeepalivedConfType -- * Internal parsers -- ** Global Definitions , pGlobalDefs -- ** Static routes/ip addresses , pStaticRoutes , pStaticIpaddress -- ** VRRP scrpts , pVrrpScript -- ** VRRP sync groups , pVrrpSyncGroup -- ** VRRP instances , pVrrpInstance -- ** Virtual server groups , pVirtualServerGroup -- ** Virtual servers , pVirtualServer ) where import Control.Applicative hiding ((<|>), many, optional) import Data.List import Data.Maybe import Control.Monad.Identity import Text.Keepalived.Lexer import Text.Parsec hiding (satisfy, token, tokens) import Text.Parsec.Pos import Text.Parsec.Perm import Text.Parsec.String import qualified Text.Parsec.Prim as P import Text.Keepalived.Types import Network.Layer3 import Network.Layer4 -- | Parses whole keepalived.conf pKeepalivedConf :: Stream s Identity Token => Parsec s u KeepalivedConf pKeepalivedConf = KeepalivedConf . sort <$> many1 pKeepalivedConfType <* eof -- | Parses top-level directives on keepalived.conf pKeepalivedConfType :: Stream s Identity Token => Parsec s u KeepalivedConfType pKeepalivedConfType = choice [ TGlobalDefs <$> pGlobalDefs , TStaticRoutes <$> pStaticRoutes , TStaticIpaddress <$> pStaticIpaddress , TVrrpScript <$> pVrrpScript , TVrrpSyncGroup <$> pVrrpSyncGroup , TVrrpInstance <$> pVrrpInstance , TVirtualServerGroup <$> pVirtualServerGroup , TVirtualServer <$> pVirtualServer ] -- GLOBAL CONFIGURATION -- | Parses @global_defs@. pGlobalDefs :: Stream s Identity Token => Parsec s u GlobalDefs pGlobalDefs = do blockId "global_defs" braces $ permute $ GlobalDefs <$?> ([], pNotificationEmail) <|?> (Nothing, Just <$> pNotificationEmailFrom) <|?> (Nothing, Just <$> pSmtpServer) <|?> (Nothing, Just <$> pSmtpConnectTimeout) <|?> (Nothing, Just <$> pRouterId) -- | Parses @static_routes@. pStaticRoutes :: Stream s Identity Token => Parsec s u [Route] pStaticRoutes = do blockId "static_routes" braces $ many1 (pRoute <|> pBlackhole) -- | Parses a routing entry. pRoute :: Stream s Identity Token => Parsec s u Route pRoute = do src <- optionMaybe $ value (string "src") >> value pIPAddr optional $ value $ string "to" dst <- value pCIDR via <- optionMaybe $ value (string "via" <|> string "gw") >> value pIPAddr or <- optionMaybe $ value (string "or") >> value pIPAddr dev <- optionMaybe $ value (string "dev") >> value (many1 anyChar) scope <- optionMaybe $ value (string "scope") >> value (many1 anyChar) table <- optionMaybe $ value (string "table") >> value (many1 anyChar) metric <- optionMaybe $ value (string "metric") >> value integer lookAhead $ choice [ () <$ closeBrace , () <$ value pCIDR , () <$ value pIPAddr , () <$ value (string "src" <|> string "blackhole") ] return $ Route src dst via or dev scope table metric -- | Parses a black hole filtering entry. pBlackhole :: Stream s Identity Token => Parsec s u Route pBlackhole = do value (string "blackhole") cidr <- value pCIDR return $ Blackhole cidr -- | Parses a @static_ipaddress@. pStaticIpaddress :: Stream s Identity Token => Parsec s u [Ipaddress] pStaticIpaddress = do blockId "static_ipaddress" braces $ many1 pIpaddress -- VRRP CONFIGURATION -- Parses a @vrrp_scripts@. pVrrpScript :: Stream s Identity Token => Parsec s u VrrpScript pVrrpScript = do blockId "vrrp_script" ident <- value stringLiteral braces $ permute $ VrrpScript <$$> return ident <||> pScript <||> pScriptInterval <|?> (Nothing, Just <$> pScriptWeight) -- | Parses a @script@. pScript :: Stream s Identity Token => Parsec s u String pScript = do identifier "script" quoted stringLiteral -- | Parsers an @interval@. pScriptInterval :: Stream s Identity Token => Parsec s u Integer pScriptInterval = do identifier "interval" value natural -- | Parses a @weight@. pScriptWeight :: Stream s Identity Token => Parsec s u Integer pScriptWeight = do identifier "weight" value integer -- vrrp syncronization group(s) -- | Parses a @vrrp_sync_group@. pVrrpSyncGroup :: Stream s Identity Token => Parsec s u VrrpSyncGroup pVrrpSyncGroup = do blockId "vrrp_sync_group" ident <- value stringLiteral braces $ permute $ VrrpSyncGroup <$$> return ident <||> pVrrpGroups <|?> ([], many1 pVrrpNotify) <|?> (Nothing, Just <$> pSmtpAlert) -- | Parses a @group@. pVrrpGroups :: Stream s Identity Token => Parsec s u [String] pVrrpGroups = do blockId "group" braces $ many $ value stringLiteral -- | Parses a @vrrp instance@. pVrrpInstance :: Stream s Identity Token => Parsec s u VrrpInstance pVrrpInstance = do blockId "vrrp_instance" name <- value $ many1 anyChar braces $ permute $ VrrpInstance <$$> return name <||> pInterface <||> pVirtualRouterId <||> pPriority <|?> ([], pVirtualIpaddress) <|?> ([], pVirtualIpaddressExcluded) <|?> ([], pTrackInterface) <|?> ([], pTrackScript) <|?> ([], pVirtualRoutes) <|?> ([], many1 pVrrpNotify) <|?> (Nothing, Just <$> pVrrpState) <|?> (Nothing, Just <$> pSmtpAlert) <|?> (Nothing, Just <$> pDontTrackPrimary) <|?> (Nothing, Just <$> pMcastSrcIp) <|?> (Nothing, Just <$> pLvsSyncDaemonInterface) <|?> (Nothing, Just <$> pGarpMasterDelay) <|?> (Nothing, Just <$> pAdvertInt) <|?> (Nothing, Just <$> pAuth) <|?> (Nothing, Just <$> pNoPreempt) <|?> (Nothing, Just <$> pPreemptDelay) <|?> (Nothing, Just <$> pDebug) -- LVS CONFIGURATION -- | Parses a @virtual_server_group@. pVirtualServerGroup :: Stream s Identity Token => Parsec s u VirtualServerGroup pVirtualServerGroup = do blockId "virtual_server_group" name <- value stringLiteral braces $ VirtualServerGroup <$> pure name <*> many pVirtualServerGroupMember -- | Parses an entry at @virtual_server_group@. pVirtualServerGroupMember :: Stream s Identity Token => Parsec s u VirtualServerGroupMember pVirtualServerGroupMember = pRange <|> pAddr <|> pFwmark where pAddr = VirtualServerIPAddress <$> value pIPAddr <*> value integer pFwmark = identifier "fwmark" >> VirtualServerFwmark <$> value integer pRange = do (ip, diff) <- value $ do { ip' <- pIPAddr; char '-'; diff' <- natural; return (ip', diff') } port <- value integer return $ VirtualServerIPRange ip diff port -- | Parses a @virtual_server@. pVirtualServer :: Stream s Identity Token => Parsec s u VirtualServer pVirtualServer = do blockId "virtual_server" ident <- pVirtualServerId braces $ permute $ VirtualServer <$$> return ident <||> pLvsMethod <||> pLvsSched <||> pProtocol <||> many1 pRealServer <|?> (Nothing, Just <$> pSorryServer) <|?> (Nothing, Just <$> pDelayLoop) <|?> (Nothing, Just <$> pVirtualHost) <|?> (Nothing, Just <$> pPersistenceTimeout) <|?> (Nothing, Just <$> pPersistenceGranularity) <|?> (Nothing, Just <$> pHaSuspend) <|?> (Nothing, Just <$> pAlpha) <|?> (Nothing, Just <$> pOmega) <|?> (Nothing, Just <$> pQuorum) <|?> (Nothing, Just <$> pHysteresis) <|?> (Nothing, Just <$> pQuorumUp) <|?> (Nothing, Just <$> pQuorumDown) <|?> (Nothing, Just <$> pNatMask) -- | Parses a @nat_mask@. pNatMask :: Stream s Identity Token => Parsec s u Netmask pNatMask = do identifier "nat_mask" value pNetmaskOctets -- | pVirtualServerId :: Stream s Identity Token => Parsec s u VirtualServerId pVirtualServerId = choice [ VirtualServerIpId <$> pRealServerAddress , VirtualServerFwmarkId <$> pFmark , VirtualServerGroupId <$> pGroupId ] pFmark :: Stream s Identity Token => Parsec s u Integer pFmark = do identifier "fwmark" value natural pGroupId :: Stream s Identity Token => Parsec s u String pGroupId = do blockId "group" value stringLiteral pRealServerAddress :: Stream s Identity Token => Parsec s u RealServerAddress pRealServerAddress = RealServerAddress <$> value pIPAddr <*> maybePort where maybePort = optionMaybe $ value (PortNumber . read <$> many1 digit) -- | Parses a @real_server@ block. pRealServer :: Stream s Identity Token => Parsec s u RealServer pRealServer = do blockId "real_server" addr <- pRealServerAddress braces $ permute $ RealServer <$$> return addr <||> pWeight <|?> (Nothing, Just <$> pInhibitOnFailure) <|?> (Nothing, Just <$> pHttpGet) <|?> (Nothing, Just <$> pTcpCheck) <|?> (Nothing, Just <$> pSmtpCheck) <|?> (Nothing, Just <$> pMiscCheck) <|?> ([], many1 pRealServerNotify) -- | Parses a @HTTP_GET@ block. pHttpGet :: Stream s Identity Token => Parsec s u HttpGet pHttpGet = do blockId "HTTP_GET" <|> blockId "SSL_GET" braces $ permute $ HttpGet <$$> many1 pUrl <|?> (Nothing, Just <$> pConnectPort) <|?> (Nothing, Just <$> pBindto) <|?> (Nothing, Just <$> pConnectTimeout) <|?> (Nothing, Just <$> pNbGetRetry) <|?> (Nothing, Just <$> pDelayBeforeRetry) -- | Parses an @url@ block. pUrl :: Stream s Identity Token => Parsec s u Url pUrl = do blockId "url" braces $ permute $ Url <$$> pUrlPath <|?> (Nothing, Just <$> pUrlDigest) <|?> (Nothing, Just <$> pUrlStatusCode) -- | Parses a @path@ identifier. pUrlPath :: Stream s Identity Token => Parsec s u String pUrlPath = do identifier "path" value stringLiteral -- | Parses a @digest@. pUrlDigest :: Stream s Identity Token => Parsec s u String pUrlDigest = do identifier "digest" value stringLiteral -- | Parses a @status_code@. pUrlStatusCode :: Stream s Identity Token => Parsec s u Integer pUrlStatusCode = do identifier "status_code" value natural -- | Parses a @TCP_CHECK@. pTcpCheck :: Stream s Identity Token => Parsec s u TcpCheck pTcpCheck = do blockId "TCP_CHECK" braces $ permute $ TcpCheck <$$> pConnectTimeout <|?> (Nothing, Just <$> pConnectPort) <|?> (Nothing, Just <$> pBindto) -- | Parses a @SMTP_CHECK@. pSmtpCheck :: Stream s Identity Token => Parsec s u SmtpCheck pSmtpCheck = do blockId "SMTP_CHECK" braces $ SmtpCheck <$> many pSmtpCheckOption pSmtpCheckOption :: Stream s Identity Token => Parsec s u SmtpCheckOption pSmtpCheckOption = choice [ SmtpConnectTimeout <$> pConnectTimeout , SmtpHost <$> pHost , SmtpRetry <$> pRetry , SmtpDelayBeforeRetry <$> pDelayBeforeRetry , SmtpHeloName <$> pSmtpHeloName ] -- | Parses a @host@. pHost :: Stream s Identity Token => Parsec s u Host pHost = do blockId "host" braces $ permute $ Host <$?> (Nothing, Just <$> pHostIp) <|?> (Nothing, Just <$> pConnectPort) <|?> (Nothing, Just <$> pBindto) pHostIp :: Stream s Identity Token => Parsec s u IPAddr pHostIp = do identifier "connect_ip" value pIPAddr pMiscCheck :: Stream s Identity Token => Parsec s u MiscCheck pMiscCheck = do blockId "MISC_CHECK" braces $ permute $ MiscCheck <$$> pMiscPath <|?> (Nothing, Just <$> pMiscTimeout) <|?> (Nothing, Just <$> pMiscDynamic) -- utils satisfy :: Stream s Identity Token => (Token -> Bool) -> Parsec s u Token satisfy f = P.token (show . snd) fst (\t -> if f t then Just t else Nothing) match :: TokenType -> Token -> Bool match tt (_, tt') = tt == tt' identifier :: Stream s Identity Token => String -> Parsec s u Token identifier = satisfy . match . Identifier blockId :: Stream s Identity Token => String -> Parsec s u Token blockId = satisfy . match . BlockId openBrace :: Stream s Identity Token => Parsec s u Token openBrace = satisfy $ match OpenBrace closeBrace :: Stream s Identity Token => Parsec s u Token closeBrace = satisfy $ match CloseBrace braces :: Stream s Identity Token => Parsec s u r -> Parsec s u r braces = between openBrace closeBrace value :: Stream s Identity Token => Parsec String () a -> ParsecT s u Identity a value p = do tok <- satisfy match case parse p (sourceName $ fst tok) (unValue $ snd tok) of Right r -> return r Left err -> error $ show err where match :: Token -> Bool match (_, Value s) | Right _ <- parse (p <* eof) "" s = True | otherwise = False match _ = False quoted :: Stream s Identity Token => Parsec String () a -> ParsecT s u Identity a quoted p = do tok <- satisfy match case parse p (sourceName $ fst tok) (unQuoted $ snd tok) of Right r -> return r Left err -> error $ show err where match :: Token -> Bool match (_, Quoted s) | Right _ <- parse (p <* eof) "" s = True | otherwise = False match _ = False -- blocks pSmtpServer :: Stream s Identity Token => Parsec s u IPAddr pSmtpServer = do identifier "smtp_server" value pIPAddr pVrrpState :: Stream s Identity Token => Parsec s u VrrpState pVrrpState = do identifier "state" pViMaster <|> pViBackup where pViMaster = value $ string "MASTER" >> return VrrpMaster pViBackup = value $ string "BACKUP" >> return VrrpBackup pVirtualRouterId :: Stream s Identity Token => Parsec s u Vrid pVirtualRouterId = do identifier "virtual_router_id" value $ Vrid . read <$> many1 digit pPriority :: Stream s Identity Token => Parsec s u Priority pPriority = do identifier "priority" value $ Priority . read <$> many1 digit pIpaddress :: Stream s Identity Token => Parsec s u Ipaddress pIpaddress = do dst <- value pCIDR brd <- optionMaybe $ value (string "brd") >> value pIPAddr dev <- optionMaybe $ value (string "dev") >> value stringLiteral scope <- optionMaybe $ value (string "scope") >> value stringLiteral label <- optionMaybe $ value (string "label") >> value stringLiteral lookAhead $ () <$ closeBrace <|> () <$ value pCIDR return $ Ipaddress dst brd dev scope label pVirtualIpaddress :: Stream s Identity Token => Parsec s u [Ipaddress] pVirtualIpaddress = do blockId "virtual_ipaddress" braces $ many1 pIpaddress pVirtualIpaddressExcluded :: Stream s Identity Token => Parsec s u [Ipaddress] pVirtualIpaddressExcluded = do blockId "virtual_ipaddress_excluded" braces $ many1 pIpaddress pVrrpNotify :: Stream s Identity Token => Parsec s u VrrpNotify pVrrpNotify = choice [ identifier "notify" >> choice [ value (Notify <$> many1 anyChar) , quoted (Notify <$> many1 anyChar) ] , identifier "notify_master" >> choice [ value (NotifyMaster <$> many1 anyChar) , quoted (NotifyMaster <$> many1 anyChar) ] , identifier "notify_backup" >> choice [ value (NotifyBackup <$> many1 anyChar) , quoted (NotifyBackup <$> many1 anyChar) ] , identifier "notify_fault" >> choice [ value (NotifyFault <$> many1 anyChar) , quoted (NotifyFault <$> many1 anyChar) ] ] pRealServerNotify :: Stream s Identity Token => Parsec s u RealServerNotify pRealServerNotify = choice [ identifier "notify_up" >> choice [ value (NotifyUp <$> many1 anyChar) , quoted (NotifyUp <$> many1 anyChar) ] , identifier "notify_down" >> choice [ value (NotifyDown <$> many1 anyChar) , quoted (NotifyDown <$> many1 anyChar) ]] pAuth :: Stream s Identity Token => Parsec s u Auth pAuth = do blockId "authentication" braces $ permute $ Auth <$$> pAuthType <||> pAuthPass pAuthType :: Stream s Identity Token => Parsec s u AuthType pAuthType = do identifier "auth_type" pPASS <|> pAH where pPASS = value $ string "PASS" >> return PASS pAH = value $ string "AH" >> return AH pLvsMethod :: Stream s Identity Token => Parsec s u LvsMethod pLvsMethod = do identifier "lvs_method" <|> identifier "lb_kind" choice [ value (string "DR") >> return DR , value (string "TUN") >> return TUN , value (string "NAT") >> return NAT ] pLvsSched :: Stream s Identity Token => Parsec s u LvsSched pLvsSched = do identifier "lvs_sched" <|> identifier "lb_algo" choice [ value (try (string "rr")) >> return RR , value (try (string "wrr")) >> return WRR , value (try (string "lc")) >> return LC , value (try (string "wlc")) >> return WLC , value (try (string "lblc")) >> return LBLC , value (try (string "sh")) >> return SH , value (try (string "dh")) >> return DH ] pProtocol :: Stream s Identity Token => Parsec s u Protocol pProtocol = do identifier "protocol" choice [ value (string "TCP") >> return TCP , value (string "UDP") >> return UDP ] -- CIDR parsers pSorryServer :: Stream s Identity Token => Parsec s u L4Addr pSorryServer = do identifier "sorry_server" L4Addr <$> value pIPAddr <*> value (PortNumber . read <$> many1 digit) -- IP Address parsers pMcastSrcIp :: Stream s Identity Token => Parsec s u IPAddr pMcastSrcIp = do identifier "mcast_src_ip" value pIPAddr pBindto :: Stream s Identity Token => Parsec s u IPAddr pBindto = do identifier "bindto" value pIPAddr -- Integer parsers natural :: Parser Integer natural = read <$> many1 digit integer :: Parser Integer integer = do sign <- option id (negate <$ char '-') sign . read <$> many1 digit pGarpMasterDelay :: Stream s Identity Token => Parsec s u Integer pGarpMasterDelay = do identifier "garp_master_delay" value natural pAdvertInt :: Stream s Identity Token => Parsec s u Integer pAdvertInt = do identifier "advert_int" value natural pPreemptDelay :: Stream s Identity Token => Parsec s u Integer pPreemptDelay = do identifier "preempt_delay" value natural pWeight :: Stream s Identity Token => Parsec s u Integer pWeight = do identifier "weight" value natural pConnectPort :: Stream s Identity Token => Parsec s u Integer pConnectPort = do identifier "connect_port" value natural pConnectTimeout :: Stream s Identity Token => Parsec s u Integer pConnectTimeout = do identifier "connect_timeout" value natural pSmtpConnectTimeout :: Stream s Identity Token => Parsec s u Integer pSmtpConnectTimeout = do identifier "smtp_connect_timeout" value natural pMiscTimeout :: Stream s Identity Token => Parsec s u Integer pMiscTimeout = do identifier "misc_timeout" value natural pNbGetRetry :: Stream s Identity Token => Parsec s u Integer pNbGetRetry = do identifier "nb_get_retry" value natural pRetry :: Stream s Identity Token => Parsec s u Integer pRetry = do identifier "retry" value natural pDelayBeforeRetry :: Stream s Identity Token => Parsec s u Integer pDelayBeforeRetry = do identifier "delay_before_retry" value natural pDelayLoop :: Stream s Identity Token => Parsec s u Integer pDelayLoop = do identifier "delay_loop" value natural pPersistenceTimeout :: Stream s Identity Token => Parsec s u Integer pPersistenceTimeout = do identifier "persistence_timeout" value natural pQuorum :: Stream s Identity Token => Parsec s u Integer pQuorum = do identifier "quorum" value natural pHysteresis :: Stream s Identity Token => Parsec s u Integer pHysteresis = do identifier "hysteresis" value natural -- [String] parsers pTrackInterface :: Stream s Identity Token => Parsec s u [TrackInterface] pTrackInterface = do blockId "track_interface" braces $ many1 $ do iface <- value stringLiteral weight <- optionMaybe $ identifier "weight" >> value integer return $ TrackInterface iface weight pTrackScript :: Stream s Identity Token => Parsec s u [TrackScript] pTrackScript = do blockId "track_script" braces $ many1 $ do script <- value stringLiteral weight <- optionMaybe $ identifier "weight" >> value integer return $ TrackScript script weight pVirtualRoutes :: Stream s Identity Token => Parsec s u [Route] pVirtualRoutes = do blockId "virtual_routes" braces $ many1 (pRoute <|> pBlackhole) pNotificationEmail :: Stream s Identity Token => Parsec s u [String] pNotificationEmail = do blockId "notification_email" braces $ many $ value stringLiteral -- String parsers stringLiteral :: Parser String stringLiteral = many1 anyChar pInterface :: Stream s Identity Token => Parsec s u String pInterface = do identifier "interface" value stringLiteral pLvsSyncDaemonInterface :: Stream s Identity Token => Parsec s u String pLvsSyncDaemonInterface = do identifier "lvs_sync_daemon_interface" value stringLiteral pAuthPass :: Stream s Identity Token => Parsec s u String pAuthPass = do identifier "auth_pass" value stringLiteral pSmtpHeloName :: Stream s Identity Token => Parsec s u String pSmtpHeloName = do identifier "helo_name" value stringLiteral <|> quoted stringLiteral pMiscPath :: Stream s Identity Token => Parsec s u String pMiscPath = do identifier "misc_path" value stringLiteral <|> quoted stringLiteral pPersistenceGranularity :: Stream s Identity Token => Parsec s u String pPersistenceGranularity = do identifier "persistence_granularity" value stringLiteral pVirtualHost :: Stream s Identity Token => Parsec s u String pVirtualHost = do identifier "virtualhost" value stringLiteral pNotificationEmailFrom :: Stream s Identity Token => Parsec s u String pNotificationEmailFrom = do identifier "notification_email_from" value stringLiteral pRouterId :: Stream s Identity Token => Parsec s u String pRouterId = do identifier "router_id" <|> identifier "lvs_id" value stringLiteral pQuorumUp :: Stream s Identity Token => Parsec s u String pQuorumUp = do identifier "quorum_up" value stringLiteral pQuorumDown :: Stream s Identity Token => Parsec s u String pQuorumDown = do identifier "quorum_down" value stringLiteral -- unit parsers pHaSuspend :: Stream s Identity Token => Parsec s u () pHaSuspend = () <$ identifier "ha_suspend" pAlpha :: Stream s Identity Token => Parsec s u () pAlpha = () <$ identifier "alpha" pOmega :: Stream s Identity Token => Parsec s u () pOmega = () <$ identifier "omega" pInhibitOnFailure :: Stream s Identity Token => Parsec s u () pInhibitOnFailure = () <$ identifier "inhibit_on_failure" pDontTrackPrimary :: Stream s Identity Token => Parsec s u () pDontTrackPrimary = () <$ identifier "dont_track_primary" pNoPreempt :: Stream s Identity Token => Parsec s u () pNoPreempt = () <$ identifier "nopreempt" pDebug :: Stream s Identity Token => Parsec s u () pDebug = () <$ identifier "debug" pMiscDynamic :: Stream s Identity Token => Parsec s u () pMiscDynamic = () <$ identifier "misc_dynamic" pSmtpAlert :: Stream s Identity Token => Parsec s u () pSmtpAlert = () <$ identifier "smtp_alert"
maoe/text-keepalived
src/Text/Keepalived/Parser.hs
bsd-3-clause
25,157
0
29
7,327
7,196
3,504
3,692
540
3
{-# LANGUAGE LambdaCase, RecordWildCards #-} module Mote.GhcUtil where import Bag (Bag, foldrBag) import Control.Monad.Error import ErrUtils (pprErrMsgBag) import GHC hiding (exprType) import Name import Outputable (showSDoc, vcat) import Parser (parseStmt) import RdrName (RdrName (Exact), extendLocalRdrEnvList) import SrcLoc (realSrcSpanEnd, realSrcSpanStart) import TcRnDriver (tcRnExpr) import TcRnMonad import Type (isPredTy) import TypeRep (Type(..)) import Mote.Types import Mote.Util exprType :: String -> M Type exprType = hsExprType <=< parseExpr hsExprType :: LHsExpr RdrName -> M Type hsExprType expr = do hsc_env <- lift getSession fs <- lift getSessionDynFlags ((_warns, errs), mayTy) <- liftIO $ tcRnExpr hsc_env expr case mayTy of Just t -> return t Nothing -> throwError . GHCError . showSDoc fs . vcat $ pprErrMsgBag errs parseExpr :: String -> M (LHsExpr RdrName) parseExpr e = lift (runParserM parseStmt e) >>= \case Right (Just (L _ (BodyStmt expr _ _ _))) -> return expr Right _ -> throwError $ ParseError "Expected body statement." Left parseError -> throwError $ ParseError parseError -- TcRnMonad.newUnique -- RnTypes.filterInScope has clues -- put RdrName of relevant tyvars into LocalRdrEnv -- RdrName.elemLocalRdrEnv -- extendLocalRdrEnv -- for debugging withStrTyVarsInScope :: [Name] -> TcRn a -> TcRn a withStrTyVarsInScope = withTyVarsInScope -- should actually use TcEnv/tcExtendTyVarEnv. I doubt this will work as is. -- looks like I want RnEnv/bindLocatedLocals withTyVarsInScope :: [Name] -> TcRn a -> TcRn a withTyVarsInScope tvNames inner = do lcl_rdr_env <- TcRnMonad.getLocalRdrEnv TcRnMonad.setLocalRdrEnv (extendLocalRdrEnvList lcl_rdr_env tvNames) inner rdrNameToName :: HasOccName name => name -> IOEnv (Env gbl lcl) Name rdrNameToName rdrName = do u <- newUnique return $ Name.mkSystemName u (occName rdrName) allBag :: (a -> Bool) -> Bag a -> Bool allBag p = foldrBag (\x r -> if p x then r else False) True nameVar :: Name -> Located (HsExpr RdrName) nameVar = noLoc . HsVar . Exact toSpan :: SrcSpan -> ((Int, Int), (Int, Int)) toSpan (RealSrcSpan rss) = (toPos (realSrcSpanStart rss), toPos (realSrcSpanEnd rss)) toSpan UnhelpfulSpan {} = error "Unhelpful span." toPos :: RealSrcLoc -> (Int, Int) toPos rsl = (srcLocLine rsl, srcLocCol rsl) -- needed for refine and the real version of getting hole env inHoleEnv :: TypecheckedModule -> HoleInfo -> TcRn a -> M a inHoleEnv tcmod hi tcx = do hsc_env <- lift getSession let (gbl_env, _) = tm_internals_ tcmod lcl_env = ctLocEnv . ctLoc $ holeCt hi ((_warns, errs), xMay) <- liftIO . runTcInteractive hsc_env $ do setEnvs (gbl_env, lcl_env) $ tcx fs <- lift getSessionDynFlags maybe (throwErrs fs errs) return xMay where throwErrs fs = throwError . GHCError . showSDoc fs . vcat . pprErrMsgBag -- (var, Type) withBindings :: GhcMonad m => [(String, String)] -> m a -> m a withBindings bs mx = do env0 <- getSession mapM_ (\b -> runStmt (mkBind b) RunToCompletion) bs x <- mx setSession env0 -- this is maybe a little violent... return x where mkBind (x, t) = "let " ++ x ++ " = undefined :: " ++ t discardConstraints :: TcRn a -> TcRn a discardConstraints = fmap fst . captureConstraints splitPredTys :: Type -> ([PredType], Type) splitPredTys (FunTy t1 t2) | isPredTy t1 = let (ps, t) = splitPredTys t2 in (t1:ps, t) splitPredTys t = ([], t)
imeckler/mote
Mote/GhcUtil.hs
bsd-3-clause
3,757
0
15
940
1,172
603
569
80
3
{-# LANGUAGE OverloadedStrings #-} module CodeWidget.CodeWidgetInternal where import qualified Graphics.UI.Gtk as G import qualified Graphics.UI.Gtk.SourceView as G import Text.Parsec import Text.Parsec.Pos --import Data.List import Data.IORef import Control.Monad import Control.Monad.IO.Class import Util import CodeWidget.CodeWidgetTypes import CodeWidget.CodeWidgetUtil cvCurPage :: CodeView -> IO PageID cvCurPage cv = do G.notebookGetCurrentPage $ cvNotebook cv cvSetMyPage :: CodeView -> PageContext -> IO () cvSetMyPage cv pg = do let nbpg = cvNotebook cv let pgid = pgID pg G.notebookSetCurrentPage nbpg pgid rgnChangeCB :: CodeView -> PageContext -> G.TextIter -> IO () rgnChangeCB cv pg ti = do ploc <- posFromIter pg ti mrc <- cvWhoHoldsPos pg ploc case mrc of Nothing -> return () Just rc -> case rcCallBack rc of Nothing -> return () Just x -> do _ <- x return () -- Individual Signal Handlers bufSigDeleteRange :: RCodeView -> G.TextIter -> G.TextIter -> IO () bufSigDeleteRange ref ifm ito = do cv <- readIORef ref nbi <- cvCurPage cv case getContexts cv (Region nbi rootRegion) of Nothing -> return () Just (pg,rc) -> do rgnChangeCB cv pg ifm bufSigInsertText :: RCodeView -> G.TextIter -> String -> IO () bufSigInsertText ref iter txt = do cv <- readIORef ref nbi <- cvCurPage cv case getContexts cv (Region nbi rootRegion) of Nothing -> return () Just (pg,rc) -> do rgnChangeCB cv pg iter --make sure background tagging grows with region mrgn <- cvWhoHoldsIter pg iter itxt <- dumpIter iter case mrgn of Nothing -> return () Just x -> do rgnBg pg x viewSigPasteClibB :: RCodeView -> IO () viewSigPasteClibB ref = do cv <- readIORef ref nbi <- cvCurPage cv case getContexts cv (Region nbi rootRegion) of Nothing -> return () Just (pg,rc) -> do cvSetEditFlags pg viewKeyRelease :: RCodeView -> G.EventM G.EKey Bool viewKeyRelease ref = do cv <- liftIO $ readIORef ref pi <- liftIO $ cvCurPage cv case getPage cv pi of Nothing -> return False Just pg -> do cp <- liftIO $ cvCursorPos pg mrc <- liftIO $ cvWhoHoldsPos pg cp case mrc of Nothing -> return False Just rc -> do emp <- liftIO $ rgnEmpty pg rc if emp then do ks <- G.eventKeyName kv <- G.eventKeyVal let mc = G.keyToChar kv case mc of Nothing -> if ks == "Return" then do si <- liftIO $ rgnStart pg rc liftIO $ cvRgnInsertText pg si "\n" liftIO $ cvRgnEditable pg rc return True else return False Just c -> do si <- liftIO $ rgnStart pg rc liftIO $ cvRgnInsertText pg si [c] liftIO $ cvRgnEditable pg rc return True else return False cvRgnCreateEmpty :: RCodeView -> CwRef -> SourcePos -> Bool -> IO() -> IO Region cvRgnCreateEmpty ref (pg, parent) from ed f = do cv <- readIORef ref let nextr = pgNextRegion pg let rgn = Region (pgID pg) nextr let currgns = pgRegions pg smk <- newLeftMark emk <- newRightMark bgt <- G.textTagNew Nothing let edepth = eRgnNestDepth pg (rcRegion parent) let bcolor = getRgnBgColor edepth G.set bgt [G.textTagBackground G.:= bcolor] G.textTagTableAdd (pgTagTable pg) bgt G.textTagSetPriority bgt 2 rfm <- rgnMapPos pg parent from itfm <- rootIterFromPos pg rfm G.textBufferAddMark (pgBuffer pg) smk itfm G.textBufferAddMark (pgBuffer pg) emk itfm let newrgn = RegionContext { rcRegion = nextr , rcPage = pgID pg , rcParent = rcRegion parent , rcEditable = ed , rcStart = smk , rcEnd = emk , rcInsert = Nothing , rcStartPos = rfm , rcCallBack = Just f , rcInitWidth = 0 , rcInitHeight = 0 , rcBgTag = bgt } let newpg = pg { pgNextRegion = nextr + 1, pgRegions = newrgn:currgns } writeIORef ref cv { cvPages = newpg:(cvPages cv) } cvSetEditFlags newpg return rgn --Create new region from existing region - supports 3 cases: new/parent, parent/new, and parent/new/parent. --In addition, if not cvRgnCreateFrom :: RCodeView -> CwRef -> SourcePos -> SourcePos -> Bool -> Bool -> IO () -> IO Region cvRgnCreateFrom ref (pg,rc) from to ed sib f = do cv <- readIORef ref let nextr = pgNextRegion pg let rgn = Region (pgID pg) nextr let othrgns = otherRegions pg (rcRegion rc) let par = rcRegion rc smk <- newLeftMark emk <- newRightMark bgt <- G.textTagNew Nothing let edepth = eRgnNestDepth pg $ if' (sib == False) par (rcParent rc) let bcolor = getRgnBgColor edepth G.set bgt [ G.textTagBackground G.:= bcolor ] G.textTagTableAdd (pgTagTable pg) bgt G.textTagSetPriority bgt 2 rfm <- rgnMapPos pg rc from rto <- rgnMapPos pg rc to st <- rgnStartPos pg rc nd <- rgnEndPos pg rc let h = (sourceLine rto) - (sourceLine rfm) let c = (sourceColumn rto) - (sourceColumn rfm) if st == rfm then do {-- if startpos == the parent region start, then the new region goes ahead of the current region the new region gets the parent's rcStart and rcStartPos. --} --mpStrLn $ "cvRgnCreateFrom<head> : " ++ show rfm ++ " " ++ show rto itto <- rootIterFromPos pg rto G.textBufferAddMark (pgBuffer pg) smk itto -- new start mark for parent G.textBufferAddMark (pgBuffer pg) emk itto -- new end mark for new region let newrgn = RegionContext { rcRegion = nextr , rcPage = pgID pg , rcParent = if' (sib == False) par (rcParent rc) , rcEditable = ed , rcStart = (rcStart rc) , rcEnd = emk , rcInsert = Nothing , rcStartPos = (rcStartPos rc) , rcCallBack = Just f , rcInitWidth = c , rcInitHeight = h , rcBgTag = bgt } let newPar = rc { rcStart = smk , rcStartPos = rfm } let newpg = pg { pgNextRegion = nextr + 1, pgRegions = newrgn:newPar:othrgns } let ops = otherPages cv (pgID newpg) let newcv = cv {cvPages = newpg:ops} writeIORef ref newcv cvSetEditFlags newpg return rgn else if nd == rto then do {-- If endpos = parent's endpos, new region goes after parent. new region gets parent's rcEnd, parent gets new rcEnd from newregion's startpos --} --mpStrLn $ "cvRgnCreateFrom<tail> : " ++ show rfm ++ " " ++ show rto itfm <- rootIterFromPos pg rfm G.textBufferAddMark (pgBuffer pg) smk itfm G.textBufferAddMark (pgBuffer pg) emk itfm let newrgn = RegionContext { rcRegion = nextr , rcPage = pgID pg , rcParent = if' (sib == False) par (rcParent rc) , rcEditable = ed , rcStart = smk , rcEnd = (rcEnd rc) , rcInsert = Nothing , rcStartPos = rfm , rcCallBack = Just f , rcInitWidth = c , rcInitHeight = h , rcBgTag = bgt } let newPar = rc { rcEnd = emk} let newpg = pg { pgNextRegion = nextr + 1, pgRegions = newrgn:newPar:othrgns } let ops = otherPages cv (pgID newpg) let newcv = cv {cvPages = newpg:ops} writeIORef ref newcv cvSetEditFlags newpg return rgn else do -- Nothing special - parent area becomes new subregion --mpStrLn $ "cvRgnCreateFrom<emb> : " ++ show rfm ++ " " ++ show rto itfm <- rootIterFromPos pg rfm itto <- rootIterFromPos pg rto G.textBufferAddMark (pgBuffer pg) smk itfm G.textBufferAddMark (pgBuffer pg) emk itto let newrgn = RegionContext { rcRegion = nextr , rcPage = pgID pg , rcParent = par , rcEditable = ed , rcStart = smk , rcEnd = emk , rcInsert = Nothing , rcStartPos = rfm , rcCallBack = Just f , rcInitWidth = c , rcInitHeight = h , rcBgTag = bgt } let newpg = pg { pgNextRegion = nextr + 1, pgRegions = newrgn:rc:othrgns } let ops = otherPages cv (pgID newpg) let newcv = cv {cvPages = newpg:ops} writeIORef ref newcv cvSetEditFlags newpg return rgn -- handle GTK "editable" marking for all regions cvSetEditFlags :: PageContext -> IO () cvSetEditFlags pg = do case getRegion pg rootRegion of Nothing -> error "no root region" Just r -> cvRgnStatic pg r mapM_ (cvRgnEditable pg) (editableRgns pg) -- setup GTK goodies to make a region static cvRgnStatic :: PageContext -> RegionContext -> IO () cvRgnStatic pg rc = do si <- rgnStart pg rc ei <- rgnEnd pg rc let buf = pgBuffer pg let tag = pgEditTag pg G.textBufferRemoveTag buf tag si ei G.textBufferApplyTag buf tag si ei mapM_ (\x -> do G.textMarkSetVisible (rcStart x) False G.textMarkSetVisible (rcEnd x) False si <- rgnStart pg x ei <- rgnEnd pg x G.textBufferRemoveTag (pgBuffer pg) (rcBgTag x) si ei ) (pgRegions pg) -- setup GTK goodies to make a region editable cvRgnEditable :: PageContext -> RegionContext -> IO () cvRgnEditable pg rc = do si <- rgnStart pg rc ei <- rgnEnd pg rc ssi <- dumpIter si eei <- dumpIter ei mpStrLn $ " cvRgnEditable: " ++ show (rcRegion rc) ++ " Fm:" ++ ssi ++ " To:" ++ eei G.textBufferRemoveTag (pgBuffer pg) (pgEditTag pg) si ei G.textBufferApplyTag (pgBuffer pg) (rcBgTag rc) si ei G.textMarkSetVisible (rcStart rc) True G.textMarkSetVisible (rcEnd rc) True -- map a Region.SourcePos to a global buffer position - makes adjustments for other subregions rgnMapPos :: PageContext -> RegionContext -> SourcePos -> IO SourcePos rgnMapPos pg rc p = do p2 <- rgnStartPos pg rc let nl = (sourceLine p) + (sourceLine p2) - 1 let nc = if sourceLine p == 1 then (sourceColumn p) + (sourceColumn p2) - 1 else sourceColumn p let np = newPos (sourceName p) nl nc cvAllowForPriorSubs pg rc np -- check if a given root-relative position is contained in the specified sub-region cvRgnPosInside :: PageContext -> RegionContext -> SourcePos -> IO Bool cvRgnPosInside pg rc pos = do sp <- rgnStartPos pg rc ep <- rgnEndPos pg rc return $ if' ((sp <= pos) && (pos <= ep)) True False -- Adjust a region position to account for a preceeding subregion -- (returns (delta-y, delta-x), e.g., (0,0) if not adjustment is needed). cvAdjustForSub :: PageContext -> SourcePos -> RegionContext -> IO (Int, Int) cvAdjustForSub pg pos rc = do let ln = rgnInitLine pg rc col = sourceColumn $ rgnInitPos pg rc -- let fn = sourceName pos let rn = rcRegion rc if rn == rootRegion then do return (0,0) else if sourceLine pos > ln then do h <- rgnHeight pg rc --let nln = (sourceLine pos) + h -- let np = newPos fn nln (sourceColumn pos) mpStrLn $ "cvAdjustForSub:(" ++ show rn ++ "):" ++ show pos ++ " H:" ++ show h return (h, 0) else if sourceLine pos == ln && sourceColumn pos > col then do w <- rgnWidth pg rc h <- rgnHeight pg rc -- let ncol = (sourceColumn pos) + w -- let np = newPos fn (h + (sourceLine pos)) ncol mpStrLn $ "cvAdjustForSub:(" ++ show rn ++ "):" ++ show pos ++ " H:" ++ show h ++ " W:" ++ show w return (h, w) else do mpStrLn $ "cvAdjustForSub:(" ++ show rn ++ ") N/A :" ++ show ln return (0,0) -- Adjust a SourcePos for any edits done to editable sub-regions cvAllowForPriorSubs :: PageContext -> RegionContext -> SourcePos -> IO SourcePos cvAllowForPriorSubs pg rc p = do (dy, dx) <- (liftM ((mapSnd sum) . (mapFst sum) . unzip)) $ mapM (cvAdjustForSub pg p) (childRegions pg rc) return $ newPos (sourceName p) (sourceLine p + dy) (sourceColumn p + dx) -- If region does not yet have an Insertion mark, create one and add it. Otherwise, return the existing one cvInsertMark :: RCodeView -> PageContext -> RegionContext -> IO G.TextMark cvInsertMark ref pg rc = do cv <- readIORef ref case (rcInsert rc) of Nothing -> do mk <- newRightMark st <- rgnStart pg rc pos <- posFromIter pg st --mpStrLn $ "cvInsertMark:" ++ show (rcRegion rc) ++ " T:" ++ show pos G.textBufferAddMark (pgBuffer pg) mk st let nrc = rc {rcInsert = (Just mk)} let orc = otherRegions pg (rcRegion nrc) let npg = pg {pgRegions = nrc:orc} let orp = otherPages cv (pgID pg) let ncv = cv { cvPages = npg:orp} writeIORef ref ncv return mk Just x -> do return x -- create the initial root region mkRootRegion :: PageID -> G.SourceBuffer -> G.TextTagTable -> IO RegionContext mkRootRegion p b t = do smk <- newLeftMark emk <- newRightMark bgt <- G.textTagNew Nothing vmk <- G.textTagNew Nothing G.set bgt [G.textTagBackground G.:= (getRgnBgColor rootRegion)] G.textTagTableAdd t bgt G.textTagSetPriority bgt 1 i1 <- G.textBufferGetStartIter b i2 <- G.textBufferGetStartIter b G.textBufferAddMark b smk i1 G.textBufferAddMark b emk i2 let pos = newPos "" 1 1 let r = RegionContext { rcRegion = rootRegion , rcPage = p , rcParent = noRegion , rcEditable = False , rcStart = smk , rcEnd = emk , rcInsert = Nothing , rcStartPos = pos , rcCallBack = Nothing , rcInitWidth = 0 , rcInitHeight = 0 , rcBgTag = bgt } return r -- get contents of entire text buffer cvGetAllText :: PageContext -> RegionID -> IO String cvGetAllText pg rgn = do case getRegion pg rgn of Nothing -> error "cvGetAllText: region not found" Just r -> do it1 <- rgnStart pg r it2 <- rgnEnd pg r cvRgnGetText pg it1 it2 False -- wrapper around G.textBufferGetText - debugging aid cvRgnGetText :: PageContext -> G.TextIter -> G.TextIter -> Bool -> IO String cvRgnGetText pg es ee b = do spos <- posFromIter pg es epos <- posFromIter pg ee --mpStrLn $ "GET TEXT - S:" ++ (show spos) ++ " E:" ++ (show epos) G.textBufferGetText (pgBuffer pg) es ee b -- wrapper around G.textBufferInsertText - debugging aid cvRgnInsertText :: PageContext -> G.TextIter -> String -> IO () cvRgnInsertText pg es t = do spos <- posFromIter pg es --mpStrLn $ "INSERT TEXT - S:" ++ (show spos) ++ " T:" ++ t G.textBufferInsert (pgBuffer pg) es t -- Build a string from the gaps between the regions in the list cvSubRgnGapText :: PageContext -> [RegionContext] -> IO String cvSubRgnGapText _ [] = do return "" cvSubRgnGapText _ (_:[]) = do return "" cvSubRgnGapText pg (x:xs) = do es <- rgnEnd pg x let x2 = head xs --mpStrLn $ "cvSubRgnGapText: regions:" ++ show (rcRegion x) ++","++ show (rcRegion x2) ee <- rgnStart pg x2 s1 <- cvRgnGetText pg es ee False s2 <- cvSubRgnGapText pg xs return $ s1 ++ s2 -- Get the text for this region, ignoring text in any sub-regions cvSubRgnText :: PageContext -> RegionContext -> IO String cvSubRgnText pg rc = do let sr = subRegions pg rc case sr of [] -> do es <- (rgnStart pg rc) ee <- rgnEnd pg rc cvRgnGetText pg es ee False (x:[]) -> do es1 <- rgnStart pg rc ee1 <- rgnStart pg x es3 <- rgnEnd pg x ee3 <- rgnEnd pg rc --mpStrLn "cvSubRgnText: single subregion" s1 <- cvRgnGetText pg es1 ee1 False s3 <- cvRgnGetText pg es3 ee3 False return $ s1 ++ s3 (x:xs) -> do es1 <- rgnStart pg rc ee1 <- rgnStart pg x let x2 = last xs es3 <- rgnEnd pg x2 ee3 <- rgnEnd pg rc --mpStrLn "cvSubRgnText: multiple subregions" s1 <- cvRgnGetText pg es1 ee1 False s2 <- cvSubRgnGapText pg (x:xs) s3 <- cvRgnGetText pg es3 ee3 False return $ s1 ++ s2 ++ s3 -- loop through all regions to find the one that pos belongs to cvWhoHoldsIter :: PageContext -> G.TextIter -> IO (Maybe RegionContext) cvWhoHoldsIter pg iter = do ln <- G.textIterGetLine iter co <- G.textIterGetLineOffset iter let fn = pgFileName pg cvWhoHoldsPos' pg (newPos fn (ln + 1) (co + 1)) (editableRgns pg) cvWhoHoldsPos :: PageContext -> SourcePos -> IO (Maybe RegionContext) cvWhoHoldsPos pg pos = do cvWhoHoldsPos' pg pos (editableRgns pg) cvWhoHoldsPos' :: PageContext -> SourcePos -> [RegionContext] -> IO (Maybe RegionContext) cvWhoHoldsPos' _ _ [] = do return Nothing cvWhoHoldsPos' pg pos (x:xs) = do --rtxt <- dumpRgn cv x --mpStrLn $ "cvWhoHoldsPos': " ++ rtxt ins <- cvRgnPosInside pg x pos if' (ins == True) (return $ Just x) (cvWhoHoldsPos' pg pos xs) cvCursorPos :: PageContext -> IO SourcePos cvCursorPos pg = do mk <- G.textBufferGetInsert (pgBuffer pg) iter <- G.textBufferGetIterAtMark (pgBuffer pg) mk ln <- G.textIterGetLine iter offs <- G.textIterGetLineOffset iter return $ newPos (pgFileName pg) (ln + 1) (offs + 1) dumpIter :: G.TextIter -> IO String dumpIter ti = do ln <- G.textIterGetLine ti co <- G.textIterGetLineOffset ti return $ "[LN:" ++ show (ln + 1) ++ " CO:" ++ show (co + 1) ++ "]" dumpRgns :: PageContext -> IO () dumpRgns pg = do mapM_ (\a -> do t <- dumpRgn pg a putStrLn ("CW# dumpRegions: " ++ t)) (pgRegions pg) -- debugging: display current state of a region dumpRgn :: PageContext -> RegionContext -> IO String dumpRgn pg rgn = do let rs = "#:" ++ show (rcRegion rgn) ++ " " let ps = "P:" ++ show (rcParent rgn) ++ " " let es = "E:" ++ show (rcEditable rgn) ++ " " fi <- rgnStartPos pg rgn let fs = "Fm:" ++ show fi ++ " " ti <- rgnEndPos pg rgn let ts = "To:" ++ show ti ++ " " let ss = "StPos:" ++ show (rcStartPos rgn) ++ " " let ws = "IW:" ++ show (rcInitWidth rgn) ++ " " let hs = "IH:" ++ show (rcInitHeight rgn) ++ " " rh <- rgnHeight pg rgn rw <- rgnWidth pg rgn let rhs = "HT:" ++ show rh ++ " " let rws = "WD:" ++ show rw ++ " " let ed = if' (rcEditable rgn) (show (eRgnNestDepth pg (rcParent rgn))) "" return $ rs ++ ps ++ es ++ fs ++ ts ++ ss ++ ws ++ hs ++ rhs ++ rws ++ ed
termite2/code-widget
CodeWidget/CodeWidgetInternal.hs
bsd-3-clause
25,287
0
28
12,161
6,076
2,915
3,161
403
6
import Data.List isPalindrome :: Integer -> Bool isPalindrome n = let s = show n in reverse s == s largestPalindrome :: Integer -> Integer largestPalindrome e = maximum $ filter isPalindrome [x * y | x <- [100..10^e], y <- [100..10^e], y >= x] main :: IO () main = print $ largestPalindrome 3
JacksonGariety/euler.hs
004.hs
bsd-3-clause
296
0
11
58
141
71
70
7
1
{- | =Basic Elements ==Simple Boxes >>> :{ aa2u "++ +-----+ +--+--+-----+ \n\ \++ +--+ | | | | | \n\ \ | | +--+--+--+--+ \n\ \+---+ | | | | | | \n\ \+---+ +--+ +-----+--+--+ " :} ┌┐ ┌─────┐ ┌──┬──┬─────┐ └┘ └──┐ │ │ │ │ │ │ │ ├──┴──┼──┬──┤ ┌───┐ │ │ │ │ │ │ └───┘ └──┘ └─────┴──┴──┘ ==Rounded Boxes >>> :{ aa2u ".. .-----. .--+--+-----. \n\ \'' '--. | | | | | \n\ \ | | +--+--+--+--+ \n\ \.---. | | | | | | \n\ \'---' '--' '-----+--+--' " :} ╭╮ ╭─────╮ ╭──┬──┬─────╮ ╰╯ ╰──╮ │ │ │ │ │ │ │ ├──┴──┼──┬──┤ ╭───╮ │ │ │ │ │ │ ╰───╯ ╰──╯ ╰─────┴──┴──╯ ==Dotted and double strokes >>> :{ aa2u "++ .-----. +==+==+=====+ \n\ \++ +==+ : | : | | \n\ \ : : +==+==+==+==+ \n\ \+===+ : : | | : | \n\ \+---+ '--' +=====+==+==+ " :} ┌┐ ╭─────╮ ╒══╤══╤═════╕ └┘ ╘══╕ ┆ │ ┆ │ │ ┆ ┆ ╞══╧══╪══╤══╡ ╒═══╕ ┆ ┆ │ │ ┆ │ └───┘ ╰──╯ ╘═════╧══╧══╛ ==Cast shadows >>> :{ aa2u "+-------------+ \n\ \| | \n\ \+---+ +---+# \n\ \ ##| |##### \n\ \ | |# \n\ \ +-----+# \n\ \ ###### " :} ┌─────────────┐ │ │ └───┐ ┌───┘█ ██│ │█████ │ │█ └─────┘█ ██████ =Properties ==Idempotent Already rendered portions are not affected: >>> :{ aa2u "┌┐ ╭─────╮ ╒══╤══╤═════╕ ┌───┐ \n\ \└┘ ╘══╕ ┆ │ ┆ │ │ │ │ \n\ \ ┆ ┆ ╞══╧══╪══╤══╡ │ │█ \n\ \╒═══╕ ┆ ┆ │ │ ┆ │ └───┘█ \n\ \└───┘ ╰──╯ ╘═════╧══╧══╛ ████ " :} ┌┐ ╭─────╮ ╒══╤══╤═════╕ ┌───┐ └┘ ╘══╕ ┆ │ ┆ │ │ │ │ ┆ ┆ ╞══╧══╪══╤══╡ │ │█ ╒═══╕ ┆ ┆ │ │ ┆ │ └───┘█ └───┘ ╰──╯ ╘═════╧══╧══╛ ████ ==Incremental Existing characters can be removed: >>> :{ aa2u "┌──┬ ┬──┐\n\ \ │ │ │\n\ \╞══╪ ╪══╡\n\ \│ \n\ \├──┼ ┼──┤\n\ \ │ │ │\n\ \└──┴ ┴──┘" :} ───┐ ┌──┐ │ │ │ ╒══╛ ╘══╛ │ └──┐ ┌──┐ │ │ │ ───┘ └──┘ New connections can be added: >>> :{ aa2u "┌──┐-┌──┐\n\ \│ │ │ │\n\ \╘══╛=╘══╛\n\ \| : : |\n\ \┌──┐-┌──┐\n\ \│ │ │ │\n\ \└──┘-└──┘" :} ┌──┬─┬──┐ │ │ │ │ ╞══╪═╪══╡ │ ┆ ┆ │ ├──┼─┼──┤ │ │ │ │ └──┴─┴──┘ Existing connections can be altered by replacing/adding characters: >>> :{ aa2u "┌──+──┐ .─────+─────. ┌────┐ \n\ \│ +==+ │ | │ │####│ \n\ \+==+ | │ | │ │# │█ \n\ \└──+─-┘ │ +-----+ └────┘█# \n\ \ +=====+ │ █████# \n\ \╭──+─-╮ │ | │ ##### \n\ \│ | | │ | │ \n\ \╰──+──╯ '───────────' " :} ┌──┬──┐ ╭─────┬─────╮ ┌────┐ │ ╞══╡ │ │ │ │████│ ╞══╡ │ │ │ │ │█ │█ └──┴──┘ │ ├─────┤ └────┘██ ╞═════╡ │ ██████ ╭──┬──╮ │ │ │ █████ │ │ │ │ │ │ ╰──┴──╯ ╰───────────╯ =Limitations Some connections do not work as expected (mostly because the corresponding Unicode characters do not exist), e.g. rounded corners with double-stroke lines, or connection pieces connecting horizontal single- and double-stroke lines: >>> :{ aa2u "--+== .==. .--.--. \n\ \ | | | | | | \n\ \==+-- '==' .--+--' \n\ \ | | | | \n\ \--+== --== '--'--' " :} ──┐══ ╒══╕ ╭──╮──╮ │ │ │ │ │ │ ══├── ╘══╛ ╰──┼──╯ │ │ │ │ ──┘══ ──══ ╰──╰──╯ -} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} module Text.AsciiArt where import Control.Comonad import Data.Maybe -------------------------------------------------------------------------------- -- * Zipper -------------------------------------------------------------------------------- -- | The 'Zipper' is assumed to be infinite, i.e. filled with empty values -- outside the defined area. data Zipper a = Zipper { before :: [a] , current :: a , after :: [a] } deriving (Functor) moveBefore, moveAfter :: Zipper a -> Zipper a moveBefore zipper@Zipper { before = a : as, current = b, after = cs } = zipper { before = as, current = a, after = b : cs } moveAfter zipper@Zipper { before = as, current = b, after = c : cs } = zipper { before = b : as, current = c, after = cs } -- | Renders the 'current' and the @n - 1@ elements 'after' as list. zipperToList :: Int -> Zipper a -> [a] zipperToList n Zipper{..} = current : take (n - 1) after -- | An infinite 'Zipper' filled with @a@s. zipperOf :: a -> Zipper a zipperOf a = Zipper { before = repeat a, current = a, after = repeat a } -- | Takes a list and creates a 'Zipper' from it. The 'current' element will be -- the 'head' of the list, and 'after' that 'tail'. The rest will be filled with -- @a@s to an infinite 'Zipper'. zipperFromList :: a -> [a] -> Zipper a zipperFromList a = \case [] -> zipperOf a b : bs -> (zipperOf a) { current = b, after = bs ++ repeat a } instance Comonad Zipper where extract = current extend f zipper = fmap f $ Zipper { before = iterate1 moveBefore zipper , current = zipper , after = iterate1 moveAfter zipper } where iterate1 f x = tail (iterate f x) -------------------------------------------------------------------------------- -- * Plane (two-dimensional 'Zipper') -------------------------------------------------------------------------------- -- | A plane is a 'Zipper' of 'Zipper's. The outer layer zips through lines -- (up\/down), the inner layer through columns (left\/right). -- Like the 'Zipper', the 'Plane' is assumed to be infinite in all directions. newtype Plane a = Plane { unPlane :: Zipper (Zipper a) } deriving (Functor) moveLeft, moveRight, moveUp, moveDown :: Plane a -> Plane a moveLeft = Plane . fmap moveBefore . unPlane moveRight = Plane . fmap moveAfter . unPlane moveUp = Plane . moveBefore . unPlane moveDown = Plane . moveAfter . unPlane -- | Renders @m@ lines and @n@ columns as nested list. planeToList :: Int -> Int -> Plane a -> [[a]] planeToList m n (Plane Zipper{..}) = fmap (zipperToList n) $ current : take (m - 1) after -- | An infinite 'Plane' filled with @a@s. planeOf :: a -> Plane a planeOf a = Plane $ Zipper { before = repeat (zipperOf a) , current = zipperOf a , after = repeat (zipperOf a) } -- | Create a 'Plane' from a list of lists, filling the rest with @a@s in all -- directions. planeFromList :: a -> [[a]] -> Plane a planeFromList a = \case [] -> planeOf a as : ass -> Plane $ (zipperOf (zipperOf a)) { current = zipperFromList a as , after = fmap (zipperFromList a) ass ++ repeat (zipperOf a) } instance Comonad Plane where extract = current . current . unPlane extend f plane = fmap f $ Plane $ Zipper { before = fmap foo (iterate1 moveUp plane) , current = foo plane , after = fmap foo (iterate1 moveDown plane) } where foo p = Zipper { before = iterate1 moveLeft p , current = p , after = iterate1 moveRight p } iterate1 f x = tail (iterate f x) -------------------------------------------------------------------------------- -- * Patterns -------------------------------------------------------------------------------- newtype Pattern = Pattern ((Char, Char, Char), (Char, Char, Char), (Char, Char, Char)) patternFromString :: String -> Pattern patternFromString [a, b, c, d, e, f, g, h, i] = Pattern ((a, b, c), (d, e, f), (g, h, i)) patternFromString _ = undefined patternToString :: Pattern -> String patternToString (Pattern ((a, b, c), (d, e, f), (g, h, i))) = [a, b, c, d, e, f, g, h, i] -- | Find the 'Char' to replace the center of a 'Pattern'. lookupPattern :: Pattern -> Maybe Char lookupPattern pattern = case filter (satisfies pattern) patterns of [] -> Nothing a : _ -> Just (snd a) where satisfies :: Pattern -> (Pattern, Char) -> Bool satisfies diagram (pattern, _) = and (zipWith connectsLike (patternToString diagram) (patternToString pattern)) -- | Whether a character can connect to another character. For example, @+@ -- connects both horizontally (like @-@) and vertically (like @|@), so it -- 'connectsLike' @-@, @|@, and of course like itself. connectsLike :: Char -> Char -> Bool char `connectsLike` pattern = case pattern of '-' -> char `elem` ['-', '>', '<', '─'] || char `connectsLike` '+' '=' -> char `elem` ['=', '>', '<', '═'] || char `connectsLike` '+' '|' -> char `elem` ['|', '^', 'v', '│'] || char `connectsLike` ':' || char `connectsLike` '+' ':' -> char `elem` [':', '┆'] '+' -> char `elem` [ '+' , '└', '┘', '┌', '┐' , '╘', '╛', '╒', '╕' , '├', '┤', '┬', '┴', '┼' , '╞', '╡', '╤', '╧', '╪' ] || char `connectsLike` '.' '.' -> char `elem` [ '\'', '.' , '╭', '╮', '╯', '╰' ] '\'' -> char `connectsLike` '.' ' ' -> True other -> char == other -- | The actual pattern definitions. For convenience, the simple patterns are at -- the top, and more complex ones at the bottom. 'lookupPattern' will first try -- the most complex pattern and work its way to the simpler patterns, thus -- avoiding to choose a simpler pattern and forgetting some connection. patterns :: [(Pattern, Char)] patterns = reverse $ fmap (\(a, b) -> (patternFromString a, b)) [ ( " \ \ --\ \ ", '─' ) , ( " \ \-- \ \ ", '─' ) , ( " \ \ ==\ \ ", '═' ) , ( " \ \== \ \ ", '═' ) , ( " \ \ | \ \ | ", '│' ) , ( " | \ \ | \ \ ", '│' ) , ( " \ \ : \ \ | ", '┆' ) , ( " | \ \ : \ \ ", '┆' ) , ( " \ \ : \ \ : ", '┆' ) , ( " : \ \ : \ \ ", '┆' ) , ( " | \ \=+ \ \ ", '╛' ) , ( " | \ \ +=\ \ ", '╘' ) , ( " \ \ +=\ \ | ", '╒' ) , ( " \ \=+ \ \ | ", '╕' ) , ( " | \ \ +=\ \ | ", '╞' ) , ( " | \ \=+ \ \ | ", '╡' ) , ( " \ \=+=\ \ | ", '╤' ) , ( " | \ \=+=\ \ ", '╧' ) , ( " | \ \=+=\ \ | ", '╪' ) , ( " | \ \-+ \ \ ", '┘' ) , ( " | \ \ +-\ \ ", '└' ) , ( " \ \ +-\ \ | ", '┌' ) , ( " \ \-+ \ \ | ", '┐' ) , ( " | \ \ +-\ \ | ", '├' ) , ( " | \ \-+ \ \ | ", '┤' ) , ( " \ \-+-\ \ | ", '┬' ) , ( " | \ \-+-\ \ ", '┴' ) , ( " | \ \-+-\ \ | ", '┼' ) , ( " \ \ .-\ \ | ", '╭' ) , ( " \ \-. \ \ | ", '╮' ) , ( " | \ \-' \ \ ", '╯' ) , ( " | \ \ '-\ \ ", '╰' ) , ( " \ \ # \ \ # ", '█' ) , ( " \ \## \ \ ", '█' ) , ( " \ \ ##\ \ ", '█' ) , ( " # \ \ # \ \ ", '█' ) , ( " \ \-> \ \ ", '▷' ) , ( " \ \ <-\ \ ", '◁' ) , ( " \ \ ^ \ \ | ", '△' ) , ( " | \ \ v \ \ ", '▽' ) ] -------------------------------------------------------------------------------- -- * Transforming ASCII to Unicode -------------------------------------------------------------------------------- -- | Match the 'current' element and its eight neighbours against the defined -- 'patterns' and choose the 'Char' from the matching 'Pattern'. substituteChar :: Plane Char -> Char substituteChar = \case Plane ( Zipper ((Zipper (a : as) b (c : cs)) : _) ( Zipper (d : ds) e (f : fs)) ((Zipper (g : gs) h (i : is)) : _) ) -> fromMaybe e (lookupPattern (patternFromString [a, b, c, d, e, f, g, h, i])) _ -> undefined -- We assume an infinite Zipper! -- | Transform a 'Plane' of ASCII characters to an equivalent plane where the -- ASCII box drawings have been replaced by their Unicode counterpart. -- -- This function is a convolution with 'substituteChar' using the 'Comonad'ic -- 'extend'. renderAsciiToUnicode :: Plane Char -> Plane Char renderAsciiToUnicode = extend substituteChar {- $setup >>> :{ aa2u :: String -> IO () aa2u input = let inputLines = lines input plane = planeFromList ' ' inputLines width = maximum (fmap length inputLines) height = length inputLines in putStr . unlines . fmap (reverse . dropWhile (== ' ') . reverse) . planeToList height width . renderAsciiToUnicode $ plane :} -}
fmthoma/ascii-art-to-unicode
src/Text/AsciiArt.hs
bsd-3-clause
15,146
29
16
4,684
2,188
1,315
873
184
9
module Main where import Data.Foldable import qualified Control.Foldl as L import Control.Foldl.Transduce import Lens.Family import Criterion.Main main :: IO () main = defaultMain [ bgroup "sum" [ bench "without trans" (nf (L.fold L.sum) (take 500000 (cycle [1::Int,-1]))) , bench "with trans" (nf (L.fold (folds (chunksOf 1) L.list (L.handles (folding toList) L.sum))) (take 500000 (cycle [1::Int,-1]))) ] ]
danidiaz/foldl-transduce
benchmarks/benchmarks.hs
bsd-3-clause
541
0
19
189
195
106
89
15
1
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : ./Isabelle/IsaSign.hs Description : abstract Isabelle HOL and HOLCF syntax Copyright : (c) University of Cambridge, Cambridge, England adaption (c) Till Mossakowski, Uni Bremen 2002-2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Data structures for Isabelle signatures and theories. Adapted from Isabelle. -} module Isabelle.IsaSign where import qualified Data.Map as Map import Data.Data import Data.List import Common.Utils (splitOn) {- ------------- not quite from src/Pure/term.ML ------------------------ ---------------------- Names ----------------------------------------- -} -- | type names type TName = String data AltSyntax = AltSyntax String [Int] Int deriving (Show, Eq, Ord, Typeable, Data) -- | names for values or constants (non-classes and non-types) data VName = VName { new :: String -- ^ name within Isabelle , altSyn :: Maybe AltSyntax -- ^ mixfix template syntax } deriving (Show, Typeable, Data) instance Eq VName where v1 == v2 = new v1 == new v2 instance Ord VName where v1 <= v2 = new v1 <= new v2 -- | the original (Haskell) name orig :: VName -> String orig = new data QName = QName { qname :: String , qualifiers :: [String] } deriving (Eq, Ord, Typeable, Data) instance Show QName where show q = intercalate "." $ qualifiers q ++ [qname q] mkQName :: String -> QName mkQName s = case splitOn '.' s of n : q -> QName {qname = n, qualifiers = q} _ -> error $ "empty name!" ++ s {- | Indexnames can be quickly renamed by adding an offset to the integer part, for resolution. -} data Indexname = Indexname { unindexed :: String , indexOffset :: Int } deriving (Ord, Eq, Show, Typeable, Data) -- Types are classified by sorts. data IsaClass = IsaClass String deriving (Ord, Eq, Show, Typeable, Data) type Sort = [IsaClass] {- The sorts attached to TFrees and TVars specify the sort of that variable -} data Typ = Type { typeId :: TName, typeSort :: Sort, typeArgs :: [Typ] } | TFree { typeId :: TName, typeSort :: Sort } | TVar { indexname :: Indexname, typeSort :: Sort } deriving (Eq, Ord, Show, Typeable, Data) {- Terms. Bound variables are indicated by depth number. Free variables, (scheme) variables and constants have names. A term is "closed" if every bound variable of level "lev" is enclosed by at least "lev" abstractions. It is possible to create meaningless terms containing loose bound vars or type mismatches. But such terms are not allowed in rules. -} -- IsCont True - lifted; IsCont False - not lifted, used for constructors data Continuity = IsCont Bool | NotCont deriving (Eq, Ord, Show, Typeable, Data) data TAttr = TFun | TMet | TCon | NA deriving (Eq, Ord, Show, Typeable, Data) data DTyp = Hide { typ :: Typ, kon :: TAttr, arit :: Maybe Int } | Disp { typ :: Typ, kon :: TAttr, arit :: Maybe Int } deriving (Eq, Ord, Show, Typeable, Data) data Term = Const { termName :: VName, termType :: DTyp } | Free { termName :: VName } | Abs { absVar :: Term, termId :: Term, continuity :: Continuity } -- lambda abstraction | App { funId :: Term, argId :: Term, continuity :: Continuity } -- application | If { ifId :: Term, thenId :: Term, elseId :: Term, continuity :: Continuity } | Case { termId :: Term, caseSubst :: [(Term, Term)] } | Let { letSubst :: [(Term, Term)], inId :: Term } | IsaEq { firstTerm :: Term, secondTerm :: Term } | Tuplex [Term] Continuity | Set SetDecl deriving (Eq, Ord, Show, Typeable, Data) data Prop = Prop { prop :: Term , propPats :: [Term] } deriving (Eq, Ord, Show, Typeable, Data) data Props = Props { propsName :: Maybe QName , propsArgs :: Maybe String , props :: [Prop] } deriving (Eq, Ord, Show, Typeable, Data) data Sentence = Sentence { isSimp :: Bool -- True for "[simp]" , isRefuteAux :: Bool , metaTerm :: MetaTerm , thmProof :: Maybe IsaProof } | Instance { tName :: TName , arityArgs :: [Sort] , arityRes :: Sort -- | Definitons for the instansiation with the name of the sentence (String) , definitions :: [(String, Term)] , instProof :: IsaProof } | ConstDef { senTerm :: Term } | RecDef { keyword :: Maybe String , constName :: VName , constType :: Maybe Typ , primRecSenTerms :: [Term] } | TypeDef { newType :: Typ , typeDef :: SetDecl , nonEmptyPr :: IsaProof} -- |Isabelle syntax for grouping multiple lemmas in to a single lemma. | Lemmas { lemmaName :: String , lemmasList :: [String]} | Locale { localeName :: QName, localeContext :: Ctxt, localeParents :: [QName], localeBody :: [Sentence] } | Class { className :: QName, classContext :: Ctxt, classParents :: [QName], classBody :: [Sentence] } | Datatypes [Datatype] | Domains [Domain] | Consts [(String, Maybe Mixfix, Typ)] | TypeSynonym QName (Maybe Mixfix) [String] Typ | Axioms [Axiom] | Lemma { lemmaTarget :: Maybe QName, lemmaContext :: Ctxt, lemmaProof :: Maybe String, lemmaProps :: [Props] } | Definition { definitionName :: QName, definitionMixfix :: Maybe Mixfix, definitionTarget :: Maybe String, definitionType :: Typ, definitionVars :: [Term], definitionTerm :: Term } | Fun { funTarget :: Maybe QName, funSequential :: Bool, funDefault :: Maybe String, funDomintros :: Bool, funPartials :: Bool, funEquations :: [(String, Maybe Mixfix, Typ, [([Term], Term)])] } | Primrec { primrecTarget :: Maybe QName, primrecEquations :: [(String, Maybe Mixfix, Typ, [([Term], Term)])] } | Fixrec [(String, Maybe Mixfix, Typ, [FixrecEquation])] | Instantiation { instantiationType :: TName, instantiationArity :: (Sort, [Sort]), instantiationBody :: [Sentence] } | InstanceProof { instanceProof :: String } | InstanceArity { instanceTypes :: [TName], instanceArity :: (Sort, [Sort]), instanceProof :: String } | InstanceSubclass { instanceClass :: String, instanceRel :: String, instanceClass1 :: String, instanceProof :: String } | Subclass { subclassClass :: String, subclassTarget :: Maybe QName, subclassProof :: String } | Typedef { typedefName :: QName, typedefVars :: [(String, Sort)], typedefMixfix :: Maybe Mixfix, typedefMorphisms :: Maybe (QName, QName), typedefTerm :: Term, typedefProof :: String } | Defs { defsUnchecked :: Bool, defsOverloaded :: Bool, defsEquations :: [DefEquation] } deriving (Eq, Ord, Show, Typeable, Data) data DefEquation = DefEquation { defEquationName :: QName, defEquationConst :: String, defEquationConstType :: Typ, defEquationTerm :: Term, defEquationArgs :: String } deriving (Eq, Ord, Show, Typeable, Data) data FixrecEquation = FixrecEquation { fixrecEquationUnchecked :: Bool, fixrecEquationPremises :: [Term], fixrecEquationPatterns :: [Term], fixrecEquationTerm :: Term } deriving (Eq, Ord, Show, Typeable, Data) data Ctxt = Ctxt { fixes :: [(String, Maybe Mixfix, Typ)], assumes :: [(String, Term)] } deriving (Eq, Ord, Show, Typeable, Data) data Mixfix = Mixfix { mixfixNargs :: Int, mixfixPrio :: Int, mixfixPretty :: String, mixfixTemplate :: [MixfixTemplate] } deriving (Eq, Ord, Show, Typeable, Data) data MixfixTemplate = Arg Int | Str String | Break Int | Block Int [MixfixTemplate] deriving (Eq, Ord, Show, Typeable, Data) data Datatype = Datatype { datatypeName :: QName, datatypeTVars :: [Typ], datatypeMixfix :: Maybe Mixfix, datatypeConstructors :: [DatatypeConstructor] } deriving (Eq, Ord, Show, Typeable, Data) data DatatypeConstructor = DatatypeConstructor { constructorName :: QName, constructorType :: Typ, constructorMixfix :: Maybe Mixfix, constructorArgs :: [Typ] } | DatatypeNoConstructor { constructorArgs :: [Typ] } deriving (Eq, Ord, Show, Typeable, Data) data Domain = Domain { domainName :: QName, domainTVars :: [Typ], domainMixfix :: Maybe Mixfix, domainConstructors :: [DomainConstructor] } deriving (Eq, Ord, Show, Typeable, Data) data DomainConstructor = DomainConstructor { domainConstructorName :: QName, domainConstructorType :: Typ, domainConstructorArgs :: [DomainConstructorArg] } deriving (Eq, Ord, Show, Typeable, Data) data DomainConstructorArg = DomainConstructorArg { domainConstructorArgSel :: Maybe QName, domainConstructorArgType :: Typ, domainConstructorArgLazy :: Bool } deriving (Eq, Ord, Show, Typeable, Data) data Axiom = Axiom { axiomName :: QName, axiomArgs :: String, axiomTerm :: Term } deriving (Eq, Ord, Show, Typeable, Data) data FunSig = FunSig { funSigName :: QName, funSigType :: Maybe Typ } deriving (Eq, Ord, Show, Typeable, Data) -- Other SetDecl variants to be added later data SetDecl {- | Create a set using a subset. First parameter is the variable Second is the type of the variable third is the formula describing the set comprehension e.g. x Nat "even x" would be produce the isabelle code: {x::Nat . even x} -} = SubSet Term Typ Term -- | A set declared using a list of terms. e.g. {1,2,3} would be Set [1,2,3] | FixedSet [Term] deriving (Eq, Ord, Show, Typeable, Data) data MetaTerm = Term Term | Conditional [Term] Term -- List of preconditions, conclusion. deriving (Eq, Ord, Show, Typeable, Data) mkSenAux :: Bool -> MetaTerm -> Sentence mkSenAux b t = Sentence { isSimp = False , isRefuteAux = b , thmProof = Nothing , metaTerm = t } mkSen :: Term -> Sentence mkSen = mkSenAux False . Term mkCond :: [Term] -> Term -> Sentence mkCond conds = mkSenAux False . Conditional conds mkRefuteSen :: Term -> Sentence mkRefuteSen = mkSenAux True . Term isRefute :: Sentence -> Bool isRefute s = case s of Sentence { isRefuteAux = b } -> b _ -> False -- ------------------ from src/Pure/sorts.ML ------------------------ -- - type classes and sorts - {- Classes denote (possibly empty) collections of types that are partially ordered by class inclusion. They are represented symbolically by strings. Sorts are intersections of finitely many classes. They are represented by lists of classes. Normal forms of sorts are sorted lists of minimal classes (wrt. current class inclusion). (already defined in Pure/term.ML) classrel: table representing the proper subclass relation; entries (c, (cs,a,f)) represent the superclasses cs, the assumptions a and the fixed names f of c arities: table of association lists of all type arities; (t, ars) means that type constructor t has the arities ars; an element (c, Ss) of ars represents the arity t::(Ss)c; -} type ClassDecl = ([IsaClass], [(String, Term)], [(String, Typ)]) type Classrel = Map.Map IsaClass ClassDecl type LocaleDecl = ([String], [(String, Term)], [(String, Term)], [(String, Typ, Maybe AltSyntax)]) -- parents * internal axioms * external axiosm * params type Def = (Typ, [(String, Typ)], Term) type FunDef = (Typ, [([Term], Term)]) type Locales = Map.Map String LocaleDecl type Defs = Map.Map String Def type Funs = Map.Map String FunDef type Arities = Map.Map TName [(IsaClass, [(Typ, Sort)])] type Abbrs = Map.Map TName ([TName], Typ) data TypeSig = TySg { classrel :: Classrel, -- domain of the map yields the classes locales :: Locales, defs :: Defs, funs :: Funs, defaultSort :: Sort, log_types :: [TName], univ_witness :: Maybe (Typ, Sort), abbrs :: Abbrs, -- constructor name, variable names, type. arities :: Arities } -- actually isa-instances. the former field tycons can be computed. deriving (Eq, Ord, Show, Typeable) emptyTypeSig :: TypeSig emptyTypeSig = TySg { classrel = Map.empty, locales = Map.empty, defs = Map.empty, funs = Map.empty, defaultSort = [], log_types = [], univ_witness = Nothing, abbrs = Map.empty, arities = Map.empty } isSubTypeSig :: TypeSig -> TypeSig -> Bool isSubTypeSig t1 t2 = null (defaultSort t1 \\ defaultSort t2) && Map.isSubmapOf (classrel t1) (classrel t2) && Map.isSubmapOf (locales t1) (locales t2) && Map.isSubmapOf (defs t1) (defs t2) && Map.isSubmapOf (funs t1) (funs t2) && null (log_types t1 \\ log_types t2) && (case univ_witness t1 of Nothing -> True w1 -> w1 == univ_witness t2) && Map.isSubmapOf (abbrs t1) (abbrs t2) && Map.isSubmapOf (arities t1) (arities t2) -- ------------------ from src/Pure/sign.ML ------------------------ data BaseSig = Main_thy -- ^ main theory of higher order logic (HOL) | Custom_thy | MainHC_thy -- ^ extend main theory of HOL logic for HasCASL | MainHCPairs_thy -- ^ for HasCASL translation to bool pairs | HOLCF_thy -- ^ higher order logic for continuous functions | HsHOLCF_thy -- ^ HOLCF for Haskell | HsHOL_thy -- ^ HOL for Haskell | MHsHOL_thy | MHsHOLCF_thy | CspHOLComplex_thy deriving (Eq, Ord, Show, Typeable) {- possibly simply supply a theory like MainHC as string or recursively as Isabelle.Sign -} data Sign = Sign { theoryName :: String , header :: Maybe String , keywords :: [String] , uses :: [String] , baseSig :: BaseSig -- like Main etc. , imports :: [String] -- additional imports , tsig :: TypeSig , constTab :: ConstTab -- value cons with type , domainTab :: DomainTab , showLemmas :: Bool } deriving (Eq, Ord, Show, Typeable) {- list of datatype definitions each of these consists of a list of (mutually recursive) datatypes each datatype consists of its name (Typ) and a list of constructors each constructor consists of its name (String) and list of argument types -} type ConstTab = Map.Map VName Typ {- same types for data types and domains the optional string is only relevant for alternative type names -} type DomainTab = [[DomainEntry]] type DomainEntry = (Typ, [(VName, [Typ])]) emptySign :: Sign emptySign = Sign { theoryName = "thy" , header = Nothing , keywords = [] , uses = [] , baseSig = Main_thy , imports = [] , tsig = emptyTypeSig , constTab = Map.empty , domainTab = [] , showLemmas = False } isSubSign :: Sign -> Sign -> Bool isSubSign s1 s2 = isSubTypeSig (tsig s1) (tsig s2) && Map.isSubmapOf (constTab s1) (constTab s2) && null (domainTab s1 \\ domainTab s2) union_tsig :: TypeSig -> TypeSig -> TypeSig union_tsig t1 t2 = t1 { classrel = Map.union (classrel t1) (classrel t2), locales = Map.union (locales t1) (locales t2), defs = Map.union (defs t1) (defs t2), funs = Map.union (funs t1) (funs t2), log_types = Data.List.union (log_types t1) (log_types t2), abbrs = Map.union (abbrs t1) (abbrs t2), arities = Map.union (arities t1) (arities t2) } union_sig :: Sign -> Sign -> Sign union_sig s1 s2 = s1 { tsig = union_tsig (tsig s1) (tsig s2), constTab = Map.union (constTab s1) (constTab s2), domainTab = Data.List.union (domainTab s1) (domainTab s2) } -- ---------------------- Sentence ------------------------------------- {- Instances in Haskell have form: instance (MyClass a, MyClass b) => MyClass (MyTypeConst a b) In Isabelle: instance MyTypeConst :: (MyClass, MyClass) MyClass Note that the Isabelle syntax does not allows for multi-parameter classes. Rather, it subsumes the syntax for arities. Type constraints are applied to value constructors in Haskell as follows: MyValCon :: (MyClass a, MyClass b) => MyTypeConst a b In Isabelle: MyValCon :: MyTypeConst (a::MyClass) (b::MyClass) In both cases, the typing expressions may be encoded as schemes. Schemes and instances allows for the inference of type constraints over values of functions. -} -- Data structures for Isabelle Proofs data IsaProof = IsaProof { proof :: [ProofCommand], end :: ProofEnd } deriving (Show, Eq, Ord, Typeable, Data) data ProofCommand {- | Apply a list of proof methods, which will be applied in sequence withing the apply proof command. The boolean is if the + modifier should be used at the end of the apply proof method. e.g. Apply(A,B,C) True would represent the Isabelle proof command "apply(A,B,C)+" -} = Apply [ProofMethod] Bool | Using [String] | Back | Defer Int | Prefer Int | Refute deriving (Show, Eq, Ord, Typeable, Data) data ProofEnd = By ProofMethod | DotDot | Done | Oops | Sorry deriving (Show, Eq, Ord, Typeable, Data) data Modifier -- | No_asm means that assumptions are completely ignored. = No_asm {- | No_asm_simp means that the assumptions are not simplified but are used in the simplification of the conclusion. -} | No_asm_simp {- | No_asm_use means that the assumptions are simplified but are not used in the simplification of each other or the conclusion. -} | No_asm_use deriving (Show, Eq, Ord, Typeable, Data) data ProofMethod {- | This is a plain auto with no parameters - it is used so often it warents its own constructor -} = Auto {- | This is a plain auto with no parameters - it is used so often it warents its own constructor -} | Simp {- | This is an auto where the simpset has been temporarily extended with a listof lemmas, theorems and axioms. An optional modifier can also be used to control how the assumptions are used. It is used so often it warents its own constructor -} | AutoSimpAdd (Maybe Modifier) [String] {- | This is a simp where the simpset has been temporarily extended with a listof lemmas, theorems and axioms. An optional modifier can also be used to control how the assumptions are used. It is used so often it warents its own constructor -} | SimpAdd (Maybe Modifier) [String] -- | Induction proof method. This performs induction upon a variable | Induct Term -- | Case_tac proof method. This perfom a case distinction on a term | CaseTac Term {- | Subgoal_tac proof method . Adds a term to the local assumptions and also creates a sub-goal of this term -} | SubgoalTac Term {- | Insert proof method. Inserts a lemma or theorem name to the assumptions of the first goal -} | Insert [String] {- | Used for proof methods that have not been implemented yet. This includes auto and simp with parameters -} | Other String deriving (Show, Eq, Ord, Typeable, Data) toIsaProof :: ProofEnd -> IsaProof toIsaProof = IsaProof [] mkOops :: IsaProof mkOops = toIsaProof Oops
spechub/Hets
Isabelle/IsaSign.hs
gpl-2.0
19,479
0
16
4,914
4,427
2,593
1,834
396
2
test :: (Bool,Bool) -> Bool test (b1,2b) = b1
roberth/uu-helium
test/thompson/Thompson17.hs
gpl-3.0
48
0
9
11
35
18
17
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeFamilies #-} module HERMIT.External ( -- * Externals External , ExternalName , ExternalHelp , externName , externDyn , externHelp , externTypeString , externTypeArgResString , splitFunTyArgs , toHelp , external , Extern(..) , matchingExternals -- * Tags , CmdTag(..) , TagE , Tag((.+),remTag,tagMatch) , (.&) , (.||) , notT , externTags , dictionaryOfTags -- * Boxes -- | Boxes are used by the 'Extern' class. , CoreString(..) , CrumbBox(..) , IntBox(..) , IntListBox(..) , PathBox(..) , StringBox(..) , StringListBox(..) , TagBox(..) -- ** LCore Boxes , TransformLCoreStringBox(..) , TransformLCoreUnitBox(..) , TransformLCorePathBox(..) , RewriteLCoreBox(..) , BiRewriteLCoreBox(..) , RewriteLCoreListBox(..) -- ** LCoreTC Boxes , TransformLCoreTCStringBox(..) , TransformLCoreTCUnitBox(..) , TransformLCoreTCLCoreBox(..) , TransformLCoreTCPathBox(..) , RewriteLCoreTCBox(..) , BiRewriteLCoreTCBox(..) , RewriteLCoreTCListBox(..) ) where import Data.Map hiding (map) import Data.Dynamic import Data.List import Data.Typeable.Internal (TypeRep(..)) import HERMIT.Core import HERMIT.Context (LocalPathH) import HERMIT.GHC (tcFun) import HERMIT.Kure import HERMIT.Lemma ----------------------------------------------------------------- -- | 'External' names are just strings. type ExternalName = String -- | Help information for 'External's is stored as a list of strings, designed for multi-line displaying. type ExternalHelp = [String] -- Tags -------------------------------------------------------- -- | Requirement: commands cannot have the same name as any 'CmdTag' -- (or the help function will not find it). -- These should be /user facing/, because they give the user -- a way of sub-dividing our confusing array of commands. data CmdTag = Shell -- ^ Shell-specific command. | Eval -- ^ The arrow of evaluation (reduces a term). | KURE -- ^ 'Language.KURE' command. | Loop -- ^ Command may operate multiple times. | Deep -- ^ Command may make a deep change, can be O(n). | Shallow -- ^ Command operates on local nodes only, O(1). | Navigation -- ^ Uses 'Path' or 'Lens' to focus onto something. | Query -- ^ Extract information from an expression. | Predicate -- ^ Something that passes or fails. | Introduce -- ^ Introduce something, like a new name. | Commute -- ^ Commute is when you swap nested terms. | PreCondition -- ^ Operation has a (perhaps undocumented) precondition. | Strictness -- ^ Alters the strictness of the expression. | Debug -- ^ Commands specifically to help debugging. | VersionControl -- ^ Version control for Core syntax. | Context -- ^ A command that uses its context, such as inlining. | Unsafe -- ^ Commands that are not type safe (may cause Core Lint to fail), -- or may otherwise change the semantics of the program. -- Only available in unsafe mode! | Safe -- ^ Include in Strict Safety mode (currently unused) | Proof -- ^ Commands related to proving lemmas. | TODO -- ^ An incomplete or potentially buggy command. | Experiment -- ^ Things we are trying out. | Deprecated -- ^ A command that will be removed in a future release; -- it has probably been renamed or subsumed by another command. deriving (Eq, Show, Read, Bounded, Enum) -- | Lists all the tags paired with a short description of what they're about. dictionaryOfTags :: [(CmdTag,String)] dictionaryOfTags = notes ++ [ (tag,"(unknown purpose)") | tag <- [minBound..maxBound] , tag `notElem` map fst notes ] where notes = -- These should give the user a clue about what the sub-commands might do [ (Shell, "Shell-specific command.") , (Eval, "The arrow of evaluation (reduces a term).") , (KURE, "Direct reflection of a combinator from the KURE DSL.") , (Loop, "Command may operate multiple times.") , (Deep, "Command may make a deep change, can be O(n).") , (Shallow, "Command operates on local nodes only, O(1).") , (Navigation, "Navigate via focus, or directional command.") , (Query, "Extract information from an expression.") , (Predicate, "Something that passes or fails.") , (Introduce, "Introduce something, like a new name.") , (Commute, "Commute is when you swap nested terms.") , (PreCondition, "Operation has a (perhaps undocumented) precondition.") , (Strictness, "Alters the strictness of an expression.") , (Debug, "A command specifically to help debugging.") , (VersionControl, "Version control for Core syntax.") , (Context, "A command that uses its context, such as inlining.") , (Unsafe, "Commands that are not type safe (may cause Core Lint to fail), or may otherwise change the semantics of the program.") , (Proof, "Commands related to proving lemmas.") , (TODO, "An incomplete or potentially buggy command.") , (Experiment, "Things we are trying out, use at your own risk.") , (Deprecated, "A command that will be removed in a future release; it has probably been renamed or subsumed by another command.") ] -- Unfortunately, record update syntax seems to associate to the right. -- These operators save us some parentheses. infixl 3 .+ infixr 4 .|| infixr 5 .& -- | A data type of logical operations on tags. data TagE :: * where Tag :: Tag a => a -> TagE NotTag :: TagE -> TagE AndTag :: TagE -> TagE -> TagE OrTag :: TagE -> TagE -> TagE -- | Tags are meta-data that we add to 'External's to make them sortable and searchable. class Tag a where toTagE :: a -> TagE -- | Add a 'Tag' to an 'External'. (.+) :: External -> a -> External -- | Remove a 'Tag' from an 'External'. remTag :: a -> External -> External -- | Check if an 'External' has the specified 'Tag'. tagMatch :: a -> External -> Bool instance Tag TagE where toTagE = id e .+ (Tag t) = e .+ t e .+ (NotTag t) = remTag t e e .+ (AndTag t1 t2) = e .+ t1 .+ t2 e .+ (OrTag t1 t2) = e .+ t1 .+ t2 -- not sure what else to do remTag (Tag t) e = remTag t e remTag (NotTag t) e = e .+ t remTag (AndTag t1 t2) e = remTag t1 (remTag t2 e) remTag (OrTag t1 t2) e = remTag t1 (remTag t2 e) -- again tagMatch (Tag t) e = tagMatch t e tagMatch (NotTag t) e = not (tagMatch t e) tagMatch (AndTag t1 t2) e = tagMatch t1 e && tagMatch t2 e tagMatch (OrTag t1 t2) e = tagMatch t1 e || tagMatch t2 e instance Tag CmdTag where toTagE = Tag ex@(External {externTags = ts}) .+ t = ex {externTags = t:ts} remTag t ex@(External {externTags = ts}) = ex { externTags = [ t' | t' <- ts, t' /= t ] } tagMatch t (External {externTags = ts}) = t `elem` ts -- | An \"and\" on 'Tag's. (.&) :: (Tag a, Tag b) => a -> b -> TagE t1 .& t2 = AndTag (toTagE t1) (toTagE t2) -- | An \"or\" on 'Tag's. (.||) :: (Tag a, Tag b) => a -> b -> TagE t1 .|| t2 = OrTag (toTagE t1) (toTagE t2) -- how to make a unary operator? -- | A \"not\" on 'Tag's. notT :: Tag a => a -> TagE notT = NotTag . toTagE ----------------------------------------------------------------- -- | An 'External' is a 'Dynamic' value with some associated meta-data (name, help string and tags). data External = External { externName :: ExternalName -- ^ Get the name of an 'External'. , externDyn :: Dynamic -- ^ Get the 'Dynamic' value stored in an 'External'. , externHelp :: ExternalHelp -- ^ Get the list of help 'String's for an 'External'. , externTags :: [CmdTag] -- ^ List all the 'CmdTag's associated with an 'External' } -- | The primitive way to build an 'External'. external :: Extern a => ExternalName -> a -> ExternalHelp -> External external nm fn help = External { externName = nm , externDyn = toDyn (box fn) , externHelp = map (" " ++) help , externTags = [] } -- | Get all the 'External's which match a given tag predicate -- and box a Transform of the appropriate type. matchingExternals :: (Extern tr, Tag t) => t -> [External] -> [(External, tr)] matchingExternals tag exts = [ (e,tr) | e <- exts, tagMatch tag e , Just tr <- [fmap unbox $ fromDynamic $ externDyn e] ] -- | Build a 'Data.Map' from names to help information. toHelp :: [External] -> Map ExternalName ExternalHelp toHelp = fromListWith (++) . map toH where toH :: External -> (ExternalName,ExternalHelp) toH e = (externName e, spaceout (externName e ++ " :: " ++ externTypeString e) (show (externTags e)) : externHelp e) spaceout xs ys = xs ++ replicate (width - (length xs + length ys)) ' ' ++ ys width = 78 -- | Get a string representation of the (monomorphic) type of an 'External' externTypeString :: External -> String externTypeString = deBoxify . show . dynTypeRep . externDyn -- | Remove the word 'Box' from a string. deBoxify :: String -> String deBoxify s | "CLSBox -> " `isPrefixOf` s = go (drop 10 s) | "PrettyPrinter -> " `isPrefixOf` s = go (drop 17 s) | otherwise = go s where go xs | "Box" `isPrefixOf` xs = go (drop 3 xs) go (x:xs) = x : go xs go [] = [] externTypeArgResString :: External -> ([String], String) externTypeArgResString e = (map (deBoxify . show) aTys, deBoxify (show rTy)) where (aTys, rTy) = splitExternFunType e splitExternFunType :: External -> ([TypeRep], TypeRep) splitExternFunType = splitFunTyArgs . dynTypeRep . externDyn splitFunTyArgs :: TypeRep -> ([TypeRep], TypeRep) splitFunTyArgs tr = case splitFunTyMaybe tr of Nothing -> ([], tr) Just (a, r) -> let (as, r') = splitFunTyArgs r in (a:as, r') splitFunTyMaybe :: TypeRep -> Maybe (TypeRep, TypeRep) splitFunTyMaybe (TypeRep _ tc _krs [a,r]) | tc == tcFun = Just (a,r) splitFunTyMaybe _ = Nothing ----------------------------------------------------------------- -- | The class of things that can be made into 'External's. -- To be an 'Extern' there must exist an isomorphic 'Box' type that is an instance of 'Typeable'. class Typeable (Box a) => Extern a where -- | An isomorphic wrapper. type Box a -- | Wrap a value in a 'Box'. box :: a -> Box a -- | Unwrap a value from a 'Box'. unbox :: Box a -> a ----------------------------------------------------------------- instance (Extern a, Extern b) => Extern (a -> b) where type Box (a -> b) = Box a -> Box b box f = box . f . unbox unbox f = unbox . f . box ----------------------------------------------------------------- data TagBox = TagBox TagE instance Extern TagE where type Box TagE = TagBox box = TagBox unbox (TagBox t) = t ----------------------------------------------------------------- data IntBox = IntBox Int instance Extern Int where type Box Int = IntBox box = IntBox unbox (IntBox i) = i ----------------------------------------------------------------- -- TODO: Considering unifying CrumbBox and PathBox under TransformLCoreTCPathBox. data CrumbBox = CrumbBox Crumb instance Extern Crumb where type Box Crumb = CrumbBox box = CrumbBox unbox (CrumbBox cr) = cr ----------------------------------------------------------------- data PathBox = PathBox LocalPathH instance Extern LocalPathH where type Box LocalPathH = PathBox box = PathBox unbox (PathBox p) = p ----------------------------------------------------------------- newtype CoreString = CoreString { unCoreString :: String } instance Extern CoreString where type Box CoreString = CoreString box = id unbox = id ----------------------------------------------------------------- data StringBox = StringBox String instance Extern String where type Box String = StringBox box = StringBox unbox (StringBox s) = s ----------------------------------------------------------------- data StringListBox = StringListBox [String] instance Extern [String] where type Box [String] = StringListBox box = StringListBox unbox (StringListBox l) = l ----------------------------------------------------------------- data IntListBox = IntListBox [Int] instance Extern [Int] where type Box [Int] = IntListBox box = IntListBox unbox (IntListBox l) = l ----------------------------------------------------------------- instance Extern LemmaName where type Box LemmaName = LemmaName box = id unbox = id ----------------------------------------------------------------- data RewriteLCoreBox = RewriteLCoreBox (RewriteH LCore) instance Extern (RewriteH LCore) where type Box (RewriteH LCore) = RewriteLCoreBox box = RewriteLCoreBox unbox (RewriteLCoreBox r) = r ----------------------------------------------------------------- data TransformLCoreStringBox = TransformLCoreStringBox (TransformH LCore String) instance Extern (TransformH LCore String) where type Box (TransformH LCore String) = TransformLCoreStringBox box = TransformLCoreStringBox unbox (TransformLCoreStringBox t) = t ----------------------------------------------------------------- data TransformLCoreUnitBox = TransformLCoreUnitBox (TransformH LCore ()) instance Extern (TransformH LCore ()) where type Box (TransformH LCore ()) = TransformLCoreUnitBox box = TransformLCoreUnitBox unbox (TransformLCoreUnitBox t) = t ----------------------------------------------------------------- data TransformLCorePathBox = TransformLCorePathBox (TransformH LCore LocalPathH) instance Extern (TransformH LCore LocalPathH) where type Box (TransformH LCore LocalPathH) = TransformLCorePathBox box = TransformLCorePathBox unbox (TransformLCorePathBox t) = t ----------------------------------------------------------------- data BiRewriteLCoreBox = BiRewriteLCoreBox (BiRewriteH LCore) instance Extern (BiRewriteH LCore) where type Box (BiRewriteH LCore) = BiRewriteLCoreBox box = BiRewriteLCoreBox unbox (BiRewriteLCoreBox b) = b ----------------------------------------------------------------- data RewriteLCoreListBox = RewriteLCoreListBox [RewriteH LCore] instance Extern [RewriteH LCore] where type Box [RewriteH LCore] = RewriteLCoreListBox box = RewriteLCoreListBox unbox (RewriteLCoreListBox l) = l ----------------------------------------------------------------- data RewriteLCoreTCBox = RewriteLCoreTCBox (RewriteH LCoreTC) instance Extern (RewriteH LCoreTC) where type Box (RewriteH LCoreTC) = RewriteLCoreTCBox box = RewriteLCoreTCBox unbox (RewriteLCoreTCBox r) = r ----------------------------------------------------------------- data TransformLCoreTCStringBox = TransformLCoreTCStringBox (TransformH LCoreTC String) instance Extern (TransformH LCoreTC String) where type Box (TransformH LCoreTC String) = TransformLCoreTCStringBox box = TransformLCoreTCStringBox unbox (TransformLCoreTCStringBox t) = t ----------------------------------------------------------------- data TransformLCoreTCUnitBox = TransformLCoreTCUnitBox (TransformH LCoreTC ()) instance Extern (TransformH LCoreTC ()) where type Box (TransformH LCoreTC ()) = TransformLCoreTCUnitBox box = TransformLCoreTCUnitBox unbox (TransformLCoreTCUnitBox t) = t ----------------------------------------------------------------- data TransformLCoreTCLCoreBox = TransformLCoreTCLCoreBox (TransformH LCoreTC LCore) instance Extern (TransformH LCoreTC LCore) where type Box (TransformH LCoreTC LCore) = TransformLCoreTCLCoreBox box = TransformLCoreTCLCoreBox unbox (TransformLCoreTCLCoreBox t) = t ----------------------------------------------------------------- data TransformLCoreTCPathBox = TransformLCoreTCPathBox (TransformH LCoreTC LocalPathH) instance Extern (TransformH LCoreTC LocalPathH) where type Box (TransformH LCoreTC LocalPathH) = TransformLCoreTCPathBox box = TransformLCoreTCPathBox unbox (TransformLCoreTCPathBox t) = t ----------------------------------------------------------------- data BiRewriteLCoreTCBox = BiRewriteLCoreTCBox (BiRewriteH LCoreTC) instance Extern (BiRewriteH LCoreTC) where type Box (BiRewriteH LCoreTC) = BiRewriteLCoreTCBox box = BiRewriteLCoreTCBox unbox (BiRewriteLCoreTCBox b) = b ----------------------------------------------------------------- data RewriteLCoreTCListBox = RewriteLCoreTCListBox [RewriteH LCoreTC] instance Extern [RewriteH LCoreTC] where type Box [RewriteH LCoreTC] = RewriteLCoreTCListBox box = RewriteLCoreTCListBox unbox (RewriteLCoreTCListBox l) = l -----------------------------------------------------------------
conal/hermit
src/HERMIT/External.hs
bsd-2-clause
17,876
0
14
4,430
3,731
2,100
1,631
310
3
{- (c) Galois, 2006 (c) University of Glasgow, 2007 -} {-# LANGUAGE NondecreasingIndentation #-} module ETA.DeSugar.Coverage (addTicksToBinds, hpcInitCode) where import ETA.Types.Type import ETA.HsSyn.HsSyn import ETA.BasicTypes.Module import qualified ETA.BasicTypes.Module as Module import ETA.Utils.Outputable import qualified ETA.Utils.Outputable as Outputable import ETA.Main.DynFlags import ETA.BasicTypes.SrcLoc import ETA.Main.ErrUtils import ETA.BasicTypes.NameSet hiding (FreeVars) import ETA.BasicTypes.Name import ETA.Utils.Bag import ETA.Profiling.CostCentre import ETA.Core.CoreSyn import ETA.BasicTypes.Id import ETA.BasicTypes.VarSet import ETA.Utils.FastString import ETA.Main.HscTypes import ETA.Types.TyCon import ETA.BasicTypes.UniqSupply import ETA.BasicTypes.BasicTypes import ETA.Utils.MonadUtils import ETA.Utils.Maybes import ETA.Utils.Util import ETA.Main.BreakArray import Control.Monad import Data.List import Data.Array import Data.Time import System.Directory import Trace.Hpc.Mix import Trace.Hpc.Util import Data.Map (Map) import qualified Data.Map as Map {- ************************************************************************ * * * The main function: addTicksToBinds * * ************************************************************************ -} addTicksToBinds :: DynFlags -> Module -> ModLocation -- ... off the current module -> NameSet -- Exported Ids. When we call addTicksToBinds, -- isExportedId doesn't work yet (the desugarer -- hasn't set it), so we have to work from this set. -> [TyCon] -- Type constructor in this module -> LHsBinds Id -> IO (LHsBinds Id, HpcInfo, ModBreaks) addTicksToBinds dflags mod mod_loc exports tyCons binds | let passes = coveragePasses dflags, not (null passes), Just orig_file <- ml_hs_file mod_loc = do if "boot" `isSuffixOf` orig_file then return (binds, emptyHpcInfo False, emptyModBreaks) else do us <- mkSplitUniqSupply 'C' -- for cost centres let orig_file2 = guessSourceFile binds orig_file tickPass tickish (binds,st) = let env = TTE { fileName = mkFastString orig_file2 , declPath = [] , tte_dflags = dflags , exports = exports , inlines = emptyVarSet , inScope = emptyVarSet , blackList = Map.fromList [ (getSrcSpan (tyConName tyCon),()) | tyCon <- tyCons ] , density = mkDensity tickish dflags , this_mod = mod , tickishType = tickish } (binds',_,st') = unTM (addTickLHsBinds binds) env st in (binds', st') initState = TT { tickBoxCount = 0 , mixEntries = [] , breakCount = 0 , breaks = [] , uniqSupply = us } (binds1,st) = foldr tickPass (binds, initState) passes let tickCount = tickBoxCount st hashNo <- writeMixEntries dflags mod tickCount (reverse $ mixEntries st) orig_file2 modBreaks <- mkModBreaks dflags (breakCount st) (reverse $ breaks st) when (dopt Opt_D_dump_ticked dflags) $ log_action dflags dflags SevDump noSrcSpan defaultDumpStyle (pprLHsBinds binds1) return (binds1, HpcInfo tickCount hashNo, modBreaks) | otherwise = return (binds, emptyHpcInfo False, emptyModBreaks) guessSourceFile :: LHsBinds Id -> FilePath -> FilePath guessSourceFile binds orig_file = -- Try look for a file generated from a .hsc file to a -- .hs file, by peeking ahead. let top_pos = catMaybes $ foldrBag (\ (L pos _) rest -> srcSpanFileName_maybe pos : rest) [] binds in case top_pos of (file_name:_) | ".hsc" `isSuffixOf` unpackFS file_name -> unpackFS file_name _ -> orig_file mkModBreaks :: DynFlags -> Int -> [MixEntry_] -> IO ModBreaks mkModBreaks dflags count entries = do breakArray <- newBreakArray dflags $ length entries let locsTicks = listArray (0,count-1) [ span | (span,_,_,_) <- entries ] varsTicks = listArray (0,count-1) [ vars | (_,_,vars,_) <- entries ] declsTicks= listArray (0,count-1) [ decls | (_,decls,_,_) <- entries ] modBreaks = emptyModBreaks { modBreaks_flags = breakArray , modBreaks_locs = locsTicks , modBreaks_vars = varsTicks , modBreaks_decls = declsTicks } -- return modBreaks writeMixEntries :: DynFlags -> Module -> Int -> [MixEntry_] -> FilePath -> IO Int writeMixEntries dflags mod count entries filename | not (gopt Opt_Hpc dflags) = return 0 | otherwise = do let hpc_dir = hpcDir dflags mod_name = moduleNameString (moduleName mod) hpc_mod_dir | moduleUnitId mod == mainUnitId = hpc_dir | otherwise = hpc_dir ++ "/" ++ unitIdString (moduleUnitId mod) tabStop = 8 -- <tab> counts as a normal char in GHC's location ranges. createDirectoryIfMissing True hpc_mod_dir modTime <- getModificationUTCTime filename let entries' = [ (hpcPos, box) | (span,_,_,box) <- entries, hpcPos <- [mkHpcPos span] ] when (length entries' /= count) $ do panic "the number of .mix entries are inconsistent" let hashNo = mixHash filename modTime tabStop entries' mixCreate hpc_mod_dir mod_name $ Mix filename modTime (toHash hashNo) tabStop entries' return hashNo -- ----------------------------------------------------------------------------- -- TickDensity: where to insert ticks data TickDensity = TickForCoverage -- for Hpc | TickForBreakPoints -- for GHCi | TickAllFunctions -- for -prof-auto-all | TickTopFunctions -- for -prof-auto-top | TickExportedFunctions -- for -prof-auto-exported | TickCallSites -- for stack tracing deriving Eq mkDensity :: TickishType -> DynFlags -> TickDensity mkDensity tickish dflags = case tickish of HpcTicks -> TickForCoverage SourceNotes -> TickForCoverage Breakpoints -> TickForBreakPoints ProfNotes -> case profAuto dflags of ProfAutoAll -> TickAllFunctions ProfAutoTop -> TickTopFunctions ProfAutoExports -> TickExportedFunctions ProfAutoCalls -> TickCallSites _other -> panic "mkDensity" -- | Decide whether to add a tick to a binding or not. shouldTickBind :: TickDensity -> Bool -- top level? -> Bool -- exported? -> Bool -- simple pat bind? -> Bool -- INLINE pragma? -> Bool shouldTickBind density top_lev exported simple_pat inline = case density of TickForBreakPoints -> not simple_pat -- we never add breakpoints to simple pattern bindings -- (there's always a tick on the rhs anyway). TickAllFunctions -> not inline TickTopFunctions -> top_lev && not inline TickExportedFunctions -> exported && not inline TickForCoverage -> True TickCallSites -> False shouldTickPatBind :: TickDensity -> Bool -> Bool shouldTickPatBind density top_lev = case density of TickForBreakPoints -> False TickAllFunctions -> True TickTopFunctions -> top_lev TickExportedFunctions -> False TickForCoverage -> False TickCallSites -> False -- ----------------------------------------------------------------------------- -- Adding ticks to bindings addTickLHsBinds :: LHsBinds Id -> TM (LHsBinds Id) addTickLHsBinds = mapBagM addTickLHsBind addTickLHsBind :: LHsBind Id -> TM (LHsBind Id) addTickLHsBind (L pos bind@(AbsBinds { abs_binds = binds, abs_exports = abs_exports })) = do withEnv add_exports $ do withEnv add_inlines $ do binds' <- addTickLHsBinds binds return $ L pos $ bind { abs_binds = binds' } where -- in AbsBinds, the Id on each binding is not the actual top-level -- Id that we are defining, they are related by the abs_exports -- field of AbsBinds. So if we're doing TickExportedFunctions we need -- to add the local Ids to the set of exported Names so that we know to -- tick the right bindings. add_exports env = env{ exports = exports env `extendNameSetList` [ idName mid | ABE{ abe_poly = pid, abe_mono = mid } <- abs_exports , idName pid `elemNameSet` (exports env) ] } add_inlines env = env{ inlines = inlines env `extendVarSetList` [ mid | ABE{ abe_poly = pid, abe_mono = mid } <- abs_exports , isAnyInlinePragma (idInlinePragma pid) ] } addTickLHsBind (L pos (funBind@(FunBind { fun_id = (L _ id) }))) = do let name = getOccString id decl_path <- getPathEntry density <- getDensity inline_ids <- liftM inlines getEnv let inline = isAnyInlinePragma (idInlinePragma id) || id `elemVarSet` inline_ids -- See Note [inline sccs] tickish <- tickishType `liftM` getEnv if inline && tickish == ProfNotes then return (L pos funBind) else do (fvs, mg@(MG { mg_alts = matches' })) <- getFreeVars $ addPathEntry name $ addTickMatchGroup False (fun_matches funBind) blackListed <- isBlackListed pos exported_names <- liftM exports getEnv -- We don't want to generate code for blacklisted positions -- We don't want redundant ticks on simple pattern bindings -- We don't want to tick non-exported bindings in TickExportedFunctions let simple = isSimplePatBind funBind toplev = null decl_path exported = idName id `elemNameSet` exported_names tick <- if not blackListed && shouldTickBind density toplev exported simple inline then bindTick density name pos fvs else return Nothing let mbCons = maybe Prelude.id (:) return $ L pos $ funBind { fun_matches = mg { mg_alts = matches' } , fun_tick = tick `mbCons` fun_tick funBind } where -- a binding is a simple pattern binding if it is a funbind with zero patterns isSimplePatBind :: HsBind a -> Bool isSimplePatBind funBind = matchGroupArity (fun_matches funBind) == 0 -- TODO: Revisit this addTickLHsBind (L pos (pat@(PatBind { pat_lhs = lhs, pat_rhs = rhs }))) = do let name = "(...)" (fvs, rhs') <- getFreeVars $ addPathEntry name $ addTickGRHSs False False rhs let pat' = pat { pat_rhs = rhs'} -- Should create ticks here? density <- getDensity decl_path <- getPathEntry let top_lev = null decl_path if not (shouldTickPatBind density top_lev) then return (L pos pat') else do -- Allocate the ticks rhs_tick <- bindTick density name pos fvs let patvars = map getOccString (collectPatBinders lhs) patvar_ticks <- mapM (\v -> bindTick density v pos fvs) patvars -- Add to pattern let mbCons = maybe id (:) rhs_ticks = rhs_tick `mbCons` fst (pat_ticks pat') patvar_tickss = zipWith mbCons patvar_ticks (snd (pat_ticks pat') ++ repeat []) return $ L pos $ pat' { pat_ticks = (rhs_ticks, patvar_tickss) } -- Only internal stuff, not from source, uses VarBind, so we ignore it. addTickLHsBind var_bind@(L _ (VarBind {})) = return var_bind addTickLHsBind patsyn_bind@(L _ (PatSynBind {})) = return patsyn_bind bindTick :: TickDensity -> String -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id)) bindTick density name pos fvs = do decl_path <- getPathEntry let toplev = null decl_path count_entries = toplev || density == TickAllFunctions top_only = density /= TickAllFunctions box_label = if toplev then TopLevelBox [name] else LocalBox (decl_path ++ [name]) -- allocATickBox box_label count_entries top_only pos fvs -- Note [inline sccs] -- -- It should be reasonable to add ticks to INLINE functions; however -- currently this tickles a bug later on because the SCCfinal pass -- does not look inside unfoldings to find CostCentres. It would be -- difficult to fix that, because SCCfinal currently works on STG and -- not Core (and since it also generates CostCentres for CAFs, -- changing this would be difficult too). -- -- Another reason not to add ticks to INLINE functions is that this -- sometimes handy for avoiding adding a tick to a particular function -- (see #6131) -- -- So for now we do not add any ticks to INLINE functions at all. -- ----------------------------------------------------------------------------- -- Decorate an LHsExpr with ticks -- selectively add ticks to interesting expressions addTickLHsExpr :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExpr e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | isGoodBreakExpr e0 -> tick_it TickForCoverage -> tick_it TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- Add a tick to an expression which is the RHS of an equation or a binding. -- We always consider these to be breakpoints, unless the expression is a 'let' -- (because the body will definitely have a tick somewhere). ToDo: perhaps -- we should treat 'case' and 'if' the same way? addTickLHsExprRHS :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprRHS e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | HsLet{} <- e0 -> dont_tick_it | otherwise -> tick_it TickForCoverage -> tick_it TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- The inner expression of an evaluation context: -- let binds in [], ( [] ) -- we never tick these if we're doing HPC, but otherwise -- we treat it like an ordinary expression. addTickLHsExprEvalInner :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprEvalInner e = do d <- getDensity case d of TickForCoverage -> addTickLHsExprNever e _otherwise -> addTickLHsExpr e -- | A let body is treated differently from addTickLHsExprEvalInner -- above with TickForBreakPoints, because for breakpoints we always -- want to tick the body, even if it is not a redex. See test -- break012. This gives the user the opportunity to inspect the -- values of the let-bound variables. addTickLHsExprLetBody :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprLetBody e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | HsLet{} <- e0 -> dont_tick_it | otherwise -> tick_it _other -> addTickLHsExprEvalInner e where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- version of addTick that does not actually add a tick, -- because the scope of this tick is completely subsumed by -- another. addTickLHsExprNever :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprNever (L pos e0) = do e1 <- addTickHsExpr e0 return $ L pos e1 -- general heuristic: expressions which do not denote values are good break points isGoodBreakExpr :: HsExpr Id -> Bool isGoodBreakExpr (HsApp {}) = True isGoodBreakExpr (OpApp {}) = True isGoodBreakExpr (NegApp {}) = True isGoodBreakExpr (HsIf {}) = True isGoodBreakExpr (HsMultiIf {}) = True isGoodBreakExpr (HsCase {}) = True isGoodBreakExpr (RecordCon {}) = True isGoodBreakExpr (RecordUpd {}) = True isGoodBreakExpr (ArithSeq {}) = True isGoodBreakExpr (PArrSeq {}) = True isGoodBreakExpr _other = False isCallSite :: HsExpr Id -> Bool isCallSite HsApp{} = True isCallSite OpApp{} = True isCallSite _ = False addTickLHsExprOptAlt :: Bool -> LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprOptAlt oneOfMany (L pos e0) = ifDensity TickForCoverage (allocTickBox (ExpBox oneOfMany) False False pos $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) addBinTickLHsExpr :: (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id) addBinTickLHsExpr boxLabel (L pos e0) = ifDensity TickForCoverage (allocBinTickBox boxLabel pos $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) -- ----------------------------------------------------------------------------- -- Decoarate an HsExpr with ticks addTickHsExpr :: HsExpr Id -> TM (HsExpr Id) addTickHsExpr e@(HsVar id) = do freeVar id; return e addTickHsExpr e@(HsIPVar _) = return e addTickHsExpr e@(HsOverLit _) = return e addTickHsExpr e@(HsLit _) = return e addTickHsExpr (HsLam matchgroup) = liftM HsLam (addTickMatchGroup True matchgroup) addTickHsExpr (HsLamCase ty mgs) = liftM (HsLamCase ty) (addTickMatchGroup True mgs) addTickHsExpr (HsApp e1 e2) = liftM2 HsApp (addTickLHsExprNever e1) (addTickLHsExpr e2) addTickHsExpr (OpApp e1 e2 fix e3) = liftM4 OpApp (addTickLHsExpr e1) (addTickLHsExprNever e2) (return fix) (addTickLHsExpr e3) addTickHsExpr (NegApp e neg) = liftM2 NegApp (addTickLHsExpr e) (addTickSyntaxExpr hpcSrcSpan neg) addTickHsExpr (HsPar e) = liftM HsPar (addTickLHsExprEvalInner e) addTickHsExpr (SectionL e1 e2) = liftM2 SectionL (addTickLHsExpr e1) (addTickLHsExprNever e2) addTickHsExpr (SectionR e1 e2) = liftM2 SectionR (addTickLHsExprNever e1) (addTickLHsExpr e2) addTickHsExpr (ExplicitTuple es boxity) = liftM2 ExplicitTuple (mapM addTickTupArg es) (return boxity) addTickHsExpr (HsCase e mgs) = liftM2 HsCase (addTickLHsExpr e) -- not an EvalInner; e might not necessarily -- be evaluated. (addTickMatchGroup False mgs) addTickHsExpr (HsIf cnd e1 e2 e3) = liftM3 (HsIf cnd) (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsExprOptAlt True e2) (addTickLHsExprOptAlt True e3) addTickHsExpr (HsMultiIf ty alts) = do { let isOneOfMany = case alts of [_] -> False; _ -> True ; alts' <- mapM (liftL $ addTickGRHS isOneOfMany False) alts ; return $ HsMultiIf ty alts' } addTickHsExpr (HsLet binds e) = bindLocals (collectLocalBinders binds) $ liftM2 HsLet (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsExprLetBody e) addTickHsExpr (HsDo cxt stmts srcloc) = do { (stmts', _) <- addTickLStmts' forQual stmts (return ()) ; return (HsDo cxt stmts' srcloc) } where forQual = case cxt of ListComp -> Just $ BinBox QualBinBox _ -> Nothing addTickHsExpr (ExplicitList ty wit es) = liftM3 ExplicitList (return ty) (addTickWit wit) (mapM (addTickLHsExpr) es) where addTickWit Nothing = return Nothing addTickWit (Just fln) = do fln' <- addTickHsExpr fln return (Just fln') addTickHsExpr (ExplicitPArr ty es) = liftM2 ExplicitPArr (return ty) (mapM (addTickLHsExpr) es) addTickHsExpr (HsStatic e) = HsStatic <$> addTickLHsExpr e addTickHsExpr (RecordCon id ty rec_binds) = liftM3 RecordCon (return id) (return ty) (addTickHsRecordBinds rec_binds) addTickHsExpr (RecordUpd e rec_binds cons tys1 tys2) = liftM5 RecordUpd (addTickLHsExpr e) (addTickHsRecordBinds rec_binds) (return cons) (return tys1) (return tys2) addTickHsExpr (ExprWithTySigOut e ty) = liftM2 ExprWithTySigOut (addTickLHsExprNever e) -- No need to tick the inner expression -- for expressions with signatures (return ty) addTickHsExpr (ArithSeq ty wit arith_seq) = liftM3 ArithSeq (return ty) (addTickWit wit) (addTickArithSeqInfo arith_seq) where addTickWit Nothing = return Nothing addTickWit (Just fl) = do fl' <- addTickHsExpr fl return (Just fl') -- We might encounter existing ticks (multiple Coverage passes) addTickHsExpr (HsTick t e) = liftM (HsTick t) (addTickLHsExprNever e) addTickHsExpr (HsBinTick t0 t1 e) = liftM (HsBinTick t0 t1) (addTickLHsExprNever e) addTickHsExpr (HsTickPragma _ _ (L pos e0)) = do e2 <- allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 return $ unLoc e2 addTickHsExpr (PArrSeq ty arith_seq) = liftM2 PArrSeq (return ty) (addTickArithSeqInfo arith_seq) addTickHsExpr (HsSCC src nm e) = liftM3 HsSCC (return src) (return nm) (addTickLHsExpr e) addTickHsExpr (HsCoreAnn src nm e) = liftM3 HsCoreAnn (return src) (return nm) (addTickLHsExpr e) addTickHsExpr e@(HsBracket {}) = return e addTickHsExpr e@(HsTcBracketOut {}) = return e addTickHsExpr e@(HsRnBracketOut {}) = return e addTickHsExpr e@(HsSpliceE {}) = return e addTickHsExpr (HsProc pat cmdtop) = liftM2 HsProc (addTickLPat pat) (liftL (addTickHsCmdTop) cmdtop) addTickHsExpr (HsWrap w e) = liftM2 HsWrap (return w) (addTickHsExpr e) -- explicitly no tick on inside addTickHsExpr e@(HsType _) = return e addTickHsExpr (HsUnboundVar {}) = panic "addTickHsExpr.HsUnboundVar" -- Others dhould never happen in expression content. addTickHsExpr e = pprPanic "addTickHsExpr" (ppr e) addTickTupArg :: LHsTupArg Id -> TM (LHsTupArg Id) addTickTupArg (L l (Present e)) = do { e' <- addTickLHsExpr e ; return (L l (Present e')) } addTickTupArg (L l (Missing ty)) = return (L l (Missing ty)) addTickMatchGroup :: Bool{-is lambda-} -> MatchGroup Id (LHsExpr Id) -> TM (MatchGroup Id (LHsExpr Id)) addTickMatchGroup is_lam mg@(MG { mg_alts = matches }) = do let isOneOfMany = matchesOneOfMany matches matches' <- mapM (liftL (addTickMatch isOneOfMany is_lam)) matches return $ mg { mg_alts = matches' } addTickMatch :: Bool -> Bool -> Match Id (LHsExpr Id) -> TM (Match Id (LHsExpr Id)) addTickMatch isOneOfMany isLambda (Match mf pats opSig gRHSs) = bindLocals (collectPatsBinders pats) $ do gRHSs' <- addTickGRHSs isOneOfMany isLambda gRHSs return $ Match mf pats opSig gRHSs' addTickGRHSs :: Bool -> Bool -> GRHSs Id (LHsExpr Id) -> TM (GRHSs Id (LHsExpr Id)) addTickGRHSs isOneOfMany isLambda (GRHSs guarded local_binds) = do bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL (addTickGRHS isOneOfMany isLambda)) guarded return $ GRHSs guarded' local_binds' where binders = collectLocalBinders local_binds addTickGRHS :: Bool -> Bool -> GRHS Id (LHsExpr Id) -> TM (GRHS Id (LHsExpr Id)) addTickGRHS isOneOfMany isLambda (GRHS stmts expr) = do (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts (addTickGRHSBody isOneOfMany isLambda expr) return $ GRHS stmts' expr' addTickGRHSBody :: Bool -> Bool -> LHsExpr Id -> TM (LHsExpr Id) addTickGRHSBody isOneOfMany isLambda expr@(L pos e0) = do d <- getDensity case d of TickForCoverage -> addTickLHsExprOptAlt isOneOfMany expr TickAllFunctions | isLambda -> addPathEntry "\\" $ allocTickBox (ExpBox False) True{-count-} False{-not top-} pos $ addTickHsExpr e0 _otherwise -> addTickLHsExprRHS expr addTickLStmts :: (Maybe (Bool -> BoxLabel)) -> [ExprLStmt Id] -> TM [ExprLStmt Id] addTickLStmts isGuard stmts = do (stmts, _) <- addTickLStmts' isGuard stmts (return ()) return stmts addTickLStmts' :: (Maybe (Bool -> BoxLabel)) -> [ExprLStmt Id] -> TM a -> TM ([ExprLStmt Id], a) addTickLStmts' isGuard lstmts res = bindLocals (collectLStmtsBinders lstmts) $ do { lstmts' <- mapM (liftL (addTickStmt isGuard)) lstmts ; a <- res ; return (lstmts', a) } addTickStmt :: (Maybe (Bool -> BoxLabel)) -> Stmt Id (LHsExpr Id) -> TM (Stmt Id (LHsExpr Id)) addTickStmt _isGuard (LastStmt e ret) = do liftM2 LastStmt (addTickLHsExpr e) (addTickSyntaxExpr hpcSrcSpan ret) addTickStmt _isGuard (BindStmt pat e bind fail) = do liftM4 BindStmt (addTickLPat pat) (addTickLHsExprRHS e) (addTickSyntaxExpr hpcSrcSpan bind) (addTickSyntaxExpr hpcSrcSpan fail) addTickStmt isGuard (BodyStmt e bind' guard' ty) = do liftM4 BodyStmt (addTick isGuard e) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard') (return ty) addTickStmt _isGuard (LetStmt binds) = do liftM LetStmt (addTickHsLocalBinds binds) addTickStmt isGuard (ParStmt pairs mzipExpr bindExpr) = do liftM3 ParStmt (mapM (addTickStmtAndBinders isGuard) pairs) (addTickSyntaxExpr hpcSrcSpan mzipExpr) (addTickSyntaxExpr hpcSrcSpan bindExpr) addTickStmt isGuard stmt@(TransStmt { trS_stmts = stmts , trS_by = by, trS_using = using , trS_ret = returnExpr, trS_bind = bindExpr , trS_fmap = liftMExpr }) = do t_s <- addTickLStmts isGuard stmts t_y <- fmapMaybeM addTickLHsExprRHS by t_u <- addTickLHsExprRHS using t_f <- addTickSyntaxExpr hpcSrcSpan returnExpr t_b <- addTickSyntaxExpr hpcSrcSpan bindExpr t_m <- addTickSyntaxExpr hpcSrcSpan liftMExpr return $ stmt { trS_stmts = t_s, trS_by = t_y, trS_using = t_u , trS_ret = t_f, trS_bind = t_b, trS_fmap = t_m } addTickStmt isGuard stmt@(RecStmt {}) = do { stmts' <- addTickLStmts isGuard (recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt) ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } addTick :: Maybe (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id) addTick isGuard e | Just fn <- isGuard = addBinTickLHsExpr fn e | otherwise = addTickLHsExprRHS e addTickStmtAndBinders :: Maybe (Bool -> BoxLabel) -> ParStmtBlock Id Id -> TM (ParStmtBlock Id Id) addTickStmtAndBinders isGuard (ParStmtBlock stmts ids returnExpr) = liftM3 ParStmtBlock (addTickLStmts isGuard stmts) (return ids) (addTickSyntaxExpr hpcSrcSpan returnExpr) addTickHsLocalBinds :: HsLocalBinds Id -> TM (HsLocalBinds Id) addTickHsLocalBinds (HsValBinds binds) = liftM HsValBinds (addTickHsValBinds binds) addTickHsLocalBinds (HsIPBinds binds) = liftM HsIPBinds (addTickHsIPBinds binds) addTickHsLocalBinds (EmptyLocalBinds) = return EmptyLocalBinds addTickHsValBinds :: HsValBindsLR Id a -> TM (HsValBindsLR Id b) addTickHsValBinds (ValBindsOut binds sigs) = liftM2 ValBindsOut (mapM (\ (rec,binds') -> liftM2 (,) (return rec) (addTickLHsBinds binds')) binds) (return sigs) addTickHsValBinds _ = panic "addTickHsValBinds" addTickHsIPBinds :: HsIPBinds Id -> TM (HsIPBinds Id) addTickHsIPBinds (IPBinds ipbinds dictbinds) = liftM2 IPBinds (mapM (liftL (addTickIPBind)) ipbinds) (return dictbinds) addTickIPBind :: IPBind Id -> TM (IPBind Id) addTickIPBind (IPBind nm e) = liftM2 IPBind (return nm) (addTickLHsExpr e) -- There is no location here, so we might need to use a context location?? addTickSyntaxExpr :: SrcSpan -> SyntaxExpr Id -> TM (SyntaxExpr Id) addTickSyntaxExpr pos x = do L _ x' <- addTickLHsExpr (L pos x) return $ x' -- we do not walk into patterns. addTickLPat :: LPat Id -> TM (LPat Id) addTickLPat pat = return pat addTickHsCmdTop :: HsCmdTop Id -> TM (HsCmdTop Id) addTickHsCmdTop (HsCmdTop cmd tys ty syntaxtable) = liftM4 HsCmdTop (addTickLHsCmd cmd) (return tys) (return ty) (return syntaxtable) addTickLHsCmd :: LHsCmd Id -> TM (LHsCmd Id) addTickLHsCmd (L pos c0) = do c1 <- addTickHsCmd c0 return $ L pos c1 addTickHsCmd :: HsCmd Id -> TM (HsCmd Id) addTickHsCmd (HsCmdLam matchgroup) = liftM HsCmdLam (addTickCmdMatchGroup matchgroup) addTickHsCmd (HsCmdApp c e) = liftM2 HsCmdApp (addTickLHsCmd c) (addTickLHsExpr e) {- addTickHsCmd (OpApp e1 c2 fix c3) = liftM4 OpApp (addTickLHsExpr e1) (addTickLHsCmd c2) (return fix) (addTickLHsCmd c3) -} addTickHsCmd (HsCmdPar e) = liftM HsCmdPar (addTickLHsCmd e) addTickHsCmd (HsCmdCase e mgs) = liftM2 HsCmdCase (addTickLHsExpr e) (addTickCmdMatchGroup mgs) addTickHsCmd (HsCmdIf cnd e1 c2 c3) = liftM3 (HsCmdIf cnd) (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsCmd c2) (addTickLHsCmd c3) addTickHsCmd (HsCmdLet binds c) = bindLocals (collectLocalBinders binds) $ liftM2 HsCmdLet (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsCmd c) addTickHsCmd (HsCmdDo stmts srcloc) = do { (stmts', _) <- addTickLCmdStmts' stmts (return ()) ; return (HsCmdDo stmts' srcloc) } addTickHsCmd (HsCmdArrApp e1 e2 ty1 arr_ty lr) = liftM5 HsCmdArrApp (addTickLHsExpr e1) (addTickLHsExpr e2) (return ty1) (return arr_ty) (return lr) addTickHsCmd (HsCmdArrForm e fix cmdtop) = liftM3 HsCmdArrForm (addTickLHsExpr e) (return fix) (mapM (liftL (addTickHsCmdTop)) cmdtop) addTickHsCmd (HsCmdCast co cmd) = liftM2 HsCmdCast (return co) (addTickHsCmd cmd) -- Others should never happen in a command context. --addTickHsCmd e = pprPanic "addTickHsCmd" (ppr e) addTickCmdMatchGroup :: MatchGroup Id (LHsCmd Id) -> TM (MatchGroup Id (LHsCmd Id)) addTickCmdMatchGroup mg@(MG { mg_alts = matches }) = do matches' <- mapM (liftL addTickCmdMatch) matches return $ mg { mg_alts = matches' } addTickCmdMatch :: Match Id (LHsCmd Id) -> TM (Match Id (LHsCmd Id)) addTickCmdMatch (Match mf pats opSig gRHSs) = bindLocals (collectPatsBinders pats) $ do gRHSs' <- addTickCmdGRHSs gRHSs return $ Match mf pats opSig gRHSs' addTickCmdGRHSs :: GRHSs Id (LHsCmd Id) -> TM (GRHSs Id (LHsCmd Id)) addTickCmdGRHSs (GRHSs guarded local_binds) = do bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL addTickCmdGRHS) guarded return $ GRHSs guarded' local_binds' where binders = collectLocalBinders local_binds addTickCmdGRHS :: GRHS Id (LHsCmd Id) -> TM (GRHS Id (LHsCmd Id)) -- The *guards* are *not* Cmds, although the body is -- C.f. addTickGRHS for the BinBox stuff addTickCmdGRHS (GRHS stmts cmd) = do { (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts (addTickLHsCmd cmd) ; return $ GRHS stmts' expr' } addTickLCmdStmts :: [LStmt Id (LHsCmd Id)] -> TM [LStmt Id (LHsCmd Id)] addTickLCmdStmts stmts = do (stmts, _) <- addTickLCmdStmts' stmts (return ()) return stmts addTickLCmdStmts' :: [LStmt Id (LHsCmd Id)] -> TM a -> TM ([LStmt Id (LHsCmd Id)], a) addTickLCmdStmts' lstmts res = bindLocals binders $ do lstmts' <- mapM (liftL addTickCmdStmt) lstmts a <- res return (lstmts', a) where binders = collectLStmtsBinders lstmts addTickCmdStmt :: Stmt Id (LHsCmd Id) -> TM (Stmt Id (LHsCmd Id)) addTickCmdStmt (BindStmt pat c bind fail) = do liftM4 BindStmt (addTickLPat pat) (addTickLHsCmd c) (return bind) (return fail) addTickCmdStmt (LastStmt c ret) = do liftM2 LastStmt (addTickLHsCmd c) (addTickSyntaxExpr hpcSrcSpan ret) addTickCmdStmt (BodyStmt c bind' guard' ty) = do liftM4 BodyStmt (addTickLHsCmd c) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard') (return ty) addTickCmdStmt (LetStmt binds) = do liftM LetStmt (addTickHsLocalBinds binds) addTickCmdStmt stmt@(RecStmt {}) = do { stmts' <- addTickLCmdStmts (recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt) ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } -- Others should never happen in a command context. addTickCmdStmt stmt = pprPanic "addTickHsCmd" (ppr stmt) addTickHsRecordBinds :: HsRecordBinds Id -> TM (HsRecordBinds Id) addTickHsRecordBinds (HsRecFields fields dd) = do { fields' <- mapM process fields ; return (HsRecFields fields' dd) } where process (L l (HsRecField ids expr doc)) = do { expr' <- addTickLHsExpr expr ; return (L l (HsRecField ids expr' doc)) } addTickArithSeqInfo :: ArithSeqInfo Id -> TM (ArithSeqInfo Id) addTickArithSeqInfo (From e1) = liftM From (addTickLHsExpr e1) addTickArithSeqInfo (FromThen e1 e2) = liftM2 FromThen (addTickLHsExpr e1) (addTickLHsExpr e2) addTickArithSeqInfo (FromTo e1 e2) = liftM2 FromTo (addTickLHsExpr e1) (addTickLHsExpr e2) addTickArithSeqInfo (FromThenTo e1 e2 e3) = liftM3 FromThenTo (addTickLHsExpr e1) (addTickLHsExpr e2) (addTickLHsExpr e3) liftL :: (Monad m) => (a -> m a) -> Located a -> m (Located a) liftL f (L loc a) = do a' <- f a return $ L loc a' data TickTransState = TT { tickBoxCount:: Int , mixEntries :: [MixEntry_] , breakCount :: Int , breaks :: [MixEntry_] , uniqSupply :: UniqSupply } data TickTransEnv = TTE { fileName :: FastString , density :: TickDensity , tte_dflags :: DynFlags , exports :: NameSet , inlines :: VarSet , declPath :: [String] , inScope :: VarSet , blackList :: Map SrcSpan () , this_mod :: Module , tickishType :: TickishType } -- deriving Show data TickishType = ProfNotes | HpcTicks | Breakpoints | SourceNotes deriving (Eq) coveragePasses :: DynFlags -> [TickishType] coveragePasses dflags = ifa (hscTarget dflags == HscInterpreted) Breakpoints $ ifa (gopt Opt_Hpc dflags) HpcTicks $ ifa (gopt Opt_SccProfilingOn dflags && profAuto dflags /= NoProfAuto) ProfNotes $ ifa (gopt Opt_Debug dflags) SourceNotes [] where ifa f x xs | f = x:xs | otherwise = xs -- | Tickishs that only make sense when their source code location -- refers to the current file. This might not always be true due to -- LINE pragmas in the code - which would confuse at least HPC. tickSameFileOnly :: TickishType -> Bool tickSameFileOnly HpcTicks = True tickSameFileOnly _other = False type FreeVars = OccEnv Id noFVs :: FreeVars noFVs = emptyOccEnv -- Note [freevars] -- For breakpoints we want to collect the free variables of an -- expression for pinning on the HsTick. We don't want to collect -- *all* free variables though: in particular there's no point pinning -- on free variables that are will otherwise be in scope at the GHCi -- prompt, which means all top-level bindings. Unfortunately detecting -- top-level bindings isn't easy (collectHsBindsBinders on the top-level -- bindings doesn't do it), so we keep track of a set of "in-scope" -- variables in addition to the free variables, and the former is used -- to filter additions to the latter. This gives us complete control -- over what free variables we track. data TM a = TM { unTM :: TickTransEnv -> TickTransState -> (a,FreeVars,TickTransState) } -- a combination of a state monad (TickTransState) and a writer -- monad (FreeVars). instance Functor TM where fmap = liftM instance Applicative TM where pure = return (<*>) = ap instance Monad TM where return a = TM $ \ _env st -> (a,noFVs,st) (TM m) >>= k = TM $ \ env st -> case m env st of (r1,fv1,st1) -> case unTM (k r1) env st1 of (r2,fv2,st2) -> (r2, fv1 `plusOccEnv` fv2, st2) instance HasDynFlags TM where getDynFlags = TM $ \ env st -> (tte_dflags env, noFVs, st) instance MonadUnique TM where getUniqueSupplyM = TM $ \_ st -> (uniqSupply st, noFVs, st) getUniqueM = TM $ \_ st -> let (u, us') = takeUniqFromSupply (uniqSupply st) in (u, noFVs, st { uniqSupply = us' }) getState :: TM TickTransState getState = TM $ \ _ st -> (st, noFVs, st) setState :: (TickTransState -> TickTransState) -> TM () setState f = TM $ \ _ st -> ((), noFVs, f st) getEnv :: TM TickTransEnv getEnv = TM $ \ env st -> (env, noFVs, st) withEnv :: (TickTransEnv -> TickTransEnv) -> TM a -> TM a withEnv f (TM m) = TM $ \ env st -> case m (f env) st of (a, fvs, st') -> (a, fvs, st') getDensity :: TM TickDensity getDensity = TM $ \env st -> (density env, noFVs, st) ifDensity :: TickDensity -> TM a -> TM a -> TM a ifDensity d th el = do d0 <- getDensity; if d == d0 then th else el getFreeVars :: TM a -> TM (FreeVars, a) getFreeVars (TM m) = TM $ \ env st -> case m env st of (a, fv, st') -> ((fv,a), fv, st') freeVar :: Id -> TM () freeVar id = TM $ \ env st -> if id `elemVarSet` inScope env then ((), unitOccEnv (nameOccName (idName id)) id, st) else ((), noFVs, st) addPathEntry :: String -> TM a -> TM a addPathEntry nm = withEnv (\ env -> env { declPath = declPath env ++ [nm] }) getPathEntry :: TM [String] getPathEntry = declPath `liftM` getEnv getFileName :: TM FastString getFileName = fileName `liftM` getEnv isGoodSrcSpan' :: SrcSpan -> Bool isGoodSrcSpan' pos@(RealSrcSpan _) = srcSpanStart pos /= srcSpanEnd pos isGoodSrcSpan' (UnhelpfulSpan _) = False isGoodTickSrcSpan :: SrcSpan -> TM Bool isGoodTickSrcSpan pos = do file_name <- getFileName tickish <- tickishType `liftM` getEnv let need_same_file = tickSameFileOnly tickish same_file = Just file_name == srcSpanFileName_maybe pos return (isGoodSrcSpan' pos && (not need_same_file || same_file)) ifGoodTickSrcSpan :: SrcSpan -> TM a -> TM a -> TM a ifGoodTickSrcSpan pos then_code else_code = do good <- isGoodTickSrcSpan pos if good then then_code else else_code bindLocals :: [Id] -> TM a -> TM a bindLocals new_ids (TM m) = TM $ \ env st -> case m env{ inScope = inScope env `extendVarSetList` new_ids } st of (r, fv, st') -> (r, fv `delListFromOccEnv` occs, st') where occs = [ nameOccName (idName id) | id <- new_ids ] isBlackListed :: SrcSpan -> TM Bool isBlackListed pos = TM $ \ env st -> case Map.lookup pos (blackList env) of Nothing -> (False,noFVs,st) Just () -> (True,noFVs,st) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocTickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id) allocTickBox boxLabel countEntries topOnly pos m = ifGoodTickSrcSpan pos (do (fvs, e) <- getFreeVars m env <- getEnv tickish <- mkTickish boxLabel countEntries topOnly pos fvs (declPath env) return (L pos (HsTick tickish (L pos e))) ) (do e <- m return (L pos e) ) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocATickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id)) allocATickBox boxLabel countEntries topOnly pos fvs = ifGoodTickSrcSpan pos (do let mydecl_path = case boxLabel of TopLevelBox x -> x LocalBox xs -> xs _ -> panic "allocATickBox" tickish <- mkTickish boxLabel countEntries topOnly pos fvs mydecl_path return (Just tickish) ) (return Nothing) mkTickish :: BoxLabel -> Bool -> Bool -> SrcSpan -> OccEnv Id -> [String] -> TM (Tickish Id) mkTickish boxLabel countEntries topOnly pos fvs decl_path = do let ids = filter (not . isUnLiftedType . idType) $ occEnvElts fvs -- unlifted types cause two problems here: -- * we can't bind them at the GHCi prompt -- (bindLocalsAtBreakpoint already fliters them out), -- * the simplifier might try to substitute a literal for -- the Id, and we can't handle that. me = (pos, decl_path, map (nameOccName.idName) ids, boxLabel) cc_name | topOnly = head decl_path | otherwise = concat (intersperse "." decl_path) dflags <- getDynFlags env <- getEnv case tickishType env of HpcTicks -> do c <- liftM tickBoxCount getState setState $ \st -> st { tickBoxCount = c + 1 , mixEntries = me : mixEntries st } return $ HpcTick (this_mod env) c ProfNotes -> do ccUnique <- getUniqueM let cc = mkUserCC (mkFastString cc_name) (this_mod env) pos ccUnique count = countEntries && gopt Opt_ProfCountEntries dflags return $ ProfNote cc count True{-scopes-} Breakpoints -> do c <- liftM breakCount getState setState $ \st -> st { breakCount = c + 1 , breaks = me:breaks st } return $ Breakpoint c ids SourceNotes | RealSrcSpan pos' <- pos -> return $ SourceNote pos' cc_name _otherwise -> panic "mkTickish: bad source span!" allocBinTickBox :: (Bool -> BoxLabel) -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id) allocBinTickBox boxLabel pos m = do env <- getEnv case tickishType env of HpcTicks -> do e <- liftM (L pos) m ifGoodTickSrcSpan pos (mkBinTickBoxHpc boxLabel pos e) (return e) _other -> allocTickBox (ExpBox False) False False pos m mkBinTickBoxHpc :: (Bool -> BoxLabel) -> SrcSpan -> LHsExpr Id -> TM (LHsExpr Id) mkBinTickBoxHpc boxLabel pos e = TM $ \ env st -> let meT = (pos,declPath env, [],boxLabel True) meF = (pos,declPath env, [],boxLabel False) meE = (pos,declPath env, [],ExpBox False) c = tickBoxCount st mes = mixEntries st in ( L pos $ HsTick (HpcTick (this_mod env) c) $ L pos $ HsBinTick (c+1) (c+2) e -- notice that F and T are reversed, -- because we are building the list in -- reverse... , noFVs , st {tickBoxCount=c+3 , mixEntries=meF:meT:meE:mes} ) mkHpcPos :: SrcSpan -> HpcPos mkHpcPos pos@(RealSrcSpan s) | isGoodSrcSpan' pos = toHpcPos (srcSpanStartLine s, srcSpanStartCol s, srcSpanEndLine s, srcSpanEndCol s - 1) -- the end column of a SrcSpan is one -- greater than the last column of the -- span (see SrcLoc), whereas HPC -- expects to the column range to be -- inclusive, hence we subtract one above. mkHpcPos _ = panic "bad source span; expected such spans to be filtered out" hpcSrcSpan :: SrcSpan hpcSrcSpan = mkGeneralSrcSpan (fsLit "Haskell Program Coverage internals") matchesOneOfMany :: [LMatch Id body] -> Bool matchesOneOfMany lmatches = sum (map matchCount lmatches) > 1 where matchCount (L _ (Match _ _pats _ty (GRHSs grhss _binds))) = length grhss type MixEntry_ = (SrcSpan, [String], [OccName], BoxLabel) -- For the hash value, we hash everything: the file name, -- the timestamp of the original source file, the tab stop, -- and the mix entries. We cheat, and hash the show'd string. -- This hash only has to be hashed at Mix creation time, -- and is for sanity checking only. mixHash :: FilePath -> UTCTime -> Int -> [MixEntry] -> Int mixHash file tm tabstop entries = fromIntegral $ hashString (show $ Mix file tm 0 tabstop entries) {- ************************************************************************ * * * initialisation * * ************************************************************************ Each module compiled with -fhpc declares an initialisation function of the form `hpc_init_<module>()`, which is emitted into the _stub.c file and annotated with __attribute__((constructor)) so that it gets executed at startup time. The function's purpose is to call hs_hpc_module to register this module with the RTS, and it looks something like this: static void hpc_init_Main(void) __attribute__((constructor)); static void hpc_init_Main(void) {extern StgWord64 _hpc_tickboxes_Main_hpc[]; hs_hpc_module("Main",8,1150288664,_hpc_tickboxes_Main_hpc);} -} hpcInitCode :: Module -> HpcInfo -> SDoc hpcInitCode _ (NoHpcInfo {}) = Outputable.empty hpcInitCode this_mod (HpcInfo tickCount hashNo) = vcat [ text "static void hpc_init_" <> ppr this_mod <> text "(void) __attribute__((constructor));" , text "static void hpc_init_" <> ppr this_mod <> text "(void)" , braces (vcat [ ptext (sLit "extern StgWord64 ") <> tickboxes <> ptext (sLit "[]") <> semi, ptext (sLit "hs_hpc_module") <> parens (hcat (punctuate comma [ doubleQuotes full_name_str, int tickCount, -- really StgWord32 int hashNo, -- really StgWord32 tickboxes ])) <> semi ]) ] where tickboxes = undefined --TODO: HPC: ppr (mkHpcTicksLabel $ this_mod) module_name = hcat (map (text.charToC) $ bytesFS (moduleNameFS (Module.moduleName this_mod))) package_name = hcat (map (text.charToC) $ bytesFS (unitIdFS (moduleUnitId this_mod))) full_name_str | moduleUnitId this_mod == mainUnitId = module_name | otherwise = package_name <> char '/' <> module_name
pparkkin/eta
compiler/ETA/DeSugar/Coverage.hs
bsd-3-clause
49,042
0
25
14,719
13,053
6,634
6,419
932
8
-- An example of RelaxedPolyRec in action which came up -- on Haskell Cafe June 2010 (Job Vranish) module Foo where import Data.Maybe -- The fixed point datatype data Y f = Y (f (Y f)) -- Silly dummy function maybeToInt :: Maybe a -> Int maybeToInt = length . maybeToList --------------------------- -- f and g are mutually recursive -- Even though f has a totally monomorphic -- signature, g has a very polymorphic one f :: Y Maybe -> Int f (Y x) = g maybeToInt x -- With RelaxedPolyRec we can infer this type -- g :: Functor f => (f Int -> b) -> f (Y Maybe) -> b g h x = h $ fmap f x -- 'test' checks that g's type is polymorphic enough test :: Functor f => (f Int -> b) -> f (Y Maybe) -> b test = g
nushio3/ghc
testsuite/tests/typecheck/should_compile/PolyRec.hs
bsd-3-clause
739
0
10
185
157
86
71
10
1
module HaskQuery.AutoIndex where import qualified Data.IntMap.Lazy data InsertSet a = InsertSet { inserted :: Data.IntMap.Lazy.IntMap a } data DeleteSet a = DeleteSet { deleted :: Data.IntMap.Lazy.IntMap a } data UpdateSet a = UpdateSet { updated :: Data.IntMap.Lazy.IntMap (a,a) } data ChangeSet a = Insert (InsertSet a) | Delete (DeleteSet a) | Update (UpdateSet a) data Auto a b = Auto { updateAuto :: b -> a -> (Auto a b), readAuto :: b} instance Show b => Show(Auto a b) where show auto = "Auto { " ++ (show $ readAuto auto) ++ " }" type UpdatableIndex a index = Auto (ChangeSet a) index updateAutoWithInput :: Auto a b -> a -> Auto a b updateAutoWithInput auto input = (updateAuto auto) (readAuto auto) input updateEmptyIndex :: () -> a -> Auto a () updateEmptyIndex index changeSet = emptyIndex emptyIndex = Auto { updateAuto = updateEmptyIndex, readAuto = ()}
stevechy/haskellEditor
ext-src/HaskQueryPackage/HaskQuery/AutoIndex.hs
bsd-3-clause
889
0
12
169
336
187
149
15
1