_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 |
|---|---|---|---|---|---|---|---|---|
4eeeb3b29678d87ea0b9205e09caf51c5b26fb9f1610b5498e40449f26e55c12 | tdammers/ginger | PropertyTests.hs | {-#LANGUAGE OverloadedStrings #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
module Text.Ginger.PropertyTests
where
import Test.Tasty
import Test.Tasty.QuickCheck
import Data.Text (Text)
import qualified Data.Text as Text
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Default (def)
import qualified Data.HashMap.Strict as HashMap
import Control.Exception
import System.IO.Unsafe (unsafePerformIO)
import Control.Monad.Identity (Identity)
import Data.Time
import Text.Ginger
import Text.Ginger.Html
instance Arbitrary Text where
arbitrary = Text.pack <$> arbitrary
instance Arbitrary ByteString where
arbitrary = BS.pack <$> arbitrary
instance Arbitrary LBS.ByteString where
arbitrary = LBS.pack <$> arbitrary
instance Arbitrary Html where
arbitrary = oneof
[ html <$> arbitrary
, arbitraryTag
]
arbitraryTag = do
tagName <- arbitrary
inner <- arbitrary
return $ mconcat
[ unsafeRawHtml "<"
, tagName
, unsafeRawHtml ">"
, html inner
, unsafeRawHtml "</"
, tagName
, unsafeRawHtml ">"
]
instance Arbitrary Day where
arbitrary = ModifiedJulianDay <$> arbitrary
instance Arbitrary TimeOfDay where
arbitrary =
TimeOfDay
<$> resize 24 arbitrarySizedNatural
<*> resize 60 arbitrarySizedNatural
<*> (fromIntegral <$> resize 61 arbitrarySizedNatural)
instance Arbitrary LocalTime where
arbitrary =
LocalTime <$> arbitrary <*> arbitrary
instance Arbitrary TimeZone where
arbitrary =
TimeZone <$> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary ZonedTime where
arbitrary =
ZonedTime <$> arbitrary <*> arbitrary
instance Arbitrary (Statement ()) where
arbitrary = arbitraryStatement 2
arbitrarySimpleStatement = oneof
[ return (NullS ())
, ScopedS () <$> arbitrary
, LiteralS () <$> arbitrary
-- , InterpolationS <$> arbitrary
, IfS < $ > arbitrary < * > arbitrary < * > arbitrary
-- , ForS <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
-- , SetVarS <$> arbitrary <*> arbitrary
-- , DefMacroS <$> arbitrary <*> arbitrary
-- , BlockRefS <$> arbitrary
, < $ > arbitrary
]
arbitraryStatement :: Int -> Gen (Statement ())
arbitraryStatement 0 = arbitrarySimpleStatement
arbitraryStatement n = oneof
[ arbitrarySimpleStatement
, MultiS () <$> resize 5 (listOf $ arbitraryStatement (pred n))
]
instance Arbitrary (Template ()) where
arbitrary =
Template <$> arbitrary <*> return HashMap.empty <*> return Nothing
propertyTests :: TestTree
propertyTests = testGroup "Properties"
[ testGroup "Optimizer" $
[ testProperty "optimizer doesn't change behavior" $
\ast -> unsafePerformIO $ (==) <$> expand ast <*> expand (optimize ast)
]
, testGroup "ToGVal / FromGVal round tripping"
[ testProperty "Int" (roundTripGValP :: Int -> Bool)
, testProperty "Bool" (roundTripGValP :: Bool -> Bool)
, testProperty "[Text]" (roundTripGValP :: [Text] -> Bool)
, testProperty "Maybe Text" (roundTripGValP :: Maybe Text -> Bool)
, testProperty "ByteString" (roundTripGValP :: Maybe ByteString -> Bool)
, testProperty "Text" (roundTripGValP :: Text -> Bool)
, testProperty "LocalTime" (roundTripGValP :: LocalTime -> Bool)
, testProperty "TimeZone" (roundTripGValP :: TimeZone -> Bool)
For ZonedTime , we do n't have an Eq instance because it equality
-- of datetimes across time zones is unsolvable; we can, however, use
-- a "strict" equality test by simply rendering zoned times through
' show ' , i.e. , we consider two ZonedTime values equal iff they render
-- to the exact same string representations.
, testProperty "ZonedTime" (roundTripGValProjP show :: ZonedTime -> Bool)
]
]
roundTripGValExP :: (ToGVal Identity a, FromGVal Identity a)
=> (a -> a -> Bool)
-> a
-> Bool
roundTripGValExP cmp orig =
let g :: GVal Identity
g = toGVal orig
in case fromGVal g of
Nothing -> False
Just final -> cmp orig final
roundTripGValProjP :: (Eq b, ToGVal Identity a, FromGVal Identity a)
=> (a -> b)
-> a
-> Bool
roundTripGValProjP
proj = roundTripGValExP f
where
f x y = proj x == proj y
roundTripGValP :: (Eq a, ToGVal Identity a, FromGVal Identity a)
=> a -> Bool
roundTripGValP = roundTripGValExP (==)
expand :: Template () -> IO (Either String Text)
expand tpl =
mapLeft (const "ERROR" :: SomeException -> String) <$>
try (return $ runGinger (makeContextText (const def)) tpl)
mapLeft :: (a -> b) -> Either a c -> Either b c
mapLeft f (Left x) = Left (f x)
mapLeft f (Right x) = Right x
| null | https://raw.githubusercontent.com/tdammers/ginger/bd8cb39c1853d4fb4f663c4c201884575906acea/test/Text/Ginger/PropertyTests.hs | haskell | #LANGUAGE OverloadedStrings #
, InterpolationS <$> arbitrary
, ForS <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
, SetVarS <$> arbitrary <*> arbitrary
, DefMacroS <$> arbitrary <*> arbitrary
, BlockRefS <$> arbitrary
of datetimes across time zones is unsolvable; we can, however, use
a "strict" equality test by simply rendering zoned times through
to the exact same string representations. | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
module Text.Ginger.PropertyTests
where
import Test.Tasty
import Test.Tasty.QuickCheck
import Data.Text (Text)
import qualified Data.Text as Text
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Default (def)
import qualified Data.HashMap.Strict as HashMap
import Control.Exception
import System.IO.Unsafe (unsafePerformIO)
import Control.Monad.Identity (Identity)
import Data.Time
import Text.Ginger
import Text.Ginger.Html
instance Arbitrary Text where
arbitrary = Text.pack <$> arbitrary
instance Arbitrary ByteString where
arbitrary = BS.pack <$> arbitrary
instance Arbitrary LBS.ByteString where
arbitrary = LBS.pack <$> arbitrary
instance Arbitrary Html where
arbitrary = oneof
[ html <$> arbitrary
, arbitraryTag
]
arbitraryTag = do
tagName <- arbitrary
inner <- arbitrary
return $ mconcat
[ unsafeRawHtml "<"
, tagName
, unsafeRawHtml ">"
, html inner
, unsafeRawHtml "</"
, tagName
, unsafeRawHtml ">"
]
instance Arbitrary Day where
arbitrary = ModifiedJulianDay <$> arbitrary
instance Arbitrary TimeOfDay where
arbitrary =
TimeOfDay
<$> resize 24 arbitrarySizedNatural
<*> resize 60 arbitrarySizedNatural
<*> (fromIntegral <$> resize 61 arbitrarySizedNatural)
instance Arbitrary LocalTime where
arbitrary =
LocalTime <$> arbitrary <*> arbitrary
instance Arbitrary TimeZone where
arbitrary =
TimeZone <$> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary ZonedTime where
arbitrary =
ZonedTime <$> arbitrary <*> arbitrary
instance Arbitrary (Statement ()) where
arbitrary = arbitraryStatement 2
arbitrarySimpleStatement = oneof
[ return (NullS ())
, ScopedS () <$> arbitrary
, LiteralS () <$> arbitrary
, IfS < $ > arbitrary < * > arbitrary < * > arbitrary
, < $ > arbitrary
]
arbitraryStatement :: Int -> Gen (Statement ())
arbitraryStatement 0 = arbitrarySimpleStatement
arbitraryStatement n = oneof
[ arbitrarySimpleStatement
, MultiS () <$> resize 5 (listOf $ arbitraryStatement (pred n))
]
instance Arbitrary (Template ()) where
arbitrary =
Template <$> arbitrary <*> return HashMap.empty <*> return Nothing
propertyTests :: TestTree
propertyTests = testGroup "Properties"
[ testGroup "Optimizer" $
[ testProperty "optimizer doesn't change behavior" $
\ast -> unsafePerformIO $ (==) <$> expand ast <*> expand (optimize ast)
]
, testGroup "ToGVal / FromGVal round tripping"
[ testProperty "Int" (roundTripGValP :: Int -> Bool)
, testProperty "Bool" (roundTripGValP :: Bool -> Bool)
, testProperty "[Text]" (roundTripGValP :: [Text] -> Bool)
, testProperty "Maybe Text" (roundTripGValP :: Maybe Text -> Bool)
, testProperty "ByteString" (roundTripGValP :: Maybe ByteString -> Bool)
, testProperty "Text" (roundTripGValP :: Text -> Bool)
, testProperty "LocalTime" (roundTripGValP :: LocalTime -> Bool)
, testProperty "TimeZone" (roundTripGValP :: TimeZone -> Bool)
For ZonedTime , we do n't have an Eq instance because it equality
' show ' , i.e. , we consider two ZonedTime values equal iff they render
, testProperty "ZonedTime" (roundTripGValProjP show :: ZonedTime -> Bool)
]
]
roundTripGValExP :: (ToGVal Identity a, FromGVal Identity a)
=> (a -> a -> Bool)
-> a
-> Bool
roundTripGValExP cmp orig =
let g :: GVal Identity
g = toGVal orig
in case fromGVal g of
Nothing -> False
Just final -> cmp orig final
roundTripGValProjP :: (Eq b, ToGVal Identity a, FromGVal Identity a)
=> (a -> b)
-> a
-> Bool
roundTripGValProjP
proj = roundTripGValExP f
where
f x y = proj x == proj y
roundTripGValP :: (Eq a, ToGVal Identity a, FromGVal Identity a)
=> a -> Bool
roundTripGValP = roundTripGValExP (==)
expand :: Template () -> IO (Either String Text)
expand tpl =
mapLeft (const "ERROR" :: SomeException -> String) <$>
try (return $ runGinger (makeContextText (const def)) tpl)
mapLeft :: (a -> b) -> Either a c -> Either b c
mapLeft f (Left x) = Left (f x)
mapLeft f (Right x) = Right x
|
549af996f69b5a12e87aad07128dde30f06c730e25d5534f55b95eff43829d11 | practicalli/banking-on-clojure-webapp | request_handler.clj | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Request handlers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns practicalli.request-handler
(:require
Web Application
[ring.util.response :refer [response]]
[hiccup.core :refer [html]]
[hiccup.page :refer [html5 include-js include-css]]
[hiccup.element :refer [link-to]]
;; Data access
[practicalli.hanlder-helpers :as helper]))
;; Markup Generators
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn bank-account-media-object
[account-details]
[:article {:class "media"}
[:figure {:class "media-left"}
[:p {:class "image is-64x64"}
[:img {:src "-guides/master/clojure/clojure-bank-coin.png"}]]]
[:div {:class "media-content"}
[:div {:class "content"}
[:h3 {:class "subtitle"}
(str (:account-type account-details) " : λ" (:account-value account-details))]]
[:div {:class "field is-grouped"}
[:div {:class "control"}
[:div {:class "tags has-addons"}
[:span {:class "tag"} "Account number"]
[:span {:class "tag is-success is-light"} (:account-number account-details)]]]
[:div {:class "tags has-addons"}
[:span {:class "tag"} "Sort Code"]
[:span {:class "tag is-success is-light"} (:account-sort-code account-details)]]]]
[:div {:class "media-right"}
(link-to {:class "button is-primary"} "/transfer" "Transfer")
(link-to {:class "button is-info"} "/payment" "Payment")]])
;; HTML Pages
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn welcome-page
[request]
(response
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
[:div {:class "container"}
(link-to {:class "button is-primary"} "/accounts" "Login")
(link-to {:class "button is-danger"} "/register" "Register")
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]]]
])))
(defn register-customer
[request]
(response
(html
[:div
[:h1 "Banking on Clojure"]
[:p "New account holder" ]
(helper/new-customer
#:customer{:legal-name "Terry Able"
:email_address ""
:residential_address "1 Hard Code Drive, Altar IV"
:social_security_number "xx104312D"
:preferred_name "Terri"})
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]])))
(defn accounts-overview-page
"Overview of each bank account owned by the current customer.
Using Bulma media object style
-object/
Request hash-map is not currently used"
[request]
(response
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
(bank-account-media-object {:account-type "Current Account" :account-number "123456789"
:account-value "1,234" :account-sort-code "01-02-01"})
(bank-account-media-object {:account-type "Savings Account" :account-number "123454321"
:account-value "2,000" :account-sort-code "01-02-01"})
(bank-account-media-object {:account-type "Tax Free Savings Account" :account-number "123454321"
:account-value "20,000" :account-sort-code "01-02-01"})
(bank-account-media-object {:account-type "Mortgage Account" :account-number "98r9e8r79wr87e9232"
:account-value "354,000" :account-sort-code "01-02-01"})
]])))
(defn account-history
[request]
(response
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
[:div {:class "container"}
[:h1 {:class "title"}
"Account History"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]]]
])))
TODO : Add form to transfer money from one account to another
(defn money-transfer
[request]
(response
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
[:div {:class "container"}
[:h1 {:class "title"}
"Transfer Dashboard"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]]]
])))
TODO : Add form to transfer money from one account to another
(defn money-payment
[request]
(response
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
[:div {:class "container"}
[:h1 {:class "title"}
"Payment Dashboard"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]]]
])))
(comment
;; Test handler function with empty request
(welcome-page {})
(html5 {})
= > " < ! DOCTYPE html>\n < html></html > "
(html5
{:lang "en"}
[:head
(include-js "myscript.js")
(include-css "mystyle.css")]
[:body
[:div
[:h1 {:class "info"} "Hiccup"]]])
;; => "<!DOCTYPE html>\n<html lang=\"en\"><head><script src=\"myscript.js\" type=\"text/javascript\"></script><link href=\"mystyle.css\" rel=\"stylesheet\" type=\"text/css\"></head><body><div><h1 class=\"info\">Hiccup</h1></div></body></html>"
)
RDD
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(comment
;; Simple handler
(defn welcome-page
[request]
(response (html [:div
[:h1 "Banking on Clojure"]
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]])))
;; Initial design of accounts page
(defn account-dashboard
[request]
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
[:div {:class "container"}
[:h1 {:class "title"}
"Account Dashboard"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]
[:div {:class "box"}
[:h1 {:class "title"}
"Current Account"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]]
[:div {:class "box"}
[:h1 {:class "title"}
"Savings Account"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]]
[:div {:class "box"}
[:h1 {:class "title"}
"Tax Free Savings Account"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]]
[:div {:class "box"}
[:h1 {:class "title"}
"Credit Card Account"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]]
[:div {:class "box"}
[:h1 {:class "title"}
"Mortgage"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]]]
]]))
;; Abstracting hiccup with functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn unordered-list [items]
[:ul
(for [i items]
[:li i])])
;; Many lines of code can now be reduced to a single line
;; [:div
;; (unordered-list ["collection" "of" "list" "items"])]
(defn bank-account-media-object
[account-details]
[:article {:class "media"}
[:figure {:class "media-left"}
[:p {:class "image is-64x64"}
[:img {:src "-guides/master/clojure/clojure-bank-coin.png"}]]]
[:div {:class "media-content"}
[:div {:class "content"}
[:h3 {:class "subtitle"}
"Current Account : λ" (:account-value account-details)]
[:p "Account number: " {:account-number account-details} " Sort code: " {:account-sort-code account-details}]]]
[:div {:class "media-right"}
(link-to {:class "button is-primary"} "/transfer" "Transfer")
(link-to {:class "button is-info"} "/payment" "Payment")]])
#_(bank-account-media-object
{:account-type "Current Account"
:account-number "123456789"
:account-value "i1,000,000"
:account-sort-code "01-02-01"})
= > [: article { : class " media " } [: figure { : class " media - left " } [ :p { : class " image is-64x64 " } [: img { : src " -guides/master/clojure/clojure-bank-coin.png " } ] ] ] [: div { : class " media - content " } [: div { : class " content " } [: h3 { : class " subtitle " } " Current Account : & lambda ; " " i1,000,000 " ] [ :p " Account number : " { : account - number { : account - type " Current Account " , : account - number " 123456789 " , : account - value " i1,000,000 " , : account - sort - code " 01 - 02 - 01 " } } " Sort code : " { : account - sort - code { : account - type " Current Account " , : account - number " 123456789 " , : account - value " i1,000,000 " , : account - sort - code " 01 - 02 - 01 " } } ] ] ] [: div { : class " media - right " } [: a { : href # object[java.net . URI 0x3516357f " /transfer " ] , : class " button is - primary " } ( " Transfer " ) ] [: a { : href # object[java.net . URI 0x4cf62d27 " /payment " ] , : class " button is - info " } ( " Payment " ) ] ] ]
) ;; End of Rich Comment Block
| null | https://raw.githubusercontent.com/practicalli/banking-on-clojure-webapp/e903e0a72f664ae8959dc5dc05fc5149cd18f422/src/practicalli/request_handler.clj | clojure |
Request handlers
Data access
Markup Generators
HTML Pages
Test handler function with empty request
=> "<!DOCTYPE html>\n<html lang=\"en\"><head><script src=\"myscript.js\" type=\"text/javascript\"></script><link href=\"mystyle.css\" rel=\"stylesheet\" type=\"text/css\"></head><body><div><h1 class=\"info\">Hiccup</h1></div></body></html>"
Simple handler
Initial design of accounts page
Abstracting hiccup with functions
Many lines of code can now be reduced to a single line
[:div
(unordered-list ["collection" "of" "list" "items"])]
End of Rich Comment Block |
(ns practicalli.request-handler
(:require
Web Application
[ring.util.response :refer [response]]
[hiccup.core :refer [html]]
[hiccup.page :refer [html5 include-js include-css]]
[hiccup.element :refer [link-to]]
[practicalli.hanlder-helpers :as helper]))
(defn bank-account-media-object
[account-details]
[:article {:class "media"}
[:figure {:class "media-left"}
[:p {:class "image is-64x64"}
[:img {:src "-guides/master/clojure/clojure-bank-coin.png"}]]]
[:div {:class "media-content"}
[:div {:class "content"}
[:h3 {:class "subtitle"}
(str (:account-type account-details) " : λ" (:account-value account-details))]]
[:div {:class "field is-grouped"}
[:div {:class "control"}
[:div {:class "tags has-addons"}
[:span {:class "tag"} "Account number"]
[:span {:class "tag is-success is-light"} (:account-number account-details)]]]
[:div {:class "tags has-addons"}
[:span {:class "tag"} "Sort Code"]
[:span {:class "tag is-success is-light"} (:account-sort-code account-details)]]]]
[:div {:class "media-right"}
(link-to {:class "button is-primary"} "/transfer" "Transfer")
(link-to {:class "button is-info"} "/payment" "Payment")]])
(defn welcome-page
[request]
(response
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
[:div {:class "container"}
(link-to {:class "button is-primary"} "/accounts" "Login")
(link-to {:class "button is-danger"} "/register" "Register")
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]]]
])))
(defn register-customer
[request]
(response
(html
[:div
[:h1 "Banking on Clojure"]
[:p "New account holder" ]
(helper/new-customer
#:customer{:legal-name "Terry Able"
:email_address ""
:residential_address "1 Hard Code Drive, Altar IV"
:social_security_number "xx104312D"
:preferred_name "Terri"})
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]])))
(defn accounts-overview-page
"Overview of each bank account owned by the current customer.
Using Bulma media object style
-object/
Request hash-map is not currently used"
[request]
(response
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
(bank-account-media-object {:account-type "Current Account" :account-number "123456789"
:account-value "1,234" :account-sort-code "01-02-01"})
(bank-account-media-object {:account-type "Savings Account" :account-number "123454321"
:account-value "2,000" :account-sort-code "01-02-01"})
(bank-account-media-object {:account-type "Tax Free Savings Account" :account-number "123454321"
:account-value "20,000" :account-sort-code "01-02-01"})
(bank-account-media-object {:account-type "Mortgage Account" :account-number "98r9e8r79wr87e9232"
:account-value "354,000" :account-sort-code "01-02-01"})
]])))
(defn account-history
[request]
(response
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
[:div {:class "container"}
[:h1 {:class "title"}
"Account History"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]]]
])))
TODO : Add form to transfer money from one account to another
(defn money-transfer
[request]
(response
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
[:div {:class "container"}
[:h1 {:class "title"}
"Transfer Dashboard"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]]]
])))
TODO : Add form to transfer money from one account to another
(defn money-payment
[request]
(response
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
[:div {:class "container"}
[:h1 {:class "title"}
"Payment Dashboard"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]]]
])))
(comment
(welcome-page {})
(html5 {})
= > " < ! DOCTYPE html>\n < html></html > "
(html5
{:lang "en"}
[:head
(include-js "myscript.js")
(include-css "mystyle.css")]
[:body
[:div
[:h1 {:class "info"} "Hiccup"]]])
)
RDD
(comment
(defn welcome-page
[request]
(response (html [:div
[:h1 "Banking on Clojure"]
[:img {:src "-guides/master/clojure/clojure-piggy-bank.png"}]])))
(defn account-dashboard
[request]
(html5
{:lang "en"}
[:head
(include-css "@0.9.0/css/bulma.min.css")]
[:body
[:section {:class "hero is-info"}
[:div {:class "hero-body"}
[:div {:class "container"}
[:h1 {:class "title"} "Banking on Clojure"]
[:p {:class "subtitle"}
"Making your money immutable"]]]]
[:section {:class "section"}
[:div {:class "container"}
[:h1 {:class "title"}
"Account Dashboard"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]
[:div {:class "box"}
[:h1 {:class "title"}
"Current Account"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]]
[:div {:class "box"}
[:h1 {:class "title"}
"Savings Account"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]]
[:div {:class "box"}
[:h1 {:class "title"}
"Tax Free Savings Account"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]]
[:div {:class "box"}
[:h1 {:class "title"}
"Credit Card Account"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]]
[:div {:class "box"}
[:h1 {:class "title"}
"Mortgage"]
[:p {:class "content"}
"Manage your money without unexpected side-effects using a simple made easy banking service"]]]
]]))
(defn unordered-list [items]
[:ul
(for [i items]
[:li i])])
(defn bank-account-media-object
[account-details]
[:article {:class "media"}
[:figure {:class "media-left"}
[:p {:class "image is-64x64"}
[:img {:src "-guides/master/clojure/clojure-bank-coin.png"}]]]
[:div {:class "media-content"}
[:div {:class "content"}
[:h3 {:class "subtitle"}
"Current Account : λ" (:account-value account-details)]
[:p "Account number: " {:account-number account-details} " Sort code: " {:account-sort-code account-details}]]]
[:div {:class "media-right"}
(link-to {:class "button is-primary"} "/transfer" "Transfer")
(link-to {:class "button is-info"} "/payment" "Payment")]])
#_(bank-account-media-object
{:account-type "Current Account"
:account-number "123456789"
:account-value "i1,000,000"
:account-sort-code "01-02-01"})
= > [: article { : class " media " } [: figure { : class " media - left " } [ :p { : class " image is-64x64 " } [: img { : src " -guides/master/clojure/clojure-bank-coin.png " } ] ] ] [: div { : class " media - content " } [: div { : class " content " } [: h3 { : class " subtitle " } " Current Account : & lambda ; " " i1,000,000 " ] [ :p " Account number : " { : account - number { : account - type " Current Account " , : account - number " 123456789 " , : account - value " i1,000,000 " , : account - sort - code " 01 - 02 - 01 " } } " Sort code : " { : account - sort - code { : account - type " Current Account " , : account - number " 123456789 " , : account - value " i1,000,000 " , : account - sort - code " 01 - 02 - 01 " } } ] ] ] [: div { : class " media - right " } [: a { : href # object[java.net . URI 0x3516357f " /transfer " ] , : class " button is - primary " } ( " Transfer " ) ] [: a { : href # object[java.net . URI 0x4cf62d27 " /payment " ] , : class " button is - info " } ( " Payment " ) ] ] ]
|
ff24011bc914c253fbefe542ccbe40dc69a9131fcbd100abc916854709ac65ba | clojure-interop/aws-api | project.clj | (defproject clojure-interop/com.amazonaws.services.cloudsearchv2 "1.0.0"
:description "Clojure to Java Interop Bindings for com.amazonaws.services.cloudsearchv2"
:url "-interop/aws-api"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]]
:source-paths ["src"])
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.cloudsearchv2/project.clj | clojure | (defproject clojure-interop/com.amazonaws.services.cloudsearchv2 "1.0.0"
:description "Clojure to Java Interop Bindings for com.amazonaws.services.cloudsearchv2"
:url "-interop/aws-api"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]]
:source-paths ["src"])
| |
49dc98cbe923ce13b0d32181bd73cb8b2c47294a5abc229834c7c8b74aa582fd | msakai/data-interval | IntervalRelation.hs | # OPTIONS_GHC -Wall #
# LANGUAGE CPP , DeriveDataTypeable , DeriveGeneric #
{-# LANGUAGE Safe #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.IntervalRelation
Copyright : ( c ) 2016
-- License : BSD-style
--
-- Maintainer :
-- Stability : provisional
Portability : non - portable ( CPP , DeriveDataTypeable , DeriveGeneric )
--
-- Interval relations and their algebra.
--
-----------------------------------------------------------------------------
module Data.IntervalRelation
( Relation(..)
, invert
)
where
import Data.Data
import GHC.Generics (Generic)
| Describes how two intervals @x@ and @y@ can be related .
See [ 's interval algebra]( / wiki / Allen%27s_interval_algebra )
and [ Intervals and their relations]( / / intervals - and - their - relations.html ) .
data Relation
= Before
-- ^ Any element of @x@ is smaller than any element of @y@,
-- and intervals are not connected. In other words, there exists an element
that is bigger than any element of @x@ and smaller than any element of @y@.
| JustBefore
-- ^ Any element of @x@ is smaller than any element of @y@,
-- but intervals are connected and non-empty. This implies that intersection
-- of intervals is empty, and union is a single interval.
| Overlaps
-- ^ Intersection of @x@ and @y@ is non-empty,
@x@ start and finishes earlier than @y@. This implies that union
-- is a single interval, and @x@ finishes no earlier than @y@ starts.
| Starts
-- ^ @x@ is a proper subset of @y@,
-- and they share lower bounds.
| During
-- ^ @x@ is a proper subset of @y@,
-- but they share neither lower nor upper bounds.
| Finishes
-- ^ @x@ is a proper subset of @y@,
-- and they share upper bounds.
| Equal
-- ^ Intervals are equal.
| FinishedBy
-- ^ Inverse of 'Finishes'.
| Contains
-- ^ Inverse of 'During'.
| StartedBy
-- ^ Inverse of 'Starts'.
| OverlappedBy
-- ^ Inverse of 'Overlaps'.
| JustAfter
-- ^ Inverse of 'JustBefore'.
| After
-- ^ Inverse of 'Before'.
deriving (Eq, Ord, Enum, Bounded, Show, Read, Generic, Data, Typeable)
| Inverts a relation , such that @'invert ' ( ' Data.Interval.relate ' x y ) = ' Data.Interval.relate ' y
invert :: Relation -> Relation
invert relation = case relation of
Before -> After
JustBefore -> JustAfter
Overlaps -> OverlappedBy
Starts -> StartedBy
During -> Contains
Finishes -> FinishedBy
Equal -> Equal
FinishedBy -> Finishes
Contains -> During
StartedBy -> Starts
OverlappedBy -> Overlaps
JustAfter -> JustBefore
After -> Before
| null | https://raw.githubusercontent.com/msakai/data-interval/c37e7994be95623be5f05741f2a50e98fa0788e2/src/Data/IntervalRelation.hs | haskell | # LANGUAGE Safe #
---------------------------------------------------------------------------
|
Module : Data.IntervalRelation
License : BSD-style
Maintainer :
Stability : provisional
Interval relations and their algebra.
---------------------------------------------------------------------------
^ Any element of @x@ is smaller than any element of @y@,
and intervals are not connected. In other words, there exists an element
^ Any element of @x@ is smaller than any element of @y@,
but intervals are connected and non-empty. This implies that intersection
of intervals is empty, and union is a single interval.
^ Intersection of @x@ and @y@ is non-empty,
is a single interval, and @x@ finishes no earlier than @y@ starts.
^ @x@ is a proper subset of @y@,
and they share lower bounds.
^ @x@ is a proper subset of @y@,
but they share neither lower nor upper bounds.
^ @x@ is a proper subset of @y@,
and they share upper bounds.
^ Intervals are equal.
^ Inverse of 'Finishes'.
^ Inverse of 'During'.
^ Inverse of 'Starts'.
^ Inverse of 'Overlaps'.
^ Inverse of 'JustBefore'.
^ Inverse of 'Before'. | # OPTIONS_GHC -Wall #
# LANGUAGE CPP , DeriveDataTypeable , DeriveGeneric #
Copyright : ( c ) 2016
Portability : non - portable ( CPP , DeriveDataTypeable , DeriveGeneric )
module Data.IntervalRelation
( Relation(..)
, invert
)
where
import Data.Data
import GHC.Generics (Generic)
| Describes how two intervals @x@ and @y@ can be related .
See [ 's interval algebra]( / wiki / Allen%27s_interval_algebra )
and [ Intervals and their relations]( / / intervals - and - their - relations.html ) .
data Relation
= Before
that is bigger than any element of @x@ and smaller than any element of @y@.
| JustBefore
| Overlaps
@x@ start and finishes earlier than @y@. This implies that union
| Starts
| During
| Finishes
| Equal
| FinishedBy
| Contains
| StartedBy
| OverlappedBy
| JustAfter
| After
deriving (Eq, Ord, Enum, Bounded, Show, Read, Generic, Data, Typeable)
| Inverts a relation , such that @'invert ' ( ' Data.Interval.relate ' x y ) = ' Data.Interval.relate ' y
invert :: Relation -> Relation
invert relation = case relation of
Before -> After
JustBefore -> JustAfter
Overlaps -> OverlappedBy
Starts -> StartedBy
During -> Contains
Finishes -> FinishedBy
Equal -> Equal
FinishedBy -> Finishes
Contains -> During
StartedBy -> Starts
OverlappedBy -> Overlaps
JustAfter -> JustBefore
After -> Before
|
1bc249b1a653aec128fdf30ed88d0fb942f6f698bbc05d18abe41eb0b4f5c27c | racket/frtime | lang-ext.rkt | #lang racket/base
(provide raise-exceptions
deep-value-now
nothing
nothing?
;general-event-processor
;general-event-processor2
emit
select
switch
merge-e
once-e
changes
never-e
when-e
while-e
==>
-=>
=#>
=#=>
map-e
filter-e
filter-map-e
collect-e
accum-e
collect-b
accum-b
hold
for-each-e!
snapshot/sync
synchronize
snapshot
snapshot-e
snapshot/apply
milliseconds
fine-timer-granularity
seconds
delay-by
inf-delay
integral
derivative
new-cell
lift
lift-strict
event?
command-lambda
mk-command-lambda
until
event-loop
split
define-reactive
;; from core/frp
event-receiver
send-event
send-synchronous-event
send-synchronous-events
set-cell!
undefined
(rename-out [undefined?/lifted undefined?])
(rename-out [undefined? frp:undefined?])
behavior?
value-now
value-now/no-copy
value-now/sync
signal-count
signal?)
(require (for-syntax racket/base
(only-in racket/list first second last-pair empty empty?))
(only-in racket/list first second cons? empty empty? rest last-pair)
(only-in racket/function identity)
data/queue
(only-in frtime/core/frp super-lift undefined undefined? behavior? do-in-manager-after do-in-manager proc->signal set-signal-thunk! register unregister
signal? signal-depth signal:switching? signal-value value-now signal:compound? signal:compound-content signal:switching-current signal:switching-trigger
set-cell! snap? iq-enqueue value-now/no-copy event-receiver event-set? proc->signal:switching set-signal-producers! set-signal-depth! safe-signal-depth
make-events-now iq-resort event-set-events current-logical-time event-set-time event-producer2 schedule-alarm value-now/sync set-signal-value! signal-thunk
send-event exceptions send-synchronous-event send-synchronous-events signal-count))
(define nothing (void));(string->uninterned-symbol "nothing"))
(define (nothing? v) (eq? v nothing))
(define-syntax define-reactive
(syntax-rules ()
[(_ name expr)
(define name
(let ([val (parameterize ([snap? #f])
expr)])
(lambda () (deep-value-now val empty))))]))
(define (deep-value-now obj table)
(cond
[(assq obj table) => second]
[(behavior? obj)
(deep-value-now (signal-value obj) (cons (list obj (signal-value obj)) table))]
[(cons? obj)
(let* ([result (cons #f #f)]
[new-table (cons (list obj result) table)]
[car-val (deep-value-now (car obj) new-table)]
[cdr-val (deep-value-now (cdr obj) new-table)])
(if (and (eq? car-val (car obj))
(eq? cdr-val (cdr obj)))
obj
(cons car-val cdr-val)))]
; won't work in the presence of super structs or immutable fields
[(struct? obj)
(let*-values ([(info skipped) (struct-info obj)]
[(name init-k auto-k acc mut! immut sup skipped?) (struct-type-info info)]
[(ctor) (struct-type-make-constructor info)]
[(indices) (build-list init-k identity)]
[(result) (apply ctor (build-list init-k (lambda (i) #f)))]
[(new-table) (cons (list obj result) table)]
[(elts) (build-list init-k (lambda (i)
(deep-value-now (acc obj i) new-table)))])
(if (andmap (lambda (i e) (eq? (acc obj i) e)) indices elts)
obj
(begin
(for-each (lambda (i e) (mut! result i e)) indices elts)
result)))]
[(vector? obj)
(let* ([len (vector-length obj)]
[indices (build-list len identity)]
[result (build-vector len (lambda (_) #f))]
[new-table (cons (list obj result) table)]
[elts (build-list len (lambda (i)
(deep-value-now (vector-ref obj i) new-table)))])
(if (andmap (lambda (i e) (eq? (vector-ref obj i) e)) indices elts)
obj
(begin
(for-each (lambda (i e) (vector-set! result i e)) indices elts)
result)))]
[else obj]))
#;(define deep-value-now
(case-lambda
[(obj) (deep-value-now obj empty)]
[(obj table)
(cond
[(assq obj table) => second]
[(behavior? obj)
(deep-value-now (signal-value obj) (cons (list obj (signal-value obj)) table))]
[(event? obj)
(signal-value obj)]
[(cons? obj)
(let* ([result (cons #f #f)]
[new-table (cons (list obj result) table)]
[car-val (deep-value-now (car obj) new-table)]
[cdr-val (deep-value-now (cdr obj) new-table)])
(cons car-val cdr-val))]
[(struct? obj)
(let*-values ([(info skipped) (struct-info obj)]
[(name init-k auto-k acc mut immut sup skipped?) (struct-type-info info)]
[(ctor) (struct-type-make-constructor info)])
(apply ctor (build-list (+ auto-k init-k)
(lambda (i) (deep-value-now (acc obj i) table)))))]
[(vector? obj)
(build-vector
(vector-length obj)
(lambda (i)
(deep-value-now (vector-ref obj i) table)))]
[else obj])]))
(define (lift strict? fn . args)
(if (snap?) ;; maybe fix later to handle undefined-strictness
(apply fn (map value-now args))
(with-continuation-mark
'frtime 'lift-active
(cond
[(ormap signal? args)
(apply
proc->signal
(apply (if strict? create-strict-thunk create-thunk) fn args)
args)]
[(and strict? (ormap undefined? args)) undefined]
[else (apply fn args)]))))
(define (lift-strict . args)
(apply lift #t args))
new - cell : ] - > behavior[a ] ( cell )
(define new-cell
(lambda ([init undefined])
(switch (event-receiver) init)))
(define (b1 . until . b2)
(proc->signal
(lambda () (if (undefined? (value-now b2))
(value-now b1)
(value-now b2)))
b1 b2))
(define-syntax (event-loop-help stx)
(syntax-case stx ()
[(_ ([name expr] ...)
[e => body] ...)
(with-syntax ([args #'(name ...)])
#'(accum-e
(merge-e
(e . ==> . (lambda (v)
(lambda (state)
(apply
(lambda args (body v))
state)))) ...)
(list expr ...)))]))
(define-syntax (event-loop stx)
(define (add-arrow clause)
(syntax-case clause (=>)
[(e => body) #'(e => body)]
[(e body) #'(e => (lambda (_) body))]))
(syntax-case stx ()
[(_ ([name expr] ...)
clause ...)
(with-syntax ([(new-clause ...)
(map add-arrow (syntax->list #'(clause ...)))])
#'(event-loop-help
([name expr] ...)
new-clause ...)
)]))
(define undefined?/lifted (lambda (arg) (lift #f undefined? arg)))
(define (event? v)
(and (signal? v)
(if (undefined? (signal-value v))
undefined
(event-set? (signal-value v)))))
; switch : event[behavior] behavior -> behavior
(define switch
(lambda (e [init undefined])
(let* ([init (box init)]
[e-b (hold e (unbox init) #t)]
[ret (proc->signal:switching
(case-lambda [() (value-now (unbox init))]
[(msg) e])
init e-b e-b (unbox init))])
(set-signal-thunk!
ret
(case-lambda
[()
(when (not (eq? (unbox init) (signal-value e-b)))
(unregister ret (unbox init))
(set-box! init (value-now e-b))
(register ret (unbox init))
(set-signal-producers! ret (list e-b (unbox init)))
(set-signal-depth! ret (max (signal-depth ret)
(add1 (safe-signal-depth (unbox init)))))
(iq-resort))
(value-now/no-copy (unbox init))]
[(msg) e]))
ret)))
; event ... -> event
(define (merge-e . args)
(apply lift #t (lambda args
(make-events-now
(apply append
(map event-set-events
(filter (lambda (es) (= (current-logical-time) (event-set-time es)))
args)))))
args))
(define (once-e e)
(map-e second (filter-e (lambda (p) (= 1 (first p)))
(collect-e e (list 0) (lambda (e p) (list (add1 (first p)) e))))))
; behavior[a] -> event[a]
(define (changes b)
(lift #f (let ([first-time #t])
(lambda (bh)
(begin0
(make-events-now
(if first-time
empty
(list (deep-value-now bh empty))))
(set! first-time #f))))
b))
(define never-e
(changes #f))
; when-e : behavior[bool] -> event
(define (when-e b)
(let* ([last (value-now b)])
(lift #t (lambda (bh)
(make-events-now
(let ([current bh])
(begin0
(if (and (not last) current)
(list current)
empty)
(set! last current)))))
b)))
; while-e : behavior[bool] behavior[number] -> event
(define (while-e b interval)
(letrec ([ret (event-producer2
(lambda (emit)
(lambda the-args
(cond
[(value-now b) =>
(lambda (v)
(emit v)
(schedule-alarm (+ (value-now interval) (current-inexact-milliseconds)) ret))])))
b)])
ret))
; ==> : event[a] (a -> b) -> event[b]
(define (e . ==> . f)
(lift #t (lambda (es)
(make-events-now
(if (= (current-logical-time) (event-set-time es))
(map f (event-set-events es))
empty)))
e))
; -=> : event[a] b -> event[b]
(define-syntax -=>
(syntax-rules ()
[(_ e k-e) (==> e (lambda (_) k-e))]))
; =#> : event[a] (a -> bool) -> event[a]
(define (e . =#> . p)
(lift #t (lambda (es)
(make-events-now
(if (= (current-logical-time) (event-set-time es))
(filter (value-now p) (map value-now (event-set-events es)))
empty)))
e))
; =#=> : event[a] (a -> b U nothing) -> event[b]
(define (e . =#=> . f)
(lift #t (lambda (es)
(make-events-now
(if (= (current-logical-time) (event-set-time es))
(filter (compose not nothing?) (map f (event-set-events es)))
empty)))
e))
(define (map-e f e)
(==> e f))
(define (filter-e p e)
(=#> e p))
(define (filter-map-e f e)
(=#=> e f))
(define (scan trans acc lst)
(if (cons? lst)
(let ([new-acc (trans (first lst) acc)])
(cons new-acc (scan trans new-acc (rest lst))))
empty))
; event[a] b (a b -> b) -> event[b]
(define (collect-e e init trans)
(lift #t (lambda (es)
(make-events-now
(cond
[(= (current-logical-time) (event-set-time es))
(let ([all-events (scan trans init (event-set-events es))])
(when (cons? all-events)
(set! init (first (last-pair all-events))))
all-events)]
[else empty])))
e))
; event[(a -> a)] a -> event[a]
(define (accum-e e init)
(lift #t (lambda (es)
(make-events-now
(cond
[(= (current-logical-time) (event-set-time es))
(let ([all-events (scan (lambda (t a) (t a)) init (event-set-events es))])
(when (cons? all-events)
(set! init (first (last-pair all-events))))
all-events)]
[else empty])))
e))
; event[a] b (a b -> b) -> behavior[b]
(define (collect-b ev init trans)
(hold (collect-e ev init trans) init))
; event[(a -> a)] a -> behavior[a]
(define (accum-b ev init)
(hold (accum-e ev init) init))
; hold : a event[a] -> behavior[a]
(define hold
(lambda (e [init undefined] [allow-behaviors? #f])
(let ([val init]
[warn-about-behaviors? #t])
(lift #t (lambda (es) (let ([events (event-set-events es)])
(when (and (= (current-logical-time) (event-set-time es))
(cons? events))
(set! val (first (last-pair (event-set-events es)))))
(when (and (behavior? val) (not allow-behaviors?))
(set! val (value-now val))
(when warn-about-behaviors?
(thread
(lambda ()
(error "hold: input event had a behavior; snapshotting to prevent nested behavior")))
(set! warn-about-behaviors? #f)))
val))
e))))
(define-syntax snapshot/sync
(syntax-rules ()
[(_ (id ...) expr ...)
(let-values ([(id ...) (value-now/sync id ...)])
expr ...)]))
(define (synchronize)
(snapshot/sync () (void)))
(define-syntax snapshot
(syntax-rules ()
[(_ (id ...) expr ...)
(let ([id (value-now id)] ...)
expr ...)]))
(define-syntax snapshot-all
(syntax-rules ()
[(_ expr ...)
(parameterize ([snap? #t])
expr ...)]))
(define (snapshot-e e . bs)
(apply lift #t (lambda (es . bs)
(make-events-now
(cond
[(= (current-logical-time) (event-set-time es))
(map (lambda (the-event) (cons the-event (map value-now bs)))
(event-set-events es))]
[else empty])))
e bs))
(define (snapshot/apply fn . args)
(apply fn (map value-now args)))
;; Deprecated
(define-syntax frp:send
(syntax-rules ()
[(_ obj meth arg ...)
(if (snap?)
(send obj meth (value-now arg) ...)
(send obj meth arg ...))]))
(define (make-time-b ms)
(let ([ret (proc->signal void)])
(set-signal-thunk! ret
(lambda ()
(let ([t (current-inexact-milliseconds)])
(schedule-alarm (+ (value-now ms) t) ret)
t)))
(set-signal-value! ret ((signal-thunk ret)))
ret))
(define seconds
(let ([ret (proc->signal void)])
(set-signal-thunk! ret
(lambda ()
(let ([s (current-seconds)]
[t (current-inexact-milliseconds)])
(schedule-alarm (* 1000 (add1 (floor (/ t 1000)))) ret)
s)))
(set-signal-value! ret ((signal-thunk ret)))
ret))
;; signal[a] num -> signal[a]
;;
;; Returns a signal whose value at (approximately) time (+ t |delay-millis|) is a (deep) snapshot
of the value of |sig| at time t , for all times t from now on . For earlier times , the value of the
;; returned signal is undefined.
;;
;; Assumptions: (current-inexact-milliseconds) is monotonically non-decreasing; |delay-millis| is
;; positive and finite.
(define (delay-by sig delay-millis)
;; Implementation strategy:
;;
;; Maintain a queue of pairs (snapshot . timestamp) of the observed signal going back in
;; time for at least |delay-millis|. Start with (undefined . -inf.0) and (current-value . now), so
there should always be at least one item ( value . timestamp ) in the queue such that
;; (>= now (+ timestamp delay-millis)).
;;
;; |consumer| runs whenever |sig| changes and adds an item with the observed value and current
time to the queue ; schedules to run at |delay - millis| in the future , by which
;; time it should be ready to take on that observed value.
;;
;; |producer| has no dependencies recorded in the dataflow graph and only runs when scheduled
;; by the consumer. (This is what allows delay-by to break cycles.) It traverses the queue
;; looking for the latest observation (value . timestamp) such that
( > = now ( + timestamp delay - millis ) ) , and takes on the observed value . is the
;; value returned by this procedure, so it stays alive as long as anything cares about its
;; value.
(let* ([queue (make-queue)]
;; finish : (a . num) a -> a
Puts |queue - item| back on the front of the queue and returns |val| , updating the
occurrence timestamp if |val| represents an event set .
;; TODO(gcooper): We could avoid this if data/queue supported a "peek" operation.
[finish! (lambda (queue-item val)
(enqueue-front! queue queue-item)
(if (event-set? val)
(make-events-now (event-set-events val))
val))]
[now-millis (current-inexact-milliseconds)]
[_ (begin
;; Add initial observations to the queue.
(enqueue! queue (cons undefined -inf.0))
(enqueue! queue (cons (deep-value-now sig empty) now-millis)))]
's thunk needs to be in scope so it can schedule it , and
|producer| 's thunk needs to be in scope so it can keep it alive . To set up
this cycle , we first create with a dummy thunk ( void ) , then define
|producer| , and finally update 's thunk to what we want it to be .
[consumer (proc->signal void sig)]
[producer (proc->signal
(lambda ()
(let ([now-millis (current-inexact-milliseconds)])
;; There's no way to "peek" at the next item in the queue, so we have to
;; dequeue it, check whether we're ready for it, and if not, stick it back
;; on the front...
(let loop ([front (dequeue! queue)])
|val| is our current candidate value ; we 'll use it if there 's no later
;; observation that's at least |delay-millis| old.
(let* ([val (car front)])
(if (queue-empty? queue)
;; There are no later observations to consider, so use the current
;; one.
(finish! front val)
;; Look at the next item in the queue to see if we're ready for it.
;; If so, recur. Otherwise, put it back on the front of the queue
;; and use the previous value.
(let* ([next (dequeue! queue)]
[timestamp-millis (cdr next)])
: since there 's nothing that would otherwise keep
;; |consumer| alive, we retain a reference to it here, and we
;; trick the runtime into not optimizing it away by calling a
;; predicate and using the result in a conditional expression. If
;; the compiler ever gets smart enough to determine that the
;; outcome is provably always true, and therefore that it can
;; optimize away this code, we'll have to come up with a
;; different strategy (e.g., adding a special field to the signal
;; structure).
(if (and (signal? consumer)
(< now-millis (+ timestamp-millis delay-millis)))
;; We're not ready for the next value yet, so push it back
;; and proceed with the previous value.
(begin
(enqueue-front! queue next)
(finish! front val))
(loop next)))))))))])
(begin
(set-signal-thunk!
consumer
(lambda ()
(let* ([now-millis (current-inexact-milliseconds)]
[new-value (deep-value-now sig empty)])
Record the current observation and schedule to run when it 's time to take
;; on this value.
(enqueue! queue (cons new-value now-millis))
(schedule-alarm (+ now-millis delay-millis) producer))))
;; Make sure producer is scheduled to run as soon as there's a value ready for it.
(schedule-alarm (+ now-millis delay-millis) producer)
producer)))
;; signal[a] -> signal[a]
Delays |sig| by the smallest possible amount of time .
(define (inf-delay sig)
(delay-by sig 0))
; XXX fix to take arbitrary monotonically increasing number
; (instead of milliseconds)
; integral : signal[num] signal[num] -> signal[num]
(define integral
(lambda (b [ms-b 20])
(letrec ([accum 0]
[last-time (current-inexact-milliseconds)]
[last-val (value-now b)]
[last-alarm 0]
[consumer (proc->signal void b ms-b)]
[producer (proc->signal (lambda () (and (signal? consumer) accum)))])
(set-signal-thunk!
consumer
(lambda ()
(let ([now (current-inexact-milliseconds)])
(if (> now (+ last-time 20))
(begin
(when (not (number? last-val))
(set! last-val 0))
(set! accum (+ accum
(* last-val
(- now last-time))))
(set! last-time now)
(set! last-val (value-now b))
(when (value-now ms-b)
(schedule-alarm (+ last-time (value-now ms-b))
consumer)))
(when (or (>= now last-alarm)
(and (< now 0)
(>= last-alarm 0)))
(set! last-alarm (+ now 20))
(schedule-alarm last-alarm consumer)))
(schedule-alarm now producer))))
((signal-thunk consumer))
producer)))
; XXX fix for accuracy
; derivative : signal[num] -> signal[num]
(define (derivative b)
(let* ([last-value (value-now b)]
[last-time (current-inexact-milliseconds)]
[thunk (lambda ()
(let* ([new-value (value-now b)]
[new-time (current-inexact-milliseconds)]
[result (if (or (= new-value last-value)
(= new-time last-time)
(> new-time
(+ 500 last-time))
(not (number? last-value))
(not (number? new-value)))
0
(/ (- new-value last-value)
(- new-time last-time)))])
(set! last-value new-value)
(set! last-time new-time)
result))])
(proc->signal thunk b)))
(define create-strict-thunk
(case-lambda
[(fn) fn]
[(fn arg1) (lambda ()
(let ([a1 (value-now/no-copy arg1)])
(if (undefined? a1)
undefined
(fn a1))))]
[(fn arg1 arg2) (lambda ()
(let ([a1 (value-now/no-copy arg1)]
[a2 (value-now/no-copy arg2)])
(if (or (undefined? a1)
(undefined? a2))
undefined
(fn a1 a2))))]
[(fn arg1 arg2 arg3) (lambda ()
(let ([a1 (value-now/no-copy arg1)]
[a2 (value-now/no-copy arg2)]
[a3 (value-now/no-copy arg3)])
(if (or (undefined? a1)
(undefined? a2)
(undefined? a3))
undefined
(fn a1 a2 a3))))]
[(fn . args) (lambda ()
(let ([as (map value-now/no-copy args)])
(if (ormap undefined? as)
undefined
(apply fn as))))]))
(define create-thunk
(case-lambda
[(fn) fn]
[(fn arg1) (lambda () (fn (value-now/no-copy arg1)))]
[(fn arg1 arg2) (lambda () (fn (value-now/no-copy arg1) (value-now/no-copy arg2)))]
[(fn arg1 arg2 arg3) (lambda () (fn (value-now/no-copy arg1)
(value-now/no-copy arg2)
(value-now/no-copy arg3)))]
[(fn . args) (lambda () (apply fn (map value-now/no-copy args)))]))
#;
(define (general-event-processor proc . args)
proc : ( lambda ( emit suspend first - evt ) ... )
(let* ([out (econs undefined undefined)]
[esc #f]
[emit (lambda (val)
(set-erest! out (econs val undefined))
(set! out (erest out))
val)]
[streams (map signal-value args)])
(letrec ([suspend (lambda ()
(call/cc
(lambda (k)
(set! proc-k k)
(esc (void)))))]
[proc-k (lambda (evt) (proc emit suspend evt) (set! proc-k #f))])
(let ([thunk (lambda ()
(when (ormap undefined? streams)
;(eprintf "had an undefined stream\n")
(set! streams (fix-streams streams args)))
(let loop ([streams streams])
(extract (lambda (the-event strs)
(when proc-k
(call/cc
(lambda (k)
(set! esc k)
(proc-k the-event)))) (loop strs))
streams))
(set! streams (map signal-value args))
out)])
(apply proc->signal thunk args)))))
(define current-emit (make-parameter #f))
(define current-select (make-parameter #f))
(define (emit ev)
(cond
[(current-emit) => (lambda (f) (f ev))]
[else (error 'emit "outside of general-event-processor")]))
(define (select-proc . clauses)
(cond
[(current-select) => (lambda (f) (apply f clauses))]
[else (error 'select "outside of general-event-processor")]))
(define-syntax (select stx)
(syntax-case stx ()
[(select clause ...)
(with-syntax ([((e k) ...)
(map (lambda (c)
(syntax-case c (=>)
[(e => k) #'(e k)]
[(e exp0 exp1 ...) #'(e (lambda (_) exp0 exp1 ...))]))
(syntax-e #'(clause ...)))])
#'(select-proc (list e k) ...))]))
(define (flush . strs)
(select-proc (map (lambda (str) (list str void)) strs)))
#;
(define (general-event-processor2 proc)
(do-in-manager
(let* ([out (econs undefined undefined)]
[emit (lambda (val)
(set-erest! out (econs val undefined))
(set! out (erest out))
val)]
[streams (make-weak-hash)]
[extracted (make-weak-hash)]
[top-esc #f]
[rtn (proc->signal void)]
[select (lambda e/k-list
(let/ec esc
(let loop ()
(for-each (lambda (e/k)
(let* ([e (first e/k)]
[x (hash-ref
extracted e
(lambda () empty))])
(when (cons? x)
(hash-set!
extracted e (rest x))
(esc ((second e/k) (first x))))))
e/k-list)
(for-each (lambda (e/k)
(let* ([e (first e/k)])
(hash-ref
streams e
(lambda ()
(register rtn e)
(hash-set!
streams e
(signal-value e))))))
e/k-list)
(let/cc k
(set! proc (lambda () (k (void))))
(top-esc (void)))
(loop))))])
(let ([thunk (lambda ()
(hash-for-each
streams
(lambda (k v)
;; inefficient! appends each new event individually
(let loop ([str v])
(when (and (econs? str)
(not (undefined? (erest str))))
(hash-set!
extracted k
(append (hash-ref extracted k (lambda () empty))
(list (efirst (erest str)))))
(loop (erest str))))
(hash-set! streams k (signal-value k))))
(let/cc k
(set! top-esc k)
(parameterize ([current-emit emit]
[current-select select])
(proc)))
out)])
(set-signal-thunk! rtn thunk)
(iq-enqueue rtn)
rtn))))
(define (make-mutable lst)
(printf "make-mutable called on ~a\n" lst)
lst
#;(if (pair? lst)
(mcons (first lst) (make-mutable (rest lst)))
lst))
;; split : event[a] (a -> b) -> (b -> event[a])
(define (split ev fn)
(let* ([ht (make-weak-hash)]
[sig (for-each-e!
ev
(lambda (e)
(let/ec k
(send-event
(hash-ref ht (fn e) (lambda () (k (void))))
e)))
ht)])
(lambda (x)
sig
(hash-ref
ht x (lambda ()
(let ([rtn (event-receiver)])
(hash-set! ht x rtn)
rtn))))))
(define-syntax event-select
(syntax-rules ()
[(_ [ev k] ...)
()]))
(define fine-timer-granularity (new-cell 20))
(define milliseconds (make-time-b fine-timer-granularity))
(define time-b milliseconds)
;;;;;;;;;;;;;;;;;;;;;;
;; Command Lambda
(define-syntax mk-command-lambda
(syntax-rules ()
[(_ (free ...) forms body ...)
(if (ormap behavior? (list free ...))
(procs->signal:compound
(lambda x (lambda forms
(snapshot (free ...) body ...)))
(lambda (a b) void)
free ...)
(lambda forms body ...))]))
(define-for-syntax code-insp (variable-reference->module-declaration-inspector
(#%variable-reference)))
(define-syntax (command-lambda stx)
(define (arglist-bindings arglist-stx)
(syntax-case arglist-stx ()
[var
(identifier? arglist-stx)
(list arglist-stx)]
[(var ...)
(syntax->list arglist-stx)]
[(var . others)
(cons #'var (arglist-bindings #'others))]))
(define (make-snapshot-unbound insp unbound-ids)
(lambda (expr bound-ids)
(let snapshot-unbound ([expr expr] [bound-ids bound-ids])
(syntax-case (syntax-disarm expr code-insp) (#%datum
quote
#%top
let-values
letrec-values
lambda)
[x (identifier? #'x) (if (or
(syntax-property #'x 'protected)
(ormap (lambda (id)
(bound-identifier=? id #'x)) bound-ids))
#'x
(begin
(hash-set! unbound-ids #'x #t)
#'(#%app value-now x)))]
[(#%datum . val) expr]
[(quote . _) expr]
[(#%top . var) (begin
(hash-set! unbound-ids #'var #t)
FIX
[(letrec-values (((variable ...) in-e) ...) body-e ...)
(let ([new-bound-ids (append (syntax->list #'(variable ... ...)) bound-ids)])
(with-syntax ([(new-in-e ...) (map (lambda (exp)
(snapshot-unbound exp new-bound-ids))
(syntax->list #'(in-e ...)))]
[(new-body-e ...) (map (lambda (exp)
(snapshot-unbound exp new-bound-ids))
(syntax->list #'(body-e ...)))])
#'(letrec-values (((variable ...) new-in-e) ...) new-body-e ...)))]
[(let-values (((variable ...) in-e) ...) body-e ...)
(let ([new-bound-ids (append (syntax->list #'(variable ... ...)) bound-ids)])
(with-syntax ([(new-in-e ...) (map (lambda (exp)
(snapshot-unbound exp bound-ids))
(syntax->list #'(in-e ...)))]
[(new-body-e ...) (map (lambda (exp)
(snapshot-unbound exp new-bound-ids))
(syntax->list #'(body-e ...)))])
#'(let-values (((variable ...) new-in-e) ...) new-body-e ...)))]
[(lambda forms body-e ...)
(let ([new-bound-ids (append (arglist-bindings #'forms) bound-ids)])
(with-syntax ([(new-body-e ...) (map (lambda (exp)
(snapshot-unbound exp new-bound-ids))
(syntax->list #'(body-e ...)))])
#'(lambda forms new-body-e ...)))]
[(tag exp ...)
(with-syntax ([(new-exp ...) (map (lambda (exp)
(snapshot-unbound exp bound-ids))
(syntax->list #'(exp ...)))])
#'(tag new-exp ...))]
[x (begin
(eprintf "snapshot-unbound: fell through on ~a\n" #'x)
'())]))))
(syntax-case stx ()
[(src-command-lambda (id ...) expr ...)
(let ([c-insp (current-code-inspector)])
(parameterize ([current-code-inspector (make-inspector)])
(syntax-case (local-expand #'(lambda (id ...) expr ...) 'expression '()) (lambda)
[(lambda (id ...) expr ...)
(let ([unbound-ids (make-hash)])
(with-syntax ([(new-expr ...) (map (lambda (exp)
((make-snapshot-unbound c-insp unbound-ids)
exp
(syntax->list #'(id ...))))
(syntax->list #'(expr ...)))]
[(free-var ...) (hash-map unbound-ids
(lambda (k v) k))])
(begin
;(printf "~a\n" unbound-ids)
#'(if (ormap behavior? (list free-var ...))
(procs->signal:compound (lambda _
(lambda (id ...)
new-expr ...))
(lambda (a b) void)
free-var ...)
(lambda (id ...) expr ...)))))])))]))
(define for-each-e!
(let ([ht (make-weak-hash)])
(lambda (ev proc [ref 'dummy])
(hash-set! ht ref (cons (ev . ==> . proc) (hash-ref ht ref (lambda () empty)))))))
(define raise-exceptions (new-cell #t))
(define exception-raiser
(exceptions . ==> . (lambda (p) (when (value-now raise-exceptions)
(thread
(lambda () (raise (car p))))))))
| null | https://raw.githubusercontent.com/racket/frtime/9b9db67581107f4d7b995541c70f2d08f03ae89e/lang-ext.rkt | racket | general-event-processor
general-event-processor2
from core/frp
(string->uninterned-symbol "nothing"))
won't work in the presence of super structs or immutable fields
(define deep-value-now
maybe fix later to handle undefined-strictness
switch : event[behavior] behavior -> behavior
event ... -> event
behavior[a] -> event[a]
when-e : behavior[bool] -> event
while-e : behavior[bool] behavior[number] -> event
==> : event[a] (a -> b) -> event[b]
-=> : event[a] b -> event[b]
=#> : event[a] (a -> bool) -> event[a]
=#=> : event[a] (a -> b U nothing) -> event[b]
event[a] b (a b -> b) -> event[b]
event[(a -> a)] a -> event[a]
event[a] b (a b -> b) -> behavior[b]
event[(a -> a)] a -> behavior[a]
hold : a event[a] -> behavior[a]
Deprecated
signal[a] num -> signal[a]
Returns a signal whose value at (approximately) time (+ t |delay-millis|) is a (deep) snapshot
returned signal is undefined.
Assumptions: (current-inexact-milliseconds) is monotonically non-decreasing; |delay-millis| is
positive and finite.
Implementation strategy:
Maintain a queue of pairs (snapshot . timestamp) of the observed signal going back in
time for at least |delay-millis|. Start with (undefined . -inf.0) and (current-value . now), so
(>= now (+ timestamp delay-millis)).
|consumer| runs whenever |sig| changes and adds an item with the observed value and current
schedules to run at |delay - millis| in the future , by which
time it should be ready to take on that observed value.
|producer| has no dependencies recorded in the dataflow graph and only runs when scheduled
by the consumer. (This is what allows delay-by to break cycles.) It traverses the queue
looking for the latest observation (value . timestamp) such that
value returned by this procedure, so it stays alive as long as anything cares about its
value.
finish : (a . num) a -> a
TODO(gcooper): We could avoid this if data/queue supported a "peek" operation.
Add initial observations to the queue.
There's no way to "peek" at the next item in the queue, so we have to
dequeue it, check whether we're ready for it, and if not, stick it back
on the front...
we 'll use it if there 's no later
observation that's at least |delay-millis| old.
There are no later observations to consider, so use the current
one.
Look at the next item in the queue to see if we're ready for it.
If so, recur. Otherwise, put it back on the front of the queue
and use the previous value.
|consumer| alive, we retain a reference to it here, and we
trick the runtime into not optimizing it away by calling a
predicate and using the result in a conditional expression. If
the compiler ever gets smart enough to determine that the
outcome is provably always true, and therefore that it can
optimize away this code, we'll have to come up with a
different strategy (e.g., adding a special field to the signal
structure).
We're not ready for the next value yet, so push it back
and proceed with the previous value.
on this value.
Make sure producer is scheduled to run as soon as there's a value ready for it.
signal[a] -> signal[a]
XXX fix to take arbitrary monotonically increasing number
(instead of milliseconds)
integral : signal[num] signal[num] -> signal[num]
XXX fix for accuracy
derivative : signal[num] -> signal[num]
(eprintf "had an undefined stream\n")
inefficient! appends each new event individually
(if (pair? lst)
split : event[a] (a -> b) -> (b -> event[a])
Command Lambda
(printf "~a\n" unbound-ids) | #lang racket/base
(provide raise-exceptions
deep-value-now
nothing
nothing?
emit
select
switch
merge-e
once-e
changes
never-e
when-e
while-e
==>
-=>
=#>
=#=>
map-e
filter-e
filter-map-e
collect-e
accum-e
collect-b
accum-b
hold
for-each-e!
snapshot/sync
synchronize
snapshot
snapshot-e
snapshot/apply
milliseconds
fine-timer-granularity
seconds
delay-by
inf-delay
integral
derivative
new-cell
lift
lift-strict
event?
command-lambda
mk-command-lambda
until
event-loop
split
define-reactive
event-receiver
send-event
send-synchronous-event
send-synchronous-events
set-cell!
undefined
(rename-out [undefined?/lifted undefined?])
(rename-out [undefined? frp:undefined?])
behavior?
value-now
value-now/no-copy
value-now/sync
signal-count
signal?)
(require (for-syntax racket/base
(only-in racket/list first second last-pair empty empty?))
(only-in racket/list first second cons? empty empty? rest last-pair)
(only-in racket/function identity)
data/queue
(only-in frtime/core/frp super-lift undefined undefined? behavior? do-in-manager-after do-in-manager proc->signal set-signal-thunk! register unregister
signal? signal-depth signal:switching? signal-value value-now signal:compound? signal:compound-content signal:switching-current signal:switching-trigger
set-cell! snap? iq-enqueue value-now/no-copy event-receiver event-set? proc->signal:switching set-signal-producers! set-signal-depth! safe-signal-depth
make-events-now iq-resort event-set-events current-logical-time event-set-time event-producer2 schedule-alarm value-now/sync set-signal-value! signal-thunk
send-event exceptions send-synchronous-event send-synchronous-events signal-count))
(define (nothing? v) (eq? v nothing))
(define-syntax define-reactive
(syntax-rules ()
[(_ name expr)
(define name
(let ([val (parameterize ([snap? #f])
expr)])
(lambda () (deep-value-now val empty))))]))
(define (deep-value-now obj table)
(cond
[(assq obj table) => second]
[(behavior? obj)
(deep-value-now (signal-value obj) (cons (list obj (signal-value obj)) table))]
[(cons? obj)
(let* ([result (cons #f #f)]
[new-table (cons (list obj result) table)]
[car-val (deep-value-now (car obj) new-table)]
[cdr-val (deep-value-now (cdr obj) new-table)])
(if (and (eq? car-val (car obj))
(eq? cdr-val (cdr obj)))
obj
(cons car-val cdr-val)))]
[(struct? obj)
(let*-values ([(info skipped) (struct-info obj)]
[(name init-k auto-k acc mut! immut sup skipped?) (struct-type-info info)]
[(ctor) (struct-type-make-constructor info)]
[(indices) (build-list init-k identity)]
[(result) (apply ctor (build-list init-k (lambda (i) #f)))]
[(new-table) (cons (list obj result) table)]
[(elts) (build-list init-k (lambda (i)
(deep-value-now (acc obj i) new-table)))])
(if (andmap (lambda (i e) (eq? (acc obj i) e)) indices elts)
obj
(begin
(for-each (lambda (i e) (mut! result i e)) indices elts)
result)))]
[(vector? obj)
(let* ([len (vector-length obj)]
[indices (build-list len identity)]
[result (build-vector len (lambda (_) #f))]
[new-table (cons (list obj result) table)]
[elts (build-list len (lambda (i)
(deep-value-now (vector-ref obj i) new-table)))])
(if (andmap (lambda (i e) (eq? (vector-ref obj i) e)) indices elts)
obj
(begin
(for-each (lambda (i e) (vector-set! result i e)) indices elts)
result)))]
[else obj]))
(case-lambda
[(obj) (deep-value-now obj empty)]
[(obj table)
(cond
[(assq obj table) => second]
[(behavior? obj)
(deep-value-now (signal-value obj) (cons (list obj (signal-value obj)) table))]
[(event? obj)
(signal-value obj)]
[(cons? obj)
(let* ([result (cons #f #f)]
[new-table (cons (list obj result) table)]
[car-val (deep-value-now (car obj) new-table)]
[cdr-val (deep-value-now (cdr obj) new-table)])
(cons car-val cdr-val))]
[(struct? obj)
(let*-values ([(info skipped) (struct-info obj)]
[(name init-k auto-k acc mut immut sup skipped?) (struct-type-info info)]
[(ctor) (struct-type-make-constructor info)])
(apply ctor (build-list (+ auto-k init-k)
(lambda (i) (deep-value-now (acc obj i) table)))))]
[(vector? obj)
(build-vector
(vector-length obj)
(lambda (i)
(deep-value-now (vector-ref obj i) table)))]
[else obj])]))
(define (lift strict? fn . args)
(apply fn (map value-now args))
(with-continuation-mark
'frtime 'lift-active
(cond
[(ormap signal? args)
(apply
proc->signal
(apply (if strict? create-strict-thunk create-thunk) fn args)
args)]
[(and strict? (ormap undefined? args)) undefined]
[else (apply fn args)]))))
(define (lift-strict . args)
(apply lift #t args))
new - cell : ] - > behavior[a ] ( cell )
(define new-cell
(lambda ([init undefined])
(switch (event-receiver) init)))
(define (b1 . until . b2)
(proc->signal
(lambda () (if (undefined? (value-now b2))
(value-now b1)
(value-now b2)))
b1 b2))
(define-syntax (event-loop-help stx)
(syntax-case stx ()
[(_ ([name expr] ...)
[e => body] ...)
(with-syntax ([args #'(name ...)])
#'(accum-e
(merge-e
(e . ==> . (lambda (v)
(lambda (state)
(apply
(lambda args (body v))
state)))) ...)
(list expr ...)))]))
(define-syntax (event-loop stx)
(define (add-arrow clause)
(syntax-case clause (=>)
[(e => body) #'(e => body)]
[(e body) #'(e => (lambda (_) body))]))
(syntax-case stx ()
[(_ ([name expr] ...)
clause ...)
(with-syntax ([(new-clause ...)
(map add-arrow (syntax->list #'(clause ...)))])
#'(event-loop-help
([name expr] ...)
new-clause ...)
)]))
(define undefined?/lifted (lambda (arg) (lift #f undefined? arg)))
(define (event? v)
(and (signal? v)
(if (undefined? (signal-value v))
undefined
(event-set? (signal-value v)))))
(define switch
(lambda (e [init undefined])
(let* ([init (box init)]
[e-b (hold e (unbox init) #t)]
[ret (proc->signal:switching
(case-lambda [() (value-now (unbox init))]
[(msg) e])
init e-b e-b (unbox init))])
(set-signal-thunk!
ret
(case-lambda
[()
(when (not (eq? (unbox init) (signal-value e-b)))
(unregister ret (unbox init))
(set-box! init (value-now e-b))
(register ret (unbox init))
(set-signal-producers! ret (list e-b (unbox init)))
(set-signal-depth! ret (max (signal-depth ret)
(add1 (safe-signal-depth (unbox init)))))
(iq-resort))
(value-now/no-copy (unbox init))]
[(msg) e]))
ret)))
(define (merge-e . args)
(apply lift #t (lambda args
(make-events-now
(apply append
(map event-set-events
(filter (lambda (es) (= (current-logical-time) (event-set-time es)))
args)))))
args))
(define (once-e e)
(map-e second (filter-e (lambda (p) (= 1 (first p)))
(collect-e e (list 0) (lambda (e p) (list (add1 (first p)) e))))))
(define (changes b)
(lift #f (let ([first-time #t])
(lambda (bh)
(begin0
(make-events-now
(if first-time
empty
(list (deep-value-now bh empty))))
(set! first-time #f))))
b))
(define never-e
(changes #f))
(define (when-e b)
(let* ([last (value-now b)])
(lift #t (lambda (bh)
(make-events-now
(let ([current bh])
(begin0
(if (and (not last) current)
(list current)
empty)
(set! last current)))))
b)))
(define (while-e b interval)
(letrec ([ret (event-producer2
(lambda (emit)
(lambda the-args
(cond
[(value-now b) =>
(lambda (v)
(emit v)
(schedule-alarm (+ (value-now interval) (current-inexact-milliseconds)) ret))])))
b)])
ret))
(define (e . ==> . f)
(lift #t (lambda (es)
(make-events-now
(if (= (current-logical-time) (event-set-time es))
(map f (event-set-events es))
empty)))
e))
(define-syntax -=>
(syntax-rules ()
[(_ e k-e) (==> e (lambda (_) k-e))]))
(define (e . =#> . p)
(lift #t (lambda (es)
(make-events-now
(if (= (current-logical-time) (event-set-time es))
(filter (value-now p) (map value-now (event-set-events es)))
empty)))
e))
(define (e . =#=> . f)
(lift #t (lambda (es)
(make-events-now
(if (= (current-logical-time) (event-set-time es))
(filter (compose not nothing?) (map f (event-set-events es)))
empty)))
e))
(define (map-e f e)
(==> e f))
(define (filter-e p e)
(=#> e p))
(define (filter-map-e f e)
(=#=> e f))
(define (scan trans acc lst)
(if (cons? lst)
(let ([new-acc (trans (first lst) acc)])
(cons new-acc (scan trans new-acc (rest lst))))
empty))
(define (collect-e e init trans)
(lift #t (lambda (es)
(make-events-now
(cond
[(= (current-logical-time) (event-set-time es))
(let ([all-events (scan trans init (event-set-events es))])
(when (cons? all-events)
(set! init (first (last-pair all-events))))
all-events)]
[else empty])))
e))
(define (accum-e e init)
(lift #t (lambda (es)
(make-events-now
(cond
[(= (current-logical-time) (event-set-time es))
(let ([all-events (scan (lambda (t a) (t a)) init (event-set-events es))])
(when (cons? all-events)
(set! init (first (last-pair all-events))))
all-events)]
[else empty])))
e))
(define (collect-b ev init trans)
(hold (collect-e ev init trans) init))
(define (accum-b ev init)
(hold (accum-e ev init) init))
(define hold
(lambda (e [init undefined] [allow-behaviors? #f])
(let ([val init]
[warn-about-behaviors? #t])
(lift #t (lambda (es) (let ([events (event-set-events es)])
(when (and (= (current-logical-time) (event-set-time es))
(cons? events))
(set! val (first (last-pair (event-set-events es)))))
(when (and (behavior? val) (not allow-behaviors?))
(set! val (value-now val))
(when warn-about-behaviors?
(thread
(lambda ()
(error "hold: input event had a behavior; snapshotting to prevent nested behavior")))
(set! warn-about-behaviors? #f)))
val))
e))))
(define-syntax snapshot/sync
(syntax-rules ()
[(_ (id ...) expr ...)
(let-values ([(id ...) (value-now/sync id ...)])
expr ...)]))
(define (synchronize)
(snapshot/sync () (void)))
(define-syntax snapshot
(syntax-rules ()
[(_ (id ...) expr ...)
(let ([id (value-now id)] ...)
expr ...)]))
(define-syntax snapshot-all
(syntax-rules ()
[(_ expr ...)
(parameterize ([snap? #t])
expr ...)]))
(define (snapshot-e e . bs)
(apply lift #t (lambda (es . bs)
(make-events-now
(cond
[(= (current-logical-time) (event-set-time es))
(map (lambda (the-event) (cons the-event (map value-now bs)))
(event-set-events es))]
[else empty])))
e bs))
(define (snapshot/apply fn . args)
(apply fn (map value-now args)))
(define-syntax frp:send
(syntax-rules ()
[(_ obj meth arg ...)
(if (snap?)
(send obj meth (value-now arg) ...)
(send obj meth arg ...))]))
(define (make-time-b ms)
(let ([ret (proc->signal void)])
(set-signal-thunk! ret
(lambda ()
(let ([t (current-inexact-milliseconds)])
(schedule-alarm (+ (value-now ms) t) ret)
t)))
(set-signal-value! ret ((signal-thunk ret)))
ret))
(define seconds
(let ([ret (proc->signal void)])
(set-signal-thunk! ret
(lambda ()
(let ([s (current-seconds)]
[t (current-inexact-milliseconds)])
(schedule-alarm (* 1000 (add1 (floor (/ t 1000)))) ret)
s)))
(set-signal-value! ret ((signal-thunk ret)))
ret))
of the value of |sig| at time t , for all times t from now on . For earlier times , the value of the
(define (delay-by sig delay-millis)
there should always be at least one item ( value . timestamp ) in the queue such that
( > = now ( + timestamp delay - millis ) ) , and takes on the observed value . is the
(let* ([queue (make-queue)]
Puts |queue - item| back on the front of the queue and returns |val| , updating the
occurrence timestamp if |val| represents an event set .
[finish! (lambda (queue-item val)
(enqueue-front! queue queue-item)
(if (event-set? val)
(make-events-now (event-set-events val))
val))]
[now-millis (current-inexact-milliseconds)]
[_ (begin
(enqueue! queue (cons undefined -inf.0))
(enqueue! queue (cons (deep-value-now sig empty) now-millis)))]
's thunk needs to be in scope so it can schedule it , and
|producer| 's thunk needs to be in scope so it can keep it alive . To set up
this cycle , we first create with a dummy thunk ( void ) , then define
|producer| , and finally update 's thunk to what we want it to be .
[consumer (proc->signal void sig)]
[producer (proc->signal
(lambda ()
(let ([now-millis (current-inexact-milliseconds)])
(let loop ([front (dequeue! queue)])
(let* ([val (car front)])
(if (queue-empty? queue)
(finish! front val)
(let* ([next (dequeue! queue)]
[timestamp-millis (cdr next)])
: since there 's nothing that would otherwise keep
(if (and (signal? consumer)
(< now-millis (+ timestamp-millis delay-millis)))
(begin
(enqueue-front! queue next)
(finish! front val))
(loop next)))))))))])
(begin
(set-signal-thunk!
consumer
(lambda ()
(let* ([now-millis (current-inexact-milliseconds)]
[new-value (deep-value-now sig empty)])
Record the current observation and schedule to run when it 's time to take
(enqueue! queue (cons new-value now-millis))
(schedule-alarm (+ now-millis delay-millis) producer))))
(schedule-alarm (+ now-millis delay-millis) producer)
producer)))
Delays |sig| by the smallest possible amount of time .
(define (inf-delay sig)
(delay-by sig 0))
(define integral
(lambda (b [ms-b 20])
(letrec ([accum 0]
[last-time (current-inexact-milliseconds)]
[last-val (value-now b)]
[last-alarm 0]
[consumer (proc->signal void b ms-b)]
[producer (proc->signal (lambda () (and (signal? consumer) accum)))])
(set-signal-thunk!
consumer
(lambda ()
(let ([now (current-inexact-milliseconds)])
(if (> now (+ last-time 20))
(begin
(when (not (number? last-val))
(set! last-val 0))
(set! accum (+ accum
(* last-val
(- now last-time))))
(set! last-time now)
(set! last-val (value-now b))
(when (value-now ms-b)
(schedule-alarm (+ last-time (value-now ms-b))
consumer)))
(when (or (>= now last-alarm)
(and (< now 0)
(>= last-alarm 0)))
(set! last-alarm (+ now 20))
(schedule-alarm last-alarm consumer)))
(schedule-alarm now producer))))
((signal-thunk consumer))
producer)))
(define (derivative b)
(let* ([last-value (value-now b)]
[last-time (current-inexact-milliseconds)]
[thunk (lambda ()
(let* ([new-value (value-now b)]
[new-time (current-inexact-milliseconds)]
[result (if (or (= new-value last-value)
(= new-time last-time)
(> new-time
(+ 500 last-time))
(not (number? last-value))
(not (number? new-value)))
0
(/ (- new-value last-value)
(- new-time last-time)))])
(set! last-value new-value)
(set! last-time new-time)
result))])
(proc->signal thunk b)))
(define create-strict-thunk
(case-lambda
[(fn) fn]
[(fn arg1) (lambda ()
(let ([a1 (value-now/no-copy arg1)])
(if (undefined? a1)
undefined
(fn a1))))]
[(fn arg1 arg2) (lambda ()
(let ([a1 (value-now/no-copy arg1)]
[a2 (value-now/no-copy arg2)])
(if (or (undefined? a1)
(undefined? a2))
undefined
(fn a1 a2))))]
[(fn arg1 arg2 arg3) (lambda ()
(let ([a1 (value-now/no-copy arg1)]
[a2 (value-now/no-copy arg2)]
[a3 (value-now/no-copy arg3)])
(if (or (undefined? a1)
(undefined? a2)
(undefined? a3))
undefined
(fn a1 a2 a3))))]
[(fn . args) (lambda ()
(let ([as (map value-now/no-copy args)])
(if (ormap undefined? as)
undefined
(apply fn as))))]))
(define create-thunk
(case-lambda
[(fn) fn]
[(fn arg1) (lambda () (fn (value-now/no-copy arg1)))]
[(fn arg1 arg2) (lambda () (fn (value-now/no-copy arg1) (value-now/no-copy arg2)))]
[(fn arg1 arg2 arg3) (lambda () (fn (value-now/no-copy arg1)
(value-now/no-copy arg2)
(value-now/no-copy arg3)))]
[(fn . args) (lambda () (apply fn (map value-now/no-copy args)))]))
(define (general-event-processor proc . args)
proc : ( lambda ( emit suspend first - evt ) ... )
(let* ([out (econs undefined undefined)]
[esc #f]
[emit (lambda (val)
(set-erest! out (econs val undefined))
(set! out (erest out))
val)]
[streams (map signal-value args)])
(letrec ([suspend (lambda ()
(call/cc
(lambda (k)
(set! proc-k k)
(esc (void)))))]
[proc-k (lambda (evt) (proc emit suspend evt) (set! proc-k #f))])
(let ([thunk (lambda ()
(when (ormap undefined? streams)
(set! streams (fix-streams streams args)))
(let loop ([streams streams])
(extract (lambda (the-event strs)
(when proc-k
(call/cc
(lambda (k)
(set! esc k)
(proc-k the-event)))) (loop strs))
streams))
(set! streams (map signal-value args))
out)])
(apply proc->signal thunk args)))))
(define current-emit (make-parameter #f))
(define current-select (make-parameter #f))
(define (emit ev)
(cond
[(current-emit) => (lambda (f) (f ev))]
[else (error 'emit "outside of general-event-processor")]))
(define (select-proc . clauses)
(cond
[(current-select) => (lambda (f) (apply f clauses))]
[else (error 'select "outside of general-event-processor")]))
(define-syntax (select stx)
(syntax-case stx ()
[(select clause ...)
(with-syntax ([((e k) ...)
(map (lambda (c)
(syntax-case c (=>)
[(e => k) #'(e k)]
[(e exp0 exp1 ...) #'(e (lambda (_) exp0 exp1 ...))]))
(syntax-e #'(clause ...)))])
#'(select-proc (list e k) ...))]))
(define (flush . strs)
(select-proc (map (lambda (str) (list str void)) strs)))
(define (general-event-processor2 proc)
(do-in-manager
(let* ([out (econs undefined undefined)]
[emit (lambda (val)
(set-erest! out (econs val undefined))
(set! out (erest out))
val)]
[streams (make-weak-hash)]
[extracted (make-weak-hash)]
[top-esc #f]
[rtn (proc->signal void)]
[select (lambda e/k-list
(let/ec esc
(let loop ()
(for-each (lambda (e/k)
(let* ([e (first e/k)]
[x (hash-ref
extracted e
(lambda () empty))])
(when (cons? x)
(hash-set!
extracted e (rest x))
(esc ((second e/k) (first x))))))
e/k-list)
(for-each (lambda (e/k)
(let* ([e (first e/k)])
(hash-ref
streams e
(lambda ()
(register rtn e)
(hash-set!
streams e
(signal-value e))))))
e/k-list)
(let/cc k
(set! proc (lambda () (k (void))))
(top-esc (void)))
(loop))))])
(let ([thunk (lambda ()
(hash-for-each
streams
(lambda (k v)
(let loop ([str v])
(when (and (econs? str)
(not (undefined? (erest str))))
(hash-set!
extracted k
(append (hash-ref extracted k (lambda () empty))
(list (efirst (erest str)))))
(loop (erest str))))
(hash-set! streams k (signal-value k))))
(let/cc k
(set! top-esc k)
(parameterize ([current-emit emit]
[current-select select])
(proc)))
out)])
(set-signal-thunk! rtn thunk)
(iq-enqueue rtn)
rtn))))
(define (make-mutable lst)
(printf "make-mutable called on ~a\n" lst)
lst
(mcons (first lst) (make-mutable (rest lst)))
lst))
(define (split ev fn)
(let* ([ht (make-weak-hash)]
[sig (for-each-e!
ev
(lambda (e)
(let/ec k
(send-event
(hash-ref ht (fn e) (lambda () (k (void))))
e)))
ht)])
(lambda (x)
sig
(hash-ref
ht x (lambda ()
(let ([rtn (event-receiver)])
(hash-set! ht x rtn)
rtn))))))
(define-syntax event-select
(syntax-rules ()
[(_ [ev k] ...)
()]))
(define fine-timer-granularity (new-cell 20))
(define milliseconds (make-time-b fine-timer-granularity))
(define time-b milliseconds)
(define-syntax mk-command-lambda
(syntax-rules ()
[(_ (free ...) forms body ...)
(if (ormap behavior? (list free ...))
(procs->signal:compound
(lambda x (lambda forms
(snapshot (free ...) body ...)))
(lambda (a b) void)
free ...)
(lambda forms body ...))]))
(define-for-syntax code-insp (variable-reference->module-declaration-inspector
(#%variable-reference)))
(define-syntax (command-lambda stx)
(define (arglist-bindings arglist-stx)
(syntax-case arglist-stx ()
[var
(identifier? arglist-stx)
(list arglist-stx)]
[(var ...)
(syntax->list arglist-stx)]
[(var . others)
(cons #'var (arglist-bindings #'others))]))
(define (make-snapshot-unbound insp unbound-ids)
(lambda (expr bound-ids)
(let snapshot-unbound ([expr expr] [bound-ids bound-ids])
(syntax-case (syntax-disarm expr code-insp) (#%datum
quote
#%top
let-values
letrec-values
lambda)
[x (identifier? #'x) (if (or
(syntax-property #'x 'protected)
(ormap (lambda (id)
(bound-identifier=? id #'x)) bound-ids))
#'x
(begin
(hash-set! unbound-ids #'x #t)
#'(#%app value-now x)))]
[(#%datum . val) expr]
[(quote . _) expr]
[(#%top . var) (begin
(hash-set! unbound-ids #'var #t)
FIX
[(letrec-values (((variable ...) in-e) ...) body-e ...)
(let ([new-bound-ids (append (syntax->list #'(variable ... ...)) bound-ids)])
(with-syntax ([(new-in-e ...) (map (lambda (exp)
(snapshot-unbound exp new-bound-ids))
(syntax->list #'(in-e ...)))]
[(new-body-e ...) (map (lambda (exp)
(snapshot-unbound exp new-bound-ids))
(syntax->list #'(body-e ...)))])
#'(letrec-values (((variable ...) new-in-e) ...) new-body-e ...)))]
[(let-values (((variable ...) in-e) ...) body-e ...)
(let ([new-bound-ids (append (syntax->list #'(variable ... ...)) bound-ids)])
(with-syntax ([(new-in-e ...) (map (lambda (exp)
(snapshot-unbound exp bound-ids))
(syntax->list #'(in-e ...)))]
[(new-body-e ...) (map (lambda (exp)
(snapshot-unbound exp new-bound-ids))
(syntax->list #'(body-e ...)))])
#'(let-values (((variable ...) new-in-e) ...) new-body-e ...)))]
[(lambda forms body-e ...)
(let ([new-bound-ids (append (arglist-bindings #'forms) bound-ids)])
(with-syntax ([(new-body-e ...) (map (lambda (exp)
(snapshot-unbound exp new-bound-ids))
(syntax->list #'(body-e ...)))])
#'(lambda forms new-body-e ...)))]
[(tag exp ...)
(with-syntax ([(new-exp ...) (map (lambda (exp)
(snapshot-unbound exp bound-ids))
(syntax->list #'(exp ...)))])
#'(tag new-exp ...))]
[x (begin
(eprintf "snapshot-unbound: fell through on ~a\n" #'x)
'())]))))
(syntax-case stx ()
[(src-command-lambda (id ...) expr ...)
(let ([c-insp (current-code-inspector)])
(parameterize ([current-code-inspector (make-inspector)])
(syntax-case (local-expand #'(lambda (id ...) expr ...) 'expression '()) (lambda)
[(lambda (id ...) expr ...)
(let ([unbound-ids (make-hash)])
(with-syntax ([(new-expr ...) (map (lambda (exp)
((make-snapshot-unbound c-insp unbound-ids)
exp
(syntax->list #'(id ...))))
(syntax->list #'(expr ...)))]
[(free-var ...) (hash-map unbound-ids
(lambda (k v) k))])
(begin
#'(if (ormap behavior? (list free-var ...))
(procs->signal:compound (lambda _
(lambda (id ...)
new-expr ...))
(lambda (a b) void)
free-var ...)
(lambda (id ...) expr ...)))))])))]))
(define for-each-e!
(let ([ht (make-weak-hash)])
(lambda (ev proc [ref 'dummy])
(hash-set! ht ref (cons (ev . ==> . proc) (hash-ref ht ref (lambda () empty)))))))
(define raise-exceptions (new-cell #t))
(define exception-raiser
(exceptions . ==> . (lambda (p) (when (value-now raise-exceptions)
(thread
(lambda () (raise (car p))))))))
|
65e95a42ac349d10e3f33a46cd7babd6932423117d37ff3144f1cc033c222638 | anurudhp/CPHaskell | d.hs | -- AC
{-# LANGUAGE Safe #-}
import Control.Arrow ((>>>))
import qualified Data.ByteString.Lazy.Char8 as C
import safe Data.Graph (flattenSCC, stronglyConnComp)
import safe Data.Maybe (catMaybes, fromJust)
main :: IO ()
main =
C.interact $
C.lines >>>
drop 1 >>>
map (C.words >>> map readInt) >>>
process >>> map (show >>> C.pack) >>> C.unlines
where
readInt = C.readInt >>> fromJust >>> fst
process :: [[Int]] -> [Int]
process [] = []
process ([n]:ps:cs:xs) = solve n ps cs : process xs
solve :: Int -> [Int] -> [Int] -> Int
solve _ ps cs =
minimum $
best . flattenSCC <$> stronglyConnComp (zip3 cs [1 ..] ((: []) <$> ps))
best :: [Int] -> Int
best xs = head $ filter check $ filter ((== 0) . (n `mod`)) [1 .. n]
where
n = length xs
check :: Int -> Bool
check len = not . null . catMaybes $ groupZip len [] xs
groupZip :: Int -> [Maybe Int] -> [Int] -> [Maybe Int]
groupZip _ cur [] = cur
groupZip len [] xs = groupZip len (Just <$> take len xs) (drop len xs)
groupZip len cur xs =
groupZip len (zipWith comb cur (take len xs)) (drop len xs)
where
comb Nothing _ = Nothing
comb (Just x) y =
if x == y
then Just x
else Nothing
| null | https://raw.githubusercontent.com/anurudhp/CPHaskell/01ae8dde6aab4f6ddfebd122ded0b42779dd16f1/contests/codeforces/1327/d.hs | haskell | AC
# LANGUAGE Safe # |
import Control.Arrow ((>>>))
import qualified Data.ByteString.Lazy.Char8 as C
import safe Data.Graph (flattenSCC, stronglyConnComp)
import safe Data.Maybe (catMaybes, fromJust)
main :: IO ()
main =
C.interact $
C.lines >>>
drop 1 >>>
map (C.words >>> map readInt) >>>
process >>> map (show >>> C.pack) >>> C.unlines
where
readInt = C.readInt >>> fromJust >>> fst
process :: [[Int]] -> [Int]
process [] = []
process ([n]:ps:cs:xs) = solve n ps cs : process xs
solve :: Int -> [Int] -> [Int] -> Int
solve _ ps cs =
minimum $
best . flattenSCC <$> stronglyConnComp (zip3 cs [1 ..] ((: []) <$> ps))
best :: [Int] -> Int
best xs = head $ filter check $ filter ((== 0) . (n `mod`)) [1 .. n]
where
n = length xs
check :: Int -> Bool
check len = not . null . catMaybes $ groupZip len [] xs
groupZip :: Int -> [Maybe Int] -> [Int] -> [Maybe Int]
groupZip _ cur [] = cur
groupZip len [] xs = groupZip len (Just <$> take len xs) (drop len xs)
groupZip len cur xs =
groupZip len (zipWith comb cur (take len xs)) (drop len xs)
where
comb Nothing _ = Nothing
comb (Just x) y =
if x == y
then Just x
else Nothing
|
17aab285b1d49646bdaaa130e72aa395cc80e82d518b20559736e86984e489bd | tonyg/racket-nat-traversal | info.rkt | #lang setup/infotab
(define name "nat-traversal")
(define blurb
(list
`(p "Implementation of NAT traversal utilities for opening ports on home routers.")))
(define categories '(net))
(define can-be-loaded-with 'all)
(define homepage "-nat-traversal")
(define primary-file "main.rkt")
(define repositories '("4.x"))
(define scribblings '(("scribblings/nat-traversal.scrbl" ())))
(define deps '("net-lib"
"base" "bitsyntax" "web-server-lib"))
(define build-deps '("racket-doc" "scribble-lib"))
| null | https://raw.githubusercontent.com/tonyg/racket-nat-traversal/091d3ce0990b05508d1b0e0ff9997774a48161d2/info.rkt | racket | #lang setup/infotab
(define name "nat-traversal")
(define blurb
(list
`(p "Implementation of NAT traversal utilities for opening ports on home routers.")))
(define categories '(net))
(define can-be-loaded-with 'all)
(define homepage "-nat-traversal")
(define primary-file "main.rkt")
(define repositories '("4.x"))
(define scribblings '(("scribblings/nat-traversal.scrbl" ())))
(define deps '("net-lib"
"base" "bitsyntax" "web-server-lib"))
(define build-deps '("racket-doc" "scribble-lib"))
| |
a6ae9d99d985c3d8739a3ae7f78731549ac70757c6fd202aab43196a1527ee9d | raaz-crypto/raaz | Blake2bSpec.hs | # LANGUAGE ForeignFunctionInterface #
module Monocypher.Blake2bSpec where
import Data.ByteString.Internal (unsafeCreate)
import Data.ByteString.Unsafe (unsafeUseAsCStringLen)
import qualified Foreign.Storable as Storable
import Foreign.Ptr
import Foreign.C.Types
import Foreign.C.String
import Tests.Core
import qualified Raaz.Digest.Blake2b as Blake2b
foreign import ccall unsafe
crypto_blake2b :: Ptr Word8 -- hash
-> Ptr CChar -- message
-> CSize
-> IO ()
blake2bSize :: Int
blake2bSize = Storable.sizeOf (undefined :: Blake2b)
monocypher_blake2b_io :: Ptr Word8 -> CStringLen -> IO ()
monocypher_blake2b_io hshPtr (ptr, l) = crypto_blake2b hshPtr ptr (toEnum l)
monocypher_blake2b :: ByteString -> Blake2b
monocypher_blake2b bs = unsafeFromByteString $ unsafeCreate blake2bSize creator
where creator ptr = unsafeUseAsCStringLen bs (monocypher_blake2b_io ptr)
spec :: Spec
spec = prop "monocypher vs raaz - blake2b" $
\ x ->
monocypher_blake2b x `shouldBe` Blake2b.digest x
| null | https://raw.githubusercontent.com/raaz-crypto/raaz/91799e1ae528e909ad921f6c0d6f51ebd8c7328f/monocypher/tests/Monocypher/Blake2bSpec.hs | haskell | hash
message | # LANGUAGE ForeignFunctionInterface #
module Monocypher.Blake2bSpec where
import Data.ByteString.Internal (unsafeCreate)
import Data.ByteString.Unsafe (unsafeUseAsCStringLen)
import qualified Foreign.Storable as Storable
import Foreign.Ptr
import Foreign.C.Types
import Foreign.C.String
import Tests.Core
import qualified Raaz.Digest.Blake2b as Blake2b
foreign import ccall unsafe
-> CSize
-> IO ()
blake2bSize :: Int
blake2bSize = Storable.sizeOf (undefined :: Blake2b)
monocypher_blake2b_io :: Ptr Word8 -> CStringLen -> IO ()
monocypher_blake2b_io hshPtr (ptr, l) = crypto_blake2b hshPtr ptr (toEnum l)
monocypher_blake2b :: ByteString -> Blake2b
monocypher_blake2b bs = unsafeFromByteString $ unsafeCreate blake2bSize creator
where creator ptr = unsafeUseAsCStringLen bs (monocypher_blake2b_io ptr)
spec :: Spec
spec = prop "monocypher vs raaz - blake2b" $
\ x ->
monocypher_blake2b x `shouldBe` Blake2b.digest x
|
5bb05e4f82ef789c62372cdde86e3a91f51ae14fd414759bb84e738f78dc2b2c | nikita-volkov/rebase | Strict.hs | module Rebase.Data.HashMap.Strict
(
module Data.HashMap.Strict
)
where
import Data.HashMap.Strict
| null | https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Data/HashMap/Strict.hs | haskell | module Rebase.Data.HashMap.Strict
(
module Data.HashMap.Strict
)
where
import Data.HashMap.Strict
| |
d5fd48377fe1dcf198051b4f0ea873e7e0e946d158f6bf0b9a4315356c6ee414 | kmarekspartz/TaPL | Parser.hs | module Language.TaPL.Boolean.Parser (parseString, parseFile) where
import qualified Text.Parsec.Token as Token
import Text.Parsec.Language (emptyDef)
import Text.Parsec.Prim (parse)
import Text.Parsec.String (Parser)
import Control.Applicative ((<|>))
import Language.TaPL.Boolean.Syntax (Term(..))
-- This module is adapted from:
booleanDef =
emptyDef { Token.reservedNames = [ "if"
, "then"
, "else"
, "true"
, "false"
]
}
lexer = Token.makeTokenParser booleanDef
reserved = Token.reserved lexer -- parses a reserved name
parens = Token.parens lexer -- parses surrounding parenthesis:
-- parens p
-- takes care of the parenthesis and
uses p to parse what 's inside them
whiteSpace = Token.whiteSpace lexer -- parses whitespace
booleanParser :: Parser Term
booleanParser = whiteSpace >> expr
expr :: Parser Term
expr = parens expr
<|> ifExpr
<|> (reserved "true" >> return TmTrue)
<|> (reserved "false" >> return TmFalse)
ifExpr :: Parser Term
ifExpr = do reserved "if"
t1 <- expr
reserved "then"
t2 <- expr
reserved "else"
t3 <- expr
return $ TmIf t1 t2 t3
parseString :: String -> Term
parseString str =
case parse booleanParser "" str of
Left e -> error $ show e
Right t -> t
parseFile :: String -> IO Term
parseFile file =
do program <- readFile file
case parse booleanParser "" program of
Left e -> print e >> fail "parse error"
Right t -> return t
| null | https://raw.githubusercontent.com/kmarekspartz/TaPL/2f1aebf5ed370f769709852ee27020f5cb715123/src/Language/TaPL/Boolean/Parser.hs | haskell | This module is adapted from:
parses a reserved name
parses surrounding parenthesis:
parens p
takes care of the parenthesis and
parses whitespace | module Language.TaPL.Boolean.Parser (parseString, parseFile) where
import qualified Text.Parsec.Token as Token
import Text.Parsec.Language (emptyDef)
import Text.Parsec.Prim (parse)
import Text.Parsec.String (Parser)
import Control.Applicative ((<|>))
import Language.TaPL.Boolean.Syntax (Term(..))
booleanDef =
emptyDef { Token.reservedNames = [ "if"
, "then"
, "else"
, "true"
, "false"
]
}
lexer = Token.makeTokenParser booleanDef
uses p to parse what 's inside them
booleanParser :: Parser Term
booleanParser = whiteSpace >> expr
expr :: Parser Term
expr = parens expr
<|> ifExpr
<|> (reserved "true" >> return TmTrue)
<|> (reserved "false" >> return TmFalse)
ifExpr :: Parser Term
ifExpr = do reserved "if"
t1 <- expr
reserved "then"
t2 <- expr
reserved "else"
t3 <- expr
return $ TmIf t1 t2 t3
parseString :: String -> Term
parseString str =
case parse booleanParser "" str of
Left e -> error $ show e
Right t -> t
parseFile :: String -> IO Term
parseFile file =
do program <- readFile file
case parse booleanParser "" program of
Left e -> print e >> fail "parse error"
Right t -> return t
|
15ca460d096718572b79f63db9bfa8e7d4941fada533d78904e261bcfcfb50be | noinia/hgeometry | RangeTree.hs | # LANGUAGE UndecidableInstances #
# LANGUAGE UndecidableSuperClasses #
--------------------------------------------------------------------------------
-- |
-- Module : Geometry.RangeTree
Copyright : ( C )
-- License : see the LICENSE file
Maintainer :
--------------------------------------------------------------------------------
module Geometry.RangeTree where
import Control.Lens hiding (element)
import Data.Ext
import qualified Data.Foldable as F
import Geometry.Point
import qualified Geometry.RangeTree.Generic as GRT
import Geometry.RangeTree.Measure
import Geometry.Vector
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NonEmpty
import Data.Measured.Class
import Data.Range
import GHC.TypeLits
import Prelude hiding (last,init,head)
--------------------------------------------------------------------------------
type RangeTree d = RT d d
newtype RT i d v p r =
RangeTree { _unRangeTree :: GRT.RangeTree (Assoc i d v p r) (Leaf i d v p r) r }
deriving instance (Show r, Show (Assoc i d v p r), Show (Leaf i d v p r)) => Show (RT i d v p r)
deriving instance (Eq r, Eq (Assoc i d v p r), Eq (Leaf i d v p r)) => Eq (RT i d v p r)
newtype Leaf i d v p r = Leaf { _getPts :: [Point d r :+ p]} deriving (Semigroup,Monoid)
deriving instance (Show r, Show p, Arity d) => Show (Leaf i d v p r)
deriving instance (Eq r, Eq p, Arity d) => Eq (Leaf i d v p r)
type family AssocT i d v p r where
AssocT 1 d v p r = v (Point d r :+ p)
AssocT 2 d v p r = Maybe (RT 1 d v p r)
newtype Assoc i d v p r = Assoc { unAssoc :: AssocT i d v p r }
deriving instance Show (AssocT i d v p r) => Show (Assoc i d v p r)
deriving instance Eq (AssocT i d v p r) => Eq (Assoc i d v p r)
type RTMeasure v d p r = (LabeledMeasure v, Semigroup (v (Point d r :+ p)))
instance RTMeasure v d p r => Semigroup (Assoc 1 d v p r) where
(Assoc l) <> (Assoc r) = Assoc $ l <> r
instance (RTMeasure v d p r, Ord r, 1 <= d, Arity d) => Semigroup (Assoc 2 d v p r) where
(Assoc l) <> (Assoc r) = Assoc . createRangeTree'' $ toList l <> toList r
where
toList = maybe [] (F.toList . toAscList)
createRangeTree'' = fmap createRangeTree1 . NonEmpty.nonEmpty
instance (RTMeasure v d p r, Ord r, 1 <= d, Arity d) => Monoid (Assoc 2 d v p r) where
mempty = Assoc Nothing
----------------------------------------
instance ( RTMeasure v d p r
) => Measured (Assoc 1 d v p r) (Leaf 1 d v p r) where
measure (Leaf pts) = Assoc . labeledMeasure $ pts
instance ( RTMeasure v d p r, Ord r, 1 <= d, Arity d
) => Measured (Assoc 2 d v p r) (Leaf 2 d v p r) where
measure (Leaf pts) = Assoc . createRangeTree'' $ pts
where
createRangeTree'' = fmap createRangeTree1 . NonEmpty.nonEmpty
----------------------------------------
createRangeTree' :: (Ord r, RTMeasure v d p r
-- , Arity d, Arity (d+1), d ~ (d' + 1), Arity d'
-- , Measured (Assoc d v p r) (Leaf d v p r)
)
=> [Point d r :+ p] -> Maybe (RT i d v p r)
createRangeTree' = fmap createRangeTree . NonEmpty.nonEmpty
createRangeTree :: (Ord r, RTMeasure v d p r
-- , Arity d, Arity (d+1), d ~ (d' + 1), Arity d'
-- , Measured (Assoc d v p r) (Leaf d v p r)
)
=> NonEmpty (Point d r :+ p) -> RT i d v p r
createRangeTree = undefined
-- RangeTree . GRT.createTree
. fmap ( - > last ( p^.core.vector ) : + Leaf [ p ] )
--------------------------------------------------------------------------------
-- | Gets all points in the range tree
toAscList :: RT i d v p r -> [Point d r :+ p]
toAscList = concatMap (^.extra.to _getPts) . F.toList . GRT.toAscList . _unRangeTree
--------------------------------------------------------------------------------
createRangeTree1 :: (Ord r, RTMeasure v d p r, 1 <= d, Arity d)
=> NonEmpty (Point d r :+ p) -> RT 1 d v p r
createRangeTree1 = RangeTree . GRT.createTree
. fmap (\p -> head (p^.core.vector) :+ Leaf [p])
createRangeTree2 :: forall v d r p. (Ord r, RTMeasure v d p r, Arity d, 2 <= d
, 1 <= d -- this one is kind of silly
) => NonEmpty (Point d r :+ p) -> RT 2 d v p r
createRangeTree2 = RangeTree . GRT.createTree
. fmap (\p -> p^.core.coord @2 :+ Leaf [p])
--------------------------------------------------------------------------------
-- * Querying
search :: ( Ord r, Monoid (v (Point d r :+ p)), Query i d)
=> Vector d (Range r) -> RT i d v p r -> v (Point d r :+ p)
search r = mconcat . search' r
class (i <= d, Arity d) => Query i d where
search' :: Ord r => Vector d (Range r) -> RT i d v p r -> [v (Point d r :+ p)]
instance (1 <= d, Arity d) => Query 1 d where
search' qr = map unAssoc . GRT.search' r . _unRangeTree
where
r = qr^.element @0
instance ( 1 <= d, i <= d, Query (i-1) d, Arity d
, i ~ 2
) => Query 2 d where
search' qr = concatMap (maybe [] (search' qr) . unAssoc) . GRT.search' r . _unRangeTree
where
r = qr^.element @(i-1)
| null | https://raw.githubusercontent.com/noinia/hgeometry/f8cdbc02c6878d4883ce95ed229d9cb09ffe296f/hgeometry/src/Geometry/RangeTree.hs | haskell | ------------------------------------------------------------------------------
|
Module : Geometry.RangeTree
License : see the LICENSE file
------------------------------------------------------------------------------
------------------------------------------------------------------------------
--------------------------------------
--------------------------------------
, Arity d, Arity (d+1), d ~ (d' + 1), Arity d'
, Measured (Assoc d v p r) (Leaf d v p r)
, Arity d, Arity (d+1), d ~ (d' + 1), Arity d'
, Measured (Assoc d v p r) (Leaf d v p r)
RangeTree . GRT.createTree
------------------------------------------------------------------------------
| Gets all points in the range tree
------------------------------------------------------------------------------
this one is kind of silly
------------------------------------------------------------------------------
* Querying | # LANGUAGE UndecidableInstances #
# LANGUAGE UndecidableSuperClasses #
Copyright : ( C )
Maintainer :
module Geometry.RangeTree where
import Control.Lens hiding (element)
import Data.Ext
import qualified Data.Foldable as F
import Geometry.Point
import qualified Geometry.RangeTree.Generic as GRT
import Geometry.RangeTree.Measure
import Geometry.Vector
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NonEmpty
import Data.Measured.Class
import Data.Range
import GHC.TypeLits
import Prelude hiding (last,init,head)
type RangeTree d = RT d d
newtype RT i d v p r =
RangeTree { _unRangeTree :: GRT.RangeTree (Assoc i d v p r) (Leaf i d v p r) r }
deriving instance (Show r, Show (Assoc i d v p r), Show (Leaf i d v p r)) => Show (RT i d v p r)
deriving instance (Eq r, Eq (Assoc i d v p r), Eq (Leaf i d v p r)) => Eq (RT i d v p r)
newtype Leaf i d v p r = Leaf { _getPts :: [Point d r :+ p]} deriving (Semigroup,Monoid)
deriving instance (Show r, Show p, Arity d) => Show (Leaf i d v p r)
deriving instance (Eq r, Eq p, Arity d) => Eq (Leaf i d v p r)
type family AssocT i d v p r where
AssocT 1 d v p r = v (Point d r :+ p)
AssocT 2 d v p r = Maybe (RT 1 d v p r)
newtype Assoc i d v p r = Assoc { unAssoc :: AssocT i d v p r }
deriving instance Show (AssocT i d v p r) => Show (Assoc i d v p r)
deriving instance Eq (AssocT i d v p r) => Eq (Assoc i d v p r)
type RTMeasure v d p r = (LabeledMeasure v, Semigroup (v (Point d r :+ p)))
instance RTMeasure v d p r => Semigroup (Assoc 1 d v p r) where
(Assoc l) <> (Assoc r) = Assoc $ l <> r
instance (RTMeasure v d p r, Ord r, 1 <= d, Arity d) => Semigroup (Assoc 2 d v p r) where
(Assoc l) <> (Assoc r) = Assoc . createRangeTree'' $ toList l <> toList r
where
toList = maybe [] (F.toList . toAscList)
createRangeTree'' = fmap createRangeTree1 . NonEmpty.nonEmpty
instance (RTMeasure v d p r, Ord r, 1 <= d, Arity d) => Monoid (Assoc 2 d v p r) where
mempty = Assoc Nothing
instance ( RTMeasure v d p r
) => Measured (Assoc 1 d v p r) (Leaf 1 d v p r) where
measure (Leaf pts) = Assoc . labeledMeasure $ pts
instance ( RTMeasure v d p r, Ord r, 1 <= d, Arity d
) => Measured (Assoc 2 d v p r) (Leaf 2 d v p r) where
measure (Leaf pts) = Assoc . createRangeTree'' $ pts
where
createRangeTree'' = fmap createRangeTree1 . NonEmpty.nonEmpty
createRangeTree' :: (Ord r, RTMeasure v d p r
)
=> [Point d r :+ p] -> Maybe (RT i d v p r)
createRangeTree' = fmap createRangeTree . NonEmpty.nonEmpty
createRangeTree :: (Ord r, RTMeasure v d p r
)
=> NonEmpty (Point d r :+ p) -> RT i d v p r
createRangeTree = undefined
. fmap ( - > last ( p^.core.vector ) : + Leaf [ p ] )
toAscList :: RT i d v p r -> [Point d r :+ p]
toAscList = concatMap (^.extra.to _getPts) . F.toList . GRT.toAscList . _unRangeTree
createRangeTree1 :: (Ord r, RTMeasure v d p r, 1 <= d, Arity d)
=> NonEmpty (Point d r :+ p) -> RT 1 d v p r
createRangeTree1 = RangeTree . GRT.createTree
. fmap (\p -> head (p^.core.vector) :+ Leaf [p])
createRangeTree2 :: forall v d r p. (Ord r, RTMeasure v d p r, Arity d, 2 <= d
) => NonEmpty (Point d r :+ p) -> RT 2 d v p r
createRangeTree2 = RangeTree . GRT.createTree
. fmap (\p -> p^.core.coord @2 :+ Leaf [p])
search :: ( Ord r, Monoid (v (Point d r :+ p)), Query i d)
=> Vector d (Range r) -> RT i d v p r -> v (Point d r :+ p)
search r = mconcat . search' r
class (i <= d, Arity d) => Query i d where
search' :: Ord r => Vector d (Range r) -> RT i d v p r -> [v (Point d r :+ p)]
instance (1 <= d, Arity d) => Query 1 d where
search' qr = map unAssoc . GRT.search' r . _unRangeTree
where
r = qr^.element @0
instance ( 1 <= d, i <= d, Query (i-1) d, Arity d
, i ~ 2
) => Query 2 d where
search' qr = concatMap (maybe [] (search' qr) . unAssoc) . GRT.search' r . _unRangeTree
where
r = qr^.element @(i-1)
|
8a3fea9f180ac19e503f33d98f9e15d3eb166da412440c39c4dd4e940b69d634 | kuberlog/daemon-clj | emotion_animation_test.clj | (ns dameon.face.emotion-animation-test.clj
(use clojure.test)
(require [dameon.face.emotion-animation :as subject]
[quil.core :as q]
[quil.middleware :as m]))
(deftest generate-animation-file-paths
(is (= "happy/emotion.png" (:emotion-loop-path (subject/get-full-file-paths "happy"))));param without trailing slash
2nd file . with trailing /
(is (= "happy/emotion_to_neutral.png" (:emotion-to-neutral-path (subject/get-full-file-paths "happy/"))));param without trailing slash
)
(run-tests)
| null | https://raw.githubusercontent.com/kuberlog/daemon-clj/904699d005ea2df3d86426d8aa1d3b030178e683/test/daemon/face/emotion_animation_test.clj | clojure | param without trailing slash
param without trailing slash | (ns dameon.face.emotion-animation-test.clj
(use clojure.test)
(require [dameon.face.emotion-animation :as subject]
[quil.core :as q]
[quil.middleware :as m]))
(deftest generate-animation-file-paths
2nd file . with trailing /
)
(run-tests)
|
be9b58b7269abf63f27d36e11e71c068e360850066b99a83e4b370cf9e444396 | cronokirby/haskell-in-haskell | 0004.hs | -- OUT(24)
main = 1 * 2 * 3 * 4
| null | https://raw.githubusercontent.com/cronokirby/haskell-in-haskell/83cb8114c7a71f2fc530d1865dd22776a3779417/integration_tests/0004.hs | haskell | OUT(24) | main = 1 * 2 * 3 * 4
|
d110d9b3a4eb49d7b430fdec63310d7632643447c4a230b10f7392f7ad678bb6 | processone/tsung | ts_mon_cache.erl | %%% This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
%%% (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%%% GNU General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 , USA .
%%%
%%% In addition, as a special exception, you have the permission to
%%% link the code of this program with any library released under
the EPL license and distribute linked combinations including
the two ; the MPL ( Mozilla Public License ) , which EPL ( Erlang
%%% Public License) is based on, is included in this exception.
%%%-------------------------------------------------------------------
%%% File : ts_session_cache.erl
Author : < >
%%% Description : cache sessions request from ts_config_server
%%%
Created : 2 Dec 2003 by < >
%%%-------------------------------------------------------------------
-module(ts_mon_cache).
-behaviour(gen_server).
%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
%%--------------------------------------------------------------------
%% External exports
-export([start/0, add/1, add_match/2, dump/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3]).
-record(state, {
cache stats
cache transaction stats msgs
cache pages stats msgs
cache requests stats
cache connect stats
match=[], % cache match logs
protocol=[], % cache dump=protocol data
cache sum stats
}).
-include("ts_config.hrl").
%%====================================================================
%% External functions
%%====================================================================
%%--------------------------------------------------------------------
Function : start_link/0
%% Description: Starts the server
%%--------------------------------------------------------------------
start() ->
?LOG("Starting~n",?INFO),
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
%%--------------------------------------------------------------------
%% Function: add/1
%% Description: Add stats data. Will be accumulated sent periodically
%% to ts_mon
%%--------------------------------------------------------------------
add(Data) ->
gen_server:cast(?MODULE, {add, Data}).
add_match(Data::list(),{UserId::integer(),SessionId::integer(),RequestId::integer ( ) ,
%% TimeStamp::tuple(),Transactions::list(),Name::atom()}) -> ok;
%% (Data::list(),{UserId::integer(),SessionId::integer(),RequestId::integer(),
( ) } ) - > ok .
add_match(Data,{UserId,SessionId,RequestId,Tr,Name}) ->
add_match(Data,{UserId,SessionId,RequestId,[],Tr,Name});
add_match(Data,{UserId,SessionId,RequestId,Bin,Tr,Name}) ->
TimeStamp=?TIMESTAMP,
add_match(Data,{UserId,SessionId,RequestId,TimeStamp,Bin,Tr,Name});
add_match(Data=[Head|_],{UserId,SessionId,RequestId,TimeStamp,Bin,Tr,Name}) ->
put(last_match,Head),
gen_server:cast(?MODULE, {add_match, Data, {UserId,SessionId,RequestId,TimeStamp,Bin,Tr,Name}}).
%% @spec dump({Type, Who, What}) -> ok @end
dump({none, _, _}) -> skip;
dump({_Type, Who, What}) ->
gen_server:cast(?MODULE, {dump, Who, ?TIMESTAMP, What}).
%%====================================================================
%% Server functions
%%====================================================================
%%--------------------------------------------------------------------
%% Function: init/1
%% Description: Initiates the server
%% Returns: {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%%--------------------------------------------------------------------
init([]) ->
erlang:start_timer(?CACHE_DUMP_STATS_INTERVAL, self(), dump_stats ),
{ok, #state{sum=dict:new()}}.
%%--------------------------------------------------------------------
Function : handle_call/3
%% Description: Handling call messages
%% Returns: {reply, Reply, State} |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} | (terminate/2 is called)
%% {stop, Reason, State} (terminate/2 is called)
%%--------------------------------------------------------------------
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
%%--------------------------------------------------------------------
%% Function: handle_cast/2
%% Description: Handling cast messages
Returns : { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State} (terminate/2 is called)
%%--------------------------------------------------------------------
handle_cast({add, Data}, State) when is_list(Data) ->
LastState = lists:foldl(fun(NewData,NewState)->
update_stats(NewData,NewState)
end, State, Data),
{noreply, LastState };
handle_cast({add, Data}, State) when is_tuple(Data) ->
{noreply,update_stats(Data, State)};
handle_cast({add_match, Data=[First|_Tail],{UserId,SessionId,RequestId,TimeStamp,Bin,Tr,Name}},
State=#state{stats=List, match=MatchList})->
NewMatchList=lists:append([{UserId,SessionId,RequestId,TimeStamp,First, Bin, Tr,Name}], MatchList),
{noreply, State#state{stats = lists:append(Data, List), match = NewMatchList}};
handle_cast({dump, Who, When, What}, State=#state{protocol=Cache}) ->
Log = io_lib:format("~w;~w;~s~n",[ts_utils:time2sec_hires(When),Who,What]),
{noreply, State#state{protocol=[Log|Cache]}};
handle_cast(_Msg, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
%% Function: handle_info/2
%% Description: Handling all non call/cast messages
Returns : { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State} (terminate/2 is called)
%%--------------------------------------------------------------------
handle_info({timeout, _Ref, dump_stats}, State =#state{protocol=ProtocolData, stats= Stats, match=MatchList}) ->
Fun = fun(Key,Val, Acc) -> [{sum,Key,Val}| Acc] end,
NewStats=dict:fold(Fun, Stats, State#state.sum),
ts_stats_mon:add(NewStats),
ts_stats_mon:add(State#state.requests,request),
ts_stats_mon:add(State#state.connections,connect),
ts_stats_mon:add(State#state.transactions,transaction),
ts_stats_mon:add(State#state.pages,page),
ts_mon:dump({cached, list_to_binary(lists:reverse(ProtocolData))}),
ts_match_logger:add(MatchList),
erlang:start_timer(?CACHE_DUMP_STATS_INTERVAL, self(), dump_stats ),
{noreply, State#state{protocol=[],stats=[],match=[],pages=[],requests=[],transactions=[],connections=[],sum=dict:new()}};
handle_info(_Info, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
%% Function: terminate/2
%% Description: Shutdown the server
%% Returns: any (ignored by gen_server)
%%--------------------------------------------------------------------
terminate(Reason, _State) ->
?LOGF("Die ! (~p)~n",[Reason],?ERR),
ok.
%%--------------------------------------------------------------------
%% Func: code_change/3
%% Purpose: Convert process state when code is changed
%% Returns: {ok, NewState}
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
update_stats({sample, request, Val}, State=#state{requests=L}) ->
State#state{requests=lists:append([Val],L)};
update_stats({sample, page, Val}, State=#state{pages=L}) ->
State#state{pages=lists:append([Val],L)};
update_stats({sample, connect, Val}, State=#state{connections=L}) ->
State#state{connections=lists:append([Val],L)};
update_stats(S={sample, _Type, _}, State=#state{transactions=L}) ->
State#state{transactions=lists:append([S],L)};
update_stats({sum, Type, Val}, State=#state{sum=Sum}) ->
NewSum=dict:update_counter(Type,Val,Sum),
State#state{sum=NewSum};
update_stats({count, Type}, State=#state{sum=Sum}) ->
NewSum=dict:update_counter(Type,1,Sum),
State#state{sum=NewSum};
update_stats(Data, State=#state{stats=L}) when is_tuple(Data)->
State#state{stats=lists:append([Data],L)}.
| null | https://raw.githubusercontent.com/processone/tsung/e9babe2acfb4298e3b51bd56886561b052979884/src/tsung/ts_mon_cache.erl | erlang | This program is free software; you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
In addition, as a special exception, you have the permission to
link the code of this program with any library released under
Public License) is based on, is included in this exception.
-------------------------------------------------------------------
File : ts_session_cache.erl
Description : cache sessions request from ts_config_server
-------------------------------------------------------------------
--------------------------------------------------------------------
Include files
--------------------------------------------------------------------
--------------------------------------------------------------------
External exports
gen_server callbacks
cache match logs
cache dump=protocol data
====================================================================
External functions
====================================================================
--------------------------------------------------------------------
Description: Starts the server
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: add/1
Description: Add stats data. Will be accumulated sent periodically
to ts_mon
--------------------------------------------------------------------
TimeStamp::tuple(),Transactions::list(),Name::atom()}) -> ok;
(Data::list(),{UserId::integer(),SessionId::integer(),RequestId::integer(),
@spec dump({Type, Who, What}) -> ok @end
====================================================================
Server functions
====================================================================
--------------------------------------------------------------------
Function: init/1
Description: Initiates the server
Returns: {ok, State} |
ignore |
{stop, Reason}
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Handling call messages
Returns: {reply, Reply, State} |
{stop, Reason, Reply, State} | (terminate/2 is called)
{stop, Reason, State} (terminate/2 is called)
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: handle_cast/2
Description: Handling cast messages
{stop, Reason, State} (terminate/2 is called)
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: handle_info/2
Description: Handling all non call/cast messages
{stop, Reason, State} (terminate/2 is called)
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: terminate/2
Description: Shutdown the server
Returns: any (ignored by gen_server)
--------------------------------------------------------------------
--------------------------------------------------------------------
Func: code_change/3
Purpose: Convert process state when code is changed
Returns: {ok, NewState}
-------------------------------------------------------------------- | it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 , USA .
the EPL license and distribute linked combinations including
the two ; the MPL ( Mozilla Public License ) , which EPL ( Erlang
Author : < >
Created : 2 Dec 2003 by < >
-module(ts_mon_cache).
-behaviour(gen_server).
-export([start/0, add/1, add_match/2, dump/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3]).
-record(state, {
cache stats
cache transaction stats msgs
cache pages stats msgs
cache requests stats
cache connect stats
cache sum stats
}).
-include("ts_config.hrl").
Function : start_link/0
start() ->
?LOG("Starting~n",?INFO),
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
add(Data) ->
gen_server:cast(?MODULE, {add, Data}).
add_match(Data::list(),{UserId::integer(),SessionId::integer(),RequestId::integer ( ) ,
( ) } ) - > ok .
add_match(Data,{UserId,SessionId,RequestId,Tr,Name}) ->
add_match(Data,{UserId,SessionId,RequestId,[],Tr,Name});
add_match(Data,{UserId,SessionId,RequestId,Bin,Tr,Name}) ->
TimeStamp=?TIMESTAMP,
add_match(Data,{UserId,SessionId,RequestId,TimeStamp,Bin,Tr,Name});
add_match(Data=[Head|_],{UserId,SessionId,RequestId,TimeStamp,Bin,Tr,Name}) ->
put(last_match,Head),
gen_server:cast(?MODULE, {add_match, Data, {UserId,SessionId,RequestId,TimeStamp,Bin,Tr,Name}}).
dump({none, _, _}) -> skip;
dump({_Type, Who, What}) ->
gen_server:cast(?MODULE, {dump, Who, ?TIMESTAMP, What}).
{ ok , State , Timeout } |
init([]) ->
erlang:start_timer(?CACHE_DUMP_STATS_INTERVAL, self(), dump_stats ),
{ok, #state{sum=dict:new()}}.
Function : handle_call/3
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
Returns : { noreply , State } |
{ noreply , State , Timeout } |
handle_cast({add, Data}, State) when is_list(Data) ->
LastState = lists:foldl(fun(NewData,NewState)->
update_stats(NewData,NewState)
end, State, Data),
{noreply, LastState };
handle_cast({add, Data}, State) when is_tuple(Data) ->
{noreply,update_stats(Data, State)};
handle_cast({add_match, Data=[First|_Tail],{UserId,SessionId,RequestId,TimeStamp,Bin,Tr,Name}},
State=#state{stats=List, match=MatchList})->
NewMatchList=lists:append([{UserId,SessionId,RequestId,TimeStamp,First, Bin, Tr,Name}], MatchList),
{noreply, State#state{stats = lists:append(Data, List), match = NewMatchList}};
handle_cast({dump, Who, When, What}, State=#state{protocol=Cache}) ->
Log = io_lib:format("~w;~w;~s~n",[ts_utils:time2sec_hires(When),Who,What]),
{noreply, State#state{protocol=[Log|Cache]}};
handle_cast(_Msg, State) ->
{noreply, State}.
Returns : { noreply , State } |
{ noreply , State , Timeout } |
handle_info({timeout, _Ref, dump_stats}, State =#state{protocol=ProtocolData, stats= Stats, match=MatchList}) ->
Fun = fun(Key,Val, Acc) -> [{sum,Key,Val}| Acc] end,
NewStats=dict:fold(Fun, Stats, State#state.sum),
ts_stats_mon:add(NewStats),
ts_stats_mon:add(State#state.requests,request),
ts_stats_mon:add(State#state.connections,connect),
ts_stats_mon:add(State#state.transactions,transaction),
ts_stats_mon:add(State#state.pages,page),
ts_mon:dump({cached, list_to_binary(lists:reverse(ProtocolData))}),
ts_match_logger:add(MatchList),
erlang:start_timer(?CACHE_DUMP_STATS_INTERVAL, self(), dump_stats ),
{noreply, State#state{protocol=[],stats=[],match=[],pages=[],requests=[],transactions=[],connections=[],sum=dict:new()}};
handle_info(_Info, State) ->
{noreply, State}.
terminate(Reason, _State) ->
?LOGF("Die ! (~p)~n",[Reason],?ERR),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
update_stats({sample, request, Val}, State=#state{requests=L}) ->
State#state{requests=lists:append([Val],L)};
update_stats({sample, page, Val}, State=#state{pages=L}) ->
State#state{pages=lists:append([Val],L)};
update_stats({sample, connect, Val}, State=#state{connections=L}) ->
State#state{connections=lists:append([Val],L)};
update_stats(S={sample, _Type, _}, State=#state{transactions=L}) ->
State#state{transactions=lists:append([S],L)};
update_stats({sum, Type, Val}, State=#state{sum=Sum}) ->
NewSum=dict:update_counter(Type,Val,Sum),
State#state{sum=NewSum};
update_stats({count, Type}, State=#state{sum=Sum}) ->
NewSum=dict:update_counter(Type,1,Sum),
State#state{sum=NewSum};
update_stats(Data, State=#state{stats=L}) when is_tuple(Data)->
State#state{stats=lists:append([Data],L)}.
|
f091d3270955580e08df4829831fec0b2c20b4711706ffdcf72fb0a31ae8516b | gvannest/piscine_OCaml | ribosome.ml | type phosphate = string
type deoxyribose = string
type nucleobase = A | T | C | G | U | None
type nucleotide = {
phosphate : phosphate ;
deoxyribose : deoxyribose ;
nucleobase : nucleobase
}
type helix = nucleotide list
let generate_nucleotide c =
{
phosphate = "phosphate" ;
deoxyribose = "deoxyribose" ;
nucleobase = match c with
| 'A' -> A
| 'T' -> T
| 'C' -> C
| 'G' -> G
| 'U' -> U
| _ -> None
}
let generate_helix n =
if n < 1 then begin print_endline "Error: number of nucleotides must be greater than 0 to generate an helix" ; [] end
else begin
Random.self_init() ;
let rec choice = function
| 0 -> 'A'
| 1 -> 'T'
| 2 -> 'C'
| 3 -> 'G'
| _ -> 'O'
in
let rec gen_helix_aux i (acc: helix) = match i with
| y when y = n -> acc
| _ -> gen_helix_aux (i + 1) ((generate_nucleotide (choice (Random.int 4))) :: acc)
in
gen_helix_aux 0 []
end
type strOption = String of string | None
let extractStrOption value = match value with
| None -> "N/A"
| String str -> str
let nucleobase_str = function
| A -> String "A"
| T -> String "T"
| C -> String "C"
| G -> String "G"
| U -> String "U"
| _ -> None
let helix_to_string (lst: helix) =
let rec loop lst_remaining str = match lst_remaining with
| [] -> str
| h :: t -> begin
let nclbase = nucleobase_str h.nucleobase in
match nclbase with
| None -> loop t str
| _ -> loop t (str ^ (extractStrOption nclbase))
end
in
loop lst ""
let complementary_helix (helix:helix) =
let get_complement = function
| A -> 'T'
| T -> 'A'
| C -> 'G'
| G -> 'C'
| _ -> 'O'
in
let rec loop remaining_helix (comp_helix:helix) = match remaining_helix with
| [] -> comp_helix
| h :: t -> loop t (comp_helix@[generate_nucleotide (get_complement h.nucleobase)])
in
loop helix []
(* ----------------- ex06 ----------------- *)
type rna = nucleobase list
let generate_rna (hlx:helix) =
let compl_helix = complementary_helix hlx in
let rec loop input_compl_helix (rna:rna) = match input_compl_helix with
| [] -> rna
| h :: t when h.nucleobase = T -> loop t (rna@[U])
| h :: t -> loop t (rna@[h.nucleobase])
in loop compl_helix []
let rec print_rna (rna:rna) = match rna with
| [] -> print_char '\n'
| h :: t -> print_string (extractStrOption (nucleobase_str h)) ; print_rna t
(* ----------------- ex07 ----------------- *)
let generate_bases_triplets (rna:rna) =
let rec create_triplets rna_lst output = match rna_lst with
| h :: a :: b :: tail -> create_triplets tail (output @ [(h, a, b)])
| _ -> output
in create_triplets rna []
let print_list_triplets lst =
print_char '[' ;
let rec loop new_lst = match new_lst with
| [] -> print_char ']' ; print_char '\n'
| h :: t -> match h with
| (a, b, c) -> begin
print_char '(' ; print_string (extractStrOption (nucleobase_str a)) ;
print_string ", ";
print_string (extractStrOption (nucleobase_str b)) ;
print_string ", ";
print_string (extractStrOption (nucleobase_str c)) ;
print_string "), ";
loop t
end
in loop lst
type aminoacid = Ala | Arg | Asn | Asp | Cys | Gln | Glu | Gly | His | Ile | Leu | Lys | Met | Phe | Pro | Ser | Thr | Trp | Tyr | Val | Stop
type protein = aminoacid list
let string_of_protein (protein:protein) =
let string_of_aminoacid = function
| Ala -> "Alanine"
| Arg -> "Arginine"
| Asn -> "Asparagine"
| Asp -> "Aspatique"
| Cys -> "Cysteine"
| Gln -> "Glutamine"
| Glu -> "Glutamique"
| Gly -> "Glycine"
| His -> "Histidine"
| Ile -> "Isoleucine"
| Leu -> "Leucine"
| Lys -> "Lysine"
| Met -> "Methionine"
| Phe -> "Phenylalanine"
| Pro -> "Proline"
| Ser -> "Serine"
| Thr -> "Threonine"
| Trp -> "Tryptophane"
| Tyr -> "Tyrosine"
| Val -> "Valine"
| Stop -> "Stop"
in
let rec loop protein_loop output = match protein_loop with
| [] -> output
| h :: t -> if t <> [] then begin loop t (output ^ (string_of_aminoacid h) ^ ", ") end else begin output ^ (string_of_aminoacid h) end
in
loop protein ""
let decode_arn (rna:rna) =
let triplets = generate_bases_triplets rna in
let rec decode_aux rna_tripl_lst (protein:protein) = match rna_tripl_lst with
| (U,A,A) :: (U,A,G) :: (U,G,A) :: tail -> (protein@[Stop])
| (G,C,A) :: (G,C,C) :: (G,C,G) :: (G,C,U) :: tail -> decode_aux tail (protein@[Ala])
| (A,G,A) :: (A,G,G) :: (C,G,A) :: (C,G,C) :: (C,G,G) :: (C,G,U) :: tail -> decode_aux tail (protein@[Arg])
| (A,A,C) :: (A,A,U) :: tail -> decode_aux tail (protein@[Asn])
| (G,A,C) :: (G,A,U) :: tail -> decode_aux tail (protein@[Asp])
| (U,G,C) :: (U,G,U) :: tail -> decode_aux tail (protein@[Cys])
| (C,A,A) :: (C,A,G) :: tail -> decode_aux tail (protein@[Gln])
| (G,A,A) :: (G,A,G) :: tail -> decode_aux tail (protein@[Glu])
| (G,G,A) :: (G,G,C) :: (G,G,G) :: (G,G,U) :: tail -> decode_aux tail (protein@[Gly])
| (C,A,C) :: (C,A,U) :: tail -> decode_aux tail (protein@[His])
| (A,U,A) :: (A,U,C) :: (A,U,U) :: tail -> decode_aux tail (protein@[Ile])
| (C,U,A) :: (C,U,C) :: (C,U,G) :: (C,U,U) :: (U,U,A) :: (U,U,G) :: tail -> decode_aux tail (protein@[Leu])
| (A,A,A) :: (A,A,G) :: tail -> decode_aux tail (protein@[Lys])
| (A,U,G) :: tail -> decode_aux tail (protein@[Met])
| (U,U,C) :: (U,U,U) :: tail -> decode_aux tail (protein@[Phe])
| (C,C,C) :: (C,C,A) :: (C,C,G) :: (C,C,U) :: tail -> decode_aux tail (protein@[Pro])
| (U,C,A) :: (U,C,C) :: (U,C,G) :: (U,C,U) :: (A,G,U) :: (A,G,C) :: tail -> decode_aux tail (protein@[Ser])
| (A,C,A) :: (A,C,C) :: (A,C,G) :: (A,C,U) :: tail -> decode_aux tail (protein@[Thr])
| (U,G,G) :: tail -> decode_aux tail (protein@[Trp])
| (U,A,C) :: (U,A,U) :: tail -> decode_aux tail (protein@[Tyr])
| (G,U,A) :: (G,U,C) :: (G,U,G) :: (G,U,U) :: tail -> decode_aux tail (protein@[Val])
| h :: tail -> decode_aux tail protein
| [] -> protein
in decode_aux triplets []
let () =
let (rna1:rna) = [G;C;A;G;C;C;G;C;G;G;C;U;G;A;C;G;A;U;U;A;A;U;A;G;U;G;A] in
let (rna2:rna) = [G;G;A;G;G;C;G;G;G;G;G;U;A;U;A;A;U;C;A;U;U;U;C;A;U;C;C;U;C;G;U;C;U;A;G;U;A;G;C;U;A;A;U;A;G;U;G;A] in
let (rna3:rna) = [G;U;A;G;U;C;G;U;G;G;U;U;U;A;A;U;A;G;U;G;A] in
print_list_triplets (generate_bases_triplets rna1);
print_endline (string_of_protein (decode_arn rna1)) ;
print_endline "--------------" ;
print_list_triplets (generate_bases_triplets rna2);
print_endline (string_of_protein (decode_arn rna2)) ;
print_endline "--------------" ;
print_list_triplets (generate_bases_triplets rna3);
print_endline (string_of_protein (decode_arn rna3)) | null | https://raw.githubusercontent.com/gvannest/piscine_OCaml/2533c6152cfb46c637d48a6d0718f7c7262b3ba6/d02/ex07/ribosome.ml | ocaml | ----------------- ex06 -----------------
----------------- ex07 ----------------- | type phosphate = string
type deoxyribose = string
type nucleobase = A | T | C | G | U | None
type nucleotide = {
phosphate : phosphate ;
deoxyribose : deoxyribose ;
nucleobase : nucleobase
}
type helix = nucleotide list
let generate_nucleotide c =
{
phosphate = "phosphate" ;
deoxyribose = "deoxyribose" ;
nucleobase = match c with
| 'A' -> A
| 'T' -> T
| 'C' -> C
| 'G' -> G
| 'U' -> U
| _ -> None
}
let generate_helix n =
if n < 1 then begin print_endline "Error: number of nucleotides must be greater than 0 to generate an helix" ; [] end
else begin
Random.self_init() ;
let rec choice = function
| 0 -> 'A'
| 1 -> 'T'
| 2 -> 'C'
| 3 -> 'G'
| _ -> 'O'
in
let rec gen_helix_aux i (acc: helix) = match i with
| y when y = n -> acc
| _ -> gen_helix_aux (i + 1) ((generate_nucleotide (choice (Random.int 4))) :: acc)
in
gen_helix_aux 0 []
end
type strOption = String of string | None
let extractStrOption value = match value with
| None -> "N/A"
| String str -> str
let nucleobase_str = function
| A -> String "A"
| T -> String "T"
| C -> String "C"
| G -> String "G"
| U -> String "U"
| _ -> None
let helix_to_string (lst: helix) =
let rec loop lst_remaining str = match lst_remaining with
| [] -> str
| h :: t -> begin
let nclbase = nucleobase_str h.nucleobase in
match nclbase with
| None -> loop t str
| _ -> loop t (str ^ (extractStrOption nclbase))
end
in
loop lst ""
let complementary_helix (helix:helix) =
let get_complement = function
| A -> 'T'
| T -> 'A'
| C -> 'G'
| G -> 'C'
| _ -> 'O'
in
let rec loop remaining_helix (comp_helix:helix) = match remaining_helix with
| [] -> comp_helix
| h :: t -> loop t (comp_helix@[generate_nucleotide (get_complement h.nucleobase)])
in
loop helix []
type rna = nucleobase list
let generate_rna (hlx:helix) =
let compl_helix = complementary_helix hlx in
let rec loop input_compl_helix (rna:rna) = match input_compl_helix with
| [] -> rna
| h :: t when h.nucleobase = T -> loop t (rna@[U])
| h :: t -> loop t (rna@[h.nucleobase])
in loop compl_helix []
let rec print_rna (rna:rna) = match rna with
| [] -> print_char '\n'
| h :: t -> print_string (extractStrOption (nucleobase_str h)) ; print_rna t
let generate_bases_triplets (rna:rna) =
let rec create_triplets rna_lst output = match rna_lst with
| h :: a :: b :: tail -> create_triplets tail (output @ [(h, a, b)])
| _ -> output
in create_triplets rna []
let print_list_triplets lst =
print_char '[' ;
let rec loop new_lst = match new_lst with
| [] -> print_char ']' ; print_char '\n'
| h :: t -> match h with
| (a, b, c) -> begin
print_char '(' ; print_string (extractStrOption (nucleobase_str a)) ;
print_string ", ";
print_string (extractStrOption (nucleobase_str b)) ;
print_string ", ";
print_string (extractStrOption (nucleobase_str c)) ;
print_string "), ";
loop t
end
in loop lst
type aminoacid = Ala | Arg | Asn | Asp | Cys | Gln | Glu | Gly | His | Ile | Leu | Lys | Met | Phe | Pro | Ser | Thr | Trp | Tyr | Val | Stop
type protein = aminoacid list
let string_of_protein (protein:protein) =
let string_of_aminoacid = function
| Ala -> "Alanine"
| Arg -> "Arginine"
| Asn -> "Asparagine"
| Asp -> "Aspatique"
| Cys -> "Cysteine"
| Gln -> "Glutamine"
| Glu -> "Glutamique"
| Gly -> "Glycine"
| His -> "Histidine"
| Ile -> "Isoleucine"
| Leu -> "Leucine"
| Lys -> "Lysine"
| Met -> "Methionine"
| Phe -> "Phenylalanine"
| Pro -> "Proline"
| Ser -> "Serine"
| Thr -> "Threonine"
| Trp -> "Tryptophane"
| Tyr -> "Tyrosine"
| Val -> "Valine"
| Stop -> "Stop"
in
let rec loop protein_loop output = match protein_loop with
| [] -> output
| h :: t -> if t <> [] then begin loop t (output ^ (string_of_aminoacid h) ^ ", ") end else begin output ^ (string_of_aminoacid h) end
in
loop protein ""
let decode_arn (rna:rna) =
let triplets = generate_bases_triplets rna in
let rec decode_aux rna_tripl_lst (protein:protein) = match rna_tripl_lst with
| (U,A,A) :: (U,A,G) :: (U,G,A) :: tail -> (protein@[Stop])
| (G,C,A) :: (G,C,C) :: (G,C,G) :: (G,C,U) :: tail -> decode_aux tail (protein@[Ala])
| (A,G,A) :: (A,G,G) :: (C,G,A) :: (C,G,C) :: (C,G,G) :: (C,G,U) :: tail -> decode_aux tail (protein@[Arg])
| (A,A,C) :: (A,A,U) :: tail -> decode_aux tail (protein@[Asn])
| (G,A,C) :: (G,A,U) :: tail -> decode_aux tail (protein@[Asp])
| (U,G,C) :: (U,G,U) :: tail -> decode_aux tail (protein@[Cys])
| (C,A,A) :: (C,A,G) :: tail -> decode_aux tail (protein@[Gln])
| (G,A,A) :: (G,A,G) :: tail -> decode_aux tail (protein@[Glu])
| (G,G,A) :: (G,G,C) :: (G,G,G) :: (G,G,U) :: tail -> decode_aux tail (protein@[Gly])
| (C,A,C) :: (C,A,U) :: tail -> decode_aux tail (protein@[His])
| (A,U,A) :: (A,U,C) :: (A,U,U) :: tail -> decode_aux tail (protein@[Ile])
| (C,U,A) :: (C,U,C) :: (C,U,G) :: (C,U,U) :: (U,U,A) :: (U,U,G) :: tail -> decode_aux tail (protein@[Leu])
| (A,A,A) :: (A,A,G) :: tail -> decode_aux tail (protein@[Lys])
| (A,U,G) :: tail -> decode_aux tail (protein@[Met])
| (U,U,C) :: (U,U,U) :: tail -> decode_aux tail (protein@[Phe])
| (C,C,C) :: (C,C,A) :: (C,C,G) :: (C,C,U) :: tail -> decode_aux tail (protein@[Pro])
| (U,C,A) :: (U,C,C) :: (U,C,G) :: (U,C,U) :: (A,G,U) :: (A,G,C) :: tail -> decode_aux tail (protein@[Ser])
| (A,C,A) :: (A,C,C) :: (A,C,G) :: (A,C,U) :: tail -> decode_aux tail (protein@[Thr])
| (U,G,G) :: tail -> decode_aux tail (protein@[Trp])
| (U,A,C) :: (U,A,U) :: tail -> decode_aux tail (protein@[Tyr])
| (G,U,A) :: (G,U,C) :: (G,U,G) :: (G,U,U) :: tail -> decode_aux tail (protein@[Val])
| h :: tail -> decode_aux tail protein
| [] -> protein
in decode_aux triplets []
let () =
let (rna1:rna) = [G;C;A;G;C;C;G;C;G;G;C;U;G;A;C;G;A;U;U;A;A;U;A;G;U;G;A] in
let (rna2:rna) = [G;G;A;G;G;C;G;G;G;G;G;U;A;U;A;A;U;C;A;U;U;U;C;A;U;C;C;U;C;G;U;C;U;A;G;U;A;G;C;U;A;A;U;A;G;U;G;A] in
let (rna3:rna) = [G;U;A;G;U;C;G;U;G;G;U;U;U;A;A;U;A;G;U;G;A] in
print_list_triplets (generate_bases_triplets rna1);
print_endline (string_of_protein (decode_arn rna1)) ;
print_endline "--------------" ;
print_list_triplets (generate_bases_triplets rna2);
print_endline (string_of_protein (decode_arn rna2)) ;
print_endline "--------------" ;
print_list_triplets (generate_bases_triplets rna3);
print_endline (string_of_protein (decode_arn rna3)) |
ada73b7380860d439d08f1866d391f850cc100191dfdc5586bc0b24982b30bd0 | reasonml/reason | migrate_parsetree_413_414_migrate.ml | open Stdlib0
module From = Ast_413
module To = Ast_414
let rec copy_out_type_extension :
Ast_413.Outcometree.out_type_extension ->
Ast_414.Outcometree.out_type_extension
=
fun
{ Ast_413.Outcometree.otyext_name = otyext_name;
Ast_413.Outcometree.otyext_params = otyext_params;
Ast_413.Outcometree.otyext_constructors = otyext_constructors;
Ast_413.Outcometree.otyext_private = otyext_private }
->
{
Ast_414.Outcometree.otyext_name = otyext_name;
Ast_414.Outcometree.otyext_params =
(List.map (fun x -> x) otyext_params);
Ast_414.Outcometree.otyext_constructors =
(List.map
(fun x ->
let (x0, x1, x2) = x in
let x1 = (List.map copy_out_type x1) in
let x2 = (Option.map copy_out_type x2) in
Ast_414.Outcometree.{ ocstr_name = x0; ocstr_args = x1; ocstr_return_type = x2 })
otyext_constructors);
Ast_414.Outcometree.otyext_private = (copy_private_flag otyext_private)
}
and copy_out_phrase :
Ast_413.Outcometree.out_phrase -> Ast_414.Outcometree.out_phrase =
function
| Ast_413.Outcometree.Ophr_eval (x0, x1) ->
Ast_414.Outcometree.Ophr_eval ((copy_out_value x0), (copy_out_type x1))
| Ast_413.Outcometree.Ophr_signature x0 ->
Ast_414.Outcometree.Ophr_signature
(List.map
(fun x ->
let (x0, x1) = x in
((copy_out_sig_item x0), (Option.map copy_out_value x1))) x0)
| Ast_413.Outcometree.Ophr_exception x0 ->
Ast_414.Outcometree.Ophr_exception
(let (x0, x1) = x0 in (x0, (copy_out_value x1)))
and copy_out_sig_item :
Ast_413.Outcometree.out_sig_item -> Ast_414.Outcometree.out_sig_item =
function
| Ast_413.Outcometree.Osig_class (x0, x1, x2, x3, x4) ->
Ast_414.Outcometree.Osig_class
(x0, x1, (List.map copy_out_type_param x2), (copy_out_class_type x3),
(copy_out_rec_status x4))
| Ast_413.Outcometree.Osig_class_type (x0, x1, x2, x3, x4) ->
Ast_414.Outcometree.Osig_class_type
(x0, x1, (List.map copy_out_type_param x2), (copy_out_class_type x3),
(copy_out_rec_status x4))
| Ast_413.Outcometree.Osig_typext (x0, x1) ->
Ast_414.Outcometree.Osig_typext
((copy_out_extension_constructor x0), (copy_out_ext_status x1))
| Ast_413.Outcometree.Osig_modtype (x0, x1) ->
Ast_414.Outcometree.Osig_modtype (x0, (copy_out_module_type x1))
| Ast_413.Outcometree.Osig_module (x0, x1, x2) ->
Ast_414.Outcometree.Osig_module
(x0, (copy_out_module_type x1), (copy_out_rec_status x2))
| Ast_413.Outcometree.Osig_type (x0, x1) ->
Ast_414.Outcometree.Osig_type
((copy_out_type_decl x0), (copy_out_rec_status x1))
| Ast_413.Outcometree.Osig_value x0 ->
Ast_414.Outcometree.Osig_value (copy_out_val_decl x0)
| Ast_413.Outcometree.Osig_ellipsis -> Ast_414.Outcometree.Osig_ellipsis
and copy_out_val_decl :
Ast_413.Outcometree.out_val_decl -> Ast_414.Outcometree.out_val_decl =
fun
{ Ast_413.Outcometree.oval_name = oval_name;
Ast_413.Outcometree.oval_type = oval_type;
Ast_413.Outcometree.oval_prims = oval_prims;
Ast_413.Outcometree.oval_attributes = oval_attributes }
->
{
Ast_414.Outcometree.oval_name = oval_name;
Ast_414.Outcometree.oval_type = (copy_out_type oval_type);
Ast_414.Outcometree.oval_prims = (List.map (fun x -> x) oval_prims);
Ast_414.Outcometree.oval_attributes =
(List.map copy_out_attribute oval_attributes)
}
and copy_out_type_decl :
Ast_413.Outcometree.out_type_decl -> Ast_414.Outcometree.out_type_decl =
fun
{ Ast_413.Outcometree.otype_name = otype_name;
Ast_413.Outcometree.otype_params = otype_params;
Ast_413.Outcometree.otype_type = otype_type;
Ast_413.Outcometree.otype_private = otype_private;
Ast_413.Outcometree.otype_immediate = otype_immediate;
Ast_413.Outcometree.otype_unboxed = otype_unboxed;
Ast_413.Outcometree.otype_cstrs = otype_cstrs }
->
{
Ast_414.Outcometree.otype_name = otype_name;
Ast_414.Outcometree.otype_params =
(List.map copy_out_type_param otype_params);
Ast_414.Outcometree.otype_type = (copy_out_type otype_type);
Ast_414.Outcometree.otype_private = (copy_private_flag otype_private);
Ast_414.Outcometree.otype_immediate =
(copy_Type_immediacy_t otype_immediate);
Ast_414.Outcometree.otype_unboxed = otype_unboxed;
Ast_414.Outcometree.otype_cstrs =
(List.map
(fun x ->
let (x0, x1) = x in ((copy_out_type x0), (copy_out_type x1)))
otype_cstrs)
}
and copy_Type_immediacy_t :
Ast_413.Type_immediacy.t -> Ast_414.Type_immediacy.t =
function
| Ast_413.Type_immediacy.Unknown -> Ast_414.Type_immediacy.Unknown
| Ast_413.Type_immediacy.Always -> Ast_414.Type_immediacy.Always
| Ast_413.Type_immediacy.Always_on_64bits ->
Ast_414.Type_immediacy.Always_on_64bits
and copy_out_module_type :
Ast_413.Outcometree.out_module_type -> Ast_414.Outcometree.out_module_type
=
function
| Ast_413.Outcometree.Omty_abstract -> Ast_414.Outcometree.Omty_abstract
| Ast_413.Outcometree.Omty_functor (x0, x1) ->
Ast_414.Outcometree.Omty_functor
((Option.map
(fun x ->
let (x0, x1) = x in
((Option.map (fun x -> x) x0), (copy_out_module_type x1))) x0),
(copy_out_module_type x1))
| Ast_413.Outcometree.Omty_ident x0 ->
Ast_414.Outcometree.Omty_ident (copy_out_ident x0)
| Ast_413.Outcometree.Omty_signature x0 ->
Ast_414.Outcometree.Omty_signature (List.map copy_out_sig_item x0)
| Ast_413.Outcometree.Omty_alias x0 ->
Ast_414.Outcometree.Omty_alias (copy_out_ident x0)
and copy_out_ext_status :
Ast_413.Outcometree.out_ext_status -> Ast_414.Outcometree.out_ext_status =
function
| Ast_413.Outcometree.Oext_first -> Ast_414.Outcometree.Oext_first
| Ast_413.Outcometree.Oext_next -> Ast_414.Outcometree.Oext_next
| Ast_413.Outcometree.Oext_exception -> Ast_414.Outcometree.Oext_exception
and copy_out_extension_constructor :
Ast_413.Outcometree.out_extension_constructor ->
Ast_414.Outcometree.out_extension_constructor
=
fun
{ Ast_413.Outcometree.oext_name = oext_name;
Ast_413.Outcometree.oext_type_name = oext_type_name;
Ast_413.Outcometree.oext_type_params = oext_type_params;
Ast_413.Outcometree.oext_args = oext_args;
Ast_413.Outcometree.oext_ret_type = oext_ret_type;
Ast_413.Outcometree.oext_private = oext_private }
->
{
Ast_414.Outcometree.oext_name = oext_name;
Ast_414.Outcometree.oext_type_name = oext_type_name;
Ast_414.Outcometree.oext_type_params =
(List.map (fun x -> x) oext_type_params);
Ast_414.Outcometree.oext_args = (List.map copy_out_type oext_args);
Ast_414.Outcometree.oext_ret_type =
(Option.map copy_out_type oext_ret_type);
Ast_414.Outcometree.oext_private = (copy_private_flag oext_private)
}
and copy_out_rec_status :
Ast_413.Outcometree.out_rec_status -> Ast_414.Outcometree.out_rec_status =
function
| Ast_413.Outcometree.Orec_not -> Ast_414.Outcometree.Orec_not
| Ast_413.Outcometree.Orec_first -> Ast_414.Outcometree.Orec_first
| Ast_413.Outcometree.Orec_next -> Ast_414.Outcometree.Orec_next
and copy_out_class_type :
Ast_413.Outcometree.out_class_type -> Ast_414.Outcometree.out_class_type =
function
| Ast_413.Outcometree.Octy_constr (x0, x1) ->
Ast_414.Outcometree.Octy_constr
((copy_out_ident x0), (List.map copy_out_type x1))
| Ast_413.Outcometree.Octy_arrow (x0, x1, x2) ->
Ast_414.Outcometree.Octy_arrow
(x0, (copy_out_type x1), (copy_out_class_type x2))
| Ast_413.Outcometree.Octy_signature (x0, x1) ->
Ast_414.Outcometree.Octy_signature
((Option.map copy_out_type x0),
(List.map copy_out_class_sig_item x1))
and copy_out_class_sig_item :
Ast_413.Outcometree.out_class_sig_item ->
Ast_414.Outcometree.out_class_sig_item
=
function
| Ast_413.Outcometree.Ocsg_constraint (x0, x1) ->
Ast_414.Outcometree.Ocsg_constraint
((copy_out_type x0), (copy_out_type x1))
| Ast_413.Outcometree.Ocsg_method (x0, x1, x2, x3) ->
Ast_414.Outcometree.Ocsg_method (x0, x1, x2, (copy_out_type x3))
| Ast_413.Outcometree.Ocsg_value (x0, x1, x2, x3) ->
Ast_414.Outcometree.Ocsg_value (x0, x1, x2, (copy_out_type x3))
and copy_out_type_param :
Ast_413.Outcometree.out_type_param -> Ast_414.Outcometree.out_type_param =
fun x ->
let (x0, x1) = x in
(x0, (let (x0, x1) = x1 in ((copy_variance x0), (copy_injectivity x1))))
and copy_out_type :
Ast_413.Outcometree.out_type -> Ast_414.Outcometree.out_type =
function
| Ast_413.Outcometree.Otyp_abstract -> Ast_414.Outcometree.Otyp_abstract
| Ast_413.Outcometree.Otyp_open -> Ast_414.Outcometree.Otyp_open
| Ast_413.Outcometree.Otyp_alias (x0, x1) ->
Ast_414.Outcometree.Otyp_alias ((copy_out_type x0), x1)
| Ast_413.Outcometree.Otyp_arrow (x0, x1, x2) ->
Ast_414.Outcometree.Otyp_arrow
(x0, (copy_out_type x1), (copy_out_type x2))
| Ast_413.Outcometree.Otyp_class (x0, x1, x2) ->
Ast_414.Outcometree.Otyp_class
(x0, (copy_out_ident x1), (List.map copy_out_type x2))
| Ast_413.Outcometree.Otyp_constr (x0, x1) ->
Ast_414.Outcometree.Otyp_constr
((copy_out_ident x0), (List.map copy_out_type x1))
| Ast_413.Outcometree.Otyp_manifest (x0, x1) ->
Ast_414.Outcometree.Otyp_manifest
((copy_out_type x0), (copy_out_type x1))
| Ast_413.Outcometree.Otyp_object (x0, x1) ->
Ast_414.Outcometree.Otyp_object
((List.map (fun x -> let (x0, x1) = x in (x0, (copy_out_type x1))) x0),
(Option.map (fun x -> x) x1))
| Ast_413.Outcometree.Otyp_record x0 ->
Ast_414.Outcometree.Otyp_record
(List.map
(fun x -> let (x0, x1, x2) = x in (x0, x1, (copy_out_type x2))) x0)
| Ast_413.Outcometree.Otyp_stuff x0 -> Ast_414.Outcometree.Otyp_stuff x0
| Ast_413.Outcometree.Otyp_sum x0 ->
Ast_414.Outcometree.Otyp_sum
(List.map
(fun x ->
let (x0, x1, x2) = x in
let x1 = (List.map copy_out_type x1) in
let x2 = (Option.map copy_out_type x2) in
Ast_414.Outcometree.{ ocstr_name = x0; ocstr_args = x1; ocstr_return_type = x2 })
x0)
| Ast_413.Outcometree.Otyp_tuple x0 ->
Ast_414.Outcometree.Otyp_tuple (List.map copy_out_type x0)
| Ast_413.Outcometree.Otyp_var (x0, x1) ->
Ast_414.Outcometree.Otyp_var (x0, x1)
| Ast_413.Outcometree.Otyp_variant (x0, x1, x2, x3) ->
Ast_414.Outcometree.Otyp_variant
(x0, (copy_out_variant x1), x2,
(Option.map (fun x -> List.map (fun x -> x) x) x3))
| Ast_413.Outcometree.Otyp_poly (x0, x1) ->
Ast_414.Outcometree.Otyp_poly
((List.map (fun x -> x) x0), (copy_out_type x1))
| Ast_413.Outcometree.Otyp_module (x0, x1) ->
Ast_414.Outcometree.Otyp_module
((copy_out_ident x0), (List.map (fun (x, y) -> x, copy_out_type y) x1))
| Ast_413.Outcometree.Otyp_attribute (x0, x1) ->
Ast_414.Outcometree.Otyp_attribute
((copy_out_type x0), (copy_out_attribute x1))
and copy_out_attribute :
Ast_413.Outcometree.out_attribute -> Ast_414.Outcometree.out_attribute =
fun { Ast_413.Outcometree.oattr_name = oattr_name } ->
{ Ast_414.Outcometree.oattr_name = oattr_name }
and copy_out_variant :
Ast_413.Outcometree.out_variant -> Ast_414.Outcometree.out_variant =
function
| Ast_413.Outcometree.Ovar_fields x0 ->
Ast_414.Outcometree.Ovar_fields
(List.map
(fun x ->
let (x0, x1, x2) = x in (x0, x1, (List.map copy_out_type x2)))
x0)
| Ast_413.Outcometree.Ovar_typ x0 ->
Ast_414.Outcometree.Ovar_typ (copy_out_type x0)
and copy_out_value :
Ast_413.Outcometree.out_value -> Ast_414.Outcometree.out_value =
function
| Ast_413.Outcometree.Oval_array x0 ->
Ast_414.Outcometree.Oval_array (List.map copy_out_value x0)
| Ast_413.Outcometree.Oval_char x0 -> Ast_414.Outcometree.Oval_char x0
| Ast_413.Outcometree.Oval_constr (x0, x1) ->
Ast_414.Outcometree.Oval_constr
((copy_out_ident x0), (List.map copy_out_value x1))
| Ast_413.Outcometree.Oval_ellipsis -> Ast_414.Outcometree.Oval_ellipsis
| Ast_413.Outcometree.Oval_float x0 -> Ast_414.Outcometree.Oval_float x0
| Ast_413.Outcometree.Oval_int x0 -> Ast_414.Outcometree.Oval_int x0
| Ast_413.Outcometree.Oval_int32 x0 -> Ast_414.Outcometree.Oval_int32 x0
| Ast_413.Outcometree.Oval_int64 x0 -> Ast_414.Outcometree.Oval_int64 x0
| Ast_413.Outcometree.Oval_nativeint x0 ->
Ast_414.Outcometree.Oval_nativeint x0
| Ast_413.Outcometree.Oval_list x0 ->
Ast_414.Outcometree.Oval_list (List.map copy_out_value x0)
| Ast_413.Outcometree.Oval_printer x0 ->
Ast_414.Outcometree.Oval_printer x0
| Ast_413.Outcometree.Oval_record x0 ->
Ast_414.Outcometree.Oval_record
(List.map
(fun x ->
let (x0, x1) = x in ((copy_out_ident x0), (copy_out_value x1)))
x0)
| Ast_413.Outcometree.Oval_string (x0, x1, x2) ->
Ast_414.Outcometree.Oval_string (x0, x1, (copy_out_string x2))
| Ast_413.Outcometree.Oval_stuff x0 -> Ast_414.Outcometree.Oval_stuff x0
| Ast_413.Outcometree.Oval_tuple x0 ->
Ast_414.Outcometree.Oval_tuple (List.map copy_out_value x0)
| Ast_413.Outcometree.Oval_variant (x0, x1) ->
Ast_414.Outcometree.Oval_variant (x0, (Option.map copy_out_value x1))
and copy_out_string :
Ast_413.Outcometree.out_string -> Ast_414.Outcometree.out_string =
function
| Ast_413.Outcometree.Ostr_string -> Ast_414.Outcometree.Ostr_string
| Ast_413.Outcometree.Ostr_bytes -> Ast_414.Outcometree.Ostr_bytes
and copy_out_ident :
Ast_413.Outcometree.out_ident -> Ast_414.Outcometree.out_ident =
function
| Ast_413.Outcometree.Oide_apply (x0, x1) ->
Ast_414.Outcometree.Oide_apply
((copy_out_ident x0), (copy_out_ident x1))
| Ast_413.Outcometree.Oide_dot (x0, x1) ->
Ast_414.Outcometree.Oide_dot ((copy_out_ident x0), x1)
| Ast_413.Outcometree.Oide_ident x0 ->
Ast_414.Outcometree.Oide_ident (copy_out_name x0)
and copy_out_name :
Ast_413.Outcometree.out_name -> Ast_414.Outcometree.out_name =
fun { Ast_413.Outcometree.printed_name = printed_name } ->
{ Ast_414.Outcometree.printed_name = printed_name }
and copy_toplevel_phrase :
Ast_413.Parsetree.toplevel_phrase -> Ast_414.Parsetree.toplevel_phrase =
function
| Ast_413.Parsetree.Ptop_def x0 ->
Ast_414.Parsetree.Ptop_def (copy_structure x0)
| Ast_413.Parsetree.Ptop_dir x0 ->
Ast_414.Parsetree.Ptop_dir (copy_toplevel_directive x0)
and copy_toplevel_directive :
Ast_413.Parsetree.toplevel_directive ->
Ast_414.Parsetree.toplevel_directive
=
fun
{ Ast_413.Parsetree.pdir_name = pdir_name;
Ast_413.Parsetree.pdir_arg = pdir_arg;
Ast_413.Parsetree.pdir_loc = pdir_loc }
->
{
Ast_414.Parsetree.pdir_name = (copy_loc (fun x -> x) pdir_name);
Ast_414.Parsetree.pdir_arg =
(Option.map copy_directive_argument pdir_arg);
Ast_414.Parsetree.pdir_loc = (copy_location pdir_loc)
}
and copy_directive_argument :
Ast_413.Parsetree.directive_argument ->
Ast_414.Parsetree.directive_argument
=
fun
{ Ast_413.Parsetree.pdira_desc = pdira_desc;
Ast_413.Parsetree.pdira_loc = pdira_loc }
->
{
Ast_414.Parsetree.pdira_desc =
(copy_directive_argument_desc pdira_desc);
Ast_414.Parsetree.pdira_loc = (copy_location pdira_loc)
}
and copy_directive_argument_desc :
Ast_413.Parsetree.directive_argument_desc ->
Ast_414.Parsetree.directive_argument_desc
=
function
| Ast_413.Parsetree.Pdir_string x0 -> Ast_414.Parsetree.Pdir_string x0
| Ast_413.Parsetree.Pdir_int (x0, x1) ->
Ast_414.Parsetree.Pdir_int (x0, (Option.map (fun x -> x) x1))
| Ast_413.Parsetree.Pdir_ident x0 ->
Ast_414.Parsetree.Pdir_ident (copy_Longident_t x0)
| Ast_413.Parsetree.Pdir_bool x0 -> Ast_414.Parsetree.Pdir_bool x0
and copy_expression :
Ast_413.Parsetree.expression -> Ast_414.Parsetree.expression =
fun
{ Ast_413.Parsetree.pexp_desc = pexp_desc;
Ast_413.Parsetree.pexp_loc = pexp_loc;
Ast_413.Parsetree.pexp_loc_stack = pexp_loc_stack;
Ast_413.Parsetree.pexp_attributes = pexp_attributes }
->
{
Ast_414.Parsetree.pexp_desc = (copy_expression_desc pexp_desc);
Ast_414.Parsetree.pexp_loc = (copy_location pexp_loc);
Ast_414.Parsetree.pexp_loc_stack = (copy_location_stack pexp_loc_stack);
Ast_414.Parsetree.pexp_attributes = (copy_attributes pexp_attributes)
}
and copy_expression_desc :
Ast_413.Parsetree.expression_desc -> Ast_414.Parsetree.expression_desc =
function
| Ast_413.Parsetree.Pexp_ident x0 ->
Ast_414.Parsetree.Pexp_ident (copy_loc copy_Longident_t x0)
| Ast_413.Parsetree.Pexp_constant x0 ->
Ast_414.Parsetree.Pexp_constant (copy_constant x0)
| Ast_413.Parsetree.Pexp_let (x0, x1, x2) ->
Ast_414.Parsetree.Pexp_let
((copy_rec_flag x0), (List.map copy_value_binding x1),
(copy_expression x2))
| Ast_413.Parsetree.Pexp_function x0 ->
Ast_414.Parsetree.Pexp_function (List.map copy_case x0)
| Ast_413.Parsetree.Pexp_fun (x0, x1, x2, x3) ->
Ast_414.Parsetree.Pexp_fun
((copy_arg_label x0), (Option.map copy_expression x1),
(copy_pattern x2), (copy_expression x3))
| Ast_413.Parsetree.Pexp_apply (x0, x1) ->
Ast_414.Parsetree.Pexp_apply
((copy_expression x0),
(List.map
(fun x ->
let (x0, x1) = x in
((copy_arg_label x0), (copy_expression x1))) x1))
| Ast_413.Parsetree.Pexp_match (x0, x1) ->
Ast_414.Parsetree.Pexp_match
((copy_expression x0), (List.map copy_case x1))
| Ast_413.Parsetree.Pexp_try (x0, x1) ->
Ast_414.Parsetree.Pexp_try
((copy_expression x0), (List.map copy_case x1))
| Ast_413.Parsetree.Pexp_tuple x0 ->
Ast_414.Parsetree.Pexp_tuple (List.map copy_expression x0)
| Ast_413.Parsetree.Pexp_construct (x0, x1) ->
Ast_414.Parsetree.Pexp_construct
((copy_loc copy_Longident_t x0), (Option.map copy_expression x1))
| Ast_413.Parsetree.Pexp_variant (x0, x1) ->
Ast_414.Parsetree.Pexp_variant
((copy_label x0), (Option.map copy_expression x1))
| Ast_413.Parsetree.Pexp_record (x0, x1) ->
Ast_414.Parsetree.Pexp_record
((List.map
(fun x ->
let (x0, x1) = x in
((copy_loc copy_Longident_t x0), (copy_expression x1))) x0),
(Option.map copy_expression x1))
| Ast_413.Parsetree.Pexp_field (x0, x1) ->
Ast_414.Parsetree.Pexp_field
((copy_expression x0), (copy_loc copy_Longident_t x1))
| Ast_413.Parsetree.Pexp_setfield (x0, x1, x2) ->
Ast_414.Parsetree.Pexp_setfield
((copy_expression x0), (copy_loc copy_Longident_t x1),
(copy_expression x2))
| Ast_413.Parsetree.Pexp_array x0 ->
Ast_414.Parsetree.Pexp_array (List.map copy_expression x0)
| Ast_413.Parsetree.Pexp_ifthenelse (x0, x1, x2) ->
Ast_414.Parsetree.Pexp_ifthenelse
((copy_expression x0), (copy_expression x1),
(Option.map copy_expression x2))
| Ast_413.Parsetree.Pexp_sequence (x0, x1) ->
Ast_414.Parsetree.Pexp_sequence
((copy_expression x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_while (x0, x1) ->
Ast_414.Parsetree.Pexp_while
((copy_expression x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_for (x0, x1, x2, x3, x4) ->
Ast_414.Parsetree.Pexp_for
((copy_pattern x0), (copy_expression x1), (copy_expression x2),
(copy_direction_flag x3), (copy_expression x4))
| Ast_413.Parsetree.Pexp_constraint (x0, x1) ->
Ast_414.Parsetree.Pexp_constraint
((copy_expression x0), (copy_core_type x1))
| Ast_413.Parsetree.Pexp_coerce (x0, x1, x2) ->
Ast_414.Parsetree.Pexp_coerce
((copy_expression x0), (Option.map copy_core_type x1),
(copy_core_type x2))
| Ast_413.Parsetree.Pexp_send (x0, x1) ->
Ast_414.Parsetree.Pexp_send
((copy_expression x0), (copy_loc copy_label x1))
| Ast_413.Parsetree.Pexp_new x0 ->
Ast_414.Parsetree.Pexp_new (copy_loc copy_Longident_t x0)
| Ast_413.Parsetree.Pexp_setinstvar (x0, x1) ->
Ast_414.Parsetree.Pexp_setinstvar
((copy_loc copy_label x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_override x0 ->
Ast_414.Parsetree.Pexp_override
(List.map
(fun x ->
let (x0, x1) = x in
((copy_loc copy_label x0), (copy_expression x1))) x0)
| Ast_413.Parsetree.Pexp_letmodule (x0, x1, x2) ->
Ast_414.Parsetree.Pexp_letmodule
((copy_loc (fun x -> Option.map (fun x -> x) x) x0),
(copy_module_expr x1), (copy_expression x2))
| Ast_413.Parsetree.Pexp_letexception (x0, x1) ->
Ast_414.Parsetree.Pexp_letexception
((copy_extension_constructor x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_assert x0 ->
Ast_414.Parsetree.Pexp_assert (copy_expression x0)
| Ast_413.Parsetree.Pexp_lazy x0 ->
Ast_414.Parsetree.Pexp_lazy (copy_expression x0)
| Ast_413.Parsetree.Pexp_poly (x0, x1) ->
Ast_414.Parsetree.Pexp_poly
((copy_expression x0), (Option.map copy_core_type x1))
| Ast_413.Parsetree.Pexp_object x0 ->
Ast_414.Parsetree.Pexp_object (copy_class_structure x0)
| Ast_413.Parsetree.Pexp_newtype (x0, x1) ->
Ast_414.Parsetree.Pexp_newtype
((copy_loc (fun x -> x) x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_pack x0 ->
Ast_414.Parsetree.Pexp_pack (copy_module_expr x0)
| Ast_413.Parsetree.Pexp_open (x0, x1) ->
Ast_414.Parsetree.Pexp_open
((copy_open_declaration x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_letop x0 ->
Ast_414.Parsetree.Pexp_letop (copy_letop x0)
| Ast_413.Parsetree.Pexp_extension x0 ->
Ast_414.Parsetree.Pexp_extension (copy_extension x0)
| Ast_413.Parsetree.Pexp_unreachable -> Ast_414.Parsetree.Pexp_unreachable
and copy_letop : Ast_413.Parsetree.letop -> Ast_414.Parsetree.letop =
fun
{ Ast_413.Parsetree.let_ = let_; Ast_413.Parsetree.ands = ands;
Ast_413.Parsetree.body = body }
->
{
Ast_414.Parsetree.let_ = (copy_binding_op let_);
Ast_414.Parsetree.ands = (List.map copy_binding_op ands);
Ast_414.Parsetree.body = (copy_expression body)
}
and copy_binding_op :
Ast_413.Parsetree.binding_op -> Ast_414.Parsetree.binding_op =
fun
{ Ast_413.Parsetree.pbop_op = pbop_op;
Ast_413.Parsetree.pbop_pat = pbop_pat;
Ast_413.Parsetree.pbop_exp = pbop_exp;
Ast_413.Parsetree.pbop_loc = pbop_loc }
->
{
Ast_414.Parsetree.pbop_op = (copy_loc (fun x -> x) pbop_op);
Ast_414.Parsetree.pbop_pat = (copy_pattern pbop_pat);
Ast_414.Parsetree.pbop_exp = (copy_expression pbop_exp);
Ast_414.Parsetree.pbop_loc = (copy_location pbop_loc)
}
and copy_direction_flag :
Ast_413.Asttypes.direction_flag -> Ast_414.Asttypes.direction_flag =
function
| Ast_413.Asttypes.Upto -> Ast_414.Asttypes.Upto
| Ast_413.Asttypes.Downto -> Ast_414.Asttypes.Downto
and copy_case : Ast_413.Parsetree.case -> Ast_414.Parsetree.case =
fun
{ Ast_413.Parsetree.pc_lhs = pc_lhs;
Ast_413.Parsetree.pc_guard = pc_guard;
Ast_413.Parsetree.pc_rhs = pc_rhs }
->
{
Ast_414.Parsetree.pc_lhs = (copy_pattern pc_lhs);
Ast_414.Parsetree.pc_guard = (Option.map copy_expression pc_guard);
Ast_414.Parsetree.pc_rhs = (copy_expression pc_rhs)
}
and copy_value_binding :
Ast_413.Parsetree.value_binding -> Ast_414.Parsetree.value_binding =
fun
{ Ast_413.Parsetree.pvb_pat = pvb_pat;
Ast_413.Parsetree.pvb_expr = pvb_expr;
Ast_413.Parsetree.pvb_attributes = pvb_attributes;
Ast_413.Parsetree.pvb_loc = pvb_loc }
->
{
Ast_414.Parsetree.pvb_pat = (copy_pattern pvb_pat);
Ast_414.Parsetree.pvb_expr = (copy_expression pvb_expr);
Ast_414.Parsetree.pvb_attributes = (copy_attributes pvb_attributes);
Ast_414.Parsetree.pvb_loc = (copy_location pvb_loc)
}
and copy_pattern : Ast_413.Parsetree.pattern -> Ast_414.Parsetree.pattern =
fun
{ Ast_413.Parsetree.ppat_desc = ppat_desc;
Ast_413.Parsetree.ppat_loc = ppat_loc;
Ast_413.Parsetree.ppat_loc_stack = ppat_loc_stack;
Ast_413.Parsetree.ppat_attributes = ppat_attributes }
->
{
Ast_414.Parsetree.ppat_desc = (copy_pattern_desc ppat_desc);
Ast_414.Parsetree.ppat_loc = (copy_location ppat_loc);
Ast_414.Parsetree.ppat_loc_stack = (copy_location_stack ppat_loc_stack);
Ast_414.Parsetree.ppat_attributes = (copy_attributes ppat_attributes)
}
and copy_pattern_desc :
Ast_413.Parsetree.pattern_desc -> Ast_414.Parsetree.pattern_desc =
function
| Ast_413.Parsetree.Ppat_any -> Ast_414.Parsetree.Ppat_any
| Ast_413.Parsetree.Ppat_var x0 ->
Ast_414.Parsetree.Ppat_var (copy_loc (fun x -> x) x0)
| Ast_413.Parsetree.Ppat_alias (x0, x1) ->
Ast_414.Parsetree.Ppat_alias
((copy_pattern x0), (copy_loc (fun x -> x) x1))
| Ast_413.Parsetree.Ppat_constant x0 ->
Ast_414.Parsetree.Ppat_constant (copy_constant x0)
| Ast_413.Parsetree.Ppat_interval (x0, x1) ->
Ast_414.Parsetree.Ppat_interval
((copy_constant x0), (copy_constant x1))
| Ast_413.Parsetree.Ppat_tuple x0 ->
Ast_414.Parsetree.Ppat_tuple (List.map copy_pattern x0)
| Ast_413.Parsetree.Ppat_construct (x0, x1) ->
Ast_414.Parsetree.Ppat_construct
((copy_loc copy_Longident_t x0), (Option.map (fun (x0, x1) -> x0, copy_pattern x1) x1))
| Ast_413.Parsetree.Ppat_variant (x0, x1) ->
Ast_414.Parsetree.Ppat_variant
((copy_label x0), (Option.map copy_pattern x1))
| Ast_413.Parsetree.Ppat_record (x0, x1) ->
Ast_414.Parsetree.Ppat_record
((List.map
(fun x ->
let (x0, x1) = x in
((copy_loc copy_Longident_t x0), (copy_pattern x1))) x0),
(copy_closed_flag x1))
| Ast_413.Parsetree.Ppat_array x0 ->
Ast_414.Parsetree.Ppat_array (List.map copy_pattern x0)
| Ast_413.Parsetree.Ppat_or (x0, x1) ->
Ast_414.Parsetree.Ppat_or ((copy_pattern x0), (copy_pattern x1))
| Ast_413.Parsetree.Ppat_constraint (x0, x1) ->
Ast_414.Parsetree.Ppat_constraint
((copy_pattern x0), (copy_core_type x1))
| Ast_413.Parsetree.Ppat_type x0 ->
Ast_414.Parsetree.Ppat_type (copy_loc copy_Longident_t x0)
| Ast_413.Parsetree.Ppat_lazy x0 ->
Ast_414.Parsetree.Ppat_lazy (copy_pattern x0)
| Ast_413.Parsetree.Ppat_unpack x0 ->
Ast_414.Parsetree.Ppat_unpack
(copy_loc (fun x -> Option.map (fun x -> x) x) x0)
| Ast_413.Parsetree.Ppat_exception x0 ->
Ast_414.Parsetree.Ppat_exception (copy_pattern x0)
| Ast_413.Parsetree.Ppat_extension x0 ->
Ast_414.Parsetree.Ppat_extension (copy_extension x0)
| Ast_413.Parsetree.Ppat_open (x0, x1) ->
Ast_414.Parsetree.Ppat_open
((copy_loc copy_Longident_t x0), (copy_pattern x1))
and copy_core_type :
Ast_413.Parsetree.core_type -> Ast_414.Parsetree.core_type =
fun
{ Ast_413.Parsetree.ptyp_desc = ptyp_desc;
Ast_413.Parsetree.ptyp_loc = ptyp_loc;
Ast_413.Parsetree.ptyp_loc_stack = ptyp_loc_stack;
Ast_413.Parsetree.ptyp_attributes = ptyp_attributes }
->
{
Ast_414.Parsetree.ptyp_desc = (copy_core_type_desc ptyp_desc);
Ast_414.Parsetree.ptyp_loc = (copy_location ptyp_loc);
Ast_414.Parsetree.ptyp_loc_stack = (copy_location_stack ptyp_loc_stack);
Ast_414.Parsetree.ptyp_attributes = (copy_attributes ptyp_attributes)
}
and copy_location_stack :
Ast_413.Parsetree.location_stack -> Ast_414.Parsetree.location_stack =
fun x -> List.map copy_location x
and copy_core_type_desc :
Ast_413.Parsetree.core_type_desc -> Ast_414.Parsetree.core_type_desc =
function
| Ast_413.Parsetree.Ptyp_any -> Ast_414.Parsetree.Ptyp_any
| Ast_413.Parsetree.Ptyp_var x0 -> Ast_414.Parsetree.Ptyp_var x0
| Ast_413.Parsetree.Ptyp_arrow (x0, x1, x2) ->
Ast_414.Parsetree.Ptyp_arrow
((copy_arg_label x0), (copy_core_type x1), (copy_core_type x2))
| Ast_413.Parsetree.Ptyp_tuple x0 ->
Ast_414.Parsetree.Ptyp_tuple (List.map copy_core_type x0)
| Ast_413.Parsetree.Ptyp_constr (x0, x1) ->
Ast_414.Parsetree.Ptyp_constr
((copy_loc copy_Longident_t x0), (List.map copy_core_type x1))
| Ast_413.Parsetree.Ptyp_object (x0, x1) ->
Ast_414.Parsetree.Ptyp_object
((List.map copy_object_field x0), (copy_closed_flag x1))
| Ast_413.Parsetree.Ptyp_class (x0, x1) ->
Ast_414.Parsetree.Ptyp_class
((copy_loc copy_Longident_t x0), (List.map copy_core_type x1))
| Ast_413.Parsetree.Ptyp_alias (x0, x1) ->
Ast_414.Parsetree.Ptyp_alias ((copy_core_type x0), x1)
| Ast_413.Parsetree.Ptyp_variant (x0, x1, x2) ->
Ast_414.Parsetree.Ptyp_variant
((List.map copy_row_field x0), (copy_closed_flag x1),
(Option.map (fun x -> List.map copy_label x) x2))
| Ast_413.Parsetree.Ptyp_poly (x0, x1) ->
Ast_414.Parsetree.Ptyp_poly
((List.map (fun x -> copy_loc (fun x -> x) x) x0),
(copy_core_type x1))
| Ast_413.Parsetree.Ptyp_package x0 ->
Ast_414.Parsetree.Ptyp_package (copy_package_type x0)
| Ast_413.Parsetree.Ptyp_extension x0 ->
Ast_414.Parsetree.Ptyp_extension (copy_extension x0)
and copy_package_type :
Ast_413.Parsetree.package_type -> Ast_414.Parsetree.package_type =
fun x ->
let (x0, x1) = x in
((copy_loc copy_Longident_t x0),
(List.map
(fun x ->
let (x0, x1) = x in
((copy_loc copy_Longident_t x0), (copy_core_type x1))) x1))
and copy_row_field :
Ast_413.Parsetree.row_field -> Ast_414.Parsetree.row_field =
fun
{ Ast_413.Parsetree.prf_desc = prf_desc;
Ast_413.Parsetree.prf_loc = prf_loc;
Ast_413.Parsetree.prf_attributes = prf_attributes }
->
{
Ast_414.Parsetree.prf_desc = (copy_row_field_desc prf_desc);
Ast_414.Parsetree.prf_loc = (copy_location prf_loc);
Ast_414.Parsetree.prf_attributes = (copy_attributes prf_attributes)
}
and copy_row_field_desc :
Ast_413.Parsetree.row_field_desc -> Ast_414.Parsetree.row_field_desc =
function
| Ast_413.Parsetree.Rtag (x0, x1, x2) ->
Ast_414.Parsetree.Rtag
((copy_loc copy_label x0), x1, (List.map copy_core_type x2))
| Ast_413.Parsetree.Rinherit x0 ->
Ast_414.Parsetree.Rinherit (copy_core_type x0)
and copy_object_field :
Ast_413.Parsetree.object_field -> Ast_414.Parsetree.object_field =
fun
{ Ast_413.Parsetree.pof_desc = pof_desc;
Ast_413.Parsetree.pof_loc = pof_loc;
Ast_413.Parsetree.pof_attributes = pof_attributes }
->
{
Ast_414.Parsetree.pof_desc = (copy_object_field_desc pof_desc);
Ast_414.Parsetree.pof_loc = (copy_location pof_loc);
Ast_414.Parsetree.pof_attributes = (copy_attributes pof_attributes)
}
and copy_attributes :
Ast_413.Parsetree.attributes -> Ast_414.Parsetree.attributes =
fun x -> List.map copy_attribute x
and copy_attribute :
Ast_413.Parsetree.attribute -> Ast_414.Parsetree.attribute =
fun
{ Ast_413.Parsetree.attr_name = attr_name;
Ast_413.Parsetree.attr_payload = attr_payload;
Ast_413.Parsetree.attr_loc = attr_loc }
->
{
Ast_414.Parsetree.attr_name = (copy_loc (fun x -> x) attr_name);
Ast_414.Parsetree.attr_payload = (copy_payload attr_payload);
Ast_414.Parsetree.attr_loc = (copy_location attr_loc)
}
and copy_payload : Ast_413.Parsetree.payload -> Ast_414.Parsetree.payload =
function
| Ast_413.Parsetree.PStr x0 -> Ast_414.Parsetree.PStr (copy_structure x0)
| Ast_413.Parsetree.PSig x0 -> Ast_414.Parsetree.PSig (copy_signature x0)
| Ast_413.Parsetree.PTyp x0 -> Ast_414.Parsetree.PTyp (copy_core_type x0)
| Ast_413.Parsetree.PPat (x0, x1) ->
Ast_414.Parsetree.PPat
((copy_pattern x0), (Option.map copy_expression x1))
and copy_structure :
Ast_413.Parsetree.structure -> Ast_414.Parsetree.structure =
fun x -> List.map copy_structure_item x
and copy_structure_item :
Ast_413.Parsetree.structure_item -> Ast_414.Parsetree.structure_item =
fun
{ Ast_413.Parsetree.pstr_desc = pstr_desc;
Ast_413.Parsetree.pstr_loc = pstr_loc }
->
{
Ast_414.Parsetree.pstr_desc = (copy_structure_item_desc pstr_desc);
Ast_414.Parsetree.pstr_loc = (copy_location pstr_loc)
}
and copy_structure_item_desc :
Ast_413.Parsetree.structure_item_desc ->
Ast_414.Parsetree.structure_item_desc
=
function
| Ast_413.Parsetree.Pstr_eval (x0, x1) ->
Ast_414.Parsetree.Pstr_eval
((copy_expression x0), (copy_attributes x1))
| Ast_413.Parsetree.Pstr_value (x0, x1) ->
Ast_414.Parsetree.Pstr_value
((copy_rec_flag x0), (List.map copy_value_binding x1))
| Ast_413.Parsetree.Pstr_primitive x0 ->
Ast_414.Parsetree.Pstr_primitive (copy_value_description x0)
| Ast_413.Parsetree.Pstr_type (x0, x1) ->
Ast_414.Parsetree.Pstr_type
((copy_rec_flag x0), (List.map copy_type_declaration x1))
| Ast_413.Parsetree.Pstr_typext x0 ->
Ast_414.Parsetree.Pstr_typext (copy_type_extension x0)
| Ast_413.Parsetree.Pstr_exception x0 ->
Ast_414.Parsetree.Pstr_exception (copy_type_exception x0)
| Ast_413.Parsetree.Pstr_module x0 ->
Ast_414.Parsetree.Pstr_module (copy_module_binding x0)
| Ast_413.Parsetree.Pstr_recmodule x0 ->
Ast_414.Parsetree.Pstr_recmodule (List.map copy_module_binding x0)
| Ast_413.Parsetree.Pstr_modtype x0 ->
Ast_414.Parsetree.Pstr_modtype (copy_module_type_declaration x0)
| Ast_413.Parsetree.Pstr_open x0 ->
Ast_414.Parsetree.Pstr_open (copy_open_declaration x0)
| Ast_413.Parsetree.Pstr_class x0 ->
Ast_414.Parsetree.Pstr_class (List.map copy_class_declaration x0)
| Ast_413.Parsetree.Pstr_class_type x0 ->
Ast_414.Parsetree.Pstr_class_type
(List.map copy_class_type_declaration x0)
| Ast_413.Parsetree.Pstr_include x0 ->
Ast_414.Parsetree.Pstr_include (copy_include_declaration x0)
| Ast_413.Parsetree.Pstr_attribute x0 ->
Ast_414.Parsetree.Pstr_attribute (copy_attribute x0)
| Ast_413.Parsetree.Pstr_extension (x0, x1) ->
Ast_414.Parsetree.Pstr_extension
((copy_extension x0), (copy_attributes x1))
and copy_include_declaration :
Ast_413.Parsetree.include_declaration ->
Ast_414.Parsetree.include_declaration
= fun x -> copy_include_infos copy_module_expr x
and copy_class_declaration :
Ast_413.Parsetree.class_declaration -> Ast_414.Parsetree.class_declaration
= fun x -> copy_class_infos copy_class_expr x
and copy_class_expr :
Ast_413.Parsetree.class_expr -> Ast_414.Parsetree.class_expr =
fun
{ Ast_413.Parsetree.pcl_desc = pcl_desc;
Ast_413.Parsetree.pcl_loc = pcl_loc;
Ast_413.Parsetree.pcl_attributes = pcl_attributes }
->
{
Ast_414.Parsetree.pcl_desc = (copy_class_expr_desc pcl_desc);
Ast_414.Parsetree.pcl_loc = (copy_location pcl_loc);
Ast_414.Parsetree.pcl_attributes = (copy_attributes pcl_attributes)
}
and copy_class_expr_desc :
Ast_413.Parsetree.class_expr_desc -> Ast_414.Parsetree.class_expr_desc =
function
| Ast_413.Parsetree.Pcl_constr (x0, x1) ->
Ast_414.Parsetree.Pcl_constr
((copy_loc copy_Longident_t x0), (List.map copy_core_type x1))
| Ast_413.Parsetree.Pcl_structure x0 ->
Ast_414.Parsetree.Pcl_structure (copy_class_structure x0)
| Ast_413.Parsetree.Pcl_fun (x0, x1, x2, x3) ->
Ast_414.Parsetree.Pcl_fun
((copy_arg_label x0), (Option.map copy_expression x1),
(copy_pattern x2), (copy_class_expr x3))
| Ast_413.Parsetree.Pcl_apply (x0, x1) ->
Ast_414.Parsetree.Pcl_apply
((copy_class_expr x0),
(List.map
(fun x ->
let (x0, x1) = x in
((copy_arg_label x0), (copy_expression x1))) x1))
| Ast_413.Parsetree.Pcl_let (x0, x1, x2) ->
Ast_414.Parsetree.Pcl_let
((copy_rec_flag x0), (List.map copy_value_binding x1),
(copy_class_expr x2))
| Ast_413.Parsetree.Pcl_constraint (x0, x1) ->
Ast_414.Parsetree.Pcl_constraint
((copy_class_expr x0), (copy_class_type x1))
| Ast_413.Parsetree.Pcl_extension x0 ->
Ast_414.Parsetree.Pcl_extension (copy_extension x0)
| Ast_413.Parsetree.Pcl_open (x0, x1) ->
Ast_414.Parsetree.Pcl_open
((copy_open_description x0), (copy_class_expr x1))
and copy_class_structure :
Ast_413.Parsetree.class_structure -> Ast_414.Parsetree.class_structure =
fun
{ Ast_413.Parsetree.pcstr_self = pcstr_self;
Ast_413.Parsetree.pcstr_fields = pcstr_fields }
->
{
Ast_414.Parsetree.pcstr_self = (copy_pattern pcstr_self);
Ast_414.Parsetree.pcstr_fields =
(List.map copy_class_field pcstr_fields)
}
and copy_class_field :
Ast_413.Parsetree.class_field -> Ast_414.Parsetree.class_field =
fun
{ Ast_413.Parsetree.pcf_desc = pcf_desc;
Ast_413.Parsetree.pcf_loc = pcf_loc;
Ast_413.Parsetree.pcf_attributes = pcf_attributes }
->
{
Ast_414.Parsetree.pcf_desc = (copy_class_field_desc pcf_desc);
Ast_414.Parsetree.pcf_loc = (copy_location pcf_loc);
Ast_414.Parsetree.pcf_attributes = (copy_attributes pcf_attributes)
}
and copy_class_field_desc :
Ast_413.Parsetree.class_field_desc -> Ast_414.Parsetree.class_field_desc =
function
| Ast_413.Parsetree.Pcf_inherit (x0, x1, x2) ->
Ast_414.Parsetree.Pcf_inherit
((copy_override_flag x0), (copy_class_expr x1),
(Option.map (fun x -> copy_loc (fun x -> x) x) x2))
| Ast_413.Parsetree.Pcf_val x0 ->
Ast_414.Parsetree.Pcf_val
(let (x0, x1, x2) = x0 in
((copy_loc copy_label x0), (copy_mutable_flag x1),
(copy_class_field_kind x2)))
| Ast_413.Parsetree.Pcf_method x0 ->
Ast_414.Parsetree.Pcf_method
(let (x0, x1, x2) = x0 in
((copy_loc copy_label x0), (copy_private_flag x1),
(copy_class_field_kind x2)))
| Ast_413.Parsetree.Pcf_constraint x0 ->
Ast_414.Parsetree.Pcf_constraint
(let (x0, x1) = x0 in ((copy_core_type x0), (copy_core_type x1)))
| Ast_413.Parsetree.Pcf_initializer x0 ->
Ast_414.Parsetree.Pcf_initializer (copy_expression x0)
| Ast_413.Parsetree.Pcf_attribute x0 ->
Ast_414.Parsetree.Pcf_attribute (copy_attribute x0)
| Ast_413.Parsetree.Pcf_extension x0 ->
Ast_414.Parsetree.Pcf_extension (copy_extension x0)
and copy_class_field_kind :
Ast_413.Parsetree.class_field_kind -> Ast_414.Parsetree.class_field_kind =
function
| Ast_413.Parsetree.Cfk_virtual x0 ->
Ast_414.Parsetree.Cfk_virtual (copy_core_type x0)
| Ast_413.Parsetree.Cfk_concrete (x0, x1) ->
Ast_414.Parsetree.Cfk_concrete
((copy_override_flag x0), (copy_expression x1))
and copy_open_declaration :
Ast_413.Parsetree.open_declaration -> Ast_414.Parsetree.open_declaration =
fun x -> copy_open_infos copy_module_expr x
and copy_module_binding :
Ast_413.Parsetree.module_binding -> Ast_414.Parsetree.module_binding =
fun
{ Ast_413.Parsetree.pmb_name = pmb_name;
Ast_413.Parsetree.pmb_expr = pmb_expr;
Ast_413.Parsetree.pmb_attributes = pmb_attributes;
Ast_413.Parsetree.pmb_loc = pmb_loc }
->
{
Ast_414.Parsetree.pmb_name =
(copy_loc (fun x -> Option.map (fun x -> x) x) pmb_name);
Ast_414.Parsetree.pmb_expr = (copy_module_expr pmb_expr);
Ast_414.Parsetree.pmb_attributes = (copy_attributes pmb_attributes);
Ast_414.Parsetree.pmb_loc = (copy_location pmb_loc)
}
and copy_module_expr :
Ast_413.Parsetree.module_expr -> Ast_414.Parsetree.module_expr =
fun
{ Ast_413.Parsetree.pmod_desc = pmod_desc;
Ast_413.Parsetree.pmod_loc = pmod_loc;
Ast_413.Parsetree.pmod_attributes = pmod_attributes }
->
{
Ast_414.Parsetree.pmod_desc = (copy_module_expr_desc pmod_desc);
Ast_414.Parsetree.pmod_loc = (copy_location pmod_loc);
Ast_414.Parsetree.pmod_attributes = (copy_attributes pmod_attributes)
}
and copy_module_expr_desc :
Ast_413.Parsetree.module_expr_desc -> Ast_414.Parsetree.module_expr_desc =
function
| Ast_413.Parsetree.Pmod_ident x0 ->
Ast_414.Parsetree.Pmod_ident (copy_loc copy_Longident_t x0)
| Ast_413.Parsetree.Pmod_structure x0 ->
Ast_414.Parsetree.Pmod_structure (copy_structure x0)
| Ast_413.Parsetree.Pmod_functor (x0, x1) ->
Ast_414.Parsetree.Pmod_functor
((copy_functor_parameter x0), (copy_module_expr x1))
| Ast_413.Parsetree.Pmod_apply (x0, x1) ->
Ast_414.Parsetree.Pmod_apply
((copy_module_expr x0), (copy_module_expr x1))
| Ast_413.Parsetree.Pmod_constraint (x0, x1) ->
Ast_414.Parsetree.Pmod_constraint
((copy_module_expr x0), (copy_module_type x1))
| Ast_413.Parsetree.Pmod_unpack x0 ->
Ast_414.Parsetree.Pmod_unpack (copy_expression x0)
| Ast_413.Parsetree.Pmod_extension x0 ->
Ast_414.Parsetree.Pmod_extension (copy_extension x0)
and copy_functor_parameter :
Ast_413.Parsetree.functor_parameter -> Ast_414.Parsetree.functor_parameter
=
function
| Ast_413.Parsetree.Unit -> Ast_414.Parsetree.Unit
| Ast_413.Parsetree.Named (x0, x1) ->
Ast_414.Parsetree.Named
((copy_loc (fun x -> Option.map (fun x -> x) x) x0),
(copy_module_type x1))
and copy_module_type :
Ast_413.Parsetree.module_type -> Ast_414.Parsetree.module_type =
fun
{ Ast_413.Parsetree.pmty_desc = pmty_desc;
Ast_413.Parsetree.pmty_loc = pmty_loc;
Ast_413.Parsetree.pmty_attributes = pmty_attributes }
->
{
Ast_414.Parsetree.pmty_desc = (copy_module_type_desc pmty_desc);
Ast_414.Parsetree.pmty_loc = (copy_location pmty_loc);
Ast_414.Parsetree.pmty_attributes = (copy_attributes pmty_attributes)
}
and copy_module_type_desc :
Ast_413.Parsetree.module_type_desc -> Ast_414.Parsetree.module_type_desc =
function
| Ast_413.Parsetree.Pmty_ident x0 ->
Ast_414.Parsetree.Pmty_ident (copy_loc copy_Longident_t x0)
| Ast_413.Parsetree.Pmty_signature x0 ->
Ast_414.Parsetree.Pmty_signature (copy_signature x0)
| Ast_413.Parsetree.Pmty_functor (x0, x1) ->
Ast_414.Parsetree.Pmty_functor
((copy_functor_parameter x0), (copy_module_type x1))
| Ast_413.Parsetree.Pmty_with (x0, x1) ->
Ast_414.Parsetree.Pmty_with
((copy_module_type x0), (List.map copy_with_constraint x1))
| Ast_413.Parsetree.Pmty_typeof x0 ->
Ast_414.Parsetree.Pmty_typeof (copy_module_expr x0)
| Ast_413.Parsetree.Pmty_extension x0 ->
Ast_414.Parsetree.Pmty_extension (copy_extension x0)
| Ast_413.Parsetree.Pmty_alias x0 ->
Ast_414.Parsetree.Pmty_alias (copy_loc copy_Longident_t x0)
and copy_with_constraint :
Ast_413.Parsetree.with_constraint -> Ast_414.Parsetree.with_constraint =
function
| Ast_413.Parsetree.Pwith_type (x0, x1) ->
Ast_414.Parsetree.Pwith_type
((copy_loc copy_Longident_t x0), (copy_type_declaration x1))
| Ast_413.Parsetree.Pwith_module (x0, x1) ->
Ast_414.Parsetree.Pwith_module
((copy_loc copy_Longident_t x0), (copy_loc copy_Longident_t x1))
| Ast_413.Parsetree.Pwith_modtype (x0, x1) ->
Ast_414.Parsetree.Pwith_modtype
((copy_loc copy_Longident_t x0), (copy_module_type x1))
| Ast_413.Parsetree.Pwith_modtypesubst (x0, x1) ->
Ast_414.Parsetree.Pwith_modtypesubst
((copy_loc copy_Longident_t x0), (copy_module_type x1))
| Ast_413.Parsetree.Pwith_typesubst (x0, x1) ->
Ast_414.Parsetree.Pwith_typesubst
((copy_loc copy_Longident_t x0), (copy_type_declaration x1))
| Ast_413.Parsetree.Pwith_modsubst (x0, x1) ->
Ast_414.Parsetree.Pwith_modsubst
((copy_loc copy_Longident_t x0), (copy_loc copy_Longident_t x1))
and copy_signature :
Ast_413.Parsetree.signature -> Ast_414.Parsetree.signature =
fun x -> List.map copy_signature_item x
and copy_signature_item :
Ast_413.Parsetree.signature_item -> Ast_414.Parsetree.signature_item =
fun
{ Ast_413.Parsetree.psig_desc = psig_desc;
Ast_413.Parsetree.psig_loc = psig_loc }
->
{
Ast_414.Parsetree.psig_desc = (copy_signature_item_desc psig_desc);
Ast_414.Parsetree.psig_loc = (copy_location psig_loc)
}
and copy_signature_item_desc :
Ast_413.Parsetree.signature_item_desc ->
Ast_414.Parsetree.signature_item_desc
=
function
| Ast_413.Parsetree.Psig_value x0 ->
Ast_414.Parsetree.Psig_value (copy_value_description x0)
| Ast_413.Parsetree.Psig_type (x0, x1) ->
Ast_414.Parsetree.Psig_type
((copy_rec_flag x0), (List.map copy_type_declaration x1))
| Ast_413.Parsetree.Psig_typesubst x0 ->
Ast_414.Parsetree.Psig_typesubst (List.map copy_type_declaration x0)
| Ast_413.Parsetree.Psig_typext x0 ->
Ast_414.Parsetree.Psig_typext (copy_type_extension x0)
| Ast_413.Parsetree.Psig_exception x0 ->
Ast_414.Parsetree.Psig_exception (copy_type_exception x0)
| Ast_413.Parsetree.Psig_module x0 ->
Ast_414.Parsetree.Psig_module (copy_module_declaration x0)
| Ast_413.Parsetree.Psig_modsubst x0 ->
Ast_414.Parsetree.Psig_modsubst (copy_module_substitution x0)
| Ast_413.Parsetree.Psig_recmodule x0 ->
Ast_414.Parsetree.Psig_recmodule (List.map copy_module_declaration x0)
| Ast_413.Parsetree.Psig_modtype x0 ->
Ast_414.Parsetree.Psig_modtype (copy_module_type_declaration x0)
| Ast_413.Parsetree.Psig_modtypesubst x0 ->
Ast_414.Parsetree.Psig_modtypesubst (copy_module_type_declaration x0)
| Ast_413.Parsetree.Psig_open x0 ->
Ast_414.Parsetree.Psig_open (copy_open_description x0)
| Ast_413.Parsetree.Psig_include x0 ->
Ast_414.Parsetree.Psig_include (copy_include_description x0)
| Ast_413.Parsetree.Psig_class x0 ->
Ast_414.Parsetree.Psig_class (List.map copy_class_description x0)
| Ast_413.Parsetree.Psig_class_type x0 ->
Ast_414.Parsetree.Psig_class_type
(List.map copy_class_type_declaration x0)
| Ast_413.Parsetree.Psig_attribute x0 ->
Ast_414.Parsetree.Psig_attribute (copy_attribute x0)
| Ast_413.Parsetree.Psig_extension (x0, x1) ->
Ast_414.Parsetree.Psig_extension
((copy_extension x0), (copy_attributes x1))
and copy_class_type_declaration :
Ast_413.Parsetree.class_type_declaration ->
Ast_414.Parsetree.class_type_declaration
= fun x -> copy_class_infos copy_class_type x
and copy_class_description :
Ast_413.Parsetree.class_description -> Ast_414.Parsetree.class_description
= fun x -> copy_class_infos copy_class_type x
and copy_class_type :
Ast_413.Parsetree.class_type -> Ast_414.Parsetree.class_type =
fun
{ Ast_413.Parsetree.pcty_desc = pcty_desc;
Ast_413.Parsetree.pcty_loc = pcty_loc;
Ast_413.Parsetree.pcty_attributes = pcty_attributes }
->
{
Ast_414.Parsetree.pcty_desc = (copy_class_type_desc pcty_desc);
Ast_414.Parsetree.pcty_loc = (copy_location pcty_loc);
Ast_414.Parsetree.pcty_attributes = (copy_attributes pcty_attributes)
}
and copy_class_type_desc :
Ast_413.Parsetree.class_type_desc -> Ast_414.Parsetree.class_type_desc =
function
| Ast_413.Parsetree.Pcty_constr (x0, x1) ->
Ast_414.Parsetree.Pcty_constr
((copy_loc copy_Longident_t x0), (List.map copy_core_type x1))
| Ast_413.Parsetree.Pcty_signature x0 ->
Ast_414.Parsetree.Pcty_signature (copy_class_signature x0)
| Ast_413.Parsetree.Pcty_arrow (x0, x1, x2) ->
Ast_414.Parsetree.Pcty_arrow
((copy_arg_label x0), (copy_core_type x1), (copy_class_type x2))
| Ast_413.Parsetree.Pcty_extension x0 ->
Ast_414.Parsetree.Pcty_extension (copy_extension x0)
| Ast_413.Parsetree.Pcty_open (x0, x1) ->
Ast_414.Parsetree.Pcty_open
((copy_open_description x0), (copy_class_type x1))
and copy_class_signature :
Ast_413.Parsetree.class_signature -> Ast_414.Parsetree.class_signature =
fun
{ Ast_413.Parsetree.pcsig_self = pcsig_self;
Ast_413.Parsetree.pcsig_fields = pcsig_fields }
->
{
Ast_414.Parsetree.pcsig_self = (copy_core_type pcsig_self);
Ast_414.Parsetree.pcsig_fields =
(List.map copy_class_type_field pcsig_fields)
}
and copy_class_type_field :
Ast_413.Parsetree.class_type_field -> Ast_414.Parsetree.class_type_field =
fun
{ Ast_413.Parsetree.pctf_desc = pctf_desc;
Ast_413.Parsetree.pctf_loc = pctf_loc;
Ast_413.Parsetree.pctf_attributes = pctf_attributes }
->
{
Ast_414.Parsetree.pctf_desc = (copy_class_type_field_desc pctf_desc);
Ast_414.Parsetree.pctf_loc = (copy_location pctf_loc);
Ast_414.Parsetree.pctf_attributes = (copy_attributes pctf_attributes)
}
and copy_class_type_field_desc :
Ast_413.Parsetree.class_type_field_desc ->
Ast_414.Parsetree.class_type_field_desc
=
function
| Ast_413.Parsetree.Pctf_inherit x0 ->
Ast_414.Parsetree.Pctf_inherit (copy_class_type x0)
| Ast_413.Parsetree.Pctf_val x0 ->
Ast_414.Parsetree.Pctf_val
(let (x0, x1, x2, x3) = x0 in
((copy_loc copy_label x0), (copy_mutable_flag x1),
(copy_virtual_flag x2), (copy_core_type x3)))
| Ast_413.Parsetree.Pctf_method x0 ->
Ast_414.Parsetree.Pctf_method
(let (x0, x1, x2, x3) = x0 in
((copy_loc copy_label x0), (copy_private_flag x1),
(copy_virtual_flag x2), (copy_core_type x3)))
| Ast_413.Parsetree.Pctf_constraint x0 ->
Ast_414.Parsetree.Pctf_constraint
(let (x0, x1) = x0 in ((copy_core_type x0), (copy_core_type x1)))
| Ast_413.Parsetree.Pctf_attribute x0 ->
Ast_414.Parsetree.Pctf_attribute (copy_attribute x0)
| Ast_413.Parsetree.Pctf_extension x0 ->
Ast_414.Parsetree.Pctf_extension (copy_extension x0)
and copy_extension :
Ast_413.Parsetree.extension -> Ast_414.Parsetree.extension =
fun x ->
let (x0, x1) = x in ((copy_loc (fun x -> x) x0), (copy_payload x1))
and copy_class_infos :
'f0 'g0 .
('f0 -> 'g0) ->
'f0 Ast_413.Parsetree.class_infos -> 'g0 Ast_414.Parsetree.class_infos
=
fun f0 ->
fun
{ Ast_413.Parsetree.pci_virt = pci_virt;
Ast_413.Parsetree.pci_params = pci_params;
Ast_413.Parsetree.pci_name = pci_name;
Ast_413.Parsetree.pci_expr = pci_expr;
Ast_413.Parsetree.pci_loc = pci_loc;
Ast_413.Parsetree.pci_attributes = pci_attributes }
->
{
Ast_414.Parsetree.pci_virt = (copy_virtual_flag pci_virt);
Ast_414.Parsetree.pci_params =
(List.map
(fun x ->
let (x0, x1) = x in
((copy_core_type x0),
(let (x0, x1) = x1 in
((copy_variance x0), (copy_injectivity x1))))) pci_params);
Ast_414.Parsetree.pci_name = (copy_loc (fun x -> x) pci_name);
Ast_414.Parsetree.pci_expr = (f0 pci_expr);
Ast_414.Parsetree.pci_loc = (copy_location pci_loc);
Ast_414.Parsetree.pci_attributes = (copy_attributes pci_attributes)
}
and copy_virtual_flag :
Ast_413.Asttypes.virtual_flag -> Ast_414.Asttypes.virtual_flag =
function
| Ast_413.Asttypes.Virtual -> Ast_414.Asttypes.Virtual
| Ast_413.Asttypes.Concrete -> Ast_414.Asttypes.Concrete
and copy_include_description :
Ast_413.Parsetree.include_description ->
Ast_414.Parsetree.include_description
= fun x -> copy_include_infos copy_module_type x
and copy_include_infos :
'f0 'g0 .
('f0 -> 'g0) ->
'f0 Ast_413.Parsetree.include_infos ->
'g0 Ast_414.Parsetree.include_infos
=
fun f0 ->
fun
{ Ast_413.Parsetree.pincl_mod = pincl_mod;
Ast_413.Parsetree.pincl_loc = pincl_loc;
Ast_413.Parsetree.pincl_attributes = pincl_attributes }
->
{
Ast_414.Parsetree.pincl_mod = (f0 pincl_mod);
Ast_414.Parsetree.pincl_loc = (copy_location pincl_loc);
Ast_414.Parsetree.pincl_attributes =
(copy_attributes pincl_attributes)
}
and copy_open_description :
Ast_413.Parsetree.open_description -> Ast_414.Parsetree.open_description =
fun x -> copy_open_infos (fun x -> copy_loc copy_Longident_t x) x
and copy_open_infos :
'f0 'g0 .
('f0 -> 'g0) ->
'f0 Ast_413.Parsetree.open_infos -> 'g0 Ast_414.Parsetree.open_infos
=
fun f0 ->
fun
{ Ast_413.Parsetree.popen_expr = popen_expr;
Ast_413.Parsetree.popen_override = popen_override;
Ast_413.Parsetree.popen_loc = popen_loc;
Ast_413.Parsetree.popen_attributes = popen_attributes }
->
{
Ast_414.Parsetree.popen_expr = (f0 popen_expr);
Ast_414.Parsetree.popen_override =
(copy_override_flag popen_override);
Ast_414.Parsetree.popen_loc = (copy_location popen_loc);
Ast_414.Parsetree.popen_attributes =
(copy_attributes popen_attributes)
}
and copy_override_flag :
Ast_413.Asttypes.override_flag -> Ast_414.Asttypes.override_flag =
function
| Ast_413.Asttypes.Override -> Ast_414.Asttypes.Override
| Ast_413.Asttypes.Fresh -> Ast_414.Asttypes.Fresh
and copy_module_type_declaration :
Ast_413.Parsetree.module_type_declaration ->
Ast_414.Parsetree.module_type_declaration
=
fun
{ Ast_413.Parsetree.pmtd_name = pmtd_name;
Ast_413.Parsetree.pmtd_type = pmtd_type;
Ast_413.Parsetree.pmtd_attributes = pmtd_attributes;
Ast_413.Parsetree.pmtd_loc = pmtd_loc }
->
{
Ast_414.Parsetree.pmtd_name = (copy_loc (fun x -> x) pmtd_name);
Ast_414.Parsetree.pmtd_type = (Option.map copy_module_type pmtd_type);
Ast_414.Parsetree.pmtd_attributes = (copy_attributes pmtd_attributes);
Ast_414.Parsetree.pmtd_loc = (copy_location pmtd_loc)
}
and copy_module_substitution :
Ast_413.Parsetree.module_substitution ->
Ast_414.Parsetree.module_substitution
=
fun
{ Ast_413.Parsetree.pms_name = pms_name;
Ast_413.Parsetree.pms_manifest = pms_manifest;
Ast_413.Parsetree.pms_attributes = pms_attributes;
Ast_413.Parsetree.pms_loc = pms_loc }
->
{
Ast_414.Parsetree.pms_name = (copy_loc (fun x -> x) pms_name);
Ast_414.Parsetree.pms_manifest =
(copy_loc copy_Longident_t pms_manifest);
Ast_414.Parsetree.pms_attributes = (copy_attributes pms_attributes);
Ast_414.Parsetree.pms_loc = (copy_location pms_loc)
}
and copy_module_declaration :
Ast_413.Parsetree.module_declaration ->
Ast_414.Parsetree.module_declaration
=
fun
{ Ast_413.Parsetree.pmd_name = pmd_name;
Ast_413.Parsetree.pmd_type = pmd_type;
Ast_413.Parsetree.pmd_attributes = pmd_attributes;
Ast_413.Parsetree.pmd_loc = pmd_loc }
->
{
Ast_414.Parsetree.pmd_name =
(copy_loc (fun x -> Option.map (fun x -> x) x) pmd_name);
Ast_414.Parsetree.pmd_type = (copy_module_type pmd_type);
Ast_414.Parsetree.pmd_attributes = (copy_attributes pmd_attributes);
Ast_414.Parsetree.pmd_loc = (copy_location pmd_loc)
}
and copy_type_exception :
Ast_413.Parsetree.type_exception -> Ast_414.Parsetree.type_exception =
fun
{ Ast_413.Parsetree.ptyexn_constructor = ptyexn_constructor;
Ast_413.Parsetree.ptyexn_loc = ptyexn_loc;
Ast_413.Parsetree.ptyexn_attributes = ptyexn_attributes }
->
{
Ast_414.Parsetree.ptyexn_constructor =
(copy_extension_constructor ptyexn_constructor);
Ast_414.Parsetree.ptyexn_loc = (copy_location ptyexn_loc);
Ast_414.Parsetree.ptyexn_attributes =
(copy_attributes ptyexn_attributes)
}
and copy_type_extension :
Ast_413.Parsetree.type_extension -> Ast_414.Parsetree.type_extension =
fun
{ Ast_413.Parsetree.ptyext_path = ptyext_path;
Ast_413.Parsetree.ptyext_params = ptyext_params;
Ast_413.Parsetree.ptyext_constructors = ptyext_constructors;
Ast_413.Parsetree.ptyext_private = ptyext_private;
Ast_413.Parsetree.ptyext_loc = ptyext_loc;
Ast_413.Parsetree.ptyext_attributes = ptyext_attributes }
->
{
Ast_414.Parsetree.ptyext_path = (copy_loc copy_Longident_t ptyext_path);
Ast_414.Parsetree.ptyext_params =
(List.map
(fun x ->
let (x0, x1) = x in
((copy_core_type x0),
(let (x0, x1) = x1 in
((copy_variance x0), (copy_injectivity x1))))) ptyext_params);
Ast_414.Parsetree.ptyext_constructors =
(List.map copy_extension_constructor ptyext_constructors);
Ast_414.Parsetree.ptyext_private = (copy_private_flag ptyext_private);
Ast_414.Parsetree.ptyext_loc = (copy_location ptyext_loc);
Ast_414.Parsetree.ptyext_attributes =
(copy_attributes ptyext_attributes)
}
and copy_extension_constructor :
Ast_413.Parsetree.extension_constructor ->
Ast_414.Parsetree.extension_constructor
=
fun
{ Ast_413.Parsetree.pext_name = pext_name;
Ast_413.Parsetree.pext_kind = pext_kind;
Ast_413.Parsetree.pext_loc = pext_loc;
Ast_413.Parsetree.pext_attributes = pext_attributes }
->
{
Ast_414.Parsetree.pext_name = (copy_loc (fun x -> x) pext_name);
Ast_414.Parsetree.pext_kind =
(copy_extension_constructor_kind pext_kind);
Ast_414.Parsetree.pext_loc = (copy_location pext_loc);
Ast_414.Parsetree.pext_attributes = (copy_attributes pext_attributes)
}
and copy_extension_constructor_kind :
Ast_413.Parsetree.extension_constructor_kind ->
Ast_414.Parsetree.extension_constructor_kind
=
function
| Ast_413.Parsetree.Pext_decl (x0, x1) ->
Ast_414.Parsetree.Pext_decl
([], (copy_constructor_arguments x0), (Option.map copy_core_type x1))
| Ast_413.Parsetree.Pext_rebind x0 ->
Ast_414.Parsetree.Pext_rebind (copy_loc copy_Longident_t x0)
and copy_type_declaration :
Ast_413.Parsetree.type_declaration -> Ast_414.Parsetree.type_declaration =
fun
{ Ast_413.Parsetree.ptype_name = ptype_name;
Ast_413.Parsetree.ptype_params = ptype_params;
Ast_413.Parsetree.ptype_cstrs = ptype_cstrs;
Ast_413.Parsetree.ptype_kind = ptype_kind;
Ast_413.Parsetree.ptype_private = ptype_private;
Ast_413.Parsetree.ptype_manifest = ptype_manifest;
Ast_413.Parsetree.ptype_attributes = ptype_attributes;
Ast_413.Parsetree.ptype_loc = ptype_loc }
->
{
Ast_414.Parsetree.ptype_name = (copy_loc (fun x -> x) ptype_name);
Ast_414.Parsetree.ptype_params =
(List.map
(fun x ->
let (x0, x1) = x in
((copy_core_type x0),
(let (x0, x1) = x1 in
((copy_variance x0), (copy_injectivity x1))))) ptype_params);
Ast_414.Parsetree.ptype_cstrs =
(List.map
(fun x ->
let (x0, x1, x2) = x in
((copy_core_type x0), (copy_core_type x1), (copy_location x2)))
ptype_cstrs);
Ast_414.Parsetree.ptype_kind = (copy_type_kind ptype_kind);
Ast_414.Parsetree.ptype_private = (copy_private_flag ptype_private);
Ast_414.Parsetree.ptype_manifest =
(Option.map copy_core_type ptype_manifest);
Ast_414.Parsetree.ptype_attributes = (copy_attributes ptype_attributes);
Ast_414.Parsetree.ptype_loc = (copy_location ptype_loc)
}
and copy_private_flag :
Ast_413.Asttypes.private_flag -> Ast_414.Asttypes.private_flag =
function
| Ast_413.Asttypes.Private -> Ast_414.Asttypes.Private
| Ast_413.Asttypes.Public -> Ast_414.Asttypes.Public
and copy_type_kind :
Ast_413.Parsetree.type_kind -> Ast_414.Parsetree.type_kind =
function
| Ast_413.Parsetree.Ptype_abstract -> Ast_414.Parsetree.Ptype_abstract
| Ast_413.Parsetree.Ptype_variant x0 ->
Ast_414.Parsetree.Ptype_variant
(List.map copy_constructor_declaration x0)
| Ast_413.Parsetree.Ptype_record x0 ->
Ast_414.Parsetree.Ptype_record (List.map copy_label_declaration x0)
| Ast_413.Parsetree.Ptype_open -> Ast_414.Parsetree.Ptype_open
and copy_constructor_declaration :
Ast_413.Parsetree.constructor_declaration ->
Ast_414.Parsetree.constructor_declaration
=
fun
{ Ast_413.Parsetree.pcd_name = pcd_name;
Ast_413.Parsetree.pcd_args = pcd_args;
Ast_413.Parsetree.pcd_res = pcd_res;
Ast_413.Parsetree.pcd_loc = pcd_loc;
Ast_413.Parsetree.pcd_attributes = pcd_attributes }
->
{
Ast_414.Parsetree.pcd_name = (copy_loc (fun x -> x) pcd_name);
Ast_414.Parsetree.pcd_vars = [];
Ast_414.Parsetree.pcd_args = (copy_constructor_arguments pcd_args);
Ast_414.Parsetree.pcd_res = (Option.map copy_core_type pcd_res);
Ast_414.Parsetree.pcd_loc = (copy_location pcd_loc);
Ast_414.Parsetree.pcd_attributes = (copy_attributes pcd_attributes)
}
and copy_constructor_arguments :
Ast_413.Parsetree.constructor_arguments ->
Ast_414.Parsetree.constructor_arguments
=
function
| Ast_413.Parsetree.Pcstr_tuple x0 ->
Ast_414.Parsetree.Pcstr_tuple (List.map copy_core_type x0)
| Ast_413.Parsetree.Pcstr_record x0 ->
Ast_414.Parsetree.Pcstr_record (List.map copy_label_declaration x0)
and copy_label_declaration :
Ast_413.Parsetree.label_declaration -> Ast_414.Parsetree.label_declaration
=
fun
{ Ast_413.Parsetree.pld_name = pld_name;
Ast_413.Parsetree.pld_mutable = pld_mutable;
Ast_413.Parsetree.pld_type = pld_type;
Ast_413.Parsetree.pld_loc = pld_loc;
Ast_413.Parsetree.pld_attributes = pld_attributes }
->
{
Ast_414.Parsetree.pld_name = (copy_loc (fun x -> x) pld_name);
Ast_414.Parsetree.pld_mutable = (copy_mutable_flag pld_mutable);
Ast_414.Parsetree.pld_type = (copy_core_type pld_type);
Ast_414.Parsetree.pld_loc = (copy_location pld_loc);
Ast_414.Parsetree.pld_attributes = (copy_attributes pld_attributes)
}
and copy_mutable_flag :
Ast_413.Asttypes.mutable_flag -> Ast_414.Asttypes.mutable_flag =
function
| Ast_413.Asttypes.Immutable -> Ast_414.Asttypes.Immutable
| Ast_413.Asttypes.Mutable -> Ast_414.Asttypes.Mutable
and copy_injectivity :
Ast_413.Asttypes.injectivity -> Ast_414.Asttypes.injectivity =
function
| Ast_413.Asttypes.Injective -> Ast_414.Asttypes.Injective
| Ast_413.Asttypes.NoInjectivity -> Ast_414.Asttypes.NoInjectivity
and copy_variance : Ast_413.Asttypes.variance -> Ast_414.Asttypes.variance =
function
| Ast_413.Asttypes.Covariant -> Ast_414.Asttypes.Covariant
| Ast_413.Asttypes.Contravariant -> Ast_414.Asttypes.Contravariant
| Ast_413.Asttypes.NoVariance -> Ast_414.Asttypes.NoVariance
and copy_value_description :
Ast_413.Parsetree.value_description -> Ast_414.Parsetree.value_description
=
fun
{ Ast_413.Parsetree.pval_name = pval_name;
Ast_413.Parsetree.pval_type = pval_type;
Ast_413.Parsetree.pval_prim = pval_prim;
Ast_413.Parsetree.pval_attributes = pval_attributes;
Ast_413.Parsetree.pval_loc = pval_loc }
->
{
Ast_414.Parsetree.pval_name = (copy_loc (fun x -> x) pval_name);
Ast_414.Parsetree.pval_type = (copy_core_type pval_type);
Ast_414.Parsetree.pval_prim = (List.map (fun x -> x) pval_prim);
Ast_414.Parsetree.pval_attributes = (copy_attributes pval_attributes);
Ast_414.Parsetree.pval_loc = (copy_location pval_loc)
}
and copy_object_field_desc :
Ast_413.Parsetree.object_field_desc -> Ast_414.Parsetree.object_field_desc
=
function
| Ast_413.Parsetree.Otag (x0, x1) ->
Ast_414.Parsetree.Otag ((copy_loc copy_label x0), (copy_core_type x1))
| Ast_413.Parsetree.Oinherit x0 ->
Ast_414.Parsetree.Oinherit (copy_core_type x0)
and copy_arg_label : Ast_413.Asttypes.arg_label -> Ast_414.Asttypes.arg_label
=
function
| Ast_413.Asttypes.Nolabel -> Ast_414.Asttypes.Nolabel
| Ast_413.Asttypes.Labelled x0 -> Ast_414.Asttypes.Labelled x0
| Ast_413.Asttypes.Optional x0 -> Ast_414.Asttypes.Optional x0
and copy_closed_flag :
Ast_413.Asttypes.closed_flag -> Ast_414.Asttypes.closed_flag =
function
| Ast_413.Asttypes.Closed -> Ast_414.Asttypes.Closed
| Ast_413.Asttypes.Open -> Ast_414.Asttypes.Open
and copy_label : Ast_413.Asttypes.label -> Ast_414.Asttypes.label =
fun x -> x
and copy_rec_flag : Ast_413.Asttypes.rec_flag -> Ast_414.Asttypes.rec_flag =
function
| Ast_413.Asttypes.Nonrecursive -> Ast_414.Asttypes.Nonrecursive
| Ast_413.Asttypes.Recursive -> Ast_414.Asttypes.Recursive
and copy_constant : Ast_413.Parsetree.constant -> Ast_414.Parsetree.constant
=
function
| Ast_413.Parsetree.Pconst_integer (x0, x1) ->
Ast_414.Parsetree.Pconst_integer (x0, (Option.map (fun x -> x) x1))
| Ast_413.Parsetree.Pconst_char x0 -> Ast_414.Parsetree.Pconst_char x0
| Ast_413.Parsetree.Pconst_string (x0, x1, x2) ->
Ast_414.Parsetree.Pconst_string
(x0, (copy_location x1), (Option.map (fun x -> x) x2))
| Ast_413.Parsetree.Pconst_float (x0, x1) ->
Ast_414.Parsetree.Pconst_float (x0, (Option.map (fun x -> x) x1))
and copy_Longident_t : Longident.t -> Longident.t =
function
| Longident.Lident x0 -> Longident.Lident x0
| Longident.Ldot (x0, x1) -> Longident.Ldot ((copy_Longident_t x0), x1)
| Longident.Lapply (x0, x1) ->
Longident.Lapply ((copy_Longident_t x0), (copy_Longident_t x1))
and copy_loc :
'f0 'g0 .
('f0 -> 'g0) -> 'f0 Ast_413.Asttypes.loc -> 'g0 Ast_414.Asttypes.loc
=
fun f0 ->
fun { Ast_413.Asttypes.txt = txt; Ast_413.Asttypes.loc = loc } ->
{
Ast_414.Asttypes.txt = (f0 txt);
Ast_414.Asttypes.loc = (copy_location loc)
}
and copy_location : Location.t -> Location.t =
fun
{ Location.loc_start = loc_start; Location.loc_end = loc_end;
Location.loc_ghost = loc_ghost }
->
{
Location.loc_start = (copy_position loc_start);
Location.loc_end = (copy_position loc_end);
Location.loc_ghost = loc_ghost
}
and copy_position : Lexing.position -> Lexing.position =
fun
{ Lexing.pos_fname = pos_fname; Lexing.pos_lnum = pos_lnum;
Lexing.pos_bol = pos_bol; Lexing.pos_cnum = pos_cnum }
->
{
Lexing.pos_fname = pos_fname;
Lexing.pos_lnum = pos_lnum;
Lexing.pos_bol = pos_bol;
Lexing.pos_cnum = pos_cnum
}
| null | https://raw.githubusercontent.com/reasonml/reason/4f6ff7616bfa699059d642a3d16d8905d83555f6/src/vendored-omp/src/migrate_parsetree_413_414_migrate.ml | ocaml | open Stdlib0
module From = Ast_413
module To = Ast_414
let rec copy_out_type_extension :
Ast_413.Outcometree.out_type_extension ->
Ast_414.Outcometree.out_type_extension
=
fun
{ Ast_413.Outcometree.otyext_name = otyext_name;
Ast_413.Outcometree.otyext_params = otyext_params;
Ast_413.Outcometree.otyext_constructors = otyext_constructors;
Ast_413.Outcometree.otyext_private = otyext_private }
->
{
Ast_414.Outcometree.otyext_name = otyext_name;
Ast_414.Outcometree.otyext_params =
(List.map (fun x -> x) otyext_params);
Ast_414.Outcometree.otyext_constructors =
(List.map
(fun x ->
let (x0, x1, x2) = x in
let x1 = (List.map copy_out_type x1) in
let x2 = (Option.map copy_out_type x2) in
Ast_414.Outcometree.{ ocstr_name = x0; ocstr_args = x1; ocstr_return_type = x2 })
otyext_constructors);
Ast_414.Outcometree.otyext_private = (copy_private_flag otyext_private)
}
and copy_out_phrase :
Ast_413.Outcometree.out_phrase -> Ast_414.Outcometree.out_phrase =
function
| Ast_413.Outcometree.Ophr_eval (x0, x1) ->
Ast_414.Outcometree.Ophr_eval ((copy_out_value x0), (copy_out_type x1))
| Ast_413.Outcometree.Ophr_signature x0 ->
Ast_414.Outcometree.Ophr_signature
(List.map
(fun x ->
let (x0, x1) = x in
((copy_out_sig_item x0), (Option.map copy_out_value x1))) x0)
| Ast_413.Outcometree.Ophr_exception x0 ->
Ast_414.Outcometree.Ophr_exception
(let (x0, x1) = x0 in (x0, (copy_out_value x1)))
and copy_out_sig_item :
Ast_413.Outcometree.out_sig_item -> Ast_414.Outcometree.out_sig_item =
function
| Ast_413.Outcometree.Osig_class (x0, x1, x2, x3, x4) ->
Ast_414.Outcometree.Osig_class
(x0, x1, (List.map copy_out_type_param x2), (copy_out_class_type x3),
(copy_out_rec_status x4))
| Ast_413.Outcometree.Osig_class_type (x0, x1, x2, x3, x4) ->
Ast_414.Outcometree.Osig_class_type
(x0, x1, (List.map copy_out_type_param x2), (copy_out_class_type x3),
(copy_out_rec_status x4))
| Ast_413.Outcometree.Osig_typext (x0, x1) ->
Ast_414.Outcometree.Osig_typext
((copy_out_extension_constructor x0), (copy_out_ext_status x1))
| Ast_413.Outcometree.Osig_modtype (x0, x1) ->
Ast_414.Outcometree.Osig_modtype (x0, (copy_out_module_type x1))
| Ast_413.Outcometree.Osig_module (x0, x1, x2) ->
Ast_414.Outcometree.Osig_module
(x0, (copy_out_module_type x1), (copy_out_rec_status x2))
| Ast_413.Outcometree.Osig_type (x0, x1) ->
Ast_414.Outcometree.Osig_type
((copy_out_type_decl x0), (copy_out_rec_status x1))
| Ast_413.Outcometree.Osig_value x0 ->
Ast_414.Outcometree.Osig_value (copy_out_val_decl x0)
| Ast_413.Outcometree.Osig_ellipsis -> Ast_414.Outcometree.Osig_ellipsis
and copy_out_val_decl :
Ast_413.Outcometree.out_val_decl -> Ast_414.Outcometree.out_val_decl =
fun
{ Ast_413.Outcometree.oval_name = oval_name;
Ast_413.Outcometree.oval_type = oval_type;
Ast_413.Outcometree.oval_prims = oval_prims;
Ast_413.Outcometree.oval_attributes = oval_attributes }
->
{
Ast_414.Outcometree.oval_name = oval_name;
Ast_414.Outcometree.oval_type = (copy_out_type oval_type);
Ast_414.Outcometree.oval_prims = (List.map (fun x -> x) oval_prims);
Ast_414.Outcometree.oval_attributes =
(List.map copy_out_attribute oval_attributes)
}
and copy_out_type_decl :
Ast_413.Outcometree.out_type_decl -> Ast_414.Outcometree.out_type_decl =
fun
{ Ast_413.Outcometree.otype_name = otype_name;
Ast_413.Outcometree.otype_params = otype_params;
Ast_413.Outcometree.otype_type = otype_type;
Ast_413.Outcometree.otype_private = otype_private;
Ast_413.Outcometree.otype_immediate = otype_immediate;
Ast_413.Outcometree.otype_unboxed = otype_unboxed;
Ast_413.Outcometree.otype_cstrs = otype_cstrs }
->
{
Ast_414.Outcometree.otype_name = otype_name;
Ast_414.Outcometree.otype_params =
(List.map copy_out_type_param otype_params);
Ast_414.Outcometree.otype_type = (copy_out_type otype_type);
Ast_414.Outcometree.otype_private = (copy_private_flag otype_private);
Ast_414.Outcometree.otype_immediate =
(copy_Type_immediacy_t otype_immediate);
Ast_414.Outcometree.otype_unboxed = otype_unboxed;
Ast_414.Outcometree.otype_cstrs =
(List.map
(fun x ->
let (x0, x1) = x in ((copy_out_type x0), (copy_out_type x1)))
otype_cstrs)
}
and copy_Type_immediacy_t :
Ast_413.Type_immediacy.t -> Ast_414.Type_immediacy.t =
function
| Ast_413.Type_immediacy.Unknown -> Ast_414.Type_immediacy.Unknown
| Ast_413.Type_immediacy.Always -> Ast_414.Type_immediacy.Always
| Ast_413.Type_immediacy.Always_on_64bits ->
Ast_414.Type_immediacy.Always_on_64bits
and copy_out_module_type :
Ast_413.Outcometree.out_module_type -> Ast_414.Outcometree.out_module_type
=
function
| Ast_413.Outcometree.Omty_abstract -> Ast_414.Outcometree.Omty_abstract
| Ast_413.Outcometree.Omty_functor (x0, x1) ->
Ast_414.Outcometree.Omty_functor
((Option.map
(fun x ->
let (x0, x1) = x in
((Option.map (fun x -> x) x0), (copy_out_module_type x1))) x0),
(copy_out_module_type x1))
| Ast_413.Outcometree.Omty_ident x0 ->
Ast_414.Outcometree.Omty_ident (copy_out_ident x0)
| Ast_413.Outcometree.Omty_signature x0 ->
Ast_414.Outcometree.Omty_signature (List.map copy_out_sig_item x0)
| Ast_413.Outcometree.Omty_alias x0 ->
Ast_414.Outcometree.Omty_alias (copy_out_ident x0)
and copy_out_ext_status :
Ast_413.Outcometree.out_ext_status -> Ast_414.Outcometree.out_ext_status =
function
| Ast_413.Outcometree.Oext_first -> Ast_414.Outcometree.Oext_first
| Ast_413.Outcometree.Oext_next -> Ast_414.Outcometree.Oext_next
| Ast_413.Outcometree.Oext_exception -> Ast_414.Outcometree.Oext_exception
and copy_out_extension_constructor :
Ast_413.Outcometree.out_extension_constructor ->
Ast_414.Outcometree.out_extension_constructor
=
fun
{ Ast_413.Outcometree.oext_name = oext_name;
Ast_413.Outcometree.oext_type_name = oext_type_name;
Ast_413.Outcometree.oext_type_params = oext_type_params;
Ast_413.Outcometree.oext_args = oext_args;
Ast_413.Outcometree.oext_ret_type = oext_ret_type;
Ast_413.Outcometree.oext_private = oext_private }
->
{
Ast_414.Outcometree.oext_name = oext_name;
Ast_414.Outcometree.oext_type_name = oext_type_name;
Ast_414.Outcometree.oext_type_params =
(List.map (fun x -> x) oext_type_params);
Ast_414.Outcometree.oext_args = (List.map copy_out_type oext_args);
Ast_414.Outcometree.oext_ret_type =
(Option.map copy_out_type oext_ret_type);
Ast_414.Outcometree.oext_private = (copy_private_flag oext_private)
}
and copy_out_rec_status :
Ast_413.Outcometree.out_rec_status -> Ast_414.Outcometree.out_rec_status =
function
| Ast_413.Outcometree.Orec_not -> Ast_414.Outcometree.Orec_not
| Ast_413.Outcometree.Orec_first -> Ast_414.Outcometree.Orec_first
| Ast_413.Outcometree.Orec_next -> Ast_414.Outcometree.Orec_next
and copy_out_class_type :
Ast_413.Outcometree.out_class_type -> Ast_414.Outcometree.out_class_type =
function
| Ast_413.Outcometree.Octy_constr (x0, x1) ->
Ast_414.Outcometree.Octy_constr
((copy_out_ident x0), (List.map copy_out_type x1))
| Ast_413.Outcometree.Octy_arrow (x0, x1, x2) ->
Ast_414.Outcometree.Octy_arrow
(x0, (copy_out_type x1), (copy_out_class_type x2))
| Ast_413.Outcometree.Octy_signature (x0, x1) ->
Ast_414.Outcometree.Octy_signature
((Option.map copy_out_type x0),
(List.map copy_out_class_sig_item x1))
and copy_out_class_sig_item :
Ast_413.Outcometree.out_class_sig_item ->
Ast_414.Outcometree.out_class_sig_item
=
function
| Ast_413.Outcometree.Ocsg_constraint (x0, x1) ->
Ast_414.Outcometree.Ocsg_constraint
((copy_out_type x0), (copy_out_type x1))
| Ast_413.Outcometree.Ocsg_method (x0, x1, x2, x3) ->
Ast_414.Outcometree.Ocsg_method (x0, x1, x2, (copy_out_type x3))
| Ast_413.Outcometree.Ocsg_value (x0, x1, x2, x3) ->
Ast_414.Outcometree.Ocsg_value (x0, x1, x2, (copy_out_type x3))
and copy_out_type_param :
Ast_413.Outcometree.out_type_param -> Ast_414.Outcometree.out_type_param =
fun x ->
let (x0, x1) = x in
(x0, (let (x0, x1) = x1 in ((copy_variance x0), (copy_injectivity x1))))
and copy_out_type :
Ast_413.Outcometree.out_type -> Ast_414.Outcometree.out_type =
function
| Ast_413.Outcometree.Otyp_abstract -> Ast_414.Outcometree.Otyp_abstract
| Ast_413.Outcometree.Otyp_open -> Ast_414.Outcometree.Otyp_open
| Ast_413.Outcometree.Otyp_alias (x0, x1) ->
Ast_414.Outcometree.Otyp_alias ((copy_out_type x0), x1)
| Ast_413.Outcometree.Otyp_arrow (x0, x1, x2) ->
Ast_414.Outcometree.Otyp_arrow
(x0, (copy_out_type x1), (copy_out_type x2))
| Ast_413.Outcometree.Otyp_class (x0, x1, x2) ->
Ast_414.Outcometree.Otyp_class
(x0, (copy_out_ident x1), (List.map copy_out_type x2))
| Ast_413.Outcometree.Otyp_constr (x0, x1) ->
Ast_414.Outcometree.Otyp_constr
((copy_out_ident x0), (List.map copy_out_type x1))
| Ast_413.Outcometree.Otyp_manifest (x0, x1) ->
Ast_414.Outcometree.Otyp_manifest
((copy_out_type x0), (copy_out_type x1))
| Ast_413.Outcometree.Otyp_object (x0, x1) ->
Ast_414.Outcometree.Otyp_object
((List.map (fun x -> let (x0, x1) = x in (x0, (copy_out_type x1))) x0),
(Option.map (fun x -> x) x1))
| Ast_413.Outcometree.Otyp_record x0 ->
Ast_414.Outcometree.Otyp_record
(List.map
(fun x -> let (x0, x1, x2) = x in (x0, x1, (copy_out_type x2))) x0)
| Ast_413.Outcometree.Otyp_stuff x0 -> Ast_414.Outcometree.Otyp_stuff x0
| Ast_413.Outcometree.Otyp_sum x0 ->
Ast_414.Outcometree.Otyp_sum
(List.map
(fun x ->
let (x0, x1, x2) = x in
let x1 = (List.map copy_out_type x1) in
let x2 = (Option.map copy_out_type x2) in
Ast_414.Outcometree.{ ocstr_name = x0; ocstr_args = x1; ocstr_return_type = x2 })
x0)
| Ast_413.Outcometree.Otyp_tuple x0 ->
Ast_414.Outcometree.Otyp_tuple (List.map copy_out_type x0)
| Ast_413.Outcometree.Otyp_var (x0, x1) ->
Ast_414.Outcometree.Otyp_var (x0, x1)
| Ast_413.Outcometree.Otyp_variant (x0, x1, x2, x3) ->
Ast_414.Outcometree.Otyp_variant
(x0, (copy_out_variant x1), x2,
(Option.map (fun x -> List.map (fun x -> x) x) x3))
| Ast_413.Outcometree.Otyp_poly (x0, x1) ->
Ast_414.Outcometree.Otyp_poly
((List.map (fun x -> x) x0), (copy_out_type x1))
| Ast_413.Outcometree.Otyp_module (x0, x1) ->
Ast_414.Outcometree.Otyp_module
((copy_out_ident x0), (List.map (fun (x, y) -> x, copy_out_type y) x1))
| Ast_413.Outcometree.Otyp_attribute (x0, x1) ->
Ast_414.Outcometree.Otyp_attribute
((copy_out_type x0), (copy_out_attribute x1))
and copy_out_attribute :
Ast_413.Outcometree.out_attribute -> Ast_414.Outcometree.out_attribute =
fun { Ast_413.Outcometree.oattr_name = oattr_name } ->
{ Ast_414.Outcometree.oattr_name = oattr_name }
and copy_out_variant :
Ast_413.Outcometree.out_variant -> Ast_414.Outcometree.out_variant =
function
| Ast_413.Outcometree.Ovar_fields x0 ->
Ast_414.Outcometree.Ovar_fields
(List.map
(fun x ->
let (x0, x1, x2) = x in (x0, x1, (List.map copy_out_type x2)))
x0)
| Ast_413.Outcometree.Ovar_typ x0 ->
Ast_414.Outcometree.Ovar_typ (copy_out_type x0)
and copy_out_value :
Ast_413.Outcometree.out_value -> Ast_414.Outcometree.out_value =
function
| Ast_413.Outcometree.Oval_array x0 ->
Ast_414.Outcometree.Oval_array (List.map copy_out_value x0)
| Ast_413.Outcometree.Oval_char x0 -> Ast_414.Outcometree.Oval_char x0
| Ast_413.Outcometree.Oval_constr (x0, x1) ->
Ast_414.Outcometree.Oval_constr
((copy_out_ident x0), (List.map copy_out_value x1))
| Ast_413.Outcometree.Oval_ellipsis -> Ast_414.Outcometree.Oval_ellipsis
| Ast_413.Outcometree.Oval_float x0 -> Ast_414.Outcometree.Oval_float x0
| Ast_413.Outcometree.Oval_int x0 -> Ast_414.Outcometree.Oval_int x0
| Ast_413.Outcometree.Oval_int32 x0 -> Ast_414.Outcometree.Oval_int32 x0
| Ast_413.Outcometree.Oval_int64 x0 -> Ast_414.Outcometree.Oval_int64 x0
| Ast_413.Outcometree.Oval_nativeint x0 ->
Ast_414.Outcometree.Oval_nativeint x0
| Ast_413.Outcometree.Oval_list x0 ->
Ast_414.Outcometree.Oval_list (List.map copy_out_value x0)
| Ast_413.Outcometree.Oval_printer x0 ->
Ast_414.Outcometree.Oval_printer x0
| Ast_413.Outcometree.Oval_record x0 ->
Ast_414.Outcometree.Oval_record
(List.map
(fun x ->
let (x0, x1) = x in ((copy_out_ident x0), (copy_out_value x1)))
x0)
| Ast_413.Outcometree.Oval_string (x0, x1, x2) ->
Ast_414.Outcometree.Oval_string (x0, x1, (copy_out_string x2))
| Ast_413.Outcometree.Oval_stuff x0 -> Ast_414.Outcometree.Oval_stuff x0
| Ast_413.Outcometree.Oval_tuple x0 ->
Ast_414.Outcometree.Oval_tuple (List.map copy_out_value x0)
| Ast_413.Outcometree.Oval_variant (x0, x1) ->
Ast_414.Outcometree.Oval_variant (x0, (Option.map copy_out_value x1))
and copy_out_string :
Ast_413.Outcometree.out_string -> Ast_414.Outcometree.out_string =
function
| Ast_413.Outcometree.Ostr_string -> Ast_414.Outcometree.Ostr_string
| Ast_413.Outcometree.Ostr_bytes -> Ast_414.Outcometree.Ostr_bytes
and copy_out_ident :
Ast_413.Outcometree.out_ident -> Ast_414.Outcometree.out_ident =
function
| Ast_413.Outcometree.Oide_apply (x0, x1) ->
Ast_414.Outcometree.Oide_apply
((copy_out_ident x0), (copy_out_ident x1))
| Ast_413.Outcometree.Oide_dot (x0, x1) ->
Ast_414.Outcometree.Oide_dot ((copy_out_ident x0), x1)
| Ast_413.Outcometree.Oide_ident x0 ->
Ast_414.Outcometree.Oide_ident (copy_out_name x0)
and copy_out_name :
Ast_413.Outcometree.out_name -> Ast_414.Outcometree.out_name =
fun { Ast_413.Outcometree.printed_name = printed_name } ->
{ Ast_414.Outcometree.printed_name = printed_name }
and copy_toplevel_phrase :
Ast_413.Parsetree.toplevel_phrase -> Ast_414.Parsetree.toplevel_phrase =
function
| Ast_413.Parsetree.Ptop_def x0 ->
Ast_414.Parsetree.Ptop_def (copy_structure x0)
| Ast_413.Parsetree.Ptop_dir x0 ->
Ast_414.Parsetree.Ptop_dir (copy_toplevel_directive x0)
and copy_toplevel_directive :
Ast_413.Parsetree.toplevel_directive ->
Ast_414.Parsetree.toplevel_directive
=
fun
{ Ast_413.Parsetree.pdir_name = pdir_name;
Ast_413.Parsetree.pdir_arg = pdir_arg;
Ast_413.Parsetree.pdir_loc = pdir_loc }
->
{
Ast_414.Parsetree.pdir_name = (copy_loc (fun x -> x) pdir_name);
Ast_414.Parsetree.pdir_arg =
(Option.map copy_directive_argument pdir_arg);
Ast_414.Parsetree.pdir_loc = (copy_location pdir_loc)
}
and copy_directive_argument :
Ast_413.Parsetree.directive_argument ->
Ast_414.Parsetree.directive_argument
=
fun
{ Ast_413.Parsetree.pdira_desc = pdira_desc;
Ast_413.Parsetree.pdira_loc = pdira_loc }
->
{
Ast_414.Parsetree.pdira_desc =
(copy_directive_argument_desc pdira_desc);
Ast_414.Parsetree.pdira_loc = (copy_location pdira_loc)
}
and copy_directive_argument_desc :
Ast_413.Parsetree.directive_argument_desc ->
Ast_414.Parsetree.directive_argument_desc
=
function
| Ast_413.Parsetree.Pdir_string x0 -> Ast_414.Parsetree.Pdir_string x0
| Ast_413.Parsetree.Pdir_int (x0, x1) ->
Ast_414.Parsetree.Pdir_int (x0, (Option.map (fun x -> x) x1))
| Ast_413.Parsetree.Pdir_ident x0 ->
Ast_414.Parsetree.Pdir_ident (copy_Longident_t x0)
| Ast_413.Parsetree.Pdir_bool x0 -> Ast_414.Parsetree.Pdir_bool x0
and copy_expression :
Ast_413.Parsetree.expression -> Ast_414.Parsetree.expression =
fun
{ Ast_413.Parsetree.pexp_desc = pexp_desc;
Ast_413.Parsetree.pexp_loc = pexp_loc;
Ast_413.Parsetree.pexp_loc_stack = pexp_loc_stack;
Ast_413.Parsetree.pexp_attributes = pexp_attributes }
->
{
Ast_414.Parsetree.pexp_desc = (copy_expression_desc pexp_desc);
Ast_414.Parsetree.pexp_loc = (copy_location pexp_loc);
Ast_414.Parsetree.pexp_loc_stack = (copy_location_stack pexp_loc_stack);
Ast_414.Parsetree.pexp_attributes = (copy_attributes pexp_attributes)
}
and copy_expression_desc :
Ast_413.Parsetree.expression_desc -> Ast_414.Parsetree.expression_desc =
function
| Ast_413.Parsetree.Pexp_ident x0 ->
Ast_414.Parsetree.Pexp_ident (copy_loc copy_Longident_t x0)
| Ast_413.Parsetree.Pexp_constant x0 ->
Ast_414.Parsetree.Pexp_constant (copy_constant x0)
| Ast_413.Parsetree.Pexp_let (x0, x1, x2) ->
Ast_414.Parsetree.Pexp_let
((copy_rec_flag x0), (List.map copy_value_binding x1),
(copy_expression x2))
| Ast_413.Parsetree.Pexp_function x0 ->
Ast_414.Parsetree.Pexp_function (List.map copy_case x0)
| Ast_413.Parsetree.Pexp_fun (x0, x1, x2, x3) ->
Ast_414.Parsetree.Pexp_fun
((copy_arg_label x0), (Option.map copy_expression x1),
(copy_pattern x2), (copy_expression x3))
| Ast_413.Parsetree.Pexp_apply (x0, x1) ->
Ast_414.Parsetree.Pexp_apply
((copy_expression x0),
(List.map
(fun x ->
let (x0, x1) = x in
((copy_arg_label x0), (copy_expression x1))) x1))
| Ast_413.Parsetree.Pexp_match (x0, x1) ->
Ast_414.Parsetree.Pexp_match
((copy_expression x0), (List.map copy_case x1))
| Ast_413.Parsetree.Pexp_try (x0, x1) ->
Ast_414.Parsetree.Pexp_try
((copy_expression x0), (List.map copy_case x1))
| Ast_413.Parsetree.Pexp_tuple x0 ->
Ast_414.Parsetree.Pexp_tuple (List.map copy_expression x0)
| Ast_413.Parsetree.Pexp_construct (x0, x1) ->
Ast_414.Parsetree.Pexp_construct
((copy_loc copy_Longident_t x0), (Option.map copy_expression x1))
| Ast_413.Parsetree.Pexp_variant (x0, x1) ->
Ast_414.Parsetree.Pexp_variant
((copy_label x0), (Option.map copy_expression x1))
| Ast_413.Parsetree.Pexp_record (x0, x1) ->
Ast_414.Parsetree.Pexp_record
((List.map
(fun x ->
let (x0, x1) = x in
((copy_loc copy_Longident_t x0), (copy_expression x1))) x0),
(Option.map copy_expression x1))
| Ast_413.Parsetree.Pexp_field (x0, x1) ->
Ast_414.Parsetree.Pexp_field
((copy_expression x0), (copy_loc copy_Longident_t x1))
| Ast_413.Parsetree.Pexp_setfield (x0, x1, x2) ->
Ast_414.Parsetree.Pexp_setfield
((copy_expression x0), (copy_loc copy_Longident_t x1),
(copy_expression x2))
| Ast_413.Parsetree.Pexp_array x0 ->
Ast_414.Parsetree.Pexp_array (List.map copy_expression x0)
| Ast_413.Parsetree.Pexp_ifthenelse (x0, x1, x2) ->
Ast_414.Parsetree.Pexp_ifthenelse
((copy_expression x0), (copy_expression x1),
(Option.map copy_expression x2))
| Ast_413.Parsetree.Pexp_sequence (x0, x1) ->
Ast_414.Parsetree.Pexp_sequence
((copy_expression x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_while (x0, x1) ->
Ast_414.Parsetree.Pexp_while
((copy_expression x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_for (x0, x1, x2, x3, x4) ->
Ast_414.Parsetree.Pexp_for
((copy_pattern x0), (copy_expression x1), (copy_expression x2),
(copy_direction_flag x3), (copy_expression x4))
| Ast_413.Parsetree.Pexp_constraint (x0, x1) ->
Ast_414.Parsetree.Pexp_constraint
((copy_expression x0), (copy_core_type x1))
| Ast_413.Parsetree.Pexp_coerce (x0, x1, x2) ->
Ast_414.Parsetree.Pexp_coerce
((copy_expression x0), (Option.map copy_core_type x1),
(copy_core_type x2))
| Ast_413.Parsetree.Pexp_send (x0, x1) ->
Ast_414.Parsetree.Pexp_send
((copy_expression x0), (copy_loc copy_label x1))
| Ast_413.Parsetree.Pexp_new x0 ->
Ast_414.Parsetree.Pexp_new (copy_loc copy_Longident_t x0)
| Ast_413.Parsetree.Pexp_setinstvar (x0, x1) ->
Ast_414.Parsetree.Pexp_setinstvar
((copy_loc copy_label x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_override x0 ->
Ast_414.Parsetree.Pexp_override
(List.map
(fun x ->
let (x0, x1) = x in
((copy_loc copy_label x0), (copy_expression x1))) x0)
| Ast_413.Parsetree.Pexp_letmodule (x0, x1, x2) ->
Ast_414.Parsetree.Pexp_letmodule
((copy_loc (fun x -> Option.map (fun x -> x) x) x0),
(copy_module_expr x1), (copy_expression x2))
| Ast_413.Parsetree.Pexp_letexception (x0, x1) ->
Ast_414.Parsetree.Pexp_letexception
((copy_extension_constructor x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_assert x0 ->
Ast_414.Parsetree.Pexp_assert (copy_expression x0)
| Ast_413.Parsetree.Pexp_lazy x0 ->
Ast_414.Parsetree.Pexp_lazy (copy_expression x0)
| Ast_413.Parsetree.Pexp_poly (x0, x1) ->
Ast_414.Parsetree.Pexp_poly
((copy_expression x0), (Option.map copy_core_type x1))
| Ast_413.Parsetree.Pexp_object x0 ->
Ast_414.Parsetree.Pexp_object (copy_class_structure x0)
| Ast_413.Parsetree.Pexp_newtype (x0, x1) ->
Ast_414.Parsetree.Pexp_newtype
((copy_loc (fun x -> x) x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_pack x0 ->
Ast_414.Parsetree.Pexp_pack (copy_module_expr x0)
| Ast_413.Parsetree.Pexp_open (x0, x1) ->
Ast_414.Parsetree.Pexp_open
((copy_open_declaration x0), (copy_expression x1))
| Ast_413.Parsetree.Pexp_letop x0 ->
Ast_414.Parsetree.Pexp_letop (copy_letop x0)
| Ast_413.Parsetree.Pexp_extension x0 ->
Ast_414.Parsetree.Pexp_extension (copy_extension x0)
| Ast_413.Parsetree.Pexp_unreachable -> Ast_414.Parsetree.Pexp_unreachable
and copy_letop : Ast_413.Parsetree.letop -> Ast_414.Parsetree.letop =
fun
{ Ast_413.Parsetree.let_ = let_; Ast_413.Parsetree.ands = ands;
Ast_413.Parsetree.body = body }
->
{
Ast_414.Parsetree.let_ = (copy_binding_op let_);
Ast_414.Parsetree.ands = (List.map copy_binding_op ands);
Ast_414.Parsetree.body = (copy_expression body)
}
and copy_binding_op :
Ast_413.Parsetree.binding_op -> Ast_414.Parsetree.binding_op =
fun
{ Ast_413.Parsetree.pbop_op = pbop_op;
Ast_413.Parsetree.pbop_pat = pbop_pat;
Ast_413.Parsetree.pbop_exp = pbop_exp;
Ast_413.Parsetree.pbop_loc = pbop_loc }
->
{
Ast_414.Parsetree.pbop_op = (copy_loc (fun x -> x) pbop_op);
Ast_414.Parsetree.pbop_pat = (copy_pattern pbop_pat);
Ast_414.Parsetree.pbop_exp = (copy_expression pbop_exp);
Ast_414.Parsetree.pbop_loc = (copy_location pbop_loc)
}
and copy_direction_flag :
Ast_413.Asttypes.direction_flag -> Ast_414.Asttypes.direction_flag =
function
| Ast_413.Asttypes.Upto -> Ast_414.Asttypes.Upto
| Ast_413.Asttypes.Downto -> Ast_414.Asttypes.Downto
and copy_case : Ast_413.Parsetree.case -> Ast_414.Parsetree.case =
fun
{ Ast_413.Parsetree.pc_lhs = pc_lhs;
Ast_413.Parsetree.pc_guard = pc_guard;
Ast_413.Parsetree.pc_rhs = pc_rhs }
->
{
Ast_414.Parsetree.pc_lhs = (copy_pattern pc_lhs);
Ast_414.Parsetree.pc_guard = (Option.map copy_expression pc_guard);
Ast_414.Parsetree.pc_rhs = (copy_expression pc_rhs)
}
and copy_value_binding :
Ast_413.Parsetree.value_binding -> Ast_414.Parsetree.value_binding =
fun
{ Ast_413.Parsetree.pvb_pat = pvb_pat;
Ast_413.Parsetree.pvb_expr = pvb_expr;
Ast_413.Parsetree.pvb_attributes = pvb_attributes;
Ast_413.Parsetree.pvb_loc = pvb_loc }
->
{
Ast_414.Parsetree.pvb_pat = (copy_pattern pvb_pat);
Ast_414.Parsetree.pvb_expr = (copy_expression pvb_expr);
Ast_414.Parsetree.pvb_attributes = (copy_attributes pvb_attributes);
Ast_414.Parsetree.pvb_loc = (copy_location pvb_loc)
}
and copy_pattern : Ast_413.Parsetree.pattern -> Ast_414.Parsetree.pattern =
fun
{ Ast_413.Parsetree.ppat_desc = ppat_desc;
Ast_413.Parsetree.ppat_loc = ppat_loc;
Ast_413.Parsetree.ppat_loc_stack = ppat_loc_stack;
Ast_413.Parsetree.ppat_attributes = ppat_attributes }
->
{
Ast_414.Parsetree.ppat_desc = (copy_pattern_desc ppat_desc);
Ast_414.Parsetree.ppat_loc = (copy_location ppat_loc);
Ast_414.Parsetree.ppat_loc_stack = (copy_location_stack ppat_loc_stack);
Ast_414.Parsetree.ppat_attributes = (copy_attributes ppat_attributes)
}
and copy_pattern_desc :
Ast_413.Parsetree.pattern_desc -> Ast_414.Parsetree.pattern_desc =
function
| Ast_413.Parsetree.Ppat_any -> Ast_414.Parsetree.Ppat_any
| Ast_413.Parsetree.Ppat_var x0 ->
Ast_414.Parsetree.Ppat_var (copy_loc (fun x -> x) x0)
| Ast_413.Parsetree.Ppat_alias (x0, x1) ->
Ast_414.Parsetree.Ppat_alias
((copy_pattern x0), (copy_loc (fun x -> x) x1))
| Ast_413.Parsetree.Ppat_constant x0 ->
Ast_414.Parsetree.Ppat_constant (copy_constant x0)
| Ast_413.Parsetree.Ppat_interval (x0, x1) ->
Ast_414.Parsetree.Ppat_interval
((copy_constant x0), (copy_constant x1))
| Ast_413.Parsetree.Ppat_tuple x0 ->
Ast_414.Parsetree.Ppat_tuple (List.map copy_pattern x0)
| Ast_413.Parsetree.Ppat_construct (x0, x1) ->
Ast_414.Parsetree.Ppat_construct
((copy_loc copy_Longident_t x0), (Option.map (fun (x0, x1) -> x0, copy_pattern x1) x1))
| Ast_413.Parsetree.Ppat_variant (x0, x1) ->
Ast_414.Parsetree.Ppat_variant
((copy_label x0), (Option.map copy_pattern x1))
| Ast_413.Parsetree.Ppat_record (x0, x1) ->
Ast_414.Parsetree.Ppat_record
((List.map
(fun x ->
let (x0, x1) = x in
((copy_loc copy_Longident_t x0), (copy_pattern x1))) x0),
(copy_closed_flag x1))
| Ast_413.Parsetree.Ppat_array x0 ->
Ast_414.Parsetree.Ppat_array (List.map copy_pattern x0)
| Ast_413.Parsetree.Ppat_or (x0, x1) ->
Ast_414.Parsetree.Ppat_or ((copy_pattern x0), (copy_pattern x1))
| Ast_413.Parsetree.Ppat_constraint (x0, x1) ->
Ast_414.Parsetree.Ppat_constraint
((copy_pattern x0), (copy_core_type x1))
| Ast_413.Parsetree.Ppat_type x0 ->
Ast_414.Parsetree.Ppat_type (copy_loc copy_Longident_t x0)
| Ast_413.Parsetree.Ppat_lazy x0 ->
Ast_414.Parsetree.Ppat_lazy (copy_pattern x0)
| Ast_413.Parsetree.Ppat_unpack x0 ->
Ast_414.Parsetree.Ppat_unpack
(copy_loc (fun x -> Option.map (fun x -> x) x) x0)
| Ast_413.Parsetree.Ppat_exception x0 ->
Ast_414.Parsetree.Ppat_exception (copy_pattern x0)
| Ast_413.Parsetree.Ppat_extension x0 ->
Ast_414.Parsetree.Ppat_extension (copy_extension x0)
| Ast_413.Parsetree.Ppat_open (x0, x1) ->
Ast_414.Parsetree.Ppat_open
((copy_loc copy_Longident_t x0), (copy_pattern x1))
and copy_core_type :
Ast_413.Parsetree.core_type -> Ast_414.Parsetree.core_type =
fun
{ Ast_413.Parsetree.ptyp_desc = ptyp_desc;
Ast_413.Parsetree.ptyp_loc = ptyp_loc;
Ast_413.Parsetree.ptyp_loc_stack = ptyp_loc_stack;
Ast_413.Parsetree.ptyp_attributes = ptyp_attributes }
->
{
Ast_414.Parsetree.ptyp_desc = (copy_core_type_desc ptyp_desc);
Ast_414.Parsetree.ptyp_loc = (copy_location ptyp_loc);
Ast_414.Parsetree.ptyp_loc_stack = (copy_location_stack ptyp_loc_stack);
Ast_414.Parsetree.ptyp_attributes = (copy_attributes ptyp_attributes)
}
and copy_location_stack :
Ast_413.Parsetree.location_stack -> Ast_414.Parsetree.location_stack =
fun x -> List.map copy_location x
and copy_core_type_desc :
Ast_413.Parsetree.core_type_desc -> Ast_414.Parsetree.core_type_desc =
function
| Ast_413.Parsetree.Ptyp_any -> Ast_414.Parsetree.Ptyp_any
| Ast_413.Parsetree.Ptyp_var x0 -> Ast_414.Parsetree.Ptyp_var x0
| Ast_413.Parsetree.Ptyp_arrow (x0, x1, x2) ->
Ast_414.Parsetree.Ptyp_arrow
((copy_arg_label x0), (copy_core_type x1), (copy_core_type x2))
| Ast_413.Parsetree.Ptyp_tuple x0 ->
Ast_414.Parsetree.Ptyp_tuple (List.map copy_core_type x0)
| Ast_413.Parsetree.Ptyp_constr (x0, x1) ->
Ast_414.Parsetree.Ptyp_constr
((copy_loc copy_Longident_t x0), (List.map copy_core_type x1))
| Ast_413.Parsetree.Ptyp_object (x0, x1) ->
Ast_414.Parsetree.Ptyp_object
((List.map copy_object_field x0), (copy_closed_flag x1))
| Ast_413.Parsetree.Ptyp_class (x0, x1) ->
Ast_414.Parsetree.Ptyp_class
((copy_loc copy_Longident_t x0), (List.map copy_core_type x1))
| Ast_413.Parsetree.Ptyp_alias (x0, x1) ->
Ast_414.Parsetree.Ptyp_alias ((copy_core_type x0), x1)
| Ast_413.Parsetree.Ptyp_variant (x0, x1, x2) ->
Ast_414.Parsetree.Ptyp_variant
((List.map copy_row_field x0), (copy_closed_flag x1),
(Option.map (fun x -> List.map copy_label x) x2))
| Ast_413.Parsetree.Ptyp_poly (x0, x1) ->
Ast_414.Parsetree.Ptyp_poly
((List.map (fun x -> copy_loc (fun x -> x) x) x0),
(copy_core_type x1))
| Ast_413.Parsetree.Ptyp_package x0 ->
Ast_414.Parsetree.Ptyp_package (copy_package_type x0)
| Ast_413.Parsetree.Ptyp_extension x0 ->
Ast_414.Parsetree.Ptyp_extension (copy_extension x0)
and copy_package_type :
Ast_413.Parsetree.package_type -> Ast_414.Parsetree.package_type =
fun x ->
let (x0, x1) = x in
((copy_loc copy_Longident_t x0),
(List.map
(fun x ->
let (x0, x1) = x in
((copy_loc copy_Longident_t x0), (copy_core_type x1))) x1))
and copy_row_field :
Ast_413.Parsetree.row_field -> Ast_414.Parsetree.row_field =
fun
{ Ast_413.Parsetree.prf_desc = prf_desc;
Ast_413.Parsetree.prf_loc = prf_loc;
Ast_413.Parsetree.prf_attributes = prf_attributes }
->
{
Ast_414.Parsetree.prf_desc = (copy_row_field_desc prf_desc);
Ast_414.Parsetree.prf_loc = (copy_location prf_loc);
Ast_414.Parsetree.prf_attributes = (copy_attributes prf_attributes)
}
and copy_row_field_desc :
Ast_413.Parsetree.row_field_desc -> Ast_414.Parsetree.row_field_desc =
function
| Ast_413.Parsetree.Rtag (x0, x1, x2) ->
Ast_414.Parsetree.Rtag
((copy_loc copy_label x0), x1, (List.map copy_core_type x2))
| Ast_413.Parsetree.Rinherit x0 ->
Ast_414.Parsetree.Rinherit (copy_core_type x0)
and copy_object_field :
Ast_413.Parsetree.object_field -> Ast_414.Parsetree.object_field =
fun
{ Ast_413.Parsetree.pof_desc = pof_desc;
Ast_413.Parsetree.pof_loc = pof_loc;
Ast_413.Parsetree.pof_attributes = pof_attributes }
->
{
Ast_414.Parsetree.pof_desc = (copy_object_field_desc pof_desc);
Ast_414.Parsetree.pof_loc = (copy_location pof_loc);
Ast_414.Parsetree.pof_attributes = (copy_attributes pof_attributes)
}
and copy_attributes :
Ast_413.Parsetree.attributes -> Ast_414.Parsetree.attributes =
fun x -> List.map copy_attribute x
and copy_attribute :
Ast_413.Parsetree.attribute -> Ast_414.Parsetree.attribute =
fun
{ Ast_413.Parsetree.attr_name = attr_name;
Ast_413.Parsetree.attr_payload = attr_payload;
Ast_413.Parsetree.attr_loc = attr_loc }
->
{
Ast_414.Parsetree.attr_name = (copy_loc (fun x -> x) attr_name);
Ast_414.Parsetree.attr_payload = (copy_payload attr_payload);
Ast_414.Parsetree.attr_loc = (copy_location attr_loc)
}
and copy_payload : Ast_413.Parsetree.payload -> Ast_414.Parsetree.payload =
function
| Ast_413.Parsetree.PStr x0 -> Ast_414.Parsetree.PStr (copy_structure x0)
| Ast_413.Parsetree.PSig x0 -> Ast_414.Parsetree.PSig (copy_signature x0)
| Ast_413.Parsetree.PTyp x0 -> Ast_414.Parsetree.PTyp (copy_core_type x0)
| Ast_413.Parsetree.PPat (x0, x1) ->
Ast_414.Parsetree.PPat
((copy_pattern x0), (Option.map copy_expression x1))
and copy_structure :
Ast_413.Parsetree.structure -> Ast_414.Parsetree.structure =
fun x -> List.map copy_structure_item x
and copy_structure_item :
Ast_413.Parsetree.structure_item -> Ast_414.Parsetree.structure_item =
fun
{ Ast_413.Parsetree.pstr_desc = pstr_desc;
Ast_413.Parsetree.pstr_loc = pstr_loc }
->
{
Ast_414.Parsetree.pstr_desc = (copy_structure_item_desc pstr_desc);
Ast_414.Parsetree.pstr_loc = (copy_location pstr_loc)
}
and copy_structure_item_desc :
Ast_413.Parsetree.structure_item_desc ->
Ast_414.Parsetree.structure_item_desc
=
function
| Ast_413.Parsetree.Pstr_eval (x0, x1) ->
Ast_414.Parsetree.Pstr_eval
((copy_expression x0), (copy_attributes x1))
| Ast_413.Parsetree.Pstr_value (x0, x1) ->
Ast_414.Parsetree.Pstr_value
((copy_rec_flag x0), (List.map copy_value_binding x1))
| Ast_413.Parsetree.Pstr_primitive x0 ->
Ast_414.Parsetree.Pstr_primitive (copy_value_description x0)
| Ast_413.Parsetree.Pstr_type (x0, x1) ->
Ast_414.Parsetree.Pstr_type
((copy_rec_flag x0), (List.map copy_type_declaration x1))
| Ast_413.Parsetree.Pstr_typext x0 ->
Ast_414.Parsetree.Pstr_typext (copy_type_extension x0)
| Ast_413.Parsetree.Pstr_exception x0 ->
Ast_414.Parsetree.Pstr_exception (copy_type_exception x0)
| Ast_413.Parsetree.Pstr_module x0 ->
Ast_414.Parsetree.Pstr_module (copy_module_binding x0)
| Ast_413.Parsetree.Pstr_recmodule x0 ->
Ast_414.Parsetree.Pstr_recmodule (List.map copy_module_binding x0)
| Ast_413.Parsetree.Pstr_modtype x0 ->
Ast_414.Parsetree.Pstr_modtype (copy_module_type_declaration x0)
| Ast_413.Parsetree.Pstr_open x0 ->
Ast_414.Parsetree.Pstr_open (copy_open_declaration x0)
| Ast_413.Parsetree.Pstr_class x0 ->
Ast_414.Parsetree.Pstr_class (List.map copy_class_declaration x0)
| Ast_413.Parsetree.Pstr_class_type x0 ->
Ast_414.Parsetree.Pstr_class_type
(List.map copy_class_type_declaration x0)
| Ast_413.Parsetree.Pstr_include x0 ->
Ast_414.Parsetree.Pstr_include (copy_include_declaration x0)
| Ast_413.Parsetree.Pstr_attribute x0 ->
Ast_414.Parsetree.Pstr_attribute (copy_attribute x0)
| Ast_413.Parsetree.Pstr_extension (x0, x1) ->
Ast_414.Parsetree.Pstr_extension
((copy_extension x0), (copy_attributes x1))
and copy_include_declaration :
Ast_413.Parsetree.include_declaration ->
Ast_414.Parsetree.include_declaration
= fun x -> copy_include_infos copy_module_expr x
and copy_class_declaration :
Ast_413.Parsetree.class_declaration -> Ast_414.Parsetree.class_declaration
= fun x -> copy_class_infos copy_class_expr x
and copy_class_expr :
Ast_413.Parsetree.class_expr -> Ast_414.Parsetree.class_expr =
fun
{ Ast_413.Parsetree.pcl_desc = pcl_desc;
Ast_413.Parsetree.pcl_loc = pcl_loc;
Ast_413.Parsetree.pcl_attributes = pcl_attributes }
->
{
Ast_414.Parsetree.pcl_desc = (copy_class_expr_desc pcl_desc);
Ast_414.Parsetree.pcl_loc = (copy_location pcl_loc);
Ast_414.Parsetree.pcl_attributes = (copy_attributes pcl_attributes)
}
and copy_class_expr_desc :
Ast_413.Parsetree.class_expr_desc -> Ast_414.Parsetree.class_expr_desc =
function
| Ast_413.Parsetree.Pcl_constr (x0, x1) ->
Ast_414.Parsetree.Pcl_constr
((copy_loc copy_Longident_t x0), (List.map copy_core_type x1))
| Ast_413.Parsetree.Pcl_structure x0 ->
Ast_414.Parsetree.Pcl_structure (copy_class_structure x0)
| Ast_413.Parsetree.Pcl_fun (x0, x1, x2, x3) ->
Ast_414.Parsetree.Pcl_fun
((copy_arg_label x0), (Option.map copy_expression x1),
(copy_pattern x2), (copy_class_expr x3))
| Ast_413.Parsetree.Pcl_apply (x0, x1) ->
Ast_414.Parsetree.Pcl_apply
((copy_class_expr x0),
(List.map
(fun x ->
let (x0, x1) = x in
((copy_arg_label x0), (copy_expression x1))) x1))
| Ast_413.Parsetree.Pcl_let (x0, x1, x2) ->
Ast_414.Parsetree.Pcl_let
((copy_rec_flag x0), (List.map copy_value_binding x1),
(copy_class_expr x2))
| Ast_413.Parsetree.Pcl_constraint (x0, x1) ->
Ast_414.Parsetree.Pcl_constraint
((copy_class_expr x0), (copy_class_type x1))
| Ast_413.Parsetree.Pcl_extension x0 ->
Ast_414.Parsetree.Pcl_extension (copy_extension x0)
| Ast_413.Parsetree.Pcl_open (x0, x1) ->
Ast_414.Parsetree.Pcl_open
((copy_open_description x0), (copy_class_expr x1))
and copy_class_structure :
Ast_413.Parsetree.class_structure -> Ast_414.Parsetree.class_structure =
fun
{ Ast_413.Parsetree.pcstr_self = pcstr_self;
Ast_413.Parsetree.pcstr_fields = pcstr_fields }
->
{
Ast_414.Parsetree.pcstr_self = (copy_pattern pcstr_self);
Ast_414.Parsetree.pcstr_fields =
(List.map copy_class_field pcstr_fields)
}
and copy_class_field :
Ast_413.Parsetree.class_field -> Ast_414.Parsetree.class_field =
fun
{ Ast_413.Parsetree.pcf_desc = pcf_desc;
Ast_413.Parsetree.pcf_loc = pcf_loc;
Ast_413.Parsetree.pcf_attributes = pcf_attributes }
->
{
Ast_414.Parsetree.pcf_desc = (copy_class_field_desc pcf_desc);
Ast_414.Parsetree.pcf_loc = (copy_location pcf_loc);
Ast_414.Parsetree.pcf_attributes = (copy_attributes pcf_attributes)
}
and copy_class_field_desc :
Ast_413.Parsetree.class_field_desc -> Ast_414.Parsetree.class_field_desc =
function
| Ast_413.Parsetree.Pcf_inherit (x0, x1, x2) ->
Ast_414.Parsetree.Pcf_inherit
((copy_override_flag x0), (copy_class_expr x1),
(Option.map (fun x -> copy_loc (fun x -> x) x) x2))
| Ast_413.Parsetree.Pcf_val x0 ->
Ast_414.Parsetree.Pcf_val
(let (x0, x1, x2) = x0 in
((copy_loc copy_label x0), (copy_mutable_flag x1),
(copy_class_field_kind x2)))
| Ast_413.Parsetree.Pcf_method x0 ->
Ast_414.Parsetree.Pcf_method
(let (x0, x1, x2) = x0 in
((copy_loc copy_label x0), (copy_private_flag x1),
(copy_class_field_kind x2)))
| Ast_413.Parsetree.Pcf_constraint x0 ->
Ast_414.Parsetree.Pcf_constraint
(let (x0, x1) = x0 in ((copy_core_type x0), (copy_core_type x1)))
| Ast_413.Parsetree.Pcf_initializer x0 ->
Ast_414.Parsetree.Pcf_initializer (copy_expression x0)
| Ast_413.Parsetree.Pcf_attribute x0 ->
Ast_414.Parsetree.Pcf_attribute (copy_attribute x0)
| Ast_413.Parsetree.Pcf_extension x0 ->
Ast_414.Parsetree.Pcf_extension (copy_extension x0)
and copy_class_field_kind :
Ast_413.Parsetree.class_field_kind -> Ast_414.Parsetree.class_field_kind =
function
| Ast_413.Parsetree.Cfk_virtual x0 ->
Ast_414.Parsetree.Cfk_virtual (copy_core_type x0)
| Ast_413.Parsetree.Cfk_concrete (x0, x1) ->
Ast_414.Parsetree.Cfk_concrete
((copy_override_flag x0), (copy_expression x1))
and copy_open_declaration :
Ast_413.Parsetree.open_declaration -> Ast_414.Parsetree.open_declaration =
fun x -> copy_open_infos copy_module_expr x
and copy_module_binding :
Ast_413.Parsetree.module_binding -> Ast_414.Parsetree.module_binding =
fun
{ Ast_413.Parsetree.pmb_name = pmb_name;
Ast_413.Parsetree.pmb_expr = pmb_expr;
Ast_413.Parsetree.pmb_attributes = pmb_attributes;
Ast_413.Parsetree.pmb_loc = pmb_loc }
->
{
Ast_414.Parsetree.pmb_name =
(copy_loc (fun x -> Option.map (fun x -> x) x) pmb_name);
Ast_414.Parsetree.pmb_expr = (copy_module_expr pmb_expr);
Ast_414.Parsetree.pmb_attributes = (copy_attributes pmb_attributes);
Ast_414.Parsetree.pmb_loc = (copy_location pmb_loc)
}
and copy_module_expr :
Ast_413.Parsetree.module_expr -> Ast_414.Parsetree.module_expr =
fun
{ Ast_413.Parsetree.pmod_desc = pmod_desc;
Ast_413.Parsetree.pmod_loc = pmod_loc;
Ast_413.Parsetree.pmod_attributes = pmod_attributes }
->
{
Ast_414.Parsetree.pmod_desc = (copy_module_expr_desc pmod_desc);
Ast_414.Parsetree.pmod_loc = (copy_location pmod_loc);
Ast_414.Parsetree.pmod_attributes = (copy_attributes pmod_attributes)
}
and copy_module_expr_desc :
Ast_413.Parsetree.module_expr_desc -> Ast_414.Parsetree.module_expr_desc =
function
| Ast_413.Parsetree.Pmod_ident x0 ->
Ast_414.Parsetree.Pmod_ident (copy_loc copy_Longident_t x0)
| Ast_413.Parsetree.Pmod_structure x0 ->
Ast_414.Parsetree.Pmod_structure (copy_structure x0)
| Ast_413.Parsetree.Pmod_functor (x0, x1) ->
Ast_414.Parsetree.Pmod_functor
((copy_functor_parameter x0), (copy_module_expr x1))
| Ast_413.Parsetree.Pmod_apply (x0, x1) ->
Ast_414.Parsetree.Pmod_apply
((copy_module_expr x0), (copy_module_expr x1))
| Ast_413.Parsetree.Pmod_constraint (x0, x1) ->
Ast_414.Parsetree.Pmod_constraint
((copy_module_expr x0), (copy_module_type x1))
| Ast_413.Parsetree.Pmod_unpack x0 ->
Ast_414.Parsetree.Pmod_unpack (copy_expression x0)
| Ast_413.Parsetree.Pmod_extension x0 ->
Ast_414.Parsetree.Pmod_extension (copy_extension x0)
and copy_functor_parameter :
Ast_413.Parsetree.functor_parameter -> Ast_414.Parsetree.functor_parameter
=
function
| Ast_413.Parsetree.Unit -> Ast_414.Parsetree.Unit
| Ast_413.Parsetree.Named (x0, x1) ->
Ast_414.Parsetree.Named
((copy_loc (fun x -> Option.map (fun x -> x) x) x0),
(copy_module_type x1))
and copy_module_type :
Ast_413.Parsetree.module_type -> Ast_414.Parsetree.module_type =
fun
{ Ast_413.Parsetree.pmty_desc = pmty_desc;
Ast_413.Parsetree.pmty_loc = pmty_loc;
Ast_413.Parsetree.pmty_attributes = pmty_attributes }
->
{
Ast_414.Parsetree.pmty_desc = (copy_module_type_desc pmty_desc);
Ast_414.Parsetree.pmty_loc = (copy_location pmty_loc);
Ast_414.Parsetree.pmty_attributes = (copy_attributes pmty_attributes)
}
and copy_module_type_desc :
Ast_413.Parsetree.module_type_desc -> Ast_414.Parsetree.module_type_desc =
function
| Ast_413.Parsetree.Pmty_ident x0 ->
Ast_414.Parsetree.Pmty_ident (copy_loc copy_Longident_t x0)
| Ast_413.Parsetree.Pmty_signature x0 ->
Ast_414.Parsetree.Pmty_signature (copy_signature x0)
| Ast_413.Parsetree.Pmty_functor (x0, x1) ->
Ast_414.Parsetree.Pmty_functor
((copy_functor_parameter x0), (copy_module_type x1))
| Ast_413.Parsetree.Pmty_with (x0, x1) ->
Ast_414.Parsetree.Pmty_with
((copy_module_type x0), (List.map copy_with_constraint x1))
| Ast_413.Parsetree.Pmty_typeof x0 ->
Ast_414.Parsetree.Pmty_typeof (copy_module_expr x0)
| Ast_413.Parsetree.Pmty_extension x0 ->
Ast_414.Parsetree.Pmty_extension (copy_extension x0)
| Ast_413.Parsetree.Pmty_alias x0 ->
Ast_414.Parsetree.Pmty_alias (copy_loc copy_Longident_t x0)
and copy_with_constraint :
Ast_413.Parsetree.with_constraint -> Ast_414.Parsetree.with_constraint =
function
| Ast_413.Parsetree.Pwith_type (x0, x1) ->
Ast_414.Parsetree.Pwith_type
((copy_loc copy_Longident_t x0), (copy_type_declaration x1))
| Ast_413.Parsetree.Pwith_module (x0, x1) ->
Ast_414.Parsetree.Pwith_module
((copy_loc copy_Longident_t x0), (copy_loc copy_Longident_t x1))
| Ast_413.Parsetree.Pwith_modtype (x0, x1) ->
Ast_414.Parsetree.Pwith_modtype
((copy_loc copy_Longident_t x0), (copy_module_type x1))
| Ast_413.Parsetree.Pwith_modtypesubst (x0, x1) ->
Ast_414.Parsetree.Pwith_modtypesubst
((copy_loc copy_Longident_t x0), (copy_module_type x1))
| Ast_413.Parsetree.Pwith_typesubst (x0, x1) ->
Ast_414.Parsetree.Pwith_typesubst
((copy_loc copy_Longident_t x0), (copy_type_declaration x1))
| Ast_413.Parsetree.Pwith_modsubst (x0, x1) ->
Ast_414.Parsetree.Pwith_modsubst
((copy_loc copy_Longident_t x0), (copy_loc copy_Longident_t x1))
and copy_signature :
Ast_413.Parsetree.signature -> Ast_414.Parsetree.signature =
fun x -> List.map copy_signature_item x
and copy_signature_item :
Ast_413.Parsetree.signature_item -> Ast_414.Parsetree.signature_item =
fun
{ Ast_413.Parsetree.psig_desc = psig_desc;
Ast_413.Parsetree.psig_loc = psig_loc }
->
{
Ast_414.Parsetree.psig_desc = (copy_signature_item_desc psig_desc);
Ast_414.Parsetree.psig_loc = (copy_location psig_loc)
}
and copy_signature_item_desc :
Ast_413.Parsetree.signature_item_desc ->
Ast_414.Parsetree.signature_item_desc
=
function
| Ast_413.Parsetree.Psig_value x0 ->
Ast_414.Parsetree.Psig_value (copy_value_description x0)
| Ast_413.Parsetree.Psig_type (x0, x1) ->
Ast_414.Parsetree.Psig_type
((copy_rec_flag x0), (List.map copy_type_declaration x1))
| Ast_413.Parsetree.Psig_typesubst x0 ->
Ast_414.Parsetree.Psig_typesubst (List.map copy_type_declaration x0)
| Ast_413.Parsetree.Psig_typext x0 ->
Ast_414.Parsetree.Psig_typext (copy_type_extension x0)
| Ast_413.Parsetree.Psig_exception x0 ->
Ast_414.Parsetree.Psig_exception (copy_type_exception x0)
| Ast_413.Parsetree.Psig_module x0 ->
Ast_414.Parsetree.Psig_module (copy_module_declaration x0)
| Ast_413.Parsetree.Psig_modsubst x0 ->
Ast_414.Parsetree.Psig_modsubst (copy_module_substitution x0)
| Ast_413.Parsetree.Psig_recmodule x0 ->
Ast_414.Parsetree.Psig_recmodule (List.map copy_module_declaration x0)
| Ast_413.Parsetree.Psig_modtype x0 ->
Ast_414.Parsetree.Psig_modtype (copy_module_type_declaration x0)
| Ast_413.Parsetree.Psig_modtypesubst x0 ->
Ast_414.Parsetree.Psig_modtypesubst (copy_module_type_declaration x0)
| Ast_413.Parsetree.Psig_open x0 ->
Ast_414.Parsetree.Psig_open (copy_open_description x0)
| Ast_413.Parsetree.Psig_include x0 ->
Ast_414.Parsetree.Psig_include (copy_include_description x0)
| Ast_413.Parsetree.Psig_class x0 ->
Ast_414.Parsetree.Psig_class (List.map copy_class_description x0)
| Ast_413.Parsetree.Psig_class_type x0 ->
Ast_414.Parsetree.Psig_class_type
(List.map copy_class_type_declaration x0)
| Ast_413.Parsetree.Psig_attribute x0 ->
Ast_414.Parsetree.Psig_attribute (copy_attribute x0)
| Ast_413.Parsetree.Psig_extension (x0, x1) ->
Ast_414.Parsetree.Psig_extension
((copy_extension x0), (copy_attributes x1))
and copy_class_type_declaration :
Ast_413.Parsetree.class_type_declaration ->
Ast_414.Parsetree.class_type_declaration
= fun x -> copy_class_infos copy_class_type x
and copy_class_description :
Ast_413.Parsetree.class_description -> Ast_414.Parsetree.class_description
= fun x -> copy_class_infos copy_class_type x
and copy_class_type :
Ast_413.Parsetree.class_type -> Ast_414.Parsetree.class_type =
fun
{ Ast_413.Parsetree.pcty_desc = pcty_desc;
Ast_413.Parsetree.pcty_loc = pcty_loc;
Ast_413.Parsetree.pcty_attributes = pcty_attributes }
->
{
Ast_414.Parsetree.pcty_desc = (copy_class_type_desc pcty_desc);
Ast_414.Parsetree.pcty_loc = (copy_location pcty_loc);
Ast_414.Parsetree.pcty_attributes = (copy_attributes pcty_attributes)
}
and copy_class_type_desc :
Ast_413.Parsetree.class_type_desc -> Ast_414.Parsetree.class_type_desc =
function
| Ast_413.Parsetree.Pcty_constr (x0, x1) ->
Ast_414.Parsetree.Pcty_constr
((copy_loc copy_Longident_t x0), (List.map copy_core_type x1))
| Ast_413.Parsetree.Pcty_signature x0 ->
Ast_414.Parsetree.Pcty_signature (copy_class_signature x0)
| Ast_413.Parsetree.Pcty_arrow (x0, x1, x2) ->
Ast_414.Parsetree.Pcty_arrow
((copy_arg_label x0), (copy_core_type x1), (copy_class_type x2))
| Ast_413.Parsetree.Pcty_extension x0 ->
Ast_414.Parsetree.Pcty_extension (copy_extension x0)
| Ast_413.Parsetree.Pcty_open (x0, x1) ->
Ast_414.Parsetree.Pcty_open
((copy_open_description x0), (copy_class_type x1))
and copy_class_signature :
Ast_413.Parsetree.class_signature -> Ast_414.Parsetree.class_signature =
fun
{ Ast_413.Parsetree.pcsig_self = pcsig_self;
Ast_413.Parsetree.pcsig_fields = pcsig_fields }
->
{
Ast_414.Parsetree.pcsig_self = (copy_core_type pcsig_self);
Ast_414.Parsetree.pcsig_fields =
(List.map copy_class_type_field pcsig_fields)
}
and copy_class_type_field :
Ast_413.Parsetree.class_type_field -> Ast_414.Parsetree.class_type_field =
fun
{ Ast_413.Parsetree.pctf_desc = pctf_desc;
Ast_413.Parsetree.pctf_loc = pctf_loc;
Ast_413.Parsetree.pctf_attributes = pctf_attributes }
->
{
Ast_414.Parsetree.pctf_desc = (copy_class_type_field_desc pctf_desc);
Ast_414.Parsetree.pctf_loc = (copy_location pctf_loc);
Ast_414.Parsetree.pctf_attributes = (copy_attributes pctf_attributes)
}
and copy_class_type_field_desc :
Ast_413.Parsetree.class_type_field_desc ->
Ast_414.Parsetree.class_type_field_desc
=
function
| Ast_413.Parsetree.Pctf_inherit x0 ->
Ast_414.Parsetree.Pctf_inherit (copy_class_type x0)
| Ast_413.Parsetree.Pctf_val x0 ->
Ast_414.Parsetree.Pctf_val
(let (x0, x1, x2, x3) = x0 in
((copy_loc copy_label x0), (copy_mutable_flag x1),
(copy_virtual_flag x2), (copy_core_type x3)))
| Ast_413.Parsetree.Pctf_method x0 ->
Ast_414.Parsetree.Pctf_method
(let (x0, x1, x2, x3) = x0 in
((copy_loc copy_label x0), (copy_private_flag x1),
(copy_virtual_flag x2), (copy_core_type x3)))
| Ast_413.Parsetree.Pctf_constraint x0 ->
Ast_414.Parsetree.Pctf_constraint
(let (x0, x1) = x0 in ((copy_core_type x0), (copy_core_type x1)))
| Ast_413.Parsetree.Pctf_attribute x0 ->
Ast_414.Parsetree.Pctf_attribute (copy_attribute x0)
| Ast_413.Parsetree.Pctf_extension x0 ->
Ast_414.Parsetree.Pctf_extension (copy_extension x0)
and copy_extension :
Ast_413.Parsetree.extension -> Ast_414.Parsetree.extension =
fun x ->
let (x0, x1) = x in ((copy_loc (fun x -> x) x0), (copy_payload x1))
and copy_class_infos :
'f0 'g0 .
('f0 -> 'g0) ->
'f0 Ast_413.Parsetree.class_infos -> 'g0 Ast_414.Parsetree.class_infos
=
fun f0 ->
fun
{ Ast_413.Parsetree.pci_virt = pci_virt;
Ast_413.Parsetree.pci_params = pci_params;
Ast_413.Parsetree.pci_name = pci_name;
Ast_413.Parsetree.pci_expr = pci_expr;
Ast_413.Parsetree.pci_loc = pci_loc;
Ast_413.Parsetree.pci_attributes = pci_attributes }
->
{
Ast_414.Parsetree.pci_virt = (copy_virtual_flag pci_virt);
Ast_414.Parsetree.pci_params =
(List.map
(fun x ->
let (x0, x1) = x in
((copy_core_type x0),
(let (x0, x1) = x1 in
((copy_variance x0), (copy_injectivity x1))))) pci_params);
Ast_414.Parsetree.pci_name = (copy_loc (fun x -> x) pci_name);
Ast_414.Parsetree.pci_expr = (f0 pci_expr);
Ast_414.Parsetree.pci_loc = (copy_location pci_loc);
Ast_414.Parsetree.pci_attributes = (copy_attributes pci_attributes)
}
and copy_virtual_flag :
Ast_413.Asttypes.virtual_flag -> Ast_414.Asttypes.virtual_flag =
function
| Ast_413.Asttypes.Virtual -> Ast_414.Asttypes.Virtual
| Ast_413.Asttypes.Concrete -> Ast_414.Asttypes.Concrete
and copy_include_description :
Ast_413.Parsetree.include_description ->
Ast_414.Parsetree.include_description
= fun x -> copy_include_infos copy_module_type x
and copy_include_infos :
'f0 'g0 .
('f0 -> 'g0) ->
'f0 Ast_413.Parsetree.include_infos ->
'g0 Ast_414.Parsetree.include_infos
=
fun f0 ->
fun
{ Ast_413.Parsetree.pincl_mod = pincl_mod;
Ast_413.Parsetree.pincl_loc = pincl_loc;
Ast_413.Parsetree.pincl_attributes = pincl_attributes }
->
{
Ast_414.Parsetree.pincl_mod = (f0 pincl_mod);
Ast_414.Parsetree.pincl_loc = (copy_location pincl_loc);
Ast_414.Parsetree.pincl_attributes =
(copy_attributes pincl_attributes)
}
and copy_open_description :
Ast_413.Parsetree.open_description -> Ast_414.Parsetree.open_description =
fun x -> copy_open_infos (fun x -> copy_loc copy_Longident_t x) x
and copy_open_infos :
'f0 'g0 .
('f0 -> 'g0) ->
'f0 Ast_413.Parsetree.open_infos -> 'g0 Ast_414.Parsetree.open_infos
=
fun f0 ->
fun
{ Ast_413.Parsetree.popen_expr = popen_expr;
Ast_413.Parsetree.popen_override = popen_override;
Ast_413.Parsetree.popen_loc = popen_loc;
Ast_413.Parsetree.popen_attributes = popen_attributes }
->
{
Ast_414.Parsetree.popen_expr = (f0 popen_expr);
Ast_414.Parsetree.popen_override =
(copy_override_flag popen_override);
Ast_414.Parsetree.popen_loc = (copy_location popen_loc);
Ast_414.Parsetree.popen_attributes =
(copy_attributes popen_attributes)
}
and copy_override_flag :
Ast_413.Asttypes.override_flag -> Ast_414.Asttypes.override_flag =
function
| Ast_413.Asttypes.Override -> Ast_414.Asttypes.Override
| Ast_413.Asttypes.Fresh -> Ast_414.Asttypes.Fresh
and copy_module_type_declaration :
Ast_413.Parsetree.module_type_declaration ->
Ast_414.Parsetree.module_type_declaration
=
fun
{ Ast_413.Parsetree.pmtd_name = pmtd_name;
Ast_413.Parsetree.pmtd_type = pmtd_type;
Ast_413.Parsetree.pmtd_attributes = pmtd_attributes;
Ast_413.Parsetree.pmtd_loc = pmtd_loc }
->
{
Ast_414.Parsetree.pmtd_name = (copy_loc (fun x -> x) pmtd_name);
Ast_414.Parsetree.pmtd_type = (Option.map copy_module_type pmtd_type);
Ast_414.Parsetree.pmtd_attributes = (copy_attributes pmtd_attributes);
Ast_414.Parsetree.pmtd_loc = (copy_location pmtd_loc)
}
and copy_module_substitution :
Ast_413.Parsetree.module_substitution ->
Ast_414.Parsetree.module_substitution
=
fun
{ Ast_413.Parsetree.pms_name = pms_name;
Ast_413.Parsetree.pms_manifest = pms_manifest;
Ast_413.Parsetree.pms_attributes = pms_attributes;
Ast_413.Parsetree.pms_loc = pms_loc }
->
{
Ast_414.Parsetree.pms_name = (copy_loc (fun x -> x) pms_name);
Ast_414.Parsetree.pms_manifest =
(copy_loc copy_Longident_t pms_manifest);
Ast_414.Parsetree.pms_attributes = (copy_attributes pms_attributes);
Ast_414.Parsetree.pms_loc = (copy_location pms_loc)
}
and copy_module_declaration :
Ast_413.Parsetree.module_declaration ->
Ast_414.Parsetree.module_declaration
=
fun
{ Ast_413.Parsetree.pmd_name = pmd_name;
Ast_413.Parsetree.pmd_type = pmd_type;
Ast_413.Parsetree.pmd_attributes = pmd_attributes;
Ast_413.Parsetree.pmd_loc = pmd_loc }
->
{
Ast_414.Parsetree.pmd_name =
(copy_loc (fun x -> Option.map (fun x -> x) x) pmd_name);
Ast_414.Parsetree.pmd_type = (copy_module_type pmd_type);
Ast_414.Parsetree.pmd_attributes = (copy_attributes pmd_attributes);
Ast_414.Parsetree.pmd_loc = (copy_location pmd_loc)
}
and copy_type_exception :
Ast_413.Parsetree.type_exception -> Ast_414.Parsetree.type_exception =
fun
{ Ast_413.Parsetree.ptyexn_constructor = ptyexn_constructor;
Ast_413.Parsetree.ptyexn_loc = ptyexn_loc;
Ast_413.Parsetree.ptyexn_attributes = ptyexn_attributes }
->
{
Ast_414.Parsetree.ptyexn_constructor =
(copy_extension_constructor ptyexn_constructor);
Ast_414.Parsetree.ptyexn_loc = (copy_location ptyexn_loc);
Ast_414.Parsetree.ptyexn_attributes =
(copy_attributes ptyexn_attributes)
}
and copy_type_extension :
Ast_413.Parsetree.type_extension -> Ast_414.Parsetree.type_extension =
fun
{ Ast_413.Parsetree.ptyext_path = ptyext_path;
Ast_413.Parsetree.ptyext_params = ptyext_params;
Ast_413.Parsetree.ptyext_constructors = ptyext_constructors;
Ast_413.Parsetree.ptyext_private = ptyext_private;
Ast_413.Parsetree.ptyext_loc = ptyext_loc;
Ast_413.Parsetree.ptyext_attributes = ptyext_attributes }
->
{
Ast_414.Parsetree.ptyext_path = (copy_loc copy_Longident_t ptyext_path);
Ast_414.Parsetree.ptyext_params =
(List.map
(fun x ->
let (x0, x1) = x in
((copy_core_type x0),
(let (x0, x1) = x1 in
((copy_variance x0), (copy_injectivity x1))))) ptyext_params);
Ast_414.Parsetree.ptyext_constructors =
(List.map copy_extension_constructor ptyext_constructors);
Ast_414.Parsetree.ptyext_private = (copy_private_flag ptyext_private);
Ast_414.Parsetree.ptyext_loc = (copy_location ptyext_loc);
Ast_414.Parsetree.ptyext_attributes =
(copy_attributes ptyext_attributes)
}
and copy_extension_constructor :
Ast_413.Parsetree.extension_constructor ->
Ast_414.Parsetree.extension_constructor
=
fun
{ Ast_413.Parsetree.pext_name = pext_name;
Ast_413.Parsetree.pext_kind = pext_kind;
Ast_413.Parsetree.pext_loc = pext_loc;
Ast_413.Parsetree.pext_attributes = pext_attributes }
->
{
Ast_414.Parsetree.pext_name = (copy_loc (fun x -> x) pext_name);
Ast_414.Parsetree.pext_kind =
(copy_extension_constructor_kind pext_kind);
Ast_414.Parsetree.pext_loc = (copy_location pext_loc);
Ast_414.Parsetree.pext_attributes = (copy_attributes pext_attributes)
}
and copy_extension_constructor_kind :
Ast_413.Parsetree.extension_constructor_kind ->
Ast_414.Parsetree.extension_constructor_kind
=
function
| Ast_413.Parsetree.Pext_decl (x0, x1) ->
Ast_414.Parsetree.Pext_decl
([], (copy_constructor_arguments x0), (Option.map copy_core_type x1))
| Ast_413.Parsetree.Pext_rebind x0 ->
Ast_414.Parsetree.Pext_rebind (copy_loc copy_Longident_t x0)
and copy_type_declaration :
Ast_413.Parsetree.type_declaration -> Ast_414.Parsetree.type_declaration =
fun
{ Ast_413.Parsetree.ptype_name = ptype_name;
Ast_413.Parsetree.ptype_params = ptype_params;
Ast_413.Parsetree.ptype_cstrs = ptype_cstrs;
Ast_413.Parsetree.ptype_kind = ptype_kind;
Ast_413.Parsetree.ptype_private = ptype_private;
Ast_413.Parsetree.ptype_manifest = ptype_manifest;
Ast_413.Parsetree.ptype_attributes = ptype_attributes;
Ast_413.Parsetree.ptype_loc = ptype_loc }
->
{
Ast_414.Parsetree.ptype_name = (copy_loc (fun x -> x) ptype_name);
Ast_414.Parsetree.ptype_params =
(List.map
(fun x ->
let (x0, x1) = x in
((copy_core_type x0),
(let (x0, x1) = x1 in
((copy_variance x0), (copy_injectivity x1))))) ptype_params);
Ast_414.Parsetree.ptype_cstrs =
(List.map
(fun x ->
let (x0, x1, x2) = x in
((copy_core_type x0), (copy_core_type x1), (copy_location x2)))
ptype_cstrs);
Ast_414.Parsetree.ptype_kind = (copy_type_kind ptype_kind);
Ast_414.Parsetree.ptype_private = (copy_private_flag ptype_private);
Ast_414.Parsetree.ptype_manifest =
(Option.map copy_core_type ptype_manifest);
Ast_414.Parsetree.ptype_attributes = (copy_attributes ptype_attributes);
Ast_414.Parsetree.ptype_loc = (copy_location ptype_loc)
}
and copy_private_flag :
Ast_413.Asttypes.private_flag -> Ast_414.Asttypes.private_flag =
function
| Ast_413.Asttypes.Private -> Ast_414.Asttypes.Private
| Ast_413.Asttypes.Public -> Ast_414.Asttypes.Public
and copy_type_kind :
Ast_413.Parsetree.type_kind -> Ast_414.Parsetree.type_kind =
function
| Ast_413.Parsetree.Ptype_abstract -> Ast_414.Parsetree.Ptype_abstract
| Ast_413.Parsetree.Ptype_variant x0 ->
Ast_414.Parsetree.Ptype_variant
(List.map copy_constructor_declaration x0)
| Ast_413.Parsetree.Ptype_record x0 ->
Ast_414.Parsetree.Ptype_record (List.map copy_label_declaration x0)
| Ast_413.Parsetree.Ptype_open -> Ast_414.Parsetree.Ptype_open
and copy_constructor_declaration :
Ast_413.Parsetree.constructor_declaration ->
Ast_414.Parsetree.constructor_declaration
=
fun
{ Ast_413.Parsetree.pcd_name = pcd_name;
Ast_413.Parsetree.pcd_args = pcd_args;
Ast_413.Parsetree.pcd_res = pcd_res;
Ast_413.Parsetree.pcd_loc = pcd_loc;
Ast_413.Parsetree.pcd_attributes = pcd_attributes }
->
{
Ast_414.Parsetree.pcd_name = (copy_loc (fun x -> x) pcd_name);
Ast_414.Parsetree.pcd_vars = [];
Ast_414.Parsetree.pcd_args = (copy_constructor_arguments pcd_args);
Ast_414.Parsetree.pcd_res = (Option.map copy_core_type pcd_res);
Ast_414.Parsetree.pcd_loc = (copy_location pcd_loc);
Ast_414.Parsetree.pcd_attributes = (copy_attributes pcd_attributes)
}
and copy_constructor_arguments :
Ast_413.Parsetree.constructor_arguments ->
Ast_414.Parsetree.constructor_arguments
=
function
| Ast_413.Parsetree.Pcstr_tuple x0 ->
Ast_414.Parsetree.Pcstr_tuple (List.map copy_core_type x0)
| Ast_413.Parsetree.Pcstr_record x0 ->
Ast_414.Parsetree.Pcstr_record (List.map copy_label_declaration x0)
and copy_label_declaration :
Ast_413.Parsetree.label_declaration -> Ast_414.Parsetree.label_declaration
=
fun
{ Ast_413.Parsetree.pld_name = pld_name;
Ast_413.Parsetree.pld_mutable = pld_mutable;
Ast_413.Parsetree.pld_type = pld_type;
Ast_413.Parsetree.pld_loc = pld_loc;
Ast_413.Parsetree.pld_attributes = pld_attributes }
->
{
Ast_414.Parsetree.pld_name = (copy_loc (fun x -> x) pld_name);
Ast_414.Parsetree.pld_mutable = (copy_mutable_flag pld_mutable);
Ast_414.Parsetree.pld_type = (copy_core_type pld_type);
Ast_414.Parsetree.pld_loc = (copy_location pld_loc);
Ast_414.Parsetree.pld_attributes = (copy_attributes pld_attributes)
}
and copy_mutable_flag :
Ast_413.Asttypes.mutable_flag -> Ast_414.Asttypes.mutable_flag =
function
| Ast_413.Asttypes.Immutable -> Ast_414.Asttypes.Immutable
| Ast_413.Asttypes.Mutable -> Ast_414.Asttypes.Mutable
and copy_injectivity :
Ast_413.Asttypes.injectivity -> Ast_414.Asttypes.injectivity =
function
| Ast_413.Asttypes.Injective -> Ast_414.Asttypes.Injective
| Ast_413.Asttypes.NoInjectivity -> Ast_414.Asttypes.NoInjectivity
and copy_variance : Ast_413.Asttypes.variance -> Ast_414.Asttypes.variance =
function
| Ast_413.Asttypes.Covariant -> Ast_414.Asttypes.Covariant
| Ast_413.Asttypes.Contravariant -> Ast_414.Asttypes.Contravariant
| Ast_413.Asttypes.NoVariance -> Ast_414.Asttypes.NoVariance
and copy_value_description :
Ast_413.Parsetree.value_description -> Ast_414.Parsetree.value_description
=
fun
{ Ast_413.Parsetree.pval_name = pval_name;
Ast_413.Parsetree.pval_type = pval_type;
Ast_413.Parsetree.pval_prim = pval_prim;
Ast_413.Parsetree.pval_attributes = pval_attributes;
Ast_413.Parsetree.pval_loc = pval_loc }
->
{
Ast_414.Parsetree.pval_name = (copy_loc (fun x -> x) pval_name);
Ast_414.Parsetree.pval_type = (copy_core_type pval_type);
Ast_414.Parsetree.pval_prim = (List.map (fun x -> x) pval_prim);
Ast_414.Parsetree.pval_attributes = (copy_attributes pval_attributes);
Ast_414.Parsetree.pval_loc = (copy_location pval_loc)
}
and copy_object_field_desc :
Ast_413.Parsetree.object_field_desc -> Ast_414.Parsetree.object_field_desc
=
function
| Ast_413.Parsetree.Otag (x0, x1) ->
Ast_414.Parsetree.Otag ((copy_loc copy_label x0), (copy_core_type x1))
| Ast_413.Parsetree.Oinherit x0 ->
Ast_414.Parsetree.Oinherit (copy_core_type x0)
and copy_arg_label : Ast_413.Asttypes.arg_label -> Ast_414.Asttypes.arg_label
=
function
| Ast_413.Asttypes.Nolabel -> Ast_414.Asttypes.Nolabel
| Ast_413.Asttypes.Labelled x0 -> Ast_414.Asttypes.Labelled x0
| Ast_413.Asttypes.Optional x0 -> Ast_414.Asttypes.Optional x0
and copy_closed_flag :
Ast_413.Asttypes.closed_flag -> Ast_414.Asttypes.closed_flag =
function
| Ast_413.Asttypes.Closed -> Ast_414.Asttypes.Closed
| Ast_413.Asttypes.Open -> Ast_414.Asttypes.Open
and copy_label : Ast_413.Asttypes.label -> Ast_414.Asttypes.label =
fun x -> x
and copy_rec_flag : Ast_413.Asttypes.rec_flag -> Ast_414.Asttypes.rec_flag =
function
| Ast_413.Asttypes.Nonrecursive -> Ast_414.Asttypes.Nonrecursive
| Ast_413.Asttypes.Recursive -> Ast_414.Asttypes.Recursive
and copy_constant : Ast_413.Parsetree.constant -> Ast_414.Parsetree.constant
=
function
| Ast_413.Parsetree.Pconst_integer (x0, x1) ->
Ast_414.Parsetree.Pconst_integer (x0, (Option.map (fun x -> x) x1))
| Ast_413.Parsetree.Pconst_char x0 -> Ast_414.Parsetree.Pconst_char x0
| Ast_413.Parsetree.Pconst_string (x0, x1, x2) ->
Ast_414.Parsetree.Pconst_string
(x0, (copy_location x1), (Option.map (fun x -> x) x2))
| Ast_413.Parsetree.Pconst_float (x0, x1) ->
Ast_414.Parsetree.Pconst_float (x0, (Option.map (fun x -> x) x1))
and copy_Longident_t : Longident.t -> Longident.t =
function
| Longident.Lident x0 -> Longident.Lident x0
| Longident.Ldot (x0, x1) -> Longident.Ldot ((copy_Longident_t x0), x1)
| Longident.Lapply (x0, x1) ->
Longident.Lapply ((copy_Longident_t x0), (copy_Longident_t x1))
and copy_loc :
'f0 'g0 .
('f0 -> 'g0) -> 'f0 Ast_413.Asttypes.loc -> 'g0 Ast_414.Asttypes.loc
=
fun f0 ->
fun { Ast_413.Asttypes.txt = txt; Ast_413.Asttypes.loc = loc } ->
{
Ast_414.Asttypes.txt = (f0 txt);
Ast_414.Asttypes.loc = (copy_location loc)
}
and copy_location : Location.t -> Location.t =
fun
{ Location.loc_start = loc_start; Location.loc_end = loc_end;
Location.loc_ghost = loc_ghost }
->
{
Location.loc_start = (copy_position loc_start);
Location.loc_end = (copy_position loc_end);
Location.loc_ghost = loc_ghost
}
and copy_position : Lexing.position -> Lexing.position =
fun
{ Lexing.pos_fname = pos_fname; Lexing.pos_lnum = pos_lnum;
Lexing.pos_bol = pos_bol; Lexing.pos_cnum = pos_cnum }
->
{
Lexing.pos_fname = pos_fname;
Lexing.pos_lnum = pos_lnum;
Lexing.pos_bol = pos_bol;
Lexing.pos_cnum = pos_cnum
}
| |
4f3d223f81721b9c0c9567d202d8f505c58b6a43669f634cddebabe4c9344fc3 | ashinkarov/heh | value.ml |
* Copyright ( c ) 2017 - 2018 , < >
*
* 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 .
* Copyright (c) 2017-2018, Artem Shinkarov <>
*
* 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.
*)
exception ValueFailure of string
type value =
| VFalse
| VTrue
| VNum of Ordinals.ordinal
| VArray of value list * value list
| VClosure of Ast.expr * Env.env
: : ptr_out_shape * ptr_inner_shape * [ * ptr_or_expr ] * env
| VImap of string * string * (vgen * expr_or_ptr) list * Env.env
(* :: ptr_func * ptr_expr * [limit_ord * vector * int] *)
| VFilter of string * string * (Ordinals.ordinal * (value list) * int) list
and vgen = value * string * value
and expr_or_ptr =
| EPptr of string
| EPexpr of Ast.expr
(* A shortcut for raising an exception. *)
let value_err msg =
raise (ValueFailure msg)
| null | https://raw.githubusercontent.com/ashinkarov/heh/42866803b2ffacdc42b8f06203bf4e5bd18e03b0/value.ml | ocaml | :: ptr_func * ptr_expr * [limit_ord * vector * int]
A shortcut for raising an exception. |
* Copyright ( c ) 2017 - 2018 , < >
*
* 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 .
* Copyright (c) 2017-2018, Artem Shinkarov <>
*
* 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.
*)
exception ValueFailure of string
type value =
| VFalse
| VTrue
| VNum of Ordinals.ordinal
| VArray of value list * value list
| VClosure of Ast.expr * Env.env
: : ptr_out_shape * ptr_inner_shape * [ * ptr_or_expr ] * env
| VImap of string * string * (vgen * expr_or_ptr) list * Env.env
| VFilter of string * string * (Ordinals.ordinal * (value list) * int) list
and vgen = value * string * value
and expr_or_ptr =
| EPptr of string
| EPexpr of Ast.expr
let value_err msg =
raise (ValueFailure msg)
|
48f7f9423d10791145abf220e3f47142895093d92fde2a9cc15481a78c44de87 | wireapp/wire-server | Servant.hs | # LANGUAGE LambdaCase #
# OPTIONS_GHC -Wno - orphans #
-- 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 Spar.Sem.SamlProtocolSettings.Servant
( sparRouteToServant,
)
where
import Imports
import Polysemy
import qualified SAML2.WebSSO as SAML
import Spar.Sem.SamlProtocolSettings
import Wire.API.Routes.Public.Spar
sparRouteToServant :: SAML.Config -> Sem (SamlProtocolSettings ': r) a -> Sem r a
sparRouteToServant cfg = interpret $ \case
SpIssuer mitlt -> pure $ sparSPIssuer mitlt cfg
ResponseURI mitlt -> pure $ sparResponseURI mitlt cfg
| null | https://raw.githubusercontent.com/wireapp/wire-server/33fcf30057511ebd824702333b088382e178e062/services/spar/src/Spar/Sem/SamlProtocolSettings/Servant.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 </>. | # LANGUAGE LambdaCase #
# OPTIONS_GHC -Wno - orphans #
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 Spar.Sem.SamlProtocolSettings.Servant
( sparRouteToServant,
)
where
import Imports
import Polysemy
import qualified SAML2.WebSSO as SAML
import Spar.Sem.SamlProtocolSettings
import Wire.API.Routes.Public.Spar
sparRouteToServant :: SAML.Config -> Sem (SamlProtocolSettings ': r) a -> Sem r a
sparRouteToServant cfg = interpret $ \case
SpIssuer mitlt -> pure $ sparSPIssuer mitlt cfg
ResponseURI mitlt -> pure $ sparResponseURI mitlt cfg
|
2b9c1b0629ce0fb0f8d8baddadfdce862bba4745d08f50097b579903abe98a36 | metaocaml/ber-metaocaml | D.ml | let z x = imp (x*2)
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/tool-ocamldep-modalias/D.ml | ocaml | let z x = imp (x*2)
| |
c36607d237f0697c3ce9d065e13b3d1d2dbb1bb304cfff7244bf8011cd9371ad | klutometis/clrs | payoff.scm | (define (maximize-payoff A B)
(let ((A (sort A >))
(B (sort B >)))
(fold (lambda (a b product) (* product (expt a b))) 1 A B)))
| null | https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/16.2/payoff.scm | scheme | (define (maximize-payoff A B)
(let ((A (sort A >))
(B (sort B >)))
(fold (lambda (a b product) (* product (expt a b))) 1 A B)))
| |
ecad57c10fe4429a7223d596082aaada4ac3848e385195cf492c4de1947d0956 | mokus0/junkbox | New.hs | # LANGUAGE DoRec #
module Functions.New where
import Control.Monad.Fix
import Data.IORef
type New t = t -> t
new :: New t -> t
new init = self where self = init self
ones = new (1:)
data Animal = Animal {
catchPhrase :: String,
speak :: IO ()
}
protoAnimal :: New Animal
protoAnimal self = Animal {
speak = putStrLn (catchPhrase self)
}
cat :: New Animal
cat self = (protoAnimal self) { catchPhrase = "Meow" }
dog :: New Animal
dog self = (protoAnimal self) { catchPhrase = "Woof", speak = putStrLn "Rowwrlrw" }
type NewM m t = t -> m t
newM :: MonadFix m => NewM m t -> m t
newM init = do
rec self <- init self
return self
data AnimalM m = AnimalM {
catchPhraseM :: m String,
speakM :: m ()
}
protoAnimalIO :: NewM IO (AnimalM IO)
protoAnimalIO self = do
putStrLn "making protoAnimal"
return AnimalM
{ speakM = catchPhraseM self >>= putStrLn
}
catIO :: NewM IO (AnimalM IO)
catIO self = do
self <- protoAnimalIO self
meowCount <- newIORef 1
let meow = do
n <- readIORef meowCount
writeIORef meowCount $! (n+1)
if n `mod` 7 /= 0
then return "Meow"
else return "Meeeeeowow!"
return self {catchPhraseM = meow}
dogIO :: NewM IO (AnimalM IO)
dogIO self = do
self <- protoAnimalIO self
return self
{ catchPhraseM = return "Woof"
, speakM = putStrLn "Rowwrlrw"
}
| null | https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Haskell/Functions/New.hs | haskell | # LANGUAGE DoRec #
module Functions.New where
import Control.Monad.Fix
import Data.IORef
type New t = t -> t
new :: New t -> t
new init = self where self = init self
ones = new (1:)
data Animal = Animal {
catchPhrase :: String,
speak :: IO ()
}
protoAnimal :: New Animal
protoAnimal self = Animal {
speak = putStrLn (catchPhrase self)
}
cat :: New Animal
cat self = (protoAnimal self) { catchPhrase = "Meow" }
dog :: New Animal
dog self = (protoAnimal self) { catchPhrase = "Woof", speak = putStrLn "Rowwrlrw" }
type NewM m t = t -> m t
newM :: MonadFix m => NewM m t -> m t
newM init = do
rec self <- init self
return self
data AnimalM m = AnimalM {
catchPhraseM :: m String,
speakM :: m ()
}
protoAnimalIO :: NewM IO (AnimalM IO)
protoAnimalIO self = do
putStrLn "making protoAnimal"
return AnimalM
{ speakM = catchPhraseM self >>= putStrLn
}
catIO :: NewM IO (AnimalM IO)
catIO self = do
self <- protoAnimalIO self
meowCount <- newIORef 1
let meow = do
n <- readIORef meowCount
writeIORef meowCount $! (n+1)
if n `mod` 7 /= 0
then return "Meow"
else return "Meeeeeowow!"
return self {catchPhraseM = meow}
dogIO :: NewM IO (AnimalM IO)
dogIO self = do
self <- protoAnimalIO self
return self
{ catchPhraseM = return "Woof"
, speakM = putStrLn "Rowwrlrw"
}
| |
ff57f316cc249d86b0c29f968d2eda9a2359072af98d728d8b22a2079e223056 | BitGameEN/bitgamex | bg_xchgsvr_sup.erl | %%%-----------------------------------
%%% @Module : bg_xchgsvr_sup
%%% @Description: 监控树
%%%-----------------------------------
-module(bg_xchgsvr_sup).
-behaviour(supervisor).
-export([start_link/1]).
-export([init/1]).
-include("common.hrl").
start_link([Ip, ServerId]) ->
supervisor:start_link({local,?MODULE}, ?MODULE, [Ip, ServerId]).
init([Ip, ServerId]) ->
Children =
[
{
bg_xchgsvr,
{bg_xchgsvr, start_link, []},
permanent,
10000,
supervisor,
[bg_xchgsvr]
},
{
mod_disperse,
{mod_disperse, start_link, [Ip, 0, ServerId, ?SVRTYPE_XCHG]},
permanent,
10000,
supervisor,
[mod_disperse]
},
{
mod_kernel,
{mod_kernel, start_link, []},
permanent,
10000,
supervisor,
[mod_kernel]
},
{
uuid_factory,
{uuid_factory, start_link, []},
permanent,
10000,
supervisor,
[uuid_factory]
},
{
httpc_proxy,
{httpc_proxy, start_link, []},
permanent,
10000,
supervisor,
[httpc_proxy]
}
],
{ok,
{
{one_for_one, 10, 10},
Children
}
}.
| null | https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/bg_xchgsvr_sup.erl | erlang | -----------------------------------
@Module : bg_xchgsvr_sup
@Description: 监控树
-----------------------------------
| -module(bg_xchgsvr_sup).
-behaviour(supervisor).
-export([start_link/1]).
-export([init/1]).
-include("common.hrl").
start_link([Ip, ServerId]) ->
supervisor:start_link({local,?MODULE}, ?MODULE, [Ip, ServerId]).
init([Ip, ServerId]) ->
Children =
[
{
bg_xchgsvr,
{bg_xchgsvr, start_link, []},
permanent,
10000,
supervisor,
[bg_xchgsvr]
},
{
mod_disperse,
{mod_disperse, start_link, [Ip, 0, ServerId, ?SVRTYPE_XCHG]},
permanent,
10000,
supervisor,
[mod_disperse]
},
{
mod_kernel,
{mod_kernel, start_link, []},
permanent,
10000,
supervisor,
[mod_kernel]
},
{
uuid_factory,
{uuid_factory, start_link, []},
permanent,
10000,
supervisor,
[uuid_factory]
},
{
httpc_proxy,
{httpc_proxy, start_link, []},
permanent,
10000,
supervisor,
[httpc_proxy]
}
],
{ok,
{
{one_for_one, 10, 10},
Children
}
}.
|
bf10ec023f145615b602f7702880949642ffd2e70fae5700ba5e67ae8a8ead83 | exercism/erlang | anagram_tests.erl | Generated with ' v0.2.0 '
%% Revision 1 of the exercises generator was used
%% -specifications/raw/6373ab6c335278328259f6407f3a3adfd4afa0f5/exercises/anagram/canonical-data.json
%% This file is automatically generated from the exercises canonical data.
-module(anagram_tests).
-include_lib("erl_exercism/include/exercism.hrl").
-include_lib("eunit/include/eunit.hrl").
'1_no_matches_test_'() ->
{"no matches",
?_assertMatch([],
lists:sort(anagram:find_anagrams("diaper",
["hello", "world",
"zombies", "pants"])))}.
'2_detects_two_anagrams_test_'() ->
{"detects two anagrams",
?_assertMatch(["lemons", "melons"],
lists:sort(anagram:find_anagrams("solemn",
["lemons", "cherry",
"melons"])))}.
'3_does_not_detect_anagram_subsets_test_'() ->
{"does not detect anagram subsets",
?_assertMatch([],
lists:sort(anagram:find_anagrams("good",
["dog", "goody"])))}.
'4_detects_anagram_test_'() ->
{"detects anagram",
?_assertMatch(["inlets"],
lists:sort(anagram:find_anagrams("listen",
["enlists", "google",
"inlets", "banana"])))}.
'5_detects_three_anagrams_test_'() ->
{"detects three anagrams",
?_assertMatch(["gallery", "largely", "regally"],
lists:sort(anagram:find_anagrams("allergy",
["gallery", "ballerina",
"regally", "clergy",
"largely", "leading"])))}.
'6_detects_multiple_anagrams_with_different_case_test_'() ->
{"detects multiple anagrams with different "
"case",
?_assertMatch(["Eons", "ONES"],
lists:sort(anagram:find_anagrams("nose",
["Eons", "ONES"])))}.
'7_does_not_detect_non_anagrams_with_identical_checksum_test_'() ->
{"does not detect non-anagrams with identical "
"checksum",
?_assertMatch([],
lists:sort(anagram:find_anagrams("mass", ["last"])))}.
'8_detects_anagrams_case_insensitively_test_'() ->
{"detects anagrams case-insensitively",
?_assertMatch(["Carthorse"],
lists:sort(anagram:find_anagrams("Orchestra",
["cashregister",
"Carthorse",
"radishes"])))}.
'9_detects_anagrams_using_case_insensitive_subject_test_'() ->
{"detects anagrams using case-insensitive "
"subject",
?_assertMatch(["carthorse"],
lists:sort(anagram:find_anagrams("Orchestra",
["cashregister",
"carthorse",
"radishes"])))}.
'10_detects_anagrams_using_case_insensitive_possible_matches_test_'() ->
{"detects anagrams using case-insensitive "
"possible matches",
?_assertMatch(["Carthorse"],
lists:sort(anagram:find_anagrams("orchestra",
["cashregister",
"Carthorse",
"radishes"])))}.
'11_does_not_detect_an_anagram_if_the_original_word_is_repeated_test_'() ->
{"does not detect an anagram if the original "
"word is repeated",
?_assertMatch([],
lists:sort(anagram:find_anagrams("go", ["go Go GO"])))}.
'12_anagrams_must_use_all_letters_exactly_once_test_'() ->
{"anagrams must use all letters exactly "
"once",
?_assertMatch([],
lists:sort(anagram:find_anagrams("tapper",
["patter"])))}.
'13_words_are_not_anagrams_of_themselves_test_'() ->
{"words are not anagrams of themselves",
?_assertMatch([],
lists:sort(anagram:find_anagrams("BANANA",
["BANANA"])))}.
'14_words_are_not_anagrams_of_themselves_even_if_letter_case_is_partially_different_test_'() ->
{"words are not anagrams of themselves "
"even if letter case is partially different",
?_assertMatch([],
lists:sort(anagram:find_anagrams("BANANA",
["Banana"])))}.
'15_words_are_not_anagrams_of_themselves_even_if_letter_case_is_completely_different_test_'() ->
{"words are not anagrams of themselves "
"even if letter case is completely different",
?_assertMatch([],
lists:sort(anagram:find_anagrams("BANANA",
["banana"])))}.
'16_words_other_than_themselves_can_be_anagrams_test_'() ->
{"words other than themselves can be anagrams",
?_assertMatch(["Silent"],
lists:sort(anagram:find_anagrams("LISTEN",
["LISTEN", "Silent"])))}.
| null | https://raw.githubusercontent.com/exercism/erlang/9b3d3c14ef826e7efbc4fcd024fd20ed09332562/exercises/practice/anagram/test/anagram_tests.erl | erlang | Revision 1 of the exercises generator was used
-specifications/raw/6373ab6c335278328259f6407f3a3adfd4afa0f5/exercises/anagram/canonical-data.json
This file is automatically generated from the exercises canonical data. | Generated with ' v0.2.0 '
-module(anagram_tests).
-include_lib("erl_exercism/include/exercism.hrl").
-include_lib("eunit/include/eunit.hrl").
'1_no_matches_test_'() ->
{"no matches",
?_assertMatch([],
lists:sort(anagram:find_anagrams("diaper",
["hello", "world",
"zombies", "pants"])))}.
'2_detects_two_anagrams_test_'() ->
{"detects two anagrams",
?_assertMatch(["lemons", "melons"],
lists:sort(anagram:find_anagrams("solemn",
["lemons", "cherry",
"melons"])))}.
'3_does_not_detect_anagram_subsets_test_'() ->
{"does not detect anagram subsets",
?_assertMatch([],
lists:sort(anagram:find_anagrams("good",
["dog", "goody"])))}.
'4_detects_anagram_test_'() ->
{"detects anagram",
?_assertMatch(["inlets"],
lists:sort(anagram:find_anagrams("listen",
["enlists", "google",
"inlets", "banana"])))}.
'5_detects_three_anagrams_test_'() ->
{"detects three anagrams",
?_assertMatch(["gallery", "largely", "regally"],
lists:sort(anagram:find_anagrams("allergy",
["gallery", "ballerina",
"regally", "clergy",
"largely", "leading"])))}.
'6_detects_multiple_anagrams_with_different_case_test_'() ->
{"detects multiple anagrams with different "
"case",
?_assertMatch(["Eons", "ONES"],
lists:sort(anagram:find_anagrams("nose",
["Eons", "ONES"])))}.
'7_does_not_detect_non_anagrams_with_identical_checksum_test_'() ->
{"does not detect non-anagrams with identical "
"checksum",
?_assertMatch([],
lists:sort(anagram:find_anagrams("mass", ["last"])))}.
'8_detects_anagrams_case_insensitively_test_'() ->
{"detects anagrams case-insensitively",
?_assertMatch(["Carthorse"],
lists:sort(anagram:find_anagrams("Orchestra",
["cashregister",
"Carthorse",
"radishes"])))}.
'9_detects_anagrams_using_case_insensitive_subject_test_'() ->
{"detects anagrams using case-insensitive "
"subject",
?_assertMatch(["carthorse"],
lists:sort(anagram:find_anagrams("Orchestra",
["cashregister",
"carthorse",
"radishes"])))}.
'10_detects_anagrams_using_case_insensitive_possible_matches_test_'() ->
{"detects anagrams using case-insensitive "
"possible matches",
?_assertMatch(["Carthorse"],
lists:sort(anagram:find_anagrams("orchestra",
["cashregister",
"Carthorse",
"radishes"])))}.
'11_does_not_detect_an_anagram_if_the_original_word_is_repeated_test_'() ->
{"does not detect an anagram if the original "
"word is repeated",
?_assertMatch([],
lists:sort(anagram:find_anagrams("go", ["go Go GO"])))}.
'12_anagrams_must_use_all_letters_exactly_once_test_'() ->
{"anagrams must use all letters exactly "
"once",
?_assertMatch([],
lists:sort(anagram:find_anagrams("tapper",
["patter"])))}.
'13_words_are_not_anagrams_of_themselves_test_'() ->
{"words are not anagrams of themselves",
?_assertMatch([],
lists:sort(anagram:find_anagrams("BANANA",
["BANANA"])))}.
'14_words_are_not_anagrams_of_themselves_even_if_letter_case_is_partially_different_test_'() ->
{"words are not anagrams of themselves "
"even if letter case is partially different",
?_assertMatch([],
lists:sort(anagram:find_anagrams("BANANA",
["Banana"])))}.
'15_words_are_not_anagrams_of_themselves_even_if_letter_case_is_completely_different_test_'() ->
{"words are not anagrams of themselves "
"even if letter case is completely different",
?_assertMatch([],
lists:sort(anagram:find_anagrams("BANANA",
["banana"])))}.
'16_words_other_than_themselves_can_be_anagrams_test_'() ->
{"words other than themselves can be anagrams",
?_assertMatch(["Silent"],
lists:sort(anagram:find_anagrams("LISTEN",
["LISTEN", "Silent"])))}.
|
7b5ec7e54a539a5bb751a9c8f1b33520c4e811966e0b8f4f09c00775e1c6d8fe | plumatic/grab-bag | classify_test.clj | (ns classify.classify-test
(:use clojure.test plumbing.core plumbing.test)
(:require
[flop.map :as map]
[classify.features :as features]
[classify.features-test :as features-test]
[classify.learn :as learn]
[classify.classify :as classify]))
(defn raw-data [& doc-args-and-labels]
(assert (even? (count doc-args-and-labels)))
(for [[d l] (partition 2 doc-args-and-labels)]
[d l]))
(def +feature-set+ (features/feature-set [features-test/starts-with-letter-t]))
(defn featurized-data [& raw-data-args]
(classify/featurize-data +feature-set+ {} (apply raw-data raw-data-args)))
(deftest featurize-data-test
(is-= [[{:lexical {"testy" 1.0 "title" 1.0}} true]
[{:lexical {"texty" 1.0}} false]]
(map (juxt (comp (partial features/fv->nested-features +feature-set+) first) second)
(classify/featurize-data
+feature-set+ {}
(raw-data
{:title "a testy title" :text "no nonsense"} true
{:title "an apple" :text "texty"} false)))))
(deftest keywise-merge-with-test
(is-= {:a 18 :b 4 :c 16}
(classify/keywise-merge-with
#(apply + (map (partial * 2) %&))
{:a 1
:b 2}
{:c 3}
{:a 3
:c 5}
{:a 5})))
(deftest confusion-test
(is-= {[true true] 2.0
[true false] 1.0
[false false] 3.0}
(map-vals
(partial sum second)
(learn/evaluate-all
classify/classification-evaluator
(classify/indexed-troves->model (map-vals map/map->trove {true {0 1 1 -2} false {}}))
(for [[wm l] {{0 4} true
{0 4 1 1} true
{0 4 1 3} true
{1 1} false
{0 -1} false
{0 -2} false}]
[(map/map->fv (map-vals double wm)) l])))))
(def +dummy-data-args+ (apply concat (for [i (range 10)] [{:title (str "title" (mod i 4)) :text (str "text" (mod i 6))} (odd? i)])))
(def +dummy-data+ (apply featurized-data +dummy-data-args+))
(deftest train-and-eval-smoke-test
(letk [[model] (learn/train-and-eval
(classify/maxent-trainer {:pred-thresh 1})
classify/classification-evaluator
+dummy-data+
+dummy-data+)]
(let [datum {:title "title1 title2" :text "text1"}
score (fn [fs m d]
(classify/posteriors m (features/feature-vector fs {} d)))
old-scores (score +feature-set+ model datum)
model-data (classify/model->nested-weight-maps +feature-set+ model)
new-feature-set (features/feature-set [features-test/starts-with-letter-t])
new-model (classify/nested-weight-maps->model new-feature-set model-data)
new-scores (score new-feature-set new-model datum)]
(is-= old-scores new-scores)
(is (= {true {:lexical 8} false {}} (map-vals (partial map-vals count) model-data))))))
(deftest ^:slow estimate-perf-and-train-model-smoke-test
(is (learn/estimate-perf-and-train-model
{:trainer (classify/maxent-trainer {:pred-thresh 1})
:evaluator classify/classification-evaluator
:data +dummy-data+})))
(deftest multiclass-smoke-test
(let [data [[{:title "titlea" :text "texta"} :a]
[{:title "titleb" :text "textb"} :b]
[{:title "titlec" :text "textc"} :c]]
featurized (apply featurized-data (aconcat data))]
(letk [[model evaluation] (learn/train-and-eval
(classify/maxent-trainer {:pred-thresh 1})
classify/classification-evaluator
(aconcat (repeat 3 featurized))
featurized)]
(is-= {[:a :a] 1.0
[:b :b] 1.0
[:c :c] 1.0}
(map-vals (partial sum second) evaluation))
(is-= [:a :b :c] (map #(learn/label model (first %)) featurized)))))
(deftest em-smoke-test
"Test that we can learn by transferring from features on labeled data
to features on unlabeled data through shared features."
(let [labeled (featurized-data
{:title "titlea" :text ""} true
{:title "titleb" :text ""} false)
unlabeled (map
first
(featurized-data
{:title "titlea" :text "transfera"} :ignore
{:title "testa" :text "transfera"} :ignore
{:title "titleb" :text "transferb"} :ignore
{:title "testb" :text "transferb"} :ignore))
model ((classify/em-trainer
(classify/maxent-trainer {:pred-thresh 0 :sigma-sq 10.0})
unlabeled
{:print-progress false
:posteriors->weights (classify/hard-em-weighter 1.0 0.6)})
labeled)
weights (safe-get-in (classify/model->nested-weight-maps +feature-set+ model) [true :lexical])]
(is (every? #(> (weights %) 0.5) ["titlea" "transfera" "testa"]))
(is (every? #(< (weights %) -0.5) ["titleb" "transferb" "testb"]))))
(use-fixtures :once validate-schemas)
| null | https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/classify/test/classify/classify_test.clj | clojure | (ns classify.classify-test
(:use clojure.test plumbing.core plumbing.test)
(:require
[flop.map :as map]
[classify.features :as features]
[classify.features-test :as features-test]
[classify.learn :as learn]
[classify.classify :as classify]))
(defn raw-data [& doc-args-and-labels]
(assert (even? (count doc-args-and-labels)))
(for [[d l] (partition 2 doc-args-and-labels)]
[d l]))
(def +feature-set+ (features/feature-set [features-test/starts-with-letter-t]))
(defn featurized-data [& raw-data-args]
(classify/featurize-data +feature-set+ {} (apply raw-data raw-data-args)))
(deftest featurize-data-test
(is-= [[{:lexical {"testy" 1.0 "title" 1.0}} true]
[{:lexical {"texty" 1.0}} false]]
(map (juxt (comp (partial features/fv->nested-features +feature-set+) first) second)
(classify/featurize-data
+feature-set+ {}
(raw-data
{:title "a testy title" :text "no nonsense"} true
{:title "an apple" :text "texty"} false)))))
(deftest keywise-merge-with-test
(is-= {:a 18 :b 4 :c 16}
(classify/keywise-merge-with
#(apply + (map (partial * 2) %&))
{:a 1
:b 2}
{:c 3}
{:a 3
:c 5}
{:a 5})))
(deftest confusion-test
(is-= {[true true] 2.0
[true false] 1.0
[false false] 3.0}
(map-vals
(partial sum second)
(learn/evaluate-all
classify/classification-evaluator
(classify/indexed-troves->model (map-vals map/map->trove {true {0 1 1 -2} false {}}))
(for [[wm l] {{0 4} true
{0 4 1 1} true
{0 4 1 3} true
{1 1} false
{0 -1} false
{0 -2} false}]
[(map/map->fv (map-vals double wm)) l])))))
(def +dummy-data-args+ (apply concat (for [i (range 10)] [{:title (str "title" (mod i 4)) :text (str "text" (mod i 6))} (odd? i)])))
(def +dummy-data+ (apply featurized-data +dummy-data-args+))
(deftest train-and-eval-smoke-test
(letk [[model] (learn/train-and-eval
(classify/maxent-trainer {:pred-thresh 1})
classify/classification-evaluator
+dummy-data+
+dummy-data+)]
(let [datum {:title "title1 title2" :text "text1"}
score (fn [fs m d]
(classify/posteriors m (features/feature-vector fs {} d)))
old-scores (score +feature-set+ model datum)
model-data (classify/model->nested-weight-maps +feature-set+ model)
new-feature-set (features/feature-set [features-test/starts-with-letter-t])
new-model (classify/nested-weight-maps->model new-feature-set model-data)
new-scores (score new-feature-set new-model datum)]
(is-= old-scores new-scores)
(is (= {true {:lexical 8} false {}} (map-vals (partial map-vals count) model-data))))))
(deftest ^:slow estimate-perf-and-train-model-smoke-test
(is (learn/estimate-perf-and-train-model
{:trainer (classify/maxent-trainer {:pred-thresh 1})
:evaluator classify/classification-evaluator
:data +dummy-data+})))
(deftest multiclass-smoke-test
(let [data [[{:title "titlea" :text "texta"} :a]
[{:title "titleb" :text "textb"} :b]
[{:title "titlec" :text "textc"} :c]]
featurized (apply featurized-data (aconcat data))]
(letk [[model evaluation] (learn/train-and-eval
(classify/maxent-trainer {:pred-thresh 1})
classify/classification-evaluator
(aconcat (repeat 3 featurized))
featurized)]
(is-= {[:a :a] 1.0
[:b :b] 1.0
[:c :c] 1.0}
(map-vals (partial sum second) evaluation))
(is-= [:a :b :c] (map #(learn/label model (first %)) featurized)))))
(deftest em-smoke-test
"Test that we can learn by transferring from features on labeled data
to features on unlabeled data through shared features."
(let [labeled (featurized-data
{:title "titlea" :text ""} true
{:title "titleb" :text ""} false)
unlabeled (map
first
(featurized-data
{:title "titlea" :text "transfera"} :ignore
{:title "testa" :text "transfera"} :ignore
{:title "titleb" :text "transferb"} :ignore
{:title "testb" :text "transferb"} :ignore))
model ((classify/em-trainer
(classify/maxent-trainer {:pred-thresh 0 :sigma-sq 10.0})
unlabeled
{:print-progress false
:posteriors->weights (classify/hard-em-weighter 1.0 0.6)})
labeled)
weights (safe-get-in (classify/model->nested-weight-maps +feature-set+ model) [true :lexical])]
(is (every? #(> (weights %) 0.5) ["titlea" "transfera" "testa"]))
(is (every? #(< (weights %) -0.5) ["titleb" "transferb" "testb"]))))
(use-fixtures :once validate-schemas)
| |
01a135cf5dcf116b281ccf3f285c74a7168efbb9783accc8c19196f0a76eb327 | startalkIM/ejabberd | jid.erl | %%%-------------------------------------------------------------------
@author < >
%%% @doc
JID processing library
%%% @end
Created : 24 Nov 2015 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2016 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%-------------------------------------------------------------------
-module(jid).
%% API
-export([start/0,
make/1,
make/3,
split/1,
from_string/1,
to_string/1,
is_nodename/1,
nodeprep/1,
nameprep/1,
resourceprep/1,
tolower/1,
remove_resource/1,
replace_resource/2]).
-include("jlib.hrl").
-export_type([jid/0]).
%%%===================================================================
%%% API
%%%===================================================================
-spec start() -> ok.
start() ->
{ok, Owner} = ets_owner(),
SplitPattern = binary:compile_pattern([<<"@">>, <<"/">>]),
%% Table is public to allow ETS insert to fix / update the table even if table already exist
%% with another owner.
catch ets:new(jlib, [named_table, public, set, {keypos, 1}, {heir, Owner, undefined}]),
ets:insert(jlib, {string_to_jid_pattern, SplitPattern}),
ok.
ets_owner() ->
case whereis(jlib_ets) of
undefined ->
Pid = spawn(fun() -> ets_keepalive() end),
case catch register(jlib_ets, Pid) of
true ->
{ok, Pid};
Error -> Error
end;
Pid ->
{ok,Pid}
end.
%% Process used to keep jlib ETS table alive in case the original owner dies.
%% The table need to be public, otherwise subsequent inserts would fail.
ets_keepalive() ->
receive
_ ->
ets_keepalive()
end.
-spec make(binary(), binary(), binary()) -> jid() | error.
make(User, Server, Resource) ->
case nodeprep(User) of
error -> error;
LUser ->
case nameprep(Server) of
error -> error;
LServer ->
case resourceprep(Resource) of
error -> error;
LResource ->
#jid{user = User, server = Server, resource = Resource,
luser = LUser, lserver = LServer,
lresource = LResource}
end
end
end.
-spec make({binary(), binary(), binary()}) -> jid() | error.
make({User, Server, Resource}) ->
make(User, Server, Resource).
%% This is the reverse of make_jid/1
-spec split(jid()) -> {binary(), binary(), binary()} | error.
split(#jid{user = U, server = S, resource = R}) ->
{U, S, R};
split(_) ->
error.
-spec from_string(binary() | string()) -> jid() | error.
from_string(S) when is_list(S) ->
%% We do not accept list because we want to enforce good practice of
%% using binaries for string. However, we do not let it crash to avoid
%% losing associated ets table.
{error, need_jid_as_binary};
from_string(S) when is_binary(S) ->
SplitPattern = ets:lookup_element(jlib, string_to_jid_pattern, 2),
Size = size(S),
End = Size-1,
case binary:match(S, SplitPattern) of
{0, _} ->
error;
{End, _} ->
error;
{Pos1, _} ->
case binary:at(S, Pos1) of
$/ ->
make(<<>>,
binary:part(S, 0, Pos1),
binary:part(S, Pos1+1, Size-Pos1-1));
_ ->
Pos1N = Pos1+1,
case binary:match(S, SplitPattern, [{scope, {Pos1+1, Size-Pos1-1}}]) of
{End, _} ->
error;
{Pos1N, _} ->
error;
{Pos2, _} ->
case binary:at(S, Pos2) of
$/ ->
make(binary:part(S, 0, Pos1),
binary:part(S, Pos1+1, Pos2-Pos1-1),
binary:part(S, Pos2+1, Size-Pos2-1));
_ -> error
end;
_ ->
make(binary:part(S, 0, Pos1),
binary:part(S, Pos1+1, Size-Pos1-1),
<<>>)
end
end;
_ ->
make(<<>>, S, <<>>)
end.
-spec to_string(jid() | ljid()) -> binary().
to_string(#jid{user = User, server = Server,
resource = Resource}) ->
to_string({User, Server, Resource});
to_string({N, S, R}) ->
Node = iolist_to_binary(N),
Server = iolist_to_binary(S),
Resource = iolist_to_binary(R),
S1 = case Node of
<<"">> -> <<"">>;
_ -> <<Node/binary, "@">>
end,
S2 = <<S1/binary, Server/binary>>,
S3 = case Resource of
<<"">> -> S2;
_ -> <<S2/binary, "/", Resource/binary>>
end,
S3.
-spec is_nodename(binary()) -> boolean().
is_nodename(Node) ->
N = nodeprep(Node),
(N /= error) and (N /= <<>>).
-define(LOWER(Char),
if Char >= $A, Char =< $Z -> Char + 32;
true -> Char
end).
-spec nodeprep(binary()) -> binary() | error.
nodeprep("") -> <<>>;
nodeprep(S) when byte_size(S) < 1024 ->
R = stringprep:nodeprep(S),
if byte_size(R) < 1024 -> R;
true -> error
end;
nodeprep(_) -> error.
-spec nameprep(binary()) -> binary() | error.
nameprep(S) when byte_size(S) < 1024 ->
R = stringprep:nameprep(S),
if byte_size(R) < 1024 -> R;
true -> error
end;
nameprep(_) -> error.
-spec resourceprep(binary()) -> binary() | error.
resourceprep(S) when byte_size(S) < 1024 ->
R = stringprep:resourceprep(S),
if byte_size(R) < 1024 -> R;
true -> error
end;
resourceprep(_) -> error.
-spec tolower(jid() | ljid()) -> error | ljid().
tolower(#jid{luser = U, lserver = S,
lresource = R}) ->
{U, S, R};
tolower({U, S, R}) ->
case nodeprep(U) of
error -> error;
LUser ->
case nameprep(S) of
error -> error;
LServer ->
case resourceprep(R) of
error -> error;
LResource -> {LUser, LServer, LResource}
end
end
end.
-spec remove_resource(jid()) -> jid();
(ljid()) -> ljid().
remove_resource(#jid{} = JID) ->
JID#jid{resource = <<"">>, lresource = <<"">>};
remove_resource({U, S, _R}) -> {U, S, <<"">>}.
-spec replace_resource(jid(), binary()) -> error | jid().
replace_resource(JID, Resource) ->
case resourceprep(Resource) of
error -> error;
LResource ->
JID#jid{resource = Resource, lresource = LResource}
end.
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/src/jid.erl | erlang | -------------------------------------------------------------------
@doc
@end
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
-------------------------------------------------------------------
API
===================================================================
API
===================================================================
Table is public to allow ETS insert to fix / update the table even if table already exist
with another owner.
Process used to keep jlib ETS table alive in case the original owner dies.
The table need to be public, otherwise subsequent inserts would fail.
This is the reverse of make_jid/1
We do not accept list because we want to enforce good practice of
using binaries for string. However, we do not let it crash to avoid
losing associated ets table.
===================================================================
=================================================================== | @author < >
JID processing library
Created : 24 Nov 2015 by < >
ejabberd , Copyright ( C ) 2002 - 2016 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(jid).
-export([start/0,
make/1,
make/3,
split/1,
from_string/1,
to_string/1,
is_nodename/1,
nodeprep/1,
nameprep/1,
resourceprep/1,
tolower/1,
remove_resource/1,
replace_resource/2]).
-include("jlib.hrl").
-export_type([jid/0]).
-spec start() -> ok.
start() ->
{ok, Owner} = ets_owner(),
SplitPattern = binary:compile_pattern([<<"@">>, <<"/">>]),
catch ets:new(jlib, [named_table, public, set, {keypos, 1}, {heir, Owner, undefined}]),
ets:insert(jlib, {string_to_jid_pattern, SplitPattern}),
ok.
ets_owner() ->
case whereis(jlib_ets) of
undefined ->
Pid = spawn(fun() -> ets_keepalive() end),
case catch register(jlib_ets, Pid) of
true ->
{ok, Pid};
Error -> Error
end;
Pid ->
{ok,Pid}
end.
ets_keepalive() ->
receive
_ ->
ets_keepalive()
end.
-spec make(binary(), binary(), binary()) -> jid() | error.
make(User, Server, Resource) ->
case nodeprep(User) of
error -> error;
LUser ->
case nameprep(Server) of
error -> error;
LServer ->
case resourceprep(Resource) of
error -> error;
LResource ->
#jid{user = User, server = Server, resource = Resource,
luser = LUser, lserver = LServer,
lresource = LResource}
end
end
end.
-spec make({binary(), binary(), binary()}) -> jid() | error.
make({User, Server, Resource}) ->
make(User, Server, Resource).
-spec split(jid()) -> {binary(), binary(), binary()} | error.
split(#jid{user = U, server = S, resource = R}) ->
{U, S, R};
split(_) ->
error.
-spec from_string(binary() | string()) -> jid() | error.
from_string(S) when is_list(S) ->
{error, need_jid_as_binary};
from_string(S) when is_binary(S) ->
SplitPattern = ets:lookup_element(jlib, string_to_jid_pattern, 2),
Size = size(S),
End = Size-1,
case binary:match(S, SplitPattern) of
{0, _} ->
error;
{End, _} ->
error;
{Pos1, _} ->
case binary:at(S, Pos1) of
$/ ->
make(<<>>,
binary:part(S, 0, Pos1),
binary:part(S, Pos1+1, Size-Pos1-1));
_ ->
Pos1N = Pos1+1,
case binary:match(S, SplitPattern, [{scope, {Pos1+1, Size-Pos1-1}}]) of
{End, _} ->
error;
{Pos1N, _} ->
error;
{Pos2, _} ->
case binary:at(S, Pos2) of
$/ ->
make(binary:part(S, 0, Pos1),
binary:part(S, Pos1+1, Pos2-Pos1-1),
binary:part(S, Pos2+1, Size-Pos2-1));
_ -> error
end;
_ ->
make(binary:part(S, 0, Pos1),
binary:part(S, Pos1+1, Size-Pos1-1),
<<>>)
end
end;
_ ->
make(<<>>, S, <<>>)
end.
-spec to_string(jid() | ljid()) -> binary().
to_string(#jid{user = User, server = Server,
resource = Resource}) ->
to_string({User, Server, Resource});
to_string({N, S, R}) ->
Node = iolist_to_binary(N),
Server = iolist_to_binary(S),
Resource = iolist_to_binary(R),
S1 = case Node of
<<"">> -> <<"">>;
_ -> <<Node/binary, "@">>
end,
S2 = <<S1/binary, Server/binary>>,
S3 = case Resource of
<<"">> -> S2;
_ -> <<S2/binary, "/", Resource/binary>>
end,
S3.
-spec is_nodename(binary()) -> boolean().
is_nodename(Node) ->
N = nodeprep(Node),
(N /= error) and (N /= <<>>).
-define(LOWER(Char),
if Char >= $A, Char =< $Z -> Char + 32;
true -> Char
end).
-spec nodeprep(binary()) -> binary() | error.
nodeprep("") -> <<>>;
nodeprep(S) when byte_size(S) < 1024 ->
R = stringprep:nodeprep(S),
if byte_size(R) < 1024 -> R;
true -> error
end;
nodeprep(_) -> error.
-spec nameprep(binary()) -> binary() | error.
nameprep(S) when byte_size(S) < 1024 ->
R = stringprep:nameprep(S),
if byte_size(R) < 1024 -> R;
true -> error
end;
nameprep(_) -> error.
-spec resourceprep(binary()) -> binary() | error.
resourceprep(S) when byte_size(S) < 1024 ->
R = stringprep:resourceprep(S),
if byte_size(R) < 1024 -> R;
true -> error
end;
resourceprep(_) -> error.
-spec tolower(jid() | ljid()) -> error | ljid().
tolower(#jid{luser = U, lserver = S,
lresource = R}) ->
{U, S, R};
tolower({U, S, R}) ->
case nodeprep(U) of
error -> error;
LUser ->
case nameprep(S) of
error -> error;
LServer ->
case resourceprep(R) of
error -> error;
LResource -> {LUser, LServer, LResource}
end
end
end.
-spec remove_resource(jid()) -> jid();
(ljid()) -> ljid().
remove_resource(#jid{} = JID) ->
JID#jid{resource = <<"">>, lresource = <<"">>};
remove_resource({U, S, _R}) -> {U, S, <<"">>}.
-spec replace_resource(jid(), binary()) -> error | jid().
replace_resource(JID, Resource) ->
case resourceprep(Resource) of
error -> error;
LResource ->
JID#jid{resource = Resource, lresource = LResource}
end.
Internal functions
|
8581502cdeea5d9784c2c7cf6c6950a14ca804d6d5a97bda73dd8cbc7acd6ce3 | MyDataFlow/ttalk-server | riakc_obj.erl | %% -------------------------------------------------------------------
%%
riakc_obj : Container for data and metadata
%%
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you 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.
%%
%% -------------------------------------------------------------------
%% @doc riakc_obj is used to wrap bucket/key/value data sent to the
%% server on put and received on get. It provides
%% accessors for retrieving the data and metadata
%% and copes with siblings if multiple values are allowed.
-module(riakc_obj).
-export([new/2, new/3, new/4,
bucket_type/1,
bucket/1,
only_bucket/1,
key/1,
vclock/1,
value_count/1,
select_sibling/2,
get_contents/1,
get_metadata/1,
get_metadatas/1,
get_content_type/1,
get_content_types/1,
get_value/1,
get_values/1,
update_metadata/2,
update_value/2,
update_value/3,
update_content_type/2,
get_update_metadata/1,
get_update_content_type/1,
get_update_value/1,
md_ctype/1,
set_vclock/2,
get_user_metadata_entry/2,
get_user_metadata_entries/1,
clear_user_metadata_entries/1,
delete_user_metadata_entry/2,
set_user_metadata_entry/2,
get_secondary_index/2,
get_secondary_indexes/1,
clear_secondary_indexes/1,
delete_secondary_index/2,
set_secondary_index/2,
add_secondary_index/2,
get_links/2,
get_all_links/1,
clear_links/1,
delete_links/2,
set_link/2,
add_link/2
]).
Internal library use only
-export([new_obj/4,index_id_to_bin/1]).
-include_lib("riak_pb/include/riak_pb_kv_codec.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-type bucket() :: binary() | {binary(), binary()}. %% A bucket name
-type key() :: binary() | 'undefined'. %% A key name
-type id() :: {bucket(), key()}.
-type vclock() :: binary(). %% An opaque vector clock
-type content_type() :: string(). %% The media type of a value
-type value() :: binary(). %% An opaque value
-type contents() :: [{metadata(), value()}]. %% All metadata/value pairs in a `riakc_obj'.
-type binary_index_id() :: {binary_index, string()}.
-type binary_index_value() :: binary().
-type binary_index() :: {binary_index_id(), [binary_index_value()]}.
-type integer_index_id() :: {integer_index, string()}.
-type integer_index_value() :: integer().
-type integer_index() :: {integer_index_id(), [integer_index_value()]}.
-type secondary_index_id() :: binary_index_id() | integer_index_id().
-type secondary_index_value() :: integer_index_value() | binary_index_value().
-type secondary_index() :: binary_index() | integer_index().
-type metadata_key() :: binary().
-type metadata_value() :: binary().
-type metadata_entry() :: {metadata_key(), metadata_value()}.
-ifdef(pre17).
-type metadata() :: dict(). %% Value metadata
-else.
-type metadata() :: dict:dict(metadata_key(), metadata_value()).
-endif.
-type tag() :: binary().
-type link() :: {tag(), [id()]}.
-record(riakc_obj, {
bucket :: bucket(),
key :: key(),
vclock :: vclock(),
contents :: contents(),
updatemetadata :: metadata(),
updatevalue :: value()
}).
The record / type containing the entire Riak object .
-export_type([riakc_obj/0, bucket/0, key/0, vclock/0, contents/0, metadata/0, value/0,
binary_index_id/0, binary_index/0, integer_index_id/0, integer_index/0,
secondary_index/0, metadata_key/0, metadata_value/0, metadata_entry/0]).
%% ====================================================================
%% object functions
%% ====================================================================
%% @doc Constructor for new riak client objects.
-spec new(bucket(), key()) -> riakc_obj().
new(Bucket, Key) ->
build_client_object(Bucket, Key, undefined).
%% @doc Constructor for new riak client objects with an update value.
-spec new(bucket(), key(), value()) -> riakc_obj().
new(Bucket, Key, Value) ->
build_client_object(Bucket, Key, Value).
%% @doc Constructor for new riak client objects with an update value and content type.
-spec new(bucket(), key(), value(), content_type()) -> riakc_obj().
new(Bucket, Key, Value, ContentType) ->
case build_client_object(Bucket, Key, Value) of
{error, Reason} ->
{error, Reason};
O ->
update_content_type(O, ContentType)
end.
%% @doc Build a new riak client object with non-empty key
-spec build_client_object(bucket(), key(), undefined | value()) ->
riakc_obj() | {error, atom()}.
build_client_object(<<>>, K, _) when is_binary(K) ->
{error, zero_length_bucket};
build_client_object(B, <<>>, _) when is_binary(B) ->
{error, zero_length_key};
build_client_object({T, B0}=B, K, V) when is_binary(T), is_binary(B0), is_binary(K) orelse undefined =:= K ->
#riakc_obj{bucket = B, key = K, contents = [], updatevalue = V};
build_client_object(B, K, V) when is_binary(B), is_binary(K) orelse undefined =:= K ->
#riakc_obj{bucket = B, key = K, contents = [], updatevalue = V}.
%% @doc Return the containing bucket for this riakc_obj.
-spec bucket(Object::riakc_obj()) -> bucket().
bucket(O) ->
O#riakc_obj.bucket.
%% @doc Return the containing bucket for this riakc_obj.
-spec only_bucket(Object::riakc_obj()) -> binary().
only_bucket(O) ->
case O#riakc_obj.bucket of
{_Type, Bucket} ->
Bucket;
Bucket ->
Bucket
end.
-spec bucket_type(Object::riakc_obj()) -> bucket().
bucket_type(O) ->
case O#riakc_obj.bucket of
{Type, _Bucket} ->
Type;
_Bucket ->
undefined
end.
%% @doc Return the key for this riakc_obj.
-spec key(Object::riakc_obj()) -> key().
key(O) ->
O#riakc_obj.key.
%% @doc Return the vector clock for this riakc_obj.
-spec vclock(Object::riakc_obj()) -> vclock() | undefined.
vclock(O) ->
O#riakc_obj.vclock.
%% @doc Return the number of values (siblings) of this riakc_obj.
-spec value_count(Object::riakc_obj()) -> non_neg_integer().
value_count(#riakc_obj{contents=Contents}) ->
length(Contents).
@doc Select the sibling to use for update - starting from 1 .
-spec select_sibling(pos_integer(), Object::riakc_obj()) -> riakc_obj().
select_sibling(Index, O) ->
{MD,V} = lists:nth(Index, O#riakc_obj.contents),
O#riakc_obj{updatemetadata=MD, updatevalue=V}.
%% @doc Return the contents (a list of {metadata, value} tuples) for
%% this riakc_obj.
-spec get_contents(Object::riakc_obj()) -> contents().
get_contents(O) ->
O#riakc_obj.contents.
%% @doc Assert that this riakc_obj has no siblings and return its
%% associated metadata. This function will throw `siblings' if
the object has siblings ( value_count ( ) > 1 ) .
%% @throws siblings
-spec get_metadata(Object::riakc_obj()) -> metadata().
get_metadata(O=#riakc_obj{}) ->
case get_contents(O) of
[] ->
dict:new();
[{MD,_V}] ->
MD;
_ ->
throw(siblings)
end.
%% @doc Return a list of the metadata values for this riakc_obj.
-spec get_metadatas(Object::riakc_obj()) -> [metadata()].
get_metadatas(#riakc_obj{contents=Contents}) ->
[M || {M,_V} <- Contents].
%% @doc Return the content type of the value if there are no siblings.
%% @see get_metadata/1
%% @throws siblings
-spec get_content_type(Object::riakc_obj()) -> content_type().
get_content_type(Object=#riakc_obj{}) ->
UM = get_metadata(Object),
md_ctype(UM).
%% @doc Return a list of content types for all siblings.
-spec get_content_types(Object::riakc_obj()) -> [content_type()].
get_content_types(Object=#riakc_obj{}) ->
F = fun({M,_}) -> md_ctype(M) end,
[F(C) || C<- get_contents(Object)].
%% @doc Assert that this riakc_obj has no siblings and return its
%% associated value. This function will throw `siblings' if the
object has siblings ( value_count ( ) > 1 ) , or ` no_value ' if the
%% object has no value.
%% @throws siblings | no_value
-spec get_value(Object::riakc_obj()) -> value().
get_value(#riakc_obj{}=O) ->
case get_contents(O) of
[] ->
throw(no_value);
[{_MD,V}] ->
V;
_ ->
throw(siblings)
end.
%% @doc Return a list of object values for this riakc_obj.
-spec get_values(Object::riakc_obj()) -> [value()].
get_values(#riakc_obj{contents=Contents}) ->
[V || {_,V} <- Contents].
%% @doc Set the updated metadata of an object to M.
-spec update_metadata(riakc_obj(), metadata()) -> riakc_obj().
update_metadata(Object=#riakc_obj{}, M) ->
Object#riakc_obj{updatemetadata=M}.
%% @doc Set the updated content-type of an object to CT.
-spec update_content_type(riakc_obj(),content_type()|binary()) -> riakc_obj().
update_content_type(Object=#riakc_obj{}, CT) when is_binary(CT) ->
update_content_type(Object, binary_to_list(CT));
update_content_type(Object=#riakc_obj{}, CT) when is_list(CT) ->
M1 = get_update_metadata(Object),
Object#riakc_obj{updatemetadata=dict:store(?MD_CTYPE, CT, M1)}.
%% @doc Set the updated value of an object to V
-spec update_value(riakc_obj(), value()) -> riakc_obj().
update_value(Object=#riakc_obj{}, V) -> Object#riakc_obj{updatevalue=V}.
%% @doc Set the updated value of an object to V
-spec update_value(riakc_obj(), value(), content_type()) -> riakc_obj().
update_value(Object=#riakc_obj{}, V, CT) ->
O1 = update_content_type(Object, CT),
O1#riakc_obj{updatevalue=V}.
%% @doc Return the updated metadata of this riakc_obj.
-spec get_update_metadata(Object::riakc_obj()) -> metadata().
get_update_metadata(#riakc_obj{updatemetadata=UM}=Object) ->
case UM of
undefined ->
get_metadata(Object);
UM ->
UM
end.
%% @doc Return the content type of the update value
-spec get_update_content_type(riakc_obj()) -> content_type().
get_update_content_type(Object=#riakc_obj{}) ->
UM = get_update_metadata(Object),
md_ctype(UM).
%% @doc Return the updated value of this riakc_obj.
-spec get_update_value(Object::riakc_obj()) -> value().
get_update_value(#riakc_obj{updatevalue=UV}=Object) ->
case UV of
undefined ->
get_value(Object);
UV ->
UV
end.
%% @doc Return the content type from metadata
-spec md_ctype(metadata()) -> undefined | content_type().
md_ctype(MetaData) ->
case dict:find(?MD_CTYPE, MetaData) of
error ->
undefined;
{ok, Ctype} ->
Ctype
end.
%% @doc Set the vector clock of an object
-spec set_vclock(riakc_obj(), vclock()) -> riakc_obj().
set_vclock(Object=#riakc_obj{}, Vclock) ->
Object#riakc_obj{vclock=Vclock}.
%% @doc Get specific metadata entry
-spec get_user_metadata_entry(metadata(), metadata_key()) -> metadata_value() | notfound.
get_user_metadata_entry(MD, Key) ->
case dict:find(?MD_USERMETA, MD) of
{ok, Entries} ->
case lists:keyfind(Key, 1, Entries) of
false ->
notfound;
{Key, Value} ->
Value
end;
error ->
notfound
end.
%% @doc Get all metadata entries
-spec get_user_metadata_entries(metadata()) -> [metadata_entry()].
get_user_metadata_entries(MD) ->
case dict:find(?MD_USERMETA, MD) of
{ok, Entries} ->
Entries;
error ->
[]
end.
%% @doc Clear all metadata entries
-spec clear_user_metadata_entries(metadata()) -> metadata().
clear_user_metadata_entries(MD) ->
dict:erase(?MD_USERMETA, MD).
%% @doc Delete specific metadata entry
-spec delete_user_metadata_entry(metadata(), metadata_key()) -> metadata().
delete_user_metadata_entry(MD, Key) ->
case dict:find(?MD_USERMETA, MD) of
{ok, Entries} ->
case [{K, V} || {K, V} <- Entries, K /= Key] of
[] ->
dict:erase(?MD_USERMETA, MD);
NewList ->
dict:store(?MD_USERMETA, NewList, MD)
end;
error ->
MD
end.
%% @doc Set a metadata entry
-spec set_user_metadata_entry(metadata(), metadata_entry()) -> metadata().
set_user_metadata_entry(MD, {Key, Value}) ->
case dict:find(?MD_USERMETA, MD) of
{ok, Entries} ->
case [{K, V} || {K, V} <- Entries, K /= Key] of
[] ->
dict:store(?MD_USERMETA, [{Key, Value}], MD);
List ->
dict:store(?MD_USERMETA, [{Key, Value} | List], MD)
end;
error ->
dict:store(?MD_USERMETA, [{Key, Value}], MD)
end.
%% @doc Get value(s) for specific secondary index
-spec get_secondary_index(metadata(), secondary_index_id()) -> [secondary_index_value()] | notfound.
get_secondary_index(MD, {Type, Name}) ->
IndexName = index_id_to_bin({Type, Name}),
case dict:find(?MD_INDEX, MD) of
{ok, Entries} ->
case {Type, [V || {K, V} <- Entries, K == IndexName]} of
{_, []} ->
notfound;
{binary_index, List} ->
List;
{integer_index, List} ->
[list_to_integer(binary_to_list(I)) || I <- List]
end;
error ->
notfound
end.
%% @doc Get all secondary indexes
-spec get_secondary_indexes(metadata()) -> [secondary_index()].
get_secondary_indexes(MD) ->
case dict:find(?MD_INDEX, MD) of
{ok, Entries} ->
dict:to_list(lists:foldl(fun({N, V}, D) ->
case bin_to_index_id(N) of
{binary_index, Name} ->
dict:append({binary_index, Name}, V, D);
{integer_index, Name} ->
Int = list_to_integer(binary_to_list(V)),
dict:append({integer_index, Name}, Int, D)
end
end, dict:new(), Entries));
error ->
[]
end.
%% @doc Clear all secondary indexes
-spec clear_secondary_indexes(metadata()) -> metadata().
clear_secondary_indexes(MD) ->
dict:erase(?MD_INDEX, MD).
%% @doc Delete specific secondary index
-spec delete_secondary_index(metadata(), secondary_index_id()) -> metadata().
delete_secondary_index(MD, IndexId) ->
IndexName = index_id_to_bin(IndexId),
case dict:find(?MD_INDEX, MD) of
{ok, Entries} ->
List = [{N, V} || {N, V} <- Entries, N /= IndexName],
dict:store(?MD_INDEX, List, MD);
error ->
MD
end.
%% @doc Set a secondary index
-spec set_secondary_index(metadata(), secondary_index() | [secondary_index()]) -> metadata().
set_secondary_index(MD, []) ->
MD;
set_secondary_index(MD, {{binary_index, Name}, BinList}) ->
set_secondary_index(MD, [{{binary_index, Name}, BinList}]);
set_secondary_index(MD, {{integer_index, Name}, IntList}) ->
set_secondary_index(MD, [{{integer_index, Name}, IntList}]);
set_secondary_index(MD, [{{binary_index, Name}, BinList} | Rest]) ->
IndexName = index_id_to_bin({binary_index, Name}),
set_secondary_index(MD, [{IndexName, BinList} | Rest]);
set_secondary_index(MD, [{{integer_index, Name}, IntList} | Rest]) ->
IndexName = index_id_to_bin({integer_index, Name}),
set_secondary_index(MD, [{IndexName, [list_to_binary(integer_to_list(I)) || I <- IntList]} | Rest]);
set_secondary_index(MD, [{Id, BinList} | Rest]) when is_binary(Id) ->
List = [{Id, V} || V <- BinList],
case dict:find(?MD_INDEX, MD) of
{ok, Entries} ->
OtherEntries = [{N, V} || {N, V} <- Entries, N /= Id],
NewList = lists:usort(lists:append(OtherEntries, List)),
MD2 = dict:store(?MD_INDEX, NewList, MD),
set_secondary_index(MD2, Rest);
error ->
NewList = lists:usort(List),
MD2 = dict:store(?MD_INDEX, NewList, MD),
set_secondary_index(MD2, Rest)
end.
%% @doc Add a secondary index
-spec add_secondary_index(metadata(), secondary_index() | [secondary_index()]) -> metadata().
add_secondary_index(MD, []) ->
MD;
add_secondary_index(MD, {{binary_index, Name}, BinList}) ->
add_secondary_index(MD, [{{binary_index, Name}, BinList}]);
add_secondary_index(MD, {{integer_index, Name}, IntList}) ->
add_secondary_index(MD, [{{integer_index, Name}, IntList}]);
add_secondary_index(MD, [{{binary_index, Name}, BinList} | Rest]) ->
IndexName = index_id_to_bin({binary_index, Name}),
add_secondary_index(MD, [{IndexName, BinList} | Rest]);
add_secondary_index(MD, [{{integer_index, Name}, IntList} | Rest]) ->
IndexName = index_id_to_bin({integer_index, Name}),
add_secondary_index(MD, [{IndexName, [list_to_binary(integer_to_list(I)) || I <- IntList]} | Rest]);
add_secondary_index(MD, [{Id, BinList} | Rest]) when is_binary(Id) ->
List = [{Id, V} || V <- BinList],
case dict:find(?MD_INDEX, MD) of
{ok, Entries} ->
NewList = lists:usort(lists:append(Entries, List)),
MD2 = dict:store(?MD_INDEX, NewList, MD),
add_secondary_index(MD2, Rest);
error ->
NewList = lists:usort(List),
MD2 = dict:store(?MD_INDEX, NewList, MD),
add_secondary_index(MD2, Rest)
end.
%% @doc Get links for a specific tag
-spec get_links(metadata(), tag()) -> [id()] | notfound.
get_links(MD, Tag) ->
case dict:find(?MD_LINKS, MD) of
{ok, Links} ->
case [I || {I, T} <- Links, T == Tag] of
[] ->
notfound;
List ->
List
end;
error ->
notfound
end.
%% @doc Get all links
-spec get_all_links(metadata()) -> [link()].
get_all_links(MD) ->
case dict:find(?MD_LINKS, MD) of
{ok, Links} ->
dict:to_list(lists:foldl(fun({I, T}, D) ->
dict:append(T, I, D)
end, dict:new(), Links));
error ->
[]
end.
%% @doc Clear all links
-spec clear_links(metadata()) -> metadata().
clear_links(MD) ->
dict:erase(?MD_LINKS, MD).
%% @doc Delete links for a specific tag
-spec delete_links(metadata(), tag()) -> metadata().
delete_links(MD, Tag) ->
case dict:find(?MD_LINKS, MD) of
{ok, Links} ->
List = [{I, T} || {I, T} <- Links, T /= Tag],
dict:store(?MD_LINKS, List, MD);
error ->
MD
end.
%% @doc Set links for a specific tag
-spec set_link(metadata(), link() | [link()]) -> metadata().
set_link(MD, []) ->
MD;
set_link(MD, Link) when is_tuple(Link) ->
set_link(MD, [Link]);
set_link(MD, [{T, IdList} | Rest]) ->
List = [{I, T} || I <- IdList],
case dict:find(?MD_LINKS, MD) of
{ok, Links} ->
OtherLinks = [{N, Tag} || {N, Tag} <- Links, Tag /= T],
NewList = lists:usort(lists:append(OtherLinks, List)),
MD2 = dict:store(?MD_LINKS, NewList, MD),
set_link(MD2, Rest);
error ->
NewList = lists:usort(List),
MD2 = dict:store(?MD_LINKS, NewList, MD),
set_link(MD2, Rest)
end.
%% @doc Add links for a specific tag
-spec add_link(metadata(), secondary_index() | [secondary_index()]) -> metadata().
add_link(MD, []) ->
MD;
add_link(MD, Link) when is_tuple(Link) ->
add_link(MD, [Link]);
add_link(MD, [{T, IdList} | Rest]) ->
List = [{I, T} || I <- IdList],
case dict:find(?MD_LINKS, MD) of
{ok, Links} ->
NewList = lists:usort(lists:append(Links, List)),
MD2 = dict:store(?MD_LINKS, NewList, MD),
add_link(MD2, Rest);
error ->
NewList = lists:usort(List),
MD2 = dict:store(?MD_LINKS, NewList, MD),
add_link(MD2, Rest)
end.
%% @doc INTERNAL USE ONLY. Set the contents of riakc_obj to the
{ Metadata , Value } pairs in MVs . Normal clients should use the
%% set_update_[value|metadata]() + apply_updates() method for changing
%% object contents.
@private
-spec new_obj(bucket(), key(), vclock(), contents()) -> riakc_obj().
new_obj(Bucket, Key, Vclock, Contents) ->
#riakc_obj{bucket = Bucket, key = Key, vclock = Vclock, contents = Contents}.
%% @doc INTERNAL USE ONLY. Convert binary secondary index name to index id tuple.
@private
-spec bin_to_index_id(binary()) -> secondary_index_id().
bin_to_index_id(Index) ->
Str = binary_to_list(Index),
case lists:split((length(Str) - 4), Str) of
{Name, "_bin"} ->
{binary_index, Name};
{Name, "_int"} ->
{integer_index, Name}
end.
@doc INTERNAL USE ONLY . Convert index i d tuple to binary index name
@private
-spec index_id_to_bin(secondary_index_id()) -> binary().
index_id_to_bin({binary_index, Name}) ->
list_to_binary([Name, "_bin"]);
index_id_to_bin({integer_index, Name}) ->
list_to_binary([Name, "_int"]).
%% ===================================================================
%% Unit Tests
%% ===================================================================
-ifdef(TEST).
bucket_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
?assertEqual(<<"b">>, bucket(O)).
key_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
?assertEqual(<<"k">>, key(O)).
invalid_key_test() ->
?assertMatch({error, _}, riakc_obj:new(<<"b">>, <<>>)),
?assertMatch({error, _}, riakc_obj:new(<<"b">>, <<>>, <<"v">>)),
?assertMatch({error, _}, riakc_obj:new(<<"b">>, <<>>, <<"v">>, <<"application/x-foo">>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<"k">>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<"k">>, <<"v">>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<"k">>, <<"v">>, <<"application/x-foo">>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<>>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<>>, <<"v">>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<>>, <<"v">>, <<"application/x-foo">>)),
?assertMatch(#riakc_obj{}, riakc_obj:new(<<"b">>, undefined)),
?assertError(function_clause, riakc_obj:new("bucket","key")).
vclock_test() ->
%% For internal use only
O = riakc_obj:new_obj(<<"b">>, <<"k">>, <<"vclock">>, []),
?assertEqual(<<"vclock">>, vclock(O)).
newcontent0_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
?assertEqual(0, value_count(O)),
?assertEqual([], get_metadatas(O)),
?assertEqual([], get_values(O)),
?assertEqual([], get_contents(O)),
?assertEqual(dict:new(), get_metadata(O)),
?assertThrow(no_value, get_value(O)).
contents0_test() ->
O = riakc_obj:new_obj(<<"b">>, <<"k">>, <<"vclock">>, []),
?assertEqual(0, value_count(O)),
?assertEqual([], get_metadatas(O)),
?assertEqual([], get_values(O)),
?assertEqual([], get_contents(O)),
?assertEqual(dict:new(), get_metadata(O)),
?assertThrow(no_value, get_value(O)).
contents1_test() ->
M1 = dict:from_list([{?MD_VTAG, "tag1"}]),
O = riakc_obj:new_obj(<<"b">>, <<"k">>, <<"vclock">>,
[{M1, <<"val1">>}]),
?assertEqual(1, value_count(O)),
?assertEqual([M1], get_metadatas(O)),
?assertEqual([<<"val1">>], get_values(O)),
?assertEqual([{M1,<<"val1">>}], get_contents(O)),
?assertEqual(M1, get_metadata(O)),
?assertEqual(<<"val1">>, get_value(O)).
contents2_test() ->
M1 = dict:from_list([{?MD_VTAG, "tag1"}]),
M2 = dict:from_list([{?MD_VTAG, "tag1"}]),
O = riakc_obj:new_obj(<<"b">>, <<"k">>, <<"vclock">>,
[{M1, <<"val1">>},
{M2, <<"val2">>}]),
?assertEqual(2, value_count(O)),
?assertEqual([M1, M2], get_metadatas(O)),
?assertEqual([<<"val1">>, <<"val2">>], get_values(O)),
?assertEqual([{M1,<<"val1">>},{M2,<<"val2">>}], get_contents(O)),
?assertThrow(siblings, get_metadata(O)),
?assertThrow(siblings, get_value(O)).
update_metadata_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
UM = riakc_obj:get_update_metadata(O),
?assertEqual([], dict:to_list(UM)).
update_value_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
?assertThrow(no_value, get_update_value(O)),
O1 = riakc_obj:update_value(O, <<"v">>),
?assertEqual(<<"v">>, get_update_value(O1)),
M1 = dict:from_list([{?MD_VTAG, "tag1"}]),
O2 = riakc_obj:update_metadata(O1, M1),
?assertEqual(M1, get_update_metadata(O2)).
updatevalue_ct_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
?assertThrow(no_value, get_update_value(O)),
O1 = riakc_obj:update_value(O, <<"v">>, "x-application/custom"),
?assertEqual(<<"v">>, get_update_value(O1)),
M1 = dict:from_list([{?MD_VTAG, "tag1"}]),
O2 = riakc_obj:update_metadata(O1, M1),
?assertEqual(M1, get_update_metadata(O2)),
?assertEqual("x-application/custom", get_update_content_type(O1)).
update_content_type_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
undefined = get_update_content_type(O),
O1 = update_content_type(O, "application/json"),
?assertEqual("application/json", get_update_content_type(O1)).
binary_content_type_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>, <<"v">>, <<"application/x-foo">>),
?assertEqual("application/x-foo", get_update_content_type(O)),
O1 = update_content_type(O, <<"application/x-bar">>),
?assertEqual("application/x-bar", get_update_content_type(O1)).
get_update_data_test() ->
MD0 = dict:from_list([{?MD_CTYPE, "text/plain"}]),
MD1 = dict:from_list([{?MD_CTYPE, "application/json"}]),
O = new_obj(<<"b">>, <<"k">>, <<"">>,
[{MD0, <<"v">>}]),
%% Create an updated metadata object
Oumd = update_metadata(O, MD1),
%% Create an updated value object
Ouv = update_value(O, <<"valueonly">>),
%% Create updated both object
Oboth = update_value(Oumd, <<"both">>),
%% dbgh:start(),
%% dbgh:trace(?MODULE)
io:format("O=~p\n", [O]),
?assertEqual(<<"v">>, get_update_value(O)),
MD2 = get_update_metadata(O),
io:format("MD2=~p\n", [MD2]),
?assertEqual("text/plain", md_ctype(MD2)),
MD3 = get_update_metadata(Oumd),
?assertEqual("application/json", md_ctype(MD3)),
?assertEqual(<<"valueonly">>, get_update_value(Ouv)),
MD4 = get_update_metadata(Ouv),
?assertEqual("text/plain", md_ctype(MD4)),
?assertEqual(<<"both">>, get_update_value(Oboth)),
MD5 = get_update_metadata(Oboth),
?assertEqual("application/json", md_ctype(MD5)).
%% get_update_data_sibs_test() ->
%% MD0 = dict:from_list([{?MD_CTYPE, "text/plain"}]),
%% MD1 = dict:from_list([{?MD_CTYPE, "application/json"}]),
%% O = new_obj(<<"b">>, <<"k">>, <<"">>,
%% [{MD0, <<"v">>},{MD1, <<"sibling">>}]),
%% %% Create an updated metadata object
%% Oumd = update_metadata(O, MD1),
%% %% Create an updated value object
%% Ouv = update_value(O, <<"valueonly">>),
%% %% Create updated both object
= , < < " both " > > ) ,
? assertThrow({error , siblings } , get_update_data(O ) ) ,
? assertThrow({error , siblings } , ) ) ,
? , siblings } , get_update_data(Ouv ) ) ,
%% ?assertEqual({ok, {MD1, <<"both">>}}, get_update_data(Oboth)).
select_sibling_test() ->
MD0 = dict:from_list([{?MD_CTYPE, "text/plain"}]),
MD1 = dict:from_list([{?MD_CTYPE, "application/json"}]),
O = new_obj(<<"b">>, <<"k">>, <<"">>,
[{MD0, <<"sib_one">>},
{MD1, <<"sib_two">>}]),
O1 = select_sibling(1, O),
O2 = select_sibling(2, O),
?assertEqual("text/plain", get_update_content_type(O1)),
?assertEqual(<<"sib_one">>, get_update_value(O1)),
?assertEqual("application/json", get_update_content_type(O2)),
?assertEqual(<<"sib_two">>, get_update_value(O2)).
user_metadata_utilities_test() ->
MD0 = dict:new(),
?assertEqual(dict:to_list(MD0), dict:to_list(delete_user_metadata_entry(MD0, <<"None">>))),
MD1 = set_user_metadata_entry(MD0,{<<"Key1">>, <<"Value0">>}),
?assertEqual([{<<"Key1">>, <<"Value0">>}], get_user_metadata_entries(MD1)),
MD2 = set_user_metadata_entry(MD1,{<<"Key1">>, <<"Value1">>}),
?assertEqual([{<<"Key1">>, <<"Value1">>}], get_user_metadata_entries(MD2)),
?assertEqual(notfound, get_user_metadata_entry(MD2, <<"WrongKey">>)),
MD3 = set_user_metadata_entry(MD2,{<<"Key2">>, <<"Value2">>}),
?assertEqual(<<"Value2">>, get_user_metadata_entry(MD3, <<"Key2">>)),
?assertEqual(2, length(get_user_metadata_entries(MD3))),
MD4 = delete_user_metadata_entry(MD3, <<"Key1">>),
?assertEqual([{<<"Key2">>, <<"Value2">>}], get_user_metadata_entries(MD4)),
MD5 = clear_user_metadata_entries(MD4),
?assertEqual([], get_user_metadata_entries(MD5)),
MD6 = delete_user_metadata_entry(MD1, <<"Key1">>),
?assertEqual([], get_user_metadata_entries(MD6)),
?assertEqual(notfound, get_user_metadata_entry(MD6, <<"Key1">>)).
link_utilities_test() ->
MD0 = dict:new(),
?assertEqual(notfound, get_links(MD0, <<"Tag1">>)),
?assertEqual([], get_all_links(MD0)),
MD1 = set_link(MD0, [{<<"Tag1">>, [{<<"B">>,<<"K1">>},{<<"B">>,<<"K2">>}]}]),
?assertEqual([{<<"B">>,<<"K1">>},{<<"B">>,<<"K2">>}], lists:sort(get_links(MD1,<<"Tag1">>))),
MD2 = add_link(MD1, [{<<"Tag1">>, [{<<"B">>,<<"K1">>},{<<"B">>,<<"K3">>}]}]),
?assertEqual([{<<"B">>,<<"K1">>},{<<"B">>,<<"K2">>},{<<"B">>,<<"K3">>}], lists:sort(get_links(MD2,<<"Tag1">>))),
MD3 = set_link(MD2, [{<<"Tag1">>, [{<<"B">>,<<"K4">>}]}]),
?assertEqual([{<<"B">>,<<"K4">>}], lists:sort(get_links(MD3,<<"Tag1">>))),
?assertEqual([{<<"Tag1">>,[{<<"B">>,<<"K4">>}]}], get_all_links(MD3)),
MD4 = set_link(MD3, [{<<"Tag2">>, [{<<"B">>,<<"K1">>}]}]),
?assertEqual([{<<"B">>,<<"K1">>}], lists:sort(get_links(MD4,<<"Tag2">>))),
MD5 = delete_links(MD4,<<"Tag1">>),
?assertEqual([{<<"Tag2">>,[{<<"B">>,<<"K1">>}]}], get_all_links(MD5)),
MD6 = clear_links(MD5),
?assertEqual([], get_all_links(MD6)).
secondary_index_utilities_test() ->
MD0 = dict:new(),
?assertEqual([], get_secondary_indexes(MD0)),
?assertEqual(notfound, get_secondary_index(MD0, {binary_index,"none"})),
?assertEqual(notfound, get_secondary_index(MD0, {integer_index,"none"})),
MD1 = set_secondary_index(MD0, [{{integer_index,"idx"}, [12,4,56]}]),
?assertEqual([4,12,56], lists:sort(get_secondary_index(MD1,{integer_index,"idx"}))),
MD2 = add_secondary_index(MD1, [{{integer_index,"idx"}, [4,15,34]}]),
?assertEqual([4,12,15,34,56], lists:sort(get_secondary_index(MD2,{integer_index,"idx"}))),
MD3 = set_secondary_index(MD2, {{integer_index,"idx"}, [7]}),
?assertEqual([7], lists:sort(get_secondary_index(MD3,{integer_index,"idx"}))),
MD4 = set_secondary_index(MD3, [{{binary_index,"idx"}, [<<"12">>,<<"4">>,<<"56">>]}]),
?assertEqual([<<"12">>,<<"4">>,<<"56">>], lists:sort(get_secondary_index(MD4,{binary_index,"idx"}))),
MD5 = add_secondary_index(MD4, [{{binary_index,"idx"}, [<<"4">>,<<"15">>,<<"34">>]}]),
?assertEqual([<<"12">>,<<"15">>,<<"34">>,<<"4">>,<<"56">>], lists:sort(get_secondary_index(MD5,{binary_index,"idx"}))),
MD6 = set_secondary_index(MD5, {{binary_index,"idx"}, [<<"7">>]}),
?assertEqual([<<"7">>], lists:sort(get_secondary_index(MD6,{binary_index,"idx"}))),
?assertEqual(2, length(get_secondary_indexes(MD6))),
?assertEqual(notfound, get_secondary_index(MD6,{binary_index,"error"})),
MD7 = delete_secondary_index(MD6,{binary_index,"idx"}),
?assertEqual([{{integer_index,"idx"},[7]}], get_secondary_indexes(MD7)),
MD8 = clear_secondary_indexes(MD7),
?assertEqual([], get_secondary_indexes(MD8)),
MD9 = delete_secondary_index(MD8,{binary_index,"none"}),
?assertEqual([], get_secondary_indexes(MD9)),
MD10 = add_secondary_index(MD9, [{{integer_index,"idx2"}, [23,4,34]}]),
?assertEqual([4,23,34], lists:sort(get_secondary_index(MD10,{integer_index,"idx2"}))),
MD11 = dict:new(),
?assertEqual([], get_secondary_indexes(MD11)),
?assertEqual(notfound, get_secondary_index(MD11, {binary_index,"none"})),
?assertEqual(notfound, get_secondary_index(MD11, {integer_index,"none"})),
MD12 = set_secondary_index(MD11, [{{integer_index,"itest"}, [12,4,56]},{{binary_index,"btest"}, [<<"test1">>]}]),
?assertEqual([4,12,56], lists:sort(get_secondary_index(MD12,{integer_index,"itest"}))),
?assertEqual([<<"test1">>], lists:sort(get_secondary_index(MD12,{binary_index,"btest"}))),
MD13 = add_secondary_index(MD12, [{{integer_index,"itest"}, [4,15,34]},{{binary_index,"btest"}, [<<"test2">>]}]),
?assertEqual([4,12,15,34,56], lists:sort(get_secondary_index(MD13,{integer_index,"itest"}))),
?assertEqual([<<"test1">>,<<"test2">>], lists:sort(get_secondary_index(MD13,{binary_index,"btest"}))).
-endif.
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/riakc/src/riakc_obj.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@doc riakc_obj is used to wrap bucket/key/value data sent to the
server on put and received on get. It provides
accessors for retrieving the data and metadata
and copes with siblings if multiple values are allowed.
A bucket name
A key name
An opaque vector clock
The media type of a value
An opaque value
All metadata/value pairs in a `riakc_obj'.
Value metadata
====================================================================
object functions
====================================================================
@doc Constructor for new riak client objects.
@doc Constructor for new riak client objects with an update value.
@doc Constructor for new riak client objects with an update value and content type.
@doc Build a new riak client object with non-empty key
@doc Return the containing bucket for this riakc_obj.
@doc Return the containing bucket for this riakc_obj.
@doc Return the key for this riakc_obj.
@doc Return the vector clock for this riakc_obj.
@doc Return the number of values (siblings) of this riakc_obj.
@doc Return the contents (a list of {metadata, value} tuples) for
this riakc_obj.
@doc Assert that this riakc_obj has no siblings and return its
associated metadata. This function will throw `siblings' if
@throws siblings
@doc Return a list of the metadata values for this riakc_obj.
@doc Return the content type of the value if there are no siblings.
@see get_metadata/1
@throws siblings
@doc Return a list of content types for all siblings.
@doc Assert that this riakc_obj has no siblings and return its
associated value. This function will throw `siblings' if the
object has no value.
@throws siblings | no_value
@doc Return a list of object values for this riakc_obj.
@doc Set the updated metadata of an object to M.
@doc Set the updated content-type of an object to CT.
@doc Set the updated value of an object to V
@doc Set the updated value of an object to V
@doc Return the updated metadata of this riakc_obj.
@doc Return the content type of the update value
@doc Return the updated value of this riakc_obj.
@doc Return the content type from metadata
@doc Set the vector clock of an object
@doc Get specific metadata entry
@doc Get all metadata entries
@doc Clear all metadata entries
@doc Delete specific metadata entry
@doc Set a metadata entry
@doc Get value(s) for specific secondary index
@doc Get all secondary indexes
@doc Clear all secondary indexes
@doc Delete specific secondary index
@doc Set a secondary index
@doc Add a secondary index
@doc Get links for a specific tag
@doc Get all links
@doc Clear all links
@doc Delete links for a specific tag
@doc Set links for a specific tag
@doc Add links for a specific tag
@doc INTERNAL USE ONLY. Set the contents of riakc_obj to the
set_update_[value|metadata]() + apply_updates() method for changing
object contents.
@doc INTERNAL USE ONLY. Convert binary secondary index name to index id tuple.
===================================================================
Unit Tests
===================================================================
For internal use only
Create an updated metadata object
Create an updated value object
Create updated both object
dbgh:start(),
dbgh:trace(?MODULE)
get_update_data_sibs_test() ->
MD0 = dict:from_list([{?MD_CTYPE, "text/plain"}]),
MD1 = dict:from_list([{?MD_CTYPE, "application/json"}]),
O = new_obj(<<"b">>, <<"k">>, <<"">>,
[{MD0, <<"v">>},{MD1, <<"sibling">>}]),
%% Create an updated metadata object
Oumd = update_metadata(O, MD1),
%% Create an updated value object
Ouv = update_value(O, <<"valueonly">>),
%% Create updated both object
?assertEqual({ok, {MD1, <<"both">>}}, get_update_data(Oboth)). | riakc_obj : Container for data and metadata
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(riakc_obj).
-export([new/2, new/3, new/4,
bucket_type/1,
bucket/1,
only_bucket/1,
key/1,
vclock/1,
value_count/1,
select_sibling/2,
get_contents/1,
get_metadata/1,
get_metadatas/1,
get_content_type/1,
get_content_types/1,
get_value/1,
get_values/1,
update_metadata/2,
update_value/2,
update_value/3,
update_content_type/2,
get_update_metadata/1,
get_update_content_type/1,
get_update_value/1,
md_ctype/1,
set_vclock/2,
get_user_metadata_entry/2,
get_user_metadata_entries/1,
clear_user_metadata_entries/1,
delete_user_metadata_entry/2,
set_user_metadata_entry/2,
get_secondary_index/2,
get_secondary_indexes/1,
clear_secondary_indexes/1,
delete_secondary_index/2,
set_secondary_index/2,
add_secondary_index/2,
get_links/2,
get_all_links/1,
clear_links/1,
delete_links/2,
set_link/2,
add_link/2
]).
Internal library use only
-export([new_obj/4,index_id_to_bin/1]).
-include_lib("riak_pb/include/riak_pb_kv_codec.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-type id() :: {bucket(), key()}.
-type binary_index_id() :: {binary_index, string()}.
-type binary_index_value() :: binary().
-type binary_index() :: {binary_index_id(), [binary_index_value()]}.
-type integer_index_id() :: {integer_index, string()}.
-type integer_index_value() :: integer().
-type integer_index() :: {integer_index_id(), [integer_index_value()]}.
-type secondary_index_id() :: binary_index_id() | integer_index_id().
-type secondary_index_value() :: integer_index_value() | binary_index_value().
-type secondary_index() :: binary_index() | integer_index().
-type metadata_key() :: binary().
-type metadata_value() :: binary().
-type metadata_entry() :: {metadata_key(), metadata_value()}.
-ifdef(pre17).
-else.
-type metadata() :: dict:dict(metadata_key(), metadata_value()).
-endif.
-type tag() :: binary().
-type link() :: {tag(), [id()]}.
-record(riakc_obj, {
bucket :: bucket(),
key :: key(),
vclock :: vclock(),
contents :: contents(),
updatemetadata :: metadata(),
updatevalue :: value()
}).
The record / type containing the entire Riak object .
-export_type([riakc_obj/0, bucket/0, key/0, vclock/0, contents/0, metadata/0, value/0,
binary_index_id/0, binary_index/0, integer_index_id/0, integer_index/0,
secondary_index/0, metadata_key/0, metadata_value/0, metadata_entry/0]).
-spec new(bucket(), key()) -> riakc_obj().
new(Bucket, Key) ->
build_client_object(Bucket, Key, undefined).
-spec new(bucket(), key(), value()) -> riakc_obj().
new(Bucket, Key, Value) ->
build_client_object(Bucket, Key, Value).
-spec new(bucket(), key(), value(), content_type()) -> riakc_obj().
new(Bucket, Key, Value, ContentType) ->
case build_client_object(Bucket, Key, Value) of
{error, Reason} ->
{error, Reason};
O ->
update_content_type(O, ContentType)
end.
-spec build_client_object(bucket(), key(), undefined | value()) ->
riakc_obj() | {error, atom()}.
build_client_object(<<>>, K, _) when is_binary(K) ->
{error, zero_length_bucket};
build_client_object(B, <<>>, _) when is_binary(B) ->
{error, zero_length_key};
build_client_object({T, B0}=B, K, V) when is_binary(T), is_binary(B0), is_binary(K) orelse undefined =:= K ->
#riakc_obj{bucket = B, key = K, contents = [], updatevalue = V};
build_client_object(B, K, V) when is_binary(B), is_binary(K) orelse undefined =:= K ->
#riakc_obj{bucket = B, key = K, contents = [], updatevalue = V}.
-spec bucket(Object::riakc_obj()) -> bucket().
bucket(O) ->
O#riakc_obj.bucket.
-spec only_bucket(Object::riakc_obj()) -> binary().
only_bucket(O) ->
case O#riakc_obj.bucket of
{_Type, Bucket} ->
Bucket;
Bucket ->
Bucket
end.
-spec bucket_type(Object::riakc_obj()) -> bucket().
bucket_type(O) ->
case O#riakc_obj.bucket of
{Type, _Bucket} ->
Type;
_Bucket ->
undefined
end.
-spec key(Object::riakc_obj()) -> key().
key(O) ->
O#riakc_obj.key.
-spec vclock(Object::riakc_obj()) -> vclock() | undefined.
vclock(O) ->
O#riakc_obj.vclock.
-spec value_count(Object::riakc_obj()) -> non_neg_integer().
value_count(#riakc_obj{contents=Contents}) ->
length(Contents).
@doc Select the sibling to use for update - starting from 1 .
-spec select_sibling(pos_integer(), Object::riakc_obj()) -> riakc_obj().
select_sibling(Index, O) ->
{MD,V} = lists:nth(Index, O#riakc_obj.contents),
O#riakc_obj{updatemetadata=MD, updatevalue=V}.
-spec get_contents(Object::riakc_obj()) -> contents().
get_contents(O) ->
O#riakc_obj.contents.
the object has siblings ( value_count ( ) > 1 ) .
-spec get_metadata(Object::riakc_obj()) -> metadata().
get_metadata(O=#riakc_obj{}) ->
case get_contents(O) of
[] ->
dict:new();
[{MD,_V}] ->
MD;
_ ->
throw(siblings)
end.
-spec get_metadatas(Object::riakc_obj()) -> [metadata()].
get_metadatas(#riakc_obj{contents=Contents}) ->
[M || {M,_V} <- Contents].
-spec get_content_type(Object::riakc_obj()) -> content_type().
get_content_type(Object=#riakc_obj{}) ->
UM = get_metadata(Object),
md_ctype(UM).
-spec get_content_types(Object::riakc_obj()) -> [content_type()].
get_content_types(Object=#riakc_obj{}) ->
F = fun({M,_}) -> md_ctype(M) end,
[F(C) || C<- get_contents(Object)].
object has siblings ( value_count ( ) > 1 ) , or ` no_value ' if the
-spec get_value(Object::riakc_obj()) -> value().
get_value(#riakc_obj{}=O) ->
case get_contents(O) of
[] ->
throw(no_value);
[{_MD,V}] ->
V;
_ ->
throw(siblings)
end.
-spec get_values(Object::riakc_obj()) -> [value()].
get_values(#riakc_obj{contents=Contents}) ->
[V || {_,V} <- Contents].
-spec update_metadata(riakc_obj(), metadata()) -> riakc_obj().
update_metadata(Object=#riakc_obj{}, M) ->
Object#riakc_obj{updatemetadata=M}.
-spec update_content_type(riakc_obj(),content_type()|binary()) -> riakc_obj().
update_content_type(Object=#riakc_obj{}, CT) when is_binary(CT) ->
update_content_type(Object, binary_to_list(CT));
update_content_type(Object=#riakc_obj{}, CT) when is_list(CT) ->
M1 = get_update_metadata(Object),
Object#riakc_obj{updatemetadata=dict:store(?MD_CTYPE, CT, M1)}.
-spec update_value(riakc_obj(), value()) -> riakc_obj().
update_value(Object=#riakc_obj{}, V) -> Object#riakc_obj{updatevalue=V}.
-spec update_value(riakc_obj(), value(), content_type()) -> riakc_obj().
update_value(Object=#riakc_obj{}, V, CT) ->
O1 = update_content_type(Object, CT),
O1#riakc_obj{updatevalue=V}.
-spec get_update_metadata(Object::riakc_obj()) -> metadata().
get_update_metadata(#riakc_obj{updatemetadata=UM}=Object) ->
case UM of
undefined ->
get_metadata(Object);
UM ->
UM
end.
-spec get_update_content_type(riakc_obj()) -> content_type().
get_update_content_type(Object=#riakc_obj{}) ->
UM = get_update_metadata(Object),
md_ctype(UM).
-spec get_update_value(Object::riakc_obj()) -> value().
get_update_value(#riakc_obj{updatevalue=UV}=Object) ->
case UV of
undefined ->
get_value(Object);
UV ->
UV
end.
-spec md_ctype(metadata()) -> undefined | content_type().
md_ctype(MetaData) ->
case dict:find(?MD_CTYPE, MetaData) of
error ->
undefined;
{ok, Ctype} ->
Ctype
end.
-spec set_vclock(riakc_obj(), vclock()) -> riakc_obj().
set_vclock(Object=#riakc_obj{}, Vclock) ->
Object#riakc_obj{vclock=Vclock}.
-spec get_user_metadata_entry(metadata(), metadata_key()) -> metadata_value() | notfound.
get_user_metadata_entry(MD, Key) ->
case dict:find(?MD_USERMETA, MD) of
{ok, Entries} ->
case lists:keyfind(Key, 1, Entries) of
false ->
notfound;
{Key, Value} ->
Value
end;
error ->
notfound
end.
-spec get_user_metadata_entries(metadata()) -> [metadata_entry()].
get_user_metadata_entries(MD) ->
case dict:find(?MD_USERMETA, MD) of
{ok, Entries} ->
Entries;
error ->
[]
end.
-spec clear_user_metadata_entries(metadata()) -> metadata().
clear_user_metadata_entries(MD) ->
dict:erase(?MD_USERMETA, MD).
-spec delete_user_metadata_entry(metadata(), metadata_key()) -> metadata().
delete_user_metadata_entry(MD, Key) ->
case dict:find(?MD_USERMETA, MD) of
{ok, Entries} ->
case [{K, V} || {K, V} <- Entries, K /= Key] of
[] ->
dict:erase(?MD_USERMETA, MD);
NewList ->
dict:store(?MD_USERMETA, NewList, MD)
end;
error ->
MD
end.
-spec set_user_metadata_entry(metadata(), metadata_entry()) -> metadata().
set_user_metadata_entry(MD, {Key, Value}) ->
case dict:find(?MD_USERMETA, MD) of
{ok, Entries} ->
case [{K, V} || {K, V} <- Entries, K /= Key] of
[] ->
dict:store(?MD_USERMETA, [{Key, Value}], MD);
List ->
dict:store(?MD_USERMETA, [{Key, Value} | List], MD)
end;
error ->
dict:store(?MD_USERMETA, [{Key, Value}], MD)
end.
-spec get_secondary_index(metadata(), secondary_index_id()) -> [secondary_index_value()] | notfound.
get_secondary_index(MD, {Type, Name}) ->
IndexName = index_id_to_bin({Type, Name}),
case dict:find(?MD_INDEX, MD) of
{ok, Entries} ->
case {Type, [V || {K, V} <- Entries, K == IndexName]} of
{_, []} ->
notfound;
{binary_index, List} ->
List;
{integer_index, List} ->
[list_to_integer(binary_to_list(I)) || I <- List]
end;
error ->
notfound
end.
-spec get_secondary_indexes(metadata()) -> [secondary_index()].
get_secondary_indexes(MD) ->
case dict:find(?MD_INDEX, MD) of
{ok, Entries} ->
dict:to_list(lists:foldl(fun({N, V}, D) ->
case bin_to_index_id(N) of
{binary_index, Name} ->
dict:append({binary_index, Name}, V, D);
{integer_index, Name} ->
Int = list_to_integer(binary_to_list(V)),
dict:append({integer_index, Name}, Int, D)
end
end, dict:new(), Entries));
error ->
[]
end.
-spec clear_secondary_indexes(metadata()) -> metadata().
clear_secondary_indexes(MD) ->
dict:erase(?MD_INDEX, MD).
-spec delete_secondary_index(metadata(), secondary_index_id()) -> metadata().
delete_secondary_index(MD, IndexId) ->
IndexName = index_id_to_bin(IndexId),
case dict:find(?MD_INDEX, MD) of
{ok, Entries} ->
List = [{N, V} || {N, V} <- Entries, N /= IndexName],
dict:store(?MD_INDEX, List, MD);
error ->
MD
end.
-spec set_secondary_index(metadata(), secondary_index() | [secondary_index()]) -> metadata().
set_secondary_index(MD, []) ->
MD;
set_secondary_index(MD, {{binary_index, Name}, BinList}) ->
set_secondary_index(MD, [{{binary_index, Name}, BinList}]);
set_secondary_index(MD, {{integer_index, Name}, IntList}) ->
set_secondary_index(MD, [{{integer_index, Name}, IntList}]);
set_secondary_index(MD, [{{binary_index, Name}, BinList} | Rest]) ->
IndexName = index_id_to_bin({binary_index, Name}),
set_secondary_index(MD, [{IndexName, BinList} | Rest]);
set_secondary_index(MD, [{{integer_index, Name}, IntList} | Rest]) ->
IndexName = index_id_to_bin({integer_index, Name}),
set_secondary_index(MD, [{IndexName, [list_to_binary(integer_to_list(I)) || I <- IntList]} | Rest]);
set_secondary_index(MD, [{Id, BinList} | Rest]) when is_binary(Id) ->
List = [{Id, V} || V <- BinList],
case dict:find(?MD_INDEX, MD) of
{ok, Entries} ->
OtherEntries = [{N, V} || {N, V} <- Entries, N /= Id],
NewList = lists:usort(lists:append(OtherEntries, List)),
MD2 = dict:store(?MD_INDEX, NewList, MD),
set_secondary_index(MD2, Rest);
error ->
NewList = lists:usort(List),
MD2 = dict:store(?MD_INDEX, NewList, MD),
set_secondary_index(MD2, Rest)
end.
-spec add_secondary_index(metadata(), secondary_index() | [secondary_index()]) -> metadata().
add_secondary_index(MD, []) ->
MD;
add_secondary_index(MD, {{binary_index, Name}, BinList}) ->
add_secondary_index(MD, [{{binary_index, Name}, BinList}]);
add_secondary_index(MD, {{integer_index, Name}, IntList}) ->
add_secondary_index(MD, [{{integer_index, Name}, IntList}]);
add_secondary_index(MD, [{{binary_index, Name}, BinList} | Rest]) ->
IndexName = index_id_to_bin({binary_index, Name}),
add_secondary_index(MD, [{IndexName, BinList} | Rest]);
add_secondary_index(MD, [{{integer_index, Name}, IntList} | Rest]) ->
IndexName = index_id_to_bin({integer_index, Name}),
add_secondary_index(MD, [{IndexName, [list_to_binary(integer_to_list(I)) || I <- IntList]} | Rest]);
add_secondary_index(MD, [{Id, BinList} | Rest]) when is_binary(Id) ->
List = [{Id, V} || V <- BinList],
case dict:find(?MD_INDEX, MD) of
{ok, Entries} ->
NewList = lists:usort(lists:append(Entries, List)),
MD2 = dict:store(?MD_INDEX, NewList, MD),
add_secondary_index(MD2, Rest);
error ->
NewList = lists:usort(List),
MD2 = dict:store(?MD_INDEX, NewList, MD),
add_secondary_index(MD2, Rest)
end.
-spec get_links(metadata(), tag()) -> [id()] | notfound.
get_links(MD, Tag) ->
case dict:find(?MD_LINKS, MD) of
{ok, Links} ->
case [I || {I, T} <- Links, T == Tag] of
[] ->
notfound;
List ->
List
end;
error ->
notfound
end.
-spec get_all_links(metadata()) -> [link()].
get_all_links(MD) ->
case dict:find(?MD_LINKS, MD) of
{ok, Links} ->
dict:to_list(lists:foldl(fun({I, T}, D) ->
dict:append(T, I, D)
end, dict:new(), Links));
error ->
[]
end.
-spec clear_links(metadata()) -> metadata().
clear_links(MD) ->
dict:erase(?MD_LINKS, MD).
-spec delete_links(metadata(), tag()) -> metadata().
delete_links(MD, Tag) ->
case dict:find(?MD_LINKS, MD) of
{ok, Links} ->
List = [{I, T} || {I, T} <- Links, T /= Tag],
dict:store(?MD_LINKS, List, MD);
error ->
MD
end.
-spec set_link(metadata(), link() | [link()]) -> metadata().
set_link(MD, []) ->
MD;
set_link(MD, Link) when is_tuple(Link) ->
set_link(MD, [Link]);
set_link(MD, [{T, IdList} | Rest]) ->
List = [{I, T} || I <- IdList],
case dict:find(?MD_LINKS, MD) of
{ok, Links} ->
OtherLinks = [{N, Tag} || {N, Tag} <- Links, Tag /= T],
NewList = lists:usort(lists:append(OtherLinks, List)),
MD2 = dict:store(?MD_LINKS, NewList, MD),
set_link(MD2, Rest);
error ->
NewList = lists:usort(List),
MD2 = dict:store(?MD_LINKS, NewList, MD),
set_link(MD2, Rest)
end.
-spec add_link(metadata(), secondary_index() | [secondary_index()]) -> metadata().
add_link(MD, []) ->
MD;
add_link(MD, Link) when is_tuple(Link) ->
add_link(MD, [Link]);
add_link(MD, [{T, IdList} | Rest]) ->
List = [{I, T} || I <- IdList],
case dict:find(?MD_LINKS, MD) of
{ok, Links} ->
NewList = lists:usort(lists:append(Links, List)),
MD2 = dict:store(?MD_LINKS, NewList, MD),
add_link(MD2, Rest);
error ->
NewList = lists:usort(List),
MD2 = dict:store(?MD_LINKS, NewList, MD),
add_link(MD2, Rest)
end.
{ Metadata , Value } pairs in MVs . Normal clients should use the
@private
-spec new_obj(bucket(), key(), vclock(), contents()) -> riakc_obj().
new_obj(Bucket, Key, Vclock, Contents) ->
#riakc_obj{bucket = Bucket, key = Key, vclock = Vclock, contents = Contents}.
@private
-spec bin_to_index_id(binary()) -> secondary_index_id().
bin_to_index_id(Index) ->
Str = binary_to_list(Index),
case lists:split((length(Str) - 4), Str) of
{Name, "_bin"} ->
{binary_index, Name};
{Name, "_int"} ->
{integer_index, Name}
end.
@doc INTERNAL USE ONLY . Convert index i d tuple to binary index name
@private
-spec index_id_to_bin(secondary_index_id()) -> binary().
index_id_to_bin({binary_index, Name}) ->
list_to_binary([Name, "_bin"]);
index_id_to_bin({integer_index, Name}) ->
list_to_binary([Name, "_int"]).
-ifdef(TEST).
bucket_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
?assertEqual(<<"b">>, bucket(O)).
key_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
?assertEqual(<<"k">>, key(O)).
invalid_key_test() ->
?assertMatch({error, _}, riakc_obj:new(<<"b">>, <<>>)),
?assertMatch({error, _}, riakc_obj:new(<<"b">>, <<>>, <<"v">>)),
?assertMatch({error, _}, riakc_obj:new(<<"b">>, <<>>, <<"v">>, <<"application/x-foo">>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<"k">>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<"k">>, <<"v">>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<"k">>, <<"v">>, <<"application/x-foo">>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<>>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<>>, <<"v">>)),
?assertMatch({error, _}, riakc_obj:new(<<>>, <<>>, <<"v">>, <<"application/x-foo">>)),
?assertMatch(#riakc_obj{}, riakc_obj:new(<<"b">>, undefined)),
?assertError(function_clause, riakc_obj:new("bucket","key")).
vclock_test() ->
O = riakc_obj:new_obj(<<"b">>, <<"k">>, <<"vclock">>, []),
?assertEqual(<<"vclock">>, vclock(O)).
newcontent0_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
?assertEqual(0, value_count(O)),
?assertEqual([], get_metadatas(O)),
?assertEqual([], get_values(O)),
?assertEqual([], get_contents(O)),
?assertEqual(dict:new(), get_metadata(O)),
?assertThrow(no_value, get_value(O)).
contents0_test() ->
O = riakc_obj:new_obj(<<"b">>, <<"k">>, <<"vclock">>, []),
?assertEqual(0, value_count(O)),
?assertEqual([], get_metadatas(O)),
?assertEqual([], get_values(O)),
?assertEqual([], get_contents(O)),
?assertEqual(dict:new(), get_metadata(O)),
?assertThrow(no_value, get_value(O)).
contents1_test() ->
M1 = dict:from_list([{?MD_VTAG, "tag1"}]),
O = riakc_obj:new_obj(<<"b">>, <<"k">>, <<"vclock">>,
[{M1, <<"val1">>}]),
?assertEqual(1, value_count(O)),
?assertEqual([M1], get_metadatas(O)),
?assertEqual([<<"val1">>], get_values(O)),
?assertEqual([{M1,<<"val1">>}], get_contents(O)),
?assertEqual(M1, get_metadata(O)),
?assertEqual(<<"val1">>, get_value(O)).
contents2_test() ->
M1 = dict:from_list([{?MD_VTAG, "tag1"}]),
M2 = dict:from_list([{?MD_VTAG, "tag1"}]),
O = riakc_obj:new_obj(<<"b">>, <<"k">>, <<"vclock">>,
[{M1, <<"val1">>},
{M2, <<"val2">>}]),
?assertEqual(2, value_count(O)),
?assertEqual([M1, M2], get_metadatas(O)),
?assertEqual([<<"val1">>, <<"val2">>], get_values(O)),
?assertEqual([{M1,<<"val1">>},{M2,<<"val2">>}], get_contents(O)),
?assertThrow(siblings, get_metadata(O)),
?assertThrow(siblings, get_value(O)).
update_metadata_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
UM = riakc_obj:get_update_metadata(O),
?assertEqual([], dict:to_list(UM)).
update_value_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
?assertThrow(no_value, get_update_value(O)),
O1 = riakc_obj:update_value(O, <<"v">>),
?assertEqual(<<"v">>, get_update_value(O1)),
M1 = dict:from_list([{?MD_VTAG, "tag1"}]),
O2 = riakc_obj:update_metadata(O1, M1),
?assertEqual(M1, get_update_metadata(O2)).
updatevalue_ct_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
?assertThrow(no_value, get_update_value(O)),
O1 = riakc_obj:update_value(O, <<"v">>, "x-application/custom"),
?assertEqual(<<"v">>, get_update_value(O1)),
M1 = dict:from_list([{?MD_VTAG, "tag1"}]),
O2 = riakc_obj:update_metadata(O1, M1),
?assertEqual(M1, get_update_metadata(O2)),
?assertEqual("x-application/custom", get_update_content_type(O1)).
update_content_type_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>),
undefined = get_update_content_type(O),
O1 = update_content_type(O, "application/json"),
?assertEqual("application/json", get_update_content_type(O1)).
binary_content_type_test() ->
O = riakc_obj:new(<<"b">>, <<"k">>, <<"v">>, <<"application/x-foo">>),
?assertEqual("application/x-foo", get_update_content_type(O)),
O1 = update_content_type(O, <<"application/x-bar">>),
?assertEqual("application/x-bar", get_update_content_type(O1)).
get_update_data_test() ->
MD0 = dict:from_list([{?MD_CTYPE, "text/plain"}]),
MD1 = dict:from_list([{?MD_CTYPE, "application/json"}]),
O = new_obj(<<"b">>, <<"k">>, <<"">>,
[{MD0, <<"v">>}]),
Oumd = update_metadata(O, MD1),
Ouv = update_value(O, <<"valueonly">>),
Oboth = update_value(Oumd, <<"both">>),
io:format("O=~p\n", [O]),
?assertEqual(<<"v">>, get_update_value(O)),
MD2 = get_update_metadata(O),
io:format("MD2=~p\n", [MD2]),
?assertEqual("text/plain", md_ctype(MD2)),
MD3 = get_update_metadata(Oumd),
?assertEqual("application/json", md_ctype(MD3)),
?assertEqual(<<"valueonly">>, get_update_value(Ouv)),
MD4 = get_update_metadata(Ouv),
?assertEqual("text/plain", md_ctype(MD4)),
?assertEqual(<<"both">>, get_update_value(Oboth)),
MD5 = get_update_metadata(Oboth),
?assertEqual("application/json", md_ctype(MD5)).
= , < < " both " > > ) ,
? assertThrow({error , siblings } , get_update_data(O ) ) ,
? assertThrow({error , siblings } , ) ) ,
? , siblings } , get_update_data(Ouv ) ) ,
select_sibling_test() ->
MD0 = dict:from_list([{?MD_CTYPE, "text/plain"}]),
MD1 = dict:from_list([{?MD_CTYPE, "application/json"}]),
O = new_obj(<<"b">>, <<"k">>, <<"">>,
[{MD0, <<"sib_one">>},
{MD1, <<"sib_two">>}]),
O1 = select_sibling(1, O),
O2 = select_sibling(2, O),
?assertEqual("text/plain", get_update_content_type(O1)),
?assertEqual(<<"sib_one">>, get_update_value(O1)),
?assertEqual("application/json", get_update_content_type(O2)),
?assertEqual(<<"sib_two">>, get_update_value(O2)).
user_metadata_utilities_test() ->
MD0 = dict:new(),
?assertEqual(dict:to_list(MD0), dict:to_list(delete_user_metadata_entry(MD0, <<"None">>))),
MD1 = set_user_metadata_entry(MD0,{<<"Key1">>, <<"Value0">>}),
?assertEqual([{<<"Key1">>, <<"Value0">>}], get_user_metadata_entries(MD1)),
MD2 = set_user_metadata_entry(MD1,{<<"Key1">>, <<"Value1">>}),
?assertEqual([{<<"Key1">>, <<"Value1">>}], get_user_metadata_entries(MD2)),
?assertEqual(notfound, get_user_metadata_entry(MD2, <<"WrongKey">>)),
MD3 = set_user_metadata_entry(MD2,{<<"Key2">>, <<"Value2">>}),
?assertEqual(<<"Value2">>, get_user_metadata_entry(MD3, <<"Key2">>)),
?assertEqual(2, length(get_user_metadata_entries(MD3))),
MD4 = delete_user_metadata_entry(MD3, <<"Key1">>),
?assertEqual([{<<"Key2">>, <<"Value2">>}], get_user_metadata_entries(MD4)),
MD5 = clear_user_metadata_entries(MD4),
?assertEqual([], get_user_metadata_entries(MD5)),
MD6 = delete_user_metadata_entry(MD1, <<"Key1">>),
?assertEqual([], get_user_metadata_entries(MD6)),
?assertEqual(notfound, get_user_metadata_entry(MD6, <<"Key1">>)).
link_utilities_test() ->
MD0 = dict:new(),
?assertEqual(notfound, get_links(MD0, <<"Tag1">>)),
?assertEqual([], get_all_links(MD0)),
MD1 = set_link(MD0, [{<<"Tag1">>, [{<<"B">>,<<"K1">>},{<<"B">>,<<"K2">>}]}]),
?assertEqual([{<<"B">>,<<"K1">>},{<<"B">>,<<"K2">>}], lists:sort(get_links(MD1,<<"Tag1">>))),
MD2 = add_link(MD1, [{<<"Tag1">>, [{<<"B">>,<<"K1">>},{<<"B">>,<<"K3">>}]}]),
?assertEqual([{<<"B">>,<<"K1">>},{<<"B">>,<<"K2">>},{<<"B">>,<<"K3">>}], lists:sort(get_links(MD2,<<"Tag1">>))),
MD3 = set_link(MD2, [{<<"Tag1">>, [{<<"B">>,<<"K4">>}]}]),
?assertEqual([{<<"B">>,<<"K4">>}], lists:sort(get_links(MD3,<<"Tag1">>))),
?assertEqual([{<<"Tag1">>,[{<<"B">>,<<"K4">>}]}], get_all_links(MD3)),
MD4 = set_link(MD3, [{<<"Tag2">>, [{<<"B">>,<<"K1">>}]}]),
?assertEqual([{<<"B">>,<<"K1">>}], lists:sort(get_links(MD4,<<"Tag2">>))),
MD5 = delete_links(MD4,<<"Tag1">>),
?assertEqual([{<<"Tag2">>,[{<<"B">>,<<"K1">>}]}], get_all_links(MD5)),
MD6 = clear_links(MD5),
?assertEqual([], get_all_links(MD6)).
secondary_index_utilities_test() ->
MD0 = dict:new(),
?assertEqual([], get_secondary_indexes(MD0)),
?assertEqual(notfound, get_secondary_index(MD0, {binary_index,"none"})),
?assertEqual(notfound, get_secondary_index(MD0, {integer_index,"none"})),
MD1 = set_secondary_index(MD0, [{{integer_index,"idx"}, [12,4,56]}]),
?assertEqual([4,12,56], lists:sort(get_secondary_index(MD1,{integer_index,"idx"}))),
MD2 = add_secondary_index(MD1, [{{integer_index,"idx"}, [4,15,34]}]),
?assertEqual([4,12,15,34,56], lists:sort(get_secondary_index(MD2,{integer_index,"idx"}))),
MD3 = set_secondary_index(MD2, {{integer_index,"idx"}, [7]}),
?assertEqual([7], lists:sort(get_secondary_index(MD3,{integer_index,"idx"}))),
MD4 = set_secondary_index(MD3, [{{binary_index,"idx"}, [<<"12">>,<<"4">>,<<"56">>]}]),
?assertEqual([<<"12">>,<<"4">>,<<"56">>], lists:sort(get_secondary_index(MD4,{binary_index,"idx"}))),
MD5 = add_secondary_index(MD4, [{{binary_index,"idx"}, [<<"4">>,<<"15">>,<<"34">>]}]),
?assertEqual([<<"12">>,<<"15">>,<<"34">>,<<"4">>,<<"56">>], lists:sort(get_secondary_index(MD5,{binary_index,"idx"}))),
MD6 = set_secondary_index(MD5, {{binary_index,"idx"}, [<<"7">>]}),
?assertEqual([<<"7">>], lists:sort(get_secondary_index(MD6,{binary_index,"idx"}))),
?assertEqual(2, length(get_secondary_indexes(MD6))),
?assertEqual(notfound, get_secondary_index(MD6,{binary_index,"error"})),
MD7 = delete_secondary_index(MD6,{binary_index,"idx"}),
?assertEqual([{{integer_index,"idx"},[7]}], get_secondary_indexes(MD7)),
MD8 = clear_secondary_indexes(MD7),
?assertEqual([], get_secondary_indexes(MD8)),
MD9 = delete_secondary_index(MD8,{binary_index,"none"}),
?assertEqual([], get_secondary_indexes(MD9)),
MD10 = add_secondary_index(MD9, [{{integer_index,"idx2"}, [23,4,34]}]),
?assertEqual([4,23,34], lists:sort(get_secondary_index(MD10,{integer_index,"idx2"}))),
MD11 = dict:new(),
?assertEqual([], get_secondary_indexes(MD11)),
?assertEqual(notfound, get_secondary_index(MD11, {binary_index,"none"})),
?assertEqual(notfound, get_secondary_index(MD11, {integer_index,"none"})),
MD12 = set_secondary_index(MD11, [{{integer_index,"itest"}, [12,4,56]},{{binary_index,"btest"}, [<<"test1">>]}]),
?assertEqual([4,12,56], lists:sort(get_secondary_index(MD12,{integer_index,"itest"}))),
?assertEqual([<<"test1">>], lists:sort(get_secondary_index(MD12,{binary_index,"btest"}))),
MD13 = add_secondary_index(MD12, [{{integer_index,"itest"}, [4,15,34]},{{binary_index,"btest"}, [<<"test2">>]}]),
?assertEqual([4,12,15,34,56], lists:sort(get_secondary_index(MD13,{integer_index,"itest"}))),
?assertEqual([<<"test1">>,<<"test2">>], lists:sort(get_secondary_index(MD13,{binary_index,"btest"}))).
-endif.
|
e7b6cfe6d6ac08b74450cc8ec1f63154f08756ec9bb7b94a4d665840e04a51c9 | PeterDWhite/Osker | KernelCoreMessage.hs | Copyright ( C ) , 2001 , 2002 , 2003
Copyright ( c ) OHSU , 2001 , 2002 , 2003
module KernelCoreMessage
A type for messages in kernel core
Get index to call table from message
) where
----------------------------------------------------------------------
The definitions that localize the message to the system
-- half instantiation of the executive.
----------------------------------------------------------------------
Osker imports
import qualified CallTableIndex as CTI
import qualified OskerMessage as OM
data KernelCoreMessageType
From the user half , via the trap handler .
= ToKernelCoreType
-- From self
| FromProcessControlType
Commands from the system half
| FromSystemHalfType
deriving (Eq, Ord, Enum, Show)
-- Convert the incoming payload to the system half to a message type.
kernelCorePayloadType :: OM.OskerPay -> KernelCoreMessageType
kernelCorePayloadType sp =
case sp of
OM.ToKernelCore _kcr -> ToKernelCoreType
OM.FromProcessControl _pcr -> FromProcessControlType
OM.FromSystemHalf _kcc -> FromSystemHalfType
_otherwise ->
error ("kernelCorePayloadType: " ++ show sp)
Get the message type from the incoming message to the system half
kernelCoreMessageType :: OM.OskerPay -> Int
kernelCoreMessageType = fromEnum . kernelCorePayloadType
Get the activity index from the incoming message to the system half .
kernelCoreMessageIndex :: OM.OskerPay -> Int
kernelCoreMessageIndex sp =
case sp of
OM.ToKernelCore kcr -> OM.kernelCoreRequest2Int kcr
OM.FromProcessControl pcr -> OM.processControlRequest2Int pcr
OM.FromSystemHalf kcc -> OM.kernelCoreComply2Int kcc
_otherwise ->
error ("kernelCorePayloadIndex: " ++ show sp)
Generate the call table index from the incoming message
to the system half .
getCallTableIndex :: CTI.ToCallTableIndex OM.OskerPay
getCallTableIndex sp =
CTI.CallTableIndex
(kernelCoreMessageType sp) -- Message type
(kernelCoreMessageIndex sp) -- Message index
| null | https://raw.githubusercontent.com/PeterDWhite/Osker/301e1185f7c08c62c2929171cc0469a159ea802f/Kernel/KernelCore/KernelCoreMessage.hs | haskell | --------------------------------------------------------------------
half instantiation of the executive.
--------------------------------------------------------------------
From self
Convert the incoming payload to the system half to a message type.
Message type
Message index | Copyright ( C ) , 2001 , 2002 , 2003
Copyright ( c ) OHSU , 2001 , 2002 , 2003
module KernelCoreMessage
A type for messages in kernel core
Get index to call table from message
) where
The definitions that localize the message to the system
Osker imports
import qualified CallTableIndex as CTI
import qualified OskerMessage as OM
data KernelCoreMessageType
From the user half , via the trap handler .
= ToKernelCoreType
| FromProcessControlType
Commands from the system half
| FromSystemHalfType
deriving (Eq, Ord, Enum, Show)
kernelCorePayloadType :: OM.OskerPay -> KernelCoreMessageType
kernelCorePayloadType sp =
case sp of
OM.ToKernelCore _kcr -> ToKernelCoreType
OM.FromProcessControl _pcr -> FromProcessControlType
OM.FromSystemHalf _kcc -> FromSystemHalfType
_otherwise ->
error ("kernelCorePayloadType: " ++ show sp)
Get the message type from the incoming message to the system half
kernelCoreMessageType :: OM.OskerPay -> Int
kernelCoreMessageType = fromEnum . kernelCorePayloadType
Get the activity index from the incoming message to the system half .
kernelCoreMessageIndex :: OM.OskerPay -> Int
kernelCoreMessageIndex sp =
case sp of
OM.ToKernelCore kcr -> OM.kernelCoreRequest2Int kcr
OM.FromProcessControl pcr -> OM.processControlRequest2Int pcr
OM.FromSystemHalf kcc -> OM.kernelCoreComply2Int kcc
_otherwise ->
error ("kernelCorePayloadIndex: " ++ show sp)
Generate the call table index from the incoming message
to the system half .
getCallTableIndex :: CTI.ToCallTableIndex OM.OskerPay
getCallTableIndex sp =
CTI.CallTableIndex
|
7a1d75ca54f0029280cfbde304beb86de4bb360cfb53bdba5895786394018841 | GaloisInc/llvm-verifier | Debugger.hs | |
Module : $ Header$
Description : Debugger implementation for LSS
License : BSD3
Stability : provisional
Point - of - contact : acfoltzer , for the LLVM Symbolic Simulator . This module provides
implementations of the ' SEH ' event handlers . Commands and their
semantics are loosely based on gdb .
Module : $Header$
Description : Debugger implementation for LSS
License : BSD3
Stability : provisional
Point-of-contact : acfoltzer, jhendrix
Debugger for the LLVM Symbolic Simulator. This module provides
implementations of the 'SEH' event handlers. Commands and their
semantics are loosely based on gdb.
-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGe PatternGuards #
{-# LANGUAGE Rank2Types #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
# LANGUAGE CPP #
module Verifier.LLVM.Debugger
( initializeDebugger
, addBreakpoint
, breakOnEntry
, resetInterrupt
, checkForBreakpoint
) where
import Control.Applicative ((<**>))
import Control.Monad
import qualified Control.Monad.Catch as E
import Control.Exception ( throwIO, throwTo )
#if !MIN_VERSION_base(4,13,0)
import Control.Monad.Fail
#endif
import Control.Monad.Identity
import qualified Control.Monad.State as MTL
import Control.Monad.State( MonadIO(..), lift )
import Control.Monad.State.Class
import Control.Lens
import Data.Char
import Data.IORef
import qualified Data.List as L
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Set as S
import Data.String
import qualified System.Console.Haskeline as HL
import System.Directory
import System.Exit
import System.FilePath
import System.IO
import System.IO.Error
import Text.PrettyPrint.ANSI.Leijen hiding ((<$>), (</>))
import qualified Text.PrettyPrint.ANSI.Leijen as PP
-- GHC.IO.Exception is imported so that we can catch
the UnsupportedOperation error that may be thrown
by getAppUserDataDirectory .
import GHC.IO.Exception
import Verifier.LLVM.Backend
import Verifier.LLVM.Codebase
import Verifier.LLVM.Debugger.Grammar
import Verifier.LLVM.Simulator.Internals
import Verifier.LLVM.Simulator.SimUtils
import Verifier.LLVM.Utils.PrettyPrint
#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
import Control.Concurrent (myThreadId)
import System.Posix.Signals
#endif
-- | Treat as IORef as a state transformer.
withIORef :: MonadIO m => IORef s -> MTL.StateT s m a -> m a
withIORef r m = do
s <- liftIO $ readIORef r
(v,s') <- MTL.runStateT m s
liftIO $ writeIORef r $! s'
return v
-- | Break on entry to the function.
breakOnEntry :: (Functor m, Monad m)
=> SymDefine (SBETerm sbe) -> Simulator sbe m ()
breakOnEntry def = addBreakpoint (sdName def) (sdEntry def, 0)
safeGetAppUserDataDirectory :: String -> IO (Maybe FilePath)
safeGetAppUserDataDirectory nm =
E.catch (Just <$> getAppUserDataDirectory nm)
catchErrors
Catch the UnsupportedOperation and DoesNotExist
-- exceptions that may be thrown.
catchErrors :: IOError -> IO (Maybe a)
catchErrors e =
case ioeGetErrorType e of
NoSuchThing -> return Nothing
UnsupportedOperation -> return Nothing
_ -> throwIO e
| Return location of LSS history file
getLSSHistoryPath :: IO (Maybe FilePath)
getLSSHistoryPath = fmap (</> "history") <$> safeGetAppUserDataDirectory "lss"
------------------------------------------------------------------------
-- User interaction
#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
@resetInterrupt does nothing on Windows .
resetInterrupt :: IO ()
resetInterrupt = return ()
#else
@resetInterrupt@ installs a one - time signal handler so
-- that the next time an interrupt (e.g. Ctrl-C) is given, a
-- @UserInterrupt@ AsyncException will be thrown in the current
-- thread.
By default GHC will do this once during program execution , but
-- subsequent uses of Ctrl-C result in immediate termination.
-- This function allows Ctrl-C to be used to interrupt multiple
-- times over program execution.
resetInterrupt :: IO ()
resetInterrupt = do
tid <- myThreadId
let handler = throwTo tid UserInterrupt
let mask = Nothing -- Any other signal handler can block while
_ <- installHandler sigINT (CatchOnce handler) mask
return ()
#endif
checkForBreakpoint :: DebuggerContext sbe m
=> DebuggerRef sbe m -> Simulator sbe m ()
checkForBreakpoint r = do
mcf <- preuse $ currentPathOfState . pathCallFrames
case mcf of
Just cf -> do
mbps <- use $ breakpoints . at (sdName (cfFunc cf))
let atBP = fromMaybe False $ S.member (cf^.cfLocation) <$> mbps
when atBP (enterDebuggerAtBreakpoint r)
Nothing -> return ()
setPrevCommand :: MonadIO m
=> DebuggerRef sbe m'
-> Debugger sbe m' ()
-> m ()
setPrevCommand dr cmd = withIORef dr $ onNoInput .= cmd
runNextCommand :: DebuggerContext sbe m
=> DebuggerCont sbe m
runNextCommand dr = do
mline <- HL.getInputLine "(lss) "
ds <- liftIO $ readIORef dr
case dropWhile isSpace <$> mline of
Nothing -> return ()
Just "" -> do
runDebugger (ds^.onNoInput) (\() -> runNextCommand) dr
Just cmdStr -> do
let pr = runIdentity $ parseString (dsGrammar ds) cmdStr
case resolveParse pr of
Left d -> do
HL.outputStrLn (show d)
setPrevCommand dr $ return ()
runNextCommand dr
Right cmd -> do
setPrevCommand dr cmd
runDebugger cmd (\() -> runNextCommand) dr
data DebuggerState sbe m
= DebuggerState { -- | Grammar to use for parsing commands
dsGrammar :: SimGrammar sbe m
, _selectedFrame :: Int
, _onNoInput :: Debugger sbe m ()
, _resumeThrowsError :: Bool
}
-- | Create initial debugger state.
initialState :: DebuggerContext sbe m
=> Codebase sbe
-> DebuggerState sbe m
initialState cb =
DebuggerState { dsGrammar = allCmds cb
, _selectedFrame = 0
, _onNoInput = return ()
, _resumeThrowsError = False
}
-- | Index of frame selected in the debugger.
-- 0 is the top frame.
selectedFrame :: Simple Lens (DebuggerState sbe m) Int
selectedFrame = lens _selectedFrame (\s v -> s { _selectedFrame = v })
-- | Command to run if no input is provided.
onNoInput :: Simple Lens (DebuggerState sbe m) (Debugger sbe m ())
onNoInput = lens _onNoInput (\s v -> s { _onNoInput = v })
-- | Flag that holds if we know that resuming from this point will throw an error.
resumeThrowsError :: Simple Lens (DebuggerState sbe m) Bool
resumeThrowsError = lens _resumeThrowsError (\s v -> s { _resumeThrowsError = v })
-- | Reference to persistent debugger state.
type DebuggerRef sbe m = IORef (DebuggerState sbe m)
type DebuggerCont sbe m
= DebuggerRef sbe m
-> HL.InputT (Simulator sbe m) ()
newtype Debugger sbe m a
= Debugger { runDebugger :: (a -> DebuggerCont sbe m)
-> DebuggerCont sbe m
}
instance Functor (Debugger sbe m) where
fmap f d = Debugger (\c -> runDebugger d (c . f))
instance Applicative (Debugger sbe m) where
pure v = Debugger ($v)
mf <*> mv = Debugger $ \c -> do
runDebugger mf (\f -> runDebugger mv (c.f))
instance DebuggerContext sbe m => Monad (Debugger sbe m) where
m >>= h = Debugger $ \c -> runDebugger m (\v -> runDebugger (h v) c)
return v = Debugger ($v)
instance DebuggerContext sbe m => MonadFail (Debugger sbe m) where
fail m = Debugger $ \_c dr -> do
dbugM $ "Unexpected error: " ++ show m
setPrevCommand dr $ return ()
runNextCommand dr
instance DebuggerContext sbe m
=> MTL.MonadState (DebuggerState sbe m) (Debugger sbe m) where
get = Debugger $ \c r -> liftIO (readIORef r) >>= flip c r
put v = Debugger $ \c r -> liftIO (writeIORef r v) >> c () r
instance DebuggerContext sbe m => MonadIO (Debugger sbe m) where
liftIO m = Debugger (\c r -> liftIO m >>= flip c r)
getDebuggerRef :: Debugger sbe m (DebuggerRef sbe m)
getDebuggerRef = Debugger (\c r -> c r r)
runSim :: Monad m => Simulator sbe m a -> Debugger sbe m a
runSim m = Debugger (\c r -> lift m >>= flip c r)
-- | Resume exectuion of simulator.
resume :: Monad m => Debugger sbe m a
resume = Debugger (\_ _ -> return ())
type DebuggerContext sbe m = (Functor sbe, Functor m
#if !MIN_VERSION_haskeline(0,8,0)
, HL.MonadException m
#else
, E.MonadMask m
#endif
, MonadIO m
, MonadFail m)
-- | Setup simulator to run debugger when needed.
initializeDebugger :: DebuggerContext sbe m
=> Simulator sbe m (DebuggerRef sbe m)
initializeDebugger = do
cb <- gets codebase
r <- liftIO $ newIORef (initialState cb)
onPathPosChange .= checkForBreakpoint r
onSimError .= enterDebuggerOnError r
onUserInterrupt .= enterDebuggerOnInterrupt r
return r
-- | Enter debugger repl.
enterDebugger :: DebuggerContext sbe m
=> DebuggerRef sbe m
-> Bool -- ^ Indicates if debugger was entered due to error in current path.
-> Simulator sbe m ()
enterDebugger r eoe = do
-- Print path location.
mcs <- use ctrlStk
case mcs of
Just cs | pathIsActive (cs^.currentPath) -> do
let p = cs^.currentPath
dbugM $ show $ indent 2 (text "at" <+> ppPathNameAndLoc p)
_ -> dbugM "No active execution path."
-- Update debugger state.
withIORef r $ do
selectedFrame .= 0
resumeThrowsError .= eoe
-- Run command.
grammar <- liftIO $ dsGrammar <$> readIORef r
historyPath <- liftIO getLSSHistoryPath
let settings = HL.setComplete (matcherCompletions grammar)
$ HL.defaultSettings { HL.historyFile = historyPath }
HL.runInputT settings (runNextCommand r)
enterDebuggerOnError :: DebuggerContext sbe m
=> DebuggerRef sbe m
-> ErrorHandler sbe m
enterDebuggerOnError r cs rsn = do
-- Reset state
ctrlStk ?= cs
-- Get current path before last step.
dbugM $ show $
text "Simulation error:" <+> ppFailRsn rsn
-- Debugger state
enterDebugger r True
enterDebuggerOnInterrupt :: DebuggerContext sbe m
=> DebuggerRef sbe m
-> Simulator sbe m ()
enterDebuggerOnInterrupt r = do
dbugM $ show $
text "Simulation interrupted: Entering debugger"
enterDebugger r False
dbugM $ "Resuming simulation"
liftIO $ resetInterrupt
enterDebuggerAtBreakpoint :: DebuggerContext sbe m
=> DebuggerRef sbe m
-> Simulator sbe m ()
enterDebuggerAtBreakpoint dr = do
dbugM "Encountered breakpoint"
enterDebugger dr False
------------------------------------------------------------------------
-- Completions
matcherCompletions :: (Functor m, Monad m)
=> Grammar Identity a
-> (String, String)
-> Simulator sbe m (String, [HL.Completion])
matcherCompletions m (l,_r) = pure (finalize a)
where rl = reverse l
a = runIdentity $ parseString m rl
finalize pr =
(reverse (take p rl), cl)
where (p,cl) = pr^.parseCompletions
data YesNo = Yes | No
deriving (Eq)
putAndFlush :: MonadIO m => String -> m ()
putAndFlush msg = liftIO $ putStr msg >> hFlush stdout
-- | Prompts the user for a string matching a choice.
promptChoice :: MonadIO m => String -> [(String,r)] -> m r
promptChoice prompt choices =
liftIO $ putAndFlush prompt >> loop
where loop = do
l <- dropWhile isSpace . fmap toLower <$> getLine
let resl = [ r | (c,r) <- choices, l `L.isPrefixOf` c ]
case (l,resl) of
("",_) -> putAndFlush prompt >> loop
(_,r:_) -> return r
(_,[]) -> do putAndFlush ("Invalid response; " ++ prompt)
loop
promptYesNoCancel :: MonadIO m => m (Maybe YesNo)
promptYesNoCancel = promptChoice prompt choices
where prompt = "Please enter (Y)es, (N)o, or (C)ancel: "
choices = [("yes", Just Yes), ("no", Just No), ("cancel", Nothing) ]
promptYesNo :: MonadIO m => m YesNo
promptYesNo = promptChoice prompt choices
where prompt = "Please enter (Y)es or (N)o: "
choices = [("yes", Yes), ("no", No)]
-- | Check to see if we should warn user before resuming. Return True
-- if resume should continue
warnIfResumeThrowsError :: DebuggerContext sbe m
=> Debugger sbe m Bool
warnIfResumeThrowsError = do
rte <- use resumeThrowsError
mcs <- runSim $ use ctrlStk
case mcs of
Just cs | rte -> do
dbugM "Resuming execution on this path should rethrow the simulation error."
if csHasSinglePath cs then do
dbugM "Should lss kill the current path, and stop simulation?"
ync <- promptYesNoCancel
case ync of
Just Yes -> do
killPathByDebugger
resume
Just No -> return True
Nothing -> return False
else do
dbugM "Should lss kill the current path, and resume on a new path?"
ync <- promptYesNoCancel
case ync of
Just Yes -> do
killPathByDebugger
return True
Just No -> return True
Nothing -> return False
Just cs -> return (pathIsActive (cs^.currentPath))
Nothing -> return False
-- | @resumeActivePath m@ runs @m@ with the current path,
-- and resumes execution if there is a current path and @m@
-- returns true.
resumeActivePath :: DebuggerContext sbe m
=> (Path sbe -> Simulator sbe m ())
-> Debugger sbe m ()
resumeActivePath action = do
continueResume <- warnIfResumeThrowsError
when continueResume $
withActivePath () $ \p -> do
runSim (action p)
resume
type DebuggerGrammar a = Grammar Identity a
type SimGrammar sbe m = DebuggerContext sbe m
=> DebuggerGrammar (Debugger sbe m ())
commandHelp :: Grammar m a -> Doc
commandHelp cmds =
text "List of commands:" <$$>
PP.empty <$$>
vcat (ppCmdHelp <$> (help^.helpCmds)) <$$>
PP.empty <$$>
text "NOT IMPLEMENTED: Type \"help\" followed by command name for full documentation." <$$>
text "Command name abbreviations are allowed if unambiguous."
where help = matcherHelp cmds
newtype NameMap = NameMap (M.Map String NameMapPair)
type NameMapPair = (Maybe SymBlockID, NameMap)
emptyNameMap :: NameMap
emptyNameMap = NameMap M.empty
splitName :: String -> [String]
splitName nm =
case break (=='.') nm of
(l,[]) -> [l]
(l,_:r) -> l : splitName r
mergeName :: SymBlockID -> [String] -> NameMapPair -> NameMapPair
mergeName b [] (_,m) = (Just b,m)
mergeName b (h:r) (o,NameMap m) = (o, NameMap $ m & at h ?~ mergeName b r mr)
where mr = fromMaybe (Nothing, NameMap M.empty) $ m^.at h
insertName :: NameMap -> SymBlockID -> NameMap
insertName m b = snd $ mergeName b (splitName (show (ppSymBlockID b)))
(Nothing,m)
pairBlocks :: SymDefine t -> NameMapPair -> Grammar m (Symbol, Breakpoint)
pairBlocks d (mb,m@(NameMap m')) = switch $ others ++ end
where others | M.null m' = []
| otherwise = [(,) "." $ nameBlocks d m]
end = case mb of
Nothing -> []
Just b -> [(,) "" $ pure (sdName d,(b,0))]
nameBlocks :: SymDefine t -> NameMap -> Grammar m (Symbol, Breakpoint)
nameBlocks d (NameMap m) = switch $ (entry <$> M.toList m)
where entry (nm,p) = (fromString nm, pairBlocks d p)
-- | Parses a program location for a breakpoint.
locSeq :: forall sbe m . Codebase sbe -> Grammar m (Symbol, Breakpoint)
locSeq cb = argLabel (text "<loc>") *> hide (switch $ fmap matchDef (cbDefs cb))
where matchDef :: SymDefine (SBETerm sbe)
-> (SwitchKey, Grammar m (Symbol, Breakpoint))
matchDef d = ( fromString nm
, switch [ (,) ":" (nameBlocks d m)
, (,) "" $ end
]
)
where Symbol nm = sdName d
end :: Grammar m (Symbol, Breakpoint)
end = pure (sdName d, (sdEntry d, 0))
m = foldl insertName emptyNameMap (M.keys (sdBody d))
optNatArg :: Integer
-- ^ Default value if argument is missing.
-> DebuggerGrammar (Integer -> Debugger sbe m ())
-> DebuggerGrammar (Debugger sbe m ())
optNatArg def g = (fromMaybe def <$> opt nat) <**> g
-- | List of commands for debugger.
allCmds :: Codebase sbe -> SimGrammar sbe m
allCmds cb = res
Breakpoints
= keyword "continue" *> continueCmd
<||> keyword "break" *> breakCmd cb
-- Execution
<||> keyword "delete" *> deleteCmd cb
<||> keyword "finish" *> finishCmd
<||> hide (keyword "s" *> stepiCmd)
<||> keyword "stepi" *> stepiCmd
-- Information about current path.
<||> keyword "info" *> infoCmd
-- <||> keyword "list" *> listCmd cb
Stack control
<||> hide (keyword "bt" *> backtraceCmd)
<||> keyword "backtrace" *> backtraceCmd
<||> keyword "frame" *> frameCmd
<||> keyword "up" *> upFrameCmd
<||> keyword "down" *> downFrameCmd
<||> keyword "select_frame" *> selectFrameCmd
-- Function for switching between paths
<||> keyword "path" *> pathCmd
-- Control and information about debugger.
<||> keyword "help" *> helpCmd res
<||> keyword "quit" *> quitCmd
helpCmd :: SimGrammar sbe m -> SimGrammar sbe m
helpCmd cmdList = cmdDef "Print list of commands." $ do
liftIO $ print (commandHelp cmdList)
pathCmd :: SimGrammar sbe m
pathCmd
= hide pathListCmd
<||> keyword "kill" *> pathKillCmd
<||> keyword "list" *> pathListCmd
<||> keyword "sat" *> pathSatCmd
pathListCmd :: SimGrammar sbe m
pathListCmd = cmdDef "List all current execution paths." $ runSim $ do
mcs <- use ctrlStk
case mcs of
Nothing ->
dbugM "No active paths."
Just cs -> dbugM $ show $ printTable table
where ppPathItem :: Integer -> Path sbe -> [String]
ppPathItem i p = [ 3 `padLeft` (show i)
, show (ppPathNameAndLoc p)
]
-- Header for table.
header = [ " Num", "Location"]
-- Entries for table.
table = header : zipWith ppPathItem [1..] (cs^..currentPaths)
pathSatCmd :: SimGrammar sbe m
pathSatCmd =
cmdDef "Check satisfiability of path assertions with SAT solver." $ do
withActiveCS () $ do
sat <- runSim $ do
sbe <- gets symBE
cond <- assumptionsForActivePath
liftSBE $ termSAT sbe cond
case sat of
Unsat -> do
dbugM "The current path is infeasible. Should simulation of the path be terminated?"
yn <- promptYesNo
when (yn == Yes) $ do
killPathByDebugger
Sat _ ->
dbugM "Conditions along path are satisfiable."
SatUnknown ->
dbugM "Could not determine if path is feasible."
-- | Kills the current path with the debugger.
-- Assumes that there is an active path.
killPathByDebugger :: DebuggerContext sbe m
=> Debugger sbe m ()
killPathByDebugger = do
runSim $ killCurrentPath (FailRsn "Terminated by debugger.")
resumeThrowsError .= False
pathKillCmd :: SimGrammar sbe m
pathKillCmd = cmdDef "Kill the current execution path." $ do
withActiveCS () $ do
killPathByDebugger
mp <- runSim $ preuse currentPathOfState
case mp of
Nothing -> dbugM "Killed last path."
Just p -> dbugM $ show $
text "Switched to path:" <+> ppPathNameAndLoc p
quitCmd :: SimGrammar sbe m
quitCmd = cmdDef "Exit LSS." $ do
mcs <- runSim $ use ctrlStk
case mcs of
Just cs | pathIsActive (cs^.currentPath) ->
liftIO $ exitWith ExitSuccess
_ -> resume
breakCmd :: Codebase sbe -> SimGrammar sbe m
breakCmd cb = (locSeq cb <**>) $ cmdDef desc $ \(b,p) -> do
runSim $ addBreakpoint b p
where desc = "Set a breakpoint at a specified location."
deleteCmd :: Codebase sbe -> SimGrammar sbe m
deleteCmd cb = (opt (locSeq cb) <**>) $ cmdDef desc $ \mbp -> do
runSim $
case mbp of
Just (b,p) -> removeBreakpoint b p
Nothing -> dbugM "Remove all breakpoints"
--TODO: implement this.
where desc = "Clear a breakpoint at a function."
concatBreakpoints :: M.Map Symbol (S.Set Breakpoint)
-> [(Symbol, Breakpoint)]
concatBreakpoints m =
[ (sym,bp) | (sym, bps) <- M.toList m, bp <- S.toList bps ]
infoCmd :: SimGrammar sbe m
infoCmd
= keyword "args" *> infoArgsCmd
<||> keyword "block" *> infoBlockCmd
<||> keyword "breakpoints" *> infoBreakpointsCmd
<||> keyword "ctrlstk" *> infoCtrlStkCmd
<||> keyword "function" *> infoFunctionCmd
<||> keyword "locals" *> infoLocalsCmd
<||> keyword "memory" *> infoMemoryCmd
<||> keyword "stack" *> backtraceCmd
infoArgsCmd :: SimGrammar sbe m
infoArgsCmd =
cmdDef "Print argument variables in the current stack frame." $ do
withActiveCallFrame () $ \cf -> do
sbe <- gets symBE
dbugM $ show $ ppLocals sbe $ cfArgValues cf
infoBlockCmd :: SimGrammar sbe m
infoBlockCmd =
cmdDef "Print block information." $ do
withActiveCallFrame () $ \cf -> do
dbugM $ show $ ppSymBlock $ cfBlock cf
infoBreakpointsCmd :: SimGrammar sbe m
infoBreakpointsCmd =
cmdDef "List breakpoints." $ runSim $ do
bps <- concatBreakpoints <$> use breakpoints
let ppRow :: Integer -> (Symbol,Breakpoint) -> [String]
ppRow i (Symbol sym,bp) =
[show i, sym ++ ":" ++ show (ppBreakpoint bp)]
dbugM $ show $
case bps of
[] -> text "No breakpoints."
_ -> printTable (header : zipWith ppRow [1..] bps)
where header = ["Num", "Location"]
infoCtrlStkCmd :: SimGrammar sbe m
infoCtrlStkCmd =
cmdDef "Print the entire control stack." $ do
runSim dumpCtrlStk
infoFunctionCmd :: SimGrammar sbe m
infoFunctionCmd =
cmdDef "Print function information." $ do
withActiveCallFrame () $ \cf -> do
dbugM $ show $ ppSymDefine (cfFunc cf)
infoLocalsCmd :: SimGrammar sbe m
infoLocalsCmd =
cmdDef "Print local variables in the current stack frame." $ do
withActiveCallFrame () $ \cf -> do
sbe <- gets symBE
dbugM $ show $ ppLocals sbe $ cfLocalValues cf
Instead writing @infoMemoryRangeCmd < * > optAddr < * > optAddr@
-- results in no "<addr>?" in the help output?!
infoMemoryCmd :: SimGrammar sbe m
infoMemoryCmd = ((,) <$> optAddr <*> optAddr) <**> infoMemoryRangeCmd
where
infoMemoryRangeCmd = cmdDef desc $ \(mlow, mhigh) -> do
let mranges = case (mlow, mhigh) of
(Just low, Just high) -> Just [(low, high)]
(Just low, Nothing) -> Just [(low, low+1)]
(Nothing, Nothing) -> Nothing
(Nothing, Just _) -> error "infoMemoryCmd: unreachable!"
runSim $ dumpMem 0 "memory" mranges
Putting the ' opt ' outside here , and ' hide ' on ' ' , results in a
-- '?' on the "<addr>" label in the help output. Without the 'hide'
-- the label "<addr>" doesn't appear at all in the help.
optAddr = opt (argLabel (text "<addr>") *> hide nat)
desc = unlines
[ "Print memory information."
, ""
, " - With no arguments, prints all memory."
, " - With one argument <addr>, prints memory at address <addr>."
, " - With two arguments <low>, <high>, prints memory in the address range"
, " [<low>,<high>)."
, ""
, " The optional address arguments may be specified in binary (e.g. 0b110),"
, " decimal, or hex (e.g. 0xabcd)."
]
listCmd : : SimGrammar sbe m
( locSeq cb < * * > ) $ cmdDef " List specified function in line . " $ \loc - > do
error " internal : listCmd undefined " loc
listCmd :: Codebase sbe -> SimGrammar sbe m
listCmd cb = (locSeq cb <**>) $ cmdDef "List specified function in line." $ \loc -> do
error "internal: listCmd undefined" loc
-}
-- | @padLeft n s@ adds extra spaces before @s@ so that the result has
-- at least @n@ characters.
padLeft :: Int -> String -> String
padLeft l s = replicate (l - length s) ' ' ++ s
| @padRight n s@ adds extra spaces after @s@ so that the result has
-- at least @n@ characters.
padRight :: String -> Int -> String
padRight s l = s ++ replicate (l - length s) ' '
printTable :: [[String]] -> Doc
printTable m = vcat padded
where maxl (i:x) (j:y) = max i j : maxl x y
maxl [] y = y
maxl x [] = x
-- Maximum lengths of each column.
ll = fmap length <$> m
maxLengths = foldr maxl (repeat 0) ll
padded = hsep . fmap text . zipWith padLeft maxLengths <$> m
ppBreakpoint :: Breakpoint -> Doc
ppBreakpoint (sbid,0) = ppSymBlockID sbid
ppBreakpoint (sbid,i) = ppSymBlockID sbid PP.<> char ':' PP.<> int i
-- | Run a computation if there is an active
withActiveCS :: DebuggerContext sbe m
=> a -- ^ Result to return if there is no execution path.
-> Debugger sbe m a -- ^ Action to run if there is an active path.
-> Debugger sbe m a
withActiveCS v action = do
mcs <- runSim $ use ctrlStk
case mcs of
Just cs | pathIsActive (cs^.currentPath) -> action
_ -> dbugM "No active execution path." >> return v
| @withActivePath v act@ runs @act@ with the active path
withActivePath :: DebuggerContext sbe m
=> a
-> (Path sbe -> Debugger sbe m a)
-> Debugger sbe m a
withActivePath v action = do
mcs <- runSim $ use ctrlStk
case mcs of
Just cs | pathIsActive (cs^.currentPath) -> action (cs^.currentPath)
_ -> dbugM "No active execution path." >> return v
| v act@ runs @act@ with the active call frame .
withActiveCallFrame :: DebuggerContext sbe m
=> a
-> (CallFrame sbe -> Simulator sbe m a)
-> Debugger sbe m a
withActiveCallFrame v action = do
i <- use selectedFrame
runSim $ do
mp <- preuse currentPathOfState
case mp of
-- Get call frame if pth is active.
Just p | cf:_ <- drop i (p^..pathCallFrames) -> do
action cf
_ -> dbugM "No active execution path." >> return v
continueCmd :: SimGrammar sbe m
continueCmd = cmdDef "Continue execution." $ do
dr <- getDebuggerRef
resumeActivePath $ \_ -> do
onPathPosChange .= checkForBreakpoint dr
onReturnFrom :: DebuggerContext sbe m
=> DebuggerRef sbe m -> Int -> Simulator sbe m ()
onReturnFrom dr ht = do
Just p <- preuse currentPathOfState
if pathStackHt p < ht then
enterDebuggerAtBreakpoint dr
else
checkForBreakpoint dr
finishCmd :: SimGrammar sbe m
finishCmd = cmdDef desc $ do
dr <- getDebuggerRef
resumeActivePath $ \p -> do
onPathPosChange .= onReturnFrom dr (pathStackHt p)
where desc = "Execute until the current stack frame returns."
enterDebuggerAfterNSteps
:: DebuggerContext sbe m
=> DebuggerRef sbe m -> Integer -> Simulator sbe m ()
enterDebuggerAfterNSteps dr n
| n <= 1 = enterDebugger dr False
| otherwise = onPathPosChange .= enterDebuggerAfterNSteps dr (n-1)
stepiCmd :: SimGrammar sbe m
stepiCmd = optNatArg 1 $
cmdDef "Execute one symbolic statement." $ \c -> do
when (c > 0) $ do
dr <- getDebuggerRef
resumeActivePath $ \_ -> do
onPathPosChange .= enterDebuggerAfterNSteps dr c
------------------------------------------------------------------------
-- Stack frame commands.
-- | Pretty print the location of the frame.
ppFrameLoc :: SBE sbe -> Int -> CallFrame sbe -> Doc
ppFrameLoc sbe i cf =
char '#' <> text (show i `padRight` 2)
<+> ppSymbol (sdName (cfFunc cf)) <> parens (commaSepList argDocs)
<+> text "at" <+> ppLocation (cf^.cfLocation)
where argDocs = ppArg <$> cfArgValues cf
ppArg (nm,v) =
ppIdent nm <> char '=' <+> prettyTermD sbe v
-- | Run action with call frame list if path is active.
withActiveStack :: DebuggerContext sbe m
=> ([CallFrame sbe] -> Debugger sbe m ())
-> Debugger sbe m ()
withActiveStack action = do
mp <- runSim $ preuse currentPathOfState
case mp of
Just p | cfl <- p^..pathCallFrames, not (null cfl) -> action cfl
_ -> dbugM "No stack."
| @selectFrame i action@ checks that @i@ is a valid frame ,
-- and is so, selects the frame and runs @action@ with the frame.
selectFrame :: DebuggerContext sbe m
=> Int -> (CallFrame sbe -> Debugger sbe m ()) -> Debugger sbe m ()
selectFrame i action =
withActiveStack $ \cfl -> do
if 0 <= i && i < length cfl then do
selectedFrame .= i
action (cfl !! i)
else do
dbugM $ "No frame #" ++ show i ++ "."
printFrameLoc :: MonadIO m => Int -> CallFrame sbe -> Debugger sbe m ()
printFrameLoc i cf = runSim $ do
sbe <- gets symBE
dbugM $ show $ ppFrameLoc sbe i cf
-- | Print backtrace of the stack.
backtraceCmd :: SimGrammar sbe m
backtraceCmd = cmdDef "Print backtrace of the stack." $ do
withActivePath () $ \p -> do
zipWithM_ printFrameLoc [0..] (p^..pathCallFrames)
-- | Select a specific frame.
selectFrameCmd :: SimGrammar sbe m
selectFrameCmd = (<**>) nat $
cmdDef "Select a stack frame without printing anything." $ \(fromInteger -> i) -> do
selectFrame i $ \_ -> return ()
-- | Select a frame and print it's location.
frameCmd :: SimGrammar sbe m
frameCmd = (<**>) nat $
cmdDef "Select and print a stack frame." $ \(fromInteger -> i) -> do
selectFrame i $ \cf -> do
printFrameLoc i cf
| Move up one or more frames to a function that called the current frame .
upFrameCmd :: SimGrammar sbe m
upFrameCmd = optNatArg 1 $
cmdDef "Select and print stack frame that called this one." $ \c -> do
withActiveStack $ \cfl -> do
i <- use selectedFrame
if i > 0 then do
let i' = max 0 (i - fromInteger c)
selectedFrame .= i'
printFrameLoc i' $ cfl !! i'
else do
dbugM "Initial frame already selected; you cannot go up."
| Move down one or more frames to a function called by the current frame .
downFrameCmd :: SimGrammar sbe m
downFrameCmd = optNatArg 1 $
cmdDef "Select and print stack frame called by this one." $ \c -> do
withActiveStack $ \cfl -> do
i <- use selectedFrame
let maxIdx = length cfl - 1
if i < maxIdx then do
let i' = min maxIdx (i + fromInteger c)
selectedFrame .= i'
printFrameLoc i' $ cfl !! i'
else do
dbugM "Bottom frame selected; you cannot go down."
| null | https://raw.githubusercontent.com/GaloisInc/llvm-verifier/d97ee6d2e731f48db833cc451326e737e1e39963/src/Verifier/LLVM/Debugger.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DoAndIfThenElse #
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# LANGUAGE Rank2Types #
GHC.IO.Exception is imported so that we can catch
| Treat as IORef as a state transformer.
| Break on entry to the function.
exceptions that may be thrown.
----------------------------------------------------------------------
User interaction
that the next time an interrupt (e.g. Ctrl-C) is given, a
@UserInterrupt@ AsyncException will be thrown in the current
thread.
subsequent uses of Ctrl-C result in immediate termination.
This function allows Ctrl-C to be used to interrupt multiple
times over program execution.
Any other signal handler can block while
| Grammar to use for parsing commands
| Create initial debugger state.
| Index of frame selected in the debugger.
0 is the top frame.
| Command to run if no input is provided.
| Flag that holds if we know that resuming from this point will throw an error.
| Reference to persistent debugger state.
| Resume exectuion of simulator.
| Setup simulator to run debugger when needed.
| Enter debugger repl.
^ Indicates if debugger was entered due to error in current path.
Print path location.
Update debugger state.
Run command.
Reset state
Get current path before last step.
Debugger state
----------------------------------------------------------------------
Completions
| Prompts the user for a string matching a choice.
| Check to see if we should warn user before resuming. Return True
if resume should continue
| @resumeActivePath m@ runs @m@ with the current path,
and resumes execution if there is a current path and @m@
returns true.
| Parses a program location for a breakpoint.
^ Default value if argument is missing.
| List of commands for debugger.
Execution
Information about current path.
<||> keyword "list" *> listCmd cb
Function for switching between paths
Control and information about debugger.
Header for table.
Entries for table.
| Kills the current path with the debugger.
Assumes that there is an active path.
TODO: implement this.
results in no "<addr>?" in the help output?!
'?' on the "<addr>" label in the help output. Without the 'hide'
the label "<addr>" doesn't appear at all in the help.
| @padLeft n s@ adds extra spaces before @s@ so that the result has
at least @n@ characters.
at least @n@ characters.
Maximum lengths of each column.
| Run a computation if there is an active
^ Result to return if there is no execution path.
^ Action to run if there is an active path.
Get call frame if pth is active.
----------------------------------------------------------------------
Stack frame commands.
| Pretty print the location of the frame.
| Run action with call frame list if path is active.
and is so, selects the frame and runs @action@ with the frame.
| Print backtrace of the stack.
| Select a specific frame.
| Select a frame and print it's location. | |
Module : $ Header$
Description : Debugger implementation for LSS
License : BSD3
Stability : provisional
Point - of - contact : acfoltzer , for the LLVM Symbolic Simulator . This module provides
implementations of the ' SEH ' event handlers . Commands and their
semantics are loosely based on gdb .
Module : $Header$
Description : Debugger implementation for LSS
License : BSD3
Stability : provisional
Point-of-contact : acfoltzer, jhendrix
Debugger for the LLVM Symbolic Simulator. This module provides
implementations of the 'SEH' event handlers. Commands and their
semantics are loosely based on gdb.
-}
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGe PatternGuards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
# LANGUAGE CPP #
module Verifier.LLVM.Debugger
( initializeDebugger
, addBreakpoint
, breakOnEntry
, resetInterrupt
, checkForBreakpoint
) where
import Control.Applicative ((<**>))
import Control.Monad
import qualified Control.Monad.Catch as E
import Control.Exception ( throwIO, throwTo )
#if !MIN_VERSION_base(4,13,0)
import Control.Monad.Fail
#endif
import Control.Monad.Identity
import qualified Control.Monad.State as MTL
import Control.Monad.State( MonadIO(..), lift )
import Control.Monad.State.Class
import Control.Lens
import Data.Char
import Data.IORef
import qualified Data.List as L
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Set as S
import Data.String
import qualified System.Console.Haskeline as HL
import System.Directory
import System.Exit
import System.FilePath
import System.IO
import System.IO.Error
import Text.PrettyPrint.ANSI.Leijen hiding ((<$>), (</>))
import qualified Text.PrettyPrint.ANSI.Leijen as PP
the UnsupportedOperation error that may be thrown
by getAppUserDataDirectory .
import GHC.IO.Exception
import Verifier.LLVM.Backend
import Verifier.LLVM.Codebase
import Verifier.LLVM.Debugger.Grammar
import Verifier.LLVM.Simulator.Internals
import Verifier.LLVM.Simulator.SimUtils
import Verifier.LLVM.Utils.PrettyPrint
#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
import Control.Concurrent (myThreadId)
import System.Posix.Signals
#endif
withIORef :: MonadIO m => IORef s -> MTL.StateT s m a -> m a
withIORef r m = do
s <- liftIO $ readIORef r
(v,s') <- MTL.runStateT m s
liftIO $ writeIORef r $! s'
return v
breakOnEntry :: (Functor m, Monad m)
=> SymDefine (SBETerm sbe) -> Simulator sbe m ()
breakOnEntry def = addBreakpoint (sdName def) (sdEntry def, 0)
safeGetAppUserDataDirectory :: String -> IO (Maybe FilePath)
safeGetAppUserDataDirectory nm =
E.catch (Just <$> getAppUserDataDirectory nm)
catchErrors
Catch the UnsupportedOperation and DoesNotExist
catchErrors :: IOError -> IO (Maybe a)
catchErrors e =
case ioeGetErrorType e of
NoSuchThing -> return Nothing
UnsupportedOperation -> return Nothing
_ -> throwIO e
| Return location of LSS history file
getLSSHistoryPath :: IO (Maybe FilePath)
getLSSHistoryPath = fmap (</> "history") <$> safeGetAppUserDataDirectory "lss"
#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
@resetInterrupt does nothing on Windows .
resetInterrupt :: IO ()
resetInterrupt = return ()
#else
@resetInterrupt@ installs a one - time signal handler so
By default GHC will do this once during program execution , but
resetInterrupt :: IO ()
resetInterrupt = do
tid <- myThreadId
let handler = throwTo tid UserInterrupt
_ <- installHandler sigINT (CatchOnce handler) mask
return ()
#endif
checkForBreakpoint :: DebuggerContext sbe m
=> DebuggerRef sbe m -> Simulator sbe m ()
checkForBreakpoint r = do
mcf <- preuse $ currentPathOfState . pathCallFrames
case mcf of
Just cf -> do
mbps <- use $ breakpoints . at (sdName (cfFunc cf))
let atBP = fromMaybe False $ S.member (cf^.cfLocation) <$> mbps
when atBP (enterDebuggerAtBreakpoint r)
Nothing -> return ()
setPrevCommand :: MonadIO m
=> DebuggerRef sbe m'
-> Debugger sbe m' ()
-> m ()
setPrevCommand dr cmd = withIORef dr $ onNoInput .= cmd
runNextCommand :: DebuggerContext sbe m
=> DebuggerCont sbe m
runNextCommand dr = do
mline <- HL.getInputLine "(lss) "
ds <- liftIO $ readIORef dr
case dropWhile isSpace <$> mline of
Nothing -> return ()
Just "" -> do
runDebugger (ds^.onNoInput) (\() -> runNextCommand) dr
Just cmdStr -> do
let pr = runIdentity $ parseString (dsGrammar ds) cmdStr
case resolveParse pr of
Left d -> do
HL.outputStrLn (show d)
setPrevCommand dr $ return ()
runNextCommand dr
Right cmd -> do
setPrevCommand dr cmd
runDebugger cmd (\() -> runNextCommand) dr
data DebuggerState sbe m
dsGrammar :: SimGrammar sbe m
, _selectedFrame :: Int
, _onNoInput :: Debugger sbe m ()
, _resumeThrowsError :: Bool
}
initialState :: DebuggerContext sbe m
=> Codebase sbe
-> DebuggerState sbe m
initialState cb =
DebuggerState { dsGrammar = allCmds cb
, _selectedFrame = 0
, _onNoInput = return ()
, _resumeThrowsError = False
}
selectedFrame :: Simple Lens (DebuggerState sbe m) Int
selectedFrame = lens _selectedFrame (\s v -> s { _selectedFrame = v })
onNoInput :: Simple Lens (DebuggerState sbe m) (Debugger sbe m ())
onNoInput = lens _onNoInput (\s v -> s { _onNoInput = v })
resumeThrowsError :: Simple Lens (DebuggerState sbe m) Bool
resumeThrowsError = lens _resumeThrowsError (\s v -> s { _resumeThrowsError = v })
type DebuggerRef sbe m = IORef (DebuggerState sbe m)
type DebuggerCont sbe m
= DebuggerRef sbe m
-> HL.InputT (Simulator sbe m) ()
newtype Debugger sbe m a
= Debugger { runDebugger :: (a -> DebuggerCont sbe m)
-> DebuggerCont sbe m
}
instance Functor (Debugger sbe m) where
fmap f d = Debugger (\c -> runDebugger d (c . f))
instance Applicative (Debugger sbe m) where
pure v = Debugger ($v)
mf <*> mv = Debugger $ \c -> do
runDebugger mf (\f -> runDebugger mv (c.f))
instance DebuggerContext sbe m => Monad (Debugger sbe m) where
m >>= h = Debugger $ \c -> runDebugger m (\v -> runDebugger (h v) c)
return v = Debugger ($v)
instance DebuggerContext sbe m => MonadFail (Debugger sbe m) where
fail m = Debugger $ \_c dr -> do
dbugM $ "Unexpected error: " ++ show m
setPrevCommand dr $ return ()
runNextCommand dr
instance DebuggerContext sbe m
=> MTL.MonadState (DebuggerState sbe m) (Debugger sbe m) where
get = Debugger $ \c r -> liftIO (readIORef r) >>= flip c r
put v = Debugger $ \c r -> liftIO (writeIORef r v) >> c () r
instance DebuggerContext sbe m => MonadIO (Debugger sbe m) where
liftIO m = Debugger (\c r -> liftIO m >>= flip c r)
getDebuggerRef :: Debugger sbe m (DebuggerRef sbe m)
getDebuggerRef = Debugger (\c r -> c r r)
runSim :: Monad m => Simulator sbe m a -> Debugger sbe m a
runSim m = Debugger (\c r -> lift m >>= flip c r)
resume :: Monad m => Debugger sbe m a
resume = Debugger (\_ _ -> return ())
type DebuggerContext sbe m = (Functor sbe, Functor m
#if !MIN_VERSION_haskeline(0,8,0)
, HL.MonadException m
#else
, E.MonadMask m
#endif
, MonadIO m
, MonadFail m)
initializeDebugger :: DebuggerContext sbe m
=> Simulator sbe m (DebuggerRef sbe m)
initializeDebugger = do
cb <- gets codebase
r <- liftIO $ newIORef (initialState cb)
onPathPosChange .= checkForBreakpoint r
onSimError .= enterDebuggerOnError r
onUserInterrupt .= enterDebuggerOnInterrupt r
return r
enterDebugger :: DebuggerContext sbe m
=> DebuggerRef sbe m
-> Simulator sbe m ()
enterDebugger r eoe = do
mcs <- use ctrlStk
case mcs of
Just cs | pathIsActive (cs^.currentPath) -> do
let p = cs^.currentPath
dbugM $ show $ indent 2 (text "at" <+> ppPathNameAndLoc p)
_ -> dbugM "No active execution path."
withIORef r $ do
selectedFrame .= 0
resumeThrowsError .= eoe
grammar <- liftIO $ dsGrammar <$> readIORef r
historyPath <- liftIO getLSSHistoryPath
let settings = HL.setComplete (matcherCompletions grammar)
$ HL.defaultSettings { HL.historyFile = historyPath }
HL.runInputT settings (runNextCommand r)
enterDebuggerOnError :: DebuggerContext sbe m
=> DebuggerRef sbe m
-> ErrorHandler sbe m
enterDebuggerOnError r cs rsn = do
ctrlStk ?= cs
dbugM $ show $
text "Simulation error:" <+> ppFailRsn rsn
enterDebugger r True
enterDebuggerOnInterrupt :: DebuggerContext sbe m
=> DebuggerRef sbe m
-> Simulator sbe m ()
enterDebuggerOnInterrupt r = do
dbugM $ show $
text "Simulation interrupted: Entering debugger"
enterDebugger r False
dbugM $ "Resuming simulation"
liftIO $ resetInterrupt
enterDebuggerAtBreakpoint :: DebuggerContext sbe m
=> DebuggerRef sbe m
-> Simulator sbe m ()
enterDebuggerAtBreakpoint dr = do
dbugM "Encountered breakpoint"
enterDebugger dr False
matcherCompletions :: (Functor m, Monad m)
=> Grammar Identity a
-> (String, String)
-> Simulator sbe m (String, [HL.Completion])
matcherCompletions m (l,_r) = pure (finalize a)
where rl = reverse l
a = runIdentity $ parseString m rl
finalize pr =
(reverse (take p rl), cl)
where (p,cl) = pr^.parseCompletions
data YesNo = Yes | No
deriving (Eq)
putAndFlush :: MonadIO m => String -> m ()
putAndFlush msg = liftIO $ putStr msg >> hFlush stdout
promptChoice :: MonadIO m => String -> [(String,r)] -> m r
promptChoice prompt choices =
liftIO $ putAndFlush prompt >> loop
where loop = do
l <- dropWhile isSpace . fmap toLower <$> getLine
let resl = [ r | (c,r) <- choices, l `L.isPrefixOf` c ]
case (l,resl) of
("",_) -> putAndFlush prompt >> loop
(_,r:_) -> return r
(_,[]) -> do putAndFlush ("Invalid response; " ++ prompt)
loop
promptYesNoCancel :: MonadIO m => m (Maybe YesNo)
promptYesNoCancel = promptChoice prompt choices
where prompt = "Please enter (Y)es, (N)o, or (C)ancel: "
choices = [("yes", Just Yes), ("no", Just No), ("cancel", Nothing) ]
promptYesNo :: MonadIO m => m YesNo
promptYesNo = promptChoice prompt choices
where prompt = "Please enter (Y)es or (N)o: "
choices = [("yes", Yes), ("no", No)]
warnIfResumeThrowsError :: DebuggerContext sbe m
=> Debugger sbe m Bool
warnIfResumeThrowsError = do
rte <- use resumeThrowsError
mcs <- runSim $ use ctrlStk
case mcs of
Just cs | rte -> do
dbugM "Resuming execution on this path should rethrow the simulation error."
if csHasSinglePath cs then do
dbugM "Should lss kill the current path, and stop simulation?"
ync <- promptYesNoCancel
case ync of
Just Yes -> do
killPathByDebugger
resume
Just No -> return True
Nothing -> return False
else do
dbugM "Should lss kill the current path, and resume on a new path?"
ync <- promptYesNoCancel
case ync of
Just Yes -> do
killPathByDebugger
return True
Just No -> return True
Nothing -> return False
Just cs -> return (pathIsActive (cs^.currentPath))
Nothing -> return False
resumeActivePath :: DebuggerContext sbe m
=> (Path sbe -> Simulator sbe m ())
-> Debugger sbe m ()
resumeActivePath action = do
continueResume <- warnIfResumeThrowsError
when continueResume $
withActivePath () $ \p -> do
runSim (action p)
resume
type DebuggerGrammar a = Grammar Identity a
type SimGrammar sbe m = DebuggerContext sbe m
=> DebuggerGrammar (Debugger sbe m ())
commandHelp :: Grammar m a -> Doc
commandHelp cmds =
text "List of commands:" <$$>
PP.empty <$$>
vcat (ppCmdHelp <$> (help^.helpCmds)) <$$>
PP.empty <$$>
text "NOT IMPLEMENTED: Type \"help\" followed by command name for full documentation." <$$>
text "Command name abbreviations are allowed if unambiguous."
where help = matcherHelp cmds
newtype NameMap = NameMap (M.Map String NameMapPair)
type NameMapPair = (Maybe SymBlockID, NameMap)
emptyNameMap :: NameMap
emptyNameMap = NameMap M.empty
splitName :: String -> [String]
splitName nm =
case break (=='.') nm of
(l,[]) -> [l]
(l,_:r) -> l : splitName r
mergeName :: SymBlockID -> [String] -> NameMapPair -> NameMapPair
mergeName b [] (_,m) = (Just b,m)
mergeName b (h:r) (o,NameMap m) = (o, NameMap $ m & at h ?~ mergeName b r mr)
where mr = fromMaybe (Nothing, NameMap M.empty) $ m^.at h
insertName :: NameMap -> SymBlockID -> NameMap
insertName m b = snd $ mergeName b (splitName (show (ppSymBlockID b)))
(Nothing,m)
pairBlocks :: SymDefine t -> NameMapPair -> Grammar m (Symbol, Breakpoint)
pairBlocks d (mb,m@(NameMap m')) = switch $ others ++ end
where others | M.null m' = []
| otherwise = [(,) "." $ nameBlocks d m]
end = case mb of
Nothing -> []
Just b -> [(,) "" $ pure (sdName d,(b,0))]
nameBlocks :: SymDefine t -> NameMap -> Grammar m (Symbol, Breakpoint)
nameBlocks d (NameMap m) = switch $ (entry <$> M.toList m)
where entry (nm,p) = (fromString nm, pairBlocks d p)
locSeq :: forall sbe m . Codebase sbe -> Grammar m (Symbol, Breakpoint)
locSeq cb = argLabel (text "<loc>") *> hide (switch $ fmap matchDef (cbDefs cb))
where matchDef :: SymDefine (SBETerm sbe)
-> (SwitchKey, Grammar m (Symbol, Breakpoint))
matchDef d = ( fromString nm
, switch [ (,) ":" (nameBlocks d m)
, (,) "" $ end
]
)
where Symbol nm = sdName d
end :: Grammar m (Symbol, Breakpoint)
end = pure (sdName d, (sdEntry d, 0))
m = foldl insertName emptyNameMap (M.keys (sdBody d))
optNatArg :: Integer
-> DebuggerGrammar (Integer -> Debugger sbe m ())
-> DebuggerGrammar (Debugger sbe m ())
optNatArg def g = (fromMaybe def <$> opt nat) <**> g
allCmds :: Codebase sbe -> SimGrammar sbe m
allCmds cb = res
Breakpoints
= keyword "continue" *> continueCmd
<||> keyword "break" *> breakCmd cb
<||> keyword "delete" *> deleteCmd cb
<||> keyword "finish" *> finishCmd
<||> hide (keyword "s" *> stepiCmd)
<||> keyword "stepi" *> stepiCmd
<||> keyword "info" *> infoCmd
Stack control
<||> hide (keyword "bt" *> backtraceCmd)
<||> keyword "backtrace" *> backtraceCmd
<||> keyword "frame" *> frameCmd
<||> keyword "up" *> upFrameCmd
<||> keyword "down" *> downFrameCmd
<||> keyword "select_frame" *> selectFrameCmd
<||> keyword "path" *> pathCmd
<||> keyword "help" *> helpCmd res
<||> keyword "quit" *> quitCmd
helpCmd :: SimGrammar sbe m -> SimGrammar sbe m
helpCmd cmdList = cmdDef "Print list of commands." $ do
liftIO $ print (commandHelp cmdList)
pathCmd :: SimGrammar sbe m
pathCmd
= hide pathListCmd
<||> keyword "kill" *> pathKillCmd
<||> keyword "list" *> pathListCmd
<||> keyword "sat" *> pathSatCmd
pathListCmd :: SimGrammar sbe m
pathListCmd = cmdDef "List all current execution paths." $ runSim $ do
mcs <- use ctrlStk
case mcs of
Nothing ->
dbugM "No active paths."
Just cs -> dbugM $ show $ printTable table
where ppPathItem :: Integer -> Path sbe -> [String]
ppPathItem i p = [ 3 `padLeft` (show i)
, show (ppPathNameAndLoc p)
]
header = [ " Num", "Location"]
table = header : zipWith ppPathItem [1..] (cs^..currentPaths)
pathSatCmd :: SimGrammar sbe m
pathSatCmd =
cmdDef "Check satisfiability of path assertions with SAT solver." $ do
withActiveCS () $ do
sat <- runSim $ do
sbe <- gets symBE
cond <- assumptionsForActivePath
liftSBE $ termSAT sbe cond
case sat of
Unsat -> do
dbugM "The current path is infeasible. Should simulation of the path be terminated?"
yn <- promptYesNo
when (yn == Yes) $ do
killPathByDebugger
Sat _ ->
dbugM "Conditions along path are satisfiable."
SatUnknown ->
dbugM "Could not determine if path is feasible."
killPathByDebugger :: DebuggerContext sbe m
=> Debugger sbe m ()
killPathByDebugger = do
runSim $ killCurrentPath (FailRsn "Terminated by debugger.")
resumeThrowsError .= False
pathKillCmd :: SimGrammar sbe m
pathKillCmd = cmdDef "Kill the current execution path." $ do
withActiveCS () $ do
killPathByDebugger
mp <- runSim $ preuse currentPathOfState
case mp of
Nothing -> dbugM "Killed last path."
Just p -> dbugM $ show $
text "Switched to path:" <+> ppPathNameAndLoc p
quitCmd :: SimGrammar sbe m
quitCmd = cmdDef "Exit LSS." $ do
mcs <- runSim $ use ctrlStk
case mcs of
Just cs | pathIsActive (cs^.currentPath) ->
liftIO $ exitWith ExitSuccess
_ -> resume
breakCmd :: Codebase sbe -> SimGrammar sbe m
breakCmd cb = (locSeq cb <**>) $ cmdDef desc $ \(b,p) -> do
runSim $ addBreakpoint b p
where desc = "Set a breakpoint at a specified location."
deleteCmd :: Codebase sbe -> SimGrammar sbe m
deleteCmd cb = (opt (locSeq cb) <**>) $ cmdDef desc $ \mbp -> do
runSim $
case mbp of
Just (b,p) -> removeBreakpoint b p
Nothing -> dbugM "Remove all breakpoints"
where desc = "Clear a breakpoint at a function."
concatBreakpoints :: M.Map Symbol (S.Set Breakpoint)
-> [(Symbol, Breakpoint)]
concatBreakpoints m =
[ (sym,bp) | (sym, bps) <- M.toList m, bp <- S.toList bps ]
infoCmd :: SimGrammar sbe m
infoCmd
= keyword "args" *> infoArgsCmd
<||> keyword "block" *> infoBlockCmd
<||> keyword "breakpoints" *> infoBreakpointsCmd
<||> keyword "ctrlstk" *> infoCtrlStkCmd
<||> keyword "function" *> infoFunctionCmd
<||> keyword "locals" *> infoLocalsCmd
<||> keyword "memory" *> infoMemoryCmd
<||> keyword "stack" *> backtraceCmd
infoArgsCmd :: SimGrammar sbe m
infoArgsCmd =
cmdDef "Print argument variables in the current stack frame." $ do
withActiveCallFrame () $ \cf -> do
sbe <- gets symBE
dbugM $ show $ ppLocals sbe $ cfArgValues cf
infoBlockCmd :: SimGrammar sbe m
infoBlockCmd =
cmdDef "Print block information." $ do
withActiveCallFrame () $ \cf -> do
dbugM $ show $ ppSymBlock $ cfBlock cf
infoBreakpointsCmd :: SimGrammar sbe m
infoBreakpointsCmd =
cmdDef "List breakpoints." $ runSim $ do
bps <- concatBreakpoints <$> use breakpoints
let ppRow :: Integer -> (Symbol,Breakpoint) -> [String]
ppRow i (Symbol sym,bp) =
[show i, sym ++ ":" ++ show (ppBreakpoint bp)]
dbugM $ show $
case bps of
[] -> text "No breakpoints."
_ -> printTable (header : zipWith ppRow [1..] bps)
where header = ["Num", "Location"]
infoCtrlStkCmd :: SimGrammar sbe m
infoCtrlStkCmd =
cmdDef "Print the entire control stack." $ do
runSim dumpCtrlStk
infoFunctionCmd :: SimGrammar sbe m
infoFunctionCmd =
cmdDef "Print function information." $ do
withActiveCallFrame () $ \cf -> do
dbugM $ show $ ppSymDefine (cfFunc cf)
infoLocalsCmd :: SimGrammar sbe m
infoLocalsCmd =
cmdDef "Print local variables in the current stack frame." $ do
withActiveCallFrame () $ \cf -> do
sbe <- gets symBE
dbugM $ show $ ppLocals sbe $ cfLocalValues cf
Instead writing @infoMemoryRangeCmd < * > optAddr < * > optAddr@
infoMemoryCmd :: SimGrammar sbe m
infoMemoryCmd = ((,) <$> optAddr <*> optAddr) <**> infoMemoryRangeCmd
where
infoMemoryRangeCmd = cmdDef desc $ \(mlow, mhigh) -> do
let mranges = case (mlow, mhigh) of
(Just low, Just high) -> Just [(low, high)]
(Just low, Nothing) -> Just [(low, low+1)]
(Nothing, Nothing) -> Nothing
(Nothing, Just _) -> error "infoMemoryCmd: unreachable!"
runSim $ dumpMem 0 "memory" mranges
Putting the ' opt ' outside here , and ' hide ' on ' ' , results in a
optAddr = opt (argLabel (text "<addr>") *> hide nat)
desc = unlines
[ "Print memory information."
, ""
, " - With no arguments, prints all memory."
, " - With one argument <addr>, prints memory at address <addr>."
, " - With two arguments <low>, <high>, prints memory in the address range"
, " [<low>,<high>)."
, ""
, " The optional address arguments may be specified in binary (e.g. 0b110),"
, " decimal, or hex (e.g. 0xabcd)."
]
listCmd : : SimGrammar sbe m
( locSeq cb < * * > ) $ cmdDef " List specified function in line . " $ \loc - > do
error " internal : listCmd undefined " loc
listCmd :: Codebase sbe -> SimGrammar sbe m
listCmd cb = (locSeq cb <**>) $ cmdDef "List specified function in line." $ \loc -> do
error "internal: listCmd undefined" loc
-}
padLeft :: Int -> String -> String
padLeft l s = replicate (l - length s) ' ' ++ s
| @padRight n s@ adds extra spaces after @s@ so that the result has
padRight :: String -> Int -> String
padRight s l = s ++ replicate (l - length s) ' '
printTable :: [[String]] -> Doc
printTable m = vcat padded
where maxl (i:x) (j:y) = max i j : maxl x y
maxl [] y = y
maxl x [] = x
ll = fmap length <$> m
maxLengths = foldr maxl (repeat 0) ll
padded = hsep . fmap text . zipWith padLeft maxLengths <$> m
ppBreakpoint :: Breakpoint -> Doc
ppBreakpoint (sbid,0) = ppSymBlockID sbid
ppBreakpoint (sbid,i) = ppSymBlockID sbid PP.<> char ':' PP.<> int i
withActiveCS :: DebuggerContext sbe m
-> Debugger sbe m a
withActiveCS v action = do
mcs <- runSim $ use ctrlStk
case mcs of
Just cs | pathIsActive (cs^.currentPath) -> action
_ -> dbugM "No active execution path." >> return v
| @withActivePath v act@ runs @act@ with the active path
withActivePath :: DebuggerContext sbe m
=> a
-> (Path sbe -> Debugger sbe m a)
-> Debugger sbe m a
withActivePath v action = do
mcs <- runSim $ use ctrlStk
case mcs of
Just cs | pathIsActive (cs^.currentPath) -> action (cs^.currentPath)
_ -> dbugM "No active execution path." >> return v
| v act@ runs @act@ with the active call frame .
withActiveCallFrame :: DebuggerContext sbe m
=> a
-> (CallFrame sbe -> Simulator sbe m a)
-> Debugger sbe m a
withActiveCallFrame v action = do
i <- use selectedFrame
runSim $ do
mp <- preuse currentPathOfState
case mp of
Just p | cf:_ <- drop i (p^..pathCallFrames) -> do
action cf
_ -> dbugM "No active execution path." >> return v
continueCmd :: SimGrammar sbe m
continueCmd = cmdDef "Continue execution." $ do
dr <- getDebuggerRef
resumeActivePath $ \_ -> do
onPathPosChange .= checkForBreakpoint dr
onReturnFrom :: DebuggerContext sbe m
=> DebuggerRef sbe m -> Int -> Simulator sbe m ()
onReturnFrom dr ht = do
Just p <- preuse currentPathOfState
if pathStackHt p < ht then
enterDebuggerAtBreakpoint dr
else
checkForBreakpoint dr
finishCmd :: SimGrammar sbe m
finishCmd = cmdDef desc $ do
dr <- getDebuggerRef
resumeActivePath $ \p -> do
onPathPosChange .= onReturnFrom dr (pathStackHt p)
where desc = "Execute until the current stack frame returns."
enterDebuggerAfterNSteps
:: DebuggerContext sbe m
=> DebuggerRef sbe m -> Integer -> Simulator sbe m ()
enterDebuggerAfterNSteps dr n
| n <= 1 = enterDebugger dr False
| otherwise = onPathPosChange .= enterDebuggerAfterNSteps dr (n-1)
stepiCmd :: SimGrammar sbe m
stepiCmd = optNatArg 1 $
cmdDef "Execute one symbolic statement." $ \c -> do
when (c > 0) $ do
dr <- getDebuggerRef
resumeActivePath $ \_ -> do
onPathPosChange .= enterDebuggerAfterNSteps dr c
ppFrameLoc :: SBE sbe -> Int -> CallFrame sbe -> Doc
ppFrameLoc sbe i cf =
char '#' <> text (show i `padRight` 2)
<+> ppSymbol (sdName (cfFunc cf)) <> parens (commaSepList argDocs)
<+> text "at" <+> ppLocation (cf^.cfLocation)
where argDocs = ppArg <$> cfArgValues cf
ppArg (nm,v) =
ppIdent nm <> char '=' <+> prettyTermD sbe v
withActiveStack :: DebuggerContext sbe m
=> ([CallFrame sbe] -> Debugger sbe m ())
-> Debugger sbe m ()
withActiveStack action = do
mp <- runSim $ preuse currentPathOfState
case mp of
Just p | cfl <- p^..pathCallFrames, not (null cfl) -> action cfl
_ -> dbugM "No stack."
| @selectFrame i action@ checks that @i@ is a valid frame ,
selectFrame :: DebuggerContext sbe m
=> Int -> (CallFrame sbe -> Debugger sbe m ()) -> Debugger sbe m ()
selectFrame i action =
withActiveStack $ \cfl -> do
if 0 <= i && i < length cfl then do
selectedFrame .= i
action (cfl !! i)
else do
dbugM $ "No frame #" ++ show i ++ "."
printFrameLoc :: MonadIO m => Int -> CallFrame sbe -> Debugger sbe m ()
printFrameLoc i cf = runSim $ do
sbe <- gets symBE
dbugM $ show $ ppFrameLoc sbe i cf
backtraceCmd :: SimGrammar sbe m
backtraceCmd = cmdDef "Print backtrace of the stack." $ do
withActivePath () $ \p -> do
zipWithM_ printFrameLoc [0..] (p^..pathCallFrames)
selectFrameCmd :: SimGrammar sbe m
selectFrameCmd = (<**>) nat $
cmdDef "Select a stack frame without printing anything." $ \(fromInteger -> i) -> do
selectFrame i $ \_ -> return ()
frameCmd :: SimGrammar sbe m
frameCmd = (<**>) nat $
cmdDef "Select and print a stack frame." $ \(fromInteger -> i) -> do
selectFrame i $ \cf -> do
printFrameLoc i cf
| Move up one or more frames to a function that called the current frame .
upFrameCmd :: SimGrammar sbe m
upFrameCmd = optNatArg 1 $
cmdDef "Select and print stack frame that called this one." $ \c -> do
withActiveStack $ \cfl -> do
i <- use selectedFrame
if i > 0 then do
let i' = max 0 (i - fromInteger c)
selectedFrame .= i'
printFrameLoc i' $ cfl !! i'
else do
dbugM "Initial frame already selected; you cannot go up."
| Move down one or more frames to a function called by the current frame .
downFrameCmd :: SimGrammar sbe m
downFrameCmd = optNatArg 1 $
cmdDef "Select and print stack frame called by this one." $ \c -> do
withActiveStack $ \cfl -> do
i <- use selectedFrame
let maxIdx = length cfl - 1
if i < maxIdx then do
let i' = min maxIdx (i + fromInteger c)
selectedFrame .= i'
printFrameLoc i' $ cfl !! i'
else do
dbugM "Bottom frame selected; you cannot go down."
|
20a8284a413ae9eaf43b10d0178587075469e290cfcecba250f46fe703663df4 | lilactown/pyramid | benchmark.clj | (ns benchmark
(:require
[pyramid.core :as p]
[criterium.core :as c]
[clj-async-profiler.core :as prof]))
(prof/serve-files 8080)
(prof/profile (dotimes [i 10000]
(p/db [{:person/id 123
:person/name "Will"
:contact {:phone "000-000-0001"}
:best-friend
{:person/id 456
:person/name "Jose"
:account/email "asdf@jkl"}
:friends
[{:person/id 9001
:person/name "Georgia"}
{:person/id 456
:person/name "Jose"}
{:person/id 789
:person/name "Frank"}
{:person/id 1000
:person/name "Robert"}]}
{:person/id 456
:best-friend {:person/id 123}}])))
(c/quick-bench
(p/db [{:person/id 123
:person/name "Will"
:contact {:phone "000-000-0001"}
:best-friend
{:person/id 456
:person/name "Jose"
:account/email "asdf@jkl"}
:friends
[{:person/id 9001
:person/name "Georgia"}
{:person/id 456
:person/name "Jose"}
{:person/id 789
:person/name "Frank"}
{:person/id 1000
:person/name "Robert"}]}
{:person/id 456
:best-friend {:person/id 123}}]))
(def big-data
[{:foo/data
(vec
(for [i (range 1000)]
{:foo/id (str "id" i)
:foo/name (str "bar" i)
:foo/metadata {:some ["dumb" "data"]}})) } ])
(c/quick-bench (p/db big-data))
(prof/profile
(dotimes [i 1000]
(p/db big-data)))
;; this throws w/ StackOverflow on my computer when running p/db
numbers 10000 and up throw when generating the tree
(def limit 7946)
(def nested-data
(letfn [(create [i]
(if (zero? i)
nil
{:id i
:child (create (dec i))}))]
{:foo (create limit) }))
(do (p/db [nested-data])
nil)
(c/quick-bench (p/db [nested-data]))
;; testing out different trampoline strategies
(defn create [k i]
(if (zero? i)
(k)
(fn []
(create
(fn []
{:id i
:child (k)})
(dec i)))))
(def really-nested-data
{:foo (trampoline create (constantly {:id 0}) 50000) })
(do (p/db [really-nested-data])
nil)
(c/quick-bench (p/db [really-nested-data]))
(prof/profile (dotimes [i 1000]
(p/db [really-nested-data])))
(def ppl-db
(p/db [{:person/id 123
:person/name "Will"
:contact {:phone "000-000-0001"}
:best-friend
{:person/id 456
:person/name "Jose"
:account/email "asdf@jkl"}
:friends
[{:person/id 9001
:person/name "Georgia"}
{:person/id 456
:person/name "Jose"}
{:person/id 789
:person/name "Frank"}
{:person/id 1000
:person/name "Robert"}]}
{:person/id 456
:best-friend {:person/id 123}}]))
(p/pull ppl-db [{[:person/id 123] [:person/id
:person/name
{:friends [:person/id :person/name]}]}])
(def query [{[:person/id 123] [:person/id
:person/name
{:friends [:person/id :person/name]}]}])
(c/quick-bench
(p/pull ppl-db query))
(prof/profile (dotimes [i 5000]
(p/pull ppl-db query)))
| null | https://raw.githubusercontent.com/lilactown/pyramid/eda474116574ec90f4199f6b2544c6fc75787653/benchmark.clj | clojure | this throws w/ StackOverflow on my computer when running p/db
testing out different trampoline strategies | (ns benchmark
(:require
[pyramid.core :as p]
[criterium.core :as c]
[clj-async-profiler.core :as prof]))
(prof/serve-files 8080)
(prof/profile (dotimes [i 10000]
(p/db [{:person/id 123
:person/name "Will"
:contact {:phone "000-000-0001"}
:best-friend
{:person/id 456
:person/name "Jose"
:account/email "asdf@jkl"}
:friends
[{:person/id 9001
:person/name "Georgia"}
{:person/id 456
:person/name "Jose"}
{:person/id 789
:person/name "Frank"}
{:person/id 1000
:person/name "Robert"}]}
{:person/id 456
:best-friend {:person/id 123}}])))
(c/quick-bench
(p/db [{:person/id 123
:person/name "Will"
:contact {:phone "000-000-0001"}
:best-friend
{:person/id 456
:person/name "Jose"
:account/email "asdf@jkl"}
:friends
[{:person/id 9001
:person/name "Georgia"}
{:person/id 456
:person/name "Jose"}
{:person/id 789
:person/name "Frank"}
{:person/id 1000
:person/name "Robert"}]}
{:person/id 456
:best-friend {:person/id 123}}]))
(def big-data
[{:foo/data
(vec
(for [i (range 1000)]
{:foo/id (str "id" i)
:foo/name (str "bar" i)
:foo/metadata {:some ["dumb" "data"]}})) } ])
(c/quick-bench (p/db big-data))
(prof/profile
(dotimes [i 1000]
(p/db big-data)))
numbers 10000 and up throw when generating the tree
(def limit 7946)
(def nested-data
(letfn [(create [i]
(if (zero? i)
nil
{:id i
:child (create (dec i))}))]
{:foo (create limit) }))
(do (p/db [nested-data])
nil)
(c/quick-bench (p/db [nested-data]))
(defn create [k i]
(if (zero? i)
(k)
(fn []
(create
(fn []
{:id i
:child (k)})
(dec i)))))
(def really-nested-data
{:foo (trampoline create (constantly {:id 0}) 50000) })
(do (p/db [really-nested-data])
nil)
(c/quick-bench (p/db [really-nested-data]))
(prof/profile (dotimes [i 1000]
(p/db [really-nested-data])))
(def ppl-db
(p/db [{:person/id 123
:person/name "Will"
:contact {:phone "000-000-0001"}
:best-friend
{:person/id 456
:person/name "Jose"
:account/email "asdf@jkl"}
:friends
[{:person/id 9001
:person/name "Georgia"}
{:person/id 456
:person/name "Jose"}
{:person/id 789
:person/name "Frank"}
{:person/id 1000
:person/name "Robert"}]}
{:person/id 456
:best-friend {:person/id 123}}]))
(p/pull ppl-db [{[:person/id 123] [:person/id
:person/name
{:friends [:person/id :person/name]}]}])
(def query [{[:person/id 123] [:person/id
:person/name
{:friends [:person/id :person/name]}]}])
(c/quick-bench
(p/pull ppl-db query))
(prof/profile (dotimes [i 5000]
(p/pull ppl-db query)))
|
92f0068d9d06acc1bf2c602d02f1406eabbc64aaabf3fa499e2228aa3adce1ef | fugue/fregot | BuildTree.hs | |
Copyright : ( c ) 2020 Fugue , Inc.
License : Apache License , version 2.0
Maintainer :
Stability : experimental
Portability : POSIX
Helper module for building rule trees from JSON and YAML documents .
Copyright : (c) 2020 Fugue, Inc.
License : Apache License, version 2.0
Maintainer :
Stability : experimental
Portability : POSIX
Helper module for building rule trees from JSON and YAML documents.
-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
module Fregot.Prepare.BuildTree
( BuildTree (..)
, toTree
, toTerm
) where
import Control.Lens (review)
import qualified Data.List as L
import Fregot.Names
import Fregot.Prepare.Ast
import Fregot.Prepare.Lens
import Fregot.Prepare.Package (PreparedRule)
import Fregot.Sources.SourceSpan (SourceSpan)
import qualified Fregot.Tree as Tree
data BuildTree
= BuildSingleton (Term SourceSpan)
| BuildTree SourceSpan [(SourceSpan, Var, BuildTree)]
toTree
:: PackageName -> [(SourceSpan, Var, BuildTree)] -> Tree.Tree PreparedRule
toTree pkgname =
Tree.prefix (review packageNameFromKey pkgname) . makeTree pkgname
makeTree
:: PackageName -> [(SourceSpan, Var, BuildTree)] -> Tree.Tree PreparedRule
makeTree pkgname = L.foldl' Tree.union Tree.empty . map toRuleOrTree
where
toRuleOrTree (loc, var, BuildSingleton t) = Tree.singleton
(review varFromKey var)
(termToRule loc pkgname var t)
toRuleOrTree (_, var, BuildTree _ t) =
Tree.parent [(var, makeTree (pkgname <> mkPackageName [unVar var]) t)]
-- NOTE(jaspervdj): Should we have this use the new 'ValueT' to only represent
-- values?
toTerm :: BuildTree -> Term SourceSpan
toTerm (BuildSingleton t) = t
toTerm (BuildTree loc children) = ObjectT loc $
[ (review termToScalar (l, String $ unVar v), toTerm child)
| (l, v, child) <- children
]
| null | https://raw.githubusercontent.com/fugue/fregot/c3d87f37c43558761d5f6ac758d2f1a4117adb3e/lib/Fregot/Prepare/BuildTree.hs | haskell | # LANGUAGE OverloadedStrings #
NOTE(jaspervdj): Should we have this use the new 'ValueT' to only represent
values? | |
Copyright : ( c ) 2020 Fugue , Inc.
License : Apache License , version 2.0
Maintainer :
Stability : experimental
Portability : POSIX
Helper module for building rule trees from JSON and YAML documents .
Copyright : (c) 2020 Fugue, Inc.
License : Apache License, version 2.0
Maintainer :
Stability : experimental
Portability : POSIX
Helper module for building rule trees from JSON and YAML documents.
-}
# LANGUAGE FlexibleContexts #
module Fregot.Prepare.BuildTree
( BuildTree (..)
, toTree
, toTerm
) where
import Control.Lens (review)
import qualified Data.List as L
import Fregot.Names
import Fregot.Prepare.Ast
import Fregot.Prepare.Lens
import Fregot.Prepare.Package (PreparedRule)
import Fregot.Sources.SourceSpan (SourceSpan)
import qualified Fregot.Tree as Tree
data BuildTree
= BuildSingleton (Term SourceSpan)
| BuildTree SourceSpan [(SourceSpan, Var, BuildTree)]
toTree
:: PackageName -> [(SourceSpan, Var, BuildTree)] -> Tree.Tree PreparedRule
toTree pkgname =
Tree.prefix (review packageNameFromKey pkgname) . makeTree pkgname
makeTree
:: PackageName -> [(SourceSpan, Var, BuildTree)] -> Tree.Tree PreparedRule
makeTree pkgname = L.foldl' Tree.union Tree.empty . map toRuleOrTree
where
toRuleOrTree (loc, var, BuildSingleton t) = Tree.singleton
(review varFromKey var)
(termToRule loc pkgname var t)
toRuleOrTree (_, var, BuildTree _ t) =
Tree.parent [(var, makeTree (pkgname <> mkPackageName [unVar var]) t)]
toTerm :: BuildTree -> Term SourceSpan
toTerm (BuildSingleton t) = t
toTerm (BuildTree loc children) = ObjectT loc $
[ (review termToScalar (l, String $ unVar v), toTerm child)
| (l, v, child) <- children
]
|
65ea7f537c535cf7e38e0a10194e7667da3a65ef01e559529a44744f7e721da1 | mirage/conan | number.mli | type t
val int64 : int64 -> t
val float : float -> t
val pp : Format.formatter -> t -> unit
val to_float : t -> float
val to_int : t -> int
val to_int64 : t -> int64
val to_int32 : t -> int32
val to_short : t -> int
val to_byte : t -> char
val to_ptime : t -> Ptime.Span.t
val parse : Sub.t -> (t * Sub.t, [> `Empty | `Invalid_number of string ]) result
| null | https://raw.githubusercontent.com/mirage/conan/fb144c7785ff0aa4ec6d8c87e58ca2a0c2d328db/src/number.mli | ocaml | type t
val int64 : int64 -> t
val float : float -> t
val pp : Format.formatter -> t -> unit
val to_float : t -> float
val to_int : t -> int
val to_int64 : t -> int64
val to_int32 : t -> int32
val to_short : t -> int
val to_byte : t -> char
val to_ptime : t -> Ptime.Span.t
val parse : Sub.t -> (t * Sub.t, [> `Empty | `Invalid_number of string ]) result
| |
b01dba792423febcebffb1744b7f7c9ba527654741299512adfe2581a9a84ef7 | fujita-y/ypsilon | 27.scm | #!nobacktrace
(define-library (srfi 27)
(import (core) (rnrs))
(export make-random-source
random-source?
random-source-state-ref
random-source-state-set!
random-source-randomize!
random-source-pseudo-randomize!
random-source-make-integers
random-source-make-reals
default-random-source
random-integer
random-real)
(begin
(define cmwc-initial-state (make-cmwc-random-state (microsecond)))
(define make-random-source (lambda () (tuple 'type:random-source (bytevector-copy cmwc-initial-state))))
(define random-source? (lambda (obj) (eq? (tuple-ref obj 0) 'type:random-source)))
(define random-source-state-ref (lambda (s) (bytevector->uint-list (tuple-ref s 1) (native-endianness) 4)))
(define random-source-state-set!
(lambda (s state) (tuple-set! s 1 (uint-list->bytevector state (native-endianness) 4))))
(define random-source-randomize!
(lambda (s)
(bytevector-copy!
(make-cmwc-random-state (microsecond))
0
(tuple-ref s 1)
0
(bytevector-length (tuple-ref s 1)))))
(define random-source-pseudo-randomize!
(lambda (s i j)
(bytevector-copy!
(make-cmwc-random-state
(+
(bitwise-and i 65535)
(bitwise-arithmetic-shift-left (bitwise-and j 65535) 16)
(bitwise-arithmetic-shift-left (bitwise-and i 4294901760) 16)
(bitwise-arithmetic-shift-left (bitwise-and j 4294901760) 32)))
0
(tuple-ref s 1)
0
(bytevector-length (tuple-ref s 1)))))
(define make-integer-rng
(lambda (cmwc-state)
(lambda (n)
(if (<= n 4294967296)
(cmwc-random-u32 cmwc-state n)
(let ()
(define rn-count (div (+ (bitwise-length n) 31) 32))
(define rn-range (- (expt 2 (* rn-count 32)) 1))
(define quo (div rn-range n))
(define limit (* quo n))
(define large-rng
(lambda ()
(let loop ((acc 0) (i 0))
(if (>= i rn-count)
acc
(loop (+ (bitwise-arithmetic-shift-left acc 32) (cmwc-random-u32 cmwc-state)) (+ i 1))))))
(let loop ((temp (large-rng))) (if (>= temp limit) (loop (large-rng)) (div temp quo))))))))
(define make-real-rng (lambda (cmwc-state) (lambda () (cmwc-random-real cmwc-state))))
(define random-source-make-integers (lambda (s) (make-integer-rng (tuple-ref s 1))))
(define random-source-make-reals (lambda (s . unit) (make-real-rng (tuple-ref s 1))))
(define default-random-source (make-random-source))
(define random-integer (random-source-make-integers default-random-source))
(define random-real (random-source-make-reals default-random-source))))
| null | https://raw.githubusercontent.com/fujita-y/ypsilon/44260d99e24000f9847e79c94826c3d9b76872c2/sitelib/srfi/27.scm | scheme | #!nobacktrace
(define-library (srfi 27)
(import (core) (rnrs))
(export make-random-source
random-source?
random-source-state-ref
random-source-state-set!
random-source-randomize!
random-source-pseudo-randomize!
random-source-make-integers
random-source-make-reals
default-random-source
random-integer
random-real)
(begin
(define cmwc-initial-state (make-cmwc-random-state (microsecond)))
(define make-random-source (lambda () (tuple 'type:random-source (bytevector-copy cmwc-initial-state))))
(define random-source? (lambda (obj) (eq? (tuple-ref obj 0) 'type:random-source)))
(define random-source-state-ref (lambda (s) (bytevector->uint-list (tuple-ref s 1) (native-endianness) 4)))
(define random-source-state-set!
(lambda (s state) (tuple-set! s 1 (uint-list->bytevector state (native-endianness) 4))))
(define random-source-randomize!
(lambda (s)
(bytevector-copy!
(make-cmwc-random-state (microsecond))
0
(tuple-ref s 1)
0
(bytevector-length (tuple-ref s 1)))))
(define random-source-pseudo-randomize!
(lambda (s i j)
(bytevector-copy!
(make-cmwc-random-state
(+
(bitwise-and i 65535)
(bitwise-arithmetic-shift-left (bitwise-and j 65535) 16)
(bitwise-arithmetic-shift-left (bitwise-and i 4294901760) 16)
(bitwise-arithmetic-shift-left (bitwise-and j 4294901760) 32)))
0
(tuple-ref s 1)
0
(bytevector-length (tuple-ref s 1)))))
(define make-integer-rng
(lambda (cmwc-state)
(lambda (n)
(if (<= n 4294967296)
(cmwc-random-u32 cmwc-state n)
(let ()
(define rn-count (div (+ (bitwise-length n) 31) 32))
(define rn-range (- (expt 2 (* rn-count 32)) 1))
(define quo (div rn-range n))
(define limit (* quo n))
(define large-rng
(lambda ()
(let loop ((acc 0) (i 0))
(if (>= i rn-count)
acc
(loop (+ (bitwise-arithmetic-shift-left acc 32) (cmwc-random-u32 cmwc-state)) (+ i 1))))))
(let loop ((temp (large-rng))) (if (>= temp limit) (loop (large-rng)) (div temp quo))))))))
(define make-real-rng (lambda (cmwc-state) (lambda () (cmwc-random-real cmwc-state))))
(define random-source-make-integers (lambda (s) (make-integer-rng (tuple-ref s 1))))
(define random-source-make-reals (lambda (s . unit) (make-real-rng (tuple-ref s 1))))
(define default-random-source (make-random-source))
(define random-integer (random-source-make-integers default-random-source))
(define random-real (random-source-make-reals default-random-source))))
| |
18c508fd9ea1f9ede7a2b734f95a4010a1f5660aad8c5a387732b39be3c35922 | roman01la/hooks | impl.cljs | (ns hooks.impl
(:require ["use-sync-external-store/shim/with-selector" :refer [useSyncExternalStoreWithSelector]]
[react-dom]
[react]))
(defn- setup-batched-updates-listener [^js ref]
;; Adding an atom holding a set of listeners on a ref if it wasn't added yet
(when-not (.-react-listeners ref)
(set! (.-react-listeners ref) (atom #{}))
When the ref is updated , execute all listeners in a batch
(add-watch ref ::batched-subscribe
(fn [_ _ _ _]
(react-dom/unstable_batchedUpdates
#(doseq [listener @(.-react-listeners ref)]
(listener)))))))
(defn- teardown-batched-updates-listener [^js ref]
;; When the last listener was removed,
;; remove batched updates listener from the ref
(when (empty? @(.-react-listeners ref))
(set! (.-react-listeners ref) nil)
(remove-watch ref ::batched-subscribe)))
(defn use-batched-subscribe
"Takes an atom-like ref type and returns a function that subscribes to changes
in the ref, where subscribed listeners execution is batched via `react-dom/unstable_batchedUpdates`"
[^js ref]
(react/useCallback
(fn [listener]
(setup-batched-updates-listener ref)
(swap! (.-react-listeners ref) conj listener)
(fn []
(swap! (.-react-listeners ref) disj listener)
(teardown-batched-updates-listener ref)))
#js [ref]))
(defn use-sync-external-store [subscribe get-snapshot]
(useSyncExternalStoreWithSelector
subscribe
get-snapshot
getServerSnapshot , only needed for SSR
identity ;; selector, not using, just returning the value itself
=)) ;; value equality check
| null | https://raw.githubusercontent.com/roman01la/hooks/7b26bcb68afdb0991f2efb341cec3d70ef5ba576/src/hooks/impl.cljs | clojure | Adding an atom holding a set of listeners on a ref if it wasn't added yet
When the last listener was removed,
remove batched updates listener from the ref
selector, not using, just returning the value itself
value equality check | (ns hooks.impl
(:require ["use-sync-external-store/shim/with-selector" :refer [useSyncExternalStoreWithSelector]]
[react-dom]
[react]))
(defn- setup-batched-updates-listener [^js ref]
(when-not (.-react-listeners ref)
(set! (.-react-listeners ref) (atom #{}))
When the ref is updated , execute all listeners in a batch
(add-watch ref ::batched-subscribe
(fn [_ _ _ _]
(react-dom/unstable_batchedUpdates
#(doseq [listener @(.-react-listeners ref)]
(listener)))))))
(defn- teardown-batched-updates-listener [^js ref]
(when (empty? @(.-react-listeners ref))
(set! (.-react-listeners ref) nil)
(remove-watch ref ::batched-subscribe)))
(defn use-batched-subscribe
"Takes an atom-like ref type and returns a function that subscribes to changes
in the ref, where subscribed listeners execution is batched via `react-dom/unstable_batchedUpdates`"
[^js ref]
(react/useCallback
(fn [listener]
(setup-batched-updates-listener ref)
(swap! (.-react-listeners ref) conj listener)
(fn []
(swap! (.-react-listeners ref) disj listener)
(teardown-batched-updates-listener ref)))
#js [ref]))
(defn use-sync-external-store [subscribe get-snapshot]
(useSyncExternalStoreWithSelector
subscribe
get-snapshot
getServerSnapshot , only needed for SSR
|
e751e5de55523064a5261839e4e5b04a0751e0c44d59b45b547344568ddf0b9a | racket/typed-racket | with-type-lift.rkt | #lang racket/base
;; Test syntax lifting in `with-type`
(require rackunit typed/racket)
(with-type #:result Number
(define-syntax (m stx)
(syntax-local-lift-expression #'(+ 1 2)))
(m))
(define-syntax (m2 stx)
(syntax-local-lift-expression #'(+ 1 2)))
(with-type #:result Number (m2))
(with-type ([val Number]) (define val (m2)))
(check-equal? val 3)
(with-type #:result (Listof String)
;; casts do lifts for the contract
(define x (cast '() (Listof String)))
;; as do predicates
(make-predicate (Listof String))
x)
| null | https://raw.githubusercontent.com/racket/typed-racket/0236151e3b95d6d39276353cb5005197843e16e4/typed-racket-test/succeed/with-type-lift.rkt | racket | Test syntax lifting in `with-type`
casts do lifts for the contract
as do predicates | #lang racket/base
(require rackunit typed/racket)
(with-type #:result Number
(define-syntax (m stx)
(syntax-local-lift-expression #'(+ 1 2)))
(m))
(define-syntax (m2 stx)
(syntax-local-lift-expression #'(+ 1 2)))
(with-type #:result Number (m2))
(with-type ([val Number]) (define val (m2)))
(check-equal? val 3)
(with-type #:result (Listof String)
(define x (cast '() (Listof String)))
(make-predicate (Listof String))
x)
|
dbbeea9acb1a5a664b8b45f4dc5576360557bfc84b5cc199a3ec1f0ab587162e | craigfe/oskel | main.ml | let ( >>| ) x f = Lwt.map f x
let git_user_name () =
Oskel.Utils.Utils_unix.exec "git config user.name"
>>| function
| Ok [ name ] -> if String.(equal (trim name) "") then None else Some name
| Ok o ->
Oskel.show_errorf "Unexpected output from `git config`: %a"
Fmt.Dump.(list string)
o
| Error _ -> None
let git_email () =
Oskel.Utils.Utils_unix.exec "git config user.email"
>>| function
| Ok [ email ] -> if String.(equal (trim email) "") then None else Some email
| Ok o ->
Oskel.show_errorf "Unexpected output from `git config`: %a"
Fmt.Dump.(list string)
o
| Error _ -> None
let ( >>? ) x f = match x with Some s -> Lwt.return (Some s) | None -> f ()
let run name project_kind project_synopsis maintainer_fullname maintainer_email
github_organisation initial_version working_dir assume_yes license
dependencies versions ocamlformat_options dry_run non_interactive git_repo
current_year () : unit =
let maintainer_fullname = maintainer_fullname >>? git_user_name in
let maintainer_email = maintainer_email >>? git_email in
Oskel.run ?name ~project_kind ?project_synopsis ~maintainer_fullname
~maintainer_email ?github_organisation ?initial_version ?working_dir
~assume_yes ~license ~dependencies ~versions ~ocamlformat_options ~dry_run
~non_interactive ~git_repo ?current_year ()
open Cmdliner
let fmap f x = Term.(app (const f) x)
module Arg = struct
include Arg
let env_var s = env_var ("OSKEL_" ^ s)
end
let project_name = Arg.(value & pos 0 (some string) None & info ~docv:"NAME" [])
let project_kind =
let kinds =
[ ("library", `Library); ("binary", `Binary); ("executable", `Executable) ]
in
let doc =
Fmt.str "Type of project to create. One of %s." (Arg.doc_alts_enum kinds)
in
let env = Arg.env_var "KIND" in
Arg.(value & opt (enum kinds) `Library & info [ "kind" ] ~doc ~env)
let project_synopsis =
let doc = "Synopsis of the project skeleton." in
Arg.(value & opt (some string) None & info [ "synopsis" ] ~doc)
let maintainer_fullname =
let doc =
"Maintainer's full name. If not specified, Oskel will attempt to read this \
from `git config user.name`."
in
let env = Arg.env_var "FULL_NAME" in
Arg.(value & opt (some string) None & info [ "full-name" ] ~doc ~env)
let maintainer_email =
let doc =
"Maintainer's contact email. If not specified, Oskel will attempt to read \
this from `git config user.email`."
in
let env = Arg.env_var "EMAIL" in
Arg.(value & opt (some string) None & info [ "email" ] ~doc ~env)
let github_organisation =
let doc = "GitHub organisation associated with the project." in
let env = Arg.env_var "GITHUB_ORG" in
Arg.(value & opt (some string) None & info [ "github-org" ] ~doc ~env)
let initial_version =
let doc = "Initial version at which to release the project." in
let env = Arg.env_var "INITIAL_VERSION" in
Arg.(value & opt (some string) None & info [ "initial-version" ] ~doc ~env)
let working_dir =
let doc =
"Run as if Oskel was started in <path> instead of the current working \
directory."
in
Arg.(value & opt (some string) None & info [ "working-dir" ] ~doc)
let assume_yes =
let doc = "Respond `yes' to all prompts and accept all defaults." in
Arg.(value & flag & info [ "yes"; "assume-yes" ] ~doc)
let license =
let licenses = Oskel.License.all in
let doc =
Fmt.str "License to add to the project. One of %s."
(Arg.doc_alts_enum licenses)
in
let env = Arg.env_var "LICENSE" in
Arg.(
value & opt (enum licenses) Oskel.License.Mit & info [ "license" ] ~doc ~env)
let dependencies =
let doc = "Dependencies of the project in a comma-separated list." in
let env = Arg.env_var "DEPENDS" in
Arg.(
value
& opt (list ~sep:',' string) [ "fmt"; "logs" ]
& info [ "depends" ] ~doc ~env)
let version_dune =
let doc = "Version of dune to associate with the project." in
let env = Arg.env_var "VERSION_DUNE" in
Arg.(value & opt (some string) None & info [ "version-dune" ] ~doc ~env)
|> fmap (fun x -> `Dune x)
let version_ocaml =
let doc = "Version of OCaml to associate with the project." in
let env = Arg.env_var "VERSION_OCAML" in
Arg.(value & opt (some string) None & info [ "version-ocaml" ] ~doc ~env)
|> fmap (fun x -> `OCaml x)
let version_opam =
let doc =
Fmt.strf
"Version of opam to associate with the project. The default value is \
`%s`."
Oskel.Opam.default_opam_version
in
let env = Arg.env_var "VERSION_OPAM" in
Arg.(value & opt (some string) None & info [ "version-opam" ] ~doc ~env)
|> fmap (fun x -> `Opam x)
let version_ocamlformat =
let doc = "Version of OCamlformat to associate with the project." in
let env = Arg.env_var "VERSION_OCAMLFORMAT" in
Arg.(
value & opt (some string) None & info [ "version-ocamlformat" ] ~doc ~env)
|> fmap (fun x -> `OCamlformat x)
let versions =
Term.(
const Oskel.Opam.get_versions
$ version_dune
$ version_ocaml
$ version_opam
$ version_ocamlformat)
let ocamlformat_options =
let doc =
"Options to add to the .ocamlformat file, as a comma-separated list of \
key-value pairs. (e.g. \
\"parse-docstrings=true,break-infix=fit-or-vertical\")"
in
let env = Arg.env_var "OCAMLFORMAT_OPTIONS" in
Arg.(
value
& opt (list ~sep:',' (pair ~sep:'=' string string)) []
& info [ "ocamlformat-options" ] ~doc ~env)
let dry_run =
let doc = "Simulate the command, but don't actually perform any changes." in
Arg.(value & flag & info [ "dry-run" ] ~doc)
let non_interactive =
let doc = "Do not show interactive prompts." in
Arg.(value & flag & info [ "non-interactive" ] ~doc)
let git_repo =
let doc = "Don't generate a git repository for the project." in
let env = Arg.env_var "DISABLE_GIT" in
Term.(pure not $ Arg.(value & flag & info [ "disable-git" ] ~doc ~env))
let current_year =
let doc =
"Set the current year. Useful for achieving deterministic output."
in
let env = Arg.env_var "CURRENT_YEAR" in
Arg.(value & opt (some int) None & info [ "current-year" ] ~env ~doc)
let setup_log =
let init style_renderer level =
Fmt_tty.setup_std_outputs ?style_renderer ();
Logs.set_level level;
Logs.set_reporter (Logs_fmt.reporter ())
in
Term.(const init $ Fmt_cli.style_renderer () $ Logs_cli.level ())
let term =
let doc = "Generate skeleton OCaml projects." in
let exits = Term.default_exits in
let man = [] in
Term.
( const run
$ project_name
$ project_kind
$ project_synopsis
$ maintainer_fullname
$ maintainer_email
$ github_organisation
$ initial_version
$ working_dir
$ assume_yes
$ license
$ dependencies
$ versions
$ ocamlformat_options
$ dry_run
$ non_interactive
$ git_repo
$ current_year
$ setup_log,
info "oskel" ~version:"%%VERSION%%" ~doc ~exits ~man )
let () = Term.exit (Term.eval term)
| null | https://raw.githubusercontent.com/craigfe/oskel/057129faaf8171ff4ed49022346e9179b04735b2/bin/main.ml | ocaml | let ( >>| ) x f = Lwt.map f x
let git_user_name () =
Oskel.Utils.Utils_unix.exec "git config user.name"
>>| function
| Ok [ name ] -> if String.(equal (trim name) "") then None else Some name
| Ok o ->
Oskel.show_errorf "Unexpected output from `git config`: %a"
Fmt.Dump.(list string)
o
| Error _ -> None
let git_email () =
Oskel.Utils.Utils_unix.exec "git config user.email"
>>| function
| Ok [ email ] -> if String.(equal (trim email) "") then None else Some email
| Ok o ->
Oskel.show_errorf "Unexpected output from `git config`: %a"
Fmt.Dump.(list string)
o
| Error _ -> None
let ( >>? ) x f = match x with Some s -> Lwt.return (Some s) | None -> f ()
let run name project_kind project_synopsis maintainer_fullname maintainer_email
github_organisation initial_version working_dir assume_yes license
dependencies versions ocamlformat_options dry_run non_interactive git_repo
current_year () : unit =
let maintainer_fullname = maintainer_fullname >>? git_user_name in
let maintainer_email = maintainer_email >>? git_email in
Oskel.run ?name ~project_kind ?project_synopsis ~maintainer_fullname
~maintainer_email ?github_organisation ?initial_version ?working_dir
~assume_yes ~license ~dependencies ~versions ~ocamlformat_options ~dry_run
~non_interactive ~git_repo ?current_year ()
open Cmdliner
let fmap f x = Term.(app (const f) x)
module Arg = struct
include Arg
let env_var s = env_var ("OSKEL_" ^ s)
end
let project_name = Arg.(value & pos 0 (some string) None & info ~docv:"NAME" [])
let project_kind =
let kinds =
[ ("library", `Library); ("binary", `Binary); ("executable", `Executable) ]
in
let doc =
Fmt.str "Type of project to create. One of %s." (Arg.doc_alts_enum kinds)
in
let env = Arg.env_var "KIND" in
Arg.(value & opt (enum kinds) `Library & info [ "kind" ] ~doc ~env)
let project_synopsis =
let doc = "Synopsis of the project skeleton." in
Arg.(value & opt (some string) None & info [ "synopsis" ] ~doc)
let maintainer_fullname =
let doc =
"Maintainer's full name. If not specified, Oskel will attempt to read this \
from `git config user.name`."
in
let env = Arg.env_var "FULL_NAME" in
Arg.(value & opt (some string) None & info [ "full-name" ] ~doc ~env)
let maintainer_email =
let doc =
"Maintainer's contact email. If not specified, Oskel will attempt to read \
this from `git config user.email`."
in
let env = Arg.env_var "EMAIL" in
Arg.(value & opt (some string) None & info [ "email" ] ~doc ~env)
let github_organisation =
let doc = "GitHub organisation associated with the project." in
let env = Arg.env_var "GITHUB_ORG" in
Arg.(value & opt (some string) None & info [ "github-org" ] ~doc ~env)
let initial_version =
let doc = "Initial version at which to release the project." in
let env = Arg.env_var "INITIAL_VERSION" in
Arg.(value & opt (some string) None & info [ "initial-version" ] ~doc ~env)
let working_dir =
let doc =
"Run as if Oskel was started in <path> instead of the current working \
directory."
in
Arg.(value & opt (some string) None & info [ "working-dir" ] ~doc)
let assume_yes =
let doc = "Respond `yes' to all prompts and accept all defaults." in
Arg.(value & flag & info [ "yes"; "assume-yes" ] ~doc)
let license =
let licenses = Oskel.License.all in
let doc =
Fmt.str "License to add to the project. One of %s."
(Arg.doc_alts_enum licenses)
in
let env = Arg.env_var "LICENSE" in
Arg.(
value & opt (enum licenses) Oskel.License.Mit & info [ "license" ] ~doc ~env)
let dependencies =
let doc = "Dependencies of the project in a comma-separated list." in
let env = Arg.env_var "DEPENDS" in
Arg.(
value
& opt (list ~sep:',' string) [ "fmt"; "logs" ]
& info [ "depends" ] ~doc ~env)
let version_dune =
let doc = "Version of dune to associate with the project." in
let env = Arg.env_var "VERSION_DUNE" in
Arg.(value & opt (some string) None & info [ "version-dune" ] ~doc ~env)
|> fmap (fun x -> `Dune x)
let version_ocaml =
let doc = "Version of OCaml to associate with the project." in
let env = Arg.env_var "VERSION_OCAML" in
Arg.(value & opt (some string) None & info [ "version-ocaml" ] ~doc ~env)
|> fmap (fun x -> `OCaml x)
let version_opam =
let doc =
Fmt.strf
"Version of opam to associate with the project. The default value is \
`%s`."
Oskel.Opam.default_opam_version
in
let env = Arg.env_var "VERSION_OPAM" in
Arg.(value & opt (some string) None & info [ "version-opam" ] ~doc ~env)
|> fmap (fun x -> `Opam x)
let version_ocamlformat =
let doc = "Version of OCamlformat to associate with the project." in
let env = Arg.env_var "VERSION_OCAMLFORMAT" in
Arg.(
value & opt (some string) None & info [ "version-ocamlformat" ] ~doc ~env)
|> fmap (fun x -> `OCamlformat x)
let versions =
Term.(
const Oskel.Opam.get_versions
$ version_dune
$ version_ocaml
$ version_opam
$ version_ocamlformat)
let ocamlformat_options =
let doc =
"Options to add to the .ocamlformat file, as a comma-separated list of \
key-value pairs. (e.g. \
\"parse-docstrings=true,break-infix=fit-or-vertical\")"
in
let env = Arg.env_var "OCAMLFORMAT_OPTIONS" in
Arg.(
value
& opt (list ~sep:',' (pair ~sep:'=' string string)) []
& info [ "ocamlformat-options" ] ~doc ~env)
let dry_run =
let doc = "Simulate the command, but don't actually perform any changes." in
Arg.(value & flag & info [ "dry-run" ] ~doc)
let non_interactive =
let doc = "Do not show interactive prompts." in
Arg.(value & flag & info [ "non-interactive" ] ~doc)
let git_repo =
let doc = "Don't generate a git repository for the project." in
let env = Arg.env_var "DISABLE_GIT" in
Term.(pure not $ Arg.(value & flag & info [ "disable-git" ] ~doc ~env))
let current_year =
let doc =
"Set the current year. Useful for achieving deterministic output."
in
let env = Arg.env_var "CURRENT_YEAR" in
Arg.(value & opt (some int) None & info [ "current-year" ] ~env ~doc)
let setup_log =
let init style_renderer level =
Fmt_tty.setup_std_outputs ?style_renderer ();
Logs.set_level level;
Logs.set_reporter (Logs_fmt.reporter ())
in
Term.(const init $ Fmt_cli.style_renderer () $ Logs_cli.level ())
let term =
let doc = "Generate skeleton OCaml projects." in
let exits = Term.default_exits in
let man = [] in
Term.
( const run
$ project_name
$ project_kind
$ project_synopsis
$ maintainer_fullname
$ maintainer_email
$ github_organisation
$ initial_version
$ working_dir
$ assume_yes
$ license
$ dependencies
$ versions
$ ocamlformat_options
$ dry_run
$ non_interactive
$ git_repo
$ current_year
$ setup_log,
info "oskel" ~version:"%%VERSION%%" ~doc ~exits ~man )
let () = Term.exit (Term.eval term)
| |
b2d1f4c93a70225b5a75c63d524daa08fda83717e77dd6abfecfd0923eb1fcba | clojurians-org/haskell-example | DataSandbox.hs | module Frontend.Page.DataSandbox (module X) where
import Frontend.Page.DataSandbox.DataSource.SQLCursor as X
import Frontend.Page.DataSandbox.DataService.FileService.SFTP as X
| null | https://raw.githubusercontent.com/clojurians-org/haskell-example/c96b021bdef52a121e04ea203c8c3e458770a25a/conduit-ui/frontend/src/Frontend/Page/DataSandbox.hs | haskell | module Frontend.Page.DataSandbox (module X) where
import Frontend.Page.DataSandbox.DataSource.SQLCursor as X
import Frontend.Page.DataSandbox.DataService.FileService.SFTP as X
| |
5ff53938f625977cdc9b476f24d01ba6fb6442c3016f9b69d58a2ea193a6de23 | ejgallego/coq-serapi | ser_cooking.ml | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * INRIA , CNRS and contributors - Copyright 1999 - 2018
(* <O___,, * (see CREDITS file for the list of authors) *)
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
(************************************************************************)
(* Coq serialization API/Plugin *)
Copyright 2016 - 2019 MINES ParisTech
Written by :
(************************************************************************)
(* Status: Very Experimental *)
(************************************************************************)
open Sexplib.Std
open Ppx_hash_lib.Std.Hash.Builtin
open Ppx_compare_lib.Builtin
module Names = Ser_names
module Univ = Ser_univ
module Constr = Ser_constr
type abstr_info = {
abstr_ctx : Constr.named_context;
abstr_auctx : Univ.AbstractContext.t;
abstr_ausubst : Univ.Instance.t;
} [@@deriving sexp,yojson,hash,compare]
type abstr_inst_info = {
abstr_rev_inst : Names.Id.t list;
abstr_uinst : Univ.Instance.t;
} [@@deriving sexp,yojson,hash,compare]
type 'a entry_map = 'a Names.Cmap.t * 'a Names.Mindmap.t [@@deriving sexp,yojson,hash,compare]
type expand_info = abstr_inst_info entry_map [@@deriving sexp,yojson,hash,compare]
module CIP = struct
type _t = {
expand_info : expand_info;
abstr_info : abstr_info;
} [@@deriving sexp,yojson,hash,compare]
type t =
[%import: Cooking.cooking_info]
end
module B_ = SerType.Pierce(CIP)
type cooking_info = B_.t
[@@deriving sexp,yojson,hash,compare]
| null | https://raw.githubusercontent.com/ejgallego/coq-serapi/dd9e3fbf7faaf3bf365fa3eff134641055151a9b/serlib/ser_cooking.ml | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
<O___,, * (see CREDITS file for the list of authors)
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
**********************************************************************
Coq serialization API/Plugin
**********************************************************************
Status: Very Experimental
********************************************************************** | v * INRIA , CNRS and contributors - Copyright 1999 - 2018
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
Copyright 2016 - 2019 MINES ParisTech
Written by :
open Sexplib.Std
open Ppx_hash_lib.Std.Hash.Builtin
open Ppx_compare_lib.Builtin
module Names = Ser_names
module Univ = Ser_univ
module Constr = Ser_constr
type abstr_info = {
abstr_ctx : Constr.named_context;
abstr_auctx : Univ.AbstractContext.t;
abstr_ausubst : Univ.Instance.t;
} [@@deriving sexp,yojson,hash,compare]
type abstr_inst_info = {
abstr_rev_inst : Names.Id.t list;
abstr_uinst : Univ.Instance.t;
} [@@deriving sexp,yojson,hash,compare]
type 'a entry_map = 'a Names.Cmap.t * 'a Names.Mindmap.t [@@deriving sexp,yojson,hash,compare]
type expand_info = abstr_inst_info entry_map [@@deriving sexp,yojson,hash,compare]
module CIP = struct
type _t = {
expand_info : expand_info;
abstr_info : abstr_info;
} [@@deriving sexp,yojson,hash,compare]
type t =
[%import: Cooking.cooking_info]
end
module B_ = SerType.Pierce(CIP)
type cooking_info = B_.t
[@@deriving sexp,yojson,hash,compare]
|
f45b5160f49be773d389ed561c5d52262d174bcdd136fd0485150e59257f9ccd | cljfx/cljfx | custom_menu_item.clj | (ns cljfx.fx.custom-menu-item
"Part of a public API"
(:require [cljfx.composite :as composite]
[cljfx.lifecycle :as lifecycle]
[cljfx.fx.menu-item :as fx.menu-item]
[cljfx.coerce :as coerce])
(:import [javafx.scene.control CustomMenuItem]))
(set! *warn-on-reflection* true)
(def props
(merge
fx.menu-item/props
(composite/props CustomMenuItem
;; overrides
:style-class [:list lifecycle/scalar :coerce coerce/style-class
:default ["custom-menu-item" "menu-item"]]
;; definitions
:content [:setter lifecycle/dynamic]
:hide-on-click [:setter lifecycle/scalar :default true])))
(def lifecycle
(lifecycle/annotate
(composite/describe CustomMenuItem
:ctor []
:props props)
:custom-menu-item))
| null | https://raw.githubusercontent.com/cljfx/cljfx/543f7409290051e9444771d2cd86dadeb8cdce33/src/cljfx/fx/custom_menu_item.clj | clojure | overrides
definitions | (ns cljfx.fx.custom-menu-item
"Part of a public API"
(:require [cljfx.composite :as composite]
[cljfx.lifecycle :as lifecycle]
[cljfx.fx.menu-item :as fx.menu-item]
[cljfx.coerce :as coerce])
(:import [javafx.scene.control CustomMenuItem]))
(set! *warn-on-reflection* true)
(def props
(merge
fx.menu-item/props
(composite/props CustomMenuItem
:style-class [:list lifecycle/scalar :coerce coerce/style-class
:default ["custom-menu-item" "menu-item"]]
:content [:setter lifecycle/dynamic]
:hide-on-click [:setter lifecycle/scalar :default true])))
(def lifecycle
(lifecycle/annotate
(composite/describe CustomMenuItem
:ctor []
:props props)
:custom-menu-item))
|
2280469ab8d77d477871f1a6c473aca0fc0d3326df10b5a88c5986b3a1143af3 | glutamate/bugpan | Format2.hs | # LANGUAGE GeneralizedNewtypeDeriving #
module Format2 where
import EvalM
import Data.Binary
import Data.Binary.Get
import qualified Data.ByteString.Lazy as L
import Numbers
--import Array
import Control.Monad
import TNUtils
import Debug.Trace
import Unsafe.Coerce
import Data.Array.IO
import System.IO
import Data.Array.MArray
import qualified Data.StorableVector as SV
import Foreign.C.Types
import ValueIO
typeTag :: T -> [Word8]
typeTag BoolT = [1]
typeTag (NumT (Just IntT)) = [2]
typeTag (NumT (Just RealT)) = [3]
typeTag (NumT (Just CmplxT)) = [4]
typeTag UnitT = [5]
typeTag (PairT t1 t2) = [6] -- ++ typeTag t1 ++ typeTag t2
typeTag (ListT t) = [7] -- ++ typeTag t
typeTag (SignalT t) = [8]
typeTag (StringT) = [9]
putTT :: V -> Put
putTT v = mapM_ putWord8 . typeTag . typeOfVal $ v
data OV = OBoolV Bool
| ONumV ONumVl
| OPairV OV OV
| OListV [OV]
| OLamV (OV->EvalM OV)
| OSigV Double Double Double (Int->OV)
shape , loc , colour
| OUnit
| OStringV String
deriving (Show, Read)
data ONumVl = OldInt Int
| OldReal Double
deriving (Show, Read)
oldVtoV (OBoolV b) = BoolV b
oldVtoV (ONumV (OldInt i))= NumV $ NInt i
oldVtoV (ONumV (OldReal i))= NumV . NReal $ i
oldVtoV (OPairV p1 p2) = PairV (oldVtoV p1) (oldVtoV p2)
oldVtoV (OListV vs) = ListV (map oldVtoV vs)
oldVtoV (OUnit) = Unit
oldVtoV (OSigV t1 t2 dt sf) = SigV ( t1) ( t2) ( dt) (oldVtoV . sf)
oldVtoV (OStringV s ) = StringV s
instance Binary OV where
put = undefined
get = getFull
putFull v@(BoolV b) = putTT v >> put b
putFull v@(NumV (NInt i)) = putTT v >>put i
putFull v@(NumV (NReal r)) = putTT v >>put r
putFull v@(PairV v1 w1) = putTT v >> putFull v1 >> putFull w1
putFull v@(ListV xs) = putTT v >> put (length xs) >> mapM_ putFull xs
putFull v@(SigV t1 t2 dt sf) = do putTT v
put t1
put t2
put dt
mapM_ (\t->putFull $ sf t) [0..round $ (t2-t1)/dt]
putFull Unit = putTT Unit
putFull v@(StringV s) = putTT v >> put s
getFull = do tt1 <- get
case idWord8 tt1 of
1 -> OBoolV `fmap` get
2 -> (ONumV . OldInt) `fmap` get
3 -> (ONumV . OldReal) `fmap` get
5 -> do () <- get
return OUnit
6 -> do p1 <- getFull
p2 <- getFull
return $ OPairV p1 p2
7 -> do n <- idInt `fmap` get
--vls <- get
vls <- forM [0..n-1] $ const getFull
return $ OListV vls
8 - > do t1 < - get
t2 < - get
dt < - get
vls < - forM [ t1,t1+dt .. t2 ] $ const getFull
let arr = listArray ( 0 , length vls -1 ) vls
return . OSigV t1 t2 dt $ \pt->arr!pt
t2 <- get
dt <- get
vls <- forM [t1,t1+dt..t2] $ const getFull
let arr = listArray (0, length vls -1) vls
return . OSigV t1 t2 dt $ \pt->arr!pt -}
9 -> OStringV `fmap` get
tt -> error $ "unknown type tag: "++show tt
where idWord8 :: Word8 -> Word8
idWord8 = id
getMany :: Binary a => Int -> Get [a]
getMany n = go [] n
where
go xs 0 = return $! reverse xs
go xs i = do x <- get
-- we must seq x to avoid stack overflows due to laziness in
-- (>>=)
x `seq` go (x:xs) (i-1)
# INLINE getMany #
--- SPECIALIZE getMany :: Int -> Get [RealNum] -}
| null | https://raw.githubusercontent.com/glutamate/bugpan/d0983152f5afce306049262cba296df00e52264b/Format2.hs | haskell | import Array
++ typeTag t1 ++ typeTag t2
++ typeTag t
vls <- get
we must seq x to avoid stack overflows due to laziness in
(>>=)
- SPECIALIZE getMany :: Int -> Get [RealNum] -} | # LANGUAGE GeneralizedNewtypeDeriving #
module Format2 where
import EvalM
import Data.Binary
import Data.Binary.Get
import qualified Data.ByteString.Lazy as L
import Numbers
import Control.Monad
import TNUtils
import Debug.Trace
import Unsafe.Coerce
import Data.Array.IO
import System.IO
import Data.Array.MArray
import qualified Data.StorableVector as SV
import Foreign.C.Types
import ValueIO
typeTag :: T -> [Word8]
typeTag BoolT = [1]
typeTag (NumT (Just IntT)) = [2]
typeTag (NumT (Just RealT)) = [3]
typeTag (NumT (Just CmplxT)) = [4]
typeTag UnitT = [5]
typeTag (SignalT t) = [8]
typeTag (StringT) = [9]
putTT :: V -> Put
putTT v = mapM_ putWord8 . typeTag . typeOfVal $ v
data OV = OBoolV Bool
| ONumV ONumVl
| OPairV OV OV
| OListV [OV]
| OLamV (OV->EvalM OV)
| OSigV Double Double Double (Int->OV)
shape , loc , colour
| OUnit
| OStringV String
deriving (Show, Read)
data ONumVl = OldInt Int
| OldReal Double
deriving (Show, Read)
oldVtoV (OBoolV b) = BoolV b
oldVtoV (ONumV (OldInt i))= NumV $ NInt i
oldVtoV (ONumV (OldReal i))= NumV . NReal $ i
oldVtoV (OPairV p1 p2) = PairV (oldVtoV p1) (oldVtoV p2)
oldVtoV (OListV vs) = ListV (map oldVtoV vs)
oldVtoV (OUnit) = Unit
oldVtoV (OSigV t1 t2 dt sf) = SigV ( t1) ( t2) ( dt) (oldVtoV . sf)
oldVtoV (OStringV s ) = StringV s
instance Binary OV where
put = undefined
get = getFull
putFull v@(BoolV b) = putTT v >> put b
putFull v@(NumV (NInt i)) = putTT v >>put i
putFull v@(NumV (NReal r)) = putTT v >>put r
putFull v@(PairV v1 w1) = putTT v >> putFull v1 >> putFull w1
putFull v@(ListV xs) = putTT v >> put (length xs) >> mapM_ putFull xs
putFull v@(SigV t1 t2 dt sf) = do putTT v
put t1
put t2
put dt
mapM_ (\t->putFull $ sf t) [0..round $ (t2-t1)/dt]
putFull Unit = putTT Unit
putFull v@(StringV s) = putTT v >> put s
getFull = do tt1 <- get
case idWord8 tt1 of
1 -> OBoolV `fmap` get
2 -> (ONumV . OldInt) `fmap` get
3 -> (ONumV . OldReal) `fmap` get
5 -> do () <- get
return OUnit
6 -> do p1 <- getFull
p2 <- getFull
return $ OPairV p1 p2
7 -> do n <- idInt `fmap` get
vls <- forM [0..n-1] $ const getFull
return $ OListV vls
8 - > do t1 < - get
t2 < - get
dt < - get
vls < - forM [ t1,t1+dt .. t2 ] $ const getFull
let arr = listArray ( 0 , length vls -1 ) vls
return . OSigV t1 t2 dt $ \pt->arr!pt
t2 <- get
dt <- get
vls <- forM [t1,t1+dt..t2] $ const getFull
let arr = listArray (0, length vls -1) vls
return . OSigV t1 t2 dt $ \pt->arr!pt -}
9 -> OStringV `fmap` get
tt -> error $ "unknown type tag: "++show tt
where idWord8 :: Word8 -> Word8
idWord8 = id
getMany :: Binary a => Int -> Get [a]
getMany n = go [] n
where
go xs 0 = return $! reverse xs
go xs i = do x <- get
x `seq` go (x:xs) (i-1)
# INLINE getMany #
|
f3b4a9de489fe020f9982c10de5afaf0ec391500b7cfb93eed0c95fd0e4ec97f | JKTKops/cspim | Expr.hs | # LANGUAGE ExistentialQuantification #
module Parser.Expr
( Expr(..)
, parseExpr
, parseRValue
, gatherExpToRValue
) where
import Pretty
import TAC.Pretty
import Text.Parsec.Expr hiding (Operator)
import qualified Text.Parsec.Expr as Parsec
import Text.Parsec as TP hiding ((<|>), (<?>))
import Data.Text (pack, Text)
import Parser.Monad
import Compiler.Monad
import Compiler.SymbolTable
import TAC.Program
import Data.Function (on)
import Control.Monad (join, when, unless)
import Control.Monad.Debug
data Expr = Expr
{ exprGraph :: Graph Insn O O
, exprResult :: TacExp
, exprResultTy :: Type
}
| ParsedExpr actions should /not/ do any parsing . They should be used for the
underlying CSpim parser actions , like ' mkFreshLocalTempUniq ' or ' fail ' .
The correct way to solve this problem would be to copy the code for Parsec 's
-- buildExpressionParser, and allow monadic operator functions.
type ParsedExpr = Parser Expr
type Operator = Parsec.Operator Text ParserState Compiler ParsedExpr
type TermParser a = ParsecT Text ParserState Compiler a
parseExpr :: Parser Expr
parseExpr = join (P $ buildExpressionParser opTableAboveTernary under) <?> "expression"
where under = pure <$> unP parseExprBelowTernary
parseExprAsRvalue :: Parser (Graph Insn O O, RValue, Type)
parseExprAsRvalue = do
Expr g res ty <- parseExpr
(g', rv) <- gather res ty
return (g <*|*> g', rv, ty)
parseExprBelowTernary :: Parser Expr
parseExprBelowTernary = join $ P $ buildExpressionParser opTableBelowTernary term
term :: TermParser ParsedExpr
term = do
rv <- unP parseRValue
expr <- case rv of
RVar (Left uniq) -> identifierTerm uniq
RVar (Right constant) -> constantTerm constant
pure $ return expr
pure $ return emptyGraph ( ValExp rv ) $ IntTy Unsigned -- TODO : correct this type
identifierTerm :: Unique -> TermParser Expr
identifierTerm uniq = do
mArgs <- TP.optionMaybe $ tpParens $ unP parseExprAsRvalue `TP.sepBy` unP comma
case mArgs of
Nothing -> staticIdTerm uniq
Just args -> funIdTerm uniq args
staticIdTerm :: Unique -> TermParser Expr
staticIdTerm uniq = do
symTab <- _symTab <$> getState
let Just ty = lookupVarType symTab uniq
when (isFunTy ty) $ fail "CSpim doesn't support function pointers."
return $ Expr emptyGraph (ValExp $ RVar $ Left uniq) ty
newtype ArgMonoid = AM { getAM :: (Graph Insn O O, [RValue]) }
instance Semigroup ArgMonoid where
AM (g1, rvs1) <> AM (g2, rvs2) = AM (g1 <*|*> g2, rvs1 <> rvs2)
instance Monoid ArgMonoid where mempty = AM (emptyGraph, [])
funIdTerm :: Unique -> [(Graph Insn O O, RValue, Type)] -> TermParser Expr
funIdTerm uniq args = do
symTab <- _symTab <$> getState
let Just ty = lookupVarType symTab uniq
Just funName = lookupVarName symTab uniq
actArgTypes = map thd args
unless (isFunTy ty) $ fail $ "Cannot call non-function `" <> funName <> "'"
let FunTy retTy formalArgTypes = ty
when (((/=) `on` length) formalArgTypes actArgTypes) $ unP $ customParseError
$ FunctionCallBadlyTyped (pack funName) formalArgTypes actArgTypes
resultTemp <- unP $ mkFreshLocalTempUniq retTy
returnLabel <- unP freshLabel
let (argGraph, rvs) = getAM $ foldMap (\(g, r, _) -> AM (g, [r])) args
callInst = Call uniq rvs returnLabel
retInst = Retrieve resultTemp
graph = argGraph <*|*> mkLast callInst
|*><*| mkLabel returnLabel
<*|*> mkMiddle retInst
return $ Expr graph (ValExp $ RVar $ Left resultTemp) retTy
where thd (_, _, c) = c
constantTerm :: Constant -> TermParser Expr
constantTerm c = return $ Expr emptyGraph (ValExp $ RVar $ Right c) $ IntTy Unsigned
parseRValue :: Parser RValue
parseRValue = RVar <$> ((Left <$> (identifier >>= uniqueOf)) <|> (Right . IntConst <$> natural))
opTableAboveTernary :: [[Operator]]
opTableAboveTernary = [p14, p15]
where p15 = []
p14 = [ assignOp, addAssign, subAssign, timesAssign
, divAssign, remAssign, shiftlAssign, shiftrAssign]
opTableBelowTernary :: [[Operator]]
opTableBelowTernary = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12]
where p1 = []
p2 = []
p3 = [timesOp, divOp, remOp]
p4 = [addOp, subOp]
p5 = [lshiftOp, rshiftOp]
p6 = [ltOp, leqOp, gtOp, geqOp]
p7 = [eqOp, neOp]
p8 = []
p9 = []
p10 = []
p11 = []
p12 = []
timesOp, divOp, remOp :: Operator
timesOp = binary "*" Mul AssocLeft
divOp = binary "/" Div AssocLeft
remOp = binary "%" Rem AssocLeft
addOp, subOp :: Operator
addOp = binary "+" Add AssocLeft
subOp = binary "-" Sub AssocLeft
lshiftOp, rshiftOp :: Operator
lshiftOp = binary "<<" ShiftL AssocLeft
rshiftOp = binary ">>" ShiftR AssocLeft
ltOp, leqOp, gtOp, geqOp :: Operator
ltOp = binary "<" Lt AssocLeft
leqOp = binary "<=" Le AssocLeft
gtOp = binary ">" Gt AssocLeft
geqOp = binary ">=" Ge AssocLeft
eqOp, neOp :: Operator
eqOp = binary "==" Eq AssocLeft
neOp = binary "!=" Ne AssocLeft
assignOp, addAssign, subAssign, timesAssign :: Operator
divAssign, remAssign, shiftlAssign, shiftrAssign :: Operator
assignOp = assign "=" Nothing
addAssign = assign "+=" (Just Add)
subAssign = assign "-=" (Just Sub)
timesAssign = assign "*=" (Just Mul)
divAssign = assign "/=" (Just Div)
remAssign = assign "%=" (Just Rem)
shiftlAssign = assign "<<=" (Just ShiftL)
shiftrAssign = assign ">>=" (Just ShiftR)
binary :: String -> Binop -> Assoc -> Operator
binary name op = Infix parse
where
parse :: ParsecT Text ParserState Compiler (ParsedExpr -> ParsedExpr -> ParsedExpr)
parse = unP $ reservedOp name >> connectBinop op
assign :: String -> Maybe Binop -> Operator
assign name op = Infix parse AssocRight
where parse = unP $ reservedOp name >> connectAssign op
connectBinop :: Binop -> Parser (ParsedExpr -> ParsedExpr -> ParsedExpr)
connectBinop op = pure $ \e1 e2 -> do
Expr lg lr lty <- e1
Expr rg rr rty <- e2
outTy <- commonRealType lty rty
(gatherLeft, leftValue) <- gather lr lty
(gatherRight, rightValue) <- gather rr rty
return $ Expr (lg <*|*> gatherLeft <*|*> rg <*|*> gatherRight)
(Binop leftValue op rightValue)
outTy
connectAssign :: Maybe Binop -> Parser (ParsedExpr -> ParsedExpr -> ParsedExpr)
connectAssign mop = pure $ \e1 e2 -> do
Expr lg lr lty <- e1
case lr of
ValExp _ -> pure ()
_ -> do notLValue <- prettyTacExp lr
fail $ notLValue ++ " is not an lvalue"
Expr rg rr rty <- e2
let outTy = lty
(gatherLeft, leftValue) <- gather lr lty
(gatherRight, rightValue) <- gather rr rty
lvalue <- lvalueOfRValue leftValue
let rhs = case mop of
Nothing -> ValExp rightValue
Just op -> Binop leftValue op rightValue
return $ Expr (rg <*|*> gatherRight -- right-to-left to match gcc
<*|*> lg
<*|*> gatherLeft
<*|*> mkMiddle (lvalue := rhs))
(ValExp leftValue)
outTy
where
lvalueOfRValue :: RValue -> Parser LValue
lvalueOfRValue (RVar (Left v)) = return $ LVar v
lvalueOfRValue (RIxArr n v) = return $ LIxArr n v
lvalueOfRValue r@(RVar (Right _)) = do
notLValue <- prettyRValue r
fail $ notLValue <> " is not an lvalue"
gather :: TacExp -> Type -> Parser (Graph Insn O O, RValue)
gather (ValExp rv) _ = return (emptyGraph, rv)
gather exp ty = do
temp <- mkFreshLocalTempUniq ty
return (mkMiddle $ LVar temp := exp, RVar (Left temp))
gatherExpToRValue = gather
commonRealType :: Type -> Type -> Parser Type
commonRealType ty1 ty2
| isIntegralTy ty1
, isIntegralTy ty2 = pure $ makeSignageAgree (promote ty1) (promote ty2)
| otherwise = panic "Parser.Expr.commonRealType: Non-integral types"
where promote :: Type -> Type
promote (IntTy Unsigned) = IntTy Unsigned
promote _ = IntTy Signed
makeSignageAgree :: Type -> Type -> Type
makeSignageAgree ty1 ty2
| IntTy Unsigned <- ty1 = IntTy Unsigned
| IntTy Unsigned <- ty2 = IntTy Unsigned
| otherwise = IntTy Signed
--------------------------------------------------------------------------------------
--
-- Alternative to Nested Parser Strategy
--
--------------------------------------------------------------------------------------
in theory , using this stuff , type ParsedExpr = ExprM Expr
instead of type ParseExpr =
would be cleaner and easier to handle ( and probably faster as well ) . The complication
is that ExprM needs to be able to run Parser actions , because while creating an expression ,
we can create new local variables .
in theory, using this stuff, type ParsedExpr = ExprM Expr
instead of type ParseExpr = Parser Expr
would be cleaner and easier to handle (and probably faster as well). The complication
is that ExprM needs to be able to run Parser actions, because while creating an expression,
we can create new local variables.
-}
data ExprError prettyThing
= ExprPanic Text
| ExprFail String
| ExprPrettyFail prettyThing (prettyThing -> Parser String) -- f p >>= fail
exprError :: ExprError p -> Parser a
exprError (ExprPanic t) = panic t
exprError (ExprFail t) = fail t
exprError (ExprPrettyFail p f) = f p >>= fail
data ExprM a = forall p. ExprM (Either (ExprError p) a)
runExprM :: ExprM a -> Parser a
runExprM (ExprM (Right a)) = pure a
runExprM (ExprM (Left e)) = exprError e
exprPanic :: Text -> ExprM a
exprFail :: String -> ExprM a
exprPFail :: p -> (p -> Parser String) -> ExprM a
exprPanic t = ExprM $ Left (ExprPanic t)
exprFail s = ExprM $ Left (ExprFail s)
exprPFail p f = ExprM $ Left (ExprPrettyFail p f)
exprMap f (ExprM expr) = ExprM $ fmap f expr
exprAp :: ExprM (a -> b) -> ExprM a -> ExprM b
exprAp (ExprM (Right f)) (ExprM (Right a)) = ExprM $ Right $ f a
exprAp (ExprM (Right _)) (ExprM (Left l)) = ExprM $ Left l
exprAp (ExprM (Left l)) _ = ExprM $ Left l
exprPure x = ExprM $ Right x
exprBind (ExprM (Right x)) f = f x
exprBind (ExprM (Left l)) _ = ExprM (Left l)
instance Functor ExprM where fmap = exprMap
instance Applicative ExprM where
pure = exprPure
(<*>) = exprAp
instance Monad ExprM where (>>=) = exprBind
| null | https://raw.githubusercontent.com/JKTKops/cspim/0218d88ee774023eecef2c4a0733c3cf1184f443/src/Parser/Expr.hs | haskell | buildExpressionParser, and allow monadic operator functions.
TODO : correct this type
right-to-left to match gcc
------------------------------------------------------------------------------------
Alternative to Nested Parser Strategy
------------------------------------------------------------------------------------
f p >>= fail | # LANGUAGE ExistentialQuantification #
module Parser.Expr
( Expr(..)
, parseExpr
, parseRValue
, gatherExpToRValue
) where
import Pretty
import TAC.Pretty
import Text.Parsec.Expr hiding (Operator)
import qualified Text.Parsec.Expr as Parsec
import Text.Parsec as TP hiding ((<|>), (<?>))
import Data.Text (pack, Text)
import Parser.Monad
import Compiler.Monad
import Compiler.SymbolTable
import TAC.Program
import Data.Function (on)
import Control.Monad (join, when, unless)
import Control.Monad.Debug
data Expr = Expr
{ exprGraph :: Graph Insn O O
, exprResult :: TacExp
, exprResultTy :: Type
}
| ParsedExpr actions should /not/ do any parsing . They should be used for the
underlying CSpim parser actions , like ' mkFreshLocalTempUniq ' or ' fail ' .
The correct way to solve this problem would be to copy the code for Parsec 's
type ParsedExpr = Parser Expr
type Operator = Parsec.Operator Text ParserState Compiler ParsedExpr
type TermParser a = ParsecT Text ParserState Compiler a
parseExpr :: Parser Expr
parseExpr = join (P $ buildExpressionParser opTableAboveTernary under) <?> "expression"
where under = pure <$> unP parseExprBelowTernary
parseExprAsRvalue :: Parser (Graph Insn O O, RValue, Type)
parseExprAsRvalue = do
Expr g res ty <- parseExpr
(g', rv) <- gather res ty
return (g <*|*> g', rv, ty)
parseExprBelowTernary :: Parser Expr
parseExprBelowTernary = join $ P $ buildExpressionParser opTableBelowTernary term
term :: TermParser ParsedExpr
term = do
rv <- unP parseRValue
expr <- case rv of
RVar (Left uniq) -> identifierTerm uniq
RVar (Right constant) -> constantTerm constant
pure $ return expr
identifierTerm :: Unique -> TermParser Expr
identifierTerm uniq = do
mArgs <- TP.optionMaybe $ tpParens $ unP parseExprAsRvalue `TP.sepBy` unP comma
case mArgs of
Nothing -> staticIdTerm uniq
Just args -> funIdTerm uniq args
staticIdTerm :: Unique -> TermParser Expr
staticIdTerm uniq = do
symTab <- _symTab <$> getState
let Just ty = lookupVarType symTab uniq
when (isFunTy ty) $ fail "CSpim doesn't support function pointers."
return $ Expr emptyGraph (ValExp $ RVar $ Left uniq) ty
newtype ArgMonoid = AM { getAM :: (Graph Insn O O, [RValue]) }
instance Semigroup ArgMonoid where
AM (g1, rvs1) <> AM (g2, rvs2) = AM (g1 <*|*> g2, rvs1 <> rvs2)
instance Monoid ArgMonoid where mempty = AM (emptyGraph, [])
funIdTerm :: Unique -> [(Graph Insn O O, RValue, Type)] -> TermParser Expr
funIdTerm uniq args = do
symTab <- _symTab <$> getState
let Just ty = lookupVarType symTab uniq
Just funName = lookupVarName symTab uniq
actArgTypes = map thd args
unless (isFunTy ty) $ fail $ "Cannot call non-function `" <> funName <> "'"
let FunTy retTy formalArgTypes = ty
when (((/=) `on` length) formalArgTypes actArgTypes) $ unP $ customParseError
$ FunctionCallBadlyTyped (pack funName) formalArgTypes actArgTypes
resultTemp <- unP $ mkFreshLocalTempUniq retTy
returnLabel <- unP freshLabel
let (argGraph, rvs) = getAM $ foldMap (\(g, r, _) -> AM (g, [r])) args
callInst = Call uniq rvs returnLabel
retInst = Retrieve resultTemp
graph = argGraph <*|*> mkLast callInst
|*><*| mkLabel returnLabel
<*|*> mkMiddle retInst
return $ Expr graph (ValExp $ RVar $ Left resultTemp) retTy
where thd (_, _, c) = c
constantTerm :: Constant -> TermParser Expr
constantTerm c = return $ Expr emptyGraph (ValExp $ RVar $ Right c) $ IntTy Unsigned
parseRValue :: Parser RValue
parseRValue = RVar <$> ((Left <$> (identifier >>= uniqueOf)) <|> (Right . IntConst <$> natural))
opTableAboveTernary :: [[Operator]]
opTableAboveTernary = [p14, p15]
where p15 = []
p14 = [ assignOp, addAssign, subAssign, timesAssign
, divAssign, remAssign, shiftlAssign, shiftrAssign]
opTableBelowTernary :: [[Operator]]
opTableBelowTernary = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12]
where p1 = []
p2 = []
p3 = [timesOp, divOp, remOp]
p4 = [addOp, subOp]
p5 = [lshiftOp, rshiftOp]
p6 = [ltOp, leqOp, gtOp, geqOp]
p7 = [eqOp, neOp]
p8 = []
p9 = []
p10 = []
p11 = []
p12 = []
timesOp, divOp, remOp :: Operator
timesOp = binary "*" Mul AssocLeft
divOp = binary "/" Div AssocLeft
remOp = binary "%" Rem AssocLeft
addOp, subOp :: Operator
addOp = binary "+" Add AssocLeft
subOp = binary "-" Sub AssocLeft
lshiftOp, rshiftOp :: Operator
lshiftOp = binary "<<" ShiftL AssocLeft
rshiftOp = binary ">>" ShiftR AssocLeft
ltOp, leqOp, gtOp, geqOp :: Operator
ltOp = binary "<" Lt AssocLeft
leqOp = binary "<=" Le AssocLeft
gtOp = binary ">" Gt AssocLeft
geqOp = binary ">=" Ge AssocLeft
eqOp, neOp :: Operator
eqOp = binary "==" Eq AssocLeft
neOp = binary "!=" Ne AssocLeft
assignOp, addAssign, subAssign, timesAssign :: Operator
divAssign, remAssign, shiftlAssign, shiftrAssign :: Operator
assignOp = assign "=" Nothing
addAssign = assign "+=" (Just Add)
subAssign = assign "-=" (Just Sub)
timesAssign = assign "*=" (Just Mul)
divAssign = assign "/=" (Just Div)
remAssign = assign "%=" (Just Rem)
shiftlAssign = assign "<<=" (Just ShiftL)
shiftrAssign = assign ">>=" (Just ShiftR)
binary :: String -> Binop -> Assoc -> Operator
binary name op = Infix parse
where
parse :: ParsecT Text ParserState Compiler (ParsedExpr -> ParsedExpr -> ParsedExpr)
parse = unP $ reservedOp name >> connectBinop op
assign :: String -> Maybe Binop -> Operator
assign name op = Infix parse AssocRight
where parse = unP $ reservedOp name >> connectAssign op
connectBinop :: Binop -> Parser (ParsedExpr -> ParsedExpr -> ParsedExpr)
connectBinop op = pure $ \e1 e2 -> do
Expr lg lr lty <- e1
Expr rg rr rty <- e2
outTy <- commonRealType lty rty
(gatherLeft, leftValue) <- gather lr lty
(gatherRight, rightValue) <- gather rr rty
return $ Expr (lg <*|*> gatherLeft <*|*> rg <*|*> gatherRight)
(Binop leftValue op rightValue)
outTy
connectAssign :: Maybe Binop -> Parser (ParsedExpr -> ParsedExpr -> ParsedExpr)
connectAssign mop = pure $ \e1 e2 -> do
Expr lg lr lty <- e1
case lr of
ValExp _ -> pure ()
_ -> do notLValue <- prettyTacExp lr
fail $ notLValue ++ " is not an lvalue"
Expr rg rr rty <- e2
let outTy = lty
(gatherLeft, leftValue) <- gather lr lty
(gatherRight, rightValue) <- gather rr rty
lvalue <- lvalueOfRValue leftValue
let rhs = case mop of
Nothing -> ValExp rightValue
Just op -> Binop leftValue op rightValue
<*|*> lg
<*|*> gatherLeft
<*|*> mkMiddle (lvalue := rhs))
(ValExp leftValue)
outTy
where
lvalueOfRValue :: RValue -> Parser LValue
lvalueOfRValue (RVar (Left v)) = return $ LVar v
lvalueOfRValue (RIxArr n v) = return $ LIxArr n v
lvalueOfRValue r@(RVar (Right _)) = do
notLValue <- prettyRValue r
fail $ notLValue <> " is not an lvalue"
gather :: TacExp -> Type -> Parser (Graph Insn O O, RValue)
gather (ValExp rv) _ = return (emptyGraph, rv)
gather exp ty = do
temp <- mkFreshLocalTempUniq ty
return (mkMiddle $ LVar temp := exp, RVar (Left temp))
gatherExpToRValue = gather
commonRealType :: Type -> Type -> Parser Type
commonRealType ty1 ty2
| isIntegralTy ty1
, isIntegralTy ty2 = pure $ makeSignageAgree (promote ty1) (promote ty2)
| otherwise = panic "Parser.Expr.commonRealType: Non-integral types"
where promote :: Type -> Type
promote (IntTy Unsigned) = IntTy Unsigned
promote _ = IntTy Signed
makeSignageAgree :: Type -> Type -> Type
makeSignageAgree ty1 ty2
| IntTy Unsigned <- ty1 = IntTy Unsigned
| IntTy Unsigned <- ty2 = IntTy Unsigned
| otherwise = IntTy Signed
in theory , using this stuff , type ParsedExpr = ExprM Expr
instead of type ParseExpr =
would be cleaner and easier to handle ( and probably faster as well ) . The complication
is that ExprM needs to be able to run Parser actions , because while creating an expression ,
we can create new local variables .
in theory, using this stuff, type ParsedExpr = ExprM Expr
instead of type ParseExpr = Parser Expr
would be cleaner and easier to handle (and probably faster as well). The complication
is that ExprM needs to be able to run Parser actions, because while creating an expression,
we can create new local variables.
-}
data ExprError prettyThing
= ExprPanic Text
| ExprFail String
exprError :: ExprError p -> Parser a
exprError (ExprPanic t) = panic t
exprError (ExprFail t) = fail t
exprError (ExprPrettyFail p f) = f p >>= fail
data ExprM a = forall p. ExprM (Either (ExprError p) a)
runExprM :: ExprM a -> Parser a
runExprM (ExprM (Right a)) = pure a
runExprM (ExprM (Left e)) = exprError e
exprPanic :: Text -> ExprM a
exprFail :: String -> ExprM a
exprPFail :: p -> (p -> Parser String) -> ExprM a
exprPanic t = ExprM $ Left (ExprPanic t)
exprFail s = ExprM $ Left (ExprFail s)
exprPFail p f = ExprM $ Left (ExprPrettyFail p f)
exprMap f (ExprM expr) = ExprM $ fmap f expr
exprAp :: ExprM (a -> b) -> ExprM a -> ExprM b
exprAp (ExprM (Right f)) (ExprM (Right a)) = ExprM $ Right $ f a
exprAp (ExprM (Right _)) (ExprM (Left l)) = ExprM $ Left l
exprAp (ExprM (Left l)) _ = ExprM $ Left l
exprPure x = ExprM $ Right x
exprBind (ExprM (Right x)) f = f x
exprBind (ExprM (Left l)) _ = ExprM (Left l)
instance Functor ExprM where fmap = exprMap
instance Applicative ExprM where
pure = exprPure
(<*>) = exprAp
instance Monad ExprM where (>>=) = exprBind
|
89b4667f7786ff039acfe917a4e9675f9e4f8e501fc1ce3622dfd692029a849c | joinr/clclojure | recurtest.lisp | (defpackage common-utils.recurtest
(:use :common-lisp :common-utils))
(in-package :common-utils.recurtest)
;;can we implement (recur ...) ?
;; (block some-name
;; (tagbody some-point
:
;; (when :recur
( progn ( update - vars )
;; (go some-point))
;; )
;; )
;; result)
;; (defun custom-loop (x)
;; (let ((res))
( ( ( recur ( )
` ( progn ( setf , ' x , )
;; (pprint ,'x)
;; (go ,'recur-from))))
;; (tagbody recur-from
( setf res
( if (= x 10 )
;; x
;; (recur (1+ x)))))
;; res)))
( defmacro with - recur ( args & rest body )
( let * ( ( recur - sym ( intern " RECUR " ) ) ; HAVE TO CAPITALIZE !
;; (local-args (mapcar (lambda (x)
;; (intern (symbol-name x))) args))
( res ( " res " ) )
( recur - from ( gentemp " recur - from " ) )
( recur - args ( mapcar ( lambda ( x ) ( ( symbol - name x ) ) ) local - args
;; ))
;; (bindings (mapcar (lambda (xy)
` ( setf , ( car xy ) , ( cdr xy ) ) ) ( pairlis local - args recur - args ) ) ) )
;; `(let ((,res))
;; (tagbody ,recur-from
;; (flet ((,recur-sym ,recur-args
( progn , @bindings
;; (go ,recur-from))
;; ))
( setf , res , @body ) ) )
;; ,res)))
( defmacro with - recur ( args & rest body )
( let * ( ( recur - sym ( intern " RECUR " ) ) ; HAVE TO CAPITALIZE !
;; (local-args (mapcar (lambda (x)
;; (intern (symbol-name x))) args))
( res ( " res " ) )
( recur - from ( gentemp " recur - from " ) )
( recur - args ( mapcar ( lambda ( x ) ( ( symbol - name x ) ) ) local - args
;; ))
( update - binds ( gentemp " update - binds " ) )
;; (bindings (mapcar (lambda (xy)
` ( setf , ( car xy ) , ( cdr xy ) ) ) ( pairlis local - args recur - args ) ) ) )
;; `(let ((,res))
;; (flet ((,update-binds ,recur-args
( progn , @bindings ) ) )
( ( ( , recur - sym , args
` ( progn ( , , update - binds , , @args )
;; (go ,,recur-from)))))
;; (tagbody ,recur-from
( setf , res , @body ) ) )
;; ,res)))
( with - recur ( x 2 )
( if ( < x 4 )
( recur ( 1 + x ) )
;; x))
;; (let ((continue? t)
( x 2 )
;; (res)
;; (continue? nil))
;; (flet ((recur (x)
( setf x x )
( setf continue ? t ) ) )
;; (tagbody recur-from
( progn
( setf res
( if ( < x 4 )
( recur ( 1 + x ) )
;; x))
;; (when continue?
( setf continue ? nil )
;; (go recur-from))))
;; res))
(comment
we can call simmary - tails on all these and get nil ,
;;or some combination of (t, nil), (t, some-list-of illegal callsites)
(defparameter normal-call
`(if (= 2 3)
:equal
(progn (print :otherwise)
:inequal)))
(defparameter good-tail
'(if (= 2 3)
(recur 2)
(recur 3)))
(defparameter bad-tail
'(progn
(recur 2)
3))
(defparameter gnarly-bad-tail
'(lambda (x)
(with-recur (acc x)
(let ((blah 5)
(blee 3))
(if (<= acc blah)
(recur (1+ x))
(progn (when (< 2 3)
(recur 44))
2))))))
(defparameter gnarly-good-tail
'(lambda (x)
(with-recur (acc x)
(let ((blah 5)
(blee 3))
(if (<= acc blah)
(recur (1+ x))
(progn (when (< 2 3)
(print 44))
2))))))
)
( with - recur ( x 2 y 3 ) ( + x y ) )
(with-recur (x 0)
(if (< x 10)
(recur (1+ x))
x))
(with-recur (x 0)
(if (> x 9)
x
(recur (1+ x))))
(defun good-tail ()
(with-recur (x 2)
(if (> x 5)
x
(if (= x 2)
(recur 5)
(recur (1+ x))))))
;;not currently checked!
(defun bad-tail ()
(with-recur ()
(progn
(recur 2)
3)))
(defun gnarly-bad-tail (x)
(with-recur (acc x)
(let ((blah 5)
(blee 3))
(if (<= acc blah)
(recur (1+ x))
(progn (when (< 2 3)
(recur 44))
2)))))
(defun gnarly-good-tail (x)
(with-recur (acc x)
(let ((blah 5)
(blee 3))
(if (<= acc blah)
(recur (1+ acc))
(progn (when (< 2 3)
(print 44))
2)))))
;;test function for sussing out the correct way to
handle recur forms with ...
(defun tst ()
(flet ((blah (&rest args) (pprint :hobart) nil))
(macrolet ((recur (&whole whole-form &rest args)
(let* ((frm (list* 'apply (list 'function 'blah) args)))
(progn (pprint (list :expanding whole-form :to frm))
frm))))
(labels ((blah (x &rest xs)
(pprint (list x xs))
(if (null xs) x
(progn (pprint (macroexpand-1 `(recur (+ ,x (first ,xs)) (rest ,xs))))
(recur (+ x (first xs)) (rest xs))))))
#'blah))))
;; ;;looking at using with-recur...
;; ;;possible naive way to inline using with-recur...
;; (defun blah (&rest xs)
;; (labels ((aux (&rest xs)
( ( ( blah ( & rest args )
;; `(apply #'aux ,args)))
;; (case (length xs)
( 1 ( with - recur ( x ( first xs ) )
;; (pprint x)))
( 2 ( with - recur ( acc ( first xs )
bound ( second xs ) )
;; (if (< acc bound)
( blah ( + acc 3 ) bound )
;; acc)))
;; (otherwise (with-recur ((x y &rest zs) xs)
( + x y ( apply # ' + zs ) ) ) ) ) ) ) )
( apply # ' aux xs ) ) )
( with - recur ( x 2 )
( if ( < x 10 ) ( recur ( 1 + x ) ) x ) )
( LET ( ( # : |continuex764| T ) ( # : |res763| ) ( X 2 ) )
( FLET ( ( RECUR ( # : X765 )
( PROGN ( SETF X # : X765 ) ( SETF # : |continuex764| T ) ) ) )
(
|recur - from2|
( PROGN
;; (SETF #:|res763|
( IF ( < X 10 )
( RECUR ( 1 + X ) )
;; X))
;; (WHEN #:|continuex764| (SETF #:|continuex764| NIL) (GO |recur-from2|))))
;; #:|res763|))
( with - recur ( ( x & rest xs ) xs )
;; (if (null zs)
;; (+ x y)
;; (recur (+ x y)
;; (first zs)
;; (rest zs))))
( destructuring - bind ( x y & rest zs ) xs
;; (LET ((#:|continuex764| T)
;; (#:|res763|)
;; (arg-X x)
;; (arg-y y)
;; (rest-zs zs))
( FLET ( ( RECUR ( x y & rest zs )
( PROGN ( SETF arg - X x )
( setf arg - y y )
( setf rest - zs zs )
;; (SETF #:|continuex764| T))))
;; (TAGBODY
;; |recur-fromvar|
( PROGN
;; (SETF #:|res763|
( IF ( < X 10 )
( RECUR ( 1 + X ) )
;; X))
;; (WHEN #:|continuex764| (SETF #:|continuex764| NIL) (GO |recur-fromvar|))))
;; #:|res763|)))
;;let's construct one from scratch..
(comment
(defun blah (&rest xs)
(let* ((blah-1 (named-fn blah-1 (x)
(pprint x)))
(blah-2 (named-fn blah-2 (acc bound)
(if (< acc bound)
(blah (+ acc 3) bound)
acc)))
(blah-variadic (named-fn blah-variadic (x y &rest zs)
(+ x y (apply #'+ zs)))))
(case (length xs)
(1 (funcall blah-1 (first xs)))
(2 (funcall blah-2 (first xs) (second xs)))
(otherwise (apply blah-variadic xs) ))))
;;shouldn't blow the stack..but it does unless compiled.
(defun blah (&rest xs)
(let* ((blah-1 (named-fn blah-1 (x)
(pprint x)))
(blah-2 (named-fn blah-2 (acc bound)
(if (< acc bound)
(recur (+ acc 3) bound)
acc)))
(blah-variadic (named-fn blah-variadic (x y &rest zs)
(+ x y (apply #'+ zs)))))
(case (length xs)
(1 (funcall blah-1 (first xs)))
(2 (funcall blah-2 (first xs) (second xs)))
(otherwise (apply blah-variadic xs) ))))
)
(comment
;;testing -this works.
(defparameter f (named-fn* blah
((x) (pprint (list x)) x)
((x &rest xs) (if (null xs) (blah x) (recur (+ x (first xs)) (rest xs))))))
)
;; (defmacro named-fn* (name &rest args-bodies)
( if (= ( length args - bodies ) 1 )
( let ( ( args - body ( first args - bodies ) ) )
` ( named - fn , name , ( first args - body ) , ( second args - body ) ) ) ; regular named - fn , no dispatch .
;; (destructuring-bind (cases var) (parse-dispatch-specs args-bodies)
( let * ( ( args ( " args " ) )
;; (funcspecs (mapcar (lambda (xs)
;; (destructuring-bind (n (args body)) xs
;; (let* ((fname (func-name name n))
( fbody ` ( named - fn , fname , args , body ) ) )
;; (if (= n 0)
;; `(,n ,fname ,fbody)
` ( , n , fname , ) ) ) ) ) cases ) )
;; (varspec (when var
;; (let* ((fname (func-name name :variadic))
( fbody ` ( named - fn , fname , ( first var ) , ( second var ) ) ) )
;; `(:variadic ,fname ,fbody))))
( specs ( if var ( append funcspecs ( list ) ) funcspecs ) )
( aux ( " aux " ) )
( dummy ( " stupid - var " ) ) )
;; `(let ((,dummy nil) )
;; (declare (ignore ,dummy))
( macrolet ( ( , name ( , ' & rest , ' args )
;; (list 'apply (list 'function (quote ,aux)) (list* 'list ,'args))))
( let ( , @(mapcar ( lambda ( xs ) ` ( , ( second xs ) , ( third xs ) ) )
;; specs))
;; (labels ((,aux (,'&rest ,args)
;; (case (length ,args)
;; ,@(mapcar (lambda (xs) (let ((n (first xs))
( name ( second xs ) ) )
;; (if (= n 0)
;; `(,n (funcall ,name))
;; `(,n (apply ,name ,args))))) funcspecs)
( otherwise , ( if var ` ( apply , ( second varspec ) , args )
;; `(error 'no-matching-args))))))
;; (function ,aux)))))))))
;;testing
(comment
(defparameter e
(named-fn* blah
((acc bound) (if (< acc bound) (recur (+ acc 3) bound) acc))
))
(defparameter f
(named-fn* blah
((acc bound) (if (< acc bound) (recur (+ acc 3) bound) acc))
((x &rest xs) (if (null xs) x (recur (+ x (first xs)) (rest xs))))
))
;;we shouldn't need progn...
(defparameter g
(named-fn* blah
((x)
(progn
(pprint (list :blah-1 :result x))
x))
((acc bound)
(progn (pprint (list :blah-2 :counting acc :to bound))
(if (< acc bound) (recur (+ acc 3) bound) acc)))
((x &rest xs)
(progn (pprint (list :blah-variadic :adding x :to xs))
(if (null xs) x (recur (+ x (first xs)) (rest xs)))))))
(defparameter h
(named-fn* blah
((x)
(progn
(pprint (list :blah-1 :result x))
x))
((acc bound)
(progn (pprint (list :blah-2 :counting acc :to bound))
(if (< acc bound) (blah (+ acc 3) bound) acc)))
;; ((x &rest xs)
( progn ( pprint ( list : blah - variadic : adding x : to xs ) )
;; (if (null xs) x (recur (+ x (first xs)) (rest xs)))))
))
)
;; (defmacro named-fn* (name &rest args-bodies)
( if (= ( length args - bodies ) 1 )
( let ( ( args - body ( first args - bodies ) ) )
` ( named - fn , name , ( first args - body ) , ( second args - body ) ) ) ; regular named - fn , no dispatch .
;; (destructuring-bind (cases var) (parse-dispatch-specs args-bodies)
;; (let* ((recur-sym (intern "RECUR"))
( args ( " args " ) )
;; (funcspecs (mapcar (lambda (xs)
;; (destructuring-bind (n (args body)) xs
;; (let* ((fname (func-name name n))
( fbody ` ( named - fn , fname , args , body ) ) )
;; (if (= n 0)
;; `(,n ,fname ,fbody)
` ( , n , fname , ) ) ) ) ) cases ) )
;; (varspec (when var
;; (let* ((fname (func-name name :variadic))
( fbody ` ( named - fn , fname , ( first var ) , ( second var ) ) ) )
;; `(:variadic ,fname ,fbody))))
( specs ( if var ( append funcspecs ( list ) ) funcspecs ) )
( aux ( " aux " ) ) )
;; `(let ((,name))
( macrolet ( ( , name ( , ' & rest , args )
;; (list* 'funcall ',name ,args)
;; ))
( let * ( , @(mapcar ( lambda ( xs ) ` ( , ( second xs ) , ( third xs ) ) ) specs ) )
;; (labels ((,aux (,'&rest ,args)
;; (case (length ,args)
;; ,@(mapcar (lambda (xs) (let ((n (first xs))
( name ( second xs ) ) )
;; (if (= n 0)
;; `(,n (funcall ,name))
;; `(,n (apply ,name ,args))))) funcspecs)
( otherwise , ( if var ` ( apply , ( second varspec ) , args )
;; `(error 'no-matching-args))))))
( setf , name ( lambda ( & rest , args ) ( apply , aux , args ) ) )
;; (labels ((,name (,'&rest ,args) (apply ,name ,args)))
;; (function ,aux))))))))))
;;testing
(comment
(defparameter the-func
(lambda*
(() 2)
((x) (+ x 1))
((x y) (+ x y))
((&rest xs) (reduce #'+ xs))))
)
| null | https://raw.githubusercontent.com/joinr/clclojure/8b51214891c4da6dfbec393dffac70846ee1d0c5/dustbin/recurtest.lisp | lisp | can we implement (recur ...) ?
(block some-name
(tagbody some-point
(when :recur
(go some-point))
)
)
result)
(defun custom-loop (x)
(let ((res))
(pprint ,'x)
(go ,'recur-from))))
(tagbody recur-from
x
(recur (1+ x)))))
res)))
HAVE TO CAPITALIZE !
(local-args (mapcar (lambda (x)
(intern (symbol-name x))) args))
))
(bindings (mapcar (lambda (xy)
`(let ((,res))
(tagbody ,recur-from
(flet ((,recur-sym ,recur-args
(go ,recur-from))
))
,res)))
HAVE TO CAPITALIZE !
(local-args (mapcar (lambda (x)
(intern (symbol-name x))) args))
))
(bindings (mapcar (lambda (xy)
`(let ((,res))
(flet ((,update-binds ,recur-args
(go ,,recur-from)))))
(tagbody ,recur-from
,res)))
x))
(let ((continue? t)
(res)
(continue? nil))
(flet ((recur (x)
(tagbody recur-from
x))
(when continue?
(go recur-from))))
res))
or some combination of (t, nil), (t, some-list-of illegal callsites)
not currently checked!
test function for sussing out the correct way to
;;looking at using with-recur...
;;possible naive way to inline using with-recur...
(defun blah (&rest xs)
(labels ((aux (&rest xs)
`(apply #'aux ,args)))
(case (length xs)
(pprint x)))
(if (< acc bound)
acc)))
(otherwise (with-recur ((x y &rest zs) xs)
(SETF #:|res763|
X))
(WHEN #:|continuex764| (SETF #:|continuex764| NIL) (GO |recur-from2|))))
#:|res763|))
(if (null zs)
(+ x y)
(recur (+ x y)
(first zs)
(rest zs))))
(LET ((#:|continuex764| T)
(#:|res763|)
(arg-X x)
(arg-y y)
(rest-zs zs))
(SETF #:|continuex764| T))))
(TAGBODY
|recur-fromvar|
(SETF #:|res763|
X))
(WHEN #:|continuex764| (SETF #:|continuex764| NIL) (GO |recur-fromvar|))))
#:|res763|)))
let's construct one from scratch..
shouldn't blow the stack..but it does unless compiled.
testing -this works.
(defmacro named-fn* (name &rest args-bodies)
regular named - fn , no dispatch .
(destructuring-bind (cases var) (parse-dispatch-specs args-bodies)
(funcspecs (mapcar (lambda (xs)
(destructuring-bind (n (args body)) xs
(let* ((fname (func-name name n))
(if (= n 0)
`(,n ,fname ,fbody)
(varspec (when var
(let* ((fname (func-name name :variadic))
`(:variadic ,fname ,fbody))))
`(let ((,dummy nil) )
(declare (ignore ,dummy))
(list 'apply (list 'function (quote ,aux)) (list* 'list ,'args))))
specs))
(labels ((,aux (,'&rest ,args)
(case (length ,args)
,@(mapcar (lambda (xs) (let ((n (first xs))
(if (= n 0)
`(,n (funcall ,name))
`(,n (apply ,name ,args))))) funcspecs)
`(error 'no-matching-args))))))
(function ,aux)))))))))
testing
we shouldn't need progn...
((x &rest xs)
(if (null xs) x (recur (+ x (first xs)) (rest xs)))))
(defmacro named-fn* (name &rest args-bodies)
regular named - fn , no dispatch .
(destructuring-bind (cases var) (parse-dispatch-specs args-bodies)
(let* ((recur-sym (intern "RECUR"))
(funcspecs (mapcar (lambda (xs)
(destructuring-bind (n (args body)) xs
(let* ((fname (func-name name n))
(if (= n 0)
`(,n ,fname ,fbody)
(varspec (when var
(let* ((fname (func-name name :variadic))
`(:variadic ,fname ,fbody))))
`(let ((,name))
(list* 'funcall ',name ,args)
))
(labels ((,aux (,'&rest ,args)
(case (length ,args)
,@(mapcar (lambda (xs) (let ((n (first xs))
(if (= n 0)
`(,n (funcall ,name))
`(,n (apply ,name ,args))))) funcspecs)
`(error 'no-matching-args))))))
(labels ((,name (,'&rest ,args) (apply ,name ,args)))
(function ,aux))))))))))
testing | (defpackage common-utils.recurtest
(:use :common-lisp :common-utils))
(in-package :common-utils.recurtest)
:
( progn ( update - vars )
( ( ( recur ( )
` ( progn ( setf , ' x , )
( setf res
( if (= x 10 )
( defmacro with - recur ( args & rest body )
( res ( " res " ) )
( recur - from ( gentemp " recur - from " ) )
( recur - args ( mapcar ( lambda ( x ) ( ( symbol - name x ) ) ) local - args
` ( setf , ( car xy ) , ( cdr xy ) ) ) ( pairlis local - args recur - args ) ) ) )
( progn , @bindings
( setf , res , @body ) ) )
( defmacro with - recur ( args & rest body )
( res ( " res " ) )
( recur - from ( gentemp " recur - from " ) )
( recur - args ( mapcar ( lambda ( x ) ( ( symbol - name x ) ) ) local - args
( update - binds ( gentemp " update - binds " ) )
` ( setf , ( car xy ) , ( cdr xy ) ) ) ( pairlis local - args recur - args ) ) ) )
( progn , @bindings ) ) )
( ( ( , recur - sym , args
` ( progn ( , , update - binds , , @args )
( setf , res , @body ) ) )
( with - recur ( x 2 )
( if ( < x 4 )
( recur ( 1 + x ) )
( x 2 )
( setf x x )
( setf continue ? t ) ) )
( progn
( setf res
( if ( < x 4 )
( recur ( 1 + x ) )
( setf continue ? nil )
(comment
we can call simmary - tails on all these and get nil ,
(defparameter normal-call
`(if (= 2 3)
:equal
(progn (print :otherwise)
:inequal)))
(defparameter good-tail
'(if (= 2 3)
(recur 2)
(recur 3)))
(defparameter bad-tail
'(progn
(recur 2)
3))
(defparameter gnarly-bad-tail
'(lambda (x)
(with-recur (acc x)
(let ((blah 5)
(blee 3))
(if (<= acc blah)
(recur (1+ x))
(progn (when (< 2 3)
(recur 44))
2))))))
(defparameter gnarly-good-tail
'(lambda (x)
(with-recur (acc x)
(let ((blah 5)
(blee 3))
(if (<= acc blah)
(recur (1+ x))
(progn (when (< 2 3)
(print 44))
2))))))
)
( with - recur ( x 2 y 3 ) ( + x y ) )
(with-recur (x 0)
(if (< x 10)
(recur (1+ x))
x))
(with-recur (x 0)
(if (> x 9)
x
(recur (1+ x))))
(defun good-tail ()
(with-recur (x 2)
(if (> x 5)
x
(if (= x 2)
(recur 5)
(recur (1+ x))))))
(defun bad-tail ()
(with-recur ()
(progn
(recur 2)
3)))
(defun gnarly-bad-tail (x)
(with-recur (acc x)
(let ((blah 5)
(blee 3))
(if (<= acc blah)
(recur (1+ x))
(progn (when (< 2 3)
(recur 44))
2)))))
(defun gnarly-good-tail (x)
(with-recur (acc x)
(let ((blah 5)
(blee 3))
(if (<= acc blah)
(recur (1+ acc))
(progn (when (< 2 3)
(print 44))
2)))))
handle recur forms with ...
(defun tst ()
(flet ((blah (&rest args) (pprint :hobart) nil))
(macrolet ((recur (&whole whole-form &rest args)
(let* ((frm (list* 'apply (list 'function 'blah) args)))
(progn (pprint (list :expanding whole-form :to frm))
frm))))
(labels ((blah (x &rest xs)
(pprint (list x xs))
(if (null xs) x
(progn (pprint (macroexpand-1 `(recur (+ ,x (first ,xs)) (rest ,xs))))
(recur (+ x (first xs)) (rest xs))))))
#'blah))))
( ( ( blah ( & rest args )
( 1 ( with - recur ( x ( first xs ) )
( 2 ( with - recur ( acc ( first xs )
bound ( second xs ) )
( blah ( + acc 3 ) bound )
( + x y ( apply # ' + zs ) ) ) ) ) ) ) )
( apply # ' aux xs ) ) )
( with - recur ( x 2 )
( if ( < x 10 ) ( recur ( 1 + x ) ) x ) )
( LET ( ( # : |continuex764| T ) ( # : |res763| ) ( X 2 ) )
( FLET ( ( RECUR ( # : X765 )
( PROGN ( SETF X # : X765 ) ( SETF # : |continuex764| T ) ) ) )
(
|recur - from2|
( PROGN
( IF ( < X 10 )
( RECUR ( 1 + X ) )
( with - recur ( ( x & rest xs ) xs )
( destructuring - bind ( x y & rest zs ) xs
( FLET ( ( RECUR ( x y & rest zs )
( PROGN ( SETF arg - X x )
( setf arg - y y )
( setf rest - zs zs )
( PROGN
( IF ( < X 10 )
( RECUR ( 1 + X ) )
(comment
(defun blah (&rest xs)
(let* ((blah-1 (named-fn blah-1 (x)
(pprint x)))
(blah-2 (named-fn blah-2 (acc bound)
(if (< acc bound)
(blah (+ acc 3) bound)
acc)))
(blah-variadic (named-fn blah-variadic (x y &rest zs)
(+ x y (apply #'+ zs)))))
(case (length xs)
(1 (funcall blah-1 (first xs)))
(2 (funcall blah-2 (first xs) (second xs)))
(otherwise (apply blah-variadic xs) ))))
(defun blah (&rest xs)
(let* ((blah-1 (named-fn blah-1 (x)
(pprint x)))
(blah-2 (named-fn blah-2 (acc bound)
(if (< acc bound)
(recur (+ acc 3) bound)
acc)))
(blah-variadic (named-fn blah-variadic (x y &rest zs)
(+ x y (apply #'+ zs)))))
(case (length xs)
(1 (funcall blah-1 (first xs)))
(2 (funcall blah-2 (first xs) (second xs)))
(otherwise (apply blah-variadic xs) ))))
)
(comment
(defparameter f (named-fn* blah
((x) (pprint (list x)) x)
((x &rest xs) (if (null xs) (blah x) (recur (+ x (first xs)) (rest xs))))))
)
( if (= ( length args - bodies ) 1 )
( let ( ( args - body ( first args - bodies ) ) )
( let * ( ( args ( " args " ) )
( fbody ` ( named - fn , fname , args , body ) ) )
` ( , n , fname , ) ) ) ) ) cases ) )
( fbody ` ( named - fn , fname , ( first var ) , ( second var ) ) ) )
( specs ( if var ( append funcspecs ( list ) ) funcspecs ) )
( aux ( " aux " ) )
( dummy ( " stupid - var " ) ) )
( macrolet ( ( , name ( , ' & rest , ' args )
( let ( , @(mapcar ( lambda ( xs ) ` ( , ( second xs ) , ( third xs ) ) )
( name ( second xs ) ) )
( otherwise , ( if var ` ( apply , ( second varspec ) , args )
(comment
(defparameter e
(named-fn* blah
((acc bound) (if (< acc bound) (recur (+ acc 3) bound) acc))
))
(defparameter f
(named-fn* blah
((acc bound) (if (< acc bound) (recur (+ acc 3) bound) acc))
((x &rest xs) (if (null xs) x (recur (+ x (first xs)) (rest xs))))
))
(defparameter g
(named-fn* blah
((x)
(progn
(pprint (list :blah-1 :result x))
x))
((acc bound)
(progn (pprint (list :blah-2 :counting acc :to bound))
(if (< acc bound) (recur (+ acc 3) bound) acc)))
((x &rest xs)
(progn (pprint (list :blah-variadic :adding x :to xs))
(if (null xs) x (recur (+ x (first xs)) (rest xs)))))))
(defparameter h
(named-fn* blah
((x)
(progn
(pprint (list :blah-1 :result x))
x))
((acc bound)
(progn (pprint (list :blah-2 :counting acc :to bound))
(if (< acc bound) (blah (+ acc 3) bound) acc)))
( progn ( pprint ( list : blah - variadic : adding x : to xs ) )
))
)
( if (= ( length args - bodies ) 1 )
( let ( ( args - body ( first args - bodies ) ) )
( args ( " args " ) )
( fbody ` ( named - fn , fname , args , body ) ) )
` ( , n , fname , ) ) ) ) ) cases ) )
( fbody ` ( named - fn , fname , ( first var ) , ( second var ) ) ) )
( specs ( if var ( append funcspecs ( list ) ) funcspecs ) )
( aux ( " aux " ) ) )
( macrolet ( ( , name ( , ' & rest , args )
( let * ( , @(mapcar ( lambda ( xs ) ` ( , ( second xs ) , ( third xs ) ) ) specs ) )
( name ( second xs ) ) )
( otherwise , ( if var ` ( apply , ( second varspec ) , args )
( setf , name ( lambda ( & rest , args ) ( apply , aux , args ) ) )
(comment
(defparameter the-func
(lambda*
(() 2)
((x) (+ x 1))
((x y) (+ x y))
((&rest xs) (reduce #'+ xs))))
)
|
c2b2c60f88c5b4e510bd45ffec0bde224ce1ec831b21f28824d6744f8cf3f968 | oral-health-and-disease-ontologies/ohd-ontology | data-source-methods.lisp |
;;; generic methods for data-source class
(defgeneric initialize-instance ((ds data-source) &key &allow-other-keys)
(:documentation "Initializes the data source."))
(defgeneric open-data-source ((ds data-source) &key &allow-other-keys)
(:documentation "Opens a stream (or connection) the data source."))
;;; methods for file-data-source
(defmethod open-data-source ((fs file-data-source) &key filespec &allow-other-keys)
"Opens a file stream to the file specified by the data source's filespec slot.
If the filespec param is given, the filespec is set to that value."
(when filespec
(setf (filespec fs) filespec))
(when (not (filespec fs))
(error "you must provide a file specificaiton for the data source."))
;; open a file stream
(setf (stream fs) (open (filespec fs)))
;; return the data-source
fs)
(defmethod close-data-source ((fs file-data-source))
"Closes the file stream of the file data source."
(when (stream fs)
(close (stream fs))
(setf (stream fs) nil)))
;;; methods for jdbc-data-source
(defmethod open-data-source ((js jdbc-data-source) &key jdbc-url &allow-other-keys)
"Opens a connection to the jdbc data source."
;; set key value
(when jdbc-url
(setf (jdbc-url js) jdbc-url))
;; check for jdbc-url
(when (not (jdbc-url js))
(error "you must supply a jdbc url (i.e., connection string)"))
set connction to jdbc data source
(when (search "jdbc:sqlite" (jdbc-url js))
(#"forName" 'Class "org.sqlite.JDBC"))
(setf (connection js)
(#"getConnection" 'java.sql.DriverManager (jdbc-url js)))
;;return the data source
js)
(defmethod open-data-source-resultset ((js jdbc-data-source) &key sql-string &allow-other-keys)
;; although it listed as a key, the sql-string must be supplied
(let ((rs (make-instance 'jdbc-results :sql-string sql-string)))
(setf rs (open-resultset rs))))
(defmethod close-data-source ((js jdbc-data-source))
"Closes the connection to the jdbc data source."
(and (connection js) (#"close" (connection js)))
(and (statement js) (#"close" (statement js))))
| null | https://raw.githubusercontent.com/oral-health-and-disease-ontologies/ohd-ontology/ba3f502b86487c8ba5fa04ff8ba33312a1679570/src/vdw-translation/development-library/classes/data-source-methods.lisp | lisp | generic methods for data-source class
methods for file-data-source
open a file stream
return the data-source
methods for jdbc-data-source
set key value
check for jdbc-url
return the data source
although it listed as a key, the sql-string must be supplied |
(defgeneric initialize-instance ((ds data-source) &key &allow-other-keys)
(:documentation "Initializes the data source."))
(defgeneric open-data-source ((ds data-source) &key &allow-other-keys)
(:documentation "Opens a stream (or connection) the data source."))
(defmethod open-data-source ((fs file-data-source) &key filespec &allow-other-keys)
"Opens a file stream to the file specified by the data source's filespec slot.
If the filespec param is given, the filespec is set to that value."
(when filespec
(setf (filespec fs) filespec))
(when (not (filespec fs))
(error "you must provide a file specificaiton for the data source."))
(setf (stream fs) (open (filespec fs)))
fs)
(defmethod close-data-source ((fs file-data-source))
"Closes the file stream of the file data source."
(when (stream fs)
(close (stream fs))
(setf (stream fs) nil)))
(defmethod open-data-source ((js jdbc-data-source) &key jdbc-url &allow-other-keys)
"Opens a connection to the jdbc data source."
(when jdbc-url
(setf (jdbc-url js) jdbc-url))
(when (not (jdbc-url js))
(error "you must supply a jdbc url (i.e., connection string)"))
set connction to jdbc data source
(when (search "jdbc:sqlite" (jdbc-url js))
(#"forName" 'Class "org.sqlite.JDBC"))
(setf (connection js)
(#"getConnection" 'java.sql.DriverManager (jdbc-url js)))
js)
(defmethod open-data-source-resultset ((js jdbc-data-source) &key sql-string &allow-other-keys)
(let ((rs (make-instance 'jdbc-results :sql-string sql-string)))
(setf rs (open-resultset rs))))
(defmethod close-data-source ((js jdbc-data-source))
"Closes the connection to the jdbc data source."
(and (connection js) (#"close" (connection js)))
(and (statement js) (#"close" (statement js))))
|
894ba31d2fafa384df131d7679c79f387bbf3f86900e0a927a39f88e95834dbc | rabbitmq/rabbitmq-test | gm_soak_test.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License 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.
%%
The Original Code is RabbitMQ .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2015 Pivotal Software , Inc. All rights reserved .
%%
-module(gm_soak_test).
-export([test/0]).
-export([joined/2, members_changed/3, handle_msg/3, handle_terminate/2]).
-behaviour(gm).
-include("gm_specs.hrl").
%% ---------------------------------------------------------------------------
%% Soak test
%% ---------------------------------------------------------------------------
get_state() ->
get(state).
with_state(Fun) ->
put(state, Fun(get_state())).
inc() ->
case 1 + get(count) of
100000 -> Now = erlang:monotonic_time(),
Start = put(ts, Now),
Diff = erlang:convert_time_unit(Now - Start,
native,
micro_seconds),
Rate = 100000 / (Diff / 1000000),
io:format("~p seeing ~p msgs/sec~n", [self(), Rate]),
put(count, 0);
N -> put(count, N)
end.
joined([], Members) ->
io:format("Joined ~p (~p members)~n", [self(), length(Members)]),
put(state, dict:from_list([{Member, empty} || Member <- Members])),
put(count, 0),
put(ts, erlang:monotonic_time()),
ok.
members_changed([], Births, Deaths) ->
with_state(
fun (State) ->
State1 =
lists:foldl(
fun (Born, StateN) ->
false = dict:is_key(Born, StateN),
dict:store(Born, empty, StateN)
end, State, Births),
lists:foldl(
fun (Died, StateN) ->
true = dict:is_key(Died, StateN),
dict:store(Died, died, StateN)
end, State1, Deaths)
end),
ok.
handle_msg([], From, {test_msg, Num}) ->
inc(),
with_state(
fun (State) ->
ok = case dict:find(From, State) of
{ok, died} ->
exit({{from, From},
{received_posthumous_delivery, Num}});
{ok, empty} -> ok;
{ok, Num} -> ok;
{ok, Num1} when Num < Num1 ->
exit({{from, From},
{duplicate_delivery_of, Num},
{expecting, Num1}});
{ok, Num1} ->
exit({{from, From},
{received_early, Num},
{expecting, Num1}});
error ->
exit({{from, From},
{received_premature_delivery, Num}})
end,
dict:store(From, Num + 1, State)
end),
ok.
handle_terminate([], Reason) ->
io:format("Left ~p (~p)~n", [self(), Reason]),
ok.
spawn_member() ->
spawn_link(
fun () ->
random:seed(erlang:phash2([node()]),
erlang:monotonic_time(),
erlang:unique_integer()),
start up delay of no more than 10 seconds
timer:sleep(random:uniform(10000)),
{ok, Pid} = gm:start_link(
?MODULE, ?MODULE, [],
fun rabbit_misc:execute_mnesia_transaction/1),
Start = random:uniform(10000),
send_loop(Pid, Start, Start + random:uniform(10000)),
gm:leave(Pid),
spawn_more()
end).
spawn_more() ->
[spawn_member() || _ <- lists:seq(1, 4 - random:uniform(4))].
send_loop(_Pid, Target, Target) ->
ok;
send_loop(Pid, Count, Target) when Target > Count ->
case random:uniform(3) of
3 -> gm:confirmed_broadcast(Pid, {test_msg, Count});
_ -> gm:broadcast(Pid, {test_msg, Count})
end,
sleep up to 4 ms
send_loop(Pid, Count + 1, Target).
test() ->
ok = gm:create_tables(),
spawn_member(),
spawn_member().
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-test/c77ef827396a32aa67b4cbfe9c237485a2650d2d/test/src/gm_soak_test.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License 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.
---------------------------------------------------------------------------
Soak test
--------------------------------------------------------------------------- | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2015 Pivotal Software , Inc. All rights reserved .
-module(gm_soak_test).
-export([test/0]).
-export([joined/2, members_changed/3, handle_msg/3, handle_terminate/2]).
-behaviour(gm).
-include("gm_specs.hrl").
get_state() ->
get(state).
with_state(Fun) ->
put(state, Fun(get_state())).
inc() ->
case 1 + get(count) of
100000 -> Now = erlang:monotonic_time(),
Start = put(ts, Now),
Diff = erlang:convert_time_unit(Now - Start,
native,
micro_seconds),
Rate = 100000 / (Diff / 1000000),
io:format("~p seeing ~p msgs/sec~n", [self(), Rate]),
put(count, 0);
N -> put(count, N)
end.
joined([], Members) ->
io:format("Joined ~p (~p members)~n", [self(), length(Members)]),
put(state, dict:from_list([{Member, empty} || Member <- Members])),
put(count, 0),
put(ts, erlang:monotonic_time()),
ok.
members_changed([], Births, Deaths) ->
with_state(
fun (State) ->
State1 =
lists:foldl(
fun (Born, StateN) ->
false = dict:is_key(Born, StateN),
dict:store(Born, empty, StateN)
end, State, Births),
lists:foldl(
fun (Died, StateN) ->
true = dict:is_key(Died, StateN),
dict:store(Died, died, StateN)
end, State1, Deaths)
end),
ok.
handle_msg([], From, {test_msg, Num}) ->
inc(),
with_state(
fun (State) ->
ok = case dict:find(From, State) of
{ok, died} ->
exit({{from, From},
{received_posthumous_delivery, Num}});
{ok, empty} -> ok;
{ok, Num} -> ok;
{ok, Num1} when Num < Num1 ->
exit({{from, From},
{duplicate_delivery_of, Num},
{expecting, Num1}});
{ok, Num1} ->
exit({{from, From},
{received_early, Num},
{expecting, Num1}});
error ->
exit({{from, From},
{received_premature_delivery, Num}})
end,
dict:store(From, Num + 1, State)
end),
ok.
handle_terminate([], Reason) ->
io:format("Left ~p (~p)~n", [self(), Reason]),
ok.
spawn_member() ->
spawn_link(
fun () ->
random:seed(erlang:phash2([node()]),
erlang:monotonic_time(),
erlang:unique_integer()),
start up delay of no more than 10 seconds
timer:sleep(random:uniform(10000)),
{ok, Pid} = gm:start_link(
?MODULE, ?MODULE, [],
fun rabbit_misc:execute_mnesia_transaction/1),
Start = random:uniform(10000),
send_loop(Pid, Start, Start + random:uniform(10000)),
gm:leave(Pid),
spawn_more()
end).
spawn_more() ->
[spawn_member() || _ <- lists:seq(1, 4 - random:uniform(4))].
send_loop(_Pid, Target, Target) ->
ok;
send_loop(Pid, Count, Target) when Target > Count ->
case random:uniform(3) of
3 -> gm:confirmed_broadcast(Pid, {test_msg, Count});
_ -> gm:broadcast(Pid, {test_msg, Count})
end,
sleep up to 4 ms
send_loop(Pid, Count + 1, Target).
test() ->
ok = gm:create_tables(),
spawn_member(),
spawn_member().
|
0c3997e32648edd55a3069a6a7d40012d3ff22d15132ee27d75705451b760829 | bobzhang/fan | test_nest_quotation.ml |
open Camlp4.PreCast;
value _loc = Loc.ghost;
value f x = <:expr<
<:patt<
<:expr< >>
;
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/test/test_nest_quotation.ml | ocaml |
open Camlp4.PreCast;
value _loc = Loc.ghost;
value f x = <:expr<
<:patt<
<:expr< >>
;
| |
e9a1549c0349934163dcc058ede25deebcbc3f150f6cdcf09c091f70e4f39f13 | leo-project/leo_gateway | leo_nfs_proto3_server.erl | %%======================================================================
%%
Leo Gateway
%%
Copyright ( c ) 2012 - 2015 Rakuten , Inc.
%%
This file is provided to you 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(leo_nfs_proto3_server).
-include("leo_gateway.hrl").
-include("leo_http.hrl").
-include_lib("leo_commons/include/leo_commons.hrl").
-include_lib("leo_redundant_manager/include/leo_redundant_manager.hrl").
-include_lib("leo_object_storage/include/leo_object_storage.hrl").
-include_lib("leo_s3_libs/include/leo_s3_bucket.hrl").
-include_lib("leo_logger/include/leo_logger.hrl").
-include("leo_nfs_proto3.hrl").
-include_lib("kernel/include/file.hrl").
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]).
-export([nfsproc3_null_3/2,
nfsproc3_getattr_3/3,
nfsproc3_setattr_3/3,
nfsproc3_lookup_3/3,
nfsproc3_access_3/3,
nfsproc3_readlink_3/3,
nfsproc3_read_3/3,
nfsproc3_write_3/3,
nfsproc3_create_3/3,
nfsproc3_mkdir_3/3,
nfsproc3_symlink_3/3,
nfsproc3_mknod_3/3,
nfsproc3_remove_3/3,
nfsproc3_rmdir_3/3,
nfsproc3_rename_3/3,
nfsproc3_link_3/3,
nfsproc3_readdir_3/3,
nfsproc3_readdirplus_3/3,
nfsproc3_fsstat_3/3,
nfsproc3_pathconf_3/3,
nfsproc3_commit_3/3,
nfsproc3_fsinfo_3/3]).
-export([sattr_mode_to_file_info/1, sattr_uid_to_file_info/1,
sattr_gid_to_file_info/1, sattr_atime_to_file_info/1,
sattr_mtime_to_file_info/1, sattr_size_to_file_info/1]).
-record(ongoing_readdir, {
filelist :: list(#?METADATA{})
}).
-define(SIMPLENFS_WCC_EMPTY, {
{false, void},
{false, void}
}).
-define(NFS_DUMMY_FILE4S3DIR, << "$$_dir_$$" >>).
-define(NFS_READDIR_NUM_OF_RESPONSE, 10).
-define(NFS3_OK, 'NFS3_OK').
-define(NFS3_NG, 'NFS3_NG').
-define(NFS3ERR_NOENT, 'NFS3ERR_NOENT').
-define(NFS3ERR_IO, 'NFS3ERR_IO').
-define(NFS3ERR_NOTEMPTY, 'NFS3ERR_NOTEMPTY').
-define(NFS3ERR_BADHANDLE,'NFS3ERR_BADHANDLE').
%% ---------------------------------------------------------------------
%% API
%% ---------------------------------------------------------------------
%% @doc Called only once from a parent rpc server process to initialize this module
%% during starting a leo_storage server.
-spec(init(any()) -> {ok, any()}).
init(_Args) ->
leo_nfs_state_ets:add_write_verfier(crypto:rand_bytes(8)),
{ok, void}.
handle_call(Req,_From, S) ->
?debug("handle_call", "req:~p from:~p", [Req,_From]),
{reply, [], S}.
handle_cast(Req, S) ->
?debug("handle_cast", "req:~p", [Req]),
{reply, [], S}.
handle_info(Req, S) ->
?debug("handle_info", "req:~p", [Req]),
{noreply, S}.
terminate(_Reason,_S) ->
ok.
%% ---------------------------------------------------------------------
%% API
%% ---------------------------------------------------------------------
%% @doc
nfsproc3_null_3(_Clnt, State) ->
{reply, [], State}.
%% @doc
nfsproc3_getattr_3({{UID}} = _1, Clnt, State) ->
case leo_nfs_state_ets:get_path(UID) of
{ok, Path} ->
?debug("nfsproc3_getattr_3", "path:~p client:~p", [Path, Clnt]),
case getattr(Path) of
{ok, Meta} ->
{reply, {?NFS3_OK, {Meta}}, State};
not_found ->
{reply, {?NFS3ERR_NOENT, void}, State};
{error, Reason} ->
?error("nfsproc3_getattr_3/3", [{path, Path}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, Reason}, State}
end;
_ ->
{reply, {?NFS3ERR_BADHANDLE, void}, State}
end.
%% @doc
%% @todo for now do nothing
nfsproc3_setattr_3({{FileUID}, {_Mode,
_UID,
_GID,
SattrSize,
_ATime,
_MTime},_Guard} = _1, Clnt, State) ->
?debug("nfsproc3_setattr_3", "args:~p client:~p", [_1, Clnt]),
Size = sattr_size_to_file_info(SattrSize),
case Size of
undefined ->
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY}}, State};
_ ->
{ok, Path} = leo_nfs_state_ets:get_path(FileUID),
case leo_nfs_file_handler:trim(Path, Size) of
ok ->
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY}}, State};
{error, Reason}->
?error("nfsproc3_setattr_3/3",
[{path, Path}, {size, Size}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, Reason}, State}
end
end.
%% @doc
nfsproc3_lookup_3({{{UID}, Name}} = _1, Clnt, State) ->
{ok, Dir} = leo_nfs_state_ets:get_path(UID),
Path = leo_nfs_file_handler:path_relative_to_abs(filename:join(Dir, Name)),
?debug("nfsproc3_lookup_3", "path:~p client:~p", [Path, Clnt]),
case getattr(Path) of
{ok, Meta} ->
{ok, FileUID} = leo_nfs_state_ets:add_path(Path),
{reply, {?NFS3_OK, {{FileUID},
{true, Meta},
{false, void}
}}, State};
not_found ->
{reply, {?NFS3ERR_NOENT, {{false, void}}}, State};
{error, Reason} ->
?error("nfsproc3_lookup_3/3", [{path, Path}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {{false, void}}}, State}
end.
%% @doc
nfsproc3_access_3({{UID}, AccessBitMask} = _1, Clnt, State) ->
{ok, Path} = leo_nfs_state_ets:get_path(UID),
?debug("nfsproc3_access_3", "path:~p mask:~p client:~p", [Path, AccessBitMask, Clnt]),
{reply, {?NFS3_OK, {{false, void}, %% post_op_attr for obj
AccessBitMask %% access bits(up all)
}}, State}.
%% @doc
nfsproc3_readlink_3(_1, Clnt, State) ->
?debug("nfsproc3_readlink_3", "args:~p client:~p", [_1, Clnt]),
{reply, {?NFS3_OK, {{false, void}, %% post_op_attr for obj
<< "link path" >>}
}, State}.
%% @doc
nfsproc3_read_3({{UID}, Offset, Count} =_1, Clnt, State) ->
?debug("nfsproc3_read_3", "args:~p client:~p", [_1, Clnt]),
{ok, Path} = leo_nfs_state_ets:get_path(UID),
case leo_nfs_file_handler:read(Path, Offset, Offset + Count - 1) of
{ok, Meta, Body} ->
EOF = Meta#?METADATA.dsize =:= (Offset + Count),
{reply, {?NFS3_OK, {{false, void}, %% post_op_attr for obj
Count, %% count read bytes
eof
Body}
}, State};
{error, Reason} ->
?error("nfsproc3_read_3/3",
[{path, Path}, {offset, Offset}, {count, Count}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {{false, void} %% post_op_attr for obj
}}, State}
end.
%% @doc
nfsproc3_write_3({{UID}, Offset, Count,_HowStable, Data} = _1, Clnt, State) ->
?debug("nfsproc3_write_3", "uid:~p offset:~p count:~p client:~p",
[UID, Offset, Count, Clnt]),
{ok, Path} = leo_nfs_state_ets:get_path(UID),
case leo_nfs_file_handler:write(Path, Offset, Offset + Count - 1, Data) of
ok ->
{ok, WriteVerf} = leo_nfs_state_ets:get_write_verfier(),
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY,
Count,
'DATA_SYNC',
WriteVerf}
}, State};
{error, Reason} ->
?error("nfsproc3_write_3/3",
[{path, Path}, {offset, Offset}, {count, Count}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {?SIMPLENFS_WCC_EMPTY}}, State}
end.
%% @doc
nfsproc3_create_3({{{UID}, Name}, {_CreateMode,_How}} = _1, Clnt, State) ->
?debug("nfsproc3_create_3", "args:~p client:~p", [_1, Clnt]),
{ok, Dir} = leo_nfs_state_ets:get_path(UID),
Key = filename:join(Dir, Name),
case leo_gateway_rpc_handler:put(#put_req_params{path = Key,
body = ?BIN_EMPTY,
dsize = 0}) of
{ok,_}->
{ok, FileUID} = leo_nfs_state_ets:add_path(Key),
{reply, {?NFS3_OK, {{true, {FileUID}}, %% post_op file handle
{false, void}, %% post_op_attr
?SIMPLENFS_WCC_EMPTY}
}, State};
{error, Reason} ->
?error("nfsproc3_create_3/3",
[{path, Key}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {?SIMPLENFS_WCC_EMPTY}}, State}
end.
%% @doc
nfsproc3_mkdir_3({{{UID}, Name},_How} = _1, Clnt, State) ->
?debug("nfsproc3_mkdir_3", "args:~p client:~p", [_1, Clnt]),
{ok, Dir} = leo_nfs_state_ets:get_path(UID),
DirPath = filename:join(Dir, Name),
Key = filename:join(DirPath, ?NFS_DUMMY_FILE4S3DIR),
case leo_gateway_rpc_handler:put(#put_req_params{path = Key,
body = ?BIN_EMPTY,
dsize = 0}) of
{ok,_}->
{reply, {?NFS3_OK, {{false, void}, %% post_op file handle
{false, void}, %% post_op_attr
?SIMPLENFS_WCC_EMPTY
}
}, State};
{error, Reason} ->
?error("nfsproc3_mkdir_3/3",
[{path, Key}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {{false, void}, %% post_op file handle
{false, void}, %% post_op_attr
?SIMPLENFS_WCC_EMPTY
}
}, State}
end.
%% @doc
nfsproc3_symlink_3(_1, Clnt, State) ->
?debug("nfsproc3_symlink_3", "args:~p client:~p", [_1, Clnt]),
{reply, {?NFS3_OK, {{false, void}, %% post_op file handle
{false, void}, %% post_op_attr
?SIMPLENFS_WCC_EMPTY}
}, State}.
%% @doc
nfsproc3_mknod_3(_1, Clnt, State) ->
?debug("nfsproc3_mknod_3", "args:~p client:~p", [_1, Clnt]),
{reply, {?NFS3_OK, {{false, void}, %% post_op file handle
{false, void}, %% post_op_attr
?SIMPLENFS_WCC_EMPTY}
}, State}.
%% @doc
nfsproc3_remove_3({{{UID}, Name}} = _1, Clnt, State) ->
?debug("nfsproc3_remove_3", "args:~p client:~p", [_1, Clnt]),
{ok, Dir} = leo_nfs_state_ets:get_path(UID),
Key = filename:join(Dir, Name),
case leo_gateway_rpc_handler:delete(Key) of
ok ->
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY}}, State};
{error, Reason} ->
?error("nfsproc3_remove_3/3",
[{path, Key}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {?SIMPLENFS_WCC_EMPTY}}, State}
end.
%% @doc
nfsproc3_rmdir_3({{{UID}, Name}} = _1, Clnt, State) ->
?debug("nfsproc3_rmdir_3", "args:~p client:~p", [_1, Clnt]),
{ok, Dir} = leo_nfs_state_ets:get_path(UID),
Path4S3 = filename:join(Dir, Name),
Path4S3Dir = leo_nfs_file_handler:path_to_dir(Path4S3),
case is_empty_dir(Path4S3Dir) of
true ->
Key = filename:join(Path4S3Dir, ?NFS_DUMMY_FILE4S3DIR),
catch leo_gateway_rpc_handler:delete(Key),
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY}}, State};
false ->
{reply, {?NFS3ERR_NOTEMPTY, {?SIMPLENFS_WCC_EMPTY}}, State}
end.
%% @doc
nfsproc3_rename_3({{{SrcUID}, SrcName}, {{DstUID}, DstName}} =_1, Clnt, State) ->
?debug("nfsproc3_rename_3", "args:~p client:~p", [_1, Clnt]),
{ok, SrcDir} = leo_nfs_state_ets:get_path(SrcUID),
{ok, DstDir} = leo_nfs_state_ets:get_path(DstUID),
Src4S3 = filename:join(SrcDir, SrcName),
Dst4S3 = filename:join(DstDir, DstName),
case leo_nfs_file_handler:rename(Src4S3, Dst4S3) of
ok ->
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY, %% src
?SIMPLENFS_WCC_EMPTY %% dst
}}, State};
{error, not_found} ->
{reply, {?NFS3ERR_NOENT, {?SIMPLENFS_WCC_EMPTY, %% src
?SIMPLENFS_WCC_EMPTY %% dst
}}, State};
{error, Reason} ->
?error("nfsproc3_rename_3/3",
[{src, Src4S3}, {dest, Dst4S3}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {?SIMPLENFS_WCC_EMPTY, %% src
?SIMPLENFS_WCC_EMPTY %% dst
}}, State}
end.
%% @doc
nfsproc3_link_3(_1, Clnt, State) ->
?debug("nfsproc3_link_3", "args:~p client:~p", [_1, Clnt]),
{reply, {?NFS3_NG, {{false, void}, %% post_op_attr
?SIMPLENFS_WCC_EMPTY
}
}, State}.
%% @doc
nfsproc3_readdir_3({{UID}, Cookie, CookieVerf, MaxCnt} = _1, Clnt, State) ->
?debug("nfsproc3_readdir_3", "args:~p client:~p", [_1, Clnt]),
{ok, Path} = leo_nfs_state_ets:get_path(UID),
readdir(Path, Cookie, CookieVerf, MaxCnt, false, State).
%% @doc
nfsproc3_readdirplus_3({{UID}, Cookie, CookieVerf,_DirCnt, MaxCnt} = _1, Clnt, State) ->
?debug("nfsproc3_readdirplus_3", "args:~p client:~p", [_1, Clnt]),
{ok, Path} = leo_nfs_state_ets:get_path(UID),
readdir(Path, Cookie, CookieVerf, MaxCnt, true, State).
%% @doc
nfsproc3_fsstat_3(_1, Clnt, State) ->
?debug("nfsproc3_fsstat_3", "args:~p client:~p", [_1, Clnt]),
{ok, {Total, Free}} = leo_nfs_file_handler:get_disk_usage(),
{reply, {?NFS3_OK, {{false, void}, %% post_op_attr
Total, %% total size
Free, %% free size
Free, %% free size(for auth user)
16, %% # of files
8, %% # of free file slots
8, %% # of free file slots(for auth user)
invarsec
}}, State}.
%% @doc
nfsproc3_fsinfo_3(_1, Clnt, State) ->
?debug("nfsproc3_fsinfo_3", "args:~p client:~p", [_1, Clnt]),
MaxFileSize = ?DEF_NFSD_MAX_FILE_SIZE,
{reply, {?NFS3_OK, {{false, void}, %% post_op_attr
5242880, %% rtmax
rtperf(limited at client up to 1024 * 1024 )
8, %% rtmult
wtmaxa(limited at client up to 1024 * 1024 )
wtperf
wtmult
dperf ( limited at client up to 32768 )
MaxFileSize, %% max file size
{1, 0}, %% time_delta
0 %% properties
}}, State}.
%% @doc
nfsproc3_pathconf_3(_1, Clnt, State) ->
?debug("nfsproc3_pathconf_3", "args:~p client:~p", [_1, Clnt]),
{reply, {?NFS3_OK, {{false, void}, %% post_op_attr
8, %% linkmax
1024, %% name_max
no_trunc - mean make a reques error if filename 's length was larger than
false, %% chown_restricted
case_insensitive
true %% case_preserving
}}, State}.
%% @doc
nfsproc3_commit_3(_1, Clnt, State) ->
?debug("nfsproc3_commit_3", "args:~p client:~p", [_1, Clnt]),
{ok, WriteVerf} = leo_nfs_state_ets:get_write_verfier(),
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY,
WriteVerf
}}, State}.
%% @doc
sattr_mode_to_file_info({0,_}) ->
undefined;
sattr_mode_to_file_info({true, Mode}) ->
Mode.
%% @doc
sattr_uid_to_file_info({0,_}) ->
undefined;
sattr_uid_to_file_info({true, UID}) ->
UID.
%% @doc
sattr_gid_to_file_info({0,_}) ->
undefined;
sattr_gid_to_file_info({true, GID}) ->
GID.
%% @doc
sattr_size_to_file_info({true, Size}) ->
Size;
sattr_size_to_file_info({_,_}) ->
undefined.
%% @doc
sattr_atime_to_file_info({'DONT_CHANGE',_}) ->
undefined;
sattr_atime_to_file_info({'SET_TO_SERVER_TIME',_}) ->
leo_date:unixtime();
sattr_atime_to_file_info({_, {ATime,_}}) ->
ATime.
%% @doc
sattr_mtime_to_file_info({'DONT_CHANGE',_}) ->
undefined;
sattr_mtime_to_file_info({'SET_TO_SERVER_TIME',_}) ->
leo_date:unixtime();
sattr_mtime_to_file_info({_, {MTime,_}}) ->
MTime.
%% ---------------------------------------------------------------------
%% INNER FUNCTIONS
%% ---------------------------------------------------------------------
%% @doc
@private
readdir(Path, Cookie, CookieVerf,_MaxCnt, IsPlus, State) ->
Path4S3Dir = leo_nfs_file_handler:path_to_dir(Path),
{ok, NewCookieVerf, ReadDir} = case CookieVerf of
<< 0,0,0,0,0,0,0,0 >> ->
readdir_add_entry(Path4S3Dir);
CookieVerf ->
readdir_get_entry(CookieVerf)
end,
case ReadDir of
undefined ->
%% empty response
readdir_del_entry(NewCookieVerf),
{reply, {?NFS3_OK, {{true, s3dir2fattr3(Path)}, %% post_op_attr
NewCookieVerf, %% cookie verfier
{ %% dir_list(empty)
void, %% pre_op_attr
eof
}}}, State};
ReadDir ->
%% create response
@TODO
# of entries should be determinted by _
{Resp, EOF} = readdir_create_resp(Path4S3Dir, Cookie, ReadDir, ?NFS_READDIR_NUM_OF_RESPONSE, IsPlus),
case EOF of
true ->
readdir_del_entry(NewCookieVerf);
false ->
void
end,
{reply, {?NFS3_OK, {{true, s3dir2fattr3(Path)}, %% post_op_attr
NewCookieVerf, %% cookie verfier
{Resp, %% pre_op_attr
EOF}
}}, State}
end.
@doc Returns true if refers to a directory which have child files ,
%% and false otherwise.
@private
-spec(is_empty_dir(binary()) -> boolean()).
is_empty_dir(Path) ->
case leo_nfs_file_handler:list_dir(Path, false) of
{ok, MetaList} when is_list(MetaList) ->
FilteredList =
lists:foldl(
fun(Meta, Acc) ->
case Meta of
#?METADATA{del = 1} ->
Acc;
#?METADATA{dsize = -1} ->
DummyKey = filename:join(Meta#?METADATA.key,
?NFS_DUMMY_FILE4S3DIR),
case leo_gateway_rpc_handler:head(DummyKey) of
{ok, #?METADATA{del = 0}} ->
[Meta | Acc];
_ ->
Acc
end;
_ ->
case filename:basename(Meta#?METADATA.key) of
?NFS_DUMMY_FILE4S3DIR ->
Acc;
_ ->
[Meta | Acc]
end
end
end, [], MetaList),
?debug("is_empty_dir/1", "Dir:~p, Filter:~p", [Path, FilteredList]),
length(FilteredList) =:= 0;
_Error ->
false
end.
@doc Returns list of file 's metadatas stored in the specified Path and
%% store that with a verifier to identify and retrieve later.
@private
-spec(readdir_add_entry(binary()) ->
{ok, binary(), #ongoing_readdir{}}).
readdir_add_entry(Path) ->
@TODO READDIR does not need the attribute
case leo_nfs_file_handler:list_dir(Path) of
{ok, FileList}->
%% gen cookie verfier
CookieVerf = crypto:rand_bytes(8),
ReadDir = #ongoing_readdir{filelist = FileList},
leo_nfs_state_ets:add_readdir_entry(CookieVerf, ReadDir),
{ok, CookieVerf, ReadDir};
Error ->
Error
end.
%% @doc Get resources correspond with a cookies verifier which returned by readdir_get_eantry
@private
-spec(readdir_get_entry(binary()) ->
{ok, binary(), #ongoing_readdir{} | undefined}).
readdir_get_entry(CookieVerf) ->
case leo_nfs_state_ets:get_readdir_entry(CookieVerf) of
not_found ->
{ok, CookieVerf, undefined};
{ok, Ret} ->
{ok, CookieVerf, Ret}
end.
%% @doc Delete resources correspond with a cookies verifier which returned by readdir_get_entry
@private
-spec(readdir_del_entry(binary()) -> ok).
readdir_del_entry(CookieVerf) ->
leo_nfs_state_ets:del_readdir_entry(CookieVerf),
ok.
@doc Create a rpc response for a readdir3 request
@private
-spec(readdir_create_resp(binary(), integer(), #ongoing_readdir{}, integer(), boolean()) ->
void | tuple()).
readdir_create_resp(Path, Cookie,
#ongoing_readdir{filelist = FileList} = ReadDir, NumEntry, IsPlus) ->
{StartCookie, EOF} = case length(FileList) =< (Cookie + NumEntry) of
true ->
{length(FileList), true};
false ->
{Cookie + NumEntry, false}
end,
readdir_create_resp(Path,
StartCookie,
ReadDir,
Cookie,
EOF,
IsPlus,
void).
@private
readdir_create_resp(_Path, CurCookie,
_ReadDir, Cookie,
EOF,_IsPlus, Resp) when CurCookie =:= Cookie ->
?debug("readdir_create_resp", "resp:~p ~n", [Resp]),
{Resp, EOF};
readdir_create_resp(Path, CurCookie,
#ongoing_readdir{filelist = FileList} = ReadDir,
Cookie, EOF, IsPlus, Resp) ->
Meta = lists:nth(CurCookie, FileList),
#?METADATA{key = Key, dsize = Size, del = Del} = Meta,
?debug("readdir_create_resp/7", "Meta ~p", [Meta]),
NormalizedKey = case Size of
-1 ->
%% dir to be normalized(means expand .|.. chars)
leo_nfs_file_handler:path_relative_to_abs(Key);
_ ->
%% file
Key
end,
Del2 = case Size =:= -1 andalso
is_empty_dir(NormalizedKey) of
true ->
DummyKey = filename:join(NormalizedKey, ?NFS_DUMMY_FILE4S3DIR),
case leo_gateway_rpc_handler:head(DummyKey) of
{ok, #?METADATA{del = 1}} ->
1;
_ ->
Del
end;
_ ->
Del
end,
FileName = filename:basename(Key),
case {Del2, FileName} of
{1,_} ->
readdir_create_resp(Path,
CurCookie - 1,
ReadDir,
Cookie,
EOF,
IsPlus,
Resp);
{_, ?NFS_DUMMY_FILE4S3DIR} ->
readdir_create_resp(Path,
CurCookie - 1,
ReadDir,
Cookie,
EOF,
IsPlus,
Resp);
_ ->
{ok, UID} = leo_nfs_state_ets:add_path(NormalizedKey),
NewResp = case IsPlus of
true ->
{inode(NormalizedKey),
FileName,
CurCookie,
{true, %% post_op_attr
meta2fattr3(Meta#?METADATA{key = NormalizedKey})
},
{true, {UID}}, %% post_op_fh3
Resp
};
_ ->
{inode(NormalizedKey),
FileName,
CurCookie,
Resp
}
end,
?debug("readdir_create_resp", "key:~p cookie:~p~n",
[NormalizedKey, CurCookie]),
readdir_create_resp(Path,
CurCookie - 1,
ReadDir,
Cookie,
EOF,
IsPlus,
NewResp)
end.
@private
getattr(Path) ->
case leo_nfs_file_handler:binary_is_contained(Path, $/) of
%% object
true ->
@todo emulate directories
case leo_gateway_rpc_handler:head(Path) of
{ok, #?METADATA{del = 0} = Meta} ->
{ok, meta2fattr3(Meta)};
{ok, #?METADATA{del = 1}} ->
not_found;
{error, not_found} ->
Path4S3Dir = leo_nfs_file_handler:path_to_dir(Path),
case leo_nfs_file_handler:is_dir(Path4S3Dir) of
true ->
{ok, s3dir2fattr3(Path)};
false ->
not_found
end;
{error, Reason} ->
{error, Reason}
end;
%% bucket
false ->
case leo_s3_bucket:find_bucket_by_name(Path) of
{ok, Bucket} ->
Attr = bucket2fattr3(Bucket),
{ok, Attr};
not_found ->
not_found;
{error, Reason} ->
{error, Reason}
end
end.
%% @doc Return the inode of Path
@private
@todo to be replaced with truely unique i d supported by LeoFS future works
-spec(inode(binary() | string()) ->
integer()).
inode(Path) ->
<< F8:8/binary,_/binary >> = erlang:md5(Path),
Hex = leo_hex:binary_to_hex(F8),
leo_hex:hex_to_integer(Hex).
%% @doc Convert from #?METADATA{} format to the format codes erpcgen generated expect
@private
-spec(meta2fattr3(#?METADATA{}) ->
tuple()).
meta2fattr3(#?METADATA{dsize = -1, key = Key}) ->
Path4S3Dir = leo_nfs_file_handler:path_to_dir(Key),
UT = get_dir_unix_timestamp(Path4S3Dir),
{'NF3DIR',
8#00777, %% @todo determin based on ACL? protection mode bits
2, %% # of hard links
0, %% @todo determin base on ACL? uid
0, %% @todo gid
4096, %% file size
@todo actual size used at disk(LeoFS should return ` body + metadata + header / footer ` )
data used for special file(in Linux first is major , second is minor number )
0, %% fsid
inode(Key),
{UT, 0}, %% last access
{UT, 0}, %% last modification
{UT, 0}}; %% last change
meta2fattr3(#?METADATA{key = Key, timestamp = TS, dsize = Size}) ->
UT = leo_date:greg_seconds_to_unixtime(TS),
{'NF3REG',
8#00666, %% @todo determin based on ACL? protection mode bits
1, %% # of hard links
0, %% @todo determin base on ACL? uid
0, %% @todo gid
Size, %% file size
@todo actual size used at disk(LeoFS should return ` body + metadata + header / footer ` )
data used for special file(in Linux first is major , second is minor number )
0, %% fsid
inode(Key), %% @todo Unique ID to be specifed fieldid
{UT, 0}, %% last access
{UT, 0}, %% last modification
{UT, 0}}. %% last change
%% @doc Convert from the directory path to the format codes erpcgen generated expect
@private
-spec(s3dir2fattr3(binary()) ->
tuple()).
s3dir2fattr3(Dir) ->
Path4S3Dir = leo_nfs_file_handler:path_to_dir(Dir),
UT = get_dir_unix_timestamp(Path4S3Dir),
{'NF3DIR',
8#00777, %% @todo determin based on ACL? protection mode bits
2, %% # of hard links
0, %% @todo determin base on ACL? uid
0, %% @todo gid
4096, %% @todo how to calc?
@todo actual size used at disk(LeoFS should return ` body + metadata + header / footer ` )
data used for special file(in Linux first is major , second is minor number )
0, %% fsid
inode(Dir), %% @todo Unique ID to be specifed fieldid
{UT, 0}, %% last access
{UT, 0}, %% last modification
{UT, 0}}. %% last change
%% @doc Convert from #?BUCKET to the format codes erpcgen generated expect
@private
-spec(bucket2fattr3(#?BUCKET{}) ->
tuple()).
bucket2fattr3(Bucket) ->
UT = leo_date:greg_seconds_to_unixtime(Bucket#?BUCKET.last_modified_at),
{'NF3DIR',
8#00777, %% @todo determin based on ACL? protection mode bits
3, %% # of hard links
0, %% @todo determin base on ACL? uid
0, %% @todo gid
@todo directory size
@todo actual size used at disk
data used for special file(in Linux first is major , second is minor number )
0, %% fsid
inode(Bucket#?BUCKET.name), %% @todo Unique ID to be specifed fieldid
{UT, 0}, %% last access
{UT, 0}, %% last modification
{UT, 0}}.%% last change
@private
get_dir_unix_timestamp(_Dir) ->
= = = For 1.4
%% case leo_gateway_rpc_handler:get_dir_meta(Dir) of
{ ok , } - >
%% Meta = binary_to_term(MetaBin),
%% leo_date:greg_seconds_to_unixtime(Meta#?METADATA.timestamp);
%% _Error ->
Now = calendar : datetime_to_gregorian_seconds(calendar : ( ) ) ,
%% leo_date:greg_seconds_to_unixtime(Now)
%% end.
Now = calendar:datetime_to_gregorian_seconds(calendar:universal_time()),
leo_date:greg_seconds_to_unixtime(Now).
| null | https://raw.githubusercontent.com/leo-project/leo_gateway/7bac8912b762688f0ef237b31fee17e30e3888a3/src/leo_nfs_proto3_server.erl | erlang | ======================================================================
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
======================================================================
---------------------------------------------------------------------
API
---------------------------------------------------------------------
@doc Called only once from a parent rpc server process to initialize this module
during starting a leo_storage server.
---------------------------------------------------------------------
API
---------------------------------------------------------------------
@doc
@doc
@doc
@todo for now do nothing
@doc
@doc
post_op_attr for obj
access bits(up all)
@doc
post_op_attr for obj
@doc
post_op_attr for obj
count read bytes
post_op_attr for obj
@doc
@doc
post_op file handle
post_op_attr
@doc
post_op file handle
post_op_attr
post_op file handle
post_op_attr
@doc
post_op file handle
post_op_attr
@doc
post_op file handle
post_op_attr
@doc
@doc
@doc
src
dst
src
dst
src
dst
@doc
post_op_attr
@doc
@doc
@doc
post_op_attr
total size
free size
free size(for auth user)
# of files
# of free file slots
# of free file slots(for auth user)
@doc
post_op_attr
rtmax
rtmult
max file size
time_delta
properties
@doc
post_op_attr
linkmax
name_max
chown_restricted
case_preserving
@doc
@doc
@doc
@doc
@doc
@doc
@doc
---------------------------------------------------------------------
INNER FUNCTIONS
---------------------------------------------------------------------
@doc
empty response
post_op_attr
cookie verfier
dir_list(empty)
pre_op_attr
create response
post_op_attr
cookie verfier
pre_op_attr
and false otherwise.
store that with a verifier to identify and retrieve later.
gen cookie verfier
@doc Get resources correspond with a cookies verifier which returned by readdir_get_eantry
@doc Delete resources correspond with a cookies verifier which returned by readdir_get_entry
dir to be normalized(means expand .|.. chars)
file
post_op_attr
post_op_fh3
object
bucket
@doc Return the inode of Path
@doc Convert from #?METADATA{} format to the format codes erpcgen generated expect
@todo determin based on ACL? protection mode bits
# of hard links
@todo determin base on ACL? uid
@todo gid
file size
fsid
last access
last modification
last change
@todo determin based on ACL? protection mode bits
# of hard links
@todo determin base on ACL? uid
@todo gid
file size
fsid
@todo Unique ID to be specifed fieldid
last access
last modification
last change
@doc Convert from the directory path to the format codes erpcgen generated expect
@todo determin based on ACL? protection mode bits
# of hard links
@todo determin base on ACL? uid
@todo gid
@todo how to calc?
fsid
@todo Unique ID to be specifed fieldid
last access
last modification
last change
@doc Convert from #?BUCKET to the format codes erpcgen generated expect
@todo determin based on ACL? protection mode bits
# of hard links
@todo determin base on ACL? uid
@todo gid
fsid
@todo Unique ID to be specifed fieldid
last access
last modification
last change
case leo_gateway_rpc_handler:get_dir_meta(Dir) of
Meta = binary_to_term(MetaBin),
leo_date:greg_seconds_to_unixtime(Meta#?METADATA.timestamp);
_Error ->
leo_date:greg_seconds_to_unixtime(Now)
end. | Leo Gateway
Copyright ( c ) 2012 - 2015 Rakuten , Inc.
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(leo_nfs_proto3_server).
-include("leo_gateway.hrl").
-include("leo_http.hrl").
-include_lib("leo_commons/include/leo_commons.hrl").
-include_lib("leo_redundant_manager/include/leo_redundant_manager.hrl").
-include_lib("leo_object_storage/include/leo_object_storage.hrl").
-include_lib("leo_s3_libs/include/leo_s3_bucket.hrl").
-include_lib("leo_logger/include/leo_logger.hrl").
-include("leo_nfs_proto3.hrl").
-include_lib("kernel/include/file.hrl").
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]).
-export([nfsproc3_null_3/2,
nfsproc3_getattr_3/3,
nfsproc3_setattr_3/3,
nfsproc3_lookup_3/3,
nfsproc3_access_3/3,
nfsproc3_readlink_3/3,
nfsproc3_read_3/3,
nfsproc3_write_3/3,
nfsproc3_create_3/3,
nfsproc3_mkdir_3/3,
nfsproc3_symlink_3/3,
nfsproc3_mknod_3/3,
nfsproc3_remove_3/3,
nfsproc3_rmdir_3/3,
nfsproc3_rename_3/3,
nfsproc3_link_3/3,
nfsproc3_readdir_3/3,
nfsproc3_readdirplus_3/3,
nfsproc3_fsstat_3/3,
nfsproc3_pathconf_3/3,
nfsproc3_commit_3/3,
nfsproc3_fsinfo_3/3]).
-export([sattr_mode_to_file_info/1, sattr_uid_to_file_info/1,
sattr_gid_to_file_info/1, sattr_atime_to_file_info/1,
sattr_mtime_to_file_info/1, sattr_size_to_file_info/1]).
-record(ongoing_readdir, {
filelist :: list(#?METADATA{})
}).
-define(SIMPLENFS_WCC_EMPTY, {
{false, void},
{false, void}
}).
-define(NFS_DUMMY_FILE4S3DIR, << "$$_dir_$$" >>).
-define(NFS_READDIR_NUM_OF_RESPONSE, 10).
-define(NFS3_OK, 'NFS3_OK').
-define(NFS3_NG, 'NFS3_NG').
-define(NFS3ERR_NOENT, 'NFS3ERR_NOENT').
-define(NFS3ERR_IO, 'NFS3ERR_IO').
-define(NFS3ERR_NOTEMPTY, 'NFS3ERR_NOTEMPTY').
-define(NFS3ERR_BADHANDLE,'NFS3ERR_BADHANDLE').
-spec(init(any()) -> {ok, any()}).
init(_Args) ->
leo_nfs_state_ets:add_write_verfier(crypto:rand_bytes(8)),
{ok, void}.
handle_call(Req,_From, S) ->
?debug("handle_call", "req:~p from:~p", [Req,_From]),
{reply, [], S}.
handle_cast(Req, S) ->
?debug("handle_cast", "req:~p", [Req]),
{reply, [], S}.
handle_info(Req, S) ->
?debug("handle_info", "req:~p", [Req]),
{noreply, S}.
terminate(_Reason,_S) ->
ok.
nfsproc3_null_3(_Clnt, State) ->
{reply, [], State}.
nfsproc3_getattr_3({{UID}} = _1, Clnt, State) ->
case leo_nfs_state_ets:get_path(UID) of
{ok, Path} ->
?debug("nfsproc3_getattr_3", "path:~p client:~p", [Path, Clnt]),
case getattr(Path) of
{ok, Meta} ->
{reply, {?NFS3_OK, {Meta}}, State};
not_found ->
{reply, {?NFS3ERR_NOENT, void}, State};
{error, Reason} ->
?error("nfsproc3_getattr_3/3", [{path, Path}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, Reason}, State}
end;
_ ->
{reply, {?NFS3ERR_BADHANDLE, void}, State}
end.
nfsproc3_setattr_3({{FileUID}, {_Mode,
_UID,
_GID,
SattrSize,
_ATime,
_MTime},_Guard} = _1, Clnt, State) ->
?debug("nfsproc3_setattr_3", "args:~p client:~p", [_1, Clnt]),
Size = sattr_size_to_file_info(SattrSize),
case Size of
undefined ->
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY}}, State};
_ ->
{ok, Path} = leo_nfs_state_ets:get_path(FileUID),
case leo_nfs_file_handler:trim(Path, Size) of
ok ->
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY}}, State};
{error, Reason}->
?error("nfsproc3_setattr_3/3",
[{path, Path}, {size, Size}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, Reason}, State}
end
end.
nfsproc3_lookup_3({{{UID}, Name}} = _1, Clnt, State) ->
{ok, Dir} = leo_nfs_state_ets:get_path(UID),
Path = leo_nfs_file_handler:path_relative_to_abs(filename:join(Dir, Name)),
?debug("nfsproc3_lookup_3", "path:~p client:~p", [Path, Clnt]),
case getattr(Path) of
{ok, Meta} ->
{ok, FileUID} = leo_nfs_state_ets:add_path(Path),
{reply, {?NFS3_OK, {{FileUID},
{true, Meta},
{false, void}
}}, State};
not_found ->
{reply, {?NFS3ERR_NOENT, {{false, void}}}, State};
{error, Reason} ->
?error("nfsproc3_lookup_3/3", [{path, Path}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {{false, void}}}, State}
end.
nfsproc3_access_3({{UID}, AccessBitMask} = _1, Clnt, State) ->
{ok, Path} = leo_nfs_state_ets:get_path(UID),
?debug("nfsproc3_access_3", "path:~p mask:~p client:~p", [Path, AccessBitMask, Clnt]),
}}, State}.
nfsproc3_readlink_3(_1, Clnt, State) ->
?debug("nfsproc3_readlink_3", "args:~p client:~p", [_1, Clnt]),
<< "link path" >>}
}, State}.
nfsproc3_read_3({{UID}, Offset, Count} =_1, Clnt, State) ->
?debug("nfsproc3_read_3", "args:~p client:~p", [_1, Clnt]),
{ok, Path} = leo_nfs_state_ets:get_path(UID),
case leo_nfs_file_handler:read(Path, Offset, Offset + Count - 1) of
{ok, Meta, Body} ->
EOF = Meta#?METADATA.dsize =:= (Offset + Count),
eof
Body}
}, State};
{error, Reason} ->
?error("nfsproc3_read_3/3",
[{path, Path}, {offset, Offset}, {count, Count}, {cause, Reason}]),
}}, State}
end.
nfsproc3_write_3({{UID}, Offset, Count,_HowStable, Data} = _1, Clnt, State) ->
?debug("nfsproc3_write_3", "uid:~p offset:~p count:~p client:~p",
[UID, Offset, Count, Clnt]),
{ok, Path} = leo_nfs_state_ets:get_path(UID),
case leo_nfs_file_handler:write(Path, Offset, Offset + Count - 1, Data) of
ok ->
{ok, WriteVerf} = leo_nfs_state_ets:get_write_verfier(),
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY,
Count,
'DATA_SYNC',
WriteVerf}
}, State};
{error, Reason} ->
?error("nfsproc3_write_3/3",
[{path, Path}, {offset, Offset}, {count, Count}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {?SIMPLENFS_WCC_EMPTY}}, State}
end.
nfsproc3_create_3({{{UID}, Name}, {_CreateMode,_How}} = _1, Clnt, State) ->
?debug("nfsproc3_create_3", "args:~p client:~p", [_1, Clnt]),
{ok, Dir} = leo_nfs_state_ets:get_path(UID),
Key = filename:join(Dir, Name),
case leo_gateway_rpc_handler:put(#put_req_params{path = Key,
body = ?BIN_EMPTY,
dsize = 0}) of
{ok,_}->
{ok, FileUID} = leo_nfs_state_ets:add_path(Key),
?SIMPLENFS_WCC_EMPTY}
}, State};
{error, Reason} ->
?error("nfsproc3_create_3/3",
[{path, Key}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {?SIMPLENFS_WCC_EMPTY}}, State}
end.
nfsproc3_mkdir_3({{{UID}, Name},_How} = _1, Clnt, State) ->
?debug("nfsproc3_mkdir_3", "args:~p client:~p", [_1, Clnt]),
{ok, Dir} = leo_nfs_state_ets:get_path(UID),
DirPath = filename:join(Dir, Name),
Key = filename:join(DirPath, ?NFS_DUMMY_FILE4S3DIR),
case leo_gateway_rpc_handler:put(#put_req_params{path = Key,
body = ?BIN_EMPTY,
dsize = 0}) of
{ok,_}->
?SIMPLENFS_WCC_EMPTY
}
}, State};
{error, Reason} ->
?error("nfsproc3_mkdir_3/3",
[{path, Key}, {cause, Reason}]),
?SIMPLENFS_WCC_EMPTY
}
}, State}
end.
nfsproc3_symlink_3(_1, Clnt, State) ->
?debug("nfsproc3_symlink_3", "args:~p client:~p", [_1, Clnt]),
?SIMPLENFS_WCC_EMPTY}
}, State}.
nfsproc3_mknod_3(_1, Clnt, State) ->
?debug("nfsproc3_mknod_3", "args:~p client:~p", [_1, Clnt]),
?SIMPLENFS_WCC_EMPTY}
}, State}.
nfsproc3_remove_3({{{UID}, Name}} = _1, Clnt, State) ->
?debug("nfsproc3_remove_3", "args:~p client:~p", [_1, Clnt]),
{ok, Dir} = leo_nfs_state_ets:get_path(UID),
Key = filename:join(Dir, Name),
case leo_gateway_rpc_handler:delete(Key) of
ok ->
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY}}, State};
{error, Reason} ->
?error("nfsproc3_remove_3/3",
[{path, Key}, {cause, Reason}]),
{reply, {?NFS3ERR_IO, {?SIMPLENFS_WCC_EMPTY}}, State}
end.
nfsproc3_rmdir_3({{{UID}, Name}} = _1, Clnt, State) ->
?debug("nfsproc3_rmdir_3", "args:~p client:~p", [_1, Clnt]),
{ok, Dir} = leo_nfs_state_ets:get_path(UID),
Path4S3 = filename:join(Dir, Name),
Path4S3Dir = leo_nfs_file_handler:path_to_dir(Path4S3),
case is_empty_dir(Path4S3Dir) of
true ->
Key = filename:join(Path4S3Dir, ?NFS_DUMMY_FILE4S3DIR),
catch leo_gateway_rpc_handler:delete(Key),
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY}}, State};
false ->
{reply, {?NFS3ERR_NOTEMPTY, {?SIMPLENFS_WCC_EMPTY}}, State}
end.
nfsproc3_rename_3({{{SrcUID}, SrcName}, {{DstUID}, DstName}} =_1, Clnt, State) ->
?debug("nfsproc3_rename_3", "args:~p client:~p", [_1, Clnt]),
{ok, SrcDir} = leo_nfs_state_ets:get_path(SrcUID),
{ok, DstDir} = leo_nfs_state_ets:get_path(DstUID),
Src4S3 = filename:join(SrcDir, SrcName),
Dst4S3 = filename:join(DstDir, DstName),
case leo_nfs_file_handler:rename(Src4S3, Dst4S3) of
ok ->
}}, State};
{error, not_found} ->
}}, State};
{error, Reason} ->
?error("nfsproc3_rename_3/3",
[{src, Src4S3}, {dest, Dst4S3}, {cause, Reason}]),
}}, State}
end.
nfsproc3_link_3(_1, Clnt, State) ->
?debug("nfsproc3_link_3", "args:~p client:~p", [_1, Clnt]),
?SIMPLENFS_WCC_EMPTY
}
}, State}.
nfsproc3_readdir_3({{UID}, Cookie, CookieVerf, MaxCnt} = _1, Clnt, State) ->
?debug("nfsproc3_readdir_3", "args:~p client:~p", [_1, Clnt]),
{ok, Path} = leo_nfs_state_ets:get_path(UID),
readdir(Path, Cookie, CookieVerf, MaxCnt, false, State).
nfsproc3_readdirplus_3({{UID}, Cookie, CookieVerf,_DirCnt, MaxCnt} = _1, Clnt, State) ->
?debug("nfsproc3_readdirplus_3", "args:~p client:~p", [_1, Clnt]),
{ok, Path} = leo_nfs_state_ets:get_path(UID),
readdir(Path, Cookie, CookieVerf, MaxCnt, true, State).
nfsproc3_fsstat_3(_1, Clnt, State) ->
?debug("nfsproc3_fsstat_3", "args:~p client:~p", [_1, Clnt]),
{ok, {Total, Free}} = leo_nfs_file_handler:get_disk_usage(),
invarsec
}}, State}.
nfsproc3_fsinfo_3(_1, Clnt, State) ->
?debug("nfsproc3_fsinfo_3", "args:~p client:~p", [_1, Clnt]),
MaxFileSize = ?DEF_NFSD_MAX_FILE_SIZE,
rtperf(limited at client up to 1024 * 1024 )
wtmaxa(limited at client up to 1024 * 1024 )
wtperf
wtmult
dperf ( limited at client up to 32768 )
}}, State}.
nfsproc3_pathconf_3(_1, Clnt, State) ->
?debug("nfsproc3_pathconf_3", "args:~p client:~p", [_1, Clnt]),
no_trunc - mean make a reques error if filename 's length was larger than
case_insensitive
}}, State}.
nfsproc3_commit_3(_1, Clnt, State) ->
?debug("nfsproc3_commit_3", "args:~p client:~p", [_1, Clnt]),
{ok, WriteVerf} = leo_nfs_state_ets:get_write_verfier(),
{reply, {?NFS3_OK, {?SIMPLENFS_WCC_EMPTY,
WriteVerf
}}, State}.
sattr_mode_to_file_info({0,_}) ->
undefined;
sattr_mode_to_file_info({true, Mode}) ->
Mode.
sattr_uid_to_file_info({0,_}) ->
undefined;
sattr_uid_to_file_info({true, UID}) ->
UID.
sattr_gid_to_file_info({0,_}) ->
undefined;
sattr_gid_to_file_info({true, GID}) ->
GID.
sattr_size_to_file_info({true, Size}) ->
Size;
sattr_size_to_file_info({_,_}) ->
undefined.
sattr_atime_to_file_info({'DONT_CHANGE',_}) ->
undefined;
sattr_atime_to_file_info({'SET_TO_SERVER_TIME',_}) ->
leo_date:unixtime();
sattr_atime_to_file_info({_, {ATime,_}}) ->
ATime.
sattr_mtime_to_file_info({'DONT_CHANGE',_}) ->
undefined;
sattr_mtime_to_file_info({'SET_TO_SERVER_TIME',_}) ->
leo_date:unixtime();
sattr_mtime_to_file_info({_, {MTime,_}}) ->
MTime.
@private
readdir(Path, Cookie, CookieVerf,_MaxCnt, IsPlus, State) ->
Path4S3Dir = leo_nfs_file_handler:path_to_dir(Path),
{ok, NewCookieVerf, ReadDir} = case CookieVerf of
<< 0,0,0,0,0,0,0,0 >> ->
readdir_add_entry(Path4S3Dir);
CookieVerf ->
readdir_get_entry(CookieVerf)
end,
case ReadDir of
undefined ->
readdir_del_entry(NewCookieVerf),
eof
}}}, State};
ReadDir ->
@TODO
# of entries should be determinted by _
{Resp, EOF} = readdir_create_resp(Path4S3Dir, Cookie, ReadDir, ?NFS_READDIR_NUM_OF_RESPONSE, IsPlus),
case EOF of
true ->
readdir_del_entry(NewCookieVerf);
false ->
void
end,
EOF}
}}, State}
end.
@doc Returns true if refers to a directory which have child files ,
@private
-spec(is_empty_dir(binary()) -> boolean()).
is_empty_dir(Path) ->
case leo_nfs_file_handler:list_dir(Path, false) of
{ok, MetaList} when is_list(MetaList) ->
FilteredList =
lists:foldl(
fun(Meta, Acc) ->
case Meta of
#?METADATA{del = 1} ->
Acc;
#?METADATA{dsize = -1} ->
DummyKey = filename:join(Meta#?METADATA.key,
?NFS_DUMMY_FILE4S3DIR),
case leo_gateway_rpc_handler:head(DummyKey) of
{ok, #?METADATA{del = 0}} ->
[Meta | Acc];
_ ->
Acc
end;
_ ->
case filename:basename(Meta#?METADATA.key) of
?NFS_DUMMY_FILE4S3DIR ->
Acc;
_ ->
[Meta | Acc]
end
end
end, [], MetaList),
?debug("is_empty_dir/1", "Dir:~p, Filter:~p", [Path, FilteredList]),
length(FilteredList) =:= 0;
_Error ->
false
end.
@doc Returns list of file 's metadatas stored in the specified Path and
@private
-spec(readdir_add_entry(binary()) ->
{ok, binary(), #ongoing_readdir{}}).
readdir_add_entry(Path) ->
@TODO READDIR does not need the attribute
case leo_nfs_file_handler:list_dir(Path) of
{ok, FileList}->
CookieVerf = crypto:rand_bytes(8),
ReadDir = #ongoing_readdir{filelist = FileList},
leo_nfs_state_ets:add_readdir_entry(CookieVerf, ReadDir),
{ok, CookieVerf, ReadDir};
Error ->
Error
end.
@private
-spec(readdir_get_entry(binary()) ->
{ok, binary(), #ongoing_readdir{} | undefined}).
readdir_get_entry(CookieVerf) ->
case leo_nfs_state_ets:get_readdir_entry(CookieVerf) of
not_found ->
{ok, CookieVerf, undefined};
{ok, Ret} ->
{ok, CookieVerf, Ret}
end.
@private
-spec(readdir_del_entry(binary()) -> ok).
readdir_del_entry(CookieVerf) ->
leo_nfs_state_ets:del_readdir_entry(CookieVerf),
ok.
@doc Create a rpc response for a readdir3 request
@private
-spec(readdir_create_resp(binary(), integer(), #ongoing_readdir{}, integer(), boolean()) ->
void | tuple()).
readdir_create_resp(Path, Cookie,
#ongoing_readdir{filelist = FileList} = ReadDir, NumEntry, IsPlus) ->
{StartCookie, EOF} = case length(FileList) =< (Cookie + NumEntry) of
true ->
{length(FileList), true};
false ->
{Cookie + NumEntry, false}
end,
readdir_create_resp(Path,
StartCookie,
ReadDir,
Cookie,
EOF,
IsPlus,
void).
@private
readdir_create_resp(_Path, CurCookie,
_ReadDir, Cookie,
EOF,_IsPlus, Resp) when CurCookie =:= Cookie ->
?debug("readdir_create_resp", "resp:~p ~n", [Resp]),
{Resp, EOF};
readdir_create_resp(Path, CurCookie,
#ongoing_readdir{filelist = FileList} = ReadDir,
Cookie, EOF, IsPlus, Resp) ->
Meta = lists:nth(CurCookie, FileList),
#?METADATA{key = Key, dsize = Size, del = Del} = Meta,
?debug("readdir_create_resp/7", "Meta ~p", [Meta]),
NormalizedKey = case Size of
-1 ->
leo_nfs_file_handler:path_relative_to_abs(Key);
_ ->
Key
end,
Del2 = case Size =:= -1 andalso
is_empty_dir(NormalizedKey) of
true ->
DummyKey = filename:join(NormalizedKey, ?NFS_DUMMY_FILE4S3DIR),
case leo_gateway_rpc_handler:head(DummyKey) of
{ok, #?METADATA{del = 1}} ->
1;
_ ->
Del
end;
_ ->
Del
end,
FileName = filename:basename(Key),
case {Del2, FileName} of
{1,_} ->
readdir_create_resp(Path,
CurCookie - 1,
ReadDir,
Cookie,
EOF,
IsPlus,
Resp);
{_, ?NFS_DUMMY_FILE4S3DIR} ->
readdir_create_resp(Path,
CurCookie - 1,
ReadDir,
Cookie,
EOF,
IsPlus,
Resp);
_ ->
{ok, UID} = leo_nfs_state_ets:add_path(NormalizedKey),
NewResp = case IsPlus of
true ->
{inode(NormalizedKey),
FileName,
CurCookie,
meta2fattr3(Meta#?METADATA{key = NormalizedKey})
},
Resp
};
_ ->
{inode(NormalizedKey),
FileName,
CurCookie,
Resp
}
end,
?debug("readdir_create_resp", "key:~p cookie:~p~n",
[NormalizedKey, CurCookie]),
readdir_create_resp(Path,
CurCookie - 1,
ReadDir,
Cookie,
EOF,
IsPlus,
NewResp)
end.
@private
getattr(Path) ->
case leo_nfs_file_handler:binary_is_contained(Path, $/) of
true ->
@todo emulate directories
case leo_gateway_rpc_handler:head(Path) of
{ok, #?METADATA{del = 0} = Meta} ->
{ok, meta2fattr3(Meta)};
{ok, #?METADATA{del = 1}} ->
not_found;
{error, not_found} ->
Path4S3Dir = leo_nfs_file_handler:path_to_dir(Path),
case leo_nfs_file_handler:is_dir(Path4S3Dir) of
true ->
{ok, s3dir2fattr3(Path)};
false ->
not_found
end;
{error, Reason} ->
{error, Reason}
end;
false ->
case leo_s3_bucket:find_bucket_by_name(Path) of
{ok, Bucket} ->
Attr = bucket2fattr3(Bucket),
{ok, Attr};
not_found ->
not_found;
{error, Reason} ->
{error, Reason}
end
end.
@private
@todo to be replaced with truely unique i d supported by LeoFS future works
-spec(inode(binary() | string()) ->
integer()).
inode(Path) ->
<< F8:8/binary,_/binary >> = erlang:md5(Path),
Hex = leo_hex:binary_to_hex(F8),
leo_hex:hex_to_integer(Hex).
@private
-spec(meta2fattr3(#?METADATA{}) ->
tuple()).
meta2fattr3(#?METADATA{dsize = -1, key = Key}) ->
Path4S3Dir = leo_nfs_file_handler:path_to_dir(Key),
UT = get_dir_unix_timestamp(Path4S3Dir),
{'NF3DIR',
@todo actual size used at disk(LeoFS should return ` body + metadata + header / footer ` )
data used for special file(in Linux first is major , second is minor number )
inode(Key),
meta2fattr3(#?METADATA{key = Key, timestamp = TS, dsize = Size}) ->
UT = leo_date:greg_seconds_to_unixtime(TS),
{'NF3REG',
@todo actual size used at disk(LeoFS should return ` body + metadata + header / footer ` )
data used for special file(in Linux first is major , second is minor number )
@private
-spec(s3dir2fattr3(binary()) ->
tuple()).
s3dir2fattr3(Dir) ->
Path4S3Dir = leo_nfs_file_handler:path_to_dir(Dir),
UT = get_dir_unix_timestamp(Path4S3Dir),
{'NF3DIR',
@todo actual size used at disk(LeoFS should return ` body + metadata + header / footer ` )
data used for special file(in Linux first is major , second is minor number )
@private
-spec(bucket2fattr3(#?BUCKET{}) ->
tuple()).
bucket2fattr3(Bucket) ->
UT = leo_date:greg_seconds_to_unixtime(Bucket#?BUCKET.last_modified_at),
{'NF3DIR',
@todo directory size
@todo actual size used at disk
data used for special file(in Linux first is major , second is minor number )
@private
get_dir_unix_timestamp(_Dir) ->
= = = For 1.4
{ ok , } - >
Now = calendar : datetime_to_gregorian_seconds(calendar : ( ) ) ,
Now = calendar:datetime_to_gregorian_seconds(calendar:universal_time()),
leo_date:greg_seconds_to_unixtime(Now).
|
8316cccfd6a3b560ebdd92718ca9e0deeae2c787e4479f381646293c88f7aa87 | souenzzo/souenzzo.github.io | helper.clj | (ns stackfriend.helper)
(defn ^Throwable create-exception
[]
(ex-info "" {}))
(defn simple-exception
[]
(let [p (promise)]
(.start (Thread. (fn []
(let [x (create-exception)]
(deliver p x)))))
@p))
| null | https://raw.githubusercontent.com/souenzzo/souenzzo.github.io/30a811c4e5633ad07bba1d58d19eb091dac222e9/stackfriend/test/stackfriend/helper.clj | clojure | (ns stackfriend.helper)
(defn ^Throwable create-exception
[]
(ex-info "" {}))
(defn simple-exception
[]
(let [p (promise)]
(.start (Thread. (fn []
(let [x (create-exception)]
(deliver p x)))))
@p))
| |
eec60fce6bae1fe69064f87be5e3db7d3c3425a4ac6e901cb03a4e41b19a335c | xapi-project/xen-api | test_vm.ml |
* Copyright ( C ) 2017 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* 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 .
* Copyright (C) 2017 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* 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.
*)
open Test_highlevel
module VMSetBiosStrings = Generic.MakeStateful (struct
module Io = struct
type input_t = (string * string) list
type output_t = ((string * string) list, exn) result
let pp_list_assoc fmt_fst fmt_snd =
Fmt.(Dump.list @@ pair ~sep:(any "=") fmt_fst fmt_snd)
let string_of_input_t = Fmt.(str "%a" (pp_list_assoc string string))
let string_of_output_t =
Fmt.(str "%a" Dump.(result ~ok:(pp_list_assoc string string) ~error:exn))
end
module State = Test_state.XapiDb
let name_label = "a"
let load_input __context _ =
ignore (Test_common.make_vm ~__context ~name_label ())
let extract_output __context value =
try
let self =
List.hd (Db.VM.get_by_name_label ~__context ~label:name_label)
in
Xapi_vm.set_bios_strings ~__context ~self ~value ;
Ok (Db.VM.get_bios_strings ~__context ~self)
with e -> Error e
let big_str = String.make (Constants.bios_string_limit_size + 1) 'x'
let non_printable_str1 = Printf.sprintf "xyz%c" (Char.chr 31)
let non_printable_str2 = Printf.sprintf "xyz%c" (Char.chr 127)
let bios_str1 = [("bios-vendor", "Test"); ("bios-version", "Test Inc. A08")]
let bios_str2 =
[
("system-manufacturer", "Test Inc.")
; ("system-product-name", "Test bios strings")
; ("system-version", "8.1.1 SP1 build 8901")
; ("system-serial-number", "test-test-test-test")
]
let bios_str3 = [("enclosure-asset-tag", "testassettag12345")]
let bios_str4 =
[
("baseboard-manufacturer", "TestB Inc.")
; ("baseboard-product-name", "TestB pro")
; ("baseboard-version", "TestB v1.0")
; ("baseboard-serial-number", "TestB s12345")
; ("baseboard-asset-tag", "TestB asset")
; ("baseboard-location-in-chassis", "TestB loc")
]
let default_settings =
[
("bios-vendor", "Xen")
; ("bios-version", "")
; ("system-manufacturer", "Xen")
; ("system-product-name", "HVM domU")
; ("system-version", "")
; ("system-serial-number", "")
; ("baseboard-manufacturer", "")
; ("baseboard-product-name", "")
; ("baseboard-version", "")
; ("baseboard-serial-number", "")
; ("baseboard-asset-tag", "")
; ("baseboard-location-in-chassis", "")
; ("enclosure-asset-tag", "")
; ("hp-rombios", "")
; ("oem-1", "Xen")
; ("oem-2", "MS_VM_CERT/SHA1/bdbeb6e0a816d43fa6d3fe8aaef04c2bad9d3e3d")
]
let update_list dl nl =
List.map
(fun (k, v) ->
if List.mem_assoc k nl then (k, List.assoc k nl) else (k, v)
)
dl
let rec combination (l : ('a * 'b) list list) =
match l with
| [] ->
[]
| [hd] ->
[hd]
| hd :: tl ->
let r = combination tl in
(hd :: List.map (fun v -> hd @ v) r) @ r
let tests =
(* Correct value *)
let valid_settings =
combination [bios_str1; bios_str2; bios_str3; bios_str4]
in
let tests =
List.concat
[
List.map
(fun settings ->
(settings, Ok (update_list default_settings settings))
)
valid_settings
; [
Invalid BIOS string key
( [("xxxx", "test")]
, Error
Api_errors.(
Server_error (invalid_value, ["xxxx"; "Unknown key"])
)
)
; (* Empty value *)
( [("enclosure-asset-tag", "")]
, Error
Api_errors.(
Server_error
( invalid_value
, ["enclosure-asset-tag"; "Value provided is empty"]
)
)
)
Value having more than 512 charactors
( [("enclosure-asset-tag", big_str)]
, Error
Api_errors.(
Server_error
( invalid_value
, [
"enclosure-asset-tag"
; Printf.sprintf "%s has length more than %d characters"
big_str Constants.bios_string_limit_size
]
)
)
)
; (* Value having non printable ascii characters *)
( [("enclosure-asset-tag", non_printable_str1)]
, Error
Api_errors.(
Server_error
( invalid_value
, [
"enclosure-asset-tag"
; non_printable_str1
^ " has non-printable ASCII characters"
]
)
)
)
; ( [("enclosure-asset-tag", non_printable_str2)]
, Error
Api_errors.(
Server_error
( invalid_value
, [
"enclosure-asset-tag"
; non_printable_str2
^ " has non-printable ASCII characters"
]
)
)
)
]
]
in
`QuickAndAutoDocumented tests
end)
let tests = [("test_vm_set_bios_strings", VMSetBiosStrings.tests)]
| null | https://raw.githubusercontent.com/xapi-project/xen-api/47fae74032aa6ade0fc12e867c530eaf2a96bf75/ocaml/tests/test_vm.ml | ocaml | Correct value
Empty value
Value having non printable ascii characters |
* Copyright ( C ) 2017 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* 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 .
* Copyright (C) 2017 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* 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.
*)
open Test_highlevel
module VMSetBiosStrings = Generic.MakeStateful (struct
module Io = struct
type input_t = (string * string) list
type output_t = ((string * string) list, exn) result
let pp_list_assoc fmt_fst fmt_snd =
Fmt.(Dump.list @@ pair ~sep:(any "=") fmt_fst fmt_snd)
let string_of_input_t = Fmt.(str "%a" (pp_list_assoc string string))
let string_of_output_t =
Fmt.(str "%a" Dump.(result ~ok:(pp_list_assoc string string) ~error:exn))
end
module State = Test_state.XapiDb
let name_label = "a"
let load_input __context _ =
ignore (Test_common.make_vm ~__context ~name_label ())
let extract_output __context value =
try
let self =
List.hd (Db.VM.get_by_name_label ~__context ~label:name_label)
in
Xapi_vm.set_bios_strings ~__context ~self ~value ;
Ok (Db.VM.get_bios_strings ~__context ~self)
with e -> Error e
let big_str = String.make (Constants.bios_string_limit_size + 1) 'x'
let non_printable_str1 = Printf.sprintf "xyz%c" (Char.chr 31)
let non_printable_str2 = Printf.sprintf "xyz%c" (Char.chr 127)
let bios_str1 = [("bios-vendor", "Test"); ("bios-version", "Test Inc. A08")]
let bios_str2 =
[
("system-manufacturer", "Test Inc.")
; ("system-product-name", "Test bios strings")
; ("system-version", "8.1.1 SP1 build 8901")
; ("system-serial-number", "test-test-test-test")
]
let bios_str3 = [("enclosure-asset-tag", "testassettag12345")]
let bios_str4 =
[
("baseboard-manufacturer", "TestB Inc.")
; ("baseboard-product-name", "TestB pro")
; ("baseboard-version", "TestB v1.0")
; ("baseboard-serial-number", "TestB s12345")
; ("baseboard-asset-tag", "TestB asset")
; ("baseboard-location-in-chassis", "TestB loc")
]
let default_settings =
[
("bios-vendor", "Xen")
; ("bios-version", "")
; ("system-manufacturer", "Xen")
; ("system-product-name", "HVM domU")
; ("system-version", "")
; ("system-serial-number", "")
; ("baseboard-manufacturer", "")
; ("baseboard-product-name", "")
; ("baseboard-version", "")
; ("baseboard-serial-number", "")
; ("baseboard-asset-tag", "")
; ("baseboard-location-in-chassis", "")
; ("enclosure-asset-tag", "")
; ("hp-rombios", "")
; ("oem-1", "Xen")
; ("oem-2", "MS_VM_CERT/SHA1/bdbeb6e0a816d43fa6d3fe8aaef04c2bad9d3e3d")
]
let update_list dl nl =
List.map
(fun (k, v) ->
if List.mem_assoc k nl then (k, List.assoc k nl) else (k, v)
)
dl
let rec combination (l : ('a * 'b) list list) =
match l with
| [] ->
[]
| [hd] ->
[hd]
| hd :: tl ->
let r = combination tl in
(hd :: List.map (fun v -> hd @ v) r) @ r
let tests =
let valid_settings =
combination [bios_str1; bios_str2; bios_str3; bios_str4]
in
let tests =
List.concat
[
List.map
(fun settings ->
(settings, Ok (update_list default_settings settings))
)
valid_settings
; [
Invalid BIOS string key
( [("xxxx", "test")]
, Error
Api_errors.(
Server_error (invalid_value, ["xxxx"; "Unknown key"])
)
)
( [("enclosure-asset-tag", "")]
, Error
Api_errors.(
Server_error
( invalid_value
, ["enclosure-asset-tag"; "Value provided is empty"]
)
)
)
Value having more than 512 charactors
( [("enclosure-asset-tag", big_str)]
, Error
Api_errors.(
Server_error
( invalid_value
, [
"enclosure-asset-tag"
; Printf.sprintf "%s has length more than %d characters"
big_str Constants.bios_string_limit_size
]
)
)
)
( [("enclosure-asset-tag", non_printable_str1)]
, Error
Api_errors.(
Server_error
( invalid_value
, [
"enclosure-asset-tag"
; non_printable_str1
^ " has non-printable ASCII characters"
]
)
)
)
; ( [("enclosure-asset-tag", non_printable_str2)]
, Error
Api_errors.(
Server_error
( invalid_value
, [
"enclosure-asset-tag"
; non_printable_str2
^ " has non-printable ASCII characters"
]
)
)
)
]
]
in
`QuickAndAutoDocumented tests
end)
let tests = [("test_vm_set_bios_strings", VMSetBiosStrings.tests)]
|
a7bc2d04d89e95126be6fbacfef3ad28531965956ffac68560ac75ccaa2e7efc | jsdw/jsdw.me | examples.hs | # LANGUAGE FlexibleContexts #
-- I import qualified so that it's clear which
functions are from the parsec library :
import qualified Text.Parsec as Parsec
-- I am the choice and optional error message infix operator, used later:
import Text.Parsec ((<?>))
-- Imported so we can play with applicative things later.
-- not qualified as mostly infix operators we'll be using.
import Control.Applicative
-- Get the Identity monad from here:
import Control.Monad.Identity (Identity)
-- alias parseTest for more concise usage in my examples:
parse rule text = Parsec.parse rule "(source)" text
-- we can catch success and failure by matching Left or Right
-- from something returned by the parse function:
error_example = do
let result = parse (Parsec.char 'H') "Hello"
case result of
Right _ -> putStrLn "success!"
Left _ -> putStrLn "whoops, error"
# # # combining rules # # #
-- this looks for letters, then spaces, then digits.
-- we then return letters and digits in a tuple.
myParser :: Parsec.Parsec String () (String,String)
myParser = do
letters <- Parsec.many1 Parsec.letter
Parsec.spaces
digits <- Parsec.many1 Parsec.digit
return (letters,digits)
-- these type signatures are equivalent:
myParser1 :: Parsec.ParsecT String () Identity (String,String)
myParser1 = myParser
myParser2 :: Parsec.Parsec String () (String,String)
myParser2 = myParser
-- separate by comma (optionally surrounded by spaces)
mySeparator :: Parsec.Parsec String () ()
mySeparator = Parsec.spaces >> Parsec.char ',' >> Parsec.spaces
--the above is the same as:
-- mySeparator = do
-- Parsec.spaces
-- Parsec.char ','
-- Parsec.spaces
-- I want to return a list of pairs, this time.
myPairs :: Parsec.Parsec String () [(String,String)]
myPairs = Parsec.many $ do
pair <- myParser
mySeparator
return pair
-- I want to return a list of pairs with an optional end separator.
myPairs2 :: Parsec.Parsec String () [(String,String)]
myPairs2 = Parsec.many $ do
pair <- myParser
Parsec.choice [Parsec.eof, mySeparator]
return pair
-- I want to return a list of pairs as above using a built in helper:
myPairs2a :: Parsec.Parsec String () [(String,String)]
myPairs2a = Parsec.endBy myParser mySeparator
-- I want to return a list of pairs without a final separator:
myPairs2b :: Parsec.Parsec String () [(String,String)]
myPairs2b = Parsec.sepBy myParser mySeparator
-- The abovem but using the choice infix operator instead
myPairs3 :: Parsec.Parsec String () [(String,String)]
myPairs3 = Parsec.many $ do
pair <- myParser
Parsec.eof <|> mySeparator
return pair
-- parsing either hello or howdy without lookahead:
helloOrHowdy :: Parsec.Parsec String () String
helloOrHowdy = do
first <- Parsec.char 'h'
rest <- Parsec.string "ello" <|> Parsec.string "owdy"
return (first:rest)
hello or howdy made more concise by using Parsec.try to catch failure and rewind :
helloOrHowdy2 :: Parsec.Parsec String () String
helloOrHowdy2 = Parsec.try (Parsec.string "hello") <|> Parsec.string "howdy"
-- parse a basic greeting:
greeting :: Parsec.Parsec String () String
greeting = do
Parsec.char 'h'
Parsec.string "olla" <|> Parsec.string "ello"
return "greeting"
--parse a custom greeting with a custom error message on failure:
greeting2 :: Parsec.Parsec String () String
greeting2 = Parsec.try greeting <?> "a greeting!"
-- applicative style:
myParserApp :: Parsec.Parsec String () (String,String)
myParserApp = (,) <$> Parsec.many1 Parsec.letter <*> (Parsec.spaces *> Parsec.many1 Parsec.digit)
-- using basic state in parsers:
matches char ' h ' , incrementing int state by 1
-- each time one is seen.
hCountParser :: Parsec.Parsec String Int ()
hCountParser = do
Parsec.char 'h'
c <- Parsec.getState
let c' = c+1
Parsec.putState c'
return ()
hCountParser' :: Parsec.Parsec String Int ()
hCountParser' = do
Parsec.char 'h'
Parsec.modifyState (\c -> c+1)
return ()
-- parse as many h's as we can, then return the state
-- to see how many there were
getHs = Parsec.runParser (Parsec.many hCountParser >> Parsec.getState) 0 "" "hhhhhhhhhhhhellooo"
| null | https://raw.githubusercontent.com/jsdw/jsdw.me/da25ce265afbb8facbe902aae7a5c2a4d88c1f11/content/posts/haskell-parsec-basics/examples.hs | haskell | I import qualified so that it's clear which
I am the choice and optional error message infix operator, used later:
Imported so we can play with applicative things later.
not qualified as mostly infix operators we'll be using.
Get the Identity monad from here:
alias parseTest for more concise usage in my examples:
we can catch success and failure by matching Left or Right
from something returned by the parse function:
this looks for letters, then spaces, then digits.
we then return letters and digits in a tuple.
these type signatures are equivalent:
separate by comma (optionally surrounded by spaces)
the above is the same as:
mySeparator = do
Parsec.spaces
Parsec.char ','
Parsec.spaces
I want to return a list of pairs, this time.
I want to return a list of pairs with an optional end separator.
I want to return a list of pairs as above using a built in helper:
I want to return a list of pairs without a final separator:
The abovem but using the choice infix operator instead
parsing either hello or howdy without lookahead:
parse a basic greeting:
parse a custom greeting with a custom error message on failure:
applicative style:
using basic state in parsers:
each time one is seen.
parse as many h's as we can, then return the state
to see how many there were | # LANGUAGE FlexibleContexts #
functions are from the parsec library :
import qualified Text.Parsec as Parsec
import Text.Parsec ((<?>))
import Control.Applicative
import Control.Monad.Identity (Identity)
parse rule text = Parsec.parse rule "(source)" text
error_example = do
let result = parse (Parsec.char 'H') "Hello"
case result of
Right _ -> putStrLn "success!"
Left _ -> putStrLn "whoops, error"
# # # combining rules # # #
myParser :: Parsec.Parsec String () (String,String)
myParser = do
letters <- Parsec.many1 Parsec.letter
Parsec.spaces
digits <- Parsec.many1 Parsec.digit
return (letters,digits)
myParser1 :: Parsec.ParsecT String () Identity (String,String)
myParser1 = myParser
myParser2 :: Parsec.Parsec String () (String,String)
myParser2 = myParser
mySeparator :: Parsec.Parsec String () ()
mySeparator = Parsec.spaces >> Parsec.char ',' >> Parsec.spaces
myPairs :: Parsec.Parsec String () [(String,String)]
myPairs = Parsec.many $ do
pair <- myParser
mySeparator
return pair
myPairs2 :: Parsec.Parsec String () [(String,String)]
myPairs2 = Parsec.many $ do
pair <- myParser
Parsec.choice [Parsec.eof, mySeparator]
return pair
myPairs2a :: Parsec.Parsec String () [(String,String)]
myPairs2a = Parsec.endBy myParser mySeparator
myPairs2b :: Parsec.Parsec String () [(String,String)]
myPairs2b = Parsec.sepBy myParser mySeparator
myPairs3 :: Parsec.Parsec String () [(String,String)]
myPairs3 = Parsec.many $ do
pair <- myParser
Parsec.eof <|> mySeparator
return pair
helloOrHowdy :: Parsec.Parsec String () String
helloOrHowdy = do
first <- Parsec.char 'h'
rest <- Parsec.string "ello" <|> Parsec.string "owdy"
return (first:rest)
hello or howdy made more concise by using Parsec.try to catch failure and rewind :
helloOrHowdy2 :: Parsec.Parsec String () String
helloOrHowdy2 = Parsec.try (Parsec.string "hello") <|> Parsec.string "howdy"
greeting :: Parsec.Parsec String () String
greeting = do
Parsec.char 'h'
Parsec.string "olla" <|> Parsec.string "ello"
return "greeting"
greeting2 :: Parsec.Parsec String () String
greeting2 = Parsec.try greeting <?> "a greeting!"
myParserApp :: Parsec.Parsec String () (String,String)
myParserApp = (,) <$> Parsec.many1 Parsec.letter <*> (Parsec.spaces *> Parsec.many1 Parsec.digit)
matches char ' h ' , incrementing int state by 1
hCountParser :: Parsec.Parsec String Int ()
hCountParser = do
Parsec.char 'h'
c <- Parsec.getState
let c' = c+1
Parsec.putState c'
return ()
hCountParser' :: Parsec.Parsec String Int ()
hCountParser' = do
Parsec.char 'h'
Parsec.modifyState (\c -> c+1)
return ()
getHs = Parsec.runParser (Parsec.many hCountParser >> Parsec.getState) 0 "" "hhhhhhhhhhhhellooo"
|
1a20dfd6c9226823802195874420efb8e23ba604180cca42f66f0de0f24087cb | cljfx/cljfx | renderer.clj | (ns cljfx.renderer
"Part of a public API"
(:require [cljfx.lifecycle :as lifecycle]
[cljfx.platform :as platform]))
(set! *warn-on-reflection* true)
(defn- complete-rendering [renderer desc component]
(let [with-component (assoc renderer :component component)]
(if (= desc (:desc renderer))
(dissoc with-component :request)
(assoc with-component :request (promise)))))
(defn- perform-render
"Re-renders component on fx thread
Since advancing is a mutating operation on dom, it can't be in `swap!` which
may retry it. During advancing new render request may arrive, in that case we
enqueue another re-render component to not lock JavaFX application thread"
[*renderer]
(let [{:keys [desc component render-fn request] :as state} @*renderer
[new-component e] (try
[(render-fn component desc) nil]
(catch Throwable e
[component e]))
new-renderer (swap! *renderer complete-rendering desc new-component)]
(when (some? e)
((:error-handler state) e))
(deliver request new-component)
(when (:request new-renderer)
(platform/run-later (perform-render *renderer)))))
(defn- or-new-promise [x]
(or x (promise)))
(defn- request-rendering-with-desc [renderer desc]
(-> renderer
(assoc :desc desc)
(update :request or-new-promise)))
(defn- request-render [*renderer desc]
(let [[old new] (swap-vals! *renderer request-rendering-with-desc desc)]
(when-not (:request old)
(if (nil? (:component old))
(platform/on-fx-thread (perform-render *renderer))
(platform/run-later (perform-render *renderer))))
(:request new)))
(defn- render-component
"Advance rendered component with special semantics for nil (meaning absence)
This allows to create, advance and delete components in single function"
[lifecycle component desc opts]
(cond
(and (nil? component) (nil? desc))
nil
(nil? component)
(lifecycle/create lifecycle desc opts)
(nil? desc)
(do (lifecycle/delete lifecycle component opts) nil)
:else
(lifecycle/advance lifecycle component desc opts)))
(defn default-error-handler [e]
(if (instance? Exception e)
(.printStackTrace ^Exception e)
(throw e)))
(defn create
([middleware opts]
(create middleware opts default-error-handler))
([middleware opts error-handler]
(let [lifecycle (middleware lifecycle/root)
*renderer (atom {:component nil
:error-handler error-handler
:render-fn #(render-component lifecycle %1 %2 opts)})]
(fn render
([]
(let [desc (:desc @*renderer)]
@(render nil)
(render desc)))
([desc]
(request-render *renderer desc))))))
(defn mount [*ref renderer]
(add-watch *ref [`mount renderer] #(renderer %4))
(renderer @*ref))
(defn unmount [*ref renderer]
(remove-watch *ref [`mount renderer])
(renderer nil))
| null | https://raw.githubusercontent.com/cljfx/cljfx/acbe9972e99abdce2d88d4595aa90f4d7c865629/src/cljfx/renderer.clj | clojure | (ns cljfx.renderer
"Part of a public API"
(:require [cljfx.lifecycle :as lifecycle]
[cljfx.platform :as platform]))
(set! *warn-on-reflection* true)
(defn- complete-rendering [renderer desc component]
(let [with-component (assoc renderer :component component)]
(if (= desc (:desc renderer))
(dissoc with-component :request)
(assoc with-component :request (promise)))))
(defn- perform-render
"Re-renders component on fx thread
Since advancing is a mutating operation on dom, it can't be in `swap!` which
may retry it. During advancing new render request may arrive, in that case we
enqueue another re-render component to not lock JavaFX application thread"
[*renderer]
(let [{:keys [desc component render-fn request] :as state} @*renderer
[new-component e] (try
[(render-fn component desc) nil]
(catch Throwable e
[component e]))
new-renderer (swap! *renderer complete-rendering desc new-component)]
(when (some? e)
((:error-handler state) e))
(deliver request new-component)
(when (:request new-renderer)
(platform/run-later (perform-render *renderer)))))
(defn- or-new-promise [x]
(or x (promise)))
(defn- request-rendering-with-desc [renderer desc]
(-> renderer
(assoc :desc desc)
(update :request or-new-promise)))
(defn- request-render [*renderer desc]
(let [[old new] (swap-vals! *renderer request-rendering-with-desc desc)]
(when-not (:request old)
(if (nil? (:component old))
(platform/on-fx-thread (perform-render *renderer))
(platform/run-later (perform-render *renderer))))
(:request new)))
(defn- render-component
"Advance rendered component with special semantics for nil (meaning absence)
This allows to create, advance and delete components in single function"
[lifecycle component desc opts]
(cond
(and (nil? component) (nil? desc))
nil
(nil? component)
(lifecycle/create lifecycle desc opts)
(nil? desc)
(do (lifecycle/delete lifecycle component opts) nil)
:else
(lifecycle/advance lifecycle component desc opts)))
(defn default-error-handler [e]
(if (instance? Exception e)
(.printStackTrace ^Exception e)
(throw e)))
(defn create
([middleware opts]
(create middleware opts default-error-handler))
([middleware opts error-handler]
(let [lifecycle (middleware lifecycle/root)
*renderer (atom {:component nil
:error-handler error-handler
:render-fn #(render-component lifecycle %1 %2 opts)})]
(fn render
([]
(let [desc (:desc @*renderer)]
@(render nil)
(render desc)))
([desc]
(request-render *renderer desc))))))
(defn mount [*ref renderer]
(add-watch *ref [`mount renderer] #(renderer %4))
(renderer @*ref))
(defn unmount [*ref renderer]
(remove-watch *ref [`mount renderer])
(renderer nil))
| |
05847a1e6aa571350a45af66505e7321ddbf2f542660f48e8a9d16eda67153d0 | Quviq/webdrv | webdrv_cap.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2013 , Quviq AB
%%%
%%% @doc
Handling of capabilities for WebDriver protocol
%%%
%%% <h2>License</h2>
%%% <pre>
%%% 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. </pre>
%%% @end
%%%-------------------------------------------------------------------
-module(webdrv_cap).
-include("../include/webdrv.hrl").
-export([default/0, default_browser/1,
to_json/1,
default_firefox/0, default_chrome/0, default_htmlunit/0,
default_safari/1]).
%% @doc Return the default capability record.
-spec default() -> #capability{}.
default() ->
#capability{ }.
%% @hidden Just for the tests
-spec default_browser(string() | atom()) -> #capability{}.
default_browser(Browser) when is_atom(Browser) ->
(default())#capability{ browserName = list_to_binary(atom_to_list(Browser))};
default_browser(Browser) when is_list(Browser) ->
(default())#capability{ browserName = list_to_binary(Browser)}.
%% @doc Return the default capability with browser set to <tt>chrome</tt>.
-spec default_chrome() -> #capability{}.
default_chrome() ->
(default())#capability{ browserName = <<"chrome">>, version = <<"">> }.
%% @doc Return the default capability with browser set to <tt>htmlunit</tt>.
-spec default_htmlunit() -> #capability{}.
default_htmlunit() ->
(default())#capability{ browserName = <<"htmlunit">>, version = <<"">> }.
%% @doc Return the default capability with browser set to <tt>firefox</tt>.
-spec default_firefox() -> #capability{}.
default_firefox() ->
(default())#capability{ browserName = <<"firefox">> }.
%% @doc Return the default capability with browser set to <tt>firefox</tt>.
-spec default_safari(string()) -> #capability{}.
default_safari(Device) ->
(default())#capability{ browserName = <<"Safari">>, device = Device }.
%% @doc Convert a capability (possibly <tt>null</tt>) to JSON format. Function is
%% idempotent, i.e. converting an already converted object is fine.
-spec to_json(capability()) -> jsonobj() | null.
to_json(C = #capability{}) ->
{obj,
[ {Field, Arg1} || {Field, Arg1, Arg2} <- lists:zip3(record_info(fields, capability),
tl(tuple_to_list(C)),
tl(tuple_to_list(#capability{}))),
(Arg1 =/= Arg2 orelse Field == javascriptEnabled)]};
to_json(Obj = {obj, _Any}) -> Obj;
to_json(null) -> null.
| null | https://raw.githubusercontent.com/Quviq/webdrv/7ceaf1f67d834e841ca0133b4bf899a9fa2db6bb/src/webdrv_cap.erl | erlang | -------------------------------------------------------------------
@doc
<h2>License</h2>
<pre>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
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. </pre>
@end
-------------------------------------------------------------------
@doc Return the default capability record.
@hidden Just for the tests
@doc Return the default capability with browser set to <tt>chrome</tt>.
@doc Return the default capability with browser set to <tt>htmlunit</tt>.
@doc Return the default capability with browser set to <tt>firefox</tt>.
@doc Return the default capability with browser set to <tt>firefox</tt>.
@doc Convert a capability (possibly <tt>null</tt>) to JSON format. Function is
idempotent, i.e. converting an already converted object is fine. | @author < >
( C ) 2013 , Quviq AB
Handling of capabilities for WebDriver protocol
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial 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
-module(webdrv_cap).
-include("../include/webdrv.hrl").
-export([default/0, default_browser/1,
to_json/1,
default_firefox/0, default_chrome/0, default_htmlunit/0,
default_safari/1]).
-spec default() -> #capability{}.
default() ->
#capability{ }.
-spec default_browser(string() | atom()) -> #capability{}.
default_browser(Browser) when is_atom(Browser) ->
(default())#capability{ browserName = list_to_binary(atom_to_list(Browser))};
default_browser(Browser) when is_list(Browser) ->
(default())#capability{ browserName = list_to_binary(Browser)}.
-spec default_chrome() -> #capability{}.
default_chrome() ->
(default())#capability{ browserName = <<"chrome">>, version = <<"">> }.
-spec default_htmlunit() -> #capability{}.
default_htmlunit() ->
(default())#capability{ browserName = <<"htmlunit">>, version = <<"">> }.
-spec default_firefox() -> #capability{}.
default_firefox() ->
(default())#capability{ browserName = <<"firefox">> }.
-spec default_safari(string()) -> #capability{}.
default_safari(Device) ->
(default())#capability{ browserName = <<"Safari">>, device = Device }.
-spec to_json(capability()) -> jsonobj() | null.
to_json(C = #capability{}) ->
{obj,
[ {Field, Arg1} || {Field, Arg1, Arg2} <- lists:zip3(record_info(fields, capability),
tl(tuple_to_list(C)),
tl(tuple_to_list(#capability{}))),
(Arg1 =/= Arg2 orelse Field == javascriptEnabled)]};
to_json(Obj = {obj, _Any}) -> Obj;
to_json(null) -> null.
|
e1a0bfed29fc29904eb5488933b2be59e9ce9f14b4fcedb67c9cefbe2c20d4e2 | zalando-stups/kio | api.clj | ; Copyright 2015 Zalando SE
;
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 org.zalando.stups.kio.api
(:require [org.zalando.stups.friboo.system.http :refer [def-http-component]]
[org.zalando.stups.friboo.config :refer [require-config]]
[org.zalando.stups.friboo.ring :refer :all]
[org.zalando.stups.friboo.log :as log]
[org.zalando.stups.friboo.user :as u]
[org.zalando.stups.friboo.auth :as auth]
[org.zalando.stups.kio.sql :as sql]
[org.zalando.stups.kio.audit :as audit]
[org.zalando.stups.kio.metrics :as metrics]
[clj-time.coerce :as tcoerce]
[io.sarnowski.swagger1st.util.api :as api]
[ring.util.response :refer :all]
[clojure.string :as str]
[clojure.java.jdbc :refer [with-db-transaction]]
[clojure.core.memoize :as memo]
[clj-http.client :as http]
[cheshire.core :as json]))
; define the API component and its dependencies
(def-http-component API "api/kio-api.yaml" [db http-audit-logger app-metrics] :dependencies-as-map true)
(def default-http-configuration
{:http-port 8080})
TODO should be replaced with , but requires test changes
(defn from-token
[request field & return-default]
(get-in request
[:tokeninfo field]
(when return-default return-default)))
(defn tokeninfo
[request]
(clojure.walk/keywordize-keys (:tokeninfo request)))
(defn require-uid
"Checks whether uid is present on token, throws 403 otherwise"
[request]
(when-not (from-token request "uid")
(log/warn "ACCESS DENIED (unauthorized) because no uid in tokeninfo.")
(api/throw-error 403 "Unauthorized")))
(defn is-admin-in-realm?
[uid realm {:keys [configuration]}]
(when (and uid realm)
(let [uid-with-realm (str realm "/" uid)
allowed-uids-with-realm (or (:admin-users configuration) "")
allowed (set (str/split allowed-uids-with-realm #","))]
(allowed uid-with-realm))))
(defn require-write-authorization
"If user is employee, check that is in correct team.
If user is service, check that it has application.write scope and is correct team.
If user is listed as admin grant access to user"
[request team]
(require-uid request)
(let [realm (str "/" (u/require-realms #{"employees" "services"} request))
uid (from-token request "uid")
is-admin? (is-admin-in-realm? uid realm request)]
(when-not is-admin?
(let [has-auth? (auth/get-auth request team)
is-robot? (= "/services" realm)
has-scope? (set (from-token request "scope"))]
(when-not has-auth?
(api/throw-error 403 "Unauthorized"))
(when (and
is-robot?
(not (has-scope? "application.write")))
(api/throw-error 403 "Unauthorized"))))))
;; applications
;;#overriding-the-cache-keys
(defn ^{:clojure.core.memoize/args-fn first}
read-applications-into-string
[params db-spec]
(let [result (sql/cmd-read-applications params {:connection db-spec})]
(when (not-empty result)
(json/generate-string result))))
(def read-application-memo
(memo/ttl #'read-applications-into-string :ttl/threshold 120000))
(defn read-applications
[{:keys [search modified_before modified_after team_id incident_contact active]} request {:keys [db]}]
(u/require-realms #{"employees" "services"} request)
(let [conn {:connection db}
params {:searchquery search
:team_id team_id
:incident_contact incident_contact
:active active
:modified_before (tcoerce/to-sql-time modified_before)
:modified_after (tcoerce/to-sql-time modified_after)}]
(if (nil? search)
(do
(log/debug "Read all applications.")
(-> (if (and (nil? team_id) (nil? incident_contact))
(read-application-memo params db)
(sql/cmd-read-applications params conn))
(response)
(content-type-json)))
(do
(log/debug "Search in applications with term %s." search)
(-> (sql/cmd-search-applications params conn)
(response)
(content-type-json))))))
(defn load-application
"Loads a single application by ID, used for team checks."
[application_id db]
(-> (sql/cmd-read-application {:id application_id}
{:connection db})
(first)))
(defn enrich-application
"Adds calculated field(s) to an application"
[application]
(assoc application :required_approvers (if (= (:criticality_level application) 1) 1 2)))
(defn enrich-applications
[applications]
(map enrich-application applications))
(defn read-application [{:keys [application_id]} request {:keys [db]}]
(u/require-realms #{"employees" "services"} request)
(log/debug "Read application %s." application_id)
(-> (sql/cmd-read-application {:id application_id} {:connection db})
(enrich-applications)
(single-response)
(content-type-json)))
(defn team-exists? [request team]
(when-not (str/blank? team)
(let [magnificent-url (get-in request [:configuration :magnificent-url])
token (get-in request [:tokeninfo "access_token"])
response (http/get
(str magnificent-url "/teams/" team)
{:content-type :json
:oauth-token token
:throw-exceptions false})
status (:status response)]
(= 200 status))))
(defn default-fields [creator-user-id]
{:incident_contact nil
:specification_url nil
:documentation_url nil
:subtitle nil
:scm_url nil
:support_url nil
:service_url nil
:description nil
:specification_type nil
:publicly_accessible false
:criticality_level nil
:created_by creator-user-id})
(defn- value-not-nil? [[_ v]] (some? v))
(defn created-or-updated-app [app-id old-app new-app user-id]
{:pre [(map? new-app)
(not (clojure.string/blank? app-id))
(not (clojure.string/blank? user-id))]
:post [(map? %)
(seq %)
(= (:last_modified_by %) user-id)
(or (some? old-app)
(= (:created_by %) user-id))
(= (:id %) app-id)]}
(let [old-app (or old-app (default-fields user-id))
new-app (into {} (filter value-not-nil? new-app))
merged-fields (merge old-app new-app)]
(assoc merged-fields
:id app-id
:last_modified_by user-id)))
(defn create-or-update-application! [{:keys [application application_id]} request {:keys [db http-audit-logger]}]
(let [uid (from-token request "uid")
existing_application (load-application application_id db)
existing_team_id (:team_id existing_application)
team_id (:team_id application)]
(if (nil? existing_application)
(require-write-authorization request team_id)
(require-write-authorization request existing_team_id))
(if (or (= team_id existing_team_id)
(team-exists? request (:team_id application)))
(try
(let [app-to-save (created-or-updated-app application_id existing_application application uid)
log-fn (:log-fn http-audit-logger)]
(sql/cmd-create-or-update-application! app-to-save {:connection db})
(log-fn (audit/app-modified
(tokeninfo request)
app-to-save))
(log/audit "Created/updated application %s using data %s." application_id application)
(response nil))
(catch AssertionError err
(-> {:message (format "Internal inconsistency: %s" (.getMessage err))
:application_id application_id
:old-app existing_application
:new-app application
:uid uid}
(response)
(status 500)
(content-type-json))))
(-> {:message (format "Team %s does not exist." team_id)}
(response)
(status 400)
(content-type-json)))))
(defn read-application-approvals [_ request {:keys [app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-application-approvals-get)
(u/require-internal-user request)
(->> []
(response)
(content-type-json)))
;; versions
(defn read-versions-by-application [_ request {:keys [app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-versions-get)
(u/require-realms #{"employees" "services"} request)
(-> []
(response)
(content-type-json)))
(defn read-version-by-application [_ request {:keys [app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-version-get)
(u/require-realms #{"employees" "services"} request)
(-> (not-found {})
(content-type-json)))
(defn create-or-update-version! [{:keys [application_id]} request {:keys [db app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-version-put)
(if-let [application (load-application application_id db)]
(do
(require-write-authorization request (:team_id application))
(response nil))
(api/error 404 "application not found")))
;; approvals
(defn read-approvals-by-version [_ request {:keys [db app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-version-approvals-get)
(u/require-realms #{"employees" "services"} request)
(-> []
(response)
(content-type-json)))
(defn approve-version! [{:keys [application_id]} request {:keys [db app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-version-approvals-put)
(if-let [application (load-application application_id db)]
(do
(u/require-internal-team (:team_id application) request)
(response nil))
(api/error 404 "application not found")))
| null | https://raw.githubusercontent.com/zalando-stups/kio/d84dd2e27d155340c4d2ae45908a11d637563493/src/org/zalando/stups/kio/api.clj | clojure | Copyright 2015 Zalando SE
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.
define the API component and its dependencies
applications
#overriding-the-cache-keys
versions
approvals | Licensed under the Apache License , Version 2.0 ( the " License " )
distributed under the License is distributed on an " AS IS " BASIS ,
(ns org.zalando.stups.kio.api
(:require [org.zalando.stups.friboo.system.http :refer [def-http-component]]
[org.zalando.stups.friboo.config :refer [require-config]]
[org.zalando.stups.friboo.ring :refer :all]
[org.zalando.stups.friboo.log :as log]
[org.zalando.stups.friboo.user :as u]
[org.zalando.stups.friboo.auth :as auth]
[org.zalando.stups.kio.sql :as sql]
[org.zalando.stups.kio.audit :as audit]
[org.zalando.stups.kio.metrics :as metrics]
[clj-time.coerce :as tcoerce]
[io.sarnowski.swagger1st.util.api :as api]
[ring.util.response :refer :all]
[clojure.string :as str]
[clojure.java.jdbc :refer [with-db-transaction]]
[clojure.core.memoize :as memo]
[clj-http.client :as http]
[cheshire.core :as json]))
(def-http-component API "api/kio-api.yaml" [db http-audit-logger app-metrics] :dependencies-as-map true)
(def default-http-configuration
{:http-port 8080})
TODO should be replaced with , but requires test changes
(defn from-token
[request field & return-default]
(get-in request
[:tokeninfo field]
(when return-default return-default)))
(defn tokeninfo
[request]
(clojure.walk/keywordize-keys (:tokeninfo request)))
(defn require-uid
"Checks whether uid is present on token, throws 403 otherwise"
[request]
(when-not (from-token request "uid")
(log/warn "ACCESS DENIED (unauthorized) because no uid in tokeninfo.")
(api/throw-error 403 "Unauthorized")))
(defn is-admin-in-realm?
[uid realm {:keys [configuration]}]
(when (and uid realm)
(let [uid-with-realm (str realm "/" uid)
allowed-uids-with-realm (or (:admin-users configuration) "")
allowed (set (str/split allowed-uids-with-realm #","))]
(allowed uid-with-realm))))
(defn require-write-authorization
"If user is employee, check that is in correct team.
If user is service, check that it has application.write scope and is correct team.
If user is listed as admin grant access to user"
[request team]
(require-uid request)
(let [realm (str "/" (u/require-realms #{"employees" "services"} request))
uid (from-token request "uid")
is-admin? (is-admin-in-realm? uid realm request)]
(when-not is-admin?
(let [has-auth? (auth/get-auth request team)
is-robot? (= "/services" realm)
has-scope? (set (from-token request "scope"))]
(when-not has-auth?
(api/throw-error 403 "Unauthorized"))
(when (and
is-robot?
(not (has-scope? "application.write")))
(api/throw-error 403 "Unauthorized"))))))
(defn ^{:clojure.core.memoize/args-fn first}
read-applications-into-string
[params db-spec]
(let [result (sql/cmd-read-applications params {:connection db-spec})]
(when (not-empty result)
(json/generate-string result))))
(def read-application-memo
(memo/ttl #'read-applications-into-string :ttl/threshold 120000))
(defn read-applications
[{:keys [search modified_before modified_after team_id incident_contact active]} request {:keys [db]}]
(u/require-realms #{"employees" "services"} request)
(let [conn {:connection db}
params {:searchquery search
:team_id team_id
:incident_contact incident_contact
:active active
:modified_before (tcoerce/to-sql-time modified_before)
:modified_after (tcoerce/to-sql-time modified_after)}]
(if (nil? search)
(do
(log/debug "Read all applications.")
(-> (if (and (nil? team_id) (nil? incident_contact))
(read-application-memo params db)
(sql/cmd-read-applications params conn))
(response)
(content-type-json)))
(do
(log/debug "Search in applications with term %s." search)
(-> (sql/cmd-search-applications params conn)
(response)
(content-type-json))))))
(defn load-application
"Loads a single application by ID, used for team checks."
[application_id db]
(-> (sql/cmd-read-application {:id application_id}
{:connection db})
(first)))
(defn enrich-application
"Adds calculated field(s) to an application"
[application]
(assoc application :required_approvers (if (= (:criticality_level application) 1) 1 2)))
(defn enrich-applications
[applications]
(map enrich-application applications))
(defn read-application [{:keys [application_id]} request {:keys [db]}]
(u/require-realms #{"employees" "services"} request)
(log/debug "Read application %s." application_id)
(-> (sql/cmd-read-application {:id application_id} {:connection db})
(enrich-applications)
(single-response)
(content-type-json)))
(defn team-exists? [request team]
(when-not (str/blank? team)
(let [magnificent-url (get-in request [:configuration :magnificent-url])
token (get-in request [:tokeninfo "access_token"])
response (http/get
(str magnificent-url "/teams/" team)
{:content-type :json
:oauth-token token
:throw-exceptions false})
status (:status response)]
(= 200 status))))
(defn default-fields [creator-user-id]
{:incident_contact nil
:specification_url nil
:documentation_url nil
:subtitle nil
:scm_url nil
:support_url nil
:service_url nil
:description nil
:specification_type nil
:publicly_accessible false
:criticality_level nil
:created_by creator-user-id})
(defn- value-not-nil? [[_ v]] (some? v))
(defn created-or-updated-app [app-id old-app new-app user-id]
{:pre [(map? new-app)
(not (clojure.string/blank? app-id))
(not (clojure.string/blank? user-id))]
:post [(map? %)
(seq %)
(= (:last_modified_by %) user-id)
(or (some? old-app)
(= (:created_by %) user-id))
(= (:id %) app-id)]}
(let [old-app (or old-app (default-fields user-id))
new-app (into {} (filter value-not-nil? new-app))
merged-fields (merge old-app new-app)]
(assoc merged-fields
:id app-id
:last_modified_by user-id)))
(defn create-or-update-application! [{:keys [application application_id]} request {:keys [db http-audit-logger]}]
(let [uid (from-token request "uid")
existing_application (load-application application_id db)
existing_team_id (:team_id existing_application)
team_id (:team_id application)]
(if (nil? existing_application)
(require-write-authorization request team_id)
(require-write-authorization request existing_team_id))
(if (or (= team_id existing_team_id)
(team-exists? request (:team_id application)))
(try
(let [app-to-save (created-or-updated-app application_id existing_application application uid)
log-fn (:log-fn http-audit-logger)]
(sql/cmd-create-or-update-application! app-to-save {:connection db})
(log-fn (audit/app-modified
(tokeninfo request)
app-to-save))
(log/audit "Created/updated application %s using data %s." application_id application)
(response nil))
(catch AssertionError err
(-> {:message (format "Internal inconsistency: %s" (.getMessage err))
:application_id application_id
:old-app existing_application
:new-app application
:uid uid}
(response)
(status 500)
(content-type-json))))
(-> {:message (format "Team %s does not exist." team_id)}
(response)
(status 400)
(content-type-json)))))
(defn read-application-approvals [_ request {:keys [app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-application-approvals-get)
(u/require-internal-user request)
(->> []
(response)
(content-type-json)))
(defn read-versions-by-application [_ request {:keys [app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-versions-get)
(u/require-realms #{"employees" "services"} request)
(-> []
(response)
(content-type-json)))
(defn read-version-by-application [_ request {:keys [app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-version-get)
(u/require-realms #{"employees" "services"} request)
(-> (not-found {})
(content-type-json)))
(defn create-or-update-version! [{:keys [application_id]} request {:keys [db app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-version-put)
(if-let [application (load-application application_id db)]
(do
(require-write-authorization request (:team_id application))
(response nil))
(api/error 404 "application not found")))
(defn read-approvals-by-version [_ request {:keys [db app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-version-approvals-get)
(u/require-realms #{"employees" "services"} request)
(-> []
(response)
(content-type-json)))
(defn approve-version! [{:keys [application_id]} request {:keys [db app-metrics]}]
(metrics/mark-deprecation app-metrics :deprecation-version-approvals-put)
(if-let [application (load-application application_id db)]
(do
(u/require-internal-team (:team_id application) request)
(response nil))
(api/error 404 "application not found")))
|
a1ac5f2c7945a07e01a7f363cbb2ef6f7c142c0c3cc06b61a3629f93a9d4e058 | Clojure2D/clojure2d-examples | main.clj | (ns rt4.the-next-week.ch05b.main
(:require [fastmath.core :as m]
[fastmath.vector :as v]
[rt4.common :as common]
[rt4.the-next-week.ch05b.sphere :as sphere]
[rt4.the-next-week.ch05b.moving-sphere :as moving-sphere]
[rt4.the-next-week.ch05b.camera :as camera]
[rt4.the-next-week.ch05b.material :as material]
[rt4.the-next-week.ch05b.scene :as scene]
[rt4.the-next-week.ch05b.hittable-list :as hittable-list]
[rt4.the-next-week.ch05b.bvh :as bvh]
[fastmath.random :as r]
[rt4.the-next-week.ch05b.texture :as texture]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
;; camera
(def default-camera-def {:vfov 20.0
:lookfrom (v/vec3 13.0 2.0 3.0)
:lookat (v/vec3 0.0 0.0 0.0)
:vup (v/vec3 0.0 1.0 0.0)
:aperture 0.1
:focus-dist 10.0})
(def default-scene-def {:image-width 400
:samples-per-pixel 100})
(defn- make-balls
[world]
(reduce (fn [w [^long a ^long b]]
(let [choose-mat (r/drand)
center (v/vec3 (+ a (r/drand 0.9)) 0.2 (+ b (r/drand 0.9)))]
(if (> (v/mag (v/sub center (v/vec3 4.0 0.2 0.0))) 0.9)
(hittable-list/add w (cond
(< choose-mat 0.8)
(let [albedo (v/emult (common/random-vec3)
(common/random-vec3))
center2 (v/add center (v/vec3 0.0 (r/drand 0.5) 0.0))]
(->> (material/lambertian albedo)
(moving-sphere/sphere center center2 0.2)))
(< choose-mat 0.95)
(let [albedo (common/random-vec3 0.5 1.0)
fuzz (r/drand 0.5)]
(->> (material/metal albedo fuzz)
(sphere/sphere center 0.2)))
:else (->> (material/dielectric 1.5)
(sphere/sphere center 0.2))))
w)))
world (for [a (range -11 11) b (range -11 11)] [a b])))
(defn random-spheres [scene-def]
(let [camera (camera/camera default-camera-def)
checker (texture/color-checker-texture 0.32 (v/vec3 0.2 0.3 0.1) (v/vec3 0.9 0.9 0.9))
ground-material (material/lambertian checker)
material1 (material/dielectric 1.5)
material2 (material/lambertian (v/vec3 0.4 0.2 0.1))
material3 (material/metal (v/vec3 0.7 0.6 0.5) 0.0)
world (hittable-list/hittable-list (sphere/sphere (v/vec3 0.0 -1000.0 0.0) 1000.0 ground-material)
(sphere/sphere (v/vec3 0.0 1.0 0.0) 1.0 material1)
(sphere/sphere (v/vec3 -4.0 1.0 0.0) 1.0 material2)
(sphere/sphere (v/vec3 4.0 1.0 0.0) 1.0 material3))]
(scene/scene camera (-> world make-balls bvh/bvh-node) scene-def)))
(defn two-spheres [scene-def]
(let [camera (camera/camera (assoc default-camera-def :aperture 0.0))
checker (texture/color-checker-texture 0.32 (v/vec3 0.2 0.3 0.1) (v/vec3 0.9 0.9 0.9))
material (material/lambertian checker)
world (hittable-list/hittable-list (sphere/sphere (v/vec3 0.0 -10.0 0.0) 10.0 material)
(sphere/sphere (v/vec3 0.0 10.0 0.0) 10.0 material))]
(scene/scene camera (-> world bvh/bvh-node) scene-def)))
(defonce earth-texture
(texture/image-texture
""))
(defn earth [scene-def]
: ( v / vec3 0.0 0.0 12.0 ) yield different view than in the book
(let [camera (camera/camera (assoc default-camera-def :aperture 0.0))
earth-surface (material/lambertian earth-texture)
globe (sphere/sphere (v/vec3 0.0 0.0 0.0) 2.0 earth-surface)]
(scene/scene camera (hittable-list/hittable-list globe) scene-def)))
(defn two-perlin-spheres [scene-def]
(let [camera (camera/camera (assoc default-camera-def :aperture 0.0))
pertext (texture/noise-texture)
material (material/lambertian pertext)
world (hittable-list/hittable-list (sphere/sphere (v/vec3 0.0 -1000.0 0.0) 1000.0 material)
(sphere/sphere (v/vec3 0.0 2.0 0.0) 2.0 material))]
(scene/scene camera (-> world bvh/bvh-node) scene-def)))
(defn main
([] (main 0))
([^long scene] (main default-scene-def scene))
([scene-def ^long scene]
(let [scene-def (merge default-scene-def scene-def)
f (case scene
1 random-spheres
2 two-spheres
3 earth
4 two-perlin-spheres
two-perlin-spheres)]
(f scene-def))))
(def image (time (scene/render (main))))
(comment
(common/save image "results/rt4/the_next_week/ch05b.jpg"))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/the_next_week/ch05b/main.clj | clojure | camera | (ns rt4.the-next-week.ch05b.main
(:require [fastmath.core :as m]
[fastmath.vector :as v]
[rt4.common :as common]
[rt4.the-next-week.ch05b.sphere :as sphere]
[rt4.the-next-week.ch05b.moving-sphere :as moving-sphere]
[rt4.the-next-week.ch05b.camera :as camera]
[rt4.the-next-week.ch05b.material :as material]
[rt4.the-next-week.ch05b.scene :as scene]
[rt4.the-next-week.ch05b.hittable-list :as hittable-list]
[rt4.the-next-week.ch05b.bvh :as bvh]
[fastmath.random :as r]
[rt4.the-next-week.ch05b.texture :as texture]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(def default-camera-def {:vfov 20.0
:lookfrom (v/vec3 13.0 2.0 3.0)
:lookat (v/vec3 0.0 0.0 0.0)
:vup (v/vec3 0.0 1.0 0.0)
:aperture 0.1
:focus-dist 10.0})
(def default-scene-def {:image-width 400
:samples-per-pixel 100})
(defn- make-balls
[world]
(reduce (fn [w [^long a ^long b]]
(let [choose-mat (r/drand)
center (v/vec3 (+ a (r/drand 0.9)) 0.2 (+ b (r/drand 0.9)))]
(if (> (v/mag (v/sub center (v/vec3 4.0 0.2 0.0))) 0.9)
(hittable-list/add w (cond
(< choose-mat 0.8)
(let [albedo (v/emult (common/random-vec3)
(common/random-vec3))
center2 (v/add center (v/vec3 0.0 (r/drand 0.5) 0.0))]
(->> (material/lambertian albedo)
(moving-sphere/sphere center center2 0.2)))
(< choose-mat 0.95)
(let [albedo (common/random-vec3 0.5 1.0)
fuzz (r/drand 0.5)]
(->> (material/metal albedo fuzz)
(sphere/sphere center 0.2)))
:else (->> (material/dielectric 1.5)
(sphere/sphere center 0.2))))
w)))
world (for [a (range -11 11) b (range -11 11)] [a b])))
(defn random-spheres [scene-def]
(let [camera (camera/camera default-camera-def)
checker (texture/color-checker-texture 0.32 (v/vec3 0.2 0.3 0.1) (v/vec3 0.9 0.9 0.9))
ground-material (material/lambertian checker)
material1 (material/dielectric 1.5)
material2 (material/lambertian (v/vec3 0.4 0.2 0.1))
material3 (material/metal (v/vec3 0.7 0.6 0.5) 0.0)
world (hittable-list/hittable-list (sphere/sphere (v/vec3 0.0 -1000.0 0.0) 1000.0 ground-material)
(sphere/sphere (v/vec3 0.0 1.0 0.0) 1.0 material1)
(sphere/sphere (v/vec3 -4.0 1.0 0.0) 1.0 material2)
(sphere/sphere (v/vec3 4.0 1.0 0.0) 1.0 material3))]
(scene/scene camera (-> world make-balls bvh/bvh-node) scene-def)))
(defn two-spheres [scene-def]
(let [camera (camera/camera (assoc default-camera-def :aperture 0.0))
checker (texture/color-checker-texture 0.32 (v/vec3 0.2 0.3 0.1) (v/vec3 0.9 0.9 0.9))
material (material/lambertian checker)
world (hittable-list/hittable-list (sphere/sphere (v/vec3 0.0 -10.0 0.0) 10.0 material)
(sphere/sphere (v/vec3 0.0 10.0 0.0) 10.0 material))]
(scene/scene camera (-> world bvh/bvh-node) scene-def)))
(defonce earth-texture
(texture/image-texture
""))
(defn earth [scene-def]
: ( v / vec3 0.0 0.0 12.0 ) yield different view than in the book
(let [camera (camera/camera (assoc default-camera-def :aperture 0.0))
earth-surface (material/lambertian earth-texture)
globe (sphere/sphere (v/vec3 0.0 0.0 0.0) 2.0 earth-surface)]
(scene/scene camera (hittable-list/hittable-list globe) scene-def)))
(defn two-perlin-spheres [scene-def]
(let [camera (camera/camera (assoc default-camera-def :aperture 0.0))
pertext (texture/noise-texture)
material (material/lambertian pertext)
world (hittable-list/hittable-list (sphere/sphere (v/vec3 0.0 -1000.0 0.0) 1000.0 material)
(sphere/sphere (v/vec3 0.0 2.0 0.0) 2.0 material))]
(scene/scene camera (-> world bvh/bvh-node) scene-def)))
(defn main
([] (main 0))
([^long scene] (main default-scene-def scene))
([scene-def ^long scene]
(let [scene-def (merge default-scene-def scene-def)
f (case scene
1 random-spheres
2 two-spheres
3 earth
4 two-perlin-spheres
two-perlin-spheres)]
(f scene-def))))
(def image (time (scene/render (main))))
(comment
(common/save image "results/rt4/the_next_week/ch05b.jpg"))
|
49831e583c5bf00b128b6572fe8e64fa7f25cbb3fec027a691de89f57018f9ee | janestreet/hardcaml | test_signal.ml | open! Import
open Signal
let%expect_test "[Reg_spec.sexp_of_t]" =
print_s [%sexp (Reg_spec.create () ~clock : Reg_spec.t)];
[%expect {|
((clock clock)
(clock_edge Rising)) |}]
;;
let%expect_test "name of empty" =
require_does_raise [%here] (fun () -> Signal.names empty);
[%expect {| "cannot get [names] from the empty signal" |}]
;;
let%expect_test "non-const signal" =
require_does_raise [%here] (fun () -> Signal.const_value (wire 1));
[%expect
{|
("cannot get the value of a non-constant signal"
(wire
(width 1)
(data_in empty))) |}]
;;
let%expect_test "non-const to_int" =
require_does_raise [%here] (fun () -> to_int (wire 1));
[%expect
{|
("cannot use [to_constant] on non-constant signal"
(wire
(width 1)
(data_in empty))) |}]
;;
let%expect_test "non-const to_bstr" =
require_does_raise [%here] (fun () -> to_bstr (wire 1));
[%expect
{|
("cannot use [to_constant] on non-constant signal"
(wire
(width 1)
(data_in empty))) |}]
;;
let%expect_test "set name of empty" =
require_does_raise [%here] (fun () -> empty -- "oops");
[%expect {|
("attempt to set the name of the empty signal" (to_ oops)) |}]
;;
let%expect_test "multiple assignment to a wire" =
require_does_raise [%here] (fun () ->
let w = wire 1 in
w <== vdd;
w <== gnd);
[%expect
{|
("attempt to assign wire multiple times"
(already_assigned_wire (
wire
(width 1)
(data_in 0b1)))
(expression (
const
(names (gnd))
(width 1)
(value 0b0)))) |}]
;;
let%expect_test "wire width mismatch" =
require_does_raise [%here] (fun () ->
let w = wire 29 in
w <== of_int ~width:17 3);
[%expect
{|
("attempt to assign expression to wire of different width"
(wire_width 29)
(expression_width 17)
(wire (wire (width 29) (data_in empty)))
(expression (const (width 17) (value 0x00003)))) |}]
;;
let%expect_test "assignment to a non-wire" =
require_does_raise [%here] (fun () ->
let w = vdd in
w <== gnd);
[%expect
{|
("attempt to assign non-wire"
(assignment_target (
const
(names (vdd))
(width 1)
(value 0b1)))
(expression (
const
(names (gnd))
(width 1)
(value 0b0)))) |}]
;;
let g_clock = clock
let g_enable = enable
let reg_error
?clock
?clock_edge
?reset
?reset_edge
?reset_to
?clear
?clear_level
?clear_to
?enable
here
=
require_does_raise here (fun () ->
reg
(Reg_spec.override
(Reg_spec.create () ~clock:(Option.value clock ~default:g_clock))
?clock
?clock_edge
?reset
?reset_edge
?reset_to
?clear
?clear_level
?clear_to)
~enable:(Option.value enable ~default:g_enable)
(input "d" 8))
;;
let%expect_test "invalid clock" =
reg_error [%here] ~clock:(input "not_a_clock" 2);
[%expect
{|
("clock is invalid"
(info "signal has unexpected width")
(expected_width 1)
(signal (
wire
(names (not_a_clock))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "invalid reset" =
reg_error [%here] ~reset:(input "not_a_reset" 2);
[%expect
{|
("reset is invalid"
(info "signal should have expected width or be empty")
(expected_width 1)
(signal (
wire
(names (not_a_reset))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "invalid reset_value" =
reg_error [%here] ~reset_to:(input "not_a_reset_value" 2);
[%expect
{|
("reset value is invalid"
(info "signal should have expected width or be empty")
(expected_width 8)
(signal (
wire
(names (not_a_reset_value))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "invalid clear" =
reg_error [%here] ~clear:(input "not_a_clear" 2);
[%expect
{|
("clear signal is invalid"
(info "signal should have expected width or be empty")
(expected_width 1)
(signal (
wire
(names (not_a_clear))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "invalid clear_value" =
reg_error [%here] ~clear_to:(input "not_a_clear_value" 2);
[%expect
{|
("clear value is invalid"
(info "signal should have expected width or be empty")
(expected_width 8)
(signal (
wire
(names (not_a_clear_value))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "invalid enable" =
reg_error [%here] ~enable:(input "not_an_enable" 2);
[%expect
{|
("enable is invalid"
(info "signal should have expected width or be empty")
(expected_width 1)
(signal (
wire
(names (not_an_enable))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "insertion" =
require_does_raise [%here] (fun () ->
insert ~into:(of_bit_string "111") (of_bit_string "00") ~at_offset:(-1));
[%expect {| ("[insert] below bit 0" -1) |}];
require_does_raise [%here] (fun () ->
insert ~into:(of_bit_string "111") (of_bit_string "00") ~at_offset:2);
[%expect
{|
("[insert] above msb of target"
(width_from 2)
(width_target 3)
(at_offset 2)
(highest_inserted_bit 4)) |}];
require_does_not_raise [%here] (fun () ->
print_s
[%message
"valid [insert]"
~_:(insert ~into:(of_bit_string "111") (of_bit_string "00") ~at_offset:1 : t)]);
[%expect
{|
("valid [insert]" (
const
(width 3)
(value 0b001))) |}]
;;
let%expect_test "mux errors" =
require_does_raise [%here] (fun () -> mux vdd [ gnd; of_bit_string "10" ]);
[%expect
{|
("[mux] got inputs of different widths" (
(const
(names (gnd))
(width 1)
(value 0b0))
(const
(width 2)
(value 0b10)))) |}];
require_does_raise [%here] (fun () -> mux vdd [ gnd; vdd; gnd ]);
[%expect
{|
("[mux] got too many inputs"
(inputs_provided 3)
(maximum_expected 2)) |}];
require_does_raise [%here] (fun () -> mux vdd [ gnd ]);
[%expect {| ("[mux] got fewer than 2 inputs" (inputs_provided 1)) |}];
require_does_raise [%here] (fun () -> mux2 (of_bit_string "11") gnd vdd);
[%expect {| "[mux] got select argument that is not one bit" |}]
;;
let%expect_test "shift errors" =
require_does_raise [%here] (fun () -> sll vdd (-1));
[%expect {| ("[sll] got negative shift" -1) |}];
require_does_raise [%here] (fun () -> srl vdd (-1));
[%expect {| ("[srl] got negative shift" -1) |}];
require_does_raise [%here] (fun () -> sra vdd (-1));
[%expect {| ("[sra] got negative shift" -1) |}];
require_does_raise [%here] (fun () -> rotl vdd (-1));
[%expect {| ("[rotl] got negative shift" -1) |}];
require_does_raise [%here] (fun () -> rotr vdd (-1));
[%expect {| ("[rotr] got negative shift" -1) |}]
;;
let%expect_test "tree errors" =
require_does_raise [%here] (fun () -> tree ~arity:2 ~f:(reduce ~f:( +: )) []);
[%expect {| "[tree] got empty list" |}];
require_does_raise [%here] (fun () -> tree ~arity:1 ~f:(reduce ~f:( +: )) []);
[%expect {| "[tree] got [arity <= 1]" |}]
;;
| null | https://raw.githubusercontent.com/janestreet/hardcaml/4126f65f39048fef5853ba9b8d766143f678a9e4/test/lib/test_signal.ml | ocaml | open! Import
open Signal
let%expect_test "[Reg_spec.sexp_of_t]" =
print_s [%sexp (Reg_spec.create () ~clock : Reg_spec.t)];
[%expect {|
((clock clock)
(clock_edge Rising)) |}]
;;
let%expect_test "name of empty" =
require_does_raise [%here] (fun () -> Signal.names empty);
[%expect {| "cannot get [names] from the empty signal" |}]
;;
let%expect_test "non-const signal" =
require_does_raise [%here] (fun () -> Signal.const_value (wire 1));
[%expect
{|
("cannot get the value of a non-constant signal"
(wire
(width 1)
(data_in empty))) |}]
;;
let%expect_test "non-const to_int" =
require_does_raise [%here] (fun () -> to_int (wire 1));
[%expect
{|
("cannot use [to_constant] on non-constant signal"
(wire
(width 1)
(data_in empty))) |}]
;;
let%expect_test "non-const to_bstr" =
require_does_raise [%here] (fun () -> to_bstr (wire 1));
[%expect
{|
("cannot use [to_constant] on non-constant signal"
(wire
(width 1)
(data_in empty))) |}]
;;
let%expect_test "set name of empty" =
require_does_raise [%here] (fun () -> empty -- "oops");
[%expect {|
("attempt to set the name of the empty signal" (to_ oops)) |}]
;;
let%expect_test "multiple assignment to a wire" =
require_does_raise [%here] (fun () ->
let w = wire 1 in
w <== vdd;
w <== gnd);
[%expect
{|
("attempt to assign wire multiple times"
(already_assigned_wire (
wire
(width 1)
(data_in 0b1)))
(expression (
const
(names (gnd))
(width 1)
(value 0b0)))) |}]
;;
let%expect_test "wire width mismatch" =
require_does_raise [%here] (fun () ->
let w = wire 29 in
w <== of_int ~width:17 3);
[%expect
{|
("attempt to assign expression to wire of different width"
(wire_width 29)
(expression_width 17)
(wire (wire (width 29) (data_in empty)))
(expression (const (width 17) (value 0x00003)))) |}]
;;
let%expect_test "assignment to a non-wire" =
require_does_raise [%here] (fun () ->
let w = vdd in
w <== gnd);
[%expect
{|
("attempt to assign non-wire"
(assignment_target (
const
(names (vdd))
(width 1)
(value 0b1)))
(expression (
const
(names (gnd))
(width 1)
(value 0b0)))) |}]
;;
let g_clock = clock
let g_enable = enable
let reg_error
?clock
?clock_edge
?reset
?reset_edge
?reset_to
?clear
?clear_level
?clear_to
?enable
here
=
require_does_raise here (fun () ->
reg
(Reg_spec.override
(Reg_spec.create () ~clock:(Option.value clock ~default:g_clock))
?clock
?clock_edge
?reset
?reset_edge
?reset_to
?clear
?clear_level
?clear_to)
~enable:(Option.value enable ~default:g_enable)
(input "d" 8))
;;
let%expect_test "invalid clock" =
reg_error [%here] ~clock:(input "not_a_clock" 2);
[%expect
{|
("clock is invalid"
(info "signal has unexpected width")
(expected_width 1)
(signal (
wire
(names (not_a_clock))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "invalid reset" =
reg_error [%here] ~reset:(input "not_a_reset" 2);
[%expect
{|
("reset is invalid"
(info "signal should have expected width or be empty")
(expected_width 1)
(signal (
wire
(names (not_a_reset))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "invalid reset_value" =
reg_error [%here] ~reset_to:(input "not_a_reset_value" 2);
[%expect
{|
("reset value is invalid"
(info "signal should have expected width or be empty")
(expected_width 8)
(signal (
wire
(names (not_a_reset_value))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "invalid clear" =
reg_error [%here] ~clear:(input "not_a_clear" 2);
[%expect
{|
("clear signal is invalid"
(info "signal should have expected width or be empty")
(expected_width 1)
(signal (
wire
(names (not_a_clear))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "invalid clear_value" =
reg_error [%here] ~clear_to:(input "not_a_clear_value" 2);
[%expect
{|
("clear value is invalid"
(info "signal should have expected width or be empty")
(expected_width 8)
(signal (
wire
(names (not_a_clear_value))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "invalid enable" =
reg_error [%here] ~enable:(input "not_an_enable" 2);
[%expect
{|
("enable is invalid"
(info "signal should have expected width or be empty")
(expected_width 1)
(signal (
wire
(names (not_an_enable))
(width 2)
(data_in empty)))) |}]
;;
let%expect_test "insertion" =
require_does_raise [%here] (fun () ->
insert ~into:(of_bit_string "111") (of_bit_string "00") ~at_offset:(-1));
[%expect {| ("[insert] below bit 0" -1) |}];
require_does_raise [%here] (fun () ->
insert ~into:(of_bit_string "111") (of_bit_string "00") ~at_offset:2);
[%expect
{|
("[insert] above msb of target"
(width_from 2)
(width_target 3)
(at_offset 2)
(highest_inserted_bit 4)) |}];
require_does_not_raise [%here] (fun () ->
print_s
[%message
"valid [insert]"
~_:(insert ~into:(of_bit_string "111") (of_bit_string "00") ~at_offset:1 : t)]);
[%expect
{|
("valid [insert]" (
const
(width 3)
(value 0b001))) |}]
;;
let%expect_test "mux errors" =
require_does_raise [%here] (fun () -> mux vdd [ gnd; of_bit_string "10" ]);
[%expect
{|
("[mux] got inputs of different widths" (
(const
(names (gnd))
(width 1)
(value 0b0))
(const
(width 2)
(value 0b10)))) |}];
require_does_raise [%here] (fun () -> mux vdd [ gnd; vdd; gnd ]);
[%expect
{|
("[mux] got too many inputs"
(inputs_provided 3)
(maximum_expected 2)) |}];
require_does_raise [%here] (fun () -> mux vdd [ gnd ]);
[%expect {| ("[mux] got fewer than 2 inputs" (inputs_provided 1)) |}];
require_does_raise [%here] (fun () -> mux2 (of_bit_string "11") gnd vdd);
[%expect {| "[mux] got select argument that is not one bit" |}]
;;
let%expect_test "shift errors" =
require_does_raise [%here] (fun () -> sll vdd (-1));
[%expect {| ("[sll] got negative shift" -1) |}];
require_does_raise [%here] (fun () -> srl vdd (-1));
[%expect {| ("[srl] got negative shift" -1) |}];
require_does_raise [%here] (fun () -> sra vdd (-1));
[%expect {| ("[sra] got negative shift" -1) |}];
require_does_raise [%here] (fun () -> rotl vdd (-1));
[%expect {| ("[rotl] got negative shift" -1) |}];
require_does_raise [%here] (fun () -> rotr vdd (-1));
[%expect {| ("[rotr] got negative shift" -1) |}]
;;
let%expect_test "tree errors" =
require_does_raise [%here] (fun () -> tree ~arity:2 ~f:(reduce ~f:( +: )) []);
[%expect {| "[tree] got empty list" |}];
require_does_raise [%here] (fun () -> tree ~arity:1 ~f:(reduce ~f:( +: )) []);
[%expect {| "[tree] got [arity <= 1]" |}]
;;
| |
a1de98a3267284dce834dda46ed36d71bc3467a5d54a10739acac5ad29a75288 | jeffshrager/biobike | specials.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*-
$ Header : /cvsroot - fuse / biolingua / BioLisp / ppcre / cl - ppcre-1.2.3 / specials.lisp , v 1.1 2005/02/03 06:09:46 roton Exp $
;;; globally declared special variables
Copyright ( c ) 2002 - 2004 , Dr. . 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 AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 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-ppcre)
;;; special variables used by the lexer/parser combo
(defvar *extended-mode-p* nil
"Whether the parser will start in extended mode.")
(declaim (type boolean *extended-mode-p*))
;;; special variables used by the SCAN function and the matchers
(defvar *string* ""
"The string which is currently scanned by SCAN.
Will always be coerced to a SIMPLE-STRING.")
(declaim (type simple-string *string*))
(defvar *start-pos* 0
"Where to start scanning within *STRING*.")
(declaim (type fixnum *start-pos*))
(defvar *real-start-pos* nil
"The real start of *STRING*. This is for repeated scans and is only used internally.")
(declaim (type (or null fixnum) *real-start-pos*))
(defvar *end-pos* 0
"Where to stop scanning within *STRING*.")
(declaim (type fixnum *end-pos*))
(defvar *reg-starts* (make-array 0)
"An array which holds the start positions
of the current register candidates.")
(declaim (type simple-vector *reg-starts*))
(defvar *regs-maybe-start* (make-array 0)
"An array which holds the next start positions
of the current register candidates.")
(declaim (type simple-vector *regs-maybe-start*))
(defvar *reg-ends* (make-array 0)
"An array which holds the end positions
of the current register candidates.")
(declaim (type simple-vector *reg-ends*))
(defvar *end-string-pos* nil
"Start of the next possible end-string candidate.")
(defvar *rep-num* 0
"Counts the number of \"complicated\" repetitions while the matchers
are built.")
(declaim (type fixnum *rep-num*))
(defvar *zero-length-num* 0
"Counts the number of repetitions the inner regexes of which may
have zero-length while the matchers are built.")
(declaim (type fixnum *zero-length-num*))
(defvar *repeat-counters* (make-array 0
:initial-element 0
:element-type 'fixnum)
"An array to keep track of how often
repetitive patterns have been tested already.")
(declaim (type (array fixnum (*)) *repeat-counters*))
(defvar *last-pos-stores* (make-array 0)
"An array to keep track of the last positions
where we saw repetitive patterns.
Only used for patterns which might have zero length.")
(declaim (type simple-vector *last-pos-stores*))
(defvar *use-bmh-matchers* t
"Whether the scanners created by CREATE-SCANNER should use the \(fast
but large) Boyer-Moore-Horspool matchers.")
(defvar *allow-quoting* nil
"Whether the parser should support Perl's \\Q and \\E.")
(pushnew :cl-ppcre *features*)
stuff for Nikodemus Siivola 's HYPERDOC
;; see <-lisp.net/project/hyperdoc/>
;; and <>
(defvar *hyperdoc-base-uri* "-ppcre/")
(let ((exported-symbols-alist
(loop for symbol being the external-symbols of :cl-ppcre
collect (cons symbol
(concatenate 'string
"#"
(string-downcase symbol))))))
(defun hyperdoc-lookup (symbol type)
(declare (ignore type))
(cdr (assoc symbol
exported-symbols-alist
:test #'eq))))
| null | https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/ppcre/cl-ppcre-1.2.3/specials.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*-
globally declared special variables
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 AUTHOR 'AS IS' AND ANY EXPRESSED
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 BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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.
special variables used by the lexer/parser combo
special variables used by the SCAN function and the matchers
see <-lisp.net/project/hyperdoc/>
and <> | $ Header : /cvsroot - fuse / biolingua / BioLisp / ppcre / cl - ppcre-1.2.3 / specials.lisp , v 1.1 2005/02/03 06:09:46 roton Exp $
Copyright ( c ) 2002 - 2004 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package #:cl-ppcre)
(defvar *extended-mode-p* nil
"Whether the parser will start in extended mode.")
(declaim (type boolean *extended-mode-p*))
(defvar *string* ""
"The string which is currently scanned by SCAN.
Will always be coerced to a SIMPLE-STRING.")
(declaim (type simple-string *string*))
(defvar *start-pos* 0
"Where to start scanning within *STRING*.")
(declaim (type fixnum *start-pos*))
(defvar *real-start-pos* nil
"The real start of *STRING*. This is for repeated scans and is only used internally.")
(declaim (type (or null fixnum) *real-start-pos*))
(defvar *end-pos* 0
"Where to stop scanning within *STRING*.")
(declaim (type fixnum *end-pos*))
(defvar *reg-starts* (make-array 0)
"An array which holds the start positions
of the current register candidates.")
(declaim (type simple-vector *reg-starts*))
(defvar *regs-maybe-start* (make-array 0)
"An array which holds the next start positions
of the current register candidates.")
(declaim (type simple-vector *regs-maybe-start*))
(defvar *reg-ends* (make-array 0)
"An array which holds the end positions
of the current register candidates.")
(declaim (type simple-vector *reg-ends*))
(defvar *end-string-pos* nil
"Start of the next possible end-string candidate.")
(defvar *rep-num* 0
"Counts the number of \"complicated\" repetitions while the matchers
are built.")
(declaim (type fixnum *rep-num*))
(defvar *zero-length-num* 0
"Counts the number of repetitions the inner regexes of which may
have zero-length while the matchers are built.")
(declaim (type fixnum *zero-length-num*))
(defvar *repeat-counters* (make-array 0
:initial-element 0
:element-type 'fixnum)
"An array to keep track of how often
repetitive patterns have been tested already.")
(declaim (type (array fixnum (*)) *repeat-counters*))
(defvar *last-pos-stores* (make-array 0)
"An array to keep track of the last positions
where we saw repetitive patterns.
Only used for patterns which might have zero length.")
(declaim (type simple-vector *last-pos-stores*))
(defvar *use-bmh-matchers* t
"Whether the scanners created by CREATE-SCANNER should use the \(fast
but large) Boyer-Moore-Horspool matchers.")
(defvar *allow-quoting* nil
"Whether the parser should support Perl's \\Q and \\E.")
(pushnew :cl-ppcre *features*)
stuff for Nikodemus Siivola 's HYPERDOC
(defvar *hyperdoc-base-uri* "-ppcre/")
(let ((exported-symbols-alist
(loop for symbol being the external-symbols of :cl-ppcre
collect (cons symbol
(concatenate 'string
"#"
(string-downcase symbol))))))
(defun hyperdoc-lookup (symbol type)
(declare (ignore type))
(cdr (assoc symbol
exported-symbols-alist
:test #'eq))))
|
6da9dbbe406cfbfbfd8518c7695bbe4467b1475eba09565e6bd96c751a135198 | LdBeth/CLFSWM | clfswm-info.lisp | ;;; --------------------------------------------------------------------------
;;; CLFSWM - FullScreen Window Manager
;;;
;;; --------------------------------------------------------------------------
;;; Documentation: Info function (see the end of this file for user definition
;;; --------------------------------------------------------------------------
;;;
( C ) 2005 - 2015 < >
;;;
;;; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 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 General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
;;; along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
;;;
;;; --------------------------------------------------------------------------
(in-package :clfswm)
(defstruct info window gc font list ilw ilh x y max-x max-y)
(defparameter *info-selected-item* nil)
(defun leave-info-mode (info)
"Leave the info mode"
(declare (ignore info))
(setf *info-selected-item* nil)
(throw 'exit-info-loop nil))
(defun leave-info-mode-and-valid (info)
"Leave the info mode and valid the selected item"
(declare (ignore info))
(throw 'exit-info-loop nil))
(defun mouse-leave-info-mode (window root-x root-y info)
"Leave the info mode"
(declare (ignore window root-x root-y info))
(setf *info-selected-item* nil)
(throw 'exit-info-loop nil))
(defun find-info-item-from-mouse (root-x root-y info)
(if (< (x-drawable-x (info-window info)) root-x
(+ (x-drawable-x (info-window info))
(x-drawable-width (info-window info))))
(truncate (/ (- (+ (- root-y (x-drawable-y (info-window info)))
(xlib:max-char-ascent (info-font info))
(info-y info)) (info-ilh info)) (info-ilh info)))
nil))
(defun set-info-item-form-mouse (root-x root-y info)
(setf *info-selected-item* (find-info-item-from-mouse root-x root-y info)))
(defun info-y-display-coords (info posy)
(- (+ (* (info-ilh info) posy) (info-ilh info)) (info-y info)))
(defun incf-info-selected-item (info n)
(setf *info-selected-item*
(min (if *info-selected-item*
(+ *info-selected-item* n)
0)
(1- (or (length (info-list info)) 1)))))
(defun decf-info-selected-item (info n)
(declare (ignore info))
(setf *info-selected-item*
(max (if *info-selected-item*
(- *info-selected-item* n)
0)
0)))
(defun draw-info-window (info)
(labels ((print-line (line posx posy &optional (color *info-foreground*))
(xlib:with-gcontext ((info-gc info) :foreground (get-color color)
:background (if (equal posy *info-selected-item*)
(get-color *info-selected-background*)
(get-color *info-background*)))
(funcall (if (equal posy *info-selected-item*)
#'xlib:draw-image-glyphs
#'xlib:draw-glyphs)
*pixmap-buffer* (info-gc info)
(- (+ (info-ilw info) (* posx (info-ilw info))) (info-x info))
(info-y-display-coords info posy)
(ensure-printable (format nil "~A" line))))
(+ posx (length line))))
(clear-pixmap-buffer (info-window info) (info-gc info))
(loop for line in (info-list info)
for y from 0
do (typecase line
(cons (typecase (first line)
(cons (let ((posx 0))
(dolist (l line)
(typecase l
(cons (setf posx (print-line (first l) posx y (second l))))
(t (setf posx (print-line l posx y)))))))
(t (print-line (first line) 0 y (second line)))))
(t (print-line line 0 y))))
(copy-pixmap-buffer (info-window info) (info-gc info))))
;;;,-----
;;;| Key binding
;;;`-----
(add-hook *binding-hook* 'init-*info-keys* 'init-*info-mouse*)
(defun set-default-info-keys ()
(define-info-key (#\q) 'leave-info-mode)
(define-info-key ("Return") 'leave-info-mode-and-valid)
(define-info-key ("KP_Enter" :mod-2) 'leave-info-mode-and-valid)
(define-info-key ("space") 'leave-info-mode-and-valid)
(define-info-key ("Escape") 'leave-info-mode)
(define-info-key ("g" :control) 'leave-info-mode)
(define-info-key ("twosuperior")
(defun info-banish-pointer (info)
"Move the pointer to the lower right corner of the screen"
(declare (ignore info))
(banish-pointer)))
(define-info-key ("Down")
(defun info-next-line (info)
"Move one line down"
(incf-info-selected-item info 1)
(when (> (info-y-display-coords info *info-selected-item*)
(+ (x-drawable-y (info-window info))
(x-drawable-height (info-window info))))
(setf (info-y info) (min (+ (info-y info) (info-ilh info)) (info-max-y info))))
(draw-info-window info)))
(define-info-key ("Up")
(defun info-previous-line (info)
"Move one line up"
(decf-info-selected-item info 1)
(when (< (info-y-display-coords info *info-selected-item*)
(+ (x-drawable-y (info-window info))
(info-ilh info)))
(setf (info-y info) (max (- (info-y info) (info-ilh info)) 0)))
(draw-info-window info)))
(define-info-key ("Left")
(defun info-previous-char (info)
"Move one char left"
(setf (info-x info) (max (- (info-x info) (info-ilw info)) 0))
(draw-info-window info)))
(define-info-key ("Right")
(defun info-next-char (info)
"Move one char right"
(setf (info-x info) (min (+ (info-x info) (info-ilw info)) (info-max-x info)))
(draw-info-window info)))
(define-info-key ("Home")
(defun info-first-line (info)
"Move to first line"
(setf (info-x info) 0
(info-y info) 0)
(setf *info-selected-item* 0)
(draw-info-window info)))
(define-info-key ("End")
(defun info-end-line (info)
"Move to last line"
(setf (info-x info) 0
(info-y info) (- (* (length (info-list info)) (info-ilh info)) (x-drawable-height (info-window info))))
(setf *info-selected-item* (1- (or (length (info-list info)) 1)))
(draw-info-window info)))
(define-info-key ("Page_Down")
(defun info-next-ten-lines (info)
"Move ten lines down"
(incf-info-selected-item info 10)
(when (> (info-y-display-coords info *info-selected-item*)
(+ (x-drawable-y (info-window info))
(x-drawable-height (info-window info))))
(setf (info-y info) (min (+ (info-y info) (* (info-ilh info) 10)) (info-max-y info))))
(draw-info-window info)))
(define-info-key ("Page_Up")
(defun info-previous-ten-lines (info)
"Move ten lines up"
(decf-info-selected-item info 10)
(when (< (info-y-display-coords info *info-selected-item*)
(+ (x-drawable-y (info-window info))
(info-ilh info)))
(setf (info-y info) (max (- (info-y info) (* (info-ilh info) 10)) 0)))
(draw-info-window info))))
(add-hook *binding-hook* 'set-default-info-keys)
(defparameter *info-start-grab-x* nil)
(defparameter *info-start-grab-y* nil)
(defun info-begin-grab (window root-x root-y info)
"Begin grab text"
(declare (ignore window))
(setf *info-start-grab-x* (min (max (+ root-x (info-x info)) 0) (info-max-x info))
*info-start-grab-y* (min (max (+ root-y (info-y info)) 0) (info-max-y info)))
(draw-info-window info))
(defun info-end-grab (window root-x root-y info)
"End grab"
(declare (ignore window))
(setf (info-x info) (min (max (- *info-start-grab-x* root-x) 0) (info-max-x info))
(info-y info) (min (max (- *info-start-grab-y* root-y) 0) (info-max-y info))
*info-start-grab-x* nil
*info-start-grab-y* nil)
(draw-info-window info))
(defun info-mouse-next-line (window root-x root-y info)
"Move one line down"
(declare (ignore window))
(setf (info-y info) (min (+ (info-y info) (info-ilh info)) (info-max-y info)))
(set-info-item-form-mouse root-x root-y info)
(draw-info-window info))
(defun info-mouse-previous-line (window root-x root-y info)
"Move one line up"
(declare (ignore window))
(setf (info-y info) (max (- (info-y info) (info-ilh info)) 0))
(set-info-item-form-mouse root-x root-y info)
(draw-info-window info))
(defun info-mouse-motion-drag (window root-x root-y info)
"Grab text"
(declare (ignore window))
(when (and *info-start-grab-x* *info-start-grab-y*)
(setf (info-x info) (min (max (- *info-start-grab-x* root-x) 0) (info-max-x info))
(info-y info) (min (max (- *info-start-grab-y* root-y) 0) (info-max-y info)))
(draw-info-window info)))
(defun info-mouse-select-item (window root-x root-y info)
(declare (ignore window))
(set-info-item-form-mouse root-x root-y info)
(leave-info-mode-and-valid info))
(defun info-mouse-motion-click (window root-x root-y info)
(declare (ignore window))
(let ((last *info-selected-item*))
(set-info-item-form-mouse root-x root-y info)
(unless (equal last *info-selected-item*)
(draw-info-window info))))
(defun set-default-info-mouse ()
(if *info-click-to-select*
(define-info-mouse (1) nil 'info-mouse-select-item)
(define-info-mouse (1) 'info-begin-grab 'info-end-grab))
(define-info-mouse (2) 'mouse-leave-info-mode)
(define-info-mouse (3) 'mouse-leave-info-mode)
(define-info-mouse (4) 'info-mouse-previous-line)
(define-info-mouse (5) 'info-mouse-next-line)
(if *info-click-to-select*
(define-info-mouse ('motion) 'info-mouse-motion-click nil)
(define-info-mouse ('motion) 'info-mouse-motion-drag nil)))
(add-hook *binding-hook* 'set-default-info-mouse)
(let (info)
(define-handler info-mode :key-press (code state)
(funcall-key-from-code *info-keys* code state info))
(define-handler info-mode :motion-notify (window root-x root-y)
(unless (compress-motion-notify)
(funcall-button-from-code *info-mouse* 'motion (modifiers->state *default-modifiers*)
window root-x root-y *fun-press* (list info))))
(define-handler info-mode :button-press (window root-x root-y code state)
(funcall-button-from-code *info-mouse* code state window root-x root-y *fun-press* (list info)))
(define-handler info-mode :button-release (window root-x root-y code state)
(funcall-button-from-code *info-mouse* code state window root-x root-y *fun-release* (list info)))
(defun info-mode (info-list &key (width nil) (height nil))
"Open the info mode. Info-list is a list of info: One string per line
Or for colored output: a list (line_string color)
Or ((1_word color) (2_word color) 3_word (4_word color)...)"
(when info-list
(setf *info-selected-item* 0)
(labels ((compute-size (line)
(typecase line
(cons (typecase (first line)
(cons (let ((val 0))
(dolist (l line val)
(incf val (typecase l
(cons (length (first l)))
(t (length l)))))))
(t (length (first line)))))
(t (length line)))))
(let* ((font (xlib:open-font *display* *info-font-string*))
(ilw (xlib:max-char-width font))
(ilh (+ (xlib:max-char-ascent font) (xlib:max-char-descent font) 1))
(width (or width
(min (* (+ (loop for l in info-list maximize (compute-size l)) 2) ilw)
(screen-width))))
(height (or height
(min (round (+ (* (length info-list) ilh) (/ ilh 2)))
(screen-height)))))
(with-placement (*info-mode-placement* x y width height)
(let* ((window (xlib:create-window :parent *root*
:x x :y y
:width width
:height height
:background (get-color *info-background*)
:colormap (xlib:screen-default-colormap *screen*)
:border-width *border-size*
:border (get-color *info-border*)
:event-mask '(:exposure)))
(gc (xlib:create-gcontext :drawable window
:foreground (get-color *info-foreground*)
:background (get-color *info-background*)
:font font
:line-style :solid)))
(setf info (make-info :window window :gc gc :x 0 :y 0 :list info-list
:font font :ilw ilw :ilh ilh
:max-x (* (loop for l in info-list maximize (compute-size l)) ilw)
:max-y (* (length info-list) ilh)))
(setf (window-transparency window) *info-transparency*)
(map-window window)
(draw-info-window info)
(wait-no-key-or-button-press)
(with-grab-keyboard-and-pointer (68 69 66 67)
(generic-mode 'info-mode 'exit-info-loop
:original-mode '(main-mode)))
(xlib:free-gcontext gc)
(xlib:destroy-window window)
(xlib:close-font font)
(xlib:display-finish-output *display*)
(display-all-frame-info)
(wait-no-key-or-button-press)
*info-selected-item*)))))))
(defun info-mode-menu (item-list &key (width nil) (height nil))
"Open an info help menu.
Item-list is: '((key function) separator (key function))
or with explicit docstring: '((key function \"documentation 1\") (key function \"bla bla\") (key function))
key is a character, a keycode or a keysym
Separator is a string or a symbol (all but a list)
Function can be a function or a list (function color) for colored output"
(let ((info-list nil)
(action nil)
(old-info-keys (copy-hash-table *info-keys*)))
(labels ((define-key (key function)
(define-info-key-fun (list key)
(lambda (&optional args)
(declare (ignore args))
(setf action function)
(leave-info-mode nil)))))
(dolist (item item-list)
(typecase item
(cons (destructuring-bind (key function explicit-doc) (ensure-n-elems item 3)
(typecase function
(cons (push (list (list (format nil "~A" key) *menu-color-menu-key*)
(list (format nil ": ~A" (or explicit-doc (documentation (first function) 'function)))
(second function)))
info-list)
(define-key key (first function)))
(t (push (list (list (format nil "~A" key) *menu-color-key*)
(format nil ": ~A" (or explicit-doc (documentation function 'function))))
info-list)
(define-key key function)))))
(t (push (list (format nil "-=- ~A -=-" item) *menu-color-comment*) info-list))))
(let ((selected-item (info-mode (nreverse info-list) :width width :height height)))
(setf *info-keys* old-info-keys)
(when selected-item
(awhen (nth selected-item item-list)
(when (consp it)
(destructuring-bind (key function explicit-doc) (ensure-n-elems it 3)
(declare (ignore key explicit-doc))
(typecase function
(cons (setf action (first function)))
(t (setf action function)))))))
(typecase action
(function (funcall action))
(symbol (when (fboundp action)
(funcall action))))))))
(defun keys-from-list (list)
"Produce a key menu based on list item"
(loop for l in list
for i from 0
collect (list (number->char i) l)))
;;;,-----
;;;| CONFIG - Info mode functions
;;;`-----
(defun key-binding-colorize-line (list); FIXME: Use a parameter instead of hard code
(loop :for line :in list
:collect (cond ((search "* CLFSWM Keys *" line) (list line *info-color-title*))
((search "---" line) (list line *info-color-underline*))
((begin-with-2-spaces line)
(list (list (subseq line 0 22) *info-color-second*)
(list (subseq line 22 44) *info-color-first*)
(subseq line 44)))
(t line))))
(defun show-key-binding (&rest hash-table-key)
"Show the binding of each hash-table-key.
Pass the :no-producing-doc symbol to remove the producing doc"
(info-mode (key-binding-colorize-line
(split-string (append-newline-space
(with-output-to-string (stream)
(produce-doc (remove :no-producing-doc hash-table-key)
stream
(not (member :no-producing-doc hash-table-key)))))
#\Newline))))
(defun show-global-key-binding ()
"Show all key binding"
(show-key-binding *main-keys* *main-mouse* *second-keys* *second-mouse*
*info-keys* *info-mouse*))
(defun show-main-mode-key-binding ()
"Show the main mode binding"
(show-key-binding *main-keys* *main-mouse*))
(defun show-second-mode-key-binding ()
"Show the second mode key binding"
(show-key-binding *second-keys* *second-mouse*))
(defun show-circulate-mode-key-binding ()
"Show the circulate mode key binding"
(show-key-binding *circulate-keys*))
(defun show-expose-window-mode-key-binding ()
"Show the expose window mode key binding"
(show-key-binding *expose-keys* *expose-mouse*))
(defun show-first-aid-kit ()
"Show the first aid kit key binding"
(labels ((add-key (hash symbol &optional (hashkey *main-keys*))
(multiple-value-bind (k v)
(find-in-hash symbol hashkey)
(setf (gethash k hash) v))))
(let ((hash (make-hash-table :test #'equal))
(hash-second (make-hash-table :test #'equal)))
(setf (gethash 'name hash) "First aid kit - Main mode key binding"
(gethash 'name hash-second) "First aid kit - Second mode key binding")
(add-key hash 'select-next-child)
(add-key hash 'select-previous-child)
(add-key hash 'select-next-brother)
(add-key hash 'select-previous-brother)
(add-key hash 'select-previous-level)
(add-key hash 'select-next-level)
(add-key hash 'enter-frame)
(add-key hash 'leave-frame)
(add-key hash 'second-key-mode)
(add-key hash 'expose-windows-mode)
(add-key hash 'expose-all-windows-mode)
(add-key hash 'present-clfswm-terminal)
(add-key hash-second 'leave-second-mode *second-keys*)
(add-key hash-second 'open-menu *second-keys*)
(add-key hash-second 'run-program-from-query-string *second-keys*)
(add-key hash-second 'eval-from-query-string *second-keys*)
(add-key hash-second 'set-open-in-new-frame-in-parent-frame-nw-hook *second-keys*)
(add-key hash-second 'b-start-xterm *second-keys*)
(add-key hash-second 'b-start-emacs *second-keys*)
(show-key-binding hash hash-second :no-producing-doc))))
(defun corner-help-colorize-line (list)
(loop :for line :in list
:collect (cond ((search "CLFSWM:" line) (list line *info-color-title*))
((search "*:" line) (list line *info-color-underline*))
((begin-with-2-spaces line)
(let ((pos (position #\: line)))
(if pos
(list (list (subseq line 0 (1+ pos)) *info-color-first*)
(subseq line (1+ pos)))
line)))
(t line))))
(defun show-corner-help ()
"Help on clfswm corner"
(info-mode (corner-help-colorize-line
(split-string (append-newline-space
(with-output-to-string (stream)
(produce-corner-doc stream)))
#\Newline))))
(defun configuration-variable-colorize-line (list)
(loop :for line :in list
:collect (cond ((search "CLFSWM " line) (list line *info-color-title*))
((search "* =" line)
(let ((pos (position #\= line)))
(list (list (subseq line 0 (1+ pos)) *info-color-first*)
(list (subseq line (1+ pos)) *info-color-second*))))
((search "<=" line) (list line *info-color-underline*))
(t line))))
(defun show-config-variable ()
"Show all configurable variables"
(let ((result nil))
(labels ((rec ()
(setf result nil)
(info-mode-menu (loop :for group :in (config-all-groups)
:for i :from 0
:collect (list (number->char i)
(let ((group group))
(lambda ()
(setf result group)))
(config-group->string group))))
(when result
(info-mode (configuration-variable-colorize-line
(split-string (append-newline-space
(with-output-to-string (stream)
(produce-conf-var-doc stream result t nil)))
#\Newline)))
(rec))))
(rec))))
(defun show-date ()
"Show the current time and date"
(info-mode (list (list `("Current date:" ,*menu-color-comment*) (date-string)))))
(defun info-on-shell (msg program)
(let ((lines (do-shell program nil t)))
(info-mode (append (list (list msg *menu-color-comment*))
(loop for line = (read-line lines nil nil)
while line
collect (ensure-printable line))))))
(defun show-cpu-proc ()
"Show current processes sorted by CPU usage"
(info-on-shell "Current processes sorted by CPU usage:"
"ps --cols=1000 --sort='-%cpu,uid,pgid,ppid,pid' -e -o user,pid,stime,pcpu,pmem,args"))
(defun show-mem-proc ()
"Show current processes sorted by memory usage"
(info-on-shell "Current processes sorted by MEMORY usage:"
"ps --cols=1000 --sort='-vsz,uid,pgid,ppid,pid' -e -o user,pid,stime,pcpu,pmem,args"))
(defun show-cd-info ()
"Show the current CD track"
(info-on-shell "Current CD track:" "pcd i"))
(defun show-cd-playlist ()
"Show the current CD playlist"
(info-on-shell "Current CD playlist:" "pcd mi"))
(defun show-version ()
"Show the current CLFSWM version"
(info-mode (list *version*)))
| null | https://raw.githubusercontent.com/LdBeth/CLFSWM/4e936552d1388718d2947a5f6ca3eada19643e75/src/clfswm-info.lisp | lisp | --------------------------------------------------------------------------
CLFSWM - FullScreen Window Manager
--------------------------------------------------------------------------
Documentation: Info function (see the end of this file for user definition
--------------------------------------------------------------------------
This program is free software; you can redistribute it and/or modify
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 General Public License for more details.
along with this program; if not, write to the Free Software
--------------------------------------------------------------------------
,-----
| Key binding
`-----
,-----
| CONFIG - Info mode functions
`-----
FIXME: Use a parameter instead of hard code | ( C ) 2005 - 2015 < >
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
(in-package :clfswm)
(defstruct info window gc font list ilw ilh x y max-x max-y)
(defparameter *info-selected-item* nil)
(defun leave-info-mode (info)
"Leave the info mode"
(declare (ignore info))
(setf *info-selected-item* nil)
(throw 'exit-info-loop nil))
(defun leave-info-mode-and-valid (info)
"Leave the info mode and valid the selected item"
(declare (ignore info))
(throw 'exit-info-loop nil))
(defun mouse-leave-info-mode (window root-x root-y info)
"Leave the info mode"
(declare (ignore window root-x root-y info))
(setf *info-selected-item* nil)
(throw 'exit-info-loop nil))
(defun find-info-item-from-mouse (root-x root-y info)
(if (< (x-drawable-x (info-window info)) root-x
(+ (x-drawable-x (info-window info))
(x-drawable-width (info-window info))))
(truncate (/ (- (+ (- root-y (x-drawable-y (info-window info)))
(xlib:max-char-ascent (info-font info))
(info-y info)) (info-ilh info)) (info-ilh info)))
nil))
(defun set-info-item-form-mouse (root-x root-y info)
(setf *info-selected-item* (find-info-item-from-mouse root-x root-y info)))
(defun info-y-display-coords (info posy)
(- (+ (* (info-ilh info) posy) (info-ilh info)) (info-y info)))
(defun incf-info-selected-item (info n)
(setf *info-selected-item*
(min (if *info-selected-item*
(+ *info-selected-item* n)
0)
(1- (or (length (info-list info)) 1)))))
(defun decf-info-selected-item (info n)
(declare (ignore info))
(setf *info-selected-item*
(max (if *info-selected-item*
(- *info-selected-item* n)
0)
0)))
(defun draw-info-window (info)
(labels ((print-line (line posx posy &optional (color *info-foreground*))
(xlib:with-gcontext ((info-gc info) :foreground (get-color color)
:background (if (equal posy *info-selected-item*)
(get-color *info-selected-background*)
(get-color *info-background*)))
(funcall (if (equal posy *info-selected-item*)
#'xlib:draw-image-glyphs
#'xlib:draw-glyphs)
*pixmap-buffer* (info-gc info)
(- (+ (info-ilw info) (* posx (info-ilw info))) (info-x info))
(info-y-display-coords info posy)
(ensure-printable (format nil "~A" line))))
(+ posx (length line))))
(clear-pixmap-buffer (info-window info) (info-gc info))
(loop for line in (info-list info)
for y from 0
do (typecase line
(cons (typecase (first line)
(cons (let ((posx 0))
(dolist (l line)
(typecase l
(cons (setf posx (print-line (first l) posx y (second l))))
(t (setf posx (print-line l posx y)))))))
(t (print-line (first line) 0 y (second line)))))
(t (print-line line 0 y))))
(copy-pixmap-buffer (info-window info) (info-gc info))))
(add-hook *binding-hook* 'init-*info-keys* 'init-*info-mouse*)
(defun set-default-info-keys ()
(define-info-key (#\q) 'leave-info-mode)
(define-info-key ("Return") 'leave-info-mode-and-valid)
(define-info-key ("KP_Enter" :mod-2) 'leave-info-mode-and-valid)
(define-info-key ("space") 'leave-info-mode-and-valid)
(define-info-key ("Escape") 'leave-info-mode)
(define-info-key ("g" :control) 'leave-info-mode)
(define-info-key ("twosuperior")
(defun info-banish-pointer (info)
"Move the pointer to the lower right corner of the screen"
(declare (ignore info))
(banish-pointer)))
(define-info-key ("Down")
(defun info-next-line (info)
"Move one line down"
(incf-info-selected-item info 1)
(when (> (info-y-display-coords info *info-selected-item*)
(+ (x-drawable-y (info-window info))
(x-drawable-height (info-window info))))
(setf (info-y info) (min (+ (info-y info) (info-ilh info)) (info-max-y info))))
(draw-info-window info)))
(define-info-key ("Up")
(defun info-previous-line (info)
"Move one line up"
(decf-info-selected-item info 1)
(when (< (info-y-display-coords info *info-selected-item*)
(+ (x-drawable-y (info-window info))
(info-ilh info)))
(setf (info-y info) (max (- (info-y info) (info-ilh info)) 0)))
(draw-info-window info)))
(define-info-key ("Left")
(defun info-previous-char (info)
"Move one char left"
(setf (info-x info) (max (- (info-x info) (info-ilw info)) 0))
(draw-info-window info)))
(define-info-key ("Right")
(defun info-next-char (info)
"Move one char right"
(setf (info-x info) (min (+ (info-x info) (info-ilw info)) (info-max-x info)))
(draw-info-window info)))
(define-info-key ("Home")
(defun info-first-line (info)
"Move to first line"
(setf (info-x info) 0
(info-y info) 0)
(setf *info-selected-item* 0)
(draw-info-window info)))
(define-info-key ("End")
(defun info-end-line (info)
"Move to last line"
(setf (info-x info) 0
(info-y info) (- (* (length (info-list info)) (info-ilh info)) (x-drawable-height (info-window info))))
(setf *info-selected-item* (1- (or (length (info-list info)) 1)))
(draw-info-window info)))
(define-info-key ("Page_Down")
(defun info-next-ten-lines (info)
"Move ten lines down"
(incf-info-selected-item info 10)
(when (> (info-y-display-coords info *info-selected-item*)
(+ (x-drawable-y (info-window info))
(x-drawable-height (info-window info))))
(setf (info-y info) (min (+ (info-y info) (* (info-ilh info) 10)) (info-max-y info))))
(draw-info-window info)))
(define-info-key ("Page_Up")
(defun info-previous-ten-lines (info)
"Move ten lines up"
(decf-info-selected-item info 10)
(when (< (info-y-display-coords info *info-selected-item*)
(+ (x-drawable-y (info-window info))
(info-ilh info)))
(setf (info-y info) (max (- (info-y info) (* (info-ilh info) 10)) 0)))
(draw-info-window info))))
(add-hook *binding-hook* 'set-default-info-keys)
(defparameter *info-start-grab-x* nil)
(defparameter *info-start-grab-y* nil)
(defun info-begin-grab (window root-x root-y info)
"Begin grab text"
(declare (ignore window))
(setf *info-start-grab-x* (min (max (+ root-x (info-x info)) 0) (info-max-x info))
*info-start-grab-y* (min (max (+ root-y (info-y info)) 0) (info-max-y info)))
(draw-info-window info))
(defun info-end-grab (window root-x root-y info)
"End grab"
(declare (ignore window))
(setf (info-x info) (min (max (- *info-start-grab-x* root-x) 0) (info-max-x info))
(info-y info) (min (max (- *info-start-grab-y* root-y) 0) (info-max-y info))
*info-start-grab-x* nil
*info-start-grab-y* nil)
(draw-info-window info))
(defun info-mouse-next-line (window root-x root-y info)
"Move one line down"
(declare (ignore window))
(setf (info-y info) (min (+ (info-y info) (info-ilh info)) (info-max-y info)))
(set-info-item-form-mouse root-x root-y info)
(draw-info-window info))
(defun info-mouse-previous-line (window root-x root-y info)
"Move one line up"
(declare (ignore window))
(setf (info-y info) (max (- (info-y info) (info-ilh info)) 0))
(set-info-item-form-mouse root-x root-y info)
(draw-info-window info))
(defun info-mouse-motion-drag (window root-x root-y info)
"Grab text"
(declare (ignore window))
(when (and *info-start-grab-x* *info-start-grab-y*)
(setf (info-x info) (min (max (- *info-start-grab-x* root-x) 0) (info-max-x info))
(info-y info) (min (max (- *info-start-grab-y* root-y) 0) (info-max-y info)))
(draw-info-window info)))
(defun info-mouse-select-item (window root-x root-y info)
(declare (ignore window))
(set-info-item-form-mouse root-x root-y info)
(leave-info-mode-and-valid info))
(defun info-mouse-motion-click (window root-x root-y info)
(declare (ignore window))
(let ((last *info-selected-item*))
(set-info-item-form-mouse root-x root-y info)
(unless (equal last *info-selected-item*)
(draw-info-window info))))
(defun set-default-info-mouse ()
(if *info-click-to-select*
(define-info-mouse (1) nil 'info-mouse-select-item)
(define-info-mouse (1) 'info-begin-grab 'info-end-grab))
(define-info-mouse (2) 'mouse-leave-info-mode)
(define-info-mouse (3) 'mouse-leave-info-mode)
(define-info-mouse (4) 'info-mouse-previous-line)
(define-info-mouse (5) 'info-mouse-next-line)
(if *info-click-to-select*
(define-info-mouse ('motion) 'info-mouse-motion-click nil)
(define-info-mouse ('motion) 'info-mouse-motion-drag nil)))
(add-hook *binding-hook* 'set-default-info-mouse)
(let (info)
(define-handler info-mode :key-press (code state)
(funcall-key-from-code *info-keys* code state info))
(define-handler info-mode :motion-notify (window root-x root-y)
(unless (compress-motion-notify)
(funcall-button-from-code *info-mouse* 'motion (modifiers->state *default-modifiers*)
window root-x root-y *fun-press* (list info))))
(define-handler info-mode :button-press (window root-x root-y code state)
(funcall-button-from-code *info-mouse* code state window root-x root-y *fun-press* (list info)))
(define-handler info-mode :button-release (window root-x root-y code state)
(funcall-button-from-code *info-mouse* code state window root-x root-y *fun-release* (list info)))
(defun info-mode (info-list &key (width nil) (height nil))
"Open the info mode. Info-list is a list of info: One string per line
Or for colored output: a list (line_string color)
Or ((1_word color) (2_word color) 3_word (4_word color)...)"
(when info-list
(setf *info-selected-item* 0)
(labels ((compute-size (line)
(typecase line
(cons (typecase (first line)
(cons (let ((val 0))
(dolist (l line val)
(incf val (typecase l
(cons (length (first l)))
(t (length l)))))))
(t (length (first line)))))
(t (length line)))))
(let* ((font (xlib:open-font *display* *info-font-string*))
(ilw (xlib:max-char-width font))
(ilh (+ (xlib:max-char-ascent font) (xlib:max-char-descent font) 1))
(width (or width
(min (* (+ (loop for l in info-list maximize (compute-size l)) 2) ilw)
(screen-width))))
(height (or height
(min (round (+ (* (length info-list) ilh) (/ ilh 2)))
(screen-height)))))
(with-placement (*info-mode-placement* x y width height)
(let* ((window (xlib:create-window :parent *root*
:x x :y y
:width width
:height height
:background (get-color *info-background*)
:colormap (xlib:screen-default-colormap *screen*)
:border-width *border-size*
:border (get-color *info-border*)
:event-mask '(:exposure)))
(gc (xlib:create-gcontext :drawable window
:foreground (get-color *info-foreground*)
:background (get-color *info-background*)
:font font
:line-style :solid)))
(setf info (make-info :window window :gc gc :x 0 :y 0 :list info-list
:font font :ilw ilw :ilh ilh
:max-x (* (loop for l in info-list maximize (compute-size l)) ilw)
:max-y (* (length info-list) ilh)))
(setf (window-transparency window) *info-transparency*)
(map-window window)
(draw-info-window info)
(wait-no-key-or-button-press)
(with-grab-keyboard-and-pointer (68 69 66 67)
(generic-mode 'info-mode 'exit-info-loop
:original-mode '(main-mode)))
(xlib:free-gcontext gc)
(xlib:destroy-window window)
(xlib:close-font font)
(xlib:display-finish-output *display*)
(display-all-frame-info)
(wait-no-key-or-button-press)
*info-selected-item*)))))))
(defun info-mode-menu (item-list &key (width nil) (height nil))
"Open an info help menu.
Item-list is: '((key function) separator (key function))
or with explicit docstring: '((key function \"documentation 1\") (key function \"bla bla\") (key function))
key is a character, a keycode or a keysym
Separator is a string or a symbol (all but a list)
Function can be a function or a list (function color) for colored output"
(let ((info-list nil)
(action nil)
(old-info-keys (copy-hash-table *info-keys*)))
(labels ((define-key (key function)
(define-info-key-fun (list key)
(lambda (&optional args)
(declare (ignore args))
(setf action function)
(leave-info-mode nil)))))
(dolist (item item-list)
(typecase item
(cons (destructuring-bind (key function explicit-doc) (ensure-n-elems item 3)
(typecase function
(cons (push (list (list (format nil "~A" key) *menu-color-menu-key*)
(list (format nil ": ~A" (or explicit-doc (documentation (first function) 'function)))
(second function)))
info-list)
(define-key key (first function)))
(t (push (list (list (format nil "~A" key) *menu-color-key*)
(format nil ": ~A" (or explicit-doc (documentation function 'function))))
info-list)
(define-key key function)))))
(t (push (list (format nil "-=- ~A -=-" item) *menu-color-comment*) info-list))))
(let ((selected-item (info-mode (nreverse info-list) :width width :height height)))
(setf *info-keys* old-info-keys)
(when selected-item
(awhen (nth selected-item item-list)
(when (consp it)
(destructuring-bind (key function explicit-doc) (ensure-n-elems it 3)
(declare (ignore key explicit-doc))
(typecase function
(cons (setf action (first function)))
(t (setf action function)))))))
(typecase action
(function (funcall action))
(symbol (when (fboundp action)
(funcall action))))))))
(defun keys-from-list (list)
"Produce a key menu based on list item"
(loop for l in list
for i from 0
collect (list (number->char i) l)))
(loop :for line :in list
:collect (cond ((search "* CLFSWM Keys *" line) (list line *info-color-title*))
((search "---" line) (list line *info-color-underline*))
((begin-with-2-spaces line)
(list (list (subseq line 0 22) *info-color-second*)
(list (subseq line 22 44) *info-color-first*)
(subseq line 44)))
(t line))))
(defun show-key-binding (&rest hash-table-key)
"Show the binding of each hash-table-key.
Pass the :no-producing-doc symbol to remove the producing doc"
(info-mode (key-binding-colorize-line
(split-string (append-newline-space
(with-output-to-string (stream)
(produce-doc (remove :no-producing-doc hash-table-key)
stream
(not (member :no-producing-doc hash-table-key)))))
#\Newline))))
(defun show-global-key-binding ()
"Show all key binding"
(show-key-binding *main-keys* *main-mouse* *second-keys* *second-mouse*
*info-keys* *info-mouse*))
(defun show-main-mode-key-binding ()
"Show the main mode binding"
(show-key-binding *main-keys* *main-mouse*))
(defun show-second-mode-key-binding ()
"Show the second mode key binding"
(show-key-binding *second-keys* *second-mouse*))
(defun show-circulate-mode-key-binding ()
"Show the circulate mode key binding"
(show-key-binding *circulate-keys*))
(defun show-expose-window-mode-key-binding ()
"Show the expose window mode key binding"
(show-key-binding *expose-keys* *expose-mouse*))
(defun show-first-aid-kit ()
"Show the first aid kit key binding"
(labels ((add-key (hash symbol &optional (hashkey *main-keys*))
(multiple-value-bind (k v)
(find-in-hash symbol hashkey)
(setf (gethash k hash) v))))
(let ((hash (make-hash-table :test #'equal))
(hash-second (make-hash-table :test #'equal)))
(setf (gethash 'name hash) "First aid kit - Main mode key binding"
(gethash 'name hash-second) "First aid kit - Second mode key binding")
(add-key hash 'select-next-child)
(add-key hash 'select-previous-child)
(add-key hash 'select-next-brother)
(add-key hash 'select-previous-brother)
(add-key hash 'select-previous-level)
(add-key hash 'select-next-level)
(add-key hash 'enter-frame)
(add-key hash 'leave-frame)
(add-key hash 'second-key-mode)
(add-key hash 'expose-windows-mode)
(add-key hash 'expose-all-windows-mode)
(add-key hash 'present-clfswm-terminal)
(add-key hash-second 'leave-second-mode *second-keys*)
(add-key hash-second 'open-menu *second-keys*)
(add-key hash-second 'run-program-from-query-string *second-keys*)
(add-key hash-second 'eval-from-query-string *second-keys*)
(add-key hash-second 'set-open-in-new-frame-in-parent-frame-nw-hook *second-keys*)
(add-key hash-second 'b-start-xterm *second-keys*)
(add-key hash-second 'b-start-emacs *second-keys*)
(show-key-binding hash hash-second :no-producing-doc))))
(defun corner-help-colorize-line (list)
(loop :for line :in list
:collect (cond ((search "CLFSWM:" line) (list line *info-color-title*))
((search "*:" line) (list line *info-color-underline*))
((begin-with-2-spaces line)
(let ((pos (position #\: line)))
(if pos
(list (list (subseq line 0 (1+ pos)) *info-color-first*)
(subseq line (1+ pos)))
line)))
(t line))))
(defun show-corner-help ()
"Help on clfswm corner"
(info-mode (corner-help-colorize-line
(split-string (append-newline-space
(with-output-to-string (stream)
(produce-corner-doc stream)))
#\Newline))))
(defun configuration-variable-colorize-line (list)
(loop :for line :in list
:collect (cond ((search "CLFSWM " line) (list line *info-color-title*))
((search "* =" line)
(let ((pos (position #\= line)))
(list (list (subseq line 0 (1+ pos)) *info-color-first*)
(list (subseq line (1+ pos)) *info-color-second*))))
((search "<=" line) (list line *info-color-underline*))
(t line))))
(defun show-config-variable ()
"Show all configurable variables"
(let ((result nil))
(labels ((rec ()
(setf result nil)
(info-mode-menu (loop :for group :in (config-all-groups)
:for i :from 0
:collect (list (number->char i)
(let ((group group))
(lambda ()
(setf result group)))
(config-group->string group))))
(when result
(info-mode (configuration-variable-colorize-line
(split-string (append-newline-space
(with-output-to-string (stream)
(produce-conf-var-doc stream result t nil)))
#\Newline)))
(rec))))
(rec))))
(defun show-date ()
"Show the current time and date"
(info-mode (list (list `("Current date:" ,*menu-color-comment*) (date-string)))))
(defun info-on-shell (msg program)
(let ((lines (do-shell program nil t)))
(info-mode (append (list (list msg *menu-color-comment*))
(loop for line = (read-line lines nil nil)
while line
collect (ensure-printable line))))))
(defun show-cpu-proc ()
"Show current processes sorted by CPU usage"
(info-on-shell "Current processes sorted by CPU usage:"
"ps --cols=1000 --sort='-%cpu,uid,pgid,ppid,pid' -e -o user,pid,stime,pcpu,pmem,args"))
(defun show-mem-proc ()
"Show current processes sorted by memory usage"
(info-on-shell "Current processes sorted by MEMORY usage:"
"ps --cols=1000 --sort='-vsz,uid,pgid,ppid,pid' -e -o user,pid,stime,pcpu,pmem,args"))
(defun show-cd-info ()
"Show the current CD track"
(info-on-shell "Current CD track:" "pcd i"))
(defun show-cd-playlist ()
"Show the current CD playlist"
(info-on-shell "Current CD playlist:" "pcd mi"))
(defun show-version ()
"Show the current CLFSWM version"
(info-mode (list *version*)))
|
b2cea8045aa3ced6bc5e3ee8cc2dbf581d5ab6cd91f450da2cc272f1b32b841f | tolitius/cbass | tools.clj | (ns cbass.tools
(:require [taoensso.nippy :as n]
[æsahættr :refer [hash-object hash-bytes murmur3-32 murmur3-128]])
(:import [org.apache.hadoop.hbase.util Bytes]
[java.time Instant ZoneId ZonedDateTime ZoneOffset Duration]
[java.time.format DateTimeFormatter]
(com.google.common.hash HashCode)))
(defmacro bytes? [s]
`(= (Class/forName "[B")
(.getClass ~s)))
(defmacro to-bytes [s]
`(if-not (bytes? ~s)
(Bytes/toBytes ~s)
~s))
(defmacro from-bytes [s]
`(Bytes/fromBytes ~s))
(defn bytes->num
"Convert byte array to a number"
[data]
(BigInteger. data))
(defn bytes->str
"Convert byte array to a string"
[data]
(apply str (map char data)))
(defn thaw [data]
(when (seq data)
(n/thaw data)))
(defonce no-values
(byte-array 0))
(defn hash-it [obj]
(->> obj
(hash-object (murmur3-128))
str))
(defn hash-key [#^bytes k-bytes]
(.asBytes ^HashCode (hash-bytes (murmur3-32)
k-bytes)))
(defn current-utc-millis []
(-> (ZoneOffset/UTC)
(ZonedDateTime/now)
(.toInstant)
(.toEpochMilli)))
(defn parse-long [ts]
(try
(Long/valueOf ^String ts)
(catch Throwable t
(prn "could not parse " ts " to a Long due to " (class t) ": " (.getMessage t)))))
(defn str-now [ts]
(if-let [timestamp (parse-long ts)]
(-> (ZonedDateTime/ofInstant
(Instant/ofEpochMilli timestamp)
(ZoneId/of "UTC"))
(.format (DateTimeFormatter/ofPattern "yyyy-MM-dd HH:mm:ss.SSS")))))
| null | https://raw.githubusercontent.com/tolitius/cbass/73701133650c7b5b8a3e098abd66c1987319b7a8/src/cbass/tools.clj | clojure | (ns cbass.tools
(:require [taoensso.nippy :as n]
[æsahættr :refer [hash-object hash-bytes murmur3-32 murmur3-128]])
(:import [org.apache.hadoop.hbase.util Bytes]
[java.time Instant ZoneId ZonedDateTime ZoneOffset Duration]
[java.time.format DateTimeFormatter]
(com.google.common.hash HashCode)))
(defmacro bytes? [s]
`(= (Class/forName "[B")
(.getClass ~s)))
(defmacro to-bytes [s]
`(if-not (bytes? ~s)
(Bytes/toBytes ~s)
~s))
(defmacro from-bytes [s]
`(Bytes/fromBytes ~s))
(defn bytes->num
"Convert byte array to a number"
[data]
(BigInteger. data))
(defn bytes->str
"Convert byte array to a string"
[data]
(apply str (map char data)))
(defn thaw [data]
(when (seq data)
(n/thaw data)))
(defonce no-values
(byte-array 0))
(defn hash-it [obj]
(->> obj
(hash-object (murmur3-128))
str))
(defn hash-key [#^bytes k-bytes]
(.asBytes ^HashCode (hash-bytes (murmur3-32)
k-bytes)))
(defn current-utc-millis []
(-> (ZoneOffset/UTC)
(ZonedDateTime/now)
(.toInstant)
(.toEpochMilli)))
(defn parse-long [ts]
(try
(Long/valueOf ^String ts)
(catch Throwable t
(prn "could not parse " ts " to a Long due to " (class t) ": " (.getMessage t)))))
(defn str-now [ts]
(if-let [timestamp (parse-long ts)]
(-> (ZonedDateTime/ofInstant
(Instant/ofEpochMilli timestamp)
(ZoneId/of "UTC"))
(.format (DateTimeFormatter/ofPattern "yyyy-MM-dd HH:mm:ss.SSS")))))
| |
2aa44a2934f75e14d2c66b00a720a5335acea80e5337afc7cbcffe0810ffad73 | incoherentsoftware/defect-process | Shot.hs | module Player.Gun.All.Revolver.Shot
( mkShotProjectile
) where
import Control.Monad.IO.Class (MonadIO)
import qualified Data.List.NonEmpty as NE
import qualified Data.Set as S
import Attack.Hit
import Collision
import Configs
import Configs.All.PlayerGun.Revolver
import Configs.All.Settings
import Configs.All.Settings.Debug
import Constants
import FileCache
import Id
import Msg
import Particle
import Particle.All.AttackSpecks.Types
import Particle.All.Simple
import Player
import Player.Gun.All.Revolver.Util
import Projectile as P
import Util
import Window.Graphics
import World.ZIndex
gunsPack = \p -> PackResourceFilePath "data/player/player-guns.pack" p
missEffectPaths = NE.fromList
[ gunsPack "bullet-miss-effect-a.spr"
, gunsPack "bullet-miss-effect-b.spr"
, gunsPack "bullet-miss-effect-c.spr"
] :: NE.NonEmpty PackResourceFilePath
whiffEffectPaths = NE.fromList
[ gunsPack "bullet-whiff-effect-a.spr"
, gunsPack "bullet-whiff-effect-b.spr"
, gunsPack "bullet-whiff-effect-c.spr"
] :: NE.NonEmpty PackResourceFilePath
hitEffectPaths = NE.fromList
[ gunsPack "bullet-hit-effect-a.spr"
, gunsPack "bullet-hit-effect-b.spr"
, gunsPack "bullet-hit-effect-c.spr"
] :: NE.NonEmpty PackResourceFilePath
enemyHitSoundPath = "event:/SFX Events/Player/Guns/gun-hit" :: FilePath
surfaceHitSoundPath = "event:/SFX Events/Player/Guns/gun-surface-hit" :: FilePath
debugHitboxColor = Color 155 155 155 255 :: Color
data ShotData = ShotData
{ _type :: RevolverShotType
, _config :: RevolverConfig
}
mkShotProjectile :: MonadIO m => RevolverShotType -> Player -> RevolverConfig -> m (Some Projectile)
mkShotProjectile shotType player cfg =
let
plId = _msgId (player :: Player)
pos = playerShoulderPos player
targetPos = playerAimTarget player (_shootRange cfg)
shotAliveSecs = _shotAliveSecs cfg
in do
msgId <- newId
let
shotData = ShotData
{ _type = shotType
, _config = cfg
}
hbx = lineHitbox pos targetPos
return . Some $ (mkProjectile shotData msgId hbx shotAliveSecs)
{ _ownerId = plId
, _registeredCollisions = S.fromList
[ ProjRegisteredEnemyCollision
, ProjRegisteredSurfaceCollision
, ProjRegisteredRoomItemCollision
]
, _think = thinkShot targetPos
, _draw = drawShotLine
, _processCollisions = processShotCollisions
}
thinkShot :: Monad m => Pos2 -> ProjectileThink ShotData m
thinkShot targetPos shot = return $ if
| P._ttl shot - timeStep <= 0.0 ->
let
mkWhiffEffect = do
whiffEffectPath <- randomChoice whiffEffectPaths
loadSimpleParticle targetPos RightDir worldEffectZIndex whiffEffectPath
in [mkMsg $ ParticleMsgAddM mkWhiffEffect]
| otherwise -> []
processShotCollisions :: ProjectileProcessCollisions ShotData
processShotCollisions projCollisions shot = processCollisions $ sortProjectileCollisions projCollisions shot
where
processCollisions :: [(Pos2, ProjectileCollision)] -> [Msg ThinkCollisionMsgsPhase]
processCollisions [] = []
processCollisions ((intersectPos, collision):collisions) = case collision of
shot stops at first thing hit
ProjEnemyCollision enemy -> shotEntityCollision enemy shot intersectPos
ProjSurfaceCollision hbx _ -> shotSurfaceCollision hbx shot intersectPos
ProjRoomItemCollision (Some roomItem) -> shotEntityCollision roomItem shot intersectPos
_ -> processCollisions collisions
shotSurfaceCollision :: Hitbox -> Projectile ShotData -> Pos2 -> [Msg ThinkCollisionMsgsPhase]
shotSurfaceCollision nonEnemyHbx shot intersectPos =
[ mkMsgTo (ProjectileMsgSetHitbox hitbox) shotId
, mkMsgTo ProjectileMsgRemoveCollision shotId
, mkMsgTo ProjectileMsgRemoveThink shotId
, mkMsg $ ParticleMsgAddM mkMissEffect
, mkMsg $ AudioMsgPlaySound surfaceHitSoundPath intersectPos
]
where
shotId = P._msgId shot
startPos = hitboxStartVertex $ projectileHitbox shot
hitbox = lineHitbox startPos intersectPos
(effectDir, effectAngle) = particleClosestDirAngle intersectPos nonEnemyHbx
mkMissEffect = do
missEffectPath <- randomChoice missEffectPaths
loadSimpleParticleRotated intersectPos effectDir worldEffectZIndex effectAngle missEffectPath
shotEntityCollision :: CollisionEntity e => e -> Projectile ShotData -> Pos2 -> [Msg ThinkCollisionMsgsPhase]
shotEntityCollision entity shot intersectPos =
[ mkMsgTo (ProjectileMsgSetHitbox hitbox) shotId
, mkMsgTo ProjectileMsgRemoveCollision shotId
, mkMsgTo ProjectileMsgRemoveThink shotId
, mkMsg $ ParticleMsgAddM mkImpactEffect
, mkMsgTo (HurtMsgAttackHit shotHit) entityId
, mkMsg $ AudioMsgPlaySoundUnique enemyHitSoundPath hashedShotId intersectPos
]
where
shotId = P._msgId shot
startPos = hitboxStartVertex $ projectileHitbox shot
hitbox = lineHitbox startPos intersectPos
hashedShotId = hashId shotId
entityId = collisionEntityMsgId entity
entityHbx = collisionEntityHitbox entity
(effectDir, effectAngle) = particleClosestDirAngle intersectPos entityHbx
mkImpactEffect = do
hitEffectPath <- randomChoice hitEffectPaths
loadSimpleParticleRotated intersectPos effectDir worldEffectZIndex effectAngle hitEffectPath
shotData = P._data shot
cfg = _config (shotData :: ShotData)
shotDamage = case _type shotData of
RevolverNormalShotType -> _normalShotDamage cfg
RevolverContinuousShotType -> _continuousShotDamage cfg
shotHit = (mkAttackHitEmpty shotId intersectPos)
{ _vel = _shotHitVel cfg
, _damage = shotDamage
, _stagger = _shotStagger cfg
, _hitstunMultiplier = _shotHitstunMultiplier cfg
, _isRanged = True
, _specksType = Just BulletSpecksType
, _specksDirection = Just SpecksAnyDir
}
drawShotLine :: (ConfigsRead m, GraphicsReadWrite m, MonadIO m) => ProjectileDraw ShotData m
drawShotLine projectile = whenM (readSettingsConfig _debug _drawEntityHitboxes) $
let points = hitboxVertices $ projectileHitbox projectile
in drawLines points debugHitboxColor debugHitboxZIndex
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/ae362274cca0e59c0fc0dcaee0f0e208db8ccc46/src/Player/Gun/All/Revolver/Shot.hs | haskell | module Player.Gun.All.Revolver.Shot
( mkShotProjectile
) where
import Control.Monad.IO.Class (MonadIO)
import qualified Data.List.NonEmpty as NE
import qualified Data.Set as S
import Attack.Hit
import Collision
import Configs
import Configs.All.PlayerGun.Revolver
import Configs.All.Settings
import Configs.All.Settings.Debug
import Constants
import FileCache
import Id
import Msg
import Particle
import Particle.All.AttackSpecks.Types
import Particle.All.Simple
import Player
import Player.Gun.All.Revolver.Util
import Projectile as P
import Util
import Window.Graphics
import World.ZIndex
gunsPack = \p -> PackResourceFilePath "data/player/player-guns.pack" p
missEffectPaths = NE.fromList
[ gunsPack "bullet-miss-effect-a.spr"
, gunsPack "bullet-miss-effect-b.spr"
, gunsPack "bullet-miss-effect-c.spr"
] :: NE.NonEmpty PackResourceFilePath
whiffEffectPaths = NE.fromList
[ gunsPack "bullet-whiff-effect-a.spr"
, gunsPack "bullet-whiff-effect-b.spr"
, gunsPack "bullet-whiff-effect-c.spr"
] :: NE.NonEmpty PackResourceFilePath
hitEffectPaths = NE.fromList
[ gunsPack "bullet-hit-effect-a.spr"
, gunsPack "bullet-hit-effect-b.spr"
, gunsPack "bullet-hit-effect-c.spr"
] :: NE.NonEmpty PackResourceFilePath
enemyHitSoundPath = "event:/SFX Events/Player/Guns/gun-hit" :: FilePath
surfaceHitSoundPath = "event:/SFX Events/Player/Guns/gun-surface-hit" :: FilePath
debugHitboxColor = Color 155 155 155 255 :: Color
data ShotData = ShotData
{ _type :: RevolverShotType
, _config :: RevolverConfig
}
mkShotProjectile :: MonadIO m => RevolverShotType -> Player -> RevolverConfig -> m (Some Projectile)
mkShotProjectile shotType player cfg =
let
plId = _msgId (player :: Player)
pos = playerShoulderPos player
targetPos = playerAimTarget player (_shootRange cfg)
shotAliveSecs = _shotAliveSecs cfg
in do
msgId <- newId
let
shotData = ShotData
{ _type = shotType
, _config = cfg
}
hbx = lineHitbox pos targetPos
return . Some $ (mkProjectile shotData msgId hbx shotAliveSecs)
{ _ownerId = plId
, _registeredCollisions = S.fromList
[ ProjRegisteredEnemyCollision
, ProjRegisteredSurfaceCollision
, ProjRegisteredRoomItemCollision
]
, _think = thinkShot targetPos
, _draw = drawShotLine
, _processCollisions = processShotCollisions
}
thinkShot :: Monad m => Pos2 -> ProjectileThink ShotData m
thinkShot targetPos shot = return $ if
| P._ttl shot - timeStep <= 0.0 ->
let
mkWhiffEffect = do
whiffEffectPath <- randomChoice whiffEffectPaths
loadSimpleParticle targetPos RightDir worldEffectZIndex whiffEffectPath
in [mkMsg $ ParticleMsgAddM mkWhiffEffect]
| otherwise -> []
processShotCollisions :: ProjectileProcessCollisions ShotData
processShotCollisions projCollisions shot = processCollisions $ sortProjectileCollisions projCollisions shot
where
processCollisions :: [(Pos2, ProjectileCollision)] -> [Msg ThinkCollisionMsgsPhase]
processCollisions [] = []
processCollisions ((intersectPos, collision):collisions) = case collision of
shot stops at first thing hit
ProjEnemyCollision enemy -> shotEntityCollision enemy shot intersectPos
ProjSurfaceCollision hbx _ -> shotSurfaceCollision hbx shot intersectPos
ProjRoomItemCollision (Some roomItem) -> shotEntityCollision roomItem shot intersectPos
_ -> processCollisions collisions
shotSurfaceCollision :: Hitbox -> Projectile ShotData -> Pos2 -> [Msg ThinkCollisionMsgsPhase]
shotSurfaceCollision nonEnemyHbx shot intersectPos =
[ mkMsgTo (ProjectileMsgSetHitbox hitbox) shotId
, mkMsgTo ProjectileMsgRemoveCollision shotId
, mkMsgTo ProjectileMsgRemoveThink shotId
, mkMsg $ ParticleMsgAddM mkMissEffect
, mkMsg $ AudioMsgPlaySound surfaceHitSoundPath intersectPos
]
where
shotId = P._msgId shot
startPos = hitboxStartVertex $ projectileHitbox shot
hitbox = lineHitbox startPos intersectPos
(effectDir, effectAngle) = particleClosestDirAngle intersectPos nonEnemyHbx
mkMissEffect = do
missEffectPath <- randomChoice missEffectPaths
loadSimpleParticleRotated intersectPos effectDir worldEffectZIndex effectAngle missEffectPath
shotEntityCollision :: CollisionEntity e => e -> Projectile ShotData -> Pos2 -> [Msg ThinkCollisionMsgsPhase]
shotEntityCollision entity shot intersectPos =
[ mkMsgTo (ProjectileMsgSetHitbox hitbox) shotId
, mkMsgTo ProjectileMsgRemoveCollision shotId
, mkMsgTo ProjectileMsgRemoveThink shotId
, mkMsg $ ParticleMsgAddM mkImpactEffect
, mkMsgTo (HurtMsgAttackHit shotHit) entityId
, mkMsg $ AudioMsgPlaySoundUnique enemyHitSoundPath hashedShotId intersectPos
]
where
shotId = P._msgId shot
startPos = hitboxStartVertex $ projectileHitbox shot
hitbox = lineHitbox startPos intersectPos
hashedShotId = hashId shotId
entityId = collisionEntityMsgId entity
entityHbx = collisionEntityHitbox entity
(effectDir, effectAngle) = particleClosestDirAngle intersectPos entityHbx
mkImpactEffect = do
hitEffectPath <- randomChoice hitEffectPaths
loadSimpleParticleRotated intersectPos effectDir worldEffectZIndex effectAngle hitEffectPath
shotData = P._data shot
cfg = _config (shotData :: ShotData)
shotDamage = case _type shotData of
RevolverNormalShotType -> _normalShotDamage cfg
RevolverContinuousShotType -> _continuousShotDamage cfg
shotHit = (mkAttackHitEmpty shotId intersectPos)
{ _vel = _shotHitVel cfg
, _damage = shotDamage
, _stagger = _shotStagger cfg
, _hitstunMultiplier = _shotHitstunMultiplier cfg
, _isRanged = True
, _specksType = Just BulletSpecksType
, _specksDirection = Just SpecksAnyDir
}
drawShotLine :: (ConfigsRead m, GraphicsReadWrite m, MonadIO m) => ProjectileDraw ShotData m
drawShotLine projectile = whenM (readSettingsConfig _debug _drawEntityHitboxes) $
let points = hitboxVertices $ projectileHitbox projectile
in drawLines points debugHitboxColor debugHitboxZIndex
| |
c7d32289575983b275020be691cfc6956ab6fe7a8bf6f8e971c4e7aea5d76455 | open-company/open-company-web | lazy_stream.cljs | (ns oc.web.components.ui.lazy-stream
(:require [rum.core :as rum]
[org.martinklepsch.derivatives :as drv]
[oc.web.dispatcher :as dis]
[oc.web.components.paginated-stream :refer (paginated-stream)]
[oc.web.actions.nav-sidebar :as nav-actions]
[oc.web.lib.utils :as utils]))
(def last-container-slug (atom nil))
(rum/defcs lazy-stream < rum/static
rum/reactive
(rum/local false ::delay)
(drv/drv :container-data)
(drv/drv :activity-data)
(drv/drv :board-slug)
;; (drv/drv :foc-layout)
{:will-mount (fn [s]
(let [container-slug (or (dis/current-board-slug) (dis/current-label-slug) (dis/current-contributions-id) (dis/current-entry-board-slug))]
(when-not (= container-slug @last-container-slug)
(reset! (::delay s) true)
(reset! last-container-slug container-slug)
(utils/after nav-actions/feed-render-delay #(reset! (::delay s) false)))
s))
:did-mount (fn [s]
(utils/scroll-to-y (dis/route-param :scroll-y) 0)
s)}
[s stream-comp]
(let [container-data (drv/react s :container-data)
_current-board-slug (drv/react s :board-slug)
foc - layout ( drv / react s : foc - layout )
data-ready? (map? container-data)
delay? @(::delay s)
collapsed - foc ? ( or (= foc - layout dis / other - foc - layout )
;; (= current-board-slug "replies"))
]
[:div.lazy-stream
(cond ;; (not data-ready?)
;; [:div.lazy-stream-interstitial
;; {:class (when collapsed-foc? "collapsed")
;; :style {:height (str (+ (dis/route-param :scroll-y)
;; (or (.. js/document -documentElement -clientHeight)
;; (.-innerHeight js/window)))
;; "px")}}]
(or delay?
(not data-ready?))
[:div.lazy-stream-pre-render-view]
:else
(paginated-stream))]))
| null | https://raw.githubusercontent.com/open-company/open-company-web/700f751b8284d287432ba73007b104f26669be91/src/main/oc/web/components/ui/lazy_stream.cljs | clojure | (drv/drv :foc-layout)
(= current-board-slug "replies"))
(not data-ready?)
[:div.lazy-stream-interstitial
{:class (when collapsed-foc? "collapsed")
:style {:height (str (+ (dis/route-param :scroll-y)
(or (.. js/document -documentElement -clientHeight)
(.-innerHeight js/window)))
"px")}}] | (ns oc.web.components.ui.lazy-stream
(:require [rum.core :as rum]
[org.martinklepsch.derivatives :as drv]
[oc.web.dispatcher :as dis]
[oc.web.components.paginated-stream :refer (paginated-stream)]
[oc.web.actions.nav-sidebar :as nav-actions]
[oc.web.lib.utils :as utils]))
(def last-container-slug (atom nil))
(rum/defcs lazy-stream < rum/static
rum/reactive
(rum/local false ::delay)
(drv/drv :container-data)
(drv/drv :activity-data)
(drv/drv :board-slug)
{:will-mount (fn [s]
(let [container-slug (or (dis/current-board-slug) (dis/current-label-slug) (dis/current-contributions-id) (dis/current-entry-board-slug))]
(when-not (= container-slug @last-container-slug)
(reset! (::delay s) true)
(reset! last-container-slug container-slug)
(utils/after nav-actions/feed-render-delay #(reset! (::delay s) false)))
s))
:did-mount (fn [s]
(utils/scroll-to-y (dis/route-param :scroll-y) 0)
s)}
[s stream-comp]
(let [container-data (drv/react s :container-data)
_current-board-slug (drv/react s :board-slug)
foc - layout ( drv / react s : foc - layout )
data-ready? (map? container-data)
delay? @(::delay s)
collapsed - foc ? ( or (= foc - layout dis / other - foc - layout )
]
[:div.lazy-stream
(or delay?
(not data-ready?))
[:div.lazy-stream-pre-render-view]
:else
(paginated-stream))]))
|
f79596ea62d1103fc6acedc4a5c41da0c07c63cb12710050820a4330f4d3bfcc | bn-d/ppx_make | record_types.ml | type b = { b1 : int } [@@deriving make]
type o = { o1 : int option } [@@deriving make]
type l = { l1 : int list } [@@deriving make]
type a = { a1 : int array } [@@deriving make]
type s = { s1 : string } [@@deriving make]
(*type q = { q1 : int seq }[@@deriving make]*)
type d = { answer : int [@default 42] } [@@deriving make]
type m = { m1 : int; [@main] m2 : int [@main] } [@@deriving make]
type r = {
r1 : int option;
r2 : string; [@required]
r3 : int option; [@required]
}
[@@deriving make]
type complex = {
c1 : int;
c2 : int option;
c3 : int list;
c4 : string;
c5 : int; [@make.default 1024]
c6 : string; [@make.required]
}
[@@deriving make]
type complex_with_main = {
cm1 : int; [@make.main]
cm2 : int option;
cm3 : int Option.t; [@main]
}
[@@deriving make]
| null | https://raw.githubusercontent.com/bn-d/ppx_make/1fa039397d839a7c9199e32b16e6623b4c199f16/test/record_types.ml | ocaml | type q = { q1 : int seq }[@@deriving make] | type b = { b1 : int } [@@deriving make]
type o = { o1 : int option } [@@deriving make]
type l = { l1 : int list } [@@deriving make]
type a = { a1 : int array } [@@deriving make]
type s = { s1 : string } [@@deriving make]
type d = { answer : int [@default 42] } [@@deriving make]
type m = { m1 : int; [@main] m2 : int [@main] } [@@deriving make]
type r = {
r1 : int option;
r2 : string; [@required]
r3 : int option; [@required]
}
[@@deriving make]
type complex = {
c1 : int;
c2 : int option;
c3 : int list;
c4 : string;
c5 : int; [@make.default 1024]
c6 : string; [@make.required]
}
[@@deriving make]
type complex_with_main = {
cm1 : int; [@make.main]
cm2 : int option;
cm3 : int Option.t; [@main]
}
[@@deriving make]
|
6084b81efcb9079c808e44cf9b31409a656c84b4490860f2e19347ee8db95cff | andersfugmann/ppx_protocol_conv | test_types.ml | open Sexplib.Std
module Make(Driver: Testable.Driver) = struct
module M = Testable.Make(Driver)
module S3 : M.Testable = struct
let name = "S3"
type storage_class = Standard [@key "STANDARD"]
| Standard_ia [@key "STANDARD_IA"]
| Reduced_redundancy [@key "REDUCED_REDUNDANCY"]
| Glacier [@key "GLACIER"]
and content = {
storage_class: storage_class [@key "StorageClass"];
etag: string [@key "ETag"];
}
and t = {
prefix: string option [@key "Prefix"];
contents: content list [@key "Contents"];
}
[@@deriving protocol ~driver:(module Driver), sexp]
let t = { prefix = Some "prefix";
contents = [ { storage_class = Standard; etag = "Etag" } ]
}
end
module T : M.Testable = struct
let name = "Types"
type a = string * int list
and aopt = a option
and v = Variant_one of int [@key "Variant_two1"]
| Variant_two of string
and y = {
y_a: int [@key "y_a"];
y_b: a;
y_c_: aopt [@key "y_yc"];
y_d_: v [@key "y_yd"];
}
and t = {
foo: int;
bar: string;
baz: y;
}
[@@deriving protocol ~driver:(module Driver), sexp]
let t = { foo=1;
bar="true";
baz={ y_a=2;
y_b=("two", [10; 20; 30]);
y_c_=Some ("three", [100; 200; 300]);
y_d_=Variant_one 1
};
}
end
let unittest = __MODULE__, [
M.test (module S3);
M.test (module T);
]
end
| null | https://raw.githubusercontent.com/andersfugmann/ppx_protocol_conv/e93eb01ca8ba8c7dd734070316cd281a199dee0d/test/test_types.ml | ocaml | open Sexplib.Std
module Make(Driver: Testable.Driver) = struct
module M = Testable.Make(Driver)
module S3 : M.Testable = struct
let name = "S3"
type storage_class = Standard [@key "STANDARD"]
| Standard_ia [@key "STANDARD_IA"]
| Reduced_redundancy [@key "REDUCED_REDUNDANCY"]
| Glacier [@key "GLACIER"]
and content = {
storage_class: storage_class [@key "StorageClass"];
etag: string [@key "ETag"];
}
and t = {
prefix: string option [@key "Prefix"];
contents: content list [@key "Contents"];
}
[@@deriving protocol ~driver:(module Driver), sexp]
let t = { prefix = Some "prefix";
contents = [ { storage_class = Standard; etag = "Etag" } ]
}
end
module T : M.Testable = struct
let name = "Types"
type a = string * int list
and aopt = a option
and v = Variant_one of int [@key "Variant_two1"]
| Variant_two of string
and y = {
y_a: int [@key "y_a"];
y_b: a;
y_c_: aopt [@key "y_yc"];
y_d_: v [@key "y_yd"];
}
and t = {
foo: int;
bar: string;
baz: y;
}
[@@deriving protocol ~driver:(module Driver), sexp]
let t = { foo=1;
bar="true";
baz={ y_a=2;
y_b=("two", [10; 20; 30]);
y_c_=Some ("three", [100; 200; 300]);
y_d_=Variant_one 1
};
}
end
let unittest = __MODULE__, [
M.test (module S3);
M.test (module T);
]
end
| |
e7de9d52aa40d5f32f1efff47e621042b5c311898d40d0c52ce756972147ce18 | drlivingston/kabob | refseq_to_uniprot_mapping_rules.clj | ;; The UniProt idmapping_selected.tab file contains a variety of identifier mappings. Here we link
;; mappings among protein identifiers using the skos:exactMatch predicate
;; uniport to refseq
`{:name "refseq-uniprot-exact-mapping-assertion"
:head ((?/uniprot skos/exactMatch ?/refseq))
:body
(~@(kabob/rtv _/record
iaoeg/EntrezGeneRefSeqUniprotKbCollabFileData_uniprotIdDataField1
?/uniprot
iaoeg/EntrezGeneRefSeqUniprotKbCollabFileData_refSeqProteinIdDataField1
?/refseq)
(?/refseq kiao/denotesSubClassOf obo/CHEBI_36080))} ;protein
rdf / type kiao / ProteinIdentifier ) ) } ; is this triple redundant ?
TODO figure out what this was ?
UniProt_ID skos : exactMatch RefSeq_Protein_ID
This only holds true when the NCBI taxonomy IDs match for the two entities ,
;; so there will be further links to add via subclass_of
;; `{:name "uniprot-exact-refseq-id-mapping-assertion"
;; :head ((?/uniprotIce skos/exactMatch ?/refseqProteinIce))
;; :body
;; ((_/record kiao/hasTemplate
iaoeg / egEntrezGeneRefSeqUniprotKbCollabFileDataSchema1 )
;; ~@(kabob/rtv _/record
iaoeg / egrefSeqProteinIdDataField1 ? /refseqProteinIce
iaoeg / eguniprotIdDataField1 ? /uniprotIce )
( _ /refseqRecord kiao / hasTemplate
;; iaorefseq/refseqRefSeqReleaseCatalogFileDataSchema1)
;; ~@(kabob/rtv _/refseqRecord
iaorefseq / refseqrefseqIdDataField1 ? /refseqProteinIce
;; iaorefseq/refseqtaxIdDataField1 _/taxId)
;; (_/uniprotRecord kiao/hasTemplate
;; iaouniprot/uniprotUniProtDatFileDataSchema1)
;; ~@(kabob/rtv _/uniprotRecord
;; iaouniprot/uniprotprimaryUniProtIDDataField1 ?/uniprotIce
;; iaouniprot/uniprotncbiTaxonomyIDDataField1 _/taxId))}
| null | https://raw.githubusercontent.com/drlivingston/kabob/7038076849744c959da9c8507e8a8ab7215410aa/kabob-build/src/main/resources/edu/ucdenver/ccp/kabob/build/rules/id_mapping/skos_exact/refseq_to_uniprot_mapping_rules.clj | clojure | The UniProt idmapping_selected.tab file contains a variety of identifier mappings. Here we link
mappings among protein identifiers using the skos:exactMatch predicate
uniport to refseq
protein
is this triple redundant ?
so there will be further links to add via subclass_of
`{:name "uniprot-exact-refseq-id-mapping-assertion"
:head ((?/uniprotIce skos/exactMatch ?/refseqProteinIce))
:body
((_/record kiao/hasTemplate
~@(kabob/rtv _/record
iaorefseq/refseqRefSeqReleaseCatalogFileDataSchema1)
~@(kabob/rtv _/refseqRecord
iaorefseq/refseqtaxIdDataField1 _/taxId)
(_/uniprotRecord kiao/hasTemplate
iaouniprot/uniprotUniProtDatFileDataSchema1)
~@(kabob/rtv _/uniprotRecord
iaouniprot/uniprotprimaryUniProtIDDataField1 ?/uniprotIce
iaouniprot/uniprotncbiTaxonomyIDDataField1 _/taxId))} |
`{:name "refseq-uniprot-exact-mapping-assertion"
:head ((?/uniprot skos/exactMatch ?/refseq))
:body
(~@(kabob/rtv _/record
iaoeg/EntrezGeneRefSeqUniprotKbCollabFileData_uniprotIdDataField1
?/uniprot
iaoeg/EntrezGeneRefSeqUniprotKbCollabFileData_refSeqProteinIdDataField1
?/refseq)
TODO figure out what this was ?
UniProt_ID skos : exactMatch RefSeq_Protein_ID
This only holds true when the NCBI taxonomy IDs match for the two entities ,
iaoeg / egEntrezGeneRefSeqUniprotKbCollabFileDataSchema1 )
iaoeg / egrefSeqProteinIdDataField1 ? /refseqProteinIce
iaoeg / eguniprotIdDataField1 ? /uniprotIce )
( _ /refseqRecord kiao / hasTemplate
iaorefseq / refseqrefseqIdDataField1 ? /refseqProteinIce
|
2b159331f4880b41bb60cca2edc2e4b4e0cb74b9423a14bfcea3fb74facb0265 | ocaml-community/yojson | monomorphic.mli | val pp : Format.formatter -> t -> unit
(** Pretty printer, useful for debugging *)
val show : t -> string
(** Convert value to string, useful for debugging *)
val equal : t -> t -> bool
* [ equal a b ] is the monomorphic equality .
Determines whether two JSON values are considered equal . In the case of
JSON objects , the order of the keys does not matter , except for
duplicate keys which will be considered equal as long as they are in the
same input order .
Determines whether two JSON values are considered equal. In the case of
JSON objects, the order of the keys does not matter, except for
duplicate keys which will be considered equal as long as they are in the
same input order.
*)
| null | https://raw.githubusercontent.com/ocaml-community/yojson/a3fbc94d1d57bcacb00d3b1b9ec4aa602326a4d0/lib/monomorphic.mli | ocaml | * Pretty printer, useful for debugging
* Convert value to string, useful for debugging | val pp : Format.formatter -> t -> unit
val show : t -> string
val equal : t -> t -> bool
* [ equal a b ] is the monomorphic equality .
Determines whether two JSON values are considered equal . In the case of
JSON objects , the order of the keys does not matter , except for
duplicate keys which will be considered equal as long as they are in the
same input order .
Determines whether two JSON values are considered equal. In the case of
JSON objects, the order of the keys does not matter, except for
duplicate keys which will be considered equal as long as they are in the
same input order.
*)
|
a4c551d2f8fd6001ede388e65ec61212d5dd2754035574f835f8803fdbf47d55 | Metaxal/bazaar | compiler.rkt | #lang racket/base
; Originally from /collects/scribble/tools/drracket-buttons.rkt
(require racket/runtime-path
;racket/class
racket/path
racket/system
setup/xref
;net/sendurl
)
(provide scribble->PDF
scribble->HTML)
(define-namespace-anchor anchor)
; file should be a full-path
(define (scribble-compile file mode suffix extra-cmdline)
;(printf "A\n")
(let-values ([(out) (current-output-port)]
[(p) (open-output-string)]
[(base name dir?) (split-path file)])
(parameterize ([current-namespace (make-base-namespace)]
[current-output-port p]
[current-error-port p]
[current-directory
(path-only (path->complete-path file))]
[current-command-line-arguments
(list->vector
(append
extra-cmdline
( list " --quiet " )
(list mode
(path->string (file-name-from-path file)))))])
;(fprintf out "cla:~a\n" (current-command-line-arguments))
;(fprintf out "currdir:~a\n" (current-directory))
(namespace-attach-module (namespace-anchor->empty-namespace anchor) 'setup/xref)
( fprintf out " C\n " )
(dynamic-require 'scribble/run #f)
)
; (current-output-port out)
( fprintf out " " )
; return:
(displayln (get-output-string p))
))
(define (scribble->HTML file)
(scribble-compile file "--html" #".html"
'("++xref-in" "setup/xref" "load-collections-xref")))
(define (scribble->PDF file)
(scribble-compile file "--pdf" #".pdf" null))
#;(cond
[(equal? suffix #".html")
(send-url/file (path-replace-suffix fn suffix))]
[else
(system (format "open ~s" (path->string (path-replace-suffix fn suffix))))])
#;(let ([html-button
(make-render-button "Scribble HTML" html.png "--html" #".html"
'("++xref-in" "setup/xref" "load-collections-xref"))]
[pdf-button
only available on OSX currently
;; when we have a general way of opening pdfs, can use that
(make-render-button "Scribble PDF" pdf.png "--pdf" #".pdf" null)]))
| null | https://raw.githubusercontent.com/Metaxal/bazaar/8432d3c5398225a4bfb5ed5c25a1beffa06409ec/scribble/compiler.rkt | racket | Originally from /collects/scribble/tools/drracket-buttons.rkt
racket/class
net/sendurl
file should be a full-path
(printf "A\n")
(fprintf out "cla:~a\n" (current-command-line-arguments))
(fprintf out "currdir:~a\n" (current-directory))
(current-output-port out)
return:
(cond
(let ([html-button
when we have a general way of opening pdfs, can use that | #lang racket/base
(require racket/runtime-path
racket/path
racket/system
setup/xref
)
(provide scribble->PDF
scribble->HTML)
(define-namespace-anchor anchor)
(define (scribble-compile file mode suffix extra-cmdline)
(let-values ([(out) (current-output-port)]
[(p) (open-output-string)]
[(base name dir?) (split-path file)])
(parameterize ([current-namespace (make-base-namespace)]
[current-output-port p]
[current-error-port p]
[current-directory
(path-only (path->complete-path file))]
[current-command-line-arguments
(list->vector
(append
extra-cmdline
( list " --quiet " )
(list mode
(path->string (file-name-from-path file)))))])
(namespace-attach-module (namespace-anchor->empty-namespace anchor) 'setup/xref)
( fprintf out " C\n " )
(dynamic-require 'scribble/run #f)
)
( fprintf out " " )
(displayln (get-output-string p))
))
(define (scribble->HTML file)
(scribble-compile file "--html" #".html"
'("++xref-in" "setup/xref" "load-collections-xref")))
(define (scribble->PDF file)
(scribble-compile file "--pdf" #".pdf" null))
[(equal? suffix #".html")
(send-url/file (path-replace-suffix fn suffix))]
[else
(system (format "open ~s" (path->string (path-replace-suffix fn suffix))))])
(make-render-button "Scribble HTML" html.png "--html" #".html"
'("++xref-in" "setup/xref" "load-collections-xref"))]
[pdf-button
only available on OSX currently
(make-render-button "Scribble PDF" pdf.png "--pdf" #".pdf" null)]))
|
732c8d21b6efed2132af3debfe1f1a032fbee485e75c86b81e3e970f5bf14727 | ryukinix/discrete-mathematics | functions.hs | {--
This file explain the basic function to do:
* type declaration
* pattern matching
* function definition
* function composition
--}
-- :: factorial function
fat :: Integer -> Integer
fat 0 = 1
fat n | n > 0 = n * fat (n - 1)
-- :: fibonacci function
| domain and contra - domain declaration
fib :: Integer -> Integer
-- | pattern matching
fib n | n <= 1 = 1
-- | formal definition of fib function
fib n | n > 1 = fib(n - 1) + fib(n - 2)
-- | function composition
-- is just like fatfib = fat(fib(x))
fatfib :: Integer -> Integer
fatfib = fat . fib
-- :: Function types
-- f :: a -> b
-- The function argument has the type a and result the type b
For example , some of the functions that we have already seen have the following types :
-- sqrt :: Double -> Double
-- max :: Integer -> Integer -> Integer
-- not :: Bool -> Bool
toUpper : :
-- :: Operators and Functions
-- When we are dealing with operators, we just put parenthesis around it
-- to specify at it. Operators are just functions with infix arguments.
An another way to do 3 + 2 is calling ( + ) 3 2 , the two statements will result
in 6 .
-- We can use any function as operator just using a back-quote on them.
max 2 3 = > 3 is equal to 2 ` max ` 3 = > 3
m = max 2 3
m' = 2 `max` 3
m'' = m == m'
-- :: Function Definitions
-- We can define new functions giving the type declaration followed by the
-- defining equation.
-- function_name :: arg1Type -> arg2Type -> ... -> argTypen -> resultType
-- function_name arg1 arg2 arg3 = exp using the arguments
square :: Integer -> Integer
square x = x * x
square 2 = > 4
-- :: Pattern Matching
-- If the argument on the left-hand side is a constant,
-- then the right-hand will be used only if the function is applied
-- to that value.
-- This makes it possible for a function definition to consist of several
-- defining equations.
f :: Integer -> String
f 1 = "one"
f 2 = "two"
f 3 = "three"
f n = show n
isThree :: Int -> Bool
isThree 3 = True
isThree x = False
nor :: Bool -> Bool -> Bool
nor False False = True
nor a b = False
first :: (a, b) -> a
first (x,y) = x
second :: (a,b) -> b
second (x,y) = y
isEmpty :: [a] -> Bool
isEmpty [] = True
isEmpty (x:xs) = False
-- guards are indicated by pipes that follow a function's names
-- and its parameters. A more powerful way of pattern matching
-- using multiple conditions
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| weight / height ^ 2 <= 18.5 = "You're underweight, you emo, you!"
| weight / height ^ 2 <= 25.0 = "You're supposedly normal. Pfft, i bet you are ugly!"
| weight / height ^ 2 <= 30.0 = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
max' :: (Ord a) => a -> a -> a
max' a b
| a > b = a
| otherwise = b
-- where bindings
initials :: String -> String -> String
initials firstname lastname = [f] ++ ". " ++ [l] ++ "."
where (f:_) = firstname
(l:_) = lastname
-- let bindings
cylinder :: (RealFloat a) => a -> a -> a
cylinder r h =
let sideArea = 2 * pi * r * h
topArea = pi * r ^ 2
in sideArea + 2 * topArea
-- case expressions
head' :: [a] -> a
head' xs = case xs of [] -> error "No head for empty lists!"
(x:_) -> x
describeList :: [a] -> String
describeList xs = "The list is " ++ case xs of [] -> "empty."
[x] -> "a singleton list."
xs -> "a longer list"
-- alternative version using where
describeList' xs = "The list is " ++ what xs
where what [] = "empty."
what [x] = "a singleton"
what xs = "a longer list"
f' x = case x of 10 -> 10
x -> x + 1
| null | https://raw.githubusercontent.com/ryukinix/discrete-mathematics/1f779e05822c094af33745e2dd3c9a35c6dfb388/src/01-introduction-to-haskell/functions.hs | haskell | -
This file explain the basic function to do:
* type declaration
* pattern matching
* function definition
* function composition
-
:: factorial function
:: fibonacci function
| pattern matching
| formal definition of fib function
| function composition
is just like fatfib = fat(fib(x))
:: Function types
f :: a -> b
The function argument has the type a and result the type b
sqrt :: Double -> Double
max :: Integer -> Integer -> Integer
not :: Bool -> Bool
:: Operators and Functions
When we are dealing with operators, we just put parenthesis around it
to specify at it. Operators are just functions with infix arguments.
We can use any function as operator just using a back-quote on them.
:: Function Definitions
We can define new functions giving the type declaration followed by the
defining equation.
function_name :: arg1Type -> arg2Type -> ... -> argTypen -> resultType
function_name arg1 arg2 arg3 = exp using the arguments
:: Pattern Matching
If the argument on the left-hand side is a constant,
then the right-hand will be used only if the function is applied
to that value.
This makes it possible for a function definition to consist of several
defining equations.
guards are indicated by pipes that follow a function's names
and its parameters. A more powerful way of pattern matching
using multiple conditions
where bindings
let bindings
case expressions
alternative version using where |
fat :: Integer -> Integer
fat 0 = 1
fat n | n > 0 = n * fat (n - 1)
| domain and contra - domain declaration
fib :: Integer -> Integer
fib n | n <= 1 = 1
fib n | n > 1 = fib(n - 1) + fib(n - 2)
fatfib :: Integer -> Integer
fatfib = fat . fib
For example , some of the functions that we have already seen have the following types :
toUpper : :
An another way to do 3 + 2 is calling ( + ) 3 2 , the two statements will result
in 6 .
max 2 3 = > 3 is equal to 2 ` max ` 3 = > 3
m = max 2 3
m' = 2 `max` 3
m'' = m == m'
square :: Integer -> Integer
square x = x * x
square 2 = > 4
f :: Integer -> String
f 1 = "one"
f 2 = "two"
f 3 = "three"
f n = show n
isThree :: Int -> Bool
isThree 3 = True
isThree x = False
nor :: Bool -> Bool -> Bool
nor False False = True
nor a b = False
first :: (a, b) -> a
first (x,y) = x
second :: (a,b) -> b
second (x,y) = y
isEmpty :: [a] -> Bool
isEmpty [] = True
isEmpty (x:xs) = False
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| weight / height ^ 2 <= 18.5 = "You're underweight, you emo, you!"
| weight / height ^ 2 <= 25.0 = "You're supposedly normal. Pfft, i bet you are ugly!"
| weight / height ^ 2 <= 30.0 = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
max' :: (Ord a) => a -> a -> a
max' a b
| a > b = a
| otherwise = b
initials :: String -> String -> String
initials firstname lastname = [f] ++ ". " ++ [l] ++ "."
where (f:_) = firstname
(l:_) = lastname
cylinder :: (RealFloat a) => a -> a -> a
cylinder r h =
let sideArea = 2 * pi * r * h
topArea = pi * r ^ 2
in sideArea + 2 * topArea
head' :: [a] -> a
head' xs = case xs of [] -> error "No head for empty lists!"
(x:_) -> x
describeList :: [a] -> String
describeList xs = "The list is " ++ case xs of [] -> "empty."
[x] -> "a singleton list."
xs -> "a longer list"
describeList' xs = "The list is " ++ what xs
where what [] = "empty."
what [x] = "a singleton"
what xs = "a longer list"
f' x = case x of 10 -> 10
x -> x + 1
|
f44e37863cfbc3937a25cfaf56229f2b524739422b6f784339fa82ad5675ef60 | metabase/metabase | upload.clj | (ns release.common.upload
(:require
[metabuild-common.core :as u]
[release.common :as c]))
(defn upload-artifact!
"Upload an artifact to downloads.metabase.com and create a CloudFront invalidation."
([source-file filename]
(upload-artifact! source-file (c/version) filename))
([source-file version filename]
(u/step (format "Upload %s to %s" source-file (c/artifact-download-url version filename))
(u/s3-copy! (u/assert-file-exists source-file) (c/s3-artifact-url version filename))
(u/create-cloudfront-invalidation! c/cloudfront-distribution-id (c/s3-artifact-path version filename)))))
| null | https://raw.githubusercontent.com/metabase/metabase/5e9b52a32dfeab754d218c758d08fffbacb7c0e7/bin/build/src/release/common/upload.clj | clojure | (ns release.common.upload
(:require
[metabuild-common.core :as u]
[release.common :as c]))
(defn upload-artifact!
"Upload an artifact to downloads.metabase.com and create a CloudFront invalidation."
([source-file filename]
(upload-artifact! source-file (c/version) filename))
([source-file version filename]
(u/step (format "Upload %s to %s" source-file (c/artifact-download-url version filename))
(u/s3-copy! (u/assert-file-exists source-file) (c/s3-artifact-url version filename))
(u/create-cloudfront-invalidation! c/cloudfront-distribution-id (c/s3-artifact-path version filename)))))
| |
5893daa120473a70490dea295aef73c89f7cc15d5c620e65975c0c3217c0cb13 | alex-gutev/generic-cl | object.lisp | ;;;; object.lisp
;;;;
Copyright 2019
;;;;
;;;; 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.
(in-package :generic-cl.object)
;;; Miscellaneous generic functions for manipulating objects
(defgeneric copy (object &key &allow-other-keys)
(:documentation
"Returns a copy of OBJECT. Some methods may accept additional
keyword arguments which allow options, on how the object is to be
copied, to be specified.
Methods specialized on sequences or collections should accept
the :DEEP keyword argument which if provided and is true, the
objects contained in the sequence/collection should be copied as
well otherwise (if not provided or is NIL) only the
sequence/collection itself should be copied."))
(defgeneric coerce (object result-type)
(:documentation
"Coerces the OBJECT to the type RESULT-TYPE.")
(:method (object type)
(cl:coerce object type)))
;;;; Copy methods for standard objects.
;;; Lists
(defmethod copy ((list cons) &key deep)
(if deep
(deep-copy-list list)
(copy-list list)))
(defun deep-copy-list (list)
"Returns a copy of LIST which contains a copy (by COPY) of each
object contained in it."
(let ((tail (cons nil nil)))
(do ((tail tail)
(head list (cdr head)))
((atom head) (setf (cdr tail) (copy head :deep t)))
(->> (cons (copy (car head) :deep t) nil)
(setf (cdr tail))
(setf tail)))
(cdr tail)))
;;; Vectors
(defmethod copy ((array vector) &key deep)
(if deep
(deep-copy-vector array)
(copy-array array)))
(defun deep-copy-vector (vec)
"Returns a copy of the vector VEC which contains a copy (by COPY) of
each object contained in it."
(let ((new (make-array (cl:length vec)
:element-type (array-element-type vec)
:adjustable (adjustable-array-p vec)
:fill-pointer (and (array-has-fill-pointer-p vec)
(fill-pointer vec)))))
(loop
for elem across vec
for i = 0 then (cl:1+ i)
do
(setf (aref new i) (copy elem :deep t)))
new))
;;; Arrays
(defmethod copy ((array array) &key deep)
(if deep
(deep-copy-array array)
(copy-array array)))
(defun deep-copy-array (array)
"Returns a copy of the multi-dimensional ARRAY which contains a
copy (by COPY) of each object contained in it."
(let ((new (make-array (array-dimensions array)
:element-type (array-element-type array)
:adjustable (adjustable-array-p array))))
(loop
for i from 0 below (array-total-size array)
do
(setf (row-major-aref new i)
(copy (row-major-aref array i) :deep t)))
new))
;;; Structures
(defmethod copy ((object structure-object) &key)
(copy-structure object))
;;; Other Objects
(defmethod copy (object &key)
"Default method, does not copy OBJECT."
object)
| null | https://raw.githubusercontent.com/alex-gutev/generic-cl/e337b8d2198791994f4377a522bf0200d2285548/src/object/object.lisp | lisp | object.lisp
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
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.
Miscellaneous generic functions for manipulating objects
Copy methods for standard objects.
Lists
Vectors
Arrays
Structures
Other Objects | Copyright 2019
files ( the " Software " ) , to deal in the Software without
copies of the Software , and to permit persons to whom the
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(in-package :generic-cl.object)
(defgeneric copy (object &key &allow-other-keys)
(:documentation
"Returns a copy of OBJECT. Some methods may accept additional
keyword arguments which allow options, on how the object is to be
copied, to be specified.
Methods specialized on sequences or collections should accept
the :DEEP keyword argument which if provided and is true, the
objects contained in the sequence/collection should be copied as
well otherwise (if not provided or is NIL) only the
sequence/collection itself should be copied."))
(defgeneric coerce (object result-type)
(:documentation
"Coerces the OBJECT to the type RESULT-TYPE.")
(:method (object type)
(cl:coerce object type)))
(defmethod copy ((list cons) &key deep)
(if deep
(deep-copy-list list)
(copy-list list)))
(defun deep-copy-list (list)
"Returns a copy of LIST which contains a copy (by COPY) of each
object contained in it."
(let ((tail (cons nil nil)))
(do ((tail tail)
(head list (cdr head)))
((atom head) (setf (cdr tail) (copy head :deep t)))
(->> (cons (copy (car head) :deep t) nil)
(setf (cdr tail))
(setf tail)))
(cdr tail)))
(defmethod copy ((array vector) &key deep)
(if deep
(deep-copy-vector array)
(copy-array array)))
(defun deep-copy-vector (vec)
"Returns a copy of the vector VEC which contains a copy (by COPY) of
each object contained in it."
(let ((new (make-array (cl:length vec)
:element-type (array-element-type vec)
:adjustable (adjustable-array-p vec)
:fill-pointer (and (array-has-fill-pointer-p vec)
(fill-pointer vec)))))
(loop
for elem across vec
for i = 0 then (cl:1+ i)
do
(setf (aref new i) (copy elem :deep t)))
new))
(defmethod copy ((array array) &key deep)
(if deep
(deep-copy-array array)
(copy-array array)))
(defun deep-copy-array (array)
"Returns a copy of the multi-dimensional ARRAY which contains a
copy (by COPY) of each object contained in it."
(let ((new (make-array (array-dimensions array)
:element-type (array-element-type array)
:adjustable (adjustable-array-p array))))
(loop
for i from 0 below (array-total-size array)
do
(setf (row-major-aref new i)
(copy (row-major-aref array i) :deep t)))
new))
(defmethod copy ((object structure-object) &key)
(copy-structure object))
(defmethod copy (object &key)
"Default method, does not copy OBJECT."
object)
|
9964ee51864c004e058572b2fed7310af0c05c8ad0598a47ce08e51fd6b10a7f | sig-gis/gridfire | spotting_test.clj | (ns gridfire.spec.spotting-test
(:require [clojure.spec.alpha :as s]
[clojure.test :refer [deftest is testing]]
[gridfire.spec.spotting :as spotting]))
(deftest spotting-test
(let [required {:mean-distance {:lo 5.0 :hi 15.0}
:normalized-distance-variance {:lo 250.0 :hi 600.0}
:flin-exp {:lo 0.2 :hi 0.4}
:ws-exp {:lo 0.4 :hi 0.7}
:crown-fire-spotting-percent [0.1 0.8]
:num-firebrands 10}]
(testing "required"
(is (s/valid? ::spotting/spotting required)))
(testing "optional surface-fire-spotting"
(let [optional {:surface-fire-spotting {:spotting-percent [[[1 149] 1.0]
[[150 169] 2.0]
[[169 204] 3.0]]
:critical-fire-line-intensity 2000.0}}]
(is (s/valid? ::spotting/spotting (merge required optional)))))))
(deftest crown-fire-spotting-percent-test
(testing "scalar"
(is (s/valid? ::spotting/crown-fire-spotting-percent 0.1)))
(testing "range"
(is (s/valid? ::spotting/crown-fire-spotting-percent [0.1 0.8])))
(testing "invalid range"
(is (not (s/valid? ::spotting/crown-fire-spotting-percent [0.8 0.1]))
"first value should not be larger than the second")))
(deftest num-firebrands-test
(testing "scalar"
(is (s/valid? ::spotting/num-firebrands 10)))
(testing "range"
(is (s/valid? ::spotting/num-firebrands {:lo 1 :hi 10})
"lo and hi can both be scalar")
(is (s/valid? ::spotting/num-firebrands {:lo [1 2] :hi [9 10]})
"lo and hi can both be ranges")
(is (s/valid? ::spotting/num-firebrands {:lo 1 :hi [9 10]})
"lo and hi can either be scalar or range"))
(testing "edge cases"
(is (s/valid? ::spotting/num-firebrands {:lo 1 :hi [1 2]})
"edge of ranges can overlap")
(is (s/valid? ::spotting/num-firebrands {:lo [1 2] :hi [2 3]})
"edge of ranges can overlap"))
(testing "invalid range"
(let [config {:lo 10
:hi 1 }]
(is (not (s/valid? ::spotting/num-firebrands config))
"lo syhould not be higher than hi"))
(let [config {:lo [1 3]
:hi [2 3]}]
(is (not (s/valid? ::spotting/num-firebrands config))
"should not have overlapping ranges"))))
(deftest surface-fire-spotting-test
(testing "scalar percents"
(let [config [[[1 149] 1.0]
[[150 169] 2.0]
[[169 204] 3.0]]]
(is (s/valid? ::spotting/spotting-percent config))))
(testing "range percents"
(let [config [[[1 149] [1.0 2.0]]
[[150 169] [3.0 4.0]]
[[169 204] [0.2 0.4]]]]
(is (s/valid? ::spotting/spotting-percent config)))))
(deftest scalar-or-map
(testing "scalar"
(is (s/valid? ::spotting/scalar-or-map 5.0)
"scalar can be float")
(is (s/valid? ::spotting/scalar-or-map 5)
"scalar can be int"))
(testing "range"
(is (s/valid? ::spotting/scalar-or-map {:lo 5.0 :hi 15.0})
"lo and hi can both be scalar floats")
(is (s/valid? ::spotting/scalar-or-map {:lo 5 :hi 15})
"lo and hi can both be scalar ints")
(is (s/valid? ::spotting/scalar-or-map {:lo [1.0 5.0] :hi [15.0 16.0]})
"lo and hi can both be float tuples")
(is (s/valid? ::spotting/scalar-or-map {:lo [1 5] :hi [15 16]})
"lo and hi can both be int tuples")
(is (s/valid? ::spotting/scalar-or-map {:lo 5.0 :hi [15.0 16.0]})
"lo and hi can either be scalar or range"))
(testing "edge cases"
(is (s/valid? ::spotting/scalar-or-map {:lo 5.0 :hi [5.0 6.0]})
"edge of ranges can overlap")
(is (s/valid? ::spotting/scalar-or-map {:lo [1.0 2.0] :hi [2.0 3.0]})
"edge of ranges can overlap"))
(testing "invalid range"
(let [config {:lo 10.0
:hi 1.0 }]
(is (not (s/valid? ::spotting/scalar-or-map config))
"lo should not be higher than hi"))
(let [config {:lo [1.0 3.0]
:hi [2.0 3.0]}]
(is (not (s/valid? ::spotting/scalar-or-map config))
"should not have overlapping ranges"))))
| null | https://raw.githubusercontent.com/sig-gis/gridfire/44aeaf56fceb01f61b21db6220d2cb562a92570b/test/gridfire/spec/spotting_test.clj | clojure | (ns gridfire.spec.spotting-test
(:require [clojure.spec.alpha :as s]
[clojure.test :refer [deftest is testing]]
[gridfire.spec.spotting :as spotting]))
(deftest spotting-test
(let [required {:mean-distance {:lo 5.0 :hi 15.0}
:normalized-distance-variance {:lo 250.0 :hi 600.0}
:flin-exp {:lo 0.2 :hi 0.4}
:ws-exp {:lo 0.4 :hi 0.7}
:crown-fire-spotting-percent [0.1 0.8]
:num-firebrands 10}]
(testing "required"
(is (s/valid? ::spotting/spotting required)))
(testing "optional surface-fire-spotting"
(let [optional {:surface-fire-spotting {:spotting-percent [[[1 149] 1.0]
[[150 169] 2.0]
[[169 204] 3.0]]
:critical-fire-line-intensity 2000.0}}]
(is (s/valid? ::spotting/spotting (merge required optional)))))))
(deftest crown-fire-spotting-percent-test
(testing "scalar"
(is (s/valid? ::spotting/crown-fire-spotting-percent 0.1)))
(testing "range"
(is (s/valid? ::spotting/crown-fire-spotting-percent [0.1 0.8])))
(testing "invalid range"
(is (not (s/valid? ::spotting/crown-fire-spotting-percent [0.8 0.1]))
"first value should not be larger than the second")))
(deftest num-firebrands-test
(testing "scalar"
(is (s/valid? ::spotting/num-firebrands 10)))
(testing "range"
(is (s/valid? ::spotting/num-firebrands {:lo 1 :hi 10})
"lo and hi can both be scalar")
(is (s/valid? ::spotting/num-firebrands {:lo [1 2] :hi [9 10]})
"lo and hi can both be ranges")
(is (s/valid? ::spotting/num-firebrands {:lo 1 :hi [9 10]})
"lo and hi can either be scalar or range"))
(testing "edge cases"
(is (s/valid? ::spotting/num-firebrands {:lo 1 :hi [1 2]})
"edge of ranges can overlap")
(is (s/valid? ::spotting/num-firebrands {:lo [1 2] :hi [2 3]})
"edge of ranges can overlap"))
(testing "invalid range"
(let [config {:lo 10
:hi 1 }]
(is (not (s/valid? ::spotting/num-firebrands config))
"lo syhould not be higher than hi"))
(let [config {:lo [1 3]
:hi [2 3]}]
(is (not (s/valid? ::spotting/num-firebrands config))
"should not have overlapping ranges"))))
(deftest surface-fire-spotting-test
(testing "scalar percents"
(let [config [[[1 149] 1.0]
[[150 169] 2.0]
[[169 204] 3.0]]]
(is (s/valid? ::spotting/spotting-percent config))))
(testing "range percents"
(let [config [[[1 149] [1.0 2.0]]
[[150 169] [3.0 4.0]]
[[169 204] [0.2 0.4]]]]
(is (s/valid? ::spotting/spotting-percent config)))))
(deftest scalar-or-map
(testing "scalar"
(is (s/valid? ::spotting/scalar-or-map 5.0)
"scalar can be float")
(is (s/valid? ::spotting/scalar-or-map 5)
"scalar can be int"))
(testing "range"
(is (s/valid? ::spotting/scalar-or-map {:lo 5.0 :hi 15.0})
"lo and hi can both be scalar floats")
(is (s/valid? ::spotting/scalar-or-map {:lo 5 :hi 15})
"lo and hi can both be scalar ints")
(is (s/valid? ::spotting/scalar-or-map {:lo [1.0 5.0] :hi [15.0 16.0]})
"lo and hi can both be float tuples")
(is (s/valid? ::spotting/scalar-or-map {:lo [1 5] :hi [15 16]})
"lo and hi can both be int tuples")
(is (s/valid? ::spotting/scalar-or-map {:lo 5.0 :hi [15.0 16.0]})
"lo and hi can either be scalar or range"))
(testing "edge cases"
(is (s/valid? ::spotting/scalar-or-map {:lo 5.0 :hi [5.0 6.0]})
"edge of ranges can overlap")
(is (s/valid? ::spotting/scalar-or-map {:lo [1.0 2.0] :hi [2.0 3.0]})
"edge of ranges can overlap"))
(testing "invalid range"
(let [config {:lo 10.0
:hi 1.0 }]
(is (not (s/valid? ::spotting/scalar-or-map config))
"lo should not be higher than hi"))
(let [config {:lo [1.0 3.0]
:hi [2.0 3.0]}]
(is (not (s/valid? ::spotting/scalar-or-map config))
"should not have overlapping ranges"))))
| |
23ee7ee059fffc04f58c1e16c6a4671b2f2a9216f3f715f8293fac18dce2d87a | plumatic/grab-bag | admin.clj | (ns dashboard.pages.admin
(:use plumbing.core)
(:require
[plumbing.graph :as graph]
[plumbing.parallel :as parallel]
[store.snapshots :as snapshots]
[service.nameserver :as nameserver]
[dashboard.pages.admin.api :as api]))
(set! *warn-on-reflection* true)
(def admin-resources
(graph/graph
:snapshots-cache (graph/instance parallel/refreshing-resource [nameserver get-snapshot-store]
{:secs 15
:f (fn []
(for-map [[nm info] (nameserver/service-map nameserver)]
nm {:info info
:last-snapshot (try (api/sanitize (snapshots/read-latest-snapshot (get-snapshot-store nm)))
(catch Exception e {:snapshot-read-error (pr-str e)}))}))})
))
| null | https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/service/dashboard/src/clj/dashboard/pages/admin.clj | clojure | (ns dashboard.pages.admin
(:use plumbing.core)
(:require
[plumbing.graph :as graph]
[plumbing.parallel :as parallel]
[store.snapshots :as snapshots]
[service.nameserver :as nameserver]
[dashboard.pages.admin.api :as api]))
(set! *warn-on-reflection* true)
(def admin-resources
(graph/graph
:snapshots-cache (graph/instance parallel/refreshing-resource [nameserver get-snapshot-store]
{:secs 15
:f (fn []
(for-map [[nm info] (nameserver/service-map nameserver)]
nm {:info info
:last-snapshot (try (api/sanitize (snapshots/read-latest-snapshot (get-snapshot-store nm)))
(catch Exception e {:snapshot-read-error (pr-str e)}))}))})
))
| |
f19fd9cb39342a08bd7c3254900ef288f8ee876f28bd54c81f997166431879b6 | eareese/htdp-exercises | 171-list-of-strings-definition.rkt | #lang htdp/bsl
(require 2htdp/batch-io)
Exercise 171 . You know what the data definition for List - of - strings looks like . Spell it out . Make sure that you can represent ’s poem as an instance of the definition where each line is a represented as a string and another one where each word is a string . Use read - lines and read - words to confirm your representation choices .
;;
Next develop the data definition for List - of - list - of - strings . Again , represent ’s poem as an instance of the definition where each line is a represented as a list of strings , one per word , and the entire poem is a list of such line representations . You may use read - words / line to confirm your choice .
Los ( short for List of strings ) is one of :
; - '()
; - (cons String Los)
A file represented by a list of lines is a Los :
( cons " TTT "
;; (cons ""
;; (cons "Put up in a place"
;; (cons "where it's easy to see"
;; (cons "the cryptic admonishment"
;; (cons ...
;; '()))))))
(read-lines "ttt.txt")
A file represented by a list of its words is also a Los :
( cons " TTT "
;; (cons "Put"
;; (cons "up"
;; (cons ...
;; '()))))
(read-words "ttt.txt")
Lls ( short for List of list of strings ) is one of :
; - '()
- ( cons Los Lls )
where Los is a List of strings .
; each line is a list.
; each line's list is a list of words
( cons ( cons " TTT " ' ( ) )
;; (cons '()
;; (cons (cons "Put"
;; (cons "up"
;; (cons ... '())))
;; (cons (cons "where"
;; (cons ... '()))
;; (cons ...
;; '())))))
(read-words/line "ttt.txt")
| null | https://raw.githubusercontent.com/eareese/htdp-exercises/a85ff3111d459dda0e94d9b463d01a09accbf9bf/part02-arbitrarily-large-data/171-list-of-strings-definition.rkt | racket |
- '()
- (cons String Los)
(cons ""
(cons "Put up in a place"
(cons "where it's easy to see"
(cons "the cryptic admonishment"
(cons ...
'()))))))
(cons "Put"
(cons "up"
(cons ...
'()))))
- '()
each line is a list.
each line's list is a list of words
(cons '()
(cons (cons "Put"
(cons "up"
(cons ... '())))
(cons (cons "where"
(cons ... '()))
(cons ...
'()))))) | #lang htdp/bsl
(require 2htdp/batch-io)
Exercise 171 . You know what the data definition for List - of - strings looks like . Spell it out . Make sure that you can represent ’s poem as an instance of the definition where each line is a represented as a string and another one where each word is a string . Use read - lines and read - words to confirm your representation choices .
Next develop the data definition for List - of - list - of - strings . Again , represent ’s poem as an instance of the definition where each line is a represented as a list of strings , one per word , and the entire poem is a list of such line representations . You may use read - words / line to confirm your choice .
Los ( short for List of strings ) is one of :
A file represented by a list of lines is a Los :
( cons " TTT "
(read-lines "ttt.txt")
A file represented by a list of its words is also a Los :
( cons " TTT "
(read-words "ttt.txt")
Lls ( short for List of list of strings ) is one of :
- ( cons Los Lls )
where Los is a List of strings .
( cons ( cons " TTT " ' ( ) )
(read-words/line "ttt.txt")
|
66a5d349df73aabb73c5e55d62bb7949104b4f70dc41370abb5fba73b9022aef | ejconlon/blanks | Sub.hs | {-# LANGUAGE DeriveAnyClass #-}
module Blanks.Util.Sub
( SubError (..)
, ThrowSub (..)
, rethrowSub
) where
import Control.DeepSeq (NFData)
import Control.Exception (Exception, throwIO)
import GHC.Generics (Generic)
-- | Errors that happen in the course of instantiation
data SubError
= ApplyError !Int !Int
| NonBinderError
deriving stock (Eq, Show, Generic)
deriving anyclass (NFData)
instance Exception SubError
| Some monadic context that lets you throw a ' SubError ' .
-- Exists to let you rethrow to a more convenient context rather than
-- pattern maching.
class ThrowSub m where
throwSub :: SubError -> m a
rethrowSub :: (Applicative m, ThrowSub m) => Either SubError a -> m a
rethrowSub = either throwSub pure
instance ThrowSub (Either SubError) where
throwSub = Left
instance ThrowSub IO where
throwSub = throwIO
| null | https://raw.githubusercontent.com/ejconlon/blanks/3235518e765a69f62ffaa1620e883270c2860dde/src/Blanks/Util/Sub.hs | haskell | # LANGUAGE DeriveAnyClass #
| Errors that happen in the course of instantiation
Exists to let you rethrow to a more convenient context rather than
pattern maching. |
module Blanks.Util.Sub
( SubError (..)
, ThrowSub (..)
, rethrowSub
) where
import Control.DeepSeq (NFData)
import Control.Exception (Exception, throwIO)
import GHC.Generics (Generic)
data SubError
= ApplyError !Int !Int
| NonBinderError
deriving stock (Eq, Show, Generic)
deriving anyclass (NFData)
instance Exception SubError
| Some monadic context that lets you throw a ' SubError ' .
class ThrowSub m where
throwSub :: SubError -> m a
rethrowSub :: (Applicative m, ThrowSub m) => Either SubError a -> m a
rethrowSub = either throwSub pure
instance ThrowSub (Either SubError) where
throwSub = Left
instance ThrowSub IO where
throwSub = throwIO
|
5710e3ad3464c3e05fa61d0410ff7978190b7d54afb575604d6aad59918c96af | hatsugai/Guedra | test_listboxvs.ml | open Csp
open Guedra
let interval_map a b f =
let rec g rs k =
if k >= b then
List.rev rs
else
g ((f k)::rs) (k + 1)
in g [] a
let item_string _ = ""
let draw_item x y width height cs i sel ud dc act =
(if i = sel then
(set_color o_o.color_fore;
fill_rect (flo x) (flo y) (flo width) (flo height);
set_color o_o.color_back)
else
set_color o_o.color_fore);
let label = Array.get cs i in
draw_text (flo x) (flo y) label
let init () =
let (wch, pch) = create_toplevel_window "Guedra" 0 0 768 512 in
let rch = make_chan () in
let cwch0 = make_chan () in
let cch = make_chan () in
let nch = make_chan () in
let cs = [(cwch0, rect 50 50 300 400)] in
let ud = {
Listbox.item_height = 18;
draw = draw_item;
item_string = item_string;
}
in
let rec process () =
recv nch always
(fun (cch, msg) ->
match msg with
Listbox.OnSelect (cs, i) ->
Printf.printf "sel: %d\n" i;
flush stdout;
process ()
| OnAction (cs, i) ->
Printf.printf "action: %d\n" i;
flush stdout;
process ()
| _ -> process ())
and main () =
let xs =
interval_map 0 100
(fun i -> Printf.sprintf "item %d (@#$%%&,.?MWgqy|)" i)
in
let v = Array.of_list xs in
send cch (Listbox.SetList (v, -1)) process
in
par [
(fun () -> Form.init wch pch rch cs);
(fun () -> Listboxvs.init cwch0 rch cch nch ud ());
main]
let () = reg_client init
| null | https://raw.githubusercontent.com/hatsugai/Guedra/592e9b4cff151228735d2c61c337154cde8b5329/test/test_listboxvs.ml | ocaml | open Csp
open Guedra
let interval_map a b f =
let rec g rs k =
if k >= b then
List.rev rs
else
g ((f k)::rs) (k + 1)
in g [] a
let item_string _ = ""
let draw_item x y width height cs i sel ud dc act =
(if i = sel then
(set_color o_o.color_fore;
fill_rect (flo x) (flo y) (flo width) (flo height);
set_color o_o.color_back)
else
set_color o_o.color_fore);
let label = Array.get cs i in
draw_text (flo x) (flo y) label
let init () =
let (wch, pch) = create_toplevel_window "Guedra" 0 0 768 512 in
let rch = make_chan () in
let cwch0 = make_chan () in
let cch = make_chan () in
let nch = make_chan () in
let cs = [(cwch0, rect 50 50 300 400)] in
let ud = {
Listbox.item_height = 18;
draw = draw_item;
item_string = item_string;
}
in
let rec process () =
recv nch always
(fun (cch, msg) ->
match msg with
Listbox.OnSelect (cs, i) ->
Printf.printf "sel: %d\n" i;
flush stdout;
process ()
| OnAction (cs, i) ->
Printf.printf "action: %d\n" i;
flush stdout;
process ()
| _ -> process ())
and main () =
let xs =
interval_map 0 100
(fun i -> Printf.sprintf "item %d (@#$%%&,.?MWgqy|)" i)
in
let v = Array.of_list xs in
send cch (Listbox.SetList (v, -1)) process
in
par [
(fun () -> Form.init wch pch rch cs);
(fun () -> Listboxvs.init cwch0 rch cch nch ud ());
main]
let () = reg_client init
| |
f12840073ff6f7c93b615b4501f0bafc9df5405f37bf4a4d9521299ae307859f | iamFIREcracker/adventofcode | day13.lisp | (defpackage :aoc/2020/13 #.cl-user::*aoc-use*)
(in-package :aoc/2020/13)
(defun read-buses (string &aux (offset 0) buses)
(dolist (item (cl-ppcre:split "," string) buses)
(when (string/= item "x")
(push (cons (parse-integer item) offset) buses))
(incf offset)))
(defun id (bus) (car bus))
(defun offset (bus) (cdr bus))
(defun read-notes (data)
(cons (parse-integer (first data)) (read-buses (second data))))
(defun earliest-departure (notes) (car notes))
(defun buses (notes) (cdr notes))
(defun wait-time (earliest-departure bus-period)
(let ((mod (mod earliest-departure bus-period)))
(if (zerop mod) 0 (- bus-period mod))))
(defun part1 (notes)
(multiple-value-call #'*
(find-min
(mapcar #'id (buses notes))
:key (partial-1 #'wait-time (earliest-departure notes)))))
(defun part2 (buses)
(loop with step = 1 and ts = 0
for (id . offset) in buses do
(loop until (zerop (wait-time (+ ts offset) id))
do (incf ts step))
(mulf step id)
finally (return ts)))
(define-solution (2020 13) (notes read-notes)
(values (part1 notes) (part2 (buses notes))))
(define-test (2020 13) (203 905694340256752))
| null | https://raw.githubusercontent.com/iamFIREcracker/adventofcode/c395df5e15657f0b9be6ec555e68dc777b0eb7ab/src/2020/day13.lisp | lisp | (defpackage :aoc/2020/13 #.cl-user::*aoc-use*)
(in-package :aoc/2020/13)
(defun read-buses (string &aux (offset 0) buses)
(dolist (item (cl-ppcre:split "," string) buses)
(when (string/= item "x")
(push (cons (parse-integer item) offset) buses))
(incf offset)))
(defun id (bus) (car bus))
(defun offset (bus) (cdr bus))
(defun read-notes (data)
(cons (parse-integer (first data)) (read-buses (second data))))
(defun earliest-departure (notes) (car notes))
(defun buses (notes) (cdr notes))
(defun wait-time (earliest-departure bus-period)
(let ((mod (mod earliest-departure bus-period)))
(if (zerop mod) 0 (- bus-period mod))))
(defun part1 (notes)
(multiple-value-call #'*
(find-min
(mapcar #'id (buses notes))
:key (partial-1 #'wait-time (earliest-departure notes)))))
(defun part2 (buses)
(loop with step = 1 and ts = 0
for (id . offset) in buses do
(loop until (zerop (wait-time (+ ts offset) id))
do (incf ts step))
(mulf step id)
finally (return ts)))
(define-solution (2020 13) (notes read-notes)
(values (part1 notes) (part2 (buses notes))))
(define-test (2020 13) (203 905694340256752))
| |
46bc72b8c279cee278c37ddffb130e29619880c06534416c0fef39db98931731 | racket/games | gofish.rkt | #lang racket
(require games/cards racket/gui racket/class racket/unit)
(provide game@)
(define game@ (unit (import) (export)
;; Player record
(define-struct player (r hand-r discard-r count-r ; regions
hand discarded ; cards
tried) #:mutable) ; memory for simulating players
;; Player names
(define PLAYER-1-NAME "Opponent 1")
(define PLAYER-2-NAME "Opponent 2")
(define YOUR-NAME "You")
;; Initial card count
(define DEAL-COUNT 7)
;; Messages
(define YOUR-TURN-MESSAGE
"Your turn. (Drag a match to your discard box or drag a card to an opponent.)")
(define GO-FISH-MESSAGE
"Go Fish! (Drag a card from the center deck to your box.)")
(define MATCH-MESSAGE "Match!")
(define GAME-OVER-MESSAGE "GAME OVER")
;; Region layout constants
(define MARGIN 10)
(define SUBMARGIN 10)
(define LABEL-H 15)
Randomize
(random-seed (modulo (current-milliseconds) 10000))
;; Set up the table
(define t (make-table "Go Fish" 8 4.5))
(define status-pane (send t create-status-pane))
(send t add-scribble-button status-pane
'(lib "games/scribblings/games.scrbl") "gofish")
(send t show #t)
(send t set-double-click-action #f)
(send t set-button-action 'left 'drag-raise/one)
(send t set-button-action 'middle 'drag/one)
(send t set-button-action 'right 'drag/one)
;; Get table width & height
(define w (send t table-width))
(define h (send t table-height))
;; Set up the cards
(define deck (shuffle-list (make-deck) 7))
(for-each (lambda (card)
(send card snap-back-after-move #t)
(send card user-can-flip #f))
deck)
;; Function for dealing or drawing cards
(define (deal n)
(let loop ([n n][d deck])
(if (zero? n)
(begin (set! deck d) null)
(cons (car d) (loop (sub1 n) (cdr d))))))
Card width & height
(define cw (send (car deck) card-width))
(define ch (send (car deck) card-height))
;; Put the cards on the table
(send t add-cards deck (/ (- w cw) 2) (- (/ (- h ch) 2) (/ ch 3)))
;; Player region size
(define pw (- (/ (- w cw) 2) (* 2 MARGIN)))
(define ph (- (/ (- h (/ ch 3)) 2) (* 2 MARGIN)))
;; Region-makers
(define (make-hand-region r)
(define m SUBMARGIN)
(make-region (+ m (region-x r)) (+ LABEL-H m (region-y r))
(- (region-w r) (* 3 m) cw) (- (region-h r) LABEL-H (* 2 m))
#f #f))
(define (make-discard-region r)
(make-region (- (+ (region-x r) (region-w r)) SUBMARGIN cw)
(- (+ (region-y r) (region-h r)) SUBMARGIN ch)
cw ch
#f #f))
(define (make-discard-count-region r c cb)
(make-region
(- (+ (region-x r) (region-w r)) SUBMARGIN cw (/ SUBMARGIN 2))
(- (+ (region-y r) (region-h r)) SUBMARGIN ch LABEL-H (/ SUBMARGIN 2))
(+ cw SUBMARGIN) (+ ch LABEL-H SUBMARGIN)
(number->string c)
cb))
;; Define the initial regions
(define player-1-region
(make-region MARGIN MARGIN pw ph PLAYER-1-NAME void))
(define player-2-region
(make-region (- w MARGIN pw) MARGIN pw ph PLAYER-2-NAME void))
(define you-region
(make-region MARGIN (- h MARGIN ph) (- w (* 2 MARGIN)) ph YOUR-NAME void))
;; Player setup
(define (create-player r discard-callback)
(let ([p (make-player
r
(make-hand-region r)
(make-discard-region r)
(make-discard-count-region r 0 discard-callback)
(deal DEAL-COUNT)
null
null)])
(send t add-region r)
(send t add-region (player-count-r p))
(for-each (lambda (card)
(send t card-to-front card)) (reverse (player-hand p)))
(send t move-cards-to-region (player-hand p) (player-hand-r p))
p))
(define player-1 (create-player player-1-region #f))
(define player-2 (create-player player-2-region #f))
;; Dragging to your discard pile checks to see if
;; the card makes a match:
(define (check-for-match cards)
(check-hand you (car cards))
(send t set-status YOUR-TURN-MESSAGE))
(define you (create-player you-region check-for-match))
;; More card setup: Opponents's cards and deck initially can't be moved
(for-each (lambda (card) (send card user-can-move #f))
(append (player-hand player-1) (player-hand player-2) deck))
;; More card setup: Show your cards
(send t flip-cards (player-hand you))
;; Function to update the display for a player record
(define (rearrange-cards p)
Stack cards in 3D first - to - last
(send t stack-cards (player-discarded p))
(send t stack-cards (player-hand p))
;; Move them to their regions
(send t move-cards-to-region (player-discarded p) (player-discard-r p))
(send t move-cards-to-region (player-hand p) (player-hand-r p))
;; Recreate the counter region to reset the count
(send t begin-card-sequence)
(send t remove-region (player-count-r p))
(set-player-count-r! p (make-discard-count-region
(player-r p) (/ (length (player-discarded p)) 2)
(region-callback (player-count-r p))))
(send t add-region (player-count-r p))
(send t end-card-sequence))
;; Function to search for an equivalent card
(define (find-equiv card hand)
(ormap (lambda (c)
(and (not (eq? c card))
(= (send card get-value) (send c get-value))
c))
hand))
;; Function to check for a match involving `card' already in the player's hand
(define (check-hand player card)
(let* ([h (player-hand player)]
[found (find-equiv card h)])
(if found
(begin
;; Make sure the matching cards are face-up and pause for the user
(send t cards-face-up (list found card))
(send t set-status MATCH-MESSAGE)
;; The players has a match! Move the card from the player's hand
;; to his discard pile
(set-player-hand! player (remove* (list card found) h))
(set-player-discarded! player
(list* found card (player-discarded player)))
;; The dicarded cards can no longer be moved
(send card user-can-move #f)
(send found user-can-move #f)
;; Move the cards to their new places
(rearrange-cards player)
;; Slower
#t)
#f)))
;; Function to enable/disable moving your cards
(define (enable-your-cards on?)
(for-each (lambda (c) (send c user-can-move on?)) (player-hand you))
;; Also disable your discard region, so that a draw can't
;; be dragged directly to the discard:
(set-region-callback! (player-count-r you) (and on? check-for-match)))
;; Callbacks communicate back to the main loop via these
(define something-happened (make-semaphore 1))
(define go-fish? #f)
;; Function for trying to get a card from another player
(define (ask-player-for-match getter giver card)
(let* ([h (player-hand giver)]
[found (find-equiv card h)])
(if found
(begin
;; The giver player has a matching card - give it to the getter
(set-player-hand! giver (remq found h))
(set-player-hand! getter (cons found (player-hand getter)))
;; Make sure the matching cards are face-up and pause for the user
(send t cards-face-up (list found card))
;; Move the cards around
(check-hand getter card)
(rearrange-cards giver)
#t)
;; The giver player doesn't have it - Go Fish!
#f)))
;; Callback for dragging a card to an opponent
(define (player-callback player)
(lambda (cards)
(set! go-fish? (not (ask-player-for-match you player (car cards))))
(semaphore-post something-happened)))
;; Visual info to go fish
(define wiggle-top-card
(lambda ()
(let ([top (car deck)]
[x (/ (- w cw) 2)]
[y (- (/ (- h ch) 2) (/ ch 3))])
(send t move-card top (- x 10) y)
(send t move-card top (+ x 10) y)
(send t move-card top x y))))
;; Callback for going fishing
(define fishing
(lambda (cards)
(send t flip-card (car deck))
(set-player-hand! you (append (deal 1) (player-hand you)))
(rearrange-cards you)
(semaphore-post something-happened)))
;; Function to simulate a player
(define (simulate-player player other-player k)
;; Try cards in the players hand that haven't been tried
(let ([cards-to-try (remq* (player-tried player) (player-hand player))])
(if (null? cards-to-try)
(begin
;; No cards to try. Reset the history and start over
(set-player-tried! player null)
(simulate-player player other-player k))
;; Pick a random card and a random opponent
(let ([c (list-ref cards-to-try (random (length cards-to-try)))]
[o (list-ref (list you other-player) (random 2))])
(set-player-tried! player (cons c (player-tried player)))
;; Show you the card-to-ask
(send t flip-card c)
Hilight player - to - ask
(send t hilite-region (player-r o))
;; Wait a moment
(sleep 0.3)
Unhilight player - to - ask
(send t unhilite-region (player-r o))
(if (ask-player-for-match player o c)
;; Got it - go again
(check-done
(lambda ()
(simulate-player player other-player k)))
;; Go fish
(begin
;; Wait a bit, then turn the asked-for card back over
(sleep 0.3)
(send t flip-card c)
(if (null? deck)
;; No more cards; pass
(k)
(begin
;; Draw a card
(set-player-hand! player (append (deal 1) (player-hand player)))
(rearrange-cards player)
(if (check-hand player (car (player-hand player)))
a good card - keep going
(check-done
(lambda ()
(simulate-player player other-player k)))
;; End of our turn
(k))))))))))
;; Function to check for end-of-game
(define (check-done k)
(if (ormap (lambda (p) (null? (player-hand p))) (list player-1 player-2 you))
(begin (enable-your-cards #f)
(send t set-status GAME-OVER-MESSAGE))
(k)))
Look in opponents ' initial hands for matches ( Since each player gets 7
;; cards, it's impossible to run out of cards this way)
(define (find-initial-matches player)
(when (ormap (lambda (card) (check-hand player card)) (player-hand player))
;; Found a match in the hand
(find-initial-matches player)))
(find-initial-matches player-1)
(find-initial-matches player-2)
;; Run the game loop
(let loop ()
(set-region-callback! (player-r you) #f)
(set-region-callback! (player-r player-1) (player-callback player-1))
(set-region-callback! (player-r player-2) (player-callback player-2))
(send t set-status YOUR-TURN-MESSAGE)
(yield something-happened)
(if go-fish?
(begin
(if (if (null? deck)
;; No more cards; pass
#f
;; Draw a card (wait for the user to drag it)
(begin (send t set-status GO-FISH-MESSAGE)
(wiggle-top-card)
(enable-your-cards #f)
(set-region-callback! (player-r player-1) #f)
(set-region-callback! (player-r player-2) #f)
(set-region-callback! (player-r you) fishing)
(send (car deck) user-can-move #t)
(yield something-happened)
(enable-your-cards #t)
(check-hand you (car (player-hand you)))))
(check-done loop)
(begin (send t set-status PLAYER-1-NAME)
(simulate-player
player-1 player-2
(lambda ()
(send t set-status PLAYER-2-NAME)
(simulate-player player-2 player-1 loop))))))
(check-done loop)))))
| null | https://raw.githubusercontent.com/racket/games/e57376f067be51257ed12cdf3e4509a00ffd533d/gofish/gofish.rkt | racket | Player record
regions
cards
memory for simulating players
Player names
Initial card count
Messages
Region layout constants
Set up the table
Get table width & height
Set up the cards
Function for dealing or drawing cards
Put the cards on the table
Player region size
Region-makers
Define the initial regions
Player setup
Dragging to your discard pile checks to see if
the card makes a match:
More card setup: Opponents's cards and deck initially can't be moved
More card setup: Show your cards
Function to update the display for a player record
Move them to their regions
Recreate the counter region to reset the count
Function to search for an equivalent card
Function to check for a match involving `card' already in the player's hand
Make sure the matching cards are face-up and pause for the user
The players has a match! Move the card from the player's hand
to his discard pile
The dicarded cards can no longer be moved
Move the cards to their new places
Slower
Function to enable/disable moving your cards
Also disable your discard region, so that a draw can't
be dragged directly to the discard:
Callbacks communicate back to the main loop via these
Function for trying to get a card from another player
The giver player has a matching card - give it to the getter
Make sure the matching cards are face-up and pause for the user
Move the cards around
The giver player doesn't have it - Go Fish!
Callback for dragging a card to an opponent
Visual info to go fish
Callback for going fishing
Function to simulate a player
Try cards in the players hand that haven't been tried
No cards to try. Reset the history and start over
Pick a random card and a random opponent
Show you the card-to-ask
Wait a moment
Got it - go again
Go fish
Wait a bit, then turn the asked-for card back over
No more cards; pass
Draw a card
End of our turn
Function to check for end-of-game
cards, it's impossible to run out of cards this way)
Found a match in the hand
Run the game loop
No more cards; pass
Draw a card (wait for the user to drag it) | #lang racket
(require games/cards racket/gui racket/class racket/unit)
(provide game@)
(define game@ (unit (import) (export)
(define PLAYER-1-NAME "Opponent 1")
(define PLAYER-2-NAME "Opponent 2")
(define YOUR-NAME "You")
(define DEAL-COUNT 7)
(define YOUR-TURN-MESSAGE
"Your turn. (Drag a match to your discard box or drag a card to an opponent.)")
(define GO-FISH-MESSAGE
"Go Fish! (Drag a card from the center deck to your box.)")
(define MATCH-MESSAGE "Match!")
(define GAME-OVER-MESSAGE "GAME OVER")
(define MARGIN 10)
(define SUBMARGIN 10)
(define LABEL-H 15)
Randomize
(random-seed (modulo (current-milliseconds) 10000))
(define t (make-table "Go Fish" 8 4.5))
(define status-pane (send t create-status-pane))
(send t add-scribble-button status-pane
'(lib "games/scribblings/games.scrbl") "gofish")
(send t show #t)
(send t set-double-click-action #f)
(send t set-button-action 'left 'drag-raise/one)
(send t set-button-action 'middle 'drag/one)
(send t set-button-action 'right 'drag/one)
(define w (send t table-width))
(define h (send t table-height))
(define deck (shuffle-list (make-deck) 7))
(for-each (lambda (card)
(send card snap-back-after-move #t)
(send card user-can-flip #f))
deck)
(define (deal n)
(let loop ([n n][d deck])
(if (zero? n)
(begin (set! deck d) null)
(cons (car d) (loop (sub1 n) (cdr d))))))
Card width & height
(define cw (send (car deck) card-width))
(define ch (send (car deck) card-height))
(send t add-cards deck (/ (- w cw) 2) (- (/ (- h ch) 2) (/ ch 3)))
(define pw (- (/ (- w cw) 2) (* 2 MARGIN)))
(define ph (- (/ (- h (/ ch 3)) 2) (* 2 MARGIN)))
(define (make-hand-region r)
(define m SUBMARGIN)
(make-region (+ m (region-x r)) (+ LABEL-H m (region-y r))
(- (region-w r) (* 3 m) cw) (- (region-h r) LABEL-H (* 2 m))
#f #f))
(define (make-discard-region r)
(make-region (- (+ (region-x r) (region-w r)) SUBMARGIN cw)
(- (+ (region-y r) (region-h r)) SUBMARGIN ch)
cw ch
#f #f))
(define (make-discard-count-region r c cb)
(make-region
(- (+ (region-x r) (region-w r)) SUBMARGIN cw (/ SUBMARGIN 2))
(- (+ (region-y r) (region-h r)) SUBMARGIN ch LABEL-H (/ SUBMARGIN 2))
(+ cw SUBMARGIN) (+ ch LABEL-H SUBMARGIN)
(number->string c)
cb))
(define player-1-region
(make-region MARGIN MARGIN pw ph PLAYER-1-NAME void))
(define player-2-region
(make-region (- w MARGIN pw) MARGIN pw ph PLAYER-2-NAME void))
(define you-region
(make-region MARGIN (- h MARGIN ph) (- w (* 2 MARGIN)) ph YOUR-NAME void))
(define (create-player r discard-callback)
(let ([p (make-player
r
(make-hand-region r)
(make-discard-region r)
(make-discard-count-region r 0 discard-callback)
(deal DEAL-COUNT)
null
null)])
(send t add-region r)
(send t add-region (player-count-r p))
(for-each (lambda (card)
(send t card-to-front card)) (reverse (player-hand p)))
(send t move-cards-to-region (player-hand p) (player-hand-r p))
p))
(define player-1 (create-player player-1-region #f))
(define player-2 (create-player player-2-region #f))
(define (check-for-match cards)
(check-hand you (car cards))
(send t set-status YOUR-TURN-MESSAGE))
(define you (create-player you-region check-for-match))
(for-each (lambda (card) (send card user-can-move #f))
(append (player-hand player-1) (player-hand player-2) deck))
(send t flip-cards (player-hand you))
(define (rearrange-cards p)
Stack cards in 3D first - to - last
(send t stack-cards (player-discarded p))
(send t stack-cards (player-hand p))
(send t move-cards-to-region (player-discarded p) (player-discard-r p))
(send t move-cards-to-region (player-hand p) (player-hand-r p))
(send t begin-card-sequence)
(send t remove-region (player-count-r p))
(set-player-count-r! p (make-discard-count-region
(player-r p) (/ (length (player-discarded p)) 2)
(region-callback (player-count-r p))))
(send t add-region (player-count-r p))
(send t end-card-sequence))
(define (find-equiv card hand)
(ormap (lambda (c)
(and (not (eq? c card))
(= (send card get-value) (send c get-value))
c))
hand))
(define (check-hand player card)
(let* ([h (player-hand player)]
[found (find-equiv card h)])
(if found
(begin
(send t cards-face-up (list found card))
(send t set-status MATCH-MESSAGE)
(set-player-hand! player (remove* (list card found) h))
(set-player-discarded! player
(list* found card (player-discarded player)))
(send card user-can-move #f)
(send found user-can-move #f)
(rearrange-cards player)
#t)
#f)))
(define (enable-your-cards on?)
(for-each (lambda (c) (send c user-can-move on?)) (player-hand you))
(set-region-callback! (player-count-r you) (and on? check-for-match)))
(define something-happened (make-semaphore 1))
(define go-fish? #f)
(define (ask-player-for-match getter giver card)
(let* ([h (player-hand giver)]
[found (find-equiv card h)])
(if found
(begin
(set-player-hand! giver (remq found h))
(set-player-hand! getter (cons found (player-hand getter)))
(send t cards-face-up (list found card))
(check-hand getter card)
(rearrange-cards giver)
#t)
#f)))
(define (player-callback player)
(lambda (cards)
(set! go-fish? (not (ask-player-for-match you player (car cards))))
(semaphore-post something-happened)))
(define wiggle-top-card
(lambda ()
(let ([top (car deck)]
[x (/ (- w cw) 2)]
[y (- (/ (- h ch) 2) (/ ch 3))])
(send t move-card top (- x 10) y)
(send t move-card top (+ x 10) y)
(send t move-card top x y))))
(define fishing
(lambda (cards)
(send t flip-card (car deck))
(set-player-hand! you (append (deal 1) (player-hand you)))
(rearrange-cards you)
(semaphore-post something-happened)))
(define (simulate-player player other-player k)
(let ([cards-to-try (remq* (player-tried player) (player-hand player))])
(if (null? cards-to-try)
(begin
(set-player-tried! player null)
(simulate-player player other-player k))
(let ([c (list-ref cards-to-try (random (length cards-to-try)))]
[o (list-ref (list you other-player) (random 2))])
(set-player-tried! player (cons c (player-tried player)))
(send t flip-card c)
Hilight player - to - ask
(send t hilite-region (player-r o))
(sleep 0.3)
Unhilight player - to - ask
(send t unhilite-region (player-r o))
(if (ask-player-for-match player o c)
(check-done
(lambda ()
(simulate-player player other-player k)))
(begin
(sleep 0.3)
(send t flip-card c)
(if (null? deck)
(k)
(begin
(set-player-hand! player (append (deal 1) (player-hand player)))
(rearrange-cards player)
(if (check-hand player (car (player-hand player)))
a good card - keep going
(check-done
(lambda ()
(simulate-player player other-player k)))
(k))))))))))
(define (check-done k)
(if (ormap (lambda (p) (null? (player-hand p))) (list player-1 player-2 you))
(begin (enable-your-cards #f)
(send t set-status GAME-OVER-MESSAGE))
(k)))
Look in opponents ' initial hands for matches ( Since each player gets 7
(define (find-initial-matches player)
(when (ormap (lambda (card) (check-hand player card)) (player-hand player))
(find-initial-matches player)))
(find-initial-matches player-1)
(find-initial-matches player-2)
(let loop ()
(set-region-callback! (player-r you) #f)
(set-region-callback! (player-r player-1) (player-callback player-1))
(set-region-callback! (player-r player-2) (player-callback player-2))
(send t set-status YOUR-TURN-MESSAGE)
(yield something-happened)
(if go-fish?
(begin
(if (if (null? deck)
#f
(begin (send t set-status GO-FISH-MESSAGE)
(wiggle-top-card)
(enable-your-cards #f)
(set-region-callback! (player-r player-1) #f)
(set-region-callback! (player-r player-2) #f)
(set-region-callback! (player-r you) fishing)
(send (car deck) user-can-move #t)
(yield something-happened)
(enable-your-cards #t)
(check-hand you (car (player-hand you)))))
(check-done loop)
(begin (send t set-status PLAYER-1-NAME)
(simulate-player
player-1 player-2
(lambda ()
(send t set-status PLAYER-2-NAME)
(simulate-player player-2 player-1 loop))))))
(check-done loop)))))
|
7d0983a0e12553f66aabb0811cf1aefbda0e8645bccaa09a3f0fab6112609443 | markus-git/co-feldspar | Backend.hs | # language GADTs #
# language QuasiQuotes #
{-# language ScopedTypeVariables #-}
{-# language FlexibleContexts #-}
module Feldspar.Software.Primitive.Backend where
import Feldspar.Software.Primitive
import Data.Complex (Complex (..))
import Data.Constraint (Dict (..))
import Data.Proxy
-- syntactic.
import Language.Syntactic
-- language-c-quote.
import Language.C.Quote.C
import qualified Language.C.Syntax as C
--imperative-edsl.
import Language.C.Monad
import Language.Embedded.Backend.C
--------------------------------------------------------------------------------
-- * Compilation of software primitives.
--------------------------------------------------------------------------------
viewLitPrim :: ASTF SoftwarePrimDomain a -> Maybe a
viewLitPrim (Sym (Lit a :&: _)) = Just a
viewLitPrim _ = Nothing
--------------------------------------------------------------------------------
instance CompTypeClass SoftwarePrimType
where
compType _ (_ :: proxy a) = case softwareRep :: SoftwarePrimTypeRep a of
BoolST -> addInclude "<stdbool.h>" >> return [cty| typename bool |]
Int8ST -> addInclude "<stdint.h>" >> return [cty| typename int8_t |]
Int16ST -> addInclude "<stdint.h>" >> return [cty| typename int16_t |]
Int32ST -> addInclude "<stdint.h>" >> return [cty| typename int32_t |]
Int64ST -> addInclude "<stdint.h>" >> return [cty| typename int64_t |]
Word8ST -> addInclude "<stdint.h>" >> return [cty| typename uint8_t |]
Word16ST -> addInclude "<stdint.h>" >> return [cty| typename uint16_t |]
Word32ST -> addInclude "<stdint.h>" >> return [cty| typename uint32_t |]
Word64ST -> addInclude "<stdint.h>" >> return [cty| typename uint64_t |]
FloatST -> return [cty| float |]
DoubleST -> return [cty| double |]
ComplexFloatST ->
addInclude "<tgmath.h>" >> return [cty| float _Complex |]
ComplexDoubleST ->
addInclude "<tgmath.h>" >> return [cty| double _Complex |]
compLit _ a = case softwarePrimTypeOf a of
BoolST ->
do addInclude "<stdbool.h>"
return $ if a then [cexp| true |] else [cexp| false |]
Int8ST -> return [cexp| $a |]
Int16ST -> return [cexp| $a |]
Int32ST -> return [cexp| $a |]
Int64ST -> return [cexp| $a |]
Word8ST -> return [cexp| $a |]
Word16ST -> return [cexp| $a |]
Word32ST -> return [cexp| $a |]
Word64ST -> return [cexp| $a |]
FloatST -> return [cexp| $a |]
DoubleST -> return [cexp| $a |]
ComplexFloatST -> return $ compComplexLit a
ComplexDoubleST -> return $ compComplexLit a
instance CompExp Prim
where
compExp = compPrim
--------------------------------------------------------------------------------
compUnOp
:: MonadC m
=> C.UnOp
-> ASTF SoftwarePrimDomain a
-> m C.Exp
compUnOp op a = do
a' <- compPrim $ Prim a
return $ C.UnOp op a' mempty
compBinOp
:: MonadC m
=> C.BinOp
-> ASTF SoftwarePrimDomain a
-> ASTF SoftwarePrimDomain b
-> m C.Exp
compBinOp op a b = do
a' <- compPrim $ Prim a
b' <- compPrim $ Prim b
return $ C.BinOp op a' b' mempty
compCast
:: MonadC m
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain b
-> m C.Exp
compCast t a = do
p <- compPrim $ Prim a
compCastExp t p
compCastExp
:: MonadC m
=> SoftwarePrimTypeRep a
-> C.Exp
-> m C.Exp
compCastExp t p = case softwarePrimWitType t of
Dict -> do
typ <- compType (Proxy :: Proxy SoftwarePrimType) t
return [cexp|($ty:typ) $p|]
compFun
:: MonadC m
=> String
-> Args (AST SoftwarePrimDomain) sig
-> m C.Exp
compFun fun args = do
as <- sequence $ listArgs (compPrim . Prim) args
return [cexp| $id:fun($args:as) |]
compRotateL_def = [cedecl|
unsigned int feld_rotl(const unsigned int value, int shift) {
if ((shift &= sizeof(value)*8 - 1) == 0)
return value;
return (value << shift) | (value >> (sizeof(value)*8 - shift));
} |]
compRotateR_def = [cedecl|
unsigned int feld_rotr(const unsigned int value, int shift) {
if ((shift &= sizeof(value)*8 - 1) == 0)
return value;
return (value >> shift) | (value << (sizeof(value)*8 - shift));
} |]
compComplexLit :: (Eq a, Num a, ToExp a) => Complex a -> C.Exp
compComplexLit (r :+ 0) = [cexp| $r |]
compComplexLit (0 :+ i) = [cexp| $i * I |]
compComplexLit (r :+ i) = [cexp| $r + $i * I |]
compAbs
:: MonadC m
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain a
-> m C.Exp
compAbs t a
| boolType t = error "compAbs: type BoolT not supported"
| integerType t = addInclude "<stdlib.h>" >> compFun "abs" (a :* Nil)
| wordType t = compPrim $ Prim a
| otherwise = addInclude "<tgmath.h>" >> compFun "fabs" (a :* Nil)
compSign
:: MonadC m
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain a
-> m C.Exp
compSign t a | boolType t = do
error "compSign: type BoolST not supported"
compSign t a | integerType t = do
addTagMacro
a' <- compPrim $ Prim a
return [cexp| TAG("signum", ($a' > 0) - ($a' < 0)) |]
compSign t a | wordType t = do
addTagMacro
a' <- compPrim $ Prim a
return [cexp| TAG("signum", $a' > 0) |]
compSign FloatST a = do
addTagMacro
a' <- compPrim $ Prim a
return [cexp| TAG("signum", (float) (($a' > 0) - ($a' < 0))) |]
compSign DoubleST a = do
addTagMacro
a' <- compPrim $ Prim a
return [cexp| TAG("signum", (double) (($a' > 0) - ($a' < 0))) |]
compSign ComplexFloatST a = do
addInclude "<complex.h>"
addGlobal complexSignf_def
a' <- compPrim $ Prim a
return [cexp| feld_complexSignf($a') |]
compSign ComplexDoubleST a = do
addInclude "<tgmath.h>"
addGlobal complexSign_def
a' <- compPrim $ Prim a
return [cexp| feld_complexSign($a') |]
todo : The floating point cases give ` sign ( -0.0 ) = 0.0 ` , which is ( slightly )
-- wrong. They should return -0.0. I don't know whether it's correct for other
-- strange values.
complexSignf_def = [cedecl|
float _Complex feld_complexSignf(float _Complex c) {
float z = cabsf(c);
if (z == 0)
return 0;
else
return (crealf(c)/z + I*(cimagf(c)/z));
} |]
complexSign_def = [cedecl|
double _Complex feld_complexSign(double _Complex c) {
double z = cabs(c);
if (z == 0)
return 0;
else
return (creal(c)/z + I*(cimag(c)/z));
} |]
compDiv
:: MonadC m
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain a
-> ASTF SoftwarePrimDomain b
-> m C.Exp
compDiv Int64ST a b = do
addGlobal ldiv_def
compFun "feld_ldiv" (a :* b :* Nil)
compDiv t a b | integerType t = do
addGlobal div_def
compFun "feld_div" (a :* b :* Nil)
compDiv t a b | wordType t = compBinOp C.Div a b
compDiv t a b = error $ "compDiv: type " ++ show t ++ " not supported"
ldiv_def = [cedecl|
long int feld_ldiv(long int x, long int y) {
int q = x/y;
int r = x%y;
if ((r!=0) && ((r<0) != (y<0))) --q;
return q;
} |]
div_def = [cedecl|
int feld_div(int x, int y) {
int q = x/y;
int r = x%y;
if ((r!=0) && ((r<0) != (y<0))) --q;
return q;
} |]
compMod
:: MonadC m
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain a
-> ASTF SoftwarePrimDomain b
-> m C.Exp
compMod Int64ST a b = do
addGlobal lmod_def
compFun "feld_lmod" (a :* b :* Nil)
compMod t a b | integerType t = do
addGlobal div_def
compFun "feld_mod" (a :* b :* Nil)
compMod t a b | wordType t = compBinOp C.Mod a b
compMod t a b = error $ "compMod: type " ++ show t ++ " not supported"
lmod_def = [cedecl|
long int feld_lmod(long int x, long int y) {
int r = x%y;
if ((r!=0) && ((r<0) != (y<0))) { r += y; }
return r;
} |]
mod_def = [cedecl|
int feld_mod(int x, int y) {
int r = x%y;
if ((r!=0) && ((r<0) != (y<0))) { r += y; }
return r;
} |]
compRound :: (SoftwarePrimType a, Num a, RealFrac b, MonadC m)
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain b
-> m C.Exp
compRound t a | integerType t || wordType t = do
addInclude "<tgmath.h>"
p <- compFun "lround" (a :* Nil)
compCastExp t p
compRound t a | floatingType t || complexType t = do
addInclude "<tgmath.h>"
p <- compFun "round" (a :* Nil)
compCastExp t p
compRound t a = do
error $ "compSign: type " ++ show t ++ " not supported"
--------------------------------------------------------------------------------
compPrim :: MonadC m => Prim a -> m C.Exp
compPrim = simpleMatch (\(s :&: t) -> go t s) . unPrim
where
go :: forall m sig
. MonadC m
=> SoftwarePrimTypeRep (DenResult sig)
-> SoftwarePrimConstructs sig
-> Args (AST SoftwarePrimDomain) sig
-> m C.Exp
go _ (FreeVar v) Nil = touchVar v >> return [cexp| $id:v |]
go t (Lit a) Nil | Dict <- softwarePrimWitType t
= compLit (Proxy :: Proxy SoftwarePrimType) a
go _ Neg (a :* Nil) = compUnOp C.Negate a
go _ Add (a :* b :* Nil) = compBinOp C.Add a b
go _ Sub (a :* b :* Nil) = compBinOp C.Sub a b
go _ Mul (a :* b :* Nil) = compBinOp C.Mul a b
go t Div (a :* b :* Nil) = compDiv t a b
go _ Quot (a :* b :* Nil) = compBinOp C.Div a b
go _ Rem (a :* b :* Nil) = compBinOp C.Mod a b
go t Mod (a :* b :* Nil) = compMod t a b
go t Abs (a :* Nil) = compAbs t a
go t Sign (a :* Nil) = compSign t a
go _ FDiv (a :* b :* Nil) = compBinOp C.Div a b
go _ Exp args = addInclude "<tgmath.h>" >> compFun "exp" args
go _ Log args = addInclude "<tgmath.h>" >> compFun "log" args
go _ Sqrt args = addInclude "<tgmath.h>" >> compFun "sqrt" args
go _ Pow args = addInclude "<tgmath.h>" >> compFun "pow" args
go _ Sin args = addInclude "<tgmath.h>" >> compFun "sin" args
go _ Cos args = addInclude "<tgmath.h>" >> compFun "cos" args
go _ Tan args = addInclude "<tgmath.h>" >> compFun "tan" args
go _ Asin args = addInclude "<tgmath.h>" >> compFun "asin" args
go _ Acos args = addInclude "<tgmath.h>" >> compFun "acos" args
go _ Atan args = addInclude "<tgmath.h>" >> compFun "atan" args
go _ Sinh args = addInclude "<tgmath.h>" >> compFun "sinh" args
go _ Cosh args = addInclude "<tgmath.h>" >> compFun "cosh" args
go _ Tanh args = addInclude "<tgmath.h>" >> compFun "tanh" args
go _ Asinh args = addInclude "<tgmath.h>" >> compFun "asinh" args
go _ Acosh args = addInclude "<tgmath.h>" >> compFun "acosh" args
go _ Atanh args = addInclude "<tgmath.h>" >> compFun "atanh" args
go t I2N (a :* Nil) = compCast t a
go t I2B (a :* Nil) = compCast t a
go t B2I (a :* Nil) = compCast t a
go t Round (a :* Nil) = compRound t a
go _ Complex (a :* b :* Nil) = do
addInclude "<tgmath.h>"
a' <- compPrim $ Prim a
b' <- compPrim $ Prim b
return $ case (viewLitPrim a, viewLitPrim b) of
(Just 0, _) -> [cexp| I*$b' |]
(_, Just 0) -> [cexp| $a' |]
_ -> [cexp| $a' + I*$b' |]
go _ Polar (m :* p :* Nil)
| Just 0 <- viewLitPrim m = do
return [cexp| 0 |]
| Just 0 <- viewLitPrim p = do
m' <- compPrim $ Prim m
return [cexp| $m' |]
| Just 1 <- viewLitPrim m = do
p' <- compPrim $ Prim p
return [cexp| exp(I*$p') |]
| otherwise = do
m' <- compPrim $ Prim m
p' <- compPrim $ Prim p
return [cexp| $m' * exp(I*$p') |]
go _ Real args = addInclude "<tgmath.h>" >> compFun "creal" args
go _ Imag args = addInclude "<tgmath.h>" >> compFun "cimag" args
go _ Magnitude args = addInclude "<tgmath.h>" >> compFun "cabs" args
go _ Phase args = addInclude "<tgmath.h>" >> compFun "carg" args
go _ Conjugate args = addInclude "<tgmath.h>" >> compFun "conj" args
go _ Not (a :* Nil) = compUnOp C.Lnot a
go _ And (a :* b :* Nil) = compBinOp C.Land a b
go _ Or (a :* b :* Nil) = compBinOp C.Lor a b
go _ Eq (a :* b :* Nil) = compBinOp C.Eq a b
go _ Neq (a :* b :* Nil) = compBinOp C.Ne a b
go _ Lt (a :* b :* Nil) = compBinOp C.Lt a b
go _ Lte (a :* b :* Nil) = compBinOp C.Le a b
go _ Gt (a :* b :* Nil) = compBinOp C.Gt a b
go _ Gte (a :* b :* Nil) = compBinOp C.Ge a b
go _ Pi Nil = addGlobal pi_def >> return [cexp| FELD_PI |]
where pi_def = [cedecl|$esc:("#define FELD_PI 3.141592653589793")|]
go _ BitAnd (a :* b :* Nil) = compBinOp C.And a b
go _ BitOr (a :* b :* Nil) = compBinOp C.Or a b
go _ BitXor (a :* b :* Nil) = compBinOp C.Xor a b
go _ BitCompl (a :* Nil) = compUnOp C.Not a
go _ ShiftL (a :* b :* Nil) = compBinOp C.Lsh a b
go _ ShiftR (a :* b :* Nil) = compBinOp C.Rsh a b
go _ RotateL (a :* b :* Nil) = do
addGlobal compRotateL_def
a' <- compPrim $ Prim a
b' <- compPrim $ Prim b
return [cexp| feld_rotl($a', $b') |]
go _ RotateR (a :* b :* Nil) = do
addGlobal compRotateR_def
a' <- compPrim $ Prim a
b' <- compPrim $ Prim b
return [cexp| feld_rotr($a', $b') |]
go _ (ArrIx arr) (i :* Nil) = do
i' <- compPrim $ Prim i
touchVar arr
return [cexp| $id:arr[$i'] |]
go _ Cond (c :* t :* f :* Nil) = do
c' <- compPrim $ Prim c
t' <- compPrim $ Prim t
f' <- compPrim $ Prim f
return $ C.Cond c' t' f' mempty
--------------------------------------------------------------------------------
addTagMacro :: MonadC m => m ()
addTagMacro = addGlobal [cedecl| $esc:("#define TAG(tag,exp) (exp)") |]
boolType :: SoftwarePrimTypeRep a -> Bool
boolType BoolST = True
boolType _ = False
integerType :: SoftwarePrimTypeRep a -> Bool
integerType Int8ST = True
integerType Int16ST = True
integerType Int32ST = True
integerType Int64ST = True
integerType _ = False
wordType :: SoftwarePrimTypeRep a -> Bool
wordType Word8ST = True
wordType Word16ST = True
wordType Word32ST = True
wordType Word64ST = True
wordType _ = False
floatingType :: SoftwarePrimTypeRep a -> Bool
floatingType FloatST = True
floatingType DoubleST = True
floatingType _ = False
complexType :: SoftwarePrimTypeRep a -> Bool
complexType ComplexFloatST = True
complexType ComplexDoubleST = True
complexType _ = False
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/markus-git/co-feldspar/bf598c803d41e03ed894bbcb490da855cce9250e/src/Feldspar/Software/Primitive/Backend.hs | haskell | # language ScopedTypeVariables #
# language FlexibleContexts #
syntactic.
language-c-quote.
imperative-edsl.
------------------------------------------------------------------------------
* Compilation of software primitives.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
wrong. They should return -0.0. I don't know whether it's correct for other
strange values.
q;
q;
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | # language GADTs #
# language QuasiQuotes #
module Feldspar.Software.Primitive.Backend where
import Feldspar.Software.Primitive
import Data.Complex (Complex (..))
import Data.Constraint (Dict (..))
import Data.Proxy
import Language.Syntactic
import Language.C.Quote.C
import qualified Language.C.Syntax as C
import Language.C.Monad
import Language.Embedded.Backend.C
viewLitPrim :: ASTF SoftwarePrimDomain a -> Maybe a
viewLitPrim (Sym (Lit a :&: _)) = Just a
viewLitPrim _ = Nothing
instance CompTypeClass SoftwarePrimType
where
compType _ (_ :: proxy a) = case softwareRep :: SoftwarePrimTypeRep a of
BoolST -> addInclude "<stdbool.h>" >> return [cty| typename bool |]
Int8ST -> addInclude "<stdint.h>" >> return [cty| typename int8_t |]
Int16ST -> addInclude "<stdint.h>" >> return [cty| typename int16_t |]
Int32ST -> addInclude "<stdint.h>" >> return [cty| typename int32_t |]
Int64ST -> addInclude "<stdint.h>" >> return [cty| typename int64_t |]
Word8ST -> addInclude "<stdint.h>" >> return [cty| typename uint8_t |]
Word16ST -> addInclude "<stdint.h>" >> return [cty| typename uint16_t |]
Word32ST -> addInclude "<stdint.h>" >> return [cty| typename uint32_t |]
Word64ST -> addInclude "<stdint.h>" >> return [cty| typename uint64_t |]
FloatST -> return [cty| float |]
DoubleST -> return [cty| double |]
ComplexFloatST ->
addInclude "<tgmath.h>" >> return [cty| float _Complex |]
ComplexDoubleST ->
addInclude "<tgmath.h>" >> return [cty| double _Complex |]
compLit _ a = case softwarePrimTypeOf a of
BoolST ->
do addInclude "<stdbool.h>"
return $ if a then [cexp| true |] else [cexp| false |]
Int8ST -> return [cexp| $a |]
Int16ST -> return [cexp| $a |]
Int32ST -> return [cexp| $a |]
Int64ST -> return [cexp| $a |]
Word8ST -> return [cexp| $a |]
Word16ST -> return [cexp| $a |]
Word32ST -> return [cexp| $a |]
Word64ST -> return [cexp| $a |]
FloatST -> return [cexp| $a |]
DoubleST -> return [cexp| $a |]
ComplexFloatST -> return $ compComplexLit a
ComplexDoubleST -> return $ compComplexLit a
instance CompExp Prim
where
compExp = compPrim
compUnOp
:: MonadC m
=> C.UnOp
-> ASTF SoftwarePrimDomain a
-> m C.Exp
compUnOp op a = do
a' <- compPrim $ Prim a
return $ C.UnOp op a' mempty
compBinOp
:: MonadC m
=> C.BinOp
-> ASTF SoftwarePrimDomain a
-> ASTF SoftwarePrimDomain b
-> m C.Exp
compBinOp op a b = do
a' <- compPrim $ Prim a
b' <- compPrim $ Prim b
return $ C.BinOp op a' b' mempty
compCast
:: MonadC m
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain b
-> m C.Exp
compCast t a = do
p <- compPrim $ Prim a
compCastExp t p
compCastExp
:: MonadC m
=> SoftwarePrimTypeRep a
-> C.Exp
-> m C.Exp
compCastExp t p = case softwarePrimWitType t of
Dict -> do
typ <- compType (Proxy :: Proxy SoftwarePrimType) t
return [cexp|($ty:typ) $p|]
compFun
:: MonadC m
=> String
-> Args (AST SoftwarePrimDomain) sig
-> m C.Exp
compFun fun args = do
as <- sequence $ listArgs (compPrim . Prim) args
return [cexp| $id:fun($args:as) |]
compRotateL_def = [cedecl|
unsigned int feld_rotl(const unsigned int value, int shift) {
if ((shift &= sizeof(value)*8 - 1) == 0)
return value;
return (value << shift) | (value >> (sizeof(value)*8 - shift));
} |]
compRotateR_def = [cedecl|
unsigned int feld_rotr(const unsigned int value, int shift) {
if ((shift &= sizeof(value)*8 - 1) == 0)
return value;
return (value >> shift) | (value << (sizeof(value)*8 - shift));
} |]
compComplexLit :: (Eq a, Num a, ToExp a) => Complex a -> C.Exp
compComplexLit (r :+ 0) = [cexp| $r |]
compComplexLit (0 :+ i) = [cexp| $i * I |]
compComplexLit (r :+ i) = [cexp| $r + $i * I |]
compAbs
:: MonadC m
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain a
-> m C.Exp
compAbs t a
| boolType t = error "compAbs: type BoolT not supported"
| integerType t = addInclude "<stdlib.h>" >> compFun "abs" (a :* Nil)
| wordType t = compPrim $ Prim a
| otherwise = addInclude "<tgmath.h>" >> compFun "fabs" (a :* Nil)
compSign
:: MonadC m
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain a
-> m C.Exp
compSign t a | boolType t = do
error "compSign: type BoolST not supported"
compSign t a | integerType t = do
addTagMacro
a' <- compPrim $ Prim a
return [cexp| TAG("signum", ($a' > 0) - ($a' < 0)) |]
compSign t a | wordType t = do
addTagMacro
a' <- compPrim $ Prim a
return [cexp| TAG("signum", $a' > 0) |]
compSign FloatST a = do
addTagMacro
a' <- compPrim $ Prim a
return [cexp| TAG("signum", (float) (($a' > 0) - ($a' < 0))) |]
compSign DoubleST a = do
addTagMacro
a' <- compPrim $ Prim a
return [cexp| TAG("signum", (double) (($a' > 0) - ($a' < 0))) |]
compSign ComplexFloatST a = do
addInclude "<complex.h>"
addGlobal complexSignf_def
a' <- compPrim $ Prim a
return [cexp| feld_complexSignf($a') |]
compSign ComplexDoubleST a = do
addInclude "<tgmath.h>"
addGlobal complexSign_def
a' <- compPrim $ Prim a
return [cexp| feld_complexSign($a') |]
todo : The floating point cases give ` sign ( -0.0 ) = 0.0 ` , which is ( slightly )
complexSignf_def = [cedecl|
float _Complex feld_complexSignf(float _Complex c) {
float z = cabsf(c);
if (z == 0)
return 0;
else
return (crealf(c)/z + I*(cimagf(c)/z));
} |]
complexSign_def = [cedecl|
double _Complex feld_complexSign(double _Complex c) {
double z = cabs(c);
if (z == 0)
return 0;
else
return (creal(c)/z + I*(cimag(c)/z));
} |]
compDiv
:: MonadC m
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain a
-> ASTF SoftwarePrimDomain b
-> m C.Exp
compDiv Int64ST a b = do
addGlobal ldiv_def
compFun "feld_ldiv" (a :* b :* Nil)
compDiv t a b | integerType t = do
addGlobal div_def
compFun "feld_div" (a :* b :* Nil)
compDiv t a b | wordType t = compBinOp C.Div a b
compDiv t a b = error $ "compDiv: type " ++ show t ++ " not supported"
ldiv_def = [cedecl|
long int feld_ldiv(long int x, long int y) {
int q = x/y;
int r = x%y;
return q;
} |]
div_def = [cedecl|
int feld_div(int x, int y) {
int q = x/y;
int r = x%y;
return q;
} |]
compMod
:: MonadC m
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain a
-> ASTF SoftwarePrimDomain b
-> m C.Exp
compMod Int64ST a b = do
addGlobal lmod_def
compFun "feld_lmod" (a :* b :* Nil)
compMod t a b | integerType t = do
addGlobal div_def
compFun "feld_mod" (a :* b :* Nil)
compMod t a b | wordType t = compBinOp C.Mod a b
compMod t a b = error $ "compMod: type " ++ show t ++ " not supported"
lmod_def = [cedecl|
long int feld_lmod(long int x, long int y) {
int r = x%y;
if ((r!=0) && ((r<0) != (y<0))) { r += y; }
return r;
} |]
mod_def = [cedecl|
int feld_mod(int x, int y) {
int r = x%y;
if ((r!=0) && ((r<0) != (y<0))) { r += y; }
return r;
} |]
compRound :: (SoftwarePrimType a, Num a, RealFrac b, MonadC m)
=> SoftwarePrimTypeRep a
-> ASTF SoftwarePrimDomain b
-> m C.Exp
compRound t a | integerType t || wordType t = do
addInclude "<tgmath.h>"
p <- compFun "lround" (a :* Nil)
compCastExp t p
compRound t a | floatingType t || complexType t = do
addInclude "<tgmath.h>"
p <- compFun "round" (a :* Nil)
compCastExp t p
compRound t a = do
error $ "compSign: type " ++ show t ++ " not supported"
compPrim :: MonadC m => Prim a -> m C.Exp
compPrim = simpleMatch (\(s :&: t) -> go t s) . unPrim
where
go :: forall m sig
. MonadC m
=> SoftwarePrimTypeRep (DenResult sig)
-> SoftwarePrimConstructs sig
-> Args (AST SoftwarePrimDomain) sig
-> m C.Exp
go _ (FreeVar v) Nil = touchVar v >> return [cexp| $id:v |]
go t (Lit a) Nil | Dict <- softwarePrimWitType t
= compLit (Proxy :: Proxy SoftwarePrimType) a
go _ Neg (a :* Nil) = compUnOp C.Negate a
go _ Add (a :* b :* Nil) = compBinOp C.Add a b
go _ Sub (a :* b :* Nil) = compBinOp C.Sub a b
go _ Mul (a :* b :* Nil) = compBinOp C.Mul a b
go t Div (a :* b :* Nil) = compDiv t a b
go _ Quot (a :* b :* Nil) = compBinOp C.Div a b
go _ Rem (a :* b :* Nil) = compBinOp C.Mod a b
go t Mod (a :* b :* Nil) = compMod t a b
go t Abs (a :* Nil) = compAbs t a
go t Sign (a :* Nil) = compSign t a
go _ FDiv (a :* b :* Nil) = compBinOp C.Div a b
go _ Exp args = addInclude "<tgmath.h>" >> compFun "exp" args
go _ Log args = addInclude "<tgmath.h>" >> compFun "log" args
go _ Sqrt args = addInclude "<tgmath.h>" >> compFun "sqrt" args
go _ Pow args = addInclude "<tgmath.h>" >> compFun "pow" args
go _ Sin args = addInclude "<tgmath.h>" >> compFun "sin" args
go _ Cos args = addInclude "<tgmath.h>" >> compFun "cos" args
go _ Tan args = addInclude "<tgmath.h>" >> compFun "tan" args
go _ Asin args = addInclude "<tgmath.h>" >> compFun "asin" args
go _ Acos args = addInclude "<tgmath.h>" >> compFun "acos" args
go _ Atan args = addInclude "<tgmath.h>" >> compFun "atan" args
go _ Sinh args = addInclude "<tgmath.h>" >> compFun "sinh" args
go _ Cosh args = addInclude "<tgmath.h>" >> compFun "cosh" args
go _ Tanh args = addInclude "<tgmath.h>" >> compFun "tanh" args
go _ Asinh args = addInclude "<tgmath.h>" >> compFun "asinh" args
go _ Acosh args = addInclude "<tgmath.h>" >> compFun "acosh" args
go _ Atanh args = addInclude "<tgmath.h>" >> compFun "atanh" args
go t I2N (a :* Nil) = compCast t a
go t I2B (a :* Nil) = compCast t a
go t B2I (a :* Nil) = compCast t a
go t Round (a :* Nil) = compRound t a
go _ Complex (a :* b :* Nil) = do
addInclude "<tgmath.h>"
a' <- compPrim $ Prim a
b' <- compPrim $ Prim b
return $ case (viewLitPrim a, viewLitPrim b) of
(Just 0, _) -> [cexp| I*$b' |]
(_, Just 0) -> [cexp| $a' |]
_ -> [cexp| $a' + I*$b' |]
go _ Polar (m :* p :* Nil)
| Just 0 <- viewLitPrim m = do
return [cexp| 0 |]
| Just 0 <- viewLitPrim p = do
m' <- compPrim $ Prim m
return [cexp| $m' |]
| Just 1 <- viewLitPrim m = do
p' <- compPrim $ Prim p
return [cexp| exp(I*$p') |]
| otherwise = do
m' <- compPrim $ Prim m
p' <- compPrim $ Prim p
return [cexp| $m' * exp(I*$p') |]
go _ Real args = addInclude "<tgmath.h>" >> compFun "creal" args
go _ Imag args = addInclude "<tgmath.h>" >> compFun "cimag" args
go _ Magnitude args = addInclude "<tgmath.h>" >> compFun "cabs" args
go _ Phase args = addInclude "<tgmath.h>" >> compFun "carg" args
go _ Conjugate args = addInclude "<tgmath.h>" >> compFun "conj" args
go _ Not (a :* Nil) = compUnOp C.Lnot a
go _ And (a :* b :* Nil) = compBinOp C.Land a b
go _ Or (a :* b :* Nil) = compBinOp C.Lor a b
go _ Eq (a :* b :* Nil) = compBinOp C.Eq a b
go _ Neq (a :* b :* Nil) = compBinOp C.Ne a b
go _ Lt (a :* b :* Nil) = compBinOp C.Lt a b
go _ Lte (a :* b :* Nil) = compBinOp C.Le a b
go _ Gt (a :* b :* Nil) = compBinOp C.Gt a b
go _ Gte (a :* b :* Nil) = compBinOp C.Ge a b
go _ Pi Nil = addGlobal pi_def >> return [cexp| FELD_PI |]
where pi_def = [cedecl|$esc:("#define FELD_PI 3.141592653589793")|]
go _ BitAnd (a :* b :* Nil) = compBinOp C.And a b
go _ BitOr (a :* b :* Nil) = compBinOp C.Or a b
go _ BitXor (a :* b :* Nil) = compBinOp C.Xor a b
go _ BitCompl (a :* Nil) = compUnOp C.Not a
go _ ShiftL (a :* b :* Nil) = compBinOp C.Lsh a b
go _ ShiftR (a :* b :* Nil) = compBinOp C.Rsh a b
go _ RotateL (a :* b :* Nil) = do
addGlobal compRotateL_def
a' <- compPrim $ Prim a
b' <- compPrim $ Prim b
return [cexp| feld_rotl($a', $b') |]
go _ RotateR (a :* b :* Nil) = do
addGlobal compRotateR_def
a' <- compPrim $ Prim a
b' <- compPrim $ Prim b
return [cexp| feld_rotr($a', $b') |]
go _ (ArrIx arr) (i :* Nil) = do
i' <- compPrim $ Prim i
touchVar arr
return [cexp| $id:arr[$i'] |]
go _ Cond (c :* t :* f :* Nil) = do
c' <- compPrim $ Prim c
t' <- compPrim $ Prim t
f' <- compPrim $ Prim f
return $ C.Cond c' t' f' mempty
addTagMacro :: MonadC m => m ()
addTagMacro = addGlobal [cedecl| $esc:("#define TAG(tag,exp) (exp)") |]
boolType :: SoftwarePrimTypeRep a -> Bool
boolType BoolST = True
boolType _ = False
integerType :: SoftwarePrimTypeRep a -> Bool
integerType Int8ST = True
integerType Int16ST = True
integerType Int32ST = True
integerType Int64ST = True
integerType _ = False
wordType :: SoftwarePrimTypeRep a -> Bool
wordType Word8ST = True
wordType Word16ST = True
wordType Word32ST = True
wordType Word64ST = True
wordType _ = False
floatingType :: SoftwarePrimTypeRep a -> Bool
floatingType FloatST = True
floatingType DoubleST = True
floatingType _ = False
complexType :: SoftwarePrimTypeRep a -> Bool
complexType ComplexFloatST = True
complexType ComplexDoubleST = True
complexType _ = False
|
4d7877a5c944a67d82fa87a49b9f58bdbc89cfc655605ff44fa1df13a67322fe | takikawa/tr-pfds | physicists.rkt | #lang typed/racket
(provide filter remove Queue head+tail build-queue
empty empty? enqueue head tail queue->list queue list->queue
(rename-out [qmap map]
[queue-andmap andmap]
[queue-ormap ormap]) fold)
(define-type (Promiseof A) (Boxof (U (→ (Listof A)) (Listof A))))
;; Physicists Queue
;; Maintains invariant lenr <= lenf
;; pref is empty only if lenf = 0
(struct: (A) Queue ([preF : (Listof A)]
[front : (Promiseof A)]
[lenf : Integer]
[rear : (Listof A)]
[lenr : Integer]))
;; Empty Queue Because of some limitations in TR in typechecking the
;; boxed values, I had to make empty a macro so that users can
;; instantiate empty easily.
(define-syntax-rule (empty A)
((inst Queue A) '() (box (lambda: () '())) 0 '() 0))
;; Checks if the given Queue is empty
(: empty? : (All (A) ((Queue A) -> Boolean)))
(define (empty? que)
(zero? (Queue-lenf que)))
(define-syntax-rule (force promise)
(let ([p (unbox promise)])
(if (procedure? p)
(let ([result (p)])
(set-box! (ann promise (Promiseof A)) result)
result)
p)))
;; Maintains "preF" invariant (preF in not not null when front is not null)
;(: check-pref-inv :
( All ( A ) ( ( A ) ( Promiseof A ) Integer ( A ) Integer - >
; (Queue A))))
(define-syntax-rule (check-pref-inv pref front lenf rear lenr)
(if (null? pref)
((inst Queue A) (force front) front lenf rear lenr)
((inst Queue A) pref front lenf rear lenr)))
;; Maintains lenr <= lenf invariant
(: check :
( All ( A ) ( ( A ) ( Promiseof A ) Integer ( A ) Integer - > ( Queue A ) ) ) )
(define-syntax-rule (check-len-inv pref front lenf rear lenr)
(if (>= lenf lenr)
(check-pref-inv pref front lenf rear lenr)
(let*: ([newpref : (Listof A) (force front)]
[newf : (Promiseof A)
(box (lambda () (append newpref (reverse rear))))])
(check-pref-inv newpref newf (+ lenf lenr) null 0))))
;; Maintains queue invariants
;(: internal-queue :
( All ( A ) ( ( A ) ( Promiseof A ) Integer ( A ) Integer - > ( Queue A ) ) ) )
(define-syntax-rule (internal-queue pref front lenf rear lenr)
(check-len-inv pref front lenf rear lenr))
an item into the list
(: enqueue : (All (A) (A (Queue A) -> (Queue A))))
(define (enqueue item que)
(internal-queue (Queue-preF que)
(Queue-front que)
(Queue-lenf que)
(cons item (Queue-rear que))
(add1 (Queue-lenr que))))
Returns the first element in the queue if non empty . Else raises an error
(: head : (All (A) ((Queue A) -> A)))
(define (head que)
(if (zero? (Queue-lenf que))
(error 'head "given queue is empty")
(car (Queue-preF que))))
Removes the first element in the queue and returns the rest
(: tail : (All (A) ((Queue A) -> (Queue A))))
(define (tail que)
(let ([lenf (Queue-lenf que)])
(if (zero? lenf)
(error 'tail "given queue is empty")
(internal-queue (cdr (Queue-preF que))
(box (lambda () (cdr (force (Queue-front que)))))
(sub1 lenf)
(Queue-rear que)
(Queue-lenr que)))))
;; similar to list map function
;; similar to list map function. apply is expensive so using case-lambda
;; in order to saperate the more common case
(: qmap :
(All (A C B ...)
(case-lambda
((A -> C) (Queue A) -> (Queue C))
((A B ... B -> C) (Queue A) (Queue B) ... B -> (Queue C)))))
(define qmap
(pcase-lambda: (A C B ...)
[([func : (A -> C)]
[deq : (Queue A)])
(map-single
((inst Queue C) '() (box (lambda () '())) 0 '() 0) func deq)]
[([func : (A B ... B -> C)]
[deq : (Queue A)] . [deqs : (Queue B) ... B])
(apply map-multiple
((inst Queue C) '() (box (lambda () '())) 0 '() 0)
func deq deqs)]))
(: map-single : (All (A C) ((Queue C) (A -> C) (Queue A) -> (Queue C))))
(define (map-single accum func que)
(if (empty? que)
accum
(map-single (enqueue (func (head que)) accum) func (tail que))))
(: map-multiple :
(All (A C B ...)
((Queue C) (A B ... B -> C) (Queue A) (Queue B) ... B -> (Queue C))))
(define (map-multiple accum func que . ques)
(if (or (empty? que) (ormap empty? ques))
accum
(apply map-multiple
(enqueue (apply func (head que) (map head ques)) accum)
func
(tail que)
(map tail ques))))
;; similar to list foldr or foldl
(: fold :
(All (A C B ...)
(case-lambda ((C A -> C) C (Queue A) -> C)
((C A B ... B -> C) C (Queue A) (Queue B) ... B -> C))))
(define fold
(pcase-lambda: (A C B ...)
[([func : (C A -> C)]
[base : C]
[que : (Queue A)])
(if (empty? que)
base
(fold func (func base (head que)) (tail que)))]
[([func : (C A B ... B -> C)]
[base : C]
[que : (Queue A)] . [ques : (Queue B) ... B])
(if (or (empty? que) (ormap empty? ques))
base
(apply fold
func
(apply func base (head que) (map head ques))
(tail que)
(map tail ques)))]))
(: queue->list : (All (A) ((Queue A) -> (Listof A))))
(define (queue->list que)
(if (empty? que)
null
(cons (head que) (queue->list (tail que)))))
(: list->queue : (All (A) ((Listof A) -> (Queue A))))
(define (list->queue items)
(foldl (inst enqueue A)
((inst Queue A) '() (box (lambda: () '())) 0 '() 0) items))
;; Queue constructor function
(: queue : (All (A) (A * -> (Queue A))))
(define (queue . items)
(foldl (inst enqueue A)
((inst Queue A) '() (box (lambda: () '())) 0 '() 0) items))
;; similar to list filter function
(: filter : (All (A) ((A -> Boolean) (Queue A) -> (Queue A))))
(define (filter func que)
(: inner : (All (A) ((A -> Boolean) (Queue A) (Queue A) -> (Queue A))))
(define (inner func que accum)
(if (empty? que)
accum
(let ([head (head que)]
[tail (tail que)])
(if (func head)
(inner func tail (enqueue head accum))
(inner func tail accum)))))
(inner func que
((inst Queue A) '() (box (lambda: () '())) 0 '() 0)))
;; similar to list remove function
(: remove : (All (A) ((A -> Boolean) (Queue A) -> (Queue A))))
(define (remove func que)
(: inner : (All (A) ((A -> Boolean) (Queue A) (Queue A) -> (Queue A))))
(define (inner func que accum)
(if (empty? que)
accum
(let ([head (head que)]
[tail (tail que)])
(if (func head)
(inner func tail accum)
(inner func tail (enqueue head accum))))))
(inner func que
((inst Queue A) '() (box (lambda: () '())) 0 '() 0)))
(: head+tail : (All (A) ((Queue A) -> (Pair A (Queue A)))))
(define (head+tail que)
(let ([lenf (Queue-lenf que)])
(if (zero? lenf)
(error 'head+tail "given queue is empty")
(let ([pref (Queue-preF que)])
(cons (car pref)
(internal-queue
(cdr pref)
(box (lambda () (cdr (force (Queue-front que)))))
(sub1 lenf)
(Queue-rear que)
(Queue-lenr que)))))))
;; Similar to build-list function
(: build-queue : (All (A) (Natural (Natural -> A) -> (Queue A))))
(define (build-queue size func)
(let: loop : (Queue A) ([n : Natural size])
(if (zero? n)
((inst Queue A) '() (box (lambda: () '())) 0 '() 0)
(let ([nsub1 (sub1 n)])
(enqueue (func nsub1) (loop nsub1))))))
similar to list andmap function
(: queue-andmap :
(All (A B ...)
(case-lambda ((A -> Boolean) (Queue A) -> Boolean)
((A B ... B -> Boolean) (Queue A) (Queue B) ... B -> Boolean))))
(define queue-andmap
(pcase-lambda: (A B ... )
[([func : (A -> Boolean)]
[queue : (Queue A)])
(or (empty? queue)
(and (func (head queue))
(queue-andmap func (tail queue))))]
[([func : (A B ... B -> Boolean)]
[queue : (Queue A)] . [queues : (Queue B) ... B])
(or (empty? queue) (ormap empty? queues)
(and (apply func (head queue) (map head queues))
(apply queue-andmap func (tail queue)
(map tail queues))))]))
;; Similar to ormap
(: queue-ormap :
(All (A B ...)
(case-lambda ((A -> Boolean) (Queue A) -> Boolean)
((A B ... B -> Boolean) (Queue A) (Queue B) ... B -> Boolean))))
(define queue-ormap
(pcase-lambda: (A B ... )
[([func : (A -> Boolean)]
[queue : (Queue A)])
(and (not (empty? queue))
(or (func (head queue))
(queue-ormap func (tail queue))))]
[([func : (A B ... B -> Boolean)]
[queue : (Queue A)] . [queues : (Queue B) ... B])
(and (not (or (empty? queue) (ormap empty? queues)))
(or (apply func (head queue) (map head queues))
(apply queue-ormap func (tail queue)
(map tail queues))))]))
| null | https://raw.githubusercontent.com/takikawa/tr-pfds/a08810bdfc760bb9ed68d08ea222a59135d9a203/pfds/queue/physicists.rkt | racket | Physicists Queue
Maintains invariant lenr <= lenf
pref is empty only if lenf = 0
Empty Queue Because of some limitations in TR in typechecking the
boxed values, I had to make empty a macro so that users can
instantiate empty easily.
Checks if the given Queue is empty
Maintains "preF" invariant (preF in not not null when front is not null)
(: check-pref-inv :
(Queue A))))
Maintains lenr <= lenf invariant
Maintains queue invariants
(: internal-queue :
similar to list map function
similar to list map function. apply is expensive so using case-lambda
in order to saperate the more common case
similar to list foldr or foldl
Queue constructor function
similar to list filter function
similar to list remove function
Similar to build-list function
Similar to ormap | #lang typed/racket
(provide filter remove Queue head+tail build-queue
empty empty? enqueue head tail queue->list queue list->queue
(rename-out [qmap map]
[queue-andmap andmap]
[queue-ormap ormap]) fold)
(define-type (Promiseof A) (Boxof (U (→ (Listof A)) (Listof A))))
(struct: (A) Queue ([preF : (Listof A)]
[front : (Promiseof A)]
[lenf : Integer]
[rear : (Listof A)]
[lenr : Integer]))
(define-syntax-rule (empty A)
((inst Queue A) '() (box (lambda: () '())) 0 '() 0))
(: empty? : (All (A) ((Queue A) -> Boolean)))
(define (empty? que)
(zero? (Queue-lenf que)))
(define-syntax-rule (force promise)
(let ([p (unbox promise)])
(if (procedure? p)
(let ([result (p)])
(set-box! (ann promise (Promiseof A)) result)
result)
p)))
( All ( A ) ( ( A ) ( Promiseof A ) Integer ( A ) Integer - >
(define-syntax-rule (check-pref-inv pref front lenf rear lenr)
(if (null? pref)
((inst Queue A) (force front) front lenf rear lenr)
((inst Queue A) pref front lenf rear lenr)))
(: check :
( All ( A ) ( ( A ) ( Promiseof A ) Integer ( A ) Integer - > ( Queue A ) ) ) )
(define-syntax-rule (check-len-inv pref front lenf rear lenr)
(if (>= lenf lenr)
(check-pref-inv pref front lenf rear lenr)
(let*: ([newpref : (Listof A) (force front)]
[newf : (Promiseof A)
(box (lambda () (append newpref (reverse rear))))])
(check-pref-inv newpref newf (+ lenf lenr) null 0))))
( All ( A ) ( ( A ) ( Promiseof A ) Integer ( A ) Integer - > ( Queue A ) ) ) )
(define-syntax-rule (internal-queue pref front lenf rear lenr)
(check-len-inv pref front lenf rear lenr))
an item into the list
(: enqueue : (All (A) (A (Queue A) -> (Queue A))))
(define (enqueue item que)
(internal-queue (Queue-preF que)
(Queue-front que)
(Queue-lenf que)
(cons item (Queue-rear que))
(add1 (Queue-lenr que))))
Returns the first element in the queue if non empty . Else raises an error
(: head : (All (A) ((Queue A) -> A)))
(define (head que)
(if (zero? (Queue-lenf que))
(error 'head "given queue is empty")
(car (Queue-preF que))))
Removes the first element in the queue and returns the rest
(: tail : (All (A) ((Queue A) -> (Queue A))))
(define (tail que)
(let ([lenf (Queue-lenf que)])
(if (zero? lenf)
(error 'tail "given queue is empty")
(internal-queue (cdr (Queue-preF que))
(box (lambda () (cdr (force (Queue-front que)))))
(sub1 lenf)
(Queue-rear que)
(Queue-lenr que)))))
(: qmap :
(All (A C B ...)
(case-lambda
((A -> C) (Queue A) -> (Queue C))
((A B ... B -> C) (Queue A) (Queue B) ... B -> (Queue C)))))
(define qmap
(pcase-lambda: (A C B ...)
[([func : (A -> C)]
[deq : (Queue A)])
(map-single
((inst Queue C) '() (box (lambda () '())) 0 '() 0) func deq)]
[([func : (A B ... B -> C)]
[deq : (Queue A)] . [deqs : (Queue B) ... B])
(apply map-multiple
((inst Queue C) '() (box (lambda () '())) 0 '() 0)
func deq deqs)]))
(: map-single : (All (A C) ((Queue C) (A -> C) (Queue A) -> (Queue C))))
(define (map-single accum func que)
(if (empty? que)
accum
(map-single (enqueue (func (head que)) accum) func (tail que))))
(: map-multiple :
(All (A C B ...)
((Queue C) (A B ... B -> C) (Queue A) (Queue B) ... B -> (Queue C))))
(define (map-multiple accum func que . ques)
(if (or (empty? que) (ormap empty? ques))
accum
(apply map-multiple
(enqueue (apply func (head que) (map head ques)) accum)
func
(tail que)
(map tail ques))))
(: fold :
(All (A C B ...)
(case-lambda ((C A -> C) C (Queue A) -> C)
((C A B ... B -> C) C (Queue A) (Queue B) ... B -> C))))
(define fold
(pcase-lambda: (A C B ...)
[([func : (C A -> C)]
[base : C]
[que : (Queue A)])
(if (empty? que)
base
(fold func (func base (head que)) (tail que)))]
[([func : (C A B ... B -> C)]
[base : C]
[que : (Queue A)] . [ques : (Queue B) ... B])
(if (or (empty? que) (ormap empty? ques))
base
(apply fold
func
(apply func base (head que) (map head ques))
(tail que)
(map tail ques)))]))
(: queue->list : (All (A) ((Queue A) -> (Listof A))))
(define (queue->list que)
(if (empty? que)
null
(cons (head que) (queue->list (tail que)))))
(: list->queue : (All (A) ((Listof A) -> (Queue A))))
(define (list->queue items)
(foldl (inst enqueue A)
((inst Queue A) '() (box (lambda: () '())) 0 '() 0) items))
(: queue : (All (A) (A * -> (Queue A))))
(define (queue . items)
(foldl (inst enqueue A)
((inst Queue A) '() (box (lambda: () '())) 0 '() 0) items))
(: filter : (All (A) ((A -> Boolean) (Queue A) -> (Queue A))))
(define (filter func que)
(: inner : (All (A) ((A -> Boolean) (Queue A) (Queue A) -> (Queue A))))
(define (inner func que accum)
(if (empty? que)
accum
(let ([head (head que)]
[tail (tail que)])
(if (func head)
(inner func tail (enqueue head accum))
(inner func tail accum)))))
(inner func que
((inst Queue A) '() (box (lambda: () '())) 0 '() 0)))
(: remove : (All (A) ((A -> Boolean) (Queue A) -> (Queue A))))
(define (remove func que)
(: inner : (All (A) ((A -> Boolean) (Queue A) (Queue A) -> (Queue A))))
(define (inner func que accum)
(if (empty? que)
accum
(let ([head (head que)]
[tail (tail que)])
(if (func head)
(inner func tail accum)
(inner func tail (enqueue head accum))))))
(inner func que
((inst Queue A) '() (box (lambda: () '())) 0 '() 0)))
(: head+tail : (All (A) ((Queue A) -> (Pair A (Queue A)))))
(define (head+tail que)
(let ([lenf (Queue-lenf que)])
(if (zero? lenf)
(error 'head+tail "given queue is empty")
(let ([pref (Queue-preF que)])
(cons (car pref)
(internal-queue
(cdr pref)
(box (lambda () (cdr (force (Queue-front que)))))
(sub1 lenf)
(Queue-rear que)
(Queue-lenr que)))))))
(: build-queue : (All (A) (Natural (Natural -> A) -> (Queue A))))
(define (build-queue size func)
(let: loop : (Queue A) ([n : Natural size])
(if (zero? n)
((inst Queue A) '() (box (lambda: () '())) 0 '() 0)
(let ([nsub1 (sub1 n)])
(enqueue (func nsub1) (loop nsub1))))))
similar to list andmap function
(: queue-andmap :
(All (A B ...)
(case-lambda ((A -> Boolean) (Queue A) -> Boolean)
((A B ... B -> Boolean) (Queue A) (Queue B) ... B -> Boolean))))
(define queue-andmap
(pcase-lambda: (A B ... )
[([func : (A -> Boolean)]
[queue : (Queue A)])
(or (empty? queue)
(and (func (head queue))
(queue-andmap func (tail queue))))]
[([func : (A B ... B -> Boolean)]
[queue : (Queue A)] . [queues : (Queue B) ... B])
(or (empty? queue) (ormap empty? queues)
(and (apply func (head queue) (map head queues))
(apply queue-andmap func (tail queue)
(map tail queues))))]))
(: queue-ormap :
(All (A B ...)
(case-lambda ((A -> Boolean) (Queue A) -> Boolean)
((A B ... B -> Boolean) (Queue A) (Queue B) ... B -> Boolean))))
(define queue-ormap
(pcase-lambda: (A B ... )
[([func : (A -> Boolean)]
[queue : (Queue A)])
(and (not (empty? queue))
(or (func (head queue))
(queue-ormap func (tail queue))))]
[([func : (A B ... B -> Boolean)]
[queue : (Queue A)] . [queues : (Queue B) ... B])
(and (not (or (empty? queue) (ormap empty? queues)))
(or (apply func (head queue) (map head queues))
(apply queue-ormap func (tail queue)
(map tail queues))))]))
|
d7ec7aea4c3169b5d1e3523e80792dc4a510b39857883da0e9ec6ee02d33407f | ocsigen/js_of_ocaml | transaction.ml |
Copyright ( c ) 2015 , < >
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 .
Copyright (c) 2015, KC Sivaramakrishnan <>
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.
*)
open Printf
open Effect
open Effect.Deep
type bottom
module type TXN = sig
type 'a t
val atomically : (unit -> unit) -> unit
val ref : 'a -> 'a t
val ( ! ) : 'a t -> 'a
val ( := ) : 'a t -> 'a -> unit
end
module Txn : TXN = struct
type 'a t = 'a ref
type _ Effect.t += Update : 'a t * 'a -> unit Effect.t
let atomically f =
let comp =
match_with
f
()
{ retc = (fun x _ -> x)
; exnc =
(fun e rb ->
rb ();
raise e)
; effc =
(fun (type a) (e : a Effect.t) ->
match e with
| Update (r, v) ->
Some
(fun (k : (a, _) continuation) rb ->
let old_v = !r in
r := v;
continue k () (fun () ->
r := old_v;
rb ()))
| _ -> None)
}
in
comp (fun () -> ())
let ref = ref
let ( ! ) = ( ! )
let ( := ) r v = perform (Update (r, v))
end
exception Res of int
open Txn
let%expect_test _ =
(try
atomically (fun () ->
let r = ref 10 in
printf "T0: %d\n" !r;
try
atomically (fun () ->
r := 20;
r := 21;
printf "T1: Before abort %d\n" !r;
raise (Res !r) |> ignore;
printf "T1: After abort %d\n" !r;
r := 30)
with
| Res v ->
printf "T0: T1 aborted with %d\n" v;
printf "T0: %d\n" !r
| e -> printf "inner exception: %s\n" (Printexc.to_string e))
with e -> printf "outer exception: %s\n" (Printexc.to_string e));
[%expect {|
T0: 10
T1: Before abort 21
T0: T1 aborted with 21
T0: 10 |}]
| null | https://raw.githubusercontent.com/ocsigen/js_of_ocaml/1ecf83641b4ccfebaa7bf37bd1197a91d36ddc41/compiler/tests-jsoo/lib-effects/transaction.ml | ocaml |
Copyright ( c ) 2015 , < >
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 .
Copyright (c) 2015, KC Sivaramakrishnan <>
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.
*)
open Printf
open Effect
open Effect.Deep
type bottom
module type TXN = sig
type 'a t
val atomically : (unit -> unit) -> unit
val ref : 'a -> 'a t
val ( ! ) : 'a t -> 'a
val ( := ) : 'a t -> 'a -> unit
end
module Txn : TXN = struct
type 'a t = 'a ref
type _ Effect.t += Update : 'a t * 'a -> unit Effect.t
let atomically f =
let comp =
match_with
f
()
{ retc = (fun x _ -> x)
; exnc =
(fun e rb ->
rb ();
raise e)
; effc =
(fun (type a) (e : a Effect.t) ->
match e with
| Update (r, v) ->
Some
(fun (k : (a, _) continuation) rb ->
let old_v = !r in
r := v;
continue k () (fun () ->
r := old_v;
rb ()))
| _ -> None)
}
in
comp (fun () -> ())
let ref = ref
let ( ! ) = ( ! )
let ( := ) r v = perform (Update (r, v))
end
exception Res of int
open Txn
let%expect_test _ =
(try
atomically (fun () ->
let r = ref 10 in
printf "T0: %d\n" !r;
try
atomically (fun () ->
r := 20;
r := 21;
printf "T1: Before abort %d\n" !r;
raise (Res !r) |> ignore;
printf "T1: After abort %d\n" !r;
r := 30)
with
| Res v ->
printf "T0: T1 aborted with %d\n" v;
printf "T0: %d\n" !r
| e -> printf "inner exception: %s\n" (Printexc.to_string e))
with e -> printf "outer exception: %s\n" (Printexc.to_string e));
[%expect {|
T0: 10
T1: Before abort 21
T0: T1 aborted with 21
T0: 10 |}]
| |
19137135e8a826c0cdfc850d3f206ec16644510a48e527b20df18e056217dcc1 | korya/efuns | appMgr.ml | (***********************************************************************)
(* *)
(* Gwml *)
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
open Options
open Xtypes
open Xlib
open Gwml
open Stdconfig
(* Application manager *)
(* This is a small hack to display a bar with all windows satisfying
a given predicate.
Button 1 -> Deiconify + raise_window
Button 2 -> Iconify/Deiconify
Button 3 -> Deiconify + Virtual goto
*)
type app_manager = {
pred : client_desc -> bool;
bar : Bar.bar;
force : int;
mutable labels: (wob_desc * Label.label) list;
}
let managers = Wobenv.new_var ()
let manager_label = Wobenv.new_var ()
let min_width = define_option ["iconMgr_width"] "" int_option 150
let min_height = define_option ["iconMgr_label_height"] "" int_option 17
(* [create wob x y pred] *)
let create w x y name force pred =
let bar =
let label = new Label.label name in
label#set_min_width !!min_width;
label#set_max_width !!min_width;
label#set_font !!iconMgr_title_font;
label#set_foreground !!iconMgr_title_foreground;
label#set_background !!iconMgr_title_background;
label#set_backimage !!iconMgr_title_image;
new Bar.bar Vertical [| Wob.desc label |]
in
let top_hook top e =
match e with
| WobEnter ->
let tw = top#wob in
raiseWindow display tw.w_window;
ontop_update tw
| WobInit ->
let w = top#wob in
let sw = w.w_parent in
let sg = sw.w_geometry in
let g = w.w_geometry in
g.x <- min (sg.width - !!min_width) x;
g.y <- y;
| _ -> ()
in
let sw = w.w_top.w_parent in
let sg = sw.w_geometry in
let top = Top.make sw ("appMgr_" ^ name)
[top_hook] (bar :> wob_desc) None None None None in
let g = top#wob.w_geometry in
g.x <- min (sg.width - !!min_width) x;
g.y <- y;
let old = try Wob.getenv sw managers with _ -> [] in
let m = { pred = pred; bar = bar; force = force; labels = []; } in
Wob.setenv sw managers (
Sort.list (fun m1 m2 -> m1.force <= m2.force)
(m :: old));
Wob.send top#wob WobMap
let goto w () =
let w = w.w_top in
let s = w.w_screen.s_scr in
(!desk_manager)#goto w;
(!virtual_manager)#goto w;
Wob.send w.w_top WobRaiseWindow;
X.warpPointer display s.scr_root 0 0 s.scr_width s.scr_height
w.w_window 20 20
let iconMgr_actions = define_option ["iconMgr_actions"]
"<iconMgr_actions> is the bindings list for each label in the icon manager
(the application manager). See <screen_actions> for the format of a list
of bindings."
(list_option binding_option) []
let toggle_iconify w =
let tw = w.w_top in
let c = tw.w_oo#client in
if c.c_wm_state = IconicState || c.c_wm_state = WithdrawnState then
Wob.send tw (WobDeiconifyRequest true)
else
Wob.send tw (WobIconifyRequest true)
let _ =
define_action "toggle_iconify" (Function toggle_iconify);
define_action "goto_window" (Function goto_window);
if !!iconMgr_actions = [] then begin
iconMgr_actions =:= [
Button (1, 0), NamedAction "raise_window", false;
Button (2, 0), NamedAction "toggle_iconify", false;
Button (3, 0), NamedAction "goto_window", false;
];
end
let client_var = Wobenv.new_var ()
let execute_action action w =
let w = Wob.getenv w client_var in
match get_action action with
NoAction -> ()
| Function f -> f w
| Menu m -> ignore (popup_menu w true (m ()))
| ActiveMenu m -> ignore (popup_menu w true (m w))
| NamedAction _ -> assert false
| NamedActionX _ -> assert false
let convert_bindings l =
List.map (fun (key, action, grabbed) ->
(key, execute_action action, grabbed)) l
let label_hook c tw desc e =
match e with
WobInit ->
desc#set_actions (convert_bindings !!iconMgr_actions);
desc#set_mask (ButtonPressMask :: desc#mask);
Log.catch "AppMgr.label_hook: WobInit -> %s" (fun _ ->
Wob.setenv desc#wob client_var tw)
| _ -> ()
let update c tw =
let sw = tw.w_parent in
let managers = Wob.getenv sw managers in
try
List.iter (fun m ->
if m.pred c then
let c_label = Wob.getenv tw manager_label in
c_label#set_string (Printf.sprintf "%s%s"
(if Wob.sgetenv tw is_iconified_var false then "(ICON) " else
if not (Wob.sgetenv tw is_in_dvroom_var true) then
"(DESK) " else "")
(!comp_name c.c_name));
raise Exit
) managers
with _ -> ()
let hook c desc e =
match e with
WobCreate ->
let tw = desc#wob in
let sw = tw.w_parent in
let managers = Wob.getenv sw managers in
List.iter (fun m ->
if m.pred c then
let c_label = new Label.label (!comp_name c.c_name) in
c_label#set_min_height !!min_height;
c_label#set_max_width !!min_width;
c_label#set_mask (ButtonPressMask :: c_label#mask);
c_label#set_borderwidth 1;
c_label#add_hook (label_hook c tw c_label);
c_label#set_font !!iconMgr_font;
c_label#set_background !!iconMgr_background;
c_label#set_foreground !!iconMgr_foreground;
c_label#set_backimage !!iconMgr_image;
c_label#set_hilite_foreground !!iconMgr_active_foreground;
c_label#set_hilite_background !!iconMgr_active_background;
c_label#set_hilite_backimage !!iconMgr_active_image;
m.bar#add_item (Wob.desc c_label);
m.labels <- (desc, c_label) :: m.labels;
Wob.setenv tw manager_label c_label;
let tw = m.bar#wob.w_top in
let s = sw.w_screen in
let (c,w) = Wintbl.find s.s_clients tw.w_window in
let tg = tw.w_geometry in
let g = w.w_geometry in
g.width <- tg.width;
g.height <- tg.height;
Wob.send w.w_top WobGetSize;
Wob.send c_label#wob WobMap;
raise Exit) managers
| WobPropertyChange p when p = XA.xa_wm_name ->
let tw = desc#wob in update c tw
| WobUnmap _
| WobMap ->
let tw = desc#wob in update c tw
| WobDestroy ->
let tw = desc#wob in
let sw = tw.w_parent in
let managers = Wob.getenv sw managers in
List.iter (fun m ->
if m.pred c then
let c_label = Wob.getenv tw manager_label in
let items = m.bar#items in
for i = 0 to Array.length items - 1 do
if (Wob.desc c_label) == items.(i) then
begin
m.bar#remove_item i;
m.labels <- List.remove_assq desc m.labels;
raise Exit
end
done;
) managers
| _ -> ()
let noOwnerEvents = false
let rec first_client managers =
match managers with
[] -> raise Exit
| { labels = [] } :: managers -> first_client managers
| { labels = client :: clients } :: managers -> client, clients, managers
let rec next_client clients managers all_managers =
match clients with
client :: clients -> client, clients, managers
| [] ->
match managers with
[] -> first_client all_managers
| { labels = [] } :: managers -> next_client [] managers all_managers
| { labels = client :: clients } :: managers ->
client, clients, managers
let prev_client client managers =
let first_client = first_client managers in
let rec iter ((_, clients, ms) as prev_client) =
let (next_client, _, _) as next = next_client clients ms managers in
if next_client == client then prev_client
else iter next
in
iter first_client
let highlight ((_,label), _,_) = label#hilite
let unhighlight ((_,label), _, _) = label#unhilite
let key_control sw managers =
let s = sw.w_screen in
let scr = s.s_scr in
let client = ref (first_client managers) in
highlight !client;
try
X.grabKeyboard display scr.scr_root noOwnerEvents
GrabModeAsync GrabModeAsync currentTime;
First of all , raise all the manager windows
List.iter (fun m ->
Xlib.raiseWindow display m.bar#wob.w_top.w_window) managers;
while true do
let ev = Xlib.peekEvent display in
match ev.ev_event with
| KeyReleaseEvent _ -> ()
| KeyPressEvent e ->
let modifiers = e.Xkey.state in
let (s,keysym,m) = KeyBind.lookupString display ev.ev_event in
if keysym = XK.xk_Escape then raise Exit;
if keysym = XK.xk_Tab || keysym = XK.xk_Down
|| keysym = XK.xk_Up then
begin
unhighlight !client;
let (c, clients, ms) = !client in
if (modifiers land controlMask <> 0) || keysym = XK.xk_Up then
client := next_client clients ms managers
else
client := prev_client c managers;
highlight !client;
end else
let ((top, _), _, _) = !client in
let c = top#client in
if keysym = XK.xk_i then begin
if c.c_wm_state = IconicState || c.c_wm_state = WithdrawnState
then Wob.send top#wob (WobDeiconifyRequest true) else
Wob.send top#wob (WobIconifyRequest true)
end
else if keysym = XK.xk_l then
Wob.send top#wob WobLowerWindow
else if keysym = XK.xk_r then
Wob.send top#wob WobRaiseWindow
else if keysym = XK.xk_k then
Wob.send top#wob WobDestroy
else if keysym = XK.xk_d then
Wob.send top#wob WobDeleteWindow
else if keysym = XK.xk_w || keysym = XK.xk_Return then begin
if c.c_wm_state = IconicState || c.c_wm_state = WithdrawnState
then Wob.send top#wob (WobDeiconifyRequest true);
goto top#wob ();
raise Exit
end
| ExposeEvent e ->
Eloop.handle_event s.s_scheduler ev
| _ -> Xlib.putBackEvent display ev
done;
with
| GrabError _ -> unhighlight !client
| _ ->
unhighlight !client;
List.iter (fun m ->
Xlib.lowerWindow display m.bar#wob.w_top.w_window) managers;
X.ungrabKeyboard display currentTime
let message w msg =
let sw = w.w_top.w_parent in
let managers = Wob.getenv sw managers in
if msg = "key-control" then key_control sw managers else
()
class manager = (object
method hook = hook
method create = create
method message = message
end : Stdconfig.icon_manager)
let manager = new manager
| null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/gwml/appMgr.ml | ocaml | *********************************************************************
Gwml
*********************************************************************
Application manager
This is a small hack to display a bar with all windows satisfying
a given predicate.
Button 1 -> Deiconify + raise_window
Button 2 -> Iconify/Deiconify
Button 3 -> Deiconify + Virtual goto
[create wob x y pred] | Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
open Options
open Xtypes
open Xlib
open Gwml
open Stdconfig
type app_manager = {
pred : client_desc -> bool;
bar : Bar.bar;
force : int;
mutable labels: (wob_desc * Label.label) list;
}
let managers = Wobenv.new_var ()
let manager_label = Wobenv.new_var ()
let min_width = define_option ["iconMgr_width"] "" int_option 150
let min_height = define_option ["iconMgr_label_height"] "" int_option 17
let create w x y name force pred =
let bar =
let label = new Label.label name in
label#set_min_width !!min_width;
label#set_max_width !!min_width;
label#set_font !!iconMgr_title_font;
label#set_foreground !!iconMgr_title_foreground;
label#set_background !!iconMgr_title_background;
label#set_backimage !!iconMgr_title_image;
new Bar.bar Vertical [| Wob.desc label |]
in
let top_hook top e =
match e with
| WobEnter ->
let tw = top#wob in
raiseWindow display tw.w_window;
ontop_update tw
| WobInit ->
let w = top#wob in
let sw = w.w_parent in
let sg = sw.w_geometry in
let g = w.w_geometry in
g.x <- min (sg.width - !!min_width) x;
g.y <- y;
| _ -> ()
in
let sw = w.w_top.w_parent in
let sg = sw.w_geometry in
let top = Top.make sw ("appMgr_" ^ name)
[top_hook] (bar :> wob_desc) None None None None in
let g = top#wob.w_geometry in
g.x <- min (sg.width - !!min_width) x;
g.y <- y;
let old = try Wob.getenv sw managers with _ -> [] in
let m = { pred = pred; bar = bar; force = force; labels = []; } in
Wob.setenv sw managers (
Sort.list (fun m1 m2 -> m1.force <= m2.force)
(m :: old));
Wob.send top#wob WobMap
let goto w () =
let w = w.w_top in
let s = w.w_screen.s_scr in
(!desk_manager)#goto w;
(!virtual_manager)#goto w;
Wob.send w.w_top WobRaiseWindow;
X.warpPointer display s.scr_root 0 0 s.scr_width s.scr_height
w.w_window 20 20
let iconMgr_actions = define_option ["iconMgr_actions"]
"<iconMgr_actions> is the bindings list for each label in the icon manager
(the application manager). See <screen_actions> for the format of a list
of bindings."
(list_option binding_option) []
let toggle_iconify w =
let tw = w.w_top in
let c = tw.w_oo#client in
if c.c_wm_state = IconicState || c.c_wm_state = WithdrawnState then
Wob.send tw (WobDeiconifyRequest true)
else
Wob.send tw (WobIconifyRequest true)
let _ =
define_action "toggle_iconify" (Function toggle_iconify);
define_action "goto_window" (Function goto_window);
if !!iconMgr_actions = [] then begin
iconMgr_actions =:= [
Button (1, 0), NamedAction "raise_window", false;
Button (2, 0), NamedAction "toggle_iconify", false;
Button (3, 0), NamedAction "goto_window", false;
];
end
let client_var = Wobenv.new_var ()
let execute_action action w =
let w = Wob.getenv w client_var in
match get_action action with
NoAction -> ()
| Function f -> f w
| Menu m -> ignore (popup_menu w true (m ()))
| ActiveMenu m -> ignore (popup_menu w true (m w))
| NamedAction _ -> assert false
| NamedActionX _ -> assert false
let convert_bindings l =
List.map (fun (key, action, grabbed) ->
(key, execute_action action, grabbed)) l
let label_hook c tw desc e =
match e with
WobInit ->
desc#set_actions (convert_bindings !!iconMgr_actions);
desc#set_mask (ButtonPressMask :: desc#mask);
Log.catch "AppMgr.label_hook: WobInit -> %s" (fun _ ->
Wob.setenv desc#wob client_var tw)
| _ -> ()
let update c tw =
let sw = tw.w_parent in
let managers = Wob.getenv sw managers in
try
List.iter (fun m ->
if m.pred c then
let c_label = Wob.getenv tw manager_label in
c_label#set_string (Printf.sprintf "%s%s"
(if Wob.sgetenv tw is_iconified_var false then "(ICON) " else
if not (Wob.sgetenv tw is_in_dvroom_var true) then
"(DESK) " else "")
(!comp_name c.c_name));
raise Exit
) managers
with _ -> ()
let hook c desc e =
match e with
WobCreate ->
let tw = desc#wob in
let sw = tw.w_parent in
let managers = Wob.getenv sw managers in
List.iter (fun m ->
if m.pred c then
let c_label = new Label.label (!comp_name c.c_name) in
c_label#set_min_height !!min_height;
c_label#set_max_width !!min_width;
c_label#set_mask (ButtonPressMask :: c_label#mask);
c_label#set_borderwidth 1;
c_label#add_hook (label_hook c tw c_label);
c_label#set_font !!iconMgr_font;
c_label#set_background !!iconMgr_background;
c_label#set_foreground !!iconMgr_foreground;
c_label#set_backimage !!iconMgr_image;
c_label#set_hilite_foreground !!iconMgr_active_foreground;
c_label#set_hilite_background !!iconMgr_active_background;
c_label#set_hilite_backimage !!iconMgr_active_image;
m.bar#add_item (Wob.desc c_label);
m.labels <- (desc, c_label) :: m.labels;
Wob.setenv tw manager_label c_label;
let tw = m.bar#wob.w_top in
let s = sw.w_screen in
let (c,w) = Wintbl.find s.s_clients tw.w_window in
let tg = tw.w_geometry in
let g = w.w_geometry in
g.width <- tg.width;
g.height <- tg.height;
Wob.send w.w_top WobGetSize;
Wob.send c_label#wob WobMap;
raise Exit) managers
| WobPropertyChange p when p = XA.xa_wm_name ->
let tw = desc#wob in update c tw
| WobUnmap _
| WobMap ->
let tw = desc#wob in update c tw
| WobDestroy ->
let tw = desc#wob in
let sw = tw.w_parent in
let managers = Wob.getenv sw managers in
List.iter (fun m ->
if m.pred c then
let c_label = Wob.getenv tw manager_label in
let items = m.bar#items in
for i = 0 to Array.length items - 1 do
if (Wob.desc c_label) == items.(i) then
begin
m.bar#remove_item i;
m.labels <- List.remove_assq desc m.labels;
raise Exit
end
done;
) managers
| _ -> ()
let noOwnerEvents = false
let rec first_client managers =
match managers with
[] -> raise Exit
| { labels = [] } :: managers -> first_client managers
| { labels = client :: clients } :: managers -> client, clients, managers
let rec next_client clients managers all_managers =
match clients with
client :: clients -> client, clients, managers
| [] ->
match managers with
[] -> first_client all_managers
| { labels = [] } :: managers -> next_client [] managers all_managers
| { labels = client :: clients } :: managers ->
client, clients, managers
let prev_client client managers =
let first_client = first_client managers in
let rec iter ((_, clients, ms) as prev_client) =
let (next_client, _, _) as next = next_client clients ms managers in
if next_client == client then prev_client
else iter next
in
iter first_client
let highlight ((_,label), _,_) = label#hilite
let unhighlight ((_,label), _, _) = label#unhilite
let key_control sw managers =
let s = sw.w_screen in
let scr = s.s_scr in
let client = ref (first_client managers) in
highlight !client;
try
X.grabKeyboard display scr.scr_root noOwnerEvents
GrabModeAsync GrabModeAsync currentTime;
First of all , raise all the manager windows
List.iter (fun m ->
Xlib.raiseWindow display m.bar#wob.w_top.w_window) managers;
while true do
let ev = Xlib.peekEvent display in
match ev.ev_event with
| KeyReleaseEvent _ -> ()
| KeyPressEvent e ->
let modifiers = e.Xkey.state in
let (s,keysym,m) = KeyBind.lookupString display ev.ev_event in
if keysym = XK.xk_Escape then raise Exit;
if keysym = XK.xk_Tab || keysym = XK.xk_Down
|| keysym = XK.xk_Up then
begin
unhighlight !client;
let (c, clients, ms) = !client in
if (modifiers land controlMask <> 0) || keysym = XK.xk_Up then
client := next_client clients ms managers
else
client := prev_client c managers;
highlight !client;
end else
let ((top, _), _, _) = !client in
let c = top#client in
if keysym = XK.xk_i then begin
if c.c_wm_state = IconicState || c.c_wm_state = WithdrawnState
then Wob.send top#wob (WobDeiconifyRequest true) else
Wob.send top#wob (WobIconifyRequest true)
end
else if keysym = XK.xk_l then
Wob.send top#wob WobLowerWindow
else if keysym = XK.xk_r then
Wob.send top#wob WobRaiseWindow
else if keysym = XK.xk_k then
Wob.send top#wob WobDestroy
else if keysym = XK.xk_d then
Wob.send top#wob WobDeleteWindow
else if keysym = XK.xk_w || keysym = XK.xk_Return then begin
if c.c_wm_state = IconicState || c.c_wm_state = WithdrawnState
then Wob.send top#wob (WobDeiconifyRequest true);
goto top#wob ();
raise Exit
end
| ExposeEvent e ->
Eloop.handle_event s.s_scheduler ev
| _ -> Xlib.putBackEvent display ev
done;
with
| GrabError _ -> unhighlight !client
| _ ->
unhighlight !client;
List.iter (fun m ->
Xlib.lowerWindow display m.bar#wob.w_top.w_window) managers;
X.ungrabKeyboard display currentTime
let message w msg =
let sw = w.w_top.w_parent in
let managers = Wob.getenv sw managers in
if msg = "key-control" then key_control sw managers else
()
class manager = (object
method hook = hook
method create = create
method message = message
end : Stdconfig.icon_manager)
let manager = new manager
|
86810bae75af8421a351f3778fe50ac228e249d6894d8575d5657bc7962b3089 | REPROSEC/dolev-yao-star | Spec_P256_MontgomeryMultiplication_PointDouble.ml | open Prims
let (prime : Prims.pos) = Spec_P256_Definitions.prime256
| null | https://raw.githubusercontent.com/REPROSEC/dolev-yao-star/d97a8dd4d07f2322437f186e4db6a1f4d5ee9230/concrete/hacl-star-snapshot/ml/Spec_P256_MontgomeryMultiplication_PointDouble.ml | ocaml | open Prims
let (prime : Prims.pos) = Spec_P256_Definitions.prime256
| |
868ee1d906f2af1fb474f4abae439acaf69204be51303e35c1abd15438fc8c93 | lymar/hastache | conditionalNumber.hs | #!/usr/local/bin/runhaskell
import Text.Hastache
import Text.Hastache.Context
import qualified Data.Text.Lazy.IO as TL
-- begin example
main = mapM_ (\ctx ->
hastacheStr defaultConfig (encodeStr template) (mkStrContext ctx)
>>= TL.putStrLn) [context1,context2]
template = "{{#msg}}{{msg}}{{/msg}}{{^msg}}No{{/msg}} new messages."
context1 "msg" = MuVariable (100 :: Int)
context2 "msg" = MuVariable (0 :: Int)
| null | https://raw.githubusercontent.com/lymar/hastache/cd299ff1ac4c35259fbd333ea7fa9b3c280b9ff9/examples/conditionalNumber.hs | haskell | begin example | #!/usr/local/bin/runhaskell
import Text.Hastache
import Text.Hastache.Context
import qualified Data.Text.Lazy.IO as TL
main = mapM_ (\ctx ->
hastacheStr defaultConfig (encodeStr template) (mkStrContext ctx)
>>= TL.putStrLn) [context1,context2]
template = "{{#msg}}{{msg}}{{/msg}}{{^msg}}No{{/msg}} new messages."
context1 "msg" = MuVariable (100 :: Int)
context2 "msg" = MuVariable (0 :: Int)
|
ab8d1e70cca172441d2bed6b7c432b17649ff2ce014127ba275884db2a017a12 | cadpnq/papyrith | instructions.lisp | ;;;; Define the instructions of the papyrus VM
(in-package :papyrith)
(defstruct instruction
op asm target name dest arg1 arg2 arg3
arg4 arg5 parameters)
(defmacro def-instruction (name asm &rest arguments)
`(defstruct (,name
(:include instruction
(op ',name)
(asm ',asm))
(:constructor ,name ,arguments)
(:print-function
(lambda (p s k)
(format s "~A ~{~A ~}"
(instruction-asm p)
(mapcar #'(lambda (a) (slot-value p a))
',arguments)))))))
(defmacro def-instructions (names &rest arguments)
`(progn ,@(loop for (name asm) in names
collect `(def-instruction ,name ,asm ,@arguments))))
(defstruct (label
(:include instruction
(op 'label))
(:constructor label (name))
(:print-function
(lambda (p s k)
(format s "~A" (instruction-name p))))))
(defun print-instruction (instruction)
(if (label-p instruction)
(format nil "~A:" instruction)
(format nil "~A" instruction)))
(defun new-label ()
(label (gensym "label")))
(def-instructions
((integer-add iadd)
(integer-sub isubtract)
(integer-mul imultiply)
(integer-div idivide)
(integer-mod imod))
dest
arg1
arg2)
(def-instruction integer-neg ineg
dest
arg1)
(def-instructions
((float-add fadd)
(float-sub fsubtract)
(float-mul fmultiply)
(float-div fdivide))
dest
arg1
arg2)
(def-instruction float-neg fneg
dest
arg1)
(def-instructions
((jump-t jumpt)
(jump-f jumpf))
arg1
target)
(def-instruction jump jump
target)
(def-instruction ret return
arg1)
(def-instruction assign assign
dest
arg1)
(def-instruction cast-as cast
dest
arg1)
(def-instruction is is
dest
arg1
arg2)
(def-instruction nop nop)
(def-instruction string-cat strcat
dest
arg1
arg2)
(def-instructions
((compare-eq compareeq)
(compare-lt comparelt)
(compare-lte comparelte)
(compare-gt comparegt)
(compare-gte comparegte))
dest
arg1
arg2)
(def-instruction logical-not not
dest
arg1)
(def-instruction prop-get propget)
(def-instruction prop-set propset)
(def-instruction array-create arraycreate)
(def-instruction array-length arraylength)
(def-instruction array-get-element arraygetelement
dest
arg1
arg2)
(def-instruction array-set-element arraysetelement
arg1
arg2
arg3)
(def-instruction array-find-element arrayfindelement)
(def-instruction array-rfind-element arrayrfindelement)
(def-instruction array-add arrayadd)
(def-instruction array-insert arrayinsert)
(def-instruction array-remove-last arrayremovelast)
(def-instruction array-remove arrayremove)
(def-instruction array-clear arrayclear)
(def-instruction array-find-struct arrayfindstruct)
(def-instruction array-rfind-struct arrayrfindstruct)
(def-instruction struct-create structcreate)
(def-instruction struct-get structget)
(def-instruction struct-set structset)
(def-instruction call-method-papyrus callmethod)
(def-instruction call-parent callparent)
(def-instruction call-static callstatic)
| null | https://raw.githubusercontent.com/cadpnq/papyrith/755579f38a7f3f20d528966b4e548cc6e9bb006f/instructions.lisp | lisp | Define the instructions of the papyrus VM |
(in-package :papyrith)
(defstruct instruction
op asm target name dest arg1 arg2 arg3
arg4 arg5 parameters)
(defmacro def-instruction (name asm &rest arguments)
`(defstruct (,name
(:include instruction
(op ',name)
(asm ',asm))
(:constructor ,name ,arguments)
(:print-function
(lambda (p s k)
(format s "~A ~{~A ~}"
(instruction-asm p)
(mapcar #'(lambda (a) (slot-value p a))
',arguments)))))))
(defmacro def-instructions (names &rest arguments)
`(progn ,@(loop for (name asm) in names
collect `(def-instruction ,name ,asm ,@arguments))))
(defstruct (label
(:include instruction
(op 'label))
(:constructor label (name))
(:print-function
(lambda (p s k)
(format s "~A" (instruction-name p))))))
(defun print-instruction (instruction)
(if (label-p instruction)
(format nil "~A:" instruction)
(format nil "~A" instruction)))
(defun new-label ()
(label (gensym "label")))
(def-instructions
((integer-add iadd)
(integer-sub isubtract)
(integer-mul imultiply)
(integer-div idivide)
(integer-mod imod))
dest
arg1
arg2)
(def-instruction integer-neg ineg
dest
arg1)
(def-instructions
((float-add fadd)
(float-sub fsubtract)
(float-mul fmultiply)
(float-div fdivide))
dest
arg1
arg2)
(def-instruction float-neg fneg
dest
arg1)
(def-instructions
((jump-t jumpt)
(jump-f jumpf))
arg1
target)
(def-instruction jump jump
target)
(def-instruction ret return
arg1)
(def-instruction assign assign
dest
arg1)
(def-instruction cast-as cast
dest
arg1)
(def-instruction is is
dest
arg1
arg2)
(def-instruction nop nop)
(def-instruction string-cat strcat
dest
arg1
arg2)
(def-instructions
((compare-eq compareeq)
(compare-lt comparelt)
(compare-lte comparelte)
(compare-gt comparegt)
(compare-gte comparegte))
dest
arg1
arg2)
(def-instruction logical-not not
dest
arg1)
(def-instruction prop-get propget)
(def-instruction prop-set propset)
(def-instruction array-create arraycreate)
(def-instruction array-length arraylength)
(def-instruction array-get-element arraygetelement
dest
arg1
arg2)
(def-instruction array-set-element arraysetelement
arg1
arg2
arg3)
(def-instruction array-find-element arrayfindelement)
(def-instruction array-rfind-element arrayrfindelement)
(def-instruction array-add arrayadd)
(def-instruction array-insert arrayinsert)
(def-instruction array-remove-last arrayremovelast)
(def-instruction array-remove arrayremove)
(def-instruction array-clear arrayclear)
(def-instruction array-find-struct arrayfindstruct)
(def-instruction array-rfind-struct arrayrfindstruct)
(def-instruction struct-create structcreate)
(def-instruction struct-get structget)
(def-instruction struct-set structset)
(def-instruction call-method-papyrus callmethod)
(def-instruction call-parent callparent)
(def-instruction call-static callstatic)
|
fd0e7028c5226c05be99335a98e5ff0682db0372378aa34632e63d29d16412b3 | inaka/sumo_rest | sr_elements_SUITE.erl | -module(sr_elements_SUITE).
-include_lib("mixer/include/mixer.hrl").
-mixin([{ sr_test_utils
, [ init_per_suite/1
, end_per_suite/1
]
}]).
-export([ all/0
, init_per_testcase/2
, end_per_testcase/2
]).
-export([ success_scenario/1
, duplicated_key/1
, invalid_headers/1
, invalid_parameters/1
, not_found/1
, location/1
, binary_id_conversion/1
]).
-spec all() -> [atom()].
all() -> sr_test_utils:all(?MODULE).
-spec init_per_testcase(atom(), sr_test_utils:config()) ->
sr_test_utils:config().
init_per_testcase(_, Config) ->
_ = sumo:delete_all(elements),
Config.
-spec end_per_testcase(atom(), sr_test_utils:config()) ->
sr_test_utils:config().
end_per_testcase(_, Config) ->
Config.
-spec success_scenario(sr_test_utils:config()) -> {comment, string()}.
success_scenario(_Config) ->
Headers = #{<<"content-type">> => <<"application/json; charset=utf-8">>},
ct:comment("There are no elements"),
#{status_code := 200, body := Body0} =
sr_test_utils:api_call(get, "/elements"),
[] = sr_json:decode(Body0),
ct:comment("Element 1 is created"),
#{status_code := 201, body := Body1} =
sr_test_utils:api_call(
post, "/elements", Headers,
#{ key => 1
, value => <<"val1">>
}),
#{ <<"key">> := 1
, <<"created_at">> := CreatedAt
, <<"updated_at">> := CreatedAt
} = Element1 = sr_json:decode(Body1),
ct:comment("Find element using query string"),
#{status_code := 200, body := BodyA} =
sr_test_utils:api_call(get, "/elements?value=val1"),
[#{ <<"created_at">> := CreatedAt
, <<"key">> := 1
, <<"updated_at">> := CreatedAt
, <<"value">> := <<"val1">>
}] = sr_json:decode(BodyA),
ct:comment("Find elements non existent value using query string"),
#{status_code := 200, body := BodyB} =
sr_test_utils:api_call(get, "/elements?novalue=noval"),
[Element1] = sr_json:decode(BodyB),
ct:comment("Element 1 is modified"),
#{status_code := 422, body := Body01} =
sr_test_utils:api_call(
put, "/elements", #{<<"content-type">> => <<"application/json">>},
#{ key => 1
, value => <<"val1">>
}),
#{ <<"error">> := <<"Duplicated entity">>
} = sr_json:decode(Body01),
ct:comment("There is one element now"),
#{status_code := 200, body := Body2} =
sr_test_utils:api_call(get, "/elements"),
[Element1] = sr_json:decode(Body2),
ct:comment("And we can fetch it"),
#{status_code := 200, body := Body21} =
sr_test_utils:api_call(get, "/elements/1"),
Element1 = sr_json:decode(Body21),
ct:comment("The element value can be changed"),
#{status_code := 200, body := Body3} =
sr_test_utils:api_call(
put, "/elements/1", Headers,
#{ key => 1
, value => <<"newval3">>
}),
#{ <<"key">> := 1
, <<"value">> := <<"newval3">>
, <<"created_at">> := CreatedAt
, <<"updated_at">> := UpdatedAt
} = Element3 = sr_json:decode(Body3),
true = UpdatedAt >= CreatedAt,
ct:comment("Still just one element"),
#{status_code := 200, body := Body4} =
sr_test_utils:api_call(get, "/elements"),
[Element3] = sr_json:decode(Body4),
ct:comment("The element value can be changed by PATCH"),
#{status_code := 200, body := Body5} =
sr_test_utils:api_call(
patch, "/elements/1", Headers, #{value => <<"newval5">>}),
#{ <<"key">> := 1
, <<"value">> := <<"newval5">>
, <<"created_at">> := CreatedAt
, <<"updated_at">> := UpdatedAt5
} = Element5 = sr_json:decode(Body5),
true = UpdatedAt5 >= CreatedAt,
ct:comment("Still just one element"),
#{status_code := 200, body := Body6} =
sr_test_utils:api_call(get, "/elements"),
[Element5] = sr_json:decode(Body6),
ct:comment("Elements can be created by PUT"),
#{status_code := 201, body := Body7} =
sr_test_utils:api_call(
put, "/elements/2", Headers,
#{ key => 2
, value => <<"val2">>
}),
#{ <<"key">> := 2
, <<"value">> := <<"val2">>
, <<"created_at">> := CreatedAt7
, <<"updated_at">> := CreatedAt7
} = Element7 = sr_json:decode(Body7),
true = CreatedAt7 >= CreatedAt,
ct:comment("There are two elements now"),
#{status_code := 200, body := Body8} =
sr_test_utils:api_call(get, "/elements"),
[Element7] = sr_json:decode(Body8) -- [Element5],
ct:comment("Element1 is deleted"),
#{status_code := 204} = sr_test_utils:api_call(delete, "/elements/1"),
ct:comment("One element again"),
#{status_code := 200, body := Body9} =
sr_test_utils:api_call(get, "/elements"),
[Element7] = sr_json:decode(Body9),
ct:comment("DELETE is not idempotent"),
#{status_code := 204} = sr_test_utils:api_call(delete, "/elements/2"),
#{status_code := 404} = sr_test_utils:api_call(delete, "/elements/2"),
ct:comment("There are no elements"),
#{status_code := 200, body := Body10} =
sr_test_utils:api_call(get, "/elements"),
[] = sr_json:decode(Body10),
{comment, ""}.
-spec duplicated_key(sr_test_utils:config()) -> {comment, string()}.
duplicated_key(_Config) ->
Headers = #{<<"content-type">> => <<"application/json; charset=utf-8">>},
Body =
#{ key => <<"element1">>
, value => <<"val1">>
},
ct:comment("Element 1 is created"),
#{status_code := 201} =
sr_test_utils:api_call(post, "/elements", Headers, Body),
ct:comment("Element 1 can't be created again"),
#{status_code := 422} =
sr_test_utils:api_call(post, "/elements", Headers, Body),
{comment, ""}.
-spec invalid_headers(sr_test_utils:config()) -> {comment, string()}.
invalid_headers(_Config) ->
NoHeaders = #{},
InvalidHeaders = #{<<"content-type">> => <<"text/plain">>},
InvalidAccept = #{ <<"content-type">> => <<"application/json">>
, <<"accept">> => <<"text/html">>
},
ct:comment("content-type must be provided for POST and PUT"),
#{status_code := 415} =
sr_test_utils:api_call(post, "/elements", NoHeaders, <<>>),
#{status_code := 415} =
sr_test_utils:api_call(put, "/elements/noheaders", NoHeaders, <<>>),
ct:comment("content-type must be JSON for POST and PUT"),
#{status_code := 415} =
sr_test_utils:api_call(post, "/elements", InvalidHeaders, <<>>),
#{status_code := 415} =
sr_test_utils:api_call(put, "/elements/badtype", InvalidHeaders, <<>>),
ct:comment("Agent must accept json for POST, GET and PUT"),
#{status_code := 406} =
sr_test_utils:api_call(post, "/elements", InvalidAccept, <<>>),
#{status_code := 406} =
sr_test_utils:api_call(get, "/elements", InvalidAccept, <<>>),
#{status_code := 406} =
sr_test_utils:api_call(put, "/elements/badaccept", InvalidAccept, <<>>),
#{status_code := 406} =
sr_test_utils:api_call(get, "/elements/badaccept", InvalidAccept, <<>>),
{comment, ""}.
-spec invalid_parameters(sr_test_utils:config()) -> {comment, string()}.
invalid_parameters(_Config) ->
Headers = #{<<"content-type">> => <<"application/json">>},
_ = sumo:persist(elements, sr_elements:new(1, <<"val">>)),
ct:comment("Empty or broken parameters are reported"),
#{status_code := 400} =
sr_test_utils:api_call(post, "/elements", Headers, <<>>),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/nobody", Headers, <<>>),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/1", Headers, <<>>),
#{status_code := 400} =
sr_test_utils:api_call(patch, "/elements/1", Headers, <<>>),
#{status_code := 400} =
sr_test_utils:api_call(post, "/elements", Headers, <<"{">>),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/broken", Headers, <<"{">>),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/1", Headers, <<"{">>),
#{status_code := 400} =
sr_test_utils:api_call(patch, "/elements/1", Headers, <<"{">>),
ct:comment("Missing parameters are reported"),
None = #{},
#{status_code := 400} =
sr_test_utils:api_call(post, "/elements", Headers, None),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/none", Headers, None),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/1", Headers, None),
#{status_code := 400} =
sr_test_utils:api_call(patch, "/elements/1", Headers, None),
NoVal = #{key => <<"noval">>},
#{status_code := 400} =
sr_test_utils:api_call(post, "/elements", Headers, NoVal),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/noval", Headers, NoVal),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/1", Headers, NoVal),
#{status_code := 400} =
sr_test_utils:api_call(patch, "/elements/1", Headers, NoVal),
{comment, ""}.
-spec not_found(sr_test_utils:config()) -> {comment, string()}.
not_found(_Config) ->
ct:comment("Not existing element is not found"),
#{status_code := 404} = sr_test_utils:api_call(get, "/elements/notfound"),
#{status_code := 404} = sr_test_utils:api_call(patch, "/elements/notfound"),
#{status_code := 404} = sr_test_utils:api_call(delete, "/elements/notfound"),
{comment, ""}.
-spec binary_id_conversion(sr_test_utils:config()) -> {comment, string()}.
binary_id_conversion(_Config) ->
ct:comment("Different types of ids"),
1 = sr_single_entity_handler:id_from_binding_internal(<<"1">>, integer),
-1 = sr_single_entity_handler:id_from_binding_internal(<<"one">>, integer),
<<"binary">> =
sr_single_entity_handler:id_from_binding_internal(<<"binary">>, binary),
"string" =
sr_single_entity_handler:id_from_binding_internal(<<"string">>, string),
{comment, ""}.
-spec location(sr_test_utils:config()) -> {comment, string()}.
location(_Config) ->
Headers = #{<<"content-type">> => <<"application/json; charset=utf-8">>},
ct:comment("Element 1 is created"),
Key = <<"element1">>,
#{status_code := 201, headers := ResponseHeaders} =
sr_test_utils:api_call(
post, "/elements", Headers,
#{ key => <<"element1">>
, value => <<"val1">>
}),
ct:comment("and its location header is set correctly"),
Location = proplists:get_value(<<"location">>, ResponseHeaders),
Location = iolist_to_binary(["/elements/", Key]),
{comment, ""}.
| null | https://raw.githubusercontent.com/inaka/sumo_rest/19a3685ab477222738ac27b72e39346cbad9463d/test/sr_elements_SUITE.erl | erlang | -module(sr_elements_SUITE).
-include_lib("mixer/include/mixer.hrl").
-mixin([{ sr_test_utils
, [ init_per_suite/1
, end_per_suite/1
]
}]).
-export([ all/0
, init_per_testcase/2
, end_per_testcase/2
]).
-export([ success_scenario/1
, duplicated_key/1
, invalid_headers/1
, invalid_parameters/1
, not_found/1
, location/1
, binary_id_conversion/1
]).
-spec all() -> [atom()].
all() -> sr_test_utils:all(?MODULE).
-spec init_per_testcase(atom(), sr_test_utils:config()) ->
sr_test_utils:config().
init_per_testcase(_, Config) ->
_ = sumo:delete_all(elements),
Config.
-spec end_per_testcase(atom(), sr_test_utils:config()) ->
sr_test_utils:config().
end_per_testcase(_, Config) ->
Config.
-spec success_scenario(sr_test_utils:config()) -> {comment, string()}.
success_scenario(_Config) ->
Headers = #{<<"content-type">> => <<"application/json; charset=utf-8">>},
ct:comment("There are no elements"),
#{status_code := 200, body := Body0} =
sr_test_utils:api_call(get, "/elements"),
[] = sr_json:decode(Body0),
ct:comment("Element 1 is created"),
#{status_code := 201, body := Body1} =
sr_test_utils:api_call(
post, "/elements", Headers,
#{ key => 1
, value => <<"val1">>
}),
#{ <<"key">> := 1
, <<"created_at">> := CreatedAt
, <<"updated_at">> := CreatedAt
} = Element1 = sr_json:decode(Body1),
ct:comment("Find element using query string"),
#{status_code := 200, body := BodyA} =
sr_test_utils:api_call(get, "/elements?value=val1"),
[#{ <<"created_at">> := CreatedAt
, <<"key">> := 1
, <<"updated_at">> := CreatedAt
, <<"value">> := <<"val1">>
}] = sr_json:decode(BodyA),
ct:comment("Find elements non existent value using query string"),
#{status_code := 200, body := BodyB} =
sr_test_utils:api_call(get, "/elements?novalue=noval"),
[Element1] = sr_json:decode(BodyB),
ct:comment("Element 1 is modified"),
#{status_code := 422, body := Body01} =
sr_test_utils:api_call(
put, "/elements", #{<<"content-type">> => <<"application/json">>},
#{ key => 1
, value => <<"val1">>
}),
#{ <<"error">> := <<"Duplicated entity">>
} = sr_json:decode(Body01),
ct:comment("There is one element now"),
#{status_code := 200, body := Body2} =
sr_test_utils:api_call(get, "/elements"),
[Element1] = sr_json:decode(Body2),
ct:comment("And we can fetch it"),
#{status_code := 200, body := Body21} =
sr_test_utils:api_call(get, "/elements/1"),
Element1 = sr_json:decode(Body21),
ct:comment("The element value can be changed"),
#{status_code := 200, body := Body3} =
sr_test_utils:api_call(
put, "/elements/1", Headers,
#{ key => 1
, value => <<"newval3">>
}),
#{ <<"key">> := 1
, <<"value">> := <<"newval3">>
, <<"created_at">> := CreatedAt
, <<"updated_at">> := UpdatedAt
} = Element3 = sr_json:decode(Body3),
true = UpdatedAt >= CreatedAt,
ct:comment("Still just one element"),
#{status_code := 200, body := Body4} =
sr_test_utils:api_call(get, "/elements"),
[Element3] = sr_json:decode(Body4),
ct:comment("The element value can be changed by PATCH"),
#{status_code := 200, body := Body5} =
sr_test_utils:api_call(
patch, "/elements/1", Headers, #{value => <<"newval5">>}),
#{ <<"key">> := 1
, <<"value">> := <<"newval5">>
, <<"created_at">> := CreatedAt
, <<"updated_at">> := UpdatedAt5
} = Element5 = sr_json:decode(Body5),
true = UpdatedAt5 >= CreatedAt,
ct:comment("Still just one element"),
#{status_code := 200, body := Body6} =
sr_test_utils:api_call(get, "/elements"),
[Element5] = sr_json:decode(Body6),
ct:comment("Elements can be created by PUT"),
#{status_code := 201, body := Body7} =
sr_test_utils:api_call(
put, "/elements/2", Headers,
#{ key => 2
, value => <<"val2">>
}),
#{ <<"key">> := 2
, <<"value">> := <<"val2">>
, <<"created_at">> := CreatedAt7
, <<"updated_at">> := CreatedAt7
} = Element7 = sr_json:decode(Body7),
true = CreatedAt7 >= CreatedAt,
ct:comment("There are two elements now"),
#{status_code := 200, body := Body8} =
sr_test_utils:api_call(get, "/elements"),
[Element7] = sr_json:decode(Body8) -- [Element5],
ct:comment("Element1 is deleted"),
#{status_code := 204} = sr_test_utils:api_call(delete, "/elements/1"),
ct:comment("One element again"),
#{status_code := 200, body := Body9} =
sr_test_utils:api_call(get, "/elements"),
[Element7] = sr_json:decode(Body9),
ct:comment("DELETE is not idempotent"),
#{status_code := 204} = sr_test_utils:api_call(delete, "/elements/2"),
#{status_code := 404} = sr_test_utils:api_call(delete, "/elements/2"),
ct:comment("There are no elements"),
#{status_code := 200, body := Body10} =
sr_test_utils:api_call(get, "/elements"),
[] = sr_json:decode(Body10),
{comment, ""}.
-spec duplicated_key(sr_test_utils:config()) -> {comment, string()}.
duplicated_key(_Config) ->
Headers = #{<<"content-type">> => <<"application/json; charset=utf-8">>},
Body =
#{ key => <<"element1">>
, value => <<"val1">>
},
ct:comment("Element 1 is created"),
#{status_code := 201} =
sr_test_utils:api_call(post, "/elements", Headers, Body),
ct:comment("Element 1 can't be created again"),
#{status_code := 422} =
sr_test_utils:api_call(post, "/elements", Headers, Body),
{comment, ""}.
-spec invalid_headers(sr_test_utils:config()) -> {comment, string()}.
invalid_headers(_Config) ->
NoHeaders = #{},
InvalidHeaders = #{<<"content-type">> => <<"text/plain">>},
InvalidAccept = #{ <<"content-type">> => <<"application/json">>
, <<"accept">> => <<"text/html">>
},
ct:comment("content-type must be provided for POST and PUT"),
#{status_code := 415} =
sr_test_utils:api_call(post, "/elements", NoHeaders, <<>>),
#{status_code := 415} =
sr_test_utils:api_call(put, "/elements/noheaders", NoHeaders, <<>>),
ct:comment("content-type must be JSON for POST and PUT"),
#{status_code := 415} =
sr_test_utils:api_call(post, "/elements", InvalidHeaders, <<>>),
#{status_code := 415} =
sr_test_utils:api_call(put, "/elements/badtype", InvalidHeaders, <<>>),
ct:comment("Agent must accept json for POST, GET and PUT"),
#{status_code := 406} =
sr_test_utils:api_call(post, "/elements", InvalidAccept, <<>>),
#{status_code := 406} =
sr_test_utils:api_call(get, "/elements", InvalidAccept, <<>>),
#{status_code := 406} =
sr_test_utils:api_call(put, "/elements/badaccept", InvalidAccept, <<>>),
#{status_code := 406} =
sr_test_utils:api_call(get, "/elements/badaccept", InvalidAccept, <<>>),
{comment, ""}.
-spec invalid_parameters(sr_test_utils:config()) -> {comment, string()}.
invalid_parameters(_Config) ->
Headers = #{<<"content-type">> => <<"application/json">>},
_ = sumo:persist(elements, sr_elements:new(1, <<"val">>)),
ct:comment("Empty or broken parameters are reported"),
#{status_code := 400} =
sr_test_utils:api_call(post, "/elements", Headers, <<>>),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/nobody", Headers, <<>>),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/1", Headers, <<>>),
#{status_code := 400} =
sr_test_utils:api_call(patch, "/elements/1", Headers, <<>>),
#{status_code := 400} =
sr_test_utils:api_call(post, "/elements", Headers, <<"{">>),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/broken", Headers, <<"{">>),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/1", Headers, <<"{">>),
#{status_code := 400} =
sr_test_utils:api_call(patch, "/elements/1", Headers, <<"{">>),
ct:comment("Missing parameters are reported"),
None = #{},
#{status_code := 400} =
sr_test_utils:api_call(post, "/elements", Headers, None),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/none", Headers, None),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/1", Headers, None),
#{status_code := 400} =
sr_test_utils:api_call(patch, "/elements/1", Headers, None),
NoVal = #{key => <<"noval">>},
#{status_code := 400} =
sr_test_utils:api_call(post, "/elements", Headers, NoVal),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/noval", Headers, NoVal),
#{status_code := 400} =
sr_test_utils:api_call(put, "/elements/1", Headers, NoVal),
#{status_code := 400} =
sr_test_utils:api_call(patch, "/elements/1", Headers, NoVal),
{comment, ""}.
-spec not_found(sr_test_utils:config()) -> {comment, string()}.
not_found(_Config) ->
ct:comment("Not existing element is not found"),
#{status_code := 404} = sr_test_utils:api_call(get, "/elements/notfound"),
#{status_code := 404} = sr_test_utils:api_call(patch, "/elements/notfound"),
#{status_code := 404} = sr_test_utils:api_call(delete, "/elements/notfound"),
{comment, ""}.
-spec binary_id_conversion(sr_test_utils:config()) -> {comment, string()}.
binary_id_conversion(_Config) ->
ct:comment("Different types of ids"),
1 = sr_single_entity_handler:id_from_binding_internal(<<"1">>, integer),
-1 = sr_single_entity_handler:id_from_binding_internal(<<"one">>, integer),
<<"binary">> =
sr_single_entity_handler:id_from_binding_internal(<<"binary">>, binary),
"string" =
sr_single_entity_handler:id_from_binding_internal(<<"string">>, string),
{comment, ""}.
-spec location(sr_test_utils:config()) -> {comment, string()}.
location(_Config) ->
Headers = #{<<"content-type">> => <<"application/json; charset=utf-8">>},
ct:comment("Element 1 is created"),
Key = <<"element1">>,
#{status_code := 201, headers := ResponseHeaders} =
sr_test_utils:api_call(
post, "/elements", Headers,
#{ key => <<"element1">>
, value => <<"val1">>
}),
ct:comment("and its location header is set correctly"),
Location = proplists:get_value(<<"location">>, ResponseHeaders),
Location = iolist_to_binary(["/elements/", Key]),
{comment, ""}.
| |
69581126e911bf08b4eabfa802871820109caabe20d8255b8a429ac7a544987a | kongo2002/statser | statser_util.erl | Copyright 2017 - 2018
%
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(statser_util).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-include("statser.hrl").
-compile({no_auto_import, [floor/1]}).
-export([ceiling/1,
floor/1,
to_number/1,
number_to_bin/1,
parse_unit/1,
parse_unit/2,
seconds/0,
epoch_seconds_to_datetime/1,
split_metric/1]).
-spec number_to_bin(number()) -> binary().
number_to_bin(Num) when is_integer(Num) ->
list_to_binary(integer_to_list(Num));
number_to_bin(Num) ->
list_to_binary(io_lib:format("~.2f", [Num])).
-spec to_number(binary()) -> {ok, number()} | error.
to_number(Binary) ->
List = binary_to_list(Binary),
case string:to_float(List) of
{error, no_float} ->
case string:to_integer(List) of
{error, _} -> error;
{Result, _} -> {ok, Result}
end;
{Result, _} -> {ok, Result}
end.
-spec floor(number()) -> integer().
floor(X) when X < 0 ->
Truncated = trunc(X),
case X - Truncated == 0 of
true -> Truncated;
false -> Truncated - 1
end;
floor(X) ->
trunc(X).
-spec ceiling(number()) -> integer().
ceiling(X) when X < 0 ->
trunc(X);
ceiling(X) ->
Truncated = trunc(X),
case X - Truncated == 0 of
true -> Truncated;
false -> Truncated + 1
end.
-spec parse_unit(binary()) -> integer() | error.
parse_unit(Value) ->
List = binary_to_list(Value),
case string:to_integer(List) of
{error, _} -> error;
{Val, Unit} -> parse_unit(Val, Unit)
end.
-spec parse_unit(integer(), unicode:chardata()) -> integer() | error.
parse_unit(Value, [$s | _]) -> Value;
parse_unit(Value, [$S | _]) -> Value;
parse_unit(Value, "min" ++ _) -> Value * 60;
parse_unit(Value, [$h | _]) -> Value * 3600;
parse_unit(Value, [$d | _]) -> Value * 86400;
parse_unit(Value, [$w | _]) -> Value * 604800;
parse_unit(Value, "mon" ++ _) -> Value * 2592000;
parse_unit(Value, [$y | _]) -> Value * 31536000;
parse_unit(_, _) -> error.
-spec seconds() -> integer().
seconds() ->
erlang:system_time(second).
-spec epoch_seconds_to_datetime(integer()) -> string().
epoch_seconds_to_datetime(Seconds) ->
calendar : datetime_to_gregorian_seconds({{1970 , 1 , 1 } , { 0 , 0 , 0 } )
EpochSeconds = 62167219200,
{{Year, Month, Day}, {Hour, Minute, Second}} = calendar:gregorian_seconds_to_datetime(EpochSeconds + Seconds),
lists:flatten(io_lib:format("~4..0w-~2..0w-~2..0wT~2..0w:~2..0w:~2..0w",
[Year, Month, Day, Hour, Minute, Second])).
-spec split_metric(binary()) -> [binary()].
split_metric(Metric) ->
binary:split(Metric, <<".">>, [global, trim_all]).
%%
%% TESTS
%%
-ifdef(TEST).
number_to_bin_test_() ->
[?_assertEqual(<<"325">>, number_to_bin(325)),
?_assertEqual(<<"-35.21">>, number_to_bin(-35.21))
].
parse_unit_test_() ->
[?_assertEqual(error, parse_unit(100, "")),
?_assertEqual(error, parse_unit(100, "m")),
?_assertEqual(100, parse_unit(100, "s")),
?_assertEqual(180, parse_unit(3, "min")),
?_assertEqual(2 * 86400 * 7, parse_unit(2, "w"))
].
floor_test_() ->
[?_assertEqual(5, floor(5.0)),
?_assertEqual(5, floor(5)),
?_assertEqual(5, floor(5.5)),
?_assertEqual(5, floor(5.9)),
?_assertEqual(-6, floor(-6)),
?_assertEqual(-6, floor(-5.1)),
?_assertEqual(-6, floor(-5.9))
].
ceiling_test_() ->
[?_assertEqual(5, ceiling(5.0)),
?_assertEqual(5, ceiling(5)),
?_assertEqual(6, ceiling(5.5)),
?_assertEqual(6, ceiling(5.9)),
?_assertEqual(-5, ceiling(-5)),
?_assertEqual(-5, ceiling(-5.1)),
?_assertEqual(-5, ceiling(-5.9))
].
epoch_seconds_to_datetime_test_() ->
[?_assertEqual("1970-01-01T00:00:00", epoch_seconds_to_datetime(0)),
?_assertEqual("1970-01-01T01:00:00", epoch_seconds_to_datetime(3600)),
?_assertEqual("1970-01-01T01:01:01", epoch_seconds_to_datetime(3661))
].
-endif.
| null | https://raw.githubusercontent.com/kongo2002/statser/1cb0498f56c97d8a010b979c5163dd2750064e98/src/statser_util.erl | erlang |
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.
TESTS
| Copyright 2017 - 2018
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(statser_util).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-include("statser.hrl").
-compile({no_auto_import, [floor/1]}).
-export([ceiling/1,
floor/1,
to_number/1,
number_to_bin/1,
parse_unit/1,
parse_unit/2,
seconds/0,
epoch_seconds_to_datetime/1,
split_metric/1]).
-spec number_to_bin(number()) -> binary().
number_to_bin(Num) when is_integer(Num) ->
list_to_binary(integer_to_list(Num));
number_to_bin(Num) ->
list_to_binary(io_lib:format("~.2f", [Num])).
-spec to_number(binary()) -> {ok, number()} | error.
to_number(Binary) ->
List = binary_to_list(Binary),
case string:to_float(List) of
{error, no_float} ->
case string:to_integer(List) of
{error, _} -> error;
{Result, _} -> {ok, Result}
end;
{Result, _} -> {ok, Result}
end.
-spec floor(number()) -> integer().
floor(X) when X < 0 ->
Truncated = trunc(X),
case X - Truncated == 0 of
true -> Truncated;
false -> Truncated - 1
end;
floor(X) ->
trunc(X).
-spec ceiling(number()) -> integer().
ceiling(X) when X < 0 ->
trunc(X);
ceiling(X) ->
Truncated = trunc(X),
case X - Truncated == 0 of
true -> Truncated;
false -> Truncated + 1
end.
-spec parse_unit(binary()) -> integer() | error.
parse_unit(Value) ->
List = binary_to_list(Value),
case string:to_integer(List) of
{error, _} -> error;
{Val, Unit} -> parse_unit(Val, Unit)
end.
-spec parse_unit(integer(), unicode:chardata()) -> integer() | error.
parse_unit(Value, [$s | _]) -> Value;
parse_unit(Value, [$S | _]) -> Value;
parse_unit(Value, "min" ++ _) -> Value * 60;
parse_unit(Value, [$h | _]) -> Value * 3600;
parse_unit(Value, [$d | _]) -> Value * 86400;
parse_unit(Value, [$w | _]) -> Value * 604800;
parse_unit(Value, "mon" ++ _) -> Value * 2592000;
parse_unit(Value, [$y | _]) -> Value * 31536000;
parse_unit(_, _) -> error.
-spec seconds() -> integer().
seconds() ->
erlang:system_time(second).
-spec epoch_seconds_to_datetime(integer()) -> string().
epoch_seconds_to_datetime(Seconds) ->
calendar : datetime_to_gregorian_seconds({{1970 , 1 , 1 } , { 0 , 0 , 0 } )
EpochSeconds = 62167219200,
{{Year, Month, Day}, {Hour, Minute, Second}} = calendar:gregorian_seconds_to_datetime(EpochSeconds + Seconds),
lists:flatten(io_lib:format("~4..0w-~2..0w-~2..0wT~2..0w:~2..0w:~2..0w",
[Year, Month, Day, Hour, Minute, Second])).
-spec split_metric(binary()) -> [binary()].
split_metric(Metric) ->
binary:split(Metric, <<".">>, [global, trim_all]).
-ifdef(TEST).
number_to_bin_test_() ->
[?_assertEqual(<<"325">>, number_to_bin(325)),
?_assertEqual(<<"-35.21">>, number_to_bin(-35.21))
].
parse_unit_test_() ->
[?_assertEqual(error, parse_unit(100, "")),
?_assertEqual(error, parse_unit(100, "m")),
?_assertEqual(100, parse_unit(100, "s")),
?_assertEqual(180, parse_unit(3, "min")),
?_assertEqual(2 * 86400 * 7, parse_unit(2, "w"))
].
floor_test_() ->
[?_assertEqual(5, floor(5.0)),
?_assertEqual(5, floor(5)),
?_assertEqual(5, floor(5.5)),
?_assertEqual(5, floor(5.9)),
?_assertEqual(-6, floor(-6)),
?_assertEqual(-6, floor(-5.1)),
?_assertEqual(-6, floor(-5.9))
].
ceiling_test_() ->
[?_assertEqual(5, ceiling(5.0)),
?_assertEqual(5, ceiling(5)),
?_assertEqual(6, ceiling(5.5)),
?_assertEqual(6, ceiling(5.9)),
?_assertEqual(-5, ceiling(-5)),
?_assertEqual(-5, ceiling(-5.1)),
?_assertEqual(-5, ceiling(-5.9))
].
epoch_seconds_to_datetime_test_() ->
[?_assertEqual("1970-01-01T00:00:00", epoch_seconds_to_datetime(0)),
?_assertEqual("1970-01-01T01:00:00", epoch_seconds_to_datetime(3600)),
?_assertEqual("1970-01-01T01:01:01", epoch_seconds_to_datetime(3661))
].
-endif.
|
869d85d7afd4dfc582d1afbd8ac4cb64373d8180dee286efde645c331babb182 | circuithub/rel8 | ReadShow.hs | {-# language ScopedTypeVariables #-}
# language StandaloneKindSignatures #
# language TypeApplications #
# language ViewPatterns #
module Rel8.Type.ReadShow ( ReadShow(..) ) where
-- base
import Data.Kind ( Type )
import Data.Proxy ( Proxy( Proxy ) )
import Data.Typeable ( Typeable, typeRep )
import Prelude
import Text.Read ( readMaybe )
-- rel8
import Rel8.Type ( DBType( typeInformation ) )
import Rel8.Type.Information ( parseTypeInformation )
-- text
import qualified Data.Text as Text
| A deriving - via helper type for column types that store a Haskell value
using a 's ' Read ' and ' Show ' type classes .
type ReadShow :: Type -> Type
newtype ReadShow a = ReadShow { fromReadShow :: a }
instance (Read a, Show a, Typeable a) => DBType (ReadShow a) where
typeInformation = parseTypeInformation parser printer typeInformation
where
parser (Text.unpack -> t) = case readMaybe t of
Just ok -> Right $ ReadShow ok
Nothing -> Left $ "Could not read " <> t <> " as a " <> show (typeRep (Proxy @a))
printer = Text.pack . show . fromReadShow
| null | https://raw.githubusercontent.com/circuithub/rel8/2a25126e214c1171c3d0c2d12d5a14ca831a266c/src/Rel8/Type/ReadShow.hs | haskell | # language ScopedTypeVariables #
base
rel8
text | # language StandaloneKindSignatures #
# language TypeApplications #
# language ViewPatterns #
module Rel8.Type.ReadShow ( ReadShow(..) ) where
import Data.Kind ( Type )
import Data.Proxy ( Proxy( Proxy ) )
import Data.Typeable ( Typeable, typeRep )
import Prelude
import Text.Read ( readMaybe )
import Rel8.Type ( DBType( typeInformation ) )
import Rel8.Type.Information ( parseTypeInformation )
import qualified Data.Text as Text
| A deriving - via helper type for column types that store a Haskell value
using a 's ' Read ' and ' Show ' type classes .
type ReadShow :: Type -> Type
newtype ReadShow a = ReadShow { fromReadShow :: a }
instance (Read a, Show a, Typeable a) => DBType (ReadShow a) where
typeInformation = parseTypeInformation parser printer typeInformation
where
parser (Text.unpack -> t) = case readMaybe t of
Just ok -> Right $ ReadShow ok
Nothing -> Left $ "Could not read " <> t <> " as a " <> show (typeRep (Proxy @a))
printer = Text.pack . show . fromReadShow
|
b7ef9eec415b97510a70193faf00e904c30274ae5052442af4bb684cffd6c27d | rems-project/cerberus | rt_ocaml.ml | Created by 2017 - 03 - 10
open Util
open Cerb_frontend
module M = Impl_mem
module C = Ctype
(* Undefined Behaviour *)
exception Undefined of string
exception Error of string
let (>>=) = M.bind
let return = M.return
(* Keep track of the last memory operation, for error display *)
type memop = Store | Load | Create | Alloc | None
let last_memop = ref None
let show_memop = function
| Store -> "store"
| Load -> "load"
| Create -> "create"
| Alloc -> "alloc"
| None -> raise (Error "unknown last memop")
(* Runtime flags *)
let batch =
try ignore (Sys.getenv "CERB_BATCH"); true
with _ -> false
(* stdout if in batch mode *)
let stdout = ref ""
let position fname lnum bol cnum = {
Lexing.pos_fname = fname;
Lexing.pos_lnum = lnum;
Lexing.pos_bol = bol;
Lexing.pos_cnum = cnum;
}
let unknown = Location_ocaml.unknown
(* TODO: digest is wrong *)
let sym (n, s) = Symbol.Symbol ("", n, Some s)
let cabsid pos id =
let mkloc x = x in
Symbol.Identifier (mkloc pos, id)
(* Helper Types *)
let char_t = C.Basic (C.Integer C.Char)
let bool_t = C.Basic (C.Integer C.Bool)
let schar_t = C.Basic (C.Integer (C.Signed C.Ichar))
let uchar_t = C.Basic (C.Integer (C.Unsigned C.Ichar))
let int_t = C.Basic (C.Integer (C.Signed C.Int_))
let uint_t = C.Basic (C.Integer (C.Unsigned C.Int_))
let short_t = C.Basic (C.Integer (C.Signed C.Short))
let ushort_t = C.Basic (C.Integer (C.Unsigned C.Short))
let long_t = C.Basic (C.Integer (C.Signed C.Long))
let ulong_t = C.Basic (C.Integer (C.Unsigned C.Long))
let longlong_t = C.Basic (C.Integer (C.Signed C.LongLong))
let ulonglong_t = C.Basic (C.Integer (C.Unsigned C.LongLong))
let size_t = C.Basic (C.Integer C.Size_t)
let ptrdiff_t = C.Basic (C.Integer C.Ptrdiff_t)
let float_t = C.Basic (C.Floating (C.RealFloating C.Float))
let double_t = C.Basic (C.Floating (C.RealFloating C.Double))
let longdouble_t = C.Basic (C.Floating (C.RealFloating C.LongDouble))
let are_compatible _ _ = false
(* Non deterministic choice *)
let nd n xs =
Random.self_init ();
Random.int n |> List.nth xs
(* IV wraps *)
let ivctor memf errmsg = function
| C.Basic (C.Integer it) -> memf it
| _ -> raise (Error errmsg)
let ivmin = ivctor M.min_ival "ivmin"
let ivmax = ivctor M.max_ival "ivmax"
let ivcompl = ivctor M.bitwise_complement_ival "ivcompl"
let ivand = ivctor M.bitwise_and_ival "ivand"
let ivor = ivctor M.bitwise_or_ival "ivor"
let ivxor = ivctor M.bitwise_xor_ival "ivxor"
let fvfromint = M.fvfromint
let ivfromfloat (cty, x) =
match cty with
| C.Basic (C.Integer it) -> M.ivfromfloat it x
| _ -> raise (Error "ivfromfloat")
let intcast_ptrval cty itarget x =
match itarget with
| C.Basic (C.Integer it) -> M.intcast_ptrval cty it x
| _ -> raise (Error "intcast_ptrval")
(* Ail types *)
let ail_qualifier (c, r, v) =
{ C.const = c;
C.restrict = r;
C.volatile = v
}
let is_scalar ty =
AilTypesAux.is_scalar (Core_aux.unproj_ctype ty)
let is_integer ty =
AilTypesAux.is_integer (Core_aux.unproj_ctype ty)
let is_signed ty =
AilTypesAux.is_signed_integer_type (Core_aux.unproj_ctype ty)
let is_unsigned ty =
AilTypesAux.is_unsigned_integer_type (Core_aux.unproj_ctype ty)
(* Loaded - Specified and unspecified values *)
type 'a loaded =
| Specified of 'a
| Unspecified of C.ctype0
let specified x = Specified x
let unspecified x = Unspecified x
let case_loaded f g = function
| Specified x -> f x
| Unspecified cty -> g cty
exception Label of string * (M.integer_value) loaded
(* Cast from memory values *)
let get_integer m =
let terr _ _ = raise (Error "Type mismatch, expecting integer values.") in
M.case_mem_value m unspecified terr (fun _ -> specified)
terr terr (terr()) terr terr
let get_float m =
let terr _ _ = raise (Error "Type mismatch, expecting integer values.") in
M.case_mem_value m unspecified terr terr (fun _ -> specified)
terr (terr()) terr terr
let get_pointer m =
let terr _ _ = raise (Error "Type mismatch, expecting pointer values.") in
M.case_mem_value m unspecified terr terr terr (fun _ p -> specified p)
(terr()) terr terr
let get_array m =
let terr _ _ = raise (Error "Type mismatch, expecting array.") in
M.case_mem_value m unspecified terr terr terr terr
specified terr terr
let get_struct m =
let terr _ _ = raise (Error "Type mismatch, expecting struct.") in
M.case_mem_value m unspecified terr terr terr terr (terr())
(fun _ -> specified) terr
let get_union m =
let terr _ _ = raise (Error "Type mismatch, expecting union.") in
M.case_mem_value m unspecified terr terr terr terr (terr())
terr (fun _ cid m -> Specified (cid, m))
(* Cast to memory values *)
let case_loaded_mval f = case_loaded f M.unspecified_mval
let mk_int s = M.integer_ival (Nat_big_num.of_string s)
let mk_float s = M.str_fval s
let mk_array xs = (*M.array_mval*) (List.map (case_loaded_mval id) xs)
let mk_pointer alloc_id addr =
M.concrete_ptrval (Nat_big_num.of_string alloc_id)
(Nat_big_num.of_string addr)
let mk_null cty = M.null_ptrval cty
let mk_null_void = mk_null C.Void0
(* Binary operations wrap *)
let add = M.op_ival Mem_common.IntAdd
let sub = M.op_ival Mem_common.IntSub
let mul = M.op_ival Mem_common.IntMul
let div = M.op_ival Mem_common.IntDiv
let remt = M.op_ival Mem_common.IntRem_t
let remf = M.op_ival Mem_common.IntRem_f
let exp = M.op_ival Mem_common.IntExp
let addf = M.op_fval Mem_common.FloatAdd
let subf = M.op_fval Mem_common.FloatSub
let mulf = M.op_fval Mem_common.FloatMul
let divf = M.op_fval Mem_common.FloatDiv
let eq n m = Option.get (M.eq_ival (Some M.initial_mem_state) n m)
let lt n m = Option.get (M.lt_ival (Some M.initial_mem_state) n m)
let gt n m = Option.get (M.lt_ival (Some M.initial_mem_state) m n)
let le n m = Option.get (M.le_ival (Some M.initial_mem_state) n m)
let ge n m = Option.get (M.le_ival (Some M.initial_mem_state) m n)
let valid_for_deref_ptrval p = return @@ M.validForDeref_ptrval p
let memcmp p q r = return @@ M.memcmp p q r
let memcpy p q r = return @@ M.memcpy p q r
let realloc al p size = return @@ M.realloc 0 al p size
(* Memory actions wrap *)
let ptr_well_aligned = M.isWellAligned_ptrval
let create pre al ty x_opt =
last_memop := Create;
M.allocate_object 0 pre al ty
(Option.case (fun x -> Some (case_loaded_mval id x))
(fun () -> None) x_opt)
let alloc pre al n =
last_memop := Alloc;
M.allocate_region 0 pre al n
let load cty ret e =
last_memop := Load;
M.load Location_ocaml.unknown cty e >>= return % ret % snd
let load_integer ity =
load (C.Basic (C.Integer ity)) get_integer
let load_float fty =
load (C.Basic (C.Floating fty)) get_float
let load_pointer q cty =
load (C.Pointer0 (q, cty)) get_pointer
let load_array q cty size =
load (C.Array0 (cty, size)) get_array
let load_struct s =
load (C.Struct0 s) get_struct
let load_union s =
load (C.Union0 s) get_union
let store f ty b e1 e2 =
last_memop := Store;
M.store Location_ocaml.unknown ty b e1 @@ case_loaded_mval f e2
let store_integer ity =
store (M.integer_value_mval ity) (C.Basic (C.Integer ity))
let store_pointer q cty =
store (M.pointer_mval cty) (C.Pointer0 (q, cty))
let store_struct s =
store (M.struct_mval s) (C.Struct0 s)
let store_union s cid =
store (M.union_mval s cid) (C.Union0 s)
let store_array_of conv cty size =
let array_mval e = M.array_mval (List.map (case_loaded_mval conv) e)
in store array_mval (C.Array0 (cty, size))
let store_array_of_int ity =
store_array_of (M.integer_value_mval ity) (C.Basic (C.Integer ity))
let store_array_of_float fty =
store_array_of (M.floating_value_mval fty) (C.Basic (C.Floating fty))
let store_array_of_ptr q cty =
store_array_of (M.pointer_mval cty) (C.Pointer0 (q, cty))
let store_array_of_struct s =
store_array_of (M.struct_mval s) (C.Struct0 s)
Printf wrap
let printf (conv : C.ctype0 -> M.integer_value -> M.integer_value)
(xs:M.integer_value list)
(args:(C.ctype0 * M.pointer_value) list) =
let encode ival = match Mem_aux.integerFromIntegerValue ival with
| Some n -> Decode_ocaml.encode_character_constant n
| None -> Debug_ocaml.error
"Printf: one of the element of the format array was invalid"
in
let eval_conv cty x =
let terr _ _ = raise (Error "Rt_ocaml.printf: expecting an integer") in
let n = M.case_mem_value x (terr()) terr (fun _ -> conv cty)
terr terr (terr()) terr terr
in Nondeterminism.nd_return (Either.Right (Undefined.Defined
(Core.Vloaded (Core.LVspecified (Core.OVinteger n)))))
in
Formatted.printf eval_conv (List.rev (List.map encode xs)) args
>>= begin function
| Either.Right (Undefined.Defined xs) ->
let n = List.length xs in
let output = String.init n (List.nth xs) in
if batch then stdout := !stdout ^ String.escaped output
else print_string output;
return (Specified (M.integer_ival (Nat_big_num.of_int n)))
(*return (M.integer_ival (Nat_big_num.of_int n))*)
| Either.Right (Undefined.Undef (_, xs) ) ->
raise (Error (String.concat ","
(List.map Undefined.stringFromUndefined_behaviour xs)))
| Either.Right (Undefined.Error (_, m) ) -> raise (Error m)
| Either.Left z -> raise (Error (Pp_errors.to_string z))
end
let sprintf _ = failwith "No support for sprintf"
let snprintf _ = failwith "No support for snprintf"
(* Exit *)
exception Exit of (M.integer_value loaded)
let print_batch i res =
Printf.printf "Defined {value: \"%s\", stdout: \"%s\", stderr: \"\", blocked: \"false\"}\n" res !stdout
let print_err_batch e =
let err = match e with
| Mem_common . MerrUnitialised str - > " MerrUnitialised \ " " ^ ( str ^ " \ " " )
| Mem_common.MerrInternal str -> "MerrInternal \"" ^ (str ^ "\"")
| Mem_common.MerrOther str -> "MerrOther \"" ^ (str ^ "\"")
| Mem_common . MerrReadFromDead - > " MerrReadFromDead "
| Mem_common.MerrWIP str -> "Memory WIP: " ^ str
| _ -> "memory error"
in
Printf.sprintf "Killed {msg: memory layout error (%s seq) ==> %s}" (show_memop !last_memop) err
let string_of_specified n =
Printf.sprintf "Specified(%s)" (Nat_big_num.to_string n)
let string_of_unspec cty =
Printf.sprintf "Unspecified(\"%s\")" (String_core_ctype.string_of_ctype cty)
let dummy_file =
let cmp = Symbol.instance_Basic_classes_Ord_Symbol_sym_dict.Lem_basic_classes.compare_method in
let impl_cmp = Implementation_.instance_Basic_classes_SetType_Implementation__implementation_constant_dict.Lem_pervasives.setElemCompare_method in
Core.{
main = None;
tagDefs = Pmap.empty cmp;
stdlib = Pmap.empty cmp;
globs = [];
funs = Pmap.empty cmp;
impl = Pmap.empty impl_cmp;
funinfo = Pmap.empty cmp;
extern = Pmap.empty compare;
}
let quit f =
try
let initial_state = Driver.initial_driver_state dummy_file
Sibylfs.fs_initial_state in
match Smt2.runND Random Impl_mem.cs_module (Driver.liftMem (f (fun x -> raise (Exit x)) ())) initial_state with
| _ -> raise (Error "continuation not raised")
with
| Exit x ->
(match x with
| Specified x ->
let n = M.eval_integer_value x |> Option.get in
if batch then print_batch 0 (string_of_specified n);
exit (Nat_big_num.to_int n)
| Unspecified cty ->
if batch then print_batch 0 (string_of_unspec cty);
exit(-1)
)
(* Start *)
let set_global (f, x) =
f return () >>= fun y -> x := y; return ()
let init_globals glbs =
List.fold_left
(fun acc (f, x) -> acc >>= fun _ -> set_global (f, x))
(return ()) glbs
let create_tag_defs_map defs =
List.fold_left
(fun m (s, xs) -> Pmap.add s xs m)
(Pmap.empty Symbol.symbol_compare) defs
let run tags gls main =
begin fun cont args ->
Tags.set_tagDefs (create_tag_defs_map tags);
init_globals gls
>>= fun _ -> main cont args
end |> quit
(* Conv loaded mem value *)
let conv_int_mval it =
case_loaded_mval (M.integer_value_mval it)
let conv_float_mval ft =
case_loaded_mval (M.floating_value_mval ft)
let conv_ptr_mval cty =
case_loaded_mval (M.pointer_mval cty)
let conv_struct_mval s =
case_loaded_mval (M.struct_mval s)
| null | https://raw.githubusercontent.com/rems-project/cerberus/e0f817cebf331b1d9f741c1f82e129c93c99f33c/backend/ocaml/runtime/rt_ocaml.ml | ocaml | Undefined Behaviour
Keep track of the last memory operation, for error display
Runtime flags
stdout if in batch mode
TODO: digest is wrong
Helper Types
Non deterministic choice
IV wraps
Ail types
Loaded - Specified and unspecified values
Cast from memory values
Cast to memory values
M.array_mval
Binary operations wrap
Memory actions wrap
return (M.integer_ival (Nat_big_num.of_int n))
Exit
Start
Conv loaded mem value | Created by 2017 - 03 - 10
open Util
open Cerb_frontend
module M = Impl_mem
module C = Ctype
exception Undefined of string
exception Error of string
let (>>=) = M.bind
let return = M.return
type memop = Store | Load | Create | Alloc | None
let last_memop = ref None
let show_memop = function
| Store -> "store"
| Load -> "load"
| Create -> "create"
| Alloc -> "alloc"
| None -> raise (Error "unknown last memop")
let batch =
try ignore (Sys.getenv "CERB_BATCH"); true
with _ -> false
let stdout = ref ""
let position fname lnum bol cnum = {
Lexing.pos_fname = fname;
Lexing.pos_lnum = lnum;
Lexing.pos_bol = bol;
Lexing.pos_cnum = cnum;
}
let unknown = Location_ocaml.unknown
let sym (n, s) = Symbol.Symbol ("", n, Some s)
let cabsid pos id =
let mkloc x = x in
Symbol.Identifier (mkloc pos, id)
let char_t = C.Basic (C.Integer C.Char)
let bool_t = C.Basic (C.Integer C.Bool)
let schar_t = C.Basic (C.Integer (C.Signed C.Ichar))
let uchar_t = C.Basic (C.Integer (C.Unsigned C.Ichar))
let int_t = C.Basic (C.Integer (C.Signed C.Int_))
let uint_t = C.Basic (C.Integer (C.Unsigned C.Int_))
let short_t = C.Basic (C.Integer (C.Signed C.Short))
let ushort_t = C.Basic (C.Integer (C.Unsigned C.Short))
let long_t = C.Basic (C.Integer (C.Signed C.Long))
let ulong_t = C.Basic (C.Integer (C.Unsigned C.Long))
let longlong_t = C.Basic (C.Integer (C.Signed C.LongLong))
let ulonglong_t = C.Basic (C.Integer (C.Unsigned C.LongLong))
let size_t = C.Basic (C.Integer C.Size_t)
let ptrdiff_t = C.Basic (C.Integer C.Ptrdiff_t)
let float_t = C.Basic (C.Floating (C.RealFloating C.Float))
let double_t = C.Basic (C.Floating (C.RealFloating C.Double))
let longdouble_t = C.Basic (C.Floating (C.RealFloating C.LongDouble))
let are_compatible _ _ = false
let nd n xs =
Random.self_init ();
Random.int n |> List.nth xs
let ivctor memf errmsg = function
| C.Basic (C.Integer it) -> memf it
| _ -> raise (Error errmsg)
let ivmin = ivctor M.min_ival "ivmin"
let ivmax = ivctor M.max_ival "ivmax"
let ivcompl = ivctor M.bitwise_complement_ival "ivcompl"
let ivand = ivctor M.bitwise_and_ival "ivand"
let ivor = ivctor M.bitwise_or_ival "ivor"
let ivxor = ivctor M.bitwise_xor_ival "ivxor"
let fvfromint = M.fvfromint
let ivfromfloat (cty, x) =
match cty with
| C.Basic (C.Integer it) -> M.ivfromfloat it x
| _ -> raise (Error "ivfromfloat")
let intcast_ptrval cty itarget x =
match itarget with
| C.Basic (C.Integer it) -> M.intcast_ptrval cty it x
| _ -> raise (Error "intcast_ptrval")
let ail_qualifier (c, r, v) =
{ C.const = c;
C.restrict = r;
C.volatile = v
}
let is_scalar ty =
AilTypesAux.is_scalar (Core_aux.unproj_ctype ty)
let is_integer ty =
AilTypesAux.is_integer (Core_aux.unproj_ctype ty)
let is_signed ty =
AilTypesAux.is_signed_integer_type (Core_aux.unproj_ctype ty)
let is_unsigned ty =
AilTypesAux.is_unsigned_integer_type (Core_aux.unproj_ctype ty)
type 'a loaded =
| Specified of 'a
| Unspecified of C.ctype0
let specified x = Specified x
let unspecified x = Unspecified x
let case_loaded f g = function
| Specified x -> f x
| Unspecified cty -> g cty
exception Label of string * (M.integer_value) loaded
let get_integer m =
let terr _ _ = raise (Error "Type mismatch, expecting integer values.") in
M.case_mem_value m unspecified terr (fun _ -> specified)
terr terr (terr()) terr terr
let get_float m =
let terr _ _ = raise (Error "Type mismatch, expecting integer values.") in
M.case_mem_value m unspecified terr terr (fun _ -> specified)
terr (terr()) terr terr
let get_pointer m =
let terr _ _ = raise (Error "Type mismatch, expecting pointer values.") in
M.case_mem_value m unspecified terr terr terr (fun _ p -> specified p)
(terr()) terr terr
let get_array m =
let terr _ _ = raise (Error "Type mismatch, expecting array.") in
M.case_mem_value m unspecified terr terr terr terr
specified terr terr
let get_struct m =
let terr _ _ = raise (Error "Type mismatch, expecting struct.") in
M.case_mem_value m unspecified terr terr terr terr (terr())
(fun _ -> specified) terr
let get_union m =
let terr _ _ = raise (Error "Type mismatch, expecting union.") in
M.case_mem_value m unspecified terr terr terr terr (terr())
terr (fun _ cid m -> Specified (cid, m))
let case_loaded_mval f = case_loaded f M.unspecified_mval
let mk_int s = M.integer_ival (Nat_big_num.of_string s)
let mk_float s = M.str_fval s
let mk_pointer alloc_id addr =
M.concrete_ptrval (Nat_big_num.of_string alloc_id)
(Nat_big_num.of_string addr)
let mk_null cty = M.null_ptrval cty
let mk_null_void = mk_null C.Void0
let add = M.op_ival Mem_common.IntAdd
let sub = M.op_ival Mem_common.IntSub
let mul = M.op_ival Mem_common.IntMul
let div = M.op_ival Mem_common.IntDiv
let remt = M.op_ival Mem_common.IntRem_t
let remf = M.op_ival Mem_common.IntRem_f
let exp = M.op_ival Mem_common.IntExp
let addf = M.op_fval Mem_common.FloatAdd
let subf = M.op_fval Mem_common.FloatSub
let mulf = M.op_fval Mem_common.FloatMul
let divf = M.op_fval Mem_common.FloatDiv
let eq n m = Option.get (M.eq_ival (Some M.initial_mem_state) n m)
let lt n m = Option.get (M.lt_ival (Some M.initial_mem_state) n m)
let gt n m = Option.get (M.lt_ival (Some M.initial_mem_state) m n)
let le n m = Option.get (M.le_ival (Some M.initial_mem_state) n m)
let ge n m = Option.get (M.le_ival (Some M.initial_mem_state) m n)
let valid_for_deref_ptrval p = return @@ M.validForDeref_ptrval p
let memcmp p q r = return @@ M.memcmp p q r
let memcpy p q r = return @@ M.memcpy p q r
let realloc al p size = return @@ M.realloc 0 al p size
let ptr_well_aligned = M.isWellAligned_ptrval
let create pre al ty x_opt =
last_memop := Create;
M.allocate_object 0 pre al ty
(Option.case (fun x -> Some (case_loaded_mval id x))
(fun () -> None) x_opt)
let alloc pre al n =
last_memop := Alloc;
M.allocate_region 0 pre al n
let load cty ret e =
last_memop := Load;
M.load Location_ocaml.unknown cty e >>= return % ret % snd
let load_integer ity =
load (C.Basic (C.Integer ity)) get_integer
let load_float fty =
load (C.Basic (C.Floating fty)) get_float
let load_pointer q cty =
load (C.Pointer0 (q, cty)) get_pointer
let load_array q cty size =
load (C.Array0 (cty, size)) get_array
let load_struct s =
load (C.Struct0 s) get_struct
let load_union s =
load (C.Union0 s) get_union
let store f ty b e1 e2 =
last_memop := Store;
M.store Location_ocaml.unknown ty b e1 @@ case_loaded_mval f e2
let store_integer ity =
store (M.integer_value_mval ity) (C.Basic (C.Integer ity))
let store_pointer q cty =
store (M.pointer_mval cty) (C.Pointer0 (q, cty))
let store_struct s =
store (M.struct_mval s) (C.Struct0 s)
let store_union s cid =
store (M.union_mval s cid) (C.Union0 s)
let store_array_of conv cty size =
let array_mval e = M.array_mval (List.map (case_loaded_mval conv) e)
in store array_mval (C.Array0 (cty, size))
let store_array_of_int ity =
store_array_of (M.integer_value_mval ity) (C.Basic (C.Integer ity))
let store_array_of_float fty =
store_array_of (M.floating_value_mval fty) (C.Basic (C.Floating fty))
let store_array_of_ptr q cty =
store_array_of (M.pointer_mval cty) (C.Pointer0 (q, cty))
let store_array_of_struct s =
store_array_of (M.struct_mval s) (C.Struct0 s)
Printf wrap
let printf (conv : C.ctype0 -> M.integer_value -> M.integer_value)
(xs:M.integer_value list)
(args:(C.ctype0 * M.pointer_value) list) =
let encode ival = match Mem_aux.integerFromIntegerValue ival with
| Some n -> Decode_ocaml.encode_character_constant n
| None -> Debug_ocaml.error
"Printf: one of the element of the format array was invalid"
in
let eval_conv cty x =
let terr _ _ = raise (Error "Rt_ocaml.printf: expecting an integer") in
let n = M.case_mem_value x (terr()) terr (fun _ -> conv cty)
terr terr (terr()) terr terr
in Nondeterminism.nd_return (Either.Right (Undefined.Defined
(Core.Vloaded (Core.LVspecified (Core.OVinteger n)))))
in
Formatted.printf eval_conv (List.rev (List.map encode xs)) args
>>= begin function
| Either.Right (Undefined.Defined xs) ->
let n = List.length xs in
let output = String.init n (List.nth xs) in
if batch then stdout := !stdout ^ String.escaped output
else print_string output;
return (Specified (M.integer_ival (Nat_big_num.of_int n)))
| Either.Right (Undefined.Undef (_, xs) ) ->
raise (Error (String.concat ","
(List.map Undefined.stringFromUndefined_behaviour xs)))
| Either.Right (Undefined.Error (_, m) ) -> raise (Error m)
| Either.Left z -> raise (Error (Pp_errors.to_string z))
end
let sprintf _ = failwith "No support for sprintf"
let snprintf _ = failwith "No support for snprintf"
exception Exit of (M.integer_value loaded)
let print_batch i res =
Printf.printf "Defined {value: \"%s\", stdout: \"%s\", stderr: \"\", blocked: \"false\"}\n" res !stdout
let print_err_batch e =
let err = match e with
| Mem_common . MerrUnitialised str - > " MerrUnitialised \ " " ^ ( str ^ " \ " " )
| Mem_common.MerrInternal str -> "MerrInternal \"" ^ (str ^ "\"")
| Mem_common.MerrOther str -> "MerrOther \"" ^ (str ^ "\"")
| Mem_common . MerrReadFromDead - > " MerrReadFromDead "
| Mem_common.MerrWIP str -> "Memory WIP: " ^ str
| _ -> "memory error"
in
Printf.sprintf "Killed {msg: memory layout error (%s seq) ==> %s}" (show_memop !last_memop) err
let string_of_specified n =
Printf.sprintf "Specified(%s)" (Nat_big_num.to_string n)
let string_of_unspec cty =
Printf.sprintf "Unspecified(\"%s\")" (String_core_ctype.string_of_ctype cty)
let dummy_file =
let cmp = Symbol.instance_Basic_classes_Ord_Symbol_sym_dict.Lem_basic_classes.compare_method in
let impl_cmp = Implementation_.instance_Basic_classes_SetType_Implementation__implementation_constant_dict.Lem_pervasives.setElemCompare_method in
Core.{
main = None;
tagDefs = Pmap.empty cmp;
stdlib = Pmap.empty cmp;
globs = [];
funs = Pmap.empty cmp;
impl = Pmap.empty impl_cmp;
funinfo = Pmap.empty cmp;
extern = Pmap.empty compare;
}
let quit f =
try
let initial_state = Driver.initial_driver_state dummy_file
Sibylfs.fs_initial_state in
match Smt2.runND Random Impl_mem.cs_module (Driver.liftMem (f (fun x -> raise (Exit x)) ())) initial_state with
| _ -> raise (Error "continuation not raised")
with
| Exit x ->
(match x with
| Specified x ->
let n = M.eval_integer_value x |> Option.get in
if batch then print_batch 0 (string_of_specified n);
exit (Nat_big_num.to_int n)
| Unspecified cty ->
if batch then print_batch 0 (string_of_unspec cty);
exit(-1)
)
let set_global (f, x) =
f return () >>= fun y -> x := y; return ()
let init_globals glbs =
List.fold_left
(fun acc (f, x) -> acc >>= fun _ -> set_global (f, x))
(return ()) glbs
let create_tag_defs_map defs =
List.fold_left
(fun m (s, xs) -> Pmap.add s xs m)
(Pmap.empty Symbol.symbol_compare) defs
let run tags gls main =
begin fun cont args ->
Tags.set_tagDefs (create_tag_defs_map tags);
init_globals gls
>>= fun _ -> main cont args
end |> quit
let conv_int_mval it =
case_loaded_mval (M.integer_value_mval it)
let conv_float_mval ft =
case_loaded_mval (M.floating_value_mval ft)
let conv_ptr_mval cty =
case_loaded_mval (M.pointer_mval cty)
let conv_struct_mval s =
case_loaded_mval (M.struct_mval s)
|
432494523b4a71f807d56376fc944285b5706c8f8e05f21c66789ca799d1f6cf | hunt-framework/hunt | Hunt.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ExistentialQuantification #
module Main where
import Hunt.AnalyzerTests
import Hunt.IndexTests
import Hunt.InterpreterTests
import Hunt.QueryParserTests
import Hunt . RankingTests
import Test.Framework
main :: IO ()
main = defaultMain
$ analyzerTests
++ contextTypeTests
++ interpreterTests
++ queryParserTests
-- XXX refactor ranking tests to be conform with new ranking
-- ++ rankingTests
| null | https://raw.githubusercontent.com/hunt-framework/hunt/d692aae756b7bdfb4c99f5a3951aec12893649a8/hunt-searchengine/test/Hunt.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeSynonymInstances #
# LANGUAGE RankNTypes #
XXX refactor ranking tests to be conform with new ranking
++ rankingTests | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE ExistentialQuantification #
module Main where
import Hunt.AnalyzerTests
import Hunt.IndexTests
import Hunt.InterpreterTests
import Hunt.QueryParserTests
import Hunt . RankingTests
import Test.Framework
main :: IO ()
main = defaultMain
$ analyzerTests
++ contextTypeTests
++ interpreterTests
++ queryParserTests
|
5bdc804143c21c36e56711da1c39453bc6fa27067b8d461474cf801015d36659 | Deltaphish/UwUpp | Spec.hs | main :: IO ()
main = putStrLn "Hahahahahahhahaaaahahaha"
| null | https://raw.githubusercontent.com/Deltaphish/UwUpp/4b993e7bd989e31dafd5e12cf3e9e53cc4f9882a/test/Spec.hs | haskell | main :: IO ()
main = putStrLn "Hahahahahahhahaaaahahaha"
| |
5240f0af2de13be7b9c2197a4bd0a6554395b233423d74e8a6d8b93d05e79699 | processone/ejabberd | mod_carboncopy.erl | %%%----------------------------------------------------------------------
%%% File : mod_carboncopy.erl
Author : < >
Purpose : Message Carbons XEP-0280 0.8
Created : 5 May 2008 by < >
%%% Usage : Add the following line in modules section of ejabberd.yml:
%%% {mod_carboncopy, []}
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module (mod_carboncopy).
-author ('').
-protocol({xep, 280, '0.13.2'}).
-behaviour(gen_mod).
%% API:
-export([start/2, stop/1, reload/3]).
-export([user_send_packet/1, user_receive_packet/1,
iq_handler/1, disco_features/5,
depends/2, mod_options/1, mod_doc/0]).
-export([c2s_copy_session/2, c2s_session_opened/1, c2s_session_resumed/1]).
%% For debugging purposes
-export([list/2]).
-include("logger.hrl").
-include_lib("xmpp/include/xmpp.hrl").
-include("translate.hrl").
-type direction() :: sent | received.
-type c2s_state() :: ejabberd_c2s:state().
start(Host, _Opts) ->
ejabberd_hooks:add(disco_local_features, Host, ?MODULE, disco_features, 50),
why priority 89 : to define clearly that we must run ( 90 )
ejabberd_hooks:add(user_send_packet,Host, ?MODULE, user_send_packet, 89),
ejabberd_hooks:add(user_receive_packet,Host, ?MODULE, user_receive_packet, 89),
ejabberd_hooks:add(c2s_copy_session, Host, ?MODULE, c2s_copy_session, 50),
ejabberd_hooks:add(c2s_session_resumed, Host, ?MODULE, c2s_session_resumed, 50),
ejabberd_hooks:add(c2s_session_opened, Host, ?MODULE, c2s_session_opened, 50),
gen_iq_handler:add_iq_handler(ejabberd_sm, Host, ?NS_CARBONS_2, ?MODULE, iq_handler).
stop(Host) ->
gen_iq_handler:remove_iq_handler(ejabberd_sm, Host, ?NS_CARBONS_2),
ejabberd_hooks:delete(disco_local_features, Host, ?MODULE, disco_features, 50),
why priority 89 : to define clearly that we must run ( 90 )
ejabberd_hooks:delete(user_send_packet,Host, ?MODULE, user_send_packet, 89),
ejabberd_hooks:delete(user_receive_packet,Host, ?MODULE, user_receive_packet, 89),
ejabberd_hooks:delete(c2s_copy_session, Host, ?MODULE, c2s_copy_session, 50),
ejabberd_hooks:delete(c2s_session_resumed, Host, ?MODULE, c2s_session_resumed, 50),
ejabberd_hooks:delete(c2s_session_opened, Host, ?MODULE, c2s_session_opened, 50).
reload(_Host, _NewOpts, _OldOpts) ->
ok.
-spec disco_features({error, stanza_error()} | {result, [binary()]} | empty,
jid(), jid(), binary(), binary()) ->
{error, stanza_error()} | {result, [binary()]}.
disco_features(empty, From, To, <<"">>, Lang) ->
disco_features({result, []}, From, To, <<"">>, Lang);
disco_features({result, Feats}, _From, _To, <<"">>, _Lang) ->
{result, [?NS_CARBONS_2,?NS_CARBONS_RULES_0|Feats]};
disco_features(Acc, _From, _To, _Node, _Lang) ->
Acc.
-spec iq_handler(iq()) -> iq().
iq_handler(#iq{type = set, lang = Lang, from = From,
sub_els = [El]} = IQ) when is_record(El, carbons_enable);
is_record(El, carbons_disable) ->
{U, S, R} = jid:tolower(From),
Result = case El of
#carbons_enable{} -> enable(S, U, R, ?NS_CARBONS_2);
#carbons_disable{} -> disable(S, U, R)
end,
case Result of
ok ->
xmpp:make_iq_result(IQ);
{error, _} ->
Txt = ?T("Database failure"),
xmpp:make_error(IQ, xmpp:err_internal_server_error(Txt, Lang))
end;
iq_handler(#iq{type = set, lang = Lang} = IQ) ->
Txt = ?T("Only <enable/> or <disable/> tags are allowed"),
xmpp:make_error(IQ, xmpp:err_bad_request(Txt, Lang));
iq_handler(#iq{type = get, lang = Lang} = IQ)->
Txt = ?T("Value 'get' of 'type' attribute is not allowed"),
xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang)).
-spec user_send_packet({stanza(), ejabberd_c2s:state()})
-> {stanza(), ejabberd_c2s:state()} | {stop, {stanza(), ejabberd_c2s:state()}}.
user_send_packet({#message{meta = #{carbon_copy := true}}, _C2SState} = Acc) ->
%% Stop the hook chain, we don't want logging modules to duplicate this
%% message.
{stop, Acc};
user_send_packet({#message{from = From, to = To} = Msg, C2SState}) ->
{check_and_forward(From, To, Msg, sent), C2SState};
user_send_packet(Acc) ->
Acc.
-spec user_receive_packet({stanza(), ejabberd_c2s:state()})
-> {stanza(), ejabberd_c2s:state()} | {stop, {stanza(), ejabberd_c2s:state()}}.
user_receive_packet({#message{meta = #{carbon_copy := true}}, _C2SState} = Acc) ->
%% Stop the hook chain, we don't want logging modules to duplicate this
%% message.
{stop, Acc};
user_receive_packet({#message{to = To} = Msg, #{jid := JID} = C2SState}) ->
{check_and_forward(JID, To, Msg, received), C2SState};
user_receive_packet(Acc) ->
Acc.
-spec c2s_copy_session(c2s_state(), c2s_state()) -> c2s_state().
c2s_copy_session(State, #{user := U, server := S, resource := R}) ->
case ejabberd_sm:get_user_info(U, S, R) of
offline -> State;
Info ->
case lists:keyfind(carboncopy, 1, Info) of
{_, CC} -> State#{carboncopy => CC};
false -> State
end
end.
-spec c2s_session_resumed(c2s_state()) -> c2s_state().
c2s_session_resumed(#{user := U, server := S, resource := R,
carboncopy := CC} = State) ->
ejabberd_sm:set_user_info(U, S, R, carboncopy, CC),
maps:remove(carboncopy, State);
c2s_session_resumed(State) ->
State.
-spec c2s_session_opened(c2s_state()) -> c2s_state().
c2s_session_opened(State) ->
maps:remove(carboncopy, State).
% Modified from original version:
% - registered to the user_send_packet hook, to be called only once even for multicast
% - do not support "private" message mode, and do not modify the original packet in any way
% - we also replicate "read" notifications
-spec check_and_forward(jid(), jid(), message(), direction()) -> message().
check_and_forward(JID, To, Msg, Direction)->
case (is_chat_message(Msg) orelse
is_received_muc_invite(Msg, Direction)) andalso
not is_received_muc_pm(To, Msg, Direction) andalso
not xmpp:has_subtag(Msg, #carbons_private{}) andalso
not xmpp:has_subtag(Msg, #hint{type = 'no-copy'}) of
true ->
send_copies(JID, To, Msg, Direction);
false ->
ok
end,
Msg.
Internal
%% Direction = received | sent <received xmlns='urn:xmpp:carbons:1'/>
-spec send_copies(jid(), jid(), message(), direction()) -> ok.
send_copies(JID, To, Msg, Direction)->
{U, S, R} = jid:tolower(JID),
PrioRes = ejabberd_sm:get_user_present_resources(U, S),
{_, AvailRs} = lists:unzip(PrioRes),
{MaxPrio, _MaxRes} = case catch lists:max(PrioRes) of
{Prio, Res} -> {Prio, Res};
_ -> {0, undefined}
end,
unavailable resources are handled like bare JIDs
IsBareTo = case {Direction, To} of
{received, #jid{lresource = <<>>}} -> true;
{received, #jid{lresource = LRes}} -> not lists:member(LRes, AvailRs);
_ -> false
end,
list of JIDs that should receive a carbon copy of this message ( excluding the
%% receiver(s) of the original message
TargetJIDs = case {IsBareTo, Msg} of
{true, #message{meta = #{sm_copy := true}}} ->
The message was sent to our bare JID , and we currently have
%% multiple resources with the same highest priority, so the session
%% manager routes the message to each of them. We create carbon
copies only from one of those resources in order to avoid
%% duplicates.
[];
{true, _} ->
OrigTo = fun(Res) -> lists:member({MaxPrio, Res}, PrioRes) end,
[ {jid:make({U, S, CCRes}), CC_Version}
|| {CCRes, CC_Version} <- list(U, S),
lists:member(CCRes, AvailRs), not OrigTo(CCRes) ];
{false, _} ->
[ {jid:make({U, S, CCRes}), CC_Version}
|| {CCRes, CC_Version} <- list(U, S),
lists:member(CCRes, AvailRs), CCRes /= R ]
= lists : delete(JID , [ jid : make({U , S , CCRes } ) || CCRes < - list(U , S ) ] ) ,
end,
lists:foreach(
fun({Dest, _Version}) ->
{_, _, Resource} = jid:tolower(Dest),
?DEBUG("Sending: ~p =/= ~p", [R, Resource]),
Sender = jid:make({U, S, <<>>}),
New = build_forward_packet(Msg, Sender, Dest, Direction),
ejabberd_router:route(xmpp:set_from_to(New, Sender, Dest))
end, TargetJIDs).
-spec build_forward_packet(message(), jid(), jid(), direction()) -> message().
build_forward_packet(#message{type = T} = Msg, Sender, Dest, Direction) ->
Forwarded = #forwarded{sub_els = [Msg]},
Carbon = case Direction of
sent -> #carbons_sent{forwarded = Forwarded};
received -> #carbons_received{forwarded = Forwarded}
end,
#message{from = Sender, to = Dest, type = T, sub_els = [Carbon],
meta = #{carbon_copy => true}}.
-spec enable(binary(), binary(), binary(), binary()) -> ok | {error, any()}.
enable(Host, U, R, CC)->
?DEBUG("Enabling carbons for ~ts@~ts/~ts", [U, Host, R]),
case ejabberd_sm:set_user_info(U, Host, R, carboncopy, CC) of
ok -> ok;
{error, Reason} = Err ->
?ERROR_MSG("Failed to enable carbons for ~ts@~ts/~ts: ~p",
[U, Host, R, Reason]),
Err
end.
-spec disable(binary(), binary(), binary()) -> ok | {error, any()}.
disable(Host, U, R)->
?DEBUG("Disabling carbons for ~ts@~ts/~ts", [U, Host, R]),
case ejabberd_sm:del_user_info(U, Host, R, carboncopy) of
ok -> ok;
{error, notfound} -> ok;
{error, Reason} = Err ->
?ERROR_MSG("Failed to disable carbons for ~ts@~ts/~ts: ~p",
[U, Host, R, Reason]),
Err
end.
-spec is_chat_message(message()) -> boolean().
is_chat_message(#message{type = chat}) ->
true;
is_chat_message(#message{type = normal, body = [_|_]}) ->
true;
is_chat_message(#message{type = Type} = Msg) when Type == chat;
Type == normal ->
has_chatstate(Msg) orelse xmpp:has_subtag(Msg, #receipt_response{});
is_chat_message(_) ->
false.
-spec is_received_muc_invite(message(), direction()) -> boolean().
is_received_muc_invite(_Msg, sent) ->
false;
is_received_muc_invite(Msg, received) ->
case xmpp:get_subtag(Msg, #muc_user{}) of
#muc_user{invites = [_|_]} ->
true;
_ ->
xmpp:has_subtag(Msg, #x_conference{jid = jid:make(<<"">>)})
end.
-spec is_received_muc_pm(jid(), message(), direction()) -> boolean().
is_received_muc_pm(#jid{lresource = <<>>}, _Msg, _Direction) ->
false;
is_received_muc_pm(_To, _Msg, sent) ->
false;
is_received_muc_pm(_To, Msg, received) ->
xmpp:has_subtag(Msg, #muc_user{}).
-spec has_chatstate(message()) -> boolean().
has_chatstate(#message{sub_els = Els}) ->
lists:any(fun(El) -> xmpp:get_ns(El) == ?NS_CHATSTATES end, Els).
-spec list(binary(), binary()) -> [{Resource :: binary(), Namespace :: binary()}].
list(User, Server) ->
lists:filtermap(
fun({Resource, Info}) ->
case lists:keyfind(carboncopy, 1, Info) of
{_, NS} -> {true, {Resource, NS}};
false -> false
end
end, ejabberd_sm:get_user_info(User, Server)).
depends(_Host, _Opts) ->
[].
mod_options(_) ->
[].
mod_doc() ->
#{desc =>
?T("The module implements -0280.html"
"[XEP-0280: Message Carbons]. "
"The module broadcasts messages on all connected "
"user resources (devices).")}.
| null | https://raw.githubusercontent.com/processone/ejabberd/c103182bc7e5b8a8ab123ce02d1959a54e939480/src/mod_carboncopy.erl | erlang | ----------------------------------------------------------------------
File : mod_carboncopy.erl
Usage : Add the following line in modules section of ejabberd.yml:
{mod_carboncopy, []}
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
----------------------------------------------------------------------
API:
For debugging purposes
Stop the hook chain, we don't want logging modules to duplicate this
message.
Stop the hook chain, we don't want logging modules to duplicate this
message.
Modified from original version:
- registered to the user_send_packet hook, to be called only once even for multicast
- do not support "private" message mode, and do not modify the original packet in any way
- we also replicate "read" notifications
Direction = received | sent <received xmlns='urn:xmpp:carbons:1'/>
receiver(s) of the original message
multiple resources with the same highest priority, so the session
manager routes the message to each of them. We create carbon
duplicates. | Author : < >
Purpose : Message Carbons XEP-0280 0.8
Created : 5 May 2008 by < >
ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module (mod_carboncopy).
-author ('').
-protocol({xep, 280, '0.13.2'}).
-behaviour(gen_mod).
-export([start/2, stop/1, reload/3]).
-export([user_send_packet/1, user_receive_packet/1,
iq_handler/1, disco_features/5,
depends/2, mod_options/1, mod_doc/0]).
-export([c2s_copy_session/2, c2s_session_opened/1, c2s_session_resumed/1]).
-export([list/2]).
-include("logger.hrl").
-include_lib("xmpp/include/xmpp.hrl").
-include("translate.hrl").
-type direction() :: sent | received.
-type c2s_state() :: ejabberd_c2s:state().
start(Host, _Opts) ->
ejabberd_hooks:add(disco_local_features, Host, ?MODULE, disco_features, 50),
why priority 89 : to define clearly that we must run ( 90 )
ejabberd_hooks:add(user_send_packet,Host, ?MODULE, user_send_packet, 89),
ejabberd_hooks:add(user_receive_packet,Host, ?MODULE, user_receive_packet, 89),
ejabberd_hooks:add(c2s_copy_session, Host, ?MODULE, c2s_copy_session, 50),
ejabberd_hooks:add(c2s_session_resumed, Host, ?MODULE, c2s_session_resumed, 50),
ejabberd_hooks:add(c2s_session_opened, Host, ?MODULE, c2s_session_opened, 50),
gen_iq_handler:add_iq_handler(ejabberd_sm, Host, ?NS_CARBONS_2, ?MODULE, iq_handler).
stop(Host) ->
gen_iq_handler:remove_iq_handler(ejabberd_sm, Host, ?NS_CARBONS_2),
ejabberd_hooks:delete(disco_local_features, Host, ?MODULE, disco_features, 50),
why priority 89 : to define clearly that we must run ( 90 )
ejabberd_hooks:delete(user_send_packet,Host, ?MODULE, user_send_packet, 89),
ejabberd_hooks:delete(user_receive_packet,Host, ?MODULE, user_receive_packet, 89),
ejabberd_hooks:delete(c2s_copy_session, Host, ?MODULE, c2s_copy_session, 50),
ejabberd_hooks:delete(c2s_session_resumed, Host, ?MODULE, c2s_session_resumed, 50),
ejabberd_hooks:delete(c2s_session_opened, Host, ?MODULE, c2s_session_opened, 50).
reload(_Host, _NewOpts, _OldOpts) ->
ok.
-spec disco_features({error, stanza_error()} | {result, [binary()]} | empty,
jid(), jid(), binary(), binary()) ->
{error, stanza_error()} | {result, [binary()]}.
disco_features(empty, From, To, <<"">>, Lang) ->
disco_features({result, []}, From, To, <<"">>, Lang);
disco_features({result, Feats}, _From, _To, <<"">>, _Lang) ->
{result, [?NS_CARBONS_2,?NS_CARBONS_RULES_0|Feats]};
disco_features(Acc, _From, _To, _Node, _Lang) ->
Acc.
-spec iq_handler(iq()) -> iq().
iq_handler(#iq{type = set, lang = Lang, from = From,
sub_els = [El]} = IQ) when is_record(El, carbons_enable);
is_record(El, carbons_disable) ->
{U, S, R} = jid:tolower(From),
Result = case El of
#carbons_enable{} -> enable(S, U, R, ?NS_CARBONS_2);
#carbons_disable{} -> disable(S, U, R)
end,
case Result of
ok ->
xmpp:make_iq_result(IQ);
{error, _} ->
Txt = ?T("Database failure"),
xmpp:make_error(IQ, xmpp:err_internal_server_error(Txt, Lang))
end;
iq_handler(#iq{type = set, lang = Lang} = IQ) ->
Txt = ?T("Only <enable/> or <disable/> tags are allowed"),
xmpp:make_error(IQ, xmpp:err_bad_request(Txt, Lang));
iq_handler(#iq{type = get, lang = Lang} = IQ)->
Txt = ?T("Value 'get' of 'type' attribute is not allowed"),
xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang)).
-spec user_send_packet({stanza(), ejabberd_c2s:state()})
-> {stanza(), ejabberd_c2s:state()} | {stop, {stanza(), ejabberd_c2s:state()}}.
user_send_packet({#message{meta = #{carbon_copy := true}}, _C2SState} = Acc) ->
{stop, Acc};
user_send_packet({#message{from = From, to = To} = Msg, C2SState}) ->
{check_and_forward(From, To, Msg, sent), C2SState};
user_send_packet(Acc) ->
Acc.
-spec user_receive_packet({stanza(), ejabberd_c2s:state()})
-> {stanza(), ejabberd_c2s:state()} | {stop, {stanza(), ejabberd_c2s:state()}}.
user_receive_packet({#message{meta = #{carbon_copy := true}}, _C2SState} = Acc) ->
{stop, Acc};
user_receive_packet({#message{to = To} = Msg, #{jid := JID} = C2SState}) ->
{check_and_forward(JID, To, Msg, received), C2SState};
user_receive_packet(Acc) ->
Acc.
-spec c2s_copy_session(c2s_state(), c2s_state()) -> c2s_state().
c2s_copy_session(State, #{user := U, server := S, resource := R}) ->
case ejabberd_sm:get_user_info(U, S, R) of
offline -> State;
Info ->
case lists:keyfind(carboncopy, 1, Info) of
{_, CC} -> State#{carboncopy => CC};
false -> State
end
end.
-spec c2s_session_resumed(c2s_state()) -> c2s_state().
c2s_session_resumed(#{user := U, server := S, resource := R,
carboncopy := CC} = State) ->
ejabberd_sm:set_user_info(U, S, R, carboncopy, CC),
maps:remove(carboncopy, State);
c2s_session_resumed(State) ->
State.
-spec c2s_session_opened(c2s_state()) -> c2s_state().
c2s_session_opened(State) ->
maps:remove(carboncopy, State).
-spec check_and_forward(jid(), jid(), message(), direction()) -> message().
check_and_forward(JID, To, Msg, Direction)->
case (is_chat_message(Msg) orelse
is_received_muc_invite(Msg, Direction)) andalso
not is_received_muc_pm(To, Msg, Direction) andalso
not xmpp:has_subtag(Msg, #carbons_private{}) andalso
not xmpp:has_subtag(Msg, #hint{type = 'no-copy'}) of
true ->
send_copies(JID, To, Msg, Direction);
false ->
ok
end,
Msg.
Internal
-spec send_copies(jid(), jid(), message(), direction()) -> ok.
send_copies(JID, To, Msg, Direction)->
{U, S, R} = jid:tolower(JID),
PrioRes = ejabberd_sm:get_user_present_resources(U, S),
{_, AvailRs} = lists:unzip(PrioRes),
{MaxPrio, _MaxRes} = case catch lists:max(PrioRes) of
{Prio, Res} -> {Prio, Res};
_ -> {0, undefined}
end,
unavailable resources are handled like bare JIDs
IsBareTo = case {Direction, To} of
{received, #jid{lresource = <<>>}} -> true;
{received, #jid{lresource = LRes}} -> not lists:member(LRes, AvailRs);
_ -> false
end,
list of JIDs that should receive a carbon copy of this message ( excluding the
TargetJIDs = case {IsBareTo, Msg} of
{true, #message{meta = #{sm_copy := true}}} ->
The message was sent to our bare JID , and we currently have
copies only from one of those resources in order to avoid
[];
{true, _} ->
OrigTo = fun(Res) -> lists:member({MaxPrio, Res}, PrioRes) end,
[ {jid:make({U, S, CCRes}), CC_Version}
|| {CCRes, CC_Version} <- list(U, S),
lists:member(CCRes, AvailRs), not OrigTo(CCRes) ];
{false, _} ->
[ {jid:make({U, S, CCRes}), CC_Version}
|| {CCRes, CC_Version} <- list(U, S),
lists:member(CCRes, AvailRs), CCRes /= R ]
= lists : delete(JID , [ jid : make({U , S , CCRes } ) || CCRes < - list(U , S ) ] ) ,
end,
lists:foreach(
fun({Dest, _Version}) ->
{_, _, Resource} = jid:tolower(Dest),
?DEBUG("Sending: ~p =/= ~p", [R, Resource]),
Sender = jid:make({U, S, <<>>}),
New = build_forward_packet(Msg, Sender, Dest, Direction),
ejabberd_router:route(xmpp:set_from_to(New, Sender, Dest))
end, TargetJIDs).
-spec build_forward_packet(message(), jid(), jid(), direction()) -> message().
build_forward_packet(#message{type = T} = Msg, Sender, Dest, Direction) ->
Forwarded = #forwarded{sub_els = [Msg]},
Carbon = case Direction of
sent -> #carbons_sent{forwarded = Forwarded};
received -> #carbons_received{forwarded = Forwarded}
end,
#message{from = Sender, to = Dest, type = T, sub_els = [Carbon],
meta = #{carbon_copy => true}}.
-spec enable(binary(), binary(), binary(), binary()) -> ok | {error, any()}.
enable(Host, U, R, CC)->
?DEBUG("Enabling carbons for ~ts@~ts/~ts", [U, Host, R]),
case ejabberd_sm:set_user_info(U, Host, R, carboncopy, CC) of
ok -> ok;
{error, Reason} = Err ->
?ERROR_MSG("Failed to enable carbons for ~ts@~ts/~ts: ~p",
[U, Host, R, Reason]),
Err
end.
-spec disable(binary(), binary(), binary()) -> ok | {error, any()}.
disable(Host, U, R)->
?DEBUG("Disabling carbons for ~ts@~ts/~ts", [U, Host, R]),
case ejabberd_sm:del_user_info(U, Host, R, carboncopy) of
ok -> ok;
{error, notfound} -> ok;
{error, Reason} = Err ->
?ERROR_MSG("Failed to disable carbons for ~ts@~ts/~ts: ~p",
[U, Host, R, Reason]),
Err
end.
-spec is_chat_message(message()) -> boolean().
is_chat_message(#message{type = chat}) ->
true;
is_chat_message(#message{type = normal, body = [_|_]}) ->
true;
is_chat_message(#message{type = Type} = Msg) when Type == chat;
Type == normal ->
has_chatstate(Msg) orelse xmpp:has_subtag(Msg, #receipt_response{});
is_chat_message(_) ->
false.
-spec is_received_muc_invite(message(), direction()) -> boolean().
is_received_muc_invite(_Msg, sent) ->
false;
is_received_muc_invite(Msg, received) ->
case xmpp:get_subtag(Msg, #muc_user{}) of
#muc_user{invites = [_|_]} ->
true;
_ ->
xmpp:has_subtag(Msg, #x_conference{jid = jid:make(<<"">>)})
end.
-spec is_received_muc_pm(jid(), message(), direction()) -> boolean().
is_received_muc_pm(#jid{lresource = <<>>}, _Msg, _Direction) ->
false;
is_received_muc_pm(_To, _Msg, sent) ->
false;
is_received_muc_pm(_To, Msg, received) ->
xmpp:has_subtag(Msg, #muc_user{}).
-spec has_chatstate(message()) -> boolean().
has_chatstate(#message{sub_els = Els}) ->
lists:any(fun(El) -> xmpp:get_ns(El) == ?NS_CHATSTATES end, Els).
-spec list(binary(), binary()) -> [{Resource :: binary(), Namespace :: binary()}].
list(User, Server) ->
lists:filtermap(
fun({Resource, Info}) ->
case lists:keyfind(carboncopy, 1, Info) of
{_, NS} -> {true, {Resource, NS}};
false -> false
end
end, ejabberd_sm:get_user_info(User, Server)).
depends(_Host, _Opts) ->
[].
mod_options(_) ->
[].
mod_doc() ->
#{desc =>
?T("The module implements -0280.html"
"[XEP-0280: Message Carbons]. "
"The module broadcasts messages on all connected "
"user resources (devices).")}.
|
772a9e296d3af3bac924c9f1e1a74e287ca7d0d95195b3afb7fc08a800d903e2 | Risto-Stevcev/bastet | Test_JsPromise.ml | open BsMocha.Mocha
open BsJsverify.Verify.Arbitrary
open BsJsverify.Verify.Property
let ( <. ) =
let open Function.Infix in
( <. )
(** Note: Promises are not actually Monads because you can't have
Js.Promise.t(Js.Promise.t('a))
Even though it's a valid bucklescript signature *)
module ComparePromise = struct
type 'a t = 'a Js.Promise.t
let eq a b =
Js.Promise.then_ (fun a' -> Js.Promise.then_ (fun b' -> Js.Promise.resolve (a' = b')) b) a
|> Obj.magic
end
;;
describe "Promise" (fun () ->
let promise a =
Js.Promise.make (fun ~resolve ~reject:_ ->
Js.Global.setTimeout (fun () -> (resolve a [@bs])) 10 |> ignore)
in
describe "Functor" (fun () ->
let module V = Verify.Compare.Functor (Promise.Functor) (ComparePromise) in
async_property1 "should satisfy identity" arb_nat (Obj.magic <. V.identity <. promise);
async_property1
"should satisfy composition"
arb_nat
(Obj.magic <. V.composition (( ^ ) "!") string_of_int <. promise));
describe "Apply" (fun () ->
let module V = Verify.Compare.Apply (Promise.Apply) (ComparePromise) in
async_property1
"should satisfy associative composition"
arb_nat
(Obj.magic
<. V.associative_composition
(Js.Promise.resolve (( ^ ) "!"))
(Js.Promise.resolve string_of_int)
<. promise));
describe "Applicative" (fun () ->
let module V = Verify.Compare.Applicative (Promise.Applicative) (ComparePromise) in
async_property1 "should satisfy identity" arb_nat (Obj.magic <. V.identity <. promise);
async_property1
"should satisfy homomorphism"
arb_nat
(Obj.magic <. V.homomorphism string_of_int)))
| null | https://raw.githubusercontent.com/Risto-Stevcev/bastet/030db286f57d2e316897f0600d40b34777eabba6/bastet_js/test/Test_JsPromise.ml | ocaml | * Note: Promises are not actually Monads because you can't have
Js.Promise.t(Js.Promise.t('a))
Even though it's a valid bucklescript signature | open BsMocha.Mocha
open BsJsverify.Verify.Arbitrary
open BsJsverify.Verify.Property
let ( <. ) =
let open Function.Infix in
( <. )
module ComparePromise = struct
type 'a t = 'a Js.Promise.t
let eq a b =
Js.Promise.then_ (fun a' -> Js.Promise.then_ (fun b' -> Js.Promise.resolve (a' = b')) b) a
|> Obj.magic
end
;;
describe "Promise" (fun () ->
let promise a =
Js.Promise.make (fun ~resolve ~reject:_ ->
Js.Global.setTimeout (fun () -> (resolve a [@bs])) 10 |> ignore)
in
describe "Functor" (fun () ->
let module V = Verify.Compare.Functor (Promise.Functor) (ComparePromise) in
async_property1 "should satisfy identity" arb_nat (Obj.magic <. V.identity <. promise);
async_property1
"should satisfy composition"
arb_nat
(Obj.magic <. V.composition (( ^ ) "!") string_of_int <. promise));
describe "Apply" (fun () ->
let module V = Verify.Compare.Apply (Promise.Apply) (ComparePromise) in
async_property1
"should satisfy associative composition"
arb_nat
(Obj.magic
<. V.associative_composition
(Js.Promise.resolve (( ^ ) "!"))
(Js.Promise.resolve string_of_int)
<. promise));
describe "Applicative" (fun () ->
let module V = Verify.Compare.Applicative (Promise.Applicative) (ComparePromise) in
async_property1 "should satisfy identity" arb_nat (Obj.magic <. V.identity <. promise);
async_property1
"should satisfy homomorphism"
arb_nat
(Obj.magic <. V.homomorphism string_of_int)))
|
90b074e16a7d5e7ad0592ac09abae81d073419004a48ed1a8b0ddf5765d144a0 | zed-throben/erlangeos | io_inheritance.erl | - module('io_inheritance').
- compile(export_all).
start() ->
Dog = eos:new(eos@obj,[],[{barkPhrase , "woof!" },{bark , fun (This,Arguments) ->
io:format(eosstd:fmt("~s\n",[eosstd:to_str(eos:get_slot(This,barkPhrase))])) end }]),
Chiwawa = eos:invoke(Dog,clone,[]),
eos:set_slot(Chiwawa,barkPhrase , "yip!"),
io:format("Dog bark: "),
eos:invoke(Dog,bark,[]),
io:format("Chiwawa bark: "),
eos:invoke(Chiwawa,bark,[]),
MyChiwawa = eos:invoke(Chiwawa,clone,[]),
eos:set_slot(MyChiwawa,barkPhrase , "Yo Quiero Taco Bell"),
io:format("myChiwawa bark: "),
eos:invoke(MyChiwawa,bark,[]).
| null | https://raw.githubusercontent.com/zed-throben/erlangeos/44e50e442f5d396c69ae90db530b0b60b01d692a/sample/io_inheritance.erl | erlang | - module('io_inheritance').
- compile(export_all).
start() ->
Dog = eos:new(eos@obj,[],[{barkPhrase , "woof!" },{bark , fun (This,Arguments) ->
io:format(eosstd:fmt("~s\n",[eosstd:to_str(eos:get_slot(This,barkPhrase))])) end }]),
Chiwawa = eos:invoke(Dog,clone,[]),
eos:set_slot(Chiwawa,barkPhrase , "yip!"),
io:format("Dog bark: "),
eos:invoke(Dog,bark,[]),
io:format("Chiwawa bark: "),
eos:invoke(Chiwawa,bark,[]),
MyChiwawa = eos:invoke(Chiwawa,clone,[]),
eos:set_slot(MyChiwawa,barkPhrase , "Yo Quiero Taco Bell"),
io:format("myChiwawa bark: "),
eos:invoke(MyChiwawa,bark,[]).
| |
6c07139671a9b2f5aa49eb18acb83ba7d95e5bc0fdd022ba6ce99032d4476cac | DaMSL/K3 | Common.hs | # LANGUAGE TupleSections #
# LANGUAGE ViewPatterns #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
-- Common utilities in writing program transformations.
module Language.K3.Transform.Common where
import Control.Monad.Identity
import Control.Monad.State
import Data.Hashable
import Data.Tree
import Language.K3.Core.Annotation
import Language.K3.Core.Common
import Language.K3.Core.Declaration
import Language.K3.Core.Expression
import Language.K3.Core.Utils
import qualified Language.K3.Core.Constructor.Expression as EC
import Language.K3.Analysis.Core
-- Configuration for many transformations at once
data TransformConfig = TransformConfig { optRefs :: Bool
, optMoves :: Bool
}
defaultTransConfig :: TransformConfig
defaultTransConfig = TransformConfig True True
noRefsTransConfig :: TransformConfig
noRefsTransConfig = defaultTransConfig { optRefs = False }
noMovesTransConfig :: TransformConfig
noMovesTransConfig = defaultTransConfig { optMoves = False }
-- | Returns whether all occurrences of a binding can be substituted in a target expression.
fullySubstitutable :: Identifier -> K3 Expression -> K3 Expression -> Bool
fullySubstitutable i iExpr expr =
runIdentity $! biFoldMapTree pruneSubs substitutable [(i, (iExpr, freeVariables iExpr))] True expr
where
pruneSubs subs (tag -> ELambda j) = return $! pruneBinding subs [j] [True]
pruneSubs subs (tag -> ELetIn j) = return $! pruneBinding subs [j] [False, True]
pruneSubs subs (tag -> EBindAs b) = return $! pruneBinding subs (bindingVariables b) [False, True]
pruneSubs subs (tag -> ECaseOf j) = return $! pruneBinding subs [j] [False, True, False]
pruneSubs subs n = return $! (subs, replicate (length $ children n) subs)
pruneBinding subs ids oldOrNew =
let newSubs = foldl cleanSubs subs ids
in (subs, map (\useNew -> if useNew then newSubs else subs) oldOrNew)
cleanSubs acc j = filter (\(_, (_, freevars)) -> j `notElem` freevars) nsubs
where nsubs = removeAssoc acc j
substitutable subs _ (tag -> EVariable j) | i == j = return $! maybe False (const True) $ lookup j subs
substitutable _ _ (Node _ []) = return True
substitutable _ ch _ = return $! and ch
-- | Substitute all occurrences of a variable with an expression in the specified target expression.
substituteImmutBinding :: Identifier -> K3 Expression -> K3 Expression -> K3 Expression
substituteImmutBinding i iExpr expr =
runIdentity $! biFoldMapTree pruneSubs rebuild [(i, (iExpr, freeVariables iExpr))] EC.unit expr
where
pruneSubs subs (tag -> ELambda j) = return $! pruneBinding subs [j] [True]
pruneSubs subs (tag -> ELetIn j) = return $! pruneBinding subs [j] [False, True]
pruneSubs subs (tag -> EBindAs b) = return $! pruneBinding subs (bindingVariables b) [False, True]
pruneSubs subs (tag -> ECaseOf j) = return $! pruneBinding subs [j] [False, True, False]
pruneSubs subs n = return $! (subs, replicate (length $! children n) subs)
pruneBinding subs ids oldOrNew =
let newSubs = foldl cleanSubs subs ids
in (subs, map (\useNew -> if useNew then newSubs else subs) oldOrNew)
cleanSubs acc j = filter (\(_, (_, freevars)) -> j `notElem` freevars) nsubs
where nsubs = removeAssoc acc j
rebuild subs _ n@(tag -> EVariable j) = return $! maybe n fst $ lookup j subs
rebuild _ _ n@(tag -> EConstant _) = return $! n
rebuild _ ch n@(tag -> ETuple) = return $! if null $ children n then n else replaceCh n ch
rebuild _ ch (Node t _) = return $! Node t ch
-- Renumber the uuids in a program
renumberUids :: K3 Declaration -> K3 Declaration
renumberUids p = evalState run 1
where
run = do
First modify declaration annotations
ds <- modifyTree (\n -> replace isDUID (DUID . UID) n) p
ds' <- mapExpression replaceAll ds
return ds'
replaceAll d = modifyTree (\n -> replace isEUID (EUID . UID) n) d
replace matcher constructor n = do
i <- get
put (i+1)
return $! (stripAnnot matcher n) @+ constructor i
stripAnnot :: Eq (Annotation a) => (Annotation a -> Bool) -> K3 a -> K3 a
stripAnnot f t = maybe t (t @-) $ t @~ f
-- Add missing spans in a program tree
addSpans :: String -> K3 Declaration -> K3 Declaration
addSpans spanName p = runIdentity $! do
ds <- modifyTree (return . add isDSpan (DSpan $! GeneratedSpan $! fromIntegral $! hash spanName)) p
mapExpression addExpr ds
where
addExpr n = modifyTree addSpanQual n
addSpanQual n = return $!
add isESpan (ESpan $! GeneratedSpan $! fromIntegral $! hash spanName) n
-- add isEQualified EImmutable n
-- Don't add span if we already have it
add matcher anno n = maybe (n @+ anno) (const n) (n @~ matcher)
-- Clean up code generation with renumbering uids and adding spans
cleanGeneration :: String -> K3 Declaration -> K3 Declaration
cleanGeneration spanName = (addSpans spanName) . renumberUids
| null | https://raw.githubusercontent.com/DaMSL/K3/51749157844e76ae79dba619116fc5ad9d685643/src/Language/K3/Transform/Common.hs | haskell | Common utilities in writing program transformations.
Configuration for many transformations at once
| Returns whether all occurrences of a binding can be substituted in a target expression.
| Substitute all occurrences of a variable with an expression in the specified target expression.
Renumber the uuids in a program
Add missing spans in a program tree
add isEQualified EImmutable n
Don't add span if we already have it
Clean up code generation with renumbering uids and adding spans | # LANGUAGE TupleSections #
# LANGUAGE ViewPatterns #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
module Language.K3.Transform.Common where
import Control.Monad.Identity
import Control.Monad.State
import Data.Hashable
import Data.Tree
import Language.K3.Core.Annotation
import Language.K3.Core.Common
import Language.K3.Core.Declaration
import Language.K3.Core.Expression
import Language.K3.Core.Utils
import qualified Language.K3.Core.Constructor.Expression as EC
import Language.K3.Analysis.Core
data TransformConfig = TransformConfig { optRefs :: Bool
, optMoves :: Bool
}
defaultTransConfig :: TransformConfig
defaultTransConfig = TransformConfig True True
noRefsTransConfig :: TransformConfig
noRefsTransConfig = defaultTransConfig { optRefs = False }
noMovesTransConfig :: TransformConfig
noMovesTransConfig = defaultTransConfig { optMoves = False }
fullySubstitutable :: Identifier -> K3 Expression -> K3 Expression -> Bool
fullySubstitutable i iExpr expr =
runIdentity $! biFoldMapTree pruneSubs substitutable [(i, (iExpr, freeVariables iExpr))] True expr
where
pruneSubs subs (tag -> ELambda j) = return $! pruneBinding subs [j] [True]
pruneSubs subs (tag -> ELetIn j) = return $! pruneBinding subs [j] [False, True]
pruneSubs subs (tag -> EBindAs b) = return $! pruneBinding subs (bindingVariables b) [False, True]
pruneSubs subs (tag -> ECaseOf j) = return $! pruneBinding subs [j] [False, True, False]
pruneSubs subs n = return $! (subs, replicate (length $ children n) subs)
pruneBinding subs ids oldOrNew =
let newSubs = foldl cleanSubs subs ids
in (subs, map (\useNew -> if useNew then newSubs else subs) oldOrNew)
cleanSubs acc j = filter (\(_, (_, freevars)) -> j `notElem` freevars) nsubs
where nsubs = removeAssoc acc j
substitutable subs _ (tag -> EVariable j) | i == j = return $! maybe False (const True) $ lookup j subs
substitutable _ _ (Node _ []) = return True
substitutable _ ch _ = return $! and ch
substituteImmutBinding :: Identifier -> K3 Expression -> K3 Expression -> K3 Expression
substituteImmutBinding i iExpr expr =
runIdentity $! biFoldMapTree pruneSubs rebuild [(i, (iExpr, freeVariables iExpr))] EC.unit expr
where
pruneSubs subs (tag -> ELambda j) = return $! pruneBinding subs [j] [True]
pruneSubs subs (tag -> ELetIn j) = return $! pruneBinding subs [j] [False, True]
pruneSubs subs (tag -> EBindAs b) = return $! pruneBinding subs (bindingVariables b) [False, True]
pruneSubs subs (tag -> ECaseOf j) = return $! pruneBinding subs [j] [False, True, False]
pruneSubs subs n = return $! (subs, replicate (length $! children n) subs)
pruneBinding subs ids oldOrNew =
let newSubs = foldl cleanSubs subs ids
in (subs, map (\useNew -> if useNew then newSubs else subs) oldOrNew)
cleanSubs acc j = filter (\(_, (_, freevars)) -> j `notElem` freevars) nsubs
where nsubs = removeAssoc acc j
rebuild subs _ n@(tag -> EVariable j) = return $! maybe n fst $ lookup j subs
rebuild _ _ n@(tag -> EConstant _) = return $! n
rebuild _ ch n@(tag -> ETuple) = return $! if null $ children n then n else replaceCh n ch
rebuild _ ch (Node t _) = return $! Node t ch
renumberUids :: K3 Declaration -> K3 Declaration
renumberUids p = evalState run 1
where
run = do
First modify declaration annotations
ds <- modifyTree (\n -> replace isDUID (DUID . UID) n) p
ds' <- mapExpression replaceAll ds
return ds'
replaceAll d = modifyTree (\n -> replace isEUID (EUID . UID) n) d
replace matcher constructor n = do
i <- get
put (i+1)
return $! (stripAnnot matcher n) @+ constructor i
stripAnnot :: Eq (Annotation a) => (Annotation a -> Bool) -> K3 a -> K3 a
stripAnnot f t = maybe t (t @-) $ t @~ f
addSpans :: String -> K3 Declaration -> K3 Declaration
addSpans spanName p = runIdentity $! do
ds <- modifyTree (return . add isDSpan (DSpan $! GeneratedSpan $! fromIntegral $! hash spanName)) p
mapExpression addExpr ds
where
addExpr n = modifyTree addSpanQual n
addSpanQual n = return $!
add isESpan (ESpan $! GeneratedSpan $! fromIntegral $! hash spanName) n
add matcher anno n = maybe (n @+ anno) (const n) (n @~ matcher)
cleanGeneration :: String -> K3 Declaration -> K3 Declaration
cleanGeneration spanName = (addSpans spanName) . renumberUids
|
2a352f4f1515fd0a3121bf9e426cacb77711f32e3955cc5bb6b8ddbc993e86b1 | hhucn/decide3 | pathom.clj | (ns decide.server-components.pathom
(:require
[clojure.spec.alpha :as s]
[clojure.string :as str]
[com.fulcrologic.rad.pathom :as rad-pathom]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[datahike.api :as d]
[decide.models.argumentation.api :as argumentation.api]
[decide.models.authorization :as auth]
[decide.models.opinion.api :as opinion.api]
[decide.models.process.resolver :as process.api]
[decide.models.proposal.api :as proposal.api]
[decide.models.user :as user]
[decide.models.user.api :as user.api]
[decide.server-components.access-checker :as access-checker]
[decide.server-components.config :refer [config]]
[decide.server-components.database :refer [conn]]
[decide.ui.translations.load :as translation]
[me.ebbinghaus.pathom-access-plugin.pathom2 :as access-plugin]
[mount.core :refer [defstate]]
[taoensso.timbre :as log]
[taoensso.tufte :as t]))
(defn- remove-keys-from-map-values [m & ks]
(->> m
(map (fn [[k v]] [k (apply dissoc v ks)]))
(into {})))
(pc/defresolver index-explorer [env _]
{::pc/input #{:com.wsscode.pathom.viz.index-explorer/id}
::pc/output [:com.wsscode.pathom.viz.index-explorer/index]}
{:com.wsscode.pathom.viz.index-explorer/index
(-> (get env ::pc/indexes)
(update ::pc/index-attributes (fn [attribute-map]
(let [attribute-keys (keys attribute-map)
keys-to-keep (remove (fn [k]
(if (keyword? k)
(some-> k namespace (str/starts-with? "com.wsscode.pathom.connect"))
k))
attribute-keys)]
(select-keys attribute-map keys-to-keep))))
; this is necessary for now, because the index contains functions which can not be serialized by transit.
(update ::pc/index-resolvers remove-keys-from-map-values ::pc/resolve ::pc/transform ::s/params)
(update ::pc/index-mutations remove-keys-from-map-values ::pc/mutate ::pc/transform ::s/params)
; to minimize clutter in the Index Explorer
(update ::pc/index-resolvers (fn [rs] (apply dissoc rs ::s/params (filter #(some-> % namespace (str/starts-with? "com.wsscode.pathom")) (keys rs)))))
(update ::pc/index-mutations (fn [rs] (apply dissoc rs ::s/params (filter #(some-> % namespace (str/starts-with? "com.wsscode.pathom")) (keys rs))))))})
(def spec-plugin
{::p/wrap-mutate
(fn [mutate]
(fn [env sym params]
(if-let [spec (get-in env [::pc/indexes ::pc/index-mutations sym ::s/params])]
(if (s/valid? spec params)
(mutate env sym params)
(do
(log/debug (s/explain spec params))
;; TODO Errors are data too!
(throw (ex-info "Failed validation!" (s/explain-data spec params)))))
(mutate env sym params))))})
(t/add-basic-println-handler! {})
(def tufte-plugin
{::p/wrap-parser
(fn [parser]
(fn [env tx]
(t/profile {:id :parser, :dynamic? true} (parser env tx))))
::pc/wrap-resolve
(fn [resolve]
(fn [env input]
(t/p (get-in env [::pc/resolver-data ::pc/sym]) (resolve env input))))
::p/wrap-mutate
(fn [mutate]
(fn [env sym params]
(t/p sym (mutate env sym params))))})
;;;
;;; This is borrowed from com.fulcrologic.rad.pathom
;;;
(defn process-error
"If there were any exceptions in the parser that cause complete failure we
respond with a well-known message that the client can handle."
[env err]
(let [msg (.getMessage err)
data (or (ex-data err) {})]
(log/error err "Parser Error:" msg #_data)
{::rad-pathom/errors {:message msg
:data data}}))
(defn parser-args [config plugins resolvers]
(let [{:keys [trace? log-requests? log-responses? no-tempids?]} (::rad-pathom/config config)]
{::p/mutate pc/mutate
::p/env {::p/reader [p/map-reader pc/reader2 pc/index-reader
pc/open-ident-reader p/env-placeholder-reader]
::p/placeholder-prefixes #{">"}
::pc/mutation-join-globals [(when-not no-tempids? :tempids) :errors]}
::p/plugins (into []
(keep identity
(concat
[(pc/connect-plugin {::pc/register resolvers})]
plugins
[spec-plugin
(when trace? tufte-plugin)
(access-plugin/access-plugin {:check-fn access-checker/check-access!})
(p/env-plugin {::p/process-error process-error})
(when log-requests? (p/pre-process-parser-plugin rad-pathom/log-request!))
;; TODO: Do we need this, and if so, we need to pass the attribute map
p/elide-special-outputs-plugin
(when log-responses? (rad-pathom/post-process-parser-plugin-with-env rad-pathom/log-response!))
rad-pathom/query-params-to-env-plugin
p/error-handler-plugin
(when trace? p/trace-plugin)])))}))
(defn new-parser
"Create a new pathom parser. `config` is a map containing a ::config key with parameters
that affect the parser. `extra-plugins` is a sequence of pathom plugins to add to the parser. The
plugins will typically need to include plugins from any storage adapters that are being used,
such as the `datomic/pathom-plugin`.
`resolvers` is a vector of all of the resolvers to register with the parser, which can be a nested collection.
Supported config options under the ::config key:
- `:trace? true` Enable the return of pathom performance trace data (development only, high overhead)
- `:log-requests? boolean` Enable logging of incoming queries/mutations.
- `:log-responses? boolean` Enable logging of parser results."
[config extra-plugins resolvers]
(let [real-parser (p/parser (parser-args config extra-plugins resolvers))
{:keys [trace?]} (get config ::rad-pathom/config {})]
(fn wrapped-parser [env tx]
(real-parser env (if trace?
(conj tx :com.wsscode.pathom/trace)
tx)))))
(def all-resolvers
[index-explorer
user/resolvers
process.api/all-resolvers
proposal.api/full-api
opinion.api/resolvers
translation/locale-resolver
user.api/all-resolvers
argumentation.api/full-api])
(defn build-parser [config conn]
(new-parser config
[(p/env-plugin {:config config})
(p/env-wrap-plugin auth/session-wrapper)
(p/env-wrap-plugin
(fn db-wrapper [env]
(assoc env
:conn conn
:db (d/db conn))))]
all-resolvers))
(defstate parser
:start
(new-parser config
[(p/env-plugin {:config config})
(p/env-wrap-plugin auth/session-wrapper)
(p/env-wrap-plugin
(fn db-wrapper [env]
(merge
{:conn conn
:db (d/db conn)}
env)))]
all-resolvers))
| null | https://raw.githubusercontent.com/hhucn/decide3/71834033c4e61da9d7b70953ca537dafd1576162/src/main/decide/server_components/pathom.clj | clojure | this is necessary for now, because the index contains functions which can not be serialized by transit.
to minimize clutter in the Index Explorer
TODO Errors are data too!
This is borrowed from com.fulcrologic.rad.pathom
TODO: Do we need this, and if so, we need to pass the attribute map | (ns decide.server-components.pathom
(:require
[clojure.spec.alpha :as s]
[clojure.string :as str]
[com.fulcrologic.rad.pathom :as rad-pathom]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[datahike.api :as d]
[decide.models.argumentation.api :as argumentation.api]
[decide.models.authorization :as auth]
[decide.models.opinion.api :as opinion.api]
[decide.models.process.resolver :as process.api]
[decide.models.proposal.api :as proposal.api]
[decide.models.user :as user]
[decide.models.user.api :as user.api]
[decide.server-components.access-checker :as access-checker]
[decide.server-components.config :refer [config]]
[decide.server-components.database :refer [conn]]
[decide.ui.translations.load :as translation]
[me.ebbinghaus.pathom-access-plugin.pathom2 :as access-plugin]
[mount.core :refer [defstate]]
[taoensso.timbre :as log]
[taoensso.tufte :as t]))
(defn- remove-keys-from-map-values [m & ks]
(->> m
(map (fn [[k v]] [k (apply dissoc v ks)]))
(into {})))
(pc/defresolver index-explorer [env _]
{::pc/input #{:com.wsscode.pathom.viz.index-explorer/id}
::pc/output [:com.wsscode.pathom.viz.index-explorer/index]}
{:com.wsscode.pathom.viz.index-explorer/index
(-> (get env ::pc/indexes)
(update ::pc/index-attributes (fn [attribute-map]
(let [attribute-keys (keys attribute-map)
keys-to-keep (remove (fn [k]
(if (keyword? k)
(some-> k namespace (str/starts-with? "com.wsscode.pathom.connect"))
k))
attribute-keys)]
(select-keys attribute-map keys-to-keep))))
(update ::pc/index-resolvers remove-keys-from-map-values ::pc/resolve ::pc/transform ::s/params)
(update ::pc/index-mutations remove-keys-from-map-values ::pc/mutate ::pc/transform ::s/params)
(update ::pc/index-resolvers (fn [rs] (apply dissoc rs ::s/params (filter #(some-> % namespace (str/starts-with? "com.wsscode.pathom")) (keys rs)))))
(update ::pc/index-mutations (fn [rs] (apply dissoc rs ::s/params (filter #(some-> % namespace (str/starts-with? "com.wsscode.pathom")) (keys rs))))))})
(def spec-plugin
{::p/wrap-mutate
(fn [mutate]
(fn [env sym params]
(if-let [spec (get-in env [::pc/indexes ::pc/index-mutations sym ::s/params])]
(if (s/valid? spec params)
(mutate env sym params)
(do
(log/debug (s/explain spec params))
(throw (ex-info "Failed validation!" (s/explain-data spec params)))))
(mutate env sym params))))})
(t/add-basic-println-handler! {})
(def tufte-plugin
{::p/wrap-parser
(fn [parser]
(fn [env tx]
(t/profile {:id :parser, :dynamic? true} (parser env tx))))
::pc/wrap-resolve
(fn [resolve]
(fn [env input]
(t/p (get-in env [::pc/resolver-data ::pc/sym]) (resolve env input))))
::p/wrap-mutate
(fn [mutate]
(fn [env sym params]
(t/p sym (mutate env sym params))))})
(defn process-error
"If there were any exceptions in the parser that cause complete failure we
respond with a well-known message that the client can handle."
[env err]
(let [msg (.getMessage err)
data (or (ex-data err) {})]
(log/error err "Parser Error:" msg #_data)
{::rad-pathom/errors {:message msg
:data data}}))
(defn parser-args [config plugins resolvers]
(let [{:keys [trace? log-requests? log-responses? no-tempids?]} (::rad-pathom/config config)]
{::p/mutate pc/mutate
::p/env {::p/reader [p/map-reader pc/reader2 pc/index-reader
pc/open-ident-reader p/env-placeholder-reader]
::p/placeholder-prefixes #{">"}
::pc/mutation-join-globals [(when-not no-tempids? :tempids) :errors]}
::p/plugins (into []
(keep identity
(concat
[(pc/connect-plugin {::pc/register resolvers})]
plugins
[spec-plugin
(when trace? tufte-plugin)
(access-plugin/access-plugin {:check-fn access-checker/check-access!})
(p/env-plugin {::p/process-error process-error})
(when log-requests? (p/pre-process-parser-plugin rad-pathom/log-request!))
p/elide-special-outputs-plugin
(when log-responses? (rad-pathom/post-process-parser-plugin-with-env rad-pathom/log-response!))
rad-pathom/query-params-to-env-plugin
p/error-handler-plugin
(when trace? p/trace-plugin)])))}))
(defn new-parser
"Create a new pathom parser. `config` is a map containing a ::config key with parameters
that affect the parser. `extra-plugins` is a sequence of pathom plugins to add to the parser. The
plugins will typically need to include plugins from any storage adapters that are being used,
such as the `datomic/pathom-plugin`.
`resolvers` is a vector of all of the resolvers to register with the parser, which can be a nested collection.
Supported config options under the ::config key:
- `:trace? true` Enable the return of pathom performance trace data (development only, high overhead)
- `:log-requests? boolean` Enable logging of incoming queries/mutations.
- `:log-responses? boolean` Enable logging of parser results."
[config extra-plugins resolvers]
(let [real-parser (p/parser (parser-args config extra-plugins resolvers))
{:keys [trace?]} (get config ::rad-pathom/config {})]
(fn wrapped-parser [env tx]
(real-parser env (if trace?
(conj tx :com.wsscode.pathom/trace)
tx)))))
(def all-resolvers
[index-explorer
user/resolvers
process.api/all-resolvers
proposal.api/full-api
opinion.api/resolvers
translation/locale-resolver
user.api/all-resolvers
argumentation.api/full-api])
(defn build-parser [config conn]
(new-parser config
[(p/env-plugin {:config config})
(p/env-wrap-plugin auth/session-wrapper)
(p/env-wrap-plugin
(fn db-wrapper [env]
(assoc env
:conn conn
:db (d/db conn))))]
all-resolvers))
(defstate parser
:start
(new-parser config
[(p/env-plugin {:config config})
(p/env-wrap-plugin auth/session-wrapper)
(p/env-wrap-plugin
(fn db-wrapper [env]
(merge
{:conn conn
:db (d/db conn)}
env)))]
all-resolvers))
|
a45df4ceea943681a26cd8be3fdc4a413e0a34b90cf192cb53217e2c71a19e65 | UU-ComputerScience/js-asteroids | jquery.hs |
import Language.UHC.JS.Assorted
import Language.UHC.JS.ECMA.String
import Language.UHC.JS.Primitives
import Language.UHC.JS.Types
import Language.UHC.JS.JQuery.JQuery
main :: IO ()
main = return ()
-- Main function
foreign export jscript "jQueryMain"
jQueryMain :: IO ()
jQueryMain :: IO ()
jQueryMain = do
showAlert
sayHi
addNeat
showNeat
-- Show an alert
foreign export jscript "showAlert"
showAlert :: IO ()
showAlert :: IO ()
showAlert = alert "Hello, World!"
-- Set the contents for to the body element.
foreign export jscript "sayHi"
sayHi :: IO ()
sayHi :: IO ()
sayHi = do
j <- jQuery "body"
setHTML j "Hi there!"
-- Add a (hidden) paragraph to the body element.
foreign export jscript "addNeat"
addNeat :: IO ()
addNeat :: IO ()
addNeat = do
j <- jQuery "body"
h <- getHTML j
setHTML j $ h ++ "<p class='neat'>"
++ "<strong>Congratulations!</strong> This awesome "
++ "jQuery script has been called by a function you have "
++ "written in Haskell!</p>"
-- Show the previously added paragraph using an animation.
foreign export jscript "showNeat"
showNeat :: IO ()
showNeat :: IO ()
showNeat = do
j <- jQuery "p.neat"
addClass j "ohmy"
jqshow j (Just slow) Nothing Nothing
| null | https://raw.githubusercontent.com/UU-ComputerScience/js-asteroids/b7015d8ad4aa57ff30f2631e0945462f6e1ef47a/uhc-js/tests/in-progress/jquery/jquery.hs | haskell | Main function
Show an alert
Set the contents for to the body element.
Add a (hidden) paragraph to the body element.
Show the previously added paragraph using an animation. |
import Language.UHC.JS.Assorted
import Language.UHC.JS.ECMA.String
import Language.UHC.JS.Primitives
import Language.UHC.JS.Types
import Language.UHC.JS.JQuery.JQuery
main :: IO ()
main = return ()
foreign export jscript "jQueryMain"
jQueryMain :: IO ()
jQueryMain :: IO ()
jQueryMain = do
showAlert
sayHi
addNeat
showNeat
foreign export jscript "showAlert"
showAlert :: IO ()
showAlert :: IO ()
showAlert = alert "Hello, World!"
foreign export jscript "sayHi"
sayHi :: IO ()
sayHi :: IO ()
sayHi = do
j <- jQuery "body"
setHTML j "Hi there!"
foreign export jscript "addNeat"
addNeat :: IO ()
addNeat :: IO ()
addNeat = do
j <- jQuery "body"
h <- getHTML j
setHTML j $ h ++ "<p class='neat'>"
++ "<strong>Congratulations!</strong> This awesome "
++ "jQuery script has been called by a function you have "
++ "written in Haskell!</p>"
foreign export jscript "showNeat"
showNeat :: IO ()
showNeat :: IO ()
showNeat = do
j <- jQuery "p.neat"
addClass j "ohmy"
jqshow j (Just slow) Nothing Nothing
|
a8aa7a3575b7182bb441cefaa6afa6492271299b06e009b74871cedf16c504d3 | emqx/hocon | demo_schema3.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2021 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
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(demo_schema3).
-include_lib("typerefl/include/types.hrl").
-behaviour(hocon_schema).
-export([namespace/0, roots/0, fields/1, tags/0]).
namespace() -> ?MODULE.
tags() ->
[<<"tag1">>, <<"another tag">>].
roots() ->
[ {foo, hoconsc:array(hoconsc:ref(foo))}
, {bar, hoconsc:ref(parent)}
].
fields(foo) ->
[ {bar, hoconsc:ref(bar)}
];
fields(bar) ->
Sc = hoconsc:union([hoconsc:ref(foo), null]), %% cyclic refs
[{"baz", Sc}];
%% below fields are to cover the test where identical paths for the same name
i.e. bar.f1.subf.baz can be reached from both " sub1 " and " sub2 "
fields(parent) ->
[{"f1", hoconsc:union([hoconsc:ref("sub1"), hoconsc:ref("sub2")])}];
fields("sub1") ->
both sub1 and sub2 refs to bar
fields("sub2") ->
both sub1 and sub2 refs to bar
| null | https://raw.githubusercontent.com/emqx/hocon/10fefe7e0ddf3f01d45d2d631562afe614ca357f/sample-schemas/demo_schema3.erl | erlang | --------------------------------------------------------------------
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.
--------------------------------------------------------------------
cyclic refs
below fields are to cover the test where identical paths for the same name | Copyright ( c ) 2021 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(demo_schema3).
-include_lib("typerefl/include/types.hrl").
-behaviour(hocon_schema).
-export([namespace/0, roots/0, fields/1, tags/0]).
namespace() -> ?MODULE.
tags() ->
[<<"tag1">>, <<"another tag">>].
roots() ->
[ {foo, hoconsc:array(hoconsc:ref(foo))}
, {bar, hoconsc:ref(parent)}
].
fields(foo) ->
[ {bar, hoconsc:ref(bar)}
];
fields(bar) ->
[{"baz", Sc}];
i.e. bar.f1.subf.baz can be reached from both " sub1 " and " sub2 "
fields(parent) ->
[{"f1", hoconsc:union([hoconsc:ref("sub1"), hoconsc:ref("sub2")])}];
fields("sub1") ->
both sub1 and sub2 refs to bar
fields("sub2") ->
both sub1 and sub2 refs to bar
|
b5082a71e262f9a3e8ad8511f80c70ec8d65ca0b713e384f497b0a1f72a64692 | herd/herdtools7 | outUtils.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2014 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
Utilities for targets ( Out module )
(* Some formating stuff *)
open Printf
let fmt_out_reg proc str = sprintf "out_%i_%s" proc str
let fmt_index name = sprintf "%s[_i]" name
let fmt_presi_index name = sprintf "_log->%s" name
let fmt_presi_ptr_index name = sprintf "_log_ptr->%s" name
let fmt_code p = sprintf "code%i" p
let fmt_prelude p = sprintf "prelude%i" p
let fmt_code_size p = sprintf "code%i_sz" p
let fmt_lbl_offset p lbl = sprintf "off_P%i_%s" p lbl
let fmt_lbl_instr (p,lbl) = sprintf "instr_P%i_%s" p lbl
let fmt_lbl_instr_offset (p,lbl) = sprintf "off_instr_P%i_%s" p lbl
let fmt_lbl_var p lbl = sprintf "P%i_%s" p lbl
let fmt_pte_tag x = Misc.add_pte x
let fmt_pte_kvm x = sprintf "_vars->%s" (fmt_pte_tag x)
let fmt_phy_tag x = "saved_" ^ Misc.add_pte x
let fmt_phy_kvm x = sprintf "_vars->%s" (fmt_phy_tag x)
(* Value (address) output *)
module type Config = sig
val memory : Memory.t
val hexa : bool
val mode : Mode.t
end
module DefaultConfig = struct
let memory = Memory.Direct
let hexa = false
end
module Make(O:Config)(V:Constant.S) = struct
open Memory
open Constant
let dump_addr a = match O.memory with
| Direct -> sprintf "&_a->%s[_i]" a
| Indirect -> sprintf "_a->%s[_i]" a
let dump_v_std v = match v with
| Concrete _ -> V.pp O.hexa v
| Symbolic (Virtual {name=a;tag=None;cap=0L;offset=0;}) -> dump_addr a
| ConcreteVector _ -> V.pp O.hexa v
| Instruction _ -> Misc.lowercase (V.pp false v)
| Tag _
| Symbolic _
| Label _
| PteVal _
-> assert false
let dump_v_kvm v = match v with
| Symbolic (System (PTE,a)) -> sprintf "_vars->%s" (Misc.add_pte a)
| Symbolic (Physical (a,0)) -> sprintf "_vars->saved_%s" (Misc.add_pte a)
| _ -> V.pp_v v
let dump_v = match O. mode with
| Mode.Std -> dump_v_std
| Mode.PreSi|Mode.Kvm -> dump_v_kvm
let addr_cpy_name s p = sprintf "_addr_%s_%i" s p
end
| null | https://raw.githubusercontent.com/herd/herdtools7/6d781eb91debffdf56998171862a18e40908c3c5/litmus/outUtils.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
Some formating stuff
Value (address) output | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2014 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
Utilities for targets ( Out module )
open Printf
let fmt_out_reg proc str = sprintf "out_%i_%s" proc str
let fmt_index name = sprintf "%s[_i]" name
let fmt_presi_index name = sprintf "_log->%s" name
let fmt_presi_ptr_index name = sprintf "_log_ptr->%s" name
let fmt_code p = sprintf "code%i" p
let fmt_prelude p = sprintf "prelude%i" p
let fmt_code_size p = sprintf "code%i_sz" p
let fmt_lbl_offset p lbl = sprintf "off_P%i_%s" p lbl
let fmt_lbl_instr (p,lbl) = sprintf "instr_P%i_%s" p lbl
let fmt_lbl_instr_offset (p,lbl) = sprintf "off_instr_P%i_%s" p lbl
let fmt_lbl_var p lbl = sprintf "P%i_%s" p lbl
let fmt_pte_tag x = Misc.add_pte x
let fmt_pte_kvm x = sprintf "_vars->%s" (fmt_pte_tag x)
let fmt_phy_tag x = "saved_" ^ Misc.add_pte x
let fmt_phy_kvm x = sprintf "_vars->%s" (fmt_phy_tag x)
module type Config = sig
val memory : Memory.t
val hexa : bool
val mode : Mode.t
end
module DefaultConfig = struct
let memory = Memory.Direct
let hexa = false
end
module Make(O:Config)(V:Constant.S) = struct
open Memory
open Constant
let dump_addr a = match O.memory with
| Direct -> sprintf "&_a->%s[_i]" a
| Indirect -> sprintf "_a->%s[_i]" a
let dump_v_std v = match v with
| Concrete _ -> V.pp O.hexa v
| Symbolic (Virtual {name=a;tag=None;cap=0L;offset=0;}) -> dump_addr a
| ConcreteVector _ -> V.pp O.hexa v
| Instruction _ -> Misc.lowercase (V.pp false v)
| Tag _
| Symbolic _
| Label _
| PteVal _
-> assert false
let dump_v_kvm v = match v with
| Symbolic (System (PTE,a)) -> sprintf "_vars->%s" (Misc.add_pte a)
| Symbolic (Physical (a,0)) -> sprintf "_vars->saved_%s" (Misc.add_pte a)
| _ -> V.pp_v v
let dump_v = match O. mode with
| Mode.Std -> dump_v_std
| Mode.PreSi|Mode.Kvm -> dump_v_kvm
let addr_cpy_name s p = sprintf "_addr_%s_%i" s p
end
|
d964a85f3b57739d63dba3a2148a1906c02747712b37c0b8b85e5edbd34cf296 | onedata/op-worker | qos_downtree_status.erl | %%%-------------------------------------------------------------------
@author
( C ) 2021 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc
Module responsible for managing QoS status downtree ( top - down ) .
%%% For more details consult `qos_status` module doc.
%%% @end
%%%-------------------------------------------------------------------
-module(qos_downtree_status).
-author("Michal Stanisz").
-include("modules/datastore/qos.hrl").
-include("modules/datastore/datastore_models.hrl").
-include("modules/datastore/datastore_runner.hrl").
-include_lib("ctool/include/errors.hrl").
-include_lib("ctool/include/logging.hrl").
%% API
-export([
check/2
]).
-export([
report_started/3, report_finished/2,
report_file_transfer_failure/2,
report_file_deleted/3, report_entry_deleted/2
]).
-define(RECONCILE_LINK_NAME(Path, TraverseId), <<Path/binary, "###", TraverseId/binary>>).
-define(FAILED_TRANSFER_LINK_NAME(Path), <<Path/binary, "###failed_transfer">>).
-define(RECONCILE_LINKS_KEY(QosEntryId), <<"qos_status_reconcile", QosEntryId/binary>>).
%%%===================================================================
%%% API
%%%===================================================================
-spec check(file_ctx:ctx(), qos_entry:doc()) -> boolean().
check(FileCtx, QosDoc) ->
check_links(FileCtx, QosDoc) andalso check_traverses(FileCtx, QosDoc).
-spec report_started(traverse:id(), file_ctx:ctx(), [qos_entry:id()]) ->
ok | {error, term()}.
report_started(TraverseId, FileCtx, QosEntries) ->
SpaceId = file_ctx:get_space_id_const(FileCtx),
lists:foreach(fun(InternalFileCtx) ->
case get_uuid_based_path(InternalFileCtx) of
not_synced ->
% add to traverses list so status can be properly checked after all files on path are synced
% (for more details see check_traverses/2 and qos_status module doc).
lists:foreach(fun(QosEntryId) ->
ok = qos_entry:add_to_traverses_list(SpaceId, QosEntryId, TraverseId,
file_ctx:get_logical_uuid_const(InternalFileCtx))
end, QosEntries);
UuidBasedPath ->
Link = {?RECONCILE_LINK_NAME(UuidBasedPath, TraverseId), TraverseId},
lists:foreach(fun(QosEntryId) ->
ok = qos_status_links:add_link(SpaceId, ?RECONCILE_LINKS_KEY(QosEntryId), Link),
ok = qos_status_links:delete_link(SpaceId, ?RECONCILE_LINKS_KEY(QosEntryId),
?FAILED_TRANSFER_LINK_NAME(UuidBasedPath))
end, QosEntries)
end
end, list_references(FileCtx)).
-spec report_finished(traverse:id(), file_ctx:ctx()) -> ok | {error, term()}.
report_finished(TraverseId, FileCtx) ->
lists:foreach(fun(InternalFileCtx) ->
FileUuid = file_ctx:get_logical_uuid_const(InternalFileCtx),
QosEntries = case file_qos:get_effective(FileUuid) of
undefined -> [];
{error, {file_meta_missing, FileUuid}} -> [];
{error, _} = Error ->
?warning("Error after file ~p have been reconciled: ~p", [FileUuid, Error]),
[];
{ok, EffectiveFileQos} ->
file_qos:get_qos_entries(EffectiveFileQos)
end,
case get_uuid_based_path(InternalFileCtx) of
not_synced ->
ok; % link was never added, so no need to delete it
UuidBasedPath ->
lists:foreach(fun(QosEntryId) ->
ok = qos_status_links:delete_link(
file_ctx:get_space_id_const(InternalFileCtx),
?RECONCILE_LINKS_KEY(QosEntryId),
?RECONCILE_LINK_NAME(UuidBasedPath, TraverseId))
end, QosEntries)
end
end, list_references(FileCtx)).
-spec report_file_transfer_failure(file_ctx:ctx(), [qos_entry:id()]) ->
ok | {error, term()}.
report_file_transfer_failure(FileCtx, QosEntries) ->
SpaceId = file_ctx:get_space_id_const(FileCtx),
lists:foreach(fun(InternalFileCtx) ->
{UuidBasedPath, _} = file_ctx:get_uuid_based_path(InternalFileCtx),
Link = {?FAILED_TRANSFER_LINK_NAME(UuidBasedPath), <<"failed_transfer">>},
lists:foreach(fun(QosEntryId) ->
ok = qos_status_links:add_link(SpaceId, ?RECONCILE_LINKS_KEY(QosEntryId), Link)
end, QosEntries),
ok = qos_entry:add_to_failed_files_list(SpaceId, file_ctx:get_logical_uuid_const(InternalFileCtx))
end, list_references(FileCtx)).
-spec report_file_deleted(file_ctx:ctx(), qos_entry:doc(), file_ctx:ctx() | undefined) -> ok.
report_file_deleted(FileCtx, #document{key = QosEntryId} = QosEntryDoc, OriginalRootParentCtx) ->
{ok, SpaceId} = qos_entry:get_space_id(QosEntryDoc),
{UuidBasedPath, _} = file_ctx:get_uuid_based_path(FileCtx),
%% TODO VFS-7133 take original parent uuid from file_meta doc
UuidBasedPath2 = case filepath_utils:split(UuidBasedPath) of
Tokens = [<<"/">>, SpaceId, Token | Rest] ->
case fslogic_file_id:is_trash_dir_uuid(Token) andalso OriginalRootParentCtx =/= undefined of
true ->
{OriginalParentUuidBasedPath, _} = file_ctx:get_uuid_based_path(OriginalRootParentCtx),
filename:join([OriginalParentUuidBasedPath | Rest]);
false ->
filename:join(Tokens)
end;
TokensOutsideTrash ->
filename:join(TokensOutsideTrash)
end,
% delete all reconcile links for given file
qos_status_links:delete_all_local_links_with_prefix(
SpaceId, ?RECONCILE_LINKS_KEY(QosEntryId), UuidBasedPath2).
-spec report_entry_deleted(od_space:id(), qos_entry:id()) -> ok.
report_entry_deleted(SpaceId, QosEntryId) ->
% delete all reconcile links for given entry
qos_status_links:delete_all_local_links_with_prefix(
SpaceId, ?RECONCILE_LINKS_KEY(QosEntryId), <<"">>).
%%%===================================================================
Internal functions
%%%===================================================================
@private
-spec check_links(file_ctx:ctx(), qos_entry:doc()) -> boolean().
check_links(FileCtx, #document{key = QosEntryId}) ->
{UuidBasedPath, _} = file_ctx:get_uuid_based_path(FileCtx),
case qos_status_links:get_next_links(?RECONCILE_LINKS_KEY(QosEntryId), UuidBasedPath, 1, all) of
{ok, []} -> true;
{ok, [Path]} -> not str_utils:binary_starts_with(Path, UuidBasedPath)
end.
@private
-spec check_traverses(file_ctx:ctx(), qos_entry:doc()) -> boolean().
check_traverses(FileCtx, #document{key = QosEntryId}) ->
qos_entry:fold_traverses(QosEntryId, fun({_TraverseId, TraverseRootUuid}, Acc) ->
Acc andalso not is_traverse_in_subtree(FileCtx, TraverseRootUuid)
end, true).
@private
-spec is_traverse_in_subtree(file_ctx:ctx(), file_meta:uuid()) -> boolean().
is_traverse_in_subtree(SubtreeRootCtx, CheckedFileUuid) ->
SpaceId = file_ctx:get_space_id_const(SubtreeRootCtx),
lists:any(fun(InternalFileCtx) ->
case get_uuid_based_path(InternalFileCtx) of
not_synced ->
% no need to check as this subtree is disconnected from space root
false;
UuidBasedPath ->
lists:member(file_ctx:get_logical_uuid_const(SubtreeRootCtx), lists:droplast(filename:split(UuidBasedPath)))
end
end, list_references(file_ctx:new_by_uuid(CheckedFileUuid, SpaceId))).
@private
-spec get_uuid_based_path(file_ctx:ctx()) -> file_meta:uuid_based_path() | not_synced.
get_uuid_based_path(FileCtx) ->
try
{UuidBasedPath, _} = file_ctx:get_uuid_based_path(FileCtx),
UuidBasedPath
catch throw:{error, {file_meta_missing, _}} ->
not_synced
end.
@private
-spec list_references(file_ctx:ctx()) -> [file_ctx:ctx()].
list_references(FileCtx) ->
case file_ctx:list_references_ctx_const(FileCtx) of
{ok, References} -> References;
{error, not_found} -> []
end. | null | https://raw.githubusercontent.com/onedata/op-worker/4a305af02da4b510c4f5c41502d7500469762c4e/src/modules/qos/qos_status/qos_downtree_status.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc
For more details consult `qos_status` module doc.
@end
-------------------------------------------------------------------
API
===================================================================
API
===================================================================
add to traverses list so status can be properly checked after all files on path are synced
(for more details see check_traverses/2 and qos_status module doc).
link was never added, so no need to delete it
TODO VFS-7133 take original parent uuid from file_meta doc
delete all reconcile links for given file
delete all reconcile links for given entry
===================================================================
===================================================================
no need to check as this subtree is disconnected from space root | @author
( C ) 2021 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
Module responsible for managing QoS status downtree ( top - down ) .
-module(qos_downtree_status).
-author("Michal Stanisz").
-include("modules/datastore/qos.hrl").
-include("modules/datastore/datastore_models.hrl").
-include("modules/datastore/datastore_runner.hrl").
-include_lib("ctool/include/errors.hrl").
-include_lib("ctool/include/logging.hrl").
-export([
check/2
]).
-export([
report_started/3, report_finished/2,
report_file_transfer_failure/2,
report_file_deleted/3, report_entry_deleted/2
]).
-define(RECONCILE_LINK_NAME(Path, TraverseId), <<Path/binary, "###", TraverseId/binary>>).
-define(FAILED_TRANSFER_LINK_NAME(Path), <<Path/binary, "###failed_transfer">>).
-define(RECONCILE_LINKS_KEY(QosEntryId), <<"qos_status_reconcile", QosEntryId/binary>>).
-spec check(file_ctx:ctx(), qos_entry:doc()) -> boolean().
check(FileCtx, QosDoc) ->
check_links(FileCtx, QosDoc) andalso check_traverses(FileCtx, QosDoc).
-spec report_started(traverse:id(), file_ctx:ctx(), [qos_entry:id()]) ->
ok | {error, term()}.
report_started(TraverseId, FileCtx, QosEntries) ->
SpaceId = file_ctx:get_space_id_const(FileCtx),
lists:foreach(fun(InternalFileCtx) ->
case get_uuid_based_path(InternalFileCtx) of
not_synced ->
lists:foreach(fun(QosEntryId) ->
ok = qos_entry:add_to_traverses_list(SpaceId, QosEntryId, TraverseId,
file_ctx:get_logical_uuid_const(InternalFileCtx))
end, QosEntries);
UuidBasedPath ->
Link = {?RECONCILE_LINK_NAME(UuidBasedPath, TraverseId), TraverseId},
lists:foreach(fun(QosEntryId) ->
ok = qos_status_links:add_link(SpaceId, ?RECONCILE_LINKS_KEY(QosEntryId), Link),
ok = qos_status_links:delete_link(SpaceId, ?RECONCILE_LINKS_KEY(QosEntryId),
?FAILED_TRANSFER_LINK_NAME(UuidBasedPath))
end, QosEntries)
end
end, list_references(FileCtx)).
-spec report_finished(traverse:id(), file_ctx:ctx()) -> ok | {error, term()}.
report_finished(TraverseId, FileCtx) ->
lists:foreach(fun(InternalFileCtx) ->
FileUuid = file_ctx:get_logical_uuid_const(InternalFileCtx),
QosEntries = case file_qos:get_effective(FileUuid) of
undefined -> [];
{error, {file_meta_missing, FileUuid}} -> [];
{error, _} = Error ->
?warning("Error after file ~p have been reconciled: ~p", [FileUuid, Error]),
[];
{ok, EffectiveFileQos} ->
file_qos:get_qos_entries(EffectiveFileQos)
end,
case get_uuid_based_path(InternalFileCtx) of
not_synced ->
UuidBasedPath ->
lists:foreach(fun(QosEntryId) ->
ok = qos_status_links:delete_link(
file_ctx:get_space_id_const(InternalFileCtx),
?RECONCILE_LINKS_KEY(QosEntryId),
?RECONCILE_LINK_NAME(UuidBasedPath, TraverseId))
end, QosEntries)
end
end, list_references(FileCtx)).
-spec report_file_transfer_failure(file_ctx:ctx(), [qos_entry:id()]) ->
ok | {error, term()}.
report_file_transfer_failure(FileCtx, QosEntries) ->
SpaceId = file_ctx:get_space_id_const(FileCtx),
lists:foreach(fun(InternalFileCtx) ->
{UuidBasedPath, _} = file_ctx:get_uuid_based_path(InternalFileCtx),
Link = {?FAILED_TRANSFER_LINK_NAME(UuidBasedPath), <<"failed_transfer">>},
lists:foreach(fun(QosEntryId) ->
ok = qos_status_links:add_link(SpaceId, ?RECONCILE_LINKS_KEY(QosEntryId), Link)
end, QosEntries),
ok = qos_entry:add_to_failed_files_list(SpaceId, file_ctx:get_logical_uuid_const(InternalFileCtx))
end, list_references(FileCtx)).
-spec report_file_deleted(file_ctx:ctx(), qos_entry:doc(), file_ctx:ctx() | undefined) -> ok.
report_file_deleted(FileCtx, #document{key = QosEntryId} = QosEntryDoc, OriginalRootParentCtx) ->
{ok, SpaceId} = qos_entry:get_space_id(QosEntryDoc),
{UuidBasedPath, _} = file_ctx:get_uuid_based_path(FileCtx),
UuidBasedPath2 = case filepath_utils:split(UuidBasedPath) of
Tokens = [<<"/">>, SpaceId, Token | Rest] ->
case fslogic_file_id:is_trash_dir_uuid(Token) andalso OriginalRootParentCtx =/= undefined of
true ->
{OriginalParentUuidBasedPath, _} = file_ctx:get_uuid_based_path(OriginalRootParentCtx),
filename:join([OriginalParentUuidBasedPath | Rest]);
false ->
filename:join(Tokens)
end;
TokensOutsideTrash ->
filename:join(TokensOutsideTrash)
end,
qos_status_links:delete_all_local_links_with_prefix(
SpaceId, ?RECONCILE_LINKS_KEY(QosEntryId), UuidBasedPath2).
-spec report_entry_deleted(od_space:id(), qos_entry:id()) -> ok.
report_entry_deleted(SpaceId, QosEntryId) ->
qos_status_links:delete_all_local_links_with_prefix(
SpaceId, ?RECONCILE_LINKS_KEY(QosEntryId), <<"">>).
Internal functions
@private
-spec check_links(file_ctx:ctx(), qos_entry:doc()) -> boolean().
check_links(FileCtx, #document{key = QosEntryId}) ->
{UuidBasedPath, _} = file_ctx:get_uuid_based_path(FileCtx),
case qos_status_links:get_next_links(?RECONCILE_LINKS_KEY(QosEntryId), UuidBasedPath, 1, all) of
{ok, []} -> true;
{ok, [Path]} -> not str_utils:binary_starts_with(Path, UuidBasedPath)
end.
@private
-spec check_traverses(file_ctx:ctx(), qos_entry:doc()) -> boolean().
check_traverses(FileCtx, #document{key = QosEntryId}) ->
qos_entry:fold_traverses(QosEntryId, fun({_TraverseId, TraverseRootUuid}, Acc) ->
Acc andalso not is_traverse_in_subtree(FileCtx, TraverseRootUuid)
end, true).
@private
-spec is_traverse_in_subtree(file_ctx:ctx(), file_meta:uuid()) -> boolean().
is_traverse_in_subtree(SubtreeRootCtx, CheckedFileUuid) ->
SpaceId = file_ctx:get_space_id_const(SubtreeRootCtx),
lists:any(fun(InternalFileCtx) ->
case get_uuid_based_path(InternalFileCtx) of
not_synced ->
false;
UuidBasedPath ->
lists:member(file_ctx:get_logical_uuid_const(SubtreeRootCtx), lists:droplast(filename:split(UuidBasedPath)))
end
end, list_references(file_ctx:new_by_uuid(CheckedFileUuid, SpaceId))).
@private
-spec get_uuid_based_path(file_ctx:ctx()) -> file_meta:uuid_based_path() | not_synced.
get_uuid_based_path(FileCtx) ->
try
{UuidBasedPath, _} = file_ctx:get_uuid_based_path(FileCtx),
UuidBasedPath
catch throw:{error, {file_meta_missing, _}} ->
not_synced
end.
@private
-spec list_references(file_ctx:ctx()) -> [file_ctx:ctx()].
list_references(FileCtx) ->
case file_ctx:list_references_ctx_const(FileCtx) of
{ok, References} -> References;
{error, not_found} -> []
end. |
4936c0dcac09770544ded968c8c6ed89c9bf48bed15bf36391d0807486a7b33e | tschady/advent-of-code | d07.clj | (ns aoc.2020.d07
(:require [aoc.file-util :as file-util]
[loom.derived :refer [subgraph-reachable-from]]
[loom.graph :as loom :refer [successors weight transpose nodes]]))
(def input (file-util/read-lines "2020/d07.txt"))
(defn parse-rule [s]
(when (not (re-find #"no other" s))
(let [[[_ parent] & inner] (map rest (re-seq #"(\d+)? ?(\w+ \w+) bag" s))
children (->> inner
(map #(hash-map (second %) (Integer/parseInt (first %))))
(apply merge))]
{parent children})))
(defn build-graph [rules]
(apply loom/weighted-digraph (keep parse-rule rules)))
(defn nested-count [g node]
(reduce + 1 (map #(* (weight g node %) (nested-count g %)) (successors g node))))
(defn part-1 [input]
(-> input build-graph transpose (subgraph-reachable-from "shiny gold") nodes count dec))
(defn part-2 [input]
(-> input build-graph (nested-count "shiny gold") dec))
| null | https://raw.githubusercontent.com/tschady/advent-of-code/9cd0cbbbbeadd083b9030f21e49ca1ac26aee53a/src/aoc/2020/d07.clj | clojure | (ns aoc.2020.d07
(:require [aoc.file-util :as file-util]
[loom.derived :refer [subgraph-reachable-from]]
[loom.graph :as loom :refer [successors weight transpose nodes]]))
(def input (file-util/read-lines "2020/d07.txt"))
(defn parse-rule [s]
(when (not (re-find #"no other" s))
(let [[[_ parent] & inner] (map rest (re-seq #"(\d+)? ?(\w+ \w+) bag" s))
children (->> inner
(map #(hash-map (second %) (Integer/parseInt (first %))))
(apply merge))]
{parent children})))
(defn build-graph [rules]
(apply loom/weighted-digraph (keep parse-rule rules)))
(defn nested-count [g node]
(reduce + 1 (map #(* (weight g node %) (nested-count g %)) (successors g node))))
(defn part-1 [input]
(-> input build-graph transpose (subgraph-reachable-from "shiny gold") nodes count dec))
(defn part-2 [input]
(-> input build-graph (nested-count "shiny gold") dec))
| |
1ae14b89acd4acdd017a23f8cb6be76e2dd7bfaf164c7fc03f4efa32fef88bd4 | funcool/buddy-sign | jwe_tests.clj | Copyright 2014 - 2016 < >
;;
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 buddy.sign.jwe-tests
(:require [clojure.test :refer :all]
[clojure.test.check.clojure-test :refer (defspec)]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as props]
[clojure.string :as str]
[buddy.core.codecs :as codecs]
[buddy.core.crypto :as crypto]
[buddy.core.bytes :as bytes]
[buddy.core.nonce :as nonce]
[buddy.core.keys :as keys]
[buddy.sign.jwe :as jwe]
[buddy.sign.util :as util]))
(def secret (codecs/hex->bytes (str "000102030405060708090a0b0c0d0e0f"
"101112131415161718191a1b1c1d1e1f")))
(def data (codecs/to-bytes "test-data"))
(def key16 (nonce/random-bytes 16))
(def key24 (nonce/random-bytes 24))
(def key32 (nonce/random-bytes 32))
(def key32' (nonce/random-bytes 32))
(def key48 (nonce/random-bytes 48))
(def key64 (nonce/random-bytes 64))
(def rsa-privkey (keys/private-key "test/_files/privkey.3des.rsa.pem" "secret"))
(def rsa-pubkey (keys/public-key "test/_files/pubkey.3des.rsa.pem"))
(def ec-privkey (keys/private-key "test/_files/privkey.ecdsa.pem" "secret"))
(def ec-pubkey (keys/public-key "test/_files/pubkey.ecdsa.pem"))
(def rsa-algs
[:rsa-oaep :rsa-oaep-256 :rsa1_5])
(def encs
[:a128gcm :a192gcm :a256gcm :a128cbc-hs256
:a192cbc-hs384 :a256cbc-hs512])
;; --- Tests
(deftest jwe-decode-header
(let [candidate "foo bar"
encrypted (jwe/encrypt candidate secret)
header (jwe/decode-header encrypted)]
(is (= {:alg :dir, :enc :a128cbc-hs256} header))))
(deftest jwe-wrong-date-specific-test
(let [token (str "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.."
"zkV7_0---NDlvQYfpNDfqw.hECYr8zURDvz9hdjz6s-O0HNF2"
"MhgHgXjnQN6KuUcgE.eXYr6ybqAYcQkkkuGNcNKA")]
(try
(jwe/decrypt token key32 {:enc :a128cbc-hs256})
(throw (Exception. "unexpected"))
(catch clojure.lang.ExceptionInfo e
(let [cause (:cause (ex-data e))]
(is (= cause :authtag)))))))
(deftest wrong-key-for-enc
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a256gcm})))
(is (thrown? AssertionError (jwe/encrypt data key48 {:enc :a256gcm})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a192gcm})))
(is (thrown? AssertionError (jwe/encrypt data key32 {:enc :a192gcm})))
(is (thrown? AssertionError (jwe/encrypt data key32 {:enc :a128gcm})))
(is (thrown? AssertionError (jwe/encrypt data key48 {:enc :a128gcm})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a256cbc-hs512})))
(is (thrown? AssertionError (jwe/encrypt data key32 {:enc :a256cbc-hs512})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a192cbc-hs384})))
(is (thrown? AssertionError (jwe/encrypt data key32 {:enc :a192cbc-hs384})))
(is (thrown? AssertionError (jwe/encrypt data key64 {:enc :a192cbc-hs384})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a128cbc-hs256})))
(is (thrown? AssertionError (jwe/encrypt data key48 {:enc :a128cbc-hs256})))
(is (thrown? AssertionError (jwe/encrypt data key32 {:enc :a128gcm :alg :a128kw})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a128gcm :alg :a192kw})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a128gcm :alg :a256kw})))
)
(defspec jwe-spec-alg-dir-enc-a256gcm 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key32 {:enc :a256gcm :alg :dir :zip zip})
res2 (jwe/decrypt res1 key32 {:enc :a256gcm :alg :dir :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-dir-enc-a192gcm 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key24 {:enc :a192gcm :alg :dir :zip zip})
res2 (jwe/decrypt res1 key24 {:enc :a192gcm :alg :dir :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-dir-enc-a128gcm 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key16 {:enc :a128gcm :alg :dir :zip zip})
res2 (jwe/decrypt res1 key16 {:enc :a128gcm :alg :dir :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-dir-enc-a256cbc-hs512 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key64 {:enc :a256cbc-hs512 :zip zip})
res2 (jwe/decrypt res1 key64 {:enc :a256cbc-hs512 :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-dir-enc-a192cbc-hs384 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key48 {:enc :a192cbc-hs384 :zip zip})
res2 (jwe/decrypt res1 key48 {:enc :a192cbc-hs384 :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-dir-enc-a128cbc-hs256 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key32 {:enc :a128cbc-hs256 :zip zip})
res2 (jwe/decrypt res1 key32 {:enc :a128cbc-hs256 :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-wrong-data 500
(props/for-all
[data gen/string-ascii]
(try
(jwe/decrypt data secret)
(throw (Exception. "unexpected"))
(catch clojure.lang.ExceptionInfo e
(let [cause (:cause (ex-data e))]
(is (or (= cause :signature)
(= cause :header))))))))
(defspec jwe-spec-wrong-token 500
(props/for-all
[data1 gen/string-alphanumeric
data2 gen/string-alphanumeric
data3 gen/string-alphanumeric
data4 gen/string-alphanumeric
data5 gen/string-alphanumeric]
(let [data (str data1 "." data2 "." data3 "." data4 "." data5)]
(try
(jwe/decrypt data secret)
(throw (Exception. "unexpected"))
(catch clojure.lang.ExceptionInfo e
(let [cause (:cause (ex-data e))]
(is (or (= cause :signature)
(= cause :header)))))))))
;; (deftest jwe-spec-wrong-data
;; (try
( jwe / decrypt " > e31kI6Gr)u2#FGRtGOGeK6^GM:\\]OuUgR7Qwqs[`pUw^Ll ~ VC?V : ddTa%l@$&]/T%z<`[]6 [ " secret )
;; (throw (Exception. "unexpected"))
( catch clojure.lang . ExceptionInfo e
;; (let [cause (:cause (ex-data e))]
;; (is (or (= cause :signature)
;; (= cause :header)))))))
(defspec jwe-spec-alg-rsa 100
(props/for-all
[enc (gen/elements encs)
alg (gen/elements rsa-algs)
zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data rsa-pubkey {:enc enc :alg alg :zip zip})
res2 (jwe/decrypt res1 rsa-privkey {:enc enc :alg alg :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-a128kw 500
(props/for-all
[enc (gen/elements encs)
zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key16 {:enc enc :alg :a128kw :zip zip})
res2 (jwe/decrypt res1 key16 {:enc enc :alg :a128kw :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-a192kw 500
(props/for-all
[enc (gen/elements encs)
zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key24 {:enc enc :alg :a192kw :zip zip})
res2 (jwe/decrypt res1 key24 {:enc enc :alg :a192kw :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-a256kw 500
(props/for-all
[enc (gen/elements encs)
zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key32 {:enc enc :alg :a256kw :zip zip})
res2 (jwe/decrypt res1 key32 {:enc enc :alg :a256kw :zip zip})]
(is (bytes/equals? res2 data)))))
| null | https://raw.githubusercontent.com/funcool/buddy-sign/c1c7ffcd4b49d3604916736d15f03893e15e5814/test/buddy/sign/jwe_tests.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.
--- Tests
(deftest jwe-spec-wrong-data
(try
(throw (Exception. "unexpected"))
(let [cause (:cause (ex-data e))]
(is (or (= cause :signature)
(= cause :header))))))) | Copyright 2014 - 2016 < >
Licensed under the Apache License , Version 2.0 ( the " License " )
distributed under the License is distributed on an " AS IS " BASIS ,
(ns buddy.sign.jwe-tests
(:require [clojure.test :refer :all]
[clojure.test.check.clojure-test :refer (defspec)]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as props]
[clojure.string :as str]
[buddy.core.codecs :as codecs]
[buddy.core.crypto :as crypto]
[buddy.core.bytes :as bytes]
[buddy.core.nonce :as nonce]
[buddy.core.keys :as keys]
[buddy.sign.jwe :as jwe]
[buddy.sign.util :as util]))
(def secret (codecs/hex->bytes (str "000102030405060708090a0b0c0d0e0f"
"101112131415161718191a1b1c1d1e1f")))
(def data (codecs/to-bytes "test-data"))
(def key16 (nonce/random-bytes 16))
(def key24 (nonce/random-bytes 24))
(def key32 (nonce/random-bytes 32))
(def key32' (nonce/random-bytes 32))
(def key48 (nonce/random-bytes 48))
(def key64 (nonce/random-bytes 64))
(def rsa-privkey (keys/private-key "test/_files/privkey.3des.rsa.pem" "secret"))
(def rsa-pubkey (keys/public-key "test/_files/pubkey.3des.rsa.pem"))
(def ec-privkey (keys/private-key "test/_files/privkey.ecdsa.pem" "secret"))
(def ec-pubkey (keys/public-key "test/_files/pubkey.ecdsa.pem"))
(def rsa-algs
[:rsa-oaep :rsa-oaep-256 :rsa1_5])
(def encs
[:a128gcm :a192gcm :a256gcm :a128cbc-hs256
:a192cbc-hs384 :a256cbc-hs512])
(deftest jwe-decode-header
(let [candidate "foo bar"
encrypted (jwe/encrypt candidate secret)
header (jwe/decode-header encrypted)]
(is (= {:alg :dir, :enc :a128cbc-hs256} header))))
(deftest jwe-wrong-date-specific-test
(let [token (str "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.."
"zkV7_0---NDlvQYfpNDfqw.hECYr8zURDvz9hdjz6s-O0HNF2"
"MhgHgXjnQN6KuUcgE.eXYr6ybqAYcQkkkuGNcNKA")]
(try
(jwe/decrypt token key32 {:enc :a128cbc-hs256})
(throw (Exception. "unexpected"))
(catch clojure.lang.ExceptionInfo e
(let [cause (:cause (ex-data e))]
(is (= cause :authtag)))))))
(deftest wrong-key-for-enc
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a256gcm})))
(is (thrown? AssertionError (jwe/encrypt data key48 {:enc :a256gcm})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a192gcm})))
(is (thrown? AssertionError (jwe/encrypt data key32 {:enc :a192gcm})))
(is (thrown? AssertionError (jwe/encrypt data key32 {:enc :a128gcm})))
(is (thrown? AssertionError (jwe/encrypt data key48 {:enc :a128gcm})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a256cbc-hs512})))
(is (thrown? AssertionError (jwe/encrypt data key32 {:enc :a256cbc-hs512})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a192cbc-hs384})))
(is (thrown? AssertionError (jwe/encrypt data key32 {:enc :a192cbc-hs384})))
(is (thrown? AssertionError (jwe/encrypt data key64 {:enc :a192cbc-hs384})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a128cbc-hs256})))
(is (thrown? AssertionError (jwe/encrypt data key48 {:enc :a128cbc-hs256})))
(is (thrown? AssertionError (jwe/encrypt data key32 {:enc :a128gcm :alg :a128kw})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a128gcm :alg :a192kw})))
(is (thrown? AssertionError (jwe/encrypt data key16 {:enc :a128gcm :alg :a256kw})))
)
(defspec jwe-spec-alg-dir-enc-a256gcm 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key32 {:enc :a256gcm :alg :dir :zip zip})
res2 (jwe/decrypt res1 key32 {:enc :a256gcm :alg :dir :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-dir-enc-a192gcm 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key24 {:enc :a192gcm :alg :dir :zip zip})
res2 (jwe/decrypt res1 key24 {:enc :a192gcm :alg :dir :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-dir-enc-a128gcm 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key16 {:enc :a128gcm :alg :dir :zip zip})
res2 (jwe/decrypt res1 key16 {:enc :a128gcm :alg :dir :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-dir-enc-a256cbc-hs512 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key64 {:enc :a256cbc-hs512 :zip zip})
res2 (jwe/decrypt res1 key64 {:enc :a256cbc-hs512 :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-dir-enc-a192cbc-hs384 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key48 {:enc :a192cbc-hs384 :zip zip})
res2 (jwe/decrypt res1 key48 {:enc :a192cbc-hs384 :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-dir-enc-a128cbc-hs256 500
(props/for-all
[zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key32 {:enc :a128cbc-hs256 :zip zip})
res2 (jwe/decrypt res1 key32 {:enc :a128cbc-hs256 :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-wrong-data 500
(props/for-all
[data gen/string-ascii]
(try
(jwe/decrypt data secret)
(throw (Exception. "unexpected"))
(catch clojure.lang.ExceptionInfo e
(let [cause (:cause (ex-data e))]
(is (or (= cause :signature)
(= cause :header))))))))
(defspec jwe-spec-wrong-token 500
(props/for-all
[data1 gen/string-alphanumeric
data2 gen/string-alphanumeric
data3 gen/string-alphanumeric
data4 gen/string-alphanumeric
data5 gen/string-alphanumeric]
(let [data (str data1 "." data2 "." data3 "." data4 "." data5)]
(try
(jwe/decrypt data secret)
(throw (Exception. "unexpected"))
(catch clojure.lang.ExceptionInfo e
(let [cause (:cause (ex-data e))]
(is (or (= cause :signature)
(= cause :header)))))))))
( jwe / decrypt " > e31kI6Gr)u2#FGRtGOGeK6^GM:\\]OuUgR7Qwqs[`pUw^Ll ~ VC?V : ddTa%l@$&]/T%z<`[]6 [ " secret )
( catch clojure.lang . ExceptionInfo e
(defspec jwe-spec-alg-rsa 100
(props/for-all
[enc (gen/elements encs)
alg (gen/elements rsa-algs)
zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data rsa-pubkey {:enc enc :alg alg :zip zip})
res2 (jwe/decrypt res1 rsa-privkey {:enc enc :alg alg :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-a128kw 500
(props/for-all
[enc (gen/elements encs)
zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key16 {:enc enc :alg :a128kw :zip zip})
res2 (jwe/decrypt res1 key16 {:enc enc :alg :a128kw :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-a192kw 500
(props/for-all
[enc (gen/elements encs)
zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key24 {:enc enc :alg :a192kw :zip zip})
res2 (jwe/decrypt res1 key24 {:enc enc :alg :a192kw :zip zip})]
(is (bytes/equals? res2 data)))))
(defspec jwe-spec-alg-a256kw 500
(props/for-all
[enc (gen/elements encs)
zip gen/boolean
data gen/bytes]
(let [res1 (jwe/encrypt data key32 {:enc enc :alg :a256kw :zip zip})
res2 (jwe/decrypt res1 key32 {:enc enc :alg :a256kw :zip zip})]
(is (bytes/equals? res2 data)))))
|
4d508923c88547c4295ce2549165539f114c13ce984e1981e72a4df07418ce7d | argp/bap | batSys.ml |
* BatSys - additional and modified functions for System
* Copyright ( C ) 1996 Copyright ( C ) 2009 , LIFO , Universite d'Orleans
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* BatSys - additional and modified functions for System
* Copyright (C) 1996 Xavier Leroy
* Copyright (C) 2009 David Teller, LIFO, Universite d'Orleans
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
overridden by real big_endian value in 4.00 and above
include Sys
let files_of d = BatArray.enum (readdir d)
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/src/batSys.ml | ocaml |
* BatSys - additional and modified functions for System
* Copyright ( C ) 1996 Copyright ( C ) 2009 , LIFO , Universite d'Orleans
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* BatSys - additional and modified functions for System
* Copyright (C) 1996 Xavier Leroy
* Copyright (C) 2009 David Teller, LIFO, Universite d'Orleans
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
overridden by real big_endian value in 4.00 and above
include Sys
let files_of d = BatArray.enum (readdir d)
| |
ba97b835bbc16929d640c91f6b79384a727bf426fae9df2af63fbcc4055214e0 | reborg/clojure-essential-reference | 12.clj | (def m {:a [0 1 2 {:d 4 :e [0 1 2]}]})
< 1 >
(into (subvec v 0 idx)
(subvec v (inc idx) (count v))))
(defn dissoc-in [m [k & ks]]
(if ks
(assoc m k (dissoc-in (get m k) ks))
(cond
(map? m) (dissoc m k)
(vector? m) (remove-at m k)
< 2 >
(dissoc-in m [:a 3 :e 0]) ;<3>
{ : a [ 0 1 2 { : d 4 , : e [ 1 2 ] } ] } | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Maps/Processing/assoc%2Cassoc-inanddissoc/12.clj | clojure | <3> | (def m {:a [0 1 2 {:d 4 :e [0 1 2]}]})
< 1 >
(into (subvec v 0 idx)
(subvec v (inc idx) (count v))))
(defn dissoc-in [m [k & ks]]
(if ks
(assoc m k (dissoc-in (get m k) ks))
(cond
(map? m) (dissoc m k)
(vector? m) (remove-at m k)
< 2 >
{ : a [ 0 1 2 { : d 4 , : e [ 1 2 ] } ] } |
b26dfee2a7e1201a68f7509de632c7507ccc03ff5817ba7b6ad1c3c1b079197b | superbobry/pareto | test.ml | open OUnit
let all () = TestList [
Tests_test.test;
Sample_test.test;
Distributions_test.test
]
| null | https://raw.githubusercontent.com/superbobry/pareto/8b3b27bce7b7df5d9713d16ed40a844861aa368e/lib_test/test.ml | ocaml | open OUnit
let all () = TestList [
Tests_test.test;
Sample_test.test;
Distributions_test.test
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.