_id
stringlengths 64
64
| repository
stringlengths 6
84
| name
stringlengths 4
110
| content
stringlengths 0
248k
| license
null | download_url
stringlengths 89
454
| language
stringclasses 7
values | comments
stringlengths 0
74.6k
| code
stringlengths 0
248k
|
---|---|---|---|---|---|---|---|---|
40b623872bc9f54d2eb0627e7c2718cb791781987b6506bb740626d658aa658f | fossas/fossa-cli | Fingerprint.hs | # LANGUAGE RecordWildCards #
# LANGUAGE RoleAnnotations #
module App.Fossa.VSI.Fingerprint (
fingerprintRaw,
fingerprintContentsRaw,
fingerprintCommentStripped,
fingerprint,
Fingerprint,
Raw,
CommentStripped,
Combined (..),
) where
import Conduit (ConduitT, await, filterC, linesUnboundedAsciiC, mapC, runConduitRes, sourceFile, yield, (.|))
import Control.Algebra (Has)
import Control.Effect.Diagnostics (Diagnostics, context, fatalOnIOException)
import Control.Effect.Exception (Lift)
import Control.Effect.Lift (sendIO)
import Crypto.Hash (Digest, HashAlgorithm, SHA256 (..))
import Data.Aeson (ToJSON, object, toJSON, (.=))
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.Conduit.Extra (sinkHash)
import Data.Maybe (fromMaybe)
import Data.String.Conversion (ToText (..))
import Data.Text (Text)
import Data.Word8 (isSpace)
import Discovery.Walk (WalkStep (..), walk')
import Effect.ReadFS (ReadFS, contentIsBinary)
import Path (Abs, Dir, File, Path, toFilePath)
| Fingerprint deterministically idenfies a file and is derived from its content .
--
-- The type variable is:
--
@k@ - Kind , the kind of fingerprint computed .
--
For ease of implementation , the backing representation of a @Fingerprint@ instance is a @Base16@ encoded @Text@.
newtype Fingerprint k = Fingerprint Text deriving (Show, Eq, ToJSON)
type role Fingerprint nominal
-- | Represents a 'Fingerprint' derived from the unmodified content of a file.
data Raw
-- | Represents a 'Fingerprint' derived from the content of a file with all C-style comments removed.
data CommentStripped
instance ToText (Fingerprint k) where
toText (Fingerprint k) = k
-- | Represents the result of running all fingerprinting implementations on a file.
data Combined = Combined
{ combinedRaw :: Fingerprint Raw
, combinedCommentStripped :: Maybe (Fingerprint CommentStripped)
}
deriving (Show, Eq)
instance ToJSON Combined where
toJSON Combined{..} =
object
[ "sha_256" .= toText combinedRaw
, "comment_stripped:sha_256" .= fmap toText combinedCommentStripped
]
encodeFingerprint :: Digest SHA256 -> Fingerprint t
encodeFingerprint = Fingerprint . toText . show
-- | Hashes the whole contents of the given file in constant memory.
hashBinaryFile :: (Has (Lift IO) sig m, Has Diagnostics sig m, HashAlgorithm hash) => FilePath -> m (Digest hash)
hashBinaryFile fp =
context "as binary" $
(fatalOnIOException "hash binary file") . sendIO . runConduitRes $
sourceFile fp .| sinkHash
hashTextFileCommentStripped :: (Has (Lift IO) sig m, Has Diagnostics sig m, HashAlgorithm hash) => FilePath -> m (Digest hash)
hashTextFileCommentStripped file =
(fatalOnIOException "hash text file comment stripped") . sendIO . runConduitRes $
sourceFile file -- Read from the file
Strip comments
.| sinkHash -- Hash the result
hashTextFile :: (Has (Lift IO) sig m, Has Diagnostics sig m, HashAlgorithm hash) => FilePath -> m (Digest hash)
hashTextFile file =
context "as text" $
(fatalOnIOException "hash text file") . sendIO . runConduitRes $
sourceFile file -- Read from the file
.| linesUnboundedAsciiC -- Split into lines (for @stripCrLines@)
.| stripCrLines -- Normalize CRLF -> LF
.| mapC (<> "\n") -- Always append a newline here
.| sinkHash -- Hash the result
fingerprintRaw :: (Has ReadFS sig m, Has (Lift IO) sig m, Has Diagnostics sig m) => Path Abs File -> m (Fingerprint Raw)
fingerprintRaw file = context "raw" $ contentIsBinary file >>= doFingerprint
where
doFingerprint isBinary = do
let hasher = if isBinary then hashBinaryFile else hashTextFile
fp <- hasher $ toFilePath file
pure $ encodeFingerprint fp
fingerprintContentsRaw :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Lift IO) sig m) => Path Abs Dir -> m [Fingerprint Raw]
fingerprintContentsRaw = walk' $ \_ _ files -> do
fps <- traverse fingerprintRaw files
pure (fps, WalkContinue)
fingerprintCommentStripped :: (Has ReadFS sig m, Has (Lift IO) sig m, Has Diagnostics sig m) => Path Abs File -> m (Maybe (Fingerprint CommentStripped))
fingerprintCommentStripped file = context "comment stripped" $ contentIsBinary file >>= doFingerprint
where
doFingerprint True = pure Nothing -- Don't attempt to comment strip binary files
doFingerprint False = do
fp <- hashTextFileCommentStripped $ toFilePath file
pure . Just $ encodeFingerprint fp
fingerprint :: (Has ReadFS sig m, Has (Lift IO) sig m, Has Diagnostics sig m) => Path Abs File -> m Combined
fingerprint file =
context "fingerprint combined" $
Combined
<$> fingerprintRaw file
<*> fingerprintCommentStripped file
-- | Converts CRLF line endings into LF line endings.
-- Must run after a @ConuitT@ that converts an input stream into lines (for example 'linesUnboundedC').
--
Windows git implementations typically add carriage returns before each newline when checked out .
However , crawlers are run on Linux , so are n't expecting files to have carriage returns .
-- While this does cause a hash mismatch on files that legitimately have CRLF endings that weren't added by git, we believe this results in fewer mismatches.
stripCrLines :: Monad m => ConduitT ByteString ByteString m ()
stripCrLines = do
chunk <- await
case chunk of
Nothing -> pure ()
Just line -> do
yield $ fromMaybe line (BS.stripSuffix "\r" line)
stripCrLines
| This implementation is based on the comment strip logic from the internal logic used when crawling OSS components .
-- It is very basic:
--
-- * Only works for C-style comments
-- * Only catches @\\n@ newlines
-- * Doesn't handle edge cases (escaped comments for example)
-- * Also omits any blank lines
-- * Trims any trailing newline off the content
--
-- Despite these drawbacks, we have to reimplement it the same way so that fingerprints line up correctly in the VSI analysis service.
--
-- Uses @ByteString@ instead of @Text@ to replicate the functionality of the Go implementation of this logic.
basicCStyleCommentStripC :: Monad m => ConduitT ByteString ByteString m ()
basicCStyleCommentStripC =
linesUnboundedAsciiC
.| stripCrLines
.| process
.| mapC stripSpace
.| filterC (not . BS.null)
.| bufferedNewline Nothing
where
-- The original version of this function included newlines between each line but did not include a trailing newline, even when originally present in the file.
-- We have to keep this compatible, because all of our fingerprint corpus relies on how this fingerprint function works.
-- As we read through the input stream, instead of writing lines directly we'll buffer one at a time.
-- This way we can delay the decision of whether to write a trailing newline until we know if we're at the end of the input.
bufferedNewline buf = do
chunk <- await
case (chunk, buf) of
First line lands here and is always buffered .
(Just line, Nothing) -> bufferedNewline (Just line)
-- All lines other than the last yield with a newline appended.
-- This only happens when we know we have another line incoming.
(Just incomingLine, Just bufferedLine) -> do
yield $ bufferedLine <> "\n"
bufferedNewline (Just incomingLine)
-- No incoming line, so the buffered line is the last one.
-- For compatibility, this line must not have a trailing newline appended.
(Nothing, Just bufferedLine) -> yield bufferedLine
-- All lines have been written, so just exit.
-- Technically unreachable since we don't recurse after yielding the last line.
(Nothing, Nothing) -> pure ()
-- Throws away lines until we find a line with the literal @*/@.
-- Once found, yields all the text *after* the literal and returns to the standard 'process' function.
processInComment = do
chunk <- await
case chunk of
Nothing -> pure ()
Just line -> case breakSubstringAndRemove "*/" line of
Nothing -> processInComment
Just (_, lineAfterComment) -> do
yield lineAfterComment
process
-- Yields lines that do not contain comments without modification.
For lines which contain a single - line comment ( @//@ ) , yields only the text leading up to that comment ( so @foo // comment@ becomes @foo @ ) .
-- For lines which contain the literal @/*@:
-- - Yields the text leading up to the literal.
-- - Enters the specialized 'processInComment' function.
process = do
chunk <- await
case chunk of
Nothing -> pure ()
Just line -> case breakSubstringAndRemove "/*" line of
Nothing -> do
yield $ fst (BS.breakSubstring "//" line)
process
Just (lineBeforeComment, _) -> do
yield lineBeforeComment
processInComment
| Like ' BS.breakSubstring ' , but with two differences .
--
1 . This removes the text that was broken on :
--
> BS.breakSubstring " foo " " foobar " = = ( " " , " foobar " )
> breakSubstringAndRemove " foo " " foobar " = = ( " " , " bar " )
--
2 . If the substring was not found , the result is @Nothing@ ,
instead of one of the options being a blank @ByteString@.
breakSubstringAndRemove :: ByteString -> ByteString -> Maybe (ByteString, ByteString)
breakSubstringAndRemove needle haystack = do
let (before, after) = BS.breakSubstring needle haystack
if needle `BS.isPrefixOf` after
then pure (before, BS.drop (BS.length needle) after)
else Nothing
-- | Remove leading and trailing spaces.
stripSpace :: ByteString -> ByteString
stripSpace s = BS.dropWhileEnd isSpace $ BS.dropWhile isSpace s
| null | https://raw.githubusercontent.com/fossas/fossa-cli/219bdc6f38d401df2bdb7991114c54083a75f56b/src/App/Fossa/VSI/Fingerprint.hs | haskell |
The type variable is:
| Represents a 'Fingerprint' derived from the unmodified content of a file.
| Represents a 'Fingerprint' derived from the content of a file with all C-style comments removed.
| Represents the result of running all fingerprinting implementations on a file.
| Hashes the whole contents of the given file in constant memory.
Read from the file
Hash the result
Read from the file
Split into lines (for @stripCrLines@)
Normalize CRLF -> LF
Always append a newline here
Hash the result
Don't attempt to comment strip binary files
| Converts CRLF line endings into LF line endings.
Must run after a @ConuitT@ that converts an input stream into lines (for example 'linesUnboundedC').
While this does cause a hash mismatch on files that legitimately have CRLF endings that weren't added by git, we believe this results in fewer mismatches.
It is very basic:
* Only works for C-style comments
* Only catches @\\n@ newlines
* Doesn't handle edge cases (escaped comments for example)
* Also omits any blank lines
* Trims any trailing newline off the content
Despite these drawbacks, we have to reimplement it the same way so that fingerprints line up correctly in the VSI analysis service.
Uses @ByteString@ instead of @Text@ to replicate the functionality of the Go implementation of this logic.
The original version of this function included newlines between each line but did not include a trailing newline, even when originally present in the file.
We have to keep this compatible, because all of our fingerprint corpus relies on how this fingerprint function works.
As we read through the input stream, instead of writing lines directly we'll buffer one at a time.
This way we can delay the decision of whether to write a trailing newline until we know if we're at the end of the input.
All lines other than the last yield with a newline appended.
This only happens when we know we have another line incoming.
No incoming line, so the buffered line is the last one.
For compatibility, this line must not have a trailing newline appended.
All lines have been written, so just exit.
Technically unreachable since we don't recurse after yielding the last line.
Throws away lines until we find a line with the literal @*/@.
Once found, yields all the text *after* the literal and returns to the standard 'process' function.
Yields lines that do not contain comments without modification.
For lines which contain the literal @/*@:
- Yields the text leading up to the literal.
- Enters the specialized 'processInComment' function.
| Remove leading and trailing spaces. | # LANGUAGE RecordWildCards #
# LANGUAGE RoleAnnotations #
module App.Fossa.VSI.Fingerprint (
fingerprintRaw,
fingerprintContentsRaw,
fingerprintCommentStripped,
fingerprint,
Fingerprint,
Raw,
CommentStripped,
Combined (..),
) where
import Conduit (ConduitT, await, filterC, linesUnboundedAsciiC, mapC, runConduitRes, sourceFile, yield, (.|))
import Control.Algebra (Has)
import Control.Effect.Diagnostics (Diagnostics, context, fatalOnIOException)
import Control.Effect.Exception (Lift)
import Control.Effect.Lift (sendIO)
import Crypto.Hash (Digest, HashAlgorithm, SHA256 (..))
import Data.Aeson (ToJSON, object, toJSON, (.=))
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.Conduit.Extra (sinkHash)
import Data.Maybe (fromMaybe)
import Data.String.Conversion (ToText (..))
import Data.Text (Text)
import Data.Word8 (isSpace)
import Discovery.Walk (WalkStep (..), walk')
import Effect.ReadFS (ReadFS, contentIsBinary)
import Path (Abs, Dir, File, Path, toFilePath)
| Fingerprint deterministically idenfies a file and is derived from its content .
@k@ - Kind , the kind of fingerprint computed .
For ease of implementation , the backing representation of a @Fingerprint@ instance is a @Base16@ encoded @Text@.
newtype Fingerprint k = Fingerprint Text deriving (Show, Eq, ToJSON)
type role Fingerprint nominal
data Raw
data CommentStripped
instance ToText (Fingerprint k) where
toText (Fingerprint k) = k
data Combined = Combined
{ combinedRaw :: Fingerprint Raw
, combinedCommentStripped :: Maybe (Fingerprint CommentStripped)
}
deriving (Show, Eq)
instance ToJSON Combined where
toJSON Combined{..} =
object
[ "sha_256" .= toText combinedRaw
, "comment_stripped:sha_256" .= fmap toText combinedCommentStripped
]
encodeFingerprint :: Digest SHA256 -> Fingerprint t
encodeFingerprint = Fingerprint . toText . show
hashBinaryFile :: (Has (Lift IO) sig m, Has Diagnostics sig m, HashAlgorithm hash) => FilePath -> m (Digest hash)
hashBinaryFile fp =
context "as binary" $
(fatalOnIOException "hash binary file") . sendIO . runConduitRes $
sourceFile fp .| sinkHash
hashTextFileCommentStripped :: (Has (Lift IO) sig m, Has Diagnostics sig m, HashAlgorithm hash) => FilePath -> m (Digest hash)
hashTextFileCommentStripped file =
(fatalOnIOException "hash text file comment stripped") . sendIO . runConduitRes $
Strip comments
hashTextFile :: (Has (Lift IO) sig m, Has Diagnostics sig m, HashAlgorithm hash) => FilePath -> m (Digest hash)
hashTextFile file =
context "as text" $
(fatalOnIOException "hash text file") . sendIO . runConduitRes $
fingerprintRaw :: (Has ReadFS sig m, Has (Lift IO) sig m, Has Diagnostics sig m) => Path Abs File -> m (Fingerprint Raw)
fingerprintRaw file = context "raw" $ contentIsBinary file >>= doFingerprint
where
doFingerprint isBinary = do
let hasher = if isBinary then hashBinaryFile else hashTextFile
fp <- hasher $ toFilePath file
pure $ encodeFingerprint fp
fingerprintContentsRaw :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Lift IO) sig m) => Path Abs Dir -> m [Fingerprint Raw]
fingerprintContentsRaw = walk' $ \_ _ files -> do
fps <- traverse fingerprintRaw files
pure (fps, WalkContinue)
fingerprintCommentStripped :: (Has ReadFS sig m, Has (Lift IO) sig m, Has Diagnostics sig m) => Path Abs File -> m (Maybe (Fingerprint CommentStripped))
fingerprintCommentStripped file = context "comment stripped" $ contentIsBinary file >>= doFingerprint
where
doFingerprint False = do
fp <- hashTextFileCommentStripped $ toFilePath file
pure . Just $ encodeFingerprint fp
fingerprint :: (Has ReadFS sig m, Has (Lift IO) sig m, Has Diagnostics sig m) => Path Abs File -> m Combined
fingerprint file =
context "fingerprint combined" $
Combined
<$> fingerprintRaw file
<*> fingerprintCommentStripped file
Windows git implementations typically add carriage returns before each newline when checked out .
However , crawlers are run on Linux , so are n't expecting files to have carriage returns .
stripCrLines :: Monad m => ConduitT ByteString ByteString m ()
stripCrLines = do
chunk <- await
case chunk of
Nothing -> pure ()
Just line -> do
yield $ fromMaybe line (BS.stripSuffix "\r" line)
stripCrLines
| This implementation is based on the comment strip logic from the internal logic used when crawling OSS components .
basicCStyleCommentStripC :: Monad m => ConduitT ByteString ByteString m ()
basicCStyleCommentStripC =
linesUnboundedAsciiC
.| stripCrLines
.| process
.| mapC stripSpace
.| filterC (not . BS.null)
.| bufferedNewline Nothing
where
bufferedNewline buf = do
chunk <- await
case (chunk, buf) of
First line lands here and is always buffered .
(Just line, Nothing) -> bufferedNewline (Just line)
(Just incomingLine, Just bufferedLine) -> do
yield $ bufferedLine <> "\n"
bufferedNewline (Just incomingLine)
(Nothing, Just bufferedLine) -> yield bufferedLine
(Nothing, Nothing) -> pure ()
processInComment = do
chunk <- await
case chunk of
Nothing -> pure ()
Just line -> case breakSubstringAndRemove "*/" line of
Nothing -> processInComment
Just (_, lineAfterComment) -> do
yield lineAfterComment
process
For lines which contain a single - line comment ( @//@ ) , yields only the text leading up to that comment ( so @foo // comment@ becomes @foo @ ) .
process = do
chunk <- await
case chunk of
Nothing -> pure ()
Just line -> case breakSubstringAndRemove "/*" line of
Nothing -> do
yield $ fst (BS.breakSubstring "//" line)
process
Just (lineBeforeComment, _) -> do
yield lineBeforeComment
processInComment
| Like ' BS.breakSubstring ' , but with two differences .
1 . This removes the text that was broken on :
> BS.breakSubstring " foo " " foobar " = = ( " " , " foobar " )
> breakSubstringAndRemove " foo " " foobar " = = ( " " , " bar " )
2 . If the substring was not found , the result is @Nothing@ ,
instead of one of the options being a blank @ByteString@.
breakSubstringAndRemove :: ByteString -> ByteString -> Maybe (ByteString, ByteString)
breakSubstringAndRemove needle haystack = do
let (before, after) = BS.breakSubstring needle haystack
if needle `BS.isPrefixOf` after
then pure (before, BS.drop (BS.length needle) after)
else Nothing
stripSpace :: ByteString -> ByteString
stripSpace s = BS.dropWhileEnd isSpace $ BS.dropWhile isSpace s
|
16e05a50a2c943c23022e66fa91e74817dcb304a354d6c7af12d1838da897655 | tonsky/datascript | query.cljc | (ns datascript.test.query
(:require
#?(:cljs [cljs.test :as t :refer-macros [is are deftest testing]]
:clj [clojure.test :as t :refer [is are deftest testing]])
[datascript.core :as d]
[datascript.db :as db]
[datascript.test.core :as tdc])
#?(:clj
(:import [clojure.lang ExceptionInfo])))
(deftest test-joins
(let [db (-> (d/empty-db)
(d/db-with [ { :db/id 1, :name "Ivan", :age 15 }
{ :db/id 2, :name "Petr", :age 37 }
{ :db/id 3, :name "Ivan", :age 37 }
{ :db/id 4, :age 15 }]))]
(is (= (d/q '[:find ?e
:where [?e :name]] db)
#{[1] [2] [3]}))
(is (= (d/q '[:find ?e ?v
:where [?e :name "Ivan"]
[?e :age ?v]] db)
#{[1 15] [3 37]}))
(is (= (d/q '[:find ?e1 ?e2
:where [?e1 :name ?n]
[?e2 :name ?n]] db)
#{[1 1] [2 2] [3 3] [1 3] [3 1]}))
(is (= (d/q '[:find ?e ?e2 ?n
:where [?e :name "Ivan"]
[?e :age ?a]
[?e2 :age ?a]
[?e2 :name ?n]] db)
#{[1 1 "Ivan"]
[3 3 "Ivan"]
[3 2 "Petr"]}))))
(deftest test-q-many
(let [db (-> (d/empty-db {:aka {:db/cardinality :db.cardinality/many}})
(d/db-with [ [:db/add 1 :name "Ivan"]
[:db/add 1 :aka "ivolga"]
[:db/add 1 :aka "pi"]
[:db/add 2 :name "Petr"]
[:db/add 2 :aka "porosenok"]
[:db/add 2 :aka "pi"] ]))]
(is (= (d/q '[:find ?n1 ?n2
:where [?e1 :aka ?x]
[?e2 :aka ?x]
[?e1 :name ?n1]
[?e2 :name ?n2]] db)
#{["Ivan" "Ivan"]
["Petr" "Petr"]
["Ivan" "Petr"]
["Petr" "Ivan"]}))))
(deftest test-q-coll
(let [db [ [1 :name "Ivan"]
[1 :age 19]
[1 :aka "dragon_killer_94"]
[1 :aka "-=autobot=-"] ] ]
(is (= (d/q '[ :find ?n ?a
:where [?e :aka "dragon_killer_94"]
[?e :name ?n]
[?e :age ?a]] db)
#{["Ivan" 19]})))
(testing "Query over long tuples"
(let [db [ [1 :name "Ivan" 945 :db/add]
[1 :age 39 999 :db/retract]] ]
(is (= (d/q '[ :find ?e ?v
:where [?e :name ?v]] db)
#{[1 "Ivan"]}))
(is (= (d/q '[ :find ?e ?a ?v ?t
:where [?e ?a ?v ?t :db/retract]] db)
#{[1 :age 39 999]})))))
(deftest test-q-in
(let [db (-> (d/empty-db)
(d/db-with [ { :db/id 1, :name "Ivan", :age 15 }
{ :db/id 2, :name "Petr", :age 37 }
{ :db/id 3, :name "Ivan", :age 37 }]))
query '{:find [?e]
:in [$ ?attr ?value]
:where [[?e ?attr ?value]]}]
(is (= (d/q query db :name "Ivan")
#{[1] [3]}))
(is (= (d/q query db :age 37)
#{[2] [3]}))
(testing "Named DB"
(is (= (d/q '[:find ?a ?v
:in $db ?e
:where [$db ?e ?a ?v]] db 1)
#{[:name "Ivan"]
[:age 15]})))
(testing "DB join with collection"
(is (= (d/q '[:find ?e ?email
:in $ $b
:where [?e :name ?n]
[$b ?n ?email]]
db
[["Ivan" ""]
["Petr" ""]])
#{[1 ""]
[2 ""]
[3 ""]})))
(testing "Query without DB"
(is (= (d/q '[:find ?a ?b
:in ?a ?b]
10 20)
#{[10 20]})))
(is (thrown-msg? "Extra inputs passed, expected: [], got: 1"
(d/q '[:find ?e :where [(inc 1) ?e]] db)))
(is (thrown-msg? "Too few inputs passed, expected: [$ $2], got: 1"
(d/q '[:find ?e :in $ $2 :where [?e]] db)))
(is (thrown-msg? "Extra inputs passed, expected: [$], got: 2"
(d/q '[:find ?e :where [?e]] db db)))
(is (thrown-msg? "Extra inputs passed, expected: [$ $2], got: 3"
(d/q '[:find ?e :in $ $2 :where [?e]] db db db)))))
(deftest test-bindings
(let [db (-> (d/empty-db)
(d/db-with [ { :db/id 1, :name "Ivan", :age 15 }
{ :db/id 2, :name "Petr", :age 37 }
{ :db/id 3, :name "Ivan", :age 37 }]))]
(testing "Relation binding"
(is (= (d/q '[:find ?e ?email
:in $ [[?n ?email]]
:where [?e :name ?n]]
db
[["Ivan" ""]
["Petr" ""]])
#{[1 ""]
[2 ""]
[3 ""]})))
(testing "Tuple binding"
(is (= (d/q '[:find ?e
:in $ [?name ?age]
:where [?e :name ?name]
[?e :age ?age]]
db ["Ivan" 37])
#{[3]})))
(testing "Collection binding"
(is (= (d/q '[:find ?attr ?value
:in $ ?e [?attr ...]
:where [?e ?attr ?value]]
db 1 [:name :age])
#{[:name "Ivan"] [:age 15]})))
(testing "Empty coll handling"
(is (= (d/q '[:find ?id
:in $ [?id ...]
:where [?id :age _]]
[[1 :name "Ivan"]
[2 :name "Petr"]]
[])
#{}))
(is (= (d/q '[:find ?id
:in $ [[?id]]
:where [?id :age _]]
[[1 :name "Ivan"]
[2 :name "Petr"]]
[])
#{})))
(testing "Placeholders"
(is (= (d/q '[:find ?x ?z
:in [?x _ ?z]]
[:x :y :z])
#{[:x :z]}))
(is (= (d/q '[:find ?x ?z
:in [[?x _ ?z]]]
[[:x :y :z] [:a :b :c]])
#{[:x :z] [:a :c]})))
(testing "Error reporting"
(is (thrown-with-msg? ExceptionInfo #"Cannot bind value :a to tuple \[\?a \?b\]"
(d/q '[:find ?a ?b :in [?a ?b]] :a)))
(is (thrown-with-msg? ExceptionInfo #"Cannot bind value :a to collection \[\?a \.\.\.\]"
(d/q '[:find ?a :in [?a ...]] :a)))
(is (thrown-with-msg? ExceptionInfo #"Not enough elements in a collection \[:a\] to bind tuple \[\?a \?b\]"
(d/q '[:find ?a ?b :in [?a ?b]] [:a]))))
))
(deftest test-nested-bindings
(is (= (d/q '[:find ?k ?v
:in [[?k ?v] ...]
:where [(> ?v 1)]]
{:a 1, :b 2, :c 3})
#{[:b 2] [:c 3]}))
(is (= (d/q '[:find ?k ?min ?max
:in [[?k ?v] ...] ?minmax
:where [(?minmax ?v) [?min ?max]]
[(> ?max ?min)]]
{:a [1 2 3 4]
:b [5 6 7]
:c [3]}
#(vector (reduce min %) (reduce max %)))
#{[:a 1 4] [:b 5 7]}))
(is (= (d/q '[:find ?k ?x
:in [[?k [?min ?max]] ...] ?range
:where [(?range ?min ?max) [?x ...]]
[(even? ?x)]]
{:a [1 7]
:b [2 4]}
range)
#{[:a 2] [:a 4] [:a 6]
[:b 2]})))
(deftest test-built-in-regex
(is (= (d/q '[:find ?name
:in [?name ...] ?key
:where [(re-pattern ?key) ?pattern]
[(re-find ?pattern ?name)]]
#{"abc" "abcX" "aXb"}
"X")
#{["abcX"] ["aXb"]})))
(deftest test-built-in-get
(is (= (d/q '[:find ?m ?m-value
:in [[?k ?m] ...] ?m-key
:where [(get ?m ?m-key) ?m-value]]
{:a {:b 1}
:c {:d 2}}
:d)
#{[{:d 2} 2]})))
(deftest ^{:doc "issue-385"} test-join-unrelated
(is (= #{}
(d/q '[:find ?name
:in $ ?my-fn
:where [?e :person/name ?name]
[(?my-fn) ?result]
[(< ?result 3)]]
(d/db-with (d/empty-db) [{:person/name "Joe"}])
(fn [] 5)))))
(deftest ^{:doc "issue-425"} test-symbol-comparison
(is (= [2]
(d/q
'[:find [?e ...]
:where [?e :s b]]
'[[1 :s a]
[2 :s b]])))
(let [db (-> (d/empty-db)
(d/db-with '[{:db/id 1, :s a}
{:db/id 2, :s b}]))]
(is (= [2]
(d/q
'[:find [?e ...]
:where [?e :s b]]
db)))))
#_(require 'datascript.test.query :reload)
#_(clojure.test/test-ns 'datascript.test.query)
| null | https://raw.githubusercontent.com/tonsky/datascript/147a5a98f81fe811438b4e79341e058aa48db8f7/test/datascript/test/query.cljc | clojure | (ns datascript.test.query
(:require
#?(:cljs [cljs.test :as t :refer-macros [is are deftest testing]]
:clj [clojure.test :as t :refer [is are deftest testing]])
[datascript.core :as d]
[datascript.db :as db]
[datascript.test.core :as tdc])
#?(:clj
(:import [clojure.lang ExceptionInfo])))
(deftest test-joins
(let [db (-> (d/empty-db)
(d/db-with [ { :db/id 1, :name "Ivan", :age 15 }
{ :db/id 2, :name "Petr", :age 37 }
{ :db/id 3, :name "Ivan", :age 37 }
{ :db/id 4, :age 15 }]))]
(is (= (d/q '[:find ?e
:where [?e :name]] db)
#{[1] [2] [3]}))
(is (= (d/q '[:find ?e ?v
:where [?e :name "Ivan"]
[?e :age ?v]] db)
#{[1 15] [3 37]}))
(is (= (d/q '[:find ?e1 ?e2
:where [?e1 :name ?n]
[?e2 :name ?n]] db)
#{[1 1] [2 2] [3 3] [1 3] [3 1]}))
(is (= (d/q '[:find ?e ?e2 ?n
:where [?e :name "Ivan"]
[?e :age ?a]
[?e2 :age ?a]
[?e2 :name ?n]] db)
#{[1 1 "Ivan"]
[3 3 "Ivan"]
[3 2 "Petr"]}))))
(deftest test-q-many
(let [db (-> (d/empty-db {:aka {:db/cardinality :db.cardinality/many}})
(d/db-with [ [:db/add 1 :name "Ivan"]
[:db/add 1 :aka "ivolga"]
[:db/add 1 :aka "pi"]
[:db/add 2 :name "Petr"]
[:db/add 2 :aka "porosenok"]
[:db/add 2 :aka "pi"] ]))]
(is (= (d/q '[:find ?n1 ?n2
:where [?e1 :aka ?x]
[?e2 :aka ?x]
[?e1 :name ?n1]
[?e2 :name ?n2]] db)
#{["Ivan" "Ivan"]
["Petr" "Petr"]
["Ivan" "Petr"]
["Petr" "Ivan"]}))))
(deftest test-q-coll
(let [db [ [1 :name "Ivan"]
[1 :age 19]
[1 :aka "dragon_killer_94"]
[1 :aka "-=autobot=-"] ] ]
(is (= (d/q '[ :find ?n ?a
:where [?e :aka "dragon_killer_94"]
[?e :name ?n]
[?e :age ?a]] db)
#{["Ivan" 19]})))
(testing "Query over long tuples"
(let [db [ [1 :name "Ivan" 945 :db/add]
[1 :age 39 999 :db/retract]] ]
(is (= (d/q '[ :find ?e ?v
:where [?e :name ?v]] db)
#{[1 "Ivan"]}))
(is (= (d/q '[ :find ?e ?a ?v ?t
:where [?e ?a ?v ?t :db/retract]] db)
#{[1 :age 39 999]})))))
(deftest test-q-in
(let [db (-> (d/empty-db)
(d/db-with [ { :db/id 1, :name "Ivan", :age 15 }
{ :db/id 2, :name "Petr", :age 37 }
{ :db/id 3, :name "Ivan", :age 37 }]))
query '{:find [?e]
:in [$ ?attr ?value]
:where [[?e ?attr ?value]]}]
(is (= (d/q query db :name "Ivan")
#{[1] [3]}))
(is (= (d/q query db :age 37)
#{[2] [3]}))
(testing "Named DB"
(is (= (d/q '[:find ?a ?v
:in $db ?e
:where [$db ?e ?a ?v]] db 1)
#{[:name "Ivan"]
[:age 15]})))
(testing "DB join with collection"
(is (= (d/q '[:find ?e ?email
:in $ $b
:where [?e :name ?n]
[$b ?n ?email]]
db
[["Ivan" ""]
["Petr" ""]])
#{[1 ""]
[2 ""]
[3 ""]})))
(testing "Query without DB"
(is (= (d/q '[:find ?a ?b
:in ?a ?b]
10 20)
#{[10 20]})))
(is (thrown-msg? "Extra inputs passed, expected: [], got: 1"
(d/q '[:find ?e :where [(inc 1) ?e]] db)))
(is (thrown-msg? "Too few inputs passed, expected: [$ $2], got: 1"
(d/q '[:find ?e :in $ $2 :where [?e]] db)))
(is (thrown-msg? "Extra inputs passed, expected: [$], got: 2"
(d/q '[:find ?e :where [?e]] db db)))
(is (thrown-msg? "Extra inputs passed, expected: [$ $2], got: 3"
(d/q '[:find ?e :in $ $2 :where [?e]] db db db)))))
(deftest test-bindings
(let [db (-> (d/empty-db)
(d/db-with [ { :db/id 1, :name "Ivan", :age 15 }
{ :db/id 2, :name "Petr", :age 37 }
{ :db/id 3, :name "Ivan", :age 37 }]))]
(testing "Relation binding"
(is (= (d/q '[:find ?e ?email
:in $ [[?n ?email]]
:where [?e :name ?n]]
db
[["Ivan" ""]
["Petr" ""]])
#{[1 ""]
[2 ""]
[3 ""]})))
(testing "Tuple binding"
(is (= (d/q '[:find ?e
:in $ [?name ?age]
:where [?e :name ?name]
[?e :age ?age]]
db ["Ivan" 37])
#{[3]})))
(testing "Collection binding"
(is (= (d/q '[:find ?attr ?value
:in $ ?e [?attr ...]
:where [?e ?attr ?value]]
db 1 [:name :age])
#{[:name "Ivan"] [:age 15]})))
(testing "Empty coll handling"
(is (= (d/q '[:find ?id
:in $ [?id ...]
:where [?id :age _]]
[[1 :name "Ivan"]
[2 :name "Petr"]]
[])
#{}))
(is (= (d/q '[:find ?id
:in $ [[?id]]
:where [?id :age _]]
[[1 :name "Ivan"]
[2 :name "Petr"]]
[])
#{})))
(testing "Placeholders"
(is (= (d/q '[:find ?x ?z
:in [?x _ ?z]]
[:x :y :z])
#{[:x :z]}))
(is (= (d/q '[:find ?x ?z
:in [[?x _ ?z]]]
[[:x :y :z] [:a :b :c]])
#{[:x :z] [:a :c]})))
(testing "Error reporting"
(is (thrown-with-msg? ExceptionInfo #"Cannot bind value :a to tuple \[\?a \?b\]"
(d/q '[:find ?a ?b :in [?a ?b]] :a)))
(is (thrown-with-msg? ExceptionInfo #"Cannot bind value :a to collection \[\?a \.\.\.\]"
(d/q '[:find ?a :in [?a ...]] :a)))
(is (thrown-with-msg? ExceptionInfo #"Not enough elements in a collection \[:a\] to bind tuple \[\?a \?b\]"
(d/q '[:find ?a ?b :in [?a ?b]] [:a]))))
))
(deftest test-nested-bindings
(is (= (d/q '[:find ?k ?v
:in [[?k ?v] ...]
:where [(> ?v 1)]]
{:a 1, :b 2, :c 3})
#{[:b 2] [:c 3]}))
(is (= (d/q '[:find ?k ?min ?max
:in [[?k ?v] ...] ?minmax
:where [(?minmax ?v) [?min ?max]]
[(> ?max ?min)]]
{:a [1 2 3 4]
:b [5 6 7]
:c [3]}
#(vector (reduce min %) (reduce max %)))
#{[:a 1 4] [:b 5 7]}))
(is (= (d/q '[:find ?k ?x
:in [[?k [?min ?max]] ...] ?range
:where [(?range ?min ?max) [?x ...]]
[(even? ?x)]]
{:a [1 7]
:b [2 4]}
range)
#{[:a 2] [:a 4] [:a 6]
[:b 2]})))
(deftest test-built-in-regex
(is (= (d/q '[:find ?name
:in [?name ...] ?key
:where [(re-pattern ?key) ?pattern]
[(re-find ?pattern ?name)]]
#{"abc" "abcX" "aXb"}
"X")
#{["abcX"] ["aXb"]})))
(deftest test-built-in-get
(is (= (d/q '[:find ?m ?m-value
:in [[?k ?m] ...] ?m-key
:where [(get ?m ?m-key) ?m-value]]
{:a {:b 1}
:c {:d 2}}
:d)
#{[{:d 2} 2]})))
(deftest ^{:doc "issue-385"} test-join-unrelated
(is (= #{}
(d/q '[:find ?name
:in $ ?my-fn
:where [?e :person/name ?name]
[(?my-fn) ?result]
[(< ?result 3)]]
(d/db-with (d/empty-db) [{:person/name "Joe"}])
(fn [] 5)))))
(deftest ^{:doc "issue-425"} test-symbol-comparison
(is (= [2]
(d/q
'[:find [?e ...]
:where [?e :s b]]
'[[1 :s a]
[2 :s b]])))
(let [db (-> (d/empty-db)
(d/db-with '[{:db/id 1, :s a}
{:db/id 2, :s b}]))]
(is (= [2]
(d/q
'[:find [?e ...]
:where [?e :s b]]
db)))))
#_(require 'datascript.test.query :reload)
#_(clojure.test/test-ns 'datascript.test.query)
|
|
d504d471187a067c8c39ff8f4345207146da55e6dec955b931391f5ff22e3e71 | jordanthayer/ocaml-search | line_errbar_dataset.ml | * Lines with error bars .
@author eaburns
@since 2010 - 04 - 30
@author eaburns
@since 2010-04-30
*)
open Verbosity
open Num_by_num_dataset
open Geometry
type line_errbar_style = {
dashes : Length.t array;
(* The dash pattern for the line. *)
number : int;
(* The number of the current line_errbar_dataset. *)
count : int ref;
(* A reference that counts the total number of associated
line_errbar_datasets. *)
}
(** [line_errbar_factory next_dashes ()] gets a line and errorbar
factory. This helps choosing where the error bars reside. *)
let line_errbar_factory next_dashes () =
let count = ref 0 in
(fun () ->
incr count;
{
dashes = next_dashes ();
number = !count - 1;
count = count;
})
(** [line_domain l] gets the domain of the line. *)
let line_domain l =
Array.fold_left (fun r pt ->
let min = if pt.x < r.min then pt.x else r.min
and max = if pt.x > r.max then pt.x else r.max
in range min max)
(range infinity neg_infinity) l
(** [common_domain lines] get the domain that the given lines have
in common. *)
let common_domain lines =
let domains = Array.map line_domain lines in
Array.fold_left (fun cur d ->
let min = if d.min < cur.min then cur.min else d.min
and max = if d.max > cur.max then cur.max else d.max
in range min max)
(range neg_infinity infinity) domains
(** [check_lines lines] throws out a nasty warning if the lines are
not sorted on the x-value. *)
let check_lines lines =
Array.iter
(fun line ->
ignore (Array.fold_left
(fun min pt ->
if pt.x <= min
then
vprintf verb_normal
"Lines are not sorted on x-value %f <= %f \n" pt.x min;
pt.x)
neg_infinity line))
lines
(** [mean_line ?xs domain lines] get a line that is the mean of all
of the given lines. [xs] is an array of x-values to ensure are
on the line. Each value in [xs] must already be in [domain]. *)
let mean_line ?(xs=[||]) domain lines =
let module Float_set = Set.Make(struct
type t = float
let compare (a:float) b = compare a b
end) in
(*check_lines lines;*)
let min = domain.min and max = domain.max in
let init_xset =
Array.fold_left (fun s x -> assert (x >= min); assert (x <= max);
Float_set.add x s)
Float_set.empty xs in
let xs =
Array.fold_left (fun set l ->
Array.fold_left (fun set pt ->
let x = pt.x in
if x >= min && x <= max
then Float_set.add x set
else set)
set l)
init_xset lines
in
Array.of_list (Float_set.fold
(fun x lst ->
let ys = Array.map (fun l -> interpolate l x) lines in
let mean = Statistics.mean ys in
(point x mean) :: lst)
xs [])
(** [errbars ~xrange ~num ~count ~domain lines] get the error
bars. *)
let errbars ~xrange ~num ~count ~domain lines =
let min = domain.min and max = domain.max in
let x = ref min in
let ngroups = 4. in
let numf = float num and countf = float count in
let group_width = (max -. min) /. ngroups in
let delta = group_width /. countf in
let group_start = delta /. 2. in
let group_offs = (group_start +. (delta *. numf)) /. group_width in
let group = ref (floor (min /. group_width)) in
let intervals = ref [] in
while !x < max do
let x' = (!group *. group_width) +. (group_width *. group_offs) in
if x' >= min && x' <= max
then begin
let ys = Array.map (fun l -> interpolate l x') lines in
let mean, ci = Statistics.mean_and_interval ys in
intervals := (triple x' mean ci) :: !intervals;
end;
x := x';
group := !group +. 1.;
done;
Array.of_list !intervals
* [ mean_line_and_errbars ~num ~count lines ] gets the mean line and
the error bars .
the error bars. *)
let mean_line_and_errbars ~num ~count lines =
let domain = common_domain lines in
let errbars = errbars ~xrange:domain ~num ~count ~domain lines in
let mean = mean_line domain lines in
mean, errbars (*[||]*)
type style_cache_entry =
{
n : int;
t : int;
comp : composite_dataset option;
}
* [ cache_key ~n ~t ] builds a key for the cache .
let cache_key ~n ~t = { n = n; t = t; comp = None }
module Style_cache = Weak.Make(struct
type t = style_cache_entry
let equal a b = a.n = b.n && a.t = b.t
let hash a = Hashtbl.hash (a.n, a.t)
end)
(** [filter_lines lines] filters out bad lines. For example, lines
with only a single point. *)
let filter_lines lines =
let n = Array.length lines in
let nrem =
Array.fold_left
(fun s l -> if (Array.length l) < 2 then s + 1 else s)
0 lines
in
let i = ref 0 in
if nrem > 0 then
vprintf verb_normal
"Ignoring %d lines with fewer than two points, %d lines remaining\n"
nrem (n - nrem);
Array.init (n - nrem)
(fun _ ->
while (Array.length lines.(!i)) < 2 do incr i done;
assert (!i < n);
incr i;
assert (!i > 0);
lines.(!i - 1))
(** [line_errbar_dataset style ?color ?line_width ?name lines] makes
a line and error bar dataset. *)
class line_errbar_dataset style ?color ?line_width ?name lines =
let lines = filter_lines lines in
let init_name = name in
(** [build_components ()] builds the line and errbar datasets. *)
let build_components () =
let count = !(style.count) in
let points, bars = mean_line_and_errbars style.number count lines in
(new Line_dataset.line_dataset style.dashes
?color ?line_width ?name points,
new Errbar_dataset.vertical_errbar_dataset ?color bars)
in
let line_dataset, errbar_dataset = build_components () in
object (self)
inherit dataset ?name ()
(** Caches the composite dataset based on the style. *)
val style_cache = Style_cache.create 10
val mutable computed_count = !(style.count)
val mutable composite =
new composite_dataset ?name:init_name [ line_dataset ; errbar_dataset ]
val mutable line_dataset = line_dataset
val mutable errbar_dataset = errbar_dataset
(** [consider_update] considers updating the line and errbar
datasets if the number of lines in this style has changed
since they were previously computed. *)
method private consider_update =
let cur_count = !(style.count) in
if cur_count <> computed_count then begin
let l, e = build_components () in
computed_count <- cur_count;
line_dataset <- l;
errbar_dataset <- e;
composite <-
new composite_dataset ?name [ line_dataset; errbar_dataset ];
end
(** [composite] either builds the composite or returns it from the
fields. *)
method private composite =
self#consider_update;
composite
method dimensions = self#composite#dimensions
method mean_y_value src =
self#consider_update;
line_dataset#mean_y_value src
method residual ctx ~src ~dst = self#composite#residual ctx ~src ~dst
method draw ctx ~src ~dst = self#composite#draw ctx ~src ~dst
method draw_legend ctx ~x ~y = self#composite#draw_legend ctx ~x ~y
method legend_dimensions ctx = self#composite#legend_dimensions ctx
method avg_slope = self#composite#avg_slope
end
let line_errbar_dataset dashes ?line_width ?color ?name lines =
new line_errbar_dataset dashes ?line_width ?color ?name lines
let line_errbar_datasets ?(color=false) ?line_width name_by_lines_list =
let next_dash = Factories.default_dash_factory () in
let next_style = line_errbar_factory next_dash () in
let next_color = (if color
then Factories.default_color_factory ()
else (fun () -> Drawing.black))
in
List.map (fun (name, lines) ->
line_errbar_dataset (next_style ()) ?line_width
~color:(next_color()) ?name lines)
name_by_lines_list
let default_radius =
Length.Pt ((Length.as_pt Scatter_dataset.default_radius) /. 2.)
let scatter_errbar_lines_dataset
?(xloc=Label_dataset.Label_after)
?(yloc=Label_dataset.Label_above)
glyph dash ?color ?(point_radius=default_radius) ?line_width ?name sets =
let pts, lbls, x_errs, y_errs =
Array.fold_left (fun (pts, lbls, x_errs, y_errs) (vls, name) ->
let xs = Array.map (fun p -> p.x) vls
and ys = Array.map (fun p -> p.y) vls in
let mu_x, int_x = Statistics.mean_and_interval xs
and mu_y, int_y = Statistics.mean_and_interval ys in
let pt = point mu_x mu_y in
Printf.eprintf "%f x %f\n" mu_x mu_y;
let lbls' = match name with
| Some txt -> (pt, txt) :: lbls
| None -> lbls
in
(pt :: pts,
lbls',
triple mu_x mu_y int_x :: x_errs,
triple mu_x mu_y int_y :: y_errs))
([], [], [], []) sets in
let scatter =
Scatter_dataset.scatter_dataset glyph ?color ~point_radius (Array.of_list pts) in
let labels =
new Label_dataset.label_dataset
~yoff:(Length.Pt ~-.(Length.as_pt point_radius)) ~xoff:point_radius
~xloc ~yloc (Array.of_list lbls)
and horiz_err =
new Errbar_dataset.horizontal_errbar_dataset ?color (Array.of_list x_errs)
and vert_err =
new Errbar_dataset.vertical_errbar_dataset ?color (Array.of_list y_errs)
and line =
Line_dataset.line_dataset dash ?color ?name ?line_width (Array.of_list pts)
in
new composite_dataset ?name [scatter; line; horiz_err; vert_err; labels;]
let scatter_errbar_lines_datasets ?(color=false) name_by_sets_list =
let next_glyph = Factories.default_glyph_factory ()
and next_dash = Factories.default_dash_factory () in
let next_color = (if color
then Factories.default_color_factory ()
else (fun () -> Drawing.black))
in
List.map (fun (name,sets) ->
scatter_errbar_lines_dataset (next_glyph())
(next_dash()) ~color:(next_color()) ~name sets)
name_by_sets_list
EOF
| null | https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/spt/src/num_by_num/line_errbar_dataset.ml | ocaml | The dash pattern for the line.
The number of the current line_errbar_dataset.
A reference that counts the total number of associated
line_errbar_datasets.
* [line_errbar_factory next_dashes ()] gets a line and errorbar
factory. This helps choosing where the error bars reside.
* [line_domain l] gets the domain of the line.
* [common_domain lines] get the domain that the given lines have
in common.
* [check_lines lines] throws out a nasty warning if the lines are
not sorted on the x-value.
* [mean_line ?xs domain lines] get a line that is the mean of all
of the given lines. [xs] is an array of x-values to ensure are
on the line. Each value in [xs] must already be in [domain].
check_lines lines;
* [errbars ~xrange ~num ~count ~domain lines] get the error
bars.
[||]
* [filter_lines lines] filters out bad lines. For example, lines
with only a single point.
* [line_errbar_dataset style ?color ?line_width ?name lines] makes
a line and error bar dataset.
* [build_components ()] builds the line and errbar datasets.
* Caches the composite dataset based on the style.
* [consider_update] considers updating the line and errbar
datasets if the number of lines in this style has changed
since they were previously computed.
* [composite] either builds the composite or returns it from the
fields. | * Lines with error bars .
@author eaburns
@since 2010 - 04 - 30
@author eaburns
@since 2010-04-30
*)
open Verbosity
open Num_by_num_dataset
open Geometry
type line_errbar_style = {
dashes : Length.t array;
number : int;
count : int ref;
}
let line_errbar_factory next_dashes () =
let count = ref 0 in
(fun () ->
incr count;
{
dashes = next_dashes ();
number = !count - 1;
count = count;
})
let line_domain l =
Array.fold_left (fun r pt ->
let min = if pt.x < r.min then pt.x else r.min
and max = if pt.x > r.max then pt.x else r.max
in range min max)
(range infinity neg_infinity) l
let common_domain lines =
let domains = Array.map line_domain lines in
Array.fold_left (fun cur d ->
let min = if d.min < cur.min then cur.min else d.min
and max = if d.max > cur.max then cur.max else d.max
in range min max)
(range neg_infinity infinity) domains
let check_lines lines =
Array.iter
(fun line ->
ignore (Array.fold_left
(fun min pt ->
if pt.x <= min
then
vprintf verb_normal
"Lines are not sorted on x-value %f <= %f \n" pt.x min;
pt.x)
neg_infinity line))
lines
let mean_line ?(xs=[||]) domain lines =
let module Float_set = Set.Make(struct
type t = float
let compare (a:float) b = compare a b
end) in
let min = domain.min and max = domain.max in
let init_xset =
Array.fold_left (fun s x -> assert (x >= min); assert (x <= max);
Float_set.add x s)
Float_set.empty xs in
let xs =
Array.fold_left (fun set l ->
Array.fold_left (fun set pt ->
let x = pt.x in
if x >= min && x <= max
then Float_set.add x set
else set)
set l)
init_xset lines
in
Array.of_list (Float_set.fold
(fun x lst ->
let ys = Array.map (fun l -> interpolate l x) lines in
let mean = Statistics.mean ys in
(point x mean) :: lst)
xs [])
let errbars ~xrange ~num ~count ~domain lines =
let min = domain.min and max = domain.max in
let x = ref min in
let ngroups = 4. in
let numf = float num and countf = float count in
let group_width = (max -. min) /. ngroups in
let delta = group_width /. countf in
let group_start = delta /. 2. in
let group_offs = (group_start +. (delta *. numf)) /. group_width in
let group = ref (floor (min /. group_width)) in
let intervals = ref [] in
while !x < max do
let x' = (!group *. group_width) +. (group_width *. group_offs) in
if x' >= min && x' <= max
then begin
let ys = Array.map (fun l -> interpolate l x') lines in
let mean, ci = Statistics.mean_and_interval ys in
intervals := (triple x' mean ci) :: !intervals;
end;
x := x';
group := !group +. 1.;
done;
Array.of_list !intervals
* [ mean_line_and_errbars ~num ~count lines ] gets the mean line and
the error bars .
the error bars. *)
let mean_line_and_errbars ~num ~count lines =
let domain = common_domain lines in
let errbars = errbars ~xrange:domain ~num ~count ~domain lines in
let mean = mean_line domain lines in
type style_cache_entry =
{
n : int;
t : int;
comp : composite_dataset option;
}
* [ cache_key ~n ~t ] builds a key for the cache .
let cache_key ~n ~t = { n = n; t = t; comp = None }
module Style_cache = Weak.Make(struct
type t = style_cache_entry
let equal a b = a.n = b.n && a.t = b.t
let hash a = Hashtbl.hash (a.n, a.t)
end)
let filter_lines lines =
let n = Array.length lines in
let nrem =
Array.fold_left
(fun s l -> if (Array.length l) < 2 then s + 1 else s)
0 lines
in
let i = ref 0 in
if nrem > 0 then
vprintf verb_normal
"Ignoring %d lines with fewer than two points, %d lines remaining\n"
nrem (n - nrem);
Array.init (n - nrem)
(fun _ ->
while (Array.length lines.(!i)) < 2 do incr i done;
assert (!i < n);
incr i;
assert (!i > 0);
lines.(!i - 1))
class line_errbar_dataset style ?color ?line_width ?name lines =
let lines = filter_lines lines in
let init_name = name in
let build_components () =
let count = !(style.count) in
let points, bars = mean_line_and_errbars style.number count lines in
(new Line_dataset.line_dataset style.dashes
?color ?line_width ?name points,
new Errbar_dataset.vertical_errbar_dataset ?color bars)
in
let line_dataset, errbar_dataset = build_components () in
object (self)
inherit dataset ?name ()
val style_cache = Style_cache.create 10
val mutable computed_count = !(style.count)
val mutable composite =
new composite_dataset ?name:init_name [ line_dataset ; errbar_dataset ]
val mutable line_dataset = line_dataset
val mutable errbar_dataset = errbar_dataset
method private consider_update =
let cur_count = !(style.count) in
if cur_count <> computed_count then begin
let l, e = build_components () in
computed_count <- cur_count;
line_dataset <- l;
errbar_dataset <- e;
composite <-
new composite_dataset ?name [ line_dataset; errbar_dataset ];
end
method private composite =
self#consider_update;
composite
method dimensions = self#composite#dimensions
method mean_y_value src =
self#consider_update;
line_dataset#mean_y_value src
method residual ctx ~src ~dst = self#composite#residual ctx ~src ~dst
method draw ctx ~src ~dst = self#composite#draw ctx ~src ~dst
method draw_legend ctx ~x ~y = self#composite#draw_legend ctx ~x ~y
method legend_dimensions ctx = self#composite#legend_dimensions ctx
method avg_slope = self#composite#avg_slope
end
let line_errbar_dataset dashes ?line_width ?color ?name lines =
new line_errbar_dataset dashes ?line_width ?color ?name lines
let line_errbar_datasets ?(color=false) ?line_width name_by_lines_list =
let next_dash = Factories.default_dash_factory () in
let next_style = line_errbar_factory next_dash () in
let next_color = (if color
then Factories.default_color_factory ()
else (fun () -> Drawing.black))
in
List.map (fun (name, lines) ->
line_errbar_dataset (next_style ()) ?line_width
~color:(next_color()) ?name lines)
name_by_lines_list
let default_radius =
Length.Pt ((Length.as_pt Scatter_dataset.default_radius) /. 2.)
let scatter_errbar_lines_dataset
?(xloc=Label_dataset.Label_after)
?(yloc=Label_dataset.Label_above)
glyph dash ?color ?(point_radius=default_radius) ?line_width ?name sets =
let pts, lbls, x_errs, y_errs =
Array.fold_left (fun (pts, lbls, x_errs, y_errs) (vls, name) ->
let xs = Array.map (fun p -> p.x) vls
and ys = Array.map (fun p -> p.y) vls in
let mu_x, int_x = Statistics.mean_and_interval xs
and mu_y, int_y = Statistics.mean_and_interval ys in
let pt = point mu_x mu_y in
Printf.eprintf "%f x %f\n" mu_x mu_y;
let lbls' = match name with
| Some txt -> (pt, txt) :: lbls
| None -> lbls
in
(pt :: pts,
lbls',
triple mu_x mu_y int_x :: x_errs,
triple mu_x mu_y int_y :: y_errs))
([], [], [], []) sets in
let scatter =
Scatter_dataset.scatter_dataset glyph ?color ~point_radius (Array.of_list pts) in
let labels =
new Label_dataset.label_dataset
~yoff:(Length.Pt ~-.(Length.as_pt point_radius)) ~xoff:point_radius
~xloc ~yloc (Array.of_list lbls)
and horiz_err =
new Errbar_dataset.horizontal_errbar_dataset ?color (Array.of_list x_errs)
and vert_err =
new Errbar_dataset.vertical_errbar_dataset ?color (Array.of_list y_errs)
and line =
Line_dataset.line_dataset dash ?color ?name ?line_width (Array.of_list pts)
in
new composite_dataset ?name [scatter; line; horiz_err; vert_err; labels;]
let scatter_errbar_lines_datasets ?(color=false) name_by_sets_list =
let next_glyph = Factories.default_glyph_factory ()
and next_dash = Factories.default_dash_factory () in
let next_color = (if color
then Factories.default_color_factory ()
else (fun () -> Drawing.black))
in
List.map (fun (name,sets) ->
scatter_errbar_lines_dataset (next_glyph())
(next_dash()) ~color:(next_color()) ~name sets)
name_by_sets_list
EOF
|
1324757b879a343f4e1a0c3974210e10c00c55dfb7db4c3a13c7064c4817d255 | mvoidex/hsdev | Types.hs | # LANGUAGE CPP , TemplateHaskell , TypeSynonymInstances , FlexibleInstances , OverloadedStrings , GeneralizedNewtypeDeriving , MultiParamTypeClasses , TypeFamilies , UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
module HsDev.Symbols.Types (
Import(..), importPosition, importName, importQualified, importAs,
Module(..), moduleSymbols, exportedSymbols, scopeSymbols, fixitiesMap, moduleFixities, moduleId, moduleDocs, moduleImports, moduleExports, moduleScope, moduleSource,
Symbol(..), symbolId, symbolDocs, symbolPosition, symbolInfo,
SymbolInfo(..), functionType, parentClass, parentType, selectorConstructors, typeArgs, typeContext, familyAssociate, symbolInfoType, symbolType, patternType, patternConstructor,
Scoped(..), scopeQualifier, scoped,
SymbolUsage(..), symbolUsed, symbolUsedQualifier, symbolUsedIn, symbolUsedRegion,
ImportedSymbol(..), importedSymbol, importedFrom,
infoOf, nullifyInfo,
Inspection(..), inspectionAt, inspectionOpts, fresh, Inspected(..), inspection, inspectedKey, inspectionTags, inspectionResult, inspected,
InspectM(..), runInspect, continueInspect, inspect, inspect_, withInspection,
inspectedTup, noTags, tag, ModuleTag(..), InspectedModule, notInspected,
module HsDev.PackageDb.Types,
module HsDev.Project,
module HsDev.Symbols.Name,
module HsDev.Symbols.Class,
module HsDev.Symbols.Location,
module HsDev.Symbols.Documented
) where
import Control.Arrow
import Control.Applicative
import Control.Lens hiding ((.=))
import Control.Monad
import Control.Monad.Morph
import Control.Monad.Catch
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
import Control.DeepSeq (NFData(..))
import Data.Aeson
import Data.Aeson.Types (Pair, Parser)
import Data.List (intercalate)
import Data.Maybe (catMaybes)
import Data.Maybe.JustIf
import Data.Monoid (Any(..))
import Data.Monoid hiding ((<>))
import Data.Function
import Data.Ord
import Data.Semigroup
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified Data.Text as T
import Data.Set (Set)
import qualified Data.Set as S
import Data.Time.Clock.POSIX (POSIXTime)
import Language.Haskell.Exts (QName(..), ModuleName(..), Boxed(..), SpecialCon(..), Fixity(..), Assoc(..))
import qualified Language.Haskell.Exts as Exts (Name(..))
import Text.Format
import Control.Apply.Util (chain)
import HsDev.Display
import HsDev.Error
import HsDev.PackageDb.Types
import HsDev.Project
import HsDev.Symbols.Name
import HsDev.Symbols.Class
import HsDev.Symbols.Location
import HsDev.Symbols.Documented
import HsDev.Symbols.Parsed
import HsDev.Util ((.::), (.::?), (.::?!), noNulls, objectUnion)
import System.Directory.Paths
instance NFData l => NFData (ModuleName l) where
rnf (ModuleName l n) = rnf l `seq` rnf n
instance NFData l => NFData (Exts.Name l) where
rnf (Exts.Ident l s) = rnf l `seq` rnf s
rnf (Exts.Symbol l s) = rnf l `seq` rnf s
instance NFData Boxed where
rnf Boxed = ()
rnf Unboxed = ()
instance NFData l => NFData (SpecialCon l) where
rnf (UnitCon l) = rnf l
rnf (ListCon l) = rnf l
rnf (FunCon l) = rnf l
rnf (TupleCon l b i) = rnf l `seq` rnf b `seq` rnf i
rnf (Cons l) = rnf l
rnf (UnboxedSingleCon l) = rnf l
#if MIN_VERSION_haskell_src_exts(1,20,0)
rnf (ExprHole l) = rnf l
#endif
instance NFData l => NFData (QName l) where
rnf (Qual l m n) = rnf l `seq` rnf m `seq` rnf n
rnf (UnQual l n) = rnf l `seq` rnf n
rnf (Special l s) = rnf l `seq` rnf s
-- | Import
data Import = Import {
_importPosition :: Position, -- source line of import
_importName :: Text, -- imported module name
_importQualified :: Bool, -- is import qualified
_importAs :: Maybe Text } -- alias of import
deriving (Eq, Ord)
instance NFData Import where
rnf (Import p n q a) = rnf p `seq` rnf n `seq` rnf q `seq` rnf a
instance Show Import where
show (Import _ n q a) = concat $ catMaybes [
Just "import",
"qualified" `justIf` q,
Just $ show n,
fmap (("as " ++) . show) a]
instance ToJSON Import where
toJSON (Import p n q a) = object [
"pos" .= p,
"name" .= n,
"qualified" .= q,
"as" .= a]
instance FromJSON Import where
parseJSON = withObject "import" $ \v -> Import <$>
v .:: "pos" <*>
v .:: "name" <*>
v .:: "qualified" <*>
v .:: "as"
-- | Module
data Module = Module {
_moduleId :: ModuleId,
_moduleDocs :: Maybe Text,
_moduleImports :: [Import], -- list of module names imported
_moduleExports :: [Symbol], -- exported module symbols
_moduleFixities :: [Fixity], -- fixities of operators
_moduleScope :: Map Name [Symbol], -- symbols in scope, only for source modules
_moduleSource :: Maybe Parsed } -- source of module
-- | Make each symbol appear only once
moduleSymbols :: Traversal' Module Symbol
moduleSymbols f m = getBack <$> (each . _1) f revList where
revList = M.toList $ M.unionsWith mappend $ concat [
[M.singleton sym ([], Any True) | sym <- _moduleExports m],
[M.singleton sym ([nm], Any False) | (nm, syms) <- M.toList (_moduleScope m), sym <- syms]]
getBack syms = m {
_moduleExports = [sym' | (sym', (_, Any True)) <- syms],
_moduleScope = M.unionsWith (++) [M.singleton n [sym'] | (sym', (ns, _)) <- syms, n <- ns] }
exportedSymbols :: Traversal' Module Symbol
exportedSymbols f m = (\e -> m { _moduleExports = e }) <$> traverse f (_moduleExports m)
scopeSymbols :: Traversal' Module (Symbol, [Name])
scopeSymbols f m = (\s -> m { _moduleScope = invMap s }) <$> traverse f (M.toList . invMap . M.toList $ _moduleScope m) where
invMap :: Ord b => [(a, [b])] -> Map b [a]
invMap es = M.unionsWith (++) [M.singleton v [k] | (k, vs) <- es, v <- vs]
fixitiesMap :: Lens' Module (Map Name Fixity)
fixitiesMap = lens g' s' where
g' m = mconcat [M.singleton n f | f@(Fixity _ _ n) <- _moduleFixities m]
s' m m' = m { _moduleFixities = M.elems m' }
instance ToJSON (Assoc ()) where
toJSON (AssocNone _) = toJSON ("none" :: String)
toJSON (AssocLeft _) = toJSON ("left" :: String)
toJSON (AssocRight _) = toJSON ("right" :: String)
instance FromJSON (Assoc ()) where
parseJSON = withText "assoc" $ \txt -> msum [
guard (txt == "none") >> return (AssocNone ()),
guard (txt == "left") >> return (AssocLeft ()),
guard (txt == "right") >> return (AssocRight ())]
instance ToJSON Fixity where
toJSON (Fixity assoc pr n) = object $ noNulls [
"assoc" .= assoc,
"prior" .= pr,
"name" .= fromName n]
instance FromJSON Fixity where
parseJSON = withObject "fixity" $ \v -> Fixity <$>
v .:: "assoc" <*>
v .:: "prior" <*>
(toName <$> v .:: "name")
instance ToJSON Module where
toJSON m = object $ noNulls [
"id" .= _moduleId m,
"docs" .= _moduleDocs m,
"imports" .= _moduleImports m,
"exports" .= _moduleExports m,
"fixities" .= _moduleFixities m]
instance FromJSON Module where
parseJSON = withObject "module" $ \v -> Module <$>
v .:: "id" <*>
v .::? "docs" <*>
v .::?! "imports" <*>
v .::?! "exports" <*>
v .::?! "fixities" <*>
pure mempty <*>
pure Nothing
instance NFData (Assoc ()) where
rnf (AssocNone _) = ()
rnf (AssocLeft _) = ()
rnf (AssocRight _) = ()
instance NFData Fixity where
rnf (Fixity assoc pr n) = rnf assoc `seq` rnf pr `seq` rnf n
instance NFData Module where
rnf (Module i d is e fs s msrc) = msrc `seq` rnf i `seq` rnf d `seq` rnf is `seq` rnf e `seq` rnf fs `seq` rnf s
instance Eq Module where
l == r = _moduleId l == _moduleId r
instance Ord Module where
compare l r = compare (_moduleId l) (_moduleId r)
instance Show Module where
show = show . _moduleId
data Symbol = Symbol {
_symbolId :: SymbolId,
_symbolDocs :: Maybe Text,
_symbolPosition :: Maybe Position,
_symbolInfo :: SymbolInfo }
instance Eq Symbol where
l == r = (_symbolId l, symbolType l) == (_symbolId r, symbolType r)
instance Ord Symbol where
compare l r = compare (_symbolId l, symbolType l) (_symbolId r, symbolType r)
instance NFData Symbol where
rnf (Symbol i d l info) = rnf i `seq` rnf d `seq` rnf l `seq` rnf info
instance Show Symbol where
show = show . _symbolId
instance ToJSON Symbol where
toJSON s = object $ noNulls [
"id" .= _symbolId s,
"docs" .= _symbolDocs s,
"pos" .= _symbolPosition s,
"info" .= _symbolInfo s]
instance FromJSON Symbol where
parseJSON = withObject "symbol" $ \v -> Symbol <$>
v .:: "id" <*>
v .::? "docs" <*>
v .::? "pos" <*>
v .:: "info"
data SymbolInfo =
Function { _functionType :: Maybe Text } |
Method { _functionType :: Maybe Text, _parentClass :: Text } |
Selector { _functionType :: Maybe Text, _parentType :: Text, _selectorConstructors :: [Text] } |
Constructor { _typeArgs :: [Text], _parentType :: Text } |
Type { _typeArgs :: [Text], _typeContext :: [Text] } |
NewType { _typeArgs :: [Text], _typeContext :: [Text] } |
Data { _typeArgs :: [Text], _typeContext :: [Text] } |
Class { _typeArgs :: [Text], _typeContext :: [Text] } |
TypeFam { _typeArgs :: [Text], _typeContext :: [Text], _familyAssociate :: Maybe Text } |
DataFam { _typeArgs :: [Text], _typeContext :: [Text], _familyAssociate :: Maybe Text } |
PatConstructor { _typeArgs :: [Text], _patternType :: Maybe Text } |
PatSelector { _functionType :: Maybe Text, _patternType :: Maybe Text, _patternConstructor :: Text }
deriving (Eq, Ord, Read, Show)
instance NFData SymbolInfo where
rnf (Function ft) = rnf ft
rnf (Method ft cls) = rnf ft `seq` rnf cls
rnf (Selector ft t cs) = rnf ft `seq` rnf t `seq` rnf cs
rnf (Constructor as t) = rnf as `seq` rnf t
rnf (Type as ctx) = rnf as `seq` rnf ctx
rnf (NewType as ctx) = rnf as `seq` rnf ctx
rnf (Data as ctx) = rnf as `seq` rnf ctx
rnf (Class as ctx) = rnf as `seq` rnf ctx
rnf (TypeFam as ctx a) = rnf as `seq` rnf ctx `seq` rnf a
rnf (DataFam as ctx a) = rnf as `seq` rnf ctx `seq` rnf a
rnf (PatConstructor as t) = rnf as `seq` rnf t
rnf (PatSelector ft t c) = rnf ft `seq` rnf t `seq` rnf c
instance ToJSON SymbolInfo where
toJSON (Function ft) = object [what "function", "type" .= ft]
toJSON (Method ft cls) = object [what "method", "type" .= ft, "class" .= cls]
toJSON (Selector ft t cs) = object [what "selector", "type" .= ft, "parent" .= t, "constructors" .= cs]
toJSON (Constructor as t) = object [what "ctor", "args" .= as, "type" .= t]
toJSON (Type as ctx) = object [what "type", "args" .= as, "ctx" .= ctx]
toJSON (NewType as ctx) = object [what "newtype", "args" .= as, "ctx" .= ctx]
toJSON (Data as ctx) = object [what "data", "args" .= as, "ctx" .= ctx]
toJSON (Class as ctx) = object [what "class", "args" .= as, "ctx" .= ctx]
toJSON (TypeFam as ctx a) = object [what "type-family", "args" .= as, "ctx" .= ctx, "associate" .= a]
toJSON (DataFam as ctx a) = object [what "data-family", "args" .= as, "ctx" .= ctx, "associate" .= a]
toJSON (PatConstructor as t) = object [what "pat-ctor", "args" .= as, "pat-type" .= t]
toJSON (PatSelector ft t c) = object [what "pat-selector", "type" .= ft, "pat-type" .= t, "constructor" .= c]
class EmptySymbolInfo a where
infoOf :: a -> SymbolInfo
instance EmptySymbolInfo SymbolInfo where
infoOf = id
instance (Monoid a, EmptySymbolInfo r) => EmptySymbolInfo (a -> r) where
infoOf f = infoOf $ f mempty
symbolInfoType :: SymbolInfo -> String
symbolInfoType (Function{}) = "function"
symbolInfoType (Method{}) = "method"
symbolInfoType (Selector{}) = "selector"
symbolInfoType (Constructor{}) = "ctor"
symbolInfoType (Type{}) = "type"
symbolInfoType (NewType{}) = "newtype"
symbolInfoType (Data{}) = "data"
symbolInfoType (Class{}) = "class"
symbolInfoType (TypeFam{}) = "type-family"
symbolInfoType (DataFam{}) = "data-family"
symbolInfoType (PatConstructor{}) = "pat-ctor"
symbolInfoType (PatSelector{}) = "pat-selector"
symbolType :: Symbol -> String
symbolType = symbolInfoType . _symbolInfo
what :: String -> Pair
what n = "what" .= n
instance FromJSON SymbolInfo where
parseJSON = withObject "symbol info" $ \v -> msum [
gwhat "function" v >> (Function <$> v .::? "type"),
gwhat "method" v >> (Method <$> v .::? "type" <*> v .:: "class"),
gwhat "selector" v >> (Selector <$> v .::? "type" <*> v .:: "parent" <*> v .::?! "constructors"),
gwhat "ctor" v >> (Constructor <$> v .::?! "args" <*> v .:: "type"),
gwhat "type" v >> (Type <$> v .::?! "args" <*> v .::?! "ctx"),
gwhat "newtype" v >> (NewType <$> v .::?! "args" <*> v .::?! "ctx"),
gwhat "data" v >> (Data <$> v .::?! "args" <*> v .::?! "ctx"),
gwhat "class" v >> (Class <$> v .::?! "args" <*> v .::?! "ctx"),
gwhat "type-family" v >> (TypeFam <$> v .::?! "args" <*> v .::?! "ctx" <*> v .::? "associate"),
gwhat "data-family" v >> (DataFam <$> v .::?! "args" <*> v .::?! "ctx" <*> v .::? "associate"),
gwhat "pat-ctor" v >> (PatConstructor <$> v .::?! "args" <*> v .::? "pat-type"),
gwhat "pat-selector" v >> (PatSelector <$> v .::? "type" <*> v .::? "pat-type" <*> v .:: "constructor")]
gwhat :: String -> Object -> Parser ()
gwhat n v = do
s <- v .:: "what"
guard (s == n)
-- | Scoped entity with qualifier
data Scoped a = Scoped {
_scopeQualifier :: Maybe Text,
_scoped :: a }
deriving (Eq, Ord)
instance Show a => Show (Scoped a) where
show (Scoped q s) = maybe "" (\q' -> T.unpack q' ++ ".") q ++ show s
instance ToJSON a => ToJSON (Scoped a) where
toJSON (Scoped q s) = toJSON s `objectUnion` object (noNulls ["qualifier" .= q])
instance FromJSON a => FromJSON (Scoped a) where
parseJSON = withObject "scope-symbol" $ \v -> Scoped <$>
(v .::? "qualifier") <*>
parseJSON (Object v)
-- | Symbol usage
data SymbolUsage = SymbolUsage {
_symbolUsed :: Symbol,
_symbolUsedQualifier :: Maybe Text,
_symbolUsedIn :: ModuleId,
_symbolUsedRegion :: Region }
deriving (Eq, Ord)
instance Show SymbolUsage where
show (SymbolUsage s _ m p) = show s ++ " at " ++ show m ++ ":" ++ show p
instance ToJSON SymbolUsage where
toJSON (SymbolUsage s q m p) = object $ noNulls ["symbol" .= s, "qualifier" .= q, "in" .= m, "at" .= p]
instance FromJSON SymbolUsage where
parseJSON = withObject "symbol-usage" $ \v -> SymbolUsage <$>
v .:: "symbol" <*>
v .::? "qualifier" <*>
v .:: "in" <*>
v .:: "at"
-- | Symbol with module it's exported from
data ImportedSymbol = ImportedSymbol {
_importedSymbol :: Symbol,
_importedFrom :: ModuleId }
deriving (Eq, Ord)
instance Show ImportedSymbol where
show (ImportedSymbol s m) = show s ++ " imported from " ++ show m
instance ToJSON ImportedSymbol where
toJSON (ImportedSymbol s m) = objectUnion (toJSON s) $ object [
"imported" .= m]
instance FromJSON ImportedSymbol where
parseJSON = withObject "imported-symbol" $ \v -> ImportedSymbol <$>
parseJSON (Object v) <*>
v .:: "imported"
-- | Inspection data
data Inspection =
-- | No inspection
InspectionNone |
-- | Time and flags of inspection
InspectionAt {
_inspectionAt :: POSIXTime,
_inspectionOpts :: [Text] }
deriving (Eq, Ord)
instance NFData Inspection where
rnf InspectionNone = ()
rnf (InspectionAt t fs) = rnf t `seq` rnf fs
instance Show Inspection where
show InspectionNone = "none"
show (InspectionAt tm fs) = "mtime " ++ show tm ++ ", flags [" ++ intercalate ", " (map T.unpack fs) ++ "]"
instance Semigroup Inspection where
InspectionNone <> r = r
l <> InspectionNone = l
InspectionAt ltm lopts <> InspectionAt rtm ropts
| ltm >= rtm = InspectionAt ltm lopts
| otherwise = InspectionAt rtm ropts
instance Monoid Inspection where
mempty = InspectionNone
mappend l r = l <> r
instance ToJSON Inspection where
toJSON InspectionNone = object ["inspected" .= False]
toJSON (InspectionAt tm fs) = object [
"mtime" .= (fromRational (toRational tm) :: Double),
"flags" .= fs]
instance FromJSON Inspection where
parseJSON = withObject "inspection" $ \v ->
((const InspectionNone :: Bool -> Inspection) <$> v .:: "inspected") <|>
(InspectionAt <$> ((fromRational . (toRational :: Double -> Rational)) <$> v .:: "mtime") <*> (v .:: "flags"))
| Is left @Inspection@ fresh comparing to right one
fresh :: Inspection -> Inspection -> Bool
fresh InspectionNone InspectionNone = True
fresh InspectionNone _ = False
fresh _ InspectionNone = True
fresh (InspectionAt tm _) (InspectionAt tm' _) = tm' - tm < 0.01
-- | Inspected entity
data Inspected k t a = Inspected {
_inspection :: Inspection,
_inspectedKey :: k,
_inspectionTags :: Set t,
_inspectionResult :: Either HsDevError a }
inspectedTup :: Inspected k t a -> (Inspection, k, Set t, Maybe a)
inspectedTup (Inspected insp i tags res) = (insp, i, tags, either (const Nothing) Just res)
instance (Eq k, Eq t, Eq a) => Eq (Inspected k t a) where
(==) = (==) `on` inspectedTup
instance (Ord k, Ord t, Ord a) => Ord (Inspected k t a) where
compare = comparing inspectedTup
instance Functor (Inspected k t) where
fmap f insp = insp {
_inspectionResult = fmap f (_inspectionResult insp) }
instance Foldable (Inspected k t) where
foldMap f = either mempty f . _inspectionResult
instance Traversable (Inspected k t) where
traverse f (Inspected insp i ts r) = Inspected insp i ts <$> either (pure . Left) (liftA Right . f) r
instance (NFData k, NFData t, NFData a) => NFData (Inspected k t a) where
rnf (Inspected t i ts r) = rnf t `seq` rnf i `seq` rnf ts `seq` rnf r
instance (ToJSON k, ToJSON t, ToJSON a) => ToJSON (Inspected k t a) where
toJSON im = object [
"inspection" .= _inspection im,
"location" .= _inspectedKey im,
"tags" .= S.toList (_inspectionTags im),
either ("error" .=) ("result" .=) (_inspectionResult im)]
instance (FromJSON k, Ord t, FromJSON t, FromJSON a) => FromJSON (Inspected k t a) where
parseJSON = withObject "inspected" $ \v -> Inspected <$>
v .:: "inspection" <*>
v .:: "location" <*>
(S.fromList <$> (v .::?! "tags")) <*>
((Left <$> v .:: "error") <|> (Right <$> v .:: "result"))
newtype InspectM k t m a = InspectM { runInspectM :: ReaderT k (ExceptT HsDevError (StateT (Inspection, S.Set t) m)) a }
deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadIO, MonadThrow, MonadCatch, MonadReader k, MonadError HsDevError, MonadState (Inspection, S.Set t))
instance MonadTrans (InspectM k t) where
lift = InspectM . lift . lift . lift
runInspect :: (Monad m, Ord t) => k -> InspectM k t m a -> m (Inspected k t a)
runInspect key act = do
(res, (insp, ts)) <- flip runStateT (InspectionNone, mempty) . runExceptT . flip runReaderT key . runInspectM $ act
return $ Inspected insp key ts res
-- | Continue inspection
continueInspect :: (Monad m, Ord t) => Inspected k t a -> (a -> InspectM k t m b) -> m (Inspected k t b)
continueInspect start act = runInspect (_inspectedKey start) $ do
put (_inspection start, _inspectionTags start)
val <- either throwError return $ _inspectionResult start
act val
inspect :: MonadCatch m => m Inspection -> (k -> m a) -> InspectM k t m a
inspect insp act = withInspection insp $ do
key <- ask
lift (hsdevCatch (hsdevLiftIO $ act key)) >>= either throwError return
withInspection :: MonadCatch m => m Inspection -> InspectM k t m a -> InspectM k t m a
withInspection insp inner = do
insp' <- lift insp
let
setInsp = modify (set _1 insp')
catchError (inner <* setInsp) (\e -> setInsp >> throwError e)
inspect_ :: MonadCatch m => m Inspection -> m a -> InspectM k t m a
inspect_ insp = inspect insp . const
-- | Empty tags
noTags :: Set t
noTags = S.empty
-- | One tag
tag :: t -> Set t
tag = S.singleton
data ModuleTag = InferredTypesTag | RefinedDocsTag | OnlyHeaderTag | DirtyTag | ResolvedNamesTag deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance NFData ModuleTag where
rnf InferredTypesTag = ()
rnf RefinedDocsTag = ()
rnf OnlyHeaderTag = ()
rnf DirtyTag = ()
rnf ResolvedNamesTag = ()
instance Display ModuleTag where
display InferredTypesTag = "types"
display RefinedDocsTag = "docs"
display OnlyHeaderTag = "header"
display DirtyTag = "dirty"
display ResolvedNamesTag = "resolved"
displayType _ = "module-tag"
instance ToJSON ModuleTag where
toJSON InferredTypesTag = toJSON ("types" :: String)
toJSON RefinedDocsTag = toJSON ("docs" :: String)
toJSON OnlyHeaderTag = toJSON ("header" :: String)
toJSON DirtyTag = toJSON ("dirty" :: String)
toJSON ResolvedNamesTag = toJSON ("resolved" :: String)
instance FromJSON ModuleTag where
parseJSON = withText "module-tag" $ \txt -> msum [
guard (txt == "types") >> return InferredTypesTag,
guard (txt == "docs") >> return RefinedDocsTag,
guard (txt == "header") >> return OnlyHeaderTag,
guard (txt == "dirty") >> return DirtyTag,
guard (txt == "resolved") >> return ResolvedNamesTag]
-- | Inspected module
type InspectedModule = Inspected ModuleLocation ModuleTag Module
instance Show InspectedModule where
show (Inspected i mi ts m) = unlines [either showError show m, "\tinspected: " ++ show i, "\ttags: " ++ intercalate ", " (map show $ S.toList ts)] where
showError :: HsDevError -> String
showError e = unlines $ ("\terror: " ++ show e) : case mi of
FileModule f p -> ["file: " ++ f ^. path, "project: " ++ maybe "" (view (projectPath . path)) p]
InstalledModule c p n _ -> ["cabal: " ++ show c, "package: " ++ show p, "name: " ++ T.unpack n]
OtherLocation src -> ["other location: " ++ T.unpack src]
NoLocation -> ["no location"]
notInspected :: ModuleLocation -> InspectedModule
notInspected mloc = Inspected mempty mloc noTags (Left $ NotInspected mloc)
instance Documented ModuleId where
brief m = brief $ _moduleLocation m
detailed = brief
instance Documented SymbolId where
brief s = "{} from {}" ~~ _symbolName s ~~ brief (_symbolModule s)
detailed = brief
instance Documented Module where
brief = brief . _moduleId
detailed m = T.unlines (brief m : info) where
info = [
"\texports: {}" ~~ T.intercalate ", " (map brief (_moduleExports m))]
instance Documented Symbol where
brief = brief . _symbolId
detailed s = T.unlines [brief s, info] where
info = case _symbolInfo s of
Function t -> "\t" `T.append` T.intercalate ", " (catMaybes [Just "function", fmap ("type: {}" ~~) t])
Method t p -> "\t" `T.append` T.intercalate ", " (catMaybes [Just "method", fmap ("type: {}" ~~) t, Just $ "parent: {}" ~~ p])
Selector t p _ -> "\t" `T.append` T.intercalate ", " (catMaybes [Just "selector", fmap ("type: {}" ~~) t, Just $ "parent: {}" ~~ p])
Constructor args p -> "\t" `T.append` T.intercalate ", " ["constructor", "args: {}" ~~ T.unwords args, "parent: {}" ~~ p]
Type args ctx -> "\t" `T.append` T.intercalate ", " ["type", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
NewType args ctx -> "\t" `T.append` T.intercalate ", " ["newtype", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
Data args ctx -> "\t" `T.append` T.intercalate ", " ["data", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
Class args ctx -> "\t" `T.append` T.intercalate ", " ["class", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
TypeFam args ctx _ -> "\t" `T.append` T.intercalate ", " ["type family", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
DataFam args ctx _ -> "\t" `T.append` T.intercalate ", " ["data family", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
PatConstructor args p -> "\t" `T.append` T.intercalate ", " (catMaybes [Just "pattern constructor", Just $ "args: {}" ~~ T.unwords args, fmap ("pat-type: {}" ~~) p])
PatSelector t p _ -> "\t" `T.append` T.intercalate ", " (catMaybes [Just "pattern selector", fmap ("type: {}" ~~) t, fmap ("pat-type: {}" ~~) p])
makeLenses ''Import
makeLenses ''Module
makeLenses ''Symbol
makeLenses ''SymbolInfo
makeLenses ''Scoped
makeLenses ''SymbolUsage
makeLenses ''ImportedSymbol
makeLenses ''Inspection
makeLenses ''Inspected
inspected :: Traversal (Inspected k t a) (Inspected k t b) a b
inspected = inspectionResult . _Right
nullifyInfo :: SymbolInfo -> SymbolInfo
nullifyInfo = chain [
set functionType mempty,
set parentClass mempty,
set parentType mempty,
set selectorConstructors mempty,
set typeArgs mempty,
set typeContext mempty,
set familyAssociate mempty,
set patternType mempty,
set patternConstructor mempty]
instance Sourced Module where
sourcedName = moduleId . moduleName
sourcedDocs = moduleDocs . _Just
sourcedModule = moduleId
instance Sourced Symbol where
sourcedName = symbolId . symbolName
sourcedDocs = symbolDocs . _Just
sourcedModule = symbolId . symbolModule
sourcedLocation = symbolPosition . _Just
| null | https://raw.githubusercontent.com/mvoidex/hsdev/016646080a6859e4d9b4a1935fc1d732e388db1a/src/HsDev/Symbols/Types.hs | haskell | | Import
source line of import
imported module name
is import qualified
alias of import
| Module
list of module names imported
exported module symbols
fixities of operators
symbols in scope, only for source modules
source of module
| Make each symbol appear only once
| Scoped entity with qualifier
| Symbol usage
| Symbol with module it's exported from
| Inspection data
| No inspection
| Time and flags of inspection
| Inspected entity
| Continue inspection
| Empty tags
| One tag
| Inspected module | # LANGUAGE CPP , TemplateHaskell , TypeSynonymInstances , FlexibleInstances , OverloadedStrings , GeneralizedNewtypeDeriving , MultiParamTypeClasses , TypeFamilies , UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
module HsDev.Symbols.Types (
Import(..), importPosition, importName, importQualified, importAs,
Module(..), moduleSymbols, exportedSymbols, scopeSymbols, fixitiesMap, moduleFixities, moduleId, moduleDocs, moduleImports, moduleExports, moduleScope, moduleSource,
Symbol(..), symbolId, symbolDocs, symbolPosition, symbolInfo,
SymbolInfo(..), functionType, parentClass, parentType, selectorConstructors, typeArgs, typeContext, familyAssociate, symbolInfoType, symbolType, patternType, patternConstructor,
Scoped(..), scopeQualifier, scoped,
SymbolUsage(..), symbolUsed, symbolUsedQualifier, symbolUsedIn, symbolUsedRegion,
ImportedSymbol(..), importedSymbol, importedFrom,
infoOf, nullifyInfo,
Inspection(..), inspectionAt, inspectionOpts, fresh, Inspected(..), inspection, inspectedKey, inspectionTags, inspectionResult, inspected,
InspectM(..), runInspect, continueInspect, inspect, inspect_, withInspection,
inspectedTup, noTags, tag, ModuleTag(..), InspectedModule, notInspected,
module HsDev.PackageDb.Types,
module HsDev.Project,
module HsDev.Symbols.Name,
module HsDev.Symbols.Class,
module HsDev.Symbols.Location,
module HsDev.Symbols.Documented
) where
import Control.Arrow
import Control.Applicative
import Control.Lens hiding ((.=))
import Control.Monad
import Control.Monad.Morph
import Control.Monad.Catch
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
import Control.DeepSeq (NFData(..))
import Data.Aeson
import Data.Aeson.Types (Pair, Parser)
import Data.List (intercalate)
import Data.Maybe (catMaybes)
import Data.Maybe.JustIf
import Data.Monoid (Any(..))
import Data.Monoid hiding ((<>))
import Data.Function
import Data.Ord
import Data.Semigroup
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified Data.Text as T
import Data.Set (Set)
import qualified Data.Set as S
import Data.Time.Clock.POSIX (POSIXTime)
import Language.Haskell.Exts (QName(..), ModuleName(..), Boxed(..), SpecialCon(..), Fixity(..), Assoc(..))
import qualified Language.Haskell.Exts as Exts (Name(..))
import Text.Format
import Control.Apply.Util (chain)
import HsDev.Display
import HsDev.Error
import HsDev.PackageDb.Types
import HsDev.Project
import HsDev.Symbols.Name
import HsDev.Symbols.Class
import HsDev.Symbols.Location
import HsDev.Symbols.Documented
import HsDev.Symbols.Parsed
import HsDev.Util ((.::), (.::?), (.::?!), noNulls, objectUnion)
import System.Directory.Paths
instance NFData l => NFData (ModuleName l) where
rnf (ModuleName l n) = rnf l `seq` rnf n
instance NFData l => NFData (Exts.Name l) where
rnf (Exts.Ident l s) = rnf l `seq` rnf s
rnf (Exts.Symbol l s) = rnf l `seq` rnf s
instance NFData Boxed where
rnf Boxed = ()
rnf Unboxed = ()
instance NFData l => NFData (SpecialCon l) where
rnf (UnitCon l) = rnf l
rnf (ListCon l) = rnf l
rnf (FunCon l) = rnf l
rnf (TupleCon l b i) = rnf l `seq` rnf b `seq` rnf i
rnf (Cons l) = rnf l
rnf (UnboxedSingleCon l) = rnf l
#if MIN_VERSION_haskell_src_exts(1,20,0)
rnf (ExprHole l) = rnf l
#endif
instance NFData l => NFData (QName l) where
rnf (Qual l m n) = rnf l `seq` rnf m `seq` rnf n
rnf (UnQual l n) = rnf l `seq` rnf n
rnf (Special l s) = rnf l `seq` rnf s
data Import = Import {
deriving (Eq, Ord)
instance NFData Import where
rnf (Import p n q a) = rnf p `seq` rnf n `seq` rnf q `seq` rnf a
instance Show Import where
show (Import _ n q a) = concat $ catMaybes [
Just "import",
"qualified" `justIf` q,
Just $ show n,
fmap (("as " ++) . show) a]
instance ToJSON Import where
toJSON (Import p n q a) = object [
"pos" .= p,
"name" .= n,
"qualified" .= q,
"as" .= a]
instance FromJSON Import where
parseJSON = withObject "import" $ \v -> Import <$>
v .:: "pos" <*>
v .:: "name" <*>
v .:: "qualified" <*>
v .:: "as"
data Module = Module {
_moduleId :: ModuleId,
_moduleDocs :: Maybe Text,
moduleSymbols :: Traversal' Module Symbol
moduleSymbols f m = getBack <$> (each . _1) f revList where
revList = M.toList $ M.unionsWith mappend $ concat [
[M.singleton sym ([], Any True) | sym <- _moduleExports m],
[M.singleton sym ([nm], Any False) | (nm, syms) <- M.toList (_moduleScope m), sym <- syms]]
getBack syms = m {
_moduleExports = [sym' | (sym', (_, Any True)) <- syms],
_moduleScope = M.unionsWith (++) [M.singleton n [sym'] | (sym', (ns, _)) <- syms, n <- ns] }
exportedSymbols :: Traversal' Module Symbol
exportedSymbols f m = (\e -> m { _moduleExports = e }) <$> traverse f (_moduleExports m)
scopeSymbols :: Traversal' Module (Symbol, [Name])
scopeSymbols f m = (\s -> m { _moduleScope = invMap s }) <$> traverse f (M.toList . invMap . M.toList $ _moduleScope m) where
invMap :: Ord b => [(a, [b])] -> Map b [a]
invMap es = M.unionsWith (++) [M.singleton v [k] | (k, vs) <- es, v <- vs]
fixitiesMap :: Lens' Module (Map Name Fixity)
fixitiesMap = lens g' s' where
g' m = mconcat [M.singleton n f | f@(Fixity _ _ n) <- _moduleFixities m]
s' m m' = m { _moduleFixities = M.elems m' }
instance ToJSON (Assoc ()) where
toJSON (AssocNone _) = toJSON ("none" :: String)
toJSON (AssocLeft _) = toJSON ("left" :: String)
toJSON (AssocRight _) = toJSON ("right" :: String)
instance FromJSON (Assoc ()) where
parseJSON = withText "assoc" $ \txt -> msum [
guard (txt == "none") >> return (AssocNone ()),
guard (txt == "left") >> return (AssocLeft ()),
guard (txt == "right") >> return (AssocRight ())]
instance ToJSON Fixity where
toJSON (Fixity assoc pr n) = object $ noNulls [
"assoc" .= assoc,
"prior" .= pr,
"name" .= fromName n]
instance FromJSON Fixity where
parseJSON = withObject "fixity" $ \v -> Fixity <$>
v .:: "assoc" <*>
v .:: "prior" <*>
(toName <$> v .:: "name")
instance ToJSON Module where
toJSON m = object $ noNulls [
"id" .= _moduleId m,
"docs" .= _moduleDocs m,
"imports" .= _moduleImports m,
"exports" .= _moduleExports m,
"fixities" .= _moduleFixities m]
instance FromJSON Module where
parseJSON = withObject "module" $ \v -> Module <$>
v .:: "id" <*>
v .::? "docs" <*>
v .::?! "imports" <*>
v .::?! "exports" <*>
v .::?! "fixities" <*>
pure mempty <*>
pure Nothing
instance NFData (Assoc ()) where
rnf (AssocNone _) = ()
rnf (AssocLeft _) = ()
rnf (AssocRight _) = ()
instance NFData Fixity where
rnf (Fixity assoc pr n) = rnf assoc `seq` rnf pr `seq` rnf n
instance NFData Module where
rnf (Module i d is e fs s msrc) = msrc `seq` rnf i `seq` rnf d `seq` rnf is `seq` rnf e `seq` rnf fs `seq` rnf s
instance Eq Module where
l == r = _moduleId l == _moduleId r
instance Ord Module where
compare l r = compare (_moduleId l) (_moduleId r)
instance Show Module where
show = show . _moduleId
data Symbol = Symbol {
_symbolId :: SymbolId,
_symbolDocs :: Maybe Text,
_symbolPosition :: Maybe Position,
_symbolInfo :: SymbolInfo }
instance Eq Symbol where
l == r = (_symbolId l, symbolType l) == (_symbolId r, symbolType r)
instance Ord Symbol where
compare l r = compare (_symbolId l, symbolType l) (_symbolId r, symbolType r)
instance NFData Symbol where
rnf (Symbol i d l info) = rnf i `seq` rnf d `seq` rnf l `seq` rnf info
instance Show Symbol where
show = show . _symbolId
instance ToJSON Symbol where
toJSON s = object $ noNulls [
"id" .= _symbolId s,
"docs" .= _symbolDocs s,
"pos" .= _symbolPosition s,
"info" .= _symbolInfo s]
instance FromJSON Symbol where
parseJSON = withObject "symbol" $ \v -> Symbol <$>
v .:: "id" <*>
v .::? "docs" <*>
v .::? "pos" <*>
v .:: "info"
data SymbolInfo =
Function { _functionType :: Maybe Text } |
Method { _functionType :: Maybe Text, _parentClass :: Text } |
Selector { _functionType :: Maybe Text, _parentType :: Text, _selectorConstructors :: [Text] } |
Constructor { _typeArgs :: [Text], _parentType :: Text } |
Type { _typeArgs :: [Text], _typeContext :: [Text] } |
NewType { _typeArgs :: [Text], _typeContext :: [Text] } |
Data { _typeArgs :: [Text], _typeContext :: [Text] } |
Class { _typeArgs :: [Text], _typeContext :: [Text] } |
TypeFam { _typeArgs :: [Text], _typeContext :: [Text], _familyAssociate :: Maybe Text } |
DataFam { _typeArgs :: [Text], _typeContext :: [Text], _familyAssociate :: Maybe Text } |
PatConstructor { _typeArgs :: [Text], _patternType :: Maybe Text } |
PatSelector { _functionType :: Maybe Text, _patternType :: Maybe Text, _patternConstructor :: Text }
deriving (Eq, Ord, Read, Show)
instance NFData SymbolInfo where
rnf (Function ft) = rnf ft
rnf (Method ft cls) = rnf ft `seq` rnf cls
rnf (Selector ft t cs) = rnf ft `seq` rnf t `seq` rnf cs
rnf (Constructor as t) = rnf as `seq` rnf t
rnf (Type as ctx) = rnf as `seq` rnf ctx
rnf (NewType as ctx) = rnf as `seq` rnf ctx
rnf (Data as ctx) = rnf as `seq` rnf ctx
rnf (Class as ctx) = rnf as `seq` rnf ctx
rnf (TypeFam as ctx a) = rnf as `seq` rnf ctx `seq` rnf a
rnf (DataFam as ctx a) = rnf as `seq` rnf ctx `seq` rnf a
rnf (PatConstructor as t) = rnf as `seq` rnf t
rnf (PatSelector ft t c) = rnf ft `seq` rnf t `seq` rnf c
instance ToJSON SymbolInfo where
toJSON (Function ft) = object [what "function", "type" .= ft]
toJSON (Method ft cls) = object [what "method", "type" .= ft, "class" .= cls]
toJSON (Selector ft t cs) = object [what "selector", "type" .= ft, "parent" .= t, "constructors" .= cs]
toJSON (Constructor as t) = object [what "ctor", "args" .= as, "type" .= t]
toJSON (Type as ctx) = object [what "type", "args" .= as, "ctx" .= ctx]
toJSON (NewType as ctx) = object [what "newtype", "args" .= as, "ctx" .= ctx]
toJSON (Data as ctx) = object [what "data", "args" .= as, "ctx" .= ctx]
toJSON (Class as ctx) = object [what "class", "args" .= as, "ctx" .= ctx]
toJSON (TypeFam as ctx a) = object [what "type-family", "args" .= as, "ctx" .= ctx, "associate" .= a]
toJSON (DataFam as ctx a) = object [what "data-family", "args" .= as, "ctx" .= ctx, "associate" .= a]
toJSON (PatConstructor as t) = object [what "pat-ctor", "args" .= as, "pat-type" .= t]
toJSON (PatSelector ft t c) = object [what "pat-selector", "type" .= ft, "pat-type" .= t, "constructor" .= c]
class EmptySymbolInfo a where
infoOf :: a -> SymbolInfo
instance EmptySymbolInfo SymbolInfo where
infoOf = id
instance (Monoid a, EmptySymbolInfo r) => EmptySymbolInfo (a -> r) where
infoOf f = infoOf $ f mempty
symbolInfoType :: SymbolInfo -> String
symbolInfoType (Function{}) = "function"
symbolInfoType (Method{}) = "method"
symbolInfoType (Selector{}) = "selector"
symbolInfoType (Constructor{}) = "ctor"
symbolInfoType (Type{}) = "type"
symbolInfoType (NewType{}) = "newtype"
symbolInfoType (Data{}) = "data"
symbolInfoType (Class{}) = "class"
symbolInfoType (TypeFam{}) = "type-family"
symbolInfoType (DataFam{}) = "data-family"
symbolInfoType (PatConstructor{}) = "pat-ctor"
symbolInfoType (PatSelector{}) = "pat-selector"
symbolType :: Symbol -> String
symbolType = symbolInfoType . _symbolInfo
what :: String -> Pair
what n = "what" .= n
instance FromJSON SymbolInfo where
parseJSON = withObject "symbol info" $ \v -> msum [
gwhat "function" v >> (Function <$> v .::? "type"),
gwhat "method" v >> (Method <$> v .::? "type" <*> v .:: "class"),
gwhat "selector" v >> (Selector <$> v .::? "type" <*> v .:: "parent" <*> v .::?! "constructors"),
gwhat "ctor" v >> (Constructor <$> v .::?! "args" <*> v .:: "type"),
gwhat "type" v >> (Type <$> v .::?! "args" <*> v .::?! "ctx"),
gwhat "newtype" v >> (NewType <$> v .::?! "args" <*> v .::?! "ctx"),
gwhat "data" v >> (Data <$> v .::?! "args" <*> v .::?! "ctx"),
gwhat "class" v >> (Class <$> v .::?! "args" <*> v .::?! "ctx"),
gwhat "type-family" v >> (TypeFam <$> v .::?! "args" <*> v .::?! "ctx" <*> v .::? "associate"),
gwhat "data-family" v >> (DataFam <$> v .::?! "args" <*> v .::?! "ctx" <*> v .::? "associate"),
gwhat "pat-ctor" v >> (PatConstructor <$> v .::?! "args" <*> v .::? "pat-type"),
gwhat "pat-selector" v >> (PatSelector <$> v .::? "type" <*> v .::? "pat-type" <*> v .:: "constructor")]
gwhat :: String -> Object -> Parser ()
gwhat n v = do
s <- v .:: "what"
guard (s == n)
data Scoped a = Scoped {
_scopeQualifier :: Maybe Text,
_scoped :: a }
deriving (Eq, Ord)
instance Show a => Show (Scoped a) where
show (Scoped q s) = maybe "" (\q' -> T.unpack q' ++ ".") q ++ show s
instance ToJSON a => ToJSON (Scoped a) where
toJSON (Scoped q s) = toJSON s `objectUnion` object (noNulls ["qualifier" .= q])
instance FromJSON a => FromJSON (Scoped a) where
parseJSON = withObject "scope-symbol" $ \v -> Scoped <$>
(v .::? "qualifier") <*>
parseJSON (Object v)
data SymbolUsage = SymbolUsage {
_symbolUsed :: Symbol,
_symbolUsedQualifier :: Maybe Text,
_symbolUsedIn :: ModuleId,
_symbolUsedRegion :: Region }
deriving (Eq, Ord)
instance Show SymbolUsage where
show (SymbolUsage s _ m p) = show s ++ " at " ++ show m ++ ":" ++ show p
instance ToJSON SymbolUsage where
toJSON (SymbolUsage s q m p) = object $ noNulls ["symbol" .= s, "qualifier" .= q, "in" .= m, "at" .= p]
instance FromJSON SymbolUsage where
parseJSON = withObject "symbol-usage" $ \v -> SymbolUsage <$>
v .:: "symbol" <*>
v .::? "qualifier" <*>
v .:: "in" <*>
v .:: "at"
data ImportedSymbol = ImportedSymbol {
_importedSymbol :: Symbol,
_importedFrom :: ModuleId }
deriving (Eq, Ord)
instance Show ImportedSymbol where
show (ImportedSymbol s m) = show s ++ " imported from " ++ show m
instance ToJSON ImportedSymbol where
toJSON (ImportedSymbol s m) = objectUnion (toJSON s) $ object [
"imported" .= m]
instance FromJSON ImportedSymbol where
parseJSON = withObject "imported-symbol" $ \v -> ImportedSymbol <$>
parseJSON (Object v) <*>
v .:: "imported"
data Inspection =
InspectionNone |
InspectionAt {
_inspectionAt :: POSIXTime,
_inspectionOpts :: [Text] }
deriving (Eq, Ord)
instance NFData Inspection where
rnf InspectionNone = ()
rnf (InspectionAt t fs) = rnf t `seq` rnf fs
instance Show Inspection where
show InspectionNone = "none"
show (InspectionAt tm fs) = "mtime " ++ show tm ++ ", flags [" ++ intercalate ", " (map T.unpack fs) ++ "]"
instance Semigroup Inspection where
InspectionNone <> r = r
l <> InspectionNone = l
InspectionAt ltm lopts <> InspectionAt rtm ropts
| ltm >= rtm = InspectionAt ltm lopts
| otherwise = InspectionAt rtm ropts
instance Monoid Inspection where
mempty = InspectionNone
mappend l r = l <> r
instance ToJSON Inspection where
toJSON InspectionNone = object ["inspected" .= False]
toJSON (InspectionAt tm fs) = object [
"mtime" .= (fromRational (toRational tm) :: Double),
"flags" .= fs]
instance FromJSON Inspection where
parseJSON = withObject "inspection" $ \v ->
((const InspectionNone :: Bool -> Inspection) <$> v .:: "inspected") <|>
(InspectionAt <$> ((fromRational . (toRational :: Double -> Rational)) <$> v .:: "mtime") <*> (v .:: "flags"))
| Is left @Inspection@ fresh comparing to right one
fresh :: Inspection -> Inspection -> Bool
fresh InspectionNone InspectionNone = True
fresh InspectionNone _ = False
fresh _ InspectionNone = True
fresh (InspectionAt tm _) (InspectionAt tm' _) = tm' - tm < 0.01
data Inspected k t a = Inspected {
_inspection :: Inspection,
_inspectedKey :: k,
_inspectionTags :: Set t,
_inspectionResult :: Either HsDevError a }
inspectedTup :: Inspected k t a -> (Inspection, k, Set t, Maybe a)
inspectedTup (Inspected insp i tags res) = (insp, i, tags, either (const Nothing) Just res)
instance (Eq k, Eq t, Eq a) => Eq (Inspected k t a) where
(==) = (==) `on` inspectedTup
instance (Ord k, Ord t, Ord a) => Ord (Inspected k t a) where
compare = comparing inspectedTup
instance Functor (Inspected k t) where
fmap f insp = insp {
_inspectionResult = fmap f (_inspectionResult insp) }
instance Foldable (Inspected k t) where
foldMap f = either mempty f . _inspectionResult
instance Traversable (Inspected k t) where
traverse f (Inspected insp i ts r) = Inspected insp i ts <$> either (pure . Left) (liftA Right . f) r
instance (NFData k, NFData t, NFData a) => NFData (Inspected k t a) where
rnf (Inspected t i ts r) = rnf t `seq` rnf i `seq` rnf ts `seq` rnf r
instance (ToJSON k, ToJSON t, ToJSON a) => ToJSON (Inspected k t a) where
toJSON im = object [
"inspection" .= _inspection im,
"location" .= _inspectedKey im,
"tags" .= S.toList (_inspectionTags im),
either ("error" .=) ("result" .=) (_inspectionResult im)]
instance (FromJSON k, Ord t, FromJSON t, FromJSON a) => FromJSON (Inspected k t a) where
parseJSON = withObject "inspected" $ \v -> Inspected <$>
v .:: "inspection" <*>
v .:: "location" <*>
(S.fromList <$> (v .::?! "tags")) <*>
((Left <$> v .:: "error") <|> (Right <$> v .:: "result"))
newtype InspectM k t m a = InspectM { runInspectM :: ReaderT k (ExceptT HsDevError (StateT (Inspection, S.Set t) m)) a }
deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadIO, MonadThrow, MonadCatch, MonadReader k, MonadError HsDevError, MonadState (Inspection, S.Set t))
instance MonadTrans (InspectM k t) where
lift = InspectM . lift . lift . lift
runInspect :: (Monad m, Ord t) => k -> InspectM k t m a -> m (Inspected k t a)
runInspect key act = do
(res, (insp, ts)) <- flip runStateT (InspectionNone, mempty) . runExceptT . flip runReaderT key . runInspectM $ act
return $ Inspected insp key ts res
continueInspect :: (Monad m, Ord t) => Inspected k t a -> (a -> InspectM k t m b) -> m (Inspected k t b)
continueInspect start act = runInspect (_inspectedKey start) $ do
put (_inspection start, _inspectionTags start)
val <- either throwError return $ _inspectionResult start
act val
inspect :: MonadCatch m => m Inspection -> (k -> m a) -> InspectM k t m a
inspect insp act = withInspection insp $ do
key <- ask
lift (hsdevCatch (hsdevLiftIO $ act key)) >>= either throwError return
withInspection :: MonadCatch m => m Inspection -> InspectM k t m a -> InspectM k t m a
withInspection insp inner = do
insp' <- lift insp
let
setInsp = modify (set _1 insp')
catchError (inner <* setInsp) (\e -> setInsp >> throwError e)
inspect_ :: MonadCatch m => m Inspection -> m a -> InspectM k t m a
inspect_ insp = inspect insp . const
noTags :: Set t
noTags = S.empty
tag :: t -> Set t
tag = S.singleton
data ModuleTag = InferredTypesTag | RefinedDocsTag | OnlyHeaderTag | DirtyTag | ResolvedNamesTag deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance NFData ModuleTag where
rnf InferredTypesTag = ()
rnf RefinedDocsTag = ()
rnf OnlyHeaderTag = ()
rnf DirtyTag = ()
rnf ResolvedNamesTag = ()
instance Display ModuleTag where
display InferredTypesTag = "types"
display RefinedDocsTag = "docs"
display OnlyHeaderTag = "header"
display DirtyTag = "dirty"
display ResolvedNamesTag = "resolved"
displayType _ = "module-tag"
instance ToJSON ModuleTag where
toJSON InferredTypesTag = toJSON ("types" :: String)
toJSON RefinedDocsTag = toJSON ("docs" :: String)
toJSON OnlyHeaderTag = toJSON ("header" :: String)
toJSON DirtyTag = toJSON ("dirty" :: String)
toJSON ResolvedNamesTag = toJSON ("resolved" :: String)
instance FromJSON ModuleTag where
parseJSON = withText "module-tag" $ \txt -> msum [
guard (txt == "types") >> return InferredTypesTag,
guard (txt == "docs") >> return RefinedDocsTag,
guard (txt == "header") >> return OnlyHeaderTag,
guard (txt == "dirty") >> return DirtyTag,
guard (txt == "resolved") >> return ResolvedNamesTag]
type InspectedModule = Inspected ModuleLocation ModuleTag Module
instance Show InspectedModule where
show (Inspected i mi ts m) = unlines [either showError show m, "\tinspected: " ++ show i, "\ttags: " ++ intercalate ", " (map show $ S.toList ts)] where
showError :: HsDevError -> String
showError e = unlines $ ("\terror: " ++ show e) : case mi of
FileModule f p -> ["file: " ++ f ^. path, "project: " ++ maybe "" (view (projectPath . path)) p]
InstalledModule c p n _ -> ["cabal: " ++ show c, "package: " ++ show p, "name: " ++ T.unpack n]
OtherLocation src -> ["other location: " ++ T.unpack src]
NoLocation -> ["no location"]
notInspected :: ModuleLocation -> InspectedModule
notInspected mloc = Inspected mempty mloc noTags (Left $ NotInspected mloc)
instance Documented ModuleId where
brief m = brief $ _moduleLocation m
detailed = brief
instance Documented SymbolId where
brief s = "{} from {}" ~~ _symbolName s ~~ brief (_symbolModule s)
detailed = brief
instance Documented Module where
brief = brief . _moduleId
detailed m = T.unlines (brief m : info) where
info = [
"\texports: {}" ~~ T.intercalate ", " (map brief (_moduleExports m))]
instance Documented Symbol where
brief = brief . _symbolId
detailed s = T.unlines [brief s, info] where
info = case _symbolInfo s of
Function t -> "\t" `T.append` T.intercalate ", " (catMaybes [Just "function", fmap ("type: {}" ~~) t])
Method t p -> "\t" `T.append` T.intercalate ", " (catMaybes [Just "method", fmap ("type: {}" ~~) t, Just $ "parent: {}" ~~ p])
Selector t p _ -> "\t" `T.append` T.intercalate ", " (catMaybes [Just "selector", fmap ("type: {}" ~~) t, Just $ "parent: {}" ~~ p])
Constructor args p -> "\t" `T.append` T.intercalate ", " ["constructor", "args: {}" ~~ T.unwords args, "parent: {}" ~~ p]
Type args ctx -> "\t" `T.append` T.intercalate ", " ["type", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
NewType args ctx -> "\t" `T.append` T.intercalate ", " ["newtype", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
Data args ctx -> "\t" `T.append` T.intercalate ", " ["data", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
Class args ctx -> "\t" `T.append` T.intercalate ", " ["class", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
TypeFam args ctx _ -> "\t" `T.append` T.intercalate ", " ["type family", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
DataFam args ctx _ -> "\t" `T.append` T.intercalate ", " ["data family", "args: {}" ~~ T.unwords args, "ctx: {}" ~~ T.unwords ctx]
PatConstructor args p -> "\t" `T.append` T.intercalate ", " (catMaybes [Just "pattern constructor", Just $ "args: {}" ~~ T.unwords args, fmap ("pat-type: {}" ~~) p])
PatSelector t p _ -> "\t" `T.append` T.intercalate ", " (catMaybes [Just "pattern selector", fmap ("type: {}" ~~) t, fmap ("pat-type: {}" ~~) p])
makeLenses ''Import
makeLenses ''Module
makeLenses ''Symbol
makeLenses ''SymbolInfo
makeLenses ''Scoped
makeLenses ''SymbolUsage
makeLenses ''ImportedSymbol
makeLenses ''Inspection
makeLenses ''Inspected
inspected :: Traversal (Inspected k t a) (Inspected k t b) a b
inspected = inspectionResult . _Right
nullifyInfo :: SymbolInfo -> SymbolInfo
nullifyInfo = chain [
set functionType mempty,
set parentClass mempty,
set parentType mempty,
set selectorConstructors mempty,
set typeArgs mempty,
set typeContext mempty,
set familyAssociate mempty,
set patternType mempty,
set patternConstructor mempty]
instance Sourced Module where
sourcedName = moduleId . moduleName
sourcedDocs = moduleDocs . _Just
sourcedModule = moduleId
instance Sourced Symbol where
sourcedName = symbolId . symbolName
sourcedDocs = symbolDocs . _Just
sourcedModule = symbolId . symbolModule
sourcedLocation = symbolPosition . _Just
|
d29842aa6433311cfbc00011f960167156d4add06487450bbfc275e1819041fe | kanaka/html5-css3-ebnf | html_mangle.clj | (ns html5-css3-ebnf.html-mangle
(:require [clojure.java.io :as io]
[clojure.string :as S]
[clojure.set :as set]
[clojure.pprint :refer [pprint]]
[linked.core :as linked]
[instaparse.core :as instaparse]
[instacheck.core :as icore]))
(def PRUNE-TAGS
#{"style"
"script"
"svg"
"font"})
(def PRUNE-TAGS-BY-ATTRIBUTE
;; [tag attribute]
#{["meta" "property"]})
(def PRUNE-TAGS-BY-ATTRIBUTE-VALUE
;; [tag attribute value]
#{["link" "rel" "stylesheet"]})
(def PRUNE-ATTRIBUTES
#{"style"
"align"
"x-ms-format-detection"
"data-viewport-emitter-state"
"windowdimensionstracker"})
(def PRUNE-TAG-ATTRIBUTES
;; tag -> [attribute ...]
{"input" ["autocapitalize" "autocorrect"]
"link" ["as" "color"]
"meta" ["value"]
"iframe" ["frameborder" "scrolling"]
"div" ["type"]
"span" ["for" "fahrenheit"]
"td" ["width"]
"table" ["cellspacing" "cellpadding" "frame" "width"]
;; TODO: these are HTML 5+ and shouldn't be removed when parsing
;; that.
"video" ["playsinline" "webkit-playsinline"]
})
(def REWRITE-TAG-ATTRIBUTE-VALUES
;; {[tag attribute value] new-value}
{["link" "rel" "styleSheet"] "stylesheet"
["select" "required" "required"] "true"
["table" "border" "0"] ""})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Tags and Attrs Method
(def TnA-parser
(instaparse/parser (slurp (io/resource "tags-and-attrs.ebnf"))))
(defn TnA-parse
[text]
(icore/parse TnA-parser text))
;; ---
(defn pr-noval-attr [[aname {:keys [asp nsp vsp avals] :as sp-avals}]]
(str (first asp) aname (first nsp)))
(defn pr-all-attrs [[aname {:keys [asp nsp vsp avals] :as sp-avals}]]
(S/join
""
(map #(str %1 aname %2 "=" %3 "\"" %4 "\"") asp nsp vsp avals)))
(defn pr-first-attr [[aname {:keys [asp nsp vsp avals] :as sp-avals}]]
(str (first asp) aname (first nsp)
"=" (first vsp) "\"" (first avals) "\""))
(defn pr-merged-attr [[aname {:keys [asp nsp vsp avals]} :as attr]]
(let [avals (filter #(not (re-seq #"^\s*$" %)) avals)]
(condp = aname
"style" (str (first asp) aname (first nsp)
"=" (first vsp) "\"" (S/join "; " avals) "\"")
"class" (str (first asp) aname (first nsp)
"=" (first vsp) "\"" (S/join " " avals) "\"")
(pr-all-attrs attr))))
(defn- trim-surrounding-spaces
[text]
(-> text (S/replace #"^\s*" "") (S/replace #"\s*$" ""))
)
(defn- attr-map
[attrs-elem]
(loop [attrs (linked/map) ;; ordered map
attr-elems (rest attrs-elem)]
(if (seq attr-elems)
(let [[attr & attr-elems] attr-elems
[_ asp [_ aname] nsp [_ vsp aval :as has-aval?]] attr
;; Empty string is different than no value and should be
;; retained
aval (if aval
(trim-surrounding-spaces aval)
(if has-aval?
""
nil))]
(recur (-> attrs
(update-in [aname :asp] (fnil conj []) asp)
(update-in [aname :nsp] (fnil conj []) nsp)
(update-in [aname :vsp] (fnil conj []) vsp)
(update-in [aname :avals] (fnil conj []) aval))
attr-elems))
attrs)))
(defn- elem-to-text
[elem {:keys [cur-tag
dupe-attr-mode
trim-spaces?
prune-tags
prune-tags-by-attr
prune-tags-by-attr-val
prune-attrs
prune-tag-attrs
rewrite-tag-attr-vals]}]
(let [tag (nth elem 2)
all-attrs (attr-map (nth elem 3))
ta-set (set (map vector
(repeat tag)
(keys all-attrs)))
tav-set (set (map vector
(repeat tag)
(keys all-attrs)
(map (comp first :avals) (vals all-attrs))))
attrs (reduce
(fn [attrs [aname {:keys [asp nsp vsp avals] :as sp-avals}]]
(if (or
;; Prune by :prune-attrs
(contains? (set prune-attrs) aname)
;; Prune by :prune-tag-attrs
(contains? (set (get prune-tag-attrs tag)) aname))
attrs
(let [rewr-val (get rewrite-tag-attr-vals
[tag aname (first avals)])
sp-avals {:asp (if trim-spaces?
(repeat (count asp) " ")
asp)
:nsp (if trim-spaces?
(repeat (count nsp) "")
nsp)
:vsp (if trim-spaces?
(repeat (count vsp) "")
vsp)
:avals (if rewr-val
[rewr-val]
avals)}]
(assoc attrs aname sp-avals))))
(linked/map) ;; ordered map
all-attrs)]
(if (or
;; Prune by :prune-tags
(contains? (set prune-tags) tag)
;; TODO: these miss end-elem in the start-elem case
;; Prune by :prune-tags-by-attr
(seq (set/intersection prune-tags-by-attr ta-set))
;; Prune by :prune-tags-by-attr-val
(seq (set/intersection prune-tags-by-attr-val tav-set)))
(if trim-spaces?
[]
;; Just the final spaces to keep subsequent tag indent unchanged
(reduce #(if (re-seq #"\S+" %2) [] (conj %1 %2)) [] (drop 7 elem)))
(concat
;; '<' and tag name
(take 2 (drop 1 elem))
;; attributes
(mapcat (fn [[_ {:keys [avals]} :as attr]]
(if (= [nil] avals)
(pr-noval-attr attr)
(condp = dupe-attr-mode
:first (pr-first-attr attr)
:merge (pr-merged-attr attr)
(pr-all-attrs attr))))
attrs)
(if (and trim-spaces?
(not (#{"style" "script"} tag)))
;; trim starting and ending spaces
(map trim-surrounding-spaces (drop 5 elem))
;; spaces, '>', spaces
(drop 4 elem))))))
(defn- elem-depths
[elem cur-depth]
(let [kind (if (string? elem) :string (first (second elem)))]
(cond
(and (= kind :start-elem)
(#{"meta" "link"} (nth (second elem) 2)))
[cur-depth cur-depth]
(= kind :start-elem)
[cur-depth (inc cur-depth)]
(= kind :end-elem)
[(dec cur-depth) (dec cur-depth)]
:default
[cur-depth cur-depth])))
(defn TnA->html
"Opts:
:dupe-attr-mode - how to handle duplicate attributes name
:trim-spaces? - remove extra leading/trailing spaces
:reindent? - reindent everything (implies :trim-spaces?)
:prune-wrap-ahem? - remove wrap-ahem span tags
:prune-tags - tags to omit by [tag]
:prune-tags-by-attr - tags to omit by [tag, attr]
:prune-tags-by-attr-val - tags to omit by [tag, attr, value]
:prune-attrs - tag attributes to omit by [attr]
:prune-tag-attrs - tag attributes to omit by [tag, attr]
:rewrite-tag-attr-vals - change attribute value by [tag, attr, val]
"
[TnA & [{:keys [trim-spaces? reindent?
prune-wrap-ahem? prune-tags] :as opts}]]
(assert (= :html (first TnA))
"Not a valid parsed HTML grammar")
(let [trim-spaces? (or reindent? trim-spaces?)
opts (assoc opts :trim-spaces? trim-spaces?)
maybe-trim (fn [s] (if trim-spaces?
(trim-surrounding-spaces s)
s))
start-spaces (maybe-trim (second TnA))]
(loop [res []
depth 0
TnA (drop 2 TnA)]
(let [[elem & next-TnA] TnA
[cur-depth new-depth] (elem-depths elem depth)
res (if reindent?
(conj res (apply str "\n" (repeat cur-depth " ")))
res)]
(if (not elem)
(if reindent?
(S/join "" (drop 1 res))
(str start-spaces (S/join "" res)))
(recur
(cond
(string? elem)
(conj res (maybe-trim elem))
(= :content (first (second elem)))
(apply conj res (map maybe-trim (rest (second elem))))
(and prune-wrap-ahem?
(= :ahem-elem (first (second elem))))
res
(= :end-elem (first (second elem)))
(if (contains? (set prune-tags) (nth (second elem) 2))
;; Drop end tag for prune-tags. Matching start tag is
;; handled in elem-to-text.
(apply conj res (map maybe-trim (drop 4 (second elem))))
(apply conj res (map maybe-trim (rest (second elem)))))
:else
(apply conj res (elem-to-text (second elem) opts)))
new-depth
next-TnA))))))
(defn extract-html
"Returns a cleaned up and normalized HTML text string. Primarily
this involves removing or rewriting unsupported tags and
attributes."
[html]
(let [html-no-unicode (S/replace html #"[^\x00-\x7f]" "")
TnA (TnA-parse html-no-unicode)]
(TnA->html
TnA
{:dupe-attr-mode :first
:trim-spaces? true
:prune-wrap-ahem? true
:prune-tags PRUNE-TAGS
:prune-tags-by-attr PRUNE-TAGS-BY-ATTRIBUTE
:prune-tags-by-attr-val PRUNE-TAGS-BY-ATTRIBUTE-VALUE
:prune-attrs PRUNE-ATTRIBUTES
:prune-tag-attrs PRUNE-TAG-ATTRIBUTES
:rewrite-tag-attr-vals REWRITE-TAG-ATTRIBUTE-VALUES})))
(defn- extract-inline-css-from-TnA
"Internal: takes a TnA parse and returns text of all inline styles.
Used by extract-inline-css and extract-css-map."
[TnA]
(let [attrs (reduce
(fn [r elem]
(if (and (vector? elem)
(not (get #{:end-elem :content}
(first (second elem))))
(= :attrs (-> elem second (nth 3) first)))
(apply conj r (-> elem second (nth 3) rest))
r))
[]
TnA)
sattrs (filter #(= [:attr-name "style"] (nth % 2)) attrs)
styles (filter (complement empty?)
(map #(S/replace (last (nth % 4)) #";\s*$" "")
sattrs))]
(str (S/join ";\n" styles))))
(defn cleanup-css
[css-text]
(-> css-text
;; Remove unicode characters
(S/replace #"[^\x00-\x7f]" "")
;; Remove non-unix newlines
(S/replace #"[\r
]" "\n")
;; remove vendor prefixes
(S/replace #"([^A-Za-z0-9])(?:-webkit-|-moz-|-ms-)" "$1")
;; Remove apple specific CSS property
(S/replace #"x-content: *\"[^\"]*\"" "")
;; Some at-rule syntax require semicolons before closing curly
(S/replace #"(@font-face *[{][^}]*[^;])[}]" "$1;}")))
(defn extract-inline-css
"Return text of all inline styles. Specifically it extracts the
content from style attributes and merges it into a single CSS block
that is surrounded by a wildcard selector."
[html]
(cleanup-css
(extract-inline-css-from-TnA (TnA-parse html))))
(defn extract-css-map
"Return a map of CSS texts with the following keys:
- :inline-style -> all inline styles in
a wildcard selector (i.e. '* { STYLES }')
- :inline-sheet-X -> inline stylesheets by indexed keyword
- \"sheet-href\" -> loaded stylesheets by path/URL
The returned styles can be combined into a single stylesheet like this:
(clojure.string/join \"\n\" (apply concat CSS-MAP))"
[html & [get-file]]
(let [get-file (or get-file slurp)
TnA (TnA-parse html)
;; inline via style attribute
inline-styles (str
"* {\n"
(cleanup-css
(extract-inline-css-from-TnA TnA))
"\n}")
;; inline via style tag
style-elems (filter #(and (vector? %)
(= :style-elem (-> % second first)))
TnA)
inline-sheets (map #(-> % second (nth 6)) style-elems)
;; external via link tag
link-elems (filter #(and (vector? %)
(= :start-elem (-> % second first))
(= "link" (-> % second (nth 2))))
TnA)
link-attrs (map #(-> % second (nth 3) attr-map) link-elems)
sheet-attrs (filter #(-> % (get "rel") :avals
first S/lower-case (= "stylesheet"))
link-attrs)
sheet-hrefs (map #(-> % (get "href") :avals first) sheet-attrs)
loaded-sheets (map #(str "/* from: " % " */\n"
(cleanup-css
(get-file %)))
sheet-hrefs)]
(merge {:inline-styles inline-styles}
(zipmap (map (comp keyword str)
(repeat "inline-sheet-")
(range))
inline-sheets)
(zipmap (map str sheet-hrefs)
loaded-sheets))))
| null | https://raw.githubusercontent.com/kanaka/html5-css3-ebnf/b7057b137893dba77d1ecfd410eedef3d2134c41/src/html5_css3_ebnf/html_mangle.clj | clojure | [tag attribute]
[tag attribute value]
tag -> [attribute ...]
TODO: these are HTML 5+ and shouldn't be removed when parsing
that.
{[tag attribute value] new-value}
Tags and Attrs Method
---
" avals) "\"")
ordered map
Empty string is different than no value and should be
retained
Prune by :prune-attrs
Prune by :prune-tag-attrs
ordered map
Prune by :prune-tags
TODO: these miss end-elem in the start-elem case
Prune by :prune-tags-by-attr
Prune by :prune-tags-by-attr-val
Just the final spaces to keep subsequent tag indent unchanged
'<' and tag name
attributes
trim starting and ending spaces
spaces, '>', spaces
Drop end tag for prune-tags. Matching start tag is
handled in elem-to-text.
Remove unicode characters
Remove non-unix newlines
remove vendor prefixes
Remove apple specific CSS property
Some at-rule syntax require semicolons before closing curly
inline via style attribute
inline via style tag
external via link tag | (ns html5-css3-ebnf.html-mangle
(:require [clojure.java.io :as io]
[clojure.string :as S]
[clojure.set :as set]
[clojure.pprint :refer [pprint]]
[linked.core :as linked]
[instaparse.core :as instaparse]
[instacheck.core :as icore]))
(def PRUNE-TAGS
#{"style"
"script"
"svg"
"font"})
(def PRUNE-TAGS-BY-ATTRIBUTE
#{["meta" "property"]})
(def PRUNE-TAGS-BY-ATTRIBUTE-VALUE
#{["link" "rel" "stylesheet"]})
(def PRUNE-ATTRIBUTES
#{"style"
"align"
"x-ms-format-detection"
"data-viewport-emitter-state"
"windowdimensionstracker"})
(def PRUNE-TAG-ATTRIBUTES
{"input" ["autocapitalize" "autocorrect"]
"link" ["as" "color"]
"meta" ["value"]
"iframe" ["frameborder" "scrolling"]
"div" ["type"]
"span" ["for" "fahrenheit"]
"td" ["width"]
"table" ["cellspacing" "cellpadding" "frame" "width"]
"video" ["playsinline" "webkit-playsinline"]
})
(def REWRITE-TAG-ATTRIBUTE-VALUES
{["link" "rel" "styleSheet"] "stylesheet"
["select" "required" "required"] "true"
["table" "border" "0"] ""})
(def TnA-parser
(instaparse/parser (slurp (io/resource "tags-and-attrs.ebnf"))))
(defn TnA-parse
[text]
(icore/parse TnA-parser text))
(defn pr-noval-attr [[aname {:keys [asp nsp vsp avals] :as sp-avals}]]
(str (first asp) aname (first nsp)))
(defn pr-all-attrs [[aname {:keys [asp nsp vsp avals] :as sp-avals}]]
(S/join
""
(map #(str %1 aname %2 "=" %3 "\"" %4 "\"") asp nsp vsp avals)))
(defn pr-first-attr [[aname {:keys [asp nsp vsp avals] :as sp-avals}]]
(str (first asp) aname (first nsp)
"=" (first vsp) "\"" (first avals) "\""))
(defn pr-merged-attr [[aname {:keys [asp nsp vsp avals]} :as attr]]
(let [avals (filter #(not (re-seq #"^\s*$" %)) avals)]
(condp = aname
"style" (str (first asp) aname (first nsp)
"class" (str (first asp) aname (first nsp)
"=" (first vsp) "\"" (S/join " " avals) "\"")
(pr-all-attrs attr))))
(defn- trim-surrounding-spaces
[text]
(-> text (S/replace #"^\s*" "") (S/replace #"\s*$" ""))
)
(defn- attr-map
[attrs-elem]
attr-elems (rest attrs-elem)]
(if (seq attr-elems)
(let [[attr & attr-elems] attr-elems
[_ asp [_ aname] nsp [_ vsp aval :as has-aval?]] attr
aval (if aval
(trim-surrounding-spaces aval)
(if has-aval?
""
nil))]
(recur (-> attrs
(update-in [aname :asp] (fnil conj []) asp)
(update-in [aname :nsp] (fnil conj []) nsp)
(update-in [aname :vsp] (fnil conj []) vsp)
(update-in [aname :avals] (fnil conj []) aval))
attr-elems))
attrs)))
(defn- elem-to-text
[elem {:keys [cur-tag
dupe-attr-mode
trim-spaces?
prune-tags
prune-tags-by-attr
prune-tags-by-attr-val
prune-attrs
prune-tag-attrs
rewrite-tag-attr-vals]}]
(let [tag (nth elem 2)
all-attrs (attr-map (nth elem 3))
ta-set (set (map vector
(repeat tag)
(keys all-attrs)))
tav-set (set (map vector
(repeat tag)
(keys all-attrs)
(map (comp first :avals) (vals all-attrs))))
attrs (reduce
(fn [attrs [aname {:keys [asp nsp vsp avals] :as sp-avals}]]
(if (or
(contains? (set prune-attrs) aname)
(contains? (set (get prune-tag-attrs tag)) aname))
attrs
(let [rewr-val (get rewrite-tag-attr-vals
[tag aname (first avals)])
sp-avals {:asp (if trim-spaces?
(repeat (count asp) " ")
asp)
:nsp (if trim-spaces?
(repeat (count nsp) "")
nsp)
:vsp (if trim-spaces?
(repeat (count vsp) "")
vsp)
:avals (if rewr-val
[rewr-val]
avals)}]
(assoc attrs aname sp-avals))))
all-attrs)]
(if (or
(contains? (set prune-tags) tag)
(seq (set/intersection prune-tags-by-attr ta-set))
(seq (set/intersection prune-tags-by-attr-val tav-set)))
(if trim-spaces?
[]
(reduce #(if (re-seq #"\S+" %2) [] (conj %1 %2)) [] (drop 7 elem)))
(concat
(take 2 (drop 1 elem))
(mapcat (fn [[_ {:keys [avals]} :as attr]]
(if (= [nil] avals)
(pr-noval-attr attr)
(condp = dupe-attr-mode
:first (pr-first-attr attr)
:merge (pr-merged-attr attr)
(pr-all-attrs attr))))
attrs)
(if (and trim-spaces?
(not (#{"style" "script"} tag)))
(map trim-surrounding-spaces (drop 5 elem))
(drop 4 elem))))))
(defn- elem-depths
[elem cur-depth]
(let [kind (if (string? elem) :string (first (second elem)))]
(cond
(and (= kind :start-elem)
(#{"meta" "link"} (nth (second elem) 2)))
[cur-depth cur-depth]
(= kind :start-elem)
[cur-depth (inc cur-depth)]
(= kind :end-elem)
[(dec cur-depth) (dec cur-depth)]
:default
[cur-depth cur-depth])))
(defn TnA->html
"Opts:
:dupe-attr-mode - how to handle duplicate attributes name
:trim-spaces? - remove extra leading/trailing spaces
:reindent? - reindent everything (implies :trim-spaces?)
:prune-wrap-ahem? - remove wrap-ahem span tags
:prune-tags - tags to omit by [tag]
:prune-tags-by-attr - tags to omit by [tag, attr]
:prune-tags-by-attr-val - tags to omit by [tag, attr, value]
:prune-attrs - tag attributes to omit by [attr]
:prune-tag-attrs - tag attributes to omit by [tag, attr]
:rewrite-tag-attr-vals - change attribute value by [tag, attr, val]
"
[TnA & [{:keys [trim-spaces? reindent?
prune-wrap-ahem? prune-tags] :as opts}]]
(assert (= :html (first TnA))
"Not a valid parsed HTML grammar")
(let [trim-spaces? (or reindent? trim-spaces?)
opts (assoc opts :trim-spaces? trim-spaces?)
maybe-trim (fn [s] (if trim-spaces?
(trim-surrounding-spaces s)
s))
start-spaces (maybe-trim (second TnA))]
(loop [res []
depth 0
TnA (drop 2 TnA)]
(let [[elem & next-TnA] TnA
[cur-depth new-depth] (elem-depths elem depth)
res (if reindent?
(conj res (apply str "\n" (repeat cur-depth " ")))
res)]
(if (not elem)
(if reindent?
(S/join "" (drop 1 res))
(str start-spaces (S/join "" res)))
(recur
(cond
(string? elem)
(conj res (maybe-trim elem))
(= :content (first (second elem)))
(apply conj res (map maybe-trim (rest (second elem))))
(and prune-wrap-ahem?
(= :ahem-elem (first (second elem))))
res
(= :end-elem (first (second elem)))
(if (contains? (set prune-tags) (nth (second elem) 2))
(apply conj res (map maybe-trim (drop 4 (second elem))))
(apply conj res (map maybe-trim (rest (second elem)))))
:else
(apply conj res (elem-to-text (second elem) opts)))
new-depth
next-TnA))))))
(defn extract-html
"Returns a cleaned up and normalized HTML text string. Primarily
this involves removing or rewriting unsupported tags and
attributes."
[html]
(let [html-no-unicode (S/replace html #"[^\x00-\x7f]" "")
TnA (TnA-parse html-no-unicode)]
(TnA->html
TnA
{:dupe-attr-mode :first
:trim-spaces? true
:prune-wrap-ahem? true
:prune-tags PRUNE-TAGS
:prune-tags-by-attr PRUNE-TAGS-BY-ATTRIBUTE
:prune-tags-by-attr-val PRUNE-TAGS-BY-ATTRIBUTE-VALUE
:prune-attrs PRUNE-ATTRIBUTES
:prune-tag-attrs PRUNE-TAG-ATTRIBUTES
:rewrite-tag-attr-vals REWRITE-TAG-ATTRIBUTE-VALUES})))
(defn- extract-inline-css-from-TnA
"Internal: takes a TnA parse and returns text of all inline styles.
Used by extract-inline-css and extract-css-map."
[TnA]
(let [attrs (reduce
(fn [r elem]
(if (and (vector? elem)
(not (get #{:end-elem :content}
(first (second elem))))
(= :attrs (-> elem second (nth 3) first)))
(apply conj r (-> elem second (nth 3) rest))
r))
[]
TnA)
sattrs (filter #(= [:attr-name "style"] (nth % 2)) attrs)
styles (filter (complement empty?)
(map #(S/replace (last (nth % 4)) #";\s*$" "")
sattrs))]
(str (S/join ";\n" styles))))
(defn cleanup-css
[css-text]
(-> css-text
(S/replace #"[^\x00-\x7f]" "")
(S/replace #"[\r
]" "\n")
(S/replace #"([^A-Za-z0-9])(?:-webkit-|-moz-|-ms-)" "$1")
(S/replace #"x-content: *\"[^\"]*\"" "")
(S/replace #"(@font-face *[{][^}]*[^;])[}]" "$1;}")))
(defn extract-inline-css
"Return text of all inline styles. Specifically it extracts the
content from style attributes and merges it into a single CSS block
that is surrounded by a wildcard selector."
[html]
(cleanup-css
(extract-inline-css-from-TnA (TnA-parse html))))
(defn extract-css-map
"Return a map of CSS texts with the following keys:
- :inline-style -> all inline styles in
a wildcard selector (i.e. '* { STYLES }')
- :inline-sheet-X -> inline stylesheets by indexed keyword
- \"sheet-href\" -> loaded stylesheets by path/URL
The returned styles can be combined into a single stylesheet like this:
(clojure.string/join \"\n\" (apply concat CSS-MAP))"
[html & [get-file]]
(let [get-file (or get-file slurp)
TnA (TnA-parse html)
inline-styles (str
"* {\n"
(cleanup-css
(extract-inline-css-from-TnA TnA))
"\n}")
style-elems (filter #(and (vector? %)
(= :style-elem (-> % second first)))
TnA)
inline-sheets (map #(-> % second (nth 6)) style-elems)
link-elems (filter #(and (vector? %)
(= :start-elem (-> % second first))
(= "link" (-> % second (nth 2))))
TnA)
link-attrs (map #(-> % second (nth 3) attr-map) link-elems)
sheet-attrs (filter #(-> % (get "rel") :avals
first S/lower-case (= "stylesheet"))
link-attrs)
sheet-hrefs (map #(-> % (get "href") :avals first) sheet-attrs)
loaded-sheets (map #(str "/* from: " % " */\n"
(cleanup-css
(get-file %)))
sheet-hrefs)]
(merge {:inline-styles inline-styles}
(zipmap (map (comp keyword str)
(repeat "inline-sheet-")
(range))
inline-sheets)
(zipmap (map str sheet-hrefs)
loaded-sheets))))
|
c0c0f37096c5f47723e0fd3e822d5450a5033da9125e2d993bdbe88b8e08d34f | cpeikert/Lol | Language.hs | |
Module : Crypto . Lol . Cyclotomic . Language
Description : Abstract interfaces for operations on cyclotomic rings .
Copyright : ( c ) , 2018-
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
\ ( \def\Z{\mathbb{Z } } \ )
\ ( \def\F{\mathbb{F } } \ )
\ ( \def\Q{\mathbb{Q } } \ )
\ ( \def\Tw{\text{Tw } } \ )
\ ( \def\Tr{\text{Tr } } \ )
\ ( \def\O{\mathcal{O } } \ )
Module : Crypto.Lol.Cyclotomic.Language
Description : Abstract interfaces for operations on cyclotomic rings.
Copyright : (c) Chris Peikert, 2018-
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
\( \def\Z{\mathbb{Z}} \)
\( \def\F{\mathbb{F}} \)
\( \def\Q{\mathbb{Q}} \)
\( \def\Tw{\text{Tw}} \)
\( \def\Tr{\text{Tr}} \)
\( \def\O{\mathcal{O}} \)
-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
module Crypto.Lol.Cyclotomic.Language
where
import Crypto.Lol.Prelude
import Control.Monad.Random (MonadRandom)
-- | Used to specify a basis for cyclotomic operations
data Basis = Pow | Dec
| Operations on cyclotomics .
class Cyclotomic cmr where
-- | Multiply by the special element \( g \).
mulG :: cmr -> cmr
-- | Divide by the special element \( g \), returning 'Nothing' if
-- the input is not evenly divisible.
divG :: cmr -> Maybe cmr
| Yield an equivalent element that be in
-- powerful\/decoding\/CRT representation. This can serve as an
-- optimization hint. E.g., call 'adviseCRT' prior to multiplying a
-- value by many other values.
advisePow, adviseDec, adviseCRT :: cmr -> cmr
class GSqNormCyc cm r where
-- | Yield the scaled squared norm of \( g_m \cdot e \) under the
-- canonical embedding, namely, \( \hat{m}^{-1} \cdot \| \sigma(g_m
-- \cdot e) \|^2 \).
gSqNorm :: cm r -> r
| Sampling from tweaked Gaussian distributions over cyclotomic
-- number fields.
class GaussianCyc cmq where
-- | Sample from the "tweaked" Gaussian distribution \( t \cdot D
-- \), where \( D \) has scaled variance \( v \).
tweakedGaussian :: (ToRational v, MonadRandom rnd) => v -> rnd cmq
| Sampling from /discretized/ tweaked Gaussian distributions over
-- cyclotomic number rings.
class RoundedGaussianCyc cmz where
| Sample from the tweaked Gaussian with given scaled variance ,
-- deterministically rounded using the decoding basis.
roundedGaussian :: (ToRational v, MonadRandom rnd) => v -> rnd cmz
| Sampling from tweaked Gaussian distributions , discretized to
-- mod-p cosets of cyclotomic number rings.
class CosetGaussianCyc rp where
| Sample from the tweaked Gaussian with scaled variance \ ( v
-- \cdot p^2 \), deterministically rounded to the given coset of
-- \( R_p \) using the decoding basis.
cosetGaussian :: (ToRational v, MonadRandom rnd)
=> v -> rp -> rnd (LiftOf rp)
| Cyclotomic extensions \ ( \O_{m'}/\O_m \ ) .
class ExtensionCyc c r where
-- | Embed into a cyclotomic extension.
embed :: (m `Divides` m') => c m r -> c m' r
| The " tweaked trace " ( twace ) \ ( \Tw(x ) = ( \hat{m } / \hat{m } ' )
-- \cdot \Tr((g' / g) \cdot x) \), which is the left-inverse of
-- 'embed' (i.e., @twace . embed == id@).
twace :: (m `Divides` m') => c m' r -> c m r
-- | The relative powerful/decoding bases of the extension.
powBasis :: (m `Divides` m') => Tagged m [c m' r]
-- | Yield the coefficient vector with respect to the given
-- (relative) basis of the extension.
coeffsCyc :: (m `Divides` m') => Basis -> c m' r -> [c m r]
coeffsPow, coeffsDec :: (ExtensionCyc c r, m `Divides` m') => c m' r -> [c m r]
-- | 'coeffsCyc' specialized to the powerful basis.
coeffsPow = coeffsCyc Pow
-- | 'coeffsCyc' specialized to the decoding basis.
coeffsDec = coeffsCyc Dec
-- | Relative CRT sets of cyclotomic extensions.
class ExtensionCyc c r => CRTSetCyc c r where
-- | The relative mod-@r@ CRT set of the extension.
crtSet :: (m `Divides` m') => Tagged m [c m' r]
-- | Map over coefficients in a specified basis.
class FunctorCyc cm a b where
-- | Map in the specified basis (where 'Nothing' indicates that
-- any 'Basis' may be used).
fmapCyc :: Maybe Basis -> (a -> b) -> cm a -> cm b
-- | Convenient specializations of 'fmapCyc'.
fmapAny, fmapPow, fmapDec :: FunctorCyc cm a b => (a -> b) -> cm a -> cm b
fmapAny = fmapCyc Nothing
fmapPow = fmapCyc $ Just Pow
fmapDec = fmapCyc $ Just Dec
-- | Fold over coefficients in a specified basis.
class FoldableCyc cm a where
-- | Fold in the specified basis (where 'Nothing' indicates that
-- any 'Basis' may be used).
foldrCyc :: Maybe Basis -> (a -> b -> b) -> b -> cm a -> b
-- | Convenient specializations of 'foldrCyc'.
foldrAny, foldrPow, foldrDec :: FoldableCyc cm a => (a -> b -> b) -> b -> cm a -> b
foldrAny = foldrCyc Nothing
foldrPow = foldrCyc $ Just Pow
foldrDec = foldrCyc $ Just Dec
-- | Reduce on a cyclotomic (in an arbitrary basis).
reduceCyc :: (FunctorCyc cm a b, Reduce a b) => cm a -> cm b
reduceCyc = fmapAny reduce
-- | Lift a cyclotomic in a specified basis.
class LiftCyc cmr where
-- | Lift in the specified basis (where 'Nothing' indicates that any
-- 'Basis' may be used).
liftCyc :: Maybe Basis -> cmr -> LiftOf cmr
-- | Convenient specializations of 'liftCyc'.
liftAny, liftPow, liftDec :: LiftCyc cmr => cmr -> LiftOf cmr
liftAny = liftCyc Nothing
liftPow = liftCyc $ Just Pow
liftDec = liftCyc $ Just Dec
| Rescaling on cyclotomics from one base ring to another . ( This is
-- a separate class because there are optimized rescaling algorithms
-- that can't be implemented using 'FunctorCyc'.)
class RescaleCyc cm a b where
-- | Rescale in the given basis.
rescaleCyc :: Basis -> cm a -> cm b
rescalePow, rescaleDec :: (RescaleCyc cm a b) => cm a -> cm b
-- | 'rescaleCyc' specialized to the powerful basis.
rescalePow = rescaleCyc Pow
-- | 'rescaleCyc' specialized to the decoding basis.
rescaleDec = rescaleCyc Dec
| null | https://raw.githubusercontent.com/cpeikert/Lol/4416ac4f03b0bff08cb1115c72a45eed1fa48ec3/lol/Crypto/Lol/Cyclotomic/Language.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
| Used to specify a basis for cyclotomic operations
| Multiply by the special element \( g \).
| Divide by the special element \( g \), returning 'Nothing' if
the input is not evenly divisible.
powerful\/decoding\/CRT representation. This can serve as an
optimization hint. E.g., call 'adviseCRT' prior to multiplying a
value by many other values.
| Yield the scaled squared norm of \( g_m \cdot e \) under the
canonical embedding, namely, \( \hat{m}^{-1} \cdot \| \sigma(g_m
\cdot e) \|^2 \).
number fields.
| Sample from the "tweaked" Gaussian distribution \( t \cdot D
\), where \( D \) has scaled variance \( v \).
cyclotomic number rings.
deterministically rounded using the decoding basis.
mod-p cosets of cyclotomic number rings.
\cdot p^2 \), deterministically rounded to the given coset of
\( R_p \) using the decoding basis.
| Embed into a cyclotomic extension.
\cdot \Tr((g' / g) \cdot x) \), which is the left-inverse of
'embed' (i.e., @twace . embed == id@).
| The relative powerful/decoding bases of the extension.
| Yield the coefficient vector with respect to the given
(relative) basis of the extension.
| 'coeffsCyc' specialized to the powerful basis.
| 'coeffsCyc' specialized to the decoding basis.
| Relative CRT sets of cyclotomic extensions.
| The relative mod-@r@ CRT set of the extension.
| Map over coefficients in a specified basis.
| Map in the specified basis (where 'Nothing' indicates that
any 'Basis' may be used).
| Convenient specializations of 'fmapCyc'.
| Fold over coefficients in a specified basis.
| Fold in the specified basis (where 'Nothing' indicates that
any 'Basis' may be used).
| Convenient specializations of 'foldrCyc'.
| Reduce on a cyclotomic (in an arbitrary basis).
| Lift a cyclotomic in a specified basis.
| Lift in the specified basis (where 'Nothing' indicates that any
'Basis' may be used).
| Convenient specializations of 'liftCyc'.
a separate class because there are optimized rescaling algorithms
that can't be implemented using 'FunctorCyc'.)
| Rescale in the given basis.
| 'rescaleCyc' specialized to the powerful basis.
| 'rescaleCyc' specialized to the decoding basis. | |
Module : Crypto . Lol . Cyclotomic . Language
Description : Abstract interfaces for operations on cyclotomic rings .
Copyright : ( c ) , 2018-
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
\ ( \def\Z{\mathbb{Z } } \ )
\ ( \def\F{\mathbb{F } } \ )
\ ( \def\Q{\mathbb{Q } } \ )
\ ( \def\Tw{\text{Tw } } \ )
\ ( \def\Tr{\text{Tr } } \ )
\ ( \def\O{\mathcal{O } } \ )
Module : Crypto.Lol.Cyclotomic.Language
Description : Abstract interfaces for operations on cyclotomic rings.
Copyright : (c) Chris Peikert, 2018-
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
\( \def\Z{\mathbb{Z}} \)
\( \def\F{\mathbb{F}} \)
\( \def\Q{\mathbb{Q}} \)
\( \def\Tw{\text{Tw}} \)
\( \def\Tr{\text{Tr}} \)
\( \def\O{\mathcal{O}} \)
-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
module Crypto.Lol.Cyclotomic.Language
where
import Crypto.Lol.Prelude
import Control.Monad.Random (MonadRandom)
data Basis = Pow | Dec
| Operations on cyclotomics .
class Cyclotomic cmr where
mulG :: cmr -> cmr
divG :: cmr -> Maybe cmr
| Yield an equivalent element that be in
advisePow, adviseDec, adviseCRT :: cmr -> cmr
class GSqNormCyc cm r where
gSqNorm :: cm r -> r
| Sampling from tweaked Gaussian distributions over cyclotomic
class GaussianCyc cmq where
tweakedGaussian :: (ToRational v, MonadRandom rnd) => v -> rnd cmq
| Sampling from /discretized/ tweaked Gaussian distributions over
class RoundedGaussianCyc cmz where
| Sample from the tweaked Gaussian with given scaled variance ,
roundedGaussian :: (ToRational v, MonadRandom rnd) => v -> rnd cmz
| Sampling from tweaked Gaussian distributions , discretized to
class CosetGaussianCyc rp where
| Sample from the tweaked Gaussian with scaled variance \ ( v
cosetGaussian :: (ToRational v, MonadRandom rnd)
=> v -> rp -> rnd (LiftOf rp)
| Cyclotomic extensions \ ( \O_{m'}/\O_m \ ) .
class ExtensionCyc c r where
embed :: (m `Divides` m') => c m r -> c m' r
| The " tweaked trace " ( twace ) \ ( \Tw(x ) = ( \hat{m } / \hat{m } ' )
twace :: (m `Divides` m') => c m' r -> c m r
powBasis :: (m `Divides` m') => Tagged m [c m' r]
coeffsCyc :: (m `Divides` m') => Basis -> c m' r -> [c m r]
coeffsPow, coeffsDec :: (ExtensionCyc c r, m `Divides` m') => c m' r -> [c m r]
coeffsPow = coeffsCyc Pow
coeffsDec = coeffsCyc Dec
class ExtensionCyc c r => CRTSetCyc c r where
crtSet :: (m `Divides` m') => Tagged m [c m' r]
class FunctorCyc cm a b where
fmapCyc :: Maybe Basis -> (a -> b) -> cm a -> cm b
fmapAny, fmapPow, fmapDec :: FunctorCyc cm a b => (a -> b) -> cm a -> cm b
fmapAny = fmapCyc Nothing
fmapPow = fmapCyc $ Just Pow
fmapDec = fmapCyc $ Just Dec
class FoldableCyc cm a where
foldrCyc :: Maybe Basis -> (a -> b -> b) -> b -> cm a -> b
foldrAny, foldrPow, foldrDec :: FoldableCyc cm a => (a -> b -> b) -> b -> cm a -> b
foldrAny = foldrCyc Nothing
foldrPow = foldrCyc $ Just Pow
foldrDec = foldrCyc $ Just Dec
reduceCyc :: (FunctorCyc cm a b, Reduce a b) => cm a -> cm b
reduceCyc = fmapAny reduce
class LiftCyc cmr where
liftCyc :: Maybe Basis -> cmr -> LiftOf cmr
liftAny, liftPow, liftDec :: LiftCyc cmr => cmr -> LiftOf cmr
liftAny = liftCyc Nothing
liftPow = liftCyc $ Just Pow
liftDec = liftCyc $ Just Dec
| Rescaling on cyclotomics from one base ring to another . ( This is
class RescaleCyc cm a b where
rescaleCyc :: Basis -> cm a -> cm b
rescalePow, rescaleDec :: (RescaleCyc cm a b) => cm a -> cm b
rescalePow = rescaleCyc Pow
rescaleDec = rescaleCyc Dec
|
6faa04d228a96fca3bd56bb593122342f309850db4193ab17d665b816f48b9ef | adomokos/haskell-katas | Ex34_FaFunctorTypeClassSpec.hs | module Ex34_FaFunctorTypeClassSpec
( spec
) where
import Test.Hspec
main :: IO ()
main = hspec spec
Functor typeclass is for things that can be mapped over .
This is how it 's implemented :
class Functor f where
fmap : : ( a - > b ) - > f a - > f b
f here is a type constructor
Remember ` Maybe Int ` is a concrete type , ` Maybe a ` is type constructor .
It takes a function from one type to the other , and a functor applied
with one type , and functor applied with another type .
Good old map is a functor : ( a - > b ) - > [ a ] - > [ b ]
instance Functor [ ] where
fmap = map
[ ] is a type constructor
Types that can act like a box can be functors
Maybe is a functor as well :
instance Functor Maybe where
fmap f ( Just x ) = Just ( f x )
fmap f Nothing = Nothing
Functor wants a type constructor that takes one type and not
a concrete type .
Only type constructors with one params can be used in functors .
Types that can act like a box can be functors .
Either is a functor
instance Functor ( Either a ) where
fmap f ( Right x ) = Right ( f x )
fmap f ( Left x ) = Left x
Functor typeclass is for things that can be mapped over.
This is how it's implemented:
class Functor f where
fmap :: (a -> b) -> f a -> f b
f here is a type constructor
Remember `Maybe Int` is a concrete type, `Maybe a` is type constructor.
It takes a function from one type to the other, and a functor applied
with one type, and functor applied with another type.
Good old map is a functor: (a -> b) -> [a] -> [b]
instance Functor [] where
fmap = map
[] is a type constructor
Types that can act like a box can be functors
Maybe is a functor as well:
instance Functor Maybe where
fmap f (Just x) = Just (f x)
fmap f Nothing = Nothing
Functor wants a type constructor that takes one type and not
a concrete type.
Only type constructors with one params can be used in functors.
Types that can act like a box can be functors.
Either is a functor
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x
-}
data Tree a
= EmptyTree
| Node a
(Tree a)
(Tree a)
deriving (Show, Read, Eq)
singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree
treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
| x == a = Node x left right
| x < a = Node a (treeInsert x left) right
| x > a = Node a left (treeInsert x right)
{- Create an Functor implementation of the Tree -}
spec :: Spec
spec =
describe "Functor typeclass" $ do
it "map is a functor" $ do
pending
_ _ _ [ 1 .. 3 ] ` shouldBe ` [ 2,4,6 ]
map _ _ _ [ 1 .. 3 ] ` shouldBe ` [ 2,4,6 ]
_ _ _ ( * 3 ) [ ] ` shouldBe ` [ ]
it "works with Maybe, as it's a functor" $ do
pending
-- fmap (++ " HEY GUYS") ___
` shouldBe ` Just " Something serious . HEY GUYS "
fmap ( + + " HEY GUYS " ) _ _ _ ` shouldBe ` Nothing
fmap ( * 2 ) _ _ _ ` shouldBe ` Just 400
fmap ( * 3 ) _ _ _ ` shouldBe ` Nothing
it "works with our Tree type class" $ do
pending
let nums = [ 20,28,12 ]
-- let numsTree = foldr treeInsert EmptyTree nums
fmap ( * 2 ) _ _ _ ` shouldBe ` EmptyTree
-- fmap ___ (foldr treeInsert EmptyTree [5,7,3])
` shouldBe ` numsTree
| null | https://raw.githubusercontent.com/adomokos/haskell-katas/be06d23192e6aca4297814455247fc74814ccbf1/test/Ex34_FaFunctorTypeClassSpec.hs | haskell | Create an Functor implementation of the Tree
fmap (++ " HEY GUYS") ___
let numsTree = foldr treeInsert EmptyTree nums
fmap ___ (foldr treeInsert EmptyTree [5,7,3]) | module Ex34_FaFunctorTypeClassSpec
( spec
) where
import Test.Hspec
main :: IO ()
main = hspec spec
Functor typeclass is for things that can be mapped over .
This is how it 's implemented :
class Functor f where
fmap : : ( a - > b ) - > f a - > f b
f here is a type constructor
Remember ` Maybe Int ` is a concrete type , ` Maybe a ` is type constructor .
It takes a function from one type to the other , and a functor applied
with one type , and functor applied with another type .
Good old map is a functor : ( a - > b ) - > [ a ] - > [ b ]
instance Functor [ ] where
fmap = map
[ ] is a type constructor
Types that can act like a box can be functors
Maybe is a functor as well :
instance Functor Maybe where
fmap f ( Just x ) = Just ( f x )
fmap f Nothing = Nothing
Functor wants a type constructor that takes one type and not
a concrete type .
Only type constructors with one params can be used in functors .
Types that can act like a box can be functors .
Either is a functor
instance Functor ( Either a ) where
fmap f ( Right x ) = Right ( f x )
fmap f ( Left x ) = Left x
Functor typeclass is for things that can be mapped over.
This is how it's implemented:
class Functor f where
fmap :: (a -> b) -> f a -> f b
f here is a type constructor
Remember `Maybe Int` is a concrete type, `Maybe a` is type constructor.
It takes a function from one type to the other, and a functor applied
with one type, and functor applied with another type.
Good old map is a functor: (a -> b) -> [a] -> [b]
instance Functor [] where
fmap = map
[] is a type constructor
Types that can act like a box can be functors
Maybe is a functor as well:
instance Functor Maybe where
fmap f (Just x) = Just (f x)
fmap f Nothing = Nothing
Functor wants a type constructor that takes one type and not
a concrete type.
Only type constructors with one params can be used in functors.
Types that can act like a box can be functors.
Either is a functor
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x
-}
data Tree a
= EmptyTree
| Node a
(Tree a)
(Tree a)
deriving (Show, Read, Eq)
singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree
treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
| x == a = Node x left right
| x < a = Node a (treeInsert x left) right
| x > a = Node a left (treeInsert x right)
spec :: Spec
spec =
describe "Functor typeclass" $ do
it "map is a functor" $ do
pending
_ _ _ [ 1 .. 3 ] ` shouldBe ` [ 2,4,6 ]
map _ _ _ [ 1 .. 3 ] ` shouldBe ` [ 2,4,6 ]
_ _ _ ( * 3 ) [ ] ` shouldBe ` [ ]
it "works with Maybe, as it's a functor" $ do
pending
` shouldBe ` Just " Something serious . HEY GUYS "
fmap ( + + " HEY GUYS " ) _ _ _ ` shouldBe ` Nothing
fmap ( * 2 ) _ _ _ ` shouldBe ` Just 400
fmap ( * 3 ) _ _ _ ` shouldBe ` Nothing
it "works with our Tree type class" $ do
pending
let nums = [ 20,28,12 ]
fmap ( * 2 ) _ _ _ ` shouldBe ` EmptyTree
` shouldBe ` numsTree
|
bdc624d62011f8a51d74e894f8cb1915536e0cbee575e41dadc23f293fdadf6f | composewell/streaming-benchmarks | ByteString.hs | -- |
-- Module : Benchmarks.ByteString
Copyright : ( c ) 2018
--
License : MIT
-- Maintainer :
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Benchmarks.ByteString where
import Benchmarks.DefaultMain (defaultMain)
import Benchmarks . Common ( value , maxValue , )
import Prelude (Int, (+), ($), (.), even, (>), (<=), subtract, undefined,
maxBound, Maybe(..))
import qualified Prelude as P
import Data.Word (Word8)
import qualified Data.ByteString as S
nElements, nAppends :: Int
nElements = 1000000
nAppends = 10000
minElem, maxElem :: Word8
minElem = 1
maxElem = maxBound
-------------------------------------------------------------------------------
-- Stream generation and elimination
-------------------------------------------------------------------------------
type Element = Word8
type Stream a = S.ByteString
# INLINE sourceN #
sourceN :: Int -> Int -> Stream Element
sourceN count begin = S.unfoldr step begin
where
step i =
if i > begin + count
then Nothing
else (Just (P.fromIntegral i, i + 1))
# INLINE source #
source :: Int -> Stream Element
source = sourceN nElements
-------------------------------------------------------------------------------
-- Append
-------------------------------------------------------------------------------
# INLINE appendSourceR #
appendSourceR :: Int -> Stream Element
appendSourceR n = P.foldr (S.append) S.empty (P.map (S.singleton . P.fromIntegral) [n..n+nAppends])
# INLINE appendSourceL #
appendSourceL :: Int -> Stream Element
appendSourceL n = P.foldl (S.append) S.empty (P.map (S.singleton . P.fromIntegral) [n..n+nAppends])
-------------------------------------------------------------------------------
-- Elimination
-------------------------------------------------------------------------------
-- Using NFData for evaluation may be fraught with problems because of a
non - optimal implementation of NFData instance . So we just evaluate each
-- element of the stream using a fold.
# INLINE eval #
eval :: Stream a -> ()
eval = S.foldr P.seq ()
-- eval foldable
# INLINE evalF #
evalF :: P.Foldable t => t a -> ()
evalF = P.foldr P.seq ()
# INLINE toNull #
toNull :: Stream Element -> ()
toNull = eval
# INLINE toList #
toList :: Stream Element -> ()
toList = evalF . S.unpack
{-# INLINE foldl #-}
foldl :: Stream Element -> Element
foldl = S.foldl' (+) 0
# INLINE last #
last :: Stream Element -> Element
last = S.last
-------------------------------------------------------------------------------
-- Transformation
-------------------------------------------------------------------------------
# INLINE transform #
transform :: Stream a -> ()
transform = eval
# INLINE composeN #
composeN :: Int
-> (Stream Element -> Stream Element)
-> Stream Element
-> ()
composeN n f =
case n of
1 -> transform . f
2 -> transform . f . f
3 -> transform . f . f . f
4 -> transform . f . f . f . f
_ -> undefined
# INLINE scan #
# INLINE map #
# INLINE mapM #
# INLINE filterEven #
# INLINE filterAllOut #
# INLINE filterAllIn #
# INLINE takeOne #
# INLINE takeAll #
# INLINE takeWhileTrue #
# INLINE dropOne #
# INLINE dropAll #
# INLINE dropWhileTrue #
# INLINE dropWhileFalse #
scan, map, mapM,
filterEven, filterAllOut, filterAllIn,
takeOne, takeAll, takeWhileTrue,
dropOne, dropAll, dropWhileTrue, dropWhileFalse
:: Int -> Stream Int -> ()
XXX there is no '
scan n = composeN n $ S.scanl (+) 0
map n = composeN n $ S.map (+1)
mapM = map
filterEven n = composeN n $ S.filter even
filterAllOut n = composeN n $ S.filter (> maxElem)
filterAllIn n = composeN n $ S.filter (<= maxElem)
takeOne n = composeN n $ S.take 1
takeAll n = composeN n $ S.take nElements
takeWhileTrue n = composeN n $ S.takeWhile (<= maxElem)
dropOne n = composeN n $ S.drop 1
dropAll n = composeN n $ S.drop nElements
dropWhileFalse n = composeN n $ S.dropWhile (> maxElem)
dropWhileTrue n = composeN n $ S.dropWhile (<= maxElem)
-------------------------------------------------------------------------------
-- Iteration
-------------------------------------------------------------------------------
iterStreamLen, maxIters :: Int
iterStreamLen = 10
maxIters = 100000
# INLINE iterateSource #
iterateSource :: (Stream Element -> Stream Element)
-> Int
-> Int
-> Stream Element
iterateSource g i n = f i (sourceN iterStreamLen n)
where
f (0 :: Int) m = g m
f x m = g (f (x P.- 1) m)
# INLINE iterateScan #
# INLINE iterateFilterEven #
# INLINE iterateTakeAll #
# INLINE iterateDropOne #
{-# INLINE iterateDropWhileFalse #-}
# INLINE iterateDropWhileTrue #
iterateScan, iterateFilterEven, iterateTakeAll, iterateDropOne,
iterateDropWhileFalse, iterateDropWhileTrue :: Int -> Stream Element
-- this is quadratic
XXX using instead of '
iterateScan n = iterateSource (S.scanl (+) 0) (maxIters `P.div` 100) n
iterateDropWhileFalse n =
iterateSource (S.dropWhile (> maxElem)) (maxIters `P.div` 100) n
iterateFilterEven n = iterateSource (S.filter even) maxIters n
iterateTakeAll n = iterateSource (S.take nElements) maxIters n
iterateDropOne n = iterateSource (S.drop 1) maxIters n
iterateDropWhileTrue n = iterateSource (S.dropWhile (<= maxElem)) maxIters n
-------------------------------------------------------------------------------
-- Mixed Composition
-------------------------------------------------------------------------------
# INLINE scanMap #
# INLINE dropMap #
# INLINE dropScan #
# INLINE takeDrop #
# INLINE takeScan #
# INLINE takeMap #
{-# INLINE filterDrop #-}
{-# INLINE filterTake #-}
# INLINE filterScan #
{-# INLINE filterMap #-}
scanMap, dropMap, dropScan, takeDrop, takeScan, takeMap, filterDrop,
filterTake, filterScan, filterMap
:: Int -> Stream Element -> ()
XXX using instead of '
scanMap n = composeN n $ S.map (subtract 1) . S.scanl (+) 0
dropMap n = composeN n $ S.map (subtract 1) . S.drop 1
dropScan n = composeN n $ S.scanl (+) 0 . S.drop 1
takeDrop n = composeN n $ S.drop 1 . S.take nElements
takeScan n = composeN n $ S.scanl (+) 0 . S.take nElements
takeMap n = composeN n $ S.map (subtract 1) . S.take nElements
filterDrop n = composeN n $ S.drop 1 . S.filter (<= maxElem)
filterTake n = composeN n $ S.take nElements . S.filter (<= maxElem)
filterScan n = composeN n $ S.scanl (+) 0 . S.filter (<= maxElem)
filterMap n = composeN n $ S.map (subtract 1) . S.filter (<= maxElem)
-------------------------------------------------------------------------------
-- Zipping and concat
-------------------------------------------------------------------------------
# INLINE zip #
zip :: Stream Element -> ()
zip src = P.foldr (\(x,y) xs -> P.seq x (P.seq y xs)) ()
$ S.zipWith (,) src src
# INLINE concatMap #
concatMap :: Stream Element -> ()
concatMap src = transform $ (S.concatMap (S.replicate 3) src)
main :: P.IO ()
main = $(defaultMain "ByteString")
| null | https://raw.githubusercontent.com/composewell/streaming-benchmarks/c31fa9d2d20c9b4e8e85be19ac1e7a41a88b4945/Benchmarks/ByteString.hs | haskell | |
Module : Benchmarks.ByteString
Maintainer :
-----------------------------------------------------------------------------
Stream generation and elimination
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Append
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Elimination
-----------------------------------------------------------------------------
Using NFData for evaluation may be fraught with problems because of a
element of the stream using a fold.
eval foldable
# INLINE foldl #
-----------------------------------------------------------------------------
Transformation
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Iteration
-----------------------------------------------------------------------------
# INLINE iterateDropWhileFalse #
this is quadratic
-----------------------------------------------------------------------------
Mixed Composition
-----------------------------------------------------------------------------
# INLINE filterDrop #
# INLINE filterTake #
# INLINE filterMap #
-----------------------------------------------------------------------------
Zipping and concat
----------------------------------------------------------------------------- | Copyright : ( c ) 2018
License : MIT
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Benchmarks.ByteString where
import Benchmarks.DefaultMain (defaultMain)
import Benchmarks . Common ( value , maxValue , )
import Prelude (Int, (+), ($), (.), even, (>), (<=), subtract, undefined,
maxBound, Maybe(..))
import qualified Prelude as P
import Data.Word (Word8)
import qualified Data.ByteString as S
nElements, nAppends :: Int
nElements = 1000000
nAppends = 10000
minElem, maxElem :: Word8
minElem = 1
maxElem = maxBound
type Element = Word8
type Stream a = S.ByteString
# INLINE sourceN #
sourceN :: Int -> Int -> Stream Element
sourceN count begin = S.unfoldr step begin
where
step i =
if i > begin + count
then Nothing
else (Just (P.fromIntegral i, i + 1))
# INLINE source #
source :: Int -> Stream Element
source = sourceN nElements
# INLINE appendSourceR #
appendSourceR :: Int -> Stream Element
appendSourceR n = P.foldr (S.append) S.empty (P.map (S.singleton . P.fromIntegral) [n..n+nAppends])
# INLINE appendSourceL #
appendSourceL :: Int -> Stream Element
appendSourceL n = P.foldl (S.append) S.empty (P.map (S.singleton . P.fromIntegral) [n..n+nAppends])
non - optimal implementation of NFData instance . So we just evaluate each
# INLINE eval #
eval :: Stream a -> ()
eval = S.foldr P.seq ()
# INLINE evalF #
evalF :: P.Foldable t => t a -> ()
evalF = P.foldr P.seq ()
# INLINE toNull #
toNull :: Stream Element -> ()
toNull = eval
# INLINE toList #
toList :: Stream Element -> ()
toList = evalF . S.unpack
foldl :: Stream Element -> Element
foldl = S.foldl' (+) 0
# INLINE last #
last :: Stream Element -> Element
last = S.last
# INLINE transform #
transform :: Stream a -> ()
transform = eval
# INLINE composeN #
composeN :: Int
-> (Stream Element -> Stream Element)
-> Stream Element
-> ()
composeN n f =
case n of
1 -> transform . f
2 -> transform . f . f
3 -> transform . f . f . f
4 -> transform . f . f . f . f
_ -> undefined
# INLINE scan #
# INLINE map #
# INLINE mapM #
# INLINE filterEven #
# INLINE filterAllOut #
# INLINE filterAllIn #
# INLINE takeOne #
# INLINE takeAll #
# INLINE takeWhileTrue #
# INLINE dropOne #
# INLINE dropAll #
# INLINE dropWhileTrue #
# INLINE dropWhileFalse #
scan, map, mapM,
filterEven, filterAllOut, filterAllIn,
takeOne, takeAll, takeWhileTrue,
dropOne, dropAll, dropWhileTrue, dropWhileFalse
:: Int -> Stream Int -> ()
XXX there is no '
scan n = composeN n $ S.scanl (+) 0
map n = composeN n $ S.map (+1)
mapM = map
filterEven n = composeN n $ S.filter even
filterAllOut n = composeN n $ S.filter (> maxElem)
filterAllIn n = composeN n $ S.filter (<= maxElem)
takeOne n = composeN n $ S.take 1
takeAll n = composeN n $ S.take nElements
takeWhileTrue n = composeN n $ S.takeWhile (<= maxElem)
dropOne n = composeN n $ S.drop 1
dropAll n = composeN n $ S.drop nElements
dropWhileFalse n = composeN n $ S.dropWhile (> maxElem)
dropWhileTrue n = composeN n $ S.dropWhile (<= maxElem)
iterStreamLen, maxIters :: Int
iterStreamLen = 10
maxIters = 100000
# INLINE iterateSource #
iterateSource :: (Stream Element -> Stream Element)
-> Int
-> Int
-> Stream Element
iterateSource g i n = f i (sourceN iterStreamLen n)
where
f (0 :: Int) m = g m
f x m = g (f (x P.- 1) m)
# INLINE iterateScan #
# INLINE iterateFilterEven #
# INLINE iterateTakeAll #
# INLINE iterateDropOne #
# INLINE iterateDropWhileTrue #
iterateScan, iterateFilterEven, iterateTakeAll, iterateDropOne,
iterateDropWhileFalse, iterateDropWhileTrue :: Int -> Stream Element
XXX using instead of '
iterateScan n = iterateSource (S.scanl (+) 0) (maxIters `P.div` 100) n
iterateDropWhileFalse n =
iterateSource (S.dropWhile (> maxElem)) (maxIters `P.div` 100) n
iterateFilterEven n = iterateSource (S.filter even) maxIters n
iterateTakeAll n = iterateSource (S.take nElements) maxIters n
iterateDropOne n = iterateSource (S.drop 1) maxIters n
iterateDropWhileTrue n = iterateSource (S.dropWhile (<= maxElem)) maxIters n
# INLINE scanMap #
# INLINE dropMap #
# INLINE dropScan #
# INLINE takeDrop #
# INLINE takeScan #
# INLINE takeMap #
# INLINE filterScan #
scanMap, dropMap, dropScan, takeDrop, takeScan, takeMap, filterDrop,
filterTake, filterScan, filterMap
:: Int -> Stream Element -> ()
XXX using instead of '
scanMap n = composeN n $ S.map (subtract 1) . S.scanl (+) 0
dropMap n = composeN n $ S.map (subtract 1) . S.drop 1
dropScan n = composeN n $ S.scanl (+) 0 . S.drop 1
takeDrop n = composeN n $ S.drop 1 . S.take nElements
takeScan n = composeN n $ S.scanl (+) 0 . S.take nElements
takeMap n = composeN n $ S.map (subtract 1) . S.take nElements
filterDrop n = composeN n $ S.drop 1 . S.filter (<= maxElem)
filterTake n = composeN n $ S.take nElements . S.filter (<= maxElem)
filterScan n = composeN n $ S.scanl (+) 0 . S.filter (<= maxElem)
filterMap n = composeN n $ S.map (subtract 1) . S.filter (<= maxElem)
# INLINE zip #
zip :: Stream Element -> ()
zip src = P.foldr (\(x,y) xs -> P.seq x (P.seq y xs)) ()
$ S.zipWith (,) src src
# INLINE concatMap #
concatMap :: Stream Element -> ()
concatMap src = transform $ (S.concatMap (S.replicate 3) src)
main :: P.IO ()
main = $(defaultMain "ByteString")
|
1d7a705ae75bd17a7599c8fd5be66259359f0b8d77d72c4d8ca1ed066f460b08 | glguy/advent | 08.hs | # Language ImportQualifiedPost , QuasiQuotes , TemplateHaskell #
|
Module : Main
Description : Day 8 solution
Copyright : ( c ) , 2020
License : ISC
Maintainer :
< >
Module : Main
Description : Day 8 solution
Copyright : (c) Eric Mertens, 2020
License : ISC
Maintainer :
<>
-}
module Main (main) where
import Advent (format, stageTH)
import Data.IntMap (IntMap)
import Data.IntMap qualified as IntMap
-- | Programs are expressed as control-flow graphs.
--
-- Nodes are instructions in the program.
--
-- Nodes are labeled with the accumulator-effect of executing that instruction.
--
-- Edges capture control flow between instructions.
--
-- Edges are labeled with the /cost/ of taking that edge. It costs @1@ to
-- take a control path generated from a toggled instruction.
data O = Onop | Ojmp | Oacc
stageTH
------------------------------------------------------------------------
-- |
-- >>> :main
1200
1023
main :: IO ()
main =
do inp <- [format|2020 8 (@O (|%+)%d%n)*|]
let pgm = IntMap.fromList (zip [0..] inp)
print (snd (part1 pgm 0 0))
print (part2 pgm 0 0)
part1 :: IntMap (O, Int) -> Int -> Int -> (Int,Int)
part1 pgm ip acc =
let continue = part1 (IntMap.delete ip pgm) in
case IntMap.lookup ip pgm of
Nothing -> (ip, acc)
Just (Onop, _) -> continue (ip+1) acc
Just (Oacc, n) -> continue (ip+1) (acc+n)
Just (Ojmp, n) -> continue (ip+n) acc
part2 :: IntMap (O, Int) -> Int -> Int -> Int
part2 pgm ip acc =
case pgm IntMap.! ip of
(Onop, n) -> try (part1 pgm (ip+n) acc) (part2 pgm (ip+1) acc)
(Ojmp, n) -> try (part1 pgm (ip+1) acc) (part2 pgm (ip+n) acc)
(Oacc, n) -> part2 pgm (ip+1) (acc+n)
where
try (ip', acc') e
| ip' == IntMap.size pgm = acc'
| otherwise = e
| null | https://raw.githubusercontent.com/glguy/advent/d72f6fec89c1a57d90345ffa185fc8dbd3e2d595/solutions/src/2020/08.hs | haskell | | Programs are expressed as control-flow graphs.
Nodes are instructions in the program.
Nodes are labeled with the accumulator-effect of executing that instruction.
Edges capture control flow between instructions.
Edges are labeled with the /cost/ of taking that edge. It costs @1@ to
take a control path generated from a toggled instruction.
----------------------------------------------------------------------
|
>>> :main | # Language ImportQualifiedPost , QuasiQuotes , TemplateHaskell #
|
Module : Main
Description : Day 8 solution
Copyright : ( c ) , 2020
License : ISC
Maintainer :
< >
Module : Main
Description : Day 8 solution
Copyright : (c) Eric Mertens, 2020
License : ISC
Maintainer :
<>
-}
module Main (main) where
import Advent (format, stageTH)
import Data.IntMap (IntMap)
import Data.IntMap qualified as IntMap
data O = Onop | Ojmp | Oacc
stageTH
1200
1023
main :: IO ()
main =
do inp <- [format|2020 8 (@O (|%+)%d%n)*|]
let pgm = IntMap.fromList (zip [0..] inp)
print (snd (part1 pgm 0 0))
print (part2 pgm 0 0)
part1 :: IntMap (O, Int) -> Int -> Int -> (Int,Int)
part1 pgm ip acc =
let continue = part1 (IntMap.delete ip pgm) in
case IntMap.lookup ip pgm of
Nothing -> (ip, acc)
Just (Onop, _) -> continue (ip+1) acc
Just (Oacc, n) -> continue (ip+1) (acc+n)
Just (Ojmp, n) -> continue (ip+n) acc
part2 :: IntMap (O, Int) -> Int -> Int -> Int
part2 pgm ip acc =
case pgm IntMap.! ip of
(Onop, n) -> try (part1 pgm (ip+n) acc) (part2 pgm (ip+1) acc)
(Ojmp, n) -> try (part1 pgm (ip+1) acc) (part2 pgm (ip+n) acc)
(Oacc, n) -> part2 pgm (ip+1) (acc+n)
where
try (ip', acc') e
| ip' == IntMap.size pgm = acc'
| otherwise = e
|
b92177afaad53a9ace88977fd369810a5c0af955fd9897588601e38849263e57 | higepon/mcbench | mcbench_util_SUITE.erl | %%%-------------------------------------------------------------------
File :
Author : >
%%% Description : Tests for mcbench utilities
%%%
Created : 7 Dec 2009 by >
%%%-------------------------------------------------------------------
-module(mcbench_util_SUITE).
-compile(export_all).
-include("ct.hrl").
suite() ->
[{timetrap,{seconds,30}}].
%% Tests start.
test_gen_random_keys(_Config) ->
N = 10000,
MaxKey = 100000,
Keys = mcbench_util:gen_random_keys(N, MaxKey),
true = is_list(Keys),
N = length(Keys),
is_unique_list(Keys),
lists:all(fun(X) -> X =< MaxKey end, Keys),
ok.
%% Tests end.
all() ->
[
test_gen_random_keys
].
%% helper
is_unique_list(List) ->
GBSet = gb_sets:from_list(List),
UList = gb_sets:to_list(GBSet),
length(List) =:= length(UList).
| null | https://raw.githubusercontent.com/higepon/mcbench/72a58cfeaef846d1d26dd8f311ff5ed5ed23382b/test/mcbench_util_SUITE.erl | erlang | -------------------------------------------------------------------
Description : Tests for mcbench utilities
-------------------------------------------------------------------
Tests start.
Tests end.
helper | File :
Author : >
Created : 7 Dec 2009 by >
-module(mcbench_util_SUITE).
-compile(export_all).
-include("ct.hrl").
suite() ->
[{timetrap,{seconds,30}}].
test_gen_random_keys(_Config) ->
N = 10000,
MaxKey = 100000,
Keys = mcbench_util:gen_random_keys(N, MaxKey),
true = is_list(Keys),
N = length(Keys),
is_unique_list(Keys),
lists:all(fun(X) -> X =< MaxKey end, Keys),
ok.
all() ->
[
test_gen_random_keys
].
is_unique_list(List) ->
GBSet = gb_sets:from_list(List),
UList = gb_sets:to_list(GBSet),
length(List) =:= length(UList).
|
e5ed933500f715319a483319c84f6c8d8adf7e02510d701a53a2a74a8dc2ec58 | Elzair/nazghul | place-to-place-1.scm | (load "naz.scm")
(kern-load "game.scm")
(load "tests/basic-time.scm")
(load "tests/test-map-1.scm")
(kern-mk-map
'm_grass_map 5 5 pal_expanded
(list
"xx xx .. .. .."
"xx .. .. .. .."
".. .. .. .. .."
".. .. .. .. .."
".. .. .. .. .."
))
(kern-mk-char 'ch_thorald_greybeard
"Thorald Greybeard"
sp_human
oc_wizard
s_companion_wizard
3
20 30 22
0 1
10 5
0 0
0 0
39 0
240 8
nil
nil
nil
(list
t_rpg
))
(kern-mk-char 'ch_slurmok ; tag
"Slurmok" ; name
sp_yellow_slime ; species
oc_wizard ; occ
s_yellow_slime ; sprite
faction-player ; starting alignment
str / int / dex
0 1 ; hp mod/mult
10 5 ; mp mod/mult
240 0 5 7 ; hp/xp/mp/lvl
'conv-b ; conv
nil ; sched
nil ; special ai
(list t_dagger)) ; readied
(kern-mk-place 'p_test2
"Underplace"
nil ; sprite
m_grass_map
#f ;; wraps
#t ;; underground
#f ;; wilderness
#f ;; tmp combat place
nil ;; subplaces
nil ;; neighbors
;; objects
(list
(list (mk-ladder-up 'p_test 4 12) 2 2)
)
nil ;; hooks
)
(kern-mk-place 'p_test
"Test Place"
nil ; sprite
m_test_1
#f ;; wraps
#f ;; underground
#f ;; wilderness
#f ;; tmp combat place
nil ;; subplaces
nil ;; neighbors
;; objects:
(list
(list (mk-door) 4 11)
(list (mk-door) 5 12)
(list (mk-ladder-down 'p_test2 2 2) 4 12)
(list (kern-mk-char 'ch_shroom ; tag
"Shroom" ; name
sp_human ; species
oc_druid ; occ
s_companion_druid ; sprite
faction-men ; starting alignment
str / int / dex
0 0 ; hp mod/mult
0 0 ; mp mod/mult
30 0 9 9 ; hp/xp/mp/lvl
nil ; conv
nil ; sched
nil ; special ai
(list t_dagger)) ; readied
9 9)
(list (kern-mk-char 'ch_olin ; tag
"Olin the Ghast" ; name
sp_ghast ; species
nil ; occ
s_ghost ; sprite
faction-men ; starting alignment
str / int / dex
0 1 ; hp mod/mult
10 5 ; mp mod/mult
240 0 8 8 ; hp/xp/mp/lvl
nil ; conv
nil ; sched
nil ; special ai
nil) ; readied
8 9)
)
nil ;; hooks
)
(kern-mk-player 'player ; tag
s_companion_fighter ; sprite
"Walk" ; movement description
sound-walking ; movement sound
1000 ; food
500 ; gold
nil ; formation
nil ; campsite map
nil ; campsite formation
nil ; vehicle
;; inventory
(kern-mk-container
nil ;; type
nil ;; trap
nil ;; contents:
)
nil ;; party members
)
(kern-party-add-member player ch_olin)
(kern-party-add-member player ch_shroom)
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.001/tests/place-to-place-1.scm | scheme | tag
name
species
occ
sprite
starting alignment
hp mod/mult
mp mod/mult
hp/xp/mp/lvl
conv
sched
special ai
readied
sprite
wraps
underground
wilderness
tmp combat place
subplaces
neighbors
objects
hooks
sprite
wraps
underground
wilderness
tmp combat place
subplaces
neighbors
objects:
tag
name
species
occ
sprite
starting alignment
hp mod/mult
mp mod/mult
hp/xp/mp/lvl
conv
sched
special ai
readied
tag
name
species
occ
sprite
starting alignment
hp mod/mult
mp mod/mult
hp/xp/mp/lvl
conv
sched
special ai
readied
hooks
tag
sprite
movement description
movement sound
food
gold
formation
campsite map
campsite formation
vehicle
inventory
type
trap
contents:
party members | (load "naz.scm")
(kern-load "game.scm")
(load "tests/basic-time.scm")
(load "tests/test-map-1.scm")
(kern-mk-map
'm_grass_map 5 5 pal_expanded
(list
"xx xx .. .. .."
"xx .. .. .. .."
".. .. .. .. .."
".. .. .. .. .."
".. .. .. .. .."
))
(kern-mk-char 'ch_thorald_greybeard
"Thorald Greybeard"
sp_human
oc_wizard
s_companion_wizard
3
20 30 22
0 1
10 5
0 0
0 0
39 0
240 8
nil
nil
nil
(list
t_rpg
))
str / int / dex
(kern-mk-place 'p_test2
"Underplace"
m_grass_map
(list
(list (mk-ladder-up 'p_test 4 12) 2 2)
)
)
(kern-mk-place 'p_test
"Test Place"
m_test_1
(list
(list (mk-door) 4 11)
(list (mk-door) 5 12)
(list (mk-ladder-down 'p_test2 2 2) 4 12)
str / int / dex
9 9)
str / int / dex
8 9)
)
)
(kern-mk-container
)
)
(kern-party-add-member player ch_olin)
(kern-party-add-member player ch_shroom)
|
196ba0dd4cc15dfce1f133e8dedac2f32489121c27950ac206aff3d1047b0aac | bendoerr/real-world-haskell | Arrays.hs | -- | Various Array specific Helpers for this chapter.
module Arrays where
import Data.Array (Array, elems, listArray)
import Data.List (foldl')
import Data.Ix (Ix(..))
-- | Helper to create an Array out of a List
listToArray :: [a] -> Array Int a
listToArray xs = listArray (0, bound) xs
where bound = length xs - 1
-- | Strict left fold, similar to foldl' on lists.
foldA :: Ix k => (a -> b -> a) -> a -> Array k b -> a
foldA f s = foldl' f s . elems
| Strict left fold using the first element of the array as its starting
value , similar to foldl1 on lists .
foldA1 :: Ix k => (a -> a -> a) -> Array k a -> a
foldA1 f = foldl1 f . elems
| null | https://raw.githubusercontent.com/bendoerr/real-world-haskell/fa43aa59e42a162f5d2d5655b274b964ebeb8f0a/ch12/Arrays.hs | haskell | | Various Array specific Helpers for this chapter.
| Helper to create an Array out of a List
| Strict left fold, similar to foldl' on lists. | module Arrays where
import Data.Array (Array, elems, listArray)
import Data.List (foldl')
import Data.Ix (Ix(..))
listToArray :: [a] -> Array Int a
listToArray xs = listArray (0, bound) xs
where bound = length xs - 1
foldA :: Ix k => (a -> b -> a) -> a -> Array k b -> a
foldA f s = foldl' f s . elems
| Strict left fold using the first element of the array as its starting
value , similar to foldl1 on lists .
foldA1 :: Ix k => (a -> a -> a) -> Array k a -> a
foldA1 f = foldl1 f . elems
|
3ea85356fec62218946e4bb1a2a3769ef1820486bfc04b54aef2b8339f82f53e | NicklasBoto/funQ | Abs.hs | Haskell data types for the abstract syntax .
Generated by the BNF converter .
# LANGUAGE GeneralizedNewtypeDeriving #
module Parser.Abs where
import Prelude (Char, Double, Integer, String)
import qualified Prelude as C (Eq, Ord, Show, Read)
import qualified Data.String
newtype FunVar = FunVar String
deriving (C.Eq, C.Ord, C.Show, C.Read, Data.String.IsString)
newtype Var = Var String
deriving (C.Eq, C.Ord, C.Show, C.Read, Data.String.IsString)
newtype GateIdent = GateIdent String
deriving (C.Eq, C.Ord, C.Show, C.Read, Data.String.IsString)
newtype Lambda = Lambda String
deriving (C.Eq, C.Ord, C.Show, C.Read, Data.String.IsString)
data Program = PDef [FunDec]
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Term
= TVar Var
| TBit Bit
| TGate Gate
| TTup Tup
| TStar
| TApp Term Term
| TIfEl Term Term Term
| TLet LetVar [LetVar] Term Term
| TLamb Lambda FunVar Type Term
| TDolr Term Term
deriving (C.Eq, C.Ord, C.Show, C.Read)
data LetVar = LVar Var
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Tup = Tuple Term [Term]
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Bit = BBit Integer
deriving (C.Eq, C.Ord, C.Show, C.Read)
data FunDec = FDecl FunVar Type Function
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Function = FDef Var [Arg] Term
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Arg = FArg Var
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Type
= TypeBit
| TypeQbit
| TypeUnit
| TypeDup Type
| TypeTens Type Type
| TypeFunc Type Type
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Gate
= GH
| GX
| GY
| GZ
| GI
| GS
| GT
| GCNOT
| GTOF
| GSWP
| GFRDK
| GIdent GateIdent
deriving (C.Eq, C.Ord, C.Show, C.Read)
| null | https://raw.githubusercontent.com/NicklasBoto/funQ/7692abfbb914c07ccb1050b952af1d539604f152/src/Parser/Abs.hs | haskell | Haskell data types for the abstract syntax .
Generated by the BNF converter .
# LANGUAGE GeneralizedNewtypeDeriving #
module Parser.Abs where
import Prelude (Char, Double, Integer, String)
import qualified Prelude as C (Eq, Ord, Show, Read)
import qualified Data.String
newtype FunVar = FunVar String
deriving (C.Eq, C.Ord, C.Show, C.Read, Data.String.IsString)
newtype Var = Var String
deriving (C.Eq, C.Ord, C.Show, C.Read, Data.String.IsString)
newtype GateIdent = GateIdent String
deriving (C.Eq, C.Ord, C.Show, C.Read, Data.String.IsString)
newtype Lambda = Lambda String
deriving (C.Eq, C.Ord, C.Show, C.Read, Data.String.IsString)
data Program = PDef [FunDec]
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Term
= TVar Var
| TBit Bit
| TGate Gate
| TTup Tup
| TStar
| TApp Term Term
| TIfEl Term Term Term
| TLet LetVar [LetVar] Term Term
| TLamb Lambda FunVar Type Term
| TDolr Term Term
deriving (C.Eq, C.Ord, C.Show, C.Read)
data LetVar = LVar Var
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Tup = Tuple Term [Term]
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Bit = BBit Integer
deriving (C.Eq, C.Ord, C.Show, C.Read)
data FunDec = FDecl FunVar Type Function
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Function = FDef Var [Arg] Term
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Arg = FArg Var
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Type
= TypeBit
| TypeQbit
| TypeUnit
| TypeDup Type
| TypeTens Type Type
| TypeFunc Type Type
deriving (C.Eq, C.Ord, C.Show, C.Read)
data Gate
= GH
| GX
| GY
| GZ
| GI
| GS
| GT
| GCNOT
| GTOF
| GSWP
| GFRDK
| GIdent GateIdent
deriving (C.Eq, C.Ord, C.Show, C.Read)
|
|
30618f3402fb8b7bdb0b670bd0d07076e1fef9e29aaec1b2faa67c23673ea117 | pveber/bistro | deeptools.ml | open Core
open Bistro
open Bistro.Shell_dsl
let img = [ docker_image ~account:"pveber" ~name:"deeptools" ~tag:"3.1.3" () ]
type 'a signal_format = [ `bigWig | `bedGraph ]
type 'a img_format = [ `png | `pdf | ` svg ]
class type compressed_numpy_array = object
inherit binary_file
method format : [`compressed_numpy_array]
end
let bigwig = `bigWig
let bedgraph = `bedGraph
let png = `png
let pdf = `pdf
let svg = `svg
let ext_of_format = function
| `png -> "png"
| `pdf -> "pdf"
| `svg -> "svg"
let file_format_expr = function
| `bigWig -> string "bigwig"
| `bedGraph -> string "bedgraph"
let filterRNAstrand_expr = function
| `forward -> string "forward"
| `reverse -> string "reverse"
let scalefactormethod_expr = function
| `readcount -> string "readCount"
| `ses -> string "SES"
let ratio_expr = function
| `log2 -> string "log2"
| `ratio -> string "ratio"
| `subtract -> string "subtract"
| `add -> string "add"
| `mean -> string "mean"
| `reciprocal_ratio -> string "reciprocal_ratio"
| `first -> string "first"
| `second -> string "second"
let slist f x = list ~sep:" " f x
let dep_list xs = slist dep xs
let normalization_method_expr = function
| `RPKM -> string "RPKM"
| `CPM -> string "CPM"
| `BPM -> string "BPM"
| `RPGC -> string "RPGC"
let bam_gen_cmd ?outfileformat ?scalefactor ?blacklist
?centerreads ?normalizeUsing ?ignorefornormalization ?skipnoncoveredregions
?smoothlength ?extendreads ?ignoreduplicates ?minmappingquality
?samflaginclude ?samflagexclude ?minfragmentlength ?maxfragmentlength
cmd_name other_args =
cmd cmd_name (
List.append [
option (opt "--outFileFormat" file_format_expr) outfileformat ;
option (opt "--scaleFactor" float) scalefactor ;
option (opt "--blackListFileName" dep) blacklist ;
option (opt "--normalizeUsing" normalization_method_expr) normalizeUsing ;
option (opt "--ignoreForNormalization" (list string ~sep:" ")) ignorefornormalization ;
option (flag string "--skipNonCoveredRegions") skipnoncoveredregions ;
option (opt "--smoothLength" int) smoothlength ;
option (opt "--extendReads" int) extendreads ;
option (flag string "--ignoreDuplicates") ignoreduplicates ;
option (opt "--minMappingQuality" int) minmappingquality ;
option (flag string "--centerReads") centerreads ;
option (opt "--samFlagInclude" int) samflaginclude ;
option (opt "--samFlagExclude" int) samflagexclude ;
option (opt "--minFragmentLength" int) minfragmentlength ;
option (opt "--maxfragmentLength" int) maxfragmentlength ;
]
other_args
)
let bamcoverage ?scalefactor ?filterrnastrand ?binsize ?blacklist
?(threads = 1) ?normalizeUsing ?ignorefornormalization
?skipnoncoveredregions ?smoothlength ?extendreads ?ignoreduplicates
?minmappingquality ?centerreads ?samflaginclude ?samflagexclude
?minfragmentlength ?maxfragmentlength outfileformat indexed_bam =
Workflow.shell ~descr:"bamcoverage" ~img ~np:threads [
bam_gen_cmd "bamCoverage" ?scalefactor ?blacklist
?normalizeUsing ?ignorefornormalization
?skipnoncoveredregions ?smoothlength ?extendreads ?ignoreduplicates
?minmappingquality ?centerreads ?samflaginclude ?samflagexclude
?minfragmentlength ?maxfragmentlength [
option (opt "--filterRNAstrand" filterRNAstrand_expr) filterrnastrand ;
option (opt "--binSize" int) binsize ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bam" Fn.id (dep (Samtools.indexed_bam_to_bam indexed_bam)) ;
opt "--outFileName" Fn.id dest ;
opt "--outFileFormat" file_format_expr outfileformat ;
]
]
let bamcompare ?scalefactormethod ?samplelength ?numberofsamples
?scalefactor ?ratio ?pseudocount ?binsize ?region ?blacklist ?(threads = 1)
?normalizeUsing ?ignorefornormalization ?skipnoncoveredregions
?smoothlength ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength outfileformat indexed_bam1 indexed_bam2 =
Workflow.shell ~descr:"bamcompare" ~img ~np:threads [
bam_gen_cmd "bamCompare"
?scalefactor ?blacklist
?normalizeUsing ?ignorefornormalization ?skipnoncoveredregions
?smoothlength ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength [
option (opt "--scaleFactorMethod" scalefactormethod_expr) scalefactormethod ;
option (opt "--sampleLength" int) samplelength ;
option (opt "--numberOfSamples" int) numberofsamples ;
option (opt "--ratio" ratio_expr) ratio ;
option (opt "--pseudocount" int) pseudocount ;
option (opt "--binSize" int) binsize ;
option (opt "--region" string) region ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bamfile1" Fn.id (dep (Samtools.indexed_bam_to_bam indexed_bam1)) ;
opt "--bamfile2" Fn.id (dep (Samtools.indexed_bam_to_bam indexed_bam2)) ;
opt "--outFileName" Fn.id dest ;
opt "--outFileFormat" file_format_expr outfileformat ;
]
]
let bigwigcompare ?scalefactor ?ratio ?pseudocount ?binsize
?region ?blacklist ?(threads = 1)
outfileformat bigwig1 bigwig2 =
Workflow.shell ~descr:"bigwigcompare" ~img ~np:threads [
cmd "bigwigCompare" [
option (opt "--scaleFactor" float) scalefactor ;
option (opt "--ratio" ratio_expr) ratio ;
option (opt "--pseudocount" int) pseudocount ;
option (opt "--binSize" int) binsize ;
option (opt "--region" string) region ;
option (opt "--blackListFileName" dep) blacklist ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bigwig1" dep bigwig1 ;
opt "--bigwig2" dep bigwig2 ;
opt "--outFileName" Fn.id dest ;
opt "--outFileFormat" file_format_expr outfileformat ;
]
]
let multibamsum_gen_cmd ?outrawcounts ?extendreads ?ignoreduplicates
?minmappingquality ?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength ?blacklist ?region cmd_name other_args =
cmd cmd_name (
List.append [
option (opt "--region" string) region ;
option (flag string "--outRawCounts") outrawcounts ;
option (opt "--extendReads" int) extendreads ;
option (flag string "--ignoreDuplicates") ignoreduplicates ;
option (opt "--minMappingQuality" int) minmappingquality ;
option (flag string "--centerReads") centerreads ;
option (opt "--samFlagInclude" int) samflaginclude ;
option (opt "--samFlagExclude" int) samflagexclude ;
option (opt "--minFragmentLength" int) minfragmentlength ;
option (opt "--maxfragmentLength" int) maxfragmentlength ;
option (opt "--blackListFileName" dep) blacklist ;
]
other_args
)
let multibamsummary_bins ?binsize ?distancebetweenbins ?region ?blacklist
?(threads = 1) ?outrawcounts ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength indexed_bams =
Workflow.shell ~descr:"multibamsummary_bins" ~img ~np:threads [
multibamsum_gen_cmd "multiBamSummary bins"
?region ?blacklist
?outrawcounts ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength [
option (opt "--binSize" int) binsize ;
option (opt "--distanceBetweenBins" int) distancebetweenbins ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bamfiles" (list (fun bam -> dep (Samtools.indexed_bam_to_bam bam)) ~sep:" ") indexed_bams ;
opt "--outFileName" Fn.id dest ;
]
]
let multibamsummary_bed ?region ?blacklist ?(threads = 1)
?outrawcounts ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength ?metagene ?transcriptid ?exonid ?transcriptiddesignator bed
indexed_bams =
Workflow.shell ~descr:"multibamsummary_bed" ~img ~np:threads [
multibamsum_gen_cmd "multiBamSummary BED-file"
?region ?blacklist
?outrawcounts ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength [
option (flag string "--metagene") metagene ;
option (flag string "--transcriptID") transcriptid ;
option (flag string "--exonID") exonid ;
option (flag string "--transcript_id_designator") transcriptiddesignator ;
opt "--numberOfProcessors" Fn.id np ;
opt "--BED" dep bed ;
opt "--bamfiles"
(list (fun bam -> dep (Samtools.indexed_bam_to_bam bam)) ~sep:" ")
indexed_bams ;
opt "--outFileName" Fn.id dest ;
]
]
let multibigwigsummary_bed
?labels ?chromosomesToSkip ?region ?blacklist ?(threads = 1)
?metagene ?transcriptid ?exonid ?transcriptiddesignator
bed bigwigs =
let inner =
Workflow.shell ~descr:"multibigwigsummary_bed" ~img ~np:threads [
mkdir_p dest ;
cmd "multiBigwigSummary BED-file" [
option (opt "--labels" (list string ~sep:" ")) labels ;
option (opt "--chromosomesToSkip" (list string ~sep:" ")) chromosomesToSkip ;
option (opt "--region" string) region ;
option (opt "--blackListFileName" dep) blacklist ;
opt "--outRawCounts" Fn.id (dest // "summary.tsv") ;
option (flag string "--metagene") metagene ;
option (flag string "--transcriptID") transcriptid ;
option (flag string "--exonID") exonid ;
option (flag string "--transcript_id_designator") transcriptiddesignator ;
opt "--BED" dep bed ;
opt "--bwfiles" (list dep ~sep:" ") bigwigs ;
opt "--outFileName" Fn.id (dest // "summary.npy.gz") ;
]
]
in
let f x = Workflow.select inner [x] in
f "summary.npy.gz", f "summary.tsv"
let reference_point_enum x =
(match x with
| `TES -> "TES"
| `TSS -> "TSS"
| `center -> "center")
|> string
let sort_regions_enum x =
(match x with
| `no -> "no"
| `ascend -> "ascend"
| `descend -> "descend"
| `keep -> "keep")
|> string
let sort_using_enum x =
(match x with
| `max -> "max"
| `min -> "min"
| `mean -> "mean"
| `median -> "median"
| `region_length -> "region_length"
| `sum -> "sum")
|> string
let average_type_bins_enum x =
(match x with
| `max -> "max"
| `min -> "min"
| `mean -> "mean"
| `median -> "median"
| `std -> "std"
| `sum -> "sum"
)
|> string
let what_to_show_enum x =
(match x with
| `plot_heatmap_and_colorbar -> "plot, heatmap and colorbar"
| `plot_and_heatmap -> "plot and heatmap"
| `heatmap_only -> "heatmap only"
| `heatmap_and_colorbar -> "heatmap and colorbar"
)
|> string
let legend_location_enum x=
string @@ match x with
| `best-> "best"
| `upper_right-> "upper_right"
| `upper_left-> "upper_left"
| `upper_center-> "upper_center"
| `lower_left-> "lower_left"
| `lower_right-> "lower_right"
| `lower_center-> "lower_center"
| `center-> "center"
| `center_left-> "center_left"
| `center_right-> "center_right"
| `none -> "none"
class type deeptools_matrix = object
inherit binary_file
method format : [`deeptools_matrix]
end
let computeMatrix_reference_point
?referencePoint ?upstream ?downstream ?nanAfterEnd
?binSize ?sortRegions ?sortUsing ?sortUsingSamples
?averageTypeBins ?missingDataAsZero ?skipZeros
?minThreshold ?maxThreshold ?blackList ?scale
?(numberOfProcessors = 1) ~regions ~scores () =
Workflow.shell ~descr:"deeptools.computeMatrix_reference_point" ~img ~np:numberOfProcessors [
cmd "computeMatrix" [
string "reference-point" ;
option (opt "--referencePoint" reference_point_enum) referencePoint ;
option (opt "--upstream" int) upstream ;
option (opt "--downstream" int) downstream ;
option (flag string "--nanAfterEnd") nanAfterEnd ;
option (opt "--binSize" int) binSize ;
option (opt "--sortRegions" sort_regions_enum) sortRegions ;
option (opt "--sortUsing" sort_using_enum) sortUsing ;
option (opt "--sortUsingSamples" (slist int) ) sortUsingSamples ;
option (opt "--averageTypeBins" average_type_bins_enum) averageTypeBins ;
option (flag string "--missingDataAsZero") missingDataAsZero ;
option (flag string "--skipZeros") skipZeros ;
option (opt "--minThreshold" float) minThreshold ;
option (opt "--maxThreshold" float) maxThreshold ;
option (opt "--blackListFileName" dep) blackList ;
option (opt "--sc" float) scale ;
opt "--numberOfProcessors" Fn.id np ;
opt "--outFileName" Fn.id dest ;
opt "--regionsFileName" dep_list regions ;
opt "--scoreFileName" dep_list scores ;
]
]
let plotHeatmap
?dpi ?kmeans ?hclust ?sortRegions ?sortUsing ?sortUsingSamples
?averageTypeSummaryPlot ?missingDataColor ?colorMap ?alpha
?colorList ?colorNumber ?zMin ?zMax ?heatmapHeight ?heatmapWidth
?whatToShow ?boxAroundHeatmaps ?xAxisLabel ?startLabel
?endLabel ?refPointLabel ?regionsLabel ?samplesLabel ?plotTitle
?yAxisLabel ?yMin ?yMax ?legendLocation ?perGroup
output_format matrix =
let tmp_file = tmp // ("file." ^ ext_of_format output_format) in
Workflow.shell ~descr:"deeptools.plotHeatmap" ~img [
cmd "plotHeatmap" [
option (opt "--dpi" int) dpi ;
option (opt "--kmeans" int) kmeans ;
option (opt "--hclust" int) hclust ;
option (opt "--sortRegions" sort_regions_enum) sortRegions ;
option (opt "--sortUsing" sort_using_enum) sortUsing ;
option (opt "--sortUsingSamples" (slist int)) sortUsingSamples ;
option (opt "--averageTypeSummaryPlot" average_type_bins_enum) averageTypeSummaryPlot ;
option (opt "--missingDataColor" string) missingDataColor ;
option (opt "--colorMap" string) colorMap ;
option (opt "--alpha" float) alpha ;
option (opt "--colorList" (slist string)) colorList ;
option (opt "--colorNumber" int) colorNumber ;
option (opt "--zMin" (slist float)) zMin ;
option (opt "--zMax" (slist float)) zMax ;
option (opt "--heatmapHeight" float) heatmapHeight ;
option (opt "--heatmapWidth" float) heatmapWidth ;
option (opt "--whatToShow" what_to_show_enum) whatToShow ;
option (opt "--boxAroundHeatmaps" (fun b -> string (if b then "yes" else "no"))) boxAroundHeatmaps ;
option (opt "--xAxisLabel" string) xAxisLabel ;
option (opt "--startLabel" string) startLabel ;
option (opt "--endLabel" string) endLabel ;
option (opt "--refPointLabel" string) refPointLabel ;
option (opt "--regionsLabel" (slist string)) regionsLabel ;
option (opt "--samplesLabel" (slist string)) samplesLabel ;
option (opt "--plotTitle" (string % quote ~using:'\'')) plotTitle ;
option (opt "--yAxisLabel" string) yAxisLabel ;
option (opt "--yMin" (slist float)) yMin ;
option (opt "--yMax" (slist float)) yMax ;
option (opt "--legendLocation" legend_location_enum) legendLocation ;
option (flag string "--perGroup") perGroup ;
opt "--matrixFile" dep matrix ;
opt "--outFileName" Fn.id tmp_file ;
] ;
mv tmp_file dest ;
]
let corMethod_enum x =
(match x with
| `spearman -> "spearman"
| `pearson -> "pearson"
)
|> string
let whatToPlot_enum x =
string @@ match x with
| `heatmap -> "heatmap"
| `scatterplot -> "scatterplot"
| `lines -> "lines"
| `fill -> "fill"
| `se -> "se"
| `std -> "std"
| `overlapped_lines -> "overlapped_lines"
let plotCorrelation
?skipZeros ?labels ?plotTitle ?removeOutliers
?colorMap ?plotNumbers ?log1p
~corMethod ~whatToPlot output_format corData
=
Workflow.shell ~descr:"deeptools.plotCorrelation" ~img [
cmd "plotCorrelation" [
opt "--corData" dep corData ;
opt "--corMethod" corMethod_enum corMethod ;
opt "--whatToPlot" whatToPlot_enum whatToPlot ;
opt "--plotFile" Fn.id dest ;
opt "--plotFileFormat" string (ext_of_format output_format) ;
option (flag string "--skipZeros") skipZeros ;
option (opt "--labels" (list ~sep:" " string)) labels ;
option (opt "--plotTitle" (string % quote ~using:'\'')) plotTitle ;
option (flag string "--removeOutliers") removeOutliers ;
option (opt "--colorMap" string) colorMap ;
option (flag string "--plotNumbers") plotNumbers ;
option (flag string "--log1p") log1p ;
] ;
]
let plotProfile
?dpi ?kmeans ?hclust ?averageType ?plotHeight
?plotWidth ?plotType ?colors ?numPlotsPerRow
?startLabel ?endLabel ?refPointLabel ?regionsLabel
?samplesLabel ?plotTitle ?yAxisLabel ?yMin ?yMax
?legendLocation ?perGroup
output_format matrix
=
Workflow.shell ~descr:"deeptools.plotProfile" ~img [
cmd "plotProfile" [
option (opt "--dpi" int) dpi ;
option (opt "--kmeans" int) kmeans ;
option (opt "--hclust" int) hclust ;
option (opt "--averageType" average_type_bins_enum) averageType ;
option (opt "--plotHeight" float) plotHeight ;
option (opt "--plotWidth" float) plotWidth ;
option (opt "--plotType" whatToPlot_enum) plotType ;
option (opt "--colors" (list ~sep:" " string)) colors ;
option (opt "--numPlotsPerRow" int) numPlotsPerRow ;
option (opt "--startLabel" (string % quote ~using:'"')) startLabel ;
option (opt "--endLabel" (string % quote ~using:'"')) endLabel ;
option (opt "--refPointLabel" (string % quote ~using:'"')) refPointLabel ;
option (opt "--regionsLabel" (list ~sep:" " (string % quote ~using:'"'))) regionsLabel ;
option (opt "--samplesLabel" (list ~sep:" " (string % quote ~using:'"'))) samplesLabel ;
option (opt "--plotTitle" (string % quote ~using:'"')) plotTitle ;
option (opt "--yAxisLabel" (string % quote ~using:'"')) yAxisLabel ;
option (opt "--yMin" (list ~sep:" " float)) yMin ;
option (opt "--yMax" (list ~sep:" " float)) yMax ;
option (opt "--legendLocation" legend_location_enum) legendLocation ;
option (flag string "--perGroup") perGroup ;
opt "--plotFileFormat" string (ext_of_format output_format) ;
opt "--outFileName" Fn.id dest ;
opt "--matrixFile" dep matrix ;
]
]
let plotEnrichment
?labels ?regionLabels ?plotTitle ?variableScales ?plotHeight
?plotWidth ?colors ?numPlotsPerRow ?alpha ?offset ?blackList
?(numberOfProcessors = 1) ~bams ~beds output_format
=
Workflow.shell ~np:numberOfProcessors ~img ~descr:"deeptools.plotEnrichment" [
cmd "plotEnrichment" [
option (opt "--labels" (list ~sep:" " (string % quote ~using:'"'))) labels ;
option (opt "--regionLabels" (list ~sep:" " (string % quote ~using:'"'))) regionLabels ;
option (opt "--plotTitle" (string % quote ~using:'"')) plotTitle ;
option (flag string "--variableScales") variableScales ;
option (opt "--plotHeight" float) plotHeight ;
option (opt "--plotWidth" float) plotWidth ;
option (opt "--colors" (list ~sep:" " string)) colors ;
option (opt "--numPlotsPerRow" int) numPlotsPerRow ;
option (opt "--alpha" float) alpha ;
option (opt "--offset" int) offset ;
option (opt "--blackListFileName" dep) blackList ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bamfiles" (list ~sep:" " dep) bams ;
opt "--BED" (list ~sep:" " dep) beds ;
opt "--plotFile" Fn.id dest ;
opt "--plotFileFormat" string (ext_of_format output_format) ;
]
]
let plotFingerprint
?extendReads ?ignoreDuplicates ?minMappingQuality ?centerReads
?samFlagInclude ?samFlagExclude ?minFragmentLength ?maxFragmentLength
?labels ?binSize ?numberOfSamples ?plotTitle ?skipZeros ?region
?blackList ?(numberOfProcessors = 1)
output_format bams
=
Workflow.shell ~descr:"deeptools.plotFingerprint" ~img ~np:numberOfProcessors [
cmd "plotFingerprint" [
option (flag string "--extendReads") extendReads ;
option (flag string "--ignoreDuplicates") ignoreDuplicates ;
option (opt "--minMappingQuality" int) minMappingQuality ;
option (flag string "--centerReads") centerReads ;
option (opt "--samFlagInclude" int) samFlagInclude ;
option (opt "--samFlagExclude" int) samFlagExclude ;
option (opt "--minFragmentLength" int) minFragmentLength ;
option (opt "--maxFragmentLength" int) maxFragmentLength ;
option (opt "--blackListFileName" dep) blackList ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bamfiles" (list ~sep:" " (fun x -> dep (Samtools.indexed_bam_to_bam x))) bams ;
opt "--plotFile" Fn.id dest ;
opt "--plotFileFormat" string (ext_of_format output_format) ;
option (opt "--labels" (list ~sep:" " (string % quote ~using:'"'))) labels ;
option (opt "--plotTitle" (string % quote ~using:'"')) plotTitle ;
option (flag string "--skipZeros") skipZeros ;
option (opt "--region" string) region ;
opt "--numberOfProcessors" Fn.id np ;
option (opt "--binSize" int) binSize ;
option (opt "--numberOfSamples" int) numberOfSamples ;
]
]
| null | https://raw.githubusercontent.com/pveber/bistro/d363bd2d8257babbcb6db15bd83fd6465df7c268/lib/bio/deeptools.ml | ocaml | open Core
open Bistro
open Bistro.Shell_dsl
let img = [ docker_image ~account:"pveber" ~name:"deeptools" ~tag:"3.1.3" () ]
type 'a signal_format = [ `bigWig | `bedGraph ]
type 'a img_format = [ `png | `pdf | ` svg ]
class type compressed_numpy_array = object
inherit binary_file
method format : [`compressed_numpy_array]
end
let bigwig = `bigWig
let bedgraph = `bedGraph
let png = `png
let pdf = `pdf
let svg = `svg
let ext_of_format = function
| `png -> "png"
| `pdf -> "pdf"
| `svg -> "svg"
let file_format_expr = function
| `bigWig -> string "bigwig"
| `bedGraph -> string "bedgraph"
let filterRNAstrand_expr = function
| `forward -> string "forward"
| `reverse -> string "reverse"
let scalefactormethod_expr = function
| `readcount -> string "readCount"
| `ses -> string "SES"
let ratio_expr = function
| `log2 -> string "log2"
| `ratio -> string "ratio"
| `subtract -> string "subtract"
| `add -> string "add"
| `mean -> string "mean"
| `reciprocal_ratio -> string "reciprocal_ratio"
| `first -> string "first"
| `second -> string "second"
let slist f x = list ~sep:" " f x
let dep_list xs = slist dep xs
let normalization_method_expr = function
| `RPKM -> string "RPKM"
| `CPM -> string "CPM"
| `BPM -> string "BPM"
| `RPGC -> string "RPGC"
let bam_gen_cmd ?outfileformat ?scalefactor ?blacklist
?centerreads ?normalizeUsing ?ignorefornormalization ?skipnoncoveredregions
?smoothlength ?extendreads ?ignoreduplicates ?minmappingquality
?samflaginclude ?samflagexclude ?minfragmentlength ?maxfragmentlength
cmd_name other_args =
cmd cmd_name (
List.append [
option (opt "--outFileFormat" file_format_expr) outfileformat ;
option (opt "--scaleFactor" float) scalefactor ;
option (opt "--blackListFileName" dep) blacklist ;
option (opt "--normalizeUsing" normalization_method_expr) normalizeUsing ;
option (opt "--ignoreForNormalization" (list string ~sep:" ")) ignorefornormalization ;
option (flag string "--skipNonCoveredRegions") skipnoncoveredregions ;
option (opt "--smoothLength" int) smoothlength ;
option (opt "--extendReads" int) extendreads ;
option (flag string "--ignoreDuplicates") ignoreduplicates ;
option (opt "--minMappingQuality" int) minmappingquality ;
option (flag string "--centerReads") centerreads ;
option (opt "--samFlagInclude" int) samflaginclude ;
option (opt "--samFlagExclude" int) samflagexclude ;
option (opt "--minFragmentLength" int) minfragmentlength ;
option (opt "--maxfragmentLength" int) maxfragmentlength ;
]
other_args
)
let bamcoverage ?scalefactor ?filterrnastrand ?binsize ?blacklist
?(threads = 1) ?normalizeUsing ?ignorefornormalization
?skipnoncoveredregions ?smoothlength ?extendreads ?ignoreduplicates
?minmappingquality ?centerreads ?samflaginclude ?samflagexclude
?minfragmentlength ?maxfragmentlength outfileformat indexed_bam =
Workflow.shell ~descr:"bamcoverage" ~img ~np:threads [
bam_gen_cmd "bamCoverage" ?scalefactor ?blacklist
?normalizeUsing ?ignorefornormalization
?skipnoncoveredregions ?smoothlength ?extendreads ?ignoreduplicates
?minmappingquality ?centerreads ?samflaginclude ?samflagexclude
?minfragmentlength ?maxfragmentlength [
option (opt "--filterRNAstrand" filterRNAstrand_expr) filterrnastrand ;
option (opt "--binSize" int) binsize ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bam" Fn.id (dep (Samtools.indexed_bam_to_bam indexed_bam)) ;
opt "--outFileName" Fn.id dest ;
opt "--outFileFormat" file_format_expr outfileformat ;
]
]
let bamcompare ?scalefactormethod ?samplelength ?numberofsamples
?scalefactor ?ratio ?pseudocount ?binsize ?region ?blacklist ?(threads = 1)
?normalizeUsing ?ignorefornormalization ?skipnoncoveredregions
?smoothlength ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength outfileformat indexed_bam1 indexed_bam2 =
Workflow.shell ~descr:"bamcompare" ~img ~np:threads [
bam_gen_cmd "bamCompare"
?scalefactor ?blacklist
?normalizeUsing ?ignorefornormalization ?skipnoncoveredregions
?smoothlength ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength [
option (opt "--scaleFactorMethod" scalefactormethod_expr) scalefactormethod ;
option (opt "--sampleLength" int) samplelength ;
option (opt "--numberOfSamples" int) numberofsamples ;
option (opt "--ratio" ratio_expr) ratio ;
option (opt "--pseudocount" int) pseudocount ;
option (opt "--binSize" int) binsize ;
option (opt "--region" string) region ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bamfile1" Fn.id (dep (Samtools.indexed_bam_to_bam indexed_bam1)) ;
opt "--bamfile2" Fn.id (dep (Samtools.indexed_bam_to_bam indexed_bam2)) ;
opt "--outFileName" Fn.id dest ;
opt "--outFileFormat" file_format_expr outfileformat ;
]
]
let bigwigcompare ?scalefactor ?ratio ?pseudocount ?binsize
?region ?blacklist ?(threads = 1)
outfileformat bigwig1 bigwig2 =
Workflow.shell ~descr:"bigwigcompare" ~img ~np:threads [
cmd "bigwigCompare" [
option (opt "--scaleFactor" float) scalefactor ;
option (opt "--ratio" ratio_expr) ratio ;
option (opt "--pseudocount" int) pseudocount ;
option (opt "--binSize" int) binsize ;
option (opt "--region" string) region ;
option (opt "--blackListFileName" dep) blacklist ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bigwig1" dep bigwig1 ;
opt "--bigwig2" dep bigwig2 ;
opt "--outFileName" Fn.id dest ;
opt "--outFileFormat" file_format_expr outfileformat ;
]
]
let multibamsum_gen_cmd ?outrawcounts ?extendreads ?ignoreduplicates
?minmappingquality ?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength ?blacklist ?region cmd_name other_args =
cmd cmd_name (
List.append [
option (opt "--region" string) region ;
option (flag string "--outRawCounts") outrawcounts ;
option (opt "--extendReads" int) extendreads ;
option (flag string "--ignoreDuplicates") ignoreduplicates ;
option (opt "--minMappingQuality" int) minmappingquality ;
option (flag string "--centerReads") centerreads ;
option (opt "--samFlagInclude" int) samflaginclude ;
option (opt "--samFlagExclude" int) samflagexclude ;
option (opt "--minFragmentLength" int) minfragmentlength ;
option (opt "--maxfragmentLength" int) maxfragmentlength ;
option (opt "--blackListFileName" dep) blacklist ;
]
other_args
)
let multibamsummary_bins ?binsize ?distancebetweenbins ?region ?blacklist
?(threads = 1) ?outrawcounts ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength indexed_bams =
Workflow.shell ~descr:"multibamsummary_bins" ~img ~np:threads [
multibamsum_gen_cmd "multiBamSummary bins"
?region ?blacklist
?outrawcounts ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength [
option (opt "--binSize" int) binsize ;
option (opt "--distanceBetweenBins" int) distancebetweenbins ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bamfiles" (list (fun bam -> dep (Samtools.indexed_bam_to_bam bam)) ~sep:" ") indexed_bams ;
opt "--outFileName" Fn.id dest ;
]
]
let multibamsummary_bed ?region ?blacklist ?(threads = 1)
?outrawcounts ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength ?metagene ?transcriptid ?exonid ?transcriptiddesignator bed
indexed_bams =
Workflow.shell ~descr:"multibamsummary_bed" ~img ~np:threads [
multibamsum_gen_cmd "multiBamSummary BED-file"
?region ?blacklist
?outrawcounts ?extendreads ?ignoreduplicates ?minmappingquality
?centerreads ?samflaginclude ?samflagexclude ?minfragmentlength
?maxfragmentlength [
option (flag string "--metagene") metagene ;
option (flag string "--transcriptID") transcriptid ;
option (flag string "--exonID") exonid ;
option (flag string "--transcript_id_designator") transcriptiddesignator ;
opt "--numberOfProcessors" Fn.id np ;
opt "--BED" dep bed ;
opt "--bamfiles"
(list (fun bam -> dep (Samtools.indexed_bam_to_bam bam)) ~sep:" ")
indexed_bams ;
opt "--outFileName" Fn.id dest ;
]
]
let multibigwigsummary_bed
?labels ?chromosomesToSkip ?region ?blacklist ?(threads = 1)
?metagene ?transcriptid ?exonid ?transcriptiddesignator
bed bigwigs =
let inner =
Workflow.shell ~descr:"multibigwigsummary_bed" ~img ~np:threads [
mkdir_p dest ;
cmd "multiBigwigSummary BED-file" [
option (opt "--labels" (list string ~sep:" ")) labels ;
option (opt "--chromosomesToSkip" (list string ~sep:" ")) chromosomesToSkip ;
option (opt "--region" string) region ;
option (opt "--blackListFileName" dep) blacklist ;
opt "--outRawCounts" Fn.id (dest // "summary.tsv") ;
option (flag string "--metagene") metagene ;
option (flag string "--transcriptID") transcriptid ;
option (flag string "--exonID") exonid ;
option (flag string "--transcript_id_designator") transcriptiddesignator ;
opt "--BED" dep bed ;
opt "--bwfiles" (list dep ~sep:" ") bigwigs ;
opt "--outFileName" Fn.id (dest // "summary.npy.gz") ;
]
]
in
let f x = Workflow.select inner [x] in
f "summary.npy.gz", f "summary.tsv"
let reference_point_enum x =
(match x with
| `TES -> "TES"
| `TSS -> "TSS"
| `center -> "center")
|> string
let sort_regions_enum x =
(match x with
| `no -> "no"
| `ascend -> "ascend"
| `descend -> "descend"
| `keep -> "keep")
|> string
let sort_using_enum x =
(match x with
| `max -> "max"
| `min -> "min"
| `mean -> "mean"
| `median -> "median"
| `region_length -> "region_length"
| `sum -> "sum")
|> string
let average_type_bins_enum x =
(match x with
| `max -> "max"
| `min -> "min"
| `mean -> "mean"
| `median -> "median"
| `std -> "std"
| `sum -> "sum"
)
|> string
let what_to_show_enum x =
(match x with
| `plot_heatmap_and_colorbar -> "plot, heatmap and colorbar"
| `plot_and_heatmap -> "plot and heatmap"
| `heatmap_only -> "heatmap only"
| `heatmap_and_colorbar -> "heatmap and colorbar"
)
|> string
let legend_location_enum x=
string @@ match x with
| `best-> "best"
| `upper_right-> "upper_right"
| `upper_left-> "upper_left"
| `upper_center-> "upper_center"
| `lower_left-> "lower_left"
| `lower_right-> "lower_right"
| `lower_center-> "lower_center"
| `center-> "center"
| `center_left-> "center_left"
| `center_right-> "center_right"
| `none -> "none"
class type deeptools_matrix = object
inherit binary_file
method format : [`deeptools_matrix]
end
let computeMatrix_reference_point
?referencePoint ?upstream ?downstream ?nanAfterEnd
?binSize ?sortRegions ?sortUsing ?sortUsingSamples
?averageTypeBins ?missingDataAsZero ?skipZeros
?minThreshold ?maxThreshold ?blackList ?scale
?(numberOfProcessors = 1) ~regions ~scores () =
Workflow.shell ~descr:"deeptools.computeMatrix_reference_point" ~img ~np:numberOfProcessors [
cmd "computeMatrix" [
string "reference-point" ;
option (opt "--referencePoint" reference_point_enum) referencePoint ;
option (opt "--upstream" int) upstream ;
option (opt "--downstream" int) downstream ;
option (flag string "--nanAfterEnd") nanAfterEnd ;
option (opt "--binSize" int) binSize ;
option (opt "--sortRegions" sort_regions_enum) sortRegions ;
option (opt "--sortUsing" sort_using_enum) sortUsing ;
option (opt "--sortUsingSamples" (slist int) ) sortUsingSamples ;
option (opt "--averageTypeBins" average_type_bins_enum) averageTypeBins ;
option (flag string "--missingDataAsZero") missingDataAsZero ;
option (flag string "--skipZeros") skipZeros ;
option (opt "--minThreshold" float) minThreshold ;
option (opt "--maxThreshold" float) maxThreshold ;
option (opt "--blackListFileName" dep) blackList ;
option (opt "--sc" float) scale ;
opt "--numberOfProcessors" Fn.id np ;
opt "--outFileName" Fn.id dest ;
opt "--regionsFileName" dep_list regions ;
opt "--scoreFileName" dep_list scores ;
]
]
let plotHeatmap
?dpi ?kmeans ?hclust ?sortRegions ?sortUsing ?sortUsingSamples
?averageTypeSummaryPlot ?missingDataColor ?colorMap ?alpha
?colorList ?colorNumber ?zMin ?zMax ?heatmapHeight ?heatmapWidth
?whatToShow ?boxAroundHeatmaps ?xAxisLabel ?startLabel
?endLabel ?refPointLabel ?regionsLabel ?samplesLabel ?plotTitle
?yAxisLabel ?yMin ?yMax ?legendLocation ?perGroup
output_format matrix =
let tmp_file = tmp // ("file." ^ ext_of_format output_format) in
Workflow.shell ~descr:"deeptools.plotHeatmap" ~img [
cmd "plotHeatmap" [
option (opt "--dpi" int) dpi ;
option (opt "--kmeans" int) kmeans ;
option (opt "--hclust" int) hclust ;
option (opt "--sortRegions" sort_regions_enum) sortRegions ;
option (opt "--sortUsing" sort_using_enum) sortUsing ;
option (opt "--sortUsingSamples" (slist int)) sortUsingSamples ;
option (opt "--averageTypeSummaryPlot" average_type_bins_enum) averageTypeSummaryPlot ;
option (opt "--missingDataColor" string) missingDataColor ;
option (opt "--colorMap" string) colorMap ;
option (opt "--alpha" float) alpha ;
option (opt "--colorList" (slist string)) colorList ;
option (opt "--colorNumber" int) colorNumber ;
option (opt "--zMin" (slist float)) zMin ;
option (opt "--zMax" (slist float)) zMax ;
option (opt "--heatmapHeight" float) heatmapHeight ;
option (opt "--heatmapWidth" float) heatmapWidth ;
option (opt "--whatToShow" what_to_show_enum) whatToShow ;
option (opt "--boxAroundHeatmaps" (fun b -> string (if b then "yes" else "no"))) boxAroundHeatmaps ;
option (opt "--xAxisLabel" string) xAxisLabel ;
option (opt "--startLabel" string) startLabel ;
option (opt "--endLabel" string) endLabel ;
option (opt "--refPointLabel" string) refPointLabel ;
option (opt "--regionsLabel" (slist string)) regionsLabel ;
option (opt "--samplesLabel" (slist string)) samplesLabel ;
option (opt "--plotTitle" (string % quote ~using:'\'')) plotTitle ;
option (opt "--yAxisLabel" string) yAxisLabel ;
option (opt "--yMin" (slist float)) yMin ;
option (opt "--yMax" (slist float)) yMax ;
option (opt "--legendLocation" legend_location_enum) legendLocation ;
option (flag string "--perGroup") perGroup ;
opt "--matrixFile" dep matrix ;
opt "--outFileName" Fn.id tmp_file ;
] ;
mv tmp_file dest ;
]
let corMethod_enum x =
(match x with
| `spearman -> "spearman"
| `pearson -> "pearson"
)
|> string
let whatToPlot_enum x =
string @@ match x with
| `heatmap -> "heatmap"
| `scatterplot -> "scatterplot"
| `lines -> "lines"
| `fill -> "fill"
| `se -> "se"
| `std -> "std"
| `overlapped_lines -> "overlapped_lines"
let plotCorrelation
?skipZeros ?labels ?plotTitle ?removeOutliers
?colorMap ?plotNumbers ?log1p
~corMethod ~whatToPlot output_format corData
=
Workflow.shell ~descr:"deeptools.plotCorrelation" ~img [
cmd "plotCorrelation" [
opt "--corData" dep corData ;
opt "--corMethod" corMethod_enum corMethod ;
opt "--whatToPlot" whatToPlot_enum whatToPlot ;
opt "--plotFile" Fn.id dest ;
opt "--plotFileFormat" string (ext_of_format output_format) ;
option (flag string "--skipZeros") skipZeros ;
option (opt "--labels" (list ~sep:" " string)) labels ;
option (opt "--plotTitle" (string % quote ~using:'\'')) plotTitle ;
option (flag string "--removeOutliers") removeOutliers ;
option (opt "--colorMap" string) colorMap ;
option (flag string "--plotNumbers") plotNumbers ;
option (flag string "--log1p") log1p ;
] ;
]
let plotProfile
?dpi ?kmeans ?hclust ?averageType ?plotHeight
?plotWidth ?plotType ?colors ?numPlotsPerRow
?startLabel ?endLabel ?refPointLabel ?regionsLabel
?samplesLabel ?plotTitle ?yAxisLabel ?yMin ?yMax
?legendLocation ?perGroup
output_format matrix
=
Workflow.shell ~descr:"deeptools.plotProfile" ~img [
cmd "plotProfile" [
option (opt "--dpi" int) dpi ;
option (opt "--kmeans" int) kmeans ;
option (opt "--hclust" int) hclust ;
option (opt "--averageType" average_type_bins_enum) averageType ;
option (opt "--plotHeight" float) plotHeight ;
option (opt "--plotWidth" float) plotWidth ;
option (opt "--plotType" whatToPlot_enum) plotType ;
option (opt "--colors" (list ~sep:" " string)) colors ;
option (opt "--numPlotsPerRow" int) numPlotsPerRow ;
option (opt "--startLabel" (string % quote ~using:'"')) startLabel ;
option (opt "--endLabel" (string % quote ~using:'"')) endLabel ;
option (opt "--refPointLabel" (string % quote ~using:'"')) refPointLabel ;
option (opt "--regionsLabel" (list ~sep:" " (string % quote ~using:'"'))) regionsLabel ;
option (opt "--samplesLabel" (list ~sep:" " (string % quote ~using:'"'))) samplesLabel ;
option (opt "--plotTitle" (string % quote ~using:'"')) plotTitle ;
option (opt "--yAxisLabel" (string % quote ~using:'"')) yAxisLabel ;
option (opt "--yMin" (list ~sep:" " float)) yMin ;
option (opt "--yMax" (list ~sep:" " float)) yMax ;
option (opt "--legendLocation" legend_location_enum) legendLocation ;
option (flag string "--perGroup") perGroup ;
opt "--plotFileFormat" string (ext_of_format output_format) ;
opt "--outFileName" Fn.id dest ;
opt "--matrixFile" dep matrix ;
]
]
let plotEnrichment
?labels ?regionLabels ?plotTitle ?variableScales ?plotHeight
?plotWidth ?colors ?numPlotsPerRow ?alpha ?offset ?blackList
?(numberOfProcessors = 1) ~bams ~beds output_format
=
Workflow.shell ~np:numberOfProcessors ~img ~descr:"deeptools.plotEnrichment" [
cmd "plotEnrichment" [
option (opt "--labels" (list ~sep:" " (string % quote ~using:'"'))) labels ;
option (opt "--regionLabels" (list ~sep:" " (string % quote ~using:'"'))) regionLabels ;
option (opt "--plotTitle" (string % quote ~using:'"')) plotTitle ;
option (flag string "--variableScales") variableScales ;
option (opt "--plotHeight" float) plotHeight ;
option (opt "--plotWidth" float) plotWidth ;
option (opt "--colors" (list ~sep:" " string)) colors ;
option (opt "--numPlotsPerRow" int) numPlotsPerRow ;
option (opt "--alpha" float) alpha ;
option (opt "--offset" int) offset ;
option (opt "--blackListFileName" dep) blackList ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bamfiles" (list ~sep:" " dep) bams ;
opt "--BED" (list ~sep:" " dep) beds ;
opt "--plotFile" Fn.id dest ;
opt "--plotFileFormat" string (ext_of_format output_format) ;
]
]
let plotFingerprint
?extendReads ?ignoreDuplicates ?minMappingQuality ?centerReads
?samFlagInclude ?samFlagExclude ?minFragmentLength ?maxFragmentLength
?labels ?binSize ?numberOfSamples ?plotTitle ?skipZeros ?region
?blackList ?(numberOfProcessors = 1)
output_format bams
=
Workflow.shell ~descr:"deeptools.plotFingerprint" ~img ~np:numberOfProcessors [
cmd "plotFingerprint" [
option (flag string "--extendReads") extendReads ;
option (flag string "--ignoreDuplicates") ignoreDuplicates ;
option (opt "--minMappingQuality" int) minMappingQuality ;
option (flag string "--centerReads") centerReads ;
option (opt "--samFlagInclude" int) samFlagInclude ;
option (opt "--samFlagExclude" int) samFlagExclude ;
option (opt "--minFragmentLength" int) minFragmentLength ;
option (opt "--maxFragmentLength" int) maxFragmentLength ;
option (opt "--blackListFileName" dep) blackList ;
opt "--numberOfProcessors" Fn.id np ;
opt "--bamfiles" (list ~sep:" " (fun x -> dep (Samtools.indexed_bam_to_bam x))) bams ;
opt "--plotFile" Fn.id dest ;
opt "--plotFileFormat" string (ext_of_format output_format) ;
option (opt "--labels" (list ~sep:" " (string % quote ~using:'"'))) labels ;
option (opt "--plotTitle" (string % quote ~using:'"')) plotTitle ;
option (flag string "--skipZeros") skipZeros ;
option (opt "--region" string) region ;
opt "--numberOfProcessors" Fn.id np ;
option (opt "--binSize" int) binSize ;
option (opt "--numberOfSamples" int) numberOfSamples ;
]
]
|
|
a4b28607899a79c5d18c2e94ed95a3a19c7b841692c58eb2479fcbfefcb46550 | jeffshrager/biobike | aux7level.lisp | ;;;; -*- mode: Lisp; Syntax: Common-Lisp; Package: bbi; -*-
(IN-PACKAGE :bbi)
(DEFUN bidirectional-best-hit (gene org2 &OPTIONAL (threshold 1e-10))
(LET* ((org1 (ORGANISM-OF gene))
(protein1 (PROTEIN-OF gene))
(pre-prot-gene2
(IF protein1
(SEQUENCE-SIMILAR-TO protein1 IN org2 PROTEIN-VS-PROTEIN
RETURN 1 NO-DISPLAY THRESHOLD threshold)
(GENE/S-SIMILAR-TO gene IN org2 RETURN 1
THRESHOLD threshold NO-DISPLAY)))
(prot-gene2
(IF (LISTP pre-prot-gene2)
(FIRST pre-prot-gene2)
pre-prot-gene2))
(pre-prot-gene-1b
(IF prot-gene2
(IF protein1
(SEQUENCE-SIMILAR-TO prot-gene2 IN org1 PROTEIN-VS-PROTEIN
RETURN 1 NO-DISPLAY THRESHOLD threshold)
(GENE/S-SIMILAR-TO prot-gene2 IN org1 RETURN 1
THRESHOLD threshold NO-DISPLAY))))
(prot-gene-1b
(IF (LISTP pre-prot-gene-1b)
(FIRST pre-prot-gene-1b)
pre-prot-gene-1b))
)
(IF (OR (AND protein1 (EQUAL protein1 prot-gene-1b))
(AND (NOT protein1) (EQUAL gene prot-gene-1b)))
prot-gene2)
)) | null | https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/bike/aux7level.lisp | lisp | -*- mode: Lisp; Syntax: Common-Lisp; Package: bbi; -*- |
(IN-PACKAGE :bbi)
(DEFUN bidirectional-best-hit (gene org2 &OPTIONAL (threshold 1e-10))
(LET* ((org1 (ORGANISM-OF gene))
(protein1 (PROTEIN-OF gene))
(pre-prot-gene2
(IF protein1
(SEQUENCE-SIMILAR-TO protein1 IN org2 PROTEIN-VS-PROTEIN
RETURN 1 NO-DISPLAY THRESHOLD threshold)
(GENE/S-SIMILAR-TO gene IN org2 RETURN 1
THRESHOLD threshold NO-DISPLAY)))
(prot-gene2
(IF (LISTP pre-prot-gene2)
(FIRST pre-prot-gene2)
pre-prot-gene2))
(pre-prot-gene-1b
(IF prot-gene2
(IF protein1
(SEQUENCE-SIMILAR-TO prot-gene2 IN org1 PROTEIN-VS-PROTEIN
RETURN 1 NO-DISPLAY THRESHOLD threshold)
(GENE/S-SIMILAR-TO prot-gene2 IN org1 RETURN 1
THRESHOLD threshold NO-DISPLAY))))
(prot-gene-1b
(IF (LISTP pre-prot-gene-1b)
(FIRST pre-prot-gene-1b)
pre-prot-gene-1b))
)
(IF (OR (AND protein1 (EQUAL protein1 prot-gene-1b))
(AND (NOT protein1) (EQUAL gene prot-gene-1b)))
prot-gene2)
)) |
a32d202fabb4b12f11990be31cc4164f68675f53dab3f753ebca44ce656edad3 | tolysz/ghcjs-stack | Dependency.hs | -----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Dependency
Copyright : ( c ) 2005 ,
2007
2008
-- License : BSD-like
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- Top level interface to dependency resolution.
-----------------------------------------------------------------------------
module Distribution.Client.Dependency (
-- * The main package dependency resolver
chooseSolver,
resolveDependencies,
Progress(..),
foldProgress,
-- * Alternate, simple resolver that does not do dependencies recursively
resolveWithoutDependencies,
-- * Constructing resolver policies
DepResolverParams(..),
PackageConstraint(..),
PackagesPreferenceDefault(..),
PackagePreference(..),
InstalledPreference(..),
-- ** Standard policy
standardInstallPolicy,
PackageSpecifier(..),
* * Sandbox policy
applySandboxInstallPolicy,
-- ** Extra policy options
dontUpgradeNonUpgradeablePackages,
hideBrokenInstalledPackages,
upgradeDependencies,
reinstallTargets,
-- ** Policy utils
addConstraints,
addPreferences,
setPreferenceDefault,
setReorderGoals,
setIndependentGoals,
setAvoidReinstalls,
setShadowPkgs,
setStrongFlags,
setMaxBackjumps,
addSourcePackages,
hideInstalledPackagesSpecificByUnitId,
hideInstalledPackagesSpecificBySourcePackageId,
hideInstalledPackagesAllVersions,
removeUpperBounds,
addDefaultSetupDependencies,
) where
import Distribution.Client.Dependency.TopDown
( topDownResolver )
import Distribution.Client.Dependency.Modular
( modularResolver, SolverConfig(..) )
import qualified Distribution.Client.PackageIndex as PackageIndex
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Client.InstallPlan (InstallPlan)
import Distribution.Client.PkgConfigDb (PkgConfigDb)
import Distribution.Client.Types
( SourcePackageDb(SourcePackageDb), SourcePackage(..)
, ConfiguredPackage(..), ConfiguredId(..)
, OptionalStanza(..), enableStanzas )
import Distribution.Client.Dependency.Types
( PreSolver(..), Solver(..), DependencyResolver, ResolverPackage(..)
, PackageConstraint(..), showPackageConstraint
, LabeledPackageConstraint(..), unlabelPackageConstraint
, ConstraintSource(..), showConstraintSource
, PackagePreferences(..), InstalledPreference(..)
, PackagesPreferenceDefault(..)
, Progress(..), foldProgress )
import Distribution.Client.Sandbox.Types
( SandboxPackageInfo(..) )
import Distribution.Client.Targets
import Distribution.Client.ComponentDeps (ComponentDeps)
import qualified Distribution.Client.ComponentDeps as CD
import qualified Distribution.InstalledPackageInfo as Installed
import Distribution.Package
( PackageName(..), PackageIdentifier(PackageIdentifier), PackageId
, Package(..), packageName, packageVersion
, UnitId, Dependency(Dependency))
import qualified Distribution.PackageDescription as PD
import qualified Distribution.PackageDescription.Configuration as PD
import Distribution.PackageDescription.Configuration
( finalizePackageDescription )
import Distribution.Client.PackageUtils
( externalBuildDepends )
import Distribution.Version
( VersionRange, Version(..), anyVersion, orLaterVersion, thisVersion
, withinRange, simplifyVersionRange )
import Distribution.Compiler
( CompilerInfo(..) )
import Distribution.System
( Platform )
import Distribution.Client.Utils
( duplicates, duplicatesBy, mergeBy, MergeResult(..) )
import Distribution.Simple.Utils
( comparing, warn, info )
import Distribution.Simple.Configure
( relaxPackageDeps )
import Distribution.Simple.Setup
( AllowNewer(..) )
import Distribution.Text
( display )
import Distribution.Verbosity
( Verbosity )
import Data.List
( foldl', sort, sortBy, nubBy, maximumBy, intercalate, nub )
import Data.Function (on)
import Data.Maybe (fromMaybe)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Set (Set)
import Control.Exception
( assert )
-- ------------------------------------------------------------
-- * High level planner policy
-- ------------------------------------------------------------
-- | The set of parameters to the dependency resolver. These parameters are
-- relatively low level but many kinds of high level policies can be
-- implemented in terms of adjustments to the parameters.
--
data DepResolverParams = DepResolverParams {
depResolverTargets :: [PackageName],
depResolverConstraints :: [LabeledPackageConstraint],
depResolverPreferences :: [PackagePreference],
depResolverPreferenceDefault :: PackagesPreferenceDefault,
depResolverInstalledPkgIndex :: InstalledPackageIndex,
depResolverSourcePkgIndex :: PackageIndex.PackageIndex SourcePackage,
depResolverReorderGoals :: Bool,
depResolverIndependentGoals :: Bool,
depResolverAvoidReinstalls :: Bool,
depResolverShadowPkgs :: Bool,
depResolverStrongFlags :: Bool,
depResolverMaxBackjumps :: Maybe Int
}
showDepResolverParams :: DepResolverParams -> String
showDepResolverParams p =
"targets: " ++ intercalate ", " (map display (depResolverTargets p))
++ "\nconstraints: "
++ concatMap (("\n " ++) . showLabeledConstraint)
(depResolverConstraints p)
++ "\npreferences: "
++ concatMap (("\n " ++) . showPackagePreference)
(depResolverPreferences p)
++ "\nstrategy: " ++ show (depResolverPreferenceDefault p)
++ "\nreorder goals: " ++ show (depResolverReorderGoals p)
++ "\nindependent goals: " ++ show (depResolverIndependentGoals p)
++ "\navoid reinstalls: " ++ show (depResolverAvoidReinstalls p)
++ "\nshadow packages: " ++ show (depResolverShadowPkgs p)
++ "\nstrong flags: " ++ show (depResolverStrongFlags p)
++ "\nmax backjumps: " ++ maybe "infinite" show
(depResolverMaxBackjumps p)
where
showLabeledConstraint :: LabeledPackageConstraint -> String
showLabeledConstraint (LabeledPackageConstraint pc src) =
showPackageConstraint pc ++ " (" ++ showConstraintSource src ++ ")"
-- | A package selection preference for a particular package.
--
-- Preferences are soft constraints that the dependency resolver should try to
-- respect where possible. It is not specified if preferences on some packages
-- are more important than others.
--
data PackagePreference =
-- | A suggested constraint on the version number.
PackageVersionPreference PackageName VersionRange
-- | If we prefer versions of packages that are already installed.
| PackageInstalledPreference PackageName InstalledPreference
-- | If we would prefer to enable these optional stanzas
-- (i.e. test suites and/or benchmarks)
| PackageStanzasPreference PackageName [OptionalStanza]
-- | Provide a textual representation of a package preference
-- for debugging purposes.
--
showPackagePreference :: PackagePreference -> String
showPackagePreference (PackageVersionPreference pn vr) =
display pn ++ " " ++ display (simplifyVersionRange vr)
showPackagePreference (PackageInstalledPreference pn ip) =
display pn ++ " " ++ show ip
showPackagePreference (PackageStanzasPreference pn st) =
display pn ++ " " ++ show st
basicDepResolverParams :: InstalledPackageIndex
-> PackageIndex.PackageIndex SourcePackage
-> DepResolverParams
basicDepResolverParams installedPkgIndex sourcePkgIndex =
DepResolverParams {
depResolverTargets = [],
depResolverConstraints = [],
depResolverPreferences = [],
depResolverPreferenceDefault = PreferLatestForSelected,
depResolverInstalledPkgIndex = installedPkgIndex,
depResolverSourcePkgIndex = sourcePkgIndex,
depResolverReorderGoals = False,
depResolverIndependentGoals = False,
depResolverAvoidReinstalls = False,
depResolverShadowPkgs = False,
depResolverStrongFlags = False,
depResolverMaxBackjumps = Nothing
}
addTargets :: [PackageName]
-> DepResolverParams -> DepResolverParams
addTargets extraTargets params =
params {
depResolverTargets = extraTargets ++ depResolverTargets params
}
addConstraints :: [LabeledPackageConstraint]
-> DepResolverParams -> DepResolverParams
addConstraints extraConstraints params =
params {
depResolverConstraints = extraConstraints
++ depResolverConstraints params
}
addPreferences :: [PackagePreference]
-> DepResolverParams -> DepResolverParams
addPreferences extraPreferences params =
params {
depResolverPreferences = extraPreferences
++ depResolverPreferences params
}
setPreferenceDefault :: PackagesPreferenceDefault
-> DepResolverParams -> DepResolverParams
setPreferenceDefault preferenceDefault params =
params {
depResolverPreferenceDefault = preferenceDefault
}
setReorderGoals :: Bool -> DepResolverParams -> DepResolverParams
setReorderGoals b params =
params {
depResolverReorderGoals = b
}
setIndependentGoals :: Bool -> DepResolverParams -> DepResolverParams
setIndependentGoals b params =
params {
depResolverIndependentGoals = b
}
setAvoidReinstalls :: Bool -> DepResolverParams -> DepResolverParams
setAvoidReinstalls b params =
params {
depResolverAvoidReinstalls = b
}
setShadowPkgs :: Bool -> DepResolverParams -> DepResolverParams
setShadowPkgs b params =
params {
depResolverShadowPkgs = b
}
setStrongFlags :: Bool -> DepResolverParams -> DepResolverParams
setStrongFlags b params =
params {
depResolverStrongFlags = b
}
setMaxBackjumps :: Maybe Int -> DepResolverParams -> DepResolverParams
setMaxBackjumps n params =
params {
depResolverMaxBackjumps = n
}
-- | Some packages are specific to a given compiler version and should never be
-- upgraded.
dontUpgradeNonUpgradeablePackages :: DepResolverParams -> DepResolverParams
dontUpgradeNonUpgradeablePackages params =
addConstraints extraConstraints params
where
extraConstraints =
[ LabeledPackageConstraint
(PackageConstraintInstalled pkgname)
ConstraintSourceNonUpgradeablePackage
| notElem (PackageName "base") (depResolverTargets params)
, pkgname <- map PackageName [ "base", "ghc-prim", "integer-gmp"
, "integer-simple" ]
, isInstalled pkgname ]
-- TODO: the top down resolver chokes on the base constraints
-- below when there are no targets and thus no dep on base.
-- Need to refactor constraints separate from needing packages.
isInstalled = not . null
. InstalledPackageIndex.lookupPackageName
(depResolverInstalledPkgIndex params)
addSourcePackages :: [SourcePackage]
-> DepResolverParams -> DepResolverParams
addSourcePackages pkgs params =
params {
depResolverSourcePkgIndex =
foldl (flip PackageIndex.insert)
(depResolverSourcePkgIndex params) pkgs
}
hideInstalledPackagesSpecificByUnitId :: [UnitId]
-> DepResolverParams
-> DepResolverParams
hideInstalledPackagesSpecificByUnitId pkgids params =
--TODO: this should work using exclude constraints instead
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deleteUnitId)
(depResolverInstalledPkgIndex params) pkgids
}
hideInstalledPackagesSpecificBySourcePackageId :: [PackageId]
-> DepResolverParams
-> DepResolverParams
hideInstalledPackagesSpecificBySourcePackageId pkgids params =
--TODO: this should work using exclude constraints instead
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deleteSourcePackageId)
(depResolverInstalledPkgIndex params) pkgids
}
hideInstalledPackagesAllVersions :: [PackageName]
-> DepResolverParams -> DepResolverParams
hideInstalledPackagesAllVersions pkgnames params =
--TODO: this should work using exclude constraints instead
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deletePackageName)
(depResolverInstalledPkgIndex params) pkgnames
}
hideBrokenInstalledPackages :: DepResolverParams -> DepResolverParams
hideBrokenInstalledPackages params =
hideInstalledPackagesSpecificByUnitId pkgids params
where
pkgids = map Installed.installedUnitId
. InstalledPackageIndex.reverseDependencyClosure
(depResolverInstalledPkgIndex params)
. map (Installed.installedUnitId . fst)
. InstalledPackageIndex.brokenPackages
$ depResolverInstalledPkgIndex params
-- | Remove upper bounds in dependencies using the policy specified by the
-- 'AllowNewer' argument (all/some/none).
--
-- Note: It's important to apply 'removeUpperBounds' after
-- 'addSourcePackages'. Otherwise, the packages inserted by
-- 'addSourcePackages' won't have upper bounds in dependencies relaxed.
--
removeUpperBounds :: AllowNewer -> DepResolverParams -> DepResolverParams
removeUpperBounds AllowNewerNone params = params
removeUpperBounds allowNewer params =
params {
depResolverSourcePkgIndex = sourcePkgIndex'
}
where
sourcePkgIndex' = fmap relaxDeps $ depResolverSourcePkgIndex params
relaxDeps :: SourcePackage -> SourcePackage
relaxDeps srcPkg = srcPkg {
packageDescription = relaxPackageDeps allowNewer
(packageDescription srcPkg)
}
-- | Supply defaults for packages without explicit Setup dependencies
--
-- Note: It's important to apply 'addDefaultSetupDepends' after
-- 'addSourcePackages'. Otherwise, the packages inserted by
-- 'addSourcePackages' won't have upper bounds in dependencies relaxed.
--
addDefaultSetupDependencies :: (SourcePackage -> Maybe [Dependency])
-> DepResolverParams -> DepResolverParams
addDefaultSetupDependencies defaultSetupDeps params =
params {
depResolverSourcePkgIndex =
fmap applyDefaultSetupDeps (depResolverSourcePkgIndex params)
}
where
applyDefaultSetupDeps :: SourcePackage -> SourcePackage
applyDefaultSetupDeps srcpkg =
srcpkg {
packageDescription = gpkgdesc {
PD.packageDescription = pkgdesc {
PD.setupBuildInfo =
case PD.setupBuildInfo pkgdesc of
Just sbi -> Just sbi
Nothing -> case defaultSetupDeps srcpkg of
Nothing -> Nothing
Just deps -> Just PD.SetupBuildInfo {
PD.defaultSetupDepends = True,
PD.setupDepends = deps
}
}
}
}
where
gpkgdesc = packageDescription srcpkg
pkgdesc = PD.packageDescription gpkgdesc
upgradeDependencies :: DepResolverParams -> DepResolverParams
upgradeDependencies = setPreferenceDefault PreferAllLatest
reinstallTargets :: DepResolverParams -> DepResolverParams
reinstallTargets params =
hideInstalledPackagesAllVersions (depResolverTargets params) params
standardInstallPolicy :: InstalledPackageIndex
-> SourcePackageDb
-> [PackageSpecifier SourcePackage]
-> DepResolverParams
standardInstallPolicy
installedPkgIndex (SourcePackageDb sourcePkgIndex sourcePkgPrefs)
pkgSpecifiers
= addPreferences
[ PackageVersionPreference name ver
| (name, ver) <- Map.toList sourcePkgPrefs ]
. addConstraints
(concatMap pkgSpecifierConstraints pkgSpecifiers)
. addTargets
(map pkgSpecifierTarget pkgSpecifiers)
. hideInstalledPackagesSpecificBySourcePackageId
[ packageId pkg | SpecificSourcePackage pkg <- pkgSpecifiers ]
. addDefaultSetupDependencies mkDefaultSetupDeps
. addSourcePackages
[ pkg | SpecificSourcePackage pkg <- pkgSpecifiers ]
$ basicDepResolverParams
installedPkgIndex sourcePkgIndex
where
Force Cabal > = 1.24 dep when the package is affected by # 3199 .
mkDefaultSetupDeps :: SourcePackage -> Maybe [Dependency]
mkDefaultSetupDeps srcpkg | affected =
Just [Dependency (PackageName "Cabal")
(orLaterVersion $ Version [1,24] [])]
| otherwise = Nothing
where
gpkgdesc = packageDescription srcpkg
pkgdesc = PD.packageDescription gpkgdesc
bt = fromMaybe PD.Custom (PD.buildType pkgdesc)
affected = bt == PD.Custom && hasBuildableFalse gpkgdesc
-- Does this package contain any components with non-empty 'build-depends'
-- and a 'buildable' field that could potentially be set to 'False'? False
-- positives are possible.
hasBuildableFalse :: PD.GenericPackageDescription -> Bool
hasBuildableFalse gpkg =
not (all alwaysTrue (zipWith PD.cOr buildableConditions noDepConditions))
where
buildableConditions = PD.extractConditions PD.buildable gpkg
noDepConditions = PD.extractConditions
(null . PD.targetBuildDepends) gpkg
alwaysTrue (PD.Lit True) = True
alwaysTrue _ = False
applySandboxInstallPolicy :: SandboxPackageInfo
-> DepResolverParams
-> DepResolverParams
applySandboxInstallPolicy
(SandboxPackageInfo modifiedDeps otherDeps allSandboxPkgs _allDeps)
params
= addPreferences [ PackageInstalledPreference n PreferInstalled
| n <- installedNotModified ]
. addTargets installedNotModified
. addPreferences
[ PackageVersionPreference (packageName pkg)
(thisVersion (packageVersion pkg)) | pkg <- otherDeps ]
. addConstraints
[ let pc = PackageConstraintVersion (packageName pkg)
(thisVersion (packageVersion pkg))
in LabeledPackageConstraint pc ConstraintSourceModifiedAddSourceDep
| pkg <- modifiedDeps ]
. addTargets [ packageName pkg | pkg <- modifiedDeps ]
. hideInstalledPackagesSpecificBySourcePackageId
[ packageId pkg | pkg <- modifiedDeps ]
We do n't need to add source packages for add - source to the
-- 'installedPkgIndex' since 'getSourcePackages' did that for us.
$ params
where
installedPkgIds =
map fst . InstalledPackageIndex.allPackagesBySourcePackageId
$ allSandboxPkgs
modifiedPkgIds = map packageId modifiedDeps
installedNotModified = [ packageName pkg | pkg <- installedPkgIds,
pkg `notElem` modifiedPkgIds ]
-- ------------------------------------------------------------
-- * Interface to the standard resolver
-- ------------------------------------------------------------
chooseSolver :: Verbosity -> PreSolver -> CompilerInfo -> IO Solver
chooseSolver verbosity preSolver _cinfo =
case preSolver of
AlwaysTopDown -> do
warn verbosity "Topdown solver is deprecated"
return TopDown
AlwaysModular -> do
return Modular
Choose -> do
info verbosity "Choosing modular solver."
return Modular
runSolver :: Solver -> SolverConfig -> DependencyResolver
runSolver TopDown = const topDownResolver -- TODO: warn about unsupported options
runSolver Modular = modularResolver
-- | Run the dependency solver.
--
-- Since this is potentially an expensive operation, the result is wrapped in a
-- a 'Progress' structure that can be unfolded to provide progress information,
-- logging messages and the final result or an error.
--
resolveDependencies :: Platform
-> CompilerInfo
-> PkgConfigDb
-> Solver
-> DepResolverParams
-> Progress String String InstallPlan
--TODO: is this needed here? see dontUpgradeNonUpgradeablePackages
resolveDependencies platform comp _pkgConfigDB _solver params
| null (depResolverTargets params)
= return (validateSolverResult platform comp indGoals [])
where
indGoals = depResolverIndependentGoals params
resolveDependencies platform comp pkgConfigDB solver params =
Step (showDepResolverParams finalparams)
$ fmap (validateSolverResult platform comp indGoals)
$ runSolver solver (SolverConfig reorderGoals indGoals noReinstalls
shadowing strFlags maxBkjumps)
platform comp installedPkgIndex sourcePkgIndex
pkgConfigDB preferences constraints targets
where
finalparams @ (DepResolverParams
targets constraints
prefs defpref
installedPkgIndex
sourcePkgIndex
reorderGoals
indGoals
noReinstalls
shadowing
strFlags
maxBkjumps) = dontUpgradeNonUpgradeablePackages
-- TODO:
-- The modular solver can properly deal with broken
-- packages and won't select them. So the
-- 'hideBrokenInstalledPackages' function should be moved
-- into a module that is specific to the top-down solver.
. (if solver /= Modular then hideBrokenInstalledPackages
else id)
$ params
preferences = interpretPackagesPreference
(Set.fromList targets) defpref prefs
-- | Give an interpretation to the global 'PackagesPreference' as
specific per - package ' ' .
--
interpretPackagesPreference :: Set PackageName
-> PackagesPreferenceDefault
-> [PackagePreference]
-> (PackageName -> PackagePreferences)
interpretPackagesPreference selected defaultPref prefs =
\pkgname -> PackagePreferences (versionPref pkgname)
(installPref pkgname)
(stanzasPref pkgname)
where
versionPref pkgname =
fromMaybe [anyVersion] (Map.lookup pkgname versionPrefs)
versionPrefs = Map.fromListWith (++)
[(pkgname, [pref])
| PackageVersionPreference pkgname pref <- prefs]
installPref pkgname =
fromMaybe (installPrefDefault pkgname) (Map.lookup pkgname installPrefs)
installPrefs = Map.fromList
[ (pkgname, pref)
| PackageInstalledPreference pkgname pref <- prefs ]
installPrefDefault = case defaultPref of
PreferAllLatest -> const PreferLatest
PreferAllInstalled -> const PreferInstalled
PreferLatestForSelected -> \pkgname ->
-- When you say cabal install foo, what you really mean is, prefer the
-- latest version of foo, but the installed version of everything else
if pkgname `Set.member` selected then PreferLatest
else PreferInstalled
stanzasPref pkgname =
fromMaybe [] (Map.lookup pkgname stanzasPrefs)
stanzasPrefs = Map.fromListWith (\a b -> nub (a ++ b))
[ (pkgname, pref)
| PackageStanzasPreference pkgname pref <- prefs ]
-- ------------------------------------------------------------
-- * Checking the result of the solver
-- ------------------------------------------------------------
| Make an install plan from the output of the dep resolver .
It checks that the plan is valid , or it 's an error in the dep resolver .
--
validateSolverResult :: Platform
-> CompilerInfo
-> Bool
-> [ResolverPackage]
-> InstallPlan
validateSolverResult platform comp indepGoals pkgs =
case planPackagesProblems platform comp pkgs of
[] -> case InstallPlan.new indepGoals index of
Right plan -> plan
Left problems -> error (formatPlanProblems problems)
problems -> error (formatPkgProblems problems)
where
index = InstalledPackageIndex.fromList (map toPlanPackage pkgs)
toPlanPackage (PreExisting pkg) = InstallPlan.PreExisting pkg
toPlanPackage (Configured pkg) = InstallPlan.Configured pkg
formatPkgProblems = formatProblemMessage . map showPlanPackageProblem
formatPlanProblems = formatProblemMessage . map InstallPlan.showPlanProblem
formatProblemMessage problems =
unlines $
"internal error: could not construct a valid install plan."
: "The proposed (invalid) plan contained the following problems:"
: problems
++ "Proposed plan:"
: [InstallPlan.showPlanIndex index]
data PlanPackageProblem =
InvalidConfiguredPackage ConfiguredPackage [PackageProblem]
showPlanPackageProblem :: PlanPackageProblem -> String
showPlanPackageProblem (InvalidConfiguredPackage pkg packageProblems) =
"Package " ++ display (packageId pkg)
++ " has an invalid configuration, in particular:\n"
++ unlines [ " " ++ showPackageProblem problem
| problem <- packageProblems ]
planPackagesProblems :: Platform -> CompilerInfo
-> [ResolverPackage]
-> [PlanPackageProblem]
planPackagesProblems platform cinfo pkgs =
[ InvalidConfiguredPackage pkg packageProblems
| Configured pkg <- pkgs
, let packageProblems = configuredPackageProblems platform cinfo pkg
, not (null packageProblems) ]
data PackageProblem = DuplicateFlag PD.FlagName
| MissingFlag PD.FlagName
| ExtraFlag PD.FlagName
| DuplicateDeps [PackageId]
| MissingDep Dependency
| ExtraDep PackageId
| InvalidDep Dependency PackageId
showPackageProblem :: PackageProblem -> String
showPackageProblem (DuplicateFlag (PD.FlagName flag)) =
"duplicate flag in the flag assignment: " ++ flag
showPackageProblem (MissingFlag (PD.FlagName flag)) =
"missing an assignment for the flag: " ++ flag
showPackageProblem (ExtraFlag (PD.FlagName flag)) =
"extra flag given that is not used by the package: " ++ flag
showPackageProblem (DuplicateDeps pkgids) =
"duplicate packages specified as selected dependencies: "
++ intercalate ", " (map display pkgids)
showPackageProblem (MissingDep dep) =
"the package has a dependency " ++ display dep
++ " but no package has been selected to satisfy it."
showPackageProblem (ExtraDep pkgid) =
"the package configuration specifies " ++ display pkgid
++ " but (with the given flag assignment) the package does not actually"
++ " depend on any version of that package."
showPackageProblem (InvalidDep dep pkgid) =
"the package depends on " ++ display dep
++ " but the configuration specifies " ++ display pkgid
++ " which does not satisfy the dependency."
-- | A 'ConfiguredPackage' is valid if the flag assignment is total and if
-- in the configuration given by the flag assignment, all the package
-- dependencies are satisfied by the specified packages.
--
configuredPackageProblems :: Platform -> CompilerInfo
-> ConfiguredPackage -> [PackageProblem]
configuredPackageProblems platform cinfo
(ConfiguredPackage pkg specifiedFlags stanzas specifiedDeps') =
[ DuplicateFlag flag | ((flag,_):_) <- duplicates specifiedFlags ]
++ [ MissingFlag flag | OnlyInLeft flag <- mergedFlags ]
++ [ ExtraFlag flag | OnlyInRight flag <- mergedFlags ]
++ [ DuplicateDeps pkgs
| pkgs <- CD.nonSetupDeps (fmap (duplicatesBy (comparing packageName))
specifiedDeps) ]
++ [ MissingDep dep | OnlyInLeft dep <- mergedDeps ]
++ [ ExtraDep pkgid | OnlyInRight pkgid <- mergedDeps ]
++ [ InvalidDep dep pkgid | InBoth dep pkgid <- mergedDeps
, not (packageSatisfiesDependency pkgid dep) ]
where
specifiedDeps :: ComponentDeps [PackageId]
specifiedDeps = fmap (map confSrcId) specifiedDeps'
mergedFlags = mergeBy compare
(sort $ map PD.flagName (PD.genPackageFlags (packageDescription pkg)))
(sort $ map fst specifiedFlags)
packageSatisfiesDependency
(PackageIdentifier name version)
(Dependency name' versionRange) = assert (name == name') $
version `withinRange` versionRange
dependencyName (Dependency name _) = name
mergedDeps :: [MergeResult Dependency PackageId]
mergedDeps = mergeDeps requiredDeps (CD.flatDeps specifiedDeps)
mergeDeps :: [Dependency] -> [PackageId]
-> [MergeResult Dependency PackageId]
mergeDeps required specified =
let sortNubOn f = nubBy ((==) `on` f) . sortBy (compare `on` f) in
mergeBy
(\dep pkgid -> dependencyName dep `compare` packageName pkgid)
(sortNubOn dependencyName required)
(sortNubOn packageName specified)
TODO : It would be nicer to use ComponentDeps here so we can be more
-- precise in our checks. That's a bit tricky though, as this currently
relies on the ' buildDepends ' field of ' PackageDescription ' . ( OTOH , that
-- field is deprecated and should be removed anyway.) As long as we _do_
-- use a flat list here, we have to allow for duplicates when we fold
specifiedDeps ; once we have proper ComponentDeps here we should get rid
of the ` nubOn ` in ` mergeDeps ` .
requiredDeps :: [Dependency]
requiredDeps =
--TODO: use something lower level than finalizePackageDescription
case finalizePackageDescription specifiedFlags
(const True)
platform cinfo
[]
(enableStanzas stanzas $ packageDescription pkg) of
Right (resolvedPkg, _) ->
externalBuildDepends resolvedPkg
++ maybe [] PD.setupDepends (PD.setupBuildInfo resolvedPkg)
Left _ ->
error "configuredPackageInvalidDeps internal error"
-- ------------------------------------------------------------
-- * Simple resolver that ignores dependencies
-- ------------------------------------------------------------
-- | A simplistic method of resolving a list of target package names to
-- available packages.
--
-- Specifically, it does not consider package dependencies at all. Unlike
-- 'resolveDependencies', no attempt is made to ensure that the selected
-- packages have dependencies that are satisfiable or consistent with
-- each other.
--
-- It is suitable for tasks such as selecting packages to download for user
-- inspection. It is not suitable for selecting packages to install.
--
Note : if no installed package index is available , it is OK to pass ' ' .
-- It simply means preferences for installed packages will be ignored.
--
resolveWithoutDependencies :: DepResolverParams
-> Either [ResolveNoDepsError] [SourcePackage]
resolveWithoutDependencies (DepResolverParams targets constraints
prefs defpref installedPkgIndex sourcePkgIndex
_reorderGoals _indGoals _avoidReinstalls
_shadowing _strFlags _maxBjumps) =
collectEithers (map selectPackage targets)
where
selectPackage :: PackageName -> Either ResolveNoDepsError SourcePackage
selectPackage pkgname
| null choices = Left $! ResolveUnsatisfiable pkgname requiredVersions
| otherwise = Right $! maximumBy bestByPrefs choices
where
-- Constraints
requiredVersions = packageConstraints pkgname
pkgDependency = Dependency pkgname requiredVersions
choices = PackageIndex.lookupDependency sourcePkgIndex
pkgDependency
-- Preferences
PackagePreferences preferredVersions preferInstalled _
= packagePreferences pkgname
bestByPrefs = comparing $ \pkg ->
(installPref pkg, versionPref pkg, packageVersion pkg)
installPref = case preferInstalled of
PreferLatest -> const False
PreferInstalled -> not . null
. InstalledPackageIndex.lookupSourcePackageId
installedPkgIndex
. packageId
versionPref pkg = length . filter (packageVersion pkg `withinRange`) $
preferredVersions
packageConstraints :: PackageName -> VersionRange
packageConstraints pkgname =
Map.findWithDefault anyVersion pkgname packageVersionConstraintMap
packageVersionConstraintMap =
let pcs = map unlabelPackageConstraint constraints
in Map.fromList [ (name, range)
| PackageConstraintVersion name range <- pcs ]
packagePreferences :: PackageName -> PackagePreferences
packagePreferences = interpretPackagesPreference
(Set.fromList targets) defpref prefs
collectEithers :: [Either a b] -> Either [a] [b]
collectEithers = collect . partitionEithers
where
collect ([], xs) = Right xs
collect (errs,_) = Left errs
partitionEithers :: [Either a b] -> ([a],[b])
partitionEithers = foldr (either left right) ([],[])
where
left a (l, r) = (a:l, r)
right a (l, r) = (l, a:r)
-- | Errors for 'resolveWithoutDependencies'.
--
data ResolveNoDepsError =
-- | A package name which cannot be resolved to a specific package.
-- Also gives the constraint on the version and whether there was
-- a constraint on the package being installed.
ResolveUnsatisfiable PackageName VersionRange
instance Show ResolveNoDepsError where
show (ResolveUnsatisfiable name ver) =
"There is no available version of " ++ display name
++ " that satisfies " ++ display (simplifyVersionRange ver)
| null | https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal-next/cabal-install/Distribution/Client/Dependency.hs | haskell | ---------------------------------------------------------------------------
|
Module : Distribution.Client.Dependency
License : BSD-like
Maintainer :
Stability : provisional
Portability : portable
Top level interface to dependency resolution.
---------------------------------------------------------------------------
* The main package dependency resolver
* Alternate, simple resolver that does not do dependencies recursively
* Constructing resolver policies
** Standard policy
** Extra policy options
** Policy utils
------------------------------------------------------------
* High level planner policy
------------------------------------------------------------
| The set of parameters to the dependency resolver. These parameters are
relatively low level but many kinds of high level policies can be
implemented in terms of adjustments to the parameters.
| A package selection preference for a particular package.
Preferences are soft constraints that the dependency resolver should try to
respect where possible. It is not specified if preferences on some packages
are more important than others.
| A suggested constraint on the version number.
| If we prefer versions of packages that are already installed.
| If we would prefer to enable these optional stanzas
(i.e. test suites and/or benchmarks)
| Provide a textual representation of a package preference
for debugging purposes.
| Some packages are specific to a given compiler version and should never be
upgraded.
TODO: the top down resolver chokes on the base constraints
below when there are no targets and thus no dep on base.
Need to refactor constraints separate from needing packages.
TODO: this should work using exclude constraints instead
TODO: this should work using exclude constraints instead
TODO: this should work using exclude constraints instead
| Remove upper bounds in dependencies using the policy specified by the
'AllowNewer' argument (all/some/none).
Note: It's important to apply 'removeUpperBounds' after
'addSourcePackages'. Otherwise, the packages inserted by
'addSourcePackages' won't have upper bounds in dependencies relaxed.
| Supply defaults for packages without explicit Setup dependencies
Note: It's important to apply 'addDefaultSetupDepends' after
'addSourcePackages'. Otherwise, the packages inserted by
'addSourcePackages' won't have upper bounds in dependencies relaxed.
Does this package contain any components with non-empty 'build-depends'
and a 'buildable' field that could potentially be set to 'False'? False
positives are possible.
'installedPkgIndex' since 'getSourcePackages' did that for us.
------------------------------------------------------------
* Interface to the standard resolver
------------------------------------------------------------
TODO: warn about unsupported options
| Run the dependency solver.
Since this is potentially an expensive operation, the result is wrapped in a
a 'Progress' structure that can be unfolded to provide progress information,
logging messages and the final result or an error.
TODO: is this needed here? see dontUpgradeNonUpgradeablePackages
TODO:
The modular solver can properly deal with broken
packages and won't select them. So the
'hideBrokenInstalledPackages' function should be moved
into a module that is specific to the top-down solver.
| Give an interpretation to the global 'PackagesPreference' as
When you say cabal install foo, what you really mean is, prefer the
latest version of foo, but the installed version of everything else
------------------------------------------------------------
* Checking the result of the solver
------------------------------------------------------------
| A 'ConfiguredPackage' is valid if the flag assignment is total and if
in the configuration given by the flag assignment, all the package
dependencies are satisfied by the specified packages.
precise in our checks. That's a bit tricky though, as this currently
field is deprecated and should be removed anyway.) As long as we _do_
use a flat list here, we have to allow for duplicates when we fold
TODO: use something lower level than finalizePackageDescription
------------------------------------------------------------
* Simple resolver that ignores dependencies
------------------------------------------------------------
| A simplistic method of resolving a list of target package names to
available packages.
Specifically, it does not consider package dependencies at all. Unlike
'resolveDependencies', no attempt is made to ensure that the selected
packages have dependencies that are satisfiable or consistent with
each other.
It is suitable for tasks such as selecting packages to download for user
inspection. It is not suitable for selecting packages to install.
It simply means preferences for installed packages will be ignored.
Constraints
Preferences
| Errors for 'resolveWithoutDependencies'.
| A package name which cannot be resolved to a specific package.
Also gives the constraint on the version and whether there was
a constraint on the package being installed. | Copyright : ( c ) 2005 ,
2007
2008
module Distribution.Client.Dependency (
chooseSolver,
resolveDependencies,
Progress(..),
foldProgress,
resolveWithoutDependencies,
DepResolverParams(..),
PackageConstraint(..),
PackagesPreferenceDefault(..),
PackagePreference(..),
InstalledPreference(..),
standardInstallPolicy,
PackageSpecifier(..),
* * Sandbox policy
applySandboxInstallPolicy,
dontUpgradeNonUpgradeablePackages,
hideBrokenInstalledPackages,
upgradeDependencies,
reinstallTargets,
addConstraints,
addPreferences,
setPreferenceDefault,
setReorderGoals,
setIndependentGoals,
setAvoidReinstalls,
setShadowPkgs,
setStrongFlags,
setMaxBackjumps,
addSourcePackages,
hideInstalledPackagesSpecificByUnitId,
hideInstalledPackagesSpecificBySourcePackageId,
hideInstalledPackagesAllVersions,
removeUpperBounds,
addDefaultSetupDependencies,
) where
import Distribution.Client.Dependency.TopDown
( topDownResolver )
import Distribution.Client.Dependency.Modular
( modularResolver, SolverConfig(..) )
import qualified Distribution.Client.PackageIndex as PackageIndex
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Client.InstallPlan (InstallPlan)
import Distribution.Client.PkgConfigDb (PkgConfigDb)
import Distribution.Client.Types
( SourcePackageDb(SourcePackageDb), SourcePackage(..)
, ConfiguredPackage(..), ConfiguredId(..)
, OptionalStanza(..), enableStanzas )
import Distribution.Client.Dependency.Types
( PreSolver(..), Solver(..), DependencyResolver, ResolverPackage(..)
, PackageConstraint(..), showPackageConstraint
, LabeledPackageConstraint(..), unlabelPackageConstraint
, ConstraintSource(..), showConstraintSource
, PackagePreferences(..), InstalledPreference(..)
, PackagesPreferenceDefault(..)
, Progress(..), foldProgress )
import Distribution.Client.Sandbox.Types
( SandboxPackageInfo(..) )
import Distribution.Client.Targets
import Distribution.Client.ComponentDeps (ComponentDeps)
import qualified Distribution.Client.ComponentDeps as CD
import qualified Distribution.InstalledPackageInfo as Installed
import Distribution.Package
( PackageName(..), PackageIdentifier(PackageIdentifier), PackageId
, Package(..), packageName, packageVersion
, UnitId, Dependency(Dependency))
import qualified Distribution.PackageDescription as PD
import qualified Distribution.PackageDescription.Configuration as PD
import Distribution.PackageDescription.Configuration
( finalizePackageDescription )
import Distribution.Client.PackageUtils
( externalBuildDepends )
import Distribution.Version
( VersionRange, Version(..), anyVersion, orLaterVersion, thisVersion
, withinRange, simplifyVersionRange )
import Distribution.Compiler
( CompilerInfo(..) )
import Distribution.System
( Platform )
import Distribution.Client.Utils
( duplicates, duplicatesBy, mergeBy, MergeResult(..) )
import Distribution.Simple.Utils
( comparing, warn, info )
import Distribution.Simple.Configure
( relaxPackageDeps )
import Distribution.Simple.Setup
( AllowNewer(..) )
import Distribution.Text
( display )
import Distribution.Verbosity
( Verbosity )
import Data.List
( foldl', sort, sortBy, nubBy, maximumBy, intercalate, nub )
import Data.Function (on)
import Data.Maybe (fromMaybe)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Set (Set)
import Control.Exception
( assert )
data DepResolverParams = DepResolverParams {
depResolverTargets :: [PackageName],
depResolverConstraints :: [LabeledPackageConstraint],
depResolverPreferences :: [PackagePreference],
depResolverPreferenceDefault :: PackagesPreferenceDefault,
depResolverInstalledPkgIndex :: InstalledPackageIndex,
depResolverSourcePkgIndex :: PackageIndex.PackageIndex SourcePackage,
depResolverReorderGoals :: Bool,
depResolverIndependentGoals :: Bool,
depResolverAvoidReinstalls :: Bool,
depResolverShadowPkgs :: Bool,
depResolverStrongFlags :: Bool,
depResolverMaxBackjumps :: Maybe Int
}
showDepResolverParams :: DepResolverParams -> String
showDepResolverParams p =
"targets: " ++ intercalate ", " (map display (depResolverTargets p))
++ "\nconstraints: "
++ concatMap (("\n " ++) . showLabeledConstraint)
(depResolverConstraints p)
++ "\npreferences: "
++ concatMap (("\n " ++) . showPackagePreference)
(depResolverPreferences p)
++ "\nstrategy: " ++ show (depResolverPreferenceDefault p)
++ "\nreorder goals: " ++ show (depResolverReorderGoals p)
++ "\nindependent goals: " ++ show (depResolverIndependentGoals p)
++ "\navoid reinstalls: " ++ show (depResolverAvoidReinstalls p)
++ "\nshadow packages: " ++ show (depResolverShadowPkgs p)
++ "\nstrong flags: " ++ show (depResolverStrongFlags p)
++ "\nmax backjumps: " ++ maybe "infinite" show
(depResolverMaxBackjumps p)
where
showLabeledConstraint :: LabeledPackageConstraint -> String
showLabeledConstraint (LabeledPackageConstraint pc src) =
showPackageConstraint pc ++ " (" ++ showConstraintSource src ++ ")"
data PackagePreference =
PackageVersionPreference PackageName VersionRange
| PackageInstalledPreference PackageName InstalledPreference
| PackageStanzasPreference PackageName [OptionalStanza]
showPackagePreference :: PackagePreference -> String
showPackagePreference (PackageVersionPreference pn vr) =
display pn ++ " " ++ display (simplifyVersionRange vr)
showPackagePreference (PackageInstalledPreference pn ip) =
display pn ++ " " ++ show ip
showPackagePreference (PackageStanzasPreference pn st) =
display pn ++ " " ++ show st
basicDepResolverParams :: InstalledPackageIndex
-> PackageIndex.PackageIndex SourcePackage
-> DepResolverParams
basicDepResolverParams installedPkgIndex sourcePkgIndex =
DepResolverParams {
depResolverTargets = [],
depResolverConstraints = [],
depResolverPreferences = [],
depResolverPreferenceDefault = PreferLatestForSelected,
depResolverInstalledPkgIndex = installedPkgIndex,
depResolverSourcePkgIndex = sourcePkgIndex,
depResolverReorderGoals = False,
depResolverIndependentGoals = False,
depResolverAvoidReinstalls = False,
depResolverShadowPkgs = False,
depResolverStrongFlags = False,
depResolverMaxBackjumps = Nothing
}
addTargets :: [PackageName]
-> DepResolverParams -> DepResolverParams
addTargets extraTargets params =
params {
depResolverTargets = extraTargets ++ depResolverTargets params
}
addConstraints :: [LabeledPackageConstraint]
-> DepResolverParams -> DepResolverParams
addConstraints extraConstraints params =
params {
depResolverConstraints = extraConstraints
++ depResolverConstraints params
}
addPreferences :: [PackagePreference]
-> DepResolverParams -> DepResolverParams
addPreferences extraPreferences params =
params {
depResolverPreferences = extraPreferences
++ depResolverPreferences params
}
setPreferenceDefault :: PackagesPreferenceDefault
-> DepResolverParams -> DepResolverParams
setPreferenceDefault preferenceDefault params =
params {
depResolverPreferenceDefault = preferenceDefault
}
setReorderGoals :: Bool -> DepResolverParams -> DepResolverParams
setReorderGoals b params =
params {
depResolverReorderGoals = b
}
setIndependentGoals :: Bool -> DepResolverParams -> DepResolverParams
setIndependentGoals b params =
params {
depResolverIndependentGoals = b
}
setAvoidReinstalls :: Bool -> DepResolverParams -> DepResolverParams
setAvoidReinstalls b params =
params {
depResolverAvoidReinstalls = b
}
setShadowPkgs :: Bool -> DepResolverParams -> DepResolverParams
setShadowPkgs b params =
params {
depResolverShadowPkgs = b
}
setStrongFlags :: Bool -> DepResolverParams -> DepResolverParams
setStrongFlags b params =
params {
depResolverStrongFlags = b
}
setMaxBackjumps :: Maybe Int -> DepResolverParams -> DepResolverParams
setMaxBackjumps n params =
params {
depResolverMaxBackjumps = n
}
dontUpgradeNonUpgradeablePackages :: DepResolverParams -> DepResolverParams
dontUpgradeNonUpgradeablePackages params =
addConstraints extraConstraints params
where
extraConstraints =
[ LabeledPackageConstraint
(PackageConstraintInstalled pkgname)
ConstraintSourceNonUpgradeablePackage
| notElem (PackageName "base") (depResolverTargets params)
, pkgname <- map PackageName [ "base", "ghc-prim", "integer-gmp"
, "integer-simple" ]
, isInstalled pkgname ]
isInstalled = not . null
. InstalledPackageIndex.lookupPackageName
(depResolverInstalledPkgIndex params)
addSourcePackages :: [SourcePackage]
-> DepResolverParams -> DepResolverParams
addSourcePackages pkgs params =
params {
depResolverSourcePkgIndex =
foldl (flip PackageIndex.insert)
(depResolverSourcePkgIndex params) pkgs
}
hideInstalledPackagesSpecificByUnitId :: [UnitId]
-> DepResolverParams
-> DepResolverParams
hideInstalledPackagesSpecificByUnitId pkgids params =
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deleteUnitId)
(depResolverInstalledPkgIndex params) pkgids
}
hideInstalledPackagesSpecificBySourcePackageId :: [PackageId]
-> DepResolverParams
-> DepResolverParams
hideInstalledPackagesSpecificBySourcePackageId pkgids params =
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deleteSourcePackageId)
(depResolverInstalledPkgIndex params) pkgids
}
hideInstalledPackagesAllVersions :: [PackageName]
-> DepResolverParams -> DepResolverParams
hideInstalledPackagesAllVersions pkgnames params =
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deletePackageName)
(depResolverInstalledPkgIndex params) pkgnames
}
hideBrokenInstalledPackages :: DepResolverParams -> DepResolverParams
hideBrokenInstalledPackages params =
hideInstalledPackagesSpecificByUnitId pkgids params
where
pkgids = map Installed.installedUnitId
. InstalledPackageIndex.reverseDependencyClosure
(depResolverInstalledPkgIndex params)
. map (Installed.installedUnitId . fst)
. InstalledPackageIndex.brokenPackages
$ depResolverInstalledPkgIndex params
removeUpperBounds :: AllowNewer -> DepResolverParams -> DepResolverParams
removeUpperBounds AllowNewerNone params = params
removeUpperBounds allowNewer params =
params {
depResolverSourcePkgIndex = sourcePkgIndex'
}
where
sourcePkgIndex' = fmap relaxDeps $ depResolverSourcePkgIndex params
relaxDeps :: SourcePackage -> SourcePackage
relaxDeps srcPkg = srcPkg {
packageDescription = relaxPackageDeps allowNewer
(packageDescription srcPkg)
}
addDefaultSetupDependencies :: (SourcePackage -> Maybe [Dependency])
-> DepResolverParams -> DepResolverParams
addDefaultSetupDependencies defaultSetupDeps params =
params {
depResolverSourcePkgIndex =
fmap applyDefaultSetupDeps (depResolverSourcePkgIndex params)
}
where
applyDefaultSetupDeps :: SourcePackage -> SourcePackage
applyDefaultSetupDeps srcpkg =
srcpkg {
packageDescription = gpkgdesc {
PD.packageDescription = pkgdesc {
PD.setupBuildInfo =
case PD.setupBuildInfo pkgdesc of
Just sbi -> Just sbi
Nothing -> case defaultSetupDeps srcpkg of
Nothing -> Nothing
Just deps -> Just PD.SetupBuildInfo {
PD.defaultSetupDepends = True,
PD.setupDepends = deps
}
}
}
}
where
gpkgdesc = packageDescription srcpkg
pkgdesc = PD.packageDescription gpkgdesc
upgradeDependencies :: DepResolverParams -> DepResolverParams
upgradeDependencies = setPreferenceDefault PreferAllLatest
reinstallTargets :: DepResolverParams -> DepResolverParams
reinstallTargets params =
hideInstalledPackagesAllVersions (depResolverTargets params) params
standardInstallPolicy :: InstalledPackageIndex
-> SourcePackageDb
-> [PackageSpecifier SourcePackage]
-> DepResolverParams
standardInstallPolicy
installedPkgIndex (SourcePackageDb sourcePkgIndex sourcePkgPrefs)
pkgSpecifiers
= addPreferences
[ PackageVersionPreference name ver
| (name, ver) <- Map.toList sourcePkgPrefs ]
. addConstraints
(concatMap pkgSpecifierConstraints pkgSpecifiers)
. addTargets
(map pkgSpecifierTarget pkgSpecifiers)
. hideInstalledPackagesSpecificBySourcePackageId
[ packageId pkg | SpecificSourcePackage pkg <- pkgSpecifiers ]
. addDefaultSetupDependencies mkDefaultSetupDeps
. addSourcePackages
[ pkg | SpecificSourcePackage pkg <- pkgSpecifiers ]
$ basicDepResolverParams
installedPkgIndex sourcePkgIndex
where
Force Cabal > = 1.24 dep when the package is affected by # 3199 .
mkDefaultSetupDeps :: SourcePackage -> Maybe [Dependency]
mkDefaultSetupDeps srcpkg | affected =
Just [Dependency (PackageName "Cabal")
(orLaterVersion $ Version [1,24] [])]
| otherwise = Nothing
where
gpkgdesc = packageDescription srcpkg
pkgdesc = PD.packageDescription gpkgdesc
bt = fromMaybe PD.Custom (PD.buildType pkgdesc)
affected = bt == PD.Custom && hasBuildableFalse gpkgdesc
hasBuildableFalse :: PD.GenericPackageDescription -> Bool
hasBuildableFalse gpkg =
not (all alwaysTrue (zipWith PD.cOr buildableConditions noDepConditions))
where
buildableConditions = PD.extractConditions PD.buildable gpkg
noDepConditions = PD.extractConditions
(null . PD.targetBuildDepends) gpkg
alwaysTrue (PD.Lit True) = True
alwaysTrue _ = False
applySandboxInstallPolicy :: SandboxPackageInfo
-> DepResolverParams
-> DepResolverParams
applySandboxInstallPolicy
(SandboxPackageInfo modifiedDeps otherDeps allSandboxPkgs _allDeps)
params
= addPreferences [ PackageInstalledPreference n PreferInstalled
| n <- installedNotModified ]
. addTargets installedNotModified
. addPreferences
[ PackageVersionPreference (packageName pkg)
(thisVersion (packageVersion pkg)) | pkg <- otherDeps ]
. addConstraints
[ let pc = PackageConstraintVersion (packageName pkg)
(thisVersion (packageVersion pkg))
in LabeledPackageConstraint pc ConstraintSourceModifiedAddSourceDep
| pkg <- modifiedDeps ]
. addTargets [ packageName pkg | pkg <- modifiedDeps ]
. hideInstalledPackagesSpecificBySourcePackageId
[ packageId pkg | pkg <- modifiedDeps ]
We do n't need to add source packages for add - source to the
$ params
where
installedPkgIds =
map fst . InstalledPackageIndex.allPackagesBySourcePackageId
$ allSandboxPkgs
modifiedPkgIds = map packageId modifiedDeps
installedNotModified = [ packageName pkg | pkg <- installedPkgIds,
pkg `notElem` modifiedPkgIds ]
chooseSolver :: Verbosity -> PreSolver -> CompilerInfo -> IO Solver
chooseSolver verbosity preSolver _cinfo =
case preSolver of
AlwaysTopDown -> do
warn verbosity "Topdown solver is deprecated"
return TopDown
AlwaysModular -> do
return Modular
Choose -> do
info verbosity "Choosing modular solver."
return Modular
runSolver :: Solver -> SolverConfig -> DependencyResolver
runSolver Modular = modularResolver
resolveDependencies :: Platform
-> CompilerInfo
-> PkgConfigDb
-> Solver
-> DepResolverParams
-> Progress String String InstallPlan
resolveDependencies platform comp _pkgConfigDB _solver params
| null (depResolverTargets params)
= return (validateSolverResult platform comp indGoals [])
where
indGoals = depResolverIndependentGoals params
resolveDependencies platform comp pkgConfigDB solver params =
Step (showDepResolverParams finalparams)
$ fmap (validateSolverResult platform comp indGoals)
$ runSolver solver (SolverConfig reorderGoals indGoals noReinstalls
shadowing strFlags maxBkjumps)
platform comp installedPkgIndex sourcePkgIndex
pkgConfigDB preferences constraints targets
where
finalparams @ (DepResolverParams
targets constraints
prefs defpref
installedPkgIndex
sourcePkgIndex
reorderGoals
indGoals
noReinstalls
shadowing
strFlags
maxBkjumps) = dontUpgradeNonUpgradeablePackages
. (if solver /= Modular then hideBrokenInstalledPackages
else id)
$ params
preferences = interpretPackagesPreference
(Set.fromList targets) defpref prefs
specific per - package ' ' .
interpretPackagesPreference :: Set PackageName
-> PackagesPreferenceDefault
-> [PackagePreference]
-> (PackageName -> PackagePreferences)
interpretPackagesPreference selected defaultPref prefs =
\pkgname -> PackagePreferences (versionPref pkgname)
(installPref pkgname)
(stanzasPref pkgname)
where
versionPref pkgname =
fromMaybe [anyVersion] (Map.lookup pkgname versionPrefs)
versionPrefs = Map.fromListWith (++)
[(pkgname, [pref])
| PackageVersionPreference pkgname pref <- prefs]
installPref pkgname =
fromMaybe (installPrefDefault pkgname) (Map.lookup pkgname installPrefs)
installPrefs = Map.fromList
[ (pkgname, pref)
| PackageInstalledPreference pkgname pref <- prefs ]
installPrefDefault = case defaultPref of
PreferAllLatest -> const PreferLatest
PreferAllInstalled -> const PreferInstalled
PreferLatestForSelected -> \pkgname ->
if pkgname `Set.member` selected then PreferLatest
else PreferInstalled
stanzasPref pkgname =
fromMaybe [] (Map.lookup pkgname stanzasPrefs)
stanzasPrefs = Map.fromListWith (\a b -> nub (a ++ b))
[ (pkgname, pref)
| PackageStanzasPreference pkgname pref <- prefs ]
| Make an install plan from the output of the dep resolver .
It checks that the plan is valid , or it 's an error in the dep resolver .
validateSolverResult :: Platform
-> CompilerInfo
-> Bool
-> [ResolverPackage]
-> InstallPlan
validateSolverResult platform comp indepGoals pkgs =
case planPackagesProblems platform comp pkgs of
[] -> case InstallPlan.new indepGoals index of
Right plan -> plan
Left problems -> error (formatPlanProblems problems)
problems -> error (formatPkgProblems problems)
where
index = InstalledPackageIndex.fromList (map toPlanPackage pkgs)
toPlanPackage (PreExisting pkg) = InstallPlan.PreExisting pkg
toPlanPackage (Configured pkg) = InstallPlan.Configured pkg
formatPkgProblems = formatProblemMessage . map showPlanPackageProblem
formatPlanProblems = formatProblemMessage . map InstallPlan.showPlanProblem
formatProblemMessage problems =
unlines $
"internal error: could not construct a valid install plan."
: "The proposed (invalid) plan contained the following problems:"
: problems
++ "Proposed plan:"
: [InstallPlan.showPlanIndex index]
data PlanPackageProblem =
InvalidConfiguredPackage ConfiguredPackage [PackageProblem]
showPlanPackageProblem :: PlanPackageProblem -> String
showPlanPackageProblem (InvalidConfiguredPackage pkg packageProblems) =
"Package " ++ display (packageId pkg)
++ " has an invalid configuration, in particular:\n"
++ unlines [ " " ++ showPackageProblem problem
| problem <- packageProblems ]
planPackagesProblems :: Platform -> CompilerInfo
-> [ResolverPackage]
-> [PlanPackageProblem]
planPackagesProblems platform cinfo pkgs =
[ InvalidConfiguredPackage pkg packageProblems
| Configured pkg <- pkgs
, let packageProblems = configuredPackageProblems platform cinfo pkg
, not (null packageProblems) ]
data PackageProblem = DuplicateFlag PD.FlagName
| MissingFlag PD.FlagName
| ExtraFlag PD.FlagName
| DuplicateDeps [PackageId]
| MissingDep Dependency
| ExtraDep PackageId
| InvalidDep Dependency PackageId
showPackageProblem :: PackageProblem -> String
showPackageProblem (DuplicateFlag (PD.FlagName flag)) =
"duplicate flag in the flag assignment: " ++ flag
showPackageProblem (MissingFlag (PD.FlagName flag)) =
"missing an assignment for the flag: " ++ flag
showPackageProblem (ExtraFlag (PD.FlagName flag)) =
"extra flag given that is not used by the package: " ++ flag
showPackageProblem (DuplicateDeps pkgids) =
"duplicate packages specified as selected dependencies: "
++ intercalate ", " (map display pkgids)
showPackageProblem (MissingDep dep) =
"the package has a dependency " ++ display dep
++ " but no package has been selected to satisfy it."
showPackageProblem (ExtraDep pkgid) =
"the package configuration specifies " ++ display pkgid
++ " but (with the given flag assignment) the package does not actually"
++ " depend on any version of that package."
showPackageProblem (InvalidDep dep pkgid) =
"the package depends on " ++ display dep
++ " but the configuration specifies " ++ display pkgid
++ " which does not satisfy the dependency."
configuredPackageProblems :: Platform -> CompilerInfo
-> ConfiguredPackage -> [PackageProblem]
configuredPackageProblems platform cinfo
(ConfiguredPackage pkg specifiedFlags stanzas specifiedDeps') =
[ DuplicateFlag flag | ((flag,_):_) <- duplicates specifiedFlags ]
++ [ MissingFlag flag | OnlyInLeft flag <- mergedFlags ]
++ [ ExtraFlag flag | OnlyInRight flag <- mergedFlags ]
++ [ DuplicateDeps pkgs
| pkgs <- CD.nonSetupDeps (fmap (duplicatesBy (comparing packageName))
specifiedDeps) ]
++ [ MissingDep dep | OnlyInLeft dep <- mergedDeps ]
++ [ ExtraDep pkgid | OnlyInRight pkgid <- mergedDeps ]
++ [ InvalidDep dep pkgid | InBoth dep pkgid <- mergedDeps
, not (packageSatisfiesDependency pkgid dep) ]
where
specifiedDeps :: ComponentDeps [PackageId]
specifiedDeps = fmap (map confSrcId) specifiedDeps'
mergedFlags = mergeBy compare
(sort $ map PD.flagName (PD.genPackageFlags (packageDescription pkg)))
(sort $ map fst specifiedFlags)
packageSatisfiesDependency
(PackageIdentifier name version)
(Dependency name' versionRange) = assert (name == name') $
version `withinRange` versionRange
dependencyName (Dependency name _) = name
mergedDeps :: [MergeResult Dependency PackageId]
mergedDeps = mergeDeps requiredDeps (CD.flatDeps specifiedDeps)
mergeDeps :: [Dependency] -> [PackageId]
-> [MergeResult Dependency PackageId]
mergeDeps required specified =
let sortNubOn f = nubBy ((==) `on` f) . sortBy (compare `on` f) in
mergeBy
(\dep pkgid -> dependencyName dep `compare` packageName pkgid)
(sortNubOn dependencyName required)
(sortNubOn packageName specified)
TODO : It would be nicer to use ComponentDeps here so we can be more
relies on the ' buildDepends ' field of ' PackageDescription ' . ( OTOH , that
specifiedDeps ; once we have proper ComponentDeps here we should get rid
of the ` nubOn ` in ` mergeDeps ` .
requiredDeps :: [Dependency]
requiredDeps =
case finalizePackageDescription specifiedFlags
(const True)
platform cinfo
[]
(enableStanzas stanzas $ packageDescription pkg) of
Right (resolvedPkg, _) ->
externalBuildDepends resolvedPkg
++ maybe [] PD.setupDepends (PD.setupBuildInfo resolvedPkg)
Left _ ->
error "configuredPackageInvalidDeps internal error"
Note : if no installed package index is available , it is OK to pass ' ' .
resolveWithoutDependencies :: DepResolverParams
-> Either [ResolveNoDepsError] [SourcePackage]
resolveWithoutDependencies (DepResolverParams targets constraints
prefs defpref installedPkgIndex sourcePkgIndex
_reorderGoals _indGoals _avoidReinstalls
_shadowing _strFlags _maxBjumps) =
collectEithers (map selectPackage targets)
where
selectPackage :: PackageName -> Either ResolveNoDepsError SourcePackage
selectPackage pkgname
| null choices = Left $! ResolveUnsatisfiable pkgname requiredVersions
| otherwise = Right $! maximumBy bestByPrefs choices
where
requiredVersions = packageConstraints pkgname
pkgDependency = Dependency pkgname requiredVersions
choices = PackageIndex.lookupDependency sourcePkgIndex
pkgDependency
PackagePreferences preferredVersions preferInstalled _
= packagePreferences pkgname
bestByPrefs = comparing $ \pkg ->
(installPref pkg, versionPref pkg, packageVersion pkg)
installPref = case preferInstalled of
PreferLatest -> const False
PreferInstalled -> not . null
. InstalledPackageIndex.lookupSourcePackageId
installedPkgIndex
. packageId
versionPref pkg = length . filter (packageVersion pkg `withinRange`) $
preferredVersions
packageConstraints :: PackageName -> VersionRange
packageConstraints pkgname =
Map.findWithDefault anyVersion pkgname packageVersionConstraintMap
packageVersionConstraintMap =
let pcs = map unlabelPackageConstraint constraints
in Map.fromList [ (name, range)
| PackageConstraintVersion name range <- pcs ]
packagePreferences :: PackageName -> PackagePreferences
packagePreferences = interpretPackagesPreference
(Set.fromList targets) defpref prefs
collectEithers :: [Either a b] -> Either [a] [b]
collectEithers = collect . partitionEithers
where
collect ([], xs) = Right xs
collect (errs,_) = Left errs
partitionEithers :: [Either a b] -> ([a],[b])
partitionEithers = foldr (either left right) ([],[])
where
left a (l, r) = (a:l, r)
right a (l, r) = (l, a:r)
data ResolveNoDepsError =
ResolveUnsatisfiable PackageName VersionRange
instance Show ResolveNoDepsError where
show (ResolveUnsatisfiable name ver) =
"There is no available version of " ++ display name
++ " that satisfies " ++ display (simplifyVersionRange ver)
|
95a227042110a9211db3b34747577994b8de861aeb76976aa729d3fcc6cf9dfb | portkey-cloud/portkey | project.clj | (defproject ring-app "0.1.0-SNAPSHOT"
:description "Sample app using ring and portkey"
:dependencies [[org.clojure/clojure "1.9.0-beta1"]
[compojure "1.6.0"]
[http-kit "2.2.0"]
[hiccup "1.0.5"]
[ring/ring-codec "1.0.1"]]
:main ^:skip-aot ring-app.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}
:repl {:dependencies [[portkey "0.1.0-SNAPSHOT"]]
:source-paths ["dev"]
:repl-options {:init-ns dev}}})
| null | https://raw.githubusercontent.com/portkey-cloud/portkey/30c1e9170c5f6df85fc58d9c644a60cd1464a6d9/examples/ring-app/project.clj | clojure | (defproject ring-app "0.1.0-SNAPSHOT"
:description "Sample app using ring and portkey"
:dependencies [[org.clojure/clojure "1.9.0-beta1"]
[compojure "1.6.0"]
[http-kit "2.2.0"]
[hiccup "1.0.5"]
[ring/ring-codec "1.0.1"]]
:main ^:skip-aot ring-app.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}
:repl {:dependencies [[portkey "0.1.0-SNAPSHOT"]]
:source-paths ["dev"]
:repl-options {:init-ns dev}}})
|
|
fb3aa91ba6c27e4d276a563da97f181aa9ae74e9b6065338f1086619a9eed3d9 | Shirakumo/kandria | camera.lisp | (in-package #:org.shirakumo.fraf.kandria)
(defclass camera (trial:2d-camera unpausable)
((name :initform :camera)
(scale :initform 1.0 :accessor view-scale)
(intended-scale :initform 1.0 :accessor intended-view-scale)
(target-size :initarg :target-size :accessor target-size)
(target :initarg :target :initform NIL :accessor target)
(intended-location :initform (vec2 0 0) :accessor intended-location)
(zoom :initarg :zoom :initform 1.0 :accessor zoom)
(intended-zoom :initform 1.0 :accessor intended-zoom)
(chunk :initform NIL :accessor chunk)
(shake-timer :initform 0f0 :accessor shake-timer)
(shake-intensity :initform 3 :accessor shake-intensity)
(shake-unique :initform 0 :accessor shake-unique)
(rumble-intensity :initform 1.0 :accessor rumble-intensity)
(offset :initform (vec 0 0) :accessor offset)
(fix-offset :initform NIL :accessor fix-offset)
(in-view-tester :initform (vec 0 0 0 0) :accessor in-view-tester))
(:default-initargs
:location (vec 0 0)
:target-size (v* +tiles-in-view+ +tile-size+ .5)))
(defmethod (setf view-scale) (value (camera camera))
(setf (slot-value camera 'scale) (max 0.0001 value)))
(defmethod (setf zoom) (value (camera camera))
(setf (slot-value camera 'zoom) (max 0.0001 value)))
(defmethod reset ((camera camera))
(setf (target camera) NIL)
(setf (chunk camera) NIL)
(setf (location camera) (vec 0 0))
(setf (intended-location camera) (vec 0 0))
(setf (zoom camera) 1.0)
(setf (intended-zoom camera) 1.0)
(setf (shake-timer camera) 0.0)
(setf (offset camera) (vec 0 0)))
(defmethod map-visible (function (camera camera) (region region))
(dolist (entity (indefinite-extent-entities region))
(funcall function entity))
(bvh:do-fitting (entity (bvh region) (in-view-tester camera))
(funcall function entity)))
(defmethod layer-index ((counter fps-counter)) 100)
(defmethod map-visible (function (camera camera) (world world))
(let ((fps (unit 'fps-counter world)))
(when fps (funcall function fps)))
(if (region world)
(map-visible function camera (region world))
(call-next-method)))
(defmethod enter :after ((camera camera) (scene scene))
(setf (target camera) (unit 'player scene))
(when (target camera)
(setf (location camera) (vcopy (location (target camera))))))
(defun clamp-camera-target (camera target &optional (dir :both))
(let ((chunk (chunk camera))
(zoom (max (zoom camera) (intended-zoom camera))))
(when chunk
(let ((lx (vx2 (location chunk)))
(ly (vy2 (location chunk)))
(lw (vx2 (bsize chunk)))
(lh (vy2 (bsize chunk)))
(cw (/ (vx2 (target-size camera)) zoom))
(ch (/ (vy2 (target-size camera)) zoom)))
(when (or (eql dir :both) (eql dir :x))
(setf (vx target) (clamp (1+ (+ lx cw (- lw)))
(vx target)
(1- (+ lx (- cw) lw)))))
(when (or (eql dir :both) (eql dir :y))
(setf (vy target) (clamp (1+ (+ ly ch (- lh)))
(vy target)
(1- (+ ly (- ch) lh)))))))))
(defmethod handle :before ((ev tick) (camera camera))
(unless (find-panel 'editor)
(let ((loc (location camera))
(dt (dt ev)))
;; Camera movement
(let ((int (intended-location camera)))
(when (target camera)
(let ((tar (location (target camera))))
(vsetf int (round (vx tar)) (round (vy tar)))))
(clamp-camera-target camera int)
(let* ((dir (v- int loc))
(len (max 1 (vlength dir)))
(ease (clamp 0 (+ 0.2 (/ (expt len 1.4) 100)) 20)))
(nv* dir (/ ease len))
(nv+ loc dir)
;; View scale transitioning
(let* ((z (view-scale camera))
(int (intended-view-scale camera)))
(when (/= z int)
(let ((dir (/ (- (log int) (log (max z 0.0001))) 10)))
(if (< (abs dir) 0.001)
(setf (view-scale camera) int)
(incf (view-scale camera) dir)))
;; Clamp based on move direction only
(clamp-camera-target camera loc (cond ((< (abs (vx dir)) (abs (vy dir))) :x)
((= 0.0 (vy dir)) NIL)
(T :y)))))))
;; Camera zoom
(let* ((z (zoom camera))
(int (intended-zoom camera)))
(when (/= z int)
(let ((dir (/ (- (log int) (log z)) 10)))
(if (< (abs dir) 0.001)
(setf (zoom camera) int)
(incf (zoom camera) dir)))
(clamp-camera-target camera loc)))
;; Camera shake
(when (< 0 (shake-timer camera))
(decf (shake-timer camera) dt)
(when (typep +input-source+ 'gamepad:device)
(gamepad:rumble +input-source+ (if (< 0 (shake-timer camera))
(rumble-intensity camera)
0.0)))
;; Deterministic shake so that we can slow it down properly.
(when (< 0 (shake-intensity camera))
(let ((frame-id (sxhash (+ (shake-unique camera) (mod (floor (* (shake-timer camera) 100)) 100)))))
(nv+ loc (vcartesian (vec (* (logand #xFF (1+ frame-id))
(setting :gameplay :screen-shake) (shake-intensity camera)
0.001)
(* (* 2 PI) (/ (logand #xFF frame-id) #xFF))))))
(clamp-camera-target camera loc)))
(let ((off (offset camera)))
(when (v/= 0 off)
(vsetf loc
(+ (vx (intended-location camera)) (vx off))
(+ (vy (intended-location camera)) (vy off)))
(unless (fix-offset camera)
(nv* off 0.98))
(when (<= (abs (vx off)) 0.1) (setf (vx off) 0.0))
(when (<= (abs (vy off)) 0.1) (setf (vy off) 0.0))
(clamp-camera-target camera loc)))))
(update-in-view-tester camera))
(defun snap-to-target (camera &optional (target (target camera)))
(setf (target camera) target)
(v<- (location camera) (location target))
(v<- (intended-location camera) (location target))
(clamp-camera-target camera (location camera)))
(defmethod (setf target) :after ((target located-entity) (camera camera))
(when (region +world+)
(setf (chunk camera) (find-chunk target))))
(defmethod handle :before ((ev resize) (camera camera))
;; Adjust max width based on aspect ratio to ensure ultrawides still get to see something.
(let ((aspect (float (/ (width ev) (max 1 (height ev))))))
(setf (vx (target-size camera))
(cond ((<= aspect 2.1)
(* (vx +tiles-in-view+) +tile-size+ .5))
((<= aspect 2.6)
(* (vx +tiles-in-view+) +tile-size+ .75))
(T
(* (vx +tiles-in-view+) +tile-size+)))))
;; Ensure we scale to fit width as much as possible without showing space
;; outside the chunk.
(let* ((optimal-scale (float (/ (width ev) (* 2 (vx (target-size camera))))))
(max-fit-scale (if (chunk camera)
(max (/ (height ev) (* 2 (- (vy (bsize (chunk camera))) 8)))
(/ (width ev) (* 2 (- (vx (bsize (chunk camera))) 8))))
optimal-scale))
(scale (max 0.0001 optimal-scale max-fit-scale)))
(setf (intended-view-scale camera) scale)
(setf (vx (target-size camera)) (/ (width ev) scale 2))
(setf (vy (target-size camera)) (/ (height ev) scale 2))))
(defmethod (setf chunk) :after (chunk (camera camera))
;; Optimal bounds might have changed, update.
(handle (make-instance 'resize :width (width *context*) :height (height *context*)) camera))
(defmethod handle ((ev switch-chunk) (camera camera))
(setf (chunk camera) (chunk ev)))
(defmethod handle ((ev switch-region) (camera camera))
(setf (target camera) (unit 'player T)))
(defmethod handle ((ev window-shown) (camera camera))
(if (target camera)
(snap-to-target camera (target camera))
(vsetf (location camera) 0 0)))
(defmethod project-view ((camera camera))
(let* ((z (max 0.0001 (* (view-scale camera) (zoom camera))))
(v (nv- (v/ (target-size camera) (zoom camera)) (location camera))))
(reset-matrix *view-matrix*)
(scale-by z z z *view-matrix*)
(translate-by (vx v) (vy v) 100 *view-matrix*)))
(defun shake-camera (&key (duration 0.2) (intensity 3) (rumble-intensity 1.0))
(let ((camera (camera +world+)))
(setf (shake-unique camera) (random 100))
(setf (shake-timer camera) duration)
(setf (shake-intensity camera) intensity)
(setf (rumble-intensity camera) (* (setting :gameplay :rumble) rumble-intensity))
(when (= 0 duration)
(gamepad:call-with-devices (lambda (d) (gamepad:rumble d 0.0))))))
(defun rumble (&key (duration 0.3) (intensity 1.0))
(let ((camera (camera +world+)))
(setf (shake-timer camera) duration)
(setf (rumble-intensity camera) (* (setting :gameplay :rumble) intensity))
(when (= 0 duration)
(gamepad:call-with-devices (lambda (d) (gamepad:rumble d 0.0))))))
(defun duck-camera (x y)
(let ((off (offset (camera +world+))))
(vsetf off
(+ (vx off) (* 0.1 (- x (vx off))))
(+ (vy off) (* 0.1 (- y (vy off)))))))
(defmethod bsize ((camera camera))
(let* ((context (context +main+))
(zoom (the single-float (zoom camera)))
(vscale (the single-float (view-scale camera))))
(tvec (/ (the (unsigned-byte 32) (width context)) (* zoom 2 vscale))
(/ (the (unsigned-byte 32) (height context)) (* zoom 2 vscale)))))
(defun in-view-p (loc bsize)
(declare (optimize speed))
(declare (type vec2 loc bsize))
(let* ((test (in-view-tester (camera +world+)))
(lx (vx2 loc))
(ly (vy2 loc))
(sx (vx2 bsize))
(sy (vy2 bsize)))
(declare (type vec4 test))
(and (< (vx4 test) (+ lx sx))
(< (vy4 test) (+ ly sy))
(< (- lx sx) (vz4 test))
(< (- ly sy) (vw4 test)))))
(defun update-in-view-tester (camera)
(declare (optimize speed))
(let* ((context (context +main+))
(zoom (the single-float (zoom camera)))
(vscale (the single-float (view-scale camera)))
(siz (the vec2 (target-size camera)))
(cloc (the vec2 (location camera)))
(xoff (/ (vx2 siz) zoom))
(yoff (/ (vy2 siz) zoom)))
(vsetf (in-view-tester camera)
(- (vx cloc) xoff)
(- (vy cloc) yoff)
(- (+ (/ (the (unsigned-byte 32) (width context)) (* zoom vscale)) (vx cloc)) xoff)
(- (+ (/ (the (unsigned-byte 32) (height context)) (* zoom vscale)) (vy cloc)) yoff))))
| null | https://raw.githubusercontent.com/Shirakumo/kandria/94fd727bd93e302c6a28fae33815043d486d794b/camera.lisp | lisp | Camera movement
View scale transitioning
Clamp based on move direction only
Camera zoom
Camera shake
Deterministic shake so that we can slow it down properly.
Adjust max width based on aspect ratio to ensure ultrawides still get to see something.
Ensure we scale to fit width as much as possible without showing space
outside the chunk.
Optimal bounds might have changed, update. | (in-package #:org.shirakumo.fraf.kandria)
(defclass camera (trial:2d-camera unpausable)
((name :initform :camera)
(scale :initform 1.0 :accessor view-scale)
(intended-scale :initform 1.0 :accessor intended-view-scale)
(target-size :initarg :target-size :accessor target-size)
(target :initarg :target :initform NIL :accessor target)
(intended-location :initform (vec2 0 0) :accessor intended-location)
(zoom :initarg :zoom :initform 1.0 :accessor zoom)
(intended-zoom :initform 1.0 :accessor intended-zoom)
(chunk :initform NIL :accessor chunk)
(shake-timer :initform 0f0 :accessor shake-timer)
(shake-intensity :initform 3 :accessor shake-intensity)
(shake-unique :initform 0 :accessor shake-unique)
(rumble-intensity :initform 1.0 :accessor rumble-intensity)
(offset :initform (vec 0 0) :accessor offset)
(fix-offset :initform NIL :accessor fix-offset)
(in-view-tester :initform (vec 0 0 0 0) :accessor in-view-tester))
(:default-initargs
:location (vec 0 0)
:target-size (v* +tiles-in-view+ +tile-size+ .5)))
(defmethod (setf view-scale) (value (camera camera))
(setf (slot-value camera 'scale) (max 0.0001 value)))
(defmethod (setf zoom) (value (camera camera))
(setf (slot-value camera 'zoom) (max 0.0001 value)))
(defmethod reset ((camera camera))
(setf (target camera) NIL)
(setf (chunk camera) NIL)
(setf (location camera) (vec 0 0))
(setf (intended-location camera) (vec 0 0))
(setf (zoom camera) 1.0)
(setf (intended-zoom camera) 1.0)
(setf (shake-timer camera) 0.0)
(setf (offset camera) (vec 0 0)))
(defmethod map-visible (function (camera camera) (region region))
(dolist (entity (indefinite-extent-entities region))
(funcall function entity))
(bvh:do-fitting (entity (bvh region) (in-view-tester camera))
(funcall function entity)))
(defmethod layer-index ((counter fps-counter)) 100)
(defmethod map-visible (function (camera camera) (world world))
(let ((fps (unit 'fps-counter world)))
(when fps (funcall function fps)))
(if (region world)
(map-visible function camera (region world))
(call-next-method)))
(defmethod enter :after ((camera camera) (scene scene))
(setf (target camera) (unit 'player scene))
(when (target camera)
(setf (location camera) (vcopy (location (target camera))))))
(defun clamp-camera-target (camera target &optional (dir :both))
(let ((chunk (chunk camera))
(zoom (max (zoom camera) (intended-zoom camera))))
(when chunk
(let ((lx (vx2 (location chunk)))
(ly (vy2 (location chunk)))
(lw (vx2 (bsize chunk)))
(lh (vy2 (bsize chunk)))
(cw (/ (vx2 (target-size camera)) zoom))
(ch (/ (vy2 (target-size camera)) zoom)))
(when (or (eql dir :both) (eql dir :x))
(setf (vx target) (clamp (1+ (+ lx cw (- lw)))
(vx target)
(1- (+ lx (- cw) lw)))))
(when (or (eql dir :both) (eql dir :y))
(setf (vy target) (clamp (1+ (+ ly ch (- lh)))
(vy target)
(1- (+ ly (- ch) lh)))))))))
(defmethod handle :before ((ev tick) (camera camera))
(unless (find-panel 'editor)
(let ((loc (location camera))
(dt (dt ev)))
(let ((int (intended-location camera)))
(when (target camera)
(let ((tar (location (target camera))))
(vsetf int (round (vx tar)) (round (vy tar)))))
(clamp-camera-target camera int)
(let* ((dir (v- int loc))
(len (max 1 (vlength dir)))
(ease (clamp 0 (+ 0.2 (/ (expt len 1.4) 100)) 20)))
(nv* dir (/ ease len))
(nv+ loc dir)
(let* ((z (view-scale camera))
(int (intended-view-scale camera)))
(when (/= z int)
(let ((dir (/ (- (log int) (log (max z 0.0001))) 10)))
(if (< (abs dir) 0.001)
(setf (view-scale camera) int)
(incf (view-scale camera) dir)))
(clamp-camera-target camera loc (cond ((< (abs (vx dir)) (abs (vy dir))) :x)
((= 0.0 (vy dir)) NIL)
(T :y)))))))
(let* ((z (zoom camera))
(int (intended-zoom camera)))
(when (/= z int)
(let ((dir (/ (- (log int) (log z)) 10)))
(if (< (abs dir) 0.001)
(setf (zoom camera) int)
(incf (zoom camera) dir)))
(clamp-camera-target camera loc)))
(when (< 0 (shake-timer camera))
(decf (shake-timer camera) dt)
(when (typep +input-source+ 'gamepad:device)
(gamepad:rumble +input-source+ (if (< 0 (shake-timer camera))
(rumble-intensity camera)
0.0)))
(when (< 0 (shake-intensity camera))
(let ((frame-id (sxhash (+ (shake-unique camera) (mod (floor (* (shake-timer camera) 100)) 100)))))
(nv+ loc (vcartesian (vec (* (logand #xFF (1+ frame-id))
(setting :gameplay :screen-shake) (shake-intensity camera)
0.001)
(* (* 2 PI) (/ (logand #xFF frame-id) #xFF))))))
(clamp-camera-target camera loc)))
(let ((off (offset camera)))
(when (v/= 0 off)
(vsetf loc
(+ (vx (intended-location camera)) (vx off))
(+ (vy (intended-location camera)) (vy off)))
(unless (fix-offset camera)
(nv* off 0.98))
(when (<= (abs (vx off)) 0.1) (setf (vx off) 0.0))
(when (<= (abs (vy off)) 0.1) (setf (vy off) 0.0))
(clamp-camera-target camera loc)))))
(update-in-view-tester camera))
(defun snap-to-target (camera &optional (target (target camera)))
(setf (target camera) target)
(v<- (location camera) (location target))
(v<- (intended-location camera) (location target))
(clamp-camera-target camera (location camera)))
(defmethod (setf target) :after ((target located-entity) (camera camera))
(when (region +world+)
(setf (chunk camera) (find-chunk target))))
(defmethod handle :before ((ev resize) (camera camera))
(let ((aspect (float (/ (width ev) (max 1 (height ev))))))
(setf (vx (target-size camera))
(cond ((<= aspect 2.1)
(* (vx +tiles-in-view+) +tile-size+ .5))
((<= aspect 2.6)
(* (vx +tiles-in-view+) +tile-size+ .75))
(T
(* (vx +tiles-in-view+) +tile-size+)))))
(let* ((optimal-scale (float (/ (width ev) (* 2 (vx (target-size camera))))))
(max-fit-scale (if (chunk camera)
(max (/ (height ev) (* 2 (- (vy (bsize (chunk camera))) 8)))
(/ (width ev) (* 2 (- (vx (bsize (chunk camera))) 8))))
optimal-scale))
(scale (max 0.0001 optimal-scale max-fit-scale)))
(setf (intended-view-scale camera) scale)
(setf (vx (target-size camera)) (/ (width ev) scale 2))
(setf (vy (target-size camera)) (/ (height ev) scale 2))))
(defmethod (setf chunk) :after (chunk (camera camera))
(handle (make-instance 'resize :width (width *context*) :height (height *context*)) camera))
(defmethod handle ((ev switch-chunk) (camera camera))
(setf (chunk camera) (chunk ev)))
(defmethod handle ((ev switch-region) (camera camera))
(setf (target camera) (unit 'player T)))
(defmethod handle ((ev window-shown) (camera camera))
(if (target camera)
(snap-to-target camera (target camera))
(vsetf (location camera) 0 0)))
(defmethod project-view ((camera camera))
(let* ((z (max 0.0001 (* (view-scale camera) (zoom camera))))
(v (nv- (v/ (target-size camera) (zoom camera)) (location camera))))
(reset-matrix *view-matrix*)
(scale-by z z z *view-matrix*)
(translate-by (vx v) (vy v) 100 *view-matrix*)))
(defun shake-camera (&key (duration 0.2) (intensity 3) (rumble-intensity 1.0))
(let ((camera (camera +world+)))
(setf (shake-unique camera) (random 100))
(setf (shake-timer camera) duration)
(setf (shake-intensity camera) intensity)
(setf (rumble-intensity camera) (* (setting :gameplay :rumble) rumble-intensity))
(when (= 0 duration)
(gamepad:call-with-devices (lambda (d) (gamepad:rumble d 0.0))))))
(defun rumble (&key (duration 0.3) (intensity 1.0))
(let ((camera (camera +world+)))
(setf (shake-timer camera) duration)
(setf (rumble-intensity camera) (* (setting :gameplay :rumble) intensity))
(when (= 0 duration)
(gamepad:call-with-devices (lambda (d) (gamepad:rumble d 0.0))))))
(defun duck-camera (x y)
(let ((off (offset (camera +world+))))
(vsetf off
(+ (vx off) (* 0.1 (- x (vx off))))
(+ (vy off) (* 0.1 (- y (vy off)))))))
(defmethod bsize ((camera camera))
(let* ((context (context +main+))
(zoom (the single-float (zoom camera)))
(vscale (the single-float (view-scale camera))))
(tvec (/ (the (unsigned-byte 32) (width context)) (* zoom 2 vscale))
(/ (the (unsigned-byte 32) (height context)) (* zoom 2 vscale)))))
(defun in-view-p (loc bsize)
(declare (optimize speed))
(declare (type vec2 loc bsize))
(let* ((test (in-view-tester (camera +world+)))
(lx (vx2 loc))
(ly (vy2 loc))
(sx (vx2 bsize))
(sy (vy2 bsize)))
(declare (type vec4 test))
(and (< (vx4 test) (+ lx sx))
(< (vy4 test) (+ ly sy))
(< (- lx sx) (vz4 test))
(< (- ly sy) (vw4 test)))))
(defun update-in-view-tester (camera)
(declare (optimize speed))
(let* ((context (context +main+))
(zoom (the single-float (zoom camera)))
(vscale (the single-float (view-scale camera)))
(siz (the vec2 (target-size camera)))
(cloc (the vec2 (location camera)))
(xoff (/ (vx2 siz) zoom))
(yoff (/ (vy2 siz) zoom)))
(vsetf (in-view-tester camera)
(- (vx cloc) xoff)
(- (vy cloc) yoff)
(- (+ (/ (the (unsigned-byte 32) (width context)) (* zoom vscale)) (vx cloc)) xoff)
(- (+ (/ (the (unsigned-byte 32) (height context)) (* zoom vscale)) (vy cloc)) yoff))))
|
56cf75ca9e59c8393677e7c83a0256315557d973e11b88ba80d76fa8eaf66587 | workframers/stillsuit | queries.clj | (ns stillsuit.lacinia.queries
"Implementation functions for creating top-level stillsuit queries."
(:require [com.walmartlabs.lacinia.resolve :as resolve]
[stillsuit.datomic.core :as datomic]
[clojure.tools.logging :as log]
[datomic.api :as d]
[stillsuit.lacinia.types :as types]
[com.walmartlabs.lacinia.schema :as schema])
(:import (com.walmartlabs.lacinia.resolve ResolverResult)))
(defn stillsuit-entity-id-query
[{:stillsuit/keys [entity-id-query-name datomic-entity-type]}]
{:type datomic-entity-type
:args {:eid {:type '(non-null ID)
:description "The `:db/id` of the entity"}}
:resolve :stillsuit/resolve-by-enitity-id
:description "Return the current time."})
(def entity-id-query-resolver
^ResolverResult
(fn entity-id-query-resolver-fn
[{:stillsuit/keys [config connection] :as context} {:keys [eid] :as args} value]
(if-let [db (some-> connection d/db)]
(let [ent (datomic/get-entity-by-eid db eid)
ent-type (types/lacinia-type ent config)]
(when (some? ent)
(resolve/resolve-as
(schema/tag-with-type ent ent-type))))
;; Else no db
(resolve/resolve-as nil {:message (format "Can't get db value from connection %s!" (str connection))}))))
(defn stillsuit-unique-attribute-query
[{:stillsuit/keys [entity-id-query-name datomic-entity-type]}]
{:type datomic-entity-type
:args {:id {:type '(non-null ID)
:description "The `:db/id` of the entity"}}
:resolve [:stillsuit/query-by-unique-id datomic-entity-type]
:description "Get a `%s` entity by specifying its `%` attribute."})
TODO : specs - ensure only one arg
(defn unique-attribute-query-resolver
"Catchpocket interface to a generic query, expected to be referenced as a resolver:
:resolve [:stillsuit/resolve-by-unique-id {:stillsuit/attribute :example/attribute
:stillsuit/type :LaciniaTypeName}]"
[{:stillsuit/keys [attribute lacinia-type]}]
^resolve/ResolverResult
(fn unique-attribute-query-resolver-fn
[{:stillsuit/keys [connection] :as ctx} args value]
(if-let [db (some-> connection d/db)]
(let [arg (some-> args vals first)
result (datomic/get-entity-by-unique-attribute db attribute arg)]
(resolve/resolve-as
(schema/tag-with-type result lacinia-type)))
;; Else no db
(resolve/resolve-as nil {:message (format "Can't get db value from connection %s!" (str connection))}))))
(defn resolver-map
[{:stillsuit/keys [entity-id-query-name query-by-unique-id-name]}]
{:stillsuit/resolve-by-enitity-id entity-id-query-resolver
:stillsuit/query-by-unique-id unique-attribute-query-resolver})
(defn attach-queries [schema config]
(let [{:stillsuit/keys [entity-id-query-name query-by-unique-id-name]} config]
(-> schema
(assoc-in [:queries entity-id-query-name]
(stillsuit-entity-id-query config))
(assoc-in [:queries query-by-unique-id-name]
(stillsuit-unique-attribute-query config)))))
| null | https://raw.githubusercontent.com/workframers/stillsuit/f73d87d97971b458a4f717fccfa2445dc82f9b72/src/stillsuit/lacinia/queries.clj | clojure | Else no db
Else no db | (ns stillsuit.lacinia.queries
"Implementation functions for creating top-level stillsuit queries."
(:require [com.walmartlabs.lacinia.resolve :as resolve]
[stillsuit.datomic.core :as datomic]
[clojure.tools.logging :as log]
[datomic.api :as d]
[stillsuit.lacinia.types :as types]
[com.walmartlabs.lacinia.schema :as schema])
(:import (com.walmartlabs.lacinia.resolve ResolverResult)))
(defn stillsuit-entity-id-query
[{:stillsuit/keys [entity-id-query-name datomic-entity-type]}]
{:type datomic-entity-type
:args {:eid {:type '(non-null ID)
:description "The `:db/id` of the entity"}}
:resolve :stillsuit/resolve-by-enitity-id
:description "Return the current time."})
(def entity-id-query-resolver
^ResolverResult
(fn entity-id-query-resolver-fn
[{:stillsuit/keys [config connection] :as context} {:keys [eid] :as args} value]
(if-let [db (some-> connection d/db)]
(let [ent (datomic/get-entity-by-eid db eid)
ent-type (types/lacinia-type ent config)]
(when (some? ent)
(resolve/resolve-as
(schema/tag-with-type ent ent-type))))
(resolve/resolve-as nil {:message (format "Can't get db value from connection %s!" (str connection))}))))
(defn stillsuit-unique-attribute-query
[{:stillsuit/keys [entity-id-query-name datomic-entity-type]}]
{:type datomic-entity-type
:args {:id {:type '(non-null ID)
:description "The `:db/id` of the entity"}}
:resolve [:stillsuit/query-by-unique-id datomic-entity-type]
:description "Get a `%s` entity by specifying its `%` attribute."})
TODO : specs - ensure only one arg
(defn unique-attribute-query-resolver
"Catchpocket interface to a generic query, expected to be referenced as a resolver:
:resolve [:stillsuit/resolve-by-unique-id {:stillsuit/attribute :example/attribute
:stillsuit/type :LaciniaTypeName}]"
[{:stillsuit/keys [attribute lacinia-type]}]
^resolve/ResolverResult
(fn unique-attribute-query-resolver-fn
[{:stillsuit/keys [connection] :as ctx} args value]
(if-let [db (some-> connection d/db)]
(let [arg (some-> args vals first)
result (datomic/get-entity-by-unique-attribute db attribute arg)]
(resolve/resolve-as
(schema/tag-with-type result lacinia-type)))
(resolve/resolve-as nil {:message (format "Can't get db value from connection %s!" (str connection))}))))
(defn resolver-map
[{:stillsuit/keys [entity-id-query-name query-by-unique-id-name]}]
{:stillsuit/resolve-by-enitity-id entity-id-query-resolver
:stillsuit/query-by-unique-id unique-attribute-query-resolver})
(defn attach-queries [schema config]
(let [{:stillsuit/keys [entity-id-query-name query-by-unique-id-name]} config]
(-> schema
(assoc-in [:queries entity-id-query-name]
(stillsuit-entity-id-query config))
(assoc-in [:queries query-by-unique-id-name]
(stillsuit-unique-attribute-query config)))))
|
4ff420eda81ca49d05a676725ac3f0b56c04b5059ca30f89c72cf9fa8d579816 | janestreet/ocaml-probes | test_prog2.ml | let () =
while true do
[%probe "prog2" (print_endline "from prog2 probe")];
print_endline "from prog2"
done
;;
| null | https://raw.githubusercontent.com/janestreet/ocaml-probes/1ddd237eb647c94918ce77b13922bd51710e94d5/test/many_tracees/test_prog2.ml | ocaml | let () =
while true do
[%probe "prog2" (print_endline "from prog2 probe")];
print_endline "from prog2"
done
;;
|
|
6603a6199f0b43290bfd5b8a7100dea5fd253da5e783cb47e067bfca90cfd68d | slyrus/cl-bio | gbseq.lisp |
(in-package :entrez)
(progn
(defparameter *feature-annotation-type-list*
'(("exon" . bio:exon)
("cds" . bio:cds)
("STS" . bio:sts)
("repeat_region" . bio:repeat-region)
("source" . bio:source)
("Region" . bio:region)
("Site" . bio::site)))
(defparameter *feature-annotation-type-hash-table*
(make-hash-table :test 'equalp))
(mapcar
(lambda (x)
(destructuring-bind (feature-type . class)
x
(setf (gethash feature-type
*feature-annotation-type-hash-table*)
(find-class class))))
*feature-annotation-type-list*))
(defun feature-annotation-type (type)
(let ((class (gethash type *feature-annotation-type-hash-table*)))
(if class
class
(warn "unknown feature type ~S" type))))
(defun get-gbseq-feature-nodes (node &key type)
(xpath:with-namespaces ()
(xpath:evaluate
(format nil
"GBSeq_feature-table/GBFeature[GBFeature_key~@[/text()=\"~A\"~]]"
type)
node)))
(defun get-gbseq-feature-type (node)
(xpath:with-namespaces ()
(xpath:string-value
(xpath:evaluate "GBFeature_key/text()" node))))
(defun get-gbseq-feature-ranges (node)
(xpath:with-namespaces ()
(mapcar
(lambda (interval)
(let ((from (xpath::number-value (xpath:evaluate "GBInterval_from/text()" interval)))
(to (xpath::number-value (xpath:evaluate "GBInterval_to/text()" interval))))
(unless (or (eql from :nan)
(eql to :nan))
(let ((from (1- from))
(to (1- to)))
(let ((alpha-range (make-instance 'bio:range :start from :end to))
(beta-range (make-instance 'bio:range :start 0 :end (- to from))))
(cons alpha-range beta-range))))))
(xpath:all-nodes
(xpath:evaluate "GBFeature_intervals/GBInterval" node)))))
(defun get-gbseq-feature-types (node)
(xpath:with-namespaces ()
(xpath:evaluate
"GBSeq_feature-table/GBFeature/GBFeature_key/text()"
node)))
(defun parse-gbseq-locus (node obj)
(let ((gbseq-locus
(xpath:string-value
(xpath:evaluate "GBSeq_locus/text()" node))))
(when gbseq-locus
(bio:add-descriptor
obj
(make-instance 'bio:identifier :id gbseq-locus :type "locus")))))
(defun parse-gbseq-definition (node obj)
(let ((gbseq-definition
(xpath:string-value
(xpath:evaluate "GBSeq_definition/text()" node))))
(when gbseq-definition
(bio:add-descriptor
obj
(make-instance 'bio:identifier :id gbseq-definition :type "definition")))))
(defun parse-gbseq-sequence (node obj)
(let ((gbseq-sequence
(xpath:string-value
(xpath:evaluate "GBSeq_sequence/text()" node))))
(when gbseq-sequence
(setf (bio:residues-string obj) gbseq-sequence))))
(defun parse-gbseq-organism (node obj)
(let ((gbseq-organism
(xpath:string-value
(xpath:evaluate "GBSeq_organism/text()" node))))
(when gbseq-organism
(bio:add-descriptor
obj
(make-instance 'bio:identifier :id gbseq-organism :type "organism")))))
(defun parse-gbseq-taxonomy (node obj)
(let ((gbseq-taxonomy
(xpath:string-value
(xpath:evaluate "GBSeq_taxonomy/text()" node))))
(when gbseq-taxonomy
(bio:add-descriptor
obj
(make-instance 'bio:identifier :id gbseq-taxonomy :type "taxonomy")))))
(defun parse-gbseq-feature (feature-node obj)
(let ((feature-class
(feature-annotation-type
(get-gbseq-feature-type feature-node)))
(feature-ranges (get-gbseq-feature-ranges feature-node)))
(when (and feature-class feature-ranges)
(mapcar
(lambda (range-pair)
(destructuring-bind (alpha-range . beta-range)
range-pair
(let* ((annot (make-instance
feature-class
:length (bio::range-end beta-range)))
(align (make-instance
'bio:simple-pairwise-alignment
:alpha-sequence obj :alpha-range alpha-range
:beta-sequence annot :beta-range beta-range)))
(push align (bio:annotations obj)))))
feature-ranges))))
(defun parse-gbseq-features (node obj)
(let ((feature-nodes (get-gbseq-feature-nodes node)))
(xpath:map-node-set
(lambda (feature-node)
(parse-gbseq-feature feature-node obj))
feature-nodes)))
(defun parse-gbseq (node)
(xpath:with-namespaces ()
(let ((moltype
(xpath:string-value
(xpath:evaluate "GBSeq_moltype/text()" node))))
(let ((obj (make-instance
(cond
((member moltype '("mRNA" "tRNA" "RNA") :test 'equal)
'bio:adjustable-rna-sequence)
((equal moltype "DNA") 'bio:adjustable-dna-sequence)
((equal moltype "AA") 'bio:adjustable-aa-sequence)
(t 'bio:simple-sequence)))))
(parse-gbseq-locus node obj)
(parse-gbseq-definition node obj)
(parse-gbseq-sequence node obj)
(parse-gbseq-organism node obj)
(parse-gbseq-taxonomy node obj)
(parse-gbseq-features node obj)
obj))))
(defun parse-gbset (node)
(xpath:with-namespaces ()
(let ((set (make-instance 'bio:gene-set)))
(let ((gb-seqs
(xpath:all-nodes
(xpath:evaluate "GBSet/GBSeq" node))))
(setf (bio:genes set)
(mapcar #'parse-gbseq gb-seqs)))
set)))
| null | https://raw.githubusercontent.com/slyrus/cl-bio/e6de2bc7f4accaa11466902407e43fae3184973f/entrez/gbseq.lisp | lisp |
(in-package :entrez)
(progn
(defparameter *feature-annotation-type-list*
'(("exon" . bio:exon)
("cds" . bio:cds)
("STS" . bio:sts)
("repeat_region" . bio:repeat-region)
("source" . bio:source)
("Region" . bio:region)
("Site" . bio::site)))
(defparameter *feature-annotation-type-hash-table*
(make-hash-table :test 'equalp))
(mapcar
(lambda (x)
(destructuring-bind (feature-type . class)
x
(setf (gethash feature-type
*feature-annotation-type-hash-table*)
(find-class class))))
*feature-annotation-type-list*))
(defun feature-annotation-type (type)
(let ((class (gethash type *feature-annotation-type-hash-table*)))
(if class
class
(warn "unknown feature type ~S" type))))
(defun get-gbseq-feature-nodes (node &key type)
(xpath:with-namespaces ()
(xpath:evaluate
(format nil
"GBSeq_feature-table/GBFeature[GBFeature_key~@[/text()=\"~A\"~]]"
type)
node)))
(defun get-gbseq-feature-type (node)
(xpath:with-namespaces ()
(xpath:string-value
(xpath:evaluate "GBFeature_key/text()" node))))
(defun get-gbseq-feature-ranges (node)
(xpath:with-namespaces ()
(mapcar
(lambda (interval)
(let ((from (xpath::number-value (xpath:evaluate "GBInterval_from/text()" interval)))
(to (xpath::number-value (xpath:evaluate "GBInterval_to/text()" interval))))
(unless (or (eql from :nan)
(eql to :nan))
(let ((from (1- from))
(to (1- to)))
(let ((alpha-range (make-instance 'bio:range :start from :end to))
(beta-range (make-instance 'bio:range :start 0 :end (- to from))))
(cons alpha-range beta-range))))))
(xpath:all-nodes
(xpath:evaluate "GBFeature_intervals/GBInterval" node)))))
(defun get-gbseq-feature-types (node)
(xpath:with-namespaces ()
(xpath:evaluate
"GBSeq_feature-table/GBFeature/GBFeature_key/text()"
node)))
(defun parse-gbseq-locus (node obj)
(let ((gbseq-locus
(xpath:string-value
(xpath:evaluate "GBSeq_locus/text()" node))))
(when gbseq-locus
(bio:add-descriptor
obj
(make-instance 'bio:identifier :id gbseq-locus :type "locus")))))
(defun parse-gbseq-definition (node obj)
(let ((gbseq-definition
(xpath:string-value
(xpath:evaluate "GBSeq_definition/text()" node))))
(when gbseq-definition
(bio:add-descriptor
obj
(make-instance 'bio:identifier :id gbseq-definition :type "definition")))))
(defun parse-gbseq-sequence (node obj)
(let ((gbseq-sequence
(xpath:string-value
(xpath:evaluate "GBSeq_sequence/text()" node))))
(when gbseq-sequence
(setf (bio:residues-string obj) gbseq-sequence))))
(defun parse-gbseq-organism (node obj)
(let ((gbseq-organism
(xpath:string-value
(xpath:evaluate "GBSeq_organism/text()" node))))
(when gbseq-organism
(bio:add-descriptor
obj
(make-instance 'bio:identifier :id gbseq-organism :type "organism")))))
(defun parse-gbseq-taxonomy (node obj)
(let ((gbseq-taxonomy
(xpath:string-value
(xpath:evaluate "GBSeq_taxonomy/text()" node))))
(when gbseq-taxonomy
(bio:add-descriptor
obj
(make-instance 'bio:identifier :id gbseq-taxonomy :type "taxonomy")))))
(defun parse-gbseq-feature (feature-node obj)
(let ((feature-class
(feature-annotation-type
(get-gbseq-feature-type feature-node)))
(feature-ranges (get-gbseq-feature-ranges feature-node)))
(when (and feature-class feature-ranges)
(mapcar
(lambda (range-pair)
(destructuring-bind (alpha-range . beta-range)
range-pair
(let* ((annot (make-instance
feature-class
:length (bio::range-end beta-range)))
(align (make-instance
'bio:simple-pairwise-alignment
:alpha-sequence obj :alpha-range alpha-range
:beta-sequence annot :beta-range beta-range)))
(push align (bio:annotations obj)))))
feature-ranges))))
(defun parse-gbseq-features (node obj)
(let ((feature-nodes (get-gbseq-feature-nodes node)))
(xpath:map-node-set
(lambda (feature-node)
(parse-gbseq-feature feature-node obj))
feature-nodes)))
(defun parse-gbseq (node)
(xpath:with-namespaces ()
(let ((moltype
(xpath:string-value
(xpath:evaluate "GBSeq_moltype/text()" node))))
(let ((obj (make-instance
(cond
((member moltype '("mRNA" "tRNA" "RNA") :test 'equal)
'bio:adjustable-rna-sequence)
((equal moltype "DNA") 'bio:adjustable-dna-sequence)
((equal moltype "AA") 'bio:adjustable-aa-sequence)
(t 'bio:simple-sequence)))))
(parse-gbseq-locus node obj)
(parse-gbseq-definition node obj)
(parse-gbseq-sequence node obj)
(parse-gbseq-organism node obj)
(parse-gbseq-taxonomy node obj)
(parse-gbseq-features node obj)
obj))))
(defun parse-gbset (node)
(xpath:with-namespaces ()
(let ((set (make-instance 'bio:gene-set)))
(let ((gb-seqs
(xpath:all-nodes
(xpath:evaluate "GBSet/GBSeq" node))))
(setf (bio:genes set)
(mapcar #'parse-gbseq gb-seqs)))
set)))
|
|
79832f76731fa12f23fcc09da436513989a54d596f5c6729b36c00f6a90f7e2b | dbuenzli/brr | fut.ml | ---------------------------------------------------------------------------
Copyright ( c ) 2020 The brr programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2020 The brr programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
We represent futures by an object { fut : < promise > } with a single
[ fut ] JavaScript Promise object which , by construction , * never *
rejects . The promise is wrapped in an object because JavaScript 's
[ resolve ] which should be monadic [ return ] unfortunately also
monadically [ join]s . This JavaScript expression :
Promise.resolve ( Promise.resolve ( " Noooooo ! " ) )
evaluates to : Promise { < fulfilled > : " Noooooo ! " }
instead of : Promise { < fulfilled > : Promise { < fulfilled > : " " Noooooo ! " " } }
This makes it impossible to type [ resolve ] correctly in OCaml since it
would need to have these two types :
val resolve : ' a - > ' a Promise.t
val resolve : ' a Promise.t - > ' a Promise.t
In general this breaks type safety for example [ bind]ing a [ ' a
Fut.t Fut.t ] value your function could end up with a ground value
of type [ ' a ] not the expected [ ' a Fut.t ] value as argument . By
wrapping the promise in an object we can control that .
[fut] JavaScript Promise object which, by construction, *never*
rejects. The promise is wrapped in an object because JavaScript's
[resolve] which should be monadic [return] unfortunately also
monadically [join]s. This JavaScript expression:
Promise.resolve (Promise.resolve ("Noooooo!"))
evaluates to: Promise {<fulfilled>: "Noooooo!"}
instead of: Promise {<fulfilled>: Promise {<fulfilled>: ""Noooooo!""}}
This makes it impossible to type [resolve] correctly in OCaml since it
would need to have these two types:
val resolve : 'a -> 'a Promise.t
val resolve : 'a Promise.t -> 'a Promise.t
In general this breaks type safety for example [bind]ing a ['a
Fut.t Fut.t] value your function could end up with a ground value
of type ['a] not the expected ['a Fut.t] value as argument. By
wrapping the promise in an object we can control that. *)
a JavaScript object of the form : { fut : < promise > }
let fut p = Jv.obj [| "fut", p |]
let promise f = Jv.get f "fut"
let promise' f = Jv.get f "fut"
Ugly as shit but that 's what new Promise gives us .
let not_set = fun _ -> assert false in
let is_set = fun _ -> Jv.throw (Jstr.v "The future is already set") in
let setter = ref not_set in
let set_setter resolve _reject = setter := resolve in
let p = Jv.Promise.create set_setter in
let set v = !setter v; setter := is_set in
fut p, set
let await f k = Jv.Promise.await (promise f) k
let return v = fut @@ Jv.Promise.resolve v
let bind f fn = fut @@ Jv.Promise.bind (promise f) (fun v -> promise (fn v))
let map fn f = bind f (fun v -> return (fn v))
let pair f0 f1 =
fut @@
Jv.Promise.bind (promise f0) @@ fun v0 ->
Jv.Promise.bind (promise f1) @@ fun v1 ->
Jv.Promise.resolve (v0, v1)
let of_list fs =
let arr = Jv.of_list promise' fs in
let all = Jv.Promise.all arr in
let to_list l = Jv.Promise.resolve (Jv.to_list Obj.magic l) in
fut @@ Jv.Promise.bind all to_list
let tick ~ms =
fut @@ Jv.Promise.create @@ fun res _rej ->
ignore (Jv.apply (Jv.get Jv.global "setTimeout") Jv.[| repr res; of_int ms |])
Converting with JavaScript promises
type nonrec ('a, 'b) result = ('a, 'b) result t
type 'a or_error = ('a, Jv.Error.t) result
let ok v = return (Ok v)
let error e = return (Error e)
let of_promise' ~ok ~error p =
let ok v = Jv.Promise.resolve (Ok (ok v)) in
let error e = Jv.Promise.resolve (Error (error e)) in
fut @@ Jv.Promise.then' p ok error
let to_promise' ~ok ~error f =
Jv.Promise.create @@ fun res rej ->
await f @@ function
| Ok v -> res (ok v)
| Error e -> rej (error e)
let of_promise ~ok v = of_promise' ~ok ~error:Jv.to_error v
let to_promise ~ok v = to_promise' ~ok ~error:Jv.of_error v
(* Future syntaxes *)
module Syntax = struct
let ( let* ) = bind
let ( and* ) = pair
let ( let+ ) f fn = map fn f
let ( and+ ) = ( and* )
end
module Result_syntax = struct
let result_pair r0 r1 = match r0, r1 with
| (Error _ as r), _ | _, (Error _ as r) -> r
| Ok v0, Ok v1 -> Ok (v0, v1)
let ( let* ) f fn = bind f @@ function
| Ok v -> fn v
| Error _ as e -> return e
let ( and* ) f0 f1 = map result_pair (pair f0 f1)
let ( let+ ) f fn = map (Result.map fn) f
let ( and+ ) = ( and* )
end
---------------------------------------------------------------------------
Copyright ( c ) 2020 The brr programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2020 The brr programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/dbuenzli/brr/3d1a0edd964a1ddfbf2be515fc3a3803d27ad707/src/fut.ml | ocaml | Future syntaxes | ---------------------------------------------------------------------------
Copyright ( c ) 2020 The brr programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2020 The brr programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
We represent futures by an object { fut : < promise > } with a single
[ fut ] JavaScript Promise object which , by construction , * never *
rejects . The promise is wrapped in an object because JavaScript 's
[ resolve ] which should be monadic [ return ] unfortunately also
monadically [ join]s . This JavaScript expression :
Promise.resolve ( Promise.resolve ( " Noooooo ! " ) )
evaluates to : Promise { < fulfilled > : " Noooooo ! " }
instead of : Promise { < fulfilled > : Promise { < fulfilled > : " " Noooooo ! " " } }
This makes it impossible to type [ resolve ] correctly in OCaml since it
would need to have these two types :
val resolve : ' a - > ' a Promise.t
val resolve : ' a Promise.t - > ' a Promise.t
In general this breaks type safety for example [ bind]ing a [ ' a
Fut.t Fut.t ] value your function could end up with a ground value
of type [ ' a ] not the expected [ ' a Fut.t ] value as argument . By
wrapping the promise in an object we can control that .
[fut] JavaScript Promise object which, by construction, *never*
rejects. The promise is wrapped in an object because JavaScript's
[resolve] which should be monadic [return] unfortunately also
monadically [join]s. This JavaScript expression:
Promise.resolve (Promise.resolve ("Noooooo!"))
evaluates to: Promise {<fulfilled>: "Noooooo!"}
instead of: Promise {<fulfilled>: Promise {<fulfilled>: ""Noooooo!""}}
This makes it impossible to type [resolve] correctly in OCaml since it
would need to have these two types:
val resolve : 'a -> 'a Promise.t
val resolve : 'a Promise.t -> 'a Promise.t
In general this breaks type safety for example [bind]ing a ['a
Fut.t Fut.t] value your function could end up with a ground value
of type ['a] not the expected ['a Fut.t] value as argument. By
wrapping the promise in an object we can control that. *)
a JavaScript object of the form : { fut : < promise > }
let fut p = Jv.obj [| "fut", p |]
let promise f = Jv.get f "fut"
let promise' f = Jv.get f "fut"
Ugly as shit but that 's what new Promise gives us .
let not_set = fun _ -> assert false in
let is_set = fun _ -> Jv.throw (Jstr.v "The future is already set") in
let setter = ref not_set in
let set_setter resolve _reject = setter := resolve in
let p = Jv.Promise.create set_setter in
let set v = !setter v; setter := is_set in
fut p, set
let await f k = Jv.Promise.await (promise f) k
let return v = fut @@ Jv.Promise.resolve v
let bind f fn = fut @@ Jv.Promise.bind (promise f) (fun v -> promise (fn v))
let map fn f = bind f (fun v -> return (fn v))
let pair f0 f1 =
fut @@
Jv.Promise.bind (promise f0) @@ fun v0 ->
Jv.Promise.bind (promise f1) @@ fun v1 ->
Jv.Promise.resolve (v0, v1)
let of_list fs =
let arr = Jv.of_list promise' fs in
let all = Jv.Promise.all arr in
let to_list l = Jv.Promise.resolve (Jv.to_list Obj.magic l) in
fut @@ Jv.Promise.bind all to_list
let tick ~ms =
fut @@ Jv.Promise.create @@ fun res _rej ->
ignore (Jv.apply (Jv.get Jv.global "setTimeout") Jv.[| repr res; of_int ms |])
Converting with JavaScript promises
type nonrec ('a, 'b) result = ('a, 'b) result t
type 'a or_error = ('a, Jv.Error.t) result
let ok v = return (Ok v)
let error e = return (Error e)
let of_promise' ~ok ~error p =
let ok v = Jv.Promise.resolve (Ok (ok v)) in
let error e = Jv.Promise.resolve (Error (error e)) in
fut @@ Jv.Promise.then' p ok error
let to_promise' ~ok ~error f =
Jv.Promise.create @@ fun res rej ->
await f @@ function
| Ok v -> res (ok v)
| Error e -> rej (error e)
let of_promise ~ok v = of_promise' ~ok ~error:Jv.to_error v
let to_promise ~ok v = to_promise' ~ok ~error:Jv.of_error v
module Syntax = struct
let ( let* ) = bind
let ( and* ) = pair
let ( let+ ) f fn = map fn f
let ( and+ ) = ( and* )
end
module Result_syntax = struct
let result_pair r0 r1 = match r0, r1 with
| (Error _ as r), _ | _, (Error _ as r) -> r
| Ok v0, Ok v1 -> Ok (v0, v1)
let ( let* ) f fn = bind f @@ function
| Ok v -> fn v
| Error _ as e -> return e
let ( and* ) f0 f1 = map result_pair (pair f0 f1)
let ( let+ ) f fn = map (Result.map fn) f
let ( and+ ) = ( and* )
end
---------------------------------------------------------------------------
Copyright ( c ) 2020 The brr programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2020 The brr programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
ef46985953e24c05adb40516a95e46ede0d6579b1afcf43a75003d8cbd2ed23c | bufferswap/ViralityEngine | line3d.lisp | (in-package #:cl-user)
;;; NOTE: Line3d represents a 3D line segment, not an infinite line in the mathematical sense. Since
;;; line segments are so common in physics, we have chosen to use this convention (as many other
;;; game physics libraries do).
(defpackage #:vorigin.geometry.line3d
(:local-nicknames
(#:point3d #:vorigin.geometry.point3d)
(#:u #:vutils)
(#:v3 #:vorigin.vec3))
(:use #:cl)
(:shadow
#:length)
(:export
#:direction
#:end
#:length
#:length-squared
#:line
#:midpoint
#:start))
(in-package #:vorigin.geometry.line3d)
(declaim (inline %line))
(defstruct (line
(:predicate nil)
(:copier nil)
(:constructor %line (start end))
(:conc-name nil))
(start (point3d:point) :type point3d:point)
(end (point3d:point) :type point3d:point))
(u:fn-> line (&key (:start point3d:point) (:end point3d:point)) line)
(declaim (inline line))
(defun line (&key (start (point3d:point)) (end (point3d:point)))
(declare (optimize speed))
(%line start end))
(u:fn-> length (line) u:f32)
(declaim (inline length))
(defun length (line)
(declare (optimize speed))
(v3:length (v3:- (end line) (start line))))
(u:fn-> length-squared (line) u:f32)
(declaim (inline length-squared))
(defun length-squared (line)
(declare (optimize speed))
(v3:length-squared (v3:- (end line) (start line))))
(u:fn-> midpoint (line) point3d:point)
(declaim (inline midpoint))
(defun midpoint (line)
(declare (optimize speed))
(v3:lerp (start line) (end line) 0.5f0))
(u:fn-> direction (line) v3:vec)
(declaim (inline direction))
(defun direction (line)
(declare (optimize speed))
(v3:normalize (v3:- (end line) (start line))))
| null | https://raw.githubusercontent.com/bufferswap/ViralityEngine/df7bb4dffaecdcb6fdcbfa618031a5e1f85f4002/support/vorigin/src/geometry/shapes/line3d.lisp | lisp | NOTE: Line3d represents a 3D line segment, not an infinite line in the mathematical sense. Since
line segments are so common in physics, we have chosen to use this convention (as many other
game physics libraries do). | (in-package #:cl-user)
(defpackage #:vorigin.geometry.line3d
(:local-nicknames
(#:point3d #:vorigin.geometry.point3d)
(#:u #:vutils)
(#:v3 #:vorigin.vec3))
(:use #:cl)
(:shadow
#:length)
(:export
#:direction
#:end
#:length
#:length-squared
#:line
#:midpoint
#:start))
(in-package #:vorigin.geometry.line3d)
(declaim (inline %line))
(defstruct (line
(:predicate nil)
(:copier nil)
(:constructor %line (start end))
(:conc-name nil))
(start (point3d:point) :type point3d:point)
(end (point3d:point) :type point3d:point))
(u:fn-> line (&key (:start point3d:point) (:end point3d:point)) line)
(declaim (inline line))
(defun line (&key (start (point3d:point)) (end (point3d:point)))
(declare (optimize speed))
(%line start end))
(u:fn-> length (line) u:f32)
(declaim (inline length))
(defun length (line)
(declare (optimize speed))
(v3:length (v3:- (end line) (start line))))
(u:fn-> length-squared (line) u:f32)
(declaim (inline length-squared))
(defun length-squared (line)
(declare (optimize speed))
(v3:length-squared (v3:- (end line) (start line))))
(u:fn-> midpoint (line) point3d:point)
(declaim (inline midpoint))
(defun midpoint (line)
(declare (optimize speed))
(v3:lerp (start line) (end line) 0.5f0))
(u:fn-> direction (line) v3:vec)
(declaim (inline direction))
(defun direction (line)
(declare (optimize speed))
(v3:normalize (v3:- (end line) (start line))))
|
a5c3a583fe88e124e1ab53c68e11bc0e274da21f29d1dc40f92e73995829d2e8 | yrashk/erlang | erl_internal.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1998 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(erl_internal).
%% Define Erlang bifs, guard tests and other internal stuff.
%%
NOTE : All guard_bif ( ) , arith_op ( ) , bool_op ( ) and ( ) must be
%% defined in bif.tab as 'ubif', i.e bif without trace wrapper.
%%
%% Why?
%%
%% Because the compiler uses an optimized instruction for
the call to these , which when loaded gets a direct
%% entry pointer inserted into itself by the loader,
%% instead of a bif table index as for regular bifs.
%%
If tracing is enabled on these , when a module is loaded ,
%% the direct entry pointer inserted into the call instruction
%% will be pointing to the trace wrapper, so even if tracing is
disabled for , the loaded module will call these bifs through
%% the trace wrappers.
%%
%% The call instruction in question does not give enough information
%% to call trace match function {caller} for it to succeed
%% other then by chance, and the 'return_to' trace flag works just
%% as bad, so both will mostly say that the caller is 'undefined'.
Furthermore the calls to these will still generate
%% trace messages from the loaded module even if tracing is disabled
%% for them, and no one knows what else might be messed up.
%%
%% That's why!
%%
-export([bif/2,bif/3,guard_bif/2,
type_test/2,new_type_test/2,old_type_test/2]).
-export([arith_op/2,bool_op/2,comp_op/2,list_op/2,send_op/2,op_type/2]).
%%---------------------------------------------------------------------------
Erlang builtin functions allowed in guards .
-spec guard_bif(Name::atom(), Arity::arity()) -> bool().
guard_bif(abs, 1) -> true;
guard_bif(float, 1) -> true;
guard_bif(trunc, 1) -> true;
guard_bif(round, 1) -> true;
guard_bif(length, 1) -> true;
guard_bif(hd, 1) -> true;
guard_bif(tl, 1) -> true;
guard_bif(size, 1) -> true;
guard_bif(bit_size, 1) -> true;
guard_bif(byte_size, 1) -> true;
guard_bif(element, 2) -> true;
guard_bif(self, 0) -> true;
guard_bif(node, 0) -> true;
guard_bif(node, 1) -> true;
guard_bif(tuple_size, 1) -> true;
guard_bif(is_atom, 1) -> true;
guard_bif(is_binary, 1) -> true;
guard_bif(is_bitstring, 1) -> true;
guard_bif(is_boolean, 1) -> true;
guard_bif(is_float, 1) -> true;
guard_bif(is_function, 1) -> true;
guard_bif(is_function, 2) -> true;
guard_bif(is_integer, 1) -> true;
guard_bif(is_list, 1) -> true;
guard_bif(is_number, 1) -> true;
guard_bif(is_pid, 1) -> true;
guard_bif(is_port, 1) -> true;
guard_bif(is_reference, 1) -> true;
guard_bif(is_tuple, 1) -> true;
guard_bif(is_record, 2) -> true;
guard_bif(is_record, 3) -> true;
guard_bif(Name, A) when is_atom(Name), is_integer(A) -> false.
Erlang type tests .
-spec type_test(Name::atom(), Arity::arity()) -> bool().
type_test(Name, Arity) ->
new_type_test(Name, Arity) orelse old_type_test(Name, Arity).
Erlang new - style type tests .
-spec new_type_test(Name::atom(), Arity::arity()) -> bool().
new_type_test(is_atom, 1) -> true;
new_type_test(is_boolean, 1) -> true;
new_type_test(is_binary, 1) -> true;
new_type_test(is_bitstring, 1) -> true;
new_type_test(is_float, 1) -> true;
new_type_test(is_function, 1) -> true;
new_type_test(is_function, 2) -> true;
new_type_test(is_integer, 1) -> true;
new_type_test(is_list, 1) -> true;
new_type_test(is_number, 1) -> true;
new_type_test(is_pid, 1) -> true;
new_type_test(is_port, 1) -> true;
new_type_test(is_reference, 1) -> true;
new_type_test(is_tuple, 1) -> true;
new_type_test(is_record, 2) -> true;
new_type_test(is_record, 3) -> true;
new_type_test(Name, A) when is_atom(Name), is_integer(A) -> false.
Erlang old - style type tests .
-spec old_type_test(Name::atom(), Arity::arity()) -> bool().
old_type_test(integer, 1) -> true;
old_type_test(float, 1) -> true;
old_type_test(number, 1) -> true;
old_type_test(atom, 1) -> true;
old_type_test(list, 1) -> true;
old_type_test(tuple, 1) -> true;
old_type_test(pid, 1) -> true;
old_type_test(reference, 1) -> true;
old_type_test(port, 1) -> true;
old_type_test(binary, 1) -> true;
old_type_test(record, 2) -> true;
old_type_test(function, 1) -> true;
old_type_test(Name, A) when is_atom(Name), is_integer(A) -> false.
-spec arith_op(Op::atom(), Arity::arity()) -> bool().
arith_op('+', 1) -> true;
arith_op('-', 1) -> true;
arith_op('*', 2) -> true;
arith_op('/', 2) -> true;
arith_op('+', 2) -> true;
arith_op('-', 2) -> true;
arith_op('bnot', 1) -> true;
arith_op('div', 2) -> true;
arith_op('rem', 2) -> true;
arith_op('band', 2) -> true;
arith_op('bor', 2) -> true;
arith_op('bxor', 2) -> true;
arith_op('bsl', 2) -> true;
arith_op('bsr', 2) -> true;
arith_op(Op, A) when is_atom(Op), is_integer(A) -> false.
-spec bool_op(Op::atom(), Arity::arity()) -> bool().
bool_op('not', 1) -> true;
bool_op('and', 2) -> true;
bool_op('or', 2) -> true;
bool_op('xor', 2) -> true;
bool_op(Op, A) when is_atom(Op), is_integer(A) -> false.
-spec comp_op(Op::atom(), Arity::arity()) -> bool().
comp_op('==', 2) -> true;
comp_op('/=', 2) -> true;
comp_op('=<', 2) -> true;
comp_op('<', 2) -> true;
comp_op('>=', 2) -> true;
comp_op('>', 2) -> true;
comp_op('=:=', 2) -> true;
comp_op('=/=', 2) -> true;
comp_op(Op, A) when is_atom(Op), is_integer(A) -> false.
-spec list_op(Op::atom(), Arity::arity()) -> bool().
list_op('++', 2) -> true;
list_op('--', 2) -> true;
list_op(Op, A) when is_atom(Op), is_integer(A) -> false.
-spec send_op(Op::atom(), Arity::arity()) -> bool().
send_op('!', 2) -> true;
send_op(Op, A) when is_atom(Op), is_integer(A) -> false.
-spec op_type(atom(), 1 | 2) -> 'arith' | 'bool' | 'comp' | 'list' | 'send'.
op_type('+', 1) -> arith;
op_type('-', 1) -> arith;
op_type('*', 2) -> arith;
op_type('/', 2) -> arith;
op_type('+', 2) -> arith;
op_type('-', 2) -> arith;
op_type('bnot', 1) -> arith;
op_type('div', 2) -> arith;
op_type('rem', 2) -> arith;
op_type('band', 2) -> arith;
op_type('bor', 2) -> arith;
op_type('bxor', 2) -> arith;
op_type('bsl', 2) -> arith;
op_type('bsr', 2) -> arith;
op_type('not', 1) -> bool;
op_type('and', 2) -> bool;
op_type('or', 2) -> bool;
op_type('xor', 2) -> bool;
op_type('==', 2) -> comp;
op_type('/=', 2) -> comp;
op_type('=<', 2) -> comp;
op_type('<', 2) -> comp;
op_type('>=', 2) -> comp;
op_type('>', 2) -> comp;
op_type('=:=', 2) -> comp;
op_type('=/=', 2) -> comp;
op_type('++', 2) -> list;
op_type('--', 2) -> list;
op_type('!', 2) -> send.
-spec bif(Mod::atom(), Name::atom(), Arity::arity()) -> bool().
bif(erlang, Name, Arity) -> bif(Name, Arity);
bif(M, F, A) when is_atom(M), is_atom(F), is_integer(A) -> false.
-spec bif(Name::atom(), Arity::arity()) -> bool().
Returns true if : Name / Arity is an auto - imported BIF , false otherwise .
Use erlang : is_bultin(Mod , Name , Arity ) to find whether a function is a BIF
%% (meaning implemented in C) or not.
bif(abs, 1) -> true;
bif(apply, 2) -> true;
bif(apply, 3) -> true;
bif(atom_to_binary, 2) -> true;
bif(atom_to_list, 1) -> true;
bif(binary_to_atom, 2) -> true;
bif(binary_to_existing_atom, 2) -> true;
bif(binary_to_list, 1) -> true;
bif(binary_to_list, 3) -> true;
bif(binary_to_term, 1) -> true;
bif(bitsize, 1) -> true;
bif(bit_size, 1) -> true;
bif(bitstring_to_list, 1) -> true;
bif(byte_size, 1) -> true;
bif(check_process_code, 2) -> true;
bif(concat_binary, 1) -> true;
bif(date, 0) -> true;
bif(delete_module, 1) -> true;
bif(disconnect_node, 1) -> true;
bif(element, 2) -> true;
bif(erase, 0) -> true;
bif(erase, 1) -> true;
bif(exit, 1) -> true;
bif(exit, 2) -> true;
bif(float, 1) -> true;
bif(float_to_list, 1) -> true;
bif(garbage_collect, 0) -> true;
bif(garbage_collect, 1) -> true;
bif(get, 0) -> true;
bif(get, 1) -> true;
bif(get_keys, 1) -> true;
bif(group_leader, 0) -> true;
bif(group_leader, 2) -> true;
bif(halt, 0) -> true;
bif(halt, 1) -> true;
bif(hd, 1) -> true;
bif(integer_to_list, 1) -> true;
bif(iolist_size, 1) -> true;
bif(iolist_to_binary, 1) -> true;
bif(is_alive, 0) -> true;
bif(is_process_alive, 1) -> true;
bif(is_atom, 1) -> true;
bif(is_boolean, 1) -> true;
bif(is_binary, 1) -> true;
bif(is_bitstr, 1) -> true;
bif(is_bitstring, 1) -> true;
bif(is_float, 1) -> true;
bif(is_function, 1) -> true;
bif(is_function, 2) -> true;
bif(is_integer, 1) -> true;
bif(is_list, 1) -> true;
bif(is_number, 1) -> true;
bif(is_pid, 1) -> true;
bif(is_port, 1) -> true;
bif(is_reference, 1) -> true;
bif(is_tuple, 1) -> true;
bif(is_record, 2) -> true;
bif(is_record, 3) -> true;
bif(length, 1) -> true;
bif(link, 1) -> true;
bif(list_to_atom, 1) -> true;
bif(list_to_binary, 1) -> true;
bif(list_to_bitstring, 1) -> true;
bif(list_to_existing_atom, 1) -> true;
bif(list_to_float, 1) -> true;
bif(list_to_integer, 1) -> true;
bif(list_to_pid, 1) -> true;
bif(list_to_tuple, 1) -> true;
bif(load_module, 2) -> true;
bif(make_ref, 0) -> true;
bif(module_loaded, 1) -> true;
bif(monitor_node, 2) -> true;
bif(node, 0) -> true;
bif(node, 1) -> true;
bif(nodes, 0) -> true;
bif(nodes, 1) -> true;
bif(now, 0) -> true;
bif(open_port, 2) -> true;
bif(pid_to_list, 1) -> true;
bif(port_close, 1) -> true;
bif(port_command, 2) -> true;
bif(port_connect, 2) -> true;
bif(port_control, 3) -> true;
bif(pre_loaded, 0) -> true;
bif(process_flag, 2) -> true;
bif(process_flag, 3) -> true;
bif(process_info, 1) -> true;
bif(process_info, 2) -> true;
bif(processes, 0) -> true;
bif(purge_module, 1) -> true;
bif(put, 2) -> true;
bif(register, 2) -> true;
bif(registered, 0) -> true;
bif(round, 1) -> true;
bif(self, 0) -> true;
bif(setelement, 3) -> true;
bif(size, 1) -> true;
bif(spawn, 1) -> true;
bif(spawn, 2) -> true;
bif(spawn, 3) -> true;
bif(spawn, 4) -> true;
bif(spawn_link, 1) -> true;
bif(spawn_link, 2) -> true;
bif(spawn_link, 3) -> true;
bif(spawn_link, 4) -> true;
bif(spawn_monitor, 1) -> true;
bif(spawn_monitor, 3) -> true;
bif(spawn_opt, 2) -> true;
bif(spawn_opt, 3) -> true;
bif(spawn_opt, 4) -> true;
bif(spawn_opt, 5) -> true;
bif(split_binary, 2) -> true;
bif(statistics, 1) -> true;
bif(term_to_binary, 1) -> true;
bif(term_to_binary, 2) -> true;
bif(throw, 1) -> true;
bif(time, 0) -> true;
bif(tl, 1) -> true;
bif(trunc, 1) -> true;
bif(tuple_size, 1) -> true;
bif(tuple_to_list, 1) -> true;
bif(unlink, 1) -> true;
bif(unregister, 1) -> true;
bif(whereis, 1) -> true;
bif(Name, A) when is_atom(Name), is_integer(A) -> false.
| null | https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/stdlib/src/erl_internal.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
Define Erlang bifs, guard tests and other internal stuff.
defined in bif.tab as 'ubif', i.e bif without trace wrapper.
Why?
Because the compiler uses an optimized instruction for
entry pointer inserted into itself by the loader,
instead of a bif table index as for regular bifs.
the direct entry pointer inserted into the call instruction
will be pointing to the trace wrapper, so even if tracing is
the trace wrappers.
The call instruction in question does not give enough information
to call trace match function {caller} for it to succeed
other then by chance, and the 'return_to' trace flag works just
as bad, so both will mostly say that the caller is 'undefined'.
trace messages from the loaded module even if tracing is disabled
for them, and no one knows what else might be messed up.
That's why!
---------------------------------------------------------------------------
(meaning implemented in C) or not. | Copyright Ericsson AB 1998 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(erl_internal).
NOTE : All guard_bif ( ) , arith_op ( ) , bool_op ( ) and ( ) must be
the call to these , which when loaded gets a direct
If tracing is enabled on these , when a module is loaded ,
disabled for , the loaded module will call these bifs through
Furthermore the calls to these will still generate
-export([bif/2,bif/3,guard_bif/2,
type_test/2,new_type_test/2,old_type_test/2]).
-export([arith_op/2,bool_op/2,comp_op/2,list_op/2,send_op/2,op_type/2]).
Erlang builtin functions allowed in guards .
-spec guard_bif(Name::atom(), Arity::arity()) -> bool().
guard_bif(abs, 1) -> true;
guard_bif(float, 1) -> true;
guard_bif(trunc, 1) -> true;
guard_bif(round, 1) -> true;
guard_bif(length, 1) -> true;
guard_bif(hd, 1) -> true;
guard_bif(tl, 1) -> true;
guard_bif(size, 1) -> true;
guard_bif(bit_size, 1) -> true;
guard_bif(byte_size, 1) -> true;
guard_bif(element, 2) -> true;
guard_bif(self, 0) -> true;
guard_bif(node, 0) -> true;
guard_bif(node, 1) -> true;
guard_bif(tuple_size, 1) -> true;
guard_bif(is_atom, 1) -> true;
guard_bif(is_binary, 1) -> true;
guard_bif(is_bitstring, 1) -> true;
guard_bif(is_boolean, 1) -> true;
guard_bif(is_float, 1) -> true;
guard_bif(is_function, 1) -> true;
guard_bif(is_function, 2) -> true;
guard_bif(is_integer, 1) -> true;
guard_bif(is_list, 1) -> true;
guard_bif(is_number, 1) -> true;
guard_bif(is_pid, 1) -> true;
guard_bif(is_port, 1) -> true;
guard_bif(is_reference, 1) -> true;
guard_bif(is_tuple, 1) -> true;
guard_bif(is_record, 2) -> true;
guard_bif(is_record, 3) -> true;
guard_bif(Name, A) when is_atom(Name), is_integer(A) -> false.
Erlang type tests .
-spec type_test(Name::atom(), Arity::arity()) -> bool().
type_test(Name, Arity) ->
new_type_test(Name, Arity) orelse old_type_test(Name, Arity).
Erlang new - style type tests .
-spec new_type_test(Name::atom(), Arity::arity()) -> bool().
new_type_test(is_atom, 1) -> true;
new_type_test(is_boolean, 1) -> true;
new_type_test(is_binary, 1) -> true;
new_type_test(is_bitstring, 1) -> true;
new_type_test(is_float, 1) -> true;
new_type_test(is_function, 1) -> true;
new_type_test(is_function, 2) -> true;
new_type_test(is_integer, 1) -> true;
new_type_test(is_list, 1) -> true;
new_type_test(is_number, 1) -> true;
new_type_test(is_pid, 1) -> true;
new_type_test(is_port, 1) -> true;
new_type_test(is_reference, 1) -> true;
new_type_test(is_tuple, 1) -> true;
new_type_test(is_record, 2) -> true;
new_type_test(is_record, 3) -> true;
new_type_test(Name, A) when is_atom(Name), is_integer(A) -> false.
Erlang old - style type tests .
-spec old_type_test(Name::atom(), Arity::arity()) -> bool().
old_type_test(integer, 1) -> true;
old_type_test(float, 1) -> true;
old_type_test(number, 1) -> true;
old_type_test(atom, 1) -> true;
old_type_test(list, 1) -> true;
old_type_test(tuple, 1) -> true;
old_type_test(pid, 1) -> true;
old_type_test(reference, 1) -> true;
old_type_test(port, 1) -> true;
old_type_test(binary, 1) -> true;
old_type_test(record, 2) -> true;
old_type_test(function, 1) -> true;
old_type_test(Name, A) when is_atom(Name), is_integer(A) -> false.
-spec arith_op(Op::atom(), Arity::arity()) -> bool().
arith_op('+', 1) -> true;
arith_op('-', 1) -> true;
arith_op('*', 2) -> true;
arith_op('/', 2) -> true;
arith_op('+', 2) -> true;
arith_op('-', 2) -> true;
arith_op('bnot', 1) -> true;
arith_op('div', 2) -> true;
arith_op('rem', 2) -> true;
arith_op('band', 2) -> true;
arith_op('bor', 2) -> true;
arith_op('bxor', 2) -> true;
arith_op('bsl', 2) -> true;
arith_op('bsr', 2) -> true;
arith_op(Op, A) when is_atom(Op), is_integer(A) -> false.
-spec bool_op(Op::atom(), Arity::arity()) -> bool().
bool_op('not', 1) -> true;
bool_op('and', 2) -> true;
bool_op('or', 2) -> true;
bool_op('xor', 2) -> true;
bool_op(Op, A) when is_atom(Op), is_integer(A) -> false.
-spec comp_op(Op::atom(), Arity::arity()) -> bool().
comp_op('==', 2) -> true;
comp_op('/=', 2) -> true;
comp_op('=<', 2) -> true;
comp_op('<', 2) -> true;
comp_op('>=', 2) -> true;
comp_op('>', 2) -> true;
comp_op('=:=', 2) -> true;
comp_op('=/=', 2) -> true;
comp_op(Op, A) when is_atom(Op), is_integer(A) -> false.
-spec list_op(Op::atom(), Arity::arity()) -> bool().
list_op('++', 2) -> true;
list_op('--', 2) -> true;
list_op(Op, A) when is_atom(Op), is_integer(A) -> false.
-spec send_op(Op::atom(), Arity::arity()) -> bool().
send_op('!', 2) -> true;
send_op(Op, A) when is_atom(Op), is_integer(A) -> false.
-spec op_type(atom(), 1 | 2) -> 'arith' | 'bool' | 'comp' | 'list' | 'send'.
op_type('+', 1) -> arith;
op_type('-', 1) -> arith;
op_type('*', 2) -> arith;
op_type('/', 2) -> arith;
op_type('+', 2) -> arith;
op_type('-', 2) -> arith;
op_type('bnot', 1) -> arith;
op_type('div', 2) -> arith;
op_type('rem', 2) -> arith;
op_type('band', 2) -> arith;
op_type('bor', 2) -> arith;
op_type('bxor', 2) -> arith;
op_type('bsl', 2) -> arith;
op_type('bsr', 2) -> arith;
op_type('not', 1) -> bool;
op_type('and', 2) -> bool;
op_type('or', 2) -> bool;
op_type('xor', 2) -> bool;
op_type('==', 2) -> comp;
op_type('/=', 2) -> comp;
op_type('=<', 2) -> comp;
op_type('<', 2) -> comp;
op_type('>=', 2) -> comp;
op_type('>', 2) -> comp;
op_type('=:=', 2) -> comp;
op_type('=/=', 2) -> comp;
op_type('++', 2) -> list;
op_type('--', 2) -> list;
op_type('!', 2) -> send.
-spec bif(Mod::atom(), Name::atom(), Arity::arity()) -> bool().
bif(erlang, Name, Arity) -> bif(Name, Arity);
bif(M, F, A) when is_atom(M), is_atom(F), is_integer(A) -> false.
-spec bif(Name::atom(), Arity::arity()) -> bool().
Returns true if : Name / Arity is an auto - imported BIF , false otherwise .
Use erlang : is_bultin(Mod , Name , Arity ) to find whether a function is a BIF
bif(abs, 1) -> true;
bif(apply, 2) -> true;
bif(apply, 3) -> true;
bif(atom_to_binary, 2) -> true;
bif(atom_to_list, 1) -> true;
bif(binary_to_atom, 2) -> true;
bif(binary_to_existing_atom, 2) -> true;
bif(binary_to_list, 1) -> true;
bif(binary_to_list, 3) -> true;
bif(binary_to_term, 1) -> true;
bif(bitsize, 1) -> true;
bif(bit_size, 1) -> true;
bif(bitstring_to_list, 1) -> true;
bif(byte_size, 1) -> true;
bif(check_process_code, 2) -> true;
bif(concat_binary, 1) -> true;
bif(date, 0) -> true;
bif(delete_module, 1) -> true;
bif(disconnect_node, 1) -> true;
bif(element, 2) -> true;
bif(erase, 0) -> true;
bif(erase, 1) -> true;
bif(exit, 1) -> true;
bif(exit, 2) -> true;
bif(float, 1) -> true;
bif(float_to_list, 1) -> true;
bif(garbage_collect, 0) -> true;
bif(garbage_collect, 1) -> true;
bif(get, 0) -> true;
bif(get, 1) -> true;
bif(get_keys, 1) -> true;
bif(group_leader, 0) -> true;
bif(group_leader, 2) -> true;
bif(halt, 0) -> true;
bif(halt, 1) -> true;
bif(hd, 1) -> true;
bif(integer_to_list, 1) -> true;
bif(iolist_size, 1) -> true;
bif(iolist_to_binary, 1) -> true;
bif(is_alive, 0) -> true;
bif(is_process_alive, 1) -> true;
bif(is_atom, 1) -> true;
bif(is_boolean, 1) -> true;
bif(is_binary, 1) -> true;
bif(is_bitstr, 1) -> true;
bif(is_bitstring, 1) -> true;
bif(is_float, 1) -> true;
bif(is_function, 1) -> true;
bif(is_function, 2) -> true;
bif(is_integer, 1) -> true;
bif(is_list, 1) -> true;
bif(is_number, 1) -> true;
bif(is_pid, 1) -> true;
bif(is_port, 1) -> true;
bif(is_reference, 1) -> true;
bif(is_tuple, 1) -> true;
bif(is_record, 2) -> true;
bif(is_record, 3) -> true;
bif(length, 1) -> true;
bif(link, 1) -> true;
bif(list_to_atom, 1) -> true;
bif(list_to_binary, 1) -> true;
bif(list_to_bitstring, 1) -> true;
bif(list_to_existing_atom, 1) -> true;
bif(list_to_float, 1) -> true;
bif(list_to_integer, 1) -> true;
bif(list_to_pid, 1) -> true;
bif(list_to_tuple, 1) -> true;
bif(load_module, 2) -> true;
bif(make_ref, 0) -> true;
bif(module_loaded, 1) -> true;
bif(monitor_node, 2) -> true;
bif(node, 0) -> true;
bif(node, 1) -> true;
bif(nodes, 0) -> true;
bif(nodes, 1) -> true;
bif(now, 0) -> true;
bif(open_port, 2) -> true;
bif(pid_to_list, 1) -> true;
bif(port_close, 1) -> true;
bif(port_command, 2) -> true;
bif(port_connect, 2) -> true;
bif(port_control, 3) -> true;
bif(pre_loaded, 0) -> true;
bif(process_flag, 2) -> true;
bif(process_flag, 3) -> true;
bif(process_info, 1) -> true;
bif(process_info, 2) -> true;
bif(processes, 0) -> true;
bif(purge_module, 1) -> true;
bif(put, 2) -> true;
bif(register, 2) -> true;
bif(registered, 0) -> true;
bif(round, 1) -> true;
bif(self, 0) -> true;
bif(setelement, 3) -> true;
bif(size, 1) -> true;
bif(spawn, 1) -> true;
bif(spawn, 2) -> true;
bif(spawn, 3) -> true;
bif(spawn, 4) -> true;
bif(spawn_link, 1) -> true;
bif(spawn_link, 2) -> true;
bif(spawn_link, 3) -> true;
bif(spawn_link, 4) -> true;
bif(spawn_monitor, 1) -> true;
bif(spawn_monitor, 3) -> true;
bif(spawn_opt, 2) -> true;
bif(spawn_opt, 3) -> true;
bif(spawn_opt, 4) -> true;
bif(spawn_opt, 5) -> true;
bif(split_binary, 2) -> true;
bif(statistics, 1) -> true;
bif(term_to_binary, 1) -> true;
bif(term_to_binary, 2) -> true;
bif(throw, 1) -> true;
bif(time, 0) -> true;
bif(tl, 1) -> true;
bif(trunc, 1) -> true;
bif(tuple_size, 1) -> true;
bif(tuple_to_list, 1) -> true;
bif(unlink, 1) -> true;
bif(unregister, 1) -> true;
bif(whereis, 1) -> true;
bif(Name, A) when is_atom(Name), is_integer(A) -> false.
|
27289f74385e8b60af579a9592bedbbeb34bfabe7eb08dfb91e846c434475300 | haskell-hvr/missingh | Daemon.hs | # LANGUAGE CPP #
# LANGUAGE Trustworthy #
Copyright ( c ) 2005 - 2011 < >
All rights reserved .
For license and copyright information , see the file LICENSE
Copyright (c) 2005-2011 John Goerzen <>
All rights reserved.
For license and copyright information, see the file LICENSE
-}
|
Module : System . Daemon
Copyright : Copyright ( C ) 2005 - 2011 SPDX - License - Identifier : BSD-3 - Clause
Stability : stable
Portability : portable to platforms with POSIX process\/signal tools
Tools for writing daemons\/server processes
Written by , jgoerzen\@complete.org
Messages from this module are logged under . See
' System . Log . Logger ' for details .
This module is not available on Windows .
Module : System.Daemon
Copyright : Copyright (C) 2005-2011 John Goerzen
SPDX-License-Identifier: BSD-3-Clause
Stability : stable
Portability: portable to platforms with POSIX process\/signal tools
Tools for writing daemons\/server processes
Written by John Goerzen, jgoerzen\@complete.org
Messages from this module are logged under @System.Daemon@. See
'System.Log.Logger' for details.
This module is not available on Windows.
-}
module System.Daemon (
#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))
detachDaemon
#endif
)
where
#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))
import System.Directory ( setCurrentDirectory )
import System.Exit ( ExitCode(ExitSuccess) )
import System.Log.Logger ( traplogging, Priority(ERROR) )
import System.Posix.IO
( openFd,
closeFd,
defaultFileFlags,
dupTo,
stdError,
stdInput,
stdOutput,
OpenMode(ReadWrite) )
import System.Posix.Process
( createSession, exitImmediately, forkProcess )
trap :: IO a -> IO a
trap = traplogging "System.Daemon" ERROR "detachDaemon"
| Detach the process from a controlling terminal and run it in the
background , handling it with standard Unix deamon semantics .
After running this , please note the following side - effects :
* The PID of the running process will change
* stdin , stdout , and stderr will not work ( they 'll be set to
\/dev\/null )
* CWD will be changed to \/
I /highly/ suggest running this function before starting any threads .
Note that this is not intended for a daemon invoked from inetd(1 ) .
background, handling it with standard Unix deamon semantics.
After running this, please note the following side-effects:
* The PID of the running process will change
* stdin, stdout, and stderr will not work (they'll be set to
\/dev\/null)
* CWD will be changed to \/
I /highly/ suggest running this function before starting any threads.
Note that this is not intended for a daemon invoked from inetd(1).
-}
detachDaemon :: IO ()
detachDaemon = trap $
do _ <- forkProcess child1
exitImmediately ExitSuccess
child1 :: IO ()
child1 = trap $
do _ <- createSession
_ <- forkProcess child2
exitImmediately ExitSuccess
child2 :: IO ()
child2 = trap $
do setCurrentDirectory "/"
mapM_ closeFd [stdInput, stdOutput, stdError]
nullFd <- openFd
"/dev/null"
ReadWrite
#if !MIN_VERSION_unix(2,8,0)
Nothing
#endif
defaultFileFlags
mapM_ (dupTo nullFd) [stdInput, stdOutput, stdError]
closeFd nullFd
#endif
| null | https://raw.githubusercontent.com/haskell-hvr/missingh/20ecfe24e2d96f4f6553dda2b9433a0a9f692eca/src/System/Daemon.hs | haskell | # LANGUAGE CPP #
# LANGUAGE Trustworthy #
Copyright ( c ) 2005 - 2011 < >
All rights reserved .
For license and copyright information , see the file LICENSE
Copyright (c) 2005-2011 John Goerzen <>
All rights reserved.
For license and copyright information, see the file LICENSE
-}
|
Module : System . Daemon
Copyright : Copyright ( C ) 2005 - 2011 SPDX - License - Identifier : BSD-3 - Clause
Stability : stable
Portability : portable to platforms with POSIX process\/signal tools
Tools for writing daemons\/server processes
Written by , jgoerzen\@complete.org
Messages from this module are logged under . See
' System . Log . Logger ' for details .
This module is not available on Windows .
Module : System.Daemon
Copyright : Copyright (C) 2005-2011 John Goerzen
SPDX-License-Identifier: BSD-3-Clause
Stability : stable
Portability: portable to platforms with POSIX process\/signal tools
Tools for writing daemons\/server processes
Written by John Goerzen, jgoerzen\@complete.org
Messages from this module are logged under @System.Daemon@. See
'System.Log.Logger' for details.
This module is not available on Windows.
-}
module System.Daemon (
#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))
detachDaemon
#endif
)
where
#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))
import System.Directory ( setCurrentDirectory )
import System.Exit ( ExitCode(ExitSuccess) )
import System.Log.Logger ( traplogging, Priority(ERROR) )
import System.Posix.IO
( openFd,
closeFd,
defaultFileFlags,
dupTo,
stdError,
stdInput,
stdOutput,
OpenMode(ReadWrite) )
import System.Posix.Process
( createSession, exitImmediately, forkProcess )
trap :: IO a -> IO a
trap = traplogging "System.Daemon" ERROR "detachDaemon"
| Detach the process from a controlling terminal and run it in the
background , handling it with standard Unix deamon semantics .
After running this , please note the following side - effects :
* The PID of the running process will change
* stdin , stdout , and stderr will not work ( they 'll be set to
\/dev\/null )
* CWD will be changed to \/
I /highly/ suggest running this function before starting any threads .
Note that this is not intended for a daemon invoked from inetd(1 ) .
background, handling it with standard Unix deamon semantics.
After running this, please note the following side-effects:
* The PID of the running process will change
* stdin, stdout, and stderr will not work (they'll be set to
\/dev\/null)
* CWD will be changed to \/
I /highly/ suggest running this function before starting any threads.
Note that this is not intended for a daemon invoked from inetd(1).
-}
detachDaemon :: IO ()
detachDaemon = trap $
do _ <- forkProcess child1
exitImmediately ExitSuccess
child1 :: IO ()
child1 = trap $
do _ <- createSession
_ <- forkProcess child2
exitImmediately ExitSuccess
child2 :: IO ()
child2 = trap $
do setCurrentDirectory "/"
mapM_ closeFd [stdInput, stdOutput, stdError]
nullFd <- openFd
"/dev/null"
ReadWrite
#if !MIN_VERSION_unix(2,8,0)
Nothing
#endif
defaultFileFlags
mapM_ (dupTo nullFd) [stdInput, stdOutput, stdError]
closeFd nullFd
#endif
|
|
432682c3e975d32a1b71461405de2874029d5320d7609a06e64e71d623a1fa74 | ekarayel/sync-mht | Server.hs | module Sync.MerkleTree.Server where
import Codec.Compression.GZip
import Control.Monad.State
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import Data.Map (Map)
import qualified Data.Map as M
import Data.String.Interpolate.IsString
import qualified Data.Text.IO as T
import Data.Time.Clock
import Sync.MerkleTree.CommTypes
import Sync.MerkleTree.Trie
import Sync.MerkleTree.Types
import System.IO
data ServerState = ServerState
{ -- | Map of open file handles with their ids
st_handles :: Map Int Handle,
-- | Next available id
st_nextHandle :: Int,
-- | Merkle Hash Tree of server file hierarchy
st_trie :: Trie Entry,
-- | path of the root of the file hierarchy
st_path :: FilePath
}
type ServerMonad = StateT ServerState IO
startServerState :: FilePath -> Trie Entry -> IO ServerState
startServerState fp trie =
do
T.hPutStr stderr $ [i|Hash of source directory: #{t_hash trie}.\n|]
return $
ServerState
{ st_handles = M.empty,
st_nextHandle = 0,
st_trie = trie,
st_path = fp
}
instance Protocol ServerMonad where
querySetReq l = get >>= (\s -> querySet (st_trie s) l)
queryHashReq l = get >>= (\s -> queryHash (st_trie s) l)
logReq msg = liftIO (T.hPutStr stderr msg) >> return True
queryFileContReq (ContHandle n) =
do
s <- get
let Just h = M.lookup n (st_handles s)
withHandle h n
queryFileReq f =
do
s <- get
h <- liftIO $ openFile (toFilePath (st_path s) f) ReadMode
let n = st_nextHandle s
put $ s {st_handles = M.insert n h (st_handles s), st_nextHandle = n + 1}
withHandle h n
queryTime = liftIO getCurrentTime
terminateReq _ = return True
| Respond to a queryFile or queryFileCont request for a given file handle and i d
withHandle :: Handle -> Int -> ServerMonad QueryFileResponse
withHandle h n =
do
bs <- liftIO $ BS.hGet h (2 ^ (17 :: Int))
if BS.null bs
then do
liftIO $ hClose h
modify (\s -> s {st_handles = M.delete n (st_handles s)})
return $ Final
else return $ ToBeContinued (BL.toStrict $ compress $ BL.fromStrict bs) $ ContHandle n
| null | https://raw.githubusercontent.com/ekarayel/sync-mht/57d724781fad9eed4e57b4e4f8416633605bdb4b/src/Sync/MerkleTree/Server.hs | haskell | | Map of open file handles with their ids
| Next available id
| Merkle Hash Tree of server file hierarchy
| path of the root of the file hierarchy | module Sync.MerkleTree.Server where
import Codec.Compression.GZip
import Control.Monad.State
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import Data.Map (Map)
import qualified Data.Map as M
import Data.String.Interpolate.IsString
import qualified Data.Text.IO as T
import Data.Time.Clock
import Sync.MerkleTree.CommTypes
import Sync.MerkleTree.Trie
import Sync.MerkleTree.Types
import System.IO
data ServerState = ServerState
st_handles :: Map Int Handle,
st_nextHandle :: Int,
st_trie :: Trie Entry,
st_path :: FilePath
}
type ServerMonad = StateT ServerState IO
startServerState :: FilePath -> Trie Entry -> IO ServerState
startServerState fp trie =
do
T.hPutStr stderr $ [i|Hash of source directory: #{t_hash trie}.\n|]
return $
ServerState
{ st_handles = M.empty,
st_nextHandle = 0,
st_trie = trie,
st_path = fp
}
instance Protocol ServerMonad where
querySetReq l = get >>= (\s -> querySet (st_trie s) l)
queryHashReq l = get >>= (\s -> queryHash (st_trie s) l)
logReq msg = liftIO (T.hPutStr stderr msg) >> return True
queryFileContReq (ContHandle n) =
do
s <- get
let Just h = M.lookup n (st_handles s)
withHandle h n
queryFileReq f =
do
s <- get
h <- liftIO $ openFile (toFilePath (st_path s) f) ReadMode
let n = st_nextHandle s
put $ s {st_handles = M.insert n h (st_handles s), st_nextHandle = n + 1}
withHandle h n
queryTime = liftIO getCurrentTime
terminateReq _ = return True
| Respond to a queryFile or queryFileCont request for a given file handle and i d
withHandle :: Handle -> Int -> ServerMonad QueryFileResponse
withHandle h n =
do
bs <- liftIO $ BS.hGet h (2 ^ (17 :: Int))
if BS.null bs
then do
liftIO $ hClose h
modify (\s -> s {st_handles = M.delete n (st_handles s)})
return $ Final
else return $ ToBeContinued (BL.toStrict $ compress $ BL.fromStrict bs) $ ContHandle n
|
a4497fd67fe970ea1b82c213c18fdbdd8d110b4663e06a21ddbaa0da6fb58582 | soren-n/bidi-higher-rank-poly | AVL.ml | open Infix
open Order
open Extra
type 'a tree =
| Null
| Node of int * int * 'a * 'a tree * 'a tree
let make_null () = Null
let make_node count height data left right =
Node (count, height, data, left, right)
let fold null_case node_case tree =
let rec _visit tree return =
match tree with
| Null -> return null_case
| Node (count, height, data, left, right) ->
_visit left (fun left' ->
_visit right (fun right' ->
return (node_case count height data left' right')))
in
_visit tree identity
let map f tree =
fold Null
(fun c h x l r ->
make_node c h (f x) l r)
tree
let get_count tree =
match tree with
| Null -> 0
| Node (count, _, _, _, _) -> count
let get_height tree =
match tree with
| Null -> 0
| Node (_, height, _, _, _) -> height
let local_inbalance pos tree =
match tree with
| Null -> EQ
| Node (_, _, _, l, r) ->
let h_l = get_height l in
let h_r = get_height r in
let h_diff = h_l - h_r in
match pos with
| EQ ->
if h_diff > 1 then LT else
if h_diff < -1 then GT else
EQ
| LT ->
if h_diff > 1 then LT else
if h_diff < 0 then GT else
EQ
| GT ->
if h_diff > 0 then LT else
if h_diff < -1 then GT else
EQ
let local_rebalance pos tree =
let _rotate_left p =
match p with
| Null -> assert false
| Node (c_p, _, u, a, q) ->
let c_a = get_count a in
let h_a = get_height a in
match q with
| Null -> assert false
| Node (_, _, v, b, c) ->
let c_b = get_count b in
let h_b = get_height b in
let c_l = c_a + c_b + 1 in
let h_l = (max h_a h_b) + 1 in
let h_r = get_height c in
Node (c_p, (max h_l h_r) + 1, v, Node (c_l, h_l, u, a, b), c)
in
let _rotate_right q =
match q with
| Null -> assert false
| Node (c_q, _, v, p, c) ->
let c_c = get_count c in
let h_c = get_height c in
match p with
| Null -> assert false
| Node (_, _, u, a, b) ->
let c_b = get_count b in
let h_b = get_height b in
let c_r = c_b + c_c + 1 in
let h_l = get_height a in
let h_r = (max h_b h_c) + 1 in
Node (c_q, (max h_l h_r) + 1, u, a, Node (c_r, h_r, v, b, c))
in
match local_inbalance pos tree with
| EQ -> tree
| LT -> _rotate_right tree
| GT -> _rotate_left tree
let insert_cont order data tree return =
let rec _visit tree pos updated inserted =
match tree with
| Null -> inserted (make_node 1 1 data Null Null)
| Node (count, height, data', left, right) ->
match order data data' with
| EQ -> updated (make_node count height data left right)
| LT ->
_visit left LT
(updated <== (swap (make_node count height data') right))
(inserted <== (local_rebalance pos) <== (fun left' ->
let height' = max ((get_height left') + 1) height in
make_node (count + 1) height' data' left' right))
| GT ->
_visit right GT
(updated <== (make_node count height data' left))
(inserted <== (local_rebalance pos) <== (fun right' ->
let height' = max ((get_height right') + 1) height in
make_node (count + 1) height' data' left right'))
in
_visit tree EQ return (return <== (local_rebalance EQ))
let insert order data tree =
insert_cont order data tree identity
let remove_cont order data tree return =
let rec _leftmost tree =
match tree with
| Null -> assert false
| Node (_, _, data, Null, _) -> data
| Node (_, _, _, left, _) -> _leftmost left
in
let rec _rightmost tree =
match tree with
| Null -> assert false
| Node (_, _, data, _, Null) -> data
| Node (_, _, _, _, right) -> _rightmost right
in
let rec _visit tree pos data return =
match tree with
| Null -> tree
| Node (count, height, data', left, right) ->
begin match order data data' with
| EQ ->
begin match left, right with
| Null, Null -> return (make_null ())
| Null, _ ->
let data' = _leftmost right in
_visit right GT data'
(return <== (local_rebalance pos) <== (fun right' ->
let height' = max ((get_height right') + 1) height in
make_node (count - 1) height' data' left right'))
| _, Null ->
let data' = _rightmost left in
_visit left LT data'
(return <== (local_rebalance pos) <== (fun left' ->
let height' = max ((get_height left') + 1) height in
make_node (count - 1) height' data' left' right))
| _, _ ->
let left_count = get_count left in
let right_count = get_count right in
begin match int_compare left_count right_count with
| LT ->
let data' = _leftmost right in
_visit right GT data'
(return <== (local_rebalance pos) <== (fun right' ->
let height' = max ((get_height right') + 1) height in
make_node (count - 1) height' data' left right'))
| GT | EQ ->
let data' = _rightmost left in
_visit left LT data'
(return <== (local_rebalance pos) <== (fun left' ->
let height' = max ((get_height left') + 1) height in
make_node (count - 1) height' data' left' right))
end
end
| LT ->
_visit left LT data
(return <== (local_rebalance pos) <== (fun left' ->
let height' = max ((get_height left') + 1) height in
make_node (count - 1) height' data' left' right))
| GT ->
_visit right GT data
(return <== (local_rebalance pos) <== (fun right' ->
let height' = max ((get_height right') + 1) height in
make_node (count - 1) height' data' left right'))
end
in
_visit tree EQ data (return <== (local_rebalance EQ))
let remove order data tree =
remove_cont order data tree identity
let is_member order item tree =
let rec _visit tree =
match tree with
| Null -> false
| Node (_, _, data, left, right) ->
match order item data with
| EQ -> true
| LT -> _visit left
| GT -> _visit right
in
_visit tree
let rec get_member index tree =
match tree with
| Null -> None
| Node (_, _, data, left, right) ->
if index = 0 then Some data else
let left_count = get_count left in
if left_count <= index
then get_member (index - left_count) right
else get_member index left
let rec get_leftmost tree =
match tree with
| Null -> None
| Node (_, _, data, left, _) ->
if left = Null then Some data else
get_leftmost left
let rec get_rightmost tree =
match tree with
| Null -> None
| Node (_, _, data, _, right) ->
if right = Null then Some data else
get_rightmost right
let to_list tree =
fold
(fun result -> result)
(fun _ _ data visit_left visit_right result ->
visit_left (data :: (visit_right result)))
tree []
let from_list items =
let _pop items f =
match items with
| item :: items' -> f item items'
| [] -> assert false
in
let rec _build pos count items return =
match count with
| 0 -> return items 0 (make_null ())
| 1 ->
_pop items (fun data items1 ->
return items1 1 (make_node 1 1 data (make_null ()) (make_null ())))
| _ ->
let n = count - 1 in
let m = n / 2 in
let _left () =
let sm = m + 1 in
_build LT sm items (fun items1 l_h left ->
_pop items1 (fun data items2 ->
_build GT m items2 (fun items3 r_h right ->
let height = (max l_h r_h) + 1 in
return items3 height (make_node count height data left right))))
in
let _right () =
let sm = m + 1 in
_build LT m items (fun items1 l_h left ->
_pop items1 (fun data items2 ->
_build GT sm items2 (fun items3 r_h right ->
let height = (max l_h r_h) + 1 in
return items3 height (make_node count height data left right))))
in
begin match pos, n mod 2 with
| _, 0 ->
_build LT m items (fun items1 l_h left ->
_pop items1 (fun data items2 ->
_build GT m items2 (fun items3 r_h right ->
let height = (max l_h r_h) + 1 in
return items3 height (make_node count height data left right))))
| EQ, _ | LT, _ -> _left ()
| GT, _ -> _right ()
end
in
let count = List.length items in
_build EQ count items (fun _ _ x -> x)
| null | https://raw.githubusercontent.com/soren-n/bidi-higher-rank-poly/c0957759657b30a52235560d1d5f40e9bd2569b3/util/lib/AVL.ml | ocaml | open Infix
open Order
open Extra
type 'a tree =
| Null
| Node of int * int * 'a * 'a tree * 'a tree
let make_null () = Null
let make_node count height data left right =
Node (count, height, data, left, right)
let fold null_case node_case tree =
let rec _visit tree return =
match tree with
| Null -> return null_case
| Node (count, height, data, left, right) ->
_visit left (fun left' ->
_visit right (fun right' ->
return (node_case count height data left' right')))
in
_visit tree identity
let map f tree =
fold Null
(fun c h x l r ->
make_node c h (f x) l r)
tree
let get_count tree =
match tree with
| Null -> 0
| Node (count, _, _, _, _) -> count
let get_height tree =
match tree with
| Null -> 0
| Node (_, height, _, _, _) -> height
let local_inbalance pos tree =
match tree with
| Null -> EQ
| Node (_, _, _, l, r) ->
let h_l = get_height l in
let h_r = get_height r in
let h_diff = h_l - h_r in
match pos with
| EQ ->
if h_diff > 1 then LT else
if h_diff < -1 then GT else
EQ
| LT ->
if h_diff > 1 then LT else
if h_diff < 0 then GT else
EQ
| GT ->
if h_diff > 0 then LT else
if h_diff < -1 then GT else
EQ
let local_rebalance pos tree =
let _rotate_left p =
match p with
| Null -> assert false
| Node (c_p, _, u, a, q) ->
let c_a = get_count a in
let h_a = get_height a in
match q with
| Null -> assert false
| Node (_, _, v, b, c) ->
let c_b = get_count b in
let h_b = get_height b in
let c_l = c_a + c_b + 1 in
let h_l = (max h_a h_b) + 1 in
let h_r = get_height c in
Node (c_p, (max h_l h_r) + 1, v, Node (c_l, h_l, u, a, b), c)
in
let _rotate_right q =
match q with
| Null -> assert false
| Node (c_q, _, v, p, c) ->
let c_c = get_count c in
let h_c = get_height c in
match p with
| Null -> assert false
| Node (_, _, u, a, b) ->
let c_b = get_count b in
let h_b = get_height b in
let c_r = c_b + c_c + 1 in
let h_l = get_height a in
let h_r = (max h_b h_c) + 1 in
Node (c_q, (max h_l h_r) + 1, u, a, Node (c_r, h_r, v, b, c))
in
match local_inbalance pos tree with
| EQ -> tree
| LT -> _rotate_right tree
| GT -> _rotate_left tree
let insert_cont order data tree return =
let rec _visit tree pos updated inserted =
match tree with
| Null -> inserted (make_node 1 1 data Null Null)
| Node (count, height, data', left, right) ->
match order data data' with
| EQ -> updated (make_node count height data left right)
| LT ->
_visit left LT
(updated <== (swap (make_node count height data') right))
(inserted <== (local_rebalance pos) <== (fun left' ->
let height' = max ((get_height left') + 1) height in
make_node (count + 1) height' data' left' right))
| GT ->
_visit right GT
(updated <== (make_node count height data' left))
(inserted <== (local_rebalance pos) <== (fun right' ->
let height' = max ((get_height right') + 1) height in
make_node (count + 1) height' data' left right'))
in
_visit tree EQ return (return <== (local_rebalance EQ))
let insert order data tree =
insert_cont order data tree identity
let remove_cont order data tree return =
let rec _leftmost tree =
match tree with
| Null -> assert false
| Node (_, _, data, Null, _) -> data
| Node (_, _, _, left, _) -> _leftmost left
in
let rec _rightmost tree =
match tree with
| Null -> assert false
| Node (_, _, data, _, Null) -> data
| Node (_, _, _, _, right) -> _rightmost right
in
let rec _visit tree pos data return =
match tree with
| Null -> tree
| Node (count, height, data', left, right) ->
begin match order data data' with
| EQ ->
begin match left, right with
| Null, Null -> return (make_null ())
| Null, _ ->
let data' = _leftmost right in
_visit right GT data'
(return <== (local_rebalance pos) <== (fun right' ->
let height' = max ((get_height right') + 1) height in
make_node (count - 1) height' data' left right'))
| _, Null ->
let data' = _rightmost left in
_visit left LT data'
(return <== (local_rebalance pos) <== (fun left' ->
let height' = max ((get_height left') + 1) height in
make_node (count - 1) height' data' left' right))
| _, _ ->
let left_count = get_count left in
let right_count = get_count right in
begin match int_compare left_count right_count with
| LT ->
let data' = _leftmost right in
_visit right GT data'
(return <== (local_rebalance pos) <== (fun right' ->
let height' = max ((get_height right') + 1) height in
make_node (count - 1) height' data' left right'))
| GT | EQ ->
let data' = _rightmost left in
_visit left LT data'
(return <== (local_rebalance pos) <== (fun left' ->
let height' = max ((get_height left') + 1) height in
make_node (count - 1) height' data' left' right))
end
end
| LT ->
_visit left LT data
(return <== (local_rebalance pos) <== (fun left' ->
let height' = max ((get_height left') + 1) height in
make_node (count - 1) height' data' left' right))
| GT ->
_visit right GT data
(return <== (local_rebalance pos) <== (fun right' ->
let height' = max ((get_height right') + 1) height in
make_node (count - 1) height' data' left right'))
end
in
_visit tree EQ data (return <== (local_rebalance EQ))
let remove order data tree =
remove_cont order data tree identity
let is_member order item tree =
let rec _visit tree =
match tree with
| Null -> false
| Node (_, _, data, left, right) ->
match order item data with
| EQ -> true
| LT -> _visit left
| GT -> _visit right
in
_visit tree
let rec get_member index tree =
match tree with
| Null -> None
| Node (_, _, data, left, right) ->
if index = 0 then Some data else
let left_count = get_count left in
if left_count <= index
then get_member (index - left_count) right
else get_member index left
let rec get_leftmost tree =
match tree with
| Null -> None
| Node (_, _, data, left, _) ->
if left = Null then Some data else
get_leftmost left
let rec get_rightmost tree =
match tree with
| Null -> None
| Node (_, _, data, _, right) ->
if right = Null then Some data else
get_rightmost right
let to_list tree =
fold
(fun result -> result)
(fun _ _ data visit_left visit_right result ->
visit_left (data :: (visit_right result)))
tree []
let from_list items =
let _pop items f =
match items with
| item :: items' -> f item items'
| [] -> assert false
in
let rec _build pos count items return =
match count with
| 0 -> return items 0 (make_null ())
| 1 ->
_pop items (fun data items1 ->
return items1 1 (make_node 1 1 data (make_null ()) (make_null ())))
| _ ->
let n = count - 1 in
let m = n / 2 in
let _left () =
let sm = m + 1 in
_build LT sm items (fun items1 l_h left ->
_pop items1 (fun data items2 ->
_build GT m items2 (fun items3 r_h right ->
let height = (max l_h r_h) + 1 in
return items3 height (make_node count height data left right))))
in
let _right () =
let sm = m + 1 in
_build LT m items (fun items1 l_h left ->
_pop items1 (fun data items2 ->
_build GT sm items2 (fun items3 r_h right ->
let height = (max l_h r_h) + 1 in
return items3 height (make_node count height data left right))))
in
begin match pos, n mod 2 with
| _, 0 ->
_build LT m items (fun items1 l_h left ->
_pop items1 (fun data items2 ->
_build GT m items2 (fun items3 r_h right ->
let height = (max l_h r_h) + 1 in
return items3 height (make_node count height data left right))))
| EQ, _ | LT, _ -> _left ()
| GT, _ -> _right ()
end
in
let count = List.length items in
_build EQ count items (fun _ _ x -> x)
|
|
82381d74b3a90b63ffd92c673d7ff77e0d582d42b7df76af8efebc9bba6a6a78 | hexlet-codebattle/battle_asserts | stickers_count.clj | (ns battle-asserts.issues.stickers-count
(:require [clojure.test.check.generators :as gen]))
(def level :elementary)
(def tags ["games"])
(def description
{:en "Given an `n * n * n` Rubik's cube, find the number of stickers that are needed to cover the whole cube."
:ru "Дан `n * n * n` кубик Рубика, найдите необходимое количество стикеров, чтобы покрыть ими весь кубик."})
(def signature
{:input [{:argument-name "num" :type {:name "integer"}}]
:output {:type {:name "integer"}}})
(defn arguments-generator
[]
(gen/tuple gen/small-integer))
(def test-data
[{:expected 6 :arguments [1]}
{:expected 24 :arguments [2]}
{:expected 54 :arguments [3]}])
(defn solution [num]
(* 6 num num))
| null | https://raw.githubusercontent.com/hexlet-codebattle/battle_asserts/dc5ed5ebae4b38d6251abda3da23590cbfa5af5f/src/battle_asserts/issues/stickers_count.clj | clojure | (ns battle-asserts.issues.stickers-count
(:require [clojure.test.check.generators :as gen]))
(def level :elementary)
(def tags ["games"])
(def description
{:en "Given an `n * n * n` Rubik's cube, find the number of stickers that are needed to cover the whole cube."
:ru "Дан `n * n * n` кубик Рубика, найдите необходимое количество стикеров, чтобы покрыть ими весь кубик."})
(def signature
{:input [{:argument-name "num" :type {:name "integer"}}]
:output {:type {:name "integer"}}})
(defn arguments-generator
[]
(gen/tuple gen/small-integer))
(def test-data
[{:expected 6 :arguments [1]}
{:expected 24 :arguments [2]}
{:expected 54 :arguments [3]}])
(defn solution [num]
(* 6 num num))
|
|
c08b1a5c4c2837c8ca8b6c92d7a52dbadd9374915ac2d3d3a35ea78e9d820996 | Bodigrim/chimera | Test.hs | # LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -fno - warn - orphans #
module Main where
import Test.QuickCheck.Function
import Test.Tasty
import Test.Tasty.HUnit as H
import Test.Tasty.QuickCheck as QC
import Data.Bits
import Data.Foldable
import Data.Function (fix)
import qualified Data.List as L
import qualified Data.Vector.Generic as G
import Data.Chimera.ContinuousMapping
import Data.Chimera.WheelMapping
import Data.Chimera (UChimera, VChimera)
import qualified Data.Chimera as Ch
instance (G.Vector v a, Arbitrary a) => Arbitrary (Ch.Chimera v a) where
arbitrary = Ch.tabulateM (const arbitrary)
main :: IO ()
main = defaultMain $ testGroup "All"
[ contMapTests
, wheelMapTests
, chimeraTests
]
contMapTests :: TestTree
contMapTests = testGroup "ContinuousMapping"
[ testGroup "wordToInt . intToWord"
[ QC.testProperty "random" $ \i -> w2i_i2w i === i
, H.testCase "maxBound" $ assertEqual "should be equal" maxBound (w2i_i2w maxBound)
, H.testCase "minBound" $ assertEqual "should be equal" minBound (w2i_i2w minBound)
]
, testGroup "intToWord . wordToInt"
[ QC.testProperty "random" $ \i -> i2w_w2i i === i
, H.testCase "maxBound" $ assertEqual "should be equal" maxBound (i2w_w2i maxBound)
, H.testCase "minBound" $ assertEqual "should be equal" minBound (i2w_w2i minBound)
]
, testGroup "to . from Z-curve 2D"
[ QC.testProperty "random" $ \z -> uncurry toZCurve (fromZCurve z) === z
]
, testGroup "from . to Z-curve 2D"
[ QC.testProperty "random" $ \x y -> fromZCurve (toZCurve x y) === (x `rem` (1 `shiftL` 32), y `rem` (1 `shiftL` 32))
]
, testGroup "to . from Z-curve 3D"
[ QC.testProperty "random" $ \t -> (\(x, y, z) -> toZCurve3 x y z) (fromZCurve3 t) === t `rem` (1 `shiftL` 63)
]
, testGroup "from . to Z-curve 3D"
[ QC.testProperty "random" $ \x y z -> fromZCurve3 (toZCurve3 x y z) === (x `rem` (1 `shiftL` 21), y `rem` (1 `shiftL` 21), z `rem` (1 `shiftL` 21))
]
]
wheelMapTests :: TestTree
wheelMapTests = testGroup "WheelMapping"
[ testGroup "toWheel . fromWheel"
[ QC.testProperty "2" $ \(Shrink2 x) -> x < maxBound `div` 2 ==> toWheel2 (fromWheel2 x) === x
, QC.testProperty "6" $ \(Shrink2 x) -> x < maxBound `div` 3 ==> toWheel6 (fromWheel6 x) === x
, QC.testProperty "30" $ \(Shrink2 x) -> x < maxBound `div` 4 ==> toWheel30 (fromWheel30 x) === x
, QC.testProperty "210" $ \(Shrink2 x) -> x < maxBound `div` 5 ==> toWheel210 (fromWheel210 x) === x
]
]
chimeraTests :: TestTree
chimeraTests = testGroup "Chimera"
[ QC.testProperty "index . tabulate = id" $
\(Fun _ (f :: Word -> Bool)) ix ->
let jx = ix `mod` 65536 in
f jx === Ch.index (Ch.tabulate f :: UChimera Bool) jx
, QC.testProperty "memoize = id" $
\(Fun _ (f :: Word -> Bool)) ix ->
let jx = ix `mod` 65536 in
f jx === Ch.memoize f jx
, QC.testProperty "index . tabulateFix = fix" $
\(Fun _ g) ix ->
let jx = ix `mod` 65536 in
let f = mkUnfix g in
fix f jx === Ch.index (Ch.tabulateFix f :: UChimera Bool) jx
, QC.testProperty "index . tabulateFix' = fix" $
\(Fun _ g) ix ->
let jx = ix `mod` 65536 in
let f = mkUnfix g in
fix f jx === Ch.index (Ch.tabulateFix' f :: UChimera Bool) jx
, QC.testProperty "memoizeFix = fix" $
\(Fun _ g) ix ->
let jx = ix `mod` 65536 in
let f = mkUnfix g in
fix f jx === Ch.memoizeFix f jx
, QC.testProperty "iterate" $
\(Fun _ (f :: Word -> Word)) seed ix ->
let jx = ix `mod` 65536 in
iterate f seed !! fromIntegral jx === Ch.index (Ch.iterate f seed :: UChimera Word) jx
, QC.testProperty "unfoldr" $
\(Fun _ (f :: Word -> (Int, Word))) seed ix ->
let jx = ix `mod` 65536 in
L.unfoldr (Just . f) seed !! fromIntegral jx === Ch.index (Ch.unfoldr f seed :: UChimera Int) jx
, QC.testProperty "interleave" $
\(Fun _ (f :: Word -> Bool)) (Fun _ (g :: Word -> Bool)) ix ->
let jx = ix `mod` 65536 in
(if even jx then f else g) (jx `quot` 2) === Ch.index (Ch.interleave (Ch.tabulate f) (Ch.tabulate g) :: UChimera Bool) jx
, QC.testProperty "pure" $
\x ix ->
let jx = ix `mod` 65536 in
x === Ch.index (pure x :: VChimera Word) jx
, QC.testProperty "cycle" $
\xs ix -> not (null xs) ==>
let jx = ix `mod` 65536 in
let vs = G.fromList xs in
vs G.! (fromIntegral jx `mod` G.length vs) === Ch.index (Ch.cycle vs :: UChimera Bool) jx
, QC.testProperty "toList" $
\x xs -> xs === take (length xs) (Ch.toList (Ch.fromListWithDef x xs :: UChimera Bool))
, QC.testProperty "fromListWithDef" $
\x xs ix ->
let jx = ix `mod` 65536 in
(if fromIntegral jx < length xs then xs !! fromIntegral jx else x) ===
Ch.index (Ch.fromListWithDef x xs :: UChimera Bool) jx
, QC.testProperty "fromVectorWithDef" $
\x xs ix ->
let jx = ix `mod` 65536 in
let vs = G.fromList xs in
(if fromIntegral jx < length xs then vs G.! fromIntegral jx else x) ===
Ch.index (Ch.fromVectorWithDef x vs :: UChimera Bool) jx
, QC.testProperty "mapWithKey" $
\(Blind bs) (Fun _ (g :: Word -> Word)) ix ->
let jx = ix `mod` 65536 in
g (Ch.index bs jx) === Ch.index (Ch.mapSubvectors (G.map g) bs :: UChimera Word) jx
, QC.testProperty "zipWithKey" $
\(Blind bs1) (Blind bs2) (Fun _ (g :: (Word, Word) -> Word)) ix ->
let jx = ix `mod` 65536 in
g (Ch.index bs1 jx, Ch.index bs2 jx) === Ch.index (Ch.zipWithSubvectors (G.zipWith (curry g)) bs1 bs2 :: UChimera Word) jx
, QC.testProperty "sliceSubvectors" $
\x xs ix ->
let vs = G.fromList xs in
fold (Ch.sliceSubvectors ix (G.length vs - max 0 ix) (Ch.fromVectorWithDef x vs :: UChimera Bool)) === G.drop ix vs
]
-------------------------------------------------------------------------------
Utils
w2i_i2w :: Int -> Int
w2i_i2w = wordToInt . intToWord
i2w_w2i :: Word -> Word
i2w_w2i = intToWord . wordToInt
mkUnfix :: (Word -> [Word]) -> (Word -> Bool) -> Word -> Bool
mkUnfix splt f x
= foldl' (==) True
$ map f
$ takeWhile (\y -> 0 <= y && y < x)
$ splt x
| null | https://raw.githubusercontent.com/Bodigrim/chimera/d63642b996e2b8cceb1bfa9607dd707423ff44c9/test/Test.hs | haskell | ----------------------------------------------------------------------------- | # LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -fno - warn - orphans #
module Main where
import Test.QuickCheck.Function
import Test.Tasty
import Test.Tasty.HUnit as H
import Test.Tasty.QuickCheck as QC
import Data.Bits
import Data.Foldable
import Data.Function (fix)
import qualified Data.List as L
import qualified Data.Vector.Generic as G
import Data.Chimera.ContinuousMapping
import Data.Chimera.WheelMapping
import Data.Chimera (UChimera, VChimera)
import qualified Data.Chimera as Ch
instance (G.Vector v a, Arbitrary a) => Arbitrary (Ch.Chimera v a) where
arbitrary = Ch.tabulateM (const arbitrary)
main :: IO ()
main = defaultMain $ testGroup "All"
[ contMapTests
, wheelMapTests
, chimeraTests
]
contMapTests :: TestTree
contMapTests = testGroup "ContinuousMapping"
[ testGroup "wordToInt . intToWord"
[ QC.testProperty "random" $ \i -> w2i_i2w i === i
, H.testCase "maxBound" $ assertEqual "should be equal" maxBound (w2i_i2w maxBound)
, H.testCase "minBound" $ assertEqual "should be equal" minBound (w2i_i2w minBound)
]
, testGroup "intToWord . wordToInt"
[ QC.testProperty "random" $ \i -> i2w_w2i i === i
, H.testCase "maxBound" $ assertEqual "should be equal" maxBound (i2w_w2i maxBound)
, H.testCase "minBound" $ assertEqual "should be equal" minBound (i2w_w2i minBound)
]
, testGroup "to . from Z-curve 2D"
[ QC.testProperty "random" $ \z -> uncurry toZCurve (fromZCurve z) === z
]
, testGroup "from . to Z-curve 2D"
[ QC.testProperty "random" $ \x y -> fromZCurve (toZCurve x y) === (x `rem` (1 `shiftL` 32), y `rem` (1 `shiftL` 32))
]
, testGroup "to . from Z-curve 3D"
[ QC.testProperty "random" $ \t -> (\(x, y, z) -> toZCurve3 x y z) (fromZCurve3 t) === t `rem` (1 `shiftL` 63)
]
, testGroup "from . to Z-curve 3D"
[ QC.testProperty "random" $ \x y z -> fromZCurve3 (toZCurve3 x y z) === (x `rem` (1 `shiftL` 21), y `rem` (1 `shiftL` 21), z `rem` (1 `shiftL` 21))
]
]
wheelMapTests :: TestTree
wheelMapTests = testGroup "WheelMapping"
[ testGroup "toWheel . fromWheel"
[ QC.testProperty "2" $ \(Shrink2 x) -> x < maxBound `div` 2 ==> toWheel2 (fromWheel2 x) === x
, QC.testProperty "6" $ \(Shrink2 x) -> x < maxBound `div` 3 ==> toWheel6 (fromWheel6 x) === x
, QC.testProperty "30" $ \(Shrink2 x) -> x < maxBound `div` 4 ==> toWheel30 (fromWheel30 x) === x
, QC.testProperty "210" $ \(Shrink2 x) -> x < maxBound `div` 5 ==> toWheel210 (fromWheel210 x) === x
]
]
chimeraTests :: TestTree
chimeraTests = testGroup "Chimera"
[ QC.testProperty "index . tabulate = id" $
\(Fun _ (f :: Word -> Bool)) ix ->
let jx = ix `mod` 65536 in
f jx === Ch.index (Ch.tabulate f :: UChimera Bool) jx
, QC.testProperty "memoize = id" $
\(Fun _ (f :: Word -> Bool)) ix ->
let jx = ix `mod` 65536 in
f jx === Ch.memoize f jx
, QC.testProperty "index . tabulateFix = fix" $
\(Fun _ g) ix ->
let jx = ix `mod` 65536 in
let f = mkUnfix g in
fix f jx === Ch.index (Ch.tabulateFix f :: UChimera Bool) jx
, QC.testProperty "index . tabulateFix' = fix" $
\(Fun _ g) ix ->
let jx = ix `mod` 65536 in
let f = mkUnfix g in
fix f jx === Ch.index (Ch.tabulateFix' f :: UChimera Bool) jx
, QC.testProperty "memoizeFix = fix" $
\(Fun _ g) ix ->
let jx = ix `mod` 65536 in
let f = mkUnfix g in
fix f jx === Ch.memoizeFix f jx
, QC.testProperty "iterate" $
\(Fun _ (f :: Word -> Word)) seed ix ->
let jx = ix `mod` 65536 in
iterate f seed !! fromIntegral jx === Ch.index (Ch.iterate f seed :: UChimera Word) jx
, QC.testProperty "unfoldr" $
\(Fun _ (f :: Word -> (Int, Word))) seed ix ->
let jx = ix `mod` 65536 in
L.unfoldr (Just . f) seed !! fromIntegral jx === Ch.index (Ch.unfoldr f seed :: UChimera Int) jx
, QC.testProperty "interleave" $
\(Fun _ (f :: Word -> Bool)) (Fun _ (g :: Word -> Bool)) ix ->
let jx = ix `mod` 65536 in
(if even jx then f else g) (jx `quot` 2) === Ch.index (Ch.interleave (Ch.tabulate f) (Ch.tabulate g) :: UChimera Bool) jx
, QC.testProperty "pure" $
\x ix ->
let jx = ix `mod` 65536 in
x === Ch.index (pure x :: VChimera Word) jx
, QC.testProperty "cycle" $
\xs ix -> not (null xs) ==>
let jx = ix `mod` 65536 in
let vs = G.fromList xs in
vs G.! (fromIntegral jx `mod` G.length vs) === Ch.index (Ch.cycle vs :: UChimera Bool) jx
, QC.testProperty "toList" $
\x xs -> xs === take (length xs) (Ch.toList (Ch.fromListWithDef x xs :: UChimera Bool))
, QC.testProperty "fromListWithDef" $
\x xs ix ->
let jx = ix `mod` 65536 in
(if fromIntegral jx < length xs then xs !! fromIntegral jx else x) ===
Ch.index (Ch.fromListWithDef x xs :: UChimera Bool) jx
, QC.testProperty "fromVectorWithDef" $
\x xs ix ->
let jx = ix `mod` 65536 in
let vs = G.fromList xs in
(if fromIntegral jx < length xs then vs G.! fromIntegral jx else x) ===
Ch.index (Ch.fromVectorWithDef x vs :: UChimera Bool) jx
, QC.testProperty "mapWithKey" $
\(Blind bs) (Fun _ (g :: Word -> Word)) ix ->
let jx = ix `mod` 65536 in
g (Ch.index bs jx) === Ch.index (Ch.mapSubvectors (G.map g) bs :: UChimera Word) jx
, QC.testProperty "zipWithKey" $
\(Blind bs1) (Blind bs2) (Fun _ (g :: (Word, Word) -> Word)) ix ->
let jx = ix `mod` 65536 in
g (Ch.index bs1 jx, Ch.index bs2 jx) === Ch.index (Ch.zipWithSubvectors (G.zipWith (curry g)) bs1 bs2 :: UChimera Word) jx
, QC.testProperty "sliceSubvectors" $
\x xs ix ->
let vs = G.fromList xs in
fold (Ch.sliceSubvectors ix (G.length vs - max 0 ix) (Ch.fromVectorWithDef x vs :: UChimera Bool)) === G.drop ix vs
]
Utils
w2i_i2w :: Int -> Int
w2i_i2w = wordToInt . intToWord
i2w_w2i :: Word -> Word
i2w_w2i = intToWord . wordToInt
mkUnfix :: (Word -> [Word]) -> (Word -> Bool) -> Word -> Bool
mkUnfix splt f x
= foldl' (==) True
$ map f
$ takeWhile (\y -> 0 <= y && y < x)
$ splt x
|
bda5e706ccc2a6cc4456ebeedf4fd9a5ba4661d74b49b988c9d18fd399c857a9 | benoitc/cbt | cbt_btree.erl | 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
%
% -2.0
%
% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
% License for the specific language governing permissions and limitations under
% the License.
-module(cbt_btree).
-export([open/2, open/3]).
-export([query_modify/4, add/2, add_remove/3]).
-export([lookup/2]).
-export([fold/3, fold/4]).
-export([fold_reduce/4, full_reduce/1, final_reduce/2]).
-export([size/1]).
-export([get_state/1]).
-export([set_options/2]).
-export([less/3]).
-include("cbt.hrl").
-define(BTREE_KV_CHUNK_THRESHOLD, 7168).
-define(BTREE_KP_CHUNK_THRESHOLD, 6144).
-type cbtree() :: #btree{}.
-type cbtree_root() :: {integer(), list(), integer()}.
-type cbtree_options() :: [{backend, cbt_file | atom()}
| {split, fun()} | {join, fun()} | {less, fun()}
| {reduce, fun()}
| {compression, cbt_compress:compression_method()}
| {kv_chunk_threshold, integer()}
| {kp_chunk_threshold, integer()}].
-type cbt_kv() :: {Key::any(), Val::any()}.
-type cbt_kvs() :: [cbt_kv()].
-type cbt_keys() :: [term()].
-type cbt_fold_options() :: [{dir, fwd | rev} | {start_key, term()} |
{end_key, term()} | {end_key_gt, term()} |
{key_group_fun, fun()}].
-export_type([cbtree/0]).
-export_type([cbtree_root/0]).
-export_type([cbtree_options/0]).
-export_type([cbt_kv/0, cbt_kvs/0]).
-export_type([cbt_keys/0]).
-export_type([cbt_fold_options/0]).
%% @doc open a btree using the default backend cbt_file.
pass in ' nil ' for State if a new Btree .
-spec open(State::nil | cbtree(), Ref::cbt_backend:ref()) -> {ok, cbtree()}.
open(State, Ref) ->
{ok, #btree{root=State, ref=Ref, mod=cbt_file}}.
%% @doc open a btree . Default backend is cbt_file.
pass in ' nil ' for State if a new Btree .
%% Options:
%% <ul>
< li > { backend , Module } : backend to use to read / append items . Default
%% is cbt_file.</li>
%% <li> {split, fun(Btree, Value)} : Take a value and extract content if
%% needed from it. It returns a {key, Value} tuple. You don't need to
%% set such function if you already give a {Key, Value} tuple to your
%% add/add_remove functions.</li>
%% <li>{join, fun(Key, Value)} : The fonction takes the key and value and
%% return a new Value ussed when you lookup. By default it return a
%% {Key, Value} .</li>
%% <li>{reduce_fun, ReduceFun} : pass the reduce fun</li>
< li > { compression , nonde | snappy } : the compression methods used to
%% compress the data</li>
< li>{less , LessFun(KeyA , KeyB ) } : function used to order the btree that
compare two keys</li >
%% </ul>
-spec open(State::nil | cbtree(), Ref::cbt_backend:ref(),
Options::cbtree_options()) -> {ok, cbtree()}.
open(State, Ref, Options) ->
{ok, set_options(#btree{root=State, ref=Ref, mod=cbt_file}, Options)}.
%% @doc return the latest btree root that will be stored in the database
%% header or value
-spec get_state(Btree::cbtree()) -> State::tuple().
get_state(#btree{root=Root}) ->
Root.
@doc set btreee options
-spec set_options(Btree::cbtree(), Options::cbtree_options()) -> Btree2::cbtree().
set_options(Bt, []) ->
Bt;
set_options(Bt, [{backend, Mod}|Rest]) ->
set_options(Bt#btree{mod=Mod}, Rest);
set_options(Bt, [{split, Extract}|Rest]) ->
set_options(Bt#btree{extract_kv=Extract}, Rest);
set_options(Bt, [{join, Assemble}|Rest]) ->
set_options(Bt#btree{assemble_kv=Assemble}, Rest);
set_options(Bt, [{less, Less}|Rest]) ->
set_options(Bt#btree{less=Less}, Rest);
set_options(Bt, [{reduce, Reduce}|Rest]) ->
set_options(Bt#btree{reduce=Reduce}, Rest);
set_options(Bt, [{compression, Comp}|Rest]) ->
set_options(Bt#btree{compression=Comp}, Rest);
set_options(Bt, [{kv_chunk_threshold, Threshold}|Rest]) ->
set_options(Bt#btree{kv_chunk_threshold = Threshold}, Rest);
set_options(Bt, [{kp_chunk_threshold, Threshold}|Rest]) ->
set_options(Bt#btree{kp_chunk_threshold = Threshold}, Rest).
%% @doc return the size in bytes of a btree
-spec size(Btree::cbtree()) -> Size::integer().
size(#btree{root = nil}) ->
0;
size(#btree{root = {_P, _Red, Size}}) ->
Size.
%% --------------------------------
Btree updates methods
%% --------------------------------
@doc insert a list of key / values in the
-spec add(Btree::cbtree(), InsertKeyValues::cbt_kvs()) ->
{ok, Btree2::cbtree()}.
add(Bt, InsertKeyValues) ->
add_remove(Bt, InsertKeyValues, []).
@doc insert and remove a list of key / values in the btree in one
%% write.
-spec add_remove(Btree::cbtree(), InsertKeyValues::cbt_kvs(),
RemoveKeys::cbt_keys()) -> {ok, Btree2::cbtree()}.
add_remove(Bt, InsertKeyValues, RemoveKeys) ->
{ok, [], Bt2} = query_modify(Bt, [], InsertKeyValues, RemoveKeys),
{ok, Bt2}.
%% @doc insert and remove a list of key/values and retrieve a list of
key / values from their key in the btree in one call .
-spec query_modify(Btree::cbtree(), LookupKeys::cbt_keys(),
InsertKeyValues::cbt_kvs(), RemoveKeys::cbt_keys()) ->
{ok, FoundKeyValues::cbt_kvs(), Btree2::cbtree()}.
query_modify(Bt, LookupKeys, InsertValues, RemoveKeys) ->
#btree{root=Root} = Bt,
InsertActions = lists:map(
fun(KeyValue) ->
{Key, Value} = extract(Bt, KeyValue),
{insert, Key, Value}
end, InsertValues),
RemoveActions = [{remove, Key, nil} || Key <- RemoveKeys],
FetchActions = [{fetch, Key, nil} || Key <- LookupKeys],
SortFun =
fun({OpA, A, _}, {OpB, B, _}) ->
case A == B of
% A and B are equal, sort by op.
true -> op_order(OpA) < op_order(OpB);
false ->
less(Bt, A, B)
end
end,
Actions = lists:sort(SortFun, lists:append([InsertActions, RemoveActions,
FetchActions])),
{ok, KeyPointers, QueryResults} = modify_node(Bt, Root, Actions, []),
{ok, NewRoot} = complete_root(Bt, KeyPointers),
{ok, QueryResults, Bt#btree{root=NewRoot}}.
%% --------------------------------
%% Btree query methods
%% --------------------------------
@doc lookup for a list of keys in the btree
%% Results are returned in the same order as the keys. If the key is
%% not_found the `not_found' result is appended to the list.
-spec lookup(Btree::cbtree(), Keys::cbt_keys()) -> [{ok, cbt_kv()} | not_found].
lookup(#btree{root=Root, less=Less}=Bt, Keys) ->
SortedKeys = case Less of
undefined -> lists:sort(Keys);
_ -> lists:sort(Less, Keys)
end,
{ok, SortedResults} = lookup(Bt, Root, SortedKeys),
% We want to return the results in the same order as the keys were input
% but we may have changed the order when we sorted. So we need to put the
% order back into the results.
cbt_util:reorder_results(Keys, SortedResults).
lookup(_Bt, nil, Keys) ->
{ok, [{Key, not_found} || Key <- Keys]};
lookup(Bt, Node, Keys) ->
Pointer = element(1, Node),
{NodeType, NodeList} = get_node(Bt, Pointer),
case NodeType of
kp_node ->
lookup_kpnode(Bt, list_to_tuple(NodeList), 1, Keys, []);
kv_node ->
lookup_kvnode(Bt, list_to_tuple(NodeList), 1, Keys, [])
end.
@doc fold key / values in the
-spec fold(Btree::cbtree(), Fun::fun(), Acc::term()) ->
{ok, {KVs::cbt_kvs(), Reductions::[term()]}, Acc2::term()}.
fold(Bt, Fun, Acc) ->
fold(Bt, Fun, Acc, []).
-spec fold(Btree::cbtree(), Fun::fun(), Acc::term(),
Options::cbt_fold_options()) ->
{ok, {KVs::cbt_kvs(), Reductions::[term()]}, Acc2::term()}.
fold(#btree{root=nil}, _Fun, Acc, _Options) ->
{ok, {[], []}, Acc};
fold(#btree{root=Root}=Bt, Fun, Acc, Options) ->
Dir = cbt_util:get_value(dir, Options, fwd),
InRange = make_key_in_end_range_function(Bt, Dir, Options),
Result =
case cbt_util:get_value(start_key, Options) of
undefined ->
stream_node(Bt, [], Bt#btree.root, InRange, Dir,
convert_fun_arity(Fun), Acc);
StartKey ->
stream_node(Bt, [], Bt#btree.root, StartKey, InRange, Dir,
convert_fun_arity(Fun), Acc)
end,
case Result of
{ok, Acc2}->
FullReduction = element(2, Root),
{ok, {[], [FullReduction]}, Acc2};
{stop, LastReduction, Acc2} ->
{ok, LastReduction, Acc2}
end.
%% @doc apply the reduce function on last reductions.
-spec final_reduce(Btree::cbtree(), LastReduction::{any(), any()}) -> term().
final_reduce(#btree{reduce=Reduce}, Val) ->
do_final_reduce(Reduce, Val).
do_final_reduce(Reduce, {[], []}) ->
Reduce(reduce, []);
do_final_reduce(_Bt, {[], [Red]}) ->
Red;
do_final_reduce(Reduce, {[], Reductions}) ->
Reduce(rereduce, Reductions);
do_final_reduce(Reduce, {KVs, Reductions}) ->
Red = Reduce(reduce, KVs),
do_final_reduce(Reduce, {[], [Red | Reductions]}).
%% @doc fold reduce values.
%%
-spec fold_reduce(Btree::cbtree(), FoldFun::fun(), Acc::any(),
Options::cbt_fold_options()) -> {ok, Acc2::term()}.
fold_reduce(#btree{root=Root}=Bt, Fun, Acc, Options) ->
Dir = cbt_util:get_value(dir, Options, fwd),
StartKey = cbt_util:get_value(start_key, Options),
InEndRangeFun = make_key_in_end_range_function(Bt, Dir, Options),
KeyGroupFun = cbt_util:get_value(key_group_fun, Options, fun(_,_) -> true end),
try
{ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} =
reduce_stream_node(Bt, Dir, Root, StartKey, InEndRangeFun, undefined, [], [],
KeyGroupFun, Fun, Acc),
if GroupedKey2 == undefined ->
{ok, Acc2};
true ->
case Fun(GroupedKey2, {GroupedKVsAcc2, GroupedRedsAcc2}, Acc2) of
{ok, Acc3} -> {ok, Acc3};
{stop, Acc3} -> {ok, Acc3}
end
end
catch
throw:{stop, AccDone} -> {ok, AccDone}
end.
@doc return the full reduceed value from the btree .
-spec full_reduce(Btree::cbtree()) -> {ok, term()}.
full_reduce(#btree{root=nil,reduce=Reduce}) ->
{ok, Reduce(reduce, [])};
full_reduce(#btree{root=Root}) ->
{ok, element(2, Root)}.
extract(#btree{extract_kv=identity}, Value) ->
Value;
extract(#btree{extract_kv=Extract}, Value) ->
Extract(Value).
assemble(#btree{assemble_kv=identity}, KeyValue) ->
KeyValue;
assemble(#btree{assemble_kv=Assemble}, KeyValue) ->
Assemble(KeyValue).
less(#btree{less=undefined}, A, B) ->
A < B;
less(#btree{less=Less}, A, B) ->
Less(A, B).
%% ------------------------------------
%% PRIVATE API
%% ------------------------------------
wraps a 2 arity function with the proper 3 arity function
convert_fun_arity(Fun) when is_function(Fun, 2) ->
fun
(visit, KV, _Reds, AccIn) -> Fun(KV, AccIn);
(traverse, _K, _Red, AccIn) -> {ok, AccIn}
end;
convert_fun_arity(Fun) when is_function(Fun, 3) ->
fun
(visit, KV, Reds, AccIn) -> Fun(KV, Reds, AccIn);
(traverse, _K, _Red, AccIn) -> {ok, AccIn}
end;
convert_fun_arity(Fun) when is_function(Fun, 4) ->
Already arity 4
make_key_in_end_range_function(Bt, fwd, Options) ->
case cbt_util:get_value(end_key_gt, Options) of
undefined ->
case cbt_util:get_value(end_key, Options) of
undefined ->
fun(_Key) -> true end;
LastKey ->
fun(Key) -> not less(Bt, LastKey, Key) end
end;
EndKey ->
fun(Key) -> less(Bt, Key, EndKey) end
end;
make_key_in_end_range_function(Bt, rev, Options) ->
case cbt_util:get_value(end_key_gt, Options) of
undefined ->
case cbt_util:get_value(end_key, Options) of
undefined ->
fun(_Key) -> true end;
LastKey ->
fun(Key) -> not less(Bt, Key, LastKey) end
end;
EndKey ->
fun(Key) -> less(Bt, EndKey, Key) end
end.
% for ordering different operations with the same key.
% fetch < remove < insert
op_order(fetch) -> 1;
op_order(remove) -> 2;
op_order(insert) -> 3.
lookup_kpnode(_Bt, _NodeTuple, _LowerBound, [], Output) ->
{ok, lists:reverse(Output)};
lookup_kpnode(_Bt, NodeTuple, LowerBound, Keys, Output) when tuple_size(NodeTuple) < LowerBound ->
{ok, lists:reverse(Output, [{Key, not_found} || Key <- Keys])};
lookup_kpnode(Bt, NodeTuple, LowerBound, [FirstLookupKey | _] = LookupKeys, Output) ->
N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), FirstLookupKey),
{Key, PointerInfo} = element(N, NodeTuple),
SplitFun = fun(LookupKey) -> not less(Bt, Key, LookupKey) end,
case lists:splitwith(SplitFun, LookupKeys) of
{[], GreaterQueries} ->
lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, Output);
{LessEqQueries, GreaterQueries} ->
{ok, Results} = lookup(Bt, PointerInfo, LessEqQueries),
lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, lists:reverse(Results, Output))
end.
lookup_kvnode(_Bt, _NodeTuple, _LowerBound, [], Output) ->
{ok, lists:reverse(Output)};
lookup_kvnode(_Bt, NodeTuple, LowerBound, Keys, Output) when tuple_size(NodeTuple) < LowerBound ->
% keys not found
{ok, lists:reverse(Output, [{Key, not_found} || Key <- Keys])};
lookup_kvnode(Bt, NodeTuple, LowerBound, [LookupKey | RestLookupKeys], Output) ->
N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), LookupKey),
KV = {Key, _Value} = element(N, NodeTuple),
case less(Bt, LookupKey, Key) of
true ->
LookupKey is less than Key
lookup_kvnode(Bt, NodeTuple, N, RestLookupKeys, [{LookupKey, not_found} | Output]);
false ->
case less(Bt, Key, LookupKey) of
true ->
LookupKey is greater than Key
lookup_kvnode(Bt, NodeTuple, N+1, RestLookupKeys,
[{LookupKey, not_found} | Output]);
false ->
LookupKey is equal to Key
lookup_kvnode(Bt, NodeTuple, N, RestLookupKeys,
[{LookupKey, {ok, assemble(Bt, KV)}} | Output])
end
end.
complete_root(_Bt, []) ->
{ok, nil};
complete_root(_Bt, [{_Key, PointerInfo}])->
{ok, PointerInfo};
complete_root(Bt, KPs) ->
{ok, ResultKeyPointers} = write_node(Bt, kp_node, KPs),
complete_root(Bt, ResultKeyPointers).
chunkify(#btree{kp_chunk_threshold = T}, kp_node, InList) ->
chunkify(T, InList);
chunkify(#btree{kv_chunk_threshold = T}, kv_node, InList) ->
chunkify(T, InList).
chunkify(ChunkThreshold0, InList) ->
case ?term_size(InList) of
Size when Size > ChunkThreshold0 ->
ChunkThreshold1 = ChunkThreshold0 div 2,
NumberOfChunksLikely = ((Size div ChunkThreshold1) + 1),
ChunkThreshold = Size div NumberOfChunksLikely,
chunkify(InList, ChunkThreshold, [], 0, []);
_Else ->
[InList]
end.
chunkify([], _ChunkThreshold, [], 0, OutputChunks) ->
lists:reverse(OutputChunks);
chunkify([], _ChunkThreshold, OutList, _OutListSize, OutputChunks) ->
lists:reverse([lists:reverse(OutList) | OutputChunks]);
chunkify([InElement | RestInList], ChunkThreshold, OutList, OutListSize, OutputChunks) ->
case ?term_size(InElement) of
Size when (Size + OutListSize) > ChunkThreshold andalso OutList /= [] ->
chunkify(RestInList, ChunkThreshold, [], 0, [lists:reverse([InElement | OutList]) | OutputChunks]);
Size ->
chunkify(RestInList, ChunkThreshold, [InElement | OutList], OutListSize + Size, OutputChunks)
end.
modify_node(Bt, RootPointerInfo, Actions, QueryOutput) ->
{NodeType, NodeList} = case RootPointerInfo of
nil ->
{kv_node, []};
_Tuple ->
Pointer = element(1, RootPointerInfo),
get_node(Bt, Pointer)
end,
NodeTuple = list_to_tuple(NodeList),
{ok, NewNodeList, QueryOutput2} = case NodeType of
kp_node -> modify_kpnode(Bt, NodeTuple, 1, Actions, [], QueryOutput);
kv_node -> modify_kvnode(Bt, NodeTuple, 1, Actions, [], QueryOutput)
end,
case NewNodeList of
[] -> % no nodes remain
{ok, [], QueryOutput2};
NodeList -> % nothing changed
{LastKey, _LastValue} = element(tuple_size(NodeTuple), NodeTuple),
{ok, [{LastKey, RootPointerInfo}], QueryOutput2};
_Else2 ->
{ok, ResultList} = write_node(Bt, NodeType, NewNodeList),
{ok, ResultList, QueryOutput2}
end.
reduce_node(#btree{reduce=nil}, _NodeType, _NodeList) ->
[];
reduce_node(#btree{reduce=R}, kp_node, NodeList) ->
R(rereduce, [element(2, Node) || {_K, Node} <- NodeList]);
reduce_node(#btree{reduce=R, assemble_kv=identity}, kv_node, NodeList) ->
R(reduce, NodeList);
reduce_node(#btree{reduce=R}=Bt, kv_node, NodeList) ->
R(reduce, [assemble(Bt, KV) || KV <- NodeList]).
reduce_tree_size(kv_node, NodeSize, _KvList) ->
NodeSize;
reduce_tree_size(kp_node, NodeSize, []) ->
NodeSize;
reduce_tree_size(kp_node, _NodeSize, [{_K, {_P, _Red, nil}} | _]) ->
nil;
reduce_tree_size(kp_node, NodeSize, [{_K, {_P, _Red, Sz}} | NodeList]) ->
reduce_tree_size(kp_node, NodeSize + Sz, NodeList).
get_node(#btree{ref = Ref, mod = Mod}, NodePos) ->
{ok, {NodeType, NodeList}} = Mod:pread_term(Ref, NodePos),
{NodeType, NodeList}.
write_node(#btree{ref = Ref, mod=Mod, compression = Comp} = Bt, NodeType, NodeList) ->
% split up nodes into smaller sizes
NodeListList = chunkify(Bt, NodeType, NodeList),
now write out each chunk and return the KeyPointer pairs for those nodes
ResultList = [
begin
{ok, Pointer, Size} = Mod:append_term(
Ref, {NodeType, ANodeList}, [{compression, Comp}]),
{LastKey, _} = lists:last(ANodeList),
SubTreeSize = reduce_tree_size(NodeType, Size, ANodeList),
{LastKey, {Pointer, reduce_node(Bt, NodeType, ANodeList), SubTreeSize}}
end
||
ANodeList <- NodeListList
],
{ok, ResultList}.
modify_kpnode(Bt, {}, _LowerBound, Actions, [], QueryOutput) ->
modify_node(Bt, nil, Actions, QueryOutput);
modify_kpnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput) ->
{ok, lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound,
tuple_size(NodeTuple), [])), QueryOutput};
modify_kpnode(Bt, NodeTuple, LowerBound,
[{_, FirstActionKey, _}|_]=Actions, ResultNode, QueryOutput) ->
Sz = tuple_size(NodeTuple),
N = find_first_gteq(Bt, NodeTuple, LowerBound, Sz, FirstActionKey),
case N =:= Sz of
true ->
% perform remaining actions on last node
{_, PointerInfo} = element(Sz, NodeTuple),
{ok, ChildKPs, QueryOutput2} =
modify_node(Bt, PointerInfo, Actions, QueryOutput),
NodeList = lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound,
Sz - 1, ChildKPs)),
{ok, NodeList, QueryOutput2};
false ->
{NodeKey, PointerInfo} = element(N, NodeTuple),
SplitFun = fun({_ActionType, ActionKey, _ActionValue}) ->
not less(Bt, NodeKey, ActionKey)
end,
{LessEqQueries, GreaterQueries} = lists:splitwith(SplitFun, Actions),
{ok, ChildKPs, QueryOutput2} =
modify_node(Bt, PointerInfo, LessEqQueries, QueryOutput),
ResultNode2 = lists:reverse(ChildKPs, bounded_tuple_to_revlist(NodeTuple,
LowerBound, N - 1, ResultNode)),
modify_kpnode(Bt, NodeTuple, N+1, GreaterQueries, ResultNode2, QueryOutput2)
end.
bounded_tuple_to_revlist(_Tuple, Start, End, Tail) when Start > End ->
Tail;
bounded_tuple_to_revlist(Tuple, Start, End, Tail) ->
bounded_tuple_to_revlist(Tuple, Start+1, End, [element(Start, Tuple)|Tail]).
bounded_tuple_to_list(Tuple, Start, End, Tail) ->
bounded_tuple_to_list2(Tuple, Start, End, [], Tail).
bounded_tuple_to_list2(_Tuple, Start, End, Acc, Tail) when Start > End ->
lists:reverse(Acc, Tail);
bounded_tuple_to_list2(Tuple, Start, End, Acc, Tail) ->
bounded_tuple_to_list2(Tuple, Start + 1, End, [element(Start, Tuple) | Acc], Tail).
find_first_gteq(_Bt, _Tuple, Start, End, _Key) when Start == End ->
End;
find_first_gteq(Bt, Tuple, Start, End, Key) ->
Mid = Start + ((End - Start) div 2),
{TupleKey, _} = element(Mid, Tuple),
case less(Bt, TupleKey, Key) of
true ->
find_first_gteq(Bt, Tuple, Mid+1, End, Key);
false ->
find_first_gteq(Bt, Tuple, Start, Mid, Key)
end.
modify_kvnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput) ->
{ok, lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound, tuple_size(NodeTuple), [])), QueryOutput};
modify_kvnode(Bt, NodeTuple, LowerBound, [{ActionType, ActionKey, ActionValue} | RestActions], ResultNode, QueryOutput) when LowerBound > tuple_size(NodeTuple) ->
case ActionType of
insert ->
modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, [{ActionKey, ActionValue} | ResultNode], QueryOutput);
remove ->
% just drop the action
modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, QueryOutput);
fetch ->
% the key/value must not exist in the tree
modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, [{not_found, {ActionKey, nil}} | QueryOutput])
end;
modify_kvnode(Bt, NodeTuple, LowerBound, [{ActionType, ActionKey, ActionValue} | RestActions], AccNode, QueryOutput) ->
N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), ActionKey),
KV={Key, _Value} = element(N, NodeTuple),
ResultNode = bounded_tuple_to_revlist(NodeTuple, LowerBound, N - 1, AccNode),
case less(Bt, ActionKey, Key) of
true ->
case ActionType of
insert ->
ActionKey is less than the Key , so insert
modify_kvnode(Bt, NodeTuple, N, RestActions,
[{ActionKey, ActionValue} | ResultNode],
QueryOutput);
remove ->
ActionKey is less than the Key , just drop the action
modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode,
QueryOutput);
fetch ->
ActionKey is less than the Key , the key / value must not exist in the tree
modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode,
[{not_found, {ActionKey, nil}} | QueryOutput])
end;
false ->
ActionKey and Key are maybe equal .
case less(Bt, Key, ActionKey) of
false ->
case ActionType of
insert ->
modify_kvnode(Bt, NodeTuple, N+1, RestActions,
[{ActionKey, ActionValue} | ResultNode],
QueryOutput);
remove ->
modify_kvnode(Bt, NodeTuple, N+1, RestActions, ResultNode,
QueryOutput);
fetch ->
ActionKey is equal to the Key , insert into the QueryOuput , but re - process the node
% since an identical action key can follow it.
modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode,
[{ok, assemble(Bt, KV)} | QueryOutput])
end;
true ->
modify_kvnode(Bt, NodeTuple, N + 1,
[{ActionType, ActionKey, ActionValue} | RestActions],
[KV | ResultNode], QueryOutput)
end
end.
reduce_stream_node(_Bt, _Dir, nil, _KeyStart, _InEndRangeFun, GroupedKey, GroupedKVsAcc,
GroupedRedsAcc, _KeyGroupFun, _Fun, Acc) ->
{ok, Acc, GroupedRedsAcc, GroupedKVsAcc, GroupedKey};
reduce_stream_node(Bt, Dir, Node, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc,
GroupedRedsAcc, KeyGroupFun, Fun, Acc) ->
P = element(1, Node),
case get_node(Bt, P) of
{kp_node, NodeList} ->
NodeList2 = adjust_dir(Dir, NodeList),
reduce_stream_kp_node(Bt, Dir, NodeList2, KeyStart, InEndRangeFun, GroupedKey,
GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc);
{kv_node, KVs} ->
KVs2 = adjust_dir(Dir, KVs),
reduce_stream_kv_node(Bt, Dir, KVs2, KeyStart, InEndRangeFun, GroupedKey,
GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc)
end.
reduce_stream_kv_node(Bt, Dir, KVs, KeyStart, InEndRangeFun,
GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
KeyGroupFun, Fun, Acc) ->
GTEKeyStartKVs =
case KeyStart of
undefined ->
KVs;
_ ->
DropFun = case Dir of
fwd ->
fun({Key, _}) -> less(Bt, Key, KeyStart) end;
rev ->
fun({Key, _}) -> less(Bt, KeyStart, Key) end
end,
lists:dropwhile(DropFun, KVs)
end,
KVs2 = lists:takewhile(
fun({Key, _}) -> InEndRangeFun(Key) end, GTEKeyStartKVs),
reduce_stream_kv_node2(Bt, KVs2, GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
KeyGroupFun, Fun, Acc).
reduce_stream_kv_node2(_Bt, [], GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
_KeyGroupFun, _Fun, Acc) ->
{ok, Acc, GroupedRedsAcc, GroupedKVsAcc, GroupedKey};
reduce_stream_kv_node2(Bt, [{Key, _Value}=KV| RestKVs], GroupedKey, GroupedKVsAcc,
GroupedRedsAcc, KeyGroupFun, Fun, Acc) ->
case GroupedKey of
undefined ->
reduce_stream_kv_node2(Bt, RestKVs, Key,
[assemble(Bt,KV)], [], KeyGroupFun, Fun, Acc);
_ ->
case KeyGroupFun(GroupedKey, Key) of
true ->
reduce_stream_kv_node2(Bt, RestKVs, GroupedKey,
[assemble(Bt,KV)|GroupedKVsAcc], GroupedRedsAcc, KeyGroupFun,
Fun, Acc);
false ->
case Fun(GroupedKey, {GroupedKVsAcc, GroupedRedsAcc}, Acc) of
{ok, Acc2} ->
reduce_stream_kv_node2(Bt, RestKVs, Key, [assemble(Bt,KV)],
[], KeyGroupFun, Fun, Acc2);
{stop, Acc2} ->
throw({stop, Acc2})
end
end
end.
reduce_stream_kp_node(Bt, Dir, NodeList, KeyStart, InEndRangeFun,
GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
KeyGroupFun, Fun, Acc) ->
Nodes =
case KeyStart of
undefined ->
NodeList;
_ ->
case Dir of
fwd ->
lists:dropwhile(fun({Key, _}) -> less(Bt, Key, KeyStart) end, NodeList);
rev ->
RevKPs = lists:reverse(NodeList),
case lists:splitwith(fun({Key, _}) -> less(Bt, Key, KeyStart) end, RevKPs) of
{_Before, []} ->
NodeList;
{Before, [FirstAfter | _]} ->
[FirstAfter | lists:reverse(Before)]
end
end
end,
{InRange, MaybeInRange} = lists:splitwith(
fun({Key, _}) -> InEndRangeFun(Key) end, Nodes),
NodesInRange = case MaybeInRange of
[FirstMaybeInRange | _] when Dir =:= fwd ->
InRange ++ [FirstMaybeInRange];
_ ->
InRange
end,
reduce_stream_kp_node2(Bt, Dir, NodesInRange, KeyStart, InEndRangeFun,
GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc).
reduce_stream_kp_node2(Bt, Dir, [{_Key, NodeInfo} | RestNodeList], KeyStart, InEndRangeFun,
undefined, [], [], KeyGroupFun, Fun, Acc) ->
{ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} =
reduce_stream_node(Bt, Dir, NodeInfo, KeyStart, InEndRangeFun, undefined,
[], [], KeyGroupFun, Fun, Acc),
reduce_stream_kp_node2(Bt, Dir, RestNodeList, KeyStart, InEndRangeFun, GroupedKey2,
GroupedKVsAcc2, GroupedRedsAcc2, KeyGroupFun, Fun, Acc2);
reduce_stream_kp_node2(Bt, Dir, NodeList, KeyStart, InEndRangeFun,
GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc) ->
{Grouped0, Ungrouped0} = lists:splitwith(fun({Key,_}) ->
KeyGroupFun(GroupedKey, Key) end, NodeList),
{GroupedNodes, UngroupedNodes} =
case Grouped0 of
[] ->
{Grouped0, Ungrouped0};
_ ->
[FirstGrouped | RestGrouped] = lists:reverse(Grouped0),
{RestGrouped, [FirstGrouped | Ungrouped0]}
end,
GroupedReds = [element(2, Node) || {_, Node} <- GroupedNodes],
case UngroupedNodes of
[{_Key, NodeInfo}|RestNodes] ->
{ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} =
reduce_stream_node(Bt, Dir, NodeInfo, KeyStart, InEndRangeFun, GroupedKey,
GroupedKVsAcc, GroupedReds ++ GroupedRedsAcc, KeyGroupFun, Fun, Acc),
reduce_stream_kp_node2(Bt, Dir, RestNodes, KeyStart, InEndRangeFun, GroupedKey2,
GroupedKVsAcc2, GroupedRedsAcc2, KeyGroupFun, Fun, Acc2);
[] ->
{ok, Acc, GroupedReds ++ GroupedRedsAcc, GroupedKVsAcc, GroupedKey}
end.
adjust_dir(fwd, List) ->
List;
adjust_dir(rev, List) ->
lists:reverse(List).
stream_node(Bt, Reds, Node, StartKey, InRange, Dir, Fun, Acc) ->
Pointer = element(1, Node),
{NodeType, NodeList} = get_node(Bt, Pointer),
case NodeType of
kp_node ->
stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc);
kv_node ->
stream_kv_node(Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc)
end.
stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc) ->
Pointer = element(1, Node),
{NodeType, NodeList} = get_node(Bt, Pointer),
case NodeType of
kp_node ->
stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc);
kv_node ->
stream_kv_node2(Bt, Reds, [], adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc)
end.
stream_kp_node(_Bt, _Reds, [], _InRange, _Dir, _Fun, Acc) ->
{ok, Acc};
stream_kp_node(Bt, Reds, [{Key, Node} | Rest], InRange, Dir, Fun, Acc) ->
Red = element(2, Node),
case Fun(traverse, Key, Red, Acc) of
{ok, Acc2} ->
case stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc2) of
{ok, Acc3} ->
stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc3);
{stop, LastReds, Acc3} ->
{stop, LastReds, Acc3}
end;
{skip, Acc2} ->
stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc2)
end.
drop_nodes(_Bt, Reds, _StartKey, []) ->
{Reds, []};
drop_nodes(Bt, Reds, StartKey, [{NodeKey, Node} | RestKPs]) ->
case less(Bt, NodeKey, StartKey) of
true ->
drop_nodes(Bt, [element(2, Node) | Reds], StartKey, RestKPs);
false ->
{Reds, [{NodeKey, Node} | RestKPs]}
end.
stream_kp_node(Bt, Reds, KPs, StartKey, InRange, Dir, Fun, Acc) ->
{NewReds, NodesToStream} =
case Dir of
fwd ->
% drop all nodes sorting before the key
drop_nodes(Bt, Reds, StartKey, KPs);
rev ->
keep all nodes sorting before the key , AND the first node to sort after
RevKPs = lists:reverse(KPs),
case lists:splitwith(fun({Key, _Pointer}) -> less(Bt, Key, StartKey) end, RevKPs) of
{_RevsBefore, []} ->
% everything sorts before it
{Reds, KPs};
{RevBefore, [FirstAfter | Drop]} ->
{[element(2, Node) || {_K, Node} <- Drop] ++ Reds,
[FirstAfter | lists:reverse(RevBefore)]}
end
end,
case NodesToStream of
[] ->
{ok, Acc};
[{_Key, Node} | Rest] ->
case stream_node(Bt, NewReds, Node, StartKey, InRange, Dir, Fun, Acc) of
{ok, Acc2} ->
Red = element(2, Node),
stream_kp_node(Bt, [Red | NewReds], Rest, InRange, Dir, Fun, Acc2);
{stop, LastReds, Acc2} ->
{stop, LastReds, Acc2}
end
end.
stream_kv_node(Bt, Reds, KVs, StartKey, InRange, Dir, Fun, Acc) ->
DropFun =
case Dir of
fwd ->
fun({Key, _}) -> less(Bt, Key, StartKey) end;
rev ->
fun({Key, _}) -> less(Bt, StartKey, Key) end
end,
{LTKVs, GTEKVs} = lists:splitwith(DropFun, KVs),
AssembleLTKVs = case Bt#btree.assemble_kv of
identity -> LTKVs;
_ -> [assemble(Bt,KV) || KV <- LTKVs]
end,
stream_kv_node2(Bt, Reds, AssembleLTKVs, GTEKVs, InRange, Dir, Fun, Acc).
stream_kv_node2(_Bt, _Reds, _PrevKVs, [], _InRange, _Dir, _Fun, Acc) ->
{ok, Acc};
stream_kv_node2(Bt, Reds, PrevKVs, [{K,_V}=KV | RestKVs], InRange, Dir,
Fun, Acc) ->
case InRange(K) of
false ->
{stop, {PrevKVs, Reds}, Acc};
true ->
AssembledKV = assemble(Bt, KV),
case Fun(visit, AssembledKV, {PrevKVs, Reds}, Acc) of
{ok, Acc2} ->
stream_kv_node2(Bt, Reds, [AssembledKV | PrevKVs], RestKVs,
InRange, Dir, Fun, Acc2);
{stop, Acc2} ->
{stop, {PrevKVs, Reds}, Acc2}
end
end.
| null | https://raw.githubusercontent.com/benoitc/cbt/49b99e56f406f918739adde152e8a4908e755521/src/cbt_btree.erl | erlang | use this file except in compliance with the License. You may obtain a copy of
the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
@doc open a btree using the default backend cbt_file.
@doc open a btree . Default backend is cbt_file.
Options:
<ul>
is cbt_file.</li>
<li> {split, fun(Btree, Value)} : Take a value and extract content if
needed from it. It returns a {key, Value} tuple. You don't need to
set such function if you already give a {Key, Value} tuple to your
add/add_remove functions.</li>
<li>{join, fun(Key, Value)} : The fonction takes the key and value and
return a new Value ussed when you lookup. By default it return a
{Key, Value} .</li>
<li>{reduce_fun, ReduceFun} : pass the reduce fun</li>
compress the data</li>
</ul>
@doc return the latest btree root that will be stored in the database
header or value
@doc return the size in bytes of a btree
--------------------------------
--------------------------------
write.
@doc insert and remove a list of key/values and retrieve a list of
A and B are equal, sort by op.
--------------------------------
Btree query methods
--------------------------------
Results are returned in the same order as the keys. If the key is
not_found the `not_found' result is appended to the list.
We want to return the results in the same order as the keys were input
but we may have changed the order when we sorted. So we need to put the
order back into the results.
@doc apply the reduce function on last reductions.
@doc fold reduce values.
------------------------------------
PRIVATE API
------------------------------------
for ordering different operations with the same key.
fetch < remove < insert
keys not found
no nodes remain
nothing changed
split up nodes into smaller sizes
perform remaining actions on last node
just drop the action
the key/value must not exist in the tree
since an identical action key can follow it.
drop all nodes sorting before the key
everything sorts before it | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(cbt_btree).
-export([open/2, open/3]).
-export([query_modify/4, add/2, add_remove/3]).
-export([lookup/2]).
-export([fold/3, fold/4]).
-export([fold_reduce/4, full_reduce/1, final_reduce/2]).
-export([size/1]).
-export([get_state/1]).
-export([set_options/2]).
-export([less/3]).
-include("cbt.hrl").
-define(BTREE_KV_CHUNK_THRESHOLD, 7168).
-define(BTREE_KP_CHUNK_THRESHOLD, 6144).
-type cbtree() :: #btree{}.
-type cbtree_root() :: {integer(), list(), integer()}.
-type cbtree_options() :: [{backend, cbt_file | atom()}
| {split, fun()} | {join, fun()} | {less, fun()}
| {reduce, fun()}
| {compression, cbt_compress:compression_method()}
| {kv_chunk_threshold, integer()}
| {kp_chunk_threshold, integer()}].
-type cbt_kv() :: {Key::any(), Val::any()}.
-type cbt_kvs() :: [cbt_kv()].
-type cbt_keys() :: [term()].
-type cbt_fold_options() :: [{dir, fwd | rev} | {start_key, term()} |
{end_key, term()} | {end_key_gt, term()} |
{key_group_fun, fun()}].
-export_type([cbtree/0]).
-export_type([cbtree_root/0]).
-export_type([cbtree_options/0]).
-export_type([cbt_kv/0, cbt_kvs/0]).
-export_type([cbt_keys/0]).
-export_type([cbt_fold_options/0]).
pass in ' nil ' for State if a new Btree .
-spec open(State::nil | cbtree(), Ref::cbt_backend:ref()) -> {ok, cbtree()}.
open(State, Ref) ->
{ok, #btree{root=State, ref=Ref, mod=cbt_file}}.
pass in ' nil ' for State if a new Btree .
< li > { backend , Module } : backend to use to read / append items . Default
< li > { compression , nonde | snappy } : the compression methods used to
< li>{less , LessFun(KeyA , KeyB ) } : function used to order the btree that
compare two keys</li >
-spec open(State::nil | cbtree(), Ref::cbt_backend:ref(),
Options::cbtree_options()) -> {ok, cbtree()}.
open(State, Ref, Options) ->
{ok, set_options(#btree{root=State, ref=Ref, mod=cbt_file}, Options)}.
-spec get_state(Btree::cbtree()) -> State::tuple().
get_state(#btree{root=Root}) ->
Root.
@doc set btreee options
-spec set_options(Btree::cbtree(), Options::cbtree_options()) -> Btree2::cbtree().
set_options(Bt, []) ->
Bt;
set_options(Bt, [{backend, Mod}|Rest]) ->
set_options(Bt#btree{mod=Mod}, Rest);
set_options(Bt, [{split, Extract}|Rest]) ->
set_options(Bt#btree{extract_kv=Extract}, Rest);
set_options(Bt, [{join, Assemble}|Rest]) ->
set_options(Bt#btree{assemble_kv=Assemble}, Rest);
set_options(Bt, [{less, Less}|Rest]) ->
set_options(Bt#btree{less=Less}, Rest);
set_options(Bt, [{reduce, Reduce}|Rest]) ->
set_options(Bt#btree{reduce=Reduce}, Rest);
set_options(Bt, [{compression, Comp}|Rest]) ->
set_options(Bt#btree{compression=Comp}, Rest);
set_options(Bt, [{kv_chunk_threshold, Threshold}|Rest]) ->
set_options(Bt#btree{kv_chunk_threshold = Threshold}, Rest);
set_options(Bt, [{kp_chunk_threshold, Threshold}|Rest]) ->
set_options(Bt#btree{kp_chunk_threshold = Threshold}, Rest).
-spec size(Btree::cbtree()) -> Size::integer().
size(#btree{root = nil}) ->
0;
size(#btree{root = {_P, _Red, Size}}) ->
Size.
Btree updates methods
@doc insert a list of key / values in the
-spec add(Btree::cbtree(), InsertKeyValues::cbt_kvs()) ->
{ok, Btree2::cbtree()}.
add(Bt, InsertKeyValues) ->
add_remove(Bt, InsertKeyValues, []).
@doc insert and remove a list of key / values in the btree in one
-spec add_remove(Btree::cbtree(), InsertKeyValues::cbt_kvs(),
RemoveKeys::cbt_keys()) -> {ok, Btree2::cbtree()}.
add_remove(Bt, InsertKeyValues, RemoveKeys) ->
{ok, [], Bt2} = query_modify(Bt, [], InsertKeyValues, RemoveKeys),
{ok, Bt2}.
key / values from their key in the btree in one call .
-spec query_modify(Btree::cbtree(), LookupKeys::cbt_keys(),
InsertKeyValues::cbt_kvs(), RemoveKeys::cbt_keys()) ->
{ok, FoundKeyValues::cbt_kvs(), Btree2::cbtree()}.
query_modify(Bt, LookupKeys, InsertValues, RemoveKeys) ->
#btree{root=Root} = Bt,
InsertActions = lists:map(
fun(KeyValue) ->
{Key, Value} = extract(Bt, KeyValue),
{insert, Key, Value}
end, InsertValues),
RemoveActions = [{remove, Key, nil} || Key <- RemoveKeys],
FetchActions = [{fetch, Key, nil} || Key <- LookupKeys],
SortFun =
fun({OpA, A, _}, {OpB, B, _}) ->
case A == B of
true -> op_order(OpA) < op_order(OpB);
false ->
less(Bt, A, B)
end
end,
Actions = lists:sort(SortFun, lists:append([InsertActions, RemoveActions,
FetchActions])),
{ok, KeyPointers, QueryResults} = modify_node(Bt, Root, Actions, []),
{ok, NewRoot} = complete_root(Bt, KeyPointers),
{ok, QueryResults, Bt#btree{root=NewRoot}}.
@doc lookup for a list of keys in the btree
-spec lookup(Btree::cbtree(), Keys::cbt_keys()) -> [{ok, cbt_kv()} | not_found].
lookup(#btree{root=Root, less=Less}=Bt, Keys) ->
SortedKeys = case Less of
undefined -> lists:sort(Keys);
_ -> lists:sort(Less, Keys)
end,
{ok, SortedResults} = lookup(Bt, Root, SortedKeys),
cbt_util:reorder_results(Keys, SortedResults).
lookup(_Bt, nil, Keys) ->
{ok, [{Key, not_found} || Key <- Keys]};
lookup(Bt, Node, Keys) ->
Pointer = element(1, Node),
{NodeType, NodeList} = get_node(Bt, Pointer),
case NodeType of
kp_node ->
lookup_kpnode(Bt, list_to_tuple(NodeList), 1, Keys, []);
kv_node ->
lookup_kvnode(Bt, list_to_tuple(NodeList), 1, Keys, [])
end.
@doc fold key / values in the
-spec fold(Btree::cbtree(), Fun::fun(), Acc::term()) ->
{ok, {KVs::cbt_kvs(), Reductions::[term()]}, Acc2::term()}.
fold(Bt, Fun, Acc) ->
fold(Bt, Fun, Acc, []).
-spec fold(Btree::cbtree(), Fun::fun(), Acc::term(),
Options::cbt_fold_options()) ->
{ok, {KVs::cbt_kvs(), Reductions::[term()]}, Acc2::term()}.
fold(#btree{root=nil}, _Fun, Acc, _Options) ->
{ok, {[], []}, Acc};
fold(#btree{root=Root}=Bt, Fun, Acc, Options) ->
Dir = cbt_util:get_value(dir, Options, fwd),
InRange = make_key_in_end_range_function(Bt, Dir, Options),
Result =
case cbt_util:get_value(start_key, Options) of
undefined ->
stream_node(Bt, [], Bt#btree.root, InRange, Dir,
convert_fun_arity(Fun), Acc);
StartKey ->
stream_node(Bt, [], Bt#btree.root, StartKey, InRange, Dir,
convert_fun_arity(Fun), Acc)
end,
case Result of
{ok, Acc2}->
FullReduction = element(2, Root),
{ok, {[], [FullReduction]}, Acc2};
{stop, LastReduction, Acc2} ->
{ok, LastReduction, Acc2}
end.
-spec final_reduce(Btree::cbtree(), LastReduction::{any(), any()}) -> term().
final_reduce(#btree{reduce=Reduce}, Val) ->
do_final_reduce(Reduce, Val).
do_final_reduce(Reduce, {[], []}) ->
Reduce(reduce, []);
do_final_reduce(_Bt, {[], [Red]}) ->
Red;
do_final_reduce(Reduce, {[], Reductions}) ->
Reduce(rereduce, Reductions);
do_final_reduce(Reduce, {KVs, Reductions}) ->
Red = Reduce(reduce, KVs),
do_final_reduce(Reduce, {[], [Red | Reductions]}).
-spec fold_reduce(Btree::cbtree(), FoldFun::fun(), Acc::any(),
Options::cbt_fold_options()) -> {ok, Acc2::term()}.
fold_reduce(#btree{root=Root}=Bt, Fun, Acc, Options) ->
Dir = cbt_util:get_value(dir, Options, fwd),
StartKey = cbt_util:get_value(start_key, Options),
InEndRangeFun = make_key_in_end_range_function(Bt, Dir, Options),
KeyGroupFun = cbt_util:get_value(key_group_fun, Options, fun(_,_) -> true end),
try
{ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} =
reduce_stream_node(Bt, Dir, Root, StartKey, InEndRangeFun, undefined, [], [],
KeyGroupFun, Fun, Acc),
if GroupedKey2 == undefined ->
{ok, Acc2};
true ->
case Fun(GroupedKey2, {GroupedKVsAcc2, GroupedRedsAcc2}, Acc2) of
{ok, Acc3} -> {ok, Acc3};
{stop, Acc3} -> {ok, Acc3}
end
end
catch
throw:{stop, AccDone} -> {ok, AccDone}
end.
@doc return the full reduceed value from the btree .
-spec full_reduce(Btree::cbtree()) -> {ok, term()}.
full_reduce(#btree{root=nil,reduce=Reduce}) ->
{ok, Reduce(reduce, [])};
full_reduce(#btree{root=Root}) ->
{ok, element(2, Root)}.
extract(#btree{extract_kv=identity}, Value) ->
Value;
extract(#btree{extract_kv=Extract}, Value) ->
Extract(Value).
assemble(#btree{assemble_kv=identity}, KeyValue) ->
KeyValue;
assemble(#btree{assemble_kv=Assemble}, KeyValue) ->
Assemble(KeyValue).
less(#btree{less=undefined}, A, B) ->
A < B;
less(#btree{less=Less}, A, B) ->
Less(A, B).
wraps a 2 arity function with the proper 3 arity function
convert_fun_arity(Fun) when is_function(Fun, 2) ->
fun
(visit, KV, _Reds, AccIn) -> Fun(KV, AccIn);
(traverse, _K, _Red, AccIn) -> {ok, AccIn}
end;
convert_fun_arity(Fun) when is_function(Fun, 3) ->
fun
(visit, KV, Reds, AccIn) -> Fun(KV, Reds, AccIn);
(traverse, _K, _Red, AccIn) -> {ok, AccIn}
end;
convert_fun_arity(Fun) when is_function(Fun, 4) ->
Already arity 4
make_key_in_end_range_function(Bt, fwd, Options) ->
case cbt_util:get_value(end_key_gt, Options) of
undefined ->
case cbt_util:get_value(end_key, Options) of
undefined ->
fun(_Key) -> true end;
LastKey ->
fun(Key) -> not less(Bt, LastKey, Key) end
end;
EndKey ->
fun(Key) -> less(Bt, Key, EndKey) end
end;
make_key_in_end_range_function(Bt, rev, Options) ->
case cbt_util:get_value(end_key_gt, Options) of
undefined ->
case cbt_util:get_value(end_key, Options) of
undefined ->
fun(_Key) -> true end;
LastKey ->
fun(Key) -> not less(Bt, Key, LastKey) end
end;
EndKey ->
fun(Key) -> less(Bt, EndKey, Key) end
end.
op_order(fetch) -> 1;
op_order(remove) -> 2;
op_order(insert) -> 3.
lookup_kpnode(_Bt, _NodeTuple, _LowerBound, [], Output) ->
{ok, lists:reverse(Output)};
lookup_kpnode(_Bt, NodeTuple, LowerBound, Keys, Output) when tuple_size(NodeTuple) < LowerBound ->
{ok, lists:reverse(Output, [{Key, not_found} || Key <- Keys])};
lookup_kpnode(Bt, NodeTuple, LowerBound, [FirstLookupKey | _] = LookupKeys, Output) ->
N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), FirstLookupKey),
{Key, PointerInfo} = element(N, NodeTuple),
SplitFun = fun(LookupKey) -> not less(Bt, Key, LookupKey) end,
case lists:splitwith(SplitFun, LookupKeys) of
{[], GreaterQueries} ->
lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, Output);
{LessEqQueries, GreaterQueries} ->
{ok, Results} = lookup(Bt, PointerInfo, LessEqQueries),
lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, lists:reverse(Results, Output))
end.
lookup_kvnode(_Bt, _NodeTuple, _LowerBound, [], Output) ->
{ok, lists:reverse(Output)};
lookup_kvnode(_Bt, NodeTuple, LowerBound, Keys, Output) when tuple_size(NodeTuple) < LowerBound ->
{ok, lists:reverse(Output, [{Key, not_found} || Key <- Keys])};
lookup_kvnode(Bt, NodeTuple, LowerBound, [LookupKey | RestLookupKeys], Output) ->
N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), LookupKey),
KV = {Key, _Value} = element(N, NodeTuple),
case less(Bt, LookupKey, Key) of
true ->
LookupKey is less than Key
lookup_kvnode(Bt, NodeTuple, N, RestLookupKeys, [{LookupKey, not_found} | Output]);
false ->
case less(Bt, Key, LookupKey) of
true ->
LookupKey is greater than Key
lookup_kvnode(Bt, NodeTuple, N+1, RestLookupKeys,
[{LookupKey, not_found} | Output]);
false ->
LookupKey is equal to Key
lookup_kvnode(Bt, NodeTuple, N, RestLookupKeys,
[{LookupKey, {ok, assemble(Bt, KV)}} | Output])
end
end.
complete_root(_Bt, []) ->
{ok, nil};
complete_root(_Bt, [{_Key, PointerInfo}])->
{ok, PointerInfo};
complete_root(Bt, KPs) ->
{ok, ResultKeyPointers} = write_node(Bt, kp_node, KPs),
complete_root(Bt, ResultKeyPointers).
chunkify(#btree{kp_chunk_threshold = T}, kp_node, InList) ->
chunkify(T, InList);
chunkify(#btree{kv_chunk_threshold = T}, kv_node, InList) ->
chunkify(T, InList).
chunkify(ChunkThreshold0, InList) ->
case ?term_size(InList) of
Size when Size > ChunkThreshold0 ->
ChunkThreshold1 = ChunkThreshold0 div 2,
NumberOfChunksLikely = ((Size div ChunkThreshold1) + 1),
ChunkThreshold = Size div NumberOfChunksLikely,
chunkify(InList, ChunkThreshold, [], 0, []);
_Else ->
[InList]
end.
chunkify([], _ChunkThreshold, [], 0, OutputChunks) ->
lists:reverse(OutputChunks);
chunkify([], _ChunkThreshold, OutList, _OutListSize, OutputChunks) ->
lists:reverse([lists:reverse(OutList) | OutputChunks]);
chunkify([InElement | RestInList], ChunkThreshold, OutList, OutListSize, OutputChunks) ->
case ?term_size(InElement) of
Size when (Size + OutListSize) > ChunkThreshold andalso OutList /= [] ->
chunkify(RestInList, ChunkThreshold, [], 0, [lists:reverse([InElement | OutList]) | OutputChunks]);
Size ->
chunkify(RestInList, ChunkThreshold, [InElement | OutList], OutListSize + Size, OutputChunks)
end.
modify_node(Bt, RootPointerInfo, Actions, QueryOutput) ->
{NodeType, NodeList} = case RootPointerInfo of
nil ->
{kv_node, []};
_Tuple ->
Pointer = element(1, RootPointerInfo),
get_node(Bt, Pointer)
end,
NodeTuple = list_to_tuple(NodeList),
{ok, NewNodeList, QueryOutput2} = case NodeType of
kp_node -> modify_kpnode(Bt, NodeTuple, 1, Actions, [], QueryOutput);
kv_node -> modify_kvnode(Bt, NodeTuple, 1, Actions, [], QueryOutput)
end,
case NewNodeList of
{ok, [], QueryOutput2};
{LastKey, _LastValue} = element(tuple_size(NodeTuple), NodeTuple),
{ok, [{LastKey, RootPointerInfo}], QueryOutput2};
_Else2 ->
{ok, ResultList} = write_node(Bt, NodeType, NewNodeList),
{ok, ResultList, QueryOutput2}
end.
reduce_node(#btree{reduce=nil}, _NodeType, _NodeList) ->
[];
reduce_node(#btree{reduce=R}, kp_node, NodeList) ->
R(rereduce, [element(2, Node) || {_K, Node} <- NodeList]);
reduce_node(#btree{reduce=R, assemble_kv=identity}, kv_node, NodeList) ->
R(reduce, NodeList);
reduce_node(#btree{reduce=R}=Bt, kv_node, NodeList) ->
R(reduce, [assemble(Bt, KV) || KV <- NodeList]).
reduce_tree_size(kv_node, NodeSize, _KvList) ->
NodeSize;
reduce_tree_size(kp_node, NodeSize, []) ->
NodeSize;
reduce_tree_size(kp_node, _NodeSize, [{_K, {_P, _Red, nil}} | _]) ->
nil;
reduce_tree_size(kp_node, NodeSize, [{_K, {_P, _Red, Sz}} | NodeList]) ->
reduce_tree_size(kp_node, NodeSize + Sz, NodeList).
get_node(#btree{ref = Ref, mod = Mod}, NodePos) ->
{ok, {NodeType, NodeList}} = Mod:pread_term(Ref, NodePos),
{NodeType, NodeList}.
write_node(#btree{ref = Ref, mod=Mod, compression = Comp} = Bt, NodeType, NodeList) ->
NodeListList = chunkify(Bt, NodeType, NodeList),
now write out each chunk and return the KeyPointer pairs for those nodes
ResultList = [
begin
{ok, Pointer, Size} = Mod:append_term(
Ref, {NodeType, ANodeList}, [{compression, Comp}]),
{LastKey, _} = lists:last(ANodeList),
SubTreeSize = reduce_tree_size(NodeType, Size, ANodeList),
{LastKey, {Pointer, reduce_node(Bt, NodeType, ANodeList), SubTreeSize}}
end
||
ANodeList <- NodeListList
],
{ok, ResultList}.
modify_kpnode(Bt, {}, _LowerBound, Actions, [], QueryOutput) ->
modify_node(Bt, nil, Actions, QueryOutput);
modify_kpnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput) ->
{ok, lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound,
tuple_size(NodeTuple), [])), QueryOutput};
modify_kpnode(Bt, NodeTuple, LowerBound,
[{_, FirstActionKey, _}|_]=Actions, ResultNode, QueryOutput) ->
Sz = tuple_size(NodeTuple),
N = find_first_gteq(Bt, NodeTuple, LowerBound, Sz, FirstActionKey),
case N =:= Sz of
true ->
{_, PointerInfo} = element(Sz, NodeTuple),
{ok, ChildKPs, QueryOutput2} =
modify_node(Bt, PointerInfo, Actions, QueryOutput),
NodeList = lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound,
Sz - 1, ChildKPs)),
{ok, NodeList, QueryOutput2};
false ->
{NodeKey, PointerInfo} = element(N, NodeTuple),
SplitFun = fun({_ActionType, ActionKey, _ActionValue}) ->
not less(Bt, NodeKey, ActionKey)
end,
{LessEqQueries, GreaterQueries} = lists:splitwith(SplitFun, Actions),
{ok, ChildKPs, QueryOutput2} =
modify_node(Bt, PointerInfo, LessEqQueries, QueryOutput),
ResultNode2 = lists:reverse(ChildKPs, bounded_tuple_to_revlist(NodeTuple,
LowerBound, N - 1, ResultNode)),
modify_kpnode(Bt, NodeTuple, N+1, GreaterQueries, ResultNode2, QueryOutput2)
end.
bounded_tuple_to_revlist(_Tuple, Start, End, Tail) when Start > End ->
Tail;
bounded_tuple_to_revlist(Tuple, Start, End, Tail) ->
bounded_tuple_to_revlist(Tuple, Start+1, End, [element(Start, Tuple)|Tail]).
bounded_tuple_to_list(Tuple, Start, End, Tail) ->
bounded_tuple_to_list2(Tuple, Start, End, [], Tail).
bounded_tuple_to_list2(_Tuple, Start, End, Acc, Tail) when Start > End ->
lists:reverse(Acc, Tail);
bounded_tuple_to_list2(Tuple, Start, End, Acc, Tail) ->
bounded_tuple_to_list2(Tuple, Start + 1, End, [element(Start, Tuple) | Acc], Tail).
find_first_gteq(_Bt, _Tuple, Start, End, _Key) when Start == End ->
End;
find_first_gteq(Bt, Tuple, Start, End, Key) ->
Mid = Start + ((End - Start) div 2),
{TupleKey, _} = element(Mid, Tuple),
case less(Bt, TupleKey, Key) of
true ->
find_first_gteq(Bt, Tuple, Mid+1, End, Key);
false ->
find_first_gteq(Bt, Tuple, Start, Mid, Key)
end.
modify_kvnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput) ->
{ok, lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound, tuple_size(NodeTuple), [])), QueryOutput};
modify_kvnode(Bt, NodeTuple, LowerBound, [{ActionType, ActionKey, ActionValue} | RestActions], ResultNode, QueryOutput) when LowerBound > tuple_size(NodeTuple) ->
case ActionType of
insert ->
modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, [{ActionKey, ActionValue} | ResultNode], QueryOutput);
remove ->
modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, QueryOutput);
fetch ->
modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, [{not_found, {ActionKey, nil}} | QueryOutput])
end;
modify_kvnode(Bt, NodeTuple, LowerBound, [{ActionType, ActionKey, ActionValue} | RestActions], AccNode, QueryOutput) ->
N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), ActionKey),
KV={Key, _Value} = element(N, NodeTuple),
ResultNode = bounded_tuple_to_revlist(NodeTuple, LowerBound, N - 1, AccNode),
case less(Bt, ActionKey, Key) of
true ->
case ActionType of
insert ->
ActionKey is less than the Key , so insert
modify_kvnode(Bt, NodeTuple, N, RestActions,
[{ActionKey, ActionValue} | ResultNode],
QueryOutput);
remove ->
ActionKey is less than the Key , just drop the action
modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode,
QueryOutput);
fetch ->
ActionKey is less than the Key , the key / value must not exist in the tree
modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode,
[{not_found, {ActionKey, nil}} | QueryOutput])
end;
false ->
ActionKey and Key are maybe equal .
case less(Bt, Key, ActionKey) of
false ->
case ActionType of
insert ->
modify_kvnode(Bt, NodeTuple, N+1, RestActions,
[{ActionKey, ActionValue} | ResultNode],
QueryOutput);
remove ->
modify_kvnode(Bt, NodeTuple, N+1, RestActions, ResultNode,
QueryOutput);
fetch ->
ActionKey is equal to the Key , insert into the QueryOuput , but re - process the node
modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode,
[{ok, assemble(Bt, KV)} | QueryOutput])
end;
true ->
modify_kvnode(Bt, NodeTuple, N + 1,
[{ActionType, ActionKey, ActionValue} | RestActions],
[KV | ResultNode], QueryOutput)
end
end.
reduce_stream_node(_Bt, _Dir, nil, _KeyStart, _InEndRangeFun, GroupedKey, GroupedKVsAcc,
GroupedRedsAcc, _KeyGroupFun, _Fun, Acc) ->
{ok, Acc, GroupedRedsAcc, GroupedKVsAcc, GroupedKey};
reduce_stream_node(Bt, Dir, Node, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc,
GroupedRedsAcc, KeyGroupFun, Fun, Acc) ->
P = element(1, Node),
case get_node(Bt, P) of
{kp_node, NodeList} ->
NodeList2 = adjust_dir(Dir, NodeList),
reduce_stream_kp_node(Bt, Dir, NodeList2, KeyStart, InEndRangeFun, GroupedKey,
GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc);
{kv_node, KVs} ->
KVs2 = adjust_dir(Dir, KVs),
reduce_stream_kv_node(Bt, Dir, KVs2, KeyStart, InEndRangeFun, GroupedKey,
GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc)
end.
reduce_stream_kv_node(Bt, Dir, KVs, KeyStart, InEndRangeFun,
GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
KeyGroupFun, Fun, Acc) ->
GTEKeyStartKVs =
case KeyStart of
undefined ->
KVs;
_ ->
DropFun = case Dir of
fwd ->
fun({Key, _}) -> less(Bt, Key, KeyStart) end;
rev ->
fun({Key, _}) -> less(Bt, KeyStart, Key) end
end,
lists:dropwhile(DropFun, KVs)
end,
KVs2 = lists:takewhile(
fun({Key, _}) -> InEndRangeFun(Key) end, GTEKeyStartKVs),
reduce_stream_kv_node2(Bt, KVs2, GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
KeyGroupFun, Fun, Acc).
reduce_stream_kv_node2(_Bt, [], GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
_KeyGroupFun, _Fun, Acc) ->
{ok, Acc, GroupedRedsAcc, GroupedKVsAcc, GroupedKey};
reduce_stream_kv_node2(Bt, [{Key, _Value}=KV| RestKVs], GroupedKey, GroupedKVsAcc,
GroupedRedsAcc, KeyGroupFun, Fun, Acc) ->
case GroupedKey of
undefined ->
reduce_stream_kv_node2(Bt, RestKVs, Key,
[assemble(Bt,KV)], [], KeyGroupFun, Fun, Acc);
_ ->
case KeyGroupFun(GroupedKey, Key) of
true ->
reduce_stream_kv_node2(Bt, RestKVs, GroupedKey,
[assemble(Bt,KV)|GroupedKVsAcc], GroupedRedsAcc, KeyGroupFun,
Fun, Acc);
false ->
case Fun(GroupedKey, {GroupedKVsAcc, GroupedRedsAcc}, Acc) of
{ok, Acc2} ->
reduce_stream_kv_node2(Bt, RestKVs, Key, [assemble(Bt,KV)],
[], KeyGroupFun, Fun, Acc2);
{stop, Acc2} ->
throw({stop, Acc2})
end
end
end.
reduce_stream_kp_node(Bt, Dir, NodeList, KeyStart, InEndRangeFun,
GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
KeyGroupFun, Fun, Acc) ->
Nodes =
case KeyStart of
undefined ->
NodeList;
_ ->
case Dir of
fwd ->
lists:dropwhile(fun({Key, _}) -> less(Bt, Key, KeyStart) end, NodeList);
rev ->
RevKPs = lists:reverse(NodeList),
case lists:splitwith(fun({Key, _}) -> less(Bt, Key, KeyStart) end, RevKPs) of
{_Before, []} ->
NodeList;
{Before, [FirstAfter | _]} ->
[FirstAfter | lists:reverse(Before)]
end
end
end,
{InRange, MaybeInRange} = lists:splitwith(
fun({Key, _}) -> InEndRangeFun(Key) end, Nodes),
NodesInRange = case MaybeInRange of
[FirstMaybeInRange | _] when Dir =:= fwd ->
InRange ++ [FirstMaybeInRange];
_ ->
InRange
end,
reduce_stream_kp_node2(Bt, Dir, NodesInRange, KeyStart, InEndRangeFun,
GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc).
reduce_stream_kp_node2(Bt, Dir, [{_Key, NodeInfo} | RestNodeList], KeyStart, InEndRangeFun,
undefined, [], [], KeyGroupFun, Fun, Acc) ->
{ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} =
reduce_stream_node(Bt, Dir, NodeInfo, KeyStart, InEndRangeFun, undefined,
[], [], KeyGroupFun, Fun, Acc),
reduce_stream_kp_node2(Bt, Dir, RestNodeList, KeyStart, InEndRangeFun, GroupedKey2,
GroupedKVsAcc2, GroupedRedsAcc2, KeyGroupFun, Fun, Acc2);
reduce_stream_kp_node2(Bt, Dir, NodeList, KeyStart, InEndRangeFun,
GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc) ->
{Grouped0, Ungrouped0} = lists:splitwith(fun({Key,_}) ->
KeyGroupFun(GroupedKey, Key) end, NodeList),
{GroupedNodes, UngroupedNodes} =
case Grouped0 of
[] ->
{Grouped0, Ungrouped0};
_ ->
[FirstGrouped | RestGrouped] = lists:reverse(Grouped0),
{RestGrouped, [FirstGrouped | Ungrouped0]}
end,
GroupedReds = [element(2, Node) || {_, Node} <- GroupedNodes],
case UngroupedNodes of
[{_Key, NodeInfo}|RestNodes] ->
{ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} =
reduce_stream_node(Bt, Dir, NodeInfo, KeyStart, InEndRangeFun, GroupedKey,
GroupedKVsAcc, GroupedReds ++ GroupedRedsAcc, KeyGroupFun, Fun, Acc),
reduce_stream_kp_node2(Bt, Dir, RestNodes, KeyStart, InEndRangeFun, GroupedKey2,
GroupedKVsAcc2, GroupedRedsAcc2, KeyGroupFun, Fun, Acc2);
[] ->
{ok, Acc, GroupedReds ++ GroupedRedsAcc, GroupedKVsAcc, GroupedKey}
end.
adjust_dir(fwd, List) ->
List;
adjust_dir(rev, List) ->
lists:reverse(List).
stream_node(Bt, Reds, Node, StartKey, InRange, Dir, Fun, Acc) ->
Pointer = element(1, Node),
{NodeType, NodeList} = get_node(Bt, Pointer),
case NodeType of
kp_node ->
stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc);
kv_node ->
stream_kv_node(Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc)
end.
stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc) ->
Pointer = element(1, Node),
{NodeType, NodeList} = get_node(Bt, Pointer),
case NodeType of
kp_node ->
stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc);
kv_node ->
stream_kv_node2(Bt, Reds, [], adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc)
end.
stream_kp_node(_Bt, _Reds, [], _InRange, _Dir, _Fun, Acc) ->
{ok, Acc};
stream_kp_node(Bt, Reds, [{Key, Node} | Rest], InRange, Dir, Fun, Acc) ->
Red = element(2, Node),
case Fun(traverse, Key, Red, Acc) of
{ok, Acc2} ->
case stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc2) of
{ok, Acc3} ->
stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc3);
{stop, LastReds, Acc3} ->
{stop, LastReds, Acc3}
end;
{skip, Acc2} ->
stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc2)
end.
drop_nodes(_Bt, Reds, _StartKey, []) ->
{Reds, []};
drop_nodes(Bt, Reds, StartKey, [{NodeKey, Node} | RestKPs]) ->
case less(Bt, NodeKey, StartKey) of
true ->
drop_nodes(Bt, [element(2, Node) | Reds], StartKey, RestKPs);
false ->
{Reds, [{NodeKey, Node} | RestKPs]}
end.
stream_kp_node(Bt, Reds, KPs, StartKey, InRange, Dir, Fun, Acc) ->
{NewReds, NodesToStream} =
case Dir of
fwd ->
drop_nodes(Bt, Reds, StartKey, KPs);
rev ->
keep all nodes sorting before the key , AND the first node to sort after
RevKPs = lists:reverse(KPs),
case lists:splitwith(fun({Key, _Pointer}) -> less(Bt, Key, StartKey) end, RevKPs) of
{_RevsBefore, []} ->
{Reds, KPs};
{RevBefore, [FirstAfter | Drop]} ->
{[element(2, Node) || {_K, Node} <- Drop] ++ Reds,
[FirstAfter | lists:reverse(RevBefore)]}
end
end,
case NodesToStream of
[] ->
{ok, Acc};
[{_Key, Node} | Rest] ->
case stream_node(Bt, NewReds, Node, StartKey, InRange, Dir, Fun, Acc) of
{ok, Acc2} ->
Red = element(2, Node),
stream_kp_node(Bt, [Red | NewReds], Rest, InRange, Dir, Fun, Acc2);
{stop, LastReds, Acc2} ->
{stop, LastReds, Acc2}
end
end.
stream_kv_node(Bt, Reds, KVs, StartKey, InRange, Dir, Fun, Acc) ->
DropFun =
case Dir of
fwd ->
fun({Key, _}) -> less(Bt, Key, StartKey) end;
rev ->
fun({Key, _}) -> less(Bt, StartKey, Key) end
end,
{LTKVs, GTEKVs} = lists:splitwith(DropFun, KVs),
AssembleLTKVs = case Bt#btree.assemble_kv of
identity -> LTKVs;
_ -> [assemble(Bt,KV) || KV <- LTKVs]
end,
stream_kv_node2(Bt, Reds, AssembleLTKVs, GTEKVs, InRange, Dir, Fun, Acc).
stream_kv_node2(_Bt, _Reds, _PrevKVs, [], _InRange, _Dir, _Fun, Acc) ->
{ok, Acc};
stream_kv_node2(Bt, Reds, PrevKVs, [{K,_V}=KV | RestKVs], InRange, Dir,
Fun, Acc) ->
case InRange(K) of
false ->
{stop, {PrevKVs, Reds}, Acc};
true ->
AssembledKV = assemble(Bt, KV),
case Fun(visit, AssembledKV, {PrevKVs, Reds}, Acc) of
{ok, Acc2} ->
stream_kv_node2(Bt, Reds, [AssembledKV | PrevKVs], RestKVs,
InRange, Dir, Fun, Acc2);
{stop, Acc2} ->
{stop, {PrevKVs, Reds}, Acc2}
end
end.
|
c201f3f2a13d89c1a70b5ce075ca48eb5cbb280da54f37e5b5301072b53ec80a | plumatic/grab-bag | project.clj | (defproject plumbing "0.1.5-SNAPSHOT"
:internal-dependencies []
:external-dependencies [com.googlecode.concurrentlinkedhashmap/concurrentlinkedhashmap-lru
com.stuartsierra/lazytest
commons-codec
commons-io
joda-time
log4j/log4j
org.clojure/java.classpath
org.clojure/test.check
org.clojure/tools.namespace
com.fasterxml.jackson.core/jackson-core
org.xerial.snappy/snappy-java
potemkin
prismatic/plumbing
prismatic/schema]
:java-source-paths ["jvm"]
:repositories {"apache" "/"
"stuartsierra-releases" ""
"stuartsierra-snapshots" ""})
| null | https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/plumbing/project.clj | clojure | (defproject plumbing "0.1.5-SNAPSHOT"
:internal-dependencies []
:external-dependencies [com.googlecode.concurrentlinkedhashmap/concurrentlinkedhashmap-lru
com.stuartsierra/lazytest
commons-codec
commons-io
joda-time
log4j/log4j
org.clojure/java.classpath
org.clojure/test.check
org.clojure/tools.namespace
com.fasterxml.jackson.core/jackson-core
org.xerial.snappy/snappy-java
potemkin
prismatic/plumbing
prismatic/schema]
:java-source-paths ["jvm"]
:repositories {"apache" "/"
"stuartsierra-releases" ""
"stuartsierra-snapshots" ""})
|
|
1774e815d38929d1757bf4383c7d3da83ded9001b2a3790f98c19a61b3d9c84a | haskell-game/tiny-games-hs | call-by-push-block.hs | n="晘㋲㛻嚵ѫ盝㞝ቂ㝑߳ⳛ㎋拓㾋ⱘ孭ひ・励㓛⭭マᙲ㛾⃝㱛㚙㛨宪㕵㝘㋐⛎㫛ϛ㙉ኛ㙈ኛ涀ʶ氉Ⴖぉ㚛㛛ᇛⴙ䘈㭾⛛䉀媴㛛㫯ⶭッ㑍坝㚤㛛坓䥫㛚≫〃㾵㛝㛛囚㛛ڛ㛫⛛孭嫭"
e('λ':c)|(a,b)<-span(>'n')c=u(u a#m 1 b)%e(y b);e(c:d)=c:e d;e l=l;e&0=u.v;f&_=f
v=foldr(zipWith(:))a;main=print=<<(mapM o.zip[1..].r(h.words).lines$m 5.w.c=<<x)
e%f=e<>f;p=putStr;l=length;w n="λo .+#_\n"!!mod n 8:w(n`div`8);d=getLine;z=m 1.u
r=map;1?f=z;4?f=h[];5?f=y%z%z;i?f=(h.(f&i).r e.f.head)%id;q(x:_)=c x`mod`7;q _=0
g=print;o(n,x)|x==[]=h 0|any(elem '_')$x!!0=do{n!x;p"λ:wasd 🔄:x 🔙:u\n";i<-q<$>d;
o(n,i?([v.u,v,id,v,v,v,r u]!!i)$x)}|0<3=l x<$n!x<*p"↩"<*d;k="λ.";y=drop 1;m=take
n!x@(s:_)=p"\^[cLvl "*>g n*>g(l x)*>p(unlines s);c=fromEnum;[]#""=".";l#""=y l%k
n#"."=n%k;[]#"+"="..";l#"+"='.':y l%k;('o':r)#"_"='O':r%k;l#x=x%l%"λ";h x=pure x
a=[]:a;u=reverse;x=n%"ᅕ䤉喤孭坫㛚㫛㪛囃盃㞛⛳䞛⛳䨫❭ቫ⨉੫❍婫❍ቅ❙孫❅㛛盫棛⛜䛣✛㛛⛛卝⫩㘛⛃㫫❝桝⫌㛝竛㝭㛛㪛㛰㛃ᝪ㭫哈坛ë㝓坝烰"
-- ^10 ------------------------------------------------------------------ 80> --
gam-10 - 80 - hs - prelude / call - by - push - block ( cole - k ) , ghc 9.2.5
λ.o.o.o.o.o._.o.o.o.o.o.λ Call - by - push - block λ.o.o.o.o.o._.o.o.o.o.o.λ
Call - by - push - block is a sokoban game where you go code golfing . To clear a
level , you must move the lambda ( ` λ ` ) to push a block ( ` o ` ) into every hole
( ` _ ` ) .
Your score is the number of moves you take . Like in real golf , a lower
score is better , but make sure you can complete the level first before you
try to get the best score .
There are 15 levels of roughly increasing difficulty . They will take around
an hour to complete , depending on experience . Your scores for each level
are given at the end : compete with your friends to see who can get the
lowest scores !
Running :
- This program requires no additional arguments and can be run using
` runghc ` .
General advice :
- You need to hit enter to submit your move ( a quirk of this entry being in
the Prelude category ) .
- Try everything ! You can always undo or reset if you reach an unsolvable
state .
- Read the " Controls in detail " section if you 're confused by the controls .
- Read the " Hints " section if you get stuck .
The cast :
- λ : The player character .
- o : A block you can push .
- _ : The hole you need to push a block into .
- Joined by several others !
Scoring :
- Your score is displayed beneath the level number , starting at 1 .
- It increments for every move and undo you make and resets whenever you
reset the level .
- A lower score is better , except for a score of 0 which indicates an
incompleted level .
Controls in detail :
Note that you need to press enter in order to make a move .
- Movement : [ wasd ]
- [ w ] : up [ s ] : down [ a ] : left [ d ] : right .
- Reset : [ x ]
- Resets the level . Also resets your score .
- Undo : [ u ]
- Undoes one move . This feature is added for convenience since moves must
be sent using the enter key ( and thus it takes longer to get back where
you were if you make a mistake ) and incurs a small score penalty .
- Additional notes
- You need to press enter in order to make a move .
- When prompted with ↩ , press enter to continue .
- Technically , all keys map to a control . Try to avoid pressing an
unlabeled key as you can accidentally skip a level this way .
Hints :
These hints all contain spoilers and as such are enciphered using rot-13 .
I recommend revealing them in order until you find one that helps . If you
are completely stuck on a level , there is a level skip code at the end .
- Levels 1 - 5
- Lbh pna qverpg tevq . erdhver lbh
va .
- Gur unfu vf n fgngvp bofgnpyr . Yvxr n ubyr , vg pnaabg or zbirq be
. vg .
- Lbh pna gvzr .
- Lbh pna chfu oybpxf bss bs gur tevq . Or pnershy abg
tevq .
- Lbh arrq na n oybpx va . Sbe
rknzcyr , , vg arrqf na . rira vg
ubyrf gung ner vanpprffvoyr .
- Levels 5 - 8
- Gur svefg uvag vf ab : n
tevq vf arprffnel . : lbh bayl arrq gb
chfu n .
- gel guvatf va . Fbzrgvzrf lbh
evtug vqrn ohg .
- Erfrg be haqb rneyl vs lbh ernyvmr lbh ner va na . N
jurgure lbh ner va bar vf gb pbhag gur ahzore
vs gurer vf n oybpx gung pna or chfurq
vagb rnpu . .
- Levels 9 - 15
- Gur cyhf vf n naq oybpxf
. Jura n vg be n cynlre
vg , vg ner ercynprq jvgu
na .
- bs unfurf be ubyrf gb zbir fbzr cynlre xrrcvat .
- Rynobengvat ba gur , lbh jvyy svaq gung fbzr
frrz vzcbffvoyr ner bayl fb abg
pbbeqvangrq va fcnpr cebcreyl . Fbzrgvzrf lbh arrq gb pbbeqvangr
bar naq xrrcvat . Bgure or
frcnengrq va na .
- Level skip cheat code
- Glcr " Purng Pbqr " ( pnfr frafvgvir ) naq .
, vaqvpngvat . Vs
lbh , will suffice .
Acknowledgements :
- Golfing : I 've learned a bunch about code golfing in Haskell from various
tips and threads I 've read from inumerably many people . I got some
explicit help from The Ninteenth Byte on Stack Exchange with shaving
characters off . Thank you !
- Testing and design : I solicited help from a bunch of people who
graciously lent me their time and feedback . Thank you !
- The jam and feedback : # haskell - game and the organizers of The Haskell Tiny
Game Jam . Thank you !
λ.o.o.o.o.o._.o.o.o.o.o.λ Call-by-push-block λ.o.o.o.o.o._.o.o.o.o.o.λ
Call-by-push-block is a sokoban game where you go code golfing. To clear a
level, you must move the lambda (`λ`) to push a block (`o`) into every hole
(`_`).
Your score is the number of moves you take. Like in real golf, a lower
score is better, but make sure you can complete the level first before you
try to get the best score.
There are 15 levels of roughly increasing difficulty. They will take around
an hour to complete, depending on experience. Your scores for each level
are given at the end: compete with your friends to see who can get the
lowest scores!
Running:
- This program requires no additional arguments and can be run using
`runghc`.
General advice:
- You need to hit enter to submit your move (a quirk of this entry being in
the Prelude category).
- Try everything! You can always undo or reset if you reach an unsolvable
state.
- Read the "Controls in detail" section if you're confused by the controls.
- Read the "Hints" section if you get stuck.
The cast:
- λ: The player character.
- o: A block you can push.
- _: The hole you need to push a block into.
- Joined by several others!
Scoring:
- Your score is displayed beneath the level number, starting at 1.
- It increments for every move and undo you make and resets whenever you
reset the level.
- A lower score is better, except for a score of 0 which indicates an
incompleted level.
Controls in detail:
Note that you need to press enter in order to make a move.
- Movement: [wasd]
- [w]: up [s]: down [a]: left [d]: right.
- Reset: [x]
- Resets the level. Also resets your score.
- Undo: [u]
- Undoes one move. This feature is added for convenience since moves must
be sent using the enter key (and thus it takes longer to get back where
you were if you make a mistake) and incurs a small score penalty.
- Additional notes
- You need to press enter in order to make a move.
- When prompted with ↩, press enter to continue.
- Technically, all keys map to a control. Try to avoid pressing an
unlabeled key as you can accidentally skip a level this way.
Hints:
These hints all contain spoilers and as such are enciphered using rot-13.
I recommend revealing them in order until you find one that helps. If you
are completely stuck on a level, there is a level skip code at the end.
- Levels 1-5
- Lbh pna qverpg gur cynlre punenpgre bss gur tevq. Guvf jvyy erdhver lbh
gb erfrg va beqre gb orng gur yriry.
- Gur unfu vf n fgngvp bofgnpyr. Yvxr n ubyr, vg pnaabg or zbirq be
cnffrq guebhtu. Lbh nyfb pnaabg chfu oybpxf vagb vg.
- Lbh pna chfu zhygvcyr oybpxf ng n gvzr.
- Lbh pna chfu oybpxf bss bs gur tevq. Or pnershy abg gb chfu n oybpx lbh
arrq bss gur tevq.
- Lbh arrq na rzcgl gvyr nqwnprag gb n oybpx va beqre gb chfu vg. Sbe
rknzcyr, gb chfu n oybpx qbja, vg arrqf na rzcgl gvyr nobir vg. Xrrc
guvf va zvaq rira sbe yngre yriryf fvapr vg jvyy nyybj lbh gb vqragvsl
ubyrf gung ner vanpprffvoyr gb pregnva oybpxf.
- Levels 5-8
- Gur svefg uvag vf ab ybatre gehr: gurer ner pbaqvgvbaf jurer chfuvat n
cynlre punenpgre bss gur tevq vf arprffnel. Erzrzore: lbh bayl arrq gb
chfu n oybpx vagb rnpu ubyr.
- Gur beqre lbh gel guvatf va bsgra znggref. Fbzrgvzrf lbh znl unir gur
evtug vqrn ohg jebat rkrphgvba beqre.
- Erfrg be haqb rneyl vs lbh ernyvmr lbh ner va na hajvaanoyr fgngr. N
dhvpx gevpx gb qrgrezvar jurgure lbh ner va bar vf gb pbhag gur ahzore
bs erznvavat ubyrf naq purpx vs gurer vf n oybpx gung pna or chfurq
vagb rnpu. Ersre nyfb gb gur ynfg uvag bs gur cerivbhf frpgvba.
- Levels 9-15
- Gur cyhf vf n gvyr gung qrfgeblf obgu cynlre punenpgref naq oybpxf
nyvxr. Jura n oybpx vf chfurq vagb vg be n cynlre punenpgre zbirf vagb
vg, obgu gur cyhf naq gur bowrpg rapbhagrevat vg ner ercynprq jvgu
na rzcgl gvyr.
- Gnxr nqinagntr bs unfurf be ubyrf gb zbir fbzr cynlre punenpgref jvyy
xrrcvat bguref fgngvbanel.
- Rynobengvat ba gur nobir uvag, lbh jvyy svaq gung fbzr guvatf juvpu
frrz vzcbffvoyr ner bayl fb orpnhfr lbhe cynlre punenpgref ner abg
pbbeqvangrq va fcnpr cebcreyl. Fbzrgvzrf lbh arrq gb pbbeqvangr gurz ol
zbivat bar naq xrrcvat nabgure fgngvbanel. Bgure gvzrf gurl jvyy or
frcnengrq va na hajvaanoyr fgngr.
- Level skip cheat code
- Glcr "Purng Pbqr" (pnfr frafvgvir) naq cerff ragre gb fxvc gur yriry.
Guvf jvyy pbasre n fpber bs 0, vaqvpngvat gur yriry jnf fxvccrq. Vs
lbh ner cynlvat ba gur haohssrerq irefvba, whfg glcvat gur svefg
yetter will suffice.
Acknowledgements :
- Golfing: I've learned a bunch about code golfing in Haskell from various
tips and threads I've read from inumerably many people. I got some
explicit help from The Ninteenth Byte on Stack Exchange with shaving
characters off. Thank you!
- Testing and design: I solicited help from a bunch of people who
graciously lent me their time and feedback. Thank you!
- The jam and feedback: #haskell-game and the organizers of The Haskell Tiny
Game Jam. Thank you!
-}
| null | https://raw.githubusercontent.com/haskell-game/tiny-games-hs/946d136392fa2986c86ee3e9d87cd9f31a03d9a6/prelude/call-by-push-block/call-by-push-block.hs | haskell | ^10 ------------------------------------------------------------------ 80> -- | n="晘㋲㛻嚵ѫ盝㞝ቂ㝑߳ⳛ㎋拓㾋ⱘ孭ひ・励㓛⭭マᙲ㛾⃝㱛㚙㛨宪㕵㝘㋐⛎㫛ϛ㙉ኛ㙈ኛ涀ʶ氉Ⴖぉ㚛㛛ᇛⴙ䘈㭾⛛䉀媴㛛㫯ⶭッ㑍坝㚤㛛坓䥫㛚≫〃㾵㛝㛛囚㛛ڛ㛫⛛孭嫭"
e('λ':c)|(a,b)<-span(>'n')c=u(u a#m 1 b)%e(y b);e(c:d)=c:e d;e l=l;e&0=u.v;f&_=f
v=foldr(zipWith(:))a;main=print=<<(mapM o.zip[1..].r(h.words).lines$m 5.w.c=<<x)
e%f=e<>f;p=putStr;l=length;w n="λo .+#_\n"!!mod n 8:w(n`div`8);d=getLine;z=m 1.u
r=map;1?f=z;4?f=h[];5?f=y%z%z;i?f=(h.(f&i).r e.f.head)%id;q(x:_)=c x`mod`7;q _=0
g=print;o(n,x)|x==[]=h 0|any(elem '_')$x!!0=do{n!x;p"λ:wasd 🔄:x 🔙:u\n";i<-q<$>d;
o(n,i?([v.u,v,id,v,v,v,r u]!!i)$x)}|0<3=l x<$n!x<*p"↩"<*d;k="λ.";y=drop 1;m=take
n!x@(s:_)=p"\^[cLvl "*>g n*>g(l x)*>p(unlines s);c=fromEnum;[]#""=".";l#""=y l%k
n#"."=n%k;[]#"+"="..";l#"+"='.':y l%k;('o':r)#"_"='O':r%k;l#x=x%l%"λ";h x=pure x
a=[]:a;u=reverse;x=n%"ᅕ䤉喤孭坫㛚㫛㪛囃盃㞛⛳䞛⛳䨫❭ቫ⨉੫❍婫❍ቅ❙孫❅㛛盫棛⛜䛣✛㛛⛛卝⫩㘛⛃㫫❝桝⫌㛝竛㝭㛛㪛㛰㛃ᝪ㭫哈坛ë㝓坝烰"
gam-10 - 80 - hs - prelude / call - by - push - block ( cole - k ) , ghc 9.2.5
λ.o.o.o.o.o._.o.o.o.o.o.λ Call - by - push - block λ.o.o.o.o.o._.o.o.o.o.o.λ
Call - by - push - block is a sokoban game where you go code golfing . To clear a
level , you must move the lambda ( ` λ ` ) to push a block ( ` o ` ) into every hole
( ` _ ` ) .
Your score is the number of moves you take . Like in real golf , a lower
score is better , but make sure you can complete the level first before you
try to get the best score .
There are 15 levels of roughly increasing difficulty . They will take around
an hour to complete , depending on experience . Your scores for each level
are given at the end : compete with your friends to see who can get the
lowest scores !
Running :
- This program requires no additional arguments and can be run using
` runghc ` .
General advice :
- You need to hit enter to submit your move ( a quirk of this entry being in
the Prelude category ) .
- Try everything ! You can always undo or reset if you reach an unsolvable
state .
- Read the " Controls in detail " section if you 're confused by the controls .
- Read the " Hints " section if you get stuck .
The cast :
- λ : The player character .
- o : A block you can push .
- _ : The hole you need to push a block into .
- Joined by several others !
Scoring :
- Your score is displayed beneath the level number , starting at 1 .
- It increments for every move and undo you make and resets whenever you
reset the level .
- A lower score is better , except for a score of 0 which indicates an
incompleted level .
Controls in detail :
Note that you need to press enter in order to make a move .
- Movement : [ wasd ]
- [ w ] : up [ s ] : down [ a ] : left [ d ] : right .
- Reset : [ x ]
- Resets the level . Also resets your score .
- Undo : [ u ]
- Undoes one move . This feature is added for convenience since moves must
be sent using the enter key ( and thus it takes longer to get back where
you were if you make a mistake ) and incurs a small score penalty .
- Additional notes
- You need to press enter in order to make a move .
- When prompted with ↩ , press enter to continue .
- Technically , all keys map to a control . Try to avoid pressing an
unlabeled key as you can accidentally skip a level this way .
Hints :
These hints all contain spoilers and as such are enciphered using rot-13 .
I recommend revealing them in order until you find one that helps . If you
are completely stuck on a level , there is a level skip code at the end .
- Levels 1 - 5
- Lbh pna qverpg tevq . erdhver lbh
va .
- Gur unfu vf n fgngvp bofgnpyr . Yvxr n ubyr , vg pnaabg or zbirq be
. vg .
- Lbh pna gvzr .
- Lbh pna chfu oybpxf bss bs gur tevq . Or pnershy abg
tevq .
- Lbh arrq na n oybpx va . Sbe
rknzcyr , , vg arrqf na . rira vg
ubyrf gung ner vanpprffvoyr .
- Levels 5 - 8
- Gur svefg uvag vf ab : n
tevq vf arprffnel . : lbh bayl arrq gb
chfu n .
- gel guvatf va . Fbzrgvzrf lbh
evtug vqrn ohg .
- Erfrg be haqb rneyl vs lbh ernyvmr lbh ner va na . N
jurgure lbh ner va bar vf gb pbhag gur ahzore
vs gurer vf n oybpx gung pna or chfurq
vagb rnpu . .
- Levels 9 - 15
- Gur cyhf vf n naq oybpxf
. Jura n vg be n cynlre
vg , vg ner ercynprq jvgu
na .
- bs unfurf be ubyrf gb zbir fbzr cynlre xrrcvat .
- Rynobengvat ba gur , lbh jvyy svaq gung fbzr
frrz vzcbffvoyr ner bayl fb abg
pbbeqvangrq va fcnpr cebcreyl . Fbzrgvzrf lbh arrq gb pbbeqvangr
bar naq xrrcvat . Bgure or
frcnengrq va na .
- Level skip cheat code
- Glcr " Purng Pbqr " ( pnfr frafvgvir ) naq .
, vaqvpngvat . Vs
lbh , will suffice .
Acknowledgements :
- Golfing : I 've learned a bunch about code golfing in Haskell from various
tips and threads I 've read from inumerably many people . I got some
explicit help from The Ninteenth Byte on Stack Exchange with shaving
characters off . Thank you !
- Testing and design : I solicited help from a bunch of people who
graciously lent me their time and feedback . Thank you !
- The jam and feedback : # haskell - game and the organizers of The Haskell Tiny
Game Jam . Thank you !
λ.o.o.o.o.o._.o.o.o.o.o.λ Call-by-push-block λ.o.o.o.o.o._.o.o.o.o.o.λ
Call-by-push-block is a sokoban game where you go code golfing. To clear a
level, you must move the lambda (`λ`) to push a block (`o`) into every hole
(`_`).
Your score is the number of moves you take. Like in real golf, a lower
score is better, but make sure you can complete the level first before you
try to get the best score.
There are 15 levels of roughly increasing difficulty. They will take around
an hour to complete, depending on experience. Your scores for each level
are given at the end: compete with your friends to see who can get the
lowest scores!
Running:
- This program requires no additional arguments and can be run using
`runghc`.
General advice:
- You need to hit enter to submit your move (a quirk of this entry being in
the Prelude category).
- Try everything! You can always undo or reset if you reach an unsolvable
state.
- Read the "Controls in detail" section if you're confused by the controls.
- Read the "Hints" section if you get stuck.
The cast:
- λ: The player character.
- o: A block you can push.
- _: The hole you need to push a block into.
- Joined by several others!
Scoring:
- Your score is displayed beneath the level number, starting at 1.
- It increments for every move and undo you make and resets whenever you
reset the level.
- A lower score is better, except for a score of 0 which indicates an
incompleted level.
Controls in detail:
Note that you need to press enter in order to make a move.
- Movement: [wasd]
- [w]: up [s]: down [a]: left [d]: right.
- Reset: [x]
- Resets the level. Also resets your score.
- Undo: [u]
- Undoes one move. This feature is added for convenience since moves must
be sent using the enter key (and thus it takes longer to get back where
you were if you make a mistake) and incurs a small score penalty.
- Additional notes
- You need to press enter in order to make a move.
- When prompted with ↩, press enter to continue.
- Technically, all keys map to a control. Try to avoid pressing an
unlabeled key as you can accidentally skip a level this way.
Hints:
These hints all contain spoilers and as such are enciphered using rot-13.
I recommend revealing them in order until you find one that helps. If you
are completely stuck on a level, there is a level skip code at the end.
- Levels 1-5
- Lbh pna qverpg gur cynlre punenpgre bss gur tevq. Guvf jvyy erdhver lbh
gb erfrg va beqre gb orng gur yriry.
- Gur unfu vf n fgngvp bofgnpyr. Yvxr n ubyr, vg pnaabg or zbirq be
cnffrq guebhtu. Lbh nyfb pnaabg chfu oybpxf vagb vg.
- Lbh pna chfu zhygvcyr oybpxf ng n gvzr.
- Lbh pna chfu oybpxf bss bs gur tevq. Or pnershy abg gb chfu n oybpx lbh
arrq bss gur tevq.
- Lbh arrq na rzcgl gvyr nqwnprag gb n oybpx va beqre gb chfu vg. Sbe
rknzcyr, gb chfu n oybpx qbja, vg arrqf na rzcgl gvyr nobir vg. Xrrc
guvf va zvaq rira sbe yngre yriryf fvapr vg jvyy nyybj lbh gb vqragvsl
ubyrf gung ner vanpprffvoyr gb pregnva oybpxf.
- Levels 5-8
- Gur svefg uvag vf ab ybatre gehr: gurer ner pbaqvgvbaf jurer chfuvat n
cynlre punenpgre bss gur tevq vf arprffnel. Erzrzore: lbh bayl arrq gb
chfu n oybpx vagb rnpu ubyr.
- Gur beqre lbh gel guvatf va bsgra znggref. Fbzrgvzrf lbh znl unir gur
evtug vqrn ohg jebat rkrphgvba beqre.
- Erfrg be haqb rneyl vs lbh ernyvmr lbh ner va na hajvaanoyr fgngr. N
dhvpx gevpx gb qrgrezvar jurgure lbh ner va bar vf gb pbhag gur ahzore
bs erznvavat ubyrf naq purpx vs gurer vf n oybpx gung pna or chfurq
vagb rnpu. Ersre nyfb gb gur ynfg uvag bs gur cerivbhf frpgvba.
- Levels 9-15
- Gur cyhf vf n gvyr gung qrfgeblf obgu cynlre punenpgref naq oybpxf
nyvxr. Jura n oybpx vf chfurq vagb vg be n cynlre punenpgre zbirf vagb
vg, obgu gur cyhf naq gur bowrpg rapbhagrevat vg ner ercynprq jvgu
na rzcgl gvyr.
- Gnxr nqinagntr bs unfurf be ubyrf gb zbir fbzr cynlre punenpgref jvyy
xrrcvat bguref fgngvbanel.
- Rynobengvat ba gur nobir uvag, lbh jvyy svaq gung fbzr guvatf juvpu
frrz vzcbffvoyr ner bayl fb orpnhfr lbhe cynlre punenpgref ner abg
pbbeqvangrq va fcnpr cebcreyl. Fbzrgvzrf lbh arrq gb pbbeqvangr gurz ol
zbivat bar naq xrrcvat nabgure fgngvbanel. Bgure gvzrf gurl jvyy or
frcnengrq va na hajvaanoyr fgngr.
- Level skip cheat code
- Glcr "Purng Pbqr" (pnfr frafvgvir) naq cerff ragre gb fxvc gur yriry.
Guvf jvyy pbasre n fpber bs 0, vaqvpngvat gur yriry jnf fxvccrq. Vs
lbh ner cynlvat ba gur haohssrerq irefvba, whfg glcvat gur svefg
yetter will suffice.
Acknowledgements :
- Golfing: I've learned a bunch about code golfing in Haskell from various
tips and threads I've read from inumerably many people. I got some
explicit help from The Ninteenth Byte on Stack Exchange with shaving
characters off. Thank you!
- Testing and design: I solicited help from a bunch of people who
graciously lent me their time and feedback. Thank you!
- The jam and feedback: #haskell-game and the organizers of The Haskell Tiny
Game Jam. Thank you!
-}
|
876a396b4297e66f7f0a26861772be1202b224b4a1a6390b00d4c361b2a53481 | haskell-opengl/OpenGLRaw | GeometryShader4.hs | # LANGUAGE PatternSynonyms #
--------------------------------------------------------------------------------
-- |
Module : Graphics . GL.ARB.GeometryShader4
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.GeometryShader4 (
-- * Extension Support
glGetARBGeometryShader4,
gl_ARB_geometry_shader4,
-- * Enums
pattern GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB,
pattern GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER,
pattern GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB,
pattern GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB,
pattern GL_GEOMETRY_INPUT_TYPE_ARB,
pattern GL_GEOMETRY_OUTPUT_TYPE_ARB,
pattern GL_GEOMETRY_SHADER_ARB,
pattern GL_GEOMETRY_VERTICES_OUT_ARB,
pattern GL_LINES_ADJACENCY_ARB,
pattern GL_LINE_STRIP_ADJACENCY_ARB,
pattern GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB,
pattern GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_ARB,
pattern GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB,
pattern GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB,
pattern GL_MAX_GEOMETRY_VARYING_COMPONENTS_ARB,
pattern GL_MAX_VARYING_COMPONENTS,
pattern GL_MAX_VERTEX_VARYING_COMPONENTS_ARB,
pattern GL_PROGRAM_POINT_SIZE_ARB,
pattern GL_TRIANGLES_ADJACENCY_ARB,
pattern GL_TRIANGLE_STRIP_ADJACENCY_ARB,
-- * Functions
glFramebufferTextureARB,
glFramebufferTextureFaceARB,
glFramebufferTextureLayerARB,
glProgramParameteriARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/ARB/GeometryShader4.hs | haskell | ------------------------------------------------------------------------------
|
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Enums
* Functions | # LANGUAGE PatternSynonyms #
Module : Graphics . GL.ARB.GeometryShader4
Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.ARB.GeometryShader4 (
glGetARBGeometryShader4,
gl_ARB_geometry_shader4,
pattern GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB,
pattern GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER,
pattern GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB,
pattern GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB,
pattern GL_GEOMETRY_INPUT_TYPE_ARB,
pattern GL_GEOMETRY_OUTPUT_TYPE_ARB,
pattern GL_GEOMETRY_SHADER_ARB,
pattern GL_GEOMETRY_VERTICES_OUT_ARB,
pattern GL_LINES_ADJACENCY_ARB,
pattern GL_LINE_STRIP_ADJACENCY_ARB,
pattern GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB,
pattern GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_ARB,
pattern GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB,
pattern GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB,
pattern GL_MAX_GEOMETRY_VARYING_COMPONENTS_ARB,
pattern GL_MAX_VARYING_COMPONENTS,
pattern GL_MAX_VERTEX_VARYING_COMPONENTS_ARB,
pattern GL_PROGRAM_POINT_SIZE_ARB,
pattern GL_TRIANGLES_ADJACENCY_ARB,
pattern GL_TRIANGLE_STRIP_ADJACENCY_ARB,
glFramebufferTextureARB,
glFramebufferTextureFaceARB,
glFramebufferTextureLayerARB,
glProgramParameteriARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
a1772b4f747d28473de0f659d1269726a3aa5eb31a60a67dd106f85ae0a9664a | binsec/haunted | dba_to_formula.ml | (**************************************************************************)
This file is part of BINSEC .
(* *)
Copyright ( C ) 2016 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* 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 , version 2.1 .
(* *)
(* It 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. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
open Formula
exception NoSmtEquivalent
let unary = function
| Dba.Unary_op.UMinus -> BvNeg
| Dba.Unary_op.Not -> BvNot
| _ -> assert false
let binary = function (* DBAs are broken *)
| Dba.Binary_op.Plus -> `Bnop BvAdd
| Dba.Binary_op.Minus -> `Bnop BvSub
| Dba.Binary_op.Mult -> `Bnop BvMul
| Dba.Binary_op.DivU -> `Bnop BvUdiv
| Dba.Binary_op.DivS -> `Bnop BvSdiv
| Dba.Binary_op.ModU -> `Bnop BvSrem
| Dba.Binary_op.ModS -> `Bnop BvSmod
| Dba.Binary_op.Or -> `Bnop BvOr
| Dba.Binary_op.And -> `Bnop BvAnd
| Dba.Binary_op.Xor -> `Bnop BvXor
| Dba.Binary_op.Concat -> `Bnop BvConcat
| Dba.Binary_op.LShift -> `Bnop BvShl
| Dba.Binary_op.RShiftU -> `Bnop BvLshr
| Dba.Binary_op.RShiftS -> `Bnop BvAshr
| Dba.Binary_op.LeftRotate -> `Unop (BvRotateLeft 0)
| Dba.Binary_op.RightRotate -> `Unop (BvRotateRight 0)
| Dba.Binary_op.Eq -> `Comp BvEqual
| Dba.Binary_op.Diff -> `Comp BvDistinct
| Dba.Binary_op.LeqU -> `Comp BvUle
| Dba.Binary_op.LtU -> `Comp BvUlt
| Dba.Binary_op.GeqU -> `Comp BvUge
| Dba.Binary_op.GtU -> `Comp BvUgt
| Dba.Binary_op.LeqS -> `Comp BvSle
| Dba.Binary_op.LtS -> `Comp BvSlt
| Dba.Binary_op.GeqS -> `Comp BvSge
| Dba.Binary_op.GtS -> `Comp BvSgt
| null | https://raw.githubusercontent.com/binsec/haunted/7ffc5f4072950fe138f53fe953ace98fff181c73/src/dba/dba_to_formula.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It 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.
************************************************************************
DBAs are broken | This file is part of BINSEC .
Copyright ( C ) 2016 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Formula
exception NoSmtEquivalent
let unary = function
| Dba.Unary_op.UMinus -> BvNeg
| Dba.Unary_op.Not -> BvNot
| _ -> assert false
| Dba.Binary_op.Plus -> `Bnop BvAdd
| Dba.Binary_op.Minus -> `Bnop BvSub
| Dba.Binary_op.Mult -> `Bnop BvMul
| Dba.Binary_op.DivU -> `Bnop BvUdiv
| Dba.Binary_op.DivS -> `Bnop BvSdiv
| Dba.Binary_op.ModU -> `Bnop BvSrem
| Dba.Binary_op.ModS -> `Bnop BvSmod
| Dba.Binary_op.Or -> `Bnop BvOr
| Dba.Binary_op.And -> `Bnop BvAnd
| Dba.Binary_op.Xor -> `Bnop BvXor
| Dba.Binary_op.Concat -> `Bnop BvConcat
| Dba.Binary_op.LShift -> `Bnop BvShl
| Dba.Binary_op.RShiftU -> `Bnop BvLshr
| Dba.Binary_op.RShiftS -> `Bnop BvAshr
| Dba.Binary_op.LeftRotate -> `Unop (BvRotateLeft 0)
| Dba.Binary_op.RightRotate -> `Unop (BvRotateRight 0)
| Dba.Binary_op.Eq -> `Comp BvEqual
| Dba.Binary_op.Diff -> `Comp BvDistinct
| Dba.Binary_op.LeqU -> `Comp BvUle
| Dba.Binary_op.LtU -> `Comp BvUlt
| Dba.Binary_op.GeqU -> `Comp BvUge
| Dba.Binary_op.GtU -> `Comp BvUgt
| Dba.Binary_op.LeqS -> `Comp BvSle
| Dba.Binary_op.LtS -> `Comp BvSlt
| Dba.Binary_op.GeqS -> `Comp BvSge
| Dba.Binary_op.GtS -> `Comp BvSgt
|
5cec5857c21d4db47af424c08a80bece2eb266165b62c8b241c0207080a016b5 | prikhi/quickbooks-for-communes | WebConnector.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module QuickBooks.WebConnector
( -- * QWC File Generation
QWCConfig(..)
, AuthFlag(..)
, PersonalDataPreference(..)
, QBType(..)
, Schedule(..)
, SOAPStyle(..)
, UnattendedModePreference(..)
* WebConnector Callbacks & Responses
, Callback(..)
, CallbackResponse(..)
, Username(..)
, Password(..)
, AuthResult(..)
, PostponeMinutes(..)
, AutorunMinutes(..)
, GetLastErrorResult(..)
)
where
import Data.Aeson ( (.=)
, ToJSON(..)
, object
)
import Data.ByteString ( ByteString )
import Data.Maybe ( catMaybes )
import Data.Text ( Text
, pack
, unpack
)
import qualified Data.Text as T
import Data.Text.Encoding ( decodeUtf8 )
import Data.UUID ( UUID )
import qualified Data.UUID as UUID
import Parser ( FromXML(..)
, Parser
, ParsingErrorType(..)
, parseError
, throwParsingError
, matchName
, oneOf
, find
, at
, parseContent
, parseContentWith
, withNamespace
)
import QuickBooks.QBXML ( Request(..)
, buildRequest
, Response(..)
, HostData
, CompanyData
, PreferencesData
)
import Text.XML.Generator ( Xml
, Elem
, Namespace
, xrender
, xelemWithText
, xelem
, xelems
, xelemQ
, xtext
, namespace
)
import Text.XML ( Name )
import XML ( ToXML(..) )
-- Config File
data QWCConfig = QWCConfig
{ qcAppDescription :: Text
, qcAppDisplayName :: Maybe Text
, qcAppID :: Text
, qcAppName :: Text
, qcAppSupport :: Text
, qcAppUniqueName :: Maybe Text
, qcAppURL :: Text
, qcCertURL :: Maybe Text
, qcAuthFlags :: [AuthFlag]
, qcFileID :: UUID
, qcIsReadOnly :: Bool
, qcNotify :: Bool
, qcOwnerID :: UUID
, qcPersonalDataPref :: Maybe PersonalDataPreference
, qcQBType :: QBType
, qcScheduler :: Maybe Schedule
, qcStyle :: Maybe SOAPStyle
, qcUnattendedModePref :: Maybe UnattendedModePreference
, qcUserName :: Text
} deriving (Show)
-- | Generate the QWC XML configuration file for a QuickBooks User's Web
-- Connector.
instance ToXML QWCConfig where
toXML QWCConfig {..} = xelem "QBWCXML" $ xelems $ catMaybes
[ justXText "AppDescription" qcAppDescription
, maybeElem "AppDisplayName" qcAppDisplayName
, justXText "AppID" qcAppID
, justXText "AppName" qcAppName
, justXText "AppSupport" qcAppSupport
, maybeElem "AppUniqueName" qcAppUniqueName
, justXText "AppURL" qcAppURL
, maybeElem "CertURL" qcCertURL
, justXText "AuthFlags" $ showT $ andAuthFlags qcAuthFlags
, justXText "FileID" $ showUUID qcFileID
, justXBool "IsReadOnly" qcIsReadOnly
, justXBool "Notify" qcNotify
, justXText "OwnerID" $ showUUID qcOwnerID
, maybeElemWith "PersonalDataPref" showT qcPersonalDataPref
, justXText "QBType" $ showT qcQBType
, fmap (xelem "Scheduler" . xSchedule) qcScheduler
, maybeElemWith "Style" showT qcStyle
, maybeElemWith "UnattendedModePref" showT qcUnattendedModePref
, justXText "UserName" qcUserName
]
where
justXText name = Just . xelemWithText name
maybeElem name = fmap $ xelemWithText name
maybeElemWith name f = maybeElem name . fmap f
justXBool name bool = justXText name $ if bool then "true" else "false"
showUUID :: UUID -> Text
showUUID uuid = "{" <> UUID.toText uuid <> "}"
-- | Nest the generated XML string under a @config@ key.
instance ToJSON QWCConfig where
toJSON cfg =
let xml :: ByteString
xml = xrender $ toXML cfg
in object ["config" .= decodeUtf8 xml]
data AuthFlag
= AllEditions
| QBSimpleStart
| QBPro
| QBPremier
| QBEnterprise
deriving (Show)
-- TODO: if list contains All, just return sum, else nub list and fold
andAuthFlags :: [AuthFlag] -> Integer
andAuthFlags = foldr (\flag acc -> toInt flag + acc) 0
where
toInt = \case
AllEditions -> 1 + 2 + 4 + 8
QBSimpleStart -> 1
QBPro -> 2
QBPremier -> 4
QBEnterprise -> 8
data PersonalDataPreference
= PersonalDataNotNeeded
| PersonalDataOptional
| PersonalDataRequired
instance Show PersonalDataPreference where
show = \case
PersonalDataNotNeeded -> "pdpNotNeeded"
PersonalDataOptional -> "pdpOptional"
PersonalDataRequired -> "pdpRequired"
data QBType
= Financial
| PointOfSale
instance Show QBType where
show = \case
Financial -> "QBFS"
PointOfSale -> "QBPOS"
data Schedule
= EveryMinute Integer
| EverySecond Integer
deriving (Show)
xSchedule :: Schedule -> Xml Elem
xSchedule = \case
EveryMinute i -> xelem "RunEveryNMinutes" . pack $ show i
EverySecond i -> xelem "RunEveryNSeconds" . pack $ show i
data SOAPStyle
= Document
| DocWrapped
| RPC
deriving (Show)
data UnattendedModePreference
= UnattendedModeOptional
| UnattendedModeRequired
instance Show UnattendedModePreference where
show = \case
UnattendedModeOptional -> "umpOptional"
UnattendedModeRequired -> "umpRequired"
-- Callbacks
data Callback
= ServerVersion
| ClientVersion Text
| Authenticate Username Password
| The first sendRequestXML callback received contains Host , Company ,
-- & Preference data.
--
-- TODO: Split out into separate record type so we can get named fields?
| InitialSendRequestXML
UUID -- ^ The session ticket
HostData -- ^ HostQuery data for the running version of QuickBooks
CompanyData -- ^ CompanyQuery data for the company file
^ PreferencesQuery data for the company file
Text -- ^ The Company Filename
Text -- ^ The Country version of QuickBooks
Integer -- ^ The Major version of the qbXML Processor
^ The Minor version of the qbXML Processor
| ReceiveResponseXML
UUID -- ^ The session ticket
^ The parsed response
| CloseConnection
UUID -- ^ The session ticket
| ConnectionError
UUID -- ^ The session ticket
^ The @HRESULT@ hex - string thrown by the WebConnector .
Text -- ^ The error message for the HRESULT.
| GetLastError
UUID -- ^ The session ticket
deriving (Show)
instance FromXML Callback where
fromXML = oneOf
[ parseServerVersion
, parseClientVersion
, parseAuthenticate
, parseInitialSendRequestXML
, parseReceiveResponseXML
, parseCloseConnection
, parseConnectionError
, parseGetLastError
, parseError "Unsupported WebConnector Callback"
]
parseServerVersion :: Parser Callback
parseServerVersion = matchName (qbName "serverVersion") $ return ServerVersion
parseClientVersion :: Parser Callback
parseClientVersion =
matchName (qbName "clientVersion")
$ ClientVersion
<$> find (qbName "strVersion") parseContent
parseAuthenticate :: Parser Callback
parseAuthenticate = matchName (qbName "authenticate") $ do
user <- Username <$> find (qbName "strUserName") parseContent
pass <- Password <$> find (qbName "strPassword") parseContent
return $ Authenticate user pass
parseInitialSendRequestXML :: Parser Callback
parseInitialSendRequestXML = matchName (qbName "sendRequestXML") $ do
(hostData, companyData, preferencesData) <-
find (qbName "strHCPResponse")
$ parseContentWith
$ find "QBXMLMsgsRs"
$ (,,)
<$> at ["HostQueryRs", "HostRet"] fromXML
<*> at ["CompanyQueryRs", "CompanyRet"] fromXML
<*> at ["PreferencesQueryRs", "PreferencesRet"] fromXML
ticket <- find (qbName "ticket") parseUUID
companyFile <- find (qbName "strCompanyFileName") parseContent
country <- find (qbName "qbXMLCountry") parseContent
majorVersion <- find (qbName "qbXMLMajorVers") fromXML
minorVersion <- find (qbName "qbXMLMinorVers") fromXML
return $ InitialSendRequestXML ticket
hostData
companyData
preferencesData
companyFile
country
majorVersion
minorVersion
parseReceiveResponseXML :: Parser Callback
parseReceiveResponseXML = matchName (qbName "receiveResponseXML") $ do
ticket <- find (qbName "ticket") parseUUID
resp <- find (qbName "response") $ parseContentWith $ find "QBXMLMsgsRs"
fromXML
return $ ReceiveResponseXML ticket resp
parseCloseConnection :: Parser Callback
parseCloseConnection =
matchName (qbName "closeConnection")
$ CloseConnection
<$> find (qbName "ticket") parseUUID
parseConnectionError :: Parser Callback
parseConnectionError = matchName (qbName "connectionError") $ do
ticket <- find (qbName "ticket") parseUUID
hresult <- find (qbName "hresult") parseContent
message <- find (qbName "message") parseContent
return $ ConnectionError ticket hresult message
parseGetLastError :: Parser Callback
parseGetLastError =
matchName (qbName "getLastError")
$ GetLastError
<$> find (qbName "ticket") parseUUID
| Build an ' Element ' name in the Intuit Developer ' ' .
qbName :: Text -> Name
qbName = withNamespace "/"
| Parse a UUID that is enclosed in braces(@{}@ ) .
parseUUID :: Parser UUID
parseUUID = do
str <- parseContent
case UUID.fromText (dropBrackets str) of
Just val -> return val
Nothing -> throwParsingError $ ContentParsingError "{UUID}" str
where dropBrackets = T.reverse . T.drop 1 . T.reverse . T.drop 1
-- | Valid responses for callbacks.
--
-- TODO: should we break these off into their own type so we can ensure the
ServerVersion callback returns a ServerVersionResp ?
data CallbackResponse
= ServerVersionResp Text
^ Respond with the Server 's version number .
| ClientVersionResp Text
-- ^ Accept the Client's version or issue a warning or error.
-- TODO: Refactor Text into Type w/ valid states(Accept, Warn, Error)
| AuthenticateResp UUID AuthResult (Maybe PostponeMinutes) (Maybe AutorunMinutes)
-- ^ Return a session ticket & the authentication result
| SendRequestXMLResp (Either () Request)
^ Send the given qbXML request
-- TODO: refactor: PauseOrError | MakeRequest Request
| ReceiveResponseXMLResp Integer
-- ^ Send the 0-100 for the percentage complete or a negative number to
-- trigger a getLastError call.
TODO : into InProgress , Complete , or Error types .
| CloseConnectionResp Text
-- ^ Send the status text to show in the WebConnector UI.
| ConnectionErrorResp Text
-- ^ Send "done" to close the connection, or any other text as the path
-- to a company file to open.
-- TODO: Refactor Text -> Done | TryCompanyFile
| GetLastErrorResp GetLastErrorResult
-- ^ Return a message string describing the issue, switch into
interactive mode , or pause for 5 seconds and call
-- again.
deriving (Show)
instance ToXML CallbackResponse where
toXML r = case r of
ServerVersionResp v ->
xelemQ qbNamespace "serverVersionResponse"
$ xelemQ qbNamespace "serverVersionResult" v
ClientVersionResp v ->
xelemQ qbNamespace "clientVersionResponse"
$ xelemQ qbNamespace "clientVersionResult" v
AuthenticateResp ticket result maybePostpone maybeAutorun ->
xelemQ qbNamespace "authenticateResponse"
$ xelemQ qbNamespace "authenticateResult"
$ qbStringArray
$ catMaybes
[ Just $ "{" <> UUID.toText ticket <> "}"
, Just $ showT result
, fmap showT maybePostpone
, fmap showT maybeAutorun
]
SendRequestXMLResp req ->
xelemQ qbNamespace "sendRequestXMLResponse"
$ xelemQ qbNamespace "sendRequestXMLResult"
$ xtext
$ either (const "") buildRequest req
ReceiveResponseXMLResp progress ->
xelemQ qbNamespace "receiveResponseXMLResponse"
$ xelemQ qbNamespace "receiveResponseXMLResult"
$ xtext
$ showT progress
CloseConnectionResp message ->
xelemQ qbNamespace "closeConnectionResponse"
$ xelemQ qbNamespace "closeConnectionResult"
$ xtext message
ConnectionErrorResp message ->
xelemQ qbNamespace "connectionErrorResponse"
$ xelemQ qbNamespace "connectionErrorResult"
$ xtext message
GetLastErrorResp result ->
xelemQ qbNamespace "getLastErrorResponse"
$ xelemQ qbNamespace "getLastErrorResult"
$ toXML result
-- | Render a Text list as a QuickBooks String Array.
qbStringArray :: [Text] -> Xml Elem
qbStringArray = xelems . map (xelemQ qbNamespace "string" . xtext)
-- | Render a showable type as Text.
showT :: Show a => a -> Text
showT = pack . show
-- | The XML Namespace for QuickBooks XML elements.
qbNamespace :: Namespace
qbNamespace = namespace "" "/"
-- Callback Types
-- | The Username passed to the 'Authenticate' callback.
newtype Username
= Username { fromUsername :: Text }
deriving (Show, Eq)
-- | The Password passed to the 'Authenticate' callback.
newtype Password
= Password { fromPassword :: Text }
deriving (Show, Eq)
-- | The result of an Authentication attempt.
data AuthResult
= ValidUser -- ^ The given 'Username' & 'Password' is valid. Connect to
the currently open QuickBooks Company File .
| CompanyFile Text -- ^ The given 'Username' & 'Password' is valid.
Connect to the given QuickBooks Company File .
| InvalidUser -- ^ An invalid 'Username' or 'Password' was supplied.
| Busy -- ^ The Application is currently busy, try again later.
deriving (Eq)
instance Show AuthResult where
show val = case val of
ValidUser -> ""
InvalidUser -> "nvu"
Busy -> "busy"
CompanyFile t -> unpack t
| The number of minutes to postpone an update by .
newtype PostponeMinutes
= PostponeMinutes { fromPostponeMinutes :: Integer }
deriving (Eq)
instance Show PostponeMinutes where
show = show . fromPostponeMinutes
-- | The minimum interval between automatic updates.
newtype AutorunMinutes
= AutorunMinutes { fromAutorunMinutes :: Integer }
deriving (Eq)
instance Show AutorunMinutes where
show = show . fromAutorunMinutes
-- | Possible response values for the getLastError callback.
data GetLastErrorResult
= NoOp
^ Pause for 5 seconds and then call again .
| InteractiveMode
-- ^ Switch to interactive mode and then call getInteractiveURL
| LastError Text
^ Log & show the error in the WebConnector and close the connection .
deriving (Show, Read, Eq)
instance ToXML GetLastErrorResult where
toXML = xtext . \case
NoOp -> "NoOp"
InteractiveMode -> "Interactive mode"
LastError message -> message
| null | https://raw.githubusercontent.com/prikhi/quickbooks-for-communes/f4aefb9de90db04e9c657674627bcc777196d92f/server/src/QuickBooks/WebConnector.hs | haskell | # LANGUAGE OverloadedStrings #
* QWC File Generation
Config File
| Generate the QWC XML configuration file for a QuickBooks User's Web
Connector.
| Nest the generated XML string under a @config@ key.
TODO: if list contains All, just return sum, else nub list and fold
Callbacks
& Preference data.
TODO: Split out into separate record type so we can get named fields?
^ The session ticket
^ HostQuery data for the running version of QuickBooks
^ CompanyQuery data for the company file
^ The Company Filename
^ The Country version of QuickBooks
^ The Major version of the qbXML Processor
^ The session ticket
^ The session ticket
^ The session ticket
^ The error message for the HRESULT.
^ The session ticket
| Valid responses for callbacks.
TODO: should we break these off into their own type so we can ensure the
^ Accept the Client's version or issue a warning or error.
TODO: Refactor Text into Type w/ valid states(Accept, Warn, Error)
^ Return a session ticket & the authentication result
TODO: refactor: PauseOrError | MakeRequest Request
^ Send the 0-100 for the percentage complete or a negative number to
trigger a getLastError call.
^ Send the status text to show in the WebConnector UI.
^ Send "done" to close the connection, or any other text as the path
to a company file to open.
TODO: Refactor Text -> Done | TryCompanyFile
^ Return a message string describing the issue, switch into
again.
| Render a Text list as a QuickBooks String Array.
| Render a showable type as Text.
| The XML Namespace for QuickBooks XML elements.
Callback Types
| The Username passed to the 'Authenticate' callback.
| The Password passed to the 'Authenticate' callback.
| The result of an Authentication attempt.
^ The given 'Username' & 'Password' is valid. Connect to
^ The given 'Username' & 'Password' is valid.
^ An invalid 'Username' or 'Password' was supplied.
^ The Application is currently busy, try again later.
| The minimum interval between automatic updates.
| Possible response values for the getLastError callback.
^ Switch to interactive mode and then call getInteractiveURL | # LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
module QuickBooks.WebConnector
QWCConfig(..)
, AuthFlag(..)
, PersonalDataPreference(..)
, QBType(..)
, Schedule(..)
, SOAPStyle(..)
, UnattendedModePreference(..)
* WebConnector Callbacks & Responses
, Callback(..)
, CallbackResponse(..)
, Username(..)
, Password(..)
, AuthResult(..)
, PostponeMinutes(..)
, AutorunMinutes(..)
, GetLastErrorResult(..)
)
where
import Data.Aeson ( (.=)
, ToJSON(..)
, object
)
import Data.ByteString ( ByteString )
import Data.Maybe ( catMaybes )
import Data.Text ( Text
, pack
, unpack
)
import qualified Data.Text as T
import Data.Text.Encoding ( decodeUtf8 )
import Data.UUID ( UUID )
import qualified Data.UUID as UUID
import Parser ( FromXML(..)
, Parser
, ParsingErrorType(..)
, parseError
, throwParsingError
, matchName
, oneOf
, find
, at
, parseContent
, parseContentWith
, withNamespace
)
import QuickBooks.QBXML ( Request(..)
, buildRequest
, Response(..)
, HostData
, CompanyData
, PreferencesData
)
import Text.XML.Generator ( Xml
, Elem
, Namespace
, xrender
, xelemWithText
, xelem
, xelems
, xelemQ
, xtext
, namespace
)
import Text.XML ( Name )
import XML ( ToXML(..) )
data QWCConfig = QWCConfig
{ qcAppDescription :: Text
, qcAppDisplayName :: Maybe Text
, qcAppID :: Text
, qcAppName :: Text
, qcAppSupport :: Text
, qcAppUniqueName :: Maybe Text
, qcAppURL :: Text
, qcCertURL :: Maybe Text
, qcAuthFlags :: [AuthFlag]
, qcFileID :: UUID
, qcIsReadOnly :: Bool
, qcNotify :: Bool
, qcOwnerID :: UUID
, qcPersonalDataPref :: Maybe PersonalDataPreference
, qcQBType :: QBType
, qcScheduler :: Maybe Schedule
, qcStyle :: Maybe SOAPStyle
, qcUnattendedModePref :: Maybe UnattendedModePreference
, qcUserName :: Text
} deriving (Show)
instance ToXML QWCConfig where
toXML QWCConfig {..} = xelem "QBWCXML" $ xelems $ catMaybes
[ justXText "AppDescription" qcAppDescription
, maybeElem "AppDisplayName" qcAppDisplayName
, justXText "AppID" qcAppID
, justXText "AppName" qcAppName
, justXText "AppSupport" qcAppSupport
, maybeElem "AppUniqueName" qcAppUniqueName
, justXText "AppURL" qcAppURL
, maybeElem "CertURL" qcCertURL
, justXText "AuthFlags" $ showT $ andAuthFlags qcAuthFlags
, justXText "FileID" $ showUUID qcFileID
, justXBool "IsReadOnly" qcIsReadOnly
, justXBool "Notify" qcNotify
, justXText "OwnerID" $ showUUID qcOwnerID
, maybeElemWith "PersonalDataPref" showT qcPersonalDataPref
, justXText "QBType" $ showT qcQBType
, fmap (xelem "Scheduler" . xSchedule) qcScheduler
, maybeElemWith "Style" showT qcStyle
, maybeElemWith "UnattendedModePref" showT qcUnattendedModePref
, justXText "UserName" qcUserName
]
where
justXText name = Just . xelemWithText name
maybeElem name = fmap $ xelemWithText name
maybeElemWith name f = maybeElem name . fmap f
justXBool name bool = justXText name $ if bool then "true" else "false"
showUUID :: UUID -> Text
showUUID uuid = "{" <> UUID.toText uuid <> "}"
instance ToJSON QWCConfig where
toJSON cfg =
let xml :: ByteString
xml = xrender $ toXML cfg
in object ["config" .= decodeUtf8 xml]
data AuthFlag
= AllEditions
| QBSimpleStart
| QBPro
| QBPremier
| QBEnterprise
deriving (Show)
andAuthFlags :: [AuthFlag] -> Integer
andAuthFlags = foldr (\flag acc -> toInt flag + acc) 0
where
toInt = \case
AllEditions -> 1 + 2 + 4 + 8
QBSimpleStart -> 1
QBPro -> 2
QBPremier -> 4
QBEnterprise -> 8
data PersonalDataPreference
= PersonalDataNotNeeded
| PersonalDataOptional
| PersonalDataRequired
instance Show PersonalDataPreference where
show = \case
PersonalDataNotNeeded -> "pdpNotNeeded"
PersonalDataOptional -> "pdpOptional"
PersonalDataRequired -> "pdpRequired"
data QBType
= Financial
| PointOfSale
instance Show QBType where
show = \case
Financial -> "QBFS"
PointOfSale -> "QBPOS"
data Schedule
= EveryMinute Integer
| EverySecond Integer
deriving (Show)
xSchedule :: Schedule -> Xml Elem
xSchedule = \case
EveryMinute i -> xelem "RunEveryNMinutes" . pack $ show i
EverySecond i -> xelem "RunEveryNSeconds" . pack $ show i
data SOAPStyle
= Document
| DocWrapped
| RPC
deriving (Show)
data UnattendedModePreference
= UnattendedModeOptional
| UnattendedModeRequired
instance Show UnattendedModePreference where
show = \case
UnattendedModeOptional -> "umpOptional"
UnattendedModeRequired -> "umpRequired"
data Callback
= ServerVersion
| ClientVersion Text
| Authenticate Username Password
| The first sendRequestXML callback received contains Host , Company ,
| InitialSendRequestXML
^ PreferencesQuery data for the company file
^ The Minor version of the qbXML Processor
| ReceiveResponseXML
^ The parsed response
| CloseConnection
| ConnectionError
^ The @HRESULT@ hex - string thrown by the WebConnector .
| GetLastError
deriving (Show)
instance FromXML Callback where
fromXML = oneOf
[ parseServerVersion
, parseClientVersion
, parseAuthenticate
, parseInitialSendRequestXML
, parseReceiveResponseXML
, parseCloseConnection
, parseConnectionError
, parseGetLastError
, parseError "Unsupported WebConnector Callback"
]
parseServerVersion :: Parser Callback
parseServerVersion = matchName (qbName "serverVersion") $ return ServerVersion
parseClientVersion :: Parser Callback
parseClientVersion =
matchName (qbName "clientVersion")
$ ClientVersion
<$> find (qbName "strVersion") parseContent
parseAuthenticate :: Parser Callback
parseAuthenticate = matchName (qbName "authenticate") $ do
user <- Username <$> find (qbName "strUserName") parseContent
pass <- Password <$> find (qbName "strPassword") parseContent
return $ Authenticate user pass
parseInitialSendRequestXML :: Parser Callback
parseInitialSendRequestXML = matchName (qbName "sendRequestXML") $ do
(hostData, companyData, preferencesData) <-
find (qbName "strHCPResponse")
$ parseContentWith
$ find "QBXMLMsgsRs"
$ (,,)
<$> at ["HostQueryRs", "HostRet"] fromXML
<*> at ["CompanyQueryRs", "CompanyRet"] fromXML
<*> at ["PreferencesQueryRs", "PreferencesRet"] fromXML
ticket <- find (qbName "ticket") parseUUID
companyFile <- find (qbName "strCompanyFileName") parseContent
country <- find (qbName "qbXMLCountry") parseContent
majorVersion <- find (qbName "qbXMLMajorVers") fromXML
minorVersion <- find (qbName "qbXMLMinorVers") fromXML
return $ InitialSendRequestXML ticket
hostData
companyData
preferencesData
companyFile
country
majorVersion
minorVersion
parseReceiveResponseXML :: Parser Callback
parseReceiveResponseXML = matchName (qbName "receiveResponseXML") $ do
ticket <- find (qbName "ticket") parseUUID
resp <- find (qbName "response") $ parseContentWith $ find "QBXMLMsgsRs"
fromXML
return $ ReceiveResponseXML ticket resp
parseCloseConnection :: Parser Callback
parseCloseConnection =
matchName (qbName "closeConnection")
$ CloseConnection
<$> find (qbName "ticket") parseUUID
parseConnectionError :: Parser Callback
parseConnectionError = matchName (qbName "connectionError") $ do
ticket <- find (qbName "ticket") parseUUID
hresult <- find (qbName "hresult") parseContent
message <- find (qbName "message") parseContent
return $ ConnectionError ticket hresult message
parseGetLastError :: Parser Callback
parseGetLastError =
matchName (qbName "getLastError")
$ GetLastError
<$> find (qbName "ticket") parseUUID
| Build an ' Element ' name in the Intuit Developer ' ' .
qbName :: Text -> Name
qbName = withNamespace "/"
| Parse a UUID that is enclosed in braces(@{}@ ) .
parseUUID :: Parser UUID
parseUUID = do
str <- parseContent
case UUID.fromText (dropBrackets str) of
Just val -> return val
Nothing -> throwParsingError $ ContentParsingError "{UUID}" str
where dropBrackets = T.reverse . T.drop 1 . T.reverse . T.drop 1
ServerVersion callback returns a ServerVersionResp ?
data CallbackResponse
= ServerVersionResp Text
^ Respond with the Server 's version number .
| ClientVersionResp Text
| AuthenticateResp UUID AuthResult (Maybe PostponeMinutes) (Maybe AutorunMinutes)
| SendRequestXMLResp (Either () Request)
^ Send the given qbXML request
| ReceiveResponseXMLResp Integer
TODO : into InProgress , Complete , or Error types .
| CloseConnectionResp Text
| ConnectionErrorResp Text
| GetLastErrorResp GetLastErrorResult
interactive mode , or pause for 5 seconds and call
deriving (Show)
instance ToXML CallbackResponse where
toXML r = case r of
ServerVersionResp v ->
xelemQ qbNamespace "serverVersionResponse"
$ xelemQ qbNamespace "serverVersionResult" v
ClientVersionResp v ->
xelemQ qbNamespace "clientVersionResponse"
$ xelemQ qbNamespace "clientVersionResult" v
AuthenticateResp ticket result maybePostpone maybeAutorun ->
xelemQ qbNamespace "authenticateResponse"
$ xelemQ qbNamespace "authenticateResult"
$ qbStringArray
$ catMaybes
[ Just $ "{" <> UUID.toText ticket <> "}"
, Just $ showT result
, fmap showT maybePostpone
, fmap showT maybeAutorun
]
SendRequestXMLResp req ->
xelemQ qbNamespace "sendRequestXMLResponse"
$ xelemQ qbNamespace "sendRequestXMLResult"
$ xtext
$ either (const "") buildRequest req
ReceiveResponseXMLResp progress ->
xelemQ qbNamespace "receiveResponseXMLResponse"
$ xelemQ qbNamespace "receiveResponseXMLResult"
$ xtext
$ showT progress
CloseConnectionResp message ->
xelemQ qbNamespace "closeConnectionResponse"
$ xelemQ qbNamespace "closeConnectionResult"
$ xtext message
ConnectionErrorResp message ->
xelemQ qbNamespace "connectionErrorResponse"
$ xelemQ qbNamespace "connectionErrorResult"
$ xtext message
GetLastErrorResp result ->
xelemQ qbNamespace "getLastErrorResponse"
$ xelemQ qbNamespace "getLastErrorResult"
$ toXML result
qbStringArray :: [Text] -> Xml Elem
qbStringArray = xelems . map (xelemQ qbNamespace "string" . xtext)
showT :: Show a => a -> Text
showT = pack . show
qbNamespace :: Namespace
qbNamespace = namespace "" "/"
newtype Username
= Username { fromUsername :: Text }
deriving (Show, Eq)
newtype Password
= Password { fromPassword :: Text }
deriving (Show, Eq)
data AuthResult
the currently open QuickBooks Company File .
Connect to the given QuickBooks Company File .
deriving (Eq)
instance Show AuthResult where
show val = case val of
ValidUser -> ""
InvalidUser -> "nvu"
Busy -> "busy"
CompanyFile t -> unpack t
| The number of minutes to postpone an update by .
newtype PostponeMinutes
= PostponeMinutes { fromPostponeMinutes :: Integer }
deriving (Eq)
instance Show PostponeMinutes where
show = show . fromPostponeMinutes
newtype AutorunMinutes
= AutorunMinutes { fromAutorunMinutes :: Integer }
deriving (Eq)
instance Show AutorunMinutes where
show = show . fromAutorunMinutes
data GetLastErrorResult
= NoOp
^ Pause for 5 seconds and then call again .
| InteractiveMode
| LastError Text
^ Log & show the error in the WebConnector and close the connection .
deriving (Show, Read, Eq)
instance ToXML GetLastErrorResult where
toXML = xtext . \case
NoOp -> "NoOp"
InteractiveMode -> "Interactive mode"
LastError message -> message
|
493acd5eed633f2f96d656ca75006ee1e2191e48a45c935061b4cd57d1b31196 | clojure-interop/aws-api | AWSXRayAsync.clj | (ns com.amazonaws.services.xray.AWSXRayAsync
"Interface for accessing AWS X-Ray asynchronously. Each asynchronous method will return a Java Future object
overloads which accept an AsyncHandler can be used to receive
notification when an asynchronous operation completes.
Note: Do not directly implement this interface, new methods are added to it regularly. Extend from
AbstractAWSXRayAsync instead.
AWS X-Ray provides APIs for managing debug traces and retrieving service maps and other data created by processing
those traces."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.xray AWSXRayAsync]))
(defn put-telemetry-records-async
"Used by the AWS X-Ray daemon to upload telemetry.
put-telemetry-records-request - `com.amazonaws.services.xray.model.PutTelemetryRecordsRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the PutTelemetryRecords operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.PutTelemetryRecordsResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutTelemetryRecordsRequest put-telemetry-records-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.putTelemetryRecordsAsync put-telemetry-records-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutTelemetryRecordsRequest put-telemetry-records-request]
(-> this (.putTelemetryRecordsAsync put-telemetry-records-request))))
(defn get-service-graph-async
"Retrieves a document that describes services that process incoming requests, and downstream services that they
call as a result. Root services process incoming requests and make calls to downstream services. Root services
are applications that use the AWS X-Ray SDK. Downstream services can be other applications, AWS resources, HTTP
web APIs, or SQL databases.
get-service-graph-request - `com.amazonaws.services.xray.model.GetServiceGraphRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetServiceGraph operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetServiceGraphResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetServiceGraphRequest get-service-graph-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getServiceGraphAsync get-service-graph-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetServiceGraphRequest get-service-graph-request]
(-> this (.getServiceGraphAsync get-service-graph-request))))
(defn get-encryption-config-async
"Retrieves the current encryption configuration for X-Ray data.
get-encryption-config-request - `com.amazonaws.services.xray.model.GetEncryptionConfigRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetEncryptionConfig operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetEncryptionConfigResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetEncryptionConfigRequest get-encryption-config-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getEncryptionConfigAsync get-encryption-config-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetEncryptionConfigRequest get-encryption-config-request]
(-> this (.getEncryptionConfigAsync get-encryption-config-request))))
(defn create-group-async
"Creates a group resource with a name and a filter expression.
create-group-request - `com.amazonaws.services.xray.model.CreateGroupRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateGroup operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.CreateGroupResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.CreateGroupRequest create-group-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createGroupAsync create-group-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.CreateGroupRequest create-group-request]
(-> this (.createGroupAsync create-group-request))))
(defn get-sampling-statistic-summaries-async
"Retrieves information about recent sampling results for all sampling rules.
get-sampling-statistic-summaries-request - `com.amazonaws.services.xray.model.GetSamplingStatisticSummariesRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetSamplingStatisticSummaries operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetSamplingStatisticSummariesResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingStatisticSummariesRequest get-sampling-statistic-summaries-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getSamplingStatisticSummariesAsync get-sampling-statistic-summaries-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingStatisticSummariesRequest get-sampling-statistic-summaries-request]
(-> this (.getSamplingStatisticSummariesAsync get-sampling-statistic-summaries-request))))
(defn get-time-series-service-statistics-async
"Get an aggregation of service statistics defined by a specific time range.
get-time-series-service-statistics-request - `com.amazonaws.services.xray.model.GetTimeSeriesServiceStatisticsRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetTimeSeriesServiceStatistics operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetTimeSeriesServiceStatisticsResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTimeSeriesServiceStatisticsRequest get-time-series-service-statistics-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getTimeSeriesServiceStatisticsAsync get-time-series-service-statistics-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTimeSeriesServiceStatisticsRequest get-time-series-service-statistics-request]
(-> this (.getTimeSeriesServiceStatisticsAsync get-time-series-service-statistics-request))))
(defn get-sampling-rules-async
"Retrieves all sampling rules.
get-sampling-rules-request - `com.amazonaws.services.xray.model.GetSamplingRulesRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetSamplingRules operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetSamplingRulesResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingRulesRequest get-sampling-rules-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getSamplingRulesAsync get-sampling-rules-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingRulesRequest get-sampling-rules-request]
(-> this (.getSamplingRulesAsync get-sampling-rules-request))))
(defn get-sampling-targets-async
"Requests a sampling quota for rules that the service is using to sample requests.
get-sampling-targets-request - `com.amazonaws.services.xray.model.GetSamplingTargetsRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetSamplingTargets operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetSamplingTargetsResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingTargetsRequest get-sampling-targets-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getSamplingTargetsAsync get-sampling-targets-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingTargetsRequest get-sampling-targets-request]
(-> this (.getSamplingTargetsAsync get-sampling-targets-request))))
(defn update-group-async
"Updates a group resource.
update-group-request - `com.amazonaws.services.xray.model.UpdateGroupRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateGroup operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.UpdateGroupResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.UpdateGroupRequest update-group-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateGroupAsync update-group-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.UpdateGroupRequest update-group-request]
(-> this (.updateGroupAsync update-group-request))))
(defn put-encryption-config-async
"Updates the encryption configuration for X-Ray data.
put-encryption-config-request - `com.amazonaws.services.xray.model.PutEncryptionConfigRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the PutEncryptionConfig operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.PutEncryptionConfigResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutEncryptionConfigRequest put-encryption-config-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.putEncryptionConfigAsync put-encryption-config-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutEncryptionConfigRequest put-encryption-config-request]
(-> this (.putEncryptionConfigAsync put-encryption-config-request))))
(defn update-sampling-rule-async
"Modifies a sampling rule's configuration.
update-sampling-rule-request - `com.amazonaws.services.xray.model.UpdateSamplingRuleRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateSamplingRule operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.UpdateSamplingRuleResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.UpdateSamplingRuleRequest update-sampling-rule-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateSamplingRuleAsync update-sampling-rule-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.UpdateSamplingRuleRequest update-sampling-rule-request]
(-> this (.updateSamplingRuleAsync update-sampling-rule-request))))
(defn put-trace-segments-async
"Uploads segment documents to AWS X-Ray. The X-Ray SDK generates segment documents and sends them to the X-Ray
daemon, which uploads them in batches. A segment document can be a completed segment, an in-progress segment, or
an array of subsegments.
Segments must include the following fields. For the full segment document schema, see AWS X-Ray Segment
Documents in the AWS X-Ray Developer Guide.
Required Segment Document Fields
name - The name of the service that handled the request.
id - A 64-bit identifier for the segment, unique among segments in the same trace, in 16 hexadecimal
digits.
trace_id - A unique identifier that connects all segments and subsegments originating from a single
client request.
start_time - Time the segment or subsegment was created, in floating point seconds in epoch time,
accurate to milliseconds. For example, 1480615200.010 or 1.480615200010E9.
end_time - Time the segment or subsegment was closed. For example, 1480615200.090 or
1.480615200090E9. Specify either an end_time or in_progress.
in_progress - Set to true instead of specifying an end_time to record that
a segment has been started, but is not complete. Send an in progress segment when your application receives a
request that will take a long time to serve, to trace the fact that the request was received. When the response
is sent, send the complete segment to overwrite the in-progress segment.
A trace_id consists of three numbers separated by hyphens. For example,
1-58406520-a006649127e371903a2de979. This includes:
Trace ID Format
The version number, i.e. 1.
The time of the original request, in Unix epoch time, in 8 hexadecimal digits. For example, 10:00AM December 2nd,
2016 PST in epoch time is 1480615200 seconds, or 58406520 in hexadecimal.
A 96-bit identifier for the trace, globally unique, in 24 hexadecimal digits.
put-trace-segments-request - `com.amazonaws.services.xray.model.PutTraceSegmentsRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the PutTraceSegments operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.PutTraceSegmentsResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutTraceSegmentsRequest put-trace-segments-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.putTraceSegmentsAsync put-trace-segments-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutTraceSegmentsRequest put-trace-segments-request]
(-> this (.putTraceSegmentsAsync put-trace-segments-request))))
(defn delete-sampling-rule-async
"Deletes a sampling rule.
delete-sampling-rule-request - `com.amazonaws.services.xray.model.DeleteSamplingRuleRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteSamplingRule operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.DeleteSamplingRuleResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.DeleteSamplingRuleRequest delete-sampling-rule-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteSamplingRuleAsync delete-sampling-rule-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.DeleteSamplingRuleRequest delete-sampling-rule-request]
(-> this (.deleteSamplingRuleAsync delete-sampling-rule-request))))
(defn get-group-async
"Retrieves group resource details.
get-group-request - `com.amazonaws.services.xray.model.GetGroupRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetGroup operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetGroupResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetGroupRequest get-group-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getGroupAsync get-group-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetGroupRequest get-group-request]
(-> this (.getGroupAsync get-group-request))))
(defn create-sampling-rule-async
"Creates a rule to control sampling behavior for instrumented applications. Services retrieve rules with
GetSamplingRules, and evaluate each rule in ascending order of priority for each request. If a rule
matches, the service records a trace, borrowing it from the reservoir size. After 10 seconds, the service reports
back to X-Ray with GetSamplingTargets to get updated versions of each in-use rule. The updated rule
contains a trace quota that the service can use instead of borrowing from the reservoir.
create-sampling-rule-request - `com.amazonaws.services.xray.model.CreateSamplingRuleRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateSamplingRule operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.CreateSamplingRuleResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.CreateSamplingRuleRequest create-sampling-rule-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createSamplingRuleAsync create-sampling-rule-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.CreateSamplingRuleRequest create-sampling-rule-request]
(-> this (.createSamplingRuleAsync create-sampling-rule-request))))
(defn get-trace-summaries-async
"Retrieves IDs and metadata for traces available for a specified time frame using an optional filter. To get the
full traces, pass the trace IDs to BatchGetTraces.
A filter expression can target traced requests that hit specific service nodes or edges, have errors, or come
from a known user. For example, the following filter expression targets traces that pass through
api.example.com:
service(\"api.example.com\")
This filter expression finds traces that have an annotation named account with the value
12345:
annotation.account = \"12345\"
For a full list of indexed fields and keywords that you can use in filter expressions, see Using Filter Expressions in
the AWS X-Ray Developer Guide.
get-trace-summaries-request - `com.amazonaws.services.xray.model.GetTraceSummariesRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetTraceSummaries operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetTraceSummariesResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTraceSummariesRequest get-trace-summaries-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getTraceSummariesAsync get-trace-summaries-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTraceSummariesRequest get-trace-summaries-request]
(-> this (.getTraceSummariesAsync get-trace-summaries-request))))
(defn get-groups-async
"Retrieves all active group details.
get-groups-request - `com.amazonaws.services.xray.model.GetGroupsRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetGroups operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetGroupsResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetGroupsRequest get-groups-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getGroupsAsync get-groups-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetGroupsRequest get-groups-request]
(-> this (.getGroupsAsync get-groups-request))))
(defn get-trace-graph-async
"Retrieves a service graph for one or more specific trace IDs.
get-trace-graph-request - `com.amazonaws.services.xray.model.GetTraceGraphRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetTraceGraph operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetTraceGraphResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTraceGraphRequest get-trace-graph-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getTraceGraphAsync get-trace-graph-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTraceGraphRequest get-trace-graph-request]
(-> this (.getTraceGraphAsync get-trace-graph-request))))
(defn delete-group-async
"Deletes a group resource.
delete-group-request - `com.amazonaws.services.xray.model.DeleteGroupRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteGroup operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.DeleteGroupResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.DeleteGroupRequest delete-group-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteGroupAsync delete-group-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.DeleteGroupRequest delete-group-request]
(-> this (.deleteGroupAsync delete-group-request))))
(defn batch-get-traces-async
"Retrieves a list of traces specified by ID. Each trace is a collection of segment documents that originates from
a single request. Use GetTraceSummaries to get a list of trace IDs.
batch-get-traces-request - `com.amazonaws.services.xray.model.BatchGetTracesRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the BatchGetTraces operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.BatchGetTracesResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.BatchGetTracesRequest batch-get-traces-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.batchGetTracesAsync batch-get-traces-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.BatchGetTracesRequest batch-get-traces-request]
(-> this (.batchGetTracesAsync batch-get-traces-request))))
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.xray/src/com/amazonaws/services/xray/AWSXRayAsync.clj | clojure | (ns com.amazonaws.services.xray.AWSXRayAsync
"Interface for accessing AWS X-Ray asynchronously. Each asynchronous method will return a Java Future object
overloads which accept an AsyncHandler can be used to receive
notification when an asynchronous operation completes.
Note: Do not directly implement this interface, new methods are added to it regularly. Extend from
AbstractAWSXRayAsync instead.
AWS X-Ray provides APIs for managing debug traces and retrieving service maps and other data created by processing
those traces."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.xray AWSXRayAsync]))
(defn put-telemetry-records-async
"Used by the AWS X-Ray daemon to upload telemetry.
put-telemetry-records-request - `com.amazonaws.services.xray.model.PutTelemetryRecordsRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the PutTelemetryRecords operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.PutTelemetryRecordsResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutTelemetryRecordsRequest put-telemetry-records-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.putTelemetryRecordsAsync put-telemetry-records-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutTelemetryRecordsRequest put-telemetry-records-request]
(-> this (.putTelemetryRecordsAsync put-telemetry-records-request))))
(defn get-service-graph-async
"Retrieves a document that describes services that process incoming requests, and downstream services that they
call as a result. Root services process incoming requests and make calls to downstream services. Root services
are applications that use the AWS X-Ray SDK. Downstream services can be other applications, AWS resources, HTTP
web APIs, or SQL databases.
get-service-graph-request - `com.amazonaws.services.xray.model.GetServiceGraphRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetServiceGraph operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetServiceGraphResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetServiceGraphRequest get-service-graph-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getServiceGraphAsync get-service-graph-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetServiceGraphRequest get-service-graph-request]
(-> this (.getServiceGraphAsync get-service-graph-request))))
(defn get-encryption-config-async
"Retrieves the current encryption configuration for X-Ray data.
get-encryption-config-request - `com.amazonaws.services.xray.model.GetEncryptionConfigRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetEncryptionConfig operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetEncryptionConfigResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetEncryptionConfigRequest get-encryption-config-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getEncryptionConfigAsync get-encryption-config-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetEncryptionConfigRequest get-encryption-config-request]
(-> this (.getEncryptionConfigAsync get-encryption-config-request))))
(defn create-group-async
"Creates a group resource with a name and a filter expression.
create-group-request - `com.amazonaws.services.xray.model.CreateGroupRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateGroup operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.CreateGroupResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.CreateGroupRequest create-group-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createGroupAsync create-group-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.CreateGroupRequest create-group-request]
(-> this (.createGroupAsync create-group-request))))
(defn get-sampling-statistic-summaries-async
"Retrieves information about recent sampling results for all sampling rules.
get-sampling-statistic-summaries-request - `com.amazonaws.services.xray.model.GetSamplingStatisticSummariesRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetSamplingStatisticSummaries operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetSamplingStatisticSummariesResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingStatisticSummariesRequest get-sampling-statistic-summaries-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getSamplingStatisticSummariesAsync get-sampling-statistic-summaries-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingStatisticSummariesRequest get-sampling-statistic-summaries-request]
(-> this (.getSamplingStatisticSummariesAsync get-sampling-statistic-summaries-request))))
(defn get-time-series-service-statistics-async
"Get an aggregation of service statistics defined by a specific time range.
get-time-series-service-statistics-request - `com.amazonaws.services.xray.model.GetTimeSeriesServiceStatisticsRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetTimeSeriesServiceStatistics operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetTimeSeriesServiceStatisticsResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTimeSeriesServiceStatisticsRequest get-time-series-service-statistics-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getTimeSeriesServiceStatisticsAsync get-time-series-service-statistics-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTimeSeriesServiceStatisticsRequest get-time-series-service-statistics-request]
(-> this (.getTimeSeriesServiceStatisticsAsync get-time-series-service-statistics-request))))
(defn get-sampling-rules-async
"Retrieves all sampling rules.
get-sampling-rules-request - `com.amazonaws.services.xray.model.GetSamplingRulesRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetSamplingRules operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetSamplingRulesResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingRulesRequest get-sampling-rules-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getSamplingRulesAsync get-sampling-rules-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingRulesRequest get-sampling-rules-request]
(-> this (.getSamplingRulesAsync get-sampling-rules-request))))
(defn get-sampling-targets-async
"Requests a sampling quota for rules that the service is using to sample requests.
get-sampling-targets-request - `com.amazonaws.services.xray.model.GetSamplingTargetsRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetSamplingTargets operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetSamplingTargetsResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingTargetsRequest get-sampling-targets-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getSamplingTargetsAsync get-sampling-targets-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetSamplingTargetsRequest get-sampling-targets-request]
(-> this (.getSamplingTargetsAsync get-sampling-targets-request))))
(defn update-group-async
"Updates a group resource.
update-group-request - `com.amazonaws.services.xray.model.UpdateGroupRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateGroup operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.UpdateGroupResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.UpdateGroupRequest update-group-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateGroupAsync update-group-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.UpdateGroupRequest update-group-request]
(-> this (.updateGroupAsync update-group-request))))
(defn put-encryption-config-async
"Updates the encryption configuration for X-Ray data.
put-encryption-config-request - `com.amazonaws.services.xray.model.PutEncryptionConfigRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the PutEncryptionConfig operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.PutEncryptionConfigResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutEncryptionConfigRequest put-encryption-config-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.putEncryptionConfigAsync put-encryption-config-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutEncryptionConfigRequest put-encryption-config-request]
(-> this (.putEncryptionConfigAsync put-encryption-config-request))))
(defn update-sampling-rule-async
"Modifies a sampling rule's configuration.
update-sampling-rule-request - `com.amazonaws.services.xray.model.UpdateSamplingRuleRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateSamplingRule operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.UpdateSamplingRuleResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.UpdateSamplingRuleRequest update-sampling-rule-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateSamplingRuleAsync update-sampling-rule-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.UpdateSamplingRuleRequest update-sampling-rule-request]
(-> this (.updateSamplingRuleAsync update-sampling-rule-request))))
(defn put-trace-segments-async
"Uploads segment documents to AWS X-Ray. The X-Ray SDK generates segment documents and sends them to the X-Ray
daemon, which uploads them in batches. A segment document can be a completed segment, an in-progress segment, or
an array of subsegments.
Segments must include the following fields. For the full segment document schema, see AWS X-Ray Segment
Documents in the AWS X-Ray Developer Guide.
Required Segment Document Fields
name - The name of the service that handled the request.
id - A 64-bit identifier for the segment, unique among segments in the same trace, in 16 hexadecimal
digits.
trace_id - A unique identifier that connects all segments and subsegments originating from a single
client request.
start_time - Time the segment or subsegment was created, in floating point seconds in epoch time,
accurate to milliseconds. For example, 1480615200.010 or 1.480615200010E9.
end_time - Time the segment or subsegment was closed. For example, 1480615200.090 or
1.480615200090E9. Specify either an end_time or in_progress.
in_progress - Set to true instead of specifying an end_time to record that
a segment has been started, but is not complete. Send an in progress segment when your application receives a
request that will take a long time to serve, to trace the fact that the request was received. When the response
is sent, send the complete segment to overwrite the in-progress segment.
A trace_id consists of three numbers separated by hyphens. For example,
1-58406520-a006649127e371903a2de979. This includes:
Trace ID Format
The version number, i.e. 1.
The time of the original request, in Unix epoch time, in 8 hexadecimal digits. For example, 10:00AM December 2nd,
2016 PST in epoch time is 1480615200 seconds, or 58406520 in hexadecimal.
A 96-bit identifier for the trace, globally unique, in 24 hexadecimal digits.
put-trace-segments-request - `com.amazonaws.services.xray.model.PutTraceSegmentsRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the PutTraceSegments operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.PutTraceSegmentsResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutTraceSegmentsRequest put-trace-segments-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.putTraceSegmentsAsync put-trace-segments-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.PutTraceSegmentsRequest put-trace-segments-request]
(-> this (.putTraceSegmentsAsync put-trace-segments-request))))
(defn delete-sampling-rule-async
"Deletes a sampling rule.
delete-sampling-rule-request - `com.amazonaws.services.xray.model.DeleteSamplingRuleRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteSamplingRule operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.DeleteSamplingRuleResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.DeleteSamplingRuleRequest delete-sampling-rule-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteSamplingRuleAsync delete-sampling-rule-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.DeleteSamplingRuleRequest delete-sampling-rule-request]
(-> this (.deleteSamplingRuleAsync delete-sampling-rule-request))))
(defn get-group-async
"Retrieves group resource details.
get-group-request - `com.amazonaws.services.xray.model.GetGroupRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetGroup operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetGroupResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetGroupRequest get-group-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getGroupAsync get-group-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetGroupRequest get-group-request]
(-> this (.getGroupAsync get-group-request))))
(defn create-sampling-rule-async
"Creates a rule to control sampling behavior for instrumented applications. Services retrieve rules with
GetSamplingRules, and evaluate each rule in ascending order of priority for each request. If a rule
matches, the service records a trace, borrowing it from the reservoir size. After 10 seconds, the service reports
back to X-Ray with GetSamplingTargets to get updated versions of each in-use rule. The updated rule
contains a trace quota that the service can use instead of borrowing from the reservoir.
create-sampling-rule-request - `com.amazonaws.services.xray.model.CreateSamplingRuleRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateSamplingRule operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.CreateSamplingRuleResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.CreateSamplingRuleRequest create-sampling-rule-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createSamplingRuleAsync create-sampling-rule-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.CreateSamplingRuleRequest create-sampling-rule-request]
(-> this (.createSamplingRuleAsync create-sampling-rule-request))))
(defn get-trace-summaries-async
"Retrieves IDs and metadata for traces available for a specified time frame using an optional filter. To get the
full traces, pass the trace IDs to BatchGetTraces.
A filter expression can target traced requests that hit specific service nodes or edges, have errors, or come
from a known user. For example, the following filter expression targets traces that pass through
api.example.com:
service(\"api.example.com\")
This filter expression finds traces that have an annotation named account with the value
12345:
annotation.account = \"12345\"
For a full list of indexed fields and keywords that you can use in filter expressions, see Using Filter Expressions in
the AWS X-Ray Developer Guide.
get-trace-summaries-request - `com.amazonaws.services.xray.model.GetTraceSummariesRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetTraceSummaries operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetTraceSummariesResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTraceSummariesRequest get-trace-summaries-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getTraceSummariesAsync get-trace-summaries-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTraceSummariesRequest get-trace-summaries-request]
(-> this (.getTraceSummariesAsync get-trace-summaries-request))))
(defn get-groups-async
"Retrieves all active group details.
get-groups-request - `com.amazonaws.services.xray.model.GetGroupsRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetGroups operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetGroupsResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetGroupsRequest get-groups-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getGroupsAsync get-groups-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetGroupsRequest get-groups-request]
(-> this (.getGroupsAsync get-groups-request))))
(defn get-trace-graph-async
"Retrieves a service graph for one or more specific trace IDs.
get-trace-graph-request - `com.amazonaws.services.xray.model.GetTraceGraphRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetTraceGraph operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.GetTraceGraphResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTraceGraphRequest get-trace-graph-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getTraceGraphAsync get-trace-graph-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.GetTraceGraphRequest get-trace-graph-request]
(-> this (.getTraceGraphAsync get-trace-graph-request))))
(defn delete-group-async
"Deletes a group resource.
delete-group-request - `com.amazonaws.services.xray.model.DeleteGroupRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteGroup operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.DeleteGroupResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.DeleteGroupRequest delete-group-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteGroupAsync delete-group-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.DeleteGroupRequest delete-group-request]
(-> this (.deleteGroupAsync delete-group-request))))
(defn batch-get-traces-async
"Retrieves a list of traces specified by ID. Each trace is a collection of segment documents that originates from
a single request. Use GetTraceSummaries to get a list of trace IDs.
batch-get-traces-request - `com.amazonaws.services.xray.model.BatchGetTracesRequest`
async-handler - Asynchronous callback handler for events in the lifecycle of the request. Users can provide an implementation of the callback methods in this interface to receive notification of successful or unsuccessful completion of the operation. - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the BatchGetTraces operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.xray.model.BatchGetTracesResult>`"
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.BatchGetTracesRequest batch-get-traces-request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.batchGetTracesAsync batch-get-traces-request async-handler)))
(^java.util.concurrent.Future [^AWSXRayAsync this ^com.amazonaws.services.xray.model.BatchGetTracesRequest batch-get-traces-request]
(-> this (.batchGetTracesAsync batch-get-traces-request))))
|
|
5ec72eaab848d529c74b49008e0dae488bb637ae9705a6bc8d6b68ffef729ae0 | meamy/feynman | Parallel.hs | module Feynman.Synthesis.Reversible.Parallel where
import Feynman.Core
import Feynman.Algebra.Base
import Feynman.Algebra.Linear
import Feynman.Algebra.Matroid
import Feynman.Synthesis.Phase
import Feynman.Synthesis.Reversible
import Data.List (partition, intersect)
import Data.Map.Strict (Map, (!))
import qualified Data.Map.Strict as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Control.Monad.State.Strict
import Control.Monad.Writer.Lazy
import Debug.Trace (trace)
The Matroid from the t - par paper [ AMM2014 ]
Note that this is kind of a nasty hack due to the way
were programmed . TODO : fix Matroid partitioning so that we do n't
-- need to carry all the context information necessary for defining
-- independence with each element
AMM t m n gives the independence instance where a set of phase terms
-- T is independent if and only if m - rank(T) <= n - |T|
data AMM = AMM Phase Int Int
instance Eq AMM where
(AMM t _ _) == (AMM t' _ _) = t == t'
instance Ord AMM where
(AMM t _ _) <= (AMM t' _ _) = t <= t'
instance Show AMM where
show (AMM t _ _) = show t
instance Matroid AMM where
independent s
| Set.null s = True
| otherwise =
let (AMM _ m n) = head $ Set.toList s
(vecs, exps) = unzip . map (\(AMM t _ _) -> t) $ Set.toList s
toTorNotToT = all ((8 ==) . order) exps || all ((8 /=) . order) exps
extensible = m - rank (fromList vecs) <= n - (length vecs)
in
toTorNotToT && extensible
synthPartition :: [Phase] -> ([Primitive], LinearTrans) -> ([Primitive], LinearTrans)
synthPartition xs (circ, input) =
let (ids, ivecs) = unzip $ Map.toList input
(vecs, exps) = unzip $ xs
inp = fromList ivecs
targ = resizeMat (m inp) (n inp) . (flip fillFrom $ inp) . fromList $ vecs
output = Map.fromList (zip ids $ toList targ)
g (n,i) = synthesizePhase (ids!!i) n
perm = linearSynth input output
phase = concatMap g (zip exps [0..])
in
(circ++perm++phase, output)
-- Strictly lazy
tparLazy :: Synthesizer
tparLazy input output [] may = (linearSynth input output, may)
tparLazy input output must may = (circ ++ linearSynth input' output, may)
where terms = [AMM x (rank . fromList $ Map.elems input) (length input) | x <- must]
partitions = map (map (\(AMM t _ _) -> t) . Set.toList) . partitionAll $ terms
(circ, input') = foldr synthPartition ([], input) partitions
-- Partitions eagerly, but applies partitions lazily
tparAMM :: Synthesizer
tparAMM input output must may = (circ ++ linearSynth input' output, concat may')
where terms = [AMM x (rank . fromList $ Map.elems input) (length input) | x <- must++may]
partitions = map (map (\(AMM t _ _) -> t) . Set.toList) . partitionAll $ terms
(must', may') = partition isMust partitions
(circ, input') = foldr synthPartition ([], input) must'
isMust part = (intersect must part) /= []
tparMaster input output must may = tparAMM input output must' may'
where (must', may') = (filter f must, filter f may)
f (bv, i) = order i /= 1 && wt bv /= 0
| null | https://raw.githubusercontent.com/meamy/feynman/6487c3e90b3c3a56e3b309436663d8bf4cbf4422/src/Feynman/Synthesis/Reversible/Parallel.hs | haskell | need to carry all the context information necessary for defining
independence with each element
T is independent if and only if m - rank(T) <= n - |T|
Strictly lazy
Partitions eagerly, but applies partitions lazily | module Feynman.Synthesis.Reversible.Parallel where
import Feynman.Core
import Feynman.Algebra.Base
import Feynman.Algebra.Linear
import Feynman.Algebra.Matroid
import Feynman.Synthesis.Phase
import Feynman.Synthesis.Reversible
import Data.List (partition, intersect)
import Data.Map.Strict (Map, (!))
import qualified Data.Map.Strict as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Control.Monad.State.Strict
import Control.Monad.Writer.Lazy
import Debug.Trace (trace)
The Matroid from the t - par paper [ AMM2014 ]
Note that this is kind of a nasty hack due to the way
were programmed . TODO : fix Matroid partitioning so that we do n't
AMM t m n gives the independence instance where a set of phase terms
data AMM = AMM Phase Int Int
instance Eq AMM where
(AMM t _ _) == (AMM t' _ _) = t == t'
instance Ord AMM where
(AMM t _ _) <= (AMM t' _ _) = t <= t'
instance Show AMM where
show (AMM t _ _) = show t
instance Matroid AMM where
independent s
| Set.null s = True
| otherwise =
let (AMM _ m n) = head $ Set.toList s
(vecs, exps) = unzip . map (\(AMM t _ _) -> t) $ Set.toList s
toTorNotToT = all ((8 ==) . order) exps || all ((8 /=) . order) exps
extensible = m - rank (fromList vecs) <= n - (length vecs)
in
toTorNotToT && extensible
synthPartition :: [Phase] -> ([Primitive], LinearTrans) -> ([Primitive], LinearTrans)
synthPartition xs (circ, input) =
let (ids, ivecs) = unzip $ Map.toList input
(vecs, exps) = unzip $ xs
inp = fromList ivecs
targ = resizeMat (m inp) (n inp) . (flip fillFrom $ inp) . fromList $ vecs
output = Map.fromList (zip ids $ toList targ)
g (n,i) = synthesizePhase (ids!!i) n
perm = linearSynth input output
phase = concatMap g (zip exps [0..])
in
(circ++perm++phase, output)
tparLazy :: Synthesizer
tparLazy input output [] may = (linearSynth input output, may)
tparLazy input output must may = (circ ++ linearSynth input' output, may)
where terms = [AMM x (rank . fromList $ Map.elems input) (length input) | x <- must]
partitions = map (map (\(AMM t _ _) -> t) . Set.toList) . partitionAll $ terms
(circ, input') = foldr synthPartition ([], input) partitions
tparAMM :: Synthesizer
tparAMM input output must may = (circ ++ linearSynth input' output, concat may')
where terms = [AMM x (rank . fromList $ Map.elems input) (length input) | x <- must++may]
partitions = map (map (\(AMM t _ _) -> t) . Set.toList) . partitionAll $ terms
(must', may') = partition isMust partitions
(circ, input') = foldr synthPartition ([], input) must'
isMust part = (intersect must part) /= []
tparMaster input output must may = tparAMM input output must' may'
where (must', may') = (filter f must, filter f may)
f (bv, i) = order i /= 1 && wt bv /= 0
|
4a0d4ad5f06a67d5a8673e91c2114663af1e677571cff195ae775fe423da572a | fpco/schoolofhaskell | Annotation.hs | | This module provides utilities for rendering the ' ' type of the
API . ' ' gives extra structure to textual information provided by
-- the backend, by adding nested annotations atop the text.
--
In the current School of Haskell code , ' ' is used for source
-- errors and type info. This allows things like links to docs for
-- identifiers, and better styling for source errors.
--
-- This module also provides utilities for getting highlight spans from
code , via Ace . This allows the display of annotated info to highlight
the involved expressions / types , and pass these ' ClassSpans ' into
-- 'renderAnn'.
module View.Annotation
( -- * Annotations
renderAnn
, annText
-- * Rendering IdInfo links
, renderCodeAnn
-- * Highlighting Code
, getHighlightSpans
, getExpHighlightSpans
, getTypeHighlightSpans
-- ** Utilities
, NoNewlines
, unNoNewlines
, mkNoNewlines
, mayMkNoNewlines
) where
import qualified Data.Text as T
import GHCJS.Foreign
import GHCJS.Marshal
import GHCJS.Types
import Import hiding (ix, to)
import Model (switchTab, navigateDoc)
--------------------------------------------------------------------------------
-- Annotations
| This renders an ' ' type , given a function for rendering the
-- annotations.
--
-- This rendering function takes the annotation, and is given the
-- 'React' rendering of the nested content. This allows it to add
parent DOM nodes / attributes , in order to apply the effect of the
-- annotation.
--
It also takes a ' ClassSpans ' value , which is used at the leaf
-- level, to slice up the spans of text, adding additional class
-- annotations. This is used to add the results of code highlighting
-- to annotated info.
renderAnn
:: forall a.
ClassSpans
-> Ann a
-> (forall b. a -> React b -> React b)
-> React ()
renderAnn spans0 x0 f = void $ go 0 spans0 x0
where
go :: Int -> ClassSpans -> Ann a -> React (Int, ClassSpans)
go ix spans (Ann ann inner) = f ann $ go ix spans inner
go ix spans (AnnGroup []) = return (ix, spans)
go ix spans (AnnGroup (x:xs)) = do
(ix', spans') <- go ix spans x
go ix' spans' (AnnGroup xs)
go ix spans (AnnLeaf txt) = do
forM_ (sliceSpans ix txt spans) $ \(chunk, mclass) -> span_ $ do
forM_ mclass class_
text chunk
return (end, dropWhile (\(_, end', _) -> end' <= end) spans)
where
end = ix + T.length txt
annText :: Ann a -> Text
annText (Ann _ x) = annText x
annText (AnnGroup xs) = T.concat (map annText xs)
annText (AnnLeaf x) = x
--------------------------------------------------------------------------------
-- Rendering IdInfo links
-- | Renders a 'CodeAnn'. This function is intended to be passed in
-- to 'renderAnn', or used to implement a function which is passed
-- into it.
renderCodeAnn :: CodeAnn -> React a -> React a
renderCodeAnn (CodeIdInfo info) inner = span_ $ do
class_ "docs-link"
title_ (displayIdInfo info)
onClick $ \_ state -> do
navigateDoc state (Just info)
switchTab state DocsTab
inner
--------------------------------------------------------------------------------
-- Highlighting code
type ClassSpans = [(Int, Int, Text)]
-- NOTE: prefixing for expressions doesn't seem to make a difference
-- for the current highlighter, but it might in the future.
-- | Get the highlight spans of an expression.
getExpHighlightSpans :: NoNewlines -> IO ClassSpans
getExpHighlightSpans = getHighlightSpansWithPrefix $ mkNoNewlines "x = "
-- | Get the highlight spans of a type.
getTypeHighlightSpans :: NoNewlines -> IO ClassSpans
getTypeHighlightSpans = getHighlightSpansWithPrefix $ mkNoNewlines "x :: "
getHighlightSpansWithPrefix :: NoNewlines -> NoNewlines -> IO ClassSpans
getHighlightSpansWithPrefix prefix codeLine = do
let offset = T.length (unNoNewlines prefix)
spans <- getHighlightSpans "ace/mode/haskell" (prefix <> codeLine)
return $
dropWhile (\(_, to, _) -> to <= 0) $
map (\(fr, to, x) -> (fr - offset, to - offset, x)) spans
getHighlightSpans :: Text -> NoNewlines -> IO ClassSpans
getHighlightSpans mode (NoNewlines codeLine) =
highlightCodeHTML (toJSString mode) (toJSString codeLine) >>=
indexArray 0 >>=
fromJSRef >>=
maybe (fail "Failed to access highlighted line html") return >>=
divFromInnerHTML >>=
spanContainerToSpans >>=
fromJSRef >>=
maybe (fail "Failed to marshal highlight spans") return
foreign import javascript "function() { var node = document.createElement('div'); node.innerHTML = $1; return node; }()"
divFromInnerHTML :: JSString -> IO (JSRef Element)
foreign import javascript "highlightCodeHTML"
highlightCodeHTML :: JSString -> JSString -> IO (JSArray JSString)
foreign import javascript "spanContainerToSpans"
spanContainerToSpans :: JSRef Element -> IO (JSRef ClassSpans)
--------------------------------------------------------------------------------
: utility for code highlighting
-- TODO: should probably use source spans / allow new lines instead
-- of having this newtype...
-- | This newtype enforces the invariant that the stored 'Text' doesn't
have the character \"\\n\ " .
newtype NoNewlines = NoNewlines Text
deriving (Eq, Show, Monoid)
unNoNewlines :: NoNewlines -> Text
unNoNewlines (NoNewlines x) = x
mkNoNewlines :: Text -> NoNewlines
mkNoNewlines = fromMaybe (error "mkNoNewlines failed") . mayMkNoNewlines
mayMkNoNewlines :: Text -> Maybe NoNewlines
mayMkNoNewlines x | "\n" `T.isInfixOf` x = Nothing
mayMkNoNewlines x = Just (NoNewlines x)
| null | https://raw.githubusercontent.com/fpco/schoolofhaskell/171454d255f57bb9ab82974625501e964c8c9b96/soh-client/src/View/Annotation.hs | haskell | the backend, by adding nested annotations atop the text.
errors and type info. This allows things like links to docs for
identifiers, and better styling for source errors.
This module also provides utilities for getting highlight spans from
'renderAnn'.
* Annotations
* Rendering IdInfo links
* Highlighting Code
** Utilities
------------------------------------------------------------------------------
Annotations
annotations.
This rendering function takes the annotation, and is given the
'React' rendering of the nested content. This allows it to add
annotation.
level, to slice up the spans of text, adding additional class
annotations. This is used to add the results of code highlighting
to annotated info.
------------------------------------------------------------------------------
Rendering IdInfo links
| Renders a 'CodeAnn'. This function is intended to be passed in
to 'renderAnn', or used to implement a function which is passed
into it.
------------------------------------------------------------------------------
Highlighting code
NOTE: prefixing for expressions doesn't seem to make a difference
for the current highlighter, but it might in the future.
| Get the highlight spans of an expression.
| Get the highlight spans of a type.
------------------------------------------------------------------------------
TODO: should probably use source spans / allow new lines instead
of having this newtype...
| This newtype enforces the invariant that the stored 'Text' doesn't | | This module provides utilities for rendering the ' ' type of the
API . ' ' gives extra structure to textual information provided by
In the current School of Haskell code , ' ' is used for source
code , via Ace . This allows the display of annotated info to highlight
the involved expressions / types , and pass these ' ClassSpans ' into
module View.Annotation
renderAnn
, annText
, renderCodeAnn
, getHighlightSpans
, getExpHighlightSpans
, getTypeHighlightSpans
, NoNewlines
, unNoNewlines
, mkNoNewlines
, mayMkNoNewlines
) where
import qualified Data.Text as T
import GHCJS.Foreign
import GHCJS.Marshal
import GHCJS.Types
import Import hiding (ix, to)
import Model (switchTab, navigateDoc)
| This renders an ' ' type , given a function for rendering the
parent DOM nodes / attributes , in order to apply the effect of the
It also takes a ' ClassSpans ' value , which is used at the leaf
renderAnn
:: forall a.
ClassSpans
-> Ann a
-> (forall b. a -> React b -> React b)
-> React ()
renderAnn spans0 x0 f = void $ go 0 spans0 x0
where
go :: Int -> ClassSpans -> Ann a -> React (Int, ClassSpans)
go ix spans (Ann ann inner) = f ann $ go ix spans inner
go ix spans (AnnGroup []) = return (ix, spans)
go ix spans (AnnGroup (x:xs)) = do
(ix', spans') <- go ix spans x
go ix' spans' (AnnGroup xs)
go ix spans (AnnLeaf txt) = do
forM_ (sliceSpans ix txt spans) $ \(chunk, mclass) -> span_ $ do
forM_ mclass class_
text chunk
return (end, dropWhile (\(_, end', _) -> end' <= end) spans)
where
end = ix + T.length txt
annText :: Ann a -> Text
annText (Ann _ x) = annText x
annText (AnnGroup xs) = T.concat (map annText xs)
annText (AnnLeaf x) = x
renderCodeAnn :: CodeAnn -> React a -> React a
renderCodeAnn (CodeIdInfo info) inner = span_ $ do
class_ "docs-link"
title_ (displayIdInfo info)
onClick $ \_ state -> do
navigateDoc state (Just info)
switchTab state DocsTab
inner
type ClassSpans = [(Int, Int, Text)]
getExpHighlightSpans :: NoNewlines -> IO ClassSpans
getExpHighlightSpans = getHighlightSpansWithPrefix $ mkNoNewlines "x = "
getTypeHighlightSpans :: NoNewlines -> IO ClassSpans
getTypeHighlightSpans = getHighlightSpansWithPrefix $ mkNoNewlines "x :: "
getHighlightSpansWithPrefix :: NoNewlines -> NoNewlines -> IO ClassSpans
getHighlightSpansWithPrefix prefix codeLine = do
let offset = T.length (unNoNewlines prefix)
spans <- getHighlightSpans "ace/mode/haskell" (prefix <> codeLine)
return $
dropWhile (\(_, to, _) -> to <= 0) $
map (\(fr, to, x) -> (fr - offset, to - offset, x)) spans
getHighlightSpans :: Text -> NoNewlines -> IO ClassSpans
getHighlightSpans mode (NoNewlines codeLine) =
highlightCodeHTML (toJSString mode) (toJSString codeLine) >>=
indexArray 0 >>=
fromJSRef >>=
maybe (fail "Failed to access highlighted line html") return >>=
divFromInnerHTML >>=
spanContainerToSpans >>=
fromJSRef >>=
maybe (fail "Failed to marshal highlight spans") return
foreign import javascript "function() { var node = document.createElement('div'); node.innerHTML = $1; return node; }()"
divFromInnerHTML :: JSString -> IO (JSRef Element)
foreign import javascript "highlightCodeHTML"
highlightCodeHTML :: JSString -> JSString -> IO (JSArray JSString)
foreign import javascript "spanContainerToSpans"
spanContainerToSpans :: JSRef Element -> IO (JSRef ClassSpans)
: utility for code highlighting
have the character \"\\n\ " .
newtype NoNewlines = NoNewlines Text
deriving (Eq, Show, Monoid)
unNoNewlines :: NoNewlines -> Text
unNoNewlines (NoNewlines x) = x
mkNoNewlines :: Text -> NoNewlines
mkNoNewlines = fromMaybe (error "mkNoNewlines failed") . mayMkNoNewlines
mayMkNoNewlines :: Text -> Maybe NoNewlines
mayMkNoNewlines x | "\n" `T.isInfixOf` x = Nothing
mayMkNoNewlines x = Just (NoNewlines x)
|
dc65d2474933a0e9921b05a9fcfa448943ecdfee1a2bad26ce3b48d0e4e0dd8a | bsansouci/bsb-native | reg.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
open Cmm
module Raw_name = struct
type t =
| Anon
| R
| Ident of Ident.t
let create_from_ident ident = Ident ident
let to_string t =
match t with
| Anon -> None
| R -> Some "R"
| Ident ident ->
let name = Ident.name ident in
if String.length name <= 0 then None else Some name
end
type t =
{ mutable raw_name: Raw_name.t;
stamp: int;
typ: Cmm.machtype_component;
mutable loc: location;
mutable spill: bool;
mutable part: int option;
mutable interf: t list;
mutable prefer: (t * int) list;
mutable degree: int;
mutable spill_cost: int;
mutable visited: bool }
and location =
Unknown
| Reg of int
| Stack of stack_location
and stack_location =
Local of int
| Incoming of int
| Outgoing of int
type reg = t
let dummy =
{ raw_name = Raw_name.Anon; stamp = 0; typ = Int; loc = Unknown;
spill = false; interf = []; prefer = []; degree = 0; spill_cost = 0;
visited = false; part = None;
}
let currstamp = ref 0
let reg_list = ref([] : t list)
let create ty =
let r = { raw_name = Raw_name.Anon; stamp = !currstamp; typ = ty;
loc = Unknown; spill = false; interf = []; prefer = []; degree = 0;
spill_cost = 0; visited = false; part = None; } in
reg_list := r :: !reg_list;
incr currstamp;
r
let createv tyv =
let n = Array.length tyv in
let rv = Array.make n dummy in
for i = 0 to n-1 do rv.(i) <- create tyv.(i) done;
rv
let createv_like rv =
let n = Array.length rv in
let rv' = Array.make n dummy in
for i = 0 to n-1 do rv'.(i) <- create rv.(i).typ done;
rv'
let clone r =
let nr = create r.typ in
nr.raw_name <- r.raw_name;
nr
let at_location ty loc =
let r = { raw_name = Raw_name.R; stamp = !currstamp; typ = ty; loc;
spill = false; interf = []; prefer = []; degree = 0;
spill_cost = 0; visited = false; part = None; } in
incr currstamp;
r
let anonymous t =
match Raw_name.to_string t.raw_name with
| None -> true
| Some _raw_name -> false
let name t =
match Raw_name.to_string t.raw_name with
| None -> ""
| Some raw_name ->
let with_spilled =
if t.spill then
"spilled-" ^ raw_name
else
raw_name
in
match t.part with
| None -> with_spilled
| Some part -> with_spilled ^ "#" ^ string_of_int part
let first_virtual_reg_stamp = ref (-1)
let reset() =
When reset ( ) is called for the first time , the current stamp reflects
all hard pseudo - registers that have been allocated by Proc , so
remember it and use it as the base stamp for allocating
soft pseudo - registers
all hard pseudo-registers that have been allocated by Proc, so
remember it and use it as the base stamp for allocating
soft pseudo-registers *)
if !first_virtual_reg_stamp = -1 then first_virtual_reg_stamp := !currstamp;
currstamp := !first_virtual_reg_stamp;
reg_list := []
let all_registers() = !reg_list
let num_registers() = !currstamp
let reinit_reg r =
r.loc <- Unknown;
r.interf <- [];
r.prefer <- [];
r.degree <- 0;
(* Preserve the very high spill costs introduced by the reloading pass *)
if r.spill_cost >= 100000
then r.spill_cost <- 100000
else r.spill_cost <- 0
let reinit() =
List.iter reinit_reg !reg_list
module RegOrder =
struct
type t = reg
let compare r1 r2 = r1.stamp - r2.stamp
end
module Set = Set.Make(RegOrder)
module Map = Map.Make(RegOrder)
let add_set_array s v =
match Array.length v with
0 -> s
| 1 -> Set.add v.(0) s
| n -> let rec add_all i =
if i >= n then s else Set.add v.(i) (add_all(i+1))
in add_all 0
let diff_set_array s v =
match Array.length v with
0 -> s
| 1 -> Set.remove v.(0) s
| n -> let rec remove_all i =
if i >= n then s else Set.remove v.(i) (remove_all(i+1))
in remove_all 0
let inter_set_array s v =
match Array.length v with
0 -> Set.empty
| 1 -> if Set.mem v.(0) s
then Set.add v.(0) Set.empty
else Set.empty
| n -> let rec inter_all i =
if i >= n then Set.empty
else if Set.mem v.(i) s then Set.add v.(i) (inter_all(i+1))
else inter_all(i+1)
in inter_all 0
let disjoint_set_array s v =
match Array.length v with
0 -> true
| 1 -> not (Set.mem v.(0) s)
| n -> let rec disjoint_all i =
if i >= n then true
else if Set.mem v.(i) s then false
else disjoint_all (i+1)
in disjoint_all 0
let set_of_array v =
match Array.length v with
0 -> Set.empty
| 1 -> Set.add v.(0) Set.empty
| n -> let rec add_all i =
if i >= n then Set.empty else Set.add v.(i) (add_all(i+1))
in add_all 0
| null | https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/asmcomp/reg.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
Preserve the very high spill costs introduced by the reloading pass | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
open Cmm
module Raw_name = struct
type t =
| Anon
| R
| Ident of Ident.t
let create_from_ident ident = Ident ident
let to_string t =
match t with
| Anon -> None
| R -> Some "R"
| Ident ident ->
let name = Ident.name ident in
if String.length name <= 0 then None else Some name
end
type t =
{ mutable raw_name: Raw_name.t;
stamp: int;
typ: Cmm.machtype_component;
mutable loc: location;
mutable spill: bool;
mutable part: int option;
mutable interf: t list;
mutable prefer: (t * int) list;
mutable degree: int;
mutable spill_cost: int;
mutable visited: bool }
and location =
Unknown
| Reg of int
| Stack of stack_location
and stack_location =
Local of int
| Incoming of int
| Outgoing of int
type reg = t
let dummy =
{ raw_name = Raw_name.Anon; stamp = 0; typ = Int; loc = Unknown;
spill = false; interf = []; prefer = []; degree = 0; spill_cost = 0;
visited = false; part = None;
}
let currstamp = ref 0
let reg_list = ref([] : t list)
let create ty =
let r = { raw_name = Raw_name.Anon; stamp = !currstamp; typ = ty;
loc = Unknown; spill = false; interf = []; prefer = []; degree = 0;
spill_cost = 0; visited = false; part = None; } in
reg_list := r :: !reg_list;
incr currstamp;
r
let createv tyv =
let n = Array.length tyv in
let rv = Array.make n dummy in
for i = 0 to n-1 do rv.(i) <- create tyv.(i) done;
rv
let createv_like rv =
let n = Array.length rv in
let rv' = Array.make n dummy in
for i = 0 to n-1 do rv'.(i) <- create rv.(i).typ done;
rv'
let clone r =
let nr = create r.typ in
nr.raw_name <- r.raw_name;
nr
let at_location ty loc =
let r = { raw_name = Raw_name.R; stamp = !currstamp; typ = ty; loc;
spill = false; interf = []; prefer = []; degree = 0;
spill_cost = 0; visited = false; part = None; } in
incr currstamp;
r
let anonymous t =
match Raw_name.to_string t.raw_name with
| None -> true
| Some _raw_name -> false
let name t =
match Raw_name.to_string t.raw_name with
| None -> ""
| Some raw_name ->
let with_spilled =
if t.spill then
"spilled-" ^ raw_name
else
raw_name
in
match t.part with
| None -> with_spilled
| Some part -> with_spilled ^ "#" ^ string_of_int part
let first_virtual_reg_stamp = ref (-1)
let reset() =
When reset ( ) is called for the first time , the current stamp reflects
all hard pseudo - registers that have been allocated by Proc , so
remember it and use it as the base stamp for allocating
soft pseudo - registers
all hard pseudo-registers that have been allocated by Proc, so
remember it and use it as the base stamp for allocating
soft pseudo-registers *)
if !first_virtual_reg_stamp = -1 then first_virtual_reg_stamp := !currstamp;
currstamp := !first_virtual_reg_stamp;
reg_list := []
let all_registers() = !reg_list
let num_registers() = !currstamp
let reinit_reg r =
r.loc <- Unknown;
r.interf <- [];
r.prefer <- [];
r.degree <- 0;
if r.spill_cost >= 100000
then r.spill_cost <- 100000
else r.spill_cost <- 0
let reinit() =
List.iter reinit_reg !reg_list
module RegOrder =
struct
type t = reg
let compare r1 r2 = r1.stamp - r2.stamp
end
module Set = Set.Make(RegOrder)
module Map = Map.Make(RegOrder)
let add_set_array s v =
match Array.length v with
0 -> s
| 1 -> Set.add v.(0) s
| n -> let rec add_all i =
if i >= n then s else Set.add v.(i) (add_all(i+1))
in add_all 0
let diff_set_array s v =
match Array.length v with
0 -> s
| 1 -> Set.remove v.(0) s
| n -> let rec remove_all i =
if i >= n then s else Set.remove v.(i) (remove_all(i+1))
in remove_all 0
let inter_set_array s v =
match Array.length v with
0 -> Set.empty
| 1 -> if Set.mem v.(0) s
then Set.add v.(0) Set.empty
else Set.empty
| n -> let rec inter_all i =
if i >= n then Set.empty
else if Set.mem v.(i) s then Set.add v.(i) (inter_all(i+1))
else inter_all(i+1)
in inter_all 0
let disjoint_set_array s v =
match Array.length v with
0 -> true
| 1 -> not (Set.mem v.(0) s)
| n -> let rec disjoint_all i =
if i >= n then true
else if Set.mem v.(i) s then false
else disjoint_all (i+1)
in disjoint_all 0
let set_of_array v =
match Array.length v with
0 -> Set.empty
| 1 -> Set.add v.(0) Set.empty
| n -> let rec add_all i =
if i >= n then Set.empty else Set.add v.(i) (add_all(i+1))
in add_all 0
|
c6d6fdd837a63666f678903cedd7dda8254036a1560400c9d1c6a8951626238c | transient-haskell/transient | teststreamsocket.hs | test.hs{-# LANGUAGE RecordWildCards, ScopedTypeVariables #-}
module Main where
import Network
import qualified Network.Socket as NS hiding (send, sendTo, recv, recvFrom)
import Network.Socket.ByteString
import qualified Network.BSD as BSD
import System.IO hiding (hPutBufNonBlocking)
import Control.Concurrent
import Control.Monad
import Control.Exception
import Control.Monad.IO.Class
import qualified Data.ByteString.Char8 as BS
import Foreign.Ptr
import Foreign.Storable
import Data.ByteString.Internal
import Foreign.ForeignPtr.Safe
main = do
let host= "localhost"; port= 2000
forkIO $ listen' $ PortNumber port
proto <- BSD.getProtocolNumber "tcp"
bracketOnError
(NS.socket NS.AF_INET NS.Stream proto)
(sClose) -- only done if there's an error
(\sock -> do
NS.setSocketOption sock NS.RecvBuffer 3000
he <- BSD.getHostByName "localhost"
NS.connect sock (NS.SockAddrInet port (BSD.hostAddress he))
loop sock 0
getChar)
where
loop sock x = do
let msg = BS.pack $ show x ++ "\n"
let l = BS.length msg
n <- send sock msg
when (n < l) $ do
print $ "CONGESTION "++ show (l-n)
sendAll sock $ BS.drop n msg
loop sock (x +1)
listen' port = do
sock <- listenOn port
(h,host,port1) <- accept sock
hSetBuffering h $ BlockBuffering Nothing
repeatRead h
where
repeatRead h= do
forkIO $ doit h
return()
where
doit h= do
s <- hGetLine h
print s
threadDelay 1000000
doit h
| null | https://raw.githubusercontent.com/transient-haskell/transient/301831888887fb199e9f9bfaba2502389e73bc93/tests/teststreamsocket.hs | haskell | # LANGUAGE RecordWildCards, ScopedTypeVariables #
only done if there's an error |
module Main where
import Network
import qualified Network.Socket as NS hiding (send, sendTo, recv, recvFrom)
import Network.Socket.ByteString
import qualified Network.BSD as BSD
import System.IO hiding (hPutBufNonBlocking)
import Control.Concurrent
import Control.Monad
import Control.Exception
import Control.Monad.IO.Class
import qualified Data.ByteString.Char8 as BS
import Foreign.Ptr
import Foreign.Storable
import Data.ByteString.Internal
import Foreign.ForeignPtr.Safe
main = do
let host= "localhost"; port= 2000
forkIO $ listen' $ PortNumber port
proto <- BSD.getProtocolNumber "tcp"
bracketOnError
(NS.socket NS.AF_INET NS.Stream proto)
(\sock -> do
NS.setSocketOption sock NS.RecvBuffer 3000
he <- BSD.getHostByName "localhost"
NS.connect sock (NS.SockAddrInet port (BSD.hostAddress he))
loop sock 0
getChar)
where
loop sock x = do
let msg = BS.pack $ show x ++ "\n"
let l = BS.length msg
n <- send sock msg
when (n < l) $ do
print $ "CONGESTION "++ show (l-n)
sendAll sock $ BS.drop n msg
loop sock (x +1)
listen' port = do
sock <- listenOn port
(h,host,port1) <- accept sock
hSetBuffering h $ BlockBuffering Nothing
repeatRead h
where
repeatRead h= do
forkIO $ doit h
return()
where
doit h= do
s <- hGetLine h
print s
threadDelay 1000000
doit h
|
f20c83c154203dfd0ad3fbff1927653a9a2027e3ea9655b2be8fc06833a7668a | tomhanika/conexp-clj | many_valued_contexts.clj | ;; Copyright ⓒ the conexp-clj developers; all rights reserved.
;; The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 ( -1.0.php )
;; which can be found in the file LICENSE at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns conexp.fca.many-valued-contexts
"Many-Valued-Contexts and some functions for scaling."
(:require [conexp.base :refer :all]
[conexp.fca.contexts :refer :all]))
;;;
(deftype Many-Valued-Context [objects attributes incidence]
Object
(equals [this other]
(generic-equals [this other] Many-Valued-Context [objects attributes incidence]))
(hashCode [this]
(hash-combine-hash Many-Valued-Context objects attributes incidence))
;;
Context
(objects [this] objects)
(attributes [this] attributes)
(incidence [this] incidence))
(defn mv-context-to-string
"Returns a string representing the given many-valued context mv-ctx
as a value-table."
([mv-ctx]
(mv-context-to-string mv-ctx sort-by-first sort-by-first))
([mv-ctx order-on-objects order-on-attributes]
(let [objs (sort order-on-objects (objects mv-ctx)),
atts (sort order-on-attributes (attributes mv-ctx)),
inz (incidence mv-ctx),
str #(if (nil? %) "nil" (str %))
max-obj-len (reduce #(max %1 (count (str %2))) 0 objs)
max-att-lens (loop [lens (transient (map-by-fn #(count (str %)) atts)),
values (seq inz)]
(if values
(let [[[_ m] w] (first values),
len (count (str w))]
(recur (if (> len (lens m))
(assoc! lens m len)
lens)
(next values)))
(persistent! lens)))]
(with-str-out
(ensure-length "" max-obj-len " ") " |" (for [att atts]
[(ensure-length (str att) (max-att-lens att) " ") " "])
"\n"
(ensure-length "" max-obj-len "-") "-+" (for [att atts]
(ensure-length "" (inc (max-att-lens att)) "-"))
"\n"
(for [obj objs]
[(ensure-length (str obj) max-obj-len)
" |"
(for [att atts]
[(ensure-length (str (inz [obj att])) (max-att-lens att))
" "])
"\n"])))))
(defmethod print-method Many-Valued-Context [mv-ctx out]
(.write ^java.io.Writer out ^String (mv-context-to-string mv-ctx)))
;;;
(defmulti make-mv-context
"Constructs a many-valued context from a set of objects, a set of
attributes and an incidence relation, given as set of triples [g m w]
or as a function from two arguments g and m to values w."
{:arglists '([objects attributes incidence])}
(fn [& args] (vec (map clojure-type args))))
(defmethod make-mv-context [Object Object clojure-coll]
[objs atts inz]
(let [objs (to-set objs),
atts (to-set atts)]
(Many-Valued-Context. objs
atts
(if (map? inz)
(do
(when-not (= (cross-product objs atts) (set (keys inz)))
(illegal-argument "Incidence map for many-value-context must be total "
"and must not contain additional keys."))
inz)
(loop [hash (transient {}),
items inz]
(if (empty? items)
(persistent! hash)
(let [[g m w] (first items)]
(recur (if (and (contains? objs g)
(contains? atts m))
(assoc! hash [g m] w)
hash)
(rest items)))))))))
(defmethod make-mv-context [Object Object clojure-fn]
[objs atts inz-fn]
(let [objs (to-set objs),
atts (to-set atts)]
(Many-Valued-Context. objs
atts
(map-by-fn (fn [[g m]]
(inz-fn g m))
(cross-product objs atts)))))
(defmethod make-mv-context :default [objs atts inz]
(illegal-argument "No method defined for types "
(clojure-type objs) ", "
(clojure-type atts) ", "
(clojure-type vals) ", "
(clojure-type inz) "."))
(defn make-mv-context-from-matrix
"Creates a many-valued context from a given matrix of
values. objects and attributes may either be given as numbers
representing the corresponding number of objects and attributes
respectively, or as collections. The number of entries in values
must match the number of objects times the number of attributes."
[objects attributes values]
(let [objects (ensure-seq objects),
attributes (ensure-seq attributes),
m (count objects),
n (count attributes)]
(assert (= (* m n) (count values)))
(let [entries (into {} (for [i (range m), j (range n)]
[[(nth objects i) (nth attributes j)] (nth values (+ (* n i) j))]))]
(make-mv-context objects attributes (fn [a b] (entries [a b]))))))
(defn make-mv-context-nc
"Just creates a many-valued context from a set of objects, a set of
attributes and a hashmap from pairs of objects and attributes to
values. Does no checking, use with care."
[objects attributes incidence]
(assert (map? incidence))
(Many-Valued-Context. (to-set objects) (to-set attributes) incidence))
;;;
(defn values-of-attribute
"For a given many-valued context mv-ctx and a given attribute m,
returns the set of all values of m in mv-ctx."
[mv-ctx m]
(when-not (contains? (attributes mv-ctx) m)
(illegal-argument "Given element is not an attribute of the given many-valued context."))
(let [inz (incidence mv-ctx)]
(set-of (inz [g m]) [g (objects mv-ctx)])))
(defn values-of-object
"For a given many-valued context mv-ctx and a given object g,
returns the set of all values of g in mv-ctx."
[mv-ctx g]
(when-not (contains? (objects mv-ctx) g)
(illegal-argument "Given element is not an object of the given many-valued context."))
(let [inz (incidence mv-ctx)]
(set-of (inz [g m]) [m (attributes mv-ctx)])))
(defn incidences-of-object
"For a given many-valued context mv-ctx and a given object g,
returns the set of all values of g in mv-ctx."
[mv-ctx g]
(when-not (contains? (objects mv-ctx) g)
(illegal-argument "Given element is not an object of the given many-valued context."))
(apply merge
(map #(hash-map (get-in % [0 1]) (second %))
(filter #(= g (get-in % [0 0]))
(incidence mv-ctx)))))
(defn object-by-incidence
"For a given many-valued context mv-ctx and an attribute-value map,
returns all objects having these values."
[mv-ctx values]
(when-not (subset? (set (keys values)) (attributes mv-ctx))
(illegal-argument "Values must only contain attributes of the context."))
(set (filter #(every? (fn [a] (= ((incidences-of-object mv-ctx %) a) (values a))) (keys values))
(objects mv-ctx))))
(defn make-mv-subcontext
"For a given many-valued context, returns the induced subcontext given
by the object and attribute set."
[mv-ctx objs attrs]
(when-not (and (subset? objs (objects mv-ctx))
(subset? attrs (attributes mv-ctx)))
(illegal-argument "The attributes and objects have to be subsets
of the many-valued contexts attributes and objects."))
(make-mv-context objs attrs
(apply merge
(map #(hash-map (first %) (second %))
(filter #(and (contains? objs (get-in % [0 0]))
(contains? attrs (get-in % [0 1])))
(apply list (incidence mv-ctx)))))))
;;;
(defn scale-mv-context
"Scales given many-valued context mv-ctx with given scales. scales must be a map from attributes m
to contexts K, where all possible values of m in mv-ctx are among the objects in K. If a scale for
an attribute is given, the default scale is used, where default should be a function returning a
scale for the supplied attribute. If no default scale is given, an error is thrown if an attribute
is missing."
([mv-ctx scales]
(scale-mv-context mv-ctx scales #(illegal-argument "No scale given for attribute " % ".")))
([mv-ctx scales default]
(assert (map? scales))
(let [scale (fn [m]
(if (contains? scales m)
(scales m)
(default m)))
inz (incidence mv-ctx),
objs (objects mv-ctx),
atts (set-of [m n] [m (attributes mv-ctx)
n (attributes (scale m))])]
(make-context-nc objs
atts
(fn [[g [m n]]]
(let [w (inz [g m])]
((incidence (scale m)) [w n])))))))
(defn nominal-scale
"Returns the nominal scale on the set base."
([values]
(nominal-scale values values))
([values others]
(make-context values others =)))
(defn ordinal-scale
"Returns the ordinal scale on the set values, optionally given an
order relation <=."
([values]
(ordinal-scale values <=))
([values <=]
(ordinal-scale values values <=))
([values others <=]
(let [atts (map #(vector '<= %) others),
inz (fn [g [_ m]]
(<= g m))]
(make-context values atts inz))))
(defn interordinal-scale
"Returns the interordinal scale on the set base, optionally given
two order relations <= and >=."
([values]
(interordinal-scale values <= >=))
([values <= >=]
(interordinal-scale values values <= >=))
([values others <= >=]
(let [objs values,
atts-<= (map #(vector '<= %) others),
atts->= (map #(vector '>= %) others),
inz (fn [g [test m]]
(if (= test '<=)
(<= g m)
(>= g m)))]
(make-context values (union atts-<= atts->=) inz))))
(defn biordinal-scale
"Returns the biordinal scale on the sequence values, optionally given
two order relations <= and >=. Note that values (and others) must be
ordered (e.g. vector or list), because otherwise the result will be
arbitrary."
([values n]
(biordinal-scale values values n <= >=))
([values others n <= >=]
(let [first-objs (take n values),
rest-objs (drop n values),
first-atts (map #(vector '<= %) (take n others)),
rest-atts (map #(vector '>= %) (drop n others)),
inz (fn [g [test m]]
(if (= test '<=)
(<= g m)
(>= g m)))]
(make-context values (union first-atts rest-atts) inz))))
(defn dichotomic-scale
"Returns the dichotimic scale on the set values. Note that base must
have exactly two arguments."
[values]
(assert (= 2 (count values)))
(nominal-scale values))
(defn interval-scale
"Returns the interval scale on the set values.
Note that values must be ordered (e.g. vector or list), because otherwise the result
will be arbitrary. Also note that the intervales will be left-open."
([values]
(interval-scale values values < >=))
([values others]
(interval-scale values others < >=))
([values others < >=]
(assert (sequential? others)
"Interval values must be ordered to obtain a reasonable result.")
(let [pairs (partition 2 1 others)
atts (map #(vector '∈ (vec %)) pairs)
inz (fn [g [_ [a b]]]
(and (< g b)
(>= g a)))]
(make-context values atts inz))))
;;;
(defmacro scale-mv-context-with
"Scales the given many-valued context ctx with the given scales. These are of the form
[att_1 att_2 ...] scale,
where att_i is an attribute of the given context and scale determines a call to a known
scale. The variable «values» will be bound to the corresponding values of each attribute
and may be used when constructing the scale. For example, you may use this macro with
(scale-mv-context-with ctx
[a b c] (nominal-scale values)
[d] (ordinal-scale values <=)
(nominal-scale values))
where the last entry (without any associated attribute) is the default scale. Note that
attributes of ctx always have to be given in a sequence, even if there is only one."
[ctx & scales]
(let [default (if (odd? (count scales))
(last scales)
nil),
scales (partition 2 (if default (butlast scales) scales)),
given-atts (mapcat first scales)]
(when (not= given-atts (distinct given-atts))
(illegal-argument "Doubly given attribute."))
`(do
~(when-not default
`(when-not (= (attributes ~ctx) '~(set given-atts))
(illegal-argument "Given scales to scale-context do not "
"yield the attribute set of the given context.")))
(scale-mv-context ~ctx
~(into {}
(for [[atts scale] scales,
att atts]
`['~att (let [~'values (values-of-attribute ~ctx '~att)]
~scale)]))
(memoize (fn [x#]
(let [~'values (values-of-attribute ~ctx x#)]
~default)))))))
;;;
nil
| null | https://raw.githubusercontent.com/tomhanika/conexp-clj/5e4c15697f06446f925f53d1d143528155d7dd3a/src/main/clojure/conexp/fca/many_valued_contexts.clj | clojure | Copyright ⓒ the conexp-clj developers; all rights reserved.
The use and distribution terms for this software are covered by the
which can be found in the file LICENSE at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
| Eclipse Public License 1.0 ( -1.0.php )
(ns conexp.fca.many-valued-contexts
"Many-Valued-Contexts and some functions for scaling."
(:require [conexp.base :refer :all]
[conexp.fca.contexts :refer :all]))
(deftype Many-Valued-Context [objects attributes incidence]
Object
(equals [this other]
(generic-equals [this other] Many-Valued-Context [objects attributes incidence]))
(hashCode [this]
(hash-combine-hash Many-Valued-Context objects attributes incidence))
Context
(objects [this] objects)
(attributes [this] attributes)
(incidence [this] incidence))
(defn mv-context-to-string
"Returns a string representing the given many-valued context mv-ctx
as a value-table."
([mv-ctx]
(mv-context-to-string mv-ctx sort-by-first sort-by-first))
([mv-ctx order-on-objects order-on-attributes]
(let [objs (sort order-on-objects (objects mv-ctx)),
atts (sort order-on-attributes (attributes mv-ctx)),
inz (incidence mv-ctx),
str #(if (nil? %) "nil" (str %))
max-obj-len (reduce #(max %1 (count (str %2))) 0 objs)
max-att-lens (loop [lens (transient (map-by-fn #(count (str %)) atts)),
values (seq inz)]
(if values
(let [[[_ m] w] (first values),
len (count (str w))]
(recur (if (> len (lens m))
(assoc! lens m len)
lens)
(next values)))
(persistent! lens)))]
(with-str-out
(ensure-length "" max-obj-len " ") " |" (for [att atts]
[(ensure-length (str att) (max-att-lens att) " ") " "])
"\n"
(ensure-length "" max-obj-len "-") "-+" (for [att atts]
(ensure-length "" (inc (max-att-lens att)) "-"))
"\n"
(for [obj objs]
[(ensure-length (str obj) max-obj-len)
" |"
(for [att atts]
[(ensure-length (str (inz [obj att])) (max-att-lens att))
" "])
"\n"])))))
(defmethod print-method Many-Valued-Context [mv-ctx out]
(.write ^java.io.Writer out ^String (mv-context-to-string mv-ctx)))
(defmulti make-mv-context
"Constructs a many-valued context from a set of objects, a set of
attributes and an incidence relation, given as set of triples [g m w]
or as a function from two arguments g and m to values w."
{:arglists '([objects attributes incidence])}
(fn [& args] (vec (map clojure-type args))))
(defmethod make-mv-context [Object Object clojure-coll]
[objs atts inz]
(let [objs (to-set objs),
atts (to-set atts)]
(Many-Valued-Context. objs
atts
(if (map? inz)
(do
(when-not (= (cross-product objs atts) (set (keys inz)))
(illegal-argument "Incidence map for many-value-context must be total "
"and must not contain additional keys."))
inz)
(loop [hash (transient {}),
items inz]
(if (empty? items)
(persistent! hash)
(let [[g m w] (first items)]
(recur (if (and (contains? objs g)
(contains? atts m))
(assoc! hash [g m] w)
hash)
(rest items)))))))))
(defmethod make-mv-context [Object Object clojure-fn]
[objs atts inz-fn]
(let [objs (to-set objs),
atts (to-set atts)]
(Many-Valued-Context. objs
atts
(map-by-fn (fn [[g m]]
(inz-fn g m))
(cross-product objs atts)))))
(defmethod make-mv-context :default [objs atts inz]
(illegal-argument "No method defined for types "
(clojure-type objs) ", "
(clojure-type atts) ", "
(clojure-type vals) ", "
(clojure-type inz) "."))
(defn make-mv-context-from-matrix
"Creates a many-valued context from a given matrix of
values. objects and attributes may either be given as numbers
representing the corresponding number of objects and attributes
respectively, or as collections. The number of entries in values
must match the number of objects times the number of attributes."
[objects attributes values]
(let [objects (ensure-seq objects),
attributes (ensure-seq attributes),
m (count objects),
n (count attributes)]
(assert (= (* m n) (count values)))
(let [entries (into {} (for [i (range m), j (range n)]
[[(nth objects i) (nth attributes j)] (nth values (+ (* n i) j))]))]
(make-mv-context objects attributes (fn [a b] (entries [a b]))))))
(defn make-mv-context-nc
"Just creates a many-valued context from a set of objects, a set of
attributes and a hashmap from pairs of objects and attributes to
values. Does no checking, use with care."
[objects attributes incidence]
(assert (map? incidence))
(Many-Valued-Context. (to-set objects) (to-set attributes) incidence))
(defn values-of-attribute
"For a given many-valued context mv-ctx and a given attribute m,
returns the set of all values of m in mv-ctx."
[mv-ctx m]
(when-not (contains? (attributes mv-ctx) m)
(illegal-argument "Given element is not an attribute of the given many-valued context."))
(let [inz (incidence mv-ctx)]
(set-of (inz [g m]) [g (objects mv-ctx)])))
(defn values-of-object
"For a given many-valued context mv-ctx and a given object g,
returns the set of all values of g in mv-ctx."
[mv-ctx g]
(when-not (contains? (objects mv-ctx) g)
(illegal-argument "Given element is not an object of the given many-valued context."))
(let [inz (incidence mv-ctx)]
(set-of (inz [g m]) [m (attributes mv-ctx)])))
(defn incidences-of-object
"For a given many-valued context mv-ctx and a given object g,
returns the set of all values of g in mv-ctx."
[mv-ctx g]
(when-not (contains? (objects mv-ctx) g)
(illegal-argument "Given element is not an object of the given many-valued context."))
(apply merge
(map #(hash-map (get-in % [0 1]) (second %))
(filter #(= g (get-in % [0 0]))
(incidence mv-ctx)))))
(defn object-by-incidence
"For a given many-valued context mv-ctx and an attribute-value map,
returns all objects having these values."
[mv-ctx values]
(when-not (subset? (set (keys values)) (attributes mv-ctx))
(illegal-argument "Values must only contain attributes of the context."))
(set (filter #(every? (fn [a] (= ((incidences-of-object mv-ctx %) a) (values a))) (keys values))
(objects mv-ctx))))
(defn make-mv-subcontext
"For a given many-valued context, returns the induced subcontext given
by the object and attribute set."
[mv-ctx objs attrs]
(when-not (and (subset? objs (objects mv-ctx))
(subset? attrs (attributes mv-ctx)))
(illegal-argument "The attributes and objects have to be subsets
of the many-valued contexts attributes and objects."))
(make-mv-context objs attrs
(apply merge
(map #(hash-map (first %) (second %))
(filter #(and (contains? objs (get-in % [0 0]))
(contains? attrs (get-in % [0 1])))
(apply list (incidence mv-ctx)))))))
(defn scale-mv-context
"Scales given many-valued context mv-ctx with given scales. scales must be a map from attributes m
to contexts K, where all possible values of m in mv-ctx are among the objects in K. If a scale for
an attribute is given, the default scale is used, where default should be a function returning a
scale for the supplied attribute. If no default scale is given, an error is thrown if an attribute
is missing."
([mv-ctx scales]
(scale-mv-context mv-ctx scales #(illegal-argument "No scale given for attribute " % ".")))
([mv-ctx scales default]
(assert (map? scales))
(let [scale (fn [m]
(if (contains? scales m)
(scales m)
(default m)))
inz (incidence mv-ctx),
objs (objects mv-ctx),
atts (set-of [m n] [m (attributes mv-ctx)
n (attributes (scale m))])]
(make-context-nc objs
atts
(fn [[g [m n]]]
(let [w (inz [g m])]
((incidence (scale m)) [w n])))))))
(defn nominal-scale
"Returns the nominal scale on the set base."
([values]
(nominal-scale values values))
([values others]
(make-context values others =)))
(defn ordinal-scale
"Returns the ordinal scale on the set values, optionally given an
order relation <=."
([values]
(ordinal-scale values <=))
([values <=]
(ordinal-scale values values <=))
([values others <=]
(let [atts (map #(vector '<= %) others),
inz (fn [g [_ m]]
(<= g m))]
(make-context values atts inz))))
(defn interordinal-scale
"Returns the interordinal scale on the set base, optionally given
two order relations <= and >=."
([values]
(interordinal-scale values <= >=))
([values <= >=]
(interordinal-scale values values <= >=))
([values others <= >=]
(let [objs values,
atts-<= (map #(vector '<= %) others),
atts->= (map #(vector '>= %) others),
inz (fn [g [test m]]
(if (= test '<=)
(<= g m)
(>= g m)))]
(make-context values (union atts-<= atts->=) inz))))
(defn biordinal-scale
"Returns the biordinal scale on the sequence values, optionally given
two order relations <= and >=. Note that values (and others) must be
ordered (e.g. vector or list), because otherwise the result will be
arbitrary."
([values n]
(biordinal-scale values values n <= >=))
([values others n <= >=]
(let [first-objs (take n values),
rest-objs (drop n values),
first-atts (map #(vector '<= %) (take n others)),
rest-atts (map #(vector '>= %) (drop n others)),
inz (fn [g [test m]]
(if (= test '<=)
(<= g m)
(>= g m)))]
(make-context values (union first-atts rest-atts) inz))))
(defn dichotomic-scale
"Returns the dichotimic scale on the set values. Note that base must
have exactly two arguments."
[values]
(assert (= 2 (count values)))
(nominal-scale values))
(defn interval-scale
"Returns the interval scale on the set values.
Note that values must be ordered (e.g. vector or list), because otherwise the result
will be arbitrary. Also note that the intervales will be left-open."
([values]
(interval-scale values values < >=))
([values others]
(interval-scale values others < >=))
([values others < >=]
(assert (sequential? others)
"Interval values must be ordered to obtain a reasonable result.")
(let [pairs (partition 2 1 others)
atts (map #(vector '∈ (vec %)) pairs)
inz (fn [g [_ [a b]]]
(and (< g b)
(>= g a)))]
(make-context values atts inz))))
(defmacro scale-mv-context-with
"Scales the given many-valued context ctx with the given scales. These are of the form
[att_1 att_2 ...] scale,
where att_i is an attribute of the given context and scale determines a call to a known
scale. The variable «values» will be bound to the corresponding values of each attribute
and may be used when constructing the scale. For example, you may use this macro with
(scale-mv-context-with ctx
[a b c] (nominal-scale values)
[d] (ordinal-scale values <=)
(nominal-scale values))
where the last entry (without any associated attribute) is the default scale. Note that
attributes of ctx always have to be given in a sequence, even if there is only one."
[ctx & scales]
(let [default (if (odd? (count scales))
(last scales)
nil),
scales (partition 2 (if default (butlast scales) scales)),
given-atts (mapcat first scales)]
(when (not= given-atts (distinct given-atts))
(illegal-argument "Doubly given attribute."))
`(do
~(when-not default
`(when-not (= (attributes ~ctx) '~(set given-atts))
(illegal-argument "Given scales to scale-context do not "
"yield the attribute set of the given context.")))
(scale-mv-context ~ctx
~(into {}
(for [[atts scale] scales,
att atts]
`['~att (let [~'values (values-of-attribute ~ctx '~att)]
~scale)]))
(memoize (fn [x#]
(let [~'values (values-of-attribute ~ctx x#)]
~default)))))))
nil
|
3d4e665192aefafd687eb9a5dcab6cce96febb01b5eca213c27b603abd56f813 | Gandalf-/coreutils | TrSpec.hs | {-# LANGUAGE OverloadedStrings #-}
module TrSpec where
import Control.Exception
import Coreutils.Tr
import Data.Array
import Data.ByteString.Char8 (ByteString)
import Data.Either
import Data.Word8
import qualified Streaming.ByteString as Q
import Test.Hspec
spec :: Spec
spec = do
describe "translationTable" $ do
it "works" $ do
let (Translator t) = translationTable False "abc" "ABC"
t ! _a `shouldBe` _A
t ! _b `shouldBe` _B
t ! _c `shouldBe` _C
t ! _d `shouldBe` _d
it "complement" $ do
let (Translator t) = translationTable True "abc" "ABC"
t ! _a `shouldBe` _a
t ! _0 `shouldBe` _C
t ! _1 `shouldBe` _C
describe "translate" $ do
it "works" $
rt upperCase "abc123" `shouldReturn` "ABC123"
-- GNU tr refuses entirely to do this
it "complement" $ do
let table = translationTable True (parse "[:digit:]") "Z"
rt table "abc123" `shouldReturn` "ZZZ123"
describe "deletionTable" $ do
it "works" $ do
let (Deleter t) = deletionTable False "123"
t ! _1 `shouldBe` False
t ! _2 `shouldBe` False
t ! _3 `shouldBe` False
t ! _a `shouldBe` True
it "complement" $ do
let (Deleter t) = deletionTable True "123"
t ! _1 `shouldBe` True
t ! _a `shouldBe` False
t ! _b `shouldBe` False
describe "delete" $ do
it "works" $
rt deleteNums "hello123" `shouldReturn` "hello"
it "complement" $
rt cDeleteNums "hello123" `shouldReturn` "123"
describe "squeeze" $
it "works" $ do
squeeze "hello" `shouldBe` "helo"
squeeze "12345" `shouldBe` "12345"
squeeze "" `shouldBe` ""
describe "truncate" $
it "works" $ do
truncate' "abc" "hello" `shouldBe` "hel"
truncate' "hello" "abc" `shouldBe` "abc"
describe "prepare" $ do
it "invalid" $ do
prepare opts []
`shouldBe` Left "At least one set must be provided"
prepare opts { optAction = Delete } ["1", "2"]
`shouldBe` Left "Deletion requires one set"
prepare opts { optAction = Translate } ["1"]
`shouldBe` Left "Translation requires two sets"
prepare opts { optAction = Translate } ["1", "2", "3"]
`shouldSatisfy` isLeft
it "default translator" $ do
let (Right e) = prepare opts ["a", "1"]
rt e "abc" `shouldReturn` "1bc"
it "default deleter" $ do
let (Right e) = prepare opts { optAction = Delete } ["123"]
rt e "abc123" `shouldReturn` "abc"
it "squeeze first" $ do
-- Hmm, not really testing much here
let (Right e) = prepare opts { optSqueeze = True, optAction = Delete } ["aabbc"]
rt e "abc123" `shouldReturn` "123"
it "squeeze second" $ do
let (Right e) = prepare opts { optSqueeze = True } ["123", "aabbc"]
rt e "abc123" `shouldReturn` "abcabc"
describe "parse" $ do
it "equivalent" $ do
parse "=a=" `shouldBe` "a"
parse "= =" `shouldBe` " "
it "range" $ do
parse "a-d" `shouldBe` "abcd"
parse "a-dx-z" `shouldBe` "abcdxyz"
parse "A-Z" `shouldBe` "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
parse "0-9" `shouldBe` parse "[:digit:]"
parse "9-0" `shouldBe` ""
it "copies" $ do
parse "a*5" `shouldBe`"aaaaa"
evaluate (parse "a*a") `shouldThrow` anyErrorCall
it "special" $ do
parse "\\n" `shouldBe` "\n"
parse "\\\\\n" `shouldBe` "\\\n"
it "combined" $ do
parse "[:digit:]abc" `shouldBe` "0123456789abc"
parse "a-d[:digit:]" `shouldBe` "abcd0123456789"
where
opts = defaultOptions
lower = parse "[:lower:]"
upper = parse "[:upper:]"
digit = parse "[:digit:]"
upperCase = translationTable False lower upper
deleteNums = deletionTable False digit
cDeleteNums = deletionTable True digit
rt :: Translator -> ByteString -> IO ByteString
rt t = Q.toStrict_ . execute t . Q.fromStrict
| null | https://raw.githubusercontent.com/Gandalf-/coreutils/0566feef66b7cbab35a8095a207fd8d87a09193d/test/TrSpec.hs | haskell | # LANGUAGE OverloadedStrings #
GNU tr refuses entirely to do this
Hmm, not really testing much here |
module TrSpec where
import Control.Exception
import Coreutils.Tr
import Data.Array
import Data.ByteString.Char8 (ByteString)
import Data.Either
import Data.Word8
import qualified Streaming.ByteString as Q
import Test.Hspec
spec :: Spec
spec = do
describe "translationTable" $ do
it "works" $ do
let (Translator t) = translationTable False "abc" "ABC"
t ! _a `shouldBe` _A
t ! _b `shouldBe` _B
t ! _c `shouldBe` _C
t ! _d `shouldBe` _d
it "complement" $ do
let (Translator t) = translationTable True "abc" "ABC"
t ! _a `shouldBe` _a
t ! _0 `shouldBe` _C
t ! _1 `shouldBe` _C
describe "translate" $ do
it "works" $
rt upperCase "abc123" `shouldReturn` "ABC123"
it "complement" $ do
let table = translationTable True (parse "[:digit:]") "Z"
rt table "abc123" `shouldReturn` "ZZZ123"
describe "deletionTable" $ do
it "works" $ do
let (Deleter t) = deletionTable False "123"
t ! _1 `shouldBe` False
t ! _2 `shouldBe` False
t ! _3 `shouldBe` False
t ! _a `shouldBe` True
it "complement" $ do
let (Deleter t) = deletionTable True "123"
t ! _1 `shouldBe` True
t ! _a `shouldBe` False
t ! _b `shouldBe` False
describe "delete" $ do
it "works" $
rt deleteNums "hello123" `shouldReturn` "hello"
it "complement" $
rt cDeleteNums "hello123" `shouldReturn` "123"
describe "squeeze" $
it "works" $ do
squeeze "hello" `shouldBe` "helo"
squeeze "12345" `shouldBe` "12345"
squeeze "" `shouldBe` ""
describe "truncate" $
it "works" $ do
truncate' "abc" "hello" `shouldBe` "hel"
truncate' "hello" "abc" `shouldBe` "abc"
describe "prepare" $ do
it "invalid" $ do
prepare opts []
`shouldBe` Left "At least one set must be provided"
prepare opts { optAction = Delete } ["1", "2"]
`shouldBe` Left "Deletion requires one set"
prepare opts { optAction = Translate } ["1"]
`shouldBe` Left "Translation requires two sets"
prepare opts { optAction = Translate } ["1", "2", "3"]
`shouldSatisfy` isLeft
it "default translator" $ do
let (Right e) = prepare opts ["a", "1"]
rt e "abc" `shouldReturn` "1bc"
it "default deleter" $ do
let (Right e) = prepare opts { optAction = Delete } ["123"]
rt e "abc123" `shouldReturn` "abc"
it "squeeze first" $ do
let (Right e) = prepare opts { optSqueeze = True, optAction = Delete } ["aabbc"]
rt e "abc123" `shouldReturn` "123"
it "squeeze second" $ do
let (Right e) = prepare opts { optSqueeze = True } ["123", "aabbc"]
rt e "abc123" `shouldReturn` "abcabc"
describe "parse" $ do
it "equivalent" $ do
parse "=a=" `shouldBe` "a"
parse "= =" `shouldBe` " "
it "range" $ do
parse "a-d" `shouldBe` "abcd"
parse "a-dx-z" `shouldBe` "abcdxyz"
parse "A-Z" `shouldBe` "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
parse "0-9" `shouldBe` parse "[:digit:]"
parse "9-0" `shouldBe` ""
it "copies" $ do
parse "a*5" `shouldBe`"aaaaa"
evaluate (parse "a*a") `shouldThrow` anyErrorCall
it "special" $ do
parse "\\n" `shouldBe` "\n"
parse "\\\\\n" `shouldBe` "\\\n"
it "combined" $ do
parse "[:digit:]abc" `shouldBe` "0123456789abc"
parse "a-d[:digit:]" `shouldBe` "abcd0123456789"
where
opts = defaultOptions
lower = parse "[:lower:]"
upper = parse "[:upper:]"
digit = parse "[:digit:]"
upperCase = translationTable False lower upper
deleteNums = deletionTable False digit
cDeleteNums = deletionTable True digit
rt :: Translator -> ByteString -> IO ByteString
rt t = Q.toStrict_ . execute t . Q.fromStrict
|
4b01baafacf9268f7dd46a6552535c029733de7b60e9494ea563adbe69ad7b4b | ghc/testsuite | tcrun022.hs | -- This test checks in which way the type checker handles phantom types in
-- RULES. We would like these type variables to be generalised, but some
versions of GHC instantiated them to ` ( ) ' , which seriously limited the
-- applicability of such RULES.
module Main (main)
where
data T a = C
foo :: T a -> String
# NOINLINE foo #
foo C = "rewrite rule did NOT fire"
{-# RULES
-- this rule will not fire if the type argument of `T' is constrained to `()'
--
"foo/C" foo C = "rewrite rule did fire"
#-}
main = putStrLn $ foo (C :: T Int)
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_run/tcrun022.hs | haskell | This test checks in which way the type checker handles phantom types in
RULES. We would like these type variables to be generalised, but some
applicability of such RULES.
# RULES
-- this rule will not fire if the type argument of `T' is constrained to `()'
--
"foo/C" foo C = "rewrite rule did fire"
# | versions of GHC instantiated them to ` ( ) ' , which seriously limited the
module Main (main)
where
data T a = C
foo :: T a -> String
# NOINLINE foo #
foo C = "rewrite rule did NOT fire"
main = putStrLn $ foo (C :: T Int)
|
c654922d3975ba0e4faf4f17c9cd661c3b4678603234ee065be50cb329a7eb5d | Smoltbob/Caml-Est-Belle | fknormal.ml | (** This module encapslates the K-normalization step.*)
open Fsyntax;;
open Printf;;
type t =
| Unit
| Bool of bool
| Int of int
| Float of float
| Not of t
| Neg of t
| Add of t * t
| Land of t * t
| Sub of t * t
| FNeg of t
| FAdd of t * t
| FSub of t * t
| FMul of t * t
| FDiv of t * t
| Eq of t * t
| LE of t * t
| IfEq of Id.t * Id.t * t * t
| IfLE of Id.t * Id.t * t * t
(*| IfBool of t * t * t*)
| Let of (Id.t * Ftype.t) * t * t
| Var of Id.t
| LetRec of fundef * t
| App of t * t list
| Tuple of t list
| LetTuple of (Id.t * Ftype.t) list * t * t
| Array of t * t
| Get of t * t
| Put of t * t * t
and fundef = { name : Id.t * Ftype.t; args : (Id.t * Ftype.t) list; body : t }
let last = ref 0
let newvar () = let res = ("v"^(Printf.sprintf "%d" !last), Ftype.gentyp ()) in incr last; res
let is_ident_or_const (ast:Fsyntax.t) =
match ast with
|Var _ -> true
|_ -> false
let ident_or_const_to_k (ast:Fsyntax.t): t =
match ast with
|Unit -> Unit
|Bool a -> Bool a
|Int a -> Int a
|Float a -> Float a
|Var a -> Var a
|_ -> failwith "Knormal.ident_or_const_to_k error"
* K - normalization . Applied to ast , return a flatter version of it : aside from let and letrec , all constructs will have a bounded depth .
@param ast Abstract syntax Tree of a general mincaml program
@return New K - normalized AST
@param ast Abstract syntax Tree of a general mincaml program
@return New K-normalized AST*)
let rec knormal (ast:Fsyntax.t) : t =
match ast with
|Unit -> Unit
|Bool a -> Bool a
|Int a -> Int a
|Float a -> Float a
|Var a -> Var a
|Not b -> knormal_unary (fun x->Not x) b
|Neg b -> knormal_unary (fun x->Neg x) b
|Sub (a, b) -> knormal_binary (fun x->fun y->Sub(x,y)) a b
|Add (a, b) -> knormal_binary (fun x->fun y->Add(x,y)) a b
|FAdd (a, b) -> knormal_binary_brute (fun x->fun y->FAdd(x,y)) a b
|FNeg b -> knormal_unary (fun x->FNeg x) b
|FSub (a, b) -> knormal_binary_brute (fun x->fun y->FSub(x,y)) a b
|FMul (a, b) -> knormal_binary_brute (fun x->fun y->FMul(x,y)) a b
|FDiv (a, b) -> knormal_binary_brute (fun x->fun y->FDiv(x,y)) a b
|Land (a, b) -> knormal_binary (fun x->fun y->Land(x,y)) a b
|App (a,b) -> (let rec aux (fname:Id.t) (vars_rem:Fsyntax.t list) (k_vars:t list) : t =
match vars_rem with
|[] -> App(Var(fname), List.rev k_vars)
|h::q -> (match h with
|Var(_) -> aux fname q ((knormal h)::k_vars)
|_ -> let (x,t) = newvar () in Let((x,t), knormal h, aux fname q ((Var x)::k_vars))
)
in
match a with
|Var(fct) -> aux fct b []
|_ -> let (f,t) = newvar () in Let((f, t), knormal a, aux f b [])
)
|If (a, b, c) ->(match a with
| LE(x, y) -> let (x',t) = newvar () in
let (y',t) = newvar () in
Let((x',t), knormal x,
Let((y',t), knormal y,
IfLE(x', y', knormal b, knormal c)))
| Eq(x, y) -> let (x',t) = newvar () in
let (y',t) = newvar () in
Let((x',t), knormal x,
Let((y',t), knormal y,
IfEq(x', y', knormal b, knormal c)))
| Not(x) -> knormal (If(x, c, b))
| _ -> let (x',t) = newvar () in
let (y',t) = newvar () in
Let((x',t), knormal a,
Let((y',t), Bool(true),
IfEq(x', y', knormal b, knormal c)))
)
|Let (a, b, c) -> if is_ident_or_const b then Let(a, ident_or_const_to_k b, knormal c)
else Let(a, knormal b, knormal c)
|LetRec (a, b) -> LetRec ({name=a.name; args=a.args; body=(knormal a.body)}, knormal b)
|Array (a, b) -> knormal_binary_brute (fun x->fun y->Array(x,y)) a b
|Get (a, b) -> knormal_binary_brute (fun x->fun y->Get(x,y)) a b
|Put (a, b, c) -> if is_ident_or_const a then
knormal_binary_brute (fun x->fun y->Put(ident_or_const_to_k a,x,y)) b c
else (
let (a',t) = newvar () in
Let((a',t), knormal a, (knormal_binary_brute (fun x->fun y->Put(Var a',x,y)) b c) )
)
|Tuple a -> let (r, t) = newvar () in
let cnt = ref 0 in
let a' = List.map (fun x-> let c = !cnt in incr cnt; knormal (Put(Var r, Int c, x))) a in
let (aa, t) = newvar () in
let (nn, t) = newvar () in
Let((nn,t), Int(List.length a'),
Let((aa,t), Int 0,
Let((r,t),
Array((Var nn) , (Var aa)),
List.fold_right (fun x->fun y->Let(("?", Ftype.gentyp ()), x, y)) a' (Var r)))
)
|LetTuple (a, b, c) -> let (b', t) = newvar () in
let cnt = ref ((List.length a) - 1) in
Let((b',t), knormal b,
List.fold_right (fun x->fun y->let cn = !cnt in decr cnt; let (d',t) = newvar () in Let((d',t),Int cn,Let(x, Get(Var b', Var d'),y))) a (knormal c))
|_ -> failwith "knormal: NotImplementedYet"
and knormal_binary (c:t->t->t) (a:Fsyntax.t) (b:Fsyntax.t) =
if is_ident_or_const a then (
if is_ident_or_const b then (
c (ident_or_const_to_k a) (ident_or_const_to_k b)
)
else (
let (b',t) = newvar () in
Let((b',t), knormal b,
c (ident_or_const_to_k a) (Var b'))
)
)
else (
let (a',t) = newvar () in
if is_ident_or_const b then (
Let((a',t), knormal a,
c (Var a') (ident_or_const_to_k b))
)
else
Let((a',t), knormal a,
let (b',t) = newvar () in
Let((b',t), knormal b,
c (Var a') (Var b')))
)
and knormal_binary_brute (c:t->t->t) (a:Fsyntax.t) (b:Fsyntax.t) =
let (a',t) = newvar () in
let (b',t) = newvar () in
Let((a',t), knormal a,
Let((b',t), knormal b,
c (Var a') (Var b')))
and knormal_unary c a =
let (a',t) = newvar () in
Let((a',t), knormal a, c (Var a'))
(** Produces a string out of a K-normalized ast
@param exp t
@return string*)
let rec k_to_string (exp:t) : string =
match exp with
| Unit -> "()"
| Bool b -> if b then "true" else "false"
| Int i -> string_of_int i
| Float f -> sprintf "%.2f" f
| Not e -> sprintf "(not %s)" (k_to_string e)
| Neg e -> sprintf "(- %s)" (k_to_string e)
| Add (e1, e2) -> sprintf "(%s + %s)" (k_to_string e1) (k_to_string e2)
| Land (e1, e2) -> sprintf "(%s && %s)" (k_to_string e1) (k_to_string e2)
| Sub (e1, e2) -> sprintf "(%s - %s)" (k_to_string e1) (k_to_string e2)
| FNeg e -> sprintf "(-. %s)" (k_to_string e)
| FAdd (e1, e2) -> sprintf "(%s +. %s)" (k_to_string e1) (k_to_string e2)
| FSub (e1, e2) -> sprintf "(%s -. %s)" (k_to_string e1) (k_to_string e2)
| FMul (e1, e2) -> sprintf "(%s *. %s)" (k_to_string e1) (k_to_string e2)
| FDiv (e1, e2) -> sprintf "(%s /. %s)" (k_to_string e1) (k_to_string e2)
| Eq (e1, e2) -> sprintf "(%s = %s)" (k_to_string e1) (k_to_string e2)
| LE (e1, e2) -> sprintf "(%s <= %s)" (k_to_string e1) (k_to_string e2)
| IfEq (x, y, e2, e3) ->
sprintf "(if %s=%s then %s else %s)" (Id.to_string x) (Id.to_string y) (k_to_string e2) (k_to_string e3)
| IfLE (x, y, e2, e3) ->
sprintf "(if %s <= %s then %s else %s)" (Id.to_string x) (Id.to_string y) (k_to_string e2) (k_to_string e3)
| Let ((id,t), e1, e2) ->
sprintf "(let %s = %s in\n %s)" (Id.to_string id) (k_to_string e1) (k_to_string e2)
| Var id -> Id.to_string id
| App (e1, le2) -> sprintf "(%s %s)" (k_to_string e1) (infix_to_string k_to_string le2 " ")
| LetRec (fd, e) ->
sprintf "(let rec %s %s = %s in\n %s)"
(let (x, _) = fd.name in (Id.to_string x))
(infix_to_string (fun (x,_) -> (Id.to_string x)) fd.args " ")
(k_to_string fd.body)
(k_to_string e)
| LetTuple (l, e1, e2)->
sprintf "(let (%s) = %s in\n %s)"
(infix_to_string (fun (x, _) -> Id.to_string x) l ", ")
(k_to_string e1)
(k_to_string e2)
| Get(e1, e2) -> sprintf "%s.(%s)" (k_to_string e1) (k_to_string e2)
| Put(e1, e2, e3) -> sprintf "(%s.(%s) <- %s)"
(k_to_string e1) (k_to_string e2) (k_to_string e3)
| Tuple(l) -> sprintf "(%s)" (infix_to_string k_to_string l ", ")
| Array(e1,e2) -> sprintf "(Array.create %s %s)"
(k_to_string e1) (k_to_string e2)
| null | https://raw.githubusercontent.com/Smoltbob/Caml-Est-Belle/3d6f53d4e8e01bbae57a0a402b7c0f02f4ed767c/compiler/fknormal.ml | ocaml | * This module encapslates the K-normalization step.
| IfBool of t * t * t
* Produces a string out of a K-normalized ast
@param exp t
@return string | open Fsyntax;;
open Printf;;
type t =
| Unit
| Bool of bool
| Int of int
| Float of float
| Not of t
| Neg of t
| Add of t * t
| Land of t * t
| Sub of t * t
| FNeg of t
| FAdd of t * t
| FSub of t * t
| FMul of t * t
| FDiv of t * t
| Eq of t * t
| LE of t * t
| IfEq of Id.t * Id.t * t * t
| IfLE of Id.t * Id.t * t * t
| Let of (Id.t * Ftype.t) * t * t
| Var of Id.t
| LetRec of fundef * t
| App of t * t list
| Tuple of t list
| LetTuple of (Id.t * Ftype.t) list * t * t
| Array of t * t
| Get of t * t
| Put of t * t * t
and fundef = { name : Id.t * Ftype.t; args : (Id.t * Ftype.t) list; body : t }
let last = ref 0
let newvar () = let res = ("v"^(Printf.sprintf "%d" !last), Ftype.gentyp ()) in incr last; res
let is_ident_or_const (ast:Fsyntax.t) =
match ast with
|Var _ -> true
|_ -> false
let ident_or_const_to_k (ast:Fsyntax.t): t =
match ast with
|Unit -> Unit
|Bool a -> Bool a
|Int a -> Int a
|Float a -> Float a
|Var a -> Var a
|_ -> failwith "Knormal.ident_or_const_to_k error"
* K - normalization . Applied to ast , return a flatter version of it : aside from let and letrec , all constructs will have a bounded depth .
@param ast Abstract syntax Tree of a general mincaml program
@return New K - normalized AST
@param ast Abstract syntax Tree of a general mincaml program
@return New K-normalized AST*)
let rec knormal (ast:Fsyntax.t) : t =
match ast with
|Unit -> Unit
|Bool a -> Bool a
|Int a -> Int a
|Float a -> Float a
|Var a -> Var a
|Not b -> knormal_unary (fun x->Not x) b
|Neg b -> knormal_unary (fun x->Neg x) b
|Sub (a, b) -> knormal_binary (fun x->fun y->Sub(x,y)) a b
|Add (a, b) -> knormal_binary (fun x->fun y->Add(x,y)) a b
|FAdd (a, b) -> knormal_binary_brute (fun x->fun y->FAdd(x,y)) a b
|FNeg b -> knormal_unary (fun x->FNeg x) b
|FSub (a, b) -> knormal_binary_brute (fun x->fun y->FSub(x,y)) a b
|FMul (a, b) -> knormal_binary_brute (fun x->fun y->FMul(x,y)) a b
|FDiv (a, b) -> knormal_binary_brute (fun x->fun y->FDiv(x,y)) a b
|Land (a, b) -> knormal_binary (fun x->fun y->Land(x,y)) a b
|App (a,b) -> (let rec aux (fname:Id.t) (vars_rem:Fsyntax.t list) (k_vars:t list) : t =
match vars_rem with
|[] -> App(Var(fname), List.rev k_vars)
|h::q -> (match h with
|Var(_) -> aux fname q ((knormal h)::k_vars)
|_ -> let (x,t) = newvar () in Let((x,t), knormal h, aux fname q ((Var x)::k_vars))
)
in
match a with
|Var(fct) -> aux fct b []
|_ -> let (f,t) = newvar () in Let((f, t), knormal a, aux f b [])
)
|If (a, b, c) ->(match a with
| LE(x, y) -> let (x',t) = newvar () in
let (y',t) = newvar () in
Let((x',t), knormal x,
Let((y',t), knormal y,
IfLE(x', y', knormal b, knormal c)))
| Eq(x, y) -> let (x',t) = newvar () in
let (y',t) = newvar () in
Let((x',t), knormal x,
Let((y',t), knormal y,
IfEq(x', y', knormal b, knormal c)))
| Not(x) -> knormal (If(x, c, b))
| _ -> let (x',t) = newvar () in
let (y',t) = newvar () in
Let((x',t), knormal a,
Let((y',t), Bool(true),
IfEq(x', y', knormal b, knormal c)))
)
|Let (a, b, c) -> if is_ident_or_const b then Let(a, ident_or_const_to_k b, knormal c)
else Let(a, knormal b, knormal c)
|LetRec (a, b) -> LetRec ({name=a.name; args=a.args; body=(knormal a.body)}, knormal b)
|Array (a, b) -> knormal_binary_brute (fun x->fun y->Array(x,y)) a b
|Get (a, b) -> knormal_binary_brute (fun x->fun y->Get(x,y)) a b
|Put (a, b, c) -> if is_ident_or_const a then
knormal_binary_brute (fun x->fun y->Put(ident_or_const_to_k a,x,y)) b c
else (
let (a',t) = newvar () in
Let((a',t), knormal a, (knormal_binary_brute (fun x->fun y->Put(Var a',x,y)) b c) )
)
|Tuple a -> let (r, t) = newvar () in
let cnt = ref 0 in
let a' = List.map (fun x-> let c = !cnt in incr cnt; knormal (Put(Var r, Int c, x))) a in
let (aa, t) = newvar () in
let (nn, t) = newvar () in
Let((nn,t), Int(List.length a'),
Let((aa,t), Int 0,
Let((r,t),
Array((Var nn) , (Var aa)),
List.fold_right (fun x->fun y->Let(("?", Ftype.gentyp ()), x, y)) a' (Var r)))
)
|LetTuple (a, b, c) -> let (b', t) = newvar () in
let cnt = ref ((List.length a) - 1) in
Let((b',t), knormal b,
List.fold_right (fun x->fun y->let cn = !cnt in decr cnt; let (d',t) = newvar () in Let((d',t),Int cn,Let(x, Get(Var b', Var d'),y))) a (knormal c))
|_ -> failwith "knormal: NotImplementedYet"
and knormal_binary (c:t->t->t) (a:Fsyntax.t) (b:Fsyntax.t) =
if is_ident_or_const a then (
if is_ident_or_const b then (
c (ident_or_const_to_k a) (ident_or_const_to_k b)
)
else (
let (b',t) = newvar () in
Let((b',t), knormal b,
c (ident_or_const_to_k a) (Var b'))
)
)
else (
let (a',t) = newvar () in
if is_ident_or_const b then (
Let((a',t), knormal a,
c (Var a') (ident_or_const_to_k b))
)
else
Let((a',t), knormal a,
let (b',t) = newvar () in
Let((b',t), knormal b,
c (Var a') (Var b')))
)
and knormal_binary_brute (c:t->t->t) (a:Fsyntax.t) (b:Fsyntax.t) =
let (a',t) = newvar () in
let (b',t) = newvar () in
Let((a',t), knormal a,
Let((b',t), knormal b,
c (Var a') (Var b')))
and knormal_unary c a =
let (a',t) = newvar () in
Let((a',t), knormal a, c (Var a'))
let rec k_to_string (exp:t) : string =
match exp with
| Unit -> "()"
| Bool b -> if b then "true" else "false"
| Int i -> string_of_int i
| Float f -> sprintf "%.2f" f
| Not e -> sprintf "(not %s)" (k_to_string e)
| Neg e -> sprintf "(- %s)" (k_to_string e)
| Add (e1, e2) -> sprintf "(%s + %s)" (k_to_string e1) (k_to_string e2)
| Land (e1, e2) -> sprintf "(%s && %s)" (k_to_string e1) (k_to_string e2)
| Sub (e1, e2) -> sprintf "(%s - %s)" (k_to_string e1) (k_to_string e2)
| FNeg e -> sprintf "(-. %s)" (k_to_string e)
| FAdd (e1, e2) -> sprintf "(%s +. %s)" (k_to_string e1) (k_to_string e2)
| FSub (e1, e2) -> sprintf "(%s -. %s)" (k_to_string e1) (k_to_string e2)
| FMul (e1, e2) -> sprintf "(%s *. %s)" (k_to_string e1) (k_to_string e2)
| FDiv (e1, e2) -> sprintf "(%s /. %s)" (k_to_string e1) (k_to_string e2)
| Eq (e1, e2) -> sprintf "(%s = %s)" (k_to_string e1) (k_to_string e2)
| LE (e1, e2) -> sprintf "(%s <= %s)" (k_to_string e1) (k_to_string e2)
| IfEq (x, y, e2, e3) ->
sprintf "(if %s=%s then %s else %s)" (Id.to_string x) (Id.to_string y) (k_to_string e2) (k_to_string e3)
| IfLE (x, y, e2, e3) ->
sprintf "(if %s <= %s then %s else %s)" (Id.to_string x) (Id.to_string y) (k_to_string e2) (k_to_string e3)
| Let ((id,t), e1, e2) ->
sprintf "(let %s = %s in\n %s)" (Id.to_string id) (k_to_string e1) (k_to_string e2)
| Var id -> Id.to_string id
| App (e1, le2) -> sprintf "(%s %s)" (k_to_string e1) (infix_to_string k_to_string le2 " ")
| LetRec (fd, e) ->
sprintf "(let rec %s %s = %s in\n %s)"
(let (x, _) = fd.name in (Id.to_string x))
(infix_to_string (fun (x,_) -> (Id.to_string x)) fd.args " ")
(k_to_string fd.body)
(k_to_string e)
| LetTuple (l, e1, e2)->
sprintf "(let (%s) = %s in\n %s)"
(infix_to_string (fun (x, _) -> Id.to_string x) l ", ")
(k_to_string e1)
(k_to_string e2)
| Get(e1, e2) -> sprintf "%s.(%s)" (k_to_string e1) (k_to_string e2)
| Put(e1, e2, e3) -> sprintf "(%s.(%s) <- %s)"
(k_to_string e1) (k_to_string e2) (k_to_string e3)
| Tuple(l) -> sprintf "(%s)" (infix_to_string k_to_string l ", ")
| Array(e1,e2) -> sprintf "(Array.create %s %s)"
(k_to_string e1) (k_to_string e2)
|
50097613dac3cb1055a47dc1637a3898209166be853516c659b570b8aae3ac3e | wireapp/wire-server | ListItems.hs | # LANGUAGE TemplateHaskell #
-- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Galley.Effects.ListItems
( ListItems (..),
listItems,
)
where
import Data.Id
import Imports
import Polysemy
import Wire.Sem.Paging
-- | General pagination-aware list-by-user effect
data ListItems p i m a where
ListItems ::
UserId ->
Maybe (PagingState p i) ->
PagingBounds p i ->
ListItems p i m (Page p i)
makeSem ''ListItems
| null | https://raw.githubusercontent.com/wireapp/wire-server/ee767dc62b3e2ddaf7eeb5a1e3f996606d3b9d7d/services/galley/src/Galley/Effects/ListItems.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
with this program. If not, see </>.
| General pagination-aware list-by-user effect | # LANGUAGE TemplateHaskell #
Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Galley.Effects.ListItems
( ListItems (..),
listItems,
)
where
import Data.Id
import Imports
import Polysemy
import Wire.Sem.Paging
data ListItems p i m a where
ListItems ::
UserId ->
Maybe (PagingState p i) ->
PagingBounds p i ->
ListItems p i m (Page p i)
makeSem ''ListItems
|
3e4d07a1ad6159ec74ebeaa49510fe5340cdedef95922dc506130c1c1d493d01 | ohua-dev/ohua-core | If.hs | |
Module : $ Header$
Description : Implementation of ALang transformation for If .
Copyright : ( c ) , 2018 . All Rights Reserved .
License : EPL-1.0
Maintainer : ,
Stability : experimental
Portability : portable
This source code is licensed under the terms described in the associated LICENSE.TXT file
= = Design :
We perform lambda lifting on both branches ( after normalization ):
@
let result = if cond
( \ ( ) - > f a b )
( \ ( ) - > g c d )
@
into :
@
let result = if cond
( \ ( ) - > let x = scope a b
in let nth 0 x
in let x1 = nth 1 x
in f x0 x1
( \ ( ) - > let x = scope c d
in let nth 0 x
in let x1 = nth 1 x
in g
The translation of ` if ` itself then produces the following code :
@
let cond : : = ...
let ncond : : Bool = not cond in
let : : Control Bool = ctrl cond in
let : : Control Bool = ctrl ncond in
let resultTrue : : Control a = ( \ ( ) - > ... true branch expression ... ) tBranchCtrl in
let resultFalse : : Control a = ( \ ( ) - > ... false branch expression ... ) fBranchCtrl in
let result : : a = select tBranchCtrl fBranchCtrl resultTrue resultFalse in
result
@
Currently , we can perform this transformation without type annotiations because of the following reasons :
1 . The ` Bool ` type of ` cond ` is verify by the ` not ` function which requires a ` Bool ` .
2 . The ` Control ` types can be easily found via checking the source of the local , i.e. , the binding that created the local .
Semantically , each branch runs in a ` Control ` context and as such that resulting value depends on
control value applied to this computation . The ` select ` then retrieves the final result using both control signals .
We finally simplify the ` select ` known that
1 . The ` ctrl ` calls will be removed by the lowering pass because its inputs are already of type ` Bool ` .
2 . The ` fBranchCtrl ` value is the negation of the ` tBranchCtrl ` value .
As such , we write :
@
let result : : a = select cond resultTrue resultFalse in ...
@
Note that we translate the applications ` ( \ ( ) - > ... branch ... ) ctrlVal ` into the following :
@
let x = scope ctrl a b in
...
let y = idependentFn ctrl in
...
@
In fact , this applies the control value to the lambda expression .
As a result , we can write the following :
@
let cond : : = ...
let ncond : : Bool = not cond in
let : : Control Bool = ctrl cond in
let : : Control Bool = ctrl ncond in
let resultTrue : : Control a = ... true branch expression ... in
let resultFalse : : Control a = ... false branch expression ... in
let result : : a = select tBranchCtrl fBranchCtrl resultTrue resultFalse in
result
@
Now this expression can be lowered to DFLang without any further ado .
The lowering itself should be sensitive to value of type ` Control ` and perform the
respective steps .
As a last step , we can optimize the DFLang expression to end up with :
@
let cond : : = ...
let ncond : : Bool = not cond in
let resultTrue : : Control a = ( \ ( ) - > ... true branch expression ... ) cond in
let resultFalse : : Control a = ( \ ( ) - > ... false branch expression ... ) ncond in
let result : : a = select cond resultTrue resultFalse in
result
@
Module : $Header$
Description : Implementation of ALang transformation for If.
Copyright : (c) Sebastian Ertel, Justus Adam 2018. All Rights Reserved.
License : EPL-1.0
Maintainer : ,
Stability : experimental
Portability : portable
This source code is licensed under the terms described in the associated LICENSE.TXT file
== Design:
We perform lambda lifting on both branches (after normalization):
@
let result = if cond
(\() -> f a b)
(\() -> g c d)
@
into:
@
let result = if cond
(\() -> let x = scope a b
in let x0 = nth 0 x
in let x1 = nth 1 x
in f x0 x1
(\() -> let x = scope c d
in let x0 = nth 0 x
in let x1 = nth 1 x
in g x0 x1
@
The translation of `if` itself then produces the following code:
@
let cond :: Bool = ...
let ncond :: Bool = not cond in
let tBranchCtrl :: Control Bool = ctrl cond in
let fBranchCtrl :: Control Bool = ctrl ncond in
let resultTrue :: Control a = (\() -> ... true branch expression ... ) tBranchCtrl in
let resultFalse :: Control a = (\() -> ... false branch expression ... ) fBranchCtrl in
let result :: a = select tBranchCtrl fBranchCtrl resultTrue resultFalse in
result
@
Currently, we can perform this transformation without type annotiations because of the following reasons:
1. The `Bool` type of `cond` is verify by the `not` function which requires a `Bool`.
2. The `Control` types can be easily found via checking the source of the local, i.e., the binding that created the local.
Semantically, each branch runs in a `Control` context and as such that resulting value depends on
control value applied to this computation. The `select` then retrieves the final result using both control signals.
We finally simplify the `select` known that
1. The `ctrl` calls will be removed by the lowering pass because its inputs are already of type `Bool`.
2. The `fBranchCtrl` value is the negation of the `tBranchCtrl` value.
As such, we write:
@
let result :: a = select cond resultTrue resultFalse in ...
@
Note that we translate the applications `(\() -> ... branch ...) ctrlVal` into the following:
@
let x = scope ctrl a b in
...
let y = idependentFn ctrl in
...
@
In fact, this applies the control value to the lambda expression.
As a result, we can write the following:
@
let cond :: Bool = ...
let ncond :: Bool = not cond in
let tBranchCtrl :: Control Bool = ctrl cond in
let fBranchCtrl :: Control Bool = ctrl ncond in
let resultTrue :: Control a = ... true branch expression ... in
let resultFalse :: Control a = ... false branch expression ... in
let result :: a = select tBranchCtrl fBranchCtrl resultTrue resultFalse in
result
@
Now this expression can be lowered to DFLang without any further ado.
The lowering itself should be sensitive to value of type `Control` and perform the
respective steps.
As a last step, we can optimize the DFLang expression to end up with:
@
let cond :: Bool = ...
let ncond :: Bool = not cond in
let resultTrue :: Control a = (\() -> ... true branch expression ... ) cond in
let resultFalse :: Control a = (\() -> ... false branch expression ... ) ncond in
let result :: a = select cond resultTrue resultFalse in
result
@
-}
# LANGUAGE CPP #
module Ohua.ALang.Passes.If where
import Ohua.Prelude
import Ohua.ALang.Lang
import Ohua.ALang.Passes.Control (liftIntoCtrlCtxt)
import qualified Ohua.ALang.Refs as Refs (ifFun, ifThenElse, select)
import Ohua.ALang.Util
( fromListToApply
, lambdaArgsAndBody
, lambdaLifting
, mkDestructured
)
import Ohua.Unit
import Control.Monad (foldM)
import Control.Category ((>>>))
import qualified Data.Text as T
selectSf :: Expression
selectSf = Lit $ FunRefLit $ FunRef Refs.select Nothing
ifFunSf :: Expression
ifFunSf = Lit $ FunRefLit $ FunRef "ohua.lang/ifFun" Nothing
#if 1
-- This is a proposal for `ifRewrite` that uses plated to make sure the
-- recursion is handled correctly. As far as I can tell the other version does
-- not recurse properly onto the branches.
ifRewrite :: (Monad m, MonadGenBnd m, MonadError Error m, MonadReadEnvironment m) => Expression -> m Expression
ifRewrite = rewriteM $ \case
"ohua.lang/if" `Apply` cond `Apply` trueBranch `Apply` falseBranch
| Lambda trueIn trueBody <- trueBranch
, isUnit trueIn
, Lambda falseIn falseBody <- falseBranch
, isUnit falseIn -> do
ctrlTrue <- generateBindingWith "ctrlTrue"
ctrlFalse <- generateBindingWith "ctrlFalse"
trueBranch' <- liftIntoCtrlCtxt ctrlTrue trueBody
falseBranch' <- liftIntoCtrlCtxt ctrlFalse falseBody
ctrls <- generateBindingWith "ctrls"
trueResult <- generateBindingWith "trueResult"
falseResult <- generateBindingWith "falseResult"
result <- generateBindingWith "result"
return $ Just $
Let ctrls (Apply ifFunSf cond) $
mkDestructured [ctrlTrue, ctrlFalse] ctrls $
Let trueResult trueBranch' $
Let falseResult falseBranch' $
Let
result
(Apply (Apply (Apply selectSf cond) $ Var trueResult) $
Var falseResult) $
Var result
| otherwise -> throwError $ "Found if with unexpected, non-unit-lambda branch(es)\ntrue:\n " <> show trueBranch <> "\nfalse:\n" <> show falseBranch
where
-- This test needs to improve
isUnit = unwrap >>> T.isPrefixOf "_"
e -> pure Nothing
#else
ifRewrite (Let v a b) = Let v <$> ifRewrite a <*> ifRewrite b
ifRewrite (Lambda v e) = Lambda v <$> ifRewrite e
ifRewrite (Apply (Apply (Apply (Lit (FunRefLit (FunRef "ohua.lang/if" Nothing))) cond) trueBranch) falseBranch)
traceM $ " true branch : " < > ( show )
-- traceM $ "false branch: " <> (show falseBranch)
= do
trueBranch' <- ifRewrite trueBranch
falseBranch' <- ifRewrite falseBranch
-- post traversal transformation:
ctrlTrue <- generateBindingWith "ctrlTrue"
ctrlFalse <- generateBindingWith "ctrlFalse"
trueBranch'' <- liftIntoCtrlCtxt ctrlTrue trueBranch'
falseBranch'' <- liftIntoCtrlCtxt ctrlFalse falseBranch'
-- now these can become normal expressions
TODO match against " ( ) " - unit symbol for args
let ((_:[]), trueBranch''') = lambdaArgsAndBody trueBranch''
let ((_:[]), falseBranch''') = lambdaArgsAndBody falseBranch''
-- return $
-- [ohualang|
let ( $ var : ctrlTrue , $ var : ) = ohua.lang/ifFun $ var : cond in
let trueResult = $ expr : ' in
let falseResult = $ expr : falseBranch ' in
let result = ohua.lang/select cond trueResult falseResult in
-- result
-- |]
ctrls <- generateBindingWith "ctrls"
trueResult <- generateBindingWith "trueResult"
falseResult <- generateBindingWith "falseResult"
result <- generateBindingWith "result"
return $
Let ctrls (Apply ifFunSf cond) $
mkDestructured [ctrlTrue, ctrlFalse] ctrls $
Let trueResult trueBranch''' $
Let falseResult falseBranch''' $
Let
result
(Apply (Apply (Apply selectSf cond) $ Var trueResult) $
Var falseResult) $
Var result
ifRewrite e = return e
#endif
| null | https://raw.githubusercontent.com/ohua-dev/ohua-core/8fe0ee90f4a1aea0c5bfabe922b290fed668a7da/core/src/Ohua/ALang/Passes/If.hs | haskell | This is a proposal for `ifRewrite` that uses plated to make sure the
recursion is handled correctly. As far as I can tell the other version does
not recurse properly onto the branches.
This test needs to improve
traceM $ "false branch: " <> (show falseBranch)
post traversal transformation:
now these can become normal expressions
return $
[ohualang|
result
|] | |
Module : $ Header$
Description : Implementation of ALang transformation for If .
Copyright : ( c ) , 2018 . All Rights Reserved .
License : EPL-1.0
Maintainer : ,
Stability : experimental
Portability : portable
This source code is licensed under the terms described in the associated LICENSE.TXT file
= = Design :
We perform lambda lifting on both branches ( after normalization ):
@
let result = if cond
( \ ( ) - > f a b )
( \ ( ) - > g c d )
@
into :
@
let result = if cond
( \ ( ) - > let x = scope a b
in let nth 0 x
in let x1 = nth 1 x
in f x0 x1
( \ ( ) - > let x = scope c d
in let nth 0 x
in let x1 = nth 1 x
in g
The translation of ` if ` itself then produces the following code :
@
let cond : : = ...
let ncond : : Bool = not cond in
let : : Control Bool = ctrl cond in
let : : Control Bool = ctrl ncond in
let resultTrue : : Control a = ( \ ( ) - > ... true branch expression ... ) tBranchCtrl in
let resultFalse : : Control a = ( \ ( ) - > ... false branch expression ... ) fBranchCtrl in
let result : : a = select tBranchCtrl fBranchCtrl resultTrue resultFalse in
result
@
Currently , we can perform this transformation without type annotiations because of the following reasons :
1 . The ` Bool ` type of ` cond ` is verify by the ` not ` function which requires a ` Bool ` .
2 . The ` Control ` types can be easily found via checking the source of the local , i.e. , the binding that created the local .
Semantically , each branch runs in a ` Control ` context and as such that resulting value depends on
control value applied to this computation . The ` select ` then retrieves the final result using both control signals .
We finally simplify the ` select ` known that
1 . The ` ctrl ` calls will be removed by the lowering pass because its inputs are already of type ` Bool ` .
2 . The ` fBranchCtrl ` value is the negation of the ` tBranchCtrl ` value .
As such , we write :
@
let result : : a = select cond resultTrue resultFalse in ...
@
Note that we translate the applications ` ( \ ( ) - > ... branch ... ) ctrlVal ` into the following :
@
let x = scope ctrl a b in
...
let y = idependentFn ctrl in
...
@
In fact , this applies the control value to the lambda expression .
As a result , we can write the following :
@
let cond : : = ...
let ncond : : Bool = not cond in
let : : Control Bool = ctrl cond in
let : : Control Bool = ctrl ncond in
let resultTrue : : Control a = ... true branch expression ... in
let resultFalse : : Control a = ... false branch expression ... in
let result : : a = select tBranchCtrl fBranchCtrl resultTrue resultFalse in
result
@
Now this expression can be lowered to DFLang without any further ado .
The lowering itself should be sensitive to value of type ` Control ` and perform the
respective steps .
As a last step , we can optimize the DFLang expression to end up with :
@
let cond : : = ...
let ncond : : Bool = not cond in
let resultTrue : : Control a = ( \ ( ) - > ... true branch expression ... ) cond in
let resultFalse : : Control a = ( \ ( ) - > ... false branch expression ... ) ncond in
let result : : a = select cond resultTrue resultFalse in
result
@
Module : $Header$
Description : Implementation of ALang transformation for If.
Copyright : (c) Sebastian Ertel, Justus Adam 2018. All Rights Reserved.
License : EPL-1.0
Maintainer : ,
Stability : experimental
Portability : portable
This source code is licensed under the terms described in the associated LICENSE.TXT file
== Design:
We perform lambda lifting on both branches (after normalization):
@
let result = if cond
(\() -> f a b)
(\() -> g c d)
@
into:
@
let result = if cond
(\() -> let x = scope a b
in let x0 = nth 0 x
in let x1 = nth 1 x
in f x0 x1
(\() -> let x = scope c d
in let x0 = nth 0 x
in let x1 = nth 1 x
in g x0 x1
@
The translation of `if` itself then produces the following code:
@
let cond :: Bool = ...
let ncond :: Bool = not cond in
let tBranchCtrl :: Control Bool = ctrl cond in
let fBranchCtrl :: Control Bool = ctrl ncond in
let resultTrue :: Control a = (\() -> ... true branch expression ... ) tBranchCtrl in
let resultFalse :: Control a = (\() -> ... false branch expression ... ) fBranchCtrl in
let result :: a = select tBranchCtrl fBranchCtrl resultTrue resultFalse in
result
@
Currently, we can perform this transformation without type annotiations because of the following reasons:
1. The `Bool` type of `cond` is verify by the `not` function which requires a `Bool`.
2. The `Control` types can be easily found via checking the source of the local, i.e., the binding that created the local.
Semantically, each branch runs in a `Control` context and as such that resulting value depends on
control value applied to this computation. The `select` then retrieves the final result using both control signals.
We finally simplify the `select` known that
1. The `ctrl` calls will be removed by the lowering pass because its inputs are already of type `Bool`.
2. The `fBranchCtrl` value is the negation of the `tBranchCtrl` value.
As such, we write:
@
let result :: a = select cond resultTrue resultFalse in ...
@
Note that we translate the applications `(\() -> ... branch ...) ctrlVal` into the following:
@
let x = scope ctrl a b in
...
let y = idependentFn ctrl in
...
@
In fact, this applies the control value to the lambda expression.
As a result, we can write the following:
@
let cond :: Bool = ...
let ncond :: Bool = not cond in
let tBranchCtrl :: Control Bool = ctrl cond in
let fBranchCtrl :: Control Bool = ctrl ncond in
let resultTrue :: Control a = ... true branch expression ... in
let resultFalse :: Control a = ... false branch expression ... in
let result :: a = select tBranchCtrl fBranchCtrl resultTrue resultFalse in
result
@
Now this expression can be lowered to DFLang without any further ado.
The lowering itself should be sensitive to value of type `Control` and perform the
respective steps.
As a last step, we can optimize the DFLang expression to end up with:
@
let cond :: Bool = ...
let ncond :: Bool = not cond in
let resultTrue :: Control a = (\() -> ... true branch expression ... ) cond in
let resultFalse :: Control a = (\() -> ... false branch expression ... ) ncond in
let result :: a = select cond resultTrue resultFalse in
result
@
-}
# LANGUAGE CPP #
module Ohua.ALang.Passes.If where
import Ohua.Prelude
import Ohua.ALang.Lang
import Ohua.ALang.Passes.Control (liftIntoCtrlCtxt)
import qualified Ohua.ALang.Refs as Refs (ifFun, ifThenElse, select)
import Ohua.ALang.Util
( fromListToApply
, lambdaArgsAndBody
, lambdaLifting
, mkDestructured
)
import Ohua.Unit
import Control.Monad (foldM)
import Control.Category ((>>>))
import qualified Data.Text as T
selectSf :: Expression
selectSf = Lit $ FunRefLit $ FunRef Refs.select Nothing
ifFunSf :: Expression
ifFunSf = Lit $ FunRefLit $ FunRef "ohua.lang/ifFun" Nothing
#if 1
ifRewrite :: (Monad m, MonadGenBnd m, MonadError Error m, MonadReadEnvironment m) => Expression -> m Expression
ifRewrite = rewriteM $ \case
"ohua.lang/if" `Apply` cond `Apply` trueBranch `Apply` falseBranch
| Lambda trueIn trueBody <- trueBranch
, isUnit trueIn
, Lambda falseIn falseBody <- falseBranch
, isUnit falseIn -> do
ctrlTrue <- generateBindingWith "ctrlTrue"
ctrlFalse <- generateBindingWith "ctrlFalse"
trueBranch' <- liftIntoCtrlCtxt ctrlTrue trueBody
falseBranch' <- liftIntoCtrlCtxt ctrlFalse falseBody
ctrls <- generateBindingWith "ctrls"
trueResult <- generateBindingWith "trueResult"
falseResult <- generateBindingWith "falseResult"
result <- generateBindingWith "result"
return $ Just $
Let ctrls (Apply ifFunSf cond) $
mkDestructured [ctrlTrue, ctrlFalse] ctrls $
Let trueResult trueBranch' $
Let falseResult falseBranch' $
Let
result
(Apply (Apply (Apply selectSf cond) $ Var trueResult) $
Var falseResult) $
Var result
| otherwise -> throwError $ "Found if with unexpected, non-unit-lambda branch(es)\ntrue:\n " <> show trueBranch <> "\nfalse:\n" <> show falseBranch
where
isUnit = unwrap >>> T.isPrefixOf "_"
e -> pure Nothing
#else
ifRewrite (Let v a b) = Let v <$> ifRewrite a <*> ifRewrite b
ifRewrite (Lambda v e) = Lambda v <$> ifRewrite e
ifRewrite (Apply (Apply (Apply (Lit (FunRefLit (FunRef "ohua.lang/if" Nothing))) cond) trueBranch) falseBranch)
traceM $ " true branch : " < > ( show )
= do
trueBranch' <- ifRewrite trueBranch
falseBranch' <- ifRewrite falseBranch
ctrlTrue <- generateBindingWith "ctrlTrue"
ctrlFalse <- generateBindingWith "ctrlFalse"
trueBranch'' <- liftIntoCtrlCtxt ctrlTrue trueBranch'
falseBranch'' <- liftIntoCtrlCtxt ctrlFalse falseBranch'
TODO match against " ( ) " - unit symbol for args
let ((_:[]), trueBranch''') = lambdaArgsAndBody trueBranch''
let ((_:[]), falseBranch''') = lambdaArgsAndBody falseBranch''
let ( $ var : ctrlTrue , $ var : ) = ohua.lang/ifFun $ var : cond in
let trueResult = $ expr : ' in
let falseResult = $ expr : falseBranch ' in
let result = ohua.lang/select cond trueResult falseResult in
ctrls <- generateBindingWith "ctrls"
trueResult <- generateBindingWith "trueResult"
falseResult <- generateBindingWith "falseResult"
result <- generateBindingWith "result"
return $
Let ctrls (Apply ifFunSf cond) $
mkDestructured [ctrlTrue, ctrlFalse] ctrls $
Let trueResult trueBranch''' $
Let falseResult falseBranch''' $
Let
result
(Apply (Apply (Apply selectSf cond) $ Var trueResult) $
Var falseResult) $
Var result
ifRewrite e = return e
#endif
|
3728e81be797317607cef592e9ed2af1998647d4e04a251cb856c581b9c294f8 | sdiehl/arithmetic-circuits | Affine.hs | module Test.Circuit.Affine where
import Circuit.Affine
import qualified Data.Map as Map
import Protolude
import Test.Tasty.QuickCheck
-------------------------------------------------------------------------------
-- Generators
-------------------------------------------------------------------------------
arbAffineCircuit ::
Arbitrary f =>
Int ->
Int ->
Gen (AffineCircuit Int f)
arbAffineCircuit numVars size
| size <= 0 =
oneof $
[ ConstGate <$> arbitrary
]
++ if numVars > 0
then [Var <$> choose (0, numVars - 1)]
else []
| size > 0 =
oneof
[ ScalarMul <$> arbitrary <*> arbAffineCircuit numVars (size - 1),
Add <$> arbAffineCircuit numVars (size - 1)
<*> arbAffineCircuit numVars (size - 1)
]
arbInputVector :: Arbitrary f => Int -> Gen (Map Int f)
arbInputVector numVars = Map.fromList . zip [0 ..] <$> vector numVars
-- | The input vector has to have the correct length, so we want to
-- generate the program and the test input simultaneously.
data AffineCircuitWithInputs f = AffineCircuitWithInputs (AffineCircuit Int f) [Map Int f]
deriving (Show)
instance Arbitrary f => Arbitrary (AffineCircuitWithInputs f) where
arbitrary = do
numVars <- abs <$> arbitrary
program <- scale (`div` 7) $ sized (arbAffineCircuit numVars)
inputs <- vectorOf 10 $ arbInputVector numVars
pure $ AffineCircuitWithInputs program inputs
-------------------------------------------------------------------------------
-- Tests
-------------------------------------------------------------------------------
-- | Check that evaluating the vector representation of the circuit
-- yields the same results as evaluating the circuit "directly". Field
-- is instantiated as being the rationals for testing. It later should
probably be something like . Fr . Fr .
prop_affineCircuitToAffineMap ::
AffineCircuitWithInputs Rational -> Bool
prop_affineCircuitToAffineMap (AffineCircuitWithInputs program inputs) =
all testInput inputs
where
testInput input =
evalAffineCircuit Map.lookup input program
== evalAffineMap (affineCircuitToAffineMap program) input
| null | https://raw.githubusercontent.com/sdiehl/arithmetic-circuits/18e15deb2438287820664406c0840067c6ffa301/test/Test/Circuit/Affine.hs | haskell | -----------------------------------------------------------------------------
Generators
-----------------------------------------------------------------------------
| The input vector has to have the correct length, so we want to
generate the program and the test input simultaneously.
-----------------------------------------------------------------------------
Tests
-----------------------------------------------------------------------------
| Check that evaluating the vector representation of the circuit
yields the same results as evaluating the circuit "directly". Field
is instantiated as being the rationals for testing. It later should | module Test.Circuit.Affine where
import Circuit.Affine
import qualified Data.Map as Map
import Protolude
import Test.Tasty.QuickCheck
arbAffineCircuit ::
Arbitrary f =>
Int ->
Int ->
Gen (AffineCircuit Int f)
arbAffineCircuit numVars size
| size <= 0 =
oneof $
[ ConstGate <$> arbitrary
]
++ if numVars > 0
then [Var <$> choose (0, numVars - 1)]
else []
| size > 0 =
oneof
[ ScalarMul <$> arbitrary <*> arbAffineCircuit numVars (size - 1),
Add <$> arbAffineCircuit numVars (size - 1)
<*> arbAffineCircuit numVars (size - 1)
]
arbInputVector :: Arbitrary f => Int -> Gen (Map Int f)
arbInputVector numVars = Map.fromList . zip [0 ..] <$> vector numVars
data AffineCircuitWithInputs f = AffineCircuitWithInputs (AffineCircuit Int f) [Map Int f]
deriving (Show)
instance Arbitrary f => Arbitrary (AffineCircuitWithInputs f) where
arbitrary = do
numVars <- abs <$> arbitrary
program <- scale (`div` 7) $ sized (arbAffineCircuit numVars)
inputs <- vectorOf 10 $ arbInputVector numVars
pure $ AffineCircuitWithInputs program inputs
probably be something like . Fr . Fr .
prop_affineCircuitToAffineMap ::
AffineCircuitWithInputs Rational -> Bool
prop_affineCircuitToAffineMap (AffineCircuitWithInputs program inputs) =
all testInput inputs
where
testInput input =
evalAffineCircuit Map.lookup input program
== evalAffineMap (affineCircuitToAffineMap program) input
|
4c0cedb7c406ac5c2eaf067419345a1178c2e7732d8a0730f9b561b58577de5b | pjstadig/humane-test-output | reporting_test.cljc | (ns pjstadig.humane-test-output.reporting-test
(:require [cljs.test #?(:clj :refer :cljs :refer-macros) [deftest]]
#?@(:cljs [[pjstadig.util]
[pjstadig.print :as p]])))
#?(:cljs
(def report #'pjstadig.util/report-))
#?(:cljs
(deftest cljs-smoke-test
(report (p/convert-event {:type :fail
:expected '(= {:map "srt"} {:map 1})
:actual '(not (= {:map "srt"} {:map 1}))
:message "this is a smoke test"}))))
| null | https://raw.githubusercontent.com/pjstadig/humane-test-output/7c4c868aa9d7424248761941cd736ac0a5f4a75b/test/pjstadig/humane_test_output/reporting_test.cljc | clojure | (ns pjstadig.humane-test-output.reporting-test
(:require [cljs.test #?(:clj :refer :cljs :refer-macros) [deftest]]
#?@(:cljs [[pjstadig.util]
[pjstadig.print :as p]])))
#?(:cljs
(def report #'pjstadig.util/report-))
#?(:cljs
(deftest cljs-smoke-test
(report (p/convert-event {:type :fail
:expected '(= {:map "srt"} {:map 1})
:actual '(not (= {:map "srt"} {:map 1}))
:message "this is a smoke test"}))))
|
|
9319b31f8ea394118c054337ad9ffc7314517de9607c572f03f1c552d1056f5d | immutant/immutant | undertow.clj | Copyright 2014 - 2017 Red Hat , Inc , and individual contributors .
;;
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
;;
;; -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.
(ns immutant.web.undertow
"Advanced options specific to the Undertow web server used by Immutant"
(:require [immutant.util :refer (at-exit)]
[immutant.internal.util :refer (kwargs-or-map->map)]
[immutant.internal.options :refer (validate-options set-valid-options! opts->set coerce)]
[immutant.web.internal.undertow :refer (create-http-handler)]
[immutant.web.ssl :refer (keystore->ssl-context)])
(:import [io.undertow Undertow Undertow$Builder UndertowOptions]
io.undertow.server.HttpHandler
io.undertow.server.handlers.GracefulShutdownHandler
[org.xnio Options SslClientAuthMode]
[org.projectodd.wunderboss.web Web$CreateOption Web$RegisterOption]))
(defn ^HttpHandler http-handler
"Create an Undertow `HttpHandler` instance from a Ring handler function"
[handler]
(create-http-handler handler))
(defn ^HttpHandler graceful-shutdown
"Creates an `io.undertow.server.handlers/GracefulShutdownHandler`
with the passed `HttpHandler` and returns it, after adding an
`immutant.util/at-exit` fn that prohibits new requests while waiting
for pending ones to complete, up to a specified number of
milliseconds"
[^HttpHandler handler ^Long timeout]
(let [h (GracefulShutdownHandler. handler)]
(at-exit (fn []
(.shutdown h)
(.awaitShutdown h timeout)))
h))
(defn ^:no-doc tune
"Return the passed tuning options with an Undertow$Builder instance
set accordingly, mapped to :configuration in the return value"
[{:keys [configuration io-threads worker-threads buffer-size buffers-per-region direct-buffers?]
:as options}]
(let [^Undertow$Builder builder (or configuration (Undertow/builder))]
(-> options
(assoc :configuration
(cond-> builder
io-threads (.setIoThreads io-threads)
worker-threads (.setWorkerThreads worker-threads)
buffer-size (.setBufferSize buffer-size)
(not (nil? direct-buffers?)) (.setDirectBuffers direct-buffers?)))
(dissoc :io-threads :worker-threads :buffer-size :buffers-per-region :direct-buffers?))))
(defn ^:no-doc listen
"Return the passed listener-related options with an Undertow$Builder
instance set accordingly, mapped to :configuration in the return
value. If :ssl-port is non-nil, either :ssl-context or :key-managers
should be set, too"
[{:keys [configuration host port ssl-port ssl-context key-managers trust-managers ajp-port]
:or {host "localhost"}
:as options}]
(let [^Undertow$Builder builder (or configuration (Undertow/builder))]
(-> options
(assoc :configuration
(cond-> builder
(and ssl-port ssl-context) (.addHttpsListener ssl-port host ssl-context)
(and ssl-port (not ssl-context)) (.addHttpsListener ^int ssl-port ^String host ^"[Ljavax.net.ssl.KeyManager;" key-managers ^"[Ljavax.net.ssl.TrustManager;" trust-managers)
(and ajp-port) (.addAjpListener ajp-port host)
(and port) (.addHttpListener port host)))
(dissoc :ssl-port :ssl-context :key-managers :trust-managers :ajp-port))))
(defn ^:no-doc client-auth
"Possible values are :want or :need (:requested and :required are
also acceptable)"
[{:keys [configuration client-auth] :as options}]
(if client-auth
(let [^Undertow$Builder builder (or configuration (Undertow/builder))]
(-> options
(assoc :configuration
(case client-auth
(:want :requested) (.setSocketOption builder
Options/SSL_CLIENT_AUTH_MODE SslClientAuthMode/REQUESTED)
(:need :required) (.setSocketOption builder
Options/SSL_CLIENT_AUTH_MODE SslClientAuthMode/REQUIRED)))
(dissoc :client-auth)))
options))
(defn ^:no-doc http2
"Enables HTTP 2.0 support if :http2? option is truthy"
[{:keys [configuration http2?] :as options}]
(if http2?
(let [^Undertow$Builder builder (or configuration (Undertow/builder))]
(-> options
(assoc :configuration
(-> builder
(.setServerOption UndertowOptions/ENABLE_HTTP2 true)
(.setServerOption UndertowOptions/ENABLE_SPDY true)))
(dissoc :http2?)))
(dissoc options :http2?)))
(defn ^:no-doc ssl-context
"Assoc an SSLContext given a keystore and a truststore, which may be
either actual KeyStore instances, or paths to them. If truststore is
ommitted, the keystore is assumed to fulfill both roles"
[{:keys [keystore key-password truststore trust-password] :as options}]
(-> options
(assoc :ssl-context (keystore->ssl-context options))
(dissoc :keystore :key-password :truststore :trust-password)))
(def options
"Takes a map of Undertow-specific options and replaces them with an
`Undertow$Builder` instance associated with :configuration. Three
types of listeners are supported: :port (HTTP), :ssl-port (HTTPS), and
:ajp-port (AJP)
The following keyword options are supported:
* :configuration - the Builder that, if passed, will be used
Common to all listeners:
* :host - the interface listener bound to, defaults to \"localhost\"
HTTP:
* :port - a number, for a standard HTTP listener
AJP:
* :ajp-port - a number, for an Apache JServ Protocol listener
HTTPS:
* :ssl-port - a number, requires either :ssl-context, :keystore, or :key-managers
* :keystore - the filepath (a String) to the keystore
* :key-password - the password for the keystore
* :truststore - if separate from the keystore
* :trust-password - if :truststore passed
* :ssl-context - a valid javax.net.ssl.SSLContext
* :key-managers - a valid javax.net.ssl.KeyManager[]
* :trust-managers - a valid javax.net.ssl.TrustManager[]
* :client-auth - SSL client auth, may be :want or :need
* :http2? - whether to enable HTTP 2.0 support
Tuning:
* :io-threads - # threads handling IO, defaults to available processors
* :worker-threads - # threads invoking handlers, defaults to (* io-threads 8)
* :buffer-size - a number, defaults to 16k for modern servers
* :buffers-per-region - a number, defaults to 10
* :direct-buffers? - boolean, defaults to true"
(comp listen ssl-context client-auth tune http2
(partial coerce [:port :ajp-port :ssl-port :io-threads :worker-threads
:buffer-size :buffers-per-region :direct-buffers? :http2?])
#(validate-options % options)
kwargs-or-map->map (fn [& x] x)))
;;; take the valid options from the arglists of the composed functions
(def ^:private valid-options
(->> [#'listen #'ssl-context #'client-auth #'tune #'http2]
(map #(-> % meta :arglists ffirst :keys))
flatten
(map keyword)
set))
(set-valid-options! options valid-options)
(def ^:private non-wunderboss-options
(clojure.set/difference
valid-options
(opts->set Web$CreateOption Web$RegisterOption)))
(defn ^:no-doc ^:internal options-maybe
[opts]
(if (some non-wunderboss-options (keys opts))
(options opts)
opts))
| null | https://raw.githubusercontent.com/immutant/immutant/6ff8fa03acf73929f61f2ca75446cb559ddfc1ef/web/src/immutant/web/undertow.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
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.
take the valid options from the arglists of the composed functions | Copyright 2014 - 2017 Red Hat , Inc , and individual contributors .
distributed under the License is distributed on an " AS IS " BASIS ,
(ns immutant.web.undertow
"Advanced options specific to the Undertow web server used by Immutant"
(:require [immutant.util :refer (at-exit)]
[immutant.internal.util :refer (kwargs-or-map->map)]
[immutant.internal.options :refer (validate-options set-valid-options! opts->set coerce)]
[immutant.web.internal.undertow :refer (create-http-handler)]
[immutant.web.ssl :refer (keystore->ssl-context)])
(:import [io.undertow Undertow Undertow$Builder UndertowOptions]
io.undertow.server.HttpHandler
io.undertow.server.handlers.GracefulShutdownHandler
[org.xnio Options SslClientAuthMode]
[org.projectodd.wunderboss.web Web$CreateOption Web$RegisterOption]))
(defn ^HttpHandler http-handler
"Create an Undertow `HttpHandler` instance from a Ring handler function"
[handler]
(create-http-handler handler))
(defn ^HttpHandler graceful-shutdown
"Creates an `io.undertow.server.handlers/GracefulShutdownHandler`
with the passed `HttpHandler` and returns it, after adding an
`immutant.util/at-exit` fn that prohibits new requests while waiting
for pending ones to complete, up to a specified number of
milliseconds"
[^HttpHandler handler ^Long timeout]
(let [h (GracefulShutdownHandler. handler)]
(at-exit (fn []
(.shutdown h)
(.awaitShutdown h timeout)))
h))
(defn ^:no-doc tune
"Return the passed tuning options with an Undertow$Builder instance
set accordingly, mapped to :configuration in the return value"
[{:keys [configuration io-threads worker-threads buffer-size buffers-per-region direct-buffers?]
:as options}]
(let [^Undertow$Builder builder (or configuration (Undertow/builder))]
(-> options
(assoc :configuration
(cond-> builder
io-threads (.setIoThreads io-threads)
worker-threads (.setWorkerThreads worker-threads)
buffer-size (.setBufferSize buffer-size)
(not (nil? direct-buffers?)) (.setDirectBuffers direct-buffers?)))
(dissoc :io-threads :worker-threads :buffer-size :buffers-per-region :direct-buffers?))))
(defn ^:no-doc listen
"Return the passed listener-related options with an Undertow$Builder
instance set accordingly, mapped to :configuration in the return
value. If :ssl-port is non-nil, either :ssl-context or :key-managers
should be set, too"
[{:keys [configuration host port ssl-port ssl-context key-managers trust-managers ajp-port]
:or {host "localhost"}
:as options}]
(let [^Undertow$Builder builder (or configuration (Undertow/builder))]
(-> options
(assoc :configuration
(cond-> builder
(and ssl-port ssl-context) (.addHttpsListener ssl-port host ssl-context)
(and ssl-port (not ssl-context)) (.addHttpsListener ^int ssl-port ^String host ^"[Ljavax.net.ssl.KeyManager;" key-managers ^"[Ljavax.net.ssl.TrustManager;" trust-managers)
(and ajp-port) (.addAjpListener ajp-port host)
(and port) (.addHttpListener port host)))
(dissoc :ssl-port :ssl-context :key-managers :trust-managers :ajp-port))))
(defn ^:no-doc client-auth
"Possible values are :want or :need (:requested and :required are
also acceptable)"
[{:keys [configuration client-auth] :as options}]
(if client-auth
(let [^Undertow$Builder builder (or configuration (Undertow/builder))]
(-> options
(assoc :configuration
(case client-auth
(:want :requested) (.setSocketOption builder
Options/SSL_CLIENT_AUTH_MODE SslClientAuthMode/REQUESTED)
(:need :required) (.setSocketOption builder
Options/SSL_CLIENT_AUTH_MODE SslClientAuthMode/REQUIRED)))
(dissoc :client-auth)))
options))
(defn ^:no-doc http2
"Enables HTTP 2.0 support if :http2? option is truthy"
[{:keys [configuration http2?] :as options}]
(if http2?
(let [^Undertow$Builder builder (or configuration (Undertow/builder))]
(-> options
(assoc :configuration
(-> builder
(.setServerOption UndertowOptions/ENABLE_HTTP2 true)
(.setServerOption UndertowOptions/ENABLE_SPDY true)))
(dissoc :http2?)))
(dissoc options :http2?)))
(defn ^:no-doc ssl-context
"Assoc an SSLContext given a keystore and a truststore, which may be
either actual KeyStore instances, or paths to them. If truststore is
ommitted, the keystore is assumed to fulfill both roles"
[{:keys [keystore key-password truststore trust-password] :as options}]
(-> options
(assoc :ssl-context (keystore->ssl-context options))
(dissoc :keystore :key-password :truststore :trust-password)))
(def options
"Takes a map of Undertow-specific options and replaces them with an
`Undertow$Builder` instance associated with :configuration. Three
types of listeners are supported: :port (HTTP), :ssl-port (HTTPS), and
:ajp-port (AJP)
The following keyword options are supported:
* :configuration - the Builder that, if passed, will be used
Common to all listeners:
* :host - the interface listener bound to, defaults to \"localhost\"
HTTP:
* :port - a number, for a standard HTTP listener
AJP:
* :ajp-port - a number, for an Apache JServ Protocol listener
HTTPS:
* :ssl-port - a number, requires either :ssl-context, :keystore, or :key-managers
* :keystore - the filepath (a String) to the keystore
* :key-password - the password for the keystore
* :truststore - if separate from the keystore
* :trust-password - if :truststore passed
* :ssl-context - a valid javax.net.ssl.SSLContext
* :key-managers - a valid javax.net.ssl.KeyManager[]
* :trust-managers - a valid javax.net.ssl.TrustManager[]
* :client-auth - SSL client auth, may be :want or :need
* :http2? - whether to enable HTTP 2.0 support
Tuning:
* :io-threads - # threads handling IO, defaults to available processors
* :worker-threads - # threads invoking handlers, defaults to (* io-threads 8)
* :buffer-size - a number, defaults to 16k for modern servers
* :buffers-per-region - a number, defaults to 10
* :direct-buffers? - boolean, defaults to true"
(comp listen ssl-context client-auth tune http2
(partial coerce [:port :ajp-port :ssl-port :io-threads :worker-threads
:buffer-size :buffers-per-region :direct-buffers? :http2?])
#(validate-options % options)
kwargs-or-map->map (fn [& x] x)))
(def ^:private valid-options
(->> [#'listen #'ssl-context #'client-auth #'tune #'http2]
(map #(-> % meta :arglists ffirst :keys))
flatten
(map keyword)
set))
(set-valid-options! options valid-options)
(def ^:private non-wunderboss-options
(clojure.set/difference
valid-options
(opts->set Web$CreateOption Web$RegisterOption)))
(defn ^:no-doc ^:internal options-maybe
[opts]
(if (some non-wunderboss-options (keys opts))
(options opts)
opts))
|
461c6318f652515dd7e7c191aa334e21f5b9f075d0d8a13144ab4c77a9107dd3 | crategus/cl-cffi-gtk | glib.key-file.lisp | ;;; ----------------------------------------------------------------------------
;;; glib.key-value.lisp
;;;
The documentation of this file is taken from the GLib 2.64 Reference
Manual and modified to document the Lisp binding to the GLib library .
;;; See <>. The API documentation of the Lisp binding is
available from < -cffi-gtk/ > .
;;;
Copyright ( C ) 2020 - 2021
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Lesser General Public License for Lisp
as published by the Free Software Foundation , either version 3 of the
;;; License, or (at your option) any later version and with a preamble to
the GNU Lesser General Public License that clarifies the terms for use
;;; with Lisp programs and is referred as the LLGPL.
;;;
;;; 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 Lesser General Public License for more details .
;;;
You should have received a copy of the GNU Lesser General Public
License along with this program and the preamble to the Gnu Lesser
;;; General Public License. If not, see </>
;;; and <>.
;;; ----------------------------------------------------------------------------
;;;
;;; Key-value file parser
;;;
;;; parses .ini-like config files
;;;
;;; Types and Values
;;;
GKeyFile
;;;
;;; G_KEY_FILE_ERROR
;;;
GKeyFileError
;;;
;;; G_KEY_FILE_DESKTOP_GROUP
;;; G_KEY_FILE_DESKTOP_KEY_TYPE
;;; G_KEY_FILE_DESKTOP_KEY_VERSION
;;; G_KEY_FILE_DESKTOP_KEY_NAME
;;; G_KEY_FILE_DESKTOP_KEY_GENERIC_NAME
;;; G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY
;;; G_KEY_FILE_DESKTOP_KEY_COMMENT
;;; G_KEY_FILE_DESKTOP_KEY_ICON
;;; G_KEY_FILE_DESKTOP_KEY_HIDDEN
;;; G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN
;;; G_KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN
G_KEY_FILE_DESKTOP_KEY_TRY_EXEC
;;; G_KEY_FILE_DESKTOP_KEY_EXEC
;;; G_KEY_FILE_DESKTOP_KEY_PATH
G_KEY_FILE_DESKTOP_KEY_TERMINAL
;;; G_KEY_FILE_DESKTOP_KEY_MIME_TYPE
;;; G_KEY_FILE_DESKTOP_KEY_CATEGORIES
;;; G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY
;;; G_KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS
;;; G_KEY_FILE_DESKTOP_KEY_URL
;;; G_KEY_FILE_DESKTOP_KEY_ACTIONS
G_KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE
;;; G_KEY_FILE_DESKTOP_TYPE_APPLICATION
;;; G_KEY_FILE_DESKTOP_TYPE_LINK
;;;
;;; Functions
;;;
;;; g_key_file_new
;;; g_key_file_free
g_key_file_ref
;;; g_key_file_unref
;;; g_key_file_set_list_separator
;;; g_key_file_load_from_file
g_key_file_load_from_data
;;; g_key_file_load_from_bytes
;;; g_key_file_load_from_data_dirs
;;; g_key_file_load_from_dirs
;;; g_key_file_to_data
;;; g_key_file_save_to_file
;;; g_key_file_get_start_group
;;; g_key_file_get_groups
;;; g_key_file_get_keys
;;; g_key_file_has_group
;;; g_key_file_has_key
;;;
;;; g_key_file_get_value
;;; g_key_file_get_string
;;; g_key_file_get_locale_string
;;; g_key_file_get_locale_for_key
;;; g_key_file_get_integer
g_key_file_get_int64
;;; g_key_file_get_uint64
;;; g_key_file_get_double
;;; g_key_file_get_string_list
;;; g_key_file_get_locale_string_list
;;; g_key_file_get_boolean_list
;;; g_key_file_get_integer_list
;;; g_key_file_get_double_list
;;; g_key_file_get_comment
;;;
;;; g_key_file_set_value
;;; g_key_file_set_string
;;; g_key_file_set_locale_string
;;; g_key_file_set_boolean
;;; g_key_file_set_integer
;;; g_key_file_set_int64
;;; g_key_file_set_uint64
;;; g_key_file_set_double
;;; g_key_file_set_string_list
;;; g_key_file_set_locale_string_list
;;; g_key_file_set_boolean_list
;;; g_key_file_set_integer_list
;;; g_key_file_set_double_list
;;; g_key_file_set_comment
;;; g_key_file_remove_group
;;; g_key_file_remove_key
;;; g_key_file_remove_comment
;;; ----------------------------------------------------------------------------
(in-package :glib)
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_ERROR
;;;
;;; #define G_KEY_FILE_ERROR g_key_file_error_quark()
;;;
;;; Error domain for key file parsing. Errors in this domain will be from the
GKeyFileError enumeration .
;;;
See GError for information on error domains .
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
enum GKeyFileError
;;;
;;; typedef enum {
;;; G_KEY_FILE_ERROR_UNKNOWN_ENCODING,
G_KEY_FILE_ERROR_PARSE ,
;;; G_KEY_FILE_ERROR_NOT_FOUND,
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND,
;;; G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
G_KEY_FILE_ERROR_INVALID_VALUE
} GKeyFileError ;
;;;
;;; Error codes returned by key file parsing.
;;;
;;; G_KEY_FILE_ERROR_UNKNOWN_ENCODING
;;; the text being parsed was in an unknown encoding
;;;
;;; G_KEY_FILE_ERROR_PARSE
;;; document was ill-formed
;;;
;;; G_KEY_FILE_ERROR_NOT_FOUND
;;; the file was not found
;;;
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND
;;; a requested key was not found
;;;
;;; G_KEY_FILE_ERROR_GROUP_NOT_FOUND
;;; a requested group was not found
;;;
G_KEY_FILE_ERROR_INVALID_VALUE
;;; a value could not be parsed
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
enum
;;; ----------------------------------------------------------------------------
(defbitfield g-key-file-flags
(:none 0)
(:keep-comments #.(ash 1 0))
(:keep-translations #.(ash 1 1)))
#+cl-cffi-gtk-documentation
(setf (gethash 'g-key-file-flags atdoc:*symbol-name-alias*)
"Bitfield"
(gethash 'g-key-file-flags atdoc:*external-symbols*)
"@version{2021-8-13}
@begin{short}
Flags which influence the parsing of key values.
@end{short}
@begin{pre}
(defbitfield g-key-file-flags
(:none 0)
(:keep-comments #.(ash 1 0))
(:keep-translations #.(ash 1 1)))
@end{pre}
@begin[code]{table}
@entry[:none]{No flags, default behaviour.}
@entry[:keep-coments]{Use this flag if you plan to write the possibly
modified contents of the key file back to a file. Otherwise all comments
will be lost when the key file is written back.}
@entry[:keep-translations]{Use this flag if you plan to write the possibly
modified contents of the key file back to a file. Otherwise only the
translations for the current language will be written back.}
@end{table}
@see-type{g-key-file}")
(export 'g-key-file-flags)
;;; ----------------------------------------------------------------------------
GKeyFile
;;; ----------------------------------------------------------------------------
(defcstruct g-key-file)
#+cl-cffi-gtk-documentation
(setf (gethash 'g-key-file atdoc:*type-name-alias*)
"CStruct"
(documentation 'g-key-file 'type)
"@version{2021-8-13}
@begin{short}
The @sym{g-key-file} structure lets you parse, edit or create files
containing groups of key-value pairs, which we call key files for lack of a
better name.
@end{short}
Several freedesktop.org specifications use key files now, e.g. the Desktop
Entry Specification and the Icon Theme Specification.
The syntax of key files is described in detail in the Desktop Entry
Specification, here is a quick summary: Key files consists of groups of
key-value pairs, interspersed with comments.
@begin{pre}
# this is just an example
# there can be comments before the first group
[First Group]
Name=Key File Example this value shows escaping
# localized strings are stored in multiple key-value pairs
Welcome=Hello
Welcome[de]=Hallo
Welcome[fr_FR]=Bonjour
Welcome[it]=Ciao
Welcome[be@@latin]=Hello
[Another Group]
20;-200;0
Booleans=true;false;true;true
@end{pre}
Lines beginning with a @code{'#'} and blank lines are considered comments.
Groups are started by a header line containing the group name enclosed in
@code{'['} and @code{']'}, and ended implicitly by the start of the next group
or the end of the file. Each key-value pair must be contained in a group.
Key-value pairs generally have the form @code{key=value}, with the exception
of localized strings, which have the form @code{key[locale]=value}, with a
locale identifier of the form @code{lang_COUNTRYMODIFIER} where @code{COUNTRY}
and @code{MODIFIER} are optional. Space before and after the @code{'='}
character are ignored. Newline, tab, carriage return and backslash characters
in value are escaped as @code{\n}, @code{\t}, @code{\r}, and @code{\\},
respectively. To preserve leading spaces in values, these can also be escaped
as @code{\s}.
Key files can store strings, possibly with localized variants, integers,
booleans and lists of these. Lists are separated by a separator character,
typically @code{';'} or @code{','}. To use the list separator character in a
value in a list, it has to be escaped by prefixing it with a backslash.
This syntax is obviously inspired by the .ini files commonly met on Windows,
but there are some important differences:
@begin{itemize}
@item{.ini files use the @code{';'} character to begin comments, key files
use the @code{'#'} character.}
@item{Key files do not allow for ungrouped keys meaning only comments can
precede the first group.}
@item{Key files are always encoded in UTF-8.}
@item{Key and Group names are case-sensitive. For example, a group called
@code{[GROUP]} is a different from @code{[group]}.}
@item{.ini files do not have a strongly typed boolean entry type, they only
have @code{GetProfileInt()}. In key files, only true and false (in lower
case) are allowed.}
@end{itemize}
Note that in contrast to the Desktop Entry Specification, groups in key
files may contain the same key multiple times. The last entry wins. Key
files may also contain multiple groups with the same name. They are merged
together. Another difference is that keys and group names in key files are
not restricted to ASCII characters.
@begin[Examples]{dictionary}
Here is an example of loading a key file and reading a value:
@begin{pre}
(let ((keyfile (g-key-file-new)))
;; Load the key file
(unless (g-key-file-load-from-file keyfile \"rtest-glib-key-file.ini\" :none)
(error \"Error loading the key file: RTEST-GLIB-KEY-FILE.INI\"))
;; Read a string from the key file
(let ((value (g-key-file-string keyfile \"First Group\" \"Welcome\")))
(unless value
(setf value \"default-value\"))
... ))
@end{pre}
Here is an example of creating and saving a key file:
@begin{pre}
(let ((keyfile (g-key-file-new)))
;; Load existing key file
(g-key-file-load-from-file keyfile \"rtest-glib-key-file.ini\" :none)
Add a string to the First Group
(setf (g-key-file-string keyfile \"First Group\" \"SomeKey\") \"New Value\")
;; Save to a file
(unless (g-key-file-save-to-file keyfile \"rtest-glib-key-file-example.ini\")
(error \"Error saving key file.\"))
;; Or save to data for use elsewhere
(let ((data (g-key-file-to-data keyfile)))
(unless data
(error \"Error saving key file.\"))
... ))
@end{pre}
@end{dictionary}
@see-function{g-key-file-new}")
(export 'g-key-file)
;;; ----------------------------------------------------------------------------
;;; g_key_file_new ()
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_new" g-key-file-new) (:pointer (:struct g-key-file))
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@return{An empty @type{g-key-file} instance.}
@begin{short}
Creates a new empty @type{g-key-file} instance.
@end{short}
Use the functions @fun{g-key-file-load-from-file}, or
@fun{g-key-file-load-from-data} to read an existing key file.
@see-type{g-key-file}
@see-function{g-key-file-load-from-file}
@see-function{g-key-file-load-from-data}")
(export 'g-key-file-new)
;;; ----------------------------------------------------------------------------
;;; g_key_file_free ()
;;;
;;; void g_key_file_free (GKeyFile *key_file);
;;;
Clears all keys and groups from key_file , and decreases the reference count
by 1 . If the reference count reaches zero , frees the key file and all its
;;; allocated memory.
;;;
;;; key_file :
a GKeyFile
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
g_key_file_ref ( )
;;;
;;; GKeyFile * g_key_file_ref (GKeyFile *key_file);
;;;
Increases the reference count of key_file .
;;;
;;; key_file :
a GKeyFile
;;;
;;; Returns :
the same key_file .
;;;
Since 2.32
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_unref ()
;;;
;;; void g_key_file_unref (GKeyFile *key_file);
;;;
Decreases the reference count of key_file by 1 . If the reference count
reaches zero , frees the key file and all its allocated memory .
;;;
;;; key_file :
a GKeyFile
;;;
Since 2.32
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_list_separator ()
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_set_list_separator" %g-key-file-set-list-separator) :void
(keyfile (:pointer (:struct g-key-file)))
(separator :char))
(defun g-key-file-set-list-separator (keyfile separator)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[separator]{a char with the separator}
@begin{short}
Sets the character which is used to separate values in lists.
@end{short}
Typically @code{';'} or @code{','} are used as separators. The default list
separator is @code{';'}.
@see-type{g-key-file}"
(%g-key-file-set-list-separator keyfile (char-code separator)))
(export 'g-key-file-set-list-separator)
;;; ----------------------------------------------------------------------------
;;; g_key_file_load_from_file ()
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_load_from_file" %g-key-file-load-from-file) :boolean
(key-file (:pointer (:struct g-key-file)))
(filename :string)
(flags g-key-file-flags)
(err :pointer))
(defun g-key-file-load-from-file (keyfile filename flags)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[filename]{a string with the path of a filename to load}
@argument[flags]{flags from the @symbol{g-key-file-flags} flags}
@return{@em{True} if a key file could be loaded, @em{false} otherwise.}
@begin{short}
Loads a key file into a @type{g-key-file} instance.
@end{short}
If the file could not be loaded then @em{false} is returned.
@see-type{g-key-file}
@see-function{g-key-file-save-to-file}"
(with-g-error (err)
(%g-key-file-load-from-file keyfile filename flags err)))
(export 'g-key-file-load-from-file)
;;; ----------------------------------------------------------------------------
g_key_file_load_from_data ( )
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_load_from_data" %g-key-file-load-from-data) :boolean
(keyfile (:pointer (:struct g-key-file)))
(data :string)
(len g-size)
(flags g-key-file-flags)
(error :pointer))
(defun g-key-file-load-from-data (keyfile data flags)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[data]{a string with the key file loaded in memory}
@argument[flags]{flags from the @symbol{g-key-file-flags} flags}
@return{@em{True} if a key file could be loaded, otherwise @em{false}.}
@begin{short}
Loads a key file from memory into a @type{g-key-file} instance.
@end{short}
If the data cannot be loaded then @em{false} is returned.
@see-type{g-key-file}"
(with-ignore-g-error (err)
(%g-key-file-load-from-data keyfile data (length data) flags err)))
(export 'g-key-file-load-from-data)
;;; ----------------------------------------------------------------------------
;;; g_key_file_load_from_bytes ()
;;;
;;; gboolean
g_key_file_load_from_bytes ( GKeyFile * key_file ,
;;; GBytes *bytes,
flags ,
;;; GError **error);
;;;
Loads a key file from the data in bytes into an empty GKeyFile structure .
If the object can not be created then error is set to a GKeyFileError .
;;;
;;; key_file :
an empty GKeyFile struct
;;;
;;; bytes :
a GBytes
;;;
;;; flags ;
flags from
;;;
;;; error :
return location for a GError , or NULL
;;;
;;; Returns :
;;; TRUE if a key file could be loaded, FALSE otherwise
;;;
Since 2.50
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_load_from_data_dirs ()
;;;
gboolean g_key_file_load_from_data_dirs ( GKeyFile * key_file ,
;;; const gchar *file,
;;; gchar **full_path,
;;; GKeyFileFlags flags,
;;; GError **error);
;;;
;;; This function looks for a key file named file in the paths returned from
( ) and g_get_system_data_dirs ( ) , loads the file into
;;; key_file and returns the file's full path in full_path. If the file could
not be loaded then an error is set to either a GFileError or GKeyFileError .
;;;
;;; key_file :
an empty GKeyFile struct
;;;
;;; file :
;;; a relative path to a filename to open and parse. [type filename]
;;;
;;; full_path :
;;; return location for a string containing the full path of the file, or
;;; NULL.
;;;
;;; flags :
flags from
;;;
;;; error :
return location for a GError , or NULL
;;;
;;; Returns :
;;; TRUE if a key file could be loaded, FALSE othewise
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_load_from_dirs ()
;;;
gboolean g_key_file_load_from_dirs ( GKeyFile * key_file ,
;;; const gchar *file,
;;; const gchar **search_dirs,
;;; gchar **full_path,
;;; GKeyFileFlags flags,
;;; GError **error);
;;;
;;; This function looks for a key file named file in the paths specified in
search_dirs , loads the file into key_file and returns the file 's full path
;;; in full_path. If the file could not be loaded then an error is set to either
a GFileError or GKeyFileError .
;;;
;;; key_file :
an empty GKeyFile struct
;;;
;;; file :
;;; a relative path to a filename to open and parse
;;;
;;; search_dirs :
;;; NULL-terminated array of directories to search
;;;
;;; full_path :
;;; return location for a string containing the full path of the file,
;;; or NULL
;;;
;;; flags :
flags from
;;;
;;; error :
return location for a GError , or NULL
;;;
;;; Returns :
;;; TRUE if a key file could be loaded, FALSE otherwise
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_to_data ()
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_to_data" %g-key-file-to-data) :string
(keyfile (:pointer (:struct g-key-file)))
(len (:pointer g-size))
(error :pointer))
(defun g-key-file-to-data (keyfile)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@return{A string holding the contents of the key file.}
@begin{short}
Outputs the key file as a string.
@end{short}
@see-type{g-key-file}
@see-function{g-key-file-save-to-file}"
(with-g-error (err)
(with-foreign-object (len 'g-size)
(%g-key-file-to-data keyfile len err))))
(export 'g-key-file-to-data)
;;; ----------------------------------------------------------------------------
;;; g_key_file_save_to_file ()
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_save_to_file" %g-key-file-save-to-file) :boolean
(keyfile (:pointer (:struct g-key-file)))
(filename :string)
(err :pointer))
(defun g-key-file-save-to-file (keyfile filename)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[filename]{a string with the file to write to}
@return{@em{True} if successful, else @em{false}.}
@begin{short}
Writes the contents of the key file to a file.
@end{short}
@see-type{g-key-file}
@see-function{g-key-file-load-from-file}"
(with-g-error (err)
(%g-key-file-save-to-file keyfile filename err)))
(export 'g-key-file-save-to-file)
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_start_group () -> g-key-file-start-group
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_get_start_group" g-key-file-start-group) :string
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@return{A string with the start group of the key file.}
@begin{short}
Returns the name of the start group of the key file.
@end{short}
@see-type{g-key-file}"
(keyfile (:pointer (:struct g-key-file))))
(export 'g-key-file-start-group)
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_groups () -> g-key-file-groups
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_get_groups" %g-key-file-groups)
(g-strv :free-from-foreign t)
(keyfile (:pointer (:struct g-key-file)))
(len (:pointer g-size)))
(defun g-key-file-groups (keyfile)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@return{A list of strings.}
@begin{short}
Returns all groups in the key file loaded with @arg{keyfile}.
@end{short}
@see-type{g-key-file}"
(%g-key-file-groups keyfile (null-pointer)))
(export 'g-key-file-groups)
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_keys () -> g-key-file-keys
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_get_keys" %g-key-file-keys) (g-strv :free-from-foreign t)
(keyfile (:pointer (:struct g-key-file)))
(group :string)
(len (:pointer g-size))
(err :pointer))
(defun g-key-file-keys (keyfile group)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[group]{a string with the group name}
@return{A list of strings.}
@begin{short}
Returns all keys for the group name.
@end{short}
In the event that the group_name cannot be found, @code{nil} is returned.
@see-type{g-key-file}"
(with-g-error (err)
(%g-key-file-keys keyfile group (null-pointer) err)))
(export 'g-key-file-keys)
;;; ----------------------------------------------------------------------------
;;; g_key_file_has_group ()
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_has_group" g-key-file-has-group) :boolean
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[group]{a string with the group name}
@return{@em{True} if @arg{group} is a part of @arg{keyfile}, @em{false}
otherwise.}
@begin{short}
Looks whether the key file has the group @arg{group}.
@end{short}
@see-type{g-key-file}"
(keyfile (:pointer (:struct g-key-file)))
(group :string))
(export 'g-key-file-has-group)
;;; ----------------------------------------------------------------------------
;;; g_key_file_has_key ()
;;; ----------------------------------------------------------------------------
(defcfun ("g_key_file_has_key" %g-key-file-has-key) :boolean
(keyfile (:pointer (:struct g-key-file)))
(group :string)
(key :string)
(err :pointer))
(defun g-key-file-has-key (keyfile group key)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[group]{a string with the group name}
@argument[key]{a string with the key name}
@return{@em{True} if @arg{key} is a part of @arg{group}, @em{false}
otherwise.}
@begin{short}
Looks whether the key file has the key @arg{key} in the group
@arg{group}.
@end{short}
@see-type{g-key-file}"
(with-g-error (err)
(%g-key-file-has-key keyfile group key err)))
(export 'g-key-file-has-key)
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_value ()
;;;
gchar * g_key_file_get_value ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; GError **error);
;;;
;;; Returns the raw value associated with key under group_name. Use
;;; g_key_file_get_string() to retrieve an unescaped UTF-8 string.
;;;
;;; In the event the key cannot be found, NULL is returned and error is set to
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be
;;; found, NULL is returned and error is set to
;;; G_KEY_FILE_ERROR_GROUP_NOT_FOUND.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; error :
return location for a GError , or NULL
;;;
;;; Returns :
;;; a newly allocated string or NULL if the specified key cannot be found.
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_string ()
;;; g_key_file_set_string () -> g-key-file-string
;;; ----------------------------------------------------------------------------
(defun (setf g-key-file-string) (value keyfile group key)
(foreign-funcall "g_key_file_set_string"
(:pointer (:struct g-key-file)) keyfile
:string group
:string key
:string value
:void)
value)
(defcfun ("g_key_file_get_string" %g-key-file-string) :string
(keyfile (:pointer (:struct g-key-file)))
(group :string)
(key :string)
(err :pointer))
(defun g-key-file-string (keyfile group key)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@syntax[]{(g-key-file-string keyfile) => value}
@syntax[]{(setf (g-key-file-string keyfile) value)}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[group]{a string with the group name}
@argument[key]{a string with the key name}
@argument[value]{a string or @code{nil}}
@begin{short}
The function @sym{g-key-file-string} returns the string value associated
with @arg{key} under @arg{group}.
@end{short}
In the event the key or the group name cannot be found, @code{nil} is
returned.
The function @sym{(setf g-key-file-string)} associates a new string value with
@arg{key} under @arg{group}. If @arg{key} or @arg{group} cannot be found then
they are created.
Unlike the function @fun{g-key-file-value}, this function handles characters
that need escaping, such as newlines.
@see-type{g-key-file}"
(with-g-error (err)
(%g-key-file-string keyfile group key err)))
(export 'g-key-file-string)
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_locale_string ()
;;;
gchar * g_key_file_get_locale_string ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; const gchar *locale,
GError * * error ) ;
;;;
;;; Returns the value associated with key under group_name translated in the
;;; given locale if available. If locale is NULL then the current locale is
;;; assumed.
;;;
;;; If key cannot be found then NULL is returned and error is set to
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND. If the value associated with key cannot be
;;; interpreted or no suitable translation can be found then the untranslated
;;; value is returned.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; locale :
;;; a locale identifier or NULL. [allow-none]
;;;
;;; error :
return location for a GError , or NULL
;;;
;;; Returns :
;;; a newly allocated string or NULL if the specified key cannot be found.
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_locale_for_key ()
;;;
;;; gchar *
g_key_file_get_locale_for_key ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; const gchar *locale);
;;;
;;; Returns the actual locale which the result of g_key_file_get_locale_string()
or g_key_file_get_locale_string_list ( ) came from .
;;;
;;; If calling g_key_file_get_locale_string() or
g_key_file_get_locale_string_list ( ) with exactly the same key_file ,
;;; group_name , key and locale , the result of those functions will have
;;; originally been tagged with the locale that is the result of this function.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; locale :
;;; a locale identifier or NULL.
;;;
;;; Returns :
;;; the locale from the file, or NULL if the key was not found or the entry
;;; in the file was was untranslated.
;;;
Since 2.56
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
( )
;;;
( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; GError **error);
;;;
;;; Returns the value associated with key under group_name as a boolean.
;;;
;;; If key cannot be found then FALSE is returned and error is set to
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key
;;; cannot be interpreted as a boolean then FALSE is returned and error is set
to G_KEY_FILE_ERROR_INVALID_VALUE .
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
;;; the value associated with the key as a boolean, or FALSE if the key was
;;; not found or could not be parsed.
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_integer ()
;;;
gint g_key_file_get_integer ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; GError **error);
;;;
;;; Returns the value associated with key under group_name as an integer.
;;;
;;; If key cannot be found then 0 is returned and error is set to
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key
;;; cannot be interpreted as an integer then 0 is returned and error is set to
G_KEY_FILE_ERROR_INVALID_VALUE .
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
;;; the value associated with the key as an integer, or 0 if the key was not
;;; found or could not be parsed.
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
g_key_file_get_int64 ( )
;;;
gint64 g_key_file_get_int64 ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; GError **error);
;;;
Returns the value associated with key under group_name as a signed 64 - bit
integer . This is similar to g_key_file_get_integer ( ) but can return 64 - bit
;;; results without truncation.
;;;
;;; key_file :
a non - NULL GKeyFile
;;;
;;; group_name :
;;; a non-NULL group name
;;;
;;; key :
;;; a non-NULL key
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
the value associated with the key as a signed 64 - bit integer , or 0 if
;;; the key was not found or could not be parsed.
;;;
Since 2.26
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_uint64 ()
;;;
guint64 g_key_file_get_uint64 ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
GError * * error ) ;
;;;
;;; Returns the value associated with key under group_name as an unsigned
64 - bit integer . This is similar to g_key_file_get_integer ( ) but can return
;;; large positive results without truncation.
;;;
;;; key_file :
a non - NULL GKeyFile
;;;
;;; group_name :
;;; a non-NULL group name
;;;
;;; key :
;;; a non-NULL key
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
the value associated with the key as an unsigned 64 - bit integer , or 0
;;; if the key was not found or could not be parsed.
;;;
Since 2.26
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_double ()
;;;
gdouble g_key_file_get_double ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
GError * * error ) ;
;;;
;;; Returns the value associated with key under group_name as a double. If
;;; group_name is NULL, the start_group is used.
;;;
If key can not be found then 0.0 is returned and error is set to
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key
can not be interpreted as a double then 0.0 is returned and error is set to
G_KEY_FILE_ERROR_INVALID_VALUE .
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
the value associated with the key as a double , or 0.0 if the key was not
;;; found or could not be parsed.
;;;
Since 2.12
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_string_list ()
;;;
gchar * * g_key_file_get_string_list ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; gsize *length,
GError * * error ) ;
;;;
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; length :
;;; return location for the number of returned strings, or NULL
;;;
;;; error :
return location for a GError , or NULL
;;;
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_string_list ()
;;;
void g_key_file_set_string_list ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; const gchar * const list[],
;;; gsize length);
;;;
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; list :
;;; an array of string values
;;;
;;; length :
;;; number of string values in list
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
(defun (setf g-key-file-string-list) (value keyfile group key)
(foreign-funcall "g_key_file_set_string_list"
(:pointer (:struct g-key-file)) keyfile
:string group
:string key
g-strv value
g-size (length value)
:void)
value)
(defcfun ("g_key_file_get_string_list" %g-key-file-string-list) g-strv
(keyfile (:pointer (:struct g-key-file)))
(group :string)
(key :string)
(len (:pointer g-size))
(err :pointer))
(defun g-key-file-string-list (keyfile group key)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@syntax[]{(g-key-file-string-list keyfile) => value}
@syntax[]{(setf (g-key-file-string-list keyfile) value)}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[group]{a string with the group name}
@argument[key]{a string with the key name}
@argument[value]{a list of strings}
@begin{short}
The function @sym{g-key-file-string-list} returns the values associated with
@arg{key} under @arg{group}.
@end{short}
In the event the key or the group name cannot be found, @code{nil} is
returned.
The function @sym{(setf g-key-file-string-list} associates a list of string
values for @arg{key} under @arg{group}. If @arg{key} or @arg{group} cannot be
found then they are created.
@see-type{g-key-file}"
(with-g-error (err)
(with-foreign-object (len 'g-size)
(%g-key-file-string-list keyfile group key len err))))
(export 'g-key-file-string-list)
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_locale_string_list ()
;;;
gchar * * g_key_file_get_locale_string_list ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; const gchar *locale,
;;; gsize *length,
;;; GError **error);
;;;
;;; Returns the values associated with key under group_name translated in the
;;; given locale if available. If locale is NULL then the current locale is
;;; assumed.
;;;
;;; If key cannot be found then NULL is returned and error is set to
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND. If the values associated with key cannot be
;;; interpreted or no suitable translations can be found then the untranslated
;;; values are returned. The returned array is NULL-terminated, so length may
;;; optionally be NULL.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; locale :
;;; a locale identifier or NULL
;;;
;;; length :
;;; return location for the number of returned strings or NULL
;;;
;;; error :
return location for a GError or NULL
;;;
;;; Returns :
;;; a newly allocated NULL-terminated string array or NULL if the key isn't
found . The string array should be freed with ( ) .
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_boolean_list ()
;;;
gboolean * g_key_file_get_boolean_list ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; gsize *length,
;;; GError **error);
;;;
;;; Returns the values associated with key under group_name as booleans.
;;;
;;; If key cannot be found then NULL is returned and error is set to
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key
;;; cannot be interpreted as booleans then NULL is returned and error is set to
G_KEY_FILE_ERROR_INVALID_VALUE .
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; length :
;;; the number of booleans returned. [out]
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
;;; the values associated with the key as a list of booleans, or NULL if the
;;; key was not found or could not be parsed. The returned list of booleans
;;; should be freed with g_free() when no longer needed.
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_integer_list ()
;;;
gint * g_key_file_get_integer_list ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; gsize *length,
;;; GError **error);
;;;
;;; Returns the values associated with key under group_name as integers.
;;;
;;; If key cannot be found then NULL is returned and error is set to
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key
;;; cannot be interpreted as integers then NULL is returned and error is set to
G_KEY_FILE_ERROR_INVALID_VALUE .
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; length :
;;; the number of integers returned. [out]
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
;;; the values associated with the key as a list of integers, or NULL if the
;;; key was not found or could not be parsed. The returned list of integers
;;; should be freed with g_free() when no longer needed.
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_double_list ()
;;;
gdouble * g_key_file_get_double_list ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; gsize *length,
GError * * error ) ;
;;;
;;; Returns the values associated with key under group_name as doubles.
;;;
;;; If key cannot be found then NULL is returned and error is set to
;;; G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key
;;; cannot be interpreted as doubles then NULL is returned and error is set to
G_KEY_FILE_ERROR_INVALID_VALUE .
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; length :
;;; the number of doubles returned. [out]
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
;;; the values associated with the key as a list of doubles, or NULL if the
;;; key was not found or could not be parsed. The returned list of doubles
;;; should be freed with g_free() when no longer needed.
;;;
Since 2.12
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_get_comment ()
;;;
gchar * g_key_file_get_comment ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; GError **error);
;;;
;;; Retrieves a comment above key from group_name. If key is NULL then comment
;;; will be read from above group_name. If both key and group_name are NULL,
then comment will be read from above the first group in the file .
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name, or NULL. [allow-none]
;;;
;;; key :
;;; a key
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
;;; a comment that should be freed with g_free()
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_value ()
;;;
void g_key_file_set_value ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; const gchar *value);
;;;
;;; Associates a new value with key under group_name.
;;;
;;; If key cannot be found then it is created. If group_name cannot be found
then it is created . To set an UTF-8 string which may contain characters that
;;; need escaping (such as newlines or spaces), use g_key_file_set_string().
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; value :
;;; a string
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_locale_string ()
;;;
void g_key_file_set_locale_string ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; const gchar *locale,
;;; const gchar *string);
;;;
;;; Associates a string value for key and locale under group_name. If the
;;; translation for key cannot be found then it is created.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; locale :
;;; a locale identifier
;;;
;;; string :
;;; a string
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_boolean ()
;;;
void g_key_file_set_boolean ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; gboolean value);
;;;
;;; Associates a new boolean value with key under group_name. If key cannot be
;;; found then it is created.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; value :
;;; TRUE or FALSE
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_integer ()
;;;
void g_key_file_set_integer ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; gint value);
;;;
;;; Associates a new integer value with key under group_name. If key cannot be
;;; found then it is created.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; value :
;;; an integer value
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_int64 ()
;;;
void g_key_file_set_int64 ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; gint64 value);
;;;
;;; Associates a new integer value with key under group_name. If key cannot be
;;; found then it is created.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; value :
;;; an integer value
;;;
Since 2.26
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_uint64 ()
;;;
void g_key_file_set_uint64 ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
guint64 value ) ;
;;;
;;; Associates a new integer value with key under group_name. If key cannot be
;;; found then it is created.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; value :
;;; an integer value
;;;
Since 2.26
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_double ()
;;;
void g_key_file_set_double ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; gdouble value);
;;;
;;; Associates a new double value with key under group_name. If key cannot be
;;; found then it is created.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; value :
;;; an double value
;;;
Since 2.12
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_locale_string_list ()
;;;
void g_key_file_set_locale_string_list ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; const gchar *locale,
;;; const gchar * const list[],
;;; gsize length);
;;;
;;; Associates a list of string values for key and locale under group_name. If
;;; the translation for key cannot be found then it is created.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; locale :
;;; a locale identifier
;;;
;;; list :
;;; a NULL-terminated array of locale string values
;;;
;;; length :
;;; the length of list
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_boolean_list ()
;;;
void ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
list [ ] ,
;;; gsize length);
;;;
;;; Associates a list of boolean values with key under group_name. If key cannot
;;; be found then it is created. If group_name is NULL, the start_group is used.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; list :
;;; an array of boolean values. [array length=length]
;;;
;;; length :
;;; length of list
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_integer_list ()
;;;
void g_key_file_set_integer_list ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; gint list[],
;;; gsize length);
;;;
;;; Associates a list of integer values with key under group_name. If key cannot
;;; be found then it is created.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; list :
;;; an array of integer values. [array length=length]
;;;
;;; length :
;;; number of integer values in list
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_double_list ()
;;;
void g_key_file_set_double_list ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; gdouble list[],
;;; gsize length);
;;;
;;; Associates a list of double values with key under group_name. If key cannot
;;; be found then it is created.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key
;;;
;;; list :
;;; an array of double values. [array length=length]
;;;
;;; length :
;;; number of double values in list
;;;
Since 2.12
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_set_comment ()
;;;
gboolean g_key_file_set_comment ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; const gchar *comment,
;;; GError **error);
;;;
;;; Places a comment above key from group_name. If key is NULL then comment will
;;; be written above group_name. If both key and group_name are NULL, then
comment will be written above the first group in the file .
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name, or NULL. [allow-none]
;;;
;;; key :
;;; a key. [allow-none]
;;;
;;; comment :
;;; a comment
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
;;; TRUE if the comment was written, FALSE otherwise
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_remove_group ()
;;;
gboolean g_key_file_remove_group ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; GError **error);
;;;
;;; Removes the specified group, group_name, from the key file.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; error :
return location for a GError or NULL
;;;
;;; Returns :
;;; TRUE if the group was removed, FALSE otherwise
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_remove_key ()
;;;
gboolean g_key_file_remove_key ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; GError **error);
;;;
;;; Removes key in group_name from the key file.
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name
;;;
;;; key :
;;; a key name to remove
;;;
;;; error :
return location for a GError or NULL
;;;
;;; Returns :
;;; TRUE if the key was removed, FALSE otherwise
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; g_key_file_remove_comment ()
;;;
gboolean g_key_file_remove_comment ( GKeyFile * key_file ,
;;; const gchar *group_name,
;;; const gchar *key,
;;; GError **error);
;;;
;;; Removes a comment above key from group_name. If key is NULL then comment
;;; will be removed above group_name. If both key and group_name are NULL, then
comment will be removed above the first group in the file .
;;;
;;; key_file :
a GKeyFile
;;;
;;; group_name :
;;; a group name, or NULL. [allow-none]
;;;
;;; key :
;;; a key. [allow-none]
;;;
;;; error :
return location for a GError
;;;
;;; Returns :
;;; TRUE if the comment was removed, FALSE otherwise
;;;
Since 2.6
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_GROUP
;;;
;;; #define G_KEY_FILE_DESKTOP_GROUP "Desktop Entry"
;;;
;;; The name of the main group of a desktop entry file, as defined in the
;;; Desktop Entry Specification. Consult the specification for more details
;;; about the meanings of the keys below.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_TYPE
;;;
;;; #define G_KEY_FILE_DESKTOP_KEY_TYPE "Type"
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string giving the
type of the desktop entry . Usually ,
G_KEY_FILE_DESKTOP_TYPE_LINK , or .
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_VERSION
;;;
# define G_KEY_FILE_DESKTOP_KEY_VERSION " Version "
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string giving the
version of the Desktop Entry Specification used for the desktop entry file .
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_NAME
;;;
# define G_KEY_FILE_DESKTOP_KEY_NAME " Name "
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a localized string
;;; giving the specific name of the desktop entry.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_GENERIC_NAME
;;;
;;; #define G_KEY_FILE_DESKTOP_KEY_GENERIC_NAME "GenericName"
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a localized string
;;; giving the generic name of the desktop entry.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY
;;;
;;; #define G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY "NoDisplay"
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating
;;; whether the desktop entry should be shown in menus.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_COMMENT
;;;
;;; #define G_KEY_FILE_DESKTOP_KEY_COMMENT "Comment"
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a localized string
;;; giving the tooltip for the desktop entry.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_ICON
;;;
# define G_KEY_FILE_DESKTOP_KEY_ICON " Icon "
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a localized string
;;; giving the name of the icon to be displayed for the desktop entry.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_HIDDEN
;;;
;;; #define G_KEY_FILE_DESKTOP_KEY_HIDDEN "Hidden"
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating
;;; whether the desktop entry has been deleted by the user.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN
;;;
# define G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN " OnlyShowIn "
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a list of strings
;;; identifying the environments that should display the desktop entry.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN
;;;
# define G_KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN " NotShowIn "
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a list of strings
;;; identifying the environments that should not display the desktop entry.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_TRY_EXEC
;;;
# define G_KEY_FILE_DESKTOP_KEY_TRY_EXEC " TryExec "
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string giving the
;;; file name of a binary on disk used to determine if the program is actually
;;; installed. It is only valid for desktop entries with the Application type.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_EXEC
;;;
# define G_KEY_FILE_DESKTOP_KEY_EXEC " Exec "
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string giving the
;;; command line to execute. It is only valid for desktop entries with the
;;; Application type.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_PATH
;;;
;;; #define G_KEY_FILE_DESKTOP_KEY_PATH "Path"
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string containing
;;; the working directory to run the program in. It is only valid for desktop
;;; entries with the Application type.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_TERMINAL
;;;
# define G_KEY_FILE_DESKTOP_KEY_TERMINAL " Terminal "
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating
;;; whether the program should be run in a terminal window. It is only valid
;;; for desktop entries with the Application type.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_MIME_TYPE
;;;
# define G_KEY_FILE_DESKTOP_KEY_MIME_TYPE " MimeType "
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a list of strings
;;; giving the MIME types supported by this desktop entry.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_CATEGORIES
;;;
;;; #define G_KEY_FILE_DESKTOP_KEY_CATEGORIES "Categories"
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a list of strings
;;; giving the categories in which the desktop entry should be shown in a menu.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY
;;;
;;; #define G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY "StartupNotify"
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating
whether the application supports the Startup Notification Protocol
Specification .
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS
;;;
# define G_KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS " StartupWMClass "
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is string identifying the
;;; WM class or name hint of a window that the application will create, which
can be used to emulate Startup Notification with older applications .
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_KEY_URL
;;;
;;; #define G_KEY_FILE_DESKTOP_KEY_URL "URL"
;;;
;;; A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string giving the
;;; URL to access. It is only valid for desktop entries with the Link type.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_TYPE_APPLICATION
;;;
;;; #define G_KEY_FILE_DESKTOP_TYPE_APPLICATION "Application"
;;;
The value of the G_KEY_FILE_DESKTOP_KEY_TYPE , key for desktop entries
;;; representing applications.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; G_KEY_FILE_DESKTOP_TYPE_LINK
;;;
;;; #define G_KEY_FILE_DESKTOP_TYPE_LINK "Link"
;;;
The value of the G_KEY_FILE_DESKTOP_KEY_TYPE , key for desktop entries
;;; representing links to documents.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;;
# define " Directory "
;;;
The value of the G_KEY_FILE_DESKTOP_KEY_TYPE , key for desktop entries
;;; representing directories.
;;;
Since 2.14
;;; ----------------------------------------------------------------------------
--- End of file ----------------------------------------
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/74a78a6912a96f982644f3ee5ab7b8396cc2235f/glib/glib.key-file.lisp | lisp | ----------------------------------------------------------------------------
glib.key-value.lisp
See <>. The API documentation of the Lisp binding is
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License for Lisp
License, or (at your option) any later version and with a preamble to
with Lisp programs and is referred as the LLGPL.
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
General Public License. If not, see </>
and <>.
----------------------------------------------------------------------------
Key-value file parser
parses .ini-like config files
Types and Values
G_KEY_FILE_ERROR
G_KEY_FILE_DESKTOP_GROUP
G_KEY_FILE_DESKTOP_KEY_TYPE
G_KEY_FILE_DESKTOP_KEY_VERSION
G_KEY_FILE_DESKTOP_KEY_NAME
G_KEY_FILE_DESKTOP_KEY_GENERIC_NAME
G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY
G_KEY_FILE_DESKTOP_KEY_COMMENT
G_KEY_FILE_DESKTOP_KEY_ICON
G_KEY_FILE_DESKTOP_KEY_HIDDEN
G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN
G_KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN
G_KEY_FILE_DESKTOP_KEY_EXEC
G_KEY_FILE_DESKTOP_KEY_PATH
G_KEY_FILE_DESKTOP_KEY_MIME_TYPE
G_KEY_FILE_DESKTOP_KEY_CATEGORIES
G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY
G_KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS
G_KEY_FILE_DESKTOP_KEY_URL
G_KEY_FILE_DESKTOP_KEY_ACTIONS
G_KEY_FILE_DESKTOP_TYPE_APPLICATION
G_KEY_FILE_DESKTOP_TYPE_LINK
Functions
g_key_file_new
g_key_file_free
g_key_file_unref
g_key_file_set_list_separator
g_key_file_load_from_file
g_key_file_load_from_bytes
g_key_file_load_from_data_dirs
g_key_file_load_from_dirs
g_key_file_to_data
g_key_file_save_to_file
g_key_file_get_start_group
g_key_file_get_groups
g_key_file_get_keys
g_key_file_has_group
g_key_file_has_key
g_key_file_get_value
g_key_file_get_string
g_key_file_get_locale_string
g_key_file_get_locale_for_key
g_key_file_get_integer
g_key_file_get_uint64
g_key_file_get_double
g_key_file_get_string_list
g_key_file_get_locale_string_list
g_key_file_get_boolean_list
g_key_file_get_integer_list
g_key_file_get_double_list
g_key_file_get_comment
g_key_file_set_value
g_key_file_set_string
g_key_file_set_locale_string
g_key_file_set_boolean
g_key_file_set_integer
g_key_file_set_int64
g_key_file_set_uint64
g_key_file_set_double
g_key_file_set_string_list
g_key_file_set_locale_string_list
g_key_file_set_boolean_list
g_key_file_set_integer_list
g_key_file_set_double_list
g_key_file_set_comment
g_key_file_remove_group
g_key_file_remove_key
g_key_file_remove_comment
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_ERROR
#define G_KEY_FILE_ERROR g_key_file_error_quark()
Error domain for key file parsing. Errors in this domain will be from the
----------------------------------------------------------------------------
----------------------------------------------------------------------------
typedef enum {
G_KEY_FILE_ERROR_UNKNOWN_ENCODING,
G_KEY_FILE_ERROR_NOT_FOUND,
G_KEY_FILE_ERROR_KEY_NOT_FOUND,
G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
Error codes returned by key file parsing.
G_KEY_FILE_ERROR_UNKNOWN_ENCODING
the text being parsed was in an unknown encoding
G_KEY_FILE_ERROR_PARSE
document was ill-formed
G_KEY_FILE_ERROR_NOT_FOUND
the file was not found
G_KEY_FILE_ERROR_KEY_NOT_FOUND
a requested key was not found
G_KEY_FILE_ERROR_GROUP_NOT_FOUND
a requested group was not found
a value could not be parsed
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-200;0
false;true;true
'} or @code{','}. To use the list separator character in a
'} character to begin comments, key files
Load the key file
Read a string from the key file
Load existing key file
Save to a file
Or save to data for use elsewhere
----------------------------------------------------------------------------
g_key_file_new ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_free ()
void g_key_file_free (GKeyFile *key_file);
allocated memory.
key_file :
----------------------------------------------------------------------------
----------------------------------------------------------------------------
GKeyFile * g_key_file_ref (GKeyFile *key_file);
key_file :
Returns :
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_unref ()
void g_key_file_unref (GKeyFile *key_file);
key_file :
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_list_separator ()
----------------------------------------------------------------------------
'} or @code{','} are used as separators. The default list
'}.
----------------------------------------------------------------------------
g_key_file_load_from_file ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_load_from_bytes ()
gboolean
GBytes *bytes,
GError **error);
key_file :
bytes :
flags ;
error :
Returns :
TRUE if a key file could be loaded, FALSE otherwise
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_load_from_data_dirs ()
const gchar *file,
gchar **full_path,
GKeyFileFlags flags,
GError **error);
This function looks for a key file named file in the paths returned from
key_file and returns the file's full path in full_path. If the file could
key_file :
file :
a relative path to a filename to open and parse. [type filename]
full_path :
return location for a string containing the full path of the file, or
NULL.
flags :
error :
Returns :
TRUE if a key file could be loaded, FALSE othewise
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_load_from_dirs ()
const gchar *file,
const gchar **search_dirs,
gchar **full_path,
GKeyFileFlags flags,
GError **error);
This function looks for a key file named file in the paths specified in
in full_path. If the file could not be loaded then an error is set to either
key_file :
file :
a relative path to a filename to open and parse
search_dirs :
NULL-terminated array of directories to search
full_path :
return location for a string containing the full path of the file,
or NULL
flags :
error :
Returns :
TRUE if a key file could be loaded, FALSE otherwise
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_to_data ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_save_to_file ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_start_group () -> g-key-file-start-group
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_groups () -> g-key-file-groups
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_keys () -> g-key-file-keys
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_has_group ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_has_key ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_value ()
const gchar *group_name,
const gchar *key,
GError **error);
Returns the raw value associated with key under group_name. Use
g_key_file_get_string() to retrieve an unescaped UTF-8 string.
In the event the key cannot be found, NULL is returned and error is set to
G_KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be
found, NULL is returned and error is set to
G_KEY_FILE_ERROR_GROUP_NOT_FOUND.
key_file :
group_name :
a group name
key :
a key
error :
Returns :
a newly allocated string or NULL if the specified key cannot be found.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_string ()
g_key_file_set_string () -> g-key-file-string
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_locale_string ()
const gchar *group_name,
const gchar *key,
const gchar *locale,
Returns the value associated with key under group_name translated in the
given locale if available. If locale is NULL then the current locale is
assumed.
If key cannot be found then NULL is returned and error is set to
G_KEY_FILE_ERROR_KEY_NOT_FOUND. If the value associated with key cannot be
interpreted or no suitable translation can be found then the untranslated
value is returned.
key_file :
group_name :
a group name
key :
a key
locale :
a locale identifier or NULL. [allow-none]
error :
Returns :
a newly allocated string or NULL if the specified key cannot be found.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_locale_for_key ()
gchar *
const gchar *group_name,
const gchar *key,
const gchar *locale);
Returns the actual locale which the result of g_key_file_get_locale_string()
If calling g_key_file_get_locale_string() or
group_name , key and locale , the result of those functions will have
originally been tagged with the locale that is the result of this function.
key_file :
group_name :
a group name
key :
a key
locale :
a locale identifier or NULL.
Returns :
the locale from the file, or NULL if the key was not found or the entry
in the file was was untranslated.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
const gchar *group_name,
const gchar *key,
GError **error);
Returns the value associated with key under group_name as a boolean.
If key cannot be found then FALSE is returned and error is set to
G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key
cannot be interpreted as a boolean then FALSE is returned and error is set
key_file :
group_name :
a group name
key :
a key
error :
Returns :
the value associated with the key as a boolean, or FALSE if the key was
not found or could not be parsed.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_integer ()
const gchar *group_name,
const gchar *key,
GError **error);
Returns the value associated with key under group_name as an integer.
If key cannot be found then 0 is returned and error is set to
G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key
cannot be interpreted as an integer then 0 is returned and error is set to
key_file :
group_name :
a group name
key :
a key
error :
Returns :
the value associated with the key as an integer, or 0 if the key was not
found or could not be parsed.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
const gchar *group_name,
const gchar *key,
GError **error);
results without truncation.
key_file :
group_name :
a non-NULL group name
key :
a non-NULL key
error :
Returns :
the key was not found or could not be parsed.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_uint64 ()
const gchar *group_name,
const gchar *key,
Returns the value associated with key under group_name as an unsigned
large positive results without truncation.
key_file :
group_name :
a non-NULL group name
key :
a non-NULL key
error :
Returns :
if the key was not found or could not be parsed.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_double ()
const gchar *group_name,
const gchar *key,
Returns the value associated with key under group_name as a double. If
group_name is NULL, the start_group is used.
G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key
key_file :
group_name :
a group name
key :
a key
error :
Returns :
found or could not be parsed.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_string_list ()
const gchar *group_name,
const gchar *key,
gsize *length,
key_file :
group_name :
a group name
key :
a key
length :
return location for the number of returned strings, or NULL
error :
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_string_list ()
const gchar *group_name,
const gchar *key,
const gchar * const list[],
gsize length);
key_file :
group_name :
a group name
key :
a key
list :
an array of string values
length :
number of string values in list
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_locale_string_list ()
const gchar *group_name,
const gchar *key,
const gchar *locale,
gsize *length,
GError **error);
Returns the values associated with key under group_name translated in the
given locale if available. If locale is NULL then the current locale is
assumed.
If key cannot be found then NULL is returned and error is set to
G_KEY_FILE_ERROR_KEY_NOT_FOUND. If the values associated with key cannot be
interpreted or no suitable translations can be found then the untranslated
values are returned. The returned array is NULL-terminated, so length may
optionally be NULL.
key_file :
group_name :
a group name
key :
a key
locale :
a locale identifier or NULL
length :
return location for the number of returned strings or NULL
error :
Returns :
a newly allocated NULL-terminated string array or NULL if the key isn't
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_boolean_list ()
const gchar *group_name,
const gchar *key,
gsize *length,
GError **error);
Returns the values associated with key under group_name as booleans.
If key cannot be found then NULL is returned and error is set to
G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key
cannot be interpreted as booleans then NULL is returned and error is set to
key_file :
group_name :
a group name
key :
a key
length :
the number of booleans returned. [out]
error :
Returns :
the values associated with the key as a list of booleans, or NULL if the
key was not found or could not be parsed. The returned list of booleans
should be freed with g_free() when no longer needed.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_integer_list ()
const gchar *group_name,
const gchar *key,
gsize *length,
GError **error);
Returns the values associated with key under group_name as integers.
If key cannot be found then NULL is returned and error is set to
G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key
cannot be interpreted as integers then NULL is returned and error is set to
key_file :
group_name :
a group name
key :
a key
length :
the number of integers returned. [out]
error :
Returns :
the values associated with the key as a list of integers, or NULL if the
key was not found or could not be parsed. The returned list of integers
should be freed with g_free() when no longer needed.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_double_list ()
const gchar *group_name,
const gchar *key,
gsize *length,
Returns the values associated with key under group_name as doubles.
If key cannot be found then NULL is returned and error is set to
G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key
cannot be interpreted as doubles then NULL is returned and error is set to
key_file :
group_name :
a group name
key :
a key
length :
the number of doubles returned. [out]
error :
Returns :
the values associated with the key as a list of doubles, or NULL if the
key was not found or could not be parsed. The returned list of doubles
should be freed with g_free() when no longer needed.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_get_comment ()
const gchar *group_name,
const gchar *key,
GError **error);
Retrieves a comment above key from group_name. If key is NULL then comment
will be read from above group_name. If both key and group_name are NULL,
key_file :
group_name :
a group name, or NULL. [allow-none]
key :
a key
error :
Returns :
a comment that should be freed with g_free()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_value ()
const gchar *group_name,
const gchar *key,
const gchar *value);
Associates a new value with key under group_name.
If key cannot be found then it is created. If group_name cannot be found
need escaping (such as newlines or spaces), use g_key_file_set_string().
key_file :
group_name :
a group name
key :
a key
value :
a string
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_locale_string ()
const gchar *group_name,
const gchar *key,
const gchar *locale,
const gchar *string);
Associates a string value for key and locale under group_name. If the
translation for key cannot be found then it is created.
key_file :
group_name :
a group name
key :
a key
locale :
a locale identifier
string :
a string
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_boolean ()
const gchar *group_name,
const gchar *key,
gboolean value);
Associates a new boolean value with key under group_name. If key cannot be
found then it is created.
key_file :
group_name :
a group name
key :
a key
value :
TRUE or FALSE
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_integer ()
const gchar *group_name,
const gchar *key,
gint value);
Associates a new integer value with key under group_name. If key cannot be
found then it is created.
key_file :
group_name :
a group name
key :
a key
value :
an integer value
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_int64 ()
const gchar *group_name,
const gchar *key,
gint64 value);
Associates a new integer value with key under group_name. If key cannot be
found then it is created.
key_file :
group_name :
a group name
key :
a key
value :
an integer value
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_uint64 ()
const gchar *group_name,
const gchar *key,
Associates a new integer value with key under group_name. If key cannot be
found then it is created.
key_file :
group_name :
a group name
key :
a key
value :
an integer value
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_double ()
const gchar *group_name,
const gchar *key,
gdouble value);
Associates a new double value with key under group_name. If key cannot be
found then it is created.
key_file :
group_name :
a group name
key :
a key
value :
an double value
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_locale_string_list ()
const gchar *group_name,
const gchar *key,
const gchar *locale,
const gchar * const list[],
gsize length);
Associates a list of string values for key and locale under group_name. If
the translation for key cannot be found then it is created.
key_file :
group_name :
a group name
key :
a key
locale :
a locale identifier
list :
a NULL-terminated array of locale string values
length :
the length of list
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_boolean_list ()
const gchar *group_name,
const gchar *key,
gsize length);
Associates a list of boolean values with key under group_name. If key cannot
be found then it is created. If group_name is NULL, the start_group is used.
key_file :
group_name :
a group name
key :
a key
list :
an array of boolean values. [array length=length]
length :
length of list
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_integer_list ()
const gchar *group_name,
const gchar *key,
gint list[],
gsize length);
Associates a list of integer values with key under group_name. If key cannot
be found then it is created.
key_file :
group_name :
a group name
key :
a key
list :
an array of integer values. [array length=length]
length :
number of integer values in list
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_double_list ()
const gchar *group_name,
const gchar *key,
gdouble list[],
gsize length);
Associates a list of double values with key under group_name. If key cannot
be found then it is created.
key_file :
group_name :
a group name
key :
a key
list :
an array of double values. [array length=length]
length :
number of double values in list
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_set_comment ()
const gchar *group_name,
const gchar *key,
const gchar *comment,
GError **error);
Places a comment above key from group_name. If key is NULL then comment will
be written above group_name. If both key and group_name are NULL, then
key_file :
group_name :
a group name, or NULL. [allow-none]
key :
a key. [allow-none]
comment :
a comment
error :
Returns :
TRUE if the comment was written, FALSE otherwise
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_remove_group ()
const gchar *group_name,
GError **error);
Removes the specified group, group_name, from the key file.
key_file :
group_name :
a group name
error :
Returns :
TRUE if the group was removed, FALSE otherwise
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_remove_key ()
const gchar *group_name,
const gchar *key,
GError **error);
Removes key in group_name from the key file.
key_file :
group_name :
a group name
key :
a key name to remove
error :
Returns :
TRUE if the key was removed, FALSE otherwise
----------------------------------------------------------------------------
----------------------------------------------------------------------------
g_key_file_remove_comment ()
const gchar *group_name,
const gchar *key,
GError **error);
Removes a comment above key from group_name. If key is NULL then comment
will be removed above group_name. If both key and group_name are NULL, then
key_file :
group_name :
a group name, or NULL. [allow-none]
key :
a key. [allow-none]
error :
Returns :
TRUE if the comment was removed, FALSE otherwise
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_GROUP
#define G_KEY_FILE_DESKTOP_GROUP "Desktop Entry"
The name of the main group of a desktop entry file, as defined in the
Desktop Entry Specification. Consult the specification for more details
about the meanings of the keys below.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_TYPE
#define G_KEY_FILE_DESKTOP_KEY_TYPE "Type"
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string giving the
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_VERSION
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string giving the
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_NAME
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a localized string
giving the specific name of the desktop entry.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_GENERIC_NAME
#define G_KEY_FILE_DESKTOP_KEY_GENERIC_NAME "GenericName"
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a localized string
giving the generic name of the desktop entry.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY
#define G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY "NoDisplay"
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating
whether the desktop entry should be shown in menus.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_COMMENT
#define G_KEY_FILE_DESKTOP_KEY_COMMENT "Comment"
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a localized string
giving the tooltip for the desktop entry.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_ICON
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a localized string
giving the name of the icon to be displayed for the desktop entry.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_HIDDEN
#define G_KEY_FILE_DESKTOP_KEY_HIDDEN "Hidden"
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating
whether the desktop entry has been deleted by the user.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a list of strings
identifying the environments that should display the desktop entry.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a list of strings
identifying the environments that should not display the desktop entry.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string giving the
file name of a binary on disk used to determine if the program is actually
installed. It is only valid for desktop entries with the Application type.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string giving the
command line to execute. It is only valid for desktop entries with the
Application type.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_PATH
#define G_KEY_FILE_DESKTOP_KEY_PATH "Path"
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string containing
the working directory to run the program in. It is only valid for desktop
entries with the Application type.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating
whether the program should be run in a terminal window. It is only valid
for desktop entries with the Application type.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_MIME_TYPE
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a list of strings
giving the MIME types supported by this desktop entry.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_CATEGORIES
#define G_KEY_FILE_DESKTOP_KEY_CATEGORIES "Categories"
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a list of strings
giving the categories in which the desktop entry should be shown in a menu.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY
#define G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY "StartupNotify"
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is string identifying the
WM class or name hint of a window that the application will create, which
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_KEY_URL
#define G_KEY_FILE_DESKTOP_KEY_URL "URL"
A key under G_KEY_FILE_DESKTOP_GROUP, whose value is a string giving the
URL to access. It is only valid for desktop entries with the Link type.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_TYPE_APPLICATION
#define G_KEY_FILE_DESKTOP_TYPE_APPLICATION "Application"
representing applications.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
G_KEY_FILE_DESKTOP_TYPE_LINK
#define G_KEY_FILE_DESKTOP_TYPE_LINK "Link"
representing links to documents.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
representing directories.
---------------------------------------------------------------------------- | The documentation of this file is taken from the GLib 2.64 Reference
Manual and modified to document the Lisp binding to the GLib library .
available from < -cffi-gtk/ > .
Copyright ( C ) 2020 - 2021
as published by the Free Software Foundation , either version 3 of the
the GNU Lesser General Public License that clarifies the terms for use
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this program and the preamble to the Gnu Lesser
GKeyFile
GKeyFileError
G_KEY_FILE_DESKTOP_KEY_TRY_EXEC
G_KEY_FILE_DESKTOP_KEY_TERMINAL
G_KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE
g_key_file_ref
g_key_file_load_from_data
g_key_file_get_int64
(in-package :glib)
GKeyFileError enumeration .
See GError for information on error domains .
enum GKeyFileError
G_KEY_FILE_ERROR_PARSE ,
G_KEY_FILE_ERROR_INVALID_VALUE
G_KEY_FILE_ERROR_INVALID_VALUE
enum
(defbitfield g-key-file-flags
(:none 0)
(:keep-comments #.(ash 1 0))
(:keep-translations #.(ash 1 1)))
#+cl-cffi-gtk-documentation
(setf (gethash 'g-key-file-flags atdoc:*symbol-name-alias*)
"Bitfield"
(gethash 'g-key-file-flags atdoc:*external-symbols*)
"@version{2021-8-13}
@begin{short}
Flags which influence the parsing of key values.
@end{short}
@begin{pre}
(defbitfield g-key-file-flags
(:none 0)
(:keep-comments #.(ash 1 0))
(:keep-translations #.(ash 1 1)))
@end{pre}
@begin[code]{table}
@entry[:none]{No flags, default behaviour.}
@entry[:keep-coments]{Use this flag if you plan to write the possibly
modified contents of the key file back to a file. Otherwise all comments
will be lost when the key file is written back.}
@entry[:keep-translations]{Use this flag if you plan to write the possibly
modified contents of the key file back to a file. Otherwise only the
translations for the current language will be written back.}
@end{table}
@see-type{g-key-file}")
(export 'g-key-file-flags)
GKeyFile
(defcstruct g-key-file)
#+cl-cffi-gtk-documentation
(setf (gethash 'g-key-file atdoc:*type-name-alias*)
"CStruct"
(documentation 'g-key-file 'type)
"@version{2021-8-13}
@begin{short}
The @sym{g-key-file} structure lets you parse, edit or create files
containing groups of key-value pairs, which we call key files for lack of a
better name.
@end{short}
Several freedesktop.org specifications use key files now, e.g. the Desktop
Entry Specification and the Icon Theme Specification.
The syntax of key files is described in detail in the Desktop Entry
Specification, here is a quick summary: Key files consists of groups of
key-value pairs, interspersed with comments.
@begin{pre}
# this is just an example
# there can be comments before the first group
[First Group]
Name=Key File Example this value shows escaping
# localized strings are stored in multiple key-value pairs
Welcome=Hello
Welcome[de]=Hallo
Welcome[fr_FR]=Bonjour
Welcome[it]=Ciao
Welcome[be@@latin]=Hello
[Another Group]
@end{pre}
Lines beginning with a @code{'#'} and blank lines are considered comments.
Groups are started by a header line containing the group name enclosed in
@code{'['} and @code{']'}, and ended implicitly by the start of the next group
or the end of the file. Each key-value pair must be contained in a group.
Key-value pairs generally have the form @code{key=value}, with the exception
of localized strings, which have the form @code{key[locale]=value}, with a
locale identifier of the form @code{lang_COUNTRYMODIFIER} where @code{COUNTRY}
and @code{MODIFIER} are optional. Space before and after the @code{'='}
character are ignored. Newline, tab, carriage return and backslash characters
in value are escaped as @code{\n}, @code{\t}, @code{\r}, and @code{\\},
respectively. To preserve leading spaces in values, these can also be escaped
as @code{\s}.
Key files can store strings, possibly with localized variants, integers,
booleans and lists of these. Lists are separated by a separator character,
value in a list, it has to be escaped by prefixing it with a backslash.
This syntax is obviously inspired by the .ini files commonly met on Windows,
but there are some important differences:
@begin{itemize}
use the @code{'#'} character.}
@item{Key files do not allow for ungrouped keys meaning only comments can
precede the first group.}
@item{Key files are always encoded in UTF-8.}
@item{Key and Group names are case-sensitive. For example, a group called
@code{[GROUP]} is a different from @code{[group]}.}
@item{.ini files do not have a strongly typed boolean entry type, they only
have @code{GetProfileInt()}. In key files, only true and false (in lower
case) are allowed.}
@end{itemize}
Note that in contrast to the Desktop Entry Specification, groups in key
files may contain the same key multiple times. The last entry wins. Key
files may also contain multiple groups with the same name. They are merged
together. Another difference is that keys and group names in key files are
not restricted to ASCII characters.
@begin[Examples]{dictionary}
Here is an example of loading a key file and reading a value:
@begin{pre}
(let ((keyfile (g-key-file-new)))
(unless (g-key-file-load-from-file keyfile \"rtest-glib-key-file.ini\" :none)
(error \"Error loading the key file: RTEST-GLIB-KEY-FILE.INI\"))
(let ((value (g-key-file-string keyfile \"First Group\" \"Welcome\")))
(unless value
(setf value \"default-value\"))
... ))
@end{pre}
Here is an example of creating and saving a key file:
@begin{pre}
(let ((keyfile (g-key-file-new)))
(g-key-file-load-from-file keyfile \"rtest-glib-key-file.ini\" :none)
Add a string to the First Group
(setf (g-key-file-string keyfile \"First Group\" \"SomeKey\") \"New Value\")
(unless (g-key-file-save-to-file keyfile \"rtest-glib-key-file-example.ini\")
(error \"Error saving key file.\"))
(let ((data (g-key-file-to-data keyfile)))
(unless data
(error \"Error saving key file.\"))
... ))
@end{pre}
@end{dictionary}
@see-function{g-key-file-new}")
(export 'g-key-file)
(defcfun ("g_key_file_new" g-key-file-new) (:pointer (:struct g-key-file))
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@return{An empty @type{g-key-file} instance.}
@begin{short}
Creates a new empty @type{g-key-file} instance.
@end{short}
Use the functions @fun{g-key-file-load-from-file}, or
@fun{g-key-file-load-from-data} to read an existing key file.
@see-type{g-key-file}
@see-function{g-key-file-load-from-file}
@see-function{g-key-file-load-from-data}")
(export 'g-key-file-new)
Clears all keys and groups from key_file , and decreases the reference count
by 1 . If the reference count reaches zero , frees the key file and all its
a GKeyFile
Since 2.6
g_key_file_ref ( )
Increases the reference count of key_file .
a GKeyFile
the same key_file .
Since 2.32
Decreases the reference count of key_file by 1 . If the reference count
reaches zero , frees the key file and all its allocated memory .
a GKeyFile
Since 2.32
(defcfun ("g_key_file_set_list_separator" %g-key-file-set-list-separator) :void
(keyfile (:pointer (:struct g-key-file)))
(separator :char))
(defun g-key-file-set-list-separator (keyfile separator)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[separator]{a char with the separator}
@begin{short}
Sets the character which is used to separate values in lists.
@end{short}
@see-type{g-key-file}"
(%g-key-file-set-list-separator keyfile (char-code separator)))
(export 'g-key-file-set-list-separator)
(defcfun ("g_key_file_load_from_file" %g-key-file-load-from-file) :boolean
(key-file (:pointer (:struct g-key-file)))
(filename :string)
(flags g-key-file-flags)
(err :pointer))
(defun g-key-file-load-from-file (keyfile filename flags)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[filename]{a string with the path of a filename to load}
@argument[flags]{flags from the @symbol{g-key-file-flags} flags}
@return{@em{True} if a key file could be loaded, @em{false} otherwise.}
@begin{short}
Loads a key file into a @type{g-key-file} instance.
@end{short}
If the file could not be loaded then @em{false} is returned.
@see-type{g-key-file}
@see-function{g-key-file-save-to-file}"
(with-g-error (err)
(%g-key-file-load-from-file keyfile filename flags err)))
(export 'g-key-file-load-from-file)
g_key_file_load_from_data ( )
(defcfun ("g_key_file_load_from_data" %g-key-file-load-from-data) :boolean
(keyfile (:pointer (:struct g-key-file)))
(data :string)
(len g-size)
(flags g-key-file-flags)
(error :pointer))
(defun g-key-file-load-from-data (keyfile data flags)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[data]{a string with the key file loaded in memory}
@argument[flags]{flags from the @symbol{g-key-file-flags} flags}
@return{@em{True} if a key file could be loaded, otherwise @em{false}.}
@begin{short}
Loads a key file from memory into a @type{g-key-file} instance.
@end{short}
If the data cannot be loaded then @em{false} is returned.
@see-type{g-key-file}"
(with-ignore-g-error (err)
(%g-key-file-load-from-data keyfile data (length data) flags err)))
(export 'g-key-file-load-from-data)
g_key_file_load_from_bytes ( GKeyFile * key_file ,
flags ,
Loads a key file from the data in bytes into an empty GKeyFile structure .
If the object can not be created then error is set to a GKeyFileError .
an empty GKeyFile struct
a GBytes
flags from
return location for a GError , or NULL
Since 2.50
gboolean g_key_file_load_from_data_dirs ( GKeyFile * key_file ,
( ) and g_get_system_data_dirs ( ) , loads the file into
not be loaded then an error is set to either a GFileError or GKeyFileError .
an empty GKeyFile struct
flags from
return location for a GError , or NULL
Since 2.6
gboolean g_key_file_load_from_dirs ( GKeyFile * key_file ,
search_dirs , loads the file into key_file and returns the file 's full path
a GFileError or GKeyFileError .
an empty GKeyFile struct
flags from
return location for a GError , or NULL
Since 2.14
(defcfun ("g_key_file_to_data" %g-key-file-to-data) :string
(keyfile (:pointer (:struct g-key-file)))
(len (:pointer g-size))
(error :pointer))
(defun g-key-file-to-data (keyfile)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@return{A string holding the contents of the key file.}
@begin{short}
Outputs the key file as a string.
@end{short}
@see-type{g-key-file}
@see-function{g-key-file-save-to-file}"
(with-g-error (err)
(with-foreign-object (len 'g-size)
(%g-key-file-to-data keyfile len err))))
(export 'g-key-file-to-data)
(defcfun ("g_key_file_save_to_file" %g-key-file-save-to-file) :boolean
(keyfile (:pointer (:struct g-key-file)))
(filename :string)
(err :pointer))
(defun g-key-file-save-to-file (keyfile filename)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[filename]{a string with the file to write to}
@return{@em{True} if successful, else @em{false}.}
@begin{short}
Writes the contents of the key file to a file.
@end{short}
@see-type{g-key-file}
@see-function{g-key-file-load-from-file}"
(with-g-error (err)
(%g-key-file-save-to-file keyfile filename err)))
(export 'g-key-file-save-to-file)
(defcfun ("g_key_file_get_start_group" g-key-file-start-group) :string
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@return{A string with the start group of the key file.}
@begin{short}
Returns the name of the start group of the key file.
@end{short}
@see-type{g-key-file}"
(keyfile (:pointer (:struct g-key-file))))
(export 'g-key-file-start-group)
(defcfun ("g_key_file_get_groups" %g-key-file-groups)
(g-strv :free-from-foreign t)
(keyfile (:pointer (:struct g-key-file)))
(len (:pointer g-size)))
(defun g-key-file-groups (keyfile)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@return{A list of strings.}
@begin{short}
Returns all groups in the key file loaded with @arg{keyfile}.
@end{short}
@see-type{g-key-file}"
(%g-key-file-groups keyfile (null-pointer)))
(export 'g-key-file-groups)
(defcfun ("g_key_file_get_keys" %g-key-file-keys) (g-strv :free-from-foreign t)
(keyfile (:pointer (:struct g-key-file)))
(group :string)
(len (:pointer g-size))
(err :pointer))
(defun g-key-file-keys (keyfile group)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[group]{a string with the group name}
@return{A list of strings.}
@begin{short}
Returns all keys for the group name.
@end{short}
In the event that the group_name cannot be found, @code{nil} is returned.
@see-type{g-key-file}"
(with-g-error (err)
(%g-key-file-keys keyfile group (null-pointer) err)))
(export 'g-key-file-keys)
(defcfun ("g_key_file_has_group" g-key-file-has-group) :boolean
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[group]{a string with the group name}
@return{@em{True} if @arg{group} is a part of @arg{keyfile}, @em{false}
otherwise.}
@begin{short}
Looks whether the key file has the group @arg{group}.
@end{short}
@see-type{g-key-file}"
(keyfile (:pointer (:struct g-key-file)))
(group :string))
(export 'g-key-file-has-group)
(defcfun ("g_key_file_has_key" %g-key-file-has-key) :boolean
(keyfile (:pointer (:struct g-key-file)))
(group :string)
(key :string)
(err :pointer))
(defun g-key-file-has-key (keyfile group key)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[group]{a string with the group name}
@argument[key]{a string with the key name}
@return{@em{True} if @arg{key} is a part of @arg{group}, @em{false}
otherwise.}
@begin{short}
Looks whether the key file has the key @arg{key} in the group
@arg{group}.
@end{short}
@see-type{g-key-file}"
(with-g-error (err)
(%g-key-file-has-key keyfile group key err)))
(export 'g-key-file-has-key)
gchar * g_key_file_get_value ( GKeyFile * key_file ,
a GKeyFile
return location for a GError , or NULL
Since 2.6
(defun (setf g-key-file-string) (value keyfile group key)
(foreign-funcall "g_key_file_set_string"
(:pointer (:struct g-key-file)) keyfile
:string group
:string key
:string value
:void)
value)
(defcfun ("g_key_file_get_string" %g-key-file-string) :string
(keyfile (:pointer (:struct g-key-file)))
(group :string)
(key :string)
(err :pointer))
(defun g-key-file-string (keyfile group key)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@syntax[]{(g-key-file-string keyfile) => value}
@syntax[]{(setf (g-key-file-string keyfile) value)}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[group]{a string with the group name}
@argument[key]{a string with the key name}
@argument[value]{a string or @code{nil}}
@begin{short}
The function @sym{g-key-file-string} returns the string value associated
with @arg{key} under @arg{group}.
@end{short}
In the event the key or the group name cannot be found, @code{nil} is
returned.
The function @sym{(setf g-key-file-string)} associates a new string value with
@arg{key} under @arg{group}. If @arg{key} or @arg{group} cannot be found then
they are created.
Unlike the function @fun{g-key-file-value}, this function handles characters
that need escaping, such as newlines.
@see-type{g-key-file}"
(with-g-error (err)
(%g-key-file-string keyfile group key err)))
(export 'g-key-file-string)
gchar * g_key_file_get_locale_string ( GKeyFile * key_file ,
a GKeyFile
return location for a GError , or NULL
Since 2.6
g_key_file_get_locale_for_key ( GKeyFile * key_file ,
or g_key_file_get_locale_string_list ( ) came from .
g_key_file_get_locale_string_list ( ) with exactly the same key_file ,
a GKeyFile
Since 2.56
( )
( GKeyFile * key_file ,
to G_KEY_FILE_ERROR_INVALID_VALUE .
a GKeyFile
return location for a GError
Since 2.6
gint g_key_file_get_integer ( GKeyFile * key_file ,
G_KEY_FILE_ERROR_INVALID_VALUE .
a GKeyFile
return location for a GError
Since 2.6
g_key_file_get_int64 ( )
gint64 g_key_file_get_int64 ( GKeyFile * key_file ,
Returns the value associated with key under group_name as a signed 64 - bit
integer . This is similar to g_key_file_get_integer ( ) but can return 64 - bit
a non - NULL GKeyFile
return location for a GError
the value associated with the key as a signed 64 - bit integer , or 0 if
Since 2.26
guint64 g_key_file_get_uint64 ( GKeyFile * key_file ,
64 - bit integer . This is similar to g_key_file_get_integer ( ) but can return
a non - NULL GKeyFile
return location for a GError
the value associated with the key as an unsigned 64 - bit integer , or 0
Since 2.26
gdouble g_key_file_get_double ( GKeyFile * key_file ,
If key can not be found then 0.0 is returned and error is set to
can not be interpreted as a double then 0.0 is returned and error is set to
G_KEY_FILE_ERROR_INVALID_VALUE .
a GKeyFile
return location for a GError
the value associated with the key as a double , or 0.0 if the key was not
Since 2.12
gchar * * g_key_file_get_string_list ( GKeyFile * key_file ,
a GKeyFile
return location for a GError , or NULL
Since 2.6
void g_key_file_set_string_list ( GKeyFile * key_file ,
a GKeyFile
Since 2.6
(defun (setf g-key-file-string-list) (value keyfile group key)
(foreign-funcall "g_key_file_set_string_list"
(:pointer (:struct g-key-file)) keyfile
:string group
:string key
g-strv value
g-size (length value)
:void)
value)
(defcfun ("g_key_file_get_string_list" %g-key-file-string-list) g-strv
(keyfile (:pointer (:struct g-key-file)))
(group :string)
(key :string)
(len (:pointer g-size))
(err :pointer))
(defun g-key-file-string-list (keyfile group key)
#+cl-cffi-gtk-documentation
"@version{2021-8-13}
@syntax[]{(g-key-file-string-list keyfile) => value}
@syntax[]{(setf (g-key-file-string-list keyfile) value)}
@argument[keyfile]{a @type{g-key-file} instance}
@argument[group]{a string with the group name}
@argument[key]{a string with the key name}
@argument[value]{a list of strings}
@begin{short}
The function @sym{g-key-file-string-list} returns the values associated with
@arg{key} under @arg{group}.
@end{short}
In the event the key or the group name cannot be found, @code{nil} is
returned.
The function @sym{(setf g-key-file-string-list} associates a list of string
values for @arg{key} under @arg{group}. If @arg{key} or @arg{group} cannot be
found then they are created.
@see-type{g-key-file}"
(with-g-error (err)
(with-foreign-object (len 'g-size)
(%g-key-file-string-list keyfile group key len err))))
(export 'g-key-file-string-list)
gchar * * g_key_file_get_locale_string_list ( GKeyFile * key_file ,
a GKeyFile
return location for a GError or NULL
found . The string array should be freed with ( ) .
Since 2.6
gboolean * g_key_file_get_boolean_list ( GKeyFile * key_file ,
G_KEY_FILE_ERROR_INVALID_VALUE .
a GKeyFile
return location for a GError
Since 2.6
gint * g_key_file_get_integer_list ( GKeyFile * key_file ,
G_KEY_FILE_ERROR_INVALID_VALUE .
a GKeyFile
return location for a GError
Since 2.6
gdouble * g_key_file_get_double_list ( GKeyFile * key_file ,
G_KEY_FILE_ERROR_INVALID_VALUE .
a GKeyFile
return location for a GError
Since 2.12
gchar * g_key_file_get_comment ( GKeyFile * key_file ,
then comment will be read from above the first group in the file .
a GKeyFile
return location for a GError
Since 2.6
void g_key_file_set_value ( GKeyFile * key_file ,
then it is created . To set an UTF-8 string which may contain characters that
a GKeyFile
Since 2.6
void g_key_file_set_locale_string ( GKeyFile * key_file ,
a GKeyFile
Since 2.6
void g_key_file_set_boolean ( GKeyFile * key_file ,
a GKeyFile
Since 2.6
void g_key_file_set_integer ( GKeyFile * key_file ,
a GKeyFile
Since 2.6
void g_key_file_set_int64 ( GKeyFile * key_file ,
a GKeyFile
Since 2.26
void g_key_file_set_uint64 ( GKeyFile * key_file ,
a GKeyFile
Since 2.26
void g_key_file_set_double ( GKeyFile * key_file ,
a GKeyFile
Since 2.12
void g_key_file_set_locale_string_list ( GKeyFile * key_file ,
a GKeyFile
Since 2.6
void ( GKeyFile * key_file ,
list [ ] ,
a GKeyFile
Since 2.6
void g_key_file_set_integer_list ( GKeyFile * key_file ,
a GKeyFile
Since 2.6
void g_key_file_set_double_list ( GKeyFile * key_file ,
a GKeyFile
Since 2.12
gboolean g_key_file_set_comment ( GKeyFile * key_file ,
comment will be written above the first group in the file .
a GKeyFile
return location for a GError
Since 2.6
gboolean g_key_file_remove_group ( GKeyFile * key_file ,
a GKeyFile
return location for a GError or NULL
Since 2.6
gboolean g_key_file_remove_key ( GKeyFile * key_file ,
a GKeyFile
return location for a GError or NULL
Since 2.6
gboolean g_key_file_remove_comment ( GKeyFile * key_file ,
comment will be removed above the first group in the file .
a GKeyFile
return location for a GError
Since 2.6
Since 2.14
type of the desktop entry . Usually ,
G_KEY_FILE_DESKTOP_TYPE_LINK , or .
Since 2.14
# define G_KEY_FILE_DESKTOP_KEY_VERSION " Version "
version of the Desktop Entry Specification used for the desktop entry file .
Since 2.14
# define G_KEY_FILE_DESKTOP_KEY_NAME " Name "
Since 2.14
Since 2.14
Since 2.14
Since 2.14
# define G_KEY_FILE_DESKTOP_KEY_ICON " Icon "
Since 2.14
Since 2.14
G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN
# define G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN " OnlyShowIn "
Since 2.14
# define G_KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN " NotShowIn "
Since 2.14
G_KEY_FILE_DESKTOP_KEY_TRY_EXEC
# define G_KEY_FILE_DESKTOP_KEY_TRY_EXEC " TryExec "
Since 2.14
G_KEY_FILE_DESKTOP_KEY_EXEC
# define G_KEY_FILE_DESKTOP_KEY_EXEC " Exec "
Since 2.14
Since 2.14
G_KEY_FILE_DESKTOP_KEY_TERMINAL
# define G_KEY_FILE_DESKTOP_KEY_TERMINAL " Terminal "
Since 2.14
# define G_KEY_FILE_DESKTOP_KEY_MIME_TYPE " MimeType "
Since 2.14
Since 2.14
whether the application supports the Startup Notification Protocol
Specification .
Since 2.14
# define G_KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS " StartupWMClass "
can be used to emulate Startup Notification with older applications .
Since 2.14
Since 2.14
The value of the G_KEY_FILE_DESKTOP_KEY_TYPE , key for desktop entries
Since 2.14
The value of the G_KEY_FILE_DESKTOP_KEY_TYPE , key for desktop entries
Since 2.14
# define " Directory "
The value of the G_KEY_FILE_DESKTOP_KEY_TYPE , key for desktop entries
Since 2.14
--- End of file ----------------------------------------
|
13bbf3a001d103c159f633486673df08aceb18acbf46aea507cb145672f00cdc | graninas/Andromeda | Interpreter.hs | module Andromeda.Language.LogicControl.Interpreter where
import Andromeda.Language.LogicControl.AST
import Andromeda.Types.Language.Scripting
toAst :: ControlProgram () -> ProgramAst
toAst p = undefined
| null | https://raw.githubusercontent.com/graninas/Andromeda/6b56052bca64fc6f55a28f8001dd775a744b95bf/src/Andromeda/Language/LogicControl/Interpreter.hs | haskell | module Andromeda.Language.LogicControl.Interpreter where
import Andromeda.Language.LogicControl.AST
import Andromeda.Types.Language.Scripting
toAst :: ControlProgram () -> ProgramAst
toAst p = undefined
|
|
3d81fa38c0f4bb56ad2e223fcf34429fd10b0fbcb6cc6377f465296730c7825f | jimweirich/sicp-study | ex1_28.scm | SICP 1.28
Exercise 1.28 . One variant of the Fermat test that can not be
fooled is called the - Rabin test ( Miller 1976 ;
1980 ) . This starts from an alternate form of Fermat 's Little
;; Theorem, which states that if n is a prime number and a is any
;; positive integer less than n, then a raised to the (n - 1)st power
is congruent to 1 modulo n. To test the primality of a number n by
the - Rabin test , we pick a random number a < n and raise a to
the ( n - 1)st power modulo n using the expmod procedure . However ,
;; whenever we perform the squaring step in expmod, we check to see if
we have discovered a ` ` nontrivial square root of 1 modulo n , '' that
is , a number not equal to 1 or n - 1 whose square is equal to 1
;; modulo n. It is possible to prove that if such a nontrivial square
root of 1 exists , then n is not prime . It is also possible to prove
;; that if n is an odd number that is not prime, then, for at least
;; half the numbers a<n, computing a^(n-1) in this way will reveal a
nontrivial square root of 1 modulo n. ( This is why the - Rabin
;; test cannot be fooled.) Modify the expmod procedure to signal if it
discovers a nontrivial square root of 1 , and use this to implement
the - Rabin test with a procedure analogous to
;; fermat-test. Check your procedure by testing various known primes
and non - primes . Hint : One convenient way to make expmod signal is
;; to have it return 0.
;; ANSWER ------------------------------------------------------------
;; Ok, I've never finished this one. It is a wee bit too math-deep
;; for even me.
| null | https://raw.githubusercontent.com/jimweirich/sicp-study/bc5190e04ed6ae321107ed6149241f26efc1b8c8/scheme/chapter1/ex1_28.scm | scheme |
Theorem, which states that if n is a prime number and a is any
positive integer less than n, then a raised to the (n - 1)st power
whenever we perform the squaring step in expmod, we check to see if
modulo n. It is possible to prove that if such a nontrivial square
that if n is an odd number that is not prime, then, for at least
half the numbers a<n, computing a^(n-1) in this way will reveal a
test cannot be fooled.) Modify the expmod procedure to signal if it
fermat-test. Check your procedure by testing various known primes
to have it return 0.
ANSWER ------------------------------------------------------------
Ok, I've never finished this one. It is a wee bit too math-deep
for even me. | SICP 1.28
Exercise 1.28 . One variant of the Fermat test that can not be
1980 ) . This starts from an alternate form of Fermat 's Little
is congruent to 1 modulo n. To test the primality of a number n by
the - Rabin test , we pick a random number a < n and raise a to
the ( n - 1)st power modulo n using the expmod procedure . However ,
we have discovered a ` ` nontrivial square root of 1 modulo n , '' that
is , a number not equal to 1 or n - 1 whose square is equal to 1
root of 1 exists , then n is not prime . It is also possible to prove
nontrivial square root of 1 modulo n. ( This is why the - Rabin
discovers a nontrivial square root of 1 , and use this to implement
the - Rabin test with a procedure analogous to
and non - primes . Hint : One convenient way to make expmod signal is
|
4bd7b1d5a1eedcf5db6f173242b039c84e38fa2c17a05c712312d88bceac3318 | dmillett/clash | spec_test.clj |
(ns clash.spec-test
(:require [clojure.test :refer :all]))
| null | https://raw.githubusercontent.com/dmillett/clash/ea36a916ccfd9e1c61cb88ac6147b6a952f33dcf/test/clash/spec_test.clj | clojure |
(ns clash.spec-test
(:require [clojure.test :refer :all]))
|
|
d1df80d96056edd99588f5d286f824419416af7541d28d87daee8c1f72bbcf3f | ghc/packages-dph | Locked.hs | # LANGUAGE CPP , NoMonomorphismRestriction #
#include "fusion-phases.h"
-- | Locked streamers and zippers.
--
-- The streams are 'locked together', meaning they have the same length and
-- cannot yield 'Skip' states.
--
-- These functions are used for processing data read directly from vectors
-- where we know the vectors all have the same length.
--
module Data.Array.Parallel.Unlifted.Stream.Locked
( stream2, lockedZip2S
, stream3, lockedZip3S
, stream4, lockedZip4S
, stream5, lockedZip5S
, stream6, lockedZip6S
, stream7, lockedZip7S
, stream8, lockedZip8S)
where
import Data.Array.Parallel.Unlifted.Stream.Swallow
import Data.Vector.Generic as G
import Data.Vector.Fusion.Stream.Monadic as S
import Data.Vector.Fusion.Bundle.Monadic as B
import Data.Vector.Fusion.Bundle.Size as S
-------------------------------------------
| Stream two vectors of the same length .
-- The fact that they are the same length means the generated code only
needs to maintain one loop counter for all streams .
--
-- Trying to stream vectors of differing lengths is undefined.
--
stream2 :: (Monad m, Vector v a, Vector v b)
=> v a -> v b
-> Bundle m v (a, b)
stream2 aa bb
= lockedZip2S (G.length aa) (swallow aa) (swallow bb)
# INLINE_STREAM stream2 #
---------------------------------------------
| Stream three vectors of the same length .
stream3 :: (Monad m, Vector v a, Vector v b, Vector v c)
=> v a -> v b -> v c
-> Bundle m v (a, b, c)
stream3 aa bb cc
= lockedZip3S (G.length aa) (swallow aa) (swallow bb) (swallow cc)
{-# INLINE_STREAM stream3 #-}
When we see that one of the vectors is being created then push down a
-- 'swallow' wrapper to signal that the consumer (lockedZip2S) knows how many
-- elements to demand. This lets us generate better code on the producer side
-- as it doesn't need to track how many elements still need to be generated.
# RULES " stream3 / new_1 "
forall as bs cs
. ( G.new as ) bs cs
= B.map ( \((b , c ) , a ) - > ( a , b , c ) )
$ lockedZip2S ( G.length bs ) ( swallow2 bs cs ) ( swallow ( G.new as ) )
#
forall as bs cs
. stream3 (G.new as) bs cs
= B.map (\((b, c), a) -> (a, b, c))
$ lockedZip2S (G.length bs) (swallow2 bs cs) (swallow (G.new as))
#-}
# RULES " stream3 / new_2 "
forall as bs cs
. as ( G.new bs ) cs
= B.map ( \((a , c ) , b ) - > ( a , b , c ) )
$ lockedZip2S ( G.length as ) ( swallow2 as cs ) ( swallow ( G.new bs ) )
#
forall as bs cs
. stream3 as (G.new bs) cs
= B.map (\((a, c), b) -> (a, b, c))
$ lockedZip2S (G.length as) (swallow2 as cs) (swallow (G.new bs))
#-}
# RULES " stream3 / new_3 "
forall as bs cs
. as bs ( G.new cs )
= B.map ( \((a , b ) , c ) - > ( a , b , c ) )
$ lockedZip2S ( G.length as ) ( swallow2 as bs ) ( swallow ( G.new cs ) )
#
forall as bs cs
. stream3 as bs (G.new cs)
= B.map (\((a, b), c) -> (a, b, c))
$ lockedZip2S (G.length as) (swallow2 as bs) (swallow (G.new cs))
#-}
---------------------------------------------
| Stream four vectors of the same length .
stream4 :: (Monad m, Vector v a, Vector v b, Vector v c, Vector v d)
=> v a -> v b -> v c -> v d
-> Bundle m v (a, b, c, d)
stream4 aa bb cc dd
= lockedZip4S (G.length aa)
(swallow aa) (swallow bb) (swallow cc) (swallow dd)
{-# INLINE_STREAM stream4 #-}
# RULES " stream4 / new_1 "
forall as bs cs ds
. stream4 ( G.new as ) bs cs ds
= B.map ( \((b , c , d ) , a ) - > ( a , b , c , d ) )
$ lockedZip2S ( G.length bs ) ( swallow3 bs cs ds ) ( swallow ( G.new as ) )
#
forall as bs cs ds
. stream4 (G.new as) bs cs ds
= B.map (\((b, c, d), a) -> (a, b, c, d))
$ lockedZip2S (G.length bs) (swallow3 bs cs ds) (swallow (G.new as))
#-}
# RULES " stream4 / new_2 "
forall as bs cs ds
. stream4 as ( G.new bs ) cs ds
= B.map ( \((a , c , d ) , b ) - > ( a , b , c , d ) )
$ lockedZip2S ( G.length as ) ( swallow3 as cs ds ) ( swallow ( G.new bs ) )
#
forall as bs cs ds
. stream4 as (G.new bs) cs ds
= B.map (\((a, c, d), b) -> (a, b, c, d))
$ lockedZip2S (G.length as) (swallow3 as cs ds) (swallow (G.new bs))
#-}
# RULES " stream4 / new_3 "
forall as bs cs ds
. stream4 as bs ( G.new cs ) ds
= B.map ( \((a , b , d ) , c ) - > ( a , b , c , d ) )
$ lockedZip2S ( G.length as ) ( swallow3 as bs ds ) ( swallow ( G.new cs ) )
#
forall as bs cs ds
. stream4 as bs (G.new cs) ds
= B.map (\((a, b, d), c) -> (a, b, c, d))
$ lockedZip2S (G.length as) (swallow3 as bs ds) (swallow (G.new cs))
#-}
# RULES " stream4 / new_4 "
forall as bs cs ds
. stream4 as ( G.new ds )
= B.map ( \((a , b , c ) , d ) - > ( a , b , c , d ) )
$ lockedZip2S ( G.length as ) ( swallow3 as bs cs ) ( swallow ( G.new ds ) )
#
forall as bs cs ds
. stream4 as bs cs (G.new ds)
= B.map (\((a, b, c), d) -> (a, b, c, d))
$ lockedZip2S (G.length as) (swallow3 as bs cs) (swallow (G.new ds))
#-}
---------------------------------------------
| Stream five vectors of the same length .
stream5 :: (Monad m, Vector v a, Vector v b, Vector v c, Vector v d, Vector v e)
=> v a -> v b -> v c -> v d -> v e
-> Bundle m v (a, b, c, d, e)
stream5 aa bb cc dd ee
= lockedZip5S (G.length aa)
(swallow aa) (swallow bb) (swallow cc) (swallow dd)
(swallow ee)
# INLINE_STREAM stream5 #
# RULES " stream5 / new_1 "
forall as . stream5 ( G.new as ) bs cs ds es
= B.map ( \((b , c , d , e ) , a ) - > ( a , b , c , d , e ) )
$ lockedZip2S ( G.length bs ) ( swallow4 bs cs ds es ) ( swallow ( G.new as ) )
#
forall as bs cs ds es
. stream5 (G.new as) bs cs ds es
= B.map (\((b, c, d, e), a) -> (a, b, c, d, e))
$ lockedZip2S (G.length bs) (swallow4 bs cs ds es) (swallow (G.new as))
#-}
# RULES " stream5 / new_2 "
forall as . stream5 as ( G.new bs ) cs ds es
= B.map ( \((a , c , d , e ) , b ) - > ( a , b , c , d , e ) )
$ lockedZip2S ( G.length as ) ( swallow4 as cs ds es ) ( swallow ( G.new bs ) )
#
forall as bs cs ds es
. stream5 as (G.new bs) cs ds es
= B.map (\((a, c, d, e), b) -> (a, b, c, d, e))
$ lockedZip2S (G.length as) (swallow4 as cs ds es) (swallow (G.new bs))
#-}
# RULES " stream5 / new_3 "
forall as . stream5 as bs ( G.new cs ) ds es
= B.map ( \((a , b , d , e ) , c ) - > ( a , b , c , d , e ) )
$ lockedZip2S ( G.length as ) ( swallow4 as bs ds es ) ( swallow ( G.new cs ) )
#
forall as bs cs ds es
. stream5 as bs (G.new cs) ds es
= B.map (\((a, b, d, e), c) -> (a, b, c, d, e))
$ lockedZip2S (G.length as) (swallow4 as bs ds es) (swallow (G.new cs))
#-}
# RULES " stream5 / new_4 "
forall as . stream5 as bs cs ( G.new ds ) es
= B.map ( \((a , b , c , e ) , d ) - > ( a , b , c , d , e ) )
$ lockedZip2S ( G.length as ) ( swallow4 as bs cs es ) ( swallow ( G.new ds ) )
#
forall as bs cs ds es
. stream5 as bs cs (G.new ds) es
= B.map (\((a, b, c, e), d) -> (a, b, c, d, e))
$ lockedZip2S (G.length as) (swallow4 as bs cs es) (swallow (G.new ds))
#-}
# RULES " stream5 / new_5 "
forall as . stream5 as bs cs ds ( G.new es )
= B.map ( \((a , b , c , d ) , e ) - > ( a , b , c , d , e ) )
$ lockedZip2S ( G.length as ) ( swallow4 as bs cs ds ) ( swallow ( ) )
#
forall as bs cs ds es
. stream5 as bs cs ds (G.new es)
= B.map (\((a, b, c, d), e) -> (a, b, c, d, e))
$ lockedZip2S (G.length as) (swallow4 as bs cs ds) (swallow (G.new es))
#-}
---------------------------------------------
| Stream six vectors of the same length .
stream6 :: (Monad m, Vector v a, Vector v b, Vector v c, Vector v d, Vector v e, Vector v f)
=> v a -> v b -> v c -> v d -> v e -> v f
-> Bundle m v (a, b, c, d, e, f)
stream6 aa bb cc dd ee ff
= lockedZip6S (G.length aa)
(swallow aa) (swallow bb) (swallow cc) (swallow dd)
(swallow ee) (swallow ff)
# INLINE_STREAM stream6 #
# RULES " stream6 / new_1 "
forall as . ( G.new as ) bs cs ds es fs
= B.map ( \((b , c , d , e , f ) , a ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length bs ) ( ) ( swallow ( G.new as ) )
#
forall as bs cs ds es fs
. stream6 (G.new as) bs cs ds es fs
= B.map (\((b, c, d, e, f), a) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length bs) (swallow5 bs cs ds es fs) (swallow (G.new as))
#-}
# RULES " stream6 / new_2 "
forall as . as ( G.new bs ) cs ds es fs
= B.map ( \((a , c , d , e , f ) , b ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length as ) ( swallow5 as cs ds es fs ) ( swallow ( G.new bs ) )
#
forall as bs cs ds es fs
. stream6 as (G.new bs) cs ds es fs
= B.map (\((a, c, d, e, f), b) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length as) (swallow5 as cs ds es fs) (swallow (G.new bs))
#-}
# RULES " stream6 / new_3 "
forall as . as bs ( G.new cs ) ds es fs
= B.map ( \((a , b , d , e , f ) , c ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length as ) ( swallow5 as bs ds es fs ) ( swallow ( G.new cs ) )
#
forall as bs cs ds es fs
. stream6 as bs (G.new cs) ds es fs
= B.map (\((a, b, d, e, f), c) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length as) (swallow5 as bs ds es fs) (swallow (G.new cs))
#-}
# RULES " stream6 / new_4 "
forall as . stream6 as bs cs ( G.new ds ) es fs
= B.map ( \((a , b , c , e , f ) , d ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length as ) ( swallow5 as bs cs es fs ) ( swallow ( G.new ds ) )
#
forall as bs cs ds es fs
. stream6 as bs cs (G.new ds) es fs
= B.map (\((a, b, c, e, f), d) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length as) (swallow5 as bs cs es fs) (swallow (G.new ds))
#-}
# RULES " stream6 / new_5 "
forall as . as bs cs ds ( ) fs
= B.map ( \((a , b , c , d , f ) , e ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length as ) ( swallow5 as bs cs ds fs ) ( swallow ( ) )
#
forall as bs cs ds es fs
. stream6 as bs cs ds (G.new es) fs
= B.map (\((a, b, c, d, f), e) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length as) (swallow5 as bs cs ds fs) (swallow (G.new es))
#-}
# RULES " stream6 / new_6 "
forall as . as bs cs ds es ( G.new fs )
= B.map ( \((a , b , c , d , e ) , f ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length as ) ( swallow5 as bs cs ds es ) ( swallow ( G.new fs ) )
#
forall as bs cs ds es fs
. stream6 as bs cs ds es (G.new fs)
= B.map (\((a, b, c, d, e), f) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length as) (swallow5 as bs cs ds es) (swallow (G.new fs))
#-}
---------------------------------------------
| Stream seven vectors of the same length .
stream7 :: (Monad m, Vector v a, Vector v b, Vector v c, Vector v d, Vector v e, Vector v f, Vector v g)
=> v a -> v b -> v c -> v d -> v e -> v f -> v g
-> Bundle m v (a, b, c, d, e, f, g)
stream7 aa bb cc dd ee ff gg
= lockedZip7S (G.length aa)
(swallow aa) (swallow bb) (swallow cc) (swallow dd)
(swallow ee) (swallow ff) (swallow gg)
# INLINE_STREAM stream7 #
# RULES " stream7 / new_1 "
forall as . ( G.new as ) bs cs ds es fs gs
= B.map ( \((b , c , d , e , f , ) , a ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length bs ) ( swallow6 bs cs ds es fs gs ) ( swallow ( G.new as ) )
#
forall as bs cs ds es fs gs
. stream7 (G.new as) bs cs ds es fs gs
= B.map (\((b, c, d, e, f, g), a) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length bs) (swallow6 bs cs ds es fs gs) (swallow (G.new as))
#-}
# RULES " stream7 / new_2 "
forall as . as ( G.new bs ) cs ds es fs gs
= B.map ( \((a , c , d , e , f , ) , b ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as cs ds es fs gs ) ( swallow ( G.new bs ) )
#
forall as bs cs ds es fs gs
. stream7 as (G.new bs) cs ds es fs gs
= B.map (\((a, c, d, e, f, g), b) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as cs ds es fs gs) (swallow (G.new bs))
#-}
# RULES " stream7 / new_3 "
forall as . stream7 as bs ( G.new cs ) ds es fs gs
= B.map ( \((a , b , d , e , f , ) , c ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as bs ds es fs gs ) ( swallow ( G.new cs ) )
#
forall as bs cs ds es fs gs
. stream7 as bs (G.new cs) ds es fs gs
= B.map (\((a, b, d, e, f, g), c) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as bs ds es fs gs) (swallow (G.new cs))
#-}
# RULES " stream7 / new_4 "
forall as . stream7 as ( G.new ds ) es fs gs
= B.map ( \((a , b , c , e , f , ) , d ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as bs cs es fs gs ) ( swallow ( G.new ds ) )
#
forall as bs cs ds es fs gs
. stream7 as bs cs (G.new ds) es fs gs
= B.map (\((a, b, c, e, f, g), d) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as bs cs es fs gs) (swallow (G.new ds))
#-}
# RULES " stream7 / new_5 "
forall as . stream7 as ( ) fs gs
= B.map ( \((a , b , c , d , f , ) , e ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as bs cs ds fs gs ) ( swallow ( ) )
#
forall as bs cs ds es fs gs
. stream7 as bs cs ds (G.new es) fs gs
= B.map (\((a, b, c, d, f, g), e) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as bs cs ds fs gs) (swallow (G.new es))
#-}
# RULES " stream7 / "
forall as . stream7 as ( G.new fs ) gs
= B.map ( \((a , b , c , d , e , ) , f ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as bs cs ds es gs ) ( swallow ( G.new fs ) )
#
forall as bs cs ds es fs gs
. stream7 as bs cs ds es (G.new fs) gs
= B.map (\((a, b, c, d, e, g), f) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as bs cs ds es gs) (swallow (G.new fs))
#-}
# RULES " stream7 / new_7 "
forall as . stream7 as ( )
= B.map ( \((a , b , c , d , e , f ) , ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as bs cs ds es fs ) ( swallow ( G.new gs ) )
#
forall as bs cs ds es fs gs
. stream7 as bs cs ds es fs (G.new gs)
= B.map (\((a, b, c, d, e, f), g) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as bs cs ds es fs) (swallow (G.new gs))
#-}
---------------------------------------------
| Stream seven vectors of the same length .
stream8 :: (Monad m, Vector v a, Vector v b, Vector v c, Vector v d, Vector v e, Vector v f, Vector v g, Vector v h)
=> v a -> v b -> v c -> v d -> v e -> v f -> v g -> v h
-> Bundle m v (a, b, c, d, e, f, g, h)
stream8 aa bb cc dd ee ff gg hh
= lockedZip8S (G.length aa)
(swallow aa) (swallow bb) (swallow cc) (swallow dd)
(swallow ee) (swallow ff) (swallow gg) (swallow hh)
{-# INLINE_STREAM stream8 #-}
# RULES " stream8 / new_1 "
forall as . ( G.new as ) bs cs ds es fs gs hs
= B.map ( \((b , c , d , e , f , , h ) , a ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length bs ) ( swallow7 bs cs ds es fs gs hs ) ( swallow ( G.new as ) )
#
forall as bs cs ds es fs gs hs
. stream8 (G.new as) bs cs ds es fs gs hs
= B.map (\((b, c, d, e, f, g, h), a) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length bs) (swallow7 bs cs ds es fs gs hs) (swallow (G.new as))
#-}
# RULES " stream8 / new_2 "
forall as . as ( G.new bs ) cs ds es fs gs hs
= B.map ( \((a , c , d , e , f , , h ) , b ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( G.new bs ) )
#
forall as bs cs ds es fs gs hs
. stream8 as (G.new bs) cs ds es fs gs hs
= B.map (\((a, c, d, e, f, g, h), b) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as cs ds es fs gs hs) (swallow (G.new bs))
#-}
# RULES " stream8 / new_3 "
forall as . as bs ( G.new cs ) ds es fs gs hs
= B.map ( \((a , b , d , e , f , , h ) , c ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as bs ds es fs gs hs ) ( swallow ( G.new cs ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs (G.new cs) ds es fs gs hs
= B.map (\((a, b, d, e, f, g, h), c) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs ds es fs gs hs) (swallow (G.new cs))
#-}
# RULES " stream8 / new_4 "
forall as . as bs cs ( G.new ds ) es fs gs hs
= B.map ( \((a , b , c , e , f , , h ) , d ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( G.new ds ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs cs (G.new ds) es fs gs hs
= B.map (\((a, b, c, e, f, g, h), d) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs cs es fs gs hs) (swallow (G.new ds))
#-}
# RULES " stream8 / new_5 "
forall as . as bs cs ds ( ) fs gs hs
= B.map ( \((a , b , c , d , f , , h ) , e ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs cs ds (G.new es) fs gs hs
= B.map (\((a, b, c, d, f, g, h), e) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs cs ds fs gs hs) (swallow (G.new es))
#-}
# RULES " stream8 / new_6 "
forall as . as bs cs ds es ( G.new fs ) gs hs
= B.map ( \((a , b , c , d , e , g , h ) , f ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( G.new fs ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs cs ds es (G.new fs) gs hs
= B.map (\((a, b, c, d, e, g, h), f) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs cs ds es gs hs) (swallow (G.new fs))
#-}
# RULES " stream8 / new_7 "
forall as . as bs cs ds es fs ( ) hs
= B.map ( \((a , b , c , d , e , f , h ) , ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( G.new gs ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs cs ds es fs (G.new gs) hs
= B.map (\((a, b, c, d, e, f, h), g) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs cs ds es fs hs) (swallow (G.new gs))
#-}
# RULES " stream8 / new_8 "
forall as . as bs cs ds es fs gs ( )
= B.map ( \((a , b , c , d , e , f , h ) , ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs cs ds es fs gs (G.new hs)
= B.map (\((a, b, c, d, e, f, h), g) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs cs ds es fs gs) (swallow (G.new hs))
#-}
-- Locked zips ----------------------------------------------------------------
| Zip the first ' n ' elements of two streams .
lockedZip2S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b
-> Bundle m v (a, b)
lockedZip2S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
= B.fromStream (Stream step (sa1, sa2, 0)) (S.Exact len)
where
{-# INLINE_INNER step #-}
step (s1, s2, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
return $ case (step1, step2) of
(Yield x1 s1', Yield x2 s2')
| i < len -> Yield (x1, x2) (s1', s2', i + 1)
_ -> Done
# INLINE_STREAM lockedZip2S #
-------------------------------------------------
| Zip the first ' n ' elements of three streams .
lockedZip3S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c
-> Bundle m v (a, b, c)
lockedZip3S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
= B.fromStream (Stream step (sa1, sa2, sa3, 0)) (S.Exact len)
where
{-# INLINE_INNER step #-}
step (s1, s2, s3, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
return $ case (step1, step2, step3) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3')
| i < len -> Yield (x1, x2, x3) (s1', s2', s3', i + 1)
_ -> Done
# INLINE_STREAM lockedZip3S #
-------------------------------------------------
| Zip the first ' n ' elements of four streams .
lockedZip4S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c -> Bundle m v d
-> Bundle m v (a, b, c, d)
lockedZip4S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
(Bundle {sElems=Stream mkStep4 sa4})
= B.fromStream (Stream step (sa1, sa2, sa3, sa4, 0)) (S.Exact len)
where
{-# INLINE_INNER step #-}
step (s1, s2, s3, s4, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
step4 <- mkStep4 s4
return $ case (step1, step2, step3, step4) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3', Yield x4 s4')
| i < len -> Yield (x1, x2, x3, x4) (s1', s2', s3', s4', i + 1)
_ -> Done
# INLINE_STREAM lockedZip4S #
-------------------------------------------------
| Zip the first ' n ' elements of five streams .
lockedZip5S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c -> Bundle m v d -> Bundle m v e
-> Bundle m v (a, b, c, d, e)
lockedZip5S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
(Bundle {sElems=Stream mkStep4 sa4})
(Bundle {sElems=Stream mkStep5 sa5})
= B.fromStream (Stream step (sa1, sa2, sa3, sa4, sa5, 0)) (S.Exact len)
where
{-# INLINE_INNER step #-}
step (s1, s2, s3, s4, s5, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
step4 <- mkStep4 s4
step5 <- mkStep5 s5
return $ case (step1, step2, step3, step4, step5) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3', Yield x4 s4', Yield x5 s5')
| i < len -> Yield (x1, x2, x3, x4, x5) (s1', s2', s3', s4', s5', i + 1)
_ -> Done
# INLINE_STREAM lockedZip5S #
-------------------------------------------------
| Zip the first ' n ' elements of six streams .
lockedZip6S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c -> Bundle m v d -> Bundle m v e -> Bundle m v f
-> Bundle m v (a, b, c, d, e, f)
lockedZip6S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
(Bundle {sElems=Stream mkStep4 sa4})
(Bundle {sElems=Stream mkStep5 sa5})
(Bundle {sElems=Stream mkStep6 sa6})
= B.fromStream (Stream step (sa1, sa2, sa3, sa4, sa5, sa6, 0)) (S.Exact len)
where
{-# INLINE_INNER step #-}
step (s1, s2, s3, s4, s5, s6, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
step4 <- mkStep4 s4
step5 <- mkStep5 s5
step6 <- mkStep6 s6
return $ case (step1, step2, step3, step4, step5, step6) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3', Yield x4 s4', Yield x5 s5', Yield x6 s6')
| i < len -> Yield (x1, x2, x3, x4, x5, x6) (s1', s2', s3', s4', s5', s6', i + 1)
_ -> Done
# INLINE_STREAM lockedZip6S #
-------------------------------------------------
| Zip the first ' n ' elements of seven streams .
lockedZip7S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c -> Bundle m v d -> Bundle m v e -> Bundle m v f -> Bundle m v g
-> Bundle m v (a, b, c, d, e, f, g)
lockedZip7S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
(Bundle {sElems=Stream mkStep4 sa4})
(Bundle {sElems=Stream mkStep5 sa5})
(Bundle {sElems=Stream mkStep6 sa6})
(Bundle {sElems=Stream mkStep7 sa7})
= B.fromStream (Stream step (sa1, sa2, sa3, sa4, sa5, sa6, sa7, 0)) (S.Exact len)
where
{-# INLINE_INNER step #-}
step (s1, s2, s3, s4, s5, s6, s7, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
step4 <- mkStep4 s4
step5 <- mkStep5 s5
step6 <- mkStep6 s6
step7 <- mkStep7 s7
return $ case (step1, step2, step3, step4, step5, step6, step7) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3', Yield x4 s4', Yield x5 s5', Yield x6 s6', Yield x7 s7')
| i < len -> Yield (x1, x2, x3, x4, x5, x6, x7) (s1', s2', s3', s4', s5', s6', s7', i + 1)
_ -> Done
# INLINE_STREAM lockedZip7S #
-------------------------------------------------
| Zip the first ' n ' elements of eight streams .
lockedZip8S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c -> Bundle m v d -> Bundle m v e -> Bundle m v f -> Bundle m v g -> Bundle m v h
-> Bundle m v (a, b, c, d, e, f, g, h)
lockedZip8S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
(Bundle {sElems=Stream mkStep4 sa4})
(Bundle {sElems=Stream mkStep5 sa5})
(Bundle {sElems=Stream mkStep6 sa6})
(Bundle {sElems=Stream mkStep7 sa7})
(Bundle {sElems=Stream mkStep8 sa8})
= B.fromStream (Stream step (sa1, sa2, sa3, sa4, sa5, sa6, sa7, sa8, 0)) (S.Exact len)
where
{-# INLINE_INNER step #-}
step (s1, s2, s3, s4, s5, s6, s7, s8, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
step4 <- mkStep4 s4
step5 <- mkStep5 s5
step6 <- mkStep6 s6
step7 <- mkStep7 s7
step8 <- mkStep8 s8
return $ case (step1, step2, step3, step4, step5, step6, step7, step8) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3', Yield x4 s4', Yield x5 s5', Yield x6 s6', Yield x7 s7', Yield x8 s8')
| i < len -> Yield (x1, x2, x3, x4, x5, x6, x7, x8) (s1', s2', s3', s4', s5', s6', s7', s8', i + 1)
_ -> Done
# INLINE_STREAM lockedZip8S #
| null | https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-prim-seq/Data/Array/Parallel/Unlifted/Stream/Locked.hs | haskell | | Locked streamers and zippers.
The streams are 'locked together', meaning they have the same length and
cannot yield 'Skip' states.
These functions are used for processing data read directly from vectors
where we know the vectors all have the same length.
-----------------------------------------
The fact that they are the same length means the generated code only
Trying to stream vectors of differing lengths is undefined.
-------------------------------------------
# INLINE_STREAM stream3 #
'swallow' wrapper to signal that the consumer (lockedZip2S) knows how many
elements to demand. This lets us generate better code on the producer side
as it doesn't need to track how many elements still need to be generated.
-------------------------------------------
# INLINE_STREAM stream4 #
-------------------------------------------
-------------------------------------------
-------------------------------------------
-------------------------------------------
# INLINE_STREAM stream8 #
Locked zips ----------------------------------------------------------------
# INLINE_INNER step #
-----------------------------------------------
# INLINE_INNER step #
-----------------------------------------------
# INLINE_INNER step #
-----------------------------------------------
# INLINE_INNER step #
-----------------------------------------------
# INLINE_INNER step #
-----------------------------------------------
# INLINE_INNER step #
-----------------------------------------------
# INLINE_INNER step # | # LANGUAGE CPP , NoMonomorphismRestriction #
#include "fusion-phases.h"
module Data.Array.Parallel.Unlifted.Stream.Locked
( stream2, lockedZip2S
, stream3, lockedZip3S
, stream4, lockedZip4S
, stream5, lockedZip5S
, stream6, lockedZip6S
, stream7, lockedZip7S
, stream8, lockedZip8S)
where
import Data.Array.Parallel.Unlifted.Stream.Swallow
import Data.Vector.Generic as G
import Data.Vector.Fusion.Stream.Monadic as S
import Data.Vector.Fusion.Bundle.Monadic as B
import Data.Vector.Fusion.Bundle.Size as S
| Stream two vectors of the same length .
needs to maintain one loop counter for all streams .
stream2 :: (Monad m, Vector v a, Vector v b)
=> v a -> v b
-> Bundle m v (a, b)
stream2 aa bb
= lockedZip2S (G.length aa) (swallow aa) (swallow bb)
# INLINE_STREAM stream2 #
| Stream three vectors of the same length .
stream3 :: (Monad m, Vector v a, Vector v b, Vector v c)
=> v a -> v b -> v c
-> Bundle m v (a, b, c)
stream3 aa bb cc
= lockedZip3S (G.length aa) (swallow aa) (swallow bb) (swallow cc)
When we see that one of the vectors is being created then push down a
# RULES " stream3 / new_1 "
forall as bs cs
. ( G.new as ) bs cs
= B.map ( \((b , c ) , a ) - > ( a , b , c ) )
$ lockedZip2S ( G.length bs ) ( swallow2 bs cs ) ( swallow ( G.new as ) )
#
forall as bs cs
. stream3 (G.new as) bs cs
= B.map (\((b, c), a) -> (a, b, c))
$ lockedZip2S (G.length bs) (swallow2 bs cs) (swallow (G.new as))
#-}
# RULES " stream3 / new_2 "
forall as bs cs
. as ( G.new bs ) cs
= B.map ( \((a , c ) , b ) - > ( a , b , c ) )
$ lockedZip2S ( G.length as ) ( swallow2 as cs ) ( swallow ( G.new bs ) )
#
forall as bs cs
. stream3 as (G.new bs) cs
= B.map (\((a, c), b) -> (a, b, c))
$ lockedZip2S (G.length as) (swallow2 as cs) (swallow (G.new bs))
#-}
# RULES " stream3 / new_3 "
forall as bs cs
. as bs ( G.new cs )
= B.map ( \((a , b ) , c ) - > ( a , b , c ) )
$ lockedZip2S ( G.length as ) ( swallow2 as bs ) ( swallow ( G.new cs ) )
#
forall as bs cs
. stream3 as bs (G.new cs)
= B.map (\((a, b), c) -> (a, b, c))
$ lockedZip2S (G.length as) (swallow2 as bs) (swallow (G.new cs))
#-}
| Stream four vectors of the same length .
stream4 :: (Monad m, Vector v a, Vector v b, Vector v c, Vector v d)
=> v a -> v b -> v c -> v d
-> Bundle m v (a, b, c, d)
stream4 aa bb cc dd
= lockedZip4S (G.length aa)
(swallow aa) (swallow bb) (swallow cc) (swallow dd)
# RULES " stream4 / new_1 "
forall as bs cs ds
. stream4 ( G.new as ) bs cs ds
= B.map ( \((b , c , d ) , a ) - > ( a , b , c , d ) )
$ lockedZip2S ( G.length bs ) ( swallow3 bs cs ds ) ( swallow ( G.new as ) )
#
forall as bs cs ds
. stream4 (G.new as) bs cs ds
= B.map (\((b, c, d), a) -> (a, b, c, d))
$ lockedZip2S (G.length bs) (swallow3 bs cs ds) (swallow (G.new as))
#-}
# RULES " stream4 / new_2 "
forall as bs cs ds
. stream4 as ( G.new bs ) cs ds
= B.map ( \((a , c , d ) , b ) - > ( a , b , c , d ) )
$ lockedZip2S ( G.length as ) ( swallow3 as cs ds ) ( swallow ( G.new bs ) )
#
forall as bs cs ds
. stream4 as (G.new bs) cs ds
= B.map (\((a, c, d), b) -> (a, b, c, d))
$ lockedZip2S (G.length as) (swallow3 as cs ds) (swallow (G.new bs))
#-}
# RULES " stream4 / new_3 "
forall as bs cs ds
. stream4 as bs ( G.new cs ) ds
= B.map ( \((a , b , d ) , c ) - > ( a , b , c , d ) )
$ lockedZip2S ( G.length as ) ( swallow3 as bs ds ) ( swallow ( G.new cs ) )
#
forall as bs cs ds
. stream4 as bs (G.new cs) ds
= B.map (\((a, b, d), c) -> (a, b, c, d))
$ lockedZip2S (G.length as) (swallow3 as bs ds) (swallow (G.new cs))
#-}
# RULES " stream4 / new_4 "
forall as bs cs ds
. stream4 as ( G.new ds )
= B.map ( \((a , b , c ) , d ) - > ( a , b , c , d ) )
$ lockedZip2S ( G.length as ) ( swallow3 as bs cs ) ( swallow ( G.new ds ) )
#
forall as bs cs ds
. stream4 as bs cs (G.new ds)
= B.map (\((a, b, c), d) -> (a, b, c, d))
$ lockedZip2S (G.length as) (swallow3 as bs cs) (swallow (G.new ds))
#-}
| Stream five vectors of the same length .
stream5 :: (Monad m, Vector v a, Vector v b, Vector v c, Vector v d, Vector v e)
=> v a -> v b -> v c -> v d -> v e
-> Bundle m v (a, b, c, d, e)
stream5 aa bb cc dd ee
= lockedZip5S (G.length aa)
(swallow aa) (swallow bb) (swallow cc) (swallow dd)
(swallow ee)
# INLINE_STREAM stream5 #
# RULES " stream5 / new_1 "
forall as . stream5 ( G.new as ) bs cs ds es
= B.map ( \((b , c , d , e ) , a ) - > ( a , b , c , d , e ) )
$ lockedZip2S ( G.length bs ) ( swallow4 bs cs ds es ) ( swallow ( G.new as ) )
#
forall as bs cs ds es
. stream5 (G.new as) bs cs ds es
= B.map (\((b, c, d, e), a) -> (a, b, c, d, e))
$ lockedZip2S (G.length bs) (swallow4 bs cs ds es) (swallow (G.new as))
#-}
# RULES " stream5 / new_2 "
forall as . stream5 as ( G.new bs ) cs ds es
= B.map ( \((a , c , d , e ) , b ) - > ( a , b , c , d , e ) )
$ lockedZip2S ( G.length as ) ( swallow4 as cs ds es ) ( swallow ( G.new bs ) )
#
forall as bs cs ds es
. stream5 as (G.new bs) cs ds es
= B.map (\((a, c, d, e), b) -> (a, b, c, d, e))
$ lockedZip2S (G.length as) (swallow4 as cs ds es) (swallow (G.new bs))
#-}
# RULES " stream5 / new_3 "
forall as . stream5 as bs ( G.new cs ) ds es
= B.map ( \((a , b , d , e ) , c ) - > ( a , b , c , d , e ) )
$ lockedZip2S ( G.length as ) ( swallow4 as bs ds es ) ( swallow ( G.new cs ) )
#
forall as bs cs ds es
. stream5 as bs (G.new cs) ds es
= B.map (\((a, b, d, e), c) -> (a, b, c, d, e))
$ lockedZip2S (G.length as) (swallow4 as bs ds es) (swallow (G.new cs))
#-}
# RULES " stream5 / new_4 "
forall as . stream5 as bs cs ( G.new ds ) es
= B.map ( \((a , b , c , e ) , d ) - > ( a , b , c , d , e ) )
$ lockedZip2S ( G.length as ) ( swallow4 as bs cs es ) ( swallow ( G.new ds ) )
#
forall as bs cs ds es
. stream5 as bs cs (G.new ds) es
= B.map (\((a, b, c, e), d) -> (a, b, c, d, e))
$ lockedZip2S (G.length as) (swallow4 as bs cs es) (swallow (G.new ds))
#-}
# RULES " stream5 / new_5 "
forall as . stream5 as bs cs ds ( G.new es )
= B.map ( \((a , b , c , d ) , e ) - > ( a , b , c , d , e ) )
$ lockedZip2S ( G.length as ) ( swallow4 as bs cs ds ) ( swallow ( ) )
#
forall as bs cs ds es
. stream5 as bs cs ds (G.new es)
= B.map (\((a, b, c, d), e) -> (a, b, c, d, e))
$ lockedZip2S (G.length as) (swallow4 as bs cs ds) (swallow (G.new es))
#-}
| Stream six vectors of the same length .
stream6 :: (Monad m, Vector v a, Vector v b, Vector v c, Vector v d, Vector v e, Vector v f)
=> v a -> v b -> v c -> v d -> v e -> v f
-> Bundle m v (a, b, c, d, e, f)
stream6 aa bb cc dd ee ff
= lockedZip6S (G.length aa)
(swallow aa) (swallow bb) (swallow cc) (swallow dd)
(swallow ee) (swallow ff)
# INLINE_STREAM stream6 #
# RULES " stream6 / new_1 "
forall as . ( G.new as ) bs cs ds es fs
= B.map ( \((b , c , d , e , f ) , a ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length bs ) ( ) ( swallow ( G.new as ) )
#
forall as bs cs ds es fs
. stream6 (G.new as) bs cs ds es fs
= B.map (\((b, c, d, e, f), a) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length bs) (swallow5 bs cs ds es fs) (swallow (G.new as))
#-}
# RULES " stream6 / new_2 "
forall as . as ( G.new bs ) cs ds es fs
= B.map ( \((a , c , d , e , f ) , b ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length as ) ( swallow5 as cs ds es fs ) ( swallow ( G.new bs ) )
#
forall as bs cs ds es fs
. stream6 as (G.new bs) cs ds es fs
= B.map (\((a, c, d, e, f), b) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length as) (swallow5 as cs ds es fs) (swallow (G.new bs))
#-}
# RULES " stream6 / new_3 "
forall as . as bs ( G.new cs ) ds es fs
= B.map ( \((a , b , d , e , f ) , c ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length as ) ( swallow5 as bs ds es fs ) ( swallow ( G.new cs ) )
#
forall as bs cs ds es fs
. stream6 as bs (G.new cs) ds es fs
= B.map (\((a, b, d, e, f), c) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length as) (swallow5 as bs ds es fs) (swallow (G.new cs))
#-}
# RULES " stream6 / new_4 "
forall as . stream6 as bs cs ( G.new ds ) es fs
= B.map ( \((a , b , c , e , f ) , d ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length as ) ( swallow5 as bs cs es fs ) ( swallow ( G.new ds ) )
#
forall as bs cs ds es fs
. stream6 as bs cs (G.new ds) es fs
= B.map (\((a, b, c, e, f), d) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length as) (swallow5 as bs cs es fs) (swallow (G.new ds))
#-}
# RULES " stream6 / new_5 "
forall as . as bs cs ds ( ) fs
= B.map ( \((a , b , c , d , f ) , e ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length as ) ( swallow5 as bs cs ds fs ) ( swallow ( ) )
#
forall as bs cs ds es fs
. stream6 as bs cs ds (G.new es) fs
= B.map (\((a, b, c, d, f), e) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length as) (swallow5 as bs cs ds fs) (swallow (G.new es))
#-}
# RULES " stream6 / new_6 "
forall as . as bs cs ds es ( G.new fs )
= B.map ( \((a , b , c , d , e ) , f ) - > ( a , b , c , d , e , f ) )
$ lockedZip2S ( G.length as ) ( swallow5 as bs cs ds es ) ( swallow ( G.new fs ) )
#
forall as bs cs ds es fs
. stream6 as bs cs ds es (G.new fs)
= B.map (\((a, b, c, d, e), f) -> (a, b, c, d, e, f))
$ lockedZip2S (G.length as) (swallow5 as bs cs ds es) (swallow (G.new fs))
#-}
| Stream seven vectors of the same length .
stream7 :: (Monad m, Vector v a, Vector v b, Vector v c, Vector v d, Vector v e, Vector v f, Vector v g)
=> v a -> v b -> v c -> v d -> v e -> v f -> v g
-> Bundle m v (a, b, c, d, e, f, g)
stream7 aa bb cc dd ee ff gg
= lockedZip7S (G.length aa)
(swallow aa) (swallow bb) (swallow cc) (swallow dd)
(swallow ee) (swallow ff) (swallow gg)
# INLINE_STREAM stream7 #
# RULES " stream7 / new_1 "
forall as . ( G.new as ) bs cs ds es fs gs
= B.map ( \((b , c , d , e , f , ) , a ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length bs ) ( swallow6 bs cs ds es fs gs ) ( swallow ( G.new as ) )
#
forall as bs cs ds es fs gs
. stream7 (G.new as) bs cs ds es fs gs
= B.map (\((b, c, d, e, f, g), a) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length bs) (swallow6 bs cs ds es fs gs) (swallow (G.new as))
#-}
# RULES " stream7 / new_2 "
forall as . as ( G.new bs ) cs ds es fs gs
= B.map ( \((a , c , d , e , f , ) , b ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as cs ds es fs gs ) ( swallow ( G.new bs ) )
#
forall as bs cs ds es fs gs
. stream7 as (G.new bs) cs ds es fs gs
= B.map (\((a, c, d, e, f, g), b) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as cs ds es fs gs) (swallow (G.new bs))
#-}
# RULES " stream7 / new_3 "
forall as . stream7 as bs ( G.new cs ) ds es fs gs
= B.map ( \((a , b , d , e , f , ) , c ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as bs ds es fs gs ) ( swallow ( G.new cs ) )
#
forall as bs cs ds es fs gs
. stream7 as bs (G.new cs) ds es fs gs
= B.map (\((a, b, d, e, f, g), c) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as bs ds es fs gs) (swallow (G.new cs))
#-}
# RULES " stream7 / new_4 "
forall as . stream7 as ( G.new ds ) es fs gs
= B.map ( \((a , b , c , e , f , ) , d ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as bs cs es fs gs ) ( swallow ( G.new ds ) )
#
forall as bs cs ds es fs gs
. stream7 as bs cs (G.new ds) es fs gs
= B.map (\((a, b, c, e, f, g), d) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as bs cs es fs gs) (swallow (G.new ds))
#-}
# RULES " stream7 / new_5 "
forall as . stream7 as ( ) fs gs
= B.map ( \((a , b , c , d , f , ) , e ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as bs cs ds fs gs ) ( swallow ( ) )
#
forall as bs cs ds es fs gs
. stream7 as bs cs ds (G.new es) fs gs
= B.map (\((a, b, c, d, f, g), e) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as bs cs ds fs gs) (swallow (G.new es))
#-}
# RULES " stream7 / "
forall as . stream7 as ( G.new fs ) gs
= B.map ( \((a , b , c , d , e , ) , f ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as bs cs ds es gs ) ( swallow ( G.new fs ) )
#
forall as bs cs ds es fs gs
. stream7 as bs cs ds es (G.new fs) gs
= B.map (\((a, b, c, d, e, g), f) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as bs cs ds es gs) (swallow (G.new fs))
#-}
# RULES " stream7 / new_7 "
forall as . stream7 as ( )
= B.map ( \((a , b , c , d , e , f ) , ) - > ( a , b , c , d , e , f , ) )
$ lockedZip2S ( G.length as ) ( swallow6 as bs cs ds es fs ) ( swallow ( G.new gs ) )
#
forall as bs cs ds es fs gs
. stream7 as bs cs ds es fs (G.new gs)
= B.map (\((a, b, c, d, e, f), g) -> (a, b, c, d, e, f, g))
$ lockedZip2S (G.length as) (swallow6 as bs cs ds es fs) (swallow (G.new gs))
#-}
| Stream seven vectors of the same length .
stream8 :: (Monad m, Vector v a, Vector v b, Vector v c, Vector v d, Vector v e, Vector v f, Vector v g, Vector v h)
=> v a -> v b -> v c -> v d -> v e -> v f -> v g -> v h
-> Bundle m v (a, b, c, d, e, f, g, h)
stream8 aa bb cc dd ee ff gg hh
= lockedZip8S (G.length aa)
(swallow aa) (swallow bb) (swallow cc) (swallow dd)
(swallow ee) (swallow ff) (swallow gg) (swallow hh)
# RULES " stream8 / new_1 "
forall as . ( G.new as ) bs cs ds es fs gs hs
= B.map ( \((b , c , d , e , f , , h ) , a ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length bs ) ( swallow7 bs cs ds es fs gs hs ) ( swallow ( G.new as ) )
#
forall as bs cs ds es fs gs hs
. stream8 (G.new as) bs cs ds es fs gs hs
= B.map (\((b, c, d, e, f, g, h), a) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length bs) (swallow7 bs cs ds es fs gs hs) (swallow (G.new as))
#-}
# RULES " stream8 / new_2 "
forall as . as ( G.new bs ) cs ds es fs gs hs
= B.map ( \((a , c , d , e , f , , h ) , b ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( G.new bs ) )
#
forall as bs cs ds es fs gs hs
. stream8 as (G.new bs) cs ds es fs gs hs
= B.map (\((a, c, d, e, f, g, h), b) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as cs ds es fs gs hs) (swallow (G.new bs))
#-}
# RULES " stream8 / new_3 "
forall as . as bs ( G.new cs ) ds es fs gs hs
= B.map ( \((a , b , d , e , f , , h ) , c ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as bs ds es fs gs hs ) ( swallow ( G.new cs ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs (G.new cs) ds es fs gs hs
= B.map (\((a, b, d, e, f, g, h), c) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs ds es fs gs hs) (swallow (G.new cs))
#-}
# RULES " stream8 / new_4 "
forall as . as bs cs ( G.new ds ) es fs gs hs
= B.map ( \((a , b , c , e , f , , h ) , d ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( G.new ds ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs cs (G.new ds) es fs gs hs
= B.map (\((a, b, c, e, f, g, h), d) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs cs es fs gs hs) (swallow (G.new ds))
#-}
# RULES " stream8 / new_5 "
forall as . as bs cs ds ( ) fs gs hs
= B.map ( \((a , b , c , d , f , , h ) , e ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs cs ds (G.new es) fs gs hs
= B.map (\((a, b, c, d, f, g, h), e) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs cs ds fs gs hs) (swallow (G.new es))
#-}
# RULES " stream8 / new_6 "
forall as . as bs cs ds es ( G.new fs ) gs hs
= B.map ( \((a , b , c , d , e , g , h ) , f ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( G.new fs ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs cs ds es (G.new fs) gs hs
= B.map (\((a, b, c, d, e, g, h), f) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs cs ds es gs hs) (swallow (G.new fs))
#-}
# RULES " stream8 / new_7 "
forall as . as bs cs ds es fs ( ) hs
= B.map ( \((a , b , c , d , e , f , h ) , ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( G.new gs ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs cs ds es fs (G.new gs) hs
= B.map (\((a, b, c, d, e, f, h), g) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs cs ds es fs hs) (swallow (G.new gs))
#-}
# RULES " stream8 / new_8 "
forall as . as bs cs ds es fs gs ( )
= B.map ( \((a , b , c , d , e , f , h ) , ) - > ( a , b , c , d , e , f , , h ) )
$ lockedZip2S ( G.length as ) ( swallow7 as ) ( swallow ( ) )
#
forall as bs cs ds es fs gs hs
. stream8 as bs cs ds es fs gs (G.new hs)
= B.map (\((a, b, c, d, e, f, h), g) -> (a, b, c, d, e, f, g, h))
$ lockedZip2S (G.length as) (swallow7 as bs cs ds es fs gs) (swallow (G.new hs))
#-}
| Zip the first ' n ' elements of two streams .
lockedZip2S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b
-> Bundle m v (a, b)
lockedZip2S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
= B.fromStream (Stream step (sa1, sa2, 0)) (S.Exact len)
where
step (s1, s2, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
return $ case (step1, step2) of
(Yield x1 s1', Yield x2 s2')
| i < len -> Yield (x1, x2) (s1', s2', i + 1)
_ -> Done
# INLINE_STREAM lockedZip2S #
| Zip the first ' n ' elements of three streams .
lockedZip3S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c
-> Bundle m v (a, b, c)
lockedZip3S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
= B.fromStream (Stream step (sa1, sa2, sa3, 0)) (S.Exact len)
where
step (s1, s2, s3, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
return $ case (step1, step2, step3) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3')
| i < len -> Yield (x1, x2, x3) (s1', s2', s3', i + 1)
_ -> Done
# INLINE_STREAM lockedZip3S #
| Zip the first ' n ' elements of four streams .
lockedZip4S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c -> Bundle m v d
-> Bundle m v (a, b, c, d)
lockedZip4S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
(Bundle {sElems=Stream mkStep4 sa4})
= B.fromStream (Stream step (sa1, sa2, sa3, sa4, 0)) (S.Exact len)
where
step (s1, s2, s3, s4, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
step4 <- mkStep4 s4
return $ case (step1, step2, step3, step4) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3', Yield x4 s4')
| i < len -> Yield (x1, x2, x3, x4) (s1', s2', s3', s4', i + 1)
_ -> Done
# INLINE_STREAM lockedZip4S #
| Zip the first ' n ' elements of five streams .
lockedZip5S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c -> Bundle m v d -> Bundle m v e
-> Bundle m v (a, b, c, d, e)
lockedZip5S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
(Bundle {sElems=Stream mkStep4 sa4})
(Bundle {sElems=Stream mkStep5 sa5})
= B.fromStream (Stream step (sa1, sa2, sa3, sa4, sa5, 0)) (S.Exact len)
where
step (s1, s2, s3, s4, s5, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
step4 <- mkStep4 s4
step5 <- mkStep5 s5
return $ case (step1, step2, step3, step4, step5) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3', Yield x4 s4', Yield x5 s5')
| i < len -> Yield (x1, x2, x3, x4, x5) (s1', s2', s3', s4', s5', i + 1)
_ -> Done
# INLINE_STREAM lockedZip5S #
| Zip the first ' n ' elements of six streams .
lockedZip6S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c -> Bundle m v d -> Bundle m v e -> Bundle m v f
-> Bundle m v (a, b, c, d, e, f)
lockedZip6S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
(Bundle {sElems=Stream mkStep4 sa4})
(Bundle {sElems=Stream mkStep5 sa5})
(Bundle {sElems=Stream mkStep6 sa6})
= B.fromStream (Stream step (sa1, sa2, sa3, sa4, sa5, sa6, 0)) (S.Exact len)
where
step (s1, s2, s3, s4, s5, s6, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
step4 <- mkStep4 s4
step5 <- mkStep5 s5
step6 <- mkStep6 s6
return $ case (step1, step2, step3, step4, step5, step6) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3', Yield x4 s4', Yield x5 s5', Yield x6 s6')
| i < len -> Yield (x1, x2, x3, x4, x5, x6) (s1', s2', s3', s4', s5', s6', i + 1)
_ -> Done
# INLINE_STREAM lockedZip6S #
| Zip the first ' n ' elements of seven streams .
lockedZip7S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c -> Bundle m v d -> Bundle m v e -> Bundle m v f -> Bundle m v g
-> Bundle m v (a, b, c, d, e, f, g)
lockedZip7S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
(Bundle {sElems=Stream mkStep4 sa4})
(Bundle {sElems=Stream mkStep5 sa5})
(Bundle {sElems=Stream mkStep6 sa6})
(Bundle {sElems=Stream mkStep7 sa7})
= B.fromStream (Stream step (sa1, sa2, sa3, sa4, sa5, sa6, sa7, 0)) (S.Exact len)
where
step (s1, s2, s3, s4, s5, s6, s7, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
step4 <- mkStep4 s4
step5 <- mkStep5 s5
step6 <- mkStep6 s6
step7 <- mkStep7 s7
return $ case (step1, step2, step3, step4, step5, step6, step7) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3', Yield x4 s4', Yield x5 s5', Yield x6 s6', Yield x7 s7')
| i < len -> Yield (x1, x2, x3, x4, x5, x6, x7) (s1', s2', s3', s4', s5', s6', s7', i + 1)
_ -> Done
# INLINE_STREAM lockedZip7S #
| Zip the first ' n ' elements of eight streams .
lockedZip8S
:: Monad m
=> Int
-> Bundle m v a -> Bundle m v b -> Bundle m v c -> Bundle m v d -> Bundle m v e -> Bundle m v f -> Bundle m v g -> Bundle m v h
-> Bundle m v (a, b, c, d, e, f, g, h)
lockedZip8S len
(Bundle {sElems=Stream mkStep1 sa1})
(Bundle {sElems=Stream mkStep2 sa2})
(Bundle {sElems=Stream mkStep3 sa3})
(Bundle {sElems=Stream mkStep4 sa4})
(Bundle {sElems=Stream mkStep5 sa5})
(Bundle {sElems=Stream mkStep6 sa6})
(Bundle {sElems=Stream mkStep7 sa7})
(Bundle {sElems=Stream mkStep8 sa8})
= B.fromStream (Stream step (sa1, sa2, sa3, sa4, sa5, sa6, sa7, sa8, 0)) (S.Exact len)
where
step (s1, s2, s3, s4, s5, s6, s7, s8, i)
= i `seq`
do step1 <- mkStep1 s1
step2 <- mkStep2 s2
step3 <- mkStep3 s3
step4 <- mkStep4 s4
step5 <- mkStep5 s5
step6 <- mkStep6 s6
step7 <- mkStep7 s7
step8 <- mkStep8 s8
return $ case (step1, step2, step3, step4, step5, step6, step7, step8) of
(Yield x1 s1', Yield x2 s2', Yield x3 s3', Yield x4 s4', Yield x5 s5', Yield x6 s6', Yield x7 s7', Yield x8 s8')
| i < len -> Yield (x1, x2, x3, x4, x5, x6, x7, x8) (s1', s2', s3', s4', s5', s6', s7', s8', i + 1)
_ -> Done
# INLINE_STREAM lockedZip8S #
|
78c08cc7154c0e3658f3022ded0e0ab784b3271170b630c0439c77b192cfb2e1 | mransan/ocaml-protoc | parse_extension_range.ml | let parse s =
Pb_parsing_parser.extension_range_list_ Pb_parsing_lexer.lexer
(Lexing.from_string s)
let parse_extension s =
Pb_parsing_parser.extension_ Pb_parsing_lexer.lexer (Lexing.from_string s)
let parse_reserved s =
Pb_parsing_parser.reserved_ Pb_parsing_lexer.lexer (Lexing.from_string s)
module Pt = Pb_parsing_parse_tree
let () =
let s = "1" in
let ev = parse s in
assert (Pt.Extension_single_number 1 = List.hd ev);
()
let () =
let s = "1 to 2" in
let ev = parse s in
assert (Pt.Extension_range (1, Pt.To_number 2) = List.hd ev);
()
let () =
let s = "1 to -1" in
let ev = parse s in
assert (Pt.Extension_range (1, Pt.To_number (-1)) = List.hd ev);
()
let () =
let s = "1 to max" in
let ev = parse s in
assert (Pt.Extension_range (1, Pt.To_max) = List.hd ev);
()
let () =
let s = "1,2,3 to 10, 11 to max" in
let ev = parse s in
(match ev with
| [ ev1; ev2; ev3; ev4 ] ->
assert (Pt.Extension_single_number 1 = ev1);
assert (Pt.Extension_single_number 2 = ev2);
assert (Pt.Extension_range (3, Pt.To_number 10) = ev3);
assert (Pt.Extension_range (11, Pt.To_max) = ev4)
| _ -> (assert false : unit));
()
let () =
let s = "extensions 1,2,3 to 10, 11 to max;" in
let ev = parse_extension s in
(match ev with
| [ ev1; ev2; ev3; ev4 ] ->
assert (Pt.Extension_single_number 1 = ev1);
assert (Pt.Extension_single_number 2 = ev2);
assert (Pt.Extension_range (3, Pt.To_number 10) = ev3);
assert (Pt.Extension_range (11, Pt.To_max) = ev4)
| _ -> (assert false : unit));
()
let () =
let s = "reserved 1,2,3 to 10, 11 to max;" in
let ev = parse_reserved s in
(match ev with
| [ ev1; ev2; ev3; ev4 ] ->
assert (Pt.Extension_single_number 1 = ev1);
assert (Pt.Extension_single_number 2 = ev2);
assert (Pt.Extension_range (3, Pt.To_number 10) = ev3);
assert (Pt.Extension_range (11, Pt.To_max) = ev4)
| _ -> (assert false : unit));
()
let test_failure f =
match f () with
| _ -> (assert false : unit)
| exception Failure _ -> ()
| exception Parsing.Parse_error -> ()
let () =
let s = "1 until 2" in
test_failure (fun () -> parse s);
()
let () =
let s = "1 to min" in
test_failure (fun () -> parse s);
()
let () = print_endline "Parse Extension Range... Ok"
| null | https://raw.githubusercontent.com/mransan/ocaml-protoc/e43b509b9c4a06e419edba92a0d3f8e26b0a89ba/src/tests/unit-tests/parse_extension_range.ml | ocaml | let parse s =
Pb_parsing_parser.extension_range_list_ Pb_parsing_lexer.lexer
(Lexing.from_string s)
let parse_extension s =
Pb_parsing_parser.extension_ Pb_parsing_lexer.lexer (Lexing.from_string s)
let parse_reserved s =
Pb_parsing_parser.reserved_ Pb_parsing_lexer.lexer (Lexing.from_string s)
module Pt = Pb_parsing_parse_tree
let () =
let s = "1" in
let ev = parse s in
assert (Pt.Extension_single_number 1 = List.hd ev);
()
let () =
let s = "1 to 2" in
let ev = parse s in
assert (Pt.Extension_range (1, Pt.To_number 2) = List.hd ev);
()
let () =
let s = "1 to -1" in
let ev = parse s in
assert (Pt.Extension_range (1, Pt.To_number (-1)) = List.hd ev);
()
let () =
let s = "1 to max" in
let ev = parse s in
assert (Pt.Extension_range (1, Pt.To_max) = List.hd ev);
()
let () =
let s = "1,2,3 to 10, 11 to max" in
let ev = parse s in
(match ev with
| [ ev1; ev2; ev3; ev4 ] ->
assert (Pt.Extension_single_number 1 = ev1);
assert (Pt.Extension_single_number 2 = ev2);
assert (Pt.Extension_range (3, Pt.To_number 10) = ev3);
assert (Pt.Extension_range (11, Pt.To_max) = ev4)
| _ -> (assert false : unit));
()
let () =
let s = "extensions 1,2,3 to 10, 11 to max;" in
let ev = parse_extension s in
(match ev with
| [ ev1; ev2; ev3; ev4 ] ->
assert (Pt.Extension_single_number 1 = ev1);
assert (Pt.Extension_single_number 2 = ev2);
assert (Pt.Extension_range (3, Pt.To_number 10) = ev3);
assert (Pt.Extension_range (11, Pt.To_max) = ev4)
| _ -> (assert false : unit));
()
let () =
let s = "reserved 1,2,3 to 10, 11 to max;" in
let ev = parse_reserved s in
(match ev with
| [ ev1; ev2; ev3; ev4 ] ->
assert (Pt.Extension_single_number 1 = ev1);
assert (Pt.Extension_single_number 2 = ev2);
assert (Pt.Extension_range (3, Pt.To_number 10) = ev3);
assert (Pt.Extension_range (11, Pt.To_max) = ev4)
| _ -> (assert false : unit));
()
let test_failure f =
match f () with
| _ -> (assert false : unit)
| exception Failure _ -> ()
| exception Parsing.Parse_error -> ()
let () =
let s = "1 until 2" in
test_failure (fun () -> parse s);
()
let () =
let s = "1 to min" in
test_failure (fun () -> parse s);
()
let () = print_endline "Parse Extension Range... Ok"
|
|
0f69820e7b5af0d172372aa2fa8bdbe45ae674c1ef7ceba9a4e1ef77eb60f7df | oakes/Paravim | text.clj | (ns paravim.text
(:require [play-cljc.text :as text]))
(def bitmap-size 1024)
(def bitmaps {:firacode (text/->bitmap bitmap-size bitmap-size)
:roboto (text/->bitmap bitmap-size bitmap-size)})
(def font-height 128)
(def baked-fonts {:firacode (text/->baked-font "ttf/FiraCode-Regular.ttf" font-height (:firacode bitmaps))
:roboto (text/->baked-font "ttf/Roboto-Regular.ttf" font-height (:roboto bitmaps))})
(defn load-font-clj [font-key callback]
(callback (font-key bitmaps) (font-key baked-fonts)))
(defmacro load-font-cljs [font-key callback]
(let [{:keys [width height] :as bitmap} (font-key bitmaps)]
`(let [image# (js/Image. ~width ~height)]
(doto image#
(-> .-src (set! ~(text/bitmap->data-uri bitmap)))
(-> .-onload (set! #(~callback {:data image# :width ~width :height ~height} ~(font-key baked-fonts))))))))
| null | https://raw.githubusercontent.com/oakes/Paravim/871b9adf4e9819a7b9f2c63466c55640f0f8c280/src/paravim/text.clj | clojure | (ns paravim.text
(:require [play-cljc.text :as text]))
(def bitmap-size 1024)
(def bitmaps {:firacode (text/->bitmap bitmap-size bitmap-size)
:roboto (text/->bitmap bitmap-size bitmap-size)})
(def font-height 128)
(def baked-fonts {:firacode (text/->baked-font "ttf/FiraCode-Regular.ttf" font-height (:firacode bitmaps))
:roboto (text/->baked-font "ttf/Roboto-Regular.ttf" font-height (:roboto bitmaps))})
(defn load-font-clj [font-key callback]
(callback (font-key bitmaps) (font-key baked-fonts)))
(defmacro load-font-cljs [font-key callback]
(let [{:keys [width height] :as bitmap} (font-key bitmaps)]
`(let [image# (js/Image. ~width ~height)]
(doto image#
(-> .-src (set! ~(text/bitmap->data-uri bitmap)))
(-> .-onload (set! #(~callback {:data image# :width ~width :height ~height} ~(font-key baked-fonts))))))))
|
|
1222b9f0a1f885a69a2e8fa9100cfe766651490685a3bd517d4c3c627e76ee19 | screenshotbot/screenshotbot-oss | compare.lisp | ;;;; Copyright 2018-Present Modern Interpreters Inc.
;;;;
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(uiop:define-package :screenshotbot/dashboard/compare
For bknr
(:use #:cl
#:alexandria
#:nibble
#:screenshotbot/template
#:screenshotbot/diff-report
#:screenshotbot/model/screenshot
#:screenshotbot/model/image-comparison
#:screenshotbot/model/image
#:screenshotbot/model/view
#:screenshotbot/model/report
#:screenshotbot/model/channel
#:screenshotbot/ignore-and-log-errors
#:screenshotbot/model/recorder-run)
(:import-from #:util
#:find-by-oid
#:oid)
(:import-from #:markup #:deftag)
(:import-from #:screenshotbot/server
#:make-thread
#:defhandler)
(:import-from #:screenshotbot/report-api
#:render-diff-report)
(:import-from #:screenshotbot/dashboard/run-page
#:run-row-filter
#:page-nav-dropdown
#:row-filter
#:mask-editor
#:commit)
(:import-from #:screenshotbot/model/image
#:dimension-width
#:dimension-height
#:image-dimensions
#:map-unequal-pixels
#:image-blob
#:rect-as-list)
(:import-from #:screenshotbot/magick
#:run-magick)
(:import-from #:core/ui/paginated
#:paginated)
(:import-from #:bknr.datastore
#:store-object)
(:import-from #:bknr.datastore
#:persistent-class)
(:import-from #:bknr.indices
#:hash-index)
(:import-from #:bknr.datastore
#:make-blob-from-file)
(:import-from #:screenshotbot/user-api
#:can-view!
#:current-user
#:created-at
#:current-company)
(:import-from #:screenshotbot/dashboard/image
#:handle-resized-image)
(:import-from #:bknr.datastore
#:store-object-id)
(:import-from #:bknr.datastore
#:store-object-id)
(:import-from #:auto-restart
#:with-auto-restart)
(:import-from #:bknr.datastore
#:delete-object)
(:import-from #:nibble
#:nibble-url)
(:import-from #:screenshotbot/magick/magick-lw
#:get-non-alpha-pixels
#:with-wand)
(:import-from #:screenshotbot/diff-report
#:actual-item
#:changes-groups
#:get-tab-title)
(:import-from #:bknr.datastore
#:cascading-delete-object)
(:import-from #:screenshotbot/taskie
#:timeago)
(:import-from #:util/misc
#:?.)
(:import-from #:screenshotbot/model/transient-object
#:with-transient-copy)
(:import-from #:screenshotbot/model/image-comparison
#:find-image-comparison-on-images)
(:import-from #:bknr.datastore
#:store-object)
(:import-from #:screenshotbot/model/view
#:can-edit
#:can-edit!)
(:import-from #:screenshotbot/dashboard/review-link
#:review-link)
(:import-from #:screenshotbot/cdn
#:make-image-cdn-url)
(:import-from #:screenshotbot/model/screenshot
#:abstract-screenshot)
(:export
#:diff-report
#:render-acceptable
#:make-diff-report
#:diff-report-empty-p
#:render-diff-report
#:diff-report-changes
#:warmup-comparison-images))
(in-package :screenshotbot/dashboard/compare)
fake symbols for bknr migration
(progn
'(result
before
after
identical-p
result))
(markup:enable-reader)
(deftag render-acceptable (&key acceptable)
(let ((accept (nibble (redirect :name :accept)
(setf (acceptable-state acceptable :user (current-user)) :accepted)
(hex:safe-redirect redirect)))
(reject (nibble (redirect :name :reject)
(setf (acceptable-state acceptable :user (current-user)) :rejected)
(hex:safe-redirect redirect)))
(btn-class
(ecase (acceptable-state acceptable)
(:accepted
"dropdown-report-accepted")
(:rejected
"dropdown-report-rejected")
((nil)
"")))
(btn-text
(ecase (acceptable-state acceptable)
(:accepted
"Accepted")
(:rejected
"Rejected")
((nil)
"Review"))))
<markup:merge-tag>
<button class= (format nil"btn btn-secondary dropdown-toggle ~a" btn-class) type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
,(progn btn-text)
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton" style= "z-index: 99999999; position: static" >
<form action=accept method= "POST" >
<button action= "submit" class= "btn btn-link acceptable accept-link dropdown-item" >
<input type= "hidden" name= "redirect"
value= (hunchentoot:script-name*) />
<mdi name= "check" />
Accept
</button>
</form>
<form action=reject method= "POST">
<input type= "hidden" name= "redirect"
value= (hunchentoot:script-name* ) />
<button action= "submit" class= "btn btn-link acceptable reject-link dropdown-item" >
<mdi name= "close" />
Reject</button>
</form>
</div>
</markup:merge-tag>))
(defun diff-report-empty-p (diff-report)
(not
(or (diff-report-added diff-report)
(diff-report-deleted diff-report)
(diff-report-changes diff-report))))
(defhandler (compare-page :uri "/runs/:id/compare/:to") (id to)
(when (string= "254" id)
(hex:safe-redirect "/report/5fd16bcf4f4b3822fd000146"))
(flet ((find-run (id)
(let ((ret (find-by-oid id 'recorder-run)))
(assert ret)
ret)))
(let* ((run (find-run id))
(to (find-run to)))
(can-view! run to)
<app-template body-class= "dashboard bg-white" >
,(async-diff-report :run run :to to)
</app-template>)))
(deftag picture-with-img (&key image dimensions alt class)
<picture>
<source srcset= (image-public-url image :size :full-page :type :webp) type= "image/webp" />
<img class= (format nil "screenshot-image change-image ~a" class) src= (image-public-url image :size :full-page :type :png)
loading= "lazy"
alt=alt
width= (?. dimension-width dimensions)
height= (?. dimension-height dimensions)
/>
</picture>)
(deftag change-image-row (&key before-image
after-image
before-dims
after-dims)
<div class="change-image-row">
<picture-with-img
image=before-image
dimensions=before-dims
alt= "before image"
class= "change-image-left" />
<mdi name= "arrow_forward" />
<picture-with-img
image=after-image
dimensions=after-dims
alt="after image"
class= "change-image-right" />
</div>)
(deftag change-image-row-triple (&key before-image
after-image
comp-image)
<div class="change-image-row change-image-row-triple">
<img class= "screenshot-image change-image change-image-left" src= before-image />
<img class= "screenshot-image change-image change-image-right" src= after-image />
<:img data-src= comp-image
class= "bg-primary image-comparison-modal-image screenshot-image change-image" alt= "Image Difference" />
</div>)
(defclass image-comparison-job ()
((donep :initform nil
:accessor donep)
(lock :initform (bt:make-lock "image-comparison")
:reader lock)
(before-image :initarg :before-image
:reader before-image)
(after-image :initarg :after-image
:reader after-image)
(image-comparison
:initarg :image-comparison
:accessor image-comparison
:documentation "The actual image-comparison object. You can get
the resulting image and other context from this object")))
(defmethod find-image-comparison ((before-screenshot abstract-screenshot)
(after-screenshot abstract-screenshot))
second level of caching , we 're going to look through the
;; datastore to see if there are any previous images
(let ((before (screenshot-image before-screenshot))
(after (screenshot-image after-screenshot)))
;; Avoid computation for large reverts
(when (> (store-object-id before)
(store-object-id after))
(rotatef before after))
(find-image-comparison-on-images
before
after
(screenshot-masks after-screenshot))))
(defmethod prepare-image-comparison-file ((self image-comparison-job))
(bt:with-lock-held ((lock self))
(cond
((donep self)
(image-comparison self))
(t
(setf (image-comparison self)
(find-image-comparison (before-image self)
(after-image self)))))))
(defmethod prepare-image-comparison ((self image-comparison-job)
&key
I ca n't use : full - page here because the JS is n't
;; designed to handle that yet.
(size nil)
(warmup nil))
(let ((image-comparison (prepare-image-comparison-file self)))
(cond
(warmup
(when size
(handle-resized-image (image-comparison-result image-comparison) size :warmup t)))
(t
(setf (hunchentoot:content-type*) "application/json")
(json:encode-json-to-string
`((:identical . ,(identical-p image-comparison))
;; for debugging: e.g. if we need to delete the comparison
(:store-object-id
.
,(when (typep image-comparison 'store-object)
(bknr.datastore:store-object-id image-comparison)))
(:zoom-to . ,(nibble-url (nibble (:name :zoom) (random-zoom-to-on-result
image-comparison))))
(:src . ,(make-image-cdn-url (image-public-url (image-comparison-result image-comparison) :size size)))
(:background . ,(make-image-cdn-url (image-public-url (screenshot-image (before-image self)) :size size)))
(:masks .
,(or
(loop for mask in (image-comparison-masks image-comparison)
collect
`((:left . ,(mask-rect-left mask))
(:top . ,(mask-rect-top mask))
(:width . ,(mask-rect-width mask))
(:height . ,(mask-rect-height mask))))
#()))))))))
(defun random-zoom-to-on-result (image-comparison)
(setf (hunchentoot:content-type*) "application/json")
(with-local-image (file (image-comparison-result image-comparison))
(with-wand (wand :file file)
(log:debug"random-zoom-to-on-result on ~a" file)
(let ((pxs (get-non-alpha-pixels wand
:masks (image-comparison-masks image-comparison))))
(let ((i (random (car (array-dimensions pxs)))))
(let ((dims (image-dimensions (image-comparison-result image-comparison))))
(json:encode-json-to-string
`((:y . ,(aref pxs i 1))
(:x . ,(aref pxs i 0))
(:width . ,(dimension-width dims))
(:height . ,(dimension-height dims))))))))))
(defun async-diff-report (&rest args &key &allow-other-keys)
(let* ((data nil)
(session auth:*current-session*)
(request hunchentoot:*request*)
(acceptor hunchentoot:*acceptor*)
(data-check-nibble (nibble (:name :data-check)
(setf (hunchentoot:content-type*) "application/json")
(json:encode-json-to-string
(cond
((eql :error data)
`((:state . "error")))
(data
`((:data . ,(markup:write-html data))
(:state . "done")))
(t
`((:state . "processing"))))))))
(make-thread (lambda ()
(ignore-and-log-errors ()
(handler-bind ((error (lambda (e)
(declare (ignore e))
(setf data :error))))
(let ((auth:*current-session* session)
(hunchentoot:*request* request)
(hunchentoot:*acceptor* acceptor))
(setf data (apply 'render-diff-report args)))))))
<div class= "async-fetch spinner-border" role= "status" data-check-nibble=data-check-nibble />))
(defun warmup-comparison-images (run previous-run)
(make-thread
(lambda ()
(restart-case
(let ((report (make-diff-report run previous-run)))
;; warmup in the order that the report would be typically
;; viewed.
(dolist (group (changes-groups report))
(let ((changes (mapcar #'actual-item (group-items group))))
(loop for change in changes
for i from 1
for before = (before change)
for after = (after change)
for image-comparison-job = (make-instance 'image-comparison-job
:before-image before
:after-image after)
do
(progn
(log:info "Warming up compare image ~d of ~d (~a)" i (length changes)
(screenshot-name after))
(restart-case
(prepare-image-comparison image-comparison-job :size nil
:warmup t)
(ignore-this-image ()
nil)))))))
(retry-warmup-thread ()
(warmup-comparison-images run previous-run))))
:name "warmup-comparison-images"))
(defun all-comparisons-page (report)
<app-template>
<a href= "javascript:window.history.back()">Back to Report</a>
,(paginated
(lambda (change)
(let* ((before (before change))
(after (after change))
(image-comparison-job (make-instance 'image-comparison-job
:before-image before
:after-image after))
(comparison-image (util:copying (image-comparison-job)
(nibble (:name :comparison)
(prepare-image-comparison image-comparison-job :size :full-page)))))
<div class= "image-comparison-wrapper" >
<h3>,(screenshot-name before)</h3>
<change-image-row-triple before-image=(image-public-url (screenshot-image before) :size :full-page)
after-image=(image-public-url (screenshot-image after) :size :full-page)
comp-image=comparison-image
/>
</div>))
:num 5
:items (diff-report-changes report))
</app-template>)
(deftag progress-img (&key (alt "Image Difference") src class)
"An <img> with a progress indicator for the image loading."
<div class= (format nil "progress-image-wrapper ~a" class) >
<div class= "alert alert-danger images-identical" style= "display:none" >
<p>
<strong>The two images are identical.</strong> This is likely because the images still have their EXIF data, e.g. timestamps.
</p>
<p class= "mb-0" >
You can pre-process images to remove timestamps. One way to do this is to use: `<:tt>exiftool -all= *.png</:tt>`.
</p>
</div>
<div class= "loading">
<div class="spinner-border" role="status">
<!-- <span class="sr-only">Loading...</span> -->
</div>
Loading (this could take upto 30s in some cases)
</div>
<div>
<div class= "alert alert-info">
<strong>New interactive comparisons!</strong> Use your mouse to pan through the image. Use the <strong>mouse wheel</strong> to zoom into a location.
</div>
<:canvas data-src=src
class= "image-comparison-modal-image" />
</div>
</div>)
(deftag zoom-to-change-button ()
<button type="button" class="btn btn-secondary zoom-to-change">
<div class="spinner-border" role="status" style="display:none; height: 1em; width: 1em" />
Zoom to change
</button>)
(defclass tab ()
((title :initarg :title
:reader tab-title)
(content :initarg :content
:reader tab-content)))
(defun maybe-tabulate (tabs &key header &aux (id (format nil "a~a" (random 10000000))))
(cond
((and (eql 1 (length tabs))
(str:emptyp (tab-title (car tabs))))
;; don't show the tabulation
<markup:merge-tag>
<div class= "card-header">
,(progn header)
</div>
<div class= "card-body">
,(tab-content (car tabs))
</div>
</markup:merge-tag>)
(t
<markup:merge-tag>
<div class= "card-header">
,(progn header)
<ul class= "nav nav-tabs card-header-tabs" role= "tablist" >
,@ (loop for tab in tabs
for ctr from 0
collect
<li class= "nav-item" role= "presentation" >
<button class= (format nil "nav-link ~a" (if (= ctr 0) "active" ""))
data-bs-toggle= "tab"
data-bs-target= (format nil "#~a-~a" id ctr)
data-title= (tab-title tab)
role= "tab"
aria-controls= (format nil "~a-~a" id ctr)
aria-selector=(if (= ctr 0) "true" "false") >
,(tab-title tab)
</button>
</li>)
</ul>
</div>
<div class= "card-body">
<div class= "tab-content">
,@(loop for tab in tabs
for ctr from 0
collect
<div class= (format nil "tab-pane ~a" (if (= ctr 0) "show active" ""))
id= (format nil "~a-~a" id ctr)
role= "tab-panel"
aria-labelled-by= (tab-title tab) >
,(tab-content tab)
</div>)
</div>
</div>
</markup:merge-tag>)))
(defun make-overlay-image (before after)
(let ((image-comparison-job (make-instance 'image-comparison-job
:before-image before
:after-image after)))
(image-comparison-result
(prepare-image-comparison-file image-comparison-job))))
(defun render-change-group (group run script-name &key search)
<div class= "col-12">
<div class= "card mb-3">
,(maybe-tabulate
(loop for group-item in (group-items group)
for change = (actual-item group-item)
for next-id = (random 1000000000000000)
for s = (before change)
for x = (after change)
collect
(make-instance
'tab
:title (group-item-subtitle group-item)
:content
(let* ((s s)
(x x)
(toggle-id (format nil "toggle-id-~a" next-id)))
<div class= "" >
<div class= "screenshot-header" >
<ul class= "screenshot-options-menu" >
<li>
<a href= "#" data-bs-toggle= "modal" data-bs-target= (format nil "#~a" toggle-id) >Compare</a>
</li>
<li>
<a href= (hex:make-url "/channel/:channel/history" :channel (store-object-id (recorder-run-channel run))
:screenshot-name (screenshot-name x))>
Full History
</a>
</li>
<li>
<a href= (nibble (:name :mask-editor) (mask-editor (recorder-run-channel run) s
:redirect script-name
:overlay (make-overlay-image x s)))
>
Edit Masks
</a>
</li>
</ul>
</div>
<change-image-row before-image=(screenshot-image x)
after-image=(screenshot-image s)
before-dims= (ignore-errors (image-dimensions (screenshot-image x)))
after-dims= (ignore-errors (image-dimensions (screenshot-image s)))
/>
<comparison-modal before=x after=s toggle-id=toggle-id />
</div>)))
:header <h4 class= "screenshot-title">,(highlight-search-term search (group-title group))</h4>)
</div>
</div>)
(defun highlight-search-term (search title)
(cond
((str:emptyp search)
title)
(t
(let* ((start (search (str:downcase search) (str:downcase title)))
(end (+ start (length search))))
(markup:make-merge-tag
(list
<span class= "text-muted">,(subseq title 0 start)</span>
<span class= "" >,(subseq title start end)</span>
<span class= "text-muted">,(subseq title end)</span>))))))
(deftag comparison-modal (&key toggle-id before after)
(let* ((modal-label (format nil "~a-modal-label" toggle-id))
(image-comparison-job
(make-instance 'image-comparison-job
:before-image before
:after-image after))
(compare-nibble (nibble (:name :compare-link)
(prepare-image-comparison
image-comparison-job))))
<div class= "modal fade image-comparison-modal" id= toggle-id tabindex= "-1" role= "dialog"
aria-labelledby=modal-label
aria-hidden= "true" >
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id=modal-label >Image Comparison</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" />
</div>
<div class="modal-body">
<progress-img
src=compare-nibble
alt= "Image difference" />
</div>
<div class="modal-footer">
<zoom-to-change-button />
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>))
(deftag compare-tab-a (body &key type default-type)
<a class= (format nil "nav-link ~a" (when (string= type default-type) "active"))
href= "#" data-type= type >
,@body
</a>)
(deftag render-diff-report (children &key run to
more
acceptable
(re-run nil))
(declare (ignore re-run))
(let* ((report (make-diff-report run to))
(all-comparisons (nibble (:name :all-comparison)
(all-comparisons-page report))))
(declare (ignorable all-comparisons))
(let* ((changes-groups (changes-groups report))
(added-groups (added-groups report))
(deleted-groups (deleted-groups report))
(default-type
(or
(hunchentoot:parameter "type")
(cond
(changes-groups "changes")
(added-groups "added")
(deleted-groups "deleted")
(t "changes")))))
<markup:merge-tag>
<div class= "mt-3 d-flex flex-wrap justify-content-between compare-header" >
<div class= "report-search-wrapper" >
<div class= "input-group">
<span class= "input-group-text report-search" >
<mdi name= "search" />
</span>
<input class= "form-control search d-inline-block" type= "text" autocomplete= "off"
placeholder= "Search..."
data-target= ".report-result" />
</div>
</div>
<div class= "options" >
<ul class= "nav nav-pills report-selector" data-target= ".report-result" >
<li class= "nav-item">
<compare-tab-a type= "changes" default-type=default-type >
,(length changes-groups) changes
</compare-tab-a>
</li>
<li class= "nav-item">
<compare-tab-a type= "added" default-type=default-type >
,(length added-groups) added
</compare-tab-a>
</li>
<li class= "nav-item">
<compare-tab-a type= "deleted" default-type=default-type >
,(length deleted-groups) deleted
</compare-tab-a>
</li>
<markup:merge-tag>
<li class= "nav-item" >
<button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
More
</button>
<ul class="dropdown-menu dropdown-menu-end">
,@ (loop for (name . url) in more
collect
<li><a class="dropdown-item" href=url >,(progn name)</a></li>)
<li><a role= "button" class= "dropdown-item" href= "#" data-bs-toggle="modal" data-bs-target= "#comparison-info-modal"><mdi name= "info"/> Info</a></li>
,(progn
#+screenshotbot-oss
(progn
<li>
<a class= "dropdown-item" href=all-comparisons >All Pixel Comparisons (OSS only) </a>
</li>))
</ul>
</li>
,(when (and (can-edit run (current-user)) acceptable)
<li class= "nav-item" >
<render-acceptable acceptable=acceptable />
</li>)
</markup:merge-tag>
</ul>
</div>
</div>
,@children
<div class= "report-result mt-3"
data-update= (nibble (:name :u-r-res) (report-result run
changes-groups
added-groups
deleted-groups))
data-args= "{}" >
,(report-result run
changes-groups
added-groups
deleted-groups
:type default-type)
</div>
,(info-modal run to)
</markup:merge-tag>)))
(deftag link-to-run (&key run)
<a href= (hex:make-url "/runs/:id" :id (oid run))>run from ,(timeago :timestamp (created-at run))</a>)
(defun info-modal (run to)
<div class="modal" tabindex="-1" id= "comparison-info-modal" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">,(channel-name (recorder-run-channel run)) </h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Comparing <link-to-run run=run /> to <link-to-run run=to />.</p>
,(when-let* ((repo (channel-repo (recorder-run-channel run)))
(this-hash (recorder-run-commit run))
(prev-hash (recorder-run-commit to)))
(let ((review-link (review-link :run run)))
<p class= "mt-2" >
This commit: <commit repo= repo hash=this-hash />
,(when review-link
<span> on ,(progn review-link)</span>)
<br />
Previous commit: <commit repo= repo hash=prev-hash />
</p>))
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>)
(defun group-matches-p (group search)
(or
(str:emptyp search)
(str:contains? search (group-title group) :ignore-case t)))
(defun report-result (run changes-groups added-groups deleted-groups
&key
(type (hunchentoot:parameter "type")))
(let ((search (hunchentoot:parameter "search")))
(cond
((string-equal "added" type)
(render-single-group-list added-groups :search search))
((string-equal "deleted" type)
(render-single-group-list deleted-groups :search search))
(t
<div class= "">
,(paginated
(lambda (group)
(render-change-group group run (hunchentoot:script-name*) :search search))
:num 10
:filter (lambda (group)
(group-matches-p group search))
:items changes-groups
:empty-view (no-screenshots))
</div>))))
(defun render-single-group-list (groups &key search)
(paginated
(lambda (group)
<div class= "col-md-6">
<div class= "card mb-3">
,(maybe-tabulate
(loop for group-item in (group-items group)
for screenshot = (actual-item group-item)
collect
(make-instance
'tab
:title (get-tab-title screenshot)
:content
<screenshot-box screenshot=screenshot title= (group-title group) /> ))
:header <h4 class= "screenshot-title" >,(highlight-search-term search (group-title group)) </h4>)
</div>
</div>)
:num 12
:filter (lambda (group)
(group-matches-p group search))
:items groups
:empty-view (no-screenshots)))
(Deftag screenshot-box (&key screenshot title)
(let ((dimensions (ignore-errors (image-dimensions (screenshot-image screenshot)))))
<div class= "mt-1" >
<picture-with-img
class= "mt-2"
image= (screenshot-image screenshot)
dimensions=dimensions
alt=title />
</div>))
(defun no-screenshots ()
<div class= "text-muted text-center">
No changes match filters
</div>)
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/284acd5998e6c81107bc5315b22bdcaf55f8db5a/src/screenshotbot/dashboard/compare.lisp | lisp | Copyright 2018-Present Modern Interpreters Inc.
datastore to see if there are any previous images
Avoid computation for large reverts
designed to handle that yet.
for debugging: e.g. if we need to delete the comparison
warmup in the order that the report would be typically
viewed.
don't show the tabulation | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(uiop:define-package :screenshotbot/dashboard/compare
For bknr
(:use #:cl
#:alexandria
#:nibble
#:screenshotbot/template
#:screenshotbot/diff-report
#:screenshotbot/model/screenshot
#:screenshotbot/model/image-comparison
#:screenshotbot/model/image
#:screenshotbot/model/view
#:screenshotbot/model/report
#:screenshotbot/model/channel
#:screenshotbot/ignore-and-log-errors
#:screenshotbot/model/recorder-run)
(:import-from #:util
#:find-by-oid
#:oid)
(:import-from #:markup #:deftag)
(:import-from #:screenshotbot/server
#:make-thread
#:defhandler)
(:import-from #:screenshotbot/report-api
#:render-diff-report)
(:import-from #:screenshotbot/dashboard/run-page
#:run-row-filter
#:page-nav-dropdown
#:row-filter
#:mask-editor
#:commit)
(:import-from #:screenshotbot/model/image
#:dimension-width
#:dimension-height
#:image-dimensions
#:map-unequal-pixels
#:image-blob
#:rect-as-list)
(:import-from #:screenshotbot/magick
#:run-magick)
(:import-from #:core/ui/paginated
#:paginated)
(:import-from #:bknr.datastore
#:store-object)
(:import-from #:bknr.datastore
#:persistent-class)
(:import-from #:bknr.indices
#:hash-index)
(:import-from #:bknr.datastore
#:make-blob-from-file)
(:import-from #:screenshotbot/user-api
#:can-view!
#:current-user
#:created-at
#:current-company)
(:import-from #:screenshotbot/dashboard/image
#:handle-resized-image)
(:import-from #:bknr.datastore
#:store-object-id)
(:import-from #:bknr.datastore
#:store-object-id)
(:import-from #:auto-restart
#:with-auto-restart)
(:import-from #:bknr.datastore
#:delete-object)
(:import-from #:nibble
#:nibble-url)
(:import-from #:screenshotbot/magick/magick-lw
#:get-non-alpha-pixels
#:with-wand)
(:import-from #:screenshotbot/diff-report
#:actual-item
#:changes-groups
#:get-tab-title)
(:import-from #:bknr.datastore
#:cascading-delete-object)
(:import-from #:screenshotbot/taskie
#:timeago)
(:import-from #:util/misc
#:?.)
(:import-from #:screenshotbot/model/transient-object
#:with-transient-copy)
(:import-from #:screenshotbot/model/image-comparison
#:find-image-comparison-on-images)
(:import-from #:bknr.datastore
#:store-object)
(:import-from #:screenshotbot/model/view
#:can-edit
#:can-edit!)
(:import-from #:screenshotbot/dashboard/review-link
#:review-link)
(:import-from #:screenshotbot/cdn
#:make-image-cdn-url)
(:import-from #:screenshotbot/model/screenshot
#:abstract-screenshot)
(:export
#:diff-report
#:render-acceptable
#:make-diff-report
#:diff-report-empty-p
#:render-diff-report
#:diff-report-changes
#:warmup-comparison-images))
(in-package :screenshotbot/dashboard/compare)
fake symbols for bknr migration
(progn
'(result
before
after
identical-p
result))
(markup:enable-reader)
(deftag render-acceptable (&key acceptable)
(let ((accept (nibble (redirect :name :accept)
(setf (acceptable-state acceptable :user (current-user)) :accepted)
(hex:safe-redirect redirect)))
(reject (nibble (redirect :name :reject)
(setf (acceptable-state acceptable :user (current-user)) :rejected)
(hex:safe-redirect redirect)))
(btn-class
(ecase (acceptable-state acceptable)
(:accepted
"dropdown-report-accepted")
(:rejected
"dropdown-report-rejected")
((nil)
"")))
(btn-text
(ecase (acceptable-state acceptable)
(:accepted
"Accepted")
(:rejected
"Rejected")
((nil)
"Review"))))
<markup:merge-tag>
<button class= (format nil"btn btn-secondary dropdown-toggle ~a" btn-class) type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
,(progn btn-text)
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton" style= "z-index: 99999999; position: static" >
<form action=accept method= "POST" >
<button action= "submit" class= "btn btn-link acceptable accept-link dropdown-item" >
<input type= "hidden" name= "redirect"
value= (hunchentoot:script-name*) />
<mdi name= "check" />
Accept
</button>
</form>
<form action=reject method= "POST">
<input type= "hidden" name= "redirect"
value= (hunchentoot:script-name* ) />
<button action= "submit" class= "btn btn-link acceptable reject-link dropdown-item" >
<mdi name= "close" />
Reject</button>
</form>
</div>
</markup:merge-tag>))
(defun diff-report-empty-p (diff-report)
(not
(or (diff-report-added diff-report)
(diff-report-deleted diff-report)
(diff-report-changes diff-report))))
(defhandler (compare-page :uri "/runs/:id/compare/:to") (id to)
(when (string= "254" id)
(hex:safe-redirect "/report/5fd16bcf4f4b3822fd000146"))
(flet ((find-run (id)
(let ((ret (find-by-oid id 'recorder-run)))
(assert ret)
ret)))
(let* ((run (find-run id))
(to (find-run to)))
(can-view! run to)
<app-template body-class= "dashboard bg-white" >
,(async-diff-report :run run :to to)
</app-template>)))
(deftag picture-with-img (&key image dimensions alt class)
<picture>
<source srcset= (image-public-url image :size :full-page :type :webp) type= "image/webp" />
<img class= (format nil "screenshot-image change-image ~a" class) src= (image-public-url image :size :full-page :type :png)
loading= "lazy"
alt=alt
width= (?. dimension-width dimensions)
height= (?. dimension-height dimensions)
/>
</picture>)
(deftag change-image-row (&key before-image
after-image
before-dims
after-dims)
<div class="change-image-row">
<picture-with-img
image=before-image
dimensions=before-dims
alt= "before image"
class= "change-image-left" />
<mdi name= "arrow_forward" />
<picture-with-img
image=after-image
dimensions=after-dims
alt="after image"
class= "change-image-right" />
</div>)
(deftag change-image-row-triple (&key before-image
after-image
comp-image)
<div class="change-image-row change-image-row-triple">
<img class= "screenshot-image change-image change-image-left" src= before-image />
<img class= "screenshot-image change-image change-image-right" src= after-image />
<:img data-src= comp-image
class= "bg-primary image-comparison-modal-image screenshot-image change-image" alt= "Image Difference" />
</div>)
(defclass image-comparison-job ()
((donep :initform nil
:accessor donep)
(lock :initform (bt:make-lock "image-comparison")
:reader lock)
(before-image :initarg :before-image
:reader before-image)
(after-image :initarg :after-image
:reader after-image)
(image-comparison
:initarg :image-comparison
:accessor image-comparison
:documentation "The actual image-comparison object. You can get
the resulting image and other context from this object")))
(defmethod find-image-comparison ((before-screenshot abstract-screenshot)
(after-screenshot abstract-screenshot))
second level of caching , we 're going to look through the
(let ((before (screenshot-image before-screenshot))
(after (screenshot-image after-screenshot)))
(when (> (store-object-id before)
(store-object-id after))
(rotatef before after))
(find-image-comparison-on-images
before
after
(screenshot-masks after-screenshot))))
(defmethod prepare-image-comparison-file ((self image-comparison-job))
(bt:with-lock-held ((lock self))
(cond
((donep self)
(image-comparison self))
(t
(setf (image-comparison self)
(find-image-comparison (before-image self)
(after-image self)))))))
(defmethod prepare-image-comparison ((self image-comparison-job)
&key
I ca n't use : full - page here because the JS is n't
(size nil)
(warmup nil))
(let ((image-comparison (prepare-image-comparison-file self)))
(cond
(warmup
(when size
(handle-resized-image (image-comparison-result image-comparison) size :warmup t)))
(t
(setf (hunchentoot:content-type*) "application/json")
(json:encode-json-to-string
`((:identical . ,(identical-p image-comparison))
(:store-object-id
.
,(when (typep image-comparison 'store-object)
(bknr.datastore:store-object-id image-comparison)))
(:zoom-to . ,(nibble-url (nibble (:name :zoom) (random-zoom-to-on-result
image-comparison))))
(:src . ,(make-image-cdn-url (image-public-url (image-comparison-result image-comparison) :size size)))
(:background . ,(make-image-cdn-url (image-public-url (screenshot-image (before-image self)) :size size)))
(:masks .
,(or
(loop for mask in (image-comparison-masks image-comparison)
collect
`((:left . ,(mask-rect-left mask))
(:top . ,(mask-rect-top mask))
(:width . ,(mask-rect-width mask))
(:height . ,(mask-rect-height mask))))
#()))))))))
(defun random-zoom-to-on-result (image-comparison)
(setf (hunchentoot:content-type*) "application/json")
(with-local-image (file (image-comparison-result image-comparison))
(with-wand (wand :file file)
(log:debug"random-zoom-to-on-result on ~a" file)
(let ((pxs (get-non-alpha-pixels wand
:masks (image-comparison-masks image-comparison))))
(let ((i (random (car (array-dimensions pxs)))))
(let ((dims (image-dimensions (image-comparison-result image-comparison))))
(json:encode-json-to-string
`((:y . ,(aref pxs i 1))
(:x . ,(aref pxs i 0))
(:width . ,(dimension-width dims))
(:height . ,(dimension-height dims))))))))))
(defun async-diff-report (&rest args &key &allow-other-keys)
(let* ((data nil)
(session auth:*current-session*)
(request hunchentoot:*request*)
(acceptor hunchentoot:*acceptor*)
(data-check-nibble (nibble (:name :data-check)
(setf (hunchentoot:content-type*) "application/json")
(json:encode-json-to-string
(cond
((eql :error data)
`((:state . "error")))
(data
`((:data . ,(markup:write-html data))
(:state . "done")))
(t
`((:state . "processing"))))))))
(make-thread (lambda ()
(ignore-and-log-errors ()
(handler-bind ((error (lambda (e)
(declare (ignore e))
(setf data :error))))
(let ((auth:*current-session* session)
(hunchentoot:*request* request)
(hunchentoot:*acceptor* acceptor))
(setf data (apply 'render-diff-report args)))))))
<div class= "async-fetch spinner-border" role= "status" data-check-nibble=data-check-nibble />))
(defun warmup-comparison-images (run previous-run)
(make-thread
(lambda ()
(restart-case
(let ((report (make-diff-report run previous-run)))
(dolist (group (changes-groups report))
(let ((changes (mapcar #'actual-item (group-items group))))
(loop for change in changes
for i from 1
for before = (before change)
for after = (after change)
for image-comparison-job = (make-instance 'image-comparison-job
:before-image before
:after-image after)
do
(progn
(log:info "Warming up compare image ~d of ~d (~a)" i (length changes)
(screenshot-name after))
(restart-case
(prepare-image-comparison image-comparison-job :size nil
:warmup t)
(ignore-this-image ()
nil)))))))
(retry-warmup-thread ()
(warmup-comparison-images run previous-run))))
:name "warmup-comparison-images"))
(defun all-comparisons-page (report)
<app-template>
<a href= "javascript:window.history.back()">Back to Report</a>
,(paginated
(lambda (change)
(let* ((before (before change))
(after (after change))
(image-comparison-job (make-instance 'image-comparison-job
:before-image before
:after-image after))
(comparison-image (util:copying (image-comparison-job)
(nibble (:name :comparison)
(prepare-image-comparison image-comparison-job :size :full-page)))))
<div class= "image-comparison-wrapper" >
<h3>,(screenshot-name before)</h3>
<change-image-row-triple before-image=(image-public-url (screenshot-image before) :size :full-page)
after-image=(image-public-url (screenshot-image after) :size :full-page)
comp-image=comparison-image
/>
</div>))
:num 5
:items (diff-report-changes report))
</app-template>)
(deftag progress-img (&key (alt "Image Difference") src class)
"An <img> with a progress indicator for the image loading."
<div class= (format nil "progress-image-wrapper ~a" class) >
<div class= "alert alert-danger images-identical" style= "display:none" >
<p>
<strong>The two images are identical.</strong> This is likely because the images still have their EXIF data, e.g. timestamps.
</p>
<p class= "mb-0" >
You can pre-process images to remove timestamps. One way to do this is to use: `<:tt>exiftool -all= *.png</:tt>`.
</p>
</div>
<div class= "loading">
<div class="spinner-border" role="status">
<!-- <span class="sr-only">Loading...</span> -->
</div>
Loading (this could take upto 30s in some cases)
</div>
<div>
<div class= "alert alert-info">
<strong>New interactive comparisons!</strong> Use your mouse to pan through the image. Use the <strong>mouse wheel</strong> to zoom into a location.
</div>
<:canvas data-src=src
class= "image-comparison-modal-image" />
</div>
</div>)
(deftag zoom-to-change-button ()
<button type="button" class="btn btn-secondary zoom-to-change">
<div class="spinner-border" role="status" style="display:none; height: 1em; width: 1em" />
Zoom to change
</button>)
(defclass tab ()
((title :initarg :title
:reader tab-title)
(content :initarg :content
:reader tab-content)))
(defun maybe-tabulate (tabs &key header &aux (id (format nil "a~a" (random 10000000))))
(cond
((and (eql 1 (length tabs))
(str:emptyp (tab-title (car tabs))))
<markup:merge-tag>
<div class= "card-header">
,(progn header)
</div>
<div class= "card-body">
,(tab-content (car tabs))
</div>
</markup:merge-tag>)
(t
<markup:merge-tag>
<div class= "card-header">
,(progn header)
<ul class= "nav nav-tabs card-header-tabs" role= "tablist" >
,@ (loop for tab in tabs
for ctr from 0
collect
<li class= "nav-item" role= "presentation" >
<button class= (format nil "nav-link ~a" (if (= ctr 0) "active" ""))
data-bs-toggle= "tab"
data-bs-target= (format nil "#~a-~a" id ctr)
data-title= (tab-title tab)
role= "tab"
aria-controls= (format nil "~a-~a" id ctr)
aria-selector=(if (= ctr 0) "true" "false") >
,(tab-title tab)
</button>
</li>)
</ul>
</div>
<div class= "card-body">
<div class= "tab-content">
,@(loop for tab in tabs
for ctr from 0
collect
<div class= (format nil "tab-pane ~a" (if (= ctr 0) "show active" ""))
id= (format nil "~a-~a" id ctr)
role= "tab-panel"
aria-labelled-by= (tab-title tab) >
,(tab-content tab)
</div>)
</div>
</div>
</markup:merge-tag>)))
(defun make-overlay-image (before after)
(let ((image-comparison-job (make-instance 'image-comparison-job
:before-image before
:after-image after)))
(image-comparison-result
(prepare-image-comparison-file image-comparison-job))))
(defun render-change-group (group run script-name &key search)
<div class= "col-12">
<div class= "card mb-3">
,(maybe-tabulate
(loop for group-item in (group-items group)
for change = (actual-item group-item)
for next-id = (random 1000000000000000)
for s = (before change)
for x = (after change)
collect
(make-instance
'tab
:title (group-item-subtitle group-item)
:content
(let* ((s s)
(x x)
(toggle-id (format nil "toggle-id-~a" next-id)))
<div class= "" >
<div class= "screenshot-header" >
<ul class= "screenshot-options-menu" >
<li>
<a href= "#" data-bs-toggle= "modal" data-bs-target= (format nil "#~a" toggle-id) >Compare</a>
</li>
<li>
<a href= (hex:make-url "/channel/:channel/history" :channel (store-object-id (recorder-run-channel run))
:screenshot-name (screenshot-name x))>
Full History
</a>
</li>
<li>
<a href= (nibble (:name :mask-editor) (mask-editor (recorder-run-channel run) s
:redirect script-name
:overlay (make-overlay-image x s)))
>
Edit Masks
</a>
</li>
</ul>
</div>
<change-image-row before-image=(screenshot-image x)
after-image=(screenshot-image s)
before-dims= (ignore-errors (image-dimensions (screenshot-image x)))
after-dims= (ignore-errors (image-dimensions (screenshot-image s)))
/>
<comparison-modal before=x after=s toggle-id=toggle-id />
</div>)))
:header <h4 class= "screenshot-title">,(highlight-search-term search (group-title group))</h4>)
</div>
</div>)
(defun highlight-search-term (search title)
(cond
((str:emptyp search)
title)
(t
(let* ((start (search (str:downcase search) (str:downcase title)))
(end (+ start (length search))))
(markup:make-merge-tag
(list
<span class= "text-muted">,(subseq title 0 start)</span>
<span class= "" >,(subseq title start end)</span>
<span class= "text-muted">,(subseq title end)</span>))))))
(deftag comparison-modal (&key toggle-id before after)
(let* ((modal-label (format nil "~a-modal-label" toggle-id))
(image-comparison-job
(make-instance 'image-comparison-job
:before-image before
:after-image after))
(compare-nibble (nibble (:name :compare-link)
(prepare-image-comparison
image-comparison-job))))
<div class= "modal fade image-comparison-modal" id= toggle-id tabindex= "-1" role= "dialog"
aria-labelledby=modal-label
aria-hidden= "true" >
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id=modal-label >Image Comparison</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" />
</div>
<div class="modal-body">
<progress-img
src=compare-nibble
alt= "Image difference" />
</div>
<div class="modal-footer">
<zoom-to-change-button />
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>))
(deftag compare-tab-a (body &key type default-type)
<a class= (format nil "nav-link ~a" (when (string= type default-type) "active"))
href= "#" data-type= type >
,@body
</a>)
(deftag render-diff-report (children &key run to
more
acceptable
(re-run nil))
(declare (ignore re-run))
(let* ((report (make-diff-report run to))
(all-comparisons (nibble (:name :all-comparison)
(all-comparisons-page report))))
(declare (ignorable all-comparisons))
(let* ((changes-groups (changes-groups report))
(added-groups (added-groups report))
(deleted-groups (deleted-groups report))
(default-type
(or
(hunchentoot:parameter "type")
(cond
(changes-groups "changes")
(added-groups "added")
(deleted-groups "deleted")
(t "changes")))))
<markup:merge-tag>
<div class= "mt-3 d-flex flex-wrap justify-content-between compare-header" >
<div class= "report-search-wrapper" >
<div class= "input-group">
<span class= "input-group-text report-search" >
<mdi name= "search" />
</span>
<input class= "form-control search d-inline-block" type= "text" autocomplete= "off"
placeholder= "Search..."
data-target= ".report-result" />
</div>
</div>
<div class= "options" >
<ul class= "nav nav-pills report-selector" data-target= ".report-result" >
<li class= "nav-item">
<compare-tab-a type= "changes" default-type=default-type >
,(length changes-groups) changes
</compare-tab-a>
</li>
<li class= "nav-item">
<compare-tab-a type= "added" default-type=default-type >
,(length added-groups) added
</compare-tab-a>
</li>
<li class= "nav-item">
<compare-tab-a type= "deleted" default-type=default-type >
,(length deleted-groups) deleted
</compare-tab-a>
</li>
<markup:merge-tag>
<li class= "nav-item" >
<button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
More
</button>
<ul class="dropdown-menu dropdown-menu-end">
,@ (loop for (name . url) in more
collect
<li><a class="dropdown-item" href=url >,(progn name)</a></li>)
<li><a role= "button" class= "dropdown-item" href= "#" data-bs-toggle="modal" data-bs-target= "#comparison-info-modal"><mdi name= "info"/> Info</a></li>
,(progn
#+screenshotbot-oss
(progn
<li>
<a class= "dropdown-item" href=all-comparisons >All Pixel Comparisons (OSS only) </a>
</li>))
</ul>
</li>
,(when (and (can-edit run (current-user)) acceptable)
<li class= "nav-item" >
<render-acceptable acceptable=acceptable />
</li>)
</markup:merge-tag>
</ul>
</div>
</div>
,@children
<div class= "report-result mt-3"
data-update= (nibble (:name :u-r-res) (report-result run
changes-groups
added-groups
deleted-groups))
data-args= "{}" >
,(report-result run
changes-groups
added-groups
deleted-groups
:type default-type)
</div>
,(info-modal run to)
</markup:merge-tag>)))
(deftag link-to-run (&key run)
<a href= (hex:make-url "/runs/:id" :id (oid run))>run from ,(timeago :timestamp (created-at run))</a>)
(defun info-modal (run to)
<div class="modal" tabindex="-1" id= "comparison-info-modal" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">,(channel-name (recorder-run-channel run)) </h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Comparing <link-to-run run=run /> to <link-to-run run=to />.</p>
,(when-let* ((repo (channel-repo (recorder-run-channel run)))
(this-hash (recorder-run-commit run))
(prev-hash (recorder-run-commit to)))
(let ((review-link (review-link :run run)))
<p class= "mt-2" >
This commit: <commit repo= repo hash=this-hash />
,(when review-link
<span> on ,(progn review-link)</span>)
<br />
Previous commit: <commit repo= repo hash=prev-hash />
</p>))
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>)
(defun group-matches-p (group search)
(or
(str:emptyp search)
(str:contains? search (group-title group) :ignore-case t)))
(defun report-result (run changes-groups added-groups deleted-groups
&key
(type (hunchentoot:parameter "type")))
(let ((search (hunchentoot:parameter "search")))
(cond
((string-equal "added" type)
(render-single-group-list added-groups :search search))
((string-equal "deleted" type)
(render-single-group-list deleted-groups :search search))
(t
<div class= "">
,(paginated
(lambda (group)
(render-change-group group run (hunchentoot:script-name*) :search search))
:num 10
:filter (lambda (group)
(group-matches-p group search))
:items changes-groups
:empty-view (no-screenshots))
</div>))))
(defun render-single-group-list (groups &key search)
(paginated
(lambda (group)
<div class= "col-md-6">
<div class= "card mb-3">
,(maybe-tabulate
(loop for group-item in (group-items group)
for screenshot = (actual-item group-item)
collect
(make-instance
'tab
:title (get-tab-title screenshot)
:content
<screenshot-box screenshot=screenshot title= (group-title group) /> ))
:header <h4 class= "screenshot-title" >,(highlight-search-term search (group-title group)) </h4>)
</div>
</div>)
:num 12
:filter (lambda (group)
(group-matches-p group search))
:items groups
:empty-view (no-screenshots)))
(Deftag screenshot-box (&key screenshot title)
(let ((dimensions (ignore-errors (image-dimensions (screenshot-image screenshot)))))
<div class= "mt-1" >
<picture-with-img
class= "mt-2"
image= (screenshot-image screenshot)
dimensions=dimensions
alt=title />
</div>))
(defun no-screenshots ()
<div class= "text-muted text-center">
No changes match filters
</div>)
|
120413ca9660a6c5785b8a28ecb4ee7035ca2309bcc5ff099d68fa643a418242 | kudu-dynamics/blaze | TestBitOp.hs | module Blaze.Types.Pil.Op.TestBitOp where
-- This module is generated. Please use app/gen_pil_ops/Main.hs to modify.
import Blaze.Prelude
data TestBitOp expr = TestBitOp
{ left :: expr
, right :: expr
} deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, FromJSON, ToJSON)
instance Hashable a => Hashable (TestBitOp a)
| null | https://raw.githubusercontent.com/kudu-dynamics/blaze/a385bb3b37a0a0e061217ebdd70dd0eecbb20332/src/Blaze/Types/Pil/Op/TestBitOp.hs | haskell | This module is generated. Please use app/gen_pil_ops/Main.hs to modify. | module Blaze.Types.Pil.Op.TestBitOp where
import Blaze.Prelude
data TestBitOp expr = TestBitOp
{ left :: expr
, right :: expr
} deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, FromJSON, ToJSON)
instance Hashable a => Hashable (TestBitOp a)
|
4993c70664f95e621f935d6bb3d43f5aee57f0182e2a7eb2cd6ae59bbe3ab669 | synduce/Synduce | parallel_max.ml | * @synduce -s 2 --no - lifting -NB -n 30
type 'a list =
| Elt of 'a
| Cons of 'a * 'a list
type 'a clist =
| Single of 'a
| Concat of 'a clist * 'a clist
let rec clist_to_list = function
| Single a -> Elt a
| Concat (x, y) -> dec y x
and dec l1 = function
| Single a -> Cons (a, clist_to_list l1)
| Concat (x, y) -> dec (Concat (y, l1)) x
;;
(** Predicate asserting that a concat-list is partitioned. *)
let rec is_partitioned = function
| Single x -> true
| Concat (x, y) -> lmax x < lmin y && is_partitioned x && is_partitioned y
and lmax = function
| Single x -> x
| Concat (x, y) -> max (lmax x) (lmax y)
and lmin = function
| Single x -> x
| Concat (x, y) -> min (lmin x) (lmin y)
;;
let rec spec = function
| Elt a -> a
| Cons (hd, tl) -> max hd (spec tl)
;;
let rec target = function
| Single x -> [%synt s0] x
| Concat (l, r) -> [%synt s1] (target r)
[@@requires is_partitioned]
;;
assert (target = clist_to_list @@ spec)
| null | https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/incomplete/sortedlist/parallel_max.ml | ocaml | * Predicate asserting that a concat-list is partitioned. | * @synduce -s 2 --no - lifting -NB -n 30
type 'a list =
| Elt of 'a
| Cons of 'a * 'a list
type 'a clist =
| Single of 'a
| Concat of 'a clist * 'a clist
let rec clist_to_list = function
| Single a -> Elt a
| Concat (x, y) -> dec y x
and dec l1 = function
| Single a -> Cons (a, clist_to_list l1)
| Concat (x, y) -> dec (Concat (y, l1)) x
;;
let rec is_partitioned = function
| Single x -> true
| Concat (x, y) -> lmax x < lmin y && is_partitioned x && is_partitioned y
and lmax = function
| Single x -> x
| Concat (x, y) -> max (lmax x) (lmax y)
and lmin = function
| Single x -> x
| Concat (x, y) -> min (lmin x) (lmin y)
;;
let rec spec = function
| Elt a -> a
| Cons (hd, tl) -> max hd (spec tl)
;;
let rec target = function
| Single x -> [%synt s0] x
| Concat (l, r) -> [%synt s1] (target r)
[@@requires is_partitioned]
;;
assert (target = clist_to_list @@ spec)
|
95b0bf6b42aab21897a7b44e6e3d8edfdf088011a6879236818c58bfeb59f106 | mirage/mirage | help.ml |
* Copyright ( c ) 2015
* Copyright ( c ) 2021 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2015 Jeremy Yallop
* Copyright (c) 2021 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Astring
(* cut a man page into sections *)
let by_sections s =
let lines = String.cuts ~sep:"\n" s in
let return l =
match List.rev l with [] -> assert false | h :: t -> (h, t)
in
let rec aux current sections = function
| [] -> List.rev (return current :: sections)
| h :: t ->
if
String.length h > 1
&& String.for_all (fun x -> Char.Ascii.(is_upper x || is_white x)) h
then aux [ h ] (return current :: sections) t
else aux (h :: current) sections t
in
aux [ "INIT" ] [] lines
let sections = [ "CONFIGURE OPTIONS"; "APPLICATION OPTIONS"; "COMMON OPTIONS" ]
let read file =
let ic = open_in_bin file in
let str = really_input_string ic (in_channel_length ic) in
close_in ic;
by_sections str
let err_usage () =
Fmt.pr "[usage]: ./help.exe [diff|show] PARAMS\n";
exit 1
let () =
if Array.length Sys.argv <> 4 then err_usage ()
else
match Sys.argv.(1) with
| "diff" ->
let s1 = read Sys.argv.(2) in
let s2 = read Sys.argv.(3) in
List.iter
(fun name ->
match (List.assoc_opt name s1, List.assoc_opt name s2) with
| Some s1, Some s2 ->
if List.length s1 <> List.length s2 then
Fmt.failwith "Number of lines in %S differs" name
else
List.iter2
(fun s1 s2 ->
if s1 <> s2 then
Fmt.failwith "Lines in section %S differ:\n %S\n %S\n"
name s1 s2)
s1 s2
| _ -> Fmt.failwith "Section %S differs" name)
sections
| "show" -> (
let s1 = read Sys.argv.(2) in
let name = Sys.argv.(3) in
match List.assoc_opt name s1 with
| None -> ()
| Some s -> List.iter print_endline s)
| _ -> err_usage ()
| null | https://raw.githubusercontent.com/mirage/mirage/bbab59bb522e4a5acd4342ea9e835024838a7644/test/functoria/e2e/help.ml | ocaml | cut a man page into sections |
* Copyright ( c ) 2015
* Copyright ( c ) 2021 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2015 Jeremy Yallop
* Copyright (c) 2021 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Astring
let by_sections s =
let lines = String.cuts ~sep:"\n" s in
let return l =
match List.rev l with [] -> assert false | h :: t -> (h, t)
in
let rec aux current sections = function
| [] -> List.rev (return current :: sections)
| h :: t ->
if
String.length h > 1
&& String.for_all (fun x -> Char.Ascii.(is_upper x || is_white x)) h
then aux [ h ] (return current :: sections) t
else aux (h :: current) sections t
in
aux [ "INIT" ] [] lines
let sections = [ "CONFIGURE OPTIONS"; "APPLICATION OPTIONS"; "COMMON OPTIONS" ]
let read file =
let ic = open_in_bin file in
let str = really_input_string ic (in_channel_length ic) in
close_in ic;
by_sections str
let err_usage () =
Fmt.pr "[usage]: ./help.exe [diff|show] PARAMS\n";
exit 1
let () =
if Array.length Sys.argv <> 4 then err_usage ()
else
match Sys.argv.(1) with
| "diff" ->
let s1 = read Sys.argv.(2) in
let s2 = read Sys.argv.(3) in
List.iter
(fun name ->
match (List.assoc_opt name s1, List.assoc_opt name s2) with
| Some s1, Some s2 ->
if List.length s1 <> List.length s2 then
Fmt.failwith "Number of lines in %S differs" name
else
List.iter2
(fun s1 s2 ->
if s1 <> s2 then
Fmt.failwith "Lines in section %S differ:\n %S\n %S\n"
name s1 s2)
s1 s2
| _ -> Fmt.failwith "Section %S differs" name)
sections
| "show" -> (
let s1 = read Sys.argv.(2) in
let name = Sys.argv.(3) in
match List.assoc_opt name s1 with
| None -> ()
| Some s -> List.iter print_endline s)
| _ -> err_usage ()
|
942f1de8691016c47409a9d81c1d29664cf0e447d1e0d8e075b4eaf339375030 | commercialhaskell/stack | Docker.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
| Run commands in containers
module Stack.Docker
( dockerCmdName
, dockerHelpOptName
, dockerPullCmdName
, entrypoint
, preventInContainer
, pull
, reset
, reExecArgName
, DockerException (..)
, getProjectRoot
, runContainerAndExit
) where
import qualified Crypto.Hash as Hash ( Digest, MD5, hash )
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Char ( isAscii, isDigit )
import Data.Conduit.List ( sinkNull )
import Data.Conduit.Process.Typed hiding ( proc )
import Data.List ( dropWhileEnd, isInfixOf, isPrefixOf )
import Data.List.Extra ( trim )
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time ( UTCTime )
import qualified Data.Version ( parseVersion )
import Distribution.Version ( mkVersion, mkVersion' )
import Pantry.Internal.AesonExtended
( FromJSON (..), (.:), (.:?), (.!=), eitherDecode )
import Path
( (</>), dirname, filename, parent, parseAbsDir
, splitExtension
)
import Path.Extra ( toFilePathNoTrailingSep )
import Path.IO hiding ( canonicalizePath )
import qualified RIO.Directory ( makeAbsolute )
import RIO.Process
( HasProcessContext, augmentPath, doesExecutableExist, proc
, processContextL, withWorkingDir
)
import Stack.Config ( getInContainer )
import Stack.Constants
( buildPlanDir, inContainerEnvVar, platformVariantEnvVar
, relDirBin, relDirDotLocal, relDirDotSsh
, relDirDotStackProgName, relDirUnderHome, stackRootEnvVar
)
import Stack.Constants.Config ( projectDockerSandboxDir )
import Stack.Docker.Handlers ( handleSetGroups, handleSignals )
import Stack.Prelude
import Stack.Setup ( ensureDockerStackExe )
import Stack.Storage.User
( loadDockerImageExeCache, saveDockerImageExeCache )
import Stack.Types.Config
( Config (..), DockerEntrypoint (..), DockerUser (..)
, HasConfig (..), configProjectRoot, stackRootL, terminalL
)
import Stack.Types.Docker
( DockerException (..), DockerOpts (..), DockerStackExe (..)
, Mount (..), dockerCmdName, dockerContainerPlatform
, dockerEntrypointArgName, dockerHelpOptName
, dockerPullCmdName, reExecArgName
)
import Stack.Types.Version ( showStackVersion, withinRange )
import System.Environment
( getArgs, getEnv, getEnvironment, getExecutablePath
, getProgName
)
import qualified System.FilePath as FP
import System.IO.Error ( isDoesNotExistError )
import System.IO.Unsafe ( unsafePerformIO )
import qualified System.PosixCompat.User as User
import qualified System.PosixCompat.Files as Files
import System.Terminal ( hIsTerminalDeviceOrMinTTY )
import Text.ParserCombinators.ReadP ( readP_to_S )
| Function to get command and arguments to run in Docker container
getCmdArgs ::
HasConfig env
=> DockerOpts
-> Inspect
-> Bool
-> RIO env (FilePath,[String],[(String,String)],[Mount])
getCmdArgs docker imageInfo isRemoteDocker = do
config <- view configL
deUser <-
if fromMaybe (not isRemoteDocker) (dockerSetUser docker)
then liftIO $ do
duUid <- User.getEffectiveUserID
duGid <- User.getEffectiveGroupID
duGroups <- nubOrd <$> User.getGroups
duUmask <- Files.setFileCreationMask 0o022
-- Only way to get old umask seems to be to change it, so set it back afterward
_ <- Files.setFileCreationMask duUmask
pure (Just DockerUser{..})
else pure Nothing
args <-
fmap
(["--" ++ reExecArgName ++ "=" ++ showStackVersion
,"--" ++ dockerEntrypointArgName
,show DockerEntrypoint{..}] ++)
(liftIO getArgs)
case dockerStackExe (configDocker config) of
Just DockerStackExeHost
| configPlatform config == dockerContainerPlatform -> do
exePath <- resolveFile' =<< liftIO getExecutablePath
cmdArgs args exePath
| otherwise -> throwIO UnsupportedStackExeHostPlatformException
Just DockerStackExeImage -> do
progName <- liftIO getProgName
pure (FP.takeBaseName progName, args, [], [])
Just (DockerStackExePath path) -> cmdArgs args path
Just DockerStackExeDownload -> exeDownload args
Nothing
| configPlatform config == dockerContainerPlatform -> do
(exePath,exeTimestamp,misCompatible) <-
do exePath <- resolveFile' =<< liftIO getExecutablePath
exeTimestamp <- getModificationTime exePath
isKnown <-
loadDockerImageExeCache
(iiId imageInfo)
exePath
exeTimestamp
pure (exePath, exeTimestamp, isKnown)
case misCompatible of
Just True -> cmdArgs args exePath
Just False -> exeDownload args
Nothing -> do
e <-
try $
sinkProcessStderrStdout
"docker"
[ "run"
, "-v"
, toFilePath exePath ++ ":" ++ "/tmp/stack"
, T.unpack (iiId imageInfo)
, "/tmp/stack"
, "--version"]
sinkNull
sinkNull
let compatible =
case e of
Left ExitCodeException{} -> False
Right _ -> True
saveDockerImageExeCache
(iiId imageInfo)
exePath
exeTimestamp
compatible
if compatible
then cmdArgs args exePath
else exeDownload args
Nothing -> exeDownload args
where
exeDownload args = do
exePath <- ensureDockerStackExe dockerContainerPlatform
cmdArgs args exePath
cmdArgs args exePath = do
MSS 2020 - 04 - 21 previously used replaceExtension , but semantics changed in path 0.7
-- In any event, I'm not even sure _why_ we need to drop a file extension here
Originally introduced here :
let exeBase =
case splitExtension exePath of
Left _ -> exePath
Right (x, _) -> x
let mountPath = hostBinDir FP.</> toFilePath (filename exeBase)
pure (mountPath, args, [], [Mount (toFilePath exePath) mountPath])
-- | Error if running in a container.
preventInContainer :: MonadIO m => m () -> m ()
preventInContainer inner =
do inContainer <- getInContainer
if inContainer
then throwIO OnlyOnHostException
else inner
| Run a command in a new Docker container , then exit the process .
runContainerAndExit :: HasConfig env => RIO env void
runContainerAndExit = do
config <- view configL
let docker = configDocker config
checkDockerVersion docker
(env,isStdinTerminal,isStderrTerminal,homeDir) <- liftIO $
(,,,)
<$> getEnvironment
<*> hIsTerminalDeviceOrMinTTY stdin
<*> hIsTerminalDeviceOrMinTTY stderr
<*> getHomeDir
isStdoutTerminal <- view terminalL
let dockerHost = lookup "DOCKER_HOST" env
dockerCertPath = lookup "DOCKER_CERT_PATH" env
bamboo = lookup "bamboo_buildKey" env
jenkins = lookup "JENKINS_HOME" env
msshAuthSock = lookup "SSH_AUTH_SOCK" env
muserEnv = lookup "USER" env
isRemoteDocker = maybe False (isPrefixOf "tcp://") dockerHost
mstackYaml <- for (lookup "STACK_YAML" env) RIO.Directory.makeAbsolute
image <- either throwIO pure (dockerImage docker)
when
( isRemoteDocker && maybe False (isInfixOf "boot2docker") dockerCertPath )
( prettyWarnS
"Using boot2docker is NOT supported, and not likely to perform well."
)
maybeImageInfo <- inspect image
imageInfo@Inspect{..} <- case maybeImageInfo of
Just ii -> pure ii
Nothing
| dockerAutoPull docker -> do
pullImage docker image
mii2 <- inspect image
case mii2 of
Just ii2 -> pure ii2
Nothing -> throwM (InspectFailedException image)
| otherwise -> throwM (NotPulledException image)
projectRoot <- getProjectRoot
sandboxDir <- projectDockerSandboxDir projectRoot
let ImageConfig {..} = iiConfig
imageEnvVars = map (break (== '=')) icEnv
platformVariant = show $ hashRepoName image
stackRoot = view stackRootL config
sandboxHomeDir = sandboxDir </> homeDirName
isTerm = not (dockerDetach docker) &&
isStdinTerminal &&
isStdoutTerminal &&
isStderrTerminal
keepStdinOpen = not (dockerDetach docker) &&
Workaround for
This is fixed in Docker 1.9.1 , but will leave the workaround
-- in place for now, for users who haven't upgraded yet.
(isTerm || (isNothing bamboo && isNothing jenkins))
let mpath = T.pack <$> lookupImageEnv "PATH" imageEnvVars
when (isNothing mpath) $ do
prettyWarnL
[ flow "The Docker image does not set the PATH environment variable. \
\This will likely fail. For further information, see"
, style Url "" <> "."
]
newPathEnv <- either throwM pure $ augmentPath
[ hostBinDir
, toFilePath (sandboxHomeDir </> relDirDotLocal </> relDirBin)
]
mpath
(cmnd,args,envVars,extraMount) <- getCmdArgs docker imageInfo isRemoteDocker
pwd <- getCurrentDir
liftIO $ mapM_ ensureDir [sandboxHomeDir, stackRoot]
-- Since $HOME is now mounted in the same place in the container we can
-- just symlink $HOME/.ssh to the right place for the stack docker user
let sshDir = homeDir </> sshRelDir
sshDirExists <- doesDirExist sshDir
sshSandboxDirExists <-
liftIO
(Files.fileExist
(toFilePathNoTrailingSep (sandboxHomeDir </> sshRelDir)))
when (sshDirExists && not sshSandboxDirExists)
(liftIO
(Files.createSymbolicLink
(toFilePathNoTrailingSep sshDir)
(toFilePathNoTrailingSep (sandboxHomeDir </> sshRelDir))))
let mountSuffix = maybe "" (":" ++) (dockerMountMode docker)
containerID <- withWorkingDir (toFilePath projectRoot) $
trim . decodeUtf8 <$> readDockerProcess
( concat
[ [ "create"
, "-e", inContainerEnvVar ++ "=1"
, "-e", stackRootEnvVar ++ "=" ++ toFilePathNoTrailingSep stackRoot
, "-e", platformVariantEnvVar ++ "=dk" ++ platformVariant
, "-e", "HOME=" ++ toFilePathNoTrailingSep sandboxHomeDir
, "-e", "PATH=" ++ T.unpack newPathEnv
, "-e", "PWD=" ++ toFilePathNoTrailingSep pwd
, "-v"
, toFilePathNoTrailingSep homeDir ++ ":" ++
toFilePathNoTrailingSep homeDir ++ mountSuffix
, "-v"
, toFilePathNoTrailingSep stackRoot ++ ":" ++
toFilePathNoTrailingSep stackRoot ++ mountSuffix
, "-v"
, toFilePathNoTrailingSep projectRoot ++ ":" ++
toFilePathNoTrailingSep projectRoot ++ mountSuffix
, "-v"
, toFilePathNoTrailingSep sandboxHomeDir ++ ":" ++
toFilePathNoTrailingSep sandboxHomeDir ++ mountSuffix
, "-w", toFilePathNoTrailingSep pwd
]
, case dockerNetwork docker of
Nothing -> ["--net=host"]
Just name -> ["--net=" ++ name]
, case muserEnv of
Nothing -> []
Just userEnv -> ["-e","USER=" ++ userEnv]
, case msshAuthSock of
Nothing -> []
Just sshAuthSock ->
[ "-e","SSH_AUTH_SOCK=" ++ sshAuthSock
, "-v",sshAuthSock ++ ":" ++ sshAuthSock
]
, case mstackYaml of
Nothing -> []
Just stackYaml ->
[ "-e","STACK_YAML=" ++ stackYaml
, "-v",stackYaml++ ":" ++ stackYaml ++ ":ro"
]
Disable the deprecated entrypoint in FP Complete - generated images
, [ "--entrypoint=/usr/bin/env"
| isJust (lookupImageEnv oldSandboxIdEnvVar imageEnvVars)
&& ( icEntrypoint == ["/usr/local/sbin/docker-entrypoint"]
|| icEntrypoint == ["/root/entrypoint.sh"]
)
]
, concatMap (\(k,v) -> ["-e", k ++ "=" ++ v]) envVars
, concatMap (mountArg mountSuffix) (extraMount ++ dockerMount docker)
, concatMap (\nv -> ["-e", nv]) (dockerEnv docker)
, case dockerContainerName docker of
Just name -> ["--name=" ++ name]
Nothing -> []
, ["-t" | isTerm]
, ["-i" | keepStdinOpen]
, dockerRunArgs docker
, [image]
, [cmnd]
, args
]
)
e <- handleSignals docker keepStdinOpen containerID
case e of
Left ExitCodeException{eceExitCode} -> exitWith eceExitCode
Right () -> exitSuccess
where
This is using a hash of the repository ( without tag or digest ) to
ensure binaries / libraries are n't shared between and host ( or
incompatible images )
hashRepoName :: String -> Hash.Digest Hash.MD5
hashRepoName = Hash.hash . BS.pack . takeWhile (\c -> c /= ':' && c /= '@')
lookupImageEnv name vars =
case lookup name vars of
Just ('=':val) -> Just val
_ -> Nothing
mountArg mountSuffix (Mount host container) =
["-v",host ++ ":" ++ container ++ mountSuffix]
sshRelDir = relDirDotSsh
| Inspect image or container .
inspect :: (HasProcessContext env, HasLogFunc env)
=> String
-> RIO env (Maybe Inspect)
inspect image = do
results <- inspects [image]
case Map.toList results of
[] -> pure Nothing
[(_,i)] -> pure (Just i)
_ -> throwIO (InvalidInspectOutputException "expect a single result")
| Inspect multiple images and/or containers .
inspects :: (HasProcessContext env, HasLogFunc env)
=> [String]
-> RIO env (Map Text Inspect)
inspects [] = pure Map.empty
inspects images = do
maybeInspectOut <-
-- not using 'readDockerProcess' as the error from a missing image
-- needs to be recovered.
try (BL.toStrict . fst <$> proc "docker" ("inspect" : images) readProcess_)
case maybeInspectOut of
Right inspectOut ->
filtering with ' isAscii ' to workaround @docker inspect@ output
containing invalid UTF-8
case eitherDecode (LBS.pack (filter isAscii (decodeUtf8 inspectOut))) of
Left msg -> throwIO (InvalidInspectOutputException msg)
Right results -> pure (Map.fromList (map (\r -> (iiId r,r)) results))
Left ece
| any (`LBS.isPrefixOf` eceStderr ece) missingImagePrefixes ->
pure Map.empty
Left e -> throwIO e
where
missingImagePrefixes = ["Error: No such image", "Error: No such object:"]
| Pull latest version of configured image from registry .
pull :: HasConfig env => RIO env ()
pull = do
config <- view configL
let docker = configDocker config
checkDockerVersion docker
either throwIO (pullImage docker) (dockerImage docker)
-- | Pull Docker image from registry.
pullImage :: (HasProcessContext env, HasLogFunc env)
=> DockerOpts
-> String
-> RIO env ()
pullImage docker image = do
logInfo ("Pulling image from registry: '" <> fromString image <> "'")
when (dockerRegistryLogin docker) $ do
logInfo "You may need to log in."
proc
"docker"
( concat
[ ["login"]
, maybe [] (\n -> ["--username=" ++ n]) (dockerRegistryUsername docker)
, maybe [] (\p -> ["--password=" ++ p]) (dockerRegistryPassword docker)
, [takeWhile (/= '/') image]
]
)
runProcess_
-- We redirect the stdout of the process to stderr so that the output
of @docker pull@ will not interfere with the output of other
commands when using --auto - docker - pull . See issue # 2733 .
ec <- proc "docker" ["pull", image] $ \pc0 -> do
let pc = setStdout (useHandleOpen stderr)
$ setStderr (useHandleOpen stderr)
$ setStdin closed
pc0
runProcess pc
case ec of
ExitSuccess -> pure ()
ExitFailure _ -> throwIO (PullFailedException image)
-- | Check docker version (throws exception if incorrect)
checkDockerVersion ::
(HasProcessContext env, HasLogFunc env)
=> DockerOpts
-> RIO env ()
checkDockerVersion docker = do
dockerExists <- doesExecutableExist "docker"
unless dockerExists (throwIO DockerNotInstalledException)
dockerVersionOut <- readDockerProcess ["--version"]
case words (decodeUtf8 dockerVersionOut) of
(_:_:v:_) ->
case fmap mkVersion' $ parseVersion' $ stripVersion v of
Just v'
| v' < minimumDockerVersion ->
throwIO (DockerTooOldException minimumDockerVersion v')
| v' `elem` prohibitedDockerVersions ->
throwIO (DockerVersionProhibitedException prohibitedDockerVersions v')
| not (v' `withinRange` dockerRequireDockerVersion docker) ->
throwIO (BadDockerVersionException (dockerRequireDockerVersion docker) v')
| otherwise ->
pure ()
_ -> throwIO InvalidVersionOutputException
_ -> throwIO InvalidVersionOutputException
where
minimumDockerVersion = mkVersion [1, 6, 0]
prohibitedDockerVersions = []
stripVersion v = takeWhile (/= '-') (dropWhileEnd (not . isDigit) v)
-- version is parsed by Data.Version provided code to avoid
Cabal 's Distribution . Version lack of support for leading zeros in version
parseVersion' =
fmap fst . listToMaybe . reverse . readP_to_S Data.Version.parseVersion
| Remove the project 's sandbox .
reset :: HasConfig env => Bool -> RIO env ()
reset keepHome = do
projectRoot <- getProjectRoot
dockerSandboxDir <- projectDockerSandboxDir projectRoot
liftIO (removeDirectoryContents
dockerSandboxDir
[homeDirName | keepHome]
[])
| The container " entrypoint " : special actions performed when first
entering a container , such as switching the UID / GID to the " outside - Docker "
-- user's.
entrypoint :: (HasProcessContext env, HasLogFunc env)
=> Config
-> DockerEntrypoint
-> RIO env ()
entrypoint config@Config{} DockerEntrypoint{..} =
modifyMVar_ entrypointMVar $ \alreadyRan -> do
-- Only run the entrypoint once
unless alreadyRan $ do
envOverride <- view processContextL
homeDir <- liftIO $ parseAbsDir =<< getEnv "HOME"
-- Get the UserEntry for the 'stack' user in the image, if it exists
estackUserEntry0 <- liftIO $ tryJust (guard . isDoesNotExistError) $
User.getUserEntryForName stackUserName
Switch UID / GID if needed , and update user 's home directory
case deUser of
Nothing -> pure ()
Just (DockerUser 0 _ _ _) -> pure ()
Just du -> withProcessContext envOverride $
updateOrCreateStackUser estackUserEntry0 homeDir du
case estackUserEntry0 of
Left _ -> pure ()
Right ue -> do
-- If the 'stack' user exists in the image, copy any build plans and
-- package indices from its original home directory to the host's
-- Stack root, to avoid needing to download them
origStackHomeDir <- liftIO $ parseAbsDir (User.homeDirectory ue)
let origStackRoot = origStackHomeDir </> relDirDotStackProgName
buildPlanDirExists <- doesDirExist (buildPlanDir origStackRoot)
when buildPlanDirExists $ do
(_, buildPlans) <- listDir (buildPlanDir origStackRoot)
forM_ buildPlans $ \srcBuildPlan -> do
let destBuildPlan =
buildPlanDir (view stackRootL config) </> filename srcBuildPlan
exists <- doesFileExist destBuildPlan
unless exists $ do
ensureDir (parent destBuildPlan)
copyFile srcBuildPlan destBuildPlan
pure True
where
updateOrCreateStackUser estackUserEntry homeDir DockerUser{..} = do
case estackUserEntry of
Left _ -> do
If no ' stack ' user in image , create one with correct UID / GID and home
-- directory
readProcessNull "groupadd"
["-o"
,"--gid",show duGid
,stackUserName]
readProcessNull "useradd"
["-oN"
,"--uid",show duUid
,"--gid",show duGid
,"--home",toFilePathNoTrailingSep homeDir
,stackUserName]
Right _ -> do
If there is already a ' stack ' user in the image , adjust its UID / GID
-- and home directory
readProcessNull "usermod"
["-o"
,"--uid",show duUid
,"--home",toFilePathNoTrailingSep homeDir
,stackUserName]
readProcessNull "groupmod"
["-o"
,"--gid",show duGid
,stackUserName]
forM_ duGroups $ \gid ->
readProcessNull "groupadd"
["-o"
,"--gid",show gid
,"group" ++ show gid]
' setuid ' to the wanted UID and GID
liftIO $ do
User.setGroupID duGid
handleSetGroups duGroups
User.setUserID duUid
_ <- Files.setFileCreationMask duUmask
pure ()
stackUserName = "stack" :: String
| MVar used to ensure the entrypoint is performed exactly once
entrypointMVar :: MVar Bool
# NOINLINE entrypointMVar #
entrypointMVar = unsafePerformIO (newMVar False)
-- | Remove the contents of a directory, without removing the directory itself.
This is used instead of ' FS.removeTree ' to clear bind - mounted directories ,
-- since removing the root of the bind-mount won't work.
removeDirectoryContents ::
Path Abs Dir -- ^ Directory to remove contents of
-> [Path Rel Dir] -- ^ Top-level directory names to exclude from removal
-> [Path Rel File] -- ^ Top-level file names to exclude from removal
-> IO ()
removeDirectoryContents path excludeDirs excludeFiles = do
isRootDir <- doesDirExist path
when isRootDir $ do
(lsd,lsf) <- listDir path
forM_ lsd
(\d -> unless (dirname d `elem` excludeDirs)
(removeDirRecur d))
forM_ lsf
(\f -> unless (filename f `elem` excludeFiles)
(removeFile f))
-- | Produce a strict 'S.ByteString' from the stdout of a process. Throws a
-- 'ReadProcessException' exception if the process fails.
--
-- The stderr output is passed straight through, which is desirable for some
-- cases e.g. docker pull, in which docker uses stderr for progress output.
--
-- Use 'readProcess_' directly to customize this.
readDockerProcess ::
(HasProcessContext env, HasLogFunc env)
=> [String] -> RIO env BS.ByteString
readDockerProcess args = BL.toStrict <$> proc "docker" args readProcessStdout_
-- | Name of home directory within docker sandbox.
homeDirName :: Path Rel Dir
homeDirName = relDirUnderHome
| Directory where ' stack ' executable is bind - mounted in container
-- This refers to a path in the Linux *container*, and so should remain a
' FilePath ' ( not ' Path Abs Dir ' ) so that it works when the host runs Windows .
hostBinDir :: FilePath
hostBinDir = "/opt/host/bin"
| Convenience function to decode ByteString to String .
decodeUtf8 :: BS.ByteString -> String
decodeUtf8 bs = T.unpack (T.decodeUtf8 bs)
-- | Fail with friendly error if project root not set.
getProjectRoot :: HasConfig env => RIO env (Path Abs Dir)
getProjectRoot = do
mroot <- view $ configL.to configProjectRoot
maybe (throwIO CannotDetermineProjectRootException) pure mroot
-- | Environment variable that contained the old sandbox ID.
-- | Use of this variable is deprecated, and only used to detect old images.
oldSandboxIdEnvVar :: String
oldSandboxIdEnvVar = "DOCKER_SANDBOX_ID"
| result of @docker inspect@.
data Inspect = Inspect
{ iiConfig :: ImageConfig
, iiCreated :: UTCTime
, iiId :: Text
, iiVirtualSize :: Maybe Integer
}
deriving Show
| Parse @docker inspect@ output .
instance FromJSON Inspect where
parseJSON v = do
o <- parseJSON v
Inspect
<$> o .: "Config"
<*> o .: "Created"
<*> o .: "Id"
<*> o .:? "VirtualSize"
| @Config@ section of @docker inspect@ output .
data ImageConfig = ImageConfig
{ icEnv :: [String]
, icEntrypoint :: [String]
}
deriving Show
| Parse @Config@ section of @docker inspect@ output .
instance FromJSON ImageConfig where
parseJSON v = do
o <- parseJSON v
ImageConfig
<$> fmap join (o .:? "Env") .!= []
<*> fmap join (o .:? "Entrypoint") .!= []
| null | https://raw.githubusercontent.com/commercialhaskell/stack/80429690da92c634cb129f99f1507dbc47a70d45/src/Stack/Docker.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
Only way to get old umask seems to be to change it, so set it back afterward
In any event, I'm not even sure _why_ we need to drop a file extension here
| Error if running in a container.
in place for now, for users who haven't upgraded yet.
Since $HOME is now mounted in the same place in the container we can
just symlink $HOME/.ssh to the right place for the stack docker user
not using 'readDockerProcess' as the error from a missing image
needs to be recovered.
| Pull Docker image from registry.
We redirect the stdout of the process to stderr so that the output
auto - docker - pull . See issue # 2733 .
| Check docker version (throws exception if incorrect)
version is parsed by Data.Version provided code to avoid
user's.
Only run the entrypoint once
Get the UserEntry for the 'stack' user in the image, if it exists
If the 'stack' user exists in the image, copy any build plans and
package indices from its original home directory to the host's
Stack root, to avoid needing to download them
directory
and home directory
| Remove the contents of a directory, without removing the directory itself.
since removing the root of the bind-mount won't work.
^ Directory to remove contents of
^ Top-level directory names to exclude from removal
^ Top-level file names to exclude from removal
| Produce a strict 'S.ByteString' from the stdout of a process. Throws a
'ReadProcessException' exception if the process fails.
The stderr output is passed straight through, which is desirable for some
cases e.g. docker pull, in which docker uses stderr for progress output.
Use 'readProcess_' directly to customize this.
| Name of home directory within docker sandbox.
This refers to a path in the Linux *container*, and so should remain a
| Fail with friendly error if project root not set.
| Environment variable that contained the old sandbox ID.
| Use of this variable is deprecated, and only used to detect old images. | # LANGUAGE NoImplicitPrelude #
| Run commands in containers
module Stack.Docker
( dockerCmdName
, dockerHelpOptName
, dockerPullCmdName
, entrypoint
, preventInContainer
, pull
, reset
, reExecArgName
, DockerException (..)
, getProjectRoot
, runContainerAndExit
) where
import qualified Crypto.Hash as Hash ( Digest, MD5, hash )
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Char ( isAscii, isDigit )
import Data.Conduit.List ( sinkNull )
import Data.Conduit.Process.Typed hiding ( proc )
import Data.List ( dropWhileEnd, isInfixOf, isPrefixOf )
import Data.List.Extra ( trim )
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time ( UTCTime )
import qualified Data.Version ( parseVersion )
import Distribution.Version ( mkVersion, mkVersion' )
import Pantry.Internal.AesonExtended
( FromJSON (..), (.:), (.:?), (.!=), eitherDecode )
import Path
( (</>), dirname, filename, parent, parseAbsDir
, splitExtension
)
import Path.Extra ( toFilePathNoTrailingSep )
import Path.IO hiding ( canonicalizePath )
import qualified RIO.Directory ( makeAbsolute )
import RIO.Process
( HasProcessContext, augmentPath, doesExecutableExist, proc
, processContextL, withWorkingDir
)
import Stack.Config ( getInContainer )
import Stack.Constants
( buildPlanDir, inContainerEnvVar, platformVariantEnvVar
, relDirBin, relDirDotLocal, relDirDotSsh
, relDirDotStackProgName, relDirUnderHome, stackRootEnvVar
)
import Stack.Constants.Config ( projectDockerSandboxDir )
import Stack.Docker.Handlers ( handleSetGroups, handleSignals )
import Stack.Prelude
import Stack.Setup ( ensureDockerStackExe )
import Stack.Storage.User
( loadDockerImageExeCache, saveDockerImageExeCache )
import Stack.Types.Config
( Config (..), DockerEntrypoint (..), DockerUser (..)
, HasConfig (..), configProjectRoot, stackRootL, terminalL
)
import Stack.Types.Docker
( DockerException (..), DockerOpts (..), DockerStackExe (..)
, Mount (..), dockerCmdName, dockerContainerPlatform
, dockerEntrypointArgName, dockerHelpOptName
, dockerPullCmdName, reExecArgName
)
import Stack.Types.Version ( showStackVersion, withinRange )
import System.Environment
( getArgs, getEnv, getEnvironment, getExecutablePath
, getProgName
)
import qualified System.FilePath as FP
import System.IO.Error ( isDoesNotExistError )
import System.IO.Unsafe ( unsafePerformIO )
import qualified System.PosixCompat.User as User
import qualified System.PosixCompat.Files as Files
import System.Terminal ( hIsTerminalDeviceOrMinTTY )
import Text.ParserCombinators.ReadP ( readP_to_S )
| Function to get command and arguments to run in Docker container
getCmdArgs ::
HasConfig env
=> DockerOpts
-> Inspect
-> Bool
-> RIO env (FilePath,[String],[(String,String)],[Mount])
getCmdArgs docker imageInfo isRemoteDocker = do
config <- view configL
deUser <-
if fromMaybe (not isRemoteDocker) (dockerSetUser docker)
then liftIO $ do
duUid <- User.getEffectiveUserID
duGid <- User.getEffectiveGroupID
duGroups <- nubOrd <$> User.getGroups
duUmask <- Files.setFileCreationMask 0o022
_ <- Files.setFileCreationMask duUmask
pure (Just DockerUser{..})
else pure Nothing
args <-
fmap
(["--" ++ reExecArgName ++ "=" ++ showStackVersion
,"--" ++ dockerEntrypointArgName
,show DockerEntrypoint{..}] ++)
(liftIO getArgs)
case dockerStackExe (configDocker config) of
Just DockerStackExeHost
| configPlatform config == dockerContainerPlatform -> do
exePath <- resolveFile' =<< liftIO getExecutablePath
cmdArgs args exePath
| otherwise -> throwIO UnsupportedStackExeHostPlatformException
Just DockerStackExeImage -> do
progName <- liftIO getProgName
pure (FP.takeBaseName progName, args, [], [])
Just (DockerStackExePath path) -> cmdArgs args path
Just DockerStackExeDownload -> exeDownload args
Nothing
| configPlatform config == dockerContainerPlatform -> do
(exePath,exeTimestamp,misCompatible) <-
do exePath <- resolveFile' =<< liftIO getExecutablePath
exeTimestamp <- getModificationTime exePath
isKnown <-
loadDockerImageExeCache
(iiId imageInfo)
exePath
exeTimestamp
pure (exePath, exeTimestamp, isKnown)
case misCompatible of
Just True -> cmdArgs args exePath
Just False -> exeDownload args
Nothing -> do
e <-
try $
sinkProcessStderrStdout
"docker"
[ "run"
, "-v"
, toFilePath exePath ++ ":" ++ "/tmp/stack"
, T.unpack (iiId imageInfo)
, "/tmp/stack"
, "--version"]
sinkNull
sinkNull
let compatible =
case e of
Left ExitCodeException{} -> False
Right _ -> True
saveDockerImageExeCache
(iiId imageInfo)
exePath
exeTimestamp
compatible
if compatible
then cmdArgs args exePath
else exeDownload args
Nothing -> exeDownload args
where
exeDownload args = do
exePath <- ensureDockerStackExe dockerContainerPlatform
cmdArgs args exePath
cmdArgs args exePath = do
MSS 2020 - 04 - 21 previously used replaceExtension , but semantics changed in path 0.7
Originally introduced here :
let exeBase =
case splitExtension exePath of
Left _ -> exePath
Right (x, _) -> x
let mountPath = hostBinDir FP.</> toFilePath (filename exeBase)
pure (mountPath, args, [], [Mount (toFilePath exePath) mountPath])
preventInContainer :: MonadIO m => m () -> m ()
preventInContainer inner =
do inContainer <- getInContainer
if inContainer
then throwIO OnlyOnHostException
else inner
| Run a command in a new Docker container , then exit the process .
runContainerAndExit :: HasConfig env => RIO env void
runContainerAndExit = do
config <- view configL
let docker = configDocker config
checkDockerVersion docker
(env,isStdinTerminal,isStderrTerminal,homeDir) <- liftIO $
(,,,)
<$> getEnvironment
<*> hIsTerminalDeviceOrMinTTY stdin
<*> hIsTerminalDeviceOrMinTTY stderr
<*> getHomeDir
isStdoutTerminal <- view terminalL
let dockerHost = lookup "DOCKER_HOST" env
dockerCertPath = lookup "DOCKER_CERT_PATH" env
bamboo = lookup "bamboo_buildKey" env
jenkins = lookup "JENKINS_HOME" env
msshAuthSock = lookup "SSH_AUTH_SOCK" env
muserEnv = lookup "USER" env
isRemoteDocker = maybe False (isPrefixOf "tcp://") dockerHost
mstackYaml <- for (lookup "STACK_YAML" env) RIO.Directory.makeAbsolute
image <- either throwIO pure (dockerImage docker)
when
( isRemoteDocker && maybe False (isInfixOf "boot2docker") dockerCertPath )
( prettyWarnS
"Using boot2docker is NOT supported, and not likely to perform well."
)
maybeImageInfo <- inspect image
imageInfo@Inspect{..} <- case maybeImageInfo of
Just ii -> pure ii
Nothing
| dockerAutoPull docker -> do
pullImage docker image
mii2 <- inspect image
case mii2 of
Just ii2 -> pure ii2
Nothing -> throwM (InspectFailedException image)
| otherwise -> throwM (NotPulledException image)
projectRoot <- getProjectRoot
sandboxDir <- projectDockerSandboxDir projectRoot
let ImageConfig {..} = iiConfig
imageEnvVars = map (break (== '=')) icEnv
platformVariant = show $ hashRepoName image
stackRoot = view stackRootL config
sandboxHomeDir = sandboxDir </> homeDirName
isTerm = not (dockerDetach docker) &&
isStdinTerminal &&
isStdoutTerminal &&
isStderrTerminal
keepStdinOpen = not (dockerDetach docker) &&
Workaround for
This is fixed in Docker 1.9.1 , but will leave the workaround
(isTerm || (isNothing bamboo && isNothing jenkins))
let mpath = T.pack <$> lookupImageEnv "PATH" imageEnvVars
when (isNothing mpath) $ do
prettyWarnL
[ flow "The Docker image does not set the PATH environment variable. \
\This will likely fail. For further information, see"
, style Url "" <> "."
]
newPathEnv <- either throwM pure $ augmentPath
[ hostBinDir
, toFilePath (sandboxHomeDir </> relDirDotLocal </> relDirBin)
]
mpath
(cmnd,args,envVars,extraMount) <- getCmdArgs docker imageInfo isRemoteDocker
pwd <- getCurrentDir
liftIO $ mapM_ ensureDir [sandboxHomeDir, stackRoot]
let sshDir = homeDir </> sshRelDir
sshDirExists <- doesDirExist sshDir
sshSandboxDirExists <-
liftIO
(Files.fileExist
(toFilePathNoTrailingSep (sandboxHomeDir </> sshRelDir)))
when (sshDirExists && not sshSandboxDirExists)
(liftIO
(Files.createSymbolicLink
(toFilePathNoTrailingSep sshDir)
(toFilePathNoTrailingSep (sandboxHomeDir </> sshRelDir))))
let mountSuffix = maybe "" (":" ++) (dockerMountMode docker)
containerID <- withWorkingDir (toFilePath projectRoot) $
trim . decodeUtf8 <$> readDockerProcess
( concat
[ [ "create"
, "-e", inContainerEnvVar ++ "=1"
, "-e", stackRootEnvVar ++ "=" ++ toFilePathNoTrailingSep stackRoot
, "-e", platformVariantEnvVar ++ "=dk" ++ platformVariant
, "-e", "HOME=" ++ toFilePathNoTrailingSep sandboxHomeDir
, "-e", "PATH=" ++ T.unpack newPathEnv
, "-e", "PWD=" ++ toFilePathNoTrailingSep pwd
, "-v"
, toFilePathNoTrailingSep homeDir ++ ":" ++
toFilePathNoTrailingSep homeDir ++ mountSuffix
, "-v"
, toFilePathNoTrailingSep stackRoot ++ ":" ++
toFilePathNoTrailingSep stackRoot ++ mountSuffix
, "-v"
, toFilePathNoTrailingSep projectRoot ++ ":" ++
toFilePathNoTrailingSep projectRoot ++ mountSuffix
, "-v"
, toFilePathNoTrailingSep sandboxHomeDir ++ ":" ++
toFilePathNoTrailingSep sandboxHomeDir ++ mountSuffix
, "-w", toFilePathNoTrailingSep pwd
]
, case dockerNetwork docker of
Nothing -> ["--net=host"]
Just name -> ["--net=" ++ name]
, case muserEnv of
Nothing -> []
Just userEnv -> ["-e","USER=" ++ userEnv]
, case msshAuthSock of
Nothing -> []
Just sshAuthSock ->
[ "-e","SSH_AUTH_SOCK=" ++ sshAuthSock
, "-v",sshAuthSock ++ ":" ++ sshAuthSock
]
, case mstackYaml of
Nothing -> []
Just stackYaml ->
[ "-e","STACK_YAML=" ++ stackYaml
, "-v",stackYaml++ ":" ++ stackYaml ++ ":ro"
]
Disable the deprecated entrypoint in FP Complete - generated images
, [ "--entrypoint=/usr/bin/env"
| isJust (lookupImageEnv oldSandboxIdEnvVar imageEnvVars)
&& ( icEntrypoint == ["/usr/local/sbin/docker-entrypoint"]
|| icEntrypoint == ["/root/entrypoint.sh"]
)
]
, concatMap (\(k,v) -> ["-e", k ++ "=" ++ v]) envVars
, concatMap (mountArg mountSuffix) (extraMount ++ dockerMount docker)
, concatMap (\nv -> ["-e", nv]) (dockerEnv docker)
, case dockerContainerName docker of
Just name -> ["--name=" ++ name]
Nothing -> []
, ["-t" | isTerm]
, ["-i" | keepStdinOpen]
, dockerRunArgs docker
, [image]
, [cmnd]
, args
]
)
e <- handleSignals docker keepStdinOpen containerID
case e of
Left ExitCodeException{eceExitCode} -> exitWith eceExitCode
Right () -> exitSuccess
where
This is using a hash of the repository ( without tag or digest ) to
ensure binaries / libraries are n't shared between and host ( or
incompatible images )
hashRepoName :: String -> Hash.Digest Hash.MD5
hashRepoName = Hash.hash . BS.pack . takeWhile (\c -> c /= ':' && c /= '@')
lookupImageEnv name vars =
case lookup name vars of
Just ('=':val) -> Just val
_ -> Nothing
mountArg mountSuffix (Mount host container) =
["-v",host ++ ":" ++ container ++ mountSuffix]
sshRelDir = relDirDotSsh
| Inspect image or container .
inspect :: (HasProcessContext env, HasLogFunc env)
=> String
-> RIO env (Maybe Inspect)
inspect image = do
results <- inspects [image]
case Map.toList results of
[] -> pure Nothing
[(_,i)] -> pure (Just i)
_ -> throwIO (InvalidInspectOutputException "expect a single result")
| Inspect multiple images and/or containers .
inspects :: (HasProcessContext env, HasLogFunc env)
=> [String]
-> RIO env (Map Text Inspect)
inspects [] = pure Map.empty
inspects images = do
maybeInspectOut <-
try (BL.toStrict . fst <$> proc "docker" ("inspect" : images) readProcess_)
case maybeInspectOut of
Right inspectOut ->
filtering with ' isAscii ' to workaround @docker inspect@ output
containing invalid UTF-8
case eitherDecode (LBS.pack (filter isAscii (decodeUtf8 inspectOut))) of
Left msg -> throwIO (InvalidInspectOutputException msg)
Right results -> pure (Map.fromList (map (\r -> (iiId r,r)) results))
Left ece
| any (`LBS.isPrefixOf` eceStderr ece) missingImagePrefixes ->
pure Map.empty
Left e -> throwIO e
where
missingImagePrefixes = ["Error: No such image", "Error: No such object:"]
| Pull latest version of configured image from registry .
pull :: HasConfig env => RIO env ()
pull = do
config <- view configL
let docker = configDocker config
checkDockerVersion docker
either throwIO (pullImage docker) (dockerImage docker)
pullImage :: (HasProcessContext env, HasLogFunc env)
=> DockerOpts
-> String
-> RIO env ()
pullImage docker image = do
logInfo ("Pulling image from registry: '" <> fromString image <> "'")
when (dockerRegistryLogin docker) $ do
logInfo "You may need to log in."
proc
"docker"
( concat
[ ["login"]
, maybe [] (\n -> ["--username=" ++ n]) (dockerRegistryUsername docker)
, maybe [] (\p -> ["--password=" ++ p]) (dockerRegistryPassword docker)
, [takeWhile (/= '/') image]
]
)
runProcess_
of @docker pull@ will not interfere with the output of other
ec <- proc "docker" ["pull", image] $ \pc0 -> do
let pc = setStdout (useHandleOpen stderr)
$ setStderr (useHandleOpen stderr)
$ setStdin closed
pc0
runProcess pc
case ec of
ExitSuccess -> pure ()
ExitFailure _ -> throwIO (PullFailedException image)
checkDockerVersion ::
(HasProcessContext env, HasLogFunc env)
=> DockerOpts
-> RIO env ()
checkDockerVersion docker = do
dockerExists <- doesExecutableExist "docker"
unless dockerExists (throwIO DockerNotInstalledException)
dockerVersionOut <- readDockerProcess ["--version"]
case words (decodeUtf8 dockerVersionOut) of
(_:_:v:_) ->
case fmap mkVersion' $ parseVersion' $ stripVersion v of
Just v'
| v' < minimumDockerVersion ->
throwIO (DockerTooOldException minimumDockerVersion v')
| v' `elem` prohibitedDockerVersions ->
throwIO (DockerVersionProhibitedException prohibitedDockerVersions v')
| not (v' `withinRange` dockerRequireDockerVersion docker) ->
throwIO (BadDockerVersionException (dockerRequireDockerVersion docker) v')
| otherwise ->
pure ()
_ -> throwIO InvalidVersionOutputException
_ -> throwIO InvalidVersionOutputException
where
minimumDockerVersion = mkVersion [1, 6, 0]
prohibitedDockerVersions = []
stripVersion v = takeWhile (/= '-') (dropWhileEnd (not . isDigit) v)
Cabal 's Distribution . Version lack of support for leading zeros in version
parseVersion' =
fmap fst . listToMaybe . reverse . readP_to_S Data.Version.parseVersion
| Remove the project 's sandbox .
reset :: HasConfig env => Bool -> RIO env ()
reset keepHome = do
projectRoot <- getProjectRoot
dockerSandboxDir <- projectDockerSandboxDir projectRoot
liftIO (removeDirectoryContents
dockerSandboxDir
[homeDirName | keepHome]
[])
| The container " entrypoint " : special actions performed when first
entering a container , such as switching the UID / GID to the " outside - Docker "
entrypoint :: (HasProcessContext env, HasLogFunc env)
=> Config
-> DockerEntrypoint
-> RIO env ()
entrypoint config@Config{} DockerEntrypoint{..} =
modifyMVar_ entrypointMVar $ \alreadyRan -> do
unless alreadyRan $ do
envOverride <- view processContextL
homeDir <- liftIO $ parseAbsDir =<< getEnv "HOME"
estackUserEntry0 <- liftIO $ tryJust (guard . isDoesNotExistError) $
User.getUserEntryForName stackUserName
Switch UID / GID if needed , and update user 's home directory
case deUser of
Nothing -> pure ()
Just (DockerUser 0 _ _ _) -> pure ()
Just du -> withProcessContext envOverride $
updateOrCreateStackUser estackUserEntry0 homeDir du
case estackUserEntry0 of
Left _ -> pure ()
Right ue -> do
origStackHomeDir <- liftIO $ parseAbsDir (User.homeDirectory ue)
let origStackRoot = origStackHomeDir </> relDirDotStackProgName
buildPlanDirExists <- doesDirExist (buildPlanDir origStackRoot)
when buildPlanDirExists $ do
(_, buildPlans) <- listDir (buildPlanDir origStackRoot)
forM_ buildPlans $ \srcBuildPlan -> do
let destBuildPlan =
buildPlanDir (view stackRootL config) </> filename srcBuildPlan
exists <- doesFileExist destBuildPlan
unless exists $ do
ensureDir (parent destBuildPlan)
copyFile srcBuildPlan destBuildPlan
pure True
where
updateOrCreateStackUser estackUserEntry homeDir DockerUser{..} = do
case estackUserEntry of
Left _ -> do
If no ' stack ' user in image , create one with correct UID / GID and home
readProcessNull "groupadd"
["-o"
,"--gid",show duGid
,stackUserName]
readProcessNull "useradd"
["-oN"
,"--uid",show duUid
,"--gid",show duGid
,"--home",toFilePathNoTrailingSep homeDir
,stackUserName]
Right _ -> do
If there is already a ' stack ' user in the image , adjust its UID / GID
readProcessNull "usermod"
["-o"
,"--uid",show duUid
,"--home",toFilePathNoTrailingSep homeDir
,stackUserName]
readProcessNull "groupmod"
["-o"
,"--gid",show duGid
,stackUserName]
forM_ duGroups $ \gid ->
readProcessNull "groupadd"
["-o"
,"--gid",show gid
,"group" ++ show gid]
' setuid ' to the wanted UID and GID
liftIO $ do
User.setGroupID duGid
handleSetGroups duGroups
User.setUserID duUid
_ <- Files.setFileCreationMask duUmask
pure ()
stackUserName = "stack" :: String
| MVar used to ensure the entrypoint is performed exactly once
entrypointMVar :: MVar Bool
# NOINLINE entrypointMVar #
entrypointMVar = unsafePerformIO (newMVar False)
This is used instead of ' FS.removeTree ' to clear bind - mounted directories ,
removeDirectoryContents ::
-> IO ()
removeDirectoryContents path excludeDirs excludeFiles = do
isRootDir <- doesDirExist path
when isRootDir $ do
(lsd,lsf) <- listDir path
forM_ lsd
(\d -> unless (dirname d `elem` excludeDirs)
(removeDirRecur d))
forM_ lsf
(\f -> unless (filename f `elem` excludeFiles)
(removeFile f))
readDockerProcess ::
(HasProcessContext env, HasLogFunc env)
=> [String] -> RIO env BS.ByteString
readDockerProcess args = BL.toStrict <$> proc "docker" args readProcessStdout_
homeDirName :: Path Rel Dir
homeDirName = relDirUnderHome
| Directory where ' stack ' executable is bind - mounted in container
' FilePath ' ( not ' Path Abs Dir ' ) so that it works when the host runs Windows .
hostBinDir :: FilePath
hostBinDir = "/opt/host/bin"
| Convenience function to decode ByteString to String .
decodeUtf8 :: BS.ByteString -> String
decodeUtf8 bs = T.unpack (T.decodeUtf8 bs)
getProjectRoot :: HasConfig env => RIO env (Path Abs Dir)
getProjectRoot = do
mroot <- view $ configL.to configProjectRoot
maybe (throwIO CannotDetermineProjectRootException) pure mroot
oldSandboxIdEnvVar :: String
oldSandboxIdEnvVar = "DOCKER_SANDBOX_ID"
| result of @docker inspect@.
data Inspect = Inspect
{ iiConfig :: ImageConfig
, iiCreated :: UTCTime
, iiId :: Text
, iiVirtualSize :: Maybe Integer
}
deriving Show
| Parse @docker inspect@ output .
instance FromJSON Inspect where
parseJSON v = do
o <- parseJSON v
Inspect
<$> o .: "Config"
<*> o .: "Created"
<*> o .: "Id"
<*> o .:? "VirtualSize"
| @Config@ section of @docker inspect@ output .
data ImageConfig = ImageConfig
{ icEnv :: [String]
, icEntrypoint :: [String]
}
deriving Show
| Parse @Config@ section of @docker inspect@ output .
instance FromJSON ImageConfig where
parseJSON v = do
o <- parseJSON v
ImageConfig
<$> fmap join (o .:? "Env") .!= []
<*> fmap join (o .:? "Entrypoint") .!= []
|
de6e89eec2ba88aa1ca48b35c22fac26e608224ed7edd1314cde58b702a63e4f | kappelmann/engaging-large-scale-functional-programming | Internal.hs | # LANGUAGE Unsafe #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ExistentialQuantification #
# LANGUAGE RecordWildCards #
{-# LANGUAGE PackageImports #-}
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE TupleSections #
# LANGUAGE StandaloneDeriving #
{-# LANGUAGE DoAndIfThenElse #-}
module Mock.System.IO.Internal (
IO, MVar, IORef, Handle, IOMode (..), SeekMode (..), FilePath, HandlePosn (..), Direction (In, Out), SpecialFile (..),
IOException (..), IOErrorType (..), ConsoleHook, HandleHook, BufferMode (..),
RealWorld (RealWorld, handles, files, workDir, isPermitted),
newWorld, emptyWorld, setUser, runIO, evalIO, tryRunIO, tryEvalIO, stdin, stdout, stderr, runUser, runUserCompletely,
newMVar, newEmptyMVar, isEmptyMVar, tryTakeMVar, takeMVar, tryPutMVar, tryReadMVar, readMVar, putMVar, swapMVar, modifyMVar, modifyMVar_,
newIORef, readIORef, writeIORef, modifyIORef, modifyIORef', atomicModifyIORef, atomicModifyIORef', atomicWriteIORef,
withFile, openFile, hClose, readFile, writeFile, appendFile, doesFileExist,
hFileSize, hSetFileSize, hIsEOF, isEOF, hGetBuffering, hSetBuffering, hFlush,
hGetPosn, hSetPosn, hSeek, hTell, hReady, hAvailable, hWaitForInput,
hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable, hIsTerminalDevice, hShow,
hGetChar, hGetLine, hLookAhead, hGetContents,
hPutChar, hPutStr, hPutStrLn, hPrint,
putChar, putStr, putStrLn, print,
getChar, getLine, getContents, readIO, readLn, interact,
dumpHandle, getOpenHandles,wait,
ioError, ioException, userError, tryIO, catchIO,
registerWriteHook, hookConsole, readConsoleHook, showConsoleHook, hookHandle, readHandleHook, showHandleHook,
isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError, isFullError, isEOFError, isIllegalOperation,
isPermissionError, isUserError, ioeGetErrorType, ioeGetLocation, ioeGetErrorString, ioeGetHandle, ioeGetFileName,
isReadDeadlockError, isAcceptDeadlockError,
R.RandomGen(R.next, R.split, R.genRange), StdGen, R.mkStdGen, getStdRandom, getStdGen, setStdGen,
newStdGen, setRandomSeed
) where
import "base" Prelude hiding (FilePath, IO, getLine, getChar, readIO, readLn, putStr, putStrLn, putChar, print,
readFile, writeFile, appendFile, getContents, interact, userError, ioError, IOError)
import qualified "random" System.Random as R
import Control.Arrow
import Control.Applicative
import Control.Exception hiding (Deadlock, ioError, IOException, IOError)
import Control.Monad
import Control.Monad.Cont
import Control.Monad.State.Strict
import Control.Monad.Pause
import Control.Monad.Except
import Data.Function
import qualified Data.Text.Lazy as T
import Data.Text.Lazy (Text)
import qualified Data.Map.Strict as M
import Data.Map.Strict (Map)
import Data.Maybe
import Data.Ord
import Data.List.Split
import Data.List
import Data.Typeable
import Foreign.C.Types
type FilePath = String
interpretPath :: FilePath -> FilePath -> FilePath
interpretPath p1 p2 = normalizePath $ if head p2 == '/' then p2 else p1 ++ "/" ++ p2
isValidPath :: FilePath -> Bool
isValidPath "" = False
isValidPath p = all (== '/') p || last p /= '/'
normalizePath :: FilePath -> FilePath
normalizePath p
| abs p = fromPartsAbs (normAbs parts [])
| otherwise = fromPartsRel (normRel parts [])
where
abs ('/':_) = True
abs _ = False
parts = filter (not . null) $ filter (/= ".") $ splitOn "/" $ p
fromPartsAbs p = "/" ++ intercalate "/" p
fromPartsRel p = if null p then "." else intercalate "/" p
normAbs [] as = reverse as
normAbs (".." : ps) [] = normAbs ps []
normAbs (".." : ps) (a : as) = normAbs ps as
normAbs (p : ps) as = normAbs ps (p : as)
normRel [] as = reverse as
normRel (".." : ps) [] = normRel ps [".."]
normRel (".." : ps) (a : as)
| a /= ".." = normRel ps as
normRel (p : ps) as = normRel ps (p : as)
data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode deriving (Show, Eq, Ord, Read, Enum, Typeable)
data SeekMode = AbsoluteSeek | RelativeSeek | SeekFromEnd deriving (Show, Eq, Ord, Read, Enum, Typeable)
allowsReading :: IOMode -> Bool
allowsReading m = m == ReadMode || m == ReadWriteMode
allowsWriting :: IOMode -> Bool
allowsWriting m = m /= ReadMode
data SpecialFile = StdIn | StdOut | StdErr deriving (Eq, Ord, Typeable)
instance Show SpecialFile where
show StdIn = "<stdin>"
show StdOut = "<stdout>"
show StdErr = "<stderr>"
data Direction = In | Out deriving (Eq, Ord, Show, Typeable)
data File = RegularFile FilePath | SpecialFile SpecialFile deriving (Eq, Ord, Typeable)
instance Show File where
show (RegularFile p) = p
show (SpecialFile t) = show t
data HandleType = SpecialHandle | RegularFileHandle deriving (Show, Eq, Ord)
data Handle = Handle {_hId :: Integer, _hName :: String, _hType :: HandleType,
_hInFile :: File, _hOutFile :: File} deriving (Typeable)
instance Eq Handle where
(==) = (==) `on` _hId
instance Ord Handle where
compare = comparing _hId
instance Show Handle where
show = _hName
data BufferMode = NoBuffering | LineBuffering | BlockBuffering (Maybe Int) deriving (Eq, Ord, Read, Show, Typeable)
data HandleData = HandleData {
_hGetMode :: IOMode,
_hIsOpen :: Bool,
_hIsSeekable :: Bool,
_hBufferMode :: BufferMode,
_hInBufPos :: Integer,
_hOutBufPos :: Integer
} deriving (Typeable)
_hIsFile :: Handle -> Bool
_hIsFile h = case _hInFile h of {RegularFile _ -> True; _ -> False}
type User = IO ()
data MVar a = MVar Integer deriving (Eq, Ord, Typeable)
data MValue = MEmpty | forall a. Typeable a => MValue a deriving (Typeable)
data IOErrorType = AlreadyExists | NoSuchThing | ResourceBusy | ResourceExhausted | EOF | IllegalOperation
| PermissionDenied | UserError | UnsatisfiedConstraints | SystemError | ProtocolError | OtherError | InvalidArgument
| InappropriateType | HardwareFault | UnsupportedOperation | TimeExpired | ResourceVanished | Interrupted
| CrossingWorlds | ReadDeadlock | AcceptDeadlock
deriving (Eq, Typeable)
instance Show IOErrorType where
showsPrec _ e =
showString $
case e of
AlreadyExists -> "already exists"
NoSuchThing -> "does not exist"
ResourceBusy -> "resource busy"
ResourceExhausted -> "resource exhausted"
EOF -> "end of file"
IllegalOperation -> "illegal operation"
PermissionDenied -> "permission denied"
UserError -> "user error"
HardwareFault -> "hardware fault"
InappropriateType -> "inappropriate type"
Interrupted -> "interrupted"
InvalidArgument -> "invalid argument"
OtherError -> "failed"
ProtocolError -> "protocol error"
ResourceVanished -> "resource vanished"
SystemError -> "system error"
TimeExpired -> "timeout"
UnsatisfiedConstraints -> "unsatisified constraints"
UnsupportedOperation -> "unsupported operation"
CrossingWorlds -> "not of this world"
ReadDeadlock -> "read deadlock"
AcceptDeadlock -> "socket accept deadlock"
data IOException = IOError {
ioe_handle :: Maybe Handle, -- the handle used by the action flagging the error.
ioe_type :: IOErrorType, -- what it was.
ioe_location :: String, -- location.
ioe_description :: String, -- error type specific information.
ioe_errno :: Maybe CInt,
ioe_filename :: Maybe FilePath -- filename the error is related to.
} deriving (Typeable)
instance Show IOException where
showsPrec p (IOError hdl iot loc s _ fn) =
(case fn of
Nothing -> case hdl of
Nothing -> id
Just h -> showsPrec p h . showString ": "
Just name -> showString name . showString ": ") .
(case loc of
"" -> id
_ -> showString loc . showString ": ") .
showsPrec p iot .
(case s of
"" -> id
_ -> showString " (" . showString s . showString ")")
instance Exception IOException
type IOError = IOException
{- IO definition -}
newtype IO a = IO { unwrapIO :: ExceptT IOException (PauseT (State RealWorld)) a }
deriving (Functor, Applicative, MonadError IOException, Typeable)
type StdGen = R.StdGen
data RealWorld = forall u. RealWorld {
workDir :: FilePath,
files :: Map File Text,
isPermitted :: FilePath -> IOMode -> Bool,
handles :: Map Handle HandleData,
nextHandle :: Integer,
user :: User,
mvars :: Map Integer MValue,
nextMVar :: Integer,
writeHooks :: [Handle -> Text -> IO ()],
theStdGen :: StdGen,
_isUserThread :: Bool
} deriving (Typeable)
instance Monad IO where
return = IO . return
IO x >>= f = IO (x >>= (\x -> case f x of IO y -> y))
instance MonadFail IO where
fail s = ioError (userError s)
IO errors
simpleIOError :: IOErrorType -> String -> String -> IO a
simpleIOError iot loc descr = throwError (IOError Nothing iot loc descr Nothing Nothing)
hIOError :: Handle -> IOErrorType -> String -> String -> IO a
hIOError h iot loc descr = throwError (IOError (Just h) iot loc descr Nothing Nothing)
fileIOError :: FilePath -> IOErrorType -> String -> String -> IO a
fileIOError path iot loc descr = throwError (IOError Nothing iot loc descr Nothing (Just path))
ioError :: IOError -> IO a
ioError = ioException
ioException :: IOException -> IO a
ioException = throwError
throwIO :: Exception e => e -> IO a
throwIO = throw
userError :: String -> IOError
userError s = IOError Nothing UserError "" s Nothing Nothing
catchIO :: IO a -> (IOException -> IO a) -> IO a
catchIO = catchError
tryIO :: IO a -> IO (Either IOException a)
tryIO io = catchIO (fmap Right io) (return . Left)
ioeGetErrorType :: IOError -> IOErrorType
ioeGetErrorType = ioe_type
ioeGetErrorString :: IOError -> String
ioeGetErrorString ioe
| isUserError ioe = ioe_description ioe
| otherwise = show (ioe_type ioe)
ioeGetLocation :: IOError -> String
ioeGetLocation ioe = ioe_location ioe
ioeGetHandle :: IOError -> Maybe Handle
ioeGetHandle ioe = ioe_handle ioe
ioeGetFileName :: IOError -> Maybe FilePath
ioeGetFileName ioe = ioe_filename ioe
isAlreadyExistsError :: IOError -> Bool
isAlreadyExistsError = (== AlreadyExists) . ioeGetErrorType
isDoesNotExistError :: IOError -> Bool
isDoesNotExistError = (== NoSuchThing) . ioeGetErrorType
isAlreadyInUseError :: IOError -> Bool
isAlreadyInUseError = (== ResourceBusy) . ioeGetErrorType
isFullError :: IOError -> Bool
isFullError = (== ResourceExhausted) . ioeGetErrorType
isEOFError :: IOError -> Bool
isEOFError = (== EOF) . ioeGetErrorType
isIllegalOperation :: IOError -> Bool
isIllegalOperation = (== IllegalOperation) . ioeGetErrorType
isPermissionError :: IOError -> Bool
isPermissionError = (== PermissionDenied) . ioeGetErrorType
isUserError :: IOError -> Bool
isUserError = (== UserError) . ioeGetErrorType
isReadDeadlockError :: IOError -> Bool
isReadDeadlockError = (== ReadDeadlock) . ioeGetErrorType
isAcceptDeadlockError :: IOError -> Bool
isAcceptDeadlockError = (== AcceptDeadlock) . ioeGetErrorType
{- World manipulation -}
getWorld :: IO RealWorld
getWorld = IO (lift get)
getFromWorld :: (RealWorld -> a) -> IO a
getFromWorld f = IO (lift (gets f))
putWorld :: RealWorld -> IO ()
putWorld w = IO (lift (put w))
updateWorld :: (RealWorld -> RealWorld) -> IO ()
updateWorld f = IO (lift (modify f))
-- Give control back to the caller
wait :: IO ()
wait = IO pause
nop :: IO ()
nop = return ()
-- Runs an IO action until wait is called, storing the remaining action in the world using the given operation.
-- Returns True iff the action ran completely.
runIOUntilSuspend :: IO () -> (IO () -> IO ()) -> IO Bool
runIOUntilSuspend (IO c) wr =
IO (stepPauseT c) >>= either (\c -> wr (IO c) >> return False) (\_ -> wr nop >> return True)
tryEvalIO :: IO a -> RealWorld -> Either IOException a
tryEvalIO io w = fst (tryRunIO io w)
tryRunIO :: IO a -> RealWorld -> (Either IOException a, RealWorld)
tryRunIO (IO io) w = runState (runPauseT (runExceptT io)) w
runIO :: IO a -> RealWorld -> (a, RealWorld)
runIO io w = first (either (\e -> error ("Mock IO Exception: " ++ show e)) id) (tryRunIO io w)
evalIO :: IO a -> RealWorld -> a
evalIO io w = fst (runIO io w)
{- Random numbers -}
setStdGen :: StdGen -> IO ()
setStdGen sgen = updateWorld (\w -> w {theStdGen = sgen})
getStdGen :: IO StdGen
getStdGen = getFromWorld theStdGen
newStdGen :: IO StdGen
newStdGen =
do (g, g') <- liftM R.split getStdGen
setStdGen g
return g'
getStdRandom :: (StdGen -> (a,StdGen)) -> IO a
getStdRandom f =
do (x, g) <- liftM f getStdGen
setStdGen g
return x
setRandomSeed :: Int -> IO ()
setRandomSeed seed = setStdGen (R.mkStdGen seed)
{- Mutable variables -}
newEmptyMVar :: Typeable a => IO (MVar a)
newEmptyMVar =
do w <- getWorld
let id = nextMVar w
putWorld (w {nextMVar = id + 1, mvars = M.insert id MEmpty (mvars w)})
return (MVar id)
newMVar :: Typeable a => a -> IO (MVar a)
newMVar y =
do w <- getWorld
let id = nextMVar w
putWorld (w {nextMVar = id + 1, mvars = M.insert id (MValue y) (mvars w)})
return (MVar id)
tryTakeMVar :: Typeable a => MVar a -> IO (Maybe a)
tryTakeMVar (MVar x) =
do y <- fmap (M.lookup x . mvars) getWorld
case y of
Nothing -> simpleIOError CrossingWorlds "tryTakeMVar" ("Invalid MVar: " ++ show x)
Just MEmpty -> return Nothing
Just (MValue y) -> case cast y of
Nothing -> simpleIOError CrossingWorlds "tryTakeMVar" ("Invalid MVar: " ++ show x)
Just y -> return (Just y)
takeMVar :: Typeable a => MVar a -> IO a
takeMVar (MVar x) = tryTakeMVar (MVar x) >>= maybe (simpleIOError ReadDeadlock "takeMVar" ("Empty MVar: " ++ show x)) return
isEmptyMVar :: Typeable a => MVar a -> IO Bool
isEmptyMVar x = fmap (maybe True (const False)) (tryTakeMVar x)
tryReadMVar :: Typeable a => MVar a -> IO a
tryReadMVar = readMVar
readMVar :: Typeable a => MVar a -> IO a
readMVar = takeMVar
swapMVar :: Typeable a => MVar a -> a -> IO a
swapMVar x y = modifyMVar x (\y' -> return (y,y'))
modifyMVar :: Typeable a => MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar (MVar x) f =
do w <- getWorld
case M.lookup x (mvars w) of
Nothing -> simpleIOError ReadDeadlock "modifyMVar" ("Empty MVar: " ++ show x)
Just MEmpty -> simpleIOError CrossingWorlds "modifyTakeMVar" ("Invalid MVar: " ++ show x)
Just (MValue y) -> case cast y of
Nothing -> simpleIOError ReadDeadlock "modifyMVar" ("Empty MVar: " ++ show x)
Just y -> do (z,r) <- f y
putWorld (w {mvars = M.insert x (MValue z) (mvars w)})
return r
modifyMVar_ :: Typeable a => MVar a -> (a -> IO a) -> IO ()
modifyMVar_ x f = modifyMVar x (fmap (, ()) . f)
tryPutMVar :: Typeable a => MVar a -> a -> IO Bool
tryPutMVar (MVar x) y =
do w <- getWorld
putWorld (w {mvars = M.insert x (MValue y) (mvars w)})
return True
putMVar :: Typeable a => MVar a -> a -> IO ()
putMVar x y = tryPutMVar x y >> return ()
{- IO References -}
newtype IORef a = IORef {ioRefToMVar :: MVar a} deriving (Eq, Ord, Typeable)
newIORef :: Typeable a => a -> IO (IORef a)
newIORef = fmap IORef . newMVar
readIORef :: Typeable a => IORef a -> IO a
readIORef (IORef v) = takeMVar v
writeIORef :: Typeable a => IORef a -> a -> IO ()
writeIORef (IORef v) x = putMVar v x
modifyIORef :: Typeable a => IORef a -> (a -> a) -> IO ()
modifyIORef (IORef v) f = modifyMVar_ v (return . f)
modifyIORef' :: Typeable a => IORef a -> (a -> a) -> IO ()
modifyIORef' (IORef v) f = modifyMVar_ v (\x -> let y = f x in y `seq` return y)
atomicModifyIORef :: Typeable a => IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef (IORef v) f = modifyMVar v (return . f)
atomicModifyIORef' :: Typeable a => IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' (IORef v) f = modifyMVar v (\x -> case f x of (y, z) -> y `seq` z `seq` return (y, z))
atomicWriteIORef :: Typeable a => IORef a -> a -> IO ()
atomicWriteIORef = writeIORef
{- Write Hooks -}
registerWriteHook :: (Handle -> Text -> IO ()) -> IO ()
registerWriteHook h = updateWorld (\w -> w {writeHooks = h : writeHooks w})
{- The User -}
setUser :: User -> IO ()
setUser = putUser
putUser :: User -> IO ()
putUser u = updateWorld (\w -> w {user = u})
defaultUser :: User
defaultUser = nop
reverseSpecialHandles :: IO ()
reverseSpecialHandles = updateWorld (\w -> w { handles = let hs = handles w in M.union (M.fromList (f hs)) hs})
where f hs = zip specialHandles (map (fromJust . flip M.lookup hs) (drop 3 (cycle specialHandles)))
runUser :: IO Bool
runUser =
do u <- getFromWorld user
reverseSpecialHandles
updateWorld (\w -> w {_isUserThread = True})
b <- runIOUntilSuspend u putUser
updateWorld (\w -> w {_isUserThread = False})
reverseSpecialHandles
return b
runUserCompletely :: IO ()
runUserCompletely =
do b <- runUser
when (not b) runUserCompletely
isUserThread :: IO Bool
isUserThread = getFromWorld _isUserThread
mkSpecialHandle :: Integer -> SpecialFile -> Handle
mkSpecialHandle id t = Handle id (show t) SpecialHandle (SpecialFile t) (SpecialFile t)
specialHandles@[stdin, stdout, stderr, usrStdin, usrStdout, usrStderr] =
zipWith mkSpecialHandle [-1,-2..] [StdIn, StdOut, StdErr, StdIn, StdOut, StdErr]
reverseSpecialHandle :: Integer -> Handle
reverseSpecialHandle i = cycle specialHandles `genericIndex` (2 - i)
newWorld :: FilePath -> [(FilePath, Text)] -> (FilePath -> IOMode -> Bool) -> RealWorld
newWorld workDir files permitted =
RealWorld {
workDir = workDir,
files = M.fromList ([(SpecialFile t, "") | t <- [StdIn, StdOut, StdErr]] ++
[(RegularFile path, content) | (path, content) <- files]),
isPermitted = permitted,
nextHandle = 0,
nextMVar = 0,
handles = M.fromList [(stdin, HandleData ReadMode True False LineBuffering 0 0),
(stdout, HandleData AppendMode True False LineBuffering 0 0),
(stderr, HandleData AppendMode True False LineBuffering 0 0),
(usrStdin, HandleData WriteMode True False LineBuffering 0 0),
(usrStdout, HandleData ReadMode True False LineBuffering 0 0),
(usrStderr, HandleData ReadMode True False LineBuffering 0 0)],
mvars = M.empty,
user = defaultUser,
writeHooks = [],
theStdGen = R.mkStdGen 0,
_isUserThread = False
}
emptyWorld :: RealWorld
emptyWorld = newWorld "/" [] (\_ _ -> True)
getHData :: String -> Handle -> IO HandleData
getHData s h = do d <- fmap (M.lookup h . handles) getWorld
case d of
Nothing -> hIOError h CrossingWorlds s "Invalid handle"
Just d -> return d
putHData :: Handle -> HandleData -> IO ()
putHData h d = do w <- getWorld
putWorld (w { handles = M.insert h d (handles w) })
hShow :: Handle -> IO String
hShow h =
do d <- getHData "hShow" h
let t = case _hGetMode d of
ReadMode -> "readable"
WriteMode -> "writable"
AppendMode -> "writable (append)"
ReadWriteMode -> "read-writable"
let s = if _hIsOpen d then
"{loc=" ++ show h ++ ",type=" ++ t ++ ",buffering=none}"
else
"{closed}"
return s
hIsSeekable :: Handle -> IO Bool
hIsSeekable h = fmap _hIsSeekable (getHData "hIsSeekable" h)
hIsTerminalDevice :: Handle -> IO Bool
hIsTerminalDevice h = case _hInFile h of SpecialFile t -> return (t == StdIn || t == StdOut || t == StdErr)
_ -> return False
getFileContents :: String -> File -> IO Text
getFileContents s f =
do w <- getWorld
case M.lookup f (files w) of
Nothing -> case f of
RegularFile p -> fileIOError p NoSuchThing s "No such file or directory"
_ -> simpleIOError NoSuchThing s "No such file or directory"
Just t -> return t
putFileContents :: File -> Text -> IO ()
putFileContents f t =
do w <- getWorld
putWorld (w {files = M.insert f t (files w)})
fileSize :: File -> IO Integer
fileSize f = fmap (fromIntegral . T.length) (getFileContents "fileSize" f)
type HandlePosition = Integer
data HandlePosn = HandlePosn Handle HandlePosition deriving (Typeable)
instance Eq HandlePosn where
(HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2
instance Show HandlePosn where
showsPrec p (HandlePosn h pos) =
showsPrec p h . showString " at position " . shows pos
hEnsureOpen' :: String -> Handle -> HandleData -> IO ()
hEnsureOpen' s h d =
if _hIsOpen d then return () else hIOError h IllegalOperation s "handle is closed"
hEnsureOpen :: String -> Handle -> IO ()
hEnsureOpen s h = getHData s h >>= hEnsureOpen' s h
hIsOpen :: Handle -> IO Bool
hIsOpen h = fmap _hIsOpen (getHData "hIsOpen" h)
hIsClosed :: Handle -> IO Bool
hIsClosed h = fmap _hIsOpen (getHData "hIsClosed" h)
fileExists :: RealWorld -> File -> Bool
fileExists w f = (case f of {RegularFile p -> isValidPath p; _ -> True}) && M.member f (files w)
doesFileExist :: FilePath -> IO Bool
doesFileExist p = fileExists <$> getWorld <*> mkFile p
mkPath :: FilePath -> IO FilePath
mkPath path = fmap (\w -> interpretPath (workDir w) path) getWorld
mkFile :: FilePath -> IO File
mkFile = fmap RegularFile . mkPath
mkHandle :: String -> HandleType -> (Integer -> File) -> (Integer -> File) -> IOMode -> Bool -> Integer -> IO Handle
mkHandle name t inFile outFile mode seekable pos =
do w <- getWorld
let id = nextHandle w
let h = Handle id name t (inFile id) (outFile id)
let d = HandleData mode True seekable LineBuffering pos pos
putWorld (w {nextHandle = id + 1, handles = M.insert h d (handles w)})
return h
openFile :: FilePath -> IOMode -> IO Handle
openFile path mode =
do w <- getWorld
p <- mkPath path
f <- mkFile path
if not (isPermitted w p mode) then
fileIOError path PermissionDenied "openFile" "Permission denied"
else do
let ex = fileExists w f
when (not ex) $
if mode == ReadMode then
fileIOError path NoSuchThing "openFile" "No such file or directory"
else
writeFile p ""
pos <- if mode == AppendMode then fmap (fromIntegral . T.length) (getFileContents "openFile" f) else return 0
mkHandle p RegularFileHandle (const f) (const f) mode True pos
hClose :: Handle -> IO ()
hClose h =
do d <- getHData "hClose" h
putHData h (d {_hIsOpen = False})
getOpenHandles :: IO [Handle]
getOpenHandles =
do w <- getWorld
return [h | (h, d) <- M.toList (handles w), _hIsOpen d]
withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
withFile path mode f =
do h <- openFile path mode
r <- f h
hClose h
return r
hTell :: Handle -> IO Integer
hTell h =
do d <- getHData "hTell" h
hEnsureOpen' "hTell" h d
if _hIsSeekable d then
return (fromIntegral (_hOutBufPos d))
else
hIOError h IllegalOperation "hTell" "handle is not seekable"
hFileSize :: Handle -> IO Integer
hFileSize h
| _hIsFile h =
do d <- getHData "hFileSize" h
hEnsureOpen' "hFileSize" h d
t <- getFileContents "hFileSize" (_hInFile h)
return (fromIntegral (T.length t))
| otherwise = hIOError h InappropriateType "hFileSize" "not a regular file"
hGetBuffering :: Handle -> IO BufferMode
hGetBuffering h = fmap _hBufferMode (getHData "hGetBuffering" h)
hSetBuffering :: Handle -> BufferMode -> IO ()
hSetBuffering h m = getHData "hSetBuffering" h >>= (\d -> putHData h (d { _hBufferMode = m}))
hGetPosn :: Handle -> IO HandlePosn
hGetPosn h = HandlePosn h <$> hTell h
hSetPosn :: HandlePosn -> IO ()
hSetPosn (HandlePosn h p) = hSeek h AbsoluteSeek p
hSeek :: Handle -> SeekMode -> Integer -> IO ()
hSeek h mode pos =
do d <- getHData "hSeek" h
hEnsureOpen' "hSeek" h d
when (not (_hIsSeekable d)) (hIOError h IllegalOperation "hSeek" "handle is not seekable")
t <- getFileContents "hSeek" (_hInFile h)
let size = fromIntegral (T.length t)
let pos' = case mode of
AbsoluteSeek -> fromIntegral pos
RelativeSeek -> _hOutBufPos d + fromIntegral pos
SeekFromEnd -> size - fromIntegral pos
when (pos' < 0) (hIOError h InvalidArgument "hSeek" "Invalid argument")
putHData h (d {_hInBufPos = pos', _hOutBufPos = pos'})
hIsEOF :: Handle -> IO Bool
hIsEOF h =
do d <- getHData "hIsEOF" h
hEnsureOpen' "hIsEOF" h d
t <- getFileContents "hIsEOF" (_hInFile h)
return (_hInBufPos d >= fromIntegral (T.length t))
hReady :: Handle -> IO Bool
hReady h =
do hWaitForInput h 0
fmap not (hIsEOF h)
hAvailable :: Handle -> IO Integer
hAvailable h =
do d <- getHData "hAvailable" h
hEnsureOpen' "hAvailable" h d
hEnsureReadable "hAvailable" h d
t <- getFileContents "hAvailable" (_hInFile h)
return (max 0 (fromIntegral (T.length t) - _hInBufPos d))
isEOF :: IO Bool
isEOF = hIsEOF stdin
hIsReadable :: Handle -> IO Bool
hIsReadable h = (allowsReading . _hGetMode) <$> getHData "hIsReadable" h
hIsWritable :: Handle -> IO Bool
hIsWritable h = (allowsWriting . _hGetMode) <$> getHData "hIsWritable" h
dumpHandle :: Handle -> Direction -> IO Text
dumpHandle h d =
do hEnsureOpen "dumpHandle" h
getFileContents "dumpHandle" (if d == In then _hInFile h else _hOutFile h)
_hSetFileSize :: String -> Handle -> HandleData -> Integer -> IO ()
_hSetFileSize s h d size =
do hEnsureOpen' s h d
when (not (allowsWriting (_hGetMode d))) $
if h == stdout || h == stderr then
hIOError h IllegalOperation s ("user cannot write to " ++ show h)
else
hIOError h IllegalOperation s "handle is not open for writing"
t <- getFileContents s (_hOutFile h)
let diff = fromIntegral size - fromIntegral (T.length t)
case compare diff 0 of
EQ -> return ()
GT -> putFileContents (_hOutFile h) (T.append t (T.replicate diff (T.singleton '\0')))
LT -> putFileContents (_hOutFile h) (T.take (fromIntegral size) t)
hSetFileSize :: Handle -> Integer -> IO ()
hSetFileSize h size =
do d <- getHData "hSetFileSize" h
_hSetFileSize "hSetFileSize" h d size
hPrepareWrite :: String -> Handle -> HandleData -> IO ()
hPrepareWrite s h d = _hSetFileSize s h d (_hOutBufPos d)
hPutText :: Handle -> Text -> IO ()
hPutText h s =
do d <- getHData "hPutText" h
hPrepareWrite "hPutText" h d
let l = T.length s
t <- getFileContents "hPutText" (_hOutFile h)
let t' = case T.splitAt (fromIntegral (_hOutBufPos d)) t of
(t1, t2) -> T.append t1 (T.append s (T.drop l t2))
putHData h (d {_hOutBufPos = _hOutBufPos d + fromIntegral l})
putFileContents (_hOutFile h) t'
hooks <- getFromWorld writeHooks
mapM_ (\hook -> hook h s) hooks
hPutStr :: Handle -> String -> IO ()
hPutStr h s = hPutText h (T.pack s)
hPutStrLn :: Handle -> String -> IO ()
hPutStrLn h s = hPutText h (T.pack (s ++ "\n"))
hPutChar :: Handle -> Char -> IO ()
hPutChar h c = hPutText h (T.singleton c)
hPrint :: Show a => Handle -> a -> IO ()
hPrint h x = hPutStrLn h (show x)
print :: Show a => a -> IO ()
print = hPrint stdout
putStr :: String -> IO ()
putStr = hPutStr stdout
putStrLn :: String -> IO ()
putStrLn = hPutStrLn stdout
putChar :: Char -> IO ()
putChar = hPutChar stdout
hEnsureReadable :: String -> Handle -> HandleData -> IO ()
hEnsureReadable s h d
| not (_hIsOpen d) = hIOError h IllegalOperation s "handle is closed"
| allowsReading (_hGetMode d) = return ()
| otherwise = if h == stdin then
hIOError h IllegalOperation s "handle is not open for reading"
else
hIOError h IllegalOperation s "user cannot read from stdin"
_hGetText :: Handle -> Integer -> IO Text
_hGetText h s =
do d <- getHData "hGetText" h
hEnsureReadable "hGetText" h d
t <- getFileContents "hGetText" (_hInFile h)
if _hInBufPos d + fromIntegral s > fromIntegral (T.length t) then
hIOError h EOF "hGetText" ""
else do
let t' = T.take (fromIntegral s) (T.drop (fromIntegral (_hInBufPos d)) t)
putHData h (d {_hInBufPos = _hInBufPos d + fromIntegral s})
return t'
_hLookAhead :: Handle -> IO Char
_hLookAhead h =
do d <- getHData "hLookAhead" h
hEnsureReadable "hLookAhead" h d
t <- getFileContents "hLookAhead" (_hInFile h)
if _hInBufPos d >= fromIntegral (T.length t) then
hIOError h EOF "hLookAhead" ""
else
return (T.index t (fromIntegral (_hInBufPos d)))
hGetChar :: Handle -> IO Char
hGetChar h = fmap T.head (hGetText h 1)
hGetContentText :: Handle -> IO Text
hGetContentText h = do {t <- aux; hClose h; return t}
where aux =
do res <- wrapBlockingOp' "hGetContexts" op h
case res of
Just t | not (T.null t) -> fmap (T.append t) (hGetContentText h)
_ -> return T.empty
op h =
do d <- getHData "hGetContexts" h
hEnsureReadable "hGetContents" h d
t <- getFileContents "hGetContents" (_hInFile h)
let t' = T.drop (fromIntegral (_hInBufPos d)) t
putHData h (d {_hInBufPos = _hInBufPos d + fromIntegral (T.length t')})
return t'
_hGetLineText :: Handle -> IO Text
_hGetLineText h =
do d <- getHData "hGetLine" h
hEnsureReadable "hGetLine" h d
t <- getFileContents "hGetLine" (_hInFile h)
if _hInBufPos d >= fromIntegral (T.length t) then
hIOError h EOF "hGetLine" ""
else do
let (t1, t2) = T.span (/= '\n') (T.drop (fromIntegral (_hInBufPos d)) t)
let s = fromIntegral (T.length t1) + (if T.isPrefixOf "\n" t2 then 1 else 0)
putHData h (d {_hInBufPos = _hInBufPos d + s})
return t1
hGetLine :: Handle -> IO String
hGetLine h = fmap T.unpack (hGetLineText h)
readFileText :: FilePath -> IO Text
readFileText path =
do w <- getWorld
p <- mkPath path
f <- mkFile path
if not (isPermitted w p ReadMode) then
fileIOError path PermissionDenied "openFile" "Permission denied"
else
mkFile path >>= getFileContents "openFile"
readFile :: FilePath -> IO String
readFile = fmap T.unpack . readFileText
writeFileText :: FilePath -> Text -> IO ()
writeFileText path t =
do w <- getWorld
p <- mkPath path
f <- mkFile path
if not (isPermitted w p WriteMode) then
fileIOError path PermissionDenied "openFile" "Permission denied"
else do
f <- mkFile path
putFileContents f t
writeFile :: FilePath -> String -> IO()
writeFile path t = writeFileText path (T.pack t)
appendFileText :: FilePath -> Text -> IO ()
appendFileText path t =
do w <- getWorld
p <- mkPath path
f <- mkFile path
if not (isPermitted w p AppendMode) then
fileIOError path PermissionDenied "openFile" "Permission denied"
else do
f <- mkFile path
w <- getWorld
case M.lookup f (files w) of
Nothing -> putFileContents f t
Just t' -> putFileContents f (T.append t' t)
appendFile :: FilePath -> String -> IO()
appendFile path t = appendFileText path (T.pack t)
readIO :: Read a => String -> IO a
readIO s = case (do { (x,t) <- reads s ;
("","") <- lex t ;
return x }) of
[x] -> return x
[] -> ioError (userError "Prelude.readIO: no parse")
_ -> ioError (userError "Prelude.readIO: ambiguous parse")
_hCanBlock :: Handle -> Bool
_hCanBlock h = h == stdin
wrapBlockingOp' :: String -> (Handle -> IO a) -> Handle -> IO (Maybe a)
wrapBlockingOp' s op h
| h == stdin || h == stdout =
do getHData s h >>= hEnsureReadable s h -- make sure this is not the user trying to getLine or something like that
hEnsureOpen s h
eof <- hIsEOF h
if not eof then fmap Just (op h) else do
if h == stdin then void runUser else wait
eof <- hIsEOF h
if eof then return Nothing else fmap Just (op h)
| otherwise = fmap Just (op h)
wrapBlockingOp :: String -> (Handle -> IO a) -> Handle -> IO a
wrapBlockingOp s op h = wrapBlockingOp' s op h >>= maybe (hIOError h ReadDeadlock s msg) return
where msg = if h == stdin then
"user input expected, but user does not respond"
else if h == stdout then
"IO thread expects user input, user expects IO output"
else
"the impossible happened"
hWaitForInput :: Handle -> Int -> IO Bool
hWaitForInput h _ = getHData "hWaitForInput" h >>= hEnsureReadable "hWaitForInput" h >>
fmap (maybe False (const True)) (wrapBlockingOp' "hWaitForInput" (const (return ())) h)
getText :: Integer -> IO Text
getText = hGetText stdin
getChar :: IO Char
getChar = hGetChar stdin
getLineText :: IO Text
getLineText = hGetLineText stdin
getLine :: IO String
getLine = hGetLine stdin
lookAhead :: IO Char
lookAhead = hLookAhead stdin
hGetText :: Handle -> Integer -> IO Text
hGetText h s = wrapBlockingOp "hGetText" (\h -> _hGetText h s) h
hLookAhead :: Handle -> IO Char
hLookAhead = wrapBlockingOp "hLookAhead" _hLookAhead
hGetLineText :: Handle -> IO Text
hGetLineText = wrapBlockingOp "hGetLine" _hGetLineText
readLn :: Read a => IO a
readLn = getLine >>= readIO
getContentText :: IO Text
getContentText = hGetContentText stdin
hGetContents :: Handle -> IO String
hGetContents h = fmap T.unpack (hGetContentText h)
getContents :: IO String
getContents = fmap T.unpack getContentText
interact :: (String -> String) -> IO ()
interact f =
do b <- isUserThread
if b then
wait
else do
void runUser
eof <- isEOF
if eof then return () else do
s <- getLine
putStrLn (f (s ++ "\n"))
interact f
hFlush :: Handle -> IO ()
hFlush _ = return ()
newtype ConsoleHook = ConsoleHook (MVar [(SpecialFile, Text)]) deriving (Typeable)
hookConsole :: IO ConsoleHook
hookConsole =
do v <- newMVar []
registerWriteHook (hook v)
return (ConsoleHook v)
where hook v h t = case _hOutFile h of
SpecialFile special -> modifyMVar_ v (\xs -> return ((special, t) : xs))
_ -> return ()
readConsoleHook :: ConsoleHook -> IO [(SpecialFile, Text)]
readConsoleHook (ConsoleHook v) = fmap reverse (readMVar v)
showConsoleHook :: ConsoleHook -> IO String
showConsoleHook h = fmap (T.unpack . T.unlines . format) (readConsoleHook h)
where format = map (\xs -> formatLine (fst (head xs)) (T.lines (T.concat (map snd xs)))) . groupBy ((==) `on` fst)
formatLine t xs = T.intercalate nl (map (T.append (prefix t)) xs)
nl = T.pack "\n"
prefix StdIn = "> "
prefix StdOut = ""
prefix StdErr = "ERR: "
newtype HandleHook = HandleHook (MVar [(Direction, Text)]) deriving (Typeable)
hookHandle :: Handle -> IO HandleHook
hookHandle h =
do v <- newMVar []
registerWriteHook (hook v)
return (HandleHook v)
where hook v h' t = if _hOutFile h' == _hOutFile h then
modifyMVar_ v (\xs -> return ((Out, t) : xs))
else if _hOutFile h' == _hInFile h then
modifyMVar_ v (\xs -> return ((In, t) : xs))
else
return ()
readHandleHook :: HandleHook -> IO [(Direction, Text)]
readHandleHook (HandleHook v) = fmap reverse (readMVar v)
showHandleHook :: HandleHook -> IO String
showHandleHook h = fmap (T.unpack . T.unlines . format) (readHandleHook h)
where format = map (\xs -> formatLine (fst (head xs)) (T.lines (T.concat (map snd xs)))) . groupBy ((==) `on` fst)
formatLine t xs = T.intercalate nl (map (T.append (prefix t)) xs)
nl = T.pack "\n"
prefix In = "<< "
prefix Out = ">> "
| null | https://raw.githubusercontent.com/kappelmann/engaging-large-scale-functional-programming/99d8b76902320fd8f2d0999bbc9b2a82da09bc72/resources/turtle_graphics/mock/Mock/System/IO/Internal.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE PackageImports #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE DoAndIfThenElse #
the handle used by the action flagging the error.
what it was.
location.
error type specific information.
filename the error is related to.
IO definition
World manipulation
Give control back to the caller
Runs an IO action until wait is called, storing the remaining action in the world using the given operation.
Returns True iff the action ran completely.
Random numbers
Mutable variables
IO References
Write Hooks
The User
make sure this is not the user trying to getLine or something like that | # LANGUAGE Unsafe #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE ExistentialQuantification #
# LANGUAGE RecordWildCards #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE TupleSections #
# LANGUAGE StandaloneDeriving #
module Mock.System.IO.Internal (
IO, MVar, IORef, Handle, IOMode (..), SeekMode (..), FilePath, HandlePosn (..), Direction (In, Out), SpecialFile (..),
IOException (..), IOErrorType (..), ConsoleHook, HandleHook, BufferMode (..),
RealWorld (RealWorld, handles, files, workDir, isPermitted),
newWorld, emptyWorld, setUser, runIO, evalIO, tryRunIO, tryEvalIO, stdin, stdout, stderr, runUser, runUserCompletely,
newMVar, newEmptyMVar, isEmptyMVar, tryTakeMVar, takeMVar, tryPutMVar, tryReadMVar, readMVar, putMVar, swapMVar, modifyMVar, modifyMVar_,
newIORef, readIORef, writeIORef, modifyIORef, modifyIORef', atomicModifyIORef, atomicModifyIORef', atomicWriteIORef,
withFile, openFile, hClose, readFile, writeFile, appendFile, doesFileExist,
hFileSize, hSetFileSize, hIsEOF, isEOF, hGetBuffering, hSetBuffering, hFlush,
hGetPosn, hSetPosn, hSeek, hTell, hReady, hAvailable, hWaitForInput,
hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable, hIsTerminalDevice, hShow,
hGetChar, hGetLine, hLookAhead, hGetContents,
hPutChar, hPutStr, hPutStrLn, hPrint,
putChar, putStr, putStrLn, print,
getChar, getLine, getContents, readIO, readLn, interact,
dumpHandle, getOpenHandles,wait,
ioError, ioException, userError, tryIO, catchIO,
registerWriteHook, hookConsole, readConsoleHook, showConsoleHook, hookHandle, readHandleHook, showHandleHook,
isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError, isFullError, isEOFError, isIllegalOperation,
isPermissionError, isUserError, ioeGetErrorType, ioeGetLocation, ioeGetErrorString, ioeGetHandle, ioeGetFileName,
isReadDeadlockError, isAcceptDeadlockError,
R.RandomGen(R.next, R.split, R.genRange), StdGen, R.mkStdGen, getStdRandom, getStdGen, setStdGen,
newStdGen, setRandomSeed
) where
import "base" Prelude hiding (FilePath, IO, getLine, getChar, readIO, readLn, putStr, putStrLn, putChar, print,
readFile, writeFile, appendFile, getContents, interact, userError, ioError, IOError)
import qualified "random" System.Random as R
import Control.Arrow
import Control.Applicative
import Control.Exception hiding (Deadlock, ioError, IOException, IOError)
import Control.Monad
import Control.Monad.Cont
import Control.Monad.State.Strict
import Control.Monad.Pause
import Control.Monad.Except
import Data.Function
import qualified Data.Text.Lazy as T
import Data.Text.Lazy (Text)
import qualified Data.Map.Strict as M
import Data.Map.Strict (Map)
import Data.Maybe
import Data.Ord
import Data.List.Split
import Data.List
import Data.Typeable
import Foreign.C.Types
type FilePath = String
interpretPath :: FilePath -> FilePath -> FilePath
interpretPath p1 p2 = normalizePath $ if head p2 == '/' then p2 else p1 ++ "/" ++ p2
isValidPath :: FilePath -> Bool
isValidPath "" = False
isValidPath p = all (== '/') p || last p /= '/'
normalizePath :: FilePath -> FilePath
normalizePath p
| abs p = fromPartsAbs (normAbs parts [])
| otherwise = fromPartsRel (normRel parts [])
where
abs ('/':_) = True
abs _ = False
parts = filter (not . null) $ filter (/= ".") $ splitOn "/" $ p
fromPartsAbs p = "/" ++ intercalate "/" p
fromPartsRel p = if null p then "." else intercalate "/" p
normAbs [] as = reverse as
normAbs (".." : ps) [] = normAbs ps []
normAbs (".." : ps) (a : as) = normAbs ps as
normAbs (p : ps) as = normAbs ps (p : as)
normRel [] as = reverse as
normRel (".." : ps) [] = normRel ps [".."]
normRel (".." : ps) (a : as)
| a /= ".." = normRel ps as
normRel (p : ps) as = normRel ps (p : as)
data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode deriving (Show, Eq, Ord, Read, Enum, Typeable)
data SeekMode = AbsoluteSeek | RelativeSeek | SeekFromEnd deriving (Show, Eq, Ord, Read, Enum, Typeable)
allowsReading :: IOMode -> Bool
allowsReading m = m == ReadMode || m == ReadWriteMode
allowsWriting :: IOMode -> Bool
allowsWriting m = m /= ReadMode
data SpecialFile = StdIn | StdOut | StdErr deriving (Eq, Ord, Typeable)
instance Show SpecialFile where
show StdIn = "<stdin>"
show StdOut = "<stdout>"
show StdErr = "<stderr>"
data Direction = In | Out deriving (Eq, Ord, Show, Typeable)
data File = RegularFile FilePath | SpecialFile SpecialFile deriving (Eq, Ord, Typeable)
instance Show File where
show (RegularFile p) = p
show (SpecialFile t) = show t
data HandleType = SpecialHandle | RegularFileHandle deriving (Show, Eq, Ord)
data Handle = Handle {_hId :: Integer, _hName :: String, _hType :: HandleType,
_hInFile :: File, _hOutFile :: File} deriving (Typeable)
instance Eq Handle where
(==) = (==) `on` _hId
instance Ord Handle where
compare = comparing _hId
instance Show Handle where
show = _hName
data BufferMode = NoBuffering | LineBuffering | BlockBuffering (Maybe Int) deriving (Eq, Ord, Read, Show, Typeable)
data HandleData = HandleData {
_hGetMode :: IOMode,
_hIsOpen :: Bool,
_hIsSeekable :: Bool,
_hBufferMode :: BufferMode,
_hInBufPos :: Integer,
_hOutBufPos :: Integer
} deriving (Typeable)
_hIsFile :: Handle -> Bool
_hIsFile h = case _hInFile h of {RegularFile _ -> True; _ -> False}
type User = IO ()
data MVar a = MVar Integer deriving (Eq, Ord, Typeable)
data MValue = MEmpty | forall a. Typeable a => MValue a deriving (Typeable)
data IOErrorType = AlreadyExists | NoSuchThing | ResourceBusy | ResourceExhausted | EOF | IllegalOperation
| PermissionDenied | UserError | UnsatisfiedConstraints | SystemError | ProtocolError | OtherError | InvalidArgument
| InappropriateType | HardwareFault | UnsupportedOperation | TimeExpired | ResourceVanished | Interrupted
| CrossingWorlds | ReadDeadlock | AcceptDeadlock
deriving (Eq, Typeable)
instance Show IOErrorType where
showsPrec _ e =
showString $
case e of
AlreadyExists -> "already exists"
NoSuchThing -> "does not exist"
ResourceBusy -> "resource busy"
ResourceExhausted -> "resource exhausted"
EOF -> "end of file"
IllegalOperation -> "illegal operation"
PermissionDenied -> "permission denied"
UserError -> "user error"
HardwareFault -> "hardware fault"
InappropriateType -> "inappropriate type"
Interrupted -> "interrupted"
InvalidArgument -> "invalid argument"
OtherError -> "failed"
ProtocolError -> "protocol error"
ResourceVanished -> "resource vanished"
SystemError -> "system error"
TimeExpired -> "timeout"
UnsatisfiedConstraints -> "unsatisified constraints"
UnsupportedOperation -> "unsupported operation"
CrossingWorlds -> "not of this world"
ReadDeadlock -> "read deadlock"
AcceptDeadlock -> "socket accept deadlock"
data IOException = IOError {
ioe_errno :: Maybe CInt,
} deriving (Typeable)
instance Show IOException where
showsPrec p (IOError hdl iot loc s _ fn) =
(case fn of
Nothing -> case hdl of
Nothing -> id
Just h -> showsPrec p h . showString ": "
Just name -> showString name . showString ": ") .
(case loc of
"" -> id
_ -> showString loc . showString ": ") .
showsPrec p iot .
(case s of
"" -> id
_ -> showString " (" . showString s . showString ")")
instance Exception IOException
type IOError = IOException
newtype IO a = IO { unwrapIO :: ExceptT IOException (PauseT (State RealWorld)) a }
deriving (Functor, Applicative, MonadError IOException, Typeable)
type StdGen = R.StdGen
data RealWorld = forall u. RealWorld {
workDir :: FilePath,
files :: Map File Text,
isPermitted :: FilePath -> IOMode -> Bool,
handles :: Map Handle HandleData,
nextHandle :: Integer,
user :: User,
mvars :: Map Integer MValue,
nextMVar :: Integer,
writeHooks :: [Handle -> Text -> IO ()],
theStdGen :: StdGen,
_isUserThread :: Bool
} deriving (Typeable)
instance Monad IO where
return = IO . return
IO x >>= f = IO (x >>= (\x -> case f x of IO y -> y))
instance MonadFail IO where
fail s = ioError (userError s)
IO errors
simpleIOError :: IOErrorType -> String -> String -> IO a
simpleIOError iot loc descr = throwError (IOError Nothing iot loc descr Nothing Nothing)
hIOError :: Handle -> IOErrorType -> String -> String -> IO a
hIOError h iot loc descr = throwError (IOError (Just h) iot loc descr Nothing Nothing)
fileIOError :: FilePath -> IOErrorType -> String -> String -> IO a
fileIOError path iot loc descr = throwError (IOError Nothing iot loc descr Nothing (Just path))
ioError :: IOError -> IO a
ioError = ioException
ioException :: IOException -> IO a
ioException = throwError
throwIO :: Exception e => e -> IO a
throwIO = throw
userError :: String -> IOError
userError s = IOError Nothing UserError "" s Nothing Nothing
catchIO :: IO a -> (IOException -> IO a) -> IO a
catchIO = catchError
tryIO :: IO a -> IO (Either IOException a)
tryIO io = catchIO (fmap Right io) (return . Left)
ioeGetErrorType :: IOError -> IOErrorType
ioeGetErrorType = ioe_type
ioeGetErrorString :: IOError -> String
ioeGetErrorString ioe
| isUserError ioe = ioe_description ioe
| otherwise = show (ioe_type ioe)
ioeGetLocation :: IOError -> String
ioeGetLocation ioe = ioe_location ioe
ioeGetHandle :: IOError -> Maybe Handle
ioeGetHandle ioe = ioe_handle ioe
ioeGetFileName :: IOError -> Maybe FilePath
ioeGetFileName ioe = ioe_filename ioe
isAlreadyExistsError :: IOError -> Bool
isAlreadyExistsError = (== AlreadyExists) . ioeGetErrorType
isDoesNotExistError :: IOError -> Bool
isDoesNotExistError = (== NoSuchThing) . ioeGetErrorType
isAlreadyInUseError :: IOError -> Bool
isAlreadyInUseError = (== ResourceBusy) . ioeGetErrorType
isFullError :: IOError -> Bool
isFullError = (== ResourceExhausted) . ioeGetErrorType
isEOFError :: IOError -> Bool
isEOFError = (== EOF) . ioeGetErrorType
isIllegalOperation :: IOError -> Bool
isIllegalOperation = (== IllegalOperation) . ioeGetErrorType
isPermissionError :: IOError -> Bool
isPermissionError = (== PermissionDenied) . ioeGetErrorType
isUserError :: IOError -> Bool
isUserError = (== UserError) . ioeGetErrorType
isReadDeadlockError :: IOError -> Bool
isReadDeadlockError = (== ReadDeadlock) . ioeGetErrorType
isAcceptDeadlockError :: IOError -> Bool
isAcceptDeadlockError = (== AcceptDeadlock) . ioeGetErrorType
getWorld :: IO RealWorld
getWorld = IO (lift get)
getFromWorld :: (RealWorld -> a) -> IO a
getFromWorld f = IO (lift (gets f))
putWorld :: RealWorld -> IO ()
putWorld w = IO (lift (put w))
updateWorld :: (RealWorld -> RealWorld) -> IO ()
updateWorld f = IO (lift (modify f))
wait :: IO ()
wait = IO pause
nop :: IO ()
nop = return ()
runIOUntilSuspend :: IO () -> (IO () -> IO ()) -> IO Bool
runIOUntilSuspend (IO c) wr =
IO (stepPauseT c) >>= either (\c -> wr (IO c) >> return False) (\_ -> wr nop >> return True)
tryEvalIO :: IO a -> RealWorld -> Either IOException a
tryEvalIO io w = fst (tryRunIO io w)
tryRunIO :: IO a -> RealWorld -> (Either IOException a, RealWorld)
tryRunIO (IO io) w = runState (runPauseT (runExceptT io)) w
runIO :: IO a -> RealWorld -> (a, RealWorld)
runIO io w = first (either (\e -> error ("Mock IO Exception: " ++ show e)) id) (tryRunIO io w)
evalIO :: IO a -> RealWorld -> a
evalIO io w = fst (runIO io w)
setStdGen :: StdGen -> IO ()
setStdGen sgen = updateWorld (\w -> w {theStdGen = sgen})
getStdGen :: IO StdGen
getStdGen = getFromWorld theStdGen
newStdGen :: IO StdGen
newStdGen =
do (g, g') <- liftM R.split getStdGen
setStdGen g
return g'
getStdRandom :: (StdGen -> (a,StdGen)) -> IO a
getStdRandom f =
do (x, g) <- liftM f getStdGen
setStdGen g
return x
setRandomSeed :: Int -> IO ()
setRandomSeed seed = setStdGen (R.mkStdGen seed)
newEmptyMVar :: Typeable a => IO (MVar a)
newEmptyMVar =
do w <- getWorld
let id = nextMVar w
putWorld (w {nextMVar = id + 1, mvars = M.insert id MEmpty (mvars w)})
return (MVar id)
newMVar :: Typeable a => a -> IO (MVar a)
newMVar y =
do w <- getWorld
let id = nextMVar w
putWorld (w {nextMVar = id + 1, mvars = M.insert id (MValue y) (mvars w)})
return (MVar id)
tryTakeMVar :: Typeable a => MVar a -> IO (Maybe a)
tryTakeMVar (MVar x) =
do y <- fmap (M.lookup x . mvars) getWorld
case y of
Nothing -> simpleIOError CrossingWorlds "tryTakeMVar" ("Invalid MVar: " ++ show x)
Just MEmpty -> return Nothing
Just (MValue y) -> case cast y of
Nothing -> simpleIOError CrossingWorlds "tryTakeMVar" ("Invalid MVar: " ++ show x)
Just y -> return (Just y)
takeMVar :: Typeable a => MVar a -> IO a
takeMVar (MVar x) = tryTakeMVar (MVar x) >>= maybe (simpleIOError ReadDeadlock "takeMVar" ("Empty MVar: " ++ show x)) return
isEmptyMVar :: Typeable a => MVar a -> IO Bool
isEmptyMVar x = fmap (maybe True (const False)) (tryTakeMVar x)
tryReadMVar :: Typeable a => MVar a -> IO a
tryReadMVar = readMVar
readMVar :: Typeable a => MVar a -> IO a
readMVar = takeMVar
swapMVar :: Typeable a => MVar a -> a -> IO a
swapMVar x y = modifyMVar x (\y' -> return (y,y'))
modifyMVar :: Typeable a => MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar (MVar x) f =
do w <- getWorld
case M.lookup x (mvars w) of
Nothing -> simpleIOError ReadDeadlock "modifyMVar" ("Empty MVar: " ++ show x)
Just MEmpty -> simpleIOError CrossingWorlds "modifyTakeMVar" ("Invalid MVar: " ++ show x)
Just (MValue y) -> case cast y of
Nothing -> simpleIOError ReadDeadlock "modifyMVar" ("Empty MVar: " ++ show x)
Just y -> do (z,r) <- f y
putWorld (w {mvars = M.insert x (MValue z) (mvars w)})
return r
modifyMVar_ :: Typeable a => MVar a -> (a -> IO a) -> IO ()
modifyMVar_ x f = modifyMVar x (fmap (, ()) . f)
tryPutMVar :: Typeable a => MVar a -> a -> IO Bool
tryPutMVar (MVar x) y =
do w <- getWorld
putWorld (w {mvars = M.insert x (MValue y) (mvars w)})
return True
putMVar :: Typeable a => MVar a -> a -> IO ()
putMVar x y = tryPutMVar x y >> return ()
newtype IORef a = IORef {ioRefToMVar :: MVar a} deriving (Eq, Ord, Typeable)
newIORef :: Typeable a => a -> IO (IORef a)
newIORef = fmap IORef . newMVar
readIORef :: Typeable a => IORef a -> IO a
readIORef (IORef v) = takeMVar v
writeIORef :: Typeable a => IORef a -> a -> IO ()
writeIORef (IORef v) x = putMVar v x
modifyIORef :: Typeable a => IORef a -> (a -> a) -> IO ()
modifyIORef (IORef v) f = modifyMVar_ v (return . f)
modifyIORef' :: Typeable a => IORef a -> (a -> a) -> IO ()
modifyIORef' (IORef v) f = modifyMVar_ v (\x -> let y = f x in y `seq` return y)
atomicModifyIORef :: Typeable a => IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef (IORef v) f = modifyMVar v (return . f)
atomicModifyIORef' :: Typeable a => IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' (IORef v) f = modifyMVar v (\x -> case f x of (y, z) -> y `seq` z `seq` return (y, z))
atomicWriteIORef :: Typeable a => IORef a -> a -> IO ()
atomicWriteIORef = writeIORef
registerWriteHook :: (Handle -> Text -> IO ()) -> IO ()
registerWriteHook h = updateWorld (\w -> w {writeHooks = h : writeHooks w})
setUser :: User -> IO ()
setUser = putUser
putUser :: User -> IO ()
putUser u = updateWorld (\w -> w {user = u})
defaultUser :: User
defaultUser = nop
reverseSpecialHandles :: IO ()
reverseSpecialHandles = updateWorld (\w -> w { handles = let hs = handles w in M.union (M.fromList (f hs)) hs})
where f hs = zip specialHandles (map (fromJust . flip M.lookup hs) (drop 3 (cycle specialHandles)))
runUser :: IO Bool
runUser =
do u <- getFromWorld user
reverseSpecialHandles
updateWorld (\w -> w {_isUserThread = True})
b <- runIOUntilSuspend u putUser
updateWorld (\w -> w {_isUserThread = False})
reverseSpecialHandles
return b
runUserCompletely :: IO ()
runUserCompletely =
do b <- runUser
when (not b) runUserCompletely
isUserThread :: IO Bool
isUserThread = getFromWorld _isUserThread
mkSpecialHandle :: Integer -> SpecialFile -> Handle
mkSpecialHandle id t = Handle id (show t) SpecialHandle (SpecialFile t) (SpecialFile t)
specialHandles@[stdin, stdout, stderr, usrStdin, usrStdout, usrStderr] =
zipWith mkSpecialHandle [-1,-2..] [StdIn, StdOut, StdErr, StdIn, StdOut, StdErr]
reverseSpecialHandle :: Integer -> Handle
reverseSpecialHandle i = cycle specialHandles `genericIndex` (2 - i)
newWorld :: FilePath -> [(FilePath, Text)] -> (FilePath -> IOMode -> Bool) -> RealWorld
newWorld workDir files permitted =
RealWorld {
workDir = workDir,
files = M.fromList ([(SpecialFile t, "") | t <- [StdIn, StdOut, StdErr]] ++
[(RegularFile path, content) | (path, content) <- files]),
isPermitted = permitted,
nextHandle = 0,
nextMVar = 0,
handles = M.fromList [(stdin, HandleData ReadMode True False LineBuffering 0 0),
(stdout, HandleData AppendMode True False LineBuffering 0 0),
(stderr, HandleData AppendMode True False LineBuffering 0 0),
(usrStdin, HandleData WriteMode True False LineBuffering 0 0),
(usrStdout, HandleData ReadMode True False LineBuffering 0 0),
(usrStderr, HandleData ReadMode True False LineBuffering 0 0)],
mvars = M.empty,
user = defaultUser,
writeHooks = [],
theStdGen = R.mkStdGen 0,
_isUserThread = False
}
emptyWorld :: RealWorld
emptyWorld = newWorld "/" [] (\_ _ -> True)
getHData :: String -> Handle -> IO HandleData
getHData s h = do d <- fmap (M.lookup h . handles) getWorld
case d of
Nothing -> hIOError h CrossingWorlds s "Invalid handle"
Just d -> return d
putHData :: Handle -> HandleData -> IO ()
putHData h d = do w <- getWorld
putWorld (w { handles = M.insert h d (handles w) })
hShow :: Handle -> IO String
hShow h =
do d <- getHData "hShow" h
let t = case _hGetMode d of
ReadMode -> "readable"
WriteMode -> "writable"
AppendMode -> "writable (append)"
ReadWriteMode -> "read-writable"
let s = if _hIsOpen d then
"{loc=" ++ show h ++ ",type=" ++ t ++ ",buffering=none}"
else
"{closed}"
return s
hIsSeekable :: Handle -> IO Bool
hIsSeekable h = fmap _hIsSeekable (getHData "hIsSeekable" h)
hIsTerminalDevice :: Handle -> IO Bool
hIsTerminalDevice h = case _hInFile h of SpecialFile t -> return (t == StdIn || t == StdOut || t == StdErr)
_ -> return False
getFileContents :: String -> File -> IO Text
getFileContents s f =
do w <- getWorld
case M.lookup f (files w) of
Nothing -> case f of
RegularFile p -> fileIOError p NoSuchThing s "No such file or directory"
_ -> simpleIOError NoSuchThing s "No such file or directory"
Just t -> return t
putFileContents :: File -> Text -> IO ()
putFileContents f t =
do w <- getWorld
putWorld (w {files = M.insert f t (files w)})
fileSize :: File -> IO Integer
fileSize f = fmap (fromIntegral . T.length) (getFileContents "fileSize" f)
type HandlePosition = Integer
data HandlePosn = HandlePosn Handle HandlePosition deriving (Typeable)
instance Eq HandlePosn where
(HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2
instance Show HandlePosn where
showsPrec p (HandlePosn h pos) =
showsPrec p h . showString " at position " . shows pos
hEnsureOpen' :: String -> Handle -> HandleData -> IO ()
hEnsureOpen' s h d =
if _hIsOpen d then return () else hIOError h IllegalOperation s "handle is closed"
hEnsureOpen :: String -> Handle -> IO ()
hEnsureOpen s h = getHData s h >>= hEnsureOpen' s h
hIsOpen :: Handle -> IO Bool
hIsOpen h = fmap _hIsOpen (getHData "hIsOpen" h)
hIsClosed :: Handle -> IO Bool
hIsClosed h = fmap _hIsOpen (getHData "hIsClosed" h)
fileExists :: RealWorld -> File -> Bool
fileExists w f = (case f of {RegularFile p -> isValidPath p; _ -> True}) && M.member f (files w)
doesFileExist :: FilePath -> IO Bool
doesFileExist p = fileExists <$> getWorld <*> mkFile p
mkPath :: FilePath -> IO FilePath
mkPath path = fmap (\w -> interpretPath (workDir w) path) getWorld
mkFile :: FilePath -> IO File
mkFile = fmap RegularFile . mkPath
mkHandle :: String -> HandleType -> (Integer -> File) -> (Integer -> File) -> IOMode -> Bool -> Integer -> IO Handle
mkHandle name t inFile outFile mode seekable pos =
do w <- getWorld
let id = nextHandle w
let h = Handle id name t (inFile id) (outFile id)
let d = HandleData mode True seekable LineBuffering pos pos
putWorld (w {nextHandle = id + 1, handles = M.insert h d (handles w)})
return h
openFile :: FilePath -> IOMode -> IO Handle
openFile path mode =
do w <- getWorld
p <- mkPath path
f <- mkFile path
if not (isPermitted w p mode) then
fileIOError path PermissionDenied "openFile" "Permission denied"
else do
let ex = fileExists w f
when (not ex) $
if mode == ReadMode then
fileIOError path NoSuchThing "openFile" "No such file or directory"
else
writeFile p ""
pos <- if mode == AppendMode then fmap (fromIntegral . T.length) (getFileContents "openFile" f) else return 0
mkHandle p RegularFileHandle (const f) (const f) mode True pos
hClose :: Handle -> IO ()
hClose h =
do d <- getHData "hClose" h
putHData h (d {_hIsOpen = False})
getOpenHandles :: IO [Handle]
getOpenHandles =
do w <- getWorld
return [h | (h, d) <- M.toList (handles w), _hIsOpen d]
withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
withFile path mode f =
do h <- openFile path mode
r <- f h
hClose h
return r
hTell :: Handle -> IO Integer
hTell h =
do d <- getHData "hTell" h
hEnsureOpen' "hTell" h d
if _hIsSeekable d then
return (fromIntegral (_hOutBufPos d))
else
hIOError h IllegalOperation "hTell" "handle is not seekable"
hFileSize :: Handle -> IO Integer
hFileSize h
| _hIsFile h =
do d <- getHData "hFileSize" h
hEnsureOpen' "hFileSize" h d
t <- getFileContents "hFileSize" (_hInFile h)
return (fromIntegral (T.length t))
| otherwise = hIOError h InappropriateType "hFileSize" "not a regular file"
hGetBuffering :: Handle -> IO BufferMode
hGetBuffering h = fmap _hBufferMode (getHData "hGetBuffering" h)
hSetBuffering :: Handle -> BufferMode -> IO ()
hSetBuffering h m = getHData "hSetBuffering" h >>= (\d -> putHData h (d { _hBufferMode = m}))
hGetPosn :: Handle -> IO HandlePosn
hGetPosn h = HandlePosn h <$> hTell h
hSetPosn :: HandlePosn -> IO ()
hSetPosn (HandlePosn h p) = hSeek h AbsoluteSeek p
hSeek :: Handle -> SeekMode -> Integer -> IO ()
hSeek h mode pos =
do d <- getHData "hSeek" h
hEnsureOpen' "hSeek" h d
when (not (_hIsSeekable d)) (hIOError h IllegalOperation "hSeek" "handle is not seekable")
t <- getFileContents "hSeek" (_hInFile h)
let size = fromIntegral (T.length t)
let pos' = case mode of
AbsoluteSeek -> fromIntegral pos
RelativeSeek -> _hOutBufPos d + fromIntegral pos
SeekFromEnd -> size - fromIntegral pos
when (pos' < 0) (hIOError h InvalidArgument "hSeek" "Invalid argument")
putHData h (d {_hInBufPos = pos', _hOutBufPos = pos'})
hIsEOF :: Handle -> IO Bool
hIsEOF h =
do d <- getHData "hIsEOF" h
hEnsureOpen' "hIsEOF" h d
t <- getFileContents "hIsEOF" (_hInFile h)
return (_hInBufPos d >= fromIntegral (T.length t))
hReady :: Handle -> IO Bool
hReady h =
do hWaitForInput h 0
fmap not (hIsEOF h)
hAvailable :: Handle -> IO Integer
hAvailable h =
do d <- getHData "hAvailable" h
hEnsureOpen' "hAvailable" h d
hEnsureReadable "hAvailable" h d
t <- getFileContents "hAvailable" (_hInFile h)
return (max 0 (fromIntegral (T.length t) - _hInBufPos d))
isEOF :: IO Bool
isEOF = hIsEOF stdin
hIsReadable :: Handle -> IO Bool
hIsReadable h = (allowsReading . _hGetMode) <$> getHData "hIsReadable" h
hIsWritable :: Handle -> IO Bool
hIsWritable h = (allowsWriting . _hGetMode) <$> getHData "hIsWritable" h
dumpHandle :: Handle -> Direction -> IO Text
dumpHandle h d =
do hEnsureOpen "dumpHandle" h
getFileContents "dumpHandle" (if d == In then _hInFile h else _hOutFile h)
_hSetFileSize :: String -> Handle -> HandleData -> Integer -> IO ()
_hSetFileSize s h d size =
do hEnsureOpen' s h d
when (not (allowsWriting (_hGetMode d))) $
if h == stdout || h == stderr then
hIOError h IllegalOperation s ("user cannot write to " ++ show h)
else
hIOError h IllegalOperation s "handle is not open for writing"
t <- getFileContents s (_hOutFile h)
let diff = fromIntegral size - fromIntegral (T.length t)
case compare diff 0 of
EQ -> return ()
GT -> putFileContents (_hOutFile h) (T.append t (T.replicate diff (T.singleton '\0')))
LT -> putFileContents (_hOutFile h) (T.take (fromIntegral size) t)
hSetFileSize :: Handle -> Integer -> IO ()
hSetFileSize h size =
do d <- getHData "hSetFileSize" h
_hSetFileSize "hSetFileSize" h d size
hPrepareWrite :: String -> Handle -> HandleData -> IO ()
hPrepareWrite s h d = _hSetFileSize s h d (_hOutBufPos d)
hPutText :: Handle -> Text -> IO ()
hPutText h s =
do d <- getHData "hPutText" h
hPrepareWrite "hPutText" h d
let l = T.length s
t <- getFileContents "hPutText" (_hOutFile h)
let t' = case T.splitAt (fromIntegral (_hOutBufPos d)) t of
(t1, t2) -> T.append t1 (T.append s (T.drop l t2))
putHData h (d {_hOutBufPos = _hOutBufPos d + fromIntegral l})
putFileContents (_hOutFile h) t'
hooks <- getFromWorld writeHooks
mapM_ (\hook -> hook h s) hooks
hPutStr :: Handle -> String -> IO ()
hPutStr h s = hPutText h (T.pack s)
hPutStrLn :: Handle -> String -> IO ()
hPutStrLn h s = hPutText h (T.pack (s ++ "\n"))
hPutChar :: Handle -> Char -> IO ()
hPutChar h c = hPutText h (T.singleton c)
hPrint :: Show a => Handle -> a -> IO ()
hPrint h x = hPutStrLn h (show x)
print :: Show a => a -> IO ()
print = hPrint stdout
putStr :: String -> IO ()
putStr = hPutStr stdout
putStrLn :: String -> IO ()
putStrLn = hPutStrLn stdout
putChar :: Char -> IO ()
putChar = hPutChar stdout
hEnsureReadable :: String -> Handle -> HandleData -> IO ()
hEnsureReadable s h d
| not (_hIsOpen d) = hIOError h IllegalOperation s "handle is closed"
| allowsReading (_hGetMode d) = return ()
| otherwise = if h == stdin then
hIOError h IllegalOperation s "handle is not open for reading"
else
hIOError h IllegalOperation s "user cannot read from stdin"
_hGetText :: Handle -> Integer -> IO Text
_hGetText h s =
do d <- getHData "hGetText" h
hEnsureReadable "hGetText" h d
t <- getFileContents "hGetText" (_hInFile h)
if _hInBufPos d + fromIntegral s > fromIntegral (T.length t) then
hIOError h EOF "hGetText" ""
else do
let t' = T.take (fromIntegral s) (T.drop (fromIntegral (_hInBufPos d)) t)
putHData h (d {_hInBufPos = _hInBufPos d + fromIntegral s})
return t'
_hLookAhead :: Handle -> IO Char
_hLookAhead h =
do d <- getHData "hLookAhead" h
hEnsureReadable "hLookAhead" h d
t <- getFileContents "hLookAhead" (_hInFile h)
if _hInBufPos d >= fromIntegral (T.length t) then
hIOError h EOF "hLookAhead" ""
else
return (T.index t (fromIntegral (_hInBufPos d)))
hGetChar :: Handle -> IO Char
hGetChar h = fmap T.head (hGetText h 1)
hGetContentText :: Handle -> IO Text
hGetContentText h = do {t <- aux; hClose h; return t}
where aux =
do res <- wrapBlockingOp' "hGetContexts" op h
case res of
Just t | not (T.null t) -> fmap (T.append t) (hGetContentText h)
_ -> return T.empty
op h =
do d <- getHData "hGetContexts" h
hEnsureReadable "hGetContents" h d
t <- getFileContents "hGetContents" (_hInFile h)
let t' = T.drop (fromIntegral (_hInBufPos d)) t
putHData h (d {_hInBufPos = _hInBufPos d + fromIntegral (T.length t')})
return t'
_hGetLineText :: Handle -> IO Text
_hGetLineText h =
do d <- getHData "hGetLine" h
hEnsureReadable "hGetLine" h d
t <- getFileContents "hGetLine" (_hInFile h)
if _hInBufPos d >= fromIntegral (T.length t) then
hIOError h EOF "hGetLine" ""
else do
let (t1, t2) = T.span (/= '\n') (T.drop (fromIntegral (_hInBufPos d)) t)
let s = fromIntegral (T.length t1) + (if T.isPrefixOf "\n" t2 then 1 else 0)
putHData h (d {_hInBufPos = _hInBufPos d + s})
return t1
hGetLine :: Handle -> IO String
hGetLine h = fmap T.unpack (hGetLineText h)
readFileText :: FilePath -> IO Text
readFileText path =
do w <- getWorld
p <- mkPath path
f <- mkFile path
if not (isPermitted w p ReadMode) then
fileIOError path PermissionDenied "openFile" "Permission denied"
else
mkFile path >>= getFileContents "openFile"
readFile :: FilePath -> IO String
readFile = fmap T.unpack . readFileText
writeFileText :: FilePath -> Text -> IO ()
writeFileText path t =
do w <- getWorld
p <- mkPath path
f <- mkFile path
if not (isPermitted w p WriteMode) then
fileIOError path PermissionDenied "openFile" "Permission denied"
else do
f <- mkFile path
putFileContents f t
writeFile :: FilePath -> String -> IO()
writeFile path t = writeFileText path (T.pack t)
appendFileText :: FilePath -> Text -> IO ()
appendFileText path t =
do w <- getWorld
p <- mkPath path
f <- mkFile path
if not (isPermitted w p AppendMode) then
fileIOError path PermissionDenied "openFile" "Permission denied"
else do
f <- mkFile path
w <- getWorld
case M.lookup f (files w) of
Nothing -> putFileContents f t
Just t' -> putFileContents f (T.append t' t)
appendFile :: FilePath -> String -> IO()
appendFile path t = appendFileText path (T.pack t)
readIO :: Read a => String -> IO a
readIO s = case (do { (x,t) <- reads s ;
("","") <- lex t ;
return x }) of
[x] -> return x
[] -> ioError (userError "Prelude.readIO: no parse")
_ -> ioError (userError "Prelude.readIO: ambiguous parse")
_hCanBlock :: Handle -> Bool
_hCanBlock h = h == stdin
wrapBlockingOp' :: String -> (Handle -> IO a) -> Handle -> IO (Maybe a)
wrapBlockingOp' s op h
| h == stdin || h == stdout =
hEnsureOpen s h
eof <- hIsEOF h
if not eof then fmap Just (op h) else do
if h == stdin then void runUser else wait
eof <- hIsEOF h
if eof then return Nothing else fmap Just (op h)
| otherwise = fmap Just (op h)
wrapBlockingOp :: String -> (Handle -> IO a) -> Handle -> IO a
wrapBlockingOp s op h = wrapBlockingOp' s op h >>= maybe (hIOError h ReadDeadlock s msg) return
where msg = if h == stdin then
"user input expected, but user does not respond"
else if h == stdout then
"IO thread expects user input, user expects IO output"
else
"the impossible happened"
hWaitForInput :: Handle -> Int -> IO Bool
hWaitForInput h _ = getHData "hWaitForInput" h >>= hEnsureReadable "hWaitForInput" h >>
fmap (maybe False (const True)) (wrapBlockingOp' "hWaitForInput" (const (return ())) h)
getText :: Integer -> IO Text
getText = hGetText stdin
getChar :: IO Char
getChar = hGetChar stdin
getLineText :: IO Text
getLineText = hGetLineText stdin
getLine :: IO String
getLine = hGetLine stdin
lookAhead :: IO Char
lookAhead = hLookAhead stdin
hGetText :: Handle -> Integer -> IO Text
hGetText h s = wrapBlockingOp "hGetText" (\h -> _hGetText h s) h
hLookAhead :: Handle -> IO Char
hLookAhead = wrapBlockingOp "hLookAhead" _hLookAhead
hGetLineText :: Handle -> IO Text
hGetLineText = wrapBlockingOp "hGetLine" _hGetLineText
readLn :: Read a => IO a
readLn = getLine >>= readIO
getContentText :: IO Text
getContentText = hGetContentText stdin
hGetContents :: Handle -> IO String
hGetContents h = fmap T.unpack (hGetContentText h)
getContents :: IO String
getContents = fmap T.unpack getContentText
interact :: (String -> String) -> IO ()
interact f =
do b <- isUserThread
if b then
wait
else do
void runUser
eof <- isEOF
if eof then return () else do
s <- getLine
putStrLn (f (s ++ "\n"))
interact f
hFlush :: Handle -> IO ()
hFlush _ = return ()
newtype ConsoleHook = ConsoleHook (MVar [(SpecialFile, Text)]) deriving (Typeable)
hookConsole :: IO ConsoleHook
hookConsole =
do v <- newMVar []
registerWriteHook (hook v)
return (ConsoleHook v)
where hook v h t = case _hOutFile h of
SpecialFile special -> modifyMVar_ v (\xs -> return ((special, t) : xs))
_ -> return ()
readConsoleHook :: ConsoleHook -> IO [(SpecialFile, Text)]
readConsoleHook (ConsoleHook v) = fmap reverse (readMVar v)
showConsoleHook :: ConsoleHook -> IO String
showConsoleHook h = fmap (T.unpack . T.unlines . format) (readConsoleHook h)
where format = map (\xs -> formatLine (fst (head xs)) (T.lines (T.concat (map snd xs)))) . groupBy ((==) `on` fst)
formatLine t xs = T.intercalate nl (map (T.append (prefix t)) xs)
nl = T.pack "\n"
prefix StdIn = "> "
prefix StdOut = ""
prefix StdErr = "ERR: "
newtype HandleHook = HandleHook (MVar [(Direction, Text)]) deriving (Typeable)
hookHandle :: Handle -> IO HandleHook
hookHandle h =
do v <- newMVar []
registerWriteHook (hook v)
return (HandleHook v)
where hook v h' t = if _hOutFile h' == _hOutFile h then
modifyMVar_ v (\xs -> return ((Out, t) : xs))
else if _hOutFile h' == _hInFile h then
modifyMVar_ v (\xs -> return ((In, t) : xs))
else
return ()
readHandleHook :: HandleHook -> IO [(Direction, Text)]
readHandleHook (HandleHook v) = fmap reverse (readMVar v)
showHandleHook :: HandleHook -> IO String
showHandleHook h = fmap (T.unpack . T.unlines . format) (readHandleHook h)
where format = map (\xs -> formatLine (fst (head xs)) (T.lines (T.concat (map snd xs)))) . groupBy ((==) `on` fst)
formatLine t xs = T.intercalate nl (map (T.append (prefix t)) xs)
nl = T.pack "\n"
prefix In = "<< "
prefix Out = ">> "
|
b6a9778add1da495bd8fcf16c9c4bc8dcaaa6b4b5fc8955f14a6ef24c8b42109 | CompSciCabal/SMRTYPRTY | exercises.rkt | #lang racket
(require scheme/mpair)
(displayln "exercise 3.10")
(displayln "--- TODO ---")
(displayln "exercise 3.11")
(displayln "--- TODO ---")
(displayln "exercise 3.12")
(define (append x y)
(if (empty? x)
y
(mcons (mcar x) (append (mcdr x) y))))
(define (append! x y)
(set-mcdr! (last-pair x) y)
x)
(define (last-pair x)
(if (empty? (mcdr x))
x
(last-pair (mcdr x))))
(define x (mlist 'a 'b))
(define y (mlist 'c 'd))
(define z (append x y))
(displayln "> z")
z ;> '(a b c d)
(displayln "> (cdr x)")
(mcdr x) ;> '(b)
(define w (append! x y))
(displayln "> w")
w ;> '(a b c d)
(displayln "> (cdr x)")
(mcdr x) ;> '(b c d)
Box and pointer ( -]- > means ptr , / ] means null )
;; x [a|-]->[b|/]
;; y [c|-]->[d|/]
;; (append! x y)
Directly modifies ( ) to point to y
[ a|-]->[b|-]->|
;; |
|<------------|
;; |
;; |->[c|-]->[d|/]
(displayln "exercise 3.13")
(define (make-cycle x)
(set-mcdr! (last-pair x) x)
x)
(define z1 (make-cycle (mlist 'a 'b 'c)))
;; [a|-]->[b|-]->[c|-]-|
;; ^ |
;; |------------------|
(displayln "exercise 3.14")
(define (mystery x)
(define (loop x y)
(if (empty? x)
y
(let [(temp (mcdr x))]
(set-mcdr! x y)
(loop temp x))))
(loop x (mlist)))
;; Mystery "in place" reverses the list
(define v1 (mlist 'a 'b 'c 'd))
;; [a|-]->[b|-]->[c|-]->[d|/]
(define w1 (mystery v1))
;; [d|-]->[c|-]->[b|-]->[a|/]
(displayln "exercise 3.15")
(define x1 (mlist 'a 'b))
(define zz1 (mcons x1 x1))
(define zz2 (mcons (mlist 'a 'b) (mlist 'a 'b)))
(define (set-to-wow! x)
(set-mcar! (mcar x) 'wow)
x)
;; x1 [wow|-]->[b|/]
;; ^---------------|
;; zz1 |<(mcar)-[-|-]->|
;; because the car and cdr of zz1 both point
;; to x and set-to-wow! sets the (mcar x) to 'wow;
;; zz1's car and cdr both see the change
;; [wow|-]->[b|/] [a|-]->[b|/]
;; ^ ^
zz2 |-<(mcar)-[-|-]->--|
(set-to-wow! zz1)
(set-to-wow! zz2)
(displayln "> zz1")
zz1
(displayln "> zz2")
zz2
(displayln "exercise 3.16")
(define (count-pairs x)
(if (not (pair? x))
0
(+ (count-pairs (car x))
(count-pairs (cdr x))
1)))
(count-pairs (list 'a 'b 'c))
(define aa '(a))
(count-pairs (list aa aa))
(define bb (cons aa aa))
(define cc (cons bb bb))
(count-pairs cc)
(define tricksy-hobbitses (mlist 'a 'b 'a))
(define isdef (mlist 'a 'b 'c))
(define undef (mlist 'a 'b 'c))
(set-mcdr! (mcdr (mcdr undef)) undef)
undef
(displayln "exercise 3.17")
(define (good-count-pairs x)
(let ([seen '()])
(define (iter x)
(if (or (not (pair? x)) (memq x seen))
0
(begin (set! seen (cons x seen))
(+ (iter (car x))
(iter (cdr x))
1))))
(iter x)))
(good-count-pairs (list aa aa))
(good-count-pairs bb)
(good-count-pairs cc)
(displayln "exercise 3.18")
(define (has-cycle? lst)
(define (iter lst seen)
(displayln seen)
(when (not (empty? lst)) (displayln (mcdr lst)))
(displayln "----")
(cond [(empty? lst) #f]
[(memq (mcdr lst) seen) #t]
[else
(iter (mcdr lst)
(cons (mcdr lst) seen))]))
(iter lst '()))
(has-cycle? isdef)
(has-cycle? tricksy-hobbitses)
(has-cycle? undef)
(displayln "exercise 3.19")
(define (const-has-cycle? lst)
(define (move lst)
(if (mpair? lst)
(mcdr lst)
'()))
(define (iter tortoise hare)
(cond [(not (mpair? tortoise)) #f]
[(not (mpair? hare)) #f]
[(eq? tortoise hare) #t]
[(eq? tortoise (move hare)) #t]
[else (iter (move tortoise)
(move (move hare)))]))
(iter (move lst) (move (move lst))))
(define list-with-cycle (mlist 'a 'b 'c 'd 'e 'f))
(set-mcdr! (mcdr (mcdr (mcdr (mcdr list-with-cycle))))
(mcdr (mcdr list-with-cycle)))
(const-has-cycle? isdef)
(const-has-cycle? undef) | null | https://raw.githubusercontent.com/CompSciCabal/SMRTYPRTY/4a5550789c997c20fb7256b81469de1f1fce3514/sicp/v2/3.2/csaunders/exercises.rkt | racket | > '(a b c d)
> '(b)
> '(a b c d)
> '(b c d)
x [a|-]->[b|/]
y [c|-]->[d|/]
(append! x y)
|
|
|->[c|-]->[d|/]
[a|-]->[b|-]->[c|-]-|
^ |
|------------------|
Mystery "in place" reverses the list
[a|-]->[b|-]->[c|-]->[d|/]
[d|-]->[c|-]->[b|-]->[a|/]
x1 [wow|-]->[b|/]
^---------------|
zz1 |<(mcar)-[-|-]->|
because the car and cdr of zz1 both point
to x and set-to-wow! sets the (mcar x) to 'wow;
zz1's car and cdr both see the change
[wow|-]->[b|/] [a|-]->[b|/]
^ ^ | #lang racket
(require scheme/mpair)
(displayln "exercise 3.10")
(displayln "--- TODO ---")
(displayln "exercise 3.11")
(displayln "--- TODO ---")
(displayln "exercise 3.12")
(define (append x y)
(if (empty? x)
y
(mcons (mcar x) (append (mcdr x) y))))
(define (append! x y)
(set-mcdr! (last-pair x) y)
x)
(define (last-pair x)
(if (empty? (mcdr x))
x
(last-pair (mcdr x))))
(define x (mlist 'a 'b))
(define y (mlist 'c 'd))
(define z (append x y))
(displayln "> z")
(displayln "> (cdr x)")
(define w (append! x y))
(displayln "> w")
(displayln "> (cdr x)")
Box and pointer ( -]- > means ptr , / ] means null )
Directly modifies ( ) to point to y
[ a|-]->[b|-]->|
|<------------|
(displayln "exercise 3.13")
(define (make-cycle x)
(set-mcdr! (last-pair x) x)
x)
(define z1 (make-cycle (mlist 'a 'b 'c)))
(displayln "exercise 3.14")
(define (mystery x)
(define (loop x y)
(if (empty? x)
y
(let [(temp (mcdr x))]
(set-mcdr! x y)
(loop temp x))))
(loop x (mlist)))
(define v1 (mlist 'a 'b 'c 'd))
(define w1 (mystery v1))
(displayln "exercise 3.15")
(define x1 (mlist 'a 'b))
(define zz1 (mcons x1 x1))
(define zz2 (mcons (mlist 'a 'b) (mlist 'a 'b)))
(define (set-to-wow! x)
(set-mcar! (mcar x) 'wow)
x)
zz2 |-<(mcar)-[-|-]->--|
(set-to-wow! zz1)
(set-to-wow! zz2)
(displayln "> zz1")
zz1
(displayln "> zz2")
zz2
(displayln "exercise 3.16")
(define (count-pairs x)
(if (not (pair? x))
0
(+ (count-pairs (car x))
(count-pairs (cdr x))
1)))
(count-pairs (list 'a 'b 'c))
(define aa '(a))
(count-pairs (list aa aa))
(define bb (cons aa aa))
(define cc (cons bb bb))
(count-pairs cc)
(define tricksy-hobbitses (mlist 'a 'b 'a))
(define isdef (mlist 'a 'b 'c))
(define undef (mlist 'a 'b 'c))
(set-mcdr! (mcdr (mcdr undef)) undef)
undef
(displayln "exercise 3.17")
(define (good-count-pairs x)
(let ([seen '()])
(define (iter x)
(if (or (not (pair? x)) (memq x seen))
0
(begin (set! seen (cons x seen))
(+ (iter (car x))
(iter (cdr x))
1))))
(iter x)))
(good-count-pairs (list aa aa))
(good-count-pairs bb)
(good-count-pairs cc)
(displayln "exercise 3.18")
(define (has-cycle? lst)
(define (iter lst seen)
(displayln seen)
(when (not (empty? lst)) (displayln (mcdr lst)))
(displayln "----")
(cond [(empty? lst) #f]
[(memq (mcdr lst) seen) #t]
[else
(iter (mcdr lst)
(cons (mcdr lst) seen))]))
(iter lst '()))
(has-cycle? isdef)
(has-cycle? tricksy-hobbitses)
(has-cycle? undef)
(displayln "exercise 3.19")
(define (const-has-cycle? lst)
(define (move lst)
(if (mpair? lst)
(mcdr lst)
'()))
(define (iter tortoise hare)
(cond [(not (mpair? tortoise)) #f]
[(not (mpair? hare)) #f]
[(eq? tortoise hare) #t]
[(eq? tortoise (move hare)) #t]
[else (iter (move tortoise)
(move (move hare)))]))
(iter (move lst) (move (move lst))))
(define list-with-cycle (mlist 'a 'b 'c 'd 'e 'f))
(set-mcdr! (mcdr (mcdr (mcdr (mcdr list-with-cycle))))
(mcdr (mcdr list-with-cycle)))
(const-has-cycle? isdef)
(const-has-cycle? undef) |
04eb74202232a296e370f7b1f4a8188651aed3c8fcbd9c7df433974b09de0463 | CloudI/CloudI | hackney_util.erl | %%% -*- erlang -*-
%%%
This file is part of hackney released under the Apache 2 license .
%%% See the NOTICE for more information.
%%%
-module(hackney_util).
-export([filter_options/3]).
-export([set_option_default/3]).
-export([require/1]).
-export([maybe_apply_defaults/2]).
-export([is_ipv6/1]).
-export([privdir/0]).
-export([mod_metrics/0]).
-export([to_atom/1]).
-export([merge_opts/2]).
-export([to_int/1]).
-include("hackney.hrl").
%% @doc filter a proplists and only keep allowed keys
-spec filter_options([{atom(), any()} | {raw, any(), any(), any()}],
[atom()], Acc) -> Acc when Acc :: [any()].
filter_options([], _, Acc) ->
Acc;
filter_options([Opt = {Key, _}|Tail], AllowedKeys, Acc) ->
case lists:member(Key, AllowedKeys) of
true -> filter_options(Tail, AllowedKeys, [Opt|Acc]);
false -> filter_options(Tail, AllowedKeys, Acc)
end;
filter_options([Opt = {raw, _, _, _}|Tail], AllowedKeys, Acc) ->
case lists:member(raw, AllowedKeys) of
true -> filter_options(Tail, AllowedKeys, [Opt|Acc]);
false -> filter_options(Tail, AllowedKeys, Acc)
end;
filter_options([Opt|Tail], AllowedKeys, Acc) when is_atom(Opt) ->
case lists:member(Opt, AllowedKeys) of
true -> filter_options(Tail, AllowedKeys, [Opt|Acc]);
false -> filter_options(Tail, AllowedKeys, Acc)
end.
%% @doc set the default options in a proplists if not defined
-spec set_option_default(Opts, atom(), any())
-> Opts when Opts :: [{atom(), any()}].
set_option_default(Opts, Key, Value) ->
case lists:keymember(Key, 1, Opts) of
true -> Opts;
false -> [{Key, Value}|Opts]
end.
%% @doc Start the given applications if they were not already started.
-spec require(list(module())) -> ok.
require([]) ->
ok;
require([App|Rest]) ->
case application:start(App) of
ok -> ok;
{error, {already_started, App}} -> ok
end,
require(Rest).
maybe_apply_defaults([], Options) ->
Options;
maybe_apply_defaults([OptName | Rest], Options) ->
case proplists:is_defined(OptName, Options) of
true ->
maybe_apply_defaults(Rest, Options);
false ->
{ok, Default} = application:get_env(hackney, OptName),
maybe_apply_defaults(Rest, [{OptName, Default} | Options])
end.
is_ipv6(Host) ->
case inet_parse:address(Host) of
{ok, {_, _, _, _, _, _, _, _}} ->
true;
{ok, {_, _, _, _}} ->
false;
_ ->
case inet:getaddr(Host, inet) of
{ok, _} ->
false;
_ ->
case inet:getaddr(Host, inet6) of
{ok, _} ->
true;
_ ->
false
end
end
end.
privdir() ->
case code:priv_dir(hackney) of
{error, _} ->
%% try to get relative priv dir. useful for tests.
EbinDir = filename:dirname(code:which(?MODULE)),
AppPath = filename:dirname(EbinDir),
filename:join(AppPath, "priv");
Dir -> Dir
end.
mod_metrics() ->
case application:get_env(hackney, mod_metrics) of
{ok, folsom} -> metrics_folsom;
{ok, exometer} -> metrics_exometer;
{ok, dummy} -> metrics_dummy;
{ok, Mod} -> Mod;
_ -> metrics_dummy
end.
to_atom(V) when is_list(V) ->
try
list_to_existing_atom(V)
catch
_:_ -> list_to_atom(V)
end;
to_atom(V) when is_binary(V) ->
to_atom(binary_to_list(V));
to_atom(V) when is_atom(V) ->
V.
merge_opts([], Options) -> Options;
merge_opts([Opt = {K, _}| Rest], Options) ->
case lists:keymember(K, 1, Options) of
true -> merge_opts(Rest, Options);
false -> merge_opts(Rest, [Opt | Options])
end;
merge_opts([Opt={raw, _, _, _} | Rest], Options) ->
merge_opts(Rest, [Opt | Options]);
merge_opts([K | Rest], Options) when is_atom(K) ->
case lists:member(K, Options) of
true -> merge_opts(Rest, Options);
false -> merge_opts(Rest, [K | Options])
end;
merge_opts([_ | Rest], Options) ->
merge_opts(Rest, Options).
to_int(S) when is_binary(S) ->
to_int(binary_to_list(S));
to_int(S) ->
try
I = list_to_integer(S),
{ok, I}
catch
error:badarg -> false
end. | null | https://raw.githubusercontent.com/CloudI/CloudI/3e45031c7ee3e974ead2612ea7dd06c9edf973c9/src/external/cloudi_x_hackney/src/hackney_util.erl | erlang | -*- erlang -*-
See the NOTICE for more information.
@doc filter a proplists and only keep allowed keys
@doc set the default options in a proplists if not defined
@doc Start the given applications if they were not already started.
try to get relative priv dir. useful for tests. | This file is part of hackney released under the Apache 2 license .
-module(hackney_util).
-export([filter_options/3]).
-export([set_option_default/3]).
-export([require/1]).
-export([maybe_apply_defaults/2]).
-export([is_ipv6/1]).
-export([privdir/0]).
-export([mod_metrics/0]).
-export([to_atom/1]).
-export([merge_opts/2]).
-export([to_int/1]).
-include("hackney.hrl").
-spec filter_options([{atom(), any()} | {raw, any(), any(), any()}],
[atom()], Acc) -> Acc when Acc :: [any()].
filter_options([], _, Acc) ->
Acc;
filter_options([Opt = {Key, _}|Tail], AllowedKeys, Acc) ->
case lists:member(Key, AllowedKeys) of
true -> filter_options(Tail, AllowedKeys, [Opt|Acc]);
false -> filter_options(Tail, AllowedKeys, Acc)
end;
filter_options([Opt = {raw, _, _, _}|Tail], AllowedKeys, Acc) ->
case lists:member(raw, AllowedKeys) of
true -> filter_options(Tail, AllowedKeys, [Opt|Acc]);
false -> filter_options(Tail, AllowedKeys, Acc)
end;
filter_options([Opt|Tail], AllowedKeys, Acc) when is_atom(Opt) ->
case lists:member(Opt, AllowedKeys) of
true -> filter_options(Tail, AllowedKeys, [Opt|Acc]);
false -> filter_options(Tail, AllowedKeys, Acc)
end.
-spec set_option_default(Opts, atom(), any())
-> Opts when Opts :: [{atom(), any()}].
set_option_default(Opts, Key, Value) ->
case lists:keymember(Key, 1, Opts) of
true -> Opts;
false -> [{Key, Value}|Opts]
end.
-spec require(list(module())) -> ok.
require([]) ->
ok;
require([App|Rest]) ->
case application:start(App) of
ok -> ok;
{error, {already_started, App}} -> ok
end,
require(Rest).
maybe_apply_defaults([], Options) ->
Options;
maybe_apply_defaults([OptName | Rest], Options) ->
case proplists:is_defined(OptName, Options) of
true ->
maybe_apply_defaults(Rest, Options);
false ->
{ok, Default} = application:get_env(hackney, OptName),
maybe_apply_defaults(Rest, [{OptName, Default} | Options])
end.
is_ipv6(Host) ->
case inet_parse:address(Host) of
{ok, {_, _, _, _, _, _, _, _}} ->
true;
{ok, {_, _, _, _}} ->
false;
_ ->
case inet:getaddr(Host, inet) of
{ok, _} ->
false;
_ ->
case inet:getaddr(Host, inet6) of
{ok, _} ->
true;
_ ->
false
end
end
end.
privdir() ->
case code:priv_dir(hackney) of
{error, _} ->
EbinDir = filename:dirname(code:which(?MODULE)),
AppPath = filename:dirname(EbinDir),
filename:join(AppPath, "priv");
Dir -> Dir
end.
mod_metrics() ->
case application:get_env(hackney, mod_metrics) of
{ok, folsom} -> metrics_folsom;
{ok, exometer} -> metrics_exometer;
{ok, dummy} -> metrics_dummy;
{ok, Mod} -> Mod;
_ -> metrics_dummy
end.
to_atom(V) when is_list(V) ->
try
list_to_existing_atom(V)
catch
_:_ -> list_to_atom(V)
end;
to_atom(V) when is_binary(V) ->
to_atom(binary_to_list(V));
to_atom(V) when is_atom(V) ->
V.
merge_opts([], Options) -> Options;
merge_opts([Opt = {K, _}| Rest], Options) ->
case lists:keymember(K, 1, Options) of
true -> merge_opts(Rest, Options);
false -> merge_opts(Rest, [Opt | Options])
end;
merge_opts([Opt={raw, _, _, _} | Rest], Options) ->
merge_opts(Rest, [Opt | Options]);
merge_opts([K | Rest], Options) when is_atom(K) ->
case lists:member(K, Options) of
true -> merge_opts(Rest, Options);
false -> merge_opts(Rest, [K | Options])
end;
merge_opts([_ | Rest], Options) ->
merge_opts(Rest, Options).
to_int(S) when is_binary(S) ->
to_int(binary_to_list(S));
to_int(S) ->
try
I = list_to_integer(S),
{ok, I}
catch
error:badarg -> false
end. |
81d0bcaef206935d997fd28981408ff4fa65028cfcf032888b0c820f91abb03c | sbcl/sbcl | float-inf-nan.lisp | ;;;; This file contains the definitions of float-specific number
support ( other than irrational stuff , which is in irrat . ) There is
code in here that assumes there are only two float formats : IEEE
;;;; single and double. (LONG-FLOAT support has been added, but bugs
;;;; may still remain due to old code which assumes this dichotomy.)
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB-KERNEL")
(declaim (maybe-inline float-denormalized-p float-infinity-p float-nan-p
float-trapping-nan-p))
(defmacro sfloat-bits-subnormalp (bits)
`(zerop (ldb sb-vm:single-float-exponent-byte ,bits)))
#-64-bit
(defmacro dfloat-high-bits-subnormalp (bits)
`(zerop (ldb sb-vm:double-float-exponent-byte ,bits)))
#+64-bit
(progn
(defmacro dfloat-exponent-from-bits (bits)
`(ldb (byte ,(byte-size sb-vm:double-float-exponent-byte)
,(+ 32 (byte-position sb-vm:double-float-exponent-byte)))
,bits))
(defmacro dfloat-bits-subnormalp (bits)
`(zerop (dfloat-exponent-from-bits ,bits))))
(defun float-denormalized-p (x)
"Return true if the float X is denormalized."
(declare (explicit-check))
(number-dispatch ((x float))
((single-float)
#+64-bit
(let ((bits (single-float-bits x)))
(and (ldb-test (byte 31 0) bits) ; is nonzero (disregard the sign bit)
(sfloat-bits-subnormalp bits)))
#-64-bit
(and (zerop (ldb sb-vm:single-float-exponent-byte (single-float-bits x)))
(not (zerop x))))
((double-float)
#+64-bit
(let ((bits (double-float-bits x)))
;; is nonzero after shifting out the sign bit
(and (not (zerop (logand (ash bits 1) most-positive-word)))
(dfloat-bits-subnormalp bits)))
#-64-bit
(and (zerop (ldb sb-vm:double-float-exponent-byte
(double-float-high-bits x)))
(not (zerop x))))
#+(and long-float x86)
((long-float)
(and (zerop (ldb sb-vm:long-float-exponent-byte (long-float-exp-bits x)))
(not (zerop x))))))
(defmacro float-inf-or-nan-test (var single double #+(and long-float x86) long)
`(number-dispatch ((,var float))
((single-float)
(let ((bits (single-float-bits ,var)))
(and (> (ldb sb-vm:single-float-exponent-byte bits)
sb-vm:single-float-normal-exponent-max)
,single)))
((double-float)
#+64-bit
With 64 - bit words , all the FOO - float - byte constants need to be reworked
;; to refer to a byte position in the whole word. I think we can reasonably
;; get away with writing the well-known values here.
(let ((bits (double-float-bits ,var)))
(and (> (ldb (byte 11 52) bits) sb-vm:double-float-normal-exponent-max)
,double))
#-64-bit
(let ((hi (double-float-high-bits ,var))
(lo (double-float-low-bits ,var)))
(declare (ignorable lo))
(and (> (ldb sb-vm:double-float-exponent-byte hi)
sb-vm:double-float-normal-exponent-max)
,double)))
#+(and long-float x86)
((long-float)
(let ((exp (long-float-exp-bits ,var))
(hi (long-float-high-bits ,var))
(lo (long-float-low-bits ,var)))
(declare (ignorable lo))
(and (> (ldb sb-vm:long-float-exponent-byte exp)
sb-vm:long-float-normal-exponent-max)
,long)))))
;; Infinities and NANs have the maximum exponent
(defun float-infinity-or-nan-p (x)
(float-inf-or-nan-test x t t #+(and long-float x86) t))
Infinity has 0 for the significand
(defun float-infinity-p (x)
"Return true if the float X is an infinity (+ or -)."
(float-inf-or-nan-test
x
(zerop (ldb sb-vm:single-float-significand-byte bits))
#+64-bit (zerop (ldb (byte 52 0) bits))
#-64-bit (zerop (logior (ldb sb-vm:double-float-significand-byte hi) lo))
#+(and long-float x86)
(and (zerop (ldb sb-vm:long-float-significand-byte hi))
(zerop lo))))
NaNs have nonzero for the significand
(defun float-nan-p (x)
"Return true if the float X is a NaN (Not a Number)."
(float-inf-or-nan-test
x
(not (zerop (ldb sb-vm:single-float-significand-byte bits)))
#+64-bit (not (zerop (ldb (byte 52 0) bits)))
#-64-bit (not (zerop (logior (ldb sb-vm:double-float-significand-byte hi) lo)))
#+(and long-float x86)
(or (not (zerop (ldb sb-vm:long-float-significand-byte hi)))
(not (zerop lo)))))
(defmacro with-float-inf-or-nan-test (float infinity nan normal)
`(block nil
,(if (equal infinity nan)
`(float-inf-or-nan-test
,float
(return ,nan)
(return ,nan))
`(float-inf-or-nan-test
,float
(if (zerop (ldb sb-vm:single-float-significand-byte bits))
(return ,infinity)
(return ,nan))
(if #+64-bit (zerop (ldb (byte 52 0) bits))
#-64-bit (zerop (logior (ldb sb-vm:double-float-significand-byte hi) lo))
(return ,infinity)
(return ,nan))))
,normal))
(defun float-trapping-nan-p (x)
"Return true if the float X is a trapping NaN (Not a Number)."
MIPS has trapping NaNs ( SNaNs ) with the trapping - nan - bit SET .
All the others have trapping NaNs ( SNaNs ) with the
;; trapping-nan-bit CLEAR. Note that the given implementation
;; considers infinities to be FLOAT-TRAPPING-NAN-P on most
;; architectures.
(float-inf-or-nan-test
x
;; SINGLE-FLOAT
#+mips (logbitp 22 bits)
#-mips (not (logbitp 22 bits))
;; DOUBLE-FLOAT
#+mips (logbitp 19 hi)
#+(and (not mips) 64-bit) (not (logbitp 51 bits))
#+(and (not mips) (not 64-bit)) (not (logbitp 19 hi))
;; LONG-FLOAT (this code is dead anyway)
#+(and long-float x86)
(zerop (logand (ldb sb-vm:long-float-significand-byte hi)
(ash 1 30)))))
| null | https://raw.githubusercontent.com/sbcl/sbcl/63b95f9e7d9c7fbb02da834dc16edfe8eae24e6a/src/code/float-inf-nan.lisp | lisp | This file contains the definitions of float-specific number
single and double. (LONG-FLOAT support has been added, but bugs
may still remain due to old code which assumes this dichotomy.)
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
is nonzero (disregard the sign bit)
is nonzero after shifting out the sign bit
to refer to a byte position in the whole word. I think we can reasonably
get away with writing the well-known values here.
Infinities and NANs have the maximum exponent
trapping-nan-bit CLEAR. Note that the given implementation
considers infinities to be FLOAT-TRAPPING-NAN-P on most
architectures.
SINGLE-FLOAT
DOUBLE-FLOAT
LONG-FLOAT (this code is dead anyway) | support ( other than irrational stuff , which is in irrat . ) There is
code in here that assumes there are only two float formats : IEEE
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB-KERNEL")
(declaim (maybe-inline float-denormalized-p float-infinity-p float-nan-p
float-trapping-nan-p))
(defmacro sfloat-bits-subnormalp (bits)
`(zerop (ldb sb-vm:single-float-exponent-byte ,bits)))
#-64-bit
(defmacro dfloat-high-bits-subnormalp (bits)
`(zerop (ldb sb-vm:double-float-exponent-byte ,bits)))
#+64-bit
(progn
(defmacro dfloat-exponent-from-bits (bits)
`(ldb (byte ,(byte-size sb-vm:double-float-exponent-byte)
,(+ 32 (byte-position sb-vm:double-float-exponent-byte)))
,bits))
(defmacro dfloat-bits-subnormalp (bits)
`(zerop (dfloat-exponent-from-bits ,bits))))
(defun float-denormalized-p (x)
"Return true if the float X is denormalized."
(declare (explicit-check))
(number-dispatch ((x float))
((single-float)
#+64-bit
(let ((bits (single-float-bits x)))
(sfloat-bits-subnormalp bits)))
#-64-bit
(and (zerop (ldb sb-vm:single-float-exponent-byte (single-float-bits x)))
(not (zerop x))))
((double-float)
#+64-bit
(let ((bits (double-float-bits x)))
(and (not (zerop (logand (ash bits 1) most-positive-word)))
(dfloat-bits-subnormalp bits)))
#-64-bit
(and (zerop (ldb sb-vm:double-float-exponent-byte
(double-float-high-bits x)))
(not (zerop x))))
#+(and long-float x86)
((long-float)
(and (zerop (ldb sb-vm:long-float-exponent-byte (long-float-exp-bits x)))
(not (zerop x))))))
(defmacro float-inf-or-nan-test (var single double #+(and long-float x86) long)
`(number-dispatch ((,var float))
((single-float)
(let ((bits (single-float-bits ,var)))
(and (> (ldb sb-vm:single-float-exponent-byte bits)
sb-vm:single-float-normal-exponent-max)
,single)))
((double-float)
#+64-bit
With 64 - bit words , all the FOO - float - byte constants need to be reworked
(let ((bits (double-float-bits ,var)))
(and (> (ldb (byte 11 52) bits) sb-vm:double-float-normal-exponent-max)
,double))
#-64-bit
(let ((hi (double-float-high-bits ,var))
(lo (double-float-low-bits ,var)))
(declare (ignorable lo))
(and (> (ldb sb-vm:double-float-exponent-byte hi)
sb-vm:double-float-normal-exponent-max)
,double)))
#+(and long-float x86)
((long-float)
(let ((exp (long-float-exp-bits ,var))
(hi (long-float-high-bits ,var))
(lo (long-float-low-bits ,var)))
(declare (ignorable lo))
(and (> (ldb sb-vm:long-float-exponent-byte exp)
sb-vm:long-float-normal-exponent-max)
,long)))))
(defun float-infinity-or-nan-p (x)
(float-inf-or-nan-test x t t #+(and long-float x86) t))
Infinity has 0 for the significand
(defun float-infinity-p (x)
"Return true if the float X is an infinity (+ or -)."
(float-inf-or-nan-test
x
(zerop (ldb sb-vm:single-float-significand-byte bits))
#+64-bit (zerop (ldb (byte 52 0) bits))
#-64-bit (zerop (logior (ldb sb-vm:double-float-significand-byte hi) lo))
#+(and long-float x86)
(and (zerop (ldb sb-vm:long-float-significand-byte hi))
(zerop lo))))
NaNs have nonzero for the significand
(defun float-nan-p (x)
"Return true if the float X is a NaN (Not a Number)."
(float-inf-or-nan-test
x
(not (zerop (ldb sb-vm:single-float-significand-byte bits)))
#+64-bit (not (zerop (ldb (byte 52 0) bits)))
#-64-bit (not (zerop (logior (ldb sb-vm:double-float-significand-byte hi) lo)))
#+(and long-float x86)
(or (not (zerop (ldb sb-vm:long-float-significand-byte hi)))
(not (zerop lo)))))
(defmacro with-float-inf-or-nan-test (float infinity nan normal)
`(block nil
,(if (equal infinity nan)
`(float-inf-or-nan-test
,float
(return ,nan)
(return ,nan))
`(float-inf-or-nan-test
,float
(if (zerop (ldb sb-vm:single-float-significand-byte bits))
(return ,infinity)
(return ,nan))
(if #+64-bit (zerop (ldb (byte 52 0) bits))
#-64-bit (zerop (logior (ldb sb-vm:double-float-significand-byte hi) lo))
(return ,infinity)
(return ,nan))))
,normal))
(defun float-trapping-nan-p (x)
"Return true if the float X is a trapping NaN (Not a Number)."
MIPS has trapping NaNs ( SNaNs ) with the trapping - nan - bit SET .
All the others have trapping NaNs ( SNaNs ) with the
(float-inf-or-nan-test
x
#+mips (logbitp 22 bits)
#-mips (not (logbitp 22 bits))
#+mips (logbitp 19 hi)
#+(and (not mips) 64-bit) (not (logbitp 51 bits))
#+(and (not mips) (not 64-bit)) (not (logbitp 19 hi))
#+(and long-float x86)
(zerop (logand (ldb sb-vm:long-float-significand-byte hi)
(ash 1 30)))))
|
65cde48b11a82b56bf3865bdaccb7af4221f1ae07d0f20be1a952d2af83f2125 | ashinn/chibi-scheme | vector.scm |
(define (vector-unfold! f vec start end . o)
(let lp ((i start) (seeds o))
(if (< i end)
(call-with-values (lambda () (apply f i seeds))
(lambda (x . seeds)
(vector-set! vec i x)
(lp (+ i 1) seeds))))))
(define (vector-unfold-right! f vec start end . o)
(let lp ((i (- end 1)) (seeds o))
(if (>= i start)
(call-with-values (lambda () (apply f i seeds))
(lambda (x . seeds)
(vector-set! vec i x)
(lp (- i 1) seeds))))))
(define (vector-unfold f len . o)
(let ((res (make-vector len)))
(apply vector-unfold! f res 0 len o)
res))
(define (vector-unfold-right f len . o)
(let ((res (make-vector len)))
(apply vector-unfold-right! f res 0 len o)
res))
(define (vector-reverse-copy vec . o)
(let* ((start (if (pair? o) (car o) 0))
(end (if (and (pair? o) (pair? (cdr o))) (cadr o) (vector-length vec)))
(len (- end start)))
(vector-unfold-right (lambda (i) (vector-ref vec (- end i 1))) len)))
(define (vector-concatenate ls)
(apply vector-append ls))
(define (vector-append-subvectors . o)
(let lp ((ls o) (vecs '()))
(if (null? ls)
(vector-concatenate (reverse vecs))
(lp (cdr (cddr ls))
(cons (vector-copy (car ls) (cadr ls) (car (cddr ls))) vecs)))))
(define (vector-empty? vec)
(zero? (vector-length vec)))
(define (vector= eq . o)
(cond
((null? o) #t)
((null? (cdr o)) #t)
(else
(and (let* ((v1 (car o))
(v2 (cadr o))
(len (vector-length v1)))
(and (= len (vector-length v2))
(let lp ((i 0))
(or (>= i len)
(and (eq (vector-ref v1 i) (vector-ref v2 i))
(lp (+ i 1)))))))
(apply vector= eq (cdr o))))))
(define (vector-fold kons knil vec1 . o)
(let ((len (vector-length vec1)))
(if (null? o)
(let lp ((i 0) (acc knil))
(if (>= i len) acc (lp (+ i 1) (kons acc (vector-ref vec1 i)))))
(let lp ((i 0) (acc knil))
(if (>= i len)
acc
(lp (+ i 1)
(apply kons acc (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))))))))
(define (vector-fold-right kons knil vec1 . o)
(let ((len (vector-length vec1)))
(if (null? o)
(let lp ((i (- len 1)) (acc knil))
(if (negative? i) acc (lp (- i 1) (kons acc (vector-ref vec1 i)))))
(let lp ((i (- len 1)) (acc knil))
(if (negative? i)
acc
(lp (- i 1)
(apply kons acc (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))))))))
(define (vector-map! proc vec1 . o)
(let ((len (vector-length vec1)))
(if (null? o)
(let lp ((i 0))
(cond
((>= i len) vec1)
(else (vector-set! vec1 i (proc (vector-ref vec1 i))) (lp (+ i 1)))))
(let lp ((i 0))
(cond
((>= i len) vec1)
(else
(let ((x (apply proc (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))))
(vector-set! vec1 i x)
(lp (+ i 1)))))))))
(define (vector-count pred? vec1 . o)
(apply vector-fold
(lambda (count . x) (+ count (if (apply pred? x) 1 0)))
0
vec1 o))
(define (vector-cumulate f knil vec)
(let* ((len (vector-length vec))
(res (make-vector len)))
(let lp ((i 0) (acc knil))
(if (>= i len)
res
(let ((acc (f acc (vector-ref vec i))))
(vector-set! res i acc)
(lp (+ i 1) acc))))))
(define (vector-index pred? vec1 . o)
(let ((len (apply min (vector-length vec1) (map vector-length o))))
(let lp ((i 0))
(and (< i len)
(if (apply pred? (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))
i
(lp (+ i 1)))))))
(define (vector-index-right pred? vec1 . o)
(let ((len (vector-length vec1)))
(let lp ((i (- len 1)))
(and (>= i 0)
(if (apply pred? (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))
i
(lp (- i 1)))))))
(define (complement f)
(lambda args (not (apply f args))))
(define (vector-skip pred? vec1 . o)
(apply vector-index (complement pred?) vec1 o))
(define (vector-skip-right pred? vec1 . o)
(apply vector-index-right (complement pred?) vec1 o))
(define (vector-binary-search vec value cmp)
(let lp ((lo 0) (hi (- (vector-length vec) 1)))
(and (<= lo hi)
(let* ((mid (quotient (+ lo hi) 2))
(x (vector-ref vec mid))
(y (cmp value x)))
(cond
((< y 0) (lp lo (- mid 1)))
((> y 0) (lp (+ mid 1) hi))
(else mid))))))
(define (vector-any pred? vec1 . o)
(let ((len (apply min (vector-length vec1) (map vector-length o))))
(let lp ((i 0))
(and (< i len)
(or (apply pred? (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))
(lp (+ i 1)))))))
(define (vector-every pred? vec1 . o)
(let ((len (apply min (vector-length vec1) (map vector-length o))))
(or (zero? len)
(let lp ((i 0))
(let ((x (apply pred? (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))))
(if (= i (- len 1))
x
(and x (lp (+ i 1)))))))))
(define (vector-swap! vec i j)
(let ((tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)))
(define (vector-reverse! vec . o)
(let lp ((left (if (pair? o) (car o) 0))
(right (- (if (and (pair? o) (pair? (cdr o)))
(cadr o)
(vector-length vec))
1)))
(cond
((>= left right) (if #f #f))
(else
(vector-swap! vec left right)
(lp (+ left 1) (- right 1))))))
(define (vector-reverse-copy! to at from . o)
(let ((start (if (pair? o) (car o) 0))
(end (if (and (pair? o) (pair? (cdr o)))
(cadr o)
(vector-length from))))
(vector-copy! to at from start end)
(vector-reverse! to at (+ at (- end start)))))
(define (reverse-vector->list vec . o)
(reverse (apply vector->list vec o)))
(define (reverse-list->vector ls)
(list->vector (reverse ls)))
(define (vector-partition pred? vec)
(let* ((len (vector-length vec))
(res (make-vector len)))
(let lp ((i 0) (left 0) (right (- len 1)))
(cond
((= i len)
(if (< left len)
(vector-reverse! res left))
(values res left))
(else
(let ((x (vector-ref vec i)))
(cond
((pred? x)
(vector-set! res left x)
(lp (+ i 1) (+ left 1) right))
(else
(vector-set! res right x)
(lp (+ i 1) left (- right 1))))))))))
| null | https://raw.githubusercontent.com/ashinn/chibi-scheme/8b27ce97265e5028c61b2386a86a2c43c1cfba0d/lib/srfi/133/vector.scm | scheme |
(define (vector-unfold! f vec start end . o)
(let lp ((i start) (seeds o))
(if (< i end)
(call-with-values (lambda () (apply f i seeds))
(lambda (x . seeds)
(vector-set! vec i x)
(lp (+ i 1) seeds))))))
(define (vector-unfold-right! f vec start end . o)
(let lp ((i (- end 1)) (seeds o))
(if (>= i start)
(call-with-values (lambda () (apply f i seeds))
(lambda (x . seeds)
(vector-set! vec i x)
(lp (- i 1) seeds))))))
(define (vector-unfold f len . o)
(let ((res (make-vector len)))
(apply vector-unfold! f res 0 len o)
res))
(define (vector-unfold-right f len . o)
(let ((res (make-vector len)))
(apply vector-unfold-right! f res 0 len o)
res))
(define (vector-reverse-copy vec . o)
(let* ((start (if (pair? o) (car o) 0))
(end (if (and (pair? o) (pair? (cdr o))) (cadr o) (vector-length vec)))
(len (- end start)))
(vector-unfold-right (lambda (i) (vector-ref vec (- end i 1))) len)))
(define (vector-concatenate ls)
(apply vector-append ls))
(define (vector-append-subvectors . o)
(let lp ((ls o) (vecs '()))
(if (null? ls)
(vector-concatenate (reverse vecs))
(lp (cdr (cddr ls))
(cons (vector-copy (car ls) (cadr ls) (car (cddr ls))) vecs)))))
(define (vector-empty? vec)
(zero? (vector-length vec)))
(define (vector= eq . o)
(cond
((null? o) #t)
((null? (cdr o)) #t)
(else
(and (let* ((v1 (car o))
(v2 (cadr o))
(len (vector-length v1)))
(and (= len (vector-length v2))
(let lp ((i 0))
(or (>= i len)
(and (eq (vector-ref v1 i) (vector-ref v2 i))
(lp (+ i 1)))))))
(apply vector= eq (cdr o))))))
(define (vector-fold kons knil vec1 . o)
(let ((len (vector-length vec1)))
(if (null? o)
(let lp ((i 0) (acc knil))
(if (>= i len) acc (lp (+ i 1) (kons acc (vector-ref vec1 i)))))
(let lp ((i 0) (acc knil))
(if (>= i len)
acc
(lp (+ i 1)
(apply kons acc (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))))))))
(define (vector-fold-right kons knil vec1 . o)
(let ((len (vector-length vec1)))
(if (null? o)
(let lp ((i (- len 1)) (acc knil))
(if (negative? i) acc (lp (- i 1) (kons acc (vector-ref vec1 i)))))
(let lp ((i (- len 1)) (acc knil))
(if (negative? i)
acc
(lp (- i 1)
(apply kons acc (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))))))))
(define (vector-map! proc vec1 . o)
(let ((len (vector-length vec1)))
(if (null? o)
(let lp ((i 0))
(cond
((>= i len) vec1)
(else (vector-set! vec1 i (proc (vector-ref vec1 i))) (lp (+ i 1)))))
(let lp ((i 0))
(cond
((>= i len) vec1)
(else
(let ((x (apply proc (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))))
(vector-set! vec1 i x)
(lp (+ i 1)))))))))
(define (vector-count pred? vec1 . o)
(apply vector-fold
(lambda (count . x) (+ count (if (apply pred? x) 1 0)))
0
vec1 o))
(define (vector-cumulate f knil vec)
(let* ((len (vector-length vec))
(res (make-vector len)))
(let lp ((i 0) (acc knil))
(if (>= i len)
res
(let ((acc (f acc (vector-ref vec i))))
(vector-set! res i acc)
(lp (+ i 1) acc))))))
(define (vector-index pred? vec1 . o)
(let ((len (apply min (vector-length vec1) (map vector-length o))))
(let lp ((i 0))
(and (< i len)
(if (apply pred? (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))
i
(lp (+ i 1)))))))
(define (vector-index-right pred? vec1 . o)
(let ((len (vector-length vec1)))
(let lp ((i (- len 1)))
(and (>= i 0)
(if (apply pred? (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))
i
(lp (- i 1)))))))
(define (complement f)
(lambda args (not (apply f args))))
(define (vector-skip pred? vec1 . o)
(apply vector-index (complement pred?) vec1 o))
(define (vector-skip-right pred? vec1 . o)
(apply vector-index-right (complement pred?) vec1 o))
(define (vector-binary-search vec value cmp)
(let lp ((lo 0) (hi (- (vector-length vec) 1)))
(and (<= lo hi)
(let* ((mid (quotient (+ lo hi) 2))
(x (vector-ref vec mid))
(y (cmp value x)))
(cond
((< y 0) (lp lo (- mid 1)))
((> y 0) (lp (+ mid 1) hi))
(else mid))))))
(define (vector-any pred? vec1 . o)
(let ((len (apply min (vector-length vec1) (map vector-length o))))
(let lp ((i 0))
(and (< i len)
(or (apply pred? (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))
(lp (+ i 1)))))))
(define (vector-every pred? vec1 . o)
(let ((len (apply min (vector-length vec1) (map vector-length o))))
(or (zero? len)
(let lp ((i 0))
(let ((x (apply pred? (vector-ref vec1 i)
(map (lambda (v) (vector-ref v i)) o))))
(if (= i (- len 1))
x
(and x (lp (+ i 1)))))))))
(define (vector-swap! vec i j)
(let ((tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)))
(define (vector-reverse! vec . o)
(let lp ((left (if (pair? o) (car o) 0))
(right (- (if (and (pair? o) (pair? (cdr o)))
(cadr o)
(vector-length vec))
1)))
(cond
((>= left right) (if #f #f))
(else
(vector-swap! vec left right)
(lp (+ left 1) (- right 1))))))
(define (vector-reverse-copy! to at from . o)
(let ((start (if (pair? o) (car o) 0))
(end (if (and (pair? o) (pair? (cdr o)))
(cadr o)
(vector-length from))))
(vector-copy! to at from start end)
(vector-reverse! to at (+ at (- end start)))))
(define (reverse-vector->list vec . o)
(reverse (apply vector->list vec o)))
(define (reverse-list->vector ls)
(list->vector (reverse ls)))
(define (vector-partition pred? vec)
(let* ((len (vector-length vec))
(res (make-vector len)))
(let lp ((i 0) (left 0) (right (- len 1)))
(cond
((= i len)
(if (< left len)
(vector-reverse! res left))
(values res left))
(else
(let ((x (vector-ref vec i)))
(cond
((pred? x)
(vector-set! res left x)
(lp (+ i 1) (+ left 1) right))
(else
(vector-set! res right x)
(lp (+ i 1) left (- right 1))))))))))
|
|
ae0b39cd82f99d17f584df37fd5375c308397112a86615bbca5346cc0bcfdc74 | tmattio/inquire | prompt_input.ml | module Input_buffer = struct
let create () = ref ""
let is_empty t = !t = ""
let add_char t chr = t := !t ^ Char.escaped chr
let rm_last_char t =
if is_empty t then
()
else
t := String.sub !t 0 (String.length !t - 1)
let get t = !t
let print t =
let input = !t in
print_string input;
flush stdout
let reset t = t := ""
end
let prompt ?validate ?default ?style message =
Utils.print_prompt ?default ?style message;
Ansi.save_cursor ();
let buf = Input_buffer.create () in
let print_input () =
Ansi.restore_cursor ();
Ansi.erase Ansi.Eol;
Input_buffer.print buf
in
let validate = match validate with None -> fun x -> Ok x | Some fn -> fn in
let reset () =
Ansi.restore_cursor ();
Ansi.erase Ansi.Eol;
Input_buffer.reset buf
in
let rec aux () =
let ch = Char.code (input_char stdin) in
match ch, default with
| 10, Some default ->
(* Enter *)
if Input_buffer.is_empty buf then (
Utils.erase_n_chars (3 + String.length default);
print_endline default;
flush stdout;
default)
else
let input = Input_buffer.get buf in
(match validate input with
| Ok output ->
Utils.erase_n_chars (3 + String.length default + String.length input);
print_endline output;
flush stdout;
output
| Error err ->
print_string "\n";
flush stdout;
Utils.print_err err;
reset ();
aux ())
| 10, None when Input_buffer.is_empty buf ->
(* Enter, no input *)
aux ()
| 10, None ->
(* Enter, with input *)
let input = Input_buffer.get buf in
(match validate input with
| Ok output ->
print_string "\n";
flush stdout;
output
| Error err ->
print_string "\n";
flush stdout;
Utils.print_err err;
reset ();
aux ())
| 12, _ ->
(* Handle ^L *)
Ansi.erase Ansi.Screen;
Ansi.set_cursor 1 1;
Utils.print_prompt ?default ?style message;
Ansi.save_cursor ();
print_input ();
aux ()
| 3, _ | 4, _ ->
Handle ^C and ^D
print_string "\n";
flush stdout;
Exit with an exception so we can catch it and revert the changes on
stdin .
stdin. *)
Utils.user_interrupt ()
| 127, _ ->
DEL
Input_buffer.rm_last_char buf;
print_input ();
aux ()
| code, _ ->
Input_buffer.add_char buf (Char.chr code);
print_input ();
aux ()
in
Utils.with_raw Unix.stdin aux
| null | https://raw.githubusercontent.com/tmattio/inquire/f5bb64ab8d9ed8987c8e529007cf380ab67fd9fd/lib/prompts/prompt_input.ml | ocaml | Enter
Enter, no input
Enter, with input
Handle ^L | module Input_buffer = struct
let create () = ref ""
let is_empty t = !t = ""
let add_char t chr = t := !t ^ Char.escaped chr
let rm_last_char t =
if is_empty t then
()
else
t := String.sub !t 0 (String.length !t - 1)
let get t = !t
let print t =
let input = !t in
print_string input;
flush stdout
let reset t = t := ""
end
let prompt ?validate ?default ?style message =
Utils.print_prompt ?default ?style message;
Ansi.save_cursor ();
let buf = Input_buffer.create () in
let print_input () =
Ansi.restore_cursor ();
Ansi.erase Ansi.Eol;
Input_buffer.print buf
in
let validate = match validate with None -> fun x -> Ok x | Some fn -> fn in
let reset () =
Ansi.restore_cursor ();
Ansi.erase Ansi.Eol;
Input_buffer.reset buf
in
let rec aux () =
let ch = Char.code (input_char stdin) in
match ch, default with
| 10, Some default ->
if Input_buffer.is_empty buf then (
Utils.erase_n_chars (3 + String.length default);
print_endline default;
flush stdout;
default)
else
let input = Input_buffer.get buf in
(match validate input with
| Ok output ->
Utils.erase_n_chars (3 + String.length default + String.length input);
print_endline output;
flush stdout;
output
| Error err ->
print_string "\n";
flush stdout;
Utils.print_err err;
reset ();
aux ())
| 10, None when Input_buffer.is_empty buf ->
aux ()
| 10, None ->
let input = Input_buffer.get buf in
(match validate input with
| Ok output ->
print_string "\n";
flush stdout;
output
| Error err ->
print_string "\n";
flush stdout;
Utils.print_err err;
reset ();
aux ())
| 12, _ ->
Ansi.erase Ansi.Screen;
Ansi.set_cursor 1 1;
Utils.print_prompt ?default ?style message;
Ansi.save_cursor ();
print_input ();
aux ()
| 3, _ | 4, _ ->
Handle ^C and ^D
print_string "\n";
flush stdout;
Exit with an exception so we can catch it and revert the changes on
stdin .
stdin. *)
Utils.user_interrupt ()
| 127, _ ->
DEL
Input_buffer.rm_last_char buf;
print_input ();
aux ()
| code, _ ->
Input_buffer.add_char buf (Char.chr code);
print_input ();
aux ()
in
Utils.with_raw Unix.stdin aux
|
2ab2beca49a0fd38d3e8a4f49fb4bcb4137970f3f3a8a4a34d631048d704633f | chicken-mobile/chicken-sdl2-android-builder | audio.scm | ;;
chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2
;;
Copyright © 2013 , 2015 - 2016 .
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR FOR ANY DIRECT ,
INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
(export SDL_AudioInit
SDL_AudioQuit
SDL_GetAudioDeviceName
SDL_GetAudioDeviceStatus
SDL_GetAudioDriver
SDL_GetAudioStatus
SDL_GetCurrentAudioDriver
SDL_GetNumAudioDevices
SDL_GetNumAudioDrivers
SDL_OpenAudioDevice
SDL_CloseAudioDevice
SDL_PauseAudioDevice
SDL_LockAudioDevice
SDL_UnlockAudioDevice
SDL_BuildAudioCVT
SDL_ConvertAudio
SDL_LoadWAV
;; SDL_LoadWAV_RW
SDL_FreeWAV
SDL_MixAudio
SDL_MixAudioFormat
;; legacy
SDL_OpenAudio
SDL_CloseAudio
SDL_PauseAudio
SDL_LockAudio
SDL_UnlockAudio
;; Audio format C-macros
SDL_AUDIO_BITSIZE
SDL_AUDIO_ISFLOAT
SDL_AUDIO_ISINT
SDL_AUDIO_ISBIGENDIAN
SDL_AUDIO_ISLITTLEENDIAN
SDL_AUDIO_ISSIGNED
SDL_AUDIO_ISUNSIGNED)
(define-function-binding SDL_AudioInit
return: (Sint32 zero-if-success)
args: ((c-string driver-name)))
(define-function-binding SDL_AudioQuit)
(define-function-binding SDL_GetAudioDeviceName
return: (c-string device-name-or-null)
args: ((Sint32 index)
(Sint32 iscapture)))
(define-function-binding SDL_GetAudioDeviceStatus
return: (SDL_AudioStatus status)
args: ((SDL_AudioDeviceID dev)))
(define-function-binding SDL_GetAudioDriver
return: (c-string driver-name-or-null)
args: ((Sint32 index)))
(define-function-binding SDL_GetAudioStatus
return: (SDL_AudioStatus status))
(define-function-binding SDL_GetCurrentAudioDriver
return: (c-string driver-name-or-null))
(define-function-binding SDL_GetNumAudioDevices
return: (Sint32 num-devices)
args: ((Sint32 iscapture)))
(define-function-binding SDL_GetNumAudioDrivers
return: (Sint32 num-drivers))
(define-function-binding SDL_OpenAudioDevice
return: (SDL_AudioDeviceID device-id)
args: ((c-string device)
(Sint32 iscapture)
(SDL_AudioSpec* desired-in-out)
(SDL_AudioSpec* obtained-out)
(Sint32 allowed-changes)))
(define-function-binding SDL_CloseAudioDevice
args: ((SDL_AudioDeviceID dev)))
(define-function-binding SDL_PauseAudioDevice
args: ((SDL_AudioDeviceID dev)
(Sint32 pause-on)))
(define-function-binding SDL_LockAudioDevice
args: ((SDL_AudioDeviceID dev)))
(define-function-binding SDL_UnlockAudioDevice
args: ((SDL_AudioDeviceID dev)))
(define-function-binding SDL_BuildAudioCVT
return: (Sint32 status)
args: ((SDL_AudioCVT* cvt-out)
(SDL_AudioFormat src-format)
(Uint8 src-channels)
(Sint32 src-rate)
(SDL_AudioFormat dst-format)
(Uint8 dst-channels)
(Sint32 dst-rate)))
(define-function-binding SDL_ConvertAudio
return: (Sint32 zero-if-success)
args: ((SDL_AudioCVT* cvt)))
(define-function-binding SDL_LoadWAV
return: (SDL_AudioSpec* actual-spec-or-null)
args: ((c-string file)
(SDL_AudioSpec* desired-spec)
((c-pointer Uint8*) audio-buf-out)
(Uint32* audio-len-out)))
( define - function - binding SDL_LoadWAV_RW
return : ( SDL_AudioSpec * actual - spec - or - null )
;; args: ((SDL_RWops* file)
( Sint32 freesrc )
( SDL_AudioSpec * desired - spec )
;; ((c-pointer Uint8*) audio-buf-out)
( Uint32 * audio - len - out ) ) )
(define-function-binding SDL_FreeWAV
args: ((Uint8* audio-buf)))
(define-function-binding SDL_MixAudio
args: ((Uint8* dst-out)
(Uint8* src)
(Uint32 len)
(Sint32 volume)))
(define-function-binding SDL_MixAudioFormat
args: ((Uint8* dst-out)
(Uint8* src)
(SDL_AudioFormat desired-format)
(Uint32 len)
(Sint32 volume)))
(define-function-binding SDL_OpenAudio
return: (Sint32 zero-if-success)
args: ((SDL_AudioSpec* desired-in-out)
(SDL_AudioSpec* obtained-out)))
(define-function-binding SDL_CloseAudio)
(define-function-binding SDL_PauseAudio
args: ((Sint32 pause-on)))
(define-function-binding SDL_LockAudio)
(define-function-binding SDL_UnlockAudio)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; AUDIO FORMAT C-MACROS
(define-function-binding* SDL_AUDIO_BITSIZE
return: (Uint32 bitsize)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_BITSIZE(value));")
(define-function-binding* SDL_AUDIO_ISFLOAT
return: (Uint32 isfloat)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISFLOAT(value));")
(define-function-binding* SDL_AUDIO_ISINT
return: (Uint32 isint)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISINT(value));")
(define-function-binding* SDL_AUDIO_ISBIGENDIAN
return: (Uint32 isbigendian)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISBIGENDIAN(value));")
(define-function-binding* SDL_AUDIO_ISLITTLEENDIAN
return: (Uint32 islittleendian)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISLITTLEENDIAN(value));")
(define-function-binding* SDL_AUDIO_ISSIGNED
return: (Uint32 issigned)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISSIGNED(value));")
(define-function-binding* SDL_AUDIO_ISUNSIGNED
return: (Uint32 isunsigned)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISUNSIGNED(value));")
| null | https://raw.githubusercontent.com/chicken-mobile/chicken-sdl2-android-builder/90ef1f0ff667737736f1932e204d29ae615a00c4/eggs/sdl2/lib/sdl2-internals/functions/audio.scm | scheme |
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
SDL_LoadWAV_RW
legacy
Audio format C-macros
args: ((SDL_RWops* file)
((c-pointer Uint8*) audio-buf-out)
AUDIO FORMAT C-MACROS | chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2
Copyright © 2013 , 2015 - 2016 .
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT HOLDER OR FOR ANY DIRECT ,
INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
(export SDL_AudioInit
SDL_AudioQuit
SDL_GetAudioDeviceName
SDL_GetAudioDeviceStatus
SDL_GetAudioDriver
SDL_GetAudioStatus
SDL_GetCurrentAudioDriver
SDL_GetNumAudioDevices
SDL_GetNumAudioDrivers
SDL_OpenAudioDevice
SDL_CloseAudioDevice
SDL_PauseAudioDevice
SDL_LockAudioDevice
SDL_UnlockAudioDevice
SDL_BuildAudioCVT
SDL_ConvertAudio
SDL_LoadWAV
SDL_FreeWAV
SDL_MixAudio
SDL_MixAudioFormat
SDL_OpenAudio
SDL_CloseAudio
SDL_PauseAudio
SDL_LockAudio
SDL_UnlockAudio
SDL_AUDIO_BITSIZE
SDL_AUDIO_ISFLOAT
SDL_AUDIO_ISINT
SDL_AUDIO_ISBIGENDIAN
SDL_AUDIO_ISLITTLEENDIAN
SDL_AUDIO_ISSIGNED
SDL_AUDIO_ISUNSIGNED)
(define-function-binding SDL_AudioInit
return: (Sint32 zero-if-success)
args: ((c-string driver-name)))
(define-function-binding SDL_AudioQuit)
(define-function-binding SDL_GetAudioDeviceName
return: (c-string device-name-or-null)
args: ((Sint32 index)
(Sint32 iscapture)))
(define-function-binding SDL_GetAudioDeviceStatus
return: (SDL_AudioStatus status)
args: ((SDL_AudioDeviceID dev)))
(define-function-binding SDL_GetAudioDriver
return: (c-string driver-name-or-null)
args: ((Sint32 index)))
(define-function-binding SDL_GetAudioStatus
return: (SDL_AudioStatus status))
(define-function-binding SDL_GetCurrentAudioDriver
return: (c-string driver-name-or-null))
(define-function-binding SDL_GetNumAudioDevices
return: (Sint32 num-devices)
args: ((Sint32 iscapture)))
(define-function-binding SDL_GetNumAudioDrivers
return: (Sint32 num-drivers))
(define-function-binding SDL_OpenAudioDevice
return: (SDL_AudioDeviceID device-id)
args: ((c-string device)
(Sint32 iscapture)
(SDL_AudioSpec* desired-in-out)
(SDL_AudioSpec* obtained-out)
(Sint32 allowed-changes)))
(define-function-binding SDL_CloseAudioDevice
args: ((SDL_AudioDeviceID dev)))
(define-function-binding SDL_PauseAudioDevice
args: ((SDL_AudioDeviceID dev)
(Sint32 pause-on)))
(define-function-binding SDL_LockAudioDevice
args: ((SDL_AudioDeviceID dev)))
(define-function-binding SDL_UnlockAudioDevice
args: ((SDL_AudioDeviceID dev)))
(define-function-binding SDL_BuildAudioCVT
return: (Sint32 status)
args: ((SDL_AudioCVT* cvt-out)
(SDL_AudioFormat src-format)
(Uint8 src-channels)
(Sint32 src-rate)
(SDL_AudioFormat dst-format)
(Uint8 dst-channels)
(Sint32 dst-rate)))
(define-function-binding SDL_ConvertAudio
return: (Sint32 zero-if-success)
args: ((SDL_AudioCVT* cvt)))
(define-function-binding SDL_LoadWAV
return: (SDL_AudioSpec* actual-spec-or-null)
args: ((c-string file)
(SDL_AudioSpec* desired-spec)
((c-pointer Uint8*) audio-buf-out)
(Uint32* audio-len-out)))
( define - function - binding SDL_LoadWAV_RW
return : ( SDL_AudioSpec * actual - spec - or - null )
( Sint32 freesrc )
( SDL_AudioSpec * desired - spec )
( Uint32 * audio - len - out ) ) )
(define-function-binding SDL_FreeWAV
args: ((Uint8* audio-buf)))
(define-function-binding SDL_MixAudio
args: ((Uint8* dst-out)
(Uint8* src)
(Uint32 len)
(Sint32 volume)))
(define-function-binding SDL_MixAudioFormat
args: ((Uint8* dst-out)
(Uint8* src)
(SDL_AudioFormat desired-format)
(Uint32 len)
(Sint32 volume)))
(define-function-binding SDL_OpenAudio
return: (Sint32 zero-if-success)
args: ((SDL_AudioSpec* desired-in-out)
(SDL_AudioSpec* obtained-out)))
(define-function-binding SDL_CloseAudio)
(define-function-binding SDL_PauseAudio
args: ((Sint32 pause-on)))
(define-function-binding SDL_LockAudio)
(define-function-binding SDL_UnlockAudio)
(define-function-binding* SDL_AUDIO_BITSIZE
return: (Uint32 bitsize)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_BITSIZE(value));")
(define-function-binding* SDL_AUDIO_ISFLOAT
return: (Uint32 isfloat)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISFLOAT(value));")
(define-function-binding* SDL_AUDIO_ISINT
return: (Uint32 isint)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISINT(value));")
(define-function-binding* SDL_AUDIO_ISBIGENDIAN
return: (Uint32 isbigendian)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISBIGENDIAN(value));")
(define-function-binding* SDL_AUDIO_ISLITTLEENDIAN
return: (Uint32 islittleendian)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISLITTLEENDIAN(value));")
(define-function-binding* SDL_AUDIO_ISSIGNED
return: (Uint32 issigned)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISSIGNED(value));")
(define-function-binding* SDL_AUDIO_ISUNSIGNED
return: (Uint32 isunsigned)
args: ((Uint32 value))
body: "C_return(SDL_AUDIO_ISUNSIGNED(value));")
|
be427abc336a22f99ae24aa597504a87ee9cf495c13db1699d7d061ce1f31ca1 | roswell/roswell | install-clisp-head.lisp | (roswell:include "util-install-quicklisp")
(defpackage :roswell.install.clisp-head
(:use :cl :roswell.install :roswell.util :roswell.locations))
(in-package :roswell.install.clisp-head)
(defun clisp-head-variant ()
(let ((uname (uname))
(variant (opt "variant")))
(cond (variant variant)
((and (equal uname "linux"))
"glibc2.19")
(t "")))) ;; TBD
(defun clisp-head-get-version ()
(format *error-output* "Checking version to install....~%")
(let ((elts
(let ((file (merge-pathnames "tmp/clisp_head.tsv" (homedir))))
(download (clisp-head-version-uri) file :interval 3600)
(mapcar (lambda (x) (uiop:split-string x :separator '(#\tab)))
(uiop:read-file-lines file))))
(uname (uname))
(uname-m (uname-m))
(variant (clisp-head-variant)))
(mapcar 'third (remove-if-not (lambda (x)
(and (equal (first x) uname)
(equal (second x) uname-m)
(equal (fourth x) variant)
))
elts))))
(defun clisp-head-argv-parse (argv)
(let ((uname (uname))
(uname-m (uname-m)))
(set-opt "as" (getf argv :version))
(set-opt "prefix" (merge-pathnames (format nil "impls/~A/~A/~A/~A/" (uname-m) (uname) (getf argv :target) (opt "as")) (homedir)))
(set-opt "src" (merge-pathnames (format nil "src/clisp-~A-~A-~A~A/"
(getf argv :version)
uname-m
uname
(let ((var (clisp-head-variant)))
(if (zerop (length var))
""
(format nil "-~A" var))))
(homedir))))
(cons t argv))
(defun clisp-head-download (argv)
(set-opt "download.uri" (format nil "~@{~A~}" (clisp-head-uri) (getf argv :version)
"/clisp-"
(getf argv :version) "-"
(uname-m) "-"
(uname)
(let ((var (clisp-head-variant)))
(if (zerop (length var))
""
(format nil "-~A" var)))
"-binary"
#-win32 ".tar.bz2"
#+win32 ".msi"))
(set-opt "download.archive" (let ((pos (position #\/ (opt "download.uri") :from-end t)))
(when pos
(merge-pathnames (format nil "archives/~A" (subseq (opt "download.uri") (1+ pos))) (homedir)))))
`((,(opt "download.archive") ,(opt "download.uri"))))
#-win32
(defun clisp-head-expand (argv)
(let ((impls (merge-pathnames (format nil "impls/~A/~A/clisp-head/" (uname-m) (uname)) (homedir))))
(cond
(t
(format t "~%Extracting archive:~A~%" (opt "download.archive"))
(expand (opt "download.archive")
(ensure-directories-exist impls))))
(ql-impl-util:rename-directory
(merge-pathnames (format nil "clisp-~A-~A-~A~A/"
(opt "as")
(uname-m)
(uname)
(let ((var (clisp-head-variant)))
(if (zerop (length var))
""
(format nil "-~A" var))))
impls)
(merge-pathnames (format nil "~A/" (opt "as")) impls)))
(cons t argv))
(defun clisp-head-help (argv)
(format t "no options for clisp-head~%")
(cons t argv))
(defun clisp-head (type)
(case type
(:help '(clisp-head-help))
(:install `(,(decide-version 'clisp-head-get-version)
clisp-head-argv-parse
start
,(decide-download 'clisp-head-download)
clisp-head-expand
setup))
(:list 'clisp-head-get-version)))
| null | https://raw.githubusercontent.com/roswell/roswell/fda4e6563c65f64d5a5b08f12691e2aca17c13fb/lisp/install-clisp-head.lisp | lisp | TBD | (roswell:include "util-install-quicklisp")
(defpackage :roswell.install.clisp-head
(:use :cl :roswell.install :roswell.util :roswell.locations))
(in-package :roswell.install.clisp-head)
(defun clisp-head-variant ()
(let ((uname (uname))
(variant (opt "variant")))
(cond (variant variant)
((and (equal uname "linux"))
"glibc2.19")
(defun clisp-head-get-version ()
(format *error-output* "Checking version to install....~%")
(let ((elts
(let ((file (merge-pathnames "tmp/clisp_head.tsv" (homedir))))
(download (clisp-head-version-uri) file :interval 3600)
(mapcar (lambda (x) (uiop:split-string x :separator '(#\tab)))
(uiop:read-file-lines file))))
(uname (uname))
(uname-m (uname-m))
(variant (clisp-head-variant)))
(mapcar 'third (remove-if-not (lambda (x)
(and (equal (first x) uname)
(equal (second x) uname-m)
(equal (fourth x) variant)
))
elts))))
(defun clisp-head-argv-parse (argv)
(let ((uname (uname))
(uname-m (uname-m)))
(set-opt "as" (getf argv :version))
(set-opt "prefix" (merge-pathnames (format nil "impls/~A/~A/~A/~A/" (uname-m) (uname) (getf argv :target) (opt "as")) (homedir)))
(set-opt "src" (merge-pathnames (format nil "src/clisp-~A-~A-~A~A/"
(getf argv :version)
uname-m
uname
(let ((var (clisp-head-variant)))
(if (zerop (length var))
""
(format nil "-~A" var))))
(homedir))))
(cons t argv))
(defun clisp-head-download (argv)
(set-opt "download.uri" (format nil "~@{~A~}" (clisp-head-uri) (getf argv :version)
"/clisp-"
(getf argv :version) "-"
(uname-m) "-"
(uname)
(let ((var (clisp-head-variant)))
(if (zerop (length var))
""
(format nil "-~A" var)))
"-binary"
#-win32 ".tar.bz2"
#+win32 ".msi"))
(set-opt "download.archive" (let ((pos (position #\/ (opt "download.uri") :from-end t)))
(when pos
(merge-pathnames (format nil "archives/~A" (subseq (opt "download.uri") (1+ pos))) (homedir)))))
`((,(opt "download.archive") ,(opt "download.uri"))))
#-win32
(defun clisp-head-expand (argv)
(let ((impls (merge-pathnames (format nil "impls/~A/~A/clisp-head/" (uname-m) (uname)) (homedir))))
(cond
(t
(format t "~%Extracting archive:~A~%" (opt "download.archive"))
(expand (opt "download.archive")
(ensure-directories-exist impls))))
(ql-impl-util:rename-directory
(merge-pathnames (format nil "clisp-~A-~A-~A~A/"
(opt "as")
(uname-m)
(uname)
(let ((var (clisp-head-variant)))
(if (zerop (length var))
""
(format nil "-~A" var))))
impls)
(merge-pathnames (format nil "~A/" (opt "as")) impls)))
(cons t argv))
(defun clisp-head-help (argv)
(format t "no options for clisp-head~%")
(cons t argv))
(defun clisp-head (type)
(case type
(:help '(clisp-head-help))
(:install `(,(decide-version 'clisp-head-get-version)
clisp-head-argv-parse
start
,(decide-download 'clisp-head-download)
clisp-head-expand
setup))
(:list 'clisp-head-get-version)))
|
3ee672ef30a876c7093a62f8777d35e5fd2971d16284e76ee40698bc85076e9b | facebook/duckling | Tests.hs | 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.
module Duckling.AmountOfMoney.VI.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.AmountOfMoney.VI.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "VI Tests"
[ makeCorpusTest [Seal AmountOfMoney] corpus
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/AmountOfMoney/VI/Tests.hs | haskell | 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. | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.AmountOfMoney.VI.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.AmountOfMoney.VI.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "VI Tests"
[ makeCorpusTest [Seal AmountOfMoney] corpus
]
|
e51665699aff42a78ce12d45a874f3d3499b23a9bea6c7093c2d8c9a66e4c34c | Clozure/ccl-tests | documentation.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Tue Dec 14 07:30:01 2004
;;;; Contains: Tests of DOCUMENTATION
(in-package :cl-test)
;;; documentation (x function) (doc-type (eql 't))
(deftest documentation.function.t.1
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(documentation (symbol-function sym) t))
nil)
(deftest documentation.function.t.2
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(let ((fn (symbol-function sym))
(doc "FOO1"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn t))
(equal doc (documentation fn t)))))))
"FOO1")
(deftest documentation.function.t.3
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(documentation (macro-function sym) t))
nil)
(deftest documentation.function.t.4
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(let ((fn (macro-function sym))
(doc "FOO2"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn t))
(equal doc (documentation fn t)))))))
"FOO2")
(deftest documentation.function.t.6
(let* ((sym (gensym))
(fn (eval `#'(lambda () ',sym)))
(doc "FOO3"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn t))
(equal doc (documentation fn t))))))
"FOO3")
(deftest documentation.function.t.6a
(let* ((sym (gensym))
(fn (compile nil `(lambda () ',sym)))
(doc "FOO3A"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn t))
(equal doc (documentation fn t))))))
"FOO3A")
Reorder 5 , 5a and 6 , 6a to expose possible interaction bug
(deftest documentation.function.t.5
(let* ((sym (gensym))
(fn (eval `#'(lambda () ',sym))))
(documentation fn t))
nil)
(deftest documentation.function.t.5a
(let* ((sym (gensym))
(fn (compile nil `(lambda () ',sym))))
(documentation fn t))
nil)
(deftest documentation.function.t.7
(let* ((sym (gensym))
(fn (eval `(defgeneric ,sym (x)))))
(documentation fn t))
nil)
(deftest documentation.function.t.8
(let* ((sym (gensym))
(fn (eval `(defgeneric ,sym (x))))
(doc "FOO4"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn t))
(equal doc (documentation fn t))))))
"FOO4")
(deftest documentation.function.t.9
(loop for s in *cl-function-symbols*
for fn = (symbol-function s)
for doc = (documentation fn t)
unless (or (null doc) (string doc))
collect (list s doc))
nil)
(deftest documentation.function.t.10
(loop for s in *cl-accessor-symbols*
for fn = (symbol-function s)
for doc = (documentation fn t)
unless (or (null doc) (string doc))
collect (list s doc))
nil)
(deftest documentation.function.t.11
(loop for s in *cl-macro-symbols*
for fn = (macro-function s)
for doc = (documentation fn t)
unless (or (null doc) (string doc))
collect (list s doc))
nil)
(deftest documentation.function.t.12
(loop for s in *cl-standard-generic-function-symbols*
for fn = (symbol-function s)
for doc = (documentation fn t)
unless (or (null doc) (string doc))
collect (list s doc))
nil)
;;; documentation (x function) (doc-type (eql 'function))
(deftest documentation.function.function.1
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(documentation (symbol-function sym) 'function))
nil)
(deftest documentation.function.function.2
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(let ((fn (symbol-function sym))
(doc "FOO5"))
(multiple-value-prog1
(setf (documentation fn 'function) (copy-seq doc))
(assert (or (null (documentation fn 'function))
(equal doc (documentation fn 'function)))))))
"FOO5")
(deftest documentation.function.function.3
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(documentation (macro-function sym) 'function))
nil)
(deftest documentation.function.function.4
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(let ((fn (macro-function sym))
(doc "FOO6"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn 'function))
(equal doc (documentation fn 'function)))))))
"FOO6")
(deftest documentation.function.function.5
(let* ((sym (gensym))
(fn (eval `(defgeneric ,sym (x)))))
(documentation fn 'function))
nil)
(deftest documentation.function.function.8
(let* ((sym (gensym))
(fn (eval `(defgeneric ,sym (x))))
(doc "FOO4A"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn 'function))
(equal doc (documentation fn 'function))))))
"FOO4A")
;;; documentation (x list) (doc-type (eql 'function))
(deftest documentation.list.function.1
(let* ((sym (gensym)))
(eval `(defun (setf ,sym) (&rest args) (declare (ignore args)) nil))
(documentation `(setf ,sym) 'function))
nil)
(deftest documentation.list.function.2
(let* ((sym (gensym)))
(eval `(defun (setf ,sym) (&rest args) (declare (ignore args)) nil))
(let ((fn `(setf ,sym))
(doc "FOO7"))
(multiple-value-prog1
(setf (documentation fn 'function) (copy-seq doc))
(assert (or (null (documentation fn 'function))
(equal doc (documentation fn 'function)))))))
"FOO7")
;;; documentation (x list) (doc-type (eql 'compiler-macro))
(deftest documentation.list.compiler-macro.1
(let* ((sym (gensym)))
(eval `(define-compiler-macro (setf ,sym) (&rest args) (declare (ignore args)) nil))
(documentation `(setf ,sym) 'compiler-macro))
nil)
(deftest documentation.list.compiler-macro.2
(let* ((sym (gensym)))
(eval `(define-compiler-macro (setf ,sym) (&rest args) (declare (ignore args)) nil))
(let ((fn `(setf ,sym))
(doc "FOO8"))
(multiple-value-prog1
(setf (documentation fn 'compiler-macro) (copy-seq doc))
(assert (or (null (documentation fn 'function))
(equal doc (documentation fn 'compiler-macro)))))))
"FOO8")
;;; documentation (x symbol) (doc-type (eql 'function))
(deftest documentation.symbol.function.1
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(documentation sym 'function))
nil)
(deftest documentation.symbol.function.2
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(let ((doc "FOO9"))
(multiple-value-prog1
(setf (documentation sym 'function) (copy-seq doc))
(assert (or (null (documentation sym 'function))
(equal doc (documentation sym 'function)))))))
"FOO9")
(deftest documentation.symbol.function.3
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(documentation sym 'function))
nil)
(deftest documentation.symbol.function.4
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(let ((doc "FOO9A"))
(multiple-value-prog1
(setf (documentation sym 'function) (copy-seq doc))
(assert (or (null (documentation sym 'function))
(equal doc (documentation sym 'function)))))))
"FOO9A")
(deftest documentation.symbol.function.5
(let* ((sym (gensym)))
(eval `(defgeneric ,sym (x)))
(documentation sym 'function))
nil)
(deftest documentation.symbol.function.6
(let* ((sym (gensym)))
(eval `(defgeneric ,sym (x)))
(let ((doc "FOO9B"))
(multiple-value-prog1
(setf (documentation sym 'function) (copy-seq doc))
(assert (or (null (documentation sym 'function))
(equal doc (documentation sym 'function)))))))
"FOO9B")
(deftest documentation.symbol.function.7
(loop for s in *cl-special-operator-symbols*
for doc = (documentation s 'function)
unless (or (null doc) (stringp doc))
collect (list s doc))
nil)
(deftest documentation.symbol.function.8
(loop for s in *cl-function-or-accessor-symbols*
for doc = (documentation s 'function)
unless (or (null doc) (stringp doc))
collect (list s doc))
nil)
(deftest documentation.symbol.function.9
(loop for s in *cl-macro-symbols*
for doc = (documentation s 'function)
unless (or (null doc) (stringp doc))
collect (list s doc))
nil)
;;; documentation (x symbol) (doc-type (eql 'compiler-macro))
(deftest documentation.symbol.compiler-macro.1
(let* ((sym (gensym)))
(eval `(define-compiler-macro ,sym (&rest args) (declare (ignore args)) nil))
(documentation sym 'compiler-macro))
nil)
(deftest documentation.symbol.compiler-macro.2
(let* ((sym (gensym)))
(eval `(define-compiler-macro ,sym (&rest args) (declare (ignore args)) nil))
(let ((doc "FOO10"))
(multiple-value-prog1
(setf (documentation sym 'compiler-macro) (copy-seq doc))
(assert (or (null (documentation sym 'compiler-macro))
(equal doc (documentation sym 'compiler-macro)))))))
"FOO10")
documentation ( x symbol ) ( doc - type ( eql ' setf ) )
(deftest documentation.symbol.setf.1
(let* ((sym (gensym))
(doc "FOO11"))
(eval `(defun ,sym () (declare (special *x*)) *x*))
(eval `(define-setf-expander ,sym ()
(let ((g (gensym)))
(values nil nil (list g) `(locally (declare (special *x*)) (setf *x* ,g))
'(locally (declare (special *x*)) *x*)))))
(multiple-value-prog1
(values
(documentation sym 'setf)
(setf (documentation sym 'setf) (copy-seq doc)))
(assert (or (null (documentation sym 'setf))
(equal doc (documentation sym 'setf))))))
nil "FOO11")
(deftest documentation.symbol.setf.2
(let* ((sym (gensym))
(doc "FOO12"))
(eval `(defmacro ,sym () `(locally (declare (special *x*)) *x*)))
(eval `(define-setf-expander ,sym ()
(let ((g (gensym)))
(values nil nil (list g) `(locally (declare (special *x*)) (setf *x* ,g))
'(locally (declare (special *x*)) *x*)))))
(multiple-value-prog1
(values
(documentation sym 'setf)
(setf (documentation sym 'setf) (copy-seq doc)))
(assert (or (null (documentation sym 'setf))
(equal doc (documentation sym 'setf))))))
nil "FOO12")
;;; documentation (x method-combination) (doc-type (eql 't))
;;; documentation (x method-combination) (doc-type (eql 'method-combination))
;;; There's no portable way to test those, since there's no portable way to
;;; get a method combination object
;;; documentation (x symbol) (doc-type (eql 'method-combination))
(deftest documentation.symbol.method-combination.1
(let* ((sym (gensym))
(doc "FOO13"))
(eval `(define-method-combination ,sym :identity-with-one-argument t))
(multiple-value-prog1
(values
(documentation sym 'method-combination)
(setf (documentation sym 'method-combination) (copy-seq doc)))
(assert (or (null (documentation sym 'method-combination))
(equal doc (documentation sym 'method-combination))))))
nil "FOO13")
;;; documentation (x standard-method) (doc-type (eql 't))
(deftest documentation.standard-method.t.1
(let* ((sym (gensym))
(doc "FOO14"))
(eval `(defgeneric ,sym (x)))
(let ((method (eval `(defmethod ,sym ((x t)) nil))))
(multiple-value-prog1
(values
(documentation method t)
(setf (documentation method t) (copy-seq doc)))
(assert (or (null (documentation method 't))
(equal doc (documentation method 't)))))))
nil "FOO14")
;;; documentation (x package) (doc-type (eql 't))
(deftest documentation.package.t.1
(let ((package-name "PACKAGE-NAME-FOR-DOCUMENATION-TESTS-1"))
(unwind-protect
(progn
(eval `(defpackage ,package-name (:use)))
(let ((pkg (find-package package-name))
(doc "FOO15"))
(assert pkg)
(multiple-value-prog1
(values
(documentation pkg t)
(setf (documentation pkg t) (copy-seq doc)))
(assert (or (null (documentation pkg t))
(equal doc (documentation pkg t)))))))
(delete-package package-name)))
nil "FOO15")
;;; documentation (x standard-class) (doc-type (eql 't))
(deftest documentation.standard-class.t.1
(let* ((sym (gensym))
(class-form `(defclass ,sym () ())))
(eval class-form)
(let ((class (find-class sym))
(doc "FOO16"))
(multiple-value-prog1
(values
(documentation class t)
(setf (documentation class t) (copy-seq doc)))
(assert (or (null (documentation class t))
(equal doc (documentation class t)))))))
nil "FOO16")
;;; documentation (x standard-class) (doc-type (eql 'type))
(deftest documentation.standard-class.type.1
(let* ((sym (gensym))
(class-form `(defclass ,sym () ())))
(eval class-form)
(let ((class (find-class sym))
(doc "FOO17"))
(multiple-value-prog1
(values
(documentation class 'type)
(setf (documentation class 'type) (copy-seq doc)))
(assert (or (null (documentation class 'type))
(equal doc (documentation class 'type)))))))
nil "FOO17")
;;; documentation (x structure-class) (doc-type (eql 't))
(deftest documentation.struct-class.t.1
(let* ((sym (gensym))
(class-form `(defstruct ,sym a b c)))
(eval class-form)
(let ((class (find-class sym))
(doc "FOO18"))
(multiple-value-prog1
(values
(documentation class t)
(setf (documentation class t) (copy-seq doc)))
(assert (or (null (documentation class t))
(equal doc (documentation class t)))))))
nil "FOO18")
;;; documentation (x structure-class) (doc-type (eql 'type))
(deftest documentation.struct-class.type.1
(let* ((sym (gensym))
(class-form `(defstruct ,sym a b c)))
(eval class-form)
(let ((class (find-class sym))
(doc "FOO19"))
(multiple-value-prog1
(values
(documentation class 'type)
(setf (documentation class 'type) (copy-seq doc)))
(assert (or (null (documentation class 'type))
(equal doc (documentation class 'type)))))))
nil "FOO19")
;;; documentation (x symbol) (doc-type (eql 'type))
(deftest documentation.symbol.type.1
(let* ((sym (gensym))
(class-form `(defclass ,sym () ()))
(doc "FOO20"))
(eval class-form)
(multiple-value-prog1
(values
(documentation sym 'type)
(setf (documentation sym 'type) (copy-seq doc)))
(assert (or (null (documentation sym 'type))
(equal doc (documentation sym 'type))))))
nil "FOO20")
(deftest documentation.symbol.type.2
(let* ((sym (gensym))
(class-form `(defstruct ,sym a b c))
(doc "FOO21"))
(eval class-form)
(multiple-value-prog1
(values
(documentation sym 'type)
(setf (documentation sym 'type) (copy-seq doc)))
(assert (or (null (documentation sym 'type))
(equal doc (documentation sym 'type))))))
nil "FOO21")
(deftest documentation.symbol.type.3
(let* ((sym (gensym))
(type-form `(deftype ,sym () t))
(doc "FOO21A"))
(eval type-form)
(multiple-value-prog1
(values
(documentation sym 'type)
(setf (documentation sym 'type) (copy-seq doc)))
(assert (or (null (documentation sym 'type))
(equal doc (documentation sym 'type))))))
nil "FOO21A")
(deftest documentation.symbol.type.4
(loop for s in *cl-all-type-symbols*
for doc = (documentation s 'type)
unless (or (null doc) (stringp doc))
collect (list doc))
nil)
;;; documentation (x symbol) (doc-type (eql 'structure))
(deftest documentation.symbol.structure.1
(let* ((sym (gensym))
(class-form `(defstruct ,sym a b c))
(doc "FOO22"))
(eval class-form)
(multiple-value-prog1
(values
(documentation sym 'structure)
(setf (documentation sym 'structure) (copy-seq doc)))
(assert (or (null (documentation sym 'structure))
(equal doc (documentation sym 'structure))))))
nil "FOO22")
(deftest documentation.symbol.structure.2
(let* ((sym (gensym))
(class-form `(defstruct (,sym (:type list)) a b c))
(doc "FOO23"))
(eval class-form)
(multiple-value-prog1
(values
(documentation sym 'structure)
(setf (documentation sym 'structure) (copy-seq doc)))
(assert (or (null (documentation sym 'structure))
(equal doc (documentation sym 'structure))))))
nil "FOO23")
(deftest documentation.symbol.structure.3
(let* ((sym (gensym))
(class-form `(defstruct (,sym (:type vector)) a b c))
(doc "FOO24"))
(eval class-form)
(multiple-value-prog1
(values
(documentation sym 'structure)
(setf (documentation sym 'structure) (copy-seq doc)))
(assert (or (null (documentation sym 'structure))
(equal doc (documentation sym 'structure))))))
nil "FOO24")
;;; documentation (x symbol) (doc-type (eql 'variable))
(deftest documentation.symbol.variable.1
(let* ((sym (gensym))
(form `(defvar ,sym))
(doc "FOO25"))
(eval form)
(multiple-value-prog1
(values
(documentation sym 'variable)
(setf (documentation sym 'variable) (copy-seq doc)))
(assert (or (null (documentation sym 'variable))
(equal doc (documentation sym 'variable))))))
nil "FOO25")
(deftest documentation.symbol.variable.2
(let* ((sym (gensym))
(form `(defvar ,sym t))
(doc "FOO26"))
(eval form)
(multiple-value-prog1
(values
(documentation sym 'variable)
(setf (documentation sym 'variable) (copy-seq doc)))
(assert (or (null (documentation sym 'variable))
(equal doc (documentation sym 'variable))))))
nil "FOO26")
(deftest documentation.symbol.variable.3
(let* ((sym (gensym))
(form `(defparameter ,sym t))
(doc "FOO27"))
(eval form)
(multiple-value-prog1
(values
(documentation sym 'variable)
(setf (documentation sym 'variable) (copy-seq doc)))
(assert (or (null (documentation sym 'variable))
(equal doc (documentation sym 'variable))))))
nil "FOO27")
(deftest documentation.symbol.variable.4
(let* ((sym (gensym))
(form `(defconstant ,sym t))
(doc "FOO27"))
(eval form)
(multiple-value-prog1
(values
(documentation sym 'variable)
(setf (documentation sym 'variable) (copy-seq doc)))
(assert (or (null (documentation sym 'variable))
(equal doc (documentation sym 'variable))))))
nil "FOO27")
(deftest documentation.symbol.variable.5
(loop for s in *cl-variable-symbols*
for doc = (documentation s 'variable)
unless (or (null doc) (stringp doc))
collect (list s doc))
nil)
(deftest documentation.symbol.variable.6
(loop for s in *cl-constant-symbols*
for doc = (documentation s 'variable)
unless (or (null doc) (stringp doc))
collect (list s doc))
nil)
;;; Defining new methods for DOCUMENTATION
(ignore-errors
(defgeneric documentation-test-class-1-doc-accessor (obj))
(defgeneric (setf documentation-test-class-1-doc-accessor) (newdoc obj))
(defclass documentation-test-class-1 () ((my-doc :accessor documentation-test-class-1-doc-accessor
:type (or null string)
:initform nil)))
(defmethod documentation-test-class-1-doc-accessor ((obj documentation-test-class-1) )
(slot-value obj 'my-doc))
(defmethod (setf documentation-test-class-1-doc-accessor) ((newdoc string) (obj documentation-test-class-1))
(setf (slot-value obj 'my-doc) newdoc))
(defmethod documentation ((obj documentation-test-class-1) (doctype (eql t)))
(documentation-test-class-1-doc-accessor obj))
(defmethod (setf documentation) ((newdoc string) (obj documentation-test-class-1) (doctype (eql t)))
(setf (documentation-test-class-1-doc-accessor obj) newdoc)))
(deftest documentation.new-method.1
(let ((obj (make-instance 'documentation-test-class-1)))
(values
(documentation obj t)
(setf (documentation obj t) "FOO28")
(documentation obj t)))
nil "FOO28" "FOO28")
| null | https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/documentation.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of DOCUMENTATION
documentation (x function) (doc-type (eql 't))
documentation (x function) (doc-type (eql 'function))
documentation (x list) (doc-type (eql 'function))
documentation (x list) (doc-type (eql 'compiler-macro))
documentation (x symbol) (doc-type (eql 'function))
documentation (x symbol) (doc-type (eql 'compiler-macro))
documentation (x method-combination) (doc-type (eql 't))
documentation (x method-combination) (doc-type (eql 'method-combination))
There's no portable way to test those, since there's no portable way to
get a method combination object
documentation (x symbol) (doc-type (eql 'method-combination))
documentation (x standard-method) (doc-type (eql 't))
documentation (x package) (doc-type (eql 't))
documentation (x standard-class) (doc-type (eql 't))
documentation (x standard-class) (doc-type (eql 'type))
documentation (x structure-class) (doc-type (eql 't))
documentation (x structure-class) (doc-type (eql 'type))
documentation (x symbol) (doc-type (eql 'type))
documentation (x symbol) (doc-type (eql 'structure))
documentation (x symbol) (doc-type (eql 'variable))
Defining new methods for DOCUMENTATION | Author :
Created : Tue Dec 14 07:30:01 2004
(in-package :cl-test)
(deftest documentation.function.t.1
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(documentation (symbol-function sym) t))
nil)
(deftest documentation.function.t.2
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(let ((fn (symbol-function sym))
(doc "FOO1"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn t))
(equal doc (documentation fn t)))))))
"FOO1")
(deftest documentation.function.t.3
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(documentation (macro-function sym) t))
nil)
(deftest documentation.function.t.4
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(let ((fn (macro-function sym))
(doc "FOO2"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn t))
(equal doc (documentation fn t)))))))
"FOO2")
(deftest documentation.function.t.6
(let* ((sym (gensym))
(fn (eval `#'(lambda () ',sym)))
(doc "FOO3"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn t))
(equal doc (documentation fn t))))))
"FOO3")
(deftest documentation.function.t.6a
(let* ((sym (gensym))
(fn (compile nil `(lambda () ',sym)))
(doc "FOO3A"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn t))
(equal doc (documentation fn t))))))
"FOO3A")
Reorder 5 , 5a and 6 , 6a to expose possible interaction bug
(deftest documentation.function.t.5
(let* ((sym (gensym))
(fn (eval `#'(lambda () ',sym))))
(documentation fn t))
nil)
(deftest documentation.function.t.5a
(let* ((sym (gensym))
(fn (compile nil `(lambda () ',sym))))
(documentation fn t))
nil)
(deftest documentation.function.t.7
(let* ((sym (gensym))
(fn (eval `(defgeneric ,sym (x)))))
(documentation fn t))
nil)
(deftest documentation.function.t.8
(let* ((sym (gensym))
(fn (eval `(defgeneric ,sym (x))))
(doc "FOO4"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn t))
(equal doc (documentation fn t))))))
"FOO4")
(deftest documentation.function.t.9
(loop for s in *cl-function-symbols*
for fn = (symbol-function s)
for doc = (documentation fn t)
unless (or (null doc) (string doc))
collect (list s doc))
nil)
(deftest documentation.function.t.10
(loop for s in *cl-accessor-symbols*
for fn = (symbol-function s)
for doc = (documentation fn t)
unless (or (null doc) (string doc))
collect (list s doc))
nil)
(deftest documentation.function.t.11
(loop for s in *cl-macro-symbols*
for fn = (macro-function s)
for doc = (documentation fn t)
unless (or (null doc) (string doc))
collect (list s doc))
nil)
(deftest documentation.function.t.12
(loop for s in *cl-standard-generic-function-symbols*
for fn = (symbol-function s)
for doc = (documentation fn t)
unless (or (null doc) (string doc))
collect (list s doc))
nil)
(deftest documentation.function.function.1
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(documentation (symbol-function sym) 'function))
nil)
(deftest documentation.function.function.2
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(let ((fn (symbol-function sym))
(doc "FOO5"))
(multiple-value-prog1
(setf (documentation fn 'function) (copy-seq doc))
(assert (or (null (documentation fn 'function))
(equal doc (documentation fn 'function)))))))
"FOO5")
(deftest documentation.function.function.3
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(documentation (macro-function sym) 'function))
nil)
(deftest documentation.function.function.4
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(let ((fn (macro-function sym))
(doc "FOO6"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn 'function))
(equal doc (documentation fn 'function)))))))
"FOO6")
(deftest documentation.function.function.5
(let* ((sym (gensym))
(fn (eval `(defgeneric ,sym (x)))))
(documentation fn 'function))
nil)
(deftest documentation.function.function.8
(let* ((sym (gensym))
(fn (eval `(defgeneric ,sym (x))))
(doc "FOO4A"))
(multiple-value-prog1
(setf (documentation fn t) (copy-seq doc))
(assert (or (null (documentation fn 'function))
(equal doc (documentation fn 'function))))))
"FOO4A")
(deftest documentation.list.function.1
(let* ((sym (gensym)))
(eval `(defun (setf ,sym) (&rest args) (declare (ignore args)) nil))
(documentation `(setf ,sym) 'function))
nil)
(deftest documentation.list.function.2
(let* ((sym (gensym)))
(eval `(defun (setf ,sym) (&rest args) (declare (ignore args)) nil))
(let ((fn `(setf ,sym))
(doc "FOO7"))
(multiple-value-prog1
(setf (documentation fn 'function) (copy-seq doc))
(assert (or (null (documentation fn 'function))
(equal doc (documentation fn 'function)))))))
"FOO7")
(deftest documentation.list.compiler-macro.1
(let* ((sym (gensym)))
(eval `(define-compiler-macro (setf ,sym) (&rest args) (declare (ignore args)) nil))
(documentation `(setf ,sym) 'compiler-macro))
nil)
(deftest documentation.list.compiler-macro.2
(let* ((sym (gensym)))
(eval `(define-compiler-macro (setf ,sym) (&rest args) (declare (ignore args)) nil))
(let ((fn `(setf ,sym))
(doc "FOO8"))
(multiple-value-prog1
(setf (documentation fn 'compiler-macro) (copy-seq doc))
(assert (or (null (documentation fn 'function))
(equal doc (documentation fn 'compiler-macro)))))))
"FOO8")
(deftest documentation.symbol.function.1
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(documentation sym 'function))
nil)
(deftest documentation.symbol.function.2
(let* ((sym (gensym)))
(eval `(defun ,sym () nil))
(let ((doc "FOO9"))
(multiple-value-prog1
(setf (documentation sym 'function) (copy-seq doc))
(assert (or (null (documentation sym 'function))
(equal doc (documentation sym 'function)))))))
"FOO9")
(deftest documentation.symbol.function.3
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(documentation sym 'function))
nil)
(deftest documentation.symbol.function.4
(let* ((sym (gensym)))
(eval `(defmacro ,sym () nil))
(let ((doc "FOO9A"))
(multiple-value-prog1
(setf (documentation sym 'function) (copy-seq doc))
(assert (or (null (documentation sym 'function))
(equal doc (documentation sym 'function)))))))
"FOO9A")
(deftest documentation.symbol.function.5
(let* ((sym (gensym)))
(eval `(defgeneric ,sym (x)))
(documentation sym 'function))
nil)
(deftest documentation.symbol.function.6
(let* ((sym (gensym)))
(eval `(defgeneric ,sym (x)))
(let ((doc "FOO9B"))
(multiple-value-prog1
(setf (documentation sym 'function) (copy-seq doc))
(assert (or (null (documentation sym 'function))
(equal doc (documentation sym 'function)))))))
"FOO9B")
(deftest documentation.symbol.function.7
(loop for s in *cl-special-operator-symbols*
for doc = (documentation s 'function)
unless (or (null doc) (stringp doc))
collect (list s doc))
nil)
(deftest documentation.symbol.function.8
(loop for s in *cl-function-or-accessor-symbols*
for doc = (documentation s 'function)
unless (or (null doc) (stringp doc))
collect (list s doc))
nil)
(deftest documentation.symbol.function.9
(loop for s in *cl-macro-symbols*
for doc = (documentation s 'function)
unless (or (null doc) (stringp doc))
collect (list s doc))
nil)
(deftest documentation.symbol.compiler-macro.1
(let* ((sym (gensym)))
(eval `(define-compiler-macro ,sym (&rest args) (declare (ignore args)) nil))
(documentation sym 'compiler-macro))
nil)
(deftest documentation.symbol.compiler-macro.2
(let* ((sym (gensym)))
(eval `(define-compiler-macro ,sym (&rest args) (declare (ignore args)) nil))
(let ((doc "FOO10"))
(multiple-value-prog1
(setf (documentation sym 'compiler-macro) (copy-seq doc))
(assert (or (null (documentation sym 'compiler-macro))
(equal doc (documentation sym 'compiler-macro)))))))
"FOO10")
documentation ( x symbol ) ( doc - type ( eql ' setf ) )
(deftest documentation.symbol.setf.1
(let* ((sym (gensym))
(doc "FOO11"))
(eval `(defun ,sym () (declare (special *x*)) *x*))
(eval `(define-setf-expander ,sym ()
(let ((g (gensym)))
(values nil nil (list g) `(locally (declare (special *x*)) (setf *x* ,g))
'(locally (declare (special *x*)) *x*)))))
(multiple-value-prog1
(values
(documentation sym 'setf)
(setf (documentation sym 'setf) (copy-seq doc)))
(assert (or (null (documentation sym 'setf))
(equal doc (documentation sym 'setf))))))
nil "FOO11")
(deftest documentation.symbol.setf.2
(let* ((sym (gensym))
(doc "FOO12"))
(eval `(defmacro ,sym () `(locally (declare (special *x*)) *x*)))
(eval `(define-setf-expander ,sym ()
(let ((g (gensym)))
(values nil nil (list g) `(locally (declare (special *x*)) (setf *x* ,g))
'(locally (declare (special *x*)) *x*)))))
(multiple-value-prog1
(values
(documentation sym 'setf)
(setf (documentation sym 'setf) (copy-seq doc)))
(assert (or (null (documentation sym 'setf))
(equal doc (documentation sym 'setf))))))
nil "FOO12")
(deftest documentation.symbol.method-combination.1
(let* ((sym (gensym))
(doc "FOO13"))
(eval `(define-method-combination ,sym :identity-with-one-argument t))
(multiple-value-prog1
(values
(documentation sym 'method-combination)
(setf (documentation sym 'method-combination) (copy-seq doc)))
(assert (or (null (documentation sym 'method-combination))
(equal doc (documentation sym 'method-combination))))))
nil "FOO13")
(deftest documentation.standard-method.t.1
(let* ((sym (gensym))
(doc "FOO14"))
(eval `(defgeneric ,sym (x)))
(let ((method (eval `(defmethod ,sym ((x t)) nil))))
(multiple-value-prog1
(values
(documentation method t)
(setf (documentation method t) (copy-seq doc)))
(assert (or (null (documentation method 't))
(equal doc (documentation method 't)))))))
nil "FOO14")
(deftest documentation.package.t.1
(let ((package-name "PACKAGE-NAME-FOR-DOCUMENATION-TESTS-1"))
(unwind-protect
(progn
(eval `(defpackage ,package-name (:use)))
(let ((pkg (find-package package-name))
(doc "FOO15"))
(assert pkg)
(multiple-value-prog1
(values
(documentation pkg t)
(setf (documentation pkg t) (copy-seq doc)))
(assert (or (null (documentation pkg t))
(equal doc (documentation pkg t)))))))
(delete-package package-name)))
nil "FOO15")
(deftest documentation.standard-class.t.1
(let* ((sym (gensym))
(class-form `(defclass ,sym () ())))
(eval class-form)
(let ((class (find-class sym))
(doc "FOO16"))
(multiple-value-prog1
(values
(documentation class t)
(setf (documentation class t) (copy-seq doc)))
(assert (or (null (documentation class t))
(equal doc (documentation class t)))))))
nil "FOO16")
(deftest documentation.standard-class.type.1
(let* ((sym (gensym))
(class-form `(defclass ,sym () ())))
(eval class-form)
(let ((class (find-class sym))
(doc "FOO17"))
(multiple-value-prog1
(values
(documentation class 'type)
(setf (documentation class 'type) (copy-seq doc)))
(assert (or (null (documentation class 'type))
(equal doc (documentation class 'type)))))))
nil "FOO17")
(deftest documentation.struct-class.t.1
(let* ((sym (gensym))
(class-form `(defstruct ,sym a b c)))
(eval class-form)
(let ((class (find-class sym))
(doc "FOO18"))
(multiple-value-prog1
(values
(documentation class t)
(setf (documentation class t) (copy-seq doc)))
(assert (or (null (documentation class t))
(equal doc (documentation class t)))))))
nil "FOO18")
(deftest documentation.struct-class.type.1
(let* ((sym (gensym))
(class-form `(defstruct ,sym a b c)))
(eval class-form)
(let ((class (find-class sym))
(doc "FOO19"))
(multiple-value-prog1
(values
(documentation class 'type)
(setf (documentation class 'type) (copy-seq doc)))
(assert (or (null (documentation class 'type))
(equal doc (documentation class 'type)))))))
nil "FOO19")
(deftest documentation.symbol.type.1
(let* ((sym (gensym))
(class-form `(defclass ,sym () ()))
(doc "FOO20"))
(eval class-form)
(multiple-value-prog1
(values
(documentation sym 'type)
(setf (documentation sym 'type) (copy-seq doc)))
(assert (or (null (documentation sym 'type))
(equal doc (documentation sym 'type))))))
nil "FOO20")
(deftest documentation.symbol.type.2
(let* ((sym (gensym))
(class-form `(defstruct ,sym a b c))
(doc "FOO21"))
(eval class-form)
(multiple-value-prog1
(values
(documentation sym 'type)
(setf (documentation sym 'type) (copy-seq doc)))
(assert (or (null (documentation sym 'type))
(equal doc (documentation sym 'type))))))
nil "FOO21")
(deftest documentation.symbol.type.3
(let* ((sym (gensym))
(type-form `(deftype ,sym () t))
(doc "FOO21A"))
(eval type-form)
(multiple-value-prog1
(values
(documentation sym 'type)
(setf (documentation sym 'type) (copy-seq doc)))
(assert (or (null (documentation sym 'type))
(equal doc (documentation sym 'type))))))
nil "FOO21A")
(deftest documentation.symbol.type.4
(loop for s in *cl-all-type-symbols*
for doc = (documentation s 'type)
unless (or (null doc) (stringp doc))
collect (list doc))
nil)
(deftest documentation.symbol.structure.1
(let* ((sym (gensym))
(class-form `(defstruct ,sym a b c))
(doc "FOO22"))
(eval class-form)
(multiple-value-prog1
(values
(documentation sym 'structure)
(setf (documentation sym 'structure) (copy-seq doc)))
(assert (or (null (documentation sym 'structure))
(equal doc (documentation sym 'structure))))))
nil "FOO22")
(deftest documentation.symbol.structure.2
(let* ((sym (gensym))
(class-form `(defstruct (,sym (:type list)) a b c))
(doc "FOO23"))
(eval class-form)
(multiple-value-prog1
(values
(documentation sym 'structure)
(setf (documentation sym 'structure) (copy-seq doc)))
(assert (or (null (documentation sym 'structure))
(equal doc (documentation sym 'structure))))))
nil "FOO23")
(deftest documentation.symbol.structure.3
(let* ((sym (gensym))
(class-form `(defstruct (,sym (:type vector)) a b c))
(doc "FOO24"))
(eval class-form)
(multiple-value-prog1
(values
(documentation sym 'structure)
(setf (documentation sym 'structure) (copy-seq doc)))
(assert (or (null (documentation sym 'structure))
(equal doc (documentation sym 'structure))))))
nil "FOO24")
(deftest documentation.symbol.variable.1
(let* ((sym (gensym))
(form `(defvar ,sym))
(doc "FOO25"))
(eval form)
(multiple-value-prog1
(values
(documentation sym 'variable)
(setf (documentation sym 'variable) (copy-seq doc)))
(assert (or (null (documentation sym 'variable))
(equal doc (documentation sym 'variable))))))
nil "FOO25")
(deftest documentation.symbol.variable.2
(let* ((sym (gensym))
(form `(defvar ,sym t))
(doc "FOO26"))
(eval form)
(multiple-value-prog1
(values
(documentation sym 'variable)
(setf (documentation sym 'variable) (copy-seq doc)))
(assert (or (null (documentation sym 'variable))
(equal doc (documentation sym 'variable))))))
nil "FOO26")
(deftest documentation.symbol.variable.3
(let* ((sym (gensym))
(form `(defparameter ,sym t))
(doc "FOO27"))
(eval form)
(multiple-value-prog1
(values
(documentation sym 'variable)
(setf (documentation sym 'variable) (copy-seq doc)))
(assert (or (null (documentation sym 'variable))
(equal doc (documentation sym 'variable))))))
nil "FOO27")
(deftest documentation.symbol.variable.4
(let* ((sym (gensym))
(form `(defconstant ,sym t))
(doc "FOO27"))
(eval form)
(multiple-value-prog1
(values
(documentation sym 'variable)
(setf (documentation sym 'variable) (copy-seq doc)))
(assert (or (null (documentation sym 'variable))
(equal doc (documentation sym 'variable))))))
nil "FOO27")
(deftest documentation.symbol.variable.5
(loop for s in *cl-variable-symbols*
for doc = (documentation s 'variable)
unless (or (null doc) (stringp doc))
collect (list s doc))
nil)
(deftest documentation.symbol.variable.6
(loop for s in *cl-constant-symbols*
for doc = (documentation s 'variable)
unless (or (null doc) (stringp doc))
collect (list s doc))
nil)
(ignore-errors
(defgeneric documentation-test-class-1-doc-accessor (obj))
(defgeneric (setf documentation-test-class-1-doc-accessor) (newdoc obj))
(defclass documentation-test-class-1 () ((my-doc :accessor documentation-test-class-1-doc-accessor
:type (or null string)
:initform nil)))
(defmethod documentation-test-class-1-doc-accessor ((obj documentation-test-class-1) )
(slot-value obj 'my-doc))
(defmethod (setf documentation-test-class-1-doc-accessor) ((newdoc string) (obj documentation-test-class-1))
(setf (slot-value obj 'my-doc) newdoc))
(defmethod documentation ((obj documentation-test-class-1) (doctype (eql t)))
(documentation-test-class-1-doc-accessor obj))
(defmethod (setf documentation) ((newdoc string) (obj documentation-test-class-1) (doctype (eql t)))
(setf (documentation-test-class-1-doc-accessor obj) newdoc)))
(deftest documentation.new-method.1
(let ((obj (make-instance 'documentation-test-class-1)))
(values
(documentation obj t)
(setf (documentation obj t) "FOO28")
(documentation obj t)))
nil "FOO28" "FOO28")
|
f3a6a98f6b5c79b8e3ba97692e9c5809b91bc7b1daed15cc8046521e3dd77d7d | ocaml/ocaml | functors.ml | (* TEST
* expect
*)
module type a
module type b
module type c
module type x = sig type x end
module type y = sig type y end
module type z = sig type z end
module type empty = sig end
module Empty = struct end
module X: x = struct type x end
module Y: y = struct type y end
module Z: z = struct type z end
module F(X:x)(Y:y)(Z:z) = struct end
[%%expect {|
module type a
module type b
module type c
module type x = sig type x end
module type y = sig type y end
module type z = sig type z end
module type empty = sig end
module Empty : sig end
module X : x
module Y : y
module Z : z
module F : functor (X : x) (Y : y) (Z : z) -> sig end
|}]
module M = F(X)(Z)
[%%expect {|
Line 1, characters 11-18:
1 | module M = F(X)(Z)
^^^^^^^
Error: The functor application is ill-typed.
These arguments:
X Z
do not match these parameters:
functor (X : x) (Y : y) (Z : z) -> ...
1. Module X matches the expected module type x
2. An argument appears to be missing with module type y
3. Module Z matches the expected module type z
|}]
module type f = functor (X:empty)(Y:empty) -> empty
module F: f =
functor(X:empty)(Y:empty)(Z:empty) -> Empty
[%%expect {|
module type f = functor (X : empty) (Y : empty) -> empty
Line 3, characters 9-45:
3 | functor(X:empty)(Y:empty)(Z:empty) -> Empty
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
functor (X : empty) (Y : empty) (Z : empty) -> ...
is not included in
functor (X : empty) (Y : empty) -> ...
1. Module types empty and empty match
2. Module types empty and empty match
3. An extra argument is provided of module type empty
|}]
module type f = functor (X:a)(Y:b) -> c
module F:f = functor (X:a)(Y:b)(Z:c) -> Empty
[%%expect {|
module type f = functor (X : a) (Y : b) -> c
Line 2, characters 21-45:
2 | module F:f = functor (X:a)(Y:b)(Z:c) -> Empty
^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
functor (X : a) (Y : b) (Z : c) -> ...
is not included in
functor (X : a) (Y : b) -> ...
1. Module types a and a match
2. Module types b and b match
3. An extra argument is provided of module type c
|}]
module M : sig module F: functor (X:sig end) -> sig end end =
struct
module F(X:sig type t end) = struct end
end
[%%expect {|
Lines 2-4, characters 2-5:
2 | ..struct
3 | module F(X:sig type t end) = struct end
4 | end
Error: Signature mismatch:
Modules do not match:
sig module F : functor (X : sig type t end) -> sig end end
is not included in
sig module F : functor (X : sig end) -> sig end end
In module F:
Modules do not match:
functor (X : $S1) -> ...
is not included in
functor (X : sig end) -> ...
Module types do not match:
$S1 = sig type t end
does not include
sig end
The type `t' is required but not provided
|}]
module F(X:sig type t end) = struct end
module M = F(struct type x end)
[%%expect {|
module F : functor (X : sig type t end) -> sig end
Line 2, characters 11-31:
2 | module M = F(struct type x end)
^^^^^^^^^^^^^^^^^^^^
Error: Modules do not match: sig type x end is not included in sig type t end
The type `t' is required but not provided
|}]
module F(X:sig type x end)(Y:sig type y end)(Z:sig type z end) = struct
type t = X of X.x | Y of Y.y | Z of Z.z
end
type u = F(X)(Z).t
[%%expect {|
module F :
functor (X : sig type x end) (Y : sig type y end) (Z : sig type z end) ->
sig type t = X of X.x | Y of Y.y | Z of Z.z end
Line 4, characters 9-18:
4 | type u = F(X)(Z).t
^^^^^^^^^
Error: The functor application F(X)(Z) is ill-typed.
These arguments:
X Z
do not match these parameters:
functor (X : ...) (Y : $T2) (Z : ...) -> ...
1. Module X matches the expected module type
2. An argument appears to be missing with module type
$T2 = sig type y end
3. Module Z matches the expected module type
|}]
module F()(X:sig type t end) = struct end
module M = F()()
[%%expect {|
module F : functor () (X : sig type t end) -> sig end
Line 2, characters 11-16:
2 | module M = F()()
^^^^^
Error: The functor application is ill-typed.
These arguments:
() ()
do not match these parameters:
functor () (X : $T2) -> ...
1. Module () matches the expected module type
2. The functor was expected to be applicative at this position
|}]
module M: sig
module F: functor(X:sig type x end)(X:sig type y end) -> sig end
end = struct
module F(X:sig type y end) = struct end
end
[%%expect {|
Lines 3-5, characters 6-3:
3 | ......struct
4 | module F(X:sig type y end) = struct end
5 | end
Error: Signature mismatch:
Modules do not match:
sig module F : functor (X : sig type y end) -> sig end end
is not included in
sig
module F :
functor (X : sig type x end) (X : sig type y end) -> sig end
end
In module F:
Modules do not match:
functor (X : $S2) -> ...
is not included in
functor (X : $T1) (X : $T2) -> ...
1. An argument appears to be missing with module type
$T1 = sig type x end
2. Module types $S2 and $T2 match
|}]
module F(Ctx: sig
module type t
module type u
module X:t
module Y:u
end) = struct
open Ctx
module F(A:t)(B:u) = struct end
module M = F(Y)(X)
end
[%%expect {|
Line 9, characters 13-20:
9 | module M = F(Y)(X)
^^^^^^^
Error: The functor application is ill-typed.
These arguments:
Ctx.Y Ctx.X
do not match these parameters:
functor (A : Ctx.t) (B : Ctx.u) -> ...
1. Modules do not match: Ctx.Y : Ctx.u is not included in Ctx.t
2. Modules do not match: Ctx.X : Ctx.t is not included in Ctx.u
|}]
(** Too many arguments *)
module Ord = struct type t = unit let compare _ _ = 0 end
module M = Map.Make(Ord)(Ord)
[%%expect {|
module Ord : sig type t = unit val compare : 'a -> 'b -> int end
Line 2, characters 11-29:
2 | module M = Map.Make(Ord)(Ord)
^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
Ord Ord
do not match these parameters:
functor (Ord : Map.OrderedType) -> ...
1. The following extra argument is provided
Ord : sig type t = unit val compare : 'a -> 'b -> int end
2. Module Ord matches the expected module type Map.OrderedType
|}]
(** Dependent types *)
(** Application side *)
module F
(A:sig type x type y end)
(B:sig type x = A.x end)
(C:sig type y = A.y end)
= struct end
module K = struct include X include Y end
module M = F(K)(struct type x = K.x end)( (* struct type z = K.y end *) )
[%%expect {|
module F :
functor (A : sig type x type y end) (B : sig type x = A.x end)
(C : sig type y = A.y end) -> sig end
module K : sig type x = X.x type y = Y.y end
Line 10, characters 11-73:
10 | module M = F(K)(struct type x = K.x end)( (* struct type z = K.y end *) )
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
K $S2 ()
do not match these parameters:
functor (A : ...) (B : ...) (C : $T3) -> ...
1. Module K matches the expected module type
2. Module $S2 matches the expected module type
3. The functor was expected to be applicative at this position
|}]
module M = F(K)(struct type y = K.y end)
[%%expect {|
Line 1, characters 11-40:
1 | module M = F(K)(struct type y = K.y end)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
K $S3
do not match these parameters:
functor (A : ...) (B : $T2) (C : ...) -> ...
1. Module K matches the expected module type
2. An argument appears to be missing with module type
$T2 = sig type x = A.x end
3. Module $S3 matches the expected module type
|}]
module M =
F
(struct include X include Y end)
(struct type x = K.x end)
(struct type yy = K.y end)
[%%expect {|
Lines 2-5, characters 2-30:
2 | ..F
3 | (struct include X include Y end)
4 | (struct type x = K.x end)
5 | (struct type yy = K.y end)
Error: The functor application is ill-typed.
These arguments:
$S1 $S2 $S3
do not match these parameters:
functor (A : ...) (B : ...) (C : $T3) -> ...
1. Module $S1 matches the expected module type
2. Module $S2 matches the expected module type
3. Modules do not match:
$S3 : sig type yy = K.y end
is not included in
$T3 = sig type y = A.y end
The type `y' is required but not provided
|}]
module M = struct
module N = struct
type x
type y
end
end
module Defs = struct
module X = struct type x = M.N.x end
module Y = struct type y = M.N.y end
end
module Missing_X = F(M.N)(Defs.Y)
[%%expect {|
module M : sig module N : sig type x type y end end
module Defs :
sig module X : sig type x = M.N.x end module Y : sig type y = M.N.y end end
Line 13, characters 19-33:
13 | module Missing_X = F(M.N)(Defs.Y)
^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
M.N Defs.Y
do not match these parameters:
functor (A : ...) (B : $T2) (C : ...) -> ...
1. Module M.N matches the expected module type
2. An argument appears to be missing with module type
$T2 = sig type x = A.x end
3. Module Defs.Y matches the expected module type
|}]
module Too_many_Xs = F(M.N)(Defs.X)(Defs.X)(Defs.Y)
[%%expect {|
Line 1, characters 21-51:
1 | module Too_many_Xs = F(M.N)(Defs.X)(Defs.X)(Defs.Y)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
M.N Defs.X Defs.X Defs.Y
do not match these parameters:
functor (A : ...) (B : ...) (C : ...) -> ...
1. Module M.N matches the expected module type
2. The following extra argument is provided
Defs.X : sig type x = M.N.x end
3. Module Defs.X matches the expected module type
4. Module Defs.Y matches the expected module type
|}]
module X = struct type x = int end
module Y = struct type y = float end
module Missing_X_bis = F(struct type x = int type y = float end)(Y)
[%%expect {|
module X : sig type x = int end
module Y : sig type y = float end
Line 3, characters 23-67:
3 | module Missing_X_bis = F(struct type x = int type y = float end)(Y)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
$S1 Y
do not match these parameters:
functor (A : ...) (B : $T2) (C : ...) -> ...
1. Module $S1 matches the expected module type
2. An argument appears to be missing with module type
$T2 = sig type x = A.x end
3. Module Y matches the expected module type
|}]
module Too_many_Xs_bis = F(struct type x = int type y = float end)(X)(X)(Y)
[%%expect {|
Line 1, characters 25-75:
1 | module Too_many_Xs_bis = F(struct type x = int type y = float end)(X)(X)(Y)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
$S1 X X Y
do not match these parameters:
functor (A : ...) (B : ...) (C : ...) -> ...
1. Module $S1 matches the expected module type
2. The following extra argument is provided X : sig type x = int end
3. Module X matches the expected module type
4. Module Y matches the expected module type
|}]
(** Inclusion side *)
module type f =
functor(A:sig type x type y end)(B:sig type x = A.x end)(C:sig type y = A.y end)
-> sig end
module F: f = functor (A:sig include x include y end)(Z:sig type y = A.y end) -> struct end
[%%expect {|
module type f =
functor (A : sig type x type y end) (B : sig type x = A.x end)
(C : sig type y = A.y end) -> sig end
Line 4, characters 22-91:
4 | module F: f = functor (A:sig include x include y end)(Z:sig type y = A.y end) -> struct end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
functor (A : $S1) (Z : $S3) -> ...
is not included in
functor (A : $T1) (B : $T2) (C : $T3) -> ...
1. Module types $S1 and $T1 match
2. An argument appears to be missing with module type
$T2 = sig type x = A.x end
3. Module types $S3 and $T3 match
|}]
module type f =
functor(B:sig type x type y type u=x type v=y end)(Y:sig type yu = Y of B.u end)(Z:sig type zv = Z of B.v end)
-> sig end
module F: f = functor (X:sig include x include y end)(Z:sig type zv = Z of X.y end) -> struct end
[%%expect {|
module type f =
functor (B : sig type x type y type u = x type v = y end)
(Y : sig type yu = Y of B.u end) (Z : sig type zv = Z of B.v end) ->
sig end
Line 4, characters 22-97:
4 | module F: f = functor (X:sig include x include y end)(Z:sig type zv = Z of X.y end) -> struct end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
functor (X : $S1) (Z : $S3) -> ...
is not included in
functor (B : $T1) (Y : $T2) (Z : $T3) -> ...
1. Module types $S1 and $T1 match
2. An argument appears to be missing with module type
$T2 = sig type yu = Y of B.u end
3. Module types $S3 and $T3 match
|}]
(** Module type equalities *)
module M: sig
module type S = sig type t end
end = struct
module type S = sig type s type t end
end;;
[%%expect {|
Lines 5-7, characters 6-3:
5 | ......struct
6 | module type S = sig type s type t end
7 | end..
Error: Signature mismatch:
Modules do not match:
sig module type S = sig type s type t end end
is not included in
sig module type S = sig type t end end
Module type declarations do not match:
module type S = sig type s type t end
does not match
module type S = sig type t end
The second module type is not included in the first
At position module type S = <here>
Module types do not match:
sig type t end
is not equal to
sig type s type t end
At position module type S = <here>
The type `s' is required but not provided
|}]
module M: sig
module type S = sig type t type u end
end = struct
module type S = sig type t end
end;;
[%%expect {|
Lines 3-5, characters 6-3:
3 | ......struct
4 | module type S = sig type t end
5 | end..
Error: Signature mismatch:
Modules do not match:
sig module type S = sig type t end end
is not included in
sig module type S = sig type t type u end end
Module type declarations do not match:
module type S = sig type t end
does not match
module type S = sig type t type u end
The first module type is not included in the second
At position module type S = <here>
Module types do not match:
sig type t end
is not equal to
sig type t type u end
At position module type S = <here>
The type `u' is required but not provided
|}]
(** Name collision test *)
module F(X:x)(B:b)(Y:y) = struct type t end
module M = struct
module type b
module G(P: sig module B:b end) = struct
open P
module U = F(struct type x end)(B)(struct type w end)
end
end
[%%expect {|
module F : functor (X : x) (B : b) (Y : y) -> sig type t end
Line 8, characters 15-57:
8 | module U = F(struct type x end)(B)(struct type w end)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
$S1 P.B $S3
do not match these parameters:
functor (X : x) (B : b/2) (Y : y) -> ...
1. Module $S1 matches the expected module type x
2. Modules do not match:
P.B : b
is not included in
b/2
Line 5, characters 2-15:
Definition of module type b
Line 2, characters 0-13:
Definition of module type b/2
3. Modules do not match: $S3 : sig type w end is not included in y
|}]
module F(X:a) = struct type t end
module M = struct
module type a
module G(P: sig module X:a end) = struct
open P
type t = F(X).t
end
end
[%%expect {|
module F : functor (X : a) -> sig type t end
Line 6, characters 13-19:
6 | type t = F(X).t
^^^^^^
Error: Modules do not match: a is not included in a/2
Line 3, characters 2-15:
Definition of module type a
Line 1, characters 0-13:
Definition of module type a/2
|}]
module M: sig module F: functor(X:a)(Y:a) -> sig end end =
struct
module type aa = a
module type a
module F(X:aa)(Y:a) = struct end
end
[%%expect {|
Lines 2-6, characters 1-3:
2 | .struct
3 | module type aa = a
4 | module type a
5 | module F(X:aa)(Y:a) = struct end
6 | end
Error: Signature mismatch:
Modules do not match:
sig
module type aa = a
module type a
module F : functor (X : aa) (Y : a) -> sig end
end
is not included in
sig module F : functor (X : a) (Y : a) -> sig end end
In module F:
Modules do not match:
functor (X : aa) (Y : a) -> ...
is not included in
functor (X : a/2) (Y : a/2) -> ...
1. Module types aa and a/2 match
2. Module types do not match:
a
does not include
a/2
Line 4, characters 2-15:
Definition of module type a
Line 1, characters 0-13:
Definition of module type a/2
|}]
module X: functor ( X: sig end) -> sig end = functor(X: Set.OrderedType) -> struct end
[%%expect {|
Line 1, characters 52-86:
1 | module X: functor ( X: sig end) -> sig end = functor(X: Set.OrderedType) -> struct end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
functor (X : Set.OrderedType) -> ...
is not included in
functor (X : sig end) -> ...
Module types do not match:
Set.OrderedType
does not include
sig end
The type `t' is required but not provided
File "set.mli", line 52, characters 4-10: Expected declaration
The value `compare' is required but not provided
File "set.mli", line 55, characters 4-31: Expected declaration
|}]
(** Deeply nested errors *)
module M: sig
module F: functor
(X:
functor(A: sig type xa end)(B:sig type xz end) -> sig end
)
(Y:
functor(A: sig type ya end)(B:sig type yb end) -> sig end
)
(Z:
functor(A: sig type za end)(B:sig type zb end) -> sig end
) -> sig end
end = struct
module F
(X:
functor (A: sig type xa end)(B:sig type xz end) -> sig end
)
(Y:
functor (A: sig type ya end)(B:sig type ybb end) -> sig end
)
(Z:
functor (A: sig type za end)(B:sig type zbb end) -> sig end
)
= struct end
end
[%%expect {|
Lines 15-27, characters 6-3:
15 | ......struct
16 | module F
17 | (X:
18 | functor (A: sig type xa end)(B:sig type xz end) -> sig end
19 | )
...
24 | functor (A: sig type za end)(B:sig type zbb end) -> sig end
25 | )
26 | = struct end
27 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
functor
(X : functor (A : sig type xa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type ybb end) ->
sig end)
(Z : functor (A : sig type za end) (B : sig type zbb end) ->
sig end)
-> sig end
end
is not included in
sig
module F :
functor
(X : functor (A : sig type xa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type yb end) ->
sig end)
(Z : functor (A : sig type za end) (B : sig type zb end) ->
sig end)
-> sig end
end
In module F:
Modules do not match:
functor (X : $S1) (Y : $S2) (Z : $S3) -> ...
is not included in
functor (X : $T1) (Y : $T2) (Z : $T3) -> ...
1. Module types $S1 and $T1 match
2. Module types do not match:
$S2 =
functor (A : sig type ya end) (B : sig type ybb end) -> sig end
does not include
$T2 =
functor (A : sig type ya end) (B : sig type yb end) -> sig end
Modules do not match:
functor (A : $S1) (B : $S2) -> ...
is not included in
functor (A : $T1) (B : $T2) -> ...
1. Module types $S1 and $T1 match
2. Module types do not match:
$S2 = sig type yb end
does not include
$T2 = sig type ybb end
The type `yb' is required but not provided
3. Module types do not match:
$S3 =
functor (A : sig type za end) (B : sig type zbb end) -> sig end
does not include
$T3 =
functor (A : sig type za end) (B : sig type zb end) -> sig end
Modules do not match:
functor (A : $S1) (B : $S2) -> ...
is not included in
functor (A : $T1) (B : $T2) -> ...
|}]
module M: sig
module F: functor
(X:
functor(A: sig type xa end)(B:sig type xz end) -> sig end
)
(Y:
functor(A: sig type ya end)(B:sig type yb end) -> sig end
)
(Z:
functor(A: sig type za end)(B:sig type zb end) -> sig end
) -> sig end
end = struct
module F
(X:
functor (A: sig type xa end)(B:sig type xz end) -> sig end
)
(Y:
functor (A: sig type ya end)(B:sig type yb end) -> sig end
)
= struct end
end
[%%expect {|
Lines 12-21, characters 6-3:
12 | ......struct
13 | module F
14 | (X:
15 | functor (A: sig type xa end)(B:sig type xz end) -> sig end
16 | )
17 | (Y:
18 | functor (A: sig type ya end)(B:sig type yb end) -> sig end
19 | )
20 | = struct end
21 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
functor
(X : functor (A : sig type xa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type yb end) ->
sig end)
-> sig end
end
is not included in
sig
module F :
functor
(X : functor (A : sig type xa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type yb end) ->
sig end)
(Z : functor (A : sig type za end) (B : sig type zb end) ->
sig end)
-> sig end
end
In module F:
Modules do not match:
functor (X : $S1) (Y : $S2) -> ...
is not included in
functor (X : $T1) (Y : $T2) (Z : $T3) -> ...
1. Module types $S1 and $T1 match
2. Module types $S2 and $T2 match
3. An argument appears to be missing with module type
$T3 =
functor (A : sig type za end) (B : sig type zb end) -> sig end
|}]
module M: sig
module F: functor
(X:
functor(A: sig type xa end)(B:sig type xz end) -> sig end
)
(Y:
functor(A: sig type ya end)(B:sig type yb end) -> sig end
)
(Z:
functor(A: sig type za end)(B:sig type zb end) -> sig end
) -> sig end
end = struct
module F
(X:
functor (A: sig type xaa end)(B:sig type xz end) -> sig end
)
(Y:
functor (A: sig type ya end)(B:sig type ybb end) -> sig end
)
(Z:
functor (A: sig type za end)(B:sig type zbb end) -> sig end
)
= struct end
end
[%%expect {|
Lines 12-24, characters 6-3:
12 | ......struct
13 | module F
14 | (X:
15 | functor (A: sig type xaa end)(B:sig type xz end) -> sig end
16 | )
...
21 | functor (A: sig type za end)(B:sig type zbb end) -> sig end
22 | )
23 | = struct end
24 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
functor
(X : functor (A : sig type xaa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type ybb end) ->
sig end)
(Z : functor (A : sig type za end) (B : sig type zbb end) ->
sig end)
-> sig end
end
is not included in
sig
module F :
functor
(X : functor (A : sig type xa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type yb end) ->
sig end)
(Z : functor (A : sig type za end) (B : sig type zb end) ->
sig end)
-> sig end
end
In module F:
Modules do not match:
functor (X : $S1) (Y : $S2) (Z : $S3) -> ...
is not included in
functor (X : $T1) (Y : $T2) (Z : $T3) -> ...
1. Module types do not match:
$S1 =
functor (A : sig type xaa end) (B : sig type xz end) -> sig end
does not include
$T1 =
functor (A : sig type xa end) (B : sig type xz end) -> sig end
Modules do not match:
functor (A : $S1) (B : $S2) -> ...
is not included in
functor (A : $T1) (B : $T2) -> ...
1. Module types do not match:
$S1 = sig type xa end
does not include
$T1 = sig type xaa end
The type `xa' is required but not provided
2. Module types $S2 and $T2 match
2. Module types do not match:
$S2 =
functor (A : sig type ya end) (B : sig type ybb end) -> sig end
does not include
$T2 =
functor (A : sig type ya end) (B : sig type yb end) -> sig end
Modules do not match:
functor (A : $S1) (B : $S2) -> ...
is not included in
functor (A : $T1) (B : $T2) -> ...
3. Module types do not match:
$S3 =
functor (A : sig type za end) (B : sig type zbb end) -> sig end
does not include
$T3 =
functor (A : sig type za end) (B : sig type zb end) -> sig end
Modules do not match:
functor (A : $S1) (B : $S2) -> ...
is not included in
functor (A : $T1) (B : $T2) -> ...
|}]
module A: sig
module B: sig
module C: sig
module D: sig
module E: sig
module F: sig type x end -> sig type y end
-> sig type z end -> sig type w end -> sig end
end
end
end
end
end = struct
module B = struct
module C = struct
module D = struct
module E = struct
module F(X:sig type x end)(Y:sig type y' end)
(W:sig type w end) = struct end
end
end
end
end
end
[%%expect {|
Lines 12-23, characters 6-3:
12 | ......struct
13 | module B = struct
14 | module C = struct
15 | module D = struct
16 | module E = struct
...
20 | end
21 | end
22 | end
23 | end
Error: Signature mismatch:
Modules do not match:
sig
module B :
sig
module C :
sig
module D :
sig
module E :
sig
module F :
functor (X : sig type x end)
(Y : sig type y' end) (W : sig type w end) ->
sig end
end
end
end
end
end
is not included in
sig
module B :
sig
module C :
sig
module D :
sig
module E :
sig
module F :
sig type x end -> sig type y end ->
sig type z end -> sig type w end -> sig end
end
end
end
end
end
In module B:
Modules do not match:
sig module C = B.C end
is not included in
sig
module C :
sig
module D :
sig
module E :
sig
module F :
sig type x end -> sig type y end ->
sig type z end -> sig type w end -> sig end
end
end
end
end
In module B.C:
Modules do not match:
sig module D = B.C.D end
is not included in
sig
module D :
sig
module E :
sig
module F :
sig type x end -> sig type y end -> sig type z end ->
sig type w end -> sig end
end
end
end
In module B.C.D:
Modules do not match:
sig module E = B.C.D.E end
is not included in
sig
module E :
sig
module F :
sig type x end -> sig type y end -> sig type z end ->
sig type w end -> sig end
end
end
In module B.C.D.E:
Modules do not match:
sig module F = B.C.D.E.F end
is not included in
sig
module F :
sig type x end -> sig type y end -> sig type z end ->
sig type w end -> sig end
end
In module B.C.D.E.F:
Modules do not match:
functor (X : $S1) (Y : $S3) (W : $S4) -> ...
is not included in
functor $T1 $T2 $T3 $T4 -> ...
1. Module types $S1 and $T1 match
2. An argument appears to be missing with module type
$T2 = sig type y end
3. Module types do not match:
$S3 = sig type y' end
does not include
$T3 = sig type z end
4. Module types $S4 and $T4 match
|}]
(** Ugly cases *)
module type Arg = sig
module type A
module type Honorificabilitudinitatibus
module X: Honorificabilitudinitatibus
module Y: A
end
module F(A:Arg)
= struct
open A
module G(X:A)(Y:A)(_:A)(Z:A) = struct end
type u = G(X)(Y)(X)(Y)(X).t
end;;
[%%expect {|
module type Arg =
sig
module type A
module type Honorificabilitudinitatibus
module X : Honorificabilitudinitatibus
module Y : A
end
Line 14, characters 11-29:
14 | type u = G(X)(Y)(X)(Y)(X).t
^^^^^^^^^^^^^^^^^^
Error: The functor application G(X)(Y)(X)(Y)(X) is ill-typed.
These arguments:
A.X A.Y A.X A.Y A.X
do not match these parameters:
functor (X : A.A) (Y : A.A) A.A (Z : A.A) -> ...
1. The following extra argument is provided
A.X : A.Honorificabilitudinitatibus
2. Module A.Y matches the expected module type A.A
3. Modules do not match:
A.X : A.Honorificabilitudinitatibus
is not included in
A.A
4. Module A.Y matches the expected module type A.A
5. Modules do not match:
A.X : A.Honorificabilitudinitatibus
is not included in
A.A
|}]
module type s = functor
(X: sig type when_ type shall type we type three type meet type again end)
(Y:sig type in_ val thunder:in_ val lightning: in_ type rain end)
(Z:sig type when_ type the type hurlyburly's type done_ end)
(Z:sig type when_ type the type battle's type lost type and_ type won end)
(W:sig type that type will type be type ere type the_ type set type of_ type sun end)
(S: sig type where type the type place end)
(R: sig type upon type the type heath end)
-> sig end
module F: s = functor
(X: sig type when_ type shall type we type tree type meet type again end)
(Y:sig type in_ val thunder:in_ val lightning: in_ type pain end)
(Z:sig type when_ type the type hurlyburly's type gone end)
(Z:sig type when_ type the type battle's type last type and_ type won end)
(W:sig type that type will type be type the type era type set type of_ type sun end)
(S: sig type where type the type lace end)
(R: sig type upon type the type heart end)
-> struct end
[%%expect {|
module type s =
functor
(X : sig
type when_
type shall
type we
type three
type meet
type again
end)
(Y : sig type in_ val thunder : in_ val lightning : in_ type rain end)
(Z : sig type when_ type the type hurlyburly's type done_ end)
(Z : sig
type when_
type the
type battle's
type lost
type and_
type won
end)
(W : sig
type that
type will
type be
type ere
type the_
type set
type of_
type sun
end)
(S : sig type where type the type place end)
(R : sig type upon type the type heath end) -> sig end
Lines 11-18, characters 2-15:
11 | ..(X: sig type when_ type shall type we type tree type meet type again end)
12 | (Y:sig type in_ val thunder:in_ val lightning: in_ type pain end)
13 | (Z:sig type when_ type the type hurlyburly's type gone end)
14 | (Z:sig type when_ type the type battle's type last type and_ type won end)
15 | (W:sig type that type will type be type the type era type set type of_ type sun end)
16 | (S: sig type where type the type lace end)
17 | (R: sig type upon type the type heart end)
18 | -> struct end
Error: Signature mismatch:
Modules do not match:
functor (X : $S1) (Y : $S2) (Z : $S3) (Z : $S4) (W : $S5) (S : $S6)
(R : $S7) -> ...
is not included in
functor (X : $T1) (Y : $T2) (Z : $T3) (Z : $T4) (W : $T5) (S : $T6)
(R : $T7) -> ...
1. Module types do not match:
$S1 =
sig
type when_
type shall
type we
type tree
type meet
type again
end
does not include
$T1 =
sig
type when_
type shall
type we
type three
type meet
type again
end
The type `tree' is required but not provided
2. Module types do not match:
$S2 =
sig type in_ val thunder : in_ val lightning : in_ type pain end
does not include
$T2 =
sig type in_ val thunder : in_ val lightning : in_ type rain end
3. Module types do not match:
$S3 = sig type when_ type the type hurlyburly's type gone end
does not include
$T3 = sig type when_ type the type hurlyburly's type done_ end
4. Module types do not match:
$S4 =
sig
type when_
type the
type battle's
type last
type and_
type won
end
does not include
$T4 =
sig
type when_
type the
type battle's
type lost
type and_
type won
end
5. Module types do not match:
$S5 =
sig
type that
type will
type be
type the
type era
type set
type of_
type sun
end
does not include
$T5 =
sig
type that
type will
type be
type ere
type the_
type set
type of_
type sun
end
6. Module types do not match:
$S6 = sig type where type the type lace end
does not include
$T6 = sig type where type the type place end
7. Module types do not match:
$S7 = sig type upon type the type heart end
does not include
$T7 = sig type upon type the type heath end
|}]
(** Abstract module type woes *)
module F(X:sig type witness module type t module M:t end) = X.M
module PF = struct
type witness
module type t = module type of F
module M = F
end
module U = F(PF)(PF)(PF)
[%%expect {|
module F :
functor (X : sig type witness module type t module M : t end) -> X.t
module PF :
sig
type witness
module type t =
functor (X : sig type witness module type t module M : t end) -> X.t
module M = F
end
module U : PF.t
|}]
module W = F(PF)(PF)(PF)(PF)(PF)(F)
[%%expect {|
Line 1, characters 11-35:
1 | module W = F(PF)(PF)(PF)(PF)(PF)(F)
^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
PF PF PF PF PF F
do not match these parameters:
functor (X : ...) (X : ...) (X : ...) (X : ...) (X : ...) (X : $T6)
-> ...
1. Module PF matches the expected module type
2. Module PF matches the expected module type
3. Module PF matches the expected module type
4. Module PF matches the expected module type
5. Module PF matches the expected module type
6. Modules do not match:
F :
functor (X : sig type witness module type t module M : t end) ->
X.t
is not included in
$T6 = sig type witness module type t module M : t end
Modules do not match:
functor (X : $S1) -> ...
is not included in
functor -> ...
An extra argument is provided of module type
$S1 = sig type witness module type t module M : t end
|}]
(** Divergent arities *)
module type arg = sig type arg end
module A = struct type arg end
module Add_one' = struct
module M(_:arg) = A
module type t = module type of M
end
module Add_one = struct type witness include Add_one' end
module Add_three' = struct
module M(_:arg)(_:arg)(_:arg) = A
module type t = module type of M
end
module Add_three = struct
include Add_three'
type witness
end
module Wrong_intro = F(Add_three')(A)(A)(A)
[%%expect {|
module type arg = sig type arg end
module A : sig type arg end
module Add_one' :
sig
module M : arg -> sig type arg = A.arg end
module type t = arg -> sig type arg = A.arg end
end
module Add_one :
sig type witness module M = Add_one'.M module type t = Add_one'.t end
module Add_three' :
sig
module M : arg -> arg -> arg -> sig type arg = A.arg end
module type t = arg -> arg -> arg -> sig type arg = A.arg end
end
module Add_three :
sig module M = Add_three'.M module type t = Add_three'.t type witness end
Line 22, characters 21-43:
22 | module Wrong_intro = F(Add_three')(A)(A)(A)
^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
Add_three' A A A
do not match these parameters:
functor (X : $T1) arg arg arg -> ...
1. Modules do not match:
Add_three' :
sig module M = Add_three'.M module type t = Add_three'.t end
is not included in
$T1 = sig type witness module type t module M : t end
The type `witness' is required but not provided
2. Module A matches the expected module type arg
3. Module A matches the expected module type arg
4. Module A matches the expected module type arg
|}]
module Choose_one = F(Add_one')(Add_three)(A)(A)(A)
[%%expect {|
Line 1, characters 20-51:
1 | module Choose_one = F(Add_one')(Add_three)(A)(A)(A)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
Add_one' Add_three A A A
do not match these parameters:
functor (X : ...) arg arg arg -> ...
1. The following extra argument is provided
Add_one' :
sig module M = Add_one'.M module type t = Add_one'.t end
2. Module Add_three matches the expected module type
3. Module A matches the expected module type arg
4. Module A matches the expected module type arg
5. Module A matches the expected module type arg
|}]
* Known lmitation : we choose the wrong environment without the
error on Add_one
*
error on Add_one
**)
module Mislead_chosen_one = F(Add_one)(Add_three)(A)(A)(A)
[%%expect {|
Line 1, characters 28-58:
1 | module Mislead_chosen_one = F(Add_one)(Add_three)(A)(A)(A)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
Add_one Add_three A A A
do not match these parameters:
functor (X : ...) arg arg arg -> ...
1. The following extra argument is provided
Add_one :
sig
type witness = Add_one.witness
module M = Add_one'.M
module type t = Add_one.t
end
2. Module Add_three matches the expected module type
3. Module A matches the expected module type arg
4. Module A matches the expected module type arg
5. Module A matches the expected module type arg
|}]
(** Hide your arity from the world *)
module M: sig
module F:
functor (X:sig
type x
module type t =
functor
(Y:sig type y end)
(Z:sig type z end)
-> sig end
end) -> X.t
end
= struct
module F(X:sig type x end)(Z:sig type z end) = struct end
end
[%%expect {|
Lines 14-16, characters 2-3:
14 | ..struct
15 | module F(X:sig type x end)(Z:sig type z end) = struct end
16 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
functor (X : sig type x end) (Z : sig type z end) -> sig end
end
is not included in
sig
module F :
functor
(X : sig
type x
module type t =
functor (Y : sig type y end) (Z : sig type z end) ->
sig end
end)
-> X.t
end
In module F:
Modules do not match:
functor (X : $S1) (Z : $S3) -> ...
is not included in
functor (X : $T1) (Y : $T2) (Z : $T3) -> ...
1. Module types $S1 and $T1 match
2. An argument appears to be missing with module type
$T2 = sig type y end
3. Module types $S3 and $T3 match
|}]
module M: sig
module F(X: sig
module type T
module type t = T -> T -> T
module M: t
end
)(_:X.T)(_:X.T): X.T
end = struct
module F (Wrong: sig type wrong end)
(X: sig
module type t
module M: t
end) = (X.M : X.t)
end
[%%expect {|
Lines 8-14, characters 6-3:
8 | ......struct
9 | module F (Wrong: sig type wrong end)
10 | (X: sig
11 | module type t
12 | module M: t
13 | end) = (X.M : X.t)
14 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
functor (Wrong : sig type wrong end)
(X : sig module type t module M : t end) -> X.t
end
is not included in
sig
module F :
functor
(X : sig
module type T
module type t = T -> T -> T
module M : t
end)
-> X.T -> X.T -> X.T
end
In module F:
Modules do not match:
functor (Wrong : $S1) (X : $S2) X.T X.T -> ...
is not included in
functor (X : $T2) X.T X.T -> ...
1. An extra argument is provided of module type
$S1 = sig type wrong end
2. Module types $S2 and $T2 match
3. Module types X.T and X.T match
4. Module types X.T and X.T match
|}]
module M: sig
module F(_:sig end)(X:
sig
module type T
module type inner = sig
module type t
module M: t
end
module F(X: inner)(_:T -> T->T):
sig module type res = X.t end
module Y: sig
module type t = T -> T -> T
module M(X:T)(Y:T): T
end
end):
X.F(X.Y)(X.Y.M).res
end = struct
module F(_:sig type wrong end) (X:
sig module type T end
)(Res: X.T)(Res: X.T)(Res: X.T) = Res
end
[%%expect {|
Lines 17-21, characters 6-3:
17 | ......struct
18 | module F(_:sig type wrong end) (X:
19 | sig module type T end
20 | )(Res: X.T)(Res: X.T)(Res: X.T) = Res
21 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
sig type wrong end ->
functor (X : sig module type T end) (Res : X.T) (Res :
X.T) (Res : X.T)
-> X.T
end
is not included in
sig
module F :
sig end ->
functor
(X : sig
module type T
module type inner =
sig module type t module M : t end
module F :
functor (X : inner) -> (T -> T -> T) ->
sig module type res = X.t end
module Y :
sig
module type t = T -> T -> T
module M : functor (X : T) (Y : T) -> T
end
end)
-> X.F(X.Y)(X.Y.M).res
end
In module F:
Modules do not match:
functor (Arg : $S1) (X : $S2) (Res : X.T) (Res : X.T) (Res :
X.T) -> ...
is not included in
functor (sig end) (X : $T2) X.T X.T -> ...
1. Module types do not match:
$S1 = sig type wrong end
does not include
sig end
The type `wrong' is required but not provided
2. Module types $S2 and $T2 match
3. An extra argument is provided of module type X.T
4. Module types X.T and X.T match
5. Module types X.T and X.T match
|}]
* The price of Gluttony : update of environment leads to a non - optimal edit distance .
module F(X:sig type t end)(Y:sig type t = Y of X.t end)(Z:sig type t = Z of X.t end) = struct end
module X = struct type t = U end
module Y = struct type t = Y of int end
module Z = struct type t = Z of int end
module Error=F(X)(struct type t = int end)(Y)(Z)
[%%expect {|
module F :
functor (X : sig type t end) (Y : sig type t = Y of X.t end)
(Z : sig type t = Z of X.t end) -> sig end
module X : sig type t = U end
module Y : sig type t = Y of int end
module Z : sig type t = Z of int end
Line 9, characters 13-48:
9 | module Error=F(X)(struct type t = int end)(Y)(Z)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
X ... Y Z
do not match these parameters:
functor (X : ...) (Y : $T3) (Z : $T4) -> ...
1. Module X matches the expected module type
2. The following extra argument is provided ... : sig type t = int end
3. Modules do not match:
Y : sig type t = Y.t = Y of int end
is not included in
$T3 = sig type t = Y of X.t end
Type declarations do not match:
type t = Y.t = Y of int
is not included in
type t = Y of X.t
Constructors do not match:
Y of int
is not the same as:
Y of X.t
The type int is not equal to the type X.t
4. Modules do not match:
Z : sig type t = Z.t = Z of int end
is not included in
$T4 = sig type t = Z of X.t end
Type declarations do not match:
type t = Z.t = Z of int
is not included in
type t = Z of X.t
Constructors do not match:
Z of int
is not the same as:
Z of X.t
The type int is not equal to the type X.t
|}]
* Final state in the presence of extensions
Test provided by in
#pullrequestreview-492359720
Test provided by Leo White in
#pullrequestreview-492359720
*)
module type A = sig type a end
module A = struct type a end
module type B = sig type b end
module B = struct type b end
module type ty = sig type t end
module TY = struct type t end
module type Ext = sig module type T module X : T end
module AExt = struct module type T = A module X = A end
module FiveArgsExt = struct
module type T = ty -> ty -> ty -> ty -> ty -> sig end
module X : T =
functor (_ : ty) (_ : ty) (_ : ty) (_ : ty) (_ : ty) -> struct end
end
module Bar (W : A) (X : Ext) (Y : B) (Z : Ext) = Z.X
type fine = Bar(A)(FiveArgsExt)(B)(AExt).a
[%%expect{|
module type A = sig type a end
module A : sig type a end
module type B = sig type b end
module B : sig type b end
module type ty = sig type t end
module TY : sig type t end
module type Ext = sig module type T module X : T end
module AExt : sig module type T = A module X = A end
module FiveArgsExt :
sig module type T = ty -> ty -> ty -> ty -> ty -> sig end module X : T end
module Bar : functor (W : A) (X : Ext) (Y : B) (Z : Ext) -> Z.T
type fine = Bar(A)(FiveArgsExt)(B)(AExt).a
|}]
type broken1 = Bar(B)(FiveArgsExt)(B)(AExt).a
[%%expect{|
Line 1, characters 15-45:
1 | type broken1 = Bar(B)(FiveArgsExt)(B)(AExt).a
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application Bar(B)(FiveArgsExt)(B)(AExt) is ill-typed.
These arguments:
B FiveArgsExt B AExt
do not match these parameters:
functor (W : A) (X : Ext) (Y : B) (Z : Ext) -> ...
1. Modules do not match:
B : sig type b = B.b end
is not included in
A
The type `a' is required but not provided
2. Module FiveArgsExt matches the expected module type Ext
3. Module B matches the expected module type B
4. Module AExt matches the expected module type Ext
|}]
type broken2 = Bar(A)(FiveArgsExt)(TY)(TY)(TY)(TY)(TY).a
[%%expect{|
Line 1, characters 15-56:
1 | type broken2 = Bar(A)(FiveArgsExt)(TY)(TY)(TY)(TY)(TY).a
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application Bar(A)(FiveArgsExt)(TY)(TY)(TY)(TY)(TY) is ill-typed.
These arguments:
A FiveArgsExt TY TY TY TY TY
do not match these parameters:
functor (W : A) (X : Ext) (Y : B) (Z : Ext) ty ty ty ty ty -> ...
1. Module A matches the expected module type A
2. An argument appears to be missing with module type Ext
3. An argument appears to be missing with module type B
4. Module FiveArgsExt matches the expected module type Ext
5. Module TY matches the expected module type ty
6. Module TY matches the expected module type ty
7. Module TY matches the expected module type ty
8. Module TY matches the expected module type ty
9. Module TY matches the expected module type ty
|}]
module Shape_arg = struct
module M1 (Arg1 : sig end) = struct
module type S1 = sig
type t
end
end
module type S2 = sig
module Make (Arg2 : sig end) : M1(Arg2).S1
end
module M2 : S2 = struct
module Make (Arg3 : sig end) = struct
type t = T
end
end
module M3 (Arg4 : sig end) = struct
module type S3 = sig
type t = M2.Make(Arg4).t
end
end
module M4 (Arg5 : sig end) : M3(Arg5).S3 = struct
module M5 = M2.Make (Arg5)
type t = M5.t
end
end
[%%expect{|
module Shape_arg :
sig
module M1 :
functor (Arg1 : sig end) -> sig module type S1 = sig type t end end
module type S2 =
sig module Make : functor (Arg2 : sig end) -> M1(Arg2).S1 end
module M2 : S2
module M3 :
functor (Arg4 : sig end) ->
sig module type S3 = sig type t = M2.Make(Arg4).t end end
module M4 : functor (Arg5 : sig end) -> M3(Arg5).S3
end
|}]
(* Applicative or generative *)
module F(X:A) = struct end
module R = F(struct end[@warning "-73"]);;
[%%expect {|
module F : functor (X : A) -> sig end
Line 2, characters 11-40:
2 | module R = F(struct end[@warning "-73"]);;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Modules do not match: sig end is not included in A
The type `a' is required but not provided
|}]
module F()(X:empty)()(Y:A) = struct end
module R =
F(struct end[@warning "-73"])(struct end)(struct end[@warning "-73"])();;
[%%expect {|
module F : functor () (X : empty) () (Y : A) -> sig end
Line 3, characters 2-73:
3 | F(struct end[@warning "-73"])(struct end)(struct end[@warning "-73"])();;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
(struct end) (struct end) (struct end) ()
do not match these parameters:
functor () (X : empty) () (Y : A) -> ...
1. Module (struct end) matches the expected module type
2. Module (struct end) matches the expected module type empty
3. Module (struct end) matches the expected module type
4. The functor was expected to be applicative at this position
|}]
module F(X:empty) = struct end
module R =
F(struct end)();;
[%%expect {|
module F : functor (X : empty) -> sig end
Line 3, characters 2-17:
3 | F(struct end)();;
^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
(struct end) ()
do not match these parameters:
functor (X : empty) -> ...
1. Module (struct end) matches the expected module type empty
2. The following extra argument is provided ()
|}]
| null | https://raw.githubusercontent.com/ocaml/ocaml/3490eaa060cd1e2b4143bf5df42fdbeb121f0c4d/testsuite/tests/typing-modules/functors.ml | ocaml | TEST
* expect
* Too many arguments
* Dependent types
* Application side
struct type z = K.y end
struct type z = K.y end
* Inclusion side
* Module type equalities
* Name collision test
* Deeply nested errors
* Ugly cases
* Abstract module type woes
* Divergent arities
* Hide your arity from the world
Applicative or generative |
module type a
module type b
module type c
module type x = sig type x end
module type y = sig type y end
module type z = sig type z end
module type empty = sig end
module Empty = struct end
module X: x = struct type x end
module Y: y = struct type y end
module Z: z = struct type z end
module F(X:x)(Y:y)(Z:z) = struct end
[%%expect {|
module type a
module type b
module type c
module type x = sig type x end
module type y = sig type y end
module type z = sig type z end
module type empty = sig end
module Empty : sig end
module X : x
module Y : y
module Z : z
module F : functor (X : x) (Y : y) (Z : z) -> sig end
|}]
module M = F(X)(Z)
[%%expect {|
Line 1, characters 11-18:
1 | module M = F(X)(Z)
^^^^^^^
Error: The functor application is ill-typed.
These arguments:
X Z
do not match these parameters:
functor (X : x) (Y : y) (Z : z) -> ...
1. Module X matches the expected module type x
2. An argument appears to be missing with module type y
3. Module Z matches the expected module type z
|}]
module type f = functor (X:empty)(Y:empty) -> empty
module F: f =
functor(X:empty)(Y:empty)(Z:empty) -> Empty
[%%expect {|
module type f = functor (X : empty) (Y : empty) -> empty
Line 3, characters 9-45:
3 | functor(X:empty)(Y:empty)(Z:empty) -> Empty
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
functor (X : empty) (Y : empty) (Z : empty) -> ...
is not included in
functor (X : empty) (Y : empty) -> ...
1. Module types empty and empty match
2. Module types empty and empty match
3. An extra argument is provided of module type empty
|}]
module type f = functor (X:a)(Y:b) -> c
module F:f = functor (X:a)(Y:b)(Z:c) -> Empty
[%%expect {|
module type f = functor (X : a) (Y : b) -> c
Line 2, characters 21-45:
2 | module F:f = functor (X:a)(Y:b)(Z:c) -> Empty
^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
functor (X : a) (Y : b) (Z : c) -> ...
is not included in
functor (X : a) (Y : b) -> ...
1. Module types a and a match
2. Module types b and b match
3. An extra argument is provided of module type c
|}]
module M : sig module F: functor (X:sig end) -> sig end end =
struct
module F(X:sig type t end) = struct end
end
[%%expect {|
Lines 2-4, characters 2-5:
2 | ..struct
3 | module F(X:sig type t end) = struct end
4 | end
Error: Signature mismatch:
Modules do not match:
sig module F : functor (X : sig type t end) -> sig end end
is not included in
sig module F : functor (X : sig end) -> sig end end
In module F:
Modules do not match:
functor (X : $S1) -> ...
is not included in
functor (X : sig end) -> ...
Module types do not match:
$S1 = sig type t end
does not include
sig end
The type `t' is required but not provided
|}]
module F(X:sig type t end) = struct end
module M = F(struct type x end)
[%%expect {|
module F : functor (X : sig type t end) -> sig end
Line 2, characters 11-31:
2 | module M = F(struct type x end)
^^^^^^^^^^^^^^^^^^^^
Error: Modules do not match: sig type x end is not included in sig type t end
The type `t' is required but not provided
|}]
module F(X:sig type x end)(Y:sig type y end)(Z:sig type z end) = struct
type t = X of X.x | Y of Y.y | Z of Z.z
end
type u = F(X)(Z).t
[%%expect {|
module F :
functor (X : sig type x end) (Y : sig type y end) (Z : sig type z end) ->
sig type t = X of X.x | Y of Y.y | Z of Z.z end
Line 4, characters 9-18:
4 | type u = F(X)(Z).t
^^^^^^^^^
Error: The functor application F(X)(Z) is ill-typed.
These arguments:
X Z
do not match these parameters:
functor (X : ...) (Y : $T2) (Z : ...) -> ...
1. Module X matches the expected module type
2. An argument appears to be missing with module type
$T2 = sig type y end
3. Module Z matches the expected module type
|}]
module F()(X:sig type t end) = struct end
module M = F()()
[%%expect {|
module F : functor () (X : sig type t end) -> sig end
Line 2, characters 11-16:
2 | module M = F()()
^^^^^
Error: The functor application is ill-typed.
These arguments:
() ()
do not match these parameters:
functor () (X : $T2) -> ...
1. Module () matches the expected module type
2. The functor was expected to be applicative at this position
|}]
module M: sig
module F: functor(X:sig type x end)(X:sig type y end) -> sig end
end = struct
module F(X:sig type y end) = struct end
end
[%%expect {|
Lines 3-5, characters 6-3:
3 | ......struct
4 | module F(X:sig type y end) = struct end
5 | end
Error: Signature mismatch:
Modules do not match:
sig module F : functor (X : sig type y end) -> sig end end
is not included in
sig
module F :
functor (X : sig type x end) (X : sig type y end) -> sig end
end
In module F:
Modules do not match:
functor (X : $S2) -> ...
is not included in
functor (X : $T1) (X : $T2) -> ...
1. An argument appears to be missing with module type
$T1 = sig type x end
2. Module types $S2 and $T2 match
|}]
module F(Ctx: sig
module type t
module type u
module X:t
module Y:u
end) = struct
open Ctx
module F(A:t)(B:u) = struct end
module M = F(Y)(X)
end
[%%expect {|
Line 9, characters 13-20:
9 | module M = F(Y)(X)
^^^^^^^
Error: The functor application is ill-typed.
These arguments:
Ctx.Y Ctx.X
do not match these parameters:
functor (A : Ctx.t) (B : Ctx.u) -> ...
1. Modules do not match: Ctx.Y : Ctx.u is not included in Ctx.t
2. Modules do not match: Ctx.X : Ctx.t is not included in Ctx.u
|}]
module Ord = struct type t = unit let compare _ _ = 0 end
module M = Map.Make(Ord)(Ord)
[%%expect {|
module Ord : sig type t = unit val compare : 'a -> 'b -> int end
Line 2, characters 11-29:
2 | module M = Map.Make(Ord)(Ord)
^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
Ord Ord
do not match these parameters:
functor (Ord : Map.OrderedType) -> ...
1. The following extra argument is provided
Ord : sig type t = unit val compare : 'a -> 'b -> int end
2. Module Ord matches the expected module type Map.OrderedType
|}]
module F
(A:sig type x type y end)
(B:sig type x = A.x end)
(C:sig type y = A.y end)
= struct end
module K = struct include X include Y end
[%%expect {|
module F :
functor (A : sig type x type y end) (B : sig type x = A.x end)
(C : sig type y = A.y end) -> sig end
module K : sig type x = X.x type y = Y.y end
Line 10, characters 11-73:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
K $S2 ()
do not match these parameters:
functor (A : ...) (B : ...) (C : $T3) -> ...
1. Module K matches the expected module type
2. Module $S2 matches the expected module type
3. The functor was expected to be applicative at this position
|}]
module M = F(K)(struct type y = K.y end)
[%%expect {|
Line 1, characters 11-40:
1 | module M = F(K)(struct type y = K.y end)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
K $S3
do not match these parameters:
functor (A : ...) (B : $T2) (C : ...) -> ...
1. Module K matches the expected module type
2. An argument appears to be missing with module type
$T2 = sig type x = A.x end
3. Module $S3 matches the expected module type
|}]
module M =
F
(struct include X include Y end)
(struct type x = K.x end)
(struct type yy = K.y end)
[%%expect {|
Lines 2-5, characters 2-30:
2 | ..F
3 | (struct include X include Y end)
4 | (struct type x = K.x end)
5 | (struct type yy = K.y end)
Error: The functor application is ill-typed.
These arguments:
$S1 $S2 $S3
do not match these parameters:
functor (A : ...) (B : ...) (C : $T3) -> ...
1. Module $S1 matches the expected module type
2. Module $S2 matches the expected module type
3. Modules do not match:
$S3 : sig type yy = K.y end
is not included in
$T3 = sig type y = A.y end
The type `y' is required but not provided
|}]
module M = struct
module N = struct
type x
type y
end
end
module Defs = struct
module X = struct type x = M.N.x end
module Y = struct type y = M.N.y end
end
module Missing_X = F(M.N)(Defs.Y)
[%%expect {|
module M : sig module N : sig type x type y end end
module Defs :
sig module X : sig type x = M.N.x end module Y : sig type y = M.N.y end end
Line 13, characters 19-33:
13 | module Missing_X = F(M.N)(Defs.Y)
^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
M.N Defs.Y
do not match these parameters:
functor (A : ...) (B : $T2) (C : ...) -> ...
1. Module M.N matches the expected module type
2. An argument appears to be missing with module type
$T2 = sig type x = A.x end
3. Module Defs.Y matches the expected module type
|}]
module Too_many_Xs = F(M.N)(Defs.X)(Defs.X)(Defs.Y)
[%%expect {|
Line 1, characters 21-51:
1 | module Too_many_Xs = F(M.N)(Defs.X)(Defs.X)(Defs.Y)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
M.N Defs.X Defs.X Defs.Y
do not match these parameters:
functor (A : ...) (B : ...) (C : ...) -> ...
1. Module M.N matches the expected module type
2. The following extra argument is provided
Defs.X : sig type x = M.N.x end
3. Module Defs.X matches the expected module type
4. Module Defs.Y matches the expected module type
|}]
module X = struct type x = int end
module Y = struct type y = float end
module Missing_X_bis = F(struct type x = int type y = float end)(Y)
[%%expect {|
module X : sig type x = int end
module Y : sig type y = float end
Line 3, characters 23-67:
3 | module Missing_X_bis = F(struct type x = int type y = float end)(Y)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
$S1 Y
do not match these parameters:
functor (A : ...) (B : $T2) (C : ...) -> ...
1. Module $S1 matches the expected module type
2. An argument appears to be missing with module type
$T2 = sig type x = A.x end
3. Module Y matches the expected module type
|}]
module Too_many_Xs_bis = F(struct type x = int type y = float end)(X)(X)(Y)
[%%expect {|
Line 1, characters 25-75:
1 | module Too_many_Xs_bis = F(struct type x = int type y = float end)(X)(X)(Y)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
$S1 X X Y
do not match these parameters:
functor (A : ...) (B : ...) (C : ...) -> ...
1. Module $S1 matches the expected module type
2. The following extra argument is provided X : sig type x = int end
3. Module X matches the expected module type
4. Module Y matches the expected module type
|}]
module type f =
functor(A:sig type x type y end)(B:sig type x = A.x end)(C:sig type y = A.y end)
-> sig end
module F: f = functor (A:sig include x include y end)(Z:sig type y = A.y end) -> struct end
[%%expect {|
module type f =
functor (A : sig type x type y end) (B : sig type x = A.x end)
(C : sig type y = A.y end) -> sig end
Line 4, characters 22-91:
4 | module F: f = functor (A:sig include x include y end)(Z:sig type y = A.y end) -> struct end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
functor (A : $S1) (Z : $S3) -> ...
is not included in
functor (A : $T1) (B : $T2) (C : $T3) -> ...
1. Module types $S1 and $T1 match
2. An argument appears to be missing with module type
$T2 = sig type x = A.x end
3. Module types $S3 and $T3 match
|}]
module type f =
functor(B:sig type x type y type u=x type v=y end)(Y:sig type yu = Y of B.u end)(Z:sig type zv = Z of B.v end)
-> sig end
module F: f = functor (X:sig include x include y end)(Z:sig type zv = Z of X.y end) -> struct end
[%%expect {|
module type f =
functor (B : sig type x type y type u = x type v = y end)
(Y : sig type yu = Y of B.u end) (Z : sig type zv = Z of B.v end) ->
sig end
Line 4, characters 22-97:
4 | module F: f = functor (X:sig include x include y end)(Z:sig type zv = Z of X.y end) -> struct end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
functor (X : $S1) (Z : $S3) -> ...
is not included in
functor (B : $T1) (Y : $T2) (Z : $T3) -> ...
1. Module types $S1 and $T1 match
2. An argument appears to be missing with module type
$T2 = sig type yu = Y of B.u end
3. Module types $S3 and $T3 match
|}]
module M: sig
module type S = sig type t end
end = struct
module type S = sig type s type t end
end;;
[%%expect {|
Lines 5-7, characters 6-3:
5 | ......struct
6 | module type S = sig type s type t end
7 | end..
Error: Signature mismatch:
Modules do not match:
sig module type S = sig type s type t end end
is not included in
sig module type S = sig type t end end
Module type declarations do not match:
module type S = sig type s type t end
does not match
module type S = sig type t end
The second module type is not included in the first
At position module type S = <here>
Module types do not match:
sig type t end
is not equal to
sig type s type t end
At position module type S = <here>
The type `s' is required but not provided
|}]
module M: sig
module type S = sig type t type u end
end = struct
module type S = sig type t end
end;;
[%%expect {|
Lines 3-5, characters 6-3:
3 | ......struct
4 | module type S = sig type t end
5 | end..
Error: Signature mismatch:
Modules do not match:
sig module type S = sig type t end end
is not included in
sig module type S = sig type t type u end end
Module type declarations do not match:
module type S = sig type t end
does not match
module type S = sig type t type u end
The first module type is not included in the second
At position module type S = <here>
Module types do not match:
sig type t end
is not equal to
sig type t type u end
At position module type S = <here>
The type `u' is required but not provided
|}]
module F(X:x)(B:b)(Y:y) = struct type t end
module M = struct
module type b
module G(P: sig module B:b end) = struct
open P
module U = F(struct type x end)(B)(struct type w end)
end
end
[%%expect {|
module F : functor (X : x) (B : b) (Y : y) -> sig type t end
Line 8, characters 15-57:
8 | module U = F(struct type x end)(B)(struct type w end)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
$S1 P.B $S3
do not match these parameters:
functor (X : x) (B : b/2) (Y : y) -> ...
1. Module $S1 matches the expected module type x
2. Modules do not match:
P.B : b
is not included in
b/2
Line 5, characters 2-15:
Definition of module type b
Line 2, characters 0-13:
Definition of module type b/2
3. Modules do not match: $S3 : sig type w end is not included in y
|}]
module F(X:a) = struct type t end
module M = struct
module type a
module G(P: sig module X:a end) = struct
open P
type t = F(X).t
end
end
[%%expect {|
module F : functor (X : a) -> sig type t end
Line 6, characters 13-19:
6 | type t = F(X).t
^^^^^^
Error: Modules do not match: a is not included in a/2
Line 3, characters 2-15:
Definition of module type a
Line 1, characters 0-13:
Definition of module type a/2
|}]
module M: sig module F: functor(X:a)(Y:a) -> sig end end =
struct
module type aa = a
module type a
module F(X:aa)(Y:a) = struct end
end
[%%expect {|
Lines 2-6, characters 1-3:
2 | .struct
3 | module type aa = a
4 | module type a
5 | module F(X:aa)(Y:a) = struct end
6 | end
Error: Signature mismatch:
Modules do not match:
sig
module type aa = a
module type a
module F : functor (X : aa) (Y : a) -> sig end
end
is not included in
sig module F : functor (X : a) (Y : a) -> sig end end
In module F:
Modules do not match:
functor (X : aa) (Y : a) -> ...
is not included in
functor (X : a/2) (Y : a/2) -> ...
1. Module types aa and a/2 match
2. Module types do not match:
a
does not include
a/2
Line 4, characters 2-15:
Definition of module type a
Line 1, characters 0-13:
Definition of module type a/2
|}]
module X: functor ( X: sig end) -> sig end = functor(X: Set.OrderedType) -> struct end
[%%expect {|
Line 1, characters 52-86:
1 | module X: functor ( X: sig end) -> sig end = functor(X: Set.OrderedType) -> struct end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
functor (X : Set.OrderedType) -> ...
is not included in
functor (X : sig end) -> ...
Module types do not match:
Set.OrderedType
does not include
sig end
The type `t' is required but not provided
File "set.mli", line 52, characters 4-10: Expected declaration
The value `compare' is required but not provided
File "set.mli", line 55, characters 4-31: Expected declaration
|}]
module M: sig
module F: functor
(X:
functor(A: sig type xa end)(B:sig type xz end) -> sig end
)
(Y:
functor(A: sig type ya end)(B:sig type yb end) -> sig end
)
(Z:
functor(A: sig type za end)(B:sig type zb end) -> sig end
) -> sig end
end = struct
module F
(X:
functor (A: sig type xa end)(B:sig type xz end) -> sig end
)
(Y:
functor (A: sig type ya end)(B:sig type ybb end) -> sig end
)
(Z:
functor (A: sig type za end)(B:sig type zbb end) -> sig end
)
= struct end
end
[%%expect {|
Lines 15-27, characters 6-3:
15 | ......struct
16 | module F
17 | (X:
18 | functor (A: sig type xa end)(B:sig type xz end) -> sig end
19 | )
...
24 | functor (A: sig type za end)(B:sig type zbb end) -> sig end
25 | )
26 | = struct end
27 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
functor
(X : functor (A : sig type xa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type ybb end) ->
sig end)
(Z : functor (A : sig type za end) (B : sig type zbb end) ->
sig end)
-> sig end
end
is not included in
sig
module F :
functor
(X : functor (A : sig type xa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type yb end) ->
sig end)
(Z : functor (A : sig type za end) (B : sig type zb end) ->
sig end)
-> sig end
end
In module F:
Modules do not match:
functor (X : $S1) (Y : $S2) (Z : $S3) -> ...
is not included in
functor (X : $T1) (Y : $T2) (Z : $T3) -> ...
1. Module types $S1 and $T1 match
2. Module types do not match:
$S2 =
functor (A : sig type ya end) (B : sig type ybb end) -> sig end
does not include
$T2 =
functor (A : sig type ya end) (B : sig type yb end) -> sig end
Modules do not match:
functor (A : $S1) (B : $S2) -> ...
is not included in
functor (A : $T1) (B : $T2) -> ...
1. Module types $S1 and $T1 match
2. Module types do not match:
$S2 = sig type yb end
does not include
$T2 = sig type ybb end
The type `yb' is required but not provided
3. Module types do not match:
$S3 =
functor (A : sig type za end) (B : sig type zbb end) -> sig end
does not include
$T3 =
functor (A : sig type za end) (B : sig type zb end) -> sig end
Modules do not match:
functor (A : $S1) (B : $S2) -> ...
is not included in
functor (A : $T1) (B : $T2) -> ...
|}]
module M: sig
module F: functor
(X:
functor(A: sig type xa end)(B:sig type xz end) -> sig end
)
(Y:
functor(A: sig type ya end)(B:sig type yb end) -> sig end
)
(Z:
functor(A: sig type za end)(B:sig type zb end) -> sig end
) -> sig end
end = struct
module F
(X:
functor (A: sig type xa end)(B:sig type xz end) -> sig end
)
(Y:
functor (A: sig type ya end)(B:sig type yb end) -> sig end
)
= struct end
end
[%%expect {|
Lines 12-21, characters 6-3:
12 | ......struct
13 | module F
14 | (X:
15 | functor (A: sig type xa end)(B:sig type xz end) -> sig end
16 | )
17 | (Y:
18 | functor (A: sig type ya end)(B:sig type yb end) -> sig end
19 | )
20 | = struct end
21 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
functor
(X : functor (A : sig type xa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type yb end) ->
sig end)
-> sig end
end
is not included in
sig
module F :
functor
(X : functor (A : sig type xa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type yb end) ->
sig end)
(Z : functor (A : sig type za end) (B : sig type zb end) ->
sig end)
-> sig end
end
In module F:
Modules do not match:
functor (X : $S1) (Y : $S2) -> ...
is not included in
functor (X : $T1) (Y : $T2) (Z : $T3) -> ...
1. Module types $S1 and $T1 match
2. Module types $S2 and $T2 match
3. An argument appears to be missing with module type
$T3 =
functor (A : sig type za end) (B : sig type zb end) -> sig end
|}]
module M: sig
module F: functor
(X:
functor(A: sig type xa end)(B:sig type xz end) -> sig end
)
(Y:
functor(A: sig type ya end)(B:sig type yb end) -> sig end
)
(Z:
functor(A: sig type za end)(B:sig type zb end) -> sig end
) -> sig end
end = struct
module F
(X:
functor (A: sig type xaa end)(B:sig type xz end) -> sig end
)
(Y:
functor (A: sig type ya end)(B:sig type ybb end) -> sig end
)
(Z:
functor (A: sig type za end)(B:sig type zbb end) -> sig end
)
= struct end
end
[%%expect {|
Lines 12-24, characters 6-3:
12 | ......struct
13 | module F
14 | (X:
15 | functor (A: sig type xaa end)(B:sig type xz end) -> sig end
16 | )
...
21 | functor (A: sig type za end)(B:sig type zbb end) -> sig end
22 | )
23 | = struct end
24 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
functor
(X : functor (A : sig type xaa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type ybb end) ->
sig end)
(Z : functor (A : sig type za end) (B : sig type zbb end) ->
sig end)
-> sig end
end
is not included in
sig
module F :
functor
(X : functor (A : sig type xa end) (B : sig type xz end) ->
sig end)
(Y : functor (A : sig type ya end) (B : sig type yb end) ->
sig end)
(Z : functor (A : sig type za end) (B : sig type zb end) ->
sig end)
-> sig end
end
In module F:
Modules do not match:
functor (X : $S1) (Y : $S2) (Z : $S3) -> ...
is not included in
functor (X : $T1) (Y : $T2) (Z : $T3) -> ...
1. Module types do not match:
$S1 =
functor (A : sig type xaa end) (B : sig type xz end) -> sig end
does not include
$T1 =
functor (A : sig type xa end) (B : sig type xz end) -> sig end
Modules do not match:
functor (A : $S1) (B : $S2) -> ...
is not included in
functor (A : $T1) (B : $T2) -> ...
1. Module types do not match:
$S1 = sig type xa end
does not include
$T1 = sig type xaa end
The type `xa' is required but not provided
2. Module types $S2 and $T2 match
2. Module types do not match:
$S2 =
functor (A : sig type ya end) (B : sig type ybb end) -> sig end
does not include
$T2 =
functor (A : sig type ya end) (B : sig type yb end) -> sig end
Modules do not match:
functor (A : $S1) (B : $S2) -> ...
is not included in
functor (A : $T1) (B : $T2) -> ...
3. Module types do not match:
$S3 =
functor (A : sig type za end) (B : sig type zbb end) -> sig end
does not include
$T3 =
functor (A : sig type za end) (B : sig type zb end) -> sig end
Modules do not match:
functor (A : $S1) (B : $S2) -> ...
is not included in
functor (A : $T1) (B : $T2) -> ...
|}]
module A: sig
module B: sig
module C: sig
module D: sig
module E: sig
module F: sig type x end -> sig type y end
-> sig type z end -> sig type w end -> sig end
end
end
end
end
end = struct
module B = struct
module C = struct
module D = struct
module E = struct
module F(X:sig type x end)(Y:sig type y' end)
(W:sig type w end) = struct end
end
end
end
end
end
[%%expect {|
Lines 12-23, characters 6-3:
12 | ......struct
13 | module B = struct
14 | module C = struct
15 | module D = struct
16 | module E = struct
...
20 | end
21 | end
22 | end
23 | end
Error: Signature mismatch:
Modules do not match:
sig
module B :
sig
module C :
sig
module D :
sig
module E :
sig
module F :
functor (X : sig type x end)
(Y : sig type y' end) (W : sig type w end) ->
sig end
end
end
end
end
end
is not included in
sig
module B :
sig
module C :
sig
module D :
sig
module E :
sig
module F :
sig type x end -> sig type y end ->
sig type z end -> sig type w end -> sig end
end
end
end
end
end
In module B:
Modules do not match:
sig module C = B.C end
is not included in
sig
module C :
sig
module D :
sig
module E :
sig
module F :
sig type x end -> sig type y end ->
sig type z end -> sig type w end -> sig end
end
end
end
end
In module B.C:
Modules do not match:
sig module D = B.C.D end
is not included in
sig
module D :
sig
module E :
sig
module F :
sig type x end -> sig type y end -> sig type z end ->
sig type w end -> sig end
end
end
end
In module B.C.D:
Modules do not match:
sig module E = B.C.D.E end
is not included in
sig
module E :
sig
module F :
sig type x end -> sig type y end -> sig type z end ->
sig type w end -> sig end
end
end
In module B.C.D.E:
Modules do not match:
sig module F = B.C.D.E.F end
is not included in
sig
module F :
sig type x end -> sig type y end -> sig type z end ->
sig type w end -> sig end
end
In module B.C.D.E.F:
Modules do not match:
functor (X : $S1) (Y : $S3) (W : $S4) -> ...
is not included in
functor $T1 $T2 $T3 $T4 -> ...
1. Module types $S1 and $T1 match
2. An argument appears to be missing with module type
$T2 = sig type y end
3. Module types do not match:
$S3 = sig type y' end
does not include
$T3 = sig type z end
4. Module types $S4 and $T4 match
|}]
module type Arg = sig
module type A
module type Honorificabilitudinitatibus
module X: Honorificabilitudinitatibus
module Y: A
end
module F(A:Arg)
= struct
open A
module G(X:A)(Y:A)(_:A)(Z:A) = struct end
type u = G(X)(Y)(X)(Y)(X).t
end;;
[%%expect {|
module type Arg =
sig
module type A
module type Honorificabilitudinitatibus
module X : Honorificabilitudinitatibus
module Y : A
end
Line 14, characters 11-29:
14 | type u = G(X)(Y)(X)(Y)(X).t
^^^^^^^^^^^^^^^^^^
Error: The functor application G(X)(Y)(X)(Y)(X) is ill-typed.
These arguments:
A.X A.Y A.X A.Y A.X
do not match these parameters:
functor (X : A.A) (Y : A.A) A.A (Z : A.A) -> ...
1. The following extra argument is provided
A.X : A.Honorificabilitudinitatibus
2. Module A.Y matches the expected module type A.A
3. Modules do not match:
A.X : A.Honorificabilitudinitatibus
is not included in
A.A
4. Module A.Y matches the expected module type A.A
5. Modules do not match:
A.X : A.Honorificabilitudinitatibus
is not included in
A.A
|}]
module type s = functor
(X: sig type when_ type shall type we type three type meet type again end)
(Y:sig type in_ val thunder:in_ val lightning: in_ type rain end)
(Z:sig type when_ type the type hurlyburly's type done_ end)
(Z:sig type when_ type the type battle's type lost type and_ type won end)
(W:sig type that type will type be type ere type the_ type set type of_ type sun end)
(S: sig type where type the type place end)
(R: sig type upon type the type heath end)
-> sig end
module F: s = functor
(X: sig type when_ type shall type we type tree type meet type again end)
(Y:sig type in_ val thunder:in_ val lightning: in_ type pain end)
(Z:sig type when_ type the type hurlyburly's type gone end)
(Z:sig type when_ type the type battle's type last type and_ type won end)
(W:sig type that type will type be type the type era type set type of_ type sun end)
(S: sig type where type the type lace end)
(R: sig type upon type the type heart end)
-> struct end
[%%expect {|
module type s =
functor
(X : sig
type when_
type shall
type we
type three
type meet
type again
end)
(Y : sig type in_ val thunder : in_ val lightning : in_ type rain end)
(Z : sig type when_ type the type hurlyburly's type done_ end)
(Z : sig
type when_
type the
type battle's
type lost
type and_
type won
end)
(W : sig
type that
type will
type be
type ere
type the_
type set
type of_
type sun
end)
(S : sig type where type the type place end)
(R : sig type upon type the type heath end) -> sig end
Lines 11-18, characters 2-15:
11 | ..(X: sig type when_ type shall type we type tree type meet type again end)
12 | (Y:sig type in_ val thunder:in_ val lightning: in_ type pain end)
13 | (Z:sig type when_ type the type hurlyburly's type gone end)
14 | (Z:sig type when_ type the type battle's type last type and_ type won end)
15 | (W:sig type that type will type be type the type era type set type of_ type sun end)
16 | (S: sig type where type the type lace end)
17 | (R: sig type upon type the type heart end)
18 | -> struct end
Error: Signature mismatch:
Modules do not match:
functor (X : $S1) (Y : $S2) (Z : $S3) (Z : $S4) (W : $S5) (S : $S6)
(R : $S7) -> ...
is not included in
functor (X : $T1) (Y : $T2) (Z : $T3) (Z : $T4) (W : $T5) (S : $T6)
(R : $T7) -> ...
1. Module types do not match:
$S1 =
sig
type when_
type shall
type we
type tree
type meet
type again
end
does not include
$T1 =
sig
type when_
type shall
type we
type three
type meet
type again
end
The type `tree' is required but not provided
2. Module types do not match:
$S2 =
sig type in_ val thunder : in_ val lightning : in_ type pain end
does not include
$T2 =
sig type in_ val thunder : in_ val lightning : in_ type rain end
3. Module types do not match:
$S3 = sig type when_ type the type hurlyburly's type gone end
does not include
$T3 = sig type when_ type the type hurlyburly's type done_ end
4. Module types do not match:
$S4 =
sig
type when_
type the
type battle's
type last
type and_
type won
end
does not include
$T4 =
sig
type when_
type the
type battle's
type lost
type and_
type won
end
5. Module types do not match:
$S5 =
sig
type that
type will
type be
type the
type era
type set
type of_
type sun
end
does not include
$T5 =
sig
type that
type will
type be
type ere
type the_
type set
type of_
type sun
end
6. Module types do not match:
$S6 = sig type where type the type lace end
does not include
$T6 = sig type where type the type place end
7. Module types do not match:
$S7 = sig type upon type the type heart end
does not include
$T7 = sig type upon type the type heath end
|}]
module F(X:sig type witness module type t module M:t end) = X.M
module PF = struct
type witness
module type t = module type of F
module M = F
end
module U = F(PF)(PF)(PF)
[%%expect {|
module F :
functor (X : sig type witness module type t module M : t end) -> X.t
module PF :
sig
type witness
module type t =
functor (X : sig type witness module type t module M : t end) -> X.t
module M = F
end
module U : PF.t
|}]
module W = F(PF)(PF)(PF)(PF)(PF)(F)
[%%expect {|
Line 1, characters 11-35:
1 | module W = F(PF)(PF)(PF)(PF)(PF)(F)
^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
PF PF PF PF PF F
do not match these parameters:
functor (X : ...) (X : ...) (X : ...) (X : ...) (X : ...) (X : $T6)
-> ...
1. Module PF matches the expected module type
2. Module PF matches the expected module type
3. Module PF matches the expected module type
4. Module PF matches the expected module type
5. Module PF matches the expected module type
6. Modules do not match:
F :
functor (X : sig type witness module type t module M : t end) ->
X.t
is not included in
$T6 = sig type witness module type t module M : t end
Modules do not match:
functor (X : $S1) -> ...
is not included in
functor -> ...
An extra argument is provided of module type
$S1 = sig type witness module type t module M : t end
|}]
module type arg = sig type arg end
module A = struct type arg end
module Add_one' = struct
module M(_:arg) = A
module type t = module type of M
end
module Add_one = struct type witness include Add_one' end
module Add_three' = struct
module M(_:arg)(_:arg)(_:arg) = A
module type t = module type of M
end
module Add_three = struct
include Add_three'
type witness
end
module Wrong_intro = F(Add_three')(A)(A)(A)
[%%expect {|
module type arg = sig type arg end
module A : sig type arg end
module Add_one' :
sig
module M : arg -> sig type arg = A.arg end
module type t = arg -> sig type arg = A.arg end
end
module Add_one :
sig type witness module M = Add_one'.M module type t = Add_one'.t end
module Add_three' :
sig
module M : arg -> arg -> arg -> sig type arg = A.arg end
module type t = arg -> arg -> arg -> sig type arg = A.arg end
end
module Add_three :
sig module M = Add_three'.M module type t = Add_three'.t type witness end
Line 22, characters 21-43:
22 | module Wrong_intro = F(Add_three')(A)(A)(A)
^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
Add_three' A A A
do not match these parameters:
functor (X : $T1) arg arg arg -> ...
1. Modules do not match:
Add_three' :
sig module M = Add_three'.M module type t = Add_three'.t end
is not included in
$T1 = sig type witness module type t module M : t end
The type `witness' is required but not provided
2. Module A matches the expected module type arg
3. Module A matches the expected module type arg
4. Module A matches the expected module type arg
|}]
module Choose_one = F(Add_one')(Add_three)(A)(A)(A)
[%%expect {|
Line 1, characters 20-51:
1 | module Choose_one = F(Add_one')(Add_three)(A)(A)(A)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
Add_one' Add_three A A A
do not match these parameters:
functor (X : ...) arg arg arg -> ...
1. The following extra argument is provided
Add_one' :
sig module M = Add_one'.M module type t = Add_one'.t end
2. Module Add_three matches the expected module type
3. Module A matches the expected module type arg
4. Module A matches the expected module type arg
5. Module A matches the expected module type arg
|}]
* Known lmitation : we choose the wrong environment without the
error on Add_one
*
error on Add_one
**)
module Mislead_chosen_one = F(Add_one)(Add_three)(A)(A)(A)
[%%expect {|
Line 1, characters 28-58:
1 | module Mislead_chosen_one = F(Add_one)(Add_three)(A)(A)(A)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
Add_one Add_three A A A
do not match these parameters:
functor (X : ...) arg arg arg -> ...
1. The following extra argument is provided
Add_one :
sig
type witness = Add_one.witness
module M = Add_one'.M
module type t = Add_one.t
end
2. Module Add_three matches the expected module type
3. Module A matches the expected module type arg
4. Module A matches the expected module type arg
5. Module A matches the expected module type arg
|}]
module M: sig
module F:
functor (X:sig
type x
module type t =
functor
(Y:sig type y end)
(Z:sig type z end)
-> sig end
end) -> X.t
end
= struct
module F(X:sig type x end)(Z:sig type z end) = struct end
end
[%%expect {|
Lines 14-16, characters 2-3:
14 | ..struct
15 | module F(X:sig type x end)(Z:sig type z end) = struct end
16 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
functor (X : sig type x end) (Z : sig type z end) -> sig end
end
is not included in
sig
module F :
functor
(X : sig
type x
module type t =
functor (Y : sig type y end) (Z : sig type z end) ->
sig end
end)
-> X.t
end
In module F:
Modules do not match:
functor (X : $S1) (Z : $S3) -> ...
is not included in
functor (X : $T1) (Y : $T2) (Z : $T3) -> ...
1. Module types $S1 and $T1 match
2. An argument appears to be missing with module type
$T2 = sig type y end
3. Module types $S3 and $T3 match
|}]
module M: sig
module F(X: sig
module type T
module type t = T -> T -> T
module M: t
end
)(_:X.T)(_:X.T): X.T
end = struct
module F (Wrong: sig type wrong end)
(X: sig
module type t
module M: t
end) = (X.M : X.t)
end
[%%expect {|
Lines 8-14, characters 6-3:
8 | ......struct
9 | module F (Wrong: sig type wrong end)
10 | (X: sig
11 | module type t
12 | module M: t
13 | end) = (X.M : X.t)
14 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
functor (Wrong : sig type wrong end)
(X : sig module type t module M : t end) -> X.t
end
is not included in
sig
module F :
functor
(X : sig
module type T
module type t = T -> T -> T
module M : t
end)
-> X.T -> X.T -> X.T
end
In module F:
Modules do not match:
functor (Wrong : $S1) (X : $S2) X.T X.T -> ...
is not included in
functor (X : $T2) X.T X.T -> ...
1. An extra argument is provided of module type
$S1 = sig type wrong end
2. Module types $S2 and $T2 match
3. Module types X.T and X.T match
4. Module types X.T and X.T match
|}]
module M: sig
module F(_:sig end)(X:
sig
module type T
module type inner = sig
module type t
module M: t
end
module F(X: inner)(_:T -> T->T):
sig module type res = X.t end
module Y: sig
module type t = T -> T -> T
module M(X:T)(Y:T): T
end
end):
X.F(X.Y)(X.Y.M).res
end = struct
module F(_:sig type wrong end) (X:
sig module type T end
)(Res: X.T)(Res: X.T)(Res: X.T) = Res
end
[%%expect {|
Lines 17-21, characters 6-3:
17 | ......struct
18 | module F(_:sig type wrong end) (X:
19 | sig module type T end
20 | )(Res: X.T)(Res: X.T)(Res: X.T) = Res
21 | end
Error: Signature mismatch:
Modules do not match:
sig
module F :
sig type wrong end ->
functor (X : sig module type T end) (Res : X.T) (Res :
X.T) (Res : X.T)
-> X.T
end
is not included in
sig
module F :
sig end ->
functor
(X : sig
module type T
module type inner =
sig module type t module M : t end
module F :
functor (X : inner) -> (T -> T -> T) ->
sig module type res = X.t end
module Y :
sig
module type t = T -> T -> T
module M : functor (X : T) (Y : T) -> T
end
end)
-> X.F(X.Y)(X.Y.M).res
end
In module F:
Modules do not match:
functor (Arg : $S1) (X : $S2) (Res : X.T) (Res : X.T) (Res :
X.T) -> ...
is not included in
functor (sig end) (X : $T2) X.T X.T -> ...
1. Module types do not match:
$S1 = sig type wrong end
does not include
sig end
The type `wrong' is required but not provided
2. Module types $S2 and $T2 match
3. An extra argument is provided of module type X.T
4. Module types X.T and X.T match
5. Module types X.T and X.T match
|}]
* The price of Gluttony : update of environment leads to a non - optimal edit distance .
module F(X:sig type t end)(Y:sig type t = Y of X.t end)(Z:sig type t = Z of X.t end) = struct end
module X = struct type t = U end
module Y = struct type t = Y of int end
module Z = struct type t = Z of int end
module Error=F(X)(struct type t = int end)(Y)(Z)
[%%expect {|
module F :
functor (X : sig type t end) (Y : sig type t = Y of X.t end)
(Z : sig type t = Z of X.t end) -> sig end
module X : sig type t = U end
module Y : sig type t = Y of int end
module Z : sig type t = Z of int end
Line 9, characters 13-48:
9 | module Error=F(X)(struct type t = int end)(Y)(Z)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
X ... Y Z
do not match these parameters:
functor (X : ...) (Y : $T3) (Z : $T4) -> ...
1. Module X matches the expected module type
2. The following extra argument is provided ... : sig type t = int end
3. Modules do not match:
Y : sig type t = Y.t = Y of int end
is not included in
$T3 = sig type t = Y of X.t end
Type declarations do not match:
type t = Y.t = Y of int
is not included in
type t = Y of X.t
Constructors do not match:
Y of int
is not the same as:
Y of X.t
The type int is not equal to the type X.t
4. Modules do not match:
Z : sig type t = Z.t = Z of int end
is not included in
$T4 = sig type t = Z of X.t end
Type declarations do not match:
type t = Z.t = Z of int
is not included in
type t = Z of X.t
Constructors do not match:
Z of int
is not the same as:
Z of X.t
The type int is not equal to the type X.t
|}]
* Final state in the presence of extensions
Test provided by in
#pullrequestreview-492359720
Test provided by Leo White in
#pullrequestreview-492359720
*)
module type A = sig type a end
module A = struct type a end
module type B = sig type b end
module B = struct type b end
module type ty = sig type t end
module TY = struct type t end
module type Ext = sig module type T module X : T end
module AExt = struct module type T = A module X = A end
module FiveArgsExt = struct
module type T = ty -> ty -> ty -> ty -> ty -> sig end
module X : T =
functor (_ : ty) (_ : ty) (_ : ty) (_ : ty) (_ : ty) -> struct end
end
module Bar (W : A) (X : Ext) (Y : B) (Z : Ext) = Z.X
type fine = Bar(A)(FiveArgsExt)(B)(AExt).a
[%%expect{|
module type A = sig type a end
module A : sig type a end
module type B = sig type b end
module B : sig type b end
module type ty = sig type t end
module TY : sig type t end
module type Ext = sig module type T module X : T end
module AExt : sig module type T = A module X = A end
module FiveArgsExt :
sig module type T = ty -> ty -> ty -> ty -> ty -> sig end module X : T end
module Bar : functor (W : A) (X : Ext) (Y : B) (Z : Ext) -> Z.T
type fine = Bar(A)(FiveArgsExt)(B)(AExt).a
|}]
type broken1 = Bar(B)(FiveArgsExt)(B)(AExt).a
[%%expect{|
Line 1, characters 15-45:
1 | type broken1 = Bar(B)(FiveArgsExt)(B)(AExt).a
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application Bar(B)(FiveArgsExt)(B)(AExt) is ill-typed.
These arguments:
B FiveArgsExt B AExt
do not match these parameters:
functor (W : A) (X : Ext) (Y : B) (Z : Ext) -> ...
1. Modules do not match:
B : sig type b = B.b end
is not included in
A
The type `a' is required but not provided
2. Module FiveArgsExt matches the expected module type Ext
3. Module B matches the expected module type B
4. Module AExt matches the expected module type Ext
|}]
type broken2 = Bar(A)(FiveArgsExt)(TY)(TY)(TY)(TY)(TY).a
[%%expect{|
Line 1, characters 15-56:
1 | type broken2 = Bar(A)(FiveArgsExt)(TY)(TY)(TY)(TY)(TY).a
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application Bar(A)(FiveArgsExt)(TY)(TY)(TY)(TY)(TY) is ill-typed.
These arguments:
A FiveArgsExt TY TY TY TY TY
do not match these parameters:
functor (W : A) (X : Ext) (Y : B) (Z : Ext) ty ty ty ty ty -> ...
1. Module A matches the expected module type A
2. An argument appears to be missing with module type Ext
3. An argument appears to be missing with module type B
4. Module FiveArgsExt matches the expected module type Ext
5. Module TY matches the expected module type ty
6. Module TY matches the expected module type ty
7. Module TY matches the expected module type ty
8. Module TY matches the expected module type ty
9. Module TY matches the expected module type ty
|}]
module Shape_arg = struct
module M1 (Arg1 : sig end) = struct
module type S1 = sig
type t
end
end
module type S2 = sig
module Make (Arg2 : sig end) : M1(Arg2).S1
end
module M2 : S2 = struct
module Make (Arg3 : sig end) = struct
type t = T
end
end
module M3 (Arg4 : sig end) = struct
module type S3 = sig
type t = M2.Make(Arg4).t
end
end
module M4 (Arg5 : sig end) : M3(Arg5).S3 = struct
module M5 = M2.Make (Arg5)
type t = M5.t
end
end
[%%expect{|
module Shape_arg :
sig
module M1 :
functor (Arg1 : sig end) -> sig module type S1 = sig type t end end
module type S2 =
sig module Make : functor (Arg2 : sig end) -> M1(Arg2).S1 end
module M2 : S2
module M3 :
functor (Arg4 : sig end) ->
sig module type S3 = sig type t = M2.Make(Arg4).t end end
module M4 : functor (Arg5 : sig end) -> M3(Arg5).S3
end
|}]
module F(X:A) = struct end
module R = F(struct end[@warning "-73"]);;
[%%expect {|
module F : functor (X : A) -> sig end
Line 2, characters 11-40:
2 | module R = F(struct end[@warning "-73"]);;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Modules do not match: sig end is not included in A
The type `a' is required but not provided
|}]
module F()(X:empty)()(Y:A) = struct end
module R =
F(struct end[@warning "-73"])(struct end)(struct end[@warning "-73"])();;
[%%expect {|
module F : functor () (X : empty) () (Y : A) -> sig end
Line 3, characters 2-73:
3 | F(struct end[@warning "-73"])(struct end)(struct end[@warning "-73"])();;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
(struct end) (struct end) (struct end) ()
do not match these parameters:
functor () (X : empty) () (Y : A) -> ...
1. Module (struct end) matches the expected module type
2. Module (struct end) matches the expected module type empty
3. Module (struct end) matches the expected module type
4. The functor was expected to be applicative at this position
|}]
module F(X:empty) = struct end
module R =
F(struct end)();;
[%%expect {|
module F : functor (X : empty) -> sig end
Line 3, characters 2-17:
3 | F(struct end)();;
^^^^^^^^^^^^^^^
Error: The functor application is ill-typed.
These arguments:
(struct end) ()
do not match these parameters:
functor (X : empty) -> ...
1. Module (struct end) matches the expected module type empty
2. The following extra argument is provided ()
|}]
|
a805d4a91d706c16af5cfd7431685dbf0ce2bde3994bd24dda16afecef3efd9e | monadfix/ormolu-live | PrimOp.hs |
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998
\section[PrimOp]{Primitive operations ( machine - level ) }
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[PrimOp]{Primitive operations (machine-level)}
-}
# LANGUAGE CPP #
module PrimOp (
PrimOp(..), PrimOpVecCat(..), allThePrimOps,
primOpType, primOpSig,
primOpTag, maxPrimOpTag, primOpOcc,
primOpWrapperId,
tagToEnumKey,
primOpOutOfLine, primOpCodeSize,
primOpOkForSpeculation, primOpOkForSideEffects,
primOpIsCheap, primOpFixity,
getPrimOpResultInfo, isComparisonPrimOp, PrimOpResultInfo(..),
PrimCall(..)
) where
#include "HsVersions2.h"
import GhcPrelude
import TysPrim
import TysWiredIn
import CmmType
import Demand
import Id ( Id, mkVanillaGlobalWithInfo )
import IdInfo ( vanillaIdInfo, setCafInfo, CafInfo(NoCafRefs) )
import Name
import PrelNames ( gHC_PRIMOPWRAPPERS )
import TyCon ( TyCon, isPrimTyCon, PrimRep(..) )
import Type
import RepType ( typePrimRep1, tyConPrimRep1 )
import BasicTypes ( Arity, Fixity(..), FixityDirection(..), Boxity(..),
SourceText(..) )
import SrcLoc ( wiredInSrcSpan )
import ForeignCall ( CLabelString )
import Unique ( Unique, mkPrimOpIdUnique, mkPrimOpWrapperUnique )
import Outputable
import FastString
import Module ( UnitId )
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
\subsection[PrimOp - datatype]{Datatype for @PrimOp@ ( an enumeration ) }
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
These are in \tr{state - interface.verb } order .
************************************************************************
* *
\subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
* *
************************************************************************
These are in \tr{state-interface.verb} order.
-}
-- supplies:
-- data PrimOp = ...
#include "primop-data-decl.hs-incl"
-- supplies
-- primOpTag :: PrimOp -> Int
#include "primop-tag.hs-incl"
primOpTag _ = error "primOpTag: unknown primop"
instance Eq PrimOp where
op1 == op2 = primOpTag op1 == primOpTag op2
instance Ord PrimOp where
op1 < op2 = primOpTag op1 < primOpTag op2
op1 <= op2 = primOpTag op1 <= primOpTag op2
op1 >= op2 = primOpTag op1 >= primOpTag op2
op1 > op2 = primOpTag op1 > primOpTag op2
op1 `compare` op2 | op1 < op2 = LT
| op1 == op2 = EQ
| otherwise = GT
instance Outputable PrimOp where
ppr op = pprPrimOp op
data PrimOpVecCat = IntVec
| WordVec
| FloatVec
-- An @Enum@-derived list would be better; meanwhile... (ToDo)
allThePrimOps :: [PrimOp]
allThePrimOps =
#include "primop-list.hs-incl"
tagToEnumKey :: Unique
tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
\subsection[PrimOp - info]{The essential info about each @PrimOp@ }
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
The @String@ in the @PrimOpInfos@ is the ` ` base name '' by which the user may
refer to the primitive operation . The conventional \tr{#}-for-
unboxed ops is added on later .
The reason for the funny characters in the names is so we do not
interfere with the programmer 's name spaces .
We use @PrimKinds@ for the ` ` type '' information , because they 're
( slightly ) more convenient to use than @TyCons@.
************************************************************************
* *
\subsection[PrimOp-info]{The essential info about each @PrimOp@}
* *
************************************************************************
The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
refer to the primitive operation. The conventional \tr{#}-for-
unboxed ops is added on later.
The reason for the funny characters in the names is so we do not
interfere with the programmer's Haskell name spaces.
We use @PrimKinds@ for the ``type'' information, because they're
(slightly) more convenient to use than @TyCons@.
-}
data PrimOpInfo
= Dyadic OccName -- string :: T -> T -> T
Type
| Monadic OccName -- string :: T -> T
Type
| Compare OccName -- string :: T -> T -> Int#
Type
| GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
[TyVar]
[Type]
Type
mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo
mkDyadic str ty = Dyadic (mkVarOccFS str) ty
mkMonadic str ty = Monadic (mkVarOccFS str) ty
mkCompare str ty = Compare (mkVarOccFS str) ty
mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo
mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty
{-
************************************************************************
* *
\subsubsection{Strictness}
* *
************************************************************************
Not all primops are strict!
-}
primOpStrictness :: PrimOp -> Arity -> StrictSig
-- See Demand.StrictnessInfo for discussion of what the results
The arity should be the arity of the primop ; that 's why
-- this function isn't exported.
#include "primop-strictness.hs-incl"
{-
************************************************************************
* *
\subsubsection{Fixity}
* *
************************************************************************
-}
primOpFixity :: PrimOp -> Maybe Fixity
#include "primop-fixity.hs-incl"
{-
************************************************************************
* *
\subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
* *
************************************************************************
@primOpInfo@ gives all essential information (from which everything
else, notably a type, can be constructed) for each @PrimOp@.
-}
primOpInfo :: PrimOp -> PrimOpInfo
#include "primop-primop-info.hs-incl"
primOpInfo _ = error "primOpInfo: unknown primop"
Here are a load of comments from the old primOp info :
A @Word#@ is an unsigned
@decodeFloat#@ is given w/ Integer - stuff ( it 's similar ) .
@decodeDouble#@ is given w/ Integer - stuff ( it 's similar ) .
Decoding of floating - point numbers is sorta Integer - related . Encoding
is done with plain ccalls now ( see PrelNumExtra.hs ) .
A @Weak@ Pointer is created by the @mkWeak#@ primitive :
mkWeak # : : k - > v - > f - > State # RealWorld
- > ( # State # RealWorld , Weak # v # )
In practice , you 'll use the higher - level
data Weak v = Weak # v
mkWeak : : k - > v - > IO ( ) - > IO ( Weak v )
The following operation dereferences a weak pointer . The weak pointer
may have been finalized , so the operation returns a result code which
must be inspected before looking at the dereferenced value .
deRefWeak # : : Weak # v - > State # RealWorld - >
( # State # RealWorld , v , Int # # )
Only look at v if the Int # returned is /= 0 ! !
The higher - level op is
deRefWeak : : Weak v - > IO ( Maybe v )
Weak pointers can be finalized early by using the finalize # operation :
finalizeWeak # : : Weak # v - > State # RealWorld - >
( # State # RealWorld , Int # , IO ( ) # )
The Int # returned is either
0 if the weak pointer has already been finalized , or it has no
finalizer ( the third component is then invalid ) .
1 if the weak pointer is still alive , with the finalizer returned
as the third component .
A { \em stable name / pointer } is an index into a table of stable name
entries . Since the garbage collector is told about stable pointers ,
it is safe to pass a stable pointer to external systems such as C
routines .
}
makeStablePtr # : : a - > State # RealWorld - > ( # State # RealWorld , StablePtr # a # )
freeStablePtr : : StablePtr # a - > State # RealWorld - > State # RealWorld
deRefStablePtr # : : StablePtr # a - > State # RealWorld - > ( # State # RealWorld , a # )
eqStablePtr # : : StablePtr # a - > StablePtr # a - > Int #
\end{verbatim }
It may seem a bit surprising that @makeStablePtr#@ is a @IO@
operation since it does n't ( directly ) involve IO operations . The
reason is that if some optimisation pass decided to duplicate calls to
@makeStablePtr#@ and we only pass one of the stable pointers over , a
massive space leak can result . Putting it into the IO monad
prevents this . ( Another reason for putting them in a monad is to
ensure correct sequencing wrt the side - effecting @freeStablePtr@
operation . )
An important property of stable pointers is that if you call
makeStablePtr # twice on the same object you get the same stable
pointer back .
Note that we can implement @freeStablePtr#@ using @_ccall_@ ( and ,
besides , it 's not likely to be used from ) so it 's not a
primop .
Question : Why @RealWorld@ - wo n't any instance of @_ST@ do the job ? [ ADR ]
Stable Names
~~~~~~~~~~~~
A stable name is like a stable pointer , but with three important differences :
( a ) You ca n't deRef one to get back to the original object .
( b ) You can convert one to an Int .
( c ) You do n't need to ' freeStableName '
The existence of a stable name does n't guarantee to keep the object it
points to alive ( unlike a stable pointer ) , hence ( a ) .
Invariants :
( a ) makeStableName always returns the same value for a given
object ( same as stable pointers ) .
( b ) if two stable names are equal , it implies that the objects
from which they were created were the same .
( c ) stableNameToInt always returns the same Int for a given
stable name .
These primops are pretty weird .
tagToEnum # : : Int - > a ( result type must be an enumerated type )
The constraints are n't currently checked by the front end , but the
code generator will fall over if they are n't satisfied .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Which PrimOps are out - of - line
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Some PrimOps need to be called out - of - line because they either need to
perform a heap check or they block .
Here are a load of comments from the old primOp info:
A @Word#@ is an unsigned @Int#@.
@decodeFloat#@ is given w/ Integer-stuff (it's similar).
@decodeDouble#@ is given w/ Integer-stuff (it's similar).
Decoding of floating-point numbers is sorta Integer-related. Encoding
is done with plain ccalls now (see PrelNumExtra.hs).
A @Weak@ Pointer is created by the @mkWeak#@ primitive:
mkWeak# :: k -> v -> f -> State# RealWorld
-> (# State# RealWorld, Weak# v #)
In practice, you'll use the higher-level
data Weak v = Weak# v
mkWeak :: k -> v -> IO () -> IO (Weak v)
The following operation dereferences a weak pointer. The weak pointer
may have been finalized, so the operation returns a result code which
must be inspected before looking at the dereferenced value.
deRefWeak# :: Weak# v -> State# RealWorld ->
(# State# RealWorld, v, Int# #)
Only look at v if the Int# returned is /= 0 !!
The higher-level op is
deRefWeak :: Weak v -> IO (Maybe v)
Weak pointers can be finalized early by using the finalize# operation:
finalizeWeak# :: Weak# v -> State# RealWorld ->
(# State# RealWorld, Int#, IO () #)
The Int# returned is either
0 if the weak pointer has already been finalized, or it has no
finalizer (the third component is then invalid).
1 if the weak pointer is still alive, with the finalizer returned
as the third component.
A {\em stable name/pointer} is an index into a table of stable name
entries. Since the garbage collector is told about stable pointers,
it is safe to pass a stable pointer to external systems such as C
routines.
\begin{verbatim}
makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
\end{verbatim}
It may seem a bit surprising that @makeStablePtr#@ is a @IO@
operation since it doesn't (directly) involve IO operations. The
reason is that if some optimisation pass decided to duplicate calls to
@makeStablePtr#@ and we only pass one of the stable pointers over, a
massive space leak can result. Putting it into the IO monad
prevents this. (Another reason for putting them in a monad is to
ensure correct sequencing wrt the side-effecting @freeStablePtr@
operation.)
An important property of stable pointers is that if you call
makeStablePtr# twice on the same object you get the same stable
pointer back.
Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
besides, it's not likely to be used from Haskell) so it's not a
primop.
Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
Stable Names
~~~~~~~~~~~~
A stable name is like a stable pointer, but with three important differences:
(a) You can't deRef one to get back to the original object.
(b) You can convert one to an Int.
(c) You don't need to 'freeStableName'
The existence of a stable name doesn't guarantee to keep the object it
points to alive (unlike a stable pointer), hence (a).
Invariants:
(a) makeStableName always returns the same value for a given
object (same as stable pointers).
(b) if two stable names are equal, it implies that the objects
from which they were created were the same.
(c) stableNameToInt always returns the same Int for a given
stable name.
These primops are pretty weird.
tagToEnum# :: Int -> a (result type must be an enumerated type)
The constraints aren't currently checked by the front end, but the
code generator will fall over if they aren't satisfied.
************************************************************************
* *
Which PrimOps are out-of-line
* *
************************************************************************
Some PrimOps need to be called out-of-line because they either need to
perform a heap check or they block.
-}
primOpOutOfLine :: PrimOp -> Bool
#include "primop-out-of-line.hs-incl"
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Failure and side effects
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Note [ Checking versus non - checking primops ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In GHC primops break down into two classes :
a. Checking primops behave , for instance , like division . In this
case the primop may throw an exception ( e.g. division - by - zero )
and is consequently is marked with the flag described below .
The ability to fail comes at the expense of precluding some optimizations .
b. Non - checking primops behavior , for instance , like addition . While
addition can overflow it does not produce an exception . So is
set to False , and we get more optimisation opportunities . But we must
never throw an exception , so we can not rewrite to a call to error .
It is important that a non - checking primop never be transformed in a way that
would cause it to bottom . Doing so would violate Core 's let / app invariant
( see Note [ CoreSyn let / app invariant ] in CoreSyn ) which is critical to
the simplifier 's ability to float without fear of changing program meaning .
Note [ PrimOp can_fail and has_side_effects ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Both can_fail and has_side_effects mean that the primop has
some effect that is not captured entirely by its result value .
---------- has_side_effects ---------------------
A primop " has_side_effects " if it has some * write * effect , visible
elsewhere
- writing to the world ( I / O )
- writing to a mutable data structure ( writeIORef )
- throwing a synchronous exception
Often such primops have a type like
State - > input - > ( State , output )
so the state token guarantees ordering . In general we rely * only * on
data dependencies of the state token to enforce write - effect ordering
* NB1 : if you inline unsafePerformIO , you may end up with
side - effecting ops whose ' state ' output is discarded .
And programmers may do that by hand ; see # 9390 .
That is why we ( conservatively ) do not discard write - effecting
primops even if both their state and result is discarded .
* NB2 : We consider primops , such as raiseIO # , that can raise a
( ) synchronous exception to " have_side_effects " but not
" can_fail " . We must be careful about not discarding such things ;
see the paper " A semantics for imprecise exceptions " .
* NB3 : * Read * effects ( like reading an IORef ) do n't count here ,
because it does n't matter if we do n't do them , or do them more than
once . * Sequencing * is maintained by the data dependency of the state
token .
---------- can_fail ----------------------------
A primop " can_fail " if it can fail with an * unchecked * exception on
some elements of its input domain . Main examples :
division ( fails on zero demoninator )
array indexing ( fails if the index is out of bounds )
An " unchecked exception " is one that is an outright error , ( not
turned into a exception , ) such as seg - fault or
divide - by - zero error . Such are ALWAYS surrounded
with a test that checks for the bad cases , but we need to be
very careful about code motion that might move it out of
the scope of the test .
Note [ Transformations affected by can_fail and has_side_effects ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The can_fail and has_side_effects properties have the following effect
on program transformations . Summary table is followed by details .
can_fail has_side_effects
Discard YES NO
Float in YES YES
Float out NO NO
Duplicate YES NO
* Discarding . case ( a ` op ` b ) of _ - > rhs = = = > rhs
You should not discard a has_side_effects primop ; e.g.
case ( writeIntArray # a i v s of ( # _ , _ # ) - > True
Arguably you should be able to discard this , since the
returned stat token is not used , but that relies on NEVER
inlining unsafePerformIO , and programmers sometimes write
this kind of stuff by hand ( # 9390 ) . So we ( conservatively )
never discard a has_side_effects primop .
However , it 's fine to discard a . For example
case ( indexIntArray # a i ) of _ - > True
We can discard indexIntArray # ; it has , but not
has_side_effects ; see # 5658 which was all about this .
Notice that indexIntArray # is ( in a more general handling of
effects ) read effect , but we do n't care about that here , and
treat read effects as * not * has_side_effects .
Similarly ( a ` / # ` b ) can be discarded . It can seg - fault or
cause a hardware exception , but not a synchronous
exception .
exceptions , e.g. from raiseIO # , are treated
as has_side_effects and hence are not discarded .
* Float in . You can float a can_fail or has_side_effects primop
* inwards * , but not inside a lambda ( see Duplication below ) .
* Float out . You must not float a can_fail primop * outwards * lest
you escape the dynamic scope of the test . Example :
case d > # 0 # of
True - > case x / # d of r - > r + # 1
False - > 0
Here we must not float the case outwards to give
case x/ # d of r - >
case d > # 0 # of
True - > r + # 1
False - > 0
Nor can you float out a has_side_effects primop . For example :
if blah then case # v True s0 of ( # s1 # ) - > s1
else s0
Notice that s0 is mentioned in both branches of the ' if ' , but
only one of these two will actually be consumed . But if we
float out to
case writeMutVar # v True s0 of ( # s1 # ) - >
if blah then s1 else s0
the will be performed in both branches , which is
utterly wrong .
* Duplication . You can not duplicate a has_side_effect primop . You
might wonder how this can occur given the state token threading , but
just look at Control . Monad . ST.Lazy . Imp.strictToLazy ! We get
something like this
p = case readMutVar # s v of
( # s ' , r # ) - > ( S # s ' , r )
s ' = case p of ( s ' , r ) - > s '
r = case p of ( s ' , r ) - > r
( All these bindings are boxed . ) If we inline p at its two call
sites , we get a catastrophe : because the read is performed once when
s ' is demanded , and once when ' r ' is demanded , which may be much
later . Utterly wrong . # 3207 is real example of this happening .
However , it 's fine to duplicate a . That is really
the only difference between can_fail and has_side_effects .
Note [ Implementation : how / has_side_effects affect transformations ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How do we ensure that that floating / duplication / discarding are done right
in the simplifier ?
Two main predicates on primpops test these flags :
primOpOkForSideEffects < = > not has_side_effects
primOpOkForSpeculation < = > not ( has_side_effects || can_fail )
* The " no - float - out " thing is achieved by ensuring that we never
let - bind a can_fail or has_side_effects primop . The RHS of a
let - binding ( which can float in and out freely ) satisfies
exprOkForSpeculation ; this is the let / app invariant . And
exprOkForSpeculation is false of can_fail and has_side_effects .
* So and will appear only as the
scrutinees of cases , and that 's why the pass is capable
of floating case bindings inwards .
* The no - duplicate thing is done via primOpIsCheap , by making
has_side_effects things ( very very very ) not - cheap !
************************************************************************
* *
Failure and side effects
* *
************************************************************************
Note [Checking versus non-checking primops]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In GHC primops break down into two classes:
a. Checking primops behave, for instance, like division. In this
case the primop may throw an exception (e.g. division-by-zero)
and is consequently is marked with the can_fail flag described below.
The ability to fail comes at the expense of precluding some optimizations.
b. Non-checking primops behavior, for instance, like addition. While
addition can overflow it does not produce an exception. So can_fail is
set to False, and we get more optimisation opportunities. But we must
never throw an exception, so we cannot rewrite to a call to error.
It is important that a non-checking primop never be transformed in a way that
would cause it to bottom. Doing so would violate Core's let/app invariant
(see Note [CoreSyn let/app invariant] in CoreSyn) which is critical to
the simplifier's ability to float without fear of changing program meaning.
Note [PrimOp can_fail and has_side_effects]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Both can_fail and has_side_effects mean that the primop has
some effect that is not captured entirely by its result value.
---------- has_side_effects ---------------------
A primop "has_side_effects" if it has some *write* effect, visible
elsewhere
- writing to the world (I/O)
- writing to a mutable data structure (writeIORef)
- throwing a synchronous Haskell exception
Often such primops have a type like
State -> input -> (State, output)
so the state token guarantees ordering. In general we rely *only* on
data dependencies of the state token to enforce write-effect ordering
* NB1: if you inline unsafePerformIO, you may end up with
side-effecting ops whose 'state' output is discarded.
And programmers may do that by hand; see #9390.
That is why we (conservatively) do not discard write-effecting
primops even if both their state and result is discarded.
* NB2: We consider primops, such as raiseIO#, that can raise a
(Haskell) synchronous exception to "have_side_effects" but not
"can_fail". We must be careful about not discarding such things;
see the paper "A semantics for imprecise exceptions".
* NB3: *Read* effects (like reading an IORef) don't count here,
because it doesn't matter if we don't do them, or do them more than
once. *Sequencing* is maintained by the data dependency of the state
token.
---------- can_fail ----------------------------
A primop "can_fail" if it can fail with an *unchecked* exception on
some elements of its input domain. Main examples:
division (fails on zero demoninator)
array indexing (fails if the index is out of bounds)
An "unchecked exception" is one that is an outright error, (not
turned into a Haskell exception,) such as seg-fault or
divide-by-zero error. Such can_fail primops are ALWAYS surrounded
with a test that checks for the bad cases, but we need to be
very careful about code motion that might move it out of
the scope of the test.
Note [Transformations affected by can_fail and has_side_effects]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The can_fail and has_side_effects properties have the following effect
on program transformations. Summary table is followed by details.
can_fail has_side_effects
Discard YES NO
Float in YES YES
Float out NO NO
Duplicate YES NO
* Discarding. case (a `op` b) of _ -> rhs ===> rhs
You should not discard a has_side_effects primop; e.g.
case (writeIntArray# a i v s of (# _, _ #) -> True
Arguably you should be able to discard this, since the
returned stat token is not used, but that relies on NEVER
inlining unsafePerformIO, and programmers sometimes write
this kind of stuff by hand (#9390). So we (conservatively)
never discard a has_side_effects primop.
However, it's fine to discard a can_fail primop. For example
case (indexIntArray# a i) of _ -> True
We can discard indexIntArray#; it has can_fail, but not
has_side_effects; see #5658 which was all about this.
Notice that indexIntArray# is (in a more general handling of
effects) read effect, but we don't care about that here, and
treat read effects as *not* has_side_effects.
Similarly (a `/#` b) can be discarded. It can seg-fault or
cause a hardware exception, but not a synchronous Haskell
exception.
Synchronous Haskell exceptions, e.g. from raiseIO#, are treated
as has_side_effects and hence are not discarded.
* Float in. You can float a can_fail or has_side_effects primop
*inwards*, but not inside a lambda (see Duplication below).
* Float out. You must not float a can_fail primop *outwards* lest
you escape the dynamic scope of the test. Example:
case d ># 0# of
True -> case x /# d of r -> r +# 1
False -> 0
Here we must not float the case outwards to give
case x/# d of r ->
case d ># 0# of
True -> r +# 1
False -> 0
Nor can you float out a has_side_effects primop. For example:
if blah then case writeMutVar# v True s0 of (# s1 #) -> s1
else s0
Notice that s0 is mentioned in both branches of the 'if', but
only one of these two will actually be consumed. But if we
float out to
case writeMutVar# v True s0 of (# s1 #) ->
if blah then s1 else s0
the writeMutVar will be performed in both branches, which is
utterly wrong.
* Duplication. You cannot duplicate a has_side_effect primop. You
might wonder how this can occur given the state token threading, but
just look at Control.Monad.ST.Lazy.Imp.strictToLazy! We get
something like this
p = case readMutVar# s v of
(# s', r #) -> (S# s', r)
s' = case p of (s', r) -> s'
r = case p of (s', r) -> r
(All these bindings are boxed.) If we inline p at its two call
sites, we get a catastrophe: because the read is performed once when
s' is demanded, and once when 'r' is demanded, which may be much
later. Utterly wrong. #3207 is real example of this happening.
However, it's fine to duplicate a can_fail primop. That is really
the only difference between can_fail and has_side_effects.
Note [Implementation: how can_fail/has_side_effects affect transformations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How do we ensure that that floating/duplication/discarding are done right
in the simplifier?
Two main predicates on primpops test these flags:
primOpOkForSideEffects <=> not has_side_effects
primOpOkForSpeculation <=> not (has_side_effects || can_fail)
* The "no-float-out" thing is achieved by ensuring that we never
let-bind a can_fail or has_side_effects primop. The RHS of a
let-binding (which can float in and out freely) satisfies
exprOkForSpeculation; this is the let/app invariant. And
exprOkForSpeculation is false of can_fail and has_side_effects.
* So can_fail and has_side_effects primops will appear only as the
scrutinees of cases, and that's why the FloatIn pass is capable
of floating case bindings inwards.
* The no-duplicate thing is done via primOpIsCheap, by making
has_side_effects things (very very very) not-cheap!
-}
primOpHasSideEffects :: PrimOp -> Bool
#include "primop-has-side-effects.hs-incl"
primOpCanFail :: PrimOp -> Bool
#include "primop-can-fail.hs-incl"
primOpOkForSpeculation :: PrimOp -> Bool
-- See Note [PrimOp can_fail and has_side_effects]
See comments with CoreUtils.exprOkForSpeculation
-- primOpOkForSpeculation => primOpOkForSideEffects
primOpOkForSpeculation op
= primOpOkForSideEffects op
&& not (primOpOutOfLine op || primOpCanFail op)
-- I think the "out of line" test is because out of line things can
-- be expensive (eg sine, cosine), and so we may not want to speculate them
primOpOkForSideEffects :: PrimOp -> Bool
primOpOkForSideEffects op
= not (primOpHasSideEffects op)
Note [ primOpIsCheap ]
~~~~~~~~~~~~~~~~~~~~
@primOpIsCheap@ , as used in \tr{SimplUtils.hs } . For now ( HACK
WARNING ) , we just borrow some other predicates for a
what - should - be - good - enough test . " Cheap " means willing to call it more
than once , and/or push it inside a lambda . The latter could change the
behaviour of ' seq ' for that can fail , so we do n't treat them as cheap .
Note [primOpIsCheap]
~~~~~~~~~~~~~~~~~~~~
@primOpIsCheap@, as used in \tr{SimplUtils.hs}. For now (HACK
WARNING), we just borrow some other predicates for a
what-should-be-good-enough test. "Cheap" means willing to call it more
than once, and/or push it inside a lambda. The latter could change the
behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
-}
primOpIsCheap :: PrimOp -> Bool
-- See Note [PrimOp can_fail and has_side_effects]
primOpIsCheap op = primOpOkForSpeculation op
In March 2001 , we changed this to
-- primOpIsCheap op = False
-- thereby making *no* primops seem cheap. But this killed eta
-- expansion on case (x ==# y) of True -> \s -> ...
-- which is bad. In particular a loop like
-- doLoop n = loop 0
-- where
-- loop i | i == n = return ()
-- | otherwise = bar i >> loop (i+1)
-- allocated a closure every time round because it doesn't eta expand.
--
-- The problem that originally gave rise to the change was
-- let x = a +# b *# c in x +# x
-- were we don't want to inline x. But primopIsCheap doesn't control
-- that (it's exprIsDupable that does) so the problem doesn't occur
-- even if primOpIsCheap sometimes says 'True'.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
PrimOp code size
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
primOpCodeSize
~~~~~~~~~~~~~~
Gives an indication of the code size of a primop , for the purposes of
calculating unfolding sizes ; see CoreUnfold.sizeExpr .
************************************************************************
* *
PrimOp code size
* *
************************************************************************
primOpCodeSize
~~~~~~~~~~~~~~
Gives an indication of the code size of a primop, for the purposes of
calculating unfolding sizes; see CoreUnfold.sizeExpr.
-}
primOpCodeSize :: PrimOp -> Int
#include "primop-code-size.hs-incl"
primOpCodeSizeDefault :: Int
primOpCodeSizeDefault = 1
-- CoreUnfold.primOpSize already takes into account primOpOutOfLine
-- and adds some further costs for the args in that case.
primOpCodeSizeForeignCall :: Int
primOpCodeSizeForeignCall = 4
{-
************************************************************************
* *
PrimOp types
* *
************************************************************************
-}
primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
primOpType op
= case primOpInfo op of
Dyadic _occ ty -> dyadic_fun_ty ty
Monadic _occ ty -> monadic_fun_ty ty
Compare _occ ty -> compare_fun_ty ty
GenPrimOp _occ tyvars arg_tys res_ty ->
mkSpecForAllTys tyvars (mkVisFunTys arg_tys res_ty)
primOpOcc :: PrimOp -> OccName
primOpOcc op = case primOpInfo op of
Dyadic occ _ -> occ
Monadic occ _ -> occ
Compare occ _ -> occ
GenPrimOp occ _ _ _ -> occ
Note [ Primop wrappers ]
~~~~~~~~~~~~~~~~~~~~~~~~~
Previously hasNoBinding would claim that PrimOpIds did n't have a curried
function definition . This caused quite some trouble as we would be forced to
eta expand unsaturated primop applications very late in the Core pipeline . Not
only would this produce unnecessary thunks , but it would also result in nasty
inconsistencies in CAFfy - ness determinations ( see # 16846 and
Note [ CAFfyness inconsistencies due to late eta expansion ] in ) .
However , it was quite unnecessary for hasNoBinding to claim this ; primops in
fact * do * have curried definitions which are found in GHC.PrimopWrappers , which
is auto - generated by utils / genprimops from prelude / primops.txt.pp . These wrappers
are standard functions mirroring the types of the primops they wrap .
For instance , in the case of plusInt # we would have :
module GHC.PrimopWrappers where
import GHC.Prim as P
plusInt # a b = P.plusInt # a b
We now take advantage of these curried definitions by letting hasNoBinding
claim that PrimOpIds have a curried definition and then rewrite any unsaturated
PrimOpId applications that we find during CoreToStg as applications of the
associated wrapper ( e.g. ` GHC.Prim.plusInt # 3 # ` will get rewritten to
` GHC.PrimopWrappers.plusInt # 3 # ` ) . ` The I d of the wrapper for a primop can be
found using ' PrimOp.primOpWrapperId ' .
: GHC.PrimopWrappers is needed * regardless * , because it 's
used by GHCi , which does not implement primops direct at all .
~~~~~~~~~~~~~~~~~~~~~~~~~
Previously hasNoBinding would claim that PrimOpIds didn't have a curried
function definition. This caused quite some trouble as we would be forced to
eta expand unsaturated primop applications very late in the Core pipeline. Not
only would this produce unnecessary thunks, but it would also result in nasty
inconsistencies in CAFfy-ness determinations (see #16846 and
Note [CAFfyness inconsistencies due to late eta expansion] in TidyPgm).
However, it was quite unnecessary for hasNoBinding to claim this; primops in
fact *do* have curried definitions which are found in GHC.PrimopWrappers, which
is auto-generated by utils/genprimops from prelude/primops.txt.pp. These wrappers
are standard Haskell functions mirroring the types of the primops they wrap.
For instance, in the case of plusInt# we would have:
module GHC.PrimopWrappers where
import GHC.Prim as P
plusInt# a b = P.plusInt# a b
We now take advantage of these curried definitions by letting hasNoBinding
claim that PrimOpIds have a curried definition and then rewrite any unsaturated
PrimOpId applications that we find during CoreToStg as applications of the
associated wrapper (e.g. `GHC.Prim.plusInt# 3#` will get rewritten to
`GHC.PrimopWrappers.plusInt# 3#`).` The Id of the wrapper for a primop can be
found using 'PrimOp.primOpWrapperId'.
Nota Bene: GHC.PrimopWrappers is needed *regardless*, because it's
used by GHCi, which does not implement primops direct at all.
-}
-- | Returns the 'Id' of the wrapper associated with the given 'PrimOp'.
See Note [ Primop wrappers ] .
primOpWrapperId :: PrimOp -> Id
primOpWrapperId op = mkVanillaGlobalWithInfo name ty info
where
info = setCafInfo vanillaIdInfo NoCafRefs
name = mkExternalName uniq gHC_PRIMOPWRAPPERS (primOpOcc op) wiredInSrcSpan
uniq = mkPrimOpWrapperUnique (primOpTag op)
ty = primOpType op
isComparisonPrimOp :: PrimOp -> Bool
isComparisonPrimOp op = case primOpInfo op of
Compare {} -> True
_ -> False
primOpSig is like primOpType but gives the result split apart :
-- (type variables, argument types, result type)
-- It also gives arity, strictness info
primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
primOpSig op
= (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
where
arity = length arg_tys
(tyvars, arg_tys, res_ty)
= case (primOpInfo op) of
Monadic _occ ty -> ([], [ty], ty )
Dyadic _occ ty -> ([], [ty,ty], ty )
Compare _occ ty -> ([], [ty,ty], intPrimTy)
GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty )
data PrimOpResultInfo
= ReturnsPrim PrimRep
| ReturnsAlg TyCon
Some PrimOps need not return a manifest primitive or algebraic value
( i.e. they might return a polymorphic value ) . These PrimOps * must *
-- be out of line, or the code generator won't work.
getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
getPrimOpResultInfo op
= case (primOpInfo op) of
Dyadic _ ty -> ReturnsPrim (typePrimRep1 ty)
Monadic _ ty -> ReturnsPrim (typePrimRep1 ty)
Compare _ _ -> ReturnsPrim (tyConPrimRep1 intPrimTyCon)
GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep1 tc)
| otherwise -> ReturnsAlg tc
where
tc = tyConAppTyCon ty
-- All primops return a tycon-app result
-- The tycon can be an unboxed tuple or sum, though,
which gives rise to a ReturnAlg
{-
We do not currently make use of whether primops are commutable.
We used to try to move constants to the right hand side for strength
reduction.
-}
{-
commutableOp :: PrimOp -> Bool
#include "primop-commutable.hs-incl"
-}
-- Utils:
dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
dyadic_fun_ty ty = mkVisFunTys [ty, ty] ty
monadic_fun_ty ty = mkVisFunTy ty ty
compare_fun_ty ty = mkVisFunTys [ty, ty] intPrimTy
-- Output stuff:
pprPrimOp :: PrimOp -> SDoc
pprPrimOp other_op = pprOccName (primOpOcc other_op)
{-
************************************************************************
* *
\subsubsection[PrimCall]{User-imported primitive calls}
* *
************************************************************************
-}
data PrimCall = PrimCall CLabelString UnitId
instance Outputable PrimCall where
ppr (PrimCall lbl pkgId)
= text "__primcall" <+> ppr pkgId <+> ppr lbl
| null | https://raw.githubusercontent.com/monadfix/ormolu-live/d8ae72ef168b98a8d179d642f70352c88b3ac226/ghc-lib-parser-8.10.1.20200412/compiler/prelude/PrimOp.hs | haskell | supplies:
data PrimOp = ...
supplies
primOpTag :: PrimOp -> Int
An @Enum@-derived list would be better; meanwhile... (ToDo)
string :: T -> T -> T
string :: T -> T
string :: T -> T -> Int#
string :: \/a1..an . T1 -> .. -> Tk -> T
************************************************************************
* *
\subsubsection{Strictness}
* *
************************************************************************
Not all primops are strict!
See Demand.StrictnessInfo for discussion of what the results
this function isn't exported.
************************************************************************
* *
\subsubsection{Fixity}
* *
************************************************************************
************************************************************************
* *
\subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
* *
************************************************************************
@primOpInfo@ gives all essential information (from which everything
else, notably a type, can be constructed) for each @PrimOp@.
-------- has_side_effects ---------------------
-------- can_fail ----------------------------
-------- has_side_effects ---------------------
-------- can_fail ----------------------------
See Note [PrimOp can_fail and has_side_effects]
primOpOkForSpeculation => primOpOkForSideEffects
I think the "out of line" test is because out of line things can
be expensive (eg sine, cosine), and so we may not want to speculate them
See Note [PrimOp can_fail and has_side_effects]
primOpIsCheap op = False
thereby making *no* primops seem cheap. But this killed eta
expansion on case (x ==# y) of True -> \s -> ...
which is bad. In particular a loop like
doLoop n = loop 0
where
loop i | i == n = return ()
| otherwise = bar i >> loop (i+1)
allocated a closure every time round because it doesn't eta expand.
The problem that originally gave rise to the change was
let x = a +# b *# c in x +# x
were we don't want to inline x. But primopIsCheap doesn't control
that (it's exprIsDupable that does) so the problem doesn't occur
even if primOpIsCheap sometimes says 'True'.
CoreUnfold.primOpSize already takes into account primOpOutOfLine
and adds some further costs for the args in that case.
************************************************************************
* *
PrimOp types
* *
************************************************************************
you may want to use primOpSig instead
| Returns the 'Id' of the wrapper associated with the given 'PrimOp'.
(type variables, argument types, result type)
It also gives arity, strictness info
be out of line, or the code generator won't work.
All primops return a tycon-app result
The tycon can be an unboxed tuple or sum, though,
We do not currently make use of whether primops are commutable.
We used to try to move constants to the right hand side for strength
reduction.
commutableOp :: PrimOp -> Bool
#include "primop-commutable.hs-incl"
Utils:
Output stuff:
************************************************************************
* *
\subsubsection[PrimCall]{User-imported primitive calls}
* *
************************************************************************
|
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998
\section[PrimOp]{Primitive operations ( machine - level ) }
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[PrimOp]{Primitive operations (machine-level)}
-}
# LANGUAGE CPP #
module PrimOp (
PrimOp(..), PrimOpVecCat(..), allThePrimOps,
primOpType, primOpSig,
primOpTag, maxPrimOpTag, primOpOcc,
primOpWrapperId,
tagToEnumKey,
primOpOutOfLine, primOpCodeSize,
primOpOkForSpeculation, primOpOkForSideEffects,
primOpIsCheap, primOpFixity,
getPrimOpResultInfo, isComparisonPrimOp, PrimOpResultInfo(..),
PrimCall(..)
) where
#include "HsVersions2.h"
import GhcPrelude
import TysPrim
import TysWiredIn
import CmmType
import Demand
import Id ( Id, mkVanillaGlobalWithInfo )
import IdInfo ( vanillaIdInfo, setCafInfo, CafInfo(NoCafRefs) )
import Name
import PrelNames ( gHC_PRIMOPWRAPPERS )
import TyCon ( TyCon, isPrimTyCon, PrimRep(..) )
import Type
import RepType ( typePrimRep1, tyConPrimRep1 )
import BasicTypes ( Arity, Fixity(..), FixityDirection(..), Boxity(..),
SourceText(..) )
import SrcLoc ( wiredInSrcSpan )
import ForeignCall ( CLabelString )
import Unique ( Unique, mkPrimOpIdUnique, mkPrimOpWrapperUnique )
import Outputable
import FastString
import Module ( UnitId )
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
\subsection[PrimOp - datatype]{Datatype for @PrimOp@ ( an enumeration ) }
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
These are in \tr{state - interface.verb } order .
************************************************************************
* *
\subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
* *
************************************************************************
These are in \tr{state-interface.verb} order.
-}
#include "primop-data-decl.hs-incl"
#include "primop-tag.hs-incl"
primOpTag _ = error "primOpTag: unknown primop"
instance Eq PrimOp where
op1 == op2 = primOpTag op1 == primOpTag op2
instance Ord PrimOp where
op1 < op2 = primOpTag op1 < primOpTag op2
op1 <= op2 = primOpTag op1 <= primOpTag op2
op1 >= op2 = primOpTag op1 >= primOpTag op2
op1 > op2 = primOpTag op1 > primOpTag op2
op1 `compare` op2 | op1 < op2 = LT
| op1 == op2 = EQ
| otherwise = GT
instance Outputable PrimOp where
ppr op = pprPrimOp op
data PrimOpVecCat = IntVec
| WordVec
| FloatVec
allThePrimOps :: [PrimOp]
allThePrimOps =
#include "primop-list.hs-incl"
tagToEnumKey :: Unique
tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
\subsection[PrimOp - info]{The essential info about each @PrimOp@ }
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
The @String@ in the @PrimOpInfos@ is the ` ` base name '' by which the user may
refer to the primitive operation . The conventional \tr{#}-for-
unboxed ops is added on later .
The reason for the funny characters in the names is so we do not
interfere with the programmer 's name spaces .
We use @PrimKinds@ for the ` ` type '' information , because they 're
( slightly ) more convenient to use than @TyCons@.
************************************************************************
* *
\subsection[PrimOp-info]{The essential info about each @PrimOp@}
* *
************************************************************************
The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
refer to the primitive operation. The conventional \tr{#}-for-
unboxed ops is added on later.
The reason for the funny characters in the names is so we do not
interfere with the programmer's Haskell name spaces.
We use @PrimKinds@ for the ``type'' information, because they're
(slightly) more convenient to use than @TyCons@.
-}
data PrimOpInfo
Type
Type
Type
[TyVar]
[Type]
Type
mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo
mkDyadic str ty = Dyadic (mkVarOccFS str) ty
mkMonadic str ty = Monadic (mkVarOccFS str) ty
mkCompare str ty = Compare (mkVarOccFS str) ty
mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo
mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty
primOpStrictness :: PrimOp -> Arity -> StrictSig
The arity should be the arity of the primop ; that 's why
#include "primop-strictness.hs-incl"
primOpFixity :: PrimOp -> Maybe Fixity
#include "primop-fixity.hs-incl"
primOpInfo :: PrimOp -> PrimOpInfo
#include "primop-primop-info.hs-incl"
primOpInfo _ = error "primOpInfo: unknown primop"
Here are a load of comments from the old primOp info :
A @Word#@ is an unsigned
@decodeFloat#@ is given w/ Integer - stuff ( it 's similar ) .
@decodeDouble#@ is given w/ Integer - stuff ( it 's similar ) .
Decoding of floating - point numbers is sorta Integer - related . Encoding
is done with plain ccalls now ( see PrelNumExtra.hs ) .
A @Weak@ Pointer is created by the @mkWeak#@ primitive :
mkWeak # : : k - > v - > f - > State # RealWorld
- > ( # State # RealWorld , Weak # v # )
In practice , you 'll use the higher - level
data Weak v = Weak # v
mkWeak : : k - > v - > IO ( ) - > IO ( Weak v )
The following operation dereferences a weak pointer . The weak pointer
may have been finalized , so the operation returns a result code which
must be inspected before looking at the dereferenced value .
deRefWeak # : : Weak # v - > State # RealWorld - >
( # State # RealWorld , v , Int # # )
Only look at v if the Int # returned is /= 0 ! !
The higher - level op is
deRefWeak : : Weak v - > IO ( Maybe v )
Weak pointers can be finalized early by using the finalize # operation :
finalizeWeak # : : Weak # v - > State # RealWorld - >
( # State # RealWorld , Int # , IO ( ) # )
The Int # returned is either
0 if the weak pointer has already been finalized , or it has no
finalizer ( the third component is then invalid ) .
1 if the weak pointer is still alive , with the finalizer returned
as the third component .
A { \em stable name / pointer } is an index into a table of stable name
entries . Since the garbage collector is told about stable pointers ,
it is safe to pass a stable pointer to external systems such as C
routines .
}
makeStablePtr # : : a - > State # RealWorld - > ( # State # RealWorld , StablePtr # a # )
freeStablePtr : : StablePtr # a - > State # RealWorld - > State # RealWorld
deRefStablePtr # : : StablePtr # a - > State # RealWorld - > ( # State # RealWorld , a # )
eqStablePtr # : : StablePtr # a - > StablePtr # a - > Int #
\end{verbatim }
It may seem a bit surprising that @makeStablePtr#@ is a @IO@
operation since it does n't ( directly ) involve IO operations . The
reason is that if some optimisation pass decided to duplicate calls to
@makeStablePtr#@ and we only pass one of the stable pointers over , a
massive space leak can result . Putting it into the IO monad
prevents this . ( Another reason for putting them in a monad is to
ensure correct sequencing wrt the side - effecting @freeStablePtr@
operation . )
An important property of stable pointers is that if you call
makeStablePtr # twice on the same object you get the same stable
pointer back .
Note that we can implement @freeStablePtr#@ using @_ccall_@ ( and ,
besides , it 's not likely to be used from ) so it 's not a
primop .
Question : Why @RealWorld@ - wo n't any instance of @_ST@ do the job ? [ ADR ]
Stable Names
~~~~~~~~~~~~
A stable name is like a stable pointer , but with three important differences :
( a ) You ca n't deRef one to get back to the original object .
( b ) You can convert one to an Int .
( c ) You do n't need to ' freeStableName '
The existence of a stable name does n't guarantee to keep the object it
points to alive ( unlike a stable pointer ) , hence ( a ) .
Invariants :
( a ) makeStableName always returns the same value for a given
object ( same as stable pointers ) .
( b ) if two stable names are equal , it implies that the objects
from which they were created were the same .
( c ) stableNameToInt always returns the same Int for a given
stable name .
These primops are pretty weird .
tagToEnum # : : Int - > a ( result type must be an enumerated type )
The constraints are n't currently checked by the front end , but the
code generator will fall over if they are n't satisfied .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Which PrimOps are out - of - line
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Some PrimOps need to be called out - of - line because they either need to
perform a heap check or they block .
Here are a load of comments from the old primOp info:
A @Word#@ is an unsigned @Int#@.
@decodeFloat#@ is given w/ Integer-stuff (it's similar).
@decodeDouble#@ is given w/ Integer-stuff (it's similar).
Decoding of floating-point numbers is sorta Integer-related. Encoding
is done with plain ccalls now (see PrelNumExtra.hs).
A @Weak@ Pointer is created by the @mkWeak#@ primitive:
mkWeak# :: k -> v -> f -> State# RealWorld
-> (# State# RealWorld, Weak# v #)
In practice, you'll use the higher-level
data Weak v = Weak# v
mkWeak :: k -> v -> IO () -> IO (Weak v)
The following operation dereferences a weak pointer. The weak pointer
may have been finalized, so the operation returns a result code which
must be inspected before looking at the dereferenced value.
deRefWeak# :: Weak# v -> State# RealWorld ->
(# State# RealWorld, v, Int# #)
Only look at v if the Int# returned is /= 0 !!
The higher-level op is
deRefWeak :: Weak v -> IO (Maybe v)
Weak pointers can be finalized early by using the finalize# operation:
finalizeWeak# :: Weak# v -> State# RealWorld ->
(# State# RealWorld, Int#, IO () #)
The Int# returned is either
0 if the weak pointer has already been finalized, or it has no
finalizer (the third component is then invalid).
1 if the weak pointer is still alive, with the finalizer returned
as the third component.
A {\em stable name/pointer} is an index into a table of stable name
entries. Since the garbage collector is told about stable pointers,
it is safe to pass a stable pointer to external systems such as C
routines.
\begin{verbatim}
makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
\end{verbatim}
It may seem a bit surprising that @makeStablePtr#@ is a @IO@
operation since it doesn't (directly) involve IO operations. The
reason is that if some optimisation pass decided to duplicate calls to
@makeStablePtr#@ and we only pass one of the stable pointers over, a
massive space leak can result. Putting it into the IO monad
prevents this. (Another reason for putting them in a monad is to
ensure correct sequencing wrt the side-effecting @freeStablePtr@
operation.)
An important property of stable pointers is that if you call
makeStablePtr# twice on the same object you get the same stable
pointer back.
Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
besides, it's not likely to be used from Haskell) so it's not a
primop.
Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
Stable Names
~~~~~~~~~~~~
A stable name is like a stable pointer, but with three important differences:
(a) You can't deRef one to get back to the original object.
(b) You can convert one to an Int.
(c) You don't need to 'freeStableName'
The existence of a stable name doesn't guarantee to keep the object it
points to alive (unlike a stable pointer), hence (a).
Invariants:
(a) makeStableName always returns the same value for a given
object (same as stable pointers).
(b) if two stable names are equal, it implies that the objects
from which they were created were the same.
(c) stableNameToInt always returns the same Int for a given
stable name.
These primops are pretty weird.
tagToEnum# :: Int -> a (result type must be an enumerated type)
The constraints aren't currently checked by the front end, but the
code generator will fall over if they aren't satisfied.
************************************************************************
* *
Which PrimOps are out-of-line
* *
************************************************************************
Some PrimOps need to be called out-of-line because they either need to
perform a heap check or they block.
-}
primOpOutOfLine :: PrimOp -> Bool
#include "primop-out-of-line.hs-incl"
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Failure and side effects
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Note [ Checking versus non - checking primops ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In GHC primops break down into two classes :
a. Checking primops behave , for instance , like division . In this
case the primop may throw an exception ( e.g. division - by - zero )
and is consequently is marked with the flag described below .
The ability to fail comes at the expense of precluding some optimizations .
b. Non - checking primops behavior , for instance , like addition . While
addition can overflow it does not produce an exception . So is
set to False , and we get more optimisation opportunities . But we must
never throw an exception , so we can not rewrite to a call to error .
It is important that a non - checking primop never be transformed in a way that
would cause it to bottom . Doing so would violate Core 's let / app invariant
( see Note [ CoreSyn let / app invariant ] in CoreSyn ) which is critical to
the simplifier 's ability to float without fear of changing program meaning .
Note [ PrimOp can_fail and has_side_effects ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Both can_fail and has_side_effects mean that the primop has
some effect that is not captured entirely by its result value .
A primop " has_side_effects " if it has some * write * effect , visible
elsewhere
- writing to the world ( I / O )
- writing to a mutable data structure ( writeIORef )
- throwing a synchronous exception
Often such primops have a type like
State - > input - > ( State , output )
so the state token guarantees ordering . In general we rely * only * on
data dependencies of the state token to enforce write - effect ordering
* NB1 : if you inline unsafePerformIO , you may end up with
side - effecting ops whose ' state ' output is discarded .
And programmers may do that by hand ; see # 9390 .
That is why we ( conservatively ) do not discard write - effecting
primops even if both their state and result is discarded .
* NB2 : We consider primops , such as raiseIO # , that can raise a
( ) synchronous exception to " have_side_effects " but not
" can_fail " . We must be careful about not discarding such things ;
see the paper " A semantics for imprecise exceptions " .
* NB3 : * Read * effects ( like reading an IORef ) do n't count here ,
because it does n't matter if we do n't do them , or do them more than
once . * Sequencing * is maintained by the data dependency of the state
token .
A primop " can_fail " if it can fail with an * unchecked * exception on
some elements of its input domain . Main examples :
division ( fails on zero demoninator )
array indexing ( fails if the index is out of bounds )
An " unchecked exception " is one that is an outright error , ( not
turned into a exception , ) such as seg - fault or
divide - by - zero error . Such are ALWAYS surrounded
with a test that checks for the bad cases , but we need to be
very careful about code motion that might move it out of
the scope of the test .
Note [ Transformations affected by can_fail and has_side_effects ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The can_fail and has_side_effects properties have the following effect
on program transformations . Summary table is followed by details .
can_fail has_side_effects
Discard YES NO
Float in YES YES
Float out NO NO
Duplicate YES NO
* Discarding . case ( a ` op ` b ) of _ - > rhs = = = > rhs
You should not discard a has_side_effects primop ; e.g.
case ( writeIntArray # a i v s of ( # _ , _ # ) - > True
Arguably you should be able to discard this , since the
returned stat token is not used , but that relies on NEVER
inlining unsafePerformIO , and programmers sometimes write
this kind of stuff by hand ( # 9390 ) . So we ( conservatively )
never discard a has_side_effects primop .
However , it 's fine to discard a . For example
case ( indexIntArray # a i ) of _ - > True
We can discard indexIntArray # ; it has , but not
has_side_effects ; see # 5658 which was all about this .
Notice that indexIntArray # is ( in a more general handling of
effects ) read effect , but we do n't care about that here , and
treat read effects as * not * has_side_effects .
Similarly ( a ` / # ` b ) can be discarded . It can seg - fault or
cause a hardware exception , but not a synchronous
exception .
exceptions , e.g. from raiseIO # , are treated
as has_side_effects and hence are not discarded .
* Float in . You can float a can_fail or has_side_effects primop
* inwards * , but not inside a lambda ( see Duplication below ) .
* Float out . You must not float a can_fail primop * outwards * lest
you escape the dynamic scope of the test . Example :
case d > # 0 # of
True - > case x / # d of r - > r + # 1
False - > 0
Here we must not float the case outwards to give
case x/ # d of r - >
case d > # 0 # of
True - > r + # 1
False - > 0
Nor can you float out a has_side_effects primop . For example :
if blah then case # v True s0 of ( # s1 # ) - > s1
else s0
Notice that s0 is mentioned in both branches of the ' if ' , but
only one of these two will actually be consumed . But if we
float out to
case writeMutVar # v True s0 of ( # s1 # ) - >
if blah then s1 else s0
the will be performed in both branches , which is
utterly wrong .
* Duplication . You can not duplicate a has_side_effect primop . You
might wonder how this can occur given the state token threading , but
just look at Control . Monad . ST.Lazy . Imp.strictToLazy ! We get
something like this
p = case readMutVar # s v of
( # s ' , r # ) - > ( S # s ' , r )
s ' = case p of ( s ' , r ) - > s '
r = case p of ( s ' , r ) - > r
( All these bindings are boxed . ) If we inline p at its two call
sites , we get a catastrophe : because the read is performed once when
s ' is demanded , and once when ' r ' is demanded , which may be much
later . Utterly wrong . # 3207 is real example of this happening .
However , it 's fine to duplicate a . That is really
the only difference between can_fail and has_side_effects .
Note [ Implementation : how / has_side_effects affect transformations ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How do we ensure that that floating / duplication / discarding are done right
in the simplifier ?
Two main predicates on primpops test these flags :
primOpOkForSideEffects < = > not has_side_effects
primOpOkForSpeculation < = > not ( has_side_effects || can_fail )
* The " no - float - out " thing is achieved by ensuring that we never
let - bind a can_fail or has_side_effects primop . The RHS of a
let - binding ( which can float in and out freely ) satisfies
exprOkForSpeculation ; this is the let / app invariant . And
exprOkForSpeculation is false of can_fail and has_side_effects .
* So and will appear only as the
scrutinees of cases , and that 's why the pass is capable
of floating case bindings inwards .
* The no - duplicate thing is done via primOpIsCheap , by making
has_side_effects things ( very very very ) not - cheap !
************************************************************************
* *
Failure and side effects
* *
************************************************************************
Note [Checking versus non-checking primops]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In GHC primops break down into two classes:
a. Checking primops behave, for instance, like division. In this
case the primop may throw an exception (e.g. division-by-zero)
and is consequently is marked with the can_fail flag described below.
The ability to fail comes at the expense of precluding some optimizations.
b. Non-checking primops behavior, for instance, like addition. While
addition can overflow it does not produce an exception. So can_fail is
set to False, and we get more optimisation opportunities. But we must
never throw an exception, so we cannot rewrite to a call to error.
It is important that a non-checking primop never be transformed in a way that
would cause it to bottom. Doing so would violate Core's let/app invariant
(see Note [CoreSyn let/app invariant] in CoreSyn) which is critical to
the simplifier's ability to float without fear of changing program meaning.
Note [PrimOp can_fail and has_side_effects]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Both can_fail and has_side_effects mean that the primop has
some effect that is not captured entirely by its result value.
A primop "has_side_effects" if it has some *write* effect, visible
elsewhere
- writing to the world (I/O)
- writing to a mutable data structure (writeIORef)
- throwing a synchronous Haskell exception
Often such primops have a type like
State -> input -> (State, output)
so the state token guarantees ordering. In general we rely *only* on
data dependencies of the state token to enforce write-effect ordering
* NB1: if you inline unsafePerformIO, you may end up with
side-effecting ops whose 'state' output is discarded.
And programmers may do that by hand; see #9390.
That is why we (conservatively) do not discard write-effecting
primops even if both their state and result is discarded.
* NB2: We consider primops, such as raiseIO#, that can raise a
(Haskell) synchronous exception to "have_side_effects" but not
"can_fail". We must be careful about not discarding such things;
see the paper "A semantics for imprecise exceptions".
* NB3: *Read* effects (like reading an IORef) don't count here,
because it doesn't matter if we don't do them, or do them more than
once. *Sequencing* is maintained by the data dependency of the state
token.
A primop "can_fail" if it can fail with an *unchecked* exception on
some elements of its input domain. Main examples:
division (fails on zero demoninator)
array indexing (fails if the index is out of bounds)
An "unchecked exception" is one that is an outright error, (not
turned into a Haskell exception,) such as seg-fault or
divide-by-zero error. Such can_fail primops are ALWAYS surrounded
with a test that checks for the bad cases, but we need to be
very careful about code motion that might move it out of
the scope of the test.
Note [Transformations affected by can_fail and has_side_effects]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The can_fail and has_side_effects properties have the following effect
on program transformations. Summary table is followed by details.
can_fail has_side_effects
Discard YES NO
Float in YES YES
Float out NO NO
Duplicate YES NO
* Discarding. case (a `op` b) of _ -> rhs ===> rhs
You should not discard a has_side_effects primop; e.g.
case (writeIntArray# a i v s of (# _, _ #) -> True
Arguably you should be able to discard this, since the
returned stat token is not used, but that relies on NEVER
inlining unsafePerformIO, and programmers sometimes write
this kind of stuff by hand (#9390). So we (conservatively)
never discard a has_side_effects primop.
However, it's fine to discard a can_fail primop. For example
case (indexIntArray# a i) of _ -> True
We can discard indexIntArray#; it has can_fail, but not
has_side_effects; see #5658 which was all about this.
Notice that indexIntArray# is (in a more general handling of
effects) read effect, but we don't care about that here, and
treat read effects as *not* has_side_effects.
Similarly (a `/#` b) can be discarded. It can seg-fault or
cause a hardware exception, but not a synchronous Haskell
exception.
Synchronous Haskell exceptions, e.g. from raiseIO#, are treated
as has_side_effects and hence are not discarded.
* Float in. You can float a can_fail or has_side_effects primop
*inwards*, but not inside a lambda (see Duplication below).
* Float out. You must not float a can_fail primop *outwards* lest
you escape the dynamic scope of the test. Example:
case d ># 0# of
True -> case x /# d of r -> r +# 1
False -> 0
Here we must not float the case outwards to give
case x/# d of r ->
case d ># 0# of
True -> r +# 1
False -> 0
Nor can you float out a has_side_effects primop. For example:
if blah then case writeMutVar# v True s0 of (# s1 #) -> s1
else s0
Notice that s0 is mentioned in both branches of the 'if', but
only one of these two will actually be consumed. But if we
float out to
case writeMutVar# v True s0 of (# s1 #) ->
if blah then s1 else s0
the writeMutVar will be performed in both branches, which is
utterly wrong.
* Duplication. You cannot duplicate a has_side_effect primop. You
might wonder how this can occur given the state token threading, but
just look at Control.Monad.ST.Lazy.Imp.strictToLazy! We get
something like this
p = case readMutVar# s v of
(# s', r #) -> (S# s', r)
s' = case p of (s', r) -> s'
r = case p of (s', r) -> r
(All these bindings are boxed.) If we inline p at its two call
sites, we get a catastrophe: because the read is performed once when
s' is demanded, and once when 'r' is demanded, which may be much
later. Utterly wrong. #3207 is real example of this happening.
However, it's fine to duplicate a can_fail primop. That is really
the only difference between can_fail and has_side_effects.
Note [Implementation: how can_fail/has_side_effects affect transformations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How do we ensure that that floating/duplication/discarding are done right
in the simplifier?
Two main predicates on primpops test these flags:
primOpOkForSideEffects <=> not has_side_effects
primOpOkForSpeculation <=> not (has_side_effects || can_fail)
* The "no-float-out" thing is achieved by ensuring that we never
let-bind a can_fail or has_side_effects primop. The RHS of a
let-binding (which can float in and out freely) satisfies
exprOkForSpeculation; this is the let/app invariant. And
exprOkForSpeculation is false of can_fail and has_side_effects.
* So can_fail and has_side_effects primops will appear only as the
scrutinees of cases, and that's why the FloatIn pass is capable
of floating case bindings inwards.
* The no-duplicate thing is done via primOpIsCheap, by making
has_side_effects things (very very very) not-cheap!
-}
primOpHasSideEffects :: PrimOp -> Bool
#include "primop-has-side-effects.hs-incl"
primOpCanFail :: PrimOp -> Bool
#include "primop-can-fail.hs-incl"
primOpOkForSpeculation :: PrimOp -> Bool
See comments with CoreUtils.exprOkForSpeculation
primOpOkForSpeculation op
= primOpOkForSideEffects op
&& not (primOpOutOfLine op || primOpCanFail op)
primOpOkForSideEffects :: PrimOp -> Bool
primOpOkForSideEffects op
= not (primOpHasSideEffects op)
Note [ primOpIsCheap ]
~~~~~~~~~~~~~~~~~~~~
@primOpIsCheap@ , as used in \tr{SimplUtils.hs } . For now ( HACK
WARNING ) , we just borrow some other predicates for a
what - should - be - good - enough test . " Cheap " means willing to call it more
than once , and/or push it inside a lambda . The latter could change the
behaviour of ' seq ' for that can fail , so we do n't treat them as cheap .
Note [primOpIsCheap]
~~~~~~~~~~~~~~~~~~~~
@primOpIsCheap@, as used in \tr{SimplUtils.hs}. For now (HACK
WARNING), we just borrow some other predicates for a
what-should-be-good-enough test. "Cheap" means willing to call it more
than once, and/or push it inside a lambda. The latter could change the
behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
-}
primOpIsCheap :: PrimOp -> Bool
primOpIsCheap op = primOpOkForSpeculation op
In March 2001 , we changed this to
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
PrimOp code size
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
primOpCodeSize
~~~~~~~~~~~~~~
Gives an indication of the code size of a primop , for the purposes of
calculating unfolding sizes ; see CoreUnfold.sizeExpr .
************************************************************************
* *
PrimOp code size
* *
************************************************************************
primOpCodeSize
~~~~~~~~~~~~~~
Gives an indication of the code size of a primop, for the purposes of
calculating unfolding sizes; see CoreUnfold.sizeExpr.
-}
primOpCodeSize :: PrimOp -> Int
#include "primop-code-size.hs-incl"
primOpCodeSizeDefault :: Int
primOpCodeSizeDefault = 1
primOpCodeSizeForeignCall :: Int
primOpCodeSizeForeignCall = 4
primOpType op
= case primOpInfo op of
Dyadic _occ ty -> dyadic_fun_ty ty
Monadic _occ ty -> monadic_fun_ty ty
Compare _occ ty -> compare_fun_ty ty
GenPrimOp _occ tyvars arg_tys res_ty ->
mkSpecForAllTys tyvars (mkVisFunTys arg_tys res_ty)
primOpOcc :: PrimOp -> OccName
primOpOcc op = case primOpInfo op of
Dyadic occ _ -> occ
Monadic occ _ -> occ
Compare occ _ -> occ
GenPrimOp occ _ _ _ -> occ
Note [ Primop wrappers ]
~~~~~~~~~~~~~~~~~~~~~~~~~
Previously hasNoBinding would claim that PrimOpIds did n't have a curried
function definition . This caused quite some trouble as we would be forced to
eta expand unsaturated primop applications very late in the Core pipeline . Not
only would this produce unnecessary thunks , but it would also result in nasty
inconsistencies in CAFfy - ness determinations ( see # 16846 and
Note [ CAFfyness inconsistencies due to late eta expansion ] in ) .
However , it was quite unnecessary for hasNoBinding to claim this ; primops in
fact * do * have curried definitions which are found in GHC.PrimopWrappers , which
is auto - generated by utils / genprimops from prelude / primops.txt.pp . These wrappers
are standard functions mirroring the types of the primops they wrap .
For instance , in the case of plusInt # we would have :
module GHC.PrimopWrappers where
import GHC.Prim as P
plusInt # a b = P.plusInt # a b
We now take advantage of these curried definitions by letting hasNoBinding
claim that PrimOpIds have a curried definition and then rewrite any unsaturated
PrimOpId applications that we find during CoreToStg as applications of the
associated wrapper ( e.g. ` GHC.Prim.plusInt # 3 # ` will get rewritten to
` GHC.PrimopWrappers.plusInt # 3 # ` ) . ` The I d of the wrapper for a primop can be
found using ' PrimOp.primOpWrapperId ' .
: GHC.PrimopWrappers is needed * regardless * , because it 's
used by GHCi , which does not implement primops direct at all .
~~~~~~~~~~~~~~~~~~~~~~~~~
Previously hasNoBinding would claim that PrimOpIds didn't have a curried
function definition. This caused quite some trouble as we would be forced to
eta expand unsaturated primop applications very late in the Core pipeline. Not
only would this produce unnecessary thunks, but it would also result in nasty
inconsistencies in CAFfy-ness determinations (see #16846 and
Note [CAFfyness inconsistencies due to late eta expansion] in TidyPgm).
However, it was quite unnecessary for hasNoBinding to claim this; primops in
fact *do* have curried definitions which are found in GHC.PrimopWrappers, which
is auto-generated by utils/genprimops from prelude/primops.txt.pp. These wrappers
are standard Haskell functions mirroring the types of the primops they wrap.
For instance, in the case of plusInt# we would have:
module GHC.PrimopWrappers where
import GHC.Prim as P
plusInt# a b = P.plusInt# a b
We now take advantage of these curried definitions by letting hasNoBinding
claim that PrimOpIds have a curried definition and then rewrite any unsaturated
PrimOpId applications that we find during CoreToStg as applications of the
associated wrapper (e.g. `GHC.Prim.plusInt# 3#` will get rewritten to
`GHC.PrimopWrappers.plusInt# 3#`).` The Id of the wrapper for a primop can be
found using 'PrimOp.primOpWrapperId'.
Nota Bene: GHC.PrimopWrappers is needed *regardless*, because it's
used by GHCi, which does not implement primops direct at all.
-}
See Note [ Primop wrappers ] .
primOpWrapperId :: PrimOp -> Id
primOpWrapperId op = mkVanillaGlobalWithInfo name ty info
where
info = setCafInfo vanillaIdInfo NoCafRefs
name = mkExternalName uniq gHC_PRIMOPWRAPPERS (primOpOcc op) wiredInSrcSpan
uniq = mkPrimOpWrapperUnique (primOpTag op)
ty = primOpType op
isComparisonPrimOp :: PrimOp -> Bool
isComparisonPrimOp op = case primOpInfo op of
Compare {} -> True
_ -> False
primOpSig is like primOpType but gives the result split apart :
primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
primOpSig op
= (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
where
arity = length arg_tys
(tyvars, arg_tys, res_ty)
= case (primOpInfo op) of
Monadic _occ ty -> ([], [ty], ty )
Dyadic _occ ty -> ([], [ty,ty], ty )
Compare _occ ty -> ([], [ty,ty], intPrimTy)
GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty )
data PrimOpResultInfo
= ReturnsPrim PrimRep
| ReturnsAlg TyCon
Some PrimOps need not return a manifest primitive or algebraic value
( i.e. they might return a polymorphic value ) . These PrimOps * must *
getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
getPrimOpResultInfo op
= case (primOpInfo op) of
Dyadic _ ty -> ReturnsPrim (typePrimRep1 ty)
Monadic _ ty -> ReturnsPrim (typePrimRep1 ty)
Compare _ _ -> ReturnsPrim (tyConPrimRep1 intPrimTyCon)
GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep1 tc)
| otherwise -> ReturnsAlg tc
where
tc = tyConAppTyCon ty
which gives rise to a ReturnAlg
dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
dyadic_fun_ty ty = mkVisFunTys [ty, ty] ty
monadic_fun_ty ty = mkVisFunTy ty ty
compare_fun_ty ty = mkVisFunTys [ty, ty] intPrimTy
pprPrimOp :: PrimOp -> SDoc
pprPrimOp other_op = pprOccName (primOpOcc other_op)
data PrimCall = PrimCall CLabelString UnitId
instance Outputable PrimCall where
ppr (PrimCall lbl pkgId)
= text "__primcall" <+> ppr pkgId <+> ppr lbl
|
b8efb020d342757bfda0f575cda2e58ca061241b738359d1c7bc041d38a19066 | fendor/hsimport | ModuleTest12.hs | {-# Language PatternGuards #-}
module Blub where
import Control.Monad
| null | https://raw.githubusercontent.com/fendor/hsimport/9be9918b06545cfd7282e4db08c2b88f1d8162cd/tests/goldenFiles/ModuleTest12.hs | haskell | # Language PatternGuards # | module Blub where
import Control.Monad
|
1ce335d2c10d28461e2862f8c10c384150d827aa4982b6c34cd915599c2199be | Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library | OrdersPaymentMethodOptionsAfterpayClearpay.hs | {-# LANGUAGE MultiWayIf #-}
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
{-# LANGUAGE OverloadedStrings #-}
-- | Contains the types generated from the schema OrdersPaymentMethodOptionsAfterpayClearpay
module StripeAPI.Types.OrdersPaymentMethodOptionsAfterpayClearpay where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
-- | Defines the object schema located at @components.schemas.orders_payment_method_options_afterpay_clearpay@ in the specification.
data OrdersPaymentMethodOptionsAfterpayClearpay = OrdersPaymentMethodOptionsAfterpayClearpay
{ -- | capture_method: Controls when the funds will be captured from the customer\'s account.
ordersPaymentMethodOptionsAfterpayClearpayCaptureMethod :: (GHC.Maybe.Maybe OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'),
| reference : Order identifier shown to the user in Afterpay\ 's online portal . We recommend using a value that helps you answer any questions a customer might have about the payment . The identifier is limited to 128 characters and may contain only letters , digits , underscores , backslashes and dashes .
--
-- Constraints:
--
* Maximum length of 5000
ordersPaymentMethodOptionsAfterpayClearpayReference :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)),
-- | setup_future_usage: Indicates that you intend to make future payments with the payment method.
--
Providing this parameter will [ attach the payment method](https:\/\/stripe.com\/docs\/payments\/save - during - payment ) to the order\ 's Customer , if present , after the order\ 's PaymentIntent is confirmed and any required actions from the user are complete . If no Customer was provided , the payment method can still be [ ) to a Customer after the transaction completes .
--
When processing card payments , Stripe also uses \`setup_future_usage\ ` to dynamically optimize your payment flow and comply with regional legislation and network rules , such as [ SCA](https:\/\/stripe.com\/docs\/strong - customer - authentication ) .
--
-- If \`setup_future_usage\` is already set and you are performing a request using a publishable key, you may only update the value from \`on_session\` to \`off_session\`.
ordersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage :: (GHC.Maybe.Maybe OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage')
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON OrdersPaymentMethodOptionsAfterpayClearpay where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("capture_method" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpayCaptureMethod obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("reference" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpayReference obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("setup_future_usage" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("capture_method" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpayCaptureMethod obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("reference" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpayReference obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("setup_future_usage" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON OrdersPaymentMethodOptionsAfterpayClearpay where
parseJSON = Data.Aeson.Types.FromJSON.withObject "OrdersPaymentMethodOptionsAfterpayClearpay" (\obj -> ((GHC.Base.pure OrdersPaymentMethodOptionsAfterpayClearpay GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "capture_method")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "reference")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "setup_future_usage"))
-- | Create a new 'OrdersPaymentMethodOptionsAfterpayClearpay' with all required fields.
mkOrdersPaymentMethodOptionsAfterpayClearpay :: OrdersPaymentMethodOptionsAfterpayClearpay
mkOrdersPaymentMethodOptionsAfterpayClearpay =
OrdersPaymentMethodOptionsAfterpayClearpay
{ ordersPaymentMethodOptionsAfterpayClearpayCaptureMethod = GHC.Maybe.Nothing,
ordersPaymentMethodOptionsAfterpayClearpayReference = GHC.Maybe.Nothing,
ordersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage = GHC.Maybe.Nothing
}
| Defines the enum schema located at @components.schemas.orders_payment_method_options_afterpay_clearpay.properties.capture_method@ in the specification .
--
-- Controls when the funds will be captured from the customer\'s account.
data OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'
= -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'Other Data.Aeson.Types.Internal.Value
| -- | This constructor can be used to send values to the server which are not present in the specification yet.
OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'Typed Data.Text.Internal.Text
| -- | Represents the JSON value @"automatic"@
OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumAutomatic
| Represents the JSON value @"manual"@
OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumManual
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod' where
toJSON (OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'Other val) = val
toJSON (OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumAutomatic) = "automatic"
toJSON (OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumManual) = "manual"
instance Data.Aeson.Types.FromJSON.FromJSON OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "automatic" -> OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumAutomatic
| val GHC.Classes.== "manual" -> OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumManual
| GHC.Base.otherwise -> OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'Other val
)
-- | Defines the enum schema located at @components.schemas.orders_payment_method_options_afterpay_clearpay.properties.setup_future_usage@ in the specification.
--
-- Indicates that you intend to make future payments with the payment method.
--
Providing this parameter will [ attach the payment method](https:\/\/stripe.com\/docs\/payments\/save - during - payment ) to the order\ 's Customer , if present , after the order\ 's PaymentIntent is confirmed and any required actions from the user are complete . If no Customer was provided , the payment method can still be [ ) to a Customer after the transaction completes .
--
When processing card payments , Stripe also uses \`setup_future_usage\ ` to dynamically optimize your payment flow and comply with regional legislation and network rules , such as [ SCA](https:\/\/stripe.com\/docs\/strong - customer - authentication ) .
--
-- If \`setup_future_usage\` is already set and you are performing a request using a publishable key, you may only update the value from \`on_session\` to \`off_session\`.
data OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'
= -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'Other Data.Aeson.Types.Internal.Value
| -- | This constructor can be used to send values to the server which are not present in the specification yet.
OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'Typed Data.Text.Internal.Text
| -- | Represents the JSON value @"none"@
OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'EnumNone
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage' where
toJSON (OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'Other val) = val
toJSON (OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'EnumNone) = "none"
instance Data.Aeson.Types.FromJSON.FromJSON OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "none" -> OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'EnumNone
| GHC.Base.otherwise -> OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'Other val
)
| null | https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/OrdersPaymentMethodOptionsAfterpayClearpay.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
| Contains the types generated from the schema OrdersPaymentMethodOptionsAfterpayClearpay
| Defines the object schema located at @components.schemas.orders_payment_method_options_afterpay_clearpay@ in the specification.
| capture_method: Controls when the funds will be captured from the customer\'s account.
Constraints:
| setup_future_usage: Indicates that you intend to make future payments with the payment method.
If \`setup_future_usage\` is already set and you are performing a request using a publishable key, you may only update the value from \`on_session\` to \`off_session\`.
| Create a new 'OrdersPaymentMethodOptionsAfterpayClearpay' with all required fields.
Controls when the funds will be captured from the customer\'s account.
| This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
| This constructor can be used to send values to the server which are not present in the specification yet.
| Represents the JSON value @"automatic"@
| Defines the enum schema located at @components.schemas.orders_payment_method_options_afterpay_clearpay.properties.setup_future_usage@ in the specification.
Indicates that you intend to make future payments with the payment method.
If \`setup_future_usage\` is already set and you are performing a request using a publishable key, you may only update the value from \`on_session\` to \`off_session\`.
| This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
| This constructor can be used to send values to the server which are not present in the specification yet.
| Represents the JSON value @"none"@ | CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
module StripeAPI.Types.OrdersPaymentMethodOptionsAfterpayClearpay where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
data OrdersPaymentMethodOptionsAfterpayClearpay = OrdersPaymentMethodOptionsAfterpayClearpay
ordersPaymentMethodOptionsAfterpayClearpayCaptureMethod :: (GHC.Maybe.Maybe OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'),
| reference : Order identifier shown to the user in Afterpay\ 's online portal . We recommend using a value that helps you answer any questions a customer might have about the payment . The identifier is limited to 128 characters and may contain only letters , digits , underscores , backslashes and dashes .
* Maximum length of 5000
ordersPaymentMethodOptionsAfterpayClearpayReference :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)),
Providing this parameter will [ attach the payment method](https:\/\/stripe.com\/docs\/payments\/save - during - payment ) to the order\ 's Customer , if present , after the order\ 's PaymentIntent is confirmed and any required actions from the user are complete . If no Customer was provided , the payment method can still be [ ) to a Customer after the transaction completes .
When processing card payments , Stripe also uses \`setup_future_usage\ ` to dynamically optimize your payment flow and comply with regional legislation and network rules , such as [ SCA](https:\/\/stripe.com\/docs\/strong - customer - authentication ) .
ordersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage :: (GHC.Maybe.Maybe OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage')
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON OrdersPaymentMethodOptionsAfterpayClearpay where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("capture_method" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpayCaptureMethod obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("reference" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpayReference obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("setup_future_usage" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("capture_method" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpayCaptureMethod obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("reference" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpayReference obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("setup_future_usage" Data.Aeson.Types.ToJSON..=)) (ordersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON OrdersPaymentMethodOptionsAfterpayClearpay where
parseJSON = Data.Aeson.Types.FromJSON.withObject "OrdersPaymentMethodOptionsAfterpayClearpay" (\obj -> ((GHC.Base.pure OrdersPaymentMethodOptionsAfterpayClearpay GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "capture_method")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "reference")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "setup_future_usage"))
mkOrdersPaymentMethodOptionsAfterpayClearpay :: OrdersPaymentMethodOptionsAfterpayClearpay
mkOrdersPaymentMethodOptionsAfterpayClearpay =
OrdersPaymentMethodOptionsAfterpayClearpay
{ ordersPaymentMethodOptionsAfterpayClearpayCaptureMethod = GHC.Maybe.Nothing,
ordersPaymentMethodOptionsAfterpayClearpayReference = GHC.Maybe.Nothing,
ordersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage = GHC.Maybe.Nothing
}
| Defines the enum schema located at @components.schemas.orders_payment_method_options_afterpay_clearpay.properties.capture_method@ in the specification .
data OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'
OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'Other Data.Aeson.Types.Internal.Value
OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'Typed Data.Text.Internal.Text
OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumAutomatic
| Represents the JSON value @"manual"@
OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumManual
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod' where
toJSON (OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'Other val) = val
toJSON (OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumAutomatic) = "automatic"
toJSON (OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumManual) = "manual"
instance Data.Aeson.Types.FromJSON.FromJSON OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "automatic" -> OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumAutomatic
| val GHC.Classes.== "manual" -> OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'EnumManual
| GHC.Base.otherwise -> OrdersPaymentMethodOptionsAfterpayClearpayCaptureMethod'Other val
)
Providing this parameter will [ attach the payment method](https:\/\/stripe.com\/docs\/payments\/save - during - payment ) to the order\ 's Customer , if present , after the order\ 's PaymentIntent is confirmed and any required actions from the user are complete . If no Customer was provided , the payment method can still be [ ) to a Customer after the transaction completes .
When processing card payments , Stripe also uses \`setup_future_usage\ ` to dynamically optimize your payment flow and comply with regional legislation and network rules , such as [ SCA](https:\/\/stripe.com\/docs\/strong - customer - authentication ) .
data OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'
OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'Other Data.Aeson.Types.Internal.Value
OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'Typed Data.Text.Internal.Text
OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'EnumNone
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage' where
toJSON (OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'Other val) = val
toJSON (OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'EnumNone) = "none"
instance Data.Aeson.Types.FromJSON.FromJSON OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "none" -> OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'EnumNone
| GHC.Base.otherwise -> OrdersPaymentMethodOptionsAfterpayClearpaySetupFutureUsage'Other val
)
|
2ad55013783b4cc6a68c8e1f8de23b2dbe6b9d0730f6da2ad79e248143cfa082 | ubf/ubf | ubf.erl | %%% The MIT License
%%%
Copyright ( C ) 2011 - 2016 by < >
Copyright ( C ) 2002 by
%%%
%%% Permission is hereby granted, free of charge, to any person obtaining a copy
%%% of this software and associated documentation files (the "Software"), to deal
in the Software without restriction , including without limitation the rights
%%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
%%% furnished to do so, subject to the following conditions:
%%%
%%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
%%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%%% THE SOFTWARE.
%%% @doc Low-level functions for encoding and decoding the UBF(a)
%%% protocol.
%%%
UBF is a family of languages for transporting and describing
complex data structures across a network . It has three
%%% components. In terms of a protocol stack, UBF(a) is a data
transport format , roughly equivalent to well - formed XML .
%%%
%%% UBF(a) is the transport format, it was designed to be easy to
parse and to be easy to write with a text editor . UBF(a ) is based
on a byte encoded virtual machine , 26 byte codes are
%%% reserved. Instead of allocating the byte codes from 0 we use the
%%% printable character codes to make the format easy to read.
%%%
-module(ubf).
-behaviour(contract_proto).
-export([proto_vsn/0, proto_driver/0, proto_packet_type/0]).
-export([encode/1, encode/2]).
-export([decode_init/0, decode_init/1, decode_init/2, decode/1, decode/2, decode/3]).
-export([deabstract/1]).
-import(lists, [foldl/3, reverse/1, map/2, seq/2, sort/1]).
-record(state, {
safe=false :: boolean(),
FYI - dict : dict ( ) vs. dict ( ) Erlang / OTP 17 incompatibility
}).
%%---------------------------------------------------------------------
proto_vsn() -> 'ubf1.0'.
proto_driver() -> ubf_driver.
proto_packet_type() -> 0.
%%---------------------------------------------------------------------
decode_init() ->
decode_init(false).
decode_init(Safe) ->
decode_init(Safe, []).
decode_init(Safe, []) ->
State = #state{safe=Safe, dict=dict:new()},
{more, fun(I) -> decode1(I, [[]], State) end};
decode_init(Safe, String) when is_list(String) ->
State = #state{safe=Safe, dict=dict:new()},
decode1(String, [[]], State).
decode(String) ->
decode(String, ?MODULE).
decode(String, Mod) ->
decode(String, Mod, decode_init(false)).
decode(S, _Mod, {more, Fun}) ->
Fun(S).
decode1([$'|T], Stack, State) ->
get_stuff(T, $', [], Stack, State);
decode1([$~|T], [[Int|Stack]|S1], State) when is_integer(Int), Int >= 0 ->
collect_binary(Int, T, [], [Stack|S1], State);
decode1([$~|_T], _Stack, _State) ->
exit(tilde);
, Stack , State ) - >
, [ ] , Stack , State ) ;
decode1([$"|T], Stack, State) ->
get_stuff(T, $", [], Stack, State);
decode1([$`|T], Stack, State) ->
get_stuff(T, $`, [], Stack, State);
decode1([$-|T], Stack, State) ->
collect_int(T, 0, '-', Stack, State);
decode1([H|T], Stack, State) when $0 =< H, H =< $9 ->
collect_int(T, H-$0, '+', Stack, State);
decode1([${|T], Stack, State) ->
decode1(T, [[]|Stack], State);
decode1([$}|T], [H|Stack], State) ->
decode1(T, push(list_to_tuple(reverse(H)),Stack), State);
decode1([$&|T], [[H1,H2|T1] | Stack], State) ->
decode1(T, [[[H1|H2]|T1]|Stack], State);
decode1([$#|T], Stack, State) ->
decode1(T, push([], Stack), State);
decode1([$$|T], [[X]], _State) ->
{done, X, T, undefined};
decode1([$>], Stack, State) ->
{more, fun(I) -> decode1([$>|I], Stack, State) end};
decode1([$>,Key|T], [[Val|R]|Stack], #state{dict=Dict}=State) ->
decode1(T, [R|Stack], State#state{dict=dict:store(Key,Val,Dict)});
decode1([H|T], Stack, #state{dict=Dict}=State) ->
case special(H) of
true ->
decode1(T, Stack, State);
false ->
decode1(T, push(dict:fetch(H, Dict), Stack), State)
end;
decode1([], Stack, State) ->
{more, fun(I) -> decode1(I, Stack, State) end};
decode1(_X, _Stack, _State) ->
exit(decode1).
get_stuff([$\\], Stop, L, Stack, State) ->
{more, fun(I) -> get_stuff([$\\|I], Stop, L, Stack, State) end};
get_stuff([$\\,H|T], Stop, L, Stack, State) ->
get_stuff(T, Stop, [H|L], Stack, State);
get_stuff([$'|T], $', L, Stack, #state{safe=Safe}=State) ->
RevL = reverse(L),
Atom = if Safe -> list_to_existing_atom(RevL); true -> list_to_atom(RevL) end,
decode1(T, push(Atom, Stack), State);
get_stuff([$"|T], $", L, Stack, State) ->
decode1(T, push({'#S',reverse(L)},Stack), State);
get_stuff([$`|T], $`, L, [[X|Top]|Stack], State) ->
decode1(T, push({'$TYPE', reverse(L), X}, [Top|Stack]), State);
$ % , _ L , Stack , State ) - >
decode1(T, Stack, State);
get_stuff([H|T], Stop, L, Stack, State) ->
get_stuff(T, Stop, [H|L], Stack, State);
get_stuff([], Stop, L, Stack, State) ->
{more, fun(I) -> get_stuff(I, Stop, L, Stack, State) end}.
collect_binary(0, T, L, Stack, State) ->
expect_tilde(T, push(list_to_binary(reverse(L)),Stack), State);
collect_binary(N, [H|T], L, Stack, State) ->
collect_binary(N-1, T, [H|L], Stack, State);
collect_binary(N, [], L, Stack, State) ->
{more, fun(I) -> collect_binary(N, I, L, Stack, State) end}.
expect_tilde([$~|T], Stack, State) ->
decode1(T, Stack, State);
expect_tilde([], Stack, State) ->
{more, fun(I) -> expect_tilde(I, Stack, State) end};
expect_tilde([H|_], _, _) ->
exit({expect_tilde, H}).
push(X, [Top|Rest]) ->
[[X|Top]|Rest];
push(_X, _Y) ->
exit(push).
special($ ) -> true;
special(${) -> true;
special($}) -> true;
special($,) -> true;
special($#) -> true;
special($&) -> true;
special($%) -> true;
special($>) -> true;
special($\n) -> true;
special($\r) -> true;
special($\t) -> true;
special($$) -> true;
special($") -> true;
special($') -> true;
special($~) -> true;
special(_) -> false.
special_chars() ->
" 0123456789{},~%#>\n\r\s\t\"'-&$".
collect_int([H|T], N, Sign, Stack, State) when $0 =< H, H =< $9 ->
collect_int(T, N*10 + H - $0, Sign, Stack, State);
collect_int([], N, Sign, Stack, State) ->
{more, fun(I) -> collect_int(I, N, Sign, Stack, State) end};
collect_int(T, N, '+', Stack, State) ->
decode1(T, push(N, Stack), State);
collect_int(T, N, '-', Stack, State) ->
decode1(T, push(-N, Stack), State).
%%---------------------------------------------------------------------
encode(X) ->
encode(X, ?MODULE).
encode(X, _Mod) ->
element(1, encode1(X, dict:new())).
encode1(X, Dict0) ->
{Dict1, L1} = initial_dict(X, Dict0),
case (catch do_encode(X, Dict1)) of
{'EXIT', _What} ->
exit(encode1);
L ->
{flatten([L1, L,$$]), Dict1}
end.
initial_dict(X, Dict0) ->
Free = seq(32,255) -- special_chars(),
Most = analyse(X),
load_dict(Most, Free, Dict0, []).
load_dict([{N,X}|T], [Key|T1], Dict0, L) when N > 0->
load_dict(T, T1, dict:store(X, Key, Dict0),
[encode_obj(X),">",Key|L]);
load_dict(_, _, Dict, L) ->
{Dict, L}.
analyse(T) ->
KV = dict:to_list(analyse(T, dict:new())),
%% The Range is the Number of things times its size. If the size
%% is greater than 0
KV1 = map(fun rank/1, KV),
reverse(sort(KV1)).
rank({X, K}) when is_atom(X) ->
case length(atom_to_list(X)) of
N when N > 1, K > 1 ->
{(N-1) * K, X};
_ ->
{0, X}
end;
rank({X, K}) when is_integer(X) ->
case length(integer_to_list(X)) of
N when N > 1, K > 1 ->
{(N-1) * K, X};
_ ->
{0, X}
end;
rank({X, _}) ->
{0, X}.
analyse({'#S', String}, Dict) ->
analyse(String, Dict);
analyse(T, Dict) when is_tuple(T) ->
foldl(fun analyse/2, Dict, tuple_to_list(T));
analyse(X, Dict) ->
case dict:find(X, Dict) of
{ok, Val} ->
dict:store(X, Val+1, Dict);
error ->
dict:store(X, 1, Dict)
end.
flatten(L) ->
binary_to_list(list_to_binary(L)).
encode_obj(X) when is_atom(X) -> encode_atom(X);
encode_obj(X) when is_integer(X) -> integer_to_list(X);
encode_obj(X) when is_binary(X) -> encode_binary(X).
encode_string(S) -> [$",add_string(S, $"), $"].
encode_atom(X) -> [$',add_string(atom_to_list(X), $'), $'].
encode_binary(X) -> [integer_to_list(byte_size(X)), $~,X,$~].
do_encode(X, Dict) when is_atom(X); is_integer(X); is_binary(X) ->
case dict:find(X, Dict) of
{ok, Y} ->
Y;
error ->
encode_obj(X)
end;
do_encode({'#S', String}, _Dict) ->
%% This *is* a string
encode_string(String);
do_encode([H|T], Dict) ->
S1 = do_encode(T, Dict),
S2 = do_encode(H, Dict),
[S1,S2,$&];
do_encode(T, Dict) when is_tuple(T) ->
S1 = encode_tuple(1, T, Dict),
[${,S1,$}];
do_encode([], _Dict) ->
$#.
encode_tuple(N, T, _Dict) when N > tuple_size(T) ->
"";
encode_tuple(N, T, Dict) ->
S1 = do_encode(element(N, T), Dict),
S2 = encode_tuple(N+1, T, Dict),
[S1,possible_comma(N, T),S2].
possible_comma(N, T) when N < tuple_size(T) -> $,;
possible_comma(_, _) -> [].
The ascii printables are in the range 32 .. 126 inclusive
add_string([$\\|T], Quote) -> [$\\,$\\|add_string(T, Quote)];
add_string([Quote|T], Quote) -> [$\\,Quote|add_string(T, Quote)];
add_string([H|T], Quote) when H >= 0, H=< 255 -> [H|add_string(T, Quote)];
add_string([H|_], _Quote) -> exit({string_character,H});
add_string([], _) -> [].
%%---------------------------------------------------------------------
deabstract({'#S',S}) -> S;
deabstract(T) when is_tuple(T) ->
list_to_tuple(map(fun deabstract/1, tuple_to_list(T)));
deabstract([H|T]) -> [deabstract(H)|deabstract(T)];
deabstract(T) -> T.
| null | https://raw.githubusercontent.com/ubf/ubf/c876f684fbd4959548ace1eb1cfc91941f93d377/src/ubf.erl | erlang | The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@doc Low-level functions for encoding and decoding the UBF(a)
protocol.
components. In terms of a protocol stack, UBF(a) is a data
UBF(a) is the transport format, it was designed to be easy to
reserved. Instead of allocating the byte codes from 0 we use the
printable character codes to make the format easy to read.
---------------------------------------------------------------------
---------------------------------------------------------------------
, _ L , Stack , State ) - >
) -> true;
---------------------------------------------------------------------
The Range is the Number of things times its size. If the size
is greater than 0
This *is* a string
--------------------------------------------------------------------- | Copyright ( C ) 2011 - 2016 by < >
Copyright ( C ) 2002 by
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
UBF is a family of languages for transporting and describing
complex data structures across a network . It has three
transport format , roughly equivalent to well - formed XML .
parse and to be easy to write with a text editor . UBF(a ) is based
on a byte encoded virtual machine , 26 byte codes are
-module(ubf).
-behaviour(contract_proto).
-export([proto_vsn/0, proto_driver/0, proto_packet_type/0]).
-export([encode/1, encode/2]).
-export([decode_init/0, decode_init/1, decode_init/2, decode/1, decode/2, decode/3]).
-export([deabstract/1]).
-import(lists, [foldl/3, reverse/1, map/2, seq/2, sort/1]).
-record(state, {
safe=false :: boolean(),
FYI - dict : dict ( ) vs. dict ( ) Erlang / OTP 17 incompatibility
}).
proto_vsn() -> 'ubf1.0'.
proto_driver() -> ubf_driver.
proto_packet_type() -> 0.
decode_init() ->
decode_init(false).
decode_init(Safe) ->
decode_init(Safe, []).
decode_init(Safe, []) ->
State = #state{safe=Safe, dict=dict:new()},
{more, fun(I) -> decode1(I, [[]], State) end};
decode_init(Safe, String) when is_list(String) ->
State = #state{safe=Safe, dict=dict:new()},
decode1(String, [[]], State).
decode(String) ->
decode(String, ?MODULE).
decode(String, Mod) ->
decode(String, Mod, decode_init(false)).
decode(S, _Mod, {more, Fun}) ->
Fun(S).
decode1([$'|T], Stack, State) ->
get_stuff(T, $', [], Stack, State);
decode1([$~|T], [[Int|Stack]|S1], State) when is_integer(Int), Int >= 0 ->
collect_binary(Int, T, [], [Stack|S1], State);
decode1([$~|_T], _Stack, _State) ->
exit(tilde);
, Stack , State ) - >
, [ ] , Stack , State ) ;
decode1([$"|T], Stack, State) ->
get_stuff(T, $", [], Stack, State);
decode1([$`|T], Stack, State) ->
get_stuff(T, $`, [], Stack, State);
decode1([$-|T], Stack, State) ->
collect_int(T, 0, '-', Stack, State);
decode1([H|T], Stack, State) when $0 =< H, H =< $9 ->
collect_int(T, H-$0, '+', Stack, State);
decode1([${|T], Stack, State) ->
decode1(T, [[]|Stack], State);
decode1([$}|T], [H|Stack], State) ->
decode1(T, push(list_to_tuple(reverse(H)),Stack), State);
decode1([$&|T], [[H1,H2|T1] | Stack], State) ->
decode1(T, [[[H1|H2]|T1]|Stack], State);
decode1([$#|T], Stack, State) ->
decode1(T, push([], Stack), State);
decode1([$$|T], [[X]], _State) ->
{done, X, T, undefined};
decode1([$>], Stack, State) ->
{more, fun(I) -> decode1([$>|I], Stack, State) end};
decode1([$>,Key|T], [[Val|R]|Stack], #state{dict=Dict}=State) ->
decode1(T, [R|Stack], State#state{dict=dict:store(Key,Val,Dict)});
decode1([H|T], Stack, #state{dict=Dict}=State) ->
case special(H) of
true ->
decode1(T, Stack, State);
false ->
decode1(T, push(dict:fetch(H, Dict), Stack), State)
end;
decode1([], Stack, State) ->
{more, fun(I) -> decode1(I, Stack, State) end};
decode1(_X, _Stack, _State) ->
exit(decode1).
get_stuff([$\\], Stop, L, Stack, State) ->
{more, fun(I) -> get_stuff([$\\|I], Stop, L, Stack, State) end};
get_stuff([$\\,H|T], Stop, L, Stack, State) ->
get_stuff(T, Stop, [H|L], Stack, State);
get_stuff([$'|T], $', L, Stack, #state{safe=Safe}=State) ->
RevL = reverse(L),
Atom = if Safe -> list_to_existing_atom(RevL); true -> list_to_atom(RevL) end,
decode1(T, push(Atom, Stack), State);
get_stuff([$"|T], $", L, Stack, State) ->
decode1(T, push({'#S',reverse(L)},Stack), State);
get_stuff([$`|T], $`, L, [[X|Top]|Stack], State) ->
decode1(T, push({'$TYPE', reverse(L), X}, [Top|Stack]), State);
decode1(T, Stack, State);
get_stuff([H|T], Stop, L, Stack, State) ->
get_stuff(T, Stop, [H|L], Stack, State);
get_stuff([], Stop, L, Stack, State) ->
{more, fun(I) -> get_stuff(I, Stop, L, Stack, State) end}.
collect_binary(0, T, L, Stack, State) ->
expect_tilde(T, push(list_to_binary(reverse(L)),Stack), State);
collect_binary(N, [H|T], L, Stack, State) ->
collect_binary(N-1, T, [H|L], Stack, State);
collect_binary(N, [], L, Stack, State) ->
{more, fun(I) -> collect_binary(N, I, L, Stack, State) end}.
expect_tilde([$~|T], Stack, State) ->
decode1(T, Stack, State);
expect_tilde([], Stack, State) ->
{more, fun(I) -> expect_tilde(I, Stack, State) end};
expect_tilde([H|_], _, _) ->
exit({expect_tilde, H}).
push(X, [Top|Rest]) ->
[[X|Top]|Rest];
push(_X, _Y) ->
exit(push).
special($ ) -> true;
special(${) -> true;
special($}) -> true;
special($,) -> true;
special($#) -> true;
special($&) -> true;
special($>) -> true;
special($\n) -> true;
special($\r) -> true;
special($\t) -> true;
special($$) -> true;
special($") -> true;
special($') -> true;
special($~) -> true;
special(_) -> false.
special_chars() ->
" 0123456789{},~%#>\n\r\s\t\"'-&$".
collect_int([H|T], N, Sign, Stack, State) when $0 =< H, H =< $9 ->
collect_int(T, N*10 + H - $0, Sign, Stack, State);
collect_int([], N, Sign, Stack, State) ->
{more, fun(I) -> collect_int(I, N, Sign, Stack, State) end};
collect_int(T, N, '+', Stack, State) ->
decode1(T, push(N, Stack), State);
collect_int(T, N, '-', Stack, State) ->
decode1(T, push(-N, Stack), State).
encode(X) ->
encode(X, ?MODULE).
encode(X, _Mod) ->
element(1, encode1(X, dict:new())).
encode1(X, Dict0) ->
{Dict1, L1} = initial_dict(X, Dict0),
case (catch do_encode(X, Dict1)) of
{'EXIT', _What} ->
exit(encode1);
L ->
{flatten([L1, L,$$]), Dict1}
end.
initial_dict(X, Dict0) ->
Free = seq(32,255) -- special_chars(),
Most = analyse(X),
load_dict(Most, Free, Dict0, []).
load_dict([{N,X}|T], [Key|T1], Dict0, L) when N > 0->
load_dict(T, T1, dict:store(X, Key, Dict0),
[encode_obj(X),">",Key|L]);
load_dict(_, _, Dict, L) ->
{Dict, L}.
analyse(T) ->
KV = dict:to_list(analyse(T, dict:new())),
KV1 = map(fun rank/1, KV),
reverse(sort(KV1)).
rank({X, K}) when is_atom(X) ->
case length(atom_to_list(X)) of
N when N > 1, K > 1 ->
{(N-1) * K, X};
_ ->
{0, X}
end;
rank({X, K}) when is_integer(X) ->
case length(integer_to_list(X)) of
N when N > 1, K > 1 ->
{(N-1) * K, X};
_ ->
{0, X}
end;
rank({X, _}) ->
{0, X}.
analyse({'#S', String}, Dict) ->
analyse(String, Dict);
analyse(T, Dict) when is_tuple(T) ->
foldl(fun analyse/2, Dict, tuple_to_list(T));
analyse(X, Dict) ->
case dict:find(X, Dict) of
{ok, Val} ->
dict:store(X, Val+1, Dict);
error ->
dict:store(X, 1, Dict)
end.
flatten(L) ->
binary_to_list(list_to_binary(L)).
encode_obj(X) when is_atom(X) -> encode_atom(X);
encode_obj(X) when is_integer(X) -> integer_to_list(X);
encode_obj(X) when is_binary(X) -> encode_binary(X).
encode_string(S) -> [$",add_string(S, $"), $"].
encode_atom(X) -> [$',add_string(atom_to_list(X), $'), $'].
encode_binary(X) -> [integer_to_list(byte_size(X)), $~,X,$~].
do_encode(X, Dict) when is_atom(X); is_integer(X); is_binary(X) ->
case dict:find(X, Dict) of
{ok, Y} ->
Y;
error ->
encode_obj(X)
end;
do_encode({'#S', String}, _Dict) ->
encode_string(String);
do_encode([H|T], Dict) ->
S1 = do_encode(T, Dict),
S2 = do_encode(H, Dict),
[S1,S2,$&];
do_encode(T, Dict) when is_tuple(T) ->
S1 = encode_tuple(1, T, Dict),
[${,S1,$}];
do_encode([], _Dict) ->
$#.
encode_tuple(N, T, _Dict) when N > tuple_size(T) ->
"";
encode_tuple(N, T, Dict) ->
S1 = do_encode(element(N, T), Dict),
S2 = encode_tuple(N+1, T, Dict),
[S1,possible_comma(N, T),S2].
possible_comma(N, T) when N < tuple_size(T) -> $,;
possible_comma(_, _) -> [].
The ascii printables are in the range 32 .. 126 inclusive
add_string([$\\|T], Quote) -> [$\\,$\\|add_string(T, Quote)];
add_string([Quote|T], Quote) -> [$\\,Quote|add_string(T, Quote)];
add_string([H|T], Quote) when H >= 0, H=< 255 -> [H|add_string(T, Quote)];
add_string([H|_], _Quote) -> exit({string_character,H});
add_string([], _) -> [].
deabstract({'#S',S}) -> S;
deabstract(T) when is_tuple(T) ->
list_to_tuple(map(fun deabstract/1, tuple_to_list(T)));
deabstract([H|T]) -> [deabstract(H)|deabstract(T)];
deabstract(T) -> T.
|
0f946dfa3e41384dbd5a5d990bdd0de412c4da75083a684909b66795a8248911 | sadiqj/ocaml-esp32 | env.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Environment handling *)
open Types
module PathMap : Map.S with type key = Path.t
and type 'a t = 'a Map.Make(Path).t
type summary =
Env_empty
| Env_value of summary * Ident.t * value_description
| Env_type of summary * Ident.t * type_declaration
| Env_extension of summary * Ident.t * extension_constructor
| Env_module of summary * Ident.t * module_declaration
| Env_modtype of summary * Ident.t * modtype_declaration
| Env_class of summary * Ident.t * class_declaration
| Env_cltype of summary * Ident.t * class_type_declaration
| Env_open of summary * Path.t
| Env_functor_arg of summary * Ident.t
| Env_constraints of summary * type_declaration PathMap.t
| Env_copy_types of summary * string list
type t
val empty: t
val initial_safe_string: t
val initial_unsafe_string: t
val diff: t -> t -> Ident.t list
val copy_local: from:t -> t -> t
type type_descriptions =
constructor_description list * label_description list
(* For short-paths *)
type iter_cont
val iter_types:
(Path.t -> Path.t * (type_declaration * type_descriptions) -> unit) ->
t -> iter_cont
val run_iter_cont: iter_cont list -> (Path.t * iter_cont) list
val same_types: t -> t -> bool
val used_persistent: unit -> Concr.t
val find_shadowed_types: Path.t -> t -> Path.t list
val without_cmis: ('a -> 'b) -> 'a -> 'b
[ without_cmis f arg ] applies [ f ] to [ arg ] , but does not
allow opening cmis during its execution
allow opening cmis during its execution *)
(* Lookup by paths *)
val find_value: Path.t -> t -> value_description
val find_type: Path.t -> t -> type_declaration
val find_type_descrs: Path.t -> t -> type_descriptions
val find_module: Path.t -> t -> module_declaration
val find_modtype: Path.t -> t -> modtype_declaration
val find_class: Path.t -> t -> class_declaration
val find_cltype: Path.t -> t -> class_type_declaration
val find_type_expansion:
Path.t -> t -> type_expr list * type_expr * int option
val find_type_expansion_opt:
Path.t -> t -> type_expr list * type_expr * int option
(* Find the manifest type information associated to a type for the sake
of the compiler's type-based optimisations. *)
val find_modtype_expansion: Path.t -> t -> module_type
val add_functor_arg: Ident.t -> t -> t
val is_functor_arg: Path.t -> t -> bool
val normalize_path: Location.t option -> t -> Path.t -> Path.t
(* Normalize the path to a concrete value or module.
If the option is None, allow returning dangling paths.
Otherwise raise a Missing_module error, and may add forgotten
head as required global. *)
val normalize_path_prefix: Location.t option -> t -> Path.t -> Path.t
(* Only normalize the prefix part of the path *)
val reset_required_globals: unit -> unit
val get_required_globals: unit -> Ident.t list
val add_required_global: Ident.t -> unit
val has_local_constraints: t -> bool
val add_gadt_instance_level: int -> t -> t
val gadt_instance_level: t -> type_expr -> int option
val add_gadt_instances: t -> int -> type_expr list -> unit
val add_gadt_instance_chain: t -> int -> type_expr -> unit
(* Lookup by long identifiers *)
? loc is used to report ' deprecated module ' warnings
val lookup_value:
?loc:Location.t -> Longident.t -> t -> Path.t * value_description
val lookup_constructor:
?loc:Location.t -> Longident.t -> t -> constructor_description
val lookup_all_constructors:
?loc:Location.t ->
Longident.t -> t -> (constructor_description * (unit -> unit)) list
val lookup_label:
?loc:Location.t -> Longident.t -> t -> label_description
val lookup_all_labels:
?loc:Location.t ->
Longident.t -> t -> (label_description * (unit -> unit)) list
val lookup_type:
?loc:Location.t -> Longident.t -> t -> Path.t
Since 4.04 , this function no longer returns [ type_description ] .
To obtain it , you should either call [ Env.find_type ] , or replace
it by [ Typetexp.find_type ]
To obtain it, you should either call [Env.find_type], or replace
it by [Typetexp.find_type] *)
val lookup_module:
load:bool -> ?loc:Location.t -> Longident.t -> t -> Path.t
val lookup_modtype:
?loc:Location.t -> Longident.t -> t -> Path.t * modtype_declaration
val lookup_class:
?loc:Location.t -> Longident.t -> t -> Path.t * class_declaration
val lookup_cltype:
?loc:Location.t -> Longident.t -> t -> Path.t * class_type_declaration
val copy_types: string list -> t -> t
Used only in .
exception Recmodule
Raise by lookup_module when the identifier refers
to one of the modules of a recursive definition
during the computation of its approximation ( see # 5965 ) .
to one of the modules of a recursive definition
during the computation of its approximation (see #5965). *)
(* Insertion by identifier *)
val add_value:
?check:(string -> Warnings.t) -> Ident.t -> value_description -> t -> t
val add_type: check:bool -> Ident.t -> type_declaration -> t -> t
val add_extension: check:bool -> Ident.t -> extension_constructor -> t -> t
val add_module: ?arg:bool -> Ident.t -> module_type -> t -> t
val add_module_declaration: ?arg:bool -> check:bool -> Ident.t ->
module_declaration -> t -> t
val add_modtype: Ident.t -> modtype_declaration -> t -> t
val add_class: Ident.t -> class_declaration -> t -> t
val add_cltype: Ident.t -> class_type_declaration -> t -> t
val add_local_constraint: Path.t -> type_declaration -> int -> t -> t
val add_local_type: Path.t -> type_declaration -> t -> t
(* Insertion of all fields of a signature. *)
val add_item: signature_item -> t -> t
val add_signature: signature -> t -> t
(* Insertion of all fields of a signature, relative to the given path.
Used to implement open. Returns None if the path refers to a functor,
not a structure. *)
val open_signature:
?used_slot:bool ref ->
?loc:Location.t -> ?toplevel:bool -> Asttypes.override_flag -> Path.t ->
t -> t option
val open_pers_signature: string -> t -> t
(* Insertion by name *)
val enter_value:
?check:(string -> Warnings.t) ->
string -> value_description -> t -> Ident.t * t
val enter_type: string -> type_declaration -> t -> Ident.t * t
val enter_extension: string -> extension_constructor -> t -> Ident.t * t
val enter_module: ?arg:bool -> string -> module_type -> t -> Ident.t * t
val enter_module_declaration:
?arg:bool -> Ident.t -> module_declaration -> t -> t
val enter_modtype: string -> modtype_declaration -> t -> Ident.t * t
val enter_class: string -> class_declaration -> t -> Ident.t * t
val enter_cltype: string -> class_type_declaration -> t -> Ident.t * t
Initialize the cache of in - core module interfaces .
val reset_cache: unit -> unit
(* To be called before each toplevel phrase. *)
val reset_cache_toplevel: unit -> unit
(* Remember the name of the current compilation unit. *)
val set_unit_name: string -> unit
val get_unit_name: unit -> string
(* Read, save a signature to/from a file *)
val read_signature: string -> string -> signature
(* Arguments: module name, file name. Results: signature. *)
val save_signature:
deprecated:string option -> signature -> string -> string -> Cmi_format.cmi_infos
(* Arguments: signature, module name, file name. *)
val save_signature_with_imports:
deprecated:string option ->
signature -> string -> string -> (string * Digest.t option) list
-> Cmi_format.cmi_infos
Arguments : signature , module name , file name ,
imported units with their CRCs .
imported units with their CRCs. *)
Return the CRC of the interface of the given compilation unit
val crc_of_unit: string -> Digest.t
Return the set of compilation units imported , with their CRC
val imports: unit -> (string * Digest.t option) list
(* [is_imported_opaque md] returns true if [md] is an opaque imported module *)
val is_imported_opaque: string -> bool
Direct access to the table of imported compilation units with their CRC
val crc_units: Consistbl.t
val add_import: string -> unit
(* Summaries -- compact representation of an environment, to be
exported in debugging information. *)
val summary: t -> summary
Return an equivalent environment where all fields have been reset ,
except the summary . The initial environment can be rebuilt from the
summary , using Envaux.env_of_only_summary .
except the summary. The initial environment can be rebuilt from the
summary, using Envaux.env_of_only_summary. *)
val keep_only_summary : t -> t
val env_of_only_summary : (summary -> Subst.t -> t) -> t -> t
(* Error report *)
type error =
| Illegal_renaming of string * string * string
| Inconsistent_import of string * string * string
| Need_recursive_types of string * string
| Depend_on_unsafe_string_unit of string * string
| Missing_module of Location.t * Path.t * Path.t
| Illegal_value_name of Location.t * string
exception Error of error
open Format
val report_error: formatter -> error -> unit
val mark_value_used: t -> string -> value_description -> unit
val mark_module_used: t -> string -> Location.t -> unit
val mark_type_used: t -> string -> type_declaration -> unit
type constructor_usage = Positive | Pattern | Privatize
val mark_constructor_used:
constructor_usage -> t -> string -> type_declaration -> string -> unit
val mark_constructor:
constructor_usage -> t -> string -> constructor_description -> unit
val mark_extension_used:
constructor_usage -> t -> extension_constructor -> string -> unit
val in_signature: bool -> t -> t
val implicit_coercion: t -> t
val is_in_signature: t -> bool
val set_value_used_callback:
string -> value_description -> (unit -> unit) -> unit
val set_type_used_callback:
string -> type_declaration -> ((unit -> unit) -> unit) -> unit
Forward declaration to break mutual recursion with .
val check_modtype_inclusion:
(loc:Location.t -> t -> module_type -> Path.t -> module_type -> unit) ref
Forward declaration to break mutual recursion with .
val add_delayed_check_forward: ((unit -> unit) -> unit) ref
Forward declaration to break mutual recursion with Mtype .
val strengthen:
(aliasable:bool -> t -> module_type -> Path.t -> module_type) ref
Forward declaration to break mutual recursion with Ctype .
val same_constr: (t -> type_expr -> type_expr -> bool) ref
(** Folding over all identifiers (for analysis purpose) *)
val fold_values:
(string -> Path.t -> value_description -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_types:
(string -> Path.t -> type_declaration * type_descriptions -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_constructors:
(constructor_description -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_labels:
(label_description -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
(** Persistent structures are only traversed if they are already loaded. *)
val fold_modules:
(string -> Path.t -> module_declaration -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_modtypes:
(string -> Path.t -> modtype_declaration -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_classs:
(string -> Path.t -> class_declaration -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_cltypes:
(string -> Path.t -> class_type_declaration -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
(** Utilities *)
val scrape_alias: t -> module_type -> module_type
val check_value_name: string -> Location.t -> unit
module Persistent_signature : sig
type t =
{ filename : string; (** Name of the file containing the signature. *)
cmi : Cmi_format.cmi_infos }
* Function used to load a persistent signature . The default is to look for
the file in the load path . This function can be overridden to load
it from memory , for instance to build a self - contained toplevel .
the .cmi file in the load path. This function can be overridden to load
it from memory, for instance to build a self-contained toplevel. *)
val load : (unit_name:string -> t option) ref
end
| null | https://raw.githubusercontent.com/sadiqj/ocaml-esp32/33aad4ca2becb9701eb90d779c1b1183aefeb578/typing/env.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Environment handling
For short-paths
Lookup by paths
Find the manifest type information associated to a type for the sake
of the compiler's type-based optimisations.
Normalize the path to a concrete value or module.
If the option is None, allow returning dangling paths.
Otherwise raise a Missing_module error, and may add forgotten
head as required global.
Only normalize the prefix part of the path
Lookup by long identifiers
Insertion by identifier
Insertion of all fields of a signature.
Insertion of all fields of a signature, relative to the given path.
Used to implement open. Returns None if the path refers to a functor,
not a structure.
Insertion by name
To be called before each toplevel phrase.
Remember the name of the current compilation unit.
Read, save a signature to/from a file
Arguments: module name, file name. Results: signature.
Arguments: signature, module name, file name.
[is_imported_opaque md] returns true if [md] is an opaque imported module
Summaries -- compact representation of an environment, to be
exported in debugging information.
Error report
* Folding over all identifiers (for analysis purpose)
* Persistent structures are only traversed if they are already loaded.
* Utilities
* Name of the file containing the signature. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Types
module PathMap : Map.S with type key = Path.t
and type 'a t = 'a Map.Make(Path).t
type summary =
Env_empty
| Env_value of summary * Ident.t * value_description
| Env_type of summary * Ident.t * type_declaration
| Env_extension of summary * Ident.t * extension_constructor
| Env_module of summary * Ident.t * module_declaration
| Env_modtype of summary * Ident.t * modtype_declaration
| Env_class of summary * Ident.t * class_declaration
| Env_cltype of summary * Ident.t * class_type_declaration
| Env_open of summary * Path.t
| Env_functor_arg of summary * Ident.t
| Env_constraints of summary * type_declaration PathMap.t
| Env_copy_types of summary * string list
type t
val empty: t
val initial_safe_string: t
val initial_unsafe_string: t
val diff: t -> t -> Ident.t list
val copy_local: from:t -> t -> t
type type_descriptions =
constructor_description list * label_description list
type iter_cont
val iter_types:
(Path.t -> Path.t * (type_declaration * type_descriptions) -> unit) ->
t -> iter_cont
val run_iter_cont: iter_cont list -> (Path.t * iter_cont) list
val same_types: t -> t -> bool
val used_persistent: unit -> Concr.t
val find_shadowed_types: Path.t -> t -> Path.t list
val without_cmis: ('a -> 'b) -> 'a -> 'b
[ without_cmis f arg ] applies [ f ] to [ arg ] , but does not
allow opening cmis during its execution
allow opening cmis during its execution *)
val find_value: Path.t -> t -> value_description
val find_type: Path.t -> t -> type_declaration
val find_type_descrs: Path.t -> t -> type_descriptions
val find_module: Path.t -> t -> module_declaration
val find_modtype: Path.t -> t -> modtype_declaration
val find_class: Path.t -> t -> class_declaration
val find_cltype: Path.t -> t -> class_type_declaration
val find_type_expansion:
Path.t -> t -> type_expr list * type_expr * int option
val find_type_expansion_opt:
Path.t -> t -> type_expr list * type_expr * int option
val find_modtype_expansion: Path.t -> t -> module_type
val add_functor_arg: Ident.t -> t -> t
val is_functor_arg: Path.t -> t -> bool
val normalize_path: Location.t option -> t -> Path.t -> Path.t
val normalize_path_prefix: Location.t option -> t -> Path.t -> Path.t
val reset_required_globals: unit -> unit
val get_required_globals: unit -> Ident.t list
val add_required_global: Ident.t -> unit
val has_local_constraints: t -> bool
val add_gadt_instance_level: int -> t -> t
val gadt_instance_level: t -> type_expr -> int option
val add_gadt_instances: t -> int -> type_expr list -> unit
val add_gadt_instance_chain: t -> int -> type_expr -> unit
? loc is used to report ' deprecated module ' warnings
val lookup_value:
?loc:Location.t -> Longident.t -> t -> Path.t * value_description
val lookup_constructor:
?loc:Location.t -> Longident.t -> t -> constructor_description
val lookup_all_constructors:
?loc:Location.t ->
Longident.t -> t -> (constructor_description * (unit -> unit)) list
val lookup_label:
?loc:Location.t -> Longident.t -> t -> label_description
val lookup_all_labels:
?loc:Location.t ->
Longident.t -> t -> (label_description * (unit -> unit)) list
val lookup_type:
?loc:Location.t -> Longident.t -> t -> Path.t
Since 4.04 , this function no longer returns [ type_description ] .
To obtain it , you should either call [ Env.find_type ] , or replace
it by [ Typetexp.find_type ]
To obtain it, you should either call [Env.find_type], or replace
it by [Typetexp.find_type] *)
val lookup_module:
load:bool -> ?loc:Location.t -> Longident.t -> t -> Path.t
val lookup_modtype:
?loc:Location.t -> Longident.t -> t -> Path.t * modtype_declaration
val lookup_class:
?loc:Location.t -> Longident.t -> t -> Path.t * class_declaration
val lookup_cltype:
?loc:Location.t -> Longident.t -> t -> Path.t * class_type_declaration
val copy_types: string list -> t -> t
Used only in .
exception Recmodule
Raise by lookup_module when the identifier refers
to one of the modules of a recursive definition
during the computation of its approximation ( see # 5965 ) .
to one of the modules of a recursive definition
during the computation of its approximation (see #5965). *)
val add_value:
?check:(string -> Warnings.t) -> Ident.t -> value_description -> t -> t
val add_type: check:bool -> Ident.t -> type_declaration -> t -> t
val add_extension: check:bool -> Ident.t -> extension_constructor -> t -> t
val add_module: ?arg:bool -> Ident.t -> module_type -> t -> t
val add_module_declaration: ?arg:bool -> check:bool -> Ident.t ->
module_declaration -> t -> t
val add_modtype: Ident.t -> modtype_declaration -> t -> t
val add_class: Ident.t -> class_declaration -> t -> t
val add_cltype: Ident.t -> class_type_declaration -> t -> t
val add_local_constraint: Path.t -> type_declaration -> int -> t -> t
val add_local_type: Path.t -> type_declaration -> t -> t
val add_item: signature_item -> t -> t
val add_signature: signature -> t -> t
val open_signature:
?used_slot:bool ref ->
?loc:Location.t -> ?toplevel:bool -> Asttypes.override_flag -> Path.t ->
t -> t option
val open_pers_signature: string -> t -> t
val enter_value:
?check:(string -> Warnings.t) ->
string -> value_description -> t -> Ident.t * t
val enter_type: string -> type_declaration -> t -> Ident.t * t
val enter_extension: string -> extension_constructor -> t -> Ident.t * t
val enter_module: ?arg:bool -> string -> module_type -> t -> Ident.t * t
val enter_module_declaration:
?arg:bool -> Ident.t -> module_declaration -> t -> t
val enter_modtype: string -> modtype_declaration -> t -> Ident.t * t
val enter_class: string -> class_declaration -> t -> Ident.t * t
val enter_cltype: string -> class_type_declaration -> t -> Ident.t * t
Initialize the cache of in - core module interfaces .
val reset_cache: unit -> unit
val reset_cache_toplevel: unit -> unit
val set_unit_name: string -> unit
val get_unit_name: unit -> string
val read_signature: string -> string -> signature
val save_signature:
deprecated:string option -> signature -> string -> string -> Cmi_format.cmi_infos
val save_signature_with_imports:
deprecated:string option ->
signature -> string -> string -> (string * Digest.t option) list
-> Cmi_format.cmi_infos
Arguments : signature , module name , file name ,
imported units with their CRCs .
imported units with their CRCs. *)
Return the CRC of the interface of the given compilation unit
val crc_of_unit: string -> Digest.t
Return the set of compilation units imported , with their CRC
val imports: unit -> (string * Digest.t option) list
val is_imported_opaque: string -> bool
Direct access to the table of imported compilation units with their CRC
val crc_units: Consistbl.t
val add_import: string -> unit
val summary: t -> summary
Return an equivalent environment where all fields have been reset ,
except the summary . The initial environment can be rebuilt from the
summary , using Envaux.env_of_only_summary .
except the summary. The initial environment can be rebuilt from the
summary, using Envaux.env_of_only_summary. *)
val keep_only_summary : t -> t
val env_of_only_summary : (summary -> Subst.t -> t) -> t -> t
type error =
| Illegal_renaming of string * string * string
| Inconsistent_import of string * string * string
| Need_recursive_types of string * string
| Depend_on_unsafe_string_unit of string * string
| Missing_module of Location.t * Path.t * Path.t
| Illegal_value_name of Location.t * string
exception Error of error
open Format
val report_error: formatter -> error -> unit
val mark_value_used: t -> string -> value_description -> unit
val mark_module_used: t -> string -> Location.t -> unit
val mark_type_used: t -> string -> type_declaration -> unit
type constructor_usage = Positive | Pattern | Privatize
val mark_constructor_used:
constructor_usage -> t -> string -> type_declaration -> string -> unit
val mark_constructor:
constructor_usage -> t -> string -> constructor_description -> unit
val mark_extension_used:
constructor_usage -> t -> extension_constructor -> string -> unit
val in_signature: bool -> t -> t
val implicit_coercion: t -> t
val is_in_signature: t -> bool
val set_value_used_callback:
string -> value_description -> (unit -> unit) -> unit
val set_type_used_callback:
string -> type_declaration -> ((unit -> unit) -> unit) -> unit
Forward declaration to break mutual recursion with .
val check_modtype_inclusion:
(loc:Location.t -> t -> module_type -> Path.t -> module_type -> unit) ref
Forward declaration to break mutual recursion with .
val add_delayed_check_forward: ((unit -> unit) -> unit) ref
Forward declaration to break mutual recursion with Mtype .
val strengthen:
(aliasable:bool -> t -> module_type -> Path.t -> module_type) ref
Forward declaration to break mutual recursion with Ctype .
val same_constr: (t -> type_expr -> type_expr -> bool) ref
val fold_values:
(string -> Path.t -> value_description -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_types:
(string -> Path.t -> type_declaration * type_descriptions -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_constructors:
(constructor_description -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_labels:
(label_description -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_modules:
(string -> Path.t -> module_declaration -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_modtypes:
(string -> Path.t -> modtype_declaration -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_classs:
(string -> Path.t -> class_declaration -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val fold_cltypes:
(string -> Path.t -> class_type_declaration -> 'a -> 'a) ->
Longident.t option -> t -> 'a -> 'a
val scrape_alias: t -> module_type -> module_type
val check_value_name: string -> Location.t -> unit
module Persistent_signature : sig
type t =
cmi : Cmi_format.cmi_infos }
* Function used to load a persistent signature . The default is to look for
the file in the load path . This function can be overridden to load
it from memory , for instance to build a self - contained toplevel .
the .cmi file in the load path. This function can be overridden to load
it from memory, for instance to build a self-contained toplevel. *)
val load : (unit_name:string -> t option) ref
end
|
68a21d40fc303e7d8377b9013eaee94b86498671c7bc1a2b8766a398bb4b9f61 | scrintal/heroicons-reagent | bars_2.cljs | (ns com.scrintal.heroicons.mini.bars-2)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 20 20"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M2 6.75A.75.75 0 012.75 6h14.5a.75.75 0 010 1.5H2.75A.75.75 0 012 6.75zm0 6.5a.75.75 0 01.75-.75h14.5a.75.75 0 010 1.5H2.75a.75.75 0 01-.75-.75z"
:clipRule "evenodd"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/mini/bars_2.cljs | clojure | (ns com.scrintal.heroicons.mini.bars-2)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 20 20"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M2 6.75A.75.75 0 012.75 6h14.5a.75.75 0 010 1.5H2.75A.75.75 0 012 6.75zm0 6.5a.75.75 0 01.75-.75h14.5a.75.75 0 010 1.5H2.75a.75.75 0 01-.75-.75z"
:clipRule "evenodd"}]]) |
|
9eb410f944325c11117d32a3fa823302f2065428cf360a8366e04e1f0df5ac7e | scrive/hpqtypes | Catalog.hs | # LANGUAGE FlexibleContexts , OverloadedStrings , RecordWildCards
, ScopedTypeVariables , TypeFamilies #
, ScopedTypeVariables, TypeFamilies #-}
# OPTIONS_GHC -Wall #
import Control.Arrow (second)
import Control.Monad
import Control.Monad.Base
import Control.Monad.Catch
import Data.Function
import Data.Int
import Data.Monoid
import Data.Monoid.Utils
import Database.PostgreSQL.PQTypes
import Database.PostgreSQL.PQTypes.Internal.Utils (mread)
import System.Console.Readline
import System.Environment
import qualified Data.ByteString.Char8 as BS
-- | Generic 'putStrLn'.
printLn :: MonadBase IO m => String -> m ()
printLn = liftBase . putStrLn
-- | Get connection string from command line argument.
getConnSettings :: IO ConnectionSettings
getConnSettings = do
args <- getArgs
case args of
[conninfo] -> return def { csConnInfo = BS.pack conninfo }
_ -> do
prog <- getProgName
error $ "Usage:" <+> prog <+> "<connection info>"
----------------------------------------
-- | Representation of a book.
data Book = Book
{ bookID :: Int64
, bookName :: String
, bookYear :: Int32
} deriving (Read, Show)
-- | Intermediate representation of 'Book'.
type instance CompositeRow Book = (Int64, String, Int32)
instance PQFormat Book where
pqFormat = "%book_"
instance CompositeFromSQL Book where
toComposite (bid, name, year) = Book {
bookID = bid
, bookName = name
, bookYear = year
}
withCatalog :: ConnectionSettings -> IO () -> IO ()
withCatalog cs = bracket_ createStructure dropStructure
where
-- | Create needed tables and types.
createStructure = runDBT (simpleSource cs) def $ do
printLn "Creating tables..."
runSQL_ $ mconcat [
"CREATE TABLE authors_ ("
, " id BIGSERIAL NOT NULL"
, ", name TEXT NOT NULL"
, ", PRIMARY KEY (id)"
, ")"
]
runSQL_ $ mconcat [
"CREATE TABLE books_ ("
, " id BIGSERIAL NOT NULL"
, ", name TEXT NOT NULL"
, ", year INTEGER NOT NULL"
, ", author_id BIGINT NOT NULL"
, ", PRIMARY KEY (id)"
, ", FOREIGN KEY (author_id) REFERENCES authors_ (id)"
, ")"
]
runSQL_ $ mconcat [
"CREATE TYPE book_ AS ("
, " id BIGINT"
, ", name TEXT"
, ", year INTEGER"
, ")"
]
-- | Drop previously created database structures.
dropStructure = runDBT (simpleSource cs) def $ do
printLn "Dropping tables..."
runSQL_ "DROP TYPE book_"
runSQL_ "DROP TABLE books_"
runSQL_ "DROP TABLE authors_"
----------------------------------------
processCommand :: ConnectionSource -> String -> IO ()
processCommand cs cmd = case parse cmd of
-- | Display authors.
("authors", "") -> runDBT cs def $ do
runSQL_ "SELECT * FROM authors_ ORDER BY name"
mapDB_ $ \(aid::Int64, name) -> printLn $ show aid <> ":" <+> name
-- | Display books.
("books", "") -> runDBT cs def $ do
runSQL_ "SELECT a.name, ARRAY(SELECT (b.id, b.name, b.year)::book_ FROM books_ b WHERE b.author_id = a.id) FROM authors_ a ORDER BY a.name"
mapDB_ $ \(author, CompositeArray1 (books::[Book])) -> do
printLn $ author <> ":"
forM_ books $ \book -> printLn $ "*" <+> show book
-- | Insert an author.
("insert_author", mname) -> case mread mname of
Just (name::String) -> runDBT cs def . runQuery_ $
"INSERT INTO authors_ (name) VALUES (" <?> name <+> ")"
Nothing -> printLn $ "Invalid name"
-- | Insert a book.
("insert_book", mbook) -> case mread mbook of
Just record -> runDBT cs def . runQuery_ $ rawSQL
"INSERT INTO books_ (name, year, author_id) VALUES ($1, $2, $3)"
(record::(String, Int32, Int64))
Nothing -> printLn $ "Invalid book record"
-- | Handle unknown commands.
_ -> printLn $ "Unknown command:" <+> cmd
where
parse = second (drop 1) . break (==' ')
-- | Example chain of commands:
--
> insert_author " "
> insert_author " "
-- > authors
> insert_book ( " The Sunset " , 2006 , 1 )
> insert_book ( " Waterfall " , 2011 , 2 )
> insert_book ( " The Sunrise " , 2013 , 1 )
-- > books
--
-- If you want to check out exceptions in action,
-- try inserting a book with invalid author id.
main :: IO ()
main = do
cs <- getConnSettings
withCatalog cs $ do
pool <- poolSource (cs { csComposites = ["book_"] }) 1 10 4
fix $ \next -> readline "> " >>= maybe (printLn "") (\cmd -> do
when (cmd /= "quit") $ do
processCommand pool cmd
addHistory cmd
next
)
| null | https://raw.githubusercontent.com/scrive/hpqtypes/5b652645d5fdebbec8dbd1a68583fbcb8dfe5d93/examples/Catalog.hs | haskell | | Generic 'putStrLn'.
| Get connection string from command line argument.
--------------------------------------
| Representation of a book.
| Intermediate representation of 'Book'.
| Create needed tables and types.
| Drop previously created database structures.
--------------------------------------
| Display authors.
| Display books.
| Insert an author.
| Insert a book.
| Handle unknown commands.
| Example chain of commands:
> authors
> books
If you want to check out exceptions in action,
try inserting a book with invalid author id. | # LANGUAGE FlexibleContexts , OverloadedStrings , RecordWildCards
, ScopedTypeVariables , TypeFamilies #
, ScopedTypeVariables, TypeFamilies #-}
# OPTIONS_GHC -Wall #
import Control.Arrow (second)
import Control.Monad
import Control.Monad.Base
import Control.Monad.Catch
import Data.Function
import Data.Int
import Data.Monoid
import Data.Monoid.Utils
import Database.PostgreSQL.PQTypes
import Database.PostgreSQL.PQTypes.Internal.Utils (mread)
import System.Console.Readline
import System.Environment
import qualified Data.ByteString.Char8 as BS
printLn :: MonadBase IO m => String -> m ()
printLn = liftBase . putStrLn
getConnSettings :: IO ConnectionSettings
getConnSettings = do
args <- getArgs
case args of
[conninfo] -> return def { csConnInfo = BS.pack conninfo }
_ -> do
prog <- getProgName
error $ "Usage:" <+> prog <+> "<connection info>"
data Book = Book
{ bookID :: Int64
, bookName :: String
, bookYear :: Int32
} deriving (Read, Show)
type instance CompositeRow Book = (Int64, String, Int32)
instance PQFormat Book where
pqFormat = "%book_"
instance CompositeFromSQL Book where
toComposite (bid, name, year) = Book {
bookID = bid
, bookName = name
, bookYear = year
}
withCatalog :: ConnectionSettings -> IO () -> IO ()
withCatalog cs = bracket_ createStructure dropStructure
where
createStructure = runDBT (simpleSource cs) def $ do
printLn "Creating tables..."
runSQL_ $ mconcat [
"CREATE TABLE authors_ ("
, " id BIGSERIAL NOT NULL"
, ", name TEXT NOT NULL"
, ", PRIMARY KEY (id)"
, ")"
]
runSQL_ $ mconcat [
"CREATE TABLE books_ ("
, " id BIGSERIAL NOT NULL"
, ", name TEXT NOT NULL"
, ", year INTEGER NOT NULL"
, ", author_id BIGINT NOT NULL"
, ", PRIMARY KEY (id)"
, ", FOREIGN KEY (author_id) REFERENCES authors_ (id)"
, ")"
]
runSQL_ $ mconcat [
"CREATE TYPE book_ AS ("
, " id BIGINT"
, ", name TEXT"
, ", year INTEGER"
, ")"
]
dropStructure = runDBT (simpleSource cs) def $ do
printLn "Dropping tables..."
runSQL_ "DROP TYPE book_"
runSQL_ "DROP TABLE books_"
runSQL_ "DROP TABLE authors_"
processCommand :: ConnectionSource -> String -> IO ()
processCommand cs cmd = case parse cmd of
("authors", "") -> runDBT cs def $ do
runSQL_ "SELECT * FROM authors_ ORDER BY name"
mapDB_ $ \(aid::Int64, name) -> printLn $ show aid <> ":" <+> name
("books", "") -> runDBT cs def $ do
runSQL_ "SELECT a.name, ARRAY(SELECT (b.id, b.name, b.year)::book_ FROM books_ b WHERE b.author_id = a.id) FROM authors_ a ORDER BY a.name"
mapDB_ $ \(author, CompositeArray1 (books::[Book])) -> do
printLn $ author <> ":"
forM_ books $ \book -> printLn $ "*" <+> show book
("insert_author", mname) -> case mread mname of
Just (name::String) -> runDBT cs def . runQuery_ $
"INSERT INTO authors_ (name) VALUES (" <?> name <+> ")"
Nothing -> printLn $ "Invalid name"
("insert_book", mbook) -> case mread mbook of
Just record -> runDBT cs def . runQuery_ $ rawSQL
"INSERT INTO books_ (name, year, author_id) VALUES ($1, $2, $3)"
(record::(String, Int32, Int64))
Nothing -> printLn $ "Invalid book record"
_ -> printLn $ "Unknown command:" <+> cmd
where
parse = second (drop 1) . break (==' ')
> insert_author " "
> insert_author " "
> insert_book ( " The Sunset " , 2006 , 1 )
> insert_book ( " Waterfall " , 2011 , 2 )
> insert_book ( " The Sunrise " , 2013 , 1 )
main :: IO ()
main = do
cs <- getConnSettings
withCatalog cs $ do
pool <- poolSource (cs { csComposites = ["book_"] }) 1 10 4
fix $ \next -> readline "> " >>= maybe (printLn "") (\cmd -> do
when (cmd /= "quit") $ do
processCommand pool cmd
addHistory cmd
next
)
|
8ba4bb87bb02bc7b152249445d739a2249809ef2511661fc52c840fbbbe3158a | threatgrid/ctia | core.clj | (ns ctia.schemas.core)
(defmacro def-acl-schema [name-sym ddl spec-kw-ns]
`(do
~ddl
~spec-kw-ns
(def ~name-sym)))
(defmacro def-stored-schema [name-sym _sch]
`(def ~name-sym))
(defmacro def-advanced-acl-schema [{:keys [name-sym
ddl
_spec-kw-ns
_open?]}]
`(do
~ddl
(def ~name-sym)))
| null | https://raw.githubusercontent.com/threatgrid/ctia/4d42a63f472490f36814c1855faf50beb45c75ba/.clj-kondo/ctia/schemas/core.clj | clojure | (ns ctia.schemas.core)
(defmacro def-acl-schema [name-sym ddl spec-kw-ns]
`(do
~ddl
~spec-kw-ns
(def ~name-sym)))
(defmacro def-stored-schema [name-sym _sch]
`(def ~name-sym))
(defmacro def-advanced-acl-schema [{:keys [name-sym
ddl
_spec-kw-ns
_open?]}]
`(do
~ddl
(def ~name-sym)))
|
|
3fabba57f46fcca2a8dba1dccde48cf650a61187d6da455fd1c487003a8d47ea | tibbe/event | Thread.hs | # LANGUAGE BangPatterns , ForeignFunctionInterface , NoImplicitPrelude #
module System.Event.Thread
(
ensureIOManagerIsRunning
, threadWaitRead
, threadWaitWrite
, threadDelay
, registerDelay
) where
import Control.Concurrent.MVar (modifyMVar_)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import GHC.Base
import GHC.Conc (TVar, ThreadId, ThreadStatus(..), atomically, forkIO,
labelThread, newTVar, threadStatus, writeTVar)
import qualified GHC.Conc as Conc
import GHC.MVar (MVar, newEmptyMVar, newMVar, putMVar, takeMVar)
import GHC.Num (fromInteger)
import GHC.Real (div)
import System.Event.Manager (Event, EventManager, evtRead, evtWrite, loop,
new, registerFd, unregisterFd_, registerTimeout)
import System.IO.Unsafe (unsafePerformIO)
import System.Posix.Types (Fd)
-- | Suspends the current thread for a given number of microseconds
( GHC only ) .
--
-- There is no guarantee that the thread will be rescheduled promptly
-- when the delay has expired, but the thread will never continue to
-- run /earlier/ than specified.
threadDelay :: Int -> IO ()
threadDelay time
| threaded = waitForDelayEvent time
| otherwise = Conc.threadDelay time
waitForDelayEvent :: Int -> IO ()
waitForDelayEvent usecs = do
Running mgr <- readIORef eventManager
m <- newEmptyMVar
_ <- registerTimeout mgr (usecs `div` 1000) (putMVar m ())
takeMVar m
| Set the value of returned TVar to True after a given number of
-- microseconds. The caveats associated with threadDelay also apply.
--
registerDelay :: Int -> IO (TVar Bool)
registerDelay usecs
| threaded = waitForDelayEventSTM usecs
| otherwise = error "registerDelay: requires -threaded"
waitForDelayEventSTM :: Int -> IO (TVar Bool)
waitForDelayEventSTM usecs = do
t <- atomically $ newTVar False
Running mgr <- readIORef eventManager
_ <- registerTimeout mgr (usecs `div` 1000) . atomically $ writeTVar t True
return t
-- | Block the current thread until data is available to read from the
-- given file descriptor.
threadWaitRead :: Fd -> IO ()
threadWaitRead fd
| threaded = threadWait evtRead fd
| otherwise = Conc.threadWaitRead fd
-- | Block the current thread until the given file descriptor can
-- accept data to write.
threadWaitWrite :: Fd -> IO ()
threadWaitWrite fd
| threaded = threadWait evtWrite fd
| otherwise = Conc.threadWaitWrite fd
data Managing a = None
| Running !a
threadWait :: Event -> Fd -> IO ()
threadWait evt fd = do
m <- newEmptyMVar
Running mgr <- readIORef eventManager
_ <- registerFd mgr (\reg _ -> unregisterFd_ mgr reg >> putMVar m ()) fd evt
takeMVar m
eventManager :: IORef (Managing EventManager)
eventManager = unsafePerformIO $ newIORef None
# NOINLINE eventManager #
ioManager :: MVar (Managing ThreadId)
ioManager = unsafePerformIO $ newMVar None
# NOINLINE ioManager #
ensureIOManagerIsRunning :: IO ()
ensureIOManagerIsRunning
| not threaded = return ()
| otherwise = modifyMVar_ ioManager $ \old -> do
maybeMgr <- readIORef eventManager
mgr <- case maybeMgr of
Running m -> return m
None -> do !m <- new
writeIORef eventManager $ Running m
return m
let create = do
!t <- forkIO $ loop mgr
labelThread t "IOManager"
return $ Running t
case old of
None -> create
st@(Running t) -> do
s <- threadStatus t
case s of
ThreadFinished -> create
ThreadDied -> create
_other -> return st
foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
| null | https://raw.githubusercontent.com/tibbe/event/2ca43e49327aa7854396b800ff4184d8b00a69f0/src/System/Event/Thread.hs | haskell | | Suspends the current thread for a given number of microseconds
There is no guarantee that the thread will be rescheduled promptly
when the delay has expired, but the thread will never continue to
run /earlier/ than specified.
microseconds. The caveats associated with threadDelay also apply.
| Block the current thread until data is available to read from the
given file descriptor.
| Block the current thread until the given file descriptor can
accept data to write. | # LANGUAGE BangPatterns , ForeignFunctionInterface , NoImplicitPrelude #
module System.Event.Thread
(
ensureIOManagerIsRunning
, threadWaitRead
, threadWaitWrite
, threadDelay
, registerDelay
) where
import Control.Concurrent.MVar (modifyMVar_)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import GHC.Base
import GHC.Conc (TVar, ThreadId, ThreadStatus(..), atomically, forkIO,
labelThread, newTVar, threadStatus, writeTVar)
import qualified GHC.Conc as Conc
import GHC.MVar (MVar, newEmptyMVar, newMVar, putMVar, takeMVar)
import GHC.Num (fromInteger)
import GHC.Real (div)
import System.Event.Manager (Event, EventManager, evtRead, evtWrite, loop,
new, registerFd, unregisterFd_, registerTimeout)
import System.IO.Unsafe (unsafePerformIO)
import System.Posix.Types (Fd)
( GHC only ) .
threadDelay :: Int -> IO ()
threadDelay time
| threaded = waitForDelayEvent time
| otherwise = Conc.threadDelay time
waitForDelayEvent :: Int -> IO ()
waitForDelayEvent usecs = do
Running mgr <- readIORef eventManager
m <- newEmptyMVar
_ <- registerTimeout mgr (usecs `div` 1000) (putMVar m ())
takeMVar m
| Set the value of returned TVar to True after a given number of
registerDelay :: Int -> IO (TVar Bool)
registerDelay usecs
| threaded = waitForDelayEventSTM usecs
| otherwise = error "registerDelay: requires -threaded"
waitForDelayEventSTM :: Int -> IO (TVar Bool)
waitForDelayEventSTM usecs = do
t <- atomically $ newTVar False
Running mgr <- readIORef eventManager
_ <- registerTimeout mgr (usecs `div` 1000) . atomically $ writeTVar t True
return t
threadWaitRead :: Fd -> IO ()
threadWaitRead fd
| threaded = threadWait evtRead fd
| otherwise = Conc.threadWaitRead fd
threadWaitWrite :: Fd -> IO ()
threadWaitWrite fd
| threaded = threadWait evtWrite fd
| otherwise = Conc.threadWaitWrite fd
data Managing a = None
| Running !a
threadWait :: Event -> Fd -> IO ()
threadWait evt fd = do
m <- newEmptyMVar
Running mgr <- readIORef eventManager
_ <- registerFd mgr (\reg _ -> unregisterFd_ mgr reg >> putMVar m ()) fd evt
takeMVar m
eventManager :: IORef (Managing EventManager)
eventManager = unsafePerformIO $ newIORef None
# NOINLINE eventManager #
ioManager :: MVar (Managing ThreadId)
ioManager = unsafePerformIO $ newMVar None
# NOINLINE ioManager #
ensureIOManagerIsRunning :: IO ()
ensureIOManagerIsRunning
| not threaded = return ()
| otherwise = modifyMVar_ ioManager $ \old -> do
maybeMgr <- readIORef eventManager
mgr <- case maybeMgr of
Running m -> return m
None -> do !m <- new
writeIORef eventManager $ Running m
return m
let create = do
!t <- forkIO $ loop mgr
labelThread t "IOManager"
return $ Running t
case old of
None -> create
st@(Running t) -> do
s <- threadStatus t
case s of
ThreadFinished -> create
ThreadDied -> create
_other -> return st
foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
|
0a666d2eed7e703484bb3277d6d06208c9ef00981b7e2a611e8fbdfb9063419d | eugeneia/erlangen | algorithms.lisp | Generic algorithms
(in-package :erlangen.algorithms)
(defun repeat-pace (function &key (delta 0.01) (maxsleep 0.1))
"Repeatedly call FUNCTION, but pace interval "
(loop with sleep = 0 for progress = (funcall function)
if progress do
(setf sleep 0)
else do
(setf sleep (max (+ sleep delta) maxsleep))
(sleep sleep)))
(let ((float-time-units (float internal-time-units-per-second)))
(defun now ()
(/ (get-internal-real-time) float-time-units)))
(defun repeat-rate (function &key (hz 1))
(let ((interval (/ 1 hz))
(start (now)))
(loop do
(funcall function)
(let* ((next (+ start interval))
(now (now))
(sleep (- next now)))
(when (> sleep 0)
(sleep sleep))
(setf start (max now next))))))
| null | https://raw.githubusercontent.com/eugeneia/erlangen/204166b33833c49841617bbc6ecfaf4dd77cf6d8/algorithms.lisp | lisp | Generic algorithms
(in-package :erlangen.algorithms)
(defun repeat-pace (function &key (delta 0.01) (maxsleep 0.1))
"Repeatedly call FUNCTION, but pace interval "
(loop with sleep = 0 for progress = (funcall function)
if progress do
(setf sleep 0)
else do
(setf sleep (max (+ sleep delta) maxsleep))
(sleep sleep)))
(let ((float-time-units (float internal-time-units-per-second)))
(defun now ()
(/ (get-internal-real-time) float-time-units)))
(defun repeat-rate (function &key (hz 1))
(let ((interval (/ 1 hz))
(start (now)))
(loop do
(funcall function)
(let* ((next (+ start interval))
(now (now))
(sleep (- next now)))
(when (> sleep 0)
(sleep sleep))
(setf start (max now next))))))
|
|
7fe5a94b3c9a0ce78e8deed9457c748a016efc781f878fdf9b90b4899e3242a4 | plum-umd/fundamentals | maze-data.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname maze-data) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define MAZE0
(list
(make-posn 0 0)
(make-posn 1 0)
(make-posn 2 0)
(make-posn 3 0)
(make-posn 4 0)
(make-posn 5 0)
(make-posn 6 0)
(make-posn 7 0)
(make-posn 8 0)
(make-posn 9 0)
(make-posn 10 0)
(make-posn 11 0)
(make-posn 12 0)
(make-posn 13 0)
(make-posn 14 0)
(make-posn 15 0)
(make-posn 16 0)
(make-posn 17 0)
(make-posn 18 0)
(make-posn 19 0)
(make-posn 20 0)
(make-posn 0 1)
(make-posn 10 1)
(make-posn 20 1)
(make-posn 0 2)
(make-posn 2 2)
(make-posn 3 2)
(make-posn 5 2)
(make-posn 6 2)
(make-posn 7 2)
(make-posn 8 2)
(make-posn 10 2)
(make-posn 12 2)
(make-posn 13 2)
(make-posn 14 2)
(make-posn 15 2)
(make-posn 17 2)
(make-posn 18 2)
(make-posn 20 2)
(make-posn 0 3)
(make-posn 2 3)
(make-posn 3 3)
(make-posn 5 3)
(make-posn 6 3)
(make-posn 7 3)
(make-posn 8 3)
(make-posn 10 3)
(make-posn 12 3)
(make-posn 13 3)
(make-posn 14 3)
(make-posn 15 3)
(make-posn 17 3)
(make-posn 18 3)
(make-posn 20 3)
(make-posn 0 4)
(make-posn 20 4)
(make-posn 0 5)
(make-posn 2 5)
(make-posn 3 5)
(make-posn 5 5)
(make-posn 7 5)
(make-posn 8 5)
(make-posn 9 5)
(make-posn 10 5)
(make-posn 11 5)
(make-posn 12 5)
(make-posn 13 5)
(make-posn 15 5)
(make-posn 17 5)
(make-posn 18 5)
(make-posn 20 5)
(make-posn 0 6)
(make-posn 5 6)
(make-posn 10 6)
(make-posn 15 6)
(make-posn 20 6)
(make-posn 0 7)
(make-posn 1 7)
(make-posn 2 7)
(make-posn 3 7)
(make-posn 5 7)
(make-posn 6 7)
(make-posn 7 7)
(make-posn 8 7)
(make-posn 10 7)
(make-posn 12 7)
(make-posn 13 7)
(make-posn 14 7)
(make-posn 15 7)
(make-posn 17 7)
(make-posn 18 7)
(make-posn 19 7)
(make-posn 20 7)
(make-posn 0 8)
(make-posn 1 8)
(make-posn 2 8)
(make-posn 3 8)
(make-posn 5 8)
(make-posn 15 8)
(make-posn 17 8)
(make-posn 18 8)
(make-posn 19 8)
(make-posn 20 8)
(make-posn 0 9)
(make-posn 1 9)
(make-posn 2 9)
(make-posn 3 9)
(make-posn 5 9)
(make-posn 7 9)
(make-posn 8 9)
(make-posn 9 9)
(make-posn 10 9)
(make-posn 11 9)
(make-posn 12 9)
(make-posn 13 9)
(make-posn 15 9)
(make-posn 17 9)
(make-posn 18 9)
(make-posn 19 9)
(make-posn 20 9)
(make-posn 7 10)
(make-posn 8 10)
(make-posn 9 10)
(make-posn 10 10)
(make-posn 11 10)
(make-posn 12 10)
(make-posn 13 10)
(make-posn 0 11)
(make-posn 1 11)
(make-posn 2 11)
(make-posn 3 11)
(make-posn 5 11)
(make-posn 7 11)
(make-posn 8 11)
(make-posn 9 11)
(make-posn 10 11)
(make-posn 11 11)
(make-posn 12 11)
(make-posn 13 11)
(make-posn 15 11)
(make-posn 17 11)
(make-posn 18 11)
(make-posn 19 11)
(make-posn 20 11)
(make-posn 0 12)
(make-posn 1 12)
(make-posn 2 12)
(make-posn 3 12)
(make-posn 5 12)
(make-posn 15 12)
(make-posn 17 12)
(make-posn 18 12)
(make-posn 19 12)
(make-posn 20 12)
(make-posn 0 13)
(make-posn 1 13)
(make-posn 2 13)
(make-posn 3 13)
(make-posn 5 13)
(make-posn 7 13)
(make-posn 8 13)
(make-posn 9 13)
(make-posn 10 13)
(make-posn 11 13)
(make-posn 12 13)
(make-posn 13 13)
(make-posn 15 13)
(make-posn 17 13)
(make-posn 18 13)
(make-posn 19 13)
(make-posn 20 13)
(make-posn 0 14)
(make-posn 10 14)
(make-posn 20 14)
(make-posn 0 15)
(make-posn 2 15)
(make-posn 3 15)
(make-posn 5 15)
(make-posn 6 15)
(make-posn 7 15)
(make-posn 8 15)
(make-posn 10 15)
(make-posn 12 15)
(make-posn 13 15)
(make-posn 14 15)
(make-posn 15 15)
(make-posn 17 15)
(make-posn 18 15)
(make-posn 20 15)
(make-posn 0 16)
(make-posn 3 16)
(make-posn 17 16)
(make-posn 20 16)
(make-posn 0 17)
(make-posn 1 17)
(make-posn 3 17)
(make-posn 5 17)
(make-posn 7 17)
(make-posn 8 17)
(make-posn 9 17)
(make-posn 10 17)
(make-posn 11 17)
(make-posn 12 17)
(make-posn 13 17)
(make-posn 15 17)
(make-posn 17 17)
(make-posn 19 17)
(make-posn 20 17)
(make-posn 0 18)
(make-posn 5 18)
(make-posn 10 18)
(make-posn 15 18)
(make-posn 20 18)
(make-posn 0 19)
(make-posn 2 19)
(make-posn 3 19)
(make-posn 4 19)
(make-posn 5 19)
(make-posn 6 19)
(make-posn 7 19)
(make-posn 8 19)
(make-posn 10 19)
(make-posn 12 19)
(make-posn 13 19)
(make-posn 14 19)
(make-posn 15 19)
(make-posn 16 19)
(make-posn 17 19)
(make-posn 18 19)
(make-posn 20 19)
(make-posn 0 20)
(make-posn 20 20)
(make-posn 0 21)
(make-posn 1 21)
(make-posn 2 21)
(make-posn 3 21)
(make-posn 4 21)
(make-posn 5 21)
(make-posn 6 21)
(make-posn 7 21)
(make-posn 8 21)
(make-posn 9 21)
(make-posn 10 21)
(make-posn 11 21)
(make-posn 12 21)
(make-posn 13 21)
(make-posn 14 21)
(make-posn 15 21)
(make-posn 16 21)
(make-posn 17 21)
(make-posn 18 21)
(make-posn 19 21)
(make-posn 20 21)))
(define DOTS0
(list
(make-posn 1 1)
(make-posn 2 1)
(make-posn 3 1)
(make-posn 4 1)
(make-posn 5 1)
(make-posn 6 1)
(make-posn 7 1)
(make-posn 8 1)
(make-posn 9 1)
(make-posn 11 1)
(make-posn 12 1)
(make-posn 13 1)
(make-posn 14 1)
(make-posn 15 1)
(make-posn 16 1)
(make-posn 17 1)
(make-posn 18 1)
(make-posn 19 1)
(make-posn 4 2)
(make-posn 9 2)
(make-posn 11 2)
(make-posn 16 2)
(make-posn 1 3)
(make-posn 4 3)
(make-posn 9 3)
(make-posn 11 3)
(make-posn 16 3)
(make-posn 19 3)
(make-posn 1 4)
(make-posn 2 4)
(make-posn 3 4)
(make-posn 4 4)
(make-posn 5 4)
(make-posn 6 4)
(make-posn 7 4)
(make-posn 8 4)
(make-posn 9 4)
(make-posn 10 4)
(make-posn 11 4)
(make-posn 12 4)
(make-posn 13 4)
(make-posn 14 4)
(make-posn 15 4)
(make-posn 16 4)
(make-posn 17 4)
(make-posn 18 4)
(make-posn 19 4)
(make-posn 1 5)
(make-posn 4 5)
(make-posn 6 5)
(make-posn 14 5)
(make-posn 16 5)
(make-posn 19 5)
(make-posn 1 6)
(make-posn 2 6)
(make-posn 3 6)
(make-posn 4 6)
(make-posn 6 6)
(make-posn 7 6)
(make-posn 8 6)
(make-posn 9 6)
(make-posn 11 6)
(make-posn 12 6)
(make-posn 13 6)
(make-posn 14 6)
(make-posn 16 6)
(make-posn 17 6)
(make-posn 18 6)
(make-posn 19 6)
(make-posn 4 7)
(make-posn 9 7)
(make-posn 11 7)
(make-posn 16 7)
(make-posn 4 8)
(make-posn 6 8)
(make-posn 7 8)
(make-posn 8 8)
(make-posn 9 8)
(make-posn 10 8)
(make-posn 11 8)
(make-posn 12 8)
(make-posn 13 8)
(make-posn 14 8)
(make-posn 16 8)
(make-posn 4 9)
(make-posn 6 9)
(make-posn 14 9)
(make-posn 16 9)
(make-posn 0 10)
(make-posn 1 10)
(make-posn 2 10)
(make-posn 3 10)
(make-posn 4 10)
(make-posn 5 10)
(make-posn 6 10)
(make-posn 14 10)
(make-posn 15 10)
(make-posn 16 10)
(make-posn 17 10)
(make-posn 18 10)
(make-posn 19 10)
(make-posn 20 10)
(make-posn 4 11)
(make-posn 6 11)
(make-posn 14 11)
(make-posn 16 11)
(make-posn 4 12)
(make-posn 6 12)
(make-posn 7 12)
(make-posn 8 12)
(make-posn 9 12)
(make-posn 10 12)
(make-posn 11 12)
(make-posn 12 12)
(make-posn 13 12)
(make-posn 14 12)
(make-posn 16 12)
(make-posn 4 13)
(make-posn 6 13)
(make-posn 14 13)
(make-posn 16 13)
(make-posn 1 14)
(make-posn 2 14)
(make-posn 3 14)
(make-posn 4 14)
(make-posn 5 14)
(make-posn 6 14)
(make-posn 7 14)
(make-posn 8 14)
(make-posn 9 14)
(make-posn 11 14)
(make-posn 12 14)
(make-posn 13 14)
(make-posn 14 14)
(make-posn 15 14)
(make-posn 16 14)
(make-posn 17 14)
(make-posn 18 14)
(make-posn 19 14)
(make-posn 1 15)
(make-posn 4 15)
(make-posn 9 15)
(make-posn 11 15)
(make-posn 16 15)
(make-posn 19 15)
(make-posn 2 16)
(make-posn 4 16)
(make-posn 5 16)
(make-posn 6 16)
(make-posn 7 16)
(make-posn 8 16)
(make-posn 9 16)
(make-posn 11 16)
(make-posn 12 16)
(make-posn 13 16)
(make-posn 14 16)
(make-posn 15 16)
(make-posn 16 16)
(make-posn 18 16)
(make-posn 2 17)
(make-posn 4 17)
(make-posn 6 17)
(make-posn 14 17)
(make-posn 16 17)
(make-posn 18 17)
(make-posn 1 18)
(make-posn 2 18)
(make-posn 3 18)
(make-posn 4 18)
(make-posn 6 18)
(make-posn 7 18)
(make-posn 8 18)
(make-posn 9 18)
(make-posn 11 18)
(make-posn 12 18)
(make-posn 13 18)
(make-posn 14 18)
(make-posn 16 18)
(make-posn 17 18)
(make-posn 18 18)
(make-posn 19 18)
(make-posn 1 19)
(make-posn 9 19)
(make-posn 11 19)
(make-posn 19 19)
(make-posn 1 20)
(make-posn 2 20)
(make-posn 3 20)
(make-posn 4 20)
(make-posn 5 20)
(make-posn 6 20)
(make-posn 7 20)
(make-posn 8 20)
(make-posn 9 20)
(make-posn 10 20)
(make-posn 11 20)
(make-posn 12 20)
(make-posn 13 20)
(make-posn 14 20)
(make-posn 15 20)
(make-posn 16 20)
(make-posn 17 20)
(make-posn 18 20)
(make-posn 19 20)
(make-posn 1 2)
(make-posn 19 2)
(make-posn 1 16)
(make-posn 19 16))) | null | https://raw.githubusercontent.com/plum-umd/fundamentals/eb01ac528d42855be53649991a17d19c025a97ad/1/www/code/maze-data.rkt | racket | about the language level of this file in a form that our tools can easily process. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname maze-data) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define MAZE0
(list
(make-posn 0 0)
(make-posn 1 0)
(make-posn 2 0)
(make-posn 3 0)
(make-posn 4 0)
(make-posn 5 0)
(make-posn 6 0)
(make-posn 7 0)
(make-posn 8 0)
(make-posn 9 0)
(make-posn 10 0)
(make-posn 11 0)
(make-posn 12 0)
(make-posn 13 0)
(make-posn 14 0)
(make-posn 15 0)
(make-posn 16 0)
(make-posn 17 0)
(make-posn 18 0)
(make-posn 19 0)
(make-posn 20 0)
(make-posn 0 1)
(make-posn 10 1)
(make-posn 20 1)
(make-posn 0 2)
(make-posn 2 2)
(make-posn 3 2)
(make-posn 5 2)
(make-posn 6 2)
(make-posn 7 2)
(make-posn 8 2)
(make-posn 10 2)
(make-posn 12 2)
(make-posn 13 2)
(make-posn 14 2)
(make-posn 15 2)
(make-posn 17 2)
(make-posn 18 2)
(make-posn 20 2)
(make-posn 0 3)
(make-posn 2 3)
(make-posn 3 3)
(make-posn 5 3)
(make-posn 6 3)
(make-posn 7 3)
(make-posn 8 3)
(make-posn 10 3)
(make-posn 12 3)
(make-posn 13 3)
(make-posn 14 3)
(make-posn 15 3)
(make-posn 17 3)
(make-posn 18 3)
(make-posn 20 3)
(make-posn 0 4)
(make-posn 20 4)
(make-posn 0 5)
(make-posn 2 5)
(make-posn 3 5)
(make-posn 5 5)
(make-posn 7 5)
(make-posn 8 5)
(make-posn 9 5)
(make-posn 10 5)
(make-posn 11 5)
(make-posn 12 5)
(make-posn 13 5)
(make-posn 15 5)
(make-posn 17 5)
(make-posn 18 5)
(make-posn 20 5)
(make-posn 0 6)
(make-posn 5 6)
(make-posn 10 6)
(make-posn 15 6)
(make-posn 20 6)
(make-posn 0 7)
(make-posn 1 7)
(make-posn 2 7)
(make-posn 3 7)
(make-posn 5 7)
(make-posn 6 7)
(make-posn 7 7)
(make-posn 8 7)
(make-posn 10 7)
(make-posn 12 7)
(make-posn 13 7)
(make-posn 14 7)
(make-posn 15 7)
(make-posn 17 7)
(make-posn 18 7)
(make-posn 19 7)
(make-posn 20 7)
(make-posn 0 8)
(make-posn 1 8)
(make-posn 2 8)
(make-posn 3 8)
(make-posn 5 8)
(make-posn 15 8)
(make-posn 17 8)
(make-posn 18 8)
(make-posn 19 8)
(make-posn 20 8)
(make-posn 0 9)
(make-posn 1 9)
(make-posn 2 9)
(make-posn 3 9)
(make-posn 5 9)
(make-posn 7 9)
(make-posn 8 9)
(make-posn 9 9)
(make-posn 10 9)
(make-posn 11 9)
(make-posn 12 9)
(make-posn 13 9)
(make-posn 15 9)
(make-posn 17 9)
(make-posn 18 9)
(make-posn 19 9)
(make-posn 20 9)
(make-posn 7 10)
(make-posn 8 10)
(make-posn 9 10)
(make-posn 10 10)
(make-posn 11 10)
(make-posn 12 10)
(make-posn 13 10)
(make-posn 0 11)
(make-posn 1 11)
(make-posn 2 11)
(make-posn 3 11)
(make-posn 5 11)
(make-posn 7 11)
(make-posn 8 11)
(make-posn 9 11)
(make-posn 10 11)
(make-posn 11 11)
(make-posn 12 11)
(make-posn 13 11)
(make-posn 15 11)
(make-posn 17 11)
(make-posn 18 11)
(make-posn 19 11)
(make-posn 20 11)
(make-posn 0 12)
(make-posn 1 12)
(make-posn 2 12)
(make-posn 3 12)
(make-posn 5 12)
(make-posn 15 12)
(make-posn 17 12)
(make-posn 18 12)
(make-posn 19 12)
(make-posn 20 12)
(make-posn 0 13)
(make-posn 1 13)
(make-posn 2 13)
(make-posn 3 13)
(make-posn 5 13)
(make-posn 7 13)
(make-posn 8 13)
(make-posn 9 13)
(make-posn 10 13)
(make-posn 11 13)
(make-posn 12 13)
(make-posn 13 13)
(make-posn 15 13)
(make-posn 17 13)
(make-posn 18 13)
(make-posn 19 13)
(make-posn 20 13)
(make-posn 0 14)
(make-posn 10 14)
(make-posn 20 14)
(make-posn 0 15)
(make-posn 2 15)
(make-posn 3 15)
(make-posn 5 15)
(make-posn 6 15)
(make-posn 7 15)
(make-posn 8 15)
(make-posn 10 15)
(make-posn 12 15)
(make-posn 13 15)
(make-posn 14 15)
(make-posn 15 15)
(make-posn 17 15)
(make-posn 18 15)
(make-posn 20 15)
(make-posn 0 16)
(make-posn 3 16)
(make-posn 17 16)
(make-posn 20 16)
(make-posn 0 17)
(make-posn 1 17)
(make-posn 3 17)
(make-posn 5 17)
(make-posn 7 17)
(make-posn 8 17)
(make-posn 9 17)
(make-posn 10 17)
(make-posn 11 17)
(make-posn 12 17)
(make-posn 13 17)
(make-posn 15 17)
(make-posn 17 17)
(make-posn 19 17)
(make-posn 20 17)
(make-posn 0 18)
(make-posn 5 18)
(make-posn 10 18)
(make-posn 15 18)
(make-posn 20 18)
(make-posn 0 19)
(make-posn 2 19)
(make-posn 3 19)
(make-posn 4 19)
(make-posn 5 19)
(make-posn 6 19)
(make-posn 7 19)
(make-posn 8 19)
(make-posn 10 19)
(make-posn 12 19)
(make-posn 13 19)
(make-posn 14 19)
(make-posn 15 19)
(make-posn 16 19)
(make-posn 17 19)
(make-posn 18 19)
(make-posn 20 19)
(make-posn 0 20)
(make-posn 20 20)
(make-posn 0 21)
(make-posn 1 21)
(make-posn 2 21)
(make-posn 3 21)
(make-posn 4 21)
(make-posn 5 21)
(make-posn 6 21)
(make-posn 7 21)
(make-posn 8 21)
(make-posn 9 21)
(make-posn 10 21)
(make-posn 11 21)
(make-posn 12 21)
(make-posn 13 21)
(make-posn 14 21)
(make-posn 15 21)
(make-posn 16 21)
(make-posn 17 21)
(make-posn 18 21)
(make-posn 19 21)
(make-posn 20 21)))
(define DOTS0
(list
(make-posn 1 1)
(make-posn 2 1)
(make-posn 3 1)
(make-posn 4 1)
(make-posn 5 1)
(make-posn 6 1)
(make-posn 7 1)
(make-posn 8 1)
(make-posn 9 1)
(make-posn 11 1)
(make-posn 12 1)
(make-posn 13 1)
(make-posn 14 1)
(make-posn 15 1)
(make-posn 16 1)
(make-posn 17 1)
(make-posn 18 1)
(make-posn 19 1)
(make-posn 4 2)
(make-posn 9 2)
(make-posn 11 2)
(make-posn 16 2)
(make-posn 1 3)
(make-posn 4 3)
(make-posn 9 3)
(make-posn 11 3)
(make-posn 16 3)
(make-posn 19 3)
(make-posn 1 4)
(make-posn 2 4)
(make-posn 3 4)
(make-posn 4 4)
(make-posn 5 4)
(make-posn 6 4)
(make-posn 7 4)
(make-posn 8 4)
(make-posn 9 4)
(make-posn 10 4)
(make-posn 11 4)
(make-posn 12 4)
(make-posn 13 4)
(make-posn 14 4)
(make-posn 15 4)
(make-posn 16 4)
(make-posn 17 4)
(make-posn 18 4)
(make-posn 19 4)
(make-posn 1 5)
(make-posn 4 5)
(make-posn 6 5)
(make-posn 14 5)
(make-posn 16 5)
(make-posn 19 5)
(make-posn 1 6)
(make-posn 2 6)
(make-posn 3 6)
(make-posn 4 6)
(make-posn 6 6)
(make-posn 7 6)
(make-posn 8 6)
(make-posn 9 6)
(make-posn 11 6)
(make-posn 12 6)
(make-posn 13 6)
(make-posn 14 6)
(make-posn 16 6)
(make-posn 17 6)
(make-posn 18 6)
(make-posn 19 6)
(make-posn 4 7)
(make-posn 9 7)
(make-posn 11 7)
(make-posn 16 7)
(make-posn 4 8)
(make-posn 6 8)
(make-posn 7 8)
(make-posn 8 8)
(make-posn 9 8)
(make-posn 10 8)
(make-posn 11 8)
(make-posn 12 8)
(make-posn 13 8)
(make-posn 14 8)
(make-posn 16 8)
(make-posn 4 9)
(make-posn 6 9)
(make-posn 14 9)
(make-posn 16 9)
(make-posn 0 10)
(make-posn 1 10)
(make-posn 2 10)
(make-posn 3 10)
(make-posn 4 10)
(make-posn 5 10)
(make-posn 6 10)
(make-posn 14 10)
(make-posn 15 10)
(make-posn 16 10)
(make-posn 17 10)
(make-posn 18 10)
(make-posn 19 10)
(make-posn 20 10)
(make-posn 4 11)
(make-posn 6 11)
(make-posn 14 11)
(make-posn 16 11)
(make-posn 4 12)
(make-posn 6 12)
(make-posn 7 12)
(make-posn 8 12)
(make-posn 9 12)
(make-posn 10 12)
(make-posn 11 12)
(make-posn 12 12)
(make-posn 13 12)
(make-posn 14 12)
(make-posn 16 12)
(make-posn 4 13)
(make-posn 6 13)
(make-posn 14 13)
(make-posn 16 13)
(make-posn 1 14)
(make-posn 2 14)
(make-posn 3 14)
(make-posn 4 14)
(make-posn 5 14)
(make-posn 6 14)
(make-posn 7 14)
(make-posn 8 14)
(make-posn 9 14)
(make-posn 11 14)
(make-posn 12 14)
(make-posn 13 14)
(make-posn 14 14)
(make-posn 15 14)
(make-posn 16 14)
(make-posn 17 14)
(make-posn 18 14)
(make-posn 19 14)
(make-posn 1 15)
(make-posn 4 15)
(make-posn 9 15)
(make-posn 11 15)
(make-posn 16 15)
(make-posn 19 15)
(make-posn 2 16)
(make-posn 4 16)
(make-posn 5 16)
(make-posn 6 16)
(make-posn 7 16)
(make-posn 8 16)
(make-posn 9 16)
(make-posn 11 16)
(make-posn 12 16)
(make-posn 13 16)
(make-posn 14 16)
(make-posn 15 16)
(make-posn 16 16)
(make-posn 18 16)
(make-posn 2 17)
(make-posn 4 17)
(make-posn 6 17)
(make-posn 14 17)
(make-posn 16 17)
(make-posn 18 17)
(make-posn 1 18)
(make-posn 2 18)
(make-posn 3 18)
(make-posn 4 18)
(make-posn 6 18)
(make-posn 7 18)
(make-posn 8 18)
(make-posn 9 18)
(make-posn 11 18)
(make-posn 12 18)
(make-posn 13 18)
(make-posn 14 18)
(make-posn 16 18)
(make-posn 17 18)
(make-posn 18 18)
(make-posn 19 18)
(make-posn 1 19)
(make-posn 9 19)
(make-posn 11 19)
(make-posn 19 19)
(make-posn 1 20)
(make-posn 2 20)
(make-posn 3 20)
(make-posn 4 20)
(make-posn 5 20)
(make-posn 6 20)
(make-posn 7 20)
(make-posn 8 20)
(make-posn 9 20)
(make-posn 10 20)
(make-posn 11 20)
(make-posn 12 20)
(make-posn 13 20)
(make-posn 14 20)
(make-posn 15 20)
(make-posn 16 20)
(make-posn 17 20)
(make-posn 18 20)
(make-posn 19 20)
(make-posn 1 2)
(make-posn 19 2)
(make-posn 1 16)
(make-posn 19 16))) |
874d174d113a9e80f8fe24feed693770fb7e15bac70c1486d4734c5ed389e908 | gbwey/persistent-odbc | TestODBC.hs | -- stack build --test --flag persistent-odbc:tester --stack-yaml=stack865.yaml
stack --stack - yaml = stack865.yaml exec -- testodbc s
-- stack build --test --flag persistent-odbc:tester --stack-yaml=stack8103.yaml
stack --stack - yaml = stack8103.yaml exec -- testodbc s
-- cabal configure -f tester
-- cabal build
cabal exec -- TestODBC s
{-# OPTIONS -Wall #-}
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE EmptyDataDecls #-}
# LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE StandaloneDeriving #
module Main where
import Database.Persist
import Database.Persist.ODBC
import Database.Persist.TH
import Control.Monad.Trans.Reader (ask)
import Control.Monad.Trans.Resource (runResourceT, ResourceT)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger
import qualified Data.Text as T
import Data.Functor
import Data.Time (getCurrentTime,UTCTime)
import System.Environment (getArgs)
import Employment
import Data.Conduit
import qualified Data.Conduit.List as CL
import Control.Monad (when,unless,forM_)
import qualified Database.HDBC as H
import qualified Database.HDBC.ODBC as H
import FtypeEnum
import qualified Database.Esqueleto as E
import Database.Esqueleto (select,where_,(^.),from,Value(..))
import Data.ByteString (ByteString)
import Data.Ratio
import Text.Blaze.Html
--import Debug.Trace
share [mkPersist sqlSettings, mkMigrate "migrateAll", mkDeleteCascade sqlSettings] [persistLowerCase|
Test0
mybool Bool
deriving Show
Test1
flag Bool
flag1 Bool Maybe
dbl Double
db2 Double Maybe
deriving Show
Test2
dt UTCTime
deriving Show
Persony
name String
employment Employment
deriving Show
Personx
name String Eq Ne Desc
age Int Lt Asc
color String Maybe Eq Ne
Unique PersonxNameKey name
deriving Show
Testnum
bar Int
znork Int Maybe
znork1 String
znork2 String Maybe
znork3 UTCTime
name String Maybe
deriving Show
Foo
bar String
deriving Show
Personz
name String
age Int Maybe
deriving Show
BlogPost
title String
refPersonz PersonzId
deriving Show
Asm
name String
description String
Unique MyUniqueAsm name
deriving Show
Xsd
name String
description String
asmid AsmId
Unique MyUniqueXsd name -- global
deriving Show
Ftype
name String
Unique MyUniqueFtype name
deriving Show
Line
name String
description String
pos Int
ftypeid FtypeEnum
xsdid XsdId
within an xsd : so can repeat fieldnames in different xsds
Unique EinzigPos xsdid pos
deriving Show
Interface
name String
fname String
ftypeid FtypeId
iname FtypeEnum
Unique MyUniqueInterface name
deriving Show
json -- no FromJSON instance in aeson anymore for bytestring
bs1 ByteString Maybe
bs2 ByteString
deriving Show
Testrational json
rat Rational
deriving Show
Testhtml
myhtml Html
-- deriving Show
Testblob
bs1 ByteString Maybe
deriving Show
Testblob3
bs1 ByteString
bs2 ByteString
bs3 ByteString
deriving Show
Testlen
txt String maxlen=5 -- default='xx12'
str String maxlen=5
bs ByteString maxlen=5
mtxt String Maybe maxlen=5
mstr String Maybe maxlen=5
mbs ByteString Maybe maxlen=5
deriving Show
Aaaa
name String maxlen=100
deriving Show Eq
Bbbb
name String maxlen=100
deriving Show Eq
Both
refAaaa AaaaId
refBbbb BbbbId
Primary refAaaa refBbbb
deriving Show Eq
|]
main :: IO ()
main = do
[arg] <- getArgs
let (dbtype',dsn) =
odbc system dsn
"d" -> (DB2,"dsn=db2_test")
"p" -> (Postgres,"dsn=pg_test")
"m" -> (MySQL,"dsn=mysql_test")
have to pass UID= .. ; .. ; or use Trusted_Connection or Trusted Connection depending on the driver and environment
mssql 2012 [ full limit and offset support ]
mssql pre 2012 [ limit support only ]
"o" -> (Oracle False,"dsn=oracle_test") -- pre oracle 12c [no support for limit and offset]
"on" -> (Oracle True,"dsn=oracle_test") -- >= oracle 12c [full limit and offset support]
"q" -> (Sqlite False,"dsn=sqlite_test;NoWCHAR=1")
"qn" -> (Sqlite True,"dsn=sqlite_test;NoWCHAR=1")
xs -> error $ "unknown option:choose p m s so o on d q qn found[" ++ xs ++ "]"
runResourceT $ runNoLoggingT $ withODBCConn Nothing dsn $ runSqlConn $ do
conn <- ask
let dbtype=read $ T.unpack $ connRDBMS conn
liftIO $ putStrLn $ "original:" ++ show dbtype' ++ " calculated:" ++ show dbtype
liftIO $ putStrLn "\nbefore migration\n"
runMigration migrateAll
liftIO $ putStrLn "after migration"
case dbtype of
deleteCascadeWhere Asm causes seg fault for mssql only
deleteWhere ([] :: [Filter Line])
deleteWhere ([] :: [Filter Xsd])
deleteWhere ([] :: [Filter Asm])
_ -> do
deleteCascadeWhere ([] :: [Filter Asm])
deleteCascadeWhere ([] :: [Filter Personz])
deleteWhere ([] :: [Filter Personz])
deleteWhere ([] :: [Filter Persony])
deleteWhere ([] :: [Filter Personx])
deleteWhere ([] :: [Filter Testother])
deleteWhere ([] :: [Filter Testrational])
deleteWhere ([] :: [Filter Testblob])
deleteWhere ([] :: [Filter Testblob3])
deleteWhere ([] :: [Filter Testother])
deleteWhere ([] :: [Filter Testnum])
deleteWhere ([] :: [Filter Testhtml])
deleteWhere ([] :: [Filter Testblob3])
deleteWhere ([] :: [Filter Test1])
deleteWhere ([] :: [Filter Test0])
deleteWhere ([] :: [Filter Testlen])
when True $ testbase dbtype
liftIO $ putStrLn "Ended tests"
testbase :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
testbase dbtype = do
liftIO $ putStrLn "\n*** in testbase\n"
a1 <- insert $ Foo "test"
liftIO $ putStrLn $ "a1=" ++ show a1
a2 <- selectList ([] :: [Filter Foo]) []
liftIO $ putStrLn $ "a2="
liftIO $ mapM_ print a2
johnId <- insert $ Personz "John Doe" $ Just 35
liftIO $ putStrLn $ "johnId[" ++ show johnId ++ "]"
janeId <- insert $ Personz "Jane Doe" Nothing
liftIO $ putStrLn $ "janeId[" ++ show janeId ++ "]"
a3 <- selectList ([] :: [Filter Personz]) []
unless (length a3 == 2) $ error $ "wrong number of Personz rows " ++ show a3
liftIO $ putStrLn $ "a3="
liftIO $ mapM_ print a3
void $ insert $ BlogPost "My fr1st p0st" johnId
liftIO $ putStrLn $ "after insert johnId"
void $ insert $ BlogPost "One more for good measure" johnId
liftIO $ putStrLn $ "after insert johnId 2"
a4 <- selectList ([] :: [Filter BlogPost]) []
liftIO $ putStrLn $ "a4="
liftIO $ mapM_ print a4
unless (length a4 == 2) $ error $ "wrong number of BlogPost rows " ++ show a4
oneJohnPost < - selectList [ BlogPostAuthorId = = . johnId ] [ LimitTo 1 ]
--liftIO $ print (oneJohnPost :: [Entity BlogPost])
john <- get johnId
liftIO $ print (john :: Maybe Personz)
dt <- liftIO getCurrentTime
v1 <- insert $ Testnum 100 Nothing "hello" (Just "world") dt Nothing
v2 <- insert $ Testnum 100 (Just 222) "dude" Nothing dt (Just "something")
liftIO $ putStrLn $ "v1=" ++ show v1
liftIO $ putStrLn $ "v2=" ++ show v2
a5 <- selectList ([] :: [Filter Testnum]) []
unless (length a5 == 2) $ error $ "wrong number of Testnum rows " ++ show a5
delete janeId
deleteWhere [BlogPostRefPersonz ==. johnId]
test0
test1 dbtype
test2
test3
test4
case dbtype of
MSSQL {} -> return ()
_ -> test5 dbtype
test6
when (limitoffset dbtype) test7
when (limitoffset dbtype) test8
case dbtype of
Oracle { oracle12c=False } -> return ()
_ -> test9
case dbtype of
MSSQL {} -> return ()
_ -> test10 dbtype
case dbtype of
MSSQL {} -> return ()
_ -> test11 dbtype
test12 dbtype
test0 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test0 = do
liftIO $ putStrLn "\n*** in test0\n"
pid <- insert $ Personx "Michael" 25 Nothing
liftIO $ print pid
p1 <- get pid
liftIO $ print p1
replace pid $ Personx "Michael" 26 Nothing
p2 <- get pid
liftIO $ print p2
p3 <- selectList [PersonxName ==. "Michael"] []
liftIO $ mapM_ print p3
_ <- insert $ Personx "Michael2" 27 Nothing
deleteWhere [PersonxName ==. "Michael2"]
p4 <- selectList [PersonxAge <. 28] []
liftIO $ mapM_ print p4
update pid [PersonxAge =. 28]
p5 <- get pid
liftIO $ print p5
updateWhere [PersonxName ==. "Michael"] [PersonxAge =. 29]
p6 <- get pid
liftIO $ print p6
_ <- insert $ Personx "Eliezer" 2 $ Just "blue"
p7 <- selectList [] [Asc PersonxAge]
liftIO $ mapM_ print p7
_ <- insert $ Personx "Abe" 30 $ Just "black"
p8 <- selectList [PersonxAge <. 30] [Desc PersonxName]
liftIO $ mapM_ print p8
_ <- insert $ Personx "Abe1" 31 $ Just "brown"
p9 <- selectList [PersonxName ==. "Abe1"] []
liftIO $ mapM_ print p9
a6 <- selectList ([] :: [Filter Personx]) []
unless (length a6 == 4) $ error $ "wrong number of Personx rows " ++ show a6
p10 <- getBy $ PersonxNameKey "Michael"
liftIO $ print p10
p11 <- selectList [PersonxColor ==. Just "blue"] []
liftIO $ mapM_ print p11
p12 <- selectList [PersonxColor ==. Nothing] []
liftIO $ mapM_ print p12
p13 <- selectList [PersonxColor !=. Nothing] []
liftIO $ mapM_ print p13
delete pid
plast <- get pid
liftIO $ print plast
test1 :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
test1 dbtype = do
liftIO $ putStrLn "\n*** in test1\n"
pid1 <- insert $ Persony "Dude" Retired
liftIO $ print pid1
pid2 <- insert $ Persony "Dude1" Employed
liftIO $ print pid2
pid3 <- insert $ Persony "Snoyman aa" Unemployed
liftIO $ print pid3
pid4 <- insert $ Persony "bbb Snoyman" Employed
liftIO $ print pid4
a1 <- selectList ([] :: [Filter Persony]) []
unless (length a1 == 4) $ error $ "wrong number of Personz rows " ++ show a1
liftIO $ putStrLn $ "persony "
liftIO $ mapM_ print a1
let sql = case dbtype of
MSSQL {} -> "SELECT [name] FROM [persony] WHERE [name] LIKE '%Snoyman%'"
MySQL {} -> "SELECT `name` FROM `persony` WHERE `name` LIKE '%Snoyman%'"
_ -> "SELECT \"name\" FROM \"persony\" WHERE \"name\" LIKE '%Snoyman%'"
runConduit $ rawQuery sql [] .| CL.mapM_ (liftIO . print)
test2 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test2 = do
liftIO $ putStrLn "\n*** in test2\n"
aaa <- insert $ Test0 False
liftIO $ print aaa
a1 <- selectList ([] :: [Filter Test0]) []
unless (length a1 == 1) $ error $ "wrong number of Personz rows " ++ show a1
test3 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test3 = do
liftIO $ putStrLn "\n*** in test3\n"
a1 <- insert $ Test1 True (Just False) 100.3 Nothing
liftIO $ putStrLn $ "a1=" ++ show a1
a2 <- insert $ Test1 False Nothing 100.3 (Just 12.44)
liftIO $ putStrLn $ "a2=" ++ show a2
a3 <- insert $ Test1 True (Just True) 100.3 (Just 11.11)
liftIO $ putStrLn $ "a3=" ++ show a3
a4 <- insert $ Test1 False Nothing 100.3 Nothing
liftIO $ putStrLn $ "a4=" ++ show a4
ret <- selectList ([] :: [Filter Test1]) []
liftIO $ mapM_ print ret
a5 <- selectList ([] :: [Filter Test1]) []
unless (length a5 == 4) $ error $ "wrong number of Test1 rows " ++ show a5
test4 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test4 = do
liftIO $ putStrLn "\n*** in test4\n"
a1 <- insert $ Asm "NewAsm1" "description for newasm1"
x11 <- insert $ Xsd "NewXsd11" "description for newxsd11" a1
liftIO $ putStrLn $ "x11=" ++ show x11
l111 <- insert $ Line "NewLine111" "description for newline111" 10 Xsd_string x11
liftIO $ putStrLn $ "l111=" ++ show l111
l112 <- insert $ Line "NewLine112" "description for newline112" 11 Xsd_boolean x11
liftIO $ putStrLn $ "l112=" ++ show l112
l113 <- insert $ Line "NewLine113" "description for newline113" 12 Xsd_decimal x11
liftIO $ putStrLn $ "l113=" ++ show l113
l114 <- insert $ Line "NewLine114" "description for newline114" 15 Xsd_int x11
liftIO $ putStrLn $ "l114=" ++ show l114
x12 <- insert $ Xsd "NewXsd12" "description for newxsd12" a1
liftIO $ putStrLn $ "x12=" ++ show x12
l121 <- insert $ Line "NewLine121" "description for newline1" 12 Xsd_int x12
liftIO $ putStrLn $ "l121=" ++ show l121
l122 <- insert $ Line "NewLine122" "description for newline2" 19 Xsd_boolean x12
liftIO $ putStrLn $ "l122=" ++ show l122
l123 <- insert $ Line "NewLine123" "description for newline3" 13 Xsd_string x12
liftIO $ putStrLn $ "l123=" ++ show l123
l124 <- insert $ Line "NewLine124" "description for newline4" 99 Xsd_double x12
liftIO $ putStrLn $ "l124=" ++ show l124
l125 <- insert $ Line "NewLine125" "description for newline5" 2 Xsd_boolean x12
liftIO $ putStrLn $ "l125=" ++ show l125
a2 <- insert $ Asm "NewAsm2" "description for newasm2"
liftIO $ putStrLn $ "a2=" ++ show a2
a3 <- insert $ Asm "NewAsm3" "description for newasm3"
liftIO $ putStrLn $ "a3=" ++ show a3
x31 <- insert $ Xsd "NewXsd31" "description for newxsd311" a3
liftIO $ putStrLn $ "x31=" ++ show x31
a4 <- selectList ([] :: [Filter Asm]) []
liftIO $ putStrLn "a4="
liftIO $ mapM_ print a4
unless (length a4 == 3) $ error $ "wrong number of Asm rows " ++ show a4
a5 <- selectList ([] :: [Filter Xsd]) []
liftIO $ putStrLn "a5="
liftIO $ mapM_ print a5
unless (length a5 == 3) $ error $ "wrong number of Xsd rows " ++ show a5
a6 <- selectList ([] :: [Filter Line]) []
liftIO $ putStrLn "a6="
liftIO $ mapM_ print a6
unless (length a6 == 9) $ error $ "wrong number of Line rows " ++ show a6
[Value mpos] <- select $
from $ \ln -> do
where_ (ln ^. LineXsdid E.==. E.val x11)
return $ E.joinV $ E.max_ (E.just (ln ^. LinePos))
liftIO $ putStrLn $ "mpos=" ++ show mpos
test5 :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
test5 dbtype = do
liftIO $ putStrLn "\n*** in test5\n"
a1 <- insert $ Testother (Just "abc") "zzzz"
liftIO $ putStrLn $ "a1=" ++ show a1
case dbtype of
DB2 {} -> liftIO $ putStrLn $ show dbtype ++ " insert multiple blob fields with a null fails"
_ -> do
a2 <- insert $ Testother Nothing "aaa"
liftIO $ putStrLn $ "a2=" ++ show a2
a3 <- insert $ Testother (Just "nnn") "bbb"
liftIO $ putStrLn $ "a3=" ++ show a3
a4 <- insert $ Testother (Just "ddd") "mmm"
liftIO $ putStrLn $ "a4=" ++ show a4
xs <- case dbtype of
can not sort blobs in oracle
can not sort blobs in db2 ?
_ -> selectList [] [Desc TestotherBs1]
liftIO $ putStrLn $ "xs=" ++ show xs
case dbtype of
Oracle {} -> return ()
DB2 {} -> return ()
_ -> do
ys <- selectList [] [Desc TestotherBs2]
liftIO $ putStrLn $ "ys=" ++ show ys
a7 <- selectList ([] :: [Filter Testother]) []
case dbtype of
DB2 {} -> unless (length a7 == 3) $ error $ show dbtype ++ " :wrong number of Testother rows " ++ show a7
_ -> unless (length a7 == 4) $ error $ "wrong number of Testother rows " ++ show a7
liftIO $ putStrLn "end of test5"
test6 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test6 = do
liftIO $ putStrLn "\n*** in test6\n"
r1 <- insert $ Testrational (4%6)
r2 <- insert $ Testrational (13 % 14)
liftIO $ putStrLn $ "r1=" ++ show r1
liftIO $ putStrLn $ "r2=" ++ show r2
zs <- selectList [] [Desc TestrationalRat]
liftIO $ putStrLn "zs="
liftIO $ mapM_ print zs
h1 <- insert $ Testhtml $ preEscapedToMarkup ("<p>hello</p>"::String)
liftIO $ putStrLn $ "h1=" ++ show h1
a1 <- selectList ([] :: [Filter Testrational]) []
unless (length a1 == 2) $ error $ "wrong number of Testrational rows " ++ show a1
a2 <- selectList ([] :: [Filter Testhtml]) []
unless (length a2 == 1) $ error $ "wrong number of Testhtml rows "
test7 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test7 = do
liftIO $ putStrLn "\n*** in test7\n"
a1 <- selectList [] [Desc LinePos, LimitTo 2, OffsetBy 3]
liftIO $ putStrLn $ show (length a1) ++ " rows: limit=2,offset=3 a1="
liftIO $ mapM_ print a1
a2 <- selectList [] [Desc LinePos, LimitTo 2]
liftIO $ putStrLn $ show (length a2) ++ " rows: limit=2 a2="
liftIO $ mapM_ print a2
a3 <- selectList [] [Desc LinePos, OffsetBy 3]
liftIO $ putStrLn $ show (length a3) ++ " rows: offset=3 a3="
liftIO $ mapM_ print a3
test8 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test8 = do
liftIO $ putStrLn "\n*** in test8\n"
xs <- select $
from $ \ln -> do
where_ (ln ^. LinePos E.>=. E.val 0)
E.orderBy [E.asc (ln ^. LinePos)]
E.limit 2
E.offset 3
return ln
liftIO $ putStrLn $ show (length xs) ++ " rows: limit=2 offset=3 xs=" ++ show xs
test9 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test9 = do
liftIO $ putStrLn "\n*** in test9\n"
a1 <- selectList [] [Desc LinePos, LimitTo 2]
liftIO $ putStrLn $ show (length a1) ++ " rows: limit=2,offset=0 a1="
liftIO $ mapM_ print a1
a2 <- selectList [] [Desc LinePos, LimitTo 4]
liftIO $ putStrLn $ show (length a2) ++ " rows: limit=4,offset=0 a2="
liftIO $ mapM_ print a2
test10 :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
test10 dbtype = do
liftIO $ putStrLn "\n*** in test10\n"
a1 <- insert $ Testblob3 "abc1" "def1" "zzzz1"
liftIO $ putStrLn $ "a1=" ++ show a1
a2 <- insert $ Testblob3 "abc2" "def2" "test2"
liftIO $ putStrLn $ "a2=" ++ show a2
case dbtype of
Oracle {} -> liftIO $ putStrLn "skipping insert empty string into oracle blob column (treated as a null)"
{-
*** Exception: SqlError {seState = "[\"HY000\"]", seNativeError = -1,
seErrorMsg = "execute execute: [\"1400: [Oracle][ODBC][Ora]ORA-01400: cannot insert NULL into (\\\"SYSTEM\\\".\\\"testblob3\\\".\\\"bs1\\\")\\n\"]"}
-}
_ -> void $ insert $ Testblob3 "" "hello3" "world3"
ys <- selectList ([] :: [Filter Testblob3]) []
liftIO $ putStrLn "ys="
liftIO $ mapM_ print ys
a3 <- selectList ([] :: [Filter Testblob3]) []
case dbtype of
Oracle {} -> unless (length a3 == 2) $ error $ show dbtype ++ " :wrong number of Testblob3 rows " ++ show a3
_ -> unless (length a3 == 3) $ error $ "wrong number of Testblob3 rows " ++ show a3
liftIO $ mapM_ print a3
test11 :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
test11 dbtype = do
liftIO $ putStrLn "\n*** in test11\n"
case dbtype of
MSSQL {} -> liftIO $ putStrLn $ show dbtype ++ ":inserting null in a blob not supported so skipping"
DB2 {} -> liftIO $ putStrLn $ show dbtype ++ ":inserting null in a blob not supported so skipping"
_ -> do
_ <- insert $ Testblob Nothing
return ()
_ <- insert $ Testblob $ Just "some data for testing"
_ <- insert $ Testblob $ Just "world"
liftIO $ putStrLn "after testblob inserts"
mssql fails if there is a null in a blog column
liftIO $ putStrLn $ "testblob xs="
liftIO $ mapM_ print xs
a1 <- selectList ([] :: [Filter Testblob]) []
case dbtype of
MSSQL {} -> unless (length a1 == 2) $ error $ show dbtype ++ " :wrong number of Testblob rows " ++ show a1
DB2 {} -> unless (length a1 == 2) $ error $ show dbtype ++ " :wrong number of Testblob rows " ++ show a1
_ -> unless (length a1 == 3) $ error $ "wrong number of Testblob rows " ++ show a1
test12 :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
test12 dbtype = do
liftIO $ putStrLn "\n*** in test12\n"
a1 <- insert $ Testlen "txt1" "str1" "bs1" (Just "txt1m") (Just "str1m") (Just "bs1m")
liftIO $ putStrLn $ "a1=" ++ show a1
a2 <- insert $ Testlen "txt2" "str2" "bs2" (Just "aaaa") (Just "str2m") (Just "bs2m")
liftIO $ putStrLn $ "a2=" ++ show a2
a3 <- selectList ([] :: [Filter Testlen]) []
case dbtype of
Oracle { } - > unless ( length a3 = = 2 ) $ error $ show dbtype + + " : wrong number of Testlen rows " + + show a3
_ -> unless (length a3 == 2) $ error $ "wrong number of Testlen rows " ++ show a3
liftIO $ putStrLn $ "a3="
liftIO $ mapM_ print a3
limitoffset :: DBType -> Bool
trace ( " limitoffset dbtype= " + + show dbtype ) $
case dbtype of
Oracle False -> False
MSSQL False -> False
_ -> True
main2 :: IO ()
main2 = do
let = " = mssql_test ; Trusted_Connection = True "
let connectionString = "dsn=db2_test"
conn <- H.connectODBC connectionString
putStrLn "\n1\n"
stmt1 <- H.prepare conn "select * from test93"
putStrLn "\n2\n"
vals1 <- H.execute stmt1 []
print vals1
putStrLn "\n3\n"
results1 <- H.fetchAllRowsAL stmt1
putStrLn "\n4\n"
forM_ (zip [1::Int ..] results1) $ \(i,x) -> putStrLn $ "i=" ++ show i ++ " result=" ++ show x
putStrLn "\na\n"
--stmt1 <- H.prepare conn "create table test93 (bs1 blob)"
--putStrLn "\nb\n"
--vals <- H.execute stmt1 []
putStrLn " \nc\n "
stmt2 <- H.prepare conn "insert into test93 values(blob(?))"
putStrLn "\nd\n"
vals2 <- H.execute stmt2 [H.SqlByteString "hello world"]
putStrLn "\ne\n"
print vals2
-- _ <- H.commit conn
-- error "we are done!!"
a < - H.quickQuery ' conn " select * from testblob " [ ] -- hangs here in both mssql drivers [ not all the time ]
" \n5\n "
-- print a
stmt3 <- H.prepare conn "insert into testblob (bs1) values(?)"
putStrLn "\n6\n"
vals3a <- H.execute stmt3 [H.SqlNull]
putStrLn $ "vals3a=" ++ show vals3a
putStrLn "\n7\n"
vals3b <- H.execute stmt3 [H.SqlNull]
putStrLn $ "vals3b=" ++ show vals3b
putStrLn "\n8\n"
vals3c <- H.execute stmt3 [H.SqlNull]
putStrLn $ "vals3c=" ++ show vals3c
putStrLn "\n9\n"
results2 <- H.fetchAllRowsAL stmt2
forM_ (zip [1::Int ..] results2) $ \(i,x) -> putStrLn $ "i=" ++ show i ++ " result=" ++ show x
putStrLn "\nTESTBLOB worked\n"
stmt conn " insert into ( bs1,bs2 ) values(convert(varbinary(max),?),convert(varbinary(max ) , ? ) ) "
stmt4 <- H.prepare conn "insert into testother (bs1,bs2) values(convert(varbinary(max), cast (? as varchar(100))),convert(varbinary(max), cast (? as varchar(100))))"
vals4 <- H.execute stmt4 [H.SqlByteString "hello",H.SqlByteString "test"]
putStrLn $ "vals4=" ++ show vals4
vals < - H.execute [ , H.SqlByteString " test " ]
putStrLn "\nTESTOTHER worked\n"
H.commit conn
main3 :: IO ()
main3 = do
let = " = pg_test "
let connectionString = "dsn=mysql_test"
let = " = mssql_test ; Trusted_Connection = True "
let = " = oracle_test "
let = " = db2_test "
conn <- H.connectODBC connectionString
putStrLn "\n1\n"
putStrLn $ "drivername=" ++ H.hdbcDriverName conn
putStrLn $ "clientver=" ++ H.hdbcClientVer conn
putStrLn $ "proxied drivername=" ++ H.proxiedClientName conn
putStrLn $ "proxied clientver=" ++ H.proxiedClientVer conn
putStrLn $ "serverver=" ++ H.dbServerVer conn
mssql
let lenfn="length "
a <- H.describeTable conn "persony"
print a
stmt1 <- H.prepare conn ("update \"persony\" set \"name\" = ? where \"id\" >= ?")
putStrLn "\n2\n"
vals1 <- H.execute stmt1 [H.SqlString "dooble and stuff", H.toSql (1 :: Integer)]
print vals1
putStrLn "\n3\n"
stmt2 <- H.prepare conn ("select \"id\","++lenfn++"(\"name\"),\"name\" from \"persony\"")
putStrLn "\n4\n"
vals2 <- H.execute stmt2 []
print vals2
results <- H.fetchAllRowsAL' stmt2
mapM_ print results
H.commit conn
main4 :: IO ()
main4 = do
let = " = pg_test "
let connectionString = "dsn=mysql_test"
let = " = mssql_test ; Trusted_Connection = True "
let = " = oracle_test "
let = " = db2_test "
conn <- H.connectODBC connectionString
putStrLn "\nbefore create\n"
stmt1 <- H.prepare conn "create table fred (nm varchar(100) not null)"
a1 <- H.execute stmt1 []
print a1
putStrLn "\nbefore insert\n"
stmt2 <- H.prepare conn "insert into fred values(?)"
a2 <- H.execute stmt2 [H.SqlString "hello"]
print a2
putStrLn "\nbefore select\n"
stmt3 <- H.prepare conn "select nm,length(nm) from fred"
vals3 <- H.execute stmt3 []
print vals3
results3 <- H.fetchAllRowsAL' stmt3
putStrLn "select after insert"
print results3
putStrLn "\nbefore update\n"
stmt4 <- H.prepare conn "update fred set nm=?"
a4 <- H.execute stmt4 [H.SqlString "worldly"]
print a4
putStrLn "\nbefore select #2\n"
stmt5 <- H.prepare conn "select nm,length(nm) from fred"
vals5 <- H.execute stmt5 []
print vals5
results <- H.fetchAllRowsAL' stmt5
putStrLn "select after update"
print results
H.commit conn
| null | https://raw.githubusercontent.com/gbwey/persistent-odbc/cfe90437486a9e738c02cf22a0de43d4ac99619b/examples/TestODBC.hs | haskell | stack build --test --flag persistent-odbc:tester --stack-yaml=stack865.yaml
stack - yaml = stack865.yaml exec -- testodbc s
stack build --test --flag persistent-odbc:tester --stack-yaml=stack8103.yaml
stack - yaml = stack8103.yaml exec -- testodbc s
cabal configure -f tester
cabal build
TestODBC s
# OPTIONS -Wall #
# LANGUAGE OverloadedStrings #
# LANGUAGE GADTs #
# LANGUAGE EmptyDataDecls #
import Debug.Trace
global
no FromJSON instance in aeson anymore for bytestring
deriving Show
default='xx12'
pre oracle 12c [no support for limit and offset]
>= oracle 12c [full limit and offset support]
liftIO $ print (oneJohnPost :: [Entity BlogPost])
*** Exception: SqlError {seState = "[\"HY000\"]", seNativeError = -1,
seErrorMsg = "execute execute: [\"1400: [Oracle][ODBC][Ora]ORA-01400: cannot insert NULL into (\\\"SYSTEM\\\".\\\"testblob3\\\".\\\"bs1\\\")\\n\"]"}
stmt1 <- H.prepare conn "create table test93 (bs1 blob)"
putStrLn "\nb\n"
vals <- H.execute stmt1 []
_ <- H.commit conn
error "we are done!!"
hangs here in both mssql drivers [ not all the time ]
print a | # LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleContexts #
# LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE StandaloneDeriving #
module Main where
import Database.Persist
import Database.Persist.ODBC
import Database.Persist.TH
import Control.Monad.Trans.Reader (ask)
import Control.Monad.Trans.Resource (runResourceT, ResourceT)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger
import qualified Data.Text as T
import Data.Functor
import Data.Time (getCurrentTime,UTCTime)
import System.Environment (getArgs)
import Employment
import Data.Conduit
import qualified Data.Conduit.List as CL
import Control.Monad (when,unless,forM_)
import qualified Database.HDBC as H
import qualified Database.HDBC.ODBC as H
import FtypeEnum
import qualified Database.Esqueleto as E
import Database.Esqueleto (select,where_,(^.),from,Value(..))
import Data.ByteString (ByteString)
import Data.Ratio
import Text.Blaze.Html
share [mkPersist sqlSettings, mkMigrate "migrateAll", mkDeleteCascade sqlSettings] [persistLowerCase|
Test0
mybool Bool
deriving Show
Test1
flag Bool
flag1 Bool Maybe
dbl Double
db2 Double Maybe
deriving Show
Test2
dt UTCTime
deriving Show
Persony
name String
employment Employment
deriving Show
Personx
name String Eq Ne Desc
age Int Lt Asc
color String Maybe Eq Ne
Unique PersonxNameKey name
deriving Show
Testnum
bar Int
znork Int Maybe
znork1 String
znork2 String Maybe
znork3 UTCTime
name String Maybe
deriving Show
Foo
bar String
deriving Show
Personz
name String
age Int Maybe
deriving Show
BlogPost
title String
refPersonz PersonzId
deriving Show
Asm
name String
description String
Unique MyUniqueAsm name
deriving Show
Xsd
name String
description String
asmid AsmId
deriving Show
Ftype
name String
Unique MyUniqueFtype name
deriving Show
Line
name String
description String
pos Int
ftypeid FtypeEnum
xsdid XsdId
within an xsd : so can repeat fieldnames in different xsds
Unique EinzigPos xsdid pos
deriving Show
Interface
name String
fname String
ftypeid FtypeId
iname FtypeEnum
Unique MyUniqueInterface name
deriving Show
bs1 ByteString Maybe
bs2 ByteString
deriving Show
Testrational json
rat Rational
deriving Show
Testhtml
myhtml Html
Testblob
bs1 ByteString Maybe
deriving Show
Testblob3
bs1 ByteString
bs2 ByteString
bs3 ByteString
deriving Show
Testlen
str String maxlen=5
bs ByteString maxlen=5
mtxt String Maybe maxlen=5
mstr String Maybe maxlen=5
mbs ByteString Maybe maxlen=5
deriving Show
Aaaa
name String maxlen=100
deriving Show Eq
Bbbb
name String maxlen=100
deriving Show Eq
Both
refAaaa AaaaId
refBbbb BbbbId
Primary refAaaa refBbbb
deriving Show Eq
|]
main :: IO ()
main = do
[arg] <- getArgs
let (dbtype',dsn) =
odbc system dsn
"d" -> (DB2,"dsn=db2_test")
"p" -> (Postgres,"dsn=pg_test")
"m" -> (MySQL,"dsn=mysql_test")
have to pass UID= .. ; .. ; or use Trusted_Connection or Trusted Connection depending on the driver and environment
mssql 2012 [ full limit and offset support ]
mssql pre 2012 [ limit support only ]
"q" -> (Sqlite False,"dsn=sqlite_test;NoWCHAR=1")
"qn" -> (Sqlite True,"dsn=sqlite_test;NoWCHAR=1")
xs -> error $ "unknown option:choose p m s so o on d q qn found[" ++ xs ++ "]"
runResourceT $ runNoLoggingT $ withODBCConn Nothing dsn $ runSqlConn $ do
conn <- ask
let dbtype=read $ T.unpack $ connRDBMS conn
liftIO $ putStrLn $ "original:" ++ show dbtype' ++ " calculated:" ++ show dbtype
liftIO $ putStrLn "\nbefore migration\n"
runMigration migrateAll
liftIO $ putStrLn "after migration"
case dbtype of
deleteCascadeWhere Asm causes seg fault for mssql only
deleteWhere ([] :: [Filter Line])
deleteWhere ([] :: [Filter Xsd])
deleteWhere ([] :: [Filter Asm])
_ -> do
deleteCascadeWhere ([] :: [Filter Asm])
deleteCascadeWhere ([] :: [Filter Personz])
deleteWhere ([] :: [Filter Personz])
deleteWhere ([] :: [Filter Persony])
deleteWhere ([] :: [Filter Personx])
deleteWhere ([] :: [Filter Testother])
deleteWhere ([] :: [Filter Testrational])
deleteWhere ([] :: [Filter Testblob])
deleteWhere ([] :: [Filter Testblob3])
deleteWhere ([] :: [Filter Testother])
deleteWhere ([] :: [Filter Testnum])
deleteWhere ([] :: [Filter Testhtml])
deleteWhere ([] :: [Filter Testblob3])
deleteWhere ([] :: [Filter Test1])
deleteWhere ([] :: [Filter Test0])
deleteWhere ([] :: [Filter Testlen])
when True $ testbase dbtype
liftIO $ putStrLn "Ended tests"
testbase :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
testbase dbtype = do
liftIO $ putStrLn "\n*** in testbase\n"
a1 <- insert $ Foo "test"
liftIO $ putStrLn $ "a1=" ++ show a1
a2 <- selectList ([] :: [Filter Foo]) []
liftIO $ putStrLn $ "a2="
liftIO $ mapM_ print a2
johnId <- insert $ Personz "John Doe" $ Just 35
liftIO $ putStrLn $ "johnId[" ++ show johnId ++ "]"
janeId <- insert $ Personz "Jane Doe" Nothing
liftIO $ putStrLn $ "janeId[" ++ show janeId ++ "]"
a3 <- selectList ([] :: [Filter Personz]) []
unless (length a3 == 2) $ error $ "wrong number of Personz rows " ++ show a3
liftIO $ putStrLn $ "a3="
liftIO $ mapM_ print a3
void $ insert $ BlogPost "My fr1st p0st" johnId
liftIO $ putStrLn $ "after insert johnId"
void $ insert $ BlogPost "One more for good measure" johnId
liftIO $ putStrLn $ "after insert johnId 2"
a4 <- selectList ([] :: [Filter BlogPost]) []
liftIO $ putStrLn $ "a4="
liftIO $ mapM_ print a4
unless (length a4 == 2) $ error $ "wrong number of BlogPost rows " ++ show a4
oneJohnPost < - selectList [ BlogPostAuthorId = = . johnId ] [ LimitTo 1 ]
john <- get johnId
liftIO $ print (john :: Maybe Personz)
dt <- liftIO getCurrentTime
v1 <- insert $ Testnum 100 Nothing "hello" (Just "world") dt Nothing
v2 <- insert $ Testnum 100 (Just 222) "dude" Nothing dt (Just "something")
liftIO $ putStrLn $ "v1=" ++ show v1
liftIO $ putStrLn $ "v2=" ++ show v2
a5 <- selectList ([] :: [Filter Testnum]) []
unless (length a5 == 2) $ error $ "wrong number of Testnum rows " ++ show a5
delete janeId
deleteWhere [BlogPostRefPersonz ==. johnId]
test0
test1 dbtype
test2
test3
test4
case dbtype of
MSSQL {} -> return ()
_ -> test5 dbtype
test6
when (limitoffset dbtype) test7
when (limitoffset dbtype) test8
case dbtype of
Oracle { oracle12c=False } -> return ()
_ -> test9
case dbtype of
MSSQL {} -> return ()
_ -> test10 dbtype
case dbtype of
MSSQL {} -> return ()
_ -> test11 dbtype
test12 dbtype
test0 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test0 = do
liftIO $ putStrLn "\n*** in test0\n"
pid <- insert $ Personx "Michael" 25 Nothing
liftIO $ print pid
p1 <- get pid
liftIO $ print p1
replace pid $ Personx "Michael" 26 Nothing
p2 <- get pid
liftIO $ print p2
p3 <- selectList [PersonxName ==. "Michael"] []
liftIO $ mapM_ print p3
_ <- insert $ Personx "Michael2" 27 Nothing
deleteWhere [PersonxName ==. "Michael2"]
p4 <- selectList [PersonxAge <. 28] []
liftIO $ mapM_ print p4
update pid [PersonxAge =. 28]
p5 <- get pid
liftIO $ print p5
updateWhere [PersonxName ==. "Michael"] [PersonxAge =. 29]
p6 <- get pid
liftIO $ print p6
_ <- insert $ Personx "Eliezer" 2 $ Just "blue"
p7 <- selectList [] [Asc PersonxAge]
liftIO $ mapM_ print p7
_ <- insert $ Personx "Abe" 30 $ Just "black"
p8 <- selectList [PersonxAge <. 30] [Desc PersonxName]
liftIO $ mapM_ print p8
_ <- insert $ Personx "Abe1" 31 $ Just "brown"
p9 <- selectList [PersonxName ==. "Abe1"] []
liftIO $ mapM_ print p9
a6 <- selectList ([] :: [Filter Personx]) []
unless (length a6 == 4) $ error $ "wrong number of Personx rows " ++ show a6
p10 <- getBy $ PersonxNameKey "Michael"
liftIO $ print p10
p11 <- selectList [PersonxColor ==. Just "blue"] []
liftIO $ mapM_ print p11
p12 <- selectList [PersonxColor ==. Nothing] []
liftIO $ mapM_ print p12
p13 <- selectList [PersonxColor !=. Nothing] []
liftIO $ mapM_ print p13
delete pid
plast <- get pid
liftIO $ print plast
test1 :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
test1 dbtype = do
liftIO $ putStrLn "\n*** in test1\n"
pid1 <- insert $ Persony "Dude" Retired
liftIO $ print pid1
pid2 <- insert $ Persony "Dude1" Employed
liftIO $ print pid2
pid3 <- insert $ Persony "Snoyman aa" Unemployed
liftIO $ print pid3
pid4 <- insert $ Persony "bbb Snoyman" Employed
liftIO $ print pid4
a1 <- selectList ([] :: [Filter Persony]) []
unless (length a1 == 4) $ error $ "wrong number of Personz rows " ++ show a1
liftIO $ putStrLn $ "persony "
liftIO $ mapM_ print a1
let sql = case dbtype of
MSSQL {} -> "SELECT [name] FROM [persony] WHERE [name] LIKE '%Snoyman%'"
MySQL {} -> "SELECT `name` FROM `persony` WHERE `name` LIKE '%Snoyman%'"
_ -> "SELECT \"name\" FROM \"persony\" WHERE \"name\" LIKE '%Snoyman%'"
runConduit $ rawQuery sql [] .| CL.mapM_ (liftIO . print)
test2 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test2 = do
liftIO $ putStrLn "\n*** in test2\n"
aaa <- insert $ Test0 False
liftIO $ print aaa
a1 <- selectList ([] :: [Filter Test0]) []
unless (length a1 == 1) $ error $ "wrong number of Personz rows " ++ show a1
test3 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test3 = do
liftIO $ putStrLn "\n*** in test3\n"
a1 <- insert $ Test1 True (Just False) 100.3 Nothing
liftIO $ putStrLn $ "a1=" ++ show a1
a2 <- insert $ Test1 False Nothing 100.3 (Just 12.44)
liftIO $ putStrLn $ "a2=" ++ show a2
a3 <- insert $ Test1 True (Just True) 100.3 (Just 11.11)
liftIO $ putStrLn $ "a3=" ++ show a3
a4 <- insert $ Test1 False Nothing 100.3 Nothing
liftIO $ putStrLn $ "a4=" ++ show a4
ret <- selectList ([] :: [Filter Test1]) []
liftIO $ mapM_ print ret
a5 <- selectList ([] :: [Filter Test1]) []
unless (length a5 == 4) $ error $ "wrong number of Test1 rows " ++ show a5
test4 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test4 = do
liftIO $ putStrLn "\n*** in test4\n"
a1 <- insert $ Asm "NewAsm1" "description for newasm1"
x11 <- insert $ Xsd "NewXsd11" "description for newxsd11" a1
liftIO $ putStrLn $ "x11=" ++ show x11
l111 <- insert $ Line "NewLine111" "description for newline111" 10 Xsd_string x11
liftIO $ putStrLn $ "l111=" ++ show l111
l112 <- insert $ Line "NewLine112" "description for newline112" 11 Xsd_boolean x11
liftIO $ putStrLn $ "l112=" ++ show l112
l113 <- insert $ Line "NewLine113" "description for newline113" 12 Xsd_decimal x11
liftIO $ putStrLn $ "l113=" ++ show l113
l114 <- insert $ Line "NewLine114" "description for newline114" 15 Xsd_int x11
liftIO $ putStrLn $ "l114=" ++ show l114
x12 <- insert $ Xsd "NewXsd12" "description for newxsd12" a1
liftIO $ putStrLn $ "x12=" ++ show x12
l121 <- insert $ Line "NewLine121" "description for newline1" 12 Xsd_int x12
liftIO $ putStrLn $ "l121=" ++ show l121
l122 <- insert $ Line "NewLine122" "description for newline2" 19 Xsd_boolean x12
liftIO $ putStrLn $ "l122=" ++ show l122
l123 <- insert $ Line "NewLine123" "description for newline3" 13 Xsd_string x12
liftIO $ putStrLn $ "l123=" ++ show l123
l124 <- insert $ Line "NewLine124" "description for newline4" 99 Xsd_double x12
liftIO $ putStrLn $ "l124=" ++ show l124
l125 <- insert $ Line "NewLine125" "description for newline5" 2 Xsd_boolean x12
liftIO $ putStrLn $ "l125=" ++ show l125
a2 <- insert $ Asm "NewAsm2" "description for newasm2"
liftIO $ putStrLn $ "a2=" ++ show a2
a3 <- insert $ Asm "NewAsm3" "description for newasm3"
liftIO $ putStrLn $ "a3=" ++ show a3
x31 <- insert $ Xsd "NewXsd31" "description for newxsd311" a3
liftIO $ putStrLn $ "x31=" ++ show x31
a4 <- selectList ([] :: [Filter Asm]) []
liftIO $ putStrLn "a4="
liftIO $ mapM_ print a4
unless (length a4 == 3) $ error $ "wrong number of Asm rows " ++ show a4
a5 <- selectList ([] :: [Filter Xsd]) []
liftIO $ putStrLn "a5="
liftIO $ mapM_ print a5
unless (length a5 == 3) $ error $ "wrong number of Xsd rows " ++ show a5
a6 <- selectList ([] :: [Filter Line]) []
liftIO $ putStrLn "a6="
liftIO $ mapM_ print a6
unless (length a6 == 9) $ error $ "wrong number of Line rows " ++ show a6
[Value mpos] <- select $
from $ \ln -> do
where_ (ln ^. LineXsdid E.==. E.val x11)
return $ E.joinV $ E.max_ (E.just (ln ^. LinePos))
liftIO $ putStrLn $ "mpos=" ++ show mpos
test5 :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
test5 dbtype = do
liftIO $ putStrLn "\n*** in test5\n"
a1 <- insert $ Testother (Just "abc") "zzzz"
liftIO $ putStrLn $ "a1=" ++ show a1
case dbtype of
DB2 {} -> liftIO $ putStrLn $ show dbtype ++ " insert multiple blob fields with a null fails"
_ -> do
a2 <- insert $ Testother Nothing "aaa"
liftIO $ putStrLn $ "a2=" ++ show a2
a3 <- insert $ Testother (Just "nnn") "bbb"
liftIO $ putStrLn $ "a3=" ++ show a3
a4 <- insert $ Testother (Just "ddd") "mmm"
liftIO $ putStrLn $ "a4=" ++ show a4
xs <- case dbtype of
can not sort blobs in oracle
can not sort blobs in db2 ?
_ -> selectList [] [Desc TestotherBs1]
liftIO $ putStrLn $ "xs=" ++ show xs
case dbtype of
Oracle {} -> return ()
DB2 {} -> return ()
_ -> do
ys <- selectList [] [Desc TestotherBs2]
liftIO $ putStrLn $ "ys=" ++ show ys
a7 <- selectList ([] :: [Filter Testother]) []
case dbtype of
DB2 {} -> unless (length a7 == 3) $ error $ show dbtype ++ " :wrong number of Testother rows " ++ show a7
_ -> unless (length a7 == 4) $ error $ "wrong number of Testother rows " ++ show a7
liftIO $ putStrLn "end of test5"
test6 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test6 = do
liftIO $ putStrLn "\n*** in test6\n"
r1 <- insert $ Testrational (4%6)
r2 <- insert $ Testrational (13 % 14)
liftIO $ putStrLn $ "r1=" ++ show r1
liftIO $ putStrLn $ "r2=" ++ show r2
zs <- selectList [] [Desc TestrationalRat]
liftIO $ putStrLn "zs="
liftIO $ mapM_ print zs
h1 <- insert $ Testhtml $ preEscapedToMarkup ("<p>hello</p>"::String)
liftIO $ putStrLn $ "h1=" ++ show h1
a1 <- selectList ([] :: [Filter Testrational]) []
unless (length a1 == 2) $ error $ "wrong number of Testrational rows " ++ show a1
a2 <- selectList ([] :: [Filter Testhtml]) []
unless (length a2 == 1) $ error $ "wrong number of Testhtml rows "
test7 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test7 = do
liftIO $ putStrLn "\n*** in test7\n"
a1 <- selectList [] [Desc LinePos, LimitTo 2, OffsetBy 3]
liftIO $ putStrLn $ show (length a1) ++ " rows: limit=2,offset=3 a1="
liftIO $ mapM_ print a1
a2 <- selectList [] [Desc LinePos, LimitTo 2]
liftIO $ putStrLn $ show (length a2) ++ " rows: limit=2 a2="
liftIO $ mapM_ print a2
a3 <- selectList [] [Desc LinePos, OffsetBy 3]
liftIO $ putStrLn $ show (length a3) ++ " rows: offset=3 a3="
liftIO $ mapM_ print a3
test8 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test8 = do
liftIO $ putStrLn "\n*** in test8\n"
xs <- select $
from $ \ln -> do
where_ (ln ^. LinePos E.>=. E.val 0)
E.orderBy [E.asc (ln ^. LinePos)]
E.limit 2
E.offset 3
return ln
liftIO $ putStrLn $ show (length xs) ++ " rows: limit=2 offset=3 xs=" ++ show xs
test9 :: SqlPersistT (NoLoggingT (ResourceT IO)) ()
test9 = do
liftIO $ putStrLn "\n*** in test9\n"
a1 <- selectList [] [Desc LinePos, LimitTo 2]
liftIO $ putStrLn $ show (length a1) ++ " rows: limit=2,offset=0 a1="
liftIO $ mapM_ print a1
a2 <- selectList [] [Desc LinePos, LimitTo 4]
liftIO $ putStrLn $ show (length a2) ++ " rows: limit=4,offset=0 a2="
liftIO $ mapM_ print a2
test10 :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
test10 dbtype = do
liftIO $ putStrLn "\n*** in test10\n"
a1 <- insert $ Testblob3 "abc1" "def1" "zzzz1"
liftIO $ putStrLn $ "a1=" ++ show a1
a2 <- insert $ Testblob3 "abc2" "def2" "test2"
liftIO $ putStrLn $ "a2=" ++ show a2
case dbtype of
Oracle {} -> liftIO $ putStrLn "skipping insert empty string into oracle blob column (treated as a null)"
_ -> void $ insert $ Testblob3 "" "hello3" "world3"
ys <- selectList ([] :: [Filter Testblob3]) []
liftIO $ putStrLn "ys="
liftIO $ mapM_ print ys
a3 <- selectList ([] :: [Filter Testblob3]) []
case dbtype of
Oracle {} -> unless (length a3 == 2) $ error $ show dbtype ++ " :wrong number of Testblob3 rows " ++ show a3
_ -> unless (length a3 == 3) $ error $ "wrong number of Testblob3 rows " ++ show a3
liftIO $ mapM_ print a3
test11 :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
test11 dbtype = do
liftIO $ putStrLn "\n*** in test11\n"
case dbtype of
MSSQL {} -> liftIO $ putStrLn $ show dbtype ++ ":inserting null in a blob not supported so skipping"
DB2 {} -> liftIO $ putStrLn $ show dbtype ++ ":inserting null in a blob not supported so skipping"
_ -> do
_ <- insert $ Testblob Nothing
return ()
_ <- insert $ Testblob $ Just "some data for testing"
_ <- insert $ Testblob $ Just "world"
liftIO $ putStrLn "after testblob inserts"
mssql fails if there is a null in a blog column
liftIO $ putStrLn $ "testblob xs="
liftIO $ mapM_ print xs
a1 <- selectList ([] :: [Filter Testblob]) []
case dbtype of
MSSQL {} -> unless (length a1 == 2) $ error $ show dbtype ++ " :wrong number of Testblob rows " ++ show a1
DB2 {} -> unless (length a1 == 2) $ error $ show dbtype ++ " :wrong number of Testblob rows " ++ show a1
_ -> unless (length a1 == 3) $ error $ "wrong number of Testblob rows " ++ show a1
test12 :: DBType -> SqlPersistT (NoLoggingT (ResourceT IO)) ()
test12 dbtype = do
liftIO $ putStrLn "\n*** in test12\n"
a1 <- insert $ Testlen "txt1" "str1" "bs1" (Just "txt1m") (Just "str1m") (Just "bs1m")
liftIO $ putStrLn $ "a1=" ++ show a1
a2 <- insert $ Testlen "txt2" "str2" "bs2" (Just "aaaa") (Just "str2m") (Just "bs2m")
liftIO $ putStrLn $ "a2=" ++ show a2
a3 <- selectList ([] :: [Filter Testlen]) []
case dbtype of
Oracle { } - > unless ( length a3 = = 2 ) $ error $ show dbtype + + " : wrong number of Testlen rows " + + show a3
_ -> unless (length a3 == 2) $ error $ "wrong number of Testlen rows " ++ show a3
liftIO $ putStrLn $ "a3="
liftIO $ mapM_ print a3
limitoffset :: DBType -> Bool
trace ( " limitoffset dbtype= " + + show dbtype ) $
case dbtype of
Oracle False -> False
MSSQL False -> False
_ -> True
main2 :: IO ()
main2 = do
let = " = mssql_test ; Trusted_Connection = True "
let connectionString = "dsn=db2_test"
conn <- H.connectODBC connectionString
putStrLn "\n1\n"
stmt1 <- H.prepare conn "select * from test93"
putStrLn "\n2\n"
vals1 <- H.execute stmt1 []
print vals1
putStrLn "\n3\n"
results1 <- H.fetchAllRowsAL stmt1
putStrLn "\n4\n"
forM_ (zip [1::Int ..] results1) $ \(i,x) -> putStrLn $ "i=" ++ show i ++ " result=" ++ show x
putStrLn "\na\n"
putStrLn " \nc\n "
stmt2 <- H.prepare conn "insert into test93 values(blob(?))"
putStrLn "\nd\n"
vals2 <- H.execute stmt2 [H.SqlByteString "hello world"]
putStrLn "\ne\n"
print vals2
" \n5\n "
stmt3 <- H.prepare conn "insert into testblob (bs1) values(?)"
putStrLn "\n6\n"
vals3a <- H.execute stmt3 [H.SqlNull]
putStrLn $ "vals3a=" ++ show vals3a
putStrLn "\n7\n"
vals3b <- H.execute stmt3 [H.SqlNull]
putStrLn $ "vals3b=" ++ show vals3b
putStrLn "\n8\n"
vals3c <- H.execute stmt3 [H.SqlNull]
putStrLn $ "vals3c=" ++ show vals3c
putStrLn "\n9\n"
results2 <- H.fetchAllRowsAL stmt2
forM_ (zip [1::Int ..] results2) $ \(i,x) -> putStrLn $ "i=" ++ show i ++ " result=" ++ show x
putStrLn "\nTESTBLOB worked\n"
stmt conn " insert into ( bs1,bs2 ) values(convert(varbinary(max),?),convert(varbinary(max ) , ? ) ) "
stmt4 <- H.prepare conn "insert into testother (bs1,bs2) values(convert(varbinary(max), cast (? as varchar(100))),convert(varbinary(max), cast (? as varchar(100))))"
vals4 <- H.execute stmt4 [H.SqlByteString "hello",H.SqlByteString "test"]
putStrLn $ "vals4=" ++ show vals4
vals < - H.execute [ , H.SqlByteString " test " ]
putStrLn "\nTESTOTHER worked\n"
H.commit conn
main3 :: IO ()
main3 = do
let = " = pg_test "
let connectionString = "dsn=mysql_test"
let = " = mssql_test ; Trusted_Connection = True "
let = " = oracle_test "
let = " = db2_test "
conn <- H.connectODBC connectionString
putStrLn "\n1\n"
putStrLn $ "drivername=" ++ H.hdbcDriverName conn
putStrLn $ "clientver=" ++ H.hdbcClientVer conn
putStrLn $ "proxied drivername=" ++ H.proxiedClientName conn
putStrLn $ "proxied clientver=" ++ H.proxiedClientVer conn
putStrLn $ "serverver=" ++ H.dbServerVer conn
mssql
let lenfn="length "
a <- H.describeTable conn "persony"
print a
stmt1 <- H.prepare conn ("update \"persony\" set \"name\" = ? where \"id\" >= ?")
putStrLn "\n2\n"
vals1 <- H.execute stmt1 [H.SqlString "dooble and stuff", H.toSql (1 :: Integer)]
print vals1
putStrLn "\n3\n"
stmt2 <- H.prepare conn ("select \"id\","++lenfn++"(\"name\"),\"name\" from \"persony\"")
putStrLn "\n4\n"
vals2 <- H.execute stmt2 []
print vals2
results <- H.fetchAllRowsAL' stmt2
mapM_ print results
H.commit conn
main4 :: IO ()
main4 = do
let = " = pg_test "
let connectionString = "dsn=mysql_test"
let = " = mssql_test ; Trusted_Connection = True "
let = " = oracle_test "
let = " = db2_test "
conn <- H.connectODBC connectionString
putStrLn "\nbefore create\n"
stmt1 <- H.prepare conn "create table fred (nm varchar(100) not null)"
a1 <- H.execute stmt1 []
print a1
putStrLn "\nbefore insert\n"
stmt2 <- H.prepare conn "insert into fred values(?)"
a2 <- H.execute stmt2 [H.SqlString "hello"]
print a2
putStrLn "\nbefore select\n"
stmt3 <- H.prepare conn "select nm,length(nm) from fred"
vals3 <- H.execute stmt3 []
print vals3
results3 <- H.fetchAllRowsAL' stmt3
putStrLn "select after insert"
print results3
putStrLn "\nbefore update\n"
stmt4 <- H.prepare conn "update fred set nm=?"
a4 <- H.execute stmt4 [H.SqlString "worldly"]
print a4
putStrLn "\nbefore select #2\n"
stmt5 <- H.prepare conn "select nm,length(nm) from fred"
vals5 <- H.execute stmt5 []
print vals5
results <- H.fetchAllRowsAL' stmt5
putStrLn "select after update"
print results
H.commit conn
|
baafb4ee62a6016e763a57b683aad1f082ec331e89c24d05257fd72c51bab6b9 | babashka/babashka | instant.clj | (ns babashka.impl.clojure.instant
(:require [clojure.instant :as i]
[sci.core :as sci]))
(def ins (sci/create-ns 'clojure.instant nil))
(def instant-namespace
{'read-instant-date (sci/copy-var i/read-instant-date ins)
'parse-timestamp (sci/copy-var i/parse-timestamp ins)})
| null | https://raw.githubusercontent.com/babashka/babashka/76accde8dabe2acc24bb1b025345d4c4093bcbec/src/babashka/impl/clojure/instant.clj | clojure | (ns babashka.impl.clojure.instant
(:require [clojure.instant :as i]
[sci.core :as sci]))
(def ins (sci/create-ns 'clojure.instant nil))
(def instant-namespace
{'read-instant-date (sci/copy-var i/read-instant-date ins)
'parse-timestamp (sci/copy-var i/parse-timestamp ins)})
|
|
699f00770049978d500499857f3b7992c0a1fd42e20191cf2249d500b728f253 | jsarracino/spyder | Imp.hs | module Language.Spyder.AST.Imp (
Statement(..)
, Expr(..)
, Bop(..)
, Uop(..)
, Type(..)
, Block(..)
, VDecl
, stripTy
) where
data Bop =
Plus | Minus | Mul | Div
| Lt | Gt | Le | Ge | And | Or | Eq | Neq | Mod
deriving (Eq, Show, Ord)
-- Numeric negation and boolean negation
data Uop =
Neg | Not
deriving (Eq, Show, Ord)
data Expr =
VConst String -- Variables
| IConst Int -- Integers
Booleans
| AConst [Expr] -- Arrays
| BinOp Bop Expr Expr -- Binary operations
Unary operations
| Index Expr Expr -- Array indexing e.g. foo[bar]
| App Expr [Expr] -- function calls (not procedure calls)
deriving (Eq, Show, Ord)
data Type =
IntTy
| BoolTy
| ArrTy Type
deriving (Eq, Show, Ord)
type VDecl = (String, Type)
stripTy :: VDecl -> String
stripTy = fst
-- simple statements
data Statement =
Decl VDecl (Maybe Expr) -- variable decls
| Assgn String Expr -- assignment e.g. x = y
| For [VDecl] (Maybe String) [Expr] Block -- forin loops with optional index capture
| Cond Expr Block Block
| While Expr Block -- while loops
deriving (Eq, Show, Ord)
-- complex statements
data Block =
Seq [Statement]
deriving (Eq, Show, Ord)
| null | https://raw.githubusercontent.com/jsarracino/spyder/a2f6d08eb2a3907d31a89ae3d942b50aaba96a88/Language/Spyder/AST/Imp.hs | haskell | Numeric negation and boolean negation
Variables
Integers
Arrays
Binary operations
Array indexing e.g. foo[bar]
function calls (not procedure calls)
simple statements
variable decls
assignment e.g. x = y
forin loops with optional index capture
while loops
complex statements | module Language.Spyder.AST.Imp (
Statement(..)
, Expr(..)
, Bop(..)
, Uop(..)
, Type(..)
, Block(..)
, VDecl
, stripTy
) where
data Bop =
Plus | Minus | Mul | Div
| Lt | Gt | Le | Ge | And | Or | Eq | Neq | Mod
deriving (Eq, Show, Ord)
data Uop =
Neg | Not
deriving (Eq, Show, Ord)
data Expr =
Booleans
Unary operations
deriving (Eq, Show, Ord)
data Type =
IntTy
| BoolTy
| ArrTy Type
deriving (Eq, Show, Ord)
type VDecl = (String, Type)
stripTy :: VDecl -> String
stripTy = fst
data Statement =
| Cond Expr Block Block
deriving (Eq, Show, Ord)
data Block =
Seq [Statement]
deriving (Eq, Show, Ord)
|
e184cc34e0a3997094f2eb477bbfb47a4c83fa4617bb0c039c34c9bf71965425 | agajews/soup-lang | Bootstrap.hs | # LANGUAGE FlexibleContexts #
module Soup.Bootstrap (
initType,
) where
import Soup.Builtins
import Soup.Env
import Soup.Eval
import Soup.Parser
import Soup.Value
import Control.Monad.Except
import Data.Char
import qualified Data.Map as Map
initType :: Eval Value
initType = do
pexpType <- genIdent "pexp"
let pexpFun = parserToVal "'pexp" $ pexpParser pexpType
let lambdaFun = parserToVal "lambda" $ lambdaParser pexpType
let funFun = parserToVal "fun" $ funParser pexpType
let funcCallFun = parserToVal "func-call" $ parseFuncCall pexpType
let runFun = parserToVal "run" $ parseRun pexpType
topType <- genIdent "top"
let topFun = parserToVal "'top" $ topTypeParser topType
let intFun = parserToVal "int" parseInt
let strFun = parserToVal "str" parseStr
let builtinParsers = map builtinParser builtins
setVar pexpType $ ListVal $ [
pexpFun,
topFun,
lambdaFun,
funFun,
funcCallFun,
runFun,
intFun,
strFun] ++ builtinParsers
setVar topType $ ListVal [parserToVal "pexp" $ parseType pexpType]
return $ ListVal [parserToVal "top" $ topParser topType]
pexpParser :: Ident -> Parser Value
pexpParser n = literalParser "pexp" $ Variable n
topTypeParser :: Ident -> Parser Value
topTypeParser n = literalParser "top" $ Variable n
topParser :: Ident -> Parser Value
topParser topType = do
parseNewlines'
vals <- parseInterspersed (parseType topType) parseNewlines
parseNewlines'
return $ ListVal vals
literalParser :: String -> Value -> Parser Value
literalParser s v = parseString s >> (logDebug $ "'" ++ s) >> return v
lambdaParser :: Ident -> Parser Value
lambdaParser pexp = do
parseString "(lambda"
logDebug "(lambda"
parseWS
parseString "("
paramNames <- parseInterspersed' parseIdent parseWS
paramIdents <- liftEval $ mapM genIdent paramNames
let paramParsers = zipWith literalParser paramNames (map Variable paramIdents)
parseString ")"
logDebug $ (concat $ map (\n -> n ++ " ") paramNames) ++ "."
parseWS
liftEval $ modifyVar pexp (pushRules paramNames paramParsers)
body <- parseType pexp
liftEval $ modifyVar pexp popRules
parseString ")"
logDebug ")"
return $ lambdaBuilder paramIdents body
lambdaBuilder :: [Ident] -> Value -> Value
lambdaBuilder paramIdents body =
FuncCall (macro' "lambda-builder" lambdaBuilder') []
where
lambdaBuilder' _ = do
scope <- getScope
return $ Lambda paramIdents scope body
funParser :: Ident -> Parser Value
funParser pexp = do
parseString "(fun"
logDebug "(fun"
parseWS
parseString "("
paramNames <- parseInterspersed' parseIdent parseWS
paramIdents <- liftEval $ mapM genIdent paramNames
let paramParsers = zipWith literalParser paramNames (map Variable paramIdents)
parseString ")"
logDebug $ (concat $ map (\n -> n ++ " ") paramNames) ++ "."
parseWS
liftEval $ modifyVar pexp (pushRules paramNames paramParsers)
body <- parseType pexp
liftEval $ modifyVar pexp popRules
parseString ")"
logDebug ")"
scopeIdent <- liftEval $ genIdent "@@"
let funBuilder' = function' "fun-builder" funBuilder
return $ FuncCall funBuilder' [lambdaBuilder (scopeIdent : paramIdents) body]
funBuilder :: [Value] -> Eval Value
funBuilder [l@(Lambda _ _ _)] = return $ function' "fun-wrapper" $ funWrapper l
funBuilder _ = throwError InvalidArguments
funWrapper :: Value -> [Value] -> Eval Value
funWrapper (l@(Lambda _ _ _)) args = eval $ FuncCall l args
funWrapper _ _ = throwError InvalidArguments
pushRules :: [String] -> [Parser Value] -> Value -> Eval Value
pushRules names ps l@(ListVal _) = do
return $ ListVal $ (zipWith parserToVal names ps) ++ [l]
pushRules _ _ v = throwError $ InvalidType v
popRules :: Value -> Eval Value
popRules v = do
popRules' v
where
popRules' (ListVal (_:y:ys)) = popRules' (ListVal (y:ys))
popRules' (ListVal [ListVal l]) = return $ ListVal l
popRules' x = throwError $ InvalidType x
parseFuncCall :: Ident -> Parser Value
parseFuncCall pexp = do
parseString "("
logDebug "("
fun <- parseType pexp
logDebug "."
args <- catchFail (return []) $ do
parseWS
parseInterspersed (parseType pexp) parseWS
parseString ")"
logDebug ")"
return $ FuncCall fun args
parseRun :: Ident -> Parser Value
parseRun pexp = do
parseString "(run"
logDebug "(run"
parseWS
expr <- parseType pexp
parseString ")"
logDebug ")"
liftEval $ do
scope <- getScope
setScope []
res <- eval expr
setScope scope
return res
parseInt :: Parser Value
parseInt = do
digits <- parseWhile isDigit
let num = read digits
logDebug $ show num
return $ IntVal num
parseStr :: Parser Value
parseStr = do
parseString "\""
logDebug "\""
s <- takeString
logDebug $ drop 1 (show s)
return $ StringVal s
where
takeString = do
c <- takeChar
if null c
then return c
else do
s <- takeString
return $ c ++ s
takeChar = Parser $ \s c -> case s of
('"':xs) -> c "" xs
('\\':x:xs) -> if Map.member x codes
then c [codes Map.! x] xs
else c [x] xs
('\\':[]) -> return []
(x:xs) -> c [x] xs
"" -> return []
codes = Map.fromList [('b', '\b'), ('n', '\n'), ('f', '\f'), ('r', '\r'),
('t', '\t'), ('\\', '\\'), ('\"', '\"')]
isWhitespace :: Char -> Bool
isWhitespace = (`elem` [' ', '\n', '\t'])
parseWS :: Parser ()
parseWS = parseWhile isWhitespace >> return ()
parseNewlines :: Parser ()
parseNewlines = parseWhile (== '\n') >> return ()
parseNewlines' :: Parser ()
parseNewlines' = parseWhile' (== '\n') >> return ()
parseIdent :: Parser String
parseIdent = do
name <- parseWhile $ liftM2 (||) isAlphaNum (`elem` "~!@#$%^&*-=+_|'<>?")
if all isDigit name
then parserFail
else return name
builtinParser :: (String, Value) -> Value
builtinParser (name, f) = parserToVal name $ literalParser name f
| null | https://raw.githubusercontent.com/agajews/soup-lang/1c926f5853fe18244e33f0f90830db49f7fb827e/Soup/Bootstrap.hs | haskell | # LANGUAGE FlexibleContexts #
module Soup.Bootstrap (
initType,
) where
import Soup.Builtins
import Soup.Env
import Soup.Eval
import Soup.Parser
import Soup.Value
import Control.Monad.Except
import Data.Char
import qualified Data.Map as Map
initType :: Eval Value
initType = do
pexpType <- genIdent "pexp"
let pexpFun = parserToVal "'pexp" $ pexpParser pexpType
let lambdaFun = parserToVal "lambda" $ lambdaParser pexpType
let funFun = parserToVal "fun" $ funParser pexpType
let funcCallFun = parserToVal "func-call" $ parseFuncCall pexpType
let runFun = parserToVal "run" $ parseRun pexpType
topType <- genIdent "top"
let topFun = parserToVal "'top" $ topTypeParser topType
let intFun = parserToVal "int" parseInt
let strFun = parserToVal "str" parseStr
let builtinParsers = map builtinParser builtins
setVar pexpType $ ListVal $ [
pexpFun,
topFun,
lambdaFun,
funFun,
funcCallFun,
runFun,
intFun,
strFun] ++ builtinParsers
setVar topType $ ListVal [parserToVal "pexp" $ parseType pexpType]
return $ ListVal [parserToVal "top" $ topParser topType]
pexpParser :: Ident -> Parser Value
pexpParser n = literalParser "pexp" $ Variable n
topTypeParser :: Ident -> Parser Value
topTypeParser n = literalParser "top" $ Variable n
topParser :: Ident -> Parser Value
topParser topType = do
parseNewlines'
vals <- parseInterspersed (parseType topType) parseNewlines
parseNewlines'
return $ ListVal vals
literalParser :: String -> Value -> Parser Value
literalParser s v = parseString s >> (logDebug $ "'" ++ s) >> return v
lambdaParser :: Ident -> Parser Value
lambdaParser pexp = do
parseString "(lambda"
logDebug "(lambda"
parseWS
parseString "("
paramNames <- parseInterspersed' parseIdent parseWS
paramIdents <- liftEval $ mapM genIdent paramNames
let paramParsers = zipWith literalParser paramNames (map Variable paramIdents)
parseString ")"
logDebug $ (concat $ map (\n -> n ++ " ") paramNames) ++ "."
parseWS
liftEval $ modifyVar pexp (pushRules paramNames paramParsers)
body <- parseType pexp
liftEval $ modifyVar pexp popRules
parseString ")"
logDebug ")"
return $ lambdaBuilder paramIdents body
lambdaBuilder :: [Ident] -> Value -> Value
lambdaBuilder paramIdents body =
FuncCall (macro' "lambda-builder" lambdaBuilder') []
where
lambdaBuilder' _ = do
scope <- getScope
return $ Lambda paramIdents scope body
funParser :: Ident -> Parser Value
funParser pexp = do
parseString "(fun"
logDebug "(fun"
parseWS
parseString "("
paramNames <- parseInterspersed' parseIdent parseWS
paramIdents <- liftEval $ mapM genIdent paramNames
let paramParsers = zipWith literalParser paramNames (map Variable paramIdents)
parseString ")"
logDebug $ (concat $ map (\n -> n ++ " ") paramNames) ++ "."
parseWS
liftEval $ modifyVar pexp (pushRules paramNames paramParsers)
body <- parseType pexp
liftEval $ modifyVar pexp popRules
parseString ")"
logDebug ")"
scopeIdent <- liftEval $ genIdent "@@"
let funBuilder' = function' "fun-builder" funBuilder
return $ FuncCall funBuilder' [lambdaBuilder (scopeIdent : paramIdents) body]
funBuilder :: [Value] -> Eval Value
funBuilder [l@(Lambda _ _ _)] = return $ function' "fun-wrapper" $ funWrapper l
funBuilder _ = throwError InvalidArguments
funWrapper :: Value -> [Value] -> Eval Value
funWrapper (l@(Lambda _ _ _)) args = eval $ FuncCall l args
funWrapper _ _ = throwError InvalidArguments
pushRules :: [String] -> [Parser Value] -> Value -> Eval Value
pushRules names ps l@(ListVal _) = do
return $ ListVal $ (zipWith parserToVal names ps) ++ [l]
pushRules _ _ v = throwError $ InvalidType v
popRules :: Value -> Eval Value
popRules v = do
popRules' v
where
popRules' (ListVal (_:y:ys)) = popRules' (ListVal (y:ys))
popRules' (ListVal [ListVal l]) = return $ ListVal l
popRules' x = throwError $ InvalidType x
parseFuncCall :: Ident -> Parser Value
parseFuncCall pexp = do
parseString "("
logDebug "("
fun <- parseType pexp
logDebug "."
args <- catchFail (return []) $ do
parseWS
parseInterspersed (parseType pexp) parseWS
parseString ")"
logDebug ")"
return $ FuncCall fun args
parseRun :: Ident -> Parser Value
parseRun pexp = do
parseString "(run"
logDebug "(run"
parseWS
expr <- parseType pexp
parseString ")"
logDebug ")"
liftEval $ do
scope <- getScope
setScope []
res <- eval expr
setScope scope
return res
parseInt :: Parser Value
parseInt = do
digits <- parseWhile isDigit
let num = read digits
logDebug $ show num
return $ IntVal num
parseStr :: Parser Value
parseStr = do
parseString "\""
logDebug "\""
s <- takeString
logDebug $ drop 1 (show s)
return $ StringVal s
where
takeString = do
c <- takeChar
if null c
then return c
else do
s <- takeString
return $ c ++ s
takeChar = Parser $ \s c -> case s of
('"':xs) -> c "" xs
('\\':x:xs) -> if Map.member x codes
then c [codes Map.! x] xs
else c [x] xs
('\\':[]) -> return []
(x:xs) -> c [x] xs
"" -> return []
codes = Map.fromList [('b', '\b'), ('n', '\n'), ('f', '\f'), ('r', '\r'),
('t', '\t'), ('\\', '\\'), ('\"', '\"')]
isWhitespace :: Char -> Bool
isWhitespace = (`elem` [' ', '\n', '\t'])
parseWS :: Parser ()
parseWS = parseWhile isWhitespace >> return ()
parseNewlines :: Parser ()
parseNewlines = parseWhile (== '\n') >> return ()
parseNewlines' :: Parser ()
parseNewlines' = parseWhile' (== '\n') >> return ()
parseIdent :: Parser String
parseIdent = do
name <- parseWhile $ liftM2 (||) isAlphaNum (`elem` "~!@#$%^&*-=+_|'<>?")
if all isDigit name
then parserFail
else return name
builtinParser :: (String, Value) -> Value
builtinParser (name, f) = parserToVal name $ literalParser name f
|
|
2627934721da1c2cce5c35a63265225cab9d391530b6ae519f5e3be881784e6d | brendanhay/amazonka | DocumentSourceType.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
{-# LANGUAGE StrictData #-}
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - imports #
Derived from AWS service descriptions , licensed under Apache 2.0 .
-- |
Module : Amazonka . WorkDocs . Types . DocumentSourceType
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
module Amazonka.WorkDocs.Types.DocumentSourceType
( DocumentSourceType
( ..,
DocumentSourceType_ORIGINAL,
DocumentSourceType_WITH_COMMENTS
),
)
where
import qualified Amazonka.Core as Core
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
newtype DocumentSourceType = DocumentSourceType'
{ fromDocumentSourceType ::
Data.Text
}
deriving stock
( Prelude.Show,
Prelude.Read,
Prelude.Eq,
Prelude.Ord,
Prelude.Generic
)
deriving newtype
( Prelude.Hashable,
Prelude.NFData,
Data.FromText,
Data.ToText,
Data.ToByteString,
Data.ToLog,
Data.ToHeader,
Data.ToQuery,
Data.FromJSON,
Data.FromJSONKey,
Data.ToJSON,
Data.ToJSONKey,
Data.FromXML,
Data.ToXML
)
pattern DocumentSourceType_ORIGINAL :: DocumentSourceType
pattern DocumentSourceType_ORIGINAL = DocumentSourceType' "ORIGINAL"
pattern DocumentSourceType_WITH_COMMENTS :: DocumentSourceType
pattern DocumentSourceType_WITH_COMMENTS = DocumentSourceType' "WITH_COMMENTS"
# COMPLETE
DocumentSourceType_ORIGINAL ,
DocumentSourceType_WITH_COMMENTS ,
DocumentSourceType '
#
DocumentSourceType_ORIGINAL,
DocumentSourceType_WITH_COMMENTS,
DocumentSourceType'
#-}
| null | https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-workdocs/gen/Amazonka/WorkDocs/Types/DocumentSourceType.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - imports #
Derived from AWS service descriptions , licensed under Apache 2.0 .
Module : Amazonka . WorkDocs . Types . DocumentSourceType
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Amazonka.WorkDocs.Types.DocumentSourceType
( DocumentSourceType
( ..,
DocumentSourceType_ORIGINAL,
DocumentSourceType_WITH_COMMENTS
),
)
where
import qualified Amazonka.Core as Core
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
newtype DocumentSourceType = DocumentSourceType'
{ fromDocumentSourceType ::
Data.Text
}
deriving stock
( Prelude.Show,
Prelude.Read,
Prelude.Eq,
Prelude.Ord,
Prelude.Generic
)
deriving newtype
( Prelude.Hashable,
Prelude.NFData,
Data.FromText,
Data.ToText,
Data.ToByteString,
Data.ToLog,
Data.ToHeader,
Data.ToQuery,
Data.FromJSON,
Data.FromJSONKey,
Data.ToJSON,
Data.ToJSONKey,
Data.FromXML,
Data.ToXML
)
pattern DocumentSourceType_ORIGINAL :: DocumentSourceType
pattern DocumentSourceType_ORIGINAL = DocumentSourceType' "ORIGINAL"
pattern DocumentSourceType_WITH_COMMENTS :: DocumentSourceType
pattern DocumentSourceType_WITH_COMMENTS = DocumentSourceType' "WITH_COMMENTS"
# COMPLETE
DocumentSourceType_ORIGINAL ,
DocumentSourceType_WITH_COMMENTS ,
DocumentSourceType '
#
DocumentSourceType_ORIGINAL,
DocumentSourceType_WITH_COMMENTS,
DocumentSourceType'
#-}
|
3f3e1c8995155a31940063efffd6ec43664fb0f4a1ea6e8b757581e6cdb264c9 | dnaeon/cl-migratum | test-suite.lisp | Copyright ( c ) 2020 - 2022 Nikolov < >
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
1 . Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer
;; in this position and unchanged.
2 . Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S ) ` ` AS IS '' AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;; IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT
NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(defpackage :cl-migratum.test
(:use :cl :rove)
(:nicknames :migratum.test)
(:import-from :tmpdir)
(:import-from :asdf)
(:import-from :cl-dbi)
(:import-from
:migratum
:provider-init
:provider-shutdown
:provider-name
:provider-initialized
:provider-list-migrations
:provider-create-migration
:find-migration-by-id
:migration-id
:migration-kind
:migration-description
:migration-load
:driver-name
:driver-init
:driver-shutdown
:driver-initialized
:driver-list-applied
:contains-applied-migrations-p
:latest-migration
:list-pending
:apply-pending
:revert-last
:apply-next
:make-migration-id)
(:import-from :migratum.provider.local-path)
(:import-from :migratum.driver.dbi)
(:import-from :migratum.driver.rdbms-postgresql))
(in-package :cl-migratum.test)
(defparameter *migrations-path*
(asdf:system-relative-pathname :cl-migratum.test "t/migrations/")
"Path to the migration files")
(defparameter *tmpdir*
nil
"Temp directory used during tests")
(defparameter *sqlite-conn*
nil
"CL-DBI connection used during tests")
(defparameter *dbi-driver*
nil
"DBI driver used during tests")
(defparameter *rdbms-postgresql-driver*
nil
"Driver from library hu.dwim.rdbms for PostgreSQL")
(defparameter *provider*
nil
"Local path provider used during tests")
(setup
(setf *tmpdir* (tmpdir:mkdtemp))
(setf *sqlite-conn*
(cl-dbi:connect :sqlite3
:database-name (merge-pathnames (make-pathname :name "cl-migratum" :type "db")
*tmpdir*)))
(setf *provider* (cl-migratum.provider.local-path:make-provider (list *migrations-path*)))
(setf *dbi-driver*
(migratum.driver.dbi:make-driver *provider* *sqlite-conn*))
(setf *rdbms-postgresql-driver*
(migratum.driver.rdbms-postgresql:make-driver *provider*
`(:host ,(or (uiop:getenv "PGHOST") "localhost")
:database ,(or (uiop:getenv "PGDATABASE") "migratum")
:user-name ,(or (uiop:getenv "PGUSER") "migratum")
:password ,(or (uiop:getenv "PGPASSWORD") "FvbRd5qdeWHNum9p")))))
(teardown
(provider-shutdown *provider*)
(driver-shutdown *dbi-driver*)
(when *tmpdir*
(uiop:delete-directory-tree *tmpdir* :validate t)))
| null | https://raw.githubusercontent.com/dnaeon/cl-migratum/b28031405ca5a43bee85af5da6ef761ceb951d0d/t/test-suite.lisp | lisp | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer
in this position and unchanged.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | Copyright ( c ) 2020 - 2022 Nikolov < >
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S ) ` ` AS IS '' AND ANY EXPRESS OR
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
(in-package :cl-user)
(defpackage :cl-migratum.test
(:use :cl :rove)
(:nicknames :migratum.test)
(:import-from :tmpdir)
(:import-from :asdf)
(:import-from :cl-dbi)
(:import-from
:migratum
:provider-init
:provider-shutdown
:provider-name
:provider-initialized
:provider-list-migrations
:provider-create-migration
:find-migration-by-id
:migration-id
:migration-kind
:migration-description
:migration-load
:driver-name
:driver-init
:driver-shutdown
:driver-initialized
:driver-list-applied
:contains-applied-migrations-p
:latest-migration
:list-pending
:apply-pending
:revert-last
:apply-next
:make-migration-id)
(:import-from :migratum.provider.local-path)
(:import-from :migratum.driver.dbi)
(:import-from :migratum.driver.rdbms-postgresql))
(in-package :cl-migratum.test)
(defparameter *migrations-path*
(asdf:system-relative-pathname :cl-migratum.test "t/migrations/")
"Path to the migration files")
(defparameter *tmpdir*
nil
"Temp directory used during tests")
(defparameter *sqlite-conn*
nil
"CL-DBI connection used during tests")
(defparameter *dbi-driver*
nil
"DBI driver used during tests")
(defparameter *rdbms-postgresql-driver*
nil
"Driver from library hu.dwim.rdbms for PostgreSQL")
(defparameter *provider*
nil
"Local path provider used during tests")
(setup
(setf *tmpdir* (tmpdir:mkdtemp))
(setf *sqlite-conn*
(cl-dbi:connect :sqlite3
:database-name (merge-pathnames (make-pathname :name "cl-migratum" :type "db")
*tmpdir*)))
(setf *provider* (cl-migratum.provider.local-path:make-provider (list *migrations-path*)))
(setf *dbi-driver*
(migratum.driver.dbi:make-driver *provider* *sqlite-conn*))
(setf *rdbms-postgresql-driver*
(migratum.driver.rdbms-postgresql:make-driver *provider*
`(:host ,(or (uiop:getenv "PGHOST") "localhost")
:database ,(or (uiop:getenv "PGDATABASE") "migratum")
:user-name ,(or (uiop:getenv "PGUSER") "migratum")
:password ,(or (uiop:getenv "PGPASSWORD") "FvbRd5qdeWHNum9p")))))
(teardown
(provider-shutdown *provider*)
(driver-shutdown *dbi-driver*)
(when *tmpdir*
(uiop:delete-directory-tree *tmpdir* :validate t)))
|
5882c99656d9e1115228e18498296b38d0f18b73d18bb9150c008dd190b698fe | valderman/haste-compiler | Linker.hs | # LANGUAGE GeneralizedNewtypeDeriving , MultiParamTypeClasses ,
FlexibleContexts , OverloadedStrings , CPP #
FlexibleContexts, OverloadedStrings, CPP #-}
module Haste.Linker (link) where
import Haste.Config
import Haste.Module
import qualified Data.Map as M
import qualified Data.Set as S
import Control.Monad.State.Strict
import Control.Monad.Trans.Either
import Haste.AST
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString as BS
import Data.ByteString.UTF8 (toString, fromString)
import Data.ByteString.Builder
import Data.Monoid
import Data.List (sort, group)
import System.IO (hPutStrLn, stderr)
import Crypto.Hash
-- | The program entry point.
-- This will need to change when we start supporting building "binaries"
-- using cabal, since we'll have all sorts of funny package names then.
mainSym :: Name
mainSym = name "main" (Just ("main", "Main"))
-- | Link a program using the given config and input file name.
link :: Config -> BS.ByteString -> FilePath -> IO ()
link cfg pkgid target = do
let mainmod =
case mainMod cfg of
Just (m, p) -> (fromString m, fromString p)
_ -> error "Haste.Linker.link called without main sym!"
(spt, ds) <- getAllDefs cfg (targetLibPath cfg : libPaths cfg) mainmod pkgid mainSym
let myDefs = if wholeProgramOpts cfg
then topLevelInline cfg spt ds
else ds
(progText, (spt', myMain')) = prettyProg cfg mainSym spt myDefs
callMain = stringUtf8 "B(A(" <> myMain' <> stringUtf8 ", [0]));"
launchApp = appStart cfg (stringUtf8 "hasteMain")
rtslibs <- mapM readFile $ rtsLibs cfg
extlibs <- mapM readFile $ jsExternals cfg
let finalProgram = toLazyByteString $ assembleProg (wrapProg cfg)
extlibs
rtslibs
progText
callMain
launchApp
spt'
B.writeFile (outFile cfg cfg target) finalProgram
where
addHashLine p = concat
[ "var __haste_prog_id = '"
, show (hash (B.toStrict p) :: Digest SHA3_256)
, "';\n"
]
assembleProg True extlibs rtslibs progText callMain launchApp spt =
stringUtf8 (unlines extlibs)
<> stringUtf8 "function hasteMain() {\n"
<> (if useStrict cfg then stringUtf8 "\"use strict\";\n" else mempty)
<> stringUtf8 (addHashLine (toLazyByteString progText))
<> stringUtf8 "var __haste_script_elem = hasteMain.scriptElem;\n"
<> stringUtf8 (unlines rtslibs)
<> progText
<> mconcat (map addSPT spt)
<> callMain
<> stringUtf8 "};\n"
<> stringUtf8 "hasteMain.scriptElem = typeof document == 'object' ? document.currentScript : null;\n"
<> launchApp
assembleProg _ extlibs rtslibs progText callMain launchApp spt =
(if useStrict cfg then stringUtf8 "\"use strict\";\n" else mempty)
<> stringUtf8 (addHashLine (toLazyByteString progText))
<> stringUtf8 "var __haste_script_elem = typeof document == 'object' ? document.currentScript : null;\n"
<> stringUtf8 (unlines extlibs)
<> stringUtf8 (unlines rtslibs)
<> progText
<> mconcat (map addSPT spt)
<> stringUtf8 "\nvar hasteMain = function() {" <> callMain
<> stringUtf8 "};"
<> launchApp
addSPT ptr = mconcat
[ stringUtf8 "__spt_insert("
, ptr
, stringUtf8 ");\n"
]
-- | Produce an info message if verbose reporting is enabled.
info' :: Config -> String -> IO ()
info' cfg = when (verbose cfg) . hPutStrLn stderr
| Generate a sequence of all assignments needed to run Main.main .
getAllDefs :: Config
-> [FilePath]
-> (BS.ByteString, BS.ByteString)
-> BS.ByteString
-> Name
-> IO ([Name], Stm)
getAllDefs cfg libpaths mainmod pkgid mainsym =
runDep cfg mainmod $ addDef libpaths pkgid mainsym
data DepState = DepState {
mainModule :: !(BS.ByteString, BS.ByteString),
defs :: !(Stm -> Stm),
alreadySeen :: !(S.Set Name),
modules :: !(M.Map BS.ByteString Module),
infoLogger :: String -> IO (),
staticPtrs :: ![[Name]]
}
type DepM a = EitherT Name (StateT DepState IO) a
initState :: Config -> (BS.ByteString, BS.ByteString) -> DepState
initState cfg m = DepState {
mainModule = m,
defs = id,
alreadySeen = S.empty,
modules = M.empty,
infoLogger = info' cfg,
staticPtrs = []
}
-- | Log a message to stdout if verbose reporting is on.
info :: String -> DepM ()
info s = do
st <- get
liftIO $ infoLogger st s
-- | Run a dependency resolution computation.
runDep :: Show a => Config -> (BS.ByteString,BS.ByteString) -> DepM a -> IO ([Name], Stm)
runDep cfg mainmod m = do
res <- runStateT (runEitherT m) (initState cfg mainmod)
case res of
(Right _, st) ->
return (snubcat $ staticPtrs st, defs st stop)
(Left (Name f (Just (_, modul))), _) -> do
error $ msg (toString modul) (toString f)
(r, _) -> do
error $ "Impossible result in runDep: " ++ show r
where
msg "Main" "main" =
"Unable to locate a main function.\n" ++
"If your main function is not `Main.main' you must specify it using " ++
"`-main-is',\n" ++
"for instance, `-main-is MyModule.myMain'.\n" ++
"If your progam intentionally has no main function," ++
" please use `--dont-link' to avoid this error."
msg s f =
"Unable to locate function `" ++ f ++ "' in module `" ++ s ++ "'!"
-- snubcat: sort + nub + concat in O(n log n) instead of O(n²)
snubcat = map head . group . sort . concat
-- | Return the module the given variable resides in.
getModuleOf :: [FilePath] -> Name -> DepM Module
getModuleOf libpaths v@(Name n _) =
case moduleOf v of
Just "GHC.Prim" -> return foreignModule
Just "" -> return foreignModule
Nothing -> return foreignModule
Just ":Main" -> do
(p, m) <- mainModule `fmap` get
getModuleOf libpaths (Name n (Just (p, m)))
Just m -> do
mm <- getModule libpaths (maybe "main" id $ pkgOf v) m
case mm of
Just m' -> return m'
_ -> left v
-- | Return the module at the given path, loading it into cache if it's not
already there . Modules are preferentially loaded from jslib file .
getModule :: [FilePath] -> BS.ByteString -> BS.ByteString -> DepM (Maybe Module)
getModule libpaths pkgid modname = do
st <- get
case M.lookup modname (modules st) of
Just m -> do
return $ Just m
_ -> do
info $ "Linking " ++ toString modname
go libpaths
where
go (libpath:lps) = do
mm <- liftIO $ readModule libpath (toString pkgid) (toString modname)
case mm of
Just m -> do
st <- get
put st
{ modules = M.insert modname m (modules st)
, staticPtrs = modSPT m : staticPtrs st
}
mapM_ (addDef libpaths pkgid) (modSPT m)
return (Just m)
_ -> do
go lps
go [] = do
return Nothing
-- | Add a new definition and its dependencies. If the given identifier has
-- already been added, it's just ignored.
addDef :: [FilePath] -> BS.ByteString -> Name -> DepM ()
addDef libpaths pkgid v = do
st <- get
when (not $ v `S.member` alreadySeen st) $ do
m <- getModuleOf libpaths v
-- getModuleOf may update the state, so we need to refresh it
st' <- get
let dependencies = maybe S.empty id (M.lookup v (modDeps m))
put st' {alreadySeen = S.insert v (alreadySeen st')}
S.foldl' (\a x -> a >> addDef libpaths pkgid x) (return ()) dependencies
-- addDef _definitely_ updates the state, so refresh once again
st'' <- get
let Name cmnt _ = v
defs' =
maybe (defs st'')
(\body -> defs st'' . newVar True (internalVar v cmnt) body)
(M.lookup v (modDefs m))
put st'' {defs = defs'}
| null | https://raw.githubusercontent.com/valderman/haste-compiler/47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8/src/Haste/Linker.hs | haskell | | The program entry point.
This will need to change when we start supporting building "binaries"
using cabal, since we'll have all sorts of funny package names then.
| Link a program using the given config and input file name.
| Produce an info message if verbose reporting is enabled.
| Log a message to stdout if verbose reporting is on.
| Run a dependency resolution computation.
snubcat: sort + nub + concat in O(n log n) instead of O(n²)
| Return the module the given variable resides in.
| Return the module at the given path, loading it into cache if it's not
| Add a new definition and its dependencies. If the given identifier has
already been added, it's just ignored.
getModuleOf may update the state, so we need to refresh it
addDef _definitely_ updates the state, so refresh once again | # LANGUAGE GeneralizedNewtypeDeriving , MultiParamTypeClasses ,
FlexibleContexts , OverloadedStrings , CPP #
FlexibleContexts, OverloadedStrings, CPP #-}
module Haste.Linker (link) where
import Haste.Config
import Haste.Module
import qualified Data.Map as M
import qualified Data.Set as S
import Control.Monad.State.Strict
import Control.Monad.Trans.Either
import Haste.AST
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString as BS
import Data.ByteString.UTF8 (toString, fromString)
import Data.ByteString.Builder
import Data.Monoid
import Data.List (sort, group)
import System.IO (hPutStrLn, stderr)
import Crypto.Hash
mainSym :: Name
mainSym = name "main" (Just ("main", "Main"))
link :: Config -> BS.ByteString -> FilePath -> IO ()
link cfg pkgid target = do
let mainmod =
case mainMod cfg of
Just (m, p) -> (fromString m, fromString p)
_ -> error "Haste.Linker.link called without main sym!"
(spt, ds) <- getAllDefs cfg (targetLibPath cfg : libPaths cfg) mainmod pkgid mainSym
let myDefs = if wholeProgramOpts cfg
then topLevelInline cfg spt ds
else ds
(progText, (spt', myMain')) = prettyProg cfg mainSym spt myDefs
callMain = stringUtf8 "B(A(" <> myMain' <> stringUtf8 ", [0]));"
launchApp = appStart cfg (stringUtf8 "hasteMain")
rtslibs <- mapM readFile $ rtsLibs cfg
extlibs <- mapM readFile $ jsExternals cfg
let finalProgram = toLazyByteString $ assembleProg (wrapProg cfg)
extlibs
rtslibs
progText
callMain
launchApp
spt'
B.writeFile (outFile cfg cfg target) finalProgram
where
addHashLine p = concat
[ "var __haste_prog_id = '"
, show (hash (B.toStrict p) :: Digest SHA3_256)
, "';\n"
]
assembleProg True extlibs rtslibs progText callMain launchApp spt =
stringUtf8 (unlines extlibs)
<> stringUtf8 "function hasteMain() {\n"
<> (if useStrict cfg then stringUtf8 "\"use strict\";\n" else mempty)
<> stringUtf8 (addHashLine (toLazyByteString progText))
<> stringUtf8 "var __haste_script_elem = hasteMain.scriptElem;\n"
<> stringUtf8 (unlines rtslibs)
<> progText
<> mconcat (map addSPT spt)
<> callMain
<> stringUtf8 "};\n"
<> stringUtf8 "hasteMain.scriptElem = typeof document == 'object' ? document.currentScript : null;\n"
<> launchApp
assembleProg _ extlibs rtslibs progText callMain launchApp spt =
(if useStrict cfg then stringUtf8 "\"use strict\";\n" else mempty)
<> stringUtf8 (addHashLine (toLazyByteString progText))
<> stringUtf8 "var __haste_script_elem = typeof document == 'object' ? document.currentScript : null;\n"
<> stringUtf8 (unlines extlibs)
<> stringUtf8 (unlines rtslibs)
<> progText
<> mconcat (map addSPT spt)
<> stringUtf8 "\nvar hasteMain = function() {" <> callMain
<> stringUtf8 "};"
<> launchApp
addSPT ptr = mconcat
[ stringUtf8 "__spt_insert("
, ptr
, stringUtf8 ");\n"
]
info' :: Config -> String -> IO ()
info' cfg = when (verbose cfg) . hPutStrLn stderr
| Generate a sequence of all assignments needed to run Main.main .
getAllDefs :: Config
-> [FilePath]
-> (BS.ByteString, BS.ByteString)
-> BS.ByteString
-> Name
-> IO ([Name], Stm)
getAllDefs cfg libpaths mainmod pkgid mainsym =
runDep cfg mainmod $ addDef libpaths pkgid mainsym
data DepState = DepState {
mainModule :: !(BS.ByteString, BS.ByteString),
defs :: !(Stm -> Stm),
alreadySeen :: !(S.Set Name),
modules :: !(M.Map BS.ByteString Module),
infoLogger :: String -> IO (),
staticPtrs :: ![[Name]]
}
type DepM a = EitherT Name (StateT DepState IO) a
initState :: Config -> (BS.ByteString, BS.ByteString) -> DepState
initState cfg m = DepState {
mainModule = m,
defs = id,
alreadySeen = S.empty,
modules = M.empty,
infoLogger = info' cfg,
staticPtrs = []
}
info :: String -> DepM ()
info s = do
st <- get
liftIO $ infoLogger st s
runDep :: Show a => Config -> (BS.ByteString,BS.ByteString) -> DepM a -> IO ([Name], Stm)
runDep cfg mainmod m = do
res <- runStateT (runEitherT m) (initState cfg mainmod)
case res of
(Right _, st) ->
return (snubcat $ staticPtrs st, defs st stop)
(Left (Name f (Just (_, modul))), _) -> do
error $ msg (toString modul) (toString f)
(r, _) -> do
error $ "Impossible result in runDep: " ++ show r
where
msg "Main" "main" =
"Unable to locate a main function.\n" ++
"If your main function is not `Main.main' you must specify it using " ++
"`-main-is',\n" ++
"for instance, `-main-is MyModule.myMain'.\n" ++
"If your progam intentionally has no main function," ++
" please use `--dont-link' to avoid this error."
msg s f =
"Unable to locate function `" ++ f ++ "' in module `" ++ s ++ "'!"
snubcat = map head . group . sort . concat
getModuleOf :: [FilePath] -> Name -> DepM Module
getModuleOf libpaths v@(Name n _) =
case moduleOf v of
Just "GHC.Prim" -> return foreignModule
Just "" -> return foreignModule
Nothing -> return foreignModule
Just ":Main" -> do
(p, m) <- mainModule `fmap` get
getModuleOf libpaths (Name n (Just (p, m)))
Just m -> do
mm <- getModule libpaths (maybe "main" id $ pkgOf v) m
case mm of
Just m' -> return m'
_ -> left v
already there . Modules are preferentially loaded from jslib file .
getModule :: [FilePath] -> BS.ByteString -> BS.ByteString -> DepM (Maybe Module)
getModule libpaths pkgid modname = do
st <- get
case M.lookup modname (modules st) of
Just m -> do
return $ Just m
_ -> do
info $ "Linking " ++ toString modname
go libpaths
where
go (libpath:lps) = do
mm <- liftIO $ readModule libpath (toString pkgid) (toString modname)
case mm of
Just m -> do
st <- get
put st
{ modules = M.insert modname m (modules st)
, staticPtrs = modSPT m : staticPtrs st
}
mapM_ (addDef libpaths pkgid) (modSPT m)
return (Just m)
_ -> do
go lps
go [] = do
return Nothing
addDef :: [FilePath] -> BS.ByteString -> Name -> DepM ()
addDef libpaths pkgid v = do
st <- get
when (not $ v `S.member` alreadySeen st) $ do
m <- getModuleOf libpaths v
st' <- get
let dependencies = maybe S.empty id (M.lookup v (modDeps m))
put st' {alreadySeen = S.insert v (alreadySeen st')}
S.foldl' (\a x -> a >> addDef libpaths pkgid x) (return ()) dependencies
st'' <- get
let Name cmnt _ = v
defs' =
maybe (defs st'')
(\body -> defs st'' . newVar True (internalVar v cmnt) body)
(M.lookup v (modDefs m))
put st'' {defs = defs'}
|
2e34d5f8ef162f2245e0409db0c68c03761705abdb20e71618f548a7a990b653 | yallop/ocaml-ctypes | test_pointers.ml |
* Copyright ( c ) 2013 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2013 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
[@@@ocaml.warning "-6"]
open OUnit2
open Ctypes
open Foreign
let testlib = Dl.(dlopen ~filename:"clib/libtest_functions.so" ~flags:[RTLD_NOW])
module Common_tests(S : Cstubs.FOREIGN with type 'a result = 'a
and type 'a return = 'a) =
struct
module M = Functions.Stubs(S)
open M
(*
Test passing various types of pointers to a function.
*)
let test_passing_pointers _ =
assert_equal ~msg:"Passing pointers to various numeric types"
~printer:string_of_int
(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 +
11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20)
(let open Signed in
let open Unsigned in
accept_pointers
(allocate float 1.0)
(allocate double 2.0)
(allocate short 3)
(allocate int 4)
(allocate long (Long.of_int 5))
(allocate llong (LLong.of_int 6))
(allocate nativeint 7n)
(allocate int8_t 8)
(allocate int16_t 9)
(allocate int32_t 10l)
(allocate int64_t 11L)
(allocate uint8_t (UInt8.of_int 12))
(allocate uint16_t (UInt16.of_int 13))
(allocate uint32_t (UInt32.of_int 14))
(allocate uint64_t (UInt64.of_int 15))
(allocate size_t (Size_t.of_int 16))
(allocate ushort (UShort.of_int 17))
(allocate uint (UInt.of_int 18))
(allocate ulong (ULong.of_int 19))
(allocate ullong (ULLong.of_int 20)))
(*
Test passing pointers to pointers.
*)
let test_passing_pointers_to_pointers _ =
let p = allocate int 1
and pp = allocate (ptr int) (allocate int 2)
and ppp = allocate (ptr (ptr int)) (allocate (ptr int) (allocate int 3))
and pppp = allocate (ptr (ptr (ptr int)))
(allocate (ptr (ptr int)) (allocate (ptr int) (allocate int 4))) in
assert_equal ~msg:"Passing pointers to pointers"
(1 + 2 + 3 + 4)
(accept_pointers_to_pointers p pp ppp pppp)
(*
Passing a callback that accepts pointers as arguments.
*)
let test_callback_receiving_pointers _ =
assert_equal 7
(passing_pointers_to_callback (fun lp rp -> !@lp + !@rp))
(*
Passing a callback that returns a pointer.
*)
let test_callback_returning_pointers _ =
let p = allocate int 17 in
begin
assert_equal 17 !@p;
assert_equal 56
(accepting_pointer_from_callback (fun x y -> p <-@ (x * y); p));
assert_equal 12 !@p
end
(*
Test passing a pointer-to-a-function-pointer as an argument.
*)
let test_passing_pointer_to_function_pointer _ =
assert_equal ~printer:string_of_int
5 (accepting_pointer_to_function_pointer
(allocate (funptr (int @-> int @-> returning int)) ( / )))
(*
Test returning a pointer to a function pointer
*)
let test_callback_returning_pointer_to_function_pointer _ =
assert_equal
10 (!@(returning_pointer_to_function_pointer ()) 2 5)
(*
Test bindings for malloc, realloc and free.
*)
let test_allocation _ =
let open Unsigned in
let pointer = malloc (Size_t.of_int (sizeof int)) in
let int_pointer = from_voidp int pointer in
int_pointer <-@ 17;
assert_equal !@int_pointer 17;
int_pointer <-@ -3;
assert_equal !@int_pointer (-3);
let pointer' = realloc pointer (Size_t.of_int (20 * sizeof int)) in
assert_bool "realloc succeeded" (pointer' <> null);
let int_pointer = from_voidp int pointer' in
assert_equal ~msg:"realloc copied the existing data over"
!@int_pointer (-3);
for i = 0 to 19 do
(int_pointer +@ i) <-@ i
done;
for i = 0 to 19 do
assert_equal i !@(int_pointer +@ i)
done;
free pointer'
(*
Test a function that returns the address of a global variable.
*)
let test_reading_returned_global _ =
assert_equal (!@(return_global_address ())) 100
(*
Test a function that returns a pointer passed as argument.
*)
let test_passing_pointer_through _ =
let p1 = allocate int 25 in
let p2 = allocate int 32 in
let rv = pass_pointer_through p1 p2 10 in
assert_equal !@rv !@p1;
assert_equal 25 !@rv;
let rv = pass_pointer_through p1 p2 (-10) in
assert_equal !@rv !@p2;
assert_equal 32 !@rv;
let p3 = p1 +@ 1 in
let rv = pass_pointer_through p3 p1 1 in
assert_bool
"pointer with (positive) offset successfully passed through"
(ptr_compare rv p3 = 0);
assert_bool
"pointer with positive computed offset compares greater than original"
(ptr_compare p1 p3 < 0);
assert_bool
"pointer with positive computed offset compares greater than original"
(ptr_compare p3 p1 > 0);
assert_bool
"returned pointer with positive computed offset compares greater than original"
(ptr_compare p1 rv < 0);
assert_bool
"returned pointer with positive computed offset compares greater than original"
(ptr_compare rv p1 > 0);
assert_equal !@(rv -@ 1) !@(p3 -@ 1);
let p4 = p1 -@ 1 in
let rv = pass_pointer_through p1 p4 (-1) in
assert_bool
"pointer with (negative) offset successfully passed through"
(ptr_compare rv p4 = 0);
assert_bool
"pointer with negative computed offset compares less than original"
(ptr_compare p1 p4 > 0);
assert_bool
"pointer with negative computed offset compares less than original"
(ptr_compare p4 p1 < 0);
assert_bool
"returned pointer with negative computed offset compares greater than original"
(ptr_compare p1 rv > 0);
assert_bool
"returned pointer with negative computed offset compares greater than original"
(ptr_compare rv p1 < 0)
end
(*
Tests for reading and writing primitive values through pointers.
*)
let test_pointer_assignment_with_primitives _ =
let open Signed in
let open Unsigned in
let p_char = allocate char '1'
and p_uchar = allocate uchar (UChar.of_int 2)
and p_bool = allocate bool false
and p_schar = allocate schar 3
and p_float = allocate float 4.0
and p_double = allocate double 5.0
and p_short = allocate short 6
and p_int = allocate int 7
and p_long = allocate long (Long.of_int 8)
and p_llong = allocate llong (LLong.of_int 9)
and p_nativeint = allocate nativeint 10n
and p_int8_t = allocate int8_t 11
and p_int16_t = allocate int16_t 12
and p_int32_t = allocate int32_t 13l
and p_int64_t = allocate int64_t 14L
and p_uint8_t = allocate uint8_t (UInt8.of_int 15)
and p_uint16_t = allocate uint16_t (UInt16.of_int 16)
and p_uint32_t = allocate uint32_t (UInt32.of_int 17)
and p_uint64_t = allocate uint64_t (UInt64.of_int 18)
and p_size_t = allocate size_t (Size_t.of_int 19)
and p_ushort = allocate ushort (UShort.of_int 20)
and p_uint = allocate uint (UInt.of_int 21)
and p_ulong = allocate ulong (ULong.of_int 22)
and p_ullong = allocate ullong (ULLong.of_int 23)
in begin
assert_equal '1' (!@p_char);
assert_equal (UChar.of_int 2) (!@p_uchar);
assert_equal false (!@p_bool);
assert_equal 3 (!@p_schar);
assert_equal 4.0 (!@p_float);
assert_equal 5.0 (!@p_double);
assert_equal 6 (!@p_short);
assert_equal 7 (!@p_int);
assert_equal (Long.of_int 8) (!@p_long);
assert_equal (LLong.of_int 9) (!@p_llong);
assert_equal 10n (!@p_nativeint);
assert_equal 11 (!@p_int8_t);
assert_equal 12 (!@p_int16_t);
assert_equal 13l (!@p_int32_t);
assert_equal 14L (!@p_int64_t);
assert_equal (UInt8.of_int 15) (!@p_uint8_t);
assert_equal (UInt16.of_int 16) (!@p_uint16_t);
assert_equal (UInt32.of_int 17) (!@p_uint32_t);
assert_equal (UInt64.of_int 18) (!@p_uint64_t);
assert_equal (Size_t.of_int 19) (!@p_size_t);
assert_equal (UShort.of_int 20) (!@p_ushort);
assert_equal (UInt.of_int 21) (!@p_uint);
assert_equal (ULong.of_int 22) (!@p_ulong);
assert_equal (ULLong.of_int 23) (!@p_ullong);
p_char <-@ '2';
p_uchar <-@ (UChar.of_int 102);
p_bool <-@ true;
p_schar <-@ 103;
p_float <-@ 104.0;
p_double <-@ 105.0;
p_short <-@ 106;
p_int <-@ 107;
p_long <-@ (Long.of_int 108);
p_llong <-@ (LLong.of_int 109);
p_nativeint <-@ 110n;
p_int8_t <-@ 111;
p_int16_t <-@ 112;
p_int32_t <-@ 113l;
p_int64_t <-@ 114L;
p_uint8_t <-@ (UInt8.of_int 115);
p_uint16_t <-@ (UInt16.of_int 116);
p_uint32_t <-@ (UInt32.of_int 117);
p_uint64_t <-@ (UInt64.of_int 118);
p_size_t <-@ (Size_t.of_int 119);
p_ushort <-@ (UShort.of_int 120);
p_uint <-@ (UInt.of_int 121);
p_ulong <-@ (ULong.of_int 122);
p_ullong <-@ (ULLong.of_int 123);
assert_equal '2' (!@p_char);
assert_equal (UChar.of_int 102) (!@p_uchar);
assert_equal true (!@p_bool);
assert_equal 103 (!@p_schar);
assert_equal 104.0 (!@p_float);
assert_equal 105.0 (!@p_double);
assert_equal 106 (!@p_short);
assert_equal 107 (!@p_int);
assert_equal (Long.of_int 108) (!@p_long);
assert_equal (LLong.of_int 109) (!@p_llong);
assert_equal 110n (!@p_nativeint);
assert_equal 111 (!@p_int8_t);
assert_equal 112 (!@p_int16_t);
assert_equal 113l (!@p_int32_t);
assert_equal 114L (!@p_int64_t);
assert_equal (UInt8.of_int 115) (!@p_uint8_t);
assert_equal (UInt16.of_int 116) (!@p_uint16_t);
assert_equal (UInt32.of_int 117) (!@p_uint32_t);
assert_equal (UInt64.of_int 118) (!@p_uint64_t);
assert_equal (Size_t.of_int 119) (!@p_size_t);
assert_equal (UShort.of_int 120) (!@p_ushort);
assert_equal (UInt.of_int 121) (!@p_uint);
assert_equal (ULong.of_int 122) (!@p_ulong);
assert_equal (ULLong.of_int 123) (!@p_ullong);
end
(*
Dereferencing pointers to incomplete types
*)
let test_dereferencing_pointers_to_incomplete_types _ =
begin
assert_raises IncompleteType
(fun () -> !@null);
assert_raises IncompleteType
(fun () -> !@(from_voidp (structure "incomplete") null));
assert_raises IncompleteType
(fun () -> !@(from_voidp (union "incomplete") null));
end
(*
Writing through a pointer to an abstract type
*)
let test_writing_through_pointer_to_abstract_type _ =
let module Array = CArray in
let arra = Array.make int 2 in
let arrb = Array.make int 2 in
let absptr a =
from_voidp (abstract
~name:"absptr"
~size:(2 * sizeof int)
~alignment:(alignment (array 2 int)))
(to_voidp (Array.start a)) in
let () = begin
arra.(0) <- 10;
arra.(1) <- 20;
arrb.(0) <- 30;
arrb.(1) <- 40;
end in
let dest = absptr arra in
let src = absptr arrb in
begin
assert_equal 10 arra.(0);
assert_equal 20 arra.(1);
assert_equal 30 arrb.(0);
assert_equal 40 arrb.(1);
dest <-@ !@src;
assert_equal 30 arra.(0);
assert_equal 40 arra.(1);
assert_equal 30 arrb.(0);
assert_equal 40 arrb.(1);
assert_bool "pointers distinct" (dest <> src);
assert_bool "arrays distinct" (arra <> arrb);
end
(*
Test for reading and writing global values using the "foreign_value"
function.
*)
let test_reading_and_writing_global_value _ =
let ptr = foreign_value "global" int ~from:testlib in
let ptr' = foreign_value "global" int ~from:testlib in
assert_equal (!@ptr) 100;
ptr <-@ 200;
assert_equal (!@ptr) 200;
assert_equal (!@ptr') 200;
ptr' <-@ 100;
assert_equal (!@ptr) 100;
assert_equal (!@ptr') 100
(*
Tests for reading a string from an address.
*)
let test_reading_strings _ =
let p = allocate_n char 26 in begin
StringLabels.iteri "abcdefghijklmnoprwstuvwxyz"
~f:(fun i c -> (p +@ i) <-@ c);
assert_equal (string_from_ptr p 5) "abcde";
assert_equal (string_from_ptr p 26) "abcdefghijklmnoprwstuvwxyz";
assert_equal (string_from_ptr p 0) "";
assert_raises (Invalid_argument "Ctypes.string_from_ptr")
(fun () -> string_from_ptr p (-1));
end
(*
Tests for various aspects of pointer arithmetic.
*)
let test_pointer_arithmetic _ =
let module Array = CArray in
let arr = Array.of_list int [1;2;3;4;5;6;7;8] in
Traverse the array using an int pointer
let p = Array.start arr in
for i = 0 to 7 do
assert_equal !@(p +@ i) (succ i)
done;
let twoints = structure "s" in
let i1 = field twoints "i" int in
let i2 = field twoints "j" int in
let () = seal twoints in
Traverse the array using a ' struct twoints ' pointer
let ps = from_voidp twoints (to_voidp p) in
for i = 0 to 3 do
assert_equal !@((ps +@ i) |-> i1) (2 * i + 1);
assert_equal !@((ps +@ i) |-> i2) (2 * i + 2);
done;
Traverse the array using a char pointer
let pc = from_voidp char (to_voidp p) in
for i = 0 to 7 do
let p' = pc +@ i * sizeof int in
assert_equal !@(from_voidp int (to_voidp p')) (succ i)
done;
(* Reverse traversal *)
let pend = p +@ 7 in
for i = 0 to 7 do
assert_equal !@(pend -@ i) (8 - i)
done
(*
Test pointer comparisons.
*)
let test_pointer_comparison _ =
let canonicalize p =
Ensure that the ' pbyte_offset ' component of the pointer is zero by
writing the pointer to memory and then reading it back .
writing the pointer to memory and then reading it back. *)
let buf = allocate_n ~count:1 (ptr void) in
buf <-@ (to_voidp p);
!@buf
in
let (<) l r = ptr_compare l r < 0
and (>) l r = ptr_compare l r > 0
and (=) l r = ptr_compare l r = 0 in
(* equal but not identical pointers compare equal *)
let p = allocate int 10 in
let p' = from_voidp int (to_voidp p) in
assert_bool "equal but not identical poitners compare equal"
(p = p');
(* Canonicalization preserves ordering *)
assert_bool "p < p+n"
(p < (p +@ 10));
assert_bool "canonicalize(p) < canonicalize(p+n)"
(canonicalize p < canonicalize (p +@ 10));
assert_bool "p > p-1"
(p > (p -@ 1));
assert_bool "canonicalize(p) > canonicalize(p-1)"
(canonicalize p > canonicalize (p -@ 1));
let s3 = structure "s3" in
let i = field s3 "i" int in
let j = field s3 "j" int in
let k = field s3 "k" int in
let () = seal s3 in
let sp = addr (make s3) in
let p1 = to_voidp (sp |-> i)
and p2 = to_voidp (sp |-> j)
and p3 = to_voidp (sp |-> k) in
assert_bool "sp |-> i < sp |-> j"
(p1 < p2);
assert_bool "sp |-> i < canonicalize (sp |-> j)"
(p1 < canonicalize p2);
assert_bool "canonicalize (sp |-> i) < sp |-> j"
(canonicalize p1 < p2);
assert_bool "canonicalize (sp |-> i) < canonicalize (sp |-> j)"
(canonicalize p1 < canonicalize p2);
assert_bool "sp |-> i < sp |-> k"
(p1 < p3);
assert_bool "sp |-> i < canonicalize (sp |-> k)"
(p1 < canonicalize p3);
assert_bool "canonicalize (sp |-> i) < sp |-> k"
(canonicalize p1 < p3);
assert_bool "canonicalize (sp |-> i) < canonicalize (sp |-> k)"
(canonicalize p1 < canonicalize p3);
assert_bool "sp |-> j < sp |-> k"
(p2 < p3);
assert_bool "sp |-> j < canonicalize (sp |-> k)"
(p2 < canonicalize p3);
assert_bool "canonicalize (sp |-> j) < sp |-> k"
(canonicalize p2 < p3);
assert_bool "canonicalize (sp |-> j) < canonicalize (sp |-> k)"
(canonicalize p2 < canonicalize p3);
(* Canonicalization preserves equality *)
assert_bool "canonicalization preserves equality"
(to_voidp p = canonicalize p)
(*
Test pointer differences.
*)
let test_pointer_differences _ =
let canonicalize p =
Ensure that the ' pbyte_offset ' component of the pointer is zero by
writing the pointer to memory and then reading it back .
writing the pointer to memory and then reading it back. *)
let buf = allocate_n ~count:1 (ptr void) in
buf <-@ (to_voidp p);
!@buf
in
let s = structure "s" in
let (-:) ty label = field s label ty in
let i = int -: "i" in
let j = array 17 char -: "j" in
let k = double -: "k" in
let l = char -: "l" in
let () = seal s in
let v = make s in
let p = addr v in
let to_charp p = from_voidp char (to_voidp p) in
let cp = to_charp p in
assert_equal (offsetof i) (ptr_diff cp (to_charp (p |-> i)));
assert_equal (offsetof j) (ptr_diff cp (to_charp (p |-> j)));
assert_equal (offsetof k) (ptr_diff cp (to_charp (p |-> k)));
assert_equal (offsetof l) (ptr_diff cp (to_charp (p |-> l)));
assert_equal (-offsetof i) (ptr_diff (to_charp (p |-> i)) cp);
assert_equal (-offsetof j) (ptr_diff (to_charp (p |-> j)) cp);
assert_equal (-offsetof k) (ptr_diff (to_charp (p |-> k)) cp);
assert_equal (-offsetof l) (ptr_diff (to_charp (p |-> l)) cp);
assert_equal (offsetof i) (ptr_diff cp (to_charp (canonicalize (p |-> i))));
assert_equal (offsetof j) (ptr_diff cp (to_charp (canonicalize (p |-> j))));
assert_equal (offsetof k) (ptr_diff cp (to_charp (canonicalize (p |-> k))));
assert_equal (offsetof l) (ptr_diff cp (to_charp (canonicalize (p |-> l))));
assert_equal (-offsetof i) (ptr_diff (to_charp (canonicalize (p |-> i))) cp);
assert_equal (-offsetof j) (ptr_diff (to_charp (canonicalize (p |-> j))) cp);
assert_equal (-offsetof k) (ptr_diff (to_charp (canonicalize (p |-> k))) cp);
assert_equal (-offsetof l) (ptr_diff (to_charp (canonicalize (p |-> l))) cp)
(*
Test raw pointers.
*)
let test_raw_pointers _ =
(* Check that conversions to the raw form commute with arithmetic. *)
let p : float ptr = allocate double 1.0 in
let p' = p +@ 3 in
let praw = raw_address_of_ptr (to_voidp p) in
let praw' = raw_address_of_ptr (to_voidp p') in
assert_equal praw' Nativeint.(add praw (of_int (3 * sizeof double)))
module Foreign_tests = Common_tests(Tests_common.Foreign_binder)
module Stub_tests = Common_tests(Generated_bindings)
let suite = "Pointer tests" >:::
["passing pointers (foreign)"
>:: Foreign_tests.test_passing_pointers;
"passing pointers (stubs)"
>:: Stub_tests.test_passing_pointers;
"passing pointers to pointers (foreign)"
>:: Foreign_tests.test_passing_pointers_to_pointers;
"passing pointers to pointers (stubs)"
>:: Stub_tests.test_passing_pointers_to_pointers;
"callback receiving pointers (foreign)"
>:: Foreign_tests.test_callback_receiving_pointers;
"callback receiving pointers (stubs)"
>:: Stub_tests.test_callback_receiving_pointers;
"callback returning pointers (foreign)"
>:: Foreign_tests.test_callback_returning_pointers;
"callback returning pointers (stubs)"
>:: Stub_tests.test_callback_returning_pointers;
"pointer assignment with primitives"
>:: test_pointer_assignment_with_primitives;
"passing pointer to function pointer (foreign)"
>:: Foreign_tests.test_passing_pointer_to_function_pointer;
"passing pointer to function pointer (stubs)"
>:: Stub_tests.test_passing_pointer_to_function_pointer;
"callback returning pointer to function pointer (foreign)"
>:: Foreign_tests.test_callback_returning_pointer_to_function_pointer;
"callback returning pointer to function pointer (stubs)"
>:: Stub_tests.test_callback_returning_pointer_to_function_pointer;
"incomplete types"
>:: test_dereferencing_pointers_to_incomplete_types;
"abstract types"
>:: test_writing_through_pointer_to_abstract_type;
"global value"
>:: test_reading_and_writing_global_value;
"allocation (foreign)"
>:: Foreign_tests.test_allocation;
"allocation (stubs)"
>:: Stub_tests.test_allocation;
"passing pointers through functions (foreign)"
>:: Foreign_tests.test_passing_pointer_through;
"passing pointers through functions (stubs)"
>:: Stub_tests.test_passing_pointer_through;
"returned globals (foreign)"
>:: Foreign_tests.test_reading_returned_global;
"returned globals (stubs)"
>:: Stub_tests.test_reading_returned_global;
"reading strings"
>:: test_reading_strings;
"arithmetic"
>:: test_pointer_arithmetic;
"comparisons"
>:: test_pointer_comparison;
"differences"
>:: test_pointer_differences;
"raw"
>:: test_raw_pointers;
]
let _ =
run_test_tt_main suite
| null | https://raw.githubusercontent.com/yallop/ocaml-ctypes/52ff621f47dbc1ee5a90c30af0ae0474549946b4/tests/test-pointers/test_pointers.ml | ocaml |
Test passing various types of pointers to a function.
Test passing pointers to pointers.
Passing a callback that accepts pointers as arguments.
Passing a callback that returns a pointer.
Test passing a pointer-to-a-function-pointer as an argument.
Test returning a pointer to a function pointer
Test bindings for malloc, realloc and free.
Test a function that returns the address of a global variable.
Test a function that returns a pointer passed as argument.
Tests for reading and writing primitive values through pointers.
Dereferencing pointers to incomplete types
Writing through a pointer to an abstract type
Test for reading and writing global values using the "foreign_value"
function.
Tests for reading a string from an address.
Tests for various aspects of pointer arithmetic.
Reverse traversal
Test pointer comparisons.
equal but not identical pointers compare equal
Canonicalization preserves ordering
Canonicalization preserves equality
Test pointer differences.
Test raw pointers.
Check that conversions to the raw form commute with arithmetic. |
* Copyright ( c ) 2013 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2013 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
[@@@ocaml.warning "-6"]
open OUnit2
open Ctypes
open Foreign
let testlib = Dl.(dlopen ~filename:"clib/libtest_functions.so" ~flags:[RTLD_NOW])
module Common_tests(S : Cstubs.FOREIGN with type 'a result = 'a
and type 'a return = 'a) =
struct
module M = Functions.Stubs(S)
open M
let test_passing_pointers _ =
assert_equal ~msg:"Passing pointers to various numeric types"
~printer:string_of_int
(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 +
11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20)
(let open Signed in
let open Unsigned in
accept_pointers
(allocate float 1.0)
(allocate double 2.0)
(allocate short 3)
(allocate int 4)
(allocate long (Long.of_int 5))
(allocate llong (LLong.of_int 6))
(allocate nativeint 7n)
(allocate int8_t 8)
(allocate int16_t 9)
(allocate int32_t 10l)
(allocate int64_t 11L)
(allocate uint8_t (UInt8.of_int 12))
(allocate uint16_t (UInt16.of_int 13))
(allocate uint32_t (UInt32.of_int 14))
(allocate uint64_t (UInt64.of_int 15))
(allocate size_t (Size_t.of_int 16))
(allocate ushort (UShort.of_int 17))
(allocate uint (UInt.of_int 18))
(allocate ulong (ULong.of_int 19))
(allocate ullong (ULLong.of_int 20)))
let test_passing_pointers_to_pointers _ =
let p = allocate int 1
and pp = allocate (ptr int) (allocate int 2)
and ppp = allocate (ptr (ptr int)) (allocate (ptr int) (allocate int 3))
and pppp = allocate (ptr (ptr (ptr int)))
(allocate (ptr (ptr int)) (allocate (ptr int) (allocate int 4))) in
assert_equal ~msg:"Passing pointers to pointers"
(1 + 2 + 3 + 4)
(accept_pointers_to_pointers p pp ppp pppp)
let test_callback_receiving_pointers _ =
assert_equal 7
(passing_pointers_to_callback (fun lp rp -> !@lp + !@rp))
let test_callback_returning_pointers _ =
let p = allocate int 17 in
begin
assert_equal 17 !@p;
assert_equal 56
(accepting_pointer_from_callback (fun x y -> p <-@ (x * y); p));
assert_equal 12 !@p
end
let test_passing_pointer_to_function_pointer _ =
assert_equal ~printer:string_of_int
5 (accepting_pointer_to_function_pointer
(allocate (funptr (int @-> int @-> returning int)) ( / )))
let test_callback_returning_pointer_to_function_pointer _ =
assert_equal
10 (!@(returning_pointer_to_function_pointer ()) 2 5)
let test_allocation _ =
let open Unsigned in
let pointer = malloc (Size_t.of_int (sizeof int)) in
let int_pointer = from_voidp int pointer in
int_pointer <-@ 17;
assert_equal !@int_pointer 17;
int_pointer <-@ -3;
assert_equal !@int_pointer (-3);
let pointer' = realloc pointer (Size_t.of_int (20 * sizeof int)) in
assert_bool "realloc succeeded" (pointer' <> null);
let int_pointer = from_voidp int pointer' in
assert_equal ~msg:"realloc copied the existing data over"
!@int_pointer (-3);
for i = 0 to 19 do
(int_pointer +@ i) <-@ i
done;
for i = 0 to 19 do
assert_equal i !@(int_pointer +@ i)
done;
free pointer'
let test_reading_returned_global _ =
assert_equal (!@(return_global_address ())) 100
let test_passing_pointer_through _ =
let p1 = allocate int 25 in
let p2 = allocate int 32 in
let rv = pass_pointer_through p1 p2 10 in
assert_equal !@rv !@p1;
assert_equal 25 !@rv;
let rv = pass_pointer_through p1 p2 (-10) in
assert_equal !@rv !@p2;
assert_equal 32 !@rv;
let p3 = p1 +@ 1 in
let rv = pass_pointer_through p3 p1 1 in
assert_bool
"pointer with (positive) offset successfully passed through"
(ptr_compare rv p3 = 0);
assert_bool
"pointer with positive computed offset compares greater than original"
(ptr_compare p1 p3 < 0);
assert_bool
"pointer with positive computed offset compares greater than original"
(ptr_compare p3 p1 > 0);
assert_bool
"returned pointer with positive computed offset compares greater than original"
(ptr_compare p1 rv < 0);
assert_bool
"returned pointer with positive computed offset compares greater than original"
(ptr_compare rv p1 > 0);
assert_equal !@(rv -@ 1) !@(p3 -@ 1);
let p4 = p1 -@ 1 in
let rv = pass_pointer_through p1 p4 (-1) in
assert_bool
"pointer with (negative) offset successfully passed through"
(ptr_compare rv p4 = 0);
assert_bool
"pointer with negative computed offset compares less than original"
(ptr_compare p1 p4 > 0);
assert_bool
"pointer with negative computed offset compares less than original"
(ptr_compare p4 p1 < 0);
assert_bool
"returned pointer with negative computed offset compares greater than original"
(ptr_compare p1 rv > 0);
assert_bool
"returned pointer with negative computed offset compares greater than original"
(ptr_compare rv p1 < 0)
end
let test_pointer_assignment_with_primitives _ =
let open Signed in
let open Unsigned in
let p_char = allocate char '1'
and p_uchar = allocate uchar (UChar.of_int 2)
and p_bool = allocate bool false
and p_schar = allocate schar 3
and p_float = allocate float 4.0
and p_double = allocate double 5.0
and p_short = allocate short 6
and p_int = allocate int 7
and p_long = allocate long (Long.of_int 8)
and p_llong = allocate llong (LLong.of_int 9)
and p_nativeint = allocate nativeint 10n
and p_int8_t = allocate int8_t 11
and p_int16_t = allocate int16_t 12
and p_int32_t = allocate int32_t 13l
and p_int64_t = allocate int64_t 14L
and p_uint8_t = allocate uint8_t (UInt8.of_int 15)
and p_uint16_t = allocate uint16_t (UInt16.of_int 16)
and p_uint32_t = allocate uint32_t (UInt32.of_int 17)
and p_uint64_t = allocate uint64_t (UInt64.of_int 18)
and p_size_t = allocate size_t (Size_t.of_int 19)
and p_ushort = allocate ushort (UShort.of_int 20)
and p_uint = allocate uint (UInt.of_int 21)
and p_ulong = allocate ulong (ULong.of_int 22)
and p_ullong = allocate ullong (ULLong.of_int 23)
in begin
assert_equal '1' (!@p_char);
assert_equal (UChar.of_int 2) (!@p_uchar);
assert_equal false (!@p_bool);
assert_equal 3 (!@p_schar);
assert_equal 4.0 (!@p_float);
assert_equal 5.0 (!@p_double);
assert_equal 6 (!@p_short);
assert_equal 7 (!@p_int);
assert_equal (Long.of_int 8) (!@p_long);
assert_equal (LLong.of_int 9) (!@p_llong);
assert_equal 10n (!@p_nativeint);
assert_equal 11 (!@p_int8_t);
assert_equal 12 (!@p_int16_t);
assert_equal 13l (!@p_int32_t);
assert_equal 14L (!@p_int64_t);
assert_equal (UInt8.of_int 15) (!@p_uint8_t);
assert_equal (UInt16.of_int 16) (!@p_uint16_t);
assert_equal (UInt32.of_int 17) (!@p_uint32_t);
assert_equal (UInt64.of_int 18) (!@p_uint64_t);
assert_equal (Size_t.of_int 19) (!@p_size_t);
assert_equal (UShort.of_int 20) (!@p_ushort);
assert_equal (UInt.of_int 21) (!@p_uint);
assert_equal (ULong.of_int 22) (!@p_ulong);
assert_equal (ULLong.of_int 23) (!@p_ullong);
p_char <-@ '2';
p_uchar <-@ (UChar.of_int 102);
p_bool <-@ true;
p_schar <-@ 103;
p_float <-@ 104.0;
p_double <-@ 105.0;
p_short <-@ 106;
p_int <-@ 107;
p_long <-@ (Long.of_int 108);
p_llong <-@ (LLong.of_int 109);
p_nativeint <-@ 110n;
p_int8_t <-@ 111;
p_int16_t <-@ 112;
p_int32_t <-@ 113l;
p_int64_t <-@ 114L;
p_uint8_t <-@ (UInt8.of_int 115);
p_uint16_t <-@ (UInt16.of_int 116);
p_uint32_t <-@ (UInt32.of_int 117);
p_uint64_t <-@ (UInt64.of_int 118);
p_size_t <-@ (Size_t.of_int 119);
p_ushort <-@ (UShort.of_int 120);
p_uint <-@ (UInt.of_int 121);
p_ulong <-@ (ULong.of_int 122);
p_ullong <-@ (ULLong.of_int 123);
assert_equal '2' (!@p_char);
assert_equal (UChar.of_int 102) (!@p_uchar);
assert_equal true (!@p_bool);
assert_equal 103 (!@p_schar);
assert_equal 104.0 (!@p_float);
assert_equal 105.0 (!@p_double);
assert_equal 106 (!@p_short);
assert_equal 107 (!@p_int);
assert_equal (Long.of_int 108) (!@p_long);
assert_equal (LLong.of_int 109) (!@p_llong);
assert_equal 110n (!@p_nativeint);
assert_equal 111 (!@p_int8_t);
assert_equal 112 (!@p_int16_t);
assert_equal 113l (!@p_int32_t);
assert_equal 114L (!@p_int64_t);
assert_equal (UInt8.of_int 115) (!@p_uint8_t);
assert_equal (UInt16.of_int 116) (!@p_uint16_t);
assert_equal (UInt32.of_int 117) (!@p_uint32_t);
assert_equal (UInt64.of_int 118) (!@p_uint64_t);
assert_equal (Size_t.of_int 119) (!@p_size_t);
assert_equal (UShort.of_int 120) (!@p_ushort);
assert_equal (UInt.of_int 121) (!@p_uint);
assert_equal (ULong.of_int 122) (!@p_ulong);
assert_equal (ULLong.of_int 123) (!@p_ullong);
end
let test_dereferencing_pointers_to_incomplete_types _ =
begin
assert_raises IncompleteType
(fun () -> !@null);
assert_raises IncompleteType
(fun () -> !@(from_voidp (structure "incomplete") null));
assert_raises IncompleteType
(fun () -> !@(from_voidp (union "incomplete") null));
end
let test_writing_through_pointer_to_abstract_type _ =
let module Array = CArray in
let arra = Array.make int 2 in
let arrb = Array.make int 2 in
let absptr a =
from_voidp (abstract
~name:"absptr"
~size:(2 * sizeof int)
~alignment:(alignment (array 2 int)))
(to_voidp (Array.start a)) in
let () = begin
arra.(0) <- 10;
arra.(1) <- 20;
arrb.(0) <- 30;
arrb.(1) <- 40;
end in
let dest = absptr arra in
let src = absptr arrb in
begin
assert_equal 10 arra.(0);
assert_equal 20 arra.(1);
assert_equal 30 arrb.(0);
assert_equal 40 arrb.(1);
dest <-@ !@src;
assert_equal 30 arra.(0);
assert_equal 40 arra.(1);
assert_equal 30 arrb.(0);
assert_equal 40 arrb.(1);
assert_bool "pointers distinct" (dest <> src);
assert_bool "arrays distinct" (arra <> arrb);
end
let test_reading_and_writing_global_value _ =
let ptr = foreign_value "global" int ~from:testlib in
let ptr' = foreign_value "global" int ~from:testlib in
assert_equal (!@ptr) 100;
ptr <-@ 200;
assert_equal (!@ptr) 200;
assert_equal (!@ptr') 200;
ptr' <-@ 100;
assert_equal (!@ptr) 100;
assert_equal (!@ptr') 100
let test_reading_strings _ =
let p = allocate_n char 26 in begin
StringLabels.iteri "abcdefghijklmnoprwstuvwxyz"
~f:(fun i c -> (p +@ i) <-@ c);
assert_equal (string_from_ptr p 5) "abcde";
assert_equal (string_from_ptr p 26) "abcdefghijklmnoprwstuvwxyz";
assert_equal (string_from_ptr p 0) "";
assert_raises (Invalid_argument "Ctypes.string_from_ptr")
(fun () -> string_from_ptr p (-1));
end
let test_pointer_arithmetic _ =
let module Array = CArray in
let arr = Array.of_list int [1;2;3;4;5;6;7;8] in
Traverse the array using an int pointer
let p = Array.start arr in
for i = 0 to 7 do
assert_equal !@(p +@ i) (succ i)
done;
let twoints = structure "s" in
let i1 = field twoints "i" int in
let i2 = field twoints "j" int in
let () = seal twoints in
Traverse the array using a ' struct twoints ' pointer
let ps = from_voidp twoints (to_voidp p) in
for i = 0 to 3 do
assert_equal !@((ps +@ i) |-> i1) (2 * i + 1);
assert_equal !@((ps +@ i) |-> i2) (2 * i + 2);
done;
Traverse the array using a char pointer
let pc = from_voidp char (to_voidp p) in
for i = 0 to 7 do
let p' = pc +@ i * sizeof int in
assert_equal !@(from_voidp int (to_voidp p')) (succ i)
done;
let pend = p +@ 7 in
for i = 0 to 7 do
assert_equal !@(pend -@ i) (8 - i)
done
let test_pointer_comparison _ =
let canonicalize p =
Ensure that the ' pbyte_offset ' component of the pointer is zero by
writing the pointer to memory and then reading it back .
writing the pointer to memory and then reading it back. *)
let buf = allocate_n ~count:1 (ptr void) in
buf <-@ (to_voidp p);
!@buf
in
let (<) l r = ptr_compare l r < 0
and (>) l r = ptr_compare l r > 0
and (=) l r = ptr_compare l r = 0 in
let p = allocate int 10 in
let p' = from_voidp int (to_voidp p) in
assert_bool "equal but not identical poitners compare equal"
(p = p');
assert_bool "p < p+n"
(p < (p +@ 10));
assert_bool "canonicalize(p) < canonicalize(p+n)"
(canonicalize p < canonicalize (p +@ 10));
assert_bool "p > p-1"
(p > (p -@ 1));
assert_bool "canonicalize(p) > canonicalize(p-1)"
(canonicalize p > canonicalize (p -@ 1));
let s3 = structure "s3" in
let i = field s3 "i" int in
let j = field s3 "j" int in
let k = field s3 "k" int in
let () = seal s3 in
let sp = addr (make s3) in
let p1 = to_voidp (sp |-> i)
and p2 = to_voidp (sp |-> j)
and p3 = to_voidp (sp |-> k) in
assert_bool "sp |-> i < sp |-> j"
(p1 < p2);
assert_bool "sp |-> i < canonicalize (sp |-> j)"
(p1 < canonicalize p2);
assert_bool "canonicalize (sp |-> i) < sp |-> j"
(canonicalize p1 < p2);
assert_bool "canonicalize (sp |-> i) < canonicalize (sp |-> j)"
(canonicalize p1 < canonicalize p2);
assert_bool "sp |-> i < sp |-> k"
(p1 < p3);
assert_bool "sp |-> i < canonicalize (sp |-> k)"
(p1 < canonicalize p3);
assert_bool "canonicalize (sp |-> i) < sp |-> k"
(canonicalize p1 < p3);
assert_bool "canonicalize (sp |-> i) < canonicalize (sp |-> k)"
(canonicalize p1 < canonicalize p3);
assert_bool "sp |-> j < sp |-> k"
(p2 < p3);
assert_bool "sp |-> j < canonicalize (sp |-> k)"
(p2 < canonicalize p3);
assert_bool "canonicalize (sp |-> j) < sp |-> k"
(canonicalize p2 < p3);
assert_bool "canonicalize (sp |-> j) < canonicalize (sp |-> k)"
(canonicalize p2 < canonicalize p3);
assert_bool "canonicalization preserves equality"
(to_voidp p = canonicalize p)
let test_pointer_differences _ =
let canonicalize p =
Ensure that the ' pbyte_offset ' component of the pointer is zero by
writing the pointer to memory and then reading it back .
writing the pointer to memory and then reading it back. *)
let buf = allocate_n ~count:1 (ptr void) in
buf <-@ (to_voidp p);
!@buf
in
let s = structure "s" in
let (-:) ty label = field s label ty in
let i = int -: "i" in
let j = array 17 char -: "j" in
let k = double -: "k" in
let l = char -: "l" in
let () = seal s in
let v = make s in
let p = addr v in
let to_charp p = from_voidp char (to_voidp p) in
let cp = to_charp p in
assert_equal (offsetof i) (ptr_diff cp (to_charp (p |-> i)));
assert_equal (offsetof j) (ptr_diff cp (to_charp (p |-> j)));
assert_equal (offsetof k) (ptr_diff cp (to_charp (p |-> k)));
assert_equal (offsetof l) (ptr_diff cp (to_charp (p |-> l)));
assert_equal (-offsetof i) (ptr_diff (to_charp (p |-> i)) cp);
assert_equal (-offsetof j) (ptr_diff (to_charp (p |-> j)) cp);
assert_equal (-offsetof k) (ptr_diff (to_charp (p |-> k)) cp);
assert_equal (-offsetof l) (ptr_diff (to_charp (p |-> l)) cp);
assert_equal (offsetof i) (ptr_diff cp (to_charp (canonicalize (p |-> i))));
assert_equal (offsetof j) (ptr_diff cp (to_charp (canonicalize (p |-> j))));
assert_equal (offsetof k) (ptr_diff cp (to_charp (canonicalize (p |-> k))));
assert_equal (offsetof l) (ptr_diff cp (to_charp (canonicalize (p |-> l))));
assert_equal (-offsetof i) (ptr_diff (to_charp (canonicalize (p |-> i))) cp);
assert_equal (-offsetof j) (ptr_diff (to_charp (canonicalize (p |-> j))) cp);
assert_equal (-offsetof k) (ptr_diff (to_charp (canonicalize (p |-> k))) cp);
assert_equal (-offsetof l) (ptr_diff (to_charp (canonicalize (p |-> l))) cp)
let test_raw_pointers _ =
let p : float ptr = allocate double 1.0 in
let p' = p +@ 3 in
let praw = raw_address_of_ptr (to_voidp p) in
let praw' = raw_address_of_ptr (to_voidp p') in
assert_equal praw' Nativeint.(add praw (of_int (3 * sizeof double)))
module Foreign_tests = Common_tests(Tests_common.Foreign_binder)
module Stub_tests = Common_tests(Generated_bindings)
let suite = "Pointer tests" >:::
["passing pointers (foreign)"
>:: Foreign_tests.test_passing_pointers;
"passing pointers (stubs)"
>:: Stub_tests.test_passing_pointers;
"passing pointers to pointers (foreign)"
>:: Foreign_tests.test_passing_pointers_to_pointers;
"passing pointers to pointers (stubs)"
>:: Stub_tests.test_passing_pointers_to_pointers;
"callback receiving pointers (foreign)"
>:: Foreign_tests.test_callback_receiving_pointers;
"callback receiving pointers (stubs)"
>:: Stub_tests.test_callback_receiving_pointers;
"callback returning pointers (foreign)"
>:: Foreign_tests.test_callback_returning_pointers;
"callback returning pointers (stubs)"
>:: Stub_tests.test_callback_returning_pointers;
"pointer assignment with primitives"
>:: test_pointer_assignment_with_primitives;
"passing pointer to function pointer (foreign)"
>:: Foreign_tests.test_passing_pointer_to_function_pointer;
"passing pointer to function pointer (stubs)"
>:: Stub_tests.test_passing_pointer_to_function_pointer;
"callback returning pointer to function pointer (foreign)"
>:: Foreign_tests.test_callback_returning_pointer_to_function_pointer;
"callback returning pointer to function pointer (stubs)"
>:: Stub_tests.test_callback_returning_pointer_to_function_pointer;
"incomplete types"
>:: test_dereferencing_pointers_to_incomplete_types;
"abstract types"
>:: test_writing_through_pointer_to_abstract_type;
"global value"
>:: test_reading_and_writing_global_value;
"allocation (foreign)"
>:: Foreign_tests.test_allocation;
"allocation (stubs)"
>:: Stub_tests.test_allocation;
"passing pointers through functions (foreign)"
>:: Foreign_tests.test_passing_pointer_through;
"passing pointers through functions (stubs)"
>:: Stub_tests.test_passing_pointer_through;
"returned globals (foreign)"
>:: Foreign_tests.test_reading_returned_global;
"returned globals (stubs)"
>:: Stub_tests.test_reading_returned_global;
"reading strings"
>:: test_reading_strings;
"arithmetic"
>:: test_pointer_arithmetic;
"comparisons"
>:: test_pointer_comparison;
"differences"
>:: test_pointer_differences;
"raw"
>:: test_raw_pointers;
]
let _ =
run_test_tt_main suite
|
06c97eb7c218f4ffb0ef4a2428af2b5d0d0e3c0103c1602c002972b7657fbeab | mirage/irmin | dict.mli |
* Copyright ( c ) 2018 - 2022 Tarides < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2018-2022 Tarides <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
include Dict_intf.Sigs
* @inline
| null | https://raw.githubusercontent.com/mirage/irmin/abeee121a6db7b085b3c68af50ef24a8d8f9ed05/src/irmin-pack/unix/dict.mli | ocaml |
* Copyright ( c ) 2018 - 2022 Tarides < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2018-2022 Tarides <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
include Dict_intf.Sigs
* @inline
|
|
c9a9a3a2e1c726cd107503dedf3e7c17efbd8c9318617e60ec24311270d3409b | tisnik/clojure-examples | project.clj | ;
( C ) Copyright 2018 , 2020 , 2021
;
; All rights reserved. This program and the accompanying materials
; are made available under the terms of the Eclipse Public License v1.0
; which accompanies this distribution, and is available at
-v10.html
;
; Contributors:
;
(defproject cucumber+expectB "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/data.json "0.2.5"]
[expectations "2.0.9"]]
:plugins [[lein-codox "0.10.7"]
[test2junit "1.1.0"]
[ lein - test - out " 0.3.1 " ]
[lein-cloverage "1.0.7-SNAPSHOT"]
[lein-kibit "0.1.8"]
[lein-clean-m2 "0.1.2"]
[lein-project-edn "0.3.0"]
[lein-marginalia "0.9.1"]
[com.siili/lein-cucumber "1.0.7"]
[lein-expectations "0.0.8"]]
:cucumber-feature-paths ["features/"]
:target-path "target/%s"
:profiles {:uberjar {:aot :all}
:dev {:dependencies [[com.siili/lein-cucumber "1.0.7"]]}})
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/78061b533c0755d0165002961334bbe98d994087/cucumber%2BexpectB/project.clj | clojure |
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
Contributors:
| ( C ) Copyright 2018 , 2020 , 2021
-v10.html
(defproject cucumber+expectB "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/data.json "0.2.5"]
[expectations "2.0.9"]]
:plugins [[lein-codox "0.10.7"]
[test2junit "1.1.0"]
[ lein - test - out " 0.3.1 " ]
[lein-cloverage "1.0.7-SNAPSHOT"]
[lein-kibit "0.1.8"]
[lein-clean-m2 "0.1.2"]
[lein-project-edn "0.3.0"]
[lein-marginalia "0.9.1"]
[com.siili/lein-cucumber "1.0.7"]
[lein-expectations "0.0.8"]]
:cucumber-feature-paths ["features/"]
:target-path "target/%s"
:profiles {:uberjar {:aot :all}
:dev {:dependencies [[com.siili/lein-cucumber "1.0.7"]]}})
|
0e5e2efa09c02785f042d84f0bf0650de55ee448240a214a00824cb7052d1ce7 | MichaelBurge/pyramid-scheme | simplifier.rkt | #lang typed/racket
(require "types.rkt")
(require "ast.rkt")
(require "io.rkt")
(require "expander.rkt")
(require "utils.rkt")
(require "globals.rkt")
(require racket/pretty)
(require typed/racket/unsafe)
(unsafe-require/typed racket/set
[ set-add! (All (A) (-> (Setof A) A Void))]
[ mutable-set (All (A) (-> (Setof A)))])
(define *pass-number* 0)
(provide simplify
simplify-macros
(all-defined-out))
(: simplify Pass)
(define (simplify prog)
(set! prog (fixpass (λ ([ prog : Pyramid])
(set! prog (fixpass pass-expand-macros prog))
(*assume-macros-complete?* #t)
(set! prog (fixpass pass-determine-unknown-applications prog))
prog)
prog))
(set! prog (pass-inline-simple-definitions prog))
(set! prog (fixpass pass-remove-unused-definitions prog))
(set! prog (pass-collapse-nested-begins prog))
;(pretty-print prog)
(set! prog (pass-error-on-undefined-variables prog))
;(pretty-print prog)
(set! prog (pass-remove-empty-asms prog))
(set! prog (pass-collapse-nested-begins prog))
;(pretty-print prog)
prog
)
(define-syntax-rule (define-pass (name prog) body ...)
(define (name prog)
(define (pass) body ...)
(define new-x (pass))
(verbose-section
(format "AST pass '~a" (syntax->datum #'name))
VERBOSITY-HIGH
(pretty-print (pyramid->datum new-x)))
(set! *pass-number* (+ *pass-number* 1))
new-x))
(: pass-expand-macros Pass)
(define-pass (pass-expand-macros prog)
(define prog2
(transform-ast-descendants-on prog pyr-macro-definition?
(λ ([ x : pyr-macro-definition ])
(begin
(install-macro-exp! x)
(pyr-begin '())))))
(define prog3 (fixpass
(λ (x)
(transform-ast-descendants-on x pyr-macro-application? expand-macro))
prog2))
(define prog4 (pass-determine-unknown-applications prog3))
prog4
)
(: simplify-macros Pass)
(define simplify-macros (λ ([ prog : Pyramid ]) (fixpass pass-expand-macros prog)))
(: pass-remove-unused-definitions Pass)
(define-pass (pass-remove-unused-definitions prog)
(let ([ unuseds (set-subtract (defined-vars prog) (used-vars prog))])
(remove-definitions prog unuseds)))
(: pass-error-on-undefined-variables Pass)
(define-pass (pass-error-on-undefined-variables prog)
(let ([ undefineds (set-subtract (used-vars prog) (defined-vars prog))])
(if (set-empty? undefineds)
prog
(begin
(print-ast prog)
(error "Undefined variables" undefineds)))))
(: pass-collapse-nested-begins Pass)
(define-pass (pass-collapse-nested-begins prog)
(transform-ast-descendants-on
prog
pyr-begin?
(λ ([ x : pyr-begin ])
(sequence->exp
(apply append
(map (λ ([y : Pyramid])
(if (pyr-begin? y)
(pyr-begin-body y)
(list y)))
(pyr-begin-body x)))))))
(: pass-inline-simple-definitions Pass)
(define-pass (pass-inline-simple-definitions prog)
(: nonsimple-definitions (Setof Symbol))
(define nonsimple-definitions (mutable-set))
(: simple-definitions (HashTable Symbol Pyramid))
(define simple-definitions (make-hash))
(: simple-definition? (-> Pyramid Boolean : #:+ pyr-definition))
(define (simple-definition? x)
(and (pyr-definition? x)
(not (set-member? nonsimple-definitions (pyr-definition-name x)))
(match (pyr-definition-body x)
[(? pyr-const?) #t]
[(? pyr-variable?) #t]
[(? pyr-quoted?) #t]
[_ #f])))
; Mutated variables can't be inlined.
(let ([ prog (transform-ast-descendants-on
prog pyr-assign?
(λ ([ x : pyr-assign])
(begin
(set-add! nonsimple-definitions (pyr-assign-name x))
x)))])
; Remove simple definitions
(let ([ prog (transform-ast-descendants-on
prog simple-definition?
(λ ([ x : pyr-definition])
(begin
(hash-set! simple-definitions
(pyr-definition-name x)
(pyr-definition-body x))
(pyr-begin '()))))])
(let ([ prog (transform-ast-descendants-on
prog pyr-variable?
(λ ([x : pyr-variable])
(let ([ var (pyr-variable-name x)])
(if (hash-has-key? simple-definitions var)
(hash-ref simple-definitions var)
x))))])
prog))))
(: *fixpass-num-iterations* (Parameterof Integer))
(define *fixpass-num-iterations* (make-parameter 1000))
(: fixpass (-> Pass Pyramid Pyramid))
(define (fixpass pass prog)
(define n (*fixpass-num-iterations*))
(if (< n 0)
(error "fixpass: Maximum iterations reached reducing program" prog)
(parameterize ([ *fixpass-num-iterations* (- n 1)])
(let ([ newprog (pass prog) ])
(if (equal? prog newprog)
prog
(fixpass pass newprog))))))
(: remove-definitions (-> Pyramid (Setof VariableName) Pyramid))
(define (remove-definitions prog vars)
(: transform Pass)
(define (transform x)
(if (and (pyr-definition? x)
(set-member? vars (pyr-definition-name x)))
(pyr-begin '())
x))
(transform-ast-descendants prog transform))
; assume-macros-complete? means "Are all possible macros defined?".
; After macro expansion, every unknown application can default to a function application.
; But during macro expansion, a macro could be defined later even if it isn't now.
(: pass-determine-unknown-applications Pass)
(define-pass (pass-determine-unknown-applications ast)
(transform-ast-descendants-on ast pyr-unknown-application?
(λ ([ x : pyr-unknown-application ])
(: x-name VariableName)
(destruct pyr-unknown-application x)
(if (macro? x-name)
(pyr-macro-application x-name x-app-syntax)
(if (*assume-macros-complete?*)
(unknown->application x)
x)))))
(: pass-remove-empty-asms Pass)
(define-pass (pass-remove-empty-asms ast)
(transform-ast-descendants-on ast pyr-asm?
(λ ([ x : pyr-asm ])
(if (null? (pyr-asm-insts x))
(pyr-begin (list))
x))))
(: defined-vars (-> Pyramid (Setof VariableName)))
(define (defined-vars prog)
(apply set (append (map pyr-definition-name (all-definitions prog))
(apply append (map pyr-lambda-names (all-lambdas prog))))))
(: used-vars (-> Pyramid (Setof VariableName)))
(define (used-vars prog)
(let* ([ vars : pyr-variables (all-variables prog)]
[ names : VariableNames ((inst map VariableName pyr-variable) pyr-variable-name vars)]
[ assign-vars (all-assigns prog)]
[ assign-var-names (map pyr-assign-name assign-vars)]
)
(set-union (apply set names)
(apply set assign-var-names))))
| null | https://raw.githubusercontent.com/MichaelBurge/pyramid-scheme/d38ba194dca8eced474fb26956864ea30f9e23ce/simplifier.rkt | racket | (pretty-print prog)
(pretty-print prog)
(pretty-print prog)
Mutated variables can't be inlined.
Remove simple definitions
assume-macros-complete? means "Are all possible macros defined?".
After macro expansion, every unknown application can default to a function application.
But during macro expansion, a macro could be defined later even if it isn't now. | #lang typed/racket
(require "types.rkt")
(require "ast.rkt")
(require "io.rkt")
(require "expander.rkt")
(require "utils.rkt")
(require "globals.rkt")
(require racket/pretty)
(require typed/racket/unsafe)
(unsafe-require/typed racket/set
[ set-add! (All (A) (-> (Setof A) A Void))]
[ mutable-set (All (A) (-> (Setof A)))])
(define *pass-number* 0)
(provide simplify
simplify-macros
(all-defined-out))
(: simplify Pass)
(define (simplify prog)
(set! prog (fixpass (λ ([ prog : Pyramid])
(set! prog (fixpass pass-expand-macros prog))
(*assume-macros-complete?* #t)
(set! prog (fixpass pass-determine-unknown-applications prog))
prog)
prog))
(set! prog (pass-inline-simple-definitions prog))
(set! prog (fixpass pass-remove-unused-definitions prog))
(set! prog (pass-collapse-nested-begins prog))
(set! prog (pass-error-on-undefined-variables prog))
(set! prog (pass-remove-empty-asms prog))
(set! prog (pass-collapse-nested-begins prog))
prog
)
(define-syntax-rule (define-pass (name prog) body ...)
(define (name prog)
(define (pass) body ...)
(define new-x (pass))
(verbose-section
(format "AST pass '~a" (syntax->datum #'name))
VERBOSITY-HIGH
(pretty-print (pyramid->datum new-x)))
(set! *pass-number* (+ *pass-number* 1))
new-x))
(: pass-expand-macros Pass)
(define-pass (pass-expand-macros prog)
(define prog2
(transform-ast-descendants-on prog pyr-macro-definition?
(λ ([ x : pyr-macro-definition ])
(begin
(install-macro-exp! x)
(pyr-begin '())))))
(define prog3 (fixpass
(λ (x)
(transform-ast-descendants-on x pyr-macro-application? expand-macro))
prog2))
(define prog4 (pass-determine-unknown-applications prog3))
prog4
)
(: simplify-macros Pass)
(define simplify-macros (λ ([ prog : Pyramid ]) (fixpass pass-expand-macros prog)))
(: pass-remove-unused-definitions Pass)
(define-pass (pass-remove-unused-definitions prog)
(let ([ unuseds (set-subtract (defined-vars prog) (used-vars prog))])
(remove-definitions prog unuseds)))
(: pass-error-on-undefined-variables Pass)
(define-pass (pass-error-on-undefined-variables prog)
(let ([ undefineds (set-subtract (used-vars prog) (defined-vars prog))])
(if (set-empty? undefineds)
prog
(begin
(print-ast prog)
(error "Undefined variables" undefineds)))))
(: pass-collapse-nested-begins Pass)
(define-pass (pass-collapse-nested-begins prog)
(transform-ast-descendants-on
prog
pyr-begin?
(λ ([ x : pyr-begin ])
(sequence->exp
(apply append
(map (λ ([y : Pyramid])
(if (pyr-begin? y)
(pyr-begin-body y)
(list y)))
(pyr-begin-body x)))))))
(: pass-inline-simple-definitions Pass)
(define-pass (pass-inline-simple-definitions prog)
(: nonsimple-definitions (Setof Symbol))
(define nonsimple-definitions (mutable-set))
(: simple-definitions (HashTable Symbol Pyramid))
(define simple-definitions (make-hash))
(: simple-definition? (-> Pyramid Boolean : #:+ pyr-definition))
(define (simple-definition? x)
(and (pyr-definition? x)
(not (set-member? nonsimple-definitions (pyr-definition-name x)))
(match (pyr-definition-body x)
[(? pyr-const?) #t]
[(? pyr-variable?) #t]
[(? pyr-quoted?) #t]
[_ #f])))
(let ([ prog (transform-ast-descendants-on
prog pyr-assign?
(λ ([ x : pyr-assign])
(begin
(set-add! nonsimple-definitions (pyr-assign-name x))
x)))])
(let ([ prog (transform-ast-descendants-on
prog simple-definition?
(λ ([ x : pyr-definition])
(begin
(hash-set! simple-definitions
(pyr-definition-name x)
(pyr-definition-body x))
(pyr-begin '()))))])
(let ([ prog (transform-ast-descendants-on
prog pyr-variable?
(λ ([x : pyr-variable])
(let ([ var (pyr-variable-name x)])
(if (hash-has-key? simple-definitions var)
(hash-ref simple-definitions var)
x))))])
prog))))
(: *fixpass-num-iterations* (Parameterof Integer))
(define *fixpass-num-iterations* (make-parameter 1000))
(: fixpass (-> Pass Pyramid Pyramid))
(define (fixpass pass prog)
(define n (*fixpass-num-iterations*))
(if (< n 0)
(error "fixpass: Maximum iterations reached reducing program" prog)
(parameterize ([ *fixpass-num-iterations* (- n 1)])
(let ([ newprog (pass prog) ])
(if (equal? prog newprog)
prog
(fixpass pass newprog))))))
(: remove-definitions (-> Pyramid (Setof VariableName) Pyramid))
(define (remove-definitions prog vars)
(: transform Pass)
(define (transform x)
(if (and (pyr-definition? x)
(set-member? vars (pyr-definition-name x)))
(pyr-begin '())
x))
(transform-ast-descendants prog transform))
(: pass-determine-unknown-applications Pass)
(define-pass (pass-determine-unknown-applications ast)
(transform-ast-descendants-on ast pyr-unknown-application?
(λ ([ x : pyr-unknown-application ])
(: x-name VariableName)
(destruct pyr-unknown-application x)
(if (macro? x-name)
(pyr-macro-application x-name x-app-syntax)
(if (*assume-macros-complete?*)
(unknown->application x)
x)))))
(: pass-remove-empty-asms Pass)
(define-pass (pass-remove-empty-asms ast)
(transform-ast-descendants-on ast pyr-asm?
(λ ([ x : pyr-asm ])
(if (null? (pyr-asm-insts x))
(pyr-begin (list))
x))))
(: defined-vars (-> Pyramid (Setof VariableName)))
(define (defined-vars prog)
(apply set (append (map pyr-definition-name (all-definitions prog))
(apply append (map pyr-lambda-names (all-lambdas prog))))))
(: used-vars (-> Pyramid (Setof VariableName)))
(define (used-vars prog)
(let* ([ vars : pyr-variables (all-variables prog)]
[ names : VariableNames ((inst map VariableName pyr-variable) pyr-variable-name vars)]
[ assign-vars (all-assigns prog)]
[ assign-var-names (map pyr-assign-name assign-vars)]
)
(set-union (apply set names)
(apply set assign-var-names))))
|
36e63073fc9cbd4cd32df889a4e05ea0d6946c573d971fae738775da79615bba | mnieper/unsyntax | runtime.scm | Copyright © ( 2020 ) .
;; This file is part of unsyntax.
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation files
( the " Software " ) , to deal in the Software without restriction ,
;; including without limitation the rights to use, copy, modify, merge,
publish , distribute , sublicense , and/or sell copies of the Software ,
and to permit persons to whom the Software is furnished to do so ,
;; subject to the following conditions:
;; The above copyright notice and this permission notice (including the
;; next paragraph) shall be included in all copies or substantial
portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(include-library-declarations "stdlibs/runtime-exports.scm")
(export current-features with-error-handler expand-unsyntax unsyntax-scheme
install-library rib syntax-object)
(import (rename (except (scheme base) define-record-type)
(features host-features))
(scheme case-lambda)
(scheme char)
(scheme complex)
(scheme cxr)
(rename (scheme eval)
(eval host-eval)
(environment host-environment))
(scheme file)
(scheme inexact)
(scheme lazy)
(scheme time)
(rename (scheme process-context)
(command-line host-command-line))
(scheme write)
(srfi 27)
(srfi 125)
(srfi 128)
(unsyntax define-record-type)
(unsyntax syntax-object)
(unsyntax gensym))
(begin
(define-syntax rib
(syntax-rules ()
((rib chunk* ...)
(list #f 'chunk* ...))))
(define-syntax syntax-object
(syntax-rules ()
((syntax-object expr marks substs)
(make-syntax-object expr
'marks
(list . substs)
#f)))))
| null | https://raw.githubusercontent.com/mnieper/unsyntax/cd12891805a93229255ff0f2c46cf0e2b5316c7c/src/unsyntax/stdlibs/runtime.scm | scheme | This file is part of unsyntax.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
including without limitation the rights to use, copy, modify, merge,
subject to the following conditions:
The above copyright notice and this permission notice (including the
next paragraph) shall be included in all copies or substantial
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. | Copyright © ( 2020 ) .
( the " Software " ) , to deal in the Software without restriction ,
publish , distribute , sublicense , and/or sell copies of the Software ,
and to permit persons to whom the Software is furnished to do so ,
portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
(include-library-declarations "stdlibs/runtime-exports.scm")
(export current-features with-error-handler expand-unsyntax unsyntax-scheme
install-library rib syntax-object)
(import (rename (except (scheme base) define-record-type)
(features host-features))
(scheme case-lambda)
(scheme char)
(scheme complex)
(scheme cxr)
(rename (scheme eval)
(eval host-eval)
(environment host-environment))
(scheme file)
(scheme inexact)
(scheme lazy)
(scheme time)
(rename (scheme process-context)
(command-line host-command-line))
(scheme write)
(srfi 27)
(srfi 125)
(srfi 128)
(unsyntax define-record-type)
(unsyntax syntax-object)
(unsyntax gensym))
(begin
(define-syntax rib
(syntax-rules ()
((rib chunk* ...)
(list #f 'chunk* ...))))
(define-syntax syntax-object
(syntax-rules ()
((syntax-object expr marks substs)
(make-syntax-object expr
'marks
(list . substs)
#f)))))
|
6cdb9a68607fabc0a5062e690df77cd0c3451b40e80eda97cc2d9eb681322a38 | saner/fun-os | CompileUtils.hs | module CompileUtils where
import Prelude
import Control.Monad
import Control.Monad.State
import System.Environment
import System.IO
import System.IO.Unsafe
import System.FilePath
import qualified Data.Map as Map
import Parser
import PreCompiler
import Compiler
import ArmInstructions
-- printing nicely generated code
formatCompCode ([]) = ""
formatCompCode (code:rest) =
let codeF = case code of
Label l -> line (show code)
Special s -> indentLine (show code)
_ -> indentLine (show code)
in codeF ++ (formatCompCode rest)
where
indentLine l = " " ++ l ++ "\n"
line l = l ++ "\n"
compile :: String -> Either String [ArmInstruction]
compile code = do
case parseCode code of
Left error -> Left ("Error, parsing: \n" ++ show error)
Right code -> do
let preCompiledCode = preCompileCode code
let compiled = evalState (compileCode preCompiledCode) (Map.fromList [], Map.fromList [], 0, (-1, -1))
Right compiled
compileFile fileName = do
let outputFileName = replaceExtension fileName ".s"
contents <- readFile fileName
let compiled = CompileUtils.compile contents
case compiled of
Left str -> putStrLn str
Right insts ->
writeFile outputFileName $ formatCompCode insts
| null | https://raw.githubusercontent.com/saner/fun-os/4f0bf0d536401613717b312c67cb43c298dbdf9d/compiler/CompileUtils.hs | haskell | printing nicely generated code | module CompileUtils where
import Prelude
import Control.Monad
import Control.Monad.State
import System.Environment
import System.IO
import System.IO.Unsafe
import System.FilePath
import qualified Data.Map as Map
import Parser
import PreCompiler
import Compiler
import ArmInstructions
formatCompCode ([]) = ""
formatCompCode (code:rest) =
let codeF = case code of
Label l -> line (show code)
Special s -> indentLine (show code)
_ -> indentLine (show code)
in codeF ++ (formatCompCode rest)
where
indentLine l = " " ++ l ++ "\n"
line l = l ++ "\n"
compile :: String -> Either String [ArmInstruction]
compile code = do
case parseCode code of
Left error -> Left ("Error, parsing: \n" ++ show error)
Right code -> do
let preCompiledCode = preCompileCode code
let compiled = evalState (compileCode preCompiledCode) (Map.fromList [], Map.fromList [], 0, (-1, -1))
Right compiled
compileFile fileName = do
let outputFileName = replaceExtension fileName ".s"
contents <- readFile fileName
let compiled = CompileUtils.compile contents
case compiled of
Left str -> putStrLn str
Right insts ->
writeFile outputFileName $ formatCompCode insts
|
c388ca098be842a60869c6c8ca7d3e49be044d8dd0dc3229342fc7bed7e0fc37 | thheller/shadow-cljs | cli_actual.clj | (ns shadow.cljs.devtools.cli-actual
(:require
[clojure.string :as str]
[clojure.main :as main]
[shadow.cljs.silence-default-loggers]
[shadow.cljs.devtools.config :as config]
[shadow.cljs.devtools.cli-opts :as opts]
[shadow.cljs.devtools.api :as api]
[shadow.cljs.devtools.errors :as errors]
[shadow.cljs.devtools.server.npm-deps :as npm-deps]
[shadow.build.api :as cljs]
[shadow.build.node :as node]
[shadow.cljs.devtools.server.socket-repl :as socket-repl]
[shadow.cljs.devtools.server.env :as env]
[shadow.cljs.devtools.server.runtime :as runtime])
(:import (clojure.lang LineNumberingPushbackReader)
(java.io StringReader)))
;; delayed require to we can improve startup time a bit
(defn lazy-invoke [var-sym & args]
(require (-> var-sym namespace symbol))
(let [var (find-var var-sym)]
(apply var args)))
(defn do-build-command [{:keys [action options] :as opts} build-config]
(case action
:release
(api/release* build-config options)
:check
(api/check* build-config options)
:compile
(api/compile* build-config options)
(throw (ex-info "invalid action" {:opts opts :build-config build-config}))))
(defn do-build-commands
[{:keys [builds] :as config} {:keys [action options] :as opts} build-ids]
;; sequentially run the commands
(doseq [build-id build-ids]
(let [build-config (get builds build-id)]
(when-not build-config
(throw (ex-info (str "no build with id: " build-id)
{:build-id build-id
:known-builds (-> builds (keys) (set))})))
(do-build-command opts build-config))))
(defn do-clj-eval [config {:keys [arguments options] :as opts}]
(let [in
(if (:stdin options)
*in*
(-> (str/join " " arguments)
(StringReader.)
(LineNumberingPushbackReader.)))]
(binding [*in* in]
(main/repl
:init #(socket-repl/repl-init {:print false})
:prompt (fn [])))
))
(defn do-clj-run [config {:keys [arguments options] :as opts}]
(let [[main & args]
arguments
main-sym
(symbol main)
main-sym
(if (nil? (namespace main-sym))
(symbol main "-main")
main-sym)
main-ns
(namespace main-sym)]
(try
(require (symbol main-ns))
(catch Exception e
(throw (ex-info
(format "failed to load namespace: %s" main-ns)
{:tag ::clj-run-load
:main-ns main-ns
:main-sym main-sym} e))))
(let [main-var (find-var main-sym)]
(if-not main-var
(println (format "could not find %s" main-sym))
(let [main-meta (meta main-var)]
(try
(cond
;; running in server
(runtime/get-instance)
(apply main-var args)
new jvm . task fn wants to run watch
(:shadow/requires-server main-meta)
(do (lazy-invoke 'shadow.cljs.devtools.server/start!)
(apply main-var args)
(lazy-invoke 'shadow.cljs.devtools.server/wait-for-stop!))
new jvm . task fn does n't need watch
:else
(api/with-runtime
(apply main-var args)))
(catch Exception e
(throw (ex-info
(format "failed to run function: %s" main-sym)
{:tag ::clj-run
:main-sym main-sym}
e)))))))))
(defn blocking-action
[config {:keys [action builds options] :as opts}]
(binding [*in* *in*]
(cond
(= :clj-eval action)
(api/with-runtime
(do-clj-eval config opts))
(or (= :clj-run action)
(= :run action))
(do-clj-run config opts)
(contains? #{:watch :node-repl :browser-repl :cljs-repl :clj-repl :server} action)
(lazy-invoke 'shadow.cljs.devtools.server/from-cli action builds options)
)))
(defn main [& args]
(let [{:keys [action builds options summary errors] :as opts}
(opts/parse args)
config
(config/load-cljs-edn!)]
;; always install since its a noop if everything is in package.json
;; and a server restart is not required for them to be picked up
(npm-deps/main config opts)
FIXME : need cleaner with - runtime logic
;; don't like that some actions implicitely start a server
;; while others don't
;; I think server should be a dedicated action but that only makes sense once we have a UI
(cond
;;
;; actions that do a thing and exit
;;
(:version options)
(println "TBD")
(or (:help options) (seq errors))
(opts/help opts)
;;(= action :test)
;;(api/test-all)
(= :npm-deps action)
(println "npm-deps done.")
(contains? #{:compile :check :release} action)
(api/with-runtime
(do-build-commands config opts builds))
MVP , really not sure where to take this
(= :test action)
(api/with-runtime
(api/test))
;;
;; actions that may potentially block
;;
(contains? #{:watch :node-repl :browser-repl :cljs-repl :clj-repl :server :clj-eval :clj-run :run} action)
(blocking-action config opts)
:else
(println "Unknown action.")
)))
(defn print-main-error [e]
(try
(errors/user-friendly-error e)
(catch Exception ignored
;; print failed, don't attempt to print anything again
)))
(defn print-token
"attempts to print the given token to stdout which may be a socket
if the client already closed the socket that would cause a SocketException
so we ignore any errors since the client is already gone"
[token]
(try
(println token)
(catch Exception e
;; CTRL+D closes socket so we can't write to it anymore
)))
(defn from-remote
"the CLI script calls this with 2 extra token (uuids) that will be printed to notify
the script whether or not to exit with an error code, it also causes the client to
disconnect instead of us forcibly dropping the connection"
[complete-token error-token args]
(try
(if (env/restart-required?)
(do (println "SERVER INSTANCE OUT OF DATE!\nPlease restart.")
(print-token error-token))
(do (apply main "--via" "remote" args)
(print-token complete-token)))
(catch Exception e
(print-main-error e)
(println error-token))))
;; direct launches don't need to mess with tokens
(defn -main [& args]
(try
(apply main "--via" "main" args)
(shutdown-agents)
(catch Exception e
(print-main-error e)
(System/exit 1))))
(defn from-launcher [deps-loader-fn args]
(reset! api/reload-deps-fn-ref deps-loader-fn)
(try
(apply main "--via" "launcher" args)
(shutdown-agents)
(catch Exception e
(print-main-error e)
(System/exit 1))))
(comment
(defn autotest
"no way to interrupt this, don't run this in nREPL"
[]
(-> (api/test-setup)
(cljs/watch-and-repeat!
(fn [state modified]
(-> state
(cond->
first pass , run all tests
(empty? modified)
(node/execute-all-tests!)
;; only execute tests that might have been affected by the modified files
(not (empty? modified))
(node/execute-affected-tests! modified))
)))))
(defn test-all []
(api/test-all))
(defn test-affected [test-ns]
(api/test-affected [(cljs/ns->cljs-file test-ns)]))) | null | https://raw.githubusercontent.com/thheller/shadow-cljs/ba0a02aec050c6bc8db1932916009400f99d3cce/src/main/shadow/cljs/devtools/cli_actual.clj | clojure | delayed require to we can improve startup time a bit
sequentially run the commands
running in server
always install since its a noop if everything is in package.json
and a server restart is not required for them to be picked up
don't like that some actions implicitely start a server
while others don't
I think server should be a dedicated action but that only makes sense once we have a UI
actions that do a thing and exit
(= action :test)
(api/test-all)
actions that may potentially block
print failed, don't attempt to print anything again
CTRL+D closes socket so we can't write to it anymore
direct launches don't need to mess with tokens
only execute tests that might have been affected by the modified files | (ns shadow.cljs.devtools.cli-actual
(:require
[clojure.string :as str]
[clojure.main :as main]
[shadow.cljs.silence-default-loggers]
[shadow.cljs.devtools.config :as config]
[shadow.cljs.devtools.cli-opts :as opts]
[shadow.cljs.devtools.api :as api]
[shadow.cljs.devtools.errors :as errors]
[shadow.cljs.devtools.server.npm-deps :as npm-deps]
[shadow.build.api :as cljs]
[shadow.build.node :as node]
[shadow.cljs.devtools.server.socket-repl :as socket-repl]
[shadow.cljs.devtools.server.env :as env]
[shadow.cljs.devtools.server.runtime :as runtime])
(:import (clojure.lang LineNumberingPushbackReader)
(java.io StringReader)))
(defn lazy-invoke [var-sym & args]
(require (-> var-sym namespace symbol))
(let [var (find-var var-sym)]
(apply var args)))
(defn do-build-command [{:keys [action options] :as opts} build-config]
(case action
:release
(api/release* build-config options)
:check
(api/check* build-config options)
:compile
(api/compile* build-config options)
(throw (ex-info "invalid action" {:opts opts :build-config build-config}))))
(defn do-build-commands
[{:keys [builds] :as config} {:keys [action options] :as opts} build-ids]
(doseq [build-id build-ids]
(let [build-config (get builds build-id)]
(when-not build-config
(throw (ex-info (str "no build with id: " build-id)
{:build-id build-id
:known-builds (-> builds (keys) (set))})))
(do-build-command opts build-config))))
(defn do-clj-eval [config {:keys [arguments options] :as opts}]
(let [in
(if (:stdin options)
*in*
(-> (str/join " " arguments)
(StringReader.)
(LineNumberingPushbackReader.)))]
(binding [*in* in]
(main/repl
:init #(socket-repl/repl-init {:print false})
:prompt (fn [])))
))
(defn do-clj-run [config {:keys [arguments options] :as opts}]
(let [[main & args]
arguments
main-sym
(symbol main)
main-sym
(if (nil? (namespace main-sym))
(symbol main "-main")
main-sym)
main-ns
(namespace main-sym)]
(try
(require (symbol main-ns))
(catch Exception e
(throw (ex-info
(format "failed to load namespace: %s" main-ns)
{:tag ::clj-run-load
:main-ns main-ns
:main-sym main-sym} e))))
(let [main-var (find-var main-sym)]
(if-not main-var
(println (format "could not find %s" main-sym))
(let [main-meta (meta main-var)]
(try
(cond
(runtime/get-instance)
(apply main-var args)
new jvm . task fn wants to run watch
(:shadow/requires-server main-meta)
(do (lazy-invoke 'shadow.cljs.devtools.server/start!)
(apply main-var args)
(lazy-invoke 'shadow.cljs.devtools.server/wait-for-stop!))
new jvm . task fn does n't need watch
:else
(api/with-runtime
(apply main-var args)))
(catch Exception e
(throw (ex-info
(format "failed to run function: %s" main-sym)
{:tag ::clj-run
:main-sym main-sym}
e)))))))))
(defn blocking-action
[config {:keys [action builds options] :as opts}]
(binding [*in* *in*]
(cond
(= :clj-eval action)
(api/with-runtime
(do-clj-eval config opts))
(or (= :clj-run action)
(= :run action))
(do-clj-run config opts)
(contains? #{:watch :node-repl :browser-repl :cljs-repl :clj-repl :server} action)
(lazy-invoke 'shadow.cljs.devtools.server/from-cli action builds options)
)))
(defn main [& args]
(let [{:keys [action builds options summary errors] :as opts}
(opts/parse args)
config
(config/load-cljs-edn!)]
(npm-deps/main config opts)
FIXME : need cleaner with - runtime logic
(cond
(:version options)
(println "TBD")
(or (:help options) (seq errors))
(opts/help opts)
(= :npm-deps action)
(println "npm-deps done.")
(contains? #{:compile :check :release} action)
(api/with-runtime
(do-build-commands config opts builds))
MVP , really not sure where to take this
(= :test action)
(api/with-runtime
(api/test))
(contains? #{:watch :node-repl :browser-repl :cljs-repl :clj-repl :server :clj-eval :clj-run :run} action)
(blocking-action config opts)
:else
(println "Unknown action.")
)))
(defn print-main-error [e]
(try
(errors/user-friendly-error e)
(catch Exception ignored
)))
(defn print-token
"attempts to print the given token to stdout which may be a socket
if the client already closed the socket that would cause a SocketException
so we ignore any errors since the client is already gone"
[token]
(try
(println token)
(catch Exception e
)))
(defn from-remote
"the CLI script calls this with 2 extra token (uuids) that will be printed to notify
the script whether or not to exit with an error code, it also causes the client to
disconnect instead of us forcibly dropping the connection"
[complete-token error-token args]
(try
(if (env/restart-required?)
(do (println "SERVER INSTANCE OUT OF DATE!\nPlease restart.")
(print-token error-token))
(do (apply main "--via" "remote" args)
(print-token complete-token)))
(catch Exception e
(print-main-error e)
(println error-token))))
(defn -main [& args]
(try
(apply main "--via" "main" args)
(shutdown-agents)
(catch Exception e
(print-main-error e)
(System/exit 1))))
(defn from-launcher [deps-loader-fn args]
(reset! api/reload-deps-fn-ref deps-loader-fn)
(try
(apply main "--via" "launcher" args)
(shutdown-agents)
(catch Exception e
(print-main-error e)
(System/exit 1))))
(comment
(defn autotest
"no way to interrupt this, don't run this in nREPL"
[]
(-> (api/test-setup)
(cljs/watch-and-repeat!
(fn [state modified]
(-> state
(cond->
first pass , run all tests
(empty? modified)
(node/execute-all-tests!)
(not (empty? modified))
(node/execute-affected-tests! modified))
)))))
(defn test-all []
(api/test-all))
(defn test-affected [test-ns]
(api/test-affected [(cljs/ns->cljs-file test-ns)]))) |
5fe15ba1548c38bd9a742abd860bfccc03d84c13e92e0d47c689011d070e8694 | RestitutorOrbis/adventura | Labyrinth.hs | module Labyrinth
(
Path(..)
,Labyrinth
,generateLabyrinth
) where
import System.Random
import Enemies
import Weapons
data Path = Path {enemies:: [Enemy],rewardWeapon :: Weapon} deriving (Show)
type Labyrinth = [[Path]]
generateListOfRandomInts :: RandomGen g => g -> Int -> (Int, Int) -> [Int]
generateListOfRandomInts generator number range = take number $ randomRs range generator :: [Int]
generatePathTemplate :: StdGen -> [Enemy] -> [Weapon] -> Int -> Path
generatePathTemplate generator enemies weapons maxEnemies=
let (numEnemies,gen')=randomR (1,maxEnemies) generator :: (Int,StdGen)
(weaponIndex,gen'')=randomR (1,(length weapons)-1) gen' :: (Int,StdGen)
enemiesLength=length enemies
randomInts=generateListOfRandomInts gen'' numEnemies (1,enemiesLength-1)
in Path [enemies!!x|x<-randomInts] (weapons!!weaponIndex)
generateEasyPath :: StdGen -> Path
generateEasyPath generator=generatePathTemplate generator weakEnemies weakWeapons 5
generateModeratePath :: StdGen -> Path
generateModeratePath generator=generatePathTemplate generator strongEnemies mediocreWeapons 3
generateHardPath :: StdGen -> Path
generateHardPath generator=generatePathTemplate generator bosses strongWeapons 1
generatePath :: (Num a, Ord a) => a -> StdGen -> Path
generatePath difficultyLevel generator
|difficultyLevel<=1 = generateEasyPath generator
|difficultyLevel==2 = generateModeratePath generator
|otherwise = generateHardPath generator
generateNumberOfPaths :: Int -> StdGen -> [Int]
generateNumberOfPaths n generator=take n $ randomRs (1,3) generator :: [Int]
generatePaths::[StdGen]->Int->[Int]->[[Path]]
generatePaths generators difficultyLevel listOfNumPaths=
let randoms=take 200 $ randomRs (0,(length generators)-1) (generators!!0) :: [Int]
randomGenerators=map (generators!!) randoms
numPathsWithIndexes=zip listOfNumPaths [0..(length listOfNumPaths)-1]
in [[generatePath difficultyLevel (randomGenerators!!((snd x)+y)) |y<-[0..(fst x)-1]]|x<-numPathsWithIndexes]
generateLabyrinth :: [StdGen] -> Labyrinth
generateLabyrinth gens =
let numEasyPaths = generateNumberOfPaths 1 (gens!!0)
easyPaths=generatePaths gens 1 numEasyPaths
numMediumPaths=generateNumberOfPaths 1 (gens!!1)
mediumPaths=generatePaths gens 2 numMediumPaths
hardPaths=[[generateHardPath (gens!!2)]]
in easyPaths++mediumPaths++hardPaths
| null | https://raw.githubusercontent.com/RestitutorOrbis/adventura/2bea02254e1c9583f8557b8a825bb9388bbb2c14/Labyrinth.hs | haskell | module Labyrinth
(
Path(..)
,Labyrinth
,generateLabyrinth
) where
import System.Random
import Enemies
import Weapons
data Path = Path {enemies:: [Enemy],rewardWeapon :: Weapon} deriving (Show)
type Labyrinth = [[Path]]
generateListOfRandomInts :: RandomGen g => g -> Int -> (Int, Int) -> [Int]
generateListOfRandomInts generator number range = take number $ randomRs range generator :: [Int]
generatePathTemplate :: StdGen -> [Enemy] -> [Weapon] -> Int -> Path
generatePathTemplate generator enemies weapons maxEnemies=
let (numEnemies,gen')=randomR (1,maxEnemies) generator :: (Int,StdGen)
(weaponIndex,gen'')=randomR (1,(length weapons)-1) gen' :: (Int,StdGen)
enemiesLength=length enemies
randomInts=generateListOfRandomInts gen'' numEnemies (1,enemiesLength-1)
in Path [enemies!!x|x<-randomInts] (weapons!!weaponIndex)
generateEasyPath :: StdGen -> Path
generateEasyPath generator=generatePathTemplate generator weakEnemies weakWeapons 5
generateModeratePath :: StdGen -> Path
generateModeratePath generator=generatePathTemplate generator strongEnemies mediocreWeapons 3
generateHardPath :: StdGen -> Path
generateHardPath generator=generatePathTemplate generator bosses strongWeapons 1
generatePath :: (Num a, Ord a) => a -> StdGen -> Path
generatePath difficultyLevel generator
|difficultyLevel<=1 = generateEasyPath generator
|difficultyLevel==2 = generateModeratePath generator
|otherwise = generateHardPath generator
generateNumberOfPaths :: Int -> StdGen -> [Int]
generateNumberOfPaths n generator=take n $ randomRs (1,3) generator :: [Int]
generatePaths::[StdGen]->Int->[Int]->[[Path]]
generatePaths generators difficultyLevel listOfNumPaths=
let randoms=take 200 $ randomRs (0,(length generators)-1) (generators!!0) :: [Int]
randomGenerators=map (generators!!) randoms
numPathsWithIndexes=zip listOfNumPaths [0..(length listOfNumPaths)-1]
in [[generatePath difficultyLevel (randomGenerators!!((snd x)+y)) |y<-[0..(fst x)-1]]|x<-numPathsWithIndexes]
generateLabyrinth :: [StdGen] -> Labyrinth
generateLabyrinth gens =
let numEasyPaths = generateNumberOfPaths 1 (gens!!0)
easyPaths=generatePaths gens 1 numEasyPaths
numMediumPaths=generateNumberOfPaths 1 (gens!!1)
mediumPaths=generatePaths gens 2 numMediumPaths
hardPaths=[[generateHardPath (gens!!2)]]
in easyPaths++mediumPaths++hardPaths
|
|
bc4b81d0307d53f32b8363d15324f033e98e7dab0f780f32d868e69802cca27e | ofmooseandmen/Aeromess | F19.hs | -- |
ICAO Field Type 19 parser .
module Data.Icao.F19
( parser
) where
import Data.Aeromess.Parser
import Data.Char ()
import Data.Either ()
import Data.Icao.Lang
import Data.Icao.SupplementaryInformation
import qualified Data.Icao.Switches as S
import Data.Icao.Time
import Data.List hiding (words)
import Data.Maybe
import Prelude hiding (words)
data Data
= Fe Hhmm
| Pob PersonsOnBoard
| At [Transmitter]
| Se [SurvivalEquipment]
| Lj [LifeJacket]
| Di Dinghies
| Ad FreeText
| Rmk FreeText
| Pn FreeText
data SwitchKey
= E
| P
| R
| S
| J
| D
| A
| N
| C
deriving (Bounded, Enum, Eq, Read, Show)
suppInfoFiller :: Data -> SupplementaryInformation -> SupplementaryInformation
suppInfoFiller (Fe x) o = o {fuelEndurance = Just x}
suppInfoFiller (Pob x) o = o {personsOnBoard = Just x}
suppInfoFiller (At x) o = o {availableTransmitters = x}
suppInfoFiller (Se x) o = o {survivalEquipments = x}
suppInfoFiller (Lj x) o = o {lifeJackets = x}
suppInfoFiller (Di x) o = o {dinghies = x}
suppInfoFiller (Ad x) o = o {aircraftDescription = Just x}
suppInfoFiller (Rmk x) o = o {otherRemarks = Just x}
suppInfoFiller (Pn x) o = o {pilotInCommand = Just x}
mkSuppInformation :: [Data] -> SupplementaryInformation
mkSuppInformation = foldl (flip suppInfoFiller) emptySupplementaryInformation
pobParser :: Parser PersonsOnBoard
pobParser = do
n <- natural 3 <|> natural 2 <|> natural 1
mkPersonsOnBoard n
transmitterParser :: Parser Transmitter
transmitterParser = do
c <- oneOf "UVE"
return $
case c of
'U' -> UHF
'V' -> VHF
'E' -> ELT
_ -> error "?"
atParser :: Parser [Transmitter]
atParser = some transmitterParser
survEquipParser :: Parser SurvivalEquipment
survEquipParser = do
c <- oneOf "PDMJ"
return $
case c of
'P' -> Polar
'D' -> Desert
'M' -> Maritime
'J' -> Jungle
_ -> error "?"
seParser :: Parser [SurvivalEquipment]
seParser = some survEquipParser
lfParser :: Parser LifeJacket
lfParser = do
c <- oneOf "LF"
return $
case c of
'L' -> WithLight
'F' -> WithFluorescein
_ -> error "?"
uvParser :: Parser LifeJacket
uvParser = do
c <- oneOf "UV"
return $
case c of
'U' -> WithRadioUHF
'V' -> WithRadioVHF
_ -> error "?"
ljParser :: Parser [LifeJacket]
ljParser = do
uv <- many lfParser
_ <- try space
lf <- many uvParser
return (uv ++ lf)
2 NUMERICS giving the number of dinghies carried ,
3 NUMERICS giving the total capacity , in persons carried , of all dinghies .
-- C if dinghies are covered.
-- The colour of the dinghies (e.g. RED).
deParser :: Parser Dinghies
deParser = do
nb <- optional (natural 2 <* space)
capa <- optional (natural 3 <* space)
cov <- optional (char 'C' <* space)
col <- optional word
mkDinghies nb capa (isJust cov) col
switchParser :: Parser (Maybe Data)
switchParser =
S.parser E hhmmParser Fe <|> S.parser P pobParser Pob <|> S.parser R atParser At <|>
S.parser S seParser Se <|>
S.parser J ljParser Lj <|>
S.parser D deParser Di <|>
S.parser A freeTextParser Ad <|>
S.parser N freeTextParser Rmk <|>
S.parser C freeTextParser Pn
-- | 'SupplementaryInformation' parser.
parser :: Parser SupplementaryInformation
parser = do
s <- some switchParser
_ <- endOfFieldParser
return (mkSuppInformation (catMaybes s))
| null | https://raw.githubusercontent.com/ofmooseandmen/Aeromess/765f3ea10073993e43c71b6b6955b9f0d234a4ef/src/Data/Icao/F19.hs | haskell | |
C if dinghies are covered.
The colour of the dinghies (e.g. RED).
| 'SupplementaryInformation' parser. | ICAO Field Type 19 parser .
module Data.Icao.F19
( parser
) where
import Data.Aeromess.Parser
import Data.Char ()
import Data.Either ()
import Data.Icao.Lang
import Data.Icao.SupplementaryInformation
import qualified Data.Icao.Switches as S
import Data.Icao.Time
import Data.List hiding (words)
import Data.Maybe
import Prelude hiding (words)
data Data
= Fe Hhmm
| Pob PersonsOnBoard
| At [Transmitter]
| Se [SurvivalEquipment]
| Lj [LifeJacket]
| Di Dinghies
| Ad FreeText
| Rmk FreeText
| Pn FreeText
data SwitchKey
= E
| P
| R
| S
| J
| D
| A
| N
| C
deriving (Bounded, Enum, Eq, Read, Show)
suppInfoFiller :: Data -> SupplementaryInformation -> SupplementaryInformation
suppInfoFiller (Fe x) o = o {fuelEndurance = Just x}
suppInfoFiller (Pob x) o = o {personsOnBoard = Just x}
suppInfoFiller (At x) o = o {availableTransmitters = x}
suppInfoFiller (Se x) o = o {survivalEquipments = x}
suppInfoFiller (Lj x) o = o {lifeJackets = x}
suppInfoFiller (Di x) o = o {dinghies = x}
suppInfoFiller (Ad x) o = o {aircraftDescription = Just x}
suppInfoFiller (Rmk x) o = o {otherRemarks = Just x}
suppInfoFiller (Pn x) o = o {pilotInCommand = Just x}
mkSuppInformation :: [Data] -> SupplementaryInformation
mkSuppInformation = foldl (flip suppInfoFiller) emptySupplementaryInformation
pobParser :: Parser PersonsOnBoard
pobParser = do
n <- natural 3 <|> natural 2 <|> natural 1
mkPersonsOnBoard n
transmitterParser :: Parser Transmitter
transmitterParser = do
c <- oneOf "UVE"
return $
case c of
'U' -> UHF
'V' -> VHF
'E' -> ELT
_ -> error "?"
atParser :: Parser [Transmitter]
atParser = some transmitterParser
survEquipParser :: Parser SurvivalEquipment
survEquipParser = do
c <- oneOf "PDMJ"
return $
case c of
'P' -> Polar
'D' -> Desert
'M' -> Maritime
'J' -> Jungle
_ -> error "?"
seParser :: Parser [SurvivalEquipment]
seParser = some survEquipParser
lfParser :: Parser LifeJacket
lfParser = do
c <- oneOf "LF"
return $
case c of
'L' -> WithLight
'F' -> WithFluorescein
_ -> error "?"
uvParser :: Parser LifeJacket
uvParser = do
c <- oneOf "UV"
return $
case c of
'U' -> WithRadioUHF
'V' -> WithRadioVHF
_ -> error "?"
ljParser :: Parser [LifeJacket]
ljParser = do
uv <- many lfParser
_ <- try space
lf <- many uvParser
return (uv ++ lf)
2 NUMERICS giving the number of dinghies carried ,
3 NUMERICS giving the total capacity , in persons carried , of all dinghies .
deParser :: Parser Dinghies
deParser = do
nb <- optional (natural 2 <* space)
capa <- optional (natural 3 <* space)
cov <- optional (char 'C' <* space)
col <- optional word
mkDinghies nb capa (isJust cov) col
switchParser :: Parser (Maybe Data)
switchParser =
S.parser E hhmmParser Fe <|> S.parser P pobParser Pob <|> S.parser R atParser At <|>
S.parser S seParser Se <|>
S.parser J ljParser Lj <|>
S.parser D deParser Di <|>
S.parser A freeTextParser Ad <|>
S.parser N freeTextParser Rmk <|>
S.parser C freeTextParser Pn
parser :: Parser SupplementaryInformation
parser = do
s <- some switchParser
_ <- endOfFieldParser
return (mkSuppInformation (catMaybes s))
|
a0a3b474d16d50c08f152cc561bf3dd7242a46a95d96e5843ceffd11f2e81125 | sbcl/sbcl | defbangstruct.lisp | DEF!STRUCT = bootstrap DEFSTRUCT , a wrapper around DEFSTRUCT which
;;;; provides special features to help at bootstrap time:
1 . Layout information , inheritance information , and so forth is
;;;; retained in such a way that we can get to it even on vanilla
;;;; ANSI Common Lisp at cross-compiler build time.
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB-KERNEL")
machinery used in the implementation of SB - XC : DEFSTRUCT delaying
a description of a SB - XC : DEFSTRUCT call to be stored until we get
;; enough of the system running to finish processing it
(defstruct (delayed-defstruct (:constructor make-delayed-defstruct (args)))
(args nil :type cons)
;; because the expansion autogenerates slot names based on current package
(package (cl:package-name *package*) :type string))
a list of DELAYED - DEFSTRUCTs stored until we get SB - XC : DEFSTRUCT
;; working fully so that we can apply it to them then. After
SB - XC : DEFSTRUCT is made to work fully , this list is processed , then
;; made unbound, and should no longer be used.
(defvar *delayed-defstructs* nil)
;;; DEF!STRUCT defines a structure for both the host and target.
(defmacro def!struct (&rest args)
(multiple-value-bind (name options slots)
(destructuring-bind (nameoid &rest slots) args
(multiple-value-bind (name options)
(if (consp nameoid)
(values (first nameoid) (rest nameoid))
(values nameoid nil))
(declare (type list options))
(when (find :type options :key #'first)
(error "can't use :TYPE option in DEF!STRUCT"))
(values name options slots)))
Attempting to define a type named by a CL symbol is an error .
(assert (not (eq (sb-xc:symbol-package name) *cl-package*)))
(assert (equal (uncross options) options))
`(progn
(sb-xc:defstruct ,@args)
(defstruct (,name
,@(remove :pure options :key #'car))
,@slots))))
Workaround for questionable behavior of CCL - it issues a warning about
;;; a duplicate definition in src/code/defstruct if we use DEFMACRO here,
despite the second occurrence being preceded by FMAKUNBOUND .
;;; The warning can not be remedied by putting this in its own compilation unit,
;;; which I can't even explain. I would have expected at worst a "redefinition"
;;; warning, not a "duplicate" in that case.
#+nil ; It would be this
(defmacro sb-xc:defstruct (&rest args)
`(push (make-delayed-defstruct ',args) *delayed-defstructs*))
;;; But instead it's this. No eval-when needed, since we LOAD this file.
(setf (cl:macro-function 'sb-xc:defstruct)
(lambda (form environment)
(declare (ignore environment))
`(push (make-delayed-defstruct ',(cdr form)) *delayed-defstructs*)))
| null | https://raw.githubusercontent.com/sbcl/sbcl/0e824004154286dc3c7805969f177afae69d2286/src/code/defbangstruct.lisp | lisp | provides special features to help at bootstrap time:
retained in such a way that we can get to it even on vanilla
ANSI Common Lisp at cross-compiler build time.
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
enough of the system running to finish processing it
because the expansion autogenerates slot names based on current package
working fully so that we can apply it to them then. After
made unbound, and should no longer be used.
DEF!STRUCT defines a structure for both the host and target.
a duplicate definition in src/code/defstruct if we use DEFMACRO here,
The warning can not be remedied by putting this in its own compilation unit,
which I can't even explain. I would have expected at worst a "redefinition"
warning, not a "duplicate" in that case.
It would be this
But instead it's this. No eval-when needed, since we LOAD this file. | DEF!STRUCT = bootstrap DEFSTRUCT , a wrapper around DEFSTRUCT which
1 . Layout information , inheritance information , and so forth is
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB-KERNEL")
machinery used in the implementation of SB - XC : DEFSTRUCT delaying
a description of a SB - XC : DEFSTRUCT call to be stored until we get
(defstruct (delayed-defstruct (:constructor make-delayed-defstruct (args)))
(args nil :type cons)
(package (cl:package-name *package*) :type string))
a list of DELAYED - DEFSTRUCTs stored until we get SB - XC : DEFSTRUCT
SB - XC : DEFSTRUCT is made to work fully , this list is processed , then
(defvar *delayed-defstructs* nil)
(defmacro def!struct (&rest args)
(multiple-value-bind (name options slots)
(destructuring-bind (nameoid &rest slots) args
(multiple-value-bind (name options)
(if (consp nameoid)
(values (first nameoid) (rest nameoid))
(values nameoid nil))
(declare (type list options))
(when (find :type options :key #'first)
(error "can't use :TYPE option in DEF!STRUCT"))
(values name options slots)))
Attempting to define a type named by a CL symbol is an error .
(assert (not (eq (sb-xc:symbol-package name) *cl-package*)))
(assert (equal (uncross options) options))
`(progn
(sb-xc:defstruct ,@args)
(defstruct (,name
,@(remove :pure options :key #'car))
,@slots))))
Workaround for questionable behavior of CCL - it issues a warning about
despite the second occurrence being preceded by FMAKUNBOUND .
(defmacro sb-xc:defstruct (&rest args)
`(push (make-delayed-defstruct ',args) *delayed-defstructs*))
(setf (cl:macro-function 'sb-xc:defstruct)
(lambda (form environment)
(declare (ignore environment))
`(push (make-delayed-defstruct ',(cdr form)) *delayed-defstructs*)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.