_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
|
---|---|---|---|---|---|---|---|---|
61d46abfc309a188a9221304985b6f62de718059bab7cc46398b14c061994e17 | namenu/advent-of-code | day04_test.clj | (ns aoc.year2018.day04-test
(:require [clojure.test :refer [deftest is]]
[aoc.year2018.day04 :refer [part1 part2]]
[aoc.util :refer [input-lines]]))
(deftest test-day4-sample
(let [input ["[1518-11-01 00:00] Guard #10 begins shift"
"[1518-11-01 00:05] falls asleep"
"[1518-11-01 00:25] wakes up"
"[1518-11-01 00:30] falls asleep"
"[1518-11-01 00:55] wakes up"
"[1518-11-01 23:58] Guard #99 begins shift"
"[1518-11-02 00:40] falls asleep"
"[1518-11-02 00:50] wakes up"
"[1518-11-03 00:05] Guard #10 begins shift"
"[1518-11-03 00:24] falls asleep"
"[1518-11-03 00:29] wakes up"
"[1518-11-04 00:02] Guard #99 begins shift"
"[1518-11-04 00:36] falls asleep"
"[1518-11-04 00:46] wakes up"
"[1518-11-05 00:03] Guard #99 begins shift"
"[1518-11-05 00:45] falls asleep"
"[1518-11-05 00:55] wakes up"]]
(is (= 240 (part1 input)))
(is (= 4455 (part2 input)))))
(deftest test-day4
(let [input (input-lines 2018 4)]
(is (= 63509 (part1 input)))
(is (= 47910 (part2 input)))))
(clojure.test/run-tests) | null | https://raw.githubusercontent.com/namenu/advent-of-code/83f8cf05931f814dab76696bf46fec1bb1276fac/2018/clojure/test/aoc/year2018/day04_test.clj | clojure | (ns aoc.year2018.day04-test
(:require [clojure.test :refer [deftest is]]
[aoc.year2018.day04 :refer [part1 part2]]
[aoc.util :refer [input-lines]]))
(deftest test-day4-sample
(let [input ["[1518-11-01 00:00] Guard #10 begins shift"
"[1518-11-01 00:05] falls asleep"
"[1518-11-01 00:25] wakes up"
"[1518-11-01 00:30] falls asleep"
"[1518-11-01 00:55] wakes up"
"[1518-11-01 23:58] Guard #99 begins shift"
"[1518-11-02 00:40] falls asleep"
"[1518-11-02 00:50] wakes up"
"[1518-11-03 00:05] Guard #10 begins shift"
"[1518-11-03 00:24] falls asleep"
"[1518-11-03 00:29] wakes up"
"[1518-11-04 00:02] Guard #99 begins shift"
"[1518-11-04 00:36] falls asleep"
"[1518-11-04 00:46] wakes up"
"[1518-11-05 00:03] Guard #99 begins shift"
"[1518-11-05 00:45] falls asleep"
"[1518-11-05 00:55] wakes up"]]
(is (= 240 (part1 input)))
(is (= 4455 (part2 input)))))
(deftest test-day4
(let [input (input-lines 2018 4)]
(is (= 63509 (part1 input)))
(is (= 47910 (part2 input)))))
(clojure.test/run-tests) |
|
5d15f360d22d38651ba4e0bda6e298eaa4429be7c006b65014727ee925f85c76 | composewell/streamly | Channel.hs | -- |
Module : Streamly . Internal . Data . Fold . Concurrent . Channel
Copyright : ( c ) 2022 Composewell Technologies
-- License : BSD-3-Clause
-- Maintainer :
-- Stability : experimental
Portability : GHC
module Streamly.Internal.Data.Fold.Concurrent.Channel
(
-- * Channel
Channel
-- * Configuration
, Config
, maxBuffer
, inspect
-- * Fold operations
, parEval
)
where
import Control.Concurrent (takeMVar)
import Control.Monad (void, when)
import Control.Monad.IO.Class (MonadIO(liftIO))
import Data.IORef (writeIORef)
import Streamly.Internal.Control.Concurrent (MonadAsync)
import Streamly.Internal.Data.Fold (Fold(..), Step (..))
import Streamly.Internal.Data.Stream.Channel.Worker (sendWithDoorBell)
import Streamly.Internal.Data.Time.Clock (Clock(Monotonic), getTime)
import Streamly.Internal.Data.Fold.Concurrent.Channel.Type
import Streamly.Internal.Data.Stream.Channel.Types
-------------------------------------------------------------------------------
Evaluating a Fold
-------------------------------------------------------------------------------
XXX Cleanup the fold if the stream is interrupted . Add a GC hook .
-- | Evaluate the fold asynchronously in a worker thread separate from the
-- driver thread.
--
# INLINABLE parEval #
parEval :: MonadAsync m => (Config -> Config) -> Fold m a b -> Fold m a b
parEval modifier f =
Fold step initial extract
where
initial = Partial <$> newChannel modifier f
-- XXX This is not truly asynchronous. If the fold is done we only get to
-- know when we send the next input unless the stream ends. We could
-- potentially throw an async exception to the driver to inform it
-- asynchronously. Alternatively, the stream should not block forever, it
-- should keep polling the fold status. We can insert a timer tick in the
-- input stream to do that.
--
-- A polled stream abstraction may be useful, it would consist of normal
-- events and tick events, latter are guaranteed to arrive.
step chan a = do
status <- sendToWorker chan a
return $ case status of
Nothing -> Partial chan
Just b -> Done b
extract chan = do
liftIO $ void
$ sendWithDoorBell
(outputQueue chan)
(outputDoorBell chan)
ChildStopChannel
status <- checkFoldStatus chan
case status of
Nothing -> do
liftIO
$ withDiagMVar
(svarInspectMode chan)
(dumpSVar chan)
"parEval: waiting to drain"
$ takeMVar (outputDoorBellFromConsumer chan)
-- XXX remove recursion
extract chan
Just b -> do
when (svarInspectMode chan) $ liftIO $ do
t <- getTime Monotonic
writeIORef (svarStopTime (svarStats chan)) (Just t)
printSVar (dumpSVar chan) "SVar Done"
return b
| null | https://raw.githubusercontent.com/composewell/streamly/c2f79142411383e14d8c7db0f2456775549925f0/src/Streamly/Internal/Data/Fold/Concurrent/Channel.hs | haskell | |
License : BSD-3-Clause
Maintainer :
Stability : experimental
* Channel
* Configuration
* Fold operations
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| Evaluate the fold asynchronously in a worker thread separate from the
driver thread.
XXX This is not truly asynchronous. If the fold is done we only get to
know when we send the next input unless the stream ends. We could
potentially throw an async exception to the driver to inform it
asynchronously. Alternatively, the stream should not block forever, it
should keep polling the fold status. We can insert a timer tick in the
input stream to do that.
A polled stream abstraction may be useful, it would consist of normal
events and tick events, latter are guaranteed to arrive.
XXX remove recursion | Module : Streamly . Internal . Data . Fold . Concurrent . Channel
Copyright : ( c ) 2022 Composewell Technologies
Portability : GHC
module Streamly.Internal.Data.Fold.Concurrent.Channel
(
Channel
, Config
, maxBuffer
, inspect
, parEval
)
where
import Control.Concurrent (takeMVar)
import Control.Monad (void, when)
import Control.Monad.IO.Class (MonadIO(liftIO))
import Data.IORef (writeIORef)
import Streamly.Internal.Control.Concurrent (MonadAsync)
import Streamly.Internal.Data.Fold (Fold(..), Step (..))
import Streamly.Internal.Data.Stream.Channel.Worker (sendWithDoorBell)
import Streamly.Internal.Data.Time.Clock (Clock(Monotonic), getTime)
import Streamly.Internal.Data.Fold.Concurrent.Channel.Type
import Streamly.Internal.Data.Stream.Channel.Types
Evaluating a Fold
XXX Cleanup the fold if the stream is interrupted . Add a GC hook .
# INLINABLE parEval #
parEval :: MonadAsync m => (Config -> Config) -> Fold m a b -> Fold m a b
parEval modifier f =
Fold step initial extract
where
initial = Partial <$> newChannel modifier f
step chan a = do
status <- sendToWorker chan a
return $ case status of
Nothing -> Partial chan
Just b -> Done b
extract chan = do
liftIO $ void
$ sendWithDoorBell
(outputQueue chan)
(outputDoorBell chan)
ChildStopChannel
status <- checkFoldStatus chan
case status of
Nothing -> do
liftIO
$ withDiagMVar
(svarInspectMode chan)
(dumpSVar chan)
"parEval: waiting to drain"
$ takeMVar (outputDoorBellFromConsumer chan)
extract chan
Just b -> do
when (svarInspectMode chan) $ liftIO $ do
t <- getTime Monotonic
writeIORef (svarStopTime (svarStats chan)) (Just t)
printSVar (dumpSVar chan) "SVar Done"
return b
|
7974455d449197fd5b848500f7906fffd064fa7bdcf11cf17d641f036e4ed107 | jakemcc/sicp-study | exercise1.8.clj | exercise 1.8
(defn diff-between [first second]
(Math/abs (- first second)))
(defn good-enough? [first second]
(< (diff-between first second) (* 0.001 second)))
(defn square [x] (* x x))
(defn improve [guess x]
(/ (+ (/ x (square guess)) (* 2.0 guess)) 3))
(defn cube-root [x]
(let [cube-root-iter (fn [prev-guess curr-guess]
(if (good-enough? prev-guess curr-guess)
curr-guess
(recur curr-guess (improve curr-guess x) )))]
(cube-root-iter 0 1.0)))
(println (cube-root 9))
; Do it using (loop)
(defn cube-root [x]
(loop [prev-guess 0 curr-guess 1.0]
(if (good-enough? prev-guess curr-guess)
curr-guess
(recur curr-guess (improve curr-guess x)))))
(println (cube-root 9))
user= > ( cube - root 9 )
2.0800838232385224
| null | https://raw.githubusercontent.com/jakemcc/sicp-study/3b9e3d6c8cc30ad92b0d9bbcbbbfe36a8413f89d/clojure/section1.1/exercise1.8.clj | clojure | Do it using (loop) | exercise 1.8
(defn diff-between [first second]
(Math/abs (- first second)))
(defn good-enough? [first second]
(< (diff-between first second) (* 0.001 second)))
(defn square [x] (* x x))
(defn improve [guess x]
(/ (+ (/ x (square guess)) (* 2.0 guess)) 3))
(defn cube-root [x]
(let [cube-root-iter (fn [prev-guess curr-guess]
(if (good-enough? prev-guess curr-guess)
curr-guess
(recur curr-guess (improve curr-guess x) )))]
(cube-root-iter 0 1.0)))
(println (cube-root 9))
(defn cube-root [x]
(loop [prev-guess 0 curr-guess 1.0]
(if (good-enough? prev-guess curr-guess)
curr-guess
(recur curr-guess (improve curr-guess x)))))
(println (cube-root 9))
user= > ( cube - root 9 )
2.0800838232385224
|
dd1ec8008a810f06d07e402965edbefb8ec16fea6f9dea7561c03f72f96b4c09 | nikita-volkov/rebase | Lift.hs | module Rebase.Control.Applicative.Lift
(
module Control.Applicative.Lift
)
where
import Control.Applicative.Lift
| null | https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Control/Applicative/Lift.hs | haskell | module Rebase.Control.Applicative.Lift
(
module Control.Applicative.Lift
)
where
import Control.Applicative.Lift
|
|
2410a334afbcffb985d5c075298492c5e96f7b5e00125260a076a2ce4c4c289a | openbadgefactory/salava | data.clj | (ns salava.user.data
(:require
[yesql.core :refer [defqueries]]
[salava.user.db :as u]
[salava.badge.main :as b]
[salava.page.main :as p]
[salava.file.db :as f]
[salava.social.db :as so]
[salava.location.db :as loc]
[salava.core.helper :refer [dump]]
[salava.core.util :as util]
[clj-pdf.core :as pdf]
[clj-pdf-markdown.core :refer [markdown->clj-pdf]]
[salava.core.time :refer [unix-time date-from-unix-time]]
[clojure.string :refer [ends-with? join capitalize blank? lower-case upper-case]]
[clojure.zip :as zip]
[net.cgrand.enlive-html :as enlive]
[salava.core.i18n :refer [t translate-text]]
[salava.user.schemas :refer [contact-fields]]
[salava.badge.pdf :refer [replace-nils process-markdown]]
[salava.badge.endorsement :refer [all-user-endorsements]]))
(defqueries "sql/badge/main.sql")
(defqueries "sql/badge/endorsement.sql")
(defqueries "sql/social/queries.sql")
(defqueries "sql/admin/queries.sql")
(defqueries "sql/location/queries.sql")
(defn- request-event-map [ctx request-id user-id md?]
(let [{:keys [user_badge_id content]} (select-request-by-request-id {:id request-id} (into {:result-set-fn first} (util/get-db ctx)))
badge-info (when user_badge_id (b/get-badge ctx user_badge_id user-id))]
(if (and user_badge_id name content) {:object_name (-> badge-info :content first :name) :content (if md? (util/md->html content) content) :badge_id user_badge_id} nil)))
(defn- endorsement-event-map [ctx endorsement-id user-id md?]
(let [{:keys [user_badge_id name content]} (select-endorsement-event-info-by-endorsement-id {:id endorsement-id} (into {:result-set-fn first} (util/get-db ctx)))]
(if (and user_badge_id name content) {:object_name name :content (if md? (util/md->html content) content) :badge_id user_badge_id} nil)))
(defn- create-selfie-event-map [ctx selfie_id user-id]
(let [f (first (util/plugin-fun (util/get-plugins ctx) "db" "user-selfie-badge"))
selfie (if (ifn? f) (some->> (f ctx user-id selfie_id) first) {})]
{:object_name (:name selfie) :selfie_id selfie_id}))
(defn events-helper [ctx event user-id md?]
(let [badge-info (select-multi-language-badge-content {:id (:object event)} (util/get-db ctx))
badge-id (select-user-badge-id-by-badge-id-and-user-id {:id (:id event)} (util/get-db ctx))
get-badge (b/fetch-badge ctx (:id badge-id))
user-info (u/user-information ctx (:object event))
user-badge-info (b/fetch-badge ctx (:object event))
message (select-message-by-badge-id-and-user-id {:badge_id (:object event) :user_id user-id :ctime (:ctime event)} (util/get-db ctx))
page-info (p/page-with-blocks ctx (:object event))
request-info (when (= "request_endorsement" (:verb event)) (request-event-map ctx (:object event) user-id md?))
endorsement-info (when (= "endorse_badge" (:verb event)) (endorsement-event-map ctx (:object event) user-id md?))]
(cond
(and (= (:verb event) "follow") (= (:type event) "badge")) {:object_name (:name (first badge-info)) :badge_id (:id badge-id)}
(and (= (:verb event) "follow") (= (:type event) "user")) {:object_name (str (:first_name user-info) " " (:last_name user-info)) :id (:object event)}
(and (= (:verb event) "congratulate") (= (:type event) "badge")) {:object_name (:name (first (:content user-badge-info))) :badge_id (:object event)}
(and (= (:verb event) "message") (= (:type event) "badge")) {:object_name (:name (first badge-info)) :badge_id badge-id :message (first message)}
(and (= (:verb event) "publish") (= (:type event) "badge")) {:object_name (:name (first (:content user-badge-info))) :badge_id (:object event)}
(and (= (:verb event) "unpublish") (= (:type event) "badge")) {:object_name (:name (first (:content user-badge-info))) :badge_id (:object event)}
(and (= (:verb event) "publish") (= (:type event) "page")) {:object_name (:name page-info) :page_id (:id page-info)}
(and (= (:verb event) "unpublish") (= (:type event) "page")) {:object_name (:name page-info) :page_id (:id page-info)}
(and (= (:verb event) "request_endorsement") (= (:type event) "badge")) request-info
(and (= (:verb event) "endorse_badge") (= (:type event) "badge")) endorsement-info
(and (= (:verb event) "issue") (= (:type event) "selfie")) {:object_name (:name (first (:content user-badge-info))) :badge_id (:object event)}
(and (= (:verb event) "create") (= (:type event) "selfie")) (create-selfie-event-map ctx (:object event) user-id)
(and (= (:verb event) "modify") (= (:type event) "selfie")) (create-selfie-event-map ctx (:object event) user-id)
:else nil)))
(defn all-user-data
([ctx user-id current-user-id]
(let [all-user-info (u/user-information-and-profile ctx user-id current-user-id)
email-addresses (u/email-addresses ctx current-user-id)
user-badges (b/user-badges-all ctx current-user-id)
user-pages (p/user-pages-all ctx current-user-id)
user-files (f/user-files-all ctx current-user-id)
events (map #(-> %
(assoc :info (events-helper ctx % user-id false))) (so/get-all-user-events ctx user-id))
connections (so/get-connections-badge ctx current-user-id)
endorsements (-> (all-user-endorsements ctx user-id true))
pending-badges (b/user-badges-pending ctx user-id)
user-followers-fn (first (util/plugin-fun (util/get-plugins ctx) "db" "get-user-followers-connections"))
user-followers (if-not (nil? user-followers-fn) (user-followers-fn ctx user-id) nil)
user-following-fn (first (util/plugin-fun (util/get-plugins ctx) "db" "get-user-following-connections-user"))
user-following (if-not (nil? user-followers-fn) (user-following-fn ctx user-id) nil)
user-location (-> (select-user-location {:user current-user-id} (into {:result-set-fn first} (util/get-db ctx))))
selfie-badges (as-> (first (util/plugin-fun (util/get-plugins ctx) "db" "user-selfie-badges")) $
(if (ifn? $) ($ ctx user-id)))]
(assoc (replace-nils (assoc all-user-info
:emails email-addresses
:user_badges user-badges
:user_pages user-pages
:user_files (:files user-files)
;:events events
:connections connections
:endorsements endorsements
:pending_badges pending-badges
:user_followers user-followers
:user_following user-following
:location user-location
:selfies selfie-badges))
:events events)))
([ctx user-id current-user-id _]
(let [all-user-info (u/user-information-and-profile ctx user-id current-user-id)
email-addresses (u/email-addresses ctx current-user-id)
user-badges (map (fn [b]
{:id (:id b)
:badge_id (:badge_id b)
:name (:name b)})(some->> (b/user-badges-all ctx current-user-id) :badges))
pending-badges (map (fn [pb]
{:name (:name pb)
:description (:description pb)}) (b/user-badges-pending ctx user-id))
user-pages (map (fn [p]
{:id (:id p)
:name (:name p)})(p/user-pages-all ctx current-user-id))
user-files (map (fn [f]
{:name (:name f)
:path (:path f)}) (:files (f/user-files-all ctx current-user-id)))
events (map #(-> %
(assoc :info (events-helper ctx % user-id true))) (so/get-all-user-events ctx user-id))
connections (count (so/get-connections-badge ctx current-user-id))
endorsements (-> (all-user-endorsements ctx user-id) :all-endorsements count)
user-followers-fn (first (util/plugin-fun (util/get-plugins ctx) "db" "get-user-followers-connections"))
user-followers (if-not (nil? user-followers-fn) (user-followers-fn ctx user-id) ())
user-following-fn (first (util/plugin-fun (util/get-plugins ctx) "db" "get-user-following-connections-user"))
user-following (if-not (nil? user-followers-fn) (user-following-fn ctx user-id) ())
user-location (-> (select-user-location {:user current-user-id} (into {:result-set-fn first} (util/get-db ctx))))
selfie-badges (as-> (first (util/plugin-fun (util/get-plugins ctx) "db" "user-selfie-badges")) $
(if (ifn? $)
(some->> ($ ctx user-id)
(map (fn [s] {:id (:id s)
:name (:name s)
:image (:image s)
:description (:description s)
:criteria (:criteria_html s)
:tags (or (:tags s) [])})))
[]))]
(replace-nils (assoc all-user-info
:emails email-addresses
:user_badges user-badges
:user_pages user-pages
:user_files user-files
:events events
:connections connections
:pending_badges pending-badges
:user_followers user-followers
:user_following user-following
:endorsements endorsements
:location user-location
:selfies selfie-badges)))))
(defn strip-html-tags [s]
(->> s
java.io.StringReader.
enlive/html-resource
first
zip/xml-zip
(iterate zip/next)
(take-while (complement zip/end?))
(filter (complement zip/branch?))
(map zip/node)
(apply str)))
(defn export-data-to-pdf [ctx user-id current-user-id]
(let [data-dir (get-in ctx [:config :core :data-dir])
site-url (get-in ctx [:config :core :site-url])
user-data (conj () (all-user-data ctx user-id current-user-id))
ul (let [lang (get-in (first user-data) [:user :language])]
(if (= "-" lang) "en" lang))
font-path (first (mapcat #(get-in ctx [:config % :font] []) (util/get-plugins ctx)))
font {:ttf-name (str site-url font-path)}
stylesheet {:heading-name {:color [127 113 121]
:family :times-roman
:align :center}
:generic {:family :times-roman
:color [127 113 121]
:indent 20}
:link {:family :times-roman
:color [66 100 162]}
:chunk {:size 11
:style :bold}
:small-heading {:size 13 :style :bold}}
pdf-settings (if (empty? font-path) {:stylesheet stylesheet :bottom-margin 0 :footer {:page-numbers false :align :right}} {:font font :stylesheet stylesheet :bottom-margin 0 :footer {:page-numbers false :align :right}})
user-info-template (pdf/template
(let [template (cons [:paragraph]
[[:heading.heading-name
(str (capitalize (:first_name $user)) " " (capitalize (:last_name $user)))]
[:spacer 2]
[:paragraph.generic
[:chunk.chunk (str (t :user/UserID ul)": ")] [:chunk (str (:id $user))]"\n"
[:chunk.chunk (str (t :user/Role ul) ": ")] [:chunk (if (= "user" (:role $user)) (t :social/User ul) (t :admin/Admin ul))]"\n"
[:chunk.chunk (str (t :user/Firstname ul)": ")] [:chunk (capitalize (:first_name $user))]"\n"
[:chunk.chunk (str (t :user/Lastname ul)": ")][:chunk (capitalize (:last_name $user))]"\n"
[:chunk.chunk (str (t :user/Profilepicture ul)": ")] [:anchor {:target (str site-url "/" (:profile_picture $user))} [:chunk.link (str site-url "/" (:profile_picture $user))]]"\n"
[:chunk.chunk (str (t :user/Language ul)": ")][:chunk (str (upper-case (:language $user)) " ")]
[:chunk.chunk (str (t :user/Country ul)": ")][:chunk (str (:country $user))]"\n"
[:chunk.chunk (str (t :user/Activated ul) ": ")][:chunk (str (if (true? (:activated $user)) (t :core/Yes ul) (t :core/No ul)) " ")]
[:chunk.chunk (str (t :user/Emailnotifications ul) ": ")][:chunk (str (if (true? (:email_notifications $user)) (t :core/Yes ul) (t :core/No ul)) " ")]
[:chunk.chunk (str (t :user/Profilevisibility ul) ": ")][:chunk (t (keyword (str "core/"(capitalize (:profile_visibility $user)))) ul)]"\n"
(when-not (or (nil? $location) (= "-" $location))[:paragraph [:chunk.chunk (str (t :location/Location ul) ": ")][:chunk (str (:lat $location) "," (:lng $location))]])
(when-not (blank? (:about $user))[:paragraph
[:chunk.chunk (str (t :user/Aboutme ul) ":")]"\n"
[:paragraph (str (:about $user))]])]
[:spacer 2]])]
template))
email-template (pdf/template
[:paragraph.generic
(if (> (count $emails) 1) [:heading.heading-name (t :user/Emailaddresses ul)] [:heading.heading-name (t :user/Emailaddress ul)])
[:spacer 0]
(into [:paragraph]
(for [e $emails
:let [primary-address (:primary_address e)]]
[:paragraph
[:chunk.chunk (str (t :user/Emailaddress ul)": ")] [:chunk (:email e)]"\n"
[:chunk.chunk (str (t :social/Created ul) ": ")] [:chunk (if (number? (:ctime e)) (str (date-from-unix-time (long (* 1000 (:ctime e))) "date")" ") (str (:ctime e) " "))]
[:chunk.chunk (str (t :user/verified ul)": ")] [:chunk (str (if (true? (:verified e)) (t :core/Yes ul) (t :core/No ul)) " ")]
(when (= true primary-address)
[:phrase
[:chunk.chunk (str (t :user/Loginaddress ul)": ")] [:chunk (t :core/Yes ul)] "\n"])
[:chunk.chunk (str (t :user/BackpackID ul) ": ")][:chunk (str (:backpack_id e))]]))])
profile-template (pdf/template
[:paragraph.generic
(when (not-empty $profile)
[:paragraph.generic
[:heading.heading-name (t :user/Myprofile ul)]
[:spacer 0]
(into [:paragraph ] (for [p (sort-by :order $profile)
:let[ k (->> contact-fields
(filter #(= (:type %) (:field p)))
first
:key)]]
[:phrase
[:chunk.chunk (str (t k ul)": ")] [:chunk (str (:value p) " ")]]))])])
badge-template (pdf/template
[:paragraph.generic
(when-not (empty? $user_badges)
(into [:paragraph
[:spacer 0]
[:heading.heading-name (t :badge/Mybadges ul)]]
(for [b $user_badges
:let [more-badge-info (replace-nils (b/get-badge ctx (:id b) user-id))
content (:content more-badge-info)
congratulated? (:congratulated? more-badge-info)
message-count (so/get-badge-message-count ctx (:badge_id b) user-id)
messages (replace-nils (select-badge-messages {:badge_id (:badge_id b)} (util/get-db ctx)))
endorsements (replace-nils (select-badge-endorsements {:id (:badge_id b)} (util/get-db ctx)))
location (loc/user-badge-location ctx current-user-id (:id b))
template #(cons [:paragraph][[:paragraph
[:chunk.chunk (str (t :badge/BadgeID ul) ": ")][:chunk (str (or (:badge_id b ) "-"))]"\n"
[:chunk.chunk (str (t :badge/Name ul) ": ") ][:chunk (or (:name %) "-")]"\n"
[:chunk.chunk (str (t :page/Description ul) ": ")][:chunk (str (:description %))]"\n"
[:chunk.chunk (str (t :badge/Imagefile ul) ": ")] [:anchor {:target (str site-url "/"(:image_file %))} [:chunk.link (str site-url "/"(:image_file %))]]"\n"
[:chunk.chunk (str (t :badge/Issuedby ul) ": ")] [:chunk (str (:issuer_content_name %)" ")]
[:chunk.chunk (str (t :badge/Issuerurl ul) ": ")] [:anchor {:target (str (:issuer_content_url %))} [:chunk.link (str (:issuer_content_url %))]]"\n"
[:chunk.chunk (str (t :badge/Issuercontact ul) ": ")] [:chunk.link (str (:issuer_contact %))]"\n"
(when-not (= "-" (:creator_name %))
[:phrase
[:chunk.chunk (str (t :badge/Createdby ul) ": ")][:chunk (str (:creator_name %))]"\n"])
(when-not (= "-" (:creator_url %))
[:phrase
[:chunk.chunk (str (t :badge/Creatorurl ul) ": ")][:chunk.link (str (:creator_url %))]"\n"])
(when-not (= "-" (:creator_email %))
[:phrase
[:chunk.chunk (str (t :badge/Creatorcontact ul) ": ")] [:chunk.link (str (:creator_email %))]"\n"])
[:chunk.chunk (str (t :badge/Criteriaurl ul) ": ") ] [:anchor {:target (str (:criteria_url %))} [:chunk.link (str (:criteria_url %))]]"\n"
[:paragraph
[:chunk.chunk (str (t :badge/Criteria ul) ": ")][:paragraph (strip-html-tags (:criteria_content %))]"\n"]
(when-not (blank? (:status b)) [:phrase [:chunk.chunk (str (t :user/Status ul) ": ")][:chunk (capitalize (str (t (keyword (str "social/"(:status b))) ul) " "))]])
(when-not (or (nil? location) (every? nil? (vals location))) [:phrase [:chunk.chunk (str (t :location/Location ul) ": ")] [:chunk (str (:lat location) "," (:lng location))] " "])
[:chunk.chunk (str (t :badge/Verifiedbyobf ul) ": ")][:chunk (str (if (true? (:verified_by_obf b)) (t :core/Yes ul) (t :core/No ul)) " ")]
[:chunk.chunk (str (t :badge/Issuedbyobf ul) ": ")][:chunk (str (if (true? (:issued_by_obf b)) (t :core/Yes ul) (t :core/No ul)))]"\n"
(when (not-empty (:tags b))
[:phrase
[:chunk.chunk (str (t :badge/Tags ul) ": ")] [:chunk (join ", " (:tags b))]"\n"])
[:chunk.chunk (str (t :badge/Issuedon ul) ": ")][:chunk (if (number? (:issued_on b))(str (date-from-unix-time (long (* 1000 (:issued_on b))) "date") " ") (str (:issued_on b) " "))]
[:chunk.chunk (str (t :badge/Expireson ul) ": ")][:chunk (if (number? (:expires_on b)) (date-from-unix-time (long (* 1000 (:expires_on b))) "date") (:expires_on b))]"\n"
[:chunk.chunk (str (t :badge/Issuerverified ul) ": ")] (if (== 0 (:issuer_verified b) ) [:chunk (str (t :core/No ul) " ")] [:chunk (str (t :core/Yes ul) " ")])
[:chunk.chunk (str (t :badge/Revoked ul) ": ")] [:chunk (str (if (true? (:revoked b)) (t :core/Yes ul) (t :core/No ul)) " ")]
[:chunk.chunk (str (t :badge/Badgevisibility ul) ": ")] [:chunk (t (keyword (str "core/" (capitalize (:visibility b)))) ul)]"\n"
[:chunk.chunk (str (t :badge/OBFurl ul) ": ")] [:anchor {:target (:obf_url b)} [:chunk.link (:obf_url b)]]"\n"
[:chunk.chunk (str (t :badge/Assertionurl ul) ": ")] [:anchor {:target (:assertion_url more-badge-info) } [:chunk.link (str (:assertion_url more-badge-info))]]"\n"
[:chunk.chunk (str (t :badge/Assertionjson ul) ": ")][:chunk (str (:assertion_json more-badge-info))]"\n"
[:chunk.chunk (str (t :badge/Badgerating ul) ": ") ] [:chunk (str (:rating more-badge-info) " ")]"\n"
( str ( t : badge / Evidenceurl ul ) " : " ) ] [: anchor { : target (: evidence_url more - badge - info ) } [: chunk.link ( str (: evidence_url more - badge - info ) " " ) ] ] " \n "
(when-not (empty? (:evidences more-badge-info))
[:paragraph
[:spacer]
[:chunk.chunk (str (t :badge/Evidence ul) ": " (count (:evidences more-badge-info)))]"\n"
(reduce (fn [r evidence]
(conj r [:paragraph
(when-not (blank? (:name evidence))[:phrase [:chunk.chunk (str (t :badge/Name ul) ": ")] [:chunk (:name evidence)]])"\n"
(when-not (blank? (:description evidence)) [:phrase [:chunk.chunk (str (t :admin/Description ul) ": ")][:chunk (:description evidence)]])"\n"
[:anchor {:target (:url evidence)}[:phrase [:chunk.chunk (str (t :admin/Url ul) ": ")] [:chunk.link (:url evidence)]]]
[:spacer 0]]) )[:paragraph] (:evidences more-badge-info))])
(when (not-empty (:alignment %))
[:paragraph
[:chunk.chunk (str (t :badge/Alignments ul) ": " (count (:alignment %)))]"\n"
(into [:paragraph]
(for [a (:alignment %)]
[:paragraph
[:chunk (:name a)]"\n"
[:chunk (:description a)]"\n"
[:chunk.link (:url a)]
[:spacer 0]]))])
[:chunk.chunk (str (t :badge/Viewed ul) ": ")] [:chunk (str (:view_count more-badge-info) " " (t :badge/times ul)" ")]", "
[:chunk.chunk (str (t :badge/Recipientcount ul) ": ")][:chunk (str (:recipient_count more-badge-info) " ")]", "
[:chunk.chunk (str (t :badge/Congratulated ul) "?: ")][:chunk (str (if (true? congratulated?) (t :core/Yes ul) (t :core/No ul))" ")]"\n"
(when-not (empty? (:congratulations more-badge-info))
[:paragraph
[:chunk.chunk (str (t :badge/Congratulations ul) ": ")]"\n"
[:paragraph
(into [:paragraph] (for [c (:congratulations more-badge-info)]
[:phrase
[:chunk (str (:first_name c) " " (:last_name c))] "\n"]))]])
(when (> (:endorsement_count %) 0) (blank? (str (:endorsement_count %)))
[:phrase
[:chunk.chunk (str (capitalize (t :badge/endorsements ul)) ": ")][:chunk (str (:endorsement_count %))]"\n"])
(when (not-empty endorsements)
(into [:paragraph {:indent 0}]
(for [e endorsements]
[:paragraph {:indent 0}
(:issuer_name e) "\n"
[:anchor {:target (:issuer_url e) :style{:family :times-roman :color [66 100 162]}} (:issuer_url e) ] "\n"
[:chunk (if (number? (:issued_on e)) (date-from-unix-time (long (* 1000 (:issued_on e)))) (:issued_on e))] "\n"
(process-markdown (:content e) (:badge_id b ) "Endorsements")])))
(when (> (:all-messages message-count) 0)
[:phrase
[:chunk.chunk (str (t :social/Messages ul) ": ")] [:chunk (str (:all-messages message-count))]"\n"])
(when (> (:all-messages message-count) 0)
(into [:paragraph]
(for [m messages]
[:paragraph
[:chunk(:message m)]"\n"
[:chunk (str (:first_name m) " " (:last_name m))]"\n"
[:chunk (if (number? (:ctime m)) (date-from-unix-time (long (* 1000 (:ctime m))) "date") (:ctime m))]
[:spacer 0]])))
[:chunk.chunk (str (t :social/Lastmodified ul) ": ")][:chunk (if (number? (:mtime b))(str (date-from-unix-time (long (* 1000 (:mtime b))) "date")" ") (str (:mtime b) " "))]
[:chunk.chunk (str (t :badge/URL ul) ": ")] [:anchor {:target (str site-url "/app/badge/info/" (:id b))} [:chunk.link {:style :italic} (str site-url "/app/badge/info/" (:id b))]]
[:spacer 1]]])]]
(reduce into [:paragraph] (-> (mapv template content)
(conj [[:line {:dotted true}]]))))))])
pending-badges-template (pdf/template
[:paragraph.generic
(when-not (empty? $pending_badges)
[:paragraph
[:heading.heading-name (t :badge/Pendingbadges ul)]
[:spacer 0]
(into [:paragraph]
(for [pb $pending_badges]
[:paragraph
[:chunk.chunk (str (t :badge/BadgeID ul) ": ")] [:chunk (str (:badge_id pb))]"\n"
[:chunk.chunk (str (t :badge/Name ul) ": ")] [:chunk (str (:name pb))]"\n"
[:chunk.chunk (str (t :page/Description ul) ": ")] [:chunk (str (:description pb))]"\n"
[:chunk.chunk (str (t :badge/Imagefile ul) ": ")] [:anchor {:target (str site-url "/" (:image_file pb))} [:chunk.link (str site-url "/" (:image_file pb)) ]]"\n"
[:chunk.chunk (str (t :badge/Assertionurl ul) ": ")] [:anchor {:target (:assertion_url pb)} [:chunk.link (:assertion_url pb) ]]"\n"
(when (not-empty (:tags pb))
[:phrase
[:chunk.chunk (str (t :badge/Tags ul) ": ")] [:chunk (join ", " (:tags pb))]"\n"])
[:chunk.chunk (str (t :badge/Badgevisibility ul) ": ")] [:chunk (t (keyword (str "core/" (capitalize (:visibility pb)))))]"\n"
[:chunk.chunk (str (t :badge/Issuedon ul) ": ")] [:chunk (if (number? (:issued_on pb)) (str (date-from-unix-time (long (* 1000 (:issued_on pb))) "date") ", ") (str (:issued_on pb) ", "))]
[:chunk.chunk (str (t :badge/Expireson ul) ": ")] [:chunk (if (number? (:expires_on pb)) (str (date-from-unix-time (long (* 1000 (:expires_on pb))) "date") ", ") (str (:expires_on pb) ", "))]]))])])
selfie-template (pdf/template
[:paragraph.generic
(when (seq $selfies)
[:paragraph
[:heading.heading-name (t :badgeIssuer/Selfiebadges ul)]
[:spacer]
(into [:paragraph]
(for [s $selfies]
[:paragraph
[:chunk.chunk (str (t :badge/BadgeID ul) ": ")] [:chunk (str (:id s))] "\n"
[:chunk.chunk (str (t :badge/Name ul) ": ")] [:chunk (str (:name s))]"\n"
[:chunk.chunk (str (t :page/Description ul) ": ")] [:chunk (str (:description s))]"\n"
[:chunk.chunk (str (t :badge/Imagefile ul) ": ")] [:anchor {:target (str site-url "/" (:image s))} [:chunk.link (str site-url "/" (:image s)) ]]"\n"
[:paragraph
[:chunk.chunk (str (t :badge/Criteria ul) ": ")][:paragraph (str (:criteria s))]] ;(process-markdown (:criteria s) (:id s) "Selfie badges")]"\n"]
(when (seq (:tags s))
[:phrase
[:chunk.chunk (str (t :badge/Tags ul) ": ")] [:chunk (join ", " (:tags s))]"\n"])
[:chunk.chunk (str (t :badgeIssuer/Issuableselfiebadge ul) ": ")] [:chunk (str (:issuable_from_gallery s))]
[:spacer 1]]))])])
page-template (pdf/template
[:paragraph.generic
(when-not (empty? $user_pages)
[:paragraph
[:heading.heading-name (t :page/Mypages ul)]
[:spacer 0]
(into [:paragraph]
(for [p $user_pages
:let [ page-owner? (p/page-owner? ctx (:id p) user-id)
page-blocks (p/page-blocks ctx (:id p))]]
[:paragraph
[:chunk.chunk (str (t :page/PageID ul) ": ")][:chunk (str (:id p))]"\n"
[:chunk.chunk (str (t :badge/Name ul) ": ")][:chunk (str (:name p))]"\n"
[:chunk.chunk (str (t :page/Owner ul) "?: ")][:chunk (if (= true page-owner?) (t :core/Yes ul) (t :core/No ul))] "\n"
[:chunk.chunk (str (t :page/Pagepassword ul) ": ")][:chunk (str (:password p))]"\n"
[:chunk.chunk (str (t :page/Description ul) ": ")][:chunk (str (:description p))]"\n"
[:chunk.chunk (str (t :social/Created ul) ": ")][:chunk (str (if (number? (:ctime p)) (date-from-unix-time (long (* 1000 (:ctime p))) "date") (:ctime p)) " ")]
[:chunk.chunk (str (t :social/Lastmodified ul) ": ")][:chunk (str (if (number? (:mtime p))(date-from-unix-time (long (* 1000 (:mtime p))) "date") (:mtime p)))]"\n"
(when (not-empty (:tags p))
[:phrase
[:chunk.chunk (str (t :badge/Tags ul) ": ")] [:chunk (join ", " (:tags p))]"\n"])
[:chunk.chunk (str (t :page/Theme ul) ": ")][:chunk (str (:theme p) " ")]
[:chunk.chunk (str (t :page/Border ul) ": ")][:chunk (str (:border p) " ")]
[:chunk.chunk (str (t :page/Padding ul) ": ")][:chunk (str (:padding p))]"\n"
[:spacer 1]
(when (not-empty page-blocks)
(into [:paragraph
[:phrase.chunk (t :page/Pageblocks ul)]
[:spacer 0]]
(for [pb page-blocks]
[:paragraph
(when (= "heading" (:type pb))
(case (:size pb)
"h1" [:phrase.generic {:align :left}
[:chunk.chunk (str (t :page/Heading ul)": ")] [:chunk (str (:content pb))]]
"h2" [:phrase.generic {:align :left}
[:chunk.chunk (str (t :page/Subheading ul) ": ")] [:chunk (str (:content pb))]]))
(when (= "badge" (:type pb))
[:phrase
[:phrase.chunk (str (t :badge/Badge ul) ": ")]
[:anchor {:target (str site-url "/app/badge/info/" (:badge_id pb))} [:chunk.link (str (:name pb))]]"\n"])
(when (= "html" (:type pb))
[:phrase
[:spacer 0]
[:phrase.chunk (str (t :page/Html ul) ": ")]
[:spacer 0]
(:content pb)])
(when (= "file" (:type pb))
[:paragraph
[:spacer 0]
[:phrase.chunk (str (t :file/Files ul) ": ")]"\n"
(into [:paragraph]
(for [file (:files pb)]
[:phrase
[:chunk.bold (str (t :badge/Name ul) ": ")] [:chunk (:name file)]"\n"
[:chunk.bold (str (t :badge/URL ul) ": ")][:anchor {:target (str site-url "/"(:path file)) :style{:family :times-roman :color [66 100 162]}} (str site-url "/"(:path file))]]))])
(when (= "tag" (:type pb))
[:paragraph
[:phrase.chunk (str (t :page/Badgegroup ul) ": ")]
[:spacer 0]
(into [:phrase ] (for [b (:badges pb)]
[:phrase
[:anchor {:target (str site-url "/app/badge/info/" (:id b))} [:chunk.link (str (:name b))]]"\n"]))])])))
[:line {:dotted true}] [:spacer 0]]))])])
user-connections-template (pdf/template
[:paragraph.generic
(when (or (not-empty $user_followers) (not-empty $user_following))
[:paragraph
[:heading.heading-name (str (t :user/Socialconnections ul) ": ")]
[:spacer 0]
(when-not (empty? $user_followers)
(into [:paragraph
[:phrase.chunk (str (t :social/Followersusers ul) ": ")] [:spacer 0]] (for [follower $user_followers
:let [follower-id (:owner_id follower)
fname (:first_name follower)
lname (:last_name follower)
status (:status follower)]]
[:paragraph
[:anchor {:target (str site-url "/app/user/profile/" follower-id)} [:chunk.link (str fname " " lname ", ")]]
[:chunk.chunk (str (t :user/Status ul) ": ")] [:chunk (str (t (keyword (str "social/"status)) ul))]])))
(when-not (empty? $user_following)
(into [:paragraph
[:phrase.chunk (str (t :social/Followedusers ul) ": ")][:spacer 0]] (for [f $user_following
:let [followee-id (:user_id f)
fname (:first_name f)
lname (:last_name f)
status (:status f)]]
[:paragraph
[:anchor {:target (str site-url "/app/user/profile/" followee-id)} [:chunk.link (str fname " " lname ", ")]]
[:chunk.chunk (str (t :user/Status ul) ": ")] [:chunk (str (t (keyword (str "social/"status)) ul))]])))])])
badge-connections-template (pdf/template
[:paragraph.generic
(when-not (empty? $connections)
[:paragraph
[:heading.heading-name (str (t :user/Badgeconnections ul) ": ")]
[:spacer 0]
(into [:paragraph]
(for [c $connections]
[:paragraph
[:chunk.chunk (str (t :badge/BadgeID ul) ": ")] [:chunk (str (:id c))]"\n"
[:chunk.chunk (str (t :badge/Name ul) ": ")][:chunk (str (:name c))]"\n"
[:chunk.chunk (str (t :page/Description ul) ": ")][:chunk (str (:description c))]"\n"
[:chunk.chunk (str (t :badge/Imagefile ul) ": ")][:anchor {:target (str site-url "/" (:image_file c))} [:chunk.link (str site-url "/" (:image_file c))]]"\n"]))])])
user-endorsements-template (pdf/template
[:paragraph.generic
(when-not (empty? $endorsements)
(let [{:keys [given received sent-requests]} $endorsements]
[:paragraph
[:heading.heading-name (str (t :badge/Myendorsements ul) ": ")]
[:spacer 0]
(when (seq given)
[:paragraph
[:chunk..small-heading (t :badge/Iendorsed ul)]
[:spacer 1]
(into [:paragraph] (for [g given
:let [name (str (:first_name g) " " (:last_name g))]]
[:paragraph
[:chunk name]"\n"
[:chunk.chunk (:name g)]"\n"
[:chunk (date-from-unix-time (long (* 1000 (:mtime g))) "date")]"\n"
(process-markdown (:content g) (:user_badge_id g) "User Endorsements")]))])
(when (seq received)
[:paragraph
[:chunk.small-heading (t :badge/Endorsedme ul)]
[:spacer 1]
(into [:paragraph] (for [r received
:let [name (str (:first_name r) " " (:last_name r))]]
[:paragraph
[:chunk (:issuer_name r)]"\n"
[:chunk.chunk (:name r)]"\n"
[:chunk (date-from-unix-time (long (* 1000 (:mtime r))) "date")]"\n"
(process-markdown (:content r) (:user_badge_id r) "User Endorsements")]))])
(when (seq sent-requests)
[:paragraph
[:chunk.small-heading (t :badge/Sentendorsementrequests ul)]
[:spacer 1]
(into [:paragraph] (for [sr sent-requests
:let [name (str (:first_name sr) " " (:last_name sr))]]
[:paragraph
[:chunk (:issuer_name sr)]"\n"
[:chunk.chunk (:name sr)]"\n"
[:chunk (date-from-unix-time (long (* 1000 (:mtime sr))) "date")]"\n"
(process-markdown (:content sr) (:user_badge_id sr) "User Endorsements")]))])]))])
events-template (pdf/template
(let [template (cons [:paragraph]
[[:paragraph.generic
(when-not (empty? $events)
[:heading.heading-name (t :user/Activityhistory ul)])]
(when-not (empty? $events)
(into [:table.generic {:header [(t :social/Action ul) (t :social/Object ul) (t :social/Objecttype ul) (t :social/Created ul)]}]
(for [e (->> (reverse $events) (remove (fn [e] (nil? (:info e)))))]
[[:cell (if-not (= "-" (:verb e)) (t (keyword (str "social/"(:verb e))) ul) "-")]
[:cell [:phrase
[:chunk (get-in e [:info :object_name])]"\n"
(if (contains? (:info e) :message)
[:chunk {:style :italic} (get-in e [:info :message :message])])
(when-not (blank? (get-in e [:info :content]))
[:chunk {:style :italic} (get-in e [:info :content])])]]
[:cell
(when-not (blank? (str (:type e)))
(cond
(= "page" (:type e)) (t :social/Emailpage ul)
(= "badge" (:type e)) (t :social/Emailbadge ul)
(= "user" (:type e)) (lower-case (t :social/User ul))
(= "admin" (:type e)) (lower-case (t :admin/Admin ul))
(= "selfie" (:type e)) (lower-case (t :badgeIssuer/Selfie ul))
:else "-"))]
[:cell (if (number? (:ctime e))(date-from-unix-time (long (* 1000 (:ctime e))) "date") (:ctime e))]])))])]
template))]
(fn [output-stream]
(pdf/pdf (into [pdf-settings] (concat (user-info-template user-data)
(email-template user-data)
(profile-template user-data)
(badge-template user-data)
(pending-badges-template user-data)
(selfie-template user-data)
(page-template user-data)
(user-connections-template user-data)
(badge-connections-template user-data)
(user-endorsements-template user-data)
(events-template user-data))) output-stream))))
| null | https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/src/clj/salava/user/data.clj | clojure | :events events
(process-markdown (:criteria s) (:id s) "Selfie badges")]"\n"] | (ns salava.user.data
(:require
[yesql.core :refer [defqueries]]
[salava.user.db :as u]
[salava.badge.main :as b]
[salava.page.main :as p]
[salava.file.db :as f]
[salava.social.db :as so]
[salava.location.db :as loc]
[salava.core.helper :refer [dump]]
[salava.core.util :as util]
[clj-pdf.core :as pdf]
[clj-pdf-markdown.core :refer [markdown->clj-pdf]]
[salava.core.time :refer [unix-time date-from-unix-time]]
[clojure.string :refer [ends-with? join capitalize blank? lower-case upper-case]]
[clojure.zip :as zip]
[net.cgrand.enlive-html :as enlive]
[salava.core.i18n :refer [t translate-text]]
[salava.user.schemas :refer [contact-fields]]
[salava.badge.pdf :refer [replace-nils process-markdown]]
[salava.badge.endorsement :refer [all-user-endorsements]]))
(defqueries "sql/badge/main.sql")
(defqueries "sql/badge/endorsement.sql")
(defqueries "sql/social/queries.sql")
(defqueries "sql/admin/queries.sql")
(defqueries "sql/location/queries.sql")
(defn- request-event-map [ctx request-id user-id md?]
(let [{:keys [user_badge_id content]} (select-request-by-request-id {:id request-id} (into {:result-set-fn first} (util/get-db ctx)))
badge-info (when user_badge_id (b/get-badge ctx user_badge_id user-id))]
(if (and user_badge_id name content) {:object_name (-> badge-info :content first :name) :content (if md? (util/md->html content) content) :badge_id user_badge_id} nil)))
(defn- endorsement-event-map [ctx endorsement-id user-id md?]
(let [{:keys [user_badge_id name content]} (select-endorsement-event-info-by-endorsement-id {:id endorsement-id} (into {:result-set-fn first} (util/get-db ctx)))]
(if (and user_badge_id name content) {:object_name name :content (if md? (util/md->html content) content) :badge_id user_badge_id} nil)))
(defn- create-selfie-event-map [ctx selfie_id user-id]
(let [f (first (util/plugin-fun (util/get-plugins ctx) "db" "user-selfie-badge"))
selfie (if (ifn? f) (some->> (f ctx user-id selfie_id) first) {})]
{:object_name (:name selfie) :selfie_id selfie_id}))
(defn events-helper [ctx event user-id md?]
(let [badge-info (select-multi-language-badge-content {:id (:object event)} (util/get-db ctx))
badge-id (select-user-badge-id-by-badge-id-and-user-id {:id (:id event)} (util/get-db ctx))
get-badge (b/fetch-badge ctx (:id badge-id))
user-info (u/user-information ctx (:object event))
user-badge-info (b/fetch-badge ctx (:object event))
message (select-message-by-badge-id-and-user-id {:badge_id (:object event) :user_id user-id :ctime (:ctime event)} (util/get-db ctx))
page-info (p/page-with-blocks ctx (:object event))
request-info (when (= "request_endorsement" (:verb event)) (request-event-map ctx (:object event) user-id md?))
endorsement-info (when (= "endorse_badge" (:verb event)) (endorsement-event-map ctx (:object event) user-id md?))]
(cond
(and (= (:verb event) "follow") (= (:type event) "badge")) {:object_name (:name (first badge-info)) :badge_id (:id badge-id)}
(and (= (:verb event) "follow") (= (:type event) "user")) {:object_name (str (:first_name user-info) " " (:last_name user-info)) :id (:object event)}
(and (= (:verb event) "congratulate") (= (:type event) "badge")) {:object_name (:name (first (:content user-badge-info))) :badge_id (:object event)}
(and (= (:verb event) "message") (= (:type event) "badge")) {:object_name (:name (first badge-info)) :badge_id badge-id :message (first message)}
(and (= (:verb event) "publish") (= (:type event) "badge")) {:object_name (:name (first (:content user-badge-info))) :badge_id (:object event)}
(and (= (:verb event) "unpublish") (= (:type event) "badge")) {:object_name (:name (first (:content user-badge-info))) :badge_id (:object event)}
(and (= (:verb event) "publish") (= (:type event) "page")) {:object_name (:name page-info) :page_id (:id page-info)}
(and (= (:verb event) "unpublish") (= (:type event) "page")) {:object_name (:name page-info) :page_id (:id page-info)}
(and (= (:verb event) "request_endorsement") (= (:type event) "badge")) request-info
(and (= (:verb event) "endorse_badge") (= (:type event) "badge")) endorsement-info
(and (= (:verb event) "issue") (= (:type event) "selfie")) {:object_name (:name (first (:content user-badge-info))) :badge_id (:object event)}
(and (= (:verb event) "create") (= (:type event) "selfie")) (create-selfie-event-map ctx (:object event) user-id)
(and (= (:verb event) "modify") (= (:type event) "selfie")) (create-selfie-event-map ctx (:object event) user-id)
:else nil)))
(defn all-user-data
([ctx user-id current-user-id]
(let [all-user-info (u/user-information-and-profile ctx user-id current-user-id)
email-addresses (u/email-addresses ctx current-user-id)
user-badges (b/user-badges-all ctx current-user-id)
user-pages (p/user-pages-all ctx current-user-id)
user-files (f/user-files-all ctx current-user-id)
events (map #(-> %
(assoc :info (events-helper ctx % user-id false))) (so/get-all-user-events ctx user-id))
connections (so/get-connections-badge ctx current-user-id)
endorsements (-> (all-user-endorsements ctx user-id true))
pending-badges (b/user-badges-pending ctx user-id)
user-followers-fn (first (util/plugin-fun (util/get-plugins ctx) "db" "get-user-followers-connections"))
user-followers (if-not (nil? user-followers-fn) (user-followers-fn ctx user-id) nil)
user-following-fn (first (util/plugin-fun (util/get-plugins ctx) "db" "get-user-following-connections-user"))
user-following (if-not (nil? user-followers-fn) (user-following-fn ctx user-id) nil)
user-location (-> (select-user-location {:user current-user-id} (into {:result-set-fn first} (util/get-db ctx))))
selfie-badges (as-> (first (util/plugin-fun (util/get-plugins ctx) "db" "user-selfie-badges")) $
(if (ifn? $) ($ ctx user-id)))]
(assoc (replace-nils (assoc all-user-info
:emails email-addresses
:user_badges user-badges
:user_pages user-pages
:user_files (:files user-files)
:connections connections
:endorsements endorsements
:pending_badges pending-badges
:user_followers user-followers
:user_following user-following
:location user-location
:selfies selfie-badges))
:events events)))
([ctx user-id current-user-id _]
(let [all-user-info (u/user-information-and-profile ctx user-id current-user-id)
email-addresses (u/email-addresses ctx current-user-id)
user-badges (map (fn [b]
{:id (:id b)
:badge_id (:badge_id b)
:name (:name b)})(some->> (b/user-badges-all ctx current-user-id) :badges))
pending-badges (map (fn [pb]
{:name (:name pb)
:description (:description pb)}) (b/user-badges-pending ctx user-id))
user-pages (map (fn [p]
{:id (:id p)
:name (:name p)})(p/user-pages-all ctx current-user-id))
user-files (map (fn [f]
{:name (:name f)
:path (:path f)}) (:files (f/user-files-all ctx current-user-id)))
events (map #(-> %
(assoc :info (events-helper ctx % user-id true))) (so/get-all-user-events ctx user-id))
connections (count (so/get-connections-badge ctx current-user-id))
endorsements (-> (all-user-endorsements ctx user-id) :all-endorsements count)
user-followers-fn (first (util/plugin-fun (util/get-plugins ctx) "db" "get-user-followers-connections"))
user-followers (if-not (nil? user-followers-fn) (user-followers-fn ctx user-id) ())
user-following-fn (first (util/plugin-fun (util/get-plugins ctx) "db" "get-user-following-connections-user"))
user-following (if-not (nil? user-followers-fn) (user-following-fn ctx user-id) ())
user-location (-> (select-user-location {:user current-user-id} (into {:result-set-fn first} (util/get-db ctx))))
selfie-badges (as-> (first (util/plugin-fun (util/get-plugins ctx) "db" "user-selfie-badges")) $
(if (ifn? $)
(some->> ($ ctx user-id)
(map (fn [s] {:id (:id s)
:name (:name s)
:image (:image s)
:description (:description s)
:criteria (:criteria_html s)
:tags (or (:tags s) [])})))
[]))]
(replace-nils (assoc all-user-info
:emails email-addresses
:user_badges user-badges
:user_pages user-pages
:user_files user-files
:events events
:connections connections
:pending_badges pending-badges
:user_followers user-followers
:user_following user-following
:endorsements endorsements
:location user-location
:selfies selfie-badges)))))
(defn strip-html-tags [s]
(->> s
java.io.StringReader.
enlive/html-resource
first
zip/xml-zip
(iterate zip/next)
(take-while (complement zip/end?))
(filter (complement zip/branch?))
(map zip/node)
(apply str)))
(defn export-data-to-pdf [ctx user-id current-user-id]
(let [data-dir (get-in ctx [:config :core :data-dir])
site-url (get-in ctx [:config :core :site-url])
user-data (conj () (all-user-data ctx user-id current-user-id))
ul (let [lang (get-in (first user-data) [:user :language])]
(if (= "-" lang) "en" lang))
font-path (first (mapcat #(get-in ctx [:config % :font] []) (util/get-plugins ctx)))
font {:ttf-name (str site-url font-path)}
stylesheet {:heading-name {:color [127 113 121]
:family :times-roman
:align :center}
:generic {:family :times-roman
:color [127 113 121]
:indent 20}
:link {:family :times-roman
:color [66 100 162]}
:chunk {:size 11
:style :bold}
:small-heading {:size 13 :style :bold}}
pdf-settings (if (empty? font-path) {:stylesheet stylesheet :bottom-margin 0 :footer {:page-numbers false :align :right}} {:font font :stylesheet stylesheet :bottom-margin 0 :footer {:page-numbers false :align :right}})
user-info-template (pdf/template
(let [template (cons [:paragraph]
[[:heading.heading-name
(str (capitalize (:first_name $user)) " " (capitalize (:last_name $user)))]
[:spacer 2]
[:paragraph.generic
[:chunk.chunk (str (t :user/UserID ul)": ")] [:chunk (str (:id $user))]"\n"
[:chunk.chunk (str (t :user/Role ul) ": ")] [:chunk (if (= "user" (:role $user)) (t :social/User ul) (t :admin/Admin ul))]"\n"
[:chunk.chunk (str (t :user/Firstname ul)": ")] [:chunk (capitalize (:first_name $user))]"\n"
[:chunk.chunk (str (t :user/Lastname ul)": ")][:chunk (capitalize (:last_name $user))]"\n"
[:chunk.chunk (str (t :user/Profilepicture ul)": ")] [:anchor {:target (str site-url "/" (:profile_picture $user))} [:chunk.link (str site-url "/" (:profile_picture $user))]]"\n"
[:chunk.chunk (str (t :user/Language ul)": ")][:chunk (str (upper-case (:language $user)) " ")]
[:chunk.chunk (str (t :user/Country ul)": ")][:chunk (str (:country $user))]"\n"
[:chunk.chunk (str (t :user/Activated ul) ": ")][:chunk (str (if (true? (:activated $user)) (t :core/Yes ul) (t :core/No ul)) " ")]
[:chunk.chunk (str (t :user/Emailnotifications ul) ": ")][:chunk (str (if (true? (:email_notifications $user)) (t :core/Yes ul) (t :core/No ul)) " ")]
[:chunk.chunk (str (t :user/Profilevisibility ul) ": ")][:chunk (t (keyword (str "core/"(capitalize (:profile_visibility $user)))) ul)]"\n"
(when-not (or (nil? $location) (= "-" $location))[:paragraph [:chunk.chunk (str (t :location/Location ul) ": ")][:chunk (str (:lat $location) "," (:lng $location))]])
(when-not (blank? (:about $user))[:paragraph
[:chunk.chunk (str (t :user/Aboutme ul) ":")]"\n"
[:paragraph (str (:about $user))]])]
[:spacer 2]])]
template))
email-template (pdf/template
[:paragraph.generic
(if (> (count $emails) 1) [:heading.heading-name (t :user/Emailaddresses ul)] [:heading.heading-name (t :user/Emailaddress ul)])
[:spacer 0]
(into [:paragraph]
(for [e $emails
:let [primary-address (:primary_address e)]]
[:paragraph
[:chunk.chunk (str (t :user/Emailaddress ul)": ")] [:chunk (:email e)]"\n"
[:chunk.chunk (str (t :social/Created ul) ": ")] [:chunk (if (number? (:ctime e)) (str (date-from-unix-time (long (* 1000 (:ctime e))) "date")" ") (str (:ctime e) " "))]
[:chunk.chunk (str (t :user/verified ul)": ")] [:chunk (str (if (true? (:verified e)) (t :core/Yes ul) (t :core/No ul)) " ")]
(when (= true primary-address)
[:phrase
[:chunk.chunk (str (t :user/Loginaddress ul)": ")] [:chunk (t :core/Yes ul)] "\n"])
[:chunk.chunk (str (t :user/BackpackID ul) ": ")][:chunk (str (:backpack_id e))]]))])
profile-template (pdf/template
[:paragraph.generic
(when (not-empty $profile)
[:paragraph.generic
[:heading.heading-name (t :user/Myprofile ul)]
[:spacer 0]
(into [:paragraph ] (for [p (sort-by :order $profile)
:let[ k (->> contact-fields
(filter #(= (:type %) (:field p)))
first
:key)]]
[:phrase
[:chunk.chunk (str (t k ul)": ")] [:chunk (str (:value p) " ")]]))])])
badge-template (pdf/template
[:paragraph.generic
(when-not (empty? $user_badges)
(into [:paragraph
[:spacer 0]
[:heading.heading-name (t :badge/Mybadges ul)]]
(for [b $user_badges
:let [more-badge-info (replace-nils (b/get-badge ctx (:id b) user-id))
content (:content more-badge-info)
congratulated? (:congratulated? more-badge-info)
message-count (so/get-badge-message-count ctx (:badge_id b) user-id)
messages (replace-nils (select-badge-messages {:badge_id (:badge_id b)} (util/get-db ctx)))
endorsements (replace-nils (select-badge-endorsements {:id (:badge_id b)} (util/get-db ctx)))
location (loc/user-badge-location ctx current-user-id (:id b))
template #(cons [:paragraph][[:paragraph
[:chunk.chunk (str (t :badge/BadgeID ul) ": ")][:chunk (str (or (:badge_id b ) "-"))]"\n"
[:chunk.chunk (str (t :badge/Name ul) ": ") ][:chunk (or (:name %) "-")]"\n"
[:chunk.chunk (str (t :page/Description ul) ": ")][:chunk (str (:description %))]"\n"
[:chunk.chunk (str (t :badge/Imagefile ul) ": ")] [:anchor {:target (str site-url "/"(:image_file %))} [:chunk.link (str site-url "/"(:image_file %))]]"\n"
[:chunk.chunk (str (t :badge/Issuedby ul) ": ")] [:chunk (str (:issuer_content_name %)" ")]
[:chunk.chunk (str (t :badge/Issuerurl ul) ": ")] [:anchor {:target (str (:issuer_content_url %))} [:chunk.link (str (:issuer_content_url %))]]"\n"
[:chunk.chunk (str (t :badge/Issuercontact ul) ": ")] [:chunk.link (str (:issuer_contact %))]"\n"
(when-not (= "-" (:creator_name %))
[:phrase
[:chunk.chunk (str (t :badge/Createdby ul) ": ")][:chunk (str (:creator_name %))]"\n"])
(when-not (= "-" (:creator_url %))
[:phrase
[:chunk.chunk (str (t :badge/Creatorurl ul) ": ")][:chunk.link (str (:creator_url %))]"\n"])
(when-not (= "-" (:creator_email %))
[:phrase
[:chunk.chunk (str (t :badge/Creatorcontact ul) ": ")] [:chunk.link (str (:creator_email %))]"\n"])
[:chunk.chunk (str (t :badge/Criteriaurl ul) ": ") ] [:anchor {:target (str (:criteria_url %))} [:chunk.link (str (:criteria_url %))]]"\n"
[:paragraph
[:chunk.chunk (str (t :badge/Criteria ul) ": ")][:paragraph (strip-html-tags (:criteria_content %))]"\n"]
(when-not (blank? (:status b)) [:phrase [:chunk.chunk (str (t :user/Status ul) ": ")][:chunk (capitalize (str (t (keyword (str "social/"(:status b))) ul) " "))]])
(when-not (or (nil? location) (every? nil? (vals location))) [:phrase [:chunk.chunk (str (t :location/Location ul) ": ")] [:chunk (str (:lat location) "," (:lng location))] " "])
[:chunk.chunk (str (t :badge/Verifiedbyobf ul) ": ")][:chunk (str (if (true? (:verified_by_obf b)) (t :core/Yes ul) (t :core/No ul)) " ")]
[:chunk.chunk (str (t :badge/Issuedbyobf ul) ": ")][:chunk (str (if (true? (:issued_by_obf b)) (t :core/Yes ul) (t :core/No ul)))]"\n"
(when (not-empty (:tags b))
[:phrase
[:chunk.chunk (str (t :badge/Tags ul) ": ")] [:chunk (join ", " (:tags b))]"\n"])
[:chunk.chunk (str (t :badge/Issuedon ul) ": ")][:chunk (if (number? (:issued_on b))(str (date-from-unix-time (long (* 1000 (:issued_on b))) "date") " ") (str (:issued_on b) " "))]
[:chunk.chunk (str (t :badge/Expireson ul) ": ")][:chunk (if (number? (:expires_on b)) (date-from-unix-time (long (* 1000 (:expires_on b))) "date") (:expires_on b))]"\n"
[:chunk.chunk (str (t :badge/Issuerverified ul) ": ")] (if (== 0 (:issuer_verified b) ) [:chunk (str (t :core/No ul) " ")] [:chunk (str (t :core/Yes ul) " ")])
[:chunk.chunk (str (t :badge/Revoked ul) ": ")] [:chunk (str (if (true? (:revoked b)) (t :core/Yes ul) (t :core/No ul)) " ")]
[:chunk.chunk (str (t :badge/Badgevisibility ul) ": ")] [:chunk (t (keyword (str "core/" (capitalize (:visibility b)))) ul)]"\n"
[:chunk.chunk (str (t :badge/OBFurl ul) ": ")] [:anchor {:target (:obf_url b)} [:chunk.link (:obf_url b)]]"\n"
[:chunk.chunk (str (t :badge/Assertionurl ul) ": ")] [:anchor {:target (:assertion_url more-badge-info) } [:chunk.link (str (:assertion_url more-badge-info))]]"\n"
[:chunk.chunk (str (t :badge/Assertionjson ul) ": ")][:chunk (str (:assertion_json more-badge-info))]"\n"
[:chunk.chunk (str (t :badge/Badgerating ul) ": ") ] [:chunk (str (:rating more-badge-info) " ")]"\n"
( str ( t : badge / Evidenceurl ul ) " : " ) ] [: anchor { : target (: evidence_url more - badge - info ) } [: chunk.link ( str (: evidence_url more - badge - info ) " " ) ] ] " \n "
(when-not (empty? (:evidences more-badge-info))
[:paragraph
[:spacer]
[:chunk.chunk (str (t :badge/Evidence ul) ": " (count (:evidences more-badge-info)))]"\n"
(reduce (fn [r evidence]
(conj r [:paragraph
(when-not (blank? (:name evidence))[:phrase [:chunk.chunk (str (t :badge/Name ul) ": ")] [:chunk (:name evidence)]])"\n"
(when-not (blank? (:description evidence)) [:phrase [:chunk.chunk (str (t :admin/Description ul) ": ")][:chunk (:description evidence)]])"\n"
[:anchor {:target (:url evidence)}[:phrase [:chunk.chunk (str (t :admin/Url ul) ": ")] [:chunk.link (:url evidence)]]]
[:spacer 0]]) )[:paragraph] (:evidences more-badge-info))])
(when (not-empty (:alignment %))
[:paragraph
[:chunk.chunk (str (t :badge/Alignments ul) ": " (count (:alignment %)))]"\n"
(into [:paragraph]
(for [a (:alignment %)]
[:paragraph
[:chunk (:name a)]"\n"
[:chunk (:description a)]"\n"
[:chunk.link (:url a)]
[:spacer 0]]))])
[:chunk.chunk (str (t :badge/Viewed ul) ": ")] [:chunk (str (:view_count more-badge-info) " " (t :badge/times ul)" ")]", "
[:chunk.chunk (str (t :badge/Recipientcount ul) ": ")][:chunk (str (:recipient_count more-badge-info) " ")]", "
[:chunk.chunk (str (t :badge/Congratulated ul) "?: ")][:chunk (str (if (true? congratulated?) (t :core/Yes ul) (t :core/No ul))" ")]"\n"
(when-not (empty? (:congratulations more-badge-info))
[:paragraph
[:chunk.chunk (str (t :badge/Congratulations ul) ": ")]"\n"
[:paragraph
(into [:paragraph] (for [c (:congratulations more-badge-info)]
[:phrase
[:chunk (str (:first_name c) " " (:last_name c))] "\n"]))]])
(when (> (:endorsement_count %) 0) (blank? (str (:endorsement_count %)))
[:phrase
[:chunk.chunk (str (capitalize (t :badge/endorsements ul)) ": ")][:chunk (str (:endorsement_count %))]"\n"])
(when (not-empty endorsements)
(into [:paragraph {:indent 0}]
(for [e endorsements]
[:paragraph {:indent 0}
(:issuer_name e) "\n"
[:anchor {:target (:issuer_url e) :style{:family :times-roman :color [66 100 162]}} (:issuer_url e) ] "\n"
[:chunk (if (number? (:issued_on e)) (date-from-unix-time (long (* 1000 (:issued_on e)))) (:issued_on e))] "\n"
(process-markdown (:content e) (:badge_id b ) "Endorsements")])))
(when (> (:all-messages message-count) 0)
[:phrase
[:chunk.chunk (str (t :social/Messages ul) ": ")] [:chunk (str (:all-messages message-count))]"\n"])
(when (> (:all-messages message-count) 0)
(into [:paragraph]
(for [m messages]
[:paragraph
[:chunk(:message m)]"\n"
[:chunk (str (:first_name m) " " (:last_name m))]"\n"
[:chunk (if (number? (:ctime m)) (date-from-unix-time (long (* 1000 (:ctime m))) "date") (:ctime m))]
[:spacer 0]])))
[:chunk.chunk (str (t :social/Lastmodified ul) ": ")][:chunk (if (number? (:mtime b))(str (date-from-unix-time (long (* 1000 (:mtime b))) "date")" ") (str (:mtime b) " "))]
[:chunk.chunk (str (t :badge/URL ul) ": ")] [:anchor {:target (str site-url "/app/badge/info/" (:id b))} [:chunk.link {:style :italic} (str site-url "/app/badge/info/" (:id b))]]
[:spacer 1]]])]]
(reduce into [:paragraph] (-> (mapv template content)
(conj [[:line {:dotted true}]]))))))])
pending-badges-template (pdf/template
[:paragraph.generic
(when-not (empty? $pending_badges)
[:paragraph
[:heading.heading-name (t :badge/Pendingbadges ul)]
[:spacer 0]
(into [:paragraph]
(for [pb $pending_badges]
[:paragraph
[:chunk.chunk (str (t :badge/BadgeID ul) ": ")] [:chunk (str (:badge_id pb))]"\n"
[:chunk.chunk (str (t :badge/Name ul) ": ")] [:chunk (str (:name pb))]"\n"
[:chunk.chunk (str (t :page/Description ul) ": ")] [:chunk (str (:description pb))]"\n"
[:chunk.chunk (str (t :badge/Imagefile ul) ": ")] [:anchor {:target (str site-url "/" (:image_file pb))} [:chunk.link (str site-url "/" (:image_file pb)) ]]"\n"
[:chunk.chunk (str (t :badge/Assertionurl ul) ": ")] [:anchor {:target (:assertion_url pb)} [:chunk.link (:assertion_url pb) ]]"\n"
(when (not-empty (:tags pb))
[:phrase
[:chunk.chunk (str (t :badge/Tags ul) ": ")] [:chunk (join ", " (:tags pb))]"\n"])
[:chunk.chunk (str (t :badge/Badgevisibility ul) ": ")] [:chunk (t (keyword (str "core/" (capitalize (:visibility pb)))))]"\n"
[:chunk.chunk (str (t :badge/Issuedon ul) ": ")] [:chunk (if (number? (:issued_on pb)) (str (date-from-unix-time (long (* 1000 (:issued_on pb))) "date") ", ") (str (:issued_on pb) ", "))]
[:chunk.chunk (str (t :badge/Expireson ul) ": ")] [:chunk (if (number? (:expires_on pb)) (str (date-from-unix-time (long (* 1000 (:expires_on pb))) "date") ", ") (str (:expires_on pb) ", "))]]))])])
selfie-template (pdf/template
[:paragraph.generic
(when (seq $selfies)
[:paragraph
[:heading.heading-name (t :badgeIssuer/Selfiebadges ul)]
[:spacer]
(into [:paragraph]
(for [s $selfies]
[:paragraph
[:chunk.chunk (str (t :badge/BadgeID ul) ": ")] [:chunk (str (:id s))] "\n"
[:chunk.chunk (str (t :badge/Name ul) ": ")] [:chunk (str (:name s))]"\n"
[:chunk.chunk (str (t :page/Description ul) ": ")] [:chunk (str (:description s))]"\n"
[:chunk.chunk (str (t :badge/Imagefile ul) ": ")] [:anchor {:target (str site-url "/" (:image s))} [:chunk.link (str site-url "/" (:image s)) ]]"\n"
[:paragraph
(when (seq (:tags s))
[:phrase
[:chunk.chunk (str (t :badge/Tags ul) ": ")] [:chunk (join ", " (:tags s))]"\n"])
[:chunk.chunk (str (t :badgeIssuer/Issuableselfiebadge ul) ": ")] [:chunk (str (:issuable_from_gallery s))]
[:spacer 1]]))])])
page-template (pdf/template
[:paragraph.generic
(when-not (empty? $user_pages)
[:paragraph
[:heading.heading-name (t :page/Mypages ul)]
[:spacer 0]
(into [:paragraph]
(for [p $user_pages
:let [ page-owner? (p/page-owner? ctx (:id p) user-id)
page-blocks (p/page-blocks ctx (:id p))]]
[:paragraph
[:chunk.chunk (str (t :page/PageID ul) ": ")][:chunk (str (:id p))]"\n"
[:chunk.chunk (str (t :badge/Name ul) ": ")][:chunk (str (:name p))]"\n"
[:chunk.chunk (str (t :page/Owner ul) "?: ")][:chunk (if (= true page-owner?) (t :core/Yes ul) (t :core/No ul))] "\n"
[:chunk.chunk (str (t :page/Pagepassword ul) ": ")][:chunk (str (:password p))]"\n"
[:chunk.chunk (str (t :page/Description ul) ": ")][:chunk (str (:description p))]"\n"
[:chunk.chunk (str (t :social/Created ul) ": ")][:chunk (str (if (number? (:ctime p)) (date-from-unix-time (long (* 1000 (:ctime p))) "date") (:ctime p)) " ")]
[:chunk.chunk (str (t :social/Lastmodified ul) ": ")][:chunk (str (if (number? (:mtime p))(date-from-unix-time (long (* 1000 (:mtime p))) "date") (:mtime p)))]"\n"
(when (not-empty (:tags p))
[:phrase
[:chunk.chunk (str (t :badge/Tags ul) ": ")] [:chunk (join ", " (:tags p))]"\n"])
[:chunk.chunk (str (t :page/Theme ul) ": ")][:chunk (str (:theme p) " ")]
[:chunk.chunk (str (t :page/Border ul) ": ")][:chunk (str (:border p) " ")]
[:chunk.chunk (str (t :page/Padding ul) ": ")][:chunk (str (:padding p))]"\n"
[:spacer 1]
(when (not-empty page-blocks)
(into [:paragraph
[:phrase.chunk (t :page/Pageblocks ul)]
[:spacer 0]]
(for [pb page-blocks]
[:paragraph
(when (= "heading" (:type pb))
(case (:size pb)
"h1" [:phrase.generic {:align :left}
[:chunk.chunk (str (t :page/Heading ul)": ")] [:chunk (str (:content pb))]]
"h2" [:phrase.generic {:align :left}
[:chunk.chunk (str (t :page/Subheading ul) ": ")] [:chunk (str (:content pb))]]))
(when (= "badge" (:type pb))
[:phrase
[:phrase.chunk (str (t :badge/Badge ul) ": ")]
[:anchor {:target (str site-url "/app/badge/info/" (:badge_id pb))} [:chunk.link (str (:name pb))]]"\n"])
(when (= "html" (:type pb))
[:phrase
[:spacer 0]
[:phrase.chunk (str (t :page/Html ul) ": ")]
[:spacer 0]
(:content pb)])
(when (= "file" (:type pb))
[:paragraph
[:spacer 0]
[:phrase.chunk (str (t :file/Files ul) ": ")]"\n"
(into [:paragraph]
(for [file (:files pb)]
[:phrase
[:chunk.bold (str (t :badge/Name ul) ": ")] [:chunk (:name file)]"\n"
[:chunk.bold (str (t :badge/URL ul) ": ")][:anchor {:target (str site-url "/"(:path file)) :style{:family :times-roman :color [66 100 162]}} (str site-url "/"(:path file))]]))])
(when (= "tag" (:type pb))
[:paragraph
[:phrase.chunk (str (t :page/Badgegroup ul) ": ")]
[:spacer 0]
(into [:phrase ] (for [b (:badges pb)]
[:phrase
[:anchor {:target (str site-url "/app/badge/info/" (:id b))} [:chunk.link (str (:name b))]]"\n"]))])])))
[:line {:dotted true}] [:spacer 0]]))])])
user-connections-template (pdf/template
[:paragraph.generic
(when (or (not-empty $user_followers) (not-empty $user_following))
[:paragraph
[:heading.heading-name (str (t :user/Socialconnections ul) ": ")]
[:spacer 0]
(when-not (empty? $user_followers)
(into [:paragraph
[:phrase.chunk (str (t :social/Followersusers ul) ": ")] [:spacer 0]] (for [follower $user_followers
:let [follower-id (:owner_id follower)
fname (:first_name follower)
lname (:last_name follower)
status (:status follower)]]
[:paragraph
[:anchor {:target (str site-url "/app/user/profile/" follower-id)} [:chunk.link (str fname " " lname ", ")]]
[:chunk.chunk (str (t :user/Status ul) ": ")] [:chunk (str (t (keyword (str "social/"status)) ul))]])))
(when-not (empty? $user_following)
(into [:paragraph
[:phrase.chunk (str (t :social/Followedusers ul) ": ")][:spacer 0]] (for [f $user_following
:let [followee-id (:user_id f)
fname (:first_name f)
lname (:last_name f)
status (:status f)]]
[:paragraph
[:anchor {:target (str site-url "/app/user/profile/" followee-id)} [:chunk.link (str fname " " lname ", ")]]
[:chunk.chunk (str (t :user/Status ul) ": ")] [:chunk (str (t (keyword (str "social/"status)) ul))]])))])])
badge-connections-template (pdf/template
[:paragraph.generic
(when-not (empty? $connections)
[:paragraph
[:heading.heading-name (str (t :user/Badgeconnections ul) ": ")]
[:spacer 0]
(into [:paragraph]
(for [c $connections]
[:paragraph
[:chunk.chunk (str (t :badge/BadgeID ul) ": ")] [:chunk (str (:id c))]"\n"
[:chunk.chunk (str (t :badge/Name ul) ": ")][:chunk (str (:name c))]"\n"
[:chunk.chunk (str (t :page/Description ul) ": ")][:chunk (str (:description c))]"\n"
[:chunk.chunk (str (t :badge/Imagefile ul) ": ")][:anchor {:target (str site-url "/" (:image_file c))} [:chunk.link (str site-url "/" (:image_file c))]]"\n"]))])])
user-endorsements-template (pdf/template
[:paragraph.generic
(when-not (empty? $endorsements)
(let [{:keys [given received sent-requests]} $endorsements]
[:paragraph
[:heading.heading-name (str (t :badge/Myendorsements ul) ": ")]
[:spacer 0]
(when (seq given)
[:paragraph
[:chunk..small-heading (t :badge/Iendorsed ul)]
[:spacer 1]
(into [:paragraph] (for [g given
:let [name (str (:first_name g) " " (:last_name g))]]
[:paragraph
[:chunk name]"\n"
[:chunk.chunk (:name g)]"\n"
[:chunk (date-from-unix-time (long (* 1000 (:mtime g))) "date")]"\n"
(process-markdown (:content g) (:user_badge_id g) "User Endorsements")]))])
(when (seq received)
[:paragraph
[:chunk.small-heading (t :badge/Endorsedme ul)]
[:spacer 1]
(into [:paragraph] (for [r received
:let [name (str (:first_name r) " " (:last_name r))]]
[:paragraph
[:chunk (:issuer_name r)]"\n"
[:chunk.chunk (:name r)]"\n"
[:chunk (date-from-unix-time (long (* 1000 (:mtime r))) "date")]"\n"
(process-markdown (:content r) (:user_badge_id r) "User Endorsements")]))])
(when (seq sent-requests)
[:paragraph
[:chunk.small-heading (t :badge/Sentendorsementrequests ul)]
[:spacer 1]
(into [:paragraph] (for [sr sent-requests
:let [name (str (:first_name sr) " " (:last_name sr))]]
[:paragraph
[:chunk (:issuer_name sr)]"\n"
[:chunk.chunk (:name sr)]"\n"
[:chunk (date-from-unix-time (long (* 1000 (:mtime sr))) "date")]"\n"
(process-markdown (:content sr) (:user_badge_id sr) "User Endorsements")]))])]))])
events-template (pdf/template
(let [template (cons [:paragraph]
[[:paragraph.generic
(when-not (empty? $events)
[:heading.heading-name (t :user/Activityhistory ul)])]
(when-not (empty? $events)
(into [:table.generic {:header [(t :social/Action ul) (t :social/Object ul) (t :social/Objecttype ul) (t :social/Created ul)]}]
(for [e (->> (reverse $events) (remove (fn [e] (nil? (:info e)))))]
[[:cell (if-not (= "-" (:verb e)) (t (keyword (str "social/"(:verb e))) ul) "-")]
[:cell [:phrase
[:chunk (get-in e [:info :object_name])]"\n"
(if (contains? (:info e) :message)
[:chunk {:style :italic} (get-in e [:info :message :message])])
(when-not (blank? (get-in e [:info :content]))
[:chunk {:style :italic} (get-in e [:info :content])])]]
[:cell
(when-not (blank? (str (:type e)))
(cond
(= "page" (:type e)) (t :social/Emailpage ul)
(= "badge" (:type e)) (t :social/Emailbadge ul)
(= "user" (:type e)) (lower-case (t :social/User ul))
(= "admin" (:type e)) (lower-case (t :admin/Admin ul))
(= "selfie" (:type e)) (lower-case (t :badgeIssuer/Selfie ul))
:else "-"))]
[:cell (if (number? (:ctime e))(date-from-unix-time (long (* 1000 (:ctime e))) "date") (:ctime e))]])))])]
template))]
(fn [output-stream]
(pdf/pdf (into [pdf-settings] (concat (user-info-template user-data)
(email-template user-data)
(profile-template user-data)
(badge-template user-data)
(pending-badges-template user-data)
(selfie-template user-data)
(page-template user-data)
(user-connections-template user-data)
(badge-connections-template user-data)
(user-endorsements-template user-data)
(events-template user-data))) output-stream))))
|
1ddc3a7e038e547bcbe067bf3b2c4b854fbb6157cc7dee7f777e60d7386d0cfc | ucsd-progsys/liquidhaskell | T1288.hs | {-@ LIQUID "--expect-any-error" @-}
module T1288 where
{-@ measure foo @-}
foo :: () -> Int
foo _ = 10
@ : : { v : Int | v = 100 } @
blub = foo ()
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/neg/T1288.hs | haskell | @ LIQUID "--expect-any-error" @
@ measure foo @ | module T1288 where
foo :: () -> Int
foo _ = 10
@ : : { v : Int | v = 100 } @
blub = foo ()
|
3f3a7daa6b677b6d9ac67ed70b8c33c86bc003907d14fc76af209dcd0b098bc5 | jkvor/emysql | honeybee.erl | -module(honeybee).
-behavior(emysql_worker).
-export([init/1, process/1]).
-export([get_by_bid/1, get_by_type/1, get_all/0, create/1, update_type/2]).
-export([cajole_bee/1]).
-record(bee, {name, type, size}).
init(_) ->
erlang:register(honeybee1, self()),
Prepares = [
{bees_by_bid, <<"select * from hive where name = ?">>},
{bees_by_type, <<"select * from hive where type = ?">>},
{bees_all, <<"select * from hive">>},
{bees_create, <<"INSERT INTO hive SET name = ?, type = ?, size = ?">>},
{bees_update_type, <<"UPDATE hive SET type = ? WHERE name = ?">>}
],
{ok, Prepares, master}.
process({get_by_bid, Args}) ->
{bees_by_bid, Args, {bee, record_info(fields, bee), fun cajole_bee/1}};
process({get_by_type, _}) ->
{bees_by_type};
process({get_all, Args}) ->
{bees_all, Args, {bee, record_info(fields, bee)}};
process({update, [BeeID, Type]}) ->
{bees_update_type, [Type, BeeID]};
process({create, Bee}) ->
{bees_create, [Bee#bee.name, Bee#bee.type, Bee#bee.size]}.
get_by_bid(BeeId) ->
emysql_worker:execute(honeybee1, {get_by_bid, [BeeId]}).
get_by_type(Type) ->
emysql_worker:execute(honeybee1, {get_by_type, [Type]}).
get_all() ->
emysql_worker:execute(honeybee1, {get_all}).
create(Bee) ->
emysql_worker:execute(honeybee1, {create, Bee}).
update_type(BeeID, Type) ->
emysql_worker:execute(honeybee1, {update, [BeeID, Type]}).
cajole_bee(X) -> X.
| null | https://raw.githubusercontent.com/jkvor/emysql/6f72bc729200024f5940a2c11f15afd2af6f3d11/t/honeybee.erl | erlang | -module(honeybee).
-behavior(emysql_worker).
-export([init/1, process/1]).
-export([get_by_bid/1, get_by_type/1, get_all/0, create/1, update_type/2]).
-export([cajole_bee/1]).
-record(bee, {name, type, size}).
init(_) ->
erlang:register(honeybee1, self()),
Prepares = [
{bees_by_bid, <<"select * from hive where name = ?">>},
{bees_by_type, <<"select * from hive where type = ?">>},
{bees_all, <<"select * from hive">>},
{bees_create, <<"INSERT INTO hive SET name = ?, type = ?, size = ?">>},
{bees_update_type, <<"UPDATE hive SET type = ? WHERE name = ?">>}
],
{ok, Prepares, master}.
process({get_by_bid, Args}) ->
{bees_by_bid, Args, {bee, record_info(fields, bee), fun cajole_bee/1}};
process({get_by_type, _}) ->
{bees_by_type};
process({get_all, Args}) ->
{bees_all, Args, {bee, record_info(fields, bee)}};
process({update, [BeeID, Type]}) ->
{bees_update_type, [Type, BeeID]};
process({create, Bee}) ->
{bees_create, [Bee#bee.name, Bee#bee.type, Bee#bee.size]}.
get_by_bid(BeeId) ->
emysql_worker:execute(honeybee1, {get_by_bid, [BeeId]}).
get_by_type(Type) ->
emysql_worker:execute(honeybee1, {get_by_type, [Type]}).
get_all() ->
emysql_worker:execute(honeybee1, {get_all}).
create(Bee) ->
emysql_worker:execute(honeybee1, {create, Bee}).
update_type(BeeID, Type) ->
emysql_worker:execute(honeybee1, {update, [BeeID, Type]}).
cajole_bee(X) -> X.
|
|
6358fa7852d2cb98fa3adc0341afe8b995a90a2743997746e2747fb843680a18 | CryptoKami/cryptokami-core | Model.hs | -- | Distributed Hash Table for peer discovery.
# OPTIONS_GHC -F -pgmF autoexporter #
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/infra/Pos/DHT/Model.hs | haskell | | Distributed Hash Table for peer discovery. |
# OPTIONS_GHC -F -pgmF autoexporter #
|
e1d090545df2754fd5ffcca02f71e77e0411850c32283d64f07f967abdcbe921 | bcambel/oss.io | test_utils.clj | (ns hsm.test-utils
(:use midje.sweet)
(:require [hsm.utils :refer :all]))
(tabular
(fact "Domain name resolution"
(domain-of {:headers { "host" ?host }} ) => ?result )
?host ?result
"dev.pythonhackers.com" ["dev" "pythonhackers" "com"]
"pythonhackers.com" ["pythonhackers" "com"]
"www.clojurehackers.com" ["www" "clojurehackers" "com"])
(tabular
(fact "Find Host of the Request"
(host-of {:headers { "host" ?host }} ) => ?result)
?host ?result
"dev.pythonhackers.com" "dev.pythonhackers.com"
"clojurehackers.com" "clojurehackers.com")
(tabular
(fact "Empty Host Request with falsy hash-map "
(host-of ?request ) => ?result)
?request ?result
{:headers { "TEST" 1}} nil
{:headers2 "test"} nil
)
; Well Token fetcher always returns the same ID for right now! Very effective!! :)
(tabular
(fact "Find User Token"
(whois {:headers { "X-AUTH-TOKEN" ?token }}) => ?result)
?token ?result
1 243975551163827208
)
(tabular
(fact "Select Values of a Hash-Map"
(select-values ?hashmap ?keys) => ?result)
?hashmap ?keys ?result
{:a 1 :b 2} [:a :b] [1 2]
{:a 1 :b 2} [:a] [1]
{:a 1 :b 2} [] []
{:a 1 :b 2} nil []
)
(let [temp-file (java.io.File/createTempFile (str "body-test" (now->ep)) ".txt")]
(doto (clojure.java.io/writer temp-file)
(.write "testing")
(.close))
(tabular
(fact "Body Slurping"
(body-as-string {:body ?body}) => ?result)
?body ?result
"test" "test"
temp-file "testing")
(.delete temp-file))
(tabular
(fact "Convert maps into keyword keyed hashmaps"
(mapkeyw ?hashmap) => ?result)
?hashmap ?result
{"a" 1 "b" 2} {:a 1 :b 2}
{:a 1 :b 2} {:a 1 :b 2}
{1 2} {nil 2}
{1 2 3 4} {nil 4}
{"1" 2 "3" 4} {:1 2 :3 4}
)
(tabular
(fact "FQDN"
(fqdn {:headers {"host" ?request}}) => ?result)
?request ?result
"dev.pythonhackers.com" "dev.pythonhackers.com"
"pythonhackers.com" "www.pythonhackers.com"
)
(tabular
(fact "Not NIL"
(!nil? ?obj) => ?bool)
?obj ?bool
1 true
nil false
[] true
[nil] true
0 true
)
(tabular
(fact "NOT BLank"
(!blank? ?str) => ?bool)
?str ?bool
"" false
"a" true
:1 (throws ClassCastException)
1 (throws ClassCastException)
)
(tabular
(fact "Vecof 2"
(vec2? ?vec) => ?bool)
?vec ?bool
nil false
[1 2] true
[1 [1 2]] true
[nil nil] true
)
(tabular
(fact "Vecof N"
(nvec? ?n ?vec) => ?bool)
?vec ?n ?bool
nil 1 false
[1 2] 2 true
[1 [1 2]] 2 true
[nil nil] 2 true
[nil nil 1] 3 true
)
(fact "Has 1" (vec1? [nil]) => true)
(fact "Has 3" (vec3? [nil nil 0]) => true)
(fact "Not Negative Num" (!neg? 123) => true)
(fact "Not Negative Num" (!neg? -123) => false)
(fact "Not Negative Num" (!neg? 0) => true)
(fact "0 is not Positive" (pos-int? 0) => false)
(fact "1 is Positive" (pos-int? 1) => true)
(fact "Max VALUE is Positive" (pos-int? Integer/MAX_VALUE) => true)
(fact "MAX VALUE + 1 is Positive" (pos-int? (+ 1 Integer/MAX_VALUE)) => true)
(fact "MIN VALUE - 1 is Positive" (pos-int? (- 1 Integer/MIN_VALUE)) => true)
(tabular
(fact "Vectorize"
(vec* ?coll) => ?res)
?coll ?res
#{1} [1]
nil []
[1] [1]
[nil] [nil]
{:a 1} [[:a 1]]
#{:a 1} [1 :a]
)
(tabular
(fact "Setify"
(set* ?coll) => ?res)
?coll ?res
#{1} #{1}
nil #{}
[1] #{1}
[nil] #{nil}
{:a 1} #{[:a 1]}
#{:a 1} #{:a 1}
)
(tabular
(fact "Not NIL but Equal"
(!nil= ?o1 ?o2) => ?res)
?o1 ?o2 ?res
1 2 false
1 nil false
nil 1 false
1 [1] false
1 1/1 true
[1] [[1]] false
[1] #{1} false
[] nil false
[] #{} false
[] '() true
[1] '(1) true
[1 [1]] '(1 [1]) true
)
(tabular
(fact "Hexadecimal Cassandra keys to String"
(hex-to-str ?s ) => ?res)
?s ?res
"6d7574686875732f666c6173682d6d6573736167652d636f6e647563746f72" "muthhus/flash-message-conductor"
"657268756162757368756f2f50726f746f636f6c2d466f726573742d56616d6569" "erhuabushuo/Protocol-Forest-Vamei"
"726f7566666a2f486f77746f536563757269747942756e646c65" "rouffj/HowtoSecurityBundle"
)
| null | https://raw.githubusercontent.com/bcambel/oss.io/cddb8b8ba4610084bc2f3c78c7837cdec87a8c76/test/hsm/test_utils.clj | clojure | Well Token fetcher always returns the same ID for right now! Very effective!! :) | (ns hsm.test-utils
(:use midje.sweet)
(:require [hsm.utils :refer :all]))
(tabular
(fact "Domain name resolution"
(domain-of {:headers { "host" ?host }} ) => ?result )
?host ?result
"dev.pythonhackers.com" ["dev" "pythonhackers" "com"]
"pythonhackers.com" ["pythonhackers" "com"]
"www.clojurehackers.com" ["www" "clojurehackers" "com"])
(tabular
(fact "Find Host of the Request"
(host-of {:headers { "host" ?host }} ) => ?result)
?host ?result
"dev.pythonhackers.com" "dev.pythonhackers.com"
"clojurehackers.com" "clojurehackers.com")
(tabular
(fact "Empty Host Request with falsy hash-map "
(host-of ?request ) => ?result)
?request ?result
{:headers { "TEST" 1}} nil
{:headers2 "test"} nil
)
(tabular
(fact "Find User Token"
(whois {:headers { "X-AUTH-TOKEN" ?token }}) => ?result)
?token ?result
1 243975551163827208
)
(tabular
(fact "Select Values of a Hash-Map"
(select-values ?hashmap ?keys) => ?result)
?hashmap ?keys ?result
{:a 1 :b 2} [:a :b] [1 2]
{:a 1 :b 2} [:a] [1]
{:a 1 :b 2} [] []
{:a 1 :b 2} nil []
)
(let [temp-file (java.io.File/createTempFile (str "body-test" (now->ep)) ".txt")]
(doto (clojure.java.io/writer temp-file)
(.write "testing")
(.close))
(tabular
(fact "Body Slurping"
(body-as-string {:body ?body}) => ?result)
?body ?result
"test" "test"
temp-file "testing")
(.delete temp-file))
(tabular
(fact "Convert maps into keyword keyed hashmaps"
(mapkeyw ?hashmap) => ?result)
?hashmap ?result
{"a" 1 "b" 2} {:a 1 :b 2}
{:a 1 :b 2} {:a 1 :b 2}
{1 2} {nil 2}
{1 2 3 4} {nil 4}
{"1" 2 "3" 4} {:1 2 :3 4}
)
(tabular
(fact "FQDN"
(fqdn {:headers {"host" ?request}}) => ?result)
?request ?result
"dev.pythonhackers.com" "dev.pythonhackers.com"
"pythonhackers.com" "www.pythonhackers.com"
)
(tabular
(fact "Not NIL"
(!nil? ?obj) => ?bool)
?obj ?bool
1 true
nil false
[] true
[nil] true
0 true
)
(tabular
(fact "NOT BLank"
(!blank? ?str) => ?bool)
?str ?bool
"" false
"a" true
:1 (throws ClassCastException)
1 (throws ClassCastException)
)
(tabular
(fact "Vecof 2"
(vec2? ?vec) => ?bool)
?vec ?bool
nil false
[1 2] true
[1 [1 2]] true
[nil nil] true
)
(tabular
(fact "Vecof N"
(nvec? ?n ?vec) => ?bool)
?vec ?n ?bool
nil 1 false
[1 2] 2 true
[1 [1 2]] 2 true
[nil nil] 2 true
[nil nil 1] 3 true
)
(fact "Has 1" (vec1? [nil]) => true)
(fact "Has 3" (vec3? [nil nil 0]) => true)
(fact "Not Negative Num" (!neg? 123) => true)
(fact "Not Negative Num" (!neg? -123) => false)
(fact "Not Negative Num" (!neg? 0) => true)
(fact "0 is not Positive" (pos-int? 0) => false)
(fact "1 is Positive" (pos-int? 1) => true)
(fact "Max VALUE is Positive" (pos-int? Integer/MAX_VALUE) => true)
(fact "MAX VALUE + 1 is Positive" (pos-int? (+ 1 Integer/MAX_VALUE)) => true)
(fact "MIN VALUE - 1 is Positive" (pos-int? (- 1 Integer/MIN_VALUE)) => true)
(tabular
(fact "Vectorize"
(vec* ?coll) => ?res)
?coll ?res
#{1} [1]
nil []
[1] [1]
[nil] [nil]
{:a 1} [[:a 1]]
#{:a 1} [1 :a]
)
(tabular
(fact "Setify"
(set* ?coll) => ?res)
?coll ?res
#{1} #{1}
nil #{}
[1] #{1}
[nil] #{nil}
{:a 1} #{[:a 1]}
#{:a 1} #{:a 1}
)
(tabular
(fact "Not NIL but Equal"
(!nil= ?o1 ?o2) => ?res)
?o1 ?o2 ?res
1 2 false
1 nil false
nil 1 false
1 [1] false
1 1/1 true
[1] [[1]] false
[1] #{1} false
[] nil false
[] #{} false
[] '() true
[1] '(1) true
[1 [1]] '(1 [1]) true
)
(tabular
(fact "Hexadecimal Cassandra keys to String"
(hex-to-str ?s ) => ?res)
?s ?res
"6d7574686875732f666c6173682d6d6573736167652d636f6e647563746f72" "muthhus/flash-message-conductor"
"657268756162757368756f2f50726f746f636f6c2d466f726573742d56616d6569" "erhuabushuo/Protocol-Forest-Vamei"
"726f7566666a2f486f77746f536563757269747942756e646c65" "rouffj/HowtoSecurityBundle"
)
|
3857b9cb12d8fa298ee9e303602c320aac02d3762b5915baf1e29f9a38da578b | fulcrologic/video-series | session.clj | (ns app.model.session
(:require
[com.wsscode.pathom.connect :as pc]
[com.fulcrologic.fulcro.server.api-middleware :refer [augment-response]]
[taoensso.timbre :as log]))
(def users (atom {1 {:user/id 1
:user/email ""
:user/password "letmein"}}))
(pc/defresolver user-resolver [env {:user/keys [id]}]
{::pc/input #{:user/id}
::pc/output [:user/email]}
{:user/id id
:user/email (get-in @users [id :user/email])})
(pc/defresolver current-user-resolver [env _]
{::pc/output [{:session/current-user [:user/id]}]}
(let [{:user/keys [id email]} (log/spy :info (-> env :request :session))]
{:session/current-user
(if id
{:user/email email
:user/id id
:user/valid? true}
{:user/id :nobody
:user/valid? false})}))
(pc/defmutation login [env {:user/keys [email password]}]
{::pc/params #{:user/email :user/password}
::pc/output [:user/id :user/valid?]}
(log/info "Login " email)
(Thread/sleep 500)
(let [subject (first (filter (fn [u] (= (:user/email u) email)) (vals @users)))]
(if (and subject (= password (:user/password subject)))
(augment-response
{:user/email email
:user/id (:user/id subject)
:user/valid? true}
(fn [ring-resp] (assoc ring-resp :session subject)))
{:user/valid? false})))
(pc/defmutation logout [env {:user/keys [email password]}]
{::pc/params #{:user/email :user/password}
::pc/output [:user/id :user/valid?]}
(augment-response
{:user/id :nobody
:user/valid? false}
(fn [ring-resp] (assoc ring-resp :session {}))))
(def resolvers [user-resolver current-user-resolver login logout])
| null | https://raw.githubusercontent.com/fulcrologic/video-series/817969602a31aee5fbf546b35893d73f93f1d78c/src/app/model/session.clj | clojure | (ns app.model.session
(:require
[com.wsscode.pathom.connect :as pc]
[com.fulcrologic.fulcro.server.api-middleware :refer [augment-response]]
[taoensso.timbre :as log]))
(def users (atom {1 {:user/id 1
:user/email ""
:user/password "letmein"}}))
(pc/defresolver user-resolver [env {:user/keys [id]}]
{::pc/input #{:user/id}
::pc/output [:user/email]}
{:user/id id
:user/email (get-in @users [id :user/email])})
(pc/defresolver current-user-resolver [env _]
{::pc/output [{:session/current-user [:user/id]}]}
(let [{:user/keys [id email]} (log/spy :info (-> env :request :session))]
{:session/current-user
(if id
{:user/email email
:user/id id
:user/valid? true}
{:user/id :nobody
:user/valid? false})}))
(pc/defmutation login [env {:user/keys [email password]}]
{::pc/params #{:user/email :user/password}
::pc/output [:user/id :user/valid?]}
(log/info "Login " email)
(Thread/sleep 500)
(let [subject (first (filter (fn [u] (= (:user/email u) email)) (vals @users)))]
(if (and subject (= password (:user/password subject)))
(augment-response
{:user/email email
:user/id (:user/id subject)
:user/valid? true}
(fn [ring-resp] (assoc ring-resp :session subject)))
{:user/valid? false})))
(pc/defmutation logout [env {:user/keys [email password]}]
{::pc/params #{:user/email :user/password}
::pc/output [:user/id :user/valid?]}
(augment-response
{:user/id :nobody
:user/valid? false}
(fn [ring-resp] (assoc ring-resp :session {}))))
(def resolvers [user-resolver current-user-resolver login logout])
|
|
731985bcd8e53021d6782bc5f1f2917c4d657360362fabb7933731352b46b4f6 | avatar29A/hs-aitubots-api | Media.hs | {-# LANGUAGE OverloadedStrings #-}
module Aitu.Bot.Types.Media (Media (..)) where
import Data.Aeson
import Data.Text
data Media = Media {
mediaType :: Text
, mediaFileId :: Maybe Text
} deriving (Show)
instance FromJSON Media where
parseJSON (Object v) =
Media <$> v .: "type"
<*> v .: "fileId" | null | https://raw.githubusercontent.com/avatar29A/hs-aitubots-api/9cc3fd1e4e9e81491628741a6bbb68afbb85704e/src/Aitu/Bot/Types/Media.hs | haskell | # LANGUAGE OverloadedStrings # |
module Aitu.Bot.Types.Media (Media (..)) where
import Data.Aeson
import Data.Text
data Media = Media {
mediaType :: Text
, mediaFileId :: Maybe Text
} deriving (Show)
instance FromJSON Media where
parseJSON (Object v) =
Media <$> v .: "type"
<*> v .: "fileId" |
661cb690db094804941ee9318360c50115d541895b9730475a51316c69b10898 | threatgrid/ctim | actor_test.clj | (ns ctim.generators.actor-test
(:require [clj-momo.test-helpers.core :as mth]
[clojure.test :refer [use-fixtures]]
[clojure.test.check.clojure-test :refer [defspec]]
[ctim.schemas.actor :as actor]
[ctim.test-helpers
[core :as th]
[properties :as property]]
[flanders.utils :as fu]))
(use-fixtures :once
th/fixture-spec-validation
mth/fixture-schema-validation
(th/fixture-spec actor/Actor
"test.actor")
(th/fixture-spec actor/NewActor
"test.new-actor")
(th/fixture-spec (fu/require-all actor/Actor)
"test.max.actor")
(th/fixture-spec (fu/require-all actor/NewActor)
"test.max.new-actor"))
;; Actor
(defspec ^:gen spec-generated-actor-is-valid
(property/generated-entity-is-valid :test.actor/map))
(defspec ^:gen spec-generated-max-actor-is-valid
(property/generated-entity-is-valid :test.max.actor/map))
(defspec ^:gen spec-generated-actor-id-is-valid
(property/generated-entity-id-is-valid :test.actor/map
"actor"))
;; New Actor
(defspec ^:gen spec-generated-new-actor-is-valid
(property/generated-entity-is-valid :test.new-actor/map))
(defspec ^:gen spec-generated-max-new-actor-is-valid
(property/generated-entity-is-valid :test.max.actor/map))
(defspec ^:gen spec-generated-new-actor-id-is-valid
(property/generated-entity-id-is-valid :test.new-actor/map
"actor"
:optional))
| null | https://raw.githubusercontent.com/threatgrid/ctim/2ecae70682e69495cc3a12fd58a474d4ea57ae9c/test/ctim/generators/actor_test.clj | clojure | Actor
New Actor | (ns ctim.generators.actor-test
(:require [clj-momo.test-helpers.core :as mth]
[clojure.test :refer [use-fixtures]]
[clojure.test.check.clojure-test :refer [defspec]]
[ctim.schemas.actor :as actor]
[ctim.test-helpers
[core :as th]
[properties :as property]]
[flanders.utils :as fu]))
(use-fixtures :once
th/fixture-spec-validation
mth/fixture-schema-validation
(th/fixture-spec actor/Actor
"test.actor")
(th/fixture-spec actor/NewActor
"test.new-actor")
(th/fixture-spec (fu/require-all actor/Actor)
"test.max.actor")
(th/fixture-spec (fu/require-all actor/NewActor)
"test.max.new-actor"))
(defspec ^:gen spec-generated-actor-is-valid
(property/generated-entity-is-valid :test.actor/map))
(defspec ^:gen spec-generated-max-actor-is-valid
(property/generated-entity-is-valid :test.max.actor/map))
(defspec ^:gen spec-generated-actor-id-is-valid
(property/generated-entity-id-is-valid :test.actor/map
"actor"))
(defspec ^:gen spec-generated-new-actor-is-valid
(property/generated-entity-is-valid :test.new-actor/map))
(defspec ^:gen spec-generated-max-new-actor-is-valid
(property/generated-entity-is-valid :test.max.actor/map))
(defspec ^:gen spec-generated-new-actor-id-is-valid
(property/generated-entity-id-is-valid :test.new-actor/map
"actor"
:optional))
|
1f93e55dbbeb4c47746e868005eaaaf9e62e32a840bed67d715c11afa9c5be4e | static-analysis-engineering/codehawk | jCHSplitArray.mli | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
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
, 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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
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.
============================================================================= *)
class ['b] split_array_t : int -> 'b ->
object ('a)
val empty_small_array : 'b array
val dim1 : int ref
val dim2 : int ref
val arrays : 'b array array ref
method copy : 'a
method get : int -> 'b
method iteri : (int -> unit) -> unit
method set : int -> 'b -> unit
end
class split_matrix_t : int -> int -> int ->
object ('a)
val empty_small_matrix : int array array array
val dim1 : int ref
val dim2 : int ref
val dim3 : int ref
val dim4 : int ref
val arrays : int array array array array ref
method copy : 'a
method get : int -> int -> int
method set : int -> int -> int -> unit
end
class ['b] split3_array_t : int -> 'b ->
object ('a)
val empty_small_array : 'b array
val empty_medium_array : 'b array array
val dim1 : int ref
val dim2 : int ref
val dim3 : int ref
val arrays : 'b array array array ref
method copy : 'a
method get : int -> 'b
method iteri : (int -> unit) -> unit
method set : int -> 'b -> unit
end
val make : int -> 'b -> 'b split_array_t
val make_empty : 'b -> 'b split_array_t
val make_matrix : int -> int -> int -> split_matrix_t
val make_empty_matrix : int -> split_matrix_t
val make3 : int -> 'b -> 'b split_array_t
val make3_empty : 'b -> 'b split_array_t
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchsys/jCHSplitArray.mli | ocaml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
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
, 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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
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.
============================================================================= *)
class ['b] split_array_t : int -> 'b ->
object ('a)
val empty_small_array : 'b array
val dim1 : int ref
val dim2 : int ref
val arrays : 'b array array ref
method copy : 'a
method get : int -> 'b
method iteri : (int -> unit) -> unit
method set : int -> 'b -> unit
end
class split_matrix_t : int -> int -> int ->
object ('a)
val empty_small_matrix : int array array array
val dim1 : int ref
val dim2 : int ref
val dim3 : int ref
val dim4 : int ref
val arrays : int array array array array ref
method copy : 'a
method get : int -> int -> int
method set : int -> int -> int -> unit
end
class ['b] split3_array_t : int -> 'b ->
object ('a)
val empty_small_array : 'b array
val empty_medium_array : 'b array array
val dim1 : int ref
val dim2 : int ref
val dim3 : int ref
val arrays : 'b array array array ref
method copy : 'a
method get : int -> 'b
method iteri : (int -> unit) -> unit
method set : int -> 'b -> unit
end
val make : int -> 'b -> 'b split_array_t
val make_empty : 'b -> 'b split_array_t
val make_matrix : int -> int -> int -> split_matrix_t
val make_empty_matrix : int -> split_matrix_t
val make3 : int -> 'b -> 'b split_array_t
val make3_empty : 'b -> 'b split_array_t
|
|
6176bebf006f80803534cf22c9ae4e5f8883658dc00ad867be8dc35942778620 | maximedenes/native-coq | declarations.ml | open Errors
open Util
open Names
open Term
open Validate
Bytecode
type values
type reloc_table
type to_patch_substituted
(*Retroknowledge *)
type action
type retroknowledge
type engagement = ImpredicativeSet
let val_eng = val_enum "eng" 1
type polymorphic_arity = {
poly_param_levels : Univ.universe option list;
poly_level : Univ.universe;
}
let val_pol_arity =
val_tuple ~name:"polyorphic_arity"[|val_list(val_opt val_univ);val_univ|]
type constant_type =
| NonPolymorphicType of constr
| PolymorphicArity of rel_context * polymorphic_arity
let val_cst_type =
val_sum "constant_type" 0 [|[|val_constr|];[|val_rctxt;val_pol_arity|]|]
(** Substitutions, code imported from kernel/mod_subst *)
type delta_hint =
| Inline of int * constr option
| Equiv of kernel_name
module Deltamap = struct
type t = module_path MPmap.t * delta_hint KNmap.t
let empty = MPmap.empty, KNmap.empty
let add_kn kn hint (mm,km) = (mm,KNmap.add kn hint km)
let add_mp mp mp' (mm,km) = (MPmap.add mp mp' mm, km)
let remove_mp mp (mm,km) = (MPmap.remove mp mm, km)
let find_mp mp map = MPmap.find mp (fst map)
let find_kn kn map = KNmap.find kn (snd map)
let mem_mp mp map = MPmap.mem mp (fst map)
let mem_kn kn map = KNmap.mem kn (snd map)
let fold_kn f map i = KNmap.fold f (snd map) i
let fold fmp fkn (mm,km) i =
MPmap.fold fmp mm (KNmap.fold fkn km i)
let join map1 map2 = fold add_mp add_kn map1 map2
end
type delta_resolver = Deltamap.t
let empty_delta_resolver = Deltamap.empty
module MBImap = Map.Make
(struct
type t = mod_bound_id
let compare = Pervasives.compare
end)
module Umap = struct
type 'a t = 'a MPmap.t * 'a MBImap.t
let empty = MPmap.empty, MBImap.empty
let is_empty (m1,m2) = MPmap.is_empty m1 && MBImap.is_empty m2
let add_mbi mbi x (m1,m2) = (m1,MBImap.add mbi x m2)
let add_mp mp x (m1,m2) = (MPmap.add mp x m1, m2)
let find_mp mp map = MPmap.find mp (fst map)
let find_mbi mbi map = MBImap.find mbi (snd map)
let mem_mp mp map = MPmap.mem mp (fst map)
let mem_mbi mbi map = MBImap.mem mbi (snd map)
let iter_mbi f map = MBImap.iter f (snd map)
let fold fmp fmbi (m1,m2) i =
MPmap.fold fmp m1 (MBImap.fold fmbi m2 i)
let join map1 map2 = fold add_mp add_mbi map1 map2
end
type substitution = (module_path * delta_resolver) Umap.t
type 'a subst_fun = substitution -> 'a -> 'a
let empty_subst = Umap.empty
let is_empty_subst = Umap.is_empty
let val_delta_hint =
val_sum "delta_hint" 0
[|[|val_int; val_opt val_constr|];[|val_kn|]|]
let val_res =
val_tuple ~name:"delta_resolver"
[|val_map ~name:"delta_resolver" val_mp val_mp;
val_map ~name:"delta_resolver" val_kn val_delta_hint|]
let val_mp_res = val_tuple [|val_mp;val_res|]
let val_subst =
val_tuple ~name:"substitution"
[|val_map ~name:"substitution" val_mp val_mp_res;
val_map ~name:"substitution" val_uid val_mp_res|]
let add_mbid mbid mp = Umap.add_mbi mbid (mp,empty_delta_resolver)
let add_mp mp1 mp2 = Umap.add_mp mp1 (mp2,empty_delta_resolver)
let map_mbid mbid mp = add_mbid mbid mp empty_subst
let map_mp mp1 mp2 = add_mp mp1 mp2 empty_subst
let mp_in_delta mp =
Deltamap.mem_mp mp
let rec find_prefix resolve mp =
let rec sub_mp = function
| MPdot(mp,l) as mp_sup ->
(try Deltamap.find_mp mp_sup resolve
with Not_found -> MPdot(sub_mp mp,l))
| p -> Deltamap.find_mp p resolve
in
try sub_mp mp with Not_found -> mp
* : the following function is slightly different in mod_subst
PL : Is it on purpose ?
PL: Is it on purpose ? *)
let solve_delta_kn resolve kn =
try
match Deltamap.find_kn kn resolve with
| Equiv kn1 -> kn1
| Inline _ -> raise Not_found
with Not_found ->
let mp,dir,l = repr_kn kn in
let new_mp = find_prefix resolve mp in
if mp == new_mp then
kn
else
make_kn new_mp dir l
let gen_of_delta resolve x kn fix_can =
try
let new_kn = solve_delta_kn resolve kn in
if kn == new_kn then x else fix_can new_kn
with _ -> x
let constant_of_delta resolve con =
let kn = user_con con in
gen_of_delta resolve con kn (constant_of_kn_equiv kn)
let constant_of_delta2 resolve con =
let kn, kn' = canonical_con con, user_con con in
gen_of_delta resolve con kn (constant_of_kn_equiv kn')
let mind_of_delta resolve mind =
let kn = user_mind mind in
gen_of_delta resolve mind kn (mind_of_kn_equiv kn)
let mind_of_delta2 resolve mind =
let kn, kn' = canonical_mind mind, user_mind mind in
gen_of_delta resolve mind kn (mind_of_kn_equiv kn')
let find_inline_of_delta kn resolve =
match Deltamap.find_kn kn resolve with
| Inline (_,o) -> o
| _ -> raise Not_found
let constant_of_delta_with_inline resolve con =
let kn1,kn2 = canonical_con con,user_con con in
try find_inline_of_delta kn2 resolve
with Not_found ->
try find_inline_of_delta kn1 resolve
with Not_found -> None
let subst_mp0 sub mp = (* 's like subst *)
let rec aux mp =
match mp with
| MPfile sid -> Umap.find_mp mp sub
| MPbound bid ->
begin
try Umap.find_mbi bid sub
with Not_found -> Umap.find_mp mp sub
end
| MPdot (mp1,l) as mp2 ->
begin
try Umap.find_mp mp2 sub
with Not_found ->
let mp1',resolve = aux mp1 in
MPdot (mp1',l),resolve
end
in
try Some (aux mp) with Not_found -> None
let subst_mp sub mp =
match subst_mp0 sub mp with
None -> mp
| Some (mp',_) -> mp'
let subst_kn_delta sub kn =
let mp,dir,l = repr_kn kn in
match subst_mp0 sub mp with
Some (mp',resolve) ->
solve_delta_kn resolve (make_kn mp' dir l)
| None -> kn
let subst_kn sub kn =
let mp,dir,l = repr_kn kn in
match subst_mp0 sub mp with
Some (mp',_) ->
make_kn mp' dir l
| None -> kn
exception No_subst
type sideconstantsubst =
| User
| Canonical
let gen_subst_mp f sub mp1 mp2 =
match subst_mp0 sub mp1, subst_mp0 sub mp2 with
| None, None -> raise No_subst
| Some (mp',resolve), None -> User, (f mp' mp2), resolve
| None, Some (mp',resolve) -> Canonical, (f mp1 mp'), resolve
| Some (mp1',_), Some (mp2',resolve2) -> Canonical, (f mp1' mp2'), resolve2
let subst_ind sub mind =
let kn1,kn2 = user_mind mind, canonical_mind mind in
let mp1,dir,l = repr_kn kn1 in
let mp2,_,_ = repr_kn kn2 in
let rebuild_mind mp1 mp2 = make_mind_equiv mp1 mp2 dir l in
try
let side,mind',resolve = gen_subst_mp rebuild_mind sub mp1 mp2 in
match side with
| User -> mind_of_delta resolve mind'
| Canonical -> mind_of_delta2 resolve mind'
with No_subst -> mind
let subst_con0 sub con =
let kn1,kn2 = user_con con,canonical_con con in
let mp1,dir,l = repr_kn kn1 in
let mp2,_,_ = repr_kn kn2 in
let rebuild_con mp1 mp2 = make_con_equiv mp1 mp2 dir l in
let dup con = con, Const con in
let side,con',resolve = gen_subst_mp rebuild_con sub mp1 mp2 in
match constant_of_delta_with_inline resolve con' with
| Some t -> con', t
| None ->
let con'' = match side with
| User -> constant_of_delta resolve con'
| Canonical -> constant_of_delta2 resolve con'
in
if con'' == con then raise No_subst else dup con''
let rec map_kn f f' c =
let func = map_kn f f' in
match c with
| Const kn -> (try snd (f' kn) with No_subst -> c)
| Ind (kn,i) ->
let kn' = f kn in
if kn'==kn then c else Ind (kn',i)
| Construct ((kn,i),j) ->
let kn' = f kn in
if kn'==kn then c else Construct ((kn',i),j)
| Case (ci,p,ct,l) ->
let ci_ind =
let (kn,i) = ci.ci_ind in
let kn' = f kn in
if kn'==kn then ci.ci_ind else kn',i
in
let p' = func p in
let ct' = func ct in
let l' = array_smartmap func l in
if (ci.ci_ind==ci_ind && p'==p
&& l'==l && ct'==ct)then c
else
Case ({ci with ci_ind = ci_ind},
p',ct', l')
| Cast (ct,k,t) ->
let ct' = func ct in
let t'= func t in
if (t'==t && ct'==ct) then c
else Cast (ct', k, t')
| Prod (na,t,ct) ->
let ct' = func ct in
let t'= func t in
if (t'==t && ct'==ct) then c
else Prod (na, t', ct')
| Lambda (na,t,ct) ->
let ct' = func ct in
let t'= func t in
if (t'==t && ct'==ct) then c
else Lambda (na, t', ct')
| LetIn (na,b,t,ct) ->
let ct' = func ct in
let t'= func t in
let b'= func b in
if (t'==t && ct'==ct && b==b') then c
else LetIn (na, b', t', ct')
| App (ct,l) ->
let ct' = func ct in
let l' = array_smartmap func l in
if (ct'== ct && l'==l) then c
else App (ct',l')
| Evar (e,l) ->
let l' = array_smartmap func l in
if (l'==l) then c
else Evar (e,l')
| Fix (ln,(lna,tl,bl)) ->
let tl' = array_smartmap func tl in
let bl' = array_smartmap func bl in
if (bl == bl'&& tl == tl') then c
else Fix (ln,(lna,tl',bl'))
| CoFix(ln,(lna,tl,bl)) ->
let tl' = array_smartmap func tl in
let bl' = array_smartmap func bl in
if (bl == bl'&& tl == tl') then c
else CoFix (ln,(lna,tl',bl'))
| _ -> c
let subst_mps sub c =
if is_empty_subst sub then c
else map_kn (subst_ind sub) (subst_con0 sub) c
type 'a lazy_subst =
| LSval of 'a
| LSlazy of substitution list * 'a
type 'a substituted = 'a lazy_subst ref
let val_substituted val_a =
val_ref
(val_sum "constr_substituted" 0
[|[|val_a|];[|val_list val_subst;val_a|]|])
let from_val a = ref (LSval a)
let rec replace_mp_in_mp mpfrom mpto mp =
match mp with
| _ when mp = mpfrom -> mpto
| MPdot (mp1,l) ->
let mp1' = replace_mp_in_mp mpfrom mpto mp1 in
if mp1==mp1' then mp
else MPdot (mp1',l)
| _ -> mp
let rec mp_in_mp mp mp1 =
match mp1 with
| _ when mp1 = mp -> true
| MPdot (mp2,l) -> mp_in_mp mp mp2
| _ -> false
let subset_prefixed_by mp resolver =
let mp_prefix mkey mequ rslv =
if mp_in_mp mp mkey then Deltamap.add_mp mkey mequ rslv else rslv
in
let kn_prefix kn hint rslv =
match hint with
| Inline _ -> rslv
| Equiv _ ->
if mp_in_mp mp (modpath kn) then Deltamap.add_kn kn hint rslv else rslv
in
Deltamap.fold mp_prefix kn_prefix resolver empty_delta_resolver
let subst_dom_delta_resolver subst resolver =
let mp_apply_subst mkey mequ rslv =
Deltamap.add_mp (subst_mp subst mkey) mequ rslv
in
let kn_apply_subst kkey hint rslv =
Deltamap.add_kn (subst_kn subst kkey) hint rslv
in
Deltamap.fold mp_apply_subst kn_apply_subst resolver empty_delta_resolver
let subst_mp_delta sub mp mkey =
match subst_mp0 sub mp with
None -> empty_delta_resolver,mp
| Some (mp',resolve) ->
let mp1 = find_prefix resolve mp' in
let resolve1 = subset_prefixed_by mp1 resolve in
(subst_dom_delta_resolver
(map_mp mp1 mkey) resolve1),mp1
let gen_subst_delta_resolver dom subst resolver =
let mp_apply_subst mkey mequ rslv =
let mkey' = if dom then subst_mp subst mkey else mkey in
let rslv',mequ' = subst_mp_delta subst mequ mkey in
Deltamap.join rslv' (Deltamap.add_mp mkey' mequ' rslv)
in
let kn_apply_subst kkey hint rslv =
let kkey' = if dom then subst_kn subst kkey else kkey in
let hint' = match hint with
| Equiv kequ -> Equiv (subst_kn_delta subst kequ)
| Inline (lev,Some t) -> Inline (lev,Some (subst_mps subst t))
| Inline (_,None) -> hint
in
Deltamap.add_kn kkey' hint' rslv
in
Deltamap.fold mp_apply_subst kn_apply_subst resolver empty_delta_resolver
let subst_codom_delta_resolver = gen_subst_delta_resolver false
let subst_dom_codom_delta_resolver = gen_subst_delta_resolver true
let update_delta_resolver resolver1 resolver2 =
let mp_apply_rslv mkey mequ rslv =
if Deltamap.mem_mp mkey resolver2 then rslv
else Deltamap.add_mp mkey (find_prefix resolver2 mequ) rslv
in
let kn_apply_rslv kkey hint rslv =
if Deltamap.mem_kn kkey resolver2 then rslv
else
let hint' = match hint with
| Equiv kequ -> Equiv (solve_delta_kn resolver2 kequ)
| _ -> hint
in
Deltamap.add_kn kkey hint' rslv
in
Deltamap.fold mp_apply_rslv kn_apply_rslv resolver1 empty_delta_resolver
let add_delta_resolver resolver1 resolver2 =
if resolver1 == resolver2 then
resolver2
else if resolver2 = empty_delta_resolver then
resolver1
else
Deltamap.join (update_delta_resolver resolver1 resolver2) resolver2
let substition_prefixed_by k mp subst =
let mp_prefixmp kmp (mp_to,reso) sub =
if mp_in_mp mp kmp && mp <> kmp then
let new_key = replace_mp_in_mp mp k kmp in
Umap.add_mp new_key (mp_to,reso) sub
else sub
in
let mbi_prefixmp mbi _ sub = sub
in
Umap.fold mp_prefixmp mbi_prefixmp subst empty_subst
let join subst1 subst2 =
let apply_subst mpk add (mp,resolve) res =
let mp',resolve' =
match subst_mp0 subst2 mp with
| None -> mp, None
| Some (mp',resolve') -> mp', Some resolve' in
let resolve'' =
match resolve' with
| Some res ->
add_delta_resolver
(subst_dom_codom_delta_resolver subst2 resolve) res
| None ->
subst_codom_delta_resolver subst2 resolve
in
let prefixed_subst = substition_prefixed_by mpk mp' subst2 in
Umap.join prefixed_subst (add (mp',resolve'') res)
in
let mp_apply_subst mp = apply_subst mp (Umap.add_mp mp) in
let mbi_apply_subst mbi = apply_subst (MPbound mbi) (Umap.add_mbi mbi) in
let subst = Umap.fold mp_apply_subst mbi_apply_subst subst1 empty_subst in
Umap.join subst2 subst
let force fsubst r =
match !r with
| LSval a -> a
| LSlazy(s,a) ->
let subst = List.fold_left join empty_subst (List.rev s) in
let a' = fsubst subst a in
r := LSval a';
a'
let subst_substituted s r =
match !r with
| LSval a -> ref (LSlazy([s],a))
| LSlazy(s',a) ->
ref (LSlazy(s::s',a))
let force_constr = force subst_mps
type constr_substituted = constr substituted
let val_cstr_subst = val_substituted val_constr
let subst_constr_subst = subst_substituted
* Beware ! In .vo files , lazy_constr are stored as integers
used as indexes for a separate table . The actual lazy_constr is restored
later , by [ Safe_typing.LightenLibrary.load ] . This allows us
to use here a different definition of lazy_constr than coqtop :
since the checker will inspect all proofs parts , even opaque
ones , no need to use Lazy.t here
used as indexes for a separate table. The actual lazy_constr is restored
later, by [Safe_typing.LightenLibrary.load]. This allows us
to use here a different definition of lazy_constr than coqtop:
since the checker will inspect all proofs parts, even opaque
ones, no need to use Lazy.t here *)
type lazy_constr = constr_substituted
let subst_lazy_constr = subst_substituted
let force_lazy_constr = force_constr
let lazy_constr_from_val c = c
let val_lazy_constr = val_cstr_subst
(** Inlining level of parameters at functor applications.
This is ignored by the checker. *)
type inline = int option
(** A constant can have no body (axiom/parameter), or a
transparent body, or an opaque one *)
type constant_def =
| Undef of inline
| Def of constr_substituted
| OpaqueDef of lazy_constr
let val_cst_def =
val_sum "constant_def" 0
[|[|val_opt val_int|]; [|val_cstr_subst|]; [|val_lazy_constr|]|]
let subst_constant_def sub = function
| Undef inl -> Undef inl
| Def c -> Def (subst_constr_subst sub c)
| OpaqueDef lc -> OpaqueDef (subst_lazy_constr sub lc)
type constant_body = {
const_hyps : section_context; (* New: younger hyp at top *)
const_body : constant_def;
const_type : constant_type;
const_body_code : to_patch_substituted;
const_constraints : Univ.constraints }
let body_of_constant cb = match cb.const_body with
| Undef _ -> None
| Def c -> Some c
| OpaqueDef c -> Some c
let constant_has_body cb = match cb.const_body with
| Undef _ -> false
| Def _ | OpaqueDef _ -> true
let is_opaque cb = match cb.const_body with
| OpaqueDef _ -> true
| Def _ | Undef _ -> false
let val_cb = val_tuple ~name:"constant_body"
[|val_nctxt;
val_cst_def;
val_cst_type;
no_val;
val_cstrs|]
let subst_rel_declaration sub (id,copt,t as x) =
let copt' = Option.smartmap (subst_mps sub) copt in
let t' = subst_mps sub t in
if copt == copt' & t == t' then x else (id,copt',t')
let subst_rel_context sub = list_smartmap (subst_rel_declaration sub)
type recarg =
| Norec
| Mrec of inductive
| Imbr of inductive
Norec
let subst_recarg sub r = match r with
| Norec -> r
| (Mrec(kn,i)|Imbr (kn,i)) -> let kn' = subst_ind sub kn in
if kn==kn' then r else Imbr (kn',i)
type wf_paths = recarg Rtree.t
let val_wfp = val_rec_sum "wf_paths" 0
(fun val_wfp ->
[|[|val_int;val_int|]; (* Rtree.Param *)
[|val_recarg;val_array val_wfp|]; (* Rtree.Node *)
[|val_int;val_array val_wfp|] (* Rtree.Rec *)
|])
let mk_norec = Rtree.mk_node Norec [||]
let mk_paths r recargs =
Rtree.mk_node r
(Array.map (fun l -> Rtree.mk_node Norec (Array.of_list l)) recargs)
let dest_recarg p = fst (Rtree.dest_node p)
let dest_subterms p =
let (_,cstrs) = Rtree.dest_node p in
Array.map (fun t -> Array.to_list (snd (Rtree.dest_node t))) cstrs
let subst_wf_paths sub p = Rtree.smartmap (subst_recarg sub) p
(**********************************************************************)
(* Representation of mutual inductive types in the kernel *)
Inductive I1 ( params ) : U1 : = c11 : T11 | ... | c1p1 : T1p1
...
with In ( params ) : Un : = cn1 : Tn1 | ... | : Tnpn
Inductive I1 (params) : U1 := c11 : T11 | ... | c1p1 : T1p1
...
with In (params) : Un := cn1 : Tn1 | ... | cnpn : Tnpn
*)
type monomorphic_inductive_arity = {
mind_user_arity : constr;
mind_sort : sorts;
}
let val_mono_ind_arity =
val_tuple ~name:"monomorphic_inductive_arity"[|val_constr;val_sort|]
type inductive_arity =
| Monomorphic of monomorphic_inductive_arity
| Polymorphic of polymorphic_arity
let val_ind_arity = val_sum "inductive_arity" 0
[|[|val_mono_ind_arity|];[|val_pol_arity|]|]
type one_inductive_body = {
(* Primitive datas *)
(* Name of the type: [Ii] *)
mind_typename : identifier;
(* Arity context of [Ii] with parameters: [forall params, Ui] *)
mind_arity_ctxt : rel_context;
(* Arity sort, original user arity, and allowed elim sorts, if monomorphic *)
mind_arity : inductive_arity;
(* Names of the constructors: [cij] *)
mind_consnames : identifier array;
Types of the constructors with parameters : [ forall params , Tij ] ,
where the Ik are replaced by de Bruijn index in the context
I1 : forall params , U1 .. In : forall params , Un
where the Ik are replaced by de Bruijn index in the context
I1:forall params, U1 .. In:forall params, Un *)
mind_user_lc : constr array;
(* Derived datas *)
(* Number of expected real arguments of the type (no let, no params) *)
mind_nrealargs : int;
(* Length of realargs context (with let, no params) *)
mind_nrealargs_ctxt : int;
(* List of allowed elimination sorts *)
mind_kelim : sorts_family list;
(* Head normalized constructor types so that their conclusion is atomic *)
mind_nf_lc : constr array;
(* Length of the signature of the constructors (with let, w/o params) *)
mind_consnrealdecls : int array;
(* Signature of recursive arguments in the constructors *)
mind_recargs : wf_paths;
(* Datas for bytecode compilation *)
(* number of constant constructor *)
mind_nb_constant : int;
(* number of no constant constructor *)
mind_nb_args : int;
mind_reloc_tbl : reloc_table;
}
let val_one_ind = val_tuple ~name:"one_inductive_body"
[|val_id;val_rctxt;val_ind_arity;val_array val_id;val_array val_constr;
val_int;val_int;val_list val_sortfam;val_array val_constr;val_array val_int;
val_wfp;val_int;val_int;no_val|]
type mutual_inductive_body = {
(* The component of the mutual inductive block *)
mind_packets : one_inductive_body array;
(* Whether the inductive type has been declared as a record *)
mind_record : bool;
(* Whether the type is inductive or coinductive *)
mind_finite : bool;
(* Number of types in the block *)
mind_ntypes : int;
(* Section hypotheses on which the block depends *)
mind_hyps : section_context;
(* Number of expected parameters *)
mind_nparams : int;
(* Number of recursively uniform (i.e. ordinary) parameters *)
mind_nparams_rec : int;
(* The context of parameters (includes let-in declaration) *)
mind_params_ctxt : rel_context;
Universes constraints enforced by the inductive declaration
mind_constraints : Univ.constraints;
}
let val_ind_pack = val_tuple ~name:"mutual_inductive_body"
[|val_array val_one_ind;val_bool;val_bool;val_int;val_nctxt;
val_int; val_int; val_rctxt;val_cstrs|]
let subst_arity sub = function
| NonPolymorphicType s -> NonPolymorphicType (subst_mps sub s)
| PolymorphicArity (ctx,s) -> PolymorphicArity (subst_rel_context sub ctx,s)
TODO : should be changed to non - coping after Term.subst_mps
let subst_const_body sub cb = {
const_hyps = (assert (cb.const_hyps=[]); []);
const_body = subst_constant_def sub cb.const_body;
const_type = subst_arity sub cb.const_type;
sub
const_constraints = cb.const_constraints}
let subst_arity sub = function
| Monomorphic s ->
Monomorphic {
mind_user_arity = subst_mps sub s.mind_user_arity;
mind_sort = s.mind_sort;
}
| Polymorphic s as x -> x
let subst_mind_packet sub mbp =
{ mind_consnames = mbp.mind_consnames;
mind_consnrealdecls = mbp.mind_consnrealdecls;
mind_typename = mbp.mind_typename;
mind_nf_lc = array_smartmap (subst_mps sub) mbp.mind_nf_lc;
mind_arity_ctxt = subst_rel_context sub mbp.mind_arity_ctxt;
mind_arity = subst_arity sub mbp.mind_arity;
mind_user_lc = array_smartmap (subst_mps sub) mbp.mind_user_lc;
mind_nrealargs = mbp.mind_nrealargs;
mind_nrealargs_ctxt = mbp.mind_nrealargs_ctxt;
mind_kelim = mbp.mind_kelim;
mind_recargs = subst_wf_paths sub mbp.mind_recargs (*wf_paths*);
mind_nb_constant = mbp.mind_nb_constant;
mind_nb_args = mbp.mind_nb_args;
mind_reloc_tbl = mbp.mind_reloc_tbl }
let subst_mind sub mib =
{ mind_record = mib.mind_record ;
mind_finite = mib.mind_finite ;
mind_ntypes = mib.mind_ntypes ;
mind_hyps = (assert (mib.mind_hyps=[]); []) ;
mind_nparams = mib.mind_nparams;
mind_nparams_rec = mib.mind_nparams_rec;
mind_params_ctxt =
map_rel_context (subst_mps sub) mib.mind_params_ctxt;
mind_packets = array_smartmap (subst_mind_packet sub) mib.mind_packets ;
mind_constraints = mib.mind_constraints }
(* Modules *)
(* Whenever you change these types, please do update the validation
functions below *)
type structure_field_body =
| SFBconst of constant_body
| SFBmind of mutual_inductive_body
| SFBmodule of module_body
| SFBmodtype of module_type_body
and structure_body = (label * structure_field_body) list
and struct_expr_body =
| SEBident of module_path
| SEBfunctor of mod_bound_id * module_type_body * struct_expr_body
| SEBapply of struct_expr_body * struct_expr_body * Univ.constraints
| SEBstruct of structure_body
| SEBwith of struct_expr_body * with_declaration_body
and with_declaration_body =
With_module_body of identifier list * module_path
| With_definition_body of identifier list * constant_body
and module_body =
{ mod_mp : module_path;
mod_expr : struct_expr_body option;
mod_type : struct_expr_body;
mod_type_alg : struct_expr_body option;
mod_constraints : Univ.constraints;
mod_delta : delta_resolver;
mod_retroknowledge : action list}
and module_type_body =
{ typ_mp : module_path;
typ_expr : struct_expr_body;
typ_expr_alg : struct_expr_body option ;
typ_constraints : Univ.constraints;
typ_delta :delta_resolver}
(* the validation functions: *)
let rec val_sfb o = val_sum "struct_field_body" 0
SFBconst
SFBmind
SFBmodule
SFBmodtype
|] o
and val_sb o = val_list (val_tuple ~name:"label*sfb"[|val_id;val_sfb|]) o
and val_seb o = val_sum "struct_expr_body" 0
[|[|val_mp|]; (* SEBident *)
[|val_uid;val_modtype;val_seb|]; (* SEBfunctor *)
SEBapply
SEBstruct
|] o
and val_with o = val_sum "with_declaration_body" 0
[|[|val_list val_id;val_mp|];
[|val_list val_id;val_cb|]|] o
and val_module o = val_tuple ~name:"module_body"
[|val_mp;val_opt val_seb;val_seb;
val_opt val_seb;val_cstrs;val_res;no_val|] o
and val_modtype o = val_tuple ~name:"module_type_body"
[|val_mp;val_seb;val_opt val_seb;val_cstrs;val_res|] o
let rec subst_with_body sub = function
| With_module_body(id,mp) ->
With_module_body(id,subst_mp sub mp)
| With_definition_body(id,cb) ->
With_definition_body( id,subst_const_body sub cb)
and subst_modtype sub mtb=
let typ_expr' = subst_struct_expr sub mtb.typ_expr in
let typ_alg' =
Option.smartmap
(subst_struct_expr sub) mtb.typ_expr_alg in
let mp = subst_mp sub mtb.typ_mp
in
if typ_expr'==mtb.typ_expr &&
typ_alg'==mtb.typ_expr_alg && mp==mtb.typ_mp then
mtb
else
{mtb with
typ_mp = mp;
typ_expr = typ_expr';
typ_expr_alg = typ_alg'}
and subst_structure sub sign =
let subst_body = function
SFBconst cb ->
SFBconst (subst_const_body sub cb)
| SFBmind mib ->
SFBmind (subst_mind sub mib)
| SFBmodule mb ->
SFBmodule (subst_module sub mb)
| SFBmodtype mtb ->
SFBmodtype (subst_modtype sub mtb)
in
List.map (fun (l,b) -> (l,subst_body b)) sign
and subst_module sub mb =
let mtb' = subst_struct_expr sub mb.mod_type in
let typ_alg' = Option.smartmap
(subst_struct_expr sub ) mb.mod_type_alg in
let me' = Option.smartmap
(subst_struct_expr sub) mb.mod_expr in
let mp = subst_mp sub mb.mod_mp in
if mtb'==mb.mod_type && mb.mod_expr == me'
&& mp == mb.mod_mp
then mb else
{ mb with
mod_mp = mp;
mod_expr = me';
mod_type_alg = typ_alg';
mod_type=mtb'}
and subst_struct_expr sub = function
| SEBident mp -> SEBident (subst_mp sub mp)
| SEBfunctor (mbid, mtb, meb') ->
SEBfunctor(mbid,subst_modtype sub mtb
,subst_struct_expr sub meb')
| SEBstruct (str)->
SEBstruct( subst_structure sub str)
| SEBapply (meb1,meb2,cst)->
SEBapply(subst_struct_expr sub meb1,
subst_struct_expr sub meb2,
cst)
| SEBwith (meb,wdb)->
SEBwith(subst_struct_expr sub meb,
subst_with_body sub wdb)
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/checker/declarations.ml | ocaml | Retroknowledge
* Substitutions, code imported from kernel/mod_subst
's like subst
* Inlining level of parameters at functor applications.
This is ignored by the checker.
* A constant can have no body (axiom/parameter), or a
transparent body, or an opaque one
New: younger hyp at top
Rtree.Param
Rtree.Node
Rtree.Rec
********************************************************************
Representation of mutual inductive types in the kernel
Primitive datas
Name of the type: [Ii]
Arity context of [Ii] with parameters: [forall params, Ui]
Arity sort, original user arity, and allowed elim sorts, if monomorphic
Names of the constructors: [cij]
Derived datas
Number of expected real arguments of the type (no let, no params)
Length of realargs context (with let, no params)
List of allowed elimination sorts
Head normalized constructor types so that their conclusion is atomic
Length of the signature of the constructors (with let, w/o params)
Signature of recursive arguments in the constructors
Datas for bytecode compilation
number of constant constructor
number of no constant constructor
The component of the mutual inductive block
Whether the inductive type has been declared as a record
Whether the type is inductive or coinductive
Number of types in the block
Section hypotheses on which the block depends
Number of expected parameters
Number of recursively uniform (i.e. ordinary) parameters
The context of parameters (includes let-in declaration)
wf_paths
Modules
Whenever you change these types, please do update the validation
functions below
the validation functions:
SEBident
SEBfunctor | open Errors
open Util
open Names
open Term
open Validate
Bytecode
type values
type reloc_table
type to_patch_substituted
type action
type retroknowledge
type engagement = ImpredicativeSet
let val_eng = val_enum "eng" 1
type polymorphic_arity = {
poly_param_levels : Univ.universe option list;
poly_level : Univ.universe;
}
let val_pol_arity =
val_tuple ~name:"polyorphic_arity"[|val_list(val_opt val_univ);val_univ|]
type constant_type =
| NonPolymorphicType of constr
| PolymorphicArity of rel_context * polymorphic_arity
let val_cst_type =
val_sum "constant_type" 0 [|[|val_constr|];[|val_rctxt;val_pol_arity|]|]
type delta_hint =
| Inline of int * constr option
| Equiv of kernel_name
module Deltamap = struct
type t = module_path MPmap.t * delta_hint KNmap.t
let empty = MPmap.empty, KNmap.empty
let add_kn kn hint (mm,km) = (mm,KNmap.add kn hint km)
let add_mp mp mp' (mm,km) = (MPmap.add mp mp' mm, km)
let remove_mp mp (mm,km) = (MPmap.remove mp mm, km)
let find_mp mp map = MPmap.find mp (fst map)
let find_kn kn map = KNmap.find kn (snd map)
let mem_mp mp map = MPmap.mem mp (fst map)
let mem_kn kn map = KNmap.mem kn (snd map)
let fold_kn f map i = KNmap.fold f (snd map) i
let fold fmp fkn (mm,km) i =
MPmap.fold fmp mm (KNmap.fold fkn km i)
let join map1 map2 = fold add_mp add_kn map1 map2
end
type delta_resolver = Deltamap.t
let empty_delta_resolver = Deltamap.empty
module MBImap = Map.Make
(struct
type t = mod_bound_id
let compare = Pervasives.compare
end)
module Umap = struct
type 'a t = 'a MPmap.t * 'a MBImap.t
let empty = MPmap.empty, MBImap.empty
let is_empty (m1,m2) = MPmap.is_empty m1 && MBImap.is_empty m2
let add_mbi mbi x (m1,m2) = (m1,MBImap.add mbi x m2)
let add_mp mp x (m1,m2) = (MPmap.add mp x m1, m2)
let find_mp mp map = MPmap.find mp (fst map)
let find_mbi mbi map = MBImap.find mbi (snd map)
let mem_mp mp map = MPmap.mem mp (fst map)
let mem_mbi mbi map = MBImap.mem mbi (snd map)
let iter_mbi f map = MBImap.iter f (snd map)
let fold fmp fmbi (m1,m2) i =
MPmap.fold fmp m1 (MBImap.fold fmbi m2 i)
let join map1 map2 = fold add_mp add_mbi map1 map2
end
type substitution = (module_path * delta_resolver) Umap.t
type 'a subst_fun = substitution -> 'a -> 'a
let empty_subst = Umap.empty
let is_empty_subst = Umap.is_empty
let val_delta_hint =
val_sum "delta_hint" 0
[|[|val_int; val_opt val_constr|];[|val_kn|]|]
let val_res =
val_tuple ~name:"delta_resolver"
[|val_map ~name:"delta_resolver" val_mp val_mp;
val_map ~name:"delta_resolver" val_kn val_delta_hint|]
let val_mp_res = val_tuple [|val_mp;val_res|]
let val_subst =
val_tuple ~name:"substitution"
[|val_map ~name:"substitution" val_mp val_mp_res;
val_map ~name:"substitution" val_uid val_mp_res|]
let add_mbid mbid mp = Umap.add_mbi mbid (mp,empty_delta_resolver)
let add_mp mp1 mp2 = Umap.add_mp mp1 (mp2,empty_delta_resolver)
let map_mbid mbid mp = add_mbid mbid mp empty_subst
let map_mp mp1 mp2 = add_mp mp1 mp2 empty_subst
let mp_in_delta mp =
Deltamap.mem_mp mp
let rec find_prefix resolve mp =
let rec sub_mp = function
| MPdot(mp,l) as mp_sup ->
(try Deltamap.find_mp mp_sup resolve
with Not_found -> MPdot(sub_mp mp,l))
| p -> Deltamap.find_mp p resolve
in
try sub_mp mp with Not_found -> mp
* : the following function is slightly different in mod_subst
PL : Is it on purpose ?
PL: Is it on purpose ? *)
let solve_delta_kn resolve kn =
try
match Deltamap.find_kn kn resolve with
| Equiv kn1 -> kn1
| Inline _ -> raise Not_found
with Not_found ->
let mp,dir,l = repr_kn kn in
let new_mp = find_prefix resolve mp in
if mp == new_mp then
kn
else
make_kn new_mp dir l
let gen_of_delta resolve x kn fix_can =
try
let new_kn = solve_delta_kn resolve kn in
if kn == new_kn then x else fix_can new_kn
with _ -> x
let constant_of_delta resolve con =
let kn = user_con con in
gen_of_delta resolve con kn (constant_of_kn_equiv kn)
let constant_of_delta2 resolve con =
let kn, kn' = canonical_con con, user_con con in
gen_of_delta resolve con kn (constant_of_kn_equiv kn')
let mind_of_delta resolve mind =
let kn = user_mind mind in
gen_of_delta resolve mind kn (mind_of_kn_equiv kn)
let mind_of_delta2 resolve mind =
let kn, kn' = canonical_mind mind, user_mind mind in
gen_of_delta resolve mind kn (mind_of_kn_equiv kn')
let find_inline_of_delta kn resolve =
match Deltamap.find_kn kn resolve with
| Inline (_,o) -> o
| _ -> raise Not_found
let constant_of_delta_with_inline resolve con =
let kn1,kn2 = canonical_con con,user_con con in
try find_inline_of_delta kn2 resolve
with Not_found ->
try find_inline_of_delta kn1 resolve
with Not_found -> None
let rec aux mp =
match mp with
| MPfile sid -> Umap.find_mp mp sub
| MPbound bid ->
begin
try Umap.find_mbi bid sub
with Not_found -> Umap.find_mp mp sub
end
| MPdot (mp1,l) as mp2 ->
begin
try Umap.find_mp mp2 sub
with Not_found ->
let mp1',resolve = aux mp1 in
MPdot (mp1',l),resolve
end
in
try Some (aux mp) with Not_found -> None
let subst_mp sub mp =
match subst_mp0 sub mp with
None -> mp
| Some (mp',_) -> mp'
let subst_kn_delta sub kn =
let mp,dir,l = repr_kn kn in
match subst_mp0 sub mp with
Some (mp',resolve) ->
solve_delta_kn resolve (make_kn mp' dir l)
| None -> kn
let subst_kn sub kn =
let mp,dir,l = repr_kn kn in
match subst_mp0 sub mp with
Some (mp',_) ->
make_kn mp' dir l
| None -> kn
exception No_subst
type sideconstantsubst =
| User
| Canonical
let gen_subst_mp f sub mp1 mp2 =
match subst_mp0 sub mp1, subst_mp0 sub mp2 with
| None, None -> raise No_subst
| Some (mp',resolve), None -> User, (f mp' mp2), resolve
| None, Some (mp',resolve) -> Canonical, (f mp1 mp'), resolve
| Some (mp1',_), Some (mp2',resolve2) -> Canonical, (f mp1' mp2'), resolve2
let subst_ind sub mind =
let kn1,kn2 = user_mind mind, canonical_mind mind in
let mp1,dir,l = repr_kn kn1 in
let mp2,_,_ = repr_kn kn2 in
let rebuild_mind mp1 mp2 = make_mind_equiv mp1 mp2 dir l in
try
let side,mind',resolve = gen_subst_mp rebuild_mind sub mp1 mp2 in
match side with
| User -> mind_of_delta resolve mind'
| Canonical -> mind_of_delta2 resolve mind'
with No_subst -> mind
let subst_con0 sub con =
let kn1,kn2 = user_con con,canonical_con con in
let mp1,dir,l = repr_kn kn1 in
let mp2,_,_ = repr_kn kn2 in
let rebuild_con mp1 mp2 = make_con_equiv mp1 mp2 dir l in
let dup con = con, Const con in
let side,con',resolve = gen_subst_mp rebuild_con sub mp1 mp2 in
match constant_of_delta_with_inline resolve con' with
| Some t -> con', t
| None ->
let con'' = match side with
| User -> constant_of_delta resolve con'
| Canonical -> constant_of_delta2 resolve con'
in
if con'' == con then raise No_subst else dup con''
let rec map_kn f f' c =
let func = map_kn f f' in
match c with
| Const kn -> (try snd (f' kn) with No_subst -> c)
| Ind (kn,i) ->
let kn' = f kn in
if kn'==kn then c else Ind (kn',i)
| Construct ((kn,i),j) ->
let kn' = f kn in
if kn'==kn then c else Construct ((kn',i),j)
| Case (ci,p,ct,l) ->
let ci_ind =
let (kn,i) = ci.ci_ind in
let kn' = f kn in
if kn'==kn then ci.ci_ind else kn',i
in
let p' = func p in
let ct' = func ct in
let l' = array_smartmap func l in
if (ci.ci_ind==ci_ind && p'==p
&& l'==l && ct'==ct)then c
else
Case ({ci with ci_ind = ci_ind},
p',ct', l')
| Cast (ct,k,t) ->
let ct' = func ct in
let t'= func t in
if (t'==t && ct'==ct) then c
else Cast (ct', k, t')
| Prod (na,t,ct) ->
let ct' = func ct in
let t'= func t in
if (t'==t && ct'==ct) then c
else Prod (na, t', ct')
| Lambda (na,t,ct) ->
let ct' = func ct in
let t'= func t in
if (t'==t && ct'==ct) then c
else Lambda (na, t', ct')
| LetIn (na,b,t,ct) ->
let ct' = func ct in
let t'= func t in
let b'= func b in
if (t'==t && ct'==ct && b==b') then c
else LetIn (na, b', t', ct')
| App (ct,l) ->
let ct' = func ct in
let l' = array_smartmap func l in
if (ct'== ct && l'==l) then c
else App (ct',l')
| Evar (e,l) ->
let l' = array_smartmap func l in
if (l'==l) then c
else Evar (e,l')
| Fix (ln,(lna,tl,bl)) ->
let tl' = array_smartmap func tl in
let bl' = array_smartmap func bl in
if (bl == bl'&& tl == tl') then c
else Fix (ln,(lna,tl',bl'))
| CoFix(ln,(lna,tl,bl)) ->
let tl' = array_smartmap func tl in
let bl' = array_smartmap func bl in
if (bl == bl'&& tl == tl') then c
else CoFix (ln,(lna,tl',bl'))
| _ -> c
let subst_mps sub c =
if is_empty_subst sub then c
else map_kn (subst_ind sub) (subst_con0 sub) c
type 'a lazy_subst =
| LSval of 'a
| LSlazy of substitution list * 'a
type 'a substituted = 'a lazy_subst ref
let val_substituted val_a =
val_ref
(val_sum "constr_substituted" 0
[|[|val_a|];[|val_list val_subst;val_a|]|])
let from_val a = ref (LSval a)
let rec replace_mp_in_mp mpfrom mpto mp =
match mp with
| _ when mp = mpfrom -> mpto
| MPdot (mp1,l) ->
let mp1' = replace_mp_in_mp mpfrom mpto mp1 in
if mp1==mp1' then mp
else MPdot (mp1',l)
| _ -> mp
let rec mp_in_mp mp mp1 =
match mp1 with
| _ when mp1 = mp -> true
| MPdot (mp2,l) -> mp_in_mp mp mp2
| _ -> false
let subset_prefixed_by mp resolver =
let mp_prefix mkey mequ rslv =
if mp_in_mp mp mkey then Deltamap.add_mp mkey mequ rslv else rslv
in
let kn_prefix kn hint rslv =
match hint with
| Inline _ -> rslv
| Equiv _ ->
if mp_in_mp mp (modpath kn) then Deltamap.add_kn kn hint rslv else rslv
in
Deltamap.fold mp_prefix kn_prefix resolver empty_delta_resolver
let subst_dom_delta_resolver subst resolver =
let mp_apply_subst mkey mequ rslv =
Deltamap.add_mp (subst_mp subst mkey) mequ rslv
in
let kn_apply_subst kkey hint rslv =
Deltamap.add_kn (subst_kn subst kkey) hint rslv
in
Deltamap.fold mp_apply_subst kn_apply_subst resolver empty_delta_resolver
let subst_mp_delta sub mp mkey =
match subst_mp0 sub mp with
None -> empty_delta_resolver,mp
| Some (mp',resolve) ->
let mp1 = find_prefix resolve mp' in
let resolve1 = subset_prefixed_by mp1 resolve in
(subst_dom_delta_resolver
(map_mp mp1 mkey) resolve1),mp1
let gen_subst_delta_resolver dom subst resolver =
let mp_apply_subst mkey mequ rslv =
let mkey' = if dom then subst_mp subst mkey else mkey in
let rslv',mequ' = subst_mp_delta subst mequ mkey in
Deltamap.join rslv' (Deltamap.add_mp mkey' mequ' rslv)
in
let kn_apply_subst kkey hint rslv =
let kkey' = if dom then subst_kn subst kkey else kkey in
let hint' = match hint with
| Equiv kequ -> Equiv (subst_kn_delta subst kequ)
| Inline (lev,Some t) -> Inline (lev,Some (subst_mps subst t))
| Inline (_,None) -> hint
in
Deltamap.add_kn kkey' hint' rslv
in
Deltamap.fold mp_apply_subst kn_apply_subst resolver empty_delta_resolver
let subst_codom_delta_resolver = gen_subst_delta_resolver false
let subst_dom_codom_delta_resolver = gen_subst_delta_resolver true
let update_delta_resolver resolver1 resolver2 =
let mp_apply_rslv mkey mequ rslv =
if Deltamap.mem_mp mkey resolver2 then rslv
else Deltamap.add_mp mkey (find_prefix resolver2 mequ) rslv
in
let kn_apply_rslv kkey hint rslv =
if Deltamap.mem_kn kkey resolver2 then rslv
else
let hint' = match hint with
| Equiv kequ -> Equiv (solve_delta_kn resolver2 kequ)
| _ -> hint
in
Deltamap.add_kn kkey hint' rslv
in
Deltamap.fold mp_apply_rslv kn_apply_rslv resolver1 empty_delta_resolver
let add_delta_resolver resolver1 resolver2 =
if resolver1 == resolver2 then
resolver2
else if resolver2 = empty_delta_resolver then
resolver1
else
Deltamap.join (update_delta_resolver resolver1 resolver2) resolver2
let substition_prefixed_by k mp subst =
let mp_prefixmp kmp (mp_to,reso) sub =
if mp_in_mp mp kmp && mp <> kmp then
let new_key = replace_mp_in_mp mp k kmp in
Umap.add_mp new_key (mp_to,reso) sub
else sub
in
let mbi_prefixmp mbi _ sub = sub
in
Umap.fold mp_prefixmp mbi_prefixmp subst empty_subst
let join subst1 subst2 =
let apply_subst mpk add (mp,resolve) res =
let mp',resolve' =
match subst_mp0 subst2 mp with
| None -> mp, None
| Some (mp',resolve') -> mp', Some resolve' in
let resolve'' =
match resolve' with
| Some res ->
add_delta_resolver
(subst_dom_codom_delta_resolver subst2 resolve) res
| None ->
subst_codom_delta_resolver subst2 resolve
in
let prefixed_subst = substition_prefixed_by mpk mp' subst2 in
Umap.join prefixed_subst (add (mp',resolve'') res)
in
let mp_apply_subst mp = apply_subst mp (Umap.add_mp mp) in
let mbi_apply_subst mbi = apply_subst (MPbound mbi) (Umap.add_mbi mbi) in
let subst = Umap.fold mp_apply_subst mbi_apply_subst subst1 empty_subst in
Umap.join subst2 subst
let force fsubst r =
match !r with
| LSval a -> a
| LSlazy(s,a) ->
let subst = List.fold_left join empty_subst (List.rev s) in
let a' = fsubst subst a in
r := LSval a';
a'
let subst_substituted s r =
match !r with
| LSval a -> ref (LSlazy([s],a))
| LSlazy(s',a) ->
ref (LSlazy(s::s',a))
let force_constr = force subst_mps
type constr_substituted = constr substituted
let val_cstr_subst = val_substituted val_constr
let subst_constr_subst = subst_substituted
* Beware ! In .vo files , lazy_constr are stored as integers
used as indexes for a separate table . The actual lazy_constr is restored
later , by [ Safe_typing.LightenLibrary.load ] . This allows us
to use here a different definition of lazy_constr than coqtop :
since the checker will inspect all proofs parts , even opaque
ones , no need to use Lazy.t here
used as indexes for a separate table. The actual lazy_constr is restored
later, by [Safe_typing.LightenLibrary.load]. This allows us
to use here a different definition of lazy_constr than coqtop:
since the checker will inspect all proofs parts, even opaque
ones, no need to use Lazy.t here *)
type lazy_constr = constr_substituted
let subst_lazy_constr = subst_substituted
let force_lazy_constr = force_constr
let lazy_constr_from_val c = c
let val_lazy_constr = val_cstr_subst
type inline = int option
type constant_def =
| Undef of inline
| Def of constr_substituted
| OpaqueDef of lazy_constr
let val_cst_def =
val_sum "constant_def" 0
[|[|val_opt val_int|]; [|val_cstr_subst|]; [|val_lazy_constr|]|]
let subst_constant_def sub = function
| Undef inl -> Undef inl
| Def c -> Def (subst_constr_subst sub c)
| OpaqueDef lc -> OpaqueDef (subst_lazy_constr sub lc)
type constant_body = {
const_body : constant_def;
const_type : constant_type;
const_body_code : to_patch_substituted;
const_constraints : Univ.constraints }
let body_of_constant cb = match cb.const_body with
| Undef _ -> None
| Def c -> Some c
| OpaqueDef c -> Some c
let constant_has_body cb = match cb.const_body with
| Undef _ -> false
| Def _ | OpaqueDef _ -> true
let is_opaque cb = match cb.const_body with
| OpaqueDef _ -> true
| Def _ | Undef _ -> false
let val_cb = val_tuple ~name:"constant_body"
[|val_nctxt;
val_cst_def;
val_cst_type;
no_val;
val_cstrs|]
let subst_rel_declaration sub (id,copt,t as x) =
let copt' = Option.smartmap (subst_mps sub) copt in
let t' = subst_mps sub t in
if copt == copt' & t == t' then x else (id,copt',t')
let subst_rel_context sub = list_smartmap (subst_rel_declaration sub)
type recarg =
| Norec
| Mrec of inductive
| Imbr of inductive
Norec
let subst_recarg sub r = match r with
| Norec -> r
| (Mrec(kn,i)|Imbr (kn,i)) -> let kn' = subst_ind sub kn in
if kn==kn' then r else Imbr (kn',i)
type wf_paths = recarg Rtree.t
let val_wfp = val_rec_sum "wf_paths" 0
(fun val_wfp ->
|])
let mk_norec = Rtree.mk_node Norec [||]
let mk_paths r recargs =
Rtree.mk_node r
(Array.map (fun l -> Rtree.mk_node Norec (Array.of_list l)) recargs)
let dest_recarg p = fst (Rtree.dest_node p)
let dest_subterms p =
let (_,cstrs) = Rtree.dest_node p in
Array.map (fun t -> Array.to_list (snd (Rtree.dest_node t))) cstrs
let subst_wf_paths sub p = Rtree.smartmap (subst_recarg sub) p
Inductive I1 ( params ) : U1 : = c11 : T11 | ... | c1p1 : T1p1
...
with In ( params ) : Un : = cn1 : Tn1 | ... | : Tnpn
Inductive I1 (params) : U1 := c11 : T11 | ... | c1p1 : T1p1
...
with In (params) : Un := cn1 : Tn1 | ... | cnpn : Tnpn
*)
type monomorphic_inductive_arity = {
mind_user_arity : constr;
mind_sort : sorts;
}
let val_mono_ind_arity =
val_tuple ~name:"monomorphic_inductive_arity"[|val_constr;val_sort|]
type inductive_arity =
| Monomorphic of monomorphic_inductive_arity
| Polymorphic of polymorphic_arity
let val_ind_arity = val_sum "inductive_arity" 0
[|[|val_mono_ind_arity|];[|val_pol_arity|]|]
type one_inductive_body = {
mind_typename : identifier;
mind_arity_ctxt : rel_context;
mind_arity : inductive_arity;
mind_consnames : identifier array;
Types of the constructors with parameters : [ forall params , Tij ] ,
where the Ik are replaced by de Bruijn index in the context
I1 : forall params , U1 .. In : forall params , Un
where the Ik are replaced by de Bruijn index in the context
I1:forall params, U1 .. In:forall params, Un *)
mind_user_lc : constr array;
mind_nrealargs : int;
mind_nrealargs_ctxt : int;
mind_kelim : sorts_family list;
mind_nf_lc : constr array;
mind_consnrealdecls : int array;
mind_recargs : wf_paths;
mind_nb_constant : int;
mind_nb_args : int;
mind_reloc_tbl : reloc_table;
}
let val_one_ind = val_tuple ~name:"one_inductive_body"
[|val_id;val_rctxt;val_ind_arity;val_array val_id;val_array val_constr;
val_int;val_int;val_list val_sortfam;val_array val_constr;val_array val_int;
val_wfp;val_int;val_int;no_val|]
type mutual_inductive_body = {
mind_packets : one_inductive_body array;
mind_record : bool;
mind_finite : bool;
mind_ntypes : int;
mind_hyps : section_context;
mind_nparams : int;
mind_nparams_rec : int;
mind_params_ctxt : rel_context;
Universes constraints enforced by the inductive declaration
mind_constraints : Univ.constraints;
}
let val_ind_pack = val_tuple ~name:"mutual_inductive_body"
[|val_array val_one_ind;val_bool;val_bool;val_int;val_nctxt;
val_int; val_int; val_rctxt;val_cstrs|]
let subst_arity sub = function
| NonPolymorphicType s -> NonPolymorphicType (subst_mps sub s)
| PolymorphicArity (ctx,s) -> PolymorphicArity (subst_rel_context sub ctx,s)
TODO : should be changed to non - coping after Term.subst_mps
let subst_const_body sub cb = {
const_hyps = (assert (cb.const_hyps=[]); []);
const_body = subst_constant_def sub cb.const_body;
const_type = subst_arity sub cb.const_type;
sub
const_constraints = cb.const_constraints}
let subst_arity sub = function
| Monomorphic s ->
Monomorphic {
mind_user_arity = subst_mps sub s.mind_user_arity;
mind_sort = s.mind_sort;
}
| Polymorphic s as x -> x
let subst_mind_packet sub mbp =
{ mind_consnames = mbp.mind_consnames;
mind_consnrealdecls = mbp.mind_consnrealdecls;
mind_typename = mbp.mind_typename;
mind_nf_lc = array_smartmap (subst_mps sub) mbp.mind_nf_lc;
mind_arity_ctxt = subst_rel_context sub mbp.mind_arity_ctxt;
mind_arity = subst_arity sub mbp.mind_arity;
mind_user_lc = array_smartmap (subst_mps sub) mbp.mind_user_lc;
mind_nrealargs = mbp.mind_nrealargs;
mind_nrealargs_ctxt = mbp.mind_nrealargs_ctxt;
mind_kelim = mbp.mind_kelim;
mind_nb_constant = mbp.mind_nb_constant;
mind_nb_args = mbp.mind_nb_args;
mind_reloc_tbl = mbp.mind_reloc_tbl }
let subst_mind sub mib =
{ mind_record = mib.mind_record ;
mind_finite = mib.mind_finite ;
mind_ntypes = mib.mind_ntypes ;
mind_hyps = (assert (mib.mind_hyps=[]); []) ;
mind_nparams = mib.mind_nparams;
mind_nparams_rec = mib.mind_nparams_rec;
mind_params_ctxt =
map_rel_context (subst_mps sub) mib.mind_params_ctxt;
mind_packets = array_smartmap (subst_mind_packet sub) mib.mind_packets ;
mind_constraints = mib.mind_constraints }
type structure_field_body =
| SFBconst of constant_body
| SFBmind of mutual_inductive_body
| SFBmodule of module_body
| SFBmodtype of module_type_body
and structure_body = (label * structure_field_body) list
and struct_expr_body =
| SEBident of module_path
| SEBfunctor of mod_bound_id * module_type_body * struct_expr_body
| SEBapply of struct_expr_body * struct_expr_body * Univ.constraints
| SEBstruct of structure_body
| SEBwith of struct_expr_body * with_declaration_body
and with_declaration_body =
With_module_body of identifier list * module_path
| With_definition_body of identifier list * constant_body
and module_body =
{ mod_mp : module_path;
mod_expr : struct_expr_body option;
mod_type : struct_expr_body;
mod_type_alg : struct_expr_body option;
mod_constraints : Univ.constraints;
mod_delta : delta_resolver;
mod_retroknowledge : action list}
and module_type_body =
{ typ_mp : module_path;
typ_expr : struct_expr_body;
typ_expr_alg : struct_expr_body option ;
typ_constraints : Univ.constraints;
typ_delta :delta_resolver}
let rec val_sfb o = val_sum "struct_field_body" 0
SFBconst
SFBmind
SFBmodule
SFBmodtype
|] o
and val_sb o = val_list (val_tuple ~name:"label*sfb"[|val_id;val_sfb|]) o
and val_seb o = val_sum "struct_expr_body" 0
SEBapply
SEBstruct
|] o
and val_with o = val_sum "with_declaration_body" 0
[|[|val_list val_id;val_mp|];
[|val_list val_id;val_cb|]|] o
and val_module o = val_tuple ~name:"module_body"
[|val_mp;val_opt val_seb;val_seb;
val_opt val_seb;val_cstrs;val_res;no_val|] o
and val_modtype o = val_tuple ~name:"module_type_body"
[|val_mp;val_seb;val_opt val_seb;val_cstrs;val_res|] o
let rec subst_with_body sub = function
| With_module_body(id,mp) ->
With_module_body(id,subst_mp sub mp)
| With_definition_body(id,cb) ->
With_definition_body( id,subst_const_body sub cb)
and subst_modtype sub mtb=
let typ_expr' = subst_struct_expr sub mtb.typ_expr in
let typ_alg' =
Option.smartmap
(subst_struct_expr sub) mtb.typ_expr_alg in
let mp = subst_mp sub mtb.typ_mp
in
if typ_expr'==mtb.typ_expr &&
typ_alg'==mtb.typ_expr_alg && mp==mtb.typ_mp then
mtb
else
{mtb with
typ_mp = mp;
typ_expr = typ_expr';
typ_expr_alg = typ_alg'}
and subst_structure sub sign =
let subst_body = function
SFBconst cb ->
SFBconst (subst_const_body sub cb)
| SFBmind mib ->
SFBmind (subst_mind sub mib)
| SFBmodule mb ->
SFBmodule (subst_module sub mb)
| SFBmodtype mtb ->
SFBmodtype (subst_modtype sub mtb)
in
List.map (fun (l,b) -> (l,subst_body b)) sign
and subst_module sub mb =
let mtb' = subst_struct_expr sub mb.mod_type in
let typ_alg' = Option.smartmap
(subst_struct_expr sub ) mb.mod_type_alg in
let me' = Option.smartmap
(subst_struct_expr sub) mb.mod_expr in
let mp = subst_mp sub mb.mod_mp in
if mtb'==mb.mod_type && mb.mod_expr == me'
&& mp == mb.mod_mp
then mb else
{ mb with
mod_mp = mp;
mod_expr = me';
mod_type_alg = typ_alg';
mod_type=mtb'}
and subst_struct_expr sub = function
| SEBident mp -> SEBident (subst_mp sub mp)
| SEBfunctor (mbid, mtb, meb') ->
SEBfunctor(mbid,subst_modtype sub mtb
,subst_struct_expr sub meb')
| SEBstruct (str)->
SEBstruct( subst_structure sub str)
| SEBapply (meb1,meb2,cst)->
SEBapply(subst_struct_expr sub meb1,
subst_struct_expr sub meb2,
cst)
| SEBwith (meb,wdb)->
SEBwith(subst_struct_expr sub meb,
subst_with_body sub wdb)
|
ee661e282a64c797ae8348355c42030b0207571dbd0cb91ac12efcb28b118070 | marcoheisig/Typo | data-and-control-flow.lisp | (in-package #:typo.vm)
(define-fnrecord apply (function arg &rest more-args)
(:specializer
(assert-wrapper-type function function-designator)
(let ((tail (if (null more-args)
arg
(car (last more-args)))))
(ntype-subtypecase (wrapper-ntype tail)
((not list) (abort-specialization))
(null (apply (function-specializer 'funcall) function arg (butlast more-args)))
;; We give up here, because we cannot determine the number of values
;; returned by APPLY.
(t (wrap-default* '() '() (type-specifier-ntype 't)))))))
(define-fnrecord fdefinition (name)
(:specializer
(assert-wrapper-type name function-name)
(wrap-default (type-specifier-ntype 't))))
(define-fnrecord fboundp (name)
(:specializer
(assert-wrapper-type name function-name)
(wrap-default (type-specifier-ntype 't))))
(define-fnrecord fmakunbound (name)
(:specializer
(assert-wrapper-type name function-name)
(wrap-default (type-specifier-ntype 'function-name))))
(define-fnrecord funcall (function &rest arguments)
(:specializer
(let ((function-ntype (wrapper-ntype function)))
(if (eql-ntype-p function-ntype)
(apply (function-specializer (eql-ntype-object function-ntype)) arguments)
(progn
(assert-wrapper-type function function)
(wrap-default* '() '() (type-specifier-ntype 't)))))))
(define-fnrecord function-lambda-expression (function)
(:specializer
(assert-wrapper-type function function)
(wrap-default (type-specifier-ntype 'list))))
(define-fnrecord not (x)
(:properties :foldable :movable)
(:specializer
(let ((ntype (wrapper-ntype x)))
(if (eql-ntype-p ntype)
(wrap-constant (not (eql-ntype-object x)))
(ntype-subtypecase ntype
(null (wrap t))
((not null) (wrap nil))
(t (wrap-default (type-specifier-ntype 'boolean))))))))
(define-fnrecord eq (a b)
(:properties :foldable :movable)
(:specializer
(wrap-default (type-specifier-ntype 'generalized-boolean))))
(define-fnrecord eql (a b)
(:properties :foldable :movable)
(:specializer
(wrap-default (type-specifier-ntype 'generalized-boolean))))
(define-fnrecord equal (a b)
(:properties :foldable)
(:specializer
(wrap-default (type-specifier-ntype 'generalized-boolean))))
(define-fnrecord equalp (a b)
(:properties :foldable)
(:specializer
(wrap-default (type-specifier-ntype 'generalized-boolean))))
(define-fnrecord identity (object)
(:properties :foldable :movable)
(:specializer
(wrap object)))
(define-fnrecord complement (function)
(:properties :foldable :movable)
(:specializer
(assert-wrapper-type function function)
(wrap-default (type-specifier-ntype 'function))))
(define-fnrecord constantly (value)
(:properties :movable)
(:specializer
(wrap-default (type-specifier-ntype 'function))))
(define-fnrecord values (&rest objects)
(:properties :foldable :movable)
(:specializer
(wrap-function (ensure-fnrecord 'values) objects (mapcar #'wrapper-ntype objects) '() nil)))
(define-fnrecord values-list (list)
(:properties :foldable :movable)
(:specializer
(assert-wrapper-type list list)
(wrap-default* '() '() (type-specifier-ntype 't))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Control Flow Directives
(define-fnrecord choose (boolean a b)
(:properties :foldable :movable)
(:specializer
(ntype-subtypecase (wrapper-ntype boolean)
(null (wrap b))
((not null) (wrap a))
(t (wrap-default (ntype-union (wrapper-ntype a) (wrapper-ntype b)))))))
(define-fnrecord and-fn (&rest args)
(:properties :foldable :movable)
(:specializer
(let ((sure t))
(loop for arg in args do
(ntype-subtypecase (wrapper-ntype arg)
(null (return-from and-fn (wrap nil)))
((not null))
(t (setf sure nil))))
(if sure
(wrap t)
(wrap-default (type-specifier-ntype 'generalized-boolean))))))
(define-fnrecord or-fn (&rest args)
(:properties :foldable :movable)
(:specializer
(let ((sure t))
(loop for arg in args do
(ntype-subtypecase (wrapper-ntype arg)
((not null)
(if sure
(return-from or-fn arg)
(wrap-default (true-ntype))))
(null)
(t (setf sure nil))))
(if sure
(wrap nil)
(wrap-default (type-specifier-ntype 'generalized-boolean))))))
(define-fnrecord prog2-fn (a b)
(:properties :foldable :movable)
(:specializer
(wrap-function
(ensure-fnrecord 'prog2-fn)
(list a b) (list (wrapper-ntype b)) '() nil)))
| null | https://raw.githubusercontent.com/marcoheisig/Typo/303e21c38b1773f7d6f87eeb7f03617c286c4a44/code/vm/data-and-control-flow.lisp | lisp | We give up here, because we cannot determine the number of values
returned by APPLY.
| (in-package #:typo.vm)
(define-fnrecord apply (function arg &rest more-args)
(:specializer
(assert-wrapper-type function function-designator)
(let ((tail (if (null more-args)
arg
(car (last more-args)))))
(ntype-subtypecase (wrapper-ntype tail)
((not list) (abort-specialization))
(null (apply (function-specializer 'funcall) function arg (butlast more-args)))
(t (wrap-default* '() '() (type-specifier-ntype 't)))))))
(define-fnrecord fdefinition (name)
(:specializer
(assert-wrapper-type name function-name)
(wrap-default (type-specifier-ntype 't))))
(define-fnrecord fboundp (name)
(:specializer
(assert-wrapper-type name function-name)
(wrap-default (type-specifier-ntype 't))))
(define-fnrecord fmakunbound (name)
(:specializer
(assert-wrapper-type name function-name)
(wrap-default (type-specifier-ntype 'function-name))))
(define-fnrecord funcall (function &rest arguments)
(:specializer
(let ((function-ntype (wrapper-ntype function)))
(if (eql-ntype-p function-ntype)
(apply (function-specializer (eql-ntype-object function-ntype)) arguments)
(progn
(assert-wrapper-type function function)
(wrap-default* '() '() (type-specifier-ntype 't)))))))
(define-fnrecord function-lambda-expression (function)
(:specializer
(assert-wrapper-type function function)
(wrap-default (type-specifier-ntype 'list))))
(define-fnrecord not (x)
(:properties :foldable :movable)
(:specializer
(let ((ntype (wrapper-ntype x)))
(if (eql-ntype-p ntype)
(wrap-constant (not (eql-ntype-object x)))
(ntype-subtypecase ntype
(null (wrap t))
((not null) (wrap nil))
(t (wrap-default (type-specifier-ntype 'boolean))))))))
(define-fnrecord eq (a b)
(:properties :foldable :movable)
(:specializer
(wrap-default (type-specifier-ntype 'generalized-boolean))))
(define-fnrecord eql (a b)
(:properties :foldable :movable)
(:specializer
(wrap-default (type-specifier-ntype 'generalized-boolean))))
(define-fnrecord equal (a b)
(:properties :foldable)
(:specializer
(wrap-default (type-specifier-ntype 'generalized-boolean))))
(define-fnrecord equalp (a b)
(:properties :foldable)
(:specializer
(wrap-default (type-specifier-ntype 'generalized-boolean))))
(define-fnrecord identity (object)
(:properties :foldable :movable)
(:specializer
(wrap object)))
(define-fnrecord complement (function)
(:properties :foldable :movable)
(:specializer
(assert-wrapper-type function function)
(wrap-default (type-specifier-ntype 'function))))
(define-fnrecord constantly (value)
(:properties :movable)
(:specializer
(wrap-default (type-specifier-ntype 'function))))
(define-fnrecord values (&rest objects)
(:properties :foldable :movable)
(:specializer
(wrap-function (ensure-fnrecord 'values) objects (mapcar #'wrapper-ntype objects) '() nil)))
(define-fnrecord values-list (list)
(:properties :foldable :movable)
(:specializer
(assert-wrapper-type list list)
(wrap-default* '() '() (type-specifier-ntype 't))))
Control Flow Directives
(define-fnrecord choose (boolean a b)
(:properties :foldable :movable)
(:specializer
(ntype-subtypecase (wrapper-ntype boolean)
(null (wrap b))
((not null) (wrap a))
(t (wrap-default (ntype-union (wrapper-ntype a) (wrapper-ntype b)))))))
(define-fnrecord and-fn (&rest args)
(:properties :foldable :movable)
(:specializer
(let ((sure t))
(loop for arg in args do
(ntype-subtypecase (wrapper-ntype arg)
(null (return-from and-fn (wrap nil)))
((not null))
(t (setf sure nil))))
(if sure
(wrap t)
(wrap-default (type-specifier-ntype 'generalized-boolean))))))
(define-fnrecord or-fn (&rest args)
(:properties :foldable :movable)
(:specializer
(let ((sure t))
(loop for arg in args do
(ntype-subtypecase (wrapper-ntype arg)
((not null)
(if sure
(return-from or-fn arg)
(wrap-default (true-ntype))))
(null)
(t (setf sure nil))))
(if sure
(wrap nil)
(wrap-default (type-specifier-ntype 'generalized-boolean))))))
(define-fnrecord prog2-fn (a b)
(:properties :foldable :movable)
(:specializer
(wrap-function
(ensure-fnrecord 'prog2-fn)
(list a b) (list (wrapper-ntype b)) '() nil)))
|
95f75639a7d2ad650d441acbbf5954f22d94debd0e2efc620663b5dd931cddd3 | larcenists/larceny | 16inv4.scm | (bits 16)
(text
(alt (if (inv (alt (nop)
z!
(inv (nop))
ge!))
(inv (nop))
(nop))
(nop)))
00000000 90 nop
00000001 EB08 short 0xb
00000003 7406 jz 0xb
00000005 90 nop
00000006 7D03 jnl 0xb
00000008 90 nop
00000009 EB03 short 0xe
0000000B 90 nop
0000000C EB01 short 0xf
0000000E 90 nop
| null | https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/src/Lib/Sassy/tests/prims16/16inv4.scm | scheme | (bits 16)
(text
(alt (if (inv (alt (nop)
z!
(inv (nop))
ge!))
(inv (nop))
(nop))
(nop)))
00000000 90 nop
00000001 EB08 short 0xb
00000003 7406 jz 0xb
00000005 90 nop
00000006 7D03 jnl 0xb
00000008 90 nop
00000009 EB03 short 0xe
0000000B 90 nop
0000000C EB01 short 0xf
0000000E 90 nop
|
|
727d73359e2d25e5a5deafb5ca95712b10f799ea628c8f0a3f9bda54782101bb | codecrafters-io/build-your-own-grep | Parser.hs | module Parser (parse, astToMatcher, AST(..)) where
import qualified Text.Megaparsec as M
import Text.Megaparsec.Char (char, digitChar)
import Data.Void (Void)
import Data.Maybe (fromMaybe, isNothing)
import RegEx (M, posLit, negLit, emptyStrM, digitM, digitInverseM, alphaNumM, alphaNumInverseM, anyCharM, orM, andM, concatM, kleeneStarM, kleenePlusM)
type MParser = M.Parsec Void String
data AST a = PosLit a
| NegLit a
| DigitM
| DigitInverseM
| AlphaNumM
| AlphaNumInverseM
| AnyCharM
| OrM [AST a]
| AndM [AST a]
| ConcatM [AST a]
| KleeneStarM (AST a)
| KleenePlusM (AST a)
| EmptyStrM
deriving (Eq, Show)
astToMatcher :: AST Char -> M Char
astToMatcher (PosLit a) = posLit a
astToMatcher (NegLit a) = negLit a
astToMatcher DigitM = digitM
astToMatcher DigitInverseM = digitInverseM
astToMatcher AlphaNumM = alphaNumM
astToMatcher AlphaNumInverseM = alphaNumInverseM
astToMatcher AnyCharM = anyCharM
astToMatcher (OrM ms) = orM $ fmap astToMatcher ms
astToMatcher (AndM ms) = andM $ fmap astToMatcher ms
astToMatcher (ConcatM ms) = concatM $ fmap astToMatcher ms
astToMatcher (KleeneStarM m) = kleeneStarM $ astToMatcher m
astToMatcher (KleenePlusM m) = kleenePlusM $ astToMatcher m
astToMatcher EmptyStrM = emptyStrM
notChar :: Char -> MParser Char
notChar c = M.satisfy (/=c)
anyNotUsed :: String -> MParser Char
anyNotUsed s = M.satisfy $ not . (`elem` s)
-- | Inverts an AST Char
neg :: AST Char -> AST Char
neg DigitM = DigitInverseM
neg AlphaNumM = AlphaNumInverseM
neg (PosLit c) = NegLit c
neg _ = error "Unsupported input string"
-- The regex parser starts here
--
-- I had to adjust a few rules to support better parsing
pRegEx :: MParser (AST Char)
pRegEx = do
s <- pStartOfString
expression <- pExpression
return $ ConcatM [s, expression, KleeneStarM AnyCharM]
pStartOfString :: MParser (AST Char)
pStartOfString = do
s <- M.optional $ char '^'
return $ if isNothing s then KleeneStarM AnyCharM else EmptyStrM
pExpression :: MParser (AST Char)
pExpression = pSubExpression
pSubExpression :: MParser (AST Char)
pSubExpression = do
subExp <- M.some $ M.try pMatch
return $ ConcatM subExp
pMatch :: MParser (AST Char)
pMatch = pMatchItem
pMatchItem :: MParser (AST Char)
pMatchItem = M.try pMatchCharacterClass M.<|> M.try pMatchCharacter
pMatchCharacterClass :: MParser (AST Char)
pMatchCharacterClass = M.try pCharacterGroup M.<|> M.try pCharacterClass
pMatchCharacter :: MParser (AST Char)
pMatchCharacter = do
c <- anyNotUsed "|()$"
return $ PosLit c
pCharacterGroup :: MParser (AST Char)
pCharacterGroup = M.try pPositiveCharacterGroup M.<|> M.try pNegativeCharacterGroup
pPositiveCharacterGroup :: MParser (AST Char)
pPositiveCharacterGroup = do
_ <- char '['
c <- anyNotUsed "^]"
cs <- M.many pCharacterGroupItem
let cs' = PosLit c : cs
_ <- char ']'
return $ OrM cs'
pNegativeCharacterGroup :: MParser (AST Char)
pNegativeCharacterGroup = do
_ <- char '['
_ <- char '^'
ms <- M.some pCharacterGroupItem
_ <- char ']'
return $ AndM $ fmap neg ms
pCharacterGroupItem :: MParser (AST Char)
pCharacterGroupItem = M.try pCharacterClass M.<|> M.try pChar
pCharacterClass :: MParser (AST Char)
pCharacterClass = M.try pCharacterClassAnyWord M.<|> M.try pCharacterClassAnyDecimal
pCharacterClassAnyWord :: MParser (AST a)
pCharacterClassAnyWord = do
_ <- char '\\'
_ <- char 'w'
return AlphaNumM
pCharacterClassAnyDecimal :: MParser (AST Char)
pCharacterClassAnyDecimal = do
_ <- char '\\'
_ <- char 'd'
return DigitM
pChar :: MParser (AST Char)
pChar = do
c <- notChar ']'
return $ PosLit c
parse :: String -> Maybe (AST Char)
parse = M.parseMaybe pRegEx
| null | https://raw.githubusercontent.com/codecrafters-io/build-your-own-grep/085a70404357c4abf11ff7c039cdf13181349e3c/solutions/haskell/07-start_of_string_anchor/code/src/Parser.hs | haskell | | Inverts an AST Char
The regex parser starts here
I had to adjust a few rules to support better parsing | module Parser (parse, astToMatcher, AST(..)) where
import qualified Text.Megaparsec as M
import Text.Megaparsec.Char (char, digitChar)
import Data.Void (Void)
import Data.Maybe (fromMaybe, isNothing)
import RegEx (M, posLit, negLit, emptyStrM, digitM, digitInverseM, alphaNumM, alphaNumInverseM, anyCharM, orM, andM, concatM, kleeneStarM, kleenePlusM)
type MParser = M.Parsec Void String
data AST a = PosLit a
| NegLit a
| DigitM
| DigitInverseM
| AlphaNumM
| AlphaNumInverseM
| AnyCharM
| OrM [AST a]
| AndM [AST a]
| ConcatM [AST a]
| KleeneStarM (AST a)
| KleenePlusM (AST a)
| EmptyStrM
deriving (Eq, Show)
astToMatcher :: AST Char -> M Char
astToMatcher (PosLit a) = posLit a
astToMatcher (NegLit a) = negLit a
astToMatcher DigitM = digitM
astToMatcher DigitInverseM = digitInverseM
astToMatcher AlphaNumM = alphaNumM
astToMatcher AlphaNumInverseM = alphaNumInverseM
astToMatcher AnyCharM = anyCharM
astToMatcher (OrM ms) = orM $ fmap astToMatcher ms
astToMatcher (AndM ms) = andM $ fmap astToMatcher ms
astToMatcher (ConcatM ms) = concatM $ fmap astToMatcher ms
astToMatcher (KleeneStarM m) = kleeneStarM $ astToMatcher m
astToMatcher (KleenePlusM m) = kleenePlusM $ astToMatcher m
astToMatcher EmptyStrM = emptyStrM
notChar :: Char -> MParser Char
notChar c = M.satisfy (/=c)
anyNotUsed :: String -> MParser Char
anyNotUsed s = M.satisfy $ not . (`elem` s)
neg :: AST Char -> AST Char
neg DigitM = DigitInverseM
neg AlphaNumM = AlphaNumInverseM
neg (PosLit c) = NegLit c
neg _ = error "Unsupported input string"
pRegEx :: MParser (AST Char)
pRegEx = do
s <- pStartOfString
expression <- pExpression
return $ ConcatM [s, expression, KleeneStarM AnyCharM]
pStartOfString :: MParser (AST Char)
pStartOfString = do
s <- M.optional $ char '^'
return $ if isNothing s then KleeneStarM AnyCharM else EmptyStrM
pExpression :: MParser (AST Char)
pExpression = pSubExpression
pSubExpression :: MParser (AST Char)
pSubExpression = do
subExp <- M.some $ M.try pMatch
return $ ConcatM subExp
pMatch :: MParser (AST Char)
pMatch = pMatchItem
pMatchItem :: MParser (AST Char)
pMatchItem = M.try pMatchCharacterClass M.<|> M.try pMatchCharacter
pMatchCharacterClass :: MParser (AST Char)
pMatchCharacterClass = M.try pCharacterGroup M.<|> M.try pCharacterClass
pMatchCharacter :: MParser (AST Char)
pMatchCharacter = do
c <- anyNotUsed "|()$"
return $ PosLit c
pCharacterGroup :: MParser (AST Char)
pCharacterGroup = M.try pPositiveCharacterGroup M.<|> M.try pNegativeCharacterGroup
pPositiveCharacterGroup :: MParser (AST Char)
pPositiveCharacterGroup = do
_ <- char '['
c <- anyNotUsed "^]"
cs <- M.many pCharacterGroupItem
let cs' = PosLit c : cs
_ <- char ']'
return $ OrM cs'
pNegativeCharacterGroup :: MParser (AST Char)
pNegativeCharacterGroup = do
_ <- char '['
_ <- char '^'
ms <- M.some pCharacterGroupItem
_ <- char ']'
return $ AndM $ fmap neg ms
pCharacterGroupItem :: MParser (AST Char)
pCharacterGroupItem = M.try pCharacterClass M.<|> M.try pChar
pCharacterClass :: MParser (AST Char)
pCharacterClass = M.try pCharacterClassAnyWord M.<|> M.try pCharacterClassAnyDecimal
pCharacterClassAnyWord :: MParser (AST a)
pCharacterClassAnyWord = do
_ <- char '\\'
_ <- char 'w'
return AlphaNumM
pCharacterClassAnyDecimal :: MParser (AST Char)
pCharacterClassAnyDecimal = do
_ <- char '\\'
_ <- char 'd'
return DigitM
pChar :: MParser (AST Char)
pChar = do
c <- notChar ']'
return $ PosLit c
parse :: String -> Maybe (AST Char)
parse = M.parseMaybe pRegEx
|
19041572ae447139562df4622850127636f211be2878b420b4331b2b6becc68a | ajhc/ajhc | T2497.hs | # OPTIONS_GHC -fwarn - unused - binds #
module ShouldCompile() where
Trac # 2497 ; test should compile without language
-- pragmas to swith on the forall
{-# RULES "id" forall (x :: a). id x = x #-}
Trac # 2213 ; eq should not be reported as unused
eq,beq :: Eq a => a -> a -> Bool
eq = (==) -- Used
beq = (==) -- Unused
# RULES
" rule 1 " forall x y. x = = y = y ` eq ` x
#
"rule 1" forall x y. x == y = y `eq` x
#-}
| null | https://raw.githubusercontent.com/ajhc/ajhc/8ef784a6a3b5998cfcd95d0142d627da9576f264/regress/tests/1_typecheck/2_pass/ghc/T2497.hs | haskell | pragmas to swith on the forall
# RULES "id" forall (x :: a). id x = x #
Used
Unused | # OPTIONS_GHC -fwarn - unused - binds #
module ShouldCompile() where
Trac # 2497 ; test should compile without language
Trac # 2213 ; eq should not be reported as unused
eq,beq :: Eq a => a -> a -> Bool
# RULES
" rule 1 " forall x y. x = = y = y ` eq ` x
#
"rule 1" forall x y. x == y = y `eq` x
#-}
|
0766acfdeacc509bf589817b84d88151f18e3d7c4a609f8f0a285b07d7f0dd1e | sanette/oplot | surf3d.ml | Three 3D views .
open Oplot.Plt
let a = axis 0. 0.
let fx u v = 0.3 +. ((1. +. (0.5 *. cos u)) *. cos v)
let fy u v = 0.2 +. ((1. +. (0.5 *. cos u)) *. sin v)
let fz u _ = 0.5 *. sin u
let s = surf3d_plot ~wire:true ~width:10 ~height:50 fx fy fz 0. 0. 3. 6.29
let set_wire po wire =
match po with
| Surf3d ((fx, fy, fz, v3, _), _) ->
Surf3d ((fx, fy, fz, v3, wire), Internal.gllist_empty ())
| Grid ((fm, v3, _), _) -> Grid ((fm, v3, wire), Internal.gllist_empty ())
| _ -> raise Not_found
let t1 = text "Press CTRL-L to toggle lighting" 0.3 0.3
let t2 = text "Use the mouse to rotate the scene" 0.3 0.1;;
display [ set_wire s false; Color red; t1; t2 ];;
display [ Color cyan; set_wire s true; Color red; a ] ~dev:gl
let fx u v =
((3. *. (1. +. sin v)) +. (2. *. (1. -. (cos v /. 2.)) *. cos u)) *. cos v
let fy u v = (4. +. (2. *. (1. -. (cos v /. 2.)) *. cos u)) *. sin v
let fz u v = -2. *. (1. -. (cos v /. 2.)) *. sin u
let s = surf3d_plot ~width:30 ~height:50 fx fy fz 0. 0. 6.283 6.283;;
display [ Clear black; Color cyan; s; Color red ];;
quit ()
| null | https://raw.githubusercontent.com/sanette/oplot/facce7233787bc81f14acc261e210c0ae243a123/bin/surf3d.ml | ocaml | Three 3D views .
open Oplot.Plt
let a = axis 0. 0.
let fx u v = 0.3 +. ((1. +. (0.5 *. cos u)) *. cos v)
let fy u v = 0.2 +. ((1. +. (0.5 *. cos u)) *. sin v)
let fz u _ = 0.5 *. sin u
let s = surf3d_plot ~wire:true ~width:10 ~height:50 fx fy fz 0. 0. 3. 6.29
let set_wire po wire =
match po with
| Surf3d ((fx, fy, fz, v3, _), _) ->
Surf3d ((fx, fy, fz, v3, wire), Internal.gllist_empty ())
| Grid ((fm, v3, _), _) -> Grid ((fm, v3, wire), Internal.gllist_empty ())
| _ -> raise Not_found
let t1 = text "Press CTRL-L to toggle lighting" 0.3 0.3
let t2 = text "Use the mouse to rotate the scene" 0.3 0.1;;
display [ set_wire s false; Color red; t1; t2 ];;
display [ Color cyan; set_wire s true; Color red; a ] ~dev:gl
let fx u v =
((3. *. (1. +. sin v)) +. (2. *. (1. -. (cos v /. 2.)) *. cos u)) *. cos v
let fy u v = (4. +. (2. *. (1. -. (cos v /. 2.)) *. cos u)) *. sin v
let fz u v = -2. *. (1. -. (cos v /. 2.)) *. sin u
let s = surf3d_plot ~width:30 ~height:50 fx fy fz 0. 0. 6.283 6.283;;
display [ Clear black; Color cyan; s; Color red ];;
quit ()
|
|
ad5cef1f4de445fb651b799727e2575d3b2b64d3aa64f4aa2eb1ec0579c874aa | riverford/durable-ref | cheshire.clj | (ns riverford.durable-ref.format.json.cheshire
(:require [cheshire.core :as cheshire]
[riverford.durable-ref.core :as dref]
[clojure.java.io :as io])
(:import (java.io ByteArrayOutputStream)
(java.util.zip GZIPOutputStream GZIPInputStream)))
(defmethod dref/serialize "json"
[obj _ opts]
(let [bao (ByteArrayOutputStream.)]
(with-open [w (io/writer bao)]
(cheshire/generate-stream obj w (-> opts :format :json :cheshire :write-opts)))
(.toByteArray bao)))
(defmethod dref/deserialize "json"
[in _ opts]
(let [read-opts (-> opts :format :json :cheshire :read-opts)]
(with-open [rdr (io/reader in)]
(cheshire/parse-stream
rdr
(:key-fn read-opts identity)
(:array-coerce-fn read-opts (constantly []))))))
(defmethod dref/serialize "json.zip"
[obj _ opts]
(let [bao (ByteArrayOutputStream.)]
(with-open [gzipo (GZIPOutputStream. bao)
w (io/writer gzipo)]
(cheshire/generate-stream obj w (-> opts :format :json :cheshire :write-opts)))
(.toByteArray bao)))
(defmethod dref/deserialize "json.zip"
[in _ opts]
(let [read-opts (-> opts :format :json :cheshire :read-opts)]
(with-open [in (io/input-stream in)
gzipi (GZIPInputStream. in)
rdr (io/reader gzipi)]
(cheshire/parse-stream
rdr
(:key-fn read-opts identity)
(:array-coerce-fn read-opts (constantly [])))))) | null | https://raw.githubusercontent.com/riverford/durable-ref/f18402c07549079fd3a1c8d2595f893a055851de/src/riverford/durable_ref/format/json/cheshire.clj | clojure | (ns riverford.durable-ref.format.json.cheshire
(:require [cheshire.core :as cheshire]
[riverford.durable-ref.core :as dref]
[clojure.java.io :as io])
(:import (java.io ByteArrayOutputStream)
(java.util.zip GZIPOutputStream GZIPInputStream)))
(defmethod dref/serialize "json"
[obj _ opts]
(let [bao (ByteArrayOutputStream.)]
(with-open [w (io/writer bao)]
(cheshire/generate-stream obj w (-> opts :format :json :cheshire :write-opts)))
(.toByteArray bao)))
(defmethod dref/deserialize "json"
[in _ opts]
(let [read-opts (-> opts :format :json :cheshire :read-opts)]
(with-open [rdr (io/reader in)]
(cheshire/parse-stream
rdr
(:key-fn read-opts identity)
(:array-coerce-fn read-opts (constantly []))))))
(defmethod dref/serialize "json.zip"
[obj _ opts]
(let [bao (ByteArrayOutputStream.)]
(with-open [gzipo (GZIPOutputStream. bao)
w (io/writer gzipo)]
(cheshire/generate-stream obj w (-> opts :format :json :cheshire :write-opts)))
(.toByteArray bao)))
(defmethod dref/deserialize "json.zip"
[in _ opts]
(let [read-opts (-> opts :format :json :cheshire :read-opts)]
(with-open [in (io/input-stream in)
gzipi (GZIPInputStream. in)
rdr (io/reader gzipi)]
(cheshire/parse-stream
rdr
(:key-fn read-opts identity)
(:array-coerce-fn read-opts (constantly [])))))) |
|
de5f8871746dfdbb3764012e1b248aab79d986b782cb8452f3d7db522df87cea | MinaProtocol/mina | plonk_constraint_system.ml | (* TODO: remove these openings *)
open Sponge
open Unsigned.Size_t
TODO : open Core here instead of opening it multiple times below
module Kimchi_gate_type = struct
to allow deriving sexp
type t = Kimchi_types.gate_type =
| Zero
| Generic
| Poseidon
| CompleteAdd
| VarBaseMul
| EndoMul
| EndoMulScalar
| Lookup
| CairoClaim
| CairoInstruction
| CairoFlags
| CairoTransition
| RangeCheck0
| RangeCheck1
| ForeignFieldAdd
| ForeignFieldMul
| Xor16
| Rot64
[@@deriving sexp]
end
(** A gate interface, parameterized by a field. *)
module type Gate_vector_intf = sig
open Unsigned
type field
type t
val create : unit -> t
val add : t -> field Kimchi_types.circuit_gate -> unit
val get : t -> int -> field Kimchi_types.circuit_gate
val len : t -> int
val digest : int -> t -> bytes
val to_json : int -> t -> string
end
(** A row indexing in a constraint system. *)
module Row = struct
open Core_kernel
* Either a public input row ,
or a non - public input row that starts at index 0 .
or a non-public input row that starts at index 0.
*)
type t = Public_input of int | After_public_input of int
[@@deriving hash, sexp, compare]
let to_absolute ~public_input_size = function
| Public_input i ->
i
| After_public_input i ->
the first i rows are public - input rows
i + public_input_size
end
TODO : rename module Position to Permutation / Wiring ?
(** A position represents the position of a cell in the constraint system. *)
module Position = struct
open Core_kernel
(** A position is a row and a column. *)
type 'row t = { row : 'row; col : int } [@@deriving hash, sexp, compare]
(** Generates a full row of positions that each points to itself. *)
let create_cols (row : 'row) : _ t array =
Array.init Constants.permutation_cols ~f:(fun i -> { row; col = i })
(** Given a number of columns,
append enough column wires to get an entire row.
The wire appended will simply point to themselves,
so as to not take part in the permutation argument.
*)
let append_cols (row : 'row) (cols : _ t array) : _ t array =
let padding_offset = Array.length cols in
assert (padding_offset <= Constants.permutation_cols) ;
let padding_len = Constants.permutation_cols - padding_offset in
let padding =
Array.init padding_len ~f:(fun i -> { row; col = i + padding_offset })
in
Array.append cols padding
(** Converts an array of [Constants.columns] to [Constants.permutation_cols].
This is useful to truncate arrays of cells to the ones that only matter for the permutation argument.
*)
let cols_to_perms cols = Array.slice cols 0 Constants.permutation_cols
* Converts a [ Position.t ] into the Rust - compatible type [ Kimchi_types.wire ] .
*)
let to_rust_wire { row; col } : Kimchi_types.wire = { row; col }
end
(** A gate. *)
module Gate_spec = struct
open Core_kernel
(* TODO: split kind/coeffs from row/wired_to *)
(** A gate/row/constraint consists of a type (kind), a row, the other cells its columns/cells are connected to (wired_to), and the selector polynomial associated with the gate. *)
type ('row, 'f) t =
{ kind : Kimchi_gate_type.t
; wired_to : 'row Position.t array
; coeffs : 'f array
}
[@@deriving sexp_of]
(** Applies a function [f] to the [row] of [t] and all the rows of its [wired_to]. *)
let map_rows (t : (_, _) t) ~f : (_, _) t =
(* { wire with row = f row } *)
let wired_to =
Array.map
~f:(fun (pos : _ Position.t) -> { pos with row = f pos.row })
t.wired_to
in
{ t with wired_to }
TODO : just send the array to directly
let to_rust_gate { kind; wired_to; coeffs } : _ Kimchi_types.circuit_gate =
let typ = kind in
let wired_to = Array.map ~f:Position.to_rust_wire wired_to in
let wires =
( wired_to.(0)
, wired_to.(1)
, wired_to.(2)
, wired_to.(3)
, wired_to.(4)
, wired_to.(5)
, wired_to.(6) )
in
{ typ; wires; coeffs }
end
(** The PLONK constraints. *)
module Plonk_constraint = struct
open Core_kernel
* A PLONK constraint ( or gate ) can be [ Basic ] , [ ] , [ ] , [ EC_scale ] , [ EC_endoscale ] , [ EC_endoscalar ] , [ RangeCheck0 ] , [ RangeCheck1 ] , [ Xor ]
module T = struct
type ('v, 'f) t =
| Basic of { l : 'f * 'v; r : 'f * 'v; o : 'f * 'v; m : 'f; c : 'f }
* the state is an array of states ( and states are arrays of size 3 ) .
| Poseidon of { state : 'v array array }
| EC_add_complete of
{ p1 : 'v * 'v
; p2 : 'v * 'v
; p3 : 'v * 'v
; inf : 'v
; same_x : 'v
; slope : 'v
; inf_z : 'v
; x21_inv : 'v
}
| EC_scale of { state : 'v Scale_round.t array }
| EC_endoscale of
{ state : 'v Endoscale_round.t array; xs : 'v; ys : 'v; n_acc : 'v }
| EC_endoscalar of { state : 'v Endoscale_scalar_round.t array }
| RangeCheck0 of
Value to constrain to 88 - bits
; v0p0 : 'v (* MSBs *)
vpX are 12 - bit plookup chunks
; v0p2 : 'v
; v0p3 : 'v
; v0p4 : 'v
; v0p5 : 'v
vcX are 2 - bit crumbs
; v0c1 : 'v
; v0c2 : 'v
; v0c3 : 'v
; v0c4 : 'v
; v0c5 : 'v
; v0c6 : 'v
; v0c7 : 'v (* LSBs *)
; (* Coefficients *)
compact : 'f
Limbs mode coefficient : 0 ( standard 3 - limb ) or 1 ( compact 2 - limb )
}
| RangeCheck1 of
{ (* Current row *)
Value to constrain to 88 - bits
Optional value used in compact 2 - limb mode
MSBs , 2 - bit crumb
vpX are 12 - bit plookup chunks
; v2p1 : 'v
; v2p2 : 'v
; v2p3 : 'v
vcX are 2 - bit crumbs
; v2c2 : 'v
; v2c3 : 'v
; v2c4 : 'v
; v2c5 : 'v
; v2c6 : 'v
; v2c7 : 'v
; v2c8 : 'v (* LSBs *)
; (* Next row *) v2c9 : 'v
; v2c10 : 'v
; v2c11 : 'v
; v0p0 : 'v
; v0p1 : 'v
; v1p0 : 'v
; v1p1 : 'v
; v2c12 : 'v
; v2c13 : 'v
; v2c14 : 'v
; v2c15 : 'v
; v2c16 : 'v
; v2c17 : 'v
; v2c18 : 'v
; v2c19 : 'v
}
| Xor of
{ in1 : 'v
; in2 : 'v
; out : 'v
; in1_0 : 'v
; in1_1 : 'v
; in1_2 : 'v
; in1_3 : 'v
; in2_0 : 'v
; in2_1 : 'v
; in2_2 : 'v
; in2_3 : 'v
; out_0 : 'v
; out_1 : 'v
; out_2 : 'v
; out_3 : 'v
}
| ForeignFieldAdd of
{ left_input_lo : 'v
; left_input_mi : 'v
; left_input_hi : 'v
; right_input_lo : 'v
; right_input_mi : 'v
; right_input_hi : 'v
; field_overflow : 'v
; carry : 'v
}
| ForeignFieldMul of
{ (* Current row *)
left_input0 : 'v
; left_input1 : 'v
; left_input2 : 'v
; right_input0 : 'v
; right_input1 : 'v
; right_input2 : 'v
; carry1_lo : 'v
; carry1_hi : 'v
; carry0 : 'v
; quotient0 : 'v
; quotient1 : 'v
; quotient2 : 'v
; quotient_bound_carry : 'v
; product1_hi_1 : 'v
; (* Next row *) remainder0 : 'v
; remainder1 : 'v
; remainder2 : 'v
; quotient_bound01 : 'v
; quotient_bound2 : 'v
; product1_lo : 'v
; product1_hi_0 : 'v
}
| Rot64 of
{ (* Current row *)
word : 'v
; rotated : 'v
; excess : 'v
; bound_limb0 : 'v
; bound_limb1 : 'v
; bound_limb2 : 'v
; bound_limb3 : 'v
; bound_crumb0 : 'v
; bound_crumb1 : 'v
; bound_crumb2 : 'v
; bound_crumb3 : 'v
; bound_crumb4 : 'v
; bound_crumb5 : 'v
; bound_crumb6 : 'v
; bound_crumb7 : 'v
; (* Next row *) shifted : 'v
; shifted_limb0 : 'v
; shifted_limb1 : 'v
; shifted_limb2 : 'v
; shifted_limb3 : 'v
; shifted_crumb0 : 'v
; shifted_crumb1 : 'v
; shifted_crumb2 : 'v
; shifted_crumb3 : 'v
; shifted_crumb4 : 'v
; shifted_crumb5 : 'v
; shifted_crumb6 : 'v
; shifted_crumb7 : 'v
Rotation scalar 2^rot
}
| Raw of
{ kind : Kimchi_gate_type.t; values : 'v array; coeffs : 'f array }
[@@deriving sexp]
(** map t *)
let map (type a b f) (t : (a, f) t) ~(f : a -> b) =
let fp (x, y) = (f x, f y) in
match t with
| Basic { l; r; o; m; c } ->
let p (x, y) = (x, f y) in
Basic { l = p l; r = p r; o = p o; m; c }
| Poseidon { state } ->
Poseidon { state = Array.map ~f:(fun x -> Array.map ~f x) state }
| EC_add_complete { p1; p2; p3; inf; same_x; slope; inf_z; x21_inv } ->
EC_add_complete
{ p1 = fp p1
; p2 = fp p2
; p3 = fp p3
; inf = f inf
; same_x = f same_x
; slope = f slope
; inf_z = f inf_z
; x21_inv = f x21_inv
}
| EC_scale { state } ->
EC_scale
{ state = Array.map ~f:(fun x -> Scale_round.map ~f x) state }
| EC_endoscale { state; xs; ys; n_acc } ->
EC_endoscale
{ state = Array.map ~f:(fun x -> Endoscale_round.map ~f x) state
; xs = f xs
; ys = f ys
; n_acc = f n_acc
}
| EC_endoscalar { state } ->
EC_endoscalar
{ state =
Array.map ~f:(fun x -> Endoscale_scalar_round.map ~f x) state
}
| RangeCheck0
{ v0
; v0p0
; v0p1
; v0p2
; v0p3
; v0p4
; v0p5
; v0c0
; v0c1
; v0c2
; v0c3
; v0c4
; v0c5
; v0c6
; v0c7
; compact
} ->
RangeCheck0
{ v0 = f v0
; v0p0 = f v0p0
; v0p1 = f v0p1
; v0p2 = f v0p2
; v0p3 = f v0p3
; v0p4 = f v0p4
; v0p5 = f v0p5
; v0c0 = f v0c0
; v0c1 = f v0c1
; v0c2 = f v0c2
; v0c3 = f v0c3
; v0c4 = f v0c4
; v0c5 = f v0c5
; v0c6 = f v0c6
; v0c7 = f v0c7
; compact
}
| RangeCheck1
{ (* Current row *) v2
; v12
; v2c0
; v2p0
; v2p1
; v2p2
; v2p3
; v2c1
; v2c2
; v2c3
; v2c4
; v2c5
; v2c6
; v2c7
; v2c8
; (* Next row *) v2c9
; v2c10
; v2c11
; v0p0
; v0p1
; v1p0
; v1p1
; v2c12
; v2c13
; v2c14
; v2c15
; v2c16
; v2c17
; v2c18
; v2c19
} ->
RangeCheck1
{ (* Current row *) v2 = f v2
; v12 = f v12
; v2c0 = f v2c0
; v2p0 = f v2p0
; v2p1 = f v2p1
; v2p2 = f v2p2
; v2p3 = f v2p3
; v2c1 = f v2c1
; v2c2 = f v2c2
; v2c3 = f v2c3
; v2c4 = f v2c4
; v2c5 = f v2c5
; v2c6 = f v2c6
; v2c7 = f v2c7
; v2c8 = f v2c8
; (* Next row *) v2c9 = f v2c9
; v2c10 = f v2c10
; v2c11 = f v2c11
; v0p0 = f v0p0
; v0p1 = f v0p1
; v1p0 = f v1p0
; v1p1 = f v1p1
; v2c12 = f v2c12
; v2c13 = f v2c13
; v2c14 = f v2c14
; v2c15 = f v2c15
; v2c16 = f v2c16
; v2c17 = f v2c17
; v2c18 = f v2c18
; v2c19 = f v2c19
}
| Xor
{ in1
; in2
; out
; in1_0
; in1_1
; in1_2
; in1_3
; in2_0
; in2_1
; in2_2
; in2_3
; out_0
; out_1
; out_2
; out_3
} ->
Xor
{ in1 = f in1
; in2 = f in2
; out = f out
; in1_0 = f in1_0
; in1_1 = f in1_1
; in1_2 = f in1_2
; in1_3 = f in1_3
; in2_0 = f in2_0
; in2_1 = f in2_1
; in2_2 = f in2_2
; in2_3 = f in2_3
; out_0 = f out_0
; out_1 = f out_1
; out_2 = f out_2
; out_3 = f out_3
}
| ForeignFieldAdd
{ left_input_lo
; left_input_mi
; left_input_hi
; right_input_lo
; right_input_mi
; right_input_hi
; field_overflow
; carry
} ->
ForeignFieldAdd
{ left_input_lo = f left_input_lo
; left_input_mi = f left_input_mi
; left_input_hi = f left_input_hi
; right_input_lo = f right_input_lo
; right_input_mi = f right_input_mi
; right_input_hi = f right_input_hi
; field_overflow = f field_overflow
; carry = f carry
}
| ForeignFieldMul
{ (* Current row *) left_input0
; left_input1
; left_input2
; right_input0
; right_input1
; right_input2
; carry1_lo
; carry1_hi
; carry0
; quotient0
; quotient1
; quotient2
; quotient_bound_carry
; product1_hi_1
; (* Next row *) remainder0
; remainder1
; remainder2
; quotient_bound01
; quotient_bound2
; product1_lo
; product1_hi_0
} ->
ForeignFieldMul
{ (* Current row *) left_input0 = f left_input0
; left_input1 = f left_input1
; left_input2 = f left_input2
; right_input0 = f right_input0
; right_input1 = f right_input1
; right_input2 = f right_input2
; carry1_lo = f carry1_lo
; carry1_hi = f carry1_hi
; carry0 = f carry0
; quotient0 = f quotient0
; quotient1 = f quotient1
; quotient2 = f quotient2
; quotient_bound_carry = f quotient_bound_carry
; product1_hi_1 = f product1_hi_1
; (* Next row *) remainder0 = f remainder0
; remainder1 = f remainder1
; remainder2 = f remainder2
; quotient_bound01 = f quotient_bound01
; quotient_bound2 = f quotient_bound2
; product1_lo = f product1_lo
; product1_hi_0 = f product1_hi_0
}
| Rot64
{ (* Current row *) word
; rotated
; excess
; bound_limb0
; bound_limb1
; bound_limb2
; bound_limb3
; bound_crumb0
; bound_crumb1
; bound_crumb2
; bound_crumb3
; bound_crumb4
; bound_crumb5
; bound_crumb6
; bound_crumb7
; (* Next row *) shifted
; shifted_limb0
; shifted_limb1
; shifted_limb2
; shifted_limb3
; shifted_crumb0
; shifted_crumb1
; shifted_crumb2
; shifted_crumb3
; shifted_crumb4
; shifted_crumb5
; shifted_crumb6
; shifted_crumb7
; (* Coefficients *) two_to_rot
} ->
Rot64
{ (* Current row *) word = f word
; rotated = f rotated
; excess = f excess
; bound_limb0 = f bound_limb0
; bound_limb1 = f bound_limb1
; bound_limb2 = f bound_limb2
; bound_limb3 = f bound_limb3
; bound_crumb0 = f bound_crumb0
; bound_crumb1 = f bound_crumb1
; bound_crumb2 = f bound_crumb2
; bound_crumb3 = f bound_crumb3
; bound_crumb4 = f bound_crumb4
; bound_crumb5 = f bound_crumb5
; bound_crumb6 = f bound_crumb6
; bound_crumb7 = f bound_crumb7
; (* Next row *) shifted = f shifted
; shifted_limb0 = f shifted_limb0
; shifted_limb1 = f shifted_limb1
; shifted_limb2 = f shifted_limb2
; shifted_limb3 = f shifted_limb3
; shifted_crumb0 = f shifted_crumb0
; shifted_crumb1 = f shifted_crumb1
; shifted_crumb2 = f shifted_crumb2
; shifted_crumb3 = f shifted_crumb3
; shifted_crumb4 = f shifted_crumb4
; shifted_crumb5 = f shifted_crumb5
; shifted_crumb6 = f shifted_crumb6
; shifted_crumb7 = f shifted_crumb7
; (* Coefficients *) two_to_rot
}
| Raw { kind; values; coeffs } ->
Raw { kind; values = Array.map ~f values; coeffs }
(** [eval (module F) get_variable gate] checks that [gate]'s polynomial is
satisfied by the assignments given by [get_variable].
Warning: currently only implemented for the [Basic] gate.
*)
let eval (type v f)
(module F : Snarky_backendless.Field_intf.S with type t = f)
(eval_one : v -> f) (t : (v, f) t) =
match t with
cl * vl + cr * vr + co * vo + m * vl*vr + c = 0
| Basic { l = cl, vl; r = cr, vr; o = co, vo; m; c } ->
let vl = eval_one vl in
let vr = eval_one vr in
let vo = eval_one vo in
let open F in
let res =
List.reduce_exn ~f:add
[ mul cl vl; mul cr vr; mul co vo; mul m (mul vl vr); c ]
in
if not (equal zero res) then (
eprintf
!"%{sexp:t} * %{sexp:t}\n\
+ %{sexp:t} * %{sexp:t}\n\
+ %{sexp:t} * %{sexp:t}\n\
+ %{sexp:t} * %{sexp:t}\n\
+ %{sexp:t}\n\
= %{sexp:t}%!"
cl vl cr vr co vo m (mul vl vr) c res ;
false )
else true
| _ ->
true
end
include T
Adds our constraint enum to the list of constraints handled by .
include Snarky_backendless.Constraint.Add_kind (T)
end
module Internal_var = Core_kernel.Unique_id.Int ()
module V = struct
open Core_kernel
module T = struct
(** Variables linking uses of the same data between different gates.
Every internal variable is computable from a finite list of external
variables and internal variables.
Currently, in fact, every internal variable is a linear combination of
external variables and previously generated internal variables.
*)
type t =
| External of int
(** An external variable (generated by snarky, via [exists]). *)
| Internal of Internal_var.t
* An internal variable is generated to hold an intermediate value
( e.g. , in reducing linear combinations to single PLONK positions ) .
(e.g., in reducing linear combinations to single PLONK positions).
*)
[@@deriving compare, hash, sexp]
end
include T
include Comparable.Make (T)
include Hashable.Make (T)
end
(** Keeps track of a circuit (which is a list of gates)
while it is being written.
*)
type ('f, 'rust_gates) circuit =
| Unfinalized_rev of (unit, 'f) Gate_spec.t list
(** A circuit still being written. *)
| Compiled of Core_kernel.Md5.t * 'rust_gates
(** Once finalized, a circuit is represented as a digest
and a list of gates that corresponds to the circuit.
*)
(** The constraint system. *)
type ('f, 'rust_gates) t =
{ (* Map of cells that share the same value (enforced by to the permutation). *)
equivalence_classes : Row.t Position.t list V.Table.t
; (* How to compute each internal variable (as a linear combination of other variables). *)
internal_vars : (('f * V.t) list * 'f option) Internal_var.Table.t
; (* The variables that hold each witness value for each row, in reverse order. *)
mutable rows_rev : V.t option array list
; (* A circuit is described by a series of gates.
A gate is finalized once [finalize_and_get_gates] is called.
The finalized tag contains the digest of the circuit.
*)
mutable gates : ('f, 'rust_gates) circuit
; (* The row to use the next time we add a constraint. *)
mutable next_row : int
The size of the public input ( which fills the first rows of our constraint system .
public_input_size : int Core_kernel.Set_once.t
; (* The number of previous recursion challenges. *)
prev_challenges : int Core_kernel.Set_once.t
; (* Whatever is not public input. *)
mutable auxiliary_input_size : int
Queue ( of size 1 ) of generic gate .
mutable pending_generic_gate :
(V.t option * V.t option * V.t option * 'f array) option
; (* V.t's corresponding to constant values. We reuse them so we don't need to
use a fresh generic constraint each time to create a constant.
*)
cached_constants : ('f, V.t) Core_kernel.Hashtbl.t
(* The [equivalence_classes] field keeps track of the positions which must be
enforced to be equivalent due to the fact that they correspond to the same V.t value.
I.e., positions that are different usages of the same [V.t].
We use a union-find data structure to track equalities that a constraint system wants
enforced *between* [V.t] values. Then, at the end, for all [V.t]s that have been unioned
together, we combine their equivalence classes in the [equivalence_classes] table into
a single equivalence class, so that the permutation argument enforces these desired equalities
as well.
*)
; union_finds : V.t Core_kernel.Union_find.t V.Table.t
}
let get_public_input_size sys = sys.public_input_size
let get_rows_len sys = List.length sys.rows_rev
let get_prev_challenges sys = sys.prev_challenges
let set_prev_challenges sys challenges =
Core_kernel.Set_once.set_exn sys.prev_challenges [%here] challenges
(* TODO: shouldn't that Make create something bounded by a signature? As we know what a back end should be? Check where this is used *)
(* TODO: glossary of terms in this file (terms, reducing, feeding) + module doc *)
TODO : rename to F or Field
(** ? *)
module Make
(Fp : Field.S)
We create a type for gate vector , instead of using ` Gate.t list ` . If we did , we would have to convert it to a ` Gate.t array ` to pass it across the FFI boundary , where then it gets converted to a ` Vec < Gate > ` ; it 's more efficient to just create the ` Vec < Gate > ` directly .
*)
(Gates : Gate_vector_intf with type field := Fp.t)
(Params : sig
val params : Fp.t Params.t
end) : sig
open Core_kernel
type nonrec t = (Fp.t, Gates.t) t
val create : unit -> t
val get_public_input_size : t -> int Set_once.t
val get_primary_input_size : t -> int
val set_primary_input_size : t -> int -> unit
val get_auxiliary_input_size : t -> int
val set_auxiliary_input_size : t -> int -> unit
val get_prev_challenges : t -> int option
val set_prev_challenges : t -> int -> unit
val get_rows_len : t -> int
val next_row : t -> int
val add_constraint :
?label:string
-> t
-> ( Fp.t Snarky_backendless.Cvar.t
, Fp.t )
Snarky_backendless.Constraint.basic
-> unit
val compute_witness : t -> (int -> Fp.t) -> Fp.t array array
val finalize : t -> unit
val finalize_and_get_gates : t -> Gates.t
val num_constraints : t -> int
val digest : t -> Md5.t
val to_json : t -> string
end = struct
open Core_kernel
open Pickles_types
type nonrec t = (Fp.t, Gates.t) t
* Converts the set of permutations ( equivalence_classes ) to
a hash table that maps each position to the next one .
For example , if one of the equivalence class is [ pos1 , pos3 , pos7 ] ,
the function will return a hashtable that maps pos1 to pos3 ,
pos3 to pos7 , and pos7 to .
a hash table that maps each position to the next one.
For example, if one of the equivalence class is [pos1, pos3, pos7],
the function will return a hashtable that maps pos1 to pos3,
pos3 to pos7, and pos7 to pos1.
*)
let equivalence_classes_to_hashtbl sys =
let module Relative_position = struct
module T = struct
type t = Row.t Position.t [@@deriving hash, sexp, compare]
end
include T
include Core_kernel.Hashable.Make (T)
end in
let equivalence_classes = V.Table.create () in
Hashtbl.iteri sys.equivalence_classes ~f:(fun ~key ~data ->
let u = Hashtbl.find_exn sys.union_finds key in
Hashtbl.update equivalence_classes (Union_find.get u) ~f:(function
| None ->
Relative_position.Hash_set.of_list data
| Some ps ->
List.iter ~f:(Hash_set.add ps) data ;
ps ) ) ;
let res = Relative_position.Table.create () in
Hashtbl.iter equivalence_classes ~f:(fun ps ->
let rotate_left = function [] -> [] | x :: xs -> xs @ [ x ] in
let ps = Hash_set.to_list ps in
List.iter2_exn ps (rotate_left ps) ~f:(fun input output ->
Hashtbl.add_exn res ~key:input ~data:output ) ) ;
res
(** Compute the witness, given the constraint system `sys`
and a function that converts the indexed secret inputs to their concrete values.
*)
let compute_witness (sys : t) (external_values : int -> Fp.t) :
Fp.t array array =
let internal_values : Fp.t Internal_var.Table.t =
Internal_var.Table.create ()
in
let public_input_size = Set_once.get_exn sys.public_input_size [%here] in
let num_rows = public_input_size + sys.next_row in
let res =
Array.init Constants.columns ~f:(fun _ ->
Array.create ~len:num_rows Fp.zero )
in
(* Public input *)
for i = 0 to public_input_size - 1 do
res.(0).(i) <- external_values (i + 1)
done ;
let find t k =
match Hashtbl.find t k with
| None ->
failwithf !"Could not find %{sexp:Internal_var.t}\n%!" k ()
| Some x ->
x
in
(* Compute an internal variable associated value. *)
let compute ((lc, c) : (Fp.t * V.t) list * Fp.t option) =
List.fold lc ~init:(Option.value c ~default:Fp.zero) ~f:(fun acc (s, x) ->
let x =
match x with
| External x ->
external_values x
| Internal x ->
find internal_values x
in
Fp.(acc + (s * x)) )
in
(* Update the witness table with the value of the variables from each row. *)
List.iteri (List.rev sys.rows_rev) ~f:(fun i_after_input cols ->
let row_idx = i_after_input + public_input_size in
Array.iteri cols ~f:(fun col_idx var ->
match var with
| None ->
()
| Some (External var) ->
res.(col_idx).(row_idx) <- external_values var
| Some (Internal var) ->
let lc = find sys.internal_vars var in
let value = compute lc in
res.(col_idx).(row_idx) <- value ;
Hashtbl.set internal_values ~key:var ~data:value ) ) ;
(* Return the witness. *)
res
let union_find sys v =
Hashtbl.find_or_add sys.union_finds v ~default:(fun () ->
Union_find.create v )
(** Creates an internal variable and assigns it the value lc and constant. *)
let create_internal ?constant sys lc : V.t =
let v = Internal_var.create () in
ignore (union_find sys (Internal v) : _ Union_find.t) ;
Hashtbl.add_exn sys.internal_vars ~key:v ~data:(lc, constant) ;
V.Internal v
(* Initializes a constraint system. *)
let create () : t =
{ public_input_size = Set_once.create ()
; prev_challenges = Set_once.create ()
; internal_vars = Internal_var.Table.create ()
Gates.create ( )
; rows_rev = []
; next_row = 0
; equivalence_classes = V.Table.create ()
; auxiliary_input_size = 0
; pending_generic_gate = None
; cached_constants = Hashtbl.create (module Fp)
; union_finds = V.Table.create ()
}
(** Returns the number of auxiliary inputs. *)
let get_auxiliary_input_size t = t.auxiliary_input_size
(** Returns the number of public inputs. *)
let get_primary_input_size t = Set_once.get_exn t.public_input_size [%here]
(** Returns the number of previous challenges. *)
let get_prev_challenges t = Set_once.get t.prev_challenges
(* Non-public part of the witness. *)
let set_auxiliary_input_size t x = t.auxiliary_input_size <- x
(** Sets the number of public-input. It must and can only be called once. *)
let set_primary_input_size (sys : t) num_pub_inputs =
Set_once.set_exn sys.public_input_size [%here] num_pub_inputs
(** Sets the number of previous challenges. It must and can only be called once. *)
let set_prev_challenges (sys : t) num_prev_challenges =
Set_once.set_exn sys.prev_challenges [%here] num_prev_challenges
let get_public_input_size (sys : t) = get_public_input_size sys
let get_rows_len (sys : t) = get_rows_len sys
let next_row (sys : t) = sys.next_row
(** Adds {row; col} to the system's wiring under a specific key.
A key is an external or internal variable.
The row must be given relative to the start of the circuit
(so at the start of the public-input rows). *)
let wire' sys key row (col : int) =
ignore (union_find sys key : V.t Union_find.t) ;
V.Table.add_multi sys.equivalence_classes ~key ~data:{ row; col }
TODO : rename to wire_abs and wire_rel ? or wire_public and ? or force a single use function that takes a Row.t ?
(** Same as wire', except that the row must be given relatively to the end of the public-input rows. *)
let wire sys key row col = wire' sys key (Row.After_public_input row) col
(** Adds a row/gate/constraint to a constraint system `sys`. *)
let add_row sys (vars : V.t option array) kind coeffs =
match sys.gates with
| Compiled _ ->
failwith "add_row called on finalized constraint system"
| Unfinalized_rev gates ->
As we 're adding a row , we 're adding new cells .
If these cells ( the first 7 ) contain variables ,
make sure that they are wired
If these cells (the first 7) contain variables,
make sure that they are wired
*)
let num_vars = min Constants.permutation_cols (Array.length vars) in
let vars_for_perm = Array.slice vars 0 num_vars in
Array.iteri vars_for_perm ~f:(fun col x ->
Option.iter x ~f:(fun x -> wire sys x sys.next_row col) ) ;
(* Add to gates. *)
let open Position in
sys.gates <- Unfinalized_rev ({ kind; wired_to = [||]; coeffs } :: gates) ;
(* Increment row. *)
sys.next_row <- sys.next_row + 1 ;
(* Add to row. *)
sys.rows_rev <- vars :: sys.rows_rev
* Adds zero - knowledgeness to the gates / rows ,
and convert into Rust type [ Gates.t ] .
This can only be called once .
and convert into Rust type [Gates.t].
This can only be called once.
*)
let rec finalize_and_get_gates sys =
match sys with
| { gates = Compiled (_, gates); _ } ->
gates
| { pending_generic_gate = Some (l, r, o, coeffs); _ } ->
Finalize any pending generic constraint first .
add_row sys [| l; r; o |] Generic coeffs ;
sys.pending_generic_gate <- None ;
finalize_and_get_gates sys
| { gates = Unfinalized_rev gates_rev; _ } ->
let rust_gates = Gates.create () in
(* Create rows for public input. *)
let public_input_size =
Set_once.get_exn sys.public_input_size [%here]
in
let pub_selectors = [| Fp.one; Fp.zero; Fp.zero; Fp.zero; Fp.zero |] in
let pub_input_gate_specs_rev = ref [] in
for row = 0 to public_input_size - 1 do
let public_var = V.External (row + 1) in
wire' sys public_var (Row.Public_input row) 0 ;
pub_input_gate_specs_rev :=
{ Gate_spec.kind = Generic
; wired_to = [||]
; coeffs = pub_selectors
}
:: !pub_input_gate_specs_rev
done ;
Construct permutation hashmap .
let pos_map = equivalence_classes_to_hashtbl sys in
let permutation (pos : Row.t Position.t) : Row.t Position.t =
Option.value (Hashtbl.find pos_map pos) ~default:pos
in
let update_gate_with_permutation_info (row : Row.t)
(gate : (unit, _) Gate_spec.t) : (Row.t, _) Gate_spec.t =
{ gate with
wired_to =
Array.init Constants.permutation_cols ~f:(fun col ->
permutation { row; col } )
}
in
(* Process public gates. *)
let public_gates = List.rev !pub_input_gate_specs_rev in
let public_gates =
List.mapi public_gates ~f:(fun absolute_row gate ->
update_gate_with_permutation_info (Row.Public_input absolute_row)
gate )
in
construct all the other gates ( except zero - knowledge rows )
let gates = List.rev gates_rev in
let gates =
List.mapi gates ~f:(fun relative_row gate ->
update_gate_with_permutation_info
(Row.After_public_input relative_row) gate )
in
(* concatenate and convert to absolute rows *)
let to_absolute_row =
Gate_spec.map_rows ~f:(Row.to_absolute ~public_input_size)
in
(* convert all the gates into our Gates.t Rust vector type *)
let add_gates gates =
List.iter gates ~f:(fun g ->
let g = to_absolute_row g in
Gates.add rust_gates (Gate_spec.to_rust_gate g) )
in
add_gates public_gates ;
add_gates gates ;
(* compute the circuit's digest *)
let digest = Gates.digest public_input_size rust_gates in
let md5_digest = Md5.digest_bytes digest in
(* drop the gates, we don't need them anymore *)
sys.gates <- Compiled (md5_digest, rust_gates) ;
(* return the gates *)
rust_gates
(** Calls [finalize_and_get_gates] and ignores the result. *)
let finalize t = ignore (finalize_and_get_gates t : Gates.t)
let num_constraints sys = finalize_and_get_gates sys |> Gates.len
let to_json (sys : t) : string =
let gates = finalize_and_get_gates sys in
let public_input_size = Set_once.get_exn sys.public_input_size [%here] in
Gates.to_json public_input_size gates
(* Returns a hash of the circuit. *)
let rec digest (sys : t) =
match sys.gates with
| Unfinalized_rev _ ->
finalize sys ; digest sys
| Compiled (digest, _) ->
digest
* Regroup terms that share the same variable .
For example , ( 3 , i2 ) ; ( 2 , i2 ) can be simplified to ( 5 , i2 ) .
It assumes that the list of given terms is sorted ,
and that i0 is the smallest one .
For example , ` i0 = 1 ` and ` terms = [ ( _ , 2 ) ; ( _ , 2 ) ; ( _ ; 4 ) ; ... ] `
Returns ` ( last_scalar , last_variable , terms , terms_length ) `
where terms does not contain the last scalar and last variable observed .
For example, (3, i2) ; (2, i2) can be simplified to (5, i2).
It assumes that the list of given terms is sorted,
and that i0 is the smallest one.
For example, `i0 = 1` and `terms = [(_, 2); (_, 2); (_; 4); ...]`
Returns `(last_scalar, last_variable, terms, terms_length)`
where terms does not contain the last scalar and last variable observed.
*)
let accumulate_terms terms =
List.fold terms ~init:Int.Map.empty ~f:(fun acc (x, i) ->
Map.change acc i ~f:(fun y ->
let res = match y with None -> x | Some y -> Fp.add x y in
if Fp.(equal zero res) then None else Some res ) )
(** Converts a [Cvar.t] to a `(terms, terms_length, has_constant)`.
if `has_constant` is set, then terms start with a constant term in the form of (c, 0).
*)
let canonicalize x =
let c, terms =
Fp.(
Snarky_backendless.Cvar.to_constant_and_terms ~add ~mul ~zero:(of_int 0)
~equal ~one:(of_int 1))
x
in
Note : [ ( c , 0 ) ] represents the field element [ c ] multiplied by the 0th
variable , which is held constant as [ Field.one ] .
variable, which is held constant as [Field.one].
*)
let terms = match c with None -> terms | Some c -> (c, 0) :: terms in
let has_constant_term = Option.is_some c in
let terms = accumulate_terms terms in
let terms_list =
Map.fold_right ~init:[] terms ~f:(fun ~key ~data acc ->
(data, key) :: acc )
in
Some (terms_list, Map.length terms, has_constant_term)
* Adds a generic constraint to the constraint system .
As there are two generic gates per row , we queue
every other generic gate .
As there are two generic gates per row, we queue
every other generic gate.
*)
let add_generic_constraint ?l ?r ?o coeffs sys : unit =
match sys.pending_generic_gate with
(* if the queue of generic gate is empty, queue this *)
| None ->
sys.pending_generic_gate <- Some (l, r, o, coeffs)
(* otherwise empty the queue and create the row *)
| Some (l2, r2, o2, coeffs2) ->
let coeffs = Array.append coeffs coeffs2 in
add_row sys [| l; r; o; l2; r2; o2 |] Generic coeffs ;
sys.pending_generic_gate <- None
* Converts a number of scaled additions \sum s_i * x_i
to as many constraints as needed ,
creating temporary variables for each new row / constraint ,
and returning the output variable .
For example , [ ( s1 , x1 ) , ( s2 , x2 ) ] is transformed into :
- internal_var_1 = s1 * x1 + s2 * x2
- return ( 1 , internal_var_1 )
and [ ( s1 , x1 ) , ( s2 , x2 ) , ( s3 , x3 ) ] is transformed into :
- internal_var_1 = s1 * x1 + s2 * x2
- internal_var_2 = 1 * internal_var_1 + s3 * x3
- return ( 1 , internal_var_2 )
It assumes that the list of terms is not empty .
to as many constraints as needed,
creating temporary variables for each new row/constraint,
and returning the output variable.
For example, [(s1, x1), (s2, x2)] is transformed into:
- internal_var_1 = s1 * x1 + s2 * x2
- return (1, internal_var_1)
and [(s1, x1), (s2, x2), (s3, x3)] is transformed into:
- internal_var_1 = s1 * x1 + s2 * x2
- internal_var_2 = 1 * internal_var_1 + s3 * x3
- return (1, internal_var_2)
It assumes that the list of terms is not empty. *)
let completely_reduce sys (terms : (Fp.t * int) list) =
(* just adding constrained variables without values *)
let rec go = function
| [] ->
assert false
| [ (s, x) ] ->
(s, V.External x)
| (ls, lx) :: t ->
let lx = V.External lx in
(* TODO: this should be rewritten to be tail-optimized *)
let rs, rx = go t in
let s1x1_plus_s2x2 = create_internal sys [ (ls, lx); (rs, rx) ] in
add_generic_constraint ~l:lx ~r:rx ~o:s1x1_plus_s2x2
[| ls; rs; Fp.(negate one); Fp.zero; Fp.zero |]
sys ;
(Fp.one, s1x1_plus_s2x2)
in
go terms
* Converts a linear combination of variables into a set of constraints .
It returns the output variable as ( 1 , ` Var res ) ,
unless the output is a constant , in which case it returns ( c , ` Constant ) .
It returns the output variable as (1, `Var res),
unless the output is a constant, in which case it returns (c, `Constant).
*)
let reduce_lincom sys (x : Fp.t Snarky_backendless.Cvar.t) =
let constant, terms =
Fp.(
Snarky_backendless.Cvar.to_constant_and_terms ~add ~mul ~zero:(of_int 0)
~equal ~one:(of_int 1))
x
in
let terms = accumulate_terms terms in
let terms_list =
Map.fold_right ~init:[] terms ~f:(fun ~key ~data acc ->
(data, key) :: acc )
in
match (constant, Map.is_empty terms) with
| Some c, true ->
(c, `Constant)
| None, true ->
(Fp.zero, `Constant)
| _ -> (
match terms_list with
| [] ->
assert false
| [ (ls, lx) ] -> (
match constant with
| None ->
(ls, `Var (V.External lx))
| Some c ->
(* res = ls * lx + c *)
let res =
create_internal ~constant:c sys [ (ls, External lx) ]
in
add_generic_constraint ~l:(External lx) ~o:res
[| ls; Fp.zero; Fp.(negate one); Fp.zero; c |]
(* Could be here *)
sys ;
(Fp.one, `Var res) )
| (ls, lx) :: tl ->
(* reduce the terms, then add the constant *)
let rs, rx = completely_reduce sys tl in
let res =
create_internal ?constant sys [ (ls, External lx); (rs, rx) ]
in
(* res = ls * lx + rs * rx + c *)
add_generic_constraint ~l:(External lx) ~r:rx ~o:res
[| ls
; rs
; Fp.(negate one)
; Fp.zero
; (match constant with Some x -> x | None -> Fp.zero)
|]
(* Could be here *)
sys ;
(Fp.one, `Var res) )
(** Adds a constraint to the constraint system. *)
let add_constraint ?label:_ sys
(constr :
( Fp.t Snarky_backendless.Cvar.t
, Fp.t )
Snarky_backendless.Constraint.basic ) =
let red = reduce_lincom sys in
(* reduce any [Cvar.t] to a single internal variable *)
let reduce_to_v (x : Fp.t Snarky_backendless.Cvar.t) : V.t =
match red x with
| s, `Var x ->
if Fp.equal s Fp.one then x
else
let sx = create_internal sys [ (s, x) ] in
(* s * x - sx = 0 *)
add_generic_constraint ~l:x ~o:sx
[| s; Fp.zero; Fp.(negate one); Fp.zero; Fp.zero |]
sys ;
sx
| s, `Constant -> (
match Hashtbl.find sys.cached_constants s with
| Some x ->
x
| None ->
let x = create_internal sys ~constant:s [] in
add_generic_constraint ~l:x
[| Fp.one; Fp.zero; Fp.zero; Fp.zero; Fp.negate s |]
sys ;
Hashtbl.set sys.cached_constants ~key:s ~data:x ;
x )
in
match constr with
| Snarky_backendless.Constraint.Square (v1, v2) -> (
match (red v1, red v2) with
| (sl, `Var xl), (so, `Var xo) ->
(* (sl * xl)^2 = so * xo
sl^2 * xl * xl - so * xo = 0
*)
add_generic_constraint ~l:xl ~r:xl ~o:xo
[| Fp.zero; Fp.zero; Fp.negate so; Fp.(sl * sl); Fp.zero |]
sys
| (sl, `Var xl), (so, `Constant) ->
(* TODO: it's hard to read the array of selector values, name them! *)
add_generic_constraint ~l:xl ~r:xl
[| Fp.zero; Fp.zero; Fp.zero; Fp.(sl * sl); Fp.negate so |]
sys
| (sl, `Constant), (so, `Var xo) ->
(* sl^2 = so * xo *)
add_generic_constraint ~o:xo
[| Fp.zero; Fp.zero; so; Fp.zero; Fp.negate (Fp.square sl) |]
sys
| (sl, `Constant), (so, `Constant) ->
assert (Fp.(equal (square sl) so)) )
| Snarky_backendless.Constraint.R1CS (v1, v2, v3) -> (
match (red v1, red v2, red v3) with
| (s1, `Var x1), (s2, `Var x2), (s3, `Var x3) ->
(* s1 x1 * s2 x2 = s3 x3
- s1 s2 (x1 x2) + s3 x3 = 0
*)
add_generic_constraint ~l:x1 ~r:x2 ~o:x3
[| Fp.zero; Fp.zero; s3; Fp.(negate s1 * s2); Fp.zero |]
sys
| (s1, `Var x1), (s2, `Var x2), (s3, `Constant) ->
add_generic_constraint ~l:x1 ~r:x2
[| Fp.zero; Fp.zero; Fp.zero; Fp.(s1 * s2); Fp.negate s3 |]
sys
| (s1, `Var x1), (s2, `Constant), (s3, `Var x3) ->
(* s1 x1 * s2 = s3 x3
*)
add_generic_constraint ~l:x1 ~o:x3
[| Fp.(s1 * s2); Fp.zero; Fp.negate s3; Fp.zero; Fp.zero |]
sys
| (s1, `Constant), (s2, `Var x2), (s3, `Var x3) ->
add_generic_constraint ~r:x2 ~o:x3
[| Fp.zero; Fp.(s1 * s2); Fp.negate s3; Fp.zero; Fp.zero |]
sys
| (s1, `Var x1), (s2, `Constant), (s3, `Constant) ->
add_generic_constraint ~l:x1
[| Fp.(s1 * s2); Fp.zero; Fp.zero; Fp.zero; Fp.negate s3 |]
sys
| (s1, `Constant), (s2, `Var x2), (s3, `Constant) ->
add_generic_constraint ~r:x2
[| Fp.zero; Fp.(s1 * s2); Fp.zero; Fp.zero; Fp.negate s3 |]
sys
| (s1, `Constant), (s2, `Constant), (s3, `Var x3) ->
add_generic_constraint ~o:x3
[| Fp.zero; Fp.zero; s3; Fp.zero; Fp.(negate s1 * s2) |]
sys
| (s1, `Constant), (s2, `Constant), (s3, `Constant) ->
assert (Fp.(equal s3 Fp.(s1 * s2))) )
| Snarky_backendless.Constraint.Boolean v -> (
let s, x = red v in
match x with
| `Var x ->
(* -x + x * x = 0 *)
add_generic_constraint ~l:x ~r:x
[| Fp.(negate one); Fp.zero; Fp.zero; Fp.one; Fp.zero |]
sys
| `Constant ->
assert (Fp.(equal s (s * s))) )
| Snarky_backendless.Constraint.Equal (v1, v2) -> (
let (s1, x1), (s2, x2) = (red v1, red v2) in
match (x1, x2) with
| `Var x1, `Var x2 ->
if Fp.equal s1 s2 then (
if not (Fp.equal s1 Fp.zero) then
Union_find.union (union_find sys x1) (union_find sys x2) )
else if (* s1 x1 - s2 x2 = 0
*)
not (Fp.equal s1 s2) then
add_generic_constraint ~l:x1 ~r:x2
[| s1; Fp.(negate s2); Fp.zero; Fp.zero; Fp.zero |]
sys
else
add_generic_constraint ~l:x1 ~r:x2
[| s1; Fp.(negate s2); Fp.zero; Fp.zero; Fp.zero |]
sys
| `Var x1, `Constant -> (
(* s1 * x1 = s2
x1 = s2 / s1
*)
let ratio = Fp.(s2 / s1) in
match Hashtbl.find sys.cached_constants ratio with
| Some x2 ->
Union_find.union (union_find sys x1) (union_find sys x2)
| None ->
add_generic_constraint ~l:x1
[| s1; Fp.zero; Fp.zero; Fp.zero; Fp.negate s2 |]
sys ;
Hashtbl.set sys.cached_constants ~key:ratio ~data:x1 )
| `Constant, `Var x2 -> (
(* s1 = s2 * x2
x2 = s1 / s2
*)
let ratio = Fp.(s1 / s2) in
match Hashtbl.find sys.cached_constants ratio with
| Some x1 ->
Union_find.union (union_find sys x1) (union_find sys x2)
| None ->
add_generic_constraint ~r:x2
[| Fp.zero; s2; Fp.zero; Fp.zero; Fp.negate s1 |]
sys ;
Hashtbl.set sys.cached_constants ~key:ratio ~data:x2 )
| `Constant, `Constant ->
assert (Fp.(equal s1 s2)) )
| Plonk_constraint.T (Basic { l; r; o; m; c }) ->
0
= l.s * l.x
+ r.s * r.x
+ o.s * o.x
+ m * ( l.x * r.x )
+ c
=
* l.x '
+ r.s * r.s ' * r.x '
+ o.s * o.s ' * o.x '
+ m * ( l.s ' * l.x ' * r.s ' * r.x ' )
+ c
=
( l.s * l.s ' ) * l.x '
+ ( r.s * r.s ' ) * r.x '
+ ( o.s * o.s ' ) * o.x '
+ ( m * l.s ' * r.s ' ) * l.x ' r.x '
+ c
= l.s * l.x
+ r.s * r.x
+ o.s * o.x
+ m * (l.x * r.x)
+ c
=
l.s * l.s' * l.x'
+ r.s * r.s' * r.x'
+ o.s * o.s' * o.x'
+ m * (l.s' * l.x' * r.s' * r.x')
+ c
=
(l.s * l.s') * l.x'
+ (r.s * r.s') * r.x'
+ (o.s * o.s') * o.x'
+ (m * l.s' * r.s') * l.x' r.x'
+ c
*)
(* TODO: This is sub-optimal *)
let c = ref c in
let red_pr (s, x) =
match red x with
| s', `Constant ->
c := Fp.add !c Fp.(s * s') ;
(* No need to have a real term. *)
(s', None)
| s', `Var x ->
(s', Some (Fp.(s * s'), x))
in
l.s * l.x
+ r.s * r.x
+ o.s * o.x
+ m * ( l.x * r.x )
+ c
=
* l.x '
+ r.s * r.x
+ o.s * o.x
+ m * ( l.x * r.x )
+ c
=
+ r.s * r.x
+ o.s * o.x
+ m * (l.x * r.x)
+ c
=
l.s * l.s' * l.x'
+ r.s * r.x
+ o.s * o.x
+ m * (l.x * r.x)
+ c
=
*)
let l_s', l = red_pr l in
let r_s', r = red_pr r in
let _, o = red_pr o in
let var = Option.map ~f:snd in
let coeff = Option.value_map ~default:Fp.zero ~f:fst in
let m =
match (l, r) with
| Some _, Some _ ->
Fp.(l_s' * r_s' * m)
| _ ->
(* TODO: Figure this out later. *)
failwith "Must use non-constant cvar in plonk constraints"
in
add_generic_constraint ?l:(var l) ?r:(var r) ?o:(var o)
[| coeff l; coeff r; coeff o; m; !c |]
sys
| w0 | w1 | w2 | w3 | w4 | w5
state = [ x , x , x ] , [ y , y , y ] , ... ]
i=0 , perm^ i=1 , perm^
state = [ x , x , x ], [ y, y, y ], ... ]
i=0, perm^ i=1, perm^
*)
| Plonk_constraint.T (Poseidon { state }) ->
(* reduce the state *)
let reduce_state sys (s : Fp.t Snarky_backendless.Cvar.t array array) :
V.t array array =
Array.map ~f:(Array.map ~f:reduce_to_v) s
in
let state = reduce_state sys state in
add_round_state adds a row that contains 5 rounds of permutation
let add_round_state ~round (s1, s2, s3, s4, s5) =
let vars =
[| Some s1.(0)
; Some s1.(1)
; Some s1.(2)
the last state is in 2nd position
; Some s5.(1)
; Some s5.(2)
; Some s2.(0)
; Some s2.(1)
; Some s2.(2)
; Some s3.(0)
; Some s3.(1)
; Some s3.(2)
; Some s4.(0)
; Some s4.(1)
; Some s4.(2)
|]
in
let coeffs =
[| Params.params.round_constants.(round).(0)
; Params.params.round_constants.(round).(1)
; Params.params.round_constants.(round).(2)
; Params.params.round_constants.(round + 1).(0)
; Params.params.round_constants.(round + 1).(1)
; Params.params.round_constants.(round + 1).(2)
; Params.params.round_constants.(round + 2).(0)
; Params.params.round_constants.(round + 2).(1)
; Params.params.round_constants.(round + 2).(2)
; Params.params.round_constants.(round + 3).(0)
; Params.params.round_constants.(round + 3).(1)
; Params.params.round_constants.(round + 3).(2)
; Params.params.round_constants.(round + 4).(0)
; Params.params.round_constants.(round + 4).(1)
; Params.params.round_constants.(round + 4).(2)
|]
in
add_row sys vars Poseidon coeffs
in
(* add_last_row adds the last row containing the output *)
let add_last_row state =
let vars =
[| Some state.(0)
; Some state.(1)
; Some state.(2)
; None
; None
; None
; None
; None
; None
; None
; None
; None
; None
; None
; None
|]
in
add_row sys vars Zero [||]
in
go through the states row by row ( a row contains 5 states )
let rec process_5_states_at_a_time ~round = function
| [ s1; s2; s3; s4; s5; last ] ->
add_round_state ~round (s1, s2, s3, s4, s5) ;
add_last_row last
| s1 :: s2 :: s3 :: s4 :: s5 :: tl ->
add_round_state ~round (s1, s2, s3, s4, s5) ;
process_5_states_at_a_time ~round:(round + 5) tl
| _ ->
failwith "incorrect number of states given"
in
process_5_states_at_a_time ~round:0 (Array.to_list state)
| Plonk_constraint.T
(EC_add_complete { p1; p2; p3; inf; same_x; slope; inf_z; x21_inv }) ->
let reduce_curve_point (x, y) = (reduce_to_v x, reduce_to_v y) in
// ! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// ! x1 y1 x2 y2 x3 y3 inf same_x s inf_z x21_inv
//! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
//! x1 y1 x2 y2 x3 y3 inf same_x s inf_z x21_inv
*)
let x1, y1 = reduce_curve_point p1 in
let x2, y2 = reduce_curve_point p2 in
let x3, y3 = reduce_curve_point p3 in
let vars =
[| Some x1
; Some y1
; Some x2
; Some y2
; Some x3
; Some y3
; Some (reduce_to_v inf)
; Some (reduce_to_v same_x)
; Some (reduce_to_v slope)
; Some (reduce_to_v inf_z)
; Some (reduce_to_v x21_inv)
; None
; None
; None
; None
|]
in
add_row sys vars CompleteAdd [||]
| Plonk_constraint.T (EC_scale { state }) ->
let i = ref 0 in
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
xT yT x0 y0 n n ' x1 y1 x2 y2 x3 y3 x4 y4
x5 y5 b0 b1 b2 b3 b4 s0 s1 s2 s3 s4
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
xT yT x0 y0 n n' x1 y1 x2 y2 x3 y3 x4 y4
x5 y5 b0 b1 b2 b3 b4 s0 s1 s2 s3 s4
*)
let add_ecscale_round
Scale_round.{ accs; bits; ss; base = xt, yt; n_prev; n_next } =
let curr_row =
[| Some xt
; Some yt
; Some (fst accs.(0))
; Some (snd accs.(0))
; Some n_prev
; Some n_next
; None
; Some (fst accs.(1))
; Some (snd accs.(1))
; Some (fst accs.(2))
; Some (snd accs.(2))
; Some (fst accs.(3))
; Some (snd accs.(3))
; Some (fst accs.(4))
; Some (snd accs.(4))
|]
in
let next_row =
[| Some (fst accs.(5))
; Some (snd accs.(5))
; Some bits.(0)
; Some bits.(1)
; Some bits.(2)
; Some bits.(3)
; Some bits.(4)
; Some ss.(0)
; Some ss.(1)
; Some ss.(2)
; Some ss.(3)
; Some ss.(4)
; None
; None
; None
|]
in
add_row sys curr_row VarBaseMul [||] ;
add_row sys next_row Zero [||]
in
Array.iter
~f:(fun round -> add_ecscale_round round ; incr i)
(Array.map state ~f:(Scale_round.map ~f:reduce_to_v)) ;
()
| Plonk_constraint.T (EC_endoscale { state; xs; ys; n_acc }) ->
(* Reduce state. *)
let state = Array.map state ~f:(Endoscale_round.map ~f:reduce_to_v) in
(* Add round function. *)
let add_endoscale_round (round : V.t Endoscale_round.t) =
let row =
[| Some round.xt
; Some round.yt
; None
; None
; Some round.xp
; Some round.yp
; Some round.n_acc
; Some round.xr
; Some round.yr
; Some round.s1
; Some round.s3
; Some round.b1
; Some round.b2
; Some round.b3
; Some round.b4
|]
in
add_row sys row Kimchi_types.EndoMul [||]
in
Array.iter state ~f:add_endoscale_round ;
Last row .
let vars =
[| None
; None
; None
; None
; Some (reduce_to_v xs)
; Some (reduce_to_v ys)
; Some (reduce_to_v n_acc)
; None
; None
; None
; None
; None
; None
; None
; None
|]
in
add_row sys vars Zero [||]
| Plonk_constraint.T
(EC_endoscalar { state : 'v Endoscale_scalar_round.t array }) ->
(* Add round function. *)
let add_endoscale_scalar_round (round : V.t Endoscale_scalar_round.t) =
let row =
[| Some round.n0
; Some round.n8
; Some round.a0
; Some round.b0
; Some round.a8
; Some round.b8
; Some round.x0
; Some round.x1
; Some round.x2
; Some round.x3
; Some round.x4
; Some round.x5
; Some round.x6
; Some round.x7
; None
|]
in
add_row sys row Kimchi_types.EndoMulScalar [||]
in
Array.iter state
~f:
(Fn.compose add_endoscale_scalar_round
(Endoscale_scalar_round.map ~f:reduce_to_v) )
| Plonk_constraint.T
(RangeCheck0
{ v0
; v0p0
; v0p1
; v0p2
; v0p3
; v0p4
; v0p5
; v0c0
; v0c1
; v0c2
; v0c3
; v0c4
; v0c5
; v0c6
; v0c7
; compact
} ) ->
// ! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// ! v vp0 vp1 vp2 vp4 vp5 vc0 vc1 vc2 vc4 vc5 vc6 vc7
//! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
//! v vp0 vp1 vp2 vp3 vp4 vp5 vc0 vc1 vc2 vc3 vc4 vc5 vc6 vc7
*)
let vars =
[| Some (reduce_to_v v0)
; Some (reduce_to_v v0p0) (* MSBs *)
; Some (reduce_to_v v0p1)
; Some (reduce_to_v v0p2)
; Some (reduce_to_v v0p3)
; Some (reduce_to_v v0p4)
; Some (reduce_to_v v0p5)
; Some (reduce_to_v v0c0)
; Some (reduce_to_v v0c1)
; Some (reduce_to_v v0c2)
; Some (reduce_to_v v0c3)
; Some (reduce_to_v v0c4)
; Some (reduce_to_v v0c5)
; Some (reduce_to_v v0c6)
; Some (reduce_to_v v0c7) (* LSBs *)
|]
in
let coeff = if Fp.equal compact Fp.one then Fp.one else Fp.zero in
add_row sys vars RangeCheck0 [| coeff |]
| Plonk_constraint.T
(RangeCheck1
{ (* Current row *) v2
; v12
; v2c0
; v2p0
; v2p1
; v2p2
; v2p3
; v2c1
; v2c2
; v2c3
; v2c4
; v2c5
; v2c6
; v2c7
; v2c8
; (* Next row *) v2c9
; v2c10
; v2c11
; v0p0
; v0p1
; v1p0
; v1p1
; v2c12
; v2c13
; v2c14
; v2c15
; v2c16
; v2c17
; v2c18
; v2c19
} ) ->
// ! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// ! Curr : v2 v12 v2c0 v2p0 v2p1 v2p2 v2p3 v2c1 v2c2 v2c3 v2c6 v2c7 v2c8
// ! Next : v2c9 v2c11 v0p0 v0p1 v1p0 v1p1 v2c12 v2c13 v2c14 v2c15 v2c16 v2c17 v2c19
//! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
//! Curr: v2 v12 v2c0 v2p0 v2p1 v2p2 v2p3 v2c1 v2c2 v2c3 v2c4 v2c5 v2c6 v2c7 v2c8
//! Next: v2c9 v2c10 v2c11 v0p0 v0p1 v1p0 v1p1 v2c12 v2c13 v2c14 v2c15 v2c16 v2c17 v2c18 v2c19
*)
let vars_curr =
[| (* Current row *) Some (reduce_to_v v2)
; Some (reduce_to_v v12)
; Some (reduce_to_v v2c0) (* MSBs *)
; Some (reduce_to_v v2p0)
; Some (reduce_to_v v2p1)
; Some (reduce_to_v v2p2)
; Some (reduce_to_v v2p3)
; Some (reduce_to_v v2c1)
; Some (reduce_to_v v2c2)
; Some (reduce_to_v v2c3)
; Some (reduce_to_v v2c4)
; Some (reduce_to_v v2c5)
; Some (reduce_to_v v2c6)
; Some (reduce_to_v v2c7)
; Some (reduce_to_v v2c8) (* LSBs *)
|]
in
let vars_next =
[| (* Next row *) Some (reduce_to_v v2c9)
; Some (reduce_to_v v2c10)
; Some (reduce_to_v v2c11)
; Some (reduce_to_v v0p0)
; Some (reduce_to_v v0p1)
; Some (reduce_to_v v1p0)
; Some (reduce_to_v v1p1)
; Some (reduce_to_v v2c12)
; Some (reduce_to_v v2c13)
; Some (reduce_to_v v2c14)
; Some (reduce_to_v v2c15)
; Some (reduce_to_v v2c16)
; Some (reduce_to_v v2c17)
; Some (reduce_to_v v2c18)
; Some (reduce_to_v v2c19)
|]
in
add_row sys vars_curr RangeCheck1 [||] ;
add_row sys vars_next Zero [||]
| Plonk_constraint.T
(Xor
{ in1
; in2
; out
; in1_0
; in1_1
; in1_2
; in1_3
; in2_0
; in2_1
; in2_2
; in2_3
; out_0
; out_1
; out_2
; out_3
} ) ->
| Column | Curr | Next ( gadget responsibility ) |
| ------ | ---------------- | ---------------------------- |
| 0 | copy ` in1 ` | copy ` in1 ' ` |
| 1 | copy ` in2 ` | copy ` in2 ' ` |
| 2 | copy ` out ` | copy ` out ' ` |
| 3 | ` in1_0 ` | |
| 4 | plookup1 ` in1_1 ` | |
| 5 | plookup2 ` in1_2 ` | |
| 6 | in1_3 ` | |
| 7 | |
| 8 | plookup1 ` in2_1 ` | |
| 9 | plookup2 ` in2_2 ` | |
| 10 | plookup3 ` in2_3 ` | |
| 11 | ` out_0 ` | |
| 12 | plookup1 ` out_1 ` | |
| 13 | plookup2 ` out_2 ` | |
| 14 |
| ------ | ---------------- | ---------------------------- |
| 0 | copy `in1` | copy `in1'` |
| 1 | copy `in2` | copy `in2'` |
| 2 | copy `out` | copy `out'` |
| 3 | plookup0 `in1_0` | |
| 4 | plookup1 `in1_1` | |
| 5 | plookup2 `in1_2` | |
| 6 | plookup3 `in1_3` | |
| 7 | plookup0 `in2_0` | |
| 8 | plookup1 `in2_1` | |
| 9 | plookup2 `in2_2` | |
| 10 | plookup3 `in2_3` | |
| 11 | plookup0 `out_0` | |
| 12 | plookup1 `out_1` | |
| 13 | plookup2 `out_2` | |
| 14 | plookup3 `out_3` | |
*)
let curr_row =
[| Some (reduce_to_v in1)
; Some (reduce_to_v in2)
; Some (reduce_to_v out)
; Some (reduce_to_v in1_0)
; Some (reduce_to_v in1_1)
; Some (reduce_to_v in1_2)
; Some (reduce_to_v in1_3)
; Some (reduce_to_v in2_0)
; Some (reduce_to_v in2_1)
; Some (reduce_to_v in2_2)
; Some (reduce_to_v in2_3)
; Some (reduce_to_v out_0)
; Some (reduce_to_v out_1)
; Some (reduce_to_v out_2)
; Some (reduce_to_v out_3)
|]
in
The generic gate after a Xor16 gate is a Const to check that all values are zero .
For that , the first coefficient is 1 and the rest will be zero .
This will be included in the gadget for a chain of Xors , not here .
For that, the first coefficient is 1 and the rest will be zero.
This will be included in the gadget for a chain of Xors, not here.*)
add_row sys curr_row Xor16 [||]
| Plonk_constraint.T
(ForeignFieldAdd
{ left_input_lo
; left_input_mi
; left_input_hi
; right_input_lo
; right_input_mi
; right_input_hi
; field_overflow
; carry
} ) ->
// ! | Gate | ` ForeignFieldAdd ` | Circuit / gadget responsibility |
// ! | ------ | ------------------------ | ------------------------------ |
// ! | Column | ` Curr ` | ` Next ` |
// ! | ------ | ------------------------ | ------------------------------ |
// ! | 0 | ` left_input_lo ` ( copy ) | ` result_lo ` ( copy ) |
// ! | 1 | ` left_input_mi ` ( copy ) | ` result_mi ` ( copy ) |
// ! | 2 | ` left_input_hi ` ( copy ) | ` result_hi ` ( copy ) |
// ! | 3 | ` right_input_lo ` ( copy ) | |
// ! | 4 | ` right_input_mi ` ( copy ) | |
// ! | 5 | ` right_input_hi ` ( copy ) | |
// ! | 6 | ` field_overflow ` ( copy ? ) | |
// ! | 7 | ` carry ` | |
// ! | 8 | | |
// ! | 9 | | |
// ! | 10 | | |
// ! | 11 | | |
// ! | 12 | | |
// ! | 13 | | |
// ! | 14 | | |
//! | Gate | `ForeignFieldAdd` | Circuit/gadget responsibility |
//! | ------ | ------------------------ | ------------------------------ |
//! | Column | `Curr` | `Next` |
//! | ------ | ------------------------ | ------------------------------ |
//! | 0 | `left_input_lo` (copy) | `result_lo` (copy) |
//! | 1 | `left_input_mi` (copy) | `result_mi` (copy) |
//! | 2 | `left_input_hi` (copy) | `result_hi` (copy) |
//! | 3 | `right_input_lo` (copy) | |
//! | 4 | `right_input_mi` (copy) | |
//! | 5 | `right_input_hi` (copy) | |
//! | 6 | `field_overflow` (copy?) | |
//! | 7 | `carry` | |
//! | 8 | | |
//! | 9 | | |
//! | 10 | | |
//! | 11 | | |
//! | 12 | | |
//! | 13 | | |
//! | 14 | | |
*)
let vars =
[| (* Current row *) Some (reduce_to_v left_input_lo)
; Some (reduce_to_v left_input_mi)
; Some (reduce_to_v left_input_hi)
; Some (reduce_to_v right_input_lo)
; Some (reduce_to_v right_input_mi)
; Some (reduce_to_v right_input_hi)
; Some (reduce_to_v field_overflow)
; Some (reduce_to_v carry)
; None
; None
; None
; None
; None
; None
; None
|]
in
add_row sys vars ForeignFieldAdd [||]
| Plonk_constraint.T
(ForeignFieldMul
{ (* Current row *) left_input0
; left_input1
; left_input2
; right_input0
; right_input1
; right_input2
; carry1_lo
; carry1_hi
; carry0
; quotient0
; quotient1
; quotient2
; quotient_bound_carry
; product1_hi_1
; (* Next row *) remainder0
; remainder1
; remainder2
; quotient_bound01
; quotient_bound2
; product1_lo
; product1_hi_0
} ) ->
// ! | Gate | ` ForeignFieldMul ` | ` Zero ` |
// ! | ------ | ---------------------------- | ------------------------- |
// ! | Column | ` Curr ` | ` Next ` |
// ! | ------ | ---------------------------- | ------------------------- |
// ! | 0 | ` left_input0 ` ( copy ) | ` remainder0 ` ( copy ) |
// ! | 1 | ` left_input1 ` ( copy ) | ` remainder1 ` ( copy ) |
// ! | 2 | ` left_input2 ` ( copy ) | ` remainder2 ` ( copy ) |
// ! | 3 | ` right_input0 ` ( copy ) | ` quotient_bound01 ` ( copy ) |
// ! | 4 | ` right_input1 ` ( copy ) | ` quotient_bound2 ` ( copy ) |
// ! | 5 | ` right_input2 ` ( copy ) | ` product1_lo ` ( copy ) |
// ! | 6 | ` carry1_lo ` ( copy ) | ` product1_hi_0 ` ( copy ) |
// ! | 7 | ` carry1_hi ` ( plookup ) | |
// ! | 8 | ` carry0 ` | |
// ! | 9 | ` quotient0 ` | |
// ! | 10 | ` quotient1 ` | |
// ! | 11 | ` quotient2 ` | |
// ! | 12 | ` quotient_bound_carry ` | |
// ! | 13 | ` product1_hi_1 ` | |
// ! | 14 | | |
//! | Gate | `ForeignFieldMul` | `Zero` |
//! | ------ | ---------------------------- | ------------------------- |
//! | Column | `Curr` | `Next` |
//! | ------ | ---------------------------- | ------------------------- |
//! | 0 | `left_input0` (copy) | `remainder0` (copy) |
//! | 1 | `left_input1` (copy) | `remainder1` (copy) |
//! | 2 | `left_input2` (copy) | `remainder2` (copy) |
//! | 3 | `right_input0` (copy) | `quotient_bound01` (copy) |
//! | 4 | `right_input1` (copy) | `quotient_bound2` (copy) |
//! | 5 | `right_input2` (copy) | `product1_lo` (copy) |
//! | 6 | `carry1_lo` (copy) | `product1_hi_0` (copy) |
//! | 7 | `carry1_hi` (plookup) | |
//! | 8 | `carry0` | |
//! | 9 | `quotient0` | |
//! | 10 | `quotient1` | |
//! | 11 | `quotient2` | |
//! | 12 | `quotient_bound_carry` | |
//! | 13 | `product1_hi_1` | |
//! | 14 | | |
*)
let vars_curr =
[| (* Current row *) Some (reduce_to_v left_input0)
; Some (reduce_to_v left_input1)
; Some (reduce_to_v left_input2)
; Some (reduce_to_v right_input0)
; Some (reduce_to_v right_input1)
; Some (reduce_to_v right_input2)
; Some (reduce_to_v carry1_lo)
; Some (reduce_to_v carry1_hi)
; Some (reduce_to_v carry0)
; Some (reduce_to_v quotient0)
; Some (reduce_to_v quotient1)
; Some (reduce_to_v quotient2)
; Some (reduce_to_v quotient_bound_carry)
; Some (reduce_to_v product1_hi_1)
; None
|]
in
let vars_next =
[| (* Next row *) Some (reduce_to_v remainder0)
; Some (reduce_to_v remainder1)
; Some (reduce_to_v remainder2)
; Some (reduce_to_v quotient_bound01)
; Some (reduce_to_v quotient_bound2)
; Some (reduce_to_v product1_lo)
; Some (reduce_to_v product1_hi_0)
; None
; None
; None
; None
; None
; None
; None
; None
|]
in
add_row sys vars_curr ForeignFieldMul [||] ;
add_row sys vars_next Zero [||]
| Plonk_constraint.T
(Rot64
{ (* Current row *) word
; rotated
; excess
; bound_limb0
; bound_limb1
; bound_limb2
; bound_limb3
; bound_crumb0
; bound_crumb1
; bound_crumb2
; bound_crumb3
; bound_crumb4
; bound_crumb5
; bound_crumb6
; bound_crumb7
; (* Next row *) shifted
; shifted_limb0
; shifted_limb1
; shifted_limb2
; shifted_limb3
; shifted_crumb0
; shifted_crumb1
; shifted_crumb2
; shifted_crumb3
; shifted_crumb4
; shifted_crumb5
; shifted_crumb6
; shifted_crumb7
; (* Coefficients *) two_to_rot
} ) ->
// ! | Gate | ` Rot64 ` | ` RangeCheck0 ` |
// ! | ------ | ------------------- | ---------------- |
// ! | Column | ` Curr ` | ` Next ` |
// ! | ------ | ------------------- | ---------------- |
// ! | 0 | copy ` word ` |`shifted ` |
// ! | 1 | copy ` rotated ` | 0 |
// ! | 2 | ` excess ` | 0 |
// ! | 3 | ` bound_limb0 ` | ` shifted_limb0 ` |
// ! | 4 | ` bound_limb1 ` | ` shifted_limb1 ` |
// ! | 5 | ` bound_limb2 ` | ` shifted_limb2 ` |
// ! | 6 | ` bound_limb3 ` | ` shifted_limb3 ` |
// ! | 7 | ` bound_crumb0 ` | ` shifted_crumb0 ` |
// ! | 8 | ` bound_crumb1 ` | ` shifted_crumb1 ` |
// ! | 9 | ` bound_crumb2 ` | ` shifted_crumb2 ` |
// ! | 10 | ` bound_crumb3 ` | ` shifted_crumb3 ` |
// ! | 11 | ` bound_crumb4 ` | ` shifted_crumb4 ` |
// ! | 12 | ` bound_crumb5 ` | ` shifted_crumb5 ` |
// ! | 13 | ` bound_crumb6 ` | ` shifted_crumb6 ` |
// ! | 14 | ` bound_crumb7 ` | ` shifted_crumb7 ` |
//! | Gate | `Rot64` | `RangeCheck0` |
//! | ------ | ------------------- | ---------------- |
//! | Column | `Curr` | `Next` |
//! | ------ | ------------------- | ---------------- |
//! | 0 | copy `word` |`shifted` |
//! | 1 | copy `rotated` | 0 |
//! | 2 | `excess` | 0 |
//! | 3 | `bound_limb0` | `shifted_limb0` |
//! | 4 | `bound_limb1` | `shifted_limb1` |
//! | 5 | `bound_limb2` | `shifted_limb2` |
//! | 6 | `bound_limb3` | `shifted_limb3` |
//! | 7 | `bound_crumb0` | `shifted_crumb0` |
//! | 8 | `bound_crumb1` | `shifted_crumb1` |
//! | 9 | `bound_crumb2` | `shifted_crumb2` |
//! | 10 | `bound_crumb3` | `shifted_crumb3` |
//! | 11 | `bound_crumb4` | `shifted_crumb4` |
//! | 12 | `bound_crumb5` | `shifted_crumb5` |
//! | 13 | `bound_crumb6` | `shifted_crumb6` |
//! | 14 | `bound_crumb7` | `shifted_crumb7` |
*)
let vars_curr =
[| (* Current row *) Some (reduce_to_v word)
; Some (reduce_to_v rotated)
; Some (reduce_to_v excess)
; Some (reduce_to_v bound_limb0)
; Some (reduce_to_v bound_limb1)
; Some (reduce_to_v bound_limb2)
; Some (reduce_to_v bound_limb3)
; Some (reduce_to_v bound_crumb0)
; Some (reduce_to_v bound_crumb1)
; Some (reduce_to_v bound_crumb2)
; Some (reduce_to_v bound_crumb3)
; Some (reduce_to_v bound_crumb4)
; Some (reduce_to_v bound_crumb5)
; Some (reduce_to_v bound_crumb6)
; Some (reduce_to_v bound_crumb7)
|]
in
let vars_next =
[| (* Next row *) Some (reduce_to_v shifted)
; None
; None
; Some (reduce_to_v shifted_limb0)
; Some (reduce_to_v shifted_limb1)
; Some (reduce_to_v shifted_limb2)
; Some (reduce_to_v shifted_limb3)
; Some (reduce_to_v shifted_crumb0)
; Some (reduce_to_v shifted_crumb1)
; Some (reduce_to_v shifted_crumb2)
; Some (reduce_to_v shifted_crumb3)
; Some (reduce_to_v shifted_crumb4)
; Some (reduce_to_v shifted_crumb5)
; Some (reduce_to_v shifted_crumb6)
; Some (reduce_to_v shifted_crumb7)
|]
in
let compact = Fp.zero in
add_row sys vars_curr Rot64 [| two_to_rot |] ;
add_row sys vars_next RangeCheck0
[| compact (* Standard 3-limb mode *) |]
| Plonk_constraint.T (Raw { kind; values; coeffs }) ->
let values =
Array.init 15 ~f:(fun i ->
(* Insert [None] if the index is beyond the end of the [values]
array.
*)
Option.try_with (fun () -> reduce_to_v values.(i)) )
in
add_row sys values kind coeffs
| constr ->
failwithf "Unhandled constraint %s"
Obj.(Extension_constructor.name (Extension_constructor.of_val constr))
()
end
| null | https://raw.githubusercontent.com/MinaProtocol/mina/a4e030878c166014f8731c356b48ce362abd6f90/src/lib/crypto/kimchi_backend/common/plonk_constraint_system.ml | ocaml | TODO: remove these openings
* A gate interface, parameterized by a field.
* A row indexing in a constraint system.
* A position represents the position of a cell in the constraint system.
* A position is a row and a column.
* Generates a full row of positions that each points to itself.
* Given a number of columns,
append enough column wires to get an entire row.
The wire appended will simply point to themselves,
so as to not take part in the permutation argument.
* Converts an array of [Constants.columns] to [Constants.permutation_cols].
This is useful to truncate arrays of cells to the ones that only matter for the permutation argument.
* A gate.
TODO: split kind/coeffs from row/wired_to
* A gate/row/constraint consists of a type (kind), a row, the other cells its columns/cells are connected to (wired_to), and the selector polynomial associated with the gate.
* Applies a function [f] to the [row] of [t] and all the rows of its [wired_to].
{ wire with row = f row }
* The PLONK constraints.
MSBs
LSBs
Coefficients
Current row
LSBs
Next row
Current row
Next row
Current row
Next row
* map t
Current row
Next row
Current row
Next row
Current row
Next row
Current row
Next row
Current row
Next row
Coefficients
Current row
Next row
Coefficients
* [eval (module F) get_variable gate] checks that [gate]'s polynomial is
satisfied by the assignments given by [get_variable].
Warning: currently only implemented for the [Basic] gate.
* Variables linking uses of the same data between different gates.
Every internal variable is computable from a finite list of external
variables and internal variables.
Currently, in fact, every internal variable is a linear combination of
external variables and previously generated internal variables.
* An external variable (generated by snarky, via [exists]).
* Keeps track of a circuit (which is a list of gates)
while it is being written.
* A circuit still being written.
* Once finalized, a circuit is represented as a digest
and a list of gates that corresponds to the circuit.
* The constraint system.
Map of cells that share the same value (enforced by to the permutation).
How to compute each internal variable (as a linear combination of other variables).
The variables that hold each witness value for each row, in reverse order.
A circuit is described by a series of gates.
A gate is finalized once [finalize_and_get_gates] is called.
The finalized tag contains the digest of the circuit.
The row to use the next time we add a constraint.
The number of previous recursion challenges.
Whatever is not public input.
V.t's corresponding to constant values. We reuse them so we don't need to
use a fresh generic constraint each time to create a constant.
The [equivalence_classes] field keeps track of the positions which must be
enforced to be equivalent due to the fact that they correspond to the same V.t value.
I.e., positions that are different usages of the same [V.t].
We use a union-find data structure to track equalities that a constraint system wants
enforced *between* [V.t] values. Then, at the end, for all [V.t]s that have been unioned
together, we combine their equivalence classes in the [equivalence_classes] table into
a single equivalence class, so that the permutation argument enforces these desired equalities
as well.
TODO: shouldn't that Make create something bounded by a signature? As we know what a back end should be? Check where this is used
TODO: glossary of terms in this file (terms, reducing, feeding) + module doc
* ?
* Compute the witness, given the constraint system `sys`
and a function that converts the indexed secret inputs to their concrete values.
Public input
Compute an internal variable associated value.
Update the witness table with the value of the variables from each row.
Return the witness.
* Creates an internal variable and assigns it the value lc and constant.
Initializes a constraint system.
* Returns the number of auxiliary inputs.
* Returns the number of public inputs.
* Returns the number of previous challenges.
Non-public part of the witness.
* Sets the number of public-input. It must and can only be called once.
* Sets the number of previous challenges. It must and can only be called once.
* Adds {row; col} to the system's wiring under a specific key.
A key is an external or internal variable.
The row must be given relative to the start of the circuit
(so at the start of the public-input rows).
* Same as wire', except that the row must be given relatively to the end of the public-input rows.
* Adds a row/gate/constraint to a constraint system `sys`.
Add to gates.
Increment row.
Add to row.
Create rows for public input.
Process public gates.
concatenate and convert to absolute rows
convert all the gates into our Gates.t Rust vector type
compute the circuit's digest
drop the gates, we don't need them anymore
return the gates
* Calls [finalize_and_get_gates] and ignores the result.
Returns a hash of the circuit.
* Converts a [Cvar.t] to a `(terms, terms_length, has_constant)`.
if `has_constant` is set, then terms start with a constant term in the form of (c, 0).
if the queue of generic gate is empty, queue this
otherwise empty the queue and create the row
just adding constrained variables without values
TODO: this should be rewritten to be tail-optimized
res = ls * lx + c
Could be here
reduce the terms, then add the constant
res = ls * lx + rs * rx + c
Could be here
* Adds a constraint to the constraint system.
reduce any [Cvar.t] to a single internal variable
s * x - sx = 0
(sl * xl)^2 = so * xo
sl^2 * xl * xl - so * xo = 0
TODO: it's hard to read the array of selector values, name them!
sl^2 = so * xo
s1 x1 * s2 x2 = s3 x3
- s1 s2 (x1 x2) + s3 x3 = 0
s1 x1 * s2 = s3 x3
-x + x * x = 0
s1 x1 - s2 x2 = 0
s1 * x1 = s2
x1 = s2 / s1
s1 = s2 * x2
x2 = s1 / s2
TODO: This is sub-optimal
No need to have a real term.
TODO: Figure this out later.
reduce the state
add_last_row adds the last row containing the output
Reduce state.
Add round function.
Add round function.
MSBs
LSBs
Current row
Next row
Current row
MSBs
LSBs
Next row
Current row
Current row
Next row
Current row
Next row
Current row
Next row
Coefficients
Current row
Next row
Standard 3-limb mode
Insert [None] if the index is beyond the end of the [values]
array.
| open Sponge
open Unsigned.Size_t
TODO : open Core here instead of opening it multiple times below
module Kimchi_gate_type = struct
to allow deriving sexp
type t = Kimchi_types.gate_type =
| Zero
| Generic
| Poseidon
| CompleteAdd
| VarBaseMul
| EndoMul
| EndoMulScalar
| Lookup
| CairoClaim
| CairoInstruction
| CairoFlags
| CairoTransition
| RangeCheck0
| RangeCheck1
| ForeignFieldAdd
| ForeignFieldMul
| Xor16
| Rot64
[@@deriving sexp]
end
module type Gate_vector_intf = sig
open Unsigned
type field
type t
val create : unit -> t
val add : t -> field Kimchi_types.circuit_gate -> unit
val get : t -> int -> field Kimchi_types.circuit_gate
val len : t -> int
val digest : int -> t -> bytes
val to_json : int -> t -> string
end
module Row = struct
open Core_kernel
* Either a public input row ,
or a non - public input row that starts at index 0 .
or a non-public input row that starts at index 0.
*)
type t = Public_input of int | After_public_input of int
[@@deriving hash, sexp, compare]
let to_absolute ~public_input_size = function
| Public_input i ->
i
| After_public_input i ->
the first i rows are public - input rows
i + public_input_size
end
TODO : rename module Position to Permutation / Wiring ?
module Position = struct
open Core_kernel
type 'row t = { row : 'row; col : int } [@@deriving hash, sexp, compare]
let create_cols (row : 'row) : _ t array =
Array.init Constants.permutation_cols ~f:(fun i -> { row; col = i })
let append_cols (row : 'row) (cols : _ t array) : _ t array =
let padding_offset = Array.length cols in
assert (padding_offset <= Constants.permutation_cols) ;
let padding_len = Constants.permutation_cols - padding_offset in
let padding =
Array.init padding_len ~f:(fun i -> { row; col = i + padding_offset })
in
Array.append cols padding
let cols_to_perms cols = Array.slice cols 0 Constants.permutation_cols
* Converts a [ Position.t ] into the Rust - compatible type [ Kimchi_types.wire ] .
*)
let to_rust_wire { row; col } : Kimchi_types.wire = { row; col }
end
module Gate_spec = struct
open Core_kernel
type ('row, 'f) t =
{ kind : Kimchi_gate_type.t
; wired_to : 'row Position.t array
; coeffs : 'f array
}
[@@deriving sexp_of]
let map_rows (t : (_, _) t) ~f : (_, _) t =
let wired_to =
Array.map
~f:(fun (pos : _ Position.t) -> { pos with row = f pos.row })
t.wired_to
in
{ t with wired_to }
TODO : just send the array to directly
let to_rust_gate { kind; wired_to; coeffs } : _ Kimchi_types.circuit_gate =
let typ = kind in
let wired_to = Array.map ~f:Position.to_rust_wire wired_to in
let wires =
( wired_to.(0)
, wired_to.(1)
, wired_to.(2)
, wired_to.(3)
, wired_to.(4)
, wired_to.(5)
, wired_to.(6) )
in
{ typ; wires; coeffs }
end
module Plonk_constraint = struct
open Core_kernel
* A PLONK constraint ( or gate ) can be [ Basic ] , [ ] , [ ] , [ EC_scale ] , [ EC_endoscale ] , [ EC_endoscalar ] , [ RangeCheck0 ] , [ RangeCheck1 ] , [ Xor ]
module T = struct
type ('v, 'f) t =
| Basic of { l : 'f * 'v; r : 'f * 'v; o : 'f * 'v; m : 'f; c : 'f }
* the state is an array of states ( and states are arrays of size 3 ) .
| Poseidon of { state : 'v array array }
| EC_add_complete of
{ p1 : 'v * 'v
; p2 : 'v * 'v
; p3 : 'v * 'v
; inf : 'v
; same_x : 'v
; slope : 'v
; inf_z : 'v
; x21_inv : 'v
}
| EC_scale of { state : 'v Scale_round.t array }
| EC_endoscale of
{ state : 'v Endoscale_round.t array; xs : 'v; ys : 'v; n_acc : 'v }
| EC_endoscalar of { state : 'v Endoscale_scalar_round.t array }
| RangeCheck0 of
Value to constrain to 88 - bits
vpX are 12 - bit plookup chunks
; v0p2 : 'v
; v0p3 : 'v
; v0p4 : 'v
; v0p5 : 'v
vcX are 2 - bit crumbs
; v0c1 : 'v
; v0c2 : 'v
; v0c3 : 'v
; v0c4 : 'v
; v0c5 : 'v
; v0c6 : 'v
compact : 'f
Limbs mode coefficient : 0 ( standard 3 - limb ) or 1 ( compact 2 - limb )
}
| RangeCheck1 of
Value to constrain to 88 - bits
Optional value used in compact 2 - limb mode
MSBs , 2 - bit crumb
vpX are 12 - bit plookup chunks
; v2p1 : 'v
; v2p2 : 'v
; v2p3 : 'v
vcX are 2 - bit crumbs
; v2c2 : 'v
; v2c3 : 'v
; v2c4 : 'v
; v2c5 : 'v
; v2c6 : 'v
; v2c7 : 'v
; v2c10 : 'v
; v2c11 : 'v
; v0p0 : 'v
; v0p1 : 'v
; v1p0 : 'v
; v1p1 : 'v
; v2c12 : 'v
; v2c13 : 'v
; v2c14 : 'v
; v2c15 : 'v
; v2c16 : 'v
; v2c17 : 'v
; v2c18 : 'v
; v2c19 : 'v
}
| Xor of
{ in1 : 'v
; in2 : 'v
; out : 'v
; in1_0 : 'v
; in1_1 : 'v
; in1_2 : 'v
; in1_3 : 'v
; in2_0 : 'v
; in2_1 : 'v
; in2_2 : 'v
; in2_3 : 'v
; out_0 : 'v
; out_1 : 'v
; out_2 : 'v
; out_3 : 'v
}
| ForeignFieldAdd of
{ left_input_lo : 'v
; left_input_mi : 'v
; left_input_hi : 'v
; right_input_lo : 'v
; right_input_mi : 'v
; right_input_hi : 'v
; field_overflow : 'v
; carry : 'v
}
| ForeignFieldMul of
left_input0 : 'v
; left_input1 : 'v
; left_input2 : 'v
; right_input0 : 'v
; right_input1 : 'v
; right_input2 : 'v
; carry1_lo : 'v
; carry1_hi : 'v
; carry0 : 'v
; quotient0 : 'v
; quotient1 : 'v
; quotient2 : 'v
; quotient_bound_carry : 'v
; product1_hi_1 : 'v
; remainder1 : 'v
; remainder2 : 'v
; quotient_bound01 : 'v
; quotient_bound2 : 'v
; product1_lo : 'v
; product1_hi_0 : 'v
}
| Rot64 of
word : 'v
; rotated : 'v
; excess : 'v
; bound_limb0 : 'v
; bound_limb1 : 'v
; bound_limb2 : 'v
; bound_limb3 : 'v
; bound_crumb0 : 'v
; bound_crumb1 : 'v
; bound_crumb2 : 'v
; bound_crumb3 : 'v
; bound_crumb4 : 'v
; bound_crumb5 : 'v
; bound_crumb6 : 'v
; bound_crumb7 : 'v
; shifted_limb0 : 'v
; shifted_limb1 : 'v
; shifted_limb2 : 'v
; shifted_limb3 : 'v
; shifted_crumb0 : 'v
; shifted_crumb1 : 'v
; shifted_crumb2 : 'v
; shifted_crumb3 : 'v
; shifted_crumb4 : 'v
; shifted_crumb5 : 'v
; shifted_crumb6 : 'v
; shifted_crumb7 : 'v
Rotation scalar 2^rot
}
| Raw of
{ kind : Kimchi_gate_type.t; values : 'v array; coeffs : 'f array }
[@@deriving sexp]
let map (type a b f) (t : (a, f) t) ~(f : a -> b) =
let fp (x, y) = (f x, f y) in
match t with
| Basic { l; r; o; m; c } ->
let p (x, y) = (x, f y) in
Basic { l = p l; r = p r; o = p o; m; c }
| Poseidon { state } ->
Poseidon { state = Array.map ~f:(fun x -> Array.map ~f x) state }
| EC_add_complete { p1; p2; p3; inf; same_x; slope; inf_z; x21_inv } ->
EC_add_complete
{ p1 = fp p1
; p2 = fp p2
; p3 = fp p3
; inf = f inf
; same_x = f same_x
; slope = f slope
; inf_z = f inf_z
; x21_inv = f x21_inv
}
| EC_scale { state } ->
EC_scale
{ state = Array.map ~f:(fun x -> Scale_round.map ~f x) state }
| EC_endoscale { state; xs; ys; n_acc } ->
EC_endoscale
{ state = Array.map ~f:(fun x -> Endoscale_round.map ~f x) state
; xs = f xs
; ys = f ys
; n_acc = f n_acc
}
| EC_endoscalar { state } ->
EC_endoscalar
{ state =
Array.map ~f:(fun x -> Endoscale_scalar_round.map ~f x) state
}
| RangeCheck0
{ v0
; v0p0
; v0p1
; v0p2
; v0p3
; v0p4
; v0p5
; v0c0
; v0c1
; v0c2
; v0c3
; v0c4
; v0c5
; v0c6
; v0c7
; compact
} ->
RangeCheck0
{ v0 = f v0
; v0p0 = f v0p0
; v0p1 = f v0p1
; v0p2 = f v0p2
; v0p3 = f v0p3
; v0p4 = f v0p4
; v0p5 = f v0p5
; v0c0 = f v0c0
; v0c1 = f v0c1
; v0c2 = f v0c2
; v0c3 = f v0c3
; v0c4 = f v0c4
; v0c5 = f v0c5
; v0c6 = f v0c6
; v0c7 = f v0c7
; compact
}
| RangeCheck1
; v12
; v2c0
; v2p0
; v2p1
; v2p2
; v2p3
; v2c1
; v2c2
; v2c3
; v2c4
; v2c5
; v2c6
; v2c7
; v2c8
; v2c10
; v2c11
; v0p0
; v0p1
; v1p0
; v1p1
; v2c12
; v2c13
; v2c14
; v2c15
; v2c16
; v2c17
; v2c18
; v2c19
} ->
RangeCheck1
; v12 = f v12
; v2c0 = f v2c0
; v2p0 = f v2p0
; v2p1 = f v2p1
; v2p2 = f v2p2
; v2p3 = f v2p3
; v2c1 = f v2c1
; v2c2 = f v2c2
; v2c3 = f v2c3
; v2c4 = f v2c4
; v2c5 = f v2c5
; v2c6 = f v2c6
; v2c7 = f v2c7
; v2c8 = f v2c8
; v2c10 = f v2c10
; v2c11 = f v2c11
; v0p0 = f v0p0
; v0p1 = f v0p1
; v1p0 = f v1p0
; v1p1 = f v1p1
; v2c12 = f v2c12
; v2c13 = f v2c13
; v2c14 = f v2c14
; v2c15 = f v2c15
; v2c16 = f v2c16
; v2c17 = f v2c17
; v2c18 = f v2c18
; v2c19 = f v2c19
}
| Xor
{ in1
; in2
; out
; in1_0
; in1_1
; in1_2
; in1_3
; in2_0
; in2_1
; in2_2
; in2_3
; out_0
; out_1
; out_2
; out_3
} ->
Xor
{ in1 = f in1
; in2 = f in2
; out = f out
; in1_0 = f in1_0
; in1_1 = f in1_1
; in1_2 = f in1_2
; in1_3 = f in1_3
; in2_0 = f in2_0
; in2_1 = f in2_1
; in2_2 = f in2_2
; in2_3 = f in2_3
; out_0 = f out_0
; out_1 = f out_1
; out_2 = f out_2
; out_3 = f out_3
}
| ForeignFieldAdd
{ left_input_lo
; left_input_mi
; left_input_hi
; right_input_lo
; right_input_mi
; right_input_hi
; field_overflow
; carry
} ->
ForeignFieldAdd
{ left_input_lo = f left_input_lo
; left_input_mi = f left_input_mi
; left_input_hi = f left_input_hi
; right_input_lo = f right_input_lo
; right_input_mi = f right_input_mi
; right_input_hi = f right_input_hi
; field_overflow = f field_overflow
; carry = f carry
}
| ForeignFieldMul
; left_input1
; left_input2
; right_input0
; right_input1
; right_input2
; carry1_lo
; carry1_hi
; carry0
; quotient0
; quotient1
; quotient2
; quotient_bound_carry
; product1_hi_1
; remainder1
; remainder2
; quotient_bound01
; quotient_bound2
; product1_lo
; product1_hi_0
} ->
ForeignFieldMul
; left_input1 = f left_input1
; left_input2 = f left_input2
; right_input0 = f right_input0
; right_input1 = f right_input1
; right_input2 = f right_input2
; carry1_lo = f carry1_lo
; carry1_hi = f carry1_hi
; carry0 = f carry0
; quotient0 = f quotient0
; quotient1 = f quotient1
; quotient2 = f quotient2
; quotient_bound_carry = f quotient_bound_carry
; product1_hi_1 = f product1_hi_1
; remainder1 = f remainder1
; remainder2 = f remainder2
; quotient_bound01 = f quotient_bound01
; quotient_bound2 = f quotient_bound2
; product1_lo = f product1_lo
; product1_hi_0 = f product1_hi_0
}
| Rot64
; rotated
; excess
; bound_limb0
; bound_limb1
; bound_limb2
; bound_limb3
; bound_crumb0
; bound_crumb1
; bound_crumb2
; bound_crumb3
; bound_crumb4
; bound_crumb5
; bound_crumb6
; bound_crumb7
; shifted_limb0
; shifted_limb1
; shifted_limb2
; shifted_limb3
; shifted_crumb0
; shifted_crumb1
; shifted_crumb2
; shifted_crumb3
; shifted_crumb4
; shifted_crumb5
; shifted_crumb6
; shifted_crumb7
} ->
Rot64
; rotated = f rotated
; excess = f excess
; bound_limb0 = f bound_limb0
; bound_limb1 = f bound_limb1
; bound_limb2 = f bound_limb2
; bound_limb3 = f bound_limb3
; bound_crumb0 = f bound_crumb0
; bound_crumb1 = f bound_crumb1
; bound_crumb2 = f bound_crumb2
; bound_crumb3 = f bound_crumb3
; bound_crumb4 = f bound_crumb4
; bound_crumb5 = f bound_crumb5
; bound_crumb6 = f bound_crumb6
; bound_crumb7 = f bound_crumb7
; shifted_limb0 = f shifted_limb0
; shifted_limb1 = f shifted_limb1
; shifted_limb2 = f shifted_limb2
; shifted_limb3 = f shifted_limb3
; shifted_crumb0 = f shifted_crumb0
; shifted_crumb1 = f shifted_crumb1
; shifted_crumb2 = f shifted_crumb2
; shifted_crumb3 = f shifted_crumb3
; shifted_crumb4 = f shifted_crumb4
; shifted_crumb5 = f shifted_crumb5
; shifted_crumb6 = f shifted_crumb6
; shifted_crumb7 = f shifted_crumb7
}
| Raw { kind; values; coeffs } ->
Raw { kind; values = Array.map ~f values; coeffs }
let eval (type v f)
(module F : Snarky_backendless.Field_intf.S with type t = f)
(eval_one : v -> f) (t : (v, f) t) =
match t with
cl * vl + cr * vr + co * vo + m * vl*vr + c = 0
| Basic { l = cl, vl; r = cr, vr; o = co, vo; m; c } ->
let vl = eval_one vl in
let vr = eval_one vr in
let vo = eval_one vo in
let open F in
let res =
List.reduce_exn ~f:add
[ mul cl vl; mul cr vr; mul co vo; mul m (mul vl vr); c ]
in
if not (equal zero res) then (
eprintf
!"%{sexp:t} * %{sexp:t}\n\
+ %{sexp:t} * %{sexp:t}\n\
+ %{sexp:t} * %{sexp:t}\n\
+ %{sexp:t} * %{sexp:t}\n\
+ %{sexp:t}\n\
= %{sexp:t}%!"
cl vl cr vr co vo m (mul vl vr) c res ;
false )
else true
| _ ->
true
end
include T
Adds our constraint enum to the list of constraints handled by .
include Snarky_backendless.Constraint.Add_kind (T)
end
module Internal_var = Core_kernel.Unique_id.Int ()
module V = struct
open Core_kernel
module T = struct
type t =
| External of int
| Internal of Internal_var.t
* An internal variable is generated to hold an intermediate value
( e.g. , in reducing linear combinations to single PLONK positions ) .
(e.g., in reducing linear combinations to single PLONK positions).
*)
[@@deriving compare, hash, sexp]
end
include T
include Comparable.Make (T)
include Hashable.Make (T)
end
type ('f, 'rust_gates) circuit =
| Unfinalized_rev of (unit, 'f) Gate_spec.t list
| Compiled of Core_kernel.Md5.t * 'rust_gates
type ('f, 'rust_gates) t =
equivalence_classes : Row.t Position.t list V.Table.t
internal_vars : (('f * V.t) list * 'f option) Internal_var.Table.t
mutable rows_rev : V.t option array list
mutable gates : ('f, 'rust_gates) circuit
mutable next_row : int
The size of the public input ( which fills the first rows of our constraint system .
public_input_size : int Core_kernel.Set_once.t
prev_challenges : int Core_kernel.Set_once.t
mutable auxiliary_input_size : int
Queue ( of size 1 ) of generic gate .
mutable pending_generic_gate :
(V.t option * V.t option * V.t option * 'f array) option
cached_constants : ('f, V.t) Core_kernel.Hashtbl.t
; union_finds : V.t Core_kernel.Union_find.t V.Table.t
}
let get_public_input_size sys = sys.public_input_size
let get_rows_len sys = List.length sys.rows_rev
let get_prev_challenges sys = sys.prev_challenges
let set_prev_challenges sys challenges =
Core_kernel.Set_once.set_exn sys.prev_challenges [%here] challenges
TODO : rename to F or Field
module Make
(Fp : Field.S)
We create a type for gate vector , instead of using ` Gate.t list ` . If we did , we would have to convert it to a ` Gate.t array ` to pass it across the FFI boundary , where then it gets converted to a ` Vec < Gate > ` ; it 's more efficient to just create the ` Vec < Gate > ` directly .
*)
(Gates : Gate_vector_intf with type field := Fp.t)
(Params : sig
val params : Fp.t Params.t
end) : sig
open Core_kernel
type nonrec t = (Fp.t, Gates.t) t
val create : unit -> t
val get_public_input_size : t -> int Set_once.t
val get_primary_input_size : t -> int
val set_primary_input_size : t -> int -> unit
val get_auxiliary_input_size : t -> int
val set_auxiliary_input_size : t -> int -> unit
val get_prev_challenges : t -> int option
val set_prev_challenges : t -> int -> unit
val get_rows_len : t -> int
val next_row : t -> int
val add_constraint :
?label:string
-> t
-> ( Fp.t Snarky_backendless.Cvar.t
, Fp.t )
Snarky_backendless.Constraint.basic
-> unit
val compute_witness : t -> (int -> Fp.t) -> Fp.t array array
val finalize : t -> unit
val finalize_and_get_gates : t -> Gates.t
val num_constraints : t -> int
val digest : t -> Md5.t
val to_json : t -> string
end = struct
open Core_kernel
open Pickles_types
type nonrec t = (Fp.t, Gates.t) t
* Converts the set of permutations ( equivalence_classes ) to
a hash table that maps each position to the next one .
For example , if one of the equivalence class is [ pos1 , pos3 , pos7 ] ,
the function will return a hashtable that maps pos1 to pos3 ,
pos3 to pos7 , and pos7 to .
a hash table that maps each position to the next one.
For example, if one of the equivalence class is [pos1, pos3, pos7],
the function will return a hashtable that maps pos1 to pos3,
pos3 to pos7, and pos7 to pos1.
*)
let equivalence_classes_to_hashtbl sys =
let module Relative_position = struct
module T = struct
type t = Row.t Position.t [@@deriving hash, sexp, compare]
end
include T
include Core_kernel.Hashable.Make (T)
end in
let equivalence_classes = V.Table.create () in
Hashtbl.iteri sys.equivalence_classes ~f:(fun ~key ~data ->
let u = Hashtbl.find_exn sys.union_finds key in
Hashtbl.update equivalence_classes (Union_find.get u) ~f:(function
| None ->
Relative_position.Hash_set.of_list data
| Some ps ->
List.iter ~f:(Hash_set.add ps) data ;
ps ) ) ;
let res = Relative_position.Table.create () in
Hashtbl.iter equivalence_classes ~f:(fun ps ->
let rotate_left = function [] -> [] | x :: xs -> xs @ [ x ] in
let ps = Hash_set.to_list ps in
List.iter2_exn ps (rotate_left ps) ~f:(fun input output ->
Hashtbl.add_exn res ~key:input ~data:output ) ) ;
res
let compute_witness (sys : t) (external_values : int -> Fp.t) :
Fp.t array array =
let internal_values : Fp.t Internal_var.Table.t =
Internal_var.Table.create ()
in
let public_input_size = Set_once.get_exn sys.public_input_size [%here] in
let num_rows = public_input_size + sys.next_row in
let res =
Array.init Constants.columns ~f:(fun _ ->
Array.create ~len:num_rows Fp.zero )
in
for i = 0 to public_input_size - 1 do
res.(0).(i) <- external_values (i + 1)
done ;
let find t k =
match Hashtbl.find t k with
| None ->
failwithf !"Could not find %{sexp:Internal_var.t}\n%!" k ()
| Some x ->
x
in
let compute ((lc, c) : (Fp.t * V.t) list * Fp.t option) =
List.fold lc ~init:(Option.value c ~default:Fp.zero) ~f:(fun acc (s, x) ->
let x =
match x with
| External x ->
external_values x
| Internal x ->
find internal_values x
in
Fp.(acc + (s * x)) )
in
List.iteri (List.rev sys.rows_rev) ~f:(fun i_after_input cols ->
let row_idx = i_after_input + public_input_size in
Array.iteri cols ~f:(fun col_idx var ->
match var with
| None ->
()
| Some (External var) ->
res.(col_idx).(row_idx) <- external_values var
| Some (Internal var) ->
let lc = find sys.internal_vars var in
let value = compute lc in
res.(col_idx).(row_idx) <- value ;
Hashtbl.set internal_values ~key:var ~data:value ) ) ;
res
let union_find sys v =
Hashtbl.find_or_add sys.union_finds v ~default:(fun () ->
Union_find.create v )
let create_internal ?constant sys lc : V.t =
let v = Internal_var.create () in
ignore (union_find sys (Internal v) : _ Union_find.t) ;
Hashtbl.add_exn sys.internal_vars ~key:v ~data:(lc, constant) ;
V.Internal v
let create () : t =
{ public_input_size = Set_once.create ()
; prev_challenges = Set_once.create ()
; internal_vars = Internal_var.Table.create ()
Gates.create ( )
; rows_rev = []
; next_row = 0
; equivalence_classes = V.Table.create ()
; auxiliary_input_size = 0
; pending_generic_gate = None
; cached_constants = Hashtbl.create (module Fp)
; union_finds = V.Table.create ()
}
let get_auxiliary_input_size t = t.auxiliary_input_size
let get_primary_input_size t = Set_once.get_exn t.public_input_size [%here]
let get_prev_challenges t = Set_once.get t.prev_challenges
let set_auxiliary_input_size t x = t.auxiliary_input_size <- x
let set_primary_input_size (sys : t) num_pub_inputs =
Set_once.set_exn sys.public_input_size [%here] num_pub_inputs
let set_prev_challenges (sys : t) num_prev_challenges =
Set_once.set_exn sys.prev_challenges [%here] num_prev_challenges
let get_public_input_size (sys : t) = get_public_input_size sys
let get_rows_len (sys : t) = get_rows_len sys
let next_row (sys : t) = sys.next_row
let wire' sys key row (col : int) =
ignore (union_find sys key : V.t Union_find.t) ;
V.Table.add_multi sys.equivalence_classes ~key ~data:{ row; col }
TODO : rename to wire_abs and wire_rel ? or wire_public and ? or force a single use function that takes a Row.t ?
let wire sys key row col = wire' sys key (Row.After_public_input row) col
let add_row sys (vars : V.t option array) kind coeffs =
match sys.gates with
| Compiled _ ->
failwith "add_row called on finalized constraint system"
| Unfinalized_rev gates ->
As we 're adding a row , we 're adding new cells .
If these cells ( the first 7 ) contain variables ,
make sure that they are wired
If these cells (the first 7) contain variables,
make sure that they are wired
*)
let num_vars = min Constants.permutation_cols (Array.length vars) in
let vars_for_perm = Array.slice vars 0 num_vars in
Array.iteri vars_for_perm ~f:(fun col x ->
Option.iter x ~f:(fun x -> wire sys x sys.next_row col) ) ;
let open Position in
sys.gates <- Unfinalized_rev ({ kind; wired_to = [||]; coeffs } :: gates) ;
sys.next_row <- sys.next_row + 1 ;
sys.rows_rev <- vars :: sys.rows_rev
* Adds zero - knowledgeness to the gates / rows ,
and convert into Rust type [ Gates.t ] .
This can only be called once .
and convert into Rust type [Gates.t].
This can only be called once.
*)
let rec finalize_and_get_gates sys =
match sys with
| { gates = Compiled (_, gates); _ } ->
gates
| { pending_generic_gate = Some (l, r, o, coeffs); _ } ->
Finalize any pending generic constraint first .
add_row sys [| l; r; o |] Generic coeffs ;
sys.pending_generic_gate <- None ;
finalize_and_get_gates sys
| { gates = Unfinalized_rev gates_rev; _ } ->
let rust_gates = Gates.create () in
let public_input_size =
Set_once.get_exn sys.public_input_size [%here]
in
let pub_selectors = [| Fp.one; Fp.zero; Fp.zero; Fp.zero; Fp.zero |] in
let pub_input_gate_specs_rev = ref [] in
for row = 0 to public_input_size - 1 do
let public_var = V.External (row + 1) in
wire' sys public_var (Row.Public_input row) 0 ;
pub_input_gate_specs_rev :=
{ Gate_spec.kind = Generic
; wired_to = [||]
; coeffs = pub_selectors
}
:: !pub_input_gate_specs_rev
done ;
Construct permutation hashmap .
let pos_map = equivalence_classes_to_hashtbl sys in
let permutation (pos : Row.t Position.t) : Row.t Position.t =
Option.value (Hashtbl.find pos_map pos) ~default:pos
in
let update_gate_with_permutation_info (row : Row.t)
(gate : (unit, _) Gate_spec.t) : (Row.t, _) Gate_spec.t =
{ gate with
wired_to =
Array.init Constants.permutation_cols ~f:(fun col ->
permutation { row; col } )
}
in
let public_gates = List.rev !pub_input_gate_specs_rev in
let public_gates =
List.mapi public_gates ~f:(fun absolute_row gate ->
update_gate_with_permutation_info (Row.Public_input absolute_row)
gate )
in
construct all the other gates ( except zero - knowledge rows )
let gates = List.rev gates_rev in
let gates =
List.mapi gates ~f:(fun relative_row gate ->
update_gate_with_permutation_info
(Row.After_public_input relative_row) gate )
in
let to_absolute_row =
Gate_spec.map_rows ~f:(Row.to_absolute ~public_input_size)
in
let add_gates gates =
List.iter gates ~f:(fun g ->
let g = to_absolute_row g in
Gates.add rust_gates (Gate_spec.to_rust_gate g) )
in
add_gates public_gates ;
add_gates gates ;
let digest = Gates.digest public_input_size rust_gates in
let md5_digest = Md5.digest_bytes digest in
sys.gates <- Compiled (md5_digest, rust_gates) ;
rust_gates
let finalize t = ignore (finalize_and_get_gates t : Gates.t)
let num_constraints sys = finalize_and_get_gates sys |> Gates.len
let to_json (sys : t) : string =
let gates = finalize_and_get_gates sys in
let public_input_size = Set_once.get_exn sys.public_input_size [%here] in
Gates.to_json public_input_size gates
let rec digest (sys : t) =
match sys.gates with
| Unfinalized_rev _ ->
finalize sys ; digest sys
| Compiled (digest, _) ->
digest
* Regroup terms that share the same variable .
For example , ( 3 , i2 ) ; ( 2 , i2 ) can be simplified to ( 5 , i2 ) .
It assumes that the list of given terms is sorted ,
and that i0 is the smallest one .
For example , ` i0 = 1 ` and ` terms = [ ( _ , 2 ) ; ( _ , 2 ) ; ( _ ; 4 ) ; ... ] `
Returns ` ( last_scalar , last_variable , terms , terms_length ) `
where terms does not contain the last scalar and last variable observed .
For example, (3, i2) ; (2, i2) can be simplified to (5, i2).
It assumes that the list of given terms is sorted,
and that i0 is the smallest one.
For example, `i0 = 1` and `terms = [(_, 2); (_, 2); (_; 4); ...]`
Returns `(last_scalar, last_variable, terms, terms_length)`
where terms does not contain the last scalar and last variable observed.
*)
let accumulate_terms terms =
List.fold terms ~init:Int.Map.empty ~f:(fun acc (x, i) ->
Map.change acc i ~f:(fun y ->
let res = match y with None -> x | Some y -> Fp.add x y in
if Fp.(equal zero res) then None else Some res ) )
let canonicalize x =
let c, terms =
Fp.(
Snarky_backendless.Cvar.to_constant_and_terms ~add ~mul ~zero:(of_int 0)
~equal ~one:(of_int 1))
x
in
Note : [ ( c , 0 ) ] represents the field element [ c ] multiplied by the 0th
variable , which is held constant as [ Field.one ] .
variable, which is held constant as [Field.one].
*)
let terms = match c with None -> terms | Some c -> (c, 0) :: terms in
let has_constant_term = Option.is_some c in
let terms = accumulate_terms terms in
let terms_list =
Map.fold_right ~init:[] terms ~f:(fun ~key ~data acc ->
(data, key) :: acc )
in
Some (terms_list, Map.length terms, has_constant_term)
* Adds a generic constraint to the constraint system .
As there are two generic gates per row , we queue
every other generic gate .
As there are two generic gates per row, we queue
every other generic gate.
*)
let add_generic_constraint ?l ?r ?o coeffs sys : unit =
match sys.pending_generic_gate with
| None ->
sys.pending_generic_gate <- Some (l, r, o, coeffs)
| Some (l2, r2, o2, coeffs2) ->
let coeffs = Array.append coeffs coeffs2 in
add_row sys [| l; r; o; l2; r2; o2 |] Generic coeffs ;
sys.pending_generic_gate <- None
* Converts a number of scaled additions \sum s_i * x_i
to as many constraints as needed ,
creating temporary variables for each new row / constraint ,
and returning the output variable .
For example , [ ( s1 , x1 ) , ( s2 , x2 ) ] is transformed into :
- internal_var_1 = s1 * x1 + s2 * x2
- return ( 1 , internal_var_1 )
and [ ( s1 , x1 ) , ( s2 , x2 ) , ( s3 , x3 ) ] is transformed into :
- internal_var_1 = s1 * x1 + s2 * x2
- internal_var_2 = 1 * internal_var_1 + s3 * x3
- return ( 1 , internal_var_2 )
It assumes that the list of terms is not empty .
to as many constraints as needed,
creating temporary variables for each new row/constraint,
and returning the output variable.
For example, [(s1, x1), (s2, x2)] is transformed into:
- internal_var_1 = s1 * x1 + s2 * x2
- return (1, internal_var_1)
and [(s1, x1), (s2, x2), (s3, x3)] is transformed into:
- internal_var_1 = s1 * x1 + s2 * x2
- internal_var_2 = 1 * internal_var_1 + s3 * x3
- return (1, internal_var_2)
It assumes that the list of terms is not empty. *)
let completely_reduce sys (terms : (Fp.t * int) list) =
let rec go = function
| [] ->
assert false
| [ (s, x) ] ->
(s, V.External x)
| (ls, lx) :: t ->
let lx = V.External lx in
let rs, rx = go t in
let s1x1_plus_s2x2 = create_internal sys [ (ls, lx); (rs, rx) ] in
add_generic_constraint ~l:lx ~r:rx ~o:s1x1_plus_s2x2
[| ls; rs; Fp.(negate one); Fp.zero; Fp.zero |]
sys ;
(Fp.one, s1x1_plus_s2x2)
in
go terms
* Converts a linear combination of variables into a set of constraints .
It returns the output variable as ( 1 , ` Var res ) ,
unless the output is a constant , in which case it returns ( c , ` Constant ) .
It returns the output variable as (1, `Var res),
unless the output is a constant, in which case it returns (c, `Constant).
*)
let reduce_lincom sys (x : Fp.t Snarky_backendless.Cvar.t) =
let constant, terms =
Fp.(
Snarky_backendless.Cvar.to_constant_and_terms ~add ~mul ~zero:(of_int 0)
~equal ~one:(of_int 1))
x
in
let terms = accumulate_terms terms in
let terms_list =
Map.fold_right ~init:[] terms ~f:(fun ~key ~data acc ->
(data, key) :: acc )
in
match (constant, Map.is_empty terms) with
| Some c, true ->
(c, `Constant)
| None, true ->
(Fp.zero, `Constant)
| _ -> (
match terms_list with
| [] ->
assert false
| [ (ls, lx) ] -> (
match constant with
| None ->
(ls, `Var (V.External lx))
| Some c ->
let res =
create_internal ~constant:c sys [ (ls, External lx) ]
in
add_generic_constraint ~l:(External lx) ~o:res
[| ls; Fp.zero; Fp.(negate one); Fp.zero; c |]
sys ;
(Fp.one, `Var res) )
| (ls, lx) :: tl ->
let rs, rx = completely_reduce sys tl in
let res =
create_internal ?constant sys [ (ls, External lx); (rs, rx) ]
in
add_generic_constraint ~l:(External lx) ~r:rx ~o:res
[| ls
; rs
; Fp.(negate one)
; Fp.zero
; (match constant with Some x -> x | None -> Fp.zero)
|]
sys ;
(Fp.one, `Var res) )
let add_constraint ?label:_ sys
(constr :
( Fp.t Snarky_backendless.Cvar.t
, Fp.t )
Snarky_backendless.Constraint.basic ) =
let red = reduce_lincom sys in
let reduce_to_v (x : Fp.t Snarky_backendless.Cvar.t) : V.t =
match red x with
| s, `Var x ->
if Fp.equal s Fp.one then x
else
let sx = create_internal sys [ (s, x) ] in
add_generic_constraint ~l:x ~o:sx
[| s; Fp.zero; Fp.(negate one); Fp.zero; Fp.zero |]
sys ;
sx
| s, `Constant -> (
match Hashtbl.find sys.cached_constants s with
| Some x ->
x
| None ->
let x = create_internal sys ~constant:s [] in
add_generic_constraint ~l:x
[| Fp.one; Fp.zero; Fp.zero; Fp.zero; Fp.negate s |]
sys ;
Hashtbl.set sys.cached_constants ~key:s ~data:x ;
x )
in
match constr with
| Snarky_backendless.Constraint.Square (v1, v2) -> (
match (red v1, red v2) with
| (sl, `Var xl), (so, `Var xo) ->
add_generic_constraint ~l:xl ~r:xl ~o:xo
[| Fp.zero; Fp.zero; Fp.negate so; Fp.(sl * sl); Fp.zero |]
sys
| (sl, `Var xl), (so, `Constant) ->
add_generic_constraint ~l:xl ~r:xl
[| Fp.zero; Fp.zero; Fp.zero; Fp.(sl * sl); Fp.negate so |]
sys
| (sl, `Constant), (so, `Var xo) ->
add_generic_constraint ~o:xo
[| Fp.zero; Fp.zero; so; Fp.zero; Fp.negate (Fp.square sl) |]
sys
| (sl, `Constant), (so, `Constant) ->
assert (Fp.(equal (square sl) so)) )
| Snarky_backendless.Constraint.R1CS (v1, v2, v3) -> (
match (red v1, red v2, red v3) with
| (s1, `Var x1), (s2, `Var x2), (s3, `Var x3) ->
add_generic_constraint ~l:x1 ~r:x2 ~o:x3
[| Fp.zero; Fp.zero; s3; Fp.(negate s1 * s2); Fp.zero |]
sys
| (s1, `Var x1), (s2, `Var x2), (s3, `Constant) ->
add_generic_constraint ~l:x1 ~r:x2
[| Fp.zero; Fp.zero; Fp.zero; Fp.(s1 * s2); Fp.negate s3 |]
sys
| (s1, `Var x1), (s2, `Constant), (s3, `Var x3) ->
add_generic_constraint ~l:x1 ~o:x3
[| Fp.(s1 * s2); Fp.zero; Fp.negate s3; Fp.zero; Fp.zero |]
sys
| (s1, `Constant), (s2, `Var x2), (s3, `Var x3) ->
add_generic_constraint ~r:x2 ~o:x3
[| Fp.zero; Fp.(s1 * s2); Fp.negate s3; Fp.zero; Fp.zero |]
sys
| (s1, `Var x1), (s2, `Constant), (s3, `Constant) ->
add_generic_constraint ~l:x1
[| Fp.(s1 * s2); Fp.zero; Fp.zero; Fp.zero; Fp.negate s3 |]
sys
| (s1, `Constant), (s2, `Var x2), (s3, `Constant) ->
add_generic_constraint ~r:x2
[| Fp.zero; Fp.(s1 * s2); Fp.zero; Fp.zero; Fp.negate s3 |]
sys
| (s1, `Constant), (s2, `Constant), (s3, `Var x3) ->
add_generic_constraint ~o:x3
[| Fp.zero; Fp.zero; s3; Fp.zero; Fp.(negate s1 * s2) |]
sys
| (s1, `Constant), (s2, `Constant), (s3, `Constant) ->
assert (Fp.(equal s3 Fp.(s1 * s2))) )
| Snarky_backendless.Constraint.Boolean v -> (
let s, x = red v in
match x with
| `Var x ->
add_generic_constraint ~l:x ~r:x
[| Fp.(negate one); Fp.zero; Fp.zero; Fp.one; Fp.zero |]
sys
| `Constant ->
assert (Fp.(equal s (s * s))) )
| Snarky_backendless.Constraint.Equal (v1, v2) -> (
let (s1, x1), (s2, x2) = (red v1, red v2) in
match (x1, x2) with
| `Var x1, `Var x2 ->
if Fp.equal s1 s2 then (
if not (Fp.equal s1 Fp.zero) then
Union_find.union (union_find sys x1) (union_find sys x2) )
not (Fp.equal s1 s2) then
add_generic_constraint ~l:x1 ~r:x2
[| s1; Fp.(negate s2); Fp.zero; Fp.zero; Fp.zero |]
sys
else
add_generic_constraint ~l:x1 ~r:x2
[| s1; Fp.(negate s2); Fp.zero; Fp.zero; Fp.zero |]
sys
| `Var x1, `Constant -> (
let ratio = Fp.(s2 / s1) in
match Hashtbl.find sys.cached_constants ratio with
| Some x2 ->
Union_find.union (union_find sys x1) (union_find sys x2)
| None ->
add_generic_constraint ~l:x1
[| s1; Fp.zero; Fp.zero; Fp.zero; Fp.negate s2 |]
sys ;
Hashtbl.set sys.cached_constants ~key:ratio ~data:x1 )
| `Constant, `Var x2 -> (
let ratio = Fp.(s1 / s2) in
match Hashtbl.find sys.cached_constants ratio with
| Some x1 ->
Union_find.union (union_find sys x1) (union_find sys x2)
| None ->
add_generic_constraint ~r:x2
[| Fp.zero; s2; Fp.zero; Fp.zero; Fp.negate s1 |]
sys ;
Hashtbl.set sys.cached_constants ~key:ratio ~data:x2 )
| `Constant, `Constant ->
assert (Fp.(equal s1 s2)) )
| Plonk_constraint.T (Basic { l; r; o; m; c }) ->
0
= l.s * l.x
+ r.s * r.x
+ o.s * o.x
+ m * ( l.x * r.x )
+ c
=
* l.x '
+ r.s * r.s ' * r.x '
+ o.s * o.s ' * o.x '
+ m * ( l.s ' * l.x ' * r.s ' * r.x ' )
+ c
=
( l.s * l.s ' ) * l.x '
+ ( r.s * r.s ' ) * r.x '
+ ( o.s * o.s ' ) * o.x '
+ ( m * l.s ' * r.s ' ) * l.x ' r.x '
+ c
= l.s * l.x
+ r.s * r.x
+ o.s * o.x
+ m * (l.x * r.x)
+ c
=
l.s * l.s' * l.x'
+ r.s * r.s' * r.x'
+ o.s * o.s' * o.x'
+ m * (l.s' * l.x' * r.s' * r.x')
+ c
=
(l.s * l.s') * l.x'
+ (r.s * r.s') * r.x'
+ (o.s * o.s') * o.x'
+ (m * l.s' * r.s') * l.x' r.x'
+ c
*)
let c = ref c in
let red_pr (s, x) =
match red x with
| s', `Constant ->
c := Fp.add !c Fp.(s * s') ;
(s', None)
| s', `Var x ->
(s', Some (Fp.(s * s'), x))
in
l.s * l.x
+ r.s * r.x
+ o.s * o.x
+ m * ( l.x * r.x )
+ c
=
* l.x '
+ r.s * r.x
+ o.s * o.x
+ m * ( l.x * r.x )
+ c
=
+ r.s * r.x
+ o.s * o.x
+ m * (l.x * r.x)
+ c
=
l.s * l.s' * l.x'
+ r.s * r.x
+ o.s * o.x
+ m * (l.x * r.x)
+ c
=
*)
let l_s', l = red_pr l in
let r_s', r = red_pr r in
let _, o = red_pr o in
let var = Option.map ~f:snd in
let coeff = Option.value_map ~default:Fp.zero ~f:fst in
let m =
match (l, r) with
| Some _, Some _ ->
Fp.(l_s' * r_s' * m)
| _ ->
failwith "Must use non-constant cvar in plonk constraints"
in
add_generic_constraint ?l:(var l) ?r:(var r) ?o:(var o)
[| coeff l; coeff r; coeff o; m; !c |]
sys
| w0 | w1 | w2 | w3 | w4 | w5
state = [ x , x , x ] , [ y , y , y ] , ... ]
i=0 , perm^ i=1 , perm^
state = [ x , x , x ], [ y, y, y ], ... ]
i=0, perm^ i=1, perm^
*)
| Plonk_constraint.T (Poseidon { state }) ->
let reduce_state sys (s : Fp.t Snarky_backendless.Cvar.t array array) :
V.t array array =
Array.map ~f:(Array.map ~f:reduce_to_v) s
in
let state = reduce_state sys state in
add_round_state adds a row that contains 5 rounds of permutation
let add_round_state ~round (s1, s2, s3, s4, s5) =
let vars =
[| Some s1.(0)
; Some s1.(1)
; Some s1.(2)
the last state is in 2nd position
; Some s5.(1)
; Some s5.(2)
; Some s2.(0)
; Some s2.(1)
; Some s2.(2)
; Some s3.(0)
; Some s3.(1)
; Some s3.(2)
; Some s4.(0)
; Some s4.(1)
; Some s4.(2)
|]
in
let coeffs =
[| Params.params.round_constants.(round).(0)
; Params.params.round_constants.(round).(1)
; Params.params.round_constants.(round).(2)
; Params.params.round_constants.(round + 1).(0)
; Params.params.round_constants.(round + 1).(1)
; Params.params.round_constants.(round + 1).(2)
; Params.params.round_constants.(round + 2).(0)
; Params.params.round_constants.(round + 2).(1)
; Params.params.round_constants.(round + 2).(2)
; Params.params.round_constants.(round + 3).(0)
; Params.params.round_constants.(round + 3).(1)
; Params.params.round_constants.(round + 3).(2)
; Params.params.round_constants.(round + 4).(0)
; Params.params.round_constants.(round + 4).(1)
; Params.params.round_constants.(round + 4).(2)
|]
in
add_row sys vars Poseidon coeffs
in
let add_last_row state =
let vars =
[| Some state.(0)
; Some state.(1)
; Some state.(2)
; None
; None
; None
; None
; None
; None
; None
; None
; None
; None
; None
; None
|]
in
add_row sys vars Zero [||]
in
go through the states row by row ( a row contains 5 states )
let rec process_5_states_at_a_time ~round = function
| [ s1; s2; s3; s4; s5; last ] ->
add_round_state ~round (s1, s2, s3, s4, s5) ;
add_last_row last
| s1 :: s2 :: s3 :: s4 :: s5 :: tl ->
add_round_state ~round (s1, s2, s3, s4, s5) ;
process_5_states_at_a_time ~round:(round + 5) tl
| _ ->
failwith "incorrect number of states given"
in
process_5_states_at_a_time ~round:0 (Array.to_list state)
| Plonk_constraint.T
(EC_add_complete { p1; p2; p3; inf; same_x; slope; inf_z; x21_inv }) ->
let reduce_curve_point (x, y) = (reduce_to_v x, reduce_to_v y) in
// ! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// ! x1 y1 x2 y2 x3 y3 inf same_x s inf_z x21_inv
//! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
//! x1 y1 x2 y2 x3 y3 inf same_x s inf_z x21_inv
*)
let x1, y1 = reduce_curve_point p1 in
let x2, y2 = reduce_curve_point p2 in
let x3, y3 = reduce_curve_point p3 in
let vars =
[| Some x1
; Some y1
; Some x2
; Some y2
; Some x3
; Some y3
; Some (reduce_to_v inf)
; Some (reduce_to_v same_x)
; Some (reduce_to_v slope)
; Some (reduce_to_v inf_z)
; Some (reduce_to_v x21_inv)
; None
; None
; None
; None
|]
in
add_row sys vars CompleteAdd [||]
| Plonk_constraint.T (EC_scale { state }) ->
let i = ref 0 in
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
xT yT x0 y0 n n ' x1 y1 x2 y2 x3 y3 x4 y4
x5 y5 b0 b1 b2 b3 b4 s0 s1 s2 s3 s4
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
xT yT x0 y0 n n' x1 y1 x2 y2 x3 y3 x4 y4
x5 y5 b0 b1 b2 b3 b4 s0 s1 s2 s3 s4
*)
let add_ecscale_round
Scale_round.{ accs; bits; ss; base = xt, yt; n_prev; n_next } =
let curr_row =
[| Some xt
; Some yt
; Some (fst accs.(0))
; Some (snd accs.(0))
; Some n_prev
; Some n_next
; None
; Some (fst accs.(1))
; Some (snd accs.(1))
; Some (fst accs.(2))
; Some (snd accs.(2))
; Some (fst accs.(3))
; Some (snd accs.(3))
; Some (fst accs.(4))
; Some (snd accs.(4))
|]
in
let next_row =
[| Some (fst accs.(5))
; Some (snd accs.(5))
; Some bits.(0)
; Some bits.(1)
; Some bits.(2)
; Some bits.(3)
; Some bits.(4)
; Some ss.(0)
; Some ss.(1)
; Some ss.(2)
; Some ss.(3)
; Some ss.(4)
; None
; None
; None
|]
in
add_row sys curr_row VarBaseMul [||] ;
add_row sys next_row Zero [||]
in
Array.iter
~f:(fun round -> add_ecscale_round round ; incr i)
(Array.map state ~f:(Scale_round.map ~f:reduce_to_v)) ;
()
| Plonk_constraint.T (EC_endoscale { state; xs; ys; n_acc }) ->
let state = Array.map state ~f:(Endoscale_round.map ~f:reduce_to_v) in
let add_endoscale_round (round : V.t Endoscale_round.t) =
let row =
[| Some round.xt
; Some round.yt
; None
; None
; Some round.xp
; Some round.yp
; Some round.n_acc
; Some round.xr
; Some round.yr
; Some round.s1
; Some round.s3
; Some round.b1
; Some round.b2
; Some round.b3
; Some round.b4
|]
in
add_row sys row Kimchi_types.EndoMul [||]
in
Array.iter state ~f:add_endoscale_round ;
Last row .
let vars =
[| None
; None
; None
; None
; Some (reduce_to_v xs)
; Some (reduce_to_v ys)
; Some (reduce_to_v n_acc)
; None
; None
; None
; None
; None
; None
; None
; None
|]
in
add_row sys vars Zero [||]
| Plonk_constraint.T
(EC_endoscalar { state : 'v Endoscale_scalar_round.t array }) ->
let add_endoscale_scalar_round (round : V.t Endoscale_scalar_round.t) =
let row =
[| Some round.n0
; Some round.n8
; Some round.a0
; Some round.b0
; Some round.a8
; Some round.b8
; Some round.x0
; Some round.x1
; Some round.x2
; Some round.x3
; Some round.x4
; Some round.x5
; Some round.x6
; Some round.x7
; None
|]
in
add_row sys row Kimchi_types.EndoMulScalar [||]
in
Array.iter state
~f:
(Fn.compose add_endoscale_scalar_round
(Endoscale_scalar_round.map ~f:reduce_to_v) )
| Plonk_constraint.T
(RangeCheck0
{ v0
; v0p0
; v0p1
; v0p2
; v0p3
; v0p4
; v0p5
; v0c0
; v0c1
; v0c2
; v0c3
; v0c4
; v0c5
; v0c6
; v0c7
; compact
} ) ->
// ! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// ! v vp0 vp1 vp2 vp4 vp5 vc0 vc1 vc2 vc4 vc5 vc6 vc7
//! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
//! v vp0 vp1 vp2 vp3 vp4 vp5 vc0 vc1 vc2 vc3 vc4 vc5 vc6 vc7
*)
let vars =
[| Some (reduce_to_v v0)
; Some (reduce_to_v v0p1)
; Some (reduce_to_v v0p2)
; Some (reduce_to_v v0p3)
; Some (reduce_to_v v0p4)
; Some (reduce_to_v v0p5)
; Some (reduce_to_v v0c0)
; Some (reduce_to_v v0c1)
; Some (reduce_to_v v0c2)
; Some (reduce_to_v v0c3)
; Some (reduce_to_v v0c4)
; Some (reduce_to_v v0c5)
; Some (reduce_to_v v0c6)
|]
in
let coeff = if Fp.equal compact Fp.one then Fp.one else Fp.zero in
add_row sys vars RangeCheck0 [| coeff |]
| Plonk_constraint.T
(RangeCheck1
; v12
; v2c0
; v2p0
; v2p1
; v2p2
; v2p3
; v2c1
; v2c2
; v2c3
; v2c4
; v2c5
; v2c6
; v2c7
; v2c8
; v2c10
; v2c11
; v0p0
; v0p1
; v1p0
; v1p1
; v2c12
; v2c13
; v2c14
; v2c15
; v2c16
; v2c17
; v2c18
; v2c19
} ) ->
// ! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// ! Curr : v2 v12 v2c0 v2p0 v2p1 v2p2 v2p3 v2c1 v2c2 v2c3 v2c6 v2c7 v2c8
// ! Next : v2c9 v2c11 v0p0 v0p1 v1p0 v1p1 v2c12 v2c13 v2c14 v2c15 v2c16 v2c17 v2c19
//! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
//! Curr: v2 v12 v2c0 v2p0 v2p1 v2p2 v2p3 v2c1 v2c2 v2c3 v2c4 v2c5 v2c6 v2c7 v2c8
//! Next: v2c9 v2c10 v2c11 v0p0 v0p1 v1p0 v1p1 v2c12 v2c13 v2c14 v2c15 v2c16 v2c17 v2c18 v2c19
*)
let vars_curr =
; Some (reduce_to_v v12)
; Some (reduce_to_v v2p0)
; Some (reduce_to_v v2p1)
; Some (reduce_to_v v2p2)
; Some (reduce_to_v v2p3)
; Some (reduce_to_v v2c1)
; Some (reduce_to_v v2c2)
; Some (reduce_to_v v2c3)
; Some (reduce_to_v v2c4)
; Some (reduce_to_v v2c5)
; Some (reduce_to_v v2c6)
; Some (reduce_to_v v2c7)
|]
in
let vars_next =
; Some (reduce_to_v v2c10)
; Some (reduce_to_v v2c11)
; Some (reduce_to_v v0p0)
; Some (reduce_to_v v0p1)
; Some (reduce_to_v v1p0)
; Some (reduce_to_v v1p1)
; Some (reduce_to_v v2c12)
; Some (reduce_to_v v2c13)
; Some (reduce_to_v v2c14)
; Some (reduce_to_v v2c15)
; Some (reduce_to_v v2c16)
; Some (reduce_to_v v2c17)
; Some (reduce_to_v v2c18)
; Some (reduce_to_v v2c19)
|]
in
add_row sys vars_curr RangeCheck1 [||] ;
add_row sys vars_next Zero [||]
| Plonk_constraint.T
(Xor
{ in1
; in2
; out
; in1_0
; in1_1
; in1_2
; in1_3
; in2_0
; in2_1
; in2_2
; in2_3
; out_0
; out_1
; out_2
; out_3
} ) ->
| Column | Curr | Next ( gadget responsibility ) |
| ------ | ---------------- | ---------------------------- |
| 0 | copy ` in1 ` | copy ` in1 ' ` |
| 1 | copy ` in2 ` | copy ` in2 ' ` |
| 2 | copy ` out ` | copy ` out ' ` |
| 3 | ` in1_0 ` | |
| 4 | plookup1 ` in1_1 ` | |
| 5 | plookup2 ` in1_2 ` | |
| 6 | in1_3 ` | |
| 7 | |
| 8 | plookup1 ` in2_1 ` | |
| 9 | plookup2 ` in2_2 ` | |
| 10 | plookup3 ` in2_3 ` | |
| 11 | ` out_0 ` | |
| 12 | plookup1 ` out_1 ` | |
| 13 | plookup2 ` out_2 ` | |
| 14 |
| ------ | ---------------- | ---------------------------- |
| 0 | copy `in1` | copy `in1'` |
| 1 | copy `in2` | copy `in2'` |
| 2 | copy `out` | copy `out'` |
| 3 | plookup0 `in1_0` | |
| 4 | plookup1 `in1_1` | |
| 5 | plookup2 `in1_2` | |
| 6 | plookup3 `in1_3` | |
| 7 | plookup0 `in2_0` | |
| 8 | plookup1 `in2_1` | |
| 9 | plookup2 `in2_2` | |
| 10 | plookup3 `in2_3` | |
| 11 | plookup0 `out_0` | |
| 12 | plookup1 `out_1` | |
| 13 | plookup2 `out_2` | |
| 14 | plookup3 `out_3` | |
*)
let curr_row =
[| Some (reduce_to_v in1)
; Some (reduce_to_v in2)
; Some (reduce_to_v out)
; Some (reduce_to_v in1_0)
; Some (reduce_to_v in1_1)
; Some (reduce_to_v in1_2)
; Some (reduce_to_v in1_3)
; Some (reduce_to_v in2_0)
; Some (reduce_to_v in2_1)
; Some (reduce_to_v in2_2)
; Some (reduce_to_v in2_3)
; Some (reduce_to_v out_0)
; Some (reduce_to_v out_1)
; Some (reduce_to_v out_2)
; Some (reduce_to_v out_3)
|]
in
The generic gate after a Xor16 gate is a Const to check that all values are zero .
For that , the first coefficient is 1 and the rest will be zero .
This will be included in the gadget for a chain of Xors , not here .
For that, the first coefficient is 1 and the rest will be zero.
This will be included in the gadget for a chain of Xors, not here.*)
add_row sys curr_row Xor16 [||]
| Plonk_constraint.T
(ForeignFieldAdd
{ left_input_lo
; left_input_mi
; left_input_hi
; right_input_lo
; right_input_mi
; right_input_hi
; field_overflow
; carry
} ) ->
// ! | Gate | ` ForeignFieldAdd ` | Circuit / gadget responsibility |
// ! | ------ | ------------------------ | ------------------------------ |
// ! | Column | ` Curr ` | ` Next ` |
// ! | ------ | ------------------------ | ------------------------------ |
// ! | 0 | ` left_input_lo ` ( copy ) | ` result_lo ` ( copy ) |
// ! | 1 | ` left_input_mi ` ( copy ) | ` result_mi ` ( copy ) |
// ! | 2 | ` left_input_hi ` ( copy ) | ` result_hi ` ( copy ) |
// ! | 3 | ` right_input_lo ` ( copy ) | |
// ! | 4 | ` right_input_mi ` ( copy ) | |
// ! | 5 | ` right_input_hi ` ( copy ) | |
// ! | 6 | ` field_overflow ` ( copy ? ) | |
// ! | 7 | ` carry ` | |
// ! | 8 | | |
// ! | 9 | | |
// ! | 10 | | |
// ! | 11 | | |
// ! | 12 | | |
// ! | 13 | | |
// ! | 14 | | |
//! | Gate | `ForeignFieldAdd` | Circuit/gadget responsibility |
//! | ------ | ------------------------ | ------------------------------ |
//! | Column | `Curr` | `Next` |
//! | ------ | ------------------------ | ------------------------------ |
//! | 0 | `left_input_lo` (copy) | `result_lo` (copy) |
//! | 1 | `left_input_mi` (copy) | `result_mi` (copy) |
//! | 2 | `left_input_hi` (copy) | `result_hi` (copy) |
//! | 3 | `right_input_lo` (copy) | |
//! | 4 | `right_input_mi` (copy) | |
//! | 5 | `right_input_hi` (copy) | |
//! | 6 | `field_overflow` (copy?) | |
//! | 7 | `carry` | |
//! | 8 | | |
//! | 9 | | |
//! | 10 | | |
//! | 11 | | |
//! | 12 | | |
//! | 13 | | |
//! | 14 | | |
*)
let vars =
; Some (reduce_to_v left_input_mi)
; Some (reduce_to_v left_input_hi)
; Some (reduce_to_v right_input_lo)
; Some (reduce_to_v right_input_mi)
; Some (reduce_to_v right_input_hi)
; Some (reduce_to_v field_overflow)
; Some (reduce_to_v carry)
; None
; None
; None
; None
; None
; None
; None
|]
in
add_row sys vars ForeignFieldAdd [||]
| Plonk_constraint.T
(ForeignFieldMul
; left_input1
; left_input2
; right_input0
; right_input1
; right_input2
; carry1_lo
; carry1_hi
; carry0
; quotient0
; quotient1
; quotient2
; quotient_bound_carry
; product1_hi_1
; remainder1
; remainder2
; quotient_bound01
; quotient_bound2
; product1_lo
; product1_hi_0
} ) ->
// ! | Gate | ` ForeignFieldMul ` | ` Zero ` |
// ! | ------ | ---------------------------- | ------------------------- |
// ! | Column | ` Curr ` | ` Next ` |
// ! | ------ | ---------------------------- | ------------------------- |
// ! | 0 | ` left_input0 ` ( copy ) | ` remainder0 ` ( copy ) |
// ! | 1 | ` left_input1 ` ( copy ) | ` remainder1 ` ( copy ) |
// ! | 2 | ` left_input2 ` ( copy ) | ` remainder2 ` ( copy ) |
// ! | 3 | ` right_input0 ` ( copy ) | ` quotient_bound01 ` ( copy ) |
// ! | 4 | ` right_input1 ` ( copy ) | ` quotient_bound2 ` ( copy ) |
// ! | 5 | ` right_input2 ` ( copy ) | ` product1_lo ` ( copy ) |
// ! | 6 | ` carry1_lo ` ( copy ) | ` product1_hi_0 ` ( copy ) |
// ! | 7 | ` carry1_hi ` ( plookup ) | |
// ! | 8 | ` carry0 ` | |
// ! | 9 | ` quotient0 ` | |
// ! | 10 | ` quotient1 ` | |
// ! | 11 | ` quotient2 ` | |
// ! | 12 | ` quotient_bound_carry ` | |
// ! | 13 | ` product1_hi_1 ` | |
// ! | 14 | | |
//! | Gate | `ForeignFieldMul` | `Zero` |
//! | ------ | ---------------------------- | ------------------------- |
//! | Column | `Curr` | `Next` |
//! | ------ | ---------------------------- | ------------------------- |
//! | 0 | `left_input0` (copy) | `remainder0` (copy) |
//! | 1 | `left_input1` (copy) | `remainder1` (copy) |
//! | 2 | `left_input2` (copy) | `remainder2` (copy) |
//! | 3 | `right_input0` (copy) | `quotient_bound01` (copy) |
//! | 4 | `right_input1` (copy) | `quotient_bound2` (copy) |
//! | 5 | `right_input2` (copy) | `product1_lo` (copy) |
//! | 6 | `carry1_lo` (copy) | `product1_hi_0` (copy) |
//! | 7 | `carry1_hi` (plookup) | |
//! | 8 | `carry0` | |
//! | 9 | `quotient0` | |
//! | 10 | `quotient1` | |
//! | 11 | `quotient2` | |
//! | 12 | `quotient_bound_carry` | |
//! | 13 | `product1_hi_1` | |
//! | 14 | | |
*)
let vars_curr =
; Some (reduce_to_v left_input1)
; Some (reduce_to_v left_input2)
; Some (reduce_to_v right_input0)
; Some (reduce_to_v right_input1)
; Some (reduce_to_v right_input2)
; Some (reduce_to_v carry1_lo)
; Some (reduce_to_v carry1_hi)
; Some (reduce_to_v carry0)
; Some (reduce_to_v quotient0)
; Some (reduce_to_v quotient1)
; Some (reduce_to_v quotient2)
; Some (reduce_to_v quotient_bound_carry)
; Some (reduce_to_v product1_hi_1)
; None
|]
in
let vars_next =
; Some (reduce_to_v remainder1)
; Some (reduce_to_v remainder2)
; Some (reduce_to_v quotient_bound01)
; Some (reduce_to_v quotient_bound2)
; Some (reduce_to_v product1_lo)
; Some (reduce_to_v product1_hi_0)
; None
; None
; None
; None
; None
; None
; None
; None
|]
in
add_row sys vars_curr ForeignFieldMul [||] ;
add_row sys vars_next Zero [||]
| Plonk_constraint.T
(Rot64
; rotated
; excess
; bound_limb0
; bound_limb1
; bound_limb2
; bound_limb3
; bound_crumb0
; bound_crumb1
; bound_crumb2
; bound_crumb3
; bound_crumb4
; bound_crumb5
; bound_crumb6
; bound_crumb7
; shifted_limb0
; shifted_limb1
; shifted_limb2
; shifted_limb3
; shifted_crumb0
; shifted_crumb1
; shifted_crumb2
; shifted_crumb3
; shifted_crumb4
; shifted_crumb5
; shifted_crumb6
; shifted_crumb7
} ) ->
// ! | Gate | ` Rot64 ` | ` RangeCheck0 ` |
// ! | ------ | ------------------- | ---------------- |
// ! | Column | ` Curr ` | ` Next ` |
// ! | ------ | ------------------- | ---------------- |
// ! | 0 | copy ` word ` |`shifted ` |
// ! | 1 | copy ` rotated ` | 0 |
// ! | 2 | ` excess ` | 0 |
// ! | 3 | ` bound_limb0 ` | ` shifted_limb0 ` |
// ! | 4 | ` bound_limb1 ` | ` shifted_limb1 ` |
// ! | 5 | ` bound_limb2 ` | ` shifted_limb2 ` |
// ! | 6 | ` bound_limb3 ` | ` shifted_limb3 ` |
// ! | 7 | ` bound_crumb0 ` | ` shifted_crumb0 ` |
// ! | 8 | ` bound_crumb1 ` | ` shifted_crumb1 ` |
// ! | 9 | ` bound_crumb2 ` | ` shifted_crumb2 ` |
// ! | 10 | ` bound_crumb3 ` | ` shifted_crumb3 ` |
// ! | 11 | ` bound_crumb4 ` | ` shifted_crumb4 ` |
// ! | 12 | ` bound_crumb5 ` | ` shifted_crumb5 ` |
// ! | 13 | ` bound_crumb6 ` | ` shifted_crumb6 ` |
// ! | 14 | ` bound_crumb7 ` | ` shifted_crumb7 ` |
//! | Gate | `Rot64` | `RangeCheck0` |
//! | ------ | ------------------- | ---------------- |
//! | Column | `Curr` | `Next` |
//! | ------ | ------------------- | ---------------- |
//! | 0 | copy `word` |`shifted` |
//! | 1 | copy `rotated` | 0 |
//! | 2 | `excess` | 0 |
//! | 3 | `bound_limb0` | `shifted_limb0` |
//! | 4 | `bound_limb1` | `shifted_limb1` |
//! | 5 | `bound_limb2` | `shifted_limb2` |
//! | 6 | `bound_limb3` | `shifted_limb3` |
//! | 7 | `bound_crumb0` | `shifted_crumb0` |
//! | 8 | `bound_crumb1` | `shifted_crumb1` |
//! | 9 | `bound_crumb2` | `shifted_crumb2` |
//! | 10 | `bound_crumb3` | `shifted_crumb3` |
//! | 11 | `bound_crumb4` | `shifted_crumb4` |
//! | 12 | `bound_crumb5` | `shifted_crumb5` |
//! | 13 | `bound_crumb6` | `shifted_crumb6` |
//! | 14 | `bound_crumb7` | `shifted_crumb7` |
*)
let vars_curr =
; Some (reduce_to_v rotated)
; Some (reduce_to_v excess)
; Some (reduce_to_v bound_limb0)
; Some (reduce_to_v bound_limb1)
; Some (reduce_to_v bound_limb2)
; Some (reduce_to_v bound_limb3)
; Some (reduce_to_v bound_crumb0)
; Some (reduce_to_v bound_crumb1)
; Some (reduce_to_v bound_crumb2)
; Some (reduce_to_v bound_crumb3)
; Some (reduce_to_v bound_crumb4)
; Some (reduce_to_v bound_crumb5)
; Some (reduce_to_v bound_crumb6)
; Some (reduce_to_v bound_crumb7)
|]
in
let vars_next =
; None
; None
; Some (reduce_to_v shifted_limb0)
; Some (reduce_to_v shifted_limb1)
; Some (reduce_to_v shifted_limb2)
; Some (reduce_to_v shifted_limb3)
; Some (reduce_to_v shifted_crumb0)
; Some (reduce_to_v shifted_crumb1)
; Some (reduce_to_v shifted_crumb2)
; Some (reduce_to_v shifted_crumb3)
; Some (reduce_to_v shifted_crumb4)
; Some (reduce_to_v shifted_crumb5)
; Some (reduce_to_v shifted_crumb6)
; Some (reduce_to_v shifted_crumb7)
|]
in
let compact = Fp.zero in
add_row sys vars_curr Rot64 [| two_to_rot |] ;
add_row sys vars_next RangeCheck0
| Plonk_constraint.T (Raw { kind; values; coeffs }) ->
let values =
Array.init 15 ~f:(fun i ->
Option.try_with (fun () -> reduce_to_v values.(i)) )
in
add_row sys values kind coeffs
| constr ->
failwithf "Unhandled constraint %s"
Obj.(Extension_constructor.name (Extension_constructor.of_val constr))
()
end
|
cafd45381ef6a57e8d576070ec1fbf3b0f3058e57338a2b340678b973ed67e5a | DKurilo/hackerrank | Main.hs | import Control.Monad
import Data.Bifunctor (bimap)
import Data.List (foldl', intercalate)
import Data.Set (Set (..))
import qualified Data.Set as S
import System.IO
data Coord = Coord {cX :: Int, cY :: Int} deriving (Eq, Ord)
data Direction = N | S | E | W deriving (Show)
charToDirection :: Char -> Direction
charToDirection 'N' = N
charToDirection 'S' = S
charToDirection 'E' = E
charToDirection _ = W
data Jump = Jump {jDir :: Direction, jLength :: Int} deriving (Show)
newtype Grid = Grid {unGrid :: Set Coord}
instance Show Grid where
show (Grid grid)
| S.null grid = "."
| otherwise = intercalate "\n" [[if Coord x y `S.member` grid then '#' else '.' | x <- [xMin .. xMax]] | y <- [yMin .. yMax]]
where
xs = S.map cX grid
ys = S.map cY grid
xMin = S.findMin xs
xMax = S.findMax xs
yMin = S.findMin ys
yMax = S.findMax ys
mkGrid :: [Jump] -> Grid
mkGrid = snd . foldl' (\(c, g) j -> doJump j c g) (Coord 0 0, Grid S.empty)
where
doJump :: Jump -> Coord -> Grid -> (Coord, Grid)
doJump j c g =
( Coord (cX c + dx * jLength j) (cY c + dy * jLength j),
Grid $ foldl' (\g' c' -> if c' `S.member` g' then S.delete c' g' else S.insert c' g') (unGrid g) cs
)
where
(dx, dy) = case jDir j of
N -> (0, -1)
S -> (0, 1)
E -> (1, 0)
W -> (-1, 0)
cs = map (\n -> Coord (cX c + dx * n) (cY c + dy * n)) [1 .. jLength j]
main :: IO ()
main = do
hSetBuffering stdout NoBuffering -- DO NOT REMOVE
-- Auto-generated code below aims at helping you parse
-- the standard input according to the problem statement.
directions <- words <$> getLine
bounces <- words <$> getLine
let jumps = zipWith (curry (uncurry Jump . bimap (charToDirection . head) read)) directions bounces
-- hPutStrLn stderr "Debug messages..."
-- Write answer to stdout
print . mkGrid $ jumps
return ()
| null | https://raw.githubusercontent.com/DKurilo/hackerrank/5951bdfecca6ca2601dd7a1515fc5587531686f8/codingame/bouncing-barry/src/Main.hs | haskell | DO NOT REMOVE
Auto-generated code below aims at helping you parse
the standard input according to the problem statement.
hPutStrLn stderr "Debug messages..."
Write answer to stdout | import Control.Monad
import Data.Bifunctor (bimap)
import Data.List (foldl', intercalate)
import Data.Set (Set (..))
import qualified Data.Set as S
import System.IO
data Coord = Coord {cX :: Int, cY :: Int} deriving (Eq, Ord)
data Direction = N | S | E | W deriving (Show)
charToDirection :: Char -> Direction
charToDirection 'N' = N
charToDirection 'S' = S
charToDirection 'E' = E
charToDirection _ = W
data Jump = Jump {jDir :: Direction, jLength :: Int} deriving (Show)
newtype Grid = Grid {unGrid :: Set Coord}
instance Show Grid where
show (Grid grid)
| S.null grid = "."
| otherwise = intercalate "\n" [[if Coord x y `S.member` grid then '#' else '.' | x <- [xMin .. xMax]] | y <- [yMin .. yMax]]
where
xs = S.map cX grid
ys = S.map cY grid
xMin = S.findMin xs
xMax = S.findMax xs
yMin = S.findMin ys
yMax = S.findMax ys
mkGrid :: [Jump] -> Grid
mkGrid = snd . foldl' (\(c, g) j -> doJump j c g) (Coord 0 0, Grid S.empty)
where
doJump :: Jump -> Coord -> Grid -> (Coord, Grid)
doJump j c g =
( Coord (cX c + dx * jLength j) (cY c + dy * jLength j),
Grid $ foldl' (\g' c' -> if c' `S.member` g' then S.delete c' g' else S.insert c' g') (unGrid g) cs
)
where
(dx, dy) = case jDir j of
N -> (0, -1)
S -> (0, 1)
E -> (1, 0)
W -> (-1, 0)
cs = map (\n -> Coord (cX c + dx * n) (cY c + dy * n)) [1 .. jLength j]
main :: IO ()
main = do
directions <- words <$> getLine
bounces <- words <$> getLine
let jumps = zipWith (curry (uncurry Jump . bimap (charToDirection . head) read)) directions bounces
print . mkGrid $ jumps
return ()
|
114dd24268c0241f7b1f16d0bb669bb6c3879c0b25df72c5d675cca9b0800ad1 | marigold-dev/deku | output.mli | type t = { module_ : string; constants : (int * Values.t) array }
val make :
string ->
(int * Values.t) array ->
(t, [ `Invalid_module | `Module_validation_error ]) result
| null | https://raw.githubusercontent.com/marigold-dev/deku/a26f31e0560ad12fd86cf7fa4667bb147247c7ef/deku-c/tunac/lib/output.mli | ocaml | type t = { module_ : string; constants : (int * Values.t) array }
val make :
string ->
(int * Values.t) array ->
(t, [ `Invalid_module | `Module_validation_error ]) result
|
|
a50b19143687e18b390525dfcd59805553052541516ca48c86eb00b8277a0c22 | johnridesabike/acutis | debugAst.ml | (**************************************************************************)
(* *)
Copyright ( c ) 2022 .
(* *)
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(* *)
(**************************************************************************)
module F = Format
open Ast
let equal_pair eq_a eq_b (a1, b1) (a2, b2) = eq_a a1 a2 && eq_b b1 b2
module Record = struct
open Ast.Record
let equal_tag a b =
match (a, b) with
| Tag_int (_, a), Tag_int (_, b) | Tag_bool (_, a), Tag_bool (_, b) -> a = b
| Tag_string (_, a), Tag_string (_, b) -> a = b
| _ -> false
let pp pp ppf = function
| Untagged x -> F.fprintf ppf "(@[<2>Untagged@ %a@])" (Ast.Dict.pp pp) x
| Tagged (s, tag, m) ->
F.fprintf ppf "(@[<2>Tagged (@,%S,@ %a,@ %a@,))@]" s pp_tag tag
(Ast.Dict.pp pp) m
let equal eq a b =
match (a, b) with
| Untagged a, Untagged b -> Ast.Dict.equal eq a b
| Tagged (a_s, a_tag, a_m), Tagged (b_s, b_tag, b_m) ->
a_s = b_s && equal_tag a_tag b_tag && Ast.Dict.equal eq a_m b_m
| _ -> false
end
module Interface = struct
open Ast.Interface
let rec pp_ty ppf = function
| Named (loc, s) ->
F.fprintf ppf "(@[<2>Named (@,%a,@ %S@,))@]" Loc.pp loc s
| Nullable t -> F.fprintf ppf "(@[<2>Nullable@ %a@])" pp_ty t
| List t -> F.fprintf ppf "(@[<2>List@ %a@])" pp_ty t
| Dict t -> F.fprintf ppf "(@[<2>Dict@ %a@])" pp_ty t
| Enum_int (l, row) ->
F.fprintf ppf "(@[<2>Enum_int (@,%a,@ %a@,))@]"
(Nonempty.pp F.pp_print_int)
l Typescheme.Variant.pp_row row
| Enum_bool l ->
F.fprintf ppf "(@[<2>Enum_bool@ %a@])" (Nonempty.pp F.pp_print_int) l
| Enum_string (l, row) ->
F.fprintf ppf "(@[<2>Enum_string (@,%a,@ %a@,))@]"
(Nonempty.pp Pp.syntax_string)
l Typescheme.Variant.pp_row row
| Record (l, row) ->
F.fprintf ppf "(@[<2>Record (@,%a,@ %a@,))@]"
(Nonempty.pp (fun ppf (loc, m) ->
F.fprintf ppf "(@[%a,@ %a@])" Loc.pp loc (Record.pp pp_ty) m))
l Typescheme.Variant.pp_row row
| Tuple l -> F.fprintf ppf "(@[<2>Tuple@ %a@])" (Pp.list pp_ty) l
let rec equal_ty a b =
match (a, b) with
| Named (_, a), Named (_, b) -> a = b
| Nullable a, Nullable b | List a, List b | Dict a, Dict b -> equal_ty a b
| Enum_int (a_l, a_row), Enum_int (b_l, b_row) ->
Nonempty.equal Int.equal a_l b_l
&& Typescheme.Variant.equal_row a_row b_row
| Enum_bool a, Enum_bool b -> Nonempty.equal Int.equal a b
| Enum_string (a_l, a_row), Enum_string (b_l, b_row) ->
Nonempty.equal String.equal a_l b_l
&& Typescheme.Variant.equal_row a_row b_row
| Record (a_l, a_row), Record (b_l, b_row) ->
Nonempty.equal (equal_pair Loc.equal (Record.equal equal_ty)) a_l b_l
&& Typescheme.Variant.equal_row a_row b_row
| Tuple a, Tuple b -> List.equal equal_ty a b
| _ -> false
let pp ppf { loc; name; ty } =
F.fprintf ppf "(@[<2>Type (@,%a,@ %S,@ %a@,))@]" Loc.pp loc name pp_ty ty
let equal a { loc = _; name; ty } = a.name = name && equal_ty a.ty ty
end
type t = Ast.t
let pp_trim ppf = function
| No_trim -> F.pp_print_string ppf "No_trim"
| Trim -> F.pp_print_string ppf "Trim"
let equal_trim a b =
match (a, b) with No_trim, No_trim | Trim, Trim -> true | _ -> false
let pp_escape ppf = function
| No_escape -> F.pp_print_string ppf "No_escape"
| Escape -> F.pp_print_string ppf "Escape"
let equal_escape a b =
match (a, b) with No_escape, No_escape | Escape, Escape -> true | _ -> false
let pp_echo_flag ppf = function
| No_flag -> F.pp_print_string ppf "No_flag"
| Flag_comma -> F.pp_print_string ppf "Flag_comma"
let pp_echo_format ppf = function
| Fmt_string -> F.pp_print_string ppf "Fmt_string"
| Fmt_int flag -> F.fprintf ppf "(Fmt_int %a@,)" pp_echo_flag flag
| Fmt_float i -> F.fprintf ppf "(Fmt_float %i)" i
| Fmt_float_e i -> F.fprintf ppf "(Fmt_float_e %i)" i
| Fmt_float_g i -> F.fprintf ppf "(Fmt_float_g %i)" i
| Fmt_bool -> F.pp_print_string ppf "Fmt_bool"
let pp_echo ppf = function
| Ech_var (loc, fmt, s) ->
F.fprintf ppf "(@[<2>Ech_var (@,%a,@ %a,@ %S@,))@]" Loc.pp loc
pp_echo_format fmt s
| Ech_string (loc, s) ->
F.fprintf ppf "(@[<2>Ech_string (@,%a,@ %S@,))@]" Loc.pp loc s
let equal_echo_flag a b =
match (a, b) with
| No_flag, No_flag | Flag_comma, Flag_comma -> true
| _ -> false
let equal_echo_format a b =
match (a, b) with
| Fmt_string, Fmt_string | Fmt_bool, Fmt_bool -> true
| Fmt_int a, Fmt_int b -> equal_echo_flag a b
| Fmt_float a, Fmt_float b
| Fmt_float_e a, Fmt_float_e b
| Fmt_float_g a, Fmt_float_g b ->
a = b
| _ -> false
let equal_echo a b =
match (a, b) with
| Ech_var (_, a_fmt, a_id), Ech_var (_, b_fmt, b_id) ->
a_id = b_id && equal_echo_format a_fmt b_fmt
| Ech_string (_, a), Ech_string (_, b) -> a = b
| _ -> false
let rec pp_pat ppf = function
| Var (loc, s) -> F.fprintf ppf "(@[<2>Var (@,%a,@ %S@,))@]" Loc.pp loc s
| Bool (loc, i) -> F.fprintf ppf "(@[<2>Bool (@,%a,@ %d@,))@]" Loc.pp loc i
| Int (loc, i) -> F.fprintf ppf "(@[<2>Int (@,%a,@ %d@,))@]" Loc.pp loc i
| Float (loc, f) -> F.fprintf ppf "(@[<2>Float (@,%a,@ %F@,))@]" Loc.pp loc f
| String (loc, s) ->
F.fprintf ppf "(@[<2>String (@,%a,@ %S@,))@]" Loc.pp loc s
| Nullable (loc, t) ->
F.fprintf ppf "(@[<2>Nullable (@,%a,@ %a@,))@]" Loc.pp loc
(Pp.option pp_pat) t
| Enum_string (loc, s) ->
F.fprintf ppf "(@[<2>Enum_string (@,%a,@ %S@,))@]" Loc.pp loc s
| Enum_int (loc, i) ->
F.fprintf ppf "(@[<2>Enum_int (@,%a,@ %d@,))@]" Loc.pp loc i
| List (loc, l, t) ->
F.fprintf ppf "(@[<2>List (@,%a,@ %a,@ %a@,))@]" Loc.pp loc
(Pp.list pp_pat) l (Pp.option pp_pat) t
| Tuple (loc, t) ->
F.fprintf ppf "(@[<2>Tuple (@,%a,@ %a@,))@]" Loc.pp loc (Pp.list pp_pat) t
| Record (loc, m) ->
F.fprintf ppf "(@[<2>Record (@,%a,@ %a@,))@]" Loc.pp loc
(Record.pp pp_pat) m
| Dict (loc, m) ->
F.fprintf ppf "(@[<2>Dict (@,%a,@ %a@,))@]" Loc.pp loc
(Ast.Dict.pp pp_pat) m
| Block (loc, x) ->
F.fprintf ppf "(@[<2>Block (@,%a,@ %a@,))@]" Loc.pp loc pp x
and pp_node ppf = function
| Text (s, triml, trimr) ->
F.fprintf ppf "(@[<2>Text (@,%S,@ %a,@ %a@,))@]" s pp_trim triml pp_trim
trimr
| Echo (l, ech, esc) ->
F.fprintf ppf "(@[<2>Echo (@,%a,@ %a,@ %a@,))@]" (Pp.list pp_echo) l
pp_echo ech pp_escape esc
| Match (loc, pats, cases) ->
F.fprintf ppf "(@[<2>Match (@,%a,@ %a,@ %a@,))@]" Loc.pp loc
(Nonempty.pp pp_pat) pats (Nonempty.pp pp_case) cases
| Map_list (loc, pat, cases) ->
F.fprintf ppf "(@[<2>Map_list (@,%a,@ %a,@ %a@,))@]" Loc.pp loc pp_pat pat
(Nonempty.pp pp_case) cases
| Map_dict (loc, pat, cases) ->
F.fprintf ppf "(@[<2>Map_dict (@,%a,@ %a,@ %a@,))@]" Loc.pp loc pp_pat pat
(Nonempty.pp pp_case) cases
| Component (loc, s1, s2, pats) ->
F.fprintf ppf "(@[<2>Component (@,%a,@ %S,@ %S,@ %a@,))@]" Loc.pp loc s1
s2 (Dict.pp pp_pat) pats
| Interface (loc, l) ->
F.fprintf ppf "(@[<2>Interface (@,%a,@ %a@,))@]" Loc.pp loc
(Pp.list Interface.pp) l
and pp_case ppf { pats; nodes } =
F.fprintf ppf "@[<2>{ @[pats =@ %a@];@ @[nodes =@ %a@]@ }@]"
(Nonempty.pp (Pp.pair Loc.pp (Nonempty.pp pp_pat)))
pats pp nodes
and pp ppf x = Pp.list pp_node ppf x
let rec equal_pat a b =
match (a, b) with
| Var (_, a), Var (_, b)
| String (_, a), String (_, b)
| Enum_string (_, a), Enum_string (_, b) ->
a = b
| Bool (_, a), Bool (_, b)
| Int (_, a), Int (_, b)
| Enum_int (_, a), Enum_int (_, b) ->
a = b
| Float (_, a), Float (_, b) -> a = b
| Nullable (_, a), Nullable (_, b) -> Option.equal equal_pat a b
| List (_, a_l, a_t), List (_, b_l, b_t) ->
List.equal equal_pat a_l b_l && Option.equal equal_pat a_t b_t
| Tuple (_, a), Tuple (_, b) -> List.equal equal_pat a b
| Record (_, a), Record (_, b) -> Record.equal equal_pat a b
| Dict (_, a), Dict (_, b) -> Ast.Dict.equal equal_pat a b
| Block (_, a), Block (_, b) -> equal a b
| _ -> false
and equal_node a b =
match (a, b) with
| Text (a, a_triml, a_trimr), Text (b, b_triml, b_trimr) ->
a = b && equal_trim a_triml b_triml && equal_trim a_trimr b_trimr
| Echo (a_l, a_ech, a_esc), Echo (b_l, b_ech, b_esc) ->
List.equal equal_echo a_l b_l
&& equal_echo a_ech b_ech && equal_escape a_esc b_esc
| Match (_, a_pats, a_cases), Match (_, b_pats, b_cases) ->
Nonempty.equal equal_pat a_pats b_pats
&& Nonempty.equal equal_case a_cases b_cases
| Map_list (_, a_pat, a_cases), Map_list (_, b_pat, b_cases) ->
equal_pat a_pat b_pat && Nonempty.equal equal_case a_cases b_cases
| Map_dict (_, a_pat, a_cases), Map_dict (_, b_pat, b_cases) ->
equal_pat a_pat b_pat && Nonempty.equal equal_case a_cases b_cases
| Component (_, a_s1, a_s2, a_pats), Component (_, b_s1, b_s2, b_pats) ->
a_s1 = b_s1 && a_s2 = b_s2 && Dict.equal equal_pat a_pats b_pats
| Interface (_, a), Interface (_, b) -> List.equal Interface.equal a b
| _ -> false
and equal_case a { pats; nodes } =
Nonempty.equal (equal_pair Loc.equal (Nonempty.equal equal_pat)) a.pats pats
&& equal a.nodes nodes
and equal a b = List.equal equal_node a b
| null | https://raw.githubusercontent.com/johnridesabike/acutis/19f04e5b65cdc8910eaa2cdee5ad7ef110484b47/lib/debugAst.ml | ocaml | ************************************************************************
************************************************************************ | Copyright ( c ) 2022 .
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
module F = Format
open Ast
let equal_pair eq_a eq_b (a1, b1) (a2, b2) = eq_a a1 a2 && eq_b b1 b2
module Record = struct
open Ast.Record
let equal_tag a b =
match (a, b) with
| Tag_int (_, a), Tag_int (_, b) | Tag_bool (_, a), Tag_bool (_, b) -> a = b
| Tag_string (_, a), Tag_string (_, b) -> a = b
| _ -> false
let pp pp ppf = function
| Untagged x -> F.fprintf ppf "(@[<2>Untagged@ %a@])" (Ast.Dict.pp pp) x
| Tagged (s, tag, m) ->
F.fprintf ppf "(@[<2>Tagged (@,%S,@ %a,@ %a@,))@]" s pp_tag tag
(Ast.Dict.pp pp) m
let equal eq a b =
match (a, b) with
| Untagged a, Untagged b -> Ast.Dict.equal eq a b
| Tagged (a_s, a_tag, a_m), Tagged (b_s, b_tag, b_m) ->
a_s = b_s && equal_tag a_tag b_tag && Ast.Dict.equal eq a_m b_m
| _ -> false
end
module Interface = struct
open Ast.Interface
let rec pp_ty ppf = function
| Named (loc, s) ->
F.fprintf ppf "(@[<2>Named (@,%a,@ %S@,))@]" Loc.pp loc s
| Nullable t -> F.fprintf ppf "(@[<2>Nullable@ %a@])" pp_ty t
| List t -> F.fprintf ppf "(@[<2>List@ %a@])" pp_ty t
| Dict t -> F.fprintf ppf "(@[<2>Dict@ %a@])" pp_ty t
| Enum_int (l, row) ->
F.fprintf ppf "(@[<2>Enum_int (@,%a,@ %a@,))@]"
(Nonempty.pp F.pp_print_int)
l Typescheme.Variant.pp_row row
| Enum_bool l ->
F.fprintf ppf "(@[<2>Enum_bool@ %a@])" (Nonempty.pp F.pp_print_int) l
| Enum_string (l, row) ->
F.fprintf ppf "(@[<2>Enum_string (@,%a,@ %a@,))@]"
(Nonempty.pp Pp.syntax_string)
l Typescheme.Variant.pp_row row
| Record (l, row) ->
F.fprintf ppf "(@[<2>Record (@,%a,@ %a@,))@]"
(Nonempty.pp (fun ppf (loc, m) ->
F.fprintf ppf "(@[%a,@ %a@])" Loc.pp loc (Record.pp pp_ty) m))
l Typescheme.Variant.pp_row row
| Tuple l -> F.fprintf ppf "(@[<2>Tuple@ %a@])" (Pp.list pp_ty) l
let rec equal_ty a b =
match (a, b) with
| Named (_, a), Named (_, b) -> a = b
| Nullable a, Nullable b | List a, List b | Dict a, Dict b -> equal_ty a b
| Enum_int (a_l, a_row), Enum_int (b_l, b_row) ->
Nonempty.equal Int.equal a_l b_l
&& Typescheme.Variant.equal_row a_row b_row
| Enum_bool a, Enum_bool b -> Nonempty.equal Int.equal a b
| Enum_string (a_l, a_row), Enum_string (b_l, b_row) ->
Nonempty.equal String.equal a_l b_l
&& Typescheme.Variant.equal_row a_row b_row
| Record (a_l, a_row), Record (b_l, b_row) ->
Nonempty.equal (equal_pair Loc.equal (Record.equal equal_ty)) a_l b_l
&& Typescheme.Variant.equal_row a_row b_row
| Tuple a, Tuple b -> List.equal equal_ty a b
| _ -> false
let pp ppf { loc; name; ty } =
F.fprintf ppf "(@[<2>Type (@,%a,@ %S,@ %a@,))@]" Loc.pp loc name pp_ty ty
let equal a { loc = _; name; ty } = a.name = name && equal_ty a.ty ty
end
type t = Ast.t
let pp_trim ppf = function
| No_trim -> F.pp_print_string ppf "No_trim"
| Trim -> F.pp_print_string ppf "Trim"
let equal_trim a b =
match (a, b) with No_trim, No_trim | Trim, Trim -> true | _ -> false
let pp_escape ppf = function
| No_escape -> F.pp_print_string ppf "No_escape"
| Escape -> F.pp_print_string ppf "Escape"
let equal_escape a b =
match (a, b) with No_escape, No_escape | Escape, Escape -> true | _ -> false
let pp_echo_flag ppf = function
| No_flag -> F.pp_print_string ppf "No_flag"
| Flag_comma -> F.pp_print_string ppf "Flag_comma"
let pp_echo_format ppf = function
| Fmt_string -> F.pp_print_string ppf "Fmt_string"
| Fmt_int flag -> F.fprintf ppf "(Fmt_int %a@,)" pp_echo_flag flag
| Fmt_float i -> F.fprintf ppf "(Fmt_float %i)" i
| Fmt_float_e i -> F.fprintf ppf "(Fmt_float_e %i)" i
| Fmt_float_g i -> F.fprintf ppf "(Fmt_float_g %i)" i
| Fmt_bool -> F.pp_print_string ppf "Fmt_bool"
let pp_echo ppf = function
| Ech_var (loc, fmt, s) ->
F.fprintf ppf "(@[<2>Ech_var (@,%a,@ %a,@ %S@,))@]" Loc.pp loc
pp_echo_format fmt s
| Ech_string (loc, s) ->
F.fprintf ppf "(@[<2>Ech_string (@,%a,@ %S@,))@]" Loc.pp loc s
let equal_echo_flag a b =
match (a, b) with
| No_flag, No_flag | Flag_comma, Flag_comma -> true
| _ -> false
let equal_echo_format a b =
match (a, b) with
| Fmt_string, Fmt_string | Fmt_bool, Fmt_bool -> true
| Fmt_int a, Fmt_int b -> equal_echo_flag a b
| Fmt_float a, Fmt_float b
| Fmt_float_e a, Fmt_float_e b
| Fmt_float_g a, Fmt_float_g b ->
a = b
| _ -> false
let equal_echo a b =
match (a, b) with
| Ech_var (_, a_fmt, a_id), Ech_var (_, b_fmt, b_id) ->
a_id = b_id && equal_echo_format a_fmt b_fmt
| Ech_string (_, a), Ech_string (_, b) -> a = b
| _ -> false
let rec pp_pat ppf = function
| Var (loc, s) -> F.fprintf ppf "(@[<2>Var (@,%a,@ %S@,))@]" Loc.pp loc s
| Bool (loc, i) -> F.fprintf ppf "(@[<2>Bool (@,%a,@ %d@,))@]" Loc.pp loc i
| Int (loc, i) -> F.fprintf ppf "(@[<2>Int (@,%a,@ %d@,))@]" Loc.pp loc i
| Float (loc, f) -> F.fprintf ppf "(@[<2>Float (@,%a,@ %F@,))@]" Loc.pp loc f
| String (loc, s) ->
F.fprintf ppf "(@[<2>String (@,%a,@ %S@,))@]" Loc.pp loc s
| Nullable (loc, t) ->
F.fprintf ppf "(@[<2>Nullable (@,%a,@ %a@,))@]" Loc.pp loc
(Pp.option pp_pat) t
| Enum_string (loc, s) ->
F.fprintf ppf "(@[<2>Enum_string (@,%a,@ %S@,))@]" Loc.pp loc s
| Enum_int (loc, i) ->
F.fprintf ppf "(@[<2>Enum_int (@,%a,@ %d@,))@]" Loc.pp loc i
| List (loc, l, t) ->
F.fprintf ppf "(@[<2>List (@,%a,@ %a,@ %a@,))@]" Loc.pp loc
(Pp.list pp_pat) l (Pp.option pp_pat) t
| Tuple (loc, t) ->
F.fprintf ppf "(@[<2>Tuple (@,%a,@ %a@,))@]" Loc.pp loc (Pp.list pp_pat) t
| Record (loc, m) ->
F.fprintf ppf "(@[<2>Record (@,%a,@ %a@,))@]" Loc.pp loc
(Record.pp pp_pat) m
| Dict (loc, m) ->
F.fprintf ppf "(@[<2>Dict (@,%a,@ %a@,))@]" Loc.pp loc
(Ast.Dict.pp pp_pat) m
| Block (loc, x) ->
F.fprintf ppf "(@[<2>Block (@,%a,@ %a@,))@]" Loc.pp loc pp x
and pp_node ppf = function
| Text (s, triml, trimr) ->
F.fprintf ppf "(@[<2>Text (@,%S,@ %a,@ %a@,))@]" s pp_trim triml pp_trim
trimr
| Echo (l, ech, esc) ->
F.fprintf ppf "(@[<2>Echo (@,%a,@ %a,@ %a@,))@]" (Pp.list pp_echo) l
pp_echo ech pp_escape esc
| Match (loc, pats, cases) ->
F.fprintf ppf "(@[<2>Match (@,%a,@ %a,@ %a@,))@]" Loc.pp loc
(Nonempty.pp pp_pat) pats (Nonempty.pp pp_case) cases
| Map_list (loc, pat, cases) ->
F.fprintf ppf "(@[<2>Map_list (@,%a,@ %a,@ %a@,))@]" Loc.pp loc pp_pat pat
(Nonempty.pp pp_case) cases
| Map_dict (loc, pat, cases) ->
F.fprintf ppf "(@[<2>Map_dict (@,%a,@ %a,@ %a@,))@]" Loc.pp loc pp_pat pat
(Nonempty.pp pp_case) cases
| Component (loc, s1, s2, pats) ->
F.fprintf ppf "(@[<2>Component (@,%a,@ %S,@ %S,@ %a@,))@]" Loc.pp loc s1
s2 (Dict.pp pp_pat) pats
| Interface (loc, l) ->
F.fprintf ppf "(@[<2>Interface (@,%a,@ %a@,))@]" Loc.pp loc
(Pp.list Interface.pp) l
and pp_case ppf { pats; nodes } =
F.fprintf ppf "@[<2>{ @[pats =@ %a@];@ @[nodes =@ %a@]@ }@]"
(Nonempty.pp (Pp.pair Loc.pp (Nonempty.pp pp_pat)))
pats pp nodes
and pp ppf x = Pp.list pp_node ppf x
let rec equal_pat a b =
match (a, b) with
| Var (_, a), Var (_, b)
| String (_, a), String (_, b)
| Enum_string (_, a), Enum_string (_, b) ->
a = b
| Bool (_, a), Bool (_, b)
| Int (_, a), Int (_, b)
| Enum_int (_, a), Enum_int (_, b) ->
a = b
| Float (_, a), Float (_, b) -> a = b
| Nullable (_, a), Nullable (_, b) -> Option.equal equal_pat a b
| List (_, a_l, a_t), List (_, b_l, b_t) ->
List.equal equal_pat a_l b_l && Option.equal equal_pat a_t b_t
| Tuple (_, a), Tuple (_, b) -> List.equal equal_pat a b
| Record (_, a), Record (_, b) -> Record.equal equal_pat a b
| Dict (_, a), Dict (_, b) -> Ast.Dict.equal equal_pat a b
| Block (_, a), Block (_, b) -> equal a b
| _ -> false
and equal_node a b =
match (a, b) with
| Text (a, a_triml, a_trimr), Text (b, b_triml, b_trimr) ->
a = b && equal_trim a_triml b_triml && equal_trim a_trimr b_trimr
| Echo (a_l, a_ech, a_esc), Echo (b_l, b_ech, b_esc) ->
List.equal equal_echo a_l b_l
&& equal_echo a_ech b_ech && equal_escape a_esc b_esc
| Match (_, a_pats, a_cases), Match (_, b_pats, b_cases) ->
Nonempty.equal equal_pat a_pats b_pats
&& Nonempty.equal equal_case a_cases b_cases
| Map_list (_, a_pat, a_cases), Map_list (_, b_pat, b_cases) ->
equal_pat a_pat b_pat && Nonempty.equal equal_case a_cases b_cases
| Map_dict (_, a_pat, a_cases), Map_dict (_, b_pat, b_cases) ->
equal_pat a_pat b_pat && Nonempty.equal equal_case a_cases b_cases
| Component (_, a_s1, a_s2, a_pats), Component (_, b_s1, b_s2, b_pats) ->
a_s1 = b_s1 && a_s2 = b_s2 && Dict.equal equal_pat a_pats b_pats
| Interface (_, a), Interface (_, b) -> List.equal Interface.equal a b
| _ -> false
and equal_case a { pats; nodes } =
Nonempty.equal (equal_pair Loc.equal (Nonempty.equal equal_pat)) a.pats pats
&& equal a.nodes nodes
and equal a b = List.equal equal_node a b
|
719c0e6db2b070d28f8b90868366cba4f6be7416a0518bf674d6073af749ac01 | haskell-repa/repa | BiMap.hs |
module Data.Repa.Store.Prim.BiMap
( BiMap
, connectWithSep
-- * Conversions
, keysFwd
, keysRev
-- * Loading
, loadRev
, loadFwd
-- * Refection
, reflect
, reflectFwd
, reflectRev)
where
import Data.IORef
import Data.Repa.Convert
import Data.Text (Text)
import Data.HashMap.Strict (HashMap)
import System.IO.Unsafe
import Data.Repa.Array.Material.Boxed
import qualified Data.HashMap.Strict as HM
import qualified Data.Repa.Array.Generic as A
import qualified Data.Repa.Array.Auto.Format as A
import qualified Data.Repa.Array.Auto.IO as A
-- | Bi-directional map backed by a flat text file which defines the mapping.
data BiMap a b
= BiMap
{ biMapPath :: FilePath -- ^ Path to the external map.
, _biMapSep :: Char -- ^ Field separator for file.
, biMapFwd :: IORef (Maybe (HashMap a b))
-- ^ Demand-loaded mapping for the forward direction.
, biMapRev :: IORef (Maybe (HashMap a b))
-- ^ Demand-loaded mapping for the reverse direction.
}
-- | Connect an external bidirectional map.
--
-- The map is defined as a flat text file, with fields separated by the
-- provided character.
--
connectWithSep
:: Char -- ^ Field separator.
-> FilePath -- ^ File that defines the mapping.
-> IO (BiMap Text Text)
connectWithSep sep path
= do refFwd <- newIORef Nothing
refRev <- newIORef Nothing
return $ BiMap path sep refFwd refRev
-- Conversions ------------------------------------------------------------------------------------
-- | Get an array of all keys in the forward direction.
keysFwd :: BiMap Text Text -> A.Array B Text
keysFwd bimap
= unsafePerformIO
$ do Just fwd <- readIORef $ biMapFwd $ loadFwd bimap
return $ A.fromList B $ HM.keys fwd
-- | Get an array of all keys in the reverse direction.
keysRev :: BiMap Text Text -> A.Array B Text
keysRev bimap
= unsafePerformIO
$ do Just rev <- readIORef $ biMapRev $ loadRev bimap
return $ A.fromList B $ HM.keys rev
-- Loading ----------------------------------------------------------------------------------------
-- | Load the complete forward direction mapping into memory.
loadFwd :: BiMap Text Text -> BiMap Text Text
loadFwd bimap
= unsafePerformIO
$ (readIORef $ biMapFwd bimap)
>>= \case
Just{}
-> return bimap
Nothing
-> do arr8 <- A.readFile $ biMapPath bimap
let !arr = A.unpacksFormatLn formatBiMap arr8
let !hm = HM.fromList $ fmap (\(k :*: v :*: ()) -> (k, v)) $ A.toList arr
writeIORef (biMapFwd bimap) (Just hm)
return bimap
-- | Load the complete forward direction mapping into memory.
loadRev :: BiMap Text Text -> BiMap Text Text
loadRev bimap
= unsafePerformIO
$ (readIORef $ biMapRev bimap)
>>= \case
Just{}
-> return bimap
Nothing
-> do arr8 <- A.readFile $ biMapPath bimap
let !arr = A.unpacksFormatLn formatBiMap arr8
let !hm = HM.fromList $ fmap (\(v :*: k :*: ()) -> (k, v)) $ A.toList arr
writeIORef (biMapRev bimap) (Just hm)
return bimap
-- Reflect ----------------------------------------------------------------------------------------
-- | Reflect both directions of a bidirectional map.
--
* The first time one of the functions is applied we demand - load the whole
table into a strict ` HashMap ` .
--
* A reference to this maybe - loaded ` HashMap ` is captured in the closure of
-- the produced functions.
--
-- * The on-disk data is not reloaded if it changes.
--
reflect :: BiMap Text Text
-> ( Text -> Maybe Text
, Text -> Maybe Text)
reflect bimap
= ( reflectFwd bimap
, reflectRev bimap)
-- | Like `reflect`, but only for the forward direction.
reflectFwd :: BiMap Text Text -> (Text -> Maybe Text)
reflectFwd bimap
= unsafePerformIO
$ do Just hm <- readIORef $ biMapFwd $ loadFwd bimap
return $ flip HM.lookup hm
-- | Like `reflect`, but only for the reverse direction.
reflectRev :: BiMap Text Text -> (Text -> Maybe Text)
reflectRev bimap
= unsafePerformIO
$ do Just hm <- readIORef $ biMapRev $ loadRev bimap
return $ flip HM.lookup hm
Format for BiMap data .
formatBiMap
= mkSep ','
$ VarText -- Datum Id
:*: VarText -- Instrument Name.
:*: ()
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-store/Data/Repa/Store/Prim/BiMap.hs | haskell | * Conversions
* Loading
* Refection
| Bi-directional map backed by a flat text file which defines the mapping.
^ Path to the external map.
^ Field separator for file.
^ Demand-loaded mapping for the forward direction.
^ Demand-loaded mapping for the reverse direction.
| Connect an external bidirectional map.
The map is defined as a flat text file, with fields separated by the
provided character.
^ Field separator.
^ File that defines the mapping.
Conversions ------------------------------------------------------------------------------------
| Get an array of all keys in the forward direction.
| Get an array of all keys in the reverse direction.
Loading ----------------------------------------------------------------------------------------
| Load the complete forward direction mapping into memory.
| Load the complete forward direction mapping into memory.
Reflect ----------------------------------------------------------------------------------------
| Reflect both directions of a bidirectional map.
the produced functions.
* The on-disk data is not reloaded if it changes.
| Like `reflect`, but only for the forward direction.
| Like `reflect`, but only for the reverse direction.
Datum Id
Instrument Name. |
module Data.Repa.Store.Prim.BiMap
( BiMap
, connectWithSep
, keysFwd
, keysRev
, loadRev
, loadFwd
, reflect
, reflectFwd
, reflectRev)
where
import Data.IORef
import Data.Repa.Convert
import Data.Text (Text)
import Data.HashMap.Strict (HashMap)
import System.IO.Unsafe
import Data.Repa.Array.Material.Boxed
import qualified Data.HashMap.Strict as HM
import qualified Data.Repa.Array.Generic as A
import qualified Data.Repa.Array.Auto.Format as A
import qualified Data.Repa.Array.Auto.IO as A
data BiMap a b
= BiMap
, biMapFwd :: IORef (Maybe (HashMap a b))
, biMapRev :: IORef (Maybe (HashMap a b))
}
connectWithSep
-> IO (BiMap Text Text)
connectWithSep sep path
= do refFwd <- newIORef Nothing
refRev <- newIORef Nothing
return $ BiMap path sep refFwd refRev
keysFwd :: BiMap Text Text -> A.Array B Text
keysFwd bimap
= unsafePerformIO
$ do Just fwd <- readIORef $ biMapFwd $ loadFwd bimap
return $ A.fromList B $ HM.keys fwd
keysRev :: BiMap Text Text -> A.Array B Text
keysRev bimap
= unsafePerformIO
$ do Just rev <- readIORef $ biMapRev $ loadRev bimap
return $ A.fromList B $ HM.keys rev
loadFwd :: BiMap Text Text -> BiMap Text Text
loadFwd bimap
= unsafePerformIO
$ (readIORef $ biMapFwd bimap)
>>= \case
Just{}
-> return bimap
Nothing
-> do arr8 <- A.readFile $ biMapPath bimap
let !arr = A.unpacksFormatLn formatBiMap arr8
let !hm = HM.fromList $ fmap (\(k :*: v :*: ()) -> (k, v)) $ A.toList arr
writeIORef (biMapFwd bimap) (Just hm)
return bimap
loadRev :: BiMap Text Text -> BiMap Text Text
loadRev bimap
= unsafePerformIO
$ (readIORef $ biMapRev bimap)
>>= \case
Just{}
-> return bimap
Nothing
-> do arr8 <- A.readFile $ biMapPath bimap
let !arr = A.unpacksFormatLn formatBiMap arr8
let !hm = HM.fromList $ fmap (\(v :*: k :*: ()) -> (k, v)) $ A.toList arr
writeIORef (biMapRev bimap) (Just hm)
return bimap
* The first time one of the functions is applied we demand - load the whole
table into a strict ` HashMap ` .
* A reference to this maybe - loaded ` HashMap ` is captured in the closure of
reflect :: BiMap Text Text
-> ( Text -> Maybe Text
, Text -> Maybe Text)
reflect bimap
= ( reflectFwd bimap
, reflectRev bimap)
reflectFwd :: BiMap Text Text -> (Text -> Maybe Text)
reflectFwd bimap
= unsafePerformIO
$ do Just hm <- readIORef $ biMapFwd $ loadFwd bimap
return $ flip HM.lookup hm
reflectRev :: BiMap Text Text -> (Text -> Maybe Text)
reflectRev bimap
= unsafePerformIO
$ do Just hm <- readIORef $ biMapRev $ loadRev bimap
return $ flip HM.lookup hm
Format for BiMap data .
formatBiMap
= mkSep ','
:*: ()
|
db68802d88b9aac1d5a098f3350988ce2e08eb83da27c5dd18c8207acceb831b | TerrorJack/ghc-alter | Integer.hs | # LANGUAGE CPP #
# LANGUAGE MagicHash #
# LANGUAGE NoImplicitPrelude #
#include "MachDeps.h"
-- |
-- Module : GHC.Integer.Type
Copyright : ( c ) 2014
-- License : BSD3
--
Maintainer :
-- Stability : provisional
Portability : non - portable ( GHC Extensions )
--
-- The 'Integer' type.
--
This module exposes the /portable/ ' Integer ' API . See
" GHC.Integer . GMP.Internals " for the @integer - gmp@-specific internal
representation of ' Integer ' as well as optimized GMP - specific
-- operations.
module GHC.Integer (
Integer,
* Construct ' Integer 's
mkInteger, smallInteger, wordToInteger,
#if WORD_SIZE_IN_BITS < 64
word64ToInteger, int64ToInteger,
#endif
-- * Conversion to other integral types
integerToWord, integerToInt,
#if WORD_SIZE_IN_BITS < 64
integerToWord64, integerToInt64,
#endif
* Helpers for ' RealFloat ' type - class operations
encodeFloatInteger, floatFromInteger,
encodeDoubleInteger, decodeDoubleInteger, doubleFromInteger,
-- * Arithmetic operations
plusInteger, minusInteger, timesInteger, negateInteger,
absInteger, signumInteger,
divModInteger, divInteger, modInteger,
quotRemInteger, quotInteger, remInteger,
-- * Comparison predicates
eqInteger, neqInteger, leInteger, gtInteger, ltInteger, geInteger,
compareInteger,
-- ** 'Int#'-boolean valued versions of comparison predicates
--
-- | These operations return @0#@ and @1#@ instead of 'False' and
-- 'True' respectively. See
-- < PrimBool wiki-page>
-- for more details
eqInteger#, neqInteger#, leInteger#, gtInteger#, ltInteger#, geInteger#,
-- * Bit-operations
andInteger, orInteger, xorInteger,
complementInteger,
shiftLInteger, shiftRInteger, testBitInteger,
-- * Hashing
hashInteger,
) where
import GHC.Integer.Type
default ()
| null | https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/integer-gmp/src/GHC/Integer.hs | haskell | |
Module : GHC.Integer.Type
License : BSD3
Stability : provisional
The 'Integer' type.
operations.
* Conversion to other integral types
* Arithmetic operations
* Comparison predicates
** 'Int#'-boolean valued versions of comparison predicates
| These operations return @0#@ and @1#@ instead of 'False' and
'True' respectively. See
< PrimBool wiki-page>
for more details
* Bit-operations
* Hashing | # LANGUAGE CPP #
# LANGUAGE MagicHash #
# LANGUAGE NoImplicitPrelude #
#include "MachDeps.h"
Copyright : ( c ) 2014
Maintainer :
Portability : non - portable ( GHC Extensions )
This module exposes the /portable/ ' Integer ' API . See
" GHC.Integer . GMP.Internals " for the @integer - gmp@-specific internal
representation of ' Integer ' as well as optimized GMP - specific
module GHC.Integer (
Integer,
* Construct ' Integer 's
mkInteger, smallInteger, wordToInteger,
#if WORD_SIZE_IN_BITS < 64
word64ToInteger, int64ToInteger,
#endif
integerToWord, integerToInt,
#if WORD_SIZE_IN_BITS < 64
integerToWord64, integerToInt64,
#endif
* Helpers for ' RealFloat ' type - class operations
encodeFloatInteger, floatFromInteger,
encodeDoubleInteger, decodeDoubleInteger, doubleFromInteger,
plusInteger, minusInteger, timesInteger, negateInteger,
absInteger, signumInteger,
divModInteger, divInteger, modInteger,
quotRemInteger, quotInteger, remInteger,
eqInteger, neqInteger, leInteger, gtInteger, ltInteger, geInteger,
compareInteger,
eqInteger#, neqInteger#, leInteger#, gtInteger#, ltInteger#, geInteger#,
andInteger, orInteger, xorInteger,
complementInteger,
shiftLInteger, shiftRInteger, testBitInteger,
hashInteger,
) where
import GHC.Integer.Type
default ()
|
fa3ad84abfec7bee14e861dc61990938eef7e4543cc7bca3151323f38245e9e5 | interline/erlang-thrift | thrift_http_transport.erl | %%
Licensed to the Apache Software Foundation ( ASF ) under one
%% or more contributor license agreements. See the NOTICE file
%% distributed with this work for additional information
%% regarding copyright ownership. The ASF licenses this file
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(thrift_http_transport).
-behaviour(thrift_transport).
%% API
-export([new/2, new/3]).
%% thrift_transport callbacks
-export([write/2, read/2, flush/1, close/1]).
-record(http_transport, {host, % string()
path, % string()
read_buffer, % iolist()
write_buffer, % iolist()
http_options, % see http(3)
[ { str ( ) , ( ) } , ... ]
}).
-type state() :: #http_transport{}.
-include("thrift_transport_behaviour.hrl").
new(Host, Path) ->
new(Host, Path, _Options = []).
%%--------------------------------------------------------------------
%% Options include:
%% {http_options, HttpOptions} = See http(3)
%% {extra_headers, ExtraHeaders} = List of extra HTTP headers
%%--------------------------------------------------------------------
new(Host, Path, Options) ->
State1 = #http_transport{host = Host,
path = Path,
read_buffer = [],
write_buffer = [],
http_options = [],
extra_headers = []},
ApplyOption =
fun
({http_options, HttpOpts}, State = #http_transport{}) ->
State#http_transport{http_options = HttpOpts};
({extra_headers, ExtraHeaders}, State = #http_transport{}) ->
State#http_transport{extra_headers = ExtraHeaders};
(Other, #http_transport{}) ->
{invalid_option, Other};
(_, Error) ->
Error
end,
case lists:foldl(ApplyOption, State1, Options) of
State2 = #http_transport{} ->
thrift_transport:new(?MODULE, State2);
Else ->
{error, Else}
end.
%% Writes data into the buffer
write(State = #http_transport{write_buffer = WBuf}, Data) ->
{State#http_transport{write_buffer = [WBuf, Data]}, ok}.
%% Flushes the buffer, making a request
flush(State = #http_transport{host = Host,
path = Path,
read_buffer = Rbuf,
write_buffer = Wbuf,
http_options = HttpOptions,
extra_headers = ExtraHeaders}) ->
case iolist_to_binary(Wbuf) of
<<>> ->
%% Don't bother flushing empty buffers.
{State, ok};
WBinary ->
{ok, {{_Version, 200, _ReasonPhrase}, _Headers, Body}} =
httpc:request(post,
{"http://" ++ Host ++ Path,
[{"User-Agent", "Erlang/thrift_http_transport"} | ExtraHeaders],
"application/x-thrift",
WBinary},
HttpOptions,
[{body_format, binary}]),
State1 = State#http_transport{read_buffer = [Rbuf, Body],
write_buffer = []},
{State1, ok}
end.
close(State) ->
{State, ok}.
read(State = #http_transport{read_buffer = RBuf}, Len) when is_integer(Len) ->
%% Pull off Give bytes, return them to the user, leave the rest in the buffer.
Give = erlang:min(iolist_size(RBuf), Len),
case iolist_to_binary(RBuf) of
<<Data:Give/binary, RBuf1/binary>> ->
Response = {ok, Data},
State1 = State#http_transport{read_buffer=RBuf1},
{State1, Response};
_ ->
{State, {error, 'EOF'}}
end.
| null | https://raw.githubusercontent.com/interline/erlang-thrift/1e0c2d2e529119d18614c16d35f7117469c26099/src/thrift_http_transport.erl | erlang |
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
"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,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
API
thrift_transport callbacks
string()
string()
iolist()
iolist()
see http(3)
--------------------------------------------------------------------
Options include:
{http_options, HttpOptions} = See http(3)
{extra_headers, ExtraHeaders} = List of extra HTTP headers
--------------------------------------------------------------------
Writes data into the buffer
Flushes the buffer, making a request
Don't bother flushing empty buffers.
Pull off Give bytes, return them to the user, leave the rest in the buffer. | Licensed to the Apache Software Foundation ( ASF ) under one
to you under the Apache License , Version 2.0 ( the
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(thrift_http_transport).
-behaviour(thrift_transport).
-export([new/2, new/3]).
-export([write/2, read/2, flush/1, close/1]).
[ { str ( ) , ( ) } , ... ]
}).
-type state() :: #http_transport{}.
-include("thrift_transport_behaviour.hrl").
new(Host, Path) ->
new(Host, Path, _Options = []).
new(Host, Path, Options) ->
State1 = #http_transport{host = Host,
path = Path,
read_buffer = [],
write_buffer = [],
http_options = [],
extra_headers = []},
ApplyOption =
fun
({http_options, HttpOpts}, State = #http_transport{}) ->
State#http_transport{http_options = HttpOpts};
({extra_headers, ExtraHeaders}, State = #http_transport{}) ->
State#http_transport{extra_headers = ExtraHeaders};
(Other, #http_transport{}) ->
{invalid_option, Other};
(_, Error) ->
Error
end,
case lists:foldl(ApplyOption, State1, Options) of
State2 = #http_transport{} ->
thrift_transport:new(?MODULE, State2);
Else ->
{error, Else}
end.
write(State = #http_transport{write_buffer = WBuf}, Data) ->
{State#http_transport{write_buffer = [WBuf, Data]}, ok}.
flush(State = #http_transport{host = Host,
path = Path,
read_buffer = Rbuf,
write_buffer = Wbuf,
http_options = HttpOptions,
extra_headers = ExtraHeaders}) ->
case iolist_to_binary(Wbuf) of
<<>> ->
{State, ok};
WBinary ->
{ok, {{_Version, 200, _ReasonPhrase}, _Headers, Body}} =
httpc:request(post,
{"http://" ++ Host ++ Path,
[{"User-Agent", "Erlang/thrift_http_transport"} | ExtraHeaders],
"application/x-thrift",
WBinary},
HttpOptions,
[{body_format, binary}]),
State1 = State#http_transport{read_buffer = [Rbuf, Body],
write_buffer = []},
{State1, ok}
end.
close(State) ->
{State, ok}.
read(State = #http_transport{read_buffer = RBuf}, Len) when is_integer(Len) ->
Give = erlang:min(iolist_size(RBuf), Len),
case iolist_to_binary(RBuf) of
<<Data:Give/binary, RBuf1/binary>> ->
Response = {ok, Data},
State1 = State#http_transport{read_buffer=RBuf1},
{State1, Response};
_ ->
{State, {error, 'EOF'}}
end.
|
7b8980b7c58de781078d73e73c2a067192096782a8932686ddfed8d711917814 | kelamg/HtDP2e-workthrough | ex23.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex23) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
; run with stepper
(define (string-first-2 s)
(substring s 0 1))
(string-first-2 "hello world") | null | https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Fixed-size-Data/ex23.rkt | racket | about the language level of this file in a form that our tools can easily process.
run with stepper | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex23) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define (string-first-2 s)
(substring s 0 1))
(string-first-2 "hello world") |
31336733a93a724ddf7995810867106bae04df44d561b996edfe5209daeda43a | roglo/mlrogue | init.ml | $ I d : init.ml , v 1.64 2013/01/29 14:00:23 deraugla Exp $
#use "rogue.def";
open Rfield;
open Rogue;
open Printf;
open Translate;
value syllabes =
[| "blech"; "foo"; "barf"; "rech"; "bar"; "quo"; "bloto"; "woh"; "caca";
"blorp"; "erp"; "festr"; "rot"; "slie"; "snorf"; "iky"; "yuky"; "ooze";
"ah"; "bahl"; "zep"; "druhl"; "flem"; "behil"; "arek"; "mep"; "zihr";
"grit"; "kona"; "kini"; "ichi"; "niah"; "ogr"; "ooh"; "ighr"; "coph";
"swerr"; "mihln"; "poxi" |]
;
value max_syllabes = Array.length syllabes;
value gems =
[| "diamond"; "stibotantalite"; "lapi-lazuli"; "ruby"; "emerald";
"sapphire"; "amethyst"; "quartz"; "tiger-eye"; "opal"; "agate";
"turquoise"; "pearl"; "garnet" |]
;
value wand_materials =
[| "steel"; "bronze"; "gold"; "silver"; "copper"; "nickel"; "cobalt"; "tin";
"iron"; "magnesium"; "chrome"; "carbon"; "platinum"; "silicon";
"titanium"; "teak"; "oak"; "cherry"; "birch"; "pine"; "cedar"; "redwood";
"balsa"; "ivory"; "walnut"; "maple"; "mahogany"; "elm"; "palm";
"wooden" |]
;
value max_metal =
loop_i 0 where rec loop_i i =
if wand_materials.(i) = "titanium" then i else loop_i (i + 1)
;
value my_int_of_string s =
let (i, sign) =
if 0 < String.length s && s.[0] = '-' then (1, -1) else (0, 1)
in
loop_i 0 i where rec loop_i n i =
if i = String.length s then sign * n
else
match s.[i] with
[ '0'..'9' -> loop_i (10 * n + Char.code s.[i] - Char.code '0') (i + 1)
| _ -> failwith "int_of_string" ]
;
type args =
{ arg_lang : mutable option string;
arg_seed : mutable (option int);
arg_robot_player : mutable option string;
arg_no_handle_robot : mutable bool;
arg_batch : mutable bool;
arg_score_only : mutable bool;
arg_backup : mutable option string;
arg_rest_file : mutable string }
;
value do_args argv =
let args =
{arg_lang = None; arg_seed = None; arg_robot_player = None;
arg_no_handle_robot = False; arg_batch = False; arg_score_only = False;
arg_backup = None; arg_rest_file = ""}
in
loop_i 1 where rec loop_i i =
if i < Array.length argv then
if argv.(i) = "-lang" && i + 1 < Array.length argv then do {
args.arg_lang := Some argv.(i+1);
loop_i (i + 2)
}
else if argv.(i) = "-seed" && i + 1 < Array.length argv then do {
args.arg_seed := Some (my_int_of_string argv.(i+1));
loop_i (i + 2)
}
else if argv.(i) = "-backup" && i + 1 < Array.length argv then do {
args.arg_backup := Some argv.(i+1);
loop_i (i + 2)
}
else if argv.(i) = "-r" && i + 1 < Array.length argv then do {
args.arg_robot_player := Some argv.(i+1);
loop_i (i + 2)
}
else if argv.(i) = "-nhr" then do {
args.arg_no_handle_robot := True;
loop_i (i + 1)
}
else if argv.(i) = "-b" then do {
args.arg_batch := True;
loop_i (i + 1)
}
else if argv.(i) = "-s" then do {
args.arg_score_only := True;
loop_i (i + 1)
}
else if argv.(i).[0] = '-' then do {
eprintf "Unknown option %s\n" argv.(i);
eprintf "\
Usage: %s [args] [restore_file]
-r <param> Robot player (<param> is either socket file or speed)
-nhr No handle robot (in case of robot exception)
-s Score only
-lang <lang> Displaying language\n"
argv.(0);
exit 2
}
else do { args.arg_rest_file := argv.(i); loop_i (i + 1) }
else args
;
value start_with s i t = Imisc.string_eq s i t 0 (String.length t);
value env_get_value s i =
loop_j i where rec loop_j j =
if j = String.length s then (String.sub s i (j - i), j)
else if s.[j] = ',' then (String.sub s i (j - i), j)
else loop_j (j + 1)
;
type opts =
{ opt_fruit : mutable string;
opt_save_file : mutable string;
opt_jump : mutable bool;
opt_nick_name : mutable string;
opt_ask_quit : mutable bool;
opt_show_skull : mutable bool;
opt_fast : mutable bool }
;
value do_opts () =
let opts =
{opt_fruit = ""; opt_save_file = ""; opt_jump = True; opt_nick_name = "";
opt_ask_quit = True; opt_show_skull = (*True*)False; opt_fast = False}
in
match try Some (Sys.getenv "ROGUEOPTS") with [ Not_found -> None ] with
[ Some eptr ->
loop_i 0 where rec loop_i i =
if i < String.length eptr then
if eptr.[i] = ' ' then loop_i (i + 1)
else
let i =
if start_with eptr i "fruit=" then do {
let i = i + String.length "fruit=" in
let (v, i) = env_get_value eptr i in
opts.opt_fruit := v;
i
}
else if start_with eptr i "file=" then do {
let i = i + String.length "file=" in
let (v, i) = env_get_value eptr i in
opts.opt_save_file := v;
i
}
else if start_with eptr i "nojump" then do {
let i = i + String.length "nojump" in
opts.opt_jump := False;
i
}
else if start_with eptr i "name=" then do {
let i = i + String.length "name=" in
let (v, i) = env_get_value eptr i in
opts.opt_nick_name := v;
i
}
else if start_with eptr i "noaskquit" then do {
let i = i + String.length "noaskquit" in
opts.opt_ask_quit := False;
i
}
else if start_with eptr i "noskull" then do {
let i = i + String.length "noskull" in
opts.opt_show_skull := False;
i
}
else if start_with eptr i "notomb" then do {
let i = i + String.length "notomb" in
opts.opt_show_skull := False;
i
}
else if start_with eptr i "fast" then do {
let i = i + String.length "fast" in
opts.opt_fast := True;
i
}
else i + 1
in
let i =
if i < String.length eptr && eptr.[i] = ',' then i + 1 else i
in
loop_i i
else opts
| None -> opts ]
;
value mix_colours g = do {
let len = Array.length Object.colours in
let mix = Array.init len (fun i -> i) in
for i = 0 to 31 do {
let j = Imisc.get_rand 0 (len - 1) in
let k = Imisc.get_rand 0 (len - 1) in
let t = mix.(j) in
mix.(j) := mix.(k);
mix.(k) := t;
};
for i = 0 to Array.length Object.potion_tab - 1 do {
g.id_potions.(i) := Unidentified Object.colours.(mix.(i));
}
};
value get_wand_and_ring_materials g = do {
let used = Array.make (Array.length wand_materials) False in
for i = 0 to Array.length Object.wand_tab - 1 do {
let j =
loop () where rec loop () =
let j = Imisc.get_rand 0 (Array.length wand_materials - 1) in
if used.(j) then loop () else j
in
used.(j) := True;
g.id_wands.(i) := Unidentified wand_materials.(j);
g.is_wood.(i) := j > max_metal;
};
let used = Array.make (Array.length gems) False in
for i = 0 to Array.length Object.ring_tab - 1 do {
let j =
loop () where rec loop () =
let j = Imisc.get_rand 0 (Array.length gems - 1) in
if used.(j) then loop () else j
in
used.(j) := True;
g.id_rings.(i) := Unidentified gems.(j);
}
};
value make_scroll_titles g =
for i = 0 to Array.length Object.scroll_tab - 1 do {
let sylls = Imisc.get_rand 2 5 in
let title =
loop "" 0 where rec loop t j =
if j = sylls then t
else
let s = Imisc.get_rand 1 max_syllabes - 1 in
let syll = syllabes.(s) in
loop (if t = "" then syll else t ^ " " ^ syll) (j + 1)
in
g.id_scrolls.(i) := Unidentified (sprintf "'%s'" title);
}
;
value player_init g = do {
g.rogue.pack := [];
let _ : (char * objet) =
let ob = Object.get_food (Some Ration) in
Imisc.add_to_pack g ob
in
let a =
{ar_kind = Ringmail; ar_class = 3; ar_is_cursed = False;
ar_is_protected = False; ar_enchant = 1; ar_in_use = False;
ar_identified = False}
in
let (c, _) =
let ob = Object.create_obj (Armor a) 1 in
Imisc.add_to_pack g ob
in
Imisc.do_wear g c a;
let w =
{we_kind = Mace; we_damage = (2, 3, None); we_quiver = 0;
we_is_cursed = False; we_has_been_uncursed = False; we_hit_enchant = 1;
we_d_enchant = 1; we_in_use = False; we_identified = True}
in
let (c, _) =
let ob = Object.create_obj (Weapon w) 1 in
Imisc.add_to_pack g ob
in
Imisc.do_wield g c w;
let w =
{we_kind = Bow; we_damage = (1, 2, None); we_quiver = 0;
we_is_cursed = False; we_has_been_uncursed = False; we_hit_enchant = 1;
we_d_enchant = 0; we_in_use = False; we_identified = True}
in
let _ : (char * objet) =
let ob = Object.create_obj (Weapon w) 1 in
Imisc.add_to_pack g ob
in
let w =
{we_kind = Arrow; we_damage = (1, 2, None); we_quiver = 1;
we_is_cursed = False; we_has_been_uncursed = False; we_hit_enchant = 0;
we_d_enchant = 0; we_in_use = False; we_identified = True}
in
let _ : (char * objet) =
let q = Imisc.get_rand 25 35 in
let ob = Object.create_obj (Weapon w) q in
Imisc.add_to_pack g ob
in
()
};
value create_g saved_uid true_uid login_name args opts lang = do {
let empty_room _ =
{bottom_row = 0; right_col = 0; left_col = 0; top_row = 0;
doors = Array.make 4 None; is_room = 0}
in
let rogue =
{armor = None; weapon = None; gold = 0; hp_current = INIT_HP;
hp_max = INIT_HP; extra_hp = 0; less_hp = 0; str_current = 16;
str_max = 16; exp = 1; exp_points = 0; pack = []; row = 0; col = 0;
fight_monster = None; moves_left = 1250; confused = 0; blind = 0;
halluc = 0; see_invisible = False; detect_monster = False; levitate = 0;
haste_self = 0; bear_trap = 0; being_held = False; stealthy = 0;
left_ring = None; right_ring = None; e_rings = 0; r_rings = 0;
r_teleport = False; r_see_invisible = False; maintain_armor = False;
sustain_strength = False; add_strength = 0; regeneration = 0;
ring_exp = 0; auto_search = 0; fchar = '@'}
in
let fruit =
if opts.opt_fruit <> "" then opts.opt_fruit else Object.default_fruit
in
let env = Efield.make () in
{saved_uid = saved_uid; true_uid = true_uid; cur_level = 0; max_level = 1;
cur_room = None; lang = lang; score_only = args.arg_score_only;
save_file = opts.opt_save_file; nick_name = opts.opt_nick_name;
login_name = login_name; fruit = fruit; ask_quit = opts.opt_ask_quit;
show_skull = opts.opt_show_skull; jump = opts.opt_jump; party_counter = 0;
party_room = None; foods = 0; r_de = None; trap_door = False;
interrupted = False; can_int = False; reg_search = False;
level_objects = []; level_monsters = []; new_level_message = "";
monsters_count = 0; mon_disappeared = False; hunger_str = "";
hit_message = ""; msg_line = ""; msg_col = 0; msg_cleared = True;
same_msg = 0; m_moves = 0; wizard = False;
experimented_pick_up_scare_monster = False; rogue = rogue;
random_rooms = [| 3; 7; 5; 2; 0; 6; 1; 4; 8 |];
id_potions = Array.make (Array.length Object.potion_tab) Identified;
id_rings = Array.make (Array.length Object.ring_tab) Identified;
id_scrolls = Array.make (Array.length Object.scroll_tab) Identified;
id_wands = Array.make (Array.length Object.wand_tab) Identified;
is_wood = Array.make (Array.length Object.wand_tab) False;
rooms = Array.init MAXROOMS empty_room; traps = Array.make MAX_TRAPS None;
dungeon = Array.make_matrix DROWS DCOLS 0; env = env}
};
type init =
[ NewGame of game
| RestoreGame of string
| ScoreOnly ]
;
value robot_env nhr =
fun
[ Some str ->
let locrob =
if str = "" then Some ""
else
match str.[0] with
[ '0'..'9' -> Some str
| _ -> None ]
in
match locrob with
[ Some str -> Some (PSrobot (Robot.make str), nhr)
| None -> Some (PSsocket (Rogbotio.socket str), nhr) ]
| None -> None ]
;
value backup_env =
fun
[ Some str -> Some (str, 0)
| None -> None ]
;
value f argv = do {
let saved_uid = Unix.geteuid () in
let true_uid = Unix.getuid () in
Unix.setuid true_uid;
let login_name = (Unix.getpwuid (Unix.getuid ())).Unix.pw_name in
let args = do_args argv in
match args.arg_seed with
[ Some seed -> Random.init seed
| None -> Random.self_init () ];
let opts = do_opts () in
let lang =
match args.arg_lang with
[ Some lang -> lang
| None -> try Sys.getenv "LANG" with [ Not_found -> "" ] ]
in
let r =
if args.arg_score_only then ScoreOnly
else if args.arg_rest_file <> "" then RestoreGame args.arg_rest_file
else do {
if not opts.opt_fast then do {
printf
(ftransl lang
"Hello %s, just a moment while I dig the dungeon...")
(if opts.opt_nick_name <> "" then opts.opt_nick_name
else login_name);
flush stdout;
Unix.sleep 2;
}
else ();
let g = create_g saved_uid true_uid login_name args opts lang in
mix_colours g;
get_wand_and_ring_materials g;
make_scroll_titles g;
player_init g;
g.party_counter := Imisc.get_rand 1 PARTY_TIME;
NewGame g
}
in
let no_handle_robot = args.arg_no_handle_robot || args.arg_batch in
let robenv = robot_env no_handle_robot args.arg_robot_player in
let backupenv = backup_env args.arg_backup in
let fast = opts.opt_fast || args.arg_batch in
let batch = args.arg_batch in
let no_record_score = args.arg_seed <> None || args.arg_backup <> None in
(lang, r, robenv, backupenv, fast, batch, no_record_score)
};
| null | https://raw.githubusercontent.com/roglo/mlrogue/b73238bbbc8cd88c83579c3b72772a8c418020e5/init.ml | ocaml | True | $ I d : init.ml , v 1.64 2013/01/29 14:00:23 deraugla Exp $
#use "rogue.def";
open Rfield;
open Rogue;
open Printf;
open Translate;
value syllabes =
[| "blech"; "foo"; "barf"; "rech"; "bar"; "quo"; "bloto"; "woh"; "caca";
"blorp"; "erp"; "festr"; "rot"; "slie"; "snorf"; "iky"; "yuky"; "ooze";
"ah"; "bahl"; "zep"; "druhl"; "flem"; "behil"; "arek"; "mep"; "zihr";
"grit"; "kona"; "kini"; "ichi"; "niah"; "ogr"; "ooh"; "ighr"; "coph";
"swerr"; "mihln"; "poxi" |]
;
value max_syllabes = Array.length syllabes;
value gems =
[| "diamond"; "stibotantalite"; "lapi-lazuli"; "ruby"; "emerald";
"sapphire"; "amethyst"; "quartz"; "tiger-eye"; "opal"; "agate";
"turquoise"; "pearl"; "garnet" |]
;
value wand_materials =
[| "steel"; "bronze"; "gold"; "silver"; "copper"; "nickel"; "cobalt"; "tin";
"iron"; "magnesium"; "chrome"; "carbon"; "platinum"; "silicon";
"titanium"; "teak"; "oak"; "cherry"; "birch"; "pine"; "cedar"; "redwood";
"balsa"; "ivory"; "walnut"; "maple"; "mahogany"; "elm"; "palm";
"wooden" |]
;
value max_metal =
loop_i 0 where rec loop_i i =
if wand_materials.(i) = "titanium" then i else loop_i (i + 1)
;
value my_int_of_string s =
let (i, sign) =
if 0 < String.length s && s.[0] = '-' then (1, -1) else (0, 1)
in
loop_i 0 i where rec loop_i n i =
if i = String.length s then sign * n
else
match s.[i] with
[ '0'..'9' -> loop_i (10 * n + Char.code s.[i] - Char.code '0') (i + 1)
| _ -> failwith "int_of_string" ]
;
type args =
{ arg_lang : mutable option string;
arg_seed : mutable (option int);
arg_robot_player : mutable option string;
arg_no_handle_robot : mutable bool;
arg_batch : mutable bool;
arg_score_only : mutable bool;
arg_backup : mutable option string;
arg_rest_file : mutable string }
;
value do_args argv =
let args =
{arg_lang = None; arg_seed = None; arg_robot_player = None;
arg_no_handle_robot = False; arg_batch = False; arg_score_only = False;
arg_backup = None; arg_rest_file = ""}
in
loop_i 1 where rec loop_i i =
if i < Array.length argv then
if argv.(i) = "-lang" && i + 1 < Array.length argv then do {
args.arg_lang := Some argv.(i+1);
loop_i (i + 2)
}
else if argv.(i) = "-seed" && i + 1 < Array.length argv then do {
args.arg_seed := Some (my_int_of_string argv.(i+1));
loop_i (i + 2)
}
else if argv.(i) = "-backup" && i + 1 < Array.length argv then do {
args.arg_backup := Some argv.(i+1);
loop_i (i + 2)
}
else if argv.(i) = "-r" && i + 1 < Array.length argv then do {
args.arg_robot_player := Some argv.(i+1);
loop_i (i + 2)
}
else if argv.(i) = "-nhr" then do {
args.arg_no_handle_robot := True;
loop_i (i + 1)
}
else if argv.(i) = "-b" then do {
args.arg_batch := True;
loop_i (i + 1)
}
else if argv.(i) = "-s" then do {
args.arg_score_only := True;
loop_i (i + 1)
}
else if argv.(i).[0] = '-' then do {
eprintf "Unknown option %s\n" argv.(i);
eprintf "\
Usage: %s [args] [restore_file]
-r <param> Robot player (<param> is either socket file or speed)
-nhr No handle robot (in case of robot exception)
-s Score only
-lang <lang> Displaying language\n"
argv.(0);
exit 2
}
else do { args.arg_rest_file := argv.(i); loop_i (i + 1) }
else args
;
value start_with s i t = Imisc.string_eq s i t 0 (String.length t);
value env_get_value s i =
loop_j i where rec loop_j j =
if j = String.length s then (String.sub s i (j - i), j)
else if s.[j] = ',' then (String.sub s i (j - i), j)
else loop_j (j + 1)
;
type opts =
{ opt_fruit : mutable string;
opt_save_file : mutable string;
opt_jump : mutable bool;
opt_nick_name : mutable string;
opt_ask_quit : mutable bool;
opt_show_skull : mutable bool;
opt_fast : mutable bool }
;
value do_opts () =
let opts =
{opt_fruit = ""; opt_save_file = ""; opt_jump = True; opt_nick_name = "";
in
match try Some (Sys.getenv "ROGUEOPTS") with [ Not_found -> None ] with
[ Some eptr ->
loop_i 0 where rec loop_i i =
if i < String.length eptr then
if eptr.[i] = ' ' then loop_i (i + 1)
else
let i =
if start_with eptr i "fruit=" then do {
let i = i + String.length "fruit=" in
let (v, i) = env_get_value eptr i in
opts.opt_fruit := v;
i
}
else if start_with eptr i "file=" then do {
let i = i + String.length "file=" in
let (v, i) = env_get_value eptr i in
opts.opt_save_file := v;
i
}
else if start_with eptr i "nojump" then do {
let i = i + String.length "nojump" in
opts.opt_jump := False;
i
}
else if start_with eptr i "name=" then do {
let i = i + String.length "name=" in
let (v, i) = env_get_value eptr i in
opts.opt_nick_name := v;
i
}
else if start_with eptr i "noaskquit" then do {
let i = i + String.length "noaskquit" in
opts.opt_ask_quit := False;
i
}
else if start_with eptr i "noskull" then do {
let i = i + String.length "noskull" in
opts.opt_show_skull := False;
i
}
else if start_with eptr i "notomb" then do {
let i = i + String.length "notomb" in
opts.opt_show_skull := False;
i
}
else if start_with eptr i "fast" then do {
let i = i + String.length "fast" in
opts.opt_fast := True;
i
}
else i + 1
in
let i =
if i < String.length eptr && eptr.[i] = ',' then i + 1 else i
in
loop_i i
else opts
| None -> opts ]
;
value mix_colours g = do {
let len = Array.length Object.colours in
let mix = Array.init len (fun i -> i) in
for i = 0 to 31 do {
let j = Imisc.get_rand 0 (len - 1) in
let k = Imisc.get_rand 0 (len - 1) in
let t = mix.(j) in
mix.(j) := mix.(k);
mix.(k) := t;
};
for i = 0 to Array.length Object.potion_tab - 1 do {
g.id_potions.(i) := Unidentified Object.colours.(mix.(i));
}
};
value get_wand_and_ring_materials g = do {
let used = Array.make (Array.length wand_materials) False in
for i = 0 to Array.length Object.wand_tab - 1 do {
let j =
loop () where rec loop () =
let j = Imisc.get_rand 0 (Array.length wand_materials - 1) in
if used.(j) then loop () else j
in
used.(j) := True;
g.id_wands.(i) := Unidentified wand_materials.(j);
g.is_wood.(i) := j > max_metal;
};
let used = Array.make (Array.length gems) False in
for i = 0 to Array.length Object.ring_tab - 1 do {
let j =
loop () where rec loop () =
let j = Imisc.get_rand 0 (Array.length gems - 1) in
if used.(j) then loop () else j
in
used.(j) := True;
g.id_rings.(i) := Unidentified gems.(j);
}
};
value make_scroll_titles g =
for i = 0 to Array.length Object.scroll_tab - 1 do {
let sylls = Imisc.get_rand 2 5 in
let title =
loop "" 0 where rec loop t j =
if j = sylls then t
else
let s = Imisc.get_rand 1 max_syllabes - 1 in
let syll = syllabes.(s) in
loop (if t = "" then syll else t ^ " " ^ syll) (j + 1)
in
g.id_scrolls.(i) := Unidentified (sprintf "'%s'" title);
}
;
value player_init g = do {
g.rogue.pack := [];
let _ : (char * objet) =
let ob = Object.get_food (Some Ration) in
Imisc.add_to_pack g ob
in
let a =
{ar_kind = Ringmail; ar_class = 3; ar_is_cursed = False;
ar_is_protected = False; ar_enchant = 1; ar_in_use = False;
ar_identified = False}
in
let (c, _) =
let ob = Object.create_obj (Armor a) 1 in
Imisc.add_to_pack g ob
in
Imisc.do_wear g c a;
let w =
{we_kind = Mace; we_damage = (2, 3, None); we_quiver = 0;
we_is_cursed = False; we_has_been_uncursed = False; we_hit_enchant = 1;
we_d_enchant = 1; we_in_use = False; we_identified = True}
in
let (c, _) =
let ob = Object.create_obj (Weapon w) 1 in
Imisc.add_to_pack g ob
in
Imisc.do_wield g c w;
let w =
{we_kind = Bow; we_damage = (1, 2, None); we_quiver = 0;
we_is_cursed = False; we_has_been_uncursed = False; we_hit_enchant = 1;
we_d_enchant = 0; we_in_use = False; we_identified = True}
in
let _ : (char * objet) =
let ob = Object.create_obj (Weapon w) 1 in
Imisc.add_to_pack g ob
in
let w =
{we_kind = Arrow; we_damage = (1, 2, None); we_quiver = 1;
we_is_cursed = False; we_has_been_uncursed = False; we_hit_enchant = 0;
we_d_enchant = 0; we_in_use = False; we_identified = True}
in
let _ : (char * objet) =
let q = Imisc.get_rand 25 35 in
let ob = Object.create_obj (Weapon w) q in
Imisc.add_to_pack g ob
in
()
};
value create_g saved_uid true_uid login_name args opts lang = do {
let empty_room _ =
{bottom_row = 0; right_col = 0; left_col = 0; top_row = 0;
doors = Array.make 4 None; is_room = 0}
in
let rogue =
{armor = None; weapon = None; gold = 0; hp_current = INIT_HP;
hp_max = INIT_HP; extra_hp = 0; less_hp = 0; str_current = 16;
str_max = 16; exp = 1; exp_points = 0; pack = []; row = 0; col = 0;
fight_monster = None; moves_left = 1250; confused = 0; blind = 0;
halluc = 0; see_invisible = False; detect_monster = False; levitate = 0;
haste_self = 0; bear_trap = 0; being_held = False; stealthy = 0;
left_ring = None; right_ring = None; e_rings = 0; r_rings = 0;
r_teleport = False; r_see_invisible = False; maintain_armor = False;
sustain_strength = False; add_strength = 0; regeneration = 0;
ring_exp = 0; auto_search = 0; fchar = '@'}
in
let fruit =
if opts.opt_fruit <> "" then opts.opt_fruit else Object.default_fruit
in
let env = Efield.make () in
{saved_uid = saved_uid; true_uid = true_uid; cur_level = 0; max_level = 1;
cur_room = None; lang = lang; score_only = args.arg_score_only;
save_file = opts.opt_save_file; nick_name = opts.opt_nick_name;
login_name = login_name; fruit = fruit; ask_quit = opts.opt_ask_quit;
show_skull = opts.opt_show_skull; jump = opts.opt_jump; party_counter = 0;
party_room = None; foods = 0; r_de = None; trap_door = False;
interrupted = False; can_int = False; reg_search = False;
level_objects = []; level_monsters = []; new_level_message = "";
monsters_count = 0; mon_disappeared = False; hunger_str = "";
hit_message = ""; msg_line = ""; msg_col = 0; msg_cleared = True;
same_msg = 0; m_moves = 0; wizard = False;
experimented_pick_up_scare_monster = False; rogue = rogue;
random_rooms = [| 3; 7; 5; 2; 0; 6; 1; 4; 8 |];
id_potions = Array.make (Array.length Object.potion_tab) Identified;
id_rings = Array.make (Array.length Object.ring_tab) Identified;
id_scrolls = Array.make (Array.length Object.scroll_tab) Identified;
id_wands = Array.make (Array.length Object.wand_tab) Identified;
is_wood = Array.make (Array.length Object.wand_tab) False;
rooms = Array.init MAXROOMS empty_room; traps = Array.make MAX_TRAPS None;
dungeon = Array.make_matrix DROWS DCOLS 0; env = env}
};
type init =
[ NewGame of game
| RestoreGame of string
| ScoreOnly ]
;
value robot_env nhr =
fun
[ Some str ->
let locrob =
if str = "" then Some ""
else
match str.[0] with
[ '0'..'9' -> Some str
| _ -> None ]
in
match locrob with
[ Some str -> Some (PSrobot (Robot.make str), nhr)
| None -> Some (PSsocket (Rogbotio.socket str), nhr) ]
| None -> None ]
;
value backup_env =
fun
[ Some str -> Some (str, 0)
| None -> None ]
;
value f argv = do {
let saved_uid = Unix.geteuid () in
let true_uid = Unix.getuid () in
Unix.setuid true_uid;
let login_name = (Unix.getpwuid (Unix.getuid ())).Unix.pw_name in
let args = do_args argv in
match args.arg_seed with
[ Some seed -> Random.init seed
| None -> Random.self_init () ];
let opts = do_opts () in
let lang =
match args.arg_lang with
[ Some lang -> lang
| None -> try Sys.getenv "LANG" with [ Not_found -> "" ] ]
in
let r =
if args.arg_score_only then ScoreOnly
else if args.arg_rest_file <> "" then RestoreGame args.arg_rest_file
else do {
if not opts.opt_fast then do {
printf
(ftransl lang
"Hello %s, just a moment while I dig the dungeon...")
(if opts.opt_nick_name <> "" then opts.opt_nick_name
else login_name);
flush stdout;
Unix.sleep 2;
}
else ();
let g = create_g saved_uid true_uid login_name args opts lang in
mix_colours g;
get_wand_and_ring_materials g;
make_scroll_titles g;
player_init g;
g.party_counter := Imisc.get_rand 1 PARTY_TIME;
NewGame g
}
in
let no_handle_robot = args.arg_no_handle_robot || args.arg_batch in
let robenv = robot_env no_handle_robot args.arg_robot_player in
let backupenv = backup_env args.arg_backup in
let fast = opts.opt_fast || args.arg_batch in
let batch = args.arg_batch in
let no_record_score = args.arg_seed <> None || args.arg_backup <> None in
(lang, r, robenv, backupenv, fast, batch, no_record_score)
};
|
7c47757184cf46748fea2bf00a1ae9082751eac443262760729b2309f00330e5 | turquoise-hexagon/euler | solution.scm | (import
(euler)
(srfi 1))
(define (diagonals n)
`(,(+ (* 4 n n) (* 4 n) 1)
,(+ (* 4 n n) (* 2 n) 1)
,(- (* 4 n n) (* 2 n) -1)
,(+ (* 4 n n) 1)))
(define (solve)
(let loop ((i 1) (primes 0) (total 1))
(let ((primes (+ primes (count prime? (diagonals i)))) (total (+ total 4)))
(if (> 1/10 (/ primes total))
(+ (* 2 i) 1)
(loop (+ i 1) primes total)))))
(let ((_ (solve)))
(print _) (assert (= _ 26241)))
| null | https://raw.githubusercontent.com/turquoise-hexagon/euler/592c5f4f45fe8e8b82102be9fe11b3b1134d98fc/src/058/solution.scm | scheme | (import
(euler)
(srfi 1))
(define (diagonals n)
`(,(+ (* 4 n n) (* 4 n) 1)
,(+ (* 4 n n) (* 2 n) 1)
,(- (* 4 n n) (* 2 n) -1)
,(+ (* 4 n n) 1)))
(define (solve)
(let loop ((i 1) (primes 0) (total 1))
(let ((primes (+ primes (count prime? (diagonals i)))) (total (+ total 4)))
(if (> 1/10 (/ primes total))
(+ (* 2 i) 1)
(loop (+ i 1) primes total)))))
(let ((_ (solve)))
(print _) (assert (= _ 26241)))
|
|
eecd1455e483eaa2f27ce05cf585cb48f24edf0fc535b588aece73d703e3cb35 | mitchellwrosen/hspolls | Response.hs | module Hp.GitHub.Response
( GitHubResponse(..)
) where
import Hp.GitHub.ErrorResponse (GitHubErrorResponse)
import Data.Aeson (FromJSON(..), Value)
import Data.Aeson.Types (Parser)
data GitHubResponse a
= GitHubResponseError GitHubErrorResponse
| GitHubResponseSuccess a
deriving stock (Show)
instance FromJSON a => FromJSON (GitHubResponse a) where
parseJSON :: Value -> Parser (GitHubResponse a)
parseJSON value =
asum
[ GitHubResponseError <$> parseJSON value
, GitHubResponseSuccess <$> parseJSON value
]
| null | https://raw.githubusercontent.com/mitchellwrosen/hspolls/22efea743194ade091f7daa112a2d9ce985a4500/src/Hp/GitHub/Response.hs | haskell | module Hp.GitHub.Response
( GitHubResponse(..)
) where
import Hp.GitHub.ErrorResponse (GitHubErrorResponse)
import Data.Aeson (FromJSON(..), Value)
import Data.Aeson.Types (Parser)
data GitHubResponse a
= GitHubResponseError GitHubErrorResponse
| GitHubResponseSuccess a
deriving stock (Show)
instance FromJSON a => FromJSON (GitHubResponse a) where
parseJSON :: Value -> Parser (GitHubResponse a)
parseJSON value =
asum
[ GitHubResponseError <$> parseJSON value
, GitHubResponseSuccess <$> parseJSON value
]
|
|
3beee4bcaf08e96686ca68de3c5559149573a814a1207255c1e58eff53aecdf1 | futurice/haskell-mega-repo | Ctx.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TemplateHaskell #-}
module Futurice.App.Proxy.Ctx where
import Futurice.Postgres
import Futurice.Prelude
import Futurice.Services (Service (..))
import Prelude ()
import Futurice.App.Proxy.Endpoint (HasClientBaseurl (..), HasHttpManager (..))
import Futurice.App.Proxy.Config
| Context type , holds http manager and baseurl configurations
data Ctx = Ctx
{ _ctxManager :: !Manager
, ctxPostgresPool :: !(Pool Connection)
, ctxLogger :: !Logger
-- Base URLS
, _ctxConfig :: !Config
}
instance HasPostgresPool Ctx where
postgresPool = ctxPostgresPool
makeLenses ''Ctx
-------------------------------------------------------------------------------
-- Instances
-------------------------------------------------------------------------------
instance HasHttpManager Ctx where
httpManager = ctxManager
instance HasClientBaseurl Ctx 'AvatarService where clientBaseurl _ = ctxConfig . cfgAvatarBaseurl
instance HasClientBaseurl Ctx 'ReportsService where clientBaseurl _ = ctxConfig . cfgReportsAppBaseurl
instance HasClientBaseurl Ctx 'FumCarbonService where clientBaseurl _ = ctxConfig . cfgFumCarbonBaseurl
instance HasClientBaseurl Ctx 'PlanmillProxyService where clientBaseurl _ = ctxConfig . cfgPlanmillProxyBaseurl
instance HasClientBaseurl Ctx 'GithubProxyService where clientBaseurl _ = ctxConfig . cfgGithubProxyBaseurl
instance HasClientBaseurl Ctx 'PowerService where clientBaseurl _ = ctxConfig . cfgPowerBaseurl
instance HasClientBaseurl Ctx 'PersonioProxyService where clientBaseurl _ = ctxConfig . cfgPersonioProxyBaseurl
instance HasClientBaseurl Ctx 'ContactsApiService where clientBaseurl _ = ctxConfig . cfgContactsApiBaseurl
instance HasClientBaseurl Ctx 'SmsProxyService where clientBaseurl _ = ctxConfig . cfgSmsProxyBaseurl
instance HasClientBaseurl Ctx 'LibraryService where clientBaseurl _ = ctxConfig . cfgLibraryBaseurl
instance HasClientBaseurl Ctx 'OktaProxyService where clientBaseurl _ = ctxConfig . cfgOktaProxyBaseUrl
| null | https://raw.githubusercontent.com/futurice/haskell-mega-repo/2647723f12f5435e2edc373f6738386a9668f603/proxy-app/src/Futurice/App/Proxy/Ctx.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE TemplateHaskell #
Base URLS
-----------------------------------------------------------------------------
Instances
----------------------------------------------------------------------------- | # LANGUAGE MultiParamTypeClasses #
module Futurice.App.Proxy.Ctx where
import Futurice.Postgres
import Futurice.Prelude
import Futurice.Services (Service (..))
import Prelude ()
import Futurice.App.Proxy.Endpoint (HasClientBaseurl (..), HasHttpManager (..))
import Futurice.App.Proxy.Config
| Context type , holds http manager and baseurl configurations
data Ctx = Ctx
{ _ctxManager :: !Manager
, ctxPostgresPool :: !(Pool Connection)
, ctxLogger :: !Logger
, _ctxConfig :: !Config
}
instance HasPostgresPool Ctx where
postgresPool = ctxPostgresPool
makeLenses ''Ctx
instance HasHttpManager Ctx where
httpManager = ctxManager
instance HasClientBaseurl Ctx 'AvatarService where clientBaseurl _ = ctxConfig . cfgAvatarBaseurl
instance HasClientBaseurl Ctx 'ReportsService where clientBaseurl _ = ctxConfig . cfgReportsAppBaseurl
instance HasClientBaseurl Ctx 'FumCarbonService where clientBaseurl _ = ctxConfig . cfgFumCarbonBaseurl
instance HasClientBaseurl Ctx 'PlanmillProxyService where clientBaseurl _ = ctxConfig . cfgPlanmillProxyBaseurl
instance HasClientBaseurl Ctx 'GithubProxyService where clientBaseurl _ = ctxConfig . cfgGithubProxyBaseurl
instance HasClientBaseurl Ctx 'PowerService where clientBaseurl _ = ctxConfig . cfgPowerBaseurl
instance HasClientBaseurl Ctx 'PersonioProxyService where clientBaseurl _ = ctxConfig . cfgPersonioProxyBaseurl
instance HasClientBaseurl Ctx 'ContactsApiService where clientBaseurl _ = ctxConfig . cfgContactsApiBaseurl
instance HasClientBaseurl Ctx 'SmsProxyService where clientBaseurl _ = ctxConfig . cfgSmsProxyBaseurl
instance HasClientBaseurl Ctx 'LibraryService where clientBaseurl _ = ctxConfig . cfgLibraryBaseurl
instance HasClientBaseurl Ctx 'OktaProxyService where clientBaseurl _ = ctxConfig . cfgOktaProxyBaseUrl
|
ce74d8f24535daeee943ac2bf6114b837eac44799e27d65ffabcd71ee23fcc6d | cl-axon/cl-aima | shopping.lisp | ;;; File: shopping.lisp -*- Mode: Lisp; Syntax: Common-Lisp; -*-
The Shopping World :
;;; Warning! This code has not yet been tested or debugged!
(defparameter *page250-supermarket*
'((at edge wall)
(at (1 1) (sign :words (exit)))
(at (and (2 2) (6 2)) shopper)
(at (and (3 2) (7 2)) cashier-stand)
(at (and (4 2) (8 2) (4 7)) cashier)
(at (2 4) (sign :words (Aisle 1 Vegetables)))
(at (2 5) (-15 tomato) (sign :words (Tomatoes $ .79 lb)))
(at (2 6) (-6 lettuce) (sign :words (Lettuce $ .89)))
(at (2 7) (-8 onion) (sign :words (Onion $ .49 lb)))
(at (3 4) (sign :words (Aisle 2 Fruit)))
(at (3 5) (-12 apple) (sign :words (Apples $ .69 lb)))
(at (3 6) (-9 orange) (sign :words (Oranges $ .75 lb)))
(at (3 7) (-3 grapefruit :size 0.06 :color yellow)
(-3 grapefruit :size 0.07 :color pink)
(sign :words (Grapefruit $ .49 each)))
;; The rest of the store is temporarily out of stock ...
(at (5 4) (sign :words (Aisle 3 Soup Sauces)))
(at (6 4) (sign :words (Aisle 4 Meat)))
(at (8 4) (sign :words (Aisle 5 Sundries)))
))
(defstructure (shopping-world (:include grid-environment
(aspec '(shopping-agent))
(bspec *page250-supermarket*))))
;;;; New Structures
(defstructure (credit-card (:include object (name "$"))))
(defstructure (food (:include object (shape :round) (size .1) (name 'f))))
(defstructure (tomato (:include food (color 'red) (size .08) (name 't))))
(defstructure (lettuce (:include food (color 'green) (size .09) (name 'l))))
(defstructure (onion (:include food (color 'yellow) (size .07) (name 'o))))
(defstructure (orange (:include food (color 'orange) (size .07) (name 'o))))
(defstructure (apple (:include food (color 'red) (size .07) (name 'a))))
(defstructure (grapefruit (:include food (color 'yellow) (size .1) (name 'g))))
(defstructure (sign (:include object (name 'S) (size .09)
(color '(white (with black)))))
(words '()))
(defstructure (cashier-stand (:include object (color '(black (with chrome)))
(shape 'flat) (size .9) (name 'C))))
(defstructure (cashier (:include agent-body (name "c"))))
(defstructure (seeing-agent-body (:include agent-body (name ":")))
(zoomed-at nil) ; Some have a camera to zoom in and out at a location
(can-zoom-at '((0 0) (0 +1) (+1 +1) (-1 +1)))
(visible-offsets '((0 +1) (+1 +1) (-1 +1))))
(defstructure (shopper (:include seeing-agent-body (name "@")
(contents (list (make-credit-card))))))
;;;; Percepts
(defmethod get-percept ((env shopping-world) agent)
"The percept is a sequence of sights, touch (i.e. bump), and sounds."
(list (see agent env) (feel agent env) (hear agent env)))
(defun see (agent env)
"Return a list of visual percepts for an agent. Note the agent's camera may
either be zoomed out, so that it sees several squares, or zoomed in on one."
(let* ((body (agent-body agent))
(zoomed-at (seeing-agent-body-zoomed-at body)))
(mappend #'(lambda (offset)
(see-loc (absolute-loc body offset) env zoomed-at))
(seeing-agent-body-visible-offsets body))))
(defun feel (agent env)
(declare (ignore env))
(if (object-bump (agent-body agent)) 'bump))
(defun hear (agent env)
We can hear anything within 2 squares
(let* ((body (agent-body agent))
(loc (object-loc body))
(objects nil))
(for each obj in (grid-environment-objects env) do
(when (and (object-sound obj) (near? (object-loc obj) loc 2))
(push (object-sound obj) objects)))
objects))
(defun see-loc (loc env zoomed-at)
(let ((objects (grid-contents env loc)))
(if zoomed-at
(mappend #'appearance objects)
(appearance objects))))
(defun appearance (object)
"Return a list of visual attributes: (loc size color shape words)"
(list (object-loc object) (fuzz (object-size object)) (object-color object)
(object-shape object) (object-words object)))
(defun object-words (object)
(if (sign-p object)
(sign-words object)
nil))
(defun zoom (agent-body env offset)
"Zoom the camera at an offset if it is feasible; otherwise zoom out."
(declare (ignore env))
(cond ((member offset (seeing-agent-body-can-zoom-at agent-body))
(setf (seeing-agent-body-zoomed-at agent-body) offset)
(setf (seeing-agent-body-visible-offsets agent-body) (list offset)))
(t ;; Zoom out
(setf (seeing-agent-body-zoomed-at agent-body) nil)
(setf (seeing-agent-body-visible-offsets agent-body)
(remove '(0 0) (seeing-agent-body-can-zoom-at agent-body)
:test #'equal)))))
| null | https://raw.githubusercontent.com/cl-axon/cl-aima/1e6915fa9f3e5f2c6fd75952d674ebec53558d04/logic/environments/shopping.lisp | lisp | File: shopping.lisp -*- Mode: Lisp; Syntax: Common-Lisp; -*-
Warning! This code has not yet been tested or debugged!
The rest of the store is temporarily out of stock ...
New Structures
Some have a camera to zoom in and out at a location
Percepts
Zoom out |
The Shopping World :
(defparameter *page250-supermarket*
'((at edge wall)
(at (1 1) (sign :words (exit)))
(at (and (2 2) (6 2)) shopper)
(at (and (3 2) (7 2)) cashier-stand)
(at (and (4 2) (8 2) (4 7)) cashier)
(at (2 4) (sign :words (Aisle 1 Vegetables)))
(at (2 5) (-15 tomato) (sign :words (Tomatoes $ .79 lb)))
(at (2 6) (-6 lettuce) (sign :words (Lettuce $ .89)))
(at (2 7) (-8 onion) (sign :words (Onion $ .49 lb)))
(at (3 4) (sign :words (Aisle 2 Fruit)))
(at (3 5) (-12 apple) (sign :words (Apples $ .69 lb)))
(at (3 6) (-9 orange) (sign :words (Oranges $ .75 lb)))
(at (3 7) (-3 grapefruit :size 0.06 :color yellow)
(-3 grapefruit :size 0.07 :color pink)
(sign :words (Grapefruit $ .49 each)))
(at (5 4) (sign :words (Aisle 3 Soup Sauces)))
(at (6 4) (sign :words (Aisle 4 Meat)))
(at (8 4) (sign :words (Aisle 5 Sundries)))
))
(defstructure (shopping-world (:include grid-environment
(aspec '(shopping-agent))
(bspec *page250-supermarket*))))
(defstructure (credit-card (:include object (name "$"))))
(defstructure (food (:include object (shape :round) (size .1) (name 'f))))
(defstructure (tomato (:include food (color 'red) (size .08) (name 't))))
(defstructure (lettuce (:include food (color 'green) (size .09) (name 'l))))
(defstructure (onion (:include food (color 'yellow) (size .07) (name 'o))))
(defstructure (orange (:include food (color 'orange) (size .07) (name 'o))))
(defstructure (apple (:include food (color 'red) (size .07) (name 'a))))
(defstructure (grapefruit (:include food (color 'yellow) (size .1) (name 'g))))
(defstructure (sign (:include object (name 'S) (size .09)
(color '(white (with black)))))
(words '()))
(defstructure (cashier-stand (:include object (color '(black (with chrome)))
(shape 'flat) (size .9) (name 'C))))
(defstructure (cashier (:include agent-body (name "c"))))
(defstructure (seeing-agent-body (:include agent-body (name ":")))
(can-zoom-at '((0 0) (0 +1) (+1 +1) (-1 +1)))
(visible-offsets '((0 +1) (+1 +1) (-1 +1))))
(defstructure (shopper (:include seeing-agent-body (name "@")
(contents (list (make-credit-card))))))
(defmethod get-percept ((env shopping-world) agent)
"The percept is a sequence of sights, touch (i.e. bump), and sounds."
(list (see agent env) (feel agent env) (hear agent env)))
(defun see (agent env)
"Return a list of visual percepts for an agent. Note the agent's camera may
either be zoomed out, so that it sees several squares, or zoomed in on one."
(let* ((body (agent-body agent))
(zoomed-at (seeing-agent-body-zoomed-at body)))
(mappend #'(lambda (offset)
(see-loc (absolute-loc body offset) env zoomed-at))
(seeing-agent-body-visible-offsets body))))
(defun feel (agent env)
(declare (ignore env))
(if (object-bump (agent-body agent)) 'bump))
(defun hear (agent env)
We can hear anything within 2 squares
(let* ((body (agent-body agent))
(loc (object-loc body))
(objects nil))
(for each obj in (grid-environment-objects env) do
(when (and (object-sound obj) (near? (object-loc obj) loc 2))
(push (object-sound obj) objects)))
objects))
(defun see-loc (loc env zoomed-at)
(let ((objects (grid-contents env loc)))
(if zoomed-at
(mappend #'appearance objects)
(appearance objects))))
(defun appearance (object)
"Return a list of visual attributes: (loc size color shape words)"
(list (object-loc object) (fuzz (object-size object)) (object-color object)
(object-shape object) (object-words object)))
(defun object-words (object)
(if (sign-p object)
(sign-words object)
nil))
(defun zoom (agent-body env offset)
"Zoom the camera at an offset if it is feasible; otherwise zoom out."
(declare (ignore env))
(cond ((member offset (seeing-agent-body-can-zoom-at agent-body))
(setf (seeing-agent-body-zoomed-at agent-body) offset)
(setf (seeing-agent-body-visible-offsets agent-body) (list offset)))
(setf (seeing-agent-body-zoomed-at agent-body) nil)
(setf (seeing-agent-body-visible-offsets agent-body)
(remove '(0 0) (seeing-agent-body-can-zoom-at agent-body)
:test #'equal)))))
|
5c22d520f5d6ec90025291f29f400ade96dba21186dcfeb33e5b50fdab3e386d | facebook/flow | scope_builder_sig.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module type S = sig
module L : Loc_sig.S
module Api : Scope_api_sig.S with module L = L
module Acc : sig
type t = Api.info
val init : t
end
val program :
?flowmin_compatibility:bool ->
enable_enums:bool ->
with_types:bool ->
(L.t, L.t) Flow_ast.Program.t ->
Acc.t
class scope_builder :
flowmin_compatibility:bool
-> enable_enums:bool
-> with_types:bool
-> object
inherit [Acc.t, L.t] Flow_ast_visitor.visitor
method with_bindings : 'a. ?lexical:bool -> L.t -> L.t Bindings.t -> ('a -> 'a) -> 'a -> 'a
method private scoped_for_statement :
L.t -> (L.t, L.t) Flow_ast.Statement.For.t -> (L.t, L.t) Flow_ast.Statement.For.t
method private scoped_for_in_statement :
L.t -> (L.t, L.t) Flow_ast.Statement.ForIn.t -> (L.t, L.t) Flow_ast.Statement.ForIn.t
method private scoped_for_of_statement :
L.t -> (L.t, L.t) Flow_ast.Statement.ForOf.t -> (L.t, L.t) Flow_ast.Statement.ForOf.t
method private switch_cases :
L.t ->
(L.t, L.t) Flow_ast.Expression.t ->
(L.t, L.t) Flow_ast.Statement.Switch.Case.t list ->
(L.t, L.t) Flow_ast.Statement.Switch.Case.t list
method private class_identifier_opt :
class_loc:L.t -> (L.t, L.t) Flow_ast.Identifier.t option -> unit
method private this_binding_function_id_opt :
fun_loc:L.t -> has_this_annot:bool -> (L.t, L.t) Flow_ast.Identifier.t option -> unit
method private lambda :
is_arrow:bool ->
fun_loc:L.t ->
generator_return_loc:L.t option ->
(L.t, L.t) Flow_ast.Function.Params.t ->
(L.t, L.t) Flow_ast.Type.Predicate.t option ->
(L.t, L.t) Flow_ast.Function.body ->
unit
method private hoist_annotations : (unit -> unit) -> unit
end
end
| null | https://raw.githubusercontent.com/facebook/flow/5625ae0ebfda43fc9ca076f5b8b7289a7be5cea0/src/analysis/scope_builder_sig.ml | ocaml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module type S = sig
module L : Loc_sig.S
module Api : Scope_api_sig.S with module L = L
module Acc : sig
type t = Api.info
val init : t
end
val program :
?flowmin_compatibility:bool ->
enable_enums:bool ->
with_types:bool ->
(L.t, L.t) Flow_ast.Program.t ->
Acc.t
class scope_builder :
flowmin_compatibility:bool
-> enable_enums:bool
-> with_types:bool
-> object
inherit [Acc.t, L.t] Flow_ast_visitor.visitor
method with_bindings : 'a. ?lexical:bool -> L.t -> L.t Bindings.t -> ('a -> 'a) -> 'a -> 'a
method private scoped_for_statement :
L.t -> (L.t, L.t) Flow_ast.Statement.For.t -> (L.t, L.t) Flow_ast.Statement.For.t
method private scoped_for_in_statement :
L.t -> (L.t, L.t) Flow_ast.Statement.ForIn.t -> (L.t, L.t) Flow_ast.Statement.ForIn.t
method private scoped_for_of_statement :
L.t -> (L.t, L.t) Flow_ast.Statement.ForOf.t -> (L.t, L.t) Flow_ast.Statement.ForOf.t
method private switch_cases :
L.t ->
(L.t, L.t) Flow_ast.Expression.t ->
(L.t, L.t) Flow_ast.Statement.Switch.Case.t list ->
(L.t, L.t) Flow_ast.Statement.Switch.Case.t list
method private class_identifier_opt :
class_loc:L.t -> (L.t, L.t) Flow_ast.Identifier.t option -> unit
method private this_binding_function_id_opt :
fun_loc:L.t -> has_this_annot:bool -> (L.t, L.t) Flow_ast.Identifier.t option -> unit
method private lambda :
is_arrow:bool ->
fun_loc:L.t ->
generator_return_loc:L.t option ->
(L.t, L.t) Flow_ast.Function.Params.t ->
(L.t, L.t) Flow_ast.Type.Predicate.t option ->
(L.t, L.t) Flow_ast.Function.body ->
unit
method private hoist_annotations : (unit -> unit) -> unit
end
end
|
|
b91e6a9666e2863ade535c67781acfc78ab4317fa31d67f9966d208499c7915d | wdebeaum/step | tests.lisp | ;;
;;
;; test suite for lf-public and kr-public functions
;;
(print (list
; ;; lf-parent
; (mapcar (lambda (in out) (equal out (funcall 'lf-parent in)))
; '(lf_move lf_thing lf_equipment lf_grade-modifier lf_adsf) '(lf_motion lf_any-sem lf_manufactured-object lf_modifier nil))
; ;; lf-parent
(mapcar (lambda (in out) (equal out (funcall 'get-parent in)))
'(lf_move lf_thing lf_equipment lf_grade-modifier lf_adsf) '(lf_motion lf_any-sem lf_manufactured-object lf_modifier nil))
; ;; lf-subtype
; (mapcar (lambda (sub super out) (equal out (funcall 'lf-subtype sub super)))
' ( lf_situation - root lf_body - process lf_qmodifier ) ' ( lf_body - process lf_situation - root lf_modifier ) ' ( nil lf_body - process lf_qmodifier ) )
;; lf-subtype
(mapcar (lambda (sub super out) (equal out (funcall 'subtype sub super)))
'(lf_situation-root lf_body-process lf_qmodifier) '(lf_body-process lf_situation-root lf_modifier) '(nil lf_body-process lf_qmodifier))
; ;; lf-more-specific
; (mapcar (lambda (sub super out) (equal out (funcall 'lf-more-specific sub super)))
' ( lf_topic - signal lf_situation - root lf_body - process lf_qmodifier ) ' ( lf_restriction lf_body - process lf_situation - root lf_modifier ) ' ( nil lf_body - process lf_body - process lf_qmodifier ) )
;; lf-more-specific
(mapcar (lambda (sub super out) (equal out (funcall 'more-specific sub super)))
'(lf_topic-signal lf_situation-root lf_body-process lf_qmodifier) '(lf_restriction lf_body-process lf_situation-root lf_modifier) '(nil lf_body-process lf_body-process lf_qmodifier))
; ;; lf-common-ancestor
; (mapcar (lambda (sub super out) (equal out (funcall 'lf-common-ancestor sub super)))
' ( lf_machine lf_situation - object - modifier lf_restriction ) ' ( lf_predicate lf_manner lf_topic ) ' ( lf_any - sem lf_situation - object - modifier ) )
;; lf-common-ancestor
(mapcar (lambda (sub super out) (equal out (funcall 'common-ancestor sub super
:ontology 'lf)))
'(lf_machine lf_situation-object-modifier lf_restriction) '(lf_predicate lf_manner lf_topic) '(lf_any-sem lf_situation-object-modifier lf_predicate))
; ;; lf-feature-subtype
; (mapcar (lambda (x y out) (equal out (funcall 'lf-feature-subtype x y)))
' ( f_bounded f_force f_mental f_atomic f_plant ) ' ( f_dynamic f_stimulating f_located f_atomic f_natural ) ' ( f_bounded nil nil f_atomic f_plant ) )
;; lf-feature-subtype
(mapcar (lambda (x y out) (equal out (funcall 'subtype x y)))
'(f_bounded f_force f_mental f_atomic f_plant) '(f_dynamic f_stimulating f_located f_atomic f_natural) '(f_bounded nil nil f_atomic f_plant))
;; lf-sem
(mapcar (lambda (x out) (equal out (funcall 'lf-sem x)))
'(lf_move lf_trajectory)
'((FT_SITUATION
(:REQUIRED (TIME-SPAN F_ANY-TIME-SPAN) (TYPE F_GO) (TRAJECTORY +)
(LOCATIVE -) (CONTAINER -) (ASPECT F_DYNAMIC) (CAUSE (? C F_FORCE -))
(INTENTIONAL -) (INFORMATION F_PROPOSITION)))
(FT_ABSTR-OBJ
(:REQUIRED (SCALE -) (MEASURE -) (CONTAINER -) (INFORMATION -)
(INTENTIONAL -) (GRADABILITY -) (TYPE F_ANY-TYPE)))
)
)
;; lf-arguments
(mapcar (lambda (x out) (equal out (funcall 'lf-arguments x)))
'(lf_land-vehicle lf_human-object lf_body-process)
'(
((:OPTIONAL LF_SPATIAL-LOC (FT_PHYS-OBJ) (:IMPLEMENTS LF_SPATIAL-LOC)))
((:OPTIONAL LF_SPATIAL-LOC (FT_PHYS-OBJ) (:IMPLEMENTS LF_SPATIAL-LOC)))
((:OPTIONAL CO-THEME (FT_PHYS-OBJ (FORM F_SUBSTANCE)) (:IMPLEMENTS CO-THEME))
(:REQUIRED THEME (FT_PHYS-OBJ (ORIGIN F_LIVING)) (:IMPLEMENTS THEME)))
)
)
;; lf-GCB
(mapcar (lambda (x y out) (equal out (funcall 'lf-GCB x y)))
'(
(ft_Situation (:required (intentional -)) (:default (origin f_living)))
(ft_phys-obj (group +) (origin f_human) (intentional +) (mobility F_movable))
(ft_Abstr-obj (CONTAINER -) (INFORMATION -) (INTENTIONAL -) (SCALE F_POINT))
)
'(
(ft_Situation (:required (intentional -) (origin f_living)))
(ft_phys-obj (group +) (origin f_natural) (intentional +) (mobility F_self-moving))
(ft_Abstr-obj (CONTAINER -) (INFORMATION -) (INTENTIONAL -) (SCALE F_VALUE))
)
'(
nil
(FT_PHYS-OBJ (MOBILITY F_SELF-MOVING) (INTENTIONAL +) (ORIGIN F_HUMAN)
(GROUP +))
(ft_Abstr-obj (SCALE nil) (INTENTIONAL -) (INFORMATION -) (CONTAINER -))
)
)
;; lf-feature-pattern-match
(mapcar (lambda (x y out) (equal out (funcall 'lf-feature-pattern-match x y)))
'(
(ft_Situation (:required (intentional -)))
(ft_Situation (:required (intentional -)) (:default (origin f_living)))
(ft_phys-obj (group +) (origin f_natural) (intentional +) (mobility F_movable))
(ft_Abstr-obj (CONTAINER -) (INFORMATION -) (INTENTIONAL -) (SCALE F_POINT))
)
'(
(ft_Situation (:required (intentional -) (origin f_living)))
(ft_Situation (:required (intentional -)))
(ft_phys-obj (group +) (origin f_human) (intentional +) (mobility F_self-moving))
(ft_Abstr-obj (CONTAINER -) (INFORMATION -) (INTENTIONAL -) (SCALE F_VALUE))
)
'(
t t t nil
)
)
;; lf-feature-set-merge
(mapcar (lambda (x y out) (equal out (funcall 'lf-feature-set-merge x y)))
'(
(ft_Abstr-obj (INTENTIONAL -) (SCALE F_POINT))
(ft_phys-obj (origin f_human))
)
'(
(ft_Abstr-obj (CONTAINER -) (INFORMATION -))
(ft_phys-obj (origin f_human) (group -))
)
'(
(FT_ABSTR-OBJ
(:REQUIRED (TYPE F_ANY-TYPE) (GRADABILITY -) (MEASURE -) (SCALE F_POINT)
(INTENTIONAL -) (CONTAINER -) (INFORMATION -)))
(FT_PHYS-OBJ
(:REQUIRED (TYPE F_ANY-TYPE) (OBJECT-FUNCTION F_ANY-OBJECT-FUNCTION)
(MOBILITY F_ANY-MOBILITY)
(SPATIAL-ABSTRACTION (? SAB F_SPATIAL-POINT F_SPATIAL-REGION))
(TRAJECTORY -) (INFORMATION -) (CONTAINER -) (GROUP -) (ORIGIN F_HUMAN)
(INTENTIONAL +) (FORM F_SOLID-OBJECT)))
)
)
;; lf-more-specific-feature-value
; (mapcar (lambda (x y out) (equal out (funcall 'lf-more-specific-feature-value x y)))
' ( f_dynamic
; f_atomic
; f_plant
; f_gas
; )
; '(
; f_unbounded
; f_extended
; f_living
; f_substance
; )
; '(
; f_unbounded
; nil
; f_plant
; f_gas
; )
; )
; ))
(mapcar (lambda (x y out) (equal out (funcall 'more-specific x y
:ontology 'lf)))
'(f_dynamic
f_atomic
f_plant
f_gas
)
'(
f_unbounded
f_extended
f_living
f_substance
)
'(
f_unbounded
nil
f_plant
f_gas
)
)
))
(print (list
; ;; kr-subclass
; (mapcar (lambda (x y out) (equal out (funcall 'kr-subclass x y)))
; '(
; objective
; intentional-object
; fly
; )
; '(
; intentional-object
; objective
; move
; )
; '( objective nil fly )
; )
;; kr-subclass
(mapcar (lambda (x y out) (equal out (funcall 'subtype x y
:ontology 'kr)))
'(
objective
intentional-object
fly
)
'(
intentional-object
objective
move
)
'( objective nil fly )
)
; ;; kr-subpred
; (mapcar (lambda (x y out) (equal out (funcall 'kr-subpred x y)))
; '(
; along
; trajectory
; ahead
; )
; '(
; trajectory
; along
; geo-loc-predicate
; )
; '( along nil ahead )
; )
;; kr-subpred
(mapcar (lambda (x y out) (equal out (funcall 'subtype x y
:ontology 'kr)))
'(
along
trajectory
ahead
)
'(
trajectory
along
geo-loc-predicate
)
'( along nil ahead )
)
; ;
; (mapcar (lambda (x y out) (equal out (funcall 'kr-suboperator x y)))
; '(
; location-operator
; root-operator
; near
; )
; '(
; root-operator
; location-operator
; root-operator
; )
; '( location-operator nil near)
; )
;; kr-suboperator
(mapcar (lambda (x y out) (equal out (funcall 'subtype x y
:ontology 'kr)))
'(
location-operator
root-operator
near
)
'(
root-operator
location-operator
root-operator
)
'( location-operator nil near)
)
; ;; kr-more-specific-class
; (mapcar (lambda (x y out) (equal out (funcall 'kr-more-specific-class x y)))
; '(
; fire-engine
; trans-agent
; plane
; )
; '(
; trans-agent
; fire-engine
; bus
; )
; '(
; fire-engine
; fire-engine
; nil
; )
; )
;; kr-more-specific-class
(mapcar (lambda (x y out) (equal out (funcall 'more-specific x y
:ontology 'kr)))
'(
fire-engine
trans-agent
plane
)
'(
trans-agent
fire-engine
bus
)
'(
fire-engine
fire-engine
nil
)
)
; ;; kr-common-ancestor-class
; (mapcar (lambda (x y out) (equal out (funcall 'kr-common-ancestor-class x y)))
; '(
; truck
; show
; shows
; )
; '(
; car
; expect
; show
; )
; '(
; vehicle
; action
; nil
; )
; )
;; kr-common-ancestor-class
(mapcar (lambda (x y out) (equal out (funcall 'common-ancestor x y
:ontology 'kr)))
'(
truck
show
shows
)
'(
car
expect
show
)
'(
vehicle
action
nil
)
)
; ;
( mapcar ( lambda ( x out ) ( equal out ( funcall ' ) ) )
; '(
; stop
; expect
; truck
; )
; '(
; action-theme
; action
; vehicle
; )
; )
; ;
; (mapcar (lambda (x out) (equal out (funcall 'kr-parentpred x)))
; '(
; south-of
; approx-at-loc
; kr-pred-root
; )
; '(
; rel-loc
; at-loc
; nil
; )
; )
; ;
; (mapcar (lambda (x out) (equal out (funcall 'kr-parentop x)))
; '(
; location-operator
; root-operator
; near
; )
; '(
; root-operator
; nil
; location-operator
; )
; )
;; kr-parentclass
(mapcar (lambda (x out) (equal out (funcall 'get-parent x :ontology 'kr)))
'(
stop
expect
truck
)
'(
action-theme
action
vehicle
)
)
;; kr-parentpred
(mapcar (lambda (x out) (equal out (funcall 'get-parent x :ontology 'kr)))
'(
south-of
approx-at-loc
kr-pred-root
)
'(
rel-loc
at-loc
nil
)
)
;; kr-parentop
(mapcar (lambda (x out) (equal out (funcall 'get-parent x :ontology 'kr)))
'(
location-operator
root-operator
near
)
'(
root-operator
nil
location-operator
)
)
;; kr-slots
(mapcar (lambda (x out) (equal out (funcall 'kr-slots x)))
'(
cargo
truck
accident
happen
)
'(
nil
((AT-LOC))
((REASON-FOR KR-ROOT) (AT-TIME TIME-LOC) (AT-LOC GEO-LOC)
(APPROX-AT-TIME TIME-LOC))
((REASON-FOR KR-ROOT) (AT-TIME TIME-LOC) (AT-LOC GEO-LOC)
(APPROX-AT-TIME TIME-LOC) (EVENTUALITY EVENT))
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/OntologyManager/tests.lisp | lisp |
test suite for lf-public and kr-public functions
;; lf-parent
(mapcar (lambda (in out) (equal out (funcall 'lf-parent in)))
'(lf_move lf_thing lf_equipment lf_grade-modifier lf_adsf) '(lf_motion lf_any-sem lf_manufactured-object lf_modifier nil))
;; lf-parent
;; lf-subtype
(mapcar (lambda (sub super out) (equal out (funcall 'lf-subtype sub super)))
lf-subtype
;; lf-more-specific
(mapcar (lambda (sub super out) (equal out (funcall 'lf-more-specific sub super)))
lf-more-specific
;; lf-common-ancestor
(mapcar (lambda (sub super out) (equal out (funcall 'lf-common-ancestor sub super)))
lf-common-ancestor
;; lf-feature-subtype
(mapcar (lambda (x y out) (equal out (funcall 'lf-feature-subtype x y)))
lf-feature-subtype
lf-sem
lf-arguments
lf-GCB
lf-feature-pattern-match
lf-feature-set-merge
lf-more-specific-feature-value
(mapcar (lambda (x y out) (equal out (funcall 'lf-more-specific-feature-value x y)))
f_atomic
f_plant
f_gas
)
'(
f_unbounded
f_extended
f_living
f_substance
)
'(
f_unbounded
nil
f_plant
f_gas
)
)
))
;; kr-subclass
(mapcar (lambda (x y out) (equal out (funcall 'kr-subclass x y)))
'(
objective
intentional-object
fly
)
'(
intentional-object
objective
move
)
'( objective nil fly )
)
kr-subclass
;; kr-subpred
(mapcar (lambda (x y out) (equal out (funcall 'kr-subpred x y)))
'(
along
trajectory
ahead
)
'(
trajectory
along
geo-loc-predicate
)
'( along nil ahead )
)
kr-subpred
;
(mapcar (lambda (x y out) (equal out (funcall 'kr-suboperator x y)))
'(
location-operator
root-operator
near
)
'(
root-operator
location-operator
root-operator
)
'( location-operator nil near)
)
kr-suboperator
;; kr-more-specific-class
(mapcar (lambda (x y out) (equal out (funcall 'kr-more-specific-class x y)))
'(
fire-engine
trans-agent
plane
)
'(
trans-agent
fire-engine
bus
)
'(
fire-engine
fire-engine
nil
)
)
kr-more-specific-class
;; kr-common-ancestor-class
(mapcar (lambda (x y out) (equal out (funcall 'kr-common-ancestor-class x y)))
'(
truck
show
shows
)
'(
car
expect
show
)
'(
vehicle
action
nil
)
)
kr-common-ancestor-class
;
'(
stop
expect
truck
)
'(
action-theme
action
vehicle
)
)
;
(mapcar (lambda (x out) (equal out (funcall 'kr-parentpred x)))
'(
south-of
approx-at-loc
kr-pred-root
)
'(
rel-loc
at-loc
nil
)
)
;
(mapcar (lambda (x out) (equal out (funcall 'kr-parentop x)))
'(
location-operator
root-operator
near
)
'(
root-operator
nil
location-operator
)
)
kr-parentclass
kr-parentpred
kr-parentop
kr-slots |
(print (list
(mapcar (lambda (in out) (equal out (funcall 'get-parent in)))
'(lf_move lf_thing lf_equipment lf_grade-modifier lf_adsf) '(lf_motion lf_any-sem lf_manufactured-object lf_modifier nil))
' ( lf_situation - root lf_body - process lf_qmodifier ) ' ( lf_body - process lf_situation - root lf_modifier ) ' ( nil lf_body - process lf_qmodifier ) )
(mapcar (lambda (sub super out) (equal out (funcall 'subtype sub super)))
'(lf_situation-root lf_body-process lf_qmodifier) '(lf_body-process lf_situation-root lf_modifier) '(nil lf_body-process lf_qmodifier))
' ( lf_topic - signal lf_situation - root lf_body - process lf_qmodifier ) ' ( lf_restriction lf_body - process lf_situation - root lf_modifier ) ' ( nil lf_body - process lf_body - process lf_qmodifier ) )
(mapcar (lambda (sub super out) (equal out (funcall 'more-specific sub super)))
'(lf_topic-signal lf_situation-root lf_body-process lf_qmodifier) '(lf_restriction lf_body-process lf_situation-root lf_modifier) '(nil lf_body-process lf_body-process lf_qmodifier))
' ( lf_machine lf_situation - object - modifier lf_restriction ) ' ( lf_predicate lf_manner lf_topic ) ' ( lf_any - sem lf_situation - object - modifier ) )
(mapcar (lambda (sub super out) (equal out (funcall 'common-ancestor sub super
:ontology 'lf)))
'(lf_machine lf_situation-object-modifier lf_restriction) '(lf_predicate lf_manner lf_topic) '(lf_any-sem lf_situation-object-modifier lf_predicate))
' ( f_bounded f_force f_mental f_atomic f_plant ) ' ( f_dynamic f_stimulating f_located f_atomic f_natural ) ' ( f_bounded nil nil f_atomic f_plant ) )
(mapcar (lambda (x y out) (equal out (funcall 'subtype x y)))
'(f_bounded f_force f_mental f_atomic f_plant) '(f_dynamic f_stimulating f_located f_atomic f_natural) '(f_bounded nil nil f_atomic f_plant))
(mapcar (lambda (x out) (equal out (funcall 'lf-sem x)))
'(lf_move lf_trajectory)
'((FT_SITUATION
(:REQUIRED (TIME-SPAN F_ANY-TIME-SPAN) (TYPE F_GO) (TRAJECTORY +)
(LOCATIVE -) (CONTAINER -) (ASPECT F_DYNAMIC) (CAUSE (? C F_FORCE -))
(INTENTIONAL -) (INFORMATION F_PROPOSITION)))
(FT_ABSTR-OBJ
(:REQUIRED (SCALE -) (MEASURE -) (CONTAINER -) (INFORMATION -)
(INTENTIONAL -) (GRADABILITY -) (TYPE F_ANY-TYPE)))
)
)
(mapcar (lambda (x out) (equal out (funcall 'lf-arguments x)))
'(lf_land-vehicle lf_human-object lf_body-process)
'(
((:OPTIONAL LF_SPATIAL-LOC (FT_PHYS-OBJ) (:IMPLEMENTS LF_SPATIAL-LOC)))
((:OPTIONAL LF_SPATIAL-LOC (FT_PHYS-OBJ) (:IMPLEMENTS LF_SPATIAL-LOC)))
((:OPTIONAL CO-THEME (FT_PHYS-OBJ (FORM F_SUBSTANCE)) (:IMPLEMENTS CO-THEME))
(:REQUIRED THEME (FT_PHYS-OBJ (ORIGIN F_LIVING)) (:IMPLEMENTS THEME)))
)
)
(mapcar (lambda (x y out) (equal out (funcall 'lf-GCB x y)))
'(
(ft_Situation (:required (intentional -)) (:default (origin f_living)))
(ft_phys-obj (group +) (origin f_human) (intentional +) (mobility F_movable))
(ft_Abstr-obj (CONTAINER -) (INFORMATION -) (INTENTIONAL -) (SCALE F_POINT))
)
'(
(ft_Situation (:required (intentional -) (origin f_living)))
(ft_phys-obj (group +) (origin f_natural) (intentional +) (mobility F_self-moving))
(ft_Abstr-obj (CONTAINER -) (INFORMATION -) (INTENTIONAL -) (SCALE F_VALUE))
)
'(
nil
(FT_PHYS-OBJ (MOBILITY F_SELF-MOVING) (INTENTIONAL +) (ORIGIN F_HUMAN)
(GROUP +))
(ft_Abstr-obj (SCALE nil) (INTENTIONAL -) (INFORMATION -) (CONTAINER -))
)
)
(mapcar (lambda (x y out) (equal out (funcall 'lf-feature-pattern-match x y)))
'(
(ft_Situation (:required (intentional -)))
(ft_Situation (:required (intentional -)) (:default (origin f_living)))
(ft_phys-obj (group +) (origin f_natural) (intentional +) (mobility F_movable))
(ft_Abstr-obj (CONTAINER -) (INFORMATION -) (INTENTIONAL -) (SCALE F_POINT))
)
'(
(ft_Situation (:required (intentional -) (origin f_living)))
(ft_Situation (:required (intentional -)))
(ft_phys-obj (group +) (origin f_human) (intentional +) (mobility F_self-moving))
(ft_Abstr-obj (CONTAINER -) (INFORMATION -) (INTENTIONAL -) (SCALE F_VALUE))
)
'(
t t t nil
)
)
(mapcar (lambda (x y out) (equal out (funcall 'lf-feature-set-merge x y)))
'(
(ft_Abstr-obj (INTENTIONAL -) (SCALE F_POINT))
(ft_phys-obj (origin f_human))
)
'(
(ft_Abstr-obj (CONTAINER -) (INFORMATION -))
(ft_phys-obj (origin f_human) (group -))
)
'(
(FT_ABSTR-OBJ
(:REQUIRED (TYPE F_ANY-TYPE) (GRADABILITY -) (MEASURE -) (SCALE F_POINT)
(INTENTIONAL -) (CONTAINER -) (INFORMATION -)))
(FT_PHYS-OBJ
(:REQUIRED (TYPE F_ANY-TYPE) (OBJECT-FUNCTION F_ANY-OBJECT-FUNCTION)
(MOBILITY F_ANY-MOBILITY)
(SPATIAL-ABSTRACTION (? SAB F_SPATIAL-POINT F_SPATIAL-REGION))
(TRAJECTORY -) (INFORMATION -) (CONTAINER -) (GROUP -) (ORIGIN F_HUMAN)
(INTENTIONAL +) (FORM F_SOLID-OBJECT)))
)
)
' ( f_dynamic
(mapcar (lambda (x y out) (equal out (funcall 'more-specific x y
:ontology 'lf)))
'(f_dynamic
f_atomic
f_plant
f_gas
)
'(
f_unbounded
f_extended
f_living
f_substance
)
'(
f_unbounded
nil
f_plant
f_gas
)
)
))
(print (list
(mapcar (lambda (x y out) (equal out (funcall 'subtype x y
:ontology 'kr)))
'(
objective
intentional-object
fly
)
'(
intentional-object
objective
move
)
'( objective nil fly )
)
(mapcar (lambda (x y out) (equal out (funcall 'subtype x y
:ontology 'kr)))
'(
along
trajectory
ahead
)
'(
trajectory
along
geo-loc-predicate
)
'( along nil ahead )
)
(mapcar (lambda (x y out) (equal out (funcall 'subtype x y
:ontology 'kr)))
'(
location-operator
root-operator
near
)
'(
root-operator
location-operator
root-operator
)
'( location-operator nil near)
)
(mapcar (lambda (x y out) (equal out (funcall 'more-specific x y
:ontology 'kr)))
'(
fire-engine
trans-agent
plane
)
'(
trans-agent
fire-engine
bus
)
'(
fire-engine
fire-engine
nil
)
)
(mapcar (lambda (x y out) (equal out (funcall 'common-ancestor x y
:ontology 'kr)))
'(
truck
show
shows
)
'(
car
expect
show
)
'(
vehicle
action
nil
)
)
( mapcar ( lambda ( x out ) ( equal out ( funcall ' ) ) )
(mapcar (lambda (x out) (equal out (funcall 'get-parent x :ontology 'kr)))
'(
stop
expect
truck
)
'(
action-theme
action
vehicle
)
)
(mapcar (lambda (x out) (equal out (funcall 'get-parent x :ontology 'kr)))
'(
south-of
approx-at-loc
kr-pred-root
)
'(
rel-loc
at-loc
nil
)
)
(mapcar (lambda (x out) (equal out (funcall 'get-parent x :ontology 'kr)))
'(
location-operator
root-operator
near
)
'(
root-operator
nil
location-operator
)
)
(mapcar (lambda (x out) (equal out (funcall 'kr-slots x)))
'(
cargo
truck
accident
happen
)
'(
nil
((AT-LOC))
((REASON-FOR KR-ROOT) (AT-TIME TIME-LOC) (AT-LOC GEO-LOC)
(APPROX-AT-TIME TIME-LOC))
((REASON-FOR KR-ROOT) (AT-TIME TIME-LOC) (AT-LOC GEO-LOC)
(APPROX-AT-TIME TIME-LOC) (EVENTUALITY EVENT))
)
)
))
|
f9c30812703d8293176d5a3659253a891c06f8ed82ad009febbaa11467563098 | sampou-org/pfad | bench18.hs | module Main where
import Code18
main :: IO ()
main = do
{ putStr "bfsolve puzzle1 : " >> print (bfsolve puzzle1)
; putStr "bfsolve puzzle2 : " >> print (bfsolve puzzle2)
; putStr "bfsolve puzzle3 : " >> print (bfsolve puzzle3)
; putStr "bfsolve puzzle4 : " >> print (bfsolve puzzle4)
; putStr "psolve puzzle1 : " >> print (psolve puzzle1)
; putStr "psolve puzzle2 : " >> print (psolve puzzle2)
; putStr "psolve puzzle3 : " >> print (psolve puzzle3)
; putStr "psolve puzzle4 : " >> print (psolve puzzle4)
}
| null | https://raw.githubusercontent.com/sampou-org/pfad/3c2e0847bea9eac80672e1fbccb86ca5a6b09415/Code/bench18.hs | haskell | module Main where
import Code18
main :: IO ()
main = do
{ putStr "bfsolve puzzle1 : " >> print (bfsolve puzzle1)
; putStr "bfsolve puzzle2 : " >> print (bfsolve puzzle2)
; putStr "bfsolve puzzle3 : " >> print (bfsolve puzzle3)
; putStr "bfsolve puzzle4 : " >> print (bfsolve puzzle4)
; putStr "psolve puzzle1 : " >> print (psolve puzzle1)
; putStr "psolve puzzle2 : " >> print (psolve puzzle2)
; putStr "psolve puzzle3 : " >> print (psolve puzzle3)
; putStr "psolve puzzle4 : " >> print (psolve puzzle4)
}
|
|
9124de225e791b13c634bbcf814627a55481bb0754286aa26598593bddaf44bf | ocamllabs/ocaml-modular-implicits | pr6513_ok.ml | module type PR6513 = sig
module type S = sig type u end
module type T = sig
type 'a wrap
type uri
end
module Make: functor (Html5 : T with type 'a wrap = 'a) ->
S with type u = < foo : Html5.uri >
end
Requires -package tyxml
module type PR6513_orig = sig
module type S =
sig
type t
type u
end
module Make : functor ( Html5 : Html5_sigs . T with type ' a Xml.wrap = ' a and type ' a wrap = ' a and type ' a list_wrap = ' a list ) - > S with
type t = Html5_types.div Html5.elt and
type u = < foo : Html5.uri >
end
module type PR6513_orig = sig
module type S =
sig
type t
type u
end
module Make: functor (Html5: Html5_sigs.T with type 'a Xml.wrap = 'a and type 'a wrap = 'a and type 'a list_wrap = 'a list) -> S with
type t = Html5_types.div Html5.elt and
type u = < foo: Html5.uri >
end
*)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/typing-modules-bugs/pr6513_ok.ml | ocaml | module type PR6513 = sig
module type S = sig type u end
module type T = sig
type 'a wrap
type uri
end
module Make: functor (Html5 : T with type 'a wrap = 'a) ->
S with type u = < foo : Html5.uri >
end
Requires -package tyxml
module type PR6513_orig = sig
module type S =
sig
type t
type u
end
module Make : functor ( Html5 : Html5_sigs . T with type ' a Xml.wrap = ' a and type ' a wrap = ' a and type ' a list_wrap = ' a list ) - > S with
type t = Html5_types.div Html5.elt and
type u = < foo : Html5.uri >
end
module type PR6513_orig = sig
module type S =
sig
type t
type u
end
module Make: functor (Html5: Html5_sigs.T with type 'a Xml.wrap = 'a and type 'a wrap = 'a and type 'a list_wrap = 'a list) -> S with
type t = Html5_types.div Html5.elt and
type u = < foo: Html5.uri >
end
*)
|
|
73d29f160e1e19b32d92b2309d29174ac730f2e064a2b5062cc80403ecc60e90 | jonase/eastwood | defn_reflection_warning.clj | (ns eastwood.test.outside-test-paths.defn-reflection-warning)
(defn foo [x]
(.fooasdlfjk x))
| null | https://raw.githubusercontent.com/jonase/eastwood/a515efe22c9ce3c84d73d800e23ae7ebbda4a78a/test-resources/eastwood/test/outside_test_paths/defn_reflection_warning.clj | clojure | (ns eastwood.test.outside-test-paths.defn-reflection-warning)
(defn foo [x]
(.fooasdlfjk x))
|
|
47bae4e3df569cf52ab71f9d80abbdb7f47e216435bdd90c7630a12fc611fbc5 | JustusAdam/language-haskell | T0073.hs | SYNTAX TEST " source.haskell " " Visible type application "
function =
let l = [] @[( Int, f [ Bool ] )] in
-- ^ meta.type-application.haskell
^^^ storage.type.haskell
-- ^ variable.other.generic-type.haskell
let x = "Hello" @String in
-- ^ meta.type-application.haskell
^^^^^^ storage.type.haskell
let c@(Some pattern) = undefined in
-- ^ - meta.type-application.haskell
-- ^^^^ constant.other.haskell
let g = f @( g ([]) -> String ) in
-- ^ meta.type-application.haskell
-- ^ variable.other.generic-type.haskell
let h = k @_ @a @Int
-- ^ ^ ^ meta.type-application.haskell
let a = b @ c
-- ^ - meta.type-application.haskell
undefined
g = f @Bool(A)
-- ^ meta.type-application.haskell
^^^^ storage.type.haskell
-- ^ - storage.type.haskell
| null | https://raw.githubusercontent.com/JustusAdam/language-haskell/c9ee1b3ee166c44db9ce350920ba502fcc868245/test/tickets/T0073.hs | haskell | ^ meta.type-application.haskell
^ variable.other.generic-type.haskell
^ meta.type-application.haskell
^ - meta.type-application.haskell
^^^^ constant.other.haskell
^ meta.type-application.haskell
^ variable.other.generic-type.haskell
^ ^ ^ meta.type-application.haskell
^ - meta.type-application.haskell
^ meta.type-application.haskell
^ - storage.type.haskell | SYNTAX TEST " source.haskell " " Visible type application "
function =
let l = [] @[( Int, f [ Bool ] )] in
^^^ storage.type.haskell
let x = "Hello" @String in
^^^^^^ storage.type.haskell
let c@(Some pattern) = undefined in
let g = f @( g ([]) -> String ) in
let h = k @_ @a @Int
let a = b @ c
undefined
g = f @Bool(A)
^^^^ storage.type.haskell
|
3cb49031feadb1f16e89e517b2522081662fadc566e562c68d3da1708a3e7358 | google/codeworld | Widget.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
# LANGUAGE ParallelListComp #
# LANGUAGE PatternGuards #
# LANGUAGE RebindableSyntax #
# LANGUAGE RecordWildCards #
# LANGUAGE NoImplicitPrelude #
-- | A very simple Graphical User Interface (GUI) for user interaction with
-- buttons, checkboxes, sliders and a few others.
module Extras.Widget
( -- $intro
guiDrawingOf,
guiActivityOf,
-- * Widgets
Widget,
toggle,
button,
slider,
randomBox,
timer,
counter,
-- * Convenience functions
withConversion,
setConversion,
-- * Examples
widgetExample1,
widgetExample2,
widgetExample3,
widgetExample4,
)
where
import Prelude
--------------------------------------------------------------------------------
-- $intro
-- = Widget API
--
-- To use the extra features in this module, you must begin your code with this
-- line:
--
-- > import Extras.Widget
-- | The function @guiDrawingOf@ is an entry point for drawing that allows
access to a simple GUI . It needs two arguments : a list of
-- Widgets and a function to create your drawing. This user-supplied drawing
-- function will have access to the list of the current values of the widgets,
-- which is passed as an argument.
--
-- Example of use:
--
-- > program = guiDrawingOf(widgets,draw)
-- > where
> widgets = [ withConversion(\v - > 1 + 19 * v , slider("width " , -7,-7 ) )
> , withConversion(\v - > 1 + 19 * v , " , -7,-9 ) )
> , withConversion(flipflop , toggle("show circle " , -7,-5 ) )
> , withConversion(flipflop , button("show in green",-7,-3 ) )
-- > , withConversion(\v -> 0.2 + 0.8 * v, randomBox("radius" ,-7,-1))
-- > ]
-- >
-- > flipflop(v) = truncation(1 + 2 * v)
-- >
-- > draw(values) = blank
-- > & [blank, circle(r)]#s
> & colored(solidRectangle(w , h),[red , green]#c )
-- > where
-- > w = values#1
-- > h = values#2
> s = values#3
> c = values#4
-- > r = values#5
--
-- Note that the order in which the widgets are defined is important,
-- because it determines how to access the correct value.
Each widget fits in a box 4 units wide and 1 unit high .
guiDrawingOf :: ([Widget], [Number] -> Picture) -> Program
guiDrawingOf (widgetsUser, drawUser) = activityOf (initAll, updateAll, drawAll)
where
initAll (rs) = initRandom (widgetsUser, rs)
updateAll (ws, event) = ws .$ updateWidget (event)
drawAll (ws) = pictures (ws .$ drawWidget) & drawUser (ws .$ value)
| The function @guiActivityOf@ is similar to @activityOf@ , but it also
-- takes in a list of widgets. The updating and drawing functions also
-- receive a list of the current values of the widgets.
--
-- Example of use:
--
> program = guiActivityOf(widgets , init , update , draw )
-- > where
> widgets = [ withConversion(\v - > 20 * v , slider("width",-7,-7 ) )
> , withConversion(\v - > 2 + 3 * v , ) )
-- > , withConversion
> ( \v - > truncation(1 + 2*v ) , ) )
-- > , button("restart",-7,-3)
-- > , randomBox("new color",-7,-1)
-- > ]
-- >
-- > draw(values,(color@(RGB(r1,r2,r3)),angle,_)) = colored(base,color)
-- > & [blank, circle(5)]#s
-- > & translated(lettering(msg),0,9)
-- > where
-- > msg = joined(["(",printed(r1),",",printed(r2),",",printed(r3),")"])
> base = rotated(solidRectangle(w , )
-- > w = values#1
-- > h = values#2
> s = values#3
-- >
-- > init(rs) = (RGB(rs#1,rs#2,rs#3),0,0)
-- >
-- > update(values,(color@(RGB(r1,r2,r3)),angle,wait),TimePassing(_))
> | values#4 > 0 , wait = = 0 = ( RGB(r2,r3,r),0,values#4 )
-- > | otherwise = (color,angle+1,wait)
-- > where
-- > r = values#5
-- >
> update(values,(color , angle , ( _ ) ) = ( color , angle,0 )
-- >
> update(values , state , event ) = state
--
-- Note that pre-defined actions on the widgets take precedence over
-- anything that you define in your updating function, so you cannot
-- alter the default behavior of the widgets.
guiActivityOf ::
( [Widget],
[Number] -> state,
([Number], state, Event) -> state,
([Number], state) -> Picture
) ->
Program
guiActivityOf (widgetsUser, initUser, updateUser, drawUser) =
activityOf (initAll, updateAll, drawAll)
where
initAll (rs) =
( initRandom (widgetsUser, rest (rs, 1)),
initUser (randomNumbers (rs # 1))
)
updateAll ((widgets, state), event) =
(newWidgets, updateUser (widgets .$ value, state, event))
where
newWidgets = widgets .$ updateWidget (event)
drawAll (widgets, state) =
pictures (widgets .$ drawWidget) & drawUser (widgets .$ value, state)
initRandom (ws, rs) = [t (w, r) | w <- ws | r <- rs]
where
t (w, r)
| isRandom (w) =
let rp = randomNumbers (r)
in w {value_ = rp # 1, randomPool = rest (rp, 1)}
| otherwise = w
isRandom (Widget {widget = Random}) = True
isRandom (_) = False
-- | A button placed at the given location. While
the button is pressed , the value produced is 0.5 ,
-- but when the button is released, the value reverts
-- back to 0.
button :: (Text, Number, Number) -> Widget
button (p) = (newWidget (p)) {widget = Button}
-- | A toggle (checkbox) with the given label at the given location.
-- When the box is not set, the value produced is 0. When the
box is set , the value produced is 0.5
toggle :: (Text, Number, Number) -> Widget
toggle (p) = (newWidget (p)) {widget = Toggle}
-- | A slider with the given label at the given location.
The possible values will range from 0 to 1 , and the initial
-- value will be 0.
slider :: (Text, Number, Number) -> Widget
slider (p) = (newWidget (p)) {widget = Slider}
| A box that produces a random number between 0 and 1 .
-- Each time you click on it, the value will change. The
value 1 is never produced , so the actual range of
values is 0 to 0.99999 ...
randomBox :: (Text, Number, Number) -> Widget
randomBox (p) = (newWidget (p)) {widget = Random}
-- | A button that keeps incrementing the value each time you press it.
The initial value is 1 .
counter :: (Text, Number, Number) -> Widget
counter (p) = (newWidget (p)) {widget = Counter, value_ = 1}
-- | A toggle that counts time up when you set it. When you click on
-- the left side of the widget, the current value is reset to 0.
-- You can stop the timer and start it again, and the value will increase
-- from where it was when you stopped it.
--
-- Example:
--
-- > program = guiDrawingOf(widgets,draw)
-- > where
> widgets = [ withConversion(\v - > 1 + 9 * v , slider("length",-7,-7 ) )
> , withConversion(\v - > v * 30 , timer("angle " , -7,-9 ) ) ]
-- >
> draw([l , a ] ) = rotated(translated(colored(solidRectangle(l,0.25),red),l/2,0),a )
--
The timer operates in seconds , including decimals . However , the precision
of the timer is not guaranteed beyond one or two decimals .
timer :: (Text, Number, Number) -> Widget
timer (p) = (newWidget (p)) {widget = Timer}
-- | Make the widget use the provided function to convert values from
-- the default range of a widget to a different range.
--
-- Example:
--
-- > newSlider = withConversion(\v -> 20 * v - 10, oldSlider)
--
-- Assuming that the old slider did not have any conversion function applied
-- to it, the example above will make the new slider produce values
between -10 and 10 , while the old slider will still produce values
between 0 and 1
withConversion :: (Number -> Number, Widget) -> Widget
withConversion (conv, w) = w {conversion = conv}
-- | Same functionality as @withConversion@, but using a different convention
-- for the arguments.
setConversion :: (Number -> Number) -> Widget -> Widget
setConversion (conv) (w) = w {conversion = conv}
-- | This is the example shown in the documentation for @guiDrawingOf@
widgetExample1 :: Program
widgetExample1 = guiDrawingOf (widgets, draw)
where
widgets =
[ withConversion (\v -> 1 + 19 * v, slider ("width", -7, -7)),
withConversion (\v -> 1 + 19 * v, slider ("height", -7, -9)),
withConversion (flipflop, toggle ("show circle", -7, -5)),
withConversion (flipflop, button ("show in green", -7, -3)),
withConversion (\v -> 0.2 + 0.8 * v, randomBox ("radius", -7, -1))
]
flipflop (v) = truncation (1 + 2 * v)
draw (values) =
blank
& [blank, circle (r)] #s
& colored (solidRectangle (w, h), [red, green] #c)
where
w = values # 1
h = values # 2
s = values # 3
c = values # 4
r = values # 5
| This is the example shown in the documentation for @guiActivityOf@
widgetExample2 :: Program
widgetExample2 = guiActivityOf (widgets, init, update, draw)
where
widgets =
[ withConversion (\v -> 20 * v, slider ("width", -7, -7)),
withConversion (\v -> 2 + 3 * v, slider ("height", -7, -9)),
withConversion
(\v -> truncation (1 + 2 * v), toggle ("show circle", -7, -5)),
button ("restart", -7, -3),
randomBox ("new color", -7, -1)
]
draw (values, (color@(RGB (r1, r2, r3)), angle, _)) =
colored (base, color)
& [blank, circle (5)] #s
& translated (lettering (msg), 0, 9)
where
msg = joined (["(", printed (r1), ",", printed (r2), ",", printed (r3), ")"])
base = rotated (solidRectangle (w, h), angle)
w = values # 1
h = values # 2
s = values # 3
init (rs) = (RGB (rs # 1, rs # 2, rs # 3), 0, 0)
update (values, (color@(RGB (r1, r2, r3)), angle, wait), TimePassing (_))
| values # 4 > 0, wait == 0 = (RGB (r2, r3, r), 0, values # 4)
| otherwise = (color, angle + 1, wait)
where
r = values # 5
update (values, (color, angle, wait), PointerRelease (_)) = (color, angle, 0)
update (values, state, event) = state
-- | This is the example shown in the documentation for @timer@
widgetExample3 = guiDrawingOf (widgets, draw)
where
widgets =
[ withConversion (\v -> 1 + 9 * v, slider ("length", -7, -7)),
withConversion (\v -> v * 30, timer ("angle", -7, -9))
]
draw ([l, a]) = rotated (translated (colored (solidRectangle (l, 0.25), red), l / 2, 0), a)
-- | This example shows a tree created by a recursive function
widgetExample4 = guiDrawingOf (widgets, draw)
where
Example copied from code shared by cdsmith
depth = 6 : 6 levels of detail
decay = 0.5 : Each smaller branch decreases in size by 50 % .
stem = 0.5 : Branches occur 50 % of the way up the stem .
angle = 30 : Branches point 30 degrees away from the stem .
widgets =
[ slider ("depth", -8, 9.5) .# setConversion (\p -> truncation (3 + 4 * p)),
timer ("decay", -8, 8) .# setConversion (\p -> 0.3 + 0.25 * saw (p, 5)),
timer ("stem", -8, 6.5) .# setConversion (\p -> saw (p, 17)),
slider ("angle", -8, 5) .# setConversion (\p -> 5 + 30 * p)
]
draw ([depth, decay, stem, angle]) =
translated (scaled (branch (depth, decay, stem, angle), 2 * decay, 2 * decay), 0, -5)
branch (0, _, _, _) = polyline [(0, 0), (0, 5)]
branch (depth, decay, stem, angle) =
blank
& polyline [(0, 0), (0, 5)]
& translated (smallBranch, 0, 5)
& translated (rotated (smallBranch, angle), 0, stem * 5)
& translated (rotated (smallBranch, - angle), 0, stem * 5)
where
smallBranch = scaled (branch (depth -1, decay, stem, angle), 1 - decay, 1 - decay)
saw (t, p) = 1 - abs (2 * abs (remainder (t, p)) / p - 1)
--------------------------------------------------------------------------------
Internal
--------------------------------------------------------------------------------
data WidgetType = Button | Toggle | Slider | Random | Counter | Timer
| The internal structure of a @Widget@ is not exposed in the user interface . You
-- have access only to the current value of each widget.
data Widget = Widget
{ selected :: Truth,
highlight :: Truth,
width :: Number,
height :: Number,
centerAt :: (Number, Number),
label :: Text,
conversion :: Number -> Number,
value_ :: Number,
widget :: WidgetType,
randomPool :: [Number]
}
newWidget (l, x, y) =
Widget
{ selected = False,
highlight = False,
width = 4,
height = 1,
centerAt = (x, y),
label = l,
value_ = 0,
conversion = (\v -> v),
widget = Button,
randomPool = []
}
-- The value, adjusted according to the conversion function
value :: Widget -> Number
value (Widget {..}) = value_ .# conversion
-- The current value of a widget is set as follows.
-- For sliders, the value is a Number
between 0 and 1 ( both included ) . For buttons and checkboxes ,
the value is 0 when they are not set and 0.5 when they are set .
-- These values allow user programs to work with either
-- @guiDrawingOf@ or @randomDrawingOf@ interchangeably, without having
-- to alter the calculations in the code.
hit (mx, my, Widget {..}) = abs (mx - x) < width / 2 && abs (my - y) < height / 2
where
(x, y) = centerAt
hitReset (mx, my, Widget {..}) = mx - xmin < 0.3 && abs (my - y) < height / 2
where
(x, y) = centerAt
xmin = x - width / 2
drawWidget (w) = case w .# widget of
Button -> drawButton (w)
Toggle -> drawToggle (w)
Slider -> drawSlider (w)
Random -> drawRandom (w)
Counter -> drawCounter (w)
Timer -> drawTimer (w)
drawButton (Widget {..}) = drawLabel & drawSelection & drawHighlight
where
solid = scaled (solidCircle (0.5), w, h)
outline = scaled (circle (0.5), w, h)
(x, y) = centerAt
msg = dilated (lettering (label), 0.5)
w = 0.9 * width
h = 0.9 * height
drawLabel = translated (msg, x, y)
drawSelection
| selected = translated (colored (solid, grey), x, y)
| otherwise = translated (outline, x, y)
drawHighlight
| highlight = translated (colored (rectangle (width, height), light (grey)), x, y)
| otherwise = blank
drawCounter (Widget {..}) = drawLabel & drawSelection
where
solid = scaled (solidPolygon (points), w, h)
outline = scaled (polygon (points), w, h)
points = [(0.5, 0.3), (0, 0.5), (-0.5, 0.3), (-0.5, -0.3), (0, -0.5), (0.5, -0.3)]
(x, y) = centerAt
msg (txt) = translated (dilated (lettering (txt), 0.5), x, y)
w = 0.9 * width
h = 0.9 * height
drawLabel
| highlight = msg (printed (value_ .# conversion))
| otherwise = msg (label)
drawSelection
| selected = translated (colored (solid, grey), x, y)
| highlight = translated (colored (outline, black), x, y)
| otherwise = translated (colored (outline, grey), x, y)
drawToggle (Widget {..}) = drawSelection & drawLabel & drawHighlight
where
w = 0.5
h = 0.5
x' = x + 2 / 5 * width
drawSelection
| selected = translated (colored (solidRectangle (w, h), grey), x', y)
| otherwise = translated (rectangle (0.9 * w, 0.9 * h), x', y)
drawLabel = translated (msg, x - width / 10, y)
drawHighlight
| highlight =
colored (outline, light (grey))
& translated (rectangle (w, h), x', y)
| otherwise = colored (outline, light (light (grey)))
outline = translated (rectangle (width, height), x, y)
(x, y) = centerAt
msg = dilated (lettering (label), 0.5)
drawTimer (Widget {..}) = drawLabel & drawSelection & drawReset & drawHighlight
where
x' = x + 2 / 5 * width
xmin = x - width / 2
drawLabel
| highlight = msg (printed (value_ .# conversion))
| otherwise = msg (label)
drawSelection
| selected = translated (box (0.5, 0.5), x', y)
| otherwise = translated (rectangle (0.45, 0.45), x', y)
drawReset = translated (box (0.3, height), xmin + 0.15, y)
drawHighlight
| highlight =
outline
& translated (rectangle (0.5, 0.5), x', y)
| otherwise = colored (outline, light (grey))
outline = translated (rectangle (width, height), x, y)
(x, y) = centerAt
msg (txt) = translated (dilated (lettering (txt), 0.5), x - width / 10, y)
box (w, h) = colored (solidRectangle (w, h), grey)
drawSlider (Widget {..}) = info & foreground & background
where
info = translated (infoMsg, x, y - height / 4)
foreground =
translated (solidCircle (height / 4), x', y')
& translated (colored (solidRectangle (width, height / 4), grey), x, y')
x' = x - width / 2 + value_ * width
y' = y + height / 4
background
| highlight = translated (colored (rectangle (width, height), light (grey)), x, y)
| otherwise = blank
(x, y) = centerAt
infoMsg = dilated (lettering (label <> ": " <> printed (value_ .# conversion)), 0.5)
drawRandom (Widget {..}) = drawLabel & drawSelection & drawHighlight
where
solid = scaled (solidRectangle (1, 1), width, height)
outline = scaled (rectangle (1, 1), width, height)
(x, y) = centerAt
msg (txt) = translated (dilated (lettering (txt), 0.5), x, y)
drawLabel
| highlight = msg (printed (value_ .# conversion))
| otherwise = msg (label)
drawSelection
| selected = translated (colored (solid, grey), x, y)
| otherwise = blank
drawHighlight
| highlight = translated (outline, x, y)
| otherwise = colored (translated (outline, x, y), grey)
updateWidget (PointerPress (mx, my)) w@(Widget {..})
| widget == Button,
hit (mx, my, w) =
w
{ selected = True,
highlight = False,
value_ = 0.5
}
| widget == Button =
w
{ selected = False,
highlight = False,
value_ = 0
}
| widget == Counter,
hit (mx, my, w) =
w
{ selected = True,
highlight = True,
value_ = 1 + value_
}
| widget == Toggle,
hit (mx, my, w) =
w
{ selected = not (selected),
value_ = 0.5 - value_,
highlight = True
}
| widget == Timer, hitReset (mx, my, w) = w {value_ = 0}
| widget == Timer,
hit (mx, my, w) =
w
{ selected = not (selected),
highlight = True
}
| widget == Slider,
hit (mx, my, w) =
w
{ selected = True,
highlight = True,
value_ = updateSliderValue (mx, w)
}
| widget == Random,
hit (mx, my, w) =
w
{ selected = True,
highlight = True,
value_ = randomPool # 1,
randomPool = rest (randomPool, 1)
}
| otherwise = w
updateWidget (PointerMovement (mx, my)) (w) =
w .# updateHighlight (mx, my) .# updateSlider (mx)
updateWidget (PointerRelease (_)) w@(Widget {..})
| widget == Toggle = w
| widget == Timer = w
| selected =
w
{ selected = False,
highlight = False,
value_ = if widget == Button then 0 else value_
}
| otherwise = w
updateWidget (TimePassing (dt)) w@(Widget {..})
| widget == Timer, selected = w {value_ = dt + value_}
| otherwise = w
updateWidget (_) (widget) = widget
updateHighlight (mx, my) (w)
| hit (mx, my, w) = w {highlight = True}
| otherwise = w {highlight = False}
updateSlider (mx) w@(Widget {..})
| widget == Slider, selected = w {value_ = updateSliderValue (mx, w)}
| otherwise = w
updateSliderValue (mx, s@(Widget {..})) =
(mx' - x + width / 2) / width
where
mx' = max (x - width / 2, min (x + width / 2, mx))
(x, _) = centerAt
x .# f = f (x)
xs .$ f = [f (x) | x <- xs]
| null | https://raw.githubusercontent.com/google/codeworld/77b0863075be12e3bc5f182a53fcc38b038c3e16/codeworld-base/src/Extras/Widget.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE PackageImports #
| A very simple Graphical User Interface (GUI) for user interaction with
buttons, checkboxes, sliders and a few others.
$intro
* Widgets
* Convenience functions
* Examples
------------------------------------------------------------------------------
$intro
= Widget API
To use the extra features in this module, you must begin your code with this
line:
> import Extras.Widget
| The function @guiDrawingOf@ is an entry point for drawing that allows
Widgets and a function to create your drawing. This user-supplied drawing
function will have access to the list of the current values of the widgets,
which is passed as an argument.
Example of use:
> program = guiDrawingOf(widgets,draw)
> where
> , withConversion(\v -> 0.2 + 0.8 * v, randomBox("radius" ,-7,-1))
> ]
>
> flipflop(v) = truncation(1 + 2 * v)
>
> draw(values) = blank
> & [blank, circle(r)]#s
> where
> w = values#1
> h = values#2
> r = values#5
Note that the order in which the widgets are defined is important,
because it determines how to access the correct value.
takes in a list of widgets. The updating and drawing functions also
receive a list of the current values of the widgets.
Example of use:
> where
> , withConversion
> , button("restart",-7,-3)
> , randomBox("new color",-7,-1)
> ]
>
> draw(values,(color@(RGB(r1,r2,r3)),angle,_)) = colored(base,color)
> & [blank, circle(5)]#s
> & translated(lettering(msg),0,9)
> where
> msg = joined(["(",printed(r1),",",printed(r2),",",printed(r3),")"])
> w = values#1
> h = values#2
>
> init(rs) = (RGB(rs#1,rs#2,rs#3),0,0)
>
> update(values,(color@(RGB(r1,r2,r3)),angle,wait),TimePassing(_))
> | otherwise = (color,angle+1,wait)
> where
> r = values#5
>
>
Note that pre-defined actions on the widgets take precedence over
anything that you define in your updating function, so you cannot
alter the default behavior of the widgets.
| A button placed at the given location. While
but when the button is released, the value reverts
back to 0.
| A toggle (checkbox) with the given label at the given location.
When the box is not set, the value produced is 0. When the
| A slider with the given label at the given location.
value will be 0.
Each time you click on it, the value will change. The
| A button that keeps incrementing the value each time you press it.
| A toggle that counts time up when you set it. When you click on
the left side of the widget, the current value is reset to 0.
You can stop the timer and start it again, and the value will increase
from where it was when you stopped it.
Example:
> program = guiDrawingOf(widgets,draw)
> where
>
| Make the widget use the provided function to convert values from
the default range of a widget to a different range.
Example:
> newSlider = withConversion(\v -> 20 * v - 10, oldSlider)
Assuming that the old slider did not have any conversion function applied
to it, the example above will make the new slider produce values
| Same functionality as @withConversion@, but using a different convention
for the arguments.
| This is the example shown in the documentation for @guiDrawingOf@
| This is the example shown in the documentation for @timer@
| This example shows a tree created by a recursive function
------------------------------------------------------------------------------
------------------------------------------------------------------------------
have access only to the current value of each widget.
The value, adjusted according to the conversion function
The current value of a widget is set as follows.
For sliders, the value is a Number
These values allow user programs to work with either
@guiDrawingOf@ or @randomDrawingOf@ interchangeably, without having
to alter the calculations in the code. | # LANGUAGE ParallelListComp #
# LANGUAGE PatternGuards #
# LANGUAGE RebindableSyntax #
# LANGUAGE RecordWildCards #
# LANGUAGE NoImplicitPrelude #
module Extras.Widget
guiDrawingOf,
guiActivityOf,
Widget,
toggle,
button,
slider,
randomBox,
timer,
counter,
withConversion,
setConversion,
widgetExample1,
widgetExample2,
widgetExample3,
widgetExample4,
)
where
import Prelude
access to a simple GUI . It needs two arguments : a list of
> widgets = [ withConversion(\v - > 1 + 19 * v , slider("width " , -7,-7 ) )
> , withConversion(\v - > 1 + 19 * v , " , -7,-9 ) )
> , withConversion(flipflop , toggle("show circle " , -7,-5 ) )
> , withConversion(flipflop , button("show in green",-7,-3 ) )
> & colored(solidRectangle(w , h),[red , green]#c )
> s = values#3
> c = values#4
Each widget fits in a box 4 units wide and 1 unit high .
guiDrawingOf :: ([Widget], [Number] -> Picture) -> Program
guiDrawingOf (widgetsUser, drawUser) = activityOf (initAll, updateAll, drawAll)
where
initAll (rs) = initRandom (widgetsUser, rs)
updateAll (ws, event) = ws .$ updateWidget (event)
drawAll (ws) = pictures (ws .$ drawWidget) & drawUser (ws .$ value)
| The function @guiActivityOf@ is similar to @activityOf@ , but it also
> program = guiActivityOf(widgets , init , update , draw )
> widgets = [ withConversion(\v - > 20 * v , slider("width",-7,-7 ) )
> , withConversion(\v - > 2 + 3 * v , ) )
> ( \v - > truncation(1 + 2*v ) , ) )
> base = rotated(solidRectangle(w , )
> s = values#3
> | values#4 > 0 , wait = = 0 = ( RGB(r2,r3,r),0,values#4 )
> update(values,(color , angle , ( _ ) ) = ( color , angle,0 )
> update(values , state , event ) = state
guiActivityOf ::
( [Widget],
[Number] -> state,
([Number], state, Event) -> state,
([Number], state) -> Picture
) ->
Program
guiActivityOf (widgetsUser, initUser, updateUser, drawUser) =
activityOf (initAll, updateAll, drawAll)
where
initAll (rs) =
( initRandom (widgetsUser, rest (rs, 1)),
initUser (randomNumbers (rs # 1))
)
updateAll ((widgets, state), event) =
(newWidgets, updateUser (widgets .$ value, state, event))
where
newWidgets = widgets .$ updateWidget (event)
drawAll (widgets, state) =
pictures (widgets .$ drawWidget) & drawUser (widgets .$ value, state)
initRandom (ws, rs) = [t (w, r) | w <- ws | r <- rs]
where
t (w, r)
| isRandom (w) =
let rp = randomNumbers (r)
in w {value_ = rp # 1, randomPool = rest (rp, 1)}
| otherwise = w
isRandom (Widget {widget = Random}) = True
isRandom (_) = False
the button is pressed , the value produced is 0.5 ,
button :: (Text, Number, Number) -> Widget
button (p) = (newWidget (p)) {widget = Button}
box is set , the value produced is 0.5
toggle :: (Text, Number, Number) -> Widget
toggle (p) = (newWidget (p)) {widget = Toggle}
The possible values will range from 0 to 1 , and the initial
slider :: (Text, Number, Number) -> Widget
slider (p) = (newWidget (p)) {widget = Slider}
| A box that produces a random number between 0 and 1 .
value 1 is never produced , so the actual range of
values is 0 to 0.99999 ...
randomBox :: (Text, Number, Number) -> Widget
randomBox (p) = (newWidget (p)) {widget = Random}
The initial value is 1 .
counter :: (Text, Number, Number) -> Widget
counter (p) = (newWidget (p)) {widget = Counter, value_ = 1}
> widgets = [ withConversion(\v - > 1 + 9 * v , slider("length",-7,-7 ) )
> , withConversion(\v - > v * 30 , timer("angle " , -7,-9 ) ) ]
> draw([l , a ] ) = rotated(translated(colored(solidRectangle(l,0.25),red),l/2,0),a )
The timer operates in seconds , including decimals . However , the precision
of the timer is not guaranteed beyond one or two decimals .
timer :: (Text, Number, Number) -> Widget
timer (p) = (newWidget (p)) {widget = Timer}
between -10 and 10 , while the old slider will still produce values
between 0 and 1
withConversion :: (Number -> Number, Widget) -> Widget
withConversion (conv, w) = w {conversion = conv}
setConversion :: (Number -> Number) -> Widget -> Widget
setConversion (conv) (w) = w {conversion = conv}
widgetExample1 :: Program
widgetExample1 = guiDrawingOf (widgets, draw)
where
widgets =
[ withConversion (\v -> 1 + 19 * v, slider ("width", -7, -7)),
withConversion (\v -> 1 + 19 * v, slider ("height", -7, -9)),
withConversion (flipflop, toggle ("show circle", -7, -5)),
withConversion (flipflop, button ("show in green", -7, -3)),
withConversion (\v -> 0.2 + 0.8 * v, randomBox ("radius", -7, -1))
]
flipflop (v) = truncation (1 + 2 * v)
draw (values) =
blank
& [blank, circle (r)] #s
& colored (solidRectangle (w, h), [red, green] #c)
where
w = values # 1
h = values # 2
s = values # 3
c = values # 4
r = values # 5
| This is the example shown in the documentation for @guiActivityOf@
widgetExample2 :: Program
widgetExample2 = guiActivityOf (widgets, init, update, draw)
where
widgets =
[ withConversion (\v -> 20 * v, slider ("width", -7, -7)),
withConversion (\v -> 2 + 3 * v, slider ("height", -7, -9)),
withConversion
(\v -> truncation (1 + 2 * v), toggle ("show circle", -7, -5)),
button ("restart", -7, -3),
randomBox ("new color", -7, -1)
]
draw (values, (color@(RGB (r1, r2, r3)), angle, _)) =
colored (base, color)
& [blank, circle (5)] #s
& translated (lettering (msg), 0, 9)
where
msg = joined (["(", printed (r1), ",", printed (r2), ",", printed (r3), ")"])
base = rotated (solidRectangle (w, h), angle)
w = values # 1
h = values # 2
s = values # 3
init (rs) = (RGB (rs # 1, rs # 2, rs # 3), 0, 0)
update (values, (color@(RGB (r1, r2, r3)), angle, wait), TimePassing (_))
| values # 4 > 0, wait == 0 = (RGB (r2, r3, r), 0, values # 4)
| otherwise = (color, angle + 1, wait)
where
r = values # 5
update (values, (color, angle, wait), PointerRelease (_)) = (color, angle, 0)
update (values, state, event) = state
widgetExample3 = guiDrawingOf (widgets, draw)
where
widgets =
[ withConversion (\v -> 1 + 9 * v, slider ("length", -7, -7)),
withConversion (\v -> v * 30, timer ("angle", -7, -9))
]
draw ([l, a]) = rotated (translated (colored (solidRectangle (l, 0.25), red), l / 2, 0), a)
widgetExample4 = guiDrawingOf (widgets, draw)
where
Example copied from code shared by cdsmith
depth = 6 : 6 levels of detail
decay = 0.5 : Each smaller branch decreases in size by 50 % .
stem = 0.5 : Branches occur 50 % of the way up the stem .
angle = 30 : Branches point 30 degrees away from the stem .
widgets =
[ slider ("depth", -8, 9.5) .# setConversion (\p -> truncation (3 + 4 * p)),
timer ("decay", -8, 8) .# setConversion (\p -> 0.3 + 0.25 * saw (p, 5)),
timer ("stem", -8, 6.5) .# setConversion (\p -> saw (p, 17)),
slider ("angle", -8, 5) .# setConversion (\p -> 5 + 30 * p)
]
draw ([depth, decay, stem, angle]) =
translated (scaled (branch (depth, decay, stem, angle), 2 * decay, 2 * decay), 0, -5)
branch (0, _, _, _) = polyline [(0, 0), (0, 5)]
branch (depth, decay, stem, angle) =
blank
& polyline [(0, 0), (0, 5)]
& translated (smallBranch, 0, 5)
& translated (rotated (smallBranch, angle), 0, stem * 5)
& translated (rotated (smallBranch, - angle), 0, stem * 5)
where
smallBranch = scaled (branch (depth -1, decay, stem, angle), 1 - decay, 1 - decay)
saw (t, p) = 1 - abs (2 * abs (remainder (t, p)) / p - 1)
Internal
data WidgetType = Button | Toggle | Slider | Random | Counter | Timer
| The internal structure of a @Widget@ is not exposed in the user interface . You
data Widget = Widget
{ selected :: Truth,
highlight :: Truth,
width :: Number,
height :: Number,
centerAt :: (Number, Number),
label :: Text,
conversion :: Number -> Number,
value_ :: Number,
widget :: WidgetType,
randomPool :: [Number]
}
newWidget (l, x, y) =
Widget
{ selected = False,
highlight = False,
width = 4,
height = 1,
centerAt = (x, y),
label = l,
value_ = 0,
conversion = (\v -> v),
widget = Button,
randomPool = []
}
value :: Widget -> Number
value (Widget {..}) = value_ .# conversion
between 0 and 1 ( both included ) . For buttons and checkboxes ,
the value is 0 when they are not set and 0.5 when they are set .
hit (mx, my, Widget {..}) = abs (mx - x) < width / 2 && abs (my - y) < height / 2
where
(x, y) = centerAt
hitReset (mx, my, Widget {..}) = mx - xmin < 0.3 && abs (my - y) < height / 2
where
(x, y) = centerAt
xmin = x - width / 2
drawWidget (w) = case w .# widget of
Button -> drawButton (w)
Toggle -> drawToggle (w)
Slider -> drawSlider (w)
Random -> drawRandom (w)
Counter -> drawCounter (w)
Timer -> drawTimer (w)
drawButton (Widget {..}) = drawLabel & drawSelection & drawHighlight
where
solid = scaled (solidCircle (0.5), w, h)
outline = scaled (circle (0.5), w, h)
(x, y) = centerAt
msg = dilated (lettering (label), 0.5)
w = 0.9 * width
h = 0.9 * height
drawLabel = translated (msg, x, y)
drawSelection
| selected = translated (colored (solid, grey), x, y)
| otherwise = translated (outline, x, y)
drawHighlight
| highlight = translated (colored (rectangle (width, height), light (grey)), x, y)
| otherwise = blank
drawCounter (Widget {..}) = drawLabel & drawSelection
where
solid = scaled (solidPolygon (points), w, h)
outline = scaled (polygon (points), w, h)
points = [(0.5, 0.3), (0, 0.5), (-0.5, 0.3), (-0.5, -0.3), (0, -0.5), (0.5, -0.3)]
(x, y) = centerAt
msg (txt) = translated (dilated (lettering (txt), 0.5), x, y)
w = 0.9 * width
h = 0.9 * height
drawLabel
| highlight = msg (printed (value_ .# conversion))
| otherwise = msg (label)
drawSelection
| selected = translated (colored (solid, grey), x, y)
| highlight = translated (colored (outline, black), x, y)
| otherwise = translated (colored (outline, grey), x, y)
drawToggle (Widget {..}) = drawSelection & drawLabel & drawHighlight
where
w = 0.5
h = 0.5
x' = x + 2 / 5 * width
drawSelection
| selected = translated (colored (solidRectangle (w, h), grey), x', y)
| otherwise = translated (rectangle (0.9 * w, 0.9 * h), x', y)
drawLabel = translated (msg, x - width / 10, y)
drawHighlight
| highlight =
colored (outline, light (grey))
& translated (rectangle (w, h), x', y)
| otherwise = colored (outline, light (light (grey)))
outline = translated (rectangle (width, height), x, y)
(x, y) = centerAt
msg = dilated (lettering (label), 0.5)
drawTimer (Widget {..}) = drawLabel & drawSelection & drawReset & drawHighlight
where
x' = x + 2 / 5 * width
xmin = x - width / 2
drawLabel
| highlight = msg (printed (value_ .# conversion))
| otherwise = msg (label)
drawSelection
| selected = translated (box (0.5, 0.5), x', y)
| otherwise = translated (rectangle (0.45, 0.45), x', y)
drawReset = translated (box (0.3, height), xmin + 0.15, y)
drawHighlight
| highlight =
outline
& translated (rectangle (0.5, 0.5), x', y)
| otherwise = colored (outline, light (grey))
outline = translated (rectangle (width, height), x, y)
(x, y) = centerAt
msg (txt) = translated (dilated (lettering (txt), 0.5), x - width / 10, y)
box (w, h) = colored (solidRectangle (w, h), grey)
drawSlider (Widget {..}) = info & foreground & background
where
info = translated (infoMsg, x, y - height / 4)
foreground =
translated (solidCircle (height / 4), x', y')
& translated (colored (solidRectangle (width, height / 4), grey), x, y')
x' = x - width / 2 + value_ * width
y' = y + height / 4
background
| highlight = translated (colored (rectangle (width, height), light (grey)), x, y)
| otherwise = blank
(x, y) = centerAt
infoMsg = dilated (lettering (label <> ": " <> printed (value_ .# conversion)), 0.5)
drawRandom (Widget {..}) = drawLabel & drawSelection & drawHighlight
where
solid = scaled (solidRectangle (1, 1), width, height)
outline = scaled (rectangle (1, 1), width, height)
(x, y) = centerAt
msg (txt) = translated (dilated (lettering (txt), 0.5), x, y)
drawLabel
| highlight = msg (printed (value_ .# conversion))
| otherwise = msg (label)
drawSelection
| selected = translated (colored (solid, grey), x, y)
| otherwise = blank
drawHighlight
| highlight = translated (outline, x, y)
| otherwise = colored (translated (outline, x, y), grey)
updateWidget (PointerPress (mx, my)) w@(Widget {..})
| widget == Button,
hit (mx, my, w) =
w
{ selected = True,
highlight = False,
value_ = 0.5
}
| widget == Button =
w
{ selected = False,
highlight = False,
value_ = 0
}
| widget == Counter,
hit (mx, my, w) =
w
{ selected = True,
highlight = True,
value_ = 1 + value_
}
| widget == Toggle,
hit (mx, my, w) =
w
{ selected = not (selected),
value_ = 0.5 - value_,
highlight = True
}
| widget == Timer, hitReset (mx, my, w) = w {value_ = 0}
| widget == Timer,
hit (mx, my, w) =
w
{ selected = not (selected),
highlight = True
}
| widget == Slider,
hit (mx, my, w) =
w
{ selected = True,
highlight = True,
value_ = updateSliderValue (mx, w)
}
| widget == Random,
hit (mx, my, w) =
w
{ selected = True,
highlight = True,
value_ = randomPool # 1,
randomPool = rest (randomPool, 1)
}
| otherwise = w
updateWidget (PointerMovement (mx, my)) (w) =
w .# updateHighlight (mx, my) .# updateSlider (mx)
updateWidget (PointerRelease (_)) w@(Widget {..})
| widget == Toggle = w
| widget == Timer = w
| selected =
w
{ selected = False,
highlight = False,
value_ = if widget == Button then 0 else value_
}
| otherwise = w
updateWidget (TimePassing (dt)) w@(Widget {..})
| widget == Timer, selected = w {value_ = dt + value_}
| otherwise = w
updateWidget (_) (widget) = widget
updateHighlight (mx, my) (w)
| hit (mx, my, w) = w {highlight = True}
| otherwise = w {highlight = False}
updateSlider (mx) w@(Widget {..})
| widget == Slider, selected = w {value_ = updateSliderValue (mx, w)}
| otherwise = w
updateSliderValue (mx, s@(Widget {..})) =
(mx' - x + width / 2) / width
where
mx' = max (x - width / 2, min (x + width / 2, mx))
(x, _) = centerAt
x .# f = f (x)
xs .$ f = [f (x) | x <- xs]
|
3ce45ed585b09391d2da5855db2294b07d3906058ff92a517e2370e430813886 | rmloveland/scheme48-0.53 | expand.scm | Copyright ( c ) 1994 by . See file COPYING .
Expanding using the Scheme 48 expander .
(define (scan-packages packages)
(let ((definitions
(fold (lambda (package definitions)
(let ((cenv (package->environment package)))
(fold (lambda (form definitions)
(let ((node (expand-form form cenv)))
(cond ((define-node? node)
(cons (eval-define (expand node cenv)
cenv)
definitions))
(else
(eval-node (expand node cenv)
global-ref
global-set!
eval-primitive)
definitions))))
(call-with-values
(lambda ()
(package-source package))
(lambda (files.forms usual-transforms primitives?)
(scan-forms (apply append (map cdr files.forms))
cenv)))
definitions)))
packages
'())))
(reverse (map (lambda (var)
(let ((value (variable-flag var)))
(set-variable-flag! var #f)
(cons var value)))
definitions))))
(define package->environment (structure-ref packages package->environment))
(define define-node? (node-predicate 'define))
(define (eval-define node cenv)
(let* ((form (node-form node))
(value (eval-node (caddr form)
global-ref
global-set!
eval-primitive))
(lhs (cadr form)))
(global-set! lhs value)
(name->variable-or-value lhs)))
(define (global-ref name)
(let ((thing (name->variable-or-value name)))
(if (variable? thing)
(variable-flag thing)
thing)))
(define (global-set! name value)
(let ((thing (name->variable-or-value name)))
(if (primitive? thing)
(bug "trying to set the value of primitive ~S" thing)
(set-variable-flag! thing value))))
(define (name->variable-or-value name)
(let ((binding (node-ref name 'binding)))
(if (binding? binding)
(let ((value (binding-place binding))
(static (binding-static binding)))
(cond ((primitive? static)
static)
((variable? value)
value)
((and (location? value)
(constant? (contents value)))
(contents value))
(else
(bug "global binding is not a variable, primitive or constant ~S" name))))
(user-error "unbound variable ~S" (node-form name)))))
| null | https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/ps-compiler/prescheme/expand.scm | scheme | Copyright ( c ) 1994 by . See file COPYING .
Expanding using the Scheme 48 expander .
(define (scan-packages packages)
(let ((definitions
(fold (lambda (package definitions)
(let ((cenv (package->environment package)))
(fold (lambda (form definitions)
(let ((node (expand-form form cenv)))
(cond ((define-node? node)
(cons (eval-define (expand node cenv)
cenv)
definitions))
(else
(eval-node (expand node cenv)
global-ref
global-set!
eval-primitive)
definitions))))
(call-with-values
(lambda ()
(package-source package))
(lambda (files.forms usual-transforms primitives?)
(scan-forms (apply append (map cdr files.forms))
cenv)))
definitions)))
packages
'())))
(reverse (map (lambda (var)
(let ((value (variable-flag var)))
(set-variable-flag! var #f)
(cons var value)))
definitions))))
(define package->environment (structure-ref packages package->environment))
(define define-node? (node-predicate 'define))
(define (eval-define node cenv)
(let* ((form (node-form node))
(value (eval-node (caddr form)
global-ref
global-set!
eval-primitive))
(lhs (cadr form)))
(global-set! lhs value)
(name->variable-or-value lhs)))
(define (global-ref name)
(let ((thing (name->variable-or-value name)))
(if (variable? thing)
(variable-flag thing)
thing)))
(define (global-set! name value)
(let ((thing (name->variable-or-value name)))
(if (primitive? thing)
(bug "trying to set the value of primitive ~S" thing)
(set-variable-flag! thing value))))
(define (name->variable-or-value name)
(let ((binding (node-ref name 'binding)))
(if (binding? binding)
(let ((value (binding-place binding))
(static (binding-static binding)))
(cond ((primitive? static)
static)
((variable? value)
value)
((and (location? value)
(constant? (contents value)))
(contents value))
(else
(bug "global binding is not a variable, primitive or constant ~S" name))))
(user-error "unbound variable ~S" (node-form name)))))
|
|
adea3d4475423bfeffcc00b5a739f857e0b06369f29ccad924f0c78cba93e1e5 | AlacrisIO/legicash-facts | assembly.ml | open Legilogic_lib
open Lib
open Signing
(* In the future, segments can be nested, and
offset would be relative to a subsegment of a segment,
to be fully resolved when the segment size is finalized.
(Also, a non-embedded front-end syntax.)
For now, everything is fixed size and we don't compute
label offsets much less optimize segment layout:
instead we merely *check* that labels are used properly
and the formulas match.
*)
type offset = int [@@deriving show, yojson, rlp]
24576 , limit set by EIP 170 -170.md
let max_segment_size = 0x6000
TODO : use pure functional arrays ?
module Segment = struct
type state =
| Bytes of Bytes.t
| Buffer of Butter.t
| Concat of Segment list
type t = { i d : int ; name : string ; state : mutable state ; offset : offset }
let create asm =
let segment =
{ id = new_id
; state = Buffer ( Buffer.create max_segment_size )
; offset = in
register_segment asm segment ;
segment
end
module Segment = struct
type state =
| Bytes of Bytes.t
| Buffer of Butter.t
| Concat of Segment list
type t = { id : int; name : string ; state : mutable state ; offset : offset }
let create asm =
let segment =
{ id=new_id
; state=Buffer (Buffer.create max_segment_size)
; offset=current_offset asm } in
register_segment asm segment;
segment
end
*)
type expr =
| Offset of offset
| Label of string
| Add of expr * expr
| Sub of expr * expr [@@deriving show, yojson, rlp]
module Fixup = struct
(* for now, manually set by the user, in the future, can be dynamic in a range? *)
type size = int [@@deriving show, yojson, rlp]
type t = expr * size [@@deriving show, yojson, rlp]
end
module Label = struct
type t = { offset : offset option
; fixups : offset list } [@@deriving show, yojson, rlp]
end
module Assembler = struct
type t = { buffer : Buffer.t (* in the future, a Segment.t *)
; labels : (string, Label.t) Hashtbl.t
; fixups : (int, Fixup.t) Hashtbl.t }
let create () = { buffer = Buffer.create max_segment_size
; labels = Hashtbl.create 100
; fixups = Hashtbl.create 200 }
end
TODO : have chunks of code of constant or unknown but bounded length ,
labels , fixups , displacements , etc . ; compile - time merging of constant stuff ( ? )
labels, fixups, displacements, etc.; compile-time merging of constant stuff(?) *)
type directive = Assembler.t -> unit
exception Label_already_defined
let rec eval_expr labels = function
| Offset o -> o
| Label l -> Option.get (Hashtbl.find labels l).Label.offset
| Add (x, y) -> (eval_expr labels x) + (eval_expr labels y)
| Sub (x, y) -> (eval_expr labels x) - (eval_expr labels y)
let char x asm = Buffer.add_char asm.Assembler.buffer x
let byte x = char (Char.chr x)
let string s asm = Buffer.add_string asm.Assembler.buffer s
let rec int size value asm =
if size > 0 then
(byte ((value lsr (8 * (size - 1))) land 255) asm;
int (size - 1) value asm)
let current_offset asm = Buffer.length asm.Assembler.buffer
let check_byte asm offset value msg =
if not (Buffer.nth asm.Assembler.buffer offset = Char.chr value) then
raise (Internal_error (msg ()))
let rec get_buffer_value buffer offset size =
if size = 0 then 0 else
let v = Char.code (Buffer.nth buffer offset) in
if size = 1 then v else 256 * v + (get_buffer_value buffer (offset + 1) (size - 1))
let rec check_bytes asm n offset value msg =
if n > 0 then
(check_byte asm offset ((value lsr (8 * (n - 1))) land 255) msg;
check_bytes asm (n - 1) (offset + 1) value msg)
let check_fixup asm offset (expr, size) =
let value = eval_expr asm.Assembler.labels expr in
if not (value >= 0 && Z.(numbits (of_int value)) < (8 * size)) then
bork "fixup @ %d %s size %d has incorrect computed value %d"
offset (show_expr expr) size value;
check_bytes asm size offset value
(fun _ -> Printf.sprintf "fixup @ %d %s size %d computed value %d doesn't match given value %d"
offset (show_expr expr) size value (get_buffer_value asm.Assembler.buffer offset size));
Hashtbl.remove asm.Assembler.fixups offset
let examine_fixup asm offset (expr, size) =
try check_fixup asm offset (expr, size) with _ -> () (* TODO: have useful error messages *)
let fixup size expr value asm =
let offset = Buffer.length asm.Assembler.buffer in
int size value asm;
Hashtbl.add asm.Assembler.fixups offset (expr, size)
let label l asm =
match Hashtbl.find_opt asm.Assembler.labels l with
| Some { offset= Some _ } ->
raise Label_already_defined
| Some { fixups } ->
let lbl = Label.{ offset=Some (current_offset asm); fixups } in
Hashtbl.replace asm.labels l lbl
| None ->
let lbl = Label.{ offset=Some (current_offset asm); fixups= [] } in
Hashtbl.add asm.labels l lbl
let eSTOP = byte 0x00 (* Halts execution - 0 *)
Addition operation - 3
Multiplication operation - 5
Subtraction operation - 3
Integer division operation - 5
Signed integer division operation ( truncated ) - 5
Modulo remainder operation - 5
Signed modulo remainder operation - 5
Modulo addition operation - 8
Modulo multiplication operation - 8
let eEXP = byte 0x0a (* Exponential operation - 10* *)
Extend length of two 's complement signed integer - 5
0x0c - 0x0f Unused Unused -
Less - than comparison - 3
Greater - than comparison - 3
Signed less - than comparison - 3
Signed greater - than comparison - 3
Equality comparison - 3
Simple not operator - 3
Bitwise AND operation - 3
Bitwise OR operation - 3
Bitwise XOR operation - 3
Bitwise NOT operation - 3
Retrieve single byte from word - 3
let eSHA3 = byte 0x20 (* Compute Keccak-256 hash - 30* *)
0x21 - 0x2f Unused Unused
Get address of currently executing account - 2
Get balance of the given account - 400
Get execution origination address - 2
Get caller address - 2
Get deposited value by the instruction / transaction responsible for this execution - 2
Get input data of current environment - 3
Get size of input data in current environment - 2 *
Copy input data in current environment to memory - 3
Get size of code running in current environment - 2
Copy code running in current environment to memory - 3 *
Get price of gas in current environment - 2
Get size of an account 's code - 700
Copy an account 's code to memory - 700 *
Pushes the size of the return data buffer onto the stack EIP 211 2
Copies data from the return data buffer to memory EIP 211 3
let eUNUSED = byte 0x3f (* - *)
Get the hash of one of the 256 most recent complete blocks - 20
Get the block 's beneficiary address - 2
Get the block 's timestamp - 2
Get the block 's number - 2
Get the block 's difficulty - 2
Get the block 's gas limit - 2
(* 0x46 - 0x4f Unused - *)
Remove word from stack - 2
Load word from memory - 3 *
Save word to memory - 3 *
Save byte to memory - 3
Load word from storage - 200
Save word to storage - 20000 * *
Alter the program counter - 8
Conditionally alter the program counter - 10
Get the value of the program counter prior to the increment - 2
Get the size of active memory in bytes - 2
Get the amount of available gas , including the corresponding reduction the amount of available gas - 2
Mark a valid destination for jumps - 1
0x5c - 0x5f Unused -
Place 1 byte item on stack - 3
Place 2 - byte item on stack - 3
Place 3 - byte item on stack - 3
Place 4 - byte item on stack - 3
Place 5 - byte item on stack - 3
Place 6 - byte item on stack - 3
Place 7 - byte item on stack - 3
Place 8 - byte item on stack - 3
Place 9 - byte item on stack - 3
Place 10 - byte item on stack - 3
Place 11 - byte item on stack - 3
Place 12 - byte item on stack - 3
Place 13 - byte item on stack - 3
Place 14 - byte item on stack - 3
Place 15 - byte item on stack - 3
Place 16 - byte item on stack - 3
Place 17 - byte item on stack - 3
Place 18 - byte item on stack - 3
Place 19 - byte item on stack - 3
Place 20 - byte item on stack - 3
Place 21 - byte item on stack - 3
Place 22 - byte item on stack - 3
Place 23 - byte item on stack - 3
Place 24 - byte item on stack - 3
Place 25 - byte item on stack - 3
Place 26 - byte item on stack - 3
Place 27 - byte item on stack - 3
Place 28 - byte item on stack - 3
Place 29 - byte item on stack - 3
Place 30 - byte item on stack - 3
Place 31 - byte item on stack - 3
Place 32 - byte ( full word ) item on stack - 3
Duplicate 1st stack item - 3
Duplicate 2nd stack item - 3
Duplicate 3rd stack item - 3
Duplicate 4th stack item - 3
Duplicate 5th stack item - 3
Duplicate 6th stack item - 3
Duplicate 7th stack item - 3
Duplicate 8th stack item - 3
Duplicate 9th stack item - 3
Duplicate 10th stack item - 3
Duplicate 11th stack item - 3
Duplicate 12th stack item - 3
Duplicate 13th stack item - 3
Duplicate 14th stack item - 3
Duplicate 15th stack item - 3
Duplicate 16th stack item - 3
Exchange 1st and 2nd stack items - 3
Exchange 1st and 3rd stack items - 3
Exchange 1st and 4th stack items - 3
Exchange 1st and 5th stack items - 3
Exchange 1st and 6th stack items - 3
Exchange 1st and 7th stack items - 3
Exchange 1st and 8th stack items - 3
Exchange 1st and 9th stack items - 3
Exchange 1st and 10th stack items - 3
Exchange 1st and 11th stack items - 3
Exchange 1st and 12th stack items - 3
Exchange 1st and 13th stack items - 3
Exchange 1st and 14th stack items - 3
Exchange 1st and 15th stack items - 3
Exchange 1st and 16th stack items - 3
Exchange 1st and 17th stack items - 3
Append log record with no topics - 375
Append log record with one topic - 750
Append log record with two topics - 1125
Append log record with three topics - 1500
Append log record with four topics - 1875
(* 0xa5 - 0xaf Unused - *)
Tentative libevmasm has different numbers EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
(* 0xbb - 0xe0 Unused - *)
let eSLOADBYTES = byte 0xe1 (* Only referenced in pyethereum - - *)
let eSSTOREBYTES = byte 0xe2 (* Only referenced in pyethereum - - *)
let eSSIZE = byte 0xe3 (* Only referenced in pyethereum - - *)
0xe4 - 0xef Unused -
Create a new account with associated code - 32000
let eCALL = byte 0xf1 (* Message-call into an account - Complicated *)
let eCALLCODE = byte 0xf2 (* Message-call into this account with alternative account's code - Complicated *)
let eRETURN = byte 0xf3 (* Halt execution returning output data - 0 *)
let eDELEGATECALL = byte 0xf4 (* Message-call into this account with an alternative account's code, but persisting into this account with an alternative account's code - Complicated *)
let eCALLBLACKBOX = byte 0xf5 (* - - *)
(* 0xf6 - 0xf9 Unused - - *)
Similar to CALL , but does not modify state - 40
Create a new account and set creation address to sha3(sender + sha3(init code ) ) % 2**160 -
let eTXEXECGAS = byte 0xfc (* Not in yellow paper FIXME - - *)
let eREVERT = byte 0xfd (* Stop execution and revert state changes, without consuming all provided gas and providing a reason - 0 *)
let eINVALID = byte 0xfe (* Designated invalid instruction - 0 *)
Halt execution and register account for later deletion - 5000 *
let jumplabel l asm =
label l asm; eJUMPDEST asm
let pushlabel1 l n asm =
ePUSH1 asm; fixup 1 (Label l) n asm
let pushlabel2 l n asm =
ePUSH2 asm; fixup 2 (Label l) n asm
let jump1 l n asm =
pushlabel1 l n asm; eJUMP asm
let jump2 l n asm =
pushlabel2 l n asm; eJUMP asm
let jumpi1 l n asm =
pushlabel1 l n asm; eJUMPI asm
let jumpi2 l n asm =
pushlabel2 l n asm; eJUMPI asm
NB : fixed size for now , even if the address starts with zeros ,
because the current assembler can not deal with dynamic sizes
because the current assembler cannot deal with dynamic sizes *)
let push_address address asm =
ePUSH20 asm; string (Address.to_big_endian_bits address) asm
let rec push_z z asm =
let s = Z.sign z in
if (s = -1) && (Z.numbits z < 240) then
(push_z (Z.lognot z) asm; eNOT asm)
else if s = 0 then
(ePUSH1 asm; byte 0 asm)
else
let bits = string_reverse Z.(to_bits (extract z 0 256)) in
(byte (0x5f + (String.length bits)) asm; string bits asm)
let rec push_int n asm =
if n < 0 then
(push_int (lnot n) asm; eNOT asm)
else if n < 256 then
(ePUSH1 asm; byte n asm)
else
push_z (Z.of_int n) asm
type program = directive list
let assemble_directives buffer program =
List.iter (fun directive -> directive buffer) program
let assemble program =
let asm = Assembler.create () in
assemble_directives asm program;
Hashtbl.iter (check_fixup asm) asm.Assembler.fixups;
Buffer.contents asm.Assembler.buffer
| null | https://raw.githubusercontent.com/AlacrisIO/legicash-facts/5d3663bade68c09bed47b3f58fa12580f38fdb46/src/legilogic_ethereum/assembly.ml | ocaml | In the future, segments can be nested, and
offset would be relative to a subsegment of a segment,
to be fully resolved when the segment size is finalized.
(Also, a non-embedded front-end syntax.)
For now, everything is fixed size and we don't compute
label offsets much less optimize segment layout:
instead we merely *check* that labels are used properly
and the formulas match.
for now, manually set by the user, in the future, can be dynamic in a range?
in the future, a Segment.t
TODO: have useful error messages
Halts execution - 0
Exponential operation - 10*
Compute Keccak-256 hash - 30*
-
0x46 - 0x4f Unused -
0xa5 - 0xaf Unused -
0xbb - 0xe0 Unused -
Only referenced in pyethereum - -
Only referenced in pyethereum - -
Only referenced in pyethereum - -
Message-call into an account - Complicated
Message-call into this account with alternative account's code - Complicated
Halt execution returning output data - 0
Message-call into this account with an alternative account's code, but persisting into this account with an alternative account's code - Complicated
- -
0xf6 - 0xf9 Unused - -
Not in yellow paper FIXME - -
Stop execution and revert state changes, without consuming all provided gas and providing a reason - 0
Designated invalid instruction - 0 | open Legilogic_lib
open Lib
open Signing
type offset = int [@@deriving show, yojson, rlp]
24576 , limit set by EIP 170 -170.md
let max_segment_size = 0x6000
TODO : use pure functional arrays ?
module Segment = struct
type state =
| Bytes of Bytes.t
| Buffer of Butter.t
| Concat of Segment list
type t = { i d : int ; name : string ; state : mutable state ; offset : offset }
let create asm =
let segment =
{ id = new_id
; state = Buffer ( Buffer.create max_segment_size )
; offset = in
register_segment asm segment ;
segment
end
module Segment = struct
type state =
| Bytes of Bytes.t
| Buffer of Butter.t
| Concat of Segment list
type t = { id : int; name : string ; state : mutable state ; offset : offset }
let create asm =
let segment =
{ id=new_id
; state=Buffer (Buffer.create max_segment_size)
; offset=current_offset asm } in
register_segment asm segment;
segment
end
*)
type expr =
| Offset of offset
| Label of string
| Add of expr * expr
| Sub of expr * expr [@@deriving show, yojson, rlp]
module Fixup = struct
type size = int [@@deriving show, yojson, rlp]
type t = expr * size [@@deriving show, yojson, rlp]
end
module Label = struct
type t = { offset : offset option
; fixups : offset list } [@@deriving show, yojson, rlp]
end
module Assembler = struct
; labels : (string, Label.t) Hashtbl.t
; fixups : (int, Fixup.t) Hashtbl.t }
let create () = { buffer = Buffer.create max_segment_size
; labels = Hashtbl.create 100
; fixups = Hashtbl.create 200 }
end
TODO : have chunks of code of constant or unknown but bounded length ,
labels , fixups , displacements , etc . ; compile - time merging of constant stuff ( ? )
labels, fixups, displacements, etc.; compile-time merging of constant stuff(?) *)
type directive = Assembler.t -> unit
exception Label_already_defined
let rec eval_expr labels = function
| Offset o -> o
| Label l -> Option.get (Hashtbl.find labels l).Label.offset
| Add (x, y) -> (eval_expr labels x) + (eval_expr labels y)
| Sub (x, y) -> (eval_expr labels x) - (eval_expr labels y)
let char x asm = Buffer.add_char asm.Assembler.buffer x
let byte x = char (Char.chr x)
let string s asm = Buffer.add_string asm.Assembler.buffer s
let rec int size value asm =
if size > 0 then
(byte ((value lsr (8 * (size - 1))) land 255) asm;
int (size - 1) value asm)
let current_offset asm = Buffer.length asm.Assembler.buffer
let check_byte asm offset value msg =
if not (Buffer.nth asm.Assembler.buffer offset = Char.chr value) then
raise (Internal_error (msg ()))
let rec get_buffer_value buffer offset size =
if size = 0 then 0 else
let v = Char.code (Buffer.nth buffer offset) in
if size = 1 then v else 256 * v + (get_buffer_value buffer (offset + 1) (size - 1))
let rec check_bytes asm n offset value msg =
if n > 0 then
(check_byte asm offset ((value lsr (8 * (n - 1))) land 255) msg;
check_bytes asm (n - 1) (offset + 1) value msg)
let check_fixup asm offset (expr, size) =
let value = eval_expr asm.Assembler.labels expr in
if not (value >= 0 && Z.(numbits (of_int value)) < (8 * size)) then
bork "fixup @ %d %s size %d has incorrect computed value %d"
offset (show_expr expr) size value;
check_bytes asm size offset value
(fun _ -> Printf.sprintf "fixup @ %d %s size %d computed value %d doesn't match given value %d"
offset (show_expr expr) size value (get_buffer_value asm.Assembler.buffer offset size));
Hashtbl.remove asm.Assembler.fixups offset
let examine_fixup asm offset (expr, size) =
let fixup size expr value asm =
let offset = Buffer.length asm.Assembler.buffer in
int size value asm;
Hashtbl.add asm.Assembler.fixups offset (expr, size)
let label l asm =
match Hashtbl.find_opt asm.Assembler.labels l with
| Some { offset= Some _ } ->
raise Label_already_defined
| Some { fixups } ->
let lbl = Label.{ offset=Some (current_offset asm); fixups } in
Hashtbl.replace asm.labels l lbl
| None ->
let lbl = Label.{ offset=Some (current_offset asm); fixups= [] } in
Hashtbl.add asm.labels l lbl
Addition operation - 3
Multiplication operation - 5
Subtraction operation - 3
Integer division operation - 5
Signed integer division operation ( truncated ) - 5
Modulo remainder operation - 5
Signed modulo remainder operation - 5
Modulo addition operation - 8
Modulo multiplication operation - 8
Extend length of two 's complement signed integer - 5
0x0c - 0x0f Unused Unused -
Less - than comparison - 3
Greater - than comparison - 3
Signed less - than comparison - 3
Signed greater - than comparison - 3
Equality comparison - 3
Simple not operator - 3
Bitwise AND operation - 3
Bitwise OR operation - 3
Bitwise XOR operation - 3
Bitwise NOT operation - 3
Retrieve single byte from word - 3
0x21 - 0x2f Unused Unused
Get address of currently executing account - 2
Get balance of the given account - 400
Get execution origination address - 2
Get caller address - 2
Get deposited value by the instruction / transaction responsible for this execution - 2
Get input data of current environment - 3
Get size of input data in current environment - 2 *
Copy input data in current environment to memory - 3
Get size of code running in current environment - 2
Copy code running in current environment to memory - 3 *
Get price of gas in current environment - 2
Get size of an account 's code - 700
Copy an account 's code to memory - 700 *
Pushes the size of the return data buffer onto the stack EIP 211 2
Copies data from the return data buffer to memory EIP 211 3
Get the hash of one of the 256 most recent complete blocks - 20
Get the block 's beneficiary address - 2
Get the block 's timestamp - 2
Get the block 's number - 2
Get the block 's difficulty - 2
Get the block 's gas limit - 2
Remove word from stack - 2
Load word from memory - 3 *
Save word to memory - 3 *
Save byte to memory - 3
Load word from storage - 200
Save word to storage - 20000 * *
Alter the program counter - 8
Conditionally alter the program counter - 10
Get the value of the program counter prior to the increment - 2
Get the size of active memory in bytes - 2
Get the amount of available gas , including the corresponding reduction the amount of available gas - 2
Mark a valid destination for jumps - 1
0x5c - 0x5f Unused -
Place 1 byte item on stack - 3
Place 2 - byte item on stack - 3
Place 3 - byte item on stack - 3
Place 4 - byte item on stack - 3
Place 5 - byte item on stack - 3
Place 6 - byte item on stack - 3
Place 7 - byte item on stack - 3
Place 8 - byte item on stack - 3
Place 9 - byte item on stack - 3
Place 10 - byte item on stack - 3
Place 11 - byte item on stack - 3
Place 12 - byte item on stack - 3
Place 13 - byte item on stack - 3
Place 14 - byte item on stack - 3
Place 15 - byte item on stack - 3
Place 16 - byte item on stack - 3
Place 17 - byte item on stack - 3
Place 18 - byte item on stack - 3
Place 19 - byte item on stack - 3
Place 20 - byte item on stack - 3
Place 21 - byte item on stack - 3
Place 22 - byte item on stack - 3
Place 23 - byte item on stack - 3
Place 24 - byte item on stack - 3
Place 25 - byte item on stack - 3
Place 26 - byte item on stack - 3
Place 27 - byte item on stack - 3
Place 28 - byte item on stack - 3
Place 29 - byte item on stack - 3
Place 30 - byte item on stack - 3
Place 31 - byte item on stack - 3
Place 32 - byte ( full word ) item on stack - 3
Duplicate 1st stack item - 3
Duplicate 2nd stack item - 3
Duplicate 3rd stack item - 3
Duplicate 4th stack item - 3
Duplicate 5th stack item - 3
Duplicate 6th stack item - 3
Duplicate 7th stack item - 3
Duplicate 8th stack item - 3
Duplicate 9th stack item - 3
Duplicate 10th stack item - 3
Duplicate 11th stack item - 3
Duplicate 12th stack item - 3
Duplicate 13th stack item - 3
Duplicate 14th stack item - 3
Duplicate 15th stack item - 3
Duplicate 16th stack item - 3
Exchange 1st and 2nd stack items - 3
Exchange 1st and 3rd stack items - 3
Exchange 1st and 4th stack items - 3
Exchange 1st and 5th stack items - 3
Exchange 1st and 6th stack items - 3
Exchange 1st and 7th stack items - 3
Exchange 1st and 8th stack items - 3
Exchange 1st and 9th stack items - 3
Exchange 1st and 10th stack items - 3
Exchange 1st and 11th stack items - 3
Exchange 1st and 12th stack items - 3
Exchange 1st and 13th stack items - 3
Exchange 1st and 14th stack items - 3
Exchange 1st and 15th stack items - 3
Exchange 1st and 16th stack items - 3
Exchange 1st and 17th stack items - 3
Append log record with no topics - 375
Append log record with one topic - 750
Append log record with two topics - 1125
Append log record with three topics - 1500
Append log record with four topics - 1875
Tentative libevmasm has different numbers EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
Tentative EIP 615
0xe4 - 0xef Unused -
Create a new account with associated code - 32000
Similar to CALL , but does not modify state - 40
Create a new account and set creation address to sha3(sender + sha3(init code ) ) % 2**160 -
Halt execution and register account for later deletion - 5000 *
let jumplabel l asm =
label l asm; eJUMPDEST asm
let pushlabel1 l n asm =
ePUSH1 asm; fixup 1 (Label l) n asm
let pushlabel2 l n asm =
ePUSH2 asm; fixup 2 (Label l) n asm
let jump1 l n asm =
pushlabel1 l n asm; eJUMP asm
let jump2 l n asm =
pushlabel2 l n asm; eJUMP asm
let jumpi1 l n asm =
pushlabel1 l n asm; eJUMPI asm
let jumpi2 l n asm =
pushlabel2 l n asm; eJUMPI asm
NB : fixed size for now , even if the address starts with zeros ,
because the current assembler can not deal with dynamic sizes
because the current assembler cannot deal with dynamic sizes *)
let push_address address asm =
ePUSH20 asm; string (Address.to_big_endian_bits address) asm
let rec push_z z asm =
let s = Z.sign z in
if (s = -1) && (Z.numbits z < 240) then
(push_z (Z.lognot z) asm; eNOT asm)
else if s = 0 then
(ePUSH1 asm; byte 0 asm)
else
let bits = string_reverse Z.(to_bits (extract z 0 256)) in
(byte (0x5f + (String.length bits)) asm; string bits asm)
let rec push_int n asm =
if n < 0 then
(push_int (lnot n) asm; eNOT asm)
else if n < 256 then
(ePUSH1 asm; byte n asm)
else
push_z (Z.of_int n) asm
type program = directive list
let assemble_directives buffer program =
List.iter (fun directive -> directive buffer) program
let assemble program =
let asm = Assembler.create () in
assemble_directives asm program;
Hashtbl.iter (check_fixup asm) asm.Assembler.fixups;
Buffer.contents asm.Assembler.buffer
|
395f00a0f826d9ed5c3e5c7172edbf1299d4d6b285f1f3fac4283adb06cbf732 | duanebester/clunk | buffered_message_socket.cljc | (ns com.clunk.buffered-message-socket
(:require [clojure.core.match :as m]
[clojure.core.async :as async]
[com.clunk.message-socket :as ms]))
(defrecord BufferedMessageSocket [buffered-socket in-ch out-ch])
(def status-map (atom {}))
(defn handle-backend-message [message]
(println "Backend: " message)
(m/match message
{:type :ParameterStatus}
(let [[key val] (:status message)]
(swap! status-map assoc (key key) val))
(else nil)))
(defn handle-incoming [incoming]
(println "Incoming: " incoming))
(defn get-buffered-socket
([port] (get-buffered-socket port "localhost"))
([port host]
(let [buffered-socket (ms/get-message-socket port host)
in-ch (async/chan)
out-ch (async/chan)
message-sock (map->BufferedMessageSocket {:buffered-socket buffered-socket
:in in-ch
:out out-ch})]
(async/go-loop []
(let [ms (async/<! (:in buffered-socket))]
(if-not ms
(ms/close-message-socket buffered-socket)
(when (async/>! in-ch (handle-backend-message ms))
(recur)))))
(async/go-loop []
(let [incoming (async/<! out-ch)]
(if-not incoming
(ms/close-message-socket buffered-socket)
(when (async/>! (:out buffered-socket) (handle-incoming incoming))
(recur)))))
message-sock)))
| null | https://raw.githubusercontent.com/duanebester/clunk/86c50a32230e055ba3b0dd1e34f31e05a32cab20/src/com/clunk/buffered_message_socket.cljc | clojure | (ns com.clunk.buffered-message-socket
(:require [clojure.core.match :as m]
[clojure.core.async :as async]
[com.clunk.message-socket :as ms]))
(defrecord BufferedMessageSocket [buffered-socket in-ch out-ch])
(def status-map (atom {}))
(defn handle-backend-message [message]
(println "Backend: " message)
(m/match message
{:type :ParameterStatus}
(let [[key val] (:status message)]
(swap! status-map assoc (key key) val))
(else nil)))
(defn handle-incoming [incoming]
(println "Incoming: " incoming))
(defn get-buffered-socket
([port] (get-buffered-socket port "localhost"))
([port host]
(let [buffered-socket (ms/get-message-socket port host)
in-ch (async/chan)
out-ch (async/chan)
message-sock (map->BufferedMessageSocket {:buffered-socket buffered-socket
:in in-ch
:out out-ch})]
(async/go-loop []
(let [ms (async/<! (:in buffered-socket))]
(if-not ms
(ms/close-message-socket buffered-socket)
(when (async/>! in-ch (handle-backend-message ms))
(recur)))))
(async/go-loop []
(let [incoming (async/<! out-ch)]
(if-not incoming
(ms/close-message-socket buffered-socket)
(when (async/>! (:out buffered-socket) (handle-incoming incoming))
(recur)))))
message-sock)))
|
|
d1c8d411925d3fc6e0a01e62d5529e337efe1ca5d5d6091c6e5659214e9994cf | helium/erlang-libp2p | libp2p_config.erl | -module(libp2p_config).
-export([get_opt/2, get_opt/3,
base_dir/1, swarm_dir/2,
insert_pid/4, lookup_pid/3, lookup_pids/2, remove_pid/2, remove_pid/3, gc_pids/1,
session/0, insert_session/3, insert_session/4, lookup_session/2, lookup_session/3, remove_session/2,
lookup_sessions/1, lookup_session_addrs/2, lookup_session_addrs/1, lookup_session_direction/2,
insert_session_addr_info/3, lookup_session_addr_info/2,
transport/0, insert_transport/3, lookup_transport/2, lookup_transports/1,
listen_addrs/1, listener/0, lookup_listener/2, insert_listener/3, remove_listener/2,
listen_socket/0, lookup_listen_socket/2, lookup_listen_socket_by_addr/2, insert_listen_socket/4, remove_listen_socket/2, listen_sockets/1,
lookup_connection_handlers/1, insert_connection_handler/2,
lookup_stream_handlers/1, insert_stream_handler/2, remove_stream_handler/2,
insert_group/3, lookup_group/2, remove_group/2, all_groups/1,
insert_relay/2, lookup_relay/1, remove_relay/1,
insert_relay_stream/3, lookup_relay_stream/2, remove_relay_stream/2,
insert_relay_sessions/3, lookup_relay_sessions/2, remove_relay_sessions/2,
insert_proxy/2, lookup_proxy/1, remove_proxy/1,
insert_nat/2, lookup_nat/1, remove_nat/1]).
-define(CONNECTION_HANDLER, connection_handler).
-define(STREAM_HANDLER, stream_handler).
-define(TRANSPORT, transport).
-define(SESSION, session).
-define(SESSION_DIRECTION, session_direction).
-define(LISTENER, listener).
-define(LISTEN_SOCKET, listen_socket).
-define(GROUP, group).
-define(RELAY, relay).
-define(RELAY_STREAM, relay_stream).
-define(RELAY_SESSIONS, relay_sessions).
-define(PROXY, proxy).
-define(NAT, nat).
-define(ADDR_INFO, addr_info).
-define(DELETE, '____DELETE'). %% this should sort before all other keys
-type handler() :: {atom(), atom()}.
-type opts() :: [{atom(), any()}].
-export_type([opts/0]).
%%
%% Global config
%%
-spec get_opt(opts(), atom() | list()) -> undefined | {ok, any()}.
get_opt(Opts, L) when is_list(Opts), is_list(L) ->
get_opt_l(L, Opts);
get_opt(Opts, K) when is_list(Opts), is_atom(K) ->
get_opt_l([K], Opts).
-spec get_opt(opts(), atom() | list(), any()) -> any().
get_opt(Opts, K, Default) ->
case get_opt(Opts, K) of
{ok, V} -> V;
undefined -> Default
end.
get_opt_l([], V) ->
{ok, V};
get_opt_l([H|T], [_|_] = L) ->
case lists:keyfind(H, 1, L) of
{_, V} ->
get_opt_l(T, V);
false ->
undefined
end;
get_opt_l(_, _) ->
undefined.
base_dir(TID) ->
Opts = libp2p_swarm:opts(TID),
get_opt(Opts, base_dir, "data").
-spec swarm_dir(ets:tab(), [file:name_all()]) -> file:filename_all().
swarm_dir(TID, Names) ->
FileName = filename:join([base_dir(TID), libp2p_swarm:name(TID) | Names]),
ok = filelib:ensure_dir(FileName),
FileName.
%%
Common pid CRUD
%%
-spec insert_pid(ets:tab(), atom(), term(), pid() | undefined) -> true.
insert_pid(TID, Kind, Ref, Pid) ->
ets:insert(TID, {{Kind, Ref}, Pid}).
-spec lookup_pid(ets:tab(), atom(), term()) -> {ok, pid()} | false.
lookup_pid(TID, Kind, Ref) ->
case ets:lookup(TID, {Kind, Ref}) of
[{_, Pid}] ->
case is_pid_deleted(TID, Kind, Pid) of
true ->
false;
false ->
{ok, Pid}
end;
[] -> false
end.
-spec lookup_pids(ets:tab(), atom()) -> [{term(), pid()}].
lookup_pids(TID, Kind) ->
[{Addr, Pid} || [Addr, Pid] <- ets:match(TID, {{Kind, '$1'}, '$2'}), not is_pid_deleted(TID, Kind, Pid)].
-spec lookup_addrs(ets:tab(), atom(), pid()) -> [string()].
lookup_addrs(TID, Kind, Pid) ->
[ Addr || [Addr] <- ets:match(TID, {{Kind, '$1'}, Pid}), not is_pid_deleted(TID, Kind, Pid)].
-spec lookup_addrs(ets:tab(), atom()) -> [string()].
lookup_addrs(TID, Kind) ->
[ Addr || [Addr, Pid] <- ets:match(TID, {{Kind, '$1'}, '_'}), not is_pid_deleted(TID, Kind, Pid)].
-spec remove_pid(ets:tab(), atom(), term()) -> true.
remove_pid(TID, Kind, Ref) ->
ets:delete(TID, {Kind, Ref}),
ets:delete(TID, {?ADDR_INFO, Kind, Ref}).
-spec remove_pid(ets:tab(), pid()) -> true.
remove_pid(TID, Pid) ->
ets:insert(TID, {{?DELETE, Pid}, Pid}).
is_pid_deleted(TID, Kind, Pid) ->
case ets:lookup(TID, {?DELETE, Pid}) of
[] ->
false;
[_Res] ->
note we do not delete the { ? DELETE , Pid } key here
as there may be other Kinds we need to GC
ets:delete(TID, {?ADDR_INFO, Kind, Pid}),
ets:delete(TID, {Kind, Pid})
end.
-spec lookup_handlers(ets:tab(), atom()) -> [{term(), any()}].
lookup_handlers(TID, TableKey) ->
[ {Key, Handler} ||
[Key, Handler] <- ets:match(TID, {{TableKey, '$1'}, '$2'})].
gc_pids(TID) ->
%% make continuations safe while deleting
ets:safe_fixtable(TID, true),
because this table is an ordered set , we can traverse in a known order and we know we 'll see the delete keys first
%% so we don't need to explicitly find them beforehand
ets : fun2ms(fun({K , _ } ) when element(1 , K ) = = addr_info - > K end ) + +
ets : fun2ms(fun({K , _ } ) when element(1 , K ) = = session_direction - > K end ) + +
ets : fun2ms(fun ( { _ , ) when is_pid(V ) - > O end )
{Matches, Continuation} = ets:select(TID, [{{'$1','_'},[{'==',{element,1,'$1'},addr_info}],['$1']},
{{'$1','_'},[{'==',{element,1,'$1'},session_direction}],['$1']},
{{'_','$1'},[{is_pid,'$1'}],['$_']}], 100),
gc_loop(Matches, Continuation, TID, sets:new()).
gc_loop([], '$end_of_table', TID, _) ->
%% indicate we're done doing a destructive iteration
ets:safe_fixtable(TID, false),
ok;
gc_loop([], Continuation, TID, Pids) ->
{Matches, NewContinuation} =
case ets:select(Continuation) of
'$end_of_table' = End -> {[], End};
Res -> Res
end,
gc_loop(Matches, NewContinuation, TID, Pids);
gc_loop([{{?DELETE, P}=Key, P}|Tail], Continuation, TID, Pids) ->
%% we know we can always delete this and add the pid to our set of
%% pids to be deleted
ets:delete(TID, Key),
gc_loop(Tail, Continuation, TID, sets:add_element(P, Pids));
gc_loop([{?SESSION_DIRECTION, P}=Key|Tail], Continuation, TID, Pids) when is_pid(P) ->
case sets:is_element(P, Pids) of
true ->
ets:delete(TID, Key);
false ->
ok
end,
gc_loop(Tail, Continuation, TID, Pids);
gc_loop([{Key, P}|Tail], Continuation, TID, Pids) when is_pid(P) ->
case sets:is_element(P, Pids) of
true ->
ets:delete(TID, Key);
false ->
ok
end,
gc_loop(Tail, Continuation, TID, Pids);
gc_loop([{?ADDR_INFO, _, P}=Key|Tail], Continuation, TID, Pids) when is_pid(P) ->
case sets:is_element(P, Pids) of
true ->
ets:delete(TID, Key);
false ->
ok
end,
gc_loop(Tail, Continuation, TID, Pids).
%%
%% Transports
%%
-spec transport() -> ?TRANSPORT.
transport() ->
?TRANSPORT.
-spec insert_transport(ets:tab(), atom(), pid() | undefined) -> true.
insert_transport(TID, Module, Pid) ->
insert_pid(TID, ?TRANSPORT, Module, Pid).
-spec lookup_transport(ets:tab(), atom()) -> {ok, pid()} | false.
lookup_transport(TID, Module) ->
lookup_pid(TID, ?TRANSPORT, Module).
-spec lookup_transports(ets:tab()) -> [{term(), pid()}].
lookup_transports(TID) ->
lookup_pids(TID, ?TRANSPORT).
%%
%% Listeners
%%
-spec listener() -> ?LISTENER.
listener() ->
?LISTENER.
-spec insert_listener(ets:tab(), [string()], pid()) -> true.
insert_listener(TID, Addrs, Pid) ->
lists:foreach(fun(A) ->
insert_pid(TID, ?LISTENER, A, Pid)
end, Addrs),
%% TODO: This was a convenient place to notify peerbook, but can
%% we not do this here?
PeerBook = libp2p_swarm:peerbook(TID),
libp2p_peerbook:changed_listener(PeerBook),
true.
-spec lookup_listener(ets:tab(), string()) -> {ok, pid()} | false.
lookup_listener(TID, Addr) ->
lookup_pid(TID, ?LISTENER, Addr).
-spec remove_listener(ets:tab(), string() | undefined) -> true.
remove_listener(TID, Addr) ->
remove_pid(TID, ?LISTENER, Addr),
%% TODO: This was a convenient place to notify peerbook, but can
%% we not do this here?
PeerBook = libp2p_swarm:peerbook(TID),
libp2p_peerbook:changed_listener(PeerBook),
true.
-spec listen_addrs(ets:tab()) -> [string()].
listen_addrs(TID) ->
[ Addr || [Addr] <- ets:match(TID, {{?LISTENER, '$1'}, '_'})].
%%
%% Listen sockets
%%
-spec listen_socket() -> ?LISTEN_SOCKET.
listen_socket() ->
?LISTEN_SOCKET.
-spec insert_listen_socket(ets:tab(), pid(), string(), gen_tcp:socket()) -> true.
insert_listen_socket(TID, Pid, ListenAddr, Socket) ->
ets:insert(TID, {{?LISTEN_SOCKET, Pid}, {ListenAddr, Socket}}),
true.
-spec lookup_listen_socket(ets:tab(), pid()) -> {ok, {string(), gen_tcp:socket()}} | false.
lookup_listen_socket(TID, Pid) ->
case ets:lookup(TID, {?LISTEN_SOCKET, Pid}) of
[{_, Sock}] -> {ok, Sock};
[] -> false
end.
-spec lookup_listen_socket_by_addr(ets:tab(), string()) -> {ok, {pid(), gen_tcp:socket()}} | false.
lookup_listen_socket_by_addr(TID, Addr) ->
case ets:match(TID, {{?LISTEN_SOCKET, '$1'}, {Addr, '$2'}}) of
[[Pid, Socket]] ->
{ok, {Pid, Socket}};
[] ->
false
end.
-spec remove_listen_socket(ets:tab(), pid()) -> true.
remove_listen_socket(TID, Pid) ->
ets:delete(TID, {?LISTEN_SOCKET, Pid}),
true.
-spec listen_sockets(ets:tab()) -> [{pid(), string(), gen_tcp:socket()}].
listen_sockets(TID) ->
[{Pid, Addr, Socket} || [Pid, Addr, Socket] <- ets:match(TID, {{?LISTEN_SOCKET, '$1'}, {'$2', '$3'}})].
%%
%% Sessions
%%
-spec session() -> ?SESSION.
session() ->
?SESSION.
-spec insert_session(ets:tab(), string(), pid(), inbound | outbound) -> true.
insert_session(TID, Addr, Pid, Direction) ->
ets:insert(TID, {{?SESSION_DIRECTION, Pid}, Direction}),
insert_session(TID, Addr, Pid).
-spec insert_session(ets:tab(), string(), pid()) -> true.
insert_session(TID, Addr, Pid) ->
insert_pid(TID, ?SESSION, Addr, Pid).
-spec lookup_session(ets:tab(), string(), opts()) -> {ok, pid()} | false.
lookup_session(TID, Addr, Options) ->
case get_opt(Options, unique_session, false) of
%% Unique session, return that we don't know about the given
%% session
true -> false;
false -> lookup_pid(TID, ?SESSION, Addr)
end.
-spec lookup_session(ets:tab(), string()) -> {ok, pid()} | false.
lookup_session(TID, Addr) ->
lookup_session(TID, Addr, []).
-spec remove_session(ets:tab(), string()) -> true.
remove_session(TID, Addr) ->
case lookup_session(TID, Addr) of
{ok, Pid} ->
ets:delete(TID, {?SESSION_DIRECTION, Pid});
_ ->
ok
end,
remove_pid(TID, ?SESSION, Addr).
-spec lookup_sessions(ets:tab()) -> [{term(), pid()}].
lookup_sessions(TID) ->
lookup_pids(TID, ?SESSION).
-spec lookup_session_addrs(ets:tab(), pid()) -> [string()].
lookup_session_addrs(TID, Pid) ->
lookup_addrs(TID, ?SESSION, Pid).
-spec lookup_session_addrs(ets:tab()) -> [string()].
lookup_session_addrs(TID) ->
lookup_addrs(TID, ?SESSION).
-spec lookup_session_addr_info(ets:tab(), pid()) -> {ok, {string(), string()}} | false.
lookup_session_addr_info(TID, Pid) ->
lookup_addr_info(TID, ?SESSION, Pid).
lookup_session_direction(TID, Pid) ->
[{{?SESSION_DIRECTION, Pid}, Direction}] = ets:lookup(TID, {?SESSION_DIRECTION, Pid}),
Direction.
-spec insert_session_addr_info(ets:tab(), pid(), {string(), string()}) -> true.
insert_session_addr_info(TID, Pid, AddrInfo) ->
insert_addr_info(TID, ?SESSION, Pid, AddrInfo).
%%
%% Addr Info
%%
-spec insert_addr_info(ets:tab(), atom(), pid(), {string(), string()}) -> true.
insert_addr_info(TID, Kind, Pid, AddrInfo) ->
Insert in the form that remove_pid understands to ensure that
%% addr info gets removed for removed pids regardless of what kind
%% of addr_info it is
ets:insert(TID, {{?ADDR_INFO, Kind, Pid}, AddrInfo}).
-spec lookup_addr_info(ets:tab(), atom(), pid()) -> {ok, {string(), string()}} | false.
lookup_addr_info(TID, Kind, Pid) ->
case ets:lookup(TID, {?ADDR_INFO, Kind, Pid}) of
[{_, AddrInfo}] ->
case is_pid_deleted(TID, Kind, Pid) of
true ->
false;
false ->
{ok, AddrInfo}
end;
[] ->
lager:info("got nothing for ~p", [Pid]),
false
end.
%%
Connections
%%
-spec lookup_connection_handlers(ets:tab()) -> [{string(), {handler(), handler() | undefined}}].
lookup_connection_handlers(TID) ->
lookup_handlers(TID, ?CONNECTION_HANDLER).
-spec insert_connection_handler(ets:tab(), {string(), handler(), handler() | undefined}) -> true.
insert_connection_handler(TID, {Key, ServerMF, ClientMF}) ->
ets:insert(TID, {{?CONNECTION_HANDLER, Key}, {ServerMF, ClientMF}}).
%%
%% Streams
%%
-spec lookup_stream_handlers(ets:tab()) -> [{string(), libp2p_session:stream_handler()}].
lookup_stream_handlers(TID) ->
lookup_handlers(TID, ?STREAM_HANDLER).
-spec insert_stream_handler(ets:tab(), {string(), libp2p_session:stream_handler()}) -> true.
insert_stream_handler(TID, {Key, ServerMF}) ->
ets:insert(TID, {{?STREAM_HANDLER, Key}, ServerMF}).
-spec remove_stream_handler(ets:tab(), string()) -> true.
remove_stream_handler(TID, Key) ->
ets:delete(TID, {?STREAM_HANDLER, Key}).
%%
Groups
%%
-spec insert_group(ets:tab(), string(), pid()) -> true.
insert_group(TID, GroupID, Pid) ->
insert_pid(TID, ?GROUP, GroupID, Pid).
-spec lookup_group(ets:tab(), string()) -> {ok, pid()} | false.
lookup_group(TID, GroupID) ->
lookup_pid(TID, ?GROUP, GroupID).
-spec remove_group(ets:tab(), string()) -> true.
remove_group(TID, GroupID) ->
remove_pid(TID, ?GROUP, GroupID).
-spec all_groups(ets:tab()) -> [Match] when
Match::[string()|pid()].
all_groups(TID) ->
ets:match(TID, {{group, '$1'}, '$2'}).
%%
%% Relay
%%
-spec insert_relay(ets:tab(), pid()) -> true.
insert_relay(TID, Pid) ->
insert_pid(TID, ?RELAY, "pid", Pid).
-spec lookup_relay(ets:tab()) -> {ok, pid()} | false.
lookup_relay(TID) ->
lookup_pid(TID, ?RELAY, "pid").
-spec remove_relay(ets:tab()) -> true.
remove_relay(TID) ->
remove_pid(TID, ?RELAY, "pid").
-spec insert_relay_stream(ets:tab(), string(), pid()) -> true.
insert_relay_stream(TID, Address, Pid) ->
insert_pid(TID, ?RELAY_STREAM, Address, Pid).
-spec lookup_relay_stream(ets:tab(), string()) -> {ok, pid()} | false.
lookup_relay_stream(TID, Address) ->
lookup_pid(TID, ?RELAY_STREAM, Address).
-spec remove_relay_stream(ets:tab(), string()) -> true.
remove_relay_stream(TID, Address) ->
remove_pid(TID, ?RELAY_STREAM, Address).
-spec insert_relay_sessions(ets:tab(), string(), pid()) -> true.
insert_relay_sessions(TID, Address, Pid) ->
insert_pid(TID, ?RELAY_SESSIONS, Address, Pid).
-spec lookup_relay_sessions(ets:tab(), string()) -> {ok, pid()} | false.
lookup_relay_sessions(TID, Address) ->
lookup_pid(TID, ?RELAY_SESSIONS, Address).
-spec remove_relay_sessions(ets:tab(), string()) -> true.
remove_relay_sessions(TID, Address) ->
remove_pid(TID, ?RELAY_SESSIONS, Address).
%%
%% Proxy
%%
-spec insert_proxy(ets:tab(), pid()) -> true.
insert_proxy(TID, Pid) ->
insert_pid(TID, ?PROXY, "pid", Pid).
-spec lookup_proxy(ets:tab()) -> {ok, pid()} | false.
lookup_proxy(TID) ->
lookup_pid(TID, ?PROXY, "pid").
-spec remove_proxy(ets:tab()) -> true.
remove_proxy(TID) ->
remove_pid(TID, ?PROXY, "pid").
%%
%%
-spec insert_nat(ets:tab(), pid()) -> true.
insert_nat(TID, Pid) ->
insert_pid(TID, ?NAT, "pid", Pid).
-spec lookup_nat(ets:tab()) -> {ok, pid()} | false.
lookup_nat(TID) ->
lookup_pid(TID, ?NAT, "pid").
-spec remove_nat(ets:tab()) -> true.
remove_nat(TID) ->
remove_pid(TID, ?NAT, "pid").
| null | https://raw.githubusercontent.com/helium/erlang-libp2p/3d81f62ba1c036e417237fb4e9e1ac6cddd8d3f2/src/libp2p_config.erl | erlang | this should sort before all other keys
Global config
make continuations safe while deleting
so we don't need to explicitly find them beforehand
indicate we're done doing a destructive iteration
we know we can always delete this and add the pid to our set of
pids to be deleted
Transports
Listeners
TODO: This was a convenient place to notify peerbook, but can
we not do this here?
TODO: This was a convenient place to notify peerbook, but can
we not do this here?
Listen sockets
Sessions
Unique session, return that we don't know about the given
session
Addr Info
addr info gets removed for removed pids regardless of what kind
of addr_info it is
Streams
Relay
Proxy
| -module(libp2p_config).
-export([get_opt/2, get_opt/3,
base_dir/1, swarm_dir/2,
insert_pid/4, lookup_pid/3, lookup_pids/2, remove_pid/2, remove_pid/3, gc_pids/1,
session/0, insert_session/3, insert_session/4, lookup_session/2, lookup_session/3, remove_session/2,
lookup_sessions/1, lookup_session_addrs/2, lookup_session_addrs/1, lookup_session_direction/2,
insert_session_addr_info/3, lookup_session_addr_info/2,
transport/0, insert_transport/3, lookup_transport/2, lookup_transports/1,
listen_addrs/1, listener/0, lookup_listener/2, insert_listener/3, remove_listener/2,
listen_socket/0, lookup_listen_socket/2, lookup_listen_socket_by_addr/2, insert_listen_socket/4, remove_listen_socket/2, listen_sockets/1,
lookup_connection_handlers/1, insert_connection_handler/2,
lookup_stream_handlers/1, insert_stream_handler/2, remove_stream_handler/2,
insert_group/3, lookup_group/2, remove_group/2, all_groups/1,
insert_relay/2, lookup_relay/1, remove_relay/1,
insert_relay_stream/3, lookup_relay_stream/2, remove_relay_stream/2,
insert_relay_sessions/3, lookup_relay_sessions/2, remove_relay_sessions/2,
insert_proxy/2, lookup_proxy/1, remove_proxy/1,
insert_nat/2, lookup_nat/1, remove_nat/1]).
-define(CONNECTION_HANDLER, connection_handler).
-define(STREAM_HANDLER, stream_handler).
-define(TRANSPORT, transport).
-define(SESSION, session).
-define(SESSION_DIRECTION, session_direction).
-define(LISTENER, listener).
-define(LISTEN_SOCKET, listen_socket).
-define(GROUP, group).
-define(RELAY, relay).
-define(RELAY_STREAM, relay_stream).
-define(RELAY_SESSIONS, relay_sessions).
-define(PROXY, proxy).
-define(NAT, nat).
-define(ADDR_INFO, addr_info).
-type handler() :: {atom(), atom()}.
-type opts() :: [{atom(), any()}].
-export_type([opts/0]).
-spec get_opt(opts(), atom() | list()) -> undefined | {ok, any()}.
get_opt(Opts, L) when is_list(Opts), is_list(L) ->
get_opt_l(L, Opts);
get_opt(Opts, K) when is_list(Opts), is_atom(K) ->
get_opt_l([K], Opts).
-spec get_opt(opts(), atom() | list(), any()) -> any().
get_opt(Opts, K, Default) ->
case get_opt(Opts, K) of
{ok, V} -> V;
undefined -> Default
end.
get_opt_l([], V) ->
{ok, V};
get_opt_l([H|T], [_|_] = L) ->
case lists:keyfind(H, 1, L) of
{_, V} ->
get_opt_l(T, V);
false ->
undefined
end;
get_opt_l(_, _) ->
undefined.
base_dir(TID) ->
Opts = libp2p_swarm:opts(TID),
get_opt(Opts, base_dir, "data").
-spec swarm_dir(ets:tab(), [file:name_all()]) -> file:filename_all().
swarm_dir(TID, Names) ->
FileName = filename:join([base_dir(TID), libp2p_swarm:name(TID) | Names]),
ok = filelib:ensure_dir(FileName),
FileName.
Common pid CRUD
-spec insert_pid(ets:tab(), atom(), term(), pid() | undefined) -> true.
insert_pid(TID, Kind, Ref, Pid) ->
ets:insert(TID, {{Kind, Ref}, Pid}).
-spec lookup_pid(ets:tab(), atom(), term()) -> {ok, pid()} | false.
lookup_pid(TID, Kind, Ref) ->
case ets:lookup(TID, {Kind, Ref}) of
[{_, Pid}] ->
case is_pid_deleted(TID, Kind, Pid) of
true ->
false;
false ->
{ok, Pid}
end;
[] -> false
end.
-spec lookup_pids(ets:tab(), atom()) -> [{term(), pid()}].
lookup_pids(TID, Kind) ->
[{Addr, Pid} || [Addr, Pid] <- ets:match(TID, {{Kind, '$1'}, '$2'}), not is_pid_deleted(TID, Kind, Pid)].
-spec lookup_addrs(ets:tab(), atom(), pid()) -> [string()].
lookup_addrs(TID, Kind, Pid) ->
[ Addr || [Addr] <- ets:match(TID, {{Kind, '$1'}, Pid}), not is_pid_deleted(TID, Kind, Pid)].
-spec lookup_addrs(ets:tab(), atom()) -> [string()].
lookup_addrs(TID, Kind) ->
[ Addr || [Addr, Pid] <- ets:match(TID, {{Kind, '$1'}, '_'}), not is_pid_deleted(TID, Kind, Pid)].
-spec remove_pid(ets:tab(), atom(), term()) -> true.
remove_pid(TID, Kind, Ref) ->
ets:delete(TID, {Kind, Ref}),
ets:delete(TID, {?ADDR_INFO, Kind, Ref}).
-spec remove_pid(ets:tab(), pid()) -> true.
remove_pid(TID, Pid) ->
ets:insert(TID, {{?DELETE, Pid}, Pid}).
is_pid_deleted(TID, Kind, Pid) ->
case ets:lookup(TID, {?DELETE, Pid}) of
[] ->
false;
[_Res] ->
note we do not delete the { ? DELETE , Pid } key here
as there may be other Kinds we need to GC
ets:delete(TID, {?ADDR_INFO, Kind, Pid}),
ets:delete(TID, {Kind, Pid})
end.
-spec lookup_handlers(ets:tab(), atom()) -> [{term(), any()}].
lookup_handlers(TID, TableKey) ->
[ {Key, Handler} ||
[Key, Handler] <- ets:match(TID, {{TableKey, '$1'}, '$2'})].
gc_pids(TID) ->
ets:safe_fixtable(TID, true),
because this table is an ordered set , we can traverse in a known order and we know we 'll see the delete keys first
ets : fun2ms(fun({K , _ } ) when element(1 , K ) = = addr_info - > K end ) + +
ets : fun2ms(fun({K , _ } ) when element(1 , K ) = = session_direction - > K end ) + +
ets : fun2ms(fun ( { _ , ) when is_pid(V ) - > O end )
{Matches, Continuation} = ets:select(TID, [{{'$1','_'},[{'==',{element,1,'$1'},addr_info}],['$1']},
{{'$1','_'},[{'==',{element,1,'$1'},session_direction}],['$1']},
{{'_','$1'},[{is_pid,'$1'}],['$_']}], 100),
gc_loop(Matches, Continuation, TID, sets:new()).
gc_loop([], '$end_of_table', TID, _) ->
ets:safe_fixtable(TID, false),
ok;
gc_loop([], Continuation, TID, Pids) ->
{Matches, NewContinuation} =
case ets:select(Continuation) of
'$end_of_table' = End -> {[], End};
Res -> Res
end,
gc_loop(Matches, NewContinuation, TID, Pids);
gc_loop([{{?DELETE, P}=Key, P}|Tail], Continuation, TID, Pids) ->
ets:delete(TID, Key),
gc_loop(Tail, Continuation, TID, sets:add_element(P, Pids));
gc_loop([{?SESSION_DIRECTION, P}=Key|Tail], Continuation, TID, Pids) when is_pid(P) ->
case sets:is_element(P, Pids) of
true ->
ets:delete(TID, Key);
false ->
ok
end,
gc_loop(Tail, Continuation, TID, Pids);
gc_loop([{Key, P}|Tail], Continuation, TID, Pids) when is_pid(P) ->
case sets:is_element(P, Pids) of
true ->
ets:delete(TID, Key);
false ->
ok
end,
gc_loop(Tail, Continuation, TID, Pids);
gc_loop([{?ADDR_INFO, _, P}=Key|Tail], Continuation, TID, Pids) when is_pid(P) ->
case sets:is_element(P, Pids) of
true ->
ets:delete(TID, Key);
false ->
ok
end,
gc_loop(Tail, Continuation, TID, Pids).
-spec transport() -> ?TRANSPORT.
transport() ->
?TRANSPORT.
-spec insert_transport(ets:tab(), atom(), pid() | undefined) -> true.
insert_transport(TID, Module, Pid) ->
insert_pid(TID, ?TRANSPORT, Module, Pid).
-spec lookup_transport(ets:tab(), atom()) -> {ok, pid()} | false.
lookup_transport(TID, Module) ->
lookup_pid(TID, ?TRANSPORT, Module).
-spec lookup_transports(ets:tab()) -> [{term(), pid()}].
lookup_transports(TID) ->
lookup_pids(TID, ?TRANSPORT).
-spec listener() -> ?LISTENER.
listener() ->
?LISTENER.
-spec insert_listener(ets:tab(), [string()], pid()) -> true.
insert_listener(TID, Addrs, Pid) ->
lists:foreach(fun(A) ->
insert_pid(TID, ?LISTENER, A, Pid)
end, Addrs),
PeerBook = libp2p_swarm:peerbook(TID),
libp2p_peerbook:changed_listener(PeerBook),
true.
-spec lookup_listener(ets:tab(), string()) -> {ok, pid()} | false.
lookup_listener(TID, Addr) ->
lookup_pid(TID, ?LISTENER, Addr).
-spec remove_listener(ets:tab(), string() | undefined) -> true.
remove_listener(TID, Addr) ->
remove_pid(TID, ?LISTENER, Addr),
PeerBook = libp2p_swarm:peerbook(TID),
libp2p_peerbook:changed_listener(PeerBook),
true.
-spec listen_addrs(ets:tab()) -> [string()].
listen_addrs(TID) ->
[ Addr || [Addr] <- ets:match(TID, {{?LISTENER, '$1'}, '_'})].
-spec listen_socket() -> ?LISTEN_SOCKET.
listen_socket() ->
?LISTEN_SOCKET.
-spec insert_listen_socket(ets:tab(), pid(), string(), gen_tcp:socket()) -> true.
insert_listen_socket(TID, Pid, ListenAddr, Socket) ->
ets:insert(TID, {{?LISTEN_SOCKET, Pid}, {ListenAddr, Socket}}),
true.
-spec lookup_listen_socket(ets:tab(), pid()) -> {ok, {string(), gen_tcp:socket()}} | false.
lookup_listen_socket(TID, Pid) ->
case ets:lookup(TID, {?LISTEN_SOCKET, Pid}) of
[{_, Sock}] -> {ok, Sock};
[] -> false
end.
-spec lookup_listen_socket_by_addr(ets:tab(), string()) -> {ok, {pid(), gen_tcp:socket()}} | false.
lookup_listen_socket_by_addr(TID, Addr) ->
case ets:match(TID, {{?LISTEN_SOCKET, '$1'}, {Addr, '$2'}}) of
[[Pid, Socket]] ->
{ok, {Pid, Socket}};
[] ->
false
end.
-spec remove_listen_socket(ets:tab(), pid()) -> true.
remove_listen_socket(TID, Pid) ->
ets:delete(TID, {?LISTEN_SOCKET, Pid}),
true.
-spec listen_sockets(ets:tab()) -> [{pid(), string(), gen_tcp:socket()}].
listen_sockets(TID) ->
[{Pid, Addr, Socket} || [Pid, Addr, Socket] <- ets:match(TID, {{?LISTEN_SOCKET, '$1'}, {'$2', '$3'}})].
-spec session() -> ?SESSION.
session() ->
?SESSION.
-spec insert_session(ets:tab(), string(), pid(), inbound | outbound) -> true.
insert_session(TID, Addr, Pid, Direction) ->
ets:insert(TID, {{?SESSION_DIRECTION, Pid}, Direction}),
insert_session(TID, Addr, Pid).
-spec insert_session(ets:tab(), string(), pid()) -> true.
insert_session(TID, Addr, Pid) ->
insert_pid(TID, ?SESSION, Addr, Pid).
-spec lookup_session(ets:tab(), string(), opts()) -> {ok, pid()} | false.
lookup_session(TID, Addr, Options) ->
case get_opt(Options, unique_session, false) of
true -> false;
false -> lookup_pid(TID, ?SESSION, Addr)
end.
-spec lookup_session(ets:tab(), string()) -> {ok, pid()} | false.
lookup_session(TID, Addr) ->
lookup_session(TID, Addr, []).
-spec remove_session(ets:tab(), string()) -> true.
remove_session(TID, Addr) ->
case lookup_session(TID, Addr) of
{ok, Pid} ->
ets:delete(TID, {?SESSION_DIRECTION, Pid});
_ ->
ok
end,
remove_pid(TID, ?SESSION, Addr).
-spec lookup_sessions(ets:tab()) -> [{term(), pid()}].
lookup_sessions(TID) ->
lookup_pids(TID, ?SESSION).
-spec lookup_session_addrs(ets:tab(), pid()) -> [string()].
lookup_session_addrs(TID, Pid) ->
lookup_addrs(TID, ?SESSION, Pid).
-spec lookup_session_addrs(ets:tab()) -> [string()].
lookup_session_addrs(TID) ->
lookup_addrs(TID, ?SESSION).
-spec lookup_session_addr_info(ets:tab(), pid()) -> {ok, {string(), string()}} | false.
lookup_session_addr_info(TID, Pid) ->
lookup_addr_info(TID, ?SESSION, Pid).
lookup_session_direction(TID, Pid) ->
[{{?SESSION_DIRECTION, Pid}, Direction}] = ets:lookup(TID, {?SESSION_DIRECTION, Pid}),
Direction.
-spec insert_session_addr_info(ets:tab(), pid(), {string(), string()}) -> true.
insert_session_addr_info(TID, Pid, AddrInfo) ->
insert_addr_info(TID, ?SESSION, Pid, AddrInfo).
-spec insert_addr_info(ets:tab(), atom(), pid(), {string(), string()}) -> true.
insert_addr_info(TID, Kind, Pid, AddrInfo) ->
Insert in the form that remove_pid understands to ensure that
ets:insert(TID, {{?ADDR_INFO, Kind, Pid}, AddrInfo}).
-spec lookup_addr_info(ets:tab(), atom(), pid()) -> {ok, {string(), string()}} | false.
lookup_addr_info(TID, Kind, Pid) ->
case ets:lookup(TID, {?ADDR_INFO, Kind, Pid}) of
[{_, AddrInfo}] ->
case is_pid_deleted(TID, Kind, Pid) of
true ->
false;
false ->
{ok, AddrInfo}
end;
[] ->
lager:info("got nothing for ~p", [Pid]),
false
end.
Connections
-spec lookup_connection_handlers(ets:tab()) -> [{string(), {handler(), handler() | undefined}}].
lookup_connection_handlers(TID) ->
lookup_handlers(TID, ?CONNECTION_HANDLER).
-spec insert_connection_handler(ets:tab(), {string(), handler(), handler() | undefined}) -> true.
insert_connection_handler(TID, {Key, ServerMF, ClientMF}) ->
ets:insert(TID, {{?CONNECTION_HANDLER, Key}, {ServerMF, ClientMF}}).
-spec lookup_stream_handlers(ets:tab()) -> [{string(), libp2p_session:stream_handler()}].
lookup_stream_handlers(TID) ->
lookup_handlers(TID, ?STREAM_HANDLER).
-spec insert_stream_handler(ets:tab(), {string(), libp2p_session:stream_handler()}) -> true.
insert_stream_handler(TID, {Key, ServerMF}) ->
ets:insert(TID, {{?STREAM_HANDLER, Key}, ServerMF}).
-spec remove_stream_handler(ets:tab(), string()) -> true.
remove_stream_handler(TID, Key) ->
ets:delete(TID, {?STREAM_HANDLER, Key}).
Groups
-spec insert_group(ets:tab(), string(), pid()) -> true.
insert_group(TID, GroupID, Pid) ->
insert_pid(TID, ?GROUP, GroupID, Pid).
-spec lookup_group(ets:tab(), string()) -> {ok, pid()} | false.
lookup_group(TID, GroupID) ->
lookup_pid(TID, ?GROUP, GroupID).
-spec remove_group(ets:tab(), string()) -> true.
remove_group(TID, GroupID) ->
remove_pid(TID, ?GROUP, GroupID).
-spec all_groups(ets:tab()) -> [Match] when
Match::[string()|pid()].
all_groups(TID) ->
ets:match(TID, {{group, '$1'}, '$2'}).
-spec insert_relay(ets:tab(), pid()) -> true.
insert_relay(TID, Pid) ->
insert_pid(TID, ?RELAY, "pid", Pid).
-spec lookup_relay(ets:tab()) -> {ok, pid()} | false.
lookup_relay(TID) ->
lookup_pid(TID, ?RELAY, "pid").
-spec remove_relay(ets:tab()) -> true.
remove_relay(TID) ->
remove_pid(TID, ?RELAY, "pid").
-spec insert_relay_stream(ets:tab(), string(), pid()) -> true.
insert_relay_stream(TID, Address, Pid) ->
insert_pid(TID, ?RELAY_STREAM, Address, Pid).
-spec lookup_relay_stream(ets:tab(), string()) -> {ok, pid()} | false.
lookup_relay_stream(TID, Address) ->
lookup_pid(TID, ?RELAY_STREAM, Address).
-spec remove_relay_stream(ets:tab(), string()) -> true.
remove_relay_stream(TID, Address) ->
remove_pid(TID, ?RELAY_STREAM, Address).
-spec insert_relay_sessions(ets:tab(), string(), pid()) -> true.
insert_relay_sessions(TID, Address, Pid) ->
insert_pid(TID, ?RELAY_SESSIONS, Address, Pid).
-spec lookup_relay_sessions(ets:tab(), string()) -> {ok, pid()} | false.
lookup_relay_sessions(TID, Address) ->
lookup_pid(TID, ?RELAY_SESSIONS, Address).
-spec remove_relay_sessions(ets:tab(), string()) -> true.
remove_relay_sessions(TID, Address) ->
remove_pid(TID, ?RELAY_SESSIONS, Address).
-spec insert_proxy(ets:tab(), pid()) -> true.
insert_proxy(TID, Pid) ->
insert_pid(TID, ?PROXY, "pid", Pid).
-spec lookup_proxy(ets:tab()) -> {ok, pid()} | false.
lookup_proxy(TID) ->
lookup_pid(TID, ?PROXY, "pid").
-spec remove_proxy(ets:tab()) -> true.
remove_proxy(TID) ->
remove_pid(TID, ?PROXY, "pid").
-spec insert_nat(ets:tab(), pid()) -> true.
insert_nat(TID, Pid) ->
insert_pid(TID, ?NAT, "pid", Pid).
-spec lookup_nat(ets:tab()) -> {ok, pid()} | false.
lookup_nat(TID) ->
lookup_pid(TID, ?NAT, "pid").
-spec remove_nat(ets:tab()) -> true.
remove_nat(TID) ->
remove_pid(TID, ?NAT, "pid").
|
9936e7166c4745ca2203e73413155810f8943439bcd61b5cc4e15b4824a46176 | hammerlab/prohlatype | fastq.ml |
module Sset = Set.Make (struct type t = string [@@deriving ord] end)
open Core_kernel
let to_stop = function
| None -> fun _ -> false
| Some n -> fun r -> r >= n
(* read header -> display, stop *)
let to_filter = function
| [] -> fun _ -> true, false
| lst ->
let s = ref (Sset.of_list lst) in
begin fun el ->
if Sset.mem el !s then begin
s := Sset.remove el !s;
true, Sset.cardinal !s <= 0
end else
false, false
end
let fold (type a) ?number_of_reads ?(specific_reads=[]) file ~f ~(init : a) =
let open Biocaml_unix in
let stop = to_stop number_of_reads in
let filt = to_filter specific_reads in
let module M = struct exception Fin of a end in
try
Future_unix.Reader.with_file file ~f:(fun rdr ->
(* Avoid circular dep *)
let fr = Biocaml_unix.Fastq.read rdr in
Future_unix.Pipe.fold fr ~init:(0,init) ~f:(fun (c, acc) oe ->
if stop c then
raise (M.Fin acc)
else
match oe with
| Error e -> eprintf "%s\n" (Error.to_string_hum e); (c, acc)
| Ok fqi -> let display, stop = filt fqi.Biocaml_unix.Fastq.name in
match display, stop with
| true, true -> raise (M.Fin (f acc fqi))
| false, true -> raise (M.Fin acc)
| true, false -> c + 1, f acc fqi
| false, false -> c, acc))
|> snd
with M.Fin m -> m
let fold_parany ?number_of_reads ?(specific_reads=[]) ~nprocs ~map ~mux file =
let open Biocaml_unix in
let stop = to_stop number_of_reads in
let filter = to_filter specific_reads in
let stop_r = ref false in
let count_r = ref 0 in
Future_unix.Reader.with_file file ~f:(fun rdr ->
let fr = Biocaml_unix.Fastq.read rdr in
let rec read () =
if !stop_r || stop !count_r then
raise Parany.End_of_input
else
match Future_unix.Pipe.read fr with
| `Eof -> raise Parany.End_of_input
| `Ok oe ->
begin match oe with
| Error e -> eprintf "%s\n" (Error.to_string_hum e);
read ()
| Ok fqi ->
let display, s = filter fqi.Biocaml_unix.Fastq.name in
stop_r := s;
if display then begin
incr count_r;
fqi
end else
read ()
end
in
let demux () = read () in
Parany.run ~verbose:false ~csize:1 ~nprocs ~demux ~work:map ~mux)
let all ?number_of_reads file =
fold ?number_of_reads
~f:(fun acc el -> el :: acc) ~init:[] file
|> List.rev
let phred_probabilities s =
let open Biocaml_unix in
let n = String.length s in
let a = Array.create ~len:n 0.0 in
let rec loop i =
if i = n then Ok a else
Result.bind (Phred_score.of_char s.[i])
~f:(fun c -> a.(i) <- Phred_score.to_probability c; loop (i + 1))
in
loop 0
let phred_log_probs s =
let open Biocaml_unix in
let n = String.length s in
let a = Array.create ~len:n 0. in
let rec loop i =
if i = n then Ok a else
Result.bind (Phred_score.of_char s.[i])
~f:(fun c -> a.(i) <- float_of_int (Phred_score.to_int c) /. -10.0;
loop (i + 1))
in
loop 0
let same cmp l1 l2 =
let rec single_loop search acc = function
| [] -> None, acc
| h :: t when search h -> (Some h), (List.rev acc) @ t
| h :: t -> single_loop search (h :: acc) t
in
let rec double_loop l2 acc = function
| [] -> None
| h :: t ->
match single_loop (cmp h) [] l2 with
| None, _ -> double_loop l2 (h :: acc) t
| Some f, lst -> Some (h, f, (List.rev acc) @ t, lst)
in
double_loop l2 [] l1
let name_as_key a = a.Biocaml_unix.Fastq.name
let fold_over_single_reads_list filt l ~init ~f =
let rec loop acc = function
| [] -> acc
| h :: t ->
(* Note that 'filt' discards reads that it is searching for;
* we should call this only for the unpaired reads! *)
let display, stop = filt h.Biocaml_unix.Fastq.name in
match display, stop with
| true, true -> f acc h
| false, true -> acc
| true, false -> loop (f acc h) t
| false, false -> loop acc t
in
loop init l
let fold_paired_both ?(to_key=name_as_key) ?number_of_reads ?(specific_reads=[])
~f ~init ?ff ?fs file1 file2 =
let open Biocaml_unix in
let stop = to_stop number_of_reads in
let filt = to_filter specific_reads in
let cmp r1 r2 = (to_key r1) = (to_key r2) in
let same = same cmp in
let open Future_unix in
let open Deferred in
let fold_if_f_not_none ff ~init l =
Option.value_map ff ~default:init
~f:(fun f -> fold_over_single_reads_list filt l ~init ~f)
in
Reader.with_file file1 ~f:(fun rdr1 ->
Reader.with_file file2 ~f:(fun rdr2 ->
(* Avoid circular dep *)
let fr1 = Biocaml_unix.Fastq.read rdr1 in
let fr2 = Biocaml_unix.Fastq.read rdr2 in
let rec two_pipe_fold c s1 s2 acc =
if stop c then
return (`DesiredReads acc)
else
Pipe.read fr1 >>= fun r1 ->
Pipe.read fr2 >>= fun r2 ->
match r1, r2 with
| `Eof, `Eof ->
let nacc = fold_if_f_not_none ff ~init:acc s1 in
let nacc = fold_if_f_not_none fs ~init:nacc s2 in
return (`BothFinished nacc)
| `Eof, `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum eb);
two_pipe_fold c s1 s2 acc
| `Eof, `Ok (Ok b) ->
same_check c s1 (b :: s2) acc
| `Ok (Error ea), `Eof ->
eprintf "%s\n" (Error.to_string_hum ea);
two_pipe_fold c s1 s2 acc
| `Ok (Ok a), `Eof ->
same_check c (a :: s1) s2 acc
| `Ok (Error ea), `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum ea);
eprintf "%s\n" (Error.to_string_hum eb);
two_pipe_fold c s1 s2 acc
| `Ok (Error ea), `Ok (Ok b) ->
eprintf "%s\n" (Error.to_string_hum ea);
two_pipe_fold c s1 (b::s2) acc
| `Ok (Ok a), `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum eb);
two_pipe_fold c (a::s1) s2 acc
| `Ok (Ok a), `Ok (Ok b) ->
if cmp a b then begin
filter_pass a b c s1 s2 acc
end else
same_check c (a :: s1) (b :: s2) acc
and same_check c ns1 ns2 acc =
match same ns1 ns2 with
| Some (r1, r2, ns1, ns2) ->
filter_pass r1 r2 c ns1 ns2 acc
| None ->
two_pipe_fold c ns1 ns2 acc
and filter_pass a b c s1 s2 acc =
let display, stop = filt a.Biocaml_unix.Fastq.name in
match display, stop with
| true, true -> `StoppedByFilter (f acc a b)
| false, true -> `StoppedByFilter acc
| true, false -> same_check (c + 1) s1 s2 (f acc a b)
| false, false -> same_check c s1 s2 acc
in
two_pipe_fold 0 [] [] init))
let fold_paired ?to_key ?number_of_reads ?specific_reads file1 file2 ~f ~init =
fold_paired_both ?to_key ?number_of_reads ?specific_reads file1 file2 ~f ~init
let fold_paired_parany ?number_of_reads ?(specific_reads=[])
~nprocs ~map ~mux file1 file2 =
let open Biocaml_unix in
let to_key = name_as_key in
let stop = to_stop number_of_reads in
let filt = to_filter specific_reads in
let cmp r1 r2 = (to_key r1) = (to_key r2) in
let same = same cmp in
let stop_r = ref false in
let count_r = ref 0 in
Future_unix.Reader.with_file file1 ~f:(fun rdr1 ->
Future_unix.Reader.with_file file2 ~f:(fun rdr2 ->
let fr1 = Biocaml_unix.Fastq.read rdr1 in
let fr2 = Biocaml_unix.Fastq.read rdr2 in
let state_ref = ref (`ReadBoth (fr1, fr2, [], [])) in
let rec same_check_both s1 s2 =
match same s1 s2 with
| Some (r1, r2, ns1, ns2) ->
state_ref := `ReadBoth (fr1, fr2, ns1, ns2);
filter_pass r1 r2
| None ->
state_ref := `ReadBoth (fr1, fr2, s1, s2);
read ()
and same_check_one fr f ns1 ns2 =
match same ns1 ns2 with
| Some (r1, r2, ns1, ns2) ->
state_ref := `ReadOne (fr, f, ns1, ns2);
filter_pass r1 r2
| None ->
state_ref := `ReadOne (fr, f, ns1, ns2);
read ()
and filter_pass r1 r2 =
let display, s = filt r1.Biocaml_unix.Fastq.name in
stop_r := s;
if display then begin
incr count_r;
Util.Sp.Paired (r1, r2)
end else
read ()
and read () =
if !stop_r || stop !count_r then
raise Parany.End_of_input
else
match !state_ref with
| `ReadBoth (fr1, fr2, s1, s2) ->
let r1 = Future_unix.Pipe.read fr1 in
let r2 = Future_unix.Pipe.read fr2 in
begin match r1, r2 with
| `Eof, `Eof ->
state_ref := `Remaining (s1, s2);
read ()
| `Eof, `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum eb);
state_ref := `ReadOne (fr2, false, s1, s2);
read ()
| `Eof, `Ok (Ok b) ->
same_check_one fr2 false s1 (b :: s2)
| `Ok (Error ea), `Eof ->
eprintf "%s\n" (Error.to_string_hum ea);
state_ref := `ReadOne (fr1, true, s1, s2);
read ()
| `Ok (Ok a), `Eof ->
same_check_one fr1 true (a :: s1) s2
| `Ok (Error ea), `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum ea);
eprintf "%s\n" (Error.to_string_hum eb);
read ()
| `Ok (Ok a), `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum eb);
same_check_both (a :: s1) s2
| `Ok (Error ea), `Ok (Ok b) ->
eprintf "%s\n" (Error.to_string_hum ea);
same_check_both s1 (b :: s2)
| `Ok (Ok a), `Ok (Ok b) ->
same_check_both (a :: s1) (b :: s2)
end
| `ReadOne (fr, f, s1, s2) ->
begin match Future_unix.Pipe.read fr with
| `Eof ->
state_ref := `Remaining (s1, s2);
read ()
| `Ok (Error e) ->
eprintf "%s\n" (Error.to_string_hum e);
read ()
| `Ok (Ok a) ->
if f then
same_check_one fr f (a :: s1) s2
else
same_check_one fr f s1 (a :: s2)
end
| `Remaining (s1, s2) ->
begin match same s1 s2 with
| Some (r1, r2, ns1, ns2) ->
state_ref := `Remaining (ns1, ns2);
filter_pass r1 r2
| None ->
state_ref := `OneAtATime (s1, s2);
read ()
end
| `OneAtATime ([], []) ->
raise Parany.End_of_input
| `OneAtATime (h :: t, l) ->
state_ref := `OneAtATime (t, l);
incr count_r;
Util.Sp.Single h
| `OneAtATime ([], h :: t) ->
state_ref := `OneAtATime ([], t);
incr count_r;
Util.Sp.Single h
in
Parany.run ~verbose:false ~csize:1 ~nprocs ~demux:read ~work:map ~mux))
let read_from_pair ~name file1 file2 =
let res =
fold_paired
~init:None ~f:(fun _ q1 q2 -> Some (q1, q2)) ~specific_reads:[name]
file1 file2
in
let opt =
match res with
| `BothFinished o
| `OneReadPairedFinished (_, o)
| `FinishedSingle o
| `StoppedByFilter o
| `DesiredReads o -> o
in
Option.map opt ~f:(fun (r1, r2) ->
( r1.Biocaml_unix.Fastq.sequence
, (phred_probabilities r1.Biocaml_unix.Fastq.qualities |> Util.unwrap)
, r2.Biocaml_unix.Fastq.sequence
, (phred_probabilities r2.Biocaml_unix.Fastq.qualities |> Util.unwrap)))
type paired_reading =
{ both : (Biocaml_unix.Fastq.item * Biocaml_unix.Fastq.item) list
; first : Biocaml_unix.Fastq.item list
; second : Biocaml_unix.Fastq.item list
}
let read_both file1 file2 =
fold_paired_both file1 file2 ~init:([],[],[])
~f:(fun (lb, l1, l2) p1 p2 -> (p1,p2) :: lb, l1, l2)
~ff:(fun (lb, l1, l2) p1 -> lb, (p1 :: l1), l2)
~fs:(fun (lb, l1, l2) p2 -> lb, l1, (p2 :: l2))
|> function
| `BothFinished (both, first, second)
| `FinishedSingle (both, first, second) -> { both; first; second}
| `OneReadPairedFinished _ -> failwith "Didn't read the rest!"
| `StoppedByFilter _
| `DesiredReads _ -> assert false
| null | https://raw.githubusercontent.com/hammerlab/prohlatype/3acaf7154f93675fc729971d4c76c2b133e90ce6/src/lib/fastq.ml | ocaml | read header -> display, stop
Avoid circular dep
Note that 'filt' discards reads that it is searching for;
* we should call this only for the unpaired reads!
Avoid circular dep |
module Sset = Set.Make (struct type t = string [@@deriving ord] end)
open Core_kernel
let to_stop = function
| None -> fun _ -> false
| Some n -> fun r -> r >= n
let to_filter = function
| [] -> fun _ -> true, false
| lst ->
let s = ref (Sset.of_list lst) in
begin fun el ->
if Sset.mem el !s then begin
s := Sset.remove el !s;
true, Sset.cardinal !s <= 0
end else
false, false
end
let fold (type a) ?number_of_reads ?(specific_reads=[]) file ~f ~(init : a) =
let open Biocaml_unix in
let stop = to_stop number_of_reads in
let filt = to_filter specific_reads in
let module M = struct exception Fin of a end in
try
Future_unix.Reader.with_file file ~f:(fun rdr ->
let fr = Biocaml_unix.Fastq.read rdr in
Future_unix.Pipe.fold fr ~init:(0,init) ~f:(fun (c, acc) oe ->
if stop c then
raise (M.Fin acc)
else
match oe with
| Error e -> eprintf "%s\n" (Error.to_string_hum e); (c, acc)
| Ok fqi -> let display, stop = filt fqi.Biocaml_unix.Fastq.name in
match display, stop with
| true, true -> raise (M.Fin (f acc fqi))
| false, true -> raise (M.Fin acc)
| true, false -> c + 1, f acc fqi
| false, false -> c, acc))
|> snd
with M.Fin m -> m
let fold_parany ?number_of_reads ?(specific_reads=[]) ~nprocs ~map ~mux file =
let open Biocaml_unix in
let stop = to_stop number_of_reads in
let filter = to_filter specific_reads in
let stop_r = ref false in
let count_r = ref 0 in
Future_unix.Reader.with_file file ~f:(fun rdr ->
let fr = Biocaml_unix.Fastq.read rdr in
let rec read () =
if !stop_r || stop !count_r then
raise Parany.End_of_input
else
match Future_unix.Pipe.read fr with
| `Eof -> raise Parany.End_of_input
| `Ok oe ->
begin match oe with
| Error e -> eprintf "%s\n" (Error.to_string_hum e);
read ()
| Ok fqi ->
let display, s = filter fqi.Biocaml_unix.Fastq.name in
stop_r := s;
if display then begin
incr count_r;
fqi
end else
read ()
end
in
let demux () = read () in
Parany.run ~verbose:false ~csize:1 ~nprocs ~demux ~work:map ~mux)
let all ?number_of_reads file =
fold ?number_of_reads
~f:(fun acc el -> el :: acc) ~init:[] file
|> List.rev
let phred_probabilities s =
let open Biocaml_unix in
let n = String.length s in
let a = Array.create ~len:n 0.0 in
let rec loop i =
if i = n then Ok a else
Result.bind (Phred_score.of_char s.[i])
~f:(fun c -> a.(i) <- Phred_score.to_probability c; loop (i + 1))
in
loop 0
let phred_log_probs s =
let open Biocaml_unix in
let n = String.length s in
let a = Array.create ~len:n 0. in
let rec loop i =
if i = n then Ok a else
Result.bind (Phred_score.of_char s.[i])
~f:(fun c -> a.(i) <- float_of_int (Phred_score.to_int c) /. -10.0;
loop (i + 1))
in
loop 0
let same cmp l1 l2 =
let rec single_loop search acc = function
| [] -> None, acc
| h :: t when search h -> (Some h), (List.rev acc) @ t
| h :: t -> single_loop search (h :: acc) t
in
let rec double_loop l2 acc = function
| [] -> None
| h :: t ->
match single_loop (cmp h) [] l2 with
| None, _ -> double_loop l2 (h :: acc) t
| Some f, lst -> Some (h, f, (List.rev acc) @ t, lst)
in
double_loop l2 [] l1
let name_as_key a = a.Biocaml_unix.Fastq.name
let fold_over_single_reads_list filt l ~init ~f =
let rec loop acc = function
| [] -> acc
| h :: t ->
let display, stop = filt h.Biocaml_unix.Fastq.name in
match display, stop with
| true, true -> f acc h
| false, true -> acc
| true, false -> loop (f acc h) t
| false, false -> loop acc t
in
loop init l
let fold_paired_both ?(to_key=name_as_key) ?number_of_reads ?(specific_reads=[])
~f ~init ?ff ?fs file1 file2 =
let open Biocaml_unix in
let stop = to_stop number_of_reads in
let filt = to_filter specific_reads in
let cmp r1 r2 = (to_key r1) = (to_key r2) in
let same = same cmp in
let open Future_unix in
let open Deferred in
let fold_if_f_not_none ff ~init l =
Option.value_map ff ~default:init
~f:(fun f -> fold_over_single_reads_list filt l ~init ~f)
in
Reader.with_file file1 ~f:(fun rdr1 ->
Reader.with_file file2 ~f:(fun rdr2 ->
let fr1 = Biocaml_unix.Fastq.read rdr1 in
let fr2 = Biocaml_unix.Fastq.read rdr2 in
let rec two_pipe_fold c s1 s2 acc =
if stop c then
return (`DesiredReads acc)
else
Pipe.read fr1 >>= fun r1 ->
Pipe.read fr2 >>= fun r2 ->
match r1, r2 with
| `Eof, `Eof ->
let nacc = fold_if_f_not_none ff ~init:acc s1 in
let nacc = fold_if_f_not_none fs ~init:nacc s2 in
return (`BothFinished nacc)
| `Eof, `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum eb);
two_pipe_fold c s1 s2 acc
| `Eof, `Ok (Ok b) ->
same_check c s1 (b :: s2) acc
| `Ok (Error ea), `Eof ->
eprintf "%s\n" (Error.to_string_hum ea);
two_pipe_fold c s1 s2 acc
| `Ok (Ok a), `Eof ->
same_check c (a :: s1) s2 acc
| `Ok (Error ea), `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum ea);
eprintf "%s\n" (Error.to_string_hum eb);
two_pipe_fold c s1 s2 acc
| `Ok (Error ea), `Ok (Ok b) ->
eprintf "%s\n" (Error.to_string_hum ea);
two_pipe_fold c s1 (b::s2) acc
| `Ok (Ok a), `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum eb);
two_pipe_fold c (a::s1) s2 acc
| `Ok (Ok a), `Ok (Ok b) ->
if cmp a b then begin
filter_pass a b c s1 s2 acc
end else
same_check c (a :: s1) (b :: s2) acc
and same_check c ns1 ns2 acc =
match same ns1 ns2 with
| Some (r1, r2, ns1, ns2) ->
filter_pass r1 r2 c ns1 ns2 acc
| None ->
two_pipe_fold c ns1 ns2 acc
and filter_pass a b c s1 s2 acc =
let display, stop = filt a.Biocaml_unix.Fastq.name in
match display, stop with
| true, true -> `StoppedByFilter (f acc a b)
| false, true -> `StoppedByFilter acc
| true, false -> same_check (c + 1) s1 s2 (f acc a b)
| false, false -> same_check c s1 s2 acc
in
two_pipe_fold 0 [] [] init))
let fold_paired ?to_key ?number_of_reads ?specific_reads file1 file2 ~f ~init =
fold_paired_both ?to_key ?number_of_reads ?specific_reads file1 file2 ~f ~init
let fold_paired_parany ?number_of_reads ?(specific_reads=[])
~nprocs ~map ~mux file1 file2 =
let open Biocaml_unix in
let to_key = name_as_key in
let stop = to_stop number_of_reads in
let filt = to_filter specific_reads in
let cmp r1 r2 = (to_key r1) = (to_key r2) in
let same = same cmp in
let stop_r = ref false in
let count_r = ref 0 in
Future_unix.Reader.with_file file1 ~f:(fun rdr1 ->
Future_unix.Reader.with_file file2 ~f:(fun rdr2 ->
let fr1 = Biocaml_unix.Fastq.read rdr1 in
let fr2 = Biocaml_unix.Fastq.read rdr2 in
let state_ref = ref (`ReadBoth (fr1, fr2, [], [])) in
let rec same_check_both s1 s2 =
match same s1 s2 with
| Some (r1, r2, ns1, ns2) ->
state_ref := `ReadBoth (fr1, fr2, ns1, ns2);
filter_pass r1 r2
| None ->
state_ref := `ReadBoth (fr1, fr2, s1, s2);
read ()
and same_check_one fr f ns1 ns2 =
match same ns1 ns2 with
| Some (r1, r2, ns1, ns2) ->
state_ref := `ReadOne (fr, f, ns1, ns2);
filter_pass r1 r2
| None ->
state_ref := `ReadOne (fr, f, ns1, ns2);
read ()
and filter_pass r1 r2 =
let display, s = filt r1.Biocaml_unix.Fastq.name in
stop_r := s;
if display then begin
incr count_r;
Util.Sp.Paired (r1, r2)
end else
read ()
and read () =
if !stop_r || stop !count_r then
raise Parany.End_of_input
else
match !state_ref with
| `ReadBoth (fr1, fr2, s1, s2) ->
let r1 = Future_unix.Pipe.read fr1 in
let r2 = Future_unix.Pipe.read fr2 in
begin match r1, r2 with
| `Eof, `Eof ->
state_ref := `Remaining (s1, s2);
read ()
| `Eof, `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum eb);
state_ref := `ReadOne (fr2, false, s1, s2);
read ()
| `Eof, `Ok (Ok b) ->
same_check_one fr2 false s1 (b :: s2)
| `Ok (Error ea), `Eof ->
eprintf "%s\n" (Error.to_string_hum ea);
state_ref := `ReadOne (fr1, true, s1, s2);
read ()
| `Ok (Ok a), `Eof ->
same_check_one fr1 true (a :: s1) s2
| `Ok (Error ea), `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum ea);
eprintf "%s\n" (Error.to_string_hum eb);
read ()
| `Ok (Ok a), `Ok (Error eb) ->
eprintf "%s\n" (Error.to_string_hum eb);
same_check_both (a :: s1) s2
| `Ok (Error ea), `Ok (Ok b) ->
eprintf "%s\n" (Error.to_string_hum ea);
same_check_both s1 (b :: s2)
| `Ok (Ok a), `Ok (Ok b) ->
same_check_both (a :: s1) (b :: s2)
end
| `ReadOne (fr, f, s1, s2) ->
begin match Future_unix.Pipe.read fr with
| `Eof ->
state_ref := `Remaining (s1, s2);
read ()
| `Ok (Error e) ->
eprintf "%s\n" (Error.to_string_hum e);
read ()
| `Ok (Ok a) ->
if f then
same_check_one fr f (a :: s1) s2
else
same_check_one fr f s1 (a :: s2)
end
| `Remaining (s1, s2) ->
begin match same s1 s2 with
| Some (r1, r2, ns1, ns2) ->
state_ref := `Remaining (ns1, ns2);
filter_pass r1 r2
| None ->
state_ref := `OneAtATime (s1, s2);
read ()
end
| `OneAtATime ([], []) ->
raise Parany.End_of_input
| `OneAtATime (h :: t, l) ->
state_ref := `OneAtATime (t, l);
incr count_r;
Util.Sp.Single h
| `OneAtATime ([], h :: t) ->
state_ref := `OneAtATime ([], t);
incr count_r;
Util.Sp.Single h
in
Parany.run ~verbose:false ~csize:1 ~nprocs ~demux:read ~work:map ~mux))
let read_from_pair ~name file1 file2 =
let res =
fold_paired
~init:None ~f:(fun _ q1 q2 -> Some (q1, q2)) ~specific_reads:[name]
file1 file2
in
let opt =
match res with
| `BothFinished o
| `OneReadPairedFinished (_, o)
| `FinishedSingle o
| `StoppedByFilter o
| `DesiredReads o -> o
in
Option.map opt ~f:(fun (r1, r2) ->
( r1.Biocaml_unix.Fastq.sequence
, (phred_probabilities r1.Biocaml_unix.Fastq.qualities |> Util.unwrap)
, r2.Biocaml_unix.Fastq.sequence
, (phred_probabilities r2.Biocaml_unix.Fastq.qualities |> Util.unwrap)))
type paired_reading =
{ both : (Biocaml_unix.Fastq.item * Biocaml_unix.Fastq.item) list
; first : Biocaml_unix.Fastq.item list
; second : Biocaml_unix.Fastq.item list
}
let read_both file1 file2 =
fold_paired_both file1 file2 ~init:([],[],[])
~f:(fun (lb, l1, l2) p1 p2 -> (p1,p2) :: lb, l1, l2)
~ff:(fun (lb, l1, l2) p1 -> lb, (p1 :: l1), l2)
~fs:(fun (lb, l1, l2) p2 -> lb, l1, (p2 :: l2))
|> function
| `BothFinished (both, first, second)
| `FinishedSingle (both, first, second) -> { both; first; second}
| `OneReadPairedFinished _ -> failwith "Didn't read the rest!"
| `StoppedByFilter _
| `DesiredReads _ -> assert false
|
9781080aaec3cd7401870f42db2c9e84e67518b9644da0669f1d51ca01e2fe11 | ghc/nofib | Main.hs | --
The Computer Language Benchmarks Game
-- /
--
contributed by ( with some bits taken from
-- version), v1.2
{-# LANGUAGE BangPatterns #-}
import Text.Printf
import Data.ByteString.Internal
import qualified Data.ByteString.Char8 as S
import Control.Applicative
import Control.Monad
import Control.Concurrent
import Foreign.Storable
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Ptr
import Foreign.ForeignPtr
import Data.Word
import Data.Bits
import Data.Char
import Data.List
import Data.Maybe
import Data.IORef
import GHC.Exts
main = do
genome <- extract (S.pack ">TH")
let actions = [
do
a <- printFreqsBySize genome 1
b <- printFreqsBySize genome 2
return $ a ++ b
] ++ map (printFreqsSpecific genome) specificSeqs
output <- concat <$> parallel actions
forM_ output putStrLn
-- Drop in replacement for sequence
parallel :: [IO a] -> IO [a]
parallel actions = do
vars <- forM actions $ \action -> do
var <- newEmptyMVar
forkIO $ do
answer <- action
putMVar var answer
return var
forM vars takeMVar
specificSeqs = map S.pack [
"GGT","GGTA","GGTATT","GGTATTTTAATT","GGTATTTTAATTTATAGT"]
extract p = do
s <- S.getContents
let (_, rem) = S.breakSubstring p s
return $! S.map toUpper -- array fusion!
. S.filter ((/=) '\n')
. S.dropWhile ((/=) '\n') $ rem
printFreqsBySize :: S.ByteString -> Int -> IO [String]
printFreqsBySize genome keySize = do
ht0 <- htNew keySize
ht <- hashGenome genome keySize ht0
l <- htToList ht
htFree ht
return $ map draw (sortBy sortRule l) ++ [""]
where
genomeLen = S.length genome
draw :: (S.ByteString, Int) -> String
draw (key, count) = printf "%s %.3f" (S.unpack key) pct
where pct = (100 * (fromIntegral count) / total) :: Double
total = fromIntegral (genomeLen - keySize + 1)
printFreqsSpecific :: S.ByteString -> S.ByteString -> IO [String]
printFreqsSpecific genome seq = do
let keySize = S.length seq
genomeLen = S.length genome
ht0 <- htNew keySize
ht <- hashGenome genome keySize ht0
let (fp, offset, len) = toForeignPtr seq
count <- withForeignPtr fp $ \p_ -> do
htGet ht (p_ `plusPtr` offset)
htFree ht
return [show count ++ ('\t' : S.unpack seq)]
hashGenome :: S.ByteString
-> Int
-> Hashtable
-> IO Hashtable
# INLINE hashGenome #
hashGenome genome keySize ht = do
let (fp, offset, len) = toForeignPtr genome
withForeignPtr fp $ \p_ -> do
let p = p_ `plusPtr` offset
loop ht idx = do
let key = p `plusPtr` idx
htInc ht key
endIdx = len - keySize + 1
foldMe i ht | i == endIdx = return ht
foldMe i ht = loop ht i >>= foldMe (i+1)
foldMe 0 ht
sortRule :: (S.ByteString, Int) -> (S.ByteString, Int) -> Ordering
sortRule (a1, b1) (a2, b2) =
case compare b2 b1 of
EQ -> compare a1 a2
x -> x
------ Hash table implementation ----------------------------------------------
-- Note: Hash tables are not generally used in functional languages, so there
are no available library implementations for . This benchmark
-- requires a hash table. This is why I have implemented the hash table here.
htNew :: Int -> IO Hashtable
htNew = htNew' (head primes)
htNew' :: Int -> Int -> IO Hashtable
htNew' slots ksz = do
let ssz = spineSize ksz slots
sp <- mallocBytes ssz
memset sp 0 (fromIntegral ssz)
return $ Hashtable {
keySize = ksz,
noOfSlots = slots,
spine = sp
}
primes = [ 1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 93241, 786433,
1572869, 3145739, 6291469, 12582917, 25165843,
50331653, 100663319, 201326611, 402653189, 805306457 ]
htFree :: Hashtable -> IO ()
htFree ht = do
htTraverse ht $ \isSpine (Entry ePtr) -> when (not isSpine) $ free ePtr
free (spine ht)
htGet :: Hashtable -> Ptr Word8 -> IO Int
htGet ht key = do
hash <- calcHash ht key
htPayload ht hash key >>= peek
htInc :: Hashtable -> Ptr Word8 -> IO Hashtable
# INLINE htInc #
htInc !ht !key = do
hash <- calcHash ht key
pPayload <- htPayload ht hash key
value <- peek pPayload
poke pPayload (value+1)
if value == 0 && (hash .&. 0x7f) == 0
then checkGrow ht
else return ht
htPut_ :: Hashtable -> Ptr Word8 -> Int -> IO ()
{-# INLINE htPut_ #-}
htPut_ !ht !key !value = do
hash <- calcHash ht key
pPayload <- htPayload ht hash key
poke pPayload value
checkGrow :: Hashtable -> IO Hashtable
checkGrow ht = do
let pTotal = totalEntriesOf ht
slots = noOfSlots ht
total <- (0x200+) <$> peek pTotal
poke pTotal total
if total >= slots
then do
let newSlots = head $ dropWhile (<= slots*2) primes
ht' <- htNew' newSlots (keySize ht)
htTraverse ht $ \_ -> reinsert ht' -- re-insert all the elts
htFree ht
poke (totalEntriesOf ht') total -- copy the total entry count
return ht'
else return ht
where
reinsert :: Hashtable -> Entry -> IO ()
reinsert ht entry = do
value <- peek (payloadOf entry)
htPut_ ht (keyOf entry) value
htToList :: Hashtable -> IO [(S.ByteString, Int)]
htToList ht =
htMap (\entry -> do
keyStr <- keyString ht (keyOf entry)
payload <- peek (payloadOf entry)
return (keyStr, payload)) ht
htMap :: (Entry -> IO a) -> Hashtable -> IO [a]
htMap f ht = mapM f =<< htEntries ht
keyString :: Hashtable -> Ptr Word8 -> IO S.ByteString
keyString ht key = S.pack . map w2c <$> peekArray (keySize ht) key
isEmptySlot :: Entry -> IO Bool
# INLINE isEmptySlot #
isEmptySlot entry = do
ch <- peek $ keyOf entry
return $ ch == 0
htEntries :: Hashtable -> IO [Entry]
htEntries ht = do
es <- newIORef []
htTraverse ht $ \_ entry -> modifyIORef es $ \l -> entry:l
readIORef es
htTraverse :: Hashtable -> (Bool -> Entry -> IO ()) -> IO ()
htTraverse ht f = he 0
where
slots = noOfSlots ht
he i | i == slots = return ()
he i = do
let entry = indexEntry ht i
empty <- isEmptySlot entry
if empty
then he (i+1)
else links True i entry
links isSpine i entry = do
next <- peek $ nextPtrOf entry
f isSpine entry
if next == nullPtr
then he (i+1)
else links False i (Entry next)
data Hashtable = Hashtable {
keySize :: Int,
noOfSlots :: Int,
spine :: Ptr Word8
}
wordSize :: Int
wordSize = max (sizeOf (nullPtr :: Ptr Word8)) (sizeOf (0 :: Int))
-- Round up to word size
roundUp :: Int -> Int
# INLINE roundUp #
roundUp !i = (i + wordSize - 1) .&. complement (wordSize - 1)
slotSize :: Int -> Int
# INLINE slotSize #
slotSize !ksz = roundUp ksz + wordSize * 2
spineSize :: Int -> Int -> Int
spineSize ksz slots = slots * slotSize ksz + wordSize
calcHash :: Hashtable -> Ptr Word8 -> IO Int
{-# INLINE calcHash #-}
calcHash !ht !key = (`mod` noOfSlots ht) <$> ch 0 0
where
ksz = keySize ht
ch :: Int -> Int -> IO Int
ch !i !acc | i == ksz = return acc
ch !i !acc = do
c <- peek (key `plusPtr` i)
ch (i+1) (acc * 131 + fromIntegral (c::Word8))
newtype Entry = Entry (Ptr Word8)
-- Count of the total number of hash table entries
totalEntriesOf :: Hashtable -> Ptr Int
# INLINE totalEntriesOf #
totalEntriesOf ht = castPtr $ spine ht
indexEntry :: Hashtable -> Int -> Entry
# INLINE indexEntry #
indexEntry !ht !hash =
let hOffset = wordSize + hash * slotSize (keySize ht)
in Entry $ spine ht `plusPtr` hOffset
entryMatches :: Hashtable -> Entry -> Ptr Word8 -> IO Bool
# INLINE entryMatches #
entryMatches !ht !entry !key = do
let eKey = keyOf entry
c <- memcmp key eKey (fromIntegral $ keySize ht)
if c == 0
then return True
else do
empty <- isEmptySlot entry
if empty
then do
memcpy eKey key (fromIntegral $ keySize ht) -- ick
return True
else
return False
nextPtrOf :: Entry -> Ptr (Ptr Word8)
# INLINE nextPtrOf #
nextPtrOf !(Entry ePtr) = castPtr $ ePtr
payloadOf :: Entry -> Ptr Int
# INLINE payloadOf #
payloadOf !(Entry ePtr) = castPtr $ ePtr `plusPtr` wordSize
keyOf :: Entry -> Ptr Word8
# INLINE keyOf #
keyOf !(Entry ePtr) = ePtr `plusPtr` (wordSize*2)
allocEntry :: Hashtable -> Ptr Word8 -> IO Entry
allocEntry !ht !key = do
let esz = slotSize $ keySize ht
ePtr <- mallocBytes esz
memset ePtr 0 (fromIntegral esz)
let entry = Entry ePtr
memcpy (keyOf entry) key (fromIntegral $ keySize ht)
return entry
htPayload :: Hashtable -> Int -> Ptr Word8 -> IO (Ptr Int)
# INLINE htPayload #
htPayload !ht !hash !key = do
entry <- findEntry (indexEntry ht hash)
return $ payloadOf entry
where
findEntry :: Entry -> IO Entry
findEntry !entry = do
match <- entryMatches ht entry key
if match
then
return entry
else do
let pNext = nextPtrOf entry
next <- peek pNext
if next == nullPtr
then do
newEntry@(Entry ePtr) <- allocEntry ht key
poke pNext ePtr
return newEntry
else
findEntry (Entry next)
| null | https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/shootout/k-nucleotide/Main.hs | haskell |
/
version), v1.2
# LANGUAGE BangPatterns #
Drop in replacement for sequence
array fusion!
---- Hash table implementation ----------------------------------------------
Note: Hash tables are not generally used in functional languages, so there
requires a hash table. This is why I have implemented the hash table here.
# INLINE htPut_ #
re-insert all the elts
copy the total entry count
Round up to word size
# INLINE calcHash #
Count of the total number of hash table entries
ick | The Computer Language Benchmarks Game
contributed by ( with some bits taken from
import Text.Printf
import Data.ByteString.Internal
import qualified Data.ByteString.Char8 as S
import Control.Applicative
import Control.Monad
import Control.Concurrent
import Foreign.Storable
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Ptr
import Foreign.ForeignPtr
import Data.Word
import Data.Bits
import Data.Char
import Data.List
import Data.Maybe
import Data.IORef
import GHC.Exts
main = do
genome <- extract (S.pack ">TH")
let actions = [
do
a <- printFreqsBySize genome 1
b <- printFreqsBySize genome 2
return $ a ++ b
] ++ map (printFreqsSpecific genome) specificSeqs
output <- concat <$> parallel actions
forM_ output putStrLn
parallel :: [IO a] -> IO [a]
parallel actions = do
vars <- forM actions $ \action -> do
var <- newEmptyMVar
forkIO $ do
answer <- action
putMVar var answer
return var
forM vars takeMVar
specificSeqs = map S.pack [
"GGT","GGTA","GGTATT","GGTATTTTAATT","GGTATTTTAATTTATAGT"]
extract p = do
s <- S.getContents
let (_, rem) = S.breakSubstring p s
. S.filter ((/=) '\n')
. S.dropWhile ((/=) '\n') $ rem
printFreqsBySize :: S.ByteString -> Int -> IO [String]
printFreqsBySize genome keySize = do
ht0 <- htNew keySize
ht <- hashGenome genome keySize ht0
l <- htToList ht
htFree ht
return $ map draw (sortBy sortRule l) ++ [""]
where
genomeLen = S.length genome
draw :: (S.ByteString, Int) -> String
draw (key, count) = printf "%s %.3f" (S.unpack key) pct
where pct = (100 * (fromIntegral count) / total) :: Double
total = fromIntegral (genomeLen - keySize + 1)
printFreqsSpecific :: S.ByteString -> S.ByteString -> IO [String]
printFreqsSpecific genome seq = do
let keySize = S.length seq
genomeLen = S.length genome
ht0 <- htNew keySize
ht <- hashGenome genome keySize ht0
let (fp, offset, len) = toForeignPtr seq
count <- withForeignPtr fp $ \p_ -> do
htGet ht (p_ `plusPtr` offset)
htFree ht
return [show count ++ ('\t' : S.unpack seq)]
hashGenome :: S.ByteString
-> Int
-> Hashtable
-> IO Hashtable
# INLINE hashGenome #
hashGenome genome keySize ht = do
let (fp, offset, len) = toForeignPtr genome
withForeignPtr fp $ \p_ -> do
let p = p_ `plusPtr` offset
loop ht idx = do
let key = p `plusPtr` idx
htInc ht key
endIdx = len - keySize + 1
foldMe i ht | i == endIdx = return ht
foldMe i ht = loop ht i >>= foldMe (i+1)
foldMe 0 ht
sortRule :: (S.ByteString, Int) -> (S.ByteString, Int) -> Ordering
sortRule (a1, b1) (a2, b2) =
case compare b2 b1 of
EQ -> compare a1 a2
x -> x
are no available library implementations for . This benchmark
htNew :: Int -> IO Hashtable
htNew = htNew' (head primes)
htNew' :: Int -> Int -> IO Hashtable
htNew' slots ksz = do
let ssz = spineSize ksz slots
sp <- mallocBytes ssz
memset sp 0 (fromIntegral ssz)
return $ Hashtable {
keySize = ksz,
noOfSlots = slots,
spine = sp
}
primes = [ 1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 93241, 786433,
1572869, 3145739, 6291469, 12582917, 25165843,
50331653, 100663319, 201326611, 402653189, 805306457 ]
htFree :: Hashtable -> IO ()
htFree ht = do
htTraverse ht $ \isSpine (Entry ePtr) -> when (not isSpine) $ free ePtr
free (spine ht)
htGet :: Hashtable -> Ptr Word8 -> IO Int
htGet ht key = do
hash <- calcHash ht key
htPayload ht hash key >>= peek
htInc :: Hashtable -> Ptr Word8 -> IO Hashtable
# INLINE htInc #
htInc !ht !key = do
hash <- calcHash ht key
pPayload <- htPayload ht hash key
value <- peek pPayload
poke pPayload (value+1)
if value == 0 && (hash .&. 0x7f) == 0
then checkGrow ht
else return ht
htPut_ :: Hashtable -> Ptr Word8 -> Int -> IO ()
htPut_ !ht !key !value = do
hash <- calcHash ht key
pPayload <- htPayload ht hash key
poke pPayload value
checkGrow :: Hashtable -> IO Hashtable
checkGrow ht = do
let pTotal = totalEntriesOf ht
slots = noOfSlots ht
total <- (0x200+) <$> peek pTotal
poke pTotal total
if total >= slots
then do
let newSlots = head $ dropWhile (<= slots*2) primes
ht' <- htNew' newSlots (keySize ht)
htFree ht
return ht'
else return ht
where
reinsert :: Hashtable -> Entry -> IO ()
reinsert ht entry = do
value <- peek (payloadOf entry)
htPut_ ht (keyOf entry) value
htToList :: Hashtable -> IO [(S.ByteString, Int)]
htToList ht =
htMap (\entry -> do
keyStr <- keyString ht (keyOf entry)
payload <- peek (payloadOf entry)
return (keyStr, payload)) ht
htMap :: (Entry -> IO a) -> Hashtable -> IO [a]
htMap f ht = mapM f =<< htEntries ht
keyString :: Hashtable -> Ptr Word8 -> IO S.ByteString
keyString ht key = S.pack . map w2c <$> peekArray (keySize ht) key
isEmptySlot :: Entry -> IO Bool
# INLINE isEmptySlot #
isEmptySlot entry = do
ch <- peek $ keyOf entry
return $ ch == 0
htEntries :: Hashtable -> IO [Entry]
htEntries ht = do
es <- newIORef []
htTraverse ht $ \_ entry -> modifyIORef es $ \l -> entry:l
readIORef es
htTraverse :: Hashtable -> (Bool -> Entry -> IO ()) -> IO ()
htTraverse ht f = he 0
where
slots = noOfSlots ht
he i | i == slots = return ()
he i = do
let entry = indexEntry ht i
empty <- isEmptySlot entry
if empty
then he (i+1)
else links True i entry
links isSpine i entry = do
next <- peek $ nextPtrOf entry
f isSpine entry
if next == nullPtr
then he (i+1)
else links False i (Entry next)
data Hashtable = Hashtable {
keySize :: Int,
noOfSlots :: Int,
spine :: Ptr Word8
}
wordSize :: Int
wordSize = max (sizeOf (nullPtr :: Ptr Word8)) (sizeOf (0 :: Int))
roundUp :: Int -> Int
# INLINE roundUp #
roundUp !i = (i + wordSize - 1) .&. complement (wordSize - 1)
slotSize :: Int -> Int
# INLINE slotSize #
slotSize !ksz = roundUp ksz + wordSize * 2
spineSize :: Int -> Int -> Int
spineSize ksz slots = slots * slotSize ksz + wordSize
calcHash :: Hashtable -> Ptr Word8 -> IO Int
calcHash !ht !key = (`mod` noOfSlots ht) <$> ch 0 0
where
ksz = keySize ht
ch :: Int -> Int -> IO Int
ch !i !acc | i == ksz = return acc
ch !i !acc = do
c <- peek (key `plusPtr` i)
ch (i+1) (acc * 131 + fromIntegral (c::Word8))
newtype Entry = Entry (Ptr Word8)
totalEntriesOf :: Hashtable -> Ptr Int
# INLINE totalEntriesOf #
totalEntriesOf ht = castPtr $ spine ht
indexEntry :: Hashtable -> Int -> Entry
# INLINE indexEntry #
indexEntry !ht !hash =
let hOffset = wordSize + hash * slotSize (keySize ht)
in Entry $ spine ht `plusPtr` hOffset
entryMatches :: Hashtable -> Entry -> Ptr Word8 -> IO Bool
# INLINE entryMatches #
entryMatches !ht !entry !key = do
let eKey = keyOf entry
c <- memcmp key eKey (fromIntegral $ keySize ht)
if c == 0
then return True
else do
empty <- isEmptySlot entry
if empty
then do
return True
else
return False
nextPtrOf :: Entry -> Ptr (Ptr Word8)
# INLINE nextPtrOf #
nextPtrOf !(Entry ePtr) = castPtr $ ePtr
payloadOf :: Entry -> Ptr Int
# INLINE payloadOf #
payloadOf !(Entry ePtr) = castPtr $ ePtr `plusPtr` wordSize
keyOf :: Entry -> Ptr Word8
# INLINE keyOf #
keyOf !(Entry ePtr) = ePtr `plusPtr` (wordSize*2)
allocEntry :: Hashtable -> Ptr Word8 -> IO Entry
allocEntry !ht !key = do
let esz = slotSize $ keySize ht
ePtr <- mallocBytes esz
memset ePtr 0 (fromIntegral esz)
let entry = Entry ePtr
memcpy (keyOf entry) key (fromIntegral $ keySize ht)
return entry
htPayload :: Hashtable -> Int -> Ptr Word8 -> IO (Ptr Int)
# INLINE htPayload #
htPayload !ht !hash !key = do
entry <- findEntry (indexEntry ht hash)
return $ payloadOf entry
where
findEntry :: Entry -> IO Entry
findEntry !entry = do
match <- entryMatches ht entry key
if match
then
return entry
else do
let pNext = nextPtrOf entry
next <- peek pNext
if next == nullPtr
then do
newEntry@(Entry ePtr) <- allocEntry ht key
poke pNext ePtr
return newEntry
else
findEntry (Entry next)
|
b0df241c2bd4589e151d13599225f2e1ff8107cbad2cfacfdb30b16bb1e02c2a | kunstmusik/pink | demo_node.clj | (ns pink.demo.demo-node
(:require [pink.engine :refer :all]
[pink.event :refer :all]
[pink.instruments.horn :refer :all]
[pink.util :refer [mul try-func]]
[pink.oscillators :refer :all]
[pink.envelopes :refer [env]]
[pink.node :refer :all]
[pink.dynamics :refer [db->amp]]
))
(comment
(def e (engine-create :nchnls 2))
(engine-start e)
;(require '[pink.noise :refer :all])
;(engine-add-afunc e (white-noise))
(def root-node (gain-node))
(engine-add-afunc e root-node)
(def my-score
(let [num-notes 5]
(node-events root-node
(map #(event horn (* % 0.5)
(/ 0.75 (+ 1 %))
(* 220 (+ 1 %))
(- (* 2 (/ % (- num-notes 1))) 1))
(range num-notes)))))
(engine-add-events e my-score)
(def m-node (mixer-node))
(engine-add-afunc e m-node)
(set-pan! m-node 0.25)
(set-gain! m-node (db->amp -12))
(engine-add-events e
(let [num-notes 5]
(node-events m-node
(map #(event horn (* % 0.5)
(/ 0.75 (+ 1 %))
(* 220 (+ 1 %)))
(range num-notes)))))
( def s ( sine 440.0 ) )
;(node-add-func root-node s)
;(node-remove-func root-node s)
(engine-stop e)
(engine-clear e)
(engine-kill-all)
)
| null | https://raw.githubusercontent.com/kunstmusik/pink/7d37764b6a036a68a4619c93546fa3887f9951a7/src/demo/pink/demo/demo_node.clj | clojure | (require '[pink.noise :refer :all])
(engine-add-afunc e (white-noise))
(node-add-func root-node s)
(node-remove-func root-node s) | (ns pink.demo.demo-node
(:require [pink.engine :refer :all]
[pink.event :refer :all]
[pink.instruments.horn :refer :all]
[pink.util :refer [mul try-func]]
[pink.oscillators :refer :all]
[pink.envelopes :refer [env]]
[pink.node :refer :all]
[pink.dynamics :refer [db->amp]]
))
(comment
(def e (engine-create :nchnls 2))
(engine-start e)
(def root-node (gain-node))
(engine-add-afunc e root-node)
(def my-score
(let [num-notes 5]
(node-events root-node
(map #(event horn (* % 0.5)
(/ 0.75 (+ 1 %))
(* 220 (+ 1 %))
(- (* 2 (/ % (- num-notes 1))) 1))
(range num-notes)))))
(engine-add-events e my-score)
(def m-node (mixer-node))
(engine-add-afunc e m-node)
(set-pan! m-node 0.25)
(set-gain! m-node (db->amp -12))
(engine-add-events e
(let [num-notes 5]
(node-events m-node
(map #(event horn (* % 0.5)
(/ 0.75 (+ 1 %))
(* 220 (+ 1 %)))
(range num-notes)))))
( def s ( sine 440.0 ) )
(engine-stop e)
(engine-clear e)
(engine-kill-all)
)
|
c483a907788a06ef0e768fcfc6004567fea71c7cafd1804dda85a5cb9ed0c631 | rizo/snowflake-os | std.mli |
* Std - Additional functions
* Copyright ( C ) 2003
*
* 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
* Std - Additional functions
* Copyright (C) 2003 Nicolas Cannasse
*
* 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
*)
(** Additional functions. *)
val string_of_char : char -> string
(** creates a string from a char. *)
external identity : 'a -> 'a = "%identity"
(** the identity function. *)
val unique : unit -> int
(** returns an unique identifier every time it is called. *)
val dump : 'a -> string
(** reprensent a runtime value as a string. *)
val finally : (unit -> unit) -> ('a -> 'b) -> 'a -> 'b
(** finally [fend f x] calls [f x] and then [fend()] even if [f x] raised
an exception. *)
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/libraries/extlib/std.mli | ocaml | * Additional functions.
* creates a string from a char.
* the identity function.
* returns an unique identifier every time it is called.
* reprensent a runtime value as a string.
* finally [fend f x] calls [f x] and then [fend()] even if [f x] raised
an exception. |
* Std - Additional functions
* Copyright ( C ) 2003
*
* 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
* Std - Additional functions
* Copyright (C) 2003 Nicolas Cannasse
*
* 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
*)
val string_of_char : char -> string
external identity : 'a -> 'a = "%identity"
val unique : unit -> int
val dump : 'a -> string
val finally : (unit -> unit) -> ('a -> 'b) -> 'a -> 'b
|
aada04db42c9067ef31337491b4d8a5611cb9f4519afe1796248d41f1635a26e | brendanhay/amazonka | UserAccessLoggingSettings.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
-- |
-- Module : Amazonka.WorkSpacesWeb.Types.UserAccessLoggingSettings
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
module Amazonka.WorkSpacesWeb.Types.UserAccessLoggingSettings where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
-- | A user access logging settings resource that can be associated with a
-- web portal.
--
-- /See:/ 'newUserAccessLoggingSettings' smart constructor.
data UserAccessLoggingSettings = UserAccessLoggingSettings'
{ -- | A list of web portal ARNs that this user access logging settings is
-- associated with.
associatedPortalArns :: Prelude.Maybe [Prelude.Text],
| The ARN of the Kinesis stream .
kinesisStreamArn :: Prelude.Maybe Prelude.Text,
| The ARN of the user access logging settings .
userAccessLoggingSettingsArn :: Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
-- Create a value of 'UserAccessLoggingSettings' with all optional fields omitted.
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
-- 'associatedPortalArns', 'userAccessLoggingSettings_associatedPortalArns' - A list of web portal ARNs that this user access logging settings is
-- associated with.
--
' kinesisStreamArn ' , ' userAccessLoggingSettings_kinesisStreamArn ' - The ARN of the Kinesis stream .
--
' userAccessLoggingSettingsArn ' , ' userAccessLoggingSettings_userAccessLoggingSettingsArn ' - The ARN of the user access logging settings .
newUserAccessLoggingSettings ::
-- | 'userAccessLoggingSettingsArn'
Prelude.Text ->
UserAccessLoggingSettings
newUserAccessLoggingSettings
pUserAccessLoggingSettingsArn_ =
UserAccessLoggingSettings'
{ associatedPortalArns =
Prelude.Nothing,
kinesisStreamArn = Prelude.Nothing,
userAccessLoggingSettingsArn =
pUserAccessLoggingSettingsArn_
}
-- | A list of web portal ARNs that this user access logging settings is
-- associated with.
userAccessLoggingSettings_associatedPortalArns :: Lens.Lens' UserAccessLoggingSettings (Prelude.Maybe [Prelude.Text])
userAccessLoggingSettings_associatedPortalArns = Lens.lens (\UserAccessLoggingSettings' {associatedPortalArns} -> associatedPortalArns) (\s@UserAccessLoggingSettings' {} a -> s {associatedPortalArns = a} :: UserAccessLoggingSettings) Prelude.. Lens.mapping Lens.coerced
| The ARN of the Kinesis stream .
userAccessLoggingSettings_kinesisStreamArn :: Lens.Lens' UserAccessLoggingSettings (Prelude.Maybe Prelude.Text)
userAccessLoggingSettings_kinesisStreamArn = Lens.lens (\UserAccessLoggingSettings' {kinesisStreamArn} -> kinesisStreamArn) (\s@UserAccessLoggingSettings' {} a -> s {kinesisStreamArn = a} :: UserAccessLoggingSettings)
| The ARN of the user access logging settings .
userAccessLoggingSettings_userAccessLoggingSettingsArn :: Lens.Lens' UserAccessLoggingSettings Prelude.Text
userAccessLoggingSettings_userAccessLoggingSettingsArn = Lens.lens (\UserAccessLoggingSettings' {userAccessLoggingSettingsArn} -> userAccessLoggingSettingsArn) (\s@UserAccessLoggingSettings' {} a -> s {userAccessLoggingSettingsArn = a} :: UserAccessLoggingSettings)
instance Data.FromJSON UserAccessLoggingSettings where
parseJSON =
Data.withObject
"UserAccessLoggingSettings"
( \x ->
UserAccessLoggingSettings'
Prelude.<$> ( x Data..:? "associatedPortalArns"
Data..!= Prelude.mempty
)
Prelude.<*> (x Data..:? "kinesisStreamArn")
Prelude.<*> (x Data..: "userAccessLoggingSettingsArn")
)
instance Prelude.Hashable UserAccessLoggingSettings where
hashWithSalt _salt UserAccessLoggingSettings' {..} =
_salt `Prelude.hashWithSalt` associatedPortalArns
`Prelude.hashWithSalt` kinesisStreamArn
`Prelude.hashWithSalt` userAccessLoggingSettingsArn
instance Prelude.NFData UserAccessLoggingSettings where
rnf UserAccessLoggingSettings' {..} =
Prelude.rnf associatedPortalArns
`Prelude.seq` Prelude.rnf kinesisStreamArn
`Prelude.seq` Prelude.rnf userAccessLoggingSettingsArn
| null | https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-workspaces-web/gen/Amazonka/WorkSpacesWeb/Types/UserAccessLoggingSettings.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Module : Amazonka.WorkSpacesWeb.Types.UserAccessLoggingSettings
Stability : auto-generated
| A user access logging settings resource that can be associated with a
web portal.
/See:/ 'newUserAccessLoggingSettings' smart constructor.
| A list of web portal ARNs that this user access logging settings is
associated with.
|
Create a value of 'UserAccessLoggingSettings' with all optional fields omitted.
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
'associatedPortalArns', 'userAccessLoggingSettings_associatedPortalArns' - A list of web portal ARNs that this user access logging settings is
associated with.
| 'userAccessLoggingSettingsArn'
| A list of web portal ARNs that this user access logging settings is
associated with. | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Amazonka.WorkSpacesWeb.Types.UserAccessLoggingSettings where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
data UserAccessLoggingSettings = UserAccessLoggingSettings'
associatedPortalArns :: Prelude.Maybe [Prelude.Text],
| The ARN of the Kinesis stream .
kinesisStreamArn :: Prelude.Maybe Prelude.Text,
| The ARN of the user access logging settings .
userAccessLoggingSettingsArn :: Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Use < -lens generic - lens > or < optics > to modify other optional fields .
' kinesisStreamArn ' , ' userAccessLoggingSettings_kinesisStreamArn ' - The ARN of the Kinesis stream .
' userAccessLoggingSettingsArn ' , ' userAccessLoggingSettings_userAccessLoggingSettingsArn ' - The ARN of the user access logging settings .
newUserAccessLoggingSettings ::
Prelude.Text ->
UserAccessLoggingSettings
newUserAccessLoggingSettings
pUserAccessLoggingSettingsArn_ =
UserAccessLoggingSettings'
{ associatedPortalArns =
Prelude.Nothing,
kinesisStreamArn = Prelude.Nothing,
userAccessLoggingSettingsArn =
pUserAccessLoggingSettingsArn_
}
userAccessLoggingSettings_associatedPortalArns :: Lens.Lens' UserAccessLoggingSettings (Prelude.Maybe [Prelude.Text])
userAccessLoggingSettings_associatedPortalArns = Lens.lens (\UserAccessLoggingSettings' {associatedPortalArns} -> associatedPortalArns) (\s@UserAccessLoggingSettings' {} a -> s {associatedPortalArns = a} :: UserAccessLoggingSettings) Prelude.. Lens.mapping Lens.coerced
| The ARN of the Kinesis stream .
userAccessLoggingSettings_kinesisStreamArn :: Lens.Lens' UserAccessLoggingSettings (Prelude.Maybe Prelude.Text)
userAccessLoggingSettings_kinesisStreamArn = Lens.lens (\UserAccessLoggingSettings' {kinesisStreamArn} -> kinesisStreamArn) (\s@UserAccessLoggingSettings' {} a -> s {kinesisStreamArn = a} :: UserAccessLoggingSettings)
| The ARN of the user access logging settings .
userAccessLoggingSettings_userAccessLoggingSettingsArn :: Lens.Lens' UserAccessLoggingSettings Prelude.Text
userAccessLoggingSettings_userAccessLoggingSettingsArn = Lens.lens (\UserAccessLoggingSettings' {userAccessLoggingSettingsArn} -> userAccessLoggingSettingsArn) (\s@UserAccessLoggingSettings' {} a -> s {userAccessLoggingSettingsArn = a} :: UserAccessLoggingSettings)
instance Data.FromJSON UserAccessLoggingSettings where
parseJSON =
Data.withObject
"UserAccessLoggingSettings"
( \x ->
UserAccessLoggingSettings'
Prelude.<$> ( x Data..:? "associatedPortalArns"
Data..!= Prelude.mempty
)
Prelude.<*> (x Data..:? "kinesisStreamArn")
Prelude.<*> (x Data..: "userAccessLoggingSettingsArn")
)
instance Prelude.Hashable UserAccessLoggingSettings where
hashWithSalt _salt UserAccessLoggingSettings' {..} =
_salt `Prelude.hashWithSalt` associatedPortalArns
`Prelude.hashWithSalt` kinesisStreamArn
`Prelude.hashWithSalt` userAccessLoggingSettingsArn
instance Prelude.NFData UserAccessLoggingSettings where
rnf UserAccessLoggingSettings' {..} =
Prelude.rnf associatedPortalArns
`Prelude.seq` Prelude.rnf kinesisStreamArn
`Prelude.seq` Prelude.rnf userAccessLoggingSettingsArn
|
205933fc4b2793bf5954739f9fd96a9bd83cafacbc3ab6d71a149a03d9b12437 | project-oak/hafnium-verification | Ident.mli |
* Copyright ( c ) 2009 - 2013 , Monoidics ltd .
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) 2009-2013, Monoidics ltd.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(** Identifiers: program variables and logical variables *)
open! IStd
(** Program and logical variables. *)
type t [@@deriving compare]
val equal : t -> t -> bool
(** Equality for identifiers. *)
(** Names used to replace strings. *)
type name [@@deriving compare]
val equal_name : name -> name -> bool
(** Equality for names. *)
(** Kind of identifiers. *)
type kind [@@deriving compare]
val equal_kind : kind -> kind -> bool
(** Equality for kind. *)
module Set : Caml.Set.S with type elt = t
(** Set for identifiers. *)
module Hash : Caml.Hashtbl.S with type key = t
(** Hash table with ident as key. *)
module Map : Caml.Map.S with type key = t
(** Map with ident as key. *)
module HashQueue : Hash_queue.S with type Key.t = t
module NameGenerator : sig
type t
val get_current : unit -> t
(** Get the current name generator. *)
val reset : unit -> unit
(** Reset the name generator. *)
val set_current : t -> unit
(** Set the current name generator. *)
end
val idlist_to_idset : t list -> Set.t
(** Convert an identifier list to an identifier set *)
val kprimed : kind
val knormal : kind
val kfootprint : kind
val name_spec : name
(** Name used for spec variables *)
val name_return : Mangled.t
(** Name used for the return variable *)
val name_return_param : Mangled.t
(** Name used for the return param variable *)
val string_to_name : string -> name
(** Convert a string to a name. *)
val name_to_string : name -> string
(** Convert a name to a string. *)
val get_name : t -> name
(** Name of the identifier. *)
val create : kind -> int -> t
(** Create an identifier with default name for the given kind *)
val create_normal : name -> int -> t
(** Generate a normal identifier with the given name and stamp. *)
val create_none : unit -> t
(** Create a "null" identifier for situations where the IR requires an id that will never be read *)
val create_footprint : name -> int -> t
(** Generate a footprint identifier with the given name and stamp. *)
val update_name_generator : t list -> unit
(** Update the name generator so that the given id's are not generated again *)
val create_fresh : kind -> t
(** Create a fresh identifier with default name for the given kind. *)
val create_fresh_specialized_with_blocks : kind -> t
* Create a fresh identifier with default name for the given kind , with a non - clashing i d for objc
block specialization
block specialization *)
val create_path : string -> t
(** Generate a normal identifier whose name encodes a path given as a string. *)
val is_primed : t -> bool
(** Check whether an identifier is primed or not. *)
val is_normal : t -> bool
(** Check whether an identifier is normal or not. *)
val is_footprint : t -> bool
(** Check whether an identifier is footprint or not. *)
val is_path : t -> bool
(** Check whether an identifier represents a path or not. *)
val is_none : t -> bool
(** Check whether an identifier is the special "none" identifier *)
val get_stamp : t -> int
(** Get the stamp of the identifier *)
val set_stamp : t -> int -> t
(** Set the stamp of the identifier *)
* { 2 Pretty Printing }
val pp_name : Format.formatter -> name -> unit
(** Pretty print a name. *)
val pp : Format.formatter -> t -> unit
(** Pretty print an identifier. *)
val to_string : t -> string
(** Convert an identifier to a string. *)
val hashqueue_of_sequence : ?init:unit HashQueue.t -> t Sequence.t -> unit HashQueue.t
val set_of_sequence : ?init:Set.t -> t Sequence.t -> Set.t
val counts_of_sequence : t Sequence.t -> t -> int
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/IR/Ident.mli | ocaml | * Identifiers: program variables and logical variables
* Program and logical variables.
* Equality for identifiers.
* Names used to replace strings.
* Equality for names.
* Kind of identifiers.
* Equality for kind.
* Set for identifiers.
* Hash table with ident as key.
* Map with ident as key.
* Get the current name generator.
* Reset the name generator.
* Set the current name generator.
* Convert an identifier list to an identifier set
* Name used for spec variables
* Name used for the return variable
* Name used for the return param variable
* Convert a string to a name.
* Convert a name to a string.
* Name of the identifier.
* Create an identifier with default name for the given kind
* Generate a normal identifier with the given name and stamp.
* Create a "null" identifier for situations where the IR requires an id that will never be read
* Generate a footprint identifier with the given name and stamp.
* Update the name generator so that the given id's are not generated again
* Create a fresh identifier with default name for the given kind.
* Generate a normal identifier whose name encodes a path given as a string.
* Check whether an identifier is primed or not.
* Check whether an identifier is normal or not.
* Check whether an identifier is footprint or not.
* Check whether an identifier represents a path or not.
* Check whether an identifier is the special "none" identifier
* Get the stamp of the identifier
* Set the stamp of the identifier
* Pretty print a name.
* Pretty print an identifier.
* Convert an identifier to a string. |
* Copyright ( c ) 2009 - 2013 , Monoidics ltd .
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) 2009-2013, Monoidics ltd.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
type t [@@deriving compare]
val equal : t -> t -> bool
type name [@@deriving compare]
val equal_name : name -> name -> bool
type kind [@@deriving compare]
val equal_kind : kind -> kind -> bool
module Set : Caml.Set.S with type elt = t
module Hash : Caml.Hashtbl.S with type key = t
module Map : Caml.Map.S with type key = t
module HashQueue : Hash_queue.S with type Key.t = t
module NameGenerator : sig
type t
val get_current : unit -> t
val reset : unit -> unit
val set_current : t -> unit
end
val idlist_to_idset : t list -> Set.t
val kprimed : kind
val knormal : kind
val kfootprint : kind
val name_spec : name
val name_return : Mangled.t
val name_return_param : Mangled.t
val string_to_name : string -> name
val name_to_string : name -> string
val get_name : t -> name
val create : kind -> int -> t
val create_normal : name -> int -> t
val create_none : unit -> t
val create_footprint : name -> int -> t
val update_name_generator : t list -> unit
val create_fresh : kind -> t
val create_fresh_specialized_with_blocks : kind -> t
* Create a fresh identifier with default name for the given kind , with a non - clashing i d for objc
block specialization
block specialization *)
val create_path : string -> t
val is_primed : t -> bool
val is_normal : t -> bool
val is_footprint : t -> bool
val is_path : t -> bool
val is_none : t -> bool
val get_stamp : t -> int
val set_stamp : t -> int -> t
* { 2 Pretty Printing }
val pp_name : Format.formatter -> name -> unit
val pp : Format.formatter -> t -> unit
val to_string : t -> string
val hashqueue_of_sequence : ?init:unit HashQueue.t -> t Sequence.t -> unit HashQueue.t
val set_of_sequence : ?init:Set.t -> t Sequence.t -> Set.t
val counts_of_sequence : t Sequence.t -> t -> int
|
4c6b69f94e458b6c6a004e477be1d1277edfa0c1bf5bef8051333c7212f4e1db | berberman/arch-hs | Main.hs | # LANGUAGE CPP #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Main (main) where
import Args
import Control.Monad (unless)
import qualified Data.Map as Map
import Diff
import Distribution.ArchHs.Core (subsumeGHCVersion)
import Distribution.ArchHs.Exception
import Distribution.ArchHs.Internal.Prelude
import Distribution.ArchHs.Options
import Distribution.ArchHs.PP
import Distribution.ArchHs.Types
import GHC.IO.Encoding (setLocaleEncoding, utf8)
import Network.HTTP.Client (Manager)
import Network.HTTP.Client.TLS (newTlsManager)
main :: IO ()
main = printHandledIOException $
do
setLocaleEncoding utf8
Options {..} <- runArgsParser
let isFlagEmpty = Map.null optFlags
unless isFlagEmpty $ do
printInfo "You assigned flags:"
putDoc $ prettyFlagAssignments optFlags <> line
community <- loadCommunityDBFromOptions optCommunityDB
manager <- newTlsManager
printInfo "Start running..."
runDiff community optFlags manager (subsumeGHCVersion $ diffCabal optPackageName optVersionA optVersionB) & printAppResult
runDiff ::
CommunityDB ->
FlagAssignments ->
Manager ->
Sem '[CommunityEnv, FlagAssignmentsEnv, Reader Manager, Trace, DependencyRecord, WithMyErr, Embed IO, Final IO] a ->
IO (Either MyException a)
runDiff community flags manager =
runFinal
. embedToFinal
. errorToIOFinal
. evalState Map.empty
. ignoreTrace
. runReader manager
. runReader flags
. runReader community
| null | https://raw.githubusercontent.com/berberman/arch-hs/ae56e926c6a8d24b580a81b2a4d49cd01ec19b5a/diff/Main.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE CPP #
# LANGUAGE RecordWildCards #
module Main (main) where
import Args
import Control.Monad (unless)
import qualified Data.Map as Map
import Diff
import Distribution.ArchHs.Core (subsumeGHCVersion)
import Distribution.ArchHs.Exception
import Distribution.ArchHs.Internal.Prelude
import Distribution.ArchHs.Options
import Distribution.ArchHs.PP
import Distribution.ArchHs.Types
import GHC.IO.Encoding (setLocaleEncoding, utf8)
import Network.HTTP.Client (Manager)
import Network.HTTP.Client.TLS (newTlsManager)
main :: IO ()
main = printHandledIOException $
do
setLocaleEncoding utf8
Options {..} <- runArgsParser
let isFlagEmpty = Map.null optFlags
unless isFlagEmpty $ do
printInfo "You assigned flags:"
putDoc $ prettyFlagAssignments optFlags <> line
community <- loadCommunityDBFromOptions optCommunityDB
manager <- newTlsManager
printInfo "Start running..."
runDiff community optFlags manager (subsumeGHCVersion $ diffCabal optPackageName optVersionA optVersionB) & printAppResult
runDiff ::
CommunityDB ->
FlagAssignments ->
Manager ->
Sem '[CommunityEnv, FlagAssignmentsEnv, Reader Manager, Trace, DependencyRecord, WithMyErr, Embed IO, Final IO] a ->
IO (Either MyException a)
runDiff community flags manager =
runFinal
. embedToFinal
. errorToIOFinal
. evalState Map.empty
. ignoreTrace
. runReader manager
. runReader flags
. runReader community
|
2e81fa0e2cac4ba00b9775382f649bb184d687e4f54cfe846bdead7f6060a3c8 | DaMSL/K3 | Data.hs | {-|
A module defining basic data structures for the type manifestation process.
-}
module Language.K3.TypeSystem.Manifestation.Data
( BoundDictionary(..)
, BoundType(..)
, DelayedOperationTag(..) -- TODO: remove entirely?
, getBoundTypeName
, getBoundDefaultType
, getConcreteUVarBounds
, getConcreteQVarBounds
, getConcreteQVarQualifiers
, getQualifierOperation
, getDualBoundType
, getTyVarOp
) where
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Monoid
import qualified Data.Set as Set
import Data.Set (Set)
import Language.K3.Core.Type
import Language.K3.TypeSystem.Data
import Language.K3.Utils.Pretty
import Language.K3.Utils.Pretty.Common
-- * Bound dictionaries
data BoundDictionary
= BoundDictionary
{ uvarBoundDict :: Map (UVar, BoundType) ShallowType
, uvarOpaqueBoundDict :: Map (UVar, BoundType) (Set OpaqueVar)
, qvarBoundDict :: Map (QVar, BoundType) ShallowType
, qvarOpaqueBoundDict :: Map (QVar, BoundType) (Set OpaqueVar)
, qvarQualDict :: Map (QVar, BoundType) (Set TQual)
, ovarRangeDict :: Map (OpaqueVar, BoundType) TypeOrVar
}
instance Monoid BoundDictionary where
mempty =
BoundDictionary Map.empty Map.empty Map.empty Map.empty Map.empty Map.empty
mappend (BoundDictionary ubD uobD qbD qobD qqD orD)
(BoundDictionary ubD' uobD' qbD' qobD' qqD' orD') =
BoundDictionary
(ubD `Map.union` ubD')
(Map.unionWith Set.union uobD uobD')
(qbD `Map.union` qbD')
(Map.unionWith Set.union qobD qobD')
(qqD `Map.union` qqD')
(orD `Map.union` orD')
instance Pretty BoundDictionary where
prettyLines dict = vconcats
[ ["UVars: "] %+
prettyVarMap prettyBoundVarPair prettyLines (uvarBoundDict dict)
, ["UVars opaque: "] %+
prettyVarMap prettyBoundVarPair normalPrettySet
(uvarOpaqueBoundDict dict)
, ["QVars: "] %+
prettyVarMap prettyBoundVarPair normalPrettyPair
(Map.intersectionWith (,) (qvarBoundDict dict) (qvarQualDict dict))
, ["QVars opaque: "] %+
prettyVarMap prettyBoundVarPair normalPrettySet
(qvarOpaqueBoundDict dict)
, ["Opaques bounds: "] %+
explicitNormalPrettyMap normalPrettyPair prettyLines
(ovarRangeDict dict)
]
where
prettyVarMap = explicitPrettyMap ["{"] ["}"] ", " ""
prettyBoundVarPair :: (TVar q, BoundType) -> [String]
prettyBoundVarPair (var, bt) =
prettyLines var %+
case bt of
UpperBound -> ["≤"]
LowerBound -> ["≥"]
-- * Bound types
-- |A data type representing a bounding direction.
data BoundType
= UpperBound
| LowerBound
deriving (Eq, Ord, Show)
instance Pretty BoundType where
prettyLines = (:[]) . (++" bound") . getBoundTypeName
-- TODO: remove this structure?
-- |An enumeration identifying the delayed operations over groups of types which
-- are used during manifestation.
data DelayedOperationTag
= DelayedIntersectionTag
| DelayedUnionTag
deriving (Eq, Ord, Show)
-- |Retrieves the name of a bound type.
getBoundTypeName :: BoundType -> String
getBoundTypeName UpperBound = "upper"
getBoundTypeName LowerBound = "lower"
-- |Retrieves the default type for a given bounding direction. This is
-- equivalent to the unit of the canonical merge (e.g. intersection or union).
getBoundDefaultType :: BoundType -> ShallowType
getBoundDefaultType UpperBound = STop
getBoundDefaultType LowerBound = SBottom
-- |Retrieves a function to generate an unqualified variable bounding query
-- based on bounding type.
getConcreteUVarBounds :: BoundType -> UVar -> ConstraintSetQuery ShallowType
getConcreteUVarBounds UpperBound = QueryTypeByUVarLowerBound
getConcreteUVarBounds LowerBound = QueryTypeByUVarUpperBound
-- |Retrieves a function to generate a qualified variable bounding query based
-- on bounding type.
getConcreteQVarBounds :: BoundType -> QVar -> ConstraintSetQuery ShallowType
getConcreteQVarBounds UpperBound = QueryTypeByQVarLowerBound
getConcreteQVarBounds LowerBound = QueryTypeByQVarUpperBound
-- |Retrieves a function to generate a query for a set of qualifiers based on
-- bounding type.
getConcreteQVarQualifiers :: BoundType -> QVar -> ConstraintSetQuery (Set TQual)
getConcreteQVarQualifiers UpperBound = QueryTQualSetByQVarLowerBound
getConcreteQVarQualifiers LowerBound = QueryTQualSetByQVarUpperBound
-- |Retrieves a qualifier set merging operation based on bounding types.
getQualifierOperation :: BoundType -> [Set TQual] -> Set TQual
getQualifierOperation UpperBound = Set.unions
getQualifierOperation LowerBound =
foldl Set.intersection (Set.fromList [TMut, TImmut])
-- |Retrieves the dual of a bounding type.
getDualBoundType :: BoundType -> BoundType
getDualBoundType UpperBound = LowerBound
getDualBoundType LowerBound = UpperBound
-- |Retrieves the type variable operator identifying the sort of operation
-- performed by a given bounding type.
getTyVarOp :: BoundType -> TypeVariableOperator
getTyVarOp UpperBound = TyVarOpIntersection
getTyVarOp LowerBound = TyVarOpUnion
| null | https://raw.githubusercontent.com/DaMSL/K3/51749157844e76ae79dba619116fc5ad9d685643/src/Language/K3/TypeSystem/Manifestation/Data.hs | haskell | |
A module defining basic data structures for the type manifestation process.
TODO: remove entirely?
* Bound dictionaries
* Bound types
|A data type representing a bounding direction.
TODO: remove this structure?
|An enumeration identifying the delayed operations over groups of types which
are used during manifestation.
|Retrieves the name of a bound type.
|Retrieves the default type for a given bounding direction. This is
equivalent to the unit of the canonical merge (e.g. intersection or union).
|Retrieves a function to generate an unqualified variable bounding query
based on bounding type.
|Retrieves a function to generate a qualified variable bounding query based
on bounding type.
|Retrieves a function to generate a query for a set of qualifiers based on
bounding type.
|Retrieves a qualifier set merging operation based on bounding types.
|Retrieves the dual of a bounding type.
|Retrieves the type variable operator identifying the sort of operation
performed by a given bounding type. |
module Language.K3.TypeSystem.Manifestation.Data
( BoundDictionary(..)
, BoundType(..)
, getBoundTypeName
, getBoundDefaultType
, getConcreteUVarBounds
, getConcreteQVarBounds
, getConcreteQVarQualifiers
, getQualifierOperation
, getDualBoundType
, getTyVarOp
) where
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Monoid
import qualified Data.Set as Set
import Data.Set (Set)
import Language.K3.Core.Type
import Language.K3.TypeSystem.Data
import Language.K3.Utils.Pretty
import Language.K3.Utils.Pretty.Common
data BoundDictionary
= BoundDictionary
{ uvarBoundDict :: Map (UVar, BoundType) ShallowType
, uvarOpaqueBoundDict :: Map (UVar, BoundType) (Set OpaqueVar)
, qvarBoundDict :: Map (QVar, BoundType) ShallowType
, qvarOpaqueBoundDict :: Map (QVar, BoundType) (Set OpaqueVar)
, qvarQualDict :: Map (QVar, BoundType) (Set TQual)
, ovarRangeDict :: Map (OpaqueVar, BoundType) TypeOrVar
}
instance Monoid BoundDictionary where
mempty =
BoundDictionary Map.empty Map.empty Map.empty Map.empty Map.empty Map.empty
mappend (BoundDictionary ubD uobD qbD qobD qqD orD)
(BoundDictionary ubD' uobD' qbD' qobD' qqD' orD') =
BoundDictionary
(ubD `Map.union` ubD')
(Map.unionWith Set.union uobD uobD')
(qbD `Map.union` qbD')
(Map.unionWith Set.union qobD qobD')
(qqD `Map.union` qqD')
(orD `Map.union` orD')
instance Pretty BoundDictionary where
prettyLines dict = vconcats
[ ["UVars: "] %+
prettyVarMap prettyBoundVarPair prettyLines (uvarBoundDict dict)
, ["UVars opaque: "] %+
prettyVarMap prettyBoundVarPair normalPrettySet
(uvarOpaqueBoundDict dict)
, ["QVars: "] %+
prettyVarMap prettyBoundVarPair normalPrettyPair
(Map.intersectionWith (,) (qvarBoundDict dict) (qvarQualDict dict))
, ["QVars opaque: "] %+
prettyVarMap prettyBoundVarPair normalPrettySet
(qvarOpaqueBoundDict dict)
, ["Opaques bounds: "] %+
explicitNormalPrettyMap normalPrettyPair prettyLines
(ovarRangeDict dict)
]
where
prettyVarMap = explicitPrettyMap ["{"] ["}"] ", " ""
prettyBoundVarPair :: (TVar q, BoundType) -> [String]
prettyBoundVarPair (var, bt) =
prettyLines var %+
case bt of
UpperBound -> ["≤"]
LowerBound -> ["≥"]
data BoundType
= UpperBound
| LowerBound
deriving (Eq, Ord, Show)
instance Pretty BoundType where
prettyLines = (:[]) . (++" bound") . getBoundTypeName
data DelayedOperationTag
= DelayedIntersectionTag
| DelayedUnionTag
deriving (Eq, Ord, Show)
getBoundTypeName :: BoundType -> String
getBoundTypeName UpperBound = "upper"
getBoundTypeName LowerBound = "lower"
getBoundDefaultType :: BoundType -> ShallowType
getBoundDefaultType UpperBound = STop
getBoundDefaultType LowerBound = SBottom
getConcreteUVarBounds :: BoundType -> UVar -> ConstraintSetQuery ShallowType
getConcreteUVarBounds UpperBound = QueryTypeByUVarLowerBound
getConcreteUVarBounds LowerBound = QueryTypeByUVarUpperBound
getConcreteQVarBounds :: BoundType -> QVar -> ConstraintSetQuery ShallowType
getConcreteQVarBounds UpperBound = QueryTypeByQVarLowerBound
getConcreteQVarBounds LowerBound = QueryTypeByQVarUpperBound
getConcreteQVarQualifiers :: BoundType -> QVar -> ConstraintSetQuery (Set TQual)
getConcreteQVarQualifiers UpperBound = QueryTQualSetByQVarLowerBound
getConcreteQVarQualifiers LowerBound = QueryTQualSetByQVarUpperBound
getQualifierOperation :: BoundType -> [Set TQual] -> Set TQual
getQualifierOperation UpperBound = Set.unions
getQualifierOperation LowerBound =
foldl Set.intersection (Set.fromList [TMut, TImmut])
getDualBoundType :: BoundType -> BoundType
getDualBoundType UpperBound = LowerBound
getDualBoundType LowerBound = UpperBound
getTyVarOp :: BoundType -> TypeVariableOperator
getTyVarOp UpperBound = TyVarOpIntersection
getTyVarOp LowerBound = TyVarOpUnion
|
8741591d664196efc9122fa08ac062875661adb36ddc02be1d5c97ec6b9a9857 | GaloisInc/semmc | Template.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE KindSignatures #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE UndecidableInstances #
module SemMC.Template (
RecoverOperandFn(..),
TemplatedOperandFn,
TemplatedOperand(..),
TemplatableOperand(..)
) where
import Data.Kind ( Type )
import Data.Parameterized.Classes ( ShowF(..) )
import Data.Parameterized.Some ( Some(..) )
import qualified Data.Set as Set
import GHC.TypeLits ( Symbol )
import qualified What4.Interface as WI
import qualified What4.Expr.GroundEval as WEG
import qualified SemMC.Architecture as A
-- | A function that allows you to recover the concrete value of a templated
-- operand given a concrete evaluation function, typically provided as the model
from an SMT solver .
newtype RecoverOperandFn sym op =
RecoverOperandFn { unRecOpFn :: (forall tp. WI.SymExpr sym tp -> IO (WEG.GroundValue tp)) -> IO op }
| The bulk of what a ' TemplatedOperand ' is . Reading off the type in English :
-- given a symbolic expression builder and a mapping from machine location to
symbolic expression , return ( in IO ) both an expression representing the
-- templated operand and a way to recover a concrete operand.
--
-- The idea is that the expression has all the register-related information
-- filled in directly, but all immediates are symbolic. The reason this is a
-- function and not the expression/recovery function themselves is that we need
-- a separation between "template possibilities" generation time and actual
-- formula generation time.
type TemplatedOperandFn arch s = forall sym.
(WI.IsExprBuilder sym,
WI.IsSymExprBuilder sym)
=> sym
-> (forall tp. A.Location arch tp -> IO (WI.SymExpr sym tp))
-> IO ( A.AllocatedOperand arch sym s
, RecoverOperandFn sym (A.Operand arch s)
)
| An operand for ' TemplatedArch ' .
data TemplatedOperand (arch :: Type) (s :: Symbol) =
TemplatedOperand { templOpLocation :: Maybe (A.Location arch (A.OperandType arch s))
-- ^ If this operand represents a location, this is it.
, templUsedLocations :: Set.Set (Some (A.Location arch))
-- ^ Locations used by this operand.
, templOpFn :: TemplatedOperandFn arch s
-- ^ How to get an expression and recovery function for this
-- operand.
}
instance ShowF (A.Location arch) => Show (TemplatedOperand arch s) where
show op = show (templUsedLocations op)
instance (ShowF (A.Operand arch), ShowF (A.Location arch)) => ShowF (TemplatedOperand arch)
instance A.IsOperand (TemplatedOperand arch)
-- | A specific type of operand of which you can generate templates.
class TemplatableOperand (arch :: Type) where
-- | All possible templates of an operand. In a nutshell, fill in register
-- parts, leave immediate parts symbolic.
opTemplates :: A.OperandTypeRepr arch s -> [TemplatedOperand arch s]
| null | https://raw.githubusercontent.com/GaloisInc/semmc/4dc4439720b3b0de8812a68f8156dc89da76da57/semmc/src/SemMC/Template.hs | haskell | # LANGUAGE RankNTypes #
| A function that allows you to recover the concrete value of a templated
operand given a concrete evaluation function, typically provided as the model
given a symbolic expression builder and a mapping from machine location to
templated operand and a way to recover a concrete operand.
The idea is that the expression has all the register-related information
filled in directly, but all immediates are symbolic. The reason this is a
function and not the expression/recovery function themselves is that we need
a separation between "template possibilities" generation time and actual
formula generation time.
^ If this operand represents a location, this is it.
^ Locations used by this operand.
^ How to get an expression and recovery function for this
operand.
| A specific type of operand of which you can generate templates.
| All possible templates of an operand. In a nutshell, fill in register
parts, leave immediate parts symbolic. | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE KindSignatures #
# LANGUAGE UndecidableInstances #
module SemMC.Template (
RecoverOperandFn(..),
TemplatedOperandFn,
TemplatedOperand(..),
TemplatableOperand(..)
) where
import Data.Kind ( Type )
import Data.Parameterized.Classes ( ShowF(..) )
import Data.Parameterized.Some ( Some(..) )
import qualified Data.Set as Set
import GHC.TypeLits ( Symbol )
import qualified What4.Interface as WI
import qualified What4.Expr.GroundEval as WEG
import qualified SemMC.Architecture as A
from an SMT solver .
newtype RecoverOperandFn sym op =
RecoverOperandFn { unRecOpFn :: (forall tp. WI.SymExpr sym tp -> IO (WEG.GroundValue tp)) -> IO op }
| The bulk of what a ' TemplatedOperand ' is . Reading off the type in English :
symbolic expression , return ( in IO ) both an expression representing the
type TemplatedOperandFn arch s = forall sym.
(WI.IsExprBuilder sym,
WI.IsSymExprBuilder sym)
=> sym
-> (forall tp. A.Location arch tp -> IO (WI.SymExpr sym tp))
-> IO ( A.AllocatedOperand arch sym s
, RecoverOperandFn sym (A.Operand arch s)
)
| An operand for ' TemplatedArch ' .
data TemplatedOperand (arch :: Type) (s :: Symbol) =
TemplatedOperand { templOpLocation :: Maybe (A.Location arch (A.OperandType arch s))
, templUsedLocations :: Set.Set (Some (A.Location arch))
, templOpFn :: TemplatedOperandFn arch s
}
instance ShowF (A.Location arch) => Show (TemplatedOperand arch s) where
show op = show (templUsedLocations op)
instance (ShowF (A.Operand arch), ShowF (A.Location arch)) => ShowF (TemplatedOperand arch)
instance A.IsOperand (TemplatedOperand arch)
class TemplatableOperand (arch :: Type) where
opTemplates :: A.OperandTypeRepr arch s -> [TemplatedOperand arch s]
|
7d74abd35fec09d149941b12839ef27a6489366dd914b6a2a3fd80483659cc46 | mozilla/medusa | changesets_test.clj | (ns medusa.changesets-test
(:require [clojure.test :refer :all]
[clj.medusa.changesets :refer [bounding-buildids]]))
(deftest test-bounding-buildids
(testing "when there is only one buildid for the day"
(is (= (bounding-buildids "2017-08-02" "mozilla-central") ["20170802100302" "20170802100302"])))
(testing "when there are multiple buildids for the day"
(is (= (bounding-buildids "2017-09-18" "mozilla-central") ["20170918100059" "20170918220054"]))))
(deftest test-buildid-from-dir
(is (= (#'clj.medusa.changesets/buildid-from-dir "2017-09-21-10-01-41-mozilla-central/") "20170921100141")))
| null | https://raw.githubusercontent.com/mozilla/medusa/213e712af2d7bb5580ba97d7770c1db140d457ee/test/medusa/changesets_test.clj | clojure | (ns medusa.changesets-test
(:require [clojure.test :refer :all]
[clj.medusa.changesets :refer [bounding-buildids]]))
(deftest test-bounding-buildids
(testing "when there is only one buildid for the day"
(is (= (bounding-buildids "2017-08-02" "mozilla-central") ["20170802100302" "20170802100302"])))
(testing "when there are multiple buildids for the day"
(is (= (bounding-buildids "2017-09-18" "mozilla-central") ["20170918100059" "20170918220054"]))))
(deftest test-buildid-from-dir
(is (= (#'clj.medusa.changesets/buildid-from-dir "2017-09-21-10-01-41-mozilla-central/") "20170921100141")))
|
|
557613e5d4603177d6e168d8838a521638b751aa071b1311e9801a129502d6b3 | roman/Haskell-Reactive-Extensions | ZipTest.hs | module Rx.Observable.ZipTest (tests) where
import Rx.Scheduler (newThread, schedule)
import qualified Rx.Observable as Rx
import Test.HUnit (assertEqual, assertFailure)
import Test.Hspec (Spec, describe, it)
tests :: Spec
tests =
describe "Rx.Observable.zipWith" $
it "is thread safe" $ do
let size = 1000000 :: Int
input = replicate size (1 :: Int)
(as, bs) = splitAt (size `div` 2) input
let ob1 = Rx.Observable $ \observer ->
schedule newThread $ do
mapM_ (Rx.onNext observer) as
Rx.onCompleted observer
ob2 = Rx.Observable $ \observer ->
schedule newThread $ do
mapM_ (Rx.onNext observer) bs
Rx.onCompleted observer
source =
Rx.foldLeft (+) 0
$ Rx.zipWith (+) ob1 ob2
eResult <- Rx.toEither source
case eResult of
Right result ->
assertEqual "should work correctly" size result
Left err ->
assertFailure $ "Rx failed on test: " ++ show err
| null | https://raw.githubusercontent.com/roman/Haskell-Reactive-Extensions/0faddbb671be7f169eeadbe6163e8d0b2be229fb/rx-core/test/Rx/Observable/ZipTest.hs | haskell | module Rx.Observable.ZipTest (tests) where
import Rx.Scheduler (newThread, schedule)
import qualified Rx.Observable as Rx
import Test.HUnit (assertEqual, assertFailure)
import Test.Hspec (Spec, describe, it)
tests :: Spec
tests =
describe "Rx.Observable.zipWith" $
it "is thread safe" $ do
let size = 1000000 :: Int
input = replicate size (1 :: Int)
(as, bs) = splitAt (size `div` 2) input
let ob1 = Rx.Observable $ \observer ->
schedule newThread $ do
mapM_ (Rx.onNext observer) as
Rx.onCompleted observer
ob2 = Rx.Observable $ \observer ->
schedule newThread $ do
mapM_ (Rx.onNext observer) bs
Rx.onCompleted observer
source =
Rx.foldLeft (+) 0
$ Rx.zipWith (+) ob1 ob2
eResult <- Rx.toEither source
case eResult of
Right result ->
assertEqual "should work correctly" size result
Left err ->
assertFailure $ "Rx failed on test: " ++ show err
|
|
8b3b7857761d0b9cc190be3affdaa51888cc33f26562eac5e9f46c3f707a744d | prg-titech/baccaml | min_caml.ml | open MinCaml
open Jit
let output_file = ref None
let run_typ = ref `Emit
let jit_typ = ref `Not_specified
let need_interp_wo_hints = ref `No
let id x = x
let emit_interp_wo_hints p =
let open Asm in
let open Jit_elim_hints in
match !need_interp_wo_hints with
| `Yes ->
(match !jit_typ with
| `Not_specified -> p
| (`Meta_tracing | `Meta_method) as typ ->
let (Prog (flttbl, strtbl, fundefs, main)) = p in
Prog (flttbl, strtbl, elim_hints_and_rename typ fundefs, main))
| `No -> p
;;
let virtualize l = Util.virtualize l |> emit_interp_wo_hints
let open_out_file f =
match !output_file with
| Some name -> open_out @@ Filename.remove_extension name ^ ".s"
| None -> open_out @@ Filename.remove_extension f ^ ".s"
;;
let annot p =
match !jit_typ with
| `Not_specified -> p
| (`Meta_method | `Meta_tracing) as typ -> Jit_annot.annotate typ p
;;
let run_dump f =
let inchan = open_in f in
try
Lexing.from_channel inchan
|> virtualize
|> Simm.f
|> annot
|> Asm.print_prog;
close_in inchan
with
| e ->
close_in inchan;
raise e
;;
let run_interp f =
let ic = open_in f in
try
Lexing.from_channel ic
|> virtualize
|> Simm.f
|> annot
|> Interp.f
|> string_of_int
|> print_endline
with
| e ->
close_in ic;
raise e
;;
let run_compile f =
let inchan = open_in f in
let outchan = open_out_file f in
try
Lexing.from_channel inchan
|> virtualize
|> Simm.f
|> annot
|> RegAlloc.f
|> Emit.f outchan;
close_in inchan;
close_out outchan
with
| e ->
close_in inchan;
close_out outchan;
raise e
;;
let print_ast f =
let ic = open_in f in
Id.counter := 0;
Typing.extenv := M.empty;
try
Lexing.from_channel ic
|> Parser.exp Lexer.token
|> Syntax.show
|> print_endline;
close_in ic
with
| e ->
close_in ic;
raise e
;;
let spec_list =
let set_jittyp str =
match str with
| "mjit" -> jit_typ := `Meta_method
| "tjit" -> jit_typ := `Meta_tracing
| _ -> ()
in
[ "-o", Arg.String (fun out -> output_file := Some out), "output file"
; ( "-inline"
, Arg.Int (fun i -> Inline.threshold := i)
, "maximum size of functions inlined" )
; ( "-iter"
, Arg.Int (fun i -> Util.limit := i)
, "maximum number of optimizations iterated" )
; "-type", Arg.String set_jittyp, "specify jit type"
; ( "-err"
, Arg.Unit (fun _ -> Log.log_level := `Error)
, "Specify loglevel as error" )
; ( "-debug"
, Arg.Unit (fun _ -> Log.log_level := `Debug)
, "Specify loglevel as debug" )
; "-dump", Arg.Unit (fun _ -> run_typ := `Dump), "emit virtual machine code"
; "-ast", Arg.Unit (fun _ -> run_typ := `Ast), "emit ast"
; ( "-no-hint"
, Arg.Unit (fun _ -> need_interp_wo_hints := `Yes)
, "eliminate hint functions written in your meta-interp." )
; "-interp", Arg.Unit (fun _ -> run_typ := `Interp), "run as interpreter"
]
;;
let usage =
"Mitou Min-Caml Compiler (C) Eijiro Sumii\n"
^ Printf.sprintf
"usage: %s [-inline m] [-iter n] ...filenames without \".ml\"..."
Sys.argv.(0)
;;
let () =
let files = ref [] in
Arg.parse spec_list (fun f -> files := !files @ [ f ]) usage;
!files
|> List.iter
(match !run_typ with
| `Ast -> print_ast
| `Dump -> run_dump
| `Interp -> run_interp
| `Emit -> run_compile)
;;
| null | https://raw.githubusercontent.com/prg-titech/baccaml/a3b95e996a995b5004ca897a4b6419edfee590aa/bin/min_caml.ml | ocaml | open MinCaml
open Jit
let output_file = ref None
let run_typ = ref `Emit
let jit_typ = ref `Not_specified
let need_interp_wo_hints = ref `No
let id x = x
let emit_interp_wo_hints p =
let open Asm in
let open Jit_elim_hints in
match !need_interp_wo_hints with
| `Yes ->
(match !jit_typ with
| `Not_specified -> p
| (`Meta_tracing | `Meta_method) as typ ->
let (Prog (flttbl, strtbl, fundefs, main)) = p in
Prog (flttbl, strtbl, elim_hints_and_rename typ fundefs, main))
| `No -> p
;;
let virtualize l = Util.virtualize l |> emit_interp_wo_hints
let open_out_file f =
match !output_file with
| Some name -> open_out @@ Filename.remove_extension name ^ ".s"
| None -> open_out @@ Filename.remove_extension f ^ ".s"
;;
let annot p =
match !jit_typ with
| `Not_specified -> p
| (`Meta_method | `Meta_tracing) as typ -> Jit_annot.annotate typ p
;;
let run_dump f =
let inchan = open_in f in
try
Lexing.from_channel inchan
|> virtualize
|> Simm.f
|> annot
|> Asm.print_prog;
close_in inchan
with
| e ->
close_in inchan;
raise e
;;
let run_interp f =
let ic = open_in f in
try
Lexing.from_channel ic
|> virtualize
|> Simm.f
|> annot
|> Interp.f
|> string_of_int
|> print_endline
with
| e ->
close_in ic;
raise e
;;
let run_compile f =
let inchan = open_in f in
let outchan = open_out_file f in
try
Lexing.from_channel inchan
|> virtualize
|> Simm.f
|> annot
|> RegAlloc.f
|> Emit.f outchan;
close_in inchan;
close_out outchan
with
| e ->
close_in inchan;
close_out outchan;
raise e
;;
let print_ast f =
let ic = open_in f in
Id.counter := 0;
Typing.extenv := M.empty;
try
Lexing.from_channel ic
|> Parser.exp Lexer.token
|> Syntax.show
|> print_endline;
close_in ic
with
| e ->
close_in ic;
raise e
;;
let spec_list =
let set_jittyp str =
match str with
| "mjit" -> jit_typ := `Meta_method
| "tjit" -> jit_typ := `Meta_tracing
| _ -> ()
in
[ "-o", Arg.String (fun out -> output_file := Some out), "output file"
; ( "-inline"
, Arg.Int (fun i -> Inline.threshold := i)
, "maximum size of functions inlined" )
; ( "-iter"
, Arg.Int (fun i -> Util.limit := i)
, "maximum number of optimizations iterated" )
; "-type", Arg.String set_jittyp, "specify jit type"
; ( "-err"
, Arg.Unit (fun _ -> Log.log_level := `Error)
, "Specify loglevel as error" )
; ( "-debug"
, Arg.Unit (fun _ -> Log.log_level := `Debug)
, "Specify loglevel as debug" )
; "-dump", Arg.Unit (fun _ -> run_typ := `Dump), "emit virtual machine code"
; "-ast", Arg.Unit (fun _ -> run_typ := `Ast), "emit ast"
; ( "-no-hint"
, Arg.Unit (fun _ -> need_interp_wo_hints := `Yes)
, "eliminate hint functions written in your meta-interp." )
; "-interp", Arg.Unit (fun _ -> run_typ := `Interp), "run as interpreter"
]
;;
let usage =
"Mitou Min-Caml Compiler (C) Eijiro Sumii\n"
^ Printf.sprintf
"usage: %s [-inline m] [-iter n] ...filenames without \".ml\"..."
Sys.argv.(0)
;;
let () =
let files = ref [] in
Arg.parse spec_list (fun f -> files := !files @ [ f ]) usage;
!files
|> List.iter
(match !run_typ with
| `Ast -> print_ast
| `Dump -> run_dump
| `Interp -> run_interp
| `Emit -> run_compile)
;;
|
|
2c186a25338584a1a4fe212e36c5e1d40240e38ce45a2a54fbd32600cb1687e2 | mirage/cowabloga | bootstrap.mli |
* Copyright ( c ) 2014 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2014 Richard Mortier <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
val body:
?google_analytics:(string * string)
-> title:string -> headers:Cow.Html.t -> Cow.Html.t
-> Cow.Html.t
val page: ?ns:string -> Cow.Html.t -> string
| null | https://raw.githubusercontent.com/mirage/cowabloga/2c256a92258f012c095bb72edcb639ad2fe164b3/lib/bootstrap.mli | ocaml |
* Copyright ( c ) 2014 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2014 Richard Mortier <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
val body:
?google_analytics:(string * string)
-> title:string -> headers:Cow.Html.t -> Cow.Html.t
-> Cow.Html.t
val page: ?ns:string -> Cow.Html.t -> string
|
|
d794d459d3effadcb27f2ab484a1c44732e80edb0f24e9e42cb171b02b7a611e | replikativ/superv.async | build.clj | (ns build
(:refer-clojure :exclude [test])
(:require [clojure.tools.build.api :as b]
[borkdude.gh-release-artifact :as gh]
[deps-deploy.deps-deploy :as dd])
(:import [clojure.lang ExceptionInfo]))
(def org "replikativ")
(def lib 'io.replikativ/superv.async)
(def current-commit (b/git-process {:git-args "rev-parse HEAD"}))
(def version (format "0.3.%s" (b/git-count-revs nil)))
(def class-dir "target/classes")
(def basis (b/create-basis {:project "deps.edn"}))
(def jar-file (format "target/%s-%s.jar" (name lib) version))
(defn clean
[_]
(b/delete {:path "target"}))
(defn jar
[_]
(b/write-pom {:class-dir class-dir
:src-pom "./template/pom.xml"
:lib lib
:version version
:basis basis
:src-dirs ["src"]})
(b/copy-dir {:src-dirs ["src" "resources"]
:target-dir class-dir})
(b/jar {:class-dir class-dir
:jar-file jar-file}))
(defn deploy
"Don't forget to set CLOJARS_USERNAME and CLOJARS_PASSWORD env vars."
[_]
(dd/deploy {:installer :remote :artifact jar-file
:pom-file (b/pom-path {:lib lib :class-dir class-dir})}))
(defn fib [a b]
(lazy-seq (cons a (fib b (+ a b)))))
(defn retry-with-fib-backoff [retries exec-fn test-fn]
(loop [idle-times (take retries (fib 1 2))]
(let [result (exec-fn)]
(if (test-fn result)
(do (println "Returned: " result)
(if-let [sleep-ms (first idle-times)]
(do (println "Retrying with remaining back-off times (in s): " idle-times)
(Thread/sleep (* 1000 sleep-ms))
(recur (rest idle-times)))
result))
result))))
(defn try-release []
(try (gh/overwrite-asset {:org org
:repo (name lib)
:tag version
:commit current-commit
:file jar-file
:content-type "application/java-archive"
:draft false})
(catch ExceptionInfo e
(assoc (ex-data e) :failure? true))))
(defn release
[_]
(let [ret (retry-with-fib-backoff 10 try-release :failure?)]
(if (:failure? ret)
(do (println "GitHub release failed!")
(System/exit 1))
(println (:url ret)))))
(defn install
[_]
(clean nil)
(jar nil)
(b/install {:basis (b/create-basis {})
:lib lib
:version version
:jar-file jar-file
:class-dir class-dir}))
| null | https://raw.githubusercontent.com/replikativ/superv.async/9d336c89ed286ec02698ebea722cdd009a9ea2ca/build.clj | clojure | (ns build
(:refer-clojure :exclude [test])
(:require [clojure.tools.build.api :as b]
[borkdude.gh-release-artifact :as gh]
[deps-deploy.deps-deploy :as dd])
(:import [clojure.lang ExceptionInfo]))
(def org "replikativ")
(def lib 'io.replikativ/superv.async)
(def current-commit (b/git-process {:git-args "rev-parse HEAD"}))
(def version (format "0.3.%s" (b/git-count-revs nil)))
(def class-dir "target/classes")
(def basis (b/create-basis {:project "deps.edn"}))
(def jar-file (format "target/%s-%s.jar" (name lib) version))
(defn clean
[_]
(b/delete {:path "target"}))
(defn jar
[_]
(b/write-pom {:class-dir class-dir
:src-pom "./template/pom.xml"
:lib lib
:version version
:basis basis
:src-dirs ["src"]})
(b/copy-dir {:src-dirs ["src" "resources"]
:target-dir class-dir})
(b/jar {:class-dir class-dir
:jar-file jar-file}))
(defn deploy
"Don't forget to set CLOJARS_USERNAME and CLOJARS_PASSWORD env vars."
[_]
(dd/deploy {:installer :remote :artifact jar-file
:pom-file (b/pom-path {:lib lib :class-dir class-dir})}))
(defn fib [a b]
(lazy-seq (cons a (fib b (+ a b)))))
(defn retry-with-fib-backoff [retries exec-fn test-fn]
(loop [idle-times (take retries (fib 1 2))]
(let [result (exec-fn)]
(if (test-fn result)
(do (println "Returned: " result)
(if-let [sleep-ms (first idle-times)]
(do (println "Retrying with remaining back-off times (in s): " idle-times)
(Thread/sleep (* 1000 sleep-ms))
(recur (rest idle-times)))
result))
result))))
(defn try-release []
(try (gh/overwrite-asset {:org org
:repo (name lib)
:tag version
:commit current-commit
:file jar-file
:content-type "application/java-archive"
:draft false})
(catch ExceptionInfo e
(assoc (ex-data e) :failure? true))))
(defn release
[_]
(let [ret (retry-with-fib-backoff 10 try-release :failure?)]
(if (:failure? ret)
(do (println "GitHub release failed!")
(System/exit 1))
(println (:url ret)))))
(defn install
[_]
(clean nil)
(jar nil)
(b/install {:basis (b/create-basis {})
:lib lib
:version version
:jar-file jar-file
:class-dir class-dir}))
|
|
2acbf973de498e626e38c8c1e986e7a54d4d2cccb1b79249cab8328a6f1cdeb5 | REMath/mit_16.399 | variables.mli | (* variables.mli *)
open Symbol_Table
type variable = Symbol_Table.variable
val number_of_variables : unit -> int
val for_all_variables : (variable -> 'a) -> unit
val print_variable : variable -> unit
val map_variables : (variable -> unit) -> (variable -> unit) -> unit
val string_of_variable : variable -> string
| null | https://raw.githubusercontent.com/REMath/mit_16.399/3f395d6a9dfa1ed232d307c3c542df3dbd5b614a/project/Generic-FW-BW-REL-Abstract-Interpreter/variables.mli | ocaml | variables.mli | open Symbol_Table
type variable = Symbol_Table.variable
val number_of_variables : unit -> int
val for_all_variables : (variable -> 'a) -> unit
val print_variable : variable -> unit
val map_variables : (variable -> unit) -> (variable -> unit) -> unit
val string_of_variable : variable -> string
|
cc2d09f3892f395a99c3cc01c500af6108e04ee014d7c8e03705dd04f92e8d78 | soulomoon/SICP | Exercise4.27.scm | Exercise 4.27 : Suppose we type in the following definitions to the lazy evaluator :
; (define count 0)
( define ( i d x ) ( set ! count ( + count 1 ) ) x )
; Give the missing values in the following sequence of interactions, and explain your answers.242
; (define w (id (id 10)))
; ; ; L - Eval input :
; count
; ; ; L - Eval value :
; ⟨response⟩
; ; ; L - Eval input :
; w
; ; ; L - Eval value :
; ⟨response⟩
; ; ; L - Eval input :
; count
; ; ; L - Eval value :
; ⟨response⟩
(define count 0)
(define (id x) (set! count (+ count 1)) x)
L - Eval input :
count
L - Eval value :
1
L - Eval input :
w
L - Eval value :
10
L - Eval input :
count
L - Eval value :
2
; (interpret
; '(begin
; (define count 0)
( define ( i d x ) ( set ! count ( + count 1 ) ) x )
; (define w (id (id 10)))
; count
; )
; )
Welcome to , version 6.7 [ 3 m ] .
Language : SICP ( PLaneT 1.18 ) ; memory limit : 128 MB .
; 'done
eval#-----(begin ( define count 0 ) ( define ( i d x ) ( set ! count ( + count 1 ) ) x ) ( define w ( i d ( i d 10 ) ) ) count ( display w ) count )
; eval#-----(define count 0)
; eval#-----0
eval#-----(define ( i d x ) ( set ! count ( + count 1 ) ) x )
eval#-----(lambda ( x ) ( set ! count ( + count 1 ) ) x )
; eval#-----(define w (id (id 10)))
; eval#-----(id (id 10))
; eval#-----id
delay - it--------(id 10 )
eval#-----(set ! count ( + count 1 ) )
eval#-----(+ count 1 )
; eval#-----+
; eval#-----count
; eval#-----1
; eval#-----x
; eval#-----count
; eval#-----(display w)
; eval#-----display
; eval#-----w
eval#-----(id 10 )
; eval#-----id
; delay-it--------10
eval#-----(set ! count ( + count 1 ) )
eval#-----(+ count 1 )
; eval#-----+
; eval#-----count
; eval#-----1
; eval#-----x
; eval#-----10
; force-it------thunk10
force - it------thunk(id 10 )
10eval#-----count
2
; > | null | https://raw.githubusercontent.com/soulomoon/SICP/1c6cbf5ecf6397eaeb990738a938d48c193af1bb/Chapter4/Exercise4.27.scm | scheme | (define count 0)
Give the missing values in the following sequence of interactions, and explain your answers.242
(define w (id (id 10)))
; ; L - Eval input :
count
; ; L - Eval value :
⟨response⟩
; ; L - Eval input :
w
; ; L - Eval value :
⟨response⟩
; ; L - Eval input :
count
; ; L - Eval value :
⟨response⟩
(interpret
'(begin
(define count 0)
(define w (id (id 10)))
count
)
)
memory limit : 128 MB .
'done
eval#-----(define count 0)
eval#-----0
eval#-----(define w (id (id 10)))
eval#-----(id (id 10))
eval#-----id
eval#-----+
eval#-----count
eval#-----1
eval#-----x
eval#-----count
eval#-----(display w)
eval#-----display
eval#-----w
eval#-----id
delay-it--------10
eval#-----+
eval#-----count
eval#-----1
eval#-----x
eval#-----10
force-it------thunk10
> | Exercise 4.27 : Suppose we type in the following definitions to the lazy evaluator :
( define ( i d x ) ( set ! count ( + count 1 ) ) x )
(define count 0)
(define (id x) (set! count (+ count 1)) x)
L - Eval input :
count
L - Eval value :
1
L - Eval input :
w
L - Eval value :
10
L - Eval input :
count
L - Eval value :
2
( define ( i d x ) ( set ! count ( + count 1 ) ) x )
Welcome to , version 6.7 [ 3 m ] .
eval#-----(begin ( define count 0 ) ( define ( i d x ) ( set ! count ( + count 1 ) ) x ) ( define w ( i d ( i d 10 ) ) ) count ( display w ) count )
eval#-----(define ( i d x ) ( set ! count ( + count 1 ) ) x )
eval#-----(lambda ( x ) ( set ! count ( + count 1 ) ) x )
delay - it--------(id 10 )
eval#-----(set ! count ( + count 1 ) )
eval#-----(+ count 1 )
eval#-----(id 10 )
eval#-----(set ! count ( + count 1 ) )
eval#-----(+ count 1 )
force - it------thunk(id 10 )
10eval#-----count
2 |
f4784b57b99f0ca565e27c1cb44699c1343fc1726a622064c574c50a519029a7 | OCamlPro/ez_api | ezReq_lwt.ml | (**************************************************************************)
(* *)
Copyright 2018 - 2022 OCamlPro
(* *)
(* All rights reserved. This file is distributed under the terms of the *)
GNU Lesser General Public License version 2.1 , with the special
(* exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
include EzCurl_multi
| null | https://raw.githubusercontent.com/OCamlPro/ez_api/5253f7dd8936e923290aa969ee43ebd3dc6fce2d/src/request/unix/curl/multi/ezReq_lwt.ml | ocaml | ************************************************************************
All rights reserved. This file is distributed under the terms of the
exception on linking described in the file LICENSE.
************************************************************************ | Copyright 2018 - 2022 OCamlPro
GNU Lesser General Public License version 2.1 , with the special
include EzCurl_multi
|
87556142582eaf3425b23d9b873097d67a3870129c2a86a81cbf7bbe70a439eb | JKTKops/ProtoHaskell | Panic.hs | module Control.Panic where
import Control.Exception
import System.Environment (getProgName)
import System.IO.Unsafe (unsafePerformIO)
import Paths_ProtoHaskell (version)
| These are exceptions that we will never catch . If one of these happens ,
-- the compiler is crashing.
data PhcException
= Panic String
| Sorry String
instance Exception PhcException
instance Show PhcException where
show e = progName ++ ": " ++ showPhcException e
showPhcException :: PhcException -> String
showPhcException = \case
Panic msg -> panicMsg msg
Sorry msg -> sorryMsg msg
where
panicMsg :: String -> String
panicMsg s = "panic! The \"impossible\" has happened.\n"
++ " (PHC version: " ++ show version ++ "):\n"
++ " " ++ s ++ "\n\n"
++ "Please report this as a bug."
sorryMsg :: String -> String
sorryMsg s = "sorry! You've run into an unimplemented feature or known bug.\n"
++ " (PHC version: " ++ show version ++ "):\n"
++ " " ++ s
panic, sorry :: String -> a
panic = throw . Panic
sorry = throw . Sorry
| The name of this instance of PHC .
progName :: String
progName = unsafePerformIO getProgName
# NOINLINE progName #
shortUsage :: String
shortUsage = "Usage: for basic information, try --help."
| null | https://raw.githubusercontent.com/JKTKops/ProtoHaskell/437c37d7bd6d862008f86d7e8045c7a60b12b532/src/Control/Panic.hs | haskell | the compiler is crashing. | module Control.Panic where
import Control.Exception
import System.Environment (getProgName)
import System.IO.Unsafe (unsafePerformIO)
import Paths_ProtoHaskell (version)
| These are exceptions that we will never catch . If one of these happens ,
data PhcException
= Panic String
| Sorry String
instance Exception PhcException
instance Show PhcException where
show e = progName ++ ": " ++ showPhcException e
showPhcException :: PhcException -> String
showPhcException = \case
Panic msg -> panicMsg msg
Sorry msg -> sorryMsg msg
where
panicMsg :: String -> String
panicMsg s = "panic! The \"impossible\" has happened.\n"
++ " (PHC version: " ++ show version ++ "):\n"
++ " " ++ s ++ "\n\n"
++ "Please report this as a bug."
sorryMsg :: String -> String
sorryMsg s = "sorry! You've run into an unimplemented feature or known bug.\n"
++ " (PHC version: " ++ show version ++ "):\n"
++ " " ++ s
panic, sorry :: String -> a
panic = throw . Panic
sorry = throw . Sorry
| The name of this instance of PHC .
progName :: String
progName = unsafePerformIO getProgName
# NOINLINE progName #
shortUsage :: String
shortUsage = "Usage: for basic information, try --help."
|
b31457f23ace48e788b2fc08f954aa6bfab411ffc83569a0c9cbc14cf1572a31 | hyperfiddle/electric | compiler4.cljc | (ns dustin.compiler4
(:require [minitest :refer [tests]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Normalize AST, implicit fmap, no bind, unify branches ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn normalize
"Expands an all points in a given form
`(normalize '{plus (lambda a b (+ a b))} '(plus 1 2))`
:= `(+ 1 2)`
"
([registry form]
(normalize registry form {}))
([registry form env]
(if (seq? form)
(let [[f & args] form]
(if-some [[_ & args-body] (registry f)]
(let [syms (butlast args-body)]
(as-> (last args-body) body
(normalize registry body (merge env (zipmap syms args)))
(normalize registry body env)))
(cons 'fmap (cons f (map #(normalize registry % env) args)))))
(get env form form))))
(tests
(normalize
'{five (lambda 5)
plus (lambda-applicative a b (+ a b))
times (lambda-bind a b (m/reactor (if (odd? a) (* a b) (/ a b))))
func (lambda a b (plus a (times b b)))}
'(func >input3 (plus >input1 >input2)))
:=1 '((lambda a b (plus a (times b b))) >input3 ((lambda a b (+ a b)) >input1 >input2))
:=2 '((plus >input3 (times ((lambda a b (+ a b)) >input1 >input2) ((lambda a b (+ a b)) >input1 >input2))) >input3)
:=3 '(((lambda a b (+ a b)) >input3 ((lambda a b (* a b)) ((lambda a b (+ a b)) >input1 >input2) ((lambda a b (+ a b)) >input1 >input2))) >input3)
:=4 '(((+ >input3 ((lambda a b (* a b)) ((+ >input1 >input2)) ((+ >input1 >input2))))) >input3)
:=5 '(((+ >input3 ((lambda a b (* a b)) ((+ >input1 >input2)) ((+ >input1 >input2))))) >input3)
:= '(+ >input3 (* (+ >input1 >input2)
this can be optimized into one node
:= '(func >input3 (plus >input1 >input2))
)
"too much dynamism"
'(func >input3 (plus >input1 >input2))
'(mlet [:let [x (+ >input1 >input2)]]
(+ >input3 (* x x)))
'(>+ >input3 (if (odd? x) (>* >x >x) (>** >x >x)))
'(>+ >input3 ((fn [x] ...) >x))
(def conjv (fnil conj []))
(defn parenting [acc parent child]
(-> acc
(assoc-in [child :parent] parent)
(update-in [parent :children] conjv child)))
(defn analyze-form [nodes form !env]
(let [idx (count nodes)]
(swap! !env assoc form idx)
(if (coll? form)
(let [[f & args] form]
;; fmap
(reduce (fn [nodes form]
(if-let [child-index (get @!env form)]
(parenting nodes idx child-index)
(parenting (analyze-form nodes form !env) idx (count nodes))))
(conj nodes
{:type 'fmap
:form form
:f f})
args)
TODO bind
)
(if (symbol? form)
(conj nodes {:type 'user
:form form})
(throw (ex-info "Unknown form." {:form form}))))))
(defn analyze [form]
(analyze-form [] form (atom {})))
(tests
(analyze '(+ >input3 (* (+ >input1 >input2) (+ >input1 >input2))))
:=
'[{:type fmap, :form (+ >input3 (* (+ >input1 >input2) (+ >input1 >input2))), :f +, :children [1 2]}
{:type user, :form >input3, :parent 0}
{:type fmap, :form (* (+ >input1 >input2) (+ >input1 >input2)), :f *, :children [3 3], :parent 0}
{:type fmap, :form (+ >input1 >input2), :f +, :children [4 5], :parent 2}
{:type user, :form >input1, :parent 3}
{:type user, :form >input2, :parent 3}])
| null | https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2021/compiler4.cljc | clojure |
Normalize AST, implicit fmap, no bind, unify branches ;;
fmap | (ns dustin.compiler4
(:require [minitest :refer [tests]]))
(defn normalize
"Expands an all points in a given form
`(normalize '{plus (lambda a b (+ a b))} '(plus 1 2))`
:= `(+ 1 2)`
"
([registry form]
(normalize registry form {}))
([registry form env]
(if (seq? form)
(let [[f & args] form]
(if-some [[_ & args-body] (registry f)]
(let [syms (butlast args-body)]
(as-> (last args-body) body
(normalize registry body (merge env (zipmap syms args)))
(normalize registry body env)))
(cons 'fmap (cons f (map #(normalize registry % env) args)))))
(get env form form))))
(tests
(normalize
'{five (lambda 5)
plus (lambda-applicative a b (+ a b))
times (lambda-bind a b (m/reactor (if (odd? a) (* a b) (/ a b))))
func (lambda a b (plus a (times b b)))}
'(func >input3 (plus >input1 >input2)))
:=1 '((lambda a b (plus a (times b b))) >input3 ((lambda a b (+ a b)) >input1 >input2))
:=2 '((plus >input3 (times ((lambda a b (+ a b)) >input1 >input2) ((lambda a b (+ a b)) >input1 >input2))) >input3)
:=3 '(((lambda a b (+ a b)) >input3 ((lambda a b (* a b)) ((lambda a b (+ a b)) >input1 >input2) ((lambda a b (+ a b)) >input1 >input2))) >input3)
:=4 '(((+ >input3 ((lambda a b (* a b)) ((+ >input1 >input2)) ((+ >input1 >input2))))) >input3)
:=5 '(((+ >input3 ((lambda a b (* a b)) ((+ >input1 >input2)) ((+ >input1 >input2))))) >input3)
:= '(+ >input3 (* (+ >input1 >input2)
this can be optimized into one node
:= '(func >input3 (plus >input1 >input2))
)
"too much dynamism"
'(func >input3 (plus >input1 >input2))
'(mlet [:let [x (+ >input1 >input2)]]
(+ >input3 (* x x)))
'(>+ >input3 (if (odd? x) (>* >x >x) (>** >x >x)))
'(>+ >input3 ((fn [x] ...) >x))
(def conjv (fnil conj []))
(defn parenting [acc parent child]
(-> acc
(assoc-in [child :parent] parent)
(update-in [parent :children] conjv child)))
(defn analyze-form [nodes form !env]
(let [idx (count nodes)]
(swap! !env assoc form idx)
(if (coll? form)
(let [[f & args] form]
(reduce (fn [nodes form]
(if-let [child-index (get @!env form)]
(parenting nodes idx child-index)
(parenting (analyze-form nodes form !env) idx (count nodes))))
(conj nodes
{:type 'fmap
:form form
:f f})
args)
TODO bind
)
(if (symbol? form)
(conj nodes {:type 'user
:form form})
(throw (ex-info "Unknown form." {:form form}))))))
(defn analyze [form]
(analyze-form [] form (atom {})))
(tests
(analyze '(+ >input3 (* (+ >input1 >input2) (+ >input1 >input2))))
:=
'[{:type fmap, :form (+ >input3 (* (+ >input1 >input2) (+ >input1 >input2))), :f +, :children [1 2]}
{:type user, :form >input3, :parent 0}
{:type fmap, :form (* (+ >input1 >input2) (+ >input1 >input2)), :f *, :children [3 3], :parent 0}
{:type fmap, :form (+ >input1 >input2), :f +, :children [4 5], :parent 2}
{:type user, :form >input1, :parent 3}
{:type user, :form >input2, :parent 3}])
|
70e2d90d6654d3fa4c1a6d05d6d05105dfb66ca6a7f09e1b0e76ee3729548b13 | achirkin/vulkan | Parser.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE Strict #-}
module VkXml.Parser
( ParseLoc (..), defParseLoc
, VkXmlParseException (..)
, VkXmlParser
, runAttrParser
, parseWithLoc
, parseFailed
, awaitReq
, parseTag
, parseTagForceAttrs
, unContent
, forceAttr
, decOrHex
) where
import Control.Applicative
import Control.Monad.Catch
import Control.Monad.Reader
import Control.Monad.State.Class
import Control.Monad.Zip
import Data.Conduit
import Data.Conduit.Lift
import Data.List (intercalate)
import Data.Semigroup
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Read as T
import Data.XML.Types
import GHC.Stack
import Path
import Text.XML.Stream.Parse
import Unsafe.Coerce
-- * Error reporing
defParseLoc :: Path b File
-> ParseLoc
defParseLoc = ParseLoc Nothing [] . toFilePath
newtype VkXmlParserT m a
= VkXmlParserT {runVkXmlParserT :: ReaderT ParseLoc m a }
deriving ( Functor, Applicative, Alternative, Monad, MonadTrans
, MonadFix, MonadIO, MonadPlus, MonadZip
, MonadReader ParseLoc, MonadState s
)
instance MonadThrow m => MonadThrow (VkXmlParserT m) where
throwM err' = VkXmlParserT $ do
eLoc <- ask
let (cs, err) = case fromException (toException err') of
Nothing -> (callStack, show err')
Just (VkXmlParseException cs' e) -> (cs', show e)
throwM . VkXmlParseException cs . T.pack
$ "\nParsing failed at " <> show eLoc <> ":\n " <> err
<> maybe "" (\e -> "\nlast opening tags were:\n" <> T.unpack e)
(mBeginTag eLoc)
<> "\n" <> prettyCallStack cs
where
mBeginTag eLoc = case treePath eLoc of
[] -> Nothing
[x] -> Just $ mkTag x
[x,y] -> Just $ mkTag y <> "\n " <> mkTag x
x:y:z:_ -> Just $ mkTag z <> "\n " <> mkTag y <> "\n " <> mkTag x
mkTag (n,as) =
"<" <> nameLocalName n
<> T.concat (map mkAttr as)
<> ">"
mkAttr (n, cs) = " " <> nameLocalName n <> "=\""
<> T.intercalate "," (map unContent cs)
<> "\""
-- | Location of parsing in the xml file
data ParseLoc = ParseLoc
{ posRange :: Maybe PositionRange
, treePath :: [(Name, [(Name, [Content])])]
, filePath :: FilePath
}
instance Show ParseLoc where
show ParseLoc {..}
= "{"
<> (intercalate "." . map (T.unpack . nameLocalName . fst) $ reverse treePath)
<> "} in " <> filePath
<> maybe "" ((":[" <>) . (<> "]") . show ) posRange
data VkXmlParseException
= VkXmlParseException
{ exceptCS :: CallStack
, unVkXmlParseException :: Text
}
instance Show VkXmlParseException where
show msg = "VkXmlParseException: " <> T.unpack (unVkXmlParseException msg)
instance Exception VkXmlParseException
-- | A constraint to allow parsing with exception throwing
type VkXmlParser m =
( MonadReader ParseLoc m
, MonadThrow m
)
-- | Show a meaningful message with error location
-- if parsing xml file has failed.
parseFailed :: (VkXmlParser m, HasCallStack) => String -> m a
parseFailed msg =
throwM . VkXmlParseException callStack $ T.pack msg
-- | Add full location information to the parsing events
parseWithLoc :: Monad m
=> ParseLoc
-> ConduitM Event o (VkXmlParserT m) r
-> ConduitM EventPos o m r
parseWithLoc initLoc pipe = parseWithLoc' initLoc =$= readLoc initLoc pipe
goDownTree :: (Name, [(Name, [Content])]) -> ParseLoc -> ParseLoc
goDownTree n pl = pl { treePath = n : treePath pl}
goUpTree :: ParseLoc -> ParseLoc
goUpTree pl = pl { treePath = drop 1 $ treePath pl}
updatePos :: Maybe PositionRange -> ParseLoc -> ParseLoc
updatePos pr pl = pl { posRange = pr }
parseWithLoc' :: Monad m => ParseLoc -> Conduit EventPos m (ParseLoc, Event)
parseWithLoc' defLoc
= evalStateC defLoc
$ awaitForever
$ \(mloc, ev) -> do
updatedLoc <- lift $ do
modify' (updatePos mloc)
case ev of
EventBeginElement n attrs -> modify' (goDownTree (n,attrs))
EventEndElement _ -> modify' goUpTree
_ -> return ()
get
yield ( updatedLoc, ev )
| Move location information from upstream to MonadReader environment
readLoc :: Monad m
=> ParseLoc
-> ConduitM Event o (VkXmlParserT m) r
-> ConduitM (ParseLoc, Event) o m r
readLoc defLoc pipe
= evalStateC defLoc
$ awaitForever updateStateAndYield
=$= transPipe (\x -> get >>= lift . runReaderT (runVkXmlParserT x)) pipe
where
updateStateAndYield (l, ev) = lift (put l) >> yield ev
-- * Helper utils
-- | Fail with `parseFailed` if encounter end of input
awaitReq :: (VkXmlParser m, HasCallStack) => Consumer Event m Event
awaitReq = await >>= maybe (parseFailed "unexpected end of input") pure
-- | Wrapper on top of `tag'` function
-- tries to consume only tag content
-- and cut the upstream for the inner conduit.
-- If name matcher or attr parser fail,
-- events are sent back via leftovers and conduit returns the flow control.
parseTag :: VkXmlParser m
=> Name
-- ^ match the name exactly
-> ReaderT ParseLoc AttrParser b
-- ^ parse tag attributes
-> (b -> ConduitM Event o m c)
-- ^ consume stuff inside the tag only
-> ConduitM Event o m (Maybe c)
parseTag name attrParser pipeF' = do
getAttrs <- runReaderT attrParser <$> ask
tag' (matching (name==)) getAttrs
(\b -> evalStateC (0 :: Int) pipeGuard =$= pipeF' b)
where
pipeGuard = awaitReq >>= \ev -> case ev of
EventBeginElement {} -> do
modify' (+1)
yield ev
pipeGuard
EventEndElement {} -> do
modify' (\x -> x-1)
curNesting <- get
if curNesting < 0
then leftover ev
else do
yield ev
pipeGuard
_ -> yield ev >> pipeGuard
-- | Raise an exception if attributes failed to parse
parseTagForceAttrs :: (VkXmlParser m, HasCallStack)
=> Name
-- ^ match the name exactly
-> ReaderT ParseLoc AttrParser b
-- ^ parse tag attributes
-> (b -> ConduitM Event o m c)
-- ^ consume stuff inside the tag only
-> ConduitM Event o m (Maybe c)
parseTagForceAttrs name attrParser pipeF' = do
mr <- parseTag name attrParser pipeF'
case mr of
Just r -> return $ Just r
Nothing -> await >>=
\case
Just ev@(EventBeginElement n attrs)
| n == name -> runAttrParser attrParser attrs
>>= \x -> x `seq` parseFailed
( "failed to parse tag attributes for " <> show ev
)
Just (EventContent c)
| T.null (T.strip (unContent c))
-> parseTagForceAttrs name attrParser pipeF'
Nothing -> return Nothing
Just ev -> leftover ev >> return Nothing
| Use GHC hachery to get
-- `xml-conduit-1.7.0/Text.XML.Stream.Parse.runAttrParser`
runAttrParser :: (VkXmlParser m, HasCallStack)
=> ReaderT ParseLoc AttrParser a -> [(Name, [Content])] -> m a
runAttrParser p x = do
loc <- ask
let p' = runReaderT p loc
pf :: [(Name, [Content])]
-> Either SomeException ([(Name, [Content])], a)
pf = p' `seq` unsafeCoerce p'
case pf x of
Right ([], r) -> pure r
Right (xs, _) -> parseFailed
$ "some attributes left unhandled: " <> show
( map (\(n, cs) -> T.unpack ( nameLocalName n)
<> " = " <> unwords (map uncontent cs)
) xs )
Left (SomeException e) -> throwM e
where
uncontent = T.unpack . unContent
forceAttr :: HasCallStack => Name -> ReaderT ParseLoc AttrParser Text
forceAttr n = do
mv <- lift (attr n)
case mv of
Nothing -> parseFailed $ "Missing tag attribute " <> show n
Just v -> return v
unContent :: Content -> Text
unContent (ContentText t) = t
unContent (ContentEntity t) = t
decOrHex :: Integral a => T.Reader a
decOrHex t = if "0x" `T.isPrefixOf` t
then T.hexadecimal t
else T.decimal t
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/genvulkan/src/VkXml/Parser.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE OverloadedStrings #
# LANGUAGE Strict #
* Error reporing
| Location of parsing in the xml file
| A constraint to allow parsing with exception throwing
| Show a meaningful message with error location
if parsing xml file has failed.
| Add full location information to the parsing events
* Helper utils
| Fail with `parseFailed` if encounter end of input
| Wrapper on top of `tag'` function
tries to consume only tag content
and cut the upstream for the inner conduit.
If name matcher or attr parser fail,
events are sent back via leftovers and conduit returns the flow control.
^ match the name exactly
^ parse tag attributes
^ consume stuff inside the tag only
| Raise an exception if attributes failed to parse
^ match the name exactly
^ parse tag attributes
^ consume stuff inside the tag only
`xml-conduit-1.7.0/Text.XML.Stream.Parse.runAttrParser` | # LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
module VkXml.Parser
( ParseLoc (..), defParseLoc
, VkXmlParseException (..)
, VkXmlParser
, runAttrParser
, parseWithLoc
, parseFailed
, awaitReq
, parseTag
, parseTagForceAttrs
, unContent
, forceAttr
, decOrHex
) where
import Control.Applicative
import Control.Monad.Catch
import Control.Monad.Reader
import Control.Monad.State.Class
import Control.Monad.Zip
import Data.Conduit
import Data.Conduit.Lift
import Data.List (intercalate)
import Data.Semigroup
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Read as T
import Data.XML.Types
import GHC.Stack
import Path
import Text.XML.Stream.Parse
import Unsafe.Coerce
defParseLoc :: Path b File
-> ParseLoc
defParseLoc = ParseLoc Nothing [] . toFilePath
newtype VkXmlParserT m a
= VkXmlParserT {runVkXmlParserT :: ReaderT ParseLoc m a }
deriving ( Functor, Applicative, Alternative, Monad, MonadTrans
, MonadFix, MonadIO, MonadPlus, MonadZip
, MonadReader ParseLoc, MonadState s
)
instance MonadThrow m => MonadThrow (VkXmlParserT m) where
throwM err' = VkXmlParserT $ do
eLoc <- ask
let (cs, err) = case fromException (toException err') of
Nothing -> (callStack, show err')
Just (VkXmlParseException cs' e) -> (cs', show e)
throwM . VkXmlParseException cs . T.pack
$ "\nParsing failed at " <> show eLoc <> ":\n " <> err
<> maybe "" (\e -> "\nlast opening tags were:\n" <> T.unpack e)
(mBeginTag eLoc)
<> "\n" <> prettyCallStack cs
where
mBeginTag eLoc = case treePath eLoc of
[] -> Nothing
[x] -> Just $ mkTag x
[x,y] -> Just $ mkTag y <> "\n " <> mkTag x
x:y:z:_ -> Just $ mkTag z <> "\n " <> mkTag y <> "\n " <> mkTag x
mkTag (n,as) =
"<" <> nameLocalName n
<> T.concat (map mkAttr as)
<> ">"
mkAttr (n, cs) = " " <> nameLocalName n <> "=\""
<> T.intercalate "," (map unContent cs)
<> "\""
data ParseLoc = ParseLoc
{ posRange :: Maybe PositionRange
, treePath :: [(Name, [(Name, [Content])])]
, filePath :: FilePath
}
instance Show ParseLoc where
show ParseLoc {..}
= "{"
<> (intercalate "." . map (T.unpack . nameLocalName . fst) $ reverse treePath)
<> "} in " <> filePath
<> maybe "" ((":[" <>) . (<> "]") . show ) posRange
data VkXmlParseException
= VkXmlParseException
{ exceptCS :: CallStack
, unVkXmlParseException :: Text
}
instance Show VkXmlParseException where
show msg = "VkXmlParseException: " <> T.unpack (unVkXmlParseException msg)
instance Exception VkXmlParseException
type VkXmlParser m =
( MonadReader ParseLoc m
, MonadThrow m
)
parseFailed :: (VkXmlParser m, HasCallStack) => String -> m a
parseFailed msg =
throwM . VkXmlParseException callStack $ T.pack msg
parseWithLoc :: Monad m
=> ParseLoc
-> ConduitM Event o (VkXmlParserT m) r
-> ConduitM EventPos o m r
parseWithLoc initLoc pipe = parseWithLoc' initLoc =$= readLoc initLoc pipe
goDownTree :: (Name, [(Name, [Content])]) -> ParseLoc -> ParseLoc
goDownTree n pl = pl { treePath = n : treePath pl}
goUpTree :: ParseLoc -> ParseLoc
goUpTree pl = pl { treePath = drop 1 $ treePath pl}
updatePos :: Maybe PositionRange -> ParseLoc -> ParseLoc
updatePos pr pl = pl { posRange = pr }
parseWithLoc' :: Monad m => ParseLoc -> Conduit EventPos m (ParseLoc, Event)
parseWithLoc' defLoc
= evalStateC defLoc
$ awaitForever
$ \(mloc, ev) -> do
updatedLoc <- lift $ do
modify' (updatePos mloc)
case ev of
EventBeginElement n attrs -> modify' (goDownTree (n,attrs))
EventEndElement _ -> modify' goUpTree
_ -> return ()
get
yield ( updatedLoc, ev )
| Move location information from upstream to MonadReader environment
readLoc :: Monad m
=> ParseLoc
-> ConduitM Event o (VkXmlParserT m) r
-> ConduitM (ParseLoc, Event) o m r
readLoc defLoc pipe
= evalStateC defLoc
$ awaitForever updateStateAndYield
=$= transPipe (\x -> get >>= lift . runReaderT (runVkXmlParserT x)) pipe
where
updateStateAndYield (l, ev) = lift (put l) >> yield ev
awaitReq :: (VkXmlParser m, HasCallStack) => Consumer Event m Event
awaitReq = await >>= maybe (parseFailed "unexpected end of input") pure
parseTag :: VkXmlParser m
=> Name
-> ReaderT ParseLoc AttrParser b
-> (b -> ConduitM Event o m c)
-> ConduitM Event o m (Maybe c)
parseTag name attrParser pipeF' = do
getAttrs <- runReaderT attrParser <$> ask
tag' (matching (name==)) getAttrs
(\b -> evalStateC (0 :: Int) pipeGuard =$= pipeF' b)
where
pipeGuard = awaitReq >>= \ev -> case ev of
EventBeginElement {} -> do
modify' (+1)
yield ev
pipeGuard
EventEndElement {} -> do
modify' (\x -> x-1)
curNesting <- get
if curNesting < 0
then leftover ev
else do
yield ev
pipeGuard
_ -> yield ev >> pipeGuard
parseTagForceAttrs :: (VkXmlParser m, HasCallStack)
=> Name
-> ReaderT ParseLoc AttrParser b
-> (b -> ConduitM Event o m c)
-> ConduitM Event o m (Maybe c)
parseTagForceAttrs name attrParser pipeF' = do
mr <- parseTag name attrParser pipeF'
case mr of
Just r -> return $ Just r
Nothing -> await >>=
\case
Just ev@(EventBeginElement n attrs)
| n == name -> runAttrParser attrParser attrs
>>= \x -> x `seq` parseFailed
( "failed to parse tag attributes for " <> show ev
)
Just (EventContent c)
| T.null (T.strip (unContent c))
-> parseTagForceAttrs name attrParser pipeF'
Nothing -> return Nothing
Just ev -> leftover ev >> return Nothing
| Use GHC hachery to get
runAttrParser :: (VkXmlParser m, HasCallStack)
=> ReaderT ParseLoc AttrParser a -> [(Name, [Content])] -> m a
runAttrParser p x = do
loc <- ask
let p' = runReaderT p loc
pf :: [(Name, [Content])]
-> Either SomeException ([(Name, [Content])], a)
pf = p' `seq` unsafeCoerce p'
case pf x of
Right ([], r) -> pure r
Right (xs, _) -> parseFailed
$ "some attributes left unhandled: " <> show
( map (\(n, cs) -> T.unpack ( nameLocalName n)
<> " = " <> unwords (map uncontent cs)
) xs )
Left (SomeException e) -> throwM e
where
uncontent = T.unpack . unContent
forceAttr :: HasCallStack => Name -> ReaderT ParseLoc AttrParser Text
forceAttr n = do
mv <- lift (attr n)
case mv of
Nothing -> parseFailed $ "Missing tag attribute " <> show n
Just v -> return v
unContent :: Content -> Text
unContent (ContentText t) = t
unContent (ContentEntity t) = t
decOrHex :: Integral a => T.Reader a
decOrHex t = if "0x" `T.isPrefixOf` t
then T.hexadecimal t
else T.decimal t
|
ec35fb818ced7979b23e9bf28ef32d38d29afed1d7aa7fb916a975476f5cfd90 | lukeg101/lplzoo | Mu.hs | module Mu where
import Data.Map as M
import Data.Set as S
import Control.Monad (guard)
-- Mu, of the form C or 'T -> T' or a mix of both
data T
= TVar Char
| Bottom
| TArr T T
deriving (Eq, Ord)
--equivalence of types compares the binary trees of each type
--we leave strict propositional equality, that is A=A since this language
--adheres to the proofs-as-programs paradigm
-- Simple show instance
instance Show T where
show Bottom = "\x22a5"
show (TVar x) = x:""
show (TArr a b) = paren (isArr a) (show a) ++ "->" ++ show b
paren :: Bool -> String -> String
paren True x = "(" ++ x ++ ")"
paren False x = x
isArr :: T -> Bool
isArr (TArr _ _) = True
isArr _ = False
Lambda Mu Calculus Terms
-- variables are numbers as it's easier for renaming
-- Abstractions carry the type Church style
data MuTerm
= Var Int
| Abs Int T MuTerm
| App MuTerm MuTerm
| Mu Int T MuTerm
| Named Int MuTerm
deriving Ord
Simple show instance for MU has bracketing conventions
instance Show MuTerm where
show (Var x) = show x
show (App t1 t2) =
paren (isAbs t1) (show t1) ++ ' ' : paren (isAbs t2 || isApp t2) (show t2)
show (Abs x t l1) =
"\x03bb" ++ show x ++ ":" ++ show t ++ "." ++ show l1
show (Mu x t l2) = "\x03bc" ++ show x ++ ":" ++ show t ++ "." ++ show l2
show (Named x t) = "[" ++ show x ++ "]" ++ show t
isAbs :: MuTerm -> Bool
isAbs (Abs _ _ _) = True
isAbs _ = False
isApp :: MuTerm -> Bool
isApp (App _ _) = True
isApp _ = False
-- alpha equivalence of terms using syntactic term equality
instance Eq MuTerm where
t1 == t2 = termEquality (t1, t2) (M.empty, M.empty) 0
-- checks for equality of terms, has a map (term, id) for each variable
-- each abstraction adds vars to the map and increments the id
-- also checks that each term is identical
-- variable occurrence checks for ocurrences in t1 and t2 using the logic:
-- if both bound, check that s is same in both maps
-- if neither is bound, check literal equality
-- if bound t1 XOR bound t2 == true then False
application recursively checks both the LHS and RHS
termEquality :: (MuTerm, MuTerm)
-> (Map Int Int, Map Int Int)
-> Int
-> Bool
termEquality (Var x, Var y) (m1, m2) s = case M.lookup x m1 of
Just a -> case M.lookup y m2 of
Just b -> a == b
_ -> False
_ -> x == y
termEquality (Abs x t1 l1, Abs y t2 l2) (m1, m2) s =
t1 == t2 && termEquality (l1, l2) (m1', m2') (s+1)
where
m1' = M.insert x s m1
m2' = M.insert y s m2
termEquality (App a1 b1, App a2 b2) c s =
termEquality (a1, a2) c s && termEquality (b1, b2) c s
termEquality (Mu x t1 l1, Mu y t2 l2) c s =
termEquality (Abs x t1 l1, Abs y t2 l2) c s
-- This is a hack! has same structure as Abs so we reuse the def.
termEquality (Named x l1, Named y l2) c s =
-- another hack
termEquality (Var x, Var y) c s && termEquality (l1,l2) c s
termEquality _ _ _ = False
-- Type context for t:T is Map v T where v is a variable name and T is it's supplied Type
type Context = M.Map Int T
-- typing derivation for a term in a given context
-- Just T denotes successful type derivation
-- Nothing denotes failure to type the term (not in \->)
typeof :: MuTerm -> Context -> Maybe T
typeof (Var v) ctx = M.lookup v ctx
typeof l@(Abs x t l1) ctx = do
t' <- typeof l1 (M.insert x t ctx)
return $ TArr t t'
typeof l@(App l1 l2) ctx = do
t1 <- typeof l2 ctx
case typeof l1 ctx of
Just (TArr t2 t3) -> if t1 == t2 then return t3 else Nothing
_ -> Nothing
typeof l@(Mu x t l2) ctx = do
guard (t /= Bottom)
t' <- typeof l2 (M.insert x t ctx)
guard (t' == Bottom)
Just t
typeof l@(Named x l2) ctx = do
t1 <- M.lookup x ctx
t2 <- typeof l2 ctx
guard(t1 == t2)
Just Bottom
-- top level typing function providing empty context
typeof' l = typeof l M.empty
--bound variables of a term
bound :: MuTerm -> Set Int
bound (Var n) = S.empty
bound (Abs n t l1) = S.insert n $ bound l1
bound (App l1 l2) = S.union (bound l1) (bound l2)
bound (Mu x t l2) = bound l2
bound (Named x l2) = bound l2
--free variables of a term
free :: MuTerm -> Set Int
free (Var n) = S.singleton n
free (Abs n t l1) = S.delete n (free l1)
free (App l1 l2) = S.union (free l1) (free l2)
free (Mu x t l2) = free l2
free (Named x l2) = free l2
--test to see if a term is closed (has no free vars)
closed :: MuTerm -> Bool
closed = S.null . free
--subterms of a term
sub :: MuTerm -> Set MuTerm
sub l@(Var x) = S.singleton l
sub l@(Abs c t l1) = S.insert l $ sub l1
sub l@(App l1 l2) = S.insert l $ S.union (sub l1) (sub l2)
sub l@(Mu x t l2) = S.insert l $ sub l2
sub l@(Named x l2) = S.insert l $ sub l2
--element is bound in a term
notfree :: Int -> MuTerm -> Bool
notfree x = not . S.member x . free
--set of variables in a term
vars :: MuTerm -> Set Int
vars (Var x) = S.singleton x
vars (App t1 t2) = S.union (vars t1) (vars t2)
vars (Abs x t l1) = S.insert x $ vars l1
vars (Mu x t l2) = vars l2
vars (Named x l2) = vars l2
--generates a fresh variable name for a term
newlabel :: MuTerm -> Int
newlabel = (+1) . maximum . vars
--rename t (x,y): renames free occurences of x in t to y
rename :: MuTerm -> (Int, Int) -> MuTerm
rename (Var a) (x,y) = if a == x then Var y else Var a
rename l@(Abs a t l1) (x,y) = if a == x then l else Abs a t $ rename l1 (x, y)
rename (App l1 l2) (x,y) = App (rename l1 (x,y)) (rename l2 (x,y))
-- renames named terms only
renameNamed :: MuTerm -> (Int, Int) -> MuTerm
renameNamed l@(Var x) _ = l
renameNamed (Abs x t l2) c = Abs x t (renameNamed l2 c)
renameNamed (App l1 l2) c = App (renameNamed l1 c) (renameNamed l2 c)
renameNamed (Mu x t l1) c@(z,y)
= Mu x t $ if x == z then l1 else (renameNamed l1 c)
renameNamed (Named x t) c@(z,y)
| x == z = Named y (renameNamed t c)
| otherwise = Named x (renameNamed t c)
substitute one lambda term for another in a term
--does capture avoiding substitution
substitute :: MuTerm -> (MuTerm, MuTerm) -> MuTerm
substitute l1@(Var c1) (Var c2, l2)
= if c1 == c2 then l2 else l1
substitute (App l1 l2) c
= App (substitute l1 c) (substitute l2 c)
substitute (Abs y t l1) c@(Var x, l2)
| y == x = Abs y t l1
| y `notfree` l2 = Abs y t $ substitute l1 c
| otherwise = Abs z t $ substitute (rename l1 (y,z)) c
where z = max (newlabel l1) (newlabel l2)
substitute (Mu x t l2) c = Mu x t $ substitute l2 c
substitute (Named x l2) c = Named x $ substitute l2 c
one - step reduction relation
reduce1 :: MuTerm -> Maybe MuTerm
reduce1 l@(Var x) = Nothing
reduce1 l@(Abs x t s) = do
s' <- reduce1 s
return $ Abs x t s'
reduce1 l@(App (Abs x t l1) l2)
= Just $ substitute l1 (Var x, l2) --beta conversion
reduce1 (App l1 l2) = do case reduce1 l1 of
Just l1' -> Just (App l1' l2)
_ -> do {l2' <- reduce1 l2; Just $ App l1 l2'}
reduce1 l@(Named a (Mu b t l2))
= Just $ renameNamed l2 (b,a)
reduce1 t = Nothing
-- multi-step reduction relation
-- NOT GUARANTEED TO TERMINATE IF typeof' FAILS
reduce :: MuTerm -> MuTerm
reduce t = case reduce1 t of
Just t' -> reduce t'
Nothing -> t
--- multi-step reduction relation that accumulates all reduction steps
-- NOT GUARANTEED TO TERMINATE IF typeof' FAILS
reductions :: MuTerm -> [MuTerm]
reductions t = case reduce1 t of
Just t' -> t' : reductions t'
_ -> []
--common combinators
pierce = Abs 0 (TArr (TArr (TVar 'A') (TVar 'B')) (TVar 'A')) $
Mu 1 (TVar 'A') $ Named 1 $ App (Var 0) $ Abs 2 (TVar 'A') $
Mu 3 (TVar 'B') $ Named 1 (Var 2) --from the paper
TODO Examples - exercise for the reader ;)
i = Abs 1 ( TArr TVar TVar ) ( Var 1 )
true = Abs 1 TVar ( Abs 2 TVar ( Var 1 ) )
false = Abs 1 TVar ( Abs 2 TVar ( Var 2 ) )
zero = false
xx = Abs 1 ( TArr TVar TVar ) ( App ( Var 1 ) ( Var 1 ) ) --won't type check as expected
omega = App xx xx --won't type check , see above
_ if = t f - > App ( App c t ) f
_ isZero = \n - > _ if n false true
-- Haskell Int to Simply Typed Church Numeral
toChurch : : Int - > MuTerm
toChurch n = Abs 0 ( TArr TVar TVar)(Abs 1 TVar ( toChurch ' n ) )
where
toChurch ' 0 = Var 1
toChurch ' n = App ( Var 0 ) ( toChurch ' ( n-1 ) )
-- test cases
test1 = Abs 1 ( TArr TVar TVar ) $ Abs 2 TVar $ App ( Var 1 ) ( Var 2 ) -- \f x. f x
test2 = Abs 1 ( TArr TVar TVar ) $ Abs 2 TVar $ App ( App ( Var 1 ) ( Var 2 ) ) ( Var 1 ) -- \f x. ( f x ) f
test3 = App i ( Abs 1 ( TArr TVar TVar ) ( App ( Var 1 ) ( Var 1 ) ) ) -- i xx
test4 = App ( App ( Abs 1 TVar ( Abs 2 TVar ( Var 2 ) ) ) ( Var 2 ) ) ( Var 4 )
TODO Examples - exercise for the reader ;)
i = Abs 1 (TArr TVar TVar) (Var 1)
true = Abs 1 TVar (Abs 2 TVar (Var 1))
false = Abs 1 TVar (Abs 2 TVar (Var 2))
zero = false
xx = Abs 1 (TArr TVar TVar) (App (Var 1) (Var 1)) --won't type check as expected
omega = App xx xx --won't type check, see above
_if = \c t f -> App (App c t) f
_isZero = \n -> _if n false true
-- Haskell Int to Simply Typed Church Numeral
toChurch :: Int -> MuTerm
toChurch n = Abs 0 (TArr TVar TVar)(Abs 1 TVar (toChurch' n))
where
toChurch' 0 = Var 1
toChurch' n = App (Var 0) (toChurch' (n-1))
-- test cases
test1 = Abs 1 (TArr TVar TVar) $ Abs 2 TVar $ App (Var 1) (Var 2) -- \f x. f x
test2 = Abs 1 (TArr TVar TVar) $ Abs 2 TVar $ App (App (Var 1) (Var 2)) (Var 1) -- \f x. (f x) f
test3 = App i (Abs 1 (TArr TVar TVar) (App (Var 1) (Var 1))) -- i xx
test4 = App (App (Abs 1 TVar (Abs 2 TVar (Var 2))) (Var 2)) (Var 4)
-}
| null | https://raw.githubusercontent.com/lukeg101/lplzoo/463ca93f22f018ee07bdc18d84b3b0c966d51766/Mu/Mu.hs | haskell | Mu, of the form C or 'T -> T' or a mix of both
equivalence of types compares the binary trees of each type
we leave strict propositional equality, that is A=A since this language
adheres to the proofs-as-programs paradigm
Simple show instance
variables are numbers as it's easier for renaming
Abstractions carry the type Church style
alpha equivalence of terms using syntactic term equality
checks for equality of terms, has a map (term, id) for each variable
each abstraction adds vars to the map and increments the id
also checks that each term is identical
variable occurrence checks for ocurrences in t1 and t2 using the logic:
if both bound, check that s is same in both maps
if neither is bound, check literal equality
if bound t1 XOR bound t2 == true then False
This is a hack! has same structure as Abs so we reuse the def.
another hack
Type context for t:T is Map v T where v is a variable name and T is it's supplied Type
typing derivation for a term in a given context
Just T denotes successful type derivation
Nothing denotes failure to type the term (not in \->)
top level typing function providing empty context
bound variables of a term
free variables of a term
test to see if a term is closed (has no free vars)
subterms of a term
element is bound in a term
set of variables in a term
generates a fresh variable name for a term
rename t (x,y): renames free occurences of x in t to y
renames named terms only
does capture avoiding substitution
beta conversion
multi-step reduction relation
NOT GUARANTEED TO TERMINATE IF typeof' FAILS
- multi-step reduction relation that accumulates all reduction steps
NOT GUARANTEED TO TERMINATE IF typeof' FAILS
common combinators
from the paper
won't type check as expected
won't type check , see above
Haskell Int to Simply Typed Church Numeral
test cases
\f x. f x
\f x. ( f x ) f
i xx
won't type check as expected
won't type check, see above
Haskell Int to Simply Typed Church Numeral
test cases
\f x. f x
\f x. (f x) f
i xx | module Mu where
import Data.Map as M
import Data.Set as S
import Control.Monad (guard)
data T
= TVar Char
| Bottom
| TArr T T
deriving (Eq, Ord)
instance Show T where
show Bottom = "\x22a5"
show (TVar x) = x:""
show (TArr a b) = paren (isArr a) (show a) ++ "->" ++ show b
paren :: Bool -> String -> String
paren True x = "(" ++ x ++ ")"
paren False x = x
isArr :: T -> Bool
isArr (TArr _ _) = True
isArr _ = False
Lambda Mu Calculus Terms
data MuTerm
= Var Int
| Abs Int T MuTerm
| App MuTerm MuTerm
| Mu Int T MuTerm
| Named Int MuTerm
deriving Ord
Simple show instance for MU has bracketing conventions
instance Show MuTerm where
show (Var x) = show x
show (App t1 t2) =
paren (isAbs t1) (show t1) ++ ' ' : paren (isAbs t2 || isApp t2) (show t2)
show (Abs x t l1) =
"\x03bb" ++ show x ++ ":" ++ show t ++ "." ++ show l1
show (Mu x t l2) = "\x03bc" ++ show x ++ ":" ++ show t ++ "." ++ show l2
show (Named x t) = "[" ++ show x ++ "]" ++ show t
isAbs :: MuTerm -> Bool
isAbs (Abs _ _ _) = True
isAbs _ = False
isApp :: MuTerm -> Bool
isApp (App _ _) = True
isApp _ = False
instance Eq MuTerm where
t1 == t2 = termEquality (t1, t2) (M.empty, M.empty) 0
application recursively checks both the LHS and RHS
termEquality :: (MuTerm, MuTerm)
-> (Map Int Int, Map Int Int)
-> Int
-> Bool
termEquality (Var x, Var y) (m1, m2) s = case M.lookup x m1 of
Just a -> case M.lookup y m2 of
Just b -> a == b
_ -> False
_ -> x == y
termEquality (Abs x t1 l1, Abs y t2 l2) (m1, m2) s =
t1 == t2 && termEquality (l1, l2) (m1', m2') (s+1)
where
m1' = M.insert x s m1
m2' = M.insert y s m2
termEquality (App a1 b1, App a2 b2) c s =
termEquality (a1, a2) c s && termEquality (b1, b2) c s
termEquality (Mu x t1 l1, Mu y t2 l2) c s =
termEquality (Abs x t1 l1, Abs y t2 l2) c s
termEquality (Named x l1, Named y l2) c s =
termEquality (Var x, Var y) c s && termEquality (l1,l2) c s
termEquality _ _ _ = False
type Context = M.Map Int T
typeof :: MuTerm -> Context -> Maybe T
typeof (Var v) ctx = M.lookup v ctx
typeof l@(Abs x t l1) ctx = do
t' <- typeof l1 (M.insert x t ctx)
return $ TArr t t'
typeof l@(App l1 l2) ctx = do
t1 <- typeof l2 ctx
case typeof l1 ctx of
Just (TArr t2 t3) -> if t1 == t2 then return t3 else Nothing
_ -> Nothing
typeof l@(Mu x t l2) ctx = do
guard (t /= Bottom)
t' <- typeof l2 (M.insert x t ctx)
guard (t' == Bottom)
Just t
typeof l@(Named x l2) ctx = do
t1 <- M.lookup x ctx
t2 <- typeof l2 ctx
guard(t1 == t2)
Just Bottom
typeof' l = typeof l M.empty
bound :: MuTerm -> Set Int
bound (Var n) = S.empty
bound (Abs n t l1) = S.insert n $ bound l1
bound (App l1 l2) = S.union (bound l1) (bound l2)
bound (Mu x t l2) = bound l2
bound (Named x l2) = bound l2
free :: MuTerm -> Set Int
free (Var n) = S.singleton n
free (Abs n t l1) = S.delete n (free l1)
free (App l1 l2) = S.union (free l1) (free l2)
free (Mu x t l2) = free l2
free (Named x l2) = free l2
closed :: MuTerm -> Bool
closed = S.null . free
sub :: MuTerm -> Set MuTerm
sub l@(Var x) = S.singleton l
sub l@(Abs c t l1) = S.insert l $ sub l1
sub l@(App l1 l2) = S.insert l $ S.union (sub l1) (sub l2)
sub l@(Mu x t l2) = S.insert l $ sub l2
sub l@(Named x l2) = S.insert l $ sub l2
notfree :: Int -> MuTerm -> Bool
notfree x = not . S.member x . free
vars :: MuTerm -> Set Int
vars (Var x) = S.singleton x
vars (App t1 t2) = S.union (vars t1) (vars t2)
vars (Abs x t l1) = S.insert x $ vars l1
vars (Mu x t l2) = vars l2
vars (Named x l2) = vars l2
newlabel :: MuTerm -> Int
newlabel = (+1) . maximum . vars
rename :: MuTerm -> (Int, Int) -> MuTerm
rename (Var a) (x,y) = if a == x then Var y else Var a
rename l@(Abs a t l1) (x,y) = if a == x then l else Abs a t $ rename l1 (x, y)
rename (App l1 l2) (x,y) = App (rename l1 (x,y)) (rename l2 (x,y))
renameNamed :: MuTerm -> (Int, Int) -> MuTerm
renameNamed l@(Var x) _ = l
renameNamed (Abs x t l2) c = Abs x t (renameNamed l2 c)
renameNamed (App l1 l2) c = App (renameNamed l1 c) (renameNamed l2 c)
renameNamed (Mu x t l1) c@(z,y)
= Mu x t $ if x == z then l1 else (renameNamed l1 c)
renameNamed (Named x t) c@(z,y)
| x == z = Named y (renameNamed t c)
| otherwise = Named x (renameNamed t c)
substitute one lambda term for another in a term
substitute :: MuTerm -> (MuTerm, MuTerm) -> MuTerm
substitute l1@(Var c1) (Var c2, l2)
= if c1 == c2 then l2 else l1
substitute (App l1 l2) c
= App (substitute l1 c) (substitute l2 c)
substitute (Abs y t l1) c@(Var x, l2)
| y == x = Abs y t l1
| y `notfree` l2 = Abs y t $ substitute l1 c
| otherwise = Abs z t $ substitute (rename l1 (y,z)) c
where z = max (newlabel l1) (newlabel l2)
substitute (Mu x t l2) c = Mu x t $ substitute l2 c
substitute (Named x l2) c = Named x $ substitute l2 c
one - step reduction relation
reduce1 :: MuTerm -> Maybe MuTerm
reduce1 l@(Var x) = Nothing
reduce1 l@(Abs x t s) = do
s' <- reduce1 s
return $ Abs x t s'
reduce1 l@(App (Abs x t l1) l2)
reduce1 (App l1 l2) = do case reduce1 l1 of
Just l1' -> Just (App l1' l2)
_ -> do {l2' <- reduce1 l2; Just $ App l1 l2'}
reduce1 l@(Named a (Mu b t l2))
= Just $ renameNamed l2 (b,a)
reduce1 t = Nothing
reduce :: MuTerm -> MuTerm
reduce t = case reduce1 t of
Just t' -> reduce t'
Nothing -> t
reductions :: MuTerm -> [MuTerm]
reductions t = case reduce1 t of
Just t' -> t' : reductions t'
_ -> []
pierce = Abs 0 (TArr (TArr (TVar 'A') (TVar 'B')) (TVar 'A')) $
Mu 1 (TVar 'A') $ Named 1 $ App (Var 0) $ Abs 2 (TVar 'A') $
TODO Examples - exercise for the reader ;)
i = Abs 1 ( TArr TVar TVar ) ( Var 1 )
true = Abs 1 TVar ( Abs 2 TVar ( Var 1 ) )
false = Abs 1 TVar ( Abs 2 TVar ( Var 2 ) )
zero = false
_ if = t f - > App ( App c t ) f
_ isZero = \n - > _ if n false true
toChurch : : Int - > MuTerm
toChurch n = Abs 0 ( TArr TVar TVar)(Abs 1 TVar ( toChurch ' n ) )
where
toChurch ' 0 = Var 1
toChurch ' n = App ( Var 0 ) ( toChurch ' ( n-1 ) )
test4 = App ( App ( Abs 1 TVar ( Abs 2 TVar ( Var 2 ) ) ) ( Var 2 ) ) ( Var 4 )
TODO Examples - exercise for the reader ;)
i = Abs 1 (TArr TVar TVar) (Var 1)
true = Abs 1 TVar (Abs 2 TVar (Var 1))
false = Abs 1 TVar (Abs 2 TVar (Var 2))
zero = false
_if = \c t f -> App (App c t) f
_isZero = \n -> _if n false true
toChurch :: Int -> MuTerm
toChurch n = Abs 0 (TArr TVar TVar)(Abs 1 TVar (toChurch' n))
where
toChurch' 0 = Var 1
toChurch' n = App (Var 0) (toChurch' (n-1))
test4 = App (App (Abs 1 TVar (Abs 2 TVar (Var 2))) (Var 2)) (Var 4)
-}
|
5fb2b8ea457232c126c85c1b4e1c83e95ea49c948e87c04ba741912044a3eda6 | typelead/intellij-eta | Layout00004.hs | module Layout00004 where
f x = x
where start = SrcLoc {
srcFilename = parseFilename mode,
srcLine = 1
} | null | https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/test/resources/fixtures/eta/sources/Layout00004.hs | haskell | module Layout00004 where
f x = x
where start = SrcLoc {
srcFilename = parseFilename mode,
srcLine = 1
} |
|
375897fc0ade9afc0c3f50545ae95ef6e5a1d6bdae37712fd4da571cbfb213a7 | xxyzz/SICP | Exercise_2_21.rkt | #lang racket/base
(define (square x) (* x x))
(define (square-list items)
(if (null? items)
null
(cons (square (car itmes)) (square-list (cdr itmes)))))
(define (square-list items)
(map square items))
(square-list (list 1 2 3 4))
; '(1 4 9 16)
| null | https://raw.githubusercontent.com/xxyzz/SICP/e26aea1c58fd896297dbf5406f7fcd32bb4f8f78/2_Building_Abstractions_with_Data/2.2_Hierarchical_Data_and_the_Closure_Property/Exercise_2_21.rkt | racket | '(1 4 9 16) | #lang racket/base
(define (square x) (* x x))
(define (square-list items)
(if (null? items)
null
(cons (square (car itmes)) (square-list (cdr itmes)))))
(define (square-list items)
(map square items))
(square-list (list 1 2 3 4))
|
e432d560b4e9e2a88ee52e749ef03f99e8cf3f4c9edb0093d082136728d66620 | SoftwareFoundationGroupAtKyotoU/VeriCUDA | vctrans.ml |
# use " topfind " ; ;
# directory " /home / kozima/.opam/4.01.0 / lib / menhirLib " ; ;
# load " menhirLib.cmo " ; ;
# require " why3 " ; ;
# require " cil " ; ;
#use "topfind";;
#directory "/home/kozima/.opam/4.01.0/lib/menhirLib";;
#load "menhirLib.cmo";;
#require "why3";;
#require "cil";;
*)
open Why3.Term
open Why3api
open Formula
open Vc
open Utils
open ExtList
module I = Why3.BigInt
open Why3util
open Why3util.PTerm
* ---------------- Decompose quantifications over thread
let t_is_valid_tid_inline t =
let zero = t_zero in
t_and_simp_l [
t_le zero (t_x t); t_le zero (t_y t); t_le zero (t_z t);
t_lt (t_x t) t_bdimx; t_lt (t_y t) t_bdimy; t_lt (t_z t) t_bdimz;
]
let t_is_valid_bid_inline t =
let zero = t_zero in
t_and_simp_l [
t_le zero (t_x t); t_le zero (t_y t); t_le zero (t_z t);
t_lt (t_x t) t_gdimx; t_lt (t_y t) t_gdimy; t_lt (t_z t) t_gdimz;
]
let rec inline_is_valid_thread t =
match t.t_node with
| Tapp (ls, [t']) when ls_equal ls ps_is_valid_thread ->
begin
match t'.t_node with
| Tapp (ls, [t1; t2]) when ls_equal ls (fs_tuple 2) ->
t_and_simp (t_is_valid_bid_inline t1) (t_is_valid_tid_inline t2)
| _ ->
TermTF.t_map_simp (fun t -> t) inline_is_valid_thread t
end
| _ ->
TermTF.t_map_simp (fun t -> t) inline_is_valid_thread t
let decomposing_quant q vss body =
let rec rewrite_body vss acc_vs body =
match vss with
| [] -> acc_vs, body
| vs::vss' ->
if Why3.Ty.ty_equal vs.vs_ty ty_thread then
let bx = create_vsymbol (Why3.Ident.id_fresh "b_x") ty_int in
let by = create_vsymbol (Why3.Ident.id_fresh "b_y") ty_int in
let bz = create_vsymbol (Why3.Ident.id_fresh "b_z") ty_int in
let tx = create_vsymbol (Why3.Ident.id_fresh "t_x") ty_int in
let ty = create_vsymbol (Why3.Ident.id_fresh "t_y") ty_int in
let tz = create_vsymbol (Why3.Ident.id_fresh "t_z") ty_int in
let th = t_tuple [t_dim3 (t_var bx) (t_var by) (t_var bz);
t_dim3 (t_var tx) (t_var ty) (t_var tz)]
in
t_subst_single vs th body
|> inline_is_valid_thread
|> compute_thread_projections
|> simplify_formula
|> simplify_dim3_equality
|> rewrite_body vss' (bx :: tx :: by :: ty :: bz :: tz :: acc_vs)
else if Why3.Ty.ty_equal vs.vs_ty ty_dim3 then
let x = create_vsymbol (Why3.Ident.id_fresh "d_x") ty_int in
let y = create_vsymbol (Why3.Ident.id_fresh "d_y") ty_int in
let z = create_vsymbol (Why3.Ident.id_fresh "d_z") ty_int in
let d = t_dim3 (t_var x) (t_var y) (t_var z) in
t_subst_single vs d body
|> inline_is_valid_thread
|> compute_thread_projections
|> simplify_formula
|> simplify_dim3_equality
|> rewrite_body vss' (x :: y :: z :: acc_vs)
else
rewrite_body vss' (vs :: acc_vs) body
in
let (vss, body) = rewrite_body vss [] body in
t_quant_close_simp q vss [] body
let rec decompose_thread_quant t =
match t.t_node with
| Tquant (q, tq) ->
let (vss, tr, body) = t_open_quant tq in
(* decompose only when there is no trigger *)
if tr = [] &&
List.exists (fun vs ->
Why3.Ty.ty_equal vs.vs_ty ty_thread
|| Why3.Ty.ty_equal vs.vs_ty ty_dim3) vss then
decomposing_quant q vss @@ decompose_thread_quant body
else
TermTF.t_map_simp (fun t -> t) decompose_thread_quant t
| _ -> TermTF.t_map_simp (fun t -> t) decompose_thread_quant t
(** ---------------- eliminating quantifiers *)
maybe optimizable using a method similar to
* why3 - 0.85 / src / transform / simplify_formula.ml ,
* find the value [ s ] , substitute to [ vs ] in the whole formula ,
* and then simplify it modulo ring equality using polynomial repr . above .
* why3-0.85/src/transform/simplify_formula.ml,
* find the value [s], substitute to [vs] in the whole formula,
* and then simplify it modulo ring equality using polynomial repr. above. *)
let rec eliminate_unique_quant_1 bvars sign vs t =
(* Try to find the value of [vs] if it is unique in [t].
* If the value is found, returns a pair [t'] and [Some s]
* where [s] is the value, and [t'] is [t(vs:=s)]. *)
match t.t_node with
| Tapp (ls, [t1; t2])
when sign && ls_equal ls ps_equ && is_int t1 &&
Mvs.set_disjoint (t_vars t) bvars ->
begin
match isolate_var (t_var vs)
(p_sub (to_polynomial t1) (to_polynomial t2))
with
| None -> (t, None)
| Some (p, _) when t_v_occurs vs (from_polynomial p) > 0 -> (t, None)
| Some (p, s) ->
(* t1 - t2 = s * x + p (= 0)
* ==> x = -s * p *)
let p' = if s = 1 then (p_neg p) else p in
(t_true, Some (from_polynomial p'))
end
| Tbinop (Tor, t1, t2) when not sign ->
let (t1', r1) = eliminate_unique_quant_1 bvars sign vs t1 in
begin
match r1 with
| None ->
assert (t_equal t1 t1');
let (t2', r2) = eliminate_unique_quant_1 bvars sign vs t2 in
begin
match r2 with
| None ->
assert (t_equal t2 t2');
(t, None)
| Some s -> (t_or_simp (t_subst_single vs s t1) t2', r2)
end
| Some s ->
(t_or_simp t1' (t_subst_single vs s t2), r1)
end
| Tbinop (Tand, t1, t2) when sign ->
let (t1', r1) = eliminate_unique_quant_1 bvars sign vs t1 in
begin
match r1 with
| None ->
assert (t_equal t1 t1');
let (t2', r2) = eliminate_unique_quant_1 bvars sign vs t2 in
begin
match r2 with
| None ->
assert (t_equal t2 t2');
(t, None)
| Some s ->
(t_and_simp (t_subst_single vs s t1) t2', r2)
end
| Some s ->
(t_and_simp t1' (t_subst_single vs s t2), r1)
end
| Tbinop (Timplies, t1, t2) when not sign ->
let (t1', r1) = eliminate_unique_quant_1 bvars (not sign) vs t1 in
begin
match r1 with
| None ->
assert (t_equal t1 t1');
let (t2', r2) = eliminate_unique_quant_1 bvars sign vs t2 in
begin
match r2 with
| None ->
assert (t_equal t2 t2');
(t, None)
| Some s ->
(t_implies_simp (t_subst_single vs s t1) t2', r2)
end
| Some s ->
(t_implies_simp t1' (t_subst_single vs s t2), r1)
end
| Tnot t' ->
let (t'', r) = eliminate_unique_quant_1 bvars (not sign) vs t' in
t_not_simp t'', r
| Tquant (q, tq) ->
let (vsyms, triggers, body, cb) = t_open_quant_cb tq in
let bvars' = List.fold_left (fun bvs v -> Mvs.add v 1 bvs) bvars vsyms in
let (t', r) = eliminate_unique_quant_1 bvars' sign vs body in
t_quant q (cb vsyms triggers t'), r
| _ -> (t, None)
let rec eliminate_unique_quant t =
match t.t_node with
| Tquant (q, tq) ->
begin
match t_open_quant tq with
| (vss, [], body) ->
let sign = match q with Tforall -> false | Texists -> true in
let rec elim vss vss_rem t =
match vss with
| [] -> t_quant_close_simp q vss_rem [] t
| vs :: vss' ->
let (t', r) = eliminate_unique_quant_1 Mvs.empty sign vs t in
match r with
| None ->
assert (t_equal t t');
elim vss' (vs :: vss_rem) t'
| Some _ ->
elim vss' vss_rem t'
in elim vss [] @@ eliminate_unique_quant body
| (vsyms, triggers, body) ->
t_quant_close q vsyms triggers (eliminate_unique_quant body)
end
| _ -> TermTF.t_map_simp (fun t -> t) eliminate_unique_quant t
(** ---------------- merging quantifiers *)
Try to find a subformula equivalent to either
* forall x y. 0 < = x < a - > 0 < = y < b - > P ( x + a * y )
* exists x y. 0 < = x < a /\ 0 < = y < b /\ P ( x + a * y )
* and replace it with
* a < = 0 \/ b < = 0 \/ forall z. 0 < = z < a * b - > P z
* a > 0 /\ b > 0 /\ exists 0 < = z < a * b /\ P z
* respectively .
* forall x y. 0 <= x < a -> 0 <= y < b -> P (x + a * y)
* exists x y. 0 <= x < a /\ 0 <= y < b /\ P (x + a * y)
* and replace it with
* a <= 0 \/ b <= 0 \/ forall z. 0 <= z < a * b -> P z
* a > 0 /\ b > 0 /\ exists z. 0 <= z < a * b /\ P z
* respectively. *)
(* A (node of a) term is said to be a polynomial node if
* - it is of type int, and
* - it is either variable, integer constant or an application whose
* operator is one of the ring operations. *)
let is_polynomial_node t =
match t.t_node with
| Tvar vs -> Why3.Ty.ty_equal vs.vs_ty ty_int
| Tconst (Why3.Number.ConstInt _) -> true
| Tapp (ls, _) ->
ls_equal ls fs_plus
|| ls_equal ls fs_minus
|| ls_equal ls fs_mult
|| ls_equal ls fs_uminus
| _ -> false
(* We call a subterm [p] of [t] a prime polynomial node if
* - [p] is a polynomial node, and
* -- either [p = t], or
* -- the parent node of [p] is not a polynomial node. *)
exception CannotReduceVariables
let really_process_polynomial x a y z t =
(* [t] is a prime polynomial node of the formula in question. *)
let p = to_polynomial t in
Given p(a , x , y ) , a polynomial in a , x , and y , returns a
* polynomial g(a , z ) such that g(a , x + a * y ) = p(a , x , y ) . If
* there is no such f , returns [ None ] .
* Lemma : p(a , x , y ) is written in the form g(a , x + a * y )
* if and only if p(a , x , y ) = p(a , x + a * y , 0 ) .
* In this case g can be taken as g(a , z ) = p(a , z , 0 ) .
* polynomial g(a, z) such that g(a, x + a * y) = p(a, x, y). If
* there is no such f, returns [None].
* Lemma: p(a, x, y) is written in the form g(a, x + a * y)
* if and only if p(a, x, y) = p(a, x + a * y, 0).
* In this case g can be taken as g(a, z) = p(a, z, 0). *)
let p_a = to_polynomial a in
let p_x = to_polynomial x in
let p_y = to_polynomial y in
if p_equal p (p_subst x (p_add p_x (p_mult p_a p_y))
(p_subst y p_zero p))
then from_polynomial @@ p_subst x (p_var z) (p_subst y p_zero p)
else raise CannotReduceVariables
let process_polynomial x a y z t =
let rec f p t =
(* Apply [really_process_polynomial] to every prime polynomial
* node of [t]. Parameter [p] is true iff the parent of the
* argument [t] is a polynomial (in particular [t] is not a root). *)
if is_polynomial_node t then
let t' = t_map_simp (f true) t in
if p then t' else really_process_polynomial x a y z t'
else t_map_simp (f false) t
in f false t
let rec try_reduce_vars x a y z t =
match t.t_node with
| Tvar _ -> if t_equal t x || t_equal t y
then raise CannotReduceVariables
else t
| Tapp (ls, [t1; t2]) when is_int t1 && is_cmp_op ls ->
let t' = process_polynomial x a y z (t_minus t1 t2) in
t_app ls [t'; t_zero] None
| Tapp (ls, ts) ->
if is_formula t then t_map_simp (try_reduce_vars x a y z) t
else process_polynomial x a y z t
| _ ->
t_map_simp (try_reduce_vars x a y z) t
let reduce_variables q vs1 bound1 vs2 bound2 t =
assert (is_formula t);
let new_vs = create_vsymbol (Why3.Ident.id_fresh "z") ty_int in
let v1 = t_var vs1 in
let v2 = t_var vs2 in
let v = t_var new_vs in
try
let t' = try_reduce_vars v1 bound1 v2 v t in new_vs, t'
with CannotReduceVariables ->
let t' = try_reduce_vars v2 bound2 v1 v t in new_vs, t'
let check_lower_bound q v t =
(* Returns [t'] such that
* when [q] is [Texists], [t] iff [0 <= v /\ t'], and
* when [q] is [Tforall], [t] iff [0 <= v -> t'].
*
* This function actually finds a subformula equivalent to [0 <= v]
* in appropriate positions, and replaces such subformulas with [true].
*)
let check_cmp pos ls t1 t2 =
let p = p_sub (to_polynomial t1) (to_polynomial t2) in
match isolate_var v p with
| Some (q, 1) ->
(* p = x + q, therefore [x <ls> -q]. *)
if pos then
(* is [x <ls> -q] equivalent to [x >= 0]? *)
ls_equal ls ps_ge && p_equal q p_zero
|| ls_equal ls ps_gt && p_equal q (p_int 1)
else
(* is [x <ls> -q] equivalent to [x < 0]? *)
ls_equal ls ps_le && p_equal q (p_int 1)
|| ls_equal ls ps_lt && p_equal q p_zero
| Some (q, s) ->
assert (s = -1);
(* p = -x + q, therefore [q <ls> x]. *)
if pos then
(* is [q <ls> x] equivalent to [x >= 0]? *)
ls_equal ls ps_le && p_equal q p_zero
|| ls_equal ls ps_lt && p_equal q (p_int (-1))
else
(* is [q <ls> x] equivalent to [x < 0]? *)
ls_equal ls ps_ge && p_equal q (p_int (-1))
|| ls_equal ls ps_gt && p_equal q p_zero
| None -> false
in
let rec check pos t =
match t.t_node with
| Tapp (ls, [t1; t2]) when is_int t1 && is_cmp_op ls ->
check_cmp pos ls t1 t2
| Tbinop (Tand, t1, t2) ->
if pos then
(* does [t1 /\ t2] imply [0 < v]? *)
check pos t1 || check pos t2
else
(* does [v < 0] imply [t1 /\ t2]? *)
check pos t1 && check pos t2
| Tbinop (Tor, t1, t2) ->
if pos then
check pos t1 && check pos t2
else
check pos t1 || check pos t2
| Tbinop (Timplies, t1, t2) ->
if pos then
check (not pos) t1 && check pos t2
else
check (not pos) t1 || check pos t2
| Tbinop (Tiff, t1, t2) ->
check pos (t_and (t_implies t1 t2) (t_implies t2 t1))
| Tnot t' ->
check (not pos) t'
| Tquant (q, tq) ->
(* Here we are assuming that the domain of quantification
* is always non-empty. *)
let (_, _, t') = t_open_quant tq in
check pos t'
| _ ->
(* Ignore let, case, eps, etc. *)
false
in check (q = Texists) t
let find_upper_bounds q v t =
(* Returns the set of [u]'s such that:
* when [q] is [Texists], [t] implies [v < u], and
* when [q] is [Tforall], [t] is implied by [v >= u].
*)
let rec find pos t =
match t.t_node with
| Tapp (ls, [t1; t2]) when is_int t1 && is_cmp_op ls ->
let p = p_sub (to_polynomial t1) (to_polynomial t2) in
begin
match isolate_var v p with
| Some (q, 1) ->
if pos then (* want: [v < u] for some u *)
(* p = v + q, therefore [x <ls> -q]. *)
if ls_equal ls ps_le then
(* v <= -q, hence v < -q + 1 *)
Sterm.singleton (from_polynomial (p_add (p_int 1) (p_neg q)))
else if ls_equal ls ps_lt then
(* v < -q *)
Sterm.singleton (from_polynomial (p_neg q))
else
Sterm.empty
else (* want: [v >= u] for some u *)
if ls_equal ls ps_ge then
(* v >= -q *)
Sterm.singleton (from_polynomial (p_neg q))
else if ls_equal ls ps_gt then
(* v > -q, hence v >= -q + 1 *)
Sterm.singleton (from_polynomial (p_add (p_int 1) (p_neg q)))
else
Sterm.empty
| Some (q, s) ->
assert (s = -1);
if pos then (* want: [v < u] for some u *)
(* p = -v + q, therefore [q <ls> v]. *)
if ls_equal ls ps_ge then
(* q >= v, hence v < q + 1 *)
Sterm.singleton (from_polynomial (p_add (p_int 1) q))
else if ls_equal ls ps_gt then
(* q > v *)
Sterm.singleton (from_polynomial q)
else
Sterm.empty
else (* want: [v >= u] for some u *)
if ls_equal ls ps_le then
(* q <= v *)
Sterm.singleton (from_polynomial q)
else if ls_equal ls ps_lt then
(* q < v, hence q + 1 < v *)
Sterm.singleton (from_polynomial (p_add (p_int 1) q))
else
Sterm.empty
| None -> Sterm.empty
end
| Tbinop (Tand, t1, t2) ->
if pos then
Sterm.union (find pos t1) (find pos t2)
else
Sterm.inter (find pos t1) (find pos t2)
| Tbinop (Tor, t1, t2) ->
if pos then
Sterm.inter (find pos t1) (find pos t2)
else
Sterm.union (find pos t1) (find pos t2)
| Tbinop (Timplies, t1, t2) ->
if pos then
Sterm.inter (find (not pos) t1) (find pos t2)
else
Sterm.union (find (not pos) t1) (find pos t2)
| Tnot t' ->
find (not pos) t'
| Tquant (q, tq) ->
let (_, _, t') = t_open_quant tq in
find pos t'
| _ -> Sterm.empty
in find (q = Texists) t
let polynomial_of_inequality ls t1 t2 =
(* returns a polynomial [p] such that [t1 <ls> t2] iff [0 < p]. *)
let p1, p2 = to_polynomial t1, to_polynomial t2 in
if ls_equal ls ps_le then
(* [t1 <= t2] iff [0 < t2 - t1 + 1] *)
p_add (p_sub p2 p1) (p_int 1)
else if ls_equal ls ps_lt then
(* [t1 < t2] iff [0 < t2 - t1] *)
p_sub p2 p1
else if ls_equal ls ps_ge then
(* [t1 >= t2] iff [0 < t1 - t2 + 1 ] *)
p_add (p_sub p1 p2) (p_int 1)
else if ls_equal ls ps_gt then
(* [t1 > t2] iff [0 < t1 - t2] *)
p_sub p2 p1
else
implementation_error "invalid argument to polynomial_of_inequality"
let replace_guard_formula vs u t =
(* replace (as many as possible) subformulas of [t] with [true]
* which are implied by [0 <= vs < u]. *)
let p1 = polynomial_of_inequality ps_le t_zero (t_var vs) in
let p2 = polynomial_of_inequality ps_lt (t_var vs) u in
let is_non_negative p = p_is_const p && I.le I.zero (p_const_part p) in
let rec replace t =
match t.t_node with
| Tapp (ls, [t1; t2]) when is_int t1 && is_cmp_op ls &&
not @@ ls_equal ls ps_equ ->
let p = polynomial_of_inequality ls t1 t2 in
We have to check [ 0 < p ] implies either [ 0 < p1 ] or [ 0 < p2 ] .
* Either [ p < = p1 ] or [ p < = p2 ] is sufficient ( but not necessary ) .
* We simply check that either [ ] or [ p2 - p ] is a non - negative
* constant .
* Either [p <= p1] or [p <= p2] is sufficient (but not necessary).
* We simply check that either [p1 - p] or [p2 - p] is a non-negative
* constant. *)
if is_non_negative (p_sub p1 p) || is_non_negative (p_sub p2 p)
then t_true
else t
| _ ->
TermTF.t_map_simp (fun t -> t) replace t
in replace t
let rec merge_quantifiers t =
match t.t_node with
| Tquant (q, _) ->
(* Separate [t] into a list of quantified variables,
* a list of guards, and a body.
* [t] is logically equivalent to
* [t_quant_close_guard q vss [] (t_and_simp_l gs) b]. *)
let vss, gs, b =
(* Guards are accumulated in the reverse order;
* but there is no strong reason for doing so. *)
let rec separate q qvss gs t =
match t.t_node with
| Tquant (q', tq) when q = q' ->
(* triggers are removed here (any problem?) *)
let (vss, _, t') = t_open_quant tq in
separate q (qvss @ vss) gs t'
| Tbinop (op, t1, t2)
when (q = Tforall && op = Timplies) ||
(q = Texists && op = Tand)
-> separate q qvss (t1 :: gs) t2
| _ ->
qvss, gs, t
in
separate q [] [] t
in
Merge inner quantifiers first ;
* [ t ] is equivalent to [ [ ] t ' ]
* [t] is equivalent to [t_quant_close q vss [] t'] *)
let gs' = List.rev_map merge_quantifiers gs in
let b' = merge_quantifiers b in
let t' =
match q with
| Tforall -> t_implies_simp (t_and_simp_l gs') b'
| Texists -> t_and_simp (t_and_simp_l gs') b'
in
Partition [ vss ] into two ; bounded and unbounded ones .
* Bounded variables should essentially be guarded by [ 0 < = x < u ]
* for some term [ u ] , otherwise a variable is considered unbounded .
* [ vs_ub_list ] is a list of bounded variables each of which is
* associated with its upper bound , and [ vs_nb ] consists of unbounded
* ones .
* Bounded variables should essentially be guarded by [0 <= x < u]
* for some term [u], otherwise a variable is considered unbounded.
* [vs_ub_list] is a list of bounded variables each of which is
* associated with its upper bound, and [vs_nb] consists of unbounded
* ones. *)
let vs_ub_list, vs_nb =
List.fold_left (fun (b, nb) vs ->
if check_lower_bound q (t_var vs) t' then
let ubs = Sterm.elements @@
find_upper_bounds q (t_var vs) t'
|> List.filter (fun ub ->
t_v_occurs vs ub = 0)
in
if ubs = [] then b, vs :: nb
else (vs, ubs) :: b, nb
else b, vs :: nb)
([], []) (List.rev vss)
in
let merge'' q vs ub vs' ub' t =
assert (t_v_occurs vs ub = 0);
assert (t_v_occurs vs' ub' = 0);
if t_v_occurs vs' ub = 0 && t_v_occurs vs ub' = 0 then
try
let vs_new, t' = reduce_variables q vs ub vs' ub' t in
Some (vs_new, vs, vs', ub, ub', t')
with CannotReduceVariables -> None
else None
in
let rec merge' vs ub l t =
match l with
| [] -> None
| (vs', ubs') :: l' ->
try Some (List.find_map (fun ub' ->
merge'' q vs ub vs' ub' @@
replace_guard_formula vs' ub' t)
ubs')
with Not_found -> merge' vs ub l' t
in
let rec merge l t =
match l with
| [] | [_] -> None
| (vs, ubs) :: l' ->
try Some (List.find_map (fun ub ->
merge' vs ub l' @@
replace_guard_formula vs ub t)
ubs)
with Not_found -> merge l' t
in
(* Merge as many variables from [list] as possible, and returns
* the resulting formula and a list of variables used in it
* (both newly introduced ones and the ones that were not merged). *)
let rec merge_all list t =
match merge list t with
| Some (vs_new, vs, vs', ub, ub', t') ->
(* Found a pair to be merged. *)
(* [vs] and [vs'] are to be eliminated; they should not
* appear in the formula we are going to return, which is
* built from [t'], [ub], and [ub']. *)
assert (t_v_occurs vs t' = 0);
assert (t_v_occurs vs' t' = 0);
assert (List.exists (fun (vs'', _) -> vs_equal vs'' vs) list);
assert (List.exists (fun (vs'', _) -> vs_equal vs'' vs') list);
(* Here [t] can be rewritten as (when [q] is [Tforall]):
* 0 <= vs_new < ub * ub' -> t'
* but the equivalence holds only if [ub] and [ub'] are positive.
* So in general we need more complex form
* 0 < ub /\ 0 < ub' /\ 0 <= vs_new < ub * ub' -> t'.
* The case of [Texists] is similar.
* Therefore the guard is
* 0 < ub /\ 0 < ub' /\ 0 <= vs_new < ub * ub'. *)
let guard = t_and_simp_l [
t_pos ub;
t_pos ub';
t_le t_zero (t_var vs_new);
t_lt (t_var vs_new) (t_mult ub ub')]
|> remove_trivial_comparison
in
(* New list of variables, equipped with their upper bounds. *)
let list' =
(vs_new, [t_mult ub ub']) ::
List.filter
(fun (vs'', _) ->
not (vs_equal vs' vs'' || vs_equal vs vs''))
list
in
(* Add the guard above to the body, and try to merge
* remaining variables. *)
merge_all list' @@
if q = Tforall then
t_implies_simp guard t'
else
t_and_simp guard t'
| None ->
(* no more pairs to be merged *)
list, t
in
let list', t'' = merge_all vs_ub_list t' in
if List.length list' < List.length vs_ub_list then
(* [list'] has length fewer than the original list.
* This means that some pair of variables are merged. *)
t_quant_close_simp q (List.map fst list' @ vs_nb) [] t''
else if List.for_all2 t_equal gs gs' && t_equal b b' then
(* No variables are merged. Return the original formula. *)
t
else
(* No variables among [vss] are merged, but the variables in
* guards or body are merged. *)
t_quant_close_simp q vss [] t''
| _ ->
TermTF.t_map_simp (fun t -> t) merge_quantifiers t
let merge_quantifiers t =
let t' = merge_quantifiers t in
if not @@ t_equal t t' then
debug "merge quantifiers: %a@. -->@. %a@."
Why3.Pretty.print_term t Why3.Pretty.print_term t'
else
debug "merge quantifiers fails: %a@."
Why3.Pretty.print_term t;
t'
(** ---------------- eliminate existentials in premises *)
let rec eliminate_existential_in_premises task =
let destruct d = match d.Why3.Decl.d_node with
| Why3.Decl.Dprop (k, pr, { t_node = Tquant (Texists, tq) }) ->
begin
match t_open_quant tq with
| (vss, [], body) ->
let alist =
List.map (fun vs ->
let ls =
create_lsymbol
(Why3.Ident.id_clone vs.vs_name)
[] (Some vs.vs_ty) in
(vs, ls))
vss
in
let body' =
List.fold_left (fun t (vs, ls) ->
t_subst_single vs (fs_app ls [] vs.vs_ty) t)
body alist
in
List.map (fun (_, ls) -> Why3.Decl.create_param_decl ls) alist @
[Why3.Decl.create_prop_decl k pr body']
| _ -> [d]
end
| _ -> [d]
in
Why3.Trans.apply (Why3.Trans.decl destruct None) task
(** ---------------- apply equalities in premises *)
type complex_eqn = {
ce_vars : vsymbol list;
ce_guards : term list;
ce_ls : lsymbol;
ce_args : term list;
ce_rhs : term;
}
type simple_eqn = {
se_ls : lsymbol;
se_lhs : term;
se_rhs : term;
}
type eqn =
| SimpleEqn of simple_eqn
| ComplexEqn of complex_eqn
type eqn_info = {
ei_eqn : eqn;
ei_ps : Why3.Decl.prsymbol;
}
let eqn_info_ls = function
| { ei_eqn = SimpleEqn { se_ls = ls } }
| { ei_eqn = ComplexEqn { ce_ls = ls } } -> ls
let print_complex_eqn fmt = function
{ ce_vars = vars;
ce_guards = guards;
ce_ls = ls;
ce_args = args;
ce_rhs = rhs; } ->
Format.fprintf fmt
"@[{ ce_vars = %a;@. \
ce_guards = %a;@. \
ce_ls = %a;@. \
ce_args = %a;@. \
ce_rhs = %a; }@.@]"
(fun fmt vss ->
Format.fprintf fmt "[";
List.iter (Format.fprintf fmt "%a; " Why3.Pretty.print_vs)
vss;
Format.fprintf fmt "]")
vars
(fun fmt guards ->
Format.fprintf fmt "[";
List.iter (Format.fprintf fmt "%a; " Why3.Pretty.print_term)
guards;
Format.fprintf fmt "]")
guards
Why3.Pretty.print_ls
ls
(fun fmt guards ->
Format.fprintf fmt "[";
List.iter (Format.fprintf fmt "%a; " Why3.Pretty.print_term)
guards;
Format.fprintf fmt "]")
args
Why3.Pretty.print_term rhs
let rec extract_complex_eqn f =
Extract complex_eqn from [ f ] .
* If [ f ] is of the form
* forall xs1 . gs1 - > forall xs2 . gs2 - > ... forall xsn . gsn - >
* ls[arg1][arg2] ... [argm ] = rhs
* then returns
* Some
* { = xs1 @ xs2 @ ... @ xsn ;
* ce_guards = [ gs1 ; gs2 ; ... ; gsn ] ;
* ce_ls = ls ; ce_args = [ argm ; ... ; ; arg1 ] ;
* = rhs } .
* If [f] is of the form
* forall xs1. gs1 -> forall xs2. gs2 -> ... forall xsn. gsn ->
* ls[arg1][arg2]...[argm] = rhs
* then returns
* Some
* { ce_vars = xs1 @ xs2 @ ... @ xsn;
* ce_guards = [gs1; gs2; ...; gsn];
* ce_ls = ls; ce_args = [argm; ...; arg2; arg1];
* ce_rhs = rhs }. *)
match f.t_node with
| Tapp (ls, [lhs; rhs]) when ls_equal ps_equ ls ->
let rec f t = match t.t_node with
| Tapp (ls, []) -> Some (ls, [])
| Tapp (ls, [t1; t2]) when ls_equal ls fs_get ->
begin
match f t1 with
| Some (ls', args) -> Some (ls', t2 :: args)
| None -> None
end
| _ -> None
in
begin
match f lhs with
| Some (ls, args)
(* To avoid infinite loop, make sure that [ls] does not
* appear in the rhs. *)
when t_s_any (fun _ -> true) (ls_equal ls) rhs ->
Some { ce_vars = []; ce_guards = [];
ce_ls = ls; ce_args = args; ce_rhs = rhs; }
| _ -> None
end
| Tbinop (Timplies, f1, f2) ->
begin
match extract_complex_eqn f2 with
| Some e -> Some { e with ce_guards = f1 :: e.ce_guards }
| None -> None
end
| Tbinop ( Tand , f1 , f2 ) - >
* merge ( extract_ce_info f1 ) ( f2 )
* | ( Tiff , f1 , f2 ) - >
* merge ( f1 , f2 ) ( f2 , extract_ce_info f1 )
* merge (extract_ce_info f1) (extract_ce_info f2)
* | Tbinop (Tiff, f1, f2) ->
* merge (f1, extract_ce_info f2) (f2, extract_ce_info f1) *)
| Tquant (Tforall, tq) ->
let (vss, tr, f') = t_open_quant tq in
begin
match extract_complex_eqn f' with
| Some e -> Some { e with ce_vars = vss @ e.ce_vars; }
| None -> None
end
| _ -> None
let is_wf_eqn = function
{ ce_vars = vars;
ce_guards = guards;
ce_ls = ls;
ce_args = args;
ce_rhs = rhs; } ->
not (List.exists (t_ls_occurs ls) guards)
let extract_eqn t =
match t.t_node with
| Tapp (ls, [t1; t2]) when ls_equal ps_equ ls ->
Some (SimpleEqn { se_ls = ls; se_lhs = t1; se_rhs = t2 })
| _ -> match extract_complex_eqn t with
| Some e -> if is_wf_eqn e then Some (ComplexEqn e) else None
| None -> None
let collect_eqns task =
List.filter_map (fun decl ->
match decl.Why3.Decl.d_node with
| Why3.Decl.Dprop (Why3.Decl.Paxiom, ps, t) ->
begin
match extract_eqn t with
| Some e -> Some { ei_eqn = e; ei_ps = ps }
| None -> None
end
| _ -> None)
(Why3.Task.task_decls task)
let collect_eqns_test task =
let eqns = collect_eqns task in
if eqns = [] then debug "No equations found@."
else List.iter
(function
| { ei_eqn = SimpleEqn { se_lhs =lhs; se_rhs = rhs } } ->
debug "Found equation: %a = %a@."
Why3.Pretty.print_term lhs
Why3.Pretty.print_term rhs
| { ei_eqn =
ComplexEqn { ce_ls = ls; ce_args = args; ce_rhs = rhs; } } ->
let lhs =
List.fold_left t_get (t_app ls [] ls.ls_value)
(List.rev args)
in
debug "Found equation: %a = %a@."
Why3.Pretty.print_term lhs
Why3.Pretty.print_term rhs)
eqns
let rec match_lhs ls args t =
(* If [args] is [a1; a2; ...; an], this function checkes whether
* [t] has the form [get (... (get (get ls a1) a2) ...) an],
* and returns the list of terms corresponding to [a1], [a2], ...,
* [an] in the reverse order. *)
match t.t_node, args with
| Tapp (ls', []), [] when ls_equal ls ls' -> Some []
| Tapp (ls', [t1; t2]), a::args' when ls_equal ls' fs_get ->
begin
match match_lhs ls args' t1 with
| Some ts -> Some (t2 :: ts)
| None -> None
end
| _ -> None
let rec find_match bvs ls args t =
match match_lhs ls args t with
| Some ts ->
if Svs.exists (fun vs -> List.exists
(t_v_any (vs_equal vs)) ts)
bvs
then
At least one of [ ts ] contains a bound variable ; reject .
[]
else [(ts, t)]
| None ->
match t.t_node with
| Tquant (q, tq) ->
let (vss, _, t') = t_open_quant tq in
let bvs' = List.fold_right Svs.add vss bvs in
find_match bvs' ls args t'
| Teps b ->
let (vs, t') = t_open_bound b in
find_match (Svs.add vs bvs) ls args t'
| Tlet (t1, b) ->
let (vs, t2) = t_open_bound b in
find_match bvs ls args t1
@ find_match (Svs.add vs bvs) ls args t2
| _ ->
t_fold (fun acc t ->
find_match bvs ls args t @ acc)
[] t
let apply_simple_eqn { se_lhs = lhs; se_rhs = rhs } t =
t_replace lhs rhs t
let rec t_map_on_quant f t =
match t.t_node with
| Tquant _ -> t_map_simp f t
| _ -> t_map_simp (t_map_on_quant f) t
let rec apply_complex_eqn eqn seen t =
if t_ls_occurs eqn.ce_ls t then
match t.t_node with
| Tbinop (op, t1, t2) when not (t_ls_occurs eqn.ce_ls t1) ->
t_binary_simp op t1 (apply_complex_eqn eqn seen t2)
| Tbinop (op, t1, t2) when not (t_ls_occurs eqn.ce_ls t2) ->
t_binary_simp op (apply_complex_eqn eqn seen t1) t2
| _ ->
let matches = find_match Svs.empty eqn.ce_ls eqn.ce_args t
|> List.filter (fun (_, s) -> not (Sterm.mem s seen))
|> List.unique
~cmp:(fun (ts, t) (ts', t') ->
if t_equal t t' then
(assert (List.for_all2 t_equal ts ts'); true)
else false)
in
let seen' = List.fold_left
(fun seen (_, s) -> Sterm.add s seen)
seen matches
in
List.fold_left
(fun t (ts, s) ->
(* [t_occurs s t] is not necessarily true because of the
* simplification. *)
if t_occurs s t then
t_or_simp
(t_exists_close eqn.ce_vars [] @@
(t_and_simp_l [t_and_simp_l eqn.ce_guards;
t_and_simp_l (List.map2 t_equ_simp
eqn.ce_args ts);
t_replace s eqn.ce_rhs t]))
(t_and_simp
(t_not_simp
(t_exists_close eqn.ce_vars [] @@
(t_and_simp (t_and_simp_l eqn.ce_guards)
(t_and_simp_l (List.map2 t_equ_simp
eqn.ce_args ts)))))
t)
|> simplify_formula
else t)
t matches
|> t_map_on_quant (apply_complex_eqn eqn seen')
else
t
let apply_eqn_to_term e t =
match e with
| SimpleEqn e -> apply_simple_eqn e t
| ComplexEqn e -> apply_complex_eqn e Sterm.empty t
let rec apply_eqn_info task eqn_info =
(* debug "apply_eqn_info %d@." (Why3.Task.task_hash task); *)
match task with
| None -> None
| Some {
Why3.Task.task_decl = tdecl;
Why3.Task.task_prev = task_prev;
} ->
match tdecl.Why3.Theory.td_node with
| Why3.Theory.Decl {
Why3.Decl.d_node = Why3.Decl.Dprop (k, pr, t)
} when not (Why3.Decl.pr_equal pr eqn_info.ei_ps) ->
let task_prev' = apply_eqn_info task_prev eqn_info in
let t' = apply_eqn_to_term eqn_info.ei_eqn t in
if Why3.Task.task_equal task_prev task_prev' then
There is no further occurrence of [ lhs ] .
if t_equal t t' then
There is no occurrence of [ lhs ] in [ t ] , so we
* just leave [ task ] unchanged .
* just leave [task] unchanged. *)
task
else if k = Why3.Decl.Paxiom && is_tautology t' then
(* Slight optimization to suppress trivial axioms. *)
task_prev'
else
[ lhs ] occurs in [ t ] , so we should replace it with [ rhs ] .
* Since this is the first occurrence of [ lhs ] , we have to
* declare lsymbols in [ rhs ] here .
* Since this is the first occurrence of [lhs], we have to
* declare lsymbols in [rhs] here. *)
let lss = t_s_fold (fun s _ -> s)
(fun s ls -> Sls.add ls s)
Sls.empty t'
in
let task' =
Sls.fold (fun ls task ->
let decl = Why3.Decl.create_param_decl ls in
try Why3.Task.add_decl task decl
with Why3.Decl.RedeclaredIdent _ -> task)
lss task_prev
in
let decl = Why3.Decl.create_prop_decl k pr t' in
Why3.Task.add_decl task' decl
else
[ lhs ] occurs in [ task_prev ] , so lsymbols inside [ rhs ] is
* already declared in [ task_prev ' ] .
* already declared in [task_prev']. *)
if t_equal t t' then
Why3.Task.add_tdecl task_prev' tdecl
else if k = Why3.Decl.Paxiom && is_tautology t' then
task_prev'
else
let decl = Why3.Decl.create_prop_decl k pr t' in
Why3.Task.add_decl task_prev' decl
| Why3.Theory.Decl {
Why3.Decl.d_node = Why3.Decl.Dparam ls
} ->
if ls_equal ls (eqn_info_ls eqn_info) then
(* Nothing more to be rewritten. *)
task
else
let task_prev' = apply_eqn_info task_prev eqn_info in
if Why3.Task.task_equal task_prev task_prev' then
There is no further occurrence of [ lhs ] .
* No changes needed .
* No changes needed. *)
task
else
There is an occurence of [ lhs ] in [ task_prev ] ;
* In this case [ ls ] may already be declared in [ task_prev ' ] ,
* but I do n't know an easy way to check it .
* Instead , just try to declare [ ls ] .
* If the attempt fails , return [ task_prev ' ] .
* In this case [ls] may already be declared in [task_prev'],
* but I don't know an easy way to check it.
* Instead, just try to declare [ls].
* If the attempt fails, return [task_prev']. *)
let decl = Why3.Decl.create_param_decl ls in
begin
try Why3.Task.add_decl task_prev' decl
(* [ls] is already declared, so we don't have to add it. *)
with Why3.Decl.RedeclaredIdent _ -> task_prev'
end
| _ ->
let task_prev' = apply_eqn_info task_prev eqn_info in
if Why3.Task.task_equal task_prev task_prev' then
task
else
Why3.Task.add_tdecl task_prev' tdecl
let apply_eqn_info_simp tasks eqn_info =
List.map (fun task ->
apply_eqn_info task eqn_info
|> Why3.Trans.apply_transform "simplify_trivial_quantification"
Why3api.env)
tasks
|> List.concat
let rewrite_using_simple_premises task =
collect_eqns task
|> List.filter_map
(fun e -> match e with
| { ei_eqn = SimpleEqn _ } -> Some e
| _ -> None)
|> List.fold_left apply_eqn_info_simp [task]
(* |> Why3.Trans.apply_transform "simplify_trivial_quantification"
* Why3api.env *)
|> List.map (task_map_decl simplify_guards)
let rewrite_using_premises task =
collect_eqns task
|> List.fold_left apply_eqn_info_simp [task]
(* |> Why3.Trans.apply_transform "simplify_trivial_quantification"
* Why3api.env *)
|> List.map (task_map_decl simplify_guards)
(** ---------------- quantifier elimination *)
let rec is_qf t =
match t.t_node with
| Tquant (_, _) -> false
| _ -> t_all is_qf t
type literal =
| Lit_le : polynomial -> literal
| Lit_ge : polynomial -> literal
| Lit_eq : polynomial -> literal
| Lit_const : term -> literal
let lit_not = function
| Lit_le p -> [[Lit_ge (p_add p (p_int 1))]]
| Lit_ge p -> [[Lit_le (p_sub p (p_int 1))]]
| Lit_eq p -> [[Lit_ge (p_add p (p_int 1))];
[Lit_le (p_sub p (p_int 1))]]
| Lit_const t -> [[Lit_const (t_not_simp t)]]
let clause_not c =
not ( L1 and ... and ) < = > ( not L1 ) or ... or ( not )
List.concat @@ List.map lit_not c
let lit_equal x y = match x, y with
| Lit_le p, Lit_le q
| Lit_ge p, Lit_ge q
| Lit_eq p, Lit_eq q -> p_equal p q
| Lit_const t, Lit_const t' -> t_equal t t'
| _, _ -> false
let clause_and c1 c2 =
let c = List.unique ~cmp:lit_equal @@ c1 @ c2 in
put multiple [ Lit_const ] 's into one
let rec f const cmps = function
| [] -> if t_equal const t_false then
[Lit_const t_false]
else if t_equal const t_true then
cmps
else
Lit_const const :: cmps
| Lit_const t :: c' -> f (t_and_simp const t) cmps c'
| l :: c' -> f const (l :: cmps) c'
in
f t_true [] c
let is_subset_of c c' =
List.for_all (fun l -> List.exists (lit_equal l) c') c
let has_subset_of f c =
List.exists (fun c' -> is_subset_of c' c) f
let rec dnf_or f1 f2 =
match f1 with
| [] -> f2
| c::f1' ->
if has_subset_of f2 c then dnf_or f1' f2 else c :: dnf_or f1' f2
let rec dnf_and f1 f2 =
match f1 with
| [] -> []
| c::f1' ->
( C1 or C2 or ... or Cn ) and f2
* < = > ( C1 and f2 ) or ( C2 and f2 ) or ... or ( Cn and f2 ) ;
* C and ( C1 or ... or Cn )
* < = > ( C and C1 ) or ( C and C2 ) or ... or ( C and Cn ) ;
* C and C1 < = > union of C and C1 ( considered as a clause )
* <=> (C1 and f2) or (C2 and f2) or ... or (Cn and f2);
* C and (C1 or ... or Cn)
* <=> (C and C1) or (C and C2) or ... or (C and Cn);
* C and C1 <=> union of C and C1 (considered as a clause) *)
dnf_or (List.map (clause_and c) f2) (dnf_and f1' f2)
let rec dnf_not = function
| [] -> [[]] (* not false <=> true *)
| c::cs ->
(* not (C1 or C2 or ... or Cn)
* <=> not C1 and not (C2 or ... or Cn) *)
dnf_and (clause_not c) (dnf_not cs)
let dnf_implies f1 f2 = dnf_or (dnf_not f1) f2
let dnf_iff f1 f2 = dnf_and (dnf_implies f1 f2) (dnf_implies f2 f1)
let dnf_op op f1 f2 = match op with
| Tand -> dnf_and f1 f2
| Tor -> dnf_or f1 f2
| Timplies -> dnf_implies f1 f2
| Tiff -> dnf_iff f1 f2
let nnf_of t =
let rec nnf_pos t =
match t.t_node with
| Tbinop (op, t1, t2) ->
begin
match op with
| Tand -> t_and_simp (nnf_pos t1) (nnf_pos t2)
| Tor -> t_or_simp (nnf_pos t1) (nnf_pos t2)
| Timplies -> t_or_simp (nnf_neg t1) (nnf_pos t2)
| Tiff -> t_and_simp
(t_or_simp (nnf_neg t1) (nnf_pos t2))
(t_or_simp (nnf_neg t2) (nnf_pos t1))
end
| Tnot t -> nnf_neg t
| _ -> t
and nnf_neg t =
match t.t_node with
| Tbinop (op, t1, t2) ->
begin
match op with
| Tand -> t_or_simp (nnf_neg t1) (nnf_neg t2)
| Tor -> t_and_simp (nnf_neg t1) (nnf_neg t2)
| Timplies -> t_and_simp (nnf_pos t1) (nnf_neg t2)
| Tiff -> t_or_simp
(t_and_simp (nnf_pos t1) (nnf_neg t2))
(t_and_simp (nnf_pos t2) (nnf_neg t1))
end
| Tnot t -> nnf_pos t
| _ -> t_not_simp t
in nnf_pos t
let rec dnf_of vs t: literal list list option =
let rec dnf t =
(* [t]: term, [vs]: variable *)
match t.t_node with
| _ when not (t_v_any (vs_equal vs) t) -> Some [[Lit_const t]]
| Tapp (ls, [t1; t2]) when is_cmp_op ps_equ && is_int t1 ->
let p = p_sub (to_polynomial t1) (to_polynomial t2) in
if p_contains (t_var vs) p then
begin
match isolate_var (t_var vs) p with
| None -> None
| Some (p, _) when t_v_any (vs_equal vs) (from_polynomial p) -> None
| Some (p, s) ->
(* t1 - t2 = s * v + p *)
if ls_equal ls ps_equ then
(* v = -s * p *)
Some [[Lit_eq (if s = 1 then (p_neg p) else p)]]
else if ls_equal ls ps_lt then
v < -p if s = 1 , and v > p if s = -1
* i.e. v < = -(p + 1 ) if s = 1 , and v > = p + 1 if s = -1
* i.e. v <= -(p + 1) if s = 1, and v >= p + 1 if s = -1 *)
if s = 1 then Some [[Lit_le (p_neg (p_add p (p_int 1)))]]
else Some [[Lit_ge (p_add p (p_int 1))]]
else if ls_equal ls ps_le then
v < = -p if s = 1 , and v > = p if s = -1
if s = 1 then Some [[Lit_le (p_neg p)]]
else Some [[Lit_ge p]]
else if ls_equal ls ps_gt then
v > -p if s = 1 , and v < p if s = -1
if s = 1 then Some [[Lit_ge (p_add (p_neg p) (p_int 1))]]
else Some [[Lit_le (p_sub p (p_int 1))]]
else (* assert (ls_equal ls ps_ge); *)
v > = -p if s = 1 , and v < = p if s = -1
if s = 1 then Some [[Lit_ge (p_neg p)]]
else Some [[Lit_le p]]
end
else
(* Some (t_app ls [from_polynomial p; t_zero] None) *)
(* In this case [vs] is not contained in [t], so this case
* is trivial. *)
if t_v_any (vs_equal vs) (from_polynomial p) then
None
else
begin
match (from_polynomial p).t_node with
| Tconst (Why3.Number.ConstInt n) ->
let cmp =
if ls_equal ls ps_equ then I.eq
else if ls_equal ls ps_lt then I.lt
else if ls_equal ls ps_le then I.le
else if ls_equal ls ps_gt then I.gt
else I.ge
in
if cmp (Why3.Number.compute_int n) I.zero then
Some [[Lit_const t_true]]
else Some [[Lit_const t_false]]
| _ ->
Some [[Lit_const (t_app ls [from_polynomial p; t_zero] None)]]
end
| Tbinop (op, t1, t2) ->
begin
match dnf t1, dnf t2 with
| Some f1, Some f2 -> Some (dnf_op op f1 f2)
| _, _ -> None
end
| Tnot t1 ->
begin
match dnf t1 with
| Some f -> Some (dnf_not f)
| None -> None
end
| _ -> None
in dnf (nnf_of t)
let print_literal fmt = function
| Lit_le p -> Format.fprintf fmt "Lit_le (%a)"
Why3.Pretty.print_term (from_polynomial p)
| Lit_ge p -> Format.fprintf fmt "Lit_ge (%a)"
Why3.Pretty.print_term (from_polynomial p)
| Lit_eq p -> Format.fprintf fmt "Lit_eq (%a)"
Why3.Pretty.print_term (from_polynomial p)
| Lit_const c -> Format.fprintf fmt "Lit_const (%a)"
Why3.Pretty.print_term c
let print_dnf fmt f =
Format.fprintf fmt "[@[";
List.iter (fun c -> Format.fprintf fmt "[@[";
List.iter (Format.fprintf fmt "%a;@." print_literal) c;
Format.fprintf fmt "@]];@.")
f;
Format.fprintf fmt "@]]@."
let eliminate_quantifier_from_conj c =
(* List.iter print_literal c; *)
let rec collect ubs lbs eqs consts = function
| [] -> ubs, lbs, eqs, consts
| Lit_le t :: c' -> collect (t :: ubs) lbs eqs consts c'
| Lit_ge t :: c' -> collect ubs (t :: lbs) eqs consts c'
| Lit_eq t :: c' -> collect ubs lbs (t :: eqs) consts c'
| Lit_const t :: c' -> collect ubs lbs eqs (t :: consts) c'
in
let p_ubs, p_lbs, p_eqs, consts = collect [] [] [] [] c in
let ubs = List.map from_polynomial p_ubs in
let lbs = List.map from_polynomial p_lbs in
let eqs = List.map from_polynomial p_eqs in
match eqs with
| [] ->
remove_trivial_comparison @@
t_and_simp
(t_and_simp_l @@
List.concat @@
List.map (fun l -> List.map (t_le l) ubs) lbs)
(t_and_simp_l consts)
| r :: rs ->
remove_trivial_comparison @@
t_and_simp_l @@
t_and_simp_l (List.map (t_equ_simp r) rs) ::
t_and_simp_l (List.map (t_le r) ubs) ::
t_and_simp_l (List.map (t_ge r) lbs) ::
consts
let eliminate_quantifier_from_dnf f =
List.map (fun c -> eliminate_quantifier_from_conj c) f
let eliminate_linear_quantifier_1 q vs t =
match q with
| Tforall ->
begin
match dnf_of vs (t_not_simp t) with
| Some f ->
let ts = eliminate_quantifier_from_dnf f in
Some (t_not_simp (t_or_simp_l ts))
| None ->
None
end
| Texists ->
match dnf_of vs t with
| Some f ->
let ts = eliminate_quantifier_from_dnf f in
Some (t_or_simp_l ts)
| None -> None
let rec eliminate_linear_quantifier_t t =
Eliminate inner quantifiers first .
let t = TermTF.t_map_simp (fun t -> t) eliminate_linear_quantifier_t @@
eliminate_unique_quant t
in
match t.t_node with
| Tquant (q, tq) ->
(* debug "eliminate_linear_quantifier_t: @[%a@]@." Why3.Pretty.print_term t; *)
let vss, tr, t' = t_open_quant tq in
let rec elim vss t =
(* Tries to eliminate variables in [vss], and returns a pair
* [vss_left, t'] where [vss_left] is the list of variables
* that are not eliminated, and [t'] is the resulting formula. *)
match vss with
| [] -> [], t
| vs::vss' ->
let (vss_left, t') = elim vss' t in
match eliminate_linear_quantifier_1 q vs t' with
| Some t'' -> vss_left, t''
| None -> vs::vss_left, t'
in
let vss_left, t'' = elim vss t' in
t_quant_close_simp q vss_left tr t''
| _ -> t
let eliminate_linear_quantifier task =
task_map_decl
(fun t ->
(* debug "eliminate_linear_quantifier: @[%a@]@." Why3.Pretty.print_term t; *)
let t' = eliminate_unique_quant t
|> eliminate_linear_quantifier_t
|> simplify_formula
in
if not (t_equal t t') then
debug "eliminate_linear_quantifier rewrites@. %[email protected]@. %a@."
Why3.Pretty.print_term t Why3.Pretty.print_term t';
t')
task
(** ---------------- replace anonymous functions with a variable *)
let rec bind_epsilon_by_let t =
let rec collect bvs m t =
match t.t_node with
| Tlet (t', tb) ->
let m' = collect bvs m t' in
let (vs, t'') = t_open_bound tb in
collect (Svs.add vs bvs) m' t''
| Tcase _ -> not_implemented "bind_epsilon_by_let, case"
| Teps _ when Svs.for_all (fun vs -> t_v_occurs vs t = 0) bvs ->
if Mterm.mem t m then
Mterm.add t (Mterm.find t m + 1) m
else
Mterm.add t 1 m
| Tquant (_, tq) ->
let (vss, _, t') = t_open_quant tq in
collect (List.fold_right Svs.add vss bvs) m t'
| _ ->
t_fold (collect bvs) m t
in
let t' = TermTF.t_map_simp (fun t -> t) bind_epsilon_by_let t in
let m = collect Svs.empty Mterm.empty t' in
Mterm.fold
(fun te n t ->
if n > 1 then
match te.t_ty with
| Some ty ->
let vs = create_vsymbol (Why3.Ident.id_fresh "func") ty in
t_let_close vs te (t_replace_simp te (t_var vs) t')
| None -> t'
else t')
m t'
(** ---------------- congruence *)
let apply_congruence t =
let modified = ref false in
let rec apply sign t =
match t.t_node with
| Tapp (ls, [t1; t2]) when ls_equal ls ps_equ ->
begin
match t1.t_node, t2.t_node with
| Tapp (ls, ts), Tapp (ls', ts')
when ls_equal ls ls' &&
List.for_all2 (fun t t' ->
match t.t_ty, t'.t_ty with
| None, None -> true
| Some ty, Some ty' -> Why3.Ty.ty_equal ty ty'
| _ -> false)
ts ts'
->
debug "congruence matching %a@." Why3.Pretty.print_term t;
t_and_simp_l @@ List.map2 t_equ_simp ts ts'
|> fun t ->
debug "returning %a@." Why3.Pretty.print_term t;
modified := true;
t
| _, _ -> t
end
| _ -> TermTF.t_map_sign (fun _ t -> t) apply sign t
in
let result = apply true t in
if !modified then Some result else None
(** ---------------- replace equality with [False] *)
(* perhaps this doesn't help much *)
let replace_equality_with_false t =
let rec replace sign t =
match t.t_node with
| Tapp (ls, [{t_node = Tapp (ls', ts)}; _])
when ls_equal ls ps_equ && ls_equal ls' fs_get ->
(* Replace occurrences of [get _ _ = _] at positive positions
* with [False]. *)
if sign then t_false else t_true
| Tbinop (Tand | Tor as op, t1, t2) ->
t_binary_simp op (replace sign t1) (replace sign t2)
| Tbinop (Timplies, t1, t2) ->
t_implies_simp (replace (not sign) t1) (replace sign t2)
| Tnot t' -> t_not_simp (replace (not sign) t')
| _ -> TermTF.t_map_simp (fun t -> t) (replace sign) t
in replace true t
|> fun t' ->
debug "replace %a@. into %a@."
Why3.Pretty.print_term t Why3.Pretty.print_term t';
t'
(** ---------------- eliminate ls *)
let rec eliminate_ls_t sign ls t =
(* Replace any occurrence of an atomic formula containing [ls]
* with true (if [sign] is true) or false (if [sign] is false). *)
match t.t_node with
| Tapp (_, _) ->
if t_ls_occurs ls t then
if sign then t_false else t_true
else t
| Tbinop ((Tand | Tor as op), t1, t2) ->
t_binary_simp op (eliminate_ls_t sign ls t1)
(eliminate_ls_t sign ls t2)
| Tbinop (Timplies, t1, t2) ->
t_implies_simp (eliminate_ls_t (not sign) ls t1)
(eliminate_ls_t sign ls t2)
| Tbinop (Tiff, t1, t2) ->
t_and_simp
(t_implies_simp (eliminate_ls_t (not sign) ls t1)
(eliminate_ls_t sign ls t2))
(t_implies_simp (eliminate_ls_t (not sign) ls t2)
(eliminate_ls_t sign ls t1))
| Tnot t' ->
t_not_simp (eliminate_ls_t (not sign) ls t')
| _ -> TermTF.t_map_simp (fun t -> t) (eliminate_ls_t sign ls) t
let eliminate_ls ls task =
let rec elim tdecls task =
match task with
| None -> tdecls, task
| Some {
Why3.Task.task_decl = tdecl;
Why3.Task.task_prev = task_prev;
} ->
match tdecl.Why3.Theory.td_node with
| Why3.Theory.Decl {
Why3.Decl.d_node = Why3.Decl.Dparam ls'
} when ls_equal ls' ls ->
(* Nothing more to be eliminated. *)
tdecls, task_prev
| Why3.Theory.Decl {
Why3.Decl.d_node = Why3.Decl.Dprop (k, pr, t)
} ->
let t' = eliminate_ls_t (k = Why3.Decl.Pgoal) ls t in
if t_equal t' t_true && k <> Why3.Decl.Pgoal then
elim (tdecl :: tdecls) task_prev
else
elim ((Why3.Theory.create_decl @@
Why3.Decl.create_prop_decl k pr t') :: tdecls)
task_prev
| _ ->
elim (tdecl :: tdecls) task_prev
in
let tdecls, task = elim [] task
in List.fold_left Why3.Task.add_tdecl task tdecls
* ---------------- simplify affine ( in)equalities
let collect_ls_bounds task =
let decls = Why3.Task.task_decls task in
let rec collect decls acc =
match decls with
| decl :: decls' ->
let acc' =
match decl.Why3.Decl.d_node with
| Why3.Decl.Dparam ({ ls_args = []; ls_value = Some ty } as ls)
when Why3.Ty.ty_equal ty ty_int ->
if List.exists (function
| { Why3.Decl.d_node =
Why3.Decl.Dprop (Why3.Decl.Paxiom, _, ax) } ->
check_lower_bound Texists (t_ls ls) ax
| _ -> false)
decls'
then
List.map (function
| { Why3.Decl.d_node =
Why3.Decl.Dprop (Why3.Decl.Paxiom, _, ax) } ->
find_upper_bounds Texists (t_ls ls) ax
| _ -> Sterm.empty)
decls'
|> List.fold_left Sterm.union Sterm.empty
|> (fun ts -> Mterm.add (t_ls ls) ts acc)
else acc
| _ -> acc
in collect decls' acc'
| [] -> acc
in collect decls Mterm.empty
let why3_bigInt_gcd n1 n2 =
let rec euclid x y =
(* assume x >= y *)
if I.eq I.zero y then x
else euclid y (I.euclidean_mod x y)
in
let x = I.abs n1 in
let y = I.abs n2 in
if I.ge x y then euclid x y else euclid y x
let term_list_intersect ts1 ts2 =
List.filter (fun t -> List.exists (t_equal t) ts1) ts2
let common_factor p =
let ts, ns = List.split (PTerm.p_repr p) in
let m =
match ts with
| t :: ts' -> List.fold_left term_list_intersect t ts'
| [] -> []
in
let n =
match ns with
| n :: ns' -> List.fold_left why3_bigInt_gcd n ns'
| [] -> I.zero
in
m, n
let from_polynomial_opt = function
| Some p -> from_polynomial p
| None -> implementation_error "from_polynomial_opt"
let rec find_first list f = match list with
| x :: xs ->
begin match f x with None -> find_first xs f | r -> r end
| [] -> None
let simp_op bounds cmp t1 t2 : term option =
(* in case t1 and t2 have a common factor;
* but we consider only common monomials *)
let p1 = to_polynomial t1 in
let p2 = to_polynomial t2 in
(* transpose terms with negative coefficients *)
let p1, p2 =
let p = p_repr @@ p_sub p1 p2 in
let pos, neg = List.partition (fun (_, n) -> I.gt n I.zero) p in
of_repr pos, p_neg (of_repr neg)
in
let m1, n1 = common_factor p1 in
let m2, n2 = common_factor p2 in
let m = if I.eq I.zero n1 then m2
else if I.eq I.zero n2 then m1
else term_list_intersect m1 m2
in
let n = why3_bigInt_gcd n1 n2 in
if I.eq n I.zero then
begin
(* t1 = t2 = 0 *)
assert (p_repr p1 = []);
assert (p_repr p2 = []);
match cmp with
| `Le | `Eq | `Ge -> Some t_true
| _ -> Some t_false
end
else if m = [] && I.eq n I.one then
(* no common factor *)
let repr1 = p_repr p1 in
let repr2 = p_repr p2 in
let is_var = function
| [{ t_node = Tvar _ } as v], n
| [{ t_node = Tapp(_, []) } as v], n ->
if I.eq n I.one
then Some (v, 1)
else if I.eq n (I.minus I.one)
then Some (v, -1)
else None
| _ -> None
in
let vs1 = List.filter_map is_var repr1 in
let vs2 = List.filter_map is_var repr2 in
if vs1 <> [] && vs2 <> [] then
let _ =
debug "t1 = %a, and@." Why3.Pretty.print_term t1;
debug "t2 = %a@." Why3.Pretty.print_term t2;
in
let mk_cmp s v1 v2 q1 q2 =
(* here pi = s * vi + b * qi;
* note: we may assume 0 <= vi < b *)
match cmp with
| `Lt ->
s * v1 + b * q1 < s * v2 + b * q2
* < = > q1 < q2 \/ ( q1 = q2 /\ s * v1 < s * v2 )
* <=> q1 < q2 \/ (q1 = q2 /\ s * v1 < s * v2) *)
t_or (t_lt q1 q2)
(t_and (t_equ q1 q2)
(if s = 1 then t_lt v1 v2
else t_lt v2 v1))
| `Le ->
s * v1 + b * q1 < = s * v2 + b * q2
* < = > q1 < q2 \/ ( q1 = q2 /\ s * v1 < = s * v2 )
* <=> q1 < q2 \/ (q1 = q2 /\ s * v1 <= s * v2) *)
t_or (t_lt q1 q2)
(t_and (t_equ q1 q2)
(if s = 1 then t_le v1 v2
else t_le v2 v1))
| `Eq ->
s * v1 + b * q1 = s * v2 + b * q2
* < = > q1 = q2 /\ v1 = v2
* <=> q1 = q2 /\ v1 = v2 *)
t_and (t_equ q1 q2) (t_equ v1 v2)
| `Gt ->
s * v1 + b * q1 > s * v2 + b * q2
* < = > q1 > q2 \/ ( q1 = q2 /\ s * v1 > s * v2 )
* <=> q1 > q2 \/ (q1 = q2 /\ s * v1 > s * v2) *)
t_or (t_lt q2 q1)
(t_and (t_equ q1 q2)
(if s = 1 then t_lt v2 v1
else t_lt v1 v2))
| `Ge ->
s * v1 + b * q1 > = s * v2 + b * q2
* < = > q1 > q2 \/ ( q1 = q2 /\ s * v1 > = s * v2 )
* <=> q1 > q2 \/ (q1 = q2 /\ s * v1 >= s * v2) *)
t_or (t_lt q2 q1)
(t_and (t_equ q1 q2)
(if s = 1 then t_le v2 v1
else t_le v1 v2))
in
let do_simp s v1 v2 b =
(* p1 = s * v1 + p1', p2 = s * v2 + p2' *)
let p1' = p_sub p1 (p_mult (p_int s) (p_var v1)) in
let p2' = p_sub p2 (p_mult (p_int s) (p_var v2)) in
match p_divide p1' b, p_divide p2' b with
| None, _ | _, None -> None
| Some q1', Some q2' ->
p1 = s * v1 + b * q1 , p2 = s * v2 + b * q2
let q1 = from_polynomial q1' in
let q2 = from_polynomial q2' in
Some (mk_cmp s v1 v2 q1 q2 |> remove_trivial_comparison)
in
find_first vs1 @@
(fun (v1, s1) ->
(* debug "v1 = %a; s1 = %a@." Why3.Pretty.print_term v1
* Format.pp_print_int s1; *)
find_first vs2 @@
(fun (v2, s2) ->
(* debug "v2 = %a; s2 = %a@." Why3.Pretty.print_term v2
* Format.pp_print_int s2; *)
if s1 = s2 then
find_first (Mterm.find_def [] v2 bounds)
(fun b ->
if List.exists (p_equal b)
(Mterm.find_def [] v1 bounds)
then (do_simp s1 v1 v2 b)
else None)
else None))
else if vs1 = [] && vs2 = [] then
None
else
exactly one of p1 or p2 has the form s * v + q ;
* by swapping p1 and p2 if necessary , we may assume
* p1 = s * v + b * q1 , p2 = b * q2 , and 0 < = v < b
* by swapping p1 and p2 if necessary, we may assume
* p1 = s * v + b * q1, p2 = b * q2, and 0 <= v < b *)
let vs, p1, p2, cmp =
if vs1 <> [] then (vs1, p1, p2, cmp)
else (vs2, p2, p1,
match cmp with
`Le -> `Ge | `Lt -> `Gt | `Eq -> `Eq | `Ge -> `Le | `Gt -> `Lt)
in
let mk_cmp s v q1 q2 =
p1 = s * v + b * q1 ; p2 = b * q2
match cmp with
| `Lt ->
s * v + b * q1 < b * q2
* < = > q1 < q2 \/ ( q1 = q2 /\ s * v < 0 )
* < = > if s = 1 then q1 < q2
* else q1 < q2 \/ ( q1 = q2 /\ 0 < v )
* <=> q1 < q2 \/ (q1 = q2 /\ s * v < 0)
* <=> if s = 1 then q1 < q2
* else q1 < q2 \/ (q1 = q2 /\ 0 < v) *)
if s = 1 then t_lt q1 q2
else
t_or (t_lt q1 q2)
(t_and (t_equ q1 q2) (t_lt t_zero v))
| `Le ->
s * v + b * q1 < = b * q2
* < = > q1 < q2 \/ ( q1 = q2 /\ s * v < = 0 )
* < = > if s = 1 then q1 < q2 \/ ( q1 = q2 /\ v = 0 )
* else q1 < q2 \/ q1 = q2
* <=> q1 < q2 \/ (q1 = q2 /\ s * v <= 0)
* <=> if s = 1 then q1 < q2 \/ (q1 = q2 /\ v = 0)
* else q1 < q2 \/ q1 = q2 *)
t_or (t_lt q1 q2)
(if s = 1 then t_and (t_equ q1 q2) (t_equ v t_zero)
else t_equ q1 q2)
| `Eq ->
s * v + b * q1 = b * q2
* < = > q1 = q2 /\ v = 0
* <=> q1 = q2 /\ v = 0 *)
t_and (t_equ q1 q2) (t_equ v t_zero)
| `Gt ->
s * v + b * q1 > b * q2
* < = > q1 > q2 \/ ( q1 = q2 /\ s * v > 0 )
* < = > if s = 1 then q1 > q2 \/ ( q1 = q2 /\ 0 < v )
* else q1 > q2
* <=> q1 > q2 \/ (q1 = q2 /\ s * v > 0)
* <=> if s = 1 then q1 > q2 \/ (q1 = q2 /\ 0 < v)
* else q1 > q2 *)
if s = 1 then
t_or (t_gt q1 q2)
(t_and (t_equ q1 q2) (t_lt t_zero v))
else t_gt q1 q2
| `Ge ->
s * v + b * q1 > = b * q2
* < = > q1 > q2 \/ ( q1 = q2 /\ s * v > = 0 )
* < = > if s = 1 then q1 > q2 \/ q1 = q2
* else q1 > q2 \/ ( q1 = q2 /\ v = 0 )
* <=> q1 > q2 \/ (q1 = q2 /\ s * v >= 0)
* <=> if s = 1 then q1 > q2 \/ q1 = q2
* else q1 > q2 \/ (q1 = q2 /\ v = 0) *)
t_or (t_gt q1 q2)
(if s = 1 then t_equ q1 q2
else t_and (t_equ q1 q2) (t_equ v t_zero))
in
let do_simp1 b s v =
let p1' = p_sub p1 (p_mult (p_int s) (p_var v)) in
match p_divide p1' b, p_divide p2 b with
| None, _ | _, None -> None
| Some q1', Some q2' ->
let q1 = from_polynomial q1' in
let q2 = from_polynomial q2' in
debug "t1 = %a@." Why3.Pretty.print_term t1;
debug "t2 = %a@." Why3.Pretty.print_term t2;
debug "s, v = %a, %a@." Format.pp_print_int s Why3.Pretty.print_term v;
debug "b = %a@." Why3.Pretty.print_term (from_polynomial b);
debug "p1 = %a@." Why3.Pretty.print_term @@ from_polynomial p1;
debug "p1' = %a@." Why3.Pretty.print_term @@ from_polynomial p1';
debug "p2 = %a@." Why3.Pretty.print_term @@ from_polynomial p2;
debug "q1 = %a@." Why3.Pretty.print_term q1;
debug "q2 = %a@." Why3.Pretty.print_term q2;
Some (mk_cmp s v q1 q2)
in
find_first vs
(fun (v, s) ->
find_first (Mterm.find_def [] v bounds)
(fun b -> do_simp1 b s v))
else
(* found a common factor *)
let factor = List.fold_left p_mult (p_bigint n) @@ List.map p_var m in
(* debug "found common factor: %a@." Why3.Pretty.print_term (from_polynomial factor); *)
assert (I.gt n I.zero);
let q1 = match p_divide p1 factor with
| Some q -> from_polynomial q
| None -> implementation_error "in simplify_affine_formula"
in
let q2 = match p_divide p2 factor with
| Some q -> from_polynomial q
| None -> implementation_error "in simplify_affine_formula"
in
if m = [] then
(* factor is a (positive) constant; remove it *)
match cmp with
| `Lt -> Some (t_lt q1 q2)
| `Le -> Some (t_le q1 q2)
| `Eq -> Some (t_equ q1 q2)
| `Gt -> Some (t_gt q1 q2)
| `Ge -> Some (t_ge q1 q2)
else if (t_equal q1 t_one || t_equal q1 t_zero) &&
(t_equal q2 t_one || t_equal q2 t_zero)
then
(* factor is not a constant, but the quotient is trivial *)
None
else
let d = from_polynomial factor in
(* t1 = q1 * d <cmp> t2 = q2 * d *)
let result =
match cmp with
| `Le ->
q1 * d < = q2 * d < = > ( q1 < = q2 /\ d > = 0 ) \/ ( q1 > = q2 /\ d < = 0 )
t_or (t_and (t_le q1 q2) (t_le t_zero d))
(t_and (t_le q2 q1) (t_le d t_zero))
| `Lt ->
q1 * d < q2 * d < = > ( q1 < q2 /\ d > 0 ) \/ ( q1 > q2 /\ d < 0 )
t_or (t_and (t_lt q1 q2) (t_lt t_zero d))
(t_and (t_lt q2 q1) (t_lt d t_zero))
| `Eq ->
(* q1 * d = q2 * d <=> (q1 = q2 \/ d = 0) *)
t_or (t_equ q1 q2) (t_equ t_zero d)
| `Ge ->
q1 * d > = q2 * d < = > ( q1 > = q2 /\ d > = 0 ) \/ ( q1 < = q2 /\ d < = 0 )
t_or (t_and (t_le q2 q1) (t_le t_zero d))
(t_and (t_le q1 q2) (t_le d t_zero))
| `Gt ->
q1 * d > q2 * d < = > ( q1 > q2 /\ d > 0 ) \/ ( q1 < q2 /\ d < 0 )
t_or (t_and (t_lt q2 q1) (t_lt t_zero d))
(t_and (t_lt q1 q2) (t_lt d t_zero))
in Some (remove_trivial_comparison result)
let simplify_affine_formula task =
let filter_ub t =
(* returns [Some p] if t consists of a single term,
* where [p] is a polynomial corresponding to t *)
let p = to_polynomial t in
match p_repr p with
| [] | [_] -> Some p
| _ -> None
in
let bounds = Mterm.map (fun ubs ->
List.filter_map filter_ub @@ Sterm.elements ubs)
@@ collect_ls_bounds task
in
let is_atomic t = match t.t_node with
| Tvar _
| Tapp (_, [])
| Tconst _ -> true
| _ -> false
in
let rec simp bounds t =
match t.t_node with
| Tapp (ls, [t1; t2]) when is_int t1 ->
if is_atomic t1 && is_atomic t2 then t
else
let repeat = function
| Some t' ->
if t_equal t t' then t
else
(debug "simp %a@." Why3.Pretty.print_term t;
debug "==> %a@." Why3.Pretty.print_term t';
simp bounds @@ remove_trivial_comparison t')
| None -> t
in
if ls_equal ls ps_le then simp_op bounds `Le t1 t2 |> repeat
else if ls_equal ls ps_lt then
match simp_op bounds `Lt t1 t2 with
| Some _ as r -> repeat r
| None -> simp_op bounds `Le t1 (t_minus t2 t_one) |> repeat
else if ls_equal ls ps_equ then simp_op bounds `Eq t1 t2 |> repeat
else if ls_equal ls ps_ge then simp_op bounds `Ge t1 t2 |> repeat
else if ls_equal ls ps_gt then simp_op bounds `Gt t1 t2 |> repeat
else t
| Tquant (q, tq) ->
(* Problem: if i < N is added to a bound list,
* the procedure tries to remove i < N itself.
* As a workaround, we separate guards and body. *)
let (vss, triggers, body) = t_open_quant tq in
let bounds' =
List.fold_left (fun bounds vs ->
let v = t_var vs in
if is_int v && check_lower_bound q v body then
let ubs = Sterm.elements @@
find_upper_bounds q v body
|> List.filter_map
(fun ub ->
if t_v_occurs vs ub = 0 then
filter_ub ub
else None)
in
if ubs = [] then bounds
else Mterm.add v ubs bounds
else bounds)
bounds (List.rev vss)
in
let body' = simp bounds' body in
let guard =
List.map (fun vs ->
let ubs = Mterm.find_def [] (t_var vs) bounds' in
t_le t_zero (t_var vs) ::
List.map (fun ub -> t_lt (t_var vs) @@ from_polynomial ub) ubs)
vss
|> List.concat
|> t_and_simp_l
in
let body'' = match q with
| Tforall -> t_implies_simp guard body'
| Texists -> t_and_simp guard body'
in
t_quant_close_simp q vss triggers @@ simplify_guards body''
| _ ->
TermTF.t_map_simp (fun x -> x) (simp bounds) t
in
Why3util.transform_goal (simp bounds) task
(** ----------------unmerge quantifiers *)
(* not implemented yet *)
(* let unmerge_quantifiers task =
* let bounds = collect_ls_bounds task in
*
* Why3util.transform_goal (simp bounds) task *)
| null | https://raw.githubusercontent.com/SoftwareFoundationGroupAtKyotoU/VeriCUDA/8c62058af5362cb1bd6c86121d9b8742e31706f2/vctrans.ml | ocaml | decompose only when there is no trigger
* ---------------- eliminating quantifiers
Try to find the value of [vs] if it is unique in [t].
* If the value is found, returns a pair [t'] and [Some s]
* where [s] is the value, and [t'] is [t(vs:=s)].
t1 - t2 = s * x + p (= 0)
* ==> x = -s * p
* ---------------- merging quantifiers
A (node of a) term is said to be a polynomial node if
* - it is of type int, and
* - it is either variable, integer constant or an application whose
* operator is one of the ring operations.
We call a subterm [p] of [t] a prime polynomial node if
* - [p] is a polynomial node, and
* -- either [p = t], or
* -- the parent node of [p] is not a polynomial node.
[t] is a prime polynomial node of the formula in question.
Apply [really_process_polynomial] to every prime polynomial
* node of [t]. Parameter [p] is true iff the parent of the
* argument [t] is a polynomial (in particular [t] is not a root).
Returns [t'] such that
* when [q] is [Texists], [t] iff [0 <= v /\ t'], and
* when [q] is [Tforall], [t] iff [0 <= v -> t'].
*
* This function actually finds a subformula equivalent to [0 <= v]
* in appropriate positions, and replaces such subformulas with [true].
p = x + q, therefore [x <ls> -q].
is [x <ls> -q] equivalent to [x >= 0]?
is [x <ls> -q] equivalent to [x < 0]?
p = -x + q, therefore [q <ls> x].
is [q <ls> x] equivalent to [x >= 0]?
is [q <ls> x] equivalent to [x < 0]?
does [t1 /\ t2] imply [0 < v]?
does [v < 0] imply [t1 /\ t2]?
Here we are assuming that the domain of quantification
* is always non-empty.
Ignore let, case, eps, etc.
Returns the set of [u]'s such that:
* when [q] is [Texists], [t] implies [v < u], and
* when [q] is [Tforall], [t] is implied by [v >= u].
want: [v < u] for some u
p = v + q, therefore [x <ls> -q].
v <= -q, hence v < -q + 1
v < -q
want: [v >= u] for some u
v >= -q
v > -q, hence v >= -q + 1
want: [v < u] for some u
p = -v + q, therefore [q <ls> v].
q >= v, hence v < q + 1
q > v
want: [v >= u] for some u
q <= v
q < v, hence q + 1 < v
returns a polynomial [p] such that [t1 <ls> t2] iff [0 < p].
[t1 <= t2] iff [0 < t2 - t1 + 1]
[t1 < t2] iff [0 < t2 - t1]
[t1 >= t2] iff [0 < t1 - t2 + 1 ]
[t1 > t2] iff [0 < t1 - t2]
replace (as many as possible) subformulas of [t] with [true]
* which are implied by [0 <= vs < u].
Separate [t] into a list of quantified variables,
* a list of guards, and a body.
* [t] is logically equivalent to
* [t_quant_close_guard q vss [] (t_and_simp_l gs) b].
Guards are accumulated in the reverse order;
* but there is no strong reason for doing so.
triggers are removed here (any problem?)
Merge as many variables from [list] as possible, and returns
* the resulting formula and a list of variables used in it
* (both newly introduced ones and the ones that were not merged).
Found a pair to be merged.
[vs] and [vs'] are to be eliminated; they should not
* appear in the formula we are going to return, which is
* built from [t'], [ub], and [ub'].
Here [t] can be rewritten as (when [q] is [Tforall]):
* 0 <= vs_new < ub * ub' -> t'
* but the equivalence holds only if [ub] and [ub'] are positive.
* So in general we need more complex form
* 0 < ub /\ 0 < ub' /\ 0 <= vs_new < ub * ub' -> t'.
* The case of [Texists] is similar.
* Therefore the guard is
* 0 < ub /\ 0 < ub' /\ 0 <= vs_new < ub * ub'.
New list of variables, equipped with their upper bounds.
Add the guard above to the body, and try to merge
* remaining variables.
no more pairs to be merged
[list'] has length fewer than the original list.
* This means that some pair of variables are merged.
No variables are merged. Return the original formula.
No variables among [vss] are merged, but the variables in
* guards or body are merged.
* ---------------- eliminate existentials in premises
* ---------------- apply equalities in premises
To avoid infinite loop, make sure that [ls] does not
* appear in the rhs.
If [args] is [a1; a2; ...; an], this function checkes whether
* [t] has the form [get (... (get (get ls a1) a2) ...) an],
* and returns the list of terms corresponding to [a1], [a2], ...,
* [an] in the reverse order.
[t_occurs s t] is not necessarily true because of the
* simplification.
debug "apply_eqn_info %d@." (Why3.Task.task_hash task);
Slight optimization to suppress trivial axioms.
Nothing more to be rewritten.
[ls] is already declared, so we don't have to add it.
|> Why3.Trans.apply_transform "simplify_trivial_quantification"
* Why3api.env
|> Why3.Trans.apply_transform "simplify_trivial_quantification"
* Why3api.env
* ---------------- quantifier elimination
not false <=> true
not (C1 or C2 or ... or Cn)
* <=> not C1 and not (C2 or ... or Cn)
[t]: term, [vs]: variable
t1 - t2 = s * v + p
v = -s * p
assert (ls_equal ls ps_ge);
Some (t_app ls [from_polynomial p; t_zero] None)
In this case [vs] is not contained in [t], so this case
* is trivial.
List.iter print_literal c;
debug "eliminate_linear_quantifier_t: @[%a@]@." Why3.Pretty.print_term t;
Tries to eliminate variables in [vss], and returns a pair
* [vss_left, t'] where [vss_left] is the list of variables
* that are not eliminated, and [t'] is the resulting formula.
debug "eliminate_linear_quantifier: @[%a@]@." Why3.Pretty.print_term t;
* ---------------- replace anonymous functions with a variable
* ---------------- congruence
* ---------------- replace equality with [False]
perhaps this doesn't help much
Replace occurrences of [get _ _ = _] at positive positions
* with [False].
* ---------------- eliminate ls
Replace any occurrence of an atomic formula containing [ls]
* with true (if [sign] is true) or false (if [sign] is false).
Nothing more to be eliminated.
assume x >= y
in case t1 and t2 have a common factor;
* but we consider only common monomials
transpose terms with negative coefficients
t1 = t2 = 0
no common factor
here pi = s * vi + b * qi;
* note: we may assume 0 <= vi < b
p1 = s * v1 + p1', p2 = s * v2 + p2'
debug "v1 = %a; s1 = %a@." Why3.Pretty.print_term v1
* Format.pp_print_int s1;
debug "v2 = %a; s2 = %a@." Why3.Pretty.print_term v2
* Format.pp_print_int s2;
found a common factor
debug "found common factor: %a@." Why3.Pretty.print_term (from_polynomial factor);
factor is a (positive) constant; remove it
factor is not a constant, but the quotient is trivial
t1 = q1 * d <cmp> t2 = q2 * d
q1 * d = q2 * d <=> (q1 = q2 \/ d = 0)
returns [Some p] if t consists of a single term,
* where [p] is a polynomial corresponding to t
Problem: if i < N is added to a bound list,
* the procedure tries to remove i < N itself.
* As a workaround, we separate guards and body.
* ----------------unmerge quantifiers
not implemented yet
let unmerge_quantifiers task =
* let bounds = collect_ls_bounds task in
*
* Why3util.transform_goal (simp bounds) task |
# use " topfind " ; ;
# directory " /home / kozima/.opam/4.01.0 / lib / menhirLib " ; ;
# load " menhirLib.cmo " ; ;
# require " why3 " ; ;
# require " cil " ; ;
#use "topfind";;
#directory "/home/kozima/.opam/4.01.0/lib/menhirLib";;
#load "menhirLib.cmo";;
#require "why3";;
#require "cil";;
*)
open Why3.Term
open Why3api
open Formula
open Vc
open Utils
open ExtList
module I = Why3.BigInt
open Why3util
open Why3util.PTerm
* ---------------- Decompose quantifications over thread
let t_is_valid_tid_inline t =
let zero = t_zero in
t_and_simp_l [
t_le zero (t_x t); t_le zero (t_y t); t_le zero (t_z t);
t_lt (t_x t) t_bdimx; t_lt (t_y t) t_bdimy; t_lt (t_z t) t_bdimz;
]
let t_is_valid_bid_inline t =
let zero = t_zero in
t_and_simp_l [
t_le zero (t_x t); t_le zero (t_y t); t_le zero (t_z t);
t_lt (t_x t) t_gdimx; t_lt (t_y t) t_gdimy; t_lt (t_z t) t_gdimz;
]
let rec inline_is_valid_thread t =
match t.t_node with
| Tapp (ls, [t']) when ls_equal ls ps_is_valid_thread ->
begin
match t'.t_node with
| Tapp (ls, [t1; t2]) when ls_equal ls (fs_tuple 2) ->
t_and_simp (t_is_valid_bid_inline t1) (t_is_valid_tid_inline t2)
| _ ->
TermTF.t_map_simp (fun t -> t) inline_is_valid_thread t
end
| _ ->
TermTF.t_map_simp (fun t -> t) inline_is_valid_thread t
let decomposing_quant q vss body =
let rec rewrite_body vss acc_vs body =
match vss with
| [] -> acc_vs, body
| vs::vss' ->
if Why3.Ty.ty_equal vs.vs_ty ty_thread then
let bx = create_vsymbol (Why3.Ident.id_fresh "b_x") ty_int in
let by = create_vsymbol (Why3.Ident.id_fresh "b_y") ty_int in
let bz = create_vsymbol (Why3.Ident.id_fresh "b_z") ty_int in
let tx = create_vsymbol (Why3.Ident.id_fresh "t_x") ty_int in
let ty = create_vsymbol (Why3.Ident.id_fresh "t_y") ty_int in
let tz = create_vsymbol (Why3.Ident.id_fresh "t_z") ty_int in
let th = t_tuple [t_dim3 (t_var bx) (t_var by) (t_var bz);
t_dim3 (t_var tx) (t_var ty) (t_var tz)]
in
t_subst_single vs th body
|> inline_is_valid_thread
|> compute_thread_projections
|> simplify_formula
|> simplify_dim3_equality
|> rewrite_body vss' (bx :: tx :: by :: ty :: bz :: tz :: acc_vs)
else if Why3.Ty.ty_equal vs.vs_ty ty_dim3 then
let x = create_vsymbol (Why3.Ident.id_fresh "d_x") ty_int in
let y = create_vsymbol (Why3.Ident.id_fresh "d_y") ty_int in
let z = create_vsymbol (Why3.Ident.id_fresh "d_z") ty_int in
let d = t_dim3 (t_var x) (t_var y) (t_var z) in
t_subst_single vs d body
|> inline_is_valid_thread
|> compute_thread_projections
|> simplify_formula
|> simplify_dim3_equality
|> rewrite_body vss' (x :: y :: z :: acc_vs)
else
rewrite_body vss' (vs :: acc_vs) body
in
let (vss, body) = rewrite_body vss [] body in
t_quant_close_simp q vss [] body
let rec decompose_thread_quant t =
match t.t_node with
| Tquant (q, tq) ->
let (vss, tr, body) = t_open_quant tq in
if tr = [] &&
List.exists (fun vs ->
Why3.Ty.ty_equal vs.vs_ty ty_thread
|| Why3.Ty.ty_equal vs.vs_ty ty_dim3) vss then
decomposing_quant q vss @@ decompose_thread_quant body
else
TermTF.t_map_simp (fun t -> t) decompose_thread_quant t
| _ -> TermTF.t_map_simp (fun t -> t) decompose_thread_quant t
maybe optimizable using a method similar to
* why3 - 0.85 / src / transform / simplify_formula.ml ,
* find the value [ s ] , substitute to [ vs ] in the whole formula ,
* and then simplify it modulo ring equality using polynomial repr . above .
* why3-0.85/src/transform/simplify_formula.ml,
* find the value [s], substitute to [vs] in the whole formula,
* and then simplify it modulo ring equality using polynomial repr. above. *)
let rec eliminate_unique_quant_1 bvars sign vs t =
match t.t_node with
| Tapp (ls, [t1; t2])
when sign && ls_equal ls ps_equ && is_int t1 &&
Mvs.set_disjoint (t_vars t) bvars ->
begin
match isolate_var (t_var vs)
(p_sub (to_polynomial t1) (to_polynomial t2))
with
| None -> (t, None)
| Some (p, _) when t_v_occurs vs (from_polynomial p) > 0 -> (t, None)
| Some (p, s) ->
let p' = if s = 1 then (p_neg p) else p in
(t_true, Some (from_polynomial p'))
end
| Tbinop (Tor, t1, t2) when not sign ->
let (t1', r1) = eliminate_unique_quant_1 bvars sign vs t1 in
begin
match r1 with
| None ->
assert (t_equal t1 t1');
let (t2', r2) = eliminate_unique_quant_1 bvars sign vs t2 in
begin
match r2 with
| None ->
assert (t_equal t2 t2');
(t, None)
| Some s -> (t_or_simp (t_subst_single vs s t1) t2', r2)
end
| Some s ->
(t_or_simp t1' (t_subst_single vs s t2), r1)
end
| Tbinop (Tand, t1, t2) when sign ->
let (t1', r1) = eliminate_unique_quant_1 bvars sign vs t1 in
begin
match r1 with
| None ->
assert (t_equal t1 t1');
let (t2', r2) = eliminate_unique_quant_1 bvars sign vs t2 in
begin
match r2 with
| None ->
assert (t_equal t2 t2');
(t, None)
| Some s ->
(t_and_simp (t_subst_single vs s t1) t2', r2)
end
| Some s ->
(t_and_simp t1' (t_subst_single vs s t2), r1)
end
| Tbinop (Timplies, t1, t2) when not sign ->
let (t1', r1) = eliminate_unique_quant_1 bvars (not sign) vs t1 in
begin
match r1 with
| None ->
assert (t_equal t1 t1');
let (t2', r2) = eliminate_unique_quant_1 bvars sign vs t2 in
begin
match r2 with
| None ->
assert (t_equal t2 t2');
(t, None)
| Some s ->
(t_implies_simp (t_subst_single vs s t1) t2', r2)
end
| Some s ->
(t_implies_simp t1' (t_subst_single vs s t2), r1)
end
| Tnot t' ->
let (t'', r) = eliminate_unique_quant_1 bvars (not sign) vs t' in
t_not_simp t'', r
| Tquant (q, tq) ->
let (vsyms, triggers, body, cb) = t_open_quant_cb tq in
let bvars' = List.fold_left (fun bvs v -> Mvs.add v 1 bvs) bvars vsyms in
let (t', r) = eliminate_unique_quant_1 bvars' sign vs body in
t_quant q (cb vsyms triggers t'), r
| _ -> (t, None)
let rec eliminate_unique_quant t =
match t.t_node with
| Tquant (q, tq) ->
begin
match t_open_quant tq with
| (vss, [], body) ->
let sign = match q with Tforall -> false | Texists -> true in
let rec elim vss vss_rem t =
match vss with
| [] -> t_quant_close_simp q vss_rem [] t
| vs :: vss' ->
let (t', r) = eliminate_unique_quant_1 Mvs.empty sign vs t in
match r with
| None ->
assert (t_equal t t');
elim vss' (vs :: vss_rem) t'
| Some _ ->
elim vss' vss_rem t'
in elim vss [] @@ eliminate_unique_quant body
| (vsyms, triggers, body) ->
t_quant_close q vsyms triggers (eliminate_unique_quant body)
end
| _ -> TermTF.t_map_simp (fun t -> t) eliminate_unique_quant t
Try to find a subformula equivalent to either
* forall x y. 0 < = x < a - > 0 < = y < b - > P ( x + a * y )
* exists x y. 0 < = x < a /\ 0 < = y < b /\ P ( x + a * y )
* and replace it with
* a < = 0 \/ b < = 0 \/ forall z. 0 < = z < a * b - > P z
* a > 0 /\ b > 0 /\ exists 0 < = z < a * b /\ P z
* respectively .
* forall x y. 0 <= x < a -> 0 <= y < b -> P (x + a * y)
* exists x y. 0 <= x < a /\ 0 <= y < b /\ P (x + a * y)
* and replace it with
* a <= 0 \/ b <= 0 \/ forall z. 0 <= z < a * b -> P z
* a > 0 /\ b > 0 /\ exists z. 0 <= z < a * b /\ P z
* respectively. *)
let is_polynomial_node t =
match t.t_node with
| Tvar vs -> Why3.Ty.ty_equal vs.vs_ty ty_int
| Tconst (Why3.Number.ConstInt _) -> true
| Tapp (ls, _) ->
ls_equal ls fs_plus
|| ls_equal ls fs_minus
|| ls_equal ls fs_mult
|| ls_equal ls fs_uminus
| _ -> false
exception CannotReduceVariables
let really_process_polynomial x a y z t =
let p = to_polynomial t in
Given p(a , x , y ) , a polynomial in a , x , and y , returns a
* polynomial g(a , z ) such that g(a , x + a * y ) = p(a , x , y ) . If
* there is no such f , returns [ None ] .
* Lemma : p(a , x , y ) is written in the form g(a , x + a * y )
* if and only if p(a , x , y ) = p(a , x + a * y , 0 ) .
* In this case g can be taken as g(a , z ) = p(a , z , 0 ) .
* polynomial g(a, z) such that g(a, x + a * y) = p(a, x, y). If
* there is no such f, returns [None].
* Lemma: p(a, x, y) is written in the form g(a, x + a * y)
* if and only if p(a, x, y) = p(a, x + a * y, 0).
* In this case g can be taken as g(a, z) = p(a, z, 0). *)
let p_a = to_polynomial a in
let p_x = to_polynomial x in
let p_y = to_polynomial y in
if p_equal p (p_subst x (p_add p_x (p_mult p_a p_y))
(p_subst y p_zero p))
then from_polynomial @@ p_subst x (p_var z) (p_subst y p_zero p)
else raise CannotReduceVariables
let process_polynomial x a y z t =
let rec f p t =
if is_polynomial_node t then
let t' = t_map_simp (f true) t in
if p then t' else really_process_polynomial x a y z t'
else t_map_simp (f false) t
in f false t
let rec try_reduce_vars x a y z t =
match t.t_node with
| Tvar _ -> if t_equal t x || t_equal t y
then raise CannotReduceVariables
else t
| Tapp (ls, [t1; t2]) when is_int t1 && is_cmp_op ls ->
let t' = process_polynomial x a y z (t_minus t1 t2) in
t_app ls [t'; t_zero] None
| Tapp (ls, ts) ->
if is_formula t then t_map_simp (try_reduce_vars x a y z) t
else process_polynomial x a y z t
| _ ->
t_map_simp (try_reduce_vars x a y z) t
let reduce_variables q vs1 bound1 vs2 bound2 t =
assert (is_formula t);
let new_vs = create_vsymbol (Why3.Ident.id_fresh "z") ty_int in
let v1 = t_var vs1 in
let v2 = t_var vs2 in
let v = t_var new_vs in
try
let t' = try_reduce_vars v1 bound1 v2 v t in new_vs, t'
with CannotReduceVariables ->
let t' = try_reduce_vars v2 bound2 v1 v t in new_vs, t'
let check_lower_bound q v t =
let check_cmp pos ls t1 t2 =
let p = p_sub (to_polynomial t1) (to_polynomial t2) in
match isolate_var v p with
| Some (q, 1) ->
if pos then
ls_equal ls ps_ge && p_equal q p_zero
|| ls_equal ls ps_gt && p_equal q (p_int 1)
else
ls_equal ls ps_le && p_equal q (p_int 1)
|| ls_equal ls ps_lt && p_equal q p_zero
| Some (q, s) ->
assert (s = -1);
if pos then
ls_equal ls ps_le && p_equal q p_zero
|| ls_equal ls ps_lt && p_equal q (p_int (-1))
else
ls_equal ls ps_ge && p_equal q (p_int (-1))
|| ls_equal ls ps_gt && p_equal q p_zero
| None -> false
in
let rec check pos t =
match t.t_node with
| Tapp (ls, [t1; t2]) when is_int t1 && is_cmp_op ls ->
check_cmp pos ls t1 t2
| Tbinop (Tand, t1, t2) ->
if pos then
check pos t1 || check pos t2
else
check pos t1 && check pos t2
| Tbinop (Tor, t1, t2) ->
if pos then
check pos t1 && check pos t2
else
check pos t1 || check pos t2
| Tbinop (Timplies, t1, t2) ->
if pos then
check (not pos) t1 && check pos t2
else
check (not pos) t1 || check pos t2
| Tbinop (Tiff, t1, t2) ->
check pos (t_and (t_implies t1 t2) (t_implies t2 t1))
| Tnot t' ->
check (not pos) t'
| Tquant (q, tq) ->
let (_, _, t') = t_open_quant tq in
check pos t'
| _ ->
false
in check (q = Texists) t
let find_upper_bounds q v t =
let rec find pos t =
match t.t_node with
| Tapp (ls, [t1; t2]) when is_int t1 && is_cmp_op ls ->
let p = p_sub (to_polynomial t1) (to_polynomial t2) in
begin
match isolate_var v p with
| Some (q, 1) ->
if ls_equal ls ps_le then
Sterm.singleton (from_polynomial (p_add (p_int 1) (p_neg q)))
else if ls_equal ls ps_lt then
Sterm.singleton (from_polynomial (p_neg q))
else
Sterm.empty
if ls_equal ls ps_ge then
Sterm.singleton (from_polynomial (p_neg q))
else if ls_equal ls ps_gt then
Sterm.singleton (from_polynomial (p_add (p_int 1) (p_neg q)))
else
Sterm.empty
| Some (q, s) ->
assert (s = -1);
if ls_equal ls ps_ge then
Sterm.singleton (from_polynomial (p_add (p_int 1) q))
else if ls_equal ls ps_gt then
Sterm.singleton (from_polynomial q)
else
Sterm.empty
if ls_equal ls ps_le then
Sterm.singleton (from_polynomial q)
else if ls_equal ls ps_lt then
Sterm.singleton (from_polynomial (p_add (p_int 1) q))
else
Sterm.empty
| None -> Sterm.empty
end
| Tbinop (Tand, t1, t2) ->
if pos then
Sterm.union (find pos t1) (find pos t2)
else
Sterm.inter (find pos t1) (find pos t2)
| Tbinop (Tor, t1, t2) ->
if pos then
Sterm.inter (find pos t1) (find pos t2)
else
Sterm.union (find pos t1) (find pos t2)
| Tbinop (Timplies, t1, t2) ->
if pos then
Sterm.inter (find (not pos) t1) (find pos t2)
else
Sterm.union (find (not pos) t1) (find pos t2)
| Tnot t' ->
find (not pos) t'
| Tquant (q, tq) ->
let (_, _, t') = t_open_quant tq in
find pos t'
| _ -> Sterm.empty
in find (q = Texists) t
let polynomial_of_inequality ls t1 t2 =
let p1, p2 = to_polynomial t1, to_polynomial t2 in
if ls_equal ls ps_le then
p_add (p_sub p2 p1) (p_int 1)
else if ls_equal ls ps_lt then
p_sub p2 p1
else if ls_equal ls ps_ge then
p_add (p_sub p1 p2) (p_int 1)
else if ls_equal ls ps_gt then
p_sub p2 p1
else
implementation_error "invalid argument to polynomial_of_inequality"
let replace_guard_formula vs u t =
let p1 = polynomial_of_inequality ps_le t_zero (t_var vs) in
let p2 = polynomial_of_inequality ps_lt (t_var vs) u in
let is_non_negative p = p_is_const p && I.le I.zero (p_const_part p) in
let rec replace t =
match t.t_node with
| Tapp (ls, [t1; t2]) when is_int t1 && is_cmp_op ls &&
not @@ ls_equal ls ps_equ ->
let p = polynomial_of_inequality ls t1 t2 in
We have to check [ 0 < p ] implies either [ 0 < p1 ] or [ 0 < p2 ] .
* Either [ p < = p1 ] or [ p < = p2 ] is sufficient ( but not necessary ) .
* We simply check that either [ ] or [ p2 - p ] is a non - negative
* constant .
* Either [p <= p1] or [p <= p2] is sufficient (but not necessary).
* We simply check that either [p1 - p] or [p2 - p] is a non-negative
* constant. *)
if is_non_negative (p_sub p1 p) || is_non_negative (p_sub p2 p)
then t_true
else t
| _ ->
TermTF.t_map_simp (fun t -> t) replace t
in replace t
let rec merge_quantifiers t =
match t.t_node with
| Tquant (q, _) ->
let vss, gs, b =
let rec separate q qvss gs t =
match t.t_node with
| Tquant (q', tq) when q = q' ->
let (vss, _, t') = t_open_quant tq in
separate q (qvss @ vss) gs t'
| Tbinop (op, t1, t2)
when (q = Tforall && op = Timplies) ||
(q = Texists && op = Tand)
-> separate q qvss (t1 :: gs) t2
| _ ->
qvss, gs, t
in
separate q [] [] t
in
Merge inner quantifiers first ;
* [ t ] is equivalent to [ [ ] t ' ]
* [t] is equivalent to [t_quant_close q vss [] t'] *)
let gs' = List.rev_map merge_quantifiers gs in
let b' = merge_quantifiers b in
let t' =
match q with
| Tforall -> t_implies_simp (t_and_simp_l gs') b'
| Texists -> t_and_simp (t_and_simp_l gs') b'
in
Partition [ vss ] into two ; bounded and unbounded ones .
* Bounded variables should essentially be guarded by [ 0 < = x < u ]
* for some term [ u ] , otherwise a variable is considered unbounded .
* [ vs_ub_list ] is a list of bounded variables each of which is
* associated with its upper bound , and [ vs_nb ] consists of unbounded
* ones .
* Bounded variables should essentially be guarded by [0 <= x < u]
* for some term [u], otherwise a variable is considered unbounded.
* [vs_ub_list] is a list of bounded variables each of which is
* associated with its upper bound, and [vs_nb] consists of unbounded
* ones. *)
let vs_ub_list, vs_nb =
List.fold_left (fun (b, nb) vs ->
if check_lower_bound q (t_var vs) t' then
let ubs = Sterm.elements @@
find_upper_bounds q (t_var vs) t'
|> List.filter (fun ub ->
t_v_occurs vs ub = 0)
in
if ubs = [] then b, vs :: nb
else (vs, ubs) :: b, nb
else b, vs :: nb)
([], []) (List.rev vss)
in
let merge'' q vs ub vs' ub' t =
assert (t_v_occurs vs ub = 0);
assert (t_v_occurs vs' ub' = 0);
if t_v_occurs vs' ub = 0 && t_v_occurs vs ub' = 0 then
try
let vs_new, t' = reduce_variables q vs ub vs' ub' t in
Some (vs_new, vs, vs', ub, ub', t')
with CannotReduceVariables -> None
else None
in
let rec merge' vs ub l t =
match l with
| [] -> None
| (vs', ubs') :: l' ->
try Some (List.find_map (fun ub' ->
merge'' q vs ub vs' ub' @@
replace_guard_formula vs' ub' t)
ubs')
with Not_found -> merge' vs ub l' t
in
let rec merge l t =
match l with
| [] | [_] -> None
| (vs, ubs) :: l' ->
try Some (List.find_map (fun ub ->
merge' vs ub l' @@
replace_guard_formula vs ub t)
ubs)
with Not_found -> merge l' t
in
let rec merge_all list t =
match merge list t with
| Some (vs_new, vs, vs', ub, ub', t') ->
assert (t_v_occurs vs t' = 0);
assert (t_v_occurs vs' t' = 0);
assert (List.exists (fun (vs'', _) -> vs_equal vs'' vs) list);
assert (List.exists (fun (vs'', _) -> vs_equal vs'' vs') list);
let guard = t_and_simp_l [
t_pos ub;
t_pos ub';
t_le t_zero (t_var vs_new);
t_lt (t_var vs_new) (t_mult ub ub')]
|> remove_trivial_comparison
in
let list' =
(vs_new, [t_mult ub ub']) ::
List.filter
(fun (vs'', _) ->
not (vs_equal vs' vs'' || vs_equal vs vs''))
list
in
merge_all list' @@
if q = Tforall then
t_implies_simp guard t'
else
t_and_simp guard t'
| None ->
list, t
in
let list', t'' = merge_all vs_ub_list t' in
if List.length list' < List.length vs_ub_list then
t_quant_close_simp q (List.map fst list' @ vs_nb) [] t''
else if List.for_all2 t_equal gs gs' && t_equal b b' then
t
else
t_quant_close_simp q vss [] t''
| _ ->
TermTF.t_map_simp (fun t -> t) merge_quantifiers t
let merge_quantifiers t =
let t' = merge_quantifiers t in
if not @@ t_equal t t' then
debug "merge quantifiers: %a@. -->@. %a@."
Why3.Pretty.print_term t Why3.Pretty.print_term t'
else
debug "merge quantifiers fails: %a@."
Why3.Pretty.print_term t;
t'
let rec eliminate_existential_in_premises task =
let destruct d = match d.Why3.Decl.d_node with
| Why3.Decl.Dprop (k, pr, { t_node = Tquant (Texists, tq) }) ->
begin
match t_open_quant tq with
| (vss, [], body) ->
let alist =
List.map (fun vs ->
let ls =
create_lsymbol
(Why3.Ident.id_clone vs.vs_name)
[] (Some vs.vs_ty) in
(vs, ls))
vss
in
let body' =
List.fold_left (fun t (vs, ls) ->
t_subst_single vs (fs_app ls [] vs.vs_ty) t)
body alist
in
List.map (fun (_, ls) -> Why3.Decl.create_param_decl ls) alist @
[Why3.Decl.create_prop_decl k pr body']
| _ -> [d]
end
| _ -> [d]
in
Why3.Trans.apply (Why3.Trans.decl destruct None) task
type complex_eqn = {
ce_vars : vsymbol list;
ce_guards : term list;
ce_ls : lsymbol;
ce_args : term list;
ce_rhs : term;
}
type simple_eqn = {
se_ls : lsymbol;
se_lhs : term;
se_rhs : term;
}
type eqn =
| SimpleEqn of simple_eqn
| ComplexEqn of complex_eqn
type eqn_info = {
ei_eqn : eqn;
ei_ps : Why3.Decl.prsymbol;
}
let eqn_info_ls = function
| { ei_eqn = SimpleEqn { se_ls = ls } }
| { ei_eqn = ComplexEqn { ce_ls = ls } } -> ls
let print_complex_eqn fmt = function
{ ce_vars = vars;
ce_guards = guards;
ce_ls = ls;
ce_args = args;
ce_rhs = rhs; } ->
Format.fprintf fmt
"@[{ ce_vars = %a;@. \
ce_guards = %a;@. \
ce_ls = %a;@. \
ce_args = %a;@. \
ce_rhs = %a; }@.@]"
(fun fmt vss ->
Format.fprintf fmt "[";
List.iter (Format.fprintf fmt "%a; " Why3.Pretty.print_vs)
vss;
Format.fprintf fmt "]")
vars
(fun fmt guards ->
Format.fprintf fmt "[";
List.iter (Format.fprintf fmt "%a; " Why3.Pretty.print_term)
guards;
Format.fprintf fmt "]")
guards
Why3.Pretty.print_ls
ls
(fun fmt guards ->
Format.fprintf fmt "[";
List.iter (Format.fprintf fmt "%a; " Why3.Pretty.print_term)
guards;
Format.fprintf fmt "]")
args
Why3.Pretty.print_term rhs
let rec extract_complex_eqn f =
Extract complex_eqn from [ f ] .
* If [ f ] is of the form
* forall xs1 . gs1 - > forall xs2 . gs2 - > ... forall xsn . gsn - >
* ls[arg1][arg2] ... [argm ] = rhs
* then returns
* Some
* { = xs1 @ xs2 @ ... @ xsn ;
* ce_guards = [ gs1 ; gs2 ; ... ; gsn ] ;
* ce_ls = ls ; ce_args = [ argm ; ... ; ; arg1 ] ;
* = rhs } .
* If [f] is of the form
* forall xs1. gs1 -> forall xs2. gs2 -> ... forall xsn. gsn ->
* ls[arg1][arg2]...[argm] = rhs
* then returns
* Some
* { ce_vars = xs1 @ xs2 @ ... @ xsn;
* ce_guards = [gs1; gs2; ...; gsn];
* ce_ls = ls; ce_args = [argm; ...; arg2; arg1];
* ce_rhs = rhs }. *)
match f.t_node with
| Tapp (ls, [lhs; rhs]) when ls_equal ps_equ ls ->
let rec f t = match t.t_node with
| Tapp (ls, []) -> Some (ls, [])
| Tapp (ls, [t1; t2]) when ls_equal ls fs_get ->
begin
match f t1 with
| Some (ls', args) -> Some (ls', t2 :: args)
| None -> None
end
| _ -> None
in
begin
match f lhs with
| Some (ls, args)
when t_s_any (fun _ -> true) (ls_equal ls) rhs ->
Some { ce_vars = []; ce_guards = [];
ce_ls = ls; ce_args = args; ce_rhs = rhs; }
| _ -> None
end
| Tbinop (Timplies, f1, f2) ->
begin
match extract_complex_eqn f2 with
| Some e -> Some { e with ce_guards = f1 :: e.ce_guards }
| None -> None
end
| Tbinop ( Tand , f1 , f2 ) - >
* merge ( extract_ce_info f1 ) ( f2 )
* | ( Tiff , f1 , f2 ) - >
* merge ( f1 , f2 ) ( f2 , extract_ce_info f1 )
* merge (extract_ce_info f1) (extract_ce_info f2)
* | Tbinop (Tiff, f1, f2) ->
* merge (f1, extract_ce_info f2) (f2, extract_ce_info f1) *)
| Tquant (Tforall, tq) ->
let (vss, tr, f') = t_open_quant tq in
begin
match extract_complex_eqn f' with
| Some e -> Some { e with ce_vars = vss @ e.ce_vars; }
| None -> None
end
| _ -> None
let is_wf_eqn = function
{ ce_vars = vars;
ce_guards = guards;
ce_ls = ls;
ce_args = args;
ce_rhs = rhs; } ->
not (List.exists (t_ls_occurs ls) guards)
let extract_eqn t =
match t.t_node with
| Tapp (ls, [t1; t2]) when ls_equal ps_equ ls ->
Some (SimpleEqn { se_ls = ls; se_lhs = t1; se_rhs = t2 })
| _ -> match extract_complex_eqn t with
| Some e -> if is_wf_eqn e then Some (ComplexEqn e) else None
| None -> None
let collect_eqns task =
List.filter_map (fun decl ->
match decl.Why3.Decl.d_node with
| Why3.Decl.Dprop (Why3.Decl.Paxiom, ps, t) ->
begin
match extract_eqn t with
| Some e -> Some { ei_eqn = e; ei_ps = ps }
| None -> None
end
| _ -> None)
(Why3.Task.task_decls task)
let collect_eqns_test task =
let eqns = collect_eqns task in
if eqns = [] then debug "No equations found@."
else List.iter
(function
| { ei_eqn = SimpleEqn { se_lhs =lhs; se_rhs = rhs } } ->
debug "Found equation: %a = %a@."
Why3.Pretty.print_term lhs
Why3.Pretty.print_term rhs
| { ei_eqn =
ComplexEqn { ce_ls = ls; ce_args = args; ce_rhs = rhs; } } ->
let lhs =
List.fold_left t_get (t_app ls [] ls.ls_value)
(List.rev args)
in
debug "Found equation: %a = %a@."
Why3.Pretty.print_term lhs
Why3.Pretty.print_term rhs)
eqns
let rec match_lhs ls args t =
match t.t_node, args with
| Tapp (ls', []), [] when ls_equal ls ls' -> Some []
| Tapp (ls', [t1; t2]), a::args' when ls_equal ls' fs_get ->
begin
match match_lhs ls args' t1 with
| Some ts -> Some (t2 :: ts)
| None -> None
end
| _ -> None
let rec find_match bvs ls args t =
match match_lhs ls args t with
| Some ts ->
if Svs.exists (fun vs -> List.exists
(t_v_any (vs_equal vs)) ts)
bvs
then
At least one of [ ts ] contains a bound variable ; reject .
[]
else [(ts, t)]
| None ->
match t.t_node with
| Tquant (q, tq) ->
let (vss, _, t') = t_open_quant tq in
let bvs' = List.fold_right Svs.add vss bvs in
find_match bvs' ls args t'
| Teps b ->
let (vs, t') = t_open_bound b in
find_match (Svs.add vs bvs) ls args t'
| Tlet (t1, b) ->
let (vs, t2) = t_open_bound b in
find_match bvs ls args t1
@ find_match (Svs.add vs bvs) ls args t2
| _ ->
t_fold (fun acc t ->
find_match bvs ls args t @ acc)
[] t
let apply_simple_eqn { se_lhs = lhs; se_rhs = rhs } t =
t_replace lhs rhs t
let rec t_map_on_quant f t =
match t.t_node with
| Tquant _ -> t_map_simp f t
| _ -> t_map_simp (t_map_on_quant f) t
let rec apply_complex_eqn eqn seen t =
if t_ls_occurs eqn.ce_ls t then
match t.t_node with
| Tbinop (op, t1, t2) when not (t_ls_occurs eqn.ce_ls t1) ->
t_binary_simp op t1 (apply_complex_eqn eqn seen t2)
| Tbinop (op, t1, t2) when not (t_ls_occurs eqn.ce_ls t2) ->
t_binary_simp op (apply_complex_eqn eqn seen t1) t2
| _ ->
let matches = find_match Svs.empty eqn.ce_ls eqn.ce_args t
|> List.filter (fun (_, s) -> not (Sterm.mem s seen))
|> List.unique
~cmp:(fun (ts, t) (ts', t') ->
if t_equal t t' then
(assert (List.for_all2 t_equal ts ts'); true)
else false)
in
let seen' = List.fold_left
(fun seen (_, s) -> Sterm.add s seen)
seen matches
in
List.fold_left
(fun t (ts, s) ->
if t_occurs s t then
t_or_simp
(t_exists_close eqn.ce_vars [] @@
(t_and_simp_l [t_and_simp_l eqn.ce_guards;
t_and_simp_l (List.map2 t_equ_simp
eqn.ce_args ts);
t_replace s eqn.ce_rhs t]))
(t_and_simp
(t_not_simp
(t_exists_close eqn.ce_vars [] @@
(t_and_simp (t_and_simp_l eqn.ce_guards)
(t_and_simp_l (List.map2 t_equ_simp
eqn.ce_args ts)))))
t)
|> simplify_formula
else t)
t matches
|> t_map_on_quant (apply_complex_eqn eqn seen')
else
t
let apply_eqn_to_term e t =
match e with
| SimpleEqn e -> apply_simple_eqn e t
| ComplexEqn e -> apply_complex_eqn e Sterm.empty t
let rec apply_eqn_info task eqn_info =
match task with
| None -> None
| Some {
Why3.Task.task_decl = tdecl;
Why3.Task.task_prev = task_prev;
} ->
match tdecl.Why3.Theory.td_node with
| Why3.Theory.Decl {
Why3.Decl.d_node = Why3.Decl.Dprop (k, pr, t)
} when not (Why3.Decl.pr_equal pr eqn_info.ei_ps) ->
let task_prev' = apply_eqn_info task_prev eqn_info in
let t' = apply_eqn_to_term eqn_info.ei_eqn t in
if Why3.Task.task_equal task_prev task_prev' then
There is no further occurrence of [ lhs ] .
if t_equal t t' then
There is no occurrence of [ lhs ] in [ t ] , so we
* just leave [ task ] unchanged .
* just leave [task] unchanged. *)
task
else if k = Why3.Decl.Paxiom && is_tautology t' then
task_prev'
else
[ lhs ] occurs in [ t ] , so we should replace it with [ rhs ] .
* Since this is the first occurrence of [ lhs ] , we have to
* declare lsymbols in [ rhs ] here .
* Since this is the first occurrence of [lhs], we have to
* declare lsymbols in [rhs] here. *)
let lss = t_s_fold (fun s _ -> s)
(fun s ls -> Sls.add ls s)
Sls.empty t'
in
let task' =
Sls.fold (fun ls task ->
let decl = Why3.Decl.create_param_decl ls in
try Why3.Task.add_decl task decl
with Why3.Decl.RedeclaredIdent _ -> task)
lss task_prev
in
let decl = Why3.Decl.create_prop_decl k pr t' in
Why3.Task.add_decl task' decl
else
[ lhs ] occurs in [ task_prev ] , so lsymbols inside [ rhs ] is
* already declared in [ task_prev ' ] .
* already declared in [task_prev']. *)
if t_equal t t' then
Why3.Task.add_tdecl task_prev' tdecl
else if k = Why3.Decl.Paxiom && is_tautology t' then
task_prev'
else
let decl = Why3.Decl.create_prop_decl k pr t' in
Why3.Task.add_decl task_prev' decl
| Why3.Theory.Decl {
Why3.Decl.d_node = Why3.Decl.Dparam ls
} ->
if ls_equal ls (eqn_info_ls eqn_info) then
task
else
let task_prev' = apply_eqn_info task_prev eqn_info in
if Why3.Task.task_equal task_prev task_prev' then
There is no further occurrence of [ lhs ] .
* No changes needed .
* No changes needed. *)
task
else
There is an occurence of [ lhs ] in [ task_prev ] ;
* In this case [ ls ] may already be declared in [ task_prev ' ] ,
* but I do n't know an easy way to check it .
* Instead , just try to declare [ ls ] .
* If the attempt fails , return [ task_prev ' ] .
* In this case [ls] may already be declared in [task_prev'],
* but I don't know an easy way to check it.
* Instead, just try to declare [ls].
* If the attempt fails, return [task_prev']. *)
let decl = Why3.Decl.create_param_decl ls in
begin
try Why3.Task.add_decl task_prev' decl
with Why3.Decl.RedeclaredIdent _ -> task_prev'
end
| _ ->
let task_prev' = apply_eqn_info task_prev eqn_info in
if Why3.Task.task_equal task_prev task_prev' then
task
else
Why3.Task.add_tdecl task_prev' tdecl
let apply_eqn_info_simp tasks eqn_info =
List.map (fun task ->
apply_eqn_info task eqn_info
|> Why3.Trans.apply_transform "simplify_trivial_quantification"
Why3api.env)
tasks
|> List.concat
let rewrite_using_simple_premises task =
collect_eqns task
|> List.filter_map
(fun e -> match e with
| { ei_eqn = SimpleEqn _ } -> Some e
| _ -> None)
|> List.fold_left apply_eqn_info_simp [task]
|> List.map (task_map_decl simplify_guards)
let rewrite_using_premises task =
collect_eqns task
|> List.fold_left apply_eqn_info_simp [task]
|> List.map (task_map_decl simplify_guards)
let rec is_qf t =
match t.t_node with
| Tquant (_, _) -> false
| _ -> t_all is_qf t
type literal =
| Lit_le : polynomial -> literal
| Lit_ge : polynomial -> literal
| Lit_eq : polynomial -> literal
| Lit_const : term -> literal
let lit_not = function
| Lit_le p -> [[Lit_ge (p_add p (p_int 1))]]
| Lit_ge p -> [[Lit_le (p_sub p (p_int 1))]]
| Lit_eq p -> [[Lit_ge (p_add p (p_int 1))];
[Lit_le (p_sub p (p_int 1))]]
| Lit_const t -> [[Lit_const (t_not_simp t)]]
let clause_not c =
not ( L1 and ... and ) < = > ( not L1 ) or ... or ( not )
List.concat @@ List.map lit_not c
let lit_equal x y = match x, y with
| Lit_le p, Lit_le q
| Lit_ge p, Lit_ge q
| Lit_eq p, Lit_eq q -> p_equal p q
| Lit_const t, Lit_const t' -> t_equal t t'
| _, _ -> false
let clause_and c1 c2 =
let c = List.unique ~cmp:lit_equal @@ c1 @ c2 in
put multiple [ Lit_const ] 's into one
let rec f const cmps = function
| [] -> if t_equal const t_false then
[Lit_const t_false]
else if t_equal const t_true then
cmps
else
Lit_const const :: cmps
| Lit_const t :: c' -> f (t_and_simp const t) cmps c'
| l :: c' -> f const (l :: cmps) c'
in
f t_true [] c
let is_subset_of c c' =
List.for_all (fun l -> List.exists (lit_equal l) c') c
let has_subset_of f c =
List.exists (fun c' -> is_subset_of c' c) f
let rec dnf_or f1 f2 =
match f1 with
| [] -> f2
| c::f1' ->
if has_subset_of f2 c then dnf_or f1' f2 else c :: dnf_or f1' f2
let rec dnf_and f1 f2 =
match f1 with
| [] -> []
| c::f1' ->
( C1 or C2 or ... or Cn ) and f2
* < = > ( C1 and f2 ) or ( C2 and f2 ) or ... or ( Cn and f2 ) ;
* C and ( C1 or ... or Cn )
* < = > ( C and C1 ) or ( C and C2 ) or ... or ( C and Cn ) ;
* C and C1 < = > union of C and C1 ( considered as a clause )
* <=> (C1 and f2) or (C2 and f2) or ... or (Cn and f2);
* C and (C1 or ... or Cn)
* <=> (C and C1) or (C and C2) or ... or (C and Cn);
* C and C1 <=> union of C and C1 (considered as a clause) *)
dnf_or (List.map (clause_and c) f2) (dnf_and f1' f2)
let rec dnf_not = function
| c::cs ->
dnf_and (clause_not c) (dnf_not cs)
let dnf_implies f1 f2 = dnf_or (dnf_not f1) f2
let dnf_iff f1 f2 = dnf_and (dnf_implies f1 f2) (dnf_implies f2 f1)
let dnf_op op f1 f2 = match op with
| Tand -> dnf_and f1 f2
| Tor -> dnf_or f1 f2
| Timplies -> dnf_implies f1 f2
| Tiff -> dnf_iff f1 f2
let nnf_of t =
let rec nnf_pos t =
match t.t_node with
| Tbinop (op, t1, t2) ->
begin
match op with
| Tand -> t_and_simp (nnf_pos t1) (nnf_pos t2)
| Tor -> t_or_simp (nnf_pos t1) (nnf_pos t2)
| Timplies -> t_or_simp (nnf_neg t1) (nnf_pos t2)
| Tiff -> t_and_simp
(t_or_simp (nnf_neg t1) (nnf_pos t2))
(t_or_simp (nnf_neg t2) (nnf_pos t1))
end
| Tnot t -> nnf_neg t
| _ -> t
and nnf_neg t =
match t.t_node with
| Tbinop (op, t1, t2) ->
begin
match op with
| Tand -> t_or_simp (nnf_neg t1) (nnf_neg t2)
| Tor -> t_and_simp (nnf_neg t1) (nnf_neg t2)
| Timplies -> t_and_simp (nnf_pos t1) (nnf_neg t2)
| Tiff -> t_or_simp
(t_and_simp (nnf_pos t1) (nnf_neg t2))
(t_and_simp (nnf_pos t2) (nnf_neg t1))
end
| Tnot t -> nnf_pos t
| _ -> t_not_simp t
in nnf_pos t
let rec dnf_of vs t: literal list list option =
let rec dnf t =
match t.t_node with
| _ when not (t_v_any (vs_equal vs) t) -> Some [[Lit_const t]]
| Tapp (ls, [t1; t2]) when is_cmp_op ps_equ && is_int t1 ->
let p = p_sub (to_polynomial t1) (to_polynomial t2) in
if p_contains (t_var vs) p then
begin
match isolate_var (t_var vs) p with
| None -> None
| Some (p, _) when t_v_any (vs_equal vs) (from_polynomial p) -> None
| Some (p, s) ->
if ls_equal ls ps_equ then
Some [[Lit_eq (if s = 1 then (p_neg p) else p)]]
else if ls_equal ls ps_lt then
v < -p if s = 1 , and v > p if s = -1
* i.e. v < = -(p + 1 ) if s = 1 , and v > = p + 1 if s = -1
* i.e. v <= -(p + 1) if s = 1, and v >= p + 1 if s = -1 *)
if s = 1 then Some [[Lit_le (p_neg (p_add p (p_int 1)))]]
else Some [[Lit_ge (p_add p (p_int 1))]]
else if ls_equal ls ps_le then
v < = -p if s = 1 , and v > = p if s = -1
if s = 1 then Some [[Lit_le (p_neg p)]]
else Some [[Lit_ge p]]
else if ls_equal ls ps_gt then
v > -p if s = 1 , and v < p if s = -1
if s = 1 then Some [[Lit_ge (p_add (p_neg p) (p_int 1))]]
else Some [[Lit_le (p_sub p (p_int 1))]]
v > = -p if s = 1 , and v < = p if s = -1
if s = 1 then Some [[Lit_ge (p_neg p)]]
else Some [[Lit_le p]]
end
else
if t_v_any (vs_equal vs) (from_polynomial p) then
None
else
begin
match (from_polynomial p).t_node with
| Tconst (Why3.Number.ConstInt n) ->
let cmp =
if ls_equal ls ps_equ then I.eq
else if ls_equal ls ps_lt then I.lt
else if ls_equal ls ps_le then I.le
else if ls_equal ls ps_gt then I.gt
else I.ge
in
if cmp (Why3.Number.compute_int n) I.zero then
Some [[Lit_const t_true]]
else Some [[Lit_const t_false]]
| _ ->
Some [[Lit_const (t_app ls [from_polynomial p; t_zero] None)]]
end
| Tbinop (op, t1, t2) ->
begin
match dnf t1, dnf t2 with
| Some f1, Some f2 -> Some (dnf_op op f1 f2)
| _, _ -> None
end
| Tnot t1 ->
begin
match dnf t1 with
| Some f -> Some (dnf_not f)
| None -> None
end
| _ -> None
in dnf (nnf_of t)
let print_literal fmt = function
| Lit_le p -> Format.fprintf fmt "Lit_le (%a)"
Why3.Pretty.print_term (from_polynomial p)
| Lit_ge p -> Format.fprintf fmt "Lit_ge (%a)"
Why3.Pretty.print_term (from_polynomial p)
| Lit_eq p -> Format.fprintf fmt "Lit_eq (%a)"
Why3.Pretty.print_term (from_polynomial p)
| Lit_const c -> Format.fprintf fmt "Lit_const (%a)"
Why3.Pretty.print_term c
let print_dnf fmt f =
Format.fprintf fmt "[@[";
List.iter (fun c -> Format.fprintf fmt "[@[";
List.iter (Format.fprintf fmt "%a;@." print_literal) c;
Format.fprintf fmt "@]];@.")
f;
Format.fprintf fmt "@]]@."
let eliminate_quantifier_from_conj c =
let rec collect ubs lbs eqs consts = function
| [] -> ubs, lbs, eqs, consts
| Lit_le t :: c' -> collect (t :: ubs) lbs eqs consts c'
| Lit_ge t :: c' -> collect ubs (t :: lbs) eqs consts c'
| Lit_eq t :: c' -> collect ubs lbs (t :: eqs) consts c'
| Lit_const t :: c' -> collect ubs lbs eqs (t :: consts) c'
in
let p_ubs, p_lbs, p_eqs, consts = collect [] [] [] [] c in
let ubs = List.map from_polynomial p_ubs in
let lbs = List.map from_polynomial p_lbs in
let eqs = List.map from_polynomial p_eqs in
match eqs with
| [] ->
remove_trivial_comparison @@
t_and_simp
(t_and_simp_l @@
List.concat @@
List.map (fun l -> List.map (t_le l) ubs) lbs)
(t_and_simp_l consts)
| r :: rs ->
remove_trivial_comparison @@
t_and_simp_l @@
t_and_simp_l (List.map (t_equ_simp r) rs) ::
t_and_simp_l (List.map (t_le r) ubs) ::
t_and_simp_l (List.map (t_ge r) lbs) ::
consts
let eliminate_quantifier_from_dnf f =
List.map (fun c -> eliminate_quantifier_from_conj c) f
let eliminate_linear_quantifier_1 q vs t =
match q with
| Tforall ->
begin
match dnf_of vs (t_not_simp t) with
| Some f ->
let ts = eliminate_quantifier_from_dnf f in
Some (t_not_simp (t_or_simp_l ts))
| None ->
None
end
| Texists ->
match dnf_of vs t with
| Some f ->
let ts = eliminate_quantifier_from_dnf f in
Some (t_or_simp_l ts)
| None -> None
let rec eliminate_linear_quantifier_t t =
Eliminate inner quantifiers first .
let t = TermTF.t_map_simp (fun t -> t) eliminate_linear_quantifier_t @@
eliminate_unique_quant t
in
match t.t_node with
| Tquant (q, tq) ->
let vss, tr, t' = t_open_quant tq in
let rec elim vss t =
match vss with
| [] -> [], t
| vs::vss' ->
let (vss_left, t') = elim vss' t in
match eliminate_linear_quantifier_1 q vs t' with
| Some t'' -> vss_left, t''
| None -> vs::vss_left, t'
in
let vss_left, t'' = elim vss t' in
t_quant_close_simp q vss_left tr t''
| _ -> t
let eliminate_linear_quantifier task =
task_map_decl
(fun t ->
let t' = eliminate_unique_quant t
|> eliminate_linear_quantifier_t
|> simplify_formula
in
if not (t_equal t t') then
debug "eliminate_linear_quantifier rewrites@. %[email protected]@. %a@."
Why3.Pretty.print_term t Why3.Pretty.print_term t';
t')
task
let rec bind_epsilon_by_let t =
let rec collect bvs m t =
match t.t_node with
| Tlet (t', tb) ->
let m' = collect bvs m t' in
let (vs, t'') = t_open_bound tb in
collect (Svs.add vs bvs) m' t''
| Tcase _ -> not_implemented "bind_epsilon_by_let, case"
| Teps _ when Svs.for_all (fun vs -> t_v_occurs vs t = 0) bvs ->
if Mterm.mem t m then
Mterm.add t (Mterm.find t m + 1) m
else
Mterm.add t 1 m
| Tquant (_, tq) ->
let (vss, _, t') = t_open_quant tq in
collect (List.fold_right Svs.add vss bvs) m t'
| _ ->
t_fold (collect bvs) m t
in
let t' = TermTF.t_map_simp (fun t -> t) bind_epsilon_by_let t in
let m = collect Svs.empty Mterm.empty t' in
Mterm.fold
(fun te n t ->
if n > 1 then
match te.t_ty with
| Some ty ->
let vs = create_vsymbol (Why3.Ident.id_fresh "func") ty in
t_let_close vs te (t_replace_simp te (t_var vs) t')
| None -> t'
else t')
m t'
let apply_congruence t =
let modified = ref false in
let rec apply sign t =
match t.t_node with
| Tapp (ls, [t1; t2]) when ls_equal ls ps_equ ->
begin
match t1.t_node, t2.t_node with
| Tapp (ls, ts), Tapp (ls', ts')
when ls_equal ls ls' &&
List.for_all2 (fun t t' ->
match t.t_ty, t'.t_ty with
| None, None -> true
| Some ty, Some ty' -> Why3.Ty.ty_equal ty ty'
| _ -> false)
ts ts'
->
debug "congruence matching %a@." Why3.Pretty.print_term t;
t_and_simp_l @@ List.map2 t_equ_simp ts ts'
|> fun t ->
debug "returning %a@." Why3.Pretty.print_term t;
modified := true;
t
| _, _ -> t
end
| _ -> TermTF.t_map_sign (fun _ t -> t) apply sign t
in
let result = apply true t in
if !modified then Some result else None
let replace_equality_with_false t =
let rec replace sign t =
match t.t_node with
| Tapp (ls, [{t_node = Tapp (ls', ts)}; _])
when ls_equal ls ps_equ && ls_equal ls' fs_get ->
if sign then t_false else t_true
| Tbinop (Tand | Tor as op, t1, t2) ->
t_binary_simp op (replace sign t1) (replace sign t2)
| Tbinop (Timplies, t1, t2) ->
t_implies_simp (replace (not sign) t1) (replace sign t2)
| Tnot t' -> t_not_simp (replace (not sign) t')
| _ -> TermTF.t_map_simp (fun t -> t) (replace sign) t
in replace true t
|> fun t' ->
debug "replace %a@. into %a@."
Why3.Pretty.print_term t Why3.Pretty.print_term t';
t'
let rec eliminate_ls_t sign ls t =
match t.t_node with
| Tapp (_, _) ->
if t_ls_occurs ls t then
if sign then t_false else t_true
else t
| Tbinop ((Tand | Tor as op), t1, t2) ->
t_binary_simp op (eliminate_ls_t sign ls t1)
(eliminate_ls_t sign ls t2)
| Tbinop (Timplies, t1, t2) ->
t_implies_simp (eliminate_ls_t (not sign) ls t1)
(eliminate_ls_t sign ls t2)
| Tbinop (Tiff, t1, t2) ->
t_and_simp
(t_implies_simp (eliminate_ls_t (not sign) ls t1)
(eliminate_ls_t sign ls t2))
(t_implies_simp (eliminate_ls_t (not sign) ls t2)
(eliminate_ls_t sign ls t1))
| Tnot t' ->
t_not_simp (eliminate_ls_t (not sign) ls t')
| _ -> TermTF.t_map_simp (fun t -> t) (eliminate_ls_t sign ls) t
let eliminate_ls ls task =
let rec elim tdecls task =
match task with
| None -> tdecls, task
| Some {
Why3.Task.task_decl = tdecl;
Why3.Task.task_prev = task_prev;
} ->
match tdecl.Why3.Theory.td_node with
| Why3.Theory.Decl {
Why3.Decl.d_node = Why3.Decl.Dparam ls'
} when ls_equal ls' ls ->
tdecls, task_prev
| Why3.Theory.Decl {
Why3.Decl.d_node = Why3.Decl.Dprop (k, pr, t)
} ->
let t' = eliminate_ls_t (k = Why3.Decl.Pgoal) ls t in
if t_equal t' t_true && k <> Why3.Decl.Pgoal then
elim (tdecl :: tdecls) task_prev
else
elim ((Why3.Theory.create_decl @@
Why3.Decl.create_prop_decl k pr t') :: tdecls)
task_prev
| _ ->
elim (tdecl :: tdecls) task_prev
in
let tdecls, task = elim [] task
in List.fold_left Why3.Task.add_tdecl task tdecls
* ---------------- simplify affine ( in)equalities
let collect_ls_bounds task =
let decls = Why3.Task.task_decls task in
let rec collect decls acc =
match decls with
| decl :: decls' ->
let acc' =
match decl.Why3.Decl.d_node with
| Why3.Decl.Dparam ({ ls_args = []; ls_value = Some ty } as ls)
when Why3.Ty.ty_equal ty ty_int ->
if List.exists (function
| { Why3.Decl.d_node =
Why3.Decl.Dprop (Why3.Decl.Paxiom, _, ax) } ->
check_lower_bound Texists (t_ls ls) ax
| _ -> false)
decls'
then
List.map (function
| { Why3.Decl.d_node =
Why3.Decl.Dprop (Why3.Decl.Paxiom, _, ax) } ->
find_upper_bounds Texists (t_ls ls) ax
| _ -> Sterm.empty)
decls'
|> List.fold_left Sterm.union Sterm.empty
|> (fun ts -> Mterm.add (t_ls ls) ts acc)
else acc
| _ -> acc
in collect decls' acc'
| [] -> acc
in collect decls Mterm.empty
let why3_bigInt_gcd n1 n2 =
let rec euclid x y =
if I.eq I.zero y then x
else euclid y (I.euclidean_mod x y)
in
let x = I.abs n1 in
let y = I.abs n2 in
if I.ge x y then euclid x y else euclid y x
let term_list_intersect ts1 ts2 =
List.filter (fun t -> List.exists (t_equal t) ts1) ts2
let common_factor p =
let ts, ns = List.split (PTerm.p_repr p) in
let m =
match ts with
| t :: ts' -> List.fold_left term_list_intersect t ts'
| [] -> []
in
let n =
match ns with
| n :: ns' -> List.fold_left why3_bigInt_gcd n ns'
| [] -> I.zero
in
m, n
let from_polynomial_opt = function
| Some p -> from_polynomial p
| None -> implementation_error "from_polynomial_opt"
let rec find_first list f = match list with
| x :: xs ->
begin match f x with None -> find_first xs f | r -> r end
| [] -> None
let simp_op bounds cmp t1 t2 : term option =
let p1 = to_polynomial t1 in
let p2 = to_polynomial t2 in
let p1, p2 =
let p = p_repr @@ p_sub p1 p2 in
let pos, neg = List.partition (fun (_, n) -> I.gt n I.zero) p in
of_repr pos, p_neg (of_repr neg)
in
let m1, n1 = common_factor p1 in
let m2, n2 = common_factor p2 in
let m = if I.eq I.zero n1 then m2
else if I.eq I.zero n2 then m1
else term_list_intersect m1 m2
in
let n = why3_bigInt_gcd n1 n2 in
if I.eq n I.zero then
begin
assert (p_repr p1 = []);
assert (p_repr p2 = []);
match cmp with
| `Le | `Eq | `Ge -> Some t_true
| _ -> Some t_false
end
else if m = [] && I.eq n I.one then
let repr1 = p_repr p1 in
let repr2 = p_repr p2 in
let is_var = function
| [{ t_node = Tvar _ } as v], n
| [{ t_node = Tapp(_, []) } as v], n ->
if I.eq n I.one
then Some (v, 1)
else if I.eq n (I.minus I.one)
then Some (v, -1)
else None
| _ -> None
in
let vs1 = List.filter_map is_var repr1 in
let vs2 = List.filter_map is_var repr2 in
if vs1 <> [] && vs2 <> [] then
let _ =
debug "t1 = %a, and@." Why3.Pretty.print_term t1;
debug "t2 = %a@." Why3.Pretty.print_term t2;
in
let mk_cmp s v1 v2 q1 q2 =
match cmp with
| `Lt ->
s * v1 + b * q1 < s * v2 + b * q2
* < = > q1 < q2 \/ ( q1 = q2 /\ s * v1 < s * v2 )
* <=> q1 < q2 \/ (q1 = q2 /\ s * v1 < s * v2) *)
t_or (t_lt q1 q2)
(t_and (t_equ q1 q2)
(if s = 1 then t_lt v1 v2
else t_lt v2 v1))
| `Le ->
s * v1 + b * q1 < = s * v2 + b * q2
* < = > q1 < q2 \/ ( q1 = q2 /\ s * v1 < = s * v2 )
* <=> q1 < q2 \/ (q1 = q2 /\ s * v1 <= s * v2) *)
t_or (t_lt q1 q2)
(t_and (t_equ q1 q2)
(if s = 1 then t_le v1 v2
else t_le v2 v1))
| `Eq ->
s * v1 + b * q1 = s * v2 + b * q2
* < = > q1 = q2 /\ v1 = v2
* <=> q1 = q2 /\ v1 = v2 *)
t_and (t_equ q1 q2) (t_equ v1 v2)
| `Gt ->
s * v1 + b * q1 > s * v2 + b * q2
* < = > q1 > q2 \/ ( q1 = q2 /\ s * v1 > s * v2 )
* <=> q1 > q2 \/ (q1 = q2 /\ s * v1 > s * v2) *)
t_or (t_lt q2 q1)
(t_and (t_equ q1 q2)
(if s = 1 then t_lt v2 v1
else t_lt v1 v2))
| `Ge ->
s * v1 + b * q1 > = s * v2 + b * q2
* < = > q1 > q2 \/ ( q1 = q2 /\ s * v1 > = s * v2 )
* <=> q1 > q2 \/ (q1 = q2 /\ s * v1 >= s * v2) *)
t_or (t_lt q2 q1)
(t_and (t_equ q1 q2)
(if s = 1 then t_le v2 v1
else t_le v1 v2))
in
let do_simp s v1 v2 b =
let p1' = p_sub p1 (p_mult (p_int s) (p_var v1)) in
let p2' = p_sub p2 (p_mult (p_int s) (p_var v2)) in
match p_divide p1' b, p_divide p2' b with
| None, _ | _, None -> None
| Some q1', Some q2' ->
p1 = s * v1 + b * q1 , p2 = s * v2 + b * q2
let q1 = from_polynomial q1' in
let q2 = from_polynomial q2' in
Some (mk_cmp s v1 v2 q1 q2 |> remove_trivial_comparison)
in
find_first vs1 @@
(fun (v1, s1) ->
find_first vs2 @@
(fun (v2, s2) ->
if s1 = s2 then
find_first (Mterm.find_def [] v2 bounds)
(fun b ->
if List.exists (p_equal b)
(Mterm.find_def [] v1 bounds)
then (do_simp s1 v1 v2 b)
else None)
else None))
else if vs1 = [] && vs2 = [] then
None
else
exactly one of p1 or p2 has the form s * v + q ;
* by swapping p1 and p2 if necessary , we may assume
* p1 = s * v + b * q1 , p2 = b * q2 , and 0 < = v < b
* by swapping p1 and p2 if necessary, we may assume
* p1 = s * v + b * q1, p2 = b * q2, and 0 <= v < b *)
let vs, p1, p2, cmp =
if vs1 <> [] then (vs1, p1, p2, cmp)
else (vs2, p2, p1,
match cmp with
`Le -> `Ge | `Lt -> `Gt | `Eq -> `Eq | `Ge -> `Le | `Gt -> `Lt)
in
let mk_cmp s v q1 q2 =
p1 = s * v + b * q1 ; p2 = b * q2
match cmp with
| `Lt ->
s * v + b * q1 < b * q2
* < = > q1 < q2 \/ ( q1 = q2 /\ s * v < 0 )
* < = > if s = 1 then q1 < q2
* else q1 < q2 \/ ( q1 = q2 /\ 0 < v )
* <=> q1 < q2 \/ (q1 = q2 /\ s * v < 0)
* <=> if s = 1 then q1 < q2
* else q1 < q2 \/ (q1 = q2 /\ 0 < v) *)
if s = 1 then t_lt q1 q2
else
t_or (t_lt q1 q2)
(t_and (t_equ q1 q2) (t_lt t_zero v))
| `Le ->
s * v + b * q1 < = b * q2
* < = > q1 < q2 \/ ( q1 = q2 /\ s * v < = 0 )
* < = > if s = 1 then q1 < q2 \/ ( q1 = q2 /\ v = 0 )
* else q1 < q2 \/ q1 = q2
* <=> q1 < q2 \/ (q1 = q2 /\ s * v <= 0)
* <=> if s = 1 then q1 < q2 \/ (q1 = q2 /\ v = 0)
* else q1 < q2 \/ q1 = q2 *)
t_or (t_lt q1 q2)
(if s = 1 then t_and (t_equ q1 q2) (t_equ v t_zero)
else t_equ q1 q2)
| `Eq ->
s * v + b * q1 = b * q2
* < = > q1 = q2 /\ v = 0
* <=> q1 = q2 /\ v = 0 *)
t_and (t_equ q1 q2) (t_equ v t_zero)
| `Gt ->
s * v + b * q1 > b * q2
* < = > q1 > q2 \/ ( q1 = q2 /\ s * v > 0 )
* < = > if s = 1 then q1 > q2 \/ ( q1 = q2 /\ 0 < v )
* else q1 > q2
* <=> q1 > q2 \/ (q1 = q2 /\ s * v > 0)
* <=> if s = 1 then q1 > q2 \/ (q1 = q2 /\ 0 < v)
* else q1 > q2 *)
if s = 1 then
t_or (t_gt q1 q2)
(t_and (t_equ q1 q2) (t_lt t_zero v))
else t_gt q1 q2
| `Ge ->
s * v + b * q1 > = b * q2
* < = > q1 > q2 \/ ( q1 = q2 /\ s * v > = 0 )
* < = > if s = 1 then q1 > q2 \/ q1 = q2
* else q1 > q2 \/ ( q1 = q2 /\ v = 0 )
* <=> q1 > q2 \/ (q1 = q2 /\ s * v >= 0)
* <=> if s = 1 then q1 > q2 \/ q1 = q2
* else q1 > q2 \/ (q1 = q2 /\ v = 0) *)
t_or (t_gt q1 q2)
(if s = 1 then t_equ q1 q2
else t_and (t_equ q1 q2) (t_equ v t_zero))
in
let do_simp1 b s v =
let p1' = p_sub p1 (p_mult (p_int s) (p_var v)) in
match p_divide p1' b, p_divide p2 b with
| None, _ | _, None -> None
| Some q1', Some q2' ->
let q1 = from_polynomial q1' in
let q2 = from_polynomial q2' in
debug "t1 = %a@." Why3.Pretty.print_term t1;
debug "t2 = %a@." Why3.Pretty.print_term t2;
debug "s, v = %a, %a@." Format.pp_print_int s Why3.Pretty.print_term v;
debug "b = %a@." Why3.Pretty.print_term (from_polynomial b);
debug "p1 = %a@." Why3.Pretty.print_term @@ from_polynomial p1;
debug "p1' = %a@." Why3.Pretty.print_term @@ from_polynomial p1';
debug "p2 = %a@." Why3.Pretty.print_term @@ from_polynomial p2;
debug "q1 = %a@." Why3.Pretty.print_term q1;
debug "q2 = %a@." Why3.Pretty.print_term q2;
Some (mk_cmp s v q1 q2)
in
find_first vs
(fun (v, s) ->
find_first (Mterm.find_def [] v bounds)
(fun b -> do_simp1 b s v))
else
let factor = List.fold_left p_mult (p_bigint n) @@ List.map p_var m in
assert (I.gt n I.zero);
let q1 = match p_divide p1 factor with
| Some q -> from_polynomial q
| None -> implementation_error "in simplify_affine_formula"
in
let q2 = match p_divide p2 factor with
| Some q -> from_polynomial q
| None -> implementation_error "in simplify_affine_formula"
in
if m = [] then
match cmp with
| `Lt -> Some (t_lt q1 q2)
| `Le -> Some (t_le q1 q2)
| `Eq -> Some (t_equ q1 q2)
| `Gt -> Some (t_gt q1 q2)
| `Ge -> Some (t_ge q1 q2)
else if (t_equal q1 t_one || t_equal q1 t_zero) &&
(t_equal q2 t_one || t_equal q2 t_zero)
then
None
else
let d = from_polynomial factor in
let result =
match cmp with
| `Le ->
q1 * d < = q2 * d < = > ( q1 < = q2 /\ d > = 0 ) \/ ( q1 > = q2 /\ d < = 0 )
t_or (t_and (t_le q1 q2) (t_le t_zero d))
(t_and (t_le q2 q1) (t_le d t_zero))
| `Lt ->
q1 * d < q2 * d < = > ( q1 < q2 /\ d > 0 ) \/ ( q1 > q2 /\ d < 0 )
t_or (t_and (t_lt q1 q2) (t_lt t_zero d))
(t_and (t_lt q2 q1) (t_lt d t_zero))
| `Eq ->
t_or (t_equ q1 q2) (t_equ t_zero d)
| `Ge ->
q1 * d > = q2 * d < = > ( q1 > = q2 /\ d > = 0 ) \/ ( q1 < = q2 /\ d < = 0 )
t_or (t_and (t_le q2 q1) (t_le t_zero d))
(t_and (t_le q1 q2) (t_le d t_zero))
| `Gt ->
q1 * d > q2 * d < = > ( q1 > q2 /\ d > 0 ) \/ ( q1 < q2 /\ d < 0 )
t_or (t_and (t_lt q2 q1) (t_lt t_zero d))
(t_and (t_lt q1 q2) (t_lt d t_zero))
in Some (remove_trivial_comparison result)
let simplify_affine_formula task =
let filter_ub t =
let p = to_polynomial t in
match p_repr p with
| [] | [_] -> Some p
| _ -> None
in
let bounds = Mterm.map (fun ubs ->
List.filter_map filter_ub @@ Sterm.elements ubs)
@@ collect_ls_bounds task
in
let is_atomic t = match t.t_node with
| Tvar _
| Tapp (_, [])
| Tconst _ -> true
| _ -> false
in
let rec simp bounds t =
match t.t_node with
| Tapp (ls, [t1; t2]) when is_int t1 ->
if is_atomic t1 && is_atomic t2 then t
else
let repeat = function
| Some t' ->
if t_equal t t' then t
else
(debug "simp %a@." Why3.Pretty.print_term t;
debug "==> %a@." Why3.Pretty.print_term t';
simp bounds @@ remove_trivial_comparison t')
| None -> t
in
if ls_equal ls ps_le then simp_op bounds `Le t1 t2 |> repeat
else if ls_equal ls ps_lt then
match simp_op bounds `Lt t1 t2 with
| Some _ as r -> repeat r
| None -> simp_op bounds `Le t1 (t_minus t2 t_one) |> repeat
else if ls_equal ls ps_equ then simp_op bounds `Eq t1 t2 |> repeat
else if ls_equal ls ps_ge then simp_op bounds `Ge t1 t2 |> repeat
else if ls_equal ls ps_gt then simp_op bounds `Gt t1 t2 |> repeat
else t
| Tquant (q, tq) ->
let (vss, triggers, body) = t_open_quant tq in
let bounds' =
List.fold_left (fun bounds vs ->
let v = t_var vs in
if is_int v && check_lower_bound q v body then
let ubs = Sterm.elements @@
find_upper_bounds q v body
|> List.filter_map
(fun ub ->
if t_v_occurs vs ub = 0 then
filter_ub ub
else None)
in
if ubs = [] then bounds
else Mterm.add v ubs bounds
else bounds)
bounds (List.rev vss)
in
let body' = simp bounds' body in
let guard =
List.map (fun vs ->
let ubs = Mterm.find_def [] (t_var vs) bounds' in
t_le t_zero (t_var vs) ::
List.map (fun ub -> t_lt (t_var vs) @@ from_polynomial ub) ubs)
vss
|> List.concat
|> t_and_simp_l
in
let body'' = match q with
| Tforall -> t_implies_simp guard body'
| Texists -> t_and_simp guard body'
in
t_quant_close_simp q vss triggers @@ simplify_guards body''
| _ ->
TermTF.t_map_simp (fun x -> x) (simp bounds) t
in
Why3util.transform_goal (simp bounds) task
|
6090e8e7b29d6e71f4624e6813c38f6253085864808fd2d1ce0a9632559619c8 | nd/sicp | 4.36.scm | (define (a-pythagorean-triples low)
(let ((i (an-integer-starting-from low)))
(let ((j (an-integer-starting-from i)))
(let ((k (an-integer-between j (+ (* i i) (* j j)))))
(require (= (+ (* i i) (* j j)) (* k k)))
(list i j k)))))
| null | https://raw.githubusercontent.com/nd/sicp/d8587a0403d95af7c7bcf59b812f98c4f8550afd/ch04/4.36.scm | scheme | (define (a-pythagorean-triples low)
(let ((i (an-integer-starting-from low)))
(let ((j (an-integer-starting-from i)))
(let ((k (an-integer-between j (+ (* i i) (* j j)))))
(require (= (+ (* i i) (* j j)) (* k k)))
(list i j k)))))
|
|
d73b22a86257a294ebac3774731c98b6fe21871669116ac07090d0910084f75d | dinosaure/dinoscheme | synthesis.mli | module Et: Map.S with type key = string
val eval: Type.schema Et.t -> Lambda.t -> Type.kind
| null | https://raw.githubusercontent.com/dinosaure/dinoscheme/6bc4f2f0376585f0900ab4bf8e049edd06fa3d74/dinc/synthesis.mli | ocaml | module Et: Map.S with type key = string
val eval: Type.schema Et.t -> Lambda.t -> Type.kind
|
|
a74526c405f590f373e82a13c6058078fec0656bd8019bf69361ebe9dc9b5136 | uzh/guardian | article.ml | module Make (P : Guard.Persistence_s) = struct
module User = User.MakeActor (P)
(* pretend that all these fields aren't publically visible *)
type t =
{ mutable title : string
; mutable content : string
; mutable author : User.t
; uuid : Guardian.Uuid.Target.t
}
[@@deriving show]
type kind = [ `Article ]
let make ?id title content author =
let uuid = CCOption.get_or ~default:(Guard.Uuid.Target.create ()) id in
{ uuid; title; content; author }
;;
let to_authorizable ?ctx =
let open Guard in
P.Target.decorate ?ctx (fun t ->
AuthorizableTarget.make
~owner:(snd t.author)
(TargetRoleSet.singleton `Article)
`Article
t.uuid)
;;
let update_title ?ctx (actor : [ `User ] Guard.Authorizable.t) t new_title =
let open Lwt_result.Syntax in
let f new_title =
let () = t.title <- new_title in
Lwt.return_ok t
in
let* wrapped =
P.wrap_function ?ctx CCFun.id [ `Update, `Target t.uuid ] f
in
wrapped actor new_title
;;
let update_author ?ctx (actor : [ `User ] Guard.Authorizable.t) t new_author =
let open Lwt_result.Syntax in
let f new_author =
let () = t.author <- new_author in
let* ent = to_authorizable ?ctx t in
let* () = P.Target.save_owner ?ctx ~owner:(snd new_author) ent.uuid in
Lwt.return_ok t
in
let* wrapped =
P.wrap_function ?ctx CCFun.id [ `Manage, `Target t.uuid ] f
in
wrapped actor new_author
;;
end
| null | https://raw.githubusercontent.com/uzh/guardian/37d790f1c87270faf1ab23da7d62666e1a477d92/test/article.ml | ocaml | pretend that all these fields aren't publically visible | module Make (P : Guard.Persistence_s) = struct
module User = User.MakeActor (P)
type t =
{ mutable title : string
; mutable content : string
; mutable author : User.t
; uuid : Guardian.Uuid.Target.t
}
[@@deriving show]
type kind = [ `Article ]
let make ?id title content author =
let uuid = CCOption.get_or ~default:(Guard.Uuid.Target.create ()) id in
{ uuid; title; content; author }
;;
let to_authorizable ?ctx =
let open Guard in
P.Target.decorate ?ctx (fun t ->
AuthorizableTarget.make
~owner:(snd t.author)
(TargetRoleSet.singleton `Article)
`Article
t.uuid)
;;
let update_title ?ctx (actor : [ `User ] Guard.Authorizable.t) t new_title =
let open Lwt_result.Syntax in
let f new_title =
let () = t.title <- new_title in
Lwt.return_ok t
in
let* wrapped =
P.wrap_function ?ctx CCFun.id [ `Update, `Target t.uuid ] f
in
wrapped actor new_title
;;
let update_author ?ctx (actor : [ `User ] Guard.Authorizable.t) t new_author =
let open Lwt_result.Syntax in
let f new_author =
let () = t.author <- new_author in
let* ent = to_authorizable ?ctx t in
let* () = P.Target.save_owner ?ctx ~owner:(snd new_author) ent.uuid in
Lwt.return_ok t
in
let* wrapped =
P.wrap_function ?ctx CCFun.id [ `Manage, `Target t.uuid ] f
in
wrapped actor new_author
;;
end
|
abed7b986abf28237a0f97353449b17a12e51a0bd5341885a860d3f041428c2f | ItsMeijers/Lambdabox | Http.hs | # LANGUAGE OverloadedStrings , NamedFieldPuns #
module Binance.Internal.Trade.Http
( trade
, testTrade
, currentOpenOrders
, allOrders
, queryOrderOnId
, queryOrderOnClientId
, cancelOrderOnId
, cancelOrderOnClientId
) where
import Lambdabox.Box
import Binance.Internal.Trade.Types
import Network.Wreq.Extended
import Data.Text (Text)
import Data.Aeson.Extended (Unit)
-- TODO TEST ALL THIS FUNCTIONS CAREFULLY!!!!!
| Create a trade on binance based on an BinanceOrder .
trade :: Text
-> Text
-> BinanceOrder
-> Maybe Text
-> Maybe ResponseType
-> Maybe Int
-> Box BinanceOrderResponse
trade symbol side binanceOrder newClientOrderId responseType recvWindow =
prepareTrade symbol side binanceOrder newClientOrderId responseType
recvWindow (postSigned "/api/v3/order")
-- | Test trade is like a trade but the actual binance order does not get
-- send to the matching engine. The Binance Unit tag is needed due to the
FromJSON instance for empty bodies in Aeson this unit value gets replaced
-- with a typical haskel ()
testTrade :: Text
-> Text
-> BinanceOrder
-> Maybe Text
-> Maybe ResponseType
-> Maybe Int
-> Box ()
testTrade symbol side binanceOrder newClientOrderId responseType recvWindow =
prepareTrade symbol side binanceOrder newClientOrderId responseType
recvWindow (fmap (const ()) .
(postSigned "/api/v3/order/test" :: [(Text, Text)] -> Box Unit))
-- | Prepares the trade for sending for both the trade and testTrade function.
prepareTrade :: Text
-> Text
-> BinanceOrder
-> Maybe Text
-> Maybe ResponseType
-> Maybe Int
-> ([(Text, Text)] -> Box a)
-> Box a
prepareTrade s side binanceOrder newClientOrderId responseType recvWindow f =
let standardParams = [("symbol", s), ("side", toText side)]
orderParams = paramsFromOrder binanceOrder
maybeParams = optionalParams [ "newClientOrderId" :? newClientOrderId
, "newOrderRespType" :? responseType
, "recvWindow" :? recvWindow ]
params = standardParams ++ orderParams ++ maybeParams
in f params
| Creates the parameter list based on the type of BinanceOrder and the
-- record values that are within each type.
paramsFromOrder :: BinanceOrder -> [(Text, Text)]
paramsFromOrder BinanceLimitOrder { tifLO, qtyLO, priceLO, icebergQtyLO } =
[ ("type", "LIMIT")
, ("timeInForce", toText tifLO)
, ("quantity", toText qtyLO)
, ("price", toText priceLO)
] ++ optionalParams ["icebergQty" :? icebergQtyLO]
paramsFromOrder BinanceMarketOrder { qtyMO } =
[ ("type", "MARKET")
, ("quantity", toText qtyMO)
]
paramsFromOrder BinanceStopLossOrder { qtySLO, stopPriceSLO} =
[ ("type", "STOP_LOSS")
, ("quantity", toText qtySLO)
, ("stopPrice", toText stopPriceSLO)
]
paramsFromOrder BinanceStopLossLimitOrder
{ qtySLLO, stopPriceSLLO, tifSLLO, priceSLLO, icebergQtySLLO } =
[ ("type", "STOP_LOSS_LIMIT")
, ("quantity", toText qtySLLO)
, ("stopPrice", toText stopPriceSLLO)
, ("timeInForce", toText tifSLLO)
, ("price", toText priceSLLO)
] ++ optionalParams ["icebergQty" :? icebergQtySLLO]
paramsFromOrder BinanceTakeProfit { qtyTP, stopPriceTP } =
[ ("type", "TAKE_PROFIT")
, ("quantity", toText qtyTP)
, ("stopPrice", toText stopPriceTP)
]
paramsFromOrder BinanceTakeProfitLimit
{ tifTPL, qtyTPL, priceTPL, stopPriceTPL, icebergQtyTPL } =
[ ("type", "TAKE_PROFIT_LIMIT")
, ("timeInForce", toText tifTPL)
, ("quantity", toText qtyTPL)
, ("price", toText priceTPL)
, ("stopPrice", toText stopPriceTPL)
] ++ optionalParams ["icebergQty" :? icebergQtyTPL]
paramsFromOrder BinanceLimitMaker { qtyLM, priceLM } =
[ ("type", "LIMIT_MAKER")
, ("quantity", toText qtyLM)
, ("price", toText priceLM)
]
queryOrderOnId :: Text -> Int -> Maybe Int -> Box PlacedOrder
queryOrderOnId symbol orderId recvWindow =
getSigned "/api/v3/order" $ [ ("symbol", symbol)
, ("orderId", toText orderId)
] ++ optionalParams ["recvWindow" :? recvWindow]
queryOrderOnClientId :: Text -> Text -> Maybe Int -> Box PlacedOrder
queryOrderOnClientId symbol origClientOrderId recvWindow =
getSigned "/api/v3/order" $ [ ("symbol", symbol)
, ("origClientOrderId", origClientOrderId)
] ++ optionalParams ["recvWindow" :? recvWindow]
cancelOrderOnId :: Text
-> Int
-> Maybe Text
-> Maybe Int
-> Box CancelOrder
cancelOrderOnId symbol orderId newClientOrderId recvWindow =
deleteSigned "/api/v3/order" $ [ ("symbol", symbol)
, ("orderId", toText orderId)
] ++ optionalParams
[ "newClientOrderId" :? newClientOrderId
, "recvWindow" :? recvWindow
]
cancelOrderOnClientId :: Text
-> Text
-> Maybe Text
-> Maybe Int
-> Box CancelOrder
cancelOrderOnClientId symbol origClientOrderId newClientOrderId recvWindow =
deleteSigned "/api/v3/order" $ [ ("symbol", symbol)
, ("orderId", origClientOrderId)
] ++ optionalParams
[ "newClientOrderId" :? newClientOrderId
, "recvWindow" :? recvWindow
]
-- | List all the order status that are currently open on Binance.
currentOpenOrders :: Maybe Text -> Maybe Int -> Box [OrderStatus]
currentOpenOrders symbol recvWindow =
getSigned "/api/v3/openOrders" $ optionalParams
["symbol" :? symbol, "recvWindow" :? recvWindow]
-- | List all the orders on Binance.
allOrders :: Text -> Maybe Int -> Maybe Int -> Maybe Int -> Box [PlacedOrder]
allOrders symbol orderId limit recvWindow =
getSigned "/api/v3/allOrders" $ [("symbol", symbol)] ++ optionalParams
["orderId" :? orderId, "limit" :? limit, "recvWindow" :? recvWindow] | null | https://raw.githubusercontent.com/ItsMeijers/Lambdabox/c19a8ae7d37b9f8ab5054d558fe788a5d4483092/src/Binance/Internal/Trade/Http.hs | haskell | TODO TEST ALL THIS FUNCTIONS CAREFULLY!!!!!
| Test trade is like a trade but the actual binance order does not get
send to the matching engine. The Binance Unit tag is needed due to the
with a typical haskel ()
| Prepares the trade for sending for both the trade and testTrade function.
record values that are within each type.
| List all the order status that are currently open on Binance.
| List all the orders on Binance. | # LANGUAGE OverloadedStrings , NamedFieldPuns #
module Binance.Internal.Trade.Http
( trade
, testTrade
, currentOpenOrders
, allOrders
, queryOrderOnId
, queryOrderOnClientId
, cancelOrderOnId
, cancelOrderOnClientId
) where
import Lambdabox.Box
import Binance.Internal.Trade.Types
import Network.Wreq.Extended
import Data.Text (Text)
import Data.Aeson.Extended (Unit)
| Create a trade on binance based on an BinanceOrder .
trade :: Text
-> Text
-> BinanceOrder
-> Maybe Text
-> Maybe ResponseType
-> Maybe Int
-> Box BinanceOrderResponse
trade symbol side binanceOrder newClientOrderId responseType recvWindow =
prepareTrade symbol side binanceOrder newClientOrderId responseType
recvWindow (postSigned "/api/v3/order")
FromJSON instance for empty bodies in Aeson this unit value gets replaced
testTrade :: Text
-> Text
-> BinanceOrder
-> Maybe Text
-> Maybe ResponseType
-> Maybe Int
-> Box ()
testTrade symbol side binanceOrder newClientOrderId responseType recvWindow =
prepareTrade symbol side binanceOrder newClientOrderId responseType
recvWindow (fmap (const ()) .
(postSigned "/api/v3/order/test" :: [(Text, Text)] -> Box Unit))
prepareTrade :: Text
-> Text
-> BinanceOrder
-> Maybe Text
-> Maybe ResponseType
-> Maybe Int
-> ([(Text, Text)] -> Box a)
-> Box a
prepareTrade s side binanceOrder newClientOrderId responseType recvWindow f =
let standardParams = [("symbol", s), ("side", toText side)]
orderParams = paramsFromOrder binanceOrder
maybeParams = optionalParams [ "newClientOrderId" :? newClientOrderId
, "newOrderRespType" :? responseType
, "recvWindow" :? recvWindow ]
params = standardParams ++ orderParams ++ maybeParams
in f params
| Creates the parameter list based on the type of BinanceOrder and the
paramsFromOrder :: BinanceOrder -> [(Text, Text)]
paramsFromOrder BinanceLimitOrder { tifLO, qtyLO, priceLO, icebergQtyLO } =
[ ("type", "LIMIT")
, ("timeInForce", toText tifLO)
, ("quantity", toText qtyLO)
, ("price", toText priceLO)
] ++ optionalParams ["icebergQty" :? icebergQtyLO]
paramsFromOrder BinanceMarketOrder { qtyMO } =
[ ("type", "MARKET")
, ("quantity", toText qtyMO)
]
paramsFromOrder BinanceStopLossOrder { qtySLO, stopPriceSLO} =
[ ("type", "STOP_LOSS")
, ("quantity", toText qtySLO)
, ("stopPrice", toText stopPriceSLO)
]
paramsFromOrder BinanceStopLossLimitOrder
{ qtySLLO, stopPriceSLLO, tifSLLO, priceSLLO, icebergQtySLLO } =
[ ("type", "STOP_LOSS_LIMIT")
, ("quantity", toText qtySLLO)
, ("stopPrice", toText stopPriceSLLO)
, ("timeInForce", toText tifSLLO)
, ("price", toText priceSLLO)
] ++ optionalParams ["icebergQty" :? icebergQtySLLO]
paramsFromOrder BinanceTakeProfit { qtyTP, stopPriceTP } =
[ ("type", "TAKE_PROFIT")
, ("quantity", toText qtyTP)
, ("stopPrice", toText stopPriceTP)
]
paramsFromOrder BinanceTakeProfitLimit
{ tifTPL, qtyTPL, priceTPL, stopPriceTPL, icebergQtyTPL } =
[ ("type", "TAKE_PROFIT_LIMIT")
, ("timeInForce", toText tifTPL)
, ("quantity", toText qtyTPL)
, ("price", toText priceTPL)
, ("stopPrice", toText stopPriceTPL)
] ++ optionalParams ["icebergQty" :? icebergQtyTPL]
paramsFromOrder BinanceLimitMaker { qtyLM, priceLM } =
[ ("type", "LIMIT_MAKER")
, ("quantity", toText qtyLM)
, ("price", toText priceLM)
]
queryOrderOnId :: Text -> Int -> Maybe Int -> Box PlacedOrder
queryOrderOnId symbol orderId recvWindow =
getSigned "/api/v3/order" $ [ ("symbol", symbol)
, ("orderId", toText orderId)
] ++ optionalParams ["recvWindow" :? recvWindow]
queryOrderOnClientId :: Text -> Text -> Maybe Int -> Box PlacedOrder
queryOrderOnClientId symbol origClientOrderId recvWindow =
getSigned "/api/v3/order" $ [ ("symbol", symbol)
, ("origClientOrderId", origClientOrderId)
] ++ optionalParams ["recvWindow" :? recvWindow]
cancelOrderOnId :: Text
-> Int
-> Maybe Text
-> Maybe Int
-> Box CancelOrder
cancelOrderOnId symbol orderId newClientOrderId recvWindow =
deleteSigned "/api/v3/order" $ [ ("symbol", symbol)
, ("orderId", toText orderId)
] ++ optionalParams
[ "newClientOrderId" :? newClientOrderId
, "recvWindow" :? recvWindow
]
cancelOrderOnClientId :: Text
-> Text
-> Maybe Text
-> Maybe Int
-> Box CancelOrder
cancelOrderOnClientId symbol origClientOrderId newClientOrderId recvWindow =
deleteSigned "/api/v3/order" $ [ ("symbol", symbol)
, ("orderId", origClientOrderId)
] ++ optionalParams
[ "newClientOrderId" :? newClientOrderId
, "recvWindow" :? recvWindow
]
currentOpenOrders :: Maybe Text -> Maybe Int -> Box [OrderStatus]
currentOpenOrders symbol recvWindow =
getSigned "/api/v3/openOrders" $ optionalParams
["symbol" :? symbol, "recvWindow" :? recvWindow]
allOrders :: Text -> Maybe Int -> Maybe Int -> Maybe Int -> Box [PlacedOrder]
allOrders symbol orderId limit recvWindow =
getSigned "/api/v3/allOrders" $ [("symbol", symbol)] ++ optionalParams
["orderId" :? orderId, "limit" :? limit, "recvWindow" :? recvWindow] |
317bbf2610ca10806ba0d0c85b07d01284e8c73de60da9dc7206ba8ec8d592f8 | 8l/asif | Syntax.hs | module Language.FOmega.Test.Syntax where
import Language.FOmega.Syntax
import Language.FOmega.Parse (parseExpr)
import Prelude hiding (pi)
import Test.Framework (testGroup)
import Test.Framework.Providers.HUnit
import Test.HUnit
import Control.Applicative
fromJust (Just x) = x
fromJust Nothing = error "fromJust: Nothing"
fromLeft (Left msg) = msg
fromLeft (Right _) = error "fromLeft: got Right"
fromRight (Right x) = x
fromRight (Left msg) = error msg
isRight (Right _) = True
isRight (Left _) = False
tests = testGroup "Syntax" [
renameTests
, substTests
, normTests
]
renameTests =
let go nm i o = testCase nm $ rename "x" "y" i @?= o
in testGroup "rename" [
go "lam type" (lam "x" (var "x") (var "x"))
(lam "x" (var "y") (var "x"))
, go "lam body" (lam "a" (var "b") (var "x"))
(lam "a" (var "b") (var "y"))
, go "lam body shadowed"
(lam "x" (var "a") (var "x"))
(lam "x" (var "a") (var "x"))
, go "pi type" (pi "x" (var "x") (var "x"))
(pi "x" (var "y") (var "x"))
, go "pi body" (pi "a" (var "b") (var "x"))
(pi "a" (var "b") (var "y"))
, go "pi body shadowed"
(pi "x" (var "a") (var "x"))
(pi "x" (var "a") (var "x"))
, go "decl type" (decl "x" (var "x") (var "a") (var "a"))
(decl "x" (var "y") (var "a") (var "a"))
, go "decl def" (decl "x" (var "a") (var "x") (var "a"))
(decl "x" (var "a") (var "y") (var "a"))
, go "decl body" (decl "a" (var "a") (var "a") (var "x"))
(decl "a" (var "a") (var "a") (var "y"))
, go "decl body shadowed"
(decl "x" (var "a") (var "a") (var "x"))
(decl "x" (var "a") (var "a") (var "x"))
]
substTests = testGroup "subst" [
avoidCapture
]
avoidCapture = testCase "avoid capture" $ do
s <- show . (+1) <$> nextSymId
r <- subst "x" (var "y") (lam "y" star $ var "x")
r @?= (lam s star $ var "y")
normTests =
let go nm src1 src2 = do
let Right tm1 = parseExpr src1
Right tm2 = parseExpr src2
testCase nm $ norm tm1 @?= tm2
in
testGroup "norm" [
go "under lambdas"
"\\a:*. \\x:a. (\\y:a. y) x"
"\\a:*. \\x:a. x"
, go "under Pis"
"Pi a:*. (\\b:*. b) a"
"Pi a:*. a"
, go "on right side of applications"
"\\a:*. \\x:a. \\f:a -> a. f ((\\y:a.y) x)"
"\\a:*. \\x:a. \\f:a -> a. f x"
]
| null | https://raw.githubusercontent.com/8l/asif/3a0b0909e71a2e19e0773b3c77eadfa753751b41/tests/Language/FOmega/Test/Syntax.hs | haskell | module Language.FOmega.Test.Syntax where
import Language.FOmega.Syntax
import Language.FOmega.Parse (parseExpr)
import Prelude hiding (pi)
import Test.Framework (testGroup)
import Test.Framework.Providers.HUnit
import Test.HUnit
import Control.Applicative
fromJust (Just x) = x
fromJust Nothing = error "fromJust: Nothing"
fromLeft (Left msg) = msg
fromLeft (Right _) = error "fromLeft: got Right"
fromRight (Right x) = x
fromRight (Left msg) = error msg
isRight (Right _) = True
isRight (Left _) = False
tests = testGroup "Syntax" [
renameTests
, substTests
, normTests
]
renameTests =
let go nm i o = testCase nm $ rename "x" "y" i @?= o
in testGroup "rename" [
go "lam type" (lam "x" (var "x") (var "x"))
(lam "x" (var "y") (var "x"))
, go "lam body" (lam "a" (var "b") (var "x"))
(lam "a" (var "b") (var "y"))
, go "lam body shadowed"
(lam "x" (var "a") (var "x"))
(lam "x" (var "a") (var "x"))
, go "pi type" (pi "x" (var "x") (var "x"))
(pi "x" (var "y") (var "x"))
, go "pi body" (pi "a" (var "b") (var "x"))
(pi "a" (var "b") (var "y"))
, go "pi body shadowed"
(pi "x" (var "a") (var "x"))
(pi "x" (var "a") (var "x"))
, go "decl type" (decl "x" (var "x") (var "a") (var "a"))
(decl "x" (var "y") (var "a") (var "a"))
, go "decl def" (decl "x" (var "a") (var "x") (var "a"))
(decl "x" (var "a") (var "y") (var "a"))
, go "decl body" (decl "a" (var "a") (var "a") (var "x"))
(decl "a" (var "a") (var "a") (var "y"))
, go "decl body shadowed"
(decl "x" (var "a") (var "a") (var "x"))
(decl "x" (var "a") (var "a") (var "x"))
]
substTests = testGroup "subst" [
avoidCapture
]
avoidCapture = testCase "avoid capture" $ do
s <- show . (+1) <$> nextSymId
r <- subst "x" (var "y") (lam "y" star $ var "x")
r @?= (lam s star $ var "y")
normTests =
let go nm src1 src2 = do
let Right tm1 = parseExpr src1
Right tm2 = parseExpr src2
testCase nm $ norm tm1 @?= tm2
in
testGroup "norm" [
go "under lambdas"
"\\a:*. \\x:a. (\\y:a. y) x"
"\\a:*. \\x:a. x"
, go "under Pis"
"Pi a:*. (\\b:*. b) a"
"Pi a:*. a"
, go "on right side of applications"
"\\a:*. \\x:a. \\f:a -> a. f ((\\y:a.y) x)"
"\\a:*. \\x:a. \\f:a -> a. f x"
]
|
|
f4ae6c238bc49249e8ee6741d24169fcdd92676f7d41c6743179c0ba31ec5d76 | jackfirth/racket-expect | check.rkt | #lang racket/base
(require arguments
expect
(submod "base.rkt" for-sugar))
(define (rx-or-pred->exp p)
(if (regexp? p)
(expect-struct exn [exn-message (expect-regexp-match p)])
(expect-pred p)))
(define-expect-checks
[(check-eq? a b) a (expect-eq? b)]
[(check-eqv? a b) a (expect-eqv? b)]
[(check-equal? a b) a (expect-equal? b)]
[(check-not-eq? a b) a (expect-not-eq? b)]
[(check-not-eqv? a b) a (expect-not-eqv? b)]
[(check-not-equal? a b) a (expect-not-equal? b)]
[(check-pred p v) v (expect-pred p)]
[(check-= a b eps) a (expect-= b eps)]
[(check-true v) v expect-true]
[(check-false v) v expect-false]
[(check-not-false v) v expect-not-false]
[(check-exn p f) f (expect-raise (rx-or-pred->exp p))]
[(check-not-exn f) f expect-not-raise]
[(check op a b) op (expect-call (arguments a b) (expect-return #t))])
| null | https://raw.githubusercontent.com/jackfirth/racket-expect/9530df30537ae05400b6a3add9619e5f697dca52/private/rackunit/check.rkt | racket | #lang racket/base
(require arguments
expect
(submod "base.rkt" for-sugar))
(define (rx-or-pred->exp p)
(if (regexp? p)
(expect-struct exn [exn-message (expect-regexp-match p)])
(expect-pred p)))
(define-expect-checks
[(check-eq? a b) a (expect-eq? b)]
[(check-eqv? a b) a (expect-eqv? b)]
[(check-equal? a b) a (expect-equal? b)]
[(check-not-eq? a b) a (expect-not-eq? b)]
[(check-not-eqv? a b) a (expect-not-eqv? b)]
[(check-not-equal? a b) a (expect-not-equal? b)]
[(check-pred p v) v (expect-pred p)]
[(check-= a b eps) a (expect-= b eps)]
[(check-true v) v expect-true]
[(check-false v) v expect-false]
[(check-not-false v) v expect-not-false]
[(check-exn p f) f (expect-raise (rx-or-pred->exp p))]
[(check-not-exn f) f expect-not-raise]
[(check op a b) op (expect-call (arguments a b) (expect-return #t))])
|
|
5c07b78ba153c9fcb292bf3b68f1584c0e03edf3c9ab738213e7d29a426569d0 | ailisp/Graphic-Forms | graphics-classes.lisp | (in-package :graphic-forms.uitoolkit.graphics)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defstruct color
(red 0)
(green 0)
(blue 0))
(defstruct font-data
(char-set 0)
(face-name "")
(point-size 10)
(style nil))
(defstruct font-metrics
(ascent 0)
(descent 0)
(leading 0)
(avg-char-width 0)
(max-char-width 0))
(defmacro ascent (metrics)
`(gfg::font-metrics-ascent ,metrics))
(defmacro descent (metrics)
`(gfg::font-metrics-descent ,metrics))
(defmacro leading (metrics)
`(gfg::font-metrics-leading ,metrics))
(defmacro height (metrics)
(let ((tmp-metrics (gensym)))
`(let ((,tmp-metrics ,metrics))
(+ (gfg::font-metrics-ascent ,tmp-metrics)
(gfg::font-metrics-descent ,tmp-metrics)))))
(defmacro average-char-width (metrics)
`(gfg::font-metrics-avg-char-width ,metrics))
(defmacro maximum-char-width (metrics)
`(gfg::font-metrics-max-char-width ,metrics))
(defstruct palette
(red-mask 0)
(green-mask 0)
(blue-mask 0)
(red-shift 0)
(green-shift 0)
(blue-shift 0)
(direct nil)
vector of COLOR structs
(defmacro color-table (data)
`(gfg::palette-table ,data)))
(defclass cursor (gfs:native-object)
((shared
:reader sharedp
:initarg :shared
:initform nil))
(:documentation "This class wraps a native cursor handle."))
(defclass image-data-plugin (gfs:native-object) ()
(:documentation "Base class for image data plugin implementations."))
(defclass image-data ()
((data-plugin
:reader data-plugin-of
:initarg :data-plugin
:initform nil))
(:documentation "This class maintains image attributes, color, and pixel data."))
(defclass font (gfs:native-object) ()
(:documentation "This class wraps a native font handle."))
(defclass graphics-context (gfs:native-object)
((dc-destructor
:accessor dc-destructor-of
:initform nil)
(widget-handle
:accessor widget-handle-of
:initform nil)
(surface-size
:accessor surface-size-of
:initarg :surface-size
:initform nil)
(logbrush-style
:accessor logbrush-style-of
:initform gfs::+bs-solid+)
(logbrush-color
:accessor logbrush-color-of
:initform 0)
(logbrush-hatch
:accessor logbrush-hatch-of
:initform gfs::+hs-bdiagonal+)
(miter-limit
:accessor miter-limit
:initform 10.0)
(pen-style
:accessor pen-style
:initform '(:solid))
(pen-width
:accessor pen-width
:initform 1)
(pen-handle
:accessor pen-handle-of
:initform (cffi:null-pointer)))
(:documentation "This class represents the context associated with drawing primitives."))
(defclass icon-bundle (gfs:native-object) ()
(:documentation "This class encapsulates a set of Win32 icon handles."))
(defclass image (gfs:native-object)
((transparency-pixel
:accessor transparency-pixel-of
:initarg :transparency-pixel
:initform nil))
(:documentation "This class encapsulates a Win32 bitmap handle."))
(defmacro blue-mask (data)
`(gfg::palette-blue-mask ,data))
(defmacro blue-shift (data)
`(gfg::palette-blue-shift ,data))
(defmacro direct (data flag)
`(setf (gfg::palette-direct ,data) ,flag))
(defmacro green-mask (data)
`(gfg::palette-green-mask ,data))
(defmacro green-shift (data)
`(gfg::palette-green-shift ,data))
(defmacro red-mask (data)
`(gfg::palette-red-mask ,data))
(defmacro red-shift (data)
`(gfg::palette-red-shift ,data))
(defclass pattern (gfs:native-object) ()
(:documentation "This class represents a pattern to be used with a brush."))
(defclass transform (gfs:native-object) ()
(:documentation "This class specifies how coordinates are transformed."))
| null | https://raw.githubusercontent.com/ailisp/Graphic-Forms/1e0723d07e1e4e02b8ae375db8f3d65d1b444f11/src/uitoolkit/graphics/graphics-classes.lisp | lisp | (in-package :graphic-forms.uitoolkit.graphics)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defstruct color
(red 0)
(green 0)
(blue 0))
(defstruct font-data
(char-set 0)
(face-name "")
(point-size 10)
(style nil))
(defstruct font-metrics
(ascent 0)
(descent 0)
(leading 0)
(avg-char-width 0)
(max-char-width 0))
(defmacro ascent (metrics)
`(gfg::font-metrics-ascent ,metrics))
(defmacro descent (metrics)
`(gfg::font-metrics-descent ,metrics))
(defmacro leading (metrics)
`(gfg::font-metrics-leading ,metrics))
(defmacro height (metrics)
(let ((tmp-metrics (gensym)))
`(let ((,tmp-metrics ,metrics))
(+ (gfg::font-metrics-ascent ,tmp-metrics)
(gfg::font-metrics-descent ,tmp-metrics)))))
(defmacro average-char-width (metrics)
`(gfg::font-metrics-avg-char-width ,metrics))
(defmacro maximum-char-width (metrics)
`(gfg::font-metrics-max-char-width ,metrics))
(defstruct palette
(red-mask 0)
(green-mask 0)
(blue-mask 0)
(red-shift 0)
(green-shift 0)
(blue-shift 0)
(direct nil)
vector of COLOR structs
(defmacro color-table (data)
`(gfg::palette-table ,data)))
(defclass cursor (gfs:native-object)
((shared
:reader sharedp
:initarg :shared
:initform nil))
(:documentation "This class wraps a native cursor handle."))
(defclass image-data-plugin (gfs:native-object) ()
(:documentation "Base class for image data plugin implementations."))
(defclass image-data ()
((data-plugin
:reader data-plugin-of
:initarg :data-plugin
:initform nil))
(:documentation "This class maintains image attributes, color, and pixel data."))
(defclass font (gfs:native-object) ()
(:documentation "This class wraps a native font handle."))
(defclass graphics-context (gfs:native-object)
((dc-destructor
:accessor dc-destructor-of
:initform nil)
(widget-handle
:accessor widget-handle-of
:initform nil)
(surface-size
:accessor surface-size-of
:initarg :surface-size
:initform nil)
(logbrush-style
:accessor logbrush-style-of
:initform gfs::+bs-solid+)
(logbrush-color
:accessor logbrush-color-of
:initform 0)
(logbrush-hatch
:accessor logbrush-hatch-of
:initform gfs::+hs-bdiagonal+)
(miter-limit
:accessor miter-limit
:initform 10.0)
(pen-style
:accessor pen-style
:initform '(:solid))
(pen-width
:accessor pen-width
:initform 1)
(pen-handle
:accessor pen-handle-of
:initform (cffi:null-pointer)))
(:documentation "This class represents the context associated with drawing primitives."))
(defclass icon-bundle (gfs:native-object) ()
(:documentation "This class encapsulates a set of Win32 icon handles."))
(defclass image (gfs:native-object)
((transparency-pixel
:accessor transparency-pixel-of
:initarg :transparency-pixel
:initform nil))
(:documentation "This class encapsulates a Win32 bitmap handle."))
(defmacro blue-mask (data)
`(gfg::palette-blue-mask ,data))
(defmacro blue-shift (data)
`(gfg::palette-blue-shift ,data))
(defmacro direct (data flag)
`(setf (gfg::palette-direct ,data) ,flag))
(defmacro green-mask (data)
`(gfg::palette-green-mask ,data))
(defmacro green-shift (data)
`(gfg::palette-green-shift ,data))
(defmacro red-mask (data)
`(gfg::palette-red-mask ,data))
(defmacro red-shift (data)
`(gfg::palette-red-shift ,data))
(defclass pattern (gfs:native-object) ()
(:documentation "This class represents a pattern to be used with a brush."))
(defclass transform (gfs:native-object) ()
(:documentation "This class specifies how coordinates are transformed."))
|
|
4d7bef66f447eeb9cbddcc96423a07a6f2674601e9b9673080e1f5fdfe3293b2 | janestreet/accessor_base | int_tests.ml | open! Core
open! Import
let%test_unit "negated" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Unit)
(fun () -> Accessor.Int.negated)
;;
let%test_unit "added" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Int)
Accessor.Int.added
;;
let%test_unit "substracted" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Int)
Accessor.Int.subtracted
;;
let%test_unit "incremented" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Unit)
(fun () -> Accessor.Int.incremented)
;;
let%test_unit "decremented" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Unit)
(fun () -> Accessor.Int.decremented)
;;
let%test_unit "bit_negated" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Unit)
(fun () -> Accessor.Int.bit_negated)
;;
let%test_unit "bit_xored" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Int)
Accessor.Int.bit_xored
;;
let%test_unit "bit_at_exn" =
let module Bit_index = struct
type t = int [@@deriving quickcheck, sexp_of]
let quickcheck_generator = Int.gen_uniform_incl 0 (Int.num_bits - 1)
end
in
Accessor_test_helpers.field
(module Bool)
(module Int)
(module Bit_index)
Accessor.Int.bit_at_exn;
Quickcheck.test
(Quickcheck.Generator.union
[ Int.gen_uniform_incl Int.min_value (-1)
; Int.gen_uniform_incl Int.num_bits Int.max_value
])
~f:(fun i ->
match Accessor.Int.bit_at_exn i with
| _ -> raise_s [%message "[Accessor.Int.bit_at_exn] should have raised" (i : int)]
| exception _ -> ())
;;
| null | https://raw.githubusercontent.com/janestreet/accessor_base/8384c29a37e557168ae8a43b2a5a531f0ffc16e4/test/fast/int_tests.ml | ocaml | open! Core
open! Import
let%test_unit "negated" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Unit)
(fun () -> Accessor.Int.negated)
;;
let%test_unit "added" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Int)
Accessor.Int.added
;;
let%test_unit "substracted" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Int)
Accessor.Int.subtracted
;;
let%test_unit "incremented" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Unit)
(fun () -> Accessor.Int.incremented)
;;
let%test_unit "decremented" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Unit)
(fun () -> Accessor.Int.decremented)
;;
let%test_unit "bit_negated" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Unit)
(fun () -> Accessor.Int.bit_negated)
;;
let%test_unit "bit_xored" =
Accessor_test_helpers.isomorphism
(module Int)
(module Int)
(module Int)
Accessor.Int.bit_xored
;;
let%test_unit "bit_at_exn" =
let module Bit_index = struct
type t = int [@@deriving quickcheck, sexp_of]
let quickcheck_generator = Int.gen_uniform_incl 0 (Int.num_bits - 1)
end
in
Accessor_test_helpers.field
(module Bool)
(module Int)
(module Bit_index)
Accessor.Int.bit_at_exn;
Quickcheck.test
(Quickcheck.Generator.union
[ Int.gen_uniform_incl Int.min_value (-1)
; Int.gen_uniform_incl Int.num_bits Int.max_value
])
~f:(fun i ->
match Accessor.Int.bit_at_exn i with
| _ -> raise_s [%message "[Accessor.Int.bit_at_exn] should have raised" (i : int)]
| exception _ -> ())
;;
|
|
4d18c9acef5ec6fe45bbee3c4e86cef838615eaa5c4ca43d1eca36ef5a64c3e8 | richmit/mjrcalc | use-dft.lisp | ;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;; @file use-dft.lisp
@author < >
@brief DFT and inverse DFT.@EOL
;; @std Common Lisp
@parblock
Copyright ( c ) 1996,1997,2008,2010,2013,2015 , < > All rights reserved .
;;
;; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
;;
1 . Redistributions of source code must retain the above copyright notice , this list of conditions , and the following disclaimer .
;;
2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions , and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
3 . Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
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.
;; @endparblock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :MJR_DFT
(:USE :COMMON-LISP
:MJR_ARR)
(:DOCUMENTATION "Brief: DFT and inverse DFT.;")
(:EXPORT #:mjr_dft_help
#:mjr_dft_transform
#:mjr_dft_dft
#:mjr_dft_idft
))
(in-package :MJR_DFT)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_dft_help ()
"Compute DFT and Inverse DFT of arrays"
(documentation 'mjr_dft_help 'function))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_dft_transform (x ttype &optional (offset 0) (stride 1) (maxelt nil) (out nil) (ooffset 0) (ostride 1))
"Compute DFT/IDFT a subset of the data in the array X (a 1D or 2D array)
This function forms the computational kernel of the MJR_DFT package. One normally uses the MJR_DFT_DFT and MJR_DFT_IDFT functions, but this one is exported
in order to support more sophisticated computations.
The dimension(s) of X should be power(s) of two for maximum performance.
If X is a matrix (2D array), then the 2D DFT is returned for the entire array. If X is a vector, then 1) subsets of the vector may be processed, and 2) the
output may be placed in a provided array instead of one allocated by this function. This additional functionality when X is a vector is provided via several
optional arguments:
* offset -- index to begin with
* stride -- distance between elements
* maxelt -- Maximum number of elements to process from x
* out -- vector into which output will be placed
* ooffset -- index to begin with (only valid when OUT is non-NIL)
* ostride -- distance between elements (only valid when OUT is non-NIL)
References:
The finite Fourier transform ; IEEE Trans . Audio Electroacoustics 17 "
(if (vectorp x)
(let* ((mi (array-dimension x 0)) ;; Vector case
(mo (or maxelt (ceiling (- mi offset) stride)))
(y (or out (make-array mo :initial-element 0)))
(prdp (* (if (equal :dft ttype) -1 1) #C(0 2) pi (/ mo)))
(scl (if (equal :dft ttype) 1 (/ mo))))
(if (and (> mo 4) (evenp mo))
(let ((edft (mjr_dft_transform x ttype offset (* 2 stride) (/ mo 2))) ;;;; Recursive Split odd/even
(odft (mjr_dft_transform x ttype (+ offset stride) (* 2 stride) (/ mo 2)))
(mo/2 (/ mo 2)))
construct DFT from
for ku from mo/2 ;;;;;; odd and even parts
for lhs = (aref edft kl)
for rhs = (* (exp (* prdp kl)) (aref odft kl))
finally (return y)
do (setf (aref y (+ ooffset (* ostride kl))) (* (if (equal :dft ttype) 1 1/2) (+ lhs rhs)))
do (setf (aref y (+ ooffset (* ostride ku))) (* (if (equal :dft ttype) 1 1/2) (- lhs rhs)))))
(loop for io from 0 upto (1- mo) ;;;; Direct DFT case
for ii from offset upto (1- mi) by stride
for ia from ooffset by ostride
finally (return y)
do (setf (aref y ia) ;;;;;; Eval formula
(* scl (loop for ko from 0 upto (1- mo)
for ki from offset upto (1- mi) by stride
sum (* (aref x ki) (exp (* prdp ko io)))))))))
(let* ((dims (array-dimensions x)) ;; Matrix case
(rows (first dims))
(cols (second dims))
(num-ele (* rows cols))
(workn-x (mjr_arr_nreflow-to-vec x)) ;;;; Displaced arrays let
(workn-y1 (make-array num-ele)) ;;;; us use the vector code
(workn-y2 (make-array num-ele)))
(loop for r from 0 upto (1- rows) ;;;; Row DFTs
do (mjr_dft_transform workn-x ttype (* r cols) 1 cols workn-y1 (* r cols) 1))
(loop for c from 0 upto (1- cols) ;;;; Col DFTs
do (mjr_dft_transform workn-y1 ttype c cols rows workn-y2 c cols))
(make-array dims :displaced-to workn-y2)))) ;;;; Reshape for return
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_dft_dft (x)
"Compute DFT of the data in the X (a matrix for 2D DFT or vector for 1D DFT)"
(mjr_dft_transform x :dft))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_dft_idft (x)
"Compute IDFT of the data in the X (a matrix for 2D IDFT or vector for 1D IDFT)"
(mjr_dft_transform x :idft))
| null | https://raw.githubusercontent.com/richmit/mjrcalc/96f66d030034754e7d3421688ff201f4f1db4833/use-dft.lisp | lisp | -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*-
@file use-dft.lisp
@std Common Lisp
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
and/or other materials provided with the distribution.
without specific prior written permission.
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.
@endparblock
IEEE Trans . Audio Electroacoustics 17 "
Vector case
Recursive Split odd/even
odd and even parts
Direct DFT case
Eval formula
Matrix case
Displaced arrays let
us use the vector code
Row DFTs
Col DFTs
Reshape for return
| @author < >
@brief DFT and inverse DFT.@EOL
@parblock
Copyright ( c ) 1996,1997,2008,2010,2013,2015 , < > All rights reserved .
1 . Redistributions of source code must retain the above copyright notice , this list of conditions , and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions , and the following disclaimer in the documentation
3 . Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS
(defpackage :MJR_DFT
(:USE :COMMON-LISP
:MJR_ARR)
(:DOCUMENTATION "Brief: DFT and inverse DFT.;")
(:EXPORT #:mjr_dft_help
#:mjr_dft_transform
#:mjr_dft_dft
#:mjr_dft_idft
))
(in-package :MJR_DFT)
(defun mjr_dft_help ()
"Compute DFT and Inverse DFT of arrays"
(documentation 'mjr_dft_help 'function))
(defun mjr_dft_transform (x ttype &optional (offset 0) (stride 1) (maxelt nil) (out nil) (ooffset 0) (ostride 1))
"Compute DFT/IDFT a subset of the data in the array X (a 1D or 2D array)
This function forms the computational kernel of the MJR_DFT package. One normally uses the MJR_DFT_DFT and MJR_DFT_IDFT functions, but this one is exported
in order to support more sophisticated computations.
The dimension(s) of X should be power(s) of two for maximum performance.
If X is a matrix (2D array), then the 2D DFT is returned for the entire array. If X is a vector, then 1) subsets of the vector may be processed, and 2) the
output may be placed in a provided array instead of one allocated by this function. This additional functionality when X is a vector is provided via several
optional arguments:
* offset -- index to begin with
* stride -- distance between elements
* maxelt -- Maximum number of elements to process from x
* out -- vector into which output will be placed
* ooffset -- index to begin with (only valid when OUT is non-NIL)
* ostride -- distance between elements (only valid when OUT is non-NIL)
References:
(if (vectorp x)
(mo (or maxelt (ceiling (- mi offset) stride)))
(y (or out (make-array mo :initial-element 0)))
(prdp (* (if (equal :dft ttype) -1 1) #C(0 2) pi (/ mo)))
(scl (if (equal :dft ttype) 1 (/ mo))))
(if (and (> mo 4) (evenp mo))
(odft (mjr_dft_transform x ttype (+ offset stride) (* 2 stride) (/ mo 2)))
(mo/2 (/ mo 2)))
construct DFT from
for lhs = (aref edft kl)
for rhs = (* (exp (* prdp kl)) (aref odft kl))
finally (return y)
do (setf (aref y (+ ooffset (* ostride kl))) (* (if (equal :dft ttype) 1 1/2) (+ lhs rhs)))
do (setf (aref y (+ ooffset (* ostride ku))) (* (if (equal :dft ttype) 1 1/2) (- lhs rhs)))))
for ii from offset upto (1- mi) by stride
for ia from ooffset by ostride
finally (return y)
(* scl (loop for ko from 0 upto (1- mo)
for ki from offset upto (1- mi) by stride
sum (* (aref x ki) (exp (* prdp ko io)))))))))
(rows (first dims))
(cols (second dims))
(num-ele (* rows cols))
(workn-y2 (make-array num-ele)))
do (mjr_dft_transform workn-x ttype (* r cols) 1 cols workn-y1 (* r cols) 1))
do (mjr_dft_transform workn-y1 ttype c cols rows workn-y2 c cols))
(defun mjr_dft_dft (x)
"Compute DFT of the data in the X (a matrix for 2D DFT or vector for 1D DFT)"
(mjr_dft_transform x :dft))
(defun mjr_dft_idft (x)
"Compute IDFT of the data in the X (a matrix for 2D IDFT or vector for 1D IDFT)"
(mjr_dft_transform x :idft))
|
c2962ad12266601276373e16b52e8440af9cfb4cd01042ff20534eb9198e6c25 | bnoordhuis/chicken-core | scrutiny-tests.scm | ;;;; scrutiny-tests.scm
(define (a)
(define (b)
(define (c)
(let ((x (+ 3 4)))
(if x 1 2))))) ; expected boolean but got number in conditional
(define (foo x)
(if x ; branches return differing number of results
(values 1 2)
(values 1 2 (+ (+ (+ (+ 3)))))))
(let ((bar +))
(bar 3 'a)) ; expected number, got symbol
expected 1 argument , got 0
expected 1 result , got 2
expected 1 result , got 0
(let ((x 100))
(x)) ; expected procedure, got fixnum
expected 2 numbers , but got symbols
33 does not match type of car
expected procedure , got fixnum ( canonicalizes to 1 result )
; this should *not* signal a warning:
(define (test-values x)
(define (fail) (error "failed"))
(if x
(values 42 43)
(fail)))
; same case, but nested
(define (test-values2 x y)
(define (fail) (error "failed"))
(if x
(values 42 43)
(if y (values 99 100) (fail))))
(define (foo)
(define (bar) (if foo 1)) ; should not warn (local)
(for-each void '(1 2 3)) ; should not warn (self-call)
(if foo 2) ; not in tail position
(if bar 3)) ; should warn
;; noreturn conditional branch enforces "number" on x
(define (foo2 x)
(if (string? x) (error "foo") (+ x 3))
(string-append x "abc"))
;; implicit declaration of foo3
(declare (hide foo3))
(define (foo3 x)
(string-append x "abc"))
(foo3 99)
;; predicate
(define (foo4 x)
(if (string? x)
(+ x 1)
(+ x 2))) ; ok
;; enforcement
(define (foo5 x)
(string-append x "abc")
(+ x 3))
;; aliasing
(define (foo6 x)
(let ((y x))
(string-append x "abc")
(+ x 3))) ;XXX (+ y 3) does not work yet
;; user-defined predicate
(: foo7 (* -> boolean : string))
(define (foo7 x) (string? x))
(when (foo7 x)
(+ x 1)) ; will warn about "x" being a string
;; declared procedure types are enforcing
(define-type s2s (string -> symbol))
(: foo8 s2s)
(define (foo8 x) (string->symbol x))
(: foo9 s2s)
(declare (enforce-argument-types foo9))
(define (foo9 x) (string->symbol x))
(define (foo10 x)
(foo8 x)
(+ x 1) ; foo8 does not enforce x (no warning)
(foo9 x) ; + enforces number on x
(+ x 1)) ; foo9 does enforce
;; trigger warnings for incompatible types in "the" forms
(define (foo10 x)
1
(the * (values 1 2)) ; 1 + 2
3
(the fixnum (* x y))) ; nothing (but warns about "x" being string)
Reported by :
;
- assignment inside first conditional does not invalidate blist
;; entries for "ins"/"del" in outer flow.
(define (write-blob-to-sql sql identifier last blob c-c)
(define ins '())
(define del '())
(if (vector? blob)
(begin
(set! ins (vector-ref blob 1))
(set! del (vector-ref blob 2))
(set! blob (vector-ref blob 0))))
(if (or (pair? ins)
(pair? del))
(<handle-ins-and-del>))
(<do-some-more>))
;; Checking whether reported line numbers inside modules are correct
(module foo (blabla)
(import chicken scheme)
(define (blabla)
(+ 1 'x)))
Reported by megane in # 884 :
;;
;; Custom types defined in modules need to be resolved during canonicalization
(module bar ()
(import chicken scheme)
(define-type footype string)
(the footype "bar"))
(: deprecated-procedure deprecated)
(define (deprecated-procedure x) (+ x x))
(deprecated-procedure 1)
(: another-deprecated-procedure (deprecated replacement-procedure))
(define (another-deprecated-procedure x) (+ x x))
(another-deprecated-procedure 2)
;; Needed to use "over-all-instantiations" or matching "vector"/"list" type
;; with "vector-of"/"list-of" type (reported by megane)
(: apply1 (forall (a b) (procedure ((procedure (#!rest a) b) (list-of a)) b)))
(define (apply1 f args)
(apply f args))
< - no type warning ( # 948 )
< - same here ( # 952 )
| null | https://raw.githubusercontent.com/bnoordhuis/chicken-core/56d30e3be095b6abe1bddcfe10505fa726a43bb5/tests/scrutiny-tests.scm | scheme | scrutiny-tests.scm
expected boolean but got number in conditional
branches return differing number of results
expected number, got symbol
expected procedure, got fixnum
this should *not* signal a warning:
same case, but nested
should not warn (local)
should not warn (self-call)
not in tail position
should warn
noreturn conditional branch enforces "number" on x
implicit declaration of foo3
predicate
ok
enforcement
aliasing
XXX (+ y 3) does not work yet
user-defined predicate
will warn about "x" being a string
declared procedure types are enforcing
foo8 does not enforce x (no warning)
+ enforces number on x
foo9 does enforce
trigger warnings for incompatible types in "the" forms
1 + 2
nothing (but warns about "x" being string)
entries for "ins"/"del" in outer flow.
Checking whether reported line numbers inside modules are correct
Custom types defined in modules need to be resolved during canonicalization
Needed to use "over-all-instantiations" or matching "vector"/"list" type
with "vector-of"/"list-of" type (reported by megane) |
(define (a)
(define (b)
(define (c)
(let ((x (+ 3 4)))
(define (foo x)
(values 1 2)
(values 1 2 (+ (+ (+ (+ 3)))))))
(let ((bar +))
expected 1 argument , got 0
expected 1 result , got 2
expected 1 result , got 0
(let ((x 100))
expected 2 numbers , but got symbols
33 does not match type of car
expected procedure , got fixnum ( canonicalizes to 1 result )
(define (test-values x)
(define (fail) (error "failed"))
(if x
(values 42 43)
(fail)))
(define (test-values2 x y)
(define (fail) (error "failed"))
(if x
(values 42 43)
(if y (values 99 100) (fail))))
(define (foo)
(define (foo2 x)
(if (string? x) (error "foo") (+ x 3))
(string-append x "abc"))
(declare (hide foo3))
(define (foo3 x)
(string-append x "abc"))
(foo3 99)
(define (foo4 x)
(if (string? x)
(+ x 1)
(define (foo5 x)
(string-append x "abc")
(+ x 3))
(define (foo6 x)
(let ((y x))
(string-append x "abc")
(: foo7 (* -> boolean : string))
(define (foo7 x) (string? x))
(when (foo7 x)
(define-type s2s (string -> symbol))
(: foo8 s2s)
(define (foo8 x) (string->symbol x))
(: foo9 s2s)
(declare (enforce-argument-types foo9))
(define (foo9 x) (string->symbol x))
(define (foo10 x)
(foo8 x)
(define (foo10 x)
1
3
Reported by :
- assignment inside first conditional does not invalidate blist
(define (write-blob-to-sql sql identifier last blob c-c)
(define ins '())
(define del '())
(if (vector? blob)
(begin
(set! ins (vector-ref blob 1))
(set! del (vector-ref blob 2))
(set! blob (vector-ref blob 0))))
(if (or (pair? ins)
(pair? del))
(<handle-ins-and-del>))
(<do-some-more>))
(module foo (blabla)
(import chicken scheme)
(define (blabla)
(+ 1 'x)))
Reported by megane in # 884 :
(module bar ()
(import chicken scheme)
(define-type footype string)
(the footype "bar"))
(: deprecated-procedure deprecated)
(define (deprecated-procedure x) (+ x x))
(deprecated-procedure 1)
(: another-deprecated-procedure (deprecated replacement-procedure))
(define (another-deprecated-procedure x) (+ x x))
(another-deprecated-procedure 2)
(: apply1 (forall (a b) (procedure ((procedure (#!rest a) b) (list-of a)) b)))
(define (apply1 f args)
(apply f args))
< - no type warning ( # 948 )
< - same here ( # 952 )
|
d1f62be3ddaf49cf779c8075c2809cdfc4d3d7f08a2cb576dbdefa3e689fb942 | nextjournal/viewers | expo.clj | (ns nextjournal.view.expo
(:require [clojure.java.io :as io]
[clojure.string :as str]))
(defmacro view-source [name]
(let [lines (-> "nextjournal/view/expo.cljs"
io/resource
slurp
(str/split #"\n"))]
`[nextjournal.viewer/inspect
{:nextjournal/value ~(->> lines
(drop-while #(not (str/includes? % (str " " name))))
(take-while #(not (re-find #"^$" %)))
(str/join "\n"))
:nextjournal/viewer :code}]))
| null | https://raw.githubusercontent.com/nextjournal/viewers/1a8e3300601780dccb18d5548f7d35b31b7934f9/modules/view/src/nextjournal/view/expo.clj | clojure | (ns nextjournal.view.expo
(:require [clojure.java.io :as io]
[clojure.string :as str]))
(defmacro view-source [name]
(let [lines (-> "nextjournal/view/expo.cljs"
io/resource
slurp
(str/split #"\n"))]
`[nextjournal.viewer/inspect
{:nextjournal/value ~(->> lines
(drop-while #(not (str/includes? % (str " " name))))
(take-while #(not (re-find #"^$" %)))
(str/join "\n"))
:nextjournal/viewer :code}]))
|
|
7221eefefd43b69992c11acbb2c888ee5bb41621141c7a75dc5227216ff2ac9c | wilkerlucio/js-data-interop | js_proxy_test.cljs | (ns com.wsscode.js-interop.js-proxy-test
(:require
[clojure.test :refer [deftest is are run-tests testing]]
[com.wsscode.js-interop.js-proxy :as jsp]
[goog.object :as gobj]))
(defn js= [a b]
(= (js/JSON.stringify a)
(js/JSON.stringify b)))
(deftest map-proxy-test
(testing "get"
(is (= (gobj/get (jsp/map-proxy {}) "foo")
nil))
(is (= (gobj/get (jsp/map-proxy {:foo "bar"}) "foo")
"bar"))
(is (= (gobj/get (jsp/map-proxy {:namespaced/kw 42}) "namespaced/kw")
42))
; only keyword keys are accessible, numbers are not
(is (= (gobj/get (jsp/map-proxy {5 10}) 5)
nil))
(testing "nested maps"
(is (= (gobj/getValueByKeys (jsp/map-proxy {:foo {:bar "baz"}}) "foo" "bar")
"baz")))
(testing "array content"
(is (= (-> (jsp/map-proxy {:foo [{:bar "baz"}]})
(gobj/get "foo")
(aget 0)
(gobj/get "bar"))
"baz")))
(testing "set sequence"
(is (= (-> (jsp/map-proxy {:foo #{{:bar "baz"}}})
(gobj/get "foo")
(aget 0)
(gobj/get "bar"))
"baz"))))
(testing "keys"
(is (js= (js/Object.keys
(jsp/map-proxy {:foo "bar"
:order/id "baz"}))
#js ["foo" "order/id"])))
(testing "ownKeys"
(is (js= (js/Object.getOwnPropertyNames
(jsp/map-proxy {:foo "bar"
:order/id "baz"}))
#js ["foo" "order/id"])))
(testing "has"
(is (= (gobj/containsKey (jsp/map-proxy {:foo "bar"}) "foo")
true))
(is (= (gobj/containsKey (jsp/map-proxy {:foo "bar"}) "bla")
false)))
(testing "json encode"
(is (= (js/JSON.stringify (jsp/map-proxy {:foo "bar" :order/id 123}))
"{\"foo\":\"bar\",\"order/id\":123}"))))
| null | https://raw.githubusercontent.com/wilkerlucio/js-data-interop/92632c4d8de8ab648e4fe2cf367ebc2193239739/test/com/wsscode/js_interop/js_proxy_test.cljs | clojure | only keyword keys are accessible, numbers are not | (ns com.wsscode.js-interop.js-proxy-test
(:require
[clojure.test :refer [deftest is are run-tests testing]]
[com.wsscode.js-interop.js-proxy :as jsp]
[goog.object :as gobj]))
(defn js= [a b]
(= (js/JSON.stringify a)
(js/JSON.stringify b)))
(deftest map-proxy-test
(testing "get"
(is (= (gobj/get (jsp/map-proxy {}) "foo")
nil))
(is (= (gobj/get (jsp/map-proxy {:foo "bar"}) "foo")
"bar"))
(is (= (gobj/get (jsp/map-proxy {:namespaced/kw 42}) "namespaced/kw")
42))
(is (= (gobj/get (jsp/map-proxy {5 10}) 5)
nil))
(testing "nested maps"
(is (= (gobj/getValueByKeys (jsp/map-proxy {:foo {:bar "baz"}}) "foo" "bar")
"baz")))
(testing "array content"
(is (= (-> (jsp/map-proxy {:foo [{:bar "baz"}]})
(gobj/get "foo")
(aget 0)
(gobj/get "bar"))
"baz")))
(testing "set sequence"
(is (= (-> (jsp/map-proxy {:foo #{{:bar "baz"}}})
(gobj/get "foo")
(aget 0)
(gobj/get "bar"))
"baz"))))
(testing "keys"
(is (js= (js/Object.keys
(jsp/map-proxy {:foo "bar"
:order/id "baz"}))
#js ["foo" "order/id"])))
(testing "ownKeys"
(is (js= (js/Object.getOwnPropertyNames
(jsp/map-proxy {:foo "bar"
:order/id "baz"}))
#js ["foo" "order/id"])))
(testing "has"
(is (= (gobj/containsKey (jsp/map-proxy {:foo "bar"}) "foo")
true))
(is (= (gobj/containsKey (jsp/map-proxy {:foo "bar"}) "bla")
false)))
(testing "json encode"
(is (= (js/JSON.stringify (jsp/map-proxy {:foo "bar" :order/id 123}))
"{\"foo\":\"bar\",\"order/id\":123}"))))
|
3a28886dafbd3b950c21ed0b68d217d8b7c0018d8cc97fb9c5a85da66dfb1c28 | WormBase/wormbase_rest | core.clj | (ns rest-api.classes.variation.core
(:require
[clojure.string :as str]
[pseudoace.utils :as pace-utils]
[rest-api.formatters.object :as obj :refer [pack-obj]]))
(def ^{:private true} molecular-change-effects
{:molecular-change/missense "Missense"
:molecular-change/nonsense "Nonsense"
:molecular-change/frameshift "Frameshift"
:molecular-change/silent "Silent"
:molecular-change/splice-site "Splice site"
:molecular-change/promoter "Promoter"
:molecular-change/genomic-neighbourhood "Genomic neighbourhood"
:molecular-change/regulatory-feature "Regulatory feature"
:molecular-change/readthrough "Readthrough"})
(defn- process-aa-change [molecular-change]
(pace-utils/cond-let
[n]
(first (:molecular-change/missense molecular-change))
(:molecular-change.missense/text n)
(:molecular-change/nonsense molecular-change)
(:molecular-change.nonsense/text n)))
(defn- process-aa-position [molecular-change]
(pace-utils/cond-let
[n]
(first (:molecular-change/missense molecular-change))
(:molecular-change.missense/int n)
(:molecular-change/nonsense molecular-change)
(nth (re-find #"\((\d+)\)"
(:molecular-change.nonsense/text n)) 1)))
(defn- change-set
"Return a the set of keys of all maps in `change-map-seqs`."
[& change-map-seqs]
(->> (apply concat change-map-seqs)
(mapcat keys)
(set)))
(defn remove-when-all-nil [x]
(when (some #(not (nil? %)) x) x))
(defn process-variation [var relevant-location?
& {:keys [window]
:or {window 20}}]
(let [slice (comp seq (partial take window))
cds-changes (->> (:variation/transcript var)
(:variation.transcript/transcript)
(:transcript/corresponding-cds)
(slice))
trans-changes (->> (:variation/transcript var)
(slice))
gene-changes (->> (:variation/gene var)
(filter #(relevant-location? (:variation.gene/gene %)))
(slice))]
(pace-utils/vmap
:variation
(pack-obj "variation" var)
:type
(if (:variation/transposon-insertion var)
"transposon insertion"
(str/join ", "
(or
(pace-utils/those
(if (:variation/engineered-allele var)
"Engineered allele")
(if (:variation/allele var)
"Allele")
(if (:variation/snp var)
"SNP")
(if (:variation/confirmed-snp var)
"Confirmed SNP")
(if (:variation/predicted-snp var)
"Predicted SNP")
(if (:variation/reference-strain-digest var)
"RFLP"))
["unknown"])))
:method_name
(if-let [method (:variation/method var)]
(format "<a class=\"longtext\" tip=\"%s\">%s</a>"
(or (:method.remark/text
(first (:method/remark methods)))
"")
(str/replace (:method/id method) #"_" " ")))
:gene
(when-let [ghs (:variation/gene var)]
(for [gh ghs
:let [gene (:variation.gene/gene gh)]]
(pack-obj gene)))
:molecular_change
(cond
(:variation/substitution var)
"Substitution"
(:variation/insertion var)
"Insertion"
(:variation/deletion var)
"Deletion"
(:variation/inversion var)
"Inversion"
(:variation/tandem-duplication var)
"Tandem_duplication"
:default
"Not curated")
:locations
(some->> trans-changes
(map (fn [tc]
(when-let [effects
(pace-utils/those
(when (:molecular-change/intron tc)
"Intron")
(when (:molecular-change/coding-exon tc)
"Coding exon")
(when (:molecular-change/genomic-neighbourhood tc)
"Genomic Neighbourhood")
(when (:molecular-change/noncoding-exon tc)
"Noncoding Exon")
(when (:molecular-change/five-prime-utr tc)
"5' UTR")
(when (:molecular-change/three-prime-utr tc)
"3' UTR"))]
(str/join ", " effects))))
(remove-when-all-nil)
(not-empty))
:effects
(let [changes (change-set cds-changes gene-changes trans-changes)]
(->> changes
(map molecular-change-effects)
(filter identity)
(remove-when-all-nil)
(not-empty)))
:composite_change
(some->> trans-changes
(map (fn [h]
(some->> (:molecular-change/amino-acid-change h)
(map :molecular-change.amino-acid-change/text)
(map (fn [s]
(str/join "<br />"
(map (partial apply str) (partition-all 20 s))))))))
(remove-when-all-nil))
:aa_position
(some->> trans-changes
(map (fn [h]
(some->> (:molecular-change/protein-position h)
(first)
(:molecular-change.protein-position/text)
(str/join "<br />"))))
(remove-when-all-nil))
:sift
(some->> trans-changes
(map (fn [h]
(some->> (:molecular-change/sift h)
(first)
((fn [sift]
(some-> (:molecular-change.sift/text sift)
(str/replace "_" " ")))))))
(remove-when-all-nil))
:transcript
(some->> trans-changes
(map :variation.transcript/transcript)
(map (fn [t]
(pack-obj t)))
(remove-when-all-nil))
:isoform
(some->> trans-changes
(map (fn [h]
(when (:molecular-change/cds-position h)
(some->> (:variation.transcript/transcript h)
(:transcript/corresponding-cds)
(:transcript.corresponding-cds/cds)
(pack-obj)))))
(remove-when-all-nil)
(not-empty))
:phen_count
(count (:variation/phenotype var))
:strain
(->> (:variation/strain var)
(map :variation.strain/strain)
(map #(pack-obj "strain" %))
(not-empty))
:sources
(let [var-refs (:variation/reference var)
sources (if (empty? var-refs)
(map #(let [packed (pack-obj %)]
(into packed
{:label
(str/replace (:label packed)
#"_" " ")}))
(:variation/analysis var))
(map #(pack-obj (:variation.reference/paper %))
var-refs))]
(not-empty sources)))))
| null | https://raw.githubusercontent.com/WormBase/wormbase_rest/b18dde4771f4e24f140b78f5a173c153688d6921/src/rest_api/classes/variation/core.clj | clojure | (ns rest-api.classes.variation.core
(:require
[clojure.string :as str]
[pseudoace.utils :as pace-utils]
[rest-api.formatters.object :as obj :refer [pack-obj]]))
(def ^{:private true} molecular-change-effects
{:molecular-change/missense "Missense"
:molecular-change/nonsense "Nonsense"
:molecular-change/frameshift "Frameshift"
:molecular-change/silent "Silent"
:molecular-change/splice-site "Splice site"
:molecular-change/promoter "Promoter"
:molecular-change/genomic-neighbourhood "Genomic neighbourhood"
:molecular-change/regulatory-feature "Regulatory feature"
:molecular-change/readthrough "Readthrough"})
(defn- process-aa-change [molecular-change]
(pace-utils/cond-let
[n]
(first (:molecular-change/missense molecular-change))
(:molecular-change.missense/text n)
(:molecular-change/nonsense molecular-change)
(:molecular-change.nonsense/text n)))
(defn- process-aa-position [molecular-change]
(pace-utils/cond-let
[n]
(first (:molecular-change/missense molecular-change))
(:molecular-change.missense/int n)
(:molecular-change/nonsense molecular-change)
(nth (re-find #"\((\d+)\)"
(:molecular-change.nonsense/text n)) 1)))
(defn- change-set
"Return a the set of keys of all maps in `change-map-seqs`."
[& change-map-seqs]
(->> (apply concat change-map-seqs)
(mapcat keys)
(set)))
(defn remove-when-all-nil [x]
(when (some #(not (nil? %)) x) x))
(defn process-variation [var relevant-location?
& {:keys [window]
:or {window 20}}]
(let [slice (comp seq (partial take window))
cds-changes (->> (:variation/transcript var)
(:variation.transcript/transcript)
(:transcript/corresponding-cds)
(slice))
trans-changes (->> (:variation/transcript var)
(slice))
gene-changes (->> (:variation/gene var)
(filter #(relevant-location? (:variation.gene/gene %)))
(slice))]
(pace-utils/vmap
:variation
(pack-obj "variation" var)
:type
(if (:variation/transposon-insertion var)
"transposon insertion"
(str/join ", "
(or
(pace-utils/those
(if (:variation/engineered-allele var)
"Engineered allele")
(if (:variation/allele var)
"Allele")
(if (:variation/snp var)
"SNP")
(if (:variation/confirmed-snp var)
"Confirmed SNP")
(if (:variation/predicted-snp var)
"Predicted SNP")
(if (:variation/reference-strain-digest var)
"RFLP"))
["unknown"])))
:method_name
(if-let [method (:variation/method var)]
(format "<a class=\"longtext\" tip=\"%s\">%s</a>"
(or (:method.remark/text
(first (:method/remark methods)))
"")
(str/replace (:method/id method) #"_" " ")))
:gene
(when-let [ghs (:variation/gene var)]
(for [gh ghs
:let [gene (:variation.gene/gene gh)]]
(pack-obj gene)))
:molecular_change
(cond
(:variation/substitution var)
"Substitution"
(:variation/insertion var)
"Insertion"
(:variation/deletion var)
"Deletion"
(:variation/inversion var)
"Inversion"
(:variation/tandem-duplication var)
"Tandem_duplication"
:default
"Not curated")
:locations
(some->> trans-changes
(map (fn [tc]
(when-let [effects
(pace-utils/those
(when (:molecular-change/intron tc)
"Intron")
(when (:molecular-change/coding-exon tc)
"Coding exon")
(when (:molecular-change/genomic-neighbourhood tc)
"Genomic Neighbourhood")
(when (:molecular-change/noncoding-exon tc)
"Noncoding Exon")
(when (:molecular-change/five-prime-utr tc)
"5' UTR")
(when (:molecular-change/three-prime-utr tc)
"3' UTR"))]
(str/join ", " effects))))
(remove-when-all-nil)
(not-empty))
:effects
(let [changes (change-set cds-changes gene-changes trans-changes)]
(->> changes
(map molecular-change-effects)
(filter identity)
(remove-when-all-nil)
(not-empty)))
:composite_change
(some->> trans-changes
(map (fn [h]
(some->> (:molecular-change/amino-acid-change h)
(map :molecular-change.amino-acid-change/text)
(map (fn [s]
(str/join "<br />"
(map (partial apply str) (partition-all 20 s))))))))
(remove-when-all-nil))
:aa_position
(some->> trans-changes
(map (fn [h]
(some->> (:molecular-change/protein-position h)
(first)
(:molecular-change.protein-position/text)
(str/join "<br />"))))
(remove-when-all-nil))
:sift
(some->> trans-changes
(map (fn [h]
(some->> (:molecular-change/sift h)
(first)
((fn [sift]
(some-> (:molecular-change.sift/text sift)
(str/replace "_" " ")))))))
(remove-when-all-nil))
:transcript
(some->> trans-changes
(map :variation.transcript/transcript)
(map (fn [t]
(pack-obj t)))
(remove-when-all-nil))
:isoform
(some->> trans-changes
(map (fn [h]
(when (:molecular-change/cds-position h)
(some->> (:variation.transcript/transcript h)
(:transcript/corresponding-cds)
(:transcript.corresponding-cds/cds)
(pack-obj)))))
(remove-when-all-nil)
(not-empty))
:phen_count
(count (:variation/phenotype var))
:strain
(->> (:variation/strain var)
(map :variation.strain/strain)
(map #(pack-obj "strain" %))
(not-empty))
:sources
(let [var-refs (:variation/reference var)
sources (if (empty? var-refs)
(map #(let [packed (pack-obj %)]
(into packed
{:label
(str/replace (:label packed)
#"_" " ")}))
(:variation/analysis var))
(map #(pack-obj (:variation.reference/paper %))
var-refs))]
(not-empty sources)))))
|
|
627e661e4d2b9f1d13aac238ea52e791b4d519a846484db26d9baebc6344404f | kennyjwilli/s3-mvn-upload | build.clj | (ns build
"sorted-multiset's build script.
clojure -T:build ci
clojure -T:build deploy
Run tests via:
clojure -X:test
For more information, run:
clojure -A:deps -T:build help/doc"
(:refer-clojure :exclude [test])
(:require [clojure.tools.build.api :as b]
[org.corfield.build :as bb]))
(def lib 's3-mvn-upload/s3-mvn-upload)
(def version (format "1.0.%s" (b/git-count-revs nil)))
(defn jar "Build lib jar." [opts]
(-> (assoc opts :lib lib :version version)
(bb/clean)
(bb/jar))
opts)
(defn deploy "Deploy the JAR to Clojars." [opts]
(-> opts
(assoc :lib lib :version version)
(bb/deploy)))
| null | https://raw.githubusercontent.com/kennyjwilli/s3-mvn-upload/d5ae45a69b205a5d6a38fb1641756203b7e00c17/build.clj | clojure | (ns build
"sorted-multiset's build script.
clojure -T:build ci
clojure -T:build deploy
Run tests via:
clojure -X:test
For more information, run:
clojure -A:deps -T:build help/doc"
(:refer-clojure :exclude [test])
(:require [clojure.tools.build.api :as b]
[org.corfield.build :as bb]))
(def lib 's3-mvn-upload/s3-mvn-upload)
(def version (format "1.0.%s" (b/git-count-revs nil)))
(defn jar "Build lib jar." [opts]
(-> (assoc opts :lib lib :version version)
(bb/clean)
(bb/jar))
opts)
(defn deploy "Deploy the JAR to Clojars." [opts]
(-> opts
(assoc :lib lib :version version)
(bb/deploy)))
|
|
04bf13592f9408f786f8e61cb39f19fa7c9f16a18bd5de5166e81686d11e2d47 | gersh/erlang-rtmp | rtmp_socket.erl | @author < > [ ]
2009
%%% @doc RTMP socket module.
%%% Designed to look like rtmp mode of usual TCP socket. If you have used {packet, http}, you will
%%% find many common behaviours.
%%%
%%% When working on server side, you should accept Socket::port() with:
%%% <pre><code>
%%% {ok, RTMP} = rtmp_socket:accept(Socket).
%%% receive
{ rtmp , RTMP , connected } - >
%%% rtmp_socket:setopts(RTMP, [{active, once}]),
%%% loop(RTMP)
%%% end
%%% loop(RTMP) ->
%%% receive
{ rtmp , RTMP , disconnect , Statistics } - >
%%% ok;
{ rtmp , RTMP , # rtmp_message { } = Message } - >
%%% io:format("Message: ~p~n", [Message]),
%%% loop(RTMP)
%%% end.
%%% </code></pre>
%%%
%%% You are strongly advised to use {active, once} mode, because in any other case it is very easy
to crash whole your server with OOM killer .
%%% @reference See <a href="" target="_top"></a> for more information
%%% @end
%%%
%%%
%%% The MIT License
%%%
Copyright ( c ) 2009
%%%
%%% 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.
%%%
%%%---------------------------------------------------------------------------------------
-module(rtmp_socket).
-author('Max Lapshin <>').
-include("../include/rtmp.hrl").
-include("rtmp_private.hrl").
-version(1.1).
-export([accept/1, connect/1, start_link/1, getopts/2, setopts/2, getstat/2, getstat/1, send/2]).
-export([status/3, status/4, prepare_status/2, prepare_status/3, invoke/2, invoke/4, prepare_invoke/3, notify/4, prepare_notify/3]).
-export([start_socket/2, start_server/3, set_socket/2]).
%% gen_fsm callbacks
-export([init/1, handle_event/3,
handle_sync_event/4, handle_info/3, terminate/3, code_change/4]).
-export([wait_for_socket_on_server/2, wait_for_socket_on_client/2, handshake_c1/2, handshake_c3/2, handshake_s1/2, loop/2, loop/3]).
@spec ( Port::integer ( ) , Name::atom ( ) , Callback::atom ( ) ) - > { ok , Pid::pid ( ) }
@doc Starts RTMP listener on port Port , registered under name Name with callback module Callback .
Callback must export one function : create_client/1
%% create_client(RTMPSocket::pid()) -> {ok, Pid::pid()}
%%
%% This function receives RTMPSocket, that is ready to send messages and after this callback function returns, this socket
%% will send rtmp_message as it is defined in overview.
%% @end
-spec(start_server(Port::integer(), Name::atom(), Callback::atom()) -> {ok, Pid::pid()}).
start_server(Port, Name, Callback) ->
rtmp_sup:start_rtmp_listener(Port, Name, Callback).
%% @spec (Socket::port()) -> {ok, RTMP::pid()}
@doc Accepts client connection on socket Socket , starts RTMP decoder , passes socket to it
and returns pid of newly created RTMP socket .
%% @end
-spec(accept(Socket::port()) -> {ok, RTMPSocket::pid()}).
accept(Socket) ->
{ok, Pid} = start_socket(accept, Socket),
setopts(Pid, [{consumer,self()}]),
{ok,Pid}.
%% @spec (Socket::port()) -> {ok, RTMP::pid()}
@doc Accepts client connection on socket Socket , starts RTMP decoder , passes socket to it
and returns pid of newly created RTMP socket .
%% @end
-spec(connect(Socket::port()) -> {ok, RTMPSocket::pid()}).
connect(Socket) ->
{ok, Pid} = start_socket(connect, Socket),
setopts(Pid, [{consumer,self()}]),
{ok,Pid}.
@spec ( Consumer::pid ( ) , Type::accept|connect , Socket::port ) - > { ok , RTMP::pid ( ) }
%% @doc Starts RTMP socket with provided consumer and inititiate server or client connection
%% @end
-spec(start_socket(Type::connect|accept, Socket::port()) -> {ok, RTMP::pid()}).
start_socket(Type, Socket) ->
{ok, RTMP} = rtmp_sup:start_rtmp_socket(Type),
case Socket of
_ when is_port(Socket) -> gen_tcp:controlling_process(Socket, RTMP);
_ -> ok
end,
set_socket(RTMP, Socket),
{ok, RTMP}.
set_socket(RTMP, Socket) ->
gen_fsm:send_event(RTMP, {socket, Socket}).
@private
start_link(Type) ->
gen_fsm:start_link(?MODULE, [Type], []).
@spec ( RTMP::pid ( ) , Options::[{Key , Value}]|{Key , Value } ) - > ok
%% @doc Just the same as {@link inet:setopts/2. inet:setopts/2} this function changes state of
%% rtmp socket.<br/>
%% Available options:
%% <ul><li><code>chunk_size</code> - change outgoing chunk size</li>
< li><code > window_size</code > - ask remote client to send read acknowlegement after WindowSize bytes</li >
< > amf_version</code > - change AMF0 to AMF3 , but only before first call</li >
%% <li><code>consumer</code> - change messages consumer</li>
%% <li><code>debug = true|false</code> - dump all important packets or no</li>
%% </ul>
%% @end
-spec(setopts(RTMP::rtmp_socket_pid(), Options::[{Key::atom(), Value::any()}]) -> ok).
setopts(RTMP, Options) ->
gen_fsm:send_all_state_event(RTMP, {setopts, Options}).
@spec ( RTMP::pid ( ) , Options::[{Key , Value}]|{Key , Value } ) - > ok
%% @doc Just the same as {@link inet:getopts/2. inet:getopts/2} this function gets state of
%% rtmp socket.<br/>
%% Available options:
%% <ul>
%% <li><code>chunk_size</code> - get outgoing chunk size</li>
%% <li><code>window_size</code> - get remote client read acknowlegement window size bytes</li>
< > amf_version</code > - get AMF0 or AMF3</li >
%% <li><code>consumer</code> - get messages consumer</li>
%% <li><code>address</code> - get remote client IP and port</li>
%% </ul>
%% @end
-spec(getopts(RTMP::rtmp_socket_pid(), Options::[Key::atom()]) -> ok).
getopts(RTMP, Options) ->
gen_fsm:sync_send_all_state_event(RTMP, {getopts, Options}, ?RTMP_TIMEOUT).
@spec ( RTMP::pid ( ) , Stats::[Key ] ) - > Values::[{Key , Value } ]
%% @doc Just the same as {@link inet:getstats/2. inet:getstats/2} this function gets statistics of
%% rtmp socket.<br/>
%% Available options:
%% <ul>
< li><code > recv_oct</code > - number of bytes received to the socket.</li >
%% <li><code>send_oct</code> - number of bytes sent from the socket</li>
%% </ul>
%% @end
-spec(getstat(RTMP::rtmp_socket_pid(), Options::[Key::atom()]) -> ok).
getstat(RTMP, Options) ->
gen_fsm:sync_send_all_state_event(RTMP, {getstat, Options}, ?RTMP_TIMEOUT).
@spec ( RTMP::pid ( ) ) - > Values::[{Key , Value } ]
%% @doc Just the same as {@link inet:getstats/1. inet:getstats/1} this function gets statistics of
%% rtmp socket.<br/>
-spec(getstat(RTMP::rtmp_socket_pid()) -> ok).
getstat(RTMP) ->
gen_fsm:sync_send_all_state_event(RTMP, getstat, ?RTMP_TIMEOUT).
@spec ( RTMP::pid ( ) , ( ) ) - > ok
%% @doc Sends message to client.
%% @end
-spec(send(RTMP::rtmp_socket_pid(), Message::rtmp_message()) -> ok).
send(RTMP, Message) ->
% io:format("Message ~p ~p ~p~n", [Message#rtmp_message.type, Message#rtmp_message.timestamp, Message#rtmp_message.stream_id]),
case process_info(RTMP , message_queue_len ) of
{ message_queue_len , Length } when Length < 20 - > RTMP ! Message ;
{ message_queue_len , Length } - > gen_fsm : , Message , ? RTMP_TIMEOUT ) ;
% _ -> ok
% end,
RTMP ! Message,
ok.
notify(RTMP, StreamId, Name, Args) ->
send(RTMP, prepare_notify(StreamId, Name, Args)).
prepare_notify(StreamId, Name, Args) ->
Arg = {object, lists:ukeymerge(1, [{level, <<"status">>}], lists:keysort(1, Args))},
#rtmp_message{type = metadata, channel_id = rtmp_lib:channel_id(audio, StreamId), stream_id = StreamId, body = [Name, Arg], timestamp = same}.
prepare_status(StreamId, Code) when is_list(Code) ->
prepare_status(StreamId, list_to_binary(Code), <<"-">>);
prepare_status(StreamId, Code) when is_binary(Code) ->
prepare_status(StreamId, Code, <<"-">>).
-spec(prepare_status(StreamId::non_neg_integer(), Code::any_string(), Description::any_string()) -> rtmp_message()).
prepare_status(StreamId, Code, Description) ->
Arg = {object, [
{code, Code},
{level, <<"status">>},
{description, Description}
]},
prepare_invoke(StreamId, onStatus, [Arg]).
status(RTMP, StreamId, Code, Description) ->
send(RTMP, prepare_status(StreamId, Code, Description)).
-spec(status(RTMP::rtmp_socket_pid(), StreamId::integer(), Code::any_string()) -> ok).
status(RTMP, StreamId, Code) when is_list(Code) ->
status(RTMP, StreamId, list_to_binary(Code), <<"-">>);
status(RTMP, StreamId, Code) when is_binary(Code) ->
status(RTMP, StreamId, Code, <<"-">>).
prepare_invoke(StreamId, Command, Args) when is_integer(StreamId) ->
AMF = #rtmp_funcall{
command = Command,
type = invoke,
id = 0,
stream_id = StreamId,
args = [null | Args ]},
#rtmp_message{stream_id = StreamId, type = invoke, body = AMF}.
invoke(RTMP, StreamId, Command, Args) ->
send(RTMP, prepare_invoke(StreamId, Command, Args)).
invoke(RTMP, #rtmp_funcall{stream_id = StreamId} = AMF) ->
send(RTMP, #rtmp_message{stream_id = StreamId, type = invoke, body = AMF}).
init_codec() ->
Path = code:lib_dir(rtmp,ebin) ++ "/rtmp_codec_drv.so",
case filelib:is_file(Path) of
true ->
case erl_ddll:load(code:lib_dir(rtmp,ebin), "rtmp_codec_drv") of
ok ->
open_port({spawn, rtmp_codec_drv}, [binary]);
{error, Error} ->
error_logger:error_msg("Error loading ~p: ~p", [rtmp_codec_drv, erl_ddll:format_error(Error)]),
undefined
end;
false ->
undefined
end.
@private
init([accept]) ->
{ok, wait_for_socket_on_server, #rtmp_socket{codec = init_codec(), channels = {}, out_channels = {}, active = false}, ?RTMP_TIMEOUT};
init([connect]) ->
{ok, wait_for_socket_on_client, #rtmp_socket{codec = init_codec(), channels = {}, out_channels = {}, active = false}, ?RTMP_TIMEOUT}.
@private
wait_for_socket_on_server(timeout, State) ->
{stop, normal, State};
wait_for_socket_on_server({socket, Socket}, #rtmp_socket{} = State) when is_port(Socket) ->
inet:setopts(Socket, [{active, once}, {packet, raw}, binary]),
{ok, {IP, Port}} = inet:peername(Socket),
{next_state, handshake_c1, State#rtmp_socket{socket = Socket, address = IP, port = Port}, ?RTMP_TIMEOUT};
wait_for_socket_on_server({socket, Socket}, #rtmp_socket{} = State) when is_pid(Socket) ->
link(Socket),
{next_state, handshake_c1, State#rtmp_socket{socket = Socket}, ?RTMP_TIMEOUT}.
@private
-spec(wait_for_socket_on_client(Message::any(), Socket::rtmp_socket()) -> no_return()).
wait_for_socket_on_client({socket, Socket}, #rtmp_socket{} = State) ->
inet:setopts(Socket, [{active, once}, {packet, raw}, binary]),
{ok, {IP, Port}} = inet:peername(Socket),
State1 = State#rtmp_socket{socket = Socket, address = IP, port = Port},
send_data(State1, [?HS_HEADER, rtmp_handshake:c1()]),
{next_state, handshake_s1, State1, ?RTMP_TIMEOUT}.
@private
handshake_c1(timeout, State) ->
{stop, normal, State}.
@private
handshake_c3(timeout, State) ->
{stop, normal, State}.
@private
handshake_s1(timeout, State) ->
{stop, normal, State}.
@private
loop(timeout, #rtmp_socket{pinged = false} = State) ->
send_data(State, #rtmp_message{type = ping}),
{next_state, loop, State#rtmp_socket{pinged = true}, ?RTMP_TIMEOUT};
loop(timeout, #rtmp_socket{consumer = Consumer} = State) ->
Consumer ! {rtmp, self(), timeout},
{stop, normal, State}.
@private
loop(#rtmp_message{} = Message, _From, State) ->
State1 = send_data(State, Message),
{reply, ok, loop, State1}.
-type(rtmp_option() ::active|amf_version|chunk_size|window_size|client_buffer|address).
% -type(rtmp_option_value() ::{rtmp_option(), any()}).
-spec(get_options(State::rtmp_socket(), Key::rtmp_option()|[rtmp_option()]) -> term()).
get_options(State, active) ->
{active, State#rtmp_socket.active};
get_options(State, amf_version) ->
{amf_version, State#rtmp_socket.amf_version};
get_options(State, chunk_size) ->
{chunk_size, State#rtmp_socket.server_chunk_size};
get_options(State, window_size) ->
{window_size, State#rtmp_socket.window_size};
get_options(State, client_buffer) ->
{client_buffer, State#rtmp_socket.client_buffer};
get_options(State, debug) ->
{debug, State#rtmp_socket.debug};
get_options(State, address) ->
{address, {State#rtmp_socket.address, State#rtmp_socket.port}};
get_options(_State, []) ->
[];
get_options(State, [Key | Options]) ->
[get_options(State, Key) | get_options(State, Options)].
get_stat(State) ->
get_stat(State, [recv_oct, send_oct]).
get_stat(State, recv_oct) ->
{recv_oct, State#rtmp_socket.bytes_read};
get_stat(State, send_oct) ->
{send_oct, State#rtmp_socket.bytes_sent};
get_stat(_State, []) ->
[];
get_stat(State, [Key | Options]) ->
[get_stat(State, Key) | get_stat(State, Options)].
set_options(State, [{amf_version, Version} | Options]) ->
set_options(State#rtmp_socket{amf_version = Version}, Options);
set_options(#rtmp_socket{socket = Socket, buffer = Data} = State, [{active, Active} | Options]) ->
State1 = flush_send(State#rtmp_socket{active = Active}),
State2 = case Active of
false ->
inet:setopts(Socket, [{active, false}]),
State1;
true ->
inet:setopts(Socket, [{active, true}]),
State1;
once ->
handle_rtmp_data(State1, Data)
end,
set_options(State2, Options);
set_options(#rtmp_socket{} = State, [{debug, Debug} | Options]) ->
io:format("Set debug to ~p~n", [Debug]),
set_options(State#rtmp_socket{debug = Debug}, Options);
set_options(#rtmp_socket{consumer = PrevConsumer} = State, [{consumer, Consumer} | Options]) ->
(catch unlink(PrevConsumer)),
(catch link(Consumer)),
set_options(State#rtmp_socket{consumer = Consumer}, Options);
set_options(State, [{chunk_size, ChunkSize} | Options]) ->
send_data(State, #rtmp_message{type = chunk_size, body = ChunkSize}),
set_options(State#rtmp_socket{server_chunk_size = ChunkSize}, Options);
set_options(State, []) -> State.
%%-------------------------------------------------------------------------
%% Func: handle_event/3
Returns : { next_state , NextStateName , NextStateData } |
{ next_state , NextStateName , NextStateData , Timeout } |
{ stop , , NewStateData }
@private
%%-------------------------------------------------------------------------
handle_event({setopts, Options}, StateName, State) ->
NewState = set_options(State, Options),
{next_state, StateName, NewState, ?RTMP_TIMEOUT};
handle_event(Event, StateName, StateData) ->
{stop, {StateName, undefined_event, Event}, StateData}.
%%-------------------------------------------------------------------------
%% Func: handle_sync_event/4
Returns : { next_state , NextStateName , NextStateData } |
{ next_state , NextStateName , NextStateData , Timeout } |
{ reply , Reply , NextStateName , NextStateData } |
{ reply , Reply , NextStateName , NextStateData , Timeout } |
{ stop , , NewStateData } |
%% {stop, Reason, Reply, NewStateData}
@private
%%-------------------------------------------------------------------------
handle_sync_event({getopts, Options}, _From, StateName, State) ->
{reply, get_options(State, Options), StateName, State};
handle_sync_event({getstat, Options}, _From, StateName, State) ->
{reply, get_stat(State, Options), StateName, State};
handle_sync_event(getstat, _From, StateName, State) ->
{reply, get_stat(State), StateName, State};
handle_sync_event(Event, _From, StateName, StateData) ->
{stop, {StateName, undefined_event, Event}, StateData}.
%%-------------------------------------------------------------------------
%% Func: handle_info/3
Returns : { next_state , NextStateName , NextStateData } |
{ next_state , NextStateName , NextStateData , Timeout } |
{ stop , , NewStateData }
@private
%%-------------------------------------------------------------------------
handle_info({tcp, Socket, Data}, handshake_c1, #rtmp_socket{socket=Socket, buffer = Buffer, bytes_read = BytesRead} = State) when size(Buffer) + size(Data) < ?HS_BODY_LEN + 1 ->
activate_socket(Socket),
{next_state, handshake_c1, State#rtmp_socket{buffer = <<Buffer/binary, Data/binary>>, bytes_read = BytesRead + size(Data)}, ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, handshake_c1, #rtmp_socket{socket=Socket, buffer = Buffer, bytes_read = BytesRead} = State) ->
activate_socket(Socket),
<<?HS_HEADER, Handshake:?HS_BODY_LEN/binary, Rest/binary>> = <<Buffer/binary, Data/binary>>,
send_data(State, [?HS_HEADER, rtmp_handshake:s1(), rtmp_handshake:s2(Handshake)]),
{next_state, 'handshake_c3', State#rtmp_socket{buffer = Rest, bytes_read = BytesRead + size(Data)}, ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, handshake_c3, #rtmp_socket{socket=Socket, buffer = Buffer, bytes_read = BytesRead} = State) when size(Buffer) + size(Data) < ?HS_BODY_LEN ->
activate_socket(Socket),
{next_state, handshake_c3, State#rtmp_socket{buffer = <<Buffer/binary, Data/binary>>, bytes_read = BytesRead + size(Data)}, ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, handshake_c3, #rtmp_socket{socket=Socket, consumer = Consumer, buffer = Buffer, bytes_read = BytesRead, active = Active} = State) ->
<<_HandShakeC3:?HS_BODY_LEN/binary, Rest/binary>> = <<Buffer/binary, Data/binary>>,
Consumer ! {rtmp, self(), connected},
case Active of
true -> inet:setopts(Socket, [{active, true}]);
_ -> ok
end,
{next_state, loop, handle_rtmp_data(State#rtmp_socket{bytes_read = BytesRead + size(Data)}, Rest), ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, handshake_s1, #rtmp_socket{socket=Socket, buffer = Buffer, bytes_read = BytesRead} = State) when size(Buffer) + size(Data) < ?HS_BODY_LEN*2 + 1 ->
activate_socket(Socket),
{next_state, handshake_s1, State#rtmp_socket{buffer = <<Buffer/binary, Data/binary>>, bytes_read = BytesRead + size(Data)}, ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, handshake_s1, #rtmp_socket{socket=Socket, consumer = Consumer, buffer = Buffer, bytes_read = BytesRead, active = Active} = State) ->
<<?HS_HEADER, _S1:?HS_BODY_LEN/binary, S2:?HS_BODY_LEN/binary, Rest/binary>> = <<Buffer/binary, Data/binary>>,
send_data(State, rtmp_handshake:c2(S2)),
Consumer ! {rtmp, self(), connected},
case Active of
true -> inet:setopts(Socket, [{active, true}]);
_ -> ok
end,
{next_state, loop, handle_rtmp_data(State#rtmp_socket{bytes_read = BytesRead + size(Data)}, Rest), ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, loop, #rtmp_socket{socket=Socket, buffer = Buffer, bytes_read = BytesRead, bytes_unack = BytesUnack} = State) ->
State1 = flush_send(State),
{next_state, loop, handle_rtmp_data(State1#rtmp_socket{bytes_read = BytesRead + size(Data), bytes_unack = BytesUnack + size(Data)}, <<Buffer/binary, Data/binary>>), ?RTMP_TIMEOUT};
handle_info({tcp_closed, Socket}, _StateName, #rtmp_socket{socket = Socket, consumer = Consumer} = StateData) ->
Consumer ! {rtmp, self(), disconnect, get_stat(StateData)},
{stop, normal, StateData};
handle_info(#rtmp_message{} = Message, loop, State) ->
State1 = send_data(State, Message),
State2 = flush_send(State1),
{next_state, loop, State2, ?RTMP_TIMEOUT};
handle_info({rtmpt, RTMPT, alive}, StateName, #rtmp_socket{socket = RTMPT} = State) ->
{next_state, StateName, State#rtmp_socket{pinged = false}, ?RTMP_TIMEOUT};
handle_info({rtmpt, RTMPT, Data}, StateName, State) ->
handle_info({tcp, RTMPT, Data}, StateName, State);
handle_info(_Info, StateName, StateData) ->
error_logger:error_msg("Unknown message to rtmp socket: ~p ~p~n", [_Info, StateData]),
{next_state, StateName, StateData, ?RTMP_TIMEOUT}.
flush_send(State) -> flush_send([], State).
flush_send(Packet, State) ->
receive
#rtmp_message{} = Message ->
{NewState, Data} = rtmp:encode(State, Message),
flush_send([Data | Packet], NewState)
after
0 ->
send_data(State, lists:reverse(Packet))
end.
activate_socket(Socket) when is_port(Socket) ->
inet:setopts(Socket, [{active, once}]);
activate_socket(Socket) when is_pid(Socket) ->
ok.
% FIXME: make here proper handling of flushing message queue
send_data(#rtmp_socket{socket = Socket} = State, Message) ->
{NewState, Data} = case Message of
#rtmp_message{} -> rtmp:encode(State, Message);
_ -> {State, Message}
end,
if
is_port(Socket) ->
gen_tcp:send(Socket, Data);
is_pid(Socket) ->
rtmpt:write(Socket, Data)
end,
NewState.
handle_rtmp_data(#rtmp_socket{bytes_unack = Bytes, window_size = Window} = State, Data) when Bytes >= Window ->
State1 = send_data(State, #rtmp_message{type = ack_read}),
handle_rtmp_data(State1#rtmp_socket{}, Data);
handle_rtmp_data(#rtmp_socket{debug = true} = State, Data) ->
Decode = rtmp:decode(State, Data),
case Decode of
% {_, #rtmp_message{type = audio}, _} -> ok;
% {_, #rtmp_message{type = video}, _} -> ok;
{_, #rtmp_message{channel_id = Channel, ts_type = TSType, timestamp = TS, type = Type, stream_id = StreamId, body = Body}, _} ->
DecodedBody = case Type of
video when size(Body) > 10 -> flv:decode_video_tag(Body);
audio when size(Body) > 0 -> flv:decode_audio_tag(Body);
_ -> Body
end,
io:format("~p ~p ~p ~p ~p ~p~n", [Channel, TSType, TS, Type, StreamId, DecodedBody]);
_ -> ok
end,
handle_rtmp_message(Decode);
handle_rtmp_data(#rtmp_socket{} = State, Data) ->
handle_rtmp_message(rtmp:decode(State, Data)).
handle_rtmp_message({#rtmp_socket{consumer = Consumer} = State, #rtmp_message{type = window_size, body = Size} = Message, Rest}) ->
Consumer ! {rtmp, self(), Message},
rtmp_message_sent(State#rtmp_socket{window_size = Size, buffer = Rest});
handle_rtmp_message({#rtmp_socket{consumer = Consumer, pinged = true} = State, #rtmp_message{type = pong} = Message, Rest}) ->
Consumer ! {rtmp, self(), Message},
rtmp_message_sent(State#rtmp_socket{pinged = false, buffer = Rest});
handle_rtmp_message({#rtmp_socket{consumer = Consumer} = State, #rtmp_message{type = ping, body = Timestamp} = Message, Rest}) ->
Consumer ! {rtmp, self(), Message},
send_data(State, #rtmp_message{type = pong, body = Timestamp}),
rtmp_message_sent(State#rtmp_socket{buffer = Rest});
handle_rtmp_message({#rtmp_socket{consumer = Consumer} = State, Message, Rest}) ->
Consumer ! {rtmp, self(), Message},
rtmp_message_sent(State#rtmp_socket{buffer = Rest});
handle_rtmp_message({#rtmp_socket{socket=Socket} = State, Rest}) ->
activate_socket(Socket),
State#rtmp_socket{buffer = Rest}.
rtmp_message_sent(#rtmp_socket{active = true, buffer = Data} = State) ->
handle_rtmp_data(State, Data);
rtmp_message_sent(State) ->
State.
%%-------------------------------------------------------------------------
Func : terminate/3
Purpose : Shutdown the fsm
%% Returns: any
@private
%%-------------------------------------------------------------------------
terminate(_Reason, _StateName, #rtmp_socket{socket=Socket}) when is_pid(Socket) ->
gen_server:cast(Socket, close),
ok;
terminate(_Reason, _StateName, #rtmp_socket{socket=Socket}) when is_port(Socket) ->
(catch gen_tcp:close(Socket)),
ok.
%%-------------------------------------------------------------------------
%% Func: code_change/4
%% Purpose: Convert process state when code is changed
Returns : { ok , NewState , NewStateData }
@private
%%-------------------------------------------------------------------------
code_change(_OldVersion, _StateName, _State, _Extra) ->
ok.
| null | https://raw.githubusercontent.com/gersh/erlang-rtmp/57157fb3be20278af19c87232f99aa9a83041d18/src/rtmp_socket.erl | erlang | @doc RTMP socket module.
Designed to look like rtmp mode of usual TCP socket. If you have used {packet, http}, you will
find many common behaviours.
When working on server side, you should accept Socket::port() with:
<pre><code>
{ok, RTMP} = rtmp_socket:accept(Socket).
receive
rtmp_socket:setopts(RTMP, [{active, once}]),
loop(RTMP)
end
loop(RTMP) ->
receive
ok;
io:format("Message: ~p~n", [Message]),
loop(RTMP)
end.
</code></pre>
You are strongly advised to use {active, once} mode, because in any other case it is very easy
@reference See <a href="" target="_top"></a> for more information
@end
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------------------
gen_fsm callbacks
create_client(RTMPSocket::pid()) -> {ok, Pid::pid()}
This function receives RTMPSocket, that is ready to send messages and after this callback function returns, this socket
will send rtmp_message as it is defined in overview.
@end
@spec (Socket::port()) -> {ok, RTMP::pid()}
@end
@spec (Socket::port()) -> {ok, RTMP::pid()}
@end
@doc Starts RTMP socket with provided consumer and inititiate server or client connection
@end
@doc Just the same as {@link inet:setopts/2. inet:setopts/2} this function changes state of
rtmp socket.<br/>
Available options:
<ul><li><code>chunk_size</code> - change outgoing chunk size</li>
<li><code>consumer</code> - change messages consumer</li>
<li><code>debug = true|false</code> - dump all important packets or no</li>
</ul>
@end
@doc Just the same as {@link inet:getopts/2. inet:getopts/2} this function gets state of
rtmp socket.<br/>
Available options:
<ul>
<li><code>chunk_size</code> - get outgoing chunk size</li>
<li><code>window_size</code> - get remote client read acknowlegement window size bytes</li>
<li><code>consumer</code> - get messages consumer</li>
<li><code>address</code> - get remote client IP and port</li>
</ul>
@end
@doc Just the same as {@link inet:getstats/2. inet:getstats/2} this function gets statistics of
rtmp socket.<br/>
Available options:
<ul>
<li><code>send_oct</code> - number of bytes sent from the socket</li>
</ul>
@end
@doc Just the same as {@link inet:getstats/1. inet:getstats/1} this function gets statistics of
rtmp socket.<br/>
@doc Sends message to client.
@end
io:format("Message ~p ~p ~p~n", [Message#rtmp_message.type, Message#rtmp_message.timestamp, Message#rtmp_message.stream_id]),
_ -> ok
end,
-type(rtmp_option_value() ::{rtmp_option(), any()}).
-------------------------------------------------------------------------
Func: handle_event/3
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Func: handle_sync_event/4
{stop, Reason, Reply, NewStateData}
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Func: handle_info/3
-------------------------------------------------------------------------
FIXME: make here proper handling of flushing message queue
{_, #rtmp_message{type = audio}, _} -> ok;
{_, #rtmp_message{type = video}, _} -> ok;
-------------------------------------------------------------------------
Returns: any
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Func: code_change/4
Purpose: Convert process state when code is changed
------------------------------------------------------------------------- | @author < > [ ]
2009
{ rtmp , RTMP , connected } - >
{ rtmp , RTMP , disconnect , Statistics } - >
{ rtmp , RTMP , # rtmp_message { } = Message } - >
to crash whole your server with OOM killer .
Copyright ( c ) 2009
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
-module(rtmp_socket).
-author('Max Lapshin <>').
-include("../include/rtmp.hrl").
-include("rtmp_private.hrl").
-version(1.1).
-export([accept/1, connect/1, start_link/1, getopts/2, setopts/2, getstat/2, getstat/1, send/2]).
-export([status/3, status/4, prepare_status/2, prepare_status/3, invoke/2, invoke/4, prepare_invoke/3, notify/4, prepare_notify/3]).
-export([start_socket/2, start_server/3, set_socket/2]).
-export([init/1, handle_event/3,
handle_sync_event/4, handle_info/3, terminate/3, code_change/4]).
-export([wait_for_socket_on_server/2, wait_for_socket_on_client/2, handshake_c1/2, handshake_c3/2, handshake_s1/2, loop/2, loop/3]).
@spec ( Port::integer ( ) , Name::atom ( ) , Callback::atom ( ) ) - > { ok , Pid::pid ( ) }
@doc Starts RTMP listener on port Port , registered under name Name with callback module Callback .
Callback must export one function : create_client/1
-spec(start_server(Port::integer(), Name::atom(), Callback::atom()) -> {ok, Pid::pid()}).
start_server(Port, Name, Callback) ->
rtmp_sup:start_rtmp_listener(Port, Name, Callback).
@doc Accepts client connection on socket Socket , starts RTMP decoder , passes socket to it
and returns pid of newly created RTMP socket .
-spec(accept(Socket::port()) -> {ok, RTMPSocket::pid()}).
accept(Socket) ->
{ok, Pid} = start_socket(accept, Socket),
setopts(Pid, [{consumer,self()}]),
{ok,Pid}.
@doc Accepts client connection on socket Socket , starts RTMP decoder , passes socket to it
and returns pid of newly created RTMP socket .
-spec(connect(Socket::port()) -> {ok, RTMPSocket::pid()}).
connect(Socket) ->
{ok, Pid} = start_socket(connect, Socket),
setopts(Pid, [{consumer,self()}]),
{ok,Pid}.
@spec ( Consumer::pid ( ) , Type::accept|connect , Socket::port ) - > { ok , RTMP::pid ( ) }
-spec(start_socket(Type::connect|accept, Socket::port()) -> {ok, RTMP::pid()}).
start_socket(Type, Socket) ->
{ok, RTMP} = rtmp_sup:start_rtmp_socket(Type),
case Socket of
_ when is_port(Socket) -> gen_tcp:controlling_process(Socket, RTMP);
_ -> ok
end,
set_socket(RTMP, Socket),
{ok, RTMP}.
set_socket(RTMP, Socket) ->
gen_fsm:send_event(RTMP, {socket, Socket}).
@private
start_link(Type) ->
gen_fsm:start_link(?MODULE, [Type], []).
@spec ( RTMP::pid ( ) , Options::[{Key , Value}]|{Key , Value } ) - > ok
< li><code > window_size</code > - ask remote client to send read acknowlegement after WindowSize bytes</li >
< > amf_version</code > - change AMF0 to AMF3 , but only before first call</li >
-spec(setopts(RTMP::rtmp_socket_pid(), Options::[{Key::atom(), Value::any()}]) -> ok).
setopts(RTMP, Options) ->
gen_fsm:send_all_state_event(RTMP, {setopts, Options}).
@spec ( RTMP::pid ( ) , Options::[{Key , Value}]|{Key , Value } ) - > ok
< > amf_version</code > - get AMF0 or AMF3</li >
-spec(getopts(RTMP::rtmp_socket_pid(), Options::[Key::atom()]) -> ok).
getopts(RTMP, Options) ->
gen_fsm:sync_send_all_state_event(RTMP, {getopts, Options}, ?RTMP_TIMEOUT).
@spec ( RTMP::pid ( ) , Stats::[Key ] ) - > Values::[{Key , Value } ]
< li><code > recv_oct</code > - number of bytes received to the socket.</li >
-spec(getstat(RTMP::rtmp_socket_pid(), Options::[Key::atom()]) -> ok).
getstat(RTMP, Options) ->
gen_fsm:sync_send_all_state_event(RTMP, {getstat, Options}, ?RTMP_TIMEOUT).
@spec ( RTMP::pid ( ) ) - > Values::[{Key , Value } ]
-spec(getstat(RTMP::rtmp_socket_pid()) -> ok).
getstat(RTMP) ->
gen_fsm:sync_send_all_state_event(RTMP, getstat, ?RTMP_TIMEOUT).
@spec ( RTMP::pid ( ) , ( ) ) - > ok
-spec(send(RTMP::rtmp_socket_pid(), Message::rtmp_message()) -> ok).
send(RTMP, Message) ->
case process_info(RTMP , message_queue_len ) of
{ message_queue_len , Length } when Length < 20 - > RTMP ! Message ;
{ message_queue_len , Length } - > gen_fsm : , Message , ? RTMP_TIMEOUT ) ;
RTMP ! Message,
ok.
notify(RTMP, StreamId, Name, Args) ->
send(RTMP, prepare_notify(StreamId, Name, Args)).
prepare_notify(StreamId, Name, Args) ->
Arg = {object, lists:ukeymerge(1, [{level, <<"status">>}], lists:keysort(1, Args))},
#rtmp_message{type = metadata, channel_id = rtmp_lib:channel_id(audio, StreamId), stream_id = StreamId, body = [Name, Arg], timestamp = same}.
prepare_status(StreamId, Code) when is_list(Code) ->
prepare_status(StreamId, list_to_binary(Code), <<"-">>);
prepare_status(StreamId, Code) when is_binary(Code) ->
prepare_status(StreamId, Code, <<"-">>).
-spec(prepare_status(StreamId::non_neg_integer(), Code::any_string(), Description::any_string()) -> rtmp_message()).
prepare_status(StreamId, Code, Description) ->
Arg = {object, [
{code, Code},
{level, <<"status">>},
{description, Description}
]},
prepare_invoke(StreamId, onStatus, [Arg]).
status(RTMP, StreamId, Code, Description) ->
send(RTMP, prepare_status(StreamId, Code, Description)).
-spec(status(RTMP::rtmp_socket_pid(), StreamId::integer(), Code::any_string()) -> ok).
status(RTMP, StreamId, Code) when is_list(Code) ->
status(RTMP, StreamId, list_to_binary(Code), <<"-">>);
status(RTMP, StreamId, Code) when is_binary(Code) ->
status(RTMP, StreamId, Code, <<"-">>).
prepare_invoke(StreamId, Command, Args) when is_integer(StreamId) ->
AMF = #rtmp_funcall{
command = Command,
type = invoke,
id = 0,
stream_id = StreamId,
args = [null | Args ]},
#rtmp_message{stream_id = StreamId, type = invoke, body = AMF}.
invoke(RTMP, StreamId, Command, Args) ->
send(RTMP, prepare_invoke(StreamId, Command, Args)).
invoke(RTMP, #rtmp_funcall{stream_id = StreamId} = AMF) ->
send(RTMP, #rtmp_message{stream_id = StreamId, type = invoke, body = AMF}).
init_codec() ->
Path = code:lib_dir(rtmp,ebin) ++ "/rtmp_codec_drv.so",
case filelib:is_file(Path) of
true ->
case erl_ddll:load(code:lib_dir(rtmp,ebin), "rtmp_codec_drv") of
ok ->
open_port({spawn, rtmp_codec_drv}, [binary]);
{error, Error} ->
error_logger:error_msg("Error loading ~p: ~p", [rtmp_codec_drv, erl_ddll:format_error(Error)]),
undefined
end;
false ->
undefined
end.
@private
init([accept]) ->
{ok, wait_for_socket_on_server, #rtmp_socket{codec = init_codec(), channels = {}, out_channels = {}, active = false}, ?RTMP_TIMEOUT};
init([connect]) ->
{ok, wait_for_socket_on_client, #rtmp_socket{codec = init_codec(), channels = {}, out_channels = {}, active = false}, ?RTMP_TIMEOUT}.
@private
wait_for_socket_on_server(timeout, State) ->
{stop, normal, State};
wait_for_socket_on_server({socket, Socket}, #rtmp_socket{} = State) when is_port(Socket) ->
inet:setopts(Socket, [{active, once}, {packet, raw}, binary]),
{ok, {IP, Port}} = inet:peername(Socket),
{next_state, handshake_c1, State#rtmp_socket{socket = Socket, address = IP, port = Port}, ?RTMP_TIMEOUT};
wait_for_socket_on_server({socket, Socket}, #rtmp_socket{} = State) when is_pid(Socket) ->
link(Socket),
{next_state, handshake_c1, State#rtmp_socket{socket = Socket}, ?RTMP_TIMEOUT}.
@private
-spec(wait_for_socket_on_client(Message::any(), Socket::rtmp_socket()) -> no_return()).
wait_for_socket_on_client({socket, Socket}, #rtmp_socket{} = State) ->
inet:setopts(Socket, [{active, once}, {packet, raw}, binary]),
{ok, {IP, Port}} = inet:peername(Socket),
State1 = State#rtmp_socket{socket = Socket, address = IP, port = Port},
send_data(State1, [?HS_HEADER, rtmp_handshake:c1()]),
{next_state, handshake_s1, State1, ?RTMP_TIMEOUT}.
@private
handshake_c1(timeout, State) ->
{stop, normal, State}.
@private
handshake_c3(timeout, State) ->
{stop, normal, State}.
@private
handshake_s1(timeout, State) ->
{stop, normal, State}.
@private
loop(timeout, #rtmp_socket{pinged = false} = State) ->
send_data(State, #rtmp_message{type = ping}),
{next_state, loop, State#rtmp_socket{pinged = true}, ?RTMP_TIMEOUT};
loop(timeout, #rtmp_socket{consumer = Consumer} = State) ->
Consumer ! {rtmp, self(), timeout},
{stop, normal, State}.
@private
loop(#rtmp_message{} = Message, _From, State) ->
State1 = send_data(State, Message),
{reply, ok, loop, State1}.
-type(rtmp_option() ::active|amf_version|chunk_size|window_size|client_buffer|address).
-spec(get_options(State::rtmp_socket(), Key::rtmp_option()|[rtmp_option()]) -> term()).
get_options(State, active) ->
{active, State#rtmp_socket.active};
get_options(State, amf_version) ->
{amf_version, State#rtmp_socket.amf_version};
get_options(State, chunk_size) ->
{chunk_size, State#rtmp_socket.server_chunk_size};
get_options(State, window_size) ->
{window_size, State#rtmp_socket.window_size};
get_options(State, client_buffer) ->
{client_buffer, State#rtmp_socket.client_buffer};
get_options(State, debug) ->
{debug, State#rtmp_socket.debug};
get_options(State, address) ->
{address, {State#rtmp_socket.address, State#rtmp_socket.port}};
get_options(_State, []) ->
[];
get_options(State, [Key | Options]) ->
[get_options(State, Key) | get_options(State, Options)].
get_stat(State) ->
get_stat(State, [recv_oct, send_oct]).
get_stat(State, recv_oct) ->
{recv_oct, State#rtmp_socket.bytes_read};
get_stat(State, send_oct) ->
{send_oct, State#rtmp_socket.bytes_sent};
get_stat(_State, []) ->
[];
get_stat(State, [Key | Options]) ->
[get_stat(State, Key) | get_stat(State, Options)].
set_options(State, [{amf_version, Version} | Options]) ->
set_options(State#rtmp_socket{amf_version = Version}, Options);
set_options(#rtmp_socket{socket = Socket, buffer = Data} = State, [{active, Active} | Options]) ->
State1 = flush_send(State#rtmp_socket{active = Active}),
State2 = case Active of
false ->
inet:setopts(Socket, [{active, false}]),
State1;
true ->
inet:setopts(Socket, [{active, true}]),
State1;
once ->
handle_rtmp_data(State1, Data)
end,
set_options(State2, Options);
set_options(#rtmp_socket{} = State, [{debug, Debug} | Options]) ->
io:format("Set debug to ~p~n", [Debug]),
set_options(State#rtmp_socket{debug = Debug}, Options);
set_options(#rtmp_socket{consumer = PrevConsumer} = State, [{consumer, Consumer} | Options]) ->
(catch unlink(PrevConsumer)),
(catch link(Consumer)),
set_options(State#rtmp_socket{consumer = Consumer}, Options);
set_options(State, [{chunk_size, ChunkSize} | Options]) ->
send_data(State, #rtmp_message{type = chunk_size, body = ChunkSize}),
set_options(State#rtmp_socket{server_chunk_size = ChunkSize}, Options);
set_options(State, []) -> State.
Returns : { next_state , NextStateName , NextStateData } |
{ next_state , NextStateName , NextStateData , Timeout } |
{ stop , , NewStateData }
@private
handle_event({setopts, Options}, StateName, State) ->
NewState = set_options(State, Options),
{next_state, StateName, NewState, ?RTMP_TIMEOUT};
handle_event(Event, StateName, StateData) ->
{stop, {StateName, undefined_event, Event}, StateData}.
Returns : { next_state , NextStateName , NextStateData } |
{ next_state , NextStateName , NextStateData , Timeout } |
{ reply , Reply , NextStateName , NextStateData } |
{ reply , Reply , NextStateName , NextStateData , Timeout } |
{ stop , , NewStateData } |
@private
handle_sync_event({getopts, Options}, _From, StateName, State) ->
{reply, get_options(State, Options), StateName, State};
handle_sync_event({getstat, Options}, _From, StateName, State) ->
{reply, get_stat(State, Options), StateName, State};
handle_sync_event(getstat, _From, StateName, State) ->
{reply, get_stat(State), StateName, State};
handle_sync_event(Event, _From, StateName, StateData) ->
{stop, {StateName, undefined_event, Event}, StateData}.
Returns : { next_state , NextStateName , NextStateData } |
{ next_state , NextStateName , NextStateData , Timeout } |
{ stop , , NewStateData }
@private
handle_info({tcp, Socket, Data}, handshake_c1, #rtmp_socket{socket=Socket, buffer = Buffer, bytes_read = BytesRead} = State) when size(Buffer) + size(Data) < ?HS_BODY_LEN + 1 ->
activate_socket(Socket),
{next_state, handshake_c1, State#rtmp_socket{buffer = <<Buffer/binary, Data/binary>>, bytes_read = BytesRead + size(Data)}, ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, handshake_c1, #rtmp_socket{socket=Socket, buffer = Buffer, bytes_read = BytesRead} = State) ->
activate_socket(Socket),
<<?HS_HEADER, Handshake:?HS_BODY_LEN/binary, Rest/binary>> = <<Buffer/binary, Data/binary>>,
send_data(State, [?HS_HEADER, rtmp_handshake:s1(), rtmp_handshake:s2(Handshake)]),
{next_state, 'handshake_c3', State#rtmp_socket{buffer = Rest, bytes_read = BytesRead + size(Data)}, ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, handshake_c3, #rtmp_socket{socket=Socket, buffer = Buffer, bytes_read = BytesRead} = State) when size(Buffer) + size(Data) < ?HS_BODY_LEN ->
activate_socket(Socket),
{next_state, handshake_c3, State#rtmp_socket{buffer = <<Buffer/binary, Data/binary>>, bytes_read = BytesRead + size(Data)}, ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, handshake_c3, #rtmp_socket{socket=Socket, consumer = Consumer, buffer = Buffer, bytes_read = BytesRead, active = Active} = State) ->
<<_HandShakeC3:?HS_BODY_LEN/binary, Rest/binary>> = <<Buffer/binary, Data/binary>>,
Consumer ! {rtmp, self(), connected},
case Active of
true -> inet:setopts(Socket, [{active, true}]);
_ -> ok
end,
{next_state, loop, handle_rtmp_data(State#rtmp_socket{bytes_read = BytesRead + size(Data)}, Rest), ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, handshake_s1, #rtmp_socket{socket=Socket, buffer = Buffer, bytes_read = BytesRead} = State) when size(Buffer) + size(Data) < ?HS_BODY_LEN*2 + 1 ->
activate_socket(Socket),
{next_state, handshake_s1, State#rtmp_socket{buffer = <<Buffer/binary, Data/binary>>, bytes_read = BytesRead + size(Data)}, ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, handshake_s1, #rtmp_socket{socket=Socket, consumer = Consumer, buffer = Buffer, bytes_read = BytesRead, active = Active} = State) ->
<<?HS_HEADER, _S1:?HS_BODY_LEN/binary, S2:?HS_BODY_LEN/binary, Rest/binary>> = <<Buffer/binary, Data/binary>>,
send_data(State, rtmp_handshake:c2(S2)),
Consumer ! {rtmp, self(), connected},
case Active of
true -> inet:setopts(Socket, [{active, true}]);
_ -> ok
end,
{next_state, loop, handle_rtmp_data(State#rtmp_socket{bytes_read = BytesRead + size(Data)}, Rest), ?RTMP_TIMEOUT};
handle_info({tcp, Socket, Data}, loop, #rtmp_socket{socket=Socket, buffer = Buffer, bytes_read = BytesRead, bytes_unack = BytesUnack} = State) ->
State1 = flush_send(State),
{next_state, loop, handle_rtmp_data(State1#rtmp_socket{bytes_read = BytesRead + size(Data), bytes_unack = BytesUnack + size(Data)}, <<Buffer/binary, Data/binary>>), ?RTMP_TIMEOUT};
handle_info({tcp_closed, Socket}, _StateName, #rtmp_socket{socket = Socket, consumer = Consumer} = StateData) ->
Consumer ! {rtmp, self(), disconnect, get_stat(StateData)},
{stop, normal, StateData};
handle_info(#rtmp_message{} = Message, loop, State) ->
State1 = send_data(State, Message),
State2 = flush_send(State1),
{next_state, loop, State2, ?RTMP_TIMEOUT};
handle_info({rtmpt, RTMPT, alive}, StateName, #rtmp_socket{socket = RTMPT} = State) ->
{next_state, StateName, State#rtmp_socket{pinged = false}, ?RTMP_TIMEOUT};
handle_info({rtmpt, RTMPT, Data}, StateName, State) ->
handle_info({tcp, RTMPT, Data}, StateName, State);
handle_info(_Info, StateName, StateData) ->
error_logger:error_msg("Unknown message to rtmp socket: ~p ~p~n", [_Info, StateData]),
{next_state, StateName, StateData, ?RTMP_TIMEOUT}.
flush_send(State) -> flush_send([], State).
flush_send(Packet, State) ->
receive
#rtmp_message{} = Message ->
{NewState, Data} = rtmp:encode(State, Message),
flush_send([Data | Packet], NewState)
after
0 ->
send_data(State, lists:reverse(Packet))
end.
activate_socket(Socket) when is_port(Socket) ->
inet:setopts(Socket, [{active, once}]);
activate_socket(Socket) when is_pid(Socket) ->
ok.
send_data(#rtmp_socket{socket = Socket} = State, Message) ->
{NewState, Data} = case Message of
#rtmp_message{} -> rtmp:encode(State, Message);
_ -> {State, Message}
end,
if
is_port(Socket) ->
gen_tcp:send(Socket, Data);
is_pid(Socket) ->
rtmpt:write(Socket, Data)
end,
NewState.
handle_rtmp_data(#rtmp_socket{bytes_unack = Bytes, window_size = Window} = State, Data) when Bytes >= Window ->
State1 = send_data(State, #rtmp_message{type = ack_read}),
handle_rtmp_data(State1#rtmp_socket{}, Data);
handle_rtmp_data(#rtmp_socket{debug = true} = State, Data) ->
Decode = rtmp:decode(State, Data),
case Decode of
{_, #rtmp_message{channel_id = Channel, ts_type = TSType, timestamp = TS, type = Type, stream_id = StreamId, body = Body}, _} ->
DecodedBody = case Type of
video when size(Body) > 10 -> flv:decode_video_tag(Body);
audio when size(Body) > 0 -> flv:decode_audio_tag(Body);
_ -> Body
end,
io:format("~p ~p ~p ~p ~p ~p~n", [Channel, TSType, TS, Type, StreamId, DecodedBody]);
_ -> ok
end,
handle_rtmp_message(Decode);
handle_rtmp_data(#rtmp_socket{} = State, Data) ->
handle_rtmp_message(rtmp:decode(State, Data)).
handle_rtmp_message({#rtmp_socket{consumer = Consumer} = State, #rtmp_message{type = window_size, body = Size} = Message, Rest}) ->
Consumer ! {rtmp, self(), Message},
rtmp_message_sent(State#rtmp_socket{window_size = Size, buffer = Rest});
handle_rtmp_message({#rtmp_socket{consumer = Consumer, pinged = true} = State, #rtmp_message{type = pong} = Message, Rest}) ->
Consumer ! {rtmp, self(), Message},
rtmp_message_sent(State#rtmp_socket{pinged = false, buffer = Rest});
handle_rtmp_message({#rtmp_socket{consumer = Consumer} = State, #rtmp_message{type = ping, body = Timestamp} = Message, Rest}) ->
Consumer ! {rtmp, self(), Message},
send_data(State, #rtmp_message{type = pong, body = Timestamp}),
rtmp_message_sent(State#rtmp_socket{buffer = Rest});
handle_rtmp_message({#rtmp_socket{consumer = Consumer} = State, Message, Rest}) ->
Consumer ! {rtmp, self(), Message},
rtmp_message_sent(State#rtmp_socket{buffer = Rest});
handle_rtmp_message({#rtmp_socket{socket=Socket} = State, Rest}) ->
activate_socket(Socket),
State#rtmp_socket{buffer = Rest}.
rtmp_message_sent(#rtmp_socket{active = true, buffer = Data} = State) ->
handle_rtmp_data(State, Data);
rtmp_message_sent(State) ->
State.
Func : terminate/3
Purpose : Shutdown the fsm
@private
terminate(_Reason, _StateName, #rtmp_socket{socket=Socket}) when is_pid(Socket) ->
gen_server:cast(Socket, close),
ok;
terminate(_Reason, _StateName, #rtmp_socket{socket=Socket}) when is_port(Socket) ->
(catch gen_tcp:close(Socket)),
ok.
Returns : { ok , NewState , NewStateData }
@private
code_change(_OldVersion, _StateName, _State, _Extra) ->
ok.
|
65cc13d81e580073d8ada87e3cb7cc22ed73cdf9f2d37114abb784abb0ce69f4 | 8c6794b6/haskell-sc-scratch | SerializeExt.hs | # LANGUAGE NoMonomorphismRestriction #
------------------------------------------------------------------------------
-- |
-- Module : $Header$
CopyRight : ( c ) 8c6794b6
-- License : BSD3
Maintainer :
-- Stability : unstable
-- Portability : non-portable
--
-- Lecture: <-final/course/SerializeExt.hs>
--
module SerializeExt where
import Intro2
import ExtF
import Serialize (Tree(..))
import qualified Serialize as S
instance MulSYM Tree where
mul e1 e2 = Node "Mul" [e1,e2]
tfm1_tree = S.toTree tfm1
tfm2_tree = S.toTree tfm2
fromTreeExt self t = case t of
Node "Mul" [e1,e2] -> mul (self e1) (self e2)
_ -> S.fromTreeExt self t
fromTree = S.fix fromTreeExt | null | https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Oleg/TTF/SerializeExt.hs | haskell | ----------------------------------------------------------------------------
|
Module : $Header$
License : BSD3
Stability : unstable
Portability : non-portable
Lecture: <-final/course/SerializeExt.hs>
| # LANGUAGE NoMonomorphismRestriction #
CopyRight : ( c ) 8c6794b6
Maintainer :
module SerializeExt where
import Intro2
import ExtF
import Serialize (Tree(..))
import qualified Serialize as S
instance MulSYM Tree where
mul e1 e2 = Node "Mul" [e1,e2]
tfm1_tree = S.toTree tfm1
tfm2_tree = S.toTree tfm2
fromTreeExt self t = case t of
Node "Mul" [e1,e2] -> mul (self e1) (self e2)
_ -> S.fromTreeExt self t
fromTree = S.fix fromTreeExt |
b5c05fb7a5aae88f5301a945d351241405ef39f882784c036db7eb652d0e9431 | achirkin/vulkan | VK_AMD_draw_indirect_count.hs | # OPTIONS_GHC -fno - warn - orphans #
# OPTIONS_HADDOCK not - home #
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE ForeignFunctionInterface #
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
module Graphics.Vulkan.Ext.VK_AMD_draw_indirect_count
* Vulkan extension : @VK_AMD_draw_indirect_count@
-- |
--
-- supported: @vulkan@
--
-- contact: @Daniel Rakos @drakos-amd@
--
author :
--
-- type: @device@
--
-- Extension number: @34@
VkCmdDrawIndirectCountAMD, pattern VkCmdDrawIndirectCountAMD,
HS_vkCmdDrawIndirectCountAMD, PFN_vkCmdDrawIndirectCountAMD,
VkCmdDrawIndexedIndirectCountAMD,
pattern VkCmdDrawIndexedIndirectCountAMD,
HS_vkCmdDrawIndexedIndirectCountAMD,
PFN_vkCmdDrawIndexedIndirectCountAMD,
module Graphics.Vulkan.Marshal, AHardwareBuffer(), ANativeWindow(),
CAMetalLayer(), VkBool32(..), VkDeviceAddress(..),
VkDeviceSize(..), VkFlags(..), VkSampleMask(..),
VkAccelerationStructureKHR, VkAccelerationStructureKHR_T(),
VkAccelerationStructureNV, VkAccelerationStructureNV_T(), VkBuffer,
VkBufferView, VkBufferView_T(), VkBuffer_T(), VkCommandBuffer,
VkCommandBuffer_T(), VkCommandPool, VkCommandPool_T(),
VkDebugReportCallbackEXT, VkDebugReportCallbackEXT_T(),
VkDebugUtilsMessengerEXT, VkDebugUtilsMessengerEXT_T(),
VkDeferredOperationKHR, VkDeferredOperationKHR_T(),
VkDescriptorPool, VkDescriptorPool_T(), VkDescriptorSet,
VkDescriptorSetLayout, VkDescriptorSetLayout_T(),
VkDescriptorSet_T(), VkDescriptorUpdateTemplate,
VkDescriptorUpdateTemplateKHR, VkDescriptorUpdateTemplateKHR_T(),
VkDescriptorUpdateTemplate_T(), VkDevice, VkDeviceMemory,
VkDeviceMemory_T(), VkDevice_T(), VkDisplayKHR, VkDisplayKHR_T(),
VkDisplayModeKHR, VkDisplayModeKHR_T(), VkEvent, VkEvent_T(),
VkFence, VkFence_T(), VkFramebuffer, VkFramebuffer_T(), VkImage,
VkImageView, VkImageView_T(), VkImage_T(),
VkIndirectCommandsLayoutNV, VkIndirectCommandsLayoutNV_T(),
VkInstance, VkInstance_T(), VkPerformanceConfigurationINTEL,
VkPerformanceConfigurationINTEL_T(), VkPhysicalDevice,
VkPhysicalDevice_T(), VkPipeline, VkPipelineCache,
VkPipelineCache_T(), VkPipelineLayout, VkPipelineLayout_T(),
VkPipeline_T(), VkPrivateDataSlotEXT, VkPrivateDataSlotEXT_T(),
VkQueryPool, VkQueryPool_T(), VkQueue, VkQueue_T(), VkRenderPass,
VkRenderPass_T(), VkSampler, VkSamplerYcbcrConversion,
VkSamplerYcbcrConversionKHR, VkSamplerYcbcrConversionKHR_T(),
VkSamplerYcbcrConversion_T(), VkSampler_T(), VkSemaphore,
VkSemaphore_T(), VkShaderModule, VkShaderModule_T(), VkSurfaceKHR,
VkSurfaceKHR_T(), VkSwapchainKHR, VkSwapchainKHR_T(),
VkValidationCacheEXT, VkValidationCacheEXT_T(),
VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION,
pattern VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION,
VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME,
pattern VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Marshal.Proc (VulkanProc (..))
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Handles
pattern VkCmdDrawIndirectCountAMD :: CString
pattern VkCmdDrawIndirectCountAMD <-
(is_VkCmdDrawIndirectCountAMD -> True)
where
VkCmdDrawIndirectCountAMD = _VkCmdDrawIndirectCountAMD
{-# INLINE _VkCmdDrawIndirectCountAMD #-}
_VkCmdDrawIndirectCountAMD :: CString
_VkCmdDrawIndirectCountAMD = Ptr "vkCmdDrawIndirectCountAMD\NUL"#
# INLINE is_VkCmdDrawIndirectCountAMD #
is_VkCmdDrawIndirectCountAMD :: CString -> Bool
is_VkCmdDrawIndirectCountAMD
= (EQ ==) . cmpCStrings _VkCmdDrawIndirectCountAMD
type VkCmdDrawIndirectCountAMD = "vkCmdDrawIndirectCountAMD"
-- | This is an alias for `vkCmdDrawIndirectCount`.
--
-- Queues: 'graphics'.
--
Renderpass : @inside@
--
-- Pipeline: @graphics@
--
-- > void vkCmdDrawIndirectCountAMD
> ( VkCommandBuffer commandBuffer
> , VkBuffer buffer
-- > , VkDeviceSize offset
> ,
-- > , VkDeviceSize countBufferOffset
> , uint32_t maxDrawCount
> , uint32_t stride
-- > )
--
-- <-extensions/html/vkspec.html#vkCmdDrawIndirectCountAMD vkCmdDrawIndirectCountAMD registry at www.khronos.org>
type HS_vkCmdDrawIndirectCountAMD =
^ commandBuffer
->
VkBuffer -- ^ buffer
->
VkDeviceSize -- ^ offset
->
VkBuffer -- ^ countBuffer
-> VkDeviceSize -- ^ countBufferOffset
-> Word32 -- ^ maxDrawCount
-> Word32 -- ^ stride
-> IO ()
type PFN_vkCmdDrawIndirectCountAMD =
FunPtr HS_vkCmdDrawIndirectCountAMD
foreign import ccall unsafe "dynamic"
unwrapVkCmdDrawIndirectCountAMDUnsafe ::
PFN_vkCmdDrawIndirectCountAMD -> HS_vkCmdDrawIndirectCountAMD
foreign import ccall safe "dynamic"
unwrapVkCmdDrawIndirectCountAMDSafe ::
PFN_vkCmdDrawIndirectCountAMD -> HS_vkCmdDrawIndirectCountAMD
instance VulkanProc "vkCmdDrawIndirectCountAMD" where
type VkProcType "vkCmdDrawIndirectCountAMD" =
HS_vkCmdDrawIndirectCountAMD
vkProcSymbol = _VkCmdDrawIndirectCountAMD
# INLINE vkProcSymbol #
unwrapVkProcPtrUnsafe = unwrapVkCmdDrawIndirectCountAMDUnsafe
# INLINE unwrapVkProcPtrUnsafe #
unwrapVkProcPtrSafe = unwrapVkCmdDrawIndirectCountAMDSafe
# INLINE unwrapVkProcPtrSafe #
pattern VkCmdDrawIndexedIndirectCountAMD :: CString
pattern VkCmdDrawIndexedIndirectCountAMD <-
(is_VkCmdDrawIndexedIndirectCountAMD -> True)
where
VkCmdDrawIndexedIndirectCountAMD
= _VkCmdDrawIndexedIndirectCountAMD
{-# INLINE _VkCmdDrawIndexedIndirectCountAMD #-}
_VkCmdDrawIndexedIndirectCountAMD :: CString
_VkCmdDrawIndexedIndirectCountAMD
= Ptr "vkCmdDrawIndexedIndirectCountAMD\NUL"#
# INLINE is_VkCmdDrawIndexedIndirectCountAMD #
is_VkCmdDrawIndexedIndirectCountAMD :: CString -> Bool
is_VkCmdDrawIndexedIndirectCountAMD
= (EQ ==) . cmpCStrings _VkCmdDrawIndexedIndirectCountAMD
type VkCmdDrawIndexedIndirectCountAMD =
"vkCmdDrawIndexedIndirectCountAMD"
| This is an alias for ` vkCmdDrawIndexedIndirectCount ` .
--
-- Queues: 'graphics'.
--
Renderpass : @inside@
--
-- Pipeline: @graphics@
--
-- > void vkCmdDrawIndexedIndirectCountAMD
> ( VkCommandBuffer commandBuffer
> , VkBuffer buffer
-- > , VkDeviceSize offset
> ,
-- > , VkDeviceSize countBufferOffset
> , uint32_t maxDrawCount
> , uint32_t stride
-- > )
--
< -extensions/html/vkspec.html#vkCmdDrawIndexedIndirectCountAMD vkCmdDrawIndexedIndirectCountAMD registry at www.khronos.org >
type HS_vkCmdDrawIndexedIndirectCountAMD =
^ commandBuffer
->
VkBuffer -- ^ buffer
->
VkDeviceSize -- ^ offset
->
VkBuffer -- ^ countBuffer
-> VkDeviceSize -- ^ countBufferOffset
-> Word32 -- ^ maxDrawCount
-> Word32 -- ^ stride
-> IO ()
type PFN_vkCmdDrawIndexedIndirectCountAMD =
FunPtr HS_vkCmdDrawIndexedIndirectCountAMD
foreign import ccall unsafe "dynamic"
unwrapVkCmdDrawIndexedIndirectCountAMDUnsafe ::
PFN_vkCmdDrawIndexedIndirectCountAMD ->
HS_vkCmdDrawIndexedIndirectCountAMD
foreign import ccall safe "dynamic"
unwrapVkCmdDrawIndexedIndirectCountAMDSafe ::
PFN_vkCmdDrawIndexedIndirectCountAMD ->
HS_vkCmdDrawIndexedIndirectCountAMD
instance VulkanProc "vkCmdDrawIndexedIndirectCountAMD" where
type VkProcType "vkCmdDrawIndexedIndirectCountAMD" =
HS_vkCmdDrawIndexedIndirectCountAMD
vkProcSymbol = _VkCmdDrawIndexedIndirectCountAMD
# INLINE vkProcSymbol #
unwrapVkProcPtrUnsafe
= unwrapVkCmdDrawIndexedIndirectCountAMDUnsafe
# INLINE unwrapVkProcPtrUnsafe #
unwrapVkProcPtrSafe = unwrapVkCmdDrawIndexedIndirectCountAMDSafe
# INLINE unwrapVkProcPtrSafe #
pattern VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION :: (Num a, Eq a) =>
a
pattern VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION = 2
type VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION = 2
pattern VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME :: CString
pattern VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME <-
(is_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME -> True)
where
VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME
= _VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME
{-# INLINE _VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME #-}
_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME :: CString
_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME
= Ptr "VK_AMD_draw_indirect_count\NUL"#
# INLINE is_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME #
is_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME :: CString -> Bool
is_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME
= (EQ ==) . cmpCStrings _VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME
type VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME =
"VK_AMD_draw_indirect_count"
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Ext/VK_AMD_draw_indirect_count.hs | haskell | # LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE MagicHash #
# LANGUAGE PatternSynonyms #
# LANGUAGE Strict #
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
|
supported: @vulkan@
contact: @Daniel Rakos @drakos-amd@
type: @device@
Extension number: @34@
# INLINE _VkCmdDrawIndirectCountAMD #
| This is an alias for `vkCmdDrawIndirectCount`.
Queues: 'graphics'.
Pipeline: @graphics@
> void vkCmdDrawIndirectCountAMD
> , VkDeviceSize offset
> , VkDeviceSize countBufferOffset
> )
<-extensions/html/vkspec.html#vkCmdDrawIndirectCountAMD vkCmdDrawIndirectCountAMD registry at www.khronos.org>
^ buffer
^ offset
^ countBuffer
^ countBufferOffset
^ maxDrawCount
^ stride
# INLINE _VkCmdDrawIndexedIndirectCountAMD #
Queues: 'graphics'.
Pipeline: @graphics@
> void vkCmdDrawIndexedIndirectCountAMD
> , VkDeviceSize offset
> , VkDeviceSize countBufferOffset
> )
^ buffer
^ offset
^ countBuffer
^ countBufferOffset
^ maxDrawCount
^ stride
# INLINE _VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME # | # OPTIONS_GHC -fno - warn - orphans #
# OPTIONS_HADDOCK not - home #
# LANGUAGE FlexibleInstances #
# LANGUAGE ForeignFunctionInterface #
module Graphics.Vulkan.Ext.VK_AMD_draw_indirect_count
* Vulkan extension : @VK_AMD_draw_indirect_count@
author :
VkCmdDrawIndirectCountAMD, pattern VkCmdDrawIndirectCountAMD,
HS_vkCmdDrawIndirectCountAMD, PFN_vkCmdDrawIndirectCountAMD,
VkCmdDrawIndexedIndirectCountAMD,
pattern VkCmdDrawIndexedIndirectCountAMD,
HS_vkCmdDrawIndexedIndirectCountAMD,
PFN_vkCmdDrawIndexedIndirectCountAMD,
module Graphics.Vulkan.Marshal, AHardwareBuffer(), ANativeWindow(),
CAMetalLayer(), VkBool32(..), VkDeviceAddress(..),
VkDeviceSize(..), VkFlags(..), VkSampleMask(..),
VkAccelerationStructureKHR, VkAccelerationStructureKHR_T(),
VkAccelerationStructureNV, VkAccelerationStructureNV_T(), VkBuffer,
VkBufferView, VkBufferView_T(), VkBuffer_T(), VkCommandBuffer,
VkCommandBuffer_T(), VkCommandPool, VkCommandPool_T(),
VkDebugReportCallbackEXT, VkDebugReportCallbackEXT_T(),
VkDebugUtilsMessengerEXT, VkDebugUtilsMessengerEXT_T(),
VkDeferredOperationKHR, VkDeferredOperationKHR_T(),
VkDescriptorPool, VkDescriptorPool_T(), VkDescriptorSet,
VkDescriptorSetLayout, VkDescriptorSetLayout_T(),
VkDescriptorSet_T(), VkDescriptorUpdateTemplate,
VkDescriptorUpdateTemplateKHR, VkDescriptorUpdateTemplateKHR_T(),
VkDescriptorUpdateTemplate_T(), VkDevice, VkDeviceMemory,
VkDeviceMemory_T(), VkDevice_T(), VkDisplayKHR, VkDisplayKHR_T(),
VkDisplayModeKHR, VkDisplayModeKHR_T(), VkEvent, VkEvent_T(),
VkFence, VkFence_T(), VkFramebuffer, VkFramebuffer_T(), VkImage,
VkImageView, VkImageView_T(), VkImage_T(),
VkIndirectCommandsLayoutNV, VkIndirectCommandsLayoutNV_T(),
VkInstance, VkInstance_T(), VkPerformanceConfigurationINTEL,
VkPerformanceConfigurationINTEL_T(), VkPhysicalDevice,
VkPhysicalDevice_T(), VkPipeline, VkPipelineCache,
VkPipelineCache_T(), VkPipelineLayout, VkPipelineLayout_T(),
VkPipeline_T(), VkPrivateDataSlotEXT, VkPrivateDataSlotEXT_T(),
VkQueryPool, VkQueryPool_T(), VkQueue, VkQueue_T(), VkRenderPass,
VkRenderPass_T(), VkSampler, VkSamplerYcbcrConversion,
VkSamplerYcbcrConversionKHR, VkSamplerYcbcrConversionKHR_T(),
VkSamplerYcbcrConversion_T(), VkSampler_T(), VkSemaphore,
VkSemaphore_T(), VkShaderModule, VkShaderModule_T(), VkSurfaceKHR,
VkSurfaceKHR_T(), VkSwapchainKHR, VkSwapchainKHR_T(),
VkValidationCacheEXT, VkValidationCacheEXT_T(),
VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION,
pattern VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION,
VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME,
pattern VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Marshal.Proc (VulkanProc (..))
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Handles
pattern VkCmdDrawIndirectCountAMD :: CString
pattern VkCmdDrawIndirectCountAMD <-
(is_VkCmdDrawIndirectCountAMD -> True)
where
VkCmdDrawIndirectCountAMD = _VkCmdDrawIndirectCountAMD
_VkCmdDrawIndirectCountAMD :: CString
_VkCmdDrawIndirectCountAMD = Ptr "vkCmdDrawIndirectCountAMD\NUL"#
# INLINE is_VkCmdDrawIndirectCountAMD #
is_VkCmdDrawIndirectCountAMD :: CString -> Bool
is_VkCmdDrawIndirectCountAMD
= (EQ ==) . cmpCStrings _VkCmdDrawIndirectCountAMD
type VkCmdDrawIndirectCountAMD = "vkCmdDrawIndirectCountAMD"
Renderpass : @inside@
> ( VkCommandBuffer commandBuffer
> , VkBuffer buffer
> ,
> , uint32_t maxDrawCount
> , uint32_t stride
type HS_vkCmdDrawIndirectCountAMD =
^ commandBuffer
->
->
->
-> IO ()
type PFN_vkCmdDrawIndirectCountAMD =
FunPtr HS_vkCmdDrawIndirectCountAMD
foreign import ccall unsafe "dynamic"
unwrapVkCmdDrawIndirectCountAMDUnsafe ::
PFN_vkCmdDrawIndirectCountAMD -> HS_vkCmdDrawIndirectCountAMD
foreign import ccall safe "dynamic"
unwrapVkCmdDrawIndirectCountAMDSafe ::
PFN_vkCmdDrawIndirectCountAMD -> HS_vkCmdDrawIndirectCountAMD
instance VulkanProc "vkCmdDrawIndirectCountAMD" where
type VkProcType "vkCmdDrawIndirectCountAMD" =
HS_vkCmdDrawIndirectCountAMD
vkProcSymbol = _VkCmdDrawIndirectCountAMD
# INLINE vkProcSymbol #
unwrapVkProcPtrUnsafe = unwrapVkCmdDrawIndirectCountAMDUnsafe
# INLINE unwrapVkProcPtrUnsafe #
unwrapVkProcPtrSafe = unwrapVkCmdDrawIndirectCountAMDSafe
# INLINE unwrapVkProcPtrSafe #
pattern VkCmdDrawIndexedIndirectCountAMD :: CString
pattern VkCmdDrawIndexedIndirectCountAMD <-
(is_VkCmdDrawIndexedIndirectCountAMD -> True)
where
VkCmdDrawIndexedIndirectCountAMD
= _VkCmdDrawIndexedIndirectCountAMD
_VkCmdDrawIndexedIndirectCountAMD :: CString
_VkCmdDrawIndexedIndirectCountAMD
= Ptr "vkCmdDrawIndexedIndirectCountAMD\NUL"#
# INLINE is_VkCmdDrawIndexedIndirectCountAMD #
is_VkCmdDrawIndexedIndirectCountAMD :: CString -> Bool
is_VkCmdDrawIndexedIndirectCountAMD
= (EQ ==) . cmpCStrings _VkCmdDrawIndexedIndirectCountAMD
type VkCmdDrawIndexedIndirectCountAMD =
"vkCmdDrawIndexedIndirectCountAMD"
| This is an alias for ` vkCmdDrawIndexedIndirectCount ` .
Renderpass : @inside@
> ( VkCommandBuffer commandBuffer
> , VkBuffer buffer
> ,
> , uint32_t maxDrawCount
> , uint32_t stride
< -extensions/html/vkspec.html#vkCmdDrawIndexedIndirectCountAMD vkCmdDrawIndexedIndirectCountAMD registry at www.khronos.org >
type HS_vkCmdDrawIndexedIndirectCountAMD =
^ commandBuffer
->
->
->
-> IO ()
type PFN_vkCmdDrawIndexedIndirectCountAMD =
FunPtr HS_vkCmdDrawIndexedIndirectCountAMD
foreign import ccall unsafe "dynamic"
unwrapVkCmdDrawIndexedIndirectCountAMDUnsafe ::
PFN_vkCmdDrawIndexedIndirectCountAMD ->
HS_vkCmdDrawIndexedIndirectCountAMD
foreign import ccall safe "dynamic"
unwrapVkCmdDrawIndexedIndirectCountAMDSafe ::
PFN_vkCmdDrawIndexedIndirectCountAMD ->
HS_vkCmdDrawIndexedIndirectCountAMD
instance VulkanProc "vkCmdDrawIndexedIndirectCountAMD" where
type VkProcType "vkCmdDrawIndexedIndirectCountAMD" =
HS_vkCmdDrawIndexedIndirectCountAMD
vkProcSymbol = _VkCmdDrawIndexedIndirectCountAMD
# INLINE vkProcSymbol #
unwrapVkProcPtrUnsafe
= unwrapVkCmdDrawIndexedIndirectCountAMDUnsafe
# INLINE unwrapVkProcPtrUnsafe #
unwrapVkProcPtrSafe = unwrapVkCmdDrawIndexedIndirectCountAMDSafe
# INLINE unwrapVkProcPtrSafe #
pattern VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION :: (Num a, Eq a) =>
a
pattern VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION = 2
type VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION = 2
pattern VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME :: CString
pattern VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME <-
(is_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME -> True)
where
VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME
= _VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME
_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME :: CString
_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME
= Ptr "VK_AMD_draw_indirect_count\NUL"#
# INLINE is_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME #
is_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME :: CString -> Bool
is_VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME
= (EQ ==) . cmpCStrings _VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME
type VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME =
"VK_AMD_draw_indirect_count"
|
58caa9311b8c9d76018a9f1d916761959bf0d0b60470c492b4b02de22a40bf5b | input-output-hk/cardano-prelude | Canonical.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NumDecimals #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
| Instances used in the canonical JSON encoding of ` GenesisData `
module Cardano.Prelude.Json.Canonical (
SchemaError (..),
canonicalDecodePretty,
canonicalEncodePretty,
)
where
import Cardano.Prelude.Base
import Cardano.Prelude.Json.Parse (parseJSString)
import Data.Fixed (E12, resolution)
import Data.Time (NominalDiffTime, UTCTime)
import Data.Time.Clock.POSIX (
posixSecondsToUTCTime,
utcTimeToPOSIXSeconds,
)
import Formatting (bprint, builder)
import Formatting.Buildable (Buildable (build))
import Text.JSON.Canonical (
FromJSON (fromJSON),
Int54,
JSValue (JSNum, JSString),
ReportSchemaErrors (expected),
ToJSON (toJSON),
)
import qualified Cardano.Prelude.Compat as I
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text.Lazy.Builder as Builder
import qualified Text.JSON.Canonical as CanonicalJSON
data SchemaError = SchemaError
{ seExpected :: !Text
, seActual :: !(Maybe Text)
}
deriving (Show, Eq)
instance Buildable SchemaError where
build se =
mconcat
[ bprint ("expected " . builder) $ Builder.fromText (seExpected se)
, case seActual se of
Nothing -> mempty
Just actual -> bprint (" but got " . builder) $ Builder.fromText actual
]
instance
(Applicative m, Monad m, MonadError SchemaError m) =>
ReportSchemaErrors m
where
expected expec actual =
throwError
SchemaError
{ seExpected = toS expec
, seActual = fmap toS actual
}
instance Monad m => ToJSON m Int32 where
toJSON = pure . JSNum . fromIntegral
instance Monad m => ToJSON m Word16 where
toJSON = pure . JSNum . fromIntegral
instance Monad m => ToJSON m Word32 where
toJSON = pure . JSNum . fromIntegral
instance Monad m => ToJSON m Word64 where
toJSON = pure . JSString . CanonicalJSON.toJSString . show
instance Monad m => ToJSON m Integer where
toJSON = pure . JSString . CanonicalJSON.toJSString . show
instance Monad m => ToJSON m Natural where
toJSON = pure . JSString . CanonicalJSON.toJSString . show
| For backwards compatibility we convert this to seconds
instance Monad m => ToJSON m UTCTime where
toJSON = pure . JSNum . round . utcTimeToPOSIXSeconds
-- | For backwards compatibility we convert this to microseconds
instance Monad m => ToJSON m NominalDiffTime where
toJSON = toJSON . (`div` 1e6) . toPicoseconds
where
toPicoseconds :: NominalDiffTime -> Integer
toPicoseconds t =
numerator (toRational t * toRational (resolution $ Proxy @E12))
instance ReportSchemaErrors m => FromJSON m Int32 where
fromJSON (JSNum i) = pure . fromIntegral $ i
fromJSON val = CanonicalJSON.expectedButGotValue "Int32" val
instance ReportSchemaErrors m => FromJSON m Word16 where
fromJSON (JSNum i) = pure . fromIntegral $ i
fromJSON val = CanonicalJSON.expectedButGotValue "Word16" val
instance ReportSchemaErrors m => FromJSON m Word32 where
fromJSON (JSNum i) = pure . fromIntegral $ i
fromJSON val = CanonicalJSON.expectedButGotValue "Word32" val
instance ReportSchemaErrors m => FromJSON m Word64 where
fromJSON = parseJSString (I.readEither @Word64 @Text . toS)
instance ReportSchemaErrors m => FromJSON m Integer where
fromJSON = parseJSString (I.readEither @Integer @Text . toS)
instance MonadError SchemaError m => FromJSON m Natural where
fromJSON = parseJSString (I.readEither @Natural @Text . toS)
instance MonadError SchemaError m => FromJSON m UTCTime where
fromJSON = fmap (posixSecondsToUTCTime . fromIntegral) . fromJSON @_ @Int54
instance MonadError SchemaError m => FromJSON m NominalDiffTime where
fromJSON = fmap (fromRational . (% 1e6)) . fromJSON
canonicalDecodePretty ::
forall a.
CanonicalJSON.FromJSON (Either SchemaError) a =>
LB.ByteString ->
Either Text a
canonicalDecodePretty y = do
eVal <- first toS (CanonicalJSON.parseCanonicalJSON y)
first show (CanonicalJSON.fromJSON eVal :: Either SchemaError a)
canonicalEncodePretty ::
forall a. CanonicalJSON.ToJSON Identity a => a -> LB.ByteString
canonicalEncodePretty x =
LB.fromStrict
. encodeUtf8
. toS
$ CanonicalJSON.prettyCanonicalJSON
$ runIdentity
$ CanonicalJSON.toJSON x
| null | https://raw.githubusercontent.com/input-output-hk/cardano-prelude/94b37483937cfb7c07d69a708c950a090bb9670f/cardano-prelude/src/Cardano/Prelude/Json/Canonical.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
| For backwards compatibility we convert this to microseconds | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NumDecimals #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
| Instances used in the canonical JSON encoding of ` GenesisData `
module Cardano.Prelude.Json.Canonical (
SchemaError (..),
canonicalDecodePretty,
canonicalEncodePretty,
)
where
import Cardano.Prelude.Base
import Cardano.Prelude.Json.Parse (parseJSString)
import Data.Fixed (E12, resolution)
import Data.Time (NominalDiffTime, UTCTime)
import Data.Time.Clock.POSIX (
posixSecondsToUTCTime,
utcTimeToPOSIXSeconds,
)
import Formatting (bprint, builder)
import Formatting.Buildable (Buildable (build))
import Text.JSON.Canonical (
FromJSON (fromJSON),
Int54,
JSValue (JSNum, JSString),
ReportSchemaErrors (expected),
ToJSON (toJSON),
)
import qualified Cardano.Prelude.Compat as I
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text.Lazy.Builder as Builder
import qualified Text.JSON.Canonical as CanonicalJSON
data SchemaError = SchemaError
{ seExpected :: !Text
, seActual :: !(Maybe Text)
}
deriving (Show, Eq)
instance Buildable SchemaError where
build se =
mconcat
[ bprint ("expected " . builder) $ Builder.fromText (seExpected se)
, case seActual se of
Nothing -> mempty
Just actual -> bprint (" but got " . builder) $ Builder.fromText actual
]
instance
(Applicative m, Monad m, MonadError SchemaError m) =>
ReportSchemaErrors m
where
expected expec actual =
throwError
SchemaError
{ seExpected = toS expec
, seActual = fmap toS actual
}
instance Monad m => ToJSON m Int32 where
toJSON = pure . JSNum . fromIntegral
instance Monad m => ToJSON m Word16 where
toJSON = pure . JSNum . fromIntegral
instance Monad m => ToJSON m Word32 where
toJSON = pure . JSNum . fromIntegral
instance Monad m => ToJSON m Word64 where
toJSON = pure . JSString . CanonicalJSON.toJSString . show
instance Monad m => ToJSON m Integer where
toJSON = pure . JSString . CanonicalJSON.toJSString . show
instance Monad m => ToJSON m Natural where
toJSON = pure . JSString . CanonicalJSON.toJSString . show
| For backwards compatibility we convert this to seconds
instance Monad m => ToJSON m UTCTime where
toJSON = pure . JSNum . round . utcTimeToPOSIXSeconds
instance Monad m => ToJSON m NominalDiffTime where
toJSON = toJSON . (`div` 1e6) . toPicoseconds
where
toPicoseconds :: NominalDiffTime -> Integer
toPicoseconds t =
numerator (toRational t * toRational (resolution $ Proxy @E12))
instance ReportSchemaErrors m => FromJSON m Int32 where
fromJSON (JSNum i) = pure . fromIntegral $ i
fromJSON val = CanonicalJSON.expectedButGotValue "Int32" val
instance ReportSchemaErrors m => FromJSON m Word16 where
fromJSON (JSNum i) = pure . fromIntegral $ i
fromJSON val = CanonicalJSON.expectedButGotValue "Word16" val
instance ReportSchemaErrors m => FromJSON m Word32 where
fromJSON (JSNum i) = pure . fromIntegral $ i
fromJSON val = CanonicalJSON.expectedButGotValue "Word32" val
instance ReportSchemaErrors m => FromJSON m Word64 where
fromJSON = parseJSString (I.readEither @Word64 @Text . toS)
instance ReportSchemaErrors m => FromJSON m Integer where
fromJSON = parseJSString (I.readEither @Integer @Text . toS)
instance MonadError SchemaError m => FromJSON m Natural where
fromJSON = parseJSString (I.readEither @Natural @Text . toS)
instance MonadError SchemaError m => FromJSON m UTCTime where
fromJSON = fmap (posixSecondsToUTCTime . fromIntegral) . fromJSON @_ @Int54
instance MonadError SchemaError m => FromJSON m NominalDiffTime where
fromJSON = fmap (fromRational . (% 1e6)) . fromJSON
canonicalDecodePretty ::
forall a.
CanonicalJSON.FromJSON (Either SchemaError) a =>
LB.ByteString ->
Either Text a
canonicalDecodePretty y = do
eVal <- first toS (CanonicalJSON.parseCanonicalJSON y)
first show (CanonicalJSON.fromJSON eVal :: Either SchemaError a)
canonicalEncodePretty ::
forall a. CanonicalJSON.ToJSON Identity a => a -> LB.ByteString
canonicalEncodePretty x =
LB.fromStrict
. encodeUtf8
. toS
$ CanonicalJSON.prettyCanonicalJSON
$ runIdentity
$ CanonicalJSON.toJSON x
|
d12217ae35c3581fd31675108229e358653a1214e27d0dbe5760b18bac65c28d | yurtsiv/mooncake | Eval.hs | module Interpreter.Eval where
import Data.Char (ord)
import qualified Data.Map.Strict as Map
import Interpreter.Utils
import Interpreter.Types
import qualified Parser.AST as AST
startEvaluation :: AST.Expression -> Either String Result
startEvaluation expr = do
(res, _) <- evaluate expr Map.empty
return res
evaluate :: AST.Expression -> Scope -> Either String (Result, Scope)
evaluate (AST.Integer i) scope = Right $ (Integer i, scope)
evaluate (AST.Char c) scope = Right $ (Char c, scope)
evaluate (AST.String str) scope = Right $ (String str, scope)
evaluate (AST.Bool bool) scope = Right $ (Bool bool, scope)
evaluate (AST.List exprs) scope = do
res <- sequence $ map (\e -> evaluate e scope) exprs
return $ (List $ map fst res, scope)
evaluate (AST.Function args expr) scope =
Right $ (Function Map.empty args expr, scope)
evaluate e@(AST.FunctionCall name callArgs) scope =
case Map.lookup name builtInFunctions of
Just func -> func e scope
_ -> do
(res, _) <- evaluate (AST.Identifier name) scope
case res of
Function _ _ _ -> evalFuncCall name res callArgs scope
List items -> evalListElemAccess name callArgs items scope
_ -> Left $ name ++ "is not a function or list"
evaluate (AST.If condition body) scope = do
(val, _) <- evaluate condition scope
case val of
Bool True -> evaluate body scope
Bool False -> Right $ (Empty, scope)
_ -> Left "The condition is not a boolean"
evaluate (AST.IfElse condition ifBody elseBody) scope = do
(val, _) <- evaluate condition scope
case val of
Bool True -> evaluate ifBody scope
Bool False -> evaluate elseBody scope
_ -> Left "The condition is not a boolean"
evaluate (AST.Let name expr) scope = do
(val, _) <- evaluate expr scope
return (Empty, Map.insert name val scope)
evaluate (AST.Identifier name) scope =
case (Map.lookup name scope) of
Just val -> Right (val, scope)
Nothing -> Left $ "No variable named " ++ name
evaluate (AST.Negative expr) scope = flipNumber expr scope "Infix '-' can be applied only to integers"
evaluate (AST.Positive expr) scope = flipNumber expr scope "Infix '+' can be applied only to integers"
evaluate (AST.Add expr1 expr2) scope = evalAlgebraicOp (+) expr1 expr2 scope
evaluate (AST.Sub expr1 expr2) scope = evalAlgebraicOp (-) expr1 expr2 scope
evaluate (AST.Div expr1 expr2) scope = do
(val1, _) <- evaluate expr1 scope
(val2, _) <- evaluate expr2 scope
case (val1, val2) of
(Integer v1, Integer v2) ->
if v2 == 0
then Left "Can't divide by 0"
else Right $ (Integer $ v1 `div` v2, scope)
_ -> Left "Can divide only integers"
evaluate (AST.Mul expr1 expr2) scope = evalAlgebraicOp (*) expr1 expr2 scope
evaluate (AST.Modulo expr1 expr2) scope = evalAlgebraicOp (mod) expr1 expr2 scope
evaluate (AST.Inverse expr) scope = do
(val, _) <- evaluate expr scope
case val of
Bool b -> Right $ (Bool (not b), scope)
_ -> Left "Can invert only booleans"
evaluate (AST.Or expr1 expr2) scope = evalBinBoolOp (||) expr1 expr2 scope
evaluate (AST.And expr1 expr2) scope = evalBinBoolOp (&&) expr1 expr2 scope
evaluate (AST.Gt expr1 expr2) scope = evalCompOp (>) expr1 expr2 scope
evaluate (AST.GtE expr1 expr2) scope = evalCompOp (>=) expr1 expr2 scope
evaluate (AST.Lt expr1 expr2) scope = evalCompOp (<) expr1 expr2 scope
evaluate (AST.LtE expr1 expr2) scope = evalCompOp (<=) expr1 expr2 scope
-- TODO: compare all primitive types
evaluate (AST.Eq expr1 expr2) scope = evalCompOp (==) expr1 expr2 scope
evaluate (AST.Neq expr1 expr2) scope = evalCompOp (/=) expr1 expr2 scope
evaluate (AST.Block exprs) scope = foldl evalCodeBlockItem (Right (Empty, scope)) exprs
evaluate (AST.Concat expr1 expr2) scope = do
(val1, _) <- evaluate expr1 scope
(val2, _) <- evaluate expr2 scope
case (val1, val2) of
(List elems1, List elems2) ->
Right ((List $ elems1 ++ elems2), scope)
(String str1, String str2) ->
Right ((String $ str1 ++ str2), scope)
(String str, List elems) ->
Right ((List $ (hsStringToMCList str) ++ elems), scope)
(List elems, String str) ->
Right ((List $ elems ++ (hsStringToMCList str)), scope)
_ -> Left "Can't concatenate"
evalCodeBlockItem (Right (_, scope)) expr = evaluate expr scope
evalCodeBlockItem (Left a) _ = Left a
evalAlgebraicOp op expr1 expr2 scope = do
(res1, _) <- evaluate expr1 scope
(res2, _) <- evaluate expr2 scope
case (res1, res2) of
(Integer val1, Integer val2) ->
Right $ (Integer $ op val1 val2, scope)
_ -> Left "Can perform algebraic operation only on numbers"
evalBinBoolOp op expr1 expr2 scope = do
(res1, _) <- evaluate expr1 scope
(res2, _) <- evaluate expr2 scope
case (res1, res2) of
(Bool b1, Bool b2) -> Right $ (Bool (op b1 b2), scope)
_ -> Left "Can perform operation only on booleans"
evalCompOp op expr1 expr2 scope = do
(res1, _) <- evaluate expr1 scope
(res2, _) <- evaluate expr2 scope
case (res1, res2) of
(Integer val1, Integer val2) -> Right $ (Bool $ op val1 val2, scope)
(Char c1, Char c2) -> Right $ (Bool $ op (toInteger . ord $ c1) (toInteger . ord $ c2), scope)
_ -> Left "Can only compare two comparable types"
flipNumber expr scope errMsg = do
(val, _) <- evaluate expr scope
case val of
Integer i -> Right $ (Integer $ negate i, scope)
_ -> Left $ errMsg
hsStringToMCList str = map (\c -> String [c]) str
evalLen (AST.FunctionCall _ callArgs) scope =
case callArgs of
[arg] -> do
(val, _) <- evaluate arg scope
case val of
List elems -> Right $ (Integer $ (toInteger . length) elems, scope)
String str -> Right $ (Integer $ (toInteger . length) str, scope)
_ -> Left "Can't get length"
_ ->
Left "Wrong number of arguments provided for function 'len'"
builtInFunctions = Map.fromList [("len", evalLen)]
evalFuncCall name (Function closure argNames body) callArgs scope
| (length callArgs) /= (length argNames) =
Left $ "Wrong number of arguments provided for " ++ name
| otherwise =
let evaluatedArgs = evaluate (AST.List callArgs) scope
in case evaluatedArgs of
Right (List evalArgs, _) ->
let funcScope = mergeScopes [scope, closure, (Map.fromList $ (zip argNames evalArgs))]
funcRes = evaluate body funcScope
in case funcRes of
Right (Function _ a b, s) -> Right (Function (mergeScopes [funcScope, s]) a b, scope)
Right (res, _) -> Right (res, scope)
_ -> funcRes
err -> err
evalListElemAccess name callArgs items scope
| (length callArgs) /= 1 =
Left $ "Wrong number of arguments provided for list element access"
| otherwise =
let evaluatedIndex = evaluate (callArgs !! 0) scope
in case evaluatedIndex of
Right (Integer index, _) ->
if (index >= toInteger (length items) || index < 0) then
Left $ "Index " ++ (show index) ++ " out of bound for " ++ name
else
Right $ (items !! fromInteger index, scope)
| null | https://raw.githubusercontent.com/yurtsiv/mooncake/5527188d4f9430178d1438d41ac09883c11d0bbc/src/Interpreter/Eval.hs | haskell | TODO: compare all primitive types | module Interpreter.Eval where
import Data.Char (ord)
import qualified Data.Map.Strict as Map
import Interpreter.Utils
import Interpreter.Types
import qualified Parser.AST as AST
startEvaluation :: AST.Expression -> Either String Result
startEvaluation expr = do
(res, _) <- evaluate expr Map.empty
return res
evaluate :: AST.Expression -> Scope -> Either String (Result, Scope)
evaluate (AST.Integer i) scope = Right $ (Integer i, scope)
evaluate (AST.Char c) scope = Right $ (Char c, scope)
evaluate (AST.String str) scope = Right $ (String str, scope)
evaluate (AST.Bool bool) scope = Right $ (Bool bool, scope)
evaluate (AST.List exprs) scope = do
res <- sequence $ map (\e -> evaluate e scope) exprs
return $ (List $ map fst res, scope)
evaluate (AST.Function args expr) scope =
Right $ (Function Map.empty args expr, scope)
evaluate e@(AST.FunctionCall name callArgs) scope =
case Map.lookup name builtInFunctions of
Just func -> func e scope
_ -> do
(res, _) <- evaluate (AST.Identifier name) scope
case res of
Function _ _ _ -> evalFuncCall name res callArgs scope
List items -> evalListElemAccess name callArgs items scope
_ -> Left $ name ++ "is not a function or list"
evaluate (AST.If condition body) scope = do
(val, _) <- evaluate condition scope
case val of
Bool True -> evaluate body scope
Bool False -> Right $ (Empty, scope)
_ -> Left "The condition is not a boolean"
evaluate (AST.IfElse condition ifBody elseBody) scope = do
(val, _) <- evaluate condition scope
case val of
Bool True -> evaluate ifBody scope
Bool False -> evaluate elseBody scope
_ -> Left "The condition is not a boolean"
evaluate (AST.Let name expr) scope = do
(val, _) <- evaluate expr scope
return (Empty, Map.insert name val scope)
evaluate (AST.Identifier name) scope =
case (Map.lookup name scope) of
Just val -> Right (val, scope)
Nothing -> Left $ "No variable named " ++ name
evaluate (AST.Negative expr) scope = flipNumber expr scope "Infix '-' can be applied only to integers"
evaluate (AST.Positive expr) scope = flipNumber expr scope "Infix '+' can be applied only to integers"
evaluate (AST.Add expr1 expr2) scope = evalAlgebraicOp (+) expr1 expr2 scope
evaluate (AST.Sub expr1 expr2) scope = evalAlgebraicOp (-) expr1 expr2 scope
evaluate (AST.Div expr1 expr2) scope = do
(val1, _) <- evaluate expr1 scope
(val2, _) <- evaluate expr2 scope
case (val1, val2) of
(Integer v1, Integer v2) ->
if v2 == 0
then Left "Can't divide by 0"
else Right $ (Integer $ v1 `div` v2, scope)
_ -> Left "Can divide only integers"
evaluate (AST.Mul expr1 expr2) scope = evalAlgebraicOp (*) expr1 expr2 scope
evaluate (AST.Modulo expr1 expr2) scope = evalAlgebraicOp (mod) expr1 expr2 scope
evaluate (AST.Inverse expr) scope = do
(val, _) <- evaluate expr scope
case val of
Bool b -> Right $ (Bool (not b), scope)
_ -> Left "Can invert only booleans"
evaluate (AST.Or expr1 expr2) scope = evalBinBoolOp (||) expr1 expr2 scope
evaluate (AST.And expr1 expr2) scope = evalBinBoolOp (&&) expr1 expr2 scope
evaluate (AST.Gt expr1 expr2) scope = evalCompOp (>) expr1 expr2 scope
evaluate (AST.GtE expr1 expr2) scope = evalCompOp (>=) expr1 expr2 scope
evaluate (AST.Lt expr1 expr2) scope = evalCompOp (<) expr1 expr2 scope
evaluate (AST.LtE expr1 expr2) scope = evalCompOp (<=) expr1 expr2 scope
evaluate (AST.Eq expr1 expr2) scope = evalCompOp (==) expr1 expr2 scope
evaluate (AST.Neq expr1 expr2) scope = evalCompOp (/=) expr1 expr2 scope
evaluate (AST.Block exprs) scope = foldl evalCodeBlockItem (Right (Empty, scope)) exprs
evaluate (AST.Concat expr1 expr2) scope = do
(val1, _) <- evaluate expr1 scope
(val2, _) <- evaluate expr2 scope
case (val1, val2) of
(List elems1, List elems2) ->
Right ((List $ elems1 ++ elems2), scope)
(String str1, String str2) ->
Right ((String $ str1 ++ str2), scope)
(String str, List elems) ->
Right ((List $ (hsStringToMCList str) ++ elems), scope)
(List elems, String str) ->
Right ((List $ elems ++ (hsStringToMCList str)), scope)
_ -> Left "Can't concatenate"
evalCodeBlockItem (Right (_, scope)) expr = evaluate expr scope
evalCodeBlockItem (Left a) _ = Left a
evalAlgebraicOp op expr1 expr2 scope = do
(res1, _) <- evaluate expr1 scope
(res2, _) <- evaluate expr2 scope
case (res1, res2) of
(Integer val1, Integer val2) ->
Right $ (Integer $ op val1 val2, scope)
_ -> Left "Can perform algebraic operation only on numbers"
evalBinBoolOp op expr1 expr2 scope = do
(res1, _) <- evaluate expr1 scope
(res2, _) <- evaluate expr2 scope
case (res1, res2) of
(Bool b1, Bool b2) -> Right $ (Bool (op b1 b2), scope)
_ -> Left "Can perform operation only on booleans"
evalCompOp op expr1 expr2 scope = do
(res1, _) <- evaluate expr1 scope
(res2, _) <- evaluate expr2 scope
case (res1, res2) of
(Integer val1, Integer val2) -> Right $ (Bool $ op val1 val2, scope)
(Char c1, Char c2) -> Right $ (Bool $ op (toInteger . ord $ c1) (toInteger . ord $ c2), scope)
_ -> Left "Can only compare two comparable types"
flipNumber expr scope errMsg = do
(val, _) <- evaluate expr scope
case val of
Integer i -> Right $ (Integer $ negate i, scope)
_ -> Left $ errMsg
hsStringToMCList str = map (\c -> String [c]) str
evalLen (AST.FunctionCall _ callArgs) scope =
case callArgs of
[arg] -> do
(val, _) <- evaluate arg scope
case val of
List elems -> Right $ (Integer $ (toInteger . length) elems, scope)
String str -> Right $ (Integer $ (toInteger . length) str, scope)
_ -> Left "Can't get length"
_ ->
Left "Wrong number of arguments provided for function 'len'"
builtInFunctions = Map.fromList [("len", evalLen)]
evalFuncCall name (Function closure argNames body) callArgs scope
| (length callArgs) /= (length argNames) =
Left $ "Wrong number of arguments provided for " ++ name
| otherwise =
let evaluatedArgs = evaluate (AST.List callArgs) scope
in case evaluatedArgs of
Right (List evalArgs, _) ->
let funcScope = mergeScopes [scope, closure, (Map.fromList $ (zip argNames evalArgs))]
funcRes = evaluate body funcScope
in case funcRes of
Right (Function _ a b, s) -> Right (Function (mergeScopes [funcScope, s]) a b, scope)
Right (res, _) -> Right (res, scope)
_ -> funcRes
err -> err
evalListElemAccess name callArgs items scope
| (length callArgs) /= 1 =
Left $ "Wrong number of arguments provided for list element access"
| otherwise =
let evaluatedIndex = evaluate (callArgs !! 0) scope
in case evaluatedIndex of
Right (Integer index, _) ->
if (index >= toInteger (length items) || index < 0) then
Left $ "Index " ++ (show index) ++ " out of bound for " ++ name
else
Right $ (items !! fromInteger index, scope)
|
3c15e72813849a9b82e80d8ae21571c97a636083022f385043aa877bcac0ba75 | KingMob/TrueGrit | retry.clj | (ns net.modulolotus.truegrit.retry
"Implements retries, which call a fn again when it fails (up to a limit).
See "
(:require [clojure.tools.logging.readable :as log]
[net.modulolotus.truegrit.util :as util])
(:import (io.github.resilience4j.retry Retry RetryConfig)))
(def ^:dynamic *default-config* "Set this to override the R4j defaults with your own" {})
(defn retry-config
"Creates a Resilience4j RetryConfig.
Config map options
- `:max-attempts` - # of times to try - defaults to 3
- `:wait-duration` - how long to wait after failure before trying a call again - defaults to 500 ms - accepts number of ms or java.time.Duration
- `:interval-function` - either a 1-arity fn that takes in the number of attempts so far (from 1 to n) and returns the number of ms to wait,
or an instance of io.github.resilience4j.core.IntervalFunction (see IntervalFunction for useful fns that build common wait strategies
like exponential backoff)
Less common config map options
- `:ignore-exceptions` - a coll of Throwables to ignore - e.g., [IrrelevantException IgnoreThisException] - (includes subclasses of the Throwables, too)
- `:retry-exceptions` - a coll of Throwables to retry on - defaults to all - `:ignore-exceptions` takes precedence over this
- `:retry-on-exception` - a 1-arg fn that tests a Throwable and returns true if it should be retried
- `:retry-on-result` - a 1-arg fn that tests the result and returns true if it should be retried
- `:fail-after-max-attempts?` - If :retry-on-result is set, should it throw a MaxRetriesExceededException if it reached the maximum number of attempts, but the retry-on-result predicate is still true? - defaults to false
- `:interval-bi-function` - a 2-arity fn that takes in the number of attempts so far (from 1 to n) and either a Throwable or a result - returns
the number of ms to wait - should only be used when `:retry-on-result` is also set
WARNING: `:wait-duration`, `:interval-function`, and `:interval-bi-function` conflict. Trying to set more than one will throw an exception.
"
^RetryConfig
[config]
(let [{:keys [max-attempts
wait-duration
interval-function
ignore-exceptions
retry-exceptions
retry-on-exception
retry-on-result
fail-after-max-attempts?
interval-bi-function]} (merge *default-config* config)]
(-> (RetryConfig/custom)
(cond->
max-attempts
(.maxAttempts max-attempts)
;; wait-duration and interval-function conflict
;; By placing interval-function after wait-duration, it has precedence
wait-duration
(.waitDuration (util/ms-duration wait-duration))
interval-function
(.intervalFunction (util/fn->interval-function interval-function))
ignore-exceptions
(.ignoreExceptions (into-array Class ignore-exceptions))
retry-exceptions
(.retryExceptions (into-array Class retry-exceptions))
retry-on-exception
(.retryOnException (util/fn->predicate retry-on-exception))
retry-on-result
(.retryOnResult (util/fn->predicate retry-on-result))
fail-after-max-attempts?
(.failAfterMaxAttempts fail-after-max-attempts?)
interval-bi-function
(.intervalBiFunction (util/fn->interval-bi-function interval-bi-function)))
(.build))))
(defn add-listeners
"Add event handlers for Retry lifecycle events. Note that a call that succeeds on the first
try will generate no events.
Config map options:
- `:on-event` - a handler that runs for all events
- `:on-retry` - a handler that runs after a retry - receives a RetryOnRetryEvent
- `:on-success` - a handler that runs after a successful retry (NOT a successful initial call) - receives a RetryOnSuccessEvent
- `:on-error` - a handler that runs after an error and there are no retries left - receives a RetryOnErrorEvent
- `:on-ignored-error` - a handler that runs after an error was ignored - receives a RetryOnIgnoredErrorEvent"
[^Retry rt {:keys [on-event on-retry on-success on-error on-ignored-error]}]
(let [ep (.getEventPublisher rt)]
;; Do not try this with cond-> because onEvent returns null
(when on-event (.onEvent ep (util/fn->event-consumer on-event)))
(when on-success (.onSuccess ep (util/fn->event-consumer on-success)))
(when on-retry (.onRetry ep (util/fn->event-consumer on-retry)))
(when on-error (.onError ep (util/fn->event-consumer on-error)))
(when on-ignored-error (.onIgnoredError ep (util/fn->event-consumer on-ignored-error)))))
(defn retry
"Creates a Retry with the given name and config."
^Retry
[^String retry-name config]
(doto (Retry/of retry-name (retry-config config))
(add-listeners config)))
(defn retrieve
"Retrieves a retry from a wrapped fn"
^Retry
[f]
(-> f meta :truegrit/retry))
(defn metrics
"Returns metrics for the given retry.
Numbers are for overall success of a call, not the underlying number of calls.
E.g., if it's set to retry up to 5 times, and a call fails 4 times and succeeds
on the last, that only increments `:number-of-successful-calls-with-retry-attempt`
by 1."
[^Retry rt]
(let [rt-metrics (.getMetrics rt)]
{:number-of-successful-calls-without-retry-attempt (.getNumberOfSuccessfulCallsWithoutRetryAttempt rt-metrics)
:number-of-failed-calls-without-retry-attempt (.getNumberOfFailedCallsWithoutRetryAttempt rt-metrics)
:number-of-successful-calls-with-retry-attempt (.getNumberOfSuccessfulCallsWithRetryAttempt rt-metrics)
:number-of-failed-calls-with-retry-attempt (.getNumberOfFailedCallsWithRetryAttempt rt-metrics)}))
(defn wrap
"Wraps a function in a Retry. If the max # of retries is exceeded, throws the last Exception received,
or MaxRetriesExceeded if errors didn't involve Exceptions.
Attaches the retry as metadata on the wrapped fn at :truegrit/retry"
[f ^Retry rt]
(-> (fn [& args]
(let [callable (apply util/fn->callable f args)
rt-callable (Retry/decorateCallable rt callable)]
(try
(.call rt-callable)
(catch Exception e
(log/debug e (str (.getMessage e) " - (All retries exceeded for Retry: " (some-> rt (.getName)) ")"))
(throw e)))))
(with-meta (assoc (meta f) :truegrit/retry rt))))
| null | https://raw.githubusercontent.com/KingMob/TrueGrit/e852f417899eb876c3b3200fac27ecee1975c50f/src/net/modulolotus/truegrit/retry.clj | clojure | wait-duration and interval-function conflict
By placing interval-function after wait-duration, it has precedence
Do not try this with cond-> because onEvent returns null | (ns net.modulolotus.truegrit.retry
"Implements retries, which call a fn again when it fails (up to a limit).
See "
(:require [clojure.tools.logging.readable :as log]
[net.modulolotus.truegrit.util :as util])
(:import (io.github.resilience4j.retry Retry RetryConfig)))
(def ^:dynamic *default-config* "Set this to override the R4j defaults with your own" {})
(defn retry-config
"Creates a Resilience4j RetryConfig.
Config map options
- `:max-attempts` - # of times to try - defaults to 3
- `:wait-duration` - how long to wait after failure before trying a call again - defaults to 500 ms - accepts number of ms or java.time.Duration
- `:interval-function` - either a 1-arity fn that takes in the number of attempts so far (from 1 to n) and returns the number of ms to wait,
or an instance of io.github.resilience4j.core.IntervalFunction (see IntervalFunction for useful fns that build common wait strategies
like exponential backoff)
Less common config map options
- `:ignore-exceptions` - a coll of Throwables to ignore - e.g., [IrrelevantException IgnoreThisException] - (includes subclasses of the Throwables, too)
- `:retry-exceptions` - a coll of Throwables to retry on - defaults to all - `:ignore-exceptions` takes precedence over this
- `:retry-on-exception` - a 1-arg fn that tests a Throwable and returns true if it should be retried
- `:retry-on-result` - a 1-arg fn that tests the result and returns true if it should be retried
- `:fail-after-max-attempts?` - If :retry-on-result is set, should it throw a MaxRetriesExceededException if it reached the maximum number of attempts, but the retry-on-result predicate is still true? - defaults to false
- `:interval-bi-function` - a 2-arity fn that takes in the number of attempts so far (from 1 to n) and either a Throwable or a result - returns
the number of ms to wait - should only be used when `:retry-on-result` is also set
WARNING: `:wait-duration`, `:interval-function`, and `:interval-bi-function` conflict. Trying to set more than one will throw an exception.
"
^RetryConfig
[config]
(let [{:keys [max-attempts
wait-duration
interval-function
ignore-exceptions
retry-exceptions
retry-on-exception
retry-on-result
fail-after-max-attempts?
interval-bi-function]} (merge *default-config* config)]
(-> (RetryConfig/custom)
(cond->
max-attempts
(.maxAttempts max-attempts)
wait-duration
(.waitDuration (util/ms-duration wait-duration))
interval-function
(.intervalFunction (util/fn->interval-function interval-function))
ignore-exceptions
(.ignoreExceptions (into-array Class ignore-exceptions))
retry-exceptions
(.retryExceptions (into-array Class retry-exceptions))
retry-on-exception
(.retryOnException (util/fn->predicate retry-on-exception))
retry-on-result
(.retryOnResult (util/fn->predicate retry-on-result))
fail-after-max-attempts?
(.failAfterMaxAttempts fail-after-max-attempts?)
interval-bi-function
(.intervalBiFunction (util/fn->interval-bi-function interval-bi-function)))
(.build))))
(defn add-listeners
"Add event handlers for Retry lifecycle events. Note that a call that succeeds on the first
try will generate no events.
Config map options:
- `:on-event` - a handler that runs for all events
- `:on-retry` - a handler that runs after a retry - receives a RetryOnRetryEvent
- `:on-success` - a handler that runs after a successful retry (NOT a successful initial call) - receives a RetryOnSuccessEvent
- `:on-error` - a handler that runs after an error and there are no retries left - receives a RetryOnErrorEvent
- `:on-ignored-error` - a handler that runs after an error was ignored - receives a RetryOnIgnoredErrorEvent"
[^Retry rt {:keys [on-event on-retry on-success on-error on-ignored-error]}]
(let [ep (.getEventPublisher rt)]
(when on-event (.onEvent ep (util/fn->event-consumer on-event)))
(when on-success (.onSuccess ep (util/fn->event-consumer on-success)))
(when on-retry (.onRetry ep (util/fn->event-consumer on-retry)))
(when on-error (.onError ep (util/fn->event-consumer on-error)))
(when on-ignored-error (.onIgnoredError ep (util/fn->event-consumer on-ignored-error)))))
(defn retry
"Creates a Retry with the given name and config."
^Retry
[^String retry-name config]
(doto (Retry/of retry-name (retry-config config))
(add-listeners config)))
(defn retrieve
"Retrieves a retry from a wrapped fn"
^Retry
[f]
(-> f meta :truegrit/retry))
(defn metrics
"Returns metrics for the given retry.
Numbers are for overall success of a call, not the underlying number of calls.
E.g., if it's set to retry up to 5 times, and a call fails 4 times and succeeds
on the last, that only increments `:number-of-successful-calls-with-retry-attempt`
by 1."
[^Retry rt]
(let [rt-metrics (.getMetrics rt)]
{:number-of-successful-calls-without-retry-attempt (.getNumberOfSuccessfulCallsWithoutRetryAttempt rt-metrics)
:number-of-failed-calls-without-retry-attempt (.getNumberOfFailedCallsWithoutRetryAttempt rt-metrics)
:number-of-successful-calls-with-retry-attempt (.getNumberOfSuccessfulCallsWithRetryAttempt rt-metrics)
:number-of-failed-calls-with-retry-attempt (.getNumberOfFailedCallsWithRetryAttempt rt-metrics)}))
(defn wrap
"Wraps a function in a Retry. If the max # of retries is exceeded, throws the last Exception received,
or MaxRetriesExceeded if errors didn't involve Exceptions.
Attaches the retry as metadata on the wrapped fn at :truegrit/retry"
[f ^Retry rt]
(-> (fn [& args]
(let [callable (apply util/fn->callable f args)
rt-callable (Retry/decorateCallable rt callable)]
(try
(.call rt-callable)
(catch Exception e
(log/debug e (str (.getMessage e) " - (All retries exceeded for Retry: " (some-> rt (.getName)) ")"))
(throw e)))))
(with-meta (assoc (meta f) :truegrit/retry rt))))
|
ec31d42fcb5a8be4d8526d926579ecd80525d0555fe0933c526bceee239436cd | ZHaskell/stdio | SystemTimer.hs | module Main where
import Control.Concurrent.STM
import Control.Concurrent
import Control.Monad
import GHC.Event
main :: IO ()
main = do
r <- newTVarIO 0 :: IO (TVar Int)
tm <- getSystemTimerManager
replicateM 100000 . forkIO $ do
forM_ [1..10] $ \ i -> do
registerTimeout tm (i*1000000) (atomically $ modifyTVar' r (+1))
atomically $ do
r' <- readTVar r
unless (r' == 1000000) retry
| null | https://raw.githubusercontent.com/ZHaskell/stdio/7887b9413dc9feb957ddcbea96184f904cf37c12/bench/timers/SystemTimer.hs | haskell | module Main where
import Control.Concurrent.STM
import Control.Concurrent
import Control.Monad
import GHC.Event
main :: IO ()
main = do
r <- newTVarIO 0 :: IO (TVar Int)
tm <- getSystemTimerManager
replicateM 100000 . forkIO $ do
forM_ [1..10] $ \ i -> do
registerTimeout tm (i*1000000) (atomically $ modifyTVar' r (+1))
atomically $ do
r' <- readTVar r
unless (r' == 1000000) retry
|
|
012b11360210403c718238ec4a04cd0adb9122dbe969bda5db0795975d645a7e | cedlemo/OCaml-GI-ctypes-bindings-generator | Recent_sort_type.mli | open Ctypes
type t = None | Mru | Lru | Custom
val of_value:
Unsigned.uint32 -> t
val to_value:
t -> Unsigned.uint32
val t_view: t typ
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Recent_sort_type.mli | ocaml | open Ctypes
type t = None | Mru | Lru | Custom
val of_value:
Unsigned.uint32 -> t
val to_value:
t -> Unsigned.uint32
val t_view: t typ
|
|
d7d0b0ebcad7dba31cd56cfc3ec2f64d636ac453554977fd424ce2090e3896de | fossas/fossa-cli | GopkgLock.hs | # LANGUAGE RecordWildCards #
module Strategy.Go.GopkgLock (
analyze',
GoLock (..),
Project (..),
buildGraph,
golockCodec,
) where
import Control.Effect.Diagnostics
import Data.Foldable (traverse_)
import Data.Functor (void)
import Data.Text (Text)
import DepTypes
import Diag.Common (
MissingDeepDeps (MissingDeepDeps),
MissingEdges (MissingEdges),
)
import Effect.Exec
import Effect.Grapher
import Effect.ReadFS
import Graphing (Graphing)
import Path
import Strategy.Go.Transitive (fillInTransitive)
import Strategy.Go.Types
import Toml (TomlCodec, (.=))
import Toml qualified
golockCodec :: TomlCodec GoLock
golockCodec =
GoLock
<$> Toml.list projectCodec "projects" .= lockProjects
projectCodec :: TomlCodec Project
projectCodec =
Project
<$> Toml.text "name" .= projectName
<*> Toml.dioptional (Toml.text "source") .= projectSource
<*> Toml.text "revision" .= projectRevision
newtype GoLock = GoLock
{ lockProjects :: [Project]
}
deriving (Eq, Ord, Show)
data Project = Project
{ projectName :: Text
, projectSource :: Maybe Text
, projectRevision :: Text
}
deriving (Eq, Ord, Show)
analyze' ::
( Has ReadFS sig m
, Has Exec sig m
, Has Diagnostics sig m
) =>
Path Abs File ->
m (Graphing Dependency)
analyze' file = graphingGolang $ do
golock <- readContentsToml golockCodec file
context "Building dependency graph" $ buildGraph (lockProjects golock)
void
. recover
. warnOnErr MissingDeepDeps
. warnOnErr MissingEdges
$ fillInTransitive (parent file)
buildGraph :: Has GolangGrapher sig m => [Project] -> m ()
buildGraph = void . traverse_ go
where
go :: Has GolangGrapher sig m => Project -> m ()
go Project{..} = do
let pkg = mkGolangPackage projectName
direct pkg
label pkg (mkGolangVersion projectRevision)
-- label location when it exists
traverse_ (label pkg . GolangLabelLocation) projectSource
| null | https://raw.githubusercontent.com/fossas/fossa-cli/b55bf16db5ffdbad15d40b84e8f1a47c90047e9c/src/Strategy/Go/GopkgLock.hs | haskell | label location when it exists | # LANGUAGE RecordWildCards #
module Strategy.Go.GopkgLock (
analyze',
GoLock (..),
Project (..),
buildGraph,
golockCodec,
) where
import Control.Effect.Diagnostics
import Data.Foldable (traverse_)
import Data.Functor (void)
import Data.Text (Text)
import DepTypes
import Diag.Common (
MissingDeepDeps (MissingDeepDeps),
MissingEdges (MissingEdges),
)
import Effect.Exec
import Effect.Grapher
import Effect.ReadFS
import Graphing (Graphing)
import Path
import Strategy.Go.Transitive (fillInTransitive)
import Strategy.Go.Types
import Toml (TomlCodec, (.=))
import Toml qualified
golockCodec :: TomlCodec GoLock
golockCodec =
GoLock
<$> Toml.list projectCodec "projects" .= lockProjects
projectCodec :: TomlCodec Project
projectCodec =
Project
<$> Toml.text "name" .= projectName
<*> Toml.dioptional (Toml.text "source") .= projectSource
<*> Toml.text "revision" .= projectRevision
newtype GoLock = GoLock
{ lockProjects :: [Project]
}
deriving (Eq, Ord, Show)
data Project = Project
{ projectName :: Text
, projectSource :: Maybe Text
, projectRevision :: Text
}
deriving (Eq, Ord, Show)
analyze' ::
( Has ReadFS sig m
, Has Exec sig m
, Has Diagnostics sig m
) =>
Path Abs File ->
m (Graphing Dependency)
analyze' file = graphingGolang $ do
golock <- readContentsToml golockCodec file
context "Building dependency graph" $ buildGraph (lockProjects golock)
void
. recover
. warnOnErr MissingDeepDeps
. warnOnErr MissingEdges
$ fillInTransitive (parent file)
buildGraph :: Has GolangGrapher sig m => [Project] -> m ()
buildGraph = void . traverse_ go
where
go :: Has GolangGrapher sig m => Project -> m ()
go Project{..} = do
let pkg = mkGolangPackage projectName
direct pkg
label pkg (mkGolangVersion projectRevision)
traverse_ (label pkg . GolangLabelLocation) projectSource
|
8eaeea920d7b0ceb803edb5cd92b40eb61718d545977775f4055a536f89b12bf | argp/bap | nonnegative.mli | (**************************************************************************)
(* *)
: a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software 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. *)
(* *)
(**************************************************************************)
(* This module is a contribution of Yuto Takei *)
open Sig
open Blocks
open Persistent
(** Weighted graphs without negative-cycles. *)
(** This graph maintains the invariant that it is free of such cycles that
the total length of edges involving is negative. With introduction of
those negative-cycles causes an inability to compute the shortest paths
from arbitrary vertex. By using the graph modules defined here,
introduction of such a cycle is automatically prevented. *)
(** Signature for edges' weights. *)
module type WEIGHT = sig
type label
(** Type for labels of graph edges. *)
type t
(** Type of edges' weights. *)
val weight : label -> t
(** Get the weight of an edge. *)
val compare : t -> t -> int
(** Weights must be ordered. *)
val add : t -> t -> t
(** Addition of weights. *)
val zero : t
(** Neutral element for {!add}. *)
end
module Imperative
(G: Sig.IM)
(W: WEIGHT with type label = G.E.label) : sig
include Sig.IM with module V = G.V and module E = G.E
exception Negative_cycle of G.E.t list
end
(** Persistent graphs with negative-cycle prevention *)
module Persistent
(G: Sig.P)
(W: WEIGHT with type label = G.E.label) : sig
include Sig.P with module V = G.V and module E = G.E
exception Negative_cycle of G.E.t list
* Exception [ NegativeCycle ] is raised whenever a negative cycle
is introduced for the first time ( either with [ add_edge ]
or [ add_edge_e ] )
is introduced for the first time (either with [add_edge]
or [add_edge_e]) *)
end
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/ocamlgraph/src/nonnegative.mli | ocaml | ************************************************************************
This software is free software; you can redistribute it and/or
described in file LICENSE.
This software 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.
************************************************************************
This module is a contribution of Yuto Takei
* Weighted graphs without negative-cycles.
* This graph maintains the invariant that it is free of such cycles that
the total length of edges involving is negative. With introduction of
those negative-cycles causes an inability to compute the shortest paths
from arbitrary vertex. By using the graph modules defined here,
introduction of such a cycle is automatically prevented.
* Signature for edges' weights.
* Type for labels of graph edges.
* Type of edges' weights.
* Get the weight of an edge.
* Weights must be ordered.
* Addition of weights.
* Neutral element for {!add}.
* Persistent graphs with negative-cycle prevention | : a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
open Sig
open Blocks
open Persistent
module type WEIGHT = sig
type label
type t
val weight : label -> t
val compare : t -> t -> int
val add : t -> t -> t
val zero : t
end
module Imperative
(G: Sig.IM)
(W: WEIGHT with type label = G.E.label) : sig
include Sig.IM with module V = G.V and module E = G.E
exception Negative_cycle of G.E.t list
end
module Persistent
(G: Sig.P)
(W: WEIGHT with type label = G.E.label) : sig
include Sig.P with module V = G.V and module E = G.E
exception Negative_cycle of G.E.t list
* Exception [ NegativeCycle ] is raised whenever a negative cycle
is introduced for the first time ( either with [ add_edge ]
or [ add_edge_e ] )
is introduced for the first time (either with [add_edge]
or [add_edge_e]) *)
end
|
a5ab8712df78b90187e0d1e11687125ac485658f505dba116172738e0a980b90 | j-mie6/ParsleyHaskell | Test.hs | # LANGUAGE TemplateHaskell , UnboxedTuples , ScopedTypeVariables #
module Parsley.Char.Test where
import Test.Tasty
import Test.Tasty.HUnit
import TestUtils
import qualified Parsley.Char.Parsers as Parsers
import Prelude hiding ((*>))
import Parsley ((*>))
import Parsley.Char (char, item)
tests :: TestTree
tests = testGroup "Char" [ stringTests
, oneOfTests
, noneOfTests
, tokenTests
, charTests
, itemTests
]
stringTests :: TestTree
stringTests = testGroup "string should" []
nothing :: String -> Maybe Char
nothing = $$(runParserMocked Parsers.nothing [||Parsers.nothing||])
abc :: String -> Maybe Char
abc = $$(runParserMocked Parsers.abc [||Parsers.abc||])
oneOfTests :: TestTree
oneOfTests = testGroup "oneOf should"
[ testCase "handle no options no input" $ nothing "" @?= Nothing
, testCase "handle no options with input" $ nothing "a" @?= Nothing
, testCase "parse any of characters" $ do
abc "a" @?= Just 'a'
abc "b" @?= Just 'b'
abc "c" @?= Just 'c'
, testCase "fail otherwise" $ abc "d" @?= Nothing
]
noneOfTests :: TestTree
noneOfTests = testGroup "noneOf should" []
tokenTests :: TestTree
tokenTests = testGroup "token should" []
charA :: String -> Maybe Char
charA = $$(runParserMocked (char 'a') [||char 'a'||])
charTests :: TestTree
charTests = testGroup "char should"
[ testCase "fail on empty input" $ charA "" @?= Nothing
, testCase "succeed on correct char" $ charA "a" @?= Just 'a'
, testCase "fail on wrong char" $ charA "b" @?= Nothing
]
itemTests :: TestTree
itemTests = testGroup "item should" []
| null | https://raw.githubusercontent.com/j-mie6/ParsleyHaskell/045ab78ed7af0cbb52cf8b42b6aeef5dd7f91ab2/parsley/test/Parsley/Char/Test.hs | haskell | # LANGUAGE TemplateHaskell , UnboxedTuples , ScopedTypeVariables #
module Parsley.Char.Test where
import Test.Tasty
import Test.Tasty.HUnit
import TestUtils
import qualified Parsley.Char.Parsers as Parsers
import Prelude hiding ((*>))
import Parsley ((*>))
import Parsley.Char (char, item)
tests :: TestTree
tests = testGroup "Char" [ stringTests
, oneOfTests
, noneOfTests
, tokenTests
, charTests
, itemTests
]
stringTests :: TestTree
stringTests = testGroup "string should" []
nothing :: String -> Maybe Char
nothing = $$(runParserMocked Parsers.nothing [||Parsers.nothing||])
abc :: String -> Maybe Char
abc = $$(runParserMocked Parsers.abc [||Parsers.abc||])
oneOfTests :: TestTree
oneOfTests = testGroup "oneOf should"
[ testCase "handle no options no input" $ nothing "" @?= Nothing
, testCase "handle no options with input" $ nothing "a" @?= Nothing
, testCase "parse any of characters" $ do
abc "a" @?= Just 'a'
abc "b" @?= Just 'b'
abc "c" @?= Just 'c'
, testCase "fail otherwise" $ abc "d" @?= Nothing
]
noneOfTests :: TestTree
noneOfTests = testGroup "noneOf should" []
tokenTests :: TestTree
tokenTests = testGroup "token should" []
charA :: String -> Maybe Char
charA = $$(runParserMocked (char 'a') [||char 'a'||])
charTests :: TestTree
charTests = testGroup "char should"
[ testCase "fail on empty input" $ charA "" @?= Nothing
, testCase "succeed on correct char" $ charA "a" @?= Just 'a'
, testCase "fail on wrong char" $ charA "b" @?= Nothing
]
itemTests :: TestTree
itemTests = testGroup "item should" []
|
|
b2f5906c9116b313b0cb5c3cf6cc10da51f4900a03a1f06716edb5081e534c5c | jepsen-io/jepsen | txn.clj | (ns tidb.txn
"Client for transactional workloads."
(:require [clojure.tools.logging :refer [info]]
[jepsen [client :as client]
[generator :as gen]]
[tidb.sql :as c :refer :all]))
(defn table-name
"Takes an integer and constructs a table name."
[i]
(str "txn" i))
(defn table-for
"What table should we use for the given key?"
[table-count k]
(table-name (mod (hash k) table-count)))
(defn mop!
"Executes a transactional micro-op on a connection. Returns the completed
micro-op."
[conn test table-count [f k v]]
(let [table (table-for table-count k)]
[f k (case f
:r (-> conn
(c/query [(str "select (val) from " table " where "
(if (or (:use-index test)
(:predicate-read test))
"sk"
"id")
" = ? "
(:read-lock test))
k])
first
:val)
:w (do (c/execute! conn [(str "insert into " table
" (id, sk, val) values (?, ?, ?)"
" on duplicate key update val = ?")
k k v v])
v)
:append
(let [r (c/execute!
conn
[(str "insert into " table
" (id, sk, val) values (?, ?, ?)"
" on duplicate key update val = CONCAT(val, ',', ?)")
k k (str v) (str v)])]
v))]))
(defrecord Client [conn val-type table-count]
client/Client
(open! [this test node]
(assoc this :conn (c/open node test)))
(setup! [this test]
(dotimes [i table-count]
(c/with-conn-failure-retry conn
(c/execute! conn [(str "create table if not exists " (table-name i)
" (id int not null primary key,
sk int not null,
val " val-type ")")])
(when (:use-index test)
(c/create-index! conn [(str "create index " (table-name i) "_sk_val"
" on " (table-name i) " (sk, val)")])))))
(invoke! [this test op]
(let [txn (:value op)
use-txn? (< 1 (count txn))]
;use-txn? false]
(if use-txn?
(c/with-txn op [c conn]
(assoc op :type :ok, :value
(mapv (partial mop! c test table-count) txn)))
(c/with-error-handling op
(assoc op :type :ok, :value
(mapv (partial mop! conn test table-count) txn))))))
(teardown! [this test])
(close! [this test]
(c/close! conn)))
(defn client
"Constructs a transactional client. Opts are:
:val-type An SQL type string, like \"int\", for the :val field schema.
:table-count How many tables to stripe records over."
[opts]
(Client. nil
(:val-type opts "int")
(:table-count opts 7)))
| null | https://raw.githubusercontent.com/jepsen-io/jepsen/a75d5a50dd5fa8d639a622c124bf61253460b754/tidb/src/tidb/txn.clj | clojure | use-txn? false] | (ns tidb.txn
"Client for transactional workloads."
(:require [clojure.tools.logging :refer [info]]
[jepsen [client :as client]
[generator :as gen]]
[tidb.sql :as c :refer :all]))
(defn table-name
"Takes an integer and constructs a table name."
[i]
(str "txn" i))
(defn table-for
"What table should we use for the given key?"
[table-count k]
(table-name (mod (hash k) table-count)))
(defn mop!
"Executes a transactional micro-op on a connection. Returns the completed
micro-op."
[conn test table-count [f k v]]
(let [table (table-for table-count k)]
[f k (case f
:r (-> conn
(c/query [(str "select (val) from " table " where "
(if (or (:use-index test)
(:predicate-read test))
"sk"
"id")
" = ? "
(:read-lock test))
k])
first
:val)
:w (do (c/execute! conn [(str "insert into " table
" (id, sk, val) values (?, ?, ?)"
" on duplicate key update val = ?")
k k v v])
v)
:append
(let [r (c/execute!
conn
[(str "insert into " table
" (id, sk, val) values (?, ?, ?)"
" on duplicate key update val = CONCAT(val, ',', ?)")
k k (str v) (str v)])]
v))]))
(defrecord Client [conn val-type table-count]
client/Client
(open! [this test node]
(assoc this :conn (c/open node test)))
(setup! [this test]
(dotimes [i table-count]
(c/with-conn-failure-retry conn
(c/execute! conn [(str "create table if not exists " (table-name i)
" (id int not null primary key,
sk int not null,
val " val-type ")")])
(when (:use-index test)
(c/create-index! conn [(str "create index " (table-name i) "_sk_val"
" on " (table-name i) " (sk, val)")])))))
(invoke! [this test op]
(let [txn (:value op)
use-txn? (< 1 (count txn))]
(if use-txn?
(c/with-txn op [c conn]
(assoc op :type :ok, :value
(mapv (partial mop! c test table-count) txn)))
(c/with-error-handling op
(assoc op :type :ok, :value
(mapv (partial mop! conn test table-count) txn))))))
(teardown! [this test])
(close! [this test]
(c/close! conn)))
(defn client
"Constructs a transactional client. Opts are:
:val-type An SQL type string, like \"int\", for the :val field schema.
:table-count How many tables to stripe records over."
[opts]
(Client. nil
(:val-type opts "int")
(:table-count opts 7)))
|
ba66bc446611f7db96b093e5b539b9b905bc1901a46fccdff2e80e43aaec1f33 | well-typed-lightbulbs/ocaml-esp32 | ranged_intf.ml | module type S = sig
module Endpoint : Range_intf.Endpoint_intf
module Range : Range_intf.S with type Endpoint.t = Endpoint.t
end
| null | https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/testsuite/tests/typing-misc/ranged_intf.ml | ocaml | module type S = sig
module Endpoint : Range_intf.Endpoint_intf
module Range : Range_intf.S with type Endpoint.t = Endpoint.t
end
|
|
8a0b1be2600b048a6d4876491628a2b42f6b7d7e39a99ef49e97bcc393005a8c | mfoemmel/erlang-otp | snmpa_mib.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(snmpa_mib).
%% c(snmpa_mib).
%%%-----------------------------------------------------------------
This module implements a MIB server .
%%%-----------------------------------------------------------------
%% External exports
-export([start_link/3, stop/1,
lookup/2, next/3, which_mib/2, which_mibs/1, whereis_mib/2,
load_mibs/2, unload_mibs/2,
register_subagent/3, unregister_subagent/2, info/1, info/2,
verbosity/2, dump/1, dump/2,
backup/2,
invalidate_cache/1,
gc_cache/1, gc_cache/2, gc_cache/3,
enable_cache/1, disable_cache/1,
enable_cache_autogc/1, disable_cache_autogc/1,
update_cache_gclimit/2,
update_cache_age/2,
which_cache_size/1
]).
%% Internal exports
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3]).
-include_lib("kernel/include/file.hrl").
-include("snmpa_internal.hrl").
-include("snmp_types.hrl").
-include("snmp_verbosity.hrl").
-include("snmp_debug.hrl").
-define(SERVER, ?MODULE).
-define(NO_CACHE, no_mibs_cache).
-define(DEFAULT_CACHE_USAGE, true).
-define(CACHE_GC_TICKTIME, timer:minutes(1)).
-define(DEFAULT_CACHE_AUTOGC, false).
-define(DEFAULT_CACHE_GCLIMIT, 100).
-define(DEFAULT_CACHE_AGE, timer:minutes(10)).
-define(CACHE_GC_TRIGGER, cache_gc_trigger).
-ifdef(snmp_debug).
-define(GS_START_LINK(Prio, Mibs, Opts),
gen_server:start_link(?MODULE, [Prio, Mibs, Opts], [{debug,[trace]}])).
-else.
-define(GS_START_LINK(Prio, Mibs, Opts),
gen_server:start_link(?MODULE, [Prio, Mibs, Opts], [])).
-endif.
%%-----------------------------------------------------------------
Internal Data structures
%%
State
data - is the MIB data ( defined in snmpa_mib_data )
%% meo - mib entry override
%% teo - trap (notification) entry override
%%-----------------------------------------------------------------
-record(state, {data, meo, teo, backup,
cache, cache_tmr, cache_autogc, cache_gclimit, cache_age}).
%%-----------------------------------------------------------------
%% Func: start_link/1
: is a list of mibnames .
Prio is priority of mib - server
Opts is a list of options
Purpose : starts the mib server synchronized
Returns : { ok , Pid } | { error , Reason }
%%-----------------------------------------------------------------
start_link(Prio, Mibs, Opts) ->
?d("start_link -> entry with"
"~n Prio: ~p"
"~n Mibs: ~p"
"~n Opts: ~p", [Prio, Mibs, Opts]),
?GS_START_LINK(Prio, Mibs, Opts).
verbosity(MibServer, Verbosity) ->
cast(MibServer, {verbosity,Verbosity}).
stop(MibServer) ->
call(MibServer, stop).
invalidate_cache(MibServer) ->
call(MibServer, invalidate_cache).
gc_cache(MibServer) ->
call(MibServer, gc_cache).
gc_cache(MibServer, Age) ->
call(MibServer, {gc_cache, Age}).
gc_cache(MibServer, Age, GcLimit) ->
call(MibServer, {gc_cache, Age, GcLimit}).
which_cache_size(MibServer) ->
call(MibServer, cache_size).
enable_cache(MibServer) ->
update_cache_opts(MibServer, cache, true).
disable_cache(MibServer) ->
update_cache_opts(MibServer, cache, false).
enable_cache_autogc(MibServer) ->
update_cache_opts(MibServer, autogc, true).
disable_cache_autogc(MibServer) ->
update_cache_opts(MibServer, autogc, false).
update_cache_gclimit(MibServer, GcLimit)
when ((is_integer(GcLimit) andalso (GcLimit > 0)) orelse
(GcLimit =:= infinity)) ->
update_cache_opts(MibServer, gclimit, GcLimit);
update_cache_gclimit(_, BadLimit) ->
{error, {bad_gclimit, BadLimit}}.
update_cache_age(MibServer, Age)
when is_integer(Age) andalso (Age > 0) ->
update_cache_opts(MibServer, age, Age);
update_cache_age(_, BadAge) ->
{error, {bad_age, BadAge}}.
update_cache_opts(MibServer, Key, Value) ->
call(MibServer, {update_cache_opts, Key, Value}).
%%-----------------------------------------------------------------
%% Func: lookup/2
Purpose : Finds the mib entry corresponding to the Oid . If it is a
variable , the Oid must be < Oid for var>.0 and if it is
a table , Oid must be < table>.<entry>.<col>.<any >
%% Returns: {variable, MibEntry} |
{ table_column , MibEntry , TableEntryOid } |
%% {subagent, SubAgentPid} |
%% false
%%-----------------------------------------------------------------
lookup(MibServer, Oid) ->
call(MibServer, {lookup, Oid}).
which_mib(MibServer, Oid) ->
call(MibServer, {which_mib, Oid}).
%%-----------------------------------------------------------------
Func : next/3
Purpose : Finds the lexicographically next oid .
Returns : { subagent , SubAgentPid , SANextOid } |
%% endOfMibView |
%% genErr |
NextOid
The SANextOid is used by the agent if the SubAgent returns
endOfMib , in a new call to next/2 .
%%-----------------------------------------------------------------
next(MibServer, Oid, MibView) ->
call(MibServer, {next, Oid, MibView}).
%%----------------------------------------------------------------------
Purpose : Loads mibs into the mib process .
: is a list of Filenames ( compiled ) .
%% Returns: ok | {error, Reason}
%%----------------------------------------------------------------------
load_mibs(MibServer, Mibs) ->
call(MibServer, {load_mibs, Mibs}).
%%----------------------------------------------------------------------
Purpose : Loads mibs into the mib process .
: is a list of Filenames ( compiled ) .
%% Returns: ok | {error, Reason}
%%----------------------------------------------------------------------
unload_mibs(MibServer, Mibs) ->
call(MibServer, {unload_mibs, Mibs}).
%%----------------------------------------------------------------------
%% Purpose: Simple management functions
: Mib is the name of the mib ( atom )
%% Returns: ok | {error, Reason}
%%----------------------------------------------------------------------
which_mibs(MibServer) ->
call(MibServer, which_mibs).
whereis_mib(MibServer, Mib) ->
call(MibServer, {whereis_mib, Mib}).
%%----------------------------------------------------------------------
Registers subagent with pid Pid under subtree Oid .
%%----------------------------------------------------------------------
register_subagent(MibServer, Oid, Pid) ->
call(MibServer, {register_subagent, Oid, Pid}).
unregister_subagent(MibServer, OidOrPid) ->
call(MibServer, {unregister_subagent, OidOrPid}).
info(MibServer) ->
call(MibServer, info).
info(MibServer, Type) ->
call(MibServer, {info, Type}).
dump(MibServer) ->
call(MibServer, dump).
dump(MibServer, File) when is_list(File) ->
call(MibServer, {dump, File}).
backup(MibServer, BackupDir) when is_list(BackupDir) ->
call(MibServer, {backup, BackupDir}).
%%--------------------------------------------------
The standard MIB ' stdmib ' must be present in the
%% current directory.
%%--------------------------------------------------
init([Prio, Mibs, Opts]) ->
?d("init -> entry with"
"~n Prio: ~p"
"~n Mibs: ~p"
"~n Opts: ~p", [Prio, Mibs, Opts]),
case (catch do_init(Prio, Mibs, Opts)) of
{ok, State} ->
{ok, State};
{error, Reason} ->
config_err("failed starting mib-server: ~n~p", [Reason]),
{stop, {error, Reason}};
Error ->
config_err("failed starting mib-server: ~n~p", [Error]),
{stop, {error, Error}}
end.
do_init(Prio, Mibs, Opts) ->
process_flag(priority, Prio),
process_flag(trap_exit, true),
put(sname,ms),
put(verbosity, ?vvalidate(get_verbosity(Opts))),
?vlog("starting",[]),
%% Extract the cache options
{Cache, CacheOptions} =
case get_opt(cache, Opts, ?DEFAULT_CACHE_USAGE) of
true ->
{new_cache(), []};
false ->
{?NO_CACHE, []};
CacheOpts when is_list(CacheOpts) ->
{new_cache(), CacheOpts};
Bad ->
throw({error, {bad_option, {cache, Bad}}})
end,
CacheAutoGC = get_cacheopt_autogc(Cache, CacheOptions),
CacheGcLimit = get_cacheopt_gclimit(Cache, CacheOptions),
CacheAge = get_cacheopt_age(Cache, CacheOptions),
%% Maybe start the cache gc timer
CacheGcTimer =
if
((Cache =/= ?NO_CACHE) andalso
(CacheAutoGC =:= true)) ->
start_cache_gc_timer();
true ->
undefined
end,
MeOverride = get_me_override(Opts),
TeOverride = get_te_override(Opts),
MibStorage = get_mib_storage(Opts),
Data = snmpa_mib_data:new(MibStorage),
?vtrace("init -> mib data created",[]),
case (catch mib_operations(load_mib, Mibs, Data,
MeOverride, TeOverride, true)) of
{ok, Data2} ->
?vdebug("started",[]),
snmpa_mib_data:sync(Data2),
?vdebug("mib data synced",[]),
{ok, #state{data = Data2,
teo = TeOverride,
meo = MeOverride,
cache = Cache,
cache_tmr = CacheGcTimer,
cache_autogc = CacheAutoGC,
cache_gclimit = CacheGcLimit,
cache_age = CacheAge}};
{'aborted at', Mib, _NewData, Reason} ->
?vinfo("failed loading mib ~p: ~p",[Mib,Reason]),
{error, {Mib, Reason}}
end.
%%----------------------------------------------------------------------
Returns : { ok , NewMibData } | { ' aborted at ' , Mib , NewData , Reason }
Args : Operation is load_mib | unload_mib .
%%----------------------------------------------------------------------
mib_operations(Operation, Mibs, Data, MeOverride, TeOverride) ->
mib_operations(Operation, Mibs, Data, MeOverride, TeOverride, false).
mib_operations(_Operation, [], Data, _MeOverride, _TeOverride, _Force) ->
{ok, Data};
mib_operations(Operation, [Mib|Mibs], Data0, MeOverride, TeOverride, Force) ->
?vtrace("mib operations ~p on"
"~n Mibs: ~p"
"~n with "
"~n MeOverride: ~p"
"~n TeOverride: ~p"
"~n Force: ~p", [Operation,Mibs,MeOverride,TeOverride,Force]),
Data = mib_operation(Operation, Mib, Data0, MeOverride, TeOverride, Force),
mib_operations(Operation, Mibs, Data, MeOverride, TeOverride, Force).
mib_operation(Operation, Mib, Data0, MeOverride, TeOverride, Force)
when is_list(Mib) ->
?vtrace("mib operation on mib ~p", [Mib]),
case apply(snmpa_mib_data, Operation, [Data0,Mib,MeOverride,TeOverride]) of
{error, 'already loaded'} when (Operation =:= load_mib) andalso
(Force =:= true) ->
?vlog("ignore mib ~p -> already loaded", [Mib]),
Data0;
{error, 'not loaded'} when (Operation =:= unload_mib) andalso
(Force =:= true) ->
?vlog("ignore mib ~p -> not loaded", [Mib]),
Data0;
{error, Reason} ->
?vlog("mib_operation -> failed ~p of mib ~p for ~p",
[Operation, Mib, Reason]),
throw({'aborted at', Mib, Data0, Reason});
{ok, Data} ->
Data
end;
mib_operation(_Op, Mib, Data, _MeOverride, _TeOverride, _Force) ->
throw({'aborted at', Mib, Data, bad_mibname}).
%%-----------------------------------------------------------------
%% Handle messages
%%-----------------------------------------------------------------
handle_call(invalidate_cache, _From, #state{cache = Cache} = State) ->
?vlog("invalidate_cache", []),
NewCache = maybe_invalidate_cache(Cache),
{reply, ignore, State#state{cache = NewCache}};
handle_call(cache_size, _From, #state{cache = Cache} = State) ->
?vlog("cache_size", []),
Reply = maybe_cache_size(Cache),
{reply, Reply, State};
handle_call(gc_cache, _From,
#state{cache = Cache,
cache_age = Age,
cache_gclimit = GcLimit} = State) ->
?vlog("gc_cache", []),
Result = maybe_gc_cache(Cache, Age, GcLimit),
{reply, Result, State};
handle_call({gc_cache, Age}, _From,
#state{cache = Cache,
cache_gclimit = GcLimit} = State) ->
?vlog("gc_cache with Age = ~p", [Age]),
Result = maybe_gc_cache(Cache, Age, GcLimit),
{reply, Result, State};
handle_call({gc_cache, Age, GcLimit}, _From,
#state{cache = Cache} = State) ->
?vlog("gc_cache with Age = ~p and GcLimut = ~p", [Age, GcLimit]),
Result = maybe_gc_cache(Cache, Age, GcLimit),
{reply, Result, State};
handle_call({update_cache_opts, Key, Value}, _From, State) ->
?vlog("update_cache_opts: ~p -> ~p", [Key, Value]),
{Result, NewState} = handle_update_cache_opts(Key, Value, State),
{reply, Result, NewState};
handle_call({lookup, Oid}, _From,
#state{data = Data, cache = Cache} = State) ->
?vlog("lookup ~p", [Oid]),
Key = {lookup, Oid},
{Reply, NewState} =
case maybe_cache_lookup(Cache, Key) of
?NO_CACHE ->
{snmpa_mib_data:lookup(Data, Oid), State};
[] ->
Rep = snmpa_mib_data:lookup(Data, Oid),
ets:insert(Cache, {Key, Rep, timestamp()}),
{Rep, maybe_start_cache_gc_timer(State)};
[{Key, Rep, _}] ->
?vdebug("lookup -> found in cache", []),
ets:update_element(Cache, Key, {3, timestamp()}),
{Rep, State}
end,
?vdebug("lookup -> Reply: ~p", [Reply]),
{reply, Reply, NewState};
handle_call({which_mib, Oid}, _From, #state{data = Data} = State) ->
?vlog("which_mib ~p",[Oid]),
Reply = snmpa_mib_data:which_mib(Data, Oid),
?vdebug("which_mib: ~p",[Reply]),
{reply, Reply, State};
handle_call({next, Oid, MibView}, _From,
#state{data = Data, cache = Cache} = State) ->
?vlog("next ~p [~p]", [Oid, MibView]),
Key = {next, Oid, MibView},
{Reply, NewState} =
case maybe_cache_lookup(Cache, Key) of
?NO_CACHE ->
{snmpa_mib_data:next(Data, Oid, MibView), State};
[] ->
Rep = snmpa_mib_data:next(Data, Oid, MibView),
ets:insert(Cache, {Key, Rep, timestamp()}),
{Rep, maybe_start_cache_gc_timer(State)};
[{Key, Rep, _}] ->
?vdebug("lookup -> found in cache", []),
ets:update_element(Cache, Key, {3, timestamp()}),
{Rep, State}
end,
?vdebug("next -> Reply: ~p", [Reply]),
{reply, Reply, NewState};
handle_call({load_mibs, Mibs}, _From,
#state{data = Data,
teo = TeOverride,
meo = MeOverride,
cache = Cache} = State) ->
?vlog("load mibs ~p",[Mibs]),
Invalidate cache
NewCache = maybe_invalidate_cache(Cache),
{NData,Reply} =
case (catch mib_operations(load_mib, Mibs, Data,
MeOverride, TeOverride)) of
{'aborted at', Mib, NewData, Reason} ->
?vlog("aborted at ~p for reason ~p",[Mib,Reason]),
{NewData,{error, {'load aborted at', Mib, Reason}}};
{ok, NewData} ->
{NewData,ok}
end,
snmpa_mib_data:sync(NData),
{reply, Reply, State#state{data = NData, cache = NewCache}};
handle_call({unload_mibs, Mibs}, _From,
#state{data = Data,
teo = TeOverride,
meo = MeOverride,
cache = Cache} = State) ->
?vlog("unload mibs ~p",[Mibs]),
Invalidate cache
NewCache = maybe_invalidate_cache(Cache),
%% Unload mib(s)
{NData,Reply} =
case (catch mib_operations(unload_mib, Mibs, Data,
MeOverride, TeOverride)) of
{'aborted at', Mib, NewData, Reason} ->
?vlog("aborted at ~p for reason ~p",[Mib,Reason]),
{NewData, {error, {'unload aborted at', Mib, Reason}}};
{ok, NewData} ->
{NewData,ok}
end,
snmpa_mib_data:sync(NData),
{reply, Reply, State#state{data = NData, cache = NewCache}};
handle_call(which_mibs, _From, #state{data = Data} = State) ->
?vlog("which mibs",[]),
Reply = snmpa_mib_data:which_mibs(Data),
{reply, Reply, State};
handle_call({whereis_mib, Mib}, _From, #state{data = Data} = State) ->
?vlog("whereis mib: ~p",[Mib]),
Reply = snmpa_mib_data:whereis_mib(Data, Mib),
{reply, Reply, State};
handle_call({register_subagent, Oid, Pid}, _From,
#state{data = Data, cache = Cache} = State) ->
?vlog("register subagent ~p, ~p",[Oid,Pid]),
Invalidate cache
NewCache = maybe_invalidate_cache(Cache),
case snmpa_mib_data:register_subagent(Data, Oid, Pid) of
{error, Reason} ->
?vlog("registration failed: ~p",[Reason]),
{reply, {error, Reason}, State#state{cache = NewCache}};
NewData ->
{reply, ok, State#state{data = NewData, cache = NewCache}}
end;
handle_call({unregister_subagent, OidOrPid}, _From,
#state{data = Data, cache = Cache} = State) ->
?vlog("unregister subagent ~p",[OidOrPid]),
Invalidate cache
NewCache = maybe_invalidate_cache(Cache),
case snmpa_mib_data:unregister_subagent(Data, OidOrPid) of
{ok, NewData, DeletedSubagentPid} ->
{reply, {ok, DeletedSubagentPid}, State#state{data = NewData,
cache = NewCache}};
{error, Reason} ->
?vlog("unregistration failed: ~p",[Reason]),
{reply, {error, Reason}, State#state{cache = NewCache}};
NewData ->
{reply, ok, State#state{data = NewData, cache = NewCache}}
end;
handle_call(info, _From, #state{data = Data, cache = Cache} = State) ->
?vlog("info",[]),
Reply =
case (catch snmpa_mib_data:info(Data)) of
Info when is_list(Info) ->
[{cache, size_cache(Cache)} | Info];
E ->
[{error, E}]
end,
{reply, Reply, State};
handle_call({info, Type}, _From, #state{data = Data} = State) ->
?vlog("info ~p",[Type]),
Reply =
case (catch snmpa_mib_data:info(Data, Type)) of
Info when is_list(Info) ->
Info;
E ->
[{error, E}]
end,
{reply, Reply, State};
handle_call(dump, _From, State) ->
?vlog("dump",[]),
Reply = snmpa_mib_data:dump(State#state.data),
{reply, Reply, State};
handle_call({dump, File}, _From, #state{data = Data} = State) ->
?vlog("dump on ~s",[File]),
Reply = snmpa_mib_data:dump(Data, File),
{reply, Reply, State};
handle_call({backup, BackupDir}, From, #state{data = Data} = State) ->
?vlog("backup to ~s",[BackupDir]),
Pid = self(),
V = get(verbosity),
case file:read_file_info(BackupDir) of
{ok, #file_info{type = directory}} ->
BackupServer =
erlang:spawn_link(
fun() ->
put(sname, ambs),
put(verbosity, V),
Dir = filename:join([BackupDir]),
Reply = snmpa_mib_data:backup(Data, Dir),
Pid ! {backup_done, Reply},
unlink(Pid)
end),
?vtrace("backup server: ~p", [BackupServer]),
{noreply, State#state{backup = {BackupServer, From}}};
{ok, _} ->
{reply, {error, not_a_directory}, State};
Error ->
{reply, Error, State}
end;
handle_call(stop, _From, State) ->
?vlog("stop",[]),
{stop, normal, ok, State};
handle_call(Req, _From, State) ->
warning_msg("received unknown request: ~n~p", [Req]),
Reply = {error, {unknown, Req}},
{reply, Reply, State}.
handle_cast({verbosity, Verbosity}, State) ->
?vlog("verbosity: ~p -> ~p",[get(verbosity),Verbosity]),
put(verbosity,snmp_verbosity:validate(Verbosity)),
{noreply, State};
handle_cast(Msg, State) ->
warning_msg("received unknown message: ~n~p", [Msg]),
{noreply, State}.
handle_info({'EXIT', Pid, Reason}, #state{backup = {Pid, From}} = S) ->
?vlog("backup server (~p) exited for reason ~n~p", [Pid, Reason]),
gen_server:reply(From, {error, Reason}),
{noreply, S#state{backup = undefined}};
handle_info({'EXIT', Pid, Reason}, S) ->
%% The only other processes we should be linked to are
%% either the master agent or our supervisor, so die...
{stop, {received_exit, Pid, Reason}, S};
handle_info({backup_done, Reply}, #state{backup = {_, From}} = S) ->
?vlog("backup done:"
"~n Reply: ~p", [Reply]),
gen_server:reply(From, Reply),
{noreply, S#state{backup = undefined}};
handle_info(?CACHE_GC_TRIGGER, #state{cache = Cache,
cache_age = Age,
cache_gclimit = GcLimit,
cache_autogc = true} = S)
when (Cache =/= ?NO_CACHE) ->
?vlog("cache gc trigger event", []),
maybe_gc_cache(Cache, Age, GcLimit),
Tmr = start_cache_gc_timer(),
{noreply, S#state{cache_tmr = Tmr}};
handle_info(?CACHE_GC_TRIGGER, S) ->
?vlog("out-of-date cache gc trigger event - ignore", []),
{noreply, S#state{cache_tmr = undefined}};
handle_info(Info, State) ->
warning_msg("received unknown info: ~n~p", [Info]),
{noreply, State}.
terminate(_Reason, #state{data = Data}) ->
catch snmpa_mib_data:close(Data),
ok.
%%----------------------------------------------------------
%% Code change
%%----------------------------------------------------------
%% downgrade
%%
code_change({down , _ Vsn } , S1 , ) - >
# state{data = Data , meo = MEO , , backup = B , cache = Cache } = S1 ,
del_cache(Cache ) ,
S2 = { state , Data , MEO , TEO , B } ,
%% {ok, S2};
%% %% upgrade
%% %%
%% code_change(_Vsn, S1, upgrade_from_pre_4_12) ->
{ state , Data , MEO , TEO , B } = S1 ,
%% Cache = new_cache(),
S2 = # state{data = Data , meo = MEO , , backup = B , cache = Cache } ,
%% {ok, S2};
code_change(_Vsn, State, _Extra) ->
{ok, State}.
%%-----------------------------------------------------------------
%% Option access functions
%%-----------------------------------------------------------------
get_verbosity(Options) ->
get_opt(verbosity, Options, ?default_verbosity).
get_me_override(Options) ->
get_opt(mibentry_override, Options, false).
get_te_override(Options) ->
get_opt(trapentry_override, Options, false).
get_mib_storage(Options) ->
get_opt(mib_storage, Options, ets).
get_cacheopt_autogc(Cache, CacheOpts) ->
IsValid = fun(AutoGC) when ((AutoGC =:= true) orelse
(AutoGC =:= false)) ->
true;
(_) ->
false
end,
get_cacheopt(Cache, autogc, CacheOpts,
false, ?DEFAULT_CACHE_AUTOGC,
IsValid).
get_cacheopt_gclimit(Cache, CacheOpts) ->
IsValid = fun(Limit) when ((is_integer(Limit) andalso (Limit > 0)) orelse
(Limit =:= infinity)) ->
true;
(_) ->
false
end,
get_cacheopt(Cache, gclimit, CacheOpts,
infinity, ?DEFAULT_CACHE_GCLIMIT,
IsValid).
get_cacheopt_age(Cache, CacheOpts) ->
IsValid = fun(Age) when is_integer(Age) andalso (Age > 0) ->
true;
(_) ->
false
end,
get_cacheopt(Cache, age, CacheOpts,
?DEFAULT_CACHE_AGE, ?DEFAULT_CACHE_AGE,
IsValid).
get_cacheopt(?NO_CACHE, _, _, NoCacheVal, _, _) ->
NoCacheVal;
get_cacheopt(_, Key, Opts, _, Default, IsValid) ->
Val = get_opt(Key, Opts, Default),
case IsValid(Val) of
true ->
Val;
false ->
throw({error, {bad_option, {Key, Val}}})
end.
%% ----------------------------------------------------------------
handle_update_cache_opts(cache, true = _Value,
#state{cache = ?NO_CACHE} = State) ->
{ok, State#state{cache = new_cache()}};
handle_update_cache_opts(cache, true = _Value, State) ->
{ok, State};
handle_update_cache_opts(cache, false = _Value,
#state{cache = ?NO_CACHE} = State) ->
{ok, State};
handle_update_cache_opts(cache, false = _Value,
#state{cache = Cache,
cache_tmr = Tmr} = State) ->
maybe_stop_cache_gc_timer(Tmr),
del_cache(Cache),
{ok, State#state{cache = ?NO_CACHE, cache_tmr = undefined}};
handle_update_cache_opts(autogc, true = _Value,
#state{cache_autogc = true} = State) ->
{ok, State};
handle_update_cache_opts(autogc, true = Value, State) ->
{ok, maybe_start_cache_gc_timer(State#state{cache_autogc = Value})};
handle_update_cache_opts(autogc, false = _Value,
#state{cache_autogc = false} = State) ->
{ok, State};
handle_update_cache_opts(autogc, false = Value,
#state{cache_tmr = Tmr} = State) ->
maybe_stop_cache_gc_timer(Tmr),
{ok, State#state{cache_autogc = Value, cache_tmr = undefined}};
handle_update_cache_opts(age, Age, State) ->
{ok, State#state{cache_age = Age}};
handle_update_cache_opts(gclimit, GcLimit, State) ->
{ok, State#state{cache_gclimit = GcLimit}};
handle_update_cache_opts(BadKey, Value, State) ->
{{error, {bad_cache_opt, BadKey, Value}}, State}.
maybe_stop_cache_gc_timer(undefined) ->
ok;
maybe_stop_cache_gc_timer(Tmr) ->
erlang:cancel_timer(Tmr).
maybe_start_cache_gc_timer(#state{cache = Cache,
cache_autogc = true,
cache_tmr = undefined} = State)
when (Cache =/= ?NO_CACHE) ->
Tmr = start_cache_gc_timer(),
State#state{cache_tmr = Tmr};
maybe_start_cache_gc_timer(State) ->
State.
start_cache_gc_timer() ->
erlang:send_after(?CACHE_GC_TICKTIME, self(), ?CACHE_GC_TRIGGER).
%% ----------------------------------------------------------------
maybe_gc_cache(?NO_CACHE, _Age) ->
?vtrace("cache not enabled", []),
ok;
maybe_gc_cache(Cache, Age) ->
MatchSpec = gc_cache_matchspec(Age),
Keys = ets:select(Cache, MatchSpec),
do_gc_cache(Cache, Keys),
{ok, length(Keys)}.
maybe_gc_cache(?NO_CACHE, _Age, _GcLimit) ->
ok;
maybe_gc_cache(Cache, Age, infinity = _GcLimit) ->
maybe_gc_cache(Cache, Age);
maybe_gc_cache(Cache, Age, GcLimit) ->
MatchSpec = gc_cache_matchspec(Age),
Keys =
case ets:select(Cache, MatchSpec, GcLimit) of
{Match, _Cont} ->
Match;
'$end_of_table' ->
[]
end,
do_gc_cache(Cache, Keys),
{ok, length(Keys)}.
gc_cache_matchspec(Age) ->
Oldest = timestamp() - Age,
MatchHead = {'$1', '_', '$2'},
Guard = [{'<', '$2', Oldest}],
MatchFunc = {MatchHead, Guard, ['$1']},
MatchSpec = [MatchFunc],
MatchSpec.
do_gc_cache(_, []) ->
ok;
do_gc_cache(Cache, [Key|Keys]) ->
ets:delete(Cache, Key),
do_gc_cache(Cache, Keys).
maybe_invalidate_cache(?NO_CACHE) ->
?NO_CACHE;
maybe_invalidate_cache(Cache) ->
del_cache(Cache),
new_cache().
maybe_cache_size(?NO_CACHE) ->
{error, not_enabled};
maybe_cache_size(Cache) ->
{ok, ets:info(Cache, size)}.
new_cache() ->
ets:new(snmpa_mib_cache, [set, protected, {keypos, 1}]).
del_cache(?NO_CACHE) ->
ok;
del_cache(Cache) ->
ets:delete(Cache).
maybe_cache_lookup(?NO_CACHE, _) ->
?NO_CACHE;
maybe_cache_lookup(Cache, Key) ->
ets:lookup(Cache, Key).
size_cache(?NO_CACHE) ->
undefined;
size_cache(Cache) ->
case (catch ets:info(Cache, memory)) of
Sz when is_integer(Sz) ->
Sz;
_ ->
undefined
end.
timestamp() ->
snmp_misc:now(ms).
%% ----------------------------------------------------------------
get_opt(Key, Options, Default) ->
snmp_misc:get_option(Key, Options, Default).
%% ----------------------------------------------------------------
cast(MibServer, Msg) ->
gen_server:cast(MibServer, Msg).
call(MibServer, Req) ->
call(MibServer, Req, infinity).
call(MibServer, Req, To) ->
gen_server:call(MibServer, Req, To).
%% ----------------------------------------------------------------
%% info_msg(F, A) ->
%% ?snmpa_info("Mib server: " ++ F, A).
warning_msg(F, A) ->
?snmpa_warning("Mib server: " ++ F, A).
%% error_msg(F, A) ->
%% ?snmpa_error("Mib server: " ++ F, A).
config_err(F, A) ->
snmpa_error:config_err(F, A).
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/snmp/src/agent/snmpa_mib.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
c(snmpa_mib).
-----------------------------------------------------------------
-----------------------------------------------------------------
External exports
Internal exports
-----------------------------------------------------------------
meo - mib entry override
teo - trap (notification) entry override
-----------------------------------------------------------------
-----------------------------------------------------------------
Func: start_link/1
-----------------------------------------------------------------
-----------------------------------------------------------------
Func: lookup/2
Returns: {variable, MibEntry} |
{subagent, SubAgentPid} |
false
-----------------------------------------------------------------
-----------------------------------------------------------------
endOfMibView |
genErr |
-----------------------------------------------------------------
----------------------------------------------------------------------
Returns: ok | {error, Reason}
----------------------------------------------------------------------
----------------------------------------------------------------------
Returns: ok | {error, Reason}
----------------------------------------------------------------------
----------------------------------------------------------------------
Purpose: Simple management functions
Returns: ok | {error, Reason}
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
--------------------------------------------------
current directory.
--------------------------------------------------
Extract the cache options
Maybe start the cache gc timer
----------------------------------------------------------------------
----------------------------------------------------------------------
-----------------------------------------------------------------
Handle messages
-----------------------------------------------------------------
Unload mib(s)
The only other processes we should be linked to are
either the master agent or our supervisor, so die...
----------------------------------------------------------
Code change
----------------------------------------------------------
downgrade
{ok, S2};
%% upgrade
%%
code_change(_Vsn, S1, upgrade_from_pre_4_12) ->
Cache = new_cache(),
{ok, S2};
-----------------------------------------------------------------
Option access functions
-----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
info_msg(F, A) ->
?snmpa_info("Mib server: " ++ F, A).
error_msg(F, A) ->
?snmpa_error("Mib server: " ++ F, A). | Copyright Ericsson AB 1996 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(snmpa_mib).
This module implements a MIB server .
-export([start_link/3, stop/1,
lookup/2, next/3, which_mib/2, which_mibs/1, whereis_mib/2,
load_mibs/2, unload_mibs/2,
register_subagent/3, unregister_subagent/2, info/1, info/2,
verbosity/2, dump/1, dump/2,
backup/2,
invalidate_cache/1,
gc_cache/1, gc_cache/2, gc_cache/3,
enable_cache/1, disable_cache/1,
enable_cache_autogc/1, disable_cache_autogc/1,
update_cache_gclimit/2,
update_cache_age/2,
which_cache_size/1
]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3]).
-include_lib("kernel/include/file.hrl").
-include("snmpa_internal.hrl").
-include("snmp_types.hrl").
-include("snmp_verbosity.hrl").
-include("snmp_debug.hrl").
-define(SERVER, ?MODULE).
-define(NO_CACHE, no_mibs_cache).
-define(DEFAULT_CACHE_USAGE, true).
-define(CACHE_GC_TICKTIME, timer:minutes(1)).
-define(DEFAULT_CACHE_AUTOGC, false).
-define(DEFAULT_CACHE_GCLIMIT, 100).
-define(DEFAULT_CACHE_AGE, timer:minutes(10)).
-define(CACHE_GC_TRIGGER, cache_gc_trigger).
-ifdef(snmp_debug).
-define(GS_START_LINK(Prio, Mibs, Opts),
gen_server:start_link(?MODULE, [Prio, Mibs, Opts], [{debug,[trace]}])).
-else.
-define(GS_START_LINK(Prio, Mibs, Opts),
gen_server:start_link(?MODULE, [Prio, Mibs, Opts], [])).
-endif.
Internal Data structures
State
data - is the MIB data ( defined in snmpa_mib_data )
-record(state, {data, meo, teo, backup,
cache, cache_tmr, cache_autogc, cache_gclimit, cache_age}).
: is a list of mibnames .
Prio is priority of mib - server
Opts is a list of options
Purpose : starts the mib server synchronized
Returns : { ok , Pid } | { error , Reason }
start_link(Prio, Mibs, Opts) ->
?d("start_link -> entry with"
"~n Prio: ~p"
"~n Mibs: ~p"
"~n Opts: ~p", [Prio, Mibs, Opts]),
?GS_START_LINK(Prio, Mibs, Opts).
verbosity(MibServer, Verbosity) ->
cast(MibServer, {verbosity,Verbosity}).
stop(MibServer) ->
call(MibServer, stop).
invalidate_cache(MibServer) ->
call(MibServer, invalidate_cache).
gc_cache(MibServer) ->
call(MibServer, gc_cache).
gc_cache(MibServer, Age) ->
call(MibServer, {gc_cache, Age}).
gc_cache(MibServer, Age, GcLimit) ->
call(MibServer, {gc_cache, Age, GcLimit}).
which_cache_size(MibServer) ->
call(MibServer, cache_size).
enable_cache(MibServer) ->
update_cache_opts(MibServer, cache, true).
disable_cache(MibServer) ->
update_cache_opts(MibServer, cache, false).
enable_cache_autogc(MibServer) ->
update_cache_opts(MibServer, autogc, true).
disable_cache_autogc(MibServer) ->
update_cache_opts(MibServer, autogc, false).
update_cache_gclimit(MibServer, GcLimit)
when ((is_integer(GcLimit) andalso (GcLimit > 0)) orelse
(GcLimit =:= infinity)) ->
update_cache_opts(MibServer, gclimit, GcLimit);
update_cache_gclimit(_, BadLimit) ->
{error, {bad_gclimit, BadLimit}}.
update_cache_age(MibServer, Age)
when is_integer(Age) andalso (Age > 0) ->
update_cache_opts(MibServer, age, Age);
update_cache_age(_, BadAge) ->
{error, {bad_age, BadAge}}.
update_cache_opts(MibServer, Key, Value) ->
call(MibServer, {update_cache_opts, Key, Value}).
Purpose : Finds the mib entry corresponding to the Oid . If it is a
variable , the Oid must be < Oid for var>.0 and if it is
a table , Oid must be < table>.<entry>.<col>.<any >
{ table_column , MibEntry , TableEntryOid } |
lookup(MibServer, Oid) ->
call(MibServer, {lookup, Oid}).
which_mib(MibServer, Oid) ->
call(MibServer, {which_mib, Oid}).
Func : next/3
Purpose : Finds the lexicographically next oid .
Returns : { subagent , SubAgentPid , SANextOid } |
NextOid
The SANextOid is used by the agent if the SubAgent returns
endOfMib , in a new call to next/2 .
next(MibServer, Oid, MibView) ->
call(MibServer, {next, Oid, MibView}).
Purpose : Loads mibs into the mib process .
: is a list of Filenames ( compiled ) .
load_mibs(MibServer, Mibs) ->
call(MibServer, {load_mibs, Mibs}).
Purpose : Loads mibs into the mib process .
: is a list of Filenames ( compiled ) .
unload_mibs(MibServer, Mibs) ->
call(MibServer, {unload_mibs, Mibs}).
: Mib is the name of the mib ( atom )
which_mibs(MibServer) ->
call(MibServer, which_mibs).
whereis_mib(MibServer, Mib) ->
call(MibServer, {whereis_mib, Mib}).
Registers subagent with pid Pid under subtree Oid .
register_subagent(MibServer, Oid, Pid) ->
call(MibServer, {register_subagent, Oid, Pid}).
unregister_subagent(MibServer, OidOrPid) ->
call(MibServer, {unregister_subagent, OidOrPid}).
info(MibServer) ->
call(MibServer, info).
info(MibServer, Type) ->
call(MibServer, {info, Type}).
dump(MibServer) ->
call(MibServer, dump).
dump(MibServer, File) when is_list(File) ->
call(MibServer, {dump, File}).
backup(MibServer, BackupDir) when is_list(BackupDir) ->
call(MibServer, {backup, BackupDir}).
The standard MIB ' stdmib ' must be present in the
init([Prio, Mibs, Opts]) ->
?d("init -> entry with"
"~n Prio: ~p"
"~n Mibs: ~p"
"~n Opts: ~p", [Prio, Mibs, Opts]),
case (catch do_init(Prio, Mibs, Opts)) of
{ok, State} ->
{ok, State};
{error, Reason} ->
config_err("failed starting mib-server: ~n~p", [Reason]),
{stop, {error, Reason}};
Error ->
config_err("failed starting mib-server: ~n~p", [Error]),
{stop, {error, Error}}
end.
do_init(Prio, Mibs, Opts) ->
process_flag(priority, Prio),
process_flag(trap_exit, true),
put(sname,ms),
put(verbosity, ?vvalidate(get_verbosity(Opts))),
?vlog("starting",[]),
{Cache, CacheOptions} =
case get_opt(cache, Opts, ?DEFAULT_CACHE_USAGE) of
true ->
{new_cache(), []};
false ->
{?NO_CACHE, []};
CacheOpts when is_list(CacheOpts) ->
{new_cache(), CacheOpts};
Bad ->
throw({error, {bad_option, {cache, Bad}}})
end,
CacheAutoGC = get_cacheopt_autogc(Cache, CacheOptions),
CacheGcLimit = get_cacheopt_gclimit(Cache, CacheOptions),
CacheAge = get_cacheopt_age(Cache, CacheOptions),
CacheGcTimer =
if
((Cache =/= ?NO_CACHE) andalso
(CacheAutoGC =:= true)) ->
start_cache_gc_timer();
true ->
undefined
end,
MeOverride = get_me_override(Opts),
TeOverride = get_te_override(Opts),
MibStorage = get_mib_storage(Opts),
Data = snmpa_mib_data:new(MibStorage),
?vtrace("init -> mib data created",[]),
case (catch mib_operations(load_mib, Mibs, Data,
MeOverride, TeOverride, true)) of
{ok, Data2} ->
?vdebug("started",[]),
snmpa_mib_data:sync(Data2),
?vdebug("mib data synced",[]),
{ok, #state{data = Data2,
teo = TeOverride,
meo = MeOverride,
cache = Cache,
cache_tmr = CacheGcTimer,
cache_autogc = CacheAutoGC,
cache_gclimit = CacheGcLimit,
cache_age = CacheAge}};
{'aborted at', Mib, _NewData, Reason} ->
?vinfo("failed loading mib ~p: ~p",[Mib,Reason]),
{error, {Mib, Reason}}
end.
Returns : { ok , NewMibData } | { ' aborted at ' , Mib , NewData , Reason }
Args : Operation is load_mib | unload_mib .
mib_operations(Operation, Mibs, Data, MeOverride, TeOverride) ->
mib_operations(Operation, Mibs, Data, MeOverride, TeOverride, false).
mib_operations(_Operation, [], Data, _MeOverride, _TeOverride, _Force) ->
{ok, Data};
mib_operations(Operation, [Mib|Mibs], Data0, MeOverride, TeOverride, Force) ->
?vtrace("mib operations ~p on"
"~n Mibs: ~p"
"~n with "
"~n MeOverride: ~p"
"~n TeOverride: ~p"
"~n Force: ~p", [Operation,Mibs,MeOverride,TeOverride,Force]),
Data = mib_operation(Operation, Mib, Data0, MeOverride, TeOverride, Force),
mib_operations(Operation, Mibs, Data, MeOverride, TeOverride, Force).
mib_operation(Operation, Mib, Data0, MeOverride, TeOverride, Force)
when is_list(Mib) ->
?vtrace("mib operation on mib ~p", [Mib]),
case apply(snmpa_mib_data, Operation, [Data0,Mib,MeOverride,TeOverride]) of
{error, 'already loaded'} when (Operation =:= load_mib) andalso
(Force =:= true) ->
?vlog("ignore mib ~p -> already loaded", [Mib]),
Data0;
{error, 'not loaded'} when (Operation =:= unload_mib) andalso
(Force =:= true) ->
?vlog("ignore mib ~p -> not loaded", [Mib]),
Data0;
{error, Reason} ->
?vlog("mib_operation -> failed ~p of mib ~p for ~p",
[Operation, Mib, Reason]),
throw({'aborted at', Mib, Data0, Reason});
{ok, Data} ->
Data
end;
mib_operation(_Op, Mib, Data, _MeOverride, _TeOverride, _Force) ->
throw({'aborted at', Mib, Data, bad_mibname}).
handle_call(invalidate_cache, _From, #state{cache = Cache} = State) ->
?vlog("invalidate_cache", []),
NewCache = maybe_invalidate_cache(Cache),
{reply, ignore, State#state{cache = NewCache}};
handle_call(cache_size, _From, #state{cache = Cache} = State) ->
?vlog("cache_size", []),
Reply = maybe_cache_size(Cache),
{reply, Reply, State};
handle_call(gc_cache, _From,
#state{cache = Cache,
cache_age = Age,
cache_gclimit = GcLimit} = State) ->
?vlog("gc_cache", []),
Result = maybe_gc_cache(Cache, Age, GcLimit),
{reply, Result, State};
handle_call({gc_cache, Age}, _From,
#state{cache = Cache,
cache_gclimit = GcLimit} = State) ->
?vlog("gc_cache with Age = ~p", [Age]),
Result = maybe_gc_cache(Cache, Age, GcLimit),
{reply, Result, State};
handle_call({gc_cache, Age, GcLimit}, _From,
#state{cache = Cache} = State) ->
?vlog("gc_cache with Age = ~p and GcLimut = ~p", [Age, GcLimit]),
Result = maybe_gc_cache(Cache, Age, GcLimit),
{reply, Result, State};
handle_call({update_cache_opts, Key, Value}, _From, State) ->
?vlog("update_cache_opts: ~p -> ~p", [Key, Value]),
{Result, NewState} = handle_update_cache_opts(Key, Value, State),
{reply, Result, NewState};
handle_call({lookup, Oid}, _From,
#state{data = Data, cache = Cache} = State) ->
?vlog("lookup ~p", [Oid]),
Key = {lookup, Oid},
{Reply, NewState} =
case maybe_cache_lookup(Cache, Key) of
?NO_CACHE ->
{snmpa_mib_data:lookup(Data, Oid), State};
[] ->
Rep = snmpa_mib_data:lookup(Data, Oid),
ets:insert(Cache, {Key, Rep, timestamp()}),
{Rep, maybe_start_cache_gc_timer(State)};
[{Key, Rep, _}] ->
?vdebug("lookup -> found in cache", []),
ets:update_element(Cache, Key, {3, timestamp()}),
{Rep, State}
end,
?vdebug("lookup -> Reply: ~p", [Reply]),
{reply, Reply, NewState};
handle_call({which_mib, Oid}, _From, #state{data = Data} = State) ->
?vlog("which_mib ~p",[Oid]),
Reply = snmpa_mib_data:which_mib(Data, Oid),
?vdebug("which_mib: ~p",[Reply]),
{reply, Reply, State};
handle_call({next, Oid, MibView}, _From,
#state{data = Data, cache = Cache} = State) ->
?vlog("next ~p [~p]", [Oid, MibView]),
Key = {next, Oid, MibView},
{Reply, NewState} =
case maybe_cache_lookup(Cache, Key) of
?NO_CACHE ->
{snmpa_mib_data:next(Data, Oid, MibView), State};
[] ->
Rep = snmpa_mib_data:next(Data, Oid, MibView),
ets:insert(Cache, {Key, Rep, timestamp()}),
{Rep, maybe_start_cache_gc_timer(State)};
[{Key, Rep, _}] ->
?vdebug("lookup -> found in cache", []),
ets:update_element(Cache, Key, {3, timestamp()}),
{Rep, State}
end,
?vdebug("next -> Reply: ~p", [Reply]),
{reply, Reply, NewState};
handle_call({load_mibs, Mibs}, _From,
#state{data = Data,
teo = TeOverride,
meo = MeOverride,
cache = Cache} = State) ->
?vlog("load mibs ~p",[Mibs]),
Invalidate cache
NewCache = maybe_invalidate_cache(Cache),
{NData,Reply} =
case (catch mib_operations(load_mib, Mibs, Data,
MeOverride, TeOverride)) of
{'aborted at', Mib, NewData, Reason} ->
?vlog("aborted at ~p for reason ~p",[Mib,Reason]),
{NewData,{error, {'load aborted at', Mib, Reason}}};
{ok, NewData} ->
{NewData,ok}
end,
snmpa_mib_data:sync(NData),
{reply, Reply, State#state{data = NData, cache = NewCache}};
handle_call({unload_mibs, Mibs}, _From,
#state{data = Data,
teo = TeOverride,
meo = MeOverride,
cache = Cache} = State) ->
?vlog("unload mibs ~p",[Mibs]),
Invalidate cache
NewCache = maybe_invalidate_cache(Cache),
{NData,Reply} =
case (catch mib_operations(unload_mib, Mibs, Data,
MeOverride, TeOverride)) of
{'aborted at', Mib, NewData, Reason} ->
?vlog("aborted at ~p for reason ~p",[Mib,Reason]),
{NewData, {error, {'unload aborted at', Mib, Reason}}};
{ok, NewData} ->
{NewData,ok}
end,
snmpa_mib_data:sync(NData),
{reply, Reply, State#state{data = NData, cache = NewCache}};
handle_call(which_mibs, _From, #state{data = Data} = State) ->
?vlog("which mibs",[]),
Reply = snmpa_mib_data:which_mibs(Data),
{reply, Reply, State};
handle_call({whereis_mib, Mib}, _From, #state{data = Data} = State) ->
?vlog("whereis mib: ~p",[Mib]),
Reply = snmpa_mib_data:whereis_mib(Data, Mib),
{reply, Reply, State};
handle_call({register_subagent, Oid, Pid}, _From,
#state{data = Data, cache = Cache} = State) ->
?vlog("register subagent ~p, ~p",[Oid,Pid]),
Invalidate cache
NewCache = maybe_invalidate_cache(Cache),
case snmpa_mib_data:register_subagent(Data, Oid, Pid) of
{error, Reason} ->
?vlog("registration failed: ~p",[Reason]),
{reply, {error, Reason}, State#state{cache = NewCache}};
NewData ->
{reply, ok, State#state{data = NewData, cache = NewCache}}
end;
handle_call({unregister_subagent, OidOrPid}, _From,
#state{data = Data, cache = Cache} = State) ->
?vlog("unregister subagent ~p",[OidOrPid]),
Invalidate cache
NewCache = maybe_invalidate_cache(Cache),
case snmpa_mib_data:unregister_subagent(Data, OidOrPid) of
{ok, NewData, DeletedSubagentPid} ->
{reply, {ok, DeletedSubagentPid}, State#state{data = NewData,
cache = NewCache}};
{error, Reason} ->
?vlog("unregistration failed: ~p",[Reason]),
{reply, {error, Reason}, State#state{cache = NewCache}};
NewData ->
{reply, ok, State#state{data = NewData, cache = NewCache}}
end;
handle_call(info, _From, #state{data = Data, cache = Cache} = State) ->
?vlog("info",[]),
Reply =
case (catch snmpa_mib_data:info(Data)) of
Info when is_list(Info) ->
[{cache, size_cache(Cache)} | Info];
E ->
[{error, E}]
end,
{reply, Reply, State};
handle_call({info, Type}, _From, #state{data = Data} = State) ->
?vlog("info ~p",[Type]),
Reply =
case (catch snmpa_mib_data:info(Data, Type)) of
Info when is_list(Info) ->
Info;
E ->
[{error, E}]
end,
{reply, Reply, State};
handle_call(dump, _From, State) ->
?vlog("dump",[]),
Reply = snmpa_mib_data:dump(State#state.data),
{reply, Reply, State};
handle_call({dump, File}, _From, #state{data = Data} = State) ->
?vlog("dump on ~s",[File]),
Reply = snmpa_mib_data:dump(Data, File),
{reply, Reply, State};
handle_call({backup, BackupDir}, From, #state{data = Data} = State) ->
?vlog("backup to ~s",[BackupDir]),
Pid = self(),
V = get(verbosity),
case file:read_file_info(BackupDir) of
{ok, #file_info{type = directory}} ->
BackupServer =
erlang:spawn_link(
fun() ->
put(sname, ambs),
put(verbosity, V),
Dir = filename:join([BackupDir]),
Reply = snmpa_mib_data:backup(Data, Dir),
Pid ! {backup_done, Reply},
unlink(Pid)
end),
?vtrace("backup server: ~p", [BackupServer]),
{noreply, State#state{backup = {BackupServer, From}}};
{ok, _} ->
{reply, {error, not_a_directory}, State};
Error ->
{reply, Error, State}
end;
handle_call(stop, _From, State) ->
?vlog("stop",[]),
{stop, normal, ok, State};
handle_call(Req, _From, State) ->
warning_msg("received unknown request: ~n~p", [Req]),
Reply = {error, {unknown, Req}},
{reply, Reply, State}.
handle_cast({verbosity, Verbosity}, State) ->
?vlog("verbosity: ~p -> ~p",[get(verbosity),Verbosity]),
put(verbosity,snmp_verbosity:validate(Verbosity)),
{noreply, State};
handle_cast(Msg, State) ->
warning_msg("received unknown message: ~n~p", [Msg]),
{noreply, State}.
handle_info({'EXIT', Pid, Reason}, #state{backup = {Pid, From}} = S) ->
?vlog("backup server (~p) exited for reason ~n~p", [Pid, Reason]),
gen_server:reply(From, {error, Reason}),
{noreply, S#state{backup = undefined}};
handle_info({'EXIT', Pid, Reason}, S) ->
{stop, {received_exit, Pid, Reason}, S};
handle_info({backup_done, Reply}, #state{backup = {_, From}} = S) ->
?vlog("backup done:"
"~n Reply: ~p", [Reply]),
gen_server:reply(From, Reply),
{noreply, S#state{backup = undefined}};
handle_info(?CACHE_GC_TRIGGER, #state{cache = Cache,
cache_age = Age,
cache_gclimit = GcLimit,
cache_autogc = true} = S)
when (Cache =/= ?NO_CACHE) ->
?vlog("cache gc trigger event", []),
maybe_gc_cache(Cache, Age, GcLimit),
Tmr = start_cache_gc_timer(),
{noreply, S#state{cache_tmr = Tmr}};
handle_info(?CACHE_GC_TRIGGER, S) ->
?vlog("out-of-date cache gc trigger event - ignore", []),
{noreply, S#state{cache_tmr = undefined}};
handle_info(Info, State) ->
warning_msg("received unknown info: ~n~p", [Info]),
{noreply, State}.
terminate(_Reason, #state{data = Data}) ->
catch snmpa_mib_data:close(Data),
ok.
code_change({down , _ Vsn } , S1 , ) - >
# state{data = Data , meo = MEO , , backup = B , cache = Cache } = S1 ,
del_cache(Cache ) ,
S2 = { state , Data , MEO , TEO , B } ,
{ state , Data , MEO , TEO , B } = S1 ,
S2 = # state{data = Data , meo = MEO , , backup = B , cache = Cache } ,
code_change(_Vsn, State, _Extra) ->
{ok, State}.
get_verbosity(Options) ->
get_opt(verbosity, Options, ?default_verbosity).
get_me_override(Options) ->
get_opt(mibentry_override, Options, false).
get_te_override(Options) ->
get_opt(trapentry_override, Options, false).
get_mib_storage(Options) ->
get_opt(mib_storage, Options, ets).
get_cacheopt_autogc(Cache, CacheOpts) ->
IsValid = fun(AutoGC) when ((AutoGC =:= true) orelse
(AutoGC =:= false)) ->
true;
(_) ->
false
end,
get_cacheopt(Cache, autogc, CacheOpts,
false, ?DEFAULT_CACHE_AUTOGC,
IsValid).
get_cacheopt_gclimit(Cache, CacheOpts) ->
IsValid = fun(Limit) when ((is_integer(Limit) andalso (Limit > 0)) orelse
(Limit =:= infinity)) ->
true;
(_) ->
false
end,
get_cacheopt(Cache, gclimit, CacheOpts,
infinity, ?DEFAULT_CACHE_GCLIMIT,
IsValid).
get_cacheopt_age(Cache, CacheOpts) ->
IsValid = fun(Age) when is_integer(Age) andalso (Age > 0) ->
true;
(_) ->
false
end,
get_cacheopt(Cache, age, CacheOpts,
?DEFAULT_CACHE_AGE, ?DEFAULT_CACHE_AGE,
IsValid).
get_cacheopt(?NO_CACHE, _, _, NoCacheVal, _, _) ->
NoCacheVal;
get_cacheopt(_, Key, Opts, _, Default, IsValid) ->
Val = get_opt(Key, Opts, Default),
case IsValid(Val) of
true ->
Val;
false ->
throw({error, {bad_option, {Key, Val}}})
end.
handle_update_cache_opts(cache, true = _Value,
#state{cache = ?NO_CACHE} = State) ->
{ok, State#state{cache = new_cache()}};
handle_update_cache_opts(cache, true = _Value, State) ->
{ok, State};
handle_update_cache_opts(cache, false = _Value,
#state{cache = ?NO_CACHE} = State) ->
{ok, State};
handle_update_cache_opts(cache, false = _Value,
#state{cache = Cache,
cache_tmr = Tmr} = State) ->
maybe_stop_cache_gc_timer(Tmr),
del_cache(Cache),
{ok, State#state{cache = ?NO_CACHE, cache_tmr = undefined}};
handle_update_cache_opts(autogc, true = _Value,
#state{cache_autogc = true} = State) ->
{ok, State};
handle_update_cache_opts(autogc, true = Value, State) ->
{ok, maybe_start_cache_gc_timer(State#state{cache_autogc = Value})};
handle_update_cache_opts(autogc, false = _Value,
#state{cache_autogc = false} = State) ->
{ok, State};
handle_update_cache_opts(autogc, false = Value,
#state{cache_tmr = Tmr} = State) ->
maybe_stop_cache_gc_timer(Tmr),
{ok, State#state{cache_autogc = Value, cache_tmr = undefined}};
handle_update_cache_opts(age, Age, State) ->
{ok, State#state{cache_age = Age}};
handle_update_cache_opts(gclimit, GcLimit, State) ->
{ok, State#state{cache_gclimit = GcLimit}};
handle_update_cache_opts(BadKey, Value, State) ->
{{error, {bad_cache_opt, BadKey, Value}}, State}.
maybe_stop_cache_gc_timer(undefined) ->
ok;
maybe_stop_cache_gc_timer(Tmr) ->
erlang:cancel_timer(Tmr).
maybe_start_cache_gc_timer(#state{cache = Cache,
cache_autogc = true,
cache_tmr = undefined} = State)
when (Cache =/= ?NO_CACHE) ->
Tmr = start_cache_gc_timer(),
State#state{cache_tmr = Tmr};
maybe_start_cache_gc_timer(State) ->
State.
start_cache_gc_timer() ->
erlang:send_after(?CACHE_GC_TICKTIME, self(), ?CACHE_GC_TRIGGER).
maybe_gc_cache(?NO_CACHE, _Age) ->
?vtrace("cache not enabled", []),
ok;
maybe_gc_cache(Cache, Age) ->
MatchSpec = gc_cache_matchspec(Age),
Keys = ets:select(Cache, MatchSpec),
do_gc_cache(Cache, Keys),
{ok, length(Keys)}.
maybe_gc_cache(?NO_CACHE, _Age, _GcLimit) ->
ok;
maybe_gc_cache(Cache, Age, infinity = _GcLimit) ->
maybe_gc_cache(Cache, Age);
maybe_gc_cache(Cache, Age, GcLimit) ->
MatchSpec = gc_cache_matchspec(Age),
Keys =
case ets:select(Cache, MatchSpec, GcLimit) of
{Match, _Cont} ->
Match;
'$end_of_table' ->
[]
end,
do_gc_cache(Cache, Keys),
{ok, length(Keys)}.
gc_cache_matchspec(Age) ->
Oldest = timestamp() - Age,
MatchHead = {'$1', '_', '$2'},
Guard = [{'<', '$2', Oldest}],
MatchFunc = {MatchHead, Guard, ['$1']},
MatchSpec = [MatchFunc],
MatchSpec.
do_gc_cache(_, []) ->
ok;
do_gc_cache(Cache, [Key|Keys]) ->
ets:delete(Cache, Key),
do_gc_cache(Cache, Keys).
maybe_invalidate_cache(?NO_CACHE) ->
?NO_CACHE;
maybe_invalidate_cache(Cache) ->
del_cache(Cache),
new_cache().
maybe_cache_size(?NO_CACHE) ->
{error, not_enabled};
maybe_cache_size(Cache) ->
{ok, ets:info(Cache, size)}.
new_cache() ->
ets:new(snmpa_mib_cache, [set, protected, {keypos, 1}]).
del_cache(?NO_CACHE) ->
ok;
del_cache(Cache) ->
ets:delete(Cache).
maybe_cache_lookup(?NO_CACHE, _) ->
?NO_CACHE;
maybe_cache_lookup(Cache, Key) ->
ets:lookup(Cache, Key).
size_cache(?NO_CACHE) ->
undefined;
size_cache(Cache) ->
case (catch ets:info(Cache, memory)) of
Sz when is_integer(Sz) ->
Sz;
_ ->
undefined
end.
timestamp() ->
snmp_misc:now(ms).
get_opt(Key, Options, Default) ->
snmp_misc:get_option(Key, Options, Default).
cast(MibServer, Msg) ->
gen_server:cast(MibServer, Msg).
call(MibServer, Req) ->
call(MibServer, Req, infinity).
call(MibServer, Req, To) ->
gen_server:call(MibServer, Req, To).
warning_msg(F, A) ->
?snmpa_warning("Mib server: " ++ F, A).
config_err(F, A) ->
snmpa_error:config_err(F, A).
|
79d4d7532b0d0d263ff11a961c7ba4e463ee2eb01bb8fb783c4009b512cace27 | DSTOQ/haskell-stellar-sdk | ParserSpec.hs | module Stellar.Core.Key.ParserSpec where
import qualified Data.Text as T
import Hedgehog.Extended
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Protolude
import Stellar.Core.Types.Key
import Stellar.Gens
run :: IO Bool
run = checkParallel $ Group "Parser Properties"
[ ("Parse public key", prop_parse_public_key)
, ("Parse secret key", prop_parse_secret_key)
, ("Parser error for invalid input length", prop_invalid_length_base32)
, ("Parser error for invalid Base 32", prop_invalid_base32)
]
prop_parse_public_key :: Property
prop_parse_public_key = property $ do
PublicKeyText key <- forAll genPublicKeyText
(void . evalEither . parsePublicKey) key
prop_parse_secret_key :: Property
prop_parse_secret_key = property $ do
SecretKeyText key <- forAll genSecretKeyText
(void . evalEither . parseSecretKey) key
prop_invalid_length_base32 :: Property
prop_invalid_length_base32 = property $ do
key <- forAll $ mfilter ((/= 72) . T.length)
$ Gen.text (Range.linear 1 100) Gen.alphaNum
KeyParser parser <- forAll genKeyParser
assert $ isLeft $ parser key
prop_invalid_base32 :: Property
prop_invalid_base32 = property $ do
key <- forAll $ Gen.text (Range.singleton 72) Gen.alphaNum
KeyParser parser <- forAll genKeyParser
assert $ isLeft $ parser key
| null | https://raw.githubusercontent.com/DSTOQ/haskell-stellar-sdk/82a76c2f951a2aaabdc38092fdc89044b278c53d/tests/test/Stellar/Core/Key/ParserSpec.hs | haskell | module Stellar.Core.Key.ParserSpec where
import qualified Data.Text as T
import Hedgehog.Extended
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Protolude
import Stellar.Core.Types.Key
import Stellar.Gens
run :: IO Bool
run = checkParallel $ Group "Parser Properties"
[ ("Parse public key", prop_parse_public_key)
, ("Parse secret key", prop_parse_secret_key)
, ("Parser error for invalid input length", prop_invalid_length_base32)
, ("Parser error for invalid Base 32", prop_invalid_base32)
]
prop_parse_public_key :: Property
prop_parse_public_key = property $ do
PublicKeyText key <- forAll genPublicKeyText
(void . evalEither . parsePublicKey) key
prop_parse_secret_key :: Property
prop_parse_secret_key = property $ do
SecretKeyText key <- forAll genSecretKeyText
(void . evalEither . parseSecretKey) key
prop_invalid_length_base32 :: Property
prop_invalid_length_base32 = property $ do
key <- forAll $ mfilter ((/= 72) . T.length)
$ Gen.text (Range.linear 1 100) Gen.alphaNum
KeyParser parser <- forAll genKeyParser
assert $ isLeft $ parser key
prop_invalid_base32 :: Property
prop_invalid_base32 = property $ do
key <- forAll $ Gen.text (Range.singleton 72) Gen.alphaNum
KeyParser parser <- forAll genKeyParser
assert $ isLeft $ parser key
|
|
3884a835e2520abec528ac2ea72a1d53d784463cf2eec981e532ca7247b5044b | ygrek/mldonkey | tests.ml |
open Printf
let pr fmt = ksprintf print_endline fmt
let test ?n ?s f =
try
f ()
with
exn ->
let msg = match s,n with
| Some s, Some n -> sprintf " %d %S" n s
| Some s, None -> sprintf " %S" s
| None, Some n -> sprintf " %d" n
| None, None -> ""
in
pr "Test%s failed: %s" msg (Printexc2.to_string exn)
let test1 ?n ?s f x = test ?n ?s (fun () -> f x)
let magnet s =
let magnet = CommonTypes.parse_magnet_url s in
pr "name: %S" magnet#name;
begin match magnet#size with Some size -> pr "size: %Ld" size | None -> () end;
pr "uids:";
List.iter (fun x -> pr " %s" (CommonTypes.string_of_uid x)) magnet#uids;
pr ""
let test_magnet () =
let t s = test1 ~s magnet s in
t "magnet:?xt=urn:tree:tiger:UXNWMYERN37HJNXB7V6KDJKZXMFBIQAGMDMYDBY&dn=DCPlusPlus-0.4032.exe";
t "magnet:?xt=urn:ed2k:354B15E68FB8F36D7CD88FF94116CDC1&xl=10826029&dn=mediawiki-1.15.1.tar.gz&xt=urn:tree:tiger:7N5OAMRNGMSSEUE3ORHOKWN4WWIQ5X4EBOOTLJY&xt=urn:btih:QHQXPYWMACKDWKP47RRVIV7VOURXFE5Q&tr=http%3A%2F%2Ftracker.example.org%2Fannounce.php%3Fuk%3D1111111111%26&as=http%3A%2F%2Fdownload.wikimedia.org%2Fmediawiki%2F1.15%2Fmediawiki-1.15.1.tar.gz&xs=http%3A%2F%2Fcache.example.org%2FXRX2PEFXOOEJFRVUCX6HMZMKS5TWG4K5&xs=dchub";
t "magnet:?xt=urn:ed2k:31D6CFE0D16AE931B73C59D7E0C089C0&xl=0&dn=zero_len.fil&xt=urn:bitprint:3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ.LWPNACQDBZRYXW3VHJVCJ64QBZNGHOHHHZWCLNQ&xt=urn:md5:D41D8CD98F00B204E9800998ECF8427E";
()
let test_shorten () =
let orig = "привет" in
for i = 0 to 100 do
test ~n:i ~s:"shorten" begin fun () ->
let s = DcGlobals.shorten_string orig i in
assert (s = String.sub orig 0 (min (String.length orig) (i*2)))
end
done;
()
let test_dc_parse () =
let t x s =
test ~s (fun () ->
match DcProtocol.dc_parse false s with
| DcProtocol.UnknownReq _ -> assert (not x)
| _ -> assert x)
in
t true "$ADCGET list /shared1/ 0 -1";
t true "$ADCGET file TTH/ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789012 1332982893 9194387";
t false "$ADCGET tthl q 0 -1"
let test_hmac_md5 () =
test ~s:"HMAC-MD5" begin fun () ->
let t k c s = Mailer.hmac_md5 k c = Md4.Base16.of_string 16 s in
assert (t (String.make 16 '\x0B') "Hi There" "9294727a3638bb1c13f48ef8158bfc9d");
assert (t "Jefe" "what do ya want for nothing?" "750c783e6ab0b503eaa86e310a5db738");
assert (t (String.make 16 '\xAA') (String.make 50 '\xDD') "56be34521d144c88dbb8c733f0e8b3f6");
end
let () =
(* let _ = Ip.addr_of_string "dchub" in *)
let _ = " /submit?q = dcn+dchub+411 " in
test_magnet ();
test_shorten ();
test_dc_parse ();
test_hmac_md5 ();
pr "Tests finished";
()
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/tools/tests.ml | ocaml | let _ = Ip.addr_of_string "dchub" in |
open Printf
let pr fmt = ksprintf print_endline fmt
let test ?n ?s f =
try
f ()
with
exn ->
let msg = match s,n with
| Some s, Some n -> sprintf " %d %S" n s
| Some s, None -> sprintf " %S" s
| None, Some n -> sprintf " %d" n
| None, None -> ""
in
pr "Test%s failed: %s" msg (Printexc2.to_string exn)
let test1 ?n ?s f x = test ?n ?s (fun () -> f x)
let magnet s =
let magnet = CommonTypes.parse_magnet_url s in
pr "name: %S" magnet#name;
begin match magnet#size with Some size -> pr "size: %Ld" size | None -> () end;
pr "uids:";
List.iter (fun x -> pr " %s" (CommonTypes.string_of_uid x)) magnet#uids;
pr ""
let test_magnet () =
let t s = test1 ~s magnet s in
t "magnet:?xt=urn:tree:tiger:UXNWMYERN37HJNXB7V6KDJKZXMFBIQAGMDMYDBY&dn=DCPlusPlus-0.4032.exe";
t "magnet:?xt=urn:ed2k:354B15E68FB8F36D7CD88FF94116CDC1&xl=10826029&dn=mediawiki-1.15.1.tar.gz&xt=urn:tree:tiger:7N5OAMRNGMSSEUE3ORHOKWN4WWIQ5X4EBOOTLJY&xt=urn:btih:QHQXPYWMACKDWKP47RRVIV7VOURXFE5Q&tr=http%3A%2F%2Ftracker.example.org%2Fannounce.php%3Fuk%3D1111111111%26&as=http%3A%2F%2Fdownload.wikimedia.org%2Fmediawiki%2F1.15%2Fmediawiki-1.15.1.tar.gz&xs=http%3A%2F%2Fcache.example.org%2FXRX2PEFXOOEJFRVUCX6HMZMKS5TWG4K5&xs=dchub";
t "magnet:?xt=urn:ed2k:31D6CFE0D16AE931B73C59D7E0C089C0&xl=0&dn=zero_len.fil&xt=urn:bitprint:3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ.LWPNACQDBZRYXW3VHJVCJ64QBZNGHOHHHZWCLNQ&xt=urn:md5:D41D8CD98F00B204E9800998ECF8427E";
()
let test_shorten () =
let orig = "привет" in
for i = 0 to 100 do
test ~n:i ~s:"shorten" begin fun () ->
let s = DcGlobals.shorten_string orig i in
assert (s = String.sub orig 0 (min (String.length orig) (i*2)))
end
done;
()
let test_dc_parse () =
let t x s =
test ~s (fun () ->
match DcProtocol.dc_parse false s with
| DcProtocol.UnknownReq _ -> assert (not x)
| _ -> assert x)
in
t true "$ADCGET list /shared1/ 0 -1";
t true "$ADCGET file TTH/ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789012 1332982893 9194387";
t false "$ADCGET tthl q 0 -1"
let test_hmac_md5 () =
test ~s:"HMAC-MD5" begin fun () ->
let t k c s = Mailer.hmac_md5 k c = Md4.Base16.of_string 16 s in
assert (t (String.make 16 '\x0B') "Hi There" "9294727a3638bb1c13f48ef8158bfc9d");
assert (t "Jefe" "what do ya want for nothing?" "750c783e6ab0b503eaa86e310a5db738");
assert (t (String.make 16 '\xAA') (String.make 50 '\xDD') "56be34521d144c88dbb8c733f0e8b3f6");
end
let () =
let _ = " /submit?q = dcn+dchub+411 " in
test_magnet ();
test_shorten ();
test_dc_parse ();
test_hmac_md5 ();
pr "Tests finished";
()
|
720a45f6c96495845a16fbc535ddedbde3b9d041daddc3179ed3c9d3220b728a | hjwylde/werewolf | Quit.hs | |
Module : Werewolf . Command . Quit
Description : Handler for the quit subcommand .
Copyright : ( c ) , 2016
License : :
Handler for the quit subcommand .
Module : Werewolf.Command.Quit
Description : Handler for the quit subcommand.
Copyright : (c) Henry J. Wylde, 2016
License : BSD3
Maintainer :
Handler for the quit subcommand.
-}
module Werewolf.Command.Quit (
-- * Handle
handle,
) where
import Control.Monad.Except
import Control.Monad.Extra
import Control.Monad.Random
import Control.Monad.State
import Control.Monad.Writer
import Data.Text (Text)
import Game.Werewolf
import Game.Werewolf.Command
import Game.Werewolf.Command.Global
import Game.Werewolf.Engine
import Game.Werewolf.Message.Error
import Werewolf.System
handle :: (MonadIO m, MonadRandom m) => Text -> Text -> m ()
handle callerName tag = do
unlessM (doesGameExist tag) $ exitWith failure
{ messages = [noGameRunningMessage callerName]
}
game <- readGame tag
let command = quitCommand callerName
result <- runExceptT . runWriterT $ execStateT (apply command >> checkStage >> checkGameOver) game
case result of
Left errorMessages -> exitWith failure { messages = errorMessages }
Right (game', messages) -> writeOrDeleteGame tag game' >> exitWith success { messages = messages }
| null | https://raw.githubusercontent.com/hjwylde/werewolf/d22a941120a282127fc3e2db52e7c86b5d238344/app/Werewolf/Command/Quit.hs | haskell | * Handle | |
Module : Werewolf . Command . Quit
Description : Handler for the quit subcommand .
Copyright : ( c ) , 2016
License : :
Handler for the quit subcommand .
Module : Werewolf.Command.Quit
Description : Handler for the quit subcommand.
Copyright : (c) Henry J. Wylde, 2016
License : BSD3
Maintainer :
Handler for the quit subcommand.
-}
module Werewolf.Command.Quit (
handle,
) where
import Control.Monad.Except
import Control.Monad.Extra
import Control.Monad.Random
import Control.Monad.State
import Control.Monad.Writer
import Data.Text (Text)
import Game.Werewolf
import Game.Werewolf.Command
import Game.Werewolf.Command.Global
import Game.Werewolf.Engine
import Game.Werewolf.Message.Error
import Werewolf.System
handle :: (MonadIO m, MonadRandom m) => Text -> Text -> m ()
handle callerName tag = do
unlessM (doesGameExist tag) $ exitWith failure
{ messages = [noGameRunningMessage callerName]
}
game <- readGame tag
let command = quitCommand callerName
result <- runExceptT . runWriterT $ execStateT (apply command >> checkStage >> checkGameOver) game
case result of
Left errorMessages -> exitWith failure { messages = errorMessages }
Right (game', messages) -> writeOrDeleteGame tag game' >> exitWith success { messages = messages }
|
710af026911c80e7c35b1949687715d4780f28ff9887748e0b892fe6a9c5a0ed | uw-unsat/jitsynth | tostr.rkt | #lang rosette
(require "../common/case-hex.rkt")
(require "../common/instructions.rkt")
(require (only-in "../common/debug.rkt" [debugln common:debugln]))
(provide tostr-instr)
(provide tostr-instrs)
(define DEBUG #f)
(define (debugln x)
(if DEBUG (common:debugln x) void))
(define (tostr-func func3 func7)
(case-hex func3 3
[(0) (case-hex func7 7
[(0) "add"]
[(32) "sub"])]
[(1) "sll"]
[(2) (error "slt not implemented")]
[(3) (error "sltu not implemented")]
NOTE : May need another case for signed division
[(5) (case-hex func7 7
[(0) "srl"]
[(1) "div"]
arith right shift if func7 is 32
[(6) "or"]
[(7) (case-hex func7 7
[(0) "and"]
[(1) "mod"])]))
(define (tostr-imm-func func3 imm)
(case-hex func3 3
[(0) "addi"]
[(1) "slli"]
[(2) (error "slti not implemented")]
[(3) (error "sltiu not implemented")]
[(4) "xori"]
[(5) (case-hex (extract 10 10 imm) 1
[(0) "srli"]
[(1) "srai"])]
[(6) "ori"]
[(7) "andi"]))
(define (tostr-reg x)
(case-hex x 5
[(0) "0"]
[(1) "ra"]
[(2) "sp"]
[(3) "gp"]
[(4) "tp"]
[(5) "t0"]
[(6) "t1"]
[(7) "t2"]
[(8) "fp"]
[(9) "s1"]
[(10) "a0"]
[(11) "a1"]
[(12) "a2"]
[(13) "a3"]
[(14) "a4"]
[(15) "a5"]
[(16) "a6"]
[(17) "a7"]
[(18) "s2"]
[(19) "s3"]
[(20) "s4"]
[(21) "s5"]
[(12) "s6"]
[(23) "s7"]
[(24) "s8"]
[(25) "s9"]
[(26) "s10"]
[(27) "s11"]
[(28) "t3"]
[(29) "t4"]
[(30) "t5"]
[(31) "t6"]))
(define (tostr-imm b)
(~a "0x" (number->string (bitvector->natural b) 16)))
(define (tostr-off b)
(~a (number->string (bitvector->integer b))))
(define (tostr-arith-64 ri)
(let* ([func3 (riscv-instr-func3 ri)]
[func7 (riscv-instr-func7 ri)]
[src1 (riscv-instr-src1 ri)]
[src2 (riscv-instr-src2 ri)]
[dst (riscv-instr-dst ri)])
(~a (tostr-func func3 func7) " "
(tostr-reg dst) ", "
(tostr-reg src1) ", "
(tostr-reg src2))))
(define (tostr-arith-32 ri)
(let* ([func3 (riscv-instr-func3 ri)]
[func7 (riscv-instr-func7 ri)]
[src1 (riscv-instr-src1 ri)]
[src2 (riscv-instr-src2 ri)]
[dst (riscv-instr-dst ri)]
[func (~a (tostr-func func3 func7) "w")])
(~a func " "
(tostr-reg dst) ", "
(tostr-reg src1) ", "
(tostr-reg src2))))
(define (tostr-imm-arith-64 ri)
(let* ([func3 (riscv-instr-func3 ri)]
[imm (riscv-instr-imm ri)]
[src (riscv-instr-src1 ri)]
[dst (riscv-instr-dst ri)])
(if (riscv-nop? ri) "nop"
(~a (tostr-imm-func func3 imm) " "
(tostr-reg dst) ", "
(tostr-reg src) ", "
(tostr-imm imm)))))
(define (tostr-imm-arith-32 ri)
(let* ([func3 (riscv-instr-func3 ri)]
[imm (riscv-instr-imm ri)]
[src (riscv-instr-src1 ri)]
[dst (riscv-instr-dst ri)]
[func (~a (tostr-imm-func func3 imm) "w")])
(~a func " "
(tostr-reg dst) ", "
(tostr-reg src) ", "
(tostr-imm imm))))
(define (tostr-load ri)
(let* ([width (riscv-instr-func3 ri)]
[base (riscv-instr-src1 ri)]
[dst (riscv-instr-dst ri)]
[offset (riscv-instr-imm ri)]
[func
(case-hex width 3
[(0) "lb"]
[(1) "lh"]
[(2) "lw"]
[(3) "ld"]
[(4) "lbu"]
[(5) "lhu"]
[(6) "lwu"])])
(~a func " "
(tostr-reg dst) ", "
(tostr-off offset) "(" (tostr-reg base) ")")))
(define (tostr-store ri)
(let* ([width (riscv-instr-func3 ri)]
[src (riscv-instr-src2 ri)]
[base (riscv-instr-src1 ri)]
[offset (riscv-instr-imm ri)]
[func
(case-hex width 3
[(0) "sb"]
[(1) "sh"]
[(2) "sw"]
[(3) "sd"])])
(~a func " "
(tostr-off offset) "(" (tostr-reg base) "), "
(tostr-reg src))))
TODO semantics here might be wrong , may need to first update PC
(define (tostr-auipc ri)
(let* ([imm (riscv-instr-imm ri)]
[dst (riscv-instr-dst ri)])
(~a "auipc " (tostr-reg dst) ", " (tostr-imm imm))))
; NOTE: The result is sign extended always
(define (tostr-lui ri)
(let* ([imm (riscv-instr-imm ri)]
[dst (riscv-instr-dst ri)])
(~a "lui " (tostr-reg dst) ", " (tostr-imm imm))))
(define (tostr-branch ri)
(let* ([func3 (riscv-instr-func3 ri)]
[rs2 (riscv-instr-src2 ri)]
[rs1 (riscv-instr-src1 ri)]
[offset (riscv-instr-imm ri)]
[func (case-hex func3 3
[(0) "beq"]
[(1) "bne"]
[(4) "blt"]
[(5) "bge"]
[(6) "bltu"]
[(7) "bgeu"])])
(~a func " "
(tostr-reg rs1) ", "
(tostr-reg rs2) ", "
(tostr-off offset))))
(define (tostr-jal ri)
(let* ([dst (riscv-instr-dst ri)] ; assume this is 0
[offset (riscv-instr-imm ri)])
(~a "jal " (tostr-reg dst) ", " (tostr-off offset))))
(define (tostr-jalr ri)
(let* ([dst (riscv-instr-dst ri)]
[offset (riscv-instr-imm ri)]
[src1 (riscv-instr-src1 ri)])
(~a "jalr " (tostr-reg dst) ", " (tostr-off offset) "(" (tostr-reg src1) ")")))
(define (tostr-instr ri)
(if (not (null? (symbolics ri)))
(~a ri " (symbolic)")
(let* ([opcode (riscv-instr-op ri)])
(case-hex opcode 7
[(#x3b) (tostr-arith-32 ri)]
[(#x1b) (tostr-imm-arith-32 ri)]
[(#x33) (tostr-arith-64 ri)]
[(#x13) (tostr-imm-arith-64 ri)]
[(#x03) (tostr-load ri)]
[(#x23) (tostr-store ri)]
[(#x6f) (tostr-jal ri)]
[(#x63) (tostr-branch ri)]
[(#x37) (tostr-lui ri)]
[(#x73) "ret"]
[(#x67) (tostr-jalr ri)]
[(#x17) (tostr-auipc ri)]
[(0) "0"]))))
(define (tostr-instrs ri-list)
(if (null? ri-list) ""
(~a (tostr-instr (first ri-list)) "\n" (tostr-instrs (rest ri-list)))))
| null | https://raw.githubusercontent.com/uw-unsat/jitsynth/69529e18d4a8d4dace884bfde91aa26b549523fa/riscv/tostr.rkt | racket | NOTE: The result is sign extended always
assume this is 0 | #lang rosette
(require "../common/case-hex.rkt")
(require "../common/instructions.rkt")
(require (only-in "../common/debug.rkt" [debugln common:debugln]))
(provide tostr-instr)
(provide tostr-instrs)
(define DEBUG #f)
(define (debugln x)
(if DEBUG (common:debugln x) void))
(define (tostr-func func3 func7)
(case-hex func3 3
[(0) (case-hex func7 7
[(0) "add"]
[(32) "sub"])]
[(1) "sll"]
[(2) (error "slt not implemented")]
[(3) (error "sltu not implemented")]
NOTE : May need another case for signed division
[(5) (case-hex func7 7
[(0) "srl"]
[(1) "div"]
arith right shift if func7 is 32
[(6) "or"]
[(7) (case-hex func7 7
[(0) "and"]
[(1) "mod"])]))
(define (tostr-imm-func func3 imm)
(case-hex func3 3
[(0) "addi"]
[(1) "slli"]
[(2) (error "slti not implemented")]
[(3) (error "sltiu not implemented")]
[(4) "xori"]
[(5) (case-hex (extract 10 10 imm) 1
[(0) "srli"]
[(1) "srai"])]
[(6) "ori"]
[(7) "andi"]))
(define (tostr-reg x)
(case-hex x 5
[(0) "0"]
[(1) "ra"]
[(2) "sp"]
[(3) "gp"]
[(4) "tp"]
[(5) "t0"]
[(6) "t1"]
[(7) "t2"]
[(8) "fp"]
[(9) "s1"]
[(10) "a0"]
[(11) "a1"]
[(12) "a2"]
[(13) "a3"]
[(14) "a4"]
[(15) "a5"]
[(16) "a6"]
[(17) "a7"]
[(18) "s2"]
[(19) "s3"]
[(20) "s4"]
[(21) "s5"]
[(12) "s6"]
[(23) "s7"]
[(24) "s8"]
[(25) "s9"]
[(26) "s10"]
[(27) "s11"]
[(28) "t3"]
[(29) "t4"]
[(30) "t5"]
[(31) "t6"]))
(define (tostr-imm b)
(~a "0x" (number->string (bitvector->natural b) 16)))
(define (tostr-off b)
(~a (number->string (bitvector->integer b))))
(define (tostr-arith-64 ri)
(let* ([func3 (riscv-instr-func3 ri)]
[func7 (riscv-instr-func7 ri)]
[src1 (riscv-instr-src1 ri)]
[src2 (riscv-instr-src2 ri)]
[dst (riscv-instr-dst ri)])
(~a (tostr-func func3 func7) " "
(tostr-reg dst) ", "
(tostr-reg src1) ", "
(tostr-reg src2))))
(define (tostr-arith-32 ri)
(let* ([func3 (riscv-instr-func3 ri)]
[func7 (riscv-instr-func7 ri)]
[src1 (riscv-instr-src1 ri)]
[src2 (riscv-instr-src2 ri)]
[dst (riscv-instr-dst ri)]
[func (~a (tostr-func func3 func7) "w")])
(~a func " "
(tostr-reg dst) ", "
(tostr-reg src1) ", "
(tostr-reg src2))))
(define (tostr-imm-arith-64 ri)
(let* ([func3 (riscv-instr-func3 ri)]
[imm (riscv-instr-imm ri)]
[src (riscv-instr-src1 ri)]
[dst (riscv-instr-dst ri)])
(if (riscv-nop? ri) "nop"
(~a (tostr-imm-func func3 imm) " "
(tostr-reg dst) ", "
(tostr-reg src) ", "
(tostr-imm imm)))))
(define (tostr-imm-arith-32 ri)
(let* ([func3 (riscv-instr-func3 ri)]
[imm (riscv-instr-imm ri)]
[src (riscv-instr-src1 ri)]
[dst (riscv-instr-dst ri)]
[func (~a (tostr-imm-func func3 imm) "w")])
(~a func " "
(tostr-reg dst) ", "
(tostr-reg src) ", "
(tostr-imm imm))))
(define (tostr-load ri)
(let* ([width (riscv-instr-func3 ri)]
[base (riscv-instr-src1 ri)]
[dst (riscv-instr-dst ri)]
[offset (riscv-instr-imm ri)]
[func
(case-hex width 3
[(0) "lb"]
[(1) "lh"]
[(2) "lw"]
[(3) "ld"]
[(4) "lbu"]
[(5) "lhu"]
[(6) "lwu"])])
(~a func " "
(tostr-reg dst) ", "
(tostr-off offset) "(" (tostr-reg base) ")")))
(define (tostr-store ri)
(let* ([width (riscv-instr-func3 ri)]
[src (riscv-instr-src2 ri)]
[base (riscv-instr-src1 ri)]
[offset (riscv-instr-imm ri)]
[func
(case-hex width 3
[(0) "sb"]
[(1) "sh"]
[(2) "sw"]
[(3) "sd"])])
(~a func " "
(tostr-off offset) "(" (tostr-reg base) "), "
(tostr-reg src))))
TODO semantics here might be wrong , may need to first update PC
(define (tostr-auipc ri)
(let* ([imm (riscv-instr-imm ri)]
[dst (riscv-instr-dst ri)])
(~a "auipc " (tostr-reg dst) ", " (tostr-imm imm))))
(define (tostr-lui ri)
(let* ([imm (riscv-instr-imm ri)]
[dst (riscv-instr-dst ri)])
(~a "lui " (tostr-reg dst) ", " (tostr-imm imm))))
(define (tostr-branch ri)
(let* ([func3 (riscv-instr-func3 ri)]
[rs2 (riscv-instr-src2 ri)]
[rs1 (riscv-instr-src1 ri)]
[offset (riscv-instr-imm ri)]
[func (case-hex func3 3
[(0) "beq"]
[(1) "bne"]
[(4) "blt"]
[(5) "bge"]
[(6) "bltu"]
[(7) "bgeu"])])
(~a func " "
(tostr-reg rs1) ", "
(tostr-reg rs2) ", "
(tostr-off offset))))
(define (tostr-jal ri)
[offset (riscv-instr-imm ri)])
(~a "jal " (tostr-reg dst) ", " (tostr-off offset))))
(define (tostr-jalr ri)
(let* ([dst (riscv-instr-dst ri)]
[offset (riscv-instr-imm ri)]
[src1 (riscv-instr-src1 ri)])
(~a "jalr " (tostr-reg dst) ", " (tostr-off offset) "(" (tostr-reg src1) ")")))
(define (tostr-instr ri)
(if (not (null? (symbolics ri)))
(~a ri " (symbolic)")
(let* ([opcode (riscv-instr-op ri)])
(case-hex opcode 7
[(#x3b) (tostr-arith-32 ri)]
[(#x1b) (tostr-imm-arith-32 ri)]
[(#x33) (tostr-arith-64 ri)]
[(#x13) (tostr-imm-arith-64 ri)]
[(#x03) (tostr-load ri)]
[(#x23) (tostr-store ri)]
[(#x6f) (tostr-jal ri)]
[(#x63) (tostr-branch ri)]
[(#x37) (tostr-lui ri)]
[(#x73) "ret"]
[(#x67) (tostr-jalr ri)]
[(#x17) (tostr-auipc ri)]
[(0) "0"]))))
(define (tostr-instrs ri-list)
(if (null? ri-list) ""
(~a (tostr-instr (first ri-list)) "\n" (tostr-instrs (rest ri-list)))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.