_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 |
|---|---|---|---|---|---|---|---|---|
c58b4cab1c967f9283c78e5552bf9f5df8074c83c19954d8c99f1db9663a2358 | dwysocki/mini-java | errors.clj | (ns mini-java.errors
"Utility functions for printing errors.
Used in both parse errors and static semantics errors."
(:require [mini-java.util :refer [parser-filename]]))
(defn underline-str
"Given a line with an error at the given index,
returns a string of whitespace ending with the ^ character, which
points to the error. Tabs are handled correctly.
For example, given the Java line:
= 2 ;
returns
^"
[error-line index]
(let [whitespace (filter #(Character/isWhitespace %)
(take index error-line))
remaining (- index (count whitespace))]
(str (clojure.string/join whitespace)
(clojure.string/join (repeat remaining " "))
"^")))
(defn underline-error
"Prints the line on which the current error occurred, and underlines
the error with a ^"
[parser line column]
(let [tokens (.getInputStream parser)
lines (-> tokens
.getTokenSource .getInputStream .toString
clojure.string/split-lines)]
(if (> line (count lines))
reached EOF , underline that
(println "<EOF>\n^")
did not reach EOF , do a more descriptive underline
(let [error-line (nth lines (dec line))
underline (underline-str error-line column)]
(println error-line)
(println underline)))))
(defn print-error
"Prints the given error msg along with the file, line, and column in which
it occurred. This is used for _all_ errors."
[parser msg line column]
(let [filename (parser-filename parser)]
(binding [*out* *err*]
(println (str filename ":" line ": error: " msg))
(underline-error parser line column))))
(defn print-type-error
"Prints a type mismatch error"
[parser msg line column found required]
(print-error parser msg line column)
(binding [*out* *err*]
(println " required:" required)
(println " found: " found)))
(defn print-symbol-error
"Prints a missing symbol error"
[parser msg line column symbol location]
(print-error parser msg line column)
(binding [*out* *err*]
(println " symbol: variable" symbol)
(println " location: class" location)))
| null | https://raw.githubusercontent.com/dwysocki/mini-java/5f20c87fd33c7535b126a0c01bc567489b60cb67/src/mini_java/errors.clj | clojure | (ns mini-java.errors
"Utility functions for printing errors.
Used in both parse errors and static semantics errors."
(:require [mini-java.util :refer [parser-filename]]))
(defn underline-str
"Given a line with an error at the given index,
returns a string of whitespace ending with the ^ character, which
points to the error. Tabs are handled correctly.
For example, given the Java line:
returns
^"
[error-line index]
(let [whitespace (filter #(Character/isWhitespace %)
(take index error-line))
remaining (- index (count whitespace))]
(str (clojure.string/join whitespace)
(clojure.string/join (repeat remaining " "))
"^")))
(defn underline-error
"Prints the line on which the current error occurred, and underlines
the error with a ^"
[parser line column]
(let [tokens (.getInputStream parser)
lines (-> tokens
.getTokenSource .getInputStream .toString
clojure.string/split-lines)]
(if (> line (count lines))
reached EOF , underline that
(println "<EOF>\n^")
did not reach EOF , do a more descriptive underline
(let [error-line (nth lines (dec line))
underline (underline-str error-line column)]
(println error-line)
(println underline)))))
(defn print-error
"Prints the given error msg along with the file, line, and column in which
it occurred. This is used for _all_ errors."
[parser msg line column]
(let [filename (parser-filename parser)]
(binding [*out* *err*]
(println (str filename ":" line ": error: " msg))
(underline-error parser line column))))
(defn print-type-error
"Prints a type mismatch error"
[parser msg line column found required]
(print-error parser msg line column)
(binding [*out* *err*]
(println " required:" required)
(println " found: " found)))
(defn print-symbol-error
"Prints a missing symbol error"
[parser msg line column symbol location]
(print-error parser msg line column)
(binding [*out* *err*]
(println " symbol: variable" symbol)
(println " location: class" location)))
| |
40a6e7b0830686cf6afbbd1e430f47a1a459a6c6d506f897140dce6da582b1c2 | LeventErkok/sbvPlugin | Plugin.hs | ---------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Plugin.Analyze
Copyright : ( c )
-- License : BSD3
-- Maintainer :
-- Stability : experimental
--
-- Main entry point to the SBV Plugin
-----------------------------------------------------------------------------
# LANGUAGE NamedFieldPuns #
{-# OPTIONS_GHC -Wall -Werror #-}
module Data.SBV.Plugin.Plugin(plugin) where
import GHC.Plugins
import System.Exit
import Data.Maybe (fromJust)
import Data.List (sortBy)
import Data.Bits (bitSizeMaybe)
import Data.IORef
import qualified Data.Map as M
import Data.SBV.Plugin.Common
import Data.SBV.Plugin.Env
import Data.SBV.Plugin.Analyze (analyzeBind)
-- | Entry point to the plugin
plugin :: Plugin
plugin = defaultPlugin {installCoreToDos = install}
where install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
install [] todos = return (sbvPass : todos)
install ["skip"] todos = return todos
install ["runLast"] todos = return (todos ++ [sbvPass])
install opts _ = do liftIO $ putStrLn $ "[SBV] Unexpected command line options: " ++ show opts
liftIO $ putStrLn ""
liftIO $ putStrLn "Options:"
liftIO $ putStrLn " skip (does not run the plugin)"
liftIO $ putStrLn " runLast (run the SBVPlugin last in the pipeline)"
liftIO exitFailure
sbvPass = CoreDoPluginPass "SBV based analysis" pass
pass :: ModGuts -> CoreM ModGuts
pass guts@ModGuts{mg_binds} = do
df <- getDynFlags
anns <- snd <$> getAnnotations deserializeWithData guts
let wsz = fromJust (bitSizeMaybe (0::Int))
baseTCs <- buildTCEnv wsz
baseEnv <- buildFunEnv wsz
baseDests <- buildDests
uninteresting <- uninterestingTypes
specials <- buildSpecials
rUninterpreted <- liftIO $ newIORef []
rUsedNames <- liftIO $ newIORef []
rUITypes <- liftIO $ newIORef []
let cfg = Config { isGHCi = ghcMode df == CompManager
, opts = []
, sbvAnnotation = lookupWithDefaultUFM anns [] . varName
, cfgEnv = Env { curLoc = []
, flags = df
, machWordSize = wsz
, mbListSize = Nothing
, uninteresting = uninteresting
, rUninterpreted = rUninterpreted
, rUsedNames = rUsedNames
, rUITypes = rUITypes
, specials = specials
, tcMap = baseTCs
, envMap = baseEnv
, destMap = baseDests
, bailOut = \s ss -> error $ unlines (s:ss)
, coreMap = M.fromList [(b, (varSpan b, e)) | (b, e) <- flattenBinds mg_binds]
}
}
let bindLoc (NonRec b _) = varSpan b
bindLoc (Rec []) = noSrcSpan
bindLoc (Rec ((b, _):_)) = varSpan b
cmp a b = bindLoc a `leftmost_smallest` bindLoc b
mapM_ (analyzeBind cfg) $ sortBy cmp mg_binds
return guts
| null | https://raw.githubusercontent.com/LeventErkok/sbvPlugin/8d414961ed68aa80f306056eff4fe462142fc26e/Data/SBV/Plugin/Plugin.hs | haskell | -------------------------------------------------------------------------
|
Module : Data.SBV.Plugin.Analyze
License : BSD3
Maintainer :
Stability : experimental
Main entry point to the SBV Plugin
---------------------------------------------------------------------------
# OPTIONS_GHC -Wall -Werror #
| Entry point to the plugin | Copyright : ( c )
# LANGUAGE NamedFieldPuns #
module Data.SBV.Plugin.Plugin(plugin) where
import GHC.Plugins
import System.Exit
import Data.Maybe (fromJust)
import Data.List (sortBy)
import Data.Bits (bitSizeMaybe)
import Data.IORef
import qualified Data.Map as M
import Data.SBV.Plugin.Common
import Data.SBV.Plugin.Env
import Data.SBV.Plugin.Analyze (analyzeBind)
plugin :: Plugin
plugin = defaultPlugin {installCoreToDos = install}
where install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
install [] todos = return (sbvPass : todos)
install ["skip"] todos = return todos
install ["runLast"] todos = return (todos ++ [sbvPass])
install opts _ = do liftIO $ putStrLn $ "[SBV] Unexpected command line options: " ++ show opts
liftIO $ putStrLn ""
liftIO $ putStrLn "Options:"
liftIO $ putStrLn " skip (does not run the plugin)"
liftIO $ putStrLn " runLast (run the SBVPlugin last in the pipeline)"
liftIO exitFailure
sbvPass = CoreDoPluginPass "SBV based analysis" pass
pass :: ModGuts -> CoreM ModGuts
pass guts@ModGuts{mg_binds} = do
df <- getDynFlags
anns <- snd <$> getAnnotations deserializeWithData guts
let wsz = fromJust (bitSizeMaybe (0::Int))
baseTCs <- buildTCEnv wsz
baseEnv <- buildFunEnv wsz
baseDests <- buildDests
uninteresting <- uninterestingTypes
specials <- buildSpecials
rUninterpreted <- liftIO $ newIORef []
rUsedNames <- liftIO $ newIORef []
rUITypes <- liftIO $ newIORef []
let cfg = Config { isGHCi = ghcMode df == CompManager
, opts = []
, sbvAnnotation = lookupWithDefaultUFM anns [] . varName
, cfgEnv = Env { curLoc = []
, flags = df
, machWordSize = wsz
, mbListSize = Nothing
, uninteresting = uninteresting
, rUninterpreted = rUninterpreted
, rUsedNames = rUsedNames
, rUITypes = rUITypes
, specials = specials
, tcMap = baseTCs
, envMap = baseEnv
, destMap = baseDests
, bailOut = \s ss -> error $ unlines (s:ss)
, coreMap = M.fromList [(b, (varSpan b, e)) | (b, e) <- flattenBinds mg_binds]
}
}
let bindLoc (NonRec b _) = varSpan b
bindLoc (Rec []) = noSrcSpan
bindLoc (Rec ((b, _):_)) = varSpan b
cmp a b = bindLoc a `leftmost_smallest` bindLoc b
mapM_ (analyzeBind cfg) $ sortBy cmp mg_binds
return guts
|
09d9f9078b107219a8288e807b8bb128cf03d9f328955363f614fd382b081497 | monadbobo/ocaml-core | extended_monad.ml | module List = Core.Std.List
module type S = sig
include Core.Monad.S
(* Like [List.map] but for functions which return monads *)
val map_monad : 'a list -> f : ('a -> 'b t) -> 'b list t
(* Like [map_monad] but ignores the outputs from the function. *)
val map_monad_ignore : 'a list -> f : ('a -> unit t) -> unit t
end
module Make (M : Core.Monad.Basic) : S with type 'a t := 'a M.t = struct
include Core.Monad.Make (M)
let map_monad list ~f = all (List.map ~f list)
let map_monad_ignore list ~f = all_ignore (List.map ~f list)
end
module type S2 = sig
include Core.Monad.S2
val map_monad : 'a list -> f : ('a -> ('b, 'c) t) -> ('b list, 'c) t
val map_monad_ignore : 'a list -> f : ('a -> (unit, 'b) t) -> (unit, 'b) t
end
module Make2 (M : Core.Monad.Basic2) : S2 with type ('a,'b) t := ('a,'b) M.t = struct
include Core.Monad.Make2 (M)
let map_monad list ~f = all (List.map ~f list)
let map_monad_ignore list ~f = all_ignore (List.map ~f list)
end
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/extended/lib/extended_monad.ml | ocaml | Like [List.map] but for functions which return monads
Like [map_monad] but ignores the outputs from the function. | module List = Core.Std.List
module type S = sig
include Core.Monad.S
val map_monad : 'a list -> f : ('a -> 'b t) -> 'b list t
val map_monad_ignore : 'a list -> f : ('a -> unit t) -> unit t
end
module Make (M : Core.Monad.Basic) : S with type 'a t := 'a M.t = struct
include Core.Monad.Make (M)
let map_monad list ~f = all (List.map ~f list)
let map_monad_ignore list ~f = all_ignore (List.map ~f list)
end
module type S2 = sig
include Core.Monad.S2
val map_monad : 'a list -> f : ('a -> ('b, 'c) t) -> ('b list, 'c) t
val map_monad_ignore : 'a list -> f : ('a -> (unit, 'b) t) -> (unit, 'b) t
end
module Make2 (M : Core.Monad.Basic2) : S2 with type ('a,'b) t := ('a,'b) M.t = struct
include Core.Monad.Make2 (M)
let map_monad list ~f = all (List.map ~f list)
let map_monad_ignore list ~f = all_ignore (List.map ~f list)
end
|
1b1ecd2d577d18a62b592ed2b2aa6e6303b717a5554cf01039d3036515577bc6 | WorksHub/client | www_homepage.cljc | (ns wh.components.www-homepage
(:require
#?(:cljs [reagent.core :as r])
[clojure.string :as str]
[wh.common.data :as data]
[wh.common.text :as txt]
[wh.components.carousel :refer [carousel]]
[wh.components.common :refer [companies-section link]]
[wh.components.icons :refer [icon]]
[wh.how-it-works.views :as hiw]
[wh.re-frame.subs :refer [<sub]]
[wh.util :as util]))
(def num-clouds 23)
(def get-started-cta-string "Get Started for Free")
(comment
"Used to generate the SASS for clouds"
(println
(loop [result "" total -50 idx 0]
(if (< total 4000)
(let [x (rand-int 120)
y (rand-int 80)
s (rand-nth [:s :m :l])]
(recur (str result
(format ".homepage__animated-hr__bg__cloud%s\n width: %spx; height: %spx; left: %spx; top: %spx;\n"
idx
(case s
:s 34
:m 68
:l 136)
(case s
:s 17
:m 34
:l 68) (+ total x) y)) (+ total 180) (inc idx))) result))))
(def features-data
[{:description "Targeted promotion of your job post to relevant members"
:img "/images/homepage/feature01.svg"
:id :promo}
{:description "Easy-to-use tools to track and share applicants"
:img "/images/homepage/feature02.svg"
:id :tools}
{:description "Connect with GitHub and get contributions to your open source code"
:img "/images/homepage/feature03.svg"
:id :analytics}
{:description "Recommended candidates who are matched to your job"
:img "/images/homepage/feature04.svg"
:id :recommendations}])
(def integrations-data
[{:description "Get notifications in Slack when people apply to your jobs or start work on your Open Source issues"
:img "/images/company/slack-icon.svg"
:id :slack}
{:description "Applications automatically forwarded from WorksHub into Greenhouse"
:img "/images/company/greenhouse-icon.svg"
:id :greenhouse}
{:description "Keep your setup in Workable and let WorksHub push applications in real-time"
:img "/images/company/workable-icon.svg"
:id :workable}
{:description "Got your own ATS? Webhooks coming soon..."
:img "/images/company/webhooks.svg"
:id :webhooks}])
(def testimonials-data
[{:quote "WorksHub’s understanding of the market and other companies in the space has contributed heavily to our ability to develop and expand our team of Haskell and PureScript developers."
:source "Will Jones, VP of Engineering"
:logo "/images/homepage/logos/habito.png"}
{:quote "WorksHub has consistently been able to deliver an excellent standard of candidate and we have been successful in recruiting for our needs in the knowledge that they have a thorough understanding of our growth requirements."
:source "Chris Percival, CTO"
:logo "/images/homepage/logos/inchora.png"}
{:quote "WorksHub is not only able to consistently find top-tier talent in a hyper-competitive market for Engineering hires but also takes the time to deeply understand our business and culture to ensure a great match and a great interview experience. They are the best in the game!"
:source "Greg Ratner, CTO "
:logo "/images/homepage/logos/troops.svg"}
{:quote "WorksHub has been an invaluable way to find amazing talent. No one comes close to their depth of experience"
:source "Reuben, CTO"
:logo "/images/homepage/logos/avantstay.png"}
{:quote "WorksHub has enabled us to constantly find out the great talents of Scala and functional programming globally and keep us very competitive in Japan to grow rapidly."
:source "Ken Izumi, VP Engineering"
:logo "/images/homepage/logos/paidy.svg"}])
(defn header
[market get-started-route]
[:div.homepage__header
[:div.homepage__header__img
[:div.homepage__header__img-inner
[:img {:src "/images/homepage/header.svg"
:alt ""}]]]
[:div.homepage__header__copy
[:h1 (data/www-hero-title market)]
[:p data/www-hero-copy]
(link [:button.button
{:id "www-landing__hero"}
get-started-cta-string] get-started-route)]])
(defn features
[]
[:div.columns.homepage__features
(for [{:keys [description img id]} features-data]
^{:key id}
[:div.column.homepage__feature-column
[:div.homepage__feature-column__img-container
[:img {:src img
:alt ""}]]
[:div.homepage__feature-column__description-container
[:span description]]])])
(defn integrations
[]
[:div.columns.homepage__integrations
(for [{:keys [description img id]} integrations-data]
^{:key id}
[:div.column.homepage__integration-column
[:div.homepage__integration-column__img-container
[:img {:class (str "homepage__integration-column__img homepage__integration-column__img-" (name id))
:src img
:alt ""}]]
[:div.homepage__integration-column__description-container
[:span description]]])])
(defn walkthrough
[get-started-route]
[:div.homepage__walkthrough
[:h2 "READY FOR TAKE-OFF?"]
[:h3 "Let's get started!"]
one
[:div.columns.homepage__step
[:div.column.homepage__step__description
[:span "Create a " [:strong "profile page"] " for your company. Use this space to sell your company to our community. Tell them all about what you’re building and how"]
(link [:button.button.button--inverted
{:id "www-landing__walkthrough__companies"}
"View company profiles"] :companies)]
[:div.column.homepage__step__img.homepage__step__img--offset
[:img {:src "/images/homepage/walkthrough01.svg"
:alt ""}]]]
two
[:div.columns.homepage__step
[:div.column.homepage__step__description
[:span "Your " [:strong "real time dashboard"] " allows you to monitor the performance of each job, helping you get more applications and engage a wider community, building brand awareness"]
(link [:button.button.button--inverted
{:id "www-landing__walkthrough__features"}
"View all our packages"] :pricing)]
[:div.column.homepage__step__img
[:img {:src "/images/homepage/walkthrough02.svg"
:alt ""}]]]
three
[:div.columns.homepage__step
[:div.column.homepage__step__description
[:span "Have " [:strong "Open Source software"] " that need attention? Connect your company GitHub account and start building your talent pool and get more qualified applications."]]
[:div.column.homepage__step__img
[:img {:src "/images/homepage/walkthrough03.svg"
:alt ""}]]]
four
[:div.columns.homepage__step
[:div.column.homepage__step__description
[:span "Have a question along the way? We have a " [:strong "team of experts"] " that can help at every step of the process helping you make the best possible hire."]
(link [:button.button
{:id "www-landing__walkthrough__experts"}
get-started-cta-string] get-started-route)]
[:div.column.homepage__step__img
[:img {:src "/images/homepage/walkthrough04.svg"
:alt ""}]]]])
(defn animated-hr
[img-src img-class & [class]]
[:div
{:class (util/merge-classes "homepage__animated-hr"
(when (txt/not-blank class) class))}
[:div.homepage__animated-hr__bg
(for [idx (range num-clouds)]
[:img {:key (str "cloud" idx)
:src "/images/homepage/cloud.svg"
:class (str "homepage__animated-hr__bg__cloud" idx)
:alt ""}])]
[:div
{:class (util/merge-classes "homepage__animated-hr__img"
(when (txt/not-blank img-class) img-class))}
[:img {:src img-src
:alt ""}]]])
(defn testimonial
[{:keys [quote source logo]}]
[:div.homepage__testimonial_wrapper
{:key source}
[:div
{:class "homepage__testimonial"}
[:div.homepage__testimonial__quote "\"" quote "\""]
[:div.homepage__testimonial__source source]
[:div.homepage__testimonial__logo
[:img {:src logo
:alt ""}]]]])
(defn testimonials
([]
[testimonials :register])
([get-started-route]
[:div.homepage__testimonials
[:h3 "Join our satisfied worldwide clients"]
(link [:button.button.button__public
{:id "www-landing__testimonials"}
get-started-cta-string] get-started-route)
[carousel
(for [item testimonials-data]
[testimonial item])]]))
(defn looking-to-hire
[title hide-boxes? get-started-route]
[:div.homepage__looking-to-hire
[:div.homepage__looking-to-hire__header
[:h3 "Who are you looking to hire?"]
[:p (or title "Whether you’re looking to hire software developers or engineers, from front-end to full-stack to back-end, we’ve got you covered.")]]
(when-not hide-boxes?
[:ul.homepage__looking-to-hire__types
(for [{:keys [title description logo href]} (vals data/in-demand-hiring-data)]
^{:key title}
[:li.homepage__looking-to-hire__type
[:div.homepage__looking-to-hire__type__title (str "Hire " title)]
[:div.homepage__looking-to-hire__type__description description]
[:a.a--underlined.homepage__looking-to-hire__type__link
{:href href}
(str "Hire " title)]
[:div.homepage__looking-to-hire__type__logo
(icon logo)]])])
(link [:button.button
{:id "www-landing__looking-to-hire"}
get-started-cta-string] get-started-route)])
(defn homepage
([]
(homepage nil))
([{:keys [template]}]
(let [logged-in? (<sub [:user/logged-in?])
get-started-route (if logged-in? :register-company :register)
hiring-target (data/find-hiring-target template)]
[:div.homepage
[:div.homepage__top-content
[:div.homepage__top-content__container
(header (or (:title hiring-target)
(when template (txt/capitalize-words (str/lower-case (str/replace template #"[-_/]" " "))))
"software engineers")
get-started-route)]
[:div.homepage__companies-section
[:div.homepage__companies-section__container
(companies-section "Trusted by 300+ companies:")]]]
[:div.homepage__middle-content
[:div.homepage__middle-content__container
[:h2 "THE NEW STANDARD FOR TECHNICAL HIRING"]
[:h3 "How it works"]
(features)
[:h2 "INTEGRATIONS"]
(integrations)
[:div.homepage__feature-ctas
TODO ABOUT US PAGE
(link [:button.button
{:id "www-landing__barriers-try"}
get-started-cta-string] get-started-route)]]
[animated-hr "/images/homepage/rocket.svg" "homepage__animated-hr__rocket homepage__animated-hr__rocket--start"]
[hiw/stats :company false get-started-route]
[animated-hr "/images/homepage/rocket.svg" "homepage__animated-hr__rocket homepage__animated-hr__rocket--mid"]
[animated-hr "/images/homepage/rocket.svg" "homepage__animated-hr__rocket homepage__animated-hr__rocket--end"]
[:div.homepage__middle-content__container
(walkthrough get-started-route)]
[animated-hr "/images/homepage/globe.svg" "homepage__animated-hr__globe" "homepage__animated-hr__globe-wrapper"]
[:div.homepage__middle-content__container
[testimonials get-started-route]]
[animated-hr nil nil]]
[:div.homepage__bottom-content
[:div.homepage__bottom-content__container
(looking-to-hire (:description2 hiring-target) (boolean template) get-started-route)]]])))
| null | https://raw.githubusercontent.com/WorksHub/client/e05a66f512bd37d0c3372e3d305fdfaa43290c79/common/src/wh/components/www_homepage.cljc | clojure | (ns wh.components.www-homepage
(:require
#?(:cljs [reagent.core :as r])
[clojure.string :as str]
[wh.common.data :as data]
[wh.common.text :as txt]
[wh.components.carousel :refer [carousel]]
[wh.components.common :refer [companies-section link]]
[wh.components.icons :refer [icon]]
[wh.how-it-works.views :as hiw]
[wh.re-frame.subs :refer [<sub]]
[wh.util :as util]))
(def num-clouds 23)
(def get-started-cta-string "Get Started for Free")
(comment
"Used to generate the SASS for clouds"
(println
(loop [result "" total -50 idx 0]
(if (< total 4000)
(let [x (rand-int 120)
y (rand-int 80)
s (rand-nth [:s :m :l])]
(recur (str result
(format ".homepage__animated-hr__bg__cloud%s\n width: %spx; height: %spx; left: %spx; top: %spx;\n"
idx
(case s
:s 34
:m 68
:l 136)
(case s
:s 17
:m 34
:l 68) (+ total x) y)) (+ total 180) (inc idx))) result))))
(def features-data
[{:description "Targeted promotion of your job post to relevant members"
:img "/images/homepage/feature01.svg"
:id :promo}
{:description "Easy-to-use tools to track and share applicants"
:img "/images/homepage/feature02.svg"
:id :tools}
{:description "Connect with GitHub and get contributions to your open source code"
:img "/images/homepage/feature03.svg"
:id :analytics}
{:description "Recommended candidates who are matched to your job"
:img "/images/homepage/feature04.svg"
:id :recommendations}])
(def integrations-data
[{:description "Get notifications in Slack when people apply to your jobs or start work on your Open Source issues"
:img "/images/company/slack-icon.svg"
:id :slack}
{:description "Applications automatically forwarded from WorksHub into Greenhouse"
:img "/images/company/greenhouse-icon.svg"
:id :greenhouse}
{:description "Keep your setup in Workable and let WorksHub push applications in real-time"
:img "/images/company/workable-icon.svg"
:id :workable}
{:description "Got your own ATS? Webhooks coming soon..."
:img "/images/company/webhooks.svg"
:id :webhooks}])
(def testimonials-data
[{:quote "WorksHub’s understanding of the market and other companies in the space has contributed heavily to our ability to develop and expand our team of Haskell and PureScript developers."
:source "Will Jones, VP of Engineering"
:logo "/images/homepage/logos/habito.png"}
{:quote "WorksHub has consistently been able to deliver an excellent standard of candidate and we have been successful in recruiting for our needs in the knowledge that they have a thorough understanding of our growth requirements."
:source "Chris Percival, CTO"
:logo "/images/homepage/logos/inchora.png"}
{:quote "WorksHub is not only able to consistently find top-tier talent in a hyper-competitive market for Engineering hires but also takes the time to deeply understand our business and culture to ensure a great match and a great interview experience. They are the best in the game!"
:source "Greg Ratner, CTO "
:logo "/images/homepage/logos/troops.svg"}
{:quote "WorksHub has been an invaluable way to find amazing talent. No one comes close to their depth of experience"
:source "Reuben, CTO"
:logo "/images/homepage/logos/avantstay.png"}
{:quote "WorksHub has enabled us to constantly find out the great talents of Scala and functional programming globally and keep us very competitive in Japan to grow rapidly."
:source "Ken Izumi, VP Engineering"
:logo "/images/homepage/logos/paidy.svg"}])
(defn header
[market get-started-route]
[:div.homepage__header
[:div.homepage__header__img
[:div.homepage__header__img-inner
[:img {:src "/images/homepage/header.svg"
:alt ""}]]]
[:div.homepage__header__copy
[:h1 (data/www-hero-title market)]
[:p data/www-hero-copy]
(link [:button.button
{:id "www-landing__hero"}
get-started-cta-string] get-started-route)]])
(defn features
[]
[:div.columns.homepage__features
(for [{:keys [description img id]} features-data]
^{:key id}
[:div.column.homepage__feature-column
[:div.homepage__feature-column__img-container
[:img {:src img
:alt ""}]]
[:div.homepage__feature-column__description-container
[:span description]]])])
(defn integrations
[]
[:div.columns.homepage__integrations
(for [{:keys [description img id]} integrations-data]
^{:key id}
[:div.column.homepage__integration-column
[:div.homepage__integration-column__img-container
[:img {:class (str "homepage__integration-column__img homepage__integration-column__img-" (name id))
:src img
:alt ""}]]
[:div.homepage__integration-column__description-container
[:span description]]])])
(defn walkthrough
[get-started-route]
[:div.homepage__walkthrough
[:h2 "READY FOR TAKE-OFF?"]
[:h3 "Let's get started!"]
one
[:div.columns.homepage__step
[:div.column.homepage__step__description
[:span "Create a " [:strong "profile page"] " for your company. Use this space to sell your company to our community. Tell them all about what you’re building and how"]
(link [:button.button.button--inverted
{:id "www-landing__walkthrough__companies"}
"View company profiles"] :companies)]
[:div.column.homepage__step__img.homepage__step__img--offset
[:img {:src "/images/homepage/walkthrough01.svg"
:alt ""}]]]
two
[:div.columns.homepage__step
[:div.column.homepage__step__description
[:span "Your " [:strong "real time dashboard"] " allows you to monitor the performance of each job, helping you get more applications and engage a wider community, building brand awareness"]
(link [:button.button.button--inverted
{:id "www-landing__walkthrough__features"}
"View all our packages"] :pricing)]
[:div.column.homepage__step__img
[:img {:src "/images/homepage/walkthrough02.svg"
:alt ""}]]]
three
[:div.columns.homepage__step
[:div.column.homepage__step__description
[:span "Have " [:strong "Open Source software"] " that need attention? Connect your company GitHub account and start building your talent pool and get more qualified applications."]]
[:div.column.homepage__step__img
[:img {:src "/images/homepage/walkthrough03.svg"
:alt ""}]]]
four
[:div.columns.homepage__step
[:div.column.homepage__step__description
[:span "Have a question along the way? We have a " [:strong "team of experts"] " that can help at every step of the process helping you make the best possible hire."]
(link [:button.button
{:id "www-landing__walkthrough__experts"}
get-started-cta-string] get-started-route)]
[:div.column.homepage__step__img
[:img {:src "/images/homepage/walkthrough04.svg"
:alt ""}]]]])
(defn animated-hr
[img-src img-class & [class]]
[:div
{:class (util/merge-classes "homepage__animated-hr"
(when (txt/not-blank class) class))}
[:div.homepage__animated-hr__bg
(for [idx (range num-clouds)]
[:img {:key (str "cloud" idx)
:src "/images/homepage/cloud.svg"
:class (str "homepage__animated-hr__bg__cloud" idx)
:alt ""}])]
[:div
{:class (util/merge-classes "homepage__animated-hr__img"
(when (txt/not-blank img-class) img-class))}
[:img {:src img-src
:alt ""}]]])
(defn testimonial
[{:keys [quote source logo]}]
[:div.homepage__testimonial_wrapper
{:key source}
[:div
{:class "homepage__testimonial"}
[:div.homepage__testimonial__quote "\"" quote "\""]
[:div.homepage__testimonial__source source]
[:div.homepage__testimonial__logo
[:img {:src logo
:alt ""}]]]])
(defn testimonials
([]
[testimonials :register])
([get-started-route]
[:div.homepage__testimonials
[:h3 "Join our satisfied worldwide clients"]
(link [:button.button.button__public
{:id "www-landing__testimonials"}
get-started-cta-string] get-started-route)
[carousel
(for [item testimonials-data]
[testimonial item])]]))
(defn looking-to-hire
[title hide-boxes? get-started-route]
[:div.homepage__looking-to-hire
[:div.homepage__looking-to-hire__header
[:h3 "Who are you looking to hire?"]
[:p (or title "Whether you’re looking to hire software developers or engineers, from front-end to full-stack to back-end, we’ve got you covered.")]]
(when-not hide-boxes?
[:ul.homepage__looking-to-hire__types
(for [{:keys [title description logo href]} (vals data/in-demand-hiring-data)]
^{:key title}
[:li.homepage__looking-to-hire__type
[:div.homepage__looking-to-hire__type__title (str "Hire " title)]
[:div.homepage__looking-to-hire__type__description description]
[:a.a--underlined.homepage__looking-to-hire__type__link
{:href href}
(str "Hire " title)]
[:div.homepage__looking-to-hire__type__logo
(icon logo)]])])
(link [:button.button
{:id "www-landing__looking-to-hire"}
get-started-cta-string] get-started-route)])
(defn homepage
([]
(homepage nil))
([{:keys [template]}]
(let [logged-in? (<sub [:user/logged-in?])
get-started-route (if logged-in? :register-company :register)
hiring-target (data/find-hiring-target template)]
[:div.homepage
[:div.homepage__top-content
[:div.homepage__top-content__container
(header (or (:title hiring-target)
(when template (txt/capitalize-words (str/lower-case (str/replace template #"[-_/]" " "))))
"software engineers")
get-started-route)]
[:div.homepage__companies-section
[:div.homepage__companies-section__container
(companies-section "Trusted by 300+ companies:")]]]
[:div.homepage__middle-content
[:div.homepage__middle-content__container
[:h2 "THE NEW STANDARD FOR TECHNICAL HIRING"]
[:h3 "How it works"]
(features)
[:h2 "INTEGRATIONS"]
(integrations)
[:div.homepage__feature-ctas
TODO ABOUT US PAGE
(link [:button.button
{:id "www-landing__barriers-try"}
get-started-cta-string] get-started-route)]]
[animated-hr "/images/homepage/rocket.svg" "homepage__animated-hr__rocket homepage__animated-hr__rocket--start"]
[hiw/stats :company false get-started-route]
[animated-hr "/images/homepage/rocket.svg" "homepage__animated-hr__rocket homepage__animated-hr__rocket--mid"]
[animated-hr "/images/homepage/rocket.svg" "homepage__animated-hr__rocket homepage__animated-hr__rocket--end"]
[:div.homepage__middle-content__container
(walkthrough get-started-route)]
[animated-hr "/images/homepage/globe.svg" "homepage__animated-hr__globe" "homepage__animated-hr__globe-wrapper"]
[:div.homepage__middle-content__container
[testimonials get-started-route]]
[animated-hr nil nil]]
[:div.homepage__bottom-content
[:div.homepage__bottom-content__container
(looking-to-hire (:description2 hiring-target) (boolean template) get-started-route)]]])))
| |
412d7c6eb327488ee808da2c748363060585be5169062facb67fb12370f61e02 | binsec/haunted | relse_utils.mli | type assignment_t =
| Var of string * Size.Bit.t * Rel_expr.rel_bv (* name, value *)
| Mem of Dba.size * Rel_expr.rel_bv * Rel_expr.rel_bv (* size, index, value *)
(* TODO: change to functions ? *)
32 bits
32 bits
8
val is_sse : unit -> bool
val is_self_composed : unit -> bool
val is_relational : unit -> bool
val get_main_symbol: unit -> Loader.Symbol.t
val int_to_bitvector : int -> Bitvector.t
val dba_constant_from_int: int -> Dba.Expr.t
* [ is_loadable addr ] Returns true if [ addr ] it is in a read - only
section or a section specified in cmdline
section or a section specified in cmdline *)
val is_loadable : Bitvector.t -> bool
(** Detect if the instruction is a conditional jump.
Heuristic to detect conditional jump: has multiple outer targets. **)
val is_conditional_jump: Instruction.t -> bool
(** Detect if the instruction is a return statement **)
val is_return: Instruction.t -> bool
(** [read_bitvector bv size] Reads [size] bytes in the image of the
executable at address [bv] *)
val read_bitvector : Bitvector.t -> int -> Bitvector.t
(** [temp_file ()] create a new temporary file *)
val temp_file : unit -> string
(** [mk_var_name basename idx] *)
val mk_var_name : string -> int -> string
type 'a formula_status =
| Valid
| Unsat
| Sat of 'a
| Unknown of 'a
val get_formula: Formula.bl_term formula_status -> Formula.bl_term
val solving_attempt : Formula.bl_term -> Formula.bl_term formula_status
val update_pc: Formula.bl_term Rel_expr.t ->
Formula.bl_term formula_status -> Formula.bl_term formula_status
type comparison_type = Equal | Distinct | NotComparable
val compare_bv : Formula.bv_term -> Formula.bv_term -> comparison_type
(* val normalize_simple : Formula.bv_term -> Formula.bv_term -> Formula.bv_term
* val normalize_rel : Formula.bv_term Rel_expr.t-> Formula.bv_term Rel_expr.t -> Formula.bv_term Rel_expr.t *)
(** Keep track of a list of addresses *)
module AddressSet : sig
type t
val size : t -> int
val create : name:string -> t
val add : Virtual_address.t -> t -> unit
val pp_address_trace_to_file : t -> int -> unit
(** [find addr al] Returns true if [addr] is in the address list [addr] *)
val find: Virtual_address.t -> t -> bool
end
module AddressList : sig
type t
val create : name:string -> t
val extend : Dba_types.Statement.t -> t -> t
val pp_address_trace_to_file : t -> int -> unit
(** [find addr al] Returns true if [addr] is in the address list [addr] *)
val find: Dba_types.Statement.t -> t -> bool
end
module Spectre : sig
val unresolved_mem_access: 'a Rel_expr.t -> int -> bool
end
module F : sig
val word_size: unit -> int ;;
val var: string -> Formula.sort -> Formula.var ;;
val def: Formula.term -> Formula.var -> Formula.def ;;
val decl: Formula.var -> Formula.decl ;;
val mk_initial_name: high:bool -> string -> string Rel_expr.t ;;
val rel_name: high:bool -> string -> string Rel_expr.t ;;
val with_index: string -> int -> string ;;
val mk_bv: Formula.sort -> string -> Formula.bv_term ;;
val mk_bl: string -> Formula.bl_term ;;
val memory_name: string ;;
val current_mem: high:bool -> int -> string Rel_expr.t ;;
val memory_type: unit -> Formula.sort ;;
val memory_term: string -> Formula.ax_term ;;
val current_pc: int -> string ;;
val normalize: string Rel_expr.t ->
Formula.bv_term Rel_expr.t -> Formula.sort -> Formula.bv_term Rel_expr.t ;;
val fml_add_entry: Formula.formula -> Formula.entry -> Formula.formula ;;
val fml_assign: Formula.sort -> string -> Formula.term -> Formula.formula -> Formula.formula ;;
end
| null | https://raw.githubusercontent.com/binsec/haunted/7ffc5f4072950fe138f53fe953ace98fff181c73/src/relse/relse_utils.mli | ocaml | name, value
size, index, value
TODO: change to functions ?
* Detect if the instruction is a conditional jump.
Heuristic to detect conditional jump: has multiple outer targets. *
* Detect if the instruction is a return statement *
* [read_bitvector bv size] Reads [size] bytes in the image of the
executable at address [bv]
* [temp_file ()] create a new temporary file
* [mk_var_name basename idx]
val normalize_simple : Formula.bv_term -> Formula.bv_term -> Formula.bv_term
* val normalize_rel : Formula.bv_term Rel_expr.t-> Formula.bv_term Rel_expr.t -> Formula.bv_term Rel_expr.t
* Keep track of a list of addresses
* [find addr al] Returns true if [addr] is in the address list [addr]
* [find addr al] Returns true if [addr] is in the address list [addr] | type assignment_t =
32 bits
32 bits
8
val is_sse : unit -> bool
val is_self_composed : unit -> bool
val is_relational : unit -> bool
val get_main_symbol: unit -> Loader.Symbol.t
val int_to_bitvector : int -> Bitvector.t
val dba_constant_from_int: int -> Dba.Expr.t
* [ is_loadable addr ] Returns true if [ addr ] it is in a read - only
section or a section specified in cmdline
section or a section specified in cmdline *)
val is_loadable : Bitvector.t -> bool
val is_conditional_jump: Instruction.t -> bool
val is_return: Instruction.t -> bool
val read_bitvector : Bitvector.t -> int -> Bitvector.t
val temp_file : unit -> string
val mk_var_name : string -> int -> string
type 'a formula_status =
| Valid
| Unsat
| Sat of 'a
| Unknown of 'a
val get_formula: Formula.bl_term formula_status -> Formula.bl_term
val solving_attempt : Formula.bl_term -> Formula.bl_term formula_status
val update_pc: Formula.bl_term Rel_expr.t ->
Formula.bl_term formula_status -> Formula.bl_term formula_status
type comparison_type = Equal | Distinct | NotComparable
val compare_bv : Formula.bv_term -> Formula.bv_term -> comparison_type
module AddressSet : sig
type t
val size : t -> int
val create : name:string -> t
val add : Virtual_address.t -> t -> unit
val pp_address_trace_to_file : t -> int -> unit
val find: Virtual_address.t -> t -> bool
end
module AddressList : sig
type t
val create : name:string -> t
val extend : Dba_types.Statement.t -> t -> t
val pp_address_trace_to_file : t -> int -> unit
val find: Dba_types.Statement.t -> t -> bool
end
module Spectre : sig
val unresolved_mem_access: 'a Rel_expr.t -> int -> bool
end
module F : sig
val word_size: unit -> int ;;
val var: string -> Formula.sort -> Formula.var ;;
val def: Formula.term -> Formula.var -> Formula.def ;;
val decl: Formula.var -> Formula.decl ;;
val mk_initial_name: high:bool -> string -> string Rel_expr.t ;;
val rel_name: high:bool -> string -> string Rel_expr.t ;;
val with_index: string -> int -> string ;;
val mk_bv: Formula.sort -> string -> Formula.bv_term ;;
val mk_bl: string -> Formula.bl_term ;;
val memory_name: string ;;
val current_mem: high:bool -> int -> string Rel_expr.t ;;
val memory_type: unit -> Formula.sort ;;
val memory_term: string -> Formula.ax_term ;;
val current_pc: int -> string ;;
val normalize: string Rel_expr.t ->
Formula.bv_term Rel_expr.t -> Formula.sort -> Formula.bv_term Rel_expr.t ;;
val fml_add_entry: Formula.formula -> Formula.entry -> Formula.formula ;;
val fml_assign: Formula.sort -> string -> Formula.term -> Formula.formula -> Formula.formula ;;
end
|
6ba12aa383da8de8e66e90c656d2850369add5dea4789991db26bf818787542b | Helium4Haskell/helium | CatchBug.hs | main = catch (do { [x] <- return [1, 2, 3]; return () })
(\err -> putStr "The exception has been caught")
| null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/runtimeerrors/CatchBug.hs | haskell | main = catch (do { [x] <- return [1, 2, 3]; return () })
(\err -> putStr "The exception has been caught")
| |
0fb2c3bac98640de514f4490453786545406b0c5d3da0337e87b35775f80f3b7 | lambdaclass/riak_core_tutorial | rc_example_app.erl | -module(rc_example_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
ok = riak_core:register([{vnode_module, rc_example_vnode}]),
ok = riak_core_node_watcher:service_up(rc_example, self()),
rc_example_sup:start_link().
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/lambdaclass/riak_core_tutorial/45245d92e080032696e6cee1dbe5741abd7a986d/src/rc_example_app.erl | erlang | Application callbacks | -module(rc_example_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
ok = riak_core:register([{vnode_module, rc_example_vnode}]),
ok = riak_core_node_watcher:service_up(rc_example, self()),
rc_example_sup:start_link().
stop(_State) ->
ok.
|
2c5da7084606a1be9343475f59e84c193551b98ac5164603609038dae947cc48 | vaclavsvejcar/headroom | UpdateCopyrightSpec.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StrictData #-}
# LANGUAGE NoImplicitPrelude #
module Headroom.PostProcess.UpdateCopyrightSpec
( spec
)
where
import Headroom.Data.Has (Has (..))
import Headroom.Data.Text (fromLines)
import Headroom.PostProcess (postProcess)
import Headroom.PostProcess.UpdateCopyright
import Headroom.Types (CurrentYear (..))
import RIO
import Test.Hspec
spec :: Spec
spec = do
let currYear = CurrentYear 2020
describe "updateCopyright" $ do
it "updates all authors when such mode selected" $ do
let sample =
fromLines
[ "Copyright (c) 2019 1st Author"
, "Copyright (c) 2017-2019 2nd Author"
]
expected =
fromLines
[ "Copyright (c) 2019-2020 1st Author"
, "Copyright (c) 2017-2020 2nd Author"
]
testEnv = TestEnv currYear UpdateAllAuthors
postProcess updateCopyright testEnv sample `shouldBe` expected
it "updates only selected authors in such mode" $ do
let sample =
fromLines
[ "Copyright (c) 2019 1st Author"
, "Copyright (c) 2017-2019 2nd Author"
]
expected =
fromLines
[ "Copyright (c) 2019 1st Author"
, "Copyright (c) 2017-2020 2nd Author"
]
mode = UpdateSelectedAuthors . SelectedAuthors $ "2nd Author" :| []
testEnv = TestEnv currYear mode
postProcess updateCopyright testEnv sample `shouldBe` expected
describe "updateYears" $ do
it "does nothing on up-to-date year" $ do
let sample = "Copyright (c) 2020"
updateYears currYear sample `shouldBe` sample
it "does nothing if year is higher than current year" $ do
let sample = "Copyright (c) 2021"
updateYears currYear sample `shouldBe` sample
it "does nothing on up-to-date year range" $ do
let sample = "Copyright (c) 2018-2020"
updateYears currYear sample `shouldBe` sample
it "does nothing if second year range is higher than current year" $ do
let sample = "Copyright (c) 2018-2021"
updateYears currYear sample `shouldBe` sample
it "does nothing if entire year range is higher than current year" $ do
let sample = "Copyright (c) 2021-2023"
updateYears currYear sample `shouldBe` sample
it "updates outdated year" $ do
let sample = "Copyright (c) 2019"
expected = "Copyright (c) 2019-2020"
updateYears currYear sample `shouldBe` expected
it "updates outdated year range" $ do
let sample = "Copyright (c) 2017-2019"
expected = "Copyright (c) 2017-2020"
updateYears currYear sample `shouldBe` expected
it "updates complex multi-line text" $ do
let sample =
fromLines
[ "Copyright (c) 2019"
, "Copyright (c) 2020"
, "Copyright (c) 2019-2020"
, "Copyright (c) 2017-2019"
]
expected =
fromLines
[ "Copyright (c) 2019-2020"
, "Copyright (c) 2020"
, "Copyright (c) 2019-2020"
, "Copyright (c) 2017-2020"
]
updateYears currYear sample `shouldBe` expected
------------------------------- TEST DATA TYPES ------------------------------
data TestEnv = TestEnv
{ teCurrentYear :: CurrentYear
, teMode :: UpdateCopyrightMode
}
deriving (Eq, Show)
instance Has CurrentYear TestEnv where
hasLens = lens teCurrentYear (\x y -> x{teCurrentYear = y})
instance Has UpdateCopyrightMode TestEnv where
hasLens = lens teMode (\x y -> x{teMode = y})
| null | https://raw.githubusercontent.com/vaclavsvejcar/headroom/3b20a89568248259d59f83f274f60f6e13d16f93/test/Headroom/PostProcess/UpdateCopyrightSpec.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
----------------------------- TEST DATA TYPES ------------------------------ | # LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
module Headroom.PostProcess.UpdateCopyrightSpec
( spec
)
where
import Headroom.Data.Has (Has (..))
import Headroom.Data.Text (fromLines)
import Headroom.PostProcess (postProcess)
import Headroom.PostProcess.UpdateCopyright
import Headroom.Types (CurrentYear (..))
import RIO
import Test.Hspec
spec :: Spec
spec = do
let currYear = CurrentYear 2020
describe "updateCopyright" $ do
it "updates all authors when such mode selected" $ do
let sample =
fromLines
[ "Copyright (c) 2019 1st Author"
, "Copyright (c) 2017-2019 2nd Author"
]
expected =
fromLines
[ "Copyright (c) 2019-2020 1st Author"
, "Copyright (c) 2017-2020 2nd Author"
]
testEnv = TestEnv currYear UpdateAllAuthors
postProcess updateCopyright testEnv sample `shouldBe` expected
it "updates only selected authors in such mode" $ do
let sample =
fromLines
[ "Copyright (c) 2019 1st Author"
, "Copyright (c) 2017-2019 2nd Author"
]
expected =
fromLines
[ "Copyright (c) 2019 1st Author"
, "Copyright (c) 2017-2020 2nd Author"
]
mode = UpdateSelectedAuthors . SelectedAuthors $ "2nd Author" :| []
testEnv = TestEnv currYear mode
postProcess updateCopyright testEnv sample `shouldBe` expected
describe "updateYears" $ do
it "does nothing on up-to-date year" $ do
let sample = "Copyright (c) 2020"
updateYears currYear sample `shouldBe` sample
it "does nothing if year is higher than current year" $ do
let sample = "Copyright (c) 2021"
updateYears currYear sample `shouldBe` sample
it "does nothing on up-to-date year range" $ do
let sample = "Copyright (c) 2018-2020"
updateYears currYear sample `shouldBe` sample
it "does nothing if second year range is higher than current year" $ do
let sample = "Copyright (c) 2018-2021"
updateYears currYear sample `shouldBe` sample
it "does nothing if entire year range is higher than current year" $ do
let sample = "Copyright (c) 2021-2023"
updateYears currYear sample `shouldBe` sample
it "updates outdated year" $ do
let sample = "Copyright (c) 2019"
expected = "Copyright (c) 2019-2020"
updateYears currYear sample `shouldBe` expected
it "updates outdated year range" $ do
let sample = "Copyright (c) 2017-2019"
expected = "Copyright (c) 2017-2020"
updateYears currYear sample `shouldBe` expected
it "updates complex multi-line text" $ do
let sample =
fromLines
[ "Copyright (c) 2019"
, "Copyright (c) 2020"
, "Copyright (c) 2019-2020"
, "Copyright (c) 2017-2019"
]
expected =
fromLines
[ "Copyright (c) 2019-2020"
, "Copyright (c) 2020"
, "Copyright (c) 2019-2020"
, "Copyright (c) 2017-2020"
]
updateYears currYear sample `shouldBe` expected
data TestEnv = TestEnv
{ teCurrentYear :: CurrentYear
, teMode :: UpdateCopyrightMode
}
deriving (Eq, Show)
instance Has CurrentYear TestEnv where
hasLens = lens teCurrentYear (\x y -> x{teCurrentYear = y})
instance Has UpdateCopyrightMode TestEnv where
hasLens = lens teMode (\x y -> x{teMode = y})
|
9e80e93522836481bcf3967a65e767eb4ede3839215b67d52b76123441d4676a | keithfancher/tvmv | Rename.hs | module Exec.Rename
( RenameResult (..),
executeRename,
getOp,
makeOpRelative,
makeResultRelative,
)
where
import Control.Exception (try)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Writer.Class (MonadWriter, tell)
import Domain.Rename (RenameOp (..))
import System.Directory (makeRelativeToCurrentDirectory)
import System.Directory qualified as Dir
-- Not quite an Either, since we want the op to exist even in failure cases.
data RenameResult = Success RenameOp | Failure RenameOp IOError
deriving (Eq, Show)
-- Actually rename the files on the file system. Accumulate a "log" of rename
-- results.
executeRename :: (MonadIO m, MonadWriter [RenameResult] m) => [RenameOp] -> m ()
executeRename = mapM_ executeRenameSingle
-- Rename a single file on the file system. The result of the operation,
-- whether a success or failure, will be added to the Writer values for later
-- logging.
executeRenameSingle :: (MonadIO m, MonadWriter [RenameResult] m) => RenameOp -> m ()
executeRenameSingle renameOp = do
renameResults <- tryRename (oldPath renameOp) (newPath renameOp)
tell [mkResult renameOp renameResults]
tryRename :: MonadIO m => FilePath -> FilePath -> m (Either IOError ())
tryRename old new = liftIO $ try (Dir.renameFile old new)
mkResult :: RenameOp -> Either IOError () -> RenameResult
mkResult o (Left err) = Failure o err
mkResult o (Right _) = Success o
Replace the paths in a with paths relative to the current directory .
makeOpRelative :: MonadIO m => RenameOp -> m RenameOp
makeOpRelative (RenameOp old new) = do
relativeOld <- liftIO $ makeRelativeToCurrentDirectory old
relativeNew <- liftIO $ makeRelativeToCurrentDirectory new
return RenameOp {oldPath = relativeOld, newPath = relativeNew}
makeResultRelative :: MonadIO m => RenameResult -> m RenameResult
makeResultRelative result = do
relativeOp <- makeOpRelative (getOp result)
return $ setOp result relativeOp
Gets op from a RenameResult .
getOp :: RenameResult -> RenameOp
getOp (Success op) = op
getOp (Failure op _) = op
Updates the op in a RenameResult .
setOp :: RenameResult -> RenameOp -> RenameResult
setOp (Success _) newOp = Success newOp
setOp (Failure _ err) newOp = Failure newOp err
| null | https://raw.githubusercontent.com/keithfancher/tvmv/62e500e5dbc981ae7baeea8e6608e0db3fea21ef/src/Exec/Rename.hs | haskell | Not quite an Either, since we want the op to exist even in failure cases.
Actually rename the files on the file system. Accumulate a "log" of rename
results.
Rename a single file on the file system. The result of the operation,
whether a success or failure, will be added to the Writer values for later
logging. | module Exec.Rename
( RenameResult (..),
executeRename,
getOp,
makeOpRelative,
makeResultRelative,
)
where
import Control.Exception (try)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Writer.Class (MonadWriter, tell)
import Domain.Rename (RenameOp (..))
import System.Directory (makeRelativeToCurrentDirectory)
import System.Directory qualified as Dir
data RenameResult = Success RenameOp | Failure RenameOp IOError
deriving (Eq, Show)
executeRename :: (MonadIO m, MonadWriter [RenameResult] m) => [RenameOp] -> m ()
executeRename = mapM_ executeRenameSingle
executeRenameSingle :: (MonadIO m, MonadWriter [RenameResult] m) => RenameOp -> m ()
executeRenameSingle renameOp = do
renameResults <- tryRename (oldPath renameOp) (newPath renameOp)
tell [mkResult renameOp renameResults]
tryRename :: MonadIO m => FilePath -> FilePath -> m (Either IOError ())
tryRename old new = liftIO $ try (Dir.renameFile old new)
mkResult :: RenameOp -> Either IOError () -> RenameResult
mkResult o (Left err) = Failure o err
mkResult o (Right _) = Success o
Replace the paths in a with paths relative to the current directory .
makeOpRelative :: MonadIO m => RenameOp -> m RenameOp
makeOpRelative (RenameOp old new) = do
relativeOld <- liftIO $ makeRelativeToCurrentDirectory old
relativeNew <- liftIO $ makeRelativeToCurrentDirectory new
return RenameOp {oldPath = relativeOld, newPath = relativeNew}
makeResultRelative :: MonadIO m => RenameResult -> m RenameResult
makeResultRelative result = do
relativeOp <- makeOpRelative (getOp result)
return $ setOp result relativeOp
Gets op from a RenameResult .
getOp :: RenameResult -> RenameOp
getOp (Success op) = op
getOp (Failure op _) = op
Updates the op in a RenameResult .
setOp :: RenameResult -> RenameOp -> RenameResult
setOp (Success _) newOp = Success newOp
setOp (Failure _ err) newOp = Failure newOp err
|
321f67ba081158f3a6fe59a8a47f706134b9d731662a2fa6c1ccb355b7fae884 | luminus-framework/luminus-migrations | core.clj | (ns luminus-migrations.core
(:require
[clojure.set :refer [rename-keys]]
[clojure.string :refer [join]]
[migratus.core :as migratus]
[luminus-migrations.util :refer [to-jdbc-uri]]))
(defn- parse-ids [args]
(map #(Long/parseLong %) (rest args)))
(defn- parse-url
([opts] (parse-url opts identity))
([{:keys [database-url] :as opts} transformation]
(if database-url
(-> opts
(dissoc :database-url)
(assoc-in [:db :connection-uri]
(to-jdbc-uri (transformation database-url))))
opts)))
(defn- remove-db-name [url]
(when url
(clojure.string/replace url #"(\/\/.*\/)(.*)(\?)" "$1$2$3")))
(def migrations
{"reset"
(fn [config _]
(migratus/reset config))
"destroy"
(fn [config args]
(if (> (count args) 1)
(migratus/destroy config (second args))
(migratus/destroy config)))
"pending"
(fn [config _]
(migratus/pending-list config))
"migrate"
(fn [config args]
(if (> (count args) 1)
(apply migratus/up config (parse-ids args))
(migratus/migrate config)))
"rollback"
(fn [config args]
(if (> (count args) 1)
(apply migratus/down config (parse-ids args))
(migratus/rollback config)))})
(defn migration? [[arg]]
(contains? (set (keys migrations)) arg))
(defn init
"wrapper around migratus/init
initializes the database using the script specified by the :init-script key
opts - map of options specifying the database configuration.
supported options are:
:db - Migratus db config map
:init-script - SQL script that initialized the database
:database-url - URL of the application database
:migration-dir - string specifying the directory of the migration files
:migration-table-name - string specifying the migration table name"
[opts]
(let [config (merge {:store :database} (parse-url opts remove-db-name))]
(migratus/init config)))
(defn create
"Wrapper around migratus/create.
Creates a migration file with generated timestamp-based migration id.
name - string, name of migration to be created.
opts - map of options specifying the database configuration.
supported options are:
:db - Migratus db config map
:database-url - URL of the application database
:migration-dir - string specifying the directory of the migration files
:migration-table-name - string specifying the migration table name
type - keyword, migration type (e.g. :sql and :edn for code-based migrations)"
[name opts & [type]]
(let [config (merge {:store :database} (parse-url opts))]
(migratus/create config name type)))
(defn migrate
"args - vector of arguments, e.g: [\"migrate\" \"201506104553\"]
opts - map of options specifying the database configuration.
supported options are:
:database-url - URL of the application database
:migration-dir - string specifying the directory of the migration files
:migration-table-name - string specifying the migration table name"
[args opts]
(when-not (migration? args)
(throw
(IllegalArgumentException.
(str "unrecognized option: " (first args)
", valid options are:" (join ", " (keys migrations))))))
(let [config (merge {:store :database} (parse-url opts))]
((get migrations (first args)) config args)))
| null | https://raw.githubusercontent.com/luminus-framework/luminus-migrations/9f9437a9a817c297bdfb9209a64cde290c7f06c0/src/luminus_migrations/core.clj | clojure | (ns luminus-migrations.core
(:require
[clojure.set :refer [rename-keys]]
[clojure.string :refer [join]]
[migratus.core :as migratus]
[luminus-migrations.util :refer [to-jdbc-uri]]))
(defn- parse-ids [args]
(map #(Long/parseLong %) (rest args)))
(defn- parse-url
([opts] (parse-url opts identity))
([{:keys [database-url] :as opts} transformation]
(if database-url
(-> opts
(dissoc :database-url)
(assoc-in [:db :connection-uri]
(to-jdbc-uri (transformation database-url))))
opts)))
(defn- remove-db-name [url]
(when url
(clojure.string/replace url #"(\/\/.*\/)(.*)(\?)" "$1$2$3")))
(def migrations
{"reset"
(fn [config _]
(migratus/reset config))
"destroy"
(fn [config args]
(if (> (count args) 1)
(migratus/destroy config (second args))
(migratus/destroy config)))
"pending"
(fn [config _]
(migratus/pending-list config))
"migrate"
(fn [config args]
(if (> (count args) 1)
(apply migratus/up config (parse-ids args))
(migratus/migrate config)))
"rollback"
(fn [config args]
(if (> (count args) 1)
(apply migratus/down config (parse-ids args))
(migratus/rollback config)))})
(defn migration? [[arg]]
(contains? (set (keys migrations)) arg))
(defn init
"wrapper around migratus/init
initializes the database using the script specified by the :init-script key
opts - map of options specifying the database configuration.
supported options are:
:db - Migratus db config map
:init-script - SQL script that initialized the database
:database-url - URL of the application database
:migration-dir - string specifying the directory of the migration files
:migration-table-name - string specifying the migration table name"
[opts]
(let [config (merge {:store :database} (parse-url opts remove-db-name))]
(migratus/init config)))
(defn create
"Wrapper around migratus/create.
Creates a migration file with generated timestamp-based migration id.
name - string, name of migration to be created.
opts - map of options specifying the database configuration.
supported options are:
:db - Migratus db config map
:database-url - URL of the application database
:migration-dir - string specifying the directory of the migration files
:migration-table-name - string specifying the migration table name
type - keyword, migration type (e.g. :sql and :edn for code-based migrations)"
[name opts & [type]]
(let [config (merge {:store :database} (parse-url opts))]
(migratus/create config name type)))
(defn migrate
"args - vector of arguments, e.g: [\"migrate\" \"201506104553\"]
opts - map of options specifying the database configuration.
supported options are:
:database-url - URL of the application database
:migration-dir - string specifying the directory of the migration files
:migration-table-name - string specifying the migration table name"
[args opts]
(when-not (migration? args)
(throw
(IllegalArgumentException.
(str "unrecognized option: " (first args)
", valid options are:" (join ", " (keys migrations))))))
(let [config (merge {:store :database} (parse-url opts))]
((get migrations (first args)) config args)))
| |
99208f4289b862a453528deaecba3d92c6a6e4fc603afc45dc8f7391603c584e | racket/math | number-theory.rkt | #lang typed/racket
(require "../base/base-random.rkt"
"divisibility.rkt"
"modular-arithmetic.rkt"
"types.rkt"
"small-primes.rkt")
(require/typed typed/racket
[integer-sqrt/remainder (Natural -> (Values Natural Natural))])
(provide solve-chinese
; primes
nth-prime
random-prime
next-prime untyped-next-prime
next-primes
prev-prime untyped-prev-prime
prev-primes
prime?
odd-prime?
factorize
defactorize
divisors
prime-divisors
prime-exponents
prime-omega
; roots
integer-root
integer-root/remainder
; Powers
max-dividing-power
perfect-power
perfect-power?
prime-power
prime-power?
odd-prime-power?
as-power
perfect-square
; number theoretic functions
totient
moebius-mu
divisor-sum
mangoldt-lambda
)
;;;
;;; Configuration
;;;
(define prime-strong-pseudo-certainty 1/10000000)
(define prime-strong-pseudo-trials
(integer-length (assert (/ 1 prime-strong-pseudo-certainty) integer?)))
(define *VERY-SMALL-PRIME-LIMIT* 1000)
; Determines the size of the pre-built table of very small primes
(define *SMALL-FACTORIZATION-LIMIT* *VERY-SMALL-PRIME-LIMIT*)
Determines whether to use naive factorization or Pollards rho method .
;;;
;;; Powers
;;;
(: max-dividing-power : Integer Integer -> Natural)
; (max-dividing-power p n) = m <=> p^m | n and p^(m+1) doesn't divide n
In this one is called IntegerExponent
(define (max-dividing-power p n)
(: find-start : Integer Integer -> Integer)
(define (find-start p-to-e e)
;(display (list 'fs 'p-to-e p-to-e 'e e)) (newline)
; p-to-e divides n and p-to-e = p^e
(let ([p-to-e2 (sqr p-to-e)])
(cond [(= p-to-e2 n) (* 2 e)]
[(> p-to-e2 n) (find-power p-to-e e)]
[(divides? p-to-e2 n) (if (divides? p (quotient n p-to-e2))
(find-start p-to-e2 (* 2 e))
(* 2 e))]
[else (find-power p-to-e e)])))
(: find-power : Integer Integer -> Integer)
(define (find-power p-to-e e)
;(display (list 'fp 'p-to-e p-to-e 'e e)) (newline)
; p-to-e <= n < (square p-to-e)
(+ e (max-dividing-power-naive p (quotient n p-to-e))))
(cond [(= p 1) 1]
[(not (divides? p n)) 0]
[else (assert (find-start p 1) natural?)]))
(: max-dividing-power-naive : Integer Integer -> Natural)
(define (max-dividing-power-naive p n)
; sames as max-dividing-power but using naive algorithm
(: loop : Integer Integer -> Integer)
(define (loop p-to-e e)
(if (divides? p-to-e n)
(loop (* p p-to-e) (+ e 1))
(- e 1)))
(if (= p 1)
(error 'max-dividing-power "No maximal power of 1 exists")
(assert (loop 1 0) natural?)))
; THEOREM (The Chinese Remainder Theorem)
; Let n1,...,nk be positive integers with gcd(ni,nj)=1 whenever i<>j,
; and let a1,...,ak be any integers. Then the solutions to
; x=a1 mod n1, ..., x=ak mod nk
; has a single solution in {0,...,n-1}, where n=n1*...nk.
Example : ( solve - chinese ' ( 2 3 2 ) ' ( 3 5 7 ) ) = 23
(: solve-chinese : (Listof Integer) (Listof Integer) -> Natural)
(define (solve-chinese as ns)
(unless (andmap positive? ns)
(raise-argument-error 'solve-chinese "(Listof Positive-Integer)" 1 as ns))
; the ns should be coprime
(let* ([n (apply * ns)]
[cs (map (λ: ([ni : Integer]) (quotient n ni)) ns)]
[ds (map modular-inverse cs ns)]
[es (cast ds (make-predicate (Listof Integer)))])
(cast (modulo (apply + (map * as cs es)) n) natural?)))
;;;
;;; PRIMES
;;;
(: odd-prime? : Integer -> Boolean)
(define (odd-prime? n)
(and (odd? n) (prime? n)))
PRIMALITY TESTS
From Modern Computer Algebra by and
; Strong pseudoprimality test
The strong test returns one of :
; 'probably-prime if n is a prime
' composite ( with at least probability 1/2 ) if n is a composite non - Carmichael number
a proper divisor of n ( with at least probability 1/2 ) if n is a number
[ MCA , p.509 - Algorithm 18.5 ]
(: prime-strong-pseudo-single? : Integer -> (U 'probably-prime 'composite Natural))
(define (prime-strong-pseudo-single? n)
(cond
[(n . <= . 0) (raise-argument-error 'prime-strong-pseudo-single? "Positive-Integer" n)]
[(n . >= . 4)
(define a (random-integer 2 (- n 1)))
(define g (gcd a n))
(cond
[(> g 1) g] ; factor found
[else
3 . write n-1 = 2^ν * m , m odd
(let loop ([ν 0] [m (- n 1)])
(cond
[(even? m) (loop (add1 ν) (quotient m 2))]
4 . for i=1, ... ,ν do bi < - b_{i-1}^2 rem N
(define b (modular-expt a m n))
(cond
[(= b 1) 'probably-prime]
[else
(let loop ([i 0] [b b] [b-old b])
(if (and (< i ν) (not (= b 1)))
(loop (add1 i)
(modulo (* b b) n)
b)
(if (= b 1)
(let ([g (gcd (+ b-old 1) n)])
(if (or (= g 1) (= g n))
'probably-prime
g))
'composite)))])]))])]
[(= n 1) 'composite]
[else 'probably-prime]))
(define-type Strong-Test-Result (U 'very-probably-prime 'composite Natural))
(: prime-strong-pseudo/explanation : Natural -> Strong-Test-Result)
(define (prime-strong-pseudo/explanation n)
; run the strong test several times to improve probability
(: loop : Integer (U Strong-Test-Result 'probably-prime) -> Strong-Test-Result)
(define (loop trials result)
(cond [(= trials 0) 'very-probably-prime]
[(eq? result 'probably-prime) (loop (sub1 trials) (prime-strong-pseudo-single? n))]
[else result]))
(loop prime-strong-pseudo-trials (prime-strong-pseudo-single? n)))
(: prime-strong-pseudo? : Natural -> Boolean)
(define (prime-strong-pseudo? n)
(let ([explanation (prime-strong-pseudo/explanation n)])
(or (eq? explanation 'very-probably-prime)
(eq? explanation #t))))
(: prime? : Integer -> Boolean)
(define prime?
(let ()
Sieve of Eratosthenes
;
; TODO: Only store odd integers in this table
(define N *VERY-SMALL-PRIME-LIMIT*)
(define ps (make-vector (+ N 1) #t))
(define ! vector-set!)
(! ps 0 #f)
(! ps 1 #f)
(for ([n (in-range 2 (+ N 1))])
(when (vector-ref ps n)
(for ([m (in-range (+ n n) (+ N 1) n)])
(! ps m #f))))
(lambda (n)
(let ([n (abs n)])
(cond
[(< n N)
(vector-ref ps n)]
[(< n *SMALL-PRIME-LIMIT*)
(small-prime? n)]
[else
(prime-strong-pseudo? n)])))))
(: next-prime : (case-> (Natural -> Natural)
(Integer -> Integer)))
(define (next-prime n)
(cond
[(negative? n) (- (prev-prime (abs n)))]
[(= n 0) 2]
[(= n 1) 2]
[(= n 2) 3]
[(even? n) (let ([n+1 (add1 n)])
(if (prime? n+1)
n+1
(next-prime n+1)))]
[else (let ([n+2 (+ n 2)])
(if (prime? n+2)
n+2
(next-prime n+2)))]))
(: untyped-next-prime : Integer -> Integer)
(define (untyped-next-prime z)
(next-prime z))
(: untyped-prev-prime : Integer -> Integer)
(define (untyped-prev-prime z)
(prev-prime z))
(: prev-prime : Integer -> Integer)
(define (prev-prime n)
(cond
[(negative? n) (- (next-prime (abs n)))]
[(= n 3) 2]
[(< n 3) -2]
[(even? n) (let ([n-1 (sub1 n)])
(if (prime? n-1)
n-1
(prev-prime n-1)))]
[else (let ([n-2 (- n 2)])
(if (prime? n-2)
n-2
(prev-prime n-2)))]))
(: next-primes : Integer Integer -> (Listof Integer))
(define (next-primes m primes-wanted)
(cond
[(primes-wanted . < . 0) (raise-argument-error 'next-primes "Natural" 1 m primes-wanted)]
[else
(: loop : Integer Integer -> (Listof Integer))
(define (loop n primes-wanted)
(if (= primes-wanted 0)
'()
(let ([next (next-prime n)])
(if next
(cons next (loop next (sub1 primes-wanted)))
'()))))
(loop m primes-wanted)]))
(: prev-primes : Integer Integer -> (Listof Integer))
(define (prev-primes m primes-wanted)
(cond
[(primes-wanted . < . 0) (raise-argument-error 'prev-primes "Natural" 1 m primes-wanted)]
[else
(: loop : Integer Integer -> (Listof Integer))
(define (loop n primes-wanted)
(if (= primes-wanted 0)
'()
(let ([prev (prev-prime n)])
(if prev
(cons prev (loop prev (sub1 primes-wanted)))
'()))))
(loop m primes-wanted)]))
(: nth-prime : Integer -> Natural)
(define (nth-prime n)
(cond [(n . < . 0) (raise-argument-error 'nth-prime "Natural" n)]
[else
(for/fold: ([p : Natural 2]) ([m (in-range n)])
(next-prime p))]))
(: random-prime : Integer -> Natural)
(define (random-prime n)
(when (<= n 2)
(raise-argument-error 'random-prime "Natural > 2" n))
(define p (random-natural n))
(if (prime? p)
p
(random-prime n)))
;;;
;;; FACTORIZATION
;;;
(: factorize : Natural -> (Listof (List Natural Natural)))
(define (factorize n)
(if (< n *SMALL-FACTORIZATION-LIMIT*) ; NOTE: Do measurement of best cut
(factorize-small n)
(factorize-large n)))
(: defactorize : (Listof (List Natural Natural)) -> Natural)
(define (defactorize bes)
(cond [(empty? bes) 1]
[else (define be (first bes))
(* (expt (first be) (second be))
(defactorize (rest bes)))]))
(: factorize-small : Natural -> (Listof (List Natural Natural)))
(define (factorize-small n)
; fast for small n, but works correctly for large n too
(small-prime-factors-over n 2))
(: small-prime-factors-over : Natural Natural -> (Listof (List Natural Natural)))
; Factor a number n without prime factors below the prime p.
(define (small-prime-factors-over n p) ; p prime
(cond
[(<= p 0) (raise-argument-error 'small-prime-factors-over "Natural" p)]
[(< n p) '()]
[(= n p) (list (list p 1))]
[(prime? n) (list (list n 1))]
[(divides? p n) (let ([m (max-dividing-power p n)])
(cons (list p m)
(small-prime-factors-over
(quotient n (expt p m))
(next-prime p))))]
[else (small-prime-factors-over n (next-prime p))]))
ALGORITHM 19.8 Pollard 's rho method
INPUT n>=3 neither a prime nor a perfect power
; OUTPUT Either a proper divisor of n or #f
(: pollard : Natural -> (U Natural False))
(define (pollard n)
(let ([x0 (random-natural n)])
(do ([xi x0 (remainder (+ (* xi xi) 1) n)]
[yi x0 (remainder (+ (sqr (+ (* yi yi) 1)) 1) n)]
[i 0 (add1 i)]
[g 1 (gcd (- xi yi) n)])
[(or (< 1 g n) (> i (sqrt n)))
(if (< 1 g n)
(cast g natural?)
#f)])))
(: pollard-factorize : Natural -> (Listof (List Natural Natural)))
(define (pollard-factorize n)
(if (< n *SMALL-FACTORIZATION-LIMIT*)
(factorize-small n)
(cond
[(= n 1) '()]
[(prime? n) `((, n 1))]
[(even? n) `((2 1) ,@(pollard-factorize (quotient n 2)))]
[(divides? 3 n) `((3 1) ,@(pollard-factorize (quotient n 3)))]
[(simple-perfect-power n)
=> (λ: ([base-and-exp : (List Natural Natural)])
(cond
[(prime? (car base-and-exp)) (list base-and-exp)]
[else (map (λ: ([b-and-e : (List Natural Natural)])
(list (car b-and-e)
(* (cadr base-and-exp) (cadr b-and-e))))
(pollard-factorize (car base-and-exp)))]))]
[else
(let loop ([divisor (pollard n)])
(if divisor
(append (pollard-factorize divisor)
(pollard-factorize (quotient n divisor)))
(loop (pollard n))))])))
(: factorize-large : Natural -> (Listof (List Natural Natural)))
(define (factorize-large n)
(combine-same-base
(sort (pollard-factorize n) base-and-exponent<?)))
(: base-and-exponent<? ((U Natural (List Natural Natural)) (U Natural (List Natural Natural))
-> Boolean))
(define (base-and-exponent<? x y)
(let ([id-or-first
(λ: ([x : (U Integer (List Integer Integer))])
(if (number? x) x (first x)))])
(<= (id-or-first x) (id-or-first y))))
(: combine-same-base : (Listof (List Natural Natural)) -> (Listof (List Natural Natural)))
(define (combine-same-base list-of-base-and-exponents)
; list-of-base-and-exponents must be sorted
(let ([l list-of-base-and-exponents])
(cond
[(null? l) '()]
[(null? (cdr l)) l]
[else
(define b1 (first (first l)))
(define e1 (second (first l)))
(define b2 (first (second l)))
(define e2 (second (second l)))
(define more (cddr l))
(if (= b1 b2)
(combine-same-base (cons (list b1 (+ e1 e2))
(cdr (cdr list-of-base-and-exponents))))
(cons (car list-of-base-and-exponents)
(combine-same-base (cdr list-of-base-and-exponents))))])))
find - tail pred - > pair or false
Return the first pair of clist whose car satisfies pred . If no pair does , return false .
(: find-tail : (Integer -> Boolean) (Listof Integer) -> (U False (Listof Integer)))
(define (find-tail pred xs)
(cond [(empty? xs) #f]
[(pred (car xs)) xs]
[else (find-tail pred (cdr xs))]))
;;;
;;; Powers
;;;
(: as-power : Exact-Positive-Integer -> (Values Natural Natural))
Write a>0 as b^r with r maximal . Return b and r.
(define (as-power a)
(let ([r (apply gcd ((inst map Natural (List Natural Natural)) second (factorize a)))])
(values (integer-root a r) r)))
(: prime-power : Natural -> (U (List Natural Natural) False))
; if n is a prime power, return list of prime and exponent in question,
; otherwise return #f
(define (prime-power n)
(let ([factorization (prime-divisors/exponents n)])
(if (= (length factorization) 1)
(first (prime-divisors/exponents n))
#f)))
(: prime-power? : Natural -> Boolean)
Is n of the form p^m , with p is prime ?
(define (prime-power? n)
(and (prime-power n) #t))
(: odd-prime-power? : Natural -> Boolean)
(define (odd-prime-power? n)
(let ([p/e (prime-power n)])
(and p/e
(odd? (first p/e)))))
(: perfect-power? : Natural -> Boolean)
(define (perfect-power? a)
(and (not (zero? a))
(let-values ([(base n) (as-power a)])
(and (> n 1) (> a 1)))))
(: simple-perfect-power : Natural -> (U (List Natural Natural) False))
(define (simple-perfect-power a)
; simple-perfect-power is used by pollard-fatorize
(and (not (zero? a))
(let-values ([(base n) (simple-as-power a)])
(if (and (> n 1) (> a 1))
(list base n)
#f))))
(: perfect-power : Natural -> (U (List Natural Natural) False))
if a = b^n with b>1 and
(define (perfect-power a)
(and (not (zero? a))
(let-values ([(base n) (as-power a)])
(if (and (> n 1) (> a 1))
(list base n)
#f))))
(: perfect-square : Natural -> (U Natural False))
(define (perfect-square n)
(let ([sqrt-n (integer-sqrt n)])
(if (= (* sqrt-n sqrt-n) n)
sqrt-n
#f)))
(: powers-of : Natural Natural -> (Listof Natural))
; returns a list of numbers: a^0, ..., a^n
(define (powers-of a n)
(let: loop : (Listof Natural)
([i : Natural 0]
[a^i : Natural 1])
(if (<= i n)
(cons a^i (loop (+ i 1) (* a^i a)))
'())))
(define prime-divisors/exponents factorize)
(: prime-divisors : Natural -> (Listof Natural))
; return list of primes in a factorization of n
(define (prime-divisors n)
(map (inst car Natural (Listof Natural))
(prime-divisors/exponents n)))
(: prime-exponents : Natural -> (Listof Natural))
; return list of exponents in a factorization of n
(define (prime-exponents n)
(map (inst cadr Natural Natural (Listof Natural))
(prime-divisors/exponents n)))
(: prime-omega : Natural -> Natural)
;
(define (prime-omega n)
(for/fold: ([sum : Natural 0]) ([e (in-list (prime-exponents n))])
(+ sum e)))
(: integer-root/remainder : Natural Natural -> (Values Natural Natural))
(define (integer-root/remainder a n)
(let ([i (integer-root a n)])
(values i (assert (- a (expt i n)) natural?))))
(: integer-root : Natural Natural -> Natural)
(define (integer-root x y)
; y'th root of x
(cond
[(eq? x 0) 0]
[(eq? x 1) 1]
[(eq? y 1) x]
[(eq? y 2) (integer-sqrt x)]
[(not (integer? y))
(error 'integer-root "internal error (used to return 1 here - why?) remove after testing")]
[else
(define length (integer-length x))
( expt 2 ( - length l 1 ) ) < = x < ( expt 2 length )
(assert
(cond [(<= length y) 1]
result is > = 2
[(<= length (* 2 y))
result is < 4
(if (< x (expt 3 y)) 2 3)]
[(even? y) (integer-root (integer-sqrt x) (quotient y 2))]
[else
length / y/2 > = 1 because ( < ( * 2 y ) length )
(quotient (quotient (- length 1) y) 2)])
(let ([init-g
(let* ([top-bits (arithmetic-shift x (- (* length/y/2 y)))]
[nth-root-top-bits (integer-root top-bits y)])
(arithmetic-shift (+ nth-root-top-bits 1) length/y/2))])
(let: loop : Integer ([g : Integer init-g])
(let* ([a (expt g (assert (- y 1) natural?))]
[b (* a y)]
[c (* a (- y 1))]
[d (quotient (+ x (* g c)) b)])
(let ([diff (- d g)])
(cond [(not (negative? diff))
g]
[(< diff -1)
(loop d)]
[else
;; once the difference is one, it's more
efficient to just decrement until = x
(let loop ((g d))
(if (not (< x (expt g y)))
g
(loop (- g 1))))]))))))])
natural?)]))
(: simple-as-power : Exact-Positive-Integer -> (Values Natural Natural))
For a>0 write it as a = b^r where r maximal
; return (values b r)
(define (simple-as-power a)
( ( list ' simple - as - power a ) )
; Note: The simple version is used by pollard-factorize
(let: loop : (Values Natural Natural)
([n : Natural (integer-length a)])
(let-values ([(root rem) (integer-root/remainder a (add1 n))])
(if (zero? rem)
(values root (assert (add1 n) natural?))
(if (positive? n)
(loop (sub1 n))
(error 'simple-as-power "internal error"))))))
(: prime-power? : Natural -> Boolean)
;;;
;;; DIVISORS
;;;
(: divisors : Integer -> (Listof Natural))
; return the positive divisors of n
(define (divisors n)
(cond [(zero? n) '()]
[else (define n+ (if (positive? n) n (- n)))
(sort (factorization->divisors (factorize n+)) <)]))
(: factorization->divisors : (Listof (List Natural Natural)) -> (Listof Natural))
(define (factorization->divisors f)
(cond
[(null? f) '(1)]
[else (let ([p (first (first f))]
[n (second (first f))]
[g (rest f)])
; f = p^n * g
(let ([divisors-of-g (factorization->divisors g)])
(apply append
((inst map (Listof Natural) Natural)
(λ: ([p^i : Natural]) (map (λ: ([d : Natural]) (* p^i d)) divisors-of-g))
(powers-of p n)))))]))
;;;
;;; Number theoretic functions
;;;
DEFINITION ( Euler 's phi function aka totient )
phi(n ) is the number of integers a=1,2 , ... such that gcd(a , n)=1
; THEOREM
; If m and n are coprime then
; phi(mn) = phi(m) phi(n)
THEOREM ( Euler 's phi function )
If the prime power factorization of p is
; e1 ek
; n = p1 ... pk , where pi is prime and ei>0
; then
k 1
phi(n ) = n * product ( 1 - ---- )
; i=1 pi
(: totient : Natural -> Natural)
(define (totient n)
(let ((ps (prime-divisors n)))
(assert (* (quotient n (apply * ps))
(apply * (map (λ: ([p : Natural]) (sub1 p)) ps)))
natural?)))
(: every : (All (A) (A -> Boolean) (Listof A) -> Boolean))
(define (every pred xs)
(or (empty? xs)
(and (pred (car xs))
(every pred (cdr xs)))))
; moebius-mu : natural -> {-1,0-1}
mu(n ) = 1 if n is a product of an even number of primes
; = -1 if n is a product of an odd number of primes
; = 0 if n has a multiple prime factor
(: moebius-mu : Natural -> (U -1 0 1))
(define (moebius-mu n)
(: one? : Integer -> Boolean)
(define (one? x) (= x 1))
(define f (factorize n))
(define exponents ((inst map Natural (List Natural Natural)) second f))
(cond
[(every one? exponents)
(define primes ((inst map Natural (List Natural Natural)) first f))
(if (even? (length primes))
1 -1)]
[else 0]))
(: divisor-sum : (case-> (Natural -> Natural) (Natural Natural -> Natural)))
(define divisor-sum
returns the sum of the power of all divisors of n
(let ()
(case-lambda
[(n) (divisor-sum n 1)]
[(n k) (let* ([f (factorize n)]
[ps ((inst map Natural (List Natural Natural)) first f)]
[es ((inst map Natural (List Natural Natural)) second f)])
(: divisor-sum0 : Any Natural -> Natural)
(define (divisor-sum0 p e) (+ e 1))
(: divisor-sum1 : Natural Natural -> Natural)
(define (divisor-sum1 p e)
(let: loop : Natural
([sum : Natural 1]
[n : Natural 0]
[p-to-n : Natural 1])
(cond [(= n e) sum]
[else (let ([t (* p p-to-n)])
(loop (+ t sum) (+ n 1) t))])))
(: divisor-sumk : Natural Natural -> Natural)
(define (divisor-sumk p e)
(let ([p-to-k (expt p k)])
(let: loop : Natural
([sum : Natural 1]
[n : Natural 0]
[p-to-kn : Natural 1])
(cond [(= n e) sum]
[else (let ([t (* p-to-k p-to-kn)])
(loop (+ t sum) (+ n 1) t))]))))
(cast
(apply * (map (cond [(= k 0) divisor-sum0]
[(= k 1) divisor-sum1]
[else divisor-sumk])
ps es))
natural?))])))
(: mangoldt-lambda : Integer -> Real)
(define (mangoldt-lambda n)
(cond
[(<= n 0) (raise-argument-error 'mangoldt-lambda "Natural" n)]
[else (define am (prime-power n))
(cond
[(cons? am) (log (car am))]
[else 0])]))
These tests are for un - exported functions .
#;(begin
(require typed/rackunit)
(check-equal? (max-dividing-power-naive 3 27) 3)
(check-equal? (max-dividing-power-naive 3 (* 27 2)) 3)
(check-true (<= 4 (random-integer 4 5) 4))
(check-false (prime-fermat? 0))
(check-false (prime-fermat? 1))
(check-false (prime-fermat? 4))
(check-false (prime-fermat? 6))
(check-false (prime-fermat? 8))
(check-equal? (prime-fermat? 2) #t)
(check-equal? (prime-fermat? 3) #t)
(check-equal? (prime-fermat? 5) 'possibly-prime)
(check-equal? (prime-fermat? 7) 'possibly-prime)
(check-equal? (prime-fermat? 11) 'possibly-prime)
(check-true (member? (prime-fermat? 561) '(#f possibly-prime))) ; Carmichael number
(check-equal? (prime-strong-pseudo-single? 4) 2)
(check-true (member? (prime-strong-pseudo-single? 6) '(2 3)))
(check-true (member? (prime-strong-pseudo-single? 8) '(2 4 composite)))
(check-equal? (prime-strong-pseudo-single? 5) 'probably-prime)
(check-equal? (prime-strong-pseudo-single? 7) 'probably-prime)
(check-equal? (prime-strong-pseudo-single? 11) 'probably-prime)
;; Carmichael number:
(check-true (member? (prime-strong-pseudo-single? 561) (cons 'probably-prime (divisors 561))))
)
| null | https://raw.githubusercontent.com/racket/math/3409a8e6e3b456fd3a5622e525931af49cd456b5/math-lib/math/private/number-theory/number-theory.rkt | racket | primes
roots
Powers
number theoretic functions
Configuration
Determines the size of the pre-built table of very small primes
Powers
(max-dividing-power p n) = m <=> p^m | n and p^(m+1) doesn't divide n
(display (list 'fs 'p-to-e p-to-e 'e e)) (newline)
p-to-e divides n and p-to-e = p^e
(display (list 'fp 'p-to-e p-to-e 'e e)) (newline)
p-to-e <= n < (square p-to-e)
sames as max-dividing-power but using naive algorithm
THEOREM (The Chinese Remainder Theorem)
Let n1,...,nk be positive integers with gcd(ni,nj)=1 whenever i<>j,
and let a1,...,ak be any integers. Then the solutions to
x=a1 mod n1, ..., x=ak mod nk
has a single solution in {0,...,n-1}, where n=n1*...nk.
the ns should be coprime
PRIMES
Strong pseudoprimality test
'probably-prime if n is a prime
factor found
run the strong test several times to improve probability
TODO: Only store odd integers in this table
FACTORIZATION
NOTE: Do measurement of best cut
fast for small n, but works correctly for large n too
Factor a number n without prime factors below the prime p.
p prime
OUTPUT Either a proper divisor of n or #f
list-of-base-and-exponents must be sorted
Powers
if n is a prime power, return list of prime and exponent in question,
otherwise return #f
simple-perfect-power is used by pollard-fatorize
returns a list of numbers: a^0, ..., a^n
return list of primes in a factorization of n
return list of exponents in a factorization of n
y'th root of x
once the difference is one, it's more
return (values b r)
Note: The simple version is used by pollard-factorize
DIVISORS
return the positive divisors of n
f = p^n * g
Number theoretic functions
THEOREM
If m and n are coprime then
phi(mn) = phi(m) phi(n)
e1 ek
n = p1 ... pk , where pi is prime and ei>0
then
i=1 pi
moebius-mu : natural -> {-1,0-1}
= -1 if n is a product of an odd number of primes
= 0 if n has a multiple prime factor
(begin
Carmichael number
Carmichael number: | #lang typed/racket
(require "../base/base-random.rkt"
"divisibility.rkt"
"modular-arithmetic.rkt"
"types.rkt"
"small-primes.rkt")
(require/typed typed/racket
[integer-sqrt/remainder (Natural -> (Values Natural Natural))])
(provide solve-chinese
nth-prime
random-prime
next-prime untyped-next-prime
next-primes
prev-prime untyped-prev-prime
prev-primes
prime?
odd-prime?
factorize
defactorize
divisors
prime-divisors
prime-exponents
prime-omega
integer-root
integer-root/remainder
max-dividing-power
perfect-power
perfect-power?
prime-power
prime-power?
odd-prime-power?
as-power
perfect-square
totient
moebius-mu
divisor-sum
mangoldt-lambda
)
(define prime-strong-pseudo-certainty 1/10000000)
(define prime-strong-pseudo-trials
(integer-length (assert (/ 1 prime-strong-pseudo-certainty) integer?)))
(define *VERY-SMALL-PRIME-LIMIT* 1000)
(define *SMALL-FACTORIZATION-LIMIT* *VERY-SMALL-PRIME-LIMIT*)
Determines whether to use naive factorization or Pollards rho method .
(: max-dividing-power : Integer Integer -> Natural)
In this one is called IntegerExponent
(define (max-dividing-power p n)
(: find-start : Integer Integer -> Integer)
(define (find-start p-to-e e)
(let ([p-to-e2 (sqr p-to-e)])
(cond [(= p-to-e2 n) (* 2 e)]
[(> p-to-e2 n) (find-power p-to-e e)]
[(divides? p-to-e2 n) (if (divides? p (quotient n p-to-e2))
(find-start p-to-e2 (* 2 e))
(* 2 e))]
[else (find-power p-to-e e)])))
(: find-power : Integer Integer -> Integer)
(define (find-power p-to-e e)
(+ e (max-dividing-power-naive p (quotient n p-to-e))))
(cond [(= p 1) 1]
[(not (divides? p n)) 0]
[else (assert (find-start p 1) natural?)]))
(: max-dividing-power-naive : Integer Integer -> Natural)
(define (max-dividing-power-naive p n)
(: loop : Integer Integer -> Integer)
(define (loop p-to-e e)
(if (divides? p-to-e n)
(loop (* p p-to-e) (+ e 1))
(- e 1)))
(if (= p 1)
(error 'max-dividing-power "No maximal power of 1 exists")
(assert (loop 1 0) natural?)))
Example : ( solve - chinese ' ( 2 3 2 ) ' ( 3 5 7 ) ) = 23
(: solve-chinese : (Listof Integer) (Listof Integer) -> Natural)
(define (solve-chinese as ns)
(unless (andmap positive? ns)
(raise-argument-error 'solve-chinese "(Listof Positive-Integer)" 1 as ns))
(let* ([n (apply * ns)]
[cs (map (λ: ([ni : Integer]) (quotient n ni)) ns)]
[ds (map modular-inverse cs ns)]
[es (cast ds (make-predicate (Listof Integer)))])
(cast (modulo (apply + (map * as cs es)) n) natural?)))
(: odd-prime? : Integer -> Boolean)
(define (odd-prime? n)
(and (odd? n) (prime? n)))
PRIMALITY TESTS
From Modern Computer Algebra by and
The strong test returns one of :
' composite ( with at least probability 1/2 ) if n is a composite non - Carmichael number
a proper divisor of n ( with at least probability 1/2 ) if n is a number
[ MCA , p.509 - Algorithm 18.5 ]
(: prime-strong-pseudo-single? : Integer -> (U 'probably-prime 'composite Natural))
(define (prime-strong-pseudo-single? n)
(cond
[(n . <= . 0) (raise-argument-error 'prime-strong-pseudo-single? "Positive-Integer" n)]
[(n . >= . 4)
(define a (random-integer 2 (- n 1)))
(define g (gcd a n))
(cond
[else
3 . write n-1 = 2^ν * m , m odd
(let loop ([ν 0] [m (- n 1)])
(cond
[(even? m) (loop (add1 ν) (quotient m 2))]
4 . for i=1, ... ,ν do bi < - b_{i-1}^2 rem N
(define b (modular-expt a m n))
(cond
[(= b 1) 'probably-prime]
[else
(let loop ([i 0] [b b] [b-old b])
(if (and (< i ν) (not (= b 1)))
(loop (add1 i)
(modulo (* b b) n)
b)
(if (= b 1)
(let ([g (gcd (+ b-old 1) n)])
(if (or (= g 1) (= g n))
'probably-prime
g))
'composite)))])]))])]
[(= n 1) 'composite]
[else 'probably-prime]))
(define-type Strong-Test-Result (U 'very-probably-prime 'composite Natural))
(: prime-strong-pseudo/explanation : Natural -> Strong-Test-Result)
(define (prime-strong-pseudo/explanation n)
(: loop : Integer (U Strong-Test-Result 'probably-prime) -> Strong-Test-Result)
(define (loop trials result)
(cond [(= trials 0) 'very-probably-prime]
[(eq? result 'probably-prime) (loop (sub1 trials) (prime-strong-pseudo-single? n))]
[else result]))
(loop prime-strong-pseudo-trials (prime-strong-pseudo-single? n)))
(: prime-strong-pseudo? : Natural -> Boolean)
(define (prime-strong-pseudo? n)
(let ([explanation (prime-strong-pseudo/explanation n)])
(or (eq? explanation 'very-probably-prime)
(eq? explanation #t))))
(: prime? : Integer -> Boolean)
(define prime?
(let ()
Sieve of Eratosthenes
(define N *VERY-SMALL-PRIME-LIMIT*)
(define ps (make-vector (+ N 1) #t))
(define ! vector-set!)
(! ps 0 #f)
(! ps 1 #f)
(for ([n (in-range 2 (+ N 1))])
(when (vector-ref ps n)
(for ([m (in-range (+ n n) (+ N 1) n)])
(! ps m #f))))
(lambda (n)
(let ([n (abs n)])
(cond
[(< n N)
(vector-ref ps n)]
[(< n *SMALL-PRIME-LIMIT*)
(small-prime? n)]
[else
(prime-strong-pseudo? n)])))))
(: next-prime : (case-> (Natural -> Natural)
(Integer -> Integer)))
(define (next-prime n)
(cond
[(negative? n) (- (prev-prime (abs n)))]
[(= n 0) 2]
[(= n 1) 2]
[(= n 2) 3]
[(even? n) (let ([n+1 (add1 n)])
(if (prime? n+1)
n+1
(next-prime n+1)))]
[else (let ([n+2 (+ n 2)])
(if (prime? n+2)
n+2
(next-prime n+2)))]))
(: untyped-next-prime : Integer -> Integer)
(define (untyped-next-prime z)
(next-prime z))
(: untyped-prev-prime : Integer -> Integer)
(define (untyped-prev-prime z)
(prev-prime z))
(: prev-prime : Integer -> Integer)
(define (prev-prime n)
(cond
[(negative? n) (- (next-prime (abs n)))]
[(= n 3) 2]
[(< n 3) -2]
[(even? n) (let ([n-1 (sub1 n)])
(if (prime? n-1)
n-1
(prev-prime n-1)))]
[else (let ([n-2 (- n 2)])
(if (prime? n-2)
n-2
(prev-prime n-2)))]))
(: next-primes : Integer Integer -> (Listof Integer))
(define (next-primes m primes-wanted)
(cond
[(primes-wanted . < . 0) (raise-argument-error 'next-primes "Natural" 1 m primes-wanted)]
[else
(: loop : Integer Integer -> (Listof Integer))
(define (loop n primes-wanted)
(if (= primes-wanted 0)
'()
(let ([next (next-prime n)])
(if next
(cons next (loop next (sub1 primes-wanted)))
'()))))
(loop m primes-wanted)]))
(: prev-primes : Integer Integer -> (Listof Integer))
(define (prev-primes m primes-wanted)
(cond
[(primes-wanted . < . 0) (raise-argument-error 'prev-primes "Natural" 1 m primes-wanted)]
[else
(: loop : Integer Integer -> (Listof Integer))
(define (loop n primes-wanted)
(if (= primes-wanted 0)
'()
(let ([prev (prev-prime n)])
(if prev
(cons prev (loop prev (sub1 primes-wanted)))
'()))))
(loop m primes-wanted)]))
(: nth-prime : Integer -> Natural)
(define (nth-prime n)
(cond [(n . < . 0) (raise-argument-error 'nth-prime "Natural" n)]
[else
(for/fold: ([p : Natural 2]) ([m (in-range n)])
(next-prime p))]))
(: random-prime : Integer -> Natural)
(define (random-prime n)
(when (<= n 2)
(raise-argument-error 'random-prime "Natural > 2" n))
(define p (random-natural n))
(if (prime? p)
p
(random-prime n)))
(: factorize : Natural -> (Listof (List Natural Natural)))
(define (factorize n)
(factorize-small n)
(factorize-large n)))
(: defactorize : (Listof (List Natural Natural)) -> Natural)
(define (defactorize bes)
(cond [(empty? bes) 1]
[else (define be (first bes))
(* (expt (first be) (second be))
(defactorize (rest bes)))]))
(: factorize-small : Natural -> (Listof (List Natural Natural)))
(define (factorize-small n)
(small-prime-factors-over n 2))
(: small-prime-factors-over : Natural Natural -> (Listof (List Natural Natural)))
(cond
[(<= p 0) (raise-argument-error 'small-prime-factors-over "Natural" p)]
[(< n p) '()]
[(= n p) (list (list p 1))]
[(prime? n) (list (list n 1))]
[(divides? p n) (let ([m (max-dividing-power p n)])
(cons (list p m)
(small-prime-factors-over
(quotient n (expt p m))
(next-prime p))))]
[else (small-prime-factors-over n (next-prime p))]))
ALGORITHM 19.8 Pollard 's rho method
INPUT n>=3 neither a prime nor a perfect power
(: pollard : Natural -> (U Natural False))
(define (pollard n)
(let ([x0 (random-natural n)])
(do ([xi x0 (remainder (+ (* xi xi) 1) n)]
[yi x0 (remainder (+ (sqr (+ (* yi yi) 1)) 1) n)]
[i 0 (add1 i)]
[g 1 (gcd (- xi yi) n)])
[(or (< 1 g n) (> i (sqrt n)))
(if (< 1 g n)
(cast g natural?)
#f)])))
(: pollard-factorize : Natural -> (Listof (List Natural Natural)))
(define (pollard-factorize n)
(if (< n *SMALL-FACTORIZATION-LIMIT*)
(factorize-small n)
(cond
[(= n 1) '()]
[(prime? n) `((, n 1))]
[(even? n) `((2 1) ,@(pollard-factorize (quotient n 2)))]
[(divides? 3 n) `((3 1) ,@(pollard-factorize (quotient n 3)))]
[(simple-perfect-power n)
=> (λ: ([base-and-exp : (List Natural Natural)])
(cond
[(prime? (car base-and-exp)) (list base-and-exp)]
[else (map (λ: ([b-and-e : (List Natural Natural)])
(list (car b-and-e)
(* (cadr base-and-exp) (cadr b-and-e))))
(pollard-factorize (car base-and-exp)))]))]
[else
(let loop ([divisor (pollard n)])
(if divisor
(append (pollard-factorize divisor)
(pollard-factorize (quotient n divisor)))
(loop (pollard n))))])))
(: factorize-large : Natural -> (Listof (List Natural Natural)))
(define (factorize-large n)
(combine-same-base
(sort (pollard-factorize n) base-and-exponent<?)))
(: base-and-exponent<? ((U Natural (List Natural Natural)) (U Natural (List Natural Natural))
-> Boolean))
(define (base-and-exponent<? x y)
(let ([id-or-first
(λ: ([x : (U Integer (List Integer Integer))])
(if (number? x) x (first x)))])
(<= (id-or-first x) (id-or-first y))))
(: combine-same-base : (Listof (List Natural Natural)) -> (Listof (List Natural Natural)))
(define (combine-same-base list-of-base-and-exponents)
(let ([l list-of-base-and-exponents])
(cond
[(null? l) '()]
[(null? (cdr l)) l]
[else
(define b1 (first (first l)))
(define e1 (second (first l)))
(define b2 (first (second l)))
(define e2 (second (second l)))
(define more (cddr l))
(if (= b1 b2)
(combine-same-base (cons (list b1 (+ e1 e2))
(cdr (cdr list-of-base-and-exponents))))
(cons (car list-of-base-and-exponents)
(combine-same-base (cdr list-of-base-and-exponents))))])))
find - tail pred - > pair or false
Return the first pair of clist whose car satisfies pred . If no pair does , return false .
(: find-tail : (Integer -> Boolean) (Listof Integer) -> (U False (Listof Integer)))
(define (find-tail pred xs)
(cond [(empty? xs) #f]
[(pred (car xs)) xs]
[else (find-tail pred (cdr xs))]))
(: as-power : Exact-Positive-Integer -> (Values Natural Natural))
Write a>0 as b^r with r maximal . Return b and r.
(define (as-power a)
(let ([r (apply gcd ((inst map Natural (List Natural Natural)) second (factorize a)))])
(values (integer-root a r) r)))
(: prime-power : Natural -> (U (List Natural Natural) False))
(define (prime-power n)
(let ([factorization (prime-divisors/exponents n)])
(if (= (length factorization) 1)
(first (prime-divisors/exponents n))
#f)))
(: prime-power? : Natural -> Boolean)
Is n of the form p^m , with p is prime ?
(define (prime-power? n)
(and (prime-power n) #t))
(: odd-prime-power? : Natural -> Boolean)
(define (odd-prime-power? n)
(let ([p/e (prime-power n)])
(and p/e
(odd? (first p/e)))))
(: perfect-power? : Natural -> Boolean)
(define (perfect-power? a)
(and (not (zero? a))
(let-values ([(base n) (as-power a)])
(and (> n 1) (> a 1)))))
(: simple-perfect-power : Natural -> (U (List Natural Natural) False))
(define (simple-perfect-power a)
(and (not (zero? a))
(let-values ([(base n) (simple-as-power a)])
(if (and (> n 1) (> a 1))
(list base n)
#f))))
(: perfect-power : Natural -> (U (List Natural Natural) False))
if a = b^n with b>1 and
(define (perfect-power a)
(and (not (zero? a))
(let-values ([(base n) (as-power a)])
(if (and (> n 1) (> a 1))
(list base n)
#f))))
(: perfect-square : Natural -> (U Natural False))
(define (perfect-square n)
(let ([sqrt-n (integer-sqrt n)])
(if (= (* sqrt-n sqrt-n) n)
sqrt-n
#f)))
(: powers-of : Natural Natural -> (Listof Natural))
(define (powers-of a n)
(let: loop : (Listof Natural)
([i : Natural 0]
[a^i : Natural 1])
(if (<= i n)
(cons a^i (loop (+ i 1) (* a^i a)))
'())))
(define prime-divisors/exponents factorize)
(: prime-divisors : Natural -> (Listof Natural))
(define (prime-divisors n)
(map (inst car Natural (Listof Natural))
(prime-divisors/exponents n)))
(: prime-exponents : Natural -> (Listof Natural))
(define (prime-exponents n)
(map (inst cadr Natural Natural (Listof Natural))
(prime-divisors/exponents n)))
(: prime-omega : Natural -> Natural)
(define (prime-omega n)
(for/fold: ([sum : Natural 0]) ([e (in-list (prime-exponents n))])
(+ sum e)))
(: integer-root/remainder : Natural Natural -> (Values Natural Natural))
(define (integer-root/remainder a n)
(let ([i (integer-root a n)])
(values i (assert (- a (expt i n)) natural?))))
(: integer-root : Natural Natural -> Natural)
(define (integer-root x y)
(cond
[(eq? x 0) 0]
[(eq? x 1) 1]
[(eq? y 1) x]
[(eq? y 2) (integer-sqrt x)]
[(not (integer? y))
(error 'integer-root "internal error (used to return 1 here - why?) remove after testing")]
[else
(define length (integer-length x))
( expt 2 ( - length l 1 ) ) < = x < ( expt 2 length )
(assert
(cond [(<= length y) 1]
result is > = 2
[(<= length (* 2 y))
result is < 4
(if (< x (expt 3 y)) 2 3)]
[(even? y) (integer-root (integer-sqrt x) (quotient y 2))]
[else
length / y/2 > = 1 because ( < ( * 2 y ) length )
(quotient (quotient (- length 1) y) 2)])
(let ([init-g
(let* ([top-bits (arithmetic-shift x (- (* length/y/2 y)))]
[nth-root-top-bits (integer-root top-bits y)])
(arithmetic-shift (+ nth-root-top-bits 1) length/y/2))])
(let: loop : Integer ([g : Integer init-g])
(let* ([a (expt g (assert (- y 1) natural?))]
[b (* a y)]
[c (* a (- y 1))]
[d (quotient (+ x (* g c)) b)])
(let ([diff (- d g)])
(cond [(not (negative? diff))
g]
[(< diff -1)
(loop d)]
[else
efficient to just decrement until = x
(let loop ((g d))
(if (not (< x (expt g y)))
g
(loop (- g 1))))]))))))])
natural?)]))
(: simple-as-power : Exact-Positive-Integer -> (Values Natural Natural))
For a>0 write it as a = b^r where r maximal
(define (simple-as-power a)
( ( list ' simple - as - power a ) )
(let: loop : (Values Natural Natural)
([n : Natural (integer-length a)])
(let-values ([(root rem) (integer-root/remainder a (add1 n))])
(if (zero? rem)
(values root (assert (add1 n) natural?))
(if (positive? n)
(loop (sub1 n))
(error 'simple-as-power "internal error"))))))
(: prime-power? : Natural -> Boolean)
(: divisors : Integer -> (Listof Natural))
(define (divisors n)
(cond [(zero? n) '()]
[else (define n+ (if (positive? n) n (- n)))
(sort (factorization->divisors (factorize n+)) <)]))
(: factorization->divisors : (Listof (List Natural Natural)) -> (Listof Natural))
(define (factorization->divisors f)
(cond
[(null? f) '(1)]
[else (let ([p (first (first f))]
[n (second (first f))]
[g (rest f)])
(let ([divisors-of-g (factorization->divisors g)])
(apply append
((inst map (Listof Natural) Natural)
(λ: ([p^i : Natural]) (map (λ: ([d : Natural]) (* p^i d)) divisors-of-g))
(powers-of p n)))))]))
DEFINITION ( Euler 's phi function aka totient )
phi(n ) is the number of integers a=1,2 , ... such that gcd(a , n)=1
THEOREM ( Euler 's phi function )
If the prime power factorization of p is
k 1
phi(n ) = n * product ( 1 - ---- )
(: totient : Natural -> Natural)
(define (totient n)
(let ((ps (prime-divisors n)))
(assert (* (quotient n (apply * ps))
(apply * (map (λ: ([p : Natural]) (sub1 p)) ps)))
natural?)))
(: every : (All (A) (A -> Boolean) (Listof A) -> Boolean))
(define (every pred xs)
(or (empty? xs)
(and (pred (car xs))
(every pred (cdr xs)))))
mu(n ) = 1 if n is a product of an even number of primes
(: moebius-mu : Natural -> (U -1 0 1))
(define (moebius-mu n)
(: one? : Integer -> Boolean)
(define (one? x) (= x 1))
(define f (factorize n))
(define exponents ((inst map Natural (List Natural Natural)) second f))
(cond
[(every one? exponents)
(define primes ((inst map Natural (List Natural Natural)) first f))
(if (even? (length primes))
1 -1)]
[else 0]))
(: divisor-sum : (case-> (Natural -> Natural) (Natural Natural -> Natural)))
(define divisor-sum
returns the sum of the power of all divisors of n
(let ()
(case-lambda
[(n) (divisor-sum n 1)]
[(n k) (let* ([f (factorize n)]
[ps ((inst map Natural (List Natural Natural)) first f)]
[es ((inst map Natural (List Natural Natural)) second f)])
(: divisor-sum0 : Any Natural -> Natural)
(define (divisor-sum0 p e) (+ e 1))
(: divisor-sum1 : Natural Natural -> Natural)
(define (divisor-sum1 p e)
(let: loop : Natural
([sum : Natural 1]
[n : Natural 0]
[p-to-n : Natural 1])
(cond [(= n e) sum]
[else (let ([t (* p p-to-n)])
(loop (+ t sum) (+ n 1) t))])))
(: divisor-sumk : Natural Natural -> Natural)
(define (divisor-sumk p e)
(let ([p-to-k (expt p k)])
(let: loop : Natural
([sum : Natural 1]
[n : Natural 0]
[p-to-kn : Natural 1])
(cond [(= n e) sum]
[else (let ([t (* p-to-k p-to-kn)])
(loop (+ t sum) (+ n 1) t))]))))
(cast
(apply * (map (cond [(= k 0) divisor-sum0]
[(= k 1) divisor-sum1]
[else divisor-sumk])
ps es))
natural?))])))
(: mangoldt-lambda : Integer -> Real)
(define (mangoldt-lambda n)
(cond
[(<= n 0) (raise-argument-error 'mangoldt-lambda "Natural" n)]
[else (define am (prime-power n))
(cond
[(cons? am) (log (car am))]
[else 0])]))
These tests are for un - exported functions .
(require typed/rackunit)
(check-equal? (max-dividing-power-naive 3 27) 3)
(check-equal? (max-dividing-power-naive 3 (* 27 2)) 3)
(check-true (<= 4 (random-integer 4 5) 4))
(check-false (prime-fermat? 0))
(check-false (prime-fermat? 1))
(check-false (prime-fermat? 4))
(check-false (prime-fermat? 6))
(check-false (prime-fermat? 8))
(check-equal? (prime-fermat? 2) #t)
(check-equal? (prime-fermat? 3) #t)
(check-equal? (prime-fermat? 5) 'possibly-prime)
(check-equal? (prime-fermat? 7) 'possibly-prime)
(check-equal? (prime-fermat? 11) 'possibly-prime)
(check-equal? (prime-strong-pseudo-single? 4) 2)
(check-true (member? (prime-strong-pseudo-single? 6) '(2 3)))
(check-true (member? (prime-strong-pseudo-single? 8) '(2 4 composite)))
(check-equal? (prime-strong-pseudo-single? 5) 'probably-prime)
(check-equal? (prime-strong-pseudo-single? 7) 'probably-prime)
(check-equal? (prime-strong-pseudo-single? 11) 'probably-prime)
(check-true (member? (prime-strong-pseudo-single? 561) (cons 'probably-prime (divisors 561))))
)
|
844ec282827175096c4881419b0c843432b4c3dd7d3cacb0ee13be15111da9c6 | sellout/haskerwaul | Ribbon.hs | # language UndecidableSuperClasses #
module Haskerwaul.Category.Ribbon
( module Haskerwaul.Category.Ribbon
-- * extended modules
, module Haskerwaul.Category.Monoidal.Balanced
, module Haskerwaul.Category.Monoidal.Rigid
) where
import Haskerwaul.Category.Monoidal.Balanced
import Haskerwaul.Category.Monoidal.Rigid
-- |
-- = references
--
-- - [nLab](+category)
-- - [Wikipedia]()
--
-- __NB__: Instances for this are automatically coalesced.
class (BalancedMonoidalCategory c t, RigidMonoidalCategory c t) => RibbonCategory c t
instance (BalancedMonoidalCategory c t, RigidMonoidalCategory c t) => RibbonCategory c t
| null | https://raw.githubusercontent.com/sellout/haskerwaul/cf54bd7ce5bf4f3d1fd0d9d991dc733785b66a73/src/Haskerwaul/Category/Ribbon.hs | haskell | * extended modules
|
= references
- [nLab](+category)
- [Wikipedia]()
__NB__: Instances for this are automatically coalesced. | # language UndecidableSuperClasses #
module Haskerwaul.Category.Ribbon
( module Haskerwaul.Category.Ribbon
, module Haskerwaul.Category.Monoidal.Balanced
, module Haskerwaul.Category.Monoidal.Rigid
) where
import Haskerwaul.Category.Monoidal.Balanced
import Haskerwaul.Category.Monoidal.Rigid
class (BalancedMonoidalCategory c t, RigidMonoidalCategory c t) => RibbonCategory c t
instance (BalancedMonoidalCategory c t, RigidMonoidalCategory c t) => RibbonCategory c t
|
06ad3d4f0337dfaf78a6056887dac8f8954f67358dbdd64c4018f292d07a450b | linkfluence/inventory | app.clj | (ns com.linkfluence.inventory.app
(:import [java.util.concurrent LinkedBlockingQueue])
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[com.linkfluence.store :as store]
[com.linkfluence.utils :as u]
[clj-http.client :as http]
[cheshire.core :refer :all]
[clojure.spec.alpha :as spec]
[com.linkfluence.inventory.caller :as caller]
[com.linkfluence.inventory.core :as inventory]
[com.linkfluence.inventory.queue :as queue :refer [put tke]]))
;; queue for inventory update
(def ^LinkedBlockingQueue inventory-queue (LinkedBlockingQueue.))
;;this the main inventory for apps
(def apps (atom {}))
;;atom for conf
(def conf (atom nil))
(def bulk (atom nil))
(defn ro?
[]
(:read-only @conf))
;;return queue size
(defn get-event-queue-size
[]
(.size inventory-queue))
(defn load-inventory!
[]
;;applicable if we wan't to store something (ie : not during test)
(when (:store @conf)
;load envs
(when-let [as (store/load-map (assoc (:store @conf) :key "apps"))]
(reset! apps as))))
;;store inventory backup
(defn save-inventory
[]
;;applicable if we wan't to store something (ie : not during test)
(when (:store @conf)
(when-not (ro?)
;save apps
(store/save-map (assoc (:store @conf) :key "apps") @apps))))
(defn post-event
[master ev]
(try
(http/post
(str "http://" master "/app/event")
{:content-type :json :body (generate-string {:event ev})})
true
(catch Exception e
false)))
(defn post-bulk
[master]
(try
(http/post
(str "http://" master "/app/events")
{:content-type :json :body (generate-string {:events @bulk})})
(reset! bulk nil)
true
(catch Exception e
false)))
(defn send-event
[master event]
(cond
(and (= 0 (.size inventory-queue)) (nil? @bulk))
(loop []
(when-not (post-event master event)
(Thread/sleep 60000)
(recur)))
(and (= 0 (.size inventory-queue)) (not (nil? @bulk)))
(do
(swap! bulk conj event)
(loop []
(when-not (post-bulk master)
(Thread/sleep 60000)
(recur))))
:else (if (nil? @bulk)
(reset! bulk [event])
(swap! bulk conj event))))
(defn tag-matcher
"Check if an entity group/resource match a tag"
[entity tag]
(if-not (:not tag)
(= (:value tag) ((keyword (:name tag)) entity))
(not (= (:value tag) ((keyword (:name tag)) entity)))))
(defn tags-matcher
"Check if an entity group/resource match the tags array"
[entity tags]
(if-not (= 0 (count tags))
(loop [tgs tags
m true]
(if m
(if-not (= 0 (count tgs))
(if (tag-matcher entity (first tgs))
(recur (next tgs) true)
false)
m)
false))
true))
;;add event Update
(defn add-inventory-event
"add an event to update app inventory"
[ev]
(when (or
(not (ro?))
(not (nil? (get @conf :master nil))))
(.put inventory-queue ev)))
;;Env mgt
(defn- create-env!
"Create a new empty environment"
[env desc]
(swap! apps assoc (keyword env) {:description desc :app-tags {} :resource-tags {} :apps {}}))
(defn- update-env-tags!
[env tags type]
(doseq [tag tags]
(if-not (:delete tag)
(swap! apps assoc-in [(keyword env) type (keyword (:name tag))] (:value tag))
(swap! apps update-in [(keyword env) type] dissoc (keyword (:name tag))))))
(defn- update-env!
"Tag an environment with default app-tags and resource-tags"
[env app-tags resource-tags]
(update-env-tags! env (or app-tags []) :app-tags)
(update-env-tags! env (or resource-tags []) :resource-tags))
(defn- delete-env!
"Delete an environment"
[env]
(swap! apps dissoc (keyword env)))
;;Env getter
(defn env-exists?
[env]
(not (nil? (get @apps (keyword env) nil))))
(defn get-env
[& [env]]
(if (nil? env)
(into [](keys @apps))
(dissoc (get @apps (keyword env)) :apps)))
(defn get-env-apps
[env]
(get-in @apps [(keyword env) :apps]))
(defn- update-app-tags!
[app env tags type]
(doseq [tag tags]
(if-not (:delete tag)
(if-not (:append tag)
(swap! apps assoc-in [(keyword env) :apps (keyword app) type (keyword (:name tag))] (:value tag))
(let [current-value (get-in @apps [(keyword env) :apps (keyword app) type (keyword (:name tag))])
updated-value (cond
(nil? current-value) (:value tag)
(or (string? current-value) (number? current-value))
(if-not (= (:value tag) current-value)
[current-value (:value tag)]
current-value)
(or (list? current-value) (vector? current-value))
(if-not (.contains current-value (:value tag))
(into [] (concat current-value [(:value tag)]))
current-value))]
(when-not (or (nil? updated-value) (= current-value updated-value))
(swap! apps assoc-in [(keyword env) :apps (keyword app) type (keyword (:name tag))] updated-value))))
(swap! apps update-in [(keyword env) :apps (keyword app) type] dissoc (keyword (:name tag))))))
;;App tagging
(defn- update-app!
"Create or update an application"
[app env tags resource-tags]
(update-app-tags! app env (or tags []) :tags)
(update-app-tags! app env (or resource-tags []) :resource-tags))
(defn- delete-app!
"Delete an application"
[app env]
(swap! apps update-in [(keyword env) :apps] dissoc (keyword app)))
;;App getter
(defn get-app-resources
"Return resources associated to this app/env couple"
[app env]
(when-let [app-data (get-in @apps [(keyword env) :apps (keyword app)])]
(let [env-res-tags (get-in @apps [(keyword env) :resource-tags])
app-res-tags (:resource-tags app-data)]
(inventory/get-resources (into []
(map
(fn [[k v]]
{:name (name k) :value v})
(merge env-res-tags app-res-tags)))))))
(defn get-app-resources-tag-value
"Return specific tag of resources associated to this app (ex : FQDN)"
[app env tag]
(when-let [app-data (get-in @apps [(keyword env) :apps (keyword app)])]
(let [env-res-tags (get-in @apps [(keyword env) :resource-tags])
app-res-tags (:resource-tags app-data)]
(inventory/get-tag-value-from-resources tag (into []
(map
(fn [[k v]]
{:name (name k) :value v})
(merge env-res-tags app-res-tags)))))))
(defn exists?
[app env]
(not (nil? (get-in @apps [(keyword env) :apps (keyword app)] nil))))
(defn get-app
"Return an app"
[app env]
{:tags (get-in @apps [(keyword env) :apps (keyword app) :tags] {})
:tags-from-env (get-in @apps [(keyword env) :app-tags] {})
:resource-tags (get-in @apps [(keyword env) :apps (keyword app) :resource-tags] {})
:resource-tags-from-env (get-in @apps [(keyword env) :resource-tags] {})})
(defn get-app-tags
"Return tags of a specific app"
[app env]
{:tags (get-in @apps [(keyword env) :apps (keyword app) :tags] {})
:tags-from-env (get-in @apps [(keyword env) :app-tags] {})})
(defn get-app-resource-tags
"Return tags use to match resource"
[app env]
{:resource-tags (get-in @apps [(keyword env) :apps (keyword app) :resource-tags] {})
:resource-tags-from-env (get-in @apps [(keyword env) :resource-tags] {})})
;;App lifecycle
(defn- app-systemctl
[app env action]
(let [resources (get-app-resources-tag-value app env (or (:lifecycle-tag @conf) "FQDN"))]
(log/info "[app-systemctl] will do" action "on" resources "for" app "on env" env)
(doseq [resource resources]
(caller/add-command {:commands [(str "systemctl " action " " app " --no-pager")]
:method :ssh
:hosts resource
:sudo true}))))
(defn submit-action
[app env action]
(condp = action
"start" (app-systemctl app env "start")
"stop" (app-systemctl app env "stop")
"restart" (app-systemctl app env "restart")
"reload" (app-systemctl app env "reload")
"status" (app-systemctl app env "status")
nil))
(defn update-app-with-ev!
[ev]
(when-not
(or (nil? (:app ev))
(str/includes? (name (:app ev)) " ")
(str/includes? (name (:app ev)) ";")
(str/includes? (name (:app ev)) "\"")
(str/includes? (name (:app ev)) "'"))
(if (:delete ev)
(delete-app! (:app ev) (:env ev))
(update-app! (:app ev) (:env ev) (:tags ev) (:resource-tags ev)))
(when (= 0 (.size inventory-queue))
(save-inventory)
(u/fsync "app"))))
(defn update-env-with-ev!
[ev]
(if (:create ev)
(create-env! (:env ev) (:description ev))
(if (:delete ev)
(delete-env! (:env ev))
(update-env! (:env ev) (:app-tags ev) (:resource-tags ev))))
(when (= 0 (.size inventory-queue))
(save-inventory)
(u/fsync "app")))
(defn- update-inventory!
"generic inventory update"
[ev]
(if-not (ro?)
(condp = (:type ev)
"app" (update-app-with-ev! ev)
"env" (update-env-with-ev! ev))
(when-let [master (get @conf :master nil)]
(send-event master ev))))
(defn- start-inventory-consumer!
[]
(u/start-thread!
(fn [] ;;consume queue
(when-let [ev (.take inventory-queue)]
(update-inventory! ev)))
"Inventory apps Consumer"))
(defn start!
[]
(if (or
(not (ro?))
(and (ro?)
(not (nil? (get @conf :master)))))
[(start-inventory-consumer!)]
[]))
(defn configure!
[inventory-conf]
(reset! conf inventory-conf)
(load-inventory!))
| null | https://raw.githubusercontent.com/linkfluence/inventory/b69110494f8db210d14cc7093834c441440cd4e8/src/clj/com/linkfluence/inventory/app.clj | clojure | queue for inventory update
this the main inventory for apps
atom for conf
return queue size
applicable if we wan't to store something (ie : not during test)
load envs
store inventory backup
applicable if we wan't to store something (ie : not during test)
save apps
add event Update
Env mgt
Env getter
App tagging
App getter
App lifecycle
consume queue | (ns com.linkfluence.inventory.app
(:import [java.util.concurrent LinkedBlockingQueue])
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[com.linkfluence.store :as store]
[com.linkfluence.utils :as u]
[clj-http.client :as http]
[cheshire.core :refer :all]
[clojure.spec.alpha :as spec]
[com.linkfluence.inventory.caller :as caller]
[com.linkfluence.inventory.core :as inventory]
[com.linkfluence.inventory.queue :as queue :refer [put tke]]))
(def ^LinkedBlockingQueue inventory-queue (LinkedBlockingQueue.))
(def apps (atom {}))
(def conf (atom nil))
(def bulk (atom nil))
(defn ro?
[]
(:read-only @conf))
(defn get-event-queue-size
[]
(.size inventory-queue))
(defn load-inventory!
[]
(when (:store @conf)
(when-let [as (store/load-map (assoc (:store @conf) :key "apps"))]
(reset! apps as))))
(defn save-inventory
[]
(when (:store @conf)
(when-not (ro?)
(store/save-map (assoc (:store @conf) :key "apps") @apps))))
(defn post-event
[master ev]
(try
(http/post
(str "http://" master "/app/event")
{:content-type :json :body (generate-string {:event ev})})
true
(catch Exception e
false)))
(defn post-bulk
[master]
(try
(http/post
(str "http://" master "/app/events")
{:content-type :json :body (generate-string {:events @bulk})})
(reset! bulk nil)
true
(catch Exception e
false)))
(defn send-event
[master event]
(cond
(and (= 0 (.size inventory-queue)) (nil? @bulk))
(loop []
(when-not (post-event master event)
(Thread/sleep 60000)
(recur)))
(and (= 0 (.size inventory-queue)) (not (nil? @bulk)))
(do
(swap! bulk conj event)
(loop []
(when-not (post-bulk master)
(Thread/sleep 60000)
(recur))))
:else (if (nil? @bulk)
(reset! bulk [event])
(swap! bulk conj event))))
(defn tag-matcher
"Check if an entity group/resource match a tag"
[entity tag]
(if-not (:not tag)
(= (:value tag) ((keyword (:name tag)) entity))
(not (= (:value tag) ((keyword (:name tag)) entity)))))
(defn tags-matcher
"Check if an entity group/resource match the tags array"
[entity tags]
(if-not (= 0 (count tags))
(loop [tgs tags
m true]
(if m
(if-not (= 0 (count tgs))
(if (tag-matcher entity (first tgs))
(recur (next tgs) true)
false)
m)
false))
true))
(defn add-inventory-event
"add an event to update app inventory"
[ev]
(when (or
(not (ro?))
(not (nil? (get @conf :master nil))))
(.put inventory-queue ev)))
(defn- create-env!
"Create a new empty environment"
[env desc]
(swap! apps assoc (keyword env) {:description desc :app-tags {} :resource-tags {} :apps {}}))
(defn- update-env-tags!
[env tags type]
(doseq [tag tags]
(if-not (:delete tag)
(swap! apps assoc-in [(keyword env) type (keyword (:name tag))] (:value tag))
(swap! apps update-in [(keyword env) type] dissoc (keyword (:name tag))))))
(defn- update-env!
"Tag an environment with default app-tags and resource-tags"
[env app-tags resource-tags]
(update-env-tags! env (or app-tags []) :app-tags)
(update-env-tags! env (or resource-tags []) :resource-tags))
(defn- delete-env!
"Delete an environment"
[env]
(swap! apps dissoc (keyword env)))
(defn env-exists?
[env]
(not (nil? (get @apps (keyword env) nil))))
(defn get-env
[& [env]]
(if (nil? env)
(into [](keys @apps))
(dissoc (get @apps (keyword env)) :apps)))
(defn get-env-apps
[env]
(get-in @apps [(keyword env) :apps]))
(defn- update-app-tags!
[app env tags type]
(doseq [tag tags]
(if-not (:delete tag)
(if-not (:append tag)
(swap! apps assoc-in [(keyword env) :apps (keyword app) type (keyword (:name tag))] (:value tag))
(let [current-value (get-in @apps [(keyword env) :apps (keyword app) type (keyword (:name tag))])
updated-value (cond
(nil? current-value) (:value tag)
(or (string? current-value) (number? current-value))
(if-not (= (:value tag) current-value)
[current-value (:value tag)]
current-value)
(or (list? current-value) (vector? current-value))
(if-not (.contains current-value (:value tag))
(into [] (concat current-value [(:value tag)]))
current-value))]
(when-not (or (nil? updated-value) (= current-value updated-value))
(swap! apps assoc-in [(keyword env) :apps (keyword app) type (keyword (:name tag))] updated-value))))
(swap! apps update-in [(keyword env) :apps (keyword app) type] dissoc (keyword (:name tag))))))
(defn- update-app!
"Create or update an application"
[app env tags resource-tags]
(update-app-tags! app env (or tags []) :tags)
(update-app-tags! app env (or resource-tags []) :resource-tags))
(defn- delete-app!
"Delete an application"
[app env]
(swap! apps update-in [(keyword env) :apps] dissoc (keyword app)))
(defn get-app-resources
"Return resources associated to this app/env couple"
[app env]
(when-let [app-data (get-in @apps [(keyword env) :apps (keyword app)])]
(let [env-res-tags (get-in @apps [(keyword env) :resource-tags])
app-res-tags (:resource-tags app-data)]
(inventory/get-resources (into []
(map
(fn [[k v]]
{:name (name k) :value v})
(merge env-res-tags app-res-tags)))))))
(defn get-app-resources-tag-value
"Return specific tag of resources associated to this app (ex : FQDN)"
[app env tag]
(when-let [app-data (get-in @apps [(keyword env) :apps (keyword app)])]
(let [env-res-tags (get-in @apps [(keyword env) :resource-tags])
app-res-tags (:resource-tags app-data)]
(inventory/get-tag-value-from-resources tag (into []
(map
(fn [[k v]]
{:name (name k) :value v})
(merge env-res-tags app-res-tags)))))))
(defn exists?
[app env]
(not (nil? (get-in @apps [(keyword env) :apps (keyword app)] nil))))
(defn get-app
"Return an app"
[app env]
{:tags (get-in @apps [(keyword env) :apps (keyword app) :tags] {})
:tags-from-env (get-in @apps [(keyword env) :app-tags] {})
:resource-tags (get-in @apps [(keyword env) :apps (keyword app) :resource-tags] {})
:resource-tags-from-env (get-in @apps [(keyword env) :resource-tags] {})})
(defn get-app-tags
"Return tags of a specific app"
[app env]
{:tags (get-in @apps [(keyword env) :apps (keyword app) :tags] {})
:tags-from-env (get-in @apps [(keyword env) :app-tags] {})})
(defn get-app-resource-tags
"Return tags use to match resource"
[app env]
{:resource-tags (get-in @apps [(keyword env) :apps (keyword app) :resource-tags] {})
:resource-tags-from-env (get-in @apps [(keyword env) :resource-tags] {})})
(defn- app-systemctl
[app env action]
(let [resources (get-app-resources-tag-value app env (or (:lifecycle-tag @conf) "FQDN"))]
(log/info "[app-systemctl] will do" action "on" resources "for" app "on env" env)
(doseq [resource resources]
(caller/add-command {:commands [(str "systemctl " action " " app " --no-pager")]
:method :ssh
:hosts resource
:sudo true}))))
(defn submit-action
[app env action]
(condp = action
"start" (app-systemctl app env "start")
"stop" (app-systemctl app env "stop")
"restart" (app-systemctl app env "restart")
"reload" (app-systemctl app env "reload")
"status" (app-systemctl app env "status")
nil))
(defn update-app-with-ev!
[ev]
(when-not
(or (nil? (:app ev))
(str/includes? (name (:app ev)) " ")
(str/includes? (name (:app ev)) ";")
(str/includes? (name (:app ev)) "\"")
(str/includes? (name (:app ev)) "'"))
(if (:delete ev)
(delete-app! (:app ev) (:env ev))
(update-app! (:app ev) (:env ev) (:tags ev) (:resource-tags ev)))
(when (= 0 (.size inventory-queue))
(save-inventory)
(u/fsync "app"))))
(defn update-env-with-ev!
[ev]
(if (:create ev)
(create-env! (:env ev) (:description ev))
(if (:delete ev)
(delete-env! (:env ev))
(update-env! (:env ev) (:app-tags ev) (:resource-tags ev))))
(when (= 0 (.size inventory-queue))
(save-inventory)
(u/fsync "app")))
(defn- update-inventory!
"generic inventory update"
[ev]
(if-not (ro?)
(condp = (:type ev)
"app" (update-app-with-ev! ev)
"env" (update-env-with-ev! ev))
(when-let [master (get @conf :master nil)]
(send-event master ev))))
(defn- start-inventory-consumer!
[]
(u/start-thread!
(when-let [ev (.take inventory-queue)]
(update-inventory! ev)))
"Inventory apps Consumer"))
(defn start!
[]
(if (or
(not (ro?))
(and (ro?)
(not (nil? (get @conf :master)))))
[(start-inventory-consumer!)]
[]))
(defn configure!
[inventory-conf]
(reset! conf inventory-conf)
(load-inventory!))
|
29f409655e8406442362a49f92adcc374f3058cf1044ab5078c74c20965f35f2 | engineyard/vertebra-erl | uuid_server.erl | Copyright 2008 , Engine Yard , Inc.
%
This file is part of Vertebra .
%
Vertebra is free software : you can redistribute it and/or modify it under the
% terms of the GNU Lesser General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
% later version.
%
Vertebra 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 Vertebra . If not , see < / > .
-module(uuid_server).
-behaviour(gen_server).
%% API
-export([start_link/0, generate_uuid/0, new_stanza_id/0]).
-export([cache_size/0, uuid_generator/1, uuid_generator/2, shutdown/0]).
-define(SERVER, ?MODULE).
-define(CACHE_SIZE, 100).
-define(REFILL_THRESHOLD, 10).
-define(MAX_STARTING_PACKET_ID, 1000).
-define(MAX_PACKET_ID, 1000000).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state,
{cache,
worker_running}).
generate_uuid() ->
conditional_start(),
gen_server:call({global, ?SERVER}, gen_uuid).
cache_size() ->
conditional_start(),
gen_server:call({global, ?SERVER}, cache_size).
new_stanza_id() ->
conditional_start(),
gen_server:call({global, ?SERVER}, new_stanza_id).
shutdown() ->
gen_server:call({global, ?SERVER}, shutdown).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
%% Description: Starts the server
%%--------------------------------------------------------------------
start_link() ->
gen_server:start_link({global, ?SERVER}, ?MODULE, [], []).
%%====================================================================
%% gen_server callbacks
%%====================================================================
%%--------------------------------------------------------------------
%% Function: init(Args) -> {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%% Description: Initiates the server
%%--------------------------------------------------------------------
init([]) ->
crypto:start(),
{ok, #state{cache=[], worker_running=fill_cache(0)}}.
%%--------------------------------------------------------------------
Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
%% Description: Handling call messages
%%--------------------------------------------------------------------
handle_call(shutdown, _From, State) ->
{stop, normal, State};
handle_call(new_stanza_id, _From, State) ->
{reply, new_packet_id(), State};
handle_call(cache_size, _From, State) ->
{reply, length(State#state.cache), State};
handle_call(gen_uuid, _From, State) ->
case length(State#state.cache) == 0 of
true ->
{reply, gen(), State};
false ->
{Retval, NewState} = fetch_uuid(State),
{reply, Retval, NewState}
end;
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
%%--------------------------------------------------------------------
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling cast messages
%%--------------------------------------------------------------------
handle_cast({update_cache, Entries}, State) ->
{noreply, State#state{worker_running=false, cache=lists:append(State#state.cache, Entries)}};
handle_cast(_Msg, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
handle_info(_Info, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
%% Function: terminate(Reason, State) -> void()
%% Description: This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any necessary
%% cleaning up. When it returns, the gen_server terminates with Reason.
%% The return value is ignored.
%%--------------------------------------------------------------------
terminate(_Reason, _State) ->
ok.
%%--------------------------------------------------------------------
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
%% Description: Convert process state when code is changed
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
fetch_uuid(State) ->
[H|T] = State#state.cache,
if
State#state.worker_running == true ->
{H, State#state{cache=T}};
true ->
{H, State#state{cache=T, worker_running=fill_cache(length(State#state.cache))}}
end.
fill_cache(CacheSize) ->
case ?CACHE_SIZE - CacheSize > ?REFILL_THRESHOLD of
true ->
F = fun() -> uuid_generator(round((?CACHE_SIZE - CacheSize) * 1.5)) end,
spawn(F),
spawn(F),
true;
false ->
false
end.
uuid_generator(Count) ->
uuid_generator(Count, []).
uuid_generator(0, Accum) ->
gen_server:cast(?SERVER, {update_cache, Accum});
uuid_generator(Count, Accum) ->
uuid_generator(Count - 1, lists:append(Accum, [gen()])).
%%-------------------------------------------------
%
% gen() -> uid
%
uid - > string ( 32 chars long )
%
% TODO: Add a node component to the uuid
% to guarantee uniqueness across hosts
%%-------------------------------------------------
gen() ->
% Figure out how many bytes to randomly skip
SkipSize = round_to_byte(crypto:rand_uniform(0, 32)),
% Determine the number of bytes needed to generate this uuid
PoolSize = round((96 + (SkipSize * 2)) / 8),
Pool = crypto:rand_bytes(PoolSize),
Extract the first , middle , last chunks of the uuid from the pool
% making sure to skip where needed
<<F:32/integer,_:SkipSize,M:32/integer,_:SkipSize,L:32/integer>> = Pool,
% Convert all the chunks and the current timestamp to a uuid
lists:flatten(to_hex(F) ++ to_hex(M) ++ to_hex(L) ++ get_time()).
round_to_byte(N) ->
if
N < 9 ->
8;
N < 17 ->
16;
N < 25 ->
24;
true ->
32
end.
get_time() ->
{_, _, T} = now(),
to_hex_pad(T).
to_hex(N) ->
lists:flatten(io_lib:format("~8.16.0b", [N])).
to_hex_pad(N) ->
lists:flatten(io_lib:format("~8.16.0b", [N])).
conditional_start() ->
case global:whereis_name(?SERVER) of
undefined ->
uuid_server:start_link();
_ ->
ok
end.
new_packet_id() ->
case erlang:get(vertebra_iq_id) of
undefined ->
Id = crypto:rand_uniform(1, ?MAX_STARTING_PACKET_ID),
erlang:put(vertebra_iq_id, Id),
integer_to_list(Id);
Value ->
Id = Value + 1,
if
Id > ?MAX_PACKET_ID ->
new_packet_id();
true ->
erlang:put(vertebra_iq_id, Id),
integer_to_list(Id)
end
end.
| null | https://raw.githubusercontent.com/engineyard/vertebra-erl/cf6e7c84f6dfbf2e31f19c47e9db112ae292ec27/lib/vertebra/src/uuid_server.erl | erlang |
terms of the GNU Lesser General Public License as published by the Free
later version.
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
API
gen_server callbacks
====================================================================
API
====================================================================
--------------------------------------------------------------------
Description: Starts the server
--------------------------------------------------------------------
====================================================================
gen_server callbacks
====================================================================
--------------------------------------------------------------------
Function: init(Args) -> {ok, State} |
ignore |
{stop, Reason}
Description: Initiates the server
--------------------------------------------------------------------
--------------------------------------------------------------------
% handle_call(Request , From , State ) - > { reply , Reply , State } |
{stop, Reason, Reply, State} |
{stop, Reason, State}
Description: Handling call messages
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
Description: Handling cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
Description: Handling all non call/cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: terminate(Reason, State) -> void()
Description: This function is called by a gen_server when it is about to
terminate. It should be the opposite of Module:init/1 and do any necessary
cleaning up. When it returns, the gen_server terminates with Reason.
The return value is ignored.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Convert process state when code is changed
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------
gen() -> uid
TODO: Add a node component to the uuid
to guarantee uniqueness across hosts
-------------------------------------------------
Figure out how many bytes to randomly skip
Determine the number of bytes needed to generate this uuid
making sure to skip where needed
Convert all the chunks and the current timestamp to a uuid | Copyright 2008 , Engine Yard , Inc.
This file is part of Vertebra .
Vertebra is free software : you can redistribute it and/or modify it under the
Software Foundation , either version 3 of the License , or ( at your option ) any
Vertebra is distributed in the hope that it will be useful , but WITHOUT ANY
You should have received a copy of the GNU Lesser General Public License
along with Vertebra . If not , see < / > .
-module(uuid_server).
-behaviour(gen_server).
-export([start_link/0, generate_uuid/0, new_stanza_id/0]).
-export([cache_size/0, uuid_generator/1, uuid_generator/2, shutdown/0]).
-define(SERVER, ?MODULE).
-define(CACHE_SIZE, 100).
-define(REFILL_THRESHOLD, 10).
-define(MAX_STARTING_PACKET_ID, 1000).
-define(MAX_PACKET_ID, 1000000).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state,
{cache,
worker_running}).
generate_uuid() ->
conditional_start(),
gen_server:call({global, ?SERVER}, gen_uuid).
cache_size() ->
conditional_start(),
gen_server:call({global, ?SERVER}, cache_size).
new_stanza_id() ->
conditional_start(),
gen_server:call({global, ?SERVER}, new_stanza_id).
shutdown() ->
gen_server:call({global, ?SERVER}, shutdown).
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
start_link() ->
gen_server:start_link({global, ?SERVER}, ?MODULE, [], []).
{ ok , State , Timeout } |
init([]) ->
crypto:start(),
{ok, #state{cache=[], worker_running=fill_cache(0)}}.
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call(shutdown, _From, State) ->
{stop, normal, State};
handle_call(new_stanza_id, _From, State) ->
{reply, new_packet_id(), State};
handle_call(cache_size, _From, State) ->
{reply, length(State#state.cache), State};
handle_call(gen_uuid, _From, State) ->
case length(State#state.cache) == 0 of
true ->
{reply, gen(), State};
false ->
{Retval, NewState} = fetch_uuid(State),
{reply, Retval, NewState}
end;
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_cast({update_cache, Entries}, State) ->
{noreply, State#state{worker_running=false, cache=lists:append(State#state.cache, Entries)}};
handle_cast(_Msg, State) ->
{noreply, State}.
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
fetch_uuid(State) ->
[H|T] = State#state.cache,
if
State#state.worker_running == true ->
{H, State#state{cache=T}};
true ->
{H, State#state{cache=T, worker_running=fill_cache(length(State#state.cache))}}
end.
fill_cache(CacheSize) ->
case ?CACHE_SIZE - CacheSize > ?REFILL_THRESHOLD of
true ->
F = fun() -> uuid_generator(round((?CACHE_SIZE - CacheSize) * 1.5)) end,
spawn(F),
spawn(F),
true;
false ->
false
end.
uuid_generator(Count) ->
uuid_generator(Count, []).
uuid_generator(0, Accum) ->
gen_server:cast(?SERVER, {update_cache, Accum});
uuid_generator(Count, Accum) ->
uuid_generator(Count - 1, lists:append(Accum, [gen()])).
uid - > string ( 32 chars long )
gen() ->
SkipSize = round_to_byte(crypto:rand_uniform(0, 32)),
PoolSize = round((96 + (SkipSize * 2)) / 8),
Pool = crypto:rand_bytes(PoolSize),
Extract the first , middle , last chunks of the uuid from the pool
<<F:32/integer,_:SkipSize,M:32/integer,_:SkipSize,L:32/integer>> = Pool,
lists:flatten(to_hex(F) ++ to_hex(M) ++ to_hex(L) ++ get_time()).
round_to_byte(N) ->
if
N < 9 ->
8;
N < 17 ->
16;
N < 25 ->
24;
true ->
32
end.
get_time() ->
{_, _, T} = now(),
to_hex_pad(T).
to_hex(N) ->
lists:flatten(io_lib:format("~8.16.0b", [N])).
to_hex_pad(N) ->
lists:flatten(io_lib:format("~8.16.0b", [N])).
conditional_start() ->
case global:whereis_name(?SERVER) of
undefined ->
uuid_server:start_link();
_ ->
ok
end.
new_packet_id() ->
case erlang:get(vertebra_iq_id) of
undefined ->
Id = crypto:rand_uniform(1, ?MAX_STARTING_PACKET_ID),
erlang:put(vertebra_iq_id, Id),
integer_to_list(Id);
Value ->
Id = Value + 1,
if
Id > ?MAX_PACKET_ID ->
new_packet_id();
true ->
erlang:put(vertebra_iq_id, Id),
integer_to_list(Id)
end
end.
|
02fa120caeb9b7f2944c0603520027be36daa7c67135d36c90f44f5a4fc7744a | ocamllabs/ocaml-modular-implicits | t210-setfield0.ml | open Lib;;
type t = {
mutable a : int;
};;
let x = {a = 7} in
x.a <- 11;
if x.a <> 11 then raise Not_found;
x
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 CONSTINT 7
11 MAKEBLOCK1 0
13 PUSHCONSTINT 11
15 PUSHACC1
16 SETFIELD0
17 CONSTINT 11
19 PUSHACC1
20 GETFIELD0
21 NEQ
22 BRANCHIFNOT 29
24 Not_found
26 MAKEBLOCK1 0
28 RAISE
29 ACC0
30 POP 1
32 ATOM0
33 SETGLOBAL T210 - setfield0
35 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 CONSTINT 7
11 MAKEBLOCK1 0
13 PUSHCONSTINT 11
15 PUSHACC1
16 SETFIELD0
17 CONSTINT 11
19 PUSHACC1
20 GETFIELD0
21 NEQ
22 BRANCHIFNOT 29
24 GETGLOBAL Not_found
26 MAKEBLOCK1 0
28 RAISE
29 ACC0
30 POP 1
32 ATOM0
33 SETGLOBAL T210-setfield0
35 STOP
**)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/tool-ocaml/t210-setfield0.ml | ocaml | open Lib;;
type t = {
mutable a : int;
};;
let x = {a = 7} in
x.a <- 11;
if x.a <> 11 then raise Not_found;
x
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 CONSTINT 7
11 MAKEBLOCK1 0
13 PUSHCONSTINT 11
15 PUSHACC1
16 SETFIELD0
17 CONSTINT 11
19 PUSHACC1
20 GETFIELD0
21 NEQ
22 BRANCHIFNOT 29
24 Not_found
26 MAKEBLOCK1 0
28 RAISE
29 ACC0
30 POP 1
32 ATOM0
33 SETGLOBAL T210 - setfield0
35 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 CONSTINT 7
11 MAKEBLOCK1 0
13 PUSHCONSTINT 11
15 PUSHACC1
16 SETFIELD0
17 CONSTINT 11
19 PUSHACC1
20 GETFIELD0
21 NEQ
22 BRANCHIFNOT 29
24 GETGLOBAL Not_found
26 MAKEBLOCK1 0
28 RAISE
29 ACC0
30 POP 1
32 ATOM0
33 SETGLOBAL T210-setfield0
35 STOP
**)
| |
b3e19ac6a5f1c0a0e68d3299637ef30cb001afc1ce211d1ae5ac05c307b44f65 | kiranlak/austin-sbst | checkUnsupportedFeatures.ml | Copyright : , University College London , 2011
open Cil
class unsupportedVisitor (found:bool ref) = object
inherit nopCilVisitor
method vfunc (f:fundec) =
if (startsWith "Austin__" f.svar.vname) then SkipChildren
else DoChildren
method vinst (i:instr) =
match i with
| Call(_,f,_,_) ->
(
match (stripCasts f) with
| Lval(l) ->
(
match l with
| Var vi, _ ->
if vi.vname = "longjmp" || vi.vname = "setjmp" then (
found := true;
SkipChildren
) else
DoChildren
| _ -> DoChildren
)
| _ -> DoChildren
)
| _ -> DoChildren
end
let hasUnsupportedFeature (source:file) =
let found = ref false in
let vis = new unsupportedVisitor found in
visitCilFileSameGlobals vis source;
!found
| null | https://raw.githubusercontent.com/kiranlak/austin-sbst/9c8aac72692dca952302e0e4fdb9ff381bba58ae/AustinOcaml/instrumentation/checkUnsupportedFeatures.ml | ocaml | Copyright : , University College London , 2011
open Cil
class unsupportedVisitor (found:bool ref) = object
inherit nopCilVisitor
method vfunc (f:fundec) =
if (startsWith "Austin__" f.svar.vname) then SkipChildren
else DoChildren
method vinst (i:instr) =
match i with
| Call(_,f,_,_) ->
(
match (stripCasts f) with
| Lval(l) ->
(
match l with
| Var vi, _ ->
if vi.vname = "longjmp" || vi.vname = "setjmp" then (
found := true;
SkipChildren
) else
DoChildren
| _ -> DoChildren
)
| _ -> DoChildren
)
| _ -> DoChildren
end
let hasUnsupportedFeature (source:file) =
let found = ref false in
let vis = new unsupportedVisitor found in
visitCilFileSameGlobals vis source;
!found
| |
70be9e58003ee00bda100de645d3660e933622310dfcef68074d65806744906b | mbj/mhs | CBT.hs | module CBT
( CBT.Config
, CBT.Env
, CBT.loadDefaultConfig
, Environment(..)
, runDefaultEnvironment
)
where
import CBT.Prelude
import qualified CBT.Config as CBT
import qualified MRIO.Log as Log
data Environment = Environment
{ cbtConfig :: CBT.Config
, logAction :: Log.Action
}
runDefaultEnvironment
:: MonadUnliftIO m
=> RIO Environment a
-> m a
runDefaultEnvironment action = do
cbtConfig <- CBT.loadDefaultConfig
runRIO Environment{logAction = Log.defaultCLIAction, ..} action
| null | https://raw.githubusercontent.com/mbj/mhs/703bf13f973cb89c983b5c79ae18b71447b04d18/cbt/src/CBT.hs | haskell | module CBT
( CBT.Config
, CBT.Env
, CBT.loadDefaultConfig
, Environment(..)
, runDefaultEnvironment
)
where
import CBT.Prelude
import qualified CBT.Config as CBT
import qualified MRIO.Log as Log
data Environment = Environment
{ cbtConfig :: CBT.Config
, logAction :: Log.Action
}
runDefaultEnvironment
:: MonadUnliftIO m
=> RIO Environment a
-> m a
runDefaultEnvironment action = do
cbtConfig <- CBT.loadDefaultConfig
runRIO Environment{logAction = Log.defaultCLIAction, ..} action
| |
9138e82d30b07b63803d23f2594d1bec5740d505562b6d170f90bb6014488347 | petelliott/pscheme | base.scm | (import (scheme base)
(pscheme test))
6.1 : Equivalence predicates
(define-test "eqv?"
;; true cases
(assert (eqv? #t #t))
(assert (eqv? #f #f))
(assert (eqv? 'hello 'hello))
(assert (eqv? (+ 1 2) (+ 1 2)))
;; TODO: non-fixnums
(assert (eqv? #\a #\a))
(assert (eqv? '() '()))
(define a '(1 2 3))
(assert (eqv? a a))
(define b "hello world")
(assert (eqv? b b))
TODO : vectors , bytevectors , records
(define (f x) x)
(assert (eqv? f f))
;; false cases
(assert (not (eqv? 1 '())))
(assert (not (eqv? #t #f)))
(assert (not (eqv? 'hello 'world)))
;; TODO: exact vs inexact
(assert (not (eqv? 1 2)))
;; TODO: NaN
(assert (not (eqv? #\a #\b)))
(assert (not (eqv? '() 8)))
(assert (not (eqv? '(1 2 3) '(1 2 3))))
(assert (not (eqv? "hello world" "hello world"))))
(define-test "eq?"
;; true cases
(assert (eq? #t #t))
(assert (eq? #f #f))
(assert (eq? 'hello 'hello))
(assert (eq? '() '()))
(define a '(1 2 3))
(assert (eq? a a))
(define b "hello world")
(assert (eq? b b))
TODO : vectors , bytevectors , records
(define (f x) x)
(assert (eq? f f))
;; false cases
(assert (not (eq? 1 '())))
(assert (not (eq? #t #f)))
(assert (not (eq? 'hello 'world)))
(assert (not (eq? '() 8)))
(assert (not (eq? '(1 2 3) '(1 2 3))))
(assert (not (eq? "hello world" "hello world"))))
(define-test "equal?"
;; true cases
(assert (equal? 'a 'a))
(assert (equal? '(a) '(a)))
(assert (equal? '(a (b) c) '(a (b) c)))
(assert (equal? "abc" "abc"))
(assert (equal? 2 2))
(assert (equal? (vector) (vector)))
(assert (equal? (vector 5 'a) (vector 5 'a)))
;; TODO: circular forms
(assert (not (equal? 'a 'b)))
(assert (not (equal? '(a) '(b))))
(assert (not (equal? '(a (b) c) '(a (d) c))))
(assert (not (equal? "abc" "abcd")))
(assert (not (equal? 2 3)))
(assert (not (equal? (vector 5 'a) (vector 5 'b)))))
6.2 : Numbers
(define-test "all number tests lol" SKIP)
6.3 : Booleans
(define-test "not"
(assert (not #f))
(assert (not (not #t))))
(define-test "boolean?"
(assert (boolean? #t))
(assert (boolean? #f))
(assert (not (boolean? '())))
(assert (not (boolean? 0))))
(define-test "boolean=?"
(assert (boolean=? #t #t #t))
(assert (boolean=? #f #f #f))
(assert (not (boolean=? #f #t #f))))
6.4 : Pairs and lists
(define-test "pair?"
(assert (pair? '(1 . 2)))
(assert (pair? '(1 2 3 4 5)))
(assert (not (pair? '()))))
(define-test "cons"
(assert (pair? (cons 1 2)))
(assert (equal? (cons 1 2) '(1 . 2)))
(assert (equal? (cons 1 '(2 3)) '(1 2 3))))
(define-test "car"
(assert (equal? (car '(1 . 2)) 1))
(assert (equal? (car '((1) 2 3)) '(1))))
(define-test "cdr"
(assert (equal? (cdr '(1 . 2)) 2))
(assert (equal? (cdr '((1) 2 3)) '(2 3))))
(define-test "set-car!"
(define a '(1 2 3))
(assert (equal? (car a) 1))
(set-car! a 8)
(assert (equal? (car a) 8)))
(define-test "set-cdr!"
(define a '(1 2 3))
(assert (equal? (cdr a) '(2 3)))
(set-cdr! a 8)
(assert (equal? (cdr a) 8)))
(define-test "caar"
(assert (equal? (caar '((1 . 2) . (3 . 4))) 1)))
(define-test "cadr"
(assert (equal? (cadr '((1 . 2) . (3 . 4))) 3)))
(define-test "cdar"
(assert (equal? (cdar '((1 . 2) . (3 . 4))) 2)))
(define-test "cddr"
(assert (equal? (cddr '((1 . 2) . (3 . 4))) 4)))
(define-test "null?"
(assert (null? '()))
(assert (not (null? '(1)))))
(define-test "list?"
(assert (list? '(a b c)))
(assert (list? '()))
(assert (not (list? '(a . b))))
(assert (not (list? 5))))
(define-test "make-list"
(assert (equal? (make-list 0) '()))
(assert (equal? (length (make-list 5)) 5))
(assert (equal? (make-list 0 '(a)) '()))
(assert (equal? (make-list 5 '(a)) '((a) (a) (a) (a) (a)))))
(define-test "list"
(assert (equal? (list) '()))
(assert (equal? (list 1 2 (+ 1 2)) '(1 2 3))))
(define-test "length"
(assert (equal? (length '(1 2 3 4)) 4))
(assert (equal? (length '()) 0)))
(define-test "append"
(assert (equal? (append '(1 2 3 4) '()) '(1 2 3 4)))
(assert (equal? (append '() '(1 2 3 4)) '(1 2 3 4)))
(assert (equal? (append '(1 2) '(3 4)) '(1 2 3 4))))
(define-test "reverse"
(assert (equal? (reverse '()) '()))
(assert (equal? (reverse '(1 2 3 4)) '(4 3 2 1))))
(define-test "list-tail"
(assert (equal? (list-tail '(1 2 3 4) 0) '(1 2 3 4)))
(assert (equal? (list-tail '(1 2 3 4) 2) '(3 4)))
(assert (equal? (list-tail '(1 2 3 4) 4) '())))
(define-test "list-ref"
(assert (equal? (list-ref '(1 2 3 4) 0) 1))
(assert (equal? (list-ref '(1 2 3 4) 1) 2))
(assert (equal? (list-ref '(1 2 3 4) 2) 3))
(assert (equal? (list-ref '(1 2 3 4) 3) 4)))
(define-test "list-set!"
(define a '(1 2 3 4))
(assert (equal? a '(1 2 3 4)))
(list-set! a 1 5)
(assert (equal? a '(1 5 3 4))))
(define-test "memq"
(assert (equal? (memq 'a '(a b c)) '(a b c)))
(assert (equal? (memq 'b '(a b c)) '(b c)))
(assert (equal? (memq 'd '(a b c)) #f)))
(define-test "memv"
(assert (equal? (memv 'a '(a b c)) '(a b c)))
(assert (equal? (memv 'b '(a b c)) '(b c)))
(assert (equal? (memv 'd '(a b c)) #f)))
(define-test "member"
(assert (equal? (member '(a) '((a) (b) (c))) '((a) (b) (c))))
(assert (equal? (member '(b) '((a) (b) (c))) '((b) (c))))
(assert (equal? (member '(d) '((a) (b) (c))) #f))
(assert (equal? (member 'a '() (lambda (i x) #t)) #f))
(assert (equal? (member 'a '(1 2 3) (lambda (i x) #t)) '(1 2 3))))
(define-test "assq"
(assert (equal? (assq 'a '((a . 1) (b . 2))) '(a . 1)))
(assert (equal? (assq 'b '((a . 1) (b . 2))) '(b . 2)))
(assert (equal? (assq 'c '((a . 1) (b . 2))) #f)))
(define-test "assv"
(assert (equal? (assv 'a '((a . 1) (b . 2))) '(a . 1)))
(assert (equal? (assv 'b '((a . 1) (b . 2))) '(b . 2)))
(assert (equal? (assv 'c '((a . 1) (b . 2))) #f)))
(define-test "assoc"
(assert (equal? (assoc '(a) '(((a) . 1) ((b) . 2))) '((a) . 1)))
(assert (equal? (assoc '(b) '(((a) . 1) ((b) . 2))) '((b) . 2)))
(assert (equal? (assoc '(c) '(((a) . 1) ((b) . 2))) #f))
(assert (equal? (assoc 'c '() (lambda (i x) #t)) #f))
(assert (equal? (assoc 'c '((a . 1) (b . 2)) (lambda (i x) #t)) '(a . 1))))
(define-test "list-copy"
(define a '(1 2 3))
(define b (list-copy a))
(assert (not (eq? a b)))
(assert (equal? a b)))
6.5 : Symbols
(define-test "symbol?"
(assert (symbol? 'hello))
(assert (not (symbol? "hello")))
(assert (not (symbol? 5))))
(define-test "symbol->string"
(assert (string? (symbol->string 'hello)))
(assert (equal? (symbol->string 'hello) "hello")))
(define-test "string->symbol"
(assert (symbol? (string->symbol "hello")))
(assert (eq? (string->symbol "hello") 'hello)))
6.7 : Strings
(define-test "string?"
(assert (string? "hello world")))
(define-test "make-string"
(assert (string? (make-string 10)))
(assert (string? (make-string 10 #\a)))
(assert (equal? "aaa" (make-string 3 #\a))))
(define-test "string"
(assert (string? (string #\a #\b #\c)))
(assert (equal? "abc" (string #\a #\b #\c))))
(define-test "string-length"
(assert (equal? (string-length "123456") 6)))
(define-test "string-ref"
(assert (equal? (string-ref "0123" 0) #\0))
(assert (equal? (string-ref "0123" 1) #\1))
(assert (equal? (string-ref "0123" 2) #\2))
(assert (equal? (string-ref "0123" 3) #\3)))
6.8 : Vectors
(define-test "vector?"
(assert (vector? (make-vector 0)))
(assert (not (vector? '()))))
(define-test "make-vector"
(define v (make-vector 5 8))
(assert (vector? v))
(assert (equal? (vector-length v) 5))
(assert (equal? (vector-ref v 4) 8)))
(define-test "vector"
(define v (vector 'a 'b 'c))
(assert (vector? v))
(assert (equal? (vector-length v) 3))
(assert (eq? (vector-ref v 0) 'a))
(assert (eq? (vector-ref v 1) 'b))
(assert (eq? (vector-ref v 2) 'c)))
(define-test "list->vector"
(define l '(1 () (1 2 3) a))
(assert (vector? (list->vector l)))
(assert (list? (vector->list (list->vector l))))
(assert (equal? (vector-length (list->vector '())) 0))
(assert (equal? (vector-length (list->vector l)) 4))
(assert (equal? (vector->list (list->vector l)) l)))
(define-test "vector->list"
(define v (vector 1 '() 'a))
(define l0 (vector->list v 2 2))
(define l1 (vector->list v 1 2))
(define l2 (vector->list v 1))
(assert (list? l0))
(assert (equal? l0 '()))
(assert (list? l1))
(assert (equal? l1 '(())))
(assert (list? l2))
(assert (equal? l2 '(() a))))
(define-test "vector->string"
(define v (vector #\h #\e #\l #\l #\o))
(assert (equal? (vector->string v) "hello"))
(assert (equal? (vector->string v 2) "llo"))
(assert (equal? (vector->string v 1 4) "ell")))
(define-test "string->vector"
(define s "hello")
(assert (equal? (string->vector s) (vector #\h #\e #\l #\l #\o)))
(assert (equal? (string->vector s 2) (vector #\l #\l #\o)))
(assert (equal? (string->vector s 1 4) (vector #\e #\l #\l))))
(define-test "vector-copy"
(define v (vector #\h #\e #\l #\l #\o))
(assert (equal? (vector-copy v) (vector #\h #\e #\l #\l #\o)))
(assert (equal? (vector-copy v 2) (vector #\l #\l #\o)))
(assert (equal? (vector-copy v 1 4) (vector #\e #\l #\l))))
(define-test "vector-copy!"
(define v1 (vector 1 2 3 4 5))
(define v2 (vector 'a 'b 'c 'd 'e))
(assert (equal? (vector-copy! v2 1 v1 1 4) (vector 'a 2 3 4 'e)))
(assert (equal? v2 (vector 'a 2 3 4 'e)))
(assert (equal? (vector-copy! v2 0 v1) (vector 1 2 3 4 5)))
(assert (equal? v2 (vector 1 2 3 4 5))))
(define-test "vector-append"
(assert (equal? (vector-append (vector) (vector 1 2) (vector 3 4)) (vector 1 2 3 4))))
(define-test "vector-fill!"
(define v1 (vector 1 2 3 4 5))
(vector-fill! v1 '(1))
(assert (equal? v1 (vector '(1) '(1) '(1) '(1) '(1)))))
7.3 : Derived expression types
(define-test "cond"
(assert (equal? (cond (#t 1) (#t 2) (#t 3)) 1))
(assert (equal? (cond (#f 1) (8 2) (#t 3)) 2))
(assert (equal? (cond (#f 1) (#f 2) ('() 3)) 3))
(assert (equal? (cond (#f 1) (#f 2) (#f 3)) (begin)))
(assert (equal? (cond (#f 1) (#f 2) (#t 3) (else 4)) 3))
(assert (equal? (cond (#f 1) (#f 2) (#f 3) (else 4)) 4))
(assert (equal? (cond (#f 1) ((+ 1 2) => (lambda (a) (+ a 5)))) 8)))
(define-test "case"
(assert (equal? (case (+ 1 2) ((2) 1) ((4 3 8) 2) (else 3)) 2))
(assert (equal? (case (+ 1 64) ((2) 1) ((4 3 8) 2) (else 3)) 3)))
(define-test "and"
(assert (equal? (and 7 8 (+ 1 2)) 3))
(assert (equal? (and 7 #f (+ 1 2)) #f))
(assert (equal? (and 1) 1))
(assert (equal? (and) #t)))
(define-test "or"
(assert (equal? (or 7 8 (+ 1 2)) 7))
(assert (equal? (or #f #f (+ 1 2)) 3))
(assert (equal? (or 1) 1))
(assert (equal? (or) #f)))
(define-test "when"
(assert (equal? (when #t 1 2 (+ 1 2)) 3))
(assert (equal? (when #f 1 2 (+ 1 2)) (begin))))
(define-test "unless"
(assert (equal? (unless #t 1 2 (+ 1 2)) (begin)))
(assert (equal? (unless #f 1 2 (+ 1 2)) 3)))
(define-test "let"
(assert (equal? (let ((a (+ 1 2))) 1 a) 3))
(assert (equal? (let ((a 1) (b 2)) (+ a b)) 3)))
(define-test "let*"
(assert (equal? (let* ((a (+ 1 2))) 1 a) 3))
(assert (equal? (let* ((a 1) (b (+ a 1))) (+ a b)) 3)))
(define-test "letrec" SKIP)
(define-test "letrec*" SKIP)
(define-test "let-values" SKIP)
(define-test "let*-values" SKIP)
(define-test "define-values" SKIP)
(define-test "do" SKIP)
(define-test "promises" SKIP)
(define-test "parameters" SKIP)
(define-test "guard" SKIP)
(define-test "cond-expand" SKIP)
(finish-tests)
| null | https://raw.githubusercontent.com/petelliott/pscheme/2f887315d9f667ed4c15f4fcc7bcbfc873aa74c9/test/lib/scheme/base.scm | scheme | true cases
TODO: non-fixnums
false cases
TODO: exact vs inexact
TODO: NaN
true cases
false cases
true cases
TODO: circular forms | (import (scheme base)
(pscheme test))
6.1 : Equivalence predicates
(define-test "eqv?"
(assert (eqv? #t #t))
(assert (eqv? #f #f))
(assert (eqv? 'hello 'hello))
(assert (eqv? (+ 1 2) (+ 1 2)))
(assert (eqv? #\a #\a))
(assert (eqv? '() '()))
(define a '(1 2 3))
(assert (eqv? a a))
(define b "hello world")
(assert (eqv? b b))
TODO : vectors , bytevectors , records
(define (f x) x)
(assert (eqv? f f))
(assert (not (eqv? 1 '())))
(assert (not (eqv? #t #f)))
(assert (not (eqv? 'hello 'world)))
(assert (not (eqv? 1 2)))
(assert (not (eqv? #\a #\b)))
(assert (not (eqv? '() 8)))
(assert (not (eqv? '(1 2 3) '(1 2 3))))
(assert (not (eqv? "hello world" "hello world"))))
(define-test "eq?"
(assert (eq? #t #t))
(assert (eq? #f #f))
(assert (eq? 'hello 'hello))
(assert (eq? '() '()))
(define a '(1 2 3))
(assert (eq? a a))
(define b "hello world")
(assert (eq? b b))
TODO : vectors , bytevectors , records
(define (f x) x)
(assert (eq? f f))
(assert (not (eq? 1 '())))
(assert (not (eq? #t #f)))
(assert (not (eq? 'hello 'world)))
(assert (not (eq? '() 8)))
(assert (not (eq? '(1 2 3) '(1 2 3))))
(assert (not (eq? "hello world" "hello world"))))
(define-test "equal?"
(assert (equal? 'a 'a))
(assert (equal? '(a) '(a)))
(assert (equal? '(a (b) c) '(a (b) c)))
(assert (equal? "abc" "abc"))
(assert (equal? 2 2))
(assert (equal? (vector) (vector)))
(assert (equal? (vector 5 'a) (vector 5 'a)))
(assert (not (equal? 'a 'b)))
(assert (not (equal? '(a) '(b))))
(assert (not (equal? '(a (b) c) '(a (d) c))))
(assert (not (equal? "abc" "abcd")))
(assert (not (equal? 2 3)))
(assert (not (equal? (vector 5 'a) (vector 5 'b)))))
6.2 : Numbers
(define-test "all number tests lol" SKIP)
6.3 : Booleans
(define-test "not"
(assert (not #f))
(assert (not (not #t))))
(define-test "boolean?"
(assert (boolean? #t))
(assert (boolean? #f))
(assert (not (boolean? '())))
(assert (not (boolean? 0))))
(define-test "boolean=?"
(assert (boolean=? #t #t #t))
(assert (boolean=? #f #f #f))
(assert (not (boolean=? #f #t #f))))
6.4 : Pairs and lists
(define-test "pair?"
(assert (pair? '(1 . 2)))
(assert (pair? '(1 2 3 4 5)))
(assert (not (pair? '()))))
(define-test "cons"
(assert (pair? (cons 1 2)))
(assert (equal? (cons 1 2) '(1 . 2)))
(assert (equal? (cons 1 '(2 3)) '(1 2 3))))
(define-test "car"
(assert (equal? (car '(1 . 2)) 1))
(assert (equal? (car '((1) 2 3)) '(1))))
(define-test "cdr"
(assert (equal? (cdr '(1 . 2)) 2))
(assert (equal? (cdr '((1) 2 3)) '(2 3))))
(define-test "set-car!"
(define a '(1 2 3))
(assert (equal? (car a) 1))
(set-car! a 8)
(assert (equal? (car a) 8)))
(define-test "set-cdr!"
(define a '(1 2 3))
(assert (equal? (cdr a) '(2 3)))
(set-cdr! a 8)
(assert (equal? (cdr a) 8)))
(define-test "caar"
(assert (equal? (caar '((1 . 2) . (3 . 4))) 1)))
(define-test "cadr"
(assert (equal? (cadr '((1 . 2) . (3 . 4))) 3)))
(define-test "cdar"
(assert (equal? (cdar '((1 . 2) . (3 . 4))) 2)))
(define-test "cddr"
(assert (equal? (cddr '((1 . 2) . (3 . 4))) 4)))
(define-test "null?"
(assert (null? '()))
(assert (not (null? '(1)))))
(define-test "list?"
(assert (list? '(a b c)))
(assert (list? '()))
(assert (not (list? '(a . b))))
(assert (not (list? 5))))
(define-test "make-list"
(assert (equal? (make-list 0) '()))
(assert (equal? (length (make-list 5)) 5))
(assert (equal? (make-list 0 '(a)) '()))
(assert (equal? (make-list 5 '(a)) '((a) (a) (a) (a) (a)))))
(define-test "list"
(assert (equal? (list) '()))
(assert (equal? (list 1 2 (+ 1 2)) '(1 2 3))))
(define-test "length"
(assert (equal? (length '(1 2 3 4)) 4))
(assert (equal? (length '()) 0)))
(define-test "append"
(assert (equal? (append '(1 2 3 4) '()) '(1 2 3 4)))
(assert (equal? (append '() '(1 2 3 4)) '(1 2 3 4)))
(assert (equal? (append '(1 2) '(3 4)) '(1 2 3 4))))
(define-test "reverse"
(assert (equal? (reverse '()) '()))
(assert (equal? (reverse '(1 2 3 4)) '(4 3 2 1))))
(define-test "list-tail"
(assert (equal? (list-tail '(1 2 3 4) 0) '(1 2 3 4)))
(assert (equal? (list-tail '(1 2 3 4) 2) '(3 4)))
(assert (equal? (list-tail '(1 2 3 4) 4) '())))
(define-test "list-ref"
(assert (equal? (list-ref '(1 2 3 4) 0) 1))
(assert (equal? (list-ref '(1 2 3 4) 1) 2))
(assert (equal? (list-ref '(1 2 3 4) 2) 3))
(assert (equal? (list-ref '(1 2 3 4) 3) 4)))
(define-test "list-set!"
(define a '(1 2 3 4))
(assert (equal? a '(1 2 3 4)))
(list-set! a 1 5)
(assert (equal? a '(1 5 3 4))))
(define-test "memq"
(assert (equal? (memq 'a '(a b c)) '(a b c)))
(assert (equal? (memq 'b '(a b c)) '(b c)))
(assert (equal? (memq 'd '(a b c)) #f)))
(define-test "memv"
(assert (equal? (memv 'a '(a b c)) '(a b c)))
(assert (equal? (memv 'b '(a b c)) '(b c)))
(assert (equal? (memv 'd '(a b c)) #f)))
(define-test "member"
(assert (equal? (member '(a) '((a) (b) (c))) '((a) (b) (c))))
(assert (equal? (member '(b) '((a) (b) (c))) '((b) (c))))
(assert (equal? (member '(d) '((a) (b) (c))) #f))
(assert (equal? (member 'a '() (lambda (i x) #t)) #f))
(assert (equal? (member 'a '(1 2 3) (lambda (i x) #t)) '(1 2 3))))
(define-test "assq"
(assert (equal? (assq 'a '((a . 1) (b . 2))) '(a . 1)))
(assert (equal? (assq 'b '((a . 1) (b . 2))) '(b . 2)))
(assert (equal? (assq 'c '((a . 1) (b . 2))) #f)))
(define-test "assv"
(assert (equal? (assv 'a '((a . 1) (b . 2))) '(a . 1)))
(assert (equal? (assv 'b '((a . 1) (b . 2))) '(b . 2)))
(assert (equal? (assv 'c '((a . 1) (b . 2))) #f)))
(define-test "assoc"
(assert (equal? (assoc '(a) '(((a) . 1) ((b) . 2))) '((a) . 1)))
(assert (equal? (assoc '(b) '(((a) . 1) ((b) . 2))) '((b) . 2)))
(assert (equal? (assoc '(c) '(((a) . 1) ((b) . 2))) #f))
(assert (equal? (assoc 'c '() (lambda (i x) #t)) #f))
(assert (equal? (assoc 'c '((a . 1) (b . 2)) (lambda (i x) #t)) '(a . 1))))
(define-test "list-copy"
(define a '(1 2 3))
(define b (list-copy a))
(assert (not (eq? a b)))
(assert (equal? a b)))
6.5 : Symbols
(define-test "symbol?"
(assert (symbol? 'hello))
(assert (not (symbol? "hello")))
(assert (not (symbol? 5))))
(define-test "symbol->string"
(assert (string? (symbol->string 'hello)))
(assert (equal? (symbol->string 'hello) "hello")))
(define-test "string->symbol"
(assert (symbol? (string->symbol "hello")))
(assert (eq? (string->symbol "hello") 'hello)))
6.7 : Strings
(define-test "string?"
(assert (string? "hello world")))
(define-test "make-string"
(assert (string? (make-string 10)))
(assert (string? (make-string 10 #\a)))
(assert (equal? "aaa" (make-string 3 #\a))))
(define-test "string"
(assert (string? (string #\a #\b #\c)))
(assert (equal? "abc" (string #\a #\b #\c))))
(define-test "string-length"
(assert (equal? (string-length "123456") 6)))
(define-test "string-ref"
(assert (equal? (string-ref "0123" 0) #\0))
(assert (equal? (string-ref "0123" 1) #\1))
(assert (equal? (string-ref "0123" 2) #\2))
(assert (equal? (string-ref "0123" 3) #\3)))
6.8 : Vectors
(define-test "vector?"
(assert (vector? (make-vector 0)))
(assert (not (vector? '()))))
(define-test "make-vector"
(define v (make-vector 5 8))
(assert (vector? v))
(assert (equal? (vector-length v) 5))
(assert (equal? (vector-ref v 4) 8)))
(define-test "vector"
(define v (vector 'a 'b 'c))
(assert (vector? v))
(assert (equal? (vector-length v) 3))
(assert (eq? (vector-ref v 0) 'a))
(assert (eq? (vector-ref v 1) 'b))
(assert (eq? (vector-ref v 2) 'c)))
(define-test "list->vector"
(define l '(1 () (1 2 3) a))
(assert (vector? (list->vector l)))
(assert (list? (vector->list (list->vector l))))
(assert (equal? (vector-length (list->vector '())) 0))
(assert (equal? (vector-length (list->vector l)) 4))
(assert (equal? (vector->list (list->vector l)) l)))
(define-test "vector->list"
(define v (vector 1 '() 'a))
(define l0 (vector->list v 2 2))
(define l1 (vector->list v 1 2))
(define l2 (vector->list v 1))
(assert (list? l0))
(assert (equal? l0 '()))
(assert (list? l1))
(assert (equal? l1 '(())))
(assert (list? l2))
(assert (equal? l2 '(() a))))
(define-test "vector->string"
(define v (vector #\h #\e #\l #\l #\o))
(assert (equal? (vector->string v) "hello"))
(assert (equal? (vector->string v 2) "llo"))
(assert (equal? (vector->string v 1 4) "ell")))
(define-test "string->vector"
(define s "hello")
(assert (equal? (string->vector s) (vector #\h #\e #\l #\l #\o)))
(assert (equal? (string->vector s 2) (vector #\l #\l #\o)))
(assert (equal? (string->vector s 1 4) (vector #\e #\l #\l))))
(define-test "vector-copy"
(define v (vector #\h #\e #\l #\l #\o))
(assert (equal? (vector-copy v) (vector #\h #\e #\l #\l #\o)))
(assert (equal? (vector-copy v 2) (vector #\l #\l #\o)))
(assert (equal? (vector-copy v 1 4) (vector #\e #\l #\l))))
(define-test "vector-copy!"
(define v1 (vector 1 2 3 4 5))
(define v2 (vector 'a 'b 'c 'd 'e))
(assert (equal? (vector-copy! v2 1 v1 1 4) (vector 'a 2 3 4 'e)))
(assert (equal? v2 (vector 'a 2 3 4 'e)))
(assert (equal? (vector-copy! v2 0 v1) (vector 1 2 3 4 5)))
(assert (equal? v2 (vector 1 2 3 4 5))))
(define-test "vector-append"
(assert (equal? (vector-append (vector) (vector 1 2) (vector 3 4)) (vector 1 2 3 4))))
(define-test "vector-fill!"
(define v1 (vector 1 2 3 4 5))
(vector-fill! v1 '(1))
(assert (equal? v1 (vector '(1) '(1) '(1) '(1) '(1)))))
7.3 : Derived expression types
(define-test "cond"
(assert (equal? (cond (#t 1) (#t 2) (#t 3)) 1))
(assert (equal? (cond (#f 1) (8 2) (#t 3)) 2))
(assert (equal? (cond (#f 1) (#f 2) ('() 3)) 3))
(assert (equal? (cond (#f 1) (#f 2) (#f 3)) (begin)))
(assert (equal? (cond (#f 1) (#f 2) (#t 3) (else 4)) 3))
(assert (equal? (cond (#f 1) (#f 2) (#f 3) (else 4)) 4))
(assert (equal? (cond (#f 1) ((+ 1 2) => (lambda (a) (+ a 5)))) 8)))
(define-test "case"
(assert (equal? (case (+ 1 2) ((2) 1) ((4 3 8) 2) (else 3)) 2))
(assert (equal? (case (+ 1 64) ((2) 1) ((4 3 8) 2) (else 3)) 3)))
(define-test "and"
(assert (equal? (and 7 8 (+ 1 2)) 3))
(assert (equal? (and 7 #f (+ 1 2)) #f))
(assert (equal? (and 1) 1))
(assert (equal? (and) #t)))
(define-test "or"
(assert (equal? (or 7 8 (+ 1 2)) 7))
(assert (equal? (or #f #f (+ 1 2)) 3))
(assert (equal? (or 1) 1))
(assert (equal? (or) #f)))
(define-test "when"
(assert (equal? (when #t 1 2 (+ 1 2)) 3))
(assert (equal? (when #f 1 2 (+ 1 2)) (begin))))
(define-test "unless"
(assert (equal? (unless #t 1 2 (+ 1 2)) (begin)))
(assert (equal? (unless #f 1 2 (+ 1 2)) 3)))
(define-test "let"
(assert (equal? (let ((a (+ 1 2))) 1 a) 3))
(assert (equal? (let ((a 1) (b 2)) (+ a b)) 3)))
(define-test "let*"
(assert (equal? (let* ((a (+ 1 2))) 1 a) 3))
(assert (equal? (let* ((a 1) (b (+ a 1))) (+ a b)) 3)))
(define-test "letrec" SKIP)
(define-test "letrec*" SKIP)
(define-test "let-values" SKIP)
(define-test "let*-values" SKIP)
(define-test "define-values" SKIP)
(define-test "do" SKIP)
(define-test "promises" SKIP)
(define-test "parameters" SKIP)
(define-test "guard" SKIP)
(define-test "cond-expand" SKIP)
(finish-tests)
|
73bc6aae3b1eb8f61648c301be6e879e2480e65ae7e271f0e4588817c2a9c768 | cram2/cram | low-level-common.lisp | ;;;
Copyright ( c ) 2016 , < >
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
* Neither the name of the Institute for Artificial Intelligence/
;;; Universitaet Bremen 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 OWNER 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.
(in-package :pr2-ll)
(defun values-converged (values goal-values deltas)
(flet ((value-converged (value goal-value delta)
(<= (abs (- value goal-value)) delta)))
;; correct arguments
(if (listp values)
(if (or (atom goal-values)
(not (= (length values) (length goal-values))))
(error "GOAL-VALUES (~a) and VALUES (~a) should be of same length."
goal-values values)
(if (atom deltas)
(setf deltas (make-list (length values) :initial-element deltas))
(unless (= (length values) (length deltas))
(error "DELTAS (~a) and VALUES (~a) should be of same length."
deltas values))))
(if (or (listp goal-values) (listp deltas))
(error "All arguments should be of same length")
(setf values (list values)
goal-values (list goal-values)
deltas (list deltas))))
;; actually compare
(every #'value-converged values goal-values deltas)))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_pr2/cram_pr2_low_level/src/low-level-common.lisp | lisp |
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Universitaet Bremen nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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.
correct arguments
actually compare | Copyright ( c ) 2016 , < >
* Neither the name of the Institute for Artificial Intelligence/
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package :pr2-ll)
(defun values-converged (values goal-values deltas)
(flet ((value-converged (value goal-value delta)
(<= (abs (- value goal-value)) delta)))
(if (listp values)
(if (or (atom goal-values)
(not (= (length values) (length goal-values))))
(error "GOAL-VALUES (~a) and VALUES (~a) should be of same length."
goal-values values)
(if (atom deltas)
(setf deltas (make-list (length values) :initial-element deltas))
(unless (= (length values) (length deltas))
(error "DELTAS (~a) and VALUES (~a) should be of same length."
deltas values))))
(if (or (listp goal-values) (listp deltas))
(error "All arguments should be of same length")
(setf values (list values)
goal-values (list goal-values)
deltas (list deltas))))
(every #'value-converged values goal-values deltas)))
|
f0ea9ab9e1482eff64fe4ba611b1aac423a31bd1ecb800d8eef9d14f0efe5186 | ocamllabs/ocaml-modular-implicits | stypes.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet , INRIA Rocquencourt
(* *)
Copyright 2003 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
(* Recording and dumping (partial) type information *)
(*
We record all types in a list as they are created.
This means we can dump type information even if type inference fails,
which is extremely important, since type information is most
interesting in case of errors.
*)
open Annot;;
open Lexing;;
open Location;;
open Typedtree;;
let output_int oc i = output_string oc (string_of_int i)
type annotation =
| Ti_pat of pattern
| Ti_expr of expression
| Ti_class of class_expr
| Ti_mod of module_expr
| An_call of Location.t * Annot.call
| An_ident of Location.t * string * Annot.ident
;;
let get_location ti =
match ti with
Ti_pat p -> p.pat_loc
| Ti_expr e -> e.exp_loc
| Ti_class c -> c.cl_loc
| Ti_mod m -> m.mod_loc
| An_call (l, k) -> l
| An_ident (l, s, k) -> l
;;
let annotations = ref ([] : annotation list);;
let phrases = ref ([] : Location.t list);;
let record ti =
if !Clflags.annotations && not (get_location ti).Location.loc_ghost then
annotations := ti :: !annotations
;;
let record_phrase loc =
if !Clflags.annotations then phrases := loc :: !phrases;
;;
(* comparison order:
the intervals are sorted by order of increasing upper bound
same upper bound -> sorted by decreasing lower bound
*)
let cmp_loc_inner_first loc1 loc2 =
match compare loc1.loc_end.pos_cnum loc2.loc_end.pos_cnum with
| 0 -> compare loc2.loc_start.pos_cnum loc1.loc_start.pos_cnum
| x -> x
;;
let cmp_ti_inner_first ti1 ti2 =
cmp_loc_inner_first (get_location ti1) (get_location ti2)
;;
let print_position pp pos =
if pos = dummy_pos then
output_string pp "--"
else begin
output_char pp '\"';
output_string pp (String.escaped pos.pos_fname);
output_string pp "\" ";
output_int pp pos.pos_lnum;
output_char pp ' ';
output_int pp pos.pos_bol;
output_char pp ' ';
output_int pp pos.pos_cnum;
end
;;
let print_location pp loc =
print_position pp loc.loc_start;
output_char pp ' ';
print_position pp loc.loc_end;
;;
let sort_filter_phrases () =
let ph = List.sort (fun x y -> cmp_loc_inner_first y x) !phrases in
let rec loop accu cur l =
match l with
| [] -> accu
| loc :: t ->
if cur.loc_start.pos_cnum <= loc.loc_start.pos_cnum
&& cur.loc_end.pos_cnum >= loc.loc_end.pos_cnum
then loop accu cur t
else loop (loc :: accu) loc t
in
phrases := loop [] Location.none ph;
;;
let rec printtyp_reset_maybe loc =
match !phrases with
| cur :: t when cur.loc_start.pos_cnum <= loc.loc_start.pos_cnum ->
Printtyp.reset ();
phrases := t;
printtyp_reset_maybe loc;
| _ -> ()
;;
let call_kind_string k =
match k with
| Tail -> "tail"
| Stack -> "stack"
| Inline -> "inline"
;;
let print_ident_annot pp str k =
match k with
| Idef l ->
output_string pp "def ";
output_string pp str;
output_char pp ' ';
print_location pp l;
output_char pp '\n'
| Iref_internal l ->
output_string pp "int_ref ";
output_string pp str;
output_char pp ' ';
print_location pp l;
output_char pp '\n'
| Iref_external ->
output_string pp "ext_ref ";
output_string pp str;
output_char pp '\n'
;;
(* The format of the annotation file is documented in emacs/caml-types.el. *)
let print_info pp prev_loc ti =
match ti with
| Ti_class _ | Ti_mod _ -> prev_loc
| Ti_pat {pat_loc = loc; pat_type = typ; pat_env = env}
| Ti_expr {exp_loc = loc; exp_type = typ; exp_env = env} ->
if loc <> prev_loc then begin
print_location pp loc;
output_char pp '\n'
end;
output_string pp "type(\n";
printtyp_reset_maybe loc;
Printtyp.mark_loops typ;
Format.pp_print_string Format.str_formatter " ";
Printtyp.wrap_printing_env env
(fun () -> Printtyp.type_sch Format.str_formatter typ);
Format.pp_print_newline Format.str_formatter ();
let s = Format.flush_str_formatter () in
output_string pp s;
output_string pp ")\n";
loc
| An_call (loc, k) ->
if loc <> prev_loc then begin
print_location pp loc;
output_char pp '\n'
end;
output_string pp "call(\n ";
output_string pp (call_kind_string k);
output_string pp "\n)\n";
loc
| An_ident (loc, str, k) ->
if loc <> prev_loc then begin
print_location pp loc;
output_char pp '\n'
end;
output_string pp "ident(\n ";
print_ident_annot pp str k;
output_string pp ")\n";
loc
;;
let get_info () =
let info = List.fast_sort cmp_ti_inner_first !annotations in
annotations := [];
info
;;
let dump filename =
if !Clflags.annotations then begin
let info = get_info () in
let pp =
match filename with
None -> stdout
| Some filename -> open_out filename in
sort_filter_phrases ();
ignore (List.fold_left (print_info pp) Location.none info);
phrases := [];
end else begin
annotations := [];
end;
;;
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/typing/stypes.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
Recording and dumping (partial) type information
We record all types in a list as they are created.
This means we can dump type information even if type inference fails,
which is extremely important, since type information is most
interesting in case of errors.
comparison order:
the intervals are sorted by order of increasing upper bound
same upper bound -> sorted by decreasing lower bound
The format of the annotation file is documented in emacs/caml-types.el. | , projet , INRIA Rocquencourt
Copyright 2003 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
open Annot;;
open Lexing;;
open Location;;
open Typedtree;;
let output_int oc i = output_string oc (string_of_int i)
type annotation =
| Ti_pat of pattern
| Ti_expr of expression
| Ti_class of class_expr
| Ti_mod of module_expr
| An_call of Location.t * Annot.call
| An_ident of Location.t * string * Annot.ident
;;
let get_location ti =
match ti with
Ti_pat p -> p.pat_loc
| Ti_expr e -> e.exp_loc
| Ti_class c -> c.cl_loc
| Ti_mod m -> m.mod_loc
| An_call (l, k) -> l
| An_ident (l, s, k) -> l
;;
let annotations = ref ([] : annotation list);;
let phrases = ref ([] : Location.t list);;
let record ti =
if !Clflags.annotations && not (get_location ti).Location.loc_ghost then
annotations := ti :: !annotations
;;
let record_phrase loc =
if !Clflags.annotations then phrases := loc :: !phrases;
;;
let cmp_loc_inner_first loc1 loc2 =
match compare loc1.loc_end.pos_cnum loc2.loc_end.pos_cnum with
| 0 -> compare loc2.loc_start.pos_cnum loc1.loc_start.pos_cnum
| x -> x
;;
let cmp_ti_inner_first ti1 ti2 =
cmp_loc_inner_first (get_location ti1) (get_location ti2)
;;
let print_position pp pos =
if pos = dummy_pos then
output_string pp "--"
else begin
output_char pp '\"';
output_string pp (String.escaped pos.pos_fname);
output_string pp "\" ";
output_int pp pos.pos_lnum;
output_char pp ' ';
output_int pp pos.pos_bol;
output_char pp ' ';
output_int pp pos.pos_cnum;
end
;;
let print_location pp loc =
print_position pp loc.loc_start;
output_char pp ' ';
print_position pp loc.loc_end;
;;
let sort_filter_phrases () =
let ph = List.sort (fun x y -> cmp_loc_inner_first y x) !phrases in
let rec loop accu cur l =
match l with
| [] -> accu
| loc :: t ->
if cur.loc_start.pos_cnum <= loc.loc_start.pos_cnum
&& cur.loc_end.pos_cnum >= loc.loc_end.pos_cnum
then loop accu cur t
else loop (loc :: accu) loc t
in
phrases := loop [] Location.none ph;
;;
let rec printtyp_reset_maybe loc =
match !phrases with
| cur :: t when cur.loc_start.pos_cnum <= loc.loc_start.pos_cnum ->
Printtyp.reset ();
phrases := t;
printtyp_reset_maybe loc;
| _ -> ()
;;
let call_kind_string k =
match k with
| Tail -> "tail"
| Stack -> "stack"
| Inline -> "inline"
;;
let print_ident_annot pp str k =
match k with
| Idef l ->
output_string pp "def ";
output_string pp str;
output_char pp ' ';
print_location pp l;
output_char pp '\n'
| Iref_internal l ->
output_string pp "int_ref ";
output_string pp str;
output_char pp ' ';
print_location pp l;
output_char pp '\n'
| Iref_external ->
output_string pp "ext_ref ";
output_string pp str;
output_char pp '\n'
;;
let print_info pp prev_loc ti =
match ti with
| Ti_class _ | Ti_mod _ -> prev_loc
| Ti_pat {pat_loc = loc; pat_type = typ; pat_env = env}
| Ti_expr {exp_loc = loc; exp_type = typ; exp_env = env} ->
if loc <> prev_loc then begin
print_location pp loc;
output_char pp '\n'
end;
output_string pp "type(\n";
printtyp_reset_maybe loc;
Printtyp.mark_loops typ;
Format.pp_print_string Format.str_formatter " ";
Printtyp.wrap_printing_env env
(fun () -> Printtyp.type_sch Format.str_formatter typ);
Format.pp_print_newline Format.str_formatter ();
let s = Format.flush_str_formatter () in
output_string pp s;
output_string pp ")\n";
loc
| An_call (loc, k) ->
if loc <> prev_loc then begin
print_location pp loc;
output_char pp '\n'
end;
output_string pp "call(\n ";
output_string pp (call_kind_string k);
output_string pp "\n)\n";
loc
| An_ident (loc, str, k) ->
if loc <> prev_loc then begin
print_location pp loc;
output_char pp '\n'
end;
output_string pp "ident(\n ";
print_ident_annot pp str k;
output_string pp ")\n";
loc
;;
let get_info () =
let info = List.fast_sort cmp_ti_inner_first !annotations in
annotations := [];
info
;;
let dump filename =
if !Clflags.annotations then begin
let info = get_info () in
let pp =
match filename with
None -> stdout
| Some filename -> open_out filename in
sort_filter_phrases ();
ignore (List.fold_left (print_info pp) Location.none info);
phrases := [];
end else begin
annotations := [];
end;
;;
|
96fccbeb3129b43e83e74a8557ee72daebf027c1db38a924c2fcd0e4e9a9c368 | danoctavian/bit-smuggler | StreamMultiplexSpec.hs | {-# LANGUAGE OverloadedStrings #-}
module StreamMultiplexSpec (main, spec) where
import Test.Hspec
import Test.QuickCheck
import Test.QuickCheck.Monadic (PropertyM, assert, monadicIO, pick, pre, run)
import Data.Conduit as DC
import Data.Conduit.List as DC
import Prelude as P
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Concurrent.STM.TQueue
import Control.Concurrent
import Control.Exception hiding (assert)
import Control.Monad.IO.Class
import Data.Maybe as M
import Data.ByteString as BS
import Data.Text as T
import System.Log.Logger
import Data.ByteString.Char8 as BSC
import Control.Monad
import Control.Monad.Trans.Resource
import Network.Curl
import Network.Curl.Opts
import Network.Wai.Application.Static
import Network.Wai.Handler.Warp as Warp
import Control . Monad . ST
import Control.Monad.ST
-}
import Filesystem.Path.CurrentOS
import Network.BitSmuggler.Utils
import Network.BitSmuggler.StreamMultiplex
import Network.BitSmuggler.Proxy.Client as Proxy
import Network.BitSmuggler.Proxy.Server as Proxy
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "mutiplex" $ do
it "mutiplexes 1 connection" $ do -- easiest test
P.putStrLn "todo"
quickCheckWith stdArgs { maxSuccess = 50 } $ streamsBothWays
return ()
it "mutiplexes many connections" $ do
P.putStrLn "todo"
return ()
describe "mux tcp proxy" $ do
it "proxies http requests for static files" $ P.putStrLn "wtf"
>> (testHTTPProxy `catchAny` (\e -> debugM logger $ "EXCEPTION :" ++ show e))
return ()
testHTTPProxy = void $ forM [1..10] $ \i -> runResourceT $ do
-- liftIO $ updateGlobalLogger logger (setLevel DEBUG)
let root = "test-data/test-server-root"
let serverPort = 3333
let proxyPort = 1080
let app = staticApp $ defaultWebAppSettings (fromText root)
allocAsync $ async $ Warp.run serverPort app
(clientConnData, serverConnData) <- liftIO $ initSTMConnData
allocLinkedAsync $ async
$ Proxy.proxyServer serverConnData `catchAny` (\e -> do
debugM logger $ "terminated the server thread " ++ show e
throwIO e)
allocLinkedAsync $ async
$ (Proxy.proxyClient proxyPort clientConnData) `catchAny` (\e -> do
debugM logger $ "terminated the client thread " ++ show e
throwIO e)
liftIO $ waitForServer (BSC.pack localhost) (fromIntegral serverPort)
liftIO $ waitForServer (BSC.pack localhost) (fromIntegral proxyPort)
liftIO $ debugM logger "the servers are available. continuing with testing ..."
-- run concurrent requests
results <- liftIO $ (P.flip mapConcurrently)
(P.take 10 $ P.cycle ["tinyFile.txt", "tinyFile0.txt", "tinyFile1.txt"])
$ \fileName -> do
let fullPath = (fromText root) </> (fromText fileName)
contents <- liftIO $ P.readFile (T.unpack $ fromRight $ toText fullPath)
(code, proxiedContents) <- liftIO $ curlGetString
(localhost ++ ":" ++ (show serverPort) ++ "/" ++ T.unpack fileName)
[Network.Curl.Opts.CurlProxy $ "socks4:" ++ (show proxyPort)]
debugM logger "evaluate the results"
code `shouldBe` CurlOK
proxiedContents `shouldBe` contents
liftIO $ debugM logger "DONE RUNNING TEST"
return ()
streamsBothWays arbData1 arbData2
= monadicIO $ testStream (toInputData arbData1) (toInputData arbData2)
where
toInputData = P.map BS.pack
testStream :: [ByteString] -> [ByteString] -> PropertyM IO ()
testStream clientToServer serverToClient = do
setting up 2 way channel
(clientConnData, serverConnData) <- liftIO $ initSTMConnData
clientResult <- liftIO $ newEmptyTMVarIO
serverResult <- liftIO $ newEmptyTMVarIO
tid <- liftIO $ forkIO $ void $ concurrently
(runClient clientConnData
$ (\initConn -> initConn
(\connData -> streamAndValidate connData serverToClient clientToServer
>>= (\r -> atomically $ putTMVar clientResult r) )))
(runServer serverConnData
(\connData -> streamAndValidate connData clientToServer serverToClient
>>= (\r -> atomically $ putTMVar serverResult r) ))
clientSendsPayload <- liftIO $ atomically $ takeTMVar clientResult
serverSendsPayload <- liftIO $ atomically $ takeTMVar serverResult
assert clientSendsPayload
assert serverSendsPayload
liftIO $ killThread tid
return ()
initSTMConnData = do
toServer <- newTQueueIO
toClient <- newTQueueIO
let clientConnData = ConnData {connSource = toProducer $ sourceTQueue toClient
, connSink = sinkTQueue toServer}
let serverConnData = ConnData {connSource = toProducer $ sourceTQueue toServer
, connSink = sinkTQueue toClient}
return (clientConnData, serverConnData)
streamAndValidate connData recvData sendData
= fmap fst $ concurrently
((connSource connData $$ DC.consume)
>>= (\out -> return $ BS.concat out == BS.concat recvData))
(DC.sourceList sendData $$ (connSink connData))
| null | https://raw.githubusercontent.com/danoctavian/bit-smuggler/4385ed67f1fec4ed441832fc9a119de632b796aa/BitSmuggler/test/unit/StreamMultiplexSpec.hs | haskell | # LANGUAGE OverloadedStrings #
easiest test
liftIO $ updateGlobalLogger logger (setLevel DEBUG)
run concurrent requests | module StreamMultiplexSpec (main, spec) where
import Test.Hspec
import Test.QuickCheck
import Test.QuickCheck.Monadic (PropertyM, assert, monadicIO, pick, pre, run)
import Data.Conduit as DC
import Data.Conduit.List as DC
import Prelude as P
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Concurrent.STM.TQueue
import Control.Concurrent
import Control.Exception hiding (assert)
import Control.Monad.IO.Class
import Data.Maybe as M
import Data.ByteString as BS
import Data.Text as T
import System.Log.Logger
import Data.ByteString.Char8 as BSC
import Control.Monad
import Control.Monad.Trans.Resource
import Network.Curl
import Network.Curl.Opts
import Network.Wai.Application.Static
import Network.Wai.Handler.Warp as Warp
import Control . Monad . ST
import Control.Monad.ST
-}
import Filesystem.Path.CurrentOS
import Network.BitSmuggler.Utils
import Network.BitSmuggler.StreamMultiplex
import Network.BitSmuggler.Proxy.Client as Proxy
import Network.BitSmuggler.Proxy.Server as Proxy
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "mutiplex" $ do
P.putStrLn "todo"
quickCheckWith stdArgs { maxSuccess = 50 } $ streamsBothWays
return ()
it "mutiplexes many connections" $ do
P.putStrLn "todo"
return ()
describe "mux tcp proxy" $ do
it "proxies http requests for static files" $ P.putStrLn "wtf"
>> (testHTTPProxy `catchAny` (\e -> debugM logger $ "EXCEPTION :" ++ show e))
return ()
testHTTPProxy = void $ forM [1..10] $ \i -> runResourceT $ do
let root = "test-data/test-server-root"
let serverPort = 3333
let proxyPort = 1080
let app = staticApp $ defaultWebAppSettings (fromText root)
allocAsync $ async $ Warp.run serverPort app
(clientConnData, serverConnData) <- liftIO $ initSTMConnData
allocLinkedAsync $ async
$ Proxy.proxyServer serverConnData `catchAny` (\e -> do
debugM logger $ "terminated the server thread " ++ show e
throwIO e)
allocLinkedAsync $ async
$ (Proxy.proxyClient proxyPort clientConnData) `catchAny` (\e -> do
debugM logger $ "terminated the client thread " ++ show e
throwIO e)
liftIO $ waitForServer (BSC.pack localhost) (fromIntegral serverPort)
liftIO $ waitForServer (BSC.pack localhost) (fromIntegral proxyPort)
liftIO $ debugM logger "the servers are available. continuing with testing ..."
results <- liftIO $ (P.flip mapConcurrently)
(P.take 10 $ P.cycle ["tinyFile.txt", "tinyFile0.txt", "tinyFile1.txt"])
$ \fileName -> do
let fullPath = (fromText root) </> (fromText fileName)
contents <- liftIO $ P.readFile (T.unpack $ fromRight $ toText fullPath)
(code, proxiedContents) <- liftIO $ curlGetString
(localhost ++ ":" ++ (show serverPort) ++ "/" ++ T.unpack fileName)
[Network.Curl.Opts.CurlProxy $ "socks4:" ++ (show proxyPort)]
debugM logger "evaluate the results"
code `shouldBe` CurlOK
proxiedContents `shouldBe` contents
liftIO $ debugM logger "DONE RUNNING TEST"
return ()
streamsBothWays arbData1 arbData2
= monadicIO $ testStream (toInputData arbData1) (toInputData arbData2)
where
toInputData = P.map BS.pack
testStream :: [ByteString] -> [ByteString] -> PropertyM IO ()
testStream clientToServer serverToClient = do
setting up 2 way channel
(clientConnData, serverConnData) <- liftIO $ initSTMConnData
clientResult <- liftIO $ newEmptyTMVarIO
serverResult <- liftIO $ newEmptyTMVarIO
tid <- liftIO $ forkIO $ void $ concurrently
(runClient clientConnData
$ (\initConn -> initConn
(\connData -> streamAndValidate connData serverToClient clientToServer
>>= (\r -> atomically $ putTMVar clientResult r) )))
(runServer serverConnData
(\connData -> streamAndValidate connData clientToServer serverToClient
>>= (\r -> atomically $ putTMVar serverResult r) ))
clientSendsPayload <- liftIO $ atomically $ takeTMVar clientResult
serverSendsPayload <- liftIO $ atomically $ takeTMVar serverResult
assert clientSendsPayload
assert serverSendsPayload
liftIO $ killThread tid
return ()
initSTMConnData = do
toServer <- newTQueueIO
toClient <- newTQueueIO
let clientConnData = ConnData {connSource = toProducer $ sourceTQueue toClient
, connSink = sinkTQueue toServer}
let serverConnData = ConnData {connSource = toProducer $ sourceTQueue toServer
, connSink = sinkTQueue toClient}
return (clientConnData, serverConnData)
streamAndValidate connData recvData sendData
= fmap fst $ concurrently
((connSource connData $$ DC.consume)
>>= (\out -> return $ BS.concat out == BS.concat recvData))
(DC.sourceList sendData $$ (connSink connData))
|
9e77cd9b414d27ba30ddc72c7b4598becfd164b9b4e0507e7324ba78c0b4650b | patricoferris/jsoo-mithril | vnode.mli | type t
* The type of virtual DOM nodes
val of_jv : Jv.t -> t
val to_jv : t -> Jv.t
type tag =
| String of Jstr.t
| Obj of Jv.t
* Virtual DOM tags see { { : #structure }
vnode docs } .
mithril vnode docs}. *)
(** {1 Properties} *)
val tag : t -> tag
val key : t -> Jv.t option
val attrs : t -> Jv.t option
val attrs_exn : t -> Jv.t
val children : t -> Jv.t option
val text : t -> Jv.t option
val dom : t -> Jv.t option
val dom_size : t -> int option
val state : t -> Jv.t option
val state_exn : t -> Jv.t
val events : t -> Jv.t option
val instance : t -> Jv.t option
| null | https://raw.githubusercontent.com/patricoferris/jsoo-mithril/5f2ccebd647f737bac7dbd1981b78a4d5bd0f5ea/lib/vnode.mli | ocaml | * {1 Properties} | type t
* The type of virtual DOM nodes
val of_jv : Jv.t -> t
val to_jv : t -> Jv.t
type tag =
| String of Jstr.t
| Obj of Jv.t
* Virtual DOM tags see { { : #structure }
vnode docs } .
mithril vnode docs}. *)
val tag : t -> tag
val key : t -> Jv.t option
val attrs : t -> Jv.t option
val attrs_exn : t -> Jv.t
val children : t -> Jv.t option
val text : t -> Jv.t option
val dom : t -> Jv.t option
val dom_size : t -> int option
val state : t -> Jv.t option
val state_exn : t -> Jv.t
val events : t -> Jv.t option
val instance : t -> Jv.t option
|
17ec04cb09d26660011315487c04e318fc5daa99bf7fafe2549805c2e1c10257 | pariyatti/kosa | mediabox.cljs | (ns kuti.mediabox
(:require-macros
[reagent-forms.macros :refer [render-element]])
(:require
[clojure.string :as string :refer [trim]]
[reagent.core :as r :refer [atom]]
[reagent-forms.core :as rf]))
(defn- scroll-to [element idx]
(let [list-elem (-> element
.-target
.-parentNode
(.getElementsByTagName "ul")
(.item 0))
idx (if (< idx 0) 0 idx)
item-elem (-> list-elem
.-children
(.item idx))
[item-height offset-top] (if item-elem
[(.-scrollHeight item-elem)
(.-offsetTop item-elem)]
[0 0])]
(set! (.-scrollTop list-elem)
(- offset-top
(* 2 item-height)))))
(defmethod rf/init-field :mediabox
[[type {:keys [id data-source input-class list-class item-class highlight-class
input-placeholder result-fn choice-fn clear-on-focus? selections selected-media get-index]
:as attrs
:or {result-fn identity
choice-fn identity
clear-on-focus? true}}] {:keys [doc get save!]}]
(let [typeahead-hidden? (atom true)
mouse-on-list? (atom false)
selected-index (atom -1)
selections (or selections (atom []))
selected-media (or selected-media (atom {}))
get-index (or get-index (constantly -1))
choose-selected #(when (and (not-empty @selections) (> @selected-index -1))
(let [choice (nth @selections @selected-index)]
(save! id choice)
(choice-fn choice)
(reset! typeahead-hidden? true)))]
(render-element attrs doc
[type
[:input {:type :text
:disabled (:disabled attrs)
:placeholder input-placeholder
:class input-class
:value (let [v (get id)]
(if-not (iterable? v)
v (first v)))
:on-focus #(when clear-on-focus? (save! id nil))
:on-blur #(when-not @mouse-on-list?
(reset! typeahead-hidden? true)
(reset! selected-index -1))
:on-change #(when-let [value (trim (rf/value-of %))]
(reset! selections (data-source (.toLowerCase value)))
(save! id (rf/value-of %))
(reset! typeahead-hidden? false)
(reset! selected-index (if (= 1 (count @selections)) 0 -1)))
:on-key-down #(do
(case (.-which %)
38 (do
(.preventDefault %)
(when-not (or @typeahead-hidden? (<= @selected-index 0))
(swap! selected-index dec)
(scroll-to % @selected-index)))
40 (do
(.preventDefault %)
(if @typeahead-hidden?
(do
(reset! selections (data-source :all))
(reset! selected-index (get-index (-> %
rf/value-of
trim)
@selections))
(reset! typeahead-hidden? false)
(scroll-to % @selected-index))
(when-not (= @selected-index (dec (count @selections)))
(save! id (rf/value-of %))
(swap! selected-index inc)
(scroll-to % @selected-index))))
9 (choose-selected)
13 (do
(.preventDefault %)
(choose-selected))
27 (do (reset! typeahead-hidden? true)
(reset! selected-index -1))
"default"))}]
[:ul {:style {:display (if (or (empty? @selections) @typeahead-hidden?) :none :block)}
:class list-class
:on-mouse-enter #(reset! mouse-on-list? true)
:on-mouse-leave #(reset! mouse-on-list? false)}
(doall
(map-indexed
(fn [index result]
[:li {:tab-index index
:key index
:class (if (= @selected-index index) highlight-class item-class)
:on-mouse-over #(do
;; NOTE: this used to be `.-target` but since our contents are an `img` tag, we
;; need to target the actual `li`. there might be a much better way. -sd
(reset! selected-index (js/parseInt (.getAttribute (.-currentTarget %) "tabIndex"))))
:on-click #(do
(.preventDefault %)
(reset! typeahead-hidden? true)
(save! id result)
(choice-fn result))}
(result-fn result)])
@selections))]
;; show selected url:
[:br]
(if-let [url (:url @selected-media)]
[:div
[:input {:type "hidden" :name "image-id" :id "image-id"
:value (:xt/id @selected-media)}]
[:img {:src url :width "300" :height "300"}]]
[:div "No media chosen."])])))
| null | https://raw.githubusercontent.com/pariyatti/kosa/75896fea96b3ff3f47551e272be2c45616af074e/src-cljs/kuti/mediabox.cljs | clojure | NOTE: this used to be `.-target` but since our contents are an `img` tag, we
need to target the actual `li`. there might be a much better way. -sd
show selected url: | (ns kuti.mediabox
(:require-macros
[reagent-forms.macros :refer [render-element]])
(:require
[clojure.string :as string :refer [trim]]
[reagent.core :as r :refer [atom]]
[reagent-forms.core :as rf]))
(defn- scroll-to [element idx]
(let [list-elem (-> element
.-target
.-parentNode
(.getElementsByTagName "ul")
(.item 0))
idx (if (< idx 0) 0 idx)
item-elem (-> list-elem
.-children
(.item idx))
[item-height offset-top] (if item-elem
[(.-scrollHeight item-elem)
(.-offsetTop item-elem)]
[0 0])]
(set! (.-scrollTop list-elem)
(- offset-top
(* 2 item-height)))))
(defmethod rf/init-field :mediabox
[[type {:keys [id data-source input-class list-class item-class highlight-class
input-placeholder result-fn choice-fn clear-on-focus? selections selected-media get-index]
:as attrs
:or {result-fn identity
choice-fn identity
clear-on-focus? true}}] {:keys [doc get save!]}]
(let [typeahead-hidden? (atom true)
mouse-on-list? (atom false)
selected-index (atom -1)
selections (or selections (atom []))
selected-media (or selected-media (atom {}))
get-index (or get-index (constantly -1))
choose-selected #(when (and (not-empty @selections) (> @selected-index -1))
(let [choice (nth @selections @selected-index)]
(save! id choice)
(choice-fn choice)
(reset! typeahead-hidden? true)))]
(render-element attrs doc
[type
[:input {:type :text
:disabled (:disabled attrs)
:placeholder input-placeholder
:class input-class
:value (let [v (get id)]
(if-not (iterable? v)
v (first v)))
:on-focus #(when clear-on-focus? (save! id nil))
:on-blur #(when-not @mouse-on-list?
(reset! typeahead-hidden? true)
(reset! selected-index -1))
:on-change #(when-let [value (trim (rf/value-of %))]
(reset! selections (data-source (.toLowerCase value)))
(save! id (rf/value-of %))
(reset! typeahead-hidden? false)
(reset! selected-index (if (= 1 (count @selections)) 0 -1)))
:on-key-down #(do
(case (.-which %)
38 (do
(.preventDefault %)
(when-not (or @typeahead-hidden? (<= @selected-index 0))
(swap! selected-index dec)
(scroll-to % @selected-index)))
40 (do
(.preventDefault %)
(if @typeahead-hidden?
(do
(reset! selections (data-source :all))
(reset! selected-index (get-index (-> %
rf/value-of
trim)
@selections))
(reset! typeahead-hidden? false)
(scroll-to % @selected-index))
(when-not (= @selected-index (dec (count @selections)))
(save! id (rf/value-of %))
(swap! selected-index inc)
(scroll-to % @selected-index))))
9 (choose-selected)
13 (do
(.preventDefault %)
(choose-selected))
27 (do (reset! typeahead-hidden? true)
(reset! selected-index -1))
"default"))}]
[:ul {:style {:display (if (or (empty? @selections) @typeahead-hidden?) :none :block)}
:class list-class
:on-mouse-enter #(reset! mouse-on-list? true)
:on-mouse-leave #(reset! mouse-on-list? false)}
(doall
(map-indexed
(fn [index result]
[:li {:tab-index index
:key index
:class (if (= @selected-index index) highlight-class item-class)
:on-mouse-over #(do
(reset! selected-index (js/parseInt (.getAttribute (.-currentTarget %) "tabIndex"))))
:on-click #(do
(.preventDefault %)
(reset! typeahead-hidden? true)
(save! id result)
(choice-fn result))}
(result-fn result)])
@selections))]
[:br]
(if-let [url (:url @selected-media)]
[:div
[:input {:type "hidden" :name "image-id" :id "image-id"
:value (:xt/id @selected-media)}]
[:img {:src url :width "300" :height "300"}]]
[:div "No media chosen."])])))
|
2c1784bfb968e01fb20db686255af8129f7e8f3ec6e398d212272d73e4bf4cdd | vaibhavsagar/experiments | A.hs | module A where
a :: Char
a = 'a'
| null | https://raw.githubusercontent.com/vaibhavsagar/experiments/378d7ba97eabfc7bbeaa4116380369ea6612bfeb/hugs/packages/Cabal/tests/depOnLib/libs/A.hs | haskell | module A where
a :: Char
a = 'a'
| |
7e82b75ed98dd993ebe203eeeb1a79f61e6eea295904122ca4088ecc08f79e58 | robert-strandh/SICL | dependent-maintenance.lisp | (cl:in-package #:sicl-clos)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Generic function ADD - DEPENDENT .
;;;
;;; For the specification of this generic function, see
;;; -MOP/add-dependent.html
(defgeneric add-dependent (metaobject dependent))
(defun add-dependent-default (metaobject dependent)
(pushnew dependent (dependents metaobject) :test #'eq))
(defmethod add-dependent ((metaobject standard-class) dependent)
(add-dependent-default metaobject dependent))
(defmethod add-dependent ((metaobject funcallable-standard-class) dependent)
(add-dependent-default metaobject dependent))
(defmethod add-dependent ((metaobject standard-generic-function) dependent)
(add-dependent-default metaobject dependent))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generic function REMOVE-DEPENDENT.
;;;
;;; For the specification of this generic function, see
;;; -MOP/remove-dependent.html
(defgeneric remove-dependent (metaobject dependent))
(defun remove-dependent-default (metaobject dependent)
(setf (dependents metaobject)
(remove dependent (dependents metaobject) :test #'eq)))
(defmethod remove-dependent ((metaobject standard-class) dependent)
(remove-dependent-default metaobject dependent))
(defmethod remove-dependent ((metaobject funcallable-standard-class) dependent)
(remove-dependent-default metaobject dependent))
(defmethod remove-dependent ((metaobject standard-generic-function) dependent)
(remove-dependent-default metaobject dependent))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Generic function MAP - DEPENDENTS .
;;;
;;; For the specification of this generic function, see
;;; -MOP/map-dependents.html
(defgeneric map-dependents (metaobject function))
(defun map-dependents-default (metaobject function)
(mapc function (dependents metaobject)))
(defmethod map-dependents ((metaobject standard-class) function)
(map-dependents-default metaobject function))
(defmethod map-dependents ((metaobject funcallable-standard-class) function)
(map-dependents-default metaobject function))
(defmethod map-dependents ((metaobject standard-generic-function) function)
(map-dependents-default metaobject function))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Generic function UPDATE - DEPENDENT .
;;;
;;; For the specification of this generic function, see
;;; -MOP/update-dependent.html
(defgeneric update-dependent (metaobject dependent &rest initargs))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/cc8406ee55c5dbc13387204777ff10d398a24ac4/Code/CLOS/dependent-maintenance.lisp | lisp |
For the specification of this generic function, see
-MOP/add-dependent.html
Generic function REMOVE-DEPENDENT.
For the specification of this generic function, see
-MOP/remove-dependent.html
For the specification of this generic function, see
-MOP/map-dependents.html
For the specification of this generic function, see
-MOP/update-dependent.html | (cl:in-package #:sicl-clos)
Generic function ADD - DEPENDENT .
(defgeneric add-dependent (metaobject dependent))
(defun add-dependent-default (metaobject dependent)
(pushnew dependent (dependents metaobject) :test #'eq))
(defmethod add-dependent ((metaobject standard-class) dependent)
(add-dependent-default metaobject dependent))
(defmethod add-dependent ((metaobject funcallable-standard-class) dependent)
(add-dependent-default metaobject dependent))
(defmethod add-dependent ((metaobject standard-generic-function) dependent)
(add-dependent-default metaobject dependent))
(defgeneric remove-dependent (metaobject dependent))
(defun remove-dependent-default (metaobject dependent)
(setf (dependents metaobject)
(remove dependent (dependents metaobject) :test #'eq)))
(defmethod remove-dependent ((metaobject standard-class) dependent)
(remove-dependent-default metaobject dependent))
(defmethod remove-dependent ((metaobject funcallable-standard-class) dependent)
(remove-dependent-default metaobject dependent))
(defmethod remove-dependent ((metaobject standard-generic-function) dependent)
(remove-dependent-default metaobject dependent))
Generic function MAP - DEPENDENTS .
(defgeneric map-dependents (metaobject function))
(defun map-dependents-default (metaobject function)
(mapc function (dependents metaobject)))
(defmethod map-dependents ((metaobject standard-class) function)
(map-dependents-default metaobject function))
(defmethod map-dependents ((metaobject funcallable-standard-class) function)
(map-dependents-default metaobject function))
(defmethod map-dependents ((metaobject standard-generic-function) function)
(map-dependents-default metaobject function))
Generic function UPDATE - DEPENDENT .
(defgeneric update-dependent (metaobject dependent &rest initargs))
|
6755f67403d2c4b8ddd4cb447dc0a75d30c3b25ec6f5d2b1f94ae1726ab56d1a | pflanze/chj-schemelib | wbtable.scm | Copyright 2016 - 2020 by < >
;;; This file is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 3 of the License , or
;;; (at your option) any later version. Also, as a special exception to the
;;; terms of the GPL you can link it with any code produced by Categorical
Design Solutions Inc. from Quebec , Canada .
(require easy
show
cj-cmp
wbtree
Maybe
test)
(export (class wbtable)
wbtable?
wbtable-of
empty-wbtable-of
list->wbtable-of
;; list.wbtable-of nah just too many args, k? ;; no list.wbtable, OK?
;; list.wbtable-function
(methods
wbtable.length
wbtable.ref ;; with required alternative value if missing
wbtable.refx ;; exception
wbtable.Maybe-ref
wbtable.Maybe-prev
wbtable.Maybe-next
wbtable.Maybe-min
wbtable.Maybe-max
wbtable.exists?
wbtable.update
wbtable.update*
wbtable.fold
wbtable.fold-right
;; wbtable.every?
wbtable.list
wbtable.show
;; wbtable.keys
;; wbtable.sortedkeys
;; wbtable.update-all
wbtable.add-pair
wbtable.set-pair
wbtable.delete-pair
wbtable.add
wbtable.set
wbtable.delete
wbtable.union)
#!optional
(class wbtable-head)
wbtable:list->_)
(include "cj-standarddeclares.scm")
;; FINALLY give already in and make some sort of a TYPE? Kinda give
;; in only.
( ( wbtable - key - type # ( predicate ? predicate ? )
;; #(function? cmp))
;; (def-method- (wbtreeparameter t)
;; (wbtreeparameter (on car (.cmp t))
;; pair?)))
;; Or not.
;; "~since accessing the items through all these indirections is slow"
;; (Then going on to do one with the same number of indirections anyway.)
make accessing the ( nested ) fields easy ( defmethod would allow
;; access to data easily, but not the nested ones)
(defmacro (@with-wbtable s vars . body)
(def exprs `((data (@wbtable.data ,s))
(key? (@wbtable-head.key? $table-head))
(key-cmp (@wbtable-head.key-cmp $table-head))
(value? (@wbtable-head.value? $table-head))
($wbtreeparameter (@wbtable-head.wbtreeparameter $table-head))))
(assert* symbol? s) ;; since I'm not eval-ing to a var
(assert*
list? vars
(lambda (vars*)
`(let (($table-head (@wbtable.table-head ,s)))
(let ,(map (lambda (var)
(assert* symbol? var
(lambda (var*)
;; heh use key and val right together
(or (assq var* exprs)
(raise-source-error var "request for a var I don't know about")))))
vars*)
,@body)))))
(defmacro (with-wbtable s vars . body)
(assert* symbol? s) ;; since I'm not eval-ing to a var
`(begin
(assert (wbtable? ,s))
(@with-wbtable ,s ,vars ,@body)))
;; XX The real uglyness with the following is the possibility for
;; usage errors (cmp not matching key?).
(defclass ((wbtable-head _wbtable-head)
#(predicate? key?)
#(function? key-cmp)
#(predicate? value?)
;; and cached to avoid reallocating it:
#(wbtreeparameter? wbtreeparameter))
(def (wbtable-head key? key-cmp value?)
(_wbtable-head key? key-cmp value?
(wbtreeparameter (on car key-cmp)
pair?)))
(def-method- (compatible? s t)
;; pessimistic for now...
(let-wbtable-head
((a b c _) s)
(let-wbtable-head
((x y z _) t)
(and (eq? a x)
(eq? b y)
(eq? c z))))))
(defclass ((wbtable _wbtable)
#(wbtable-head? table-head)
#(wbtree? data))
(def (wbtable key? key-cmp value?
data)
(_wbtable (wbtable-head key? key-cmp value?)
data))
(def (empty-wbtable-of key? key-cmp value?)
(wbtable key? key-cmp value? empty-wbtree))
(def (wbtable-of _key? _value?)
(lambda (v)
(and (wbtable? v)
(@with-wbtable
v (key? value?)
;; XX function comparison by eq?: evil or ? (equal?
;; really (of the type language?), REALLY.?!)
(and (eq? key? _key?)
(eq? value? _value?))))))
;; compare with:
( define * ( l )
;; (fold (lambda (x t)
;; (wbtree:add t x))
;; empty-wbtree
;; l))
;; (assert ((list-of (pair-of key? value?)) l))
;; better: throw exception while iterating
;; make re-usable by inheriting classes..:
(def (wbtable:list->_ empty l)
(fold (lambda (k.v t)
;; re-use pairs, ah (dimly remember)
(wbtable.add-pair t k.v))
empty
l))
(def ((list->wbtable-of key? key-cmp value?) l)
(wbtable:list->_ (empty-wbtable-of key? key-cmp value?) l))
;; yeah, should really rename size in wbcollection ? !
(defmethod- (length s)
(with-wbtable s ($wbtreeparameter data)
(wbtree:size data)))
(defmethod (empty? s)
(empty-wbtree? data))
(defmethod- (maybe-ref-pair s #(pair? key.val))
(with-wbtable s (key? $wbtreeparameter data)
(assert (key? (car key.val)))
(wbtree:maybe-ref data key.val)))
;; XX gah dimly remember, too: useless cons. Should add some
;; maybe-ref-key to wbtree? Hm, how is cmp used, always in same
;; order?? todo.
(defmethod- (ref s key alt)
(cond ((wbtable.maybe-ref-pair s (cons key #f)) => cdr)
(else alt)))
(defmethod- (refx s key)
(cond ((wbtable.maybe-ref-pair s (cons key #f)) => cdr)
(else (error "key not found:" key))))
(defmethod- (Maybe-ref s key)
(cond ((wbtable.maybe-ref-pair s (cons key #f)) => Just)
(else (Nothing))))
(defmethod- (Maybe-prev s key)
(with-wbtable
s ($wbtreeparameter data)
(let (v (wbtree:prev data (cons key #f)))
(if (wbtree:nothing? v)
(Nothing)
(Just v)))))
(defmethod- (Maybe-next s key)
(with-wbtable
s ($wbtreeparameter data)
(let (v (wbtree:next data (cons key #f)))
(if (wbtree:nothing? v)
(Nothing)
(Just v)))))
(defmethod- (Maybe-min s)
(with-wbtable
s ($wbtreeparameter data)
(let (v (wbtree:min data))
(if (wbtree:nothing? v)
(Nothing)
(Just v)))))
(defmethod- (Maybe-max s)
(with-wbtable
s ($wbtreeparameter data)
(let (v (wbtree:max data))
(if (wbtree:nothing? v)
(Nothing)
(Just v)))))
;; restrict `contains?` to collections, i.e. full items? And follow
;; Perl with `exists`, OK?
(defmethod- (exists? s key)
(and (wbtable.maybe-ref-pair s (cons key #f))
#t))
(def (wbtable:_update s key fn fn-initial initial-value-thunk)
(with-wbtable
s ($wbtreeparameter data)
(if-let ((kv (wbtree:maybe-ref data (cons key #f))))
(let* ((v (cdr kv))
(v* (fn v)))
(if (eq? v v*)
s
(wbtable.data-set s (wbtree:set data (cons key v*)))))
(wbtable.data-set
s (wbtree:set data (cons key (fn-initial
(initial-value-thunk))))))))
(def-method- (update s key fn initial-value-thunk)
(wbtable:_update s key fn fn initial-value-thunk))
;; alternative that doesn't apply fn in the initial case
(def-method- (update* s key fn initial-value-thunk)
(wbtable:_update s key fn identity initial-value-thunk))
(defmethod- (fold s fn start)
(with-wbtable
s ($wbtreeparameter data)
(wbtree:inorder-fold-reverse data fn start)))
(defmethod- (fold-right s fn start)
(with-wbtable
s ($wbtreeparameter data)
(wbtree:inorder-fold data fn start)))
;; wbtable.every?
(defmethod- (list s)
(with-wbtable
s ($wbtreeparameter data)
(wbtree:members data)))
(defmethod- (show s show)
(with-wbtable
s (key? key-cmp value?)
(if (.empty? s)
`(empty-wbtable-of ,(show key?)
,(show key-cmp)
,(show value?))
`((list->wbtable-of ,(show key?)
,(show key-cmp)
,(show value?))
(list ,@(map show (.list s)))))))
;; wbtable.keys
;; wbtable.sortedkeys same ?
;; wbtable.update-all what was that?
(defmethod- (add-pair s #(pair? key.val))
(with-wbtable
s ($wbtreeparameter key? value? data)
(assert (key? (car key.val)))
(assert (value? (cdr key.val)))
(wbtable.data-set s (wbtree:add data key.val))))
(defmethod- (set-pair s #(pair? key.val))
(with-wbtable
s ($wbtreeparameter key? value? data)
(assert (key? (car key.val)))
(assert (value? (cdr key.val)))
(wbtable.data-set s (wbtree:set data key.val))))
call it remove as symboltable or delete as wbcollection , wbtree ,
;; Perl?
(defmethod- (delete-pair s #(pair? key.val))
(with-wbtable
s ($wbtreeparameter key? data)
(assert (key? (car key.val)))
(wbtable.data-set s (wbtree:delete data key.val))))
^ XX what about missing keys here ? Compatibility with symboltable ,
;; or?
(defmethod- (add s key val)
(wbtable.add-pair s (cons key val)))
(defmethod- (set s key val)
(wbtable.set-pair s (cons key val)))
(defmethod- (delete s key)
(wbtable.delete-pair s (cons key #f)))
;; XX die or not on conflicting elements?
(defmethod- (union s t)
(let ((h1 (wbtable.table-head s))
(h2 (wbtable.table-head t)))
(if (wbtable-head.compatible? h1 h2)
(wbtable.data-set
s
(@with-wbtable
s ($wbtreeparameter data)
(wbtree:union data
(wbtable.data t))))
;; worry about huge data or not, forever? only show heads?
(error "incompatible table heads:"
;; and do an error that does |show| implicitely rather
;; than use |show| here, k?
h1 h2)))))
(TEST
> (def t (empty-wbtable-of symbol? symbol-cmp integer?))
> (def t2 (=> t
(.add 'x 1)
(.add 'y 2)))
> (.exists? t2 'x)
#t
> (.exists? t2 'y)
#t
> (.exists? t2 'z)
#f
> (def t3 (.delete t2 'x))
> (.exists? t3 'x)
#f
> (.exists? t3 'y)
#t
> (.refx t3 'y)
2
> (%try (.add t3 'y 3))
(exception
text:
"This object was raised: [(wbtree-duplicate-exception) (y . 2) (y . 3)]\n")
> (.refx (.set t3 'y 3) 'y)
3
> (%try-error (.refx t3 'x))
#(error "key not found:" x)
> (.ref t3 'x 'no)
no
> (map .length (list t t2 t3))
(0 2 1)
> (map .empty? (list t t2 t3))
(#t #f #f)
> (map (wbtable-of symbol? integer?)
(list t t2 t3 't (empty-wbtable-of symbol? symbol-cmp string?)))
(#t #t #t #f #f)
> (show t2)
((list->wbtable-of symbol? symbol-cmp integer?)
(list (cons 'x 1)
(cons 'y 2)))
> (def u ((list->wbtable-of symbol? symbol-cmp integer?)
'((a . 11) (b . 12) (x . 10))))
> (def u2 (.union t2 u))
> (show u2)
((list->wbtable-of symbol? symbol-cmp integer?)
(list (cons 'a 11)
(cons 'b 12)
(cons 'x 10)
(cons 'y 2))))
(TEST
> (def t (empty-wbtable-of string? string-cmp any?))
> (.ref t "foo" 'nope)
nope
> (def t (.update t "foo" inc-function (& 10)))
> (.ref t "foo" 'nope)
11
> (def t (.update t "foo" inc-function (& 10)))
> (.ref t "foo" 'nope)
12)
(TEST
> (def t (empty-wbtable-of string? string-cmp any?))
> (.ref t "foo" 'nope)
nope
> (def t (.update* t "foo" inc-function (& 10)))
> (.ref t "foo" 'nope)
10
> (def t (.update* t "foo" inc-function (& 10)))
> (.ref t "foo" 'nope)
11)
(TEST
> (def t ((list->wbtable-of symbol? symbol-cmp integer?)
'((a . 1) (c . 2) (b . 3))))
> (.fold t cons '())
((c . 2) (b . 3) (a . 1))
> (.fold-right t cons '())
((a . 1) (b . 3) (c . 2))
> (.fold t (lambda (k.v t) (+ (cdr k.v) t)) 0)
6
> (.fold-right t (lambda (k.v t) (/ (cdr k.v) t)) 1)
2/3
> (.fold t (lambda (k.v t) (/ (cdr k.v) t)) 1)
2/3
> (def t ((list->wbtable-of symbol? symbol-cmp integer?)
'((a . 1) (c . 2) (b . 3) (d . 4))))
> (.fold-right t (lambda (k.v t) (/ (cdr k.v) t)) 1)
1/6
> (.fold t (lambda (k.v t) (/ (cdr k.v) t)) 1)
6)
(TEST
> (def list.realwbtable (list->wbtable-of real? real-cmp symbol?))
> (def t (list.realwbtable '((10 . a) (20 . b) (25 . c))))
> (.Maybe-ref t 10)
[(Just) (10 . a)] ;; yes, return the pair as well for consistency, OK?
> (.Maybe-ref t 11)
[(Nothing)]
> (.Maybe-prev t 11)
[(Just) (10 . a)]
> (.Maybe-next t 11)
[(Just) (20 . b)]
> (.Maybe-next t 24)
[(Just) (25 . c)]
> (.Maybe-next t 25)
[(Nothing)]
> (.Maybe-prev t 25)
[(Just) (20 . b)]
> (.Maybe-prev t 100)
[(Just) (25 . c)])
| null | https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/wbtable.scm | scheme | This file is free software; you can redistribute it and/or modify
(at your option) any later version. Also, as a special exception to the
terms of the GPL you can link it with any code produced by Categorical
list.wbtable-of nah just too many args, k? ;; no list.wbtable, OK?
list.wbtable-function
with required alternative value if missing
exception
wbtable.every?
wbtable.keys
wbtable.sortedkeys
wbtable.update-all
FINALLY give already in and make some sort of a TYPE? Kinda give
in only.
#(function? cmp))
(def-method- (wbtreeparameter t)
(wbtreeparameter (on car (.cmp t))
pair?)))
Or not.
"~since accessing the items through all these indirections is slow"
(Then going on to do one with the same number of indirections anyway.)
access to data easily, but not the nested ones)
since I'm not eval-ing to a var
heh use key and val right together
since I'm not eval-ing to a var
XX The real uglyness with the following is the possibility for
usage errors (cmp not matching key?).
and cached to avoid reallocating it:
pessimistic for now...
XX function comparison by eq?: evil or ? (equal?
really (of the type language?), REALLY.?!)
compare with:
(fold (lambda (x t)
(wbtree:add t x))
empty-wbtree
l))
(assert ((list-of (pair-of key? value?)) l))
better: throw exception while iterating
make re-usable by inheriting classes..:
re-use pairs, ah (dimly remember)
yeah, should really rename size in wbcollection ? !
XX gah dimly remember, too: useless cons. Should add some
maybe-ref-key to wbtree? Hm, how is cmp used, always in same
order?? todo.
restrict `contains?` to collections, i.e. full items? And follow
Perl with `exists`, OK?
alternative that doesn't apply fn in the initial case
wbtable.every?
wbtable.keys
wbtable.sortedkeys same ?
wbtable.update-all what was that?
Perl?
or?
XX die or not on conflicting elements?
worry about huge data or not, forever? only show heads?
and do an error that does |show| implicitely rather
than use |show| here, k?
yes, return the pair as well for consistency, OK? | Copyright 2016 - 2020 by < >
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 3 of the License , or
Design Solutions Inc. from Quebec , Canada .
(require easy
show
cj-cmp
wbtree
Maybe
test)
(export (class wbtable)
wbtable?
wbtable-of
empty-wbtable-of
list->wbtable-of
(methods
wbtable.length
wbtable.Maybe-ref
wbtable.Maybe-prev
wbtable.Maybe-next
wbtable.Maybe-min
wbtable.Maybe-max
wbtable.exists?
wbtable.update
wbtable.update*
wbtable.fold
wbtable.fold-right
wbtable.list
wbtable.show
wbtable.add-pair
wbtable.set-pair
wbtable.delete-pair
wbtable.add
wbtable.set
wbtable.delete
wbtable.union)
#!optional
(class wbtable-head)
wbtable:list->_)
(include "cj-standarddeclares.scm")
( ( wbtable - key - type # ( predicate ? predicate ? )
make accessing the ( nested ) fields easy ( defmethod would allow
(defmacro (@with-wbtable s vars . body)
(def exprs `((data (@wbtable.data ,s))
(key? (@wbtable-head.key? $table-head))
(key-cmp (@wbtable-head.key-cmp $table-head))
(value? (@wbtable-head.value? $table-head))
($wbtreeparameter (@wbtable-head.wbtreeparameter $table-head))))
(assert*
list? vars
(lambda (vars*)
`(let (($table-head (@wbtable.table-head ,s)))
(let ,(map (lambda (var)
(assert* symbol? var
(lambda (var*)
(or (assq var* exprs)
(raise-source-error var "request for a var I don't know about")))))
vars*)
,@body)))))
(defmacro (with-wbtable s vars . body)
`(begin
(assert (wbtable? ,s))
(@with-wbtable ,s ,vars ,@body)))
(defclass ((wbtable-head _wbtable-head)
#(predicate? key?)
#(function? key-cmp)
#(predicate? value?)
#(wbtreeparameter? wbtreeparameter))
(def (wbtable-head key? key-cmp value?)
(_wbtable-head key? key-cmp value?
(wbtreeparameter (on car key-cmp)
pair?)))
(def-method- (compatible? s t)
(let-wbtable-head
((a b c _) s)
(let-wbtable-head
((x y z _) t)
(and (eq? a x)
(eq? b y)
(eq? c z))))))
(defclass ((wbtable _wbtable)
#(wbtable-head? table-head)
#(wbtree? data))
(def (wbtable key? key-cmp value?
data)
(_wbtable (wbtable-head key? key-cmp value?)
data))
(def (empty-wbtable-of key? key-cmp value?)
(wbtable key? key-cmp value? empty-wbtree))
(def (wbtable-of _key? _value?)
(lambda (v)
(and (wbtable? v)
(@with-wbtable
v (key? value?)
(and (eq? key? _key?)
(eq? value? _value?))))))
( define * ( l )
(def (wbtable:list->_ empty l)
(fold (lambda (k.v t)
(wbtable.add-pair t k.v))
empty
l))
(def ((list->wbtable-of key? key-cmp value?) l)
(wbtable:list->_ (empty-wbtable-of key? key-cmp value?) l))
(defmethod- (length s)
(with-wbtable s ($wbtreeparameter data)
(wbtree:size data)))
(defmethod (empty? s)
(empty-wbtree? data))
(defmethod- (maybe-ref-pair s #(pair? key.val))
(with-wbtable s (key? $wbtreeparameter data)
(assert (key? (car key.val)))
(wbtree:maybe-ref data key.val)))
(defmethod- (ref s key alt)
(cond ((wbtable.maybe-ref-pair s (cons key #f)) => cdr)
(else alt)))
(defmethod- (refx s key)
(cond ((wbtable.maybe-ref-pair s (cons key #f)) => cdr)
(else (error "key not found:" key))))
(defmethod- (Maybe-ref s key)
(cond ((wbtable.maybe-ref-pair s (cons key #f)) => Just)
(else (Nothing))))
(defmethod- (Maybe-prev s key)
(with-wbtable
s ($wbtreeparameter data)
(let (v (wbtree:prev data (cons key #f)))
(if (wbtree:nothing? v)
(Nothing)
(Just v)))))
(defmethod- (Maybe-next s key)
(with-wbtable
s ($wbtreeparameter data)
(let (v (wbtree:next data (cons key #f)))
(if (wbtree:nothing? v)
(Nothing)
(Just v)))))
(defmethod- (Maybe-min s)
(with-wbtable
s ($wbtreeparameter data)
(let (v (wbtree:min data))
(if (wbtree:nothing? v)
(Nothing)
(Just v)))))
(defmethod- (Maybe-max s)
(with-wbtable
s ($wbtreeparameter data)
(let (v (wbtree:max data))
(if (wbtree:nothing? v)
(Nothing)
(Just v)))))
(defmethod- (exists? s key)
(and (wbtable.maybe-ref-pair s (cons key #f))
#t))
(def (wbtable:_update s key fn fn-initial initial-value-thunk)
(with-wbtable
s ($wbtreeparameter data)
(if-let ((kv (wbtree:maybe-ref data (cons key #f))))
(let* ((v (cdr kv))
(v* (fn v)))
(if (eq? v v*)
s
(wbtable.data-set s (wbtree:set data (cons key v*)))))
(wbtable.data-set
s (wbtree:set data (cons key (fn-initial
(initial-value-thunk))))))))
(def-method- (update s key fn initial-value-thunk)
(wbtable:_update s key fn fn initial-value-thunk))
(def-method- (update* s key fn initial-value-thunk)
(wbtable:_update s key fn identity initial-value-thunk))
(defmethod- (fold s fn start)
(with-wbtable
s ($wbtreeparameter data)
(wbtree:inorder-fold-reverse data fn start)))
(defmethod- (fold-right s fn start)
(with-wbtable
s ($wbtreeparameter data)
(wbtree:inorder-fold data fn start)))
(defmethod- (list s)
(with-wbtable
s ($wbtreeparameter data)
(wbtree:members data)))
(defmethod- (show s show)
(with-wbtable
s (key? key-cmp value?)
(if (.empty? s)
`(empty-wbtable-of ,(show key?)
,(show key-cmp)
,(show value?))
`((list->wbtable-of ,(show key?)
,(show key-cmp)
,(show value?))
(list ,@(map show (.list s)))))))
(defmethod- (add-pair s #(pair? key.val))
(with-wbtable
s ($wbtreeparameter key? value? data)
(assert (key? (car key.val)))
(assert (value? (cdr key.val)))
(wbtable.data-set s (wbtree:add data key.val))))
(defmethod- (set-pair s #(pair? key.val))
(with-wbtable
s ($wbtreeparameter key? value? data)
(assert (key? (car key.val)))
(assert (value? (cdr key.val)))
(wbtable.data-set s (wbtree:set data key.val))))
call it remove as symboltable or delete as wbcollection , wbtree ,
(defmethod- (delete-pair s #(pair? key.val))
(with-wbtable
s ($wbtreeparameter key? data)
(assert (key? (car key.val)))
(wbtable.data-set s (wbtree:delete data key.val))))
^ XX what about missing keys here ? Compatibility with symboltable ,
(defmethod- (add s key val)
(wbtable.add-pair s (cons key val)))
(defmethod- (set s key val)
(wbtable.set-pair s (cons key val)))
(defmethod- (delete s key)
(wbtable.delete-pair s (cons key #f)))
(defmethod- (union s t)
(let ((h1 (wbtable.table-head s))
(h2 (wbtable.table-head t)))
(if (wbtable-head.compatible? h1 h2)
(wbtable.data-set
s
(@with-wbtable
s ($wbtreeparameter data)
(wbtree:union data
(wbtable.data t))))
(error "incompatible table heads:"
h1 h2)))))
(TEST
> (def t (empty-wbtable-of symbol? symbol-cmp integer?))
> (def t2 (=> t
(.add 'x 1)
(.add 'y 2)))
> (.exists? t2 'x)
#t
> (.exists? t2 'y)
#t
> (.exists? t2 'z)
#f
> (def t3 (.delete t2 'x))
> (.exists? t3 'x)
#f
> (.exists? t3 'y)
#t
> (.refx t3 'y)
2
> (%try (.add t3 'y 3))
(exception
text:
"This object was raised: [(wbtree-duplicate-exception) (y . 2) (y . 3)]\n")
> (.refx (.set t3 'y 3) 'y)
3
> (%try-error (.refx t3 'x))
#(error "key not found:" x)
> (.ref t3 'x 'no)
no
> (map .length (list t t2 t3))
(0 2 1)
> (map .empty? (list t t2 t3))
(#t #f #f)
> (map (wbtable-of symbol? integer?)
(list t t2 t3 't (empty-wbtable-of symbol? symbol-cmp string?)))
(#t #t #t #f #f)
> (show t2)
((list->wbtable-of symbol? symbol-cmp integer?)
(list (cons 'x 1)
(cons 'y 2)))
> (def u ((list->wbtable-of symbol? symbol-cmp integer?)
'((a . 11) (b . 12) (x . 10))))
> (def u2 (.union t2 u))
> (show u2)
((list->wbtable-of symbol? symbol-cmp integer?)
(list (cons 'a 11)
(cons 'b 12)
(cons 'x 10)
(cons 'y 2))))
(TEST
> (def t (empty-wbtable-of string? string-cmp any?))
> (.ref t "foo" 'nope)
nope
> (def t (.update t "foo" inc-function (& 10)))
> (.ref t "foo" 'nope)
11
> (def t (.update t "foo" inc-function (& 10)))
> (.ref t "foo" 'nope)
12)
(TEST
> (def t (empty-wbtable-of string? string-cmp any?))
> (.ref t "foo" 'nope)
nope
> (def t (.update* t "foo" inc-function (& 10)))
> (.ref t "foo" 'nope)
10
> (def t (.update* t "foo" inc-function (& 10)))
> (.ref t "foo" 'nope)
11)
(TEST
> (def t ((list->wbtable-of symbol? symbol-cmp integer?)
'((a . 1) (c . 2) (b . 3))))
> (.fold t cons '())
((c . 2) (b . 3) (a . 1))
> (.fold-right t cons '())
((a . 1) (b . 3) (c . 2))
> (.fold t (lambda (k.v t) (+ (cdr k.v) t)) 0)
6
> (.fold-right t (lambda (k.v t) (/ (cdr k.v) t)) 1)
2/3
> (.fold t (lambda (k.v t) (/ (cdr k.v) t)) 1)
2/3
> (def t ((list->wbtable-of symbol? symbol-cmp integer?)
'((a . 1) (c . 2) (b . 3) (d . 4))))
> (.fold-right t (lambda (k.v t) (/ (cdr k.v) t)) 1)
1/6
> (.fold t (lambda (k.v t) (/ (cdr k.v) t)) 1)
6)
(TEST
> (def list.realwbtable (list->wbtable-of real? real-cmp symbol?))
> (def t (list.realwbtable '((10 . a) (20 . b) (25 . c))))
> (.Maybe-ref t 10)
> (.Maybe-ref t 11)
[(Nothing)]
> (.Maybe-prev t 11)
[(Just) (10 . a)]
> (.Maybe-next t 11)
[(Just) (20 . b)]
> (.Maybe-next t 24)
[(Just) (25 . c)]
> (.Maybe-next t 25)
[(Nothing)]
> (.Maybe-prev t 25)
[(Just) (20 . b)]
> (.Maybe-prev t 100)
[(Just) (25 . c)])
|
c026991258be283dd1f05206c78c1c141cea5ba33eccc488d0d6ec48603bfa55 | returntocorp/semgrep | Rule.ml |
*
* Copyright ( C ) 2019 - 2022 r2c
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation , 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 file
* LICENSE for more details .
*
* Copyright (C) 2019-2022 r2c
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, 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 file
* LICENSE for more details.
*)
open Common
module G = AST_generic
module MV = Metavariable
let logger = Logging.get_logger [ __MODULE__ ]
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
Data structures to represent a Semgrep rule (= ~ AST of a rule ) .
*
* See also where formula and many other features disappear .
*
* See also Mini_rule.ml where formula and many other features disappear.
*)
(*****************************************************************************)
(* Position information *)
(*****************************************************************************)
This is similar to what we do in AST_generic to get precise
* error location when a rule is malformed .
* error location when a rule is malformed.
*)
type tok = AST_generic.tok [@@deriving show, eq, hash]
type 'a wrap = 'a AST_generic.wrap [@@deriving show, eq, hash]
(* To help report pattern errors in the playground *)
type 'a loc = {
pattern : 'a;
t : tok;
path : string list; (* path to pattern in YAML rule *)
}
[@@deriving show, eq]
(*****************************************************************************)
Formula ( patterns boolean composition )
(*****************************************************************************)
Classic boolean - logic / set operators with text range set semantic .
* The main complication is the handling of metavariables and especially
* negation in the presence of metavariables .
*
* less ? enforce invariant that Not can only appear in And ?
* The main complication is the handling of metavariables and especially
* negation in the presence of metavariables.
*
* less? enforce invariant that Not can only appear in And?
*)
type formula =
| P of Xpattern.t (* a leaf pattern *)
| And of tok * conjunction
| Or of tok * formula list
(* There are currently restrictions on where a Not can appear in a formula.
* It must be inside an And to be intersected with "positive" formula.
* TODO? Could this change if we were moving to a different range semantic?
*)
| Not of tok * formula
(* pattern: and pattern-inside: are actually slightly different so
* we need to keep the information around.
* (see tests/rules/inside.yaml)
* The same is true for pattern-not and pattern-not-inside
* (see tests/rules/negation_exact.yaml)
* todo: try to remove this at some point, but difficult. See
*
*)
| Inside of tok * formula
(* Represents all of the metavariables that are being focused by a single
`focus-metavariable`. *)
and focus_mv_list = tok * MV.mvar list
The conjunction must contain at least
* one positive " term " ( unless it 's inside a CondNestedFormula , in which
* case there is not such a restriction ) .
* See also split_and ( ) .
* one positive "term" (unless it's inside a CondNestedFormula, in which
* case there is not such a restriction).
* See also split_and().
*)
and conjunction = {
(* pattern-inside:'s and pattern:'s *)
conjuncts : formula list;
(* metavariable-xyz:'s *)
conditions : (tok * metavar_cond) list;
(* focus-metavariable:'s *)
focus : focus_mv_list list;
}
and metavar_cond =
see Eval_generic.ml
todo : at some point we should remove CondRegexp and have just
* CondEval , but for now there are some
* differences between using the matched text region of a metavariable
* ( which we use for MetavarRegexp ) and using its actual value
* ( which we use for MetavarComparison ) , which translate to different
* calls in Eval_generic.ml
* update : this is also useful to keep separate from CondEval for
* the " regexpizer " optimizer ( see Analyze_rule.ml ) .
* CondEval, but for now there are some
* differences between using the matched text region of a metavariable
* (which we use for MetavarRegexp) and using its actual value
* (which we use for MetavarComparison), which translate to different
* calls in Eval_generic.ml
* update: this is also useful to keep separate from CondEval for
* the "regexpizer" optimizer (see Analyze_rule.ml).
*)
| CondRegexp of
MV.mvar * Xpattern.regexp_string * bool (* constant-propagation *)
| CondAnalysis of MV.mvar * metavar_analysis_kind
| CondNestedFormula of MV.mvar * Xlang.t option * formula
and metavar_analysis_kind = CondEntropy | CondReDoS [@@deriving show, eq]
(*****************************************************************************)
Taint - specific types
(*****************************************************************************)
(* The sources/sanitizers/sinks used to be a simple 'formula list',
* but with taint labels things are bit more complicated.
*)
type taint_spec = {
sources : tok * taint_source list;
sanitizers : taint_sanitizer list;
sinks : tok * taint_sink list;
propagators : taint_propagator list;
}
and taint_source = {
source_formula : formula;
source_by_side_effect : bool;
label : string;
(* The label to attach to the data.
* Alt: We could have an optional label instead, allow taint that is not
* labeled, and allow sinks that work for any kind of taint? *)
source_requires : AST_generic.expr;
A Boolean expression over taint labels , using Python syntax .
* The operators allowed are ' not ' , ' or ' , and ' and ' . The expression is
* evaluated using the ` Eval_generic ` machinery .
*
* The expression that is being checked as a source must satisfy this
* in order to the label to be produced . Note that with ' requires ' a
* taint source behaves a bit like a propagator .
* The operators allowed are 'not', 'or', and 'and'. The expression is
* evaluated using the `Eval_generic` machinery.
*
* The expression that is being checked as a source must satisfy this
* in order to the label to be produced. Note that with 'requires' a
* taint source behaves a bit like a propagator. *)
}
Note that , with taint labels , we can attach a label " SANITIZED " to the
* data to flag that it has been sanitized ... so do we still need sanitizers ?
* I am not sure to be honest , I think we will have to gain some experience in
* using labels first .
* Sanitizers do allow you to completely remove taint from data , although I
* think that can be simulated with labels too . We could translate ( internally )
* ` pattern - sanitizers ` as ` pattern - sources ` with a ` " _ _ SANITIZED _ _ " ` label ,
* and then rewrite the ` requires ` of all sinks as ` ( ... ) not _ _ SANITIZED _ _ ` .
* But not - conflicting sanitizers can not be simulated that way . That said , I
* think we should replace not - conflicting sanitizers with some ` options : ` ,
* because they are a bit confusing to use sometimes .
* data to flag that it has been sanitized... so do we still need sanitizers?
* I am not sure to be honest, I think we will have to gain some experience in
* using labels first.
* Sanitizers do allow you to completely remove taint from data, although I
* think that can be simulated with labels too. We could translate (internally)
* `pattern-sanitizers` as `pattern-sources` with a `"__SANITIZED__"` label,
* and then rewrite the `requires` of all sinks as `(...) not __SANITIZED__`.
* But not-conflicting sanitizers cannot be simulated that way. That said, I
* think we should replace not-conflicting sanitizers with some `options:`,
* because they are a bit confusing to use sometimes.
*)
and taint_sanitizer = {
sanitizer_formula : formula;
sanitizer_by_side_effect : bool;
not_conflicting : bool;
(* If [not_conflicting] is enabled, the sanitizer cannot conflict with
* a sink or a source (i.e., match the exact same range) otherwise
* it is filtered out. This allows to e.g. declare `$F(...)` as a
* sanitizer, to assume that any other function will handle tainted
* data safely.
* Without this, `$F(...)` would automatically sanitize any other
* function call acting as a sink or a source.
*
* THINK: In retrospective, I'm not sure this was a good idea.
* We should add an option to disable the assumption that function
* calls always propagate taint, and deprecate not-conflicting
* sanitizers.
*)
}
and taint_sink = {
sink_id : string; (** See 'Parse_rule.parse_taint_sink'. *)
sink_formula : formula;
sink_requires : AST_generic.expr;
A Boolean expression over taint labels . See also ' ' .
* The sink will only trigger a finding if the data that reaches it
* has a set of labels attached that satisfies the ' requires ' .
* The sink will only trigger a finding if the data that reaches it
* has a set of labels attached that satisfies the 'requires'.
*)
}
e.g. if we want to specify that adding tainted data to a ` HashMap ` makes
* the ` HashMap ` tainted too , then " formula " could be ` ( HashMap $ H).add($X ) ` ,
* with " from " being ` $ X ` and " to " being ` $ H ` . So if ` $ X ` is tainted then ` $ H `
* will also be marked as tainted .
* the `HashMap` tainted too, then "formula" could be `(HashMap $H).add($X)`,
* with "from" being `$X` and "to" being `$H`. So if `$X` is tainted then `$H`
* will also be marked as tainted.
*)
and taint_propagator = {
propagator_formula : formula;
propagator_by_side_effect : bool;
from : MV.mvar wrap;
to_ : MV.mvar wrap;
propagator_requires : AST_generic.expr;
A Boolean expression over taint labels . See also ' ' .
* This propagator will only propagate taint if the incoming taint
* satisfies the ' requires ' .
* This propagator will only propagate taint if the incoming taint
* satisfies the 'requires'.
*)
propagator_replace_labels : string list option;
(* A list of the particular labels of taint to be replaced by
the propagator.
Does nothing if [propagator_label] is not also specified.
If not specified, all kinds are propagated.
*)
propagator_label : string option;
(* If [propagator_label] is specified, then the propagator will
output taint with the given label.
Otherwise, it will output taint with the same label as it
received.
*)
}
[@@deriving show]
let default_source_label = "__SOURCE__"
let default_source_requires tok = G.L (G.Bool (true, tok)) |> G.e
let default_propagator_requires tok = G.L (G.Bool (true, tok)) |> G.e
let default_sink_requires tok =
G.N (G.Id ((default_source_label, tok), G.empty_id_info ())) |> G.e
(*****************************************************************************)
(* Extract mode (semgrep as a preprocessor) *)
(*****************************************************************************)
type extract_spec = {
formula : formula;
reduce : extract_reduction;
dst_lang : Xlang.t;
(* e.g., $...BODY, $CMD *)
extract : MV.mvar;
transform : extract_transform;
}
(* Method to combine extracted ranges within a file:
- either treat them as separate files; or
- concatentate them together
*)
and extract_reduction = Separate | Concat [@@deriving show]
(* Method to transform extracted content:
- either treat them as a raw string; or
- transform JSON array into a raw string
*)
and extract_transform = NoTransform | Unquote | ConcatJsonArray
[@@deriving show]
(*****************************************************************************)
(* The rule *)
(*****************************************************************************)
type rule_id = string [@@deriving show]
type 'mode rule_info = {
(* MANDATORY fields *)
id : rule_id wrap;
mode : 'mode;
message : string; (* Currently a dummy value for extract mode rules *)
severity : severity; (* Currently a dummy value for extract mode rules *)
languages : Xlang.t;
(* OPTIONAL fields *)
options : Config_semgrep.t option;
(* deprecated? todo: parse them *)
equivalences : string list option;
fix : string option;
fix_regexp : (Xpattern.regexp_string * int option * string) option;
paths : paths option;
ex : [ ( " owasp " , " A1 : Injection " ) ] but can be anything
metadata : JSON.t option;
}
and paths = {
(* not regexp but globs *)
include_ : string list;
exclude : string list;
}
(* TODO? just reuse Error_code.severity *)
and severity = Error | Warning | Info | Inventory | Experiment
[@@deriving show]
Polymorhic variants used to improve type checking of rules ( see below )
type search_mode = [ `Search of formula ] [@@deriving show]
type taint_mode = [ `Taint of taint_spec ] [@@deriving show]
type extract_mode = [ `Extract of extract_spec ] [@@deriving show]
type mode = [ search_mode | taint_mode | extract_mode ] [@@deriving show]
(* If you know your function accepts only a certain kind of rule,
* you can use those precise types below.
*)
type search_rule = search_mode rule_info [@@deriving show]
type taint_rule = taint_mode rule_info [@@deriving show]
type extract_rule = extract_mode rule_info [@@deriving show]
(* the general type *)
type rule = mode rule_info [@@deriving show]
(* aliases *)
type t = rule [@@deriving show]
type rules = rule list [@@deriving show]
type hrules = (rule_id, t) Hashtbl.t
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
let hrules_of_rules (rules : t list) : hrules =
rules |> Common.map (fun r -> (fst r.id, r)) |> Common.hash_of_list
let partition_rules (rules : rules) :
search_rule list * taint_rule list * extract_rule list =
rules
|> Common.partition_either3 (fun r ->
match r.mode with
| `Search _ as s -> Left3 { r with mode = s }
| `Taint _ as t -> Middle3 { r with mode = t }
| `Extract _ as e -> Right3 { r with mode = e })
(*****************************************************************************)
(* Error Management *)
(*****************************************************************************)
This is used to let the user know which rule the engine was using when
* a Timeout or OutOfMemory exn occured .
* a Timeout or OutOfMemory exn occured.
*)
let last_matched_rule : rule_id option ref = ref None
(* Those are recoverable errors; We can just skip the rules containing them.
* TODO? put in Output_from_core.atd?
*)
type invalid_rule_error = invalid_rule_error_kind * rule_id * Parse_info.t
and invalid_rule_error_kind =
| InvalidLanguage of string (* the language string *)
TODO : the Parse_info.t for InvalidPattern is not precise for now ;
* it corresponds to the start of the pattern
* it corresponds to the start of the pattern *)
| InvalidPattern of
string (* pattern *)
* Xlang.t
* string (* exn *)
* string list (* yaml path *)
PCRE error message
| DeprecatedFeature of string (* e.g., pattern-where-python: *)
| MissingPositiveTermInAnd
| InvalidOther of string
[@@deriving show]
(* General errors *)
type error =
| InvalidRule of invalid_rule_error
| InvalidYaml of string * Parse_info.t
| DuplicateYamlKey of string * Parse_info.t
| UnparsableYamlException of string
(* can't use Error because it's used for severity *)
exception Err of error
(*****************************************************************************)
(* String-of *)
(*****************************************************************************)
let string_of_invalid_rule_error_kind = function
| InvalidLanguage language -> spf "invalid language %s" language
| InvalidRegexp message -> spf "invalid regex %s" message
(* coupling: this is actually intercepted in
* Semgrep_error_code.exn_to_error to generate a PatternParseError instead
* of a RuleParseError *)
| InvalidPattern (pattern, xlang, message, _yaml_path) ->
spf
"Invalid pattern for %s: %s\n\
----- pattern -----\n\
%s\n\
----- end pattern -----\n"
(Xlang.to_string xlang) message pattern
| MissingPositiveTermInAnd ->
"you need at least one positive term (not just negations or conditions)"
| DeprecatedFeature s -> spf "deprecated feature: %s" s
| InvalidOther s -> s
let string_of_invalid_rule_error ((kind, rule_id, pos) : invalid_rule_error) =
spf "invalid rule %s, %s: %s" rule_id
(Parse_info.string_of_info pos)
(string_of_invalid_rule_error_kind kind)
let string_of_error (error : error) : string =
match error with
| InvalidRule x -> string_of_invalid_rule_error x
| InvalidYaml (msg, pos) ->
spf "invalid YAML, %s: %s" (Parse_info.string_of_info pos) msg
| DuplicateYamlKey (key, pos) ->
spf "invalid YAML, %s: duplicate key %S"
(Parse_info.string_of_info pos)
key
| UnparsableYamlException s ->
(* TODO: what's the string s? *)
spf "unparsable YAML: %s" s
(*
Exception printers for Printexc.to_string.
*)
let opt_string_of_exn (exn : exn) =
match exn with
| Err x -> Some (string_of_error x)
| _else_ -> None
(* To be called by the application's main().
* TODO? why not evaluate it now like let () = Printexc.register_printer ...?
*)
let register_exception_printer () = Printexc.register_printer opt_string_of_exn
(*****************************************************************************)
(* Visitor/extractor *)
(*****************************************************************************)
currently used in Check_rule.ml metachecker
(* OK, this is only a little disgusting, but...
Evaluation order means that we will only visit children after parents.
So we keep a reference cell around, and set it to true whenever we descend
under an inside.
That way, pattern leaves underneath an Inside will properly be paired with
a true boolean.
*)
let visit_new_formula f formula =
let bref = ref false in
let rec visit_new_formula f formula =
match formula with
| P p -> f p !bref
| Inside (_, formula) ->
Common.save_excursion bref true (fun () -> visit_new_formula f formula)
| Not (_, x) -> visit_new_formula f x
| Or (_, xs)
| And (_, { conjuncts = xs; _ }) ->
xs |> List.iter (visit_new_formula f)
in
visit_new_formula f formula
(* used by the metachecker for precise error location *)
let tok_of_formula = function
| And (t, _) -> t
| Or (t, _)
| Not (t, _) ->
t
| P p -> snd p.pstr
| Inside (t, _) -> t
let kind_of_formula = function
| P _ -> "pattern"
| Or _
| And _
| Inside _
| Not _ ->
"formula"
(*****************************************************************************)
(* Converters *)
(*****************************************************************************)
(* return list of "positive" x list of Not *)
let split_and (xs : formula list) : formula list * (tok * formula) list =
xs
|> Common.partition_either (fun e ->
match e with
(* positives *)
| P _
| And _
| Inside _
| Or _ ->
Left e
(* negatives *)
| Not (tok, f) -> Right (tok, f))
(* create a fake rule when we only have a pattern and language.
* This is used when someone calls `semgrep -e print -l python`
*)
let rule_of_xpattern (xlang : Xlang.t) (xpat : Xpattern.t) : rule =
let fk = Parse_info.unsafe_fake_info "" in
{
id = ("-e", fk);
mode = `Search (P xpat);
(* alt: could put xpat.pstr for the message *)
message = "";
severity = Error;
languages = xlang;
options = None;
equivalences = None;
fix = None;
fix_regexp = None;
paths = None;
metadata = None;
}
| null | https://raw.githubusercontent.com/returntocorp/semgrep/ab09346ea6471a5c7f4db0791657d35d6de61817/src/core/Rule.ml | ocaml | ***************************************************************************
Prelude
***************************************************************************
***************************************************************************
Position information
***************************************************************************
To help report pattern errors in the playground
path to pattern in YAML rule
***************************************************************************
***************************************************************************
a leaf pattern
There are currently restrictions on where a Not can appear in a formula.
* It must be inside an And to be intersected with "positive" formula.
* TODO? Could this change if we were moving to a different range semantic?
pattern: and pattern-inside: are actually slightly different so
* we need to keep the information around.
* (see tests/rules/inside.yaml)
* The same is true for pattern-not and pattern-not-inside
* (see tests/rules/negation_exact.yaml)
* todo: try to remove this at some point, but difficult. See
*
Represents all of the metavariables that are being focused by a single
`focus-metavariable`.
pattern-inside:'s and pattern:'s
metavariable-xyz:'s
focus-metavariable:'s
constant-propagation
***************************************************************************
***************************************************************************
The sources/sanitizers/sinks used to be a simple 'formula list',
* but with taint labels things are bit more complicated.
The label to attach to the data.
* Alt: We could have an optional label instead, allow taint that is not
* labeled, and allow sinks that work for any kind of taint?
If [not_conflicting] is enabled, the sanitizer cannot conflict with
* a sink or a source (i.e., match the exact same range) otherwise
* it is filtered out. This allows to e.g. declare `$F(...)` as a
* sanitizer, to assume that any other function will handle tainted
* data safely.
* Without this, `$F(...)` would automatically sanitize any other
* function call acting as a sink or a source.
*
* THINK: In retrospective, I'm not sure this was a good idea.
* We should add an option to disable the assumption that function
* calls always propagate taint, and deprecate not-conflicting
* sanitizers.
* See 'Parse_rule.parse_taint_sink'.
A list of the particular labels of taint to be replaced by
the propagator.
Does nothing if [propagator_label] is not also specified.
If not specified, all kinds are propagated.
If [propagator_label] is specified, then the propagator will
output taint with the given label.
Otherwise, it will output taint with the same label as it
received.
***************************************************************************
Extract mode (semgrep as a preprocessor)
***************************************************************************
e.g., $...BODY, $CMD
Method to combine extracted ranges within a file:
- either treat them as separate files; or
- concatentate them together
Method to transform extracted content:
- either treat them as a raw string; or
- transform JSON array into a raw string
***************************************************************************
The rule
***************************************************************************
MANDATORY fields
Currently a dummy value for extract mode rules
Currently a dummy value for extract mode rules
OPTIONAL fields
deprecated? todo: parse them
not regexp but globs
TODO? just reuse Error_code.severity
If you know your function accepts only a certain kind of rule,
* you can use those precise types below.
the general type
aliases
***************************************************************************
Helpers
***************************************************************************
***************************************************************************
Error Management
***************************************************************************
Those are recoverable errors; We can just skip the rules containing them.
* TODO? put in Output_from_core.atd?
the language string
pattern
exn
yaml path
e.g., pattern-where-python:
General errors
can't use Error because it's used for severity
***************************************************************************
String-of
***************************************************************************
coupling: this is actually intercepted in
* Semgrep_error_code.exn_to_error to generate a PatternParseError instead
* of a RuleParseError
TODO: what's the string s?
Exception printers for Printexc.to_string.
To be called by the application's main().
* TODO? why not evaluate it now like let () = Printexc.register_printer ...?
***************************************************************************
Visitor/extractor
***************************************************************************
OK, this is only a little disgusting, but...
Evaluation order means that we will only visit children after parents.
So we keep a reference cell around, and set it to true whenever we descend
under an inside.
That way, pattern leaves underneath an Inside will properly be paired with
a true boolean.
used by the metachecker for precise error location
***************************************************************************
Converters
***************************************************************************
return list of "positive" x list of Not
positives
negatives
create a fake rule when we only have a pattern and language.
* This is used when someone calls `semgrep -e print -l python`
alt: could put xpat.pstr for the message |
*
* Copyright ( C ) 2019 - 2022 r2c
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation , 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 file
* LICENSE for more details .
*
* Copyright (C) 2019-2022 r2c
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, 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 file
* LICENSE for more details.
*)
open Common
module G = AST_generic
module MV = Metavariable
let logger = Logging.get_logger [ __MODULE__ ]
Data structures to represent a Semgrep rule (= ~ AST of a rule ) .
*
* See also where formula and many other features disappear .
*
* See also Mini_rule.ml where formula and many other features disappear.
*)
This is similar to what we do in AST_generic to get precise
* error location when a rule is malformed .
* error location when a rule is malformed.
*)
type tok = AST_generic.tok [@@deriving show, eq, hash]
type 'a wrap = 'a AST_generic.wrap [@@deriving show, eq, hash]
type 'a loc = {
pattern : 'a;
t : tok;
}
[@@deriving show, eq]
Formula ( patterns boolean composition )
Classic boolean - logic / set operators with text range set semantic .
* The main complication is the handling of metavariables and especially
* negation in the presence of metavariables .
*
* less ? enforce invariant that Not can only appear in And ?
* The main complication is the handling of metavariables and especially
* negation in the presence of metavariables.
*
* less? enforce invariant that Not can only appear in And?
*)
type formula =
| And of tok * conjunction
| Or of tok * formula list
| Not of tok * formula
| Inside of tok * formula
and focus_mv_list = tok * MV.mvar list
The conjunction must contain at least
* one positive " term " ( unless it 's inside a CondNestedFormula , in which
* case there is not such a restriction ) .
* See also split_and ( ) .
* one positive "term" (unless it's inside a CondNestedFormula, in which
* case there is not such a restriction).
* See also split_and().
*)
and conjunction = {
conjuncts : formula list;
conditions : (tok * metavar_cond) list;
focus : focus_mv_list list;
}
and metavar_cond =
see Eval_generic.ml
todo : at some point we should remove CondRegexp and have just
* CondEval , but for now there are some
* differences between using the matched text region of a metavariable
* ( which we use for MetavarRegexp ) and using its actual value
* ( which we use for MetavarComparison ) , which translate to different
* calls in Eval_generic.ml
* update : this is also useful to keep separate from CondEval for
* the " regexpizer " optimizer ( see Analyze_rule.ml ) .
* CondEval, but for now there are some
* differences between using the matched text region of a metavariable
* (which we use for MetavarRegexp) and using its actual value
* (which we use for MetavarComparison), which translate to different
* calls in Eval_generic.ml
* update: this is also useful to keep separate from CondEval for
* the "regexpizer" optimizer (see Analyze_rule.ml).
*)
| CondRegexp of
| CondAnalysis of MV.mvar * metavar_analysis_kind
| CondNestedFormula of MV.mvar * Xlang.t option * formula
and metavar_analysis_kind = CondEntropy | CondReDoS [@@deriving show, eq]
Taint - specific types
type taint_spec = {
sources : tok * taint_source list;
sanitizers : taint_sanitizer list;
sinks : tok * taint_sink list;
propagators : taint_propagator list;
}
and taint_source = {
source_formula : formula;
source_by_side_effect : bool;
label : string;
source_requires : AST_generic.expr;
A Boolean expression over taint labels , using Python syntax .
* The operators allowed are ' not ' , ' or ' , and ' and ' . The expression is
* evaluated using the ` Eval_generic ` machinery .
*
* The expression that is being checked as a source must satisfy this
* in order to the label to be produced . Note that with ' requires ' a
* taint source behaves a bit like a propagator .
* The operators allowed are 'not', 'or', and 'and'. The expression is
* evaluated using the `Eval_generic` machinery.
*
* The expression that is being checked as a source must satisfy this
* in order to the label to be produced. Note that with 'requires' a
* taint source behaves a bit like a propagator. *)
}
Note that , with taint labels , we can attach a label " SANITIZED " to the
* data to flag that it has been sanitized ... so do we still need sanitizers ?
* I am not sure to be honest , I think we will have to gain some experience in
* using labels first .
* Sanitizers do allow you to completely remove taint from data , although I
* think that can be simulated with labels too . We could translate ( internally )
* ` pattern - sanitizers ` as ` pattern - sources ` with a ` " _ _ SANITIZED _ _ " ` label ,
* and then rewrite the ` requires ` of all sinks as ` ( ... ) not _ _ SANITIZED _ _ ` .
* But not - conflicting sanitizers can not be simulated that way . That said , I
* think we should replace not - conflicting sanitizers with some ` options : ` ,
* because they are a bit confusing to use sometimes .
* data to flag that it has been sanitized... so do we still need sanitizers?
* I am not sure to be honest, I think we will have to gain some experience in
* using labels first.
* Sanitizers do allow you to completely remove taint from data, although I
* think that can be simulated with labels too. We could translate (internally)
* `pattern-sanitizers` as `pattern-sources` with a `"__SANITIZED__"` label,
* and then rewrite the `requires` of all sinks as `(...) not __SANITIZED__`.
* But not-conflicting sanitizers cannot be simulated that way. That said, I
* think we should replace not-conflicting sanitizers with some `options:`,
* because they are a bit confusing to use sometimes.
*)
and taint_sanitizer = {
sanitizer_formula : formula;
sanitizer_by_side_effect : bool;
not_conflicting : bool;
}
and taint_sink = {
sink_formula : formula;
sink_requires : AST_generic.expr;
A Boolean expression over taint labels . See also ' ' .
* The sink will only trigger a finding if the data that reaches it
* has a set of labels attached that satisfies the ' requires ' .
* The sink will only trigger a finding if the data that reaches it
* has a set of labels attached that satisfies the 'requires'.
*)
}
e.g. if we want to specify that adding tainted data to a ` HashMap ` makes
* the ` HashMap ` tainted too , then " formula " could be ` ( HashMap $ H).add($X ) ` ,
* with " from " being ` $ X ` and " to " being ` $ H ` . So if ` $ X ` is tainted then ` $ H `
* will also be marked as tainted .
* the `HashMap` tainted too, then "formula" could be `(HashMap $H).add($X)`,
* with "from" being `$X` and "to" being `$H`. So if `$X` is tainted then `$H`
* will also be marked as tainted.
*)
and taint_propagator = {
propagator_formula : formula;
propagator_by_side_effect : bool;
from : MV.mvar wrap;
to_ : MV.mvar wrap;
propagator_requires : AST_generic.expr;
A Boolean expression over taint labels . See also ' ' .
* This propagator will only propagate taint if the incoming taint
* satisfies the ' requires ' .
* This propagator will only propagate taint if the incoming taint
* satisfies the 'requires'.
*)
propagator_replace_labels : string list option;
propagator_label : string option;
}
[@@deriving show]
let default_source_label = "__SOURCE__"
let default_source_requires tok = G.L (G.Bool (true, tok)) |> G.e
let default_propagator_requires tok = G.L (G.Bool (true, tok)) |> G.e
let default_sink_requires tok =
G.N (G.Id ((default_source_label, tok), G.empty_id_info ())) |> G.e
type extract_spec = {
formula : formula;
reduce : extract_reduction;
dst_lang : Xlang.t;
extract : MV.mvar;
transform : extract_transform;
}
and extract_reduction = Separate | Concat [@@deriving show]
and extract_transform = NoTransform | Unquote | ConcatJsonArray
[@@deriving show]
type rule_id = string [@@deriving show]
type 'mode rule_info = {
id : rule_id wrap;
mode : 'mode;
languages : Xlang.t;
options : Config_semgrep.t option;
equivalences : string list option;
fix : string option;
fix_regexp : (Xpattern.regexp_string * int option * string) option;
paths : paths option;
ex : [ ( " owasp " , " A1 : Injection " ) ] but can be anything
metadata : JSON.t option;
}
and paths = {
include_ : string list;
exclude : string list;
}
and severity = Error | Warning | Info | Inventory | Experiment
[@@deriving show]
Polymorhic variants used to improve type checking of rules ( see below )
type search_mode = [ `Search of formula ] [@@deriving show]
type taint_mode = [ `Taint of taint_spec ] [@@deriving show]
type extract_mode = [ `Extract of extract_spec ] [@@deriving show]
type mode = [ search_mode | taint_mode | extract_mode ] [@@deriving show]
type search_rule = search_mode rule_info [@@deriving show]
type taint_rule = taint_mode rule_info [@@deriving show]
type extract_rule = extract_mode rule_info [@@deriving show]
type rule = mode rule_info [@@deriving show]
type t = rule [@@deriving show]
type rules = rule list [@@deriving show]
type hrules = (rule_id, t) Hashtbl.t
let hrules_of_rules (rules : t list) : hrules =
rules |> Common.map (fun r -> (fst r.id, r)) |> Common.hash_of_list
let partition_rules (rules : rules) :
search_rule list * taint_rule list * extract_rule list =
rules
|> Common.partition_either3 (fun r ->
match r.mode with
| `Search _ as s -> Left3 { r with mode = s }
| `Taint _ as t -> Middle3 { r with mode = t }
| `Extract _ as e -> Right3 { r with mode = e })
This is used to let the user know which rule the engine was using when
* a Timeout or OutOfMemory exn occured .
* a Timeout or OutOfMemory exn occured.
*)
let last_matched_rule : rule_id option ref = ref None
type invalid_rule_error = invalid_rule_error_kind * rule_id * Parse_info.t
and invalid_rule_error_kind =
TODO : the Parse_info.t for InvalidPattern is not precise for now ;
* it corresponds to the start of the pattern
* it corresponds to the start of the pattern *)
| InvalidPattern of
* Xlang.t
PCRE error message
| MissingPositiveTermInAnd
| InvalidOther of string
[@@deriving show]
type error =
| InvalidRule of invalid_rule_error
| InvalidYaml of string * Parse_info.t
| DuplicateYamlKey of string * Parse_info.t
| UnparsableYamlException of string
exception Err of error
let string_of_invalid_rule_error_kind = function
| InvalidLanguage language -> spf "invalid language %s" language
| InvalidRegexp message -> spf "invalid regex %s" message
| InvalidPattern (pattern, xlang, message, _yaml_path) ->
spf
"Invalid pattern for %s: %s\n\
----- pattern -----\n\
%s\n\
----- end pattern -----\n"
(Xlang.to_string xlang) message pattern
| MissingPositiveTermInAnd ->
"you need at least one positive term (not just negations or conditions)"
| DeprecatedFeature s -> spf "deprecated feature: %s" s
| InvalidOther s -> s
let string_of_invalid_rule_error ((kind, rule_id, pos) : invalid_rule_error) =
spf "invalid rule %s, %s: %s" rule_id
(Parse_info.string_of_info pos)
(string_of_invalid_rule_error_kind kind)
let string_of_error (error : error) : string =
match error with
| InvalidRule x -> string_of_invalid_rule_error x
| InvalidYaml (msg, pos) ->
spf "invalid YAML, %s: %s" (Parse_info.string_of_info pos) msg
| DuplicateYamlKey (key, pos) ->
spf "invalid YAML, %s: duplicate key %S"
(Parse_info.string_of_info pos)
key
| UnparsableYamlException s ->
spf "unparsable YAML: %s" s
let opt_string_of_exn (exn : exn) =
match exn with
| Err x -> Some (string_of_error x)
| _else_ -> None
let register_exception_printer () = Printexc.register_printer opt_string_of_exn
currently used in Check_rule.ml metachecker
let visit_new_formula f formula =
let bref = ref false in
let rec visit_new_formula f formula =
match formula with
| P p -> f p !bref
| Inside (_, formula) ->
Common.save_excursion bref true (fun () -> visit_new_formula f formula)
| Not (_, x) -> visit_new_formula f x
| Or (_, xs)
| And (_, { conjuncts = xs; _ }) ->
xs |> List.iter (visit_new_formula f)
in
visit_new_formula f formula
let tok_of_formula = function
| And (t, _) -> t
| Or (t, _)
| Not (t, _) ->
t
| P p -> snd p.pstr
| Inside (t, _) -> t
let kind_of_formula = function
| P _ -> "pattern"
| Or _
| And _
| Inside _
| Not _ ->
"formula"
let split_and (xs : formula list) : formula list * (tok * formula) list =
xs
|> Common.partition_either (fun e ->
match e with
| P _
| And _
| Inside _
| Or _ ->
Left e
| Not (tok, f) -> Right (tok, f))
let rule_of_xpattern (xlang : Xlang.t) (xpat : Xpattern.t) : rule =
let fk = Parse_info.unsafe_fake_info "" in
{
id = ("-e", fk);
mode = `Search (P xpat);
message = "";
severity = Error;
languages = xlang;
options = None;
equivalences = None;
fix = None;
fix_regexp = None;
paths = None;
metadata = None;
}
|
7a1061fc5f4cc64750112af3341862d54fdf43c7a4025255e80d242cd40eaf34 | tnelson/Forge | address.rkt | #lang forge2
module tour/addressBook1
sig Name, Addr {}
sig Book {addr: Name -> lone Addr}
pred show (b: Book) {
#b.addr > 1
#Name.(b.addr) > 1
}
/*
run show for 3 but 1 Book
pred add (b, b': Book, n: Name, a: Addr) {b'.addr = b.addr + n -> a}
pred del (b, b': Book, n: Name) {b'.addr = b.addr - n -> Addr}
fun lookup (b: Book, n: Name): set Addr {n.(b.addr)}
pred showAdd (b, b': Book, n: Name, a: Addr) {
add [b, b', n, a]
#Name.(b'.addr) > 1
}
run showAdd for 3 but 2 Book
assert delUndoesAdd {
all b,b',b": Book, n: Name, a: Addr |
no n.(b.addr) and
add [b,b',n,a] and del [b',b",n] implies b.addr = b".addr
}
assert addIdempotent {
all b,b',b": Book, n: Name, a: Addr |
add [b,b',n,a] and add [b',b",n,a] implies b'.addr = b".addr
}
assert addLocal {
all b,b': Book, n,n': Name, a: Addr |
add [b,b',n,a] and n != n'
implies lookup [b,n'] = lookup [b',n']
}
check delUndoesAdd for 10 but 3 Book
check addIdempotent for 3
check addLocal for 3 but 2 Book
*/ | null | https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/examples/address.rkt | racket | #lang forge2
module tour/addressBook1
sig Name, Addr {}
sig Book {addr: Name -> lone Addr}
pred show (b: Book) {
#b.addr > 1
#Name.(b.addr) > 1
}
/*
run show for 3 but 1 Book
pred add (b, b': Book, n: Name, a: Addr) {b'.addr = b.addr + n -> a}
pred del (b, b': Book, n: Name) {b'.addr = b.addr - n -> Addr}
fun lookup (b: Book, n: Name): set Addr {n.(b.addr)}
pred showAdd (b, b': Book, n: Name, a: Addr) {
add [b, b', n, a]
#Name.(b'.addr) > 1
}
run showAdd for 3 but 2 Book
assert delUndoesAdd {
all b,b',b": Book, n: Name, a: Addr |
no n.(b.addr) and
add [b,b',n,a] and del [b',b",n] implies b.addr = b".addr
}
assert addIdempotent {
all b,b',b": Book, n: Name, a: Addr |
add [b,b',n,a] and add [b',b",n,a] implies b'.addr = b".addr
}
assert addLocal {
all b,b': Book, n,n': Name, a: Addr |
add [b,b',n,a] and n != n'
implies lookup [b,n'] = lookup [b',n']
}
check delUndoesAdd for 10 but 3 Book
check addIdempotent for 3
check addLocal for 3 but 2 Book
*/ | |
99782214b5392566889a0161ece2e676f8119f1b517f3f2e631df45fa17d8845 | acowley/hpp | Directive.hs | # LANGUAGE LambdaCase , OverloadedStrings , ScopedTypeVariables ,
ViewPatterns #
ViewPatterns #-}
| Implement the logic of CPP directives ( commands prefixed with an
octothorpe ) .
module Hpp.Directive (directive, macroExpansion) where
import Control.Monad (unless)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Except
import Control.Monad.Trans.State.Strict (StateT)
import Hpp.Conditional (dropBranch, takeBranch)
import Hpp.Config (curFileName, curFileNameF)
import Hpp.Env (lookupKey, deleteKey, insertPair)
import Hpp.Expansion (expandLineState)
import Hpp.Expr (evalExpr, parseExpr)
import Hpp.Macro (parseDefinition)
import Hpp.Preprocessing (prepareInput)
import Hpp.StringSig (unquote, toChars)
import Hpp.Tokens (newLine, notImportant, trimUnimportant, detokenize, isImportant, Token(..))
import Hpp.Types
import Hpp.Parser (replace, await, insertInputSegment, takingWhile, droppingWhile, onInputSegment, evalParse, onElements, awaitJust, ParserT, Parser)
import Text.Read (readMaybe)
import Prelude hiding (String)
-- | Returns everything up to the next newline. The newline character
-- itself is consumed.
takeLine :: (Monad m, HasError m, HasHppState m) => Parser m [TOKEN] [TOKEN]
takeLine = (onElements $ do
ln <- takingWhile (not . newLine)
eat <- awaitJust "takeLine" -- Eat the newline character
case eat of
Other "\n" -> return ()
wat -> error $ "Expected newline: "++show wat++" after "++show ln
return ln)
<* (lineNum %= (+1))
dropLine :: (Monad m, HasError m, HasHppState m) => Parser m [TOKEN] ()
dropLine = do onElements $ do
droppingWhile (not . newLine)
eat <- awaitJust "dropLine" -- Eat the newline character
case eat of
Other "\n" -> return ()
wat -> error $ "Expected dropped newline: "++show wat
lineNum %= (+1)
droppingSpaces ::(Monad m) => ParserT m src TOKEN ()
droppingSpaces = droppingWhile notImportant
-- | Run a Stream with a configuration for a new file.
streamNewFile :: (Monad m, HasHppState m)
=> FilePath -> [[TOKEN]] -> Parser m [TOKEN] ()
streamNewFile fp s =
do (oldCfg,oldLine) <- do st <- getState
let cfg = hppConfig st
cfg' = cfg { curFileNameF = pure fp }
ln = hppLineNum st
-- NOTE: We should *NOT* use a the config lens here
-- because it will mutate the directory which
-- we *don't* want in this instance.
setState (st {hppConfig = cfg', hppLineNum = 1})
return (cfg, ln)
insertInputSegment
s (getState >>= setState . setL lineNum oldLine . setL config oldCfg)
| Handle preprocessor directives ( commands prefixed with an octothorpe ) .
directive :: forall m. (Monad m, HasError m, HasHppState m, HasEnv m)
=> HppT [String] (Parser m [TOKEN]) Bool
directive = lift (onElements (awaitJust "directive")) >>= aux
where aux :: TOKEN -> HppT [String] (Parser m [TOKEN]) Bool
aux (Important cmd) = case cmd of
"pragma" -> True <$ lift dropLine -- Ignored
"define" -> True <$
(lift $ fmap parseDefinition takeLine >>= \case
Nothing -> use lineNum >>=
throwError . BadMacroDefinition
Just def -> env %= insertPair def)
"undef" -> do name <- lift . onElements $ do
droppingWhile (not . isImportant)
name <- awaitJust "undef" >>= \case
Important n -> return n
_ -> error "undef directive got Other token"
return name
lift dropLine
env %= deleteKey name
return True
"include" -> True <$ includeAux hppReadFile
"include_next" -> True <$ includeAux hppReadNext
"line" -> do lift (onElements droppingSpaces)
toks <- lift (init <$> expandLineState)
case toks of
Important (toChars -> n):optFile ->
case readMaybe n of
Nothing -> use lineNum >>=
throwError . flip BadLineArgument n
Just ln' -> do
unless (null optFile) $ do
let fn = toChars . unquote . detokenize
. dropWhile (not . isImportant)
$ optFile
config %= (\cfg -> cfg { curFileNameF = pure fn })
lineNum .= ln'
return True
_ -> use lineNum >>=
throwError
. flip BadLineArgument (toChars (detokenize toks))
"ifdef" ->
do toks <- lift (onElements droppingSpaces >> takeLine)
ln <- use lineNum
case takeWhile isImportant toks of
[Important t] ->
lookupMacro t >>= \case
Nothing ->
lift dropBranch
Just _ ->
( takeBranch ln > > = precede )
_ -> throwError . UnknownCommand ln $
"ifdef "++ toChars (detokenize toks)
return True
"ifndef" ->
do toks <- lift (onElements droppingSpaces >> takeLine)
ln <- use lineNum
case takeWhile isImportant toks of
[Important t] ->
lookupMacro t >>= \case
Nothing -> lift (onInputSegment (takeBranch ln)) -- takeBranch ln >>= precede)
Just _ -> lift dropBranch
_ -> throwError . UnknownCommand ln $
"ifndef "++ toChars (detokenize toks)
return True
"else" -> True <$ lift dropLine
"if" -> True <$ ifAux
"elif" -> True <$ ifAux
"endif" -> True <$ lift dropLine
"error" -> do toks <- lift (onElements droppingSpaces >> takeLine)
ln <- subtract 1 <$> use lineNum
curFile <- curFileName <$> use config
let tokStr = toChars (detokenize toks)
throwError $ UserError ln (tokStr++" ("++curFile++")")
"warning" -> True <$ lift dropLine -- warnings not yet supported
t -> do toks <- lift takeLine
ln <- subtract 1 <$> use lineNum
throwError $ UnknownCommand ln
(toChars (detokenize (Important t:toks)))
aux _ = error "Impossible unimportant directive"
includeAux :: (LineNum -> FilePath -> HppT src (Parser m [TOKEN]) [String])
-> HppT src (Parser m [TOKEN]) ()
includeAux readFun =
do fileName <- lift (toChars . detokenize . trimUnimportant . init
<$> expandLineState)
ln <- use lineNum
src <- prepareInput <*> readFun ln fileName
lineNum .= ln+1
lift (streamNewFile (unquote fileName) src)
SPECIALIZE includeAux : :
( LineNum - > FilePath - > HppT [ String ] ( ( StateT HppState ( ExceptT Error IO ) ) [ TOKEN ] ) [ String ] )
- > HppT [ String ] ( ( StateT HppState ( ExceptT Error IO ) ) [ TOKEN ] ) ( ) #
(LineNum -> FilePath -> HppT [String] (Parser (StateT HppState (ExceptT Error IO)) [TOKEN]) [String])
-> HppT [String] (Parser (StateT HppState (ExceptT Error IO)) [TOKEN]) () #-}
ifAux =
do toks <- lift (onElements droppingSpaces >> takeLine)
e <- use env
ln <- use lineNum
lineNum .= ln - 1 -- takeLine incremented the line count
ex <- lift (lift (evalParse expandLineState [squashDefines e toks]))
let res = evalExpr <$> parseExpr (map (fmap toChars) ex)
lineNum .= ln
if maybe False (/= 0) res
( takeBranch ln > > = precede )
else lift dropBranch
# SPECIALIZE directive : :
HppT [ String ] ( ( StateT HppState ( ExceptT Error IO ) ) [ TOKEN ] ) Bool #
HppT [String] (Parser (StateT HppState (ExceptT Error IO)) [TOKEN]) Bool #-}
-- | We want to expand macros in expressions that must be evaluated
-- for conditionals, but we want to take special care when dealing
with the meta @defined@ operator of the expression language that is
-- a predicate on the evaluation environment.
squashDefines :: Env -> [TOKEN] -> [TOKEN]
squashDefines _ [] = []
squashDefines env' (Important "defined" : ts) = go ts
where go (t@(Other _) : ts') = t : go ts'
go (t@(Important "(") : ts') = t : go ts'
go (Important t : ts') =
case lookupKey t env' of
Nothing -> Important "0" : squashDefines env' ts'
Just ( _ , env '' ) - > Important " 1 " : squashDefines env '' ts '
Just _ -> Important "1" : squashDefines env' ts'
go [] = []
squashDefines env' (t : ts) = t : squashDefines env' ts
-- | Expands an input line producing a stream of output lines.
macroExpansion :: (Monad m, HasHppState m, HasError m, HasEnv m)
=> HppT [String] (Parser m [TOKEN]) (Maybe [TOKEN])
macroExpansion = do
lift await >>= \case
Nothing -> return Nothing
Just ln ->
-- when (not (all isSpace (detokenize ln)))
-- (trace ("macro expand: "++detokenize ln) (return ())) >>
case dropWhile notImportant ln of
[] -> Just ln <$ (lineNum %= (+1))
Important "#":rst -> do lift (replace (dropWhile notImportant rst))
processed <- directive
if processed
then macroExpansion
else Just ln <$ lift takeLine
_ -> lift (replace ln >> (Just <$> expandLineState)) <* (lineNum %= (+1))
| null | https://raw.githubusercontent.com/acowley/hpp/e54be4a8da7c9812c2a5e3f7f69ffe13ad7ea638/src/Hpp/Directive.hs | haskell | | Returns everything up to the next newline. The newline character
itself is consumed.
Eat the newline character
Eat the newline character
| Run a Stream with a configuration for a new file.
NOTE: We should *NOT* use a the config lens here
because it will mutate the directory which
we *don't* want in this instance.
Ignored
takeBranch ln >>= precede)
warnings not yet supported
takeLine incremented the line count
| We want to expand macros in expressions that must be evaluated
for conditionals, but we want to take special care when dealing
a predicate on the evaluation environment.
| Expands an input line producing a stream of output lines.
when (not (all isSpace (detokenize ln)))
(trace ("macro expand: "++detokenize ln) (return ())) >> | # LANGUAGE LambdaCase , OverloadedStrings , ScopedTypeVariables ,
ViewPatterns #
ViewPatterns #-}
| Implement the logic of CPP directives ( commands prefixed with an
octothorpe ) .
module Hpp.Directive (directive, macroExpansion) where
import Control.Monad (unless)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Except
import Control.Monad.Trans.State.Strict (StateT)
import Hpp.Conditional (dropBranch, takeBranch)
import Hpp.Config (curFileName, curFileNameF)
import Hpp.Env (lookupKey, deleteKey, insertPair)
import Hpp.Expansion (expandLineState)
import Hpp.Expr (evalExpr, parseExpr)
import Hpp.Macro (parseDefinition)
import Hpp.Preprocessing (prepareInput)
import Hpp.StringSig (unquote, toChars)
import Hpp.Tokens (newLine, notImportant, trimUnimportant, detokenize, isImportant, Token(..))
import Hpp.Types
import Hpp.Parser (replace, await, insertInputSegment, takingWhile, droppingWhile, onInputSegment, evalParse, onElements, awaitJust, ParserT, Parser)
import Text.Read (readMaybe)
import Prelude hiding (String)
takeLine :: (Monad m, HasError m, HasHppState m) => Parser m [TOKEN] [TOKEN]
takeLine = (onElements $ do
ln <- takingWhile (not . newLine)
case eat of
Other "\n" -> return ()
wat -> error $ "Expected newline: "++show wat++" after "++show ln
return ln)
<* (lineNum %= (+1))
dropLine :: (Monad m, HasError m, HasHppState m) => Parser m [TOKEN] ()
dropLine = do onElements $ do
droppingWhile (not . newLine)
case eat of
Other "\n" -> return ()
wat -> error $ "Expected dropped newline: "++show wat
lineNum %= (+1)
droppingSpaces ::(Monad m) => ParserT m src TOKEN ()
droppingSpaces = droppingWhile notImportant
streamNewFile :: (Monad m, HasHppState m)
=> FilePath -> [[TOKEN]] -> Parser m [TOKEN] ()
streamNewFile fp s =
do (oldCfg,oldLine) <- do st <- getState
let cfg = hppConfig st
cfg' = cfg { curFileNameF = pure fp }
ln = hppLineNum st
setState (st {hppConfig = cfg', hppLineNum = 1})
return (cfg, ln)
insertInputSegment
s (getState >>= setState . setL lineNum oldLine . setL config oldCfg)
| Handle preprocessor directives ( commands prefixed with an octothorpe ) .
directive :: forall m. (Monad m, HasError m, HasHppState m, HasEnv m)
=> HppT [String] (Parser m [TOKEN]) Bool
directive = lift (onElements (awaitJust "directive")) >>= aux
where aux :: TOKEN -> HppT [String] (Parser m [TOKEN]) Bool
aux (Important cmd) = case cmd of
"define" -> True <$
(lift $ fmap parseDefinition takeLine >>= \case
Nothing -> use lineNum >>=
throwError . BadMacroDefinition
Just def -> env %= insertPair def)
"undef" -> do name <- lift . onElements $ do
droppingWhile (not . isImportant)
name <- awaitJust "undef" >>= \case
Important n -> return n
_ -> error "undef directive got Other token"
return name
lift dropLine
env %= deleteKey name
return True
"include" -> True <$ includeAux hppReadFile
"include_next" -> True <$ includeAux hppReadNext
"line" -> do lift (onElements droppingSpaces)
toks <- lift (init <$> expandLineState)
case toks of
Important (toChars -> n):optFile ->
case readMaybe n of
Nothing -> use lineNum >>=
throwError . flip BadLineArgument n
Just ln' -> do
unless (null optFile) $ do
let fn = toChars . unquote . detokenize
. dropWhile (not . isImportant)
$ optFile
config %= (\cfg -> cfg { curFileNameF = pure fn })
lineNum .= ln'
return True
_ -> use lineNum >>=
throwError
. flip BadLineArgument (toChars (detokenize toks))
"ifdef" ->
do toks <- lift (onElements droppingSpaces >> takeLine)
ln <- use lineNum
case takeWhile isImportant toks of
[Important t] ->
lookupMacro t >>= \case
Nothing ->
lift dropBranch
Just _ ->
( takeBranch ln > > = precede )
_ -> throwError . UnknownCommand ln $
"ifdef "++ toChars (detokenize toks)
return True
"ifndef" ->
do toks <- lift (onElements droppingSpaces >> takeLine)
ln <- use lineNum
case takeWhile isImportant toks of
[Important t] ->
lookupMacro t >>= \case
Just _ -> lift dropBranch
_ -> throwError . UnknownCommand ln $
"ifndef "++ toChars (detokenize toks)
return True
"else" -> True <$ lift dropLine
"if" -> True <$ ifAux
"elif" -> True <$ ifAux
"endif" -> True <$ lift dropLine
"error" -> do toks <- lift (onElements droppingSpaces >> takeLine)
ln <- subtract 1 <$> use lineNum
curFile <- curFileName <$> use config
let tokStr = toChars (detokenize toks)
throwError $ UserError ln (tokStr++" ("++curFile++")")
t -> do toks <- lift takeLine
ln <- subtract 1 <$> use lineNum
throwError $ UnknownCommand ln
(toChars (detokenize (Important t:toks)))
aux _ = error "Impossible unimportant directive"
includeAux :: (LineNum -> FilePath -> HppT src (Parser m [TOKEN]) [String])
-> HppT src (Parser m [TOKEN]) ()
includeAux readFun =
do fileName <- lift (toChars . detokenize . trimUnimportant . init
<$> expandLineState)
ln <- use lineNum
src <- prepareInput <*> readFun ln fileName
lineNum .= ln+1
lift (streamNewFile (unquote fileName) src)
SPECIALIZE includeAux : :
( LineNum - > FilePath - > HppT [ String ] ( ( StateT HppState ( ExceptT Error IO ) ) [ TOKEN ] ) [ String ] )
- > HppT [ String ] ( ( StateT HppState ( ExceptT Error IO ) ) [ TOKEN ] ) ( ) #
(LineNum -> FilePath -> HppT [String] (Parser (StateT HppState (ExceptT Error IO)) [TOKEN]) [String])
-> HppT [String] (Parser (StateT HppState (ExceptT Error IO)) [TOKEN]) () #-}
ifAux =
do toks <- lift (onElements droppingSpaces >> takeLine)
e <- use env
ln <- use lineNum
ex <- lift (lift (evalParse expandLineState [squashDefines e toks]))
let res = evalExpr <$> parseExpr (map (fmap toChars) ex)
lineNum .= ln
if maybe False (/= 0) res
( takeBranch ln > > = precede )
else lift dropBranch
# SPECIALIZE directive : :
HppT [ String ] ( ( StateT HppState ( ExceptT Error IO ) ) [ TOKEN ] ) Bool #
HppT [String] (Parser (StateT HppState (ExceptT Error IO)) [TOKEN]) Bool #-}
with the meta @defined@ operator of the expression language that is
squashDefines :: Env -> [TOKEN] -> [TOKEN]
squashDefines _ [] = []
squashDefines env' (Important "defined" : ts) = go ts
where go (t@(Other _) : ts') = t : go ts'
go (t@(Important "(") : ts') = t : go ts'
go (Important t : ts') =
case lookupKey t env' of
Nothing -> Important "0" : squashDefines env' ts'
Just ( _ , env '' ) - > Important " 1 " : squashDefines env '' ts '
Just _ -> Important "1" : squashDefines env' ts'
go [] = []
squashDefines env' (t : ts) = t : squashDefines env' ts
macroExpansion :: (Monad m, HasHppState m, HasError m, HasEnv m)
=> HppT [String] (Parser m [TOKEN]) (Maybe [TOKEN])
macroExpansion = do
lift await >>= \case
Nothing -> return Nothing
Just ln ->
case dropWhile notImportant ln of
[] -> Just ln <$ (lineNum %= (+1))
Important "#":rst -> do lift (replace (dropWhile notImportant rst))
processed <- directive
if processed
then macroExpansion
else Just ln <$ lift takeLine
_ -> lift (replace ln >> (Just <$> expandLineState)) <* (lineNum %= (+1))
|
4370bb9cb4511106fb2c4d23590848928244cf88f01a2e928f4dadff15de8543 | crisptrutski/matchbox | utils.cljc | (ns matchbox.utils
(:refer-clojure :exclude [prn])
(:require [clojure.string :as str]))
(defn kebab->underscore [keyword]
(-> keyword name (str/replace "-" "_")))
(defn underscore->kebab [string]
(-> string (str/replace "_" "-") keyword))
(defn korks->path [korks]
(if (sequential? korks)
(str/join "/" (map name korks))
(when korks (name korks))))
(defn no-op ([_]) ([_ _]) ([_ _ _]) ([_ _ _ & _]))
(defn extract-cb [args]
(if (and (>= (count args) 2)
(= (first (take-last 2 args)) :callback))
[(last args) (drop-last 2 args)]
[nil args]))
;;
(defprotocol ISerializer
(hydrate [this x])
(serialize [this x])
(config! [this hydrate serialize]))
(deftype Serializer
[#?(:clj ^:volatile-mutable hydrate :cljs ^:mutable hydrate)
#?(:clj ^:volatile-mutable serialize :cljs ^:mutable serialize)]
ISerializer
(hydrate [_ x] (hydrate x))
(serialize [_ x] (serialize x))
(config! [_ h s] (set! hydrate h) (set! serialize s)))
(defn set-date-config! [hydrate serialize]
(-> ^Serializer
#?(:clj @(resolve 'matchbox.core/data-config)
:cljs matchbox.core/data-config)
(config! hydrate serialize)))
#?(:clj (def repl-out *out*))
#?(:clj
(defn prn
"Like clojure.core/prn, but always bound to root thread's *out*"
[& args]
(binding [*out* repl-out]
(apply clojure.core/prn args))))
| null | https://raw.githubusercontent.com/crisptrutski/matchbox/5bb9ba96f5df01bce302a8232f6cddd9d64a1d71/src/matchbox/utils.cljc | clojure | (ns matchbox.utils
(:refer-clojure :exclude [prn])
(:require [clojure.string :as str]))
(defn kebab->underscore [keyword]
(-> keyword name (str/replace "-" "_")))
(defn underscore->kebab [string]
(-> string (str/replace "_" "-") keyword))
(defn korks->path [korks]
(if (sequential? korks)
(str/join "/" (map name korks))
(when korks (name korks))))
(defn no-op ([_]) ([_ _]) ([_ _ _]) ([_ _ _ & _]))
(defn extract-cb [args]
(if (and (>= (count args) 2)
(= (first (take-last 2 args)) :callback))
[(last args) (drop-last 2 args)]
[nil args]))
(defprotocol ISerializer
(hydrate [this x])
(serialize [this x])
(config! [this hydrate serialize]))
(deftype Serializer
[#?(:clj ^:volatile-mutable hydrate :cljs ^:mutable hydrate)
#?(:clj ^:volatile-mutable serialize :cljs ^:mutable serialize)]
ISerializer
(hydrate [_ x] (hydrate x))
(serialize [_ x] (serialize x))
(config! [_ h s] (set! hydrate h) (set! serialize s)))
(defn set-date-config! [hydrate serialize]
(-> ^Serializer
#?(:clj @(resolve 'matchbox.core/data-config)
:cljs matchbox.core/data-config)
(config! hydrate serialize)))
#?(:clj (def repl-out *out*))
#?(:clj
(defn prn
"Like clojure.core/prn, but always bound to root thread's *out*"
[& args]
(binding [*out* repl-out]
(apply clojure.core/prn args))))
| |
8cb9ec7e92476c4d24018ad01aa0663b82a1bd5a702a86201a997199bfd79509 | DOBRO/uef-lib | uef_bin_tests.erl | Copyright ( c ) 2019 - 2022 , < > . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
-module(uef_bin_tests).
-include_lib("eunit/include/eunit.hrl").
%%%------------------------------------------------------------------------------
%%% Test functions
%%%------------------------------------------------------------------------------
numeric_prefix_test_() ->
[
?_assertEqual(<<>>, uef_bin:numeric_prefix(<<"a234234">>)),
?_assertEqual(<<"123">>, uef_bin:numeric_prefix(<<"123a456">>)),
?_assertEqual(<<"123">>, uef_bin:numeric_prefix(<<"123">>)),
?_assertEqual(<<"0">>, uef_bin:numeric_prefix(<<"0test">>)),
?_assertEqual(<<"1">>, uef_bin:numeric_prefix(<<"1test">>)),
?_assertEqual(<<"2">>, uef_bin:numeric_prefix(<<"2test">>)),
?_assertEqual(<<"3">>, uef_bin:numeric_prefix(<<"3test">>)),
?_assertEqual(<<"4">>, uef_bin:numeric_prefix(<<"4test">>)),
?_assertEqual(<<"5">>, uef_bin:numeric_prefix(<<"5test">>)),
?_assertEqual(<<"6">>, uef_bin:numeric_prefix(<<"6test">>)),
?_assertEqual(<<"7">>, uef_bin:numeric_prefix(<<"7test">>)),
?_assertEqual(<<"8">>, uef_bin:numeric_prefix(<<"8test">>)),
?_assertEqual(<<"9">>, uef_bin:numeric_prefix(<<"9test">>))
].
binary_join_test_() ->
[
?_assertEqual(<<>>, uef_bin:binary_join([], <<"any">>)),
?_assertEqual(<<>>, uef_bin:binary_join([], <<>>)),
?_assertEqual(<<"www.example.com">>, uef_bin:binary_join([<<"www">>, <<"example">>, <<"com">>], <<".">>)),
?_assertEqual(<<"www">>, uef_bin:binary_join([<<"www">>], <<".">>))
].
split_test_() ->
[
?_assertEqual([], uef_bin:split(<<>>, <<".">>)),
?_assertEqual([], uef_bin:split(<<>>, <<>>)),
?_assertEqual([<<".www.example.com.">>], uef_bin:split(<<".www.example.com.">>, <<>>, trim_all)),
?_assertEqual([<<>>,<<"www">>,<<"example">>,<<"com">>,<<>>], uef_bin:split(<<".www.example.com.">>, <<".">>)),
?_assertEqual([<<"www">>,<<"example">>,<<"com">>], uef_bin:split(<<"www.example.com">>, <<".">>)),
?_assertEqual([<<"www.example.com">>], uef_bin:split(<<"www.example.com">>, <<"A">>)),
?_assertEqual([<<"www">>,<<"example">>,<<"com">>], uef_bin:split(<<".....www.example.com....">>, <<".">>, trim_all))
].
repeat_test_() ->
[
?_assertEqual(<<"0">>, uef_bin:repeat(<<"0">>, 1)),
?_assertEqual(<<"aaaaa">>, uef_bin:repeat(<<"a">>, 5)),
?_assertEqual(<<0>>, uef_bin:repeat(<<0>>, 1)),
?_assertEqual(<<0,0,0>>, uef_bin:repeat(<<0>>, 3)),
?_assertEqual(<<1,1,1,1>>, uef_bin:repeat(<<1,1>>, 2)),
?_assertEqual(<<1,0,1,0>>, uef_bin:repeat(<<1,0>>, 2)),
?_assertEqual(<<"abcabcabc">>, uef_bin:repeat(<<"abc">>, 3)),
?_assertEqual(<<"ЖЖЖ"/utf8>>, uef_bin:repeat(<<"Ж"/utf8>>, 3))
].
replace_test_() ->
[
?_assertEqual(<<>>, uef_bin:replace(<<>>, <<"aa">>, <<"bb">>)),
?_assertEqual(<<"bbb">>, uef_bin:replace(<<"bbb">>, <<>>, <<"b">>)),
?_assertEqual(<<"aZZdefgZZ">>, uef_bin:replace(<<"abcdefgbc">>, <<"bc">>, <<"ZZ">>)),
?_assertEqual(<<"abcZZefgbc">>, uef_bin:replace(<<"abcdefgbc">>, <<"d">>, <<"ZZ">>))
].
replace_chars_test_() ->
[
?_assertEqual(<<"bbb">>, uef_bin:replace_chars(<<"bbb">>, [], <<>>)),
?_assertEqual(<<"wwwexamplecom">>, uef_bin:replace_chars(<<"..www.example.com.">>, [<<".">>], <<>>)),
?_assertEqual(<<"examplecom">>, uef_bin:replace_chars(<<"..www.example.com.">>, [<<".">>, <<"w">>], <<>>))
].
reverse_test_() ->
[
?_assertEqual(<<5,4,3,2,1>>, uef_bin:reverse(<<1,2,3,4,5>>)),
?_assertEqual(<<"HGFEDCBA">>, uef_bin:reverse(<<"ABCDEFGH">>)),
?_assertEqual(<<>>, uef_bin:reverse(<<>>)),
?_assertEqual(<<0>>, uef_bin:reverse(<<0>>)),
?_assertEqual(<<"0">>, uef_bin:reverse(<<"0">>)),
?_assertEqual(<<1>>, uef_bin:reverse(<<1>>)),
?_assertEqual(<<"1">>, uef_bin:reverse(<<"1">>)),
?_assertEqual(<<0, 0, 0>>, uef_bin:reverse(<<0, 0, 0>>)),
?_assertEqual(<<"ВБА">>, uef_bin:reverse(<<"АБВ">>))
].
reverse_utf8_test_() ->
[
?_assertEqual(<<5,4,3,2,1,0>>, uef_bin:reverse_utf8(<<0,1,2,3,4,5>>)),
?_assertEqual(<<"543210">>, uef_bin:reverse_utf8(<<"012345">>)),
?_assertEqual(<<"HGFEDCBA">>, uef_bin:reverse_utf8(<<"ABCDEFGH">>)),
?_assertEqual(<<>>, uef_bin:reverse_utf8(<<>>)),
?_assertEqual(<<0>>, uef_bin:reverse_utf8(<<0>>)),
?_assertEqual(<<"0">>, uef_bin:reverse_utf8(<<"0">>)),
?_assertEqual(<<1>>, uef_bin:reverse_utf8(<<1>>)),
?_assertEqual(<<"1">>, uef_bin:reverse_utf8(<<"1">>)),
?_assertEqual(<<0, 0, 0>>, uef_bin:reverse_utf8(<<0, 0, 0>>)),
?_assertEqual(<<"ВБА">>, uef_bin:reverse_utf8(<<"АБВ">>)),
?_assertEqual(<<"ЖЁЕДГВБА"/utf8>>, uef_bin:reverse_utf8(<<"АБВГДЕЁЖ"/utf8>>)),
?_assertEqual(<<7, 6, 5, 4, "ЖЁЕДГВБА"/utf8, 3, 2, 1>>, uef_bin:reverse_utf8(<<1, 2, 3, "АБВГДЕЁЖ"/utf8, 4, 5, 6, 7>>)),
?_assertEqual(<<"eßartS eid"/utf8>>, uef_bin:reverse_utf8(<<"die Straße"/utf8>>)),
?_assertEqual(<<"街條這"/utf8>>, uef_bin:reverse_utf8(<<"這條街"/utf8>>)),
?_assertEqual(<<"好你"/utf8>>, uef_bin:reverse_utf8(<<"你好"/utf8>>)),
?_assertEqual(<<"り通"/utf8>>, uef_bin:reverse_utf8(<<"通り"/utf8>>)),
?_assertEqual(<<"はちにんこ"/utf8>>, uef_bin:reverse_utf8(<<"こんにちは"/utf8>>))
].
random_latin_binary_test_() ->
Length = 11,
RandomLower = uef_bin:random_latin_binary(Length, lower),
RandomUpper = uef_bin:random_latin_binary(Length, upper),
RandomAny = uef_bin:random_latin_binary(Length, any),
[
?_assert(erlang:is_integer(Length) andalso Length > 0),
?_assertEqual(Length, erlang:byte_size(RandomLower)),
?_assertEqual(Length, erlang:byte_size(RandomUpper)),
?_assertEqual(Length, erlang:byte_size(RandomAny)),
?_assertEqual(ok, validate_random_latin_binary(RandomLower, lower)),
?_assertEqual(ok, validate_random_latin_binary(RandomUpper, upper)),
?_assertEqual(ok, validate_random_latin_binary(RandomAny, any))
].
strip_left_test_() ->
[
?_assertEqual(<<>>, uef_bin:strip_left(<<>>, <<"any">>)),
?_assertEqual(<<"test">>, uef_bin:strip_left(<<"test">>, <<>>)),
?_assertEqual(<<"est">>, uef_bin:strip_left(<<"ttest">>, <<"t">>)),
?_assertEqual(<<"est">>, uef_bin:strip_left(<<"ttest">>, <<"tt">>)),
?_assertEqual(<<"test">>, uef_bin:strip_left(<<"tttest">>, <<"tt">>)),
?_assertEqual(<<"est">>, uef_bin:strip_left(<<"ttest">>, $t)),
?_assertEqual(<<"est">>, uef_bin:strip_left(<<"tttest">>, $t)),
?_assertEqual(<<"aa">>, uef_bin:strip_left(<<"aa">>, <<"aaa">>)),
?_assertEqual(<<>>, uef_bin:strip_left(<<"aaaaaa">>, $a)),
?_assertEqual(<<>>, uef_bin:strip_left(<<"aaaaaa">>, <<"a">>)),
?_assertEqual(<<"st">>, uef_bin:strip_left(<<"test">>, <<"te">>)),
?_assertEqual(<<"st">>, uef_bin:strip_left(<<"tetest">>, <<"te">>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_left(<<1,1,1,2,3,4,5>>, <<1>>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_left(<<1,1,1,2,3,4,5>>, 1)),
?_assertEqual(<<1,2,3,4,5>>, uef_bin:strip_left(<<1,1,1,2,3,4,5>>, <<1,1>>)),
?_assertEqual(<<>>, uef_bin:strip_left(<<10, 10, 10, 10>>, 10)),
?_assertEqual(<<>>, uef_bin:strip_left(<<10, 10, 10, 10>>, <<10>>)),
?_assertEqual(<<"ривет"/utf8>>, uef_bin:strip_left(<<"привет"/utf8>>, <<"п"/utf8>>)),
?_assertEqual(<<"ривет"/utf8>>, uef_bin:strip_left(<<"пппривет"/utf8>>, <<"п"/utf8>>)),
?_assertEqual(<<"ивет"/utf8>>, uef_bin:strip_left(<<"привет"/utf8>>, <<"пр"/utf8>>))
].
strip_right_test_() ->
[
?_assertEqual(<<>>, uef_bin:strip_right(<<>>, <<"any">>)),
?_assertEqual(<<"test">>, uef_bin:strip_right(<<"test">>, <<>>)),
?_assertEqual(<<"tes">>, uef_bin:strip_right(<<"testtt">>, <<"t">>)),
?_assertEqual(<<"test">>, uef_bin:strip_right(<<"testtt">>, <<"tt">>)),
?_assertEqual(<<"test">>, uef_bin:strip_right(<<"testtttt">>, <<"tt">>)),
?_assertEqual(<<"tes">>, uef_bin:strip_right(<<"testtt">>, $t)),
?_assertEqual(<<"aa">>, uef_bin:strip_right(<<"aa">>, <<"aaa">>)),
?_assertEqual(<<>>, uef_bin:strip_right(<<"aaaaaa">>, $a)),
?_assertEqual(<<>>, uef_bin:strip_right(<<"aaaaaa">>, <<"a">>)),
?_assertEqual(<<"te">>, uef_bin:strip_right(<<"test">>, <<"st">>)),
?_assertEqual(<<"t">>, uef_bin:strip_right(<<"test">>, <<"est">>)),
?_assertEqual(<<>>, uef_bin:strip_right(<<"test">>, <<"test">>)),
?_assertEqual(<<1,2,3,4>>, uef_bin:strip_right(<<1,2,3,4,5,5,5>>, <<5>>)),
?_assertEqual(<<1,2,3,4>>, uef_bin:strip_right(<<1,2,3,4,5,5,5>>, 5)),
?_assertEqual(<<1,2,3,4,5>>, uef_bin:strip_right(<<1,2,3,4,5,5,5>>, <<5,5>>)),
?_assertEqual(<<>>, uef_bin:strip_right(<<10, 10, 10, 10>>, 10)),
?_assertEqual(<<>>, uef_bin:strip_right(<<10, 10, 10, 10>>, <<10>>)),
?_assertEqual(<<"приве"/utf8>>, uef_bin:strip_right(<<"привет"/utf8>>, <<"т"/utf8>>)),
?_assertEqual(<<"приве"/utf8>>, uef_bin:strip_right(<<"приветттт"/utf8>>, <<"т"/utf8>>)),
?_assertEqual(<<"привет"/utf8>>, uef_bin:strip_right(<<"приветтттт"/utf8>>, <<"тт"/utf8>>))
].
strip_both_test_() ->
[
?_assertEqual(<<>>, uef_bin:strip_both(<<>>, <<"any">>)),
?_assertEqual(<<"test">>, uef_bin:strip_both(<<"test">>, <<>>)),
?_assertEqual(<<"es">>, uef_bin:strip_both(<<"tttest">>, <<"t">>)),
?_assertEqual(<<"est">>, uef_bin:strip_both(<<"ttest">>, <<"tt">>)),
?_assertEqual(<<"test">>, uef_bin:strip_both(<<"tttest">>, <<"tt">>)),
?_assertEqual(<<"test">>, uef_bin:strip_both(<<"tttesttt">>, <<"tt">>)),
?_assertEqual(<<"es">>, uef_bin:strip_both(<<"ttest">>, $t)),
?_assertEqual(<<"es">>, uef_bin:strip_both(<<"tttesttt">>, $t)),
?_assertEqual(<<"aa">>, uef_bin:strip_both(<<"aa">>, <<"aaa">>)),
?_assertEqual(<<>>, uef_bin:strip_both(<<"aaaaaa">>, $a)),
?_assertEqual(<<>>, uef_bin:strip_both(<<"aaaaaa">>, <<"a">>)),
?_assertEqual(<<"st">>, uef_bin:strip_both(<<"test">>, <<"te">>)),
?_assertEqual(<<"st">>, uef_bin:strip_both(<<"tetest">>, <<"te">>)),
?_assertEqual(<<"te">>, uef_bin:strip_both(<<"test">>, <<"st">>)),
?_assertEqual(<<"te">>, uef_bin:strip_both(<<"testst">>, <<"st">>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_both(<<1,1,1,2,3,4,5>>, <<1>>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_both(<<1,1,1,2,3,4,5>>, 1)),
?_assertEqual(<<1,2,3,4,5>>, uef_bin:strip_both(<<1,1,1,2,3,4,5>>, <<1,1>>)),
?_assertEqual(<<>>, uef_bin:strip_both(<<10, 10, 10, 10>>, 10)),
?_assertEqual(<<>>, uef_bin:strip_both(<<10, 10, 10, 10>>, <<10>>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_both(<<1,1,1,2,3,4,5,1,1,1>>, <<1>>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_both(<<1,1,1,2,3,4,5,1,1,1>>, 1)),
?_assertEqual(<<1,2,3,4>>, uef_bin:strip_both(<<1,2,3,4,5,5,5>>, <<5>>)),
?_assertEqual(<<1,2,3,4>>, uef_bin:strip_both(<<1,2,3,4,5,5,5>>, 5)),
?_assertEqual(<<1,2,3,4,5>>, uef_bin:strip_both(<<1,2,3,4,5,5,5>>, <<5,5>>)),
?_assertEqual(<<>>, uef_bin:strip_both(<<10, 10, 10, 10>>, 10)),
?_assertEqual(<<>>, uef_bin:strip_both(<<10, 10, 10, 10>>, <<10>>)),
?_assertEqual(<<"ривет"/utf8>>, uef_bin:strip_both(<<"привет"/utf8>>, <<"п"/utf8>>)),
?_assertEqual(<<"ривет"/utf8>>, uef_bin:strip_both(<<"пппривет"/utf8>>, <<"п"/utf8>>)),
?_assertEqual(<<"ивет"/utf8>>, uef_bin:strip_both(<<"привет"/utf8>>, <<"пр"/utf8>>)),
?_assertEqual(<<"приве"/utf8>>, uef_bin:strip_both(<<"привет"/utf8>>, <<"т"/utf8>>)),
?_assertEqual(<<"приве"/utf8>>, uef_bin:strip_both(<<"приветттт"/utf8>>, <<"т"/utf8>>)),
?_assertEqual(<<"привет"/utf8>>, uef_bin:strip_both(<<"приветтттт"/utf8>>, <<"тт"/utf8>>)),
?_assertEqual(<<"привет"/utf8>>, uef_bin:strip_both(<<"абабабприветабабаб"/utf8>>, <<"аб"/utf8>>)),
?_assertEqual(<<"привет"/utf8>>, uef_bin:strip_both(<<"жжжжжприветжжжжж"/utf8>>, <<"ж"/utf8>>)),
?_assertEqual(<<"жприветж"/utf8>>, uef_bin:strip_both(<<"жжжжжприветжжжжж"/utf8>>, <<"жж"/utf8>>))
].
chomp_test_() ->
[
?_assertEqual(<<>>, uef_bin:chomp(<<>>)),
?_assertEqual(<<>>, uef_bin:chomp(<<"\n">>)),
?_assertEqual(<<>>, uef_bin:chomp(<<"\r">>)),
?_assertEqual(<<>>, uef_bin:chomp(<<"\n\n">>)),
?_assertEqual(<<>>, uef_bin:chomp(<<"\r\r">>)),
?_assertEqual(<<>>, uef_bin:chomp(<<"\r\n\r\n">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\n">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\r">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\n\n\n">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\r\r\r">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\r\n\r">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\n\r\n">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\r\n\r\n">>)),
?_assertEqual(<<"\naaa">>, uef_bin:chomp(<<"\naaa\n">>)),
?_assertEqual(<<"\raaa">>, uef_bin:chomp(<<"\raaa\r">>)),
?_assertEqual(<<"\n\n\naaa">>, uef_bin:chomp(<<"\n\n\naaa\n\n\n">>)),
?_assertEqual(<<"\r\r\raaa">>, uef_bin:chomp(<<"\r\r\raaa\r\r\r">>)),
?_assertEqual(<<"\r\n\raaa">>, uef_bin:chomp(<<"\r\n\raaa\r\n\r">>)),
?_assertEqual(<<"\n\r\naaa">>, uef_bin:chomp(<<"\n\r\naaa\n\r\n">>)),
?_assertEqual(<<"\r\n\r\naaa">>, uef_bin:chomp(<<"\r\n\r\naaa\r\n\r\n">>))
].
%%%------------------------------------------------------------------------------
%%% Internal functions
%%%------------------------------------------------------------------------------
validate_random_latin_binary(Bin, CaseFlag) ->
case Bin of
<<>> ->
ok;
<<C, Rest/bits>> ->
IsInRange = case CaseFlag of
lower ->
(C >= $0 andalso C =< $9) orelse (C >= $a andalso C =< $z);
upper ->
(C >= $0 andalso C =< $9) orelse (C >= $A andalso C =< $Z);
any ->
(C >= $0 andalso C =< $9) orelse (C >= $a andalso C =< $z) orelse (C >= $A andalso C =< $Z)
end,
case IsInRange of
true ->
validate_random_latin_binary(Rest, CaseFlag);
false ->
{error, {invalid_char, C}}
end;
_ ->
{error, other}
end.
| null | https://raw.githubusercontent.com/DOBRO/uef-lib/765d28837584bcfced1aae5d5f831972ec0254bb/test/uef_bin_tests.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
------------------------------------------------------------------------------
Test functions
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Internal functions
------------------------------------------------------------------------------ | Copyright ( c ) 2019 - 2022 , < > . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(uef_bin_tests).
-include_lib("eunit/include/eunit.hrl").
numeric_prefix_test_() ->
[
?_assertEqual(<<>>, uef_bin:numeric_prefix(<<"a234234">>)),
?_assertEqual(<<"123">>, uef_bin:numeric_prefix(<<"123a456">>)),
?_assertEqual(<<"123">>, uef_bin:numeric_prefix(<<"123">>)),
?_assertEqual(<<"0">>, uef_bin:numeric_prefix(<<"0test">>)),
?_assertEqual(<<"1">>, uef_bin:numeric_prefix(<<"1test">>)),
?_assertEqual(<<"2">>, uef_bin:numeric_prefix(<<"2test">>)),
?_assertEqual(<<"3">>, uef_bin:numeric_prefix(<<"3test">>)),
?_assertEqual(<<"4">>, uef_bin:numeric_prefix(<<"4test">>)),
?_assertEqual(<<"5">>, uef_bin:numeric_prefix(<<"5test">>)),
?_assertEqual(<<"6">>, uef_bin:numeric_prefix(<<"6test">>)),
?_assertEqual(<<"7">>, uef_bin:numeric_prefix(<<"7test">>)),
?_assertEqual(<<"8">>, uef_bin:numeric_prefix(<<"8test">>)),
?_assertEqual(<<"9">>, uef_bin:numeric_prefix(<<"9test">>))
].
binary_join_test_() ->
[
?_assertEqual(<<>>, uef_bin:binary_join([], <<"any">>)),
?_assertEqual(<<>>, uef_bin:binary_join([], <<>>)),
?_assertEqual(<<"www.example.com">>, uef_bin:binary_join([<<"www">>, <<"example">>, <<"com">>], <<".">>)),
?_assertEqual(<<"www">>, uef_bin:binary_join([<<"www">>], <<".">>))
].
split_test_() ->
[
?_assertEqual([], uef_bin:split(<<>>, <<".">>)),
?_assertEqual([], uef_bin:split(<<>>, <<>>)),
?_assertEqual([<<".www.example.com.">>], uef_bin:split(<<".www.example.com.">>, <<>>, trim_all)),
?_assertEqual([<<>>,<<"www">>,<<"example">>,<<"com">>,<<>>], uef_bin:split(<<".www.example.com.">>, <<".">>)),
?_assertEqual([<<"www">>,<<"example">>,<<"com">>], uef_bin:split(<<"www.example.com">>, <<".">>)),
?_assertEqual([<<"www.example.com">>], uef_bin:split(<<"www.example.com">>, <<"A">>)),
?_assertEqual([<<"www">>,<<"example">>,<<"com">>], uef_bin:split(<<".....www.example.com....">>, <<".">>, trim_all))
].
repeat_test_() ->
[
?_assertEqual(<<"0">>, uef_bin:repeat(<<"0">>, 1)),
?_assertEqual(<<"aaaaa">>, uef_bin:repeat(<<"a">>, 5)),
?_assertEqual(<<0>>, uef_bin:repeat(<<0>>, 1)),
?_assertEqual(<<0,0,0>>, uef_bin:repeat(<<0>>, 3)),
?_assertEqual(<<1,1,1,1>>, uef_bin:repeat(<<1,1>>, 2)),
?_assertEqual(<<1,0,1,0>>, uef_bin:repeat(<<1,0>>, 2)),
?_assertEqual(<<"abcabcabc">>, uef_bin:repeat(<<"abc">>, 3)),
?_assertEqual(<<"ЖЖЖ"/utf8>>, uef_bin:repeat(<<"Ж"/utf8>>, 3))
].
replace_test_() ->
[
?_assertEqual(<<>>, uef_bin:replace(<<>>, <<"aa">>, <<"bb">>)),
?_assertEqual(<<"bbb">>, uef_bin:replace(<<"bbb">>, <<>>, <<"b">>)),
?_assertEqual(<<"aZZdefgZZ">>, uef_bin:replace(<<"abcdefgbc">>, <<"bc">>, <<"ZZ">>)),
?_assertEqual(<<"abcZZefgbc">>, uef_bin:replace(<<"abcdefgbc">>, <<"d">>, <<"ZZ">>))
].
replace_chars_test_() ->
[
?_assertEqual(<<"bbb">>, uef_bin:replace_chars(<<"bbb">>, [], <<>>)),
?_assertEqual(<<"wwwexamplecom">>, uef_bin:replace_chars(<<"..www.example.com.">>, [<<".">>], <<>>)),
?_assertEqual(<<"examplecom">>, uef_bin:replace_chars(<<"..www.example.com.">>, [<<".">>, <<"w">>], <<>>))
].
reverse_test_() ->
[
?_assertEqual(<<5,4,3,2,1>>, uef_bin:reverse(<<1,2,3,4,5>>)),
?_assertEqual(<<"HGFEDCBA">>, uef_bin:reverse(<<"ABCDEFGH">>)),
?_assertEqual(<<>>, uef_bin:reverse(<<>>)),
?_assertEqual(<<0>>, uef_bin:reverse(<<0>>)),
?_assertEqual(<<"0">>, uef_bin:reverse(<<"0">>)),
?_assertEqual(<<1>>, uef_bin:reverse(<<1>>)),
?_assertEqual(<<"1">>, uef_bin:reverse(<<"1">>)),
?_assertEqual(<<0, 0, 0>>, uef_bin:reverse(<<0, 0, 0>>)),
?_assertEqual(<<"ВБА">>, uef_bin:reverse(<<"АБВ">>))
].
reverse_utf8_test_() ->
[
?_assertEqual(<<5,4,3,2,1,0>>, uef_bin:reverse_utf8(<<0,1,2,3,4,5>>)),
?_assertEqual(<<"543210">>, uef_bin:reverse_utf8(<<"012345">>)),
?_assertEqual(<<"HGFEDCBA">>, uef_bin:reverse_utf8(<<"ABCDEFGH">>)),
?_assertEqual(<<>>, uef_bin:reverse_utf8(<<>>)),
?_assertEqual(<<0>>, uef_bin:reverse_utf8(<<0>>)),
?_assertEqual(<<"0">>, uef_bin:reverse_utf8(<<"0">>)),
?_assertEqual(<<1>>, uef_bin:reverse_utf8(<<1>>)),
?_assertEqual(<<"1">>, uef_bin:reverse_utf8(<<"1">>)),
?_assertEqual(<<0, 0, 0>>, uef_bin:reverse_utf8(<<0, 0, 0>>)),
?_assertEqual(<<"ВБА">>, uef_bin:reverse_utf8(<<"АБВ">>)),
?_assertEqual(<<"ЖЁЕДГВБА"/utf8>>, uef_bin:reverse_utf8(<<"АБВГДЕЁЖ"/utf8>>)),
?_assertEqual(<<7, 6, 5, 4, "ЖЁЕДГВБА"/utf8, 3, 2, 1>>, uef_bin:reverse_utf8(<<1, 2, 3, "АБВГДЕЁЖ"/utf8, 4, 5, 6, 7>>)),
?_assertEqual(<<"eßartS eid"/utf8>>, uef_bin:reverse_utf8(<<"die Straße"/utf8>>)),
?_assertEqual(<<"街條這"/utf8>>, uef_bin:reverse_utf8(<<"這條街"/utf8>>)),
?_assertEqual(<<"好你"/utf8>>, uef_bin:reverse_utf8(<<"你好"/utf8>>)),
?_assertEqual(<<"り通"/utf8>>, uef_bin:reverse_utf8(<<"通り"/utf8>>)),
?_assertEqual(<<"はちにんこ"/utf8>>, uef_bin:reverse_utf8(<<"こんにちは"/utf8>>))
].
random_latin_binary_test_() ->
Length = 11,
RandomLower = uef_bin:random_latin_binary(Length, lower),
RandomUpper = uef_bin:random_latin_binary(Length, upper),
RandomAny = uef_bin:random_latin_binary(Length, any),
[
?_assert(erlang:is_integer(Length) andalso Length > 0),
?_assertEqual(Length, erlang:byte_size(RandomLower)),
?_assertEqual(Length, erlang:byte_size(RandomUpper)),
?_assertEqual(Length, erlang:byte_size(RandomAny)),
?_assertEqual(ok, validate_random_latin_binary(RandomLower, lower)),
?_assertEqual(ok, validate_random_latin_binary(RandomUpper, upper)),
?_assertEqual(ok, validate_random_latin_binary(RandomAny, any))
].
strip_left_test_() ->
[
?_assertEqual(<<>>, uef_bin:strip_left(<<>>, <<"any">>)),
?_assertEqual(<<"test">>, uef_bin:strip_left(<<"test">>, <<>>)),
?_assertEqual(<<"est">>, uef_bin:strip_left(<<"ttest">>, <<"t">>)),
?_assertEqual(<<"est">>, uef_bin:strip_left(<<"ttest">>, <<"tt">>)),
?_assertEqual(<<"test">>, uef_bin:strip_left(<<"tttest">>, <<"tt">>)),
?_assertEqual(<<"est">>, uef_bin:strip_left(<<"ttest">>, $t)),
?_assertEqual(<<"est">>, uef_bin:strip_left(<<"tttest">>, $t)),
?_assertEqual(<<"aa">>, uef_bin:strip_left(<<"aa">>, <<"aaa">>)),
?_assertEqual(<<>>, uef_bin:strip_left(<<"aaaaaa">>, $a)),
?_assertEqual(<<>>, uef_bin:strip_left(<<"aaaaaa">>, <<"a">>)),
?_assertEqual(<<"st">>, uef_bin:strip_left(<<"test">>, <<"te">>)),
?_assertEqual(<<"st">>, uef_bin:strip_left(<<"tetest">>, <<"te">>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_left(<<1,1,1,2,3,4,5>>, <<1>>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_left(<<1,1,1,2,3,4,5>>, 1)),
?_assertEqual(<<1,2,3,4,5>>, uef_bin:strip_left(<<1,1,1,2,3,4,5>>, <<1,1>>)),
?_assertEqual(<<>>, uef_bin:strip_left(<<10, 10, 10, 10>>, 10)),
?_assertEqual(<<>>, uef_bin:strip_left(<<10, 10, 10, 10>>, <<10>>)),
?_assertEqual(<<"ривет"/utf8>>, uef_bin:strip_left(<<"привет"/utf8>>, <<"п"/utf8>>)),
?_assertEqual(<<"ривет"/utf8>>, uef_bin:strip_left(<<"пппривет"/utf8>>, <<"п"/utf8>>)),
?_assertEqual(<<"ивет"/utf8>>, uef_bin:strip_left(<<"привет"/utf8>>, <<"пр"/utf8>>))
].
strip_right_test_() ->
[
?_assertEqual(<<>>, uef_bin:strip_right(<<>>, <<"any">>)),
?_assertEqual(<<"test">>, uef_bin:strip_right(<<"test">>, <<>>)),
?_assertEqual(<<"tes">>, uef_bin:strip_right(<<"testtt">>, <<"t">>)),
?_assertEqual(<<"test">>, uef_bin:strip_right(<<"testtt">>, <<"tt">>)),
?_assertEqual(<<"test">>, uef_bin:strip_right(<<"testtttt">>, <<"tt">>)),
?_assertEqual(<<"tes">>, uef_bin:strip_right(<<"testtt">>, $t)),
?_assertEqual(<<"aa">>, uef_bin:strip_right(<<"aa">>, <<"aaa">>)),
?_assertEqual(<<>>, uef_bin:strip_right(<<"aaaaaa">>, $a)),
?_assertEqual(<<>>, uef_bin:strip_right(<<"aaaaaa">>, <<"a">>)),
?_assertEqual(<<"te">>, uef_bin:strip_right(<<"test">>, <<"st">>)),
?_assertEqual(<<"t">>, uef_bin:strip_right(<<"test">>, <<"est">>)),
?_assertEqual(<<>>, uef_bin:strip_right(<<"test">>, <<"test">>)),
?_assertEqual(<<1,2,3,4>>, uef_bin:strip_right(<<1,2,3,4,5,5,5>>, <<5>>)),
?_assertEqual(<<1,2,3,4>>, uef_bin:strip_right(<<1,2,3,4,5,5,5>>, 5)),
?_assertEqual(<<1,2,3,4,5>>, uef_bin:strip_right(<<1,2,3,4,5,5,5>>, <<5,5>>)),
?_assertEqual(<<>>, uef_bin:strip_right(<<10, 10, 10, 10>>, 10)),
?_assertEqual(<<>>, uef_bin:strip_right(<<10, 10, 10, 10>>, <<10>>)),
?_assertEqual(<<"приве"/utf8>>, uef_bin:strip_right(<<"привет"/utf8>>, <<"т"/utf8>>)),
?_assertEqual(<<"приве"/utf8>>, uef_bin:strip_right(<<"приветттт"/utf8>>, <<"т"/utf8>>)),
?_assertEqual(<<"привет"/utf8>>, uef_bin:strip_right(<<"приветтттт"/utf8>>, <<"тт"/utf8>>))
].
strip_both_test_() ->
[
?_assertEqual(<<>>, uef_bin:strip_both(<<>>, <<"any">>)),
?_assertEqual(<<"test">>, uef_bin:strip_both(<<"test">>, <<>>)),
?_assertEqual(<<"es">>, uef_bin:strip_both(<<"tttest">>, <<"t">>)),
?_assertEqual(<<"est">>, uef_bin:strip_both(<<"ttest">>, <<"tt">>)),
?_assertEqual(<<"test">>, uef_bin:strip_both(<<"tttest">>, <<"tt">>)),
?_assertEqual(<<"test">>, uef_bin:strip_both(<<"tttesttt">>, <<"tt">>)),
?_assertEqual(<<"es">>, uef_bin:strip_both(<<"ttest">>, $t)),
?_assertEqual(<<"es">>, uef_bin:strip_both(<<"tttesttt">>, $t)),
?_assertEqual(<<"aa">>, uef_bin:strip_both(<<"aa">>, <<"aaa">>)),
?_assertEqual(<<>>, uef_bin:strip_both(<<"aaaaaa">>, $a)),
?_assertEqual(<<>>, uef_bin:strip_both(<<"aaaaaa">>, <<"a">>)),
?_assertEqual(<<"st">>, uef_bin:strip_both(<<"test">>, <<"te">>)),
?_assertEqual(<<"st">>, uef_bin:strip_both(<<"tetest">>, <<"te">>)),
?_assertEqual(<<"te">>, uef_bin:strip_both(<<"test">>, <<"st">>)),
?_assertEqual(<<"te">>, uef_bin:strip_both(<<"testst">>, <<"st">>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_both(<<1,1,1,2,3,4,5>>, <<1>>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_both(<<1,1,1,2,3,4,5>>, 1)),
?_assertEqual(<<1,2,3,4,5>>, uef_bin:strip_both(<<1,1,1,2,3,4,5>>, <<1,1>>)),
?_assertEqual(<<>>, uef_bin:strip_both(<<10, 10, 10, 10>>, 10)),
?_assertEqual(<<>>, uef_bin:strip_both(<<10, 10, 10, 10>>, <<10>>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_both(<<1,1,1,2,3,4,5,1,1,1>>, <<1>>)),
?_assertEqual(<<2,3,4,5>>, uef_bin:strip_both(<<1,1,1,2,3,4,5,1,1,1>>, 1)),
?_assertEqual(<<1,2,3,4>>, uef_bin:strip_both(<<1,2,3,4,5,5,5>>, <<5>>)),
?_assertEqual(<<1,2,3,4>>, uef_bin:strip_both(<<1,2,3,4,5,5,5>>, 5)),
?_assertEqual(<<1,2,3,4,5>>, uef_bin:strip_both(<<1,2,3,4,5,5,5>>, <<5,5>>)),
?_assertEqual(<<>>, uef_bin:strip_both(<<10, 10, 10, 10>>, 10)),
?_assertEqual(<<>>, uef_bin:strip_both(<<10, 10, 10, 10>>, <<10>>)),
?_assertEqual(<<"ривет"/utf8>>, uef_bin:strip_both(<<"привет"/utf8>>, <<"п"/utf8>>)),
?_assertEqual(<<"ривет"/utf8>>, uef_bin:strip_both(<<"пппривет"/utf8>>, <<"п"/utf8>>)),
?_assertEqual(<<"ивет"/utf8>>, uef_bin:strip_both(<<"привет"/utf8>>, <<"пр"/utf8>>)),
?_assertEqual(<<"приве"/utf8>>, uef_bin:strip_both(<<"привет"/utf8>>, <<"т"/utf8>>)),
?_assertEqual(<<"приве"/utf8>>, uef_bin:strip_both(<<"приветттт"/utf8>>, <<"т"/utf8>>)),
?_assertEqual(<<"привет"/utf8>>, uef_bin:strip_both(<<"приветтттт"/utf8>>, <<"тт"/utf8>>)),
?_assertEqual(<<"привет"/utf8>>, uef_bin:strip_both(<<"абабабприветабабаб"/utf8>>, <<"аб"/utf8>>)),
?_assertEqual(<<"привет"/utf8>>, uef_bin:strip_both(<<"жжжжжприветжжжжж"/utf8>>, <<"ж"/utf8>>)),
?_assertEqual(<<"жприветж"/utf8>>, uef_bin:strip_both(<<"жжжжжприветжжжжж"/utf8>>, <<"жж"/utf8>>))
].
chomp_test_() ->
[
?_assertEqual(<<>>, uef_bin:chomp(<<>>)),
?_assertEqual(<<>>, uef_bin:chomp(<<"\n">>)),
?_assertEqual(<<>>, uef_bin:chomp(<<"\r">>)),
?_assertEqual(<<>>, uef_bin:chomp(<<"\n\n">>)),
?_assertEqual(<<>>, uef_bin:chomp(<<"\r\r">>)),
?_assertEqual(<<>>, uef_bin:chomp(<<"\r\n\r\n">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\n">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\r">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\n\n\n">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\r\r\r">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\r\n\r">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\n\r\n">>)),
?_assertEqual(<<"aaa">>, uef_bin:chomp(<<"aaa\r\n\r\n">>)),
?_assertEqual(<<"\naaa">>, uef_bin:chomp(<<"\naaa\n">>)),
?_assertEqual(<<"\raaa">>, uef_bin:chomp(<<"\raaa\r">>)),
?_assertEqual(<<"\n\n\naaa">>, uef_bin:chomp(<<"\n\n\naaa\n\n\n">>)),
?_assertEqual(<<"\r\r\raaa">>, uef_bin:chomp(<<"\r\r\raaa\r\r\r">>)),
?_assertEqual(<<"\r\n\raaa">>, uef_bin:chomp(<<"\r\n\raaa\r\n\r">>)),
?_assertEqual(<<"\n\r\naaa">>, uef_bin:chomp(<<"\n\r\naaa\n\r\n">>)),
?_assertEqual(<<"\r\n\r\naaa">>, uef_bin:chomp(<<"\r\n\r\naaa\r\n\r\n">>))
].
validate_random_latin_binary(Bin, CaseFlag) ->
case Bin of
<<>> ->
ok;
<<C, Rest/bits>> ->
IsInRange = case CaseFlag of
lower ->
(C >= $0 andalso C =< $9) orelse (C >= $a andalso C =< $z);
upper ->
(C >= $0 andalso C =< $9) orelse (C >= $A andalso C =< $Z);
any ->
(C >= $0 andalso C =< $9) orelse (C >= $a andalso C =< $z) orelse (C >= $A andalso C =< $Z)
end,
case IsInRange of
true ->
validate_random_latin_binary(Rest, CaseFlag);
false ->
{error, {invalid_char, C}}
end;
_ ->
{error, other}
end.
|
7187f8f0c3098122d2eedc492c9f784d935f42de8adad63008e32e75a42994b0 | cornell-netlab/yates | LP_Lang.ml | open Core
open Yates_types.Types
(* (s,t,r) = node s wants to send to node t at rate r *)
type demand_pair = Topology.vertex * Topology.vertex * float
type arith_exp =
| Var of string
| Num of float
| Times of float * arith_exp
| Sum of arith_exp list
type constrain =
| Eq of string * arith_exp * float
| Leq of string * arith_exp * float
| Geq of string * arith_exp * float
type lp = arith_exp * (constrain list)
let minus ex1 ex2 =
let list1 = match ex1 with
| Var _ | Num _ | Times _ -> [ex1]
| Sum lst -> lst in
let rec negate ex = match ex with
| Var var -> [Times (-1., Var var)]
| Num f -> [Num (-.f)]
| Times (f, x) -> [Times (-.f, x)]
| Sum lst -> List.concat (List.map lst ~f:(fun x -> negate x)) in
let all_terms = list1 @ (negate ex2) in
Sum all_terms
let rec string_of_aexp ae =
match ae with
| Var v -> v
| Num f -> Float.to_string f
| Times (coeff, a2) ->
Printf.sprintf "%f %s" (coeff) (string_of_aexp a2)
| Sum (aexs) ->
List.fold_left aexs ~init:"" ~f:(fun acc ae ->
if String.equal acc "" then string_of_aexp ae else match ae with
| Times (coeff, a2) ->
if Float.(=) coeff (-1.) then acc ^ " - " ^ (string_of_aexp a2)
else if Float.(<) coeff 0. then acc ^ " - " ^
(string_of_aexp (Times (-.coeff, a2)))
else acc ^ " + " ^ (string_of_aexp ae)
| _ -> acc ^ " + " ^ (string_of_aexp ae))
let string_of_constraint c =
match c with
| Eq (name, ae, f) ->
Printf.sprintf "%s: %s = %s" name (string_of_aexp ae) (Float.to_string f)
| Leq (name, ae, f) ->
Printf.sprintf "%s: %s <= %s" name (string_of_aexp ae) (Float.to_string f)
| Geq (name, ae, f) ->
Printf.sprintf "%s: %s >= %s" name (string_of_aexp ae) (Float.to_string f)
let name_of_vertex topo v =
let label = Topology.vertex_to_label topo v in
Node.name label
let string_of_edge topo e =
let (v1,_) = Topology.edge_src e in
let (v2,_) = Topology.edge_dst e in
Printf.sprintf "%s--%s"
(name_of_vertex topo v1)
(name_of_vertex topo v2)
let string_of_pair topo (s,t) =
Printf.sprintf "%s--%s"
(name_of_vertex topo s)
(name_of_vertex topo t)
(* Given an edge (i,j) and a source-sink pair (s,t),
* returns the name of the variable representing the
* flow on (i,j) originating from s and going to t. *)
let var_name topo edge d_pair =
let src,_ = Topology.edge_src edge in
let dst,_ = Topology.edge_dst edge in
Printf.sprintf "f_%s_%s--%s"
(string_of_pair topo d_pair)
(name_of_vertex topo src)
(name_of_vertex topo dst)
(* Same as above, but for the flow in the reverse direction (j,i). *)
let var_name_rev topo edge d_pair =
let src,_ = Topology.edge_src edge in
let dst,_ = Topology.edge_dst edge in
Printf.sprintf "f_%s_%s--%s"
(string_of_pair topo d_pair)
(name_of_vertex topo dst)
(name_of_vertex topo src)
FFC : Create a LP variable for src->dst granted badnwidth
let granted_bw_var_name topo (src,dst) =
Printf.sprintf "gbf_%s--%s"
(name_of_vertex topo src)
(name_of_vertex topo dst)
let string_of_lp ((objective, constrs) : lp) : string =
let cs =
List.fold_left
constrs
~init:""
~f: (fun acc c -> acc ^ (Printf.sprintf " %s\n" (string_of_constraint c))) in
"Minimize\n" ^ (Printf.sprintf " %s\n" (string_of_aexp objective))
^ "Subject To\n" ^ cs
let serialize_lp ((objective, constrs) : lp) (filename : string) =
let open Out_channel in
let lp_file = create filename in
output_string lp_file "Minimize\n";
output_string lp_file (Printf.sprintf " %s\n" (string_of_aexp objective));
output_string lp_file "Subject To\n";
List.iter constrs ~f: (fun c -> output_string lp_file
(Printf.sprintf " %s\n" (string_of_constraint c)));
close lp_file
let serialize_max_lp ((objective, constrs) : lp) (filename : string) =
let open Out_channel in
let lp_file = create filename in
output_string lp_file "Maximize\n";
output_string lp_file (Printf.sprintf " %s\n" (string_of_aexp objective));
output_string lp_file "Subject To\n";
List.iter constrs ~f: (fun c -> output_string lp_file
(Printf.sprintf " %s\n" (string_of_constraint c)));
close lp_file
| null | https://raw.githubusercontent.com/cornell-netlab/yates/fc30922933fae3184923f7b138d24454a9537536/lib/routing/LP_Lang.ml | ocaml | (s,t,r) = node s wants to send to node t at rate r
Given an edge (i,j) and a source-sink pair (s,t),
* returns the name of the variable representing the
* flow on (i,j) originating from s and going to t.
Same as above, but for the flow in the reverse direction (j,i). | open Core
open Yates_types.Types
type demand_pair = Topology.vertex * Topology.vertex * float
type arith_exp =
| Var of string
| Num of float
| Times of float * arith_exp
| Sum of arith_exp list
type constrain =
| Eq of string * arith_exp * float
| Leq of string * arith_exp * float
| Geq of string * arith_exp * float
type lp = arith_exp * (constrain list)
let minus ex1 ex2 =
let list1 = match ex1 with
| Var _ | Num _ | Times _ -> [ex1]
| Sum lst -> lst in
let rec negate ex = match ex with
| Var var -> [Times (-1., Var var)]
| Num f -> [Num (-.f)]
| Times (f, x) -> [Times (-.f, x)]
| Sum lst -> List.concat (List.map lst ~f:(fun x -> negate x)) in
let all_terms = list1 @ (negate ex2) in
Sum all_terms
let rec string_of_aexp ae =
match ae with
| Var v -> v
| Num f -> Float.to_string f
| Times (coeff, a2) ->
Printf.sprintf "%f %s" (coeff) (string_of_aexp a2)
| Sum (aexs) ->
List.fold_left aexs ~init:"" ~f:(fun acc ae ->
if String.equal acc "" then string_of_aexp ae else match ae with
| Times (coeff, a2) ->
if Float.(=) coeff (-1.) then acc ^ " - " ^ (string_of_aexp a2)
else if Float.(<) coeff 0. then acc ^ " - " ^
(string_of_aexp (Times (-.coeff, a2)))
else acc ^ " + " ^ (string_of_aexp ae)
| _ -> acc ^ " + " ^ (string_of_aexp ae))
let string_of_constraint c =
match c with
| Eq (name, ae, f) ->
Printf.sprintf "%s: %s = %s" name (string_of_aexp ae) (Float.to_string f)
| Leq (name, ae, f) ->
Printf.sprintf "%s: %s <= %s" name (string_of_aexp ae) (Float.to_string f)
| Geq (name, ae, f) ->
Printf.sprintf "%s: %s >= %s" name (string_of_aexp ae) (Float.to_string f)
let name_of_vertex topo v =
let label = Topology.vertex_to_label topo v in
Node.name label
let string_of_edge topo e =
let (v1,_) = Topology.edge_src e in
let (v2,_) = Topology.edge_dst e in
Printf.sprintf "%s--%s"
(name_of_vertex topo v1)
(name_of_vertex topo v2)
let string_of_pair topo (s,t) =
Printf.sprintf "%s--%s"
(name_of_vertex topo s)
(name_of_vertex topo t)
let var_name topo edge d_pair =
let src,_ = Topology.edge_src edge in
let dst,_ = Topology.edge_dst edge in
Printf.sprintf "f_%s_%s--%s"
(string_of_pair topo d_pair)
(name_of_vertex topo src)
(name_of_vertex topo dst)
let var_name_rev topo edge d_pair =
let src,_ = Topology.edge_src edge in
let dst,_ = Topology.edge_dst edge in
Printf.sprintf "f_%s_%s--%s"
(string_of_pair topo d_pair)
(name_of_vertex topo dst)
(name_of_vertex topo src)
FFC : Create a LP variable for src->dst granted badnwidth
let granted_bw_var_name topo (src,dst) =
Printf.sprintf "gbf_%s--%s"
(name_of_vertex topo src)
(name_of_vertex topo dst)
let string_of_lp ((objective, constrs) : lp) : string =
let cs =
List.fold_left
constrs
~init:""
~f: (fun acc c -> acc ^ (Printf.sprintf " %s\n" (string_of_constraint c))) in
"Minimize\n" ^ (Printf.sprintf " %s\n" (string_of_aexp objective))
^ "Subject To\n" ^ cs
let serialize_lp ((objective, constrs) : lp) (filename : string) =
let open Out_channel in
let lp_file = create filename in
output_string lp_file "Minimize\n";
output_string lp_file (Printf.sprintf " %s\n" (string_of_aexp objective));
output_string lp_file "Subject To\n";
List.iter constrs ~f: (fun c -> output_string lp_file
(Printf.sprintf " %s\n" (string_of_constraint c)));
close lp_file
let serialize_max_lp ((objective, constrs) : lp) (filename : string) =
let open Out_channel in
let lp_file = create filename in
output_string lp_file "Maximize\n";
output_string lp_file (Printf.sprintf " %s\n" (string_of_aexp objective));
output_string lp_file "Subject To\n";
List.iter constrs ~f: (fun c -> output_string lp_file
(Printf.sprintf " %s\n" (string_of_constraint c)));
close lp_file
|
475463fdd07ea000493364a8f59f13c70a4fde0fc50bfd018081c01c2a26acb8 | erlang-ls/erlang_ls | els_dap_test_utils.erl | -module(els_dap_test_utils).
-export([
all/1,
all/2,
end_per_suite/1,
end_per_testcase/2,
init_per_suite/1,
init_per_testcase/2,
wait_for/2,
wait_for_fun/3
]).
-include_lib("common_test/include/ct.hrl").
%%==============================================================================
%% Defines
%%==============================================================================
-define(TEST_APP, <<"code_navigation">>).
%%==============================================================================
%% Types
%%==============================================================================
-type config() :: [{atom(), any()}].
%%==============================================================================
%% API
%%==============================================================================
-spec all(module()) -> [atom()].
all(Module) -> all(Module, []).
-spec all(module(), [atom()]) -> [atom()].
all(Module, Functions) ->
ExcludedFuns = [init_per_suite, end_per_suite, all, module_info | Functions],
Exports = Module:module_info(exports),
[F || {F, 1} <- Exports, not lists:member(F, ExcludedFuns)].
-spec init_per_suite(config()) -> config().
init_per_suite(Config) ->
PrivDir = code:priv_dir(els_dap),
RootPath = filename:join([
els_utils:to_binary(PrivDir),
?TEST_APP
]),
RootUri = els_uri:uri(RootPath),
application:load(els_core),
[
{root_uri, RootUri},
{root_path, RootPath}
| Config
].
-spec end_per_suite(config()) -> ok.
end_per_suite(_Config) ->
ok.
-spec init_per_testcase(atom(), config()) -> config().
init_per_testcase(_TestCase, Config) ->
meck:new(els_distribution_server, [no_link, passthrough]),
meck:expect(els_distribution_server, connect, 0, ok),
Started = els_test_utils:start(),
RootUri = ?config(root_uri, Config),
els_client:initialize(RootUri, #{indexingEnabled => false}),
els_client:initialized(),
[
{started, Started}
| Config
].
-spec end_per_testcase(atom(), config()) -> ok.
end_per_testcase(_TestCase, Config) ->
meck:unload(els_distribution_server),
[application:stop(App) || App <- ?config(started, Config)],
ok.
-spec wait_for(any(), non_neg_integer()) -> ok.
wait_for(_Message, Timeout) when Timeout =< 0 ->
timeout;
wait_for(Message, Timeout) ->
receive
Message -> ok
after 10 -> wait_for(Message, Timeout - 10)
end.
-spec wait_for_fun(term(), non_neg_integer(), non_neg_integer()) ->
{ok, any()} | ok | timeout.
wait_for_fun(_CheckFun, _WaitTime, 0) ->
timeout;
wait_for_fun(CheckFun, WaitTime, Retries) ->
case CheckFun() of
true ->
ok;
{true, Value} ->
{ok, Value};
false ->
timer:sleep(WaitTime),
wait_for_fun(CheckFun, WaitTime, Retries - 1)
end.
| null | https://raw.githubusercontent.com/erlang-ls/erlang_ls/2dfb48aca3879e5b44f6fd676f8349525262779f/apps/els_dap/test/els_dap_test_utils.erl | erlang | ==============================================================================
Defines
==============================================================================
==============================================================================
Types
==============================================================================
==============================================================================
API
============================================================================== | -module(els_dap_test_utils).
-export([
all/1,
all/2,
end_per_suite/1,
end_per_testcase/2,
init_per_suite/1,
init_per_testcase/2,
wait_for/2,
wait_for_fun/3
]).
-include_lib("common_test/include/ct.hrl").
-define(TEST_APP, <<"code_navigation">>).
-type config() :: [{atom(), any()}].
-spec all(module()) -> [atom()].
all(Module) -> all(Module, []).
-spec all(module(), [atom()]) -> [atom()].
all(Module, Functions) ->
ExcludedFuns = [init_per_suite, end_per_suite, all, module_info | Functions],
Exports = Module:module_info(exports),
[F || {F, 1} <- Exports, not lists:member(F, ExcludedFuns)].
-spec init_per_suite(config()) -> config().
init_per_suite(Config) ->
PrivDir = code:priv_dir(els_dap),
RootPath = filename:join([
els_utils:to_binary(PrivDir),
?TEST_APP
]),
RootUri = els_uri:uri(RootPath),
application:load(els_core),
[
{root_uri, RootUri},
{root_path, RootPath}
| Config
].
-spec end_per_suite(config()) -> ok.
end_per_suite(_Config) ->
ok.
-spec init_per_testcase(atom(), config()) -> config().
init_per_testcase(_TestCase, Config) ->
meck:new(els_distribution_server, [no_link, passthrough]),
meck:expect(els_distribution_server, connect, 0, ok),
Started = els_test_utils:start(),
RootUri = ?config(root_uri, Config),
els_client:initialize(RootUri, #{indexingEnabled => false}),
els_client:initialized(),
[
{started, Started}
| Config
].
-spec end_per_testcase(atom(), config()) -> ok.
end_per_testcase(_TestCase, Config) ->
meck:unload(els_distribution_server),
[application:stop(App) || App <- ?config(started, Config)],
ok.
-spec wait_for(any(), non_neg_integer()) -> ok.
wait_for(_Message, Timeout) when Timeout =< 0 ->
timeout;
wait_for(Message, Timeout) ->
receive
Message -> ok
after 10 -> wait_for(Message, Timeout - 10)
end.
-spec wait_for_fun(term(), non_neg_integer(), non_neg_integer()) ->
{ok, any()} | ok | timeout.
wait_for_fun(_CheckFun, _WaitTime, 0) ->
timeout;
wait_for_fun(CheckFun, WaitTime, Retries) ->
case CheckFun() of
true ->
ok;
{true, Value} ->
{ok, Value};
false ->
timer:sleep(WaitTime),
wait_for_fun(CheckFun, WaitTime, Retries - 1)
end.
|
da96b2e81187ebe8e55e2aabe9f3c45d31d3112bb7669f44c72c85177a9ea961 | binaryage/chromex | playground.cljs | (ns chromex.test.playground
(:require-macros [cljs.core.async.macros :refer [go go-loop]])
(:require [chromex.chrome-event-channel :refer [make-chrome-event-channel]]
[chromex.config :refer-macros [with-custom-config with-custom-event-listener-factory with-muted-error-reporting]]
[chromex.error :refer [get-last-error set-last-error!]]
[chromex.playground :refer-macros [call-future-api call-master-api do-something do-something-missing
do-something-optional-args get-some-missing-prop get-some-prop
get-something get-something-causing-error tap-all-events
tap-on-something-else-events tap-on-something-events tap-on-something-missing-events]]
[chromex.playground-mocks :refer [last-event-result]]
[chromex.test-utils :refer [advanced-mode?] :refer-macros [valid-api-version?]]
[cljs.core.async :refer [<! >! chan close! timeout]]
[cljs.test :refer-macros [async deftest is testing]]
[clojure.string :as string]
[chromex.console :refer [with-captured-console get-captured-console-content]]
[oops.core :refer [oapply ocall oget oset!]]))
; -- test against mocks -----------------------------------------------------------------------------------------------------
(deftest test-plain-api-call
(testing "do something"
(is (= (do-something "param") "from-native[got to-native[param]]"))))
(deftest test-api-call-with-callback
(testing "get something"
(async done
(go
(let [[result] (<! (get-something "param"))]
(is (= result "from-native[answer is to-native[param]]"))
(done))))))
(deftest test-api-call-causing-error
(testing "get something causing error"
(async done
(go
(with-muted-error-reporting
(is (= (get-last-error) nil))
(let [result (<! (get-something-causing-error "param"))]
(is (= result nil) "result channel should close when errored")
(let [last-error (get-last-error)]
(is (= (oget last-error "message") "get-something caused an error"))
(is (= (oget last-error "code") 666))
(set-last-error! nil))
(done)))))))
(deftest test-reset-last-error
(testing "non-error call should reset last error"
(async done
(go
(with-muted-error-reporting
(is (= (get-last-error) nil))
(let [result (<! (get-something-causing-error "param"))]
(is (= result nil) "result channel should close when errored")
(is (some? (get-last-error)))
(<! (get-something "param"))
(is (= (get-last-error) nil)) ; last error got resetted to nil
(done)))))))
(deftest test--custom-error-reporter
(testing "exercise custom error reporter"
(async done
(go
(let [expected-report (str "[{:id :chromex.playground/get-something-causing-error, "
":name \"getSomethingCausingError\", "
":callback? true, "
":params [{:name \"param1\", :type \"some-type\"} "
"{:name \"callback\", :type :callback, :callback {:params []}}], "
":function? true} "
"#js {:message \"get-something caused an error\", :code 666}]")
reported (volatile! [])
reporter (fn [descriptor error]
(vswap! reported conj (pr-str [descriptor error])))]
(with-custom-config #(assoc % :callback-error-reporter reporter)
(is (= (get-last-error) nil))
(<! (get-something-causing-error "param"))
(is (= (string/join @reported) expected-report))
(set-last-error! nil)
(done)))))))
(deftest test-optional-args
(testing "do something with optional args"
(is (= (do-something-optional-args 1 2 3) "got [1 \"to-native[2]\" 3]"))
(is (= (do-something-optional-args 1 2) "got [1 \"to-native[2]\"]"))
(is (= (do-something-optional-args 1) "got [1]"))
(is (= (do-something-optional-args) "got []"))
(is (= (do-something-optional-args 1 :omit 3) "got [1 3]"))
(is (= (do-something-optional-args :omit 2 :omit) "got [\"to-native[2]\"]"))
(is (= (do-something-optional-args :omit :omit 3) "got [3]"))
(is (= (do-something-optional-args :omit :omit :omit) "got []")))
(if-not advanced-mode?
(testing "try to omit non-optional arg"
(is (thrown-with-msg? js/Error #"cannot be omitted" (do-something :omit))))))
(deftest test-property-access
(testing "read prop"
(let [result (get-some-prop)]
(is (= result "from-native[prop1val]")))))
(deftest test-events
(testing "tap on-something events"
(async done
(let [chan (make-chrome-event-channel (chan))]
(tap-on-something-events chan)
(go
(dotimes [n 3]
(let [[event [item]] (<! chan)]
(is (= event :chromex.playground/on-something))
(is (= item (str "from-native[something fired! #" n "]")))))
(close! chan)
(<! (timeout 30))
(done))))))
(deftest test-passing-extra-args-to-events
(testing "tap event with extra args"
(async done
(let [chan (make-chrome-event-channel (chan))]
(tap-on-something-events chan 1 2 3)
(go
(dotimes [n 3]
(let [[event [item]] (<! chan)]
(is (= event :chromex.playground/on-something))
(is (= item (str "from-native[something fired! #" n " extra args:(1 2 3)]")))))
(close! chan)
(<! (timeout 100))
(done))))))
(deftest test-tapping-all-events
(testing "tap all events"
(async done
(let [chan (make-chrome-event-channel (chan))]
(tap-all-events chan)
(go
(dotimes [_ 3]
(let [[event _] (<! chan)]
(is (not (= event :chromex.playground/on-something-deprecated))))) ; we should be receiving only non-deprecated events
(close! chan)
(<! (timeout 30))
(done))))))
(deftest test-sync-events
(testing "tap on-something events with-custom-event-listener-factory"
(async done
(let [chan (make-chrome-event-channel (chan))
storage (atom [])]
(with-custom-event-listener-factory (fn []
(fn [& args]
(swap! storage conj (str "sync:" args))
"return val"))
(tap-on-something-events chan))
(go
give event source some time to fire at least one event
(is (= (first @storage) "sync:(\"from-native[something fired! #0]\")"))
(is (= @last-event-result "return val"))
(close! chan)
(done))))))
(deftest test-using-missing-apis
(when-not advanced-mode?
(testing "try access missing property"
(with-captured-console
(is (= nil (get-some-missing-prop))))
(let [console-content (get-captured-console-content)]
(is (= (count console-content) 1))
(is (= (first (first console-content)) :log))))
(testing "try call missing function"
(with-captured-console
(do-something-missing))
(let [console-content (get-captured-console-content)]
(is (= (count console-content) 1))
(is (= (first (first console-content)) :error))
(is (some? (re-find #"library tried to access a missing Chrome API object" (second (first console-content)))))))
(testing "try tap missing event"
(with-captured-console
(let [chan (make-chrome-event-channel (chan))]
(tap-on-something-missing-events chan)))
(let [console-content (get-captured-console-content)]
(is (= (count console-content) 1))
(is (= (first (first console-content)) :error))
(is (some? (re-find #"library tried to access a missing Chrome API object" (second (first console-content)))))))))
(deftest test-api-version-checking
(testing "valid-api-version?"
(is (= (valid-api-version? "latest" "master" "master") true))
(is (= (valid-api-version? "latest" "master" nil) true))
(is (= (valid-api-version? "latest" "100" "200") false))
(is (= (valid-api-version? "latest" "50" nil) true))
(is (= (valid-api-version? "latest" nil nil) true))
(is (= (valid-api-version? "latest" nil "10") false))
(is (= (valid-api-version? "master" "master" "master") true))
(is (= (valid-api-version? "master" "master" nil) true))
(is (= (valid-api-version? "master" "100" "200") false))
(is (= (valid-api-version? "master" "50" nil) true))
(is (= (valid-api-version? "master" nil nil) true))
(is (= (valid-api-version? "master" nil "10") false))
(is (= (valid-api-version? "50" nil nil) true))
(is (= (valid-api-version? "50" "50" nil) true))
(is (= (valid-api-version? "50" "51" nil) false))
(is (= (valid-api-version? "50" nil "49") false))
(is (= (valid-api-version? "50" nil "50") true))
(is (= (valid-api-version? "50" "50" "50") true))
(is (= (valid-api-version? "50" "49" "50") true)))
(testing "call future api"
(is (= (call-future-api) nil)))
(testing "call master api"
(is (= (call-master-api) nil))))
| null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/test/src/chromex/test/playground.cljs | clojure | -- test against mocks -----------------------------------------------------------------------------------------------------
last error got resetted to nil
we should be receiving only non-deprecated events | (ns chromex.test.playground
(:require-macros [cljs.core.async.macros :refer [go go-loop]])
(:require [chromex.chrome-event-channel :refer [make-chrome-event-channel]]
[chromex.config :refer-macros [with-custom-config with-custom-event-listener-factory with-muted-error-reporting]]
[chromex.error :refer [get-last-error set-last-error!]]
[chromex.playground :refer-macros [call-future-api call-master-api do-something do-something-missing
do-something-optional-args get-some-missing-prop get-some-prop
get-something get-something-causing-error tap-all-events
tap-on-something-else-events tap-on-something-events tap-on-something-missing-events]]
[chromex.playground-mocks :refer [last-event-result]]
[chromex.test-utils :refer [advanced-mode?] :refer-macros [valid-api-version?]]
[cljs.core.async :refer [<! >! chan close! timeout]]
[cljs.test :refer-macros [async deftest is testing]]
[clojure.string :as string]
[chromex.console :refer [with-captured-console get-captured-console-content]]
[oops.core :refer [oapply ocall oget oset!]]))
(deftest test-plain-api-call
(testing "do something"
(is (= (do-something "param") "from-native[got to-native[param]]"))))
(deftest test-api-call-with-callback
(testing "get something"
(async done
(go
(let [[result] (<! (get-something "param"))]
(is (= result "from-native[answer is to-native[param]]"))
(done))))))
(deftest test-api-call-causing-error
(testing "get something causing error"
(async done
(go
(with-muted-error-reporting
(is (= (get-last-error) nil))
(let [result (<! (get-something-causing-error "param"))]
(is (= result nil) "result channel should close when errored")
(let [last-error (get-last-error)]
(is (= (oget last-error "message") "get-something caused an error"))
(is (= (oget last-error "code") 666))
(set-last-error! nil))
(done)))))))
(deftest test-reset-last-error
(testing "non-error call should reset last error"
(async done
(go
(with-muted-error-reporting
(is (= (get-last-error) nil))
(let [result (<! (get-something-causing-error "param"))]
(is (= result nil) "result channel should close when errored")
(is (some? (get-last-error)))
(<! (get-something "param"))
(done)))))))
(deftest test--custom-error-reporter
(testing "exercise custom error reporter"
(async done
(go
(let [expected-report (str "[{:id :chromex.playground/get-something-causing-error, "
":name \"getSomethingCausingError\", "
":callback? true, "
":params [{:name \"param1\", :type \"some-type\"} "
"{:name \"callback\", :type :callback, :callback {:params []}}], "
":function? true} "
"#js {:message \"get-something caused an error\", :code 666}]")
reported (volatile! [])
reporter (fn [descriptor error]
(vswap! reported conj (pr-str [descriptor error])))]
(with-custom-config #(assoc % :callback-error-reporter reporter)
(is (= (get-last-error) nil))
(<! (get-something-causing-error "param"))
(is (= (string/join @reported) expected-report))
(set-last-error! nil)
(done)))))))
(deftest test-optional-args
(testing "do something with optional args"
(is (= (do-something-optional-args 1 2 3) "got [1 \"to-native[2]\" 3]"))
(is (= (do-something-optional-args 1 2) "got [1 \"to-native[2]\"]"))
(is (= (do-something-optional-args 1) "got [1]"))
(is (= (do-something-optional-args) "got []"))
(is (= (do-something-optional-args 1 :omit 3) "got [1 3]"))
(is (= (do-something-optional-args :omit 2 :omit) "got [\"to-native[2]\"]"))
(is (= (do-something-optional-args :omit :omit 3) "got [3]"))
(is (= (do-something-optional-args :omit :omit :omit) "got []")))
(if-not advanced-mode?
(testing "try to omit non-optional arg"
(is (thrown-with-msg? js/Error #"cannot be omitted" (do-something :omit))))))
(deftest test-property-access
(testing "read prop"
(let [result (get-some-prop)]
(is (= result "from-native[prop1val]")))))
(deftest test-events
(testing "tap on-something events"
(async done
(let [chan (make-chrome-event-channel (chan))]
(tap-on-something-events chan)
(go
(dotimes [n 3]
(let [[event [item]] (<! chan)]
(is (= event :chromex.playground/on-something))
(is (= item (str "from-native[something fired! #" n "]")))))
(close! chan)
(<! (timeout 30))
(done))))))
(deftest test-passing-extra-args-to-events
(testing "tap event with extra args"
(async done
(let [chan (make-chrome-event-channel (chan))]
(tap-on-something-events chan 1 2 3)
(go
(dotimes [n 3]
(let [[event [item]] (<! chan)]
(is (= event :chromex.playground/on-something))
(is (= item (str "from-native[something fired! #" n " extra args:(1 2 3)]")))))
(close! chan)
(<! (timeout 100))
(done))))))
(deftest test-tapping-all-events
(testing "tap all events"
(async done
(let [chan (make-chrome-event-channel (chan))]
(tap-all-events chan)
(go
(dotimes [_ 3]
(let [[event _] (<! chan)]
(close! chan)
(<! (timeout 30))
(done))))))
(deftest test-sync-events
(testing "tap on-something events with-custom-event-listener-factory"
(async done
(let [chan (make-chrome-event-channel (chan))
storage (atom [])]
(with-custom-event-listener-factory (fn []
(fn [& args]
(swap! storage conj (str "sync:" args))
"return val"))
(tap-on-something-events chan))
(go
give event source some time to fire at least one event
(is (= (first @storage) "sync:(\"from-native[something fired! #0]\")"))
(is (= @last-event-result "return val"))
(close! chan)
(done))))))
(deftest test-using-missing-apis
(when-not advanced-mode?
(testing "try access missing property"
(with-captured-console
(is (= nil (get-some-missing-prop))))
(let [console-content (get-captured-console-content)]
(is (= (count console-content) 1))
(is (= (first (first console-content)) :log))))
(testing "try call missing function"
(with-captured-console
(do-something-missing))
(let [console-content (get-captured-console-content)]
(is (= (count console-content) 1))
(is (= (first (first console-content)) :error))
(is (some? (re-find #"library tried to access a missing Chrome API object" (second (first console-content)))))))
(testing "try tap missing event"
(with-captured-console
(let [chan (make-chrome-event-channel (chan))]
(tap-on-something-missing-events chan)))
(let [console-content (get-captured-console-content)]
(is (= (count console-content) 1))
(is (= (first (first console-content)) :error))
(is (some? (re-find #"library tried to access a missing Chrome API object" (second (first console-content)))))))))
(deftest test-api-version-checking
(testing "valid-api-version?"
(is (= (valid-api-version? "latest" "master" "master") true))
(is (= (valid-api-version? "latest" "master" nil) true))
(is (= (valid-api-version? "latest" "100" "200") false))
(is (= (valid-api-version? "latest" "50" nil) true))
(is (= (valid-api-version? "latest" nil nil) true))
(is (= (valid-api-version? "latest" nil "10") false))
(is (= (valid-api-version? "master" "master" "master") true))
(is (= (valid-api-version? "master" "master" nil) true))
(is (= (valid-api-version? "master" "100" "200") false))
(is (= (valid-api-version? "master" "50" nil) true))
(is (= (valid-api-version? "master" nil nil) true))
(is (= (valid-api-version? "master" nil "10") false))
(is (= (valid-api-version? "50" nil nil) true))
(is (= (valid-api-version? "50" "50" nil) true))
(is (= (valid-api-version? "50" "51" nil) false))
(is (= (valid-api-version? "50" nil "49") false))
(is (= (valid-api-version? "50" nil "50") true))
(is (= (valid-api-version? "50" "50" "50") true))
(is (= (valid-api-version? "50" "49" "50") true)))
(testing "call future api"
(is (= (call-future-api) nil)))
(testing "call master api"
(is (= (call-master-api) nil))))
|
26cd0f826b7e6edc7fc8d86088026e1d94f1c3ccf8de3f1040b985adbd87b427 | symbiont-io/detsys-testkit | EstimateTest.hs | -- |
-- Ported from:
--
module Ldfi.EstimateTest where
import Ldfi.Estimate
import Test.HUnit
------------------------------------------------------------------------
-- * The failure free scenario
-- should only be one such scenario.
unit_estFailureFree :: Assertion
unit_estFailureFree =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 0) nodes3 @=? 1
------------------------------------------------------------------------
-- * Fail-stop scenarios
-- should treat failures independently
unit_estTreatFailuresIndependently :: Assertion
unit_estTreatFailuresIndependently =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 2) nodes2 @=? 16
-- should allow each node to crash once or never
unit_estCrashOnceOrNever :: Assertion
unit_estCrashOnceOrNever =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 1) nodes1 @=? 4
unit_estCrashOnceOrNever2 :: Assertion
unit_estCrashOnceOrNever2 =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 1) nodes2 @=? 8
unit_estCrashOnceOrNever3 :: Assertion
unit_estCrashOnceOrNever3 =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 1) nodes3 @=? 12
should respect
unit_estRespectMaxCrashes :: Assertion
unit_estRespectMaxCrashes =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 2) nodes4 @=? 96
-- ^ Explaination:
--
* There are two nodes that never crash , and there are 6 ways of picking those
two nodes ;
--
* Those nodes only have one failure schedule each ;
--
* The nodes that _ are _ crash prone can crash at one of four times .
--
So : 6 * 1 * ( 4 * 4 ) = 96
--
-- (ways to pick which nodes don't crash) *
-- (executions of crash-free nodes) *
-- (executions of crash prone nodes)
------------------------------------------------------------------------
-- * Omission-only scenarios
-- should allow omissions until eff
unit_estOmissionsEff :: Assertion
unit_estOmissionsEff = grossEstimate (Eot 3) (Eff 2) (MaxCrashes 0) nodes2 @=? 16
unit_estOmissionsEff' :: Assertion
unit_estOmissionsEff' = grossEstimate (Eot 3) (Eff 1) (MaxCrashes 0) nodes2 @=? 4
------------------------------------------------------------------------
-- * Scenarios with both crashes and omissions
-- should prevent crashed nodes from sending messages.
unit_estCrashesPreventSending :: Assertion
unit_estCrashesPreventSending = grossEstimate (Eot 3) (Eff 2) (MaxCrashes 2) nodes2 @=? 121
-- ^ Explaination:
-- With a naive estimate that treated omissions and crashes independently, each
node has 4 choices of times to crash and 4 possible combinations of message
-- omissions.
--
There are two nodes , so we have ( 4 * 4 ) ^ 2 = 256 possible failure scenarios .
--
-- However, if we condition on when the node crashes:
--
* Crash @t=1 - > 1 choices of omissions
* crash @t=2 - > 2 choices
* crash choices
* Never crash - > 4 choices
--
So 11 ^ 2 = 121 possible failure scenarios .
unit_estNoOverflow :: Assertion
unit_estNoOverflow =
assertBool
"Shouldn't overflow and estimate zero scenarios"
(grossEstimate 6 4 1 nodes5 /= 0)
------------------------------------------------------------------------
unit_estTreatFailuresIndependently' :: Assertion
unit_estTreatFailuresIndependently' =
possibleCrashFaultsCount nodes2 (MaxCrashes 2) (NetworkTrace [1, 2, 3]) @=? 25
^ NOTE : this should be 16 according to ` grossEstimate ` .
unit_estCrashOnceOrNever' :: Assertion
unit_estCrashOnceOrNever' =
possibleCrashFaultsCount nodes1 (MaxCrashes 1) (NetworkTrace [1, 2, 3]) @=? 4
unit_estCrashOnceOrNever2' :: Assertion
unit_estCrashOnceOrNever2' =
possibleCrashFaultsCount nodes2 (MaxCrashes 1) (NetworkTrace [1, 2, 3]) @=? 7
NOTE : should be 8 .
unit_estCrashOnceOrNever3' :: Assertion
unit_estCrashOnceOrNever3' =
possibleCrashFaultsCount nodes3 (MaxCrashes 1) (NetworkTrace [1, 2, 3]) @=? 10
NOTE : should be 12 .
| null | https://raw.githubusercontent.com/symbiont-io/detsys-testkit/29a3a0140730420e4c5cc8db23df6fdb03f9302c/src/ldfi/test/Ldfi/EstimateTest.hs | haskell | |
Ported from:
----------------------------------------------------------------------
* The failure free scenario
should only be one such scenario.
----------------------------------------------------------------------
* Fail-stop scenarios
should treat failures independently
should allow each node to crash once or never
^ Explaination:
(ways to pick which nodes don't crash) *
(executions of crash-free nodes) *
(executions of crash prone nodes)
----------------------------------------------------------------------
* Omission-only scenarios
should allow omissions until eff
----------------------------------------------------------------------
* Scenarios with both crashes and omissions
should prevent crashed nodes from sending messages.
^ Explaination:
With a naive estimate that treated omissions and crashes independently, each
omissions.
However, if we condition on when the node crashes:
---------------------------------------------------------------------- | module Ldfi.EstimateTest where
import Ldfi.Estimate
import Test.HUnit
unit_estFailureFree :: Assertion
unit_estFailureFree =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 0) nodes3 @=? 1
unit_estTreatFailuresIndependently :: Assertion
unit_estTreatFailuresIndependently =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 2) nodes2 @=? 16
unit_estCrashOnceOrNever :: Assertion
unit_estCrashOnceOrNever =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 1) nodes1 @=? 4
unit_estCrashOnceOrNever2 :: Assertion
unit_estCrashOnceOrNever2 =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 1) nodes2 @=? 8
unit_estCrashOnceOrNever3 :: Assertion
unit_estCrashOnceOrNever3 =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 1) nodes3 @=? 12
should respect
unit_estRespectMaxCrashes :: Assertion
unit_estRespectMaxCrashes =
grossEstimate (Eot 3) (Eff 0) (MaxCrashes 2) nodes4 @=? 96
* There are two nodes that never crash , and there are 6 ways of picking those
two nodes ;
* Those nodes only have one failure schedule each ;
* The nodes that _ are _ crash prone can crash at one of four times .
So : 6 * 1 * ( 4 * 4 ) = 96
unit_estOmissionsEff :: Assertion
unit_estOmissionsEff = grossEstimate (Eot 3) (Eff 2) (MaxCrashes 0) nodes2 @=? 16
unit_estOmissionsEff' :: Assertion
unit_estOmissionsEff' = grossEstimate (Eot 3) (Eff 1) (MaxCrashes 0) nodes2 @=? 4
unit_estCrashesPreventSending :: Assertion
unit_estCrashesPreventSending = grossEstimate (Eot 3) (Eff 2) (MaxCrashes 2) nodes2 @=? 121
node has 4 choices of times to crash and 4 possible combinations of message
There are two nodes , so we have ( 4 * 4 ) ^ 2 = 256 possible failure scenarios .
* Crash @t=1 - > 1 choices of omissions
* crash @t=2 - > 2 choices
* crash choices
* Never crash - > 4 choices
So 11 ^ 2 = 121 possible failure scenarios .
unit_estNoOverflow :: Assertion
unit_estNoOverflow =
assertBool
"Shouldn't overflow and estimate zero scenarios"
(grossEstimate 6 4 1 nodes5 /= 0)
unit_estTreatFailuresIndependently' :: Assertion
unit_estTreatFailuresIndependently' =
possibleCrashFaultsCount nodes2 (MaxCrashes 2) (NetworkTrace [1, 2, 3]) @=? 25
^ NOTE : this should be 16 according to ` grossEstimate ` .
unit_estCrashOnceOrNever' :: Assertion
unit_estCrashOnceOrNever' =
possibleCrashFaultsCount nodes1 (MaxCrashes 1) (NetworkTrace [1, 2, 3]) @=? 4
unit_estCrashOnceOrNever2' :: Assertion
unit_estCrashOnceOrNever2' =
possibleCrashFaultsCount nodes2 (MaxCrashes 1) (NetworkTrace [1, 2, 3]) @=? 7
NOTE : should be 8 .
unit_estCrashOnceOrNever3' :: Assertion
unit_estCrashOnceOrNever3' =
possibleCrashFaultsCount nodes3 (MaxCrashes 1) (NetworkTrace [1, 2, 3]) @=? 10
NOTE : should be 12 .
|
f882a0105a2c2299acee193abfbd15ee21b917d7af8b98adbd07d69e87c3da9c | chaoxu/fancy-walks | 110.hs | {-# OPTIONS_GHC -O2 #-}
import Data.List
-- (x + y) n = xy
( x - n)(y - n ) = n^2
answer is ( # divisors of n^2 + 1 ) ` div ` 2
minusOrd :: Ord a => [a] -> [a] -> [a]
minusOrd a@(x:xs) b@(y:ys) = case compare x y of
EQ -> minusOrd xs ys
LT -> x : minusOrd xs b
GT -> minusOrd a ys
minusOrd xs _ = xs
unionOrd :: Ord a => [a] -> [a] -> [a]
unionOrd a@(x:xs) b@(y:ys) = case compare x y of
EQ -> x : unionOrd xs ys
LT -> x : unionOrd xs b
GT -> y : unionOrd a ys
unionOrd xs ys = xs ++ ys
pairsOrd :: Ord a => [[a]] -> [[a]]
pairsOrd [] = []
pairsOrd [xs] = [xs]
pairsOrd ((x:xs):ys:remain) = (x : unionOrd xs ys) : pairsOrd remain
joinOrd :: Ord a => [[a]] -> [a]
joinOrd [] = []
joinOrd [xs] = xs
joinOrd ((x:xs):remain) = x : unionOrd xs (joinOrd (pairsOrd remain))
primes = sieve [2..]
where
sieve (x:xs) = x : sieve (filter ((/=0).(`mod`x)) xs)
optimumNumbers = go 1 primes [1..]
where
go mul (p:ps) lst = mul : joinOrd [go (mul * p^k) ps [1..k] | k <- lst]
factors n = go n primes
where
go x (p:ps)
| p * p > x = [x]
| x `mod` p == 0 = p : go (x `div` p) (p:ps)
| otherwise = go x ps
solve :: Integer -> Integer
solve n = (ds + 1) `div` 2
where
ds = product $ map ((+1).(*2).genericLength) $ group $ factors n
limit = 4 * 10^6
problem_110 = head [ p | p <- optimumNumbers , solve p > limit ]
main = print problem_110
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/projecteuler.net/110.hs | haskell | # OPTIONS_GHC -O2 #
(x + y) n = xy |
import Data.List
( x - n)(y - n ) = n^2
answer is ( # divisors of n^2 + 1 ) ` div ` 2
minusOrd :: Ord a => [a] -> [a] -> [a]
minusOrd a@(x:xs) b@(y:ys) = case compare x y of
EQ -> minusOrd xs ys
LT -> x : minusOrd xs b
GT -> minusOrd a ys
minusOrd xs _ = xs
unionOrd :: Ord a => [a] -> [a] -> [a]
unionOrd a@(x:xs) b@(y:ys) = case compare x y of
EQ -> x : unionOrd xs ys
LT -> x : unionOrd xs b
GT -> y : unionOrd a ys
unionOrd xs ys = xs ++ ys
pairsOrd :: Ord a => [[a]] -> [[a]]
pairsOrd [] = []
pairsOrd [xs] = [xs]
pairsOrd ((x:xs):ys:remain) = (x : unionOrd xs ys) : pairsOrd remain
joinOrd :: Ord a => [[a]] -> [a]
joinOrd [] = []
joinOrd [xs] = xs
joinOrd ((x:xs):remain) = x : unionOrd xs (joinOrd (pairsOrd remain))
primes = sieve [2..]
where
sieve (x:xs) = x : sieve (filter ((/=0).(`mod`x)) xs)
optimumNumbers = go 1 primes [1..]
where
go mul (p:ps) lst = mul : joinOrd [go (mul * p^k) ps [1..k] | k <- lst]
factors n = go n primes
where
go x (p:ps)
| p * p > x = [x]
| x `mod` p == 0 = p : go (x `div` p) (p:ps)
| otherwise = go x ps
solve :: Integer -> Integer
solve n = (ds + 1) `div` 2
where
ds = product $ map ((+1).(*2).genericLength) $ group $ factors n
limit = 4 * 10^6
problem_110 = head [ p | p <- optimumNumbers , solve p > limit ]
main = print problem_110
|
85eb4565fe90947aca5bb2de979aeeafdbf872924b0a6033298c4a92aa3f5019 | lgessler/glam | text.clj | (ns glam.xtdb.text
(:require [xtdb.api :as xt]
[glam.xtdb.util :as xutil]
[glam.xtdb.easy :as gxe]
[glam.xtdb.token :as tok]
[glam.algos.text :as ta]
[taoensso.timbre :as log])
(:refer-clojure :exclude [get merge]))
(def attr-keys [:text/id
:text/document
:text/layer
:text/body])
(defn xt->pathom [doc]
(when doc
(-> doc
(update :text/layer xutil/identize :text-layer/id)
(update :text/document xutil/identize :document/id))))
(defn create* [{:text/keys [id] :as attrs}]
(gxe/put* (xutil/create-record "text" id attrs attr-keys)))
(defn create [node attrs]
(let [[_ {:text/keys [id]} :as put] (create* attrs)
tx-status (gxe/submit! node [put])]
{:success tx-status
:id id}))
Queries ------------------------------------------------------------------------
(defn get
[node id]
(xt->pathom (gxe/find-entity node {:text/id id})))
;; Mutations ----------------------------------------------------------------------
(defn get-span-ids [node eid]
(map first (xt/q (xt/db node)
'{:find [?span]
:where [[?span :span/tokens ?tok]
[?tok :token/text ?txt]]
:in [?txt]}
eid)))
(defn get-token-ids [node eid]
(map first (xt/q (xt/db node)
'{:find [?tok]
:where [[?tok :token/text ?txt]]
:in [?txt]}
eid)))
(declare update-body**)
(gxe/deftx update-body [node eid ops]
(let [text (gxe/entity node eid)
tokens (map #(gxe/entity node %) (get-token-ids node eid))
indexed-tokens (reduce #(assoc %1 (:token/id %2) %2) {} tokens)
{new-text :text new-tokens :tokens deleted-token-ids :deleted} (ta/apply-text-edits ops text tokens)
needs-update? (fn [{:token/keys [begin end id]}] (or (not= begin (:token/begin (clojure.core/get indexed-tokens id)))
(not= end (:token/end (clojure.core/get indexed-tokens id)))))
deletion-tx (reduce into (map #(tok/delete** node %) deleted-token-ids))
update-tx (map #(gxe/put* %) (filter needs-update? new-tokens))
text-tx [(gxe/put* (assoc text :text/body (:text/body new-text)))]
tx (reduce into [text-tx deletion-tx update-tx])]
tx))
;; We don't follow the usual pattern of relying on child nodes' delete** functions here because
;; this would lead to children being included multiple times. Instead, we write a bespoke fn.
(gxe/deftx delete [node eid]
(let [span-deletes (mapv gxe/delete* (get-span-ids node eid))
token-deletes (mapv gxe/delete* (get-token-ids node eid))
text-delete [(gxe/delete* eid)]]
(reduce into
[span-deletes
token-deletes
text-delete])))
| null | https://raw.githubusercontent.com/lgessler/glam/7c6ffc73b3e72c17c4314f1e8aec3f90721ecb51/src/main/glam/xtdb/text.clj | clojure | Mutations ----------------------------------------------------------------------
We don't follow the usual pattern of relying on child nodes' delete** functions here because
this would lead to children being included multiple times. Instead, we write a bespoke fn. | (ns glam.xtdb.text
(:require [xtdb.api :as xt]
[glam.xtdb.util :as xutil]
[glam.xtdb.easy :as gxe]
[glam.xtdb.token :as tok]
[glam.algos.text :as ta]
[taoensso.timbre :as log])
(:refer-clojure :exclude [get merge]))
(def attr-keys [:text/id
:text/document
:text/layer
:text/body])
(defn xt->pathom [doc]
(when doc
(-> doc
(update :text/layer xutil/identize :text-layer/id)
(update :text/document xutil/identize :document/id))))
(defn create* [{:text/keys [id] :as attrs}]
(gxe/put* (xutil/create-record "text" id attrs attr-keys)))
(defn create [node attrs]
(let [[_ {:text/keys [id]} :as put] (create* attrs)
tx-status (gxe/submit! node [put])]
{:success tx-status
:id id}))
Queries ------------------------------------------------------------------------
(defn get
[node id]
(xt->pathom (gxe/find-entity node {:text/id id})))
(defn get-span-ids [node eid]
(map first (xt/q (xt/db node)
'{:find [?span]
:where [[?span :span/tokens ?tok]
[?tok :token/text ?txt]]
:in [?txt]}
eid)))
(defn get-token-ids [node eid]
(map first (xt/q (xt/db node)
'{:find [?tok]
:where [[?tok :token/text ?txt]]
:in [?txt]}
eid)))
(declare update-body**)
(gxe/deftx update-body [node eid ops]
(let [text (gxe/entity node eid)
tokens (map #(gxe/entity node %) (get-token-ids node eid))
indexed-tokens (reduce #(assoc %1 (:token/id %2) %2) {} tokens)
{new-text :text new-tokens :tokens deleted-token-ids :deleted} (ta/apply-text-edits ops text tokens)
needs-update? (fn [{:token/keys [begin end id]}] (or (not= begin (:token/begin (clojure.core/get indexed-tokens id)))
(not= end (:token/end (clojure.core/get indexed-tokens id)))))
deletion-tx (reduce into (map #(tok/delete** node %) deleted-token-ids))
update-tx (map #(gxe/put* %) (filter needs-update? new-tokens))
text-tx [(gxe/put* (assoc text :text/body (:text/body new-text)))]
tx (reduce into [text-tx deletion-tx update-tx])]
tx))
(gxe/deftx delete [node eid]
(let [span-deletes (mapv gxe/delete* (get-span-ids node eid))
token-deletes (mapv gxe/delete* (get-token-ids node eid))
text-delete [(gxe/delete* eid)]]
(reduce into
[span-deletes
token-deletes
text-delete])))
|
6936ea75c98c1103b2016bbcaa7f347b0c783aaaf0e21cc6b1ec0d1e7f38510c | cstar/ejabberd-old | gen_pubsub_node.erl | %%% ====================================================================
` ` 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 via the world wide web at /.
%%%
Software distributed under the License is distributed on an " AS IS "
%%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%%% the License for the specific language governing rights and limitations
%%% under the License.
%%%
The Initial Developer of the Original Code is ProcessOne .
Portions created by ProcessOne are Copyright 2006 - 2009 , ProcessOne
All Rights Reserved . ''
This software is copyright 2006 - 2009 , ProcessOne .
%%%
%%%
2006 - 2009 ProcessOne
@author < >
%%% [-one.net/]
%%% @version {@vsn}, {@date} {@time}
%%% @end
%%% ====================================================================
@private
@doc < p > The module < strong>{@module}</strong > defines the PubSub node
plugin behaviour . This behaviour is used to check that a PubSub plugin
respects the current ejabberd PubSub plugin API.</p >
-module(gen_pubsub_node).
-export([behaviour_info/1]).
( ( ) ) - > Callbacks | atom ( )
%% Callbacks = [{Function,Arity}]
%% Function = atom()
%% Arity = integer()
%% @doc Behaviour definition
behaviour_info(callbacks) ->
[{init, 3},
{terminate, 2},
{options, 0},
{features, 0},
{create_node_permission, 6},
{create_node, 2},
{delete_node, 1},
{purge_node, 2},
{subscribe_node, 8},
{unsubscribe_node, 4},
{publish_item, 6},
{delete_item, 4},
{remove_extra_items, 3},
{get_node_affiliations, 1},
{get_entity_affiliations, 2},
{get_affiliation, 2},
{set_affiliation, 3},
{get_node_subscriptions, 1},
{get_entity_subscriptions, 2},
{get_subscriptions, 2},
{set_subscriptions, 4},
{get_pending_nodes, 2},
{get_states, 1},
{get_state, 2},
{set_state, 1},
{get_items, 6},
{get_items, 2},
{get_item, 7},
{get_item, 2},
{set_item, 1},
{get_item_name, 3},
{node_to_path, 1},
{path_to_node, 1}
];
behaviour_info(_Other) ->
undefined.
| null | https://raw.githubusercontent.com/cstar/ejabberd-old/559f8b6b0a935710fe93e9afacb4270d6d6ea00f/src/mod_pubsub/gen_pubsub_node.erl | erlang | ====================================================================
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 via the world wide web 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.
[-one.net/]
@version {@vsn}, {@date} {@time}
@end
====================================================================
Callbacks = [{Function,Arity}]
Function = atom()
Arity = integer()
@doc Behaviour definition | ` ` 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 "
The Initial Developer of the Original Code is ProcessOne .
Portions created by ProcessOne are Copyright 2006 - 2009 , ProcessOne
All Rights Reserved . ''
This software is copyright 2006 - 2009 , ProcessOne .
2006 - 2009 ProcessOne
@author < >
@private
@doc < p > The module < strong>{@module}</strong > defines the PubSub node
plugin behaviour . This behaviour is used to check that a PubSub plugin
respects the current ejabberd PubSub plugin API.</p >
-module(gen_pubsub_node).
-export([behaviour_info/1]).
( ( ) ) - > Callbacks | atom ( )
behaviour_info(callbacks) ->
[{init, 3},
{terminate, 2},
{options, 0},
{features, 0},
{create_node_permission, 6},
{create_node, 2},
{delete_node, 1},
{purge_node, 2},
{subscribe_node, 8},
{unsubscribe_node, 4},
{publish_item, 6},
{delete_item, 4},
{remove_extra_items, 3},
{get_node_affiliations, 1},
{get_entity_affiliations, 2},
{get_affiliation, 2},
{set_affiliation, 3},
{get_node_subscriptions, 1},
{get_entity_subscriptions, 2},
{get_subscriptions, 2},
{set_subscriptions, 4},
{get_pending_nodes, 2},
{get_states, 1},
{get_state, 2},
{set_state, 1},
{get_items, 6},
{get_items, 2},
{get_item, 7},
{get_item, 2},
{set_item, 1},
{get_item_name, 3},
{node_to_path, 1},
{path_to_node, 1}
];
behaviour_info(_Other) ->
undefined.
|
bf782a424de92b7734250beccf38fe628b4512b81d7e03f5474e55fcb968a1d0 | azimut/shiny | xanadu.lisp | (in-package :shiny)
(start-csound (get-orchestra :xanadu))
(load-csound (get-orchestra :xanadu))
(start-thread)
;; XANADU
(make-play plucke "i1" :p4 0 :keynum 60)
(make-play pluck "i2" :p4 0 :keynum 60)
(make-play newfm "i3" :p4 0 :keynum 60 :llimit .2 :rlimit 2.0)
(play-newfm 90 5 :p4 .9)
(play-pluck 90 2)
(play-pluck-arp '(60 62) 1 1)
;; Csound tutorial
(defun lorenz ()
(labels ((interpolate (x)
(round (+ 36 (* x 60)))))
(let ((r 3.974))
(mapcar #'interpolate
(loop :repeat 100 :with y = .5 :collect
(setf y (* r y (- 1f0 y))))))))
(let ((notes (make-cycle (lorenz))))
(defun f (time)
(let ((n (next notes)))
(play-pluck n .5))
(aat (+ time #[.5 b]) #'f it)))
(defun f ())
(f (now))
| null | https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/compositions/drafts/csound/xanadu.lisp | lisp | XANADU
Csound tutorial | (in-package :shiny)
(start-csound (get-orchestra :xanadu))
(load-csound (get-orchestra :xanadu))
(start-thread)
(make-play plucke "i1" :p4 0 :keynum 60)
(make-play pluck "i2" :p4 0 :keynum 60)
(make-play newfm "i3" :p4 0 :keynum 60 :llimit .2 :rlimit 2.0)
(play-newfm 90 5 :p4 .9)
(play-pluck 90 2)
(play-pluck-arp '(60 62) 1 1)
(defun lorenz ()
(labels ((interpolate (x)
(round (+ 36 (* x 60)))))
(let ((r 3.974))
(mapcar #'interpolate
(loop :repeat 100 :with y = .5 :collect
(setf y (* r y (- 1f0 y))))))))
(let ((notes (make-cycle (lorenz))))
(defun f (time)
(let ((n (next notes)))
(play-pluck n .5))
(aat (+ time #[.5 b]) #'f it)))
(defun f ())
(f (now))
|
c51e33514cd5af0708e282d2e29da77473f6ce59d46ccd1220c07072ce6bf592 | input-output-hk/rscoin-core | MessagePack.hs | | MessagePack serialization / deserialization for Core types
module RSCoin.Core.MessagePack () where
import Control.Lens (view, _3)
import Data.Bifunctor (bimap)
import Data.Binary (decodeOrFail, encode)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Fixed as Fixed
import Data.Hashable (Hashable)
import qualified Data.HashSet as HS
import Data.Int (Int64)
import Data.MessagePack (MessagePack (fromObject, toObject), Object (ObjectBin, ObjectExt, ObjectInt),
pack, unpack)
import Data.Ratio (Ratio, denominator, numerator, (%))
import qualified Data.Set as S
import Data.Time.Clock (NominalDiffTime)
import Data.Tuple.Curry (uncurryN)
import RSCoin.Core.Crypto ()
import qualified RSCoin.Core.Primitives as C
import qualified RSCoin.Core.Protocol.Types as C
import qualified RSCoin.Core.Strategy as C
import qualified RSCoin.Core.Types as C
toInt :: Integral a => a -> Int
toInt = fromIntegral
fromInt :: Num a => Int -> a
fromInt = fromIntegral
uncurry2 :: (a -> b -> c) -> (a, b) -> c
uncurry2 = uncurryN
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 = uncurryN
uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e
uncurry4 = uncurryN
uncurry5 :: (a -> b -> c -> d -> e -> f) -> (a, b, c, d, e) -> f
uncurry5 = uncurryN
instance MessagePack (Fixed.Fixed a) where
toObject (Fixed.MkFixed a) = toObject a
fromObject = fmap Fixed.MkFixed . fromObject
instance MessagePack NominalDiffTime where
toObject = toObject . (realToFrac :: NominalDiffTime -> Fixed.Pico)
fromObject = fmap (realToFrac :: Fixed.Pico -> NominalDiffTime) . fromObject
-- msgpack library we use is awful :(
RЕАЛLY IT"S S0 AWFUЛ
instance MessagePack Int64 where
toObject = toObject . toInt
fromObject = fmap fromInt . fromObject
instance MessagePack Integer where
toObject i
| fromInt minBound <= i && i <= fromInt maxBound = ObjectInt $ toInt i
| otherwise = ObjectBin . BSL.toStrict $ encode i
fromObject (ObjectInt i) = Just $ fromInt i
fromObject (ObjectBin b) =
either (const Nothing) (Just . view _3) . decodeOrFail $ BSL.fromStrict b
fromObject _ = Nothing
instance MessagePack Word where
toObject = (toObject :: Integer -> Object) . fromIntegral
fromObject = fmap (fromIntegral :: Integer -> Word) . fromObject
instance (Integral a, MessagePack a) => MessagePack (Ratio a) where
toObject r = toObject (numerator r, denominator r)
fromObject = fmap (uncurry (%)) . fromObject
instance (MessagePack a, MessagePack b) => MessagePack (Either a b) where
toObject (Left a) = ObjectExt 0 $ BSL.toStrict $ pack a
toObject (Right b) = ObjectExt 1 $ BSL.toStrict $ pack b
fromObject (ObjectExt 0 a) = Left <$> unpack (BSL.fromStrict a)
fromObject (ObjectExt 1 b) = Right <$> unpack (BSL.fromStrict b)
fromObject _ = Nothing
instance MessagePack C.Coin where
toObject (C.Coin c t) = toObject (C.getColor c, C.getAmount t)
fromObject = fmap (uncurry C.Coin . bimap C.Color C.CoinAmount) . fromObject
instance MessagePack C.Address where
toObject (C.Address c) = toObject c
fromObject = fmap C.Address . fromObject
instance MessagePack C.Mintette where
toObject C.Mintette{..} =
toObject (toObject mintetteHost, toObject mintettePort)
fromObject = fmap (uncurry2 C.Mintette) . fromObject
instance MessagePack C.Explorer where
toObject C.Explorer{..} =
toObject
(toObject explorerHost, toObject explorerPort, toObject explorerKey)
fromObject = fmap (uncurry3 C.Explorer) . fromObject
instance MessagePack C.PeriodResult where
toObject C.PeriodResult{..} =
toObject
(prPeriodId, prBlocks, prActionLog, prBlocksNumber, prActionLogSize)
fromObject = fmap (uncurry5 C.PeriodResult) . fromObject
instance MessagePack C.NewPeriodData where
toObject C.NewPeriodData{..} =
toObject
(npdPeriodId, npdMintettes, npdHBlock, npdNewIdPayload, npdDpk)
fromObject = fmap (uncurry5 C.NewPeriodData) . fromObject
instance MessagePack C.LBlock where
toObject C.LBlock{..} =
toObject (lbHash, lbTransactions, lbSignature, lbHeads)
fromObject = fmap (uncurry4 C.LBlock) . fromObject
instance MessagePack C.Transaction where
toObject C.Transaction{..} = toObject (txInputs, txOutputs)
fromObject = fmap (uncurry2 C.Transaction) . fromObject
instance MessagePack C.CheckConfirmation where
toObject C.CheckConfirmation{..} =
toObject (ccMintetteKey, ccMintetteSignature, ccHead, ccPeriodId)
fromObject = fmap (uncurry4 C.CheckConfirmation) . fromObject
instance MessagePack C.CommitAcknowledgment where
toObject C.CommitAcknowledgment{..} =
toObject (caMintetteKey, caMintetteSignature, caHead)
fromObject = fmap (uncurry3 C.CommitAcknowledgment) . fromObject
instance MessagePack C.HBlock where
toObject C.HBlock {..} =
toObject (hbHash, hbTransactions, hbSignature, hbDpk, hbAddresses)
fromObject = fmap (uncurry5 C.HBlock) . fromObject
instance MessagePack C.TxStrategy where
toObject C.DefaultStrategy = toObj (0, ())
toObject (C.MOfNStrategy m addrs) = toObj (1, (m, addrs))
fromObject obj = do
(i, args) <- fromObject obj
case (i :: Int) of
0 -> pure C.DefaultStrategy
1 -> uncurry2 C.MOfNStrategy <$> fromObject args
_ -> Nothing
instance MessagePack C.AllocationAddress where
toObject (C.TrustAlloc addr) = toObj (0, addr)
toObject (C.UserAlloc addr) = toObj (1, addr)
fromObject obj = do
(i, addr) <- fromObject obj
case (i :: Int) of
0 -> C.TrustAlloc <$> fromObject addr
1 -> C.UserAlloc <$> fromObject addr
_ -> Nothing
instance MessagePack C.PartyAddress where
toObject (C.TrustParty genAddr pubAddr) = toObj (0, (genAddr, pubAddr))
toObject (C.UserParty genAddr) = toObj (1, genAddr)
fromObject obj = do
(i, addrs) <- fromObject obj
case (i :: Int) of
0 -> uncurry C.TrustParty <$> fromObject addrs
1 -> C.UserParty <$> fromObject addrs
_ -> Nothing
instance MessagePack C.AllocationStrategy where
toObject C.AllocationStrategy{..} = toObject (_sigNumber, _allParties)
fromObject = fmap (uncurry C.AllocationStrategy) . fromObject
instance MessagePack C.AllocationInfo where
toObject C.AllocationInfo{..} = toObject (_allocationStrategy, _currentConfirmations)
fromObject = fmap (uncurry C.AllocationInfo) . fromObject
instance (Ord e, MessagePack e) => MessagePack (S.Set e) where
toObject = toObject . S.toList
fromObject = fmap S.fromList . fromObject
instance (Eq e, Hashable e, MessagePack e) => MessagePack (HS.HashSet e) where
toObject = toObject . HS.toList
fromObject = fmap HS.fromList . fromObject
toObj
:: MessagePack a
=> (Int, a) -> Object
toObj = toObject
instance MessagePack C.ActionLogEntry where
toObject (C.QueryEntry tx) = toObj (0, tx)
toObject (C.CommitEntry tx cc) = toObj (1, (tx, cc))
toObject (C.CloseEpochEntry heads) = toObj (2, heads)
fromObject obj = do
(i,payload) <- fromObject obj
case (i :: Int) of
0 -> C.QueryEntry <$> fromObject payload
1 -> uncurry2 C.CommitEntry <$> fromObject payload
2 -> C.CloseEpochEntry <$> fromObject payload
_ -> Nothing
instance MessagePack C.BankLocalControlRequest where
toObject (C.AddMintette m pk sig) = toObj (0, (m, pk, sig))
toObject (C.PermitMintette pk sig) = toObj (1, (pk, sig))
toObject (C.AddExplorer e pid sig) = toObj (2, (e, pid, sig))
toObject (C.RemoveMintette host port sig) = toObj (3, (host, port, sig))
toObject (C.RemoveExplorer host port sig) = toObj (4, (host, port, sig))
toObject (C.FinishPeriod sig) = toObj (5, sig)
toObject (C.DumpStatistics sId sig) = toObj (6, (sId, sig))
fromObject obj = do
(i,payload) <- fromObject obj
case (i :: Int) of
0 -> uncurry3 C.AddMintette <$> fromObject payload
1 -> uncurry2 C.PermitMintette <$> fromObject payload
2 -> uncurry3 C.AddExplorer <$> fromObject payload
3 -> uncurry3 C.RemoveMintette <$> fromObject payload
4 -> uncurry3 C.RemoveExplorer <$> fromObject payload
5 -> C.FinishPeriod <$> fromObject payload
6 -> uncurry2 C.DumpStatistics <$> fromObject payload
_ -> Nothing
instance MessagePack C.HBlockMetadata where
toObject C.HBlockMetadata {..} = toObject (hbmTimestamp, hbmEmission)
fromObject = fmap (uncurry2 C.HBlockMetadata) . fromObject
instance (MessagePack a, MessagePack b) =>
MessagePack (C.WithMetadata a b) where
toObject C.WithMetadata{..} = toObject (wmValue, wmMetadata)
fromObject = fmap (uncurry C.WithMetadata) . fromObject
instance (MessagePack a) =>
MessagePack (C.WithSignature a) where
toObject C.WithSignature {..} = toObject (wsValue, wsSignature)
fromObject = fmap (uncurry C.WithSignature) . fromObject
| null | https://raw.githubusercontent.com/input-output-hk/rscoin-core/5b3fde8de1bdce71ee6ea0e8f1582ea28f451171/src/RSCoin/Core/MessagePack.hs | haskell | msgpack library we use is awful :( | | MessagePack serialization / deserialization for Core types
module RSCoin.Core.MessagePack () where
import Control.Lens (view, _3)
import Data.Bifunctor (bimap)
import Data.Binary (decodeOrFail, encode)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Fixed as Fixed
import Data.Hashable (Hashable)
import qualified Data.HashSet as HS
import Data.Int (Int64)
import Data.MessagePack (MessagePack (fromObject, toObject), Object (ObjectBin, ObjectExt, ObjectInt),
pack, unpack)
import Data.Ratio (Ratio, denominator, numerator, (%))
import qualified Data.Set as S
import Data.Time.Clock (NominalDiffTime)
import Data.Tuple.Curry (uncurryN)
import RSCoin.Core.Crypto ()
import qualified RSCoin.Core.Primitives as C
import qualified RSCoin.Core.Protocol.Types as C
import qualified RSCoin.Core.Strategy as C
import qualified RSCoin.Core.Types as C
toInt :: Integral a => a -> Int
toInt = fromIntegral
fromInt :: Num a => Int -> a
fromInt = fromIntegral
uncurry2 :: (a -> b -> c) -> (a, b) -> c
uncurry2 = uncurryN
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 = uncurryN
uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e
uncurry4 = uncurryN
uncurry5 :: (a -> b -> c -> d -> e -> f) -> (a, b, c, d, e) -> f
uncurry5 = uncurryN
instance MessagePack (Fixed.Fixed a) where
toObject (Fixed.MkFixed a) = toObject a
fromObject = fmap Fixed.MkFixed . fromObject
instance MessagePack NominalDiffTime where
toObject = toObject . (realToFrac :: NominalDiffTime -> Fixed.Pico)
fromObject = fmap (realToFrac :: Fixed.Pico -> NominalDiffTime) . fromObject
RЕАЛLY IT"S S0 AWFUЛ
instance MessagePack Int64 where
toObject = toObject . toInt
fromObject = fmap fromInt . fromObject
instance MessagePack Integer where
toObject i
| fromInt minBound <= i && i <= fromInt maxBound = ObjectInt $ toInt i
| otherwise = ObjectBin . BSL.toStrict $ encode i
fromObject (ObjectInt i) = Just $ fromInt i
fromObject (ObjectBin b) =
either (const Nothing) (Just . view _3) . decodeOrFail $ BSL.fromStrict b
fromObject _ = Nothing
instance MessagePack Word where
toObject = (toObject :: Integer -> Object) . fromIntegral
fromObject = fmap (fromIntegral :: Integer -> Word) . fromObject
instance (Integral a, MessagePack a) => MessagePack (Ratio a) where
toObject r = toObject (numerator r, denominator r)
fromObject = fmap (uncurry (%)) . fromObject
instance (MessagePack a, MessagePack b) => MessagePack (Either a b) where
toObject (Left a) = ObjectExt 0 $ BSL.toStrict $ pack a
toObject (Right b) = ObjectExt 1 $ BSL.toStrict $ pack b
fromObject (ObjectExt 0 a) = Left <$> unpack (BSL.fromStrict a)
fromObject (ObjectExt 1 b) = Right <$> unpack (BSL.fromStrict b)
fromObject _ = Nothing
instance MessagePack C.Coin where
toObject (C.Coin c t) = toObject (C.getColor c, C.getAmount t)
fromObject = fmap (uncurry C.Coin . bimap C.Color C.CoinAmount) . fromObject
instance MessagePack C.Address where
toObject (C.Address c) = toObject c
fromObject = fmap C.Address . fromObject
instance MessagePack C.Mintette where
toObject C.Mintette{..} =
toObject (toObject mintetteHost, toObject mintettePort)
fromObject = fmap (uncurry2 C.Mintette) . fromObject
instance MessagePack C.Explorer where
toObject C.Explorer{..} =
toObject
(toObject explorerHost, toObject explorerPort, toObject explorerKey)
fromObject = fmap (uncurry3 C.Explorer) . fromObject
instance MessagePack C.PeriodResult where
toObject C.PeriodResult{..} =
toObject
(prPeriodId, prBlocks, prActionLog, prBlocksNumber, prActionLogSize)
fromObject = fmap (uncurry5 C.PeriodResult) . fromObject
instance MessagePack C.NewPeriodData where
toObject C.NewPeriodData{..} =
toObject
(npdPeriodId, npdMintettes, npdHBlock, npdNewIdPayload, npdDpk)
fromObject = fmap (uncurry5 C.NewPeriodData) . fromObject
instance MessagePack C.LBlock where
toObject C.LBlock{..} =
toObject (lbHash, lbTransactions, lbSignature, lbHeads)
fromObject = fmap (uncurry4 C.LBlock) . fromObject
instance MessagePack C.Transaction where
toObject C.Transaction{..} = toObject (txInputs, txOutputs)
fromObject = fmap (uncurry2 C.Transaction) . fromObject
instance MessagePack C.CheckConfirmation where
toObject C.CheckConfirmation{..} =
toObject (ccMintetteKey, ccMintetteSignature, ccHead, ccPeriodId)
fromObject = fmap (uncurry4 C.CheckConfirmation) . fromObject
instance MessagePack C.CommitAcknowledgment where
toObject C.CommitAcknowledgment{..} =
toObject (caMintetteKey, caMintetteSignature, caHead)
fromObject = fmap (uncurry3 C.CommitAcknowledgment) . fromObject
instance MessagePack C.HBlock where
toObject C.HBlock {..} =
toObject (hbHash, hbTransactions, hbSignature, hbDpk, hbAddresses)
fromObject = fmap (uncurry5 C.HBlock) . fromObject
instance MessagePack C.TxStrategy where
toObject C.DefaultStrategy = toObj (0, ())
toObject (C.MOfNStrategy m addrs) = toObj (1, (m, addrs))
fromObject obj = do
(i, args) <- fromObject obj
case (i :: Int) of
0 -> pure C.DefaultStrategy
1 -> uncurry2 C.MOfNStrategy <$> fromObject args
_ -> Nothing
instance MessagePack C.AllocationAddress where
toObject (C.TrustAlloc addr) = toObj (0, addr)
toObject (C.UserAlloc addr) = toObj (1, addr)
fromObject obj = do
(i, addr) <- fromObject obj
case (i :: Int) of
0 -> C.TrustAlloc <$> fromObject addr
1 -> C.UserAlloc <$> fromObject addr
_ -> Nothing
instance MessagePack C.PartyAddress where
toObject (C.TrustParty genAddr pubAddr) = toObj (0, (genAddr, pubAddr))
toObject (C.UserParty genAddr) = toObj (1, genAddr)
fromObject obj = do
(i, addrs) <- fromObject obj
case (i :: Int) of
0 -> uncurry C.TrustParty <$> fromObject addrs
1 -> C.UserParty <$> fromObject addrs
_ -> Nothing
instance MessagePack C.AllocationStrategy where
toObject C.AllocationStrategy{..} = toObject (_sigNumber, _allParties)
fromObject = fmap (uncurry C.AllocationStrategy) . fromObject
instance MessagePack C.AllocationInfo where
toObject C.AllocationInfo{..} = toObject (_allocationStrategy, _currentConfirmations)
fromObject = fmap (uncurry C.AllocationInfo) . fromObject
instance (Ord e, MessagePack e) => MessagePack (S.Set e) where
toObject = toObject . S.toList
fromObject = fmap S.fromList . fromObject
instance (Eq e, Hashable e, MessagePack e) => MessagePack (HS.HashSet e) where
toObject = toObject . HS.toList
fromObject = fmap HS.fromList . fromObject
toObj
:: MessagePack a
=> (Int, a) -> Object
toObj = toObject
instance MessagePack C.ActionLogEntry where
toObject (C.QueryEntry tx) = toObj (0, tx)
toObject (C.CommitEntry tx cc) = toObj (1, (tx, cc))
toObject (C.CloseEpochEntry heads) = toObj (2, heads)
fromObject obj = do
(i,payload) <- fromObject obj
case (i :: Int) of
0 -> C.QueryEntry <$> fromObject payload
1 -> uncurry2 C.CommitEntry <$> fromObject payload
2 -> C.CloseEpochEntry <$> fromObject payload
_ -> Nothing
instance MessagePack C.BankLocalControlRequest where
toObject (C.AddMintette m pk sig) = toObj (0, (m, pk, sig))
toObject (C.PermitMintette pk sig) = toObj (1, (pk, sig))
toObject (C.AddExplorer e pid sig) = toObj (2, (e, pid, sig))
toObject (C.RemoveMintette host port sig) = toObj (3, (host, port, sig))
toObject (C.RemoveExplorer host port sig) = toObj (4, (host, port, sig))
toObject (C.FinishPeriod sig) = toObj (5, sig)
toObject (C.DumpStatistics sId sig) = toObj (6, (sId, sig))
fromObject obj = do
(i,payload) <- fromObject obj
case (i :: Int) of
0 -> uncurry3 C.AddMintette <$> fromObject payload
1 -> uncurry2 C.PermitMintette <$> fromObject payload
2 -> uncurry3 C.AddExplorer <$> fromObject payload
3 -> uncurry3 C.RemoveMintette <$> fromObject payload
4 -> uncurry3 C.RemoveExplorer <$> fromObject payload
5 -> C.FinishPeriod <$> fromObject payload
6 -> uncurry2 C.DumpStatistics <$> fromObject payload
_ -> Nothing
instance MessagePack C.HBlockMetadata where
toObject C.HBlockMetadata {..} = toObject (hbmTimestamp, hbmEmission)
fromObject = fmap (uncurry2 C.HBlockMetadata) . fromObject
instance (MessagePack a, MessagePack b) =>
MessagePack (C.WithMetadata a b) where
toObject C.WithMetadata{..} = toObject (wmValue, wmMetadata)
fromObject = fmap (uncurry C.WithMetadata) . fromObject
instance (MessagePack a) =>
MessagePack (C.WithSignature a) where
toObject C.WithSignature {..} = toObject (wsValue, wsSignature)
fromObject = fmap (uncurry C.WithSignature) . fromObject
|
8f56ed003be108eb6f6ca597d756160acd08d6dae79550aaa6bc2c3180b588e0 | GaloisInc/llvm-verifier | Common.hs | # LANGUAGE CPP #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TupleSections #
|
Module : $ Header$
Description : Symbolic execution tests
License : BSD3
Stability : provisional
Point - of - contact : atomb
Module : $Header$
Description : Symbolic execution tests
License : BSD3
Stability : provisional
Point-of-contact : atomb
-}
module Tests.Common where
import qualified Numeric
import Control.Monad (unless, void)
import Control.Monad.Fail
import Control.Monad.State (gets, MonadIO, liftIO)
import Control.Lens ( (^.) )
import Data.Int
import Data.Typeable
import Test.Tasty
import Test.Tasty.Options
import Test.Tasty.QuickCheck
import qualified Test.Tasty.HUnit as HU
import Prelude ()
import Prelude.Compat
import System.FilePath
#if !MIN_VERSION_haskeline(0,8,0)
import System.Console.Haskeline.MonadException ( MonadException )
#else
import qualified Control.Monad.Catch as E
#endif
import qualified Data.ABC as ABC
import LSSImpl
import Verifier.LLVM.Codebase
import Verifier.LLVM.Backend.BitBlast
import Verifier.LLVM.Backend.SAW
import Verifier.LLVM.Simulator hiding (run)
import qualified Test.QuickCheck as QC
import qualified Test.QuickCheck.Monadic as QC
import qualified Text.LLVM as L
qctest :: Bool -> String -> QC.PropertyM IO () -> TestTree
qctest shouldFail desc propM = testProperty desc (handleNeg $ QC.monadicIO $ propM)
where
handleNeg = if shouldFail then QC.expectFailure else id
data ExpectedRV a = AllPathsErr | VoidRV | RV a deriving (Eq, Functor)
type SBEPropM m = forall sbe. (SimulatorExceptionContext sbe m, Ord (SBETerm sbe)) => Simulator sbe m ()
type SBECreateFn = DataLayout -> IO SBEPair
abcNetwork :: ABC.Proxy ABC.GIALit ABC.GIA
abcNetwork = ABC.giaNetwork
-- | Create buddy backend and initial memory.
createBuddyModel :: SBECreateFn
createBuddyModel dl = do
(ABC.SomeGraph g) <- (ABC.newGraph abcNetwork)
let sbe = sbeBitBlast g dl (buddyMemModel dl g)
mem = buddyInitMemory (defaultMemGeom dl)
return (SBEPair sbe mem)
-- | Create buddy backend and initial memory.
createDagModel ::SBECreateFn
createDagModel dl = do
(ABC.SomeGraph g) <- ABC.newGraph abcNetwork
(mm,mem) <- createDagMemModel dl g (defaultMemGeom dl)
let sbe = sbeBitBlast g dl mm
return (SBEPair sbe mem)
createSAWModel :: SBECreateFn
createSAWModel dl = do
(sbe,mem) <- liftIO $ createSAWBackend abcNetwork dl
return (SBEPair sbe mem)
supportDir :: FilePath
supportDir = "test" </> "src" </> "support"
testsDir :: FilePath
testsDir = supportDir
testMDL :: FilePath -> IO L.Module
testMDL bcFile = loadModule $ testsDir </> bcFile
data VerbosityOption = VerbosityOption Int
deriving (Eq, Show, Typeable)
instance IsOption VerbosityOption where
defaultValue = VerbosityOption 0
parseValue = \s ->
case Numeric.readDec s of
(i,[]):_ -> Just (VerbosityOption i)
_ -> Nothing
optionName = return "verbosity"
optionHelp = return "verbosity level for the simulator"
withVerbModel :: FilePath -> (Int -> IO L.Module -> TestTree) -> TestTree
withVerbModel bcFile f =
askOption $ \(VerbosityOption v) ->
withResource (testMDL bcFile) (\_ -> return ()) $ \getmdl ->
f v getmdl
forAllMemModels :: String -> FilePath -> (String -> Int -> SBECreateFn -> IO L.Module -> TestTree) -> TestTree
forAllMemModels groupName bcFile mkTest =
withVerbModel bcFile $ \v getmdl ->
testGroup groupName
[ mkTest "buddy model" v createBuddyModel getmdl
, mkTest "dag model" v createDagModel getmdl
, mkTest "SAW model" v createSAWModel getmdl
]
runTestSimulator :: ( MonadIO m
#if !MIN_VERSION_haskeline(0,8,0)
, MonadException m
#else
, E.MonadCatch m
#endif
, Functor m, MonadFail m)
=> Int
-> SBECreateFn
-> IO L.Module -- ^ Code to run in.
-> SBEPropM m
-> m ()
runTestSimulator v createFn mdlio action = do
mdl <- liftIO mdlio
let dl = parseDataLayout (L.modDataLayout mdl)
(SBEPair sbe mem) <- liftIO $ createFn dl
([],cb) <- liftIO $ mkCodebase sbe dl mdl
runSimulator cb sbe mem Nothing $ do
setVerbosity v
action
runCInt32Fn :: (SimulatorExceptionContext sbe m
#if MIN_VERSION_haskeline(0,8,0)
, E.MonadCatch m
#endif
)
=> L.Symbol
-> [Int32]
-> ExpectedRV Integer
-> Simulator sbe m ()
runCInt32Fn sym cargs erv = do
sbe <- gets symBE
args <- mapM (liftSBE . termInt sbe 32 . fromIntegral) cargs
let rvt = if erv == VoidRV then Nothing else Just i32
void $ callDefine sym rvt ((IntType 32,) <$> args)
mrv <- getProgramReturnValue
checkReturnValue sbe erv mrv
runVoidFn :: ( SimulatorExceptionContext sbe m
#if MIN_VERSION_haskeline(0,8,0)
, E.MonadCatch m
#endif
)
=> L.Symbol
-> ExpectedRV Integer
-> Simulator sbe m ()
runVoidFn sym erv = do
sbe <- gets symBE
void $ callDefine sym Nothing []
mrv <- getProgramReturnValue
checkReturnValue sbe erv mrv
checkReturnValue :: Monad m => SBE sbe -> ExpectedRV Integer -> Maybe (SBETerm sbe) -> m ()
checkReturnValue sbe erv mrv =
case (erv,mrv) of
(RV{}, Nothing) -> error "Missing return value"
(RV chk, Just rv) ->
case asSignedInteger sbe 32 rv of
Nothing -> error $ "Symbolic return value when constant expected.\n"
++ show (prettyTermD sbe rv)
Just val ->
unless (val == chk) $
error $ "Expected " ++ show chk ++ ", got " ++ show val
(VoidRV,Nothing) -> return ()
(VoidRV, Just{}) -> error $ "Received return value when none expected."
(AllPathsErr, Nothing) -> return ()
(AllPathsErr, Just{}) ->
error "Received return value when all paths were expected to error."
lssTestAll :: String
-> [String] -- arguments to main
-> Maybe Int -- expected number of error paths
-> ExpectedRV Integer -- expected return value
-> TestTree
lssTestAll nm args expectErr expectRV =
forAllMemModels nm (nm <.> "bc") $ \bkName v sbeCF mdlio ->
runLssTest bkName v sbeCF mdlio args expectErr expectRV
runLssTest :: String
-> Int
-> SBECreateFn
-> IO L.Module
-> [String]
-> Maybe Int
-> ExpectedRV Integer
-> TestTree
runLssTest bkName v sbeCF mdlio args expectErr expectRV =
HU.testCase bkName $ runTestSimulator v sbeCF mdlio $ do
sbe <- gets symBE
execResult <- testRunMain args
liftIO $ checkExecResult sbe expectRV execResult
liftIO $ checkErrPaths expectErr execResult
testRunMain :: ( SimulatorExceptionContext sbe m
#if MIN_VERSION_haskeline(0,8,0)
, E.MonadCatch m
#endif
)
=> [String] -> Simulator sbe m (ExecRslt sbe Integer)
testRunMain args = do
cb <- gets codebase
case lookupDefine (L.Symbol "main") cb of
Nothing -> error "Provided bitcode does not contain main()."
Just mainDef -> runMainFn mainDef ("lss" : args)
checkErrPaths :: Maybe Int -> ExecRslt sbe Integer -> IO ()
checkErrPaths Nothing _ = return ()
checkErrPaths (Just n) execRslt =
HU.assertEqual "error path mismatch" n (length (execRslt^.execRsltErrorPaths))
checkExecResult :: SBE sbe -> ExpectedRV Integer -> ExecRslt sbe Integer -> IO ()
checkExecResult sbe mexpectedRV execRslt = do
case execRslt of
ConcRV _ _mm r -> do
case mexpectedRV of
VoidRV -> HU.assertFailure "Unexpected return value"
AllPathsErr -> HU.assertFailure "all paths resulted in errors"
RV expectedRV -> HU.assertEqual "incorrect return value" r expectedRV
NoMainRV _ _mm -> do
case mexpectedRV of
VoidRV -> return ()
AllPathsErr -> return ()
RV{} -> HU.assertFailure "Missing return value"
SymRV _ _ tm -> do
HU.assertFailure $ "Unexpected sym exec result: "++show (prettyTermD sbe tm)
constTermEq :: Maybe Integer -> Integer -> Bool
constTermEq (Just v) = (==v)
constTermEq _ = const False
| null | https://raw.githubusercontent.com/GaloisInc/llvm-verifier/d97ee6d2e731f48db833cc451326e737e1e39963/test/src/Tests/Common.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE ImplicitParams #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
| Create buddy backend and initial memory.
| Create buddy backend and initial memory.
^ Code to run in.
arguments to main
expected number of error paths
expected return value | # LANGUAGE CPP #
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleContexts #
# LANGUAGE TupleSections #
|
Module : $ Header$
Description : Symbolic execution tests
License : BSD3
Stability : provisional
Point - of - contact : atomb
Module : $Header$
Description : Symbolic execution tests
License : BSD3
Stability : provisional
Point-of-contact : atomb
-}
module Tests.Common where
import qualified Numeric
import Control.Monad (unless, void)
import Control.Monad.Fail
import Control.Monad.State (gets, MonadIO, liftIO)
import Control.Lens ( (^.) )
import Data.Int
import Data.Typeable
import Test.Tasty
import Test.Tasty.Options
import Test.Tasty.QuickCheck
import qualified Test.Tasty.HUnit as HU
import Prelude ()
import Prelude.Compat
import System.FilePath
#if !MIN_VERSION_haskeline(0,8,0)
import System.Console.Haskeline.MonadException ( MonadException )
#else
import qualified Control.Monad.Catch as E
#endif
import qualified Data.ABC as ABC
import LSSImpl
import Verifier.LLVM.Codebase
import Verifier.LLVM.Backend.BitBlast
import Verifier.LLVM.Backend.SAW
import Verifier.LLVM.Simulator hiding (run)
import qualified Test.QuickCheck as QC
import qualified Test.QuickCheck.Monadic as QC
import qualified Text.LLVM as L
qctest :: Bool -> String -> QC.PropertyM IO () -> TestTree
qctest shouldFail desc propM = testProperty desc (handleNeg $ QC.monadicIO $ propM)
where
handleNeg = if shouldFail then QC.expectFailure else id
data ExpectedRV a = AllPathsErr | VoidRV | RV a deriving (Eq, Functor)
type SBEPropM m = forall sbe. (SimulatorExceptionContext sbe m, Ord (SBETerm sbe)) => Simulator sbe m ()
type SBECreateFn = DataLayout -> IO SBEPair
abcNetwork :: ABC.Proxy ABC.GIALit ABC.GIA
abcNetwork = ABC.giaNetwork
createBuddyModel :: SBECreateFn
createBuddyModel dl = do
(ABC.SomeGraph g) <- (ABC.newGraph abcNetwork)
let sbe = sbeBitBlast g dl (buddyMemModel dl g)
mem = buddyInitMemory (defaultMemGeom dl)
return (SBEPair sbe mem)
createDagModel ::SBECreateFn
createDagModel dl = do
(ABC.SomeGraph g) <- ABC.newGraph abcNetwork
(mm,mem) <- createDagMemModel dl g (defaultMemGeom dl)
let sbe = sbeBitBlast g dl mm
return (SBEPair sbe mem)
createSAWModel :: SBECreateFn
createSAWModel dl = do
(sbe,mem) <- liftIO $ createSAWBackend abcNetwork dl
return (SBEPair sbe mem)
supportDir :: FilePath
supportDir = "test" </> "src" </> "support"
testsDir :: FilePath
testsDir = supportDir
testMDL :: FilePath -> IO L.Module
testMDL bcFile = loadModule $ testsDir </> bcFile
data VerbosityOption = VerbosityOption Int
deriving (Eq, Show, Typeable)
instance IsOption VerbosityOption where
defaultValue = VerbosityOption 0
parseValue = \s ->
case Numeric.readDec s of
(i,[]):_ -> Just (VerbosityOption i)
_ -> Nothing
optionName = return "verbosity"
optionHelp = return "verbosity level for the simulator"
withVerbModel :: FilePath -> (Int -> IO L.Module -> TestTree) -> TestTree
withVerbModel bcFile f =
askOption $ \(VerbosityOption v) ->
withResource (testMDL bcFile) (\_ -> return ()) $ \getmdl ->
f v getmdl
forAllMemModels :: String -> FilePath -> (String -> Int -> SBECreateFn -> IO L.Module -> TestTree) -> TestTree
forAllMemModels groupName bcFile mkTest =
withVerbModel bcFile $ \v getmdl ->
testGroup groupName
[ mkTest "buddy model" v createBuddyModel getmdl
, mkTest "dag model" v createDagModel getmdl
, mkTest "SAW model" v createSAWModel getmdl
]
runTestSimulator :: ( MonadIO m
#if !MIN_VERSION_haskeline(0,8,0)
, MonadException m
#else
, E.MonadCatch m
#endif
, Functor m, MonadFail m)
=> Int
-> SBECreateFn
-> SBEPropM m
-> m ()
runTestSimulator v createFn mdlio action = do
mdl <- liftIO mdlio
let dl = parseDataLayout (L.modDataLayout mdl)
(SBEPair sbe mem) <- liftIO $ createFn dl
([],cb) <- liftIO $ mkCodebase sbe dl mdl
runSimulator cb sbe mem Nothing $ do
setVerbosity v
action
runCInt32Fn :: (SimulatorExceptionContext sbe m
#if MIN_VERSION_haskeline(0,8,0)
, E.MonadCatch m
#endif
)
=> L.Symbol
-> [Int32]
-> ExpectedRV Integer
-> Simulator sbe m ()
runCInt32Fn sym cargs erv = do
sbe <- gets symBE
args <- mapM (liftSBE . termInt sbe 32 . fromIntegral) cargs
let rvt = if erv == VoidRV then Nothing else Just i32
void $ callDefine sym rvt ((IntType 32,) <$> args)
mrv <- getProgramReturnValue
checkReturnValue sbe erv mrv
runVoidFn :: ( SimulatorExceptionContext sbe m
#if MIN_VERSION_haskeline(0,8,0)
, E.MonadCatch m
#endif
)
=> L.Symbol
-> ExpectedRV Integer
-> Simulator sbe m ()
runVoidFn sym erv = do
sbe <- gets symBE
void $ callDefine sym Nothing []
mrv <- getProgramReturnValue
checkReturnValue sbe erv mrv
checkReturnValue :: Monad m => SBE sbe -> ExpectedRV Integer -> Maybe (SBETerm sbe) -> m ()
checkReturnValue sbe erv mrv =
case (erv,mrv) of
(RV{}, Nothing) -> error "Missing return value"
(RV chk, Just rv) ->
case asSignedInteger sbe 32 rv of
Nothing -> error $ "Symbolic return value when constant expected.\n"
++ show (prettyTermD sbe rv)
Just val ->
unless (val == chk) $
error $ "Expected " ++ show chk ++ ", got " ++ show val
(VoidRV,Nothing) -> return ()
(VoidRV, Just{}) -> error $ "Received return value when none expected."
(AllPathsErr, Nothing) -> return ()
(AllPathsErr, Just{}) ->
error "Received return value when all paths were expected to error."
lssTestAll :: String
-> TestTree
lssTestAll nm args expectErr expectRV =
forAllMemModels nm (nm <.> "bc") $ \bkName v sbeCF mdlio ->
runLssTest bkName v sbeCF mdlio args expectErr expectRV
runLssTest :: String
-> Int
-> SBECreateFn
-> IO L.Module
-> [String]
-> Maybe Int
-> ExpectedRV Integer
-> TestTree
runLssTest bkName v sbeCF mdlio args expectErr expectRV =
HU.testCase bkName $ runTestSimulator v sbeCF mdlio $ do
sbe <- gets symBE
execResult <- testRunMain args
liftIO $ checkExecResult sbe expectRV execResult
liftIO $ checkErrPaths expectErr execResult
testRunMain :: ( SimulatorExceptionContext sbe m
#if MIN_VERSION_haskeline(0,8,0)
, E.MonadCatch m
#endif
)
=> [String] -> Simulator sbe m (ExecRslt sbe Integer)
testRunMain args = do
cb <- gets codebase
case lookupDefine (L.Symbol "main") cb of
Nothing -> error "Provided bitcode does not contain main()."
Just mainDef -> runMainFn mainDef ("lss" : args)
checkErrPaths :: Maybe Int -> ExecRslt sbe Integer -> IO ()
checkErrPaths Nothing _ = return ()
checkErrPaths (Just n) execRslt =
HU.assertEqual "error path mismatch" n (length (execRslt^.execRsltErrorPaths))
checkExecResult :: SBE sbe -> ExpectedRV Integer -> ExecRslt sbe Integer -> IO ()
checkExecResult sbe mexpectedRV execRslt = do
case execRslt of
ConcRV _ _mm r -> do
case mexpectedRV of
VoidRV -> HU.assertFailure "Unexpected return value"
AllPathsErr -> HU.assertFailure "all paths resulted in errors"
RV expectedRV -> HU.assertEqual "incorrect return value" r expectedRV
NoMainRV _ _mm -> do
case mexpectedRV of
VoidRV -> return ()
AllPathsErr -> return ()
RV{} -> HU.assertFailure "Missing return value"
SymRV _ _ tm -> do
HU.assertFailure $ "Unexpected sym exec result: "++show (prettyTermD sbe tm)
constTermEq :: Maybe Integer -> Integer -> Bool
constTermEq (Just v) = (==v)
constTermEq _ = const False
|
234ae0f7c7681909e3fdd1da32863ba500dd9d9196e13d3510c97b4777706a76 | digitallyinduced/ihp | Interval.hs | # LANGUAGE TemplateHaskell #
|
Module : IHP.Postgres . Interval
Description : Adds support for the Postgres Interval type
Copyright : ( c ) digitally induced GmbH , 2020
Module: IHP.Postgres.Interval
Description: Adds support for the Postgres Interval type
Copyright: (c) digitally induced GmbH, 2020
-}
module IHP.Postgres.Interval where
import BasicPrelude
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.FromField
import qualified Database.PostgreSQL.Simple.TypeInfo.Static as TI
import Database.PostgreSQL.Simple.TypeInfo.Macro as TI
import Data.Attoparsec.ByteString.Char8 as Attoparsec
import Data.String.Conversions (cs)
import Data.Aeson
import IHP.Postgres.TimeParser (PGInterval(..))
instance FromField PGInterval where
fromField f v =
if typeOid f /= $(inlineTypoid TI.interval)
then returnError Incompatible f ""
else case v of
Nothing -> returnError UnexpectedNull f ""
Just bs -> case parseOnly pPGInterval bs of
Left err -> returnError ConversionFailed f err
Right val -> pure val
pPGInterval = do
bs <- takeByteString
pure (PGInterval bs)
instance ToField PGInterval where
toField (PGInterval interval) = toField (interval)
instance FromJSON PGInterval where
parseJSON = withText "PGInterval" $ \text -> pure (PGInterval (encodeUtf8 text))
instance ToJSON PGInterval where
toJSON (PGInterval pgInterval) = String (cs pgInterval)
| null | https://raw.githubusercontent.com/digitallyinduced/ihp/37cb74ce42420dec43376f921255b883e21bc3e8/IHP/Postgres/Interval.hs | haskell | # LANGUAGE TemplateHaskell #
|
Module : IHP.Postgres . Interval
Description : Adds support for the Postgres Interval type
Copyright : ( c ) digitally induced GmbH , 2020
Module: IHP.Postgres.Interval
Description: Adds support for the Postgres Interval type
Copyright: (c) digitally induced GmbH, 2020
-}
module IHP.Postgres.Interval where
import BasicPrelude
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.FromField
import qualified Database.PostgreSQL.Simple.TypeInfo.Static as TI
import Database.PostgreSQL.Simple.TypeInfo.Macro as TI
import Data.Attoparsec.ByteString.Char8 as Attoparsec
import Data.String.Conversions (cs)
import Data.Aeson
import IHP.Postgres.TimeParser (PGInterval(..))
instance FromField PGInterval where
fromField f v =
if typeOid f /= $(inlineTypoid TI.interval)
then returnError Incompatible f ""
else case v of
Nothing -> returnError UnexpectedNull f ""
Just bs -> case parseOnly pPGInterval bs of
Left err -> returnError ConversionFailed f err
Right val -> pure val
pPGInterval = do
bs <- takeByteString
pure (PGInterval bs)
instance ToField PGInterval where
toField (PGInterval interval) = toField (interval)
instance FromJSON PGInterval where
parseJSON = withText "PGInterval" $ \text -> pure (PGInterval (encodeUtf8 text))
instance ToJSON PGInterval where
toJSON (PGInterval pgInterval) = String (cs pgInterval)
| |
c9799d9515b95dfbdc49b3261fda307af10db38d323b0822f70bc9474f34397c | blak3mill3r/noah | serdes.clj | (ns noah.serdes
"There's a lot of room for improvement here. They don't take options, and I haven't thought it all through.
You can always build a Serde yourself. `serdes` is a multimethod so it is open to extension."
(:require
[taoensso.nippy :as nippy]
[clojure.data.json :as json])
(:import
[java.nio.charset StandardCharsets]
[org.apache.kafka.common.serialization Serdes Serde Deserializer Serializer]
[org.apache.kafka.streams.kstream Consumed Produced Serialized]))
(deftype NippyDeserializer [opts]
Deserializer
(configure [_ _ _])
(deserialize [_ _ data] (nippy/thaw data opts))
(close [_]))
(deftype NippySerializer [opts]
Serializer
(configure [_ _ _])
(serialize [_ _ data] (nippy/freeze data opts))
(close [_]))
(def the-nippy-serializer (NippySerializer. {:incl-metadata? false})) ;; TODO:(Blake) allow the user to configure this
(def the-nippy-deserializer (NippyDeserializer. {}))
(deftype NippySerde []
Serde
(configure [this map b])
(close [this])
(serializer [this] the-nippy-serializer)
(deserializer [this] the-nippy-deserializer))
(deftype EdnSerializer []
Serializer
(close [o])
(configure [this configs key?])
(serialize [this topic data]
(when data (-> (binding [*print-length* false
*print-level* false]
(prn-str data))
(.getBytes StandardCharsets/UTF_8)))))
(defrecord EdnDeserializer [opts]
Deserializer
(close [this])
(configure [this configs key?])
(deserialize [this topic data]
(when data
(->> (String. data StandardCharsets/UTF_8)
(clojure.edn/read-string opts)))))
(def the-edn-serializer (EdnSerializer.))
(def the-edn-deserializer (EdnDeserializer. {}))
(deftype EdnSerde []
Serde
(configure [this map b])
(close [this])
(serializer [this] the-edn-serializer)
(deserializer [this] the-edn-deserializer))
(deftype JsonSerializer []
Serializer
(close [o])
(configure [this configs key?])
(serialize [this topic data]
(when data (-> (json/write-str data)
(.getBytes StandardCharsets/UTF_8)))))
(defrecord JsonDeserializer [opts]
Deserializer
(close [this])
(configure [this configs key?])
(deserialize [this topic data]
(when data
(-> (String. data StandardCharsets/UTF_8)
(json/read-str opts)))))
(def the-json-serializer (JsonSerializer.))
(def the-json-deserializer (JsonDeserializer. {}))
(deftype JsonSerde []
Serde
(configure [this map b])
(close [this])
(serializer [this] the-json-serializer)
(deserializer [this] the-json-deserializer))
;; `serdes` is a multimethod in order to be open to extension
(defmulti serdes identity)
allow using a plain instance instead of a keyword
(defmethod serdes :string [_] (Serdes/String))
(defmethod serdes :long [_] (Serdes/Long))
(defmethod serdes :bytes [_] (Serdes/Bytes))
(defmethod serdes :byte-buffer [_] (Serdes/ByteBuffer))
(defmethod serdes :byte-array [_] (Serdes/ByteArray))
(defmethod serdes :short [_] (Serdes/Short))
(defmethod serdes :int [_] (Serdes/Integer))
(defmethod serdes :double [_] (Serdes/Double))
(defmethod serdes :float [_] (Serdes/Float))
(defmethod serdes :nippy [_] (NippySerde.))
(defmethod serdes :edn [_] (EdnSerde.))
(defmethod serdes :json [_] (JsonSerde.))
| null | https://raw.githubusercontent.com/blak3mill3r/noah/03f63316a082baa7a57d00fbfe6d7164061f952d/src/noah/serdes.clj | clojure | TODO:(Blake) allow the user to configure this
`serdes` is a multimethod in order to be open to extension | (ns noah.serdes
"There's a lot of room for improvement here. They don't take options, and I haven't thought it all through.
You can always build a Serde yourself. `serdes` is a multimethod so it is open to extension."
(:require
[taoensso.nippy :as nippy]
[clojure.data.json :as json])
(:import
[java.nio.charset StandardCharsets]
[org.apache.kafka.common.serialization Serdes Serde Deserializer Serializer]
[org.apache.kafka.streams.kstream Consumed Produced Serialized]))
(deftype NippyDeserializer [opts]
Deserializer
(configure [_ _ _])
(deserialize [_ _ data] (nippy/thaw data opts))
(close [_]))
(deftype NippySerializer [opts]
Serializer
(configure [_ _ _])
(serialize [_ _ data] (nippy/freeze data opts))
(close [_]))
(def the-nippy-deserializer (NippyDeserializer. {}))
(deftype NippySerde []
Serde
(configure [this map b])
(close [this])
(serializer [this] the-nippy-serializer)
(deserializer [this] the-nippy-deserializer))
(deftype EdnSerializer []
Serializer
(close [o])
(configure [this configs key?])
(serialize [this topic data]
(when data (-> (binding [*print-length* false
*print-level* false]
(prn-str data))
(.getBytes StandardCharsets/UTF_8)))))
(defrecord EdnDeserializer [opts]
Deserializer
(close [this])
(configure [this configs key?])
(deserialize [this topic data]
(when data
(->> (String. data StandardCharsets/UTF_8)
(clojure.edn/read-string opts)))))
(def the-edn-serializer (EdnSerializer.))
(def the-edn-deserializer (EdnDeserializer. {}))
(deftype EdnSerde []
Serde
(configure [this map b])
(close [this])
(serializer [this] the-edn-serializer)
(deserializer [this] the-edn-deserializer))
(deftype JsonSerializer []
Serializer
(close [o])
(configure [this configs key?])
(serialize [this topic data]
(when data (-> (json/write-str data)
(.getBytes StandardCharsets/UTF_8)))))
(defrecord JsonDeserializer [opts]
Deserializer
(close [this])
(configure [this configs key?])
(deserialize [this topic data]
(when data
(-> (String. data StandardCharsets/UTF_8)
(json/read-str opts)))))
(def the-json-serializer (JsonSerializer.))
(def the-json-deserializer (JsonDeserializer. {}))
(deftype JsonSerde []
Serde
(configure [this map b])
(close [this])
(serializer [this] the-json-serializer)
(deserializer [this] the-json-deserializer))
(defmulti serdes identity)
allow using a plain instance instead of a keyword
(defmethod serdes :string [_] (Serdes/String))
(defmethod serdes :long [_] (Serdes/Long))
(defmethod serdes :bytes [_] (Serdes/Bytes))
(defmethod serdes :byte-buffer [_] (Serdes/ByteBuffer))
(defmethod serdes :byte-array [_] (Serdes/ByteArray))
(defmethod serdes :short [_] (Serdes/Short))
(defmethod serdes :int [_] (Serdes/Integer))
(defmethod serdes :double [_] (Serdes/Double))
(defmethod serdes :float [_] (Serdes/Float))
(defmethod serdes :nippy [_] (NippySerde.))
(defmethod serdes :edn [_] (EdnSerde.))
(defmethod serdes :json [_] (JsonSerde.))
|
b3ba1cd9448bc85b0d09d0c83bda4d0e2cb5345e0b24a0ab22961159165d6853 | wdebeaum/step | useless.lisp | ;;;;
;;;; W::useless
;;;;
(define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL
:words (
(W::useless
(wordfeats (W::morph (:FORMS (-LY))))
(SENSES
((meta-data :origin calo :entry-date 20031223 :change-date 20090731 :wn ("useless%3:00:00") :comments html-purchasing-corpus)
(LF-PARENT ONT::useless)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/useless.lisp | lisp |
W::useless
|
(define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL
:words (
(W::useless
(wordfeats (W::morph (:FORMS (-LY))))
(SENSES
((meta-data :origin calo :entry-date 20031223 :change-date 20090731 :wn ("useless%3:00:00") :comments html-purchasing-corpus)
(LF-PARENT ONT::useless)
)
)
)
))
|
26e5c4fece78fc7acbe238cbf44d69fae1fdace295c3dedb65d9ad280dcfaa56 | ogaml/ogaml | matrix3D.mli | Optimized operations on 3D ( 4x4 ) float matrices
exception Matrix3D_exception of string
Type of 4x4 matrices stored in a flat column major array
type t
Zero matrix
val zero : unit -> t
(* Identity matrix *)
val identity : unit -> t
(* Pretty-printer to string *)
val to_string : t -> string
(* Translation matrix *)
val translation : Vector3f.t -> t
(* Scaling matrix *)
val scaling : Vector3f.t -> t
(* Rotation matrix *)
val rotation : Vector3f.t -> float -> t
(* Product *)
val product : t -> t -> t
Transposition
val transpose : t -> t
(* Return a new, translated matrix *)
val translate : Vector3f.t -> t -> t
(* Return a new, scaled matrix *)
val scale : Vector3f.t -> t -> t
(* Return a new, rotated matrix *)
val rotate : Vector3f.t -> float -> t -> t
(* Vector right-product *)
val times : t -> ?perspective:bool -> Vector3f.t -> Vector3f.t
(* Rotation matrix from a quaternion *)
val from_quaternion : Quaternion.t -> t
(* Look-At view matrix *)
val look_at : from:Vector3f.t -> at:Vector3f.t -> up:Vector3f.t -> t
(* Inverse Look-At view matrix *)
val ilook_at : from:Vector3f.t -> at:Vector3f.t -> up:Vector3f.t -> t
(* Look_At view matrix from angles *)
val look_at_eulerian : from:Vector3f.t -> theta:float -> phi:float -> t
(* Inverse Look_At view matrix from angles *)
val ilook_at_eulerian : from:Vector3f.t -> theta:float -> phi:float -> t
Orthographic projection matrix
val orthographic : right:float -> left:float -> near:float -> far:float ->
top:float -> bottom:float -> t
(* Inverse orthographic projection matrix *)
val iorthographic : right:float -> left:float -> near:float -> far:float ->
top:float -> bottom:float -> t
(* Perspective projection matrix *)
val perspective : near:float -> far:float -> width:float -> height:float ->
fov:float -> t
(* Inverse perspective projection matrix *)
val iperspective : near:float -> far:float -> width:float -> height:float ->
fov:float -> t
(* Returns the matrix as a bigarray *)
val to_bigarray : t -> (float, Bigarray.float32_elt, Bigarray.c_layout) Bigarray.Array1.t
| null | https://raw.githubusercontent.com/ogaml/ogaml/5e74597521abf7ba2833a9247e55780eabfbab78/src/math/matrix3D.mli | ocaml | Identity matrix
Pretty-printer to string
Translation matrix
Scaling matrix
Rotation matrix
Product
Return a new, translated matrix
Return a new, scaled matrix
Return a new, rotated matrix
Vector right-product
Rotation matrix from a quaternion
Look-At view matrix
Inverse Look-At view matrix
Look_At view matrix from angles
Inverse Look_At view matrix from angles
Inverse orthographic projection matrix
Perspective projection matrix
Inverse perspective projection matrix
Returns the matrix as a bigarray | Optimized operations on 3D ( 4x4 ) float matrices
exception Matrix3D_exception of string
Type of 4x4 matrices stored in a flat column major array
type t
Zero matrix
val zero : unit -> t
val identity : unit -> t
val to_string : t -> string
val translation : Vector3f.t -> t
val scaling : Vector3f.t -> t
val rotation : Vector3f.t -> float -> t
val product : t -> t -> t
Transposition
val transpose : t -> t
val translate : Vector3f.t -> t -> t
val scale : Vector3f.t -> t -> t
val rotate : Vector3f.t -> float -> t -> t
val times : t -> ?perspective:bool -> Vector3f.t -> Vector3f.t
val from_quaternion : Quaternion.t -> t
val look_at : from:Vector3f.t -> at:Vector3f.t -> up:Vector3f.t -> t
val ilook_at : from:Vector3f.t -> at:Vector3f.t -> up:Vector3f.t -> t
val look_at_eulerian : from:Vector3f.t -> theta:float -> phi:float -> t
val ilook_at_eulerian : from:Vector3f.t -> theta:float -> phi:float -> t
Orthographic projection matrix
val orthographic : right:float -> left:float -> near:float -> far:float ->
top:float -> bottom:float -> t
val iorthographic : right:float -> left:float -> near:float -> far:float ->
top:float -> bottom:float -> t
val perspective : near:float -> far:float -> width:float -> height:float ->
fov:float -> t
val iperspective : near:float -> far:float -> width:float -> height:float ->
fov:float -> t
val to_bigarray : t -> (float, Bigarray.float32_elt, Bigarray.c_layout) Bigarray.Array1.t
|
af1552b00b19ddb8af650f04313e167065fc568f9df5897204a49c709db2eacd | fukamachi/lack | util.lisp | (in-package :cl-user)
(defpackage t.lack.util
(:use :cl
:prove
:lack.util
:lack.test))
(in-package :t.lack.util)
(plan 2)
(subtest "find-package-or-load"
(is (find-package-or-load "LACK")
(find-package :lack))
(is (find-package-or-load "hoge") nil))
(subtest "funcall-with-cb"
(let ((cb (lambda (res)
(rplacd (car (last res)) (list "(ok from cb)"))
res)))
;; cons
(let ((app (lambda (env)
(declare (ignore env))
'(200 (:content-type "text/plain") ("ok")))))
(is (funcall-with-cb app (generate-env "/") cb)
'(200 (:content-type "text/plain") ("ok" "(ok from cb)"))))
;; function
(let* ((app (lambda (env)
(declare (ignore env))
(lambda (responder)
(funcall responder '(200 (:content-type "text/plain") ("ok"))))))
(cb-res (funcall-with-cb app (generate-env "/") cb)))
(is-type cb-res 'function)
(let (res)
(funcall cb-res (lambda (r) (setf res r)))
(is res '(200 (:content-type "text/plain") ("ok" "(ok from cb)")))))
;; otherwise
(let ((app (lambda (env)
(declare (ignore env))
1)))
(is (funcall-with-cb app (generate-env "/") cb) 1))))
(finalize)
| null | https://raw.githubusercontent.com/fukamachi/lack/1f155216aeea36291b325c519f041e469262a399/t/util.lisp | lisp | cons
function
otherwise | (in-package :cl-user)
(defpackage t.lack.util
(:use :cl
:prove
:lack.util
:lack.test))
(in-package :t.lack.util)
(plan 2)
(subtest "find-package-or-load"
(is (find-package-or-load "LACK")
(find-package :lack))
(is (find-package-or-load "hoge") nil))
(subtest "funcall-with-cb"
(let ((cb (lambda (res)
(rplacd (car (last res)) (list "(ok from cb)"))
res)))
(let ((app (lambda (env)
(declare (ignore env))
'(200 (:content-type "text/plain") ("ok")))))
(is (funcall-with-cb app (generate-env "/") cb)
'(200 (:content-type "text/plain") ("ok" "(ok from cb)"))))
(let* ((app (lambda (env)
(declare (ignore env))
(lambda (responder)
(funcall responder '(200 (:content-type "text/plain") ("ok"))))))
(cb-res (funcall-with-cb app (generate-env "/") cb)))
(is-type cb-res 'function)
(let (res)
(funcall cb-res (lambda (r) (setf res r)))
(is res '(200 (:content-type "text/plain") ("ok" "(ok from cb)")))))
(let ((app (lambda (env)
(declare (ignore env))
1)))
(is (funcall-with-cb app (generate-env "/") cb) 1))))
(finalize)
|
3c9637601f9d2ae962a00e8fb55e3a7d35b6a61a91a29cb636383269cd92b1b8 | pegesund/clojureranker | test.clj | (ns clojureranker.test)
(defn rescore [score_list]
"this is only a test rescore function"
(map (fn [doc]
(let [old-score (first doc)
lucene-id (second doc)
solr-doc (nth doc 2)
new-score (if (= (.get solr-doc "id") "055357342X") 1 (rand))
]
[new-score lucene-id])
) score_list)
) | null | https://raw.githubusercontent.com/pegesund/clojureranker/693057db12dda391e5e6b1567cb21b20e98d6c01/src/clj/clojureranker/test.clj | clojure | (ns clojureranker.test)
(defn rescore [score_list]
"this is only a test rescore function"
(map (fn [doc]
(let [old-score (first doc)
lucene-id (second doc)
solr-doc (nth doc 2)
new-score (if (= (.get solr-doc "id") "055357342X") 1 (rand))
]
[new-score lucene-id])
) score_list)
) | |
a6fdda3d08aa6cee123eee0642383093438d61105ac0c93576c8c59343763c51 | clojure/core.typed | frozen_macros.clj | (ns clojure.core.typed.test.frozen-macros
(:require
this loads the type system , must go first
[clojure.core.typed.test.test-utils :as tu]
[clojure.core.typed :as t]
[clojure.core.typed.analyzer.jvm :as ana]
[clojure.core.typed.analyzer.jvm.passes.emit-form :refer [emit-form]]
[clojure.core.typed.checker.jvm.analyze-clj :as ana-clj]
[clojure.test :refer :all]))
(def tc-config
{:ns-meta {:core.typed {:experimental #{:custom-expansions}}}})
(defmacro tc-e [frm & opts]
`(tu/tc-e ~frm ~@opts ~@(apply concat tc-config)))
(defmacro tc-err [frm & opts]
`(tu/tc-err ~frm ~@opts ~@(apply concat tc-config)))
(defmacro is-tc-e [& body]
`(is (do (tc-e ~@body)
true)))
(defmacro is-tc-err [& body]
`(is (tc-err ~@body)))
(defmacro chk-frm
"Like tc-e but doesn't type check ns form"
[frm & {:as opts}]
`(binding [*ns* *ns*
*file* *file*]
(ns ~(gensym)
~@(some-> opts :ns-meta vector))
(t/check-form-info '~frm
:check-config '~(:check-config tc-config)
~@(apply concat (dissoc opts :ns-meta)))))
(comment
(deftest simulate-test
(is (-> (chk-frm 1)
:result
#{1}))
(is (-> (chk-frm [1])
:result
#{[1]}))
(is (-> (chk-frm [(do nil (inc 0))])
:result
#{[1]}))
(is (-> (chk-frm (do (inc 0)))
:result
#{1}))
(is (-> (chk-frm (do 5 (do 6 (inc 0))))
:result
#{1}))
(is (-> (chk-frm (do 1 2 [(inc 0)]))
:result
#{[1]}))
(is (-> (chk-frm (do (defmacro a [b] b)
(a (inc 0))))
:result
#{1}))
(is (-> (chk-frm (ns baz))
:result
nil?))
(is (-> (chk-frm (clojure.core.typed/ann-form 1 clojure.core.typed/Int))
:result
#{1}))
(is (-> (chk-frm (clojure.core.typed/ann-form (do 1) clojure.core.typed/Int))
:result
#{1}))
(is (-> (chk-frm (clojure.core.typed/ann-form (do (do 1)) clojure.core.typed/Int))
:result
#{1}))
(is (-> (chk-frm (clojure.core.typed/ann-form (let* [] (do 1)) clojure.core.typed/Int))
:result
#{1}))
(is (-> (chk-frm (clojure.core.typed/ann-form [1] '[clojure.core.typed/Int]))
:result
#{[1]}))
(is (-> (chk-frm (clojure.core.typed/tc-ignore))
:result
nil?))
(is (-> (chk-frm (clojure.core.typed/tc-ignore 1))
:result
#{1}))
(is (-> (chk-frm (clojure.core.typed/tc-ignore
(do 1)
(do 2)))
:result
#{2}))
(is (-> (chk-frm (clojure.core.typed/tc-ignore
(do (defmacro a [b] b)
(a (inc 0)))
(do (defmacro c [b] b)
(c (inc 0)))))
:result
#{1}))
)
(deftest ns-test
(is-tc-e (ns foo) nil)
(is-tc-err (ns foo) Symbol))
(deftest ann-form-test
(is-tc-e (ann-form 1 Integer))
(is-tc-e (ann-form (do (defmacro a [b] b)
(a (inc 0)))
Long))
blames - form form
FIXME add types in msg
(is-tc-err (ann-form 1 Integer) nil)
(is-tc-err (ann-form 1 nil)))
(deftest tc-ignore-test
(is-tc-e (tc-ignore))
(is-tc-e (tc-ignore #(/ nil nil)))
(is-tc-e (tc-ignore #(/ nil nil) #(/ nil nil)))
(is-tc-e (tc-ignore (do (defmacro a [b] b)
(a (inc 0)))))
(is-tc-e (tc-ignore (do (defmacro a [b] b)
(a (inc 0)))
(do (defmacro c [b] b)
(c (inc 0)))))
(is-tc-err (tc-ignore #(/ nil nil)) nil))
(deftest typed-fn-test
(is-tc-e (fn [a :- (U nil Number)]))
;; inherits column from outer expression
FIXME use entire form if single arity
(is-tc-err (fn [] :- Number))
;; exact column number
(is-tc-err (fn ([] :- Number))))
(deftest when-test
(is-tc-e (when 1 (inc 2)))
(is-tc-e (fn [a :- (U nil Number)]
(when a (inc a))))
(is-tc-e (fn [a :- (U nil Number)]
(when a (inc a))))
(is-tc-e (fn [a :- Number] :- Number
(when a (inc a))))
;; better error
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when a (inc a))))
;; 'else' expected error
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when a 1)))
;; 'then+else' expected error
FIXME duplicated error
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when a))))
(deftest when-not-test
(is-tc-e (fn [a :- (U nil Number)]
(when-not (not a) (inc a))))
(is-tc-e (fn [a :- (U nil Number)]
(when-not (not a) (inc a))))
(is-tc-e (fn [a :- Number] :- Number
(when-not (not a) (inc a))))
;; better error
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when-not (not a) (inc a))))
;; 'then' expected error
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when-not (not a) 1)))
;; 'then+else' expected error
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when-not (not a)))))
(deftest let-test
;; better error
(is-tc-err (let [a 1]) Number)
(is-tc-e (let [a 1]
(inc a)))
(is-tc-e #(let [a (throw (Exception.))]
(/ nil nil)))
(is-tc-e #(let [a 1
b 2]
(/ a b)))
(is-tc-e #(let [a (throw (Exception.))
b (/ nil nil)]))
(is-tc-err #(let [a (/ nil nil)
b (throw (Exception.))]
(/ a b)))
(is-tc-err #(let [a (/ nil nil)]
(inc a)))
(is-tc-err #(let [a 1]
(/ nil nil)))
;destructuring
(is-tc-e (let [{:keys [a]} {:a 1}]
(inc a)))
(is-tc-err (let [{:keys [a]} []]
(inc a)))
;; locals shadow vars
(is-tc-e (let [identity identity]
(identity 1))))
(deftest when-let-test
(is-tc-e (when-let [_ 1]
(inc 1)))
(is-tc-e (when-let [a 1]
(inc a)))
(is-tc-e (when-let [a (ann-form 1 (U nil Number))]
(inc a)))
(is-tc-err (when-let [a (ann-form 1 (U nil Number String))]
(inc a)))
(is-tc-err (when-let [a "a"]
(inc a)))
(is-tc-err (when-let [a (ann-form nil (U nil Number))]
(inc a))
Number)
)
(deftest if-let-test
(is-tc-e (if-let [_ 1]
(inc 1)))
(is-tc-e (if-let [a (ann-form 1 (U nil Number))]
(inc a)))
; improved error
(is-tc-err (if-let [a (ann-form 1 (U nil Number))]
(inc a))
Number)
(is-tc-e (if-let [{:keys [a]} {:a 1}]
(inc a)
1))
(is-tc-err (if-let [a (ann-form 1 (U nil Number String))]
(inc a)))
(is-tc-err (if-let [a "a"]
(inc a)))
)
(deftest assert-test
(binding [*assert* true]
(is-tc-e #(assert 1)))
(binding [*assert* true]
(is-tc-e #(assert 1 "foo")))
(binding [*assert* false]
(is-tc-e #(assert (/ nil nil) "foo")))
(binding [*assert* false]
(is-tc-e #(assert (/ nil nil "foo"))))
(is-tc-err #(assert (/ nil) "foo"))
(is-tc-err #(assert (/ nil nil) "foo"))
;; unreachable message
(is-tc-e #(assert "foo" (/ nil)))
(is-tc-err #(assert nil (/ nil))))
(deftest with-open-test
(is-tc-e #(with-open [r (java.io.FileInputStream. "some/dir")]
(.available r)))
;; better error
(is-tc-err #(with-open [r (java.io.FileInputStream. "some/dir")])
[-> Number]))
(deftest fn-test
(is-tc-e (clojure.core/fn [a]))
(is-tc-e (clojure.core/fn [a] a))
(is-tc-e (clojure.core/fn [a]
{:pre [(-> a identity)]}
a))
(is-tc-e (clojure.core/fn [a]
{:post [(symbol? %)]}
a))
;; approximates line number from outer form
(is-tc-err (clojure.core/fn [a])
[Number -> Number])
;; exact line number
(is-tc-err (clojure.core/fn ([a]))
[Number -> Number])
)
(deftest assoc-in-inline-test
(is-tc-e (assoc-in {} [:a] 1) '{:a Num})
;; improved msg
(is-tc-err (assoc-in {} [:a :b] 1) '{:a Num})
;; improved msg
(is-tc-err (assoc-in 'a [:a] 1))
;; improved msg
(is-tc-err (assoc-in {:a (ann-form 'a Sym)} [:a :b] 1))
(is-tc-err (assoc-in {:a {:b (ann-form 'a Sym)}} [:a :b :c] 1))
(is-tc-err (assoc-in {:a []} [:a :b] 1))
(is-tc-e (assoc-in {:a []} [:a 0] 1) '{:a '[Num]}))
(deftest for-test
(is (-> (chk-frm (clojure.core/for [a [1 2]] a))
:result
#{'(1 2)}))
(is-tc-e #(clojure.core/for [a [1 2]] a))
(is-tc-e #(clojure.core/for [a [1 2]] a) [-> (Seqable Number)])
(is-tc-e #(clojure.core/for [a [1 2]] a) [-> (ASeq Number)])
(is-tc-e #(clojure.core/for [a '(1 2)] (ann-form a Number)) [-> (Seqable Number)])
(is-tc-e #(clojure.core/for [a [1 2]] (ann-form a Number)) [-> (Seqable Number)])
FIXME improve error locality
(is-tc-err #(clojure.core/for [a [1 2]] a) [-> (Seqable Boolean)])
(is-tc-err #(clojure.core/for [a [1 2]] a) [-> Number])
(is-tc-err #(clojure.core/for [a [1 2]] a) [-> nil])
(is-tc-e #(clojure.core/for [a [1 2] b [2 3]] [a b]))
(is-tc-e #(clojure.core/for [a [1 2] b [2 3]] [a b]) [-> (Seq '[Num Num])])
FIXME use t / fn instead of fn *
TODO propagates expected type to body
#_
(is-tc-e #(clojure.core/for [a [1 2] b [2 3]] (fn* [c] (+ c a b)))
[-> (Seq [Num -> Num])])
FIXME example of bad type propagating to body
#_
(is-tc-err #(clojure.core/for [a [1 2] b [2 3]] (fn* [c] (+ c a b))) [-> (Seq [nil -> Num])])
)
(deftest get-in-test
(is (-> (chk-frm (get-in {:a {:b 1}} [:a :b]))
:result
#{1}))
(is-tc-e (get-in {:a {:b 1}} [:a :b])
Num)
; improved error
(is-tc-err (get-in {:a {:b 1}} [:a :b])
Sym)
FIXME need better messages for ' default '
(is-tc-err (get-in {:a {:b 1}} [:a :b] 1))
(is-tc-err (get-in {:a {:b 1}} [:a :b] 1)
Sym))
(deftest update-in-inline-test
(is-tc-e (update-in {:a {:b 1}} [:a :b] identity)
'{:a '{:b Num}})
(is-tc-e (update-in {:a {:b 1 :c 2}} [:a] dissoc :b)
'{:a '{:c Num}})
TODO
#_
(is-tc-e (let [m {:a {:b {:c 3}}}]
(update-in m [:a] update-in [:b] update-in [:c] str))
'{:a '{:b '{:c Str}}})
;; error is the eventual call to `inc` on nil
FIXME garbled error
(is-tc-err (let [m {:a {:b 1}}]
(update-in m [:a] update-in [:b] update-in [:c] inc)))
;; error is (inc "a") call
FIXME garbled error
(is-tc-err (let [m {:a {:b {:c "a"}}}]
(update-in m [:a] update-in [:b] update-in [:c] inc)))
(is-tc-e (update-in {:a {:b 1}} [:a :b] inc)
'{:a '{:b Num}})
(is-tc-e (update-in {:a {:b 1}} [:a :b] str)
'{:a '{:b Str}})
(is-tc-err (update-in {:a []} [:a :b] identity))
(is-tc-err (let [m {:a []}]
(update-in m [:a :b] identity))))
(deftest ->-test
(is-tc-e (-> identity
(map [1 2 3])))
(is-tc-err (-> identity
(map [1 2 3])
(ann-form (t/Seq t/Bool))))
(is-tc-err (-> identity
(map [1 2 3])
(ann-form (t/Seq t/Bool))
(map [2 3 4])))
(is-tc-err (-> identity
(map [1 2 3]))
(t/Seq t/Bool))
; FIXME big error
(is-tc-err (-> identity
(map [1 2 3])
(map [4 5 6])
(map [7 8 9]))
(t/Seq t/Bool))
; FIXME line number
(is-tc-err (-> identity
(map [1 2 3])
vec)
(t/Seq t/Bool)))
(deftest proxy-test
(is-tc-e
(proxy [Object] []
(toString [] "a")))
;TODO actually check methods
#_
(is-tc-err
(proxy [Object] []
(toString [] 1)))
(is-tc-e
(proxy [Object] []
(toString [] "a"))
Object)
(is (tc-e
(proxy [Object] [])))
TODO
#_
(is (tc-e
(proxy [Object clojure.lang.ISeq] [])))
(is-tc-e
(proxy [Object] [])
Object)
(is-tc-err
(proxy [Object] []
(toString [] "a"))
nil)
)
(comment
(class
(proxy [clojure.lang.ASeq clojure.lang.ISeq] []
(seq [] nil)
(toString [] "a")))
(class
(proxy [clojure.lang.ISeq] []
(seq [] nil)
(first [] 1)
(toString [] "a")))
)
(comment
(deftest map-test
(is-tc-e (map '(1 2 3) [1 2 3]))
(is-tc-e (map identity [1 2 3]))
(is-tc-e (map identity (map identity [1 2 3])))
(is-tc-e (map + [1 2 3] [2 3 4]))
(is-tc-e (map identity [1 2 3])
(t/Seq t/Num))
(is-tc-e (map identity [1 2 3])
(t/HSeq [Num Num Num]))
(is-tc-e (map identity [])
(t/Seq Nothing))
(is-tc-e (map identity [1 2 3])
(t/Seq t/Bool))
;; FIXME better column number
(is-tc-err (map identity 'a))
(is-tc-err (map identity identity))
;; FIXME line number + source ns
(is-tc-err (map))
; vvvvvvvvvvvvvv
;; (map identity ('a asdlfsdf
;; ;lsdl;fsdlf)
;; ;^^^^^^^^^^^^^^
;; :a :b)
; ;vv
;; (map identity 'a
;; ;^^
;; :a :b)
(is-tc-e (map identity)
(t/Transducer t/Num t/Num))
(is-tc-e (map boolean)
(t/Transducer t/Num t/Bool))
(is-tc-err (map boolean [1 2 3])
(t/Transducer t/Bool t/Num))
;; FIXME better blame-form needed
;; can we check `expected` earlier? before we check arguments?
(is-tc-err (map boolean [1 2 3] [2 3 4])
(t/Transducer t/Bool t/Num))
FIXME this goes crazy because it inlines to ( map ( ann - form ... t / Bool ) )
FIXME need to override form for inlined inner map
(is-tc-err (map map)
(t/Transducer t/Bool t/Num))
;; FIXME better blame-form needed
(is-tc-err (map boolean)
(t/Transducer t/Bool t/Num))
(is-tc-err (map (fn [a] (boolean a)))
(t/Transducer t/Bool t/Num))
(is-tc-err (map identity))
(is-tc-err (map (fn [a :- t/Any] a)))
)
(comment
; andmap : (All (x) ((x -> y) (List x) -> y))
(lambda (a b)
(when (andmap number? (list a b))
(+ a b)))
=>
(lambda (a b)
(when (and (number? a)
(number? b))
(+ a b)))
)
(deftest every?-test
(is-tc-e (every? identity [1 2 3]))
(is-tc-e (core/fn [a]
(when (number? (first [a]))
(inc a))))
(is-tc-e (core/fn [a]
(when (number? (first [a]))
(inc a))))
(is-tc-err (core/fn [a]
(when (number? (first [0 a]))
(inc a))))
(is-tc-e (core/fn [a]
(if ((complement number?) (first [a]))
nil
(inc a))))
(is-tc-e (core/fn [a]
(when (number? (first [a]))
(inc a))))
(is-tc-e (core/fn [a]
(when (number? (first (seq [a])))
(inc a))))
(is-tc-e (core/fn [a]
(when ((fn* [& args] (number? (first args))) a)
(inc a))))
(is-tc-e (core/fn [a]
(when ((fn* [& args] (apply number? args)) a)
(inc a))))
(is-tc-e (core/fn [a]
(when-not ((fn* [& args] (not (apply number? args))) a)
(inc a))))
(is-tc-e (core/fn [a]
(if ((complement (fn* [& args] (apply number? args))) a)
nil
(inc a))))
(is-tc-e (core/fn [a]
(if (if (apply number? [a]) false true)
nil
(inc a))))
(is-tc-e (core/fn [a]
(when (apply number? [a])
(inc a))))
(is-tc-e (core/fn [a b]
{:pre [(every? number? [a b])]}
(+ a b)))
(is-tc-e (fn [a b]
{:pre [(every? number? [a b])]}
(+ a b)))
(is-tc-e (fn [a b]
{:pre [(not-any? (complement number?) [a b])]}
(+ a b)))
(is-tc-e (fn [a]
{:pre [(some number? [a])]}
(inc a)))
)
(deftest juxt-test
(is-tc-e (fn [a]
{:pre [(every? identity ((juxt number? integer?) a))]}
(inc a)))
(is-tc-e (fn [a]
{:pre [(first (nthrest [(number? a) (integer? a)] 0))]}
(inc a)))
(is-tc-e (fn [a]
{:pre [(first [(number? a) (integer? a)])]}
(inc a)))
(is-tc-e (fn [a]
{:pre [(first ((juxt number?) a))]}
(inc a)))
(is-tc-e (fn [a]
{:pre [(first ((juxt number? identity #(str %)) a))]}
(inc a)))
)
(comment
(((fn []
map))
identity
[1 2 3])
;=>
(map
identity
[1 2 3])
((fn [f]
(f 1))
(fn [d]
(inc d)))
;=>
((let [f (fn [d]
(inc d))]
(fn [d]
(inc d)))
1)
;=>
((let [f (fn [d]
(inc d))]
(let [d 1]
inc))
1)
)
(deftest symbolic-fnapp-test
(is-tc-e ((fn [f]
(f 1))
(fn [d]
(inc d)))))
(deftest beta-reduce-test
(is-tc-e ((fn* [a] a) :a) ':a)
(is-tc-err ((fn* [a] a) :a) ':b)
(is-tc-e ((fn* [a] ((fn* [a] ((fn* [a] a) a)) a)) :a) ':a)
TODO preserve original form in error msg somewhere ? or indicate
;; it's been symbolically expanded
(is-tc-err ((fn* [a] ((fn* [a] ((fn* [a] a) a)) a)) :a) ':b)
(is-tc-e (:a {:a :b}) ':b)
(is-tc-e ((let* [] :a) {:a :b}) ':b)
(is-tc-e ((let* [] (fn* [a] (:a a))) {:a :b}) ':b)
(is-tc-e (((fn* [a] a) :a)
{:a :b})
':b)
(is-tc-e (((fn* [a] a) :a)
((fn* [a] a) {:a :b}))
':b)
(is-tc-e (((fn* [f] (f :a)) (fn* [a] a)) {:a :b}) ':b)
(is-tc-e (((fn* [f b] (f b)) (fn* [c] c) :a) {:a :b}) ':b)
(is-tc-e (((fn* [f a] (f a)) (fn* [a] a) :a) {:a :b}) ':b)
(is-tc-e (((fn* [f a] (f a)) (fn* [a] a) :a) ((fn* [a] a) {:a :b})) ':b)
(is-tc-e (((fn* [f a] (f a)) identity :a) ((fn* [a] a) {:a :b})) ':b)
(is-tc-e (((fn* [f a] (f a)) (fn* [a] a) :a)
((fn* [a] a) {:a :b}))
':b)
(is-tc-e [(((fn* [f a] (f a)) (fn* [a] a) :a)
((fn* [a] a) {:a :b}))
(((fn* [f a] (f a)) (fn* [a] a) :a)
((fn* [a] a) {:a :b}))
(((fn* [f a] (f a)) (fn* [a] a) :a)
((fn* [a] a) {:a :b}))
(((fn* [f a] (f a)) (fn* [a] a) :a)
((fn* [a] a) {:a :b}))]
(Seqable ':b))
; real y combinator, all should hit the beta limit
(is-tc-err (fn* ([] ((fn* [f] ((fn* [x] (f (x x))) (fn* [y] (f (y y))))) inc))))
(is-tc-err (fn* ([] (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x)))))))))
(is-tc-err (fn* ([] (inc (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x))))))))))
(is-tc-err (fn* ([] (inc (inc (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x)))))))))))
(is-tc-err (fn* ([] (inc (inc (inc (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x))))))))))))
(is-tc-err (fn* ([] (inc (inc (inc (inc (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x)))))))))))))
(is-tc-err (fn* ([] (inc (inc (inc (inc (inc (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x))))))))))))))
;variadic fn
(is-tc-e ((fn* [& a] (map inc a)) 1))
(is-tc-err ((fn* [& a] (map inc a)) :a))
(is-tc-e ((fn* [a] (map inc (seq [a]))) 1))
(is-tc-e ((fn* [a z] (map inc (seq [a z]))) 1 2))
(is-tc-e ((fn* [_ z] (inc z)) nil 1))
(is-tc-e ((fn* [a z] (inc z)) nil 1))
(is-tc-e ((fn* [a z] (+ a z)) 2 1))
TODO keyword invocations
#_(is-tc-e ((:a {:a (fn [a] a)}) :b) ':b)
;apply
(is-tc-e (apply inc [2])
Int)
(is-tc-e (apply inc (seq [2])) Int)
(is-tc-e (apply inc [(second (first {:a 2}))]) Int)
(is-tc-e (apply map (seq [identity [1]]))
(Seqable Num))
(is-tc-e (apply map [identity])
(Transducer Num Num))
FIXME error msg
(is-tc-err (apply map [identity])
(Transducer Num Bool))
FIXME error msg
(is-tc-err (apply map [identity]))
;comp
(is-tc-e ((comp inc dec) 1) Num)
(is-tc-e ((comp inc :a) {:a 1}) Num)
(is-tc-e ((comp identity :a) {:a 1}) Num)
(is-tc-e ((comp identity :a) {:a 1}) '1)
(is-tc-e ((comp inc (constantly nil)) 1))
FIXME
#_
(is-tc-e (sequence (comp (map inc) (map dec)) [1]))
(is-tc-e ((fn* [& args]
(inc (first args)))
1))
(is-tc-e ((core/fn [& args]
(inc (first args)))
1))
(is-tc-err ((core/fn [& args]
(inc (first args)))
true))
(is-tc-err ((core/fn [& args]
(inc (first args)))
true))
;;TODO t/fn should "infer" its rest arg
#_(is-tc-e ((fn [& args]
(inc (first args)))
1))
TODO play with the map transducer expander , use fn instead of fn *
;; and figure out how to play nicely with its mexpansion
(is-tc-e (comp (map inc) (map dec))
(Transducer Num Num))
;; horrible error msg
(is-tc-err (comp (map inc) (map dec))
(Transducer Num Bool))
TODO constantly
; ensure we correctly reduce
; ((ann-form (fn [a] body)
; [A :-> B])
; v)
; =>
; (ann-form
; (expected-as e
( - form body[(ann - form v ( If e ( DomOf ( OptsOf e ) 0 : arity 2 ) ^:infer Any))/a ]
( If e ( RngOf ( TypeOf e ) : arity 2 ) ^:infer Any ) ) )
; [A :-> B])
; =>
; (ann-form body[(ann-form v A)/a]
; B)
(is-tc-e ((ann-form
(fn* [i] (inc i))
[Int :-> Int])
1))
(is-tc-e ((ann-form
(clojure.core/fn [i] (inc i))
[Int :-> Int])
1))
(is-tc-e ((ann-form
(clojure.core/fn [i] (inc i))
[Int :-> Bool])
1))
(is-tc-e ((ann-form
(clojure.core/fn [i] (inc i))
[Bool :-> Int])
1))
;; FIXME t/fn defaults to Any arguments
(is-tc-e ((t/fn [i :- Int] (inc i))
1))
(is-tc-e ((ann-form
(t/fn [i :- Int] :- Int (inc i))
[Int :-> Int])
1))
(is-tc-e ((ann-form
(ann-form
inc
[Int :-> Int])
[Int :-> Int])
1))
(is-tc-e ((ann-form
(ann-form
(fn* [i] (boolean i))
[Num :-> Bool])
[Int :-> Bool])
1))
(is-tc-e (ann-form
(ann-form
(fn* [i] (boolean i))
[Num :-> Bool])
[Int :-> Bool]))
(is-tc-err (ann-form
(ann-form
(fn* [i] (boolean i))
[Int :-> Bool])
[Num :-> Bool]))
TODO subst object in return type of beta - reduction
;reduce
(is-tc-e (reduce (fn* [a e] (conj a e))
[]
[1 2 3]))
fixpoint
#_
(is-tc-e (fixpoint
(fn* [c e] (concat c [(inc e)]))
{:subst-var x
:init [(Seq Nothing) Int :-> ^::t/infer Any]
:query (All [x] [[x Int :-> x] :-> x])
:iterate [x Int :-> ^::t/infer Any]
}))
)
(comment
(defn timet
[expr]
(let [start (. System (nanoTime))
ret (expr)]
(/ (double (- (. System (nanoTime)) start)) 1000000.0)))
(clojure.pprint/pprint
(sort-by val
(into {} (map (fn [v]
[v (timet #(clojure.test/test-vars [v]))]))
(filter (every-pred var? (comp :test meta)) (vals (ns-publics *ns*)))))
)
; no custom expansion
'([#'clojure.core.typed.test.frozen-macros/tc-ignore-test 171.394456]
[#'clojure.core.typed.test.frozen-macros/with-open-test 181.161775]
[#'clojure.core.typed.test.frozen-macros/typed-fn-test 233.531726]
[#'clojure.core.typed.test.frozen-macros/ann-form-test 235.352863]
[#'clojure.core.typed.test.frozen-macros/ns-test 240.44296]
[#'clojure.core.typed.test.frozen-macros/get-in-test 341.253694]
[#'clojure.core.typed.test.frozen-macros/fn-test 495.774091]
[#'clojure.core.typed.test.frozen-macros/when-not-test 542.922632]
[#'clojure.core.typed.test.frozen-macros/when-test 546.166276]
[#'clojure.core.typed.test.frozen-macros/when-let-test 609.879237]
[#'clojure.core.typed.test.frozen-macros/if-let-test 631.63356]
[#'clojure.core.typed.test.frozen-macros/assoc-in-inline-test 676.056304]
[#'clojure.core.typed.test.frozen-macros/assert-test 694.094945]
[#'clojure.core.typed.test.frozen-macros/update-in-inline-test 765.674776]
[#'clojure.core.typed.test.frozen-macros/let-test 992.088318]
[#'clojure.core.typed.test.frozen-macros/for-test 5778.336702])
; yes custom expansion
'([#'clojure.core.typed.test.frozen-macros/ns-test 182.167286]
[#'clojure.core.typed.test.frozen-macros/tc-ignore-test 188.358344]
[#'clojure.core.typed.test.frozen-macros/with-open-test 221.02634]
[#'clojure.core.typed.test.frozen-macros/ann-form-test 274.636581]
[#'clojure.core.typed.test.frozen-macros/typed-fn-test 330.160597]
[#'clojure.core.typed.test.frozen-macros/get-in-test 388.410054]
[#'clojure.core.typed.test.frozen-macros/fn-test 682.037165]
[#'clojure.core.typed.test.frozen-macros/assert-test 774.38307]
[#'clojure.core.typed.test.frozen-macros/if-let-test 793.200128]
[#'clojure.core.typed.test.frozen-macros/when-not-test 807.979324]
[#'clojure.core.typed.test.frozen-macros/when-let-test 816.350961]
[#'clojure.core.typed.test.frozen-macros/for-test 819.305905]
[#'clojure.core.typed.test.frozen-macros/assoc-in-inline-test 820.942907]
[#'clojure.core.typed.test.frozen-macros/when-test 865.453885]
[#'clojure.core.typed.test.frozen-macros/let-test 1221.219269]
[#'clojure.core.typed.test.frozen-macros/update-in-inline-test 1641.337323])
)
)
)
| null | https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/test/clojure/core/typed/test/frozen_macros.clj | clojure | inherits column from outer expression
exact column number
better error
'else' expected error
'then+else' expected error
better error
'then' expected error
'then+else' expected error
better error
destructuring
locals shadow vars
improved error
unreachable message
better error
approximates line number from outer form
exact line number
improved msg
improved msg
improved msg
improved error
error is the eventual call to `inc` on nil
error is (inc "a") call
FIXME big error
FIXME line number
TODO actually check methods
FIXME better column number
FIXME line number + source ns
vvvvvvvvvvvvvv
(map identity ('a asdlfsdf
;lsdl;fsdlf)
;^^^^^^^^^^^^^^
:a :b)
;vv
(map identity 'a
;^^
:a :b)
FIXME better blame-form needed
can we check `expected` earlier? before we check arguments?
FIXME better blame-form needed
andmap : (All (x) ((x -> y) (List x) -> y))
=>
=>
=>
it's been symbolically expanded
real y combinator, all should hit the beta limit
variadic fn
apply
comp
TODO t/fn should "infer" its rest arg
and figure out how to play nicely with its mexpansion
horrible error msg
ensure we correctly reduce
((ann-form (fn [a] body)
[A :-> B])
v)
=>
(ann-form
(expected-as e
[A :-> B])
=>
(ann-form body[(ann-form v A)/a]
B)
FIXME t/fn defaults to Any arguments
reduce
no custom expansion
yes custom expansion | (ns clojure.core.typed.test.frozen-macros
(:require
this loads the type system , must go first
[clojure.core.typed.test.test-utils :as tu]
[clojure.core.typed :as t]
[clojure.core.typed.analyzer.jvm :as ana]
[clojure.core.typed.analyzer.jvm.passes.emit-form :refer [emit-form]]
[clojure.core.typed.checker.jvm.analyze-clj :as ana-clj]
[clojure.test :refer :all]))
(def tc-config
{:ns-meta {:core.typed {:experimental #{:custom-expansions}}}})
(defmacro tc-e [frm & opts]
`(tu/tc-e ~frm ~@opts ~@(apply concat tc-config)))
(defmacro tc-err [frm & opts]
`(tu/tc-err ~frm ~@opts ~@(apply concat tc-config)))
(defmacro is-tc-e [& body]
`(is (do (tc-e ~@body)
true)))
(defmacro is-tc-err [& body]
`(is (tc-err ~@body)))
(defmacro chk-frm
"Like tc-e but doesn't type check ns form"
[frm & {:as opts}]
`(binding [*ns* *ns*
*file* *file*]
(ns ~(gensym)
~@(some-> opts :ns-meta vector))
(t/check-form-info '~frm
:check-config '~(:check-config tc-config)
~@(apply concat (dissoc opts :ns-meta)))))
(comment
(deftest simulate-test
(is (-> (chk-frm 1)
:result
#{1}))
(is (-> (chk-frm [1])
:result
#{[1]}))
(is (-> (chk-frm [(do nil (inc 0))])
:result
#{[1]}))
(is (-> (chk-frm (do (inc 0)))
:result
#{1}))
(is (-> (chk-frm (do 5 (do 6 (inc 0))))
:result
#{1}))
(is (-> (chk-frm (do 1 2 [(inc 0)]))
:result
#{[1]}))
(is (-> (chk-frm (do (defmacro a [b] b)
(a (inc 0))))
:result
#{1}))
(is (-> (chk-frm (ns baz))
:result
nil?))
(is (-> (chk-frm (clojure.core.typed/ann-form 1 clojure.core.typed/Int))
:result
#{1}))
(is (-> (chk-frm (clojure.core.typed/ann-form (do 1) clojure.core.typed/Int))
:result
#{1}))
(is (-> (chk-frm (clojure.core.typed/ann-form (do (do 1)) clojure.core.typed/Int))
:result
#{1}))
(is (-> (chk-frm (clojure.core.typed/ann-form (let* [] (do 1)) clojure.core.typed/Int))
:result
#{1}))
(is (-> (chk-frm (clojure.core.typed/ann-form [1] '[clojure.core.typed/Int]))
:result
#{[1]}))
(is (-> (chk-frm (clojure.core.typed/tc-ignore))
:result
nil?))
(is (-> (chk-frm (clojure.core.typed/tc-ignore 1))
:result
#{1}))
(is (-> (chk-frm (clojure.core.typed/tc-ignore
(do 1)
(do 2)))
:result
#{2}))
(is (-> (chk-frm (clojure.core.typed/tc-ignore
(do (defmacro a [b] b)
(a (inc 0)))
(do (defmacro c [b] b)
(c (inc 0)))))
:result
#{1}))
)
(deftest ns-test
(is-tc-e (ns foo) nil)
(is-tc-err (ns foo) Symbol))
(deftest ann-form-test
(is-tc-e (ann-form 1 Integer))
(is-tc-e (ann-form (do (defmacro a [b] b)
(a (inc 0)))
Long))
blames - form form
FIXME add types in msg
(is-tc-err (ann-form 1 Integer) nil)
(is-tc-err (ann-form 1 nil)))
(deftest tc-ignore-test
(is-tc-e (tc-ignore))
(is-tc-e (tc-ignore #(/ nil nil)))
(is-tc-e (tc-ignore #(/ nil nil) #(/ nil nil)))
(is-tc-e (tc-ignore (do (defmacro a [b] b)
(a (inc 0)))))
(is-tc-e (tc-ignore (do (defmacro a [b] b)
(a (inc 0)))
(do (defmacro c [b] b)
(c (inc 0)))))
(is-tc-err (tc-ignore #(/ nil nil)) nil))
(deftest typed-fn-test
(is-tc-e (fn [a :- (U nil Number)]))
FIXME use entire form if single arity
(is-tc-err (fn [] :- Number))
(is-tc-err (fn ([] :- Number))))
(deftest when-test
(is-tc-e (when 1 (inc 2)))
(is-tc-e (fn [a :- (U nil Number)]
(when a (inc a))))
(is-tc-e (fn [a :- (U nil Number)]
(when a (inc a))))
(is-tc-e (fn [a :- Number] :- Number
(when a (inc a))))
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when a (inc a))))
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when a 1)))
FIXME duplicated error
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when a))))
(deftest when-not-test
(is-tc-e (fn [a :- (U nil Number)]
(when-not (not a) (inc a))))
(is-tc-e (fn [a :- (U nil Number)]
(when-not (not a) (inc a))))
(is-tc-e (fn [a :- Number] :- Number
(when-not (not a) (inc a))))
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when-not (not a) (inc a))))
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when-not (not a) 1)))
(is-tc-err (fn [a :- (U nil Number)] :- Number,
(when-not (not a)))))
(deftest let-test
(is-tc-err (let [a 1]) Number)
(is-tc-e (let [a 1]
(inc a)))
(is-tc-e #(let [a (throw (Exception.))]
(/ nil nil)))
(is-tc-e #(let [a 1
b 2]
(/ a b)))
(is-tc-e #(let [a (throw (Exception.))
b (/ nil nil)]))
(is-tc-err #(let [a (/ nil nil)
b (throw (Exception.))]
(/ a b)))
(is-tc-err #(let [a (/ nil nil)]
(inc a)))
(is-tc-err #(let [a 1]
(/ nil nil)))
(is-tc-e (let [{:keys [a]} {:a 1}]
(inc a)))
(is-tc-err (let [{:keys [a]} []]
(inc a)))
(is-tc-e (let [identity identity]
(identity 1))))
(deftest when-let-test
(is-tc-e (when-let [_ 1]
(inc 1)))
(is-tc-e (when-let [a 1]
(inc a)))
(is-tc-e (when-let [a (ann-form 1 (U nil Number))]
(inc a)))
(is-tc-err (when-let [a (ann-form 1 (U nil Number String))]
(inc a)))
(is-tc-err (when-let [a "a"]
(inc a)))
(is-tc-err (when-let [a (ann-form nil (U nil Number))]
(inc a))
Number)
)
(deftest if-let-test
(is-tc-e (if-let [_ 1]
(inc 1)))
(is-tc-e (if-let [a (ann-form 1 (U nil Number))]
(inc a)))
(is-tc-err (if-let [a (ann-form 1 (U nil Number))]
(inc a))
Number)
(is-tc-e (if-let [{:keys [a]} {:a 1}]
(inc a)
1))
(is-tc-err (if-let [a (ann-form 1 (U nil Number String))]
(inc a)))
(is-tc-err (if-let [a "a"]
(inc a)))
)
(deftest assert-test
(binding [*assert* true]
(is-tc-e #(assert 1)))
(binding [*assert* true]
(is-tc-e #(assert 1 "foo")))
(binding [*assert* false]
(is-tc-e #(assert (/ nil nil) "foo")))
(binding [*assert* false]
(is-tc-e #(assert (/ nil nil "foo"))))
(is-tc-err #(assert (/ nil) "foo"))
(is-tc-err #(assert (/ nil nil) "foo"))
(is-tc-e #(assert "foo" (/ nil)))
(is-tc-err #(assert nil (/ nil))))
(deftest with-open-test
(is-tc-e #(with-open [r (java.io.FileInputStream. "some/dir")]
(.available r)))
(is-tc-err #(with-open [r (java.io.FileInputStream. "some/dir")])
[-> Number]))
(deftest fn-test
(is-tc-e (clojure.core/fn [a]))
(is-tc-e (clojure.core/fn [a] a))
(is-tc-e (clojure.core/fn [a]
{:pre [(-> a identity)]}
a))
(is-tc-e (clojure.core/fn [a]
{:post [(symbol? %)]}
a))
(is-tc-err (clojure.core/fn [a])
[Number -> Number])
(is-tc-err (clojure.core/fn ([a]))
[Number -> Number])
)
(deftest assoc-in-inline-test
(is-tc-e (assoc-in {} [:a] 1) '{:a Num})
(is-tc-err (assoc-in {} [:a :b] 1) '{:a Num})
(is-tc-err (assoc-in 'a [:a] 1))
(is-tc-err (assoc-in {:a (ann-form 'a Sym)} [:a :b] 1))
(is-tc-err (assoc-in {:a {:b (ann-form 'a Sym)}} [:a :b :c] 1))
(is-tc-err (assoc-in {:a []} [:a :b] 1))
(is-tc-e (assoc-in {:a []} [:a 0] 1) '{:a '[Num]}))
(deftest for-test
(is (-> (chk-frm (clojure.core/for [a [1 2]] a))
:result
#{'(1 2)}))
(is-tc-e #(clojure.core/for [a [1 2]] a))
(is-tc-e #(clojure.core/for [a [1 2]] a) [-> (Seqable Number)])
(is-tc-e #(clojure.core/for [a [1 2]] a) [-> (ASeq Number)])
(is-tc-e #(clojure.core/for [a '(1 2)] (ann-form a Number)) [-> (Seqable Number)])
(is-tc-e #(clojure.core/for [a [1 2]] (ann-form a Number)) [-> (Seqable Number)])
FIXME improve error locality
(is-tc-err #(clojure.core/for [a [1 2]] a) [-> (Seqable Boolean)])
(is-tc-err #(clojure.core/for [a [1 2]] a) [-> Number])
(is-tc-err #(clojure.core/for [a [1 2]] a) [-> nil])
(is-tc-e #(clojure.core/for [a [1 2] b [2 3]] [a b]))
(is-tc-e #(clojure.core/for [a [1 2] b [2 3]] [a b]) [-> (Seq '[Num Num])])
FIXME use t / fn instead of fn *
TODO propagates expected type to body
#_
(is-tc-e #(clojure.core/for [a [1 2] b [2 3]] (fn* [c] (+ c a b)))
[-> (Seq [Num -> Num])])
FIXME example of bad type propagating to body
#_
(is-tc-err #(clojure.core/for [a [1 2] b [2 3]] (fn* [c] (+ c a b))) [-> (Seq [nil -> Num])])
)
(deftest get-in-test
(is (-> (chk-frm (get-in {:a {:b 1}} [:a :b]))
:result
#{1}))
(is-tc-e (get-in {:a {:b 1}} [:a :b])
Num)
(is-tc-err (get-in {:a {:b 1}} [:a :b])
Sym)
FIXME need better messages for ' default '
(is-tc-err (get-in {:a {:b 1}} [:a :b] 1))
(is-tc-err (get-in {:a {:b 1}} [:a :b] 1)
Sym))
(deftest update-in-inline-test
(is-tc-e (update-in {:a {:b 1}} [:a :b] identity)
'{:a '{:b Num}})
(is-tc-e (update-in {:a {:b 1 :c 2}} [:a] dissoc :b)
'{:a '{:c Num}})
TODO
#_
(is-tc-e (let [m {:a {:b {:c 3}}}]
(update-in m [:a] update-in [:b] update-in [:c] str))
'{:a '{:b '{:c Str}}})
FIXME garbled error
(is-tc-err (let [m {:a {:b 1}}]
(update-in m [:a] update-in [:b] update-in [:c] inc)))
FIXME garbled error
(is-tc-err (let [m {:a {:b {:c "a"}}}]
(update-in m [:a] update-in [:b] update-in [:c] inc)))
(is-tc-e (update-in {:a {:b 1}} [:a :b] inc)
'{:a '{:b Num}})
(is-tc-e (update-in {:a {:b 1}} [:a :b] str)
'{:a '{:b Str}})
(is-tc-err (update-in {:a []} [:a :b] identity))
(is-tc-err (let [m {:a []}]
(update-in m [:a :b] identity))))
(deftest ->-test
(is-tc-e (-> identity
(map [1 2 3])))
(is-tc-err (-> identity
(map [1 2 3])
(ann-form (t/Seq t/Bool))))
(is-tc-err (-> identity
(map [1 2 3])
(ann-form (t/Seq t/Bool))
(map [2 3 4])))
(is-tc-err (-> identity
(map [1 2 3]))
(t/Seq t/Bool))
(is-tc-err (-> identity
(map [1 2 3])
(map [4 5 6])
(map [7 8 9]))
(t/Seq t/Bool))
(is-tc-err (-> identity
(map [1 2 3])
vec)
(t/Seq t/Bool)))
(deftest proxy-test
(is-tc-e
(proxy [Object] []
(toString [] "a")))
#_
(is-tc-err
(proxy [Object] []
(toString [] 1)))
(is-tc-e
(proxy [Object] []
(toString [] "a"))
Object)
(is (tc-e
(proxy [Object] [])))
TODO
#_
(is (tc-e
(proxy [Object clojure.lang.ISeq] [])))
(is-tc-e
(proxy [Object] [])
Object)
(is-tc-err
(proxy [Object] []
(toString [] "a"))
nil)
)
(comment
(class
(proxy [clojure.lang.ASeq clojure.lang.ISeq] []
(seq [] nil)
(toString [] "a")))
(class
(proxy [clojure.lang.ISeq] []
(seq [] nil)
(first [] 1)
(toString [] "a")))
)
(comment
(deftest map-test
(is-tc-e (map '(1 2 3) [1 2 3]))
(is-tc-e (map identity [1 2 3]))
(is-tc-e (map identity (map identity [1 2 3])))
(is-tc-e (map + [1 2 3] [2 3 4]))
(is-tc-e (map identity [1 2 3])
(t/Seq t/Num))
(is-tc-e (map identity [1 2 3])
(t/HSeq [Num Num Num]))
(is-tc-e (map identity [])
(t/Seq Nothing))
(is-tc-e (map identity [1 2 3])
(t/Seq t/Bool))
(is-tc-err (map identity 'a))
(is-tc-err (map identity identity))
(is-tc-err (map))
(is-tc-e (map identity)
(t/Transducer t/Num t/Num))
(is-tc-e (map boolean)
(t/Transducer t/Num t/Bool))
(is-tc-err (map boolean [1 2 3])
(t/Transducer t/Bool t/Num))
(is-tc-err (map boolean [1 2 3] [2 3 4])
(t/Transducer t/Bool t/Num))
FIXME this goes crazy because it inlines to ( map ( ann - form ... t / Bool ) )
FIXME need to override form for inlined inner map
(is-tc-err (map map)
(t/Transducer t/Bool t/Num))
(is-tc-err (map boolean)
(t/Transducer t/Bool t/Num))
(is-tc-err (map (fn [a] (boolean a)))
(t/Transducer t/Bool t/Num))
(is-tc-err (map identity))
(is-tc-err (map (fn [a :- t/Any] a)))
)
(comment
(lambda (a b)
(when (andmap number? (list a b))
(+ a b)))
=>
(lambda (a b)
(when (and (number? a)
(number? b))
(+ a b)))
)
(deftest every?-test
(is-tc-e (every? identity [1 2 3]))
(is-tc-e (core/fn [a]
(when (number? (first [a]))
(inc a))))
(is-tc-e (core/fn [a]
(when (number? (first [a]))
(inc a))))
(is-tc-err (core/fn [a]
(when (number? (first [0 a]))
(inc a))))
(is-tc-e (core/fn [a]
(if ((complement number?) (first [a]))
nil
(inc a))))
(is-tc-e (core/fn [a]
(when (number? (first [a]))
(inc a))))
(is-tc-e (core/fn [a]
(when (number? (first (seq [a])))
(inc a))))
(is-tc-e (core/fn [a]
(when ((fn* [& args] (number? (first args))) a)
(inc a))))
(is-tc-e (core/fn [a]
(when ((fn* [& args] (apply number? args)) a)
(inc a))))
(is-tc-e (core/fn [a]
(when-not ((fn* [& args] (not (apply number? args))) a)
(inc a))))
(is-tc-e (core/fn [a]
(if ((complement (fn* [& args] (apply number? args))) a)
nil
(inc a))))
(is-tc-e (core/fn [a]
(if (if (apply number? [a]) false true)
nil
(inc a))))
(is-tc-e (core/fn [a]
(when (apply number? [a])
(inc a))))
(is-tc-e (core/fn [a b]
{:pre [(every? number? [a b])]}
(+ a b)))
(is-tc-e (fn [a b]
{:pre [(every? number? [a b])]}
(+ a b)))
(is-tc-e (fn [a b]
{:pre [(not-any? (complement number?) [a b])]}
(+ a b)))
(is-tc-e (fn [a]
{:pre [(some number? [a])]}
(inc a)))
)
(deftest juxt-test
(is-tc-e (fn [a]
{:pre [(every? identity ((juxt number? integer?) a))]}
(inc a)))
(is-tc-e (fn [a]
{:pre [(first (nthrest [(number? a) (integer? a)] 0))]}
(inc a)))
(is-tc-e (fn [a]
{:pre [(first [(number? a) (integer? a)])]}
(inc a)))
(is-tc-e (fn [a]
{:pre [(first ((juxt number?) a))]}
(inc a)))
(is-tc-e (fn [a]
{:pre [(first ((juxt number? identity #(str %)) a))]}
(inc a)))
)
(comment
(((fn []
map))
identity
[1 2 3])
(map
identity
[1 2 3])
((fn [f]
(f 1))
(fn [d]
(inc d)))
((let [f (fn [d]
(inc d))]
(fn [d]
(inc d)))
1)
((let [f (fn [d]
(inc d))]
(let [d 1]
inc))
1)
)
(deftest symbolic-fnapp-test
(is-tc-e ((fn [f]
(f 1))
(fn [d]
(inc d)))))
(deftest beta-reduce-test
(is-tc-e ((fn* [a] a) :a) ':a)
(is-tc-err ((fn* [a] a) :a) ':b)
(is-tc-e ((fn* [a] ((fn* [a] ((fn* [a] a) a)) a)) :a) ':a)
TODO preserve original form in error msg somewhere ? or indicate
(is-tc-err ((fn* [a] ((fn* [a] ((fn* [a] a) a)) a)) :a) ':b)
(is-tc-e (:a {:a :b}) ':b)
(is-tc-e ((let* [] :a) {:a :b}) ':b)
(is-tc-e ((let* [] (fn* [a] (:a a))) {:a :b}) ':b)
(is-tc-e (((fn* [a] a) :a)
{:a :b})
':b)
(is-tc-e (((fn* [a] a) :a)
((fn* [a] a) {:a :b}))
':b)
(is-tc-e (((fn* [f] (f :a)) (fn* [a] a)) {:a :b}) ':b)
(is-tc-e (((fn* [f b] (f b)) (fn* [c] c) :a) {:a :b}) ':b)
(is-tc-e (((fn* [f a] (f a)) (fn* [a] a) :a) {:a :b}) ':b)
(is-tc-e (((fn* [f a] (f a)) (fn* [a] a) :a) ((fn* [a] a) {:a :b})) ':b)
(is-tc-e (((fn* [f a] (f a)) identity :a) ((fn* [a] a) {:a :b})) ':b)
(is-tc-e (((fn* [f a] (f a)) (fn* [a] a) :a)
((fn* [a] a) {:a :b}))
':b)
(is-tc-e [(((fn* [f a] (f a)) (fn* [a] a) :a)
((fn* [a] a) {:a :b}))
(((fn* [f a] (f a)) (fn* [a] a) :a)
((fn* [a] a) {:a :b}))
(((fn* [f a] (f a)) (fn* [a] a) :a)
((fn* [a] a) {:a :b}))
(((fn* [f a] (f a)) (fn* [a] a) :a)
((fn* [a] a) {:a :b}))]
(Seqable ':b))
(is-tc-err (fn* ([] ((fn* [f] ((fn* [x] (f (x x))) (fn* [y] (f (y y))))) inc))))
(is-tc-err (fn* ([] (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x)))))))))
(is-tc-err (fn* ([] (inc (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x))))))))))
(is-tc-err (fn* ([] (inc (inc (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x)))))))))))
(is-tc-err (fn* ([] (inc (inc (inc (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x))))))))))))
(is-tc-err (fn* ([] (inc (inc (inc (inc (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x)))))))))))))
(is-tc-err (fn* ([] (inc (inc (inc (inc (inc (inc ((fn* ([x] (inc (x x)))) (fn* ([x] (inc (x x))))))))))))))
(is-tc-e ((fn* [& a] (map inc a)) 1))
(is-tc-err ((fn* [& a] (map inc a)) :a))
(is-tc-e ((fn* [a] (map inc (seq [a]))) 1))
(is-tc-e ((fn* [a z] (map inc (seq [a z]))) 1 2))
(is-tc-e ((fn* [_ z] (inc z)) nil 1))
(is-tc-e ((fn* [a z] (inc z)) nil 1))
(is-tc-e ((fn* [a z] (+ a z)) 2 1))
TODO keyword invocations
#_(is-tc-e ((:a {:a (fn [a] a)}) :b) ':b)
(is-tc-e (apply inc [2])
Int)
(is-tc-e (apply inc (seq [2])) Int)
(is-tc-e (apply inc [(second (first {:a 2}))]) Int)
(is-tc-e (apply map (seq [identity [1]]))
(Seqable Num))
(is-tc-e (apply map [identity])
(Transducer Num Num))
FIXME error msg
(is-tc-err (apply map [identity])
(Transducer Num Bool))
FIXME error msg
(is-tc-err (apply map [identity]))
(is-tc-e ((comp inc dec) 1) Num)
(is-tc-e ((comp inc :a) {:a 1}) Num)
(is-tc-e ((comp identity :a) {:a 1}) Num)
(is-tc-e ((comp identity :a) {:a 1}) '1)
(is-tc-e ((comp inc (constantly nil)) 1))
FIXME
#_
(is-tc-e (sequence (comp (map inc) (map dec)) [1]))
(is-tc-e ((fn* [& args]
(inc (first args)))
1))
(is-tc-e ((core/fn [& args]
(inc (first args)))
1))
(is-tc-err ((core/fn [& args]
(inc (first args)))
true))
(is-tc-err ((core/fn [& args]
(inc (first args)))
true))
#_(is-tc-e ((fn [& args]
(inc (first args)))
1))
TODO play with the map transducer expander , use fn instead of fn *
(is-tc-e (comp (map inc) (map dec))
(Transducer Num Num))
(is-tc-err (comp (map inc) (map dec))
(Transducer Num Bool))
TODO constantly
( - form body[(ann - form v ( If e ( DomOf ( OptsOf e ) 0 : arity 2 ) ^:infer Any))/a ]
( If e ( RngOf ( TypeOf e ) : arity 2 ) ^:infer Any ) ) )
(is-tc-e ((ann-form
(fn* [i] (inc i))
[Int :-> Int])
1))
(is-tc-e ((ann-form
(clojure.core/fn [i] (inc i))
[Int :-> Int])
1))
(is-tc-e ((ann-form
(clojure.core/fn [i] (inc i))
[Int :-> Bool])
1))
(is-tc-e ((ann-form
(clojure.core/fn [i] (inc i))
[Bool :-> Int])
1))
(is-tc-e ((t/fn [i :- Int] (inc i))
1))
(is-tc-e ((ann-form
(t/fn [i :- Int] :- Int (inc i))
[Int :-> Int])
1))
(is-tc-e ((ann-form
(ann-form
inc
[Int :-> Int])
[Int :-> Int])
1))
(is-tc-e ((ann-form
(ann-form
(fn* [i] (boolean i))
[Num :-> Bool])
[Int :-> Bool])
1))
(is-tc-e (ann-form
(ann-form
(fn* [i] (boolean i))
[Num :-> Bool])
[Int :-> Bool]))
(is-tc-err (ann-form
(ann-form
(fn* [i] (boolean i))
[Int :-> Bool])
[Num :-> Bool]))
TODO subst object in return type of beta - reduction
(is-tc-e (reduce (fn* [a e] (conj a e))
[]
[1 2 3]))
fixpoint
#_
(is-tc-e (fixpoint
(fn* [c e] (concat c [(inc e)]))
{:subst-var x
:init [(Seq Nothing) Int :-> ^::t/infer Any]
:query (All [x] [[x Int :-> x] :-> x])
:iterate [x Int :-> ^::t/infer Any]
}))
)
(comment
(defn timet
[expr]
(let [start (. System (nanoTime))
ret (expr)]
(/ (double (- (. System (nanoTime)) start)) 1000000.0)))
(clojure.pprint/pprint
(sort-by val
(into {} (map (fn [v]
[v (timet #(clojure.test/test-vars [v]))]))
(filter (every-pred var? (comp :test meta)) (vals (ns-publics *ns*)))))
)
'([#'clojure.core.typed.test.frozen-macros/tc-ignore-test 171.394456]
[#'clojure.core.typed.test.frozen-macros/with-open-test 181.161775]
[#'clojure.core.typed.test.frozen-macros/typed-fn-test 233.531726]
[#'clojure.core.typed.test.frozen-macros/ann-form-test 235.352863]
[#'clojure.core.typed.test.frozen-macros/ns-test 240.44296]
[#'clojure.core.typed.test.frozen-macros/get-in-test 341.253694]
[#'clojure.core.typed.test.frozen-macros/fn-test 495.774091]
[#'clojure.core.typed.test.frozen-macros/when-not-test 542.922632]
[#'clojure.core.typed.test.frozen-macros/when-test 546.166276]
[#'clojure.core.typed.test.frozen-macros/when-let-test 609.879237]
[#'clojure.core.typed.test.frozen-macros/if-let-test 631.63356]
[#'clojure.core.typed.test.frozen-macros/assoc-in-inline-test 676.056304]
[#'clojure.core.typed.test.frozen-macros/assert-test 694.094945]
[#'clojure.core.typed.test.frozen-macros/update-in-inline-test 765.674776]
[#'clojure.core.typed.test.frozen-macros/let-test 992.088318]
[#'clojure.core.typed.test.frozen-macros/for-test 5778.336702])
'([#'clojure.core.typed.test.frozen-macros/ns-test 182.167286]
[#'clojure.core.typed.test.frozen-macros/tc-ignore-test 188.358344]
[#'clojure.core.typed.test.frozen-macros/with-open-test 221.02634]
[#'clojure.core.typed.test.frozen-macros/ann-form-test 274.636581]
[#'clojure.core.typed.test.frozen-macros/typed-fn-test 330.160597]
[#'clojure.core.typed.test.frozen-macros/get-in-test 388.410054]
[#'clojure.core.typed.test.frozen-macros/fn-test 682.037165]
[#'clojure.core.typed.test.frozen-macros/assert-test 774.38307]
[#'clojure.core.typed.test.frozen-macros/if-let-test 793.200128]
[#'clojure.core.typed.test.frozen-macros/when-not-test 807.979324]
[#'clojure.core.typed.test.frozen-macros/when-let-test 816.350961]
[#'clojure.core.typed.test.frozen-macros/for-test 819.305905]
[#'clojure.core.typed.test.frozen-macros/assoc-in-inline-test 820.942907]
[#'clojure.core.typed.test.frozen-macros/when-test 865.453885]
[#'clojure.core.typed.test.frozen-macros/let-test 1221.219269]
[#'clojure.core.typed.test.frozen-macros/update-in-inline-test 1641.337323])
)
)
)
|
cdc305ab1b3404ff4b60c7d8094f32219d13460f823ffbe7bd2d4360c3673997 | squirrel-prover/squirrel-prover | term.ml | open Utils
module L = Location
module Sv = Vars.Sv
module Mv = Vars.Mv
(*------------------------------------------------------------------*)
(** {2 Symbols} *)
(** Ocaml type of a typed index symbol.
Invariant: [s_typ] do not contain tvar or univars *)
type 'a isymb = {
s_symb : 'a;
s_indices : Vars.var list;
s_typ : Type.ty;
}
let mk_isymb (s : 'a) (t : Type.ty) (is : Vars.vars) =
let () = match t with
| Type.TVar _ | Type.TUnivar _ -> assert false;
| _ -> ()
in
assert (
List.for_all (fun v ->
Type.equal (Vars.ty v) Type.tindex ||
Type.equal (Vars.ty v) Type.ttimestamp
) is);
{ s_symb = s;
s_typ = t;
s_indices = is; }
type name = Symbols.name
type nsymb = name isymb
type fname = Symbols.fname
type fsymb = fname * Vars.var list
type mname = Symbols.macro
type msymb = mname isymb
type state = msymb
(*------------------------------------------------------------------*)
let pp_name ppf s = (Printer.kws `GoalName) ppf (Symbols.to_string s)
let pp_nsymb ppf (ns : nsymb) =
if ns.s_indices <> []
then Fmt.pf ppf "%a(%a)" pp_name ns.s_symb Vars.pp_list ns.s_indices
else Fmt.pf ppf "%a" pp_name ns.s_symb
let pp_nsymbs ppf (l : nsymb list) =
Fmt.pf ppf "@[<hov>%a@]"
(Fmt.list ~sep:(fun ppf () -> Fmt.pf ppf ", ") pp_nsymb) l
let pp_fname ppf s = (Printer.kws `GoalFunction) ppf (Symbols.to_string s)
let pp_fsymb ppf (fn,is) = match is with
| [] -> Fmt.pf ppf "%a" pp_fname fn
| _ -> Fmt.pf ppf "%a(%a)" pp_fname fn Vars.pp_list is
let pp_mname_s ppf s =
(Printer.kws `GoalMacro) ppf s
let pp_mname ppf s =
pp_mname_s ppf (Symbols.to_string s)
let pp_msymb ppf (ms : msymb) =
Fmt.pf ppf "%a%a"
pp_mname ms.s_symb
(Utils.pp_ne_list "(%a)" Vars.pp_list) ms.s_indices
(*------------------------------------------------------------------*)
* { 2 Atoms and terms }
type proj = string
type projs = proj list
let proj_from_string x : proj = x
let proj_to_string x : string = x
let pp_proj fmt (x : proj) = Fmt.string fmt x
let pp_projs fmt (l : projs) = Fmt.list ~sep:Fmt.comma pp_proj fmt l
let left_proj = "left"
let right_proj = "right"
module Sproj = Ss
module Mproj = Ms
(*------------------------------------------------------------------*)
type 'a diff_args =
| Explicit of (proj * 'a) list
(*------------------------------------------------------------------*)
type term =
| Fun of fsymb * Type.ftype * term list
| Name of nsymb
| Macro of msymb * term list * term
| Seq of Vars.var list * term
| Action of Symbols.action * Vars.var list
| Var of Vars.var
| Diff of term diff_args
| Find of Vars.var list * term * term * term
| ForAll of Vars.var list * term
| Exists of Vars.var list * term
type t = term
type terms = term list
(*------------------------------------------------------------------*)
let rec hash : term -> int = function
| Name n -> hcombine 0 (hash_isymb n)
| Fun ((f, is),_,terms) ->
let h = Symbols.hash f in
let h = hcombine_list Vars.hash h is in
hcombine 1 (hash_l terms h)
| Macro (m, l, ts) ->
let h = hcombine_list hash (hash_isymb m) l in
hcombine 2 (hcombine h (hash ts))
| Seq (vars, b) ->
let h = hcombine_list Vars.hash (hash b) vars in
hcombine 3 h
| Diff (Explicit l) -> hcombine 5 (hash_l (List.map snd l) 3)
| Find (b, c, d, e) ->
let h = hcombine_list Vars.hash 6 b in
hash_l [c;d;e] h
| ForAll (vs, b) ->
let h = hcombine_list Vars.hash (hash b) vs in
hcombine 7 h
| Exists (vs, b) ->
let h = hcombine_list Vars.hash (hash b) vs in
hcombine 8 h
| Var v -> hcombine 10 (Vars.hash v)
| Action (s, is) ->
let h = hcombine_list Vars.hash (Symbols.hash s) is in
hcombine 11 h
and hash_l (l : term list) (h : int) : int =
hcombine_list hash h l
(* ignore the type *)
and hash_isymb : type a. a Symbols.t isymb -> int =
fun symb ->
let h = Symbols.hash symb.s_symb in
hcombine_list Vars.hash h symb.s_indices
(*------------------------------------------------------------------*)
* { 2 Higher - order terms }
type hterm = Lambda of Vars.vars * term
(*------------------------------------------------------------------*)
* { 2 Builtins function symbols }
let mk f : fsymb = (f,[])
let f_diff = mk Symbols.fs_diff
let f_happens = mk Symbols.fs_happens
let f_pred = mk Symbols.fs_pred
let f_witness = mk Symbols.fs_witness
(** Boolean connectives *)
let f_false = mk Symbols.fs_false
let f_true = mk Symbols.fs_true
let f_and = mk Symbols.fs_and
let f_or = mk Symbols.fs_or
let f_impl = mk Symbols.fs_impl
let f_not = mk Symbols.fs_not
let f_ite = mk Symbols.fs_ite
(** Comparisons *)
let f_eq = mk Symbols.fs_eq
let f_neq = mk Symbols.fs_neq
let f_leq = mk Symbols.fs_leq
let f_lt = mk Symbols.fs_lt
let f_geq = mk Symbols.fs_geq
let f_gt = mk Symbols.fs_gt
(** Fail *)
let f_fail = mk Symbols.fs_fail
(** Xor and its unit *)
let f_xor = mk Symbols.fs_xor
let f_zero = mk Symbols.fs_zero
(** Successor over natural numbers *)
let f_succ = mk Symbols.fs_succ
(** Adversary function *)
let f_att = mk Symbols.fs_att
(** Pairing *)
let f_pair = mk Symbols.fs_pair
let f_fst = mk Symbols.fs_fst
let f_snd = mk Symbols.fs_snd
(** Boolean to Message *)
let f_of_bool = mk Symbols.fs_of_bool
(** Empty *)
let empty =
let fty = Symbols.ftype_builtin Symbols.fs_empty in
Fun (mk Symbols.fs_empty, fty, [])
(** Length *)
let f_len = mk Symbols.fs_len
let f_zeroes = mk Symbols.fs_zeroes
(** Init action *)
let init = Action(Symbols.init_action,[])
(*------------------------------------------------------------------*)
* { 2 Smart constructors }
let mk_var (v : Vars.var) : term = Var v
let mk_action a is = Action (a,is)
let mk_name n = Name n
let mk_macro ms l t = Macro (ms, l, t)
let mk_diff l =
assert
(let projs = List.map fst l in
List.sort Stdlib.compare projs = List.sort_uniq Stdlib.compare projs);
match l with
| [] -> assert false
| [_, t] -> t
| _ -> Diff (Explicit l)
(*------------------------------------------------------------------*)
let mk_fun0 fs fty terms = Fun (fs, fty, terms)
let mk_fun table fname indices terms =
let fty = Symbols.ftype table fname in
Fun ((fname,indices), fty, terms)
let mk_fbuiltin = mk_fun Symbols.builtins_table
(*------------------------------------------------------------------*)
* { 3 For first - order formulas }
(** Smart constructors.
The module is included after its definition. *)
module SmartConstructors = struct
let mk_true = mk_fbuiltin Symbols.fs_true [] []
let mk_false = mk_fbuiltin Symbols.fs_false [] []
(** Some smart constructors are redefined later, after substitutions. *)
let mk_not_ns term = mk_fbuiltin Symbols.fs_not [] [term]
let mk_and_ns t0 t1 = mk_fbuiltin Symbols.fs_and [] [t0;t1]
let mk_or_ns t0 t1 = mk_fbuiltin Symbols.fs_or [] [t0;t1]
let mk_impl_ns t0 t1 = mk_fbuiltin Symbols.fs_impl [] [t0;t1]
let mk_eq_ns t0 t1 = mk_fbuiltin Symbols.fs_eq [] [t0;t1]
let mk_neq_ns t0 t1 = mk_fbuiltin Symbols.fs_neq [] [t0;t1]
let mk_leq_ns t0 t1 = mk_fbuiltin Symbols.fs_leq [] [t0;t1]
let mk_lt_ns t0 t1 = mk_fbuiltin Symbols.fs_lt [] [t0;t1]
let mk_geq_ns t0 t1 = mk_fbuiltin Symbols.fs_geq [] [t0;t1]
let mk_gt_ns t0 t1 = mk_fbuiltin Symbols.fs_gt [] [t0;t1]
let mk_not ?(simpl=true) t1 = match t1 with
| Fun (fs,_,[t]) when fs = f_not && simpl -> t
| t -> mk_not_ns t
let mk_eq ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_true else mk_eq_ns t1 t2
let mk_neq ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_false else mk_neq_ns t1 t2
let mk_leq ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_true else mk_leq_ns t1 t2
let mk_geq ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_true else mk_geq_ns t1 t2
let mk_lt ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_false else mk_lt_ns t1 t2
let mk_gt ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_false else mk_gt_ns t1 t2
let mk_and ?(simpl=true) t1 t2 = match t1,t2 with
| tt, _ when tt = mk_false && simpl -> mk_false
| _, tt when tt = mk_false && simpl -> mk_false
| tt, t when tt = mk_true && simpl -> t
| t, tt when tt = mk_true && simpl -> t
| t1,t2 -> mk_and_ns t1 t2
let mk_ands ?(simpl=true) ts = List.fold_right (mk_and ~simpl) ts mk_true
let mk_or ?(simpl=true) t1 t2 = match t1,t2 with
| tt, _ when tt = mk_true && simpl -> mk_true
| _, tt when tt = mk_true && simpl -> mk_true
| tf, t when tf = mk_false && simpl -> t
| t, tf when tf = mk_false && simpl -> t
| t1,t2 -> mk_or_ns t1 t2
let mk_ors ?(simpl=true) ts = List.fold_right (mk_or ~simpl) ts mk_false
let mk_impl ?(simpl=true) t1 t2 = match t1,t2 with
| tf, _ when tf = mk_false && simpl -> mk_true
| tt, t when tt = mk_true && simpl -> t
| t1,t2 -> mk_impl_ns t1 t2
let mk_impls ?(simpl=true) ts t =
List.fold_left (fun tres t0 -> (mk_impl ~simpl) t0 tres) t ts
let mk_forall l f =
if l = [] then f
else match f with
| ForAll (l', f) -> ForAll (l @ l', f)
| _ -> ForAll (l, f)
let mk_exists l f =
if l = [] then f
else match f with
| Exists (l', f) -> Exists (l @ l', f)
| _ -> Exists (l, f)
let mk_happens t = mk_fbuiltin Symbols.fs_happens [] [t]
let mk_pred t = mk_fbuiltin Symbols.fs_pred [] [t]
end
include SmartConstructors
(*------------------------------------------------------------------*)
* { 3 For terms }
let mk_zero = mk_fbuiltin Symbols.fs_zero [] []
let mk_fail = mk_fbuiltin Symbols.fs_fail [] []
let mk_len term = mk_fbuiltin Symbols.fs_len [] [term]
let mk_zeroes term = mk_fbuiltin Symbols.fs_zeroes [] [term]
let mk_pair t0 t1 = mk_fbuiltin Symbols.fs_pair [] [t0;t1]
let mk_ite ?(simpl=true) c t e =
match c with
| t when t = mk_true && simpl -> t
| t when t = mk_false && simpl -> e
| _ -> mk_fbuiltin Symbols.fs_ite [] [c;t;e]
let mk_of_bool t = mk_fbuiltin Symbols.fs_of_bool [] [t]
let mk_witness ty =
let fty = Type.mk_ftype 0 [] [] ty in
Fun (f_witness, fty, [])
let mk_find ?(simpl=false) is c t e =
if not simpl then Find (is, c, t, e)
else if c = mk_false then e else Find (is, c, t, e)
(*------------------------------------------------------------------*)
* { 3 For formulas }
let mk_timestamp_leq t1 t2 = match t1,t2 with
| _, Fun (f,_, [t2']) when f = f_pred -> mk_lt t1 t2'
| _ -> mk_leq t1 t2
(** Operations on vectors of indices of the same length. *)
let mk_indices_neq (vect_i : Vars.var list) vect_j =
mk_ors ~simpl:true
(List.map2 (fun i j ->
mk_neq (mk_var i) (mk_var j)
) vect_i vect_j)
let mk_indices_eq ?(simpl=true) vect_i vect_j =
mk_ands ~simpl:true
(List.map2 (fun i j ->
mk_eq ~simpl (mk_var i) (mk_var j)
) vect_i vect_j)
let mk_lambda evs ht = match ht with
| Lambda (evs', t) -> Lambda (evs @ evs', t)
(*------------------------------------------------------------------*)
(** {2 Typing} *)
(*------------------------------------------------------------------*)
let ty ?ty_env (t : term) : Type.ty =
let must_close, ty_env = match ty_env with
| None -> true, Type.Infer.mk_env ()
| Some ty_env -> false, ty_env
in
let rec ty (t : term) : Type.ty =
match t with
| Fun (_,fty,terms) ->
let fty = Type.open_ftype ty_env fty in
let () =
List.iter2 (fun arg arg_ty ->
match Type.Infer.unify_leq ty_env (ty arg) arg_ty with
| `Ok -> ()
| `Fail -> assert false
) terms fty.Type.fty_args
in
fty.Type.fty_out
| Name ns -> ns.s_typ
| Macro (s,_,_) -> s.s_typ
| Seq _ -> Type.Message
| Var v -> Vars.ty v
| Action _ -> Type.Timestamp
| Diff (Explicit l) -> ty (snd (List.hd l))
| Find (a, b, c, d) -> ty c
| ForAll _ -> Type.Boolean
| Exists _ -> Type.Boolean
in
let tty = ty t in
if must_close
then Type.tsubst (Type.Infer.close ty_env) tty (* ty_env should be closed *)
else tty
(*------------------------------------------------------------------*)
(** {2 Destructors} *)
let destr_fun ?fs = function
| Fun (fs', _, l) when fs = None -> Some l
| Fun (fs', _, l) when fs = Some fs' -> Some l
| _ -> None
let oas_seq0 = omap as_seq0
let oas_seq1 = omap as_seq1
let oas_seq2 = omap as_seq2
(*------------------------------------------------------------------*)
* { 3 For first - order formulas }
* .
The module is included after its definition .
The module is included after its definition. *)
module SmartDestructors = struct
let destr_exists1 = function
| Exists (v :: vs, f) -> Some (v, mk_exists vs f)
| _ -> None
let rec destr_exists = function
| Exists (vs, f) ->
begin
match destr_exists f with
| Some (vs', f) -> Some (vs @ vs', f)
| None -> Some (vs, f)
end
| _ -> None
let rec decompose_exists = function
| Exists (vs, f) ->
let vs', f0 = decompose_exists f in
vs @ vs', f0
| _ as f -> [], f
let destr_forall1 = function
| ForAll (v :: vs, f) -> Some (v, mk_forall vs f)
| _ -> None
let rec destr_forall = function
| ForAll (vs, f) ->
begin
match destr_forall f with
| Some (vs', f) -> Some (vs @ vs', f)
| None -> Some (vs, f)
end
| _ -> None
let rec decompose_forall = function
| ForAll (vs, f) ->
let vs', f0 = decompose_forall f in
vs @ vs', f0
| _ as f -> [], f
(*------------------------------------------------------------------*)
let destr_false f = oas_seq0 (destr_fun ~fs:f_false f)
let destr_true f = oas_seq0 (destr_fun ~fs:f_true f)
let destr_zero f = oas_seq0 (destr_fun ~fs:f_zero f)
let destr_not f = oas_seq1 (destr_fun ~fs:f_not f)
let destr_or f = oas_seq2 (destr_fun ~fs:f_or f)
let destr_and f = oas_seq2 (destr_fun ~fs:f_and f)
let destr_impl f = oas_seq2 (destr_fun ~fs:f_impl f)
let destr_pair f = oas_seq2 (destr_fun ~fs:f_pair f)
let destr_iff f =
match f with
| Fun (fs, _, [Fun (fs1, _, [t1 ; t2]);
Fun (fs2, _, [t2'; t1'])])
when fs = f_and && fs1 = f_impl && fs2 = f_impl ->
if t1 = t1' && t2 = t2' then Some (t1, t2) else None
| _ -> None
(*------------------------------------------------------------------*)
(* let destr_neq f = oas_seq2 (obind (destr_fun ~fs:f_eq) (destr_not f)) *)
let destr_neq f = oas_seq2 (destr_fun ~fs:f_neq f)
let destr_eq f = oas_seq2 (destr_fun ~fs:f_eq f)
let destr_leq f = oas_seq2 (destr_fun ~fs:f_leq f)
let destr_lt f = oas_seq2 (destr_fun ~fs:f_leq f)
(*------------------------------------------------------------------*)
* for [ fs ] of arity 2 , left associative
let[@warning "-32"] mk_destr_many_left fs =
let rec destr l f =
if l < 0 then assert false;
if l = 1 then Some [f]
else match destr_fun ~fs f with
| None -> None
| Some [f;g] -> omap (fun l -> l @ [g]) (destr (l-1) f)
| _ -> assert false
in
destr
* for [ fs ] of arity 2 , right associative
let mk_destr_many_right fs =
let rec destr l f =
assert (l > 0);
if l = 1 then Some [f]
else match destr_fun ~fs f with
| None -> None
| Some [f;g] -> omap (fun l -> f :: l) (destr (l-1) g)
| _ -> assert false
in
destr
let destr_ors = mk_destr_many_right f_or
let destr_ands = mk_destr_many_right f_and
let destr_impls = mk_destr_many_right f_impl
(*------------------------------------------------------------------*)
(** for any associative [fs] *)
let mk_decompose fs =
let rec decompose f = match destr_fun ~fs f with
| None -> [f]
| Some l -> List.concat_map decompose l
in
decompose
let decompose_ors = mk_decompose f_or
let decompose_ands = mk_decompose f_and
let decompose_impls f =
let rec decompose f = match destr_fun ~fs:f_impl f with
| None -> [f]
| Some [f;g] -> f :: decompose g
| _ -> assert false
in
decompose f
let decompose_impls_last f =
let forms = decompose_impls f in
let rec last = function
| [] -> assert false
| [f] -> [], f
| f :: fs ->
let prems, goal = last fs in
f :: prems, goal
in
last forms
(*------------------------------------------------------------------*)
let is_false f = destr_false f <> None
let is_true f = destr_true f <> None
let is_not f = destr_not f <> None
let is_zero f = destr_zero f <> None
let is_or f = destr_or f <> None
let is_and f = destr_and f <> None
let is_impl f = destr_impl f <> None
(* is_pair is unused but having it seems to make sense *)
let[@warning "-32"] is_pair f = destr_pair f <> None
let is_exists f = destr_exists f <> None
let is_forall f = destr_forall f <> None
let is_eq f = destr_eq f <> None
let is_neq f = destr_neq f <> None
let is_leq f = destr_leq f <> None
let is_lt f = destr_lt f <> None
end
include SmartDestructors
(*------------------------------------------------------------------*)
let is_name : term -> bool = function
| Name _ -> true
| _ -> false
(*------------------------------------------------------------------*)
let destr_var : term -> Vars.var option = function
| Var v -> Some v
| _ -> None
let is_var (t:term) : bool = destr_var t <> None
(*------------------------------------------------------------------*)
let destr_action = function
| Action (s,is) -> Some (s,is)
| _ -> None
(*------------------------------------------------------------------*)
* { 2 Printing }
let pp_indices ppf l =
if l <> [] then Fmt.pf ppf "(%a)" Vars.pp_list l
let pp_ord ppf = function
| `Eq -> Fmt.pf ppf "="
| `Neq -> Fmt.pf ppf "<>"
| `Leq -> Fmt.pf ppf "<="
| `Geq -> Fmt.pf ppf ">="
| `Lt -> Fmt.pf ppf "<"
| `Gt -> Fmt.pf ppf ">"
let rec is_and_happens = function
| Fun (f, _, [t]) when f = f_happens -> true
| _ as f -> match destr_and f with
| Some (l,r) -> is_and_happens l && is_and_happens r
| _ -> false
(*------------------------------------------------------------------*)
(** Additional printing information *)
type pp_info = { styler : pp_info -> term -> Printer.keyword option * pp_info; }
let default_pp_info = { styler = fun info _ -> None, info; }
let styled_opt (err : Printer.keyword option) printer =
match err with
| None -> printer
| Some kw -> fun ppf t -> (Printer.kw kw ppf "%a" printer t)
(*------------------------------------------------------------------*)
let toplevel_prec = 0
let quant_fixity = 5 , `Prefix
(* binary *)
let impl_fixity = 10 , `Infix `Right
let iff_fixity = 12 , `Infix `Right
let pair_fixity = 20 , `NoParens
let or_fixity = 20 , `Infix `Right
let and_fixity = 25 , `Infix `Right
let xor_fixity = 26 , `Infix `Right
let eq_fixity = 27 , `Infix `NonAssoc
let order_fixity = 29 , `Infix `NonAssoc
let ite_fixity = 40 , `Infix `Left
let other_infix_fixity = 50 , `Infix `Right
let not_fixity = 26 , `Prefix
let seq_fixity = 1000 , `Prefix
let find_fixity = 1000 , `Prefix
let macro_fixity = 1000 , `NoParens
let diff_fixity = 1000 , `NoParens
let fun_fixity = 1000 , `NoParens
let happens_fixity = 1000 , `NoParens
let get_infix_prec (f : Symbols.fname) =
(* *)if f = Symbols.fs_and then fst and_fixity
else if f = Symbols.fs_or then fst or_fixity
else if f = Symbols.fs_impl then fst impl_fixity
else if f = Symbols.fs_xor then fst xor_fixity
else if f = Symbols.fs_eq then fst eq_fixity
else if f = Symbols.fs_neq then fst eq_fixity
else if f = Symbols.fs_leq then fst order_fixity
else if f = Symbols.fs_lt then fst order_fixity
else if f = Symbols.fs_gt then fst order_fixity
else if f = Symbols.fs_geq then fst order_fixity
else fst other_infix_fixity
(*------------------------------------------------------------------*)
(** Applies the styling info in [info]
NOTE: this is *not* the [pp] exported by the module, it is shadowed later *)
let rec pp
(info : pp_info)
((outer,side) : ('b * fixity) * assoc)
(ppf : Format.formatter)
(t : term)
: unit
=
let err_opt, info = info.styler info t in
styled_opt err_opt (_pp info (outer, side)) ppf t
(** Core printing function *)
and _pp
(info : pp_info)
((outer,side) : ('b * fixity) * assoc)
(ppf : Format.formatter)
(t : term)
: unit
=
let pp = pp info in
match t with
| Var m -> Fmt.pf ppf "%a" Vars.pp m
| Fun (s,_,[a]) when s = f_happens -> pp_happens info ppf [a]
(* if-then-else, no else *)
| Fun (s,_,[b;c; Fun (f,_,[])])
when s = f_ite && f = f_zero ->
let pp fmt () =
Fmt.pf ppf "@[<hov 2>if %a@ then@ %a@]"
(pp (ite_fixity, `NonAssoc)) b
(pp (ite_fixity, `Right)) c
in
maybe_paren ~outer ~side ~inner:ite_fixity pp ppf ()
(* if-then-else, true/false *)
| Fun (s,_,[b;Fun (f1,_,[]);Fun (f2,_,[])])
when s = f_ite && f1 = f_true && f2 = f_false ->
Fmt.pf ppf "%a"
(pp (ite_fixity, `NonAssoc)) b
(* if-then-else, general case *)
| Fun (s,_,[a;b;c]) when s = f_ite ->
let pp fmt () =
Fmt.pf ppf "@[<hv 0>@[<hov 2>if %a@ then@ %a@]@ %a@]"
(pp (ite_fixity, `NonAssoc)) a
(pp (ite_fixity, `NonAssoc)) b
(pp_chained_ite info) c (* prints the [else] *)
in
maybe_paren ~outer ~side ~inner:ite_fixity pp ppf ()
(* pair *)
| Fun (s,_,terms) when s = f_pair ->
Fmt.pf ppf "%a"
(Utils.pp_ne_list
"<@[<hov>%a@]>"
(Fmt.list ~sep:(fun ppf () -> Fmt.pf ppf ",@,")
(pp (pair_fixity, `NonAssoc))))
terms
(* iff. <=> *)
| Fun (fa,_,[Fun (fi1,_,[bl1;br1]);
Fun (fi2,_,[br2;bl2])])
when fa = f_and && fi1 = f_impl && fi2 = f_impl &&
bl1 = bl2 && br1 = br2 ->
let pp fmt () =
Fmt.pf ppf "@[%a@ <=>@ %a@]"
(pp (iff_fixity, `Left)) bl1
(pp (iff_fixity, `Right)) br1
in
maybe_paren ~outer ~side ~inner:iff_fixity pp ppf ()
(* happens *)
| Fun _ as f when is_and_happens f ->
pp_and_happens info ppf f
(* infix *)
| Fun ((s,is),_,[bl;br]) when Symbols.is_infix s ->
let assoc = Symbols.infix_assoc s in
let prec = get_infix_prec s in
assert (is = []);
let pp fmt () =
Fmt.pf ppf "@[<0>%a %s@ %a@]"
(pp ((prec, `Infix assoc), `Left)) bl
(Symbols.to_string s)
(pp ((prec, `Infix assoc), `Right)) br
in
maybe_paren ~outer ~side ~inner:(prec, `Infix assoc) pp ppf ()
(* not *)
| Fun (s,_,[b]) when s = f_not ->
Fmt.pf ppf "@[<hov 2>not(%a)@]" (pp (not_fixity, `Right)) b
(* true/false *)
| Fun _ as tt when tt = mk_true -> Fmt.pf ppf "true"
| Fun _ as tf when tf = mk_false -> Fmt.pf ppf "false"
(* constant *)
| Fun (f,_,[]) ->
Fmt.pf ppf "%a" pp_fsymb f
arity one
| Fun (f,_,[a]) ->
Fmt.pf ppf "@[<hov 2>%a(@,%a)@]"
pp_fsymb f
(pp (fun_fixity, `NonAssoc)) a
(* function symbol, general case *)
| Fun (f,_,terms) ->
Fmt.pf ppf "@[<hov 2>%a(%a)@]"
pp_fsymb f
(Utils.pp_ne_list
"%a"
(Fmt.list ~sep:(fun ppf () -> Fmt.pf ppf ",@,")
(pp (fun_fixity, `NonAssoc))))
terms
| Name n -> pp_nsymb ppf n
| Macro (m, l, ts) ->
Fmt.pf ppf "@[%a%a@%a@]"
pp_msymb m
(Utils.pp_ne_list
"(@[<hov>%a@])"
(Fmt.list ~sep:Fmt.comma (pp (macro_fixity, `NonAssoc)))) l
(pp (macro_fixity, `NonAssoc)) ts
| Seq (vs, b) ->
Fmt.pf ppf "@[<hov 2>seq(%a->@,%a)@]"
Vars.pp_typed_list vs (pp (seq_fixity, `NonAssoc)) b
| Action (symb,indices) ->
Printer.kw `GoalAction ppf "%s%a" (Symbols.to_string symb) pp_indices indices
| Diff (Explicit l) ->
Fmt.pf ppf "@[<hov 2>diff(@,%a)@]"
(Fmt.list ~sep:(fun fmt () -> Format.fprintf fmt ",@ ")
(pp (diff_fixity, `NonAssoc)))
TODO labels
| Find (b, c, d, Fun (f,_,[])) when f = f_zero ->
let pp fmt () =
Fmt.pf ppf "@[<hv 0>\
@[<hov 2>try find %a such that@ %a@]@;<1 0>\
@[<hov 2>in@ %a@]@]"
Vars.pp_typed_list b
(pp (find_fixity, `NonAssoc)) c
(pp (find_fixity, `Right)) d
in
maybe_paren ~outer ~side ~inner:find_fixity pp ppf ()
| Find (b, c, d, e) ->
let pp fmt () =
Fmt.pf ppf "@[<hv 0>\
@[<hov 2>try find %a such that@ %a@]@;<1 0>\
@[<hov 2>in@ %a@]@;<1 0>\
%a@]"
Vars.pp_typed_list b
(pp (find_fixity, `NonAssoc)) c
(pp (find_fixity, `NonAssoc)) d
(pp_chained_find info) e (* prints the [else] *)
in
maybe_paren ~outer ~side ~inner:find_fixity pp ppf ()
| ForAll (vs, b) ->
let pp fmt () =
Fmt.pf ppf "@[<2>forall (@[%a@]),@ %a@]"
Vars.pp_typed_list vs
(pp (quant_fixity, `Right)) b
in
maybe_paren ~outer ~side ~inner:(fst quant_fixity, `Prefix) pp ppf ()
| Exists (vs, b) ->
let pp fmt () =
Fmt.pf ppf "@[<2>exists (@[%a@]),@ %a@]"
Vars.pp_typed_list vs
(pp (quant_fixity, `Right)) b
in
maybe_paren ~outer ~side ~inner:(fst quant_fixity, `Prefix) pp ppf ()
(* Printing in a [hv] box. Print the trailing [else] of the caller. *)
and pp_chained_ite info ppf (t : term) =
match t with
| Fun (s,_,[a;b;c]) when s = f_ite ->
Fmt.pf ppf "@[<hov 2>else if %a@ then@ %a@]@ %a"
(pp info (ite_fixity, `NonAssoc)) a
(pp info (ite_fixity, `NonAssoc)) b
(pp_chained_ite info) c
| _ -> Fmt.pf ppf "@[<hov 2>else@ %a@]" (pp info (ite_fixity, `Right)) t
(* Printing in a [hv] box. Print the trailing [else] of the caller. *)
and pp_chained_find info ppf (t : term) =
match t with
| Find (b, c, d, e) ->
Fmt.pf ppf "@[<hov 2>else try find %a such that@ %a@]@;<1 0>\
@[<hov 2>in@ %a@]@;<1 0>\
%a"
Vars.pp_typed_list b
(pp info (find_fixity, `NonAssoc)) c
(pp info (find_fixity, `NonAssoc)) d
(pp_chained_find info) e
| _ -> Fmt.pf ppf "@[<hov 2>else@ %a@]" (pp info (find_fixity, `Right)) t
and pp_happens info ppf (ts : term list) =
Fmt.pf ppf "@[<hv 2>%a(%a)@]"
pp_mname_s "happens"
(Fmt.list ~sep:(fun fmt () -> Fmt.pf fmt ",@ ")
(pp info (happens_fixity, `NonAssoc))) ts
and pp_and_happens info ppf f =
let rec collect acc = function
| Fun (s, _, [ts]) when s = f_happens -> ts :: acc
| _ as f ->
let l, r = oget (destr_and f) in
collect (collect acc l) r
in
pp_happens info ppf (collect [] f)
(*------------------------------------------------------------------*)
let pp_with_info (info : pp_info) (fmt : Format.formatter) (t : term) : unit =
pp info ((toplevel_prec, `NoParens), `NonAssoc) fmt t
let pp (fmt : Format.formatter) (t : term) : unit =
pp default_pp_info ((toplevel_prec, `NoParens), `NonAssoc) fmt t
(*------------------------------------------------------------------*)
let pp_hterm fmt = function
| Lambda (evs, t) ->
Fmt.pf fmt "@[<v 2>fun (@[%a@]) ->@ %a@]"
Vars.pp_typed_list evs pp t
(*------------------------------------------------------------------*)
(** Literals. *)
type ord = [ `Eq | `Neq | `Leq | `Geq | `Lt | `Gt ]
type ord_eq = [ `Eq | `Neq ]
type ('a,'b) _atom = 'a * 'b * 'b
type xatom = [
| `Comp of (ord,term) _atom
| `Happens of term
]
type literal = [`Neg | `Pos] * xatom
type literals = literal list
let pp_xatom ppf = function
| `Comp (o,tl,tr) ->
Fmt.pf ppf "@[%a %a@ %a@]" pp tl pp_ord o pp tr
| `Happens a -> pp_happens default_pp_info ppf [a]
let pp_literal fmt ((pn,at) : literal) =
match pn with
| `Pos -> Fmt.pf fmt "%a" pp_xatom at
| `Neg -> Fmt.pf fmt "¬(%a)" pp_xatom at
let pp_literals fmt (l : literal list) =
let sep fmt () = Fmt.pf fmt " ∧ " in
(Fmt.list ~sep pp_literal) fmt l
let ty_xatom = function
| `Happens t -> Type.Timestamp
| `Comp (_, t1, t2) ->
let ty1 = ty t1 in
assert (ty1 = ty t2);
ty1
let ty_lit ((_, at) : literal) : Type.ty = ty_xatom at
let neg_lit ((pn, at) : literal) : literal =
let pn = match pn with
| `Pos -> `Neg
| `Neg -> `Pos in
(pn, at)
let form_to_xatom (form : term) : xatom option =
match form with
| Fun (f, _, [a]) when f = f_happens -> Some (`Happens a)
| Fun (fseq, _, [a;b]) when fseq = f_eq -> Some (`Comp (`Eq, a, b))
| Fun (fsneq, _, [a;b]) when fsneq = f_neq -> Some (`Comp (`Neq, a, b))
| Fun (fsleq, _, [a;b]) when fsleq = f_leq -> Some (`Comp (`Leq, a, b))
| Fun (fslt, _, [a;b]) when fslt = f_lt -> Some (`Comp (`Lt, a, b))
| Fun (fsgeq, _, [a;b]) when fsgeq = f_geq -> Some (`Comp (`Geq, a, b))
| Fun (fsgt, _, [a;b]) when fsgt = f_gt -> Some (`Comp (`Gt, a, b))
| _ -> None
let rec form_to_literal (form : term) : literal option =
match form with
| Fun (fnot, _, [f]) when fnot = f_not -> omap neg_lit (form_to_literal f)
| _ -> omap (fun at -> (`Pos, at)) (form_to_xatom form)
let disjunction_to_literals f : literal list option =
let exception Not_a_disjunction in
let rec aux_l = function
| tf when tf = mk_false -> []
| Fun (fsor,_, [a; b]) when fsor = f_or -> aux_l a @ aux_l b
| f -> match form_to_literal f with
| Some f -> [f]
| None -> raise Not_a_disjunction
in
try Some (aux_l f) with Not_a_disjunction -> None
(*------------------------------------------------------------------*)
let form_to_literals
(form : term)
: [`Entails of literal list | `Equiv of literal list]
=
let partial = ref false in
let lits : literal list =
List.fold_left (fun acc f ->
match form_to_literal f with
| Some at -> at :: acc
| None -> partial := true; acc
) [] (decompose_ands form)
in
if !partial then `Entails lits else `Equiv lits
(*------------------------------------------------------------------*)
let eq_triv f = match destr_eq f with
| Some (t1,t2) when t1=t2 ->
(match t1 with
Find _ -> false
| _ -> true)
| _ -> false
let f_triv = function
| tt when tt = mk_true -> true
| f -> eq_triv f
(*------------------------------------------------------------------*)
(** Declare input and output macros. *)
let mk s k = { s_symb = s; s_typ = k; s_indices = []; }
let in_macro : msymb = mk Symbols.inp Type.Message
let out_macro : msymb = mk Symbols.out Type.Message
let frame_macro : msymb = mk Symbols.frame Type.Message
let cond_macro : msymb = mk Symbols.cond Type.Boolean
let exec_macro : msymb = mk Symbols.exec Type.Boolean
(*------------------------------------------------------------------*)
(** Substitutions *)
type esubst = ESubst of term * term
type subst = esubst list
let rec assoc : subst -> term -> term =
fun subst term ->
match subst with
| [] -> term
| ESubst (t1,t2)::q ->
if term = t1 then t2 else assoc q term
let pp_esubst ppf (ESubst (t1,t2)) =
Fmt.pf ppf "%a->%a" pp t1 pp t2
let pp_subst ppf s =
Fmt.pf ppf "@[<hv 0>%a@]"
(Fmt.list ~sep:(fun ppf () -> Fmt.pf ppf ",@ ") pp_esubst) s
let subst_var (subst : subst) (var : Vars.var) : Vars.var =
match assoc subst (Var var) with
| Var var -> var
| _ -> assert false
let subst_vars (subst : subst) (vs : Vars.vars) : Vars.vars =
List.map (subst_var subst) vs
let subst_isymb (s : subst) (symb : 'a isymb) : 'a isymb =
{ symb with s_indices = subst_vars s symb.s_indices }
let subst_macro (s : subst) isymb =
{ isymb with s_indices = subst_vars s isymb.s_indices }
(*------------------------------------------------------------------*)
let fv (term : term) : Sv.t =
let rec fv (t : term) : Sv.t =
match t with
| Action (_,indices) -> Sv.of_list indices
| Var tv -> Sv.singleton tv
| Fun ((_,indices), _,lt) ->
Sv.union (Sv.of_list indices) (fvs lt)
| Macro (s, l, ts) ->
Sv.union
(Sv.of_list s.s_indices)
(Sv.union (fv ts) (fvs l))
| Name s -> Sv.of_list s.s_indices
| Diff (Explicit l) -> fvs (List.map snd l)
| Find (a, b, c, d) ->
Sv.union
(Sv.diff (fvs [b;c]) (Sv.of_list a))
(fv d)
| Seq (a, b)
| ForAll (a, b)
| Exists (a, b) -> Sv.diff (fv b) (Sv.of_list a)
and fvs (terms : term list) : Sv.t =
List.fold_left (fun sv x -> Sv.union (fv x) sv) Sv.empty terms
in
fv term
let get_vars t = fv t |> Sv.elements
(*------------------------------------------------------------------*)
* { 2 Iterators }
(** Does not recurse. *)
let tmap (func : term -> term) (t : term) : term =
match t with
| Action _ -> t
| Name _ -> t
| Var _ -> t
| Fun (f,fty,terms) -> Fun (f, fty, List.map func terms)
| Macro (m, l, ts) -> Macro (m, List.map func l, func ts)
| Seq (vs, b) -> Seq (vs, func b)
| Diff (Explicit l) ->
Diff (Explicit (List.map (fun (lbl,tm) -> lbl, func tm) l))
| Find (b, c, d, e) ->
let c = func c
and d = func d
and e = func e in
Find (b, c, d, e)
| ForAll (vs, b) -> ForAll (vs, func b)
| Exists (vs, b) -> Exists (vs, func b)
let tmap_fold (func : 'b -> term -> 'b * term) (b : 'b) (t : term) : 'b * term =
let bref = ref b in
let g t =
let b, t = func !bref t in
bref := b;
t
in
let t = tmap g t in
!bref, t
let titer (f : term -> unit) (t : term) : unit =
let g e = f e; e in
ignore (tmap g t)
let tfold (f : term -> 'b -> 'b) (t : term) (v : 'b) : 'b =
let vref : 'b ref = ref v in
let fi e = vref := (f e !vref) in
titer fi t;
!vref
let texists (f : term -> bool) (t : term) : bool =
tfold (fun t b -> f t || b) t false
let tforall (f : term -> bool) (t : term) : bool =
tfold (fun t b -> f t || b) t false
(*------------------------------------------------------------------*)
* { 2 Substitutions }
(** given a variable [x] and a subst [s], remove from [s] all
substitution [v->_]. *)
let filter_subst (var:Vars.var) (s:subst) =
let s =
List.fold_left (fun acc (ESubst (x, y)) ->
if not (Sv.mem var (fv x))
then (ESubst (x, y))::acc
else acc
) [] s in
List.rev s
(** Check if the substitutions only susbtitutes variables *)
let is_var_subst s =
List.for_all (fun (ESubst (t,_)) -> match t with
| Var _ -> true
| _ -> false) s
* Returns the variables appearing in a substitution LHS .
let subst_support s =
List.fold_left (fun supp (ESubst (t,_)) ->
Sv.union supp (fv t)) Sv.empty s
let is_binder : term -> bool = function
| Seq _ | ForAll _ | Exists _ | Find _ -> true
| _ -> false
let is_macro : term -> bool = function
| Macro _ -> true | _ -> false
let rec subst (s : subst) (t : term) : term =
if s = [] ||
(is_binder t &&
is_var_subst s &&
Sv.disjoint (subst_support s) (fv t))
then t
else
let new_term =
match t with
| Fun ((fs,is), fty, lt) ->
Fun ((fs, subst_vars s is), fty, List.map (subst s) lt)
| Name symb ->
Name { symb with s_indices = subst_vars s symb.s_indices}
| Macro (m, l, ts) ->
Macro (subst_macro s m, List.map (subst s) l, subst s ts)
| Var m -> Var m
| Action (a,indices) -> Action (a, subst_vars s indices)
| Diff (Explicit l) ->
Diff (Explicit (List.map (fun (lbl,tm) -> lbl, subst s tm) l))
| Seq ([], f) -> Seq ([], subst s f)
| Seq ([a], f) ->
let a, s = subst_binding a s in
let f = subst s f in
Seq ([a],f)
| Seq (a :: vs, f) ->
let a, s = subst_binding a s in
let f = subst s (Seq (vs,f)) in
let vs, f = match f with
| Seq (vs, f) -> vs, f
| _ -> assert false in
Seq (a :: vs,f)
| ForAll ([], f) -> subst s f
| ForAll (a :: vs, f) ->
let a, s = subst_binding a s in
let f = subst s (ForAll (vs,f)) in
mk_forall [a] f
| Exists ([], f) -> subst s f
| Exists (a :: vs, f) ->
let a, s = subst_binding a s in
let f = subst s (Exists (vs,f)) in
mk_exists [a] f
| Find ([], b, c, d) -> Find ([], subst s b, subst s c, subst s d)
| Find (v :: vs, b, c, d) ->
(* used because [v :: vs] are not bound in [d] *)
let dummy = mk_zero in
let v, s = subst_binding v s in
let f = subst s (Find (vs, b, c, dummy)) in
match f with
| Find (vs, b, c, _) -> Find (v :: vs, b, c, subst s d)
| _ -> assert false
in
assoc s new_term
and subst_binding : Vars.var -> subst -> Vars.var * subst =
fun var s ->
(* clear [v] entries in [s] *)
let s = filter_subst var s in
let right_fv =
List.fold_left (fun acc (ESubst (x, y)) ->
Sv.union acc (fv y)
) Sv.empty s in
let all_vars =
List.fold_left (fun acc (ESubst (x, y)) ->
Sv.union acc (fv x)
) right_fv s in
let env = ref (Vars.of_list (Sv.elements all_vars)) in
(* if [v] is appears in the RHS of [s], refresh [v] carefully *)
let var, s =
if Sv.mem var right_fv
then
let new_v = Vars.fresh_r env var in
let s = (ESubst (Var var,Var new_v)) :: s in
( new_v, s)
else ( var, s ) in
var, s
(*------------------------------------------------------------------*)
let subst_macros_ts table l ts t =
let rec subst_term (t : term) : term = match t with
| Macro (is, terms, ts') ->
let terms' = List.map subst_term terms in
begin match Symbols.Macro.get_all is.s_symb table with
| Symbols.State _, _ ->
if (List.mem (Symbols.to_string is.s_symb) l && ts=ts')
then Macro(is, terms', ts')
else Macro(is, terms', mk_pred ts')
| _ -> Macro(is, terms', ts')
end
| Diff (Explicit l) ->
Diff (Explicit (List.map (fun (lbl,tm) -> lbl, subst_term tm) l))
| Fun (f,fty,terms) -> Fun (f, fty, List.map subst_term terms)
| Seq (a, b) -> Seq (a, subst_term b)
| Find (vs, b, t, e) -> Find (vs, subst_term b, subst_term t, subst_term e)
| ForAll (vs, b) -> ForAll (vs, subst_term b)
| Exists (vs, b) -> Exists (vs, subst_term b)
| Name _ | Action _ | Var _ -> t
in
subst_term t
(*------------------------------------------------------------------*)
let rec subst_ht s ht = match ht with
| Lambda (ev :: evs, t) ->
let ev, s = subst_binding ev s in
mk_lambda [ev] (subst_ht s (Lambda (evs, t)))
| Lambda ([], t) -> Lambda ([], subst s t)
(*------------------------------------------------------------------*)
(* sanity check *)
let check_projs_subst (s : (proj * proj) list) : unit =
assert (
List.for_all (fun (p1, p2) ->
List.for_all (fun (p1', p2') ->
p1 = p1' && p2 = p2' ||
(p1 <> p1' && p2 <> p2')
) s
) s)
let subst_projs (s : (proj * proj) list) (t : term) : term =
check_projs_subst s;
let rec do_subst : term -> term = function
| Diff (Explicit l) ->
Diff (Explicit (List.map (fun (p, t) -> List.assoc_dflt p p s, t) l))
| _ as t -> tmap do_subst t
in
do_subst t
(*------------------------------------------------------------------*)
type refresh_arg = [`Global | `InEnv of Vars.env ref ]
let refresh_var (arg : refresh_arg) v =
match arg with
| `Global -> Vars.make_new_from v
| `InEnv env -> Vars.fresh_r env v
(* The substitution must be built reversed w.r.t. vars, to handle capture. *)
let refresh_vars (arg : refresh_arg) evars =
let l =
List.rev_map (fun v ->
let v' = refresh_var arg v in
v', ESubst (Var v, Var v')
) evars
in
let vars, subst = List.split l in
List.rev vars, subst
let refresh_vars_env env vs =
let env = ref env in
let vs, s = refresh_vars (`InEnv env) vs in
!env, vs, s
(*------------------------------------------------------------------*)
* { 2 Smart constructors and destructors -- Part 2 }
module type SmartFO = sig
type form
* { 3 Constructors }
val mk_true : form
val mk_false : form
val mk_eq : ?simpl:bool -> term -> term -> form
val mk_leq : ?simpl:bool -> term -> term -> form
val mk_geq : ?simpl:bool -> term -> term -> form
val mk_lt : ?simpl:bool -> term -> term -> form
val mk_gt : ?simpl:bool -> term -> term -> form
val mk_not : ?simpl:bool -> form -> form
val mk_and : ?simpl:bool -> form -> form -> form
val mk_ands : ?simpl:bool -> form list -> form
val mk_or : ?simpl:bool -> form -> form -> form
val mk_ors : ?simpl:bool -> form list -> form
val mk_impl : ?simpl:bool -> form -> form -> form
val mk_impls : ?simpl:bool -> form list -> form -> form
val mk_forall : ?simpl:bool -> Vars.vars -> form -> form
val mk_exists : ?simpl:bool -> Vars.vars -> form -> form
(*------------------------------------------------------------------*)
(** {3 Destructors} *)
val destr_forall : form -> (Vars.var list * form) option
val destr_forall1 : form -> (Vars.var * form) option
val destr_exists : form -> (Vars.var list * form) option
val destr_exists1 : form -> (Vars.var * form) option
(*------------------------------------------------------------------*)
val destr_neq : form -> (term * term) option
val destr_eq : form -> (term * term) option
val destr_leq : form -> (term * term) option
val destr_lt : form -> (term * term) option
(*------------------------------------------------------------------*)
val destr_false : form -> unit option
val destr_true : form -> unit option
val destr_not : form -> form option
val destr_and : form -> (form * form) option
val destr_or : form -> (form * form) option
val destr_impl : form -> (form * form) option
(*------------------------------------------------------------------*)
val is_false : form -> bool
val is_true : form -> bool
val is_not : form -> bool
val is_zero : form -> bool
val is_and : form -> bool
val is_or : form -> bool
val is_impl : form -> bool
val is_forall : form -> bool
val is_exists : form -> bool
(*------------------------------------------------------------------*)
val is_neq : form -> bool
val is_eq : form -> bool
val is_leq : form -> bool
val is_lt : form -> bool
(*------------------------------------------------------------------*)
(** left-associative *)
val destr_ands : int -> form -> form list option
val destr_ors : int -> form -> form list option
val destr_impls : int -> form -> form list option
(*------------------------------------------------------------------*)
val decompose_forall : form -> Vars.var list * form
val decompose_exists : form -> Vars.var list * form
(*------------------------------------------------------------------*)
val decompose_ands : form -> form list
val decompose_ors : form -> form list
val decompose_impls : form -> form list
val decompose_impls_last : form -> form list * form
end
module Smart : SmartFO with type form = term = struct
type form = term
include SmartConstructors
include SmartDestructors
FIXME : improve variable naming ( see )
let mk_forall ?(simpl=false) l f =
let l =
if simpl then
let fv = fv f in
List.filter (fun v -> Sv.mem v fv) l
else l
in
mk_forall l f
FIXME : improve variable naming ( see )
let mk_exists ?(simpl=false) l f =
let l =
if simpl then
let fv = fv f in
List.filter (fun v -> Sv.mem v fv) l
else l
in
mk_exists l f
end
include Smart
let mk_atom (o : ord) (t1 : term) (t2 : term) : term =
match o with
| `Eq -> mk_eq t1 t2
| `Leq -> mk_leq t1 t2
| `Lt -> mk_lt t1 t2
| `Neq -> mk_neq t1 t2
| `Geq -> mk_geq t1 t2
| `Gt -> mk_gt t1 t2
let xatom_to_form (l : xatom) : term = match l with
| `Comp (ord, t1, t2) -> mk_atom ord t1 t2
| `Happens l -> mk_happens l
let lit_to_form (l : literal) : term =
match l with
| `Pos, at -> xatom_to_form at
| `Neg, at -> mk_not (xatom_to_form at)
let mk_seq0 ?(simpl=false) (is : Vars.vars) term =
let is =
if simpl then
let term_fv = fv term in
List.filter (fun i ->
Sv.mem i term_fv
) is
else is
in
match is with
| [] -> term
| _ -> Seq (is, term)
(* only refresh necessary vars, hence we need an environment *)
let mk_seq env (is : Vars.vars) term =
let env =
let env_vars = Sv.of_list (Vars.to_list env) in
let term_vars = fv term in
let vars = Sv.elements (Sv.inter env_vars term_vars) in
ref (Vars.of_list vars)
in
let is, s = refresh_vars (`InEnv env) is in
let term = subst s term in
match is with
| [] -> term
| _ -> Seq (is, term)
(*------------------------------------------------------------------*)
* { 2 Apply }
let apply_ht (ht : hterm) (terms : term list) = match ht with
| Lambda (evs, t) ->
assert (List.length terms <= List.length evs);
let evs0, evs1 = List.takedrop (List.length terms) evs in
let evs0, s = refresh_vars `Global evs0 in
let ht = subst_ht s (Lambda (evs1, t)) in
let s_app =
List.map2 (fun v t -> ESubst (Var v, t)) evs0 terms
in
subst_ht s_app ht
(*------------------------------------------------------------------*)
* { 2 Type substitution }
let tsubst (ts : Type.tsubst) (t : term) : term =
no need to substitute in the types of [ Name ] , [ Macro ] , [ Fun ]
let rec tsubst : term -> term = function
| Var v -> Var (Vars.tsubst ts v)
| ForAll (vs, f) -> ForAll (List.map (Vars.tsubst ts) vs, tsubst f)
| Exists (vs, f) -> Exists (List.map (Vars.tsubst ts) vs, tsubst f)
| _ as term -> tmap (fun t -> tsubst t) term
in
tsubst t
let tsubst_ht (ts : Type.tsubst) (ht : hterm) : hterm =
match ht with
| Lambda (vs, f) -> Lambda (List.map (Vars.tsubst ts) vs, tsubst ts f)
(*------------------------------------------------------------------*)
* { 2 Simplification }
let rec not_simpl = function
| Exists (vs, f) -> ForAll(vs, not_simpl f)
| ForAll (vs, f) -> Exists(vs, not_simpl f)
| tt when tt = mk_true -> mk_false
| tf when tf = mk_false -> mk_true
| Fun (fs, _, [a;b]) when fs = f_and -> mk_or (not_simpl a) (not_simpl b)
| Fun (fs, _, [a;b]) when fs = f_or -> mk_and (not_simpl a) (not_simpl b)
| Fun (fs, _, [a;b]) when fs = f_impl -> mk_and a (not_simpl b)
| Fun (fs, _, [f]) when fs = f_not -> f
| Fun (fs, _, [a;b]) when fs = f_eq -> mk_neq a b
| Fun (fs, _, [a;b]) when fs = f_neq -> mk_eq a b
| m -> mk_not m
(*------------------------------------------------------------------*)
let is_deterministic (t : term) : bool =
let exception NonDet in
let rec is_det : term -> unit = function
| Name _ | Macro _ -> raise NonDet
| t -> titer is_det t
in
try is_det t; true with NonDet -> false
let is_pure_timestamp (t : term) =
let rec pure_ts = function
| Fun (fs, _, [t]) when fs = f_happens || fs = f_pred -> pure_ts t
| Fun (fs, _, [t1; t2])
when fs = f_or || fs = f_and || fs = f_impl ||
fs = f_eq || fs = f_neq || fs = f_leq || fs = f_lt ||
fs = f_geq || fs = f_gt ->
pure_ts t1 && pure_ts t2
| Fun (fs, _, [t]) when fs = f_not -> pure_ts t
| Fun (fs, _, []) -> true
| ForAll (_, t)
| Exists (_, t) -> pure_ts t
| Action _ -> true
| Var v -> let ty = Vars.ty v in ty = Type.Timestamp || ty = Type.Index
| _ -> false
in
pure_ts t
(*------------------------------------------------------------------*)
* { 2 Projection }
let project1 (proj : proj) (term : term) : term =
let rec project1 (t : term) : term =
match t with
(* do not recurse, as subterms cannot contain any diff *)
| Diff (Explicit l) -> List.assoc proj l
| _ -> tmap project1 t
in
project1 term
(*------------------------------------------------------------------*)
let project (projs : proj list) (term : term) : term =
let rec project (t : term) : term =
match t with
| Diff (Explicit l) ->
(* we only project over a subset of [l]'s projs *)
assert (List.for_all (fun x -> List.mem_assoc x l) projs);
(* do not recurse, as subterms cannot contain any diff *)
mk_diff (List.filter (fun (x,_) -> List.mem x projs) l)
| _ -> tmap project t
in
project term
let project_opt (projs : projs option) (term : term) : term =
omap_dflt term (project ^~ term) projs
(*------------------------------------------------------------------*)
* Evaluate topmost diff operators for a given proj of a biterm .
For example [ head_pi_term left ( diff(a , b ) ) ] is [ a ]
and [ head_pi_term left f(diff(a , b),c ) ] is [ f(diff(a , b),c ) ] .
For example [head_pi_term left (diff(a,b))] is [a]
and [head_pi_term left f(diff(a,b),c)] is [f(diff(a,b),c)]. *)
let head_pi_term (s : proj) (t : term) : term =
match t with
| Diff (Explicit l) -> List.assoc s l
| _ -> t
let diff a b =
if a = b then a else
Diff (Explicit [left_proj,a; right_proj,b])
let rec make_normal_biterm (dorec : bool) (t : term) : term =
let mdiff (t : term) (t' : term) : term =
if dorec then make_normal_biterm dorec (diff t t')
else diff t t'
in
TODO generalize to non - binary diff
match head_pi_term left_proj t, head_pi_term right_proj t with
| Fun (f,fty,l), Fun (f',fty',l') when f = f' ->
Fun (f, fty, List.map2 mdiff l l')
| Name n, Name n' when n=n' -> Name n
| Macro (m,l,ts), Macro (m',l',ts') when m = m' && ts = ts' ->
Macro (m, List.map2 mdiff l l', ts)
| Action (a,is), Action (a',is') when a = a' && is = is' -> Action (a,is)
| Var x, Var x' when x=x' -> Var x
| Find (is,c,t,e), Find (is',c',t',e') when is = is' ->
Find (is, mdiff c c', mdiff t t', mdiff e e')
| ForAll (vs,f), ForAll (vs',f') when vs = vs' -> ForAll (vs, mdiff f f')
| Exists (vs,f), Exists (vs',f') when vs = vs' -> Exists (vs, mdiff f f')
| t1,t2 -> diff t1 t2
let simple_bi_term : term -> term = make_normal_biterm true
let head_normal_biterm : term -> term = make_normal_biterm false
(*------------------------------------------------------------------*)
let combine = function
| [_,t] -> t
| ["left",_;"right",_] as l ->
simple_bi_term (Diff (Explicit l))
| _ -> assert false
(*------------------------------------------------------------------*)
let rec diff_names = function
| Name _ -> true
| Diff (Explicit l) -> List.for_all (fun (_,tm) -> diff_names tm) l
| _ -> false
(*------------------------------------------------------------------*)
* { 2 Sets and Maps }
module T = struct
type t = term
let compare = Stdlib.compare
end
module Mt = Map.Make (T)
module St = Set.Make (T)
(*------------------------------------------------------------------*)
* { 2 Matching information for error messages }
type match_info =
| MR_ok (* term matches *)
| MR_check_st of term list (* need to look at subterms *)
| MR_failed (* term does not match *)
type match_infos = match_info Mt.t
let pp_match_info fmt = function
| MR_ok -> Fmt.pf fmt "ok"
| MR_check_st terms -> Fmt.pf fmt "check subterms %a" (Fmt.list pp) terms
| MR_failed -> Fmt.pf fmt "failed"
let pp_match_infos fmt minfos =
let pp_one fmt (t, mi) = Fmt.pf fmt "%a → %a" pp t pp_match_info mi in
Fmt.pf fmt "@[<v 0>%a@]" (Fmt.list pp_one) (Mt.bindings minfos)
let match_infos_to_pp_info (minfos : match_infos) : pp_info =
let styler info (t : term) : Printer.keyword option * pp_info =
match Mt.find_opt t minfos with
| None -> None, info
| Some MR_ok -> None, default_pp_info
| Some MR_check_st _ -> None, info
| Some MR_failed -> Some `Error, info
in
{ styler }
(*------------------------------------------------------------------*)
* { 2 Term heads }
type term_head =
| HExists
| HForAll
| HSeq
| HFind
| HFun of Symbols.fname
| HMacro of Symbols.macro
| HName of Symbols.name
| HDiff
| HVar
| HAction
let pp_term_head fmt = function
| HExists -> Fmt.pf fmt "Exists"
| HForAll -> Fmt.pf fmt "Forall"
| HSeq -> Fmt.pf fmt "Seq"
| HFind -> Fmt.pf fmt "Find"
| HFun f -> Fmt.pf fmt "Fun %a" Symbols.pp f
| HMacro m -> Fmt.pf fmt "Macro %a" Symbols.pp m
| HName n -> Fmt.pf fmt "Name %a" Symbols.pp n
| HDiff -> Fmt.pf fmt "Diff"
| HVar -> Fmt.pf fmt "Var"
| HAction -> Fmt.pf fmt "Action"
let get_head : term -> term_head = function
| Exists _ -> HExists
| ForAll _ -> HForAll
| Seq _ -> HSeq
| Fun ((f,_),_,_) -> HFun f
| Find _ -> HFind
| Macro (m1,_,_) -> HMacro m1.s_symb
| Name n1 -> HName n1.s_symb
| Diff _ -> HDiff
| Var _ -> HVar
| Action _ -> HAction
module Hm = Map.Make(struct
type t = term_head
let compare = Stdlib.compare
end)
(*------------------------------------------------------------------*)
(** {2 Patterns} *)
(** A pattern is a list of free type variables, a term [t] and a subset
of [t]'s free variables that must be matched.
The free type variables must be inferred. *)
type 'a pat = {
pat_tyvars : Type.tvars;
pat_vars : Vars.Sv.t;
pat_term : 'a;
}
let pat_of_form (t : term) =
let vs, t = decompose_forall t in
let vs, s = refresh_vars `Global vs in
let t = subst s t in
{ pat_tyvars = [];
pat_vars = Vars.Sv.of_list vs;
pat_term = t; }
let project_tpat (projs : projs) (pat : term pat) : term pat =
{ pat with pat_term = project projs pat.pat_term; }
let project_tpat_opt (projs : projs option) (pat : term pat) : term pat
=
omap_dflt pat (project_tpat ^~ pat) projs
(*------------------------------------------------------------------*)
* { 2 Tests }
let () =
let mkvar x s = Var (snd (Vars.make `Approx Vars.empty_env s x)) in
Checks.add_suite "Head normalization" [
"Macro, different ts", `Quick, begin fun () ->
let ts = mkvar "ts" Type.Timestamp in
let ts' = mkvar "ts'" Type.Timestamp in
let m = in_macro in
let t = diff (Macro (m,[],ts)) (Macro (m,[],ts')) in
let r = head_normal_biterm t in
assert (r = t)
end ;
"Boolean operator", `Quick, begin fun () ->
let f = mkvar "f" Type.Boolean in
let g = mkvar "g" Type.Boolean in
let f' = mkvar "f'" Type.Boolean in
let g' = mkvar "g'" Type.Boolean in
let t = diff (mk_and f g) (mk_and f' g') in
assert (head_normal_biterm t = mk_and (diff f f') (diff g g'))
end ;
]
| null | https://raw.githubusercontent.com/squirrel-prover/squirrel-prover/c86fe5a24fbfa4db34adc01c11d8d7718a8bf870/src/term.ml | ocaml | ------------------------------------------------------------------
* {2 Symbols}
* Ocaml type of a typed index symbol.
Invariant: [s_typ] do not contain tvar or univars
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
ignore the type
------------------------------------------------------------------
------------------------------------------------------------------
* Boolean connectives
* Comparisons
* Fail
* Xor and its unit
* Successor over natural numbers
* Adversary function
* Pairing
* Boolean to Message
* Empty
* Length
* Init action
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
* Smart constructors.
The module is included after its definition.
* Some smart constructors are redefined later, after substitutions.
------------------------------------------------------------------
------------------------------------------------------------------
* Operations on vectors of indices of the same length.
------------------------------------------------------------------
* {2 Typing}
------------------------------------------------------------------
ty_env should be closed
------------------------------------------------------------------
* {2 Destructors}
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
let destr_neq f = oas_seq2 (obind (destr_fun ~fs:f_eq) (destr_not f))
------------------------------------------------------------------
------------------------------------------------------------------
* for any associative [fs]
------------------------------------------------------------------
is_pair is unused but having it seems to make sense
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
* Additional printing information
------------------------------------------------------------------
binary
------------------------------------------------------------------
* Applies the styling info in [info]
NOTE: this is *not* the [pp] exported by the module, it is shadowed later
* Core printing function
if-then-else, no else
if-then-else, true/false
if-then-else, general case
prints the [else]
pair
iff. <=>
happens
infix
not
true/false
constant
function symbol, general case
prints the [else]
Printing in a [hv] box. Print the trailing [else] of the caller.
Printing in a [hv] box. Print the trailing [else] of the caller.
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
* Literals.
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
* Declare input and output macros.
------------------------------------------------------------------
* Substitutions
------------------------------------------------------------------
------------------------------------------------------------------
* Does not recurse.
------------------------------------------------------------------
* given a variable [x] and a subst [s], remove from [s] all
substitution [v->_].
* Check if the substitutions only susbtitutes variables
used because [v :: vs] are not bound in [d]
clear [v] entries in [s]
if [v] is appears in the RHS of [s], refresh [v] carefully
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
sanity check
------------------------------------------------------------------
The substitution must be built reversed w.r.t. vars, to handle capture.
------------------------------------------------------------------
------------------------------------------------------------------
* {3 Destructors}
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
* left-associative
------------------------------------------------------------------
------------------------------------------------------------------
only refresh necessary vars, hence we need an environment
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
do not recurse, as subterms cannot contain any diff
------------------------------------------------------------------
we only project over a subset of [l]'s projs
do not recurse, as subterms cannot contain any diff
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
term matches
need to look at subterms
term does not match
------------------------------------------------------------------
------------------------------------------------------------------
* {2 Patterns}
* A pattern is a list of free type variables, a term [t] and a subset
of [t]'s free variables that must be matched.
The free type variables must be inferred.
------------------------------------------------------------------ | open Utils
module L = Location
module Sv = Vars.Sv
module Mv = Vars.Mv
type 'a isymb = {
s_symb : 'a;
s_indices : Vars.var list;
s_typ : Type.ty;
}
let mk_isymb (s : 'a) (t : Type.ty) (is : Vars.vars) =
let () = match t with
| Type.TVar _ | Type.TUnivar _ -> assert false;
| _ -> ()
in
assert (
List.for_all (fun v ->
Type.equal (Vars.ty v) Type.tindex ||
Type.equal (Vars.ty v) Type.ttimestamp
) is);
{ s_symb = s;
s_typ = t;
s_indices = is; }
type name = Symbols.name
type nsymb = name isymb
type fname = Symbols.fname
type fsymb = fname * Vars.var list
type mname = Symbols.macro
type msymb = mname isymb
type state = msymb
let pp_name ppf s = (Printer.kws `GoalName) ppf (Symbols.to_string s)
let pp_nsymb ppf (ns : nsymb) =
if ns.s_indices <> []
then Fmt.pf ppf "%a(%a)" pp_name ns.s_symb Vars.pp_list ns.s_indices
else Fmt.pf ppf "%a" pp_name ns.s_symb
let pp_nsymbs ppf (l : nsymb list) =
Fmt.pf ppf "@[<hov>%a@]"
(Fmt.list ~sep:(fun ppf () -> Fmt.pf ppf ", ") pp_nsymb) l
let pp_fname ppf s = (Printer.kws `GoalFunction) ppf (Symbols.to_string s)
let pp_fsymb ppf (fn,is) = match is with
| [] -> Fmt.pf ppf "%a" pp_fname fn
| _ -> Fmt.pf ppf "%a(%a)" pp_fname fn Vars.pp_list is
let pp_mname_s ppf s =
(Printer.kws `GoalMacro) ppf s
let pp_mname ppf s =
pp_mname_s ppf (Symbols.to_string s)
let pp_msymb ppf (ms : msymb) =
Fmt.pf ppf "%a%a"
pp_mname ms.s_symb
(Utils.pp_ne_list "(%a)" Vars.pp_list) ms.s_indices
* { 2 Atoms and terms }
type proj = string
type projs = proj list
let proj_from_string x : proj = x
let proj_to_string x : string = x
let pp_proj fmt (x : proj) = Fmt.string fmt x
let pp_projs fmt (l : projs) = Fmt.list ~sep:Fmt.comma pp_proj fmt l
let left_proj = "left"
let right_proj = "right"
module Sproj = Ss
module Mproj = Ms
type 'a diff_args =
| Explicit of (proj * 'a) list
type term =
| Fun of fsymb * Type.ftype * term list
| Name of nsymb
| Macro of msymb * term list * term
| Seq of Vars.var list * term
| Action of Symbols.action * Vars.var list
| Var of Vars.var
| Diff of term diff_args
| Find of Vars.var list * term * term * term
| ForAll of Vars.var list * term
| Exists of Vars.var list * term
type t = term
type terms = term list
let rec hash : term -> int = function
| Name n -> hcombine 0 (hash_isymb n)
| Fun ((f, is),_,terms) ->
let h = Symbols.hash f in
let h = hcombine_list Vars.hash h is in
hcombine 1 (hash_l terms h)
| Macro (m, l, ts) ->
let h = hcombine_list hash (hash_isymb m) l in
hcombine 2 (hcombine h (hash ts))
| Seq (vars, b) ->
let h = hcombine_list Vars.hash (hash b) vars in
hcombine 3 h
| Diff (Explicit l) -> hcombine 5 (hash_l (List.map snd l) 3)
| Find (b, c, d, e) ->
let h = hcombine_list Vars.hash 6 b in
hash_l [c;d;e] h
| ForAll (vs, b) ->
let h = hcombine_list Vars.hash (hash b) vs in
hcombine 7 h
| Exists (vs, b) ->
let h = hcombine_list Vars.hash (hash b) vs in
hcombine 8 h
| Var v -> hcombine 10 (Vars.hash v)
| Action (s, is) ->
let h = hcombine_list Vars.hash (Symbols.hash s) is in
hcombine 11 h
and hash_l (l : term list) (h : int) : int =
hcombine_list hash h l
and hash_isymb : type a. a Symbols.t isymb -> int =
fun symb ->
let h = Symbols.hash symb.s_symb in
hcombine_list Vars.hash h symb.s_indices
* { 2 Higher - order terms }
type hterm = Lambda of Vars.vars * term
* { 2 Builtins function symbols }
let mk f : fsymb = (f,[])
let f_diff = mk Symbols.fs_diff
let f_happens = mk Symbols.fs_happens
let f_pred = mk Symbols.fs_pred
let f_witness = mk Symbols.fs_witness
let f_false = mk Symbols.fs_false
let f_true = mk Symbols.fs_true
let f_and = mk Symbols.fs_and
let f_or = mk Symbols.fs_or
let f_impl = mk Symbols.fs_impl
let f_not = mk Symbols.fs_not
let f_ite = mk Symbols.fs_ite
let f_eq = mk Symbols.fs_eq
let f_neq = mk Symbols.fs_neq
let f_leq = mk Symbols.fs_leq
let f_lt = mk Symbols.fs_lt
let f_geq = mk Symbols.fs_geq
let f_gt = mk Symbols.fs_gt
let f_fail = mk Symbols.fs_fail
let f_xor = mk Symbols.fs_xor
let f_zero = mk Symbols.fs_zero
let f_succ = mk Symbols.fs_succ
let f_att = mk Symbols.fs_att
let f_pair = mk Symbols.fs_pair
let f_fst = mk Symbols.fs_fst
let f_snd = mk Symbols.fs_snd
let f_of_bool = mk Symbols.fs_of_bool
let empty =
let fty = Symbols.ftype_builtin Symbols.fs_empty in
Fun (mk Symbols.fs_empty, fty, [])
let f_len = mk Symbols.fs_len
let f_zeroes = mk Symbols.fs_zeroes
let init = Action(Symbols.init_action,[])
* { 2 Smart constructors }
let mk_var (v : Vars.var) : term = Var v
let mk_action a is = Action (a,is)
let mk_name n = Name n
let mk_macro ms l t = Macro (ms, l, t)
let mk_diff l =
assert
(let projs = List.map fst l in
List.sort Stdlib.compare projs = List.sort_uniq Stdlib.compare projs);
match l with
| [] -> assert false
| [_, t] -> t
| _ -> Diff (Explicit l)
let mk_fun0 fs fty terms = Fun (fs, fty, terms)
let mk_fun table fname indices terms =
let fty = Symbols.ftype table fname in
Fun ((fname,indices), fty, terms)
let mk_fbuiltin = mk_fun Symbols.builtins_table
* { 3 For first - order formulas }
module SmartConstructors = struct
let mk_true = mk_fbuiltin Symbols.fs_true [] []
let mk_false = mk_fbuiltin Symbols.fs_false [] []
let mk_not_ns term = mk_fbuiltin Symbols.fs_not [] [term]
let mk_and_ns t0 t1 = mk_fbuiltin Symbols.fs_and [] [t0;t1]
let mk_or_ns t0 t1 = mk_fbuiltin Symbols.fs_or [] [t0;t1]
let mk_impl_ns t0 t1 = mk_fbuiltin Symbols.fs_impl [] [t0;t1]
let mk_eq_ns t0 t1 = mk_fbuiltin Symbols.fs_eq [] [t0;t1]
let mk_neq_ns t0 t1 = mk_fbuiltin Symbols.fs_neq [] [t0;t1]
let mk_leq_ns t0 t1 = mk_fbuiltin Symbols.fs_leq [] [t0;t1]
let mk_lt_ns t0 t1 = mk_fbuiltin Symbols.fs_lt [] [t0;t1]
let mk_geq_ns t0 t1 = mk_fbuiltin Symbols.fs_geq [] [t0;t1]
let mk_gt_ns t0 t1 = mk_fbuiltin Symbols.fs_gt [] [t0;t1]
let mk_not ?(simpl=true) t1 = match t1 with
| Fun (fs,_,[t]) when fs = f_not && simpl -> t
| t -> mk_not_ns t
let mk_eq ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_true else mk_eq_ns t1 t2
let mk_neq ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_false else mk_neq_ns t1 t2
let mk_leq ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_true else mk_leq_ns t1 t2
let mk_geq ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_true else mk_geq_ns t1 t2
let mk_lt ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_false else mk_lt_ns t1 t2
let mk_gt ?(simpl=false) t1 t2 : term =
if t1 = t2 && simpl then mk_false else mk_gt_ns t1 t2
let mk_and ?(simpl=true) t1 t2 = match t1,t2 with
| tt, _ when tt = mk_false && simpl -> mk_false
| _, tt when tt = mk_false && simpl -> mk_false
| tt, t when tt = mk_true && simpl -> t
| t, tt when tt = mk_true && simpl -> t
| t1,t2 -> mk_and_ns t1 t2
let mk_ands ?(simpl=true) ts = List.fold_right (mk_and ~simpl) ts mk_true
let mk_or ?(simpl=true) t1 t2 = match t1,t2 with
| tt, _ when tt = mk_true && simpl -> mk_true
| _, tt when tt = mk_true && simpl -> mk_true
| tf, t when tf = mk_false && simpl -> t
| t, tf when tf = mk_false && simpl -> t
| t1,t2 -> mk_or_ns t1 t2
let mk_ors ?(simpl=true) ts = List.fold_right (mk_or ~simpl) ts mk_false
let mk_impl ?(simpl=true) t1 t2 = match t1,t2 with
| tf, _ when tf = mk_false && simpl -> mk_true
| tt, t when tt = mk_true && simpl -> t
| t1,t2 -> mk_impl_ns t1 t2
let mk_impls ?(simpl=true) ts t =
List.fold_left (fun tres t0 -> (mk_impl ~simpl) t0 tres) t ts
let mk_forall l f =
if l = [] then f
else match f with
| ForAll (l', f) -> ForAll (l @ l', f)
| _ -> ForAll (l, f)
let mk_exists l f =
if l = [] then f
else match f with
| Exists (l', f) -> Exists (l @ l', f)
| _ -> Exists (l, f)
let mk_happens t = mk_fbuiltin Symbols.fs_happens [] [t]
let mk_pred t = mk_fbuiltin Symbols.fs_pred [] [t]
end
include SmartConstructors
* { 3 For terms }
let mk_zero = mk_fbuiltin Symbols.fs_zero [] []
let mk_fail = mk_fbuiltin Symbols.fs_fail [] []
let mk_len term = mk_fbuiltin Symbols.fs_len [] [term]
let mk_zeroes term = mk_fbuiltin Symbols.fs_zeroes [] [term]
let mk_pair t0 t1 = mk_fbuiltin Symbols.fs_pair [] [t0;t1]
let mk_ite ?(simpl=true) c t e =
match c with
| t when t = mk_true && simpl -> t
| t when t = mk_false && simpl -> e
| _ -> mk_fbuiltin Symbols.fs_ite [] [c;t;e]
let mk_of_bool t = mk_fbuiltin Symbols.fs_of_bool [] [t]
let mk_witness ty =
let fty = Type.mk_ftype 0 [] [] ty in
Fun (f_witness, fty, [])
let mk_find ?(simpl=false) is c t e =
if not simpl then Find (is, c, t, e)
else if c = mk_false then e else Find (is, c, t, e)
* { 3 For formulas }
let mk_timestamp_leq t1 t2 = match t1,t2 with
| _, Fun (f,_, [t2']) when f = f_pred -> mk_lt t1 t2'
| _ -> mk_leq t1 t2
let mk_indices_neq (vect_i : Vars.var list) vect_j =
mk_ors ~simpl:true
(List.map2 (fun i j ->
mk_neq (mk_var i) (mk_var j)
) vect_i vect_j)
let mk_indices_eq ?(simpl=true) vect_i vect_j =
mk_ands ~simpl:true
(List.map2 (fun i j ->
mk_eq ~simpl (mk_var i) (mk_var j)
) vect_i vect_j)
let mk_lambda evs ht = match ht with
| Lambda (evs', t) -> Lambda (evs @ evs', t)
let ty ?ty_env (t : term) : Type.ty =
let must_close, ty_env = match ty_env with
| None -> true, Type.Infer.mk_env ()
| Some ty_env -> false, ty_env
in
let rec ty (t : term) : Type.ty =
match t with
| Fun (_,fty,terms) ->
let fty = Type.open_ftype ty_env fty in
let () =
List.iter2 (fun arg arg_ty ->
match Type.Infer.unify_leq ty_env (ty arg) arg_ty with
| `Ok -> ()
| `Fail -> assert false
) terms fty.Type.fty_args
in
fty.Type.fty_out
| Name ns -> ns.s_typ
| Macro (s,_,_) -> s.s_typ
| Seq _ -> Type.Message
| Var v -> Vars.ty v
| Action _ -> Type.Timestamp
| Diff (Explicit l) -> ty (snd (List.hd l))
| Find (a, b, c, d) -> ty c
| ForAll _ -> Type.Boolean
| Exists _ -> Type.Boolean
in
let tty = ty t in
if must_close
else tty
let destr_fun ?fs = function
| Fun (fs', _, l) when fs = None -> Some l
| Fun (fs', _, l) when fs = Some fs' -> Some l
| _ -> None
let oas_seq0 = omap as_seq0
let oas_seq1 = omap as_seq1
let oas_seq2 = omap as_seq2
* { 3 For first - order formulas }
* .
The module is included after its definition .
The module is included after its definition. *)
module SmartDestructors = struct
let destr_exists1 = function
| Exists (v :: vs, f) -> Some (v, mk_exists vs f)
| _ -> None
let rec destr_exists = function
| Exists (vs, f) ->
begin
match destr_exists f with
| Some (vs', f) -> Some (vs @ vs', f)
| None -> Some (vs, f)
end
| _ -> None
let rec decompose_exists = function
| Exists (vs, f) ->
let vs', f0 = decompose_exists f in
vs @ vs', f0
| _ as f -> [], f
let destr_forall1 = function
| ForAll (v :: vs, f) -> Some (v, mk_forall vs f)
| _ -> None
let rec destr_forall = function
| ForAll (vs, f) ->
begin
match destr_forall f with
| Some (vs', f) -> Some (vs @ vs', f)
| None -> Some (vs, f)
end
| _ -> None
let rec decompose_forall = function
| ForAll (vs, f) ->
let vs', f0 = decompose_forall f in
vs @ vs', f0
| _ as f -> [], f
let destr_false f = oas_seq0 (destr_fun ~fs:f_false f)
let destr_true f = oas_seq0 (destr_fun ~fs:f_true f)
let destr_zero f = oas_seq0 (destr_fun ~fs:f_zero f)
let destr_not f = oas_seq1 (destr_fun ~fs:f_not f)
let destr_or f = oas_seq2 (destr_fun ~fs:f_or f)
let destr_and f = oas_seq2 (destr_fun ~fs:f_and f)
let destr_impl f = oas_seq2 (destr_fun ~fs:f_impl f)
let destr_pair f = oas_seq2 (destr_fun ~fs:f_pair f)
let destr_iff f =
match f with
| Fun (fs, _, [Fun (fs1, _, [t1 ; t2]);
Fun (fs2, _, [t2'; t1'])])
when fs = f_and && fs1 = f_impl && fs2 = f_impl ->
if t1 = t1' && t2 = t2' then Some (t1, t2) else None
| _ -> None
let destr_neq f = oas_seq2 (destr_fun ~fs:f_neq f)
let destr_eq f = oas_seq2 (destr_fun ~fs:f_eq f)
let destr_leq f = oas_seq2 (destr_fun ~fs:f_leq f)
let destr_lt f = oas_seq2 (destr_fun ~fs:f_leq f)
* for [ fs ] of arity 2 , left associative
let[@warning "-32"] mk_destr_many_left fs =
let rec destr l f =
if l < 0 then assert false;
if l = 1 then Some [f]
else match destr_fun ~fs f with
| None -> None
| Some [f;g] -> omap (fun l -> l @ [g]) (destr (l-1) f)
| _ -> assert false
in
destr
* for [ fs ] of arity 2 , right associative
let mk_destr_many_right fs =
let rec destr l f =
assert (l > 0);
if l = 1 then Some [f]
else match destr_fun ~fs f with
| None -> None
| Some [f;g] -> omap (fun l -> f :: l) (destr (l-1) g)
| _ -> assert false
in
destr
let destr_ors = mk_destr_many_right f_or
let destr_ands = mk_destr_many_right f_and
let destr_impls = mk_destr_many_right f_impl
let mk_decompose fs =
let rec decompose f = match destr_fun ~fs f with
| None -> [f]
| Some l -> List.concat_map decompose l
in
decompose
let decompose_ors = mk_decompose f_or
let decompose_ands = mk_decompose f_and
let decompose_impls f =
let rec decompose f = match destr_fun ~fs:f_impl f with
| None -> [f]
| Some [f;g] -> f :: decompose g
| _ -> assert false
in
decompose f
let decompose_impls_last f =
let forms = decompose_impls f in
let rec last = function
| [] -> assert false
| [f] -> [], f
| f :: fs ->
let prems, goal = last fs in
f :: prems, goal
in
last forms
let is_false f = destr_false f <> None
let is_true f = destr_true f <> None
let is_not f = destr_not f <> None
let is_zero f = destr_zero f <> None
let is_or f = destr_or f <> None
let is_and f = destr_and f <> None
let is_impl f = destr_impl f <> None
let[@warning "-32"] is_pair f = destr_pair f <> None
let is_exists f = destr_exists f <> None
let is_forall f = destr_forall f <> None
let is_eq f = destr_eq f <> None
let is_neq f = destr_neq f <> None
let is_leq f = destr_leq f <> None
let is_lt f = destr_lt f <> None
end
include SmartDestructors
let is_name : term -> bool = function
| Name _ -> true
| _ -> false
let destr_var : term -> Vars.var option = function
| Var v -> Some v
| _ -> None
let is_var (t:term) : bool = destr_var t <> None
let destr_action = function
| Action (s,is) -> Some (s,is)
| _ -> None
* { 2 Printing }
let pp_indices ppf l =
if l <> [] then Fmt.pf ppf "(%a)" Vars.pp_list l
let pp_ord ppf = function
| `Eq -> Fmt.pf ppf "="
| `Neq -> Fmt.pf ppf "<>"
| `Leq -> Fmt.pf ppf "<="
| `Geq -> Fmt.pf ppf ">="
| `Lt -> Fmt.pf ppf "<"
| `Gt -> Fmt.pf ppf ">"
let rec is_and_happens = function
| Fun (f, _, [t]) when f = f_happens -> true
| _ as f -> match destr_and f with
| Some (l,r) -> is_and_happens l && is_and_happens r
| _ -> false
type pp_info = { styler : pp_info -> term -> Printer.keyword option * pp_info; }
let default_pp_info = { styler = fun info _ -> None, info; }
let styled_opt (err : Printer.keyword option) printer =
match err with
| None -> printer
| Some kw -> fun ppf t -> (Printer.kw kw ppf "%a" printer t)
let toplevel_prec = 0
let quant_fixity = 5 , `Prefix
let impl_fixity = 10 , `Infix `Right
let iff_fixity = 12 , `Infix `Right
let pair_fixity = 20 , `NoParens
let or_fixity = 20 , `Infix `Right
let and_fixity = 25 , `Infix `Right
let xor_fixity = 26 , `Infix `Right
let eq_fixity = 27 , `Infix `NonAssoc
let order_fixity = 29 , `Infix `NonAssoc
let ite_fixity = 40 , `Infix `Left
let other_infix_fixity = 50 , `Infix `Right
let not_fixity = 26 , `Prefix
let seq_fixity = 1000 , `Prefix
let find_fixity = 1000 , `Prefix
let macro_fixity = 1000 , `NoParens
let diff_fixity = 1000 , `NoParens
let fun_fixity = 1000 , `NoParens
let happens_fixity = 1000 , `NoParens
let get_infix_prec (f : Symbols.fname) =
else if f = Symbols.fs_or then fst or_fixity
else if f = Symbols.fs_impl then fst impl_fixity
else if f = Symbols.fs_xor then fst xor_fixity
else if f = Symbols.fs_eq then fst eq_fixity
else if f = Symbols.fs_neq then fst eq_fixity
else if f = Symbols.fs_leq then fst order_fixity
else if f = Symbols.fs_lt then fst order_fixity
else if f = Symbols.fs_gt then fst order_fixity
else if f = Symbols.fs_geq then fst order_fixity
else fst other_infix_fixity
let rec pp
(info : pp_info)
((outer,side) : ('b * fixity) * assoc)
(ppf : Format.formatter)
(t : term)
: unit
=
let err_opt, info = info.styler info t in
styled_opt err_opt (_pp info (outer, side)) ppf t
and _pp
(info : pp_info)
((outer,side) : ('b * fixity) * assoc)
(ppf : Format.formatter)
(t : term)
: unit
=
let pp = pp info in
match t with
| Var m -> Fmt.pf ppf "%a" Vars.pp m
| Fun (s,_,[a]) when s = f_happens -> pp_happens info ppf [a]
| Fun (s,_,[b;c; Fun (f,_,[])])
when s = f_ite && f = f_zero ->
let pp fmt () =
Fmt.pf ppf "@[<hov 2>if %a@ then@ %a@]"
(pp (ite_fixity, `NonAssoc)) b
(pp (ite_fixity, `Right)) c
in
maybe_paren ~outer ~side ~inner:ite_fixity pp ppf ()
| Fun (s,_,[b;Fun (f1,_,[]);Fun (f2,_,[])])
when s = f_ite && f1 = f_true && f2 = f_false ->
Fmt.pf ppf "%a"
(pp (ite_fixity, `NonAssoc)) b
| Fun (s,_,[a;b;c]) when s = f_ite ->
let pp fmt () =
Fmt.pf ppf "@[<hv 0>@[<hov 2>if %a@ then@ %a@]@ %a@]"
(pp (ite_fixity, `NonAssoc)) a
(pp (ite_fixity, `NonAssoc)) b
in
maybe_paren ~outer ~side ~inner:ite_fixity pp ppf ()
| Fun (s,_,terms) when s = f_pair ->
Fmt.pf ppf "%a"
(Utils.pp_ne_list
"<@[<hov>%a@]>"
(Fmt.list ~sep:(fun ppf () -> Fmt.pf ppf ",@,")
(pp (pair_fixity, `NonAssoc))))
terms
| Fun (fa,_,[Fun (fi1,_,[bl1;br1]);
Fun (fi2,_,[br2;bl2])])
when fa = f_and && fi1 = f_impl && fi2 = f_impl &&
bl1 = bl2 && br1 = br2 ->
let pp fmt () =
Fmt.pf ppf "@[%a@ <=>@ %a@]"
(pp (iff_fixity, `Left)) bl1
(pp (iff_fixity, `Right)) br1
in
maybe_paren ~outer ~side ~inner:iff_fixity pp ppf ()
| Fun _ as f when is_and_happens f ->
pp_and_happens info ppf f
| Fun ((s,is),_,[bl;br]) when Symbols.is_infix s ->
let assoc = Symbols.infix_assoc s in
let prec = get_infix_prec s in
assert (is = []);
let pp fmt () =
Fmt.pf ppf "@[<0>%a %s@ %a@]"
(pp ((prec, `Infix assoc), `Left)) bl
(Symbols.to_string s)
(pp ((prec, `Infix assoc), `Right)) br
in
maybe_paren ~outer ~side ~inner:(prec, `Infix assoc) pp ppf ()
| Fun (s,_,[b]) when s = f_not ->
Fmt.pf ppf "@[<hov 2>not(%a)@]" (pp (not_fixity, `Right)) b
| Fun _ as tt when tt = mk_true -> Fmt.pf ppf "true"
| Fun _ as tf when tf = mk_false -> Fmt.pf ppf "false"
| Fun (f,_,[]) ->
Fmt.pf ppf "%a" pp_fsymb f
arity one
| Fun (f,_,[a]) ->
Fmt.pf ppf "@[<hov 2>%a(@,%a)@]"
pp_fsymb f
(pp (fun_fixity, `NonAssoc)) a
| Fun (f,_,terms) ->
Fmt.pf ppf "@[<hov 2>%a(%a)@]"
pp_fsymb f
(Utils.pp_ne_list
"%a"
(Fmt.list ~sep:(fun ppf () -> Fmt.pf ppf ",@,")
(pp (fun_fixity, `NonAssoc))))
terms
| Name n -> pp_nsymb ppf n
| Macro (m, l, ts) ->
Fmt.pf ppf "@[%a%a@%a@]"
pp_msymb m
(Utils.pp_ne_list
"(@[<hov>%a@])"
(Fmt.list ~sep:Fmt.comma (pp (macro_fixity, `NonAssoc)))) l
(pp (macro_fixity, `NonAssoc)) ts
| Seq (vs, b) ->
Fmt.pf ppf "@[<hov 2>seq(%a->@,%a)@]"
Vars.pp_typed_list vs (pp (seq_fixity, `NonAssoc)) b
| Action (symb,indices) ->
Printer.kw `GoalAction ppf "%s%a" (Symbols.to_string symb) pp_indices indices
| Diff (Explicit l) ->
Fmt.pf ppf "@[<hov 2>diff(@,%a)@]"
(Fmt.list ~sep:(fun fmt () -> Format.fprintf fmt ",@ ")
(pp (diff_fixity, `NonAssoc)))
TODO labels
| Find (b, c, d, Fun (f,_,[])) when f = f_zero ->
let pp fmt () =
Fmt.pf ppf "@[<hv 0>\
@[<hov 2>try find %a such that@ %a@]@;<1 0>\
@[<hov 2>in@ %a@]@]"
Vars.pp_typed_list b
(pp (find_fixity, `NonAssoc)) c
(pp (find_fixity, `Right)) d
in
maybe_paren ~outer ~side ~inner:find_fixity pp ppf ()
| Find (b, c, d, e) ->
let pp fmt () =
Fmt.pf ppf "@[<hv 0>\
@[<hov 2>try find %a such that@ %a@]@;<1 0>\
@[<hov 2>in@ %a@]@;<1 0>\
%a@]"
Vars.pp_typed_list b
(pp (find_fixity, `NonAssoc)) c
(pp (find_fixity, `NonAssoc)) d
in
maybe_paren ~outer ~side ~inner:find_fixity pp ppf ()
| ForAll (vs, b) ->
let pp fmt () =
Fmt.pf ppf "@[<2>forall (@[%a@]),@ %a@]"
Vars.pp_typed_list vs
(pp (quant_fixity, `Right)) b
in
maybe_paren ~outer ~side ~inner:(fst quant_fixity, `Prefix) pp ppf ()
| Exists (vs, b) ->
let pp fmt () =
Fmt.pf ppf "@[<2>exists (@[%a@]),@ %a@]"
Vars.pp_typed_list vs
(pp (quant_fixity, `Right)) b
in
maybe_paren ~outer ~side ~inner:(fst quant_fixity, `Prefix) pp ppf ()
and pp_chained_ite info ppf (t : term) =
match t with
| Fun (s,_,[a;b;c]) when s = f_ite ->
Fmt.pf ppf "@[<hov 2>else if %a@ then@ %a@]@ %a"
(pp info (ite_fixity, `NonAssoc)) a
(pp info (ite_fixity, `NonAssoc)) b
(pp_chained_ite info) c
| _ -> Fmt.pf ppf "@[<hov 2>else@ %a@]" (pp info (ite_fixity, `Right)) t
and pp_chained_find info ppf (t : term) =
match t with
| Find (b, c, d, e) ->
Fmt.pf ppf "@[<hov 2>else try find %a such that@ %a@]@;<1 0>\
@[<hov 2>in@ %a@]@;<1 0>\
%a"
Vars.pp_typed_list b
(pp info (find_fixity, `NonAssoc)) c
(pp info (find_fixity, `NonAssoc)) d
(pp_chained_find info) e
| _ -> Fmt.pf ppf "@[<hov 2>else@ %a@]" (pp info (find_fixity, `Right)) t
and pp_happens info ppf (ts : term list) =
Fmt.pf ppf "@[<hv 2>%a(%a)@]"
pp_mname_s "happens"
(Fmt.list ~sep:(fun fmt () -> Fmt.pf fmt ",@ ")
(pp info (happens_fixity, `NonAssoc))) ts
and pp_and_happens info ppf f =
let rec collect acc = function
| Fun (s, _, [ts]) when s = f_happens -> ts :: acc
| _ as f ->
let l, r = oget (destr_and f) in
collect (collect acc l) r
in
pp_happens info ppf (collect [] f)
let pp_with_info (info : pp_info) (fmt : Format.formatter) (t : term) : unit =
pp info ((toplevel_prec, `NoParens), `NonAssoc) fmt t
let pp (fmt : Format.formatter) (t : term) : unit =
pp default_pp_info ((toplevel_prec, `NoParens), `NonAssoc) fmt t
let pp_hterm fmt = function
| Lambda (evs, t) ->
Fmt.pf fmt "@[<v 2>fun (@[%a@]) ->@ %a@]"
Vars.pp_typed_list evs pp t
type ord = [ `Eq | `Neq | `Leq | `Geq | `Lt | `Gt ]
type ord_eq = [ `Eq | `Neq ]
type ('a,'b) _atom = 'a * 'b * 'b
type xatom = [
| `Comp of (ord,term) _atom
| `Happens of term
]
type literal = [`Neg | `Pos] * xatom
type literals = literal list
let pp_xatom ppf = function
| `Comp (o,tl,tr) ->
Fmt.pf ppf "@[%a %a@ %a@]" pp tl pp_ord o pp tr
| `Happens a -> pp_happens default_pp_info ppf [a]
let pp_literal fmt ((pn,at) : literal) =
match pn with
| `Pos -> Fmt.pf fmt "%a" pp_xatom at
| `Neg -> Fmt.pf fmt "¬(%a)" pp_xatom at
let pp_literals fmt (l : literal list) =
let sep fmt () = Fmt.pf fmt " ∧ " in
(Fmt.list ~sep pp_literal) fmt l
let ty_xatom = function
| `Happens t -> Type.Timestamp
| `Comp (_, t1, t2) ->
let ty1 = ty t1 in
assert (ty1 = ty t2);
ty1
let ty_lit ((_, at) : literal) : Type.ty = ty_xatom at
let neg_lit ((pn, at) : literal) : literal =
let pn = match pn with
| `Pos -> `Neg
| `Neg -> `Pos in
(pn, at)
let form_to_xatom (form : term) : xatom option =
match form with
| Fun (f, _, [a]) when f = f_happens -> Some (`Happens a)
| Fun (fseq, _, [a;b]) when fseq = f_eq -> Some (`Comp (`Eq, a, b))
| Fun (fsneq, _, [a;b]) when fsneq = f_neq -> Some (`Comp (`Neq, a, b))
| Fun (fsleq, _, [a;b]) when fsleq = f_leq -> Some (`Comp (`Leq, a, b))
| Fun (fslt, _, [a;b]) when fslt = f_lt -> Some (`Comp (`Lt, a, b))
| Fun (fsgeq, _, [a;b]) when fsgeq = f_geq -> Some (`Comp (`Geq, a, b))
| Fun (fsgt, _, [a;b]) when fsgt = f_gt -> Some (`Comp (`Gt, a, b))
| _ -> None
let rec form_to_literal (form : term) : literal option =
match form with
| Fun (fnot, _, [f]) when fnot = f_not -> omap neg_lit (form_to_literal f)
| _ -> omap (fun at -> (`Pos, at)) (form_to_xatom form)
let disjunction_to_literals f : literal list option =
let exception Not_a_disjunction in
let rec aux_l = function
| tf when tf = mk_false -> []
| Fun (fsor,_, [a; b]) when fsor = f_or -> aux_l a @ aux_l b
| f -> match form_to_literal f with
| Some f -> [f]
| None -> raise Not_a_disjunction
in
try Some (aux_l f) with Not_a_disjunction -> None
let form_to_literals
(form : term)
: [`Entails of literal list | `Equiv of literal list]
=
let partial = ref false in
let lits : literal list =
List.fold_left (fun acc f ->
match form_to_literal f with
| Some at -> at :: acc
| None -> partial := true; acc
) [] (decompose_ands form)
in
if !partial then `Entails lits else `Equiv lits
let eq_triv f = match destr_eq f with
| Some (t1,t2) when t1=t2 ->
(match t1 with
Find _ -> false
| _ -> true)
| _ -> false
let f_triv = function
| tt when tt = mk_true -> true
| f -> eq_triv f
let mk s k = { s_symb = s; s_typ = k; s_indices = []; }
let in_macro : msymb = mk Symbols.inp Type.Message
let out_macro : msymb = mk Symbols.out Type.Message
let frame_macro : msymb = mk Symbols.frame Type.Message
let cond_macro : msymb = mk Symbols.cond Type.Boolean
let exec_macro : msymb = mk Symbols.exec Type.Boolean
type esubst = ESubst of term * term
type subst = esubst list
let rec assoc : subst -> term -> term =
fun subst term ->
match subst with
| [] -> term
| ESubst (t1,t2)::q ->
if term = t1 then t2 else assoc q term
let pp_esubst ppf (ESubst (t1,t2)) =
Fmt.pf ppf "%a->%a" pp t1 pp t2
let pp_subst ppf s =
Fmt.pf ppf "@[<hv 0>%a@]"
(Fmt.list ~sep:(fun ppf () -> Fmt.pf ppf ",@ ") pp_esubst) s
let subst_var (subst : subst) (var : Vars.var) : Vars.var =
match assoc subst (Var var) with
| Var var -> var
| _ -> assert false
let subst_vars (subst : subst) (vs : Vars.vars) : Vars.vars =
List.map (subst_var subst) vs
let subst_isymb (s : subst) (symb : 'a isymb) : 'a isymb =
{ symb with s_indices = subst_vars s symb.s_indices }
let subst_macro (s : subst) isymb =
{ isymb with s_indices = subst_vars s isymb.s_indices }
let fv (term : term) : Sv.t =
let rec fv (t : term) : Sv.t =
match t with
| Action (_,indices) -> Sv.of_list indices
| Var tv -> Sv.singleton tv
| Fun ((_,indices), _,lt) ->
Sv.union (Sv.of_list indices) (fvs lt)
| Macro (s, l, ts) ->
Sv.union
(Sv.of_list s.s_indices)
(Sv.union (fv ts) (fvs l))
| Name s -> Sv.of_list s.s_indices
| Diff (Explicit l) -> fvs (List.map snd l)
| Find (a, b, c, d) ->
Sv.union
(Sv.diff (fvs [b;c]) (Sv.of_list a))
(fv d)
| Seq (a, b)
| ForAll (a, b)
| Exists (a, b) -> Sv.diff (fv b) (Sv.of_list a)
and fvs (terms : term list) : Sv.t =
List.fold_left (fun sv x -> Sv.union (fv x) sv) Sv.empty terms
in
fv term
let get_vars t = fv t |> Sv.elements
* { 2 Iterators }
let tmap (func : term -> term) (t : term) : term =
match t with
| Action _ -> t
| Name _ -> t
| Var _ -> t
| Fun (f,fty,terms) -> Fun (f, fty, List.map func terms)
| Macro (m, l, ts) -> Macro (m, List.map func l, func ts)
| Seq (vs, b) -> Seq (vs, func b)
| Diff (Explicit l) ->
Diff (Explicit (List.map (fun (lbl,tm) -> lbl, func tm) l))
| Find (b, c, d, e) ->
let c = func c
and d = func d
and e = func e in
Find (b, c, d, e)
| ForAll (vs, b) -> ForAll (vs, func b)
| Exists (vs, b) -> Exists (vs, func b)
let tmap_fold (func : 'b -> term -> 'b * term) (b : 'b) (t : term) : 'b * term =
let bref = ref b in
let g t =
let b, t = func !bref t in
bref := b;
t
in
let t = tmap g t in
!bref, t
let titer (f : term -> unit) (t : term) : unit =
let g e = f e; e in
ignore (tmap g t)
let tfold (f : term -> 'b -> 'b) (t : term) (v : 'b) : 'b =
let vref : 'b ref = ref v in
let fi e = vref := (f e !vref) in
titer fi t;
!vref
let texists (f : term -> bool) (t : term) : bool =
tfold (fun t b -> f t || b) t false
let tforall (f : term -> bool) (t : term) : bool =
tfold (fun t b -> f t || b) t false
* { 2 Substitutions }
let filter_subst (var:Vars.var) (s:subst) =
let s =
List.fold_left (fun acc (ESubst (x, y)) ->
if not (Sv.mem var (fv x))
then (ESubst (x, y))::acc
else acc
) [] s in
List.rev s
let is_var_subst s =
List.for_all (fun (ESubst (t,_)) -> match t with
| Var _ -> true
| _ -> false) s
* Returns the variables appearing in a substitution LHS .
let subst_support s =
List.fold_left (fun supp (ESubst (t,_)) ->
Sv.union supp (fv t)) Sv.empty s
let is_binder : term -> bool = function
| Seq _ | ForAll _ | Exists _ | Find _ -> true
| _ -> false
let is_macro : term -> bool = function
| Macro _ -> true | _ -> false
let rec subst (s : subst) (t : term) : term =
if s = [] ||
(is_binder t &&
is_var_subst s &&
Sv.disjoint (subst_support s) (fv t))
then t
else
let new_term =
match t with
| Fun ((fs,is), fty, lt) ->
Fun ((fs, subst_vars s is), fty, List.map (subst s) lt)
| Name symb ->
Name { symb with s_indices = subst_vars s symb.s_indices}
| Macro (m, l, ts) ->
Macro (subst_macro s m, List.map (subst s) l, subst s ts)
| Var m -> Var m
| Action (a,indices) -> Action (a, subst_vars s indices)
| Diff (Explicit l) ->
Diff (Explicit (List.map (fun (lbl,tm) -> lbl, subst s tm) l))
| Seq ([], f) -> Seq ([], subst s f)
| Seq ([a], f) ->
let a, s = subst_binding a s in
let f = subst s f in
Seq ([a],f)
| Seq (a :: vs, f) ->
let a, s = subst_binding a s in
let f = subst s (Seq (vs,f)) in
let vs, f = match f with
| Seq (vs, f) -> vs, f
| _ -> assert false in
Seq (a :: vs,f)
| ForAll ([], f) -> subst s f
| ForAll (a :: vs, f) ->
let a, s = subst_binding a s in
let f = subst s (ForAll (vs,f)) in
mk_forall [a] f
| Exists ([], f) -> subst s f
| Exists (a :: vs, f) ->
let a, s = subst_binding a s in
let f = subst s (Exists (vs,f)) in
mk_exists [a] f
| Find ([], b, c, d) -> Find ([], subst s b, subst s c, subst s d)
| Find (v :: vs, b, c, d) ->
let dummy = mk_zero in
let v, s = subst_binding v s in
let f = subst s (Find (vs, b, c, dummy)) in
match f with
| Find (vs, b, c, _) -> Find (v :: vs, b, c, subst s d)
| _ -> assert false
in
assoc s new_term
and subst_binding : Vars.var -> subst -> Vars.var * subst =
fun var s ->
let s = filter_subst var s in
let right_fv =
List.fold_left (fun acc (ESubst (x, y)) ->
Sv.union acc (fv y)
) Sv.empty s in
let all_vars =
List.fold_left (fun acc (ESubst (x, y)) ->
Sv.union acc (fv x)
) right_fv s in
let env = ref (Vars.of_list (Sv.elements all_vars)) in
let var, s =
if Sv.mem var right_fv
then
let new_v = Vars.fresh_r env var in
let s = (ESubst (Var var,Var new_v)) :: s in
( new_v, s)
else ( var, s ) in
var, s
let subst_macros_ts table l ts t =
let rec subst_term (t : term) : term = match t with
| Macro (is, terms, ts') ->
let terms' = List.map subst_term terms in
begin match Symbols.Macro.get_all is.s_symb table with
| Symbols.State _, _ ->
if (List.mem (Symbols.to_string is.s_symb) l && ts=ts')
then Macro(is, terms', ts')
else Macro(is, terms', mk_pred ts')
| _ -> Macro(is, terms', ts')
end
| Diff (Explicit l) ->
Diff (Explicit (List.map (fun (lbl,tm) -> lbl, subst_term tm) l))
| Fun (f,fty,terms) -> Fun (f, fty, List.map subst_term terms)
| Seq (a, b) -> Seq (a, subst_term b)
| Find (vs, b, t, e) -> Find (vs, subst_term b, subst_term t, subst_term e)
| ForAll (vs, b) -> ForAll (vs, subst_term b)
| Exists (vs, b) -> Exists (vs, subst_term b)
| Name _ | Action _ | Var _ -> t
in
subst_term t
let rec subst_ht s ht = match ht with
| Lambda (ev :: evs, t) ->
let ev, s = subst_binding ev s in
mk_lambda [ev] (subst_ht s (Lambda (evs, t)))
| Lambda ([], t) -> Lambda ([], subst s t)
let check_projs_subst (s : (proj * proj) list) : unit =
assert (
List.for_all (fun (p1, p2) ->
List.for_all (fun (p1', p2') ->
p1 = p1' && p2 = p2' ||
(p1 <> p1' && p2 <> p2')
) s
) s)
let subst_projs (s : (proj * proj) list) (t : term) : term =
check_projs_subst s;
let rec do_subst : term -> term = function
| Diff (Explicit l) ->
Diff (Explicit (List.map (fun (p, t) -> List.assoc_dflt p p s, t) l))
| _ as t -> tmap do_subst t
in
do_subst t
type refresh_arg = [`Global | `InEnv of Vars.env ref ]
let refresh_var (arg : refresh_arg) v =
match arg with
| `Global -> Vars.make_new_from v
| `InEnv env -> Vars.fresh_r env v
let refresh_vars (arg : refresh_arg) evars =
let l =
List.rev_map (fun v ->
let v' = refresh_var arg v in
v', ESubst (Var v, Var v')
) evars
in
let vars, subst = List.split l in
List.rev vars, subst
let refresh_vars_env env vs =
let env = ref env in
let vs, s = refresh_vars (`InEnv env) vs in
!env, vs, s
* { 2 Smart constructors and destructors -- Part 2 }
module type SmartFO = sig
type form
* { 3 Constructors }
val mk_true : form
val mk_false : form
val mk_eq : ?simpl:bool -> term -> term -> form
val mk_leq : ?simpl:bool -> term -> term -> form
val mk_geq : ?simpl:bool -> term -> term -> form
val mk_lt : ?simpl:bool -> term -> term -> form
val mk_gt : ?simpl:bool -> term -> term -> form
val mk_not : ?simpl:bool -> form -> form
val mk_and : ?simpl:bool -> form -> form -> form
val mk_ands : ?simpl:bool -> form list -> form
val mk_or : ?simpl:bool -> form -> form -> form
val mk_ors : ?simpl:bool -> form list -> form
val mk_impl : ?simpl:bool -> form -> form -> form
val mk_impls : ?simpl:bool -> form list -> form -> form
val mk_forall : ?simpl:bool -> Vars.vars -> form -> form
val mk_exists : ?simpl:bool -> Vars.vars -> form -> form
val destr_forall : form -> (Vars.var list * form) option
val destr_forall1 : form -> (Vars.var * form) option
val destr_exists : form -> (Vars.var list * form) option
val destr_exists1 : form -> (Vars.var * form) option
val destr_neq : form -> (term * term) option
val destr_eq : form -> (term * term) option
val destr_leq : form -> (term * term) option
val destr_lt : form -> (term * term) option
val destr_false : form -> unit option
val destr_true : form -> unit option
val destr_not : form -> form option
val destr_and : form -> (form * form) option
val destr_or : form -> (form * form) option
val destr_impl : form -> (form * form) option
val is_false : form -> bool
val is_true : form -> bool
val is_not : form -> bool
val is_zero : form -> bool
val is_and : form -> bool
val is_or : form -> bool
val is_impl : form -> bool
val is_forall : form -> bool
val is_exists : form -> bool
val is_neq : form -> bool
val is_eq : form -> bool
val is_leq : form -> bool
val is_lt : form -> bool
val destr_ands : int -> form -> form list option
val destr_ors : int -> form -> form list option
val destr_impls : int -> form -> form list option
val decompose_forall : form -> Vars.var list * form
val decompose_exists : form -> Vars.var list * form
val decompose_ands : form -> form list
val decompose_ors : form -> form list
val decompose_impls : form -> form list
val decompose_impls_last : form -> form list * form
end
module Smart : SmartFO with type form = term = struct
type form = term
include SmartConstructors
include SmartDestructors
FIXME : improve variable naming ( see )
let mk_forall ?(simpl=false) l f =
let l =
if simpl then
let fv = fv f in
List.filter (fun v -> Sv.mem v fv) l
else l
in
mk_forall l f
FIXME : improve variable naming ( see )
let mk_exists ?(simpl=false) l f =
let l =
if simpl then
let fv = fv f in
List.filter (fun v -> Sv.mem v fv) l
else l
in
mk_exists l f
end
include Smart
let mk_atom (o : ord) (t1 : term) (t2 : term) : term =
match o with
| `Eq -> mk_eq t1 t2
| `Leq -> mk_leq t1 t2
| `Lt -> mk_lt t1 t2
| `Neq -> mk_neq t1 t2
| `Geq -> mk_geq t1 t2
| `Gt -> mk_gt t1 t2
let xatom_to_form (l : xatom) : term = match l with
| `Comp (ord, t1, t2) -> mk_atom ord t1 t2
| `Happens l -> mk_happens l
let lit_to_form (l : literal) : term =
match l with
| `Pos, at -> xatom_to_form at
| `Neg, at -> mk_not (xatom_to_form at)
let mk_seq0 ?(simpl=false) (is : Vars.vars) term =
let is =
if simpl then
let term_fv = fv term in
List.filter (fun i ->
Sv.mem i term_fv
) is
else is
in
match is with
| [] -> term
| _ -> Seq (is, term)
let mk_seq env (is : Vars.vars) term =
let env =
let env_vars = Sv.of_list (Vars.to_list env) in
let term_vars = fv term in
let vars = Sv.elements (Sv.inter env_vars term_vars) in
ref (Vars.of_list vars)
in
let is, s = refresh_vars (`InEnv env) is in
let term = subst s term in
match is with
| [] -> term
| _ -> Seq (is, term)
* { 2 Apply }
let apply_ht (ht : hterm) (terms : term list) = match ht with
| Lambda (evs, t) ->
assert (List.length terms <= List.length evs);
let evs0, evs1 = List.takedrop (List.length terms) evs in
let evs0, s = refresh_vars `Global evs0 in
let ht = subst_ht s (Lambda (evs1, t)) in
let s_app =
List.map2 (fun v t -> ESubst (Var v, t)) evs0 terms
in
subst_ht s_app ht
* { 2 Type substitution }
let tsubst (ts : Type.tsubst) (t : term) : term =
no need to substitute in the types of [ Name ] , [ Macro ] , [ Fun ]
let rec tsubst : term -> term = function
| Var v -> Var (Vars.tsubst ts v)
| ForAll (vs, f) -> ForAll (List.map (Vars.tsubst ts) vs, tsubst f)
| Exists (vs, f) -> Exists (List.map (Vars.tsubst ts) vs, tsubst f)
| _ as term -> tmap (fun t -> tsubst t) term
in
tsubst t
let tsubst_ht (ts : Type.tsubst) (ht : hterm) : hterm =
match ht with
| Lambda (vs, f) -> Lambda (List.map (Vars.tsubst ts) vs, tsubst ts f)
* { 2 Simplification }
let rec not_simpl = function
| Exists (vs, f) -> ForAll(vs, not_simpl f)
| ForAll (vs, f) -> Exists(vs, not_simpl f)
| tt when tt = mk_true -> mk_false
| tf when tf = mk_false -> mk_true
| Fun (fs, _, [a;b]) when fs = f_and -> mk_or (not_simpl a) (not_simpl b)
| Fun (fs, _, [a;b]) when fs = f_or -> mk_and (not_simpl a) (not_simpl b)
| Fun (fs, _, [a;b]) when fs = f_impl -> mk_and a (not_simpl b)
| Fun (fs, _, [f]) when fs = f_not -> f
| Fun (fs, _, [a;b]) when fs = f_eq -> mk_neq a b
| Fun (fs, _, [a;b]) when fs = f_neq -> mk_eq a b
| m -> mk_not m
let is_deterministic (t : term) : bool =
let exception NonDet in
let rec is_det : term -> unit = function
| Name _ | Macro _ -> raise NonDet
| t -> titer is_det t
in
try is_det t; true with NonDet -> false
let is_pure_timestamp (t : term) =
let rec pure_ts = function
| Fun (fs, _, [t]) when fs = f_happens || fs = f_pred -> pure_ts t
| Fun (fs, _, [t1; t2])
when fs = f_or || fs = f_and || fs = f_impl ||
fs = f_eq || fs = f_neq || fs = f_leq || fs = f_lt ||
fs = f_geq || fs = f_gt ->
pure_ts t1 && pure_ts t2
| Fun (fs, _, [t]) when fs = f_not -> pure_ts t
| Fun (fs, _, []) -> true
| ForAll (_, t)
| Exists (_, t) -> pure_ts t
| Action _ -> true
| Var v -> let ty = Vars.ty v in ty = Type.Timestamp || ty = Type.Index
| _ -> false
in
pure_ts t
* { 2 Projection }
let project1 (proj : proj) (term : term) : term =
let rec project1 (t : term) : term =
match t with
| Diff (Explicit l) -> List.assoc proj l
| _ -> tmap project1 t
in
project1 term
let project (projs : proj list) (term : term) : term =
let rec project (t : term) : term =
match t with
| Diff (Explicit l) ->
assert (List.for_all (fun x -> List.mem_assoc x l) projs);
mk_diff (List.filter (fun (x,_) -> List.mem x projs) l)
| _ -> tmap project t
in
project term
let project_opt (projs : projs option) (term : term) : term =
omap_dflt term (project ^~ term) projs
* Evaluate topmost diff operators for a given proj of a biterm .
For example [ head_pi_term left ( diff(a , b ) ) ] is [ a ]
and [ head_pi_term left f(diff(a , b),c ) ] is [ f(diff(a , b),c ) ] .
For example [head_pi_term left (diff(a,b))] is [a]
and [head_pi_term left f(diff(a,b),c)] is [f(diff(a,b),c)]. *)
let head_pi_term (s : proj) (t : term) : term =
match t with
| Diff (Explicit l) -> List.assoc s l
| _ -> t
let diff a b =
if a = b then a else
Diff (Explicit [left_proj,a; right_proj,b])
let rec make_normal_biterm (dorec : bool) (t : term) : term =
let mdiff (t : term) (t' : term) : term =
if dorec then make_normal_biterm dorec (diff t t')
else diff t t'
in
TODO generalize to non - binary diff
match head_pi_term left_proj t, head_pi_term right_proj t with
| Fun (f,fty,l), Fun (f',fty',l') when f = f' ->
Fun (f, fty, List.map2 mdiff l l')
| Name n, Name n' when n=n' -> Name n
| Macro (m,l,ts), Macro (m',l',ts') when m = m' && ts = ts' ->
Macro (m, List.map2 mdiff l l', ts)
| Action (a,is), Action (a',is') when a = a' && is = is' -> Action (a,is)
| Var x, Var x' when x=x' -> Var x
| Find (is,c,t,e), Find (is',c',t',e') when is = is' ->
Find (is, mdiff c c', mdiff t t', mdiff e e')
| ForAll (vs,f), ForAll (vs',f') when vs = vs' -> ForAll (vs, mdiff f f')
| Exists (vs,f), Exists (vs',f') when vs = vs' -> Exists (vs, mdiff f f')
| t1,t2 -> diff t1 t2
let simple_bi_term : term -> term = make_normal_biterm true
let head_normal_biterm : term -> term = make_normal_biterm false
let combine = function
| [_,t] -> t
| ["left",_;"right",_] as l ->
simple_bi_term (Diff (Explicit l))
| _ -> assert false
let rec diff_names = function
| Name _ -> true
| Diff (Explicit l) -> List.for_all (fun (_,tm) -> diff_names tm) l
| _ -> false
* { 2 Sets and Maps }
module T = struct
type t = term
let compare = Stdlib.compare
end
module Mt = Map.Make (T)
module St = Set.Make (T)
* { 2 Matching information for error messages }
type match_info =
type match_infos = match_info Mt.t
let pp_match_info fmt = function
| MR_ok -> Fmt.pf fmt "ok"
| MR_check_st terms -> Fmt.pf fmt "check subterms %a" (Fmt.list pp) terms
| MR_failed -> Fmt.pf fmt "failed"
let pp_match_infos fmt minfos =
let pp_one fmt (t, mi) = Fmt.pf fmt "%a → %a" pp t pp_match_info mi in
Fmt.pf fmt "@[<v 0>%a@]" (Fmt.list pp_one) (Mt.bindings minfos)
let match_infos_to_pp_info (minfos : match_infos) : pp_info =
let styler info (t : term) : Printer.keyword option * pp_info =
match Mt.find_opt t minfos with
| None -> None, info
| Some MR_ok -> None, default_pp_info
| Some MR_check_st _ -> None, info
| Some MR_failed -> Some `Error, info
in
{ styler }
* { 2 Term heads }
type term_head =
| HExists
| HForAll
| HSeq
| HFind
| HFun of Symbols.fname
| HMacro of Symbols.macro
| HName of Symbols.name
| HDiff
| HVar
| HAction
let pp_term_head fmt = function
| HExists -> Fmt.pf fmt "Exists"
| HForAll -> Fmt.pf fmt "Forall"
| HSeq -> Fmt.pf fmt "Seq"
| HFind -> Fmt.pf fmt "Find"
| HFun f -> Fmt.pf fmt "Fun %a" Symbols.pp f
| HMacro m -> Fmt.pf fmt "Macro %a" Symbols.pp m
| HName n -> Fmt.pf fmt "Name %a" Symbols.pp n
| HDiff -> Fmt.pf fmt "Diff"
| HVar -> Fmt.pf fmt "Var"
| HAction -> Fmt.pf fmt "Action"
let get_head : term -> term_head = function
| Exists _ -> HExists
| ForAll _ -> HForAll
| Seq _ -> HSeq
| Fun ((f,_),_,_) -> HFun f
| Find _ -> HFind
| Macro (m1,_,_) -> HMacro m1.s_symb
| Name n1 -> HName n1.s_symb
| Diff _ -> HDiff
| Var _ -> HVar
| Action _ -> HAction
module Hm = Map.Make(struct
type t = term_head
let compare = Stdlib.compare
end)
type 'a pat = {
pat_tyvars : Type.tvars;
pat_vars : Vars.Sv.t;
pat_term : 'a;
}
let pat_of_form (t : term) =
let vs, t = decompose_forall t in
let vs, s = refresh_vars `Global vs in
let t = subst s t in
{ pat_tyvars = [];
pat_vars = Vars.Sv.of_list vs;
pat_term = t; }
let project_tpat (projs : projs) (pat : term pat) : term pat =
{ pat with pat_term = project projs pat.pat_term; }
let project_tpat_opt (projs : projs option) (pat : term pat) : term pat
=
omap_dflt pat (project_tpat ^~ pat) projs
* { 2 Tests }
let () =
let mkvar x s = Var (snd (Vars.make `Approx Vars.empty_env s x)) in
Checks.add_suite "Head normalization" [
"Macro, different ts", `Quick, begin fun () ->
let ts = mkvar "ts" Type.Timestamp in
let ts' = mkvar "ts'" Type.Timestamp in
let m = in_macro in
let t = diff (Macro (m,[],ts)) (Macro (m,[],ts')) in
let r = head_normal_biterm t in
assert (r = t)
end ;
"Boolean operator", `Quick, begin fun () ->
let f = mkvar "f" Type.Boolean in
let g = mkvar "g" Type.Boolean in
let f' = mkvar "f'" Type.Boolean in
let g' = mkvar "g'" Type.Boolean in
let t = diff (mk_and f g) (mk_and f' g') in
assert (head_normal_biterm t = mk_and (diff f f') (diff g g'))
end ;
]
|
1d79ea97878e23bbc6faf04535a2f5a025350b69a4784d10de2f8cc582cd76d7 | zkat/sheeple | amop-3.7.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 ; indent - tabs - mode : nil -*-
This is a translation of section 3.7 from Art of the Metaobject Protocol , which
;;;; implements a 'monitored class' whose slot-accesses are taken note of.
(in-package :sheeple-user)
The first step is to create the metaobject . MOP messages will dispatch in this to alter behavior .
(defproto =monitored-metaobject= =standard-metaobject=
;; The AMOP example puts the access history in a closure. In our case, we can simply use the
;; metaobject to hold this 'global' data.
((access-history nil)))
;; We use NOTE-OPERATION to actually register each property operation in our access history.
(defmessage note-operation (metaobject object property-name operation)
(:reply ((metaobject =monitored-metaobject=) object property-name operation)
(push (list operation object property-name (get-universal-time)) (access-history metaobject))))
Now we can actually define our MOP replies . lives in the Sheeple - MOP package .
;; It has an smop: nickname for convenience, since the package is not meant to be :used by anything
;; that already :uses Sheeple.
;;
MOP messages are named identically to their standard Sheeple counterparts , and have the same
lambda - list except for an extra argument , the metaobject , which the message uses to dispatch .
Users of the MOP should not specialize these replies on anything but the metaobjects .
;;
;; The pattern for actually defining our replies is simple: We just write a :before reply for each
;; bit of property access we want to keep track of, and make it call NOTE-OPERATION before continuing
;; with their standard behavior.
;;
(defreply smop:direct-property-value :before ((mo =monitored-metaobject=) object pname)
(note-operation mo object pname 'direct-property-access))
(defreply smop:property-value :before ((mo =monitored-metaobject=) object pname)
(note-operation mo object pname 'property-access))
(defreply (setf smop:property-value) :before
(new-value (mo =monitored-metaobject=) object pname &key)
(declare (ignore new-value))
(note-operation mo object pname 'set-property-value))
(defreply smop:direct-property-p :before ((mo =monitored-metaobject=) object pname)
(note-operation mo object pname 'checked-direct-property-existence))
(defreply smop:property-makunbound :before ((mo =monitored-metaobject=) object pname)
(note-operation mo object pname 'property-removal))
;; Once we've defined our 'alternate' object system, it's just a matter of creating a new object
;; and making it use our =monitored-metaobject=, which essentially puts it in the realm of
;; 'The fork of Sheeple that happens to monitor some property-related stuff'.
(defproto =monitored-object= ()
((prop1 "var")
(prop2 234))
:metaobject =monitored-metaobject=)
;; Just the act of creating the monitored object should trigger a couple of these.
;; You can see which ones have already been performed by doing
;; (access-history =monitored-metaobject=)
;;
;; To try it further, perform some of the operations we wrote replies for.
One neat feature of Sheeple 's MOP is that you are able to , when appropriate , change metaobjects
;; for existing objects.
;; Let's clear the existing access history to demonstrate...
(setf (access-history =monitored-metaobject=) nil)
We first create our object normally ...
(defproto =initially-unmonitored= ()
((unmonitored-property "Test")))
;; Now we can swap the metaobjects...
(setf (object-metaobject =initially-unmonitored=) =monitored-metaobject=)
(print "History is empty...")
(print (access-history =monitored-metaobject=))
(setf (unmonitored-property =initially-unmonitored=) "Big Brother is watching me.")
(print "Object is now monitored!")
(print (access-history =monitored-metaobject=))
| null | https://raw.githubusercontent.com/zkat/sheeple/5393c74737ccf22c3fd5f390076b75c38453cb04/examples/amop-3.7.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 ; indent - tabs - mode : nil -*-
implements a 'monitored class' whose slot-accesses are taken note of.
The AMOP example puts the access history in a closure. In our case, we can simply use the
metaobject to hold this 'global' data.
We use NOTE-OPERATION to actually register each property operation in our access history.
It has an smop: nickname for convenience, since the package is not meant to be :used by anything
that already :uses Sheeple.
The pattern for actually defining our replies is simple: We just write a :before reply for each
bit of property access we want to keep track of, and make it call NOTE-OPERATION before continuing
with their standard behavior.
Once we've defined our 'alternate' object system, it's just a matter of creating a new object
and making it use our =monitored-metaobject=, which essentially puts it in the realm of
'The fork of Sheeple that happens to monitor some property-related stuff'.
Just the act of creating the monitored object should trigger a couple of these.
You can see which ones have already been performed by doing
(access-history =monitored-metaobject=)
To try it further, perform some of the operations we wrote replies for.
for existing objects.
Let's clear the existing access history to demonstrate...
Now we can swap the metaobjects... |
This is a translation of section 3.7 from Art of the Metaobject Protocol , which
(in-package :sheeple-user)
The first step is to create the metaobject . MOP messages will dispatch in this to alter behavior .
(defproto =monitored-metaobject= =standard-metaobject=
((access-history nil)))
(defmessage note-operation (metaobject object property-name operation)
(:reply ((metaobject =monitored-metaobject=) object property-name operation)
(push (list operation object property-name (get-universal-time)) (access-history metaobject))))
Now we can actually define our MOP replies . lives in the Sheeple - MOP package .
MOP messages are named identically to their standard Sheeple counterparts , and have the same
lambda - list except for an extra argument , the metaobject , which the message uses to dispatch .
Users of the MOP should not specialize these replies on anything but the metaobjects .
(defreply smop:direct-property-value :before ((mo =monitored-metaobject=) object pname)
(note-operation mo object pname 'direct-property-access))
(defreply smop:property-value :before ((mo =monitored-metaobject=) object pname)
(note-operation mo object pname 'property-access))
(defreply (setf smop:property-value) :before
(new-value (mo =monitored-metaobject=) object pname &key)
(declare (ignore new-value))
(note-operation mo object pname 'set-property-value))
(defreply smop:direct-property-p :before ((mo =monitored-metaobject=) object pname)
(note-operation mo object pname 'checked-direct-property-existence))
(defreply smop:property-makunbound :before ((mo =monitored-metaobject=) object pname)
(note-operation mo object pname 'property-removal))
(defproto =monitored-object= ()
((prop1 "var")
(prop2 234))
:metaobject =monitored-metaobject=)
One neat feature of Sheeple 's MOP is that you are able to , when appropriate , change metaobjects
(setf (access-history =monitored-metaobject=) nil)
We first create our object normally ...
(defproto =initially-unmonitored= ()
((unmonitored-property "Test")))
(setf (object-metaobject =initially-unmonitored=) =monitored-metaobject=)
(print "History is empty...")
(print (access-history =monitored-metaobject=))
(setf (unmonitored-property =initially-unmonitored=) "Big Brother is watching me.")
(print "Object is now monitored!")
(print (access-history =monitored-metaobject=))
|
c23936a7bd8e54674da990f76216057697049dea258a15bf61585f3073c4a78a | nuprl/gradual-typing-performance | image.rkt | #lang typed/racket
(provide Mode Image-Color Y-Place X-Place Angle Side-Count
Pen-Style Pen-Cap Pen-Join)
(define-type Mode
(U 'solid "solid" 'outline "outline" Byte))
(define-type Image-Color
(U String Symbol color))
(define-type Y-Place
(U "top" 'top "bottom" 'bottom "middle" 'middle "center" 'center
"baseline" 'baseline "pinhole" 'pinhole))
(define-type X-Place
(U "left" 'left "right" 'right "middle" 'middle "center" 'center
"baseline" 'baseline "pinhole" 'pinhole))
(define-type Angle Nonnegative-Real)
(define-type Side-Count Positive-Integer)
(define-type Pen-Style
(U "solid" 'solid "dot" 'dot "long-dash" 'long-dash
"short-dash" 'short-dash "dot-dash" 'dot-dash))
(define-type Pen-Cap
(U "round" 'round "projecting" 'projecting "butt" 'butt))
(define-type Pen-Join
(U "round" 'round "bevel" 'bevel "miter" 'miter))
(require/typed/provide
lang/posn
#;
[#:struct posn ([x : Real] [y : Real])
#:extra-constructor-name make-posn])
(require/typed/provide
2htdp/image
[#:opaque Image image?]
[#:struct color ([red : Byte] [green : Byte] [blue : Byte] [alpha : Byte])
#:extra-constructor-name make-color]
[#:opaque pen pen?]
;; Can't use this type unless mrlib/image-core provides the struct:pen
;; binding. For now, just leave it opaque
#;
[#:struct pen ([color : Image-Color] [width : Nonnegative-Real]
[style : Pen-Style] [cap : Pen-Cap] [join : Pen-Join])
#:extra-constructor-name make-pen]
2.3.1
[circle (Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[ellipse (Nonnegative-Real Natural Mode (U pen Image-Color) -> Image)]
[line (Real Real (U pen Image-Color) -> Image)]
[add-line (Image Real Real Real Real (U pen Image-Color) -> Image)]
[add-curve (Image Real Real Angle Real Real Angle Real
(U pen Image-Color)-> Image)]
[text (String Positive-Integer Image-Color -> Image)]
[text/font (String Positive-Integer Image-Color (Option String)
(U 'default 'decorative 'roman 'script 'swiss 'modern
'symbol 'system)
(U 'normal 'italic 'slant)
(U 'normal 'bold 'light)
Any -> Image)]
[empty-image Image]
2.3.2
[triangle (Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[right-triangle (Nonnegative-Real Natural Mode (U pen Image-Color) -> Image)]
[isosceles-triangle (Nonnegative-Real Angle Mode (U pen Image-Color) -> Image)]
[triangle/sss (Nonnegative-Real Natural Natural Mode (U pen Image-Color) -> Image)]
[triangle/ass (Angle Nonnegative-Real Natural Mode (U pen Image-Color) -> Image)]
[triangle/sas (Nonnegative-Real Angle Natural Mode (U pen Image-Color) -> Image)]
[triangle/ssa (Nonnegative-Real Natural Angle Mode (U pen Image-Color) -> Image)]
[triangle/aas (Angle Nonnegative-Real Natural Mode (U pen Image-Color) -> Image)]
[triangle/asa (Angle Nonnegative-Real Angle Mode (U pen Image-Color) -> Image)]
[triangle/saa (Nonnegative-Real Angle Angle Mode (U pen Image-Color) -> Image)]
[square (Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[rectangle (Nonnegative-Real Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[rhombus (Nonnegative-Real Angle Mode (U pen Image-Color) -> Image)]
[star (Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[star-polygon (Nonnegative-Real Side-Count Side-Count Mode (U pen Image-Color) -> Image)]
[radial-star
(Positive-Integer Nonnegative-Real Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[regular-polygon (Nonnegative-Real Side-Count Mode (U pen Image-Color) -> Image)]
#;
[polygon ((Listof posn) Mode (U pen Image-Color) -> Image)]
2.3.3
[overlay (Image Image Image * -> Image)]
[overlay/align (X-Place Y-Place Image Image Image * -> Image)]
[overlay/offset (Image Real Real Image -> Image)]
[overlay/align/offset (X-Place Y-Place Image Real Real Image -> Image)]
[overlay/xy (Image Real Real Image -> Image)]
[underlay (Image Image Image * -> Image)]
[underlay/align (X-Place Y-Place Image Image Image * -> Image)]
[underlay/offset (Image Real Real Image -> Image)]
[underlay/align/offset (X-Place Y-Place Image Real Real Image -> Image)]
[underlay/xy (Image Real Real Image -> Image)]
[beside (Image Image Image * -> Image)]
[beside/align (Y-Place Image Image Image * -> Image)]
[above (Image Image Image * -> Image)]
[above/align (X-Place Image Image Image * -> Image)]
;; 2.3.4
[empty-scene (case-> (Nonnegative-Real Nonnegative-Real -> Image)
(Nonnegative-Real Nonnegative-Real Image-Color -> Image))]
[place-image (Image Real Real Image -> Image)]
[place-image/align (Image Real Real X-Place Y-Place Image -> Image)]
[scene+line (Image Real Real Real Real (U pen Image-Color) -> Image)]
[scene+curve (Image Real Real Angle Real Real Real Angle Real
(U pen Image-Color) -> Image)]
2.3.5
[rotate (Angle Image -> Image)]
[scale (Positive-Real Image -> Image)]
[scale/xy (Positive-Real Positive-Real Image -> Image)]
[flip-horizontal (Image -> Image)]
[flip-vertical (Image -> Image)]
[crop (Real Real Nonnegative-Real Nonnegative-Real Image -> Image)]
[frame (Image -> Image)]
2.3.6
[bitmap/url (String -> Image)]
[bitmap/file (Path-String -> Image)]
[image->color-list (Image -> (Listof color))]
[color-list->bitmap
((Listof Image-Color) Nonnegative-Real Nonnegative-Real -> Image)]
[freeze
(case-> (Image -> Image)
(Nonnegative-Real Nonnegative-Real Image -> Image)
(Real Real Nonnegative-Real Nonnegative-Real Image -> Image))]
2.3.7
[image-width (Image -> Natural)]
[image-height (Image -> Natural)]
[image-baseline (Image -> Natural)]
2.3.10
[center-pinhole (Image -> Image)]
[put-pinhole (Integer Integer Image -> Image)]
[pinhole-x (Image -> (Option Integer))]
[pinhole-y (Image -> (Option Integer))]
[clear-pinhole (Image -> Image)]
[overlay/pinhole (Image Image Image * -> Image)]
[underlay/pinhole (Image Image Image * -> Image)]
2.3.11
[save-image
(case-> (Image Path-String -> Boolean)
(Image Path-String Nonnegative-Real -> Boolean)
(Image Path-String Nonnegative-Real Nonnegative-Real -> Boolean))]
[save-svg-image
(case-> (Image Path-String -> Boolean)
(Image Path-String Nonnegative-Real -> Boolean)
(Image Path-String Nonnegative-Real Nonnegative-Real -> Boolean))])
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/tr-wrapper/typed/2htdp/image.rkt | racket |
Can't use this type unless mrlib/image-core provides the struct:pen
binding. For now, just leave it opaque
2.3.4 | #lang typed/racket
(provide Mode Image-Color Y-Place X-Place Angle Side-Count
Pen-Style Pen-Cap Pen-Join)
(define-type Mode
(U 'solid "solid" 'outline "outline" Byte))
(define-type Image-Color
(U String Symbol color))
(define-type Y-Place
(U "top" 'top "bottom" 'bottom "middle" 'middle "center" 'center
"baseline" 'baseline "pinhole" 'pinhole))
(define-type X-Place
(U "left" 'left "right" 'right "middle" 'middle "center" 'center
"baseline" 'baseline "pinhole" 'pinhole))
(define-type Angle Nonnegative-Real)
(define-type Side-Count Positive-Integer)
(define-type Pen-Style
(U "solid" 'solid "dot" 'dot "long-dash" 'long-dash
"short-dash" 'short-dash "dot-dash" 'dot-dash))
(define-type Pen-Cap
(U "round" 'round "projecting" 'projecting "butt" 'butt))
(define-type Pen-Join
(U "round" 'round "bevel" 'bevel "miter" 'miter))
(require/typed/provide
lang/posn
[#:struct posn ([x : Real] [y : Real])
#:extra-constructor-name make-posn])
(require/typed/provide
2htdp/image
[#:opaque Image image?]
[#:struct color ([red : Byte] [green : Byte] [blue : Byte] [alpha : Byte])
#:extra-constructor-name make-color]
[#:opaque pen pen?]
[#:struct pen ([color : Image-Color] [width : Nonnegative-Real]
[style : Pen-Style] [cap : Pen-Cap] [join : Pen-Join])
#:extra-constructor-name make-pen]
2.3.1
[circle (Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[ellipse (Nonnegative-Real Natural Mode (U pen Image-Color) -> Image)]
[line (Real Real (U pen Image-Color) -> Image)]
[add-line (Image Real Real Real Real (U pen Image-Color) -> Image)]
[add-curve (Image Real Real Angle Real Real Angle Real
(U pen Image-Color)-> Image)]
[text (String Positive-Integer Image-Color -> Image)]
[text/font (String Positive-Integer Image-Color (Option String)
(U 'default 'decorative 'roman 'script 'swiss 'modern
'symbol 'system)
(U 'normal 'italic 'slant)
(U 'normal 'bold 'light)
Any -> Image)]
[empty-image Image]
2.3.2
[triangle (Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[right-triangle (Nonnegative-Real Natural Mode (U pen Image-Color) -> Image)]
[isosceles-triangle (Nonnegative-Real Angle Mode (U pen Image-Color) -> Image)]
[triangle/sss (Nonnegative-Real Natural Natural Mode (U pen Image-Color) -> Image)]
[triangle/ass (Angle Nonnegative-Real Natural Mode (U pen Image-Color) -> Image)]
[triangle/sas (Nonnegative-Real Angle Natural Mode (U pen Image-Color) -> Image)]
[triangle/ssa (Nonnegative-Real Natural Angle Mode (U pen Image-Color) -> Image)]
[triangle/aas (Angle Nonnegative-Real Natural Mode (U pen Image-Color) -> Image)]
[triangle/asa (Angle Nonnegative-Real Angle Mode (U pen Image-Color) -> Image)]
[triangle/saa (Nonnegative-Real Angle Angle Mode (U pen Image-Color) -> Image)]
[square (Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[rectangle (Nonnegative-Real Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[rhombus (Nonnegative-Real Angle Mode (U pen Image-Color) -> Image)]
[star (Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[star-polygon (Nonnegative-Real Side-Count Side-Count Mode (U pen Image-Color) -> Image)]
[radial-star
(Positive-Integer Nonnegative-Real Nonnegative-Real Mode (U pen Image-Color) -> Image)]
[regular-polygon (Nonnegative-Real Side-Count Mode (U pen Image-Color) -> Image)]
[polygon ((Listof posn) Mode (U pen Image-Color) -> Image)]
2.3.3
[overlay (Image Image Image * -> Image)]
[overlay/align (X-Place Y-Place Image Image Image * -> Image)]
[overlay/offset (Image Real Real Image -> Image)]
[overlay/align/offset (X-Place Y-Place Image Real Real Image -> Image)]
[overlay/xy (Image Real Real Image -> Image)]
[underlay (Image Image Image * -> Image)]
[underlay/align (X-Place Y-Place Image Image Image * -> Image)]
[underlay/offset (Image Real Real Image -> Image)]
[underlay/align/offset (X-Place Y-Place Image Real Real Image -> Image)]
[underlay/xy (Image Real Real Image -> Image)]
[beside (Image Image Image * -> Image)]
[beside/align (Y-Place Image Image Image * -> Image)]
[above (Image Image Image * -> Image)]
[above/align (X-Place Image Image Image * -> Image)]
[empty-scene (case-> (Nonnegative-Real Nonnegative-Real -> Image)
(Nonnegative-Real Nonnegative-Real Image-Color -> Image))]
[place-image (Image Real Real Image -> Image)]
[place-image/align (Image Real Real X-Place Y-Place Image -> Image)]
[scene+line (Image Real Real Real Real (U pen Image-Color) -> Image)]
[scene+curve (Image Real Real Angle Real Real Real Angle Real
(U pen Image-Color) -> Image)]
2.3.5
[rotate (Angle Image -> Image)]
[scale (Positive-Real Image -> Image)]
[scale/xy (Positive-Real Positive-Real Image -> Image)]
[flip-horizontal (Image -> Image)]
[flip-vertical (Image -> Image)]
[crop (Real Real Nonnegative-Real Nonnegative-Real Image -> Image)]
[frame (Image -> Image)]
2.3.6
[bitmap/url (String -> Image)]
[bitmap/file (Path-String -> Image)]
[image->color-list (Image -> (Listof color))]
[color-list->bitmap
((Listof Image-Color) Nonnegative-Real Nonnegative-Real -> Image)]
[freeze
(case-> (Image -> Image)
(Nonnegative-Real Nonnegative-Real Image -> Image)
(Real Real Nonnegative-Real Nonnegative-Real Image -> Image))]
2.3.7
[image-width (Image -> Natural)]
[image-height (Image -> Natural)]
[image-baseline (Image -> Natural)]
2.3.10
[center-pinhole (Image -> Image)]
[put-pinhole (Integer Integer Image -> Image)]
[pinhole-x (Image -> (Option Integer))]
[pinhole-y (Image -> (Option Integer))]
[clear-pinhole (Image -> Image)]
[overlay/pinhole (Image Image Image * -> Image)]
[underlay/pinhole (Image Image Image * -> Image)]
2.3.11
[save-image
(case-> (Image Path-String -> Boolean)
(Image Path-String Nonnegative-Real -> Boolean)
(Image Path-String Nonnegative-Real Nonnegative-Real -> Boolean))]
[save-svg-image
(case-> (Image Path-String -> Boolean)
(Image Path-String Nonnegative-Real -> Boolean)
(Image Path-String Nonnegative-Real Nonnegative-Real -> Boolean))])
|
cf53b1fae2f629a4026cc899b35f42035a36a66cf1665e56c31da26c214f95c8 | dharmatech/abstracting | gambit.scm |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (load "~~/Gambit-C/lib/syntax-case.scm")
(load "support/gambit/srfi-1/srfi-1")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define scheme-implementation 'gambit)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define abstracting-root-directory (current-directory))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define *roots* #f)
(define *loaded* '())
(define *included* '())
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (directory-contains file)
(lambda (dir)
(file-exists?
(string-append dir "/" file))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (resolve lib)
(let ((root (find (directory-contains lib) *roots*)))
(if root (string-append root "/" lib) #f)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (define (snarf dir)
( let ( ( dir ( resolve ) ) )
;; (let ((import-file (string-append dir "/import"))
;; (include-file (string-append dir "/include"))
( source - file ( string - append dir " " ) )
;; (export-file (string-append dir "/export"))
;; (compiled-file (string-append dir "/compiled-gambit")))
;; (for-each (lambda (lib) (snarf (resolve lib)))
;; (read (open-input-file import-file)))
;; (if (file-exists? compiled-file)
;; (scheme-load-compiled-file compiled-file)
;; (scheme-load-source-file source-file))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (load-include dir)
(let ((file (string-append (resolve dir) "/" "source.scm")))
(eval `(include ,file))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (require-include dir)
(cond ((not (member dir *included*))
(print "Including " dir "\n")
(load-include dir)
(set! *included* (cons dir *included*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (load-source dir)
(let ((dir (resolve dir)))
(let ((import-file (string-append dir "/import"))
(include-file (string-append dir "/include"))
(source-file (string-append dir "/source.scm")))
(if (file-exists? import-file)
(let ((import-list (call-with-input-file import-file read)))
(for-each load-source import-list)))
(if (file-exists? include-file)
(let ((include-list (call-with-input-file include-file read)))
(for-each require-include include-list)))
(print "Loading " source-file "\n")
(load source-file))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (require-source dir)
(cond ((not (member dir *loaded*))
(load-source dir)
(set! *loaded* (cons dir *loaded*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (compile-lib dir)
(print "Compiling " dir "\n")
(let ((dir (resolve dir)))
(let ((compiled-file (string-append dir "/source.o1")))
(if (file-exists? compiled-file)
(delete-file compiled-file)))
(let ((include-file (string-append dir "/include")))
(if (file-exists? include-file)
(let ((include-list (call-with-input-file include-file read)))
(for-each require-include include-list))))
(let ((source-file (string-append dir "/source.scm")))
(compile-file source-file))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (load-lib dir)
(let ((dir (resolve dir)))
(let ((import-file (string-append dir "/import")))
(if (file-exists? import-file)
(let ((import-list (call-with-input-file import-file read)))
(for-each require-lib import-list))))
(load (string-append dir "/source"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (file-newer? a b)
(> (time->seconds (file-info-last-modification-time (file-info a)))
(time->seconds (file-info-last-modification-time (file-info b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (freshen-lib lib)
(let ((dir (resolve lib)))
(let ((source-file (string-append dir "/source.scm"))
(compiled-file (string-append dir "/source.o1")))
(if (or (not (file-exists? compiled-file))
(not (file-newer? compiled-file source-file)))
(compile-lib lib)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (require-lib dir)
(cond ((not (member dir *loaded*))
(print "Loading lib " dir "\n")
(freshen-lib dir)
(load-lib dir)
(set! *loaded* (cons dir *loaded*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(load "src/boot/boot.scm")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define inexact exact->inexact)
(define exact inexact->exact)
(define (mod a b)
(modulo
(exact (round a))
(exact (round b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (current-time-in-nanoseconds)
(exact (* (time->seconds (current-time))
1000000000)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-syntax case-lambda
(syntax-rules ()
((case-lambda
(?a1 ?e1 ...)
?clause1 ...)
(lambda args
(let ((l (length args)))
(case-lambda "CLAUSE" args l
(?a1 ?e1 ...)
?clause1 ...))))
((case-lambda "CLAUSE" ?args ?l
((?a1 ...) ?e1 ...)
?clause1 ...)
(if (= ?l (length '(?a1 ...)))
(apply (lambda (?a1 ...) ?e1 ...) ?args)
(case-lambda "CLAUSE" ?args ?l
?clause1 ...)))
((case-lambda "CLAUSE" ?args ?l
((?a1 . ?ar) ?e1 ...)
?clause1 ...)
(case-lambda "IMPROPER" ?args ?l 1 (?a1 . ?ar) (?ar ?e1 ...)
?clause1 ...))
((case-lambda "CLAUSE" ?args ?l
(?a1 ?e1 ...)
?clause1 ...)
(let ((?a1 ?args))
?e1 ...))
((case-lambda "CLAUSE" ?args ?l)
(error "Wrong number of arguments to CASE-LAMBDA."))
((case-lambda "IMPROPER" ?args ?l ?k ?al ((?a1 . ?ar) ?e1 ...)
?clause1 ...)
(case-lambda "IMPROPER" ?args ?l (+ ?k 1) ?al (?ar ?e1 ...)
?clause1 ...))
((case-lambda "IMPROPER" ?args ?l ?k ?al (?ar ?e1 ...)
?clause1 ...)
(if (>= ?l ?k)
(apply (lambda ?al ?e1 ...) ?args)
(case-lambda "CLAUSE" ?args ?l
?clause1 ...)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(print "Abstracting is loaded\n") | null | https://raw.githubusercontent.com/dharmatech/abstracting/9dc5d9f45a9de03c6ee379f1928ebb393dfafc52/src/boot/gambit/gambit.scm | scheme |
(load "~~/Gambit-C/lib/syntax-case.scm")
(define (snarf dir)
(let ((import-file (string-append dir "/import"))
(include-file (string-append dir "/include"))
(export-file (string-append dir "/export"))
(compiled-file (string-append dir "/compiled-gambit")))
(for-each (lambda (lib) (snarf (resolve lib)))
(read (open-input-file import-file)))
(if (file-exists? compiled-file)
(scheme-load-compiled-file compiled-file)
(scheme-load-source-file source-file))))))
|
(load "support/gambit/srfi-1/srfi-1")
(define scheme-implementation 'gambit)
(define abstracting-root-directory (current-directory))
(define *roots* #f)
(define *loaded* '())
(define *included* '())
(define (directory-contains file)
(lambda (dir)
(file-exists?
(string-append dir "/" file))))
(define (resolve lib)
(let ((root (find (directory-contains lib) *roots*)))
(if root (string-append root "/" lib) #f)))
( let ( ( dir ( resolve ) ) )
( source - file ( string - append dir " " ) )
(define (load-include dir)
(let ((file (string-append (resolve dir) "/" "source.scm")))
(eval `(include ,file))))
(define (require-include dir)
(cond ((not (member dir *included*))
(print "Including " dir "\n")
(load-include dir)
(set! *included* (cons dir *included*)))))
(define (load-source dir)
(let ((dir (resolve dir)))
(let ((import-file (string-append dir "/import"))
(include-file (string-append dir "/include"))
(source-file (string-append dir "/source.scm")))
(if (file-exists? import-file)
(let ((import-list (call-with-input-file import-file read)))
(for-each load-source import-list)))
(if (file-exists? include-file)
(let ((include-list (call-with-input-file include-file read)))
(for-each require-include include-list)))
(print "Loading " source-file "\n")
(load source-file))))
(define (require-source dir)
(cond ((not (member dir *loaded*))
(load-source dir)
(set! *loaded* (cons dir *loaded*)))))
(define (compile-lib dir)
(print "Compiling " dir "\n")
(let ((dir (resolve dir)))
(let ((compiled-file (string-append dir "/source.o1")))
(if (file-exists? compiled-file)
(delete-file compiled-file)))
(let ((include-file (string-append dir "/include")))
(if (file-exists? include-file)
(let ((include-list (call-with-input-file include-file read)))
(for-each require-include include-list))))
(let ((source-file (string-append dir "/source.scm")))
(compile-file source-file))))
(define (load-lib dir)
(let ((dir (resolve dir)))
(let ((import-file (string-append dir "/import")))
(if (file-exists? import-file)
(let ((import-list (call-with-input-file import-file read)))
(for-each require-lib import-list))))
(load (string-append dir "/source"))))
(define (file-newer? a b)
(> (time->seconds (file-info-last-modification-time (file-info a)))
(time->seconds (file-info-last-modification-time (file-info b)))))
(define (freshen-lib lib)
(let ((dir (resolve lib)))
(let ((source-file (string-append dir "/source.scm"))
(compiled-file (string-append dir "/source.o1")))
(if (or (not (file-exists? compiled-file))
(not (file-newer? compiled-file source-file)))
(compile-lib lib)))))
(define (require-lib dir)
(cond ((not (member dir *loaded*))
(print "Loading lib " dir "\n")
(freshen-lib dir)
(load-lib dir)
(set! *loaded* (cons dir *loaded*)))))
(load "src/boot/boot.scm")
(define inexact exact->inexact)
(define exact inexact->exact)
(define (mod a b)
(modulo
(exact (round a))
(exact (round b))))
(define (current-time-in-nanoseconds)
(exact (* (time->seconds (current-time))
1000000000)))
(define-syntax case-lambda
(syntax-rules ()
((case-lambda
(?a1 ?e1 ...)
?clause1 ...)
(lambda args
(let ((l (length args)))
(case-lambda "CLAUSE" args l
(?a1 ?e1 ...)
?clause1 ...))))
((case-lambda "CLAUSE" ?args ?l
((?a1 ...) ?e1 ...)
?clause1 ...)
(if (= ?l (length '(?a1 ...)))
(apply (lambda (?a1 ...) ?e1 ...) ?args)
(case-lambda "CLAUSE" ?args ?l
?clause1 ...)))
((case-lambda "CLAUSE" ?args ?l
((?a1 . ?ar) ?e1 ...)
?clause1 ...)
(case-lambda "IMPROPER" ?args ?l 1 (?a1 . ?ar) (?ar ?e1 ...)
?clause1 ...))
((case-lambda "CLAUSE" ?args ?l
(?a1 ?e1 ...)
?clause1 ...)
(let ((?a1 ?args))
?e1 ...))
((case-lambda "CLAUSE" ?args ?l)
(error "Wrong number of arguments to CASE-LAMBDA."))
((case-lambda "IMPROPER" ?args ?l ?k ?al ((?a1 . ?ar) ?e1 ...)
?clause1 ...)
(case-lambda "IMPROPER" ?args ?l (+ ?k 1) ?al (?ar ?e1 ...)
?clause1 ...))
((case-lambda "IMPROPER" ?args ?l ?k ?al (?ar ?e1 ...)
?clause1 ...)
(if (>= ?l ?k)
(apply (lambda ?al ?e1 ...) ?args)
(case-lambda "CLAUSE" ?args ?l
?clause1 ...)))))
(print "Abstracting is loaded\n") |
b9b97974c3004e48b141bfe2dddd97472385860b2ba995ad33f3e9358095858e | coast-framework/db | helper.clj | (ns db.migrator.helper
(:require [helper.core :as helper]
[clojure.string :as string]
[env.core :as env]
[db.connector :as connector]))
(def rollback? (atom false))
(def sql {"sqlite" {:timestamp "integer"
:now "(strftime('%s', 'now'))"
:pk "integer primary key"}
"postgres" {:timestamp "timestamptz"
:now "now()"
:pk "serial primary key"}})
(defn not-null [m]
(when (false? (:null m))
"not null"))
(defn col-default [m]
(when (contains? m :default)
(str "default " (get m :default))))
(defn unique [m]
(when (true? (:unique m))
(str "unique")))
(defn collate [m]
(when (contains? m :collate)
(str "collate " (get m :collate))))
(defn col-type [type {:keys [precision scale]}]
(if (or (some? precision)
(some? scale))
(str (or (helper/sqlize type) "numeric")
(when (or (some? precision)
(some? scale))
(str "(" (string/join ","
(filter some? [(or precision 0) scale]))
")")))
(helper/sqlize type)))
(defn on-delete [m]
(when (contains? m :on-delete)
(str "on delete " (helper/sqlize (:on-delete m)))))
(defn on-update [m]
(when (contains? m :on-update)
(str "on update " (helper/sqlize (:on-update m)))))
(defn reference [m]
(when (contains? m :references)
(str "references " (:references m))))
(defn col [type col-name m]
"SQL fragment for adding a column in create or alter table"
(->> [(helper/sqlize col-name)
(col-type type m)
(unique m)
(collate m)
(not-null m)
(col-default m)
(reference m)
(on-delete m)
(on-update m)]
(filter some?)
(string/join " ")
(string/trim)))
(defn references [col-name & {:as m}]
(col :integer (str (name col-name) "-id") (merge {:null false :references (str (helper/sqlize col-name) "(id)") :index true :on-delete "cascade"} m)))
(defn drop-column
"SQL for dropping a column from a table"
[table col]
(str "alter table " (helper/sqlize table) " drop column " (helper/sqlize col)))
(defn add-column
"SQL for adding a column to an existing table"
[table col-name type & {:as m}]
(if (true? @rollback?)
(drop-column table col-name)
(str "alter table " (helper/sqlize table) " add column " (col type col-name m))))
(defn add-foreign-key
"SQL for adding a foreign key column to an existing table"
[from to & {col :col pk :pk fk-name :name :as m}]
(let [from (helper/sqlize from)
to (helper/sqlize to)
fk (if (some? col)
col
(helper/sqlize (str to "_id")))]
(string/join " "
(filter some?
["alter table"
from
"add constraint"
(or (helper/sqlize fk-name) (str from "_" to "_fk"))
"foreign key"
(str "(" fk ")")
"references"
to
(str "(" (or (helper/sqlize pk) "id") ")")
(on-delete m)
(on-update m)]))))
(defn where [m]
(when (contains? m :where)
(str "where " (:where m))))
(defn index-cols [cols {order :order}]
(->> (map #(conj [%] (get order %)) cols)
(map #(map helper/sqlize %))
(map #(string/join " " %))
(map string/trim)))
(defn add-index
"SQL for adding an index to an existing table"
[table-name cols & {:as m}]
(let [table-name (helper/sqlize table-name)
cols (if (sequential? cols)
cols
[cols])
cols (index-cols cols m)
col-name (string/join ", " cols)
index-col-names (map #(string/replace % #" " "_") cols)
index-name (or (:name m) (str table-name "_" (string/join "_" index-col-names) "_index"))]
(string/join " "
(filter some?
["create"
(unique m)
"index"
index-name
"on"
table-name
(str "(" col-name ")")
(where m)]))))
(defn add-reference
"SQL for adding a foreign key column to an existing table"
[table-name ref-name & {:as m}]
(string/join " "
(filter some?
["alter table"
(helper/sqlize table-name)
"add column"
(helper/sqlize (or (:column m) (str ref-name "_id")))
(or (-> m :type helper/sqlize) "integer")
"references"
(helper/sqlize ref-name)
(str "(id)")])))
(defn alter-column [table-name col-name type & {:as m}]
(string/join " "
(filter some?
["alter table"
(helper/sqlize table-name)
"alter column"
(helper/sqlize col-name)
"type"
(helper/sqlize type)
(when (contains? m :using)
(str "using " (:using m)))])))
(defn text [col-name & {:as m}]
(col :text col-name m))
(defn timestamp [col-name & {:as m}]
(col :timestamp col-name m))
(defn datetime [col-name & {:as m}]
(col :datetime col-name m))
(defn timestamptz [col-name & {:as m}]
(col :timestamptz col-name m))
(defn integer [col-name & {:as m}]
(col :integer col-name m))
(defn bool [col-name & {:as m}]
(col :boolean col-name m))
(defn decimal [col-name & {:as m}]
(col :decimal col-name m))
(defn json [col-name & {:as m}]
(col :json col-name m))
(defn uuid [col-name & {:as m}]
(col :uuid col-name m))
(defn drop-table [table]
(str "drop table " (helper/sqlize table)))
(defn reference-col [s]
(let [ref-col (-> (re-find #"references (\w+)" s)
(last))]
(when (some? ref-col)
(str ref-col "_id"))))
(defn create-table
"SQL to create a table"
[table & args]
(let [ctx (connector/context (env/env :coast-env))]
(if (true? @rollback?)
(drop-table table)
(let [args (if (sequential? args) args '())
[opts args] (if (map? (first args))
[(first args) (rest args)]
[{} args])
index-sql-strings (->> (map reference-col args)
(filter some?)
(map #(add-index table %)))
pk-col (or (:primary-key opts) "id")
not-exists (if (true? (:if-not-exists opts))
"if not exists "
"")]
(concat
[(string/join " "
(filter some?
[(str "create table " not-exists (helper/sqlize table) " (")
(string/join ", "
(conj args (str pk-col " " (get-in sql [(:adapter ctx) :pk]))))
")"]))]
index-sql-strings)))))
(defn create-extension [s]
(str "create extension " s))
(defn drop-extension [s]
(str "drop extension " s))
(defn drop-foreign-key [alter-table-name & {:as m}]
(let [constraint (when (contains? m :table)
(helper/sqlize (:table m)) "_" (helper/sqlize alter-table-name) "_fkey")
constraint (if (contains? m :name)
(helper/sqlize (:name m))
constraint)]
(str "alter table " (helper/sqlize alter-table-name) " drop constraint " constraint)))
(defn drop-index [table-name & {cols :column :as m}]
(let [cols (if (sequential? cols) cols [cols])
cols (index-cols cols m)
index-col-names (map #(string/replace % #" " "_") cols)
index-name (or (-> m :name helper/sqlize) (str table-name "_" (string/join "_" index-col-names) "_index"))]
(str "drop index " index-name)))
(defn drop-reference [table-name ref-name]
(str "alter table "
(helper/sqlize table-name)
" drop constraint "
(helper/sqlize ref-name) "_" (helper/sqlize table-name) "_fkey"))
(defn rename-column [table-name column-name new-column-name]
(string/join " "
["alter table"
(helper/sqlize table-name)
"rename column"
(helper/sqlize column-name)
"to"
(helper/sqlize new-column-name)]))
(defn rename-index [index-name new-index-name]
(string/join " "
["alter index"
(helper/sqlize index-name)
"rename to"
(helper/sqlize new-index-name)]))
(defn rename-table [table-name new-table-name]
(string/join " "
["alter table"
(helper/sqlize table-name)
"rename to"
(helper/sqlize new-table-name)]))
(defn timestamps []
(let [{:keys [adapter]} (connector/context (env/env :coast-env))]
(string/join " "
[(str "updated_at " (get-in sql [adapter :timestamp]) ",")
(str "created_at " (get-in sql [adapter :timestamp]) " not null default " (get-in sql [adapter :now]))])))
| null | https://raw.githubusercontent.com/coast-framework/db/e738cd6402a89c591363ac6f3e7a6e08bcc28a0e/src/db/migrator/helper.clj | clojure | (ns db.migrator.helper
(:require [helper.core :as helper]
[clojure.string :as string]
[env.core :as env]
[db.connector :as connector]))
(def rollback? (atom false))
(def sql {"sqlite" {:timestamp "integer"
:now "(strftime('%s', 'now'))"
:pk "integer primary key"}
"postgres" {:timestamp "timestamptz"
:now "now()"
:pk "serial primary key"}})
(defn not-null [m]
(when (false? (:null m))
"not null"))
(defn col-default [m]
(when (contains? m :default)
(str "default " (get m :default))))
(defn unique [m]
(when (true? (:unique m))
(str "unique")))
(defn collate [m]
(when (contains? m :collate)
(str "collate " (get m :collate))))
(defn col-type [type {:keys [precision scale]}]
(if (or (some? precision)
(some? scale))
(str (or (helper/sqlize type) "numeric")
(when (or (some? precision)
(some? scale))
(str "(" (string/join ","
(filter some? [(or precision 0) scale]))
")")))
(helper/sqlize type)))
(defn on-delete [m]
(when (contains? m :on-delete)
(str "on delete " (helper/sqlize (:on-delete m)))))
(defn on-update [m]
(when (contains? m :on-update)
(str "on update " (helper/sqlize (:on-update m)))))
(defn reference [m]
(when (contains? m :references)
(str "references " (:references m))))
(defn col [type col-name m]
"SQL fragment for adding a column in create or alter table"
(->> [(helper/sqlize col-name)
(col-type type m)
(unique m)
(collate m)
(not-null m)
(col-default m)
(reference m)
(on-delete m)
(on-update m)]
(filter some?)
(string/join " ")
(string/trim)))
(defn references [col-name & {:as m}]
(col :integer (str (name col-name) "-id") (merge {:null false :references (str (helper/sqlize col-name) "(id)") :index true :on-delete "cascade"} m)))
(defn drop-column
"SQL for dropping a column from a table"
[table col]
(str "alter table " (helper/sqlize table) " drop column " (helper/sqlize col)))
(defn add-column
"SQL for adding a column to an existing table"
[table col-name type & {:as m}]
(if (true? @rollback?)
(drop-column table col-name)
(str "alter table " (helper/sqlize table) " add column " (col type col-name m))))
(defn add-foreign-key
"SQL for adding a foreign key column to an existing table"
[from to & {col :col pk :pk fk-name :name :as m}]
(let [from (helper/sqlize from)
to (helper/sqlize to)
fk (if (some? col)
col
(helper/sqlize (str to "_id")))]
(string/join " "
(filter some?
["alter table"
from
"add constraint"
(or (helper/sqlize fk-name) (str from "_" to "_fk"))
"foreign key"
(str "(" fk ")")
"references"
to
(str "(" (or (helper/sqlize pk) "id") ")")
(on-delete m)
(on-update m)]))))
(defn where [m]
(when (contains? m :where)
(str "where " (:where m))))
(defn index-cols [cols {order :order}]
(->> (map #(conj [%] (get order %)) cols)
(map #(map helper/sqlize %))
(map #(string/join " " %))
(map string/trim)))
(defn add-index
"SQL for adding an index to an existing table"
[table-name cols & {:as m}]
(let [table-name (helper/sqlize table-name)
cols (if (sequential? cols)
cols
[cols])
cols (index-cols cols m)
col-name (string/join ", " cols)
index-col-names (map #(string/replace % #" " "_") cols)
index-name (or (:name m) (str table-name "_" (string/join "_" index-col-names) "_index"))]
(string/join " "
(filter some?
["create"
(unique m)
"index"
index-name
"on"
table-name
(str "(" col-name ")")
(where m)]))))
(defn add-reference
"SQL for adding a foreign key column to an existing table"
[table-name ref-name & {:as m}]
(string/join " "
(filter some?
["alter table"
(helper/sqlize table-name)
"add column"
(helper/sqlize (or (:column m) (str ref-name "_id")))
(or (-> m :type helper/sqlize) "integer")
"references"
(helper/sqlize ref-name)
(str "(id)")])))
(defn alter-column [table-name col-name type & {:as m}]
(string/join " "
(filter some?
["alter table"
(helper/sqlize table-name)
"alter column"
(helper/sqlize col-name)
"type"
(helper/sqlize type)
(when (contains? m :using)
(str "using " (:using m)))])))
(defn text [col-name & {:as m}]
(col :text col-name m))
(defn timestamp [col-name & {:as m}]
(col :timestamp col-name m))
(defn datetime [col-name & {:as m}]
(col :datetime col-name m))
(defn timestamptz [col-name & {:as m}]
(col :timestamptz col-name m))
(defn integer [col-name & {:as m}]
(col :integer col-name m))
(defn bool [col-name & {:as m}]
(col :boolean col-name m))
(defn decimal [col-name & {:as m}]
(col :decimal col-name m))
(defn json [col-name & {:as m}]
(col :json col-name m))
(defn uuid [col-name & {:as m}]
(col :uuid col-name m))
(defn drop-table [table]
(str "drop table " (helper/sqlize table)))
(defn reference-col [s]
(let [ref-col (-> (re-find #"references (\w+)" s)
(last))]
(when (some? ref-col)
(str ref-col "_id"))))
(defn create-table
"SQL to create a table"
[table & args]
(let [ctx (connector/context (env/env :coast-env))]
(if (true? @rollback?)
(drop-table table)
(let [args (if (sequential? args) args '())
[opts args] (if (map? (first args))
[(first args) (rest args)]
[{} args])
index-sql-strings (->> (map reference-col args)
(filter some?)
(map #(add-index table %)))
pk-col (or (:primary-key opts) "id")
not-exists (if (true? (:if-not-exists opts))
"if not exists "
"")]
(concat
[(string/join " "
(filter some?
[(str "create table " not-exists (helper/sqlize table) " (")
(string/join ", "
(conj args (str pk-col " " (get-in sql [(:adapter ctx) :pk]))))
")"]))]
index-sql-strings)))))
(defn create-extension [s]
(str "create extension " s))
(defn drop-extension [s]
(str "drop extension " s))
(defn drop-foreign-key [alter-table-name & {:as m}]
(let [constraint (when (contains? m :table)
(helper/sqlize (:table m)) "_" (helper/sqlize alter-table-name) "_fkey")
constraint (if (contains? m :name)
(helper/sqlize (:name m))
constraint)]
(str "alter table " (helper/sqlize alter-table-name) " drop constraint " constraint)))
(defn drop-index [table-name & {cols :column :as m}]
(let [cols (if (sequential? cols) cols [cols])
cols (index-cols cols m)
index-col-names (map #(string/replace % #" " "_") cols)
index-name (or (-> m :name helper/sqlize) (str table-name "_" (string/join "_" index-col-names) "_index"))]
(str "drop index " index-name)))
(defn drop-reference [table-name ref-name]
(str "alter table "
(helper/sqlize table-name)
" drop constraint "
(helper/sqlize ref-name) "_" (helper/sqlize table-name) "_fkey"))
(defn rename-column [table-name column-name new-column-name]
(string/join " "
["alter table"
(helper/sqlize table-name)
"rename column"
(helper/sqlize column-name)
"to"
(helper/sqlize new-column-name)]))
(defn rename-index [index-name new-index-name]
(string/join " "
["alter index"
(helper/sqlize index-name)
"rename to"
(helper/sqlize new-index-name)]))
(defn rename-table [table-name new-table-name]
(string/join " "
["alter table"
(helper/sqlize table-name)
"rename to"
(helper/sqlize new-table-name)]))
(defn timestamps []
(let [{:keys [adapter]} (connector/context (env/env :coast-env))]
(string/join " "
[(str "updated_at " (get-in sql [adapter :timestamp]) ",")
(str "created_at " (get-in sql [adapter :timestamp]) " not null default " (get-in sql [adapter :now]))])))
| |
65bbc32a180afd36f4bccb6bd4f8a2c6930a3985ae030741ef083d9092ecec86 | maximedenes/native-coq | cctac.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i camlp4deps: "parsing/grammar.cma" i*)
This file is the interface between the c - c algorithm and Coq
open Evd
open Proof_type
open Names
open Libnames
open Nameops
open Inductiveops
open Declarations
open Term
open Tacmach
open Tactics
open Tacticals
open Typing
open Ccalgo
open Tacinterp
open Ccproof
open Pp
open Errors
open Util
open Format
let constant dir s = lazy (Coqlib.gen_constant "CC" dir s)
let _f_equal = constant ["Init";"Logic"] "f_equal"
let _eq_rect = constant ["Init";"Logic"] "eq_rect"
let _refl_equal = constant ["Init";"Logic"] "refl_equal"
let _sym_eq = constant ["Init";"Logic"] "sym_eq"
let _trans_eq = constant ["Init";"Logic"] "trans_eq"
let _eq = constant ["Init";"Logic"] "eq"
let _False = constant ["Init";"Logic"] "False"
let whd env=
let infos=Closure.create_clos_infos Closure.betaiotazeta env in
(fun t -> Closure.whd_val infos (Closure.inject t))
let whd_delta env=
let infos=Closure.create_clos_infos Closure.betadeltaiota env in
(fun t -> Closure.whd_val infos (Closure.inject t))
(* decompose member of equality in an applicative format *)
let sf_of env sigma c = family_of_sort (sort_of env sigma c)
let rec decompose_term env sigma t=
match kind_of_term (whd env t) with
App (f,args)->
let tf=decompose_term env sigma f in
let targs=Array.map (decompose_term env sigma) args in
Array.fold_left (fun s t->Appli (s,t)) tf targs
| Prod (_,a,_b) when not (Termops.dependent (mkRel 1) _b) ->
let b = Termops.pop _b in
let sort_b = sf_of env sigma b in
let sort_a = sf_of env sigma a in
Appli(Appli(Product (sort_a,sort_b) ,
decompose_term env sigma a),
decompose_term env sigma b)
| Construct c->
let (mind,i_ind),i_con = c in
let canon_mind = mind_of_kn (canonical_mind mind) in
let canon_ind = canon_mind,i_ind in
let (oib,_)=Global.lookup_inductive (canon_ind) in
let nargs=mis_constructor_nargs_env env (canon_ind,i_con) in
Constructor {ci_constr= (canon_ind,i_con);
ci_arity=nargs;
ci_nhyps=nargs-oib.mind_nparams}
| Ind c ->
let mind,i_ind = c in
let canon_mind = mind_of_kn (canonical_mind mind) in
let canon_ind = canon_mind,i_ind in (Symb (mkInd canon_ind))
| Const c ->
let canon_const = constant_of_kn (canonical_con c) in
(Symb (mkConst canon_const))
| _ ->if closed0 t then (Symb t) else raise Not_found
(* decompose equality in members and type *)
let atom_of_constr env sigma term =
let wh = (whd_delta env term) in
let kot = kind_of_term wh in
match kot with
App (f,args)->
if eq_constr f (Lazy.force _eq) && (Array.length args)=3
then `Eq (args.(0),
decompose_term env sigma args.(1),
decompose_term env sigma args.(2))
else `Other (decompose_term env sigma term)
| _ -> `Other (decompose_term env sigma term)
let rec pattern_of_constr env sigma c =
match kind_of_term (whd env c) with
App (f,args)->
let pf = decompose_term env sigma f in
let pargs,lrels = List.split
(array_map_to_list (pattern_of_constr env sigma) args) in
PApp (pf,List.rev pargs),
List.fold_left Intset.union Intset.empty lrels
| Prod (_,a,_b) when not (Termops.dependent (mkRel 1) _b) ->
let b = Termops.pop _b in
let pa,sa = pattern_of_constr env sigma a in
let pb,sb = pattern_of_constr env sigma b in
let sort_b = sf_of env sigma b in
let sort_a = sf_of env sigma a in
PApp(Product (sort_a,sort_b),
[pa;pb]),(Intset.union sa sb)
| Rel i -> PVar i,Intset.singleton i
| _ ->
let pf = decompose_term env sigma c in
PApp (pf,[]),Intset.empty
let non_trivial = function
PVar _ -> false
| _ -> true
let patterns_of_constr env sigma nrels term=
let f,args=
try destApp (whd_delta env term) with _ -> raise Not_found in
if eq_constr f (Lazy.force _eq) && (Array.length args)=3
then
let patt1,rels1 = pattern_of_constr env sigma args.(1)
and patt2,rels2 = pattern_of_constr env sigma args.(2) in
let valid1 =
if Intset.cardinal rels1 <> nrels then Creates_variables
else if non_trivial patt1 then Normal
else Trivial args.(0)
and valid2 =
if Intset.cardinal rels2 <> nrels then Creates_variables
else if non_trivial patt2 then Normal
else Trivial args.(0) in
if valid1 <> Creates_variables
|| valid2 <> Creates_variables then
nrels,valid1,patt1,valid2,patt2
else raise Not_found
else raise Not_found
let rec quantified_atom_of_constr env sigma nrels term =
match kind_of_term (whd_delta env term) with
Prod (id,atom,ff) ->
if eq_constr ff (Lazy.force _False) then
let patts=patterns_of_constr env sigma nrels atom in
`Nrule patts
else
quantified_atom_of_constr (Environ.push_rel (id,None,atom) env) sigma (succ nrels) ff
| _ ->
let patts=patterns_of_constr env sigma nrels term in
`Rule patts
let litteral_of_constr env sigma term=
match kind_of_term (whd_delta env term) with
| Prod (id,atom,ff) ->
if eq_constr ff (Lazy.force _False) then
match (atom_of_constr env sigma atom) with
`Eq(t,a,b) -> `Neq(t,a,b)
| `Other(p) -> `Nother(p)
else
begin
try
quantified_atom_of_constr (Environ.push_rel (id,None,atom) env) sigma 1 ff
with Not_found ->
`Other (decompose_term env sigma term)
end
| _ ->
atom_of_constr env sigma term
(* store all equalities from the context *)
let rec make_prb gls depth additionnal_terms =
let env=pf_env gls in
let sigma=sig_sig gls in
let state = empty depth gls in
let pos_hyps = ref [] in
let neg_hyps =ref [] in
List.iter
(fun c ->
let t = decompose_term env sigma c in
ignore (add_term state t)) additionnal_terms;
List.iter
(fun (id,_,e) ->
begin
let cid=mkVar id in
match litteral_of_constr env sigma e with
`Eq (t,a,b) -> add_equality state cid a b
| `Neq (t,a,b) -> add_disequality state (Hyp cid) a b
| `Other ph ->
List.iter
(fun (cidn,nh) ->
add_disequality state (HeqnH (cid,cidn)) ph nh)
!neg_hyps;
pos_hyps:=(cid,ph):: !pos_hyps
| `Nother nh ->
List.iter
(fun (cidp,ph) ->
add_disequality state (HeqnH (cidp,cid)) ph nh)
!pos_hyps;
neg_hyps:=(cid,nh):: !neg_hyps
| `Rule patts -> add_quant state id true patts
| `Nrule patts -> add_quant state id false patts
end) (Environ.named_context_of_val (Goal.V82.hyps gls.sigma gls.it));
begin
match atom_of_constr env sigma (pf_concl gls) with
`Eq (t,a,b) -> add_disequality state Goal a b
| `Other g ->
List.iter
(fun (idp,ph) ->
add_disequality state (HeqG idp) ph g) !pos_hyps
end;
state
indhyps builds the array of arrays of constructor hyps for ( )
let build_projection intype outtype (cstr:constructor) special default gls=
let env=pf_env gls in
let (h,argv) =
try destApp intype with
Invalid_argument _ -> (intype,[||]) in
let ind=destInd h in
let types=Inductiveops.arities_of_constructors env ind in
let lp=Array.length types in
let ci=pred (snd cstr) in
let branch i=
let ti=Term.prod_appvect types.(i) argv in
let rc=fst (decompose_prod_assum ti) in
let head=
if i=ci then special else default in
it_mkLambda_or_LetIn head rc in
let branches=Array.init lp branch in
let casee=mkRel 1 in
let pred=mkLambda(Anonymous,intype,outtype) in
let case_info=make_case_info (pf_env gls) ind RegularStyle in
let body= mkCase(case_info, pred, casee, branches) in
let id=pf_get_new_id (id_of_string "t") gls in
mkLambda(Name id,intype,body)
(* generate an adhoc tactic following the proof tree *)
let _M =mkMeta
let rec proof_tac p gls =
match p.p_rule with
Ax c -> exact_check c gls
| SymAx c ->
let l=constr_of_term p.p_lhs and
r=constr_of_term p.p_rhs in
let typ = Termops.refresh_universes (pf_type_of gls l) in
exact_check
(mkApp(Lazy.force _sym_eq,[|typ;r;l;c|])) gls
| Refl t ->
let lr = constr_of_term t in
let typ = Termops.refresh_universes (pf_type_of gls lr) in
exact_check
(mkApp(Lazy.force _refl_equal,[|typ;constr_of_term t|])) gls
| Trans (p1,p2)->
let t1 = constr_of_term p1.p_lhs and
t2 = constr_of_term p1.p_rhs and
t3 = constr_of_term p2.p_rhs in
let typ = Termops.refresh_universes (pf_type_of gls t2) in
let prf =
mkApp(Lazy.force _trans_eq,[|typ;t1;t2;t3;_M 1;_M 2|]) in
tclTHENS (refine prf) [(proof_tac p1);(proof_tac p2)] gls
| Congr (p1,p2)->
let tf1=constr_of_term p1.p_lhs
and tx1=constr_of_term p2.p_lhs
and tf2=constr_of_term p1.p_rhs
and tx2=constr_of_term p2.p_rhs in
let typf = Termops.refresh_universes (pf_type_of gls tf1) in
let typx = Termops.refresh_universes (pf_type_of gls tx1) in
let typfx = Termops.refresh_universes (pf_type_of gls (mkApp (tf1,[|tx1|]))) in
let id = pf_get_new_id (id_of_string "f") gls in
let appx1 = mkLambda(Name id,typf,mkApp(mkRel 1,[|tx1|])) in
let lemma1 =
mkApp(Lazy.force _f_equal,
[|typf;typfx;appx1;tf1;tf2;_M 1|]) in
let lemma2=
mkApp(Lazy.force _f_equal,
[|typx;typfx;tf2;tx1;tx2;_M 1|]) in
let prf =
mkApp(Lazy.force _trans_eq,
[|typfx;
mkApp(tf1,[|tx1|]);
mkApp(tf2,[|tx1|]);
mkApp(tf2,[|tx2|]);_M 2;_M 3|]) in
tclTHENS (refine prf)
[tclTHEN (refine lemma1) (proof_tac p1);
tclFIRST
[tclTHEN (refine lemma2) (proof_tac p2);
reflexivity;
fun gls ->
errorlabstrm "Congruence"
(Pp.str
"I don't know how to handle dependent equality")]] gls
| Inject (prf,cstr,nargs,argind) ->
let ti=constr_of_term prf.p_lhs in
let tj=constr_of_term prf.p_rhs in
let default=constr_of_term p.p_lhs in
let intype = Termops.refresh_universes (pf_type_of gls ti) in
let outtype = Termops.refresh_universes (pf_type_of gls default) in
let special=mkRel (1+nargs-argind) in
let proj=build_projection intype outtype cstr special default gls in
let injt=
mkApp (Lazy.force _f_equal,[|intype;outtype;proj;ti;tj;_M 1|]) in
tclTHEN (refine injt) (proof_tac prf) gls
let refute_tac c t1 t2 p gls =
let tt1=constr_of_term t1 and tt2=constr_of_term t2 in
let intype = Termops.refresh_universes (pf_type_of gls tt1) in
let neweq=
mkApp(Lazy.force _eq,
[|intype;tt1;tt2|]) in
let hid=pf_get_new_id (id_of_string "Heq") gls in
let false_t=mkApp (c,[|mkVar hid|]) in
tclTHENS (assert_tac (Name hid) neweq)
[proof_tac p; simplest_elim false_t] gls
let convert_to_goal_tac c t1 t2 p gls =
let tt1=constr_of_term t1 and tt2=constr_of_term t2 in
let sort = Termops.refresh_universes (pf_type_of gls tt2) in
let neweq=mkApp(Lazy.force _eq,[|sort;tt1;tt2|]) in
let e=pf_get_new_id (id_of_string "e") gls in
let x=pf_get_new_id (id_of_string "X") gls in
let identity=mkLambda (Name x,sort,mkRel 1) in
let endt=mkApp (Lazy.force _eq_rect,
[|sort;tt1;identity;c;tt2;mkVar e|]) in
tclTHENS (assert_tac (Name e) neweq)
[proof_tac p;exact_check endt] gls
let convert_to_hyp_tac c1 t1 c2 t2 p gls =
let tt2=constr_of_term t2 in
let h=pf_get_new_id (id_of_string "H") gls in
let false_t=mkApp (c2,[|mkVar h|]) in
tclTHENS (assert_tac (Name h) tt2)
[convert_to_goal_tac c1 t1 t2 p;
simplest_elim false_t] gls
let discriminate_tac cstr p gls =
let t1=constr_of_term p.p_lhs and t2=constr_of_term p.p_rhs in
let intype = Termops.refresh_universes (pf_type_of gls t1) in
let concl=pf_concl gls in
let outsort = mkType (Termops.new_univ ()) in
let xid=pf_get_new_id (id_of_string "X") gls in
let tid=pf_get_new_id (id_of_string "t") gls in
let identity=mkLambda(Name xid,outsort,mkLambda(Name tid,mkRel 1,mkRel 1)) in
let trivial=pf_type_of gls identity in
let outtype = mkType (Termops.new_univ ()) in
let pred=mkLambda(Name xid,outtype,mkRel 1) in
let hid=pf_get_new_id (id_of_string "Heq") gls in
let proj=build_projection intype outtype cstr trivial concl gls in
let injt=mkApp (Lazy.force _f_equal,
[|intype;outtype;proj;t1;t2;mkVar hid|]) in
let endt=mkApp (Lazy.force _eq_rect,
[|outtype;trivial;pred;identity;concl;injt|]) in
let neweq=mkApp(Lazy.force _eq,[|intype;t1;t2|]) in
tclTHENS (assert_tac (Name hid) neweq)
[proof_tac p;exact_check endt] gls
(* wrap everything *)
let build_term_to_complete uf meta pac =
let cinfo = get_constructor_info uf pac.cnode in
let real_args = List.map (fun i -> constr_of_term (term uf i)) pac.args in
let dummy_args = List.rev (list_tabulate meta pac.arity) in
let all_args = List.rev_append real_args dummy_args in
applistc (mkConstruct cinfo.ci_constr) all_args
let cc_tactic depth additionnal_terms gls=
Coqlib.check_required_library ["Coq";"Init";"Logic"];
let _ = debug Pp.msgnl (Pp.str "Reading subgoal ...") in
let state = make_prb gls depth additionnal_terms in
let _ = debug Pp.msgnl (Pp.str "Problem built, solving ...") in
let sol = execute true state in
let _ = debug Pp.msgnl (Pp.str "Computation completed.") in
let uf=forest state in
match sol with
None -> tclFAIL 0 (str "congruence failed") gls
| Some reason ->
debug Pp.msgnl (Pp.str "Goal solved, generating proof ...");
match reason with
Discrimination (i,ipac,j,jpac) ->
let p=build_proof uf (`Discr (i,ipac,j,jpac)) in
let cstr=(get_constructor_info uf ipac.cnode).ci_constr in
discriminate_tac cstr p gls
| Incomplete ->
let metacnt = ref 0 in
let newmeta _ = incr metacnt; _M !metacnt in
let terms_to_complete =
List.map
(build_term_to_complete uf newmeta)
(epsilons uf) in
Pp.msgnl
(Pp.str "Goal is solvable by congruence but \
some arguments are missing.");
Pp.msgnl
(Pp.str " Try " ++
hov 8
begin
str "\"congruence with (" ++
prlist_with_sep
(fun () -> str ")" ++ spc () ++ str "(")
(Termops.print_constr_env (pf_env gls))
terms_to_complete ++
str ")\","
end);
Pp.msgnl
(Pp.str " replacing metavariables by arbitrary terms.");
tclFAIL 0 (str "Incomplete") gls
| Contradiction dis ->
let p=build_proof uf (`Prove (dis.lhs,dis.rhs)) in
let ta=term uf dis.lhs and tb=term uf dis.rhs in
match dis.rule with
Goal -> proof_tac p gls
| Hyp id -> refute_tac id ta tb p gls
| HeqG id ->
convert_to_goal_tac id ta tb p gls
| HeqnH (ida,idb) ->
convert_to_hyp_tac ida ta idb tb p gls
let cc_fail gls =
errorlabstrm "Congruence" (Pp.str "congruence failed.")
let congruence_tac depth l =
tclORELSE
(tclTHEN (tclREPEAT introf) (cc_tactic depth l))
cc_fail
Beware : reflexivity = constructor 1 = apply refl_equal
might be slow now , let 's rather do something equivalent
to a " simple apply refl_equal "
might be slow now, let's rather do something equivalent
to a "simple apply refl_equal" *)
let simple_reflexivity () = apply (Lazy.force _refl_equal)
(* The [f_equal] tactic.
It mimics the use of lemmas [f_equal], [f_equal2], etc.
This isn't particularly related with congruence, apart from
the fact that congruence is called internally.
*)
let f_equal gl =
let cut_eq c1 c2 =
let ty = Termops.refresh_universes (pf_type_of gl c1) in
tclTHENTRY
(Tactics.cut (mkApp (Lazy.force _eq, [|ty; c1; c2|])))
(simple_reflexivity ())
in
try match kind_of_term (pf_concl gl) with
| App (r,[|_;t;t'|]) when eq_constr r (Lazy.force _eq) ->
begin match kind_of_term t, kind_of_term t' with
| App (f,v), App (f',v') when Array.length v = Array.length v' ->
let rec cuts i =
if i < 0 then tclTRY (congruence_tac 1000 [])
else tclTHENFIRST (cut_eq v.(i) v'.(i)) (cuts (i-1))
in cuts (Array.length v - 1) gl
| _ -> tclIDTAC gl
end
| _ -> tclIDTAC gl
with Type_errors.TypeError _ -> tclIDTAC gl
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/plugins/cc/cctac.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i camlp4deps: "parsing/grammar.cma" i
decompose member of equality in an applicative format
decompose equality in members and type
store all equalities from the context
generate an adhoc tactic following the proof tree
wrap everything
The [f_equal] tactic.
It mimics the use of lemmas [f_equal], [f_equal2], etc.
This isn't particularly related with congruence, apart from
the fact that congruence is called internally.
| v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
This file is the interface between the c - c algorithm and Coq
open Evd
open Proof_type
open Names
open Libnames
open Nameops
open Inductiveops
open Declarations
open Term
open Tacmach
open Tactics
open Tacticals
open Typing
open Ccalgo
open Tacinterp
open Ccproof
open Pp
open Errors
open Util
open Format
let constant dir s = lazy (Coqlib.gen_constant "CC" dir s)
let _f_equal = constant ["Init";"Logic"] "f_equal"
let _eq_rect = constant ["Init";"Logic"] "eq_rect"
let _refl_equal = constant ["Init";"Logic"] "refl_equal"
let _sym_eq = constant ["Init";"Logic"] "sym_eq"
let _trans_eq = constant ["Init";"Logic"] "trans_eq"
let _eq = constant ["Init";"Logic"] "eq"
let _False = constant ["Init";"Logic"] "False"
let whd env=
let infos=Closure.create_clos_infos Closure.betaiotazeta env in
(fun t -> Closure.whd_val infos (Closure.inject t))
let whd_delta env=
let infos=Closure.create_clos_infos Closure.betadeltaiota env in
(fun t -> Closure.whd_val infos (Closure.inject t))
let sf_of env sigma c = family_of_sort (sort_of env sigma c)
let rec decompose_term env sigma t=
match kind_of_term (whd env t) with
App (f,args)->
let tf=decompose_term env sigma f in
let targs=Array.map (decompose_term env sigma) args in
Array.fold_left (fun s t->Appli (s,t)) tf targs
| Prod (_,a,_b) when not (Termops.dependent (mkRel 1) _b) ->
let b = Termops.pop _b in
let sort_b = sf_of env sigma b in
let sort_a = sf_of env sigma a in
Appli(Appli(Product (sort_a,sort_b) ,
decompose_term env sigma a),
decompose_term env sigma b)
| Construct c->
let (mind,i_ind),i_con = c in
let canon_mind = mind_of_kn (canonical_mind mind) in
let canon_ind = canon_mind,i_ind in
let (oib,_)=Global.lookup_inductive (canon_ind) in
let nargs=mis_constructor_nargs_env env (canon_ind,i_con) in
Constructor {ci_constr= (canon_ind,i_con);
ci_arity=nargs;
ci_nhyps=nargs-oib.mind_nparams}
| Ind c ->
let mind,i_ind = c in
let canon_mind = mind_of_kn (canonical_mind mind) in
let canon_ind = canon_mind,i_ind in (Symb (mkInd canon_ind))
| Const c ->
let canon_const = constant_of_kn (canonical_con c) in
(Symb (mkConst canon_const))
| _ ->if closed0 t then (Symb t) else raise Not_found
let atom_of_constr env sigma term =
let wh = (whd_delta env term) in
let kot = kind_of_term wh in
match kot with
App (f,args)->
if eq_constr f (Lazy.force _eq) && (Array.length args)=3
then `Eq (args.(0),
decompose_term env sigma args.(1),
decompose_term env sigma args.(2))
else `Other (decompose_term env sigma term)
| _ -> `Other (decompose_term env sigma term)
let rec pattern_of_constr env sigma c =
match kind_of_term (whd env c) with
App (f,args)->
let pf = decompose_term env sigma f in
let pargs,lrels = List.split
(array_map_to_list (pattern_of_constr env sigma) args) in
PApp (pf,List.rev pargs),
List.fold_left Intset.union Intset.empty lrels
| Prod (_,a,_b) when not (Termops.dependent (mkRel 1) _b) ->
let b = Termops.pop _b in
let pa,sa = pattern_of_constr env sigma a in
let pb,sb = pattern_of_constr env sigma b in
let sort_b = sf_of env sigma b in
let sort_a = sf_of env sigma a in
PApp(Product (sort_a,sort_b),
[pa;pb]),(Intset.union sa sb)
| Rel i -> PVar i,Intset.singleton i
| _ ->
let pf = decompose_term env sigma c in
PApp (pf,[]),Intset.empty
let non_trivial = function
PVar _ -> false
| _ -> true
let patterns_of_constr env sigma nrels term=
let f,args=
try destApp (whd_delta env term) with _ -> raise Not_found in
if eq_constr f (Lazy.force _eq) && (Array.length args)=3
then
let patt1,rels1 = pattern_of_constr env sigma args.(1)
and patt2,rels2 = pattern_of_constr env sigma args.(2) in
let valid1 =
if Intset.cardinal rels1 <> nrels then Creates_variables
else if non_trivial patt1 then Normal
else Trivial args.(0)
and valid2 =
if Intset.cardinal rels2 <> nrels then Creates_variables
else if non_trivial patt2 then Normal
else Trivial args.(0) in
if valid1 <> Creates_variables
|| valid2 <> Creates_variables then
nrels,valid1,patt1,valid2,patt2
else raise Not_found
else raise Not_found
let rec quantified_atom_of_constr env sigma nrels term =
match kind_of_term (whd_delta env term) with
Prod (id,atom,ff) ->
if eq_constr ff (Lazy.force _False) then
let patts=patterns_of_constr env sigma nrels atom in
`Nrule patts
else
quantified_atom_of_constr (Environ.push_rel (id,None,atom) env) sigma (succ nrels) ff
| _ ->
let patts=patterns_of_constr env sigma nrels term in
`Rule patts
let litteral_of_constr env sigma term=
match kind_of_term (whd_delta env term) with
| Prod (id,atom,ff) ->
if eq_constr ff (Lazy.force _False) then
match (atom_of_constr env sigma atom) with
`Eq(t,a,b) -> `Neq(t,a,b)
| `Other(p) -> `Nother(p)
else
begin
try
quantified_atom_of_constr (Environ.push_rel (id,None,atom) env) sigma 1 ff
with Not_found ->
`Other (decompose_term env sigma term)
end
| _ ->
atom_of_constr env sigma term
let rec make_prb gls depth additionnal_terms =
let env=pf_env gls in
let sigma=sig_sig gls in
let state = empty depth gls in
let pos_hyps = ref [] in
let neg_hyps =ref [] in
List.iter
(fun c ->
let t = decompose_term env sigma c in
ignore (add_term state t)) additionnal_terms;
List.iter
(fun (id,_,e) ->
begin
let cid=mkVar id in
match litteral_of_constr env sigma e with
`Eq (t,a,b) -> add_equality state cid a b
| `Neq (t,a,b) -> add_disequality state (Hyp cid) a b
| `Other ph ->
List.iter
(fun (cidn,nh) ->
add_disequality state (HeqnH (cid,cidn)) ph nh)
!neg_hyps;
pos_hyps:=(cid,ph):: !pos_hyps
| `Nother nh ->
List.iter
(fun (cidp,ph) ->
add_disequality state (HeqnH (cidp,cid)) ph nh)
!pos_hyps;
neg_hyps:=(cid,nh):: !neg_hyps
| `Rule patts -> add_quant state id true patts
| `Nrule patts -> add_quant state id false patts
end) (Environ.named_context_of_val (Goal.V82.hyps gls.sigma gls.it));
begin
match atom_of_constr env sigma (pf_concl gls) with
`Eq (t,a,b) -> add_disequality state Goal a b
| `Other g ->
List.iter
(fun (idp,ph) ->
add_disequality state (HeqG idp) ph g) !pos_hyps
end;
state
indhyps builds the array of arrays of constructor hyps for ( )
let build_projection intype outtype (cstr:constructor) special default gls=
let env=pf_env gls in
let (h,argv) =
try destApp intype with
Invalid_argument _ -> (intype,[||]) in
let ind=destInd h in
let types=Inductiveops.arities_of_constructors env ind in
let lp=Array.length types in
let ci=pred (snd cstr) in
let branch i=
let ti=Term.prod_appvect types.(i) argv in
let rc=fst (decompose_prod_assum ti) in
let head=
if i=ci then special else default in
it_mkLambda_or_LetIn head rc in
let branches=Array.init lp branch in
let casee=mkRel 1 in
let pred=mkLambda(Anonymous,intype,outtype) in
let case_info=make_case_info (pf_env gls) ind RegularStyle in
let body= mkCase(case_info, pred, casee, branches) in
let id=pf_get_new_id (id_of_string "t") gls in
mkLambda(Name id,intype,body)
let _M =mkMeta
let rec proof_tac p gls =
match p.p_rule with
Ax c -> exact_check c gls
| SymAx c ->
let l=constr_of_term p.p_lhs and
r=constr_of_term p.p_rhs in
let typ = Termops.refresh_universes (pf_type_of gls l) in
exact_check
(mkApp(Lazy.force _sym_eq,[|typ;r;l;c|])) gls
| Refl t ->
let lr = constr_of_term t in
let typ = Termops.refresh_universes (pf_type_of gls lr) in
exact_check
(mkApp(Lazy.force _refl_equal,[|typ;constr_of_term t|])) gls
| Trans (p1,p2)->
let t1 = constr_of_term p1.p_lhs and
t2 = constr_of_term p1.p_rhs and
t3 = constr_of_term p2.p_rhs in
let typ = Termops.refresh_universes (pf_type_of gls t2) in
let prf =
mkApp(Lazy.force _trans_eq,[|typ;t1;t2;t3;_M 1;_M 2|]) in
tclTHENS (refine prf) [(proof_tac p1);(proof_tac p2)] gls
| Congr (p1,p2)->
let tf1=constr_of_term p1.p_lhs
and tx1=constr_of_term p2.p_lhs
and tf2=constr_of_term p1.p_rhs
and tx2=constr_of_term p2.p_rhs in
let typf = Termops.refresh_universes (pf_type_of gls tf1) in
let typx = Termops.refresh_universes (pf_type_of gls tx1) in
let typfx = Termops.refresh_universes (pf_type_of gls (mkApp (tf1,[|tx1|]))) in
let id = pf_get_new_id (id_of_string "f") gls in
let appx1 = mkLambda(Name id,typf,mkApp(mkRel 1,[|tx1|])) in
let lemma1 =
mkApp(Lazy.force _f_equal,
[|typf;typfx;appx1;tf1;tf2;_M 1|]) in
let lemma2=
mkApp(Lazy.force _f_equal,
[|typx;typfx;tf2;tx1;tx2;_M 1|]) in
let prf =
mkApp(Lazy.force _trans_eq,
[|typfx;
mkApp(tf1,[|tx1|]);
mkApp(tf2,[|tx1|]);
mkApp(tf2,[|tx2|]);_M 2;_M 3|]) in
tclTHENS (refine prf)
[tclTHEN (refine lemma1) (proof_tac p1);
tclFIRST
[tclTHEN (refine lemma2) (proof_tac p2);
reflexivity;
fun gls ->
errorlabstrm "Congruence"
(Pp.str
"I don't know how to handle dependent equality")]] gls
| Inject (prf,cstr,nargs,argind) ->
let ti=constr_of_term prf.p_lhs in
let tj=constr_of_term prf.p_rhs in
let default=constr_of_term p.p_lhs in
let intype = Termops.refresh_universes (pf_type_of gls ti) in
let outtype = Termops.refresh_universes (pf_type_of gls default) in
let special=mkRel (1+nargs-argind) in
let proj=build_projection intype outtype cstr special default gls in
let injt=
mkApp (Lazy.force _f_equal,[|intype;outtype;proj;ti;tj;_M 1|]) in
tclTHEN (refine injt) (proof_tac prf) gls
let refute_tac c t1 t2 p gls =
let tt1=constr_of_term t1 and tt2=constr_of_term t2 in
let intype = Termops.refresh_universes (pf_type_of gls tt1) in
let neweq=
mkApp(Lazy.force _eq,
[|intype;tt1;tt2|]) in
let hid=pf_get_new_id (id_of_string "Heq") gls in
let false_t=mkApp (c,[|mkVar hid|]) in
tclTHENS (assert_tac (Name hid) neweq)
[proof_tac p; simplest_elim false_t] gls
let convert_to_goal_tac c t1 t2 p gls =
let tt1=constr_of_term t1 and tt2=constr_of_term t2 in
let sort = Termops.refresh_universes (pf_type_of gls tt2) in
let neweq=mkApp(Lazy.force _eq,[|sort;tt1;tt2|]) in
let e=pf_get_new_id (id_of_string "e") gls in
let x=pf_get_new_id (id_of_string "X") gls in
let identity=mkLambda (Name x,sort,mkRel 1) in
let endt=mkApp (Lazy.force _eq_rect,
[|sort;tt1;identity;c;tt2;mkVar e|]) in
tclTHENS (assert_tac (Name e) neweq)
[proof_tac p;exact_check endt] gls
let convert_to_hyp_tac c1 t1 c2 t2 p gls =
let tt2=constr_of_term t2 in
let h=pf_get_new_id (id_of_string "H") gls in
let false_t=mkApp (c2,[|mkVar h|]) in
tclTHENS (assert_tac (Name h) tt2)
[convert_to_goal_tac c1 t1 t2 p;
simplest_elim false_t] gls
let discriminate_tac cstr p gls =
let t1=constr_of_term p.p_lhs and t2=constr_of_term p.p_rhs in
let intype = Termops.refresh_universes (pf_type_of gls t1) in
let concl=pf_concl gls in
let outsort = mkType (Termops.new_univ ()) in
let xid=pf_get_new_id (id_of_string "X") gls in
let tid=pf_get_new_id (id_of_string "t") gls in
let identity=mkLambda(Name xid,outsort,mkLambda(Name tid,mkRel 1,mkRel 1)) in
let trivial=pf_type_of gls identity in
let outtype = mkType (Termops.new_univ ()) in
let pred=mkLambda(Name xid,outtype,mkRel 1) in
let hid=pf_get_new_id (id_of_string "Heq") gls in
let proj=build_projection intype outtype cstr trivial concl gls in
let injt=mkApp (Lazy.force _f_equal,
[|intype;outtype;proj;t1;t2;mkVar hid|]) in
let endt=mkApp (Lazy.force _eq_rect,
[|outtype;trivial;pred;identity;concl;injt|]) in
let neweq=mkApp(Lazy.force _eq,[|intype;t1;t2|]) in
tclTHENS (assert_tac (Name hid) neweq)
[proof_tac p;exact_check endt] gls
let build_term_to_complete uf meta pac =
let cinfo = get_constructor_info uf pac.cnode in
let real_args = List.map (fun i -> constr_of_term (term uf i)) pac.args in
let dummy_args = List.rev (list_tabulate meta pac.arity) in
let all_args = List.rev_append real_args dummy_args in
applistc (mkConstruct cinfo.ci_constr) all_args
let cc_tactic depth additionnal_terms gls=
Coqlib.check_required_library ["Coq";"Init";"Logic"];
let _ = debug Pp.msgnl (Pp.str "Reading subgoal ...") in
let state = make_prb gls depth additionnal_terms in
let _ = debug Pp.msgnl (Pp.str "Problem built, solving ...") in
let sol = execute true state in
let _ = debug Pp.msgnl (Pp.str "Computation completed.") in
let uf=forest state in
match sol with
None -> tclFAIL 0 (str "congruence failed") gls
| Some reason ->
debug Pp.msgnl (Pp.str "Goal solved, generating proof ...");
match reason with
Discrimination (i,ipac,j,jpac) ->
let p=build_proof uf (`Discr (i,ipac,j,jpac)) in
let cstr=(get_constructor_info uf ipac.cnode).ci_constr in
discriminate_tac cstr p gls
| Incomplete ->
let metacnt = ref 0 in
let newmeta _ = incr metacnt; _M !metacnt in
let terms_to_complete =
List.map
(build_term_to_complete uf newmeta)
(epsilons uf) in
Pp.msgnl
(Pp.str "Goal is solvable by congruence but \
some arguments are missing.");
Pp.msgnl
(Pp.str " Try " ++
hov 8
begin
str "\"congruence with (" ++
prlist_with_sep
(fun () -> str ")" ++ spc () ++ str "(")
(Termops.print_constr_env (pf_env gls))
terms_to_complete ++
str ")\","
end);
Pp.msgnl
(Pp.str " replacing metavariables by arbitrary terms.");
tclFAIL 0 (str "Incomplete") gls
| Contradiction dis ->
let p=build_proof uf (`Prove (dis.lhs,dis.rhs)) in
let ta=term uf dis.lhs and tb=term uf dis.rhs in
match dis.rule with
Goal -> proof_tac p gls
| Hyp id -> refute_tac id ta tb p gls
| HeqG id ->
convert_to_goal_tac id ta tb p gls
| HeqnH (ida,idb) ->
convert_to_hyp_tac ida ta idb tb p gls
let cc_fail gls =
errorlabstrm "Congruence" (Pp.str "congruence failed.")
let congruence_tac depth l =
tclORELSE
(tclTHEN (tclREPEAT introf) (cc_tactic depth l))
cc_fail
Beware : reflexivity = constructor 1 = apply refl_equal
might be slow now , let 's rather do something equivalent
to a " simple apply refl_equal "
might be slow now, let's rather do something equivalent
to a "simple apply refl_equal" *)
let simple_reflexivity () = apply (Lazy.force _refl_equal)
let f_equal gl =
let cut_eq c1 c2 =
let ty = Termops.refresh_universes (pf_type_of gl c1) in
tclTHENTRY
(Tactics.cut (mkApp (Lazy.force _eq, [|ty; c1; c2|])))
(simple_reflexivity ())
in
try match kind_of_term (pf_concl gl) with
| App (r,[|_;t;t'|]) when eq_constr r (Lazy.force _eq) ->
begin match kind_of_term t, kind_of_term t' with
| App (f,v), App (f',v') when Array.length v = Array.length v' ->
let rec cuts i =
if i < 0 then tclTRY (congruence_tac 1000 [])
else tclTHENFIRST (cut_eq v.(i) v'.(i)) (cuts (i-1))
in cuts (Array.length v - 1) gl
| _ -> tclIDTAC gl
end
| _ -> tclIDTAC gl
with Type_errors.TypeError _ -> tclIDTAC gl
|
d83e7c7b81f7850ac22f9b35130d224511e53788f10ea70ab124a8b3455119bc | LuisThiamNye/chic | spec.clj | (ns jl.compiler.spec
(:require
[jl.interop :as interop]
[jl.compiler.type :as type])
(:import
(org.objectweb.asm Type)))
(defn with-cast [ctor spec])
(defn untyped-num-literal? [spec]
(= [:number] (:traits spec)))
(defn untyped-int-literal? [spec]
(= [:integer] (:traits spec)))
(defn specialise-num-literal [typ spec]
{:spec/kind :exact-class
:classname (condp = typ
:long "long"
:int "int"
:byte "byte"
:float "float"
:double "double"
:bigint "java.lang.BigInteger"
:bigdec "java.lang.BigDecimal")})
(defn class-meets? [iface subject]
(isa? (Class/forName subject) (Class/forName iface)))
(defn get-exact-class [spec]
(assert (or (nil? spec) (contains? spec :spec/kind))
(pr-str {:keys (keys spec)}))
(cond
(= :exact-class (:spec/kind spec))
(:classname spec)
(= :exact-array (:spec/kind spec))
(let [c (:classname spec)
sb (StringBuilder.)]
(dotimes [_ (:ndims spec)]
(.append sb "["))
(if-some [prim(type/prim-classname->type c)]
(.append sb (.getDescriptor prim))
(do (.append sb "L")
(.append sb c)
(.append sb ";")))
(.toString sb))))
(defn get-duck-class [env spec] ;; returns a class of the intersection of behaviours
(if (= :union (:spec/kind spec))
(interop/intersect-classes
(mapv (partial get-duck-class env) (:specs spec)))
(if (= :jump (:spec/kind spec))
interop/jump-class
(if (= :nil (:spec/kind spec))
interop/nil-class
(let [c (get-exact-class spec)]
(when (nil? c)
(throw (ex-info "nil class" {:spec spec})))
(interop/resolve-class env c))))))
(defn prim? [spec]
(#{"boolean" "byte" "short" "char" "int" "long" "float" "double" "void"}
(get-exact-class spec)))
(defn void? [spec]
(or (= "void" (get-exact-class spec))
(= :jump (:spec/kind spec))))
#_#_#_
(defn biginteger-coerce [spec]
(let [clsname (get-exact-class spec)]
(condp = clsname
"[B" (with-cast spec ?)
"java.lang.String" (with-cast spec ?)
"long" (with-cast spec ?) ;;valueOf
(or
(when (#{"byte" "short" "int"})
valueOf(long )
(when (class-meets? "java.lang.BigDecimal" clsname)
(with-cast spec ?))
(when (untyped-int-literal? spec)
(with-cast ? (specialise-num-literal :long spec)))))))
(defn bigdecimal-coerce [spec]
(let [clsname (get-exact-class spec)]
(condp = clsname
"long" (with-cast ? spec)
"int" (with-cast ? spec)
"double" (with-cast ? spec)
"[C" (with-cast ? spec)
"java.lang.String" (with-cast ? spec)
(or (when (#{"short" "byte"} clsname)
;; int ctor
(with-cast ? spec))
(when (untyped-num-literal? spec)
;; string ctor
(with-cast ? spec))))))
(defn try-coerce-class [clsname spec]
(if (class-meets? clsname spec)
spec
(({"java.lang.BigInteger" biginteger-coerce
"java.lang.BigDecimal" bigdecimal-coerce}
clsname) spec)))
(defn trait-meets? [trait subject]
(or (= trait subject)
(when (= trait :number)
(= subject :integer))))
(defn certain-trait? [trait spec]
(when (= :traits (:spec/kind spec))
(some (partial trait-meets? trait) (:traits spec))))
(defn try-coerce-trait [trait spec]
(when (certain-trait? trait spec)
spec))
(defn get-certain-trait [spec trait]
(when (= :traits (:spec/kind spec))
(get-in spec [:overrides trait])))
(defn link-multispec [mspec specs]
(let [aspecs (mapv (fn [spec]
{:spec/kind :atom
:atom (atom spec)})
specs)]
(mapv (fn [spec]
spec) ;; todo
aspecs)))
(defn get-array-element [spec]
(if (= :exact-array (:spec/kind spec))
(if (= 1 (:ndims spec))
{:spec/kind :exact-class
:classname (:classname spec)}
(update spec :ndims dec))
(throw (ex-info "spec not an array"
{:spec spec}))))
(defn of-class [classname]
(let [bks (re-find #"^\[+" classname)
ndims (count bks)]
(if (= 0 ndims)
{:spec/kind :exact-class
:classname classname}
(let [c (subs classname ndims)]
{:spec/kind :exact-array
:classname (or (second (re-matches #"L(.+);" c))
(.getClassName (Type/getType c)))
:ndims ndims}))))
| null | https://raw.githubusercontent.com/LuisThiamNye/chic/5cd7c951b5ac97db2b9434e0dc4b3961f5d9dddb/src/jl/compiler/spec.clj | clojure | returns a class of the intersection of behaviours
valueOf
int ctor
string ctor
todo | (ns jl.compiler.spec
(:require
[jl.interop :as interop]
[jl.compiler.type :as type])
(:import
(org.objectweb.asm Type)))
(defn with-cast [ctor spec])
(defn untyped-num-literal? [spec]
(= [:number] (:traits spec)))
(defn untyped-int-literal? [spec]
(= [:integer] (:traits spec)))
(defn specialise-num-literal [typ spec]
{:spec/kind :exact-class
:classname (condp = typ
:long "long"
:int "int"
:byte "byte"
:float "float"
:double "double"
:bigint "java.lang.BigInteger"
:bigdec "java.lang.BigDecimal")})
(defn class-meets? [iface subject]
(isa? (Class/forName subject) (Class/forName iface)))
(defn get-exact-class [spec]
(assert (or (nil? spec) (contains? spec :spec/kind))
(pr-str {:keys (keys spec)}))
(cond
(= :exact-class (:spec/kind spec))
(:classname spec)
(= :exact-array (:spec/kind spec))
(let [c (:classname spec)
sb (StringBuilder.)]
(dotimes [_ (:ndims spec)]
(.append sb "["))
(if-some [prim(type/prim-classname->type c)]
(.append sb (.getDescriptor prim))
(do (.append sb "L")
(.append sb c)
(.append sb ";")))
(.toString sb))))
(if (= :union (:spec/kind spec))
(interop/intersect-classes
(mapv (partial get-duck-class env) (:specs spec)))
(if (= :jump (:spec/kind spec))
interop/jump-class
(if (= :nil (:spec/kind spec))
interop/nil-class
(let [c (get-exact-class spec)]
(when (nil? c)
(throw (ex-info "nil class" {:spec spec})))
(interop/resolve-class env c))))))
(defn prim? [spec]
(#{"boolean" "byte" "short" "char" "int" "long" "float" "double" "void"}
(get-exact-class spec)))
(defn void? [spec]
(or (= "void" (get-exact-class spec))
(= :jump (:spec/kind spec))))
#_#_#_
(defn biginteger-coerce [spec]
(let [clsname (get-exact-class spec)]
(condp = clsname
"[B" (with-cast spec ?)
"java.lang.String" (with-cast spec ?)
(or
(when (#{"byte" "short" "int"})
valueOf(long )
(when (class-meets? "java.lang.BigDecimal" clsname)
(with-cast spec ?))
(when (untyped-int-literal? spec)
(with-cast ? (specialise-num-literal :long spec)))))))
(defn bigdecimal-coerce [spec]
(let [clsname (get-exact-class spec)]
(condp = clsname
"long" (with-cast ? spec)
"int" (with-cast ? spec)
"double" (with-cast ? spec)
"[C" (with-cast ? spec)
"java.lang.String" (with-cast ? spec)
(or (when (#{"short" "byte"} clsname)
(with-cast ? spec))
(when (untyped-num-literal? spec)
(with-cast ? spec))))))
(defn try-coerce-class [clsname spec]
(if (class-meets? clsname spec)
spec
(({"java.lang.BigInteger" biginteger-coerce
"java.lang.BigDecimal" bigdecimal-coerce}
clsname) spec)))
(defn trait-meets? [trait subject]
(or (= trait subject)
(when (= trait :number)
(= subject :integer))))
(defn certain-trait? [trait spec]
(when (= :traits (:spec/kind spec))
(some (partial trait-meets? trait) (:traits spec))))
(defn try-coerce-trait [trait spec]
(when (certain-trait? trait spec)
spec))
(defn get-certain-trait [spec trait]
(when (= :traits (:spec/kind spec))
(get-in spec [:overrides trait])))
(defn link-multispec [mspec specs]
(let [aspecs (mapv (fn [spec]
{:spec/kind :atom
:atom (atom spec)})
specs)]
(mapv (fn [spec]
aspecs)))
(defn get-array-element [spec]
(if (= :exact-array (:spec/kind spec))
(if (= 1 (:ndims spec))
{:spec/kind :exact-class
:classname (:classname spec)}
(update spec :ndims dec))
(throw (ex-info "spec not an array"
{:spec spec}))))
(defn of-class [classname]
(let [bks (re-find #"^\[+" classname)
ndims (count bks)]
(if (= 0 ndims)
{:spec/kind :exact-class
:classname classname}
(let [c (subs classname ndims)]
{:spec/kind :exact-array
:classname (or (second (re-matches #"L(.+);" c))
(.getClassName (Type/getType c)))
:ndims ndims}))))
|
1675afa0ab4d6e1a3ca8d423244c0dca8247ef4a7d0ac7c419e6b6dfebf6d355 | icicle-lang/icicle-ambiata | Desugar.hs | # LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternGuards #
# LANGUAGE PatternSynonyms #
# LANGUAGE TupleSections #
module Icicle.Source.Transform.Desugar
( DesugarError(..)
, annotOfError
, runDesugar
, desugarQT
, desugarQ
, desugarFun
) where
import Control.Monad.Trans.Class
import Data.Hashable (Hashable)
import Data.Functor.Identity
import GHC.Generics (Generic)
import Icicle.Common.Base
import Icicle.Common.Fresh
import Icicle.Source.Query
import Icicle.Source.Transform.Simp
import Icicle.Internal.Pretty
import P
import X.Control.Monad.Trans.Either
data DesugarError a n
= DesugarErrorNoAlternative a (Pattern n) -- ^ we generated a pattern that cannot be matched
-- with any alternative.
| DesugarErrorImpossible a -- ^ just impossible, the world has ended.
| DesugarOverlappingPattern a (Pattern n) -- ^ duh
| DesugarIllTypedPatterns a [Pattern n] -- ^ patterns use constructors from different types
deriving (Eq, Show, Generic)
instance (NFData a, NFData n) => NFData (DesugarError a n)
instance (Pretty a, Pretty n) => Pretty (DesugarError a n) where
pretty (DesugarErrorNoAlternative a n) = "Missing alternative:" <+> pretty n <+> "at" <+> pretty a
pretty (DesugarErrorImpossible a) = "Impossible desugar error" <+> "at" <+> pretty a
pretty (DesugarOverlappingPattern a x) = "Overlapping pattern:" <+> pretty x <+> "at" <+> pretty a
pretty (DesugarIllTypedPatterns a xs) = "Illtyped patterns:" <+> align (vcat (pretty <$> xs)) <> line <> "at" <+> pretty a
type DesugarM a n x = FreshT n (EitherT (DesugarError a n) Identity) x
annotOfError :: DesugarError a n -> Maybe a
annotOfError (DesugarErrorNoAlternative a _) = Just a
annotOfError (DesugarErrorImpossible a) = Just a
annotOfError (DesugarOverlappingPattern a _) = Just a
annotOfError (DesugarIllTypedPatterns a _) = Just a
runDesugar :: NameState n -> DesugarM a n x -> Either (DesugarError a n) x
runDesugar n m = runIdentity . runEitherT . bimapEitherT id snd $ runFreshT m n
desugarFun
:: (Hashable n, Eq n)
=> Function a n
-> DesugarM a n (Function a n)
desugarFun f
= do b' <- desugarQ (body f)
return $ f { body = b'}
desugarQT
:: (Hashable n, Eq n)
=> QueryTop a n
-> DesugarM a n (QueryTop a n)
desugarQT qt
= do qq' <- desugarQ (query qt)
return $ qt { query = qq' }
desugarQ
:: (Hashable n, Eq n)
=> Query a n
-> DesugarM a n (Query a n)
desugarQ qq
= do cs <- mapM desugarC (contexts qq)
f <- desugarX (final qq)
return $ Query cs f
desugarC
:: (Hashable n, Eq n)
=> Context a n
-> DesugarM a n (Context a n)
desugarC cc
= case cc of
GroupBy a x -> GroupBy a <$> desugarX x
Distinct a x -> Distinct a <$> desugarX x
Filter a x -> Filter a <$> desugarX x
Let a n x -> Let a n <$> desugarX x
LetFold a f -> LetFold a <$> desugarF f
GroupFold a k v x -> GroupFold a k v <$> desugarX x
Windowed{} -> return cc
Latest{} -> return cc
desugarF
:: (Hashable n, Eq n)
=> Fold (Query a n) a n
-> DesugarM a n (Fold (Query a n) a n)
desugarF ff
= do fi' <- desugarX (foldInit ff)
fw' <- desugarX (foldWork ff)
return $ ff { foldInit = fi', foldWork = fw'}
desugarX
:: (Hashable n, Eq n)
=> Exp a n
-> DesugarM a n (Exp a n)
desugarX xx
= case xx of
Nested a q
-> do q' <- desugarQ q
return $ Nested a q'
Case a scrut patalts
-> do let pats = fmap fst patalts
ty <- foldM (flip $ addToTy $ DesugarIllTypedPatterns a pats) TyAny pats
scrut' <- desugarX scrut
patalts' <- mapM (mapM desugarX) patalts
tree <- casesForTy a scrut' ty
checkOverlapping a pats (toList tree)
treeToCase a patalts' tree
App a x1 x2
-> do x1' <- desugarX x1
x2' <- desugarX x2
return $ App a x1' x2'
Var _ _
-> return xx
Prim _ _
-> return xx
--------------------------------------------------------------------------------
-- * Case Flattening
-- | The partial "type" of patterns, up to where they are matched.
-- The type of the scrutinee is strictly more specific than this, but we don't
-- want to generate too many cases.
--
data Ty
= TyTup Ty Ty
| TyOpt Ty
| TySum Ty Ty
| TyBool
-- Literals such as numbers and argument-less enums:
-- where we can, instead of doing a real case, check against "x == Con".
This does n't work for because this desugaring uses
| TyLit [Constructor]
| TyAny
deriving (Show)
addToTy :: DesugarError a n -> Pattern n -> Ty -> DesugarM a n Ty
addToTy err (PatCon con pats) ty
= case con of
ConTuple
| [p1, p2] <- pats
, TyTup t1 t2 <- ty
-> TyTup <$> go p1 t1 <*> go p2 t2
| [p1, p2] <- pats
, TyAny <- ty
-> TyTup <$> go p1 TyAny <*> go p2 TyAny
| otherwise
-> lift $ left err
ConSome
| [p] <- pats
, TyOpt t <- ty
-> TyOpt <$> go p t
| [p] <- pats
, TyAny <- ty
-> TyOpt <$> go p TyAny
| otherwise
-> lift $ left err
ConNone
| [] <- pats
, TyOpt _ <- ty
-> return ty
| [] <- pats
, TyAny <- ty
-> return $ TyOpt TyAny
| otherwise
-> lift $ left err
ConTrue
| [] <- pats
, TyBool <- ty
-> return ty
| [] <- pats
, TyAny <- ty
-> return TyBool
| otherwise
-> lift $ left err
ConFalse
| [] <- pats
, TyBool <- ty
-> return ty
| [] <- pats
, TyAny <- ty
-> return TyBool
| otherwise
-> lift $ left err
ConLeft
| [p] <- pats
, TySum t1 t2 <- ty
-> TySum <$> go p t1 <*> return t2
| [p] <- pats
, TyAny <- ty
-> TySum <$> go p TyAny <*> return TyAny
| otherwise
-> lift $ left err
ConRight
| [p] <- pats
, TySum t1 t2 <- ty
-> TySum <$> return t1 <*> go p t2
| [p] <- pats
, TyAny <- ty
-> TySum <$> return TyAny <*> go p TyAny
| otherwise
-> lift $ left err
ConError _
| [] <- pats
, TyLit cs <- ty
-> return $ TyLit (cs <> [con])
| [] <- pats
, TyAny <- ty
-> return $ TyLit [con]
| otherwise
-> lift $ left err
where
go = addToTy err
addToTy _ PatDefault ty = return ty
addToTy _ (PatVariable _) ty = return ty
casesForTy
:: (Hashable n)
=> a
-> Exp' (Query a n) a n
-> Ty
-> DesugarM a n (Tree a n (Pattern n))
casesForTy ann scrut ty
= case ty of
Booleans just have True / False
TyBool
-> return
$ TCase scrut [ (PatCon ConTrue [], Done (PatCon ConTrue []))
, (PatCon ConFalse [], Done (PatCon ConFalse [])) ]
-- Tuples treat arguments as nested cases
TyTup a b
-> do args <- freshes 2
let pat' = PatCon ConTuple (fmap PatVariable args)
let vars = fmap (Var ann) args
bd <- subtree ConTuple vars [a, b]
return $ TCase scrut [ (pat', bd) ]
-- Options need a case for None, and nested cases for Some arguments
TyOpt a
-> do args <- freshes 1
let pat' = PatCon ConSome (fmap PatVariable args)
let vars = fmap (Var ann) args
bd <- subtree ConSome vars [a]
return $ TCase scrut [ (pat', bd)
, (PatCon ConNone [], Done (PatCon ConNone [])) ]
-- Sums need nested cases for both
TySum a b
-> do aleft <- freshes 1
let pleft = PatCon ConLeft (fmap PatVariable aleft)
aright <- freshes 1
let pright = PatCon ConRight (fmap PatVariable aright)
let vars = fmap (Var ann)
bl <- subtree ConLeft (vars aleft) [a]
br <- subtree ConRight (vars aright) [b]
return $ TCase scrut [ (pleft, bl)
, (pright, br) ]
TyLit cs
-> do var <- fresh
return $ TLet var scrut
$ TLits (Var ann var)
(fmap (\c -> (c, Done $ PatCon c [])) cs)
(Done $ PatVariable var)
-- If we don't know the type of this pattern, use a fresh variable
Use TLet to avoid generating variable patterns , since Core ca n't handle them .
TyAny
-> do var <- fresh
return $ TLet var scrut (Done (PatVariable var) )
where
subtree con vars tys
= liftM (fmap (PatCon con) . sequence)
$ zipWithM (casesForTy ann) vars tys
-- | A nested case AST. We generate this from the patterns and convert it into
-- a case statement.
--
data Tree a n x
= Done x -- ^ just use the pattern/alternative/thing.
| TCase (Exp' (Query a n) a n)
[(Pattern n, Tree a n x)] -- ^ do a case statement
| TLet (Name n)
(Exp' (Query a n) a n)
(Tree a n x) -- ^ insert a let because we cannot generate pattern variables.
| TLits (Exp' (Query a n) a n)
[(Constructor, Tree a n x)] (Tree a n x) -- ^ special case for literals
deriving (Functor, Foldable, Traversable, Show)
instance Applicative (Tree a n) where
pure = Done
(<*>) = ap
instance Monad (Tree a n) where
return = pure
a >>= b = joinT (fmap b a)
where
joinT (Done x) = x
joinT (TCase n ls) = TCase n (fmap (fmap joinT) ls)
joinT (TLet n x t) = TLet n x (joinT t)
joinT (TLits s cs d)
= TLits s (fmap (fmap joinT) cs) (joinT d)
treeToCase
:: (Eq n)
=> a
-> [(Pattern n, Exp' (Query a n) a n)]
-> Tree a n (Pattern n)
-> DesugarM a n (Exp' (Query a n) a n)
treeToCase ann patalts tree
= lift . fmap (simpDumbX . caseStmtsFor) . sequence
$ fmap (getAltBody patalts) tree
where
-- Convert tree structure to AST
caseStmtsFor (Done x)
= x
caseStmtsFor (TCase scrut alts)
= Case ann scrut (fmap (fmap caseStmtsFor) alts)
caseStmtsFor (TLet n x e)
= Nested ann (Query [Let ann n x] (caseStmtsFor e))
caseStmtsFor (TLits scrut ((c,x):cs) d)
= let eq = Prim ann $ Op $ Relation Eq
c' = Prim ann $ PrimCon c
sc = App ann (App ann eq scrut) c'
in Case ann sc
[ ( PatCon ConTrue [], caseStmtsFor x )
, ( PatCon ConFalse [], caseStmtsFor $ TLits scrut cs d ) ]
caseStmtsFor (TLits _ [] d)
= caseStmtsFor d
-- Look up the alternative for this pattern
getAltBody ((px, x) : xs) p
= case matcher p px of
Nothing
-> getAltBody xs p
Just []
-> right x
Just s
-> do s' <- mapM generateLet s
right $ Nested ann (Query s' x)
getAltBody _ p
= left $ DesugarErrorNoAlternative ann p
generateLet (n ,p)
= Let ann n <$> patternToExp p
patternToExp (PatCon c as)
= do xs <- mapM patternToExp as
right $ foldl (App ann) (Prim ann (PrimCon c)) xs
patternToExp (PatVariable v)
= right $ Var ann v
patternToExp PatDefault
= left $ DesugarErrorImpossible ann -- we never generate default patterns.
-- "Unify" the generated pattern and a user-supplied pattern.
-- Return a list of substitutions if success. This is necessary in case the
-- generated patterns are more specific than the user's pattern, e.g.
-- if we have `None` and the user just supplies a variable.
--
Precondition : matcher p q assumes p is more specific than q
Precondition : matcher p q assumes p contains no PatDefault
matcher :: Pattern t -> Pattern t -> Maybe [(Name t, Pattern t)]
matcher (PatCon c as) (PatCon c' bs)
= do guard (c == c')
substs <- zipWithM matcher as bs
return (concat substs)
matcher p (PatVariable x)
= return [(x, p)]
matcher _ (PatDefault)
= return []
matcher _ _
= Nothing
checkOverlapping
:: a -> [Pattern n] -> [Pattern n] -> DesugarM a n ()
checkOverlapping ann userpats genpats
= foldM_ (\p -> lift . go p) genpats userpats
where
go gps up
= let gps' = filter (\gp -> isNothing $ matcher gp up ) gps
in if length gps' < length gps
then return gps'
else left (DesugarOverlappingPattern ann up)
freshes :: (Monad m, Hashable n) => Int -> FreshT n m [Name n]
freshes n = replicateM n fresh
| null | https://raw.githubusercontent.com/icicle-lang/icicle-ambiata/9b9cc45a75f66603007e4db7e5f3ba908cae2df2/icicle-source/src/Icicle/Source/Transform/Desugar.hs | haskell | # LANGUAGE DeriveTraversable #
# LANGUAGE OverloadedStrings #
^ we generated a pattern that cannot be matched
with any alternative.
^ just impossible, the world has ended.
^ duh
^ patterns use constructors from different types
------------------------------------------------------------------------------
* Case Flattening
| The partial "type" of patterns, up to where they are matched.
The type of the scrutinee is strictly more specific than this, but we don't
want to generate too many cases.
Literals such as numbers and argument-less enums:
where we can, instead of doing a real case, check against "x == Con".
Tuples treat arguments as nested cases
Options need a case for None, and nested cases for Some arguments
Sums need nested cases for both
If we don't know the type of this pattern, use a fresh variable
| A nested case AST. We generate this from the patterns and convert it into
a case statement.
^ just use the pattern/alternative/thing.
^ do a case statement
^ insert a let because we cannot generate pattern variables.
^ special case for literals
Convert tree structure to AST
Look up the alternative for this pattern
we never generate default patterns.
"Unify" the generated pattern and a user-supplied pattern.
Return a list of substitutions if success. This is necessary in case the
generated patterns are more specific than the user's pattern, e.g.
if we have `None` and the user just supplies a variable.
| # LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE PatternGuards #
# LANGUAGE PatternSynonyms #
# LANGUAGE TupleSections #
module Icicle.Source.Transform.Desugar
( DesugarError(..)
, annotOfError
, runDesugar
, desugarQT
, desugarQ
, desugarFun
) where
import Control.Monad.Trans.Class
import Data.Hashable (Hashable)
import Data.Functor.Identity
import GHC.Generics (Generic)
import Icicle.Common.Base
import Icicle.Common.Fresh
import Icicle.Source.Query
import Icicle.Source.Transform.Simp
import Icicle.Internal.Pretty
import P
import X.Control.Monad.Trans.Either
data DesugarError a n
deriving (Eq, Show, Generic)
instance (NFData a, NFData n) => NFData (DesugarError a n)
instance (Pretty a, Pretty n) => Pretty (DesugarError a n) where
pretty (DesugarErrorNoAlternative a n) = "Missing alternative:" <+> pretty n <+> "at" <+> pretty a
pretty (DesugarErrorImpossible a) = "Impossible desugar error" <+> "at" <+> pretty a
pretty (DesugarOverlappingPattern a x) = "Overlapping pattern:" <+> pretty x <+> "at" <+> pretty a
pretty (DesugarIllTypedPatterns a xs) = "Illtyped patterns:" <+> align (vcat (pretty <$> xs)) <> line <> "at" <+> pretty a
type DesugarM a n x = FreshT n (EitherT (DesugarError a n) Identity) x
annotOfError :: DesugarError a n -> Maybe a
annotOfError (DesugarErrorNoAlternative a _) = Just a
annotOfError (DesugarErrorImpossible a) = Just a
annotOfError (DesugarOverlappingPattern a _) = Just a
annotOfError (DesugarIllTypedPatterns a _) = Just a
runDesugar :: NameState n -> DesugarM a n x -> Either (DesugarError a n) x
runDesugar n m = runIdentity . runEitherT . bimapEitherT id snd $ runFreshT m n
desugarFun
:: (Hashable n, Eq n)
=> Function a n
-> DesugarM a n (Function a n)
desugarFun f
= do b' <- desugarQ (body f)
return $ f { body = b'}
desugarQT
:: (Hashable n, Eq n)
=> QueryTop a n
-> DesugarM a n (QueryTop a n)
desugarQT qt
= do qq' <- desugarQ (query qt)
return $ qt { query = qq' }
desugarQ
:: (Hashable n, Eq n)
=> Query a n
-> DesugarM a n (Query a n)
desugarQ qq
= do cs <- mapM desugarC (contexts qq)
f <- desugarX (final qq)
return $ Query cs f
desugarC
:: (Hashable n, Eq n)
=> Context a n
-> DesugarM a n (Context a n)
desugarC cc
= case cc of
GroupBy a x -> GroupBy a <$> desugarX x
Distinct a x -> Distinct a <$> desugarX x
Filter a x -> Filter a <$> desugarX x
Let a n x -> Let a n <$> desugarX x
LetFold a f -> LetFold a <$> desugarF f
GroupFold a k v x -> GroupFold a k v <$> desugarX x
Windowed{} -> return cc
Latest{} -> return cc
desugarF
:: (Hashable n, Eq n)
=> Fold (Query a n) a n
-> DesugarM a n (Fold (Query a n) a n)
desugarF ff
= do fi' <- desugarX (foldInit ff)
fw' <- desugarX (foldWork ff)
return $ ff { foldInit = fi', foldWork = fw'}
desugarX
:: (Hashable n, Eq n)
=> Exp a n
-> DesugarM a n (Exp a n)
desugarX xx
= case xx of
Nested a q
-> do q' <- desugarQ q
return $ Nested a q'
Case a scrut patalts
-> do let pats = fmap fst patalts
ty <- foldM (flip $ addToTy $ DesugarIllTypedPatterns a pats) TyAny pats
scrut' <- desugarX scrut
patalts' <- mapM (mapM desugarX) patalts
tree <- casesForTy a scrut' ty
checkOverlapping a pats (toList tree)
treeToCase a patalts' tree
App a x1 x2
-> do x1' <- desugarX x1
x2' <- desugarX x2
return $ App a x1' x2'
Var _ _
-> return xx
Prim _ _
-> return xx
data Ty
= TyTup Ty Ty
| TyOpt Ty
| TySum Ty Ty
| TyBool
This does n't work for because this desugaring uses
| TyLit [Constructor]
| TyAny
deriving (Show)
addToTy :: DesugarError a n -> Pattern n -> Ty -> DesugarM a n Ty
addToTy err (PatCon con pats) ty
= case con of
ConTuple
| [p1, p2] <- pats
, TyTup t1 t2 <- ty
-> TyTup <$> go p1 t1 <*> go p2 t2
| [p1, p2] <- pats
, TyAny <- ty
-> TyTup <$> go p1 TyAny <*> go p2 TyAny
| otherwise
-> lift $ left err
ConSome
| [p] <- pats
, TyOpt t <- ty
-> TyOpt <$> go p t
| [p] <- pats
, TyAny <- ty
-> TyOpt <$> go p TyAny
| otherwise
-> lift $ left err
ConNone
| [] <- pats
, TyOpt _ <- ty
-> return ty
| [] <- pats
, TyAny <- ty
-> return $ TyOpt TyAny
| otherwise
-> lift $ left err
ConTrue
| [] <- pats
, TyBool <- ty
-> return ty
| [] <- pats
, TyAny <- ty
-> return TyBool
| otherwise
-> lift $ left err
ConFalse
| [] <- pats
, TyBool <- ty
-> return ty
| [] <- pats
, TyAny <- ty
-> return TyBool
| otherwise
-> lift $ left err
ConLeft
| [p] <- pats
, TySum t1 t2 <- ty
-> TySum <$> go p t1 <*> return t2
| [p] <- pats
, TyAny <- ty
-> TySum <$> go p TyAny <*> return TyAny
| otherwise
-> lift $ left err
ConRight
| [p] <- pats
, TySum t1 t2 <- ty
-> TySum <$> return t1 <*> go p t2
| [p] <- pats
, TyAny <- ty
-> TySum <$> return TyAny <*> go p TyAny
| otherwise
-> lift $ left err
ConError _
| [] <- pats
, TyLit cs <- ty
-> return $ TyLit (cs <> [con])
| [] <- pats
, TyAny <- ty
-> return $ TyLit [con]
| otherwise
-> lift $ left err
where
go = addToTy err
addToTy _ PatDefault ty = return ty
addToTy _ (PatVariable _) ty = return ty
casesForTy
:: (Hashable n)
=> a
-> Exp' (Query a n) a n
-> Ty
-> DesugarM a n (Tree a n (Pattern n))
casesForTy ann scrut ty
= case ty of
Booleans just have True / False
TyBool
-> return
$ TCase scrut [ (PatCon ConTrue [], Done (PatCon ConTrue []))
, (PatCon ConFalse [], Done (PatCon ConFalse [])) ]
TyTup a b
-> do args <- freshes 2
let pat' = PatCon ConTuple (fmap PatVariable args)
let vars = fmap (Var ann) args
bd <- subtree ConTuple vars [a, b]
return $ TCase scrut [ (pat', bd) ]
TyOpt a
-> do args <- freshes 1
let pat' = PatCon ConSome (fmap PatVariable args)
let vars = fmap (Var ann) args
bd <- subtree ConSome vars [a]
return $ TCase scrut [ (pat', bd)
, (PatCon ConNone [], Done (PatCon ConNone [])) ]
TySum a b
-> do aleft <- freshes 1
let pleft = PatCon ConLeft (fmap PatVariable aleft)
aright <- freshes 1
let pright = PatCon ConRight (fmap PatVariable aright)
let vars = fmap (Var ann)
bl <- subtree ConLeft (vars aleft) [a]
br <- subtree ConRight (vars aright) [b]
return $ TCase scrut [ (pleft, bl)
, (pright, br) ]
TyLit cs
-> do var <- fresh
return $ TLet var scrut
$ TLits (Var ann var)
(fmap (\c -> (c, Done $ PatCon c [])) cs)
(Done $ PatVariable var)
Use TLet to avoid generating variable patterns , since Core ca n't handle them .
TyAny
-> do var <- fresh
return $ TLet var scrut (Done (PatVariable var) )
where
subtree con vars tys
= liftM (fmap (PatCon con) . sequence)
$ zipWithM (casesForTy ann) vars tys
data Tree a n x
| TCase (Exp' (Query a n) a n)
| TLet (Name n)
(Exp' (Query a n) a n)
| TLits (Exp' (Query a n) a n)
deriving (Functor, Foldable, Traversable, Show)
instance Applicative (Tree a n) where
pure = Done
(<*>) = ap
instance Monad (Tree a n) where
return = pure
a >>= b = joinT (fmap b a)
where
joinT (Done x) = x
joinT (TCase n ls) = TCase n (fmap (fmap joinT) ls)
joinT (TLet n x t) = TLet n x (joinT t)
joinT (TLits s cs d)
= TLits s (fmap (fmap joinT) cs) (joinT d)
treeToCase
:: (Eq n)
=> a
-> [(Pattern n, Exp' (Query a n) a n)]
-> Tree a n (Pattern n)
-> DesugarM a n (Exp' (Query a n) a n)
treeToCase ann patalts tree
= lift . fmap (simpDumbX . caseStmtsFor) . sequence
$ fmap (getAltBody patalts) tree
where
caseStmtsFor (Done x)
= x
caseStmtsFor (TCase scrut alts)
= Case ann scrut (fmap (fmap caseStmtsFor) alts)
caseStmtsFor (TLet n x e)
= Nested ann (Query [Let ann n x] (caseStmtsFor e))
caseStmtsFor (TLits scrut ((c,x):cs) d)
= let eq = Prim ann $ Op $ Relation Eq
c' = Prim ann $ PrimCon c
sc = App ann (App ann eq scrut) c'
in Case ann sc
[ ( PatCon ConTrue [], caseStmtsFor x )
, ( PatCon ConFalse [], caseStmtsFor $ TLits scrut cs d ) ]
caseStmtsFor (TLits _ [] d)
= caseStmtsFor d
getAltBody ((px, x) : xs) p
= case matcher p px of
Nothing
-> getAltBody xs p
Just []
-> right x
Just s
-> do s' <- mapM generateLet s
right $ Nested ann (Query s' x)
getAltBody _ p
= left $ DesugarErrorNoAlternative ann p
generateLet (n ,p)
= Let ann n <$> patternToExp p
patternToExp (PatCon c as)
= do xs <- mapM patternToExp as
right $ foldl (App ann) (Prim ann (PrimCon c)) xs
patternToExp (PatVariable v)
= right $ Var ann v
patternToExp PatDefault
Precondition : matcher p q assumes p is more specific than q
Precondition : matcher p q assumes p contains no PatDefault
matcher :: Pattern t -> Pattern t -> Maybe [(Name t, Pattern t)]
matcher (PatCon c as) (PatCon c' bs)
= do guard (c == c')
substs <- zipWithM matcher as bs
return (concat substs)
matcher p (PatVariable x)
= return [(x, p)]
matcher _ (PatDefault)
= return []
matcher _ _
= Nothing
checkOverlapping
:: a -> [Pattern n] -> [Pattern n] -> DesugarM a n ()
checkOverlapping ann userpats genpats
= foldM_ (\p -> lift . go p) genpats userpats
where
go gps up
= let gps' = filter (\gp -> isNothing $ matcher gp up ) gps
in if length gps' < length gps
then return gps'
else left (DesugarOverlappingPattern ann up)
freshes :: (Monad m, Hashable n) => Int -> FreshT n m [Name n]
freshes n = replicateM n fresh
|
48b9035e01814cc19f49c47e3307abfeeab598d8ab10f0b7921ceb3e6e610238 | MassD/99 | p65.ml |
Layout a binary tree ( 2 ) . ( medium )
-layout2.gif
An alternative layout method is depicted in this illustration . Find out the rules and write the corresponding OCaml function .
Hint : On a given level , the horizontal distance between neighbouring nodes is constant .
Layout a binary tree (2). (medium)
-layout2.gif
An alternative layout method is depicted in this illustration. Find out the rules and write the corresponding OCaml function.
Hint: On a given level, the horizontal distance between neighbouring nodes is constant.
*)
type 'a btree = Empty | Node of 'a * 'a btree * 'a btree
type 'a pos_binary_tree =
| E (* represents the empty tree *)
| N of 'a * int * int * 'a pos_binary_tree * 'a pos_binary_tree
let rec height = function
| Empty -> 0
| Node (_,l,r) -> 1 + max (height l) (height r)
let get_x h level = (2. ** (Float.of_int (h-level)) |> Int.of_float) - 1
let get_fullsize h level = (2. ** (Float.of_int (h+1-level)) |> Int.of_float) - 1
let layout_btree2_correct t =
let h = height t in
let rec lay off y = function
| Empty -> get_fullsize h y, E
| Node (w, Empty, r) when off = 0 ->
let wtr, newr = lay 1 (y+1) r in
1+wtr, N (w, 1, y+1, E, newr)
| Node (w, l, r) ->
let wt1, newl = lay off (y+1) l in
let wt2, newr = lay (off+wt1+1) (y+1) r in
wt1+wt2+1, N (w, off+wt1+1, y, newl, newr)
in
lay 0 1 t |> snd
(* below is also wrong, as it doesn't handle the special case of leftmost node *)
let layout_btree2 t =
let h = height t in
let rec build level xs = function
| Empty -> E
| Node (k,l,r) ->
let x = xs + get_x h level in
N (k,x,level,build (level+1) xs l,build (level+1) (x+1) r)
in
build 1 0 t
(* below is a so wrong algorithm *)
let layout_btree2' t =
let rec lay off width y = function
| Empty -> 0, E
| Node (w,l, r) ->
match width with
| None ->
let wt, newl = lay off width (y+1) l in
let _, newr = lay (off+wt+1) (Some wt) (y+1) r in
2*wt+1, N (w, off+wt+1, y, newl, newr)
| Some wt ->
let mid = wt / 2 in
let _, newl = lay off (Some mid) (y+1) l in
let _, newr = lay (off+mid+1) (Some mid) (y+1) r in
wt, N (w, off+mid+1, y, newl, newr)
in
lay 0 None 1 t |> snd
let bt =
Node ('n',
Node ('k',
Node ('c',
Node ('a',Node ('0', Empty, Empty), Empty),
Node ('e',
Node ('d',Empty,Empty),
Node ('g',Empty,Empty))),
Node ('m',Empty,Empty)),
Node ('u',
Node ('p',Empty, Node ('q',Empty,Empty)),
Empty))
let rec xys = function
| E -> []
| N (k,x,y,l,r) -> (k,x,y)::(List.rev_append (xys l) (xys r))
| null | https://raw.githubusercontent.com/MassD/99/1d3019eb55b0d621ed1df4132315673dd812b1e1/55-69-binary-tress/p65.ml | ocaml | represents the empty tree
below is also wrong, as it doesn't handle the special case of leftmost node
below is a so wrong algorithm |
Layout a binary tree ( 2 ) . ( medium )
-layout2.gif
An alternative layout method is depicted in this illustration . Find out the rules and write the corresponding OCaml function .
Hint : On a given level , the horizontal distance between neighbouring nodes is constant .
Layout a binary tree (2). (medium)
-layout2.gif
An alternative layout method is depicted in this illustration. Find out the rules and write the corresponding OCaml function.
Hint: On a given level, the horizontal distance between neighbouring nodes is constant.
*)
type 'a btree = Empty | Node of 'a * 'a btree * 'a btree
type 'a pos_binary_tree =
| N of 'a * int * int * 'a pos_binary_tree * 'a pos_binary_tree
let rec height = function
| Empty -> 0
| Node (_,l,r) -> 1 + max (height l) (height r)
let get_x h level = (2. ** (Float.of_int (h-level)) |> Int.of_float) - 1
let get_fullsize h level = (2. ** (Float.of_int (h+1-level)) |> Int.of_float) - 1
let layout_btree2_correct t =
let h = height t in
let rec lay off y = function
| Empty -> get_fullsize h y, E
| Node (w, Empty, r) when off = 0 ->
let wtr, newr = lay 1 (y+1) r in
1+wtr, N (w, 1, y+1, E, newr)
| Node (w, l, r) ->
let wt1, newl = lay off (y+1) l in
let wt2, newr = lay (off+wt1+1) (y+1) r in
wt1+wt2+1, N (w, off+wt1+1, y, newl, newr)
in
lay 0 1 t |> snd
let layout_btree2 t =
let h = height t in
let rec build level xs = function
| Empty -> E
| Node (k,l,r) ->
let x = xs + get_x h level in
N (k,x,level,build (level+1) xs l,build (level+1) (x+1) r)
in
build 1 0 t
let layout_btree2' t =
let rec lay off width y = function
| Empty -> 0, E
| Node (w,l, r) ->
match width with
| None ->
let wt, newl = lay off width (y+1) l in
let _, newr = lay (off+wt+1) (Some wt) (y+1) r in
2*wt+1, N (w, off+wt+1, y, newl, newr)
| Some wt ->
let mid = wt / 2 in
let _, newl = lay off (Some mid) (y+1) l in
let _, newr = lay (off+mid+1) (Some mid) (y+1) r in
wt, N (w, off+mid+1, y, newl, newr)
in
lay 0 None 1 t |> snd
let bt =
Node ('n',
Node ('k',
Node ('c',
Node ('a',Node ('0', Empty, Empty), Empty),
Node ('e',
Node ('d',Empty,Empty),
Node ('g',Empty,Empty))),
Node ('m',Empty,Empty)),
Node ('u',
Node ('p',Empty, Node ('q',Empty,Empty)),
Empty))
let rec xys = function
| E -> []
| N (k,x,y,l,r) -> (k,x,y)::(List.rev_append (xys l) (xys r))
|
7234005aa0e11f5f9cdd697dbb28a8c2735ff4a16664a624ec73c7e907af8a9c | input-output-hk/marlowe-cardano | GetNextSteps.hs | # LANGUAGE DataKinds #
{-# LANGUAGE GADTs #-}
# LANGUAGE QuasiQuotes #
module Language.Marlowe.Runtime.Sync.Database.PostgreSQL.GetNextSteps
where
import Control.Applicative ((<|>))
import qualified Control.Foldl as Fold
import Data.Binary (get)
import Data.Binary.Get (runGet)
import Data.ByteString (ByteString)
import Data.ByteString.Lazy (fromStrict)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromJust)
import Data.Time (localTimeToUTC, utc)
import qualified Data.Vector as V
import Hasql.TH (foldStatement, maybeStatement, vectorStatement)
import qualified Hasql.Transaction as T
import Language.Marlowe.Core.V1.Semantics (MarloweData(..), MarloweParams(MarloweParams))
import Language.Marlowe.Runtime.ChainSync.Api
( Address(Address)
, AssetId(AssetId)
, Assets(..)
, BlockHeader(..)
, BlockHeaderHash(..)
, ChainPoint
, PolicyId(PolicyId)
, TokenName(TokenName)
, Tokens(Tokens)
, TxId(..)
, TxOutRef(..)
, WithGenesis(..)
, fromDatum
)
import Language.Marlowe.Runtime.Core.Api
( ContractId(..)
, MarloweVersion(..)
, MarloweVersionTag(V1)
, Payout(..)
, Transaction(..)
, TransactionOutput(..)
, TransactionScriptOutput(..)
)
import Language.Marlowe.Runtime.History.Api (ContractStep(..), RedeemStep(..))
import Language.Marlowe.Runtime.Sync.Database (Next(..))
import qualified Plutus.V2.Ledger.Api as PV2
import Prelude hiding (init)
import Witherable (catMaybes, mapMaybe)
getNextSteps :: MarloweVersion v -> ContractId -> ChainPoint -> T.Transaction (Next (ContractStep v))
getNextSteps MarloweV1 contractId point = do
orient point >>= \case
RolledBack toPoint -> pure $ Rollback toPoint
AtTip -> pure Wait
BeforeTip -> getNextTxIds contractId point >>= \case
Nothing -> pure Wait
Just NextTxIds{..} -> do
applySteps <- getApplySteps nextBlock contractId nextApplyTxIds
redeemSteps <- getRedeemSteps nextWithdrawalTxIds
pure $ Next nextBlock $ (ApplyTransaction <$> applySteps) <> (RedeemPayout <$> redeemSteps)
data Orientation
= BeforeTip
| AtTip
| RolledBack ChainPoint
orient :: ChainPoint -> T.Transaction Orientation
orient Genesis = pure BeforeTip
orient (At BlockHeader{..}) = T.statement (unBlockHeaderHash headerHash) $ decodeResult <$>
[maybeStatement|
SELECT
block.slotNo :: bigint,
block.id :: bytea,
block.blockNo :: bigint
FROM marlowe.rollbackBlock
JOIN marlowe.block ON block.id = rollbackBlock.toBlock
WHERE rollbackBlock.fromBlock = $1 :: bytea
|]
where
decodeResult Nothing = BeforeTip
decodeResult (Just (slot, hash, block))
| slot < 0 || block < 0 = RolledBack Genesis
| otherwise = RolledBack $ At BlockHeader
{ slotNo = fromIntegral slot
, headerHash = BlockHeaderHash hash
, blockNo = fromIntegral block
}
data NextTxIds = NextTxIds
{ nextBlock :: BlockHeader
, nextApplyTxIds :: [TxId]
, nextWithdrawalTxIds :: [TxId]
}
getNextTxIds :: ContractId -> ChainPoint -> T.Transaction (Maybe NextTxIds)
getNextTxIds (ContractId TxOutRef{..}) point = T.statement params $ fmap (NextTxIds <$> decodeBlockHeader <*> decodeApplyTxIds <*> decodeWithdrawalTxIds) <$>
[maybeStatement|
WITH params (createTxId, createTxIx, afterSlot) AS
( SELECT $1 :: bytea, $2 :: smallint, $3 :: bigint
)
, nextApplyTxIds (slotNo, blockHeaderHash, blockNo, txIds) AS
( SELECT
slotNo,
(ARRAY_AGG(blockId))[1],
(ARRAY_AGG(blockNo))[1],
ARRAY_AGG(txId)
FROM marlowe.applyTx
JOIN params USING (createTxId, createTxIx)
WHERE slotNo > params.afterSlot
GROUP BY slotNo
ORDER BY slotNo
LIMIT 1
)
, nextWithdrawalTxIds (slotNo, blockHeaderHash, blockNo, txIds) AS
( SELECT
slotNo,
(ARRAY_AGG(blockId))[1],
(ARRAY_AGG(blockNo))[1],
ARRAY_AGG(txId)
FROM marlowe.withdrawalTxIn
JOIN params USING (createTxId, createTxIx)
WHERE slotNo > params.afterSlot
GROUP BY slotNo
ORDER BY slotNo
LIMIT 1
)
SELECT
COALESCE (nextApplyTxIds.slotNo, nextWithdrawalTxIds.slotNo) :: bigint,
COALESCE (nextApplyTxIds.blockHeaderHash, nextWithdrawalTxIds.blockHeaderHash) :: bytea,
COALESCE (nextApplyTxIds.blockNo, nextWithdrawalTxIds.blockNo) :: bigint,
COALESCE (nextApplyTxIds.txIds, '{}') :: bytea[],
COALESCE (nextWithdrawalTxIds.txIds, '{}') :: bytea[]
FROM nextApplyTxIds
FULL OUTER JOIN nextWithdrawalTxIds
ON nextApplyTxIds.slotNo = nextWithdrawalTxIds.slotNo
ORDER BY COALESCE (nextApplyTxIds.slotNo, nextWithdrawalTxIds.slotNo)
LIMIT 1
|]
where
params = (unTxId txId, fromIntegral txIx, pointSlot)
pointSlot = case point of
Genesis -> -1
At BlockHeader{..} -> fromIntegral slotNo
decodeBlockHeader (slot, hash, block, _, _) = BlockHeader
{ slotNo = fromIntegral slot
, headerHash = BlockHeaderHash hash
, blockNo = fromIntegral block
}
decodeApplyTxIds (_, _, _, ids, _) = decodeTxIds ids
decodeWithdrawalTxIds (_, _, _, _, ids) = decodeTxIds ids
decodeTxIds ids = V.toList $ V.map TxId ids
getApplySteps :: BlockHeader -> ContractId -> [TxId] -> T.Transaction [Transaction 'V1]
getApplySteps blockHeader contractId txIds = T.statement params $
[foldStatement|
WITH txIds (txId) AS
( SELECT * FROM UNNEST ($1 :: bytea[])
)
SELECT
applyTx.txId :: bytea,
applyTx.metadata :: bytea?,
applyTx.invalidBefore :: timestamp,
applyTx.invalidHereafter :: timestamp,
applyTx.inputs :: bytea,
applyTx.outputTxIx :: smallint?,
payoutOut.txIx :: smallint?,
payoutOut.address :: bytea?,
payoutOut.lovelace :: bigint?,
payoutOut.policyIds :: bytea[]?,
payoutOut.tokenNames :: bytea[]?,
payoutOut.quantities :: bigint[]?,
payoutOut.rolesCurrency :: bytea?,
payoutOut.role :: bytea?,
contractOut.address :: bytea?,
contractOut.lovelace :: bigint?,
contractOut.policyIds :: bytea[]?,
contractOut.tokenNames :: bytea[]?,
contractOut.quantities :: bigint[]?,
contractOut.rolesCurrency :: bytea?,
contractOut.state :: bytea?,
contractOut.contract :: bytea?
FROM marlowe.applyTx
JOIN txIds USING (txId)
LEFT JOIN
( SELECT
payoutTxOut.txId AS txId,
payoutTxOut.txIx AS txIx,
(ARRAY_AGG(txOut.address))[1] AS address,
(ARRAY_AGG(txOut.lovelace))[1] AS lovelace,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.policyId), NULL)) AS policyIds,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.name), NULL)) AS tokenNames,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.quantity), NULL)) AS quantities,
(ARRAY_AGG(payoutTxOut.rolesCurrency))[1] AS rolesCurrency,
(ARRAY_AGG(payoutTxOut.role))[1] AS role
FROM marlowe.payoutTxOut
JOIN txIds USING (txId)
JOIN marlowe.txOut USING (txId, txIx)
LEFT JOIN marlowe.txOutAsset USING (txId, txIx)
GROUP BY payoutTxOut.txId, payoutTxOut.txIx
) AS payoutOut USING (txId)
LEFT JOIN
( SELECT
contractTxOut.txId AS txId,
contractTxOut.txIx AS txIx,
(ARRAY_AGG(txOut.address))[1] AS address,
(ARRAY_AGG(txOut.lovelace))[1] AS lovelace,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.policyId), NULL)) AS policyIds,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.name), NULL)) AS tokenNames,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.quantity), NULL)) AS quantities,
(ARRAY_AGG(contractTxOut.rolesCurrency))[1] AS rolesCurrency,
(ARRAY_AGG(contractTxOut.state))[1] AS state,
(ARRAY_AGG(contractTxOut.contract))[1] AS contract
FROM marlowe.contractTxOut
JOIN txIds USING (txId)
JOIN marlowe.txOut USING (txId, txIx)
LEFT JOIN marlowe.txOutAsset USING (txId, txIx)
GROUP BY contractTxOut.txId, contractTxOut.txIx
) AS contractOut USING (txId)
|] resultFold
where
resultFold = catMaybes . Map.elems <$> Fold.groupBy extractTxId (mergeWithChildren extractTx addPayouts foldPayouts)
extractTxId
( txId
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
) = txId
extractTx
( txId
, metadata
, invalidBefore
, invalidHereafter
, inputs
, outputTxIx
, _
, _
, _
, _
, _
, _
, _
, _
, outputAddress
, outputLovelace
, outputPolicyIds
, outputTokenNames
, outputQuantities
, outputRolesCurrency
, outputState
, outputContract
) = Transaction
{ transactionId = TxId txId
, contractId
, metadata = maybe mempty (runGet get. fromStrict) metadata
, blockHeader
, validityLowerBound = localTimeToUTC utc invalidBefore
, validityUpperBound = localTimeToUTC utc invalidHereafter
, inputs = fromJust $ fromDatum $ runGet get $ fromStrict inputs
, output = TransactionOutput
{ payouts = mempty
, scriptOutput = do
txIx <- outputTxIx
address <- outputAddress
lovelace <- outputLovelace
policyIds <- V.toList <$> outputPolicyIds
tokenNames <- V.toList <$> outputTokenNames
quantities <- V.toList <$> outputQuantities
rolesCurrency :: ByteString <- outputRolesCurrency
state <- outputState
contract <- outputContract
pure TransactionScriptOutput
{ address = Address address
, assets = Assets
{ ada = fromIntegral lovelace
, tokens = Tokens $ Map.fromList $ zipWith3
(\p t q -> (AssetId (PolicyId p) (TokenName t), fromIntegral q))
policyIds
tokenNames
quantities
}
, utxo = TxOutRef (TxId txId) (fromIntegral txIx)
, datum = MarloweData
{ marloweParams = MarloweParams $ PV2.CurrencySymbol $ PV2.toBuiltin rolesCurrency
, marloweState = fromJust $ fromDatum $ runGet get $ fromStrict state
, marloweContract = fromJust $ fromDatum $ runGet get $ fromStrict contract
}
}
}
} :: Transaction 'V1
foldPayouts = Map.fromList . mapMaybe (\row -> (,) <$> extractPayoutTxOutRef row <*> extractPayout row) <$> Fold.list
extractPayoutTxOutRef
( txId
, _
, _
, _
, _
, _
, txIx
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
) = TxOutRef (TxId txId) . fromIntegral <$> txIx
extractPayout
( _
, _
, _
, _
, _
, _
, _
, address
, lovelace
, policyIds
, tokenNames
, quantities
, rolesCurrency
, role
, _
, _
, _
, _
, _
, _
, _
, _
) = Payout @'V1
<$> (Address <$> address)
<*> ( Assets
<$> (fromIntegral <$> lovelace)
<*> ( Tokens . Map.fromList <$>
( zipWith3 (\p t q -> (AssetId (PolicyId p) (TokenName t), fromIntegral q))
<$> (V.toList <$> policyIds)
<*> (V.toList <$> tokenNames)
<*> (V.toList <$> quantities)
)
)
)
<*> ( AssetId
<$> (PolicyId <$> rolesCurrency)
<*> (TokenName <$> role)
)
addPayouts :: Map TxOutRef (Payout v) -> Transaction v -> Transaction v
addPayouts payouts' tx@Transaction{output} = tx
{ output = output
{ payouts = payouts output <> payouts'
}
}
params = V.fromList $ unTxId <$> txIds
getRedeemSteps :: [TxId] -> T.Transaction [RedeemStep 'V1]
getRedeemSteps txIds = T.statement params $ fmap decodeRow . V.toList <$>
[vectorStatement|
WITH txIds (txId) AS
( SELECT * FROM UNNEST ($1 :: bytea[])
)
SELECT
payoutTxOut.txId :: bytea,
payoutTxOut.txIx :: smallint,
withdrawalTxIn.txId :: bytea,
payoutTxOut.rolesCurrency :: bytea,
payoutTxOut.role :: bytea
FROM marlowe.withdrawalTxIn
JOIN txIds USING (txId)
JOIN marlowe.payoutTxOut
ON withdrawalTxIn.payoutTxId = payoutTxOut.txId
AND withdrawalTxIn.payoutTxIx = payoutTxOut.txIx
|]
where
params = V.fromList $ unTxId <$> txIds
decodeRow (payoutTxId, payoutTxIx, txId, rolesCurrency, role) = RedeemStep
{ utxo = TxOutRef (TxId payoutTxId) (fromIntegral payoutTxIx)
, redeemingTx = TxId txId
, datum = AssetId (PolicyId rolesCurrency) (TokenName role)
} :: RedeemStep 'V1
mergeWithChildren :: (a -> r) -> (c -> r -> r) -> Fold.Fold a c -> Fold.Fold a (Maybe r)
mergeWithChildren extractParent mergeChild (Fold.Fold fChild iChild pChild) = Fold.Fold foldRow (Nothing, iChild) mapResult
where
foldRow (mParent, children) row = (mParent <|> Just (extractParent row), fChild children row)
mapResult (mParent, children) = mergeChild (pChild children) <$> mParent
| null | https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/3e7471464a54f2705157380b99839770b98eede3/marlowe-runtime/sync/Language/Marlowe/Runtime/Sync/Database/PostgreSQL/GetNextSteps.hs | haskell | # LANGUAGE GADTs # | # LANGUAGE DataKinds #
# LANGUAGE QuasiQuotes #
module Language.Marlowe.Runtime.Sync.Database.PostgreSQL.GetNextSteps
where
import Control.Applicative ((<|>))
import qualified Control.Foldl as Fold
import Data.Binary (get)
import Data.Binary.Get (runGet)
import Data.ByteString (ByteString)
import Data.ByteString.Lazy (fromStrict)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromJust)
import Data.Time (localTimeToUTC, utc)
import qualified Data.Vector as V
import Hasql.TH (foldStatement, maybeStatement, vectorStatement)
import qualified Hasql.Transaction as T
import Language.Marlowe.Core.V1.Semantics (MarloweData(..), MarloweParams(MarloweParams))
import Language.Marlowe.Runtime.ChainSync.Api
( Address(Address)
, AssetId(AssetId)
, Assets(..)
, BlockHeader(..)
, BlockHeaderHash(..)
, ChainPoint
, PolicyId(PolicyId)
, TokenName(TokenName)
, Tokens(Tokens)
, TxId(..)
, TxOutRef(..)
, WithGenesis(..)
, fromDatum
)
import Language.Marlowe.Runtime.Core.Api
( ContractId(..)
, MarloweVersion(..)
, MarloweVersionTag(V1)
, Payout(..)
, Transaction(..)
, TransactionOutput(..)
, TransactionScriptOutput(..)
)
import Language.Marlowe.Runtime.History.Api (ContractStep(..), RedeemStep(..))
import Language.Marlowe.Runtime.Sync.Database (Next(..))
import qualified Plutus.V2.Ledger.Api as PV2
import Prelude hiding (init)
import Witherable (catMaybes, mapMaybe)
getNextSteps :: MarloweVersion v -> ContractId -> ChainPoint -> T.Transaction (Next (ContractStep v))
getNextSteps MarloweV1 contractId point = do
orient point >>= \case
RolledBack toPoint -> pure $ Rollback toPoint
AtTip -> pure Wait
BeforeTip -> getNextTxIds contractId point >>= \case
Nothing -> pure Wait
Just NextTxIds{..} -> do
applySteps <- getApplySteps nextBlock contractId nextApplyTxIds
redeemSteps <- getRedeemSteps nextWithdrawalTxIds
pure $ Next nextBlock $ (ApplyTransaction <$> applySteps) <> (RedeemPayout <$> redeemSteps)
data Orientation
= BeforeTip
| AtTip
| RolledBack ChainPoint
orient :: ChainPoint -> T.Transaction Orientation
orient Genesis = pure BeforeTip
orient (At BlockHeader{..}) = T.statement (unBlockHeaderHash headerHash) $ decodeResult <$>
[maybeStatement|
SELECT
block.slotNo :: bigint,
block.id :: bytea,
block.blockNo :: bigint
FROM marlowe.rollbackBlock
JOIN marlowe.block ON block.id = rollbackBlock.toBlock
WHERE rollbackBlock.fromBlock = $1 :: bytea
|]
where
decodeResult Nothing = BeforeTip
decodeResult (Just (slot, hash, block))
| slot < 0 || block < 0 = RolledBack Genesis
| otherwise = RolledBack $ At BlockHeader
{ slotNo = fromIntegral slot
, headerHash = BlockHeaderHash hash
, blockNo = fromIntegral block
}
data NextTxIds = NextTxIds
{ nextBlock :: BlockHeader
, nextApplyTxIds :: [TxId]
, nextWithdrawalTxIds :: [TxId]
}
getNextTxIds :: ContractId -> ChainPoint -> T.Transaction (Maybe NextTxIds)
getNextTxIds (ContractId TxOutRef{..}) point = T.statement params $ fmap (NextTxIds <$> decodeBlockHeader <*> decodeApplyTxIds <*> decodeWithdrawalTxIds) <$>
[maybeStatement|
WITH params (createTxId, createTxIx, afterSlot) AS
( SELECT $1 :: bytea, $2 :: smallint, $3 :: bigint
)
, nextApplyTxIds (slotNo, blockHeaderHash, blockNo, txIds) AS
( SELECT
slotNo,
(ARRAY_AGG(blockId))[1],
(ARRAY_AGG(blockNo))[1],
ARRAY_AGG(txId)
FROM marlowe.applyTx
JOIN params USING (createTxId, createTxIx)
WHERE slotNo > params.afterSlot
GROUP BY slotNo
ORDER BY slotNo
LIMIT 1
)
, nextWithdrawalTxIds (slotNo, blockHeaderHash, blockNo, txIds) AS
( SELECT
slotNo,
(ARRAY_AGG(blockId))[1],
(ARRAY_AGG(blockNo))[1],
ARRAY_AGG(txId)
FROM marlowe.withdrawalTxIn
JOIN params USING (createTxId, createTxIx)
WHERE slotNo > params.afterSlot
GROUP BY slotNo
ORDER BY slotNo
LIMIT 1
)
SELECT
COALESCE (nextApplyTxIds.slotNo, nextWithdrawalTxIds.slotNo) :: bigint,
COALESCE (nextApplyTxIds.blockHeaderHash, nextWithdrawalTxIds.blockHeaderHash) :: bytea,
COALESCE (nextApplyTxIds.blockNo, nextWithdrawalTxIds.blockNo) :: bigint,
COALESCE (nextApplyTxIds.txIds, '{}') :: bytea[],
COALESCE (nextWithdrawalTxIds.txIds, '{}') :: bytea[]
FROM nextApplyTxIds
FULL OUTER JOIN nextWithdrawalTxIds
ON nextApplyTxIds.slotNo = nextWithdrawalTxIds.slotNo
ORDER BY COALESCE (nextApplyTxIds.slotNo, nextWithdrawalTxIds.slotNo)
LIMIT 1
|]
where
params = (unTxId txId, fromIntegral txIx, pointSlot)
pointSlot = case point of
Genesis -> -1
At BlockHeader{..} -> fromIntegral slotNo
decodeBlockHeader (slot, hash, block, _, _) = BlockHeader
{ slotNo = fromIntegral slot
, headerHash = BlockHeaderHash hash
, blockNo = fromIntegral block
}
decodeApplyTxIds (_, _, _, ids, _) = decodeTxIds ids
decodeWithdrawalTxIds (_, _, _, _, ids) = decodeTxIds ids
decodeTxIds ids = V.toList $ V.map TxId ids
getApplySteps :: BlockHeader -> ContractId -> [TxId] -> T.Transaction [Transaction 'V1]
getApplySteps blockHeader contractId txIds = T.statement params $
[foldStatement|
WITH txIds (txId) AS
( SELECT * FROM UNNEST ($1 :: bytea[])
)
SELECT
applyTx.txId :: bytea,
applyTx.metadata :: bytea?,
applyTx.invalidBefore :: timestamp,
applyTx.invalidHereafter :: timestamp,
applyTx.inputs :: bytea,
applyTx.outputTxIx :: smallint?,
payoutOut.txIx :: smallint?,
payoutOut.address :: bytea?,
payoutOut.lovelace :: bigint?,
payoutOut.policyIds :: bytea[]?,
payoutOut.tokenNames :: bytea[]?,
payoutOut.quantities :: bigint[]?,
payoutOut.rolesCurrency :: bytea?,
payoutOut.role :: bytea?,
contractOut.address :: bytea?,
contractOut.lovelace :: bigint?,
contractOut.policyIds :: bytea[]?,
contractOut.tokenNames :: bytea[]?,
contractOut.quantities :: bigint[]?,
contractOut.rolesCurrency :: bytea?,
contractOut.state :: bytea?,
contractOut.contract :: bytea?
FROM marlowe.applyTx
JOIN txIds USING (txId)
LEFT JOIN
( SELECT
payoutTxOut.txId AS txId,
payoutTxOut.txIx AS txIx,
(ARRAY_AGG(txOut.address))[1] AS address,
(ARRAY_AGG(txOut.lovelace))[1] AS lovelace,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.policyId), NULL)) AS policyIds,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.name), NULL)) AS tokenNames,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.quantity), NULL)) AS quantities,
(ARRAY_AGG(payoutTxOut.rolesCurrency))[1] AS rolesCurrency,
(ARRAY_AGG(payoutTxOut.role))[1] AS role
FROM marlowe.payoutTxOut
JOIN txIds USING (txId)
JOIN marlowe.txOut USING (txId, txIx)
LEFT JOIN marlowe.txOutAsset USING (txId, txIx)
GROUP BY payoutTxOut.txId, payoutTxOut.txIx
) AS payoutOut USING (txId)
LEFT JOIN
( SELECT
contractTxOut.txId AS txId,
contractTxOut.txIx AS txIx,
(ARRAY_AGG(txOut.address))[1] AS address,
(ARRAY_AGG(txOut.lovelace))[1] AS lovelace,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.policyId), NULL)) AS policyIds,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.name), NULL)) AS tokenNames,
(ARRAY_REMOVE(ARRAY_AGG(txOutAsset.quantity), NULL)) AS quantities,
(ARRAY_AGG(contractTxOut.rolesCurrency))[1] AS rolesCurrency,
(ARRAY_AGG(contractTxOut.state))[1] AS state,
(ARRAY_AGG(contractTxOut.contract))[1] AS contract
FROM marlowe.contractTxOut
JOIN txIds USING (txId)
JOIN marlowe.txOut USING (txId, txIx)
LEFT JOIN marlowe.txOutAsset USING (txId, txIx)
GROUP BY contractTxOut.txId, contractTxOut.txIx
) AS contractOut USING (txId)
|] resultFold
where
resultFold = catMaybes . Map.elems <$> Fold.groupBy extractTxId (mergeWithChildren extractTx addPayouts foldPayouts)
extractTxId
( txId
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
) = txId
extractTx
( txId
, metadata
, invalidBefore
, invalidHereafter
, inputs
, outputTxIx
, _
, _
, _
, _
, _
, _
, _
, _
, outputAddress
, outputLovelace
, outputPolicyIds
, outputTokenNames
, outputQuantities
, outputRolesCurrency
, outputState
, outputContract
) = Transaction
{ transactionId = TxId txId
, contractId
, metadata = maybe mempty (runGet get. fromStrict) metadata
, blockHeader
, validityLowerBound = localTimeToUTC utc invalidBefore
, validityUpperBound = localTimeToUTC utc invalidHereafter
, inputs = fromJust $ fromDatum $ runGet get $ fromStrict inputs
, output = TransactionOutput
{ payouts = mempty
, scriptOutput = do
txIx <- outputTxIx
address <- outputAddress
lovelace <- outputLovelace
policyIds <- V.toList <$> outputPolicyIds
tokenNames <- V.toList <$> outputTokenNames
quantities <- V.toList <$> outputQuantities
rolesCurrency :: ByteString <- outputRolesCurrency
state <- outputState
contract <- outputContract
pure TransactionScriptOutput
{ address = Address address
, assets = Assets
{ ada = fromIntegral lovelace
, tokens = Tokens $ Map.fromList $ zipWith3
(\p t q -> (AssetId (PolicyId p) (TokenName t), fromIntegral q))
policyIds
tokenNames
quantities
}
, utxo = TxOutRef (TxId txId) (fromIntegral txIx)
, datum = MarloweData
{ marloweParams = MarloweParams $ PV2.CurrencySymbol $ PV2.toBuiltin rolesCurrency
, marloweState = fromJust $ fromDatum $ runGet get $ fromStrict state
, marloweContract = fromJust $ fromDatum $ runGet get $ fromStrict contract
}
}
}
} :: Transaction 'V1
foldPayouts = Map.fromList . mapMaybe (\row -> (,) <$> extractPayoutTxOutRef row <*> extractPayout row) <$> Fold.list
extractPayoutTxOutRef
( txId
, _
, _
, _
, _
, _
, txIx
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
, _
) = TxOutRef (TxId txId) . fromIntegral <$> txIx
extractPayout
( _
, _
, _
, _
, _
, _
, _
, address
, lovelace
, policyIds
, tokenNames
, quantities
, rolesCurrency
, role
, _
, _
, _
, _
, _
, _
, _
, _
) = Payout @'V1
<$> (Address <$> address)
<*> ( Assets
<$> (fromIntegral <$> lovelace)
<*> ( Tokens . Map.fromList <$>
( zipWith3 (\p t q -> (AssetId (PolicyId p) (TokenName t), fromIntegral q))
<$> (V.toList <$> policyIds)
<*> (V.toList <$> tokenNames)
<*> (V.toList <$> quantities)
)
)
)
<*> ( AssetId
<$> (PolicyId <$> rolesCurrency)
<*> (TokenName <$> role)
)
addPayouts :: Map TxOutRef (Payout v) -> Transaction v -> Transaction v
addPayouts payouts' tx@Transaction{output} = tx
{ output = output
{ payouts = payouts output <> payouts'
}
}
params = V.fromList $ unTxId <$> txIds
getRedeemSteps :: [TxId] -> T.Transaction [RedeemStep 'V1]
getRedeemSteps txIds = T.statement params $ fmap decodeRow . V.toList <$>
[vectorStatement|
WITH txIds (txId) AS
( SELECT * FROM UNNEST ($1 :: bytea[])
)
SELECT
payoutTxOut.txId :: bytea,
payoutTxOut.txIx :: smallint,
withdrawalTxIn.txId :: bytea,
payoutTxOut.rolesCurrency :: bytea,
payoutTxOut.role :: bytea
FROM marlowe.withdrawalTxIn
JOIN txIds USING (txId)
JOIN marlowe.payoutTxOut
ON withdrawalTxIn.payoutTxId = payoutTxOut.txId
AND withdrawalTxIn.payoutTxIx = payoutTxOut.txIx
|]
where
params = V.fromList $ unTxId <$> txIds
decodeRow (payoutTxId, payoutTxIx, txId, rolesCurrency, role) = RedeemStep
{ utxo = TxOutRef (TxId payoutTxId) (fromIntegral payoutTxIx)
, redeemingTx = TxId txId
, datum = AssetId (PolicyId rolesCurrency) (TokenName role)
} :: RedeemStep 'V1
mergeWithChildren :: (a -> r) -> (c -> r -> r) -> Fold.Fold a c -> Fold.Fold a (Maybe r)
mergeWithChildren extractParent mergeChild (Fold.Fold fChild iChild pChild) = Fold.Fold foldRow (Nothing, iChild) mapResult
where
foldRow (mParent, children) row = (mParent <|> Just (extractParent row), fChild children row)
mapResult (mParent, children) = mergeChild (pChild children) <$> mParent
|
7e2857d6453463714aa702dd9cc7f993dee939a4d76c5934c813b8fbdc98926c | cinmcantu/cartao-de-credito | dashboard.clj | (ns cartao-de-credito.dashboard.dashboard
(:require [cartao-de-credito.database.card-db :as c.d.card-db]
[cartao-de-credito.database.client-db :as c.d.client-db]
[cartao-de-credito.database.expends-db :as c.d.expends-db]
[cartao-de-credito.logics.join :as c.l.join]
[cartao-de-credito.logics.expends-by-category :as c.l.expends-by-category]
[cartao-de-credito.logics.search :as c.l.search]))
; Global symbols definitions
(def all-clients (c.d.client-db/all-clients))
(def all-cards (c.d.card-db/all-cards))
(def all-expends (c.d.expends-db/all-expends))
; All data
(println "All clients data")
(println all-clients)
(println "\nAll cards data")
(println all-cards)
(println "\nAll expends data")
(println all-expends)
; Expends grouped by category
(println "\nExpends grouped by category")
(println (c.l.expends-by-category/cards-expends-by-category all-expends))
Monthly expends per client
(println "\nMonthly expends per client")
(println (c.l.join/all-client-expends-per-month))
Searchs
(println "\nSearch per value")
(println (c.l.search/expends-per-value 30.99))
(println "\nSearch per place")
(println (c.l.search/expends-per-place "shell")) | null | https://raw.githubusercontent.com/cinmcantu/cartao-de-credito/e9fc761ee1fdd0f404449b3bf4d375f54ff60680/src/cartao_de_credito/dashboard/dashboard.clj | clojure | Global symbols definitions
All data
Expends grouped by category | (ns cartao-de-credito.dashboard.dashboard
(:require [cartao-de-credito.database.card-db :as c.d.card-db]
[cartao-de-credito.database.client-db :as c.d.client-db]
[cartao-de-credito.database.expends-db :as c.d.expends-db]
[cartao-de-credito.logics.join :as c.l.join]
[cartao-de-credito.logics.expends-by-category :as c.l.expends-by-category]
[cartao-de-credito.logics.search :as c.l.search]))
(def all-clients (c.d.client-db/all-clients))
(def all-cards (c.d.card-db/all-cards))
(def all-expends (c.d.expends-db/all-expends))
(println "All clients data")
(println all-clients)
(println "\nAll cards data")
(println all-cards)
(println "\nAll expends data")
(println all-expends)
(println "\nExpends grouped by category")
(println (c.l.expends-by-category/cards-expends-by-category all-expends))
Monthly expends per client
(println "\nMonthly expends per client")
(println (c.l.join/all-client-expends-per-month))
Searchs
(println "\nSearch per value")
(println (c.l.search/expends-per-value 30.99))
(println "\nSearch per place")
(println (c.l.search/expends-per-place "shell")) |
79c7ee280dc90b1c678a78c3198fd34bfeac32b465d04db51296611a20c7c627 | hasktorch/hasktorch | Native13.hs |
-- generated by using spec/Declarations.yaml
# LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
# LANGUAGE TemplateHaskell #
# LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
module Torch.Internal.Unmanaged.Native.Native13 where
import Foreign.C.String
import Foreign.C.Types
import Foreign
import Torch.Internal.Type
import qualified Language.C.Inline.Cpp as C
import qualified Language.C.Inline.Cpp.Unsafe as C
import qualified Language.C.Inline.Context as C
import qualified Language.C.Types as C
C.context $ C.cppCtx <> mempty { C.ctxTypesTable = typeTable }
C.include "<vector>"
C.include "<ATen/Tensor.h>"
C.include "<ATen/Functions.h>"
upsample_trilinear3d_backward_out_ttllbd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CBool
-> CDouble
-> IO (Ptr Tensor)
upsample_trilinear3d_backward_out_ttllbd _grad_input _grad_output _output_size _input_size _align_corners _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_trilinear3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(bool _align_corners)
, $(double _scales_d)));
}|]
upsample_trilinear3d_backward_out_ttllb
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CBool
-> IO (Ptr Tensor)
upsample_trilinear3d_backward_out_ttllb _grad_input _grad_output _output_size _input_size _align_corners =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_trilinear3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(bool _align_corners)));
}|]
upsample_trilinear3d_backward_tllbddd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CBool
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_trilinear3d_backward_tllbddd _grad_output _output_size _input_size _align_corners _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_trilinear3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(bool _align_corners)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_trilinear3d_backward_tllbdd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CBool
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_trilinear3d_backward_tllbdd _grad_output _output_size _input_size _align_corners _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_trilinear3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(bool _align_corners)
, $(double _scales_d)
, $(double _scales_h)));
}|]
upsample_trilinear3d_backward_tllb
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CBool
-> IO (Ptr Tensor)
upsample_trilinear3d_backward_tllb _grad_output _output_size _input_size _align_corners =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_trilinear3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(bool _align_corners)));
}|]
upsample_nearest1d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest1d_out_ttld _out _self _output_size _scales =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales)));
}|]
upsample_nearest1d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest1d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_upsample_nearest_exact1d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_out_ttld _out _self _output_size _scales =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales)));
}|]
_upsample_nearest_exact1d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest1d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest1d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_ upsample_nearest_exact1d_tld
-- :: Ptr Tensor
-- -> Ptr IntArray
-- -> CDouble
-- -> IO (Ptr Tensor)
-- _upsample_nearest_exact1d_tld _self _output_size _scales =
-- [C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d(
-- *$(at::Tensor* _self)
-- , *$(std::vector<int64_t>* _output_size)
-- , $(double _scales)));
-- }|]
_upsample_nearest_exact1d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest1d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest1d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales)));
}|]
upsample_nearest1d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest1d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact1d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales)));
}|]
_upsample_nearest_exact1d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
upsample_nearest1d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest1d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
-- _upsample_nearest_exact1d_backward_tlld
-- :: Ptr Tensor
-- -> Ptr IntArray
-- -> Ptr IntArray
-- -> CDouble
-- -> IO (Ptr Tensor)
-- _upsample_nearest_exact1d_backward_tlld _grad_output _output_size _input_size _scales =
-- [C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_backward(
-- *$(at::Tensor* _grad_output)
-- , *$(std::vector<int64_t>* _output_size)
-- , *$(std::vector<int64_t>* _input_size)
-- , $(double _scales)));
-- }|]
_upsample_nearest_exact1d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
upsample_nearest2d_out_ttldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_out_ttldd _out _self _output_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest2d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_out_ttld _out _self _output_size _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)));
}|]
upsample_nearest2d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest2d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_upsample_nearest_exact2d_out_ttldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_out_ttldd _out _self _output_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact2d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_out_ttld _out _self _output_size _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)));
}|]
_upsample_nearest_exact2d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest2d_tldd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_tldd _self _output_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest2d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest2d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_upsample_nearest_exact2d_tldd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_tldd _self _output_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
-- _upsample_nearest_exact2d_tld
-- :: Ptr Tensor
-- -> Ptr IntArray
-- -> CDouble
-- -> IO (Ptr Tensor)
-- _upsample_nearest_exact2d_tld _self _output_size _scales_h =
[ C.throwBlock| at::Tensor * { return new at::Tensor(at::_upsample_nearest_exact2d (
-- *$(at::Tensor* _self)
-- , *$(std::vector<int64_t>* _output_size)
-- , $(double _scales_h)));
-- }|]
_upsample_nearest_exact2d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest2d_backward_out_ttlldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_backward_out_ttlldd _grad_input _grad_output _output_size _input_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest2d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)));
}|]
upsample_nearest2d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest2d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact2d_backward_out_ttlldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_out_ttlldd _grad_input _grad_output _output_size _input_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact2d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)));
}|]
_upsample_nearest_exact2d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
upsample_nearest2d_backward_tlldd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_backward_tlldd _grad_output _output_size _input_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest2d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest2d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact2d_backward_tlldd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_tlldd _grad_output _output_size _input_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
-- _upsample_nearest_exact2d_backward_tlld
-- :: Ptr Tensor
-- -> Ptr IntArray
-- -> Ptr IntArray
-- -> CDouble
-- -> IO (Ptr Tensor)
-- _upsample_nearest_exact2d_backward_tlld _grad_output _output_size _input_size _scales_h =
-- [C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward(
-- *$(at::Tensor* _grad_output)
-- , *$(std::vector<int64_t>* _output_size)
-- , *$(std::vector<int64_t>* _input_size)
-- , $(double _scales_h)));
-- }|]
_upsample_nearest_exact2d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
upsample_nearest3d_out_ttlddd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_out_ttlddd _out _self _output_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest3d_out_ttldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_out_ttldd _out _self _output_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
upsample_nearest3d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_out_ttld _out _self _output_size _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)));
}|]
upsample_nearest3d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest3d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_upsample_nearest_exact3d_out_ttlddd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_out_ttlddd _out _self _output_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact3d_out_ttldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_out_ttldd _out _self _output_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
_upsample_nearest_exact3d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_out_ttld _out _self _output_size _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)));
}|]
_upsample_nearest_exact3d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest3d_tlddd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_tlddd _self _output_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest3d_tldd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_tldd _self _output_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
upsample_nearest3d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest3d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_upsample_nearest_exact3d_tlddd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_tlddd _self _output_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact3d_tldd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_tldd _self _output_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
-- _upsample_nearest_exact3d_tld
-- :: Ptr Tensor
-- -> Ptr IntArray
-- -> CDouble
-- -> IO (Ptr Tensor)
-- _upsample_nearest_exact3d_tld _self _output_size _scales_d =
-- [C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d(
-- *$(at::Tensor* _self)
-- , *$(std::vector<int64_t>* _output_size)
-- , $(double _scales_d)));
-- }|]
_upsample_nearest_exact3d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest3d_backward_out_ttllddd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_backward_out_ttllddd _grad_input _grad_output _output_size _input_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest3d_backward_out_ttlldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_backward_out_ttlldd _grad_input _grad_output _output_size _input_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
upsample_nearest3d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)));
}|]
upsample_nearest3d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest3d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact3d_backward_out_ttllddd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_out_ttllddd _grad_input _grad_output _output_size _input_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact3d_backward_out_ttlldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_out_ttlldd _grad_input _grad_output _output_size _input_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
_upsample_nearest_exact3d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)));
}|]
_upsample_nearest_exact3d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
upsample_nearest3d_backward_tllddd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_backward_tllddd _grad_output _output_size _input_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest3d_backward_tlldd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_backward_tlldd _grad_output _output_size _input_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
upsample_nearest3d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest3d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact3d_backward_tllddd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_tllddd _grad_output _output_size _input_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact3d_backward_tlldd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_tlldd _grad_output _output_size _input_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
-- _upsample_nearest_exact3d_backward_tlld
-- :: Ptr Tensor
-- -> Ptr IntArray
-- -> Ptr IntArray
-- -> CDouble
-- -> IO (Ptr Tensor)
-- _upsample_nearest_exact3d_backward_tlld _grad_output _output_size _input_size _scales_d =
-- [C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward(
-- *$(at::Tensor* _grad_output)
-- , *$(std::vector<int64_t>* _output_size)
-- , *$(std::vector<int64_t>* _input_size)
-- , $(double _scales_d)));
-- }|]
_upsample_nearest_exact3d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
sigmoid_backward_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
sigmoid_backward_out_ttt _grad_input _grad_output _output =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::sigmoid_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(at::Tensor* _output)));
}|]
sigmoid_backward_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
sigmoid_backward_tt _grad_output _output =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::sigmoid_backward(
*$(at::Tensor* _grad_output)
, *$(at::Tensor* _output)));
}|]
logit_backward_out_tttd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> CDouble
-> IO (Ptr Tensor)
logit_backward_out_tttd _grad_input _grad_output _self _eps =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::logit_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)
, $(double _eps)));
}|]
logit_backward_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
logit_backward_out_ttt _grad_input _grad_output _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::logit_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)));
}|]
logit_backward_ttd
:: Ptr Tensor
-> Ptr Tensor
-> CDouble
-> IO (Ptr Tensor)
logit_backward_ttd _grad_output _self _eps =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::logit_backward(
*$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)
, $(double _eps)));
}|]
logit_backward_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
logit_backward_tt _grad_output _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::logit_backward(
*$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)));
}|]
tanh_backward_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
tanh_backward_out_ttt _grad_input _grad_output _output =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::tanh_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(at::Tensor* _output)));
}|]
tanh_backward_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
tanh_backward_tt _grad_output _output =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::tanh_backward(
*$(at::Tensor* _grad_output)
, *$(at::Tensor* _output)));
}|]
slow_conv_transpose2d_out_tttltllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttltllll _out _self _weight _kernel_size _bias _stride _padding _output_padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_transpose2d_out_tttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttltlll _out _self _weight _kernel_size _bias _stride _padding _output_padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)));
}|]
slow_conv_transpose2d_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttltll _out _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_transpose2d_out_tttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttltl _out _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_transpose2d_out_tttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttlt _out _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_transpose2d_out_tttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttl _out _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv_transpose2d_ttltllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttltllll _self _weight _kernel_size _bias _stride _padding _output_padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_transpose2d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttltlll _self _weight _kernel_size _bias _stride _padding _output_padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)));
}|]
slow_conv_transpose2d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_transpose2d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_transpose2d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_transpose2d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv_transpose3d_out_tttltllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttltllll _out _self _weight _kernel_size _bias _stride _padding _output_padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_transpose3d_out_tttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttltlll _out _self _weight _kernel_size _bias _stride _padding _output_padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)));
}|]
slow_conv_transpose3d_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttltll _out _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_transpose3d_out_tttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttltl _out _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_transpose3d_out_tttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttlt _out _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_transpose3d_out_tttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttl _out _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv_transpose3d_ttltllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttltllll _self _weight _kernel_size _bias _stride _padding _output_padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_transpose3d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttltlll _self _weight _kernel_size _bias _stride _padding _output_padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)));
}|]
slow_conv_transpose3d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_transpose3d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_transpose3d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_transpose3d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
thnn_conv2d_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_out_tttltll _out _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
thnn_conv2d_out_tttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_out_tttltl _out _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
thnn_conv2d_out_tttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
thnn_conv2d_out_tttlt _out _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
thnn_conv2d_out_tttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_out_tttl _out _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
thnn_conv2d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
thnn_conv2d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
thnn_conv2d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
thnn_conv2d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
thnn_conv2d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
_slow_conv2d_forward_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_slow_conv2d_forward_out_tttltll _output _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_slow_conv2d_forward_out(
*$(at::Tensor* _output)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
_slow_conv2d_forward_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_slow_conv2d_forward_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_slow_conv2d_forward(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
_slow_conv2d_backward_out_ttttttlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr (StdTuple '(Tensor,Tensor,Tensor)))
_slow_conv2d_backward_out_ttttttlll _grad_input _grad_weight _grad_bias _grad_output _self _weight _kernel_size _stride _padding =
[C.throwBlock| std::tuple<at::Tensor,at::Tensor,at::Tensor>* { return new std::tuple<at::Tensor,at::Tensor,at::Tensor>(at::_slow_conv2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_weight)
, *$(at::Tensor* _grad_bias)
, *$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
_slow_conv2d_backward_tttllla
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr (StdArray '(CBool,3))
-> IO (Ptr (StdTuple '(Tensor,Tensor,Tensor)))
_slow_conv2d_backward_tttllla _grad_output _self _weight _kernel_size _stride _padding _output_mask =
[C.throwBlock| std::tuple<at::Tensor,at::Tensor,at::Tensor>* { return new std::tuple<at::Tensor,at::Tensor,at::Tensor>(at::_slow_conv2d_backward(
*$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::array<bool,3>* _output_mask)));
}|]
_conv_depthwise2d_out_tttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_conv_depthwise2d_out_tttltlll _out _self _weight _kernel_size _bias _stride _padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_conv_depthwise2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
_conv_depthwise2d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_conv_depthwise2d_ttltlll _self _weight _kernel_size _bias _stride _padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_conv_depthwise2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
conv_depthwise3d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
conv_depthwise3d_ttltlll _self _weight _kernel_size _bias _stride _padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::conv_depthwise3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv3d_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_out_tttltll _out _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv3d_out_tttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_out_tttltl _out _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv3d_out_tttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv3d_out_tttlt _out _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv3d_out_tttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_out_tttl _out _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv3d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv3d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv3d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv3d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv3d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv3d_forward_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_forward_out_tttltll _output _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_forward_out(
*$(at::Tensor* _output)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv3d_forward_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_forward_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_forward(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_dilated2d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated2d_ttltlll _self _weight _kernel_size _bias _stride _padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_dilated2d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated2d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_dilated2d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated2d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_dilated2d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_dilated2d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_dilated2d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated2d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv_dilated3d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated3d_ttltlll _self _weight _kernel_size _bias _stride _padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_dilated3d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated3d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_dilated3d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated3d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_dilated3d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_dilated3d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_dilated3d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated3d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
col2im_out_ttlllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
col2im_out_ttlllll _out _self _output_size _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::col2im_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
col2im_tlllll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
col2im_tlllll _self _output_size _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::col2im(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
col2im_backward_out_ttllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
col2im_backward_out_ttllll _grad_input _grad_output _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::col2im_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
col2im_backward_tllll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
col2im_backward_tllll _grad_output _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::col2im_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
column_stack_l
:: Ptr TensorList
-> IO (Ptr Tensor)
column_stack_l _tensors =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::column_stack(
*$(std::vector<at::Tensor>* _tensors)));
}|]
column_stack_out_tl
:: Ptr Tensor
-> Ptr TensorList
-> IO (Ptr Tensor)
column_stack_out_tl _out _tensors =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::column_stack_out(
*$(at::Tensor* _out)
, *$(std::vector<at::Tensor>* _tensors)));
}|]
im2col_out_ttllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
im2col_out_ttllll _out _self _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::im2col_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
im2col_tllll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
im2col_tllll _self _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::im2col(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
im2col_backward_out_ttlllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
im2col_backward_out_ttlllll _grad_input _grad_output _input_size _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::im2col_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _input_size)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
im2col_backward_tlllll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
im2col_backward_tlllll _grad_output _input_size _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::im2col_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _input_size)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
isfinite_t
:: Ptr Tensor
-> IO (Ptr Tensor)
isfinite_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isfinite(
*$(at::Tensor* _self)));
}|]
isinf_t
:: Ptr Tensor
-> IO (Ptr Tensor)
isinf_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isinf(
*$(at::Tensor* _self)));
}|]
isposinf_t
:: Ptr Tensor
-> IO (Ptr Tensor)
isposinf_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isposinf(
*$(at::Tensor* _self)));
}|]
isposinf_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
isposinf_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isposinf_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
isneginf_t
:: Ptr Tensor
-> IO (Ptr Tensor)
isneginf_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isneginf(
*$(at::Tensor* _self)));
}|]
isneginf_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
isneginf_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isneginf_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
_add_batch_dim_tll
:: Ptr Tensor
-> Int64
-> Int64
-> IO (Ptr Tensor)
_add_batch_dim_tll _self _batch_dim _level =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_add_batch_dim(
*$(at::Tensor* _self)
, $(int64_t _batch_dim)
, $(int64_t _level)));
}|]
_remove_batch_dim_tlll
:: Ptr Tensor
-> Int64
-> Int64
-> Int64
-> IO (Ptr Tensor)
_remove_batch_dim_tlll _self _level _batch_size _out_dim =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_remove_batch_dim(
*$(at::Tensor* _self)
, $(int64_t _level)
, $(int64_t _batch_size)
, $(int64_t _out_dim)));
}|]
special_entr_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_entr_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_entr(
*$(at::Tensor* _self)));
}|]
special_entr_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_entr_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_entr_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_ndtri_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_ndtri_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_ndtri(
*$(at::Tensor* _self)));
}|]
special_ndtri_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_ndtri_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_ndtri_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_expm1_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_expm1_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_expm1(
*$(at::Tensor* _self)));
}|]
special_expm1_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_expm1_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_expm1_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_exp2_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_exp2_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_exp2(
*$(at::Tensor* _self)));
}|]
special_exp2_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_exp2_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_exp2_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_psi_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_psi_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_psi(
*$(at::Tensor* _self)));
}|]
special_psi_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_psi_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_psi_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_digamma_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_digamma_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_digamma(
*$(at::Tensor* _self)));
}|]
special_digamma_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_digamma_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_digamma_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_gammaln_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_gammaln_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_gammaln(
*$(at::Tensor* _self)));
}|]
special_gammaln_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_gammaln_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_gammaln_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_erf_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_erf_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erf(
*$(at::Tensor* _self)));
}|]
special_erf_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_erf_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erf_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_erfc_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_erfc_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfc(
*$(at::Tensor* _self)));
}|]
special_erfc_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_erfc_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfc_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_erfcx_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_erfcx_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfcx(
*$(at::Tensor* _self)));
}|]
special_erfcx_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_erfcx_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfcx_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_erfinv_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_erfinv_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfinv(
*$(at::Tensor* _self)));
}|]
special_erfinv_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_erfinv_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfinv_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_ndtr_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_ndtr_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_ndtr(
*$(at::Tensor* _self)));
}|]
special_ndtr_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_ndtr_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_ndtr_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_xlog1py_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlog1py_tt _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py(
*$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_xlog1py_st
:: Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlog1py_st _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py(
*$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_xlog1py_ts
:: Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_xlog1py_ts _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py(
*$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_xlog1py_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlog1py_out_ttt _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_xlog1py_out_tst
:: Ptr Tensor
-> Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlog1py_out_tst _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py_out(
*$(at::Tensor* _out)
, *$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_xlog1py_out_tts
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_xlog1py_out_tts _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_xlogy_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlogy_tt _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy(
*$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_xlogy_st
:: Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlogy_st _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy(
*$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_xlogy_ts
:: Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_xlogy_ts _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy(
*$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_xlogy_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlogy_out_ttt _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_xlogy_out_tst
:: Ptr Tensor
-> Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlogy_out_tst _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy_out(
*$(at::Tensor* _out)
, *$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_xlogy_out_tts
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_xlogy_out_tts _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_zeta_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_zeta_tt _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta(
*$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_zeta_st
:: Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_zeta_st _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta(
*$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_zeta_ts
:: Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_zeta_ts _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta(
*$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_zeta_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_zeta_out_ttt _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_zeta_out_tst
:: Ptr Tensor
-> Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_zeta_out_tst _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta_out(
*$(at::Tensor* _out)
, *$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_zeta_out_tts
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_zeta_out_tts _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_i0_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_i0_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i0(
*$(at::Tensor* _self)));
}|]
special_i0_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_i0_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i0_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_i0e_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_i0e_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i0e(
*$(at::Tensor* _self)));
}|]
special_i0e_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_i0e_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i0e_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_i1_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_i1_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i1(
*$(at::Tensor* _self)));
}|]
special_i1_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_i1_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i1_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_i1e_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_i1e_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i1e(
*$(at::Tensor* _self)));
}|]
special_i1e_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_i1e_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i1e_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_logit_td
:: Ptr Tensor
-> CDouble
-> IO (Ptr Tensor)
special_logit_td _self _eps =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_logit(
*$(at::Tensor* _self)
, $(double _eps)));
}|]
| null | https://raw.githubusercontent.com/hasktorch/hasktorch/6233c173e1dd9fd7218fd13b104da15fc457f67e/libtorch-ffi/src/Torch/Internal/Unmanaged/Native/Native13.hs | haskell | generated by using spec/Declarations.yaml
# LANGUAGE OverloadedStrings #
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_tld _self _output_size _scales =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales)));
}|]
_upsample_nearest_exact1d_backward_tlld
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_backward_tlld _grad_output _output_size _input_size _scales =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales)));
}|]
_upsample_nearest_exact2d_tld
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_tld _self _output_size _scales_h =
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)));
}|]
_upsample_nearest_exact2d_backward_tlld
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_tlld _grad_output _output_size _input_size _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)));
}|]
_upsample_nearest_exact3d_tld
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_tld _self _output_size _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)));
}|]
_upsample_nearest_exact3d_backward_tlld
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_tlld _grad_output _output_size _input_size _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)));
}|] |
# LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
# LANGUAGE TemplateHaskell #
# LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
module Torch.Internal.Unmanaged.Native.Native13 where
import Foreign.C.String
import Foreign.C.Types
import Foreign
import Torch.Internal.Type
import qualified Language.C.Inline.Cpp as C
import qualified Language.C.Inline.Cpp.Unsafe as C
import qualified Language.C.Inline.Context as C
import qualified Language.C.Types as C
C.context $ C.cppCtx <> mempty { C.ctxTypesTable = typeTable }
C.include "<vector>"
C.include "<ATen/Tensor.h>"
C.include "<ATen/Functions.h>"
upsample_trilinear3d_backward_out_ttllbd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CBool
-> CDouble
-> IO (Ptr Tensor)
upsample_trilinear3d_backward_out_ttllbd _grad_input _grad_output _output_size _input_size _align_corners _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_trilinear3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(bool _align_corners)
, $(double _scales_d)));
}|]
upsample_trilinear3d_backward_out_ttllb
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CBool
-> IO (Ptr Tensor)
upsample_trilinear3d_backward_out_ttllb _grad_input _grad_output _output_size _input_size _align_corners =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_trilinear3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(bool _align_corners)));
}|]
upsample_trilinear3d_backward_tllbddd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CBool
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_trilinear3d_backward_tllbddd _grad_output _output_size _input_size _align_corners _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_trilinear3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(bool _align_corners)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_trilinear3d_backward_tllbdd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CBool
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_trilinear3d_backward_tllbdd _grad_output _output_size _input_size _align_corners _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_trilinear3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(bool _align_corners)
, $(double _scales_d)
, $(double _scales_h)));
}|]
upsample_trilinear3d_backward_tllb
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CBool
-> IO (Ptr Tensor)
upsample_trilinear3d_backward_tllb _grad_output _output_size _input_size _align_corners =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_trilinear3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(bool _align_corners)));
}|]
upsample_nearest1d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest1d_out_ttld _out _self _output_size _scales =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales)));
}|]
upsample_nearest1d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest1d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_upsample_nearest_exact1d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_out_ttld _out _self _output_size _scales =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales)));
}|]
_upsample_nearest_exact1d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest1d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest1d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_ upsample_nearest_exact1d_tld
_upsample_nearest_exact1d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest1d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest1d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales)));
}|]
upsample_nearest1d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest1d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact1d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales)));
}|]
_upsample_nearest_exact1d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
upsample_nearest1d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest1d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest1d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact1d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact1d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact1d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
upsample_nearest2d_out_ttldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_out_ttldd _out _self _output_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest2d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_out_ttld _out _self _output_size _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)));
}|]
upsample_nearest2d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest2d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_upsample_nearest_exact2d_out_ttldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_out_ttldd _out _self _output_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact2d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_out_ttld _out _self _output_size _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)));
}|]
_upsample_nearest_exact2d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest2d_tldd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_tldd _self _output_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest2d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest2d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_upsample_nearest_exact2d_tldd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_tldd _self _output_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
[ C.throwBlock| at::Tensor * { return new at::Tensor(at::_upsample_nearest_exact2d (
_upsample_nearest_exact2d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest2d_backward_out_ttlldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_backward_out_ttlldd _grad_input _grad_output _output_size _input_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest2d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)));
}|]
upsample_nearest2d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest2d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact2d_backward_out_ttlldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_out_ttlldd _grad_input _grad_output _output_size _input_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact2d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)));
}|]
_upsample_nearest_exact2d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
upsample_nearest2d_backward_tlldd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest2d_backward_tlldd _grad_output _output_size _input_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest2d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest2d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest2d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact2d_backward_tlldd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_tlldd _grad_output _output_size _input_size _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact2d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact2d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact2d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
upsample_nearest3d_out_ttlddd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_out_ttlddd _out _self _output_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest3d_out_ttldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_out_ttldd _out _self _output_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
upsample_nearest3d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_out_ttld _out _self _output_size _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)));
}|]
upsample_nearest3d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest3d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_upsample_nearest_exact3d_out_ttlddd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_out_ttlddd _out _self _output_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact3d_out_ttldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_out_ttldd _out _self _output_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
_upsample_nearest_exact3d_out_ttld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_out_ttld _out _self _output_size _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)));
}|]
_upsample_nearest_exact3d_out_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_out_ttl _out _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest3d_tlddd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_tlddd _self _output_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest3d_tldd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_tldd _self _output_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
upsample_nearest3d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest3d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
_upsample_nearest_exact3d_tlddd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_tlddd _self _output_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact3d_tldd
:: Ptr Tensor
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_tldd _self _output_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
_upsample_nearest_exact3d_tl
:: Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_tl _self _output_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)));
}|]
upsample_nearest3d_backward_out_ttllddd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_backward_out_ttllddd _grad_input _grad_output _output_size _input_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest3d_backward_out_ttlldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_backward_out_ttlldd _grad_input _grad_output _output_size _input_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
upsample_nearest3d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)));
}|]
upsample_nearest3d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest3d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact3d_backward_out_ttllddd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_out_ttllddd _grad_input _grad_output _output_size _input_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact3d_backward_out_ttlldd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_out_ttlldd _grad_input _grad_output _output_size _input_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
_upsample_nearest_exact3d_backward_out_ttlld
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_out_ttlld _grad_input _grad_output _output_size _input_size _scales_d =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)));
}|]
_upsample_nearest_exact3d_backward_out_ttll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_out_ttll _grad_input _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
upsample_nearest3d_backward_tllddd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_backward_tllddd _grad_output _output_size _input_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
upsample_nearest3d_backward_tlldd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
upsample_nearest3d_backward_tlldd _grad_output _output_size _input_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
upsample_nearest3d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
upsample_nearest3d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::upsample_nearest3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
_upsample_nearest_exact3d_backward_tllddd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_tllddd _grad_output _output_size _input_size _scales_d _scales_h _scales_w =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)
, $(double _scales_w)));
}|]
_upsample_nearest_exact3d_backward_tlldd
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> CDouble
-> CDouble
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_tlldd _grad_output _output_size _input_size _scales_d _scales_h =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)
, $(double _scales_d)
, $(double _scales_h)));
}|]
_upsample_nearest_exact3d_backward_tll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_upsample_nearest_exact3d_backward_tll _grad_output _output_size _input_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_upsample_nearest_exact3d_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _input_size)));
}|]
sigmoid_backward_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
sigmoid_backward_out_ttt _grad_input _grad_output _output =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::sigmoid_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(at::Tensor* _output)));
}|]
sigmoid_backward_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
sigmoid_backward_tt _grad_output _output =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::sigmoid_backward(
*$(at::Tensor* _grad_output)
, *$(at::Tensor* _output)));
}|]
logit_backward_out_tttd
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> CDouble
-> IO (Ptr Tensor)
logit_backward_out_tttd _grad_input _grad_output _self _eps =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::logit_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)
, $(double _eps)));
}|]
logit_backward_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
logit_backward_out_ttt _grad_input _grad_output _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::logit_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)));
}|]
logit_backward_ttd
:: Ptr Tensor
-> Ptr Tensor
-> CDouble
-> IO (Ptr Tensor)
logit_backward_ttd _grad_output _self _eps =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::logit_backward(
*$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)
, $(double _eps)));
}|]
logit_backward_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
logit_backward_tt _grad_output _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::logit_backward(
*$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)));
}|]
tanh_backward_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
tanh_backward_out_ttt _grad_input _grad_output _output =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::tanh_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(at::Tensor* _output)));
}|]
tanh_backward_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
tanh_backward_tt _grad_output _output =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::tanh_backward(
*$(at::Tensor* _grad_output)
, *$(at::Tensor* _output)));
}|]
slow_conv_transpose2d_out_tttltllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttltllll _out _self _weight _kernel_size _bias _stride _padding _output_padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_transpose2d_out_tttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttltlll _out _self _weight _kernel_size _bias _stride _padding _output_padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)));
}|]
slow_conv_transpose2d_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttltll _out _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_transpose2d_out_tttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttltl _out _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_transpose2d_out_tttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttlt _out _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_transpose2d_out_tttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_out_tttl _out _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv_transpose2d_ttltllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttltllll _self _weight _kernel_size _bias _stride _padding _output_padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_transpose2d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttltlll _self _weight _kernel_size _bias _stride _padding _output_padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)));
}|]
slow_conv_transpose2d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_transpose2d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_transpose2d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_transpose2d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose2d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv_transpose3d_out_tttltllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttltllll _out _self _weight _kernel_size _bias _stride _padding _output_padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_transpose3d_out_tttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttltlll _out _self _weight _kernel_size _bias _stride _padding _output_padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)));
}|]
slow_conv_transpose3d_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttltll _out _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_transpose3d_out_tttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttltl _out _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_transpose3d_out_tttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttlt _out _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_transpose3d_out_tttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_out_tttl _out _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv_transpose3d_ttltllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttltllll _self _weight _kernel_size _bias _stride _padding _output_padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_transpose3d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttltlll _self _weight _kernel_size _bias _stride _padding _output_padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _output_padding)));
}|]
slow_conv_transpose3d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_transpose3d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_transpose3d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_transpose3d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_transpose3d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_transpose3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
thnn_conv2d_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_out_tttltll _out _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
thnn_conv2d_out_tttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_out_tttltl _out _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
thnn_conv2d_out_tttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
thnn_conv2d_out_tttlt _out _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
thnn_conv2d_out_tttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_out_tttl _out _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
thnn_conv2d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
thnn_conv2d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
thnn_conv2d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
thnn_conv2d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
thnn_conv2d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
thnn_conv2d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::thnn_conv2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
_slow_conv2d_forward_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_slow_conv2d_forward_out_tttltll _output _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_slow_conv2d_forward_out(
*$(at::Tensor* _output)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
_slow_conv2d_forward_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_slow_conv2d_forward_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_slow_conv2d_forward(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
_slow_conv2d_backward_out_ttttttlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr (StdTuple '(Tensor,Tensor,Tensor)))
_slow_conv2d_backward_out_ttttttlll _grad_input _grad_weight _grad_bias _grad_output _self _weight _kernel_size _stride _padding =
[C.throwBlock| std::tuple<at::Tensor,at::Tensor,at::Tensor>* { return new std::tuple<at::Tensor,at::Tensor,at::Tensor>(at::_slow_conv2d_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_weight)
, *$(at::Tensor* _grad_bias)
, *$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
_slow_conv2d_backward_tttllla
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr (StdArray '(CBool,3))
-> IO (Ptr (StdTuple '(Tensor,Tensor,Tensor)))
_slow_conv2d_backward_tttllla _grad_output _self _weight _kernel_size _stride _padding _output_mask =
[C.throwBlock| std::tuple<at::Tensor,at::Tensor,at::Tensor>* { return new std::tuple<at::Tensor,at::Tensor,at::Tensor>(at::_slow_conv2d_backward(
*$(at::Tensor* _grad_output)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::array<bool,3>* _output_mask)));
}|]
_conv_depthwise2d_out_tttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_conv_depthwise2d_out_tttltlll _out _self _weight _kernel_size _bias _stride _padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_conv_depthwise2d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
_conv_depthwise2d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
_conv_depthwise2d_ttltlll _self _weight _kernel_size _bias _stride _padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_conv_depthwise2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
conv_depthwise3d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
conv_depthwise3d_ttltlll _self _weight _kernel_size _bias _stride _padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::conv_depthwise3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv3d_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_out_tttltll _out _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv3d_out_tttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_out_tttltl _out _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv3d_out_tttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv3d_out_tttlt _out _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv3d_out_tttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_out_tttl _out _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv3d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv3d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv3d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv3d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv3d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv3d_forward_out_tttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_forward_out_tttltll _output _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_forward_out(
*$(at::Tensor* _output)
, *$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv3d_forward_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv3d_forward_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv3d_forward(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_dilated2d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated2d_ttltlll _self _weight _kernel_size _bias _stride _padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_dilated2d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated2d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_dilated2d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated2d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_dilated2d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_dilated2d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_dilated2d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated2d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated2d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
slow_conv_dilated3d_ttltlll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated3d_ttltlll _self _weight _kernel_size _bias _stride _padding _dilation =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _dilation)));
}|]
slow_conv_dilated3d_ttltll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated3d_ttltll _self _weight _kernel_size _bias _stride _padding =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)
, *$(std::vector<int64_t>* _padding)));
}|]
slow_conv_dilated3d_ttltl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated3d_ttltl _self _weight _kernel_size _bias _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)
, *$(std::vector<int64_t>* _stride)));
}|]
slow_conv_dilated3d_ttlt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr Tensor
-> IO (Ptr Tensor)
slow_conv_dilated3d_ttlt _self _weight _kernel_size _bias =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)
, *$(at::Tensor* _bias)));
}|]
slow_conv_dilated3d_ttl
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> IO (Ptr Tensor)
slow_conv_dilated3d_ttl _self _weight _kernel_size =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::slow_conv_dilated3d(
*$(at::Tensor* _self)
, *$(at::Tensor* _weight)
, *$(std::vector<int64_t>* _kernel_size)));
}|]
col2im_out_ttlllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
col2im_out_ttlllll _out _self _output_size _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::col2im_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
col2im_tlllll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
col2im_tlllll _self _output_size _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::col2im(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _output_size)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
col2im_backward_out_ttllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
col2im_backward_out_ttllll _grad_input _grad_output _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::col2im_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
col2im_backward_tllll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
col2im_backward_tllll _grad_output _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::col2im_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
column_stack_l
:: Ptr TensorList
-> IO (Ptr Tensor)
column_stack_l _tensors =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::column_stack(
*$(std::vector<at::Tensor>* _tensors)));
}|]
column_stack_out_tl
:: Ptr Tensor
-> Ptr TensorList
-> IO (Ptr Tensor)
column_stack_out_tl _out _tensors =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::column_stack_out(
*$(at::Tensor* _out)
, *$(std::vector<at::Tensor>* _tensors)));
}|]
im2col_out_ttllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
im2col_out_ttllll _out _self _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::im2col_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
im2col_tllll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
im2col_tllll _self _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::im2col(
*$(at::Tensor* _self)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
im2col_backward_out_ttlllll
:: Ptr Tensor
-> Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
im2col_backward_out_ttlllll _grad_input _grad_output _input_size _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::im2col_backward_out(
*$(at::Tensor* _grad_input)
, *$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _input_size)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
im2col_backward_tlllll
:: Ptr Tensor
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> Ptr IntArray
-> IO (Ptr Tensor)
im2col_backward_tlllll _grad_output _input_size _kernel_size _dilation _padding _stride =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::im2col_backward(
*$(at::Tensor* _grad_output)
, *$(std::vector<int64_t>* _input_size)
, *$(std::vector<int64_t>* _kernel_size)
, *$(std::vector<int64_t>* _dilation)
, *$(std::vector<int64_t>* _padding)
, *$(std::vector<int64_t>* _stride)));
}|]
isfinite_t
:: Ptr Tensor
-> IO (Ptr Tensor)
isfinite_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isfinite(
*$(at::Tensor* _self)));
}|]
isinf_t
:: Ptr Tensor
-> IO (Ptr Tensor)
isinf_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isinf(
*$(at::Tensor* _self)));
}|]
isposinf_t
:: Ptr Tensor
-> IO (Ptr Tensor)
isposinf_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isposinf(
*$(at::Tensor* _self)));
}|]
isposinf_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
isposinf_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isposinf_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
isneginf_t
:: Ptr Tensor
-> IO (Ptr Tensor)
isneginf_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isneginf(
*$(at::Tensor* _self)));
}|]
isneginf_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
isneginf_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::isneginf_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
_add_batch_dim_tll
:: Ptr Tensor
-> Int64
-> Int64
-> IO (Ptr Tensor)
_add_batch_dim_tll _self _batch_dim _level =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_add_batch_dim(
*$(at::Tensor* _self)
, $(int64_t _batch_dim)
, $(int64_t _level)));
}|]
_remove_batch_dim_tlll
:: Ptr Tensor
-> Int64
-> Int64
-> Int64
-> IO (Ptr Tensor)
_remove_batch_dim_tlll _self _level _batch_size _out_dim =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::_remove_batch_dim(
*$(at::Tensor* _self)
, $(int64_t _level)
, $(int64_t _batch_size)
, $(int64_t _out_dim)));
}|]
special_entr_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_entr_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_entr(
*$(at::Tensor* _self)));
}|]
special_entr_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_entr_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_entr_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_ndtri_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_ndtri_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_ndtri(
*$(at::Tensor* _self)));
}|]
special_ndtri_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_ndtri_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_ndtri_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_expm1_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_expm1_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_expm1(
*$(at::Tensor* _self)));
}|]
special_expm1_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_expm1_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_expm1_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_exp2_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_exp2_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_exp2(
*$(at::Tensor* _self)));
}|]
special_exp2_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_exp2_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_exp2_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_psi_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_psi_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_psi(
*$(at::Tensor* _self)));
}|]
special_psi_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_psi_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_psi_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_digamma_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_digamma_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_digamma(
*$(at::Tensor* _self)));
}|]
special_digamma_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_digamma_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_digamma_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_gammaln_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_gammaln_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_gammaln(
*$(at::Tensor* _self)));
}|]
special_gammaln_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_gammaln_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_gammaln_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_erf_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_erf_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erf(
*$(at::Tensor* _self)));
}|]
special_erf_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_erf_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erf_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_erfc_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_erfc_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfc(
*$(at::Tensor* _self)));
}|]
special_erfc_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_erfc_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfc_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_erfcx_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_erfcx_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfcx(
*$(at::Tensor* _self)));
}|]
special_erfcx_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_erfcx_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfcx_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_erfinv_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_erfinv_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfinv(
*$(at::Tensor* _self)));
}|]
special_erfinv_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_erfinv_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_erfinv_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_ndtr_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_ndtr_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_ndtr(
*$(at::Tensor* _self)));
}|]
special_ndtr_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_ndtr_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_ndtr_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_xlog1py_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlog1py_tt _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py(
*$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_xlog1py_st
:: Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlog1py_st _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py(
*$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_xlog1py_ts
:: Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_xlog1py_ts _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py(
*$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_xlog1py_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlog1py_out_ttt _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_xlog1py_out_tst
:: Ptr Tensor
-> Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlog1py_out_tst _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py_out(
*$(at::Tensor* _out)
, *$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_xlog1py_out_tts
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_xlog1py_out_tts _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlog1py_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_xlogy_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlogy_tt _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy(
*$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_xlogy_st
:: Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlogy_st _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy(
*$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_xlogy_ts
:: Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_xlogy_ts _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy(
*$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_xlogy_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlogy_out_ttt _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_xlogy_out_tst
:: Ptr Tensor
-> Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_xlogy_out_tst _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy_out(
*$(at::Tensor* _out)
, *$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_xlogy_out_tts
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_xlogy_out_tts _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_xlogy_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_zeta_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_zeta_tt _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta(
*$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_zeta_st
:: Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_zeta_st _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta(
*$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_zeta_ts
:: Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_zeta_ts _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta(
*$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_zeta_out_ttt
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_zeta_out_ttt _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Tensor* _other)));
}|]
special_zeta_out_tst
:: Ptr Tensor
-> Ptr Scalar
-> Ptr Tensor
-> IO (Ptr Tensor)
special_zeta_out_tst _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta_out(
*$(at::Tensor* _out)
, *$(at::Scalar* _self)
, *$(at::Tensor* _other)));
}|]
special_zeta_out_tts
:: Ptr Tensor
-> Ptr Tensor
-> Ptr Scalar
-> IO (Ptr Tensor)
special_zeta_out_tts _out _self _other =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_zeta_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)
, *$(at::Scalar* _other)));
}|]
special_i0_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_i0_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i0(
*$(at::Tensor* _self)));
}|]
special_i0_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_i0_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i0_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_i0e_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_i0e_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i0e(
*$(at::Tensor* _self)));
}|]
special_i0e_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_i0e_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i0e_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_i1_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_i1_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i1(
*$(at::Tensor* _self)));
}|]
special_i1_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_i1_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i1_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_i1e_t
:: Ptr Tensor
-> IO (Ptr Tensor)
special_i1e_t _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i1e(
*$(at::Tensor* _self)));
}|]
special_i1e_out_tt
:: Ptr Tensor
-> Ptr Tensor
-> IO (Ptr Tensor)
special_i1e_out_tt _out _self =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_i1e_out(
*$(at::Tensor* _out)
, *$(at::Tensor* _self)));
}|]
special_logit_td
:: Ptr Tensor
-> CDouble
-> IO (Ptr Tensor)
special_logit_td _self _eps =
[C.throwBlock| at::Tensor* { return new at::Tensor(at::special_logit(
*$(at::Tensor* _self)
, $(double _eps)));
}|]
|
18209c0b50396f307d41d3dc08d15d0d9f2c71da35104e515e03e4069b47f9ea | cark/cark.behavior-tree | sequence.cljc | (ns cark.behavior-tree.node-defs.sequence
"The :sequence function succeeds when all its children succeed and fails when any of these fails."
(:require [cark.behavior-tree.context :as ctx]
[cark.behavior-tree.db :as db]
[cark.behavior-tree.tree :as tree]
[cark.behavior-tree.type :as type]
[cark.behavior-tree.base-nodes :as bn]))
(defn compile-node [tree id tag params children-ids]
[(fn sequence-tick [ctx arg]
(case (db/get-node-status ctx id)
:fresh (recur (db/set-node-status ctx id :running) arg)
:running (loop [ctx ctx
i 0]
(if-let [child-id (get children-ids i)]
(case (db/get-node-status ctx child-id)
:success (recur ctx (inc i))
(:fresh :running) (let [ctx (ctx/tick ctx child-id)]
(case (db/get-node-status ctx child-id)
:success (recur ctx (inc i))
:failure (-> (db/set-node-status ctx id :failure)
(ctx/reset-nodes (take (inc i) children-ids)))
:running ctx)))
(-> (db/set-node-status ctx id :success)
(ctx/reset-nodes (take (inc i) children-ids)))))))
tree])
(defn register []
(type/register
(bn/branch
{::type/tag :sequence
::type/compile-func compile-node})))
| null | https://raw.githubusercontent.com/cark/cark.behavior-tree/4e229fcc2ed3af3c66e74d2c51dda6684927d254/src/main/cark/behavior_tree/node_defs/sequence.cljc | clojure | (ns cark.behavior-tree.node-defs.sequence
"The :sequence function succeeds when all its children succeed and fails when any of these fails."
(:require [cark.behavior-tree.context :as ctx]
[cark.behavior-tree.db :as db]
[cark.behavior-tree.tree :as tree]
[cark.behavior-tree.type :as type]
[cark.behavior-tree.base-nodes :as bn]))
(defn compile-node [tree id tag params children-ids]
[(fn sequence-tick [ctx arg]
(case (db/get-node-status ctx id)
:fresh (recur (db/set-node-status ctx id :running) arg)
:running (loop [ctx ctx
i 0]
(if-let [child-id (get children-ids i)]
(case (db/get-node-status ctx child-id)
:success (recur ctx (inc i))
(:fresh :running) (let [ctx (ctx/tick ctx child-id)]
(case (db/get-node-status ctx child-id)
:success (recur ctx (inc i))
:failure (-> (db/set-node-status ctx id :failure)
(ctx/reset-nodes (take (inc i) children-ids)))
:running ctx)))
(-> (db/set-node-status ctx id :success)
(ctx/reset-nodes (take (inc i) children-ids)))))))
tree])
(defn register []
(type/register
(bn/branch
{::type/tag :sequence
::type/compile-func compile-node})))
| |
cc6e1ff46ea877dfcf73f6f2d2146ac11d52856c5392849edbbb83daecf77d18 | Vigilans/hscc | Utils.hs | module Language.C.Syntax.Utils where
import Language.C.Syntax
import Data.Either
-- Type
type TypeInfo = Either (Type -> Type) Type
void :: Type
void = Void
bool :: Type
bool = Integer Bool Unsigned
char :: Type
char = Integer Char Unsigned
short :: Type
short = Integer Short Signed
int :: Type
int = Integer Int Signed
long :: Type
long = Integer Long Signed
half :: Type
half = Floating Half
float :: Type
float = Floating Float
double :: Type
double = Floating Double
stringType :: String -> Type
stringType s = Array char (fromIntegral $ length s)
computeType :: [TypeInfo] -> Type
computeType infos
| length primitives > 1 = error "More than one primitive type"
| otherwise = foldr1 (.) (specifiers ++ primitives) Unknown -- Deduce start from never
where
specifiers = lefts infos
primitives = const <$> rights infos
| null | https://raw.githubusercontent.com/Vigilans/hscc/d612c54f9263d90fb01673aea1820a62fdf62551/src/Language/C/Syntax/Utils.hs | haskell | Type
Deduce start from never | module Language.C.Syntax.Utils where
import Language.C.Syntax
import Data.Either
type TypeInfo = Either (Type -> Type) Type
void :: Type
void = Void
bool :: Type
bool = Integer Bool Unsigned
char :: Type
char = Integer Char Unsigned
short :: Type
short = Integer Short Signed
int :: Type
int = Integer Int Signed
long :: Type
long = Integer Long Signed
half :: Type
half = Floating Half
float :: Type
float = Floating Float
double :: Type
double = Floating Double
stringType :: String -> Type
stringType s = Array char (fromIntegral $ length s)
computeType :: [TypeInfo] -> Type
computeType infos
| length primitives > 1 = error "More than one primitive type"
where
specifiers = lefts infos
primitives = const <$> rights infos
|
453876410808a3c79b45d2101b7512274048cd3fc0ed11a3495bd13c0bc60221 | WormBase/wormbase_rest | associations.clj | (ns rest-api.classes.anatomy-term.widgets.associations
(:require
[clojure.string :as str]
[datomic.api :as d]
[pseudoace.utils :as pace-utils]
[rest-api.formatters.object :as obj :refer [pack-obj]]
[rest-api.classes.generic-functions :as generic-functions]
[rest-api.classes.generic-fields :as generic]))
(defn transgenes [a]
{:data nil ; can't find any
:description "transgenes annotated with this anatomy_term"})
(defn gene-ontology [a]
{:data (let [db (d/entity-db a)]
(->> (d/q '[:find ?gt ?paper
:in $ ?at
:where
[?at :anatomy-term/go-term ?gh]
[?gh :anatomy-term.go-term/go-term ?gt]
[?gh :evidence/paper-evidence ?paper]]
db
(:db/id a))
(group-by first)
(map (fn [[go-term-id tuples]]
(let [go-term (d/entity db go-term-id)]
{:term (pack-obj go-term)
:reference (->> tuples
(map (fn [[_ paper-id]]
(->> (d/entity db paper-id)
(pack-obj))))
(seq))})))
(seq)))
:description "go_terms associated with this anatomy_term"})
(defn- anatomy-function [a bool]
(let [afhs (if (= bool true)
(:anatomy-function.involved/_anatomy-term a)
(:anatomy-function.not-involved/_anatomy-term a))]
(for [afh afhs
:let [af (if (= bool true)
(:anatomy-function/_involved afh)
(:anatomy-function/_not-involved afh))]]
{:gene (when-let [gh (:anatomy-function/gene af)]
(pack-obj (:anatomy-function.gene/gene gh)))
:reference (when-let [reference (:anatomy-function/reference af)]
(pack-obj reference))
:af_data (:anatomy-function/id af)
:bp_inv (when-let [hs (:anatomy-function/involved af)]
(for [h hs]
{:text (:anatomy-term.term/text
(:anatomy-term/term
(:anatomy-function.involved/anatomy-term h)))
:evidence (obj/get-evidence h)}))
:bp_not_inv (when-let [hs (:anatomy-function/not-involved af)]
(for [h hs]
{:text (:anatomy-term.term/text
(:anatomy-term/term
(:anatomy-function.not-involved/anatomy-term h)))
:evidence (obj/get-evidence h)}))
:phenotype (when-let [ph (:anatomy-function/phenotype af)]
(let [phenotype (:anatomy-function.phenotype/phenotype ph)]
(if-let [evidence (obj/get-evidence ph)]
{:text (pack-obj phenotype)
:evidence evidence}
(pack-obj phenotype))))
:assay (when-let [hs (:anatomy-function/assay af)]
(for [h hs]
{:text (:ao-code/id (:anatomy-function.assay/ao-code h))
:evidence (when-let [genotypes (:condition/genotype
(:anatomy-function.assay/condition h))]
{:genotype (str/join "<br /> " genotypes)})}))})))
(defn anatomy-functions [a]
{:data (anatomy-function a true)
:description "anatomy_functions associatated with this anatomy_term"})
(defn anatomy-function-nots [a]
{:data (anatomy-function a false)
:description "anatomy_functions associatated with this anatomy_term"})
(defn expression-clusters [a]
{:data (when-let [hs (:expression-cluster.anatomy-term/_anatomy-term a)]
(for [h hs
:let [ec (:expression-cluster/_anatomy-term h)]]
{:description (first (:expression-cluster/description ec))
:expression_cluster (pack-obj ec)}))
:description "expression cluster data"})
(defn expression-patterns [a]
{:data (when-let [hs (:expr-pattern.anatomy-term/_anatomy-term a)]
(for [h hs
:let [ep (:expr-pattern/_anatomy-term h)]]
{:description (when-let [patterns (:expr-pattern/pattern ep)]
(str/join "<br /> " patterns))
:expression_pattern (pack-obj ep)
:certainty (generic-functions/certainty h)
:reference (when-let [hs (:expr-pattern/reference ep)]
(let [paper (:expr-pattern.reference/paper (first hs))]
(:paper/id paper)))
:gene (when-let [g (:expr-pattern/gene ep)]
(pack-obj (:expr-pattern.gene/gene (first g))))
:author (when-let [a (:expr-pattern/author ep)]
(map pack-obj a))}))
:description (str "expression patterns associated with the Anatomy_term: " (:anatomy-term/id a))})
(def widget
{:name generic/name-field
:transgenes transgenes
:gene_ontology gene-ontology
:anatomy_function_nots anatomy-function-nots
:expression_clusters expression-clusters
:expression_patterns expression-patterns
:anatomy_functions anatomy-functions})
| null | https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/anatomy_term/widgets/associations.clj | clojure | can't find any | (ns rest-api.classes.anatomy-term.widgets.associations
(:require
[clojure.string :as str]
[datomic.api :as d]
[pseudoace.utils :as pace-utils]
[rest-api.formatters.object :as obj :refer [pack-obj]]
[rest-api.classes.generic-functions :as generic-functions]
[rest-api.classes.generic-fields :as generic]))
(defn transgenes [a]
:description "transgenes annotated with this anatomy_term"})
(defn gene-ontology [a]
{:data (let [db (d/entity-db a)]
(->> (d/q '[:find ?gt ?paper
:in $ ?at
:where
[?at :anatomy-term/go-term ?gh]
[?gh :anatomy-term.go-term/go-term ?gt]
[?gh :evidence/paper-evidence ?paper]]
db
(:db/id a))
(group-by first)
(map (fn [[go-term-id tuples]]
(let [go-term (d/entity db go-term-id)]
{:term (pack-obj go-term)
:reference (->> tuples
(map (fn [[_ paper-id]]
(->> (d/entity db paper-id)
(pack-obj))))
(seq))})))
(seq)))
:description "go_terms associated with this anatomy_term"})
(defn- anatomy-function [a bool]
(let [afhs (if (= bool true)
(:anatomy-function.involved/_anatomy-term a)
(:anatomy-function.not-involved/_anatomy-term a))]
(for [afh afhs
:let [af (if (= bool true)
(:anatomy-function/_involved afh)
(:anatomy-function/_not-involved afh))]]
{:gene (when-let [gh (:anatomy-function/gene af)]
(pack-obj (:anatomy-function.gene/gene gh)))
:reference (when-let [reference (:anatomy-function/reference af)]
(pack-obj reference))
:af_data (:anatomy-function/id af)
:bp_inv (when-let [hs (:anatomy-function/involved af)]
(for [h hs]
{:text (:anatomy-term.term/text
(:anatomy-term/term
(:anatomy-function.involved/anatomy-term h)))
:evidence (obj/get-evidence h)}))
:bp_not_inv (when-let [hs (:anatomy-function/not-involved af)]
(for [h hs]
{:text (:anatomy-term.term/text
(:anatomy-term/term
(:anatomy-function.not-involved/anatomy-term h)))
:evidence (obj/get-evidence h)}))
:phenotype (when-let [ph (:anatomy-function/phenotype af)]
(let [phenotype (:anatomy-function.phenotype/phenotype ph)]
(if-let [evidence (obj/get-evidence ph)]
{:text (pack-obj phenotype)
:evidence evidence}
(pack-obj phenotype))))
:assay (when-let [hs (:anatomy-function/assay af)]
(for [h hs]
{:text (:ao-code/id (:anatomy-function.assay/ao-code h))
:evidence (when-let [genotypes (:condition/genotype
(:anatomy-function.assay/condition h))]
{:genotype (str/join "<br /> " genotypes)})}))})))
(defn anatomy-functions [a]
{:data (anatomy-function a true)
:description "anatomy_functions associatated with this anatomy_term"})
(defn anatomy-function-nots [a]
{:data (anatomy-function a false)
:description "anatomy_functions associatated with this anatomy_term"})
(defn expression-clusters [a]
{:data (when-let [hs (:expression-cluster.anatomy-term/_anatomy-term a)]
(for [h hs
:let [ec (:expression-cluster/_anatomy-term h)]]
{:description (first (:expression-cluster/description ec))
:expression_cluster (pack-obj ec)}))
:description "expression cluster data"})
(defn expression-patterns [a]
{:data (when-let [hs (:expr-pattern.anatomy-term/_anatomy-term a)]
(for [h hs
:let [ep (:expr-pattern/_anatomy-term h)]]
{:description (when-let [patterns (:expr-pattern/pattern ep)]
(str/join "<br /> " patterns))
:expression_pattern (pack-obj ep)
:certainty (generic-functions/certainty h)
:reference (when-let [hs (:expr-pattern/reference ep)]
(let [paper (:expr-pattern.reference/paper (first hs))]
(:paper/id paper)))
:gene (when-let [g (:expr-pattern/gene ep)]
(pack-obj (:expr-pattern.gene/gene (first g))))
:author (when-let [a (:expr-pattern/author ep)]
(map pack-obj a))}))
:description (str "expression patterns associated with the Anatomy_term: " (:anatomy-term/id a))})
(def widget
{:name generic/name-field
:transgenes transgenes
:gene_ontology gene-ontology
:anatomy_function_nots anatomy-function-nots
:expression_clusters expression-clusters
:expression_patterns expression-patterns
:anatomy_functions anatomy-functions})
|
fa8d9332c8bc6e42dd77b2177ea4aab0645f95948f3eb857f3c169a81d8ca25c | OCamlPro/digodoc | objects.ml | (**************************************************************************)
(* *)
Copyright ( c ) 2021 OCamlPro SAS & Origin Labs SAS
(* *)
(* 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 LICENSE.md file in the root directory. *)
(* *)
(* *)
(**************************************************************************)
(** Module [Objects] contains all js objects converted from OCaml data structure or created by js_of_ocaml. *)
type nonrec opam_entry = Data_types.opam_entry = {
name : string;
path : string;
version : string;
synopsis : string;
} [@@deriving jsoo]
(** Conversion from [Data_types.opam_entry] to js object *)
type nonrec packages = opam_entry list
[@@deriving jsoo]
(** Conversion from [Data_types.packages] to js object *)
type nonrec lib_entry = Data_types.lib_entry = {
name : string;
path : string;
opam : string;
opampath: string;
} [@@deriving jsoo]
(** Conversion from [Data_types.lib_entry] to js object *)
type nonrec libraries = lib_entry list
[@@deriving jsoo]
(** Conversion from [Data_types.libraries] to js object *)
type nonrec meta_entry = Data_types.meta_entry = {
namemeta : string ;
path : string ;
opam : string ;
opampath : string;
} [@@deriving jsoo]
(** Conversion from [Data_types.meta_entry] to js object *)
type nonrec metas = meta_entry list
[@@deriving jsoo]
(** Conversion from [Data_types.metas] to js object *)
type module_entry = Data_types.module_entry = {
name : string;
path : string;
opam : string;
opampath : string;
libs : (string * string) list;
} [@@deriving jsoo]
(** Conversion from [Data_types.module_entry] to js object *)
type nonrec modules = module_entry list [@@deriving jsoo]
(** Conversion from [Data_types.modules] to js object *)
type nonrec source_entry = Data_types.source_entry = {
namesrc : string;
path : string;
opam : string;
opampath : string;
} [@@deriving jsoo]
(** Conversion from [Data_types.source_entry] to js object *)
type nonrec sources = source_entry list [@@deriving jsoo]
(** Conversion from [Data_types.sources] to js object *)
type nonrec val_element = Data_types.val_element = {
ident : string;
value : string;
mdl : string;
mdlpath : string;
opam : string;
opampath : string;
} [@@deriving jsoo]
(** Conversion from [Data_types.val_element] to js object *)
type nonrec vals = val_element list [@@deriving jsoo]
(** Conversion from [Data_types.vals] to js object *)
type nonrec type_element = Data_types.type_element = {
ident : string;
mdl : string;
mdlpath : string;
opam : string;
opampath : string;
} [@@deriving jsoo]
* Conversion from [ Data_types.type_element ] to js object
type nonrec types = type_element list [@@deriving jsoo]
(** Conversion from [Data_types.types] to js object *)
type nonrec class_element = Data_types.class_element = {
ident : string;
mdl : string;
mdlpath : string;
isclasstype : int;
opam : string;
opampath : string;
} [@@deriving jsoo]
(** Conversion from [Data_types.class_element] to js object *)
type nonrec classes = class_element list [@@deriving jsoo]
(** Conversion from [Data_types.classes] to js object *)
type nonrec search_result = Data_types.search_result = {
packages : packages;
libraries : libraries;
modules : modules;
} [@@deriving jsoo]
* Conversion from [ ] to js object
type nonrec sources_occurence = Data_types.sources_occurence = {
opamname : string;
srcpath: string;
filename: string;
occpos: int;
occline: string;
occpath: string;
} [@@deriving jsoo]
(** Conversion from [Data_types.sources_occurence] to js object *)
type nonrec sources_search_result = Data_types.sources_search_result = {
totaloccs : int;
occs : sources_occurence list
} [@@deriving jsoo]
* Conversion from [ ] to js object | null | https://raw.githubusercontent.com/OCamlPro/digodoc/431b29c097a5cf17cd546efc32006e2be4a167b0/src/frontend/objects.ml | ocaml | ************************************************************************
All rights reserved.
This file is distributed under the terms of the GNU Lesser General
described in the LICENSE.md file in the root directory.
************************************************************************
* Module [Objects] contains all js objects converted from OCaml data structure or created by js_of_ocaml.
* Conversion from [Data_types.opam_entry] to js object
* Conversion from [Data_types.packages] to js object
* Conversion from [Data_types.lib_entry] to js object
* Conversion from [Data_types.libraries] to js object
* Conversion from [Data_types.meta_entry] to js object
* Conversion from [Data_types.metas] to js object
* Conversion from [Data_types.module_entry] to js object
* Conversion from [Data_types.modules] to js object
* Conversion from [Data_types.source_entry] to js object
* Conversion from [Data_types.sources] to js object
* Conversion from [Data_types.val_element] to js object
* Conversion from [Data_types.vals] to js object
* Conversion from [Data_types.types] to js object
* Conversion from [Data_types.class_element] to js object
* Conversion from [Data_types.classes] to js object
* Conversion from [Data_types.sources_occurence] to js object | Copyright ( c ) 2021 OCamlPro SAS & Origin Labs SAS
Public License version 2.1 , with the special exception on linking
type nonrec opam_entry = Data_types.opam_entry = {
name : string;
path : string;
version : string;
synopsis : string;
} [@@deriving jsoo]
type nonrec packages = opam_entry list
[@@deriving jsoo]
type nonrec lib_entry = Data_types.lib_entry = {
name : string;
path : string;
opam : string;
opampath: string;
} [@@deriving jsoo]
type nonrec libraries = lib_entry list
[@@deriving jsoo]
type nonrec meta_entry = Data_types.meta_entry = {
namemeta : string ;
path : string ;
opam : string ;
opampath : string;
} [@@deriving jsoo]
type nonrec metas = meta_entry list
[@@deriving jsoo]
type module_entry = Data_types.module_entry = {
name : string;
path : string;
opam : string;
opampath : string;
libs : (string * string) list;
} [@@deriving jsoo]
type nonrec modules = module_entry list [@@deriving jsoo]
type nonrec source_entry = Data_types.source_entry = {
namesrc : string;
path : string;
opam : string;
opampath : string;
} [@@deriving jsoo]
type nonrec sources = source_entry list [@@deriving jsoo]
type nonrec val_element = Data_types.val_element = {
ident : string;
value : string;
mdl : string;
mdlpath : string;
opam : string;
opampath : string;
} [@@deriving jsoo]
type nonrec vals = val_element list [@@deriving jsoo]
type nonrec type_element = Data_types.type_element = {
ident : string;
mdl : string;
mdlpath : string;
opam : string;
opampath : string;
} [@@deriving jsoo]
* Conversion from [ Data_types.type_element ] to js object
type nonrec types = type_element list [@@deriving jsoo]
type nonrec class_element = Data_types.class_element = {
ident : string;
mdl : string;
mdlpath : string;
isclasstype : int;
opam : string;
opampath : string;
} [@@deriving jsoo]
type nonrec classes = class_element list [@@deriving jsoo]
type nonrec search_result = Data_types.search_result = {
packages : packages;
libraries : libraries;
modules : modules;
} [@@deriving jsoo]
* Conversion from [ ] to js object
type nonrec sources_occurence = Data_types.sources_occurence = {
opamname : string;
srcpath: string;
filename: string;
occpos: int;
occline: string;
occpath: string;
} [@@deriving jsoo]
type nonrec sources_search_result = Data_types.sources_search_result = {
totaloccs : int;
occs : sources_occurence list
} [@@deriving jsoo]
* Conversion from [ ] to js object |
ef81737bd263032293a3597d8353199de527e2f692ce49fadcf3c695797f3afc | argp/bap | euler014.ml | let rec seq i = function
1 -> i
| n when n land 1 = 0 -> seq (i+1) (n asr 1)
| n (* odd *) -> seq (i+1) (3*n+1)
let () =
let best_i = ref 1
and best_n0 = ref 1 in
for n = 1 to 1_000_000 do
let i = seq 1 n in
if i > !best_i then
( best_i := i; best_n0 := n );
done;
print_int !best_n0; print_newline ()
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/examples/euler/euler014.ml | ocaml | odd | let rec seq i = function
1 -> i
| n when n land 1 = 0 -> seq (i+1) (n asr 1)
let () =
let best_i = ref 1
and best_n0 = ref 1 in
for n = 1 to 1_000_000 do
let i = seq 1 n in
if i > !best_i then
( best_i := i; best_n0 := n );
done;
print_int !best_n0; print_newline ()
|
b9778b9ee0910d86b64d61de80200ba2727b0a78e6c754894943cc28c5ce0382 | jarvinet/scheme | section122.scm | Structure and Interpretation of Computer Programs , 1st edition
;-------------------------------------------------------------
; Section 1.2.2
(define (count-change amount)
(cc amount 5))
(define (cc amount kinds-of-coins)
(cond ((= amount 0) 1)
((or (< amount 0) (= kinds-of-coins 0)) 0)
(else (+ (cc (- amount
(first-denomination kinds-of-coins))
kinds-of-coins)
(cc amount
(- kinds-of-coins 1))))))
(define (first-denomination kinds-of-coins)
(cond ((= kinds-of-coins 1) 1) ; pennies
((= kinds-of-coins 2) 5) ; nickels
((= kinds-of-coins 3) 10) ; dimes
((= kinds-of-coins 4) 25) ; quarters
half - dollars
;-------------------------------------------------------------
exercise 1.9
; (cc 10 2)
; (+ (cc 5 2) (cc 10 1))
; (+ (+ (cc 0 2) (cc 5 1)) (+ (cc 9 1) (cc 10 0)))
; (+ (+ 1 (+ (cc 4 1) (cc 5 0)))
; (cc 5 1)
; (+ (cc 4 1) (cc (5 0)))
; (+ (+ (cc 3 1) (cc 4 0)) 0)
; (+ (+ (+ (cc 2 1) (cc 3 0)) 0) 0)
; (+ (+ (+ (+ (cc 1 1) (cc 2 0)) 0) 0) 0)
; (+ (+ (+ (+ (+ (cc 0 1) (cc 1 0)) 0) 0) 0) 0)
( + ( + ( + ( + ( + 1 0 ) 0 ) 0 ) 0 ) 0 )
; (+ (+ (+ (+ 1 0) 0) 0) 0)
( + ( + ( + 1 0 ) 0 ) 0 )
( + ( + 1 0 ) 0 )
; (+ 1 0)
1
; (cc 5 2)
; (cc 0 2)
1
; (cc 5 1)
; (cc 4 1)
; (cc 3 1)
; (cc 2 1)
; (cc 1 1)
; (cc 0 1)
1
; (cc 1 0)
; 0
; (cc 2 0)
0
; (cc 3 0)
; 0
; (cc 4 0)
; 0
; (cc 5 0)
; 0
; (cc 5 2)
; |
; +-----------------+------------------+
; | |
; (cc 0 2) (cc 5 1)
; | |
; | +-------------+--------------+
; | | |
; 1 (cc 4 1) (cc 5 0)
; | |
; +----------+---------+ |
; | | |
; (cc 3 1) (cc 4 0) 0
; | |
; +---------+--------+ |
; | | |
( cc 2 1 ) ( cc 3 0 ) 0
; | |
; +------+------+ |
; | | |
( cc 1 1 ) ( cc 2 0 ) 0
; | |
; +----+-----+ |
; | | |
;(cc 0 1) (cc 1 0) 0
; | |
1 0
; (cc 11 5)
; |
; +------------+---------------+
; (cc -39 5) (cc 11 4)
; |
; +--------+-------+
; | |
( cc -14 5 ) ( cc 11 3 )
; |
; +--------------------------+---------------------+
; | |
; (cc 1 3) (cc 11 2)
; | |
; +-------+-------+ +--------+--------+
; | | | |
; (cc -9 3) (cc 1 2) (cc 6 2) (cc 11 1)
; | |
; +-------+-------+
; | |
; (cc -4 2) (cc 1 1) (cc 1 2) (cc 6 1)
; |
; +------+------+
; | |
; (cc 0 1) (cc 1 0)
; | |
; | |
; | |
; 1 0
;
; (cc 11 5)
; (cc -39 5)
; 0
; (cc 11 4)
( cc -14 5 )
; 0
; (cc 11 3)
; (cc 1 3)
( cc -9 3 )
; 0
; (cc 1 2)
; (cc -4 2)
0
; (cc 1 1)
; (cc 0 1)
1
; (cc 1 0)
; 0
; (cc 11 2)
; (cc 6 2)
; (cc 1 2)
; (cc -4 2)
; 0
; (cc 1 1)
; (cc 0 1)
1
; (cc 1 0)
; 0
; (cc 6 1)
; (cc 5 1)
; (cc 6 0)
; 0
; (cc 11 1)
; (cc 10 1)
; (cc 11 0)
0
| null | https://raw.githubusercontent.com/jarvinet/scheme/47633d7fc4d82d739a62ceec75c111f6549b1650/Book/Edition1/section122.scm | scheme | -------------------------------------------------------------
Section 1.2.2
pennies
nickels
dimes
quarters
-------------------------------------------------------------
(cc 10 2)
(+ (cc 5 2) (cc 10 1))
(+ (+ (cc 0 2) (cc 5 1)) (+ (cc 9 1) (cc 10 0)))
(+ (+ 1 (+ (cc 4 1) (cc 5 0)))
(cc 5 1)
(+ (cc 4 1) (cc (5 0)))
(+ (+ (cc 3 1) (cc 4 0)) 0)
(+ (+ (+ (cc 2 1) (cc 3 0)) 0) 0)
(+ (+ (+ (+ (cc 1 1) (cc 2 0)) 0) 0) 0)
(+ (+ (+ (+ (+ (cc 0 1) (cc 1 0)) 0) 0) 0) 0)
(+ (+ (+ (+ 1 0) 0) 0) 0)
(+ 1 0)
(cc 5 2)
(cc 0 2)
(cc 5 1)
(cc 4 1)
(cc 3 1)
(cc 2 1)
(cc 1 1)
(cc 0 1)
(cc 1 0)
0
(cc 2 0)
(cc 3 0)
0
(cc 4 0)
0
(cc 5 0)
0
(cc 5 2)
|
+-----------------+------------------+
| |
(cc 0 2) (cc 5 1)
| |
| +-------------+--------------+
| | |
1 (cc 4 1) (cc 5 0)
| |
+----------+---------+ |
| | |
(cc 3 1) (cc 4 0) 0
| |
+---------+--------+ |
| | |
| |
+------+------+ |
| | |
| |
+----+-----+ |
| | |
(cc 0 1) (cc 1 0) 0
| |
(cc 11 5)
|
+------------+---------------+
(cc -39 5) (cc 11 4)
|
+--------+-------+
| |
|
+--------------------------+---------------------+
| |
(cc 1 3) (cc 11 2)
| |
+-------+-------+ +--------+--------+
| | | |
(cc -9 3) (cc 1 2) (cc 6 2) (cc 11 1)
| |
+-------+-------+
| |
(cc -4 2) (cc 1 1) (cc 1 2) (cc 6 1)
|
+------+------+
| |
(cc 0 1) (cc 1 0)
| |
| |
| |
1 0
(cc 11 5)
(cc -39 5)
0
(cc 11 4)
0
(cc 11 3)
(cc 1 3)
0
(cc 1 2)
(cc -4 2)
(cc 1 1)
(cc 0 1)
(cc 1 0)
0
(cc 11 2)
(cc 6 2)
(cc 1 2)
(cc -4 2)
0
(cc 1 1)
(cc 0 1)
(cc 1 0)
0
(cc 6 1)
(cc 5 1)
(cc 6 0)
0
(cc 11 1)
(cc 10 1)
(cc 11 0) | Structure and Interpretation of Computer Programs , 1st edition
(define (count-change amount)
(cc amount 5))
(define (cc amount kinds-of-coins)
(cond ((= amount 0) 1)
((or (< amount 0) (= kinds-of-coins 0)) 0)
(else (+ (cc (- amount
(first-denomination kinds-of-coins))
kinds-of-coins)
(cc amount
(- kinds-of-coins 1))))))
(define (first-denomination kinds-of-coins)
half - dollars
exercise 1.9
( + ( + ( + ( + ( + 1 0 ) 0 ) 0 ) 0 ) 0 )
( + ( + ( + 1 0 ) 0 ) 0 )
( + ( + 1 0 ) 0 )
1
1
1
0
( cc 2 1 ) ( cc 3 0 ) 0
( cc 1 1 ) ( cc 2 0 ) 0
1 0
( cc -14 5 ) ( cc 11 3 )
( cc -14 5 )
( cc -9 3 )
0
1
1
0
|
2ccdc6eb0cec3a0d0ffcb544309153fe3fd7664156ca2c81f3e31de2f08a4b21 | eerohele/tab | auto.clj | (ns tab.auto
"Load this namespace to run a Tab using sensible defaults.
See tab.api for the API proper."
(:require [tab.api :as tab]))
(def tab "A Tab." nil)
(alter-var-root #'tab
(fn [_]
(let [tab (tab/run)]
(printf "Tab is listening on %s\n" (tab/address tab))
tab)))
(defn halt
[]
(alter-var-root #'tab (fn [_] (tab/halt tab) nil)))
| null | https://raw.githubusercontent.com/eerohele/tab/6882e860acb42423dfbe78bcc86b8a0dbe91a118/src/tab/auto.clj | clojure | (ns tab.auto
"Load this namespace to run a Tab using sensible defaults.
See tab.api for the API proper."
(:require [tab.api :as tab]))
(def tab "A Tab." nil)
(alter-var-root #'tab
(fn [_]
(let [tab (tab/run)]
(printf "Tab is listening on %s\n" (tab/address tab))
tab)))
(defn halt
[]
(alter-var-root #'tab (fn [_] (tab/halt tab) nil)))
| |
1ad67299797e602197deaa238013c1724519384c38a3edafa1fae4977116df95 | biocaml/biocaml | sam.ml | open OUnit
module Sam = Biocaml_unix.Sam
let ( %> ) f g x = g (f x)
let test_parse_optional_field s v =
let f = Sam.parse_optional_field s in
assert_equal ~msg:"Optional field value (i type)"
~printer:
(Or_error.sexp_of_t Sam.sexp_of_optional_field
%> Sexplib.Sexp.to_string_hum)
f v
let test_parser () =
test_parse_optional_field "YS:i:-1"
(Sam.optional_field "YS" (Sam.optional_field_value_i (-1L)))
let tests = "SAM" >::: [ "Parse SAM" >:: test_parser ]
module Biocaml_unix . Sam_deprecated
(* module Tfxm = Biocaml_unix.Tfxm *)
(* let test_parser_deprecated () = *)
let transfo = . Transform.string_to_raw ( ) in
(* let test_line l f = *)
Tfxm.feed transfo ( l ^ " \n " ) ;
assert_bool l ( f ( Tfxm.next transfo ) )
(* in *)
(* let test_output l o = test_line l (fun oo -> `output (Ok o) = oo) in *)
test_output " @CO\tsome comment " ( ` comment " some comment " ) ;
(* test_output "@HD\tVN:1.3\tSO:coordinate" *)
( ` header ( " HD " , [ " VN " , " 1.3 " ; " SO " , " coordinate " ] ) ) ;
(* test_output "r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT\t*" *)
(* (`alignment *)
{ Sam.qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
(* qual = "*"; optional = []}); *)
(* test_output "r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT\t*\tNM:i:0" *)
(* (`alignment *)
{ Sam.qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
(* qual = "*"; optional = [("NM", 'i', "0")]}); *)
(* test_output "r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT\t*\tNM:i:0\tKJ:A:a" *)
(* (`alignment *)
{ Sam.qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
qual = " * " ; optional = [ ( " NM " , ' i ' , " 0 " ) ; ( " " , ' A ' , " a " ) ] } ) ;
(* test_line "r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT\t*\tNM:i:0\tKJ:A" *)
(* (function *)
(* | `output (Error (`wrong_optional_field (_, _))) -> true *)
(* | _ -> false); *)
" r001\t83\tref\t37\t30\t9M\t=\t7h\t-39\tCAGCGCCAT\t*\tNM : i:0\tKJ : A : a "
(* (function *)
| ` output ( Error ( ` not_an_int ( _ , " pnext " , " 7h " ) ) ) - > true
(* | _ -> false); *)
" r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT "
(* (function *)
(* | `output (Error (`wrong_alignment (_, _))) -> true *)
(* | _ -> false); *)
test_line " @HD\tT "
(* (function *)
(* | `output (Error (`invalid_tag_value_list (_, ["T"]))) -> true *)
(* | _ -> false); *)
(* () *)
(* let test_item_parser_deprecated () = *)
(* let c = ref 0 in *)
(* let check t v f = *)
let p = . Transform.raw_to_string ( ) in
(* incr c; *)
(* Tfxm.feed t v; *)
(* let res = f (Tfxm.next t) in *)
(* if not res then *)
(* eprintf "Error on %s\n" *)
(* Tfxm.( *)
match feed p v ; next p with ` output o - > o | _ - > failwith " printer ! "
(* ); *)
(* assert_bool (sprintf "test_item_parser.check %d" !c) res *)
(* in *)
(* let check_output t v o = check t v ((=) (`output (Ok o))) in *)
let t = Sam . ( ) in
(* check_output t (`comment "comment") (`comment "comment"); *)
check t ( ` header ( " HD " , [ " VN " , " 42.1 " ] ) ) ( function
| ` output ( Error ( ` header_line_not_first 2 ) ) - > true
(* | _ -> false); *)
let t = Sam . ( ) in
check_output t ( ` header ( " HD " , [ " VN " , " 42.1 " ] ) )
( ` header_line ( " 42.1 " , ` unknown , [ ] ) ) ;
(* check t (`header ("SQ", [])) (function *)
(* | `output (Error (`missing_ref_sequence_name [])) -> true *)
(* | _ -> false); *)
check t ( ` header ( " SQ " , [ " SN " , " chr0 " ] ) ) ( function
| ` output ( Error ( ` missing_ref_sequence_length [ ( " SN " , " chr0 " ) ] ) ) - > true
(* | _ -> false); *)
check t ( ` header ( " SQ " , [ " SN " , " chr0 " ; " LN " , " not an int " ] ) ) ( function
(* | `output (Error (`wrong_ref_sequence_length _)) -> true *)
(* | _ -> false); *)
let t = Sam . ( ) in
check_output t ( ` header ( " HD " , [ " VN " , " 42.1 " ;
" SO " , " coordinate " ; " HP " , " some other " ] ) )
( ` header_line ( " 42.1 " , ` coordinate , [ ( " HP " , " some other " ) ] ) ) ;
check t ( ` header ( " SQ " , [ " SN " , " chr0 " ; " LN " , " 42 " ] ) ) ( (= ) ` ) ;
check t ( ` header ( " SQ " , [ " SN " , " chr1 " ; " LN " , " 42 " ; " M5 " , " abd34f90 " ] ) )
( (= ) ` ) ;
( \ * the ref - info is being buffered , the first alignment will output it * \ )
(* check_output t (`alignment *)
{ Sam.qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
(* qual = "*"; optional = [("NM", 'i', "0")]}) *)
(* (`reference_sequence_dictionary *)
(* [| *)
{ Sam.ref_name = " chr0 " ; ref_length = 42 ; ref_assembly_identifier = None ;
(* ref_checksum = None; ref_species = None; ref_uri = None; *)
(* ref_unknown = []}; *)
{ Sam.ref_name = " chr1 " ; ref_length = 42 ; ref_assembly_identifier = None ;
(* ref_checksum = Some "abd34f90"; ref_species = None; ref_uri = None; *)
(* ref_unknown = []}; *)
(* |]); *)
(* (\* This one get the previous alignment: *\) *)
(* check_output t *)
(* (`alignment *)
{ Sam.qname = " chr0 " ; flag = 83 ; rname = " chr0 " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " * " ; 7 ; ; seq = " CAGCGCCAT " ;
(* qual = "*"; optional = [("NM", 'i', "0")]}) *)
(* (`alignment *)
{ Sam.query_template_name = " r001 " ; flags = . Flags.of_int 83 ;
reference_sequence = ` name " ref " ; position = Some 37 ;
mapping_quality = Some 30 ; cigar_operations = [ |`M 9| ] ;
next_reference_sequence = ` qname ; next_position = Some 7 ;
template_length = Some ( ) ; sequence = ` string " CAGCGCCAT " ;
(* quality = [| |]; optional_content = [ "NM", 'i', `int 0] }); *)
(* Tfxm.stop t; *)
(* (\* We still have one to get: *\) *)
(* assert_bool "last alignment" (Tfxm.next t = *)
(* `output (Ok *)
(* (`alignment *)
{ Sam.query_template_name = " chr0 " ; flags = . Flags.of_int 83 ;
(* reference_sequence = *)
(* `reference_sequence *)
{ Sam.ref_name = " chr0 " ; ref_length = 42 ;
(* ref_assembly_identifier = None; *)
(* ref_checksum = None; ref_species = None; ref_uri = None; *)
(* ref_unknown = []}; *)
position = Some 37 ; mapping_quality = Some 30 ;
(* cigar_operations = [|`M 9|]; next_reference_sequence = `none; *)
next_position = Some 7 ; template_length = Some ( ) ;
(* sequence = `string "CAGCGCCAT"; quality = [| |]; *)
(* optional_content = [ "NM", 'i', `int 0]}))); *)
(* assert_bool "EOS" (Tfxm.next t = `end_of_stream); *)
check ( ` header ( " HD " , [ " VN " , " 42.1 " ; " SO " , " coordinate " ] ) ) ;
check ( ` header ( " HD " , [ " VN " , " 42.1 " ; " SO " , " wut ? " ] ) ) ;
check ( ` header ( " HD " , [ " VN " , " 42.1 " ; " SO " , " coordinate " ; " HP " , " some other " ] ) ) ;
check ( ` header ( " HD " , [ ] ) ) ;
check ( ` header ( " SQ " , [ ] ) ) ;
check ( ` header ( " SQ " , [ " SN " , " chr0 " ] ) ) ;
check ( ` header ( " SQ " , [ " SN " , " chr0 " ; " LN " , " not an int " ] ) ) ;
check ( ` header ( " SQ " , [ " SN " , " chr0 " ; " LN " , " 42 " ] ) ) ;
check ( ` header ( " SQ " , [ " SN " , " chr1 " ; " LN " , " 42 " ; " M5 " , " abd34f90 " ] ) ) ;
check ( ` header ( " RR " , [ " SN " , " chr1 " ; " LN " , " 42 " ; " M5 " , " abd34f90 " ] ) ) ;
check ( ` alignment
{ qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
qual = " * " ; optional = [ ( " NM " , ' i ' , " 0 " ) ] } ) ;
check ( ` alignment
{ qname = " chr0 " ; flag = 83 ; rname = " chr0 " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " * " ; 7 ; ; seq = " CAGCGCCAT " ;
qual = " * " ; optional = [ ( " NM " , ' i ' , " 0 " ) ] } ) ;
check (`header ("HD", ["VN", "42.1"; "SO", "coordinate"]));
check (`header ("HD", ["VN", "42.1"; "SO", "wut?"]));
check (`header ("HD", ["VN", "42.1"; "SO", "coordinate"; "HP", "some other"]));
check (`header ("HD", []));
check (`header ("SQ", []));
check (`header ("SQ", ["SN", "chr0"]));
check (`header ("SQ", ["SN", "chr0"; "LN", "not an int"]));
check (`header ("SQ", ["SN", "chr0"; "LN", "42"]));
check (`header ("SQ", ["SN", "chr1"; "LN", "42"; "M5", "abd34f90"]));
check (`header ("RR", ["SN", "chr1"; "LN", "42"; "M5", "abd34f90"]));
check (`alignment
{qname = "r001"; flag = 83; rname = "ref"; pos = 37; mapq = 30;
cigar = "9M"; rnext = "="; pnext = 7; tlen = -39; seq = "CAGCGCCAT";
qual = "*"; optional = [("NM", 'i', "0")]});
check (`alignment
{qname = "chr0"; flag = 83; rname = "chr0"; pos = 37; mapq = 30;
cigar = "9M"; rnext = "*"; pnext = 7; tlen = -39; seq = "CAGCGCCAT";
qual = "*"; optional = [("NM", 'i', "0")]});
*)
(* let test_printer_deprecated () = *)
let transfo = . Transform.raw_to_string ( ) in
(* let test_line i l = *)
(* Tfxm.feed transfo i; *)
assert_bool l ( Tfxm.next transfo = ` output ( l ^ " \n " ) )
(* in *)
(* test_line *)
(* (`alignment *)
{ Sam.qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
(* qual = "*"; optional = [("NM", 'i', "0")]}) *)
(* "r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT\t*\tNM:i:0"; *)
test_line ( ` comment " some comment " ) " @CO\tsome comment " ;
test_line ( ` header ( " HD " , [ " VN " , " 1.3 " ; " SO " , " coordinate " ] ) )
(* "@HD\tVN:1.3\tSO:coordinate"; *)
(* () *)
(* let tests = "SAM" >::: [ *)
(* "Parse SAM" >:: test_parser ; *)
(* "Parse SAM raw" >:: test_parser_deprecated; *)
(* "Print SAM" >:: test_printer_deprecated; *)
" SAM item " > : : test_item_parser_deprecated ;
(* ] *)
| null | https://raw.githubusercontent.com/biocaml/biocaml/ac619539fed348747d686b8f628e80c1bb8bfc59/lib/test/sam.ml | ocaml | module Tfxm = Biocaml_unix.Tfxm
let test_parser_deprecated () =
let test_line l f =
in
let test_output l o = test_line l (fun oo -> `output (Ok o) = oo) in
test_output "@HD\tVN:1.3\tSO:coordinate"
test_output "r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT\t*"
(`alignment
qual = "*"; optional = []});
test_output "r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT\t*\tNM:i:0"
(`alignment
qual = "*"; optional = [("NM", 'i', "0")]});
test_output "r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT\t*\tNM:i:0\tKJ:A:a"
(`alignment
test_line "r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT\t*\tNM:i:0\tKJ:A"
(function
| `output (Error (`wrong_optional_field (_, _))) -> true
| _ -> false);
(function
| _ -> false);
(function
| `output (Error (`wrong_alignment (_, _))) -> true
| _ -> false);
(function
| `output (Error (`invalid_tag_value_list (_, ["T"]))) -> true
| _ -> false);
()
let test_item_parser_deprecated () =
let c = ref 0 in
let check t v f =
incr c;
Tfxm.feed t v;
let res = f (Tfxm.next t) in
if not res then
eprintf "Error on %s\n"
Tfxm.(
);
assert_bool (sprintf "test_item_parser.check %d" !c) res
in
let check_output t v o = check t v ((=) (`output (Ok o))) in
check_output t (`comment "comment") (`comment "comment");
| _ -> false);
check t (`header ("SQ", [])) (function
| `output (Error (`missing_ref_sequence_name [])) -> true
| _ -> false);
| _ -> false);
| `output (Error (`wrong_ref_sequence_length _)) -> true
| _ -> false);
check_output t (`alignment
qual = "*"; optional = [("NM", 'i', "0")]})
(`reference_sequence_dictionary
[|
ref_checksum = None; ref_species = None; ref_uri = None;
ref_unknown = []};
ref_checksum = Some "abd34f90"; ref_species = None; ref_uri = None;
ref_unknown = []};
|]);
(\* This one get the previous alignment: *\)
check_output t
(`alignment
qual = "*"; optional = [("NM", 'i', "0")]})
(`alignment
quality = [| |]; optional_content = [ "NM", 'i', `int 0] });
Tfxm.stop t;
(\* We still have one to get: *\)
assert_bool "last alignment" (Tfxm.next t =
`output (Ok
(`alignment
reference_sequence =
`reference_sequence
ref_assembly_identifier = None;
ref_checksum = None; ref_species = None; ref_uri = None;
ref_unknown = []};
cigar_operations = [|`M 9|]; next_reference_sequence = `none;
sequence = `string "CAGCGCCAT"; quality = [| |];
optional_content = [ "NM", 'i', `int 0]})));
assert_bool "EOS" (Tfxm.next t = `end_of_stream);
let test_printer_deprecated () =
let test_line i l =
Tfxm.feed transfo i;
in
test_line
(`alignment
qual = "*"; optional = [("NM", 'i', "0")]})
"r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT\t*\tNM:i:0";
"@HD\tVN:1.3\tSO:coordinate";
()
let tests = "SAM" >::: [
"Parse SAM" >:: test_parser ;
"Parse SAM raw" >:: test_parser_deprecated;
"Print SAM" >:: test_printer_deprecated;
] | open OUnit
module Sam = Biocaml_unix.Sam
let ( %> ) f g x = g (f x)
let test_parse_optional_field s v =
let f = Sam.parse_optional_field s in
assert_equal ~msg:"Optional field value (i type)"
~printer:
(Or_error.sexp_of_t Sam.sexp_of_optional_field
%> Sexplib.Sexp.to_string_hum)
f v
let test_parser () =
test_parse_optional_field "YS:i:-1"
(Sam.optional_field "YS" (Sam.optional_field_value_i (-1L)))
let tests = "SAM" >::: [ "Parse SAM" >:: test_parser ]
module Biocaml_unix . Sam_deprecated
let transfo = . Transform.string_to_raw ( ) in
Tfxm.feed transfo ( l ^ " \n " ) ;
assert_bool l ( f ( Tfxm.next transfo ) )
test_output " @CO\tsome comment " ( ` comment " some comment " ) ;
( ` header ( " HD " , [ " VN " , " 1.3 " ; " SO " , " coordinate " ] ) ) ;
{ Sam.qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
{ Sam.qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
{ Sam.qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
qual = " * " ; optional = [ ( " NM " , ' i ' , " 0 " ) ; ( " " , ' A ' , " a " ) ] } ) ;
" r001\t83\tref\t37\t30\t9M\t=\t7h\t-39\tCAGCGCCAT\t*\tNM : i:0\tKJ : A : a "
| ` output ( Error ( ` not_an_int ( _ , " pnext " , " 7h " ) ) ) - > true
" r001\t83\tref\t37\t30\t9M\t=\t7\t-39\tCAGCGCCAT "
test_line " @HD\tT "
let p = . Transform.raw_to_string ( ) in
match feed p v ; next p with ` output o - > o | _ - > failwith " printer ! "
let t = Sam . ( ) in
check t ( ` header ( " HD " , [ " VN " , " 42.1 " ] ) ) ( function
| ` output ( Error ( ` header_line_not_first 2 ) ) - > true
let t = Sam . ( ) in
check_output t ( ` header ( " HD " , [ " VN " , " 42.1 " ] ) )
( ` header_line ( " 42.1 " , ` unknown , [ ] ) ) ;
check t ( ` header ( " SQ " , [ " SN " , " chr0 " ] ) ) ( function
| ` output ( Error ( ` missing_ref_sequence_length [ ( " SN " , " chr0 " ) ] ) ) - > true
check t ( ` header ( " SQ " , [ " SN " , " chr0 " ; " LN " , " not an int " ] ) ) ( function
let t = Sam . ( ) in
check_output t ( ` header ( " HD " , [ " VN " , " 42.1 " ;
" SO " , " coordinate " ; " HP " , " some other " ] ) )
( ` header_line ( " 42.1 " , ` coordinate , [ ( " HP " , " some other " ) ] ) ) ;
check t ( ` header ( " SQ " , [ " SN " , " chr0 " ; " LN " , " 42 " ] ) ) ( (= ) ` ) ;
check t ( ` header ( " SQ " , [ " SN " , " chr1 " ; " LN " , " 42 " ; " M5 " , " abd34f90 " ] ) )
( (= ) ` ) ;
( \ * the ref - info is being buffered , the first alignment will output it * \ )
{ Sam.qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
{ Sam.ref_name = " chr0 " ; ref_length = 42 ; ref_assembly_identifier = None ;
{ Sam.ref_name = " chr1 " ; ref_length = 42 ; ref_assembly_identifier = None ;
{ Sam.qname = " chr0 " ; flag = 83 ; rname = " chr0 " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " * " ; 7 ; ; seq = " CAGCGCCAT " ;
{ Sam.query_template_name = " r001 " ; flags = . Flags.of_int 83 ;
reference_sequence = ` name " ref " ; position = Some 37 ;
mapping_quality = Some 30 ; cigar_operations = [ |`M 9| ] ;
next_reference_sequence = ` qname ; next_position = Some 7 ;
template_length = Some ( ) ; sequence = ` string " CAGCGCCAT " ;
{ Sam.query_template_name = " chr0 " ; flags = . Flags.of_int 83 ;
{ Sam.ref_name = " chr0 " ; ref_length = 42 ;
position = Some 37 ; mapping_quality = Some 30 ;
next_position = Some 7 ; template_length = Some ( ) ;
check ( ` header ( " HD " , [ " VN " , " 42.1 " ; " SO " , " coordinate " ] ) ) ;
check ( ` header ( " HD " , [ " VN " , " 42.1 " ; " SO " , " wut ? " ] ) ) ;
check ( ` header ( " HD " , [ " VN " , " 42.1 " ; " SO " , " coordinate " ; " HP " , " some other " ] ) ) ;
check ( ` header ( " HD " , [ ] ) ) ;
check ( ` header ( " SQ " , [ ] ) ) ;
check ( ` header ( " SQ " , [ " SN " , " chr0 " ] ) ) ;
check ( ` header ( " SQ " , [ " SN " , " chr0 " ; " LN " , " not an int " ] ) ) ;
check ( ` header ( " SQ " , [ " SN " , " chr0 " ; " LN " , " 42 " ] ) ) ;
check ( ` header ( " SQ " , [ " SN " , " chr1 " ; " LN " , " 42 " ; " M5 " , " abd34f90 " ] ) ) ;
check ( ` header ( " RR " , [ " SN " , " chr1 " ; " LN " , " 42 " ; " M5 " , " abd34f90 " ] ) ) ;
check ( ` alignment
{ qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
qual = " * " ; optional = [ ( " NM " , ' i ' , " 0 " ) ] } ) ;
check ( ` alignment
{ qname = " chr0 " ; flag = 83 ; rname = " chr0 " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " * " ; 7 ; ; seq = " CAGCGCCAT " ;
qual = " * " ; optional = [ ( " NM " , ' i ' , " 0 " ) ] } ) ;
check (`header ("HD", ["VN", "42.1"; "SO", "coordinate"]));
check (`header ("HD", ["VN", "42.1"; "SO", "wut?"]));
check (`header ("HD", ["VN", "42.1"; "SO", "coordinate"; "HP", "some other"]));
check (`header ("HD", []));
check (`header ("SQ", []));
check (`header ("SQ", ["SN", "chr0"]));
check (`header ("SQ", ["SN", "chr0"; "LN", "not an int"]));
check (`header ("SQ", ["SN", "chr0"; "LN", "42"]));
check (`header ("SQ", ["SN", "chr1"; "LN", "42"; "M5", "abd34f90"]));
check (`header ("RR", ["SN", "chr1"; "LN", "42"; "M5", "abd34f90"]));
check (`alignment
{qname = "r001"; flag = 83; rname = "ref"; pos = 37; mapq = 30;
cigar = "9M"; rnext = "="; pnext = 7; tlen = -39; seq = "CAGCGCCAT";
qual = "*"; optional = [("NM", 'i', "0")]});
check (`alignment
{qname = "chr0"; flag = 83; rname = "chr0"; pos = 37; mapq = 30;
cigar = "9M"; rnext = "*"; pnext = 7; tlen = -39; seq = "CAGCGCCAT";
qual = "*"; optional = [("NM", 'i', "0")]});
*)
let transfo = . Transform.raw_to_string ( ) in
assert_bool l ( Tfxm.next transfo = ` output ( l ^ " \n " ) )
{ Sam.qname = " r001 " ; flag = 83 ; rname = " ref " ; pos = 37 ; mapq = 30 ;
cigar = " 9 M " ; " = " ; 7 ; ; seq = " CAGCGCCAT " ;
test_line ( ` comment " some comment " ) " @CO\tsome comment " ;
test_line ( ` header ( " HD " , [ " VN " , " 1.3 " ; " SO " , " coordinate " ] ) )
" SAM item " > : : test_item_parser_deprecated ;
|
a85b6972a1c2165024f115487acc3973645b2d8d8eb3df6d3ef7d3fc0fe1dbe3 | hasktorch/hasktorch | DType.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
module Torch.DType where
import Data.Complex
import qualified Numeric.Half as N
import Data.Int
import Data.Reflection
import Data.Word
import Torch.Internal.Class (Castable (..))
import qualified Torch.Internal.Const as ATen
import qualified Torch.Internal.Type as ATen
data DType
= -- | Bool
Bool
| -- | Byte
UInt8
|
Int8
| -- | Short
Int16
| -- | Int
Int32
| -- | Long
Int64
| -- | Half
Half
| -- | Float
Float
| -- | Double
Double
| ComplexHalf
ComplexHalf
| -- | ComplexFloat
ComplexFloat
| -- | ComplexDouble
ComplexDouble
| -- | QInt8
QInt8
| -- | QUInt8
QUInt8
|
QInt32
| -- | BFloat16
BFloat16
deriving (Eq, Show, Read)
instance Reifies Bool DType where
reflect _ = Bool
instance Reifies 'Bool DType where
reflect _ = Bool
instance Reifies Word8 DType where
reflect _ = UInt8
instance Reifies Int8 DType where
reflect _ = Int8
instance Reifies 'Int8 DType where
reflect _ = Int8
instance Reifies Int16 DType where
reflect _ = Int16
instance Reifies 'Int16 DType where
reflect _ = Int16
instance Reifies Int32 DType where
reflect _ = Int32
instance Reifies 'Int32 DType where
reflect _ = Int32
instance Reifies Int DType where
reflect _ = Int64
instance Reifies Int64 DType where
reflect _ = Int64
instance Reifies 'Int64 DType where
reflect _ = Int64
instance Reifies N.Half DType where
reflect _ = Half
instance Reifies 'Half DType where
reflect _ = Half
instance Reifies Float DType where
reflect _ = Float
instance Reifies 'Float DType where
reflect _ = Float
instance Reifies Double DType where
reflect _ = Double
instance Reifies 'Double DType where
reflect _ = Double
instance Reifies (Complex N.Half) DType where
reflect _ = ComplexHalf
instance Reifies 'ComplexHalf DType where
reflect _ = ComplexHalf
instance Reifies (Complex Float) DType where
reflect _ = ComplexFloat
instance Reifies 'ComplexFloat DType where
reflect _ = ComplexFloat
instance Reifies (Complex Double) DType where
reflect _ = ComplexDouble
instance Reifies 'ComplexDouble DType where
reflect _ = ComplexDouble
instance Castable DType ATen.ScalarType where
cast Bool f = f ATen.kBool
cast UInt8 f = f ATen.kByte
cast Int8 f = f ATen.kChar
cast Int16 f = f ATen.kShort
cast Int32 f = f ATen.kInt
cast Int64 f = f ATen.kLong
cast Half f = f ATen.kHalf
cast Float f = f ATen.kFloat
cast Double f = f ATen.kDouble
cast ComplexHalf f = f ATen.kComplexHalf
cast ComplexFloat f = f ATen.kComplexFloat
cast ComplexDouble f = f ATen.kComplexDouble
cast QInt8 f = f ATen.kQInt8
cast QUInt8 f = f ATen.kQUInt8
cast QInt32 f = f ATen.kQInt32
cast BFloat16 f = f ATen.kBFloat16
uncast x f
| x == ATen.kBool = f Bool
| x == ATen.kByte = f UInt8
| x == ATen.kChar = f Int8
| x == ATen.kShort = f Int16
| x == ATen.kInt = f Int32
| x == ATen.kLong = f Int64
| x == ATen.kHalf = f Half
| x == ATen.kFloat = f Float
| x == ATen.kDouble = f Double
| x == ATen.kComplexHalf = f ComplexHalf
| x == ATen.kComplexFloat = f ComplexFloat
| x == ATen.kComplexDouble = f ComplexDouble
| x == ATen.kQInt8 = f QInt8
| x == ATen.kQUInt8 = f QUInt8
| x == ATen.kQInt32 = f QInt32
| x == ATen.kBFloat16 = f BFloat16
isIntegral :: DType -> Bool
isIntegral Bool = True
isIntegral UInt8 = True
isIntegral Int8 = True
isIntegral Int16 = True
isIntegral Int32 = True
isIntegral Int64 = True
isIntegral Half = False
isIntegral Float = False
isIntegral Double = False
isIntegral ComplexHalf = False
isIntegral ComplexFloat = False
isIntegral ComplexDouble = False
isIntegral QInt8 = False
isIntegral QUInt8 = False
isIntegral QInt32 = False
isIntegral BFloat16 = False
isComplex :: DType -> Bool
isComplex Bool = False
isComplex UInt8 = False
isComplex Int8 = False
isComplex Int16 = False
isComplex Int32 = False
isComplex Int64 = False
isComplex Half = False
isComplex Float = False
isComplex Double = False
isComplex ComplexHalf = True
isComplex ComplexFloat = True
isComplex ComplexDouble = True
isComplex QInt8 = False
isComplex QUInt8 = False
isComplex QInt32 = False
isComplex BFloat16 = False
byteLength :: DType -> Int
byteLength dtype =
case dtype of
Bool -> 1
UInt8 -> 1
Int8 -> 1
Int16 -> 2
Int32 -> 4
Int64 -> 8
Half -> 2
Float -> 4
Double -> 8
ComplexHalf -> 4
ComplexFloat -> 8
ComplexDouble -> 16
QInt8 -> 1
QUInt8 -> 1
QInt32 -> 4
BFloat16 -> 2
| null | https://raw.githubusercontent.com/hasktorch/hasktorch/4abfd12a22d0ac0161827e2b5b170762c08fba47/hasktorch/src/Torch/DType.hs | haskell | | Bool
| Byte
| Short
| Int
| Long
| Half
| Float
| Double
| ComplexFloat
| ComplexDouble
| QInt8
| QUInt8
| BFloat16 | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
module Torch.DType where
import Data.Complex
import qualified Numeric.Half as N
import Data.Int
import Data.Reflection
import Data.Word
import Torch.Internal.Class (Castable (..))
import qualified Torch.Internal.Const as ATen
import qualified Torch.Internal.Type as ATen
data DType
Bool
UInt8
|
Int8
Int16
Int32
Int64
Half
Float
Double
| ComplexHalf
ComplexHalf
ComplexFloat
ComplexDouble
QInt8
QUInt8
|
QInt32
BFloat16
deriving (Eq, Show, Read)
instance Reifies Bool DType where
reflect _ = Bool
instance Reifies 'Bool DType where
reflect _ = Bool
instance Reifies Word8 DType where
reflect _ = UInt8
instance Reifies Int8 DType where
reflect _ = Int8
instance Reifies 'Int8 DType where
reflect _ = Int8
instance Reifies Int16 DType where
reflect _ = Int16
instance Reifies 'Int16 DType where
reflect _ = Int16
instance Reifies Int32 DType where
reflect _ = Int32
instance Reifies 'Int32 DType where
reflect _ = Int32
instance Reifies Int DType where
reflect _ = Int64
instance Reifies Int64 DType where
reflect _ = Int64
instance Reifies 'Int64 DType where
reflect _ = Int64
instance Reifies N.Half DType where
reflect _ = Half
instance Reifies 'Half DType where
reflect _ = Half
instance Reifies Float DType where
reflect _ = Float
instance Reifies 'Float DType where
reflect _ = Float
instance Reifies Double DType where
reflect _ = Double
instance Reifies 'Double DType where
reflect _ = Double
instance Reifies (Complex N.Half) DType where
reflect _ = ComplexHalf
instance Reifies 'ComplexHalf DType where
reflect _ = ComplexHalf
instance Reifies (Complex Float) DType where
reflect _ = ComplexFloat
instance Reifies 'ComplexFloat DType where
reflect _ = ComplexFloat
instance Reifies (Complex Double) DType where
reflect _ = ComplexDouble
instance Reifies 'ComplexDouble DType where
reflect _ = ComplexDouble
instance Castable DType ATen.ScalarType where
cast Bool f = f ATen.kBool
cast UInt8 f = f ATen.kByte
cast Int8 f = f ATen.kChar
cast Int16 f = f ATen.kShort
cast Int32 f = f ATen.kInt
cast Int64 f = f ATen.kLong
cast Half f = f ATen.kHalf
cast Float f = f ATen.kFloat
cast Double f = f ATen.kDouble
cast ComplexHalf f = f ATen.kComplexHalf
cast ComplexFloat f = f ATen.kComplexFloat
cast ComplexDouble f = f ATen.kComplexDouble
cast QInt8 f = f ATen.kQInt8
cast QUInt8 f = f ATen.kQUInt8
cast QInt32 f = f ATen.kQInt32
cast BFloat16 f = f ATen.kBFloat16
uncast x f
| x == ATen.kBool = f Bool
| x == ATen.kByte = f UInt8
| x == ATen.kChar = f Int8
| x == ATen.kShort = f Int16
| x == ATen.kInt = f Int32
| x == ATen.kLong = f Int64
| x == ATen.kHalf = f Half
| x == ATen.kFloat = f Float
| x == ATen.kDouble = f Double
| x == ATen.kComplexHalf = f ComplexHalf
| x == ATen.kComplexFloat = f ComplexFloat
| x == ATen.kComplexDouble = f ComplexDouble
| x == ATen.kQInt8 = f QInt8
| x == ATen.kQUInt8 = f QUInt8
| x == ATen.kQInt32 = f QInt32
| x == ATen.kBFloat16 = f BFloat16
isIntegral :: DType -> Bool
isIntegral Bool = True
isIntegral UInt8 = True
isIntegral Int8 = True
isIntegral Int16 = True
isIntegral Int32 = True
isIntegral Int64 = True
isIntegral Half = False
isIntegral Float = False
isIntegral Double = False
isIntegral ComplexHalf = False
isIntegral ComplexFloat = False
isIntegral ComplexDouble = False
isIntegral QInt8 = False
isIntegral QUInt8 = False
isIntegral QInt32 = False
isIntegral BFloat16 = False
isComplex :: DType -> Bool
isComplex Bool = False
isComplex UInt8 = False
isComplex Int8 = False
isComplex Int16 = False
isComplex Int32 = False
isComplex Int64 = False
isComplex Half = False
isComplex Float = False
isComplex Double = False
isComplex ComplexHalf = True
isComplex ComplexFloat = True
isComplex ComplexDouble = True
isComplex QInt8 = False
isComplex QUInt8 = False
isComplex QInt32 = False
isComplex BFloat16 = False
byteLength :: DType -> Int
byteLength dtype =
case dtype of
Bool -> 1
UInt8 -> 1
Int8 -> 1
Int16 -> 2
Int32 -> 4
Int64 -> 8
Half -> 2
Float -> 4
Double -> 8
ComplexHalf -> 4
ComplexFloat -> 8
ComplexDouble -> 16
QInt8 -> 1
QUInt8 -> 1
QInt32 -> 4
BFloat16 -> 2
|
1ad8f6af93a87f521bbca0e8141796ca2cbdb76cdfd44a27c3848b84d46d3665 | axelarge/advent-of-code | day13.clj | (ns advent-of-code.y2016.day13
(:require [advent-of-code.support :refer :all]
[clojure.string :as str])
(:import (java.util PriorityQueue)))
(def input (get-input 2016 13))
(defn wall? [n [x y]]
(or (neg? x)
(neg? y)
(odd? (bit-count (+ (* x (+ x 3 y y))
(* y (inc y))
n)))))
(defn draw
([n path]
(draw n path (map inc (reduce (partial map max) path))))
([n path [x y]]
(let [path (set path)]
(->> (for [y (range (inc y))]
(->> (for [x (range (inc x))]
(cond (wall? n [x y]) "\u2588"
(path [x y]) \.
:else \space))
(apply str)))
(str/join "\n")))))
(defn neighbors [[x y]]
(for [[dx dy] [[-1 0] [1 0] [0 -1] [0 1]]]
[(+ x dx) (+ y dy)]))
(defn explore
([pred n]
(explore pred [1 1] n))
([pred pos n]
(let [queue (PriorityQueue.)]
(loop [pos pos
d 1
visited #{}
path [pos]]
(->> (neighbors pos)
(remove #(wall? n %))
(remove visited)
(reduce (fn [q p]
(doto q (.add [d p (conj path p)])))
queue))
(when-let [[d pos path] (.poll queue)]
(if (pred d pos)
[d visited path]
(recur pos
(inc d)
(conj visited pos)
path)))))))
(defn solve1
([input] (solve1 input [31 39]))
([input target]
(->> (find-int input)
(explore (fn [d pos] (= pos target)))
(first))))
(defn solve2 [input]
(->> (find-int input)
(explore (fn [d pos] (> d 50)))
(second)
(count)))
| null | https://raw.githubusercontent.com/axelarge/advent-of-code/4c62a53ef71605780a22cf8219029453d8e1b977/src/advent_of_code/y2016/day13.clj | clojure | (ns advent-of-code.y2016.day13
(:require [advent-of-code.support :refer :all]
[clojure.string :as str])
(:import (java.util PriorityQueue)))
(def input (get-input 2016 13))
(defn wall? [n [x y]]
(or (neg? x)
(neg? y)
(odd? (bit-count (+ (* x (+ x 3 y y))
(* y (inc y))
n)))))
(defn draw
([n path]
(draw n path (map inc (reduce (partial map max) path))))
([n path [x y]]
(let [path (set path)]
(->> (for [y (range (inc y))]
(->> (for [x (range (inc x))]
(cond (wall? n [x y]) "\u2588"
(path [x y]) \.
:else \space))
(apply str)))
(str/join "\n")))))
(defn neighbors [[x y]]
(for [[dx dy] [[-1 0] [1 0] [0 -1] [0 1]]]
[(+ x dx) (+ y dy)]))
(defn explore
([pred n]
(explore pred [1 1] n))
([pred pos n]
(let [queue (PriorityQueue.)]
(loop [pos pos
d 1
visited #{}
path [pos]]
(->> (neighbors pos)
(remove #(wall? n %))
(remove visited)
(reduce (fn [q p]
(doto q (.add [d p (conj path p)])))
queue))
(when-let [[d pos path] (.poll queue)]
(if (pred d pos)
[d visited path]
(recur pos
(inc d)
(conj visited pos)
path)))))))
(defn solve1
([input] (solve1 input [31 39]))
([input target]
(->> (find-int input)
(explore (fn [d pos] (= pos target)))
(first))))
(defn solve2 [input]
(->> (find-int input)
(explore (fn [d pos] (> d 50)))
(second)
(count)))
| |
86ab8a9432c1d3693b8e78bb02f2536625ab61d26435b9abdbe8445222dbceb3 | OCamlPro/alt-ergo | zarithNumbers.ml | (******************************************************************************)
(* *)
(* The Alt-Ergo theorem prover *)
Copyright ( C ) 2006 - 2013
(* *)
(* *)
(* *)
CNRS - INRIA - Universite Paris Sud
(* *)
This file is distributed under the terms of the Apache Software
(* License version 2.0 *)
(* *)
(* ------------------------------------------------------------------------ *)
(* *)
Alt - Ergo : The SMT Solver For Software Verification
Copyright ( C ) 2013 - 2018
(* *)
This file is distributed under the terms of the Apache Software
(* License version 2.0 *)
(* *)
(******************************************************************************)
* Integers implementation . Based on Zarith 's integers *
module Z : NumbersInterface.ZSig with type t = Z.t = struct
type t = Z.t
let zero = Z.zero
let one = Z.one
let m_one = Z.minus_one
let compare a b = Z.compare a b
let compare_to_0 t = Z.sign t
let equal a b = Z.equal a b
let sign t = Z.sign t
let hash t = Z.hash t
let is_zero t = compare_to_0 t = 0
let is_one t = equal t one
let is_m_one t = equal t m_one
let add a b = Z.add a b
let sub a b = Z.sub a b
let mult a b = Z.mul a b
let div a b = assert (not (is_zero b)); Z.div a b
let rem a b = assert (not (is_zero b)); Z.rem a b
let div_rem a b = assert (not (is_zero b)); Z.div_rem a b
let minus t = Z.neg t
let abs t = Z.abs t
let max t1 t2 = Z.max t1 t2
let from_int n = Z.of_int n
let from_string s = Z.of_string s
let to_string t = Z.to_string t
let print fmt z = Format.fprintf fmt "%s" (to_string z)
let my_gcd a b =
if is_zero a then b
else if is_zero b then a
else Z.gcd a b
let my_lcm a b =
try
let res1 = Z.lcm a b in
assert (equal res1 (div (mult a b) (my_gcd a b)));
res1
with Division_by_zero -> assert false
let to_machine_int t =
try Some (Z.to_int t) with Z.Overflow -> None
(* These functuons are not exported, but they are used by module Q below *)
let to_float z = Z.to_float z
let fdiv z1 z2 = assert (not (is_zero z2)); Z.fdiv z1 z2
let cdiv z1 z2 = assert (not (is_zero z2)); Z.cdiv z1 z2
let power z n =
assert (n >= 0);
Z.pow z n
(* Shifts left by (n:int >= 0) bits. This is the same as t * pow(2,n) *)
let shift_left = Z.shift_left
(* returns sqrt truncated with the remainder. It assumes that the argument
is positive, otherwise, [Invalid_argument] is raised. *)
let sqrt_rem = Z.sqrt_rem
let testbit z n =
assert (n >= 0);
Z.testbit z n
let numbits = Z.numbits
end
* Rationals implementation . Based on Zarith 's rationals *
module Q : NumbersInterface.QSig with module Z = Z = struct
module Z = Z
exception Not_a_float
type t = Q.t
let num t = Q.num t
let den t = Q.den t
let zero = Q.zero
let one = Q.one
let m_one = Q.minus_one
let compare t1 t2 = Q.compare t1 t2
let compare_to_0 t = Q.sign t
let equal t1 t2 = Q.equal t1 t2
let sign t = Q.sign t
let hash t = 13 * Z.hash (num t) + 23 * Z.hash (den t)
let is_zero t = compare_to_0 t = 0
let is_one t = equal t one
let is_m_one t = equal t m_one
let is_int t = Z.is_one (den t)
let add t1 t2 = Q.add t1 t2
let sub t1 t2 = Q.sub t1 t2
let mult t1 t2 = Q.mul t1 t2
let div t1 t2 = assert (not (is_zero t2)); Q.div t1 t2
let minus t = Q.neg t
let abs t = Q.abs t
let min t1 t2 = Q.min t1 t2
let max t1 t2 = Q.max t1 t2
let inv t =
if Z.is_zero (num t) then raise Division_by_zero;
Q.inv t
let from_int n = Q.of_int n
let from_z z = Q.make z Z.one
let from_zz z1 z2 = Q.make z1 z2
let from_string s = Q.of_string s
let from_float f =
if f = infinity || f = neg_infinity then raise Not_a_float;
Q.of_float f
let to_string t = Q.to_string t
let to_z q = assert (is_int q); num q
let to_float t = (Z.to_float (num t)) /. (Z.to_float (den t))
let print fmt q = Format.fprintf fmt "%s" (to_string q)
let floor t = from_z (Z.fdiv (num t) (den t))
let ceiling t = from_z (Z.cdiv (num t) (den t))
let power t n =
let abs_n = Stdlib.abs n in
let num_pow = Z.power (num t) abs_n in
let den_pow = Z.power (den t) abs_n in
if n >= 0 then from_zz num_pow den_pow else from_zz den_pow num_pow
let modulo t1 t2 =
assert (is_int t1 && is_int t2);
from_zz (Z.rem (num t1) (num t2)) Z.one
(* converts the argument to an integer by truncation. *)
let truncate = Q.to_bigint
let mult_2exp = Q.mul_2exp
let div_2exp = Q.div_2exp
end
| null | https://raw.githubusercontent.com/OCamlPro/alt-ergo/291523151417f4cd112744d740b58ab1e8a630b4/src/lib/util/zarithNumbers.ml | ocaml | ****************************************************************************
The Alt-Ergo theorem prover
License version 2.0
------------------------------------------------------------------------
License version 2.0
****************************************************************************
These functuons are not exported, but they are used by module Q below
Shifts left by (n:int >= 0) bits. This is the same as t * pow(2,n)
returns sqrt truncated with the remainder. It assumes that the argument
is positive, otherwise, [Invalid_argument] is raised.
converts the argument to an integer by truncation. | Copyright ( C ) 2006 - 2013
CNRS - INRIA - Universite Paris Sud
This file is distributed under the terms of the Apache Software
Alt - Ergo : The SMT Solver For Software Verification
Copyright ( C ) 2013 - 2018
This file is distributed under the terms of the Apache Software
* Integers implementation . Based on Zarith 's integers *
module Z : NumbersInterface.ZSig with type t = Z.t = struct
type t = Z.t
let zero = Z.zero
let one = Z.one
let m_one = Z.minus_one
let compare a b = Z.compare a b
let compare_to_0 t = Z.sign t
let equal a b = Z.equal a b
let sign t = Z.sign t
let hash t = Z.hash t
let is_zero t = compare_to_0 t = 0
let is_one t = equal t one
let is_m_one t = equal t m_one
let add a b = Z.add a b
let sub a b = Z.sub a b
let mult a b = Z.mul a b
let div a b = assert (not (is_zero b)); Z.div a b
let rem a b = assert (not (is_zero b)); Z.rem a b
let div_rem a b = assert (not (is_zero b)); Z.div_rem a b
let minus t = Z.neg t
let abs t = Z.abs t
let max t1 t2 = Z.max t1 t2
let from_int n = Z.of_int n
let from_string s = Z.of_string s
let to_string t = Z.to_string t
let print fmt z = Format.fprintf fmt "%s" (to_string z)
let my_gcd a b =
if is_zero a then b
else if is_zero b then a
else Z.gcd a b
let my_lcm a b =
try
let res1 = Z.lcm a b in
assert (equal res1 (div (mult a b) (my_gcd a b)));
res1
with Division_by_zero -> assert false
let to_machine_int t =
try Some (Z.to_int t) with Z.Overflow -> None
let to_float z = Z.to_float z
let fdiv z1 z2 = assert (not (is_zero z2)); Z.fdiv z1 z2
let cdiv z1 z2 = assert (not (is_zero z2)); Z.cdiv z1 z2
let power z n =
assert (n >= 0);
Z.pow z n
let shift_left = Z.shift_left
let sqrt_rem = Z.sqrt_rem
let testbit z n =
assert (n >= 0);
Z.testbit z n
let numbits = Z.numbits
end
* Rationals implementation . Based on Zarith 's rationals *
module Q : NumbersInterface.QSig with module Z = Z = struct
module Z = Z
exception Not_a_float
type t = Q.t
let num t = Q.num t
let den t = Q.den t
let zero = Q.zero
let one = Q.one
let m_one = Q.minus_one
let compare t1 t2 = Q.compare t1 t2
let compare_to_0 t = Q.sign t
let equal t1 t2 = Q.equal t1 t2
let sign t = Q.sign t
let hash t = 13 * Z.hash (num t) + 23 * Z.hash (den t)
let is_zero t = compare_to_0 t = 0
let is_one t = equal t one
let is_m_one t = equal t m_one
let is_int t = Z.is_one (den t)
let add t1 t2 = Q.add t1 t2
let sub t1 t2 = Q.sub t1 t2
let mult t1 t2 = Q.mul t1 t2
let div t1 t2 = assert (not (is_zero t2)); Q.div t1 t2
let minus t = Q.neg t
let abs t = Q.abs t
let min t1 t2 = Q.min t1 t2
let max t1 t2 = Q.max t1 t2
let inv t =
if Z.is_zero (num t) then raise Division_by_zero;
Q.inv t
let from_int n = Q.of_int n
let from_z z = Q.make z Z.one
let from_zz z1 z2 = Q.make z1 z2
let from_string s = Q.of_string s
let from_float f =
if f = infinity || f = neg_infinity then raise Not_a_float;
Q.of_float f
let to_string t = Q.to_string t
let to_z q = assert (is_int q); num q
let to_float t = (Z.to_float (num t)) /. (Z.to_float (den t))
let print fmt q = Format.fprintf fmt "%s" (to_string q)
let floor t = from_z (Z.fdiv (num t) (den t))
let ceiling t = from_z (Z.cdiv (num t) (den t))
let power t n =
let abs_n = Stdlib.abs n in
let num_pow = Z.power (num t) abs_n in
let den_pow = Z.power (den t) abs_n in
if n >= 0 then from_zz num_pow den_pow else from_zz den_pow num_pow
let modulo t1 t2 =
assert (is_int t1 && is_int t2);
from_zz (Z.rem (num t1) (num t2)) Z.one
let truncate = Q.to_bigint
let mult_2exp = Q.mul_2exp
let div_2exp = Q.div_2exp
end
|
4bb4c242e2035329c48791f387ba6919912ad30454feea2046c59d45951eefd1 | tjammer/raylib-ocaml | models_mesh_generation.ml | open Raylib
let get f i a = Raylib.CArray.get (f a) i
let ( %. ) = Fun.flip
let make_mesh () =
let of_list l = CArray.of_list Ctypes.float l in
let mesh = Mesh.create () in
Mesh.set_triangle_count mesh 1;
Mesh.set_vertex_count mesh 3;
Mesh.set_vertices mesh
(of_list [ 0.0; 0.0; 0.0; 1.0; 0.0; 2.0; 2.0; 0.0; 0.0 ]);
Mesh.set_normals mesh
(of_list [ 0.0; 1.0; 0.0; 0.0; 1.0; 0.0; 0.0; 1.0; 0.0 ]);
Mesh.set_texcoords mesh (of_list [ 0.0; 0.0; 0.5; 1.0; 1.0; 0.0 ]);
upload_mesh (addr mesh) false;
mesh
let setup () =
init_window 800 450 "raylib [models] expamle - mesh generation";
let checked = gen_image_checked 2 2 1 1 Color.red Color.green in
let texture = load_texture_from_image checked in
unload_image checked;
let models =
[|
load_model_from_mesh (gen_mesh_plane 2.0 2.0 5 5);
load_model_from_mesh (gen_mesh_cube 2.0 1.0 2.0);
load_model_from_mesh (gen_mesh_sphere 2.0 32 32);
load_model_from_mesh (gen_mesh_hemi_sphere 2.0 16 16);
load_model_from_mesh (gen_mesh_cylinder 1.0 2.0 16);
load_model_from_mesh (gen_mesh_torus 0.25 4.0 16 32);
load_model_from_mesh (gen_mesh_knot 1.0 2.0 16 128);
load_model_from_mesh (gen_mesh_poly 5 2.0);
load_model_from_mesh (make_mesh ());
|]
in
Array.iter
(fun model ->
model |> get Model.materials 0
|> get Material.maps MaterialMapIndex.(to_int Albedo)
|> MaterialMap.set_texture %. texture)
models;
let camera =
Camera.create
(Vector3.create 5.0 5.0 5.0)
(Vector3.create 0.0 0.0 0.0)
(Vector3.create 0.0 1.0 0.0)
45.0 CameraProjection.Perspective
in
let position = Vector3.create 0.0 0.0 0.0 in
set_camera_mode camera CameraMode.Orbital;
set_target_fps 60;
(texture, models, camera, position, ref 0)
let rec loop ((texture, models, camera, position, curr_model) as args) =
if window_should_close () then (
unload_texture texture;
Array.iter unload_model models;
close_window ())
else (
update_camera (addr camera);
if is_mouse_button_pressed MouseButton.Left || is_key_pressed Key.Right then
curr_model := (!curr_model + 1) mod Array.length models;
if is_key_pressed Key.Left then
curr_model :=
if !curr_model < 1 then Array.length models - 1 else !curr_model - 1;
begin_drawing ();
clear_background Color.raywhite;
begin_mode_3d camera;
draw_model models.(!curr_model) position 1.0 Color.white;
draw_grid 10 1.0;
end_mode_3d ();
draw_rectangle 30 400 310 30 (fade Color.skyblue 0.5);
draw_rectangle_lines 30 400 310 30 (fade Color.darkblue 0.5);
draw_text "MOUSE LEFT BUTTON to CYCLE PROCEDURAL MODELS" 40 410 10
Color.blue;
(match !curr_model with
| 0 -> draw_text "PLANE" 680 10 20 Color.darkblue
| 1 -> draw_text "CUBE" 680 10 20 Color.darkblue
| 2 -> draw_text "SPHERE" 680 10 20 Color.darkblue
| 3 -> draw_text "HEMISPHERE" 680 10 20 Color.darkblue
| 4 -> draw_text "CYLINDER" 680 10 20 Color.darkblue
| 5 -> draw_text "TORUS" 680 10 20 Color.darkblue
| 6 -> draw_text "KNOT" 680 10 20 Color.darkblue
| 7 -> draw_text "POLY" 680 10 20 Color.darkblue
| 8 -> draw_text "Parametric(custom)" 580 10 20 Color.darkblue
| _ -> ());
end_drawing ();
loop args)
let () = setup () |> loop
| null | https://raw.githubusercontent.com/tjammer/raylib-ocaml/76955c30d0a776138daeb93bfc73b104aefc6f6d/examples/models/models_mesh_generation.ml | ocaml | open Raylib
let get f i a = Raylib.CArray.get (f a) i
let ( %. ) = Fun.flip
let make_mesh () =
let of_list l = CArray.of_list Ctypes.float l in
let mesh = Mesh.create () in
Mesh.set_triangle_count mesh 1;
Mesh.set_vertex_count mesh 3;
Mesh.set_vertices mesh
(of_list [ 0.0; 0.0; 0.0; 1.0; 0.0; 2.0; 2.0; 0.0; 0.0 ]);
Mesh.set_normals mesh
(of_list [ 0.0; 1.0; 0.0; 0.0; 1.0; 0.0; 0.0; 1.0; 0.0 ]);
Mesh.set_texcoords mesh (of_list [ 0.0; 0.0; 0.5; 1.0; 1.0; 0.0 ]);
upload_mesh (addr mesh) false;
mesh
let setup () =
init_window 800 450 "raylib [models] expamle - mesh generation";
let checked = gen_image_checked 2 2 1 1 Color.red Color.green in
let texture = load_texture_from_image checked in
unload_image checked;
let models =
[|
load_model_from_mesh (gen_mesh_plane 2.0 2.0 5 5);
load_model_from_mesh (gen_mesh_cube 2.0 1.0 2.0);
load_model_from_mesh (gen_mesh_sphere 2.0 32 32);
load_model_from_mesh (gen_mesh_hemi_sphere 2.0 16 16);
load_model_from_mesh (gen_mesh_cylinder 1.0 2.0 16);
load_model_from_mesh (gen_mesh_torus 0.25 4.0 16 32);
load_model_from_mesh (gen_mesh_knot 1.0 2.0 16 128);
load_model_from_mesh (gen_mesh_poly 5 2.0);
load_model_from_mesh (make_mesh ());
|]
in
Array.iter
(fun model ->
model |> get Model.materials 0
|> get Material.maps MaterialMapIndex.(to_int Albedo)
|> MaterialMap.set_texture %. texture)
models;
let camera =
Camera.create
(Vector3.create 5.0 5.0 5.0)
(Vector3.create 0.0 0.0 0.0)
(Vector3.create 0.0 1.0 0.0)
45.0 CameraProjection.Perspective
in
let position = Vector3.create 0.0 0.0 0.0 in
set_camera_mode camera CameraMode.Orbital;
set_target_fps 60;
(texture, models, camera, position, ref 0)
let rec loop ((texture, models, camera, position, curr_model) as args) =
if window_should_close () then (
unload_texture texture;
Array.iter unload_model models;
close_window ())
else (
update_camera (addr camera);
if is_mouse_button_pressed MouseButton.Left || is_key_pressed Key.Right then
curr_model := (!curr_model + 1) mod Array.length models;
if is_key_pressed Key.Left then
curr_model :=
if !curr_model < 1 then Array.length models - 1 else !curr_model - 1;
begin_drawing ();
clear_background Color.raywhite;
begin_mode_3d camera;
draw_model models.(!curr_model) position 1.0 Color.white;
draw_grid 10 1.0;
end_mode_3d ();
draw_rectangle 30 400 310 30 (fade Color.skyblue 0.5);
draw_rectangle_lines 30 400 310 30 (fade Color.darkblue 0.5);
draw_text "MOUSE LEFT BUTTON to CYCLE PROCEDURAL MODELS" 40 410 10
Color.blue;
(match !curr_model with
| 0 -> draw_text "PLANE" 680 10 20 Color.darkblue
| 1 -> draw_text "CUBE" 680 10 20 Color.darkblue
| 2 -> draw_text "SPHERE" 680 10 20 Color.darkblue
| 3 -> draw_text "HEMISPHERE" 680 10 20 Color.darkblue
| 4 -> draw_text "CYLINDER" 680 10 20 Color.darkblue
| 5 -> draw_text "TORUS" 680 10 20 Color.darkblue
| 6 -> draw_text "KNOT" 680 10 20 Color.darkblue
| 7 -> draw_text "POLY" 680 10 20 Color.darkblue
| 8 -> draw_text "Parametric(custom)" 580 10 20 Color.darkblue
| _ -> ());
end_drawing ();
loop args)
let () = setup () |> loop
| |
676d2029f93a43a7f5a863d92a19b72a19436631f7bcabb5a5590a5e31c3dd35 | justinkirby/handlebar | handlebar_out.erl | -module(handlebar_out).
-export([
output/2
]).
-include("handlebar.hrl").
output(Template, Data) ->
?DEBUG("HANDLING ~p->~p~n",[Template,Data]),
we can do one of three things
1 . stdout
2 . filename ( append or overwrite ? )
3 . dir / filename
%% is outdir specified?
case handlebar_config:get_global(outdir,undefined) of
undefined ->
%% is outfile specified?
case handlebar_config:get_global(outfile, undefined) of
undefined ->
%% nothing specified, dump straight to stdout
file:write(standard_io, Data);
File ->
output_file(File, Data)
end;
Dir ->
output_dir(Dir, Template, Data)
end.
output_file(File, Data) ->
case filelib:ensure_dir(File) of
{error, Reason} ->
?ERROR("Can not ensure dir for file ~p:~p~n",[File, Reason]);
ok ->
case file:write_file(File, Data) of
{error, Reason2} ->
?ERROR("write error for ~p~n~p~n",[File, Reason2]);
ok -> ok
end
end.
output_dir(Dir, Template, Data) ->
FName = filename:rootname(filename:basename(Template)),
FullPath = filename:join([Dir,FName]),
?DEBUG("OUTPUT:~p~n",[FullPath]),
output_file(FullPath, Data).
| null | https://raw.githubusercontent.com/justinkirby/handlebar/330abd32841e6428d4e45f86d8af07a605176049/src/handlebar_out.erl | erlang | is outdir specified?
is outfile specified?
nothing specified, dump straight to stdout | -module(handlebar_out).
-export([
output/2
]).
-include("handlebar.hrl").
output(Template, Data) ->
?DEBUG("HANDLING ~p->~p~n",[Template,Data]),
we can do one of three things
1 . stdout
2 . filename ( append or overwrite ? )
3 . dir / filename
case handlebar_config:get_global(outdir,undefined) of
undefined ->
case handlebar_config:get_global(outfile, undefined) of
undefined ->
file:write(standard_io, Data);
File ->
output_file(File, Data)
end;
Dir ->
output_dir(Dir, Template, Data)
end.
output_file(File, Data) ->
case filelib:ensure_dir(File) of
{error, Reason} ->
?ERROR("Can not ensure dir for file ~p:~p~n",[File, Reason]);
ok ->
case file:write_file(File, Data) of
{error, Reason2} ->
?ERROR("write error for ~p~n~p~n",[File, Reason2]);
ok -> ok
end
end.
output_dir(Dir, Template, Data) ->
FName = filename:rootname(filename:basename(Template)),
FullPath = filename:join([Dir,FName]),
?DEBUG("OUTPUT:~p~n",[FullPath]),
output_file(FullPath, Data).
|
bebcd49323eef1efd3c5755a6ed12a8ca67399fa5de8de3d00d80f974f426f8c | Perry961002/SICP | exa2.3.3-set.scm | 集合作为未排序的表
(define (element-of-set? x set)
(cond ((null? set) #f)
((equal? x (car set)) #t)
(else (element-of-set? x (cdr set)))))
(define (adjoin-set x set)
(if (element-of-set? x set)
set
(cons x set)))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1)
(intersection-set (cdr set1) set2)))
(else (intersection-set (cdr set1) set2))))
;-------------------------------------------------------------------
;对于有序集合的element-of-set?操作
(define (element-of-set? x set)
(cond ((null? set) #f)
((= x (car set)) #t)
((< x (car set)) #f)
(else (element-of-set? x (cdr set)))))
;对于有序集合的intersection-set操作
(define (intersection-set set1 set2)
(if (or (null? set1) (null? set2))
'()
(let ((x1 (car set1)) (x2 (car set2)))
(cond ((= x1 x2)
(cons x1
(intersection-set (cdr set1) (cdr set2))))
((< x1 x2)
(intersection-set (cdr set1) set2))
((< x2 x1)
(intersection-set set1 (cdr set2)))))))
;-------------------------------------------------------------------------
;集合作为二叉树(BST)
;用空表作为左子树或者右子树,就表示没有子树连接在那里
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right)
(list entry left right))
(define (element-of-set? x tree)
(cond ((null? tree) #f)
((= x (entry tree)) #t)
((< x (entry tree))
(element-of-set? x (left-branch tree)))
((> x (entry tree))
(element-of-set? x (right-branch tree)))))
插入节点
(define (adjoin-set x tree)
(cond ((null? tree) (make-tree x '() '()))
((= x (entry tree)) tree)
((< x (entry tree))
(make-tree (entry tree)
(adjoin-set x (left-branch tree))
(right-branch tree)))
((> x (entry tree))
(make-tree (entry tree)
(left-branch tree)
(adjoin-set x (right-branch tree))))))
;-----------------------------------------------------------------------------
;集合与信息检索
(define (lookup given-key set-of-records)
(cond ((null? set-of-records) #f)
((equal? given-key (key (car set-of-records)))
(car set-of-records))
(else (lookup given-key (cdr set-of-records))))) | null | https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap2/example/exa2.3.3-set.scm | scheme | -------------------------------------------------------------------
对于有序集合的element-of-set?操作
对于有序集合的intersection-set操作
-------------------------------------------------------------------------
集合作为二叉树(BST)
用空表作为左子树或者右子树,就表示没有子树连接在那里
-----------------------------------------------------------------------------
集合与信息检索 | 集合作为未排序的表
(define (element-of-set? x set)
(cond ((null? set) #f)
((equal? x (car set)) #t)
(else (element-of-set? x (cdr set)))))
(define (adjoin-set x set)
(if (element-of-set? x set)
set
(cons x set)))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1)
(intersection-set (cdr set1) set2)))
(else (intersection-set (cdr set1) set2))))
(define (element-of-set? x set)
(cond ((null? set) #f)
((= x (car set)) #t)
((< x (car set)) #f)
(else (element-of-set? x (cdr set)))))
(define (intersection-set set1 set2)
(if (or (null? set1) (null? set2))
'()
(let ((x1 (car set1)) (x2 (car set2)))
(cond ((= x1 x2)
(cons x1
(intersection-set (cdr set1) (cdr set2))))
((< x1 x2)
(intersection-set (cdr set1) set2))
((< x2 x1)
(intersection-set set1 (cdr set2)))))))
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right)
(list entry left right))
(define (element-of-set? x tree)
(cond ((null? tree) #f)
((= x (entry tree)) #t)
((< x (entry tree))
(element-of-set? x (left-branch tree)))
((> x (entry tree))
(element-of-set? x (right-branch tree)))))
插入节点
(define (adjoin-set x tree)
(cond ((null? tree) (make-tree x '() '()))
((= x (entry tree)) tree)
((< x (entry tree))
(make-tree (entry tree)
(adjoin-set x (left-branch tree))
(right-branch tree)))
((> x (entry tree))
(make-tree (entry tree)
(left-branch tree)
(adjoin-set x (right-branch tree))))))
(define (lookup given-key set-of-records)
(cond ((null? set-of-records) #f)
((equal? given-key (key (car set-of-records)))
(car set-of-records))
(else (lookup given-key (cdr set-of-records))))) |
84d4e42ae97ddee4f09e5ca096404b51f0a96caa0b8e0637d2549a4e4fbd2863 | mars0i/masonclj | project.clj | (defproject mars0i/masonclj "0.2.0"
:description "masonclj is a small library providing functions and macros
to make it easier to use the MASON ABM library in Clojure."
:url ""
:license {:name "LGPL 3.0"
:url ""}
:deploy-repositories {"clojars"
{:url "" :sign-releases false}}
:dependencies [[org.clojure/clojure "1.10.0"]]
:repl-options {:init-ns masonclj.core}
)
| null | https://raw.githubusercontent.com/mars0i/masonclj/976eb9460076629d31c7b00a97dcff62ea1e7791/project.clj | clojure | (defproject mars0i/masonclj "0.2.0"
:description "masonclj is a small library providing functions and macros
to make it easier to use the MASON ABM library in Clojure."
:url ""
:license {:name "LGPL 3.0"
:url ""}
:deploy-repositories {"clojars"
{:url "" :sign-releases false}}
:dependencies [[org.clojure/clojure "1.10.0"]]
:repl-options {:init-ns masonclj.core}
)
| |
d58848dc66819d5508832e33a982e6ff635ae844bb977bb3f8d109876637b71c | cnuernber/dtype-next | const_reader.clj | (ns tech.v3.datatype.const-reader
(:require [tech.v3.datatype.protocols :as dtype-proto]
[tech.v3.datatype.casting :as casting]
[tech.v3.datatype.monotonic-range :as monotonic-range]
[ham-fisted.api :as hamf])
(:import [tech.v3.datatype ObjectReader LongReader DoubleReader Buffer
BooleanReader]
[ham_fisted Casts ChunkedList Transformables]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn make-single-elem-range
[elem]
(let [elem (long (casting/cast elem :int64))]
(monotonic-range/make-range
elem
(unchecked-inc elem))))
(defn const-reader
"Create a new reader that only returns the item for the provided indexes."
(^Buffer [item n-elems]
(let [item-dtype (if item (dtype-proto/elemwise-datatype item) :object)
n-elems (long n-elems)]
(cond
(identical? :boolean item-dtype)
(let [item (Casts/booleanCast item)]
(reify BooleanReader
(elemwiseDatatype [rdr] item-dtype)
(lsize [rdr] n-elems)
(readObject [rdr idx] item)
(subBuffer [rdr sidx eidx]
(ChunkedList/sublistCheck sidx eidx n-elems)
(const-reader item (- eidx sidx)))
(reduce [this rfn init]
(loop [init init
idx 0]
(if (and (< idx n-elems) (not (reduced? init)))
(recur (rfn init item) (unchecked-inc idx))
init)))
dtype-proto/PElemwiseReaderCast
(elemwise-reader-cast [rdr new-dtype] rdr)
dtype-proto/PConstantTimeMinMax
(has-constant-time-min-max? [this] true)
(constant-time-min [this] item)
(constant-time-max [this] item)
))
(casting/integer-type? item-dtype)
(let [item (long item)]
(reify LongReader
(elemwiseDatatype [rdr] item-dtype)
(lsize [rdr] n-elems)
(readLong [rdr idx] item)
(subBuffer [rdr sidx eidx]
(ChunkedList/sublistCheck sidx eidx n-elems)
(const-reader item (- eidx sidx)))
(reduce [this rfn init]
(let [rfn (Transformables/toLongReductionFn rfn)]
(loop [init init
idx 0]
(if (and (< idx n-elems) (not (reduced? init)))
(recur (.invokePrim rfn init item) (unchecked-inc idx))
init))))
dtype-proto/PElemwiseReaderCast
(elemwise-reader-cast [rdr new-dtype] rdr)
dtype-proto/PConstantTimeMinMax
(has-constant-time-min-max? [this] true)
(constant-time-min [this] item)
(constant-time-max [this] item)
dtype-proto/PRangeConvertible
(convertible-to-range? [this] (== 1 n-elems))
(->range [this options] (hamf/range item (unchecked-inc item)))
))
(casting/float-type? item-dtype)
(let [item (double item)]
(reify DoubleReader
(elemwiseDatatype [rdr] item-dtype)
(lsize [rdr] n-elems)
(readDouble [rdr idx] item)
(subBuffer [rdr sidx eidx]
(ChunkedList/sublistCheck sidx eidx n-elems)
(const-reader item (- eidx sidx)))
(reduce [this rfn init]
(let [rfn (Transformables/toDoubleReductionFn rfn)]
(loop [init init
idx 0]
(if (and (< idx n-elems) (not (reduced? init)))
(recur (.invokePrim rfn init item) (unchecked-inc idx))
init))))
dtype-proto/PElemwiseReaderCast
(elemwise-reader-cast [rdr new-dtype] rdr)
dtype-proto/PConstantTimeMinMax
(has-constant-time-min-max? [this] true)
(constant-time-min [this] item)
(constant-time-max [this] item)
dtype-proto/PRangeConvertible
(convertible-to-range? [this] (== 1 n-elems))
(->range [this options] (hamf/range item (+ item 1.0)))))
:else
(reify ObjectReader
(elemwiseDatatype [rdr] item-dtype)
(lsize [rdr] n-elems)
(readObject [rdr _idx] item)
(subBuffer [rdr sidx eidx]
(ChunkedList/sublistCheck sidx eidx n-elems)
(const-reader item (- eidx sidx)))
(reduce [this rfn init]
(loop [init init
idx 0]
(if (and (< idx n-elems) (not (reduced? init)))
(recur (rfn init item) (unchecked-inc idx))
init)))
dtype-proto/PElemwiseReaderCast
(elemwise-reader-cast [rdr new-dtype] rdr)
dtype-proto/PConstantTimeMinMax
(has-constant-time-min-max? [this] true)
(constant-time-min [this] item)
(constant-time-max [this] item)
dtype-proto/PRangeConvertible
(convertible-to-range? [this]
(and (== 1 n-elems)
(instance? Number item)))
(->range [this options]
(make-single-elem-range item)))))))
| null | https://raw.githubusercontent.com/cnuernber/dtype-next/99079b733d519dbfebb2b5da79419800597edd7c/src/tech/v3/datatype/const_reader.clj | clojure | (ns tech.v3.datatype.const-reader
(:require [tech.v3.datatype.protocols :as dtype-proto]
[tech.v3.datatype.casting :as casting]
[tech.v3.datatype.monotonic-range :as monotonic-range]
[ham-fisted.api :as hamf])
(:import [tech.v3.datatype ObjectReader LongReader DoubleReader Buffer
BooleanReader]
[ham_fisted Casts ChunkedList Transformables]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn make-single-elem-range
[elem]
(let [elem (long (casting/cast elem :int64))]
(monotonic-range/make-range
elem
(unchecked-inc elem))))
(defn const-reader
"Create a new reader that only returns the item for the provided indexes."
(^Buffer [item n-elems]
(let [item-dtype (if item (dtype-proto/elemwise-datatype item) :object)
n-elems (long n-elems)]
(cond
(identical? :boolean item-dtype)
(let [item (Casts/booleanCast item)]
(reify BooleanReader
(elemwiseDatatype [rdr] item-dtype)
(lsize [rdr] n-elems)
(readObject [rdr idx] item)
(subBuffer [rdr sidx eidx]
(ChunkedList/sublistCheck sidx eidx n-elems)
(const-reader item (- eidx sidx)))
(reduce [this rfn init]
(loop [init init
idx 0]
(if (and (< idx n-elems) (not (reduced? init)))
(recur (rfn init item) (unchecked-inc idx))
init)))
dtype-proto/PElemwiseReaderCast
(elemwise-reader-cast [rdr new-dtype] rdr)
dtype-proto/PConstantTimeMinMax
(has-constant-time-min-max? [this] true)
(constant-time-min [this] item)
(constant-time-max [this] item)
))
(casting/integer-type? item-dtype)
(let [item (long item)]
(reify LongReader
(elemwiseDatatype [rdr] item-dtype)
(lsize [rdr] n-elems)
(readLong [rdr idx] item)
(subBuffer [rdr sidx eidx]
(ChunkedList/sublistCheck sidx eidx n-elems)
(const-reader item (- eidx sidx)))
(reduce [this rfn init]
(let [rfn (Transformables/toLongReductionFn rfn)]
(loop [init init
idx 0]
(if (and (< idx n-elems) (not (reduced? init)))
(recur (.invokePrim rfn init item) (unchecked-inc idx))
init))))
dtype-proto/PElemwiseReaderCast
(elemwise-reader-cast [rdr new-dtype] rdr)
dtype-proto/PConstantTimeMinMax
(has-constant-time-min-max? [this] true)
(constant-time-min [this] item)
(constant-time-max [this] item)
dtype-proto/PRangeConvertible
(convertible-to-range? [this] (== 1 n-elems))
(->range [this options] (hamf/range item (unchecked-inc item)))
))
(casting/float-type? item-dtype)
(let [item (double item)]
(reify DoubleReader
(elemwiseDatatype [rdr] item-dtype)
(lsize [rdr] n-elems)
(readDouble [rdr idx] item)
(subBuffer [rdr sidx eidx]
(ChunkedList/sublistCheck sidx eidx n-elems)
(const-reader item (- eidx sidx)))
(reduce [this rfn init]
(let [rfn (Transformables/toDoubleReductionFn rfn)]
(loop [init init
idx 0]
(if (and (< idx n-elems) (not (reduced? init)))
(recur (.invokePrim rfn init item) (unchecked-inc idx))
init))))
dtype-proto/PElemwiseReaderCast
(elemwise-reader-cast [rdr new-dtype] rdr)
dtype-proto/PConstantTimeMinMax
(has-constant-time-min-max? [this] true)
(constant-time-min [this] item)
(constant-time-max [this] item)
dtype-proto/PRangeConvertible
(convertible-to-range? [this] (== 1 n-elems))
(->range [this options] (hamf/range item (+ item 1.0)))))
:else
(reify ObjectReader
(elemwiseDatatype [rdr] item-dtype)
(lsize [rdr] n-elems)
(readObject [rdr _idx] item)
(subBuffer [rdr sidx eidx]
(ChunkedList/sublistCheck sidx eidx n-elems)
(const-reader item (- eidx sidx)))
(reduce [this rfn init]
(loop [init init
idx 0]
(if (and (< idx n-elems) (not (reduced? init)))
(recur (rfn init item) (unchecked-inc idx))
init)))
dtype-proto/PElemwiseReaderCast
(elemwise-reader-cast [rdr new-dtype] rdr)
dtype-proto/PConstantTimeMinMax
(has-constant-time-min-max? [this] true)
(constant-time-min [this] item)
(constant-time-max [this] item)
dtype-proto/PRangeConvertible
(convertible-to-range? [this]
(and (== 1 n-elems)
(instance? Number item)))
(->range [this options]
(make-single-elem-range item)))))))
| |
cb68c41776b24e5633ba1e8f0235d2c211ffa371f516f06690ad759ea31f75a4 | kunstmusik/pink | horn.clj | (ns pink.instruments.horn
"Implementation of Andrew Horner and Lydia Ayer's French Horn models using
banded wavetable synthesis. Based on the Csound code implementaiton."
(:require [pink.util :refer :all]
[pink.config :refer [*buffer-size* *current-buffer-num* *sr*]]
[pink.envelopes :refer :all]
[pink.gen :refer [gen9 gen17]]
[pink.oscillators :refer :all]
[pink.filters :refer [tone atone]]
[pink.space :refer [pan]]
[pink.dynamics :refer [balance]]
))
;; Ensure unchecked math used for this namespace
(set! *unchecked-math* :warn-on-boxed)
(def ^:const ^:private ^{:tag 'long}
hwt-size 4096)
(def ^:const ^:private ^{:tag 'long}
horn-cutoff 2560)
;; TABLES
( def horn - cutoff [ 40 40 80 160 320 640 1280 2560 5120 10240 10240 ] )
format : note - freq - max adjustment table0 [ table1 table2 ]
(def horn-wave-tables
[
[85
52.476
sine-table
(gen9 hwt-size [2 6.236] [3 12.827])
(gen9 hwt-size [4 21.591] [5 11.401] [6 3.570] [7 2.833])
(gen9 hwt-size [8 3.070] [9 1.053] [10 0.773] [11 1.349] [12 0.819]
[13 0.369] [14 0.362] [15 0.165] [16 0.124] [18 0.026] [19 0.042])]
[114
18.006
sine-table
(gen9 hwt-size [2 3.236] [3 6.827])
(gen9 hwt-size [4 5.591] [5 2.401] [6 1.870] [7 0.733])
(gen9 hwt-size [8 0.970] [9 0.553] [10 0.373] [11 0.549] [12 0.319]
[13 0.119] [14 0.092] [15 0.045] [16 0.034])]
[153
11.274
sine-table
(gen9 hwt-size [2 5.019] [3 4.281])
(gen9 hwt-size [4 2.091] [5 1.001] [6 0.670] [7 0.233])
(gen9 hwt-size [8 0.200] [9 0.103] [10 0.073] [11 0.089] [12 0.059]
[13 0.029])]
[204
6.955
sine-table
(gen9 hwt-size [2 4.712] [3 1.847])
(gen9 hwt-size [4 0.591] [5 0.401] [6 0.270] [7 0.113])
(gen9 hwt-size [8 0.060] [9 0.053] [10 0.023])]
[272
2.260
sine-table
(gen9 hwt-size [2 1.512] [3 0.247])
(gen9 hwt-size [4 0.121] [5 0.101] [6 0.030] [7 0.053])
(gen9 hwt-size [8 0.030])]
[364
1.171
sine-table
(gen9 hwt-size [2 0.412] [3 0.087])
(gen9 hwt-size [4 0.071] [5 0.021])]
[486
1.106
sine-table
(gen9 hwt-size [2 0.309] [3 0.067])
(gen9 hwt-size [4 0.031])]
[Integer/MAX_VALUE
1.019
sine-table
(gen9 hwt-size [2 0.161] [3 0.047])]
])
( def horn - stopped - cutoff [ 40 40 80 160 320 640 1280 2560 5120 10240 10240 ] )
(def horn-stopped-wave-tables
[
[272
3.172
sine-table
(gen9 hwt-size [2 0.961] [3 0.052])
(gen9 hwt-size [4 0.079] [5 0.137] [6 0.185] [7 0.109])
(gen9 hwt-size [8 0.226] [9 0.107] [10 0.155] [11 0.140] [12 0.428]
[13 0.180] [15 0.070] [16 0.335] [17 0.183] [18 0.073] [19 0.172]
[20 0.117] [21 0.089] [22 0.193] [23 0.119] [24 0.080] [25 0.36]
[26 0.143] [27 0.036] [28 0.044] [29 0.040] [30 0.052] [31 0.086]
[32 0.067] [33 0.097] [34 0.046] [36 0.030] [37 0.025] [38 0.048]
[39 0.021] [40 0.025])]
[363
1.947
sine-table
(gen9 hwt-size [2 0.162] [3 0.068])
(gen9 hwt-size [4 0.116] [5 0.13] [6 0.050] [7 0.089])
(gen9 hwt-size [8 0.156] [9 0.381] [10 0.191] [11 0.126] [12 0.162]
[13 0.073] [15 0.157] [16 0.074] [17 0.087] [18 0.151] [19 0.093]
[20 0.031] [21 0.030] [22 0.051] [23 0.058] [24 0.051] [25 0.077]
[26 0.033] [27 0.021] [28 0.039])]
[484
2.221
sine-table
(gen9 hwt-size [2 0.164] [3 0.164])
(gen9 hwt-size [4 0.401] [5 0.141] [6 0.293] [7 0.203])
(gen9 hwt-size [8 0.170] [9 0.306] [10 0.170] [11 0.103]
[12 0.131] [13 0.134] [14 0.047] [15 0.182] [16 0.049] [17 0.088]
[18 0.088] [19 0.064] [20 0.024] [21 0.064] [22 0.022])]
[Integer/MAX_VALUE
2.811
sine-table
(gen9 hwt-size [2 0.193] [3 0.542])
(gen9 hwt-size [4 0.125] [5 0.958] [6 0.154] [7 0.364])
(gen9 hwt-size [8 0.444] [9 0.170] [10 0.090] [11 0.077] [12 0.026]
[13 0.073])]
])
(defn horn-lookup
"Returns the wavetable set for a given frequency and bank of wavetable sets"
[^double freq tbls]
(loop [[x & xs] tbls]
(if (nil? xs)
(rest x)
(if (< freq ^double (first x))
(rest x)
(recur xs)))))
; audio generator functions
(defn horn-play
[amp freq wave-tables]
(let [env0 (shared
(if (number? amp)
(let [a (double amp)]
(env [0 0 0.02 a 0.03 (* 0.9 a) 0.5 (* 0.9 a) 0.2 0.0] ))
(arg amp)))
env1 (shared (mul env0 env0))
env2 (shared (mul env1 env0))
env3 (shared (mul env2 env0))
envs [env0 env1 env2 env3]
freqf (shared (arg freq))
phase 0.5
[adjust & tbls] (horn-lookup freq wave-tables)
tbl-fns (map oscil3 envs (repeat freqf) tbls (repeat phase))
portamento (sum 1.0 (oscil3 0.02 0.5 sine-table))]
(let-s [asig (div (apply sum tbl-fns) (arg adjust))]
(mul portamento
(balance (tone asig horn-cutoff) asig)))
))
(defn horn
"Creates mono horn unless panning given"
([amp freq] (horn amp freq nil))
([amp freq loc]
(if (nil? loc)
(horn-play amp freq horn-wave-tables)
(pan (horn-play amp freq horn-wave-tables) loc))))
(defn horn-stopped
"Creates mono stopped horn unless panning given"
([amp freq] (horn-stopped amp freq nil))
([amp freq loc]
(if (nil? loc)
(horn-play amp freq horn-stopped-wave-tables)
(pan (horn-play amp freq horn-stopped-wave-tables) loc))))
(defn- horn-straight-mute
[asig]
(let-s [sig asig]
(balance (atone sig 1200) sig)) )
(defn horn-muted
"Creates mono muted horn unless panning given"
([amp freq] (horn-muted amp freq nil))
([amp freq loc]
(if (nil? loc)
(horn-straight-mute
(horn-play amp freq horn-wave-tables))
(pan
(horn-straight-mute
(horn-play amp freq horn-wave-tables)) loc))))
| null | https://raw.githubusercontent.com/kunstmusik/pink/7d37764b6a036a68a4619c93546fa3887f9951a7/src/main/pink/instruments/horn.clj | clojure | Ensure unchecked math used for this namespace
TABLES
audio generator functions | (ns pink.instruments.horn
"Implementation of Andrew Horner and Lydia Ayer's French Horn models using
banded wavetable synthesis. Based on the Csound code implementaiton."
(:require [pink.util :refer :all]
[pink.config :refer [*buffer-size* *current-buffer-num* *sr*]]
[pink.envelopes :refer :all]
[pink.gen :refer [gen9 gen17]]
[pink.oscillators :refer :all]
[pink.filters :refer [tone atone]]
[pink.space :refer [pan]]
[pink.dynamics :refer [balance]]
))
(set! *unchecked-math* :warn-on-boxed)
(def ^:const ^:private ^{:tag 'long}
hwt-size 4096)
(def ^:const ^:private ^{:tag 'long}
horn-cutoff 2560)
( def horn - cutoff [ 40 40 80 160 320 640 1280 2560 5120 10240 10240 ] )
format : note - freq - max adjustment table0 [ table1 table2 ]
(def horn-wave-tables
[
[85
52.476
sine-table
(gen9 hwt-size [2 6.236] [3 12.827])
(gen9 hwt-size [4 21.591] [5 11.401] [6 3.570] [7 2.833])
(gen9 hwt-size [8 3.070] [9 1.053] [10 0.773] [11 1.349] [12 0.819]
[13 0.369] [14 0.362] [15 0.165] [16 0.124] [18 0.026] [19 0.042])]
[114
18.006
sine-table
(gen9 hwt-size [2 3.236] [3 6.827])
(gen9 hwt-size [4 5.591] [5 2.401] [6 1.870] [7 0.733])
(gen9 hwt-size [8 0.970] [9 0.553] [10 0.373] [11 0.549] [12 0.319]
[13 0.119] [14 0.092] [15 0.045] [16 0.034])]
[153
11.274
sine-table
(gen9 hwt-size [2 5.019] [3 4.281])
(gen9 hwt-size [4 2.091] [5 1.001] [6 0.670] [7 0.233])
(gen9 hwt-size [8 0.200] [9 0.103] [10 0.073] [11 0.089] [12 0.059]
[13 0.029])]
[204
6.955
sine-table
(gen9 hwt-size [2 4.712] [3 1.847])
(gen9 hwt-size [4 0.591] [5 0.401] [6 0.270] [7 0.113])
(gen9 hwt-size [8 0.060] [9 0.053] [10 0.023])]
[272
2.260
sine-table
(gen9 hwt-size [2 1.512] [3 0.247])
(gen9 hwt-size [4 0.121] [5 0.101] [6 0.030] [7 0.053])
(gen9 hwt-size [8 0.030])]
[364
1.171
sine-table
(gen9 hwt-size [2 0.412] [3 0.087])
(gen9 hwt-size [4 0.071] [5 0.021])]
[486
1.106
sine-table
(gen9 hwt-size [2 0.309] [3 0.067])
(gen9 hwt-size [4 0.031])]
[Integer/MAX_VALUE
1.019
sine-table
(gen9 hwt-size [2 0.161] [3 0.047])]
])
( def horn - stopped - cutoff [ 40 40 80 160 320 640 1280 2560 5120 10240 10240 ] )
(def horn-stopped-wave-tables
[
[272
3.172
sine-table
(gen9 hwt-size [2 0.961] [3 0.052])
(gen9 hwt-size [4 0.079] [5 0.137] [6 0.185] [7 0.109])
(gen9 hwt-size [8 0.226] [9 0.107] [10 0.155] [11 0.140] [12 0.428]
[13 0.180] [15 0.070] [16 0.335] [17 0.183] [18 0.073] [19 0.172]
[20 0.117] [21 0.089] [22 0.193] [23 0.119] [24 0.080] [25 0.36]
[26 0.143] [27 0.036] [28 0.044] [29 0.040] [30 0.052] [31 0.086]
[32 0.067] [33 0.097] [34 0.046] [36 0.030] [37 0.025] [38 0.048]
[39 0.021] [40 0.025])]
[363
1.947
sine-table
(gen9 hwt-size [2 0.162] [3 0.068])
(gen9 hwt-size [4 0.116] [5 0.13] [6 0.050] [7 0.089])
(gen9 hwt-size [8 0.156] [9 0.381] [10 0.191] [11 0.126] [12 0.162]
[13 0.073] [15 0.157] [16 0.074] [17 0.087] [18 0.151] [19 0.093]
[20 0.031] [21 0.030] [22 0.051] [23 0.058] [24 0.051] [25 0.077]
[26 0.033] [27 0.021] [28 0.039])]
[484
2.221
sine-table
(gen9 hwt-size [2 0.164] [3 0.164])
(gen9 hwt-size [4 0.401] [5 0.141] [6 0.293] [7 0.203])
(gen9 hwt-size [8 0.170] [9 0.306] [10 0.170] [11 0.103]
[12 0.131] [13 0.134] [14 0.047] [15 0.182] [16 0.049] [17 0.088]
[18 0.088] [19 0.064] [20 0.024] [21 0.064] [22 0.022])]
[Integer/MAX_VALUE
2.811
sine-table
(gen9 hwt-size [2 0.193] [3 0.542])
(gen9 hwt-size [4 0.125] [5 0.958] [6 0.154] [7 0.364])
(gen9 hwt-size [8 0.444] [9 0.170] [10 0.090] [11 0.077] [12 0.026]
[13 0.073])]
])
(defn horn-lookup
"Returns the wavetable set for a given frequency and bank of wavetable sets"
[^double freq tbls]
(loop [[x & xs] tbls]
(if (nil? xs)
(rest x)
(if (< freq ^double (first x))
(rest x)
(recur xs)))))
(defn horn-play
[amp freq wave-tables]
(let [env0 (shared
(if (number? amp)
(let [a (double amp)]
(env [0 0 0.02 a 0.03 (* 0.9 a) 0.5 (* 0.9 a) 0.2 0.0] ))
(arg amp)))
env1 (shared (mul env0 env0))
env2 (shared (mul env1 env0))
env3 (shared (mul env2 env0))
envs [env0 env1 env2 env3]
freqf (shared (arg freq))
phase 0.5
[adjust & tbls] (horn-lookup freq wave-tables)
tbl-fns (map oscil3 envs (repeat freqf) tbls (repeat phase))
portamento (sum 1.0 (oscil3 0.02 0.5 sine-table))]
(let-s [asig (div (apply sum tbl-fns) (arg adjust))]
(mul portamento
(balance (tone asig horn-cutoff) asig)))
))
(defn horn
"Creates mono horn unless panning given"
([amp freq] (horn amp freq nil))
([amp freq loc]
(if (nil? loc)
(horn-play amp freq horn-wave-tables)
(pan (horn-play amp freq horn-wave-tables) loc))))
(defn horn-stopped
"Creates mono stopped horn unless panning given"
([amp freq] (horn-stopped amp freq nil))
([amp freq loc]
(if (nil? loc)
(horn-play amp freq horn-stopped-wave-tables)
(pan (horn-play amp freq horn-stopped-wave-tables) loc))))
(defn- horn-straight-mute
[asig]
(let-s [sig asig]
(balance (atone sig 1200) sig)) )
(defn horn-muted
"Creates mono muted horn unless panning given"
([amp freq] (horn-muted amp freq nil))
([amp freq loc]
(if (nil? loc)
(horn-straight-mute
(horn-play amp freq horn-wave-tables))
(pan
(horn-straight-mute
(horn-play amp freq horn-wave-tables)) loc))))
|
113a6639bcdc2fda9b5bd08a97b2c6bdeafceae9601d161d5f3b222493ce39a5 | haskell-mafia/mafia | Tripping.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module Test.Mafia.Tripping where
import Control.Applicative
import Data.Monoid
import Data.Function
import Test.QuickCheck
import Prelude
-- | Generalized round-trip property function
tripping :: (Applicative f, Show (f a), Eq (f a)) => (a -> b) -> (b -> f a) -> a -> Property
tripping = trippingOn id
trippingOn :: (Applicative f, Show (f a), Show (f c), Eq (f c)) => (a -> c) -> (a -> b) -> (b -> f a) -> a -> Property
trippingOn f = trippingWith ((===) `on` fmap f)
trippingWith :: (Applicative f, Show (f a)) => (f a -> f a -> Property) -> (a -> b) -> (b -> f a) -> a -> Property
trippingWith prop to fro a =
let tripped = (fro . to) a
purea = pure a
in counterexample (show tripped <> " /= " <> show purea)
(prop tripped purea)
| null | https://raw.githubusercontent.com/haskell-mafia/mafia/529440246ee571bf1473615e6218f52cd1e990ae/test/Test/Mafia/Tripping.hs | haskell | # LANGUAGE OverloadedStrings #
| Generalized round-trip property function | # LANGUAGE ScopedTypeVariables #
module Test.Mafia.Tripping where
import Control.Applicative
import Data.Monoid
import Data.Function
import Test.QuickCheck
import Prelude
tripping :: (Applicative f, Show (f a), Eq (f a)) => (a -> b) -> (b -> f a) -> a -> Property
tripping = trippingOn id
trippingOn :: (Applicative f, Show (f a), Show (f c), Eq (f c)) => (a -> c) -> (a -> b) -> (b -> f a) -> a -> Property
trippingOn f = trippingWith ((===) `on` fmap f)
trippingWith :: (Applicative f, Show (f a)) => (f a -> f a -> Property) -> (a -> b) -> (b -> f a) -> a -> Property
trippingWith prop to fro a =
let tripped = (fro . to) a
purea = pure a
in counterexample (show tripped <> " /= " <> show purea)
(prop tripped purea)
|
f02c1f0ff8e88816eb33cfa3f9e5a9eb9cadb01230db073bd9352e93527637ad | sifbiri/project-resources-operations | at_at.clj | (ns app.at-at
(:import [java.util.concurrent ScheduledThreadPoolExecutor TimeUnit ThreadPoolExecutor]
[java.io Writer]))
(defrecord PoolInfo [thread-pool jobs-ref id-count-ref])
(defrecord MutablePool [pool-atom])
(defrecord RecurringJob [id created-at ms-period initial-delay job pool-info desc scheduled?])
(defrecord ScheduledJob [id created-at initial-delay job pool-info desc scheduled?])
(defn- format-date
"Format date object as a string such as: 15:23:35s"
[date]
(.format (java.text.SimpleDateFormat. "EEE hh':'mm':'ss's'") date))
(defmethod print-method PoolInfo
[obj ^Writer w]
(.write w (str "#<PoolInfo: " (:thread-pool obj) " "
(count @(:jobs-ref obj)) " jobs>")))
(defmethod print-method MutablePool
[obj ^Writer w]
(.write w (str "#<MutablePool - "
"jobs: "(count @(:jobs-ref @(:pool-atom obj)))
">")))
(defmethod print-method RecurringJob
[obj ^Writer w]
(.write w (str "#<RecurringJob id: " (:id obj)
", created-at: " (format-date (:created-at obj))
", ms-period: " (:ms-period obj)
", initial-delay: " (:initial-delay obj)
", desc: \"" (:desc obj) "\""
", scheduled? " @(:scheduled? obj) ">")))
(defmethod print-method ScheduledJob
[obj ^Writer w]
(.write w (str "#<ScheduledJob id: " (:id obj)
", created-at: " (format-date (:created-at obj))
", initial-delay: " (:initial-delay obj)
", desc: \"" (:desc obj) "\""
", scheduled? " @(:scheduled? obj) ">")))
(defn- switch!
"Sets the value of atom to new-val. Similar to reset! except returns the
immediately previous value."
[atom new-val]
(let [old-val @atom
success? (compare-and-set! atom old-val new-val)]
(if success?
old-val
(recur atom new-val))))
(defn- cpu-count
"Returns the number of CPUs on this machine."
[]
(.availableProcessors (Runtime/getRuntime)))
(defn- schedule-job
"Schedule the fun to execute periodically in pool-info's pool with the
specified initial-delay and ms-period. Returns a RecurringJob record."
[pool-info fun initial-delay ms-period desc interspaced?]
(let [initial-delay (long initial-delay)
ms-period (long ms-period)
^ScheduledThreadPoolExecutor t-pool (:thread-pool pool-info)
job (if interspaced?
(.scheduleWithFixedDelay t-pool
fun
initial-delay
ms-period
TimeUnit/MILLISECONDS)
(.scheduleAtFixedRate t-pool
fun
initial-delay
ms-period
TimeUnit/MILLISECONDS))
start-time (System/currentTimeMillis)
jobs-ref (:jobs-ref pool-info)
id-count-ref (:id-count-ref pool-info)]
(dosync
(let [id (commute id-count-ref inc)
job-info (RecurringJob. id
start-time
ms-period
initial-delay
job
pool-info
desc
(atom true))]
(commute jobs-ref assoc id job-info)
job-info))))
(defn- wrap-fun-to-remove-itself
[fun jobs-ref job-info-prom]
(fn [& args]
(let [job-info @job-info-prom
id (:id job-info)
sched-ref (:scheduled? job-info)]
(reset! sched-ref false)
(dosync
(commute jobs-ref dissoc id))
(apply fun args))))
(defn- schedule-at
"Schedule the fun to execute once in the pool-info's pool after the
specified initial-delay. Returns a ScheduledJob record."
[pool-info fun initial-delay desc]
(let [initial-delay (long initial-delay)
^ScheduledThreadPoolExecutor t-pool (:thread-pool pool-info)
jobs-ref (:jobs-ref pool-info)
id-prom (promise)
^Callable fun (wrap-fun-to-remove-itself fun jobs-ref id-prom)
job (.schedule t-pool fun initial-delay TimeUnit/MILLISECONDS)
start-time (System/currentTimeMillis)
id-count-ref (:id-count-ref pool-info)
job-info (dosync
(let [id (commute id-count-ref inc)
job-info (ScheduledJob. id
start-time
initial-delay
job
pool-info
desc
(atom true))]
(commute jobs-ref assoc id job-info)
job-info))]
(deliver id-prom job-info)
job-info))
(defn- shutdown-pool-now!
"Shut the pool down NOW!"
[pool-info]
(.shutdownNow (:thread-pool pool-info))
(doseq [job (vals @(:jobs-ref pool-info))]
(reset! (:scheduled? job) false)))
(defn- shutdown-pool-gracefully!
"Shut the pool down gracefully - waits until all previously
submitted jobs have completed"
[pool-info]
(.shutdown (:thread-pool pool-info))
(let [jobs (vals @(:jobs-ref pool-info))]
(future
(loop [jobs jobs]
(doseq [job jobs]
(when (and @(:scheduled? job)
(or
(.isCancelled (:job job))
(.isDone (:job job))))
(reset! (:scheduled? job) false)))
(when-let [jobs (filter (fn [j] @(:scheduled? j)) jobs)]
(Thread/sleep 500)
(when (seq jobs)
(recur jobs)))))))
(defn- mk-sched-thread-pool
"Create a new scheduled thread pool containing num-threads threads."
[num-threads]
(let [t-pool (ScheduledThreadPoolExecutor. num-threads)]
t-pool))
(defn- mk-pool-info
[t-pool]
(PoolInfo. t-pool (ref {}) (ref 0N)))
(defn mk-pool
"Returns MutablePool record storing a mutable reference (atom) to a
PoolInfo record which contains a newly created pool of threads to
schedule new events for. Pool size defaults to the cpu count + 2."
[& {:keys [cpu-count stop-delayed? stop-periodic?]
:or {cpu-count (+ 2 (cpu-count))}}]
(MutablePool. (atom (mk-pool-info (mk-sched-thread-pool cpu-count)))))
(defn every
"Calls fun every ms-period, and takes an optional initial-delay for
the first call in ms. Returns a scheduled-fn which may be cancelled
with cancel.
Default options are
{:initial-delay 0 :desc \"\"}"
[ms-period fun pool & {:keys [initial-delay desc]
:or {initial-delay 0
desc ""}}]
(schedule-job @(:pool-atom pool) fun initial-delay ms-period desc false))
(defn interspaced
"Calls fun repeatedly with an interspacing of ms-period, i.e. the next
call of fun will happen ms-period milliseconds after the completion
of the previous call. Also takes an optional initial-delay for the
first call in ms. Returns a scheduled-fn which may be cancelled with
cancel.
Default options are
{:initial-delay 0 :desc \"\"}"
[ms-period fun pool & {:keys [initial-delay desc]
:or {initial-delay 0
desc ""}}]
(schedule-job @(:pool-atom pool) fun initial-delay ms-period desc true))
(defn now
"Return the current time in ms"
[]
(System/currentTimeMillis))
(defn at
"Schedules fun to be executed at ms-time (in milliseconds).
Use (now) to get the current time in ms.
Example usage:
(at (+ 1000 (now))
#(println \"hello from the past\")
pool
= > prints 1s from now "
[ms-time fun pool & {:keys [desc]
:or {desc ""}}]
(let [initial-delay (- ms-time (now))
pool-info @(:pool-atom pool)]
(schedule-at pool-info fun initial-delay desc)))
(defn after
"Schedules fun to be executed after delay-ms (in
milliseconds).
Example usage:
(after 1000
#(println \"hello from the past\")
pool
= > prints 1s from now "
[delay-ms fun pool & {:keys [desc]
:or {desc ""}}]
(let [pool-info @(:pool-atom pool)]
(schedule-at pool-info fun delay-ms desc)))
(defn- shutdown-pool!
[pool-info strategy]
(case strategy
:stop (shutdown-pool-gracefully! pool-info)
:kill (shutdown-pool-now! pool-info)))
(defn stop-and-reset-pool!
"Shuts down the threadpool of given MutablePool using the specified
strategy (defaults to :stop). Shutdown happens asynchronously on a
separate thread. The pool is reset to a fresh new pool preserving
the original size. Returns the old pool-info.
Strategies for stopping the old pool:
:stop - allows all running and scheduled tasks to complete before
waiting
:kill - forcefully interrupts all running tasks and does not wait
Example usage:
(stop-and-reset-pool! pool) ;=> pool is reset gracefully
(stop-and-reset-pool! pool
:strategy :kill) ;=> pool is reset forcefully"
[pool & {:keys [strategy]
:or {strategy :stop}}]
(when-not (some #{strategy} #{:stop :kill})
(throw (Exception. (str "Error: unknown pool stopping strategy: " strategy ". Expecting one of :stop or :kill"))))
(let [pool-atom (:pool-atom pool)
^ThreadPoolExecutor tp-executor (:thread-pool @pool-atom)
num-threads (.getCorePoolSize tp-executor)
new-t-pool (mk-sched-thread-pool num-threads)
new-pool-info (mk-pool-info new-t-pool)
old-pool-info (switch! pool-atom new-pool-info)]
(future (shutdown-pool! old-pool-info strategy))
old-pool-info))
(defn- cancel-job
"Cancel/stop scheduled fn if it hasn't already executed"
[job-info cancel-immediately?]
(if (:scheduled? job-info)
(let [job (:job job-info)
id (:id job-info)
pool-info (:pool-info job-info)
pool (:thread-pool pool-info)
jobs-ref (:jobs-ref pool-info)]
(.cancel job cancel-immediately?)
(reset! (:scheduled? job-info) false)
(dosync
(let [job (get @jobs-ref id)]
(commute jobs-ref dissoc id)
(true? (and job (nil? (get @jobs-ref id))))))) ;;return true if success
false))
(defn- cancel-job-id
[id pool cancel-immediately?]
(let [pool-info @(:pool-atom pool)
jobs-info @(:jobs-ref pool-info)
job-info (get jobs-info id)]
(cancel-job job-info cancel-immediately?)))
(defn stop
"Stop a recurring or scheduled job gracefully either using a
corresponding record or unique id. If you specify an id, you also
need to pass the associated pool."
([job] (cancel-job job false))
([id pool] (cancel-job-id id pool false)))
(defn kill
"kill a recurring or scheduled job forcefully either using a
corresponding record or unique id. If you specify an id, you also
need to pass the associated pool."
([job] (cancel-job job true))
([id pool] (cancel-job-id id pool true)))
(defn scheduled-jobs
"Returns a set of all current jobs (both scheduled and recurring)
for the specified pool."
[pool]
(let [pool-atom (:pool-atom pool)
jobs @(:jobs-ref @pool-atom)
jobs (vals jobs)]
jobs))
(defn- format-start-time
[date]
(if (< date (now))
""
(str ", starts at: " (format-date date))))
(defn- recurring-job-string
[job]
(str "[" (:id job) "]"
"[RECUR] created: " (format-date (:created-at job))
(format-start-time (+ (:created-at job) (:initial-delay job)))
", period: " (:ms-period job) "ms"
", desc: \""(:desc job) "\""))
(defn- scheduled-job-string
[job]
(str "[" (:id job) "]"
"[SCHED] created: " (format-date (:created-at job))
(format-start-time (+ (:created-at job) (:initial-delay job)))
", desc: \"" (:desc job) "\""))
(defn- job-string
[job]
(cond
(= RecurringJob (type job)) (recurring-job-string job)
(= ScheduledJob (type job)) (scheduled-job-string job)))
(defn show-schedule
"Pretty print all of the pool's scheduled jobs"
([pool]
(let [jobs (scheduled-jobs pool)]
(if (empty? jobs)
(println "No jobs are currently scheduled.")
(dorun
(map #(println (job-string %)) jobs))))))
| null | https://raw.githubusercontent.com/sifbiri/project-resources-operations/b08adb09ef03f123ca7ad19ec1c2bdc070a66291/src/main/app/at_at.clj | clojure | => pool is reset gracefully
=> pool is reset forcefully"
return true if success | (ns app.at-at
(:import [java.util.concurrent ScheduledThreadPoolExecutor TimeUnit ThreadPoolExecutor]
[java.io Writer]))
(defrecord PoolInfo [thread-pool jobs-ref id-count-ref])
(defrecord MutablePool [pool-atom])
(defrecord RecurringJob [id created-at ms-period initial-delay job pool-info desc scheduled?])
(defrecord ScheduledJob [id created-at initial-delay job pool-info desc scheduled?])
(defn- format-date
"Format date object as a string such as: 15:23:35s"
[date]
(.format (java.text.SimpleDateFormat. "EEE hh':'mm':'ss's'") date))
(defmethod print-method PoolInfo
[obj ^Writer w]
(.write w (str "#<PoolInfo: " (:thread-pool obj) " "
(count @(:jobs-ref obj)) " jobs>")))
(defmethod print-method MutablePool
[obj ^Writer w]
(.write w (str "#<MutablePool - "
"jobs: "(count @(:jobs-ref @(:pool-atom obj)))
">")))
(defmethod print-method RecurringJob
[obj ^Writer w]
(.write w (str "#<RecurringJob id: " (:id obj)
", created-at: " (format-date (:created-at obj))
", ms-period: " (:ms-period obj)
", initial-delay: " (:initial-delay obj)
", desc: \"" (:desc obj) "\""
", scheduled? " @(:scheduled? obj) ">")))
(defmethod print-method ScheduledJob
[obj ^Writer w]
(.write w (str "#<ScheduledJob id: " (:id obj)
", created-at: " (format-date (:created-at obj))
", initial-delay: " (:initial-delay obj)
", desc: \"" (:desc obj) "\""
", scheduled? " @(:scheduled? obj) ">")))
(defn- switch!
"Sets the value of atom to new-val. Similar to reset! except returns the
immediately previous value."
[atom new-val]
(let [old-val @atom
success? (compare-and-set! atom old-val new-val)]
(if success?
old-val
(recur atom new-val))))
(defn- cpu-count
"Returns the number of CPUs on this machine."
[]
(.availableProcessors (Runtime/getRuntime)))
(defn- schedule-job
"Schedule the fun to execute periodically in pool-info's pool with the
specified initial-delay and ms-period. Returns a RecurringJob record."
[pool-info fun initial-delay ms-period desc interspaced?]
(let [initial-delay (long initial-delay)
ms-period (long ms-period)
^ScheduledThreadPoolExecutor t-pool (:thread-pool pool-info)
job (if interspaced?
(.scheduleWithFixedDelay t-pool
fun
initial-delay
ms-period
TimeUnit/MILLISECONDS)
(.scheduleAtFixedRate t-pool
fun
initial-delay
ms-period
TimeUnit/MILLISECONDS))
start-time (System/currentTimeMillis)
jobs-ref (:jobs-ref pool-info)
id-count-ref (:id-count-ref pool-info)]
(dosync
(let [id (commute id-count-ref inc)
job-info (RecurringJob. id
start-time
ms-period
initial-delay
job
pool-info
desc
(atom true))]
(commute jobs-ref assoc id job-info)
job-info))))
(defn- wrap-fun-to-remove-itself
[fun jobs-ref job-info-prom]
(fn [& args]
(let [job-info @job-info-prom
id (:id job-info)
sched-ref (:scheduled? job-info)]
(reset! sched-ref false)
(dosync
(commute jobs-ref dissoc id))
(apply fun args))))
(defn- schedule-at
"Schedule the fun to execute once in the pool-info's pool after the
specified initial-delay. Returns a ScheduledJob record."
[pool-info fun initial-delay desc]
(let [initial-delay (long initial-delay)
^ScheduledThreadPoolExecutor t-pool (:thread-pool pool-info)
jobs-ref (:jobs-ref pool-info)
id-prom (promise)
^Callable fun (wrap-fun-to-remove-itself fun jobs-ref id-prom)
job (.schedule t-pool fun initial-delay TimeUnit/MILLISECONDS)
start-time (System/currentTimeMillis)
id-count-ref (:id-count-ref pool-info)
job-info (dosync
(let [id (commute id-count-ref inc)
job-info (ScheduledJob. id
start-time
initial-delay
job
pool-info
desc
(atom true))]
(commute jobs-ref assoc id job-info)
job-info))]
(deliver id-prom job-info)
job-info))
(defn- shutdown-pool-now!
"Shut the pool down NOW!"
[pool-info]
(.shutdownNow (:thread-pool pool-info))
(doseq [job (vals @(:jobs-ref pool-info))]
(reset! (:scheduled? job) false)))
(defn- shutdown-pool-gracefully!
"Shut the pool down gracefully - waits until all previously
submitted jobs have completed"
[pool-info]
(.shutdown (:thread-pool pool-info))
(let [jobs (vals @(:jobs-ref pool-info))]
(future
(loop [jobs jobs]
(doseq [job jobs]
(when (and @(:scheduled? job)
(or
(.isCancelled (:job job))
(.isDone (:job job))))
(reset! (:scheduled? job) false)))
(when-let [jobs (filter (fn [j] @(:scheduled? j)) jobs)]
(Thread/sleep 500)
(when (seq jobs)
(recur jobs)))))))
(defn- mk-sched-thread-pool
"Create a new scheduled thread pool containing num-threads threads."
[num-threads]
(let [t-pool (ScheduledThreadPoolExecutor. num-threads)]
t-pool))
(defn- mk-pool-info
[t-pool]
(PoolInfo. t-pool (ref {}) (ref 0N)))
(defn mk-pool
"Returns MutablePool record storing a mutable reference (atom) to a
PoolInfo record which contains a newly created pool of threads to
schedule new events for. Pool size defaults to the cpu count + 2."
[& {:keys [cpu-count stop-delayed? stop-periodic?]
:or {cpu-count (+ 2 (cpu-count))}}]
(MutablePool. (atom (mk-pool-info (mk-sched-thread-pool cpu-count)))))
(defn every
"Calls fun every ms-period, and takes an optional initial-delay for
the first call in ms. Returns a scheduled-fn which may be cancelled
with cancel.
Default options are
{:initial-delay 0 :desc \"\"}"
[ms-period fun pool & {:keys [initial-delay desc]
:or {initial-delay 0
desc ""}}]
(schedule-job @(:pool-atom pool) fun initial-delay ms-period desc false))
(defn interspaced
"Calls fun repeatedly with an interspacing of ms-period, i.e. the next
call of fun will happen ms-period milliseconds after the completion
of the previous call. Also takes an optional initial-delay for the
first call in ms. Returns a scheduled-fn which may be cancelled with
cancel.
Default options are
{:initial-delay 0 :desc \"\"}"
[ms-period fun pool & {:keys [initial-delay desc]
:or {initial-delay 0
desc ""}}]
(schedule-job @(:pool-atom pool) fun initial-delay ms-period desc true))
(defn now
"Return the current time in ms"
[]
(System/currentTimeMillis))
(defn at
"Schedules fun to be executed at ms-time (in milliseconds).
Use (now) to get the current time in ms.
Example usage:
(at (+ 1000 (now))
#(println \"hello from the past\")
pool
= > prints 1s from now "
[ms-time fun pool & {:keys [desc]
:or {desc ""}}]
(let [initial-delay (- ms-time (now))
pool-info @(:pool-atom pool)]
(schedule-at pool-info fun initial-delay desc)))
(defn after
"Schedules fun to be executed after delay-ms (in
milliseconds).
Example usage:
(after 1000
#(println \"hello from the past\")
pool
= > prints 1s from now "
[delay-ms fun pool & {:keys [desc]
:or {desc ""}}]
(let [pool-info @(:pool-atom pool)]
(schedule-at pool-info fun delay-ms desc)))
(defn- shutdown-pool!
[pool-info strategy]
(case strategy
:stop (shutdown-pool-gracefully! pool-info)
:kill (shutdown-pool-now! pool-info)))
(defn stop-and-reset-pool!
"Shuts down the threadpool of given MutablePool using the specified
strategy (defaults to :stop). Shutdown happens asynchronously on a
separate thread. The pool is reset to a fresh new pool preserving
the original size. Returns the old pool-info.
Strategies for stopping the old pool:
:stop - allows all running and scheduled tasks to complete before
waiting
:kill - forcefully interrupts all running tasks and does not wait
Example usage:
(stop-and-reset-pool! pool
[pool & {:keys [strategy]
:or {strategy :stop}}]
(when-not (some #{strategy} #{:stop :kill})
(throw (Exception. (str "Error: unknown pool stopping strategy: " strategy ". Expecting one of :stop or :kill"))))
(let [pool-atom (:pool-atom pool)
^ThreadPoolExecutor tp-executor (:thread-pool @pool-atom)
num-threads (.getCorePoolSize tp-executor)
new-t-pool (mk-sched-thread-pool num-threads)
new-pool-info (mk-pool-info new-t-pool)
old-pool-info (switch! pool-atom new-pool-info)]
(future (shutdown-pool! old-pool-info strategy))
old-pool-info))
(defn- cancel-job
"Cancel/stop scheduled fn if it hasn't already executed"
[job-info cancel-immediately?]
(if (:scheduled? job-info)
(let [job (:job job-info)
id (:id job-info)
pool-info (:pool-info job-info)
pool (:thread-pool pool-info)
jobs-ref (:jobs-ref pool-info)]
(.cancel job cancel-immediately?)
(reset! (:scheduled? job-info) false)
(dosync
(let [job (get @jobs-ref id)]
(commute jobs-ref dissoc id)
false))
(defn- cancel-job-id
[id pool cancel-immediately?]
(let [pool-info @(:pool-atom pool)
jobs-info @(:jobs-ref pool-info)
job-info (get jobs-info id)]
(cancel-job job-info cancel-immediately?)))
(defn stop
"Stop a recurring or scheduled job gracefully either using a
corresponding record or unique id. If you specify an id, you also
need to pass the associated pool."
([job] (cancel-job job false))
([id pool] (cancel-job-id id pool false)))
(defn kill
"kill a recurring or scheduled job forcefully either using a
corresponding record or unique id. If you specify an id, you also
need to pass the associated pool."
([job] (cancel-job job true))
([id pool] (cancel-job-id id pool true)))
(defn scheduled-jobs
"Returns a set of all current jobs (both scheduled and recurring)
for the specified pool."
[pool]
(let [pool-atom (:pool-atom pool)
jobs @(:jobs-ref @pool-atom)
jobs (vals jobs)]
jobs))
(defn- format-start-time
[date]
(if (< date (now))
""
(str ", starts at: " (format-date date))))
(defn- recurring-job-string
[job]
(str "[" (:id job) "]"
"[RECUR] created: " (format-date (:created-at job))
(format-start-time (+ (:created-at job) (:initial-delay job)))
", period: " (:ms-period job) "ms"
", desc: \""(:desc job) "\""))
(defn- scheduled-job-string
[job]
(str "[" (:id job) "]"
"[SCHED] created: " (format-date (:created-at job))
(format-start-time (+ (:created-at job) (:initial-delay job)))
", desc: \"" (:desc job) "\""))
(defn- job-string
[job]
(cond
(= RecurringJob (type job)) (recurring-job-string job)
(= ScheduledJob (type job)) (scheduled-job-string job)))
(defn show-schedule
"Pretty print all of the pool's scheduled jobs"
([pool]
(let [jobs (scheduled-jobs pool)]
(if (empty? jobs)
(println "No jobs are currently scheduled.")
(dorun
(map #(println (job-string %)) jobs))))))
|
967251404a07eaa1f5bd2faa5053528f1bf47544607a85ad575f8e5340182aab | iconnect/regex | PCRE.hs | {-# LANGUAGE NoImplicitPrelude #-}
# LANGUAGE RecordWildCards #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE CPP #
#if __GLASGOW_HASKELL__ >= 800
# OPTIONS_GHC -fno - warn - redundant - constraints #
{-# LANGUAGE TemplateHaskellQuotes #-}
#else
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
#endif
# OPTIONS_GHC -fno - warn - orphans #
# OPTIONS_GHC -fno - warn - unused - imports #
module Text.RE.ZeInternals.PCRE
( -- * About
-- $about
-- * RE Type
RE
, regexType
, reOptions
, reSource
, reCaptureNames
, reRegex
* and REOptions Type
, IsOption(..)
, REOptions
, defaultREOptions
, noPreludeREOptions
, unpackSimpleREOptions
-- * Compiling Regular Expressions
, compileRegex
, compileRegexWith
, compileRegexWithOptions
-- * Compiling Search-Replace Templates
, compileSearchReplace
, compileSearchReplaceWith
, compileSearchReplaceWithOptions
-- * Escaping String
, escape
, escapeWith
, escapeWithOptions
, escapeREString
-- * Macros Standard Environment
, prelude
, preludeEnv
, preludeTestsFailing
, preludeTable
, preludeSummary
, preludeSources
, preludeSource
-- * The Quasi Quoters
, re
, reMS
, reMI
, reBS
, reBI
, reMultilineSensitive
, reMultilineInsensitive
, reBlockSensitive
, reBlockInsensitive
, re_
, cp
) where
import Control.Monad.Fail
import Data.Bits
import Data.Functor.Identity
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Prelude.Compat hiding (fail)
import Text.RE.REOptions
import Text.RE.Replace
import Text.RE.TestBench
import Text.RE.Tools
import Text.RE.ZeInternals
import Text.RE.ZeInternals.Types.Poss
import Text.Regex.PCRE
-- | the RE type for this back end representing a well-formed, compiled
-- RE
data RE =
RE
{ _re_options :: !REOptions
, _re_source :: !String
, _re_cnames :: !CaptureNames
, _re_regex :: !Regex
}
-- | some functions in the "Text.RE.TestBench" need the back end to
be passed dynamically as a ' RegexType ' parameters : use ' regexType '
-- fpr this back end
regexType :: RegexType
regexType =
mkPCRE $ \txt env md -> txt =~ mdRegexSource regexType ExclCaptures env md
-- | extract the 'REOptions' from the @RE@
reOptions :: RE -> REOptions
reOptions = _re_options
-- | extract the RE source string from the @RE@
reSource :: RE -> String
reSource = _re_source
| extract the ' CaptureNames ' from the @RE@
reCaptureNames :: RE -> CaptureNames
reCaptureNames = _re_cnames
| extract the back end compiled ' Regex ' type from the @RE@
reRegex :: RE -> Regex
reRegex = _re_regex
------------------------------------------------------------------------
-- REOptions
------------------------------------------------------------------------
-- | a number of types can be used to encode 'REOptions_', each of which
-- is made a member of this class
class IsOption o where
| convert the @o@ type into an @REOptions@
makeREOptions :: o -> REOptions
-- | and the REOptions for this back end (see "Text.RE.REOptions"
-- for details)
type REOptions = REOptions_ RE CompOption ExecOption
instance IsOption SimpleREOptions where
makeREOptions = unpackSimpleREOptions
instance IsOption (Macros RE) where
makeREOptions ms = REOptions ms def_comp_option def_exec_option
instance IsOption CompOption where
makeREOptions co = REOptions prelude co def_exec_option
instance IsOption ExecOption where
makeREOptions eo = REOptions prelude def_comp_option eo
instance IsOption REOptions where
makeREOptions = id
instance IsOption () where
makeREOptions _ = unpackSimpleREOptions minBound
-- | the default 'REOptions'
defaultREOptions :: REOptions
defaultREOptions = makeREOptions (minBound::SimpleREOptions)
-- | the default 'REOptions' but with no RE macros defined
noPreludeREOptions :: REOptions
noPreludeREOptions = defaultREOptions { optionsMacs = emptyMacros }
| convert a universal ' SimpleReOptions ' into the ' REOptions ' used
-- by this back end
unpackSimpleREOptions :: SimpleREOptions -> REOptions
unpackSimpleREOptions sro =
REOptions
{ optionsMacs = prelude
, optionsComp = comp
, optionsExec = defaultExecOpt
}
where
comp =
wiggle ml compMultiline $
wiggle ci compCaseless
defaultCompOpt
wiggle True m v = v .|. m
wiggle False m v = v .&. complement m
(ml,ci) = case sro of
MultilineSensitive -> (,) True False
MultilineInsensitive -> (,) True True
BlockSensitive -> (,) False False
BlockInsensitive -> (,) False True
------------------------------------------------------------------------
-- Compiling Regular Expressions
------------------------------------------------------------------------
-- | compile a 'String' into a 'RE' with the default options,
-- generating an error if the RE is not well formed
compileRegex :: (Functor m,Monad m, MonadFail m) => String -> m RE
compileRegex = compileRegexWith minBound
-- | compile a 'String' into a 'RE' using the given @SimpleREOptions@,
-- generating an error if the RE is not well formed
compileRegexWith :: (Functor m,Monad m, MonadFail m) => SimpleREOptions -> String -> m RE
compileRegexWith = compileRegexWithOptions
-- | compile a 'String' into a 'RE' using the given @SimpleREOptions@,
-- generating an error if the RE is not well formed
compileRegexWithOptions :: (IsOption o, Functor m, Monad m, MonadFail m)
=> o
-> String
-> m RE
compileRegexWithOptions = compileRegex_ . makeREOptions
------------------------------------------------------------------------
-- Compiling Search Replace Templates
------------------------------------------------------------------------
| compile a SearchReplace template generating errors if the RE or
-- the template are not well formed, all capture references being checked
compileSearchReplace :: (Monad m,MonadFail m,Functor m,IsRegex RE s)
=> String
-> String
-> m (SearchReplace RE s)
compileSearchReplace = compileSearchReplaceWith minBound
| compile a SearchReplace template , with simple options , generating
-- errors if the RE or the template are not well formed, all capture
-- references being checked
compileSearchReplaceWith :: (Monad m,MonadFail m,Functor m,IsRegex RE s)
=> SimpleREOptions
-> String
-> String
-> m (SearchReplace RE s)
compileSearchReplaceWith sro = compileSearchAndReplace_ packR $ poss2either . compileRegexWith sro
| compile a SearchReplace template , with general options , generating
-- errors if the RE or the template are not well formed, all capture
-- references being checked
compileSearchReplaceWithOptions :: (Monad m,MonadFail m,Functor m,IsRegex RE s)
=> REOptions
-> String
-> String
-> m (SearchReplace RE s)
compileSearchReplaceWithOptions os = compileSearchAndReplace_ packR $ poss2either . compileRegexWithOptions os
------------------------------------------------------------------------
-- Escaping Strings
------------------------------------------------------------------------
-- | convert a string into a RE that matches that string, and apply it
-- to an argument continuation function to make up the RE string to be
-- compiled; e.g., to compile a RE that will only match the string:
--
@maybe undefined i d . escape ( ( ) . ( + + \"$\"))@
--
escape :: (Functor m,Monad m, MonadFail m)
=> (String->String)
-> String
-> m RE
escape = escapeWith minBound
-- | a variant of 'escape' where the 'SimpleREOptions' are specified
escapeWith :: (Functor m,Monad m, MonadFail m)
=> SimpleREOptions
-> (String->String)
-> String
-> m RE
escapeWith = escapeWithOptions
| a variant of ' escapeWith ' that allows an ' IsOption ' RE option
-- to be specified
escapeWithOptions :: ( IsOption o, Functor m, Monad m, MonadFail m)
=> o
-> (String->String)
-> String
-> m RE
escapeWithOptions o f = compileRegexWithOptions o . f . escapeREString
------------------------------------------------------------------------
Macro Standard Environment
------------------------------------------------------------------------
| the standard table of ' Macros ' used to compile REs ( which can be
-- extended or replace: see "Text.RE.TestBench")
prelude :: Macros RE
prelude = runIdentity $ preludeMacros mk regexType ExclCaptures
where
mk = Identity . unsafeCompileRegex_ noPreludeREOptions
-- | the standard 'MacroEnv' for this back end (see "Text.RE.TestBench")
preludeEnv :: MacroEnv
preludeEnv = preludeMacroEnv regexType
-- | the macros in the standard environment that are failing their tests
-- (checked by the test suite to be empty)
preludeTestsFailing :: [MacroID]
preludeTestsFailing = badMacros preludeEnv
-- | a table the standard macros in markdown format
preludeTable :: String
preludeTable = preludeMacroTable regexType
-- | a summary of the macros in the standard environment for this back
-- end in plain text
preludeSummary :: PreludeMacro -> String
preludeSummary = preludeMacroSummary regexType
-- | a listing of the RE text for each macro in the standard environment
-- with all macros expanded to normal form
preludeSources :: String
preludeSources = preludeMacroSources regexType
-- | the prelude source of a given macro in the standard environment
preludeSource :: PreludeMacro -> String
preludeSource = preludeMacroSource regexType
------------------------------------------------------------------------
-- Quasi Quoters
------------------------------------------------------------------------
-- | @[re| ... |]@, is equivalent to @[reMultilineSensitive| ... |]@,
-- compiling a case-sensitive, multi-line RE
re :: QuasiQuoter
re = re' $ Just minBound
-- | @[reMultilineSensitive| ... |]@, compiles a case-sensitive, multi-line RE
reMultilineSensitive :: QuasiQuoter
reMultilineSensitive = re' $ Just MultilineSensitive
-- | @[reMultilineInsensitive| ... |]@, compiles a case-insensitive, multi-line RE
reMultilineInsensitive :: QuasiQuoter
reMultilineInsensitive = re' $ Just MultilineInsensitive
-- | @[reMultilineInsensitive| ... |]@, compiles a case-sensitive, non-multi-line RE
reBlockSensitive :: QuasiQuoter
reBlockSensitive = re' $ Just BlockSensitive
-- | @[reMultilineInsensitive| ... |]@, compiles a case-insensitive, non-multi-line RE
reBlockInsensitive :: QuasiQuoter
reBlockInsensitive = re' $ Just BlockInsensitive
-- | @[reMS| ... |]@ is a shorthand for @[reMultilineSensitive| ... |]@
reMS :: QuasiQuoter
reMS = reMultilineSensitive
-- | @[reMI| ... |]@ is a shorthand for @[reMultilineInsensitive| ... |]@
reMI :: QuasiQuoter
reMI = reMultilineInsensitive
-- | @[reBS| ... |]@ is a shorthand for @[reBlockSensitive| ... |]@
reBS :: QuasiQuoter
reBS = reBlockSensitive
-- | @[reBI| ... |]@ is a shorthand for @[reBlockInsensitive| ... |]@
reBI :: QuasiQuoter
reBI = reBlockInsensitive
-- | @[re_| ... |]@ compiles a RE to produce a function that takes
-- the RE options (e.g., a 'SimpleREOptions' value) and yields the
-- RE compiled with those options. For example,
--
@countMatches $ s * = ~ [ - 9a - f]+| ] MultilineInsensitive@
--
-- counts the number of hexadecimal digit strings in 's', allowing
-- upper- or lower-case hex digits.
re_ :: QuasiQuoter
re_ = re' Nothing
------------------------------------------------------------------------
-- re Helpers
------------------------------------------------------------------------
re' :: Maybe SimpleREOptions -> QuasiQuoter
re' mb = case mb of
Nothing ->
(qq0 "re'")
{ quoteExp = parse minBound (\rs->[|flip unsafeCompileRegex rs|])
}
Just sro ->
(qq0 "re'")
{ quoteExp = parse sro (\rs->[|unsafeCompileRegexSimple sro rs|])
}
where
parse :: SimpleREOptions -> (String->Q Exp) -> String -> Q Exp
parse sro mk rs = poss error (\_->mk rs) $ compileRegex_ os rs
where
os = unpackSimpleREOptions sro
unsafeCompileRegexSimple :: SimpleREOptions -> String -> RE
unsafeCompileRegexSimple sro re_s = unsafeCompileRegex os re_s
where
os = unpackSimpleREOptions sro
unsafeCompileRegex :: IsOption o
=> o
-> String
-> RE
unsafeCompileRegex = unsafeCompileRegex_ . makeREOptions
unsafeCompileRegex_ :: REOptions -> String -> RE
unsafeCompileRegex_ os = poss oops id . compileRegexWithOptions os
where
oops = error . ("unsafeCompileRegex: " ++)
compileRegex' :: (Functor m,Monad m,MonadFail m)
=> REOptions
-> String
-> m (CaptureNames,Regex)
compileRegex' REOptions{..} s0 = do
((_,cnms),s2) <- either fail return $ extractNamedCaptures s1
(,) cnms <$> makeRegexOptsM optionsComp optionsExec s2
where
s1 = expandMacros reSource optionsMacs s0
compileRegex_ :: ( Functor m , Monad m, MonadFail m )
=> REOptions
-> String
-> m RE
compileRegex_ os re_s = uncurry mk <$> compileRegex' os re_s
where
mk cnms rex =
RE
{ _re_options = os
, _re_source = re_s
, _re_cnames = cnms
, _re_regex = rex
}
------------------------------------------------------------------------
-- Helpers
------------------------------------------------------------------------
def_comp_option :: CompOption
def_comp_option = optionsComp defaultREOptions
def_exec_option :: ExecOption
def_exec_option = optionsExec defaultREOptions
------------------------------------------------------------------------
-- Haddock Sections
------------------------------------------------------------------------
-- $about
--
This module provides the regex PCRE back end . Most of the functions that
-- you will need for day to day use are provided by the primary API modules
-- (e.g., "Text.RE.PCRE.ByteString").
| null | https://raw.githubusercontent.com/iconnect/regex/68752790a8f75986b917b71cf0e8e22cd3a28a3d/Text/RE/ZeInternals/PCRE.hs | haskell | # LANGUAGE NoImplicitPrelude #
# LANGUAGE TypeSynonymInstances #
# LANGUAGE TemplateHaskellQuotes #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
* About
$about
* RE Type
* Compiling Regular Expressions
* Compiling Search-Replace Templates
* Escaping String
* Macros Standard Environment
* The Quasi Quoters
| the RE type for this back end representing a well-formed, compiled
RE
| some functions in the "Text.RE.TestBench" need the back end to
fpr this back end
| extract the 'REOptions' from the @RE@
| extract the RE source string from the @RE@
----------------------------------------------------------------------
REOptions
----------------------------------------------------------------------
| a number of types can be used to encode 'REOptions_', each of which
is made a member of this class
| and the REOptions for this back end (see "Text.RE.REOptions"
for details)
| the default 'REOptions'
| the default 'REOptions' but with no RE macros defined
by this back end
----------------------------------------------------------------------
Compiling Regular Expressions
----------------------------------------------------------------------
| compile a 'String' into a 'RE' with the default options,
generating an error if the RE is not well formed
| compile a 'String' into a 'RE' using the given @SimpleREOptions@,
generating an error if the RE is not well formed
| compile a 'String' into a 'RE' using the given @SimpleREOptions@,
generating an error if the RE is not well formed
----------------------------------------------------------------------
Compiling Search Replace Templates
----------------------------------------------------------------------
the template are not well formed, all capture references being checked
errors if the RE or the template are not well formed, all capture
references being checked
errors if the RE or the template are not well formed, all capture
references being checked
----------------------------------------------------------------------
Escaping Strings
----------------------------------------------------------------------
| convert a string into a RE that matches that string, and apply it
to an argument continuation function to make up the RE string to be
compiled; e.g., to compile a RE that will only match the string:
| a variant of 'escape' where the 'SimpleREOptions' are specified
to be specified
----------------------------------------------------------------------
----------------------------------------------------------------------
extended or replace: see "Text.RE.TestBench")
| the standard 'MacroEnv' for this back end (see "Text.RE.TestBench")
| the macros in the standard environment that are failing their tests
(checked by the test suite to be empty)
| a table the standard macros in markdown format
| a summary of the macros in the standard environment for this back
end in plain text
| a listing of the RE text for each macro in the standard environment
with all macros expanded to normal form
| the prelude source of a given macro in the standard environment
----------------------------------------------------------------------
Quasi Quoters
----------------------------------------------------------------------
| @[re| ... |]@, is equivalent to @[reMultilineSensitive| ... |]@,
compiling a case-sensitive, multi-line RE
| @[reMultilineSensitive| ... |]@, compiles a case-sensitive, multi-line RE
| @[reMultilineInsensitive| ... |]@, compiles a case-insensitive, multi-line RE
| @[reMultilineInsensitive| ... |]@, compiles a case-sensitive, non-multi-line RE
| @[reMultilineInsensitive| ... |]@, compiles a case-insensitive, non-multi-line RE
| @[reMS| ... |]@ is a shorthand for @[reMultilineSensitive| ... |]@
| @[reMI| ... |]@ is a shorthand for @[reMultilineInsensitive| ... |]@
| @[reBS| ... |]@ is a shorthand for @[reBlockSensitive| ... |]@
| @[reBI| ... |]@ is a shorthand for @[reBlockInsensitive| ... |]@
| @[re_| ... |]@ compiles a RE to produce a function that takes
the RE options (e.g., a 'SimpleREOptions' value) and yields the
RE compiled with those options. For example,
counts the number of hexadecimal digit strings in 's', allowing
upper- or lower-case hex digits.
----------------------------------------------------------------------
re Helpers
----------------------------------------------------------------------
----------------------------------------------------------------------
Helpers
----------------------------------------------------------------------
----------------------------------------------------------------------
Haddock Sections
----------------------------------------------------------------------
$about
you will need for day to day use are provided by the primary API modules
(e.g., "Text.RE.PCRE.ByteString"). | # LANGUAGE RecordWildCards #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE CPP #
#if __GLASGOW_HASKELL__ >= 800
# OPTIONS_GHC -fno - warn - redundant - constraints #
#else
#endif
# OPTIONS_GHC -fno - warn - orphans #
# OPTIONS_GHC -fno - warn - unused - imports #
module Text.RE.ZeInternals.PCRE
RE
, regexType
, reOptions
, reSource
, reCaptureNames
, reRegex
* and REOptions Type
, IsOption(..)
, REOptions
, defaultREOptions
, noPreludeREOptions
, unpackSimpleREOptions
, compileRegex
, compileRegexWith
, compileRegexWithOptions
, compileSearchReplace
, compileSearchReplaceWith
, compileSearchReplaceWithOptions
, escape
, escapeWith
, escapeWithOptions
, escapeREString
, prelude
, preludeEnv
, preludeTestsFailing
, preludeTable
, preludeSummary
, preludeSources
, preludeSource
, re
, reMS
, reMI
, reBS
, reBI
, reMultilineSensitive
, reMultilineInsensitive
, reBlockSensitive
, reBlockInsensitive
, re_
, cp
) where
import Control.Monad.Fail
import Data.Bits
import Data.Functor.Identity
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Prelude.Compat hiding (fail)
import Text.RE.REOptions
import Text.RE.Replace
import Text.RE.TestBench
import Text.RE.Tools
import Text.RE.ZeInternals
import Text.RE.ZeInternals.Types.Poss
import Text.Regex.PCRE
data RE =
RE
{ _re_options :: !REOptions
, _re_source :: !String
, _re_cnames :: !CaptureNames
, _re_regex :: !Regex
}
be passed dynamically as a ' RegexType ' parameters : use ' regexType '
regexType :: RegexType
regexType =
mkPCRE $ \txt env md -> txt =~ mdRegexSource regexType ExclCaptures env md
reOptions :: RE -> REOptions
reOptions = _re_options
reSource :: RE -> String
reSource = _re_source
| extract the ' CaptureNames ' from the @RE@
reCaptureNames :: RE -> CaptureNames
reCaptureNames = _re_cnames
| extract the back end compiled ' Regex ' type from the @RE@
reRegex :: RE -> Regex
reRegex = _re_regex
class IsOption o where
| convert the @o@ type into an @REOptions@
makeREOptions :: o -> REOptions
type REOptions = REOptions_ RE CompOption ExecOption
instance IsOption SimpleREOptions where
makeREOptions = unpackSimpleREOptions
instance IsOption (Macros RE) where
makeREOptions ms = REOptions ms def_comp_option def_exec_option
instance IsOption CompOption where
makeREOptions co = REOptions prelude co def_exec_option
instance IsOption ExecOption where
makeREOptions eo = REOptions prelude def_comp_option eo
instance IsOption REOptions where
makeREOptions = id
instance IsOption () where
makeREOptions _ = unpackSimpleREOptions minBound
defaultREOptions :: REOptions
defaultREOptions = makeREOptions (minBound::SimpleREOptions)
noPreludeREOptions :: REOptions
noPreludeREOptions = defaultREOptions { optionsMacs = emptyMacros }
| convert a universal ' SimpleReOptions ' into the ' REOptions ' used
unpackSimpleREOptions :: SimpleREOptions -> REOptions
unpackSimpleREOptions sro =
REOptions
{ optionsMacs = prelude
, optionsComp = comp
, optionsExec = defaultExecOpt
}
where
comp =
wiggle ml compMultiline $
wiggle ci compCaseless
defaultCompOpt
wiggle True m v = v .|. m
wiggle False m v = v .&. complement m
(ml,ci) = case sro of
MultilineSensitive -> (,) True False
MultilineInsensitive -> (,) True True
BlockSensitive -> (,) False False
BlockInsensitive -> (,) False True
compileRegex :: (Functor m,Monad m, MonadFail m) => String -> m RE
compileRegex = compileRegexWith minBound
compileRegexWith :: (Functor m,Monad m, MonadFail m) => SimpleREOptions -> String -> m RE
compileRegexWith = compileRegexWithOptions
compileRegexWithOptions :: (IsOption o, Functor m, Monad m, MonadFail m)
=> o
-> String
-> m RE
compileRegexWithOptions = compileRegex_ . makeREOptions
| compile a SearchReplace template generating errors if the RE or
compileSearchReplace :: (Monad m,MonadFail m,Functor m,IsRegex RE s)
=> String
-> String
-> m (SearchReplace RE s)
compileSearchReplace = compileSearchReplaceWith minBound
| compile a SearchReplace template , with simple options , generating
compileSearchReplaceWith :: (Monad m,MonadFail m,Functor m,IsRegex RE s)
=> SimpleREOptions
-> String
-> String
-> m (SearchReplace RE s)
compileSearchReplaceWith sro = compileSearchAndReplace_ packR $ poss2either . compileRegexWith sro
| compile a SearchReplace template , with general options , generating
compileSearchReplaceWithOptions :: (Monad m,MonadFail m,Functor m,IsRegex RE s)
=> REOptions
-> String
-> String
-> m (SearchReplace RE s)
compileSearchReplaceWithOptions os = compileSearchAndReplace_ packR $ poss2either . compileRegexWithOptions os
@maybe undefined i d . escape ( ( ) . ( + + \"$\"))@
escape :: (Functor m,Monad m, MonadFail m)
=> (String->String)
-> String
-> m RE
escape = escapeWith minBound
escapeWith :: (Functor m,Monad m, MonadFail m)
=> SimpleREOptions
-> (String->String)
-> String
-> m RE
escapeWith = escapeWithOptions
| a variant of ' escapeWith ' that allows an ' IsOption ' RE option
escapeWithOptions :: ( IsOption o, Functor m, Monad m, MonadFail m)
=> o
-> (String->String)
-> String
-> m RE
escapeWithOptions o f = compileRegexWithOptions o . f . escapeREString
Macro Standard Environment
| the standard table of ' Macros ' used to compile REs ( which can be
prelude :: Macros RE
prelude = runIdentity $ preludeMacros mk regexType ExclCaptures
where
mk = Identity . unsafeCompileRegex_ noPreludeREOptions
preludeEnv :: MacroEnv
preludeEnv = preludeMacroEnv regexType
preludeTestsFailing :: [MacroID]
preludeTestsFailing = badMacros preludeEnv
preludeTable :: String
preludeTable = preludeMacroTable regexType
preludeSummary :: PreludeMacro -> String
preludeSummary = preludeMacroSummary regexType
preludeSources :: String
preludeSources = preludeMacroSources regexType
preludeSource :: PreludeMacro -> String
preludeSource = preludeMacroSource regexType
re :: QuasiQuoter
re = re' $ Just minBound
reMultilineSensitive :: QuasiQuoter
reMultilineSensitive = re' $ Just MultilineSensitive
reMultilineInsensitive :: QuasiQuoter
reMultilineInsensitive = re' $ Just MultilineInsensitive
reBlockSensitive :: QuasiQuoter
reBlockSensitive = re' $ Just BlockSensitive
reBlockInsensitive :: QuasiQuoter
reBlockInsensitive = re' $ Just BlockInsensitive
reMS :: QuasiQuoter
reMS = reMultilineSensitive
reMI :: QuasiQuoter
reMI = reMultilineInsensitive
reBS :: QuasiQuoter
reBS = reBlockSensitive
reBI :: QuasiQuoter
reBI = reBlockInsensitive
@countMatches $ s * = ~ [ - 9a - f]+| ] MultilineInsensitive@
re_ :: QuasiQuoter
re_ = re' Nothing
re' :: Maybe SimpleREOptions -> QuasiQuoter
re' mb = case mb of
Nothing ->
(qq0 "re'")
{ quoteExp = parse minBound (\rs->[|flip unsafeCompileRegex rs|])
}
Just sro ->
(qq0 "re'")
{ quoteExp = parse sro (\rs->[|unsafeCompileRegexSimple sro rs|])
}
where
parse :: SimpleREOptions -> (String->Q Exp) -> String -> Q Exp
parse sro mk rs = poss error (\_->mk rs) $ compileRegex_ os rs
where
os = unpackSimpleREOptions sro
unsafeCompileRegexSimple :: SimpleREOptions -> String -> RE
unsafeCompileRegexSimple sro re_s = unsafeCompileRegex os re_s
where
os = unpackSimpleREOptions sro
unsafeCompileRegex :: IsOption o
=> o
-> String
-> RE
unsafeCompileRegex = unsafeCompileRegex_ . makeREOptions
unsafeCompileRegex_ :: REOptions -> String -> RE
unsafeCompileRegex_ os = poss oops id . compileRegexWithOptions os
where
oops = error . ("unsafeCompileRegex: " ++)
compileRegex' :: (Functor m,Monad m,MonadFail m)
=> REOptions
-> String
-> m (CaptureNames,Regex)
compileRegex' REOptions{..} s0 = do
((_,cnms),s2) <- either fail return $ extractNamedCaptures s1
(,) cnms <$> makeRegexOptsM optionsComp optionsExec s2
where
s1 = expandMacros reSource optionsMacs s0
compileRegex_ :: ( Functor m , Monad m, MonadFail m )
=> REOptions
-> String
-> m RE
compileRegex_ os re_s = uncurry mk <$> compileRegex' os re_s
where
mk cnms rex =
RE
{ _re_options = os
, _re_source = re_s
, _re_cnames = cnms
, _re_regex = rex
}
def_comp_option :: CompOption
def_comp_option = optionsComp defaultREOptions
def_exec_option :: ExecOption
def_exec_option = optionsExec defaultREOptions
This module provides the regex PCRE back end . Most of the functions that
|
bc82034bda971fb6da47ab16f819a4447afce780582862620b2d5a2b59b288dc | williamthome/eel | eel_convert.erl | %%%-----------------------------------------------------------------------------
%%% @doc EEl converter module.
%%%
@author [ ]
%%% @end
%%%-----------------------------------------------------------------------------
-module(eel_convert).
-export([to_binary/1, to_binary/2]).
to_binary(Value) ->
to_binary(Value, undefined).
to_binary(Bin, _) when is_binary(Bin) ->
Bin;
to_binary(undefined, _) ->
<<>>;
to_binary([], _) ->
<<>>;
to_binary(Atom, undefined) when is_atom(Atom) ->
erlang:atom_to_binary(Atom);
to_binary(Atom, Encoding) when is_atom(Atom), is_atom(Encoding) ->
erlang:atom_to_binary(Atom, Encoding);
to_binary(Float, undefined) when is_float(Float) ->
erlang:float_to_binary(Float);
to_binary(Float, Options) when is_float(Float), is_list(Options) ->
erlang:float_to_binary(Float, Options);
to_binary(Int, undefined) when is_integer(Int) ->
erlang:integer_to_binary(Int);
to_binary(Int, Base) when is_integer(Int), is_integer(Base) ->
erlang:integer_to_binary(Int, Base);
to_binary(List, undefined) when is_list(List) ->
erlang:iolist_to_binary(List);
to_binary(Tuple, undefined) when is_tuple(Tuple) ->
to_binary(erlang:tuple_to_list(Tuple));
to_binary(PID, undefined) when is_pid(PID) ->
erlang:list_to_binary(erlang:pid_to_list(PID));
to_binary(Term, _) ->
erlang:iolist_to_binary(io_lib:format("~p", [Term])).
| null | https://raw.githubusercontent.com/williamthome/eel/7f933858c4346c5adacabd748b4ef6f8df832c26/src/eel_convert.erl | erlang | -----------------------------------------------------------------------------
@doc EEl converter module.
@end
----------------------------------------------------------------------------- | @author [ ]
-module(eel_convert).
-export([to_binary/1, to_binary/2]).
to_binary(Value) ->
to_binary(Value, undefined).
to_binary(Bin, _) when is_binary(Bin) ->
Bin;
to_binary(undefined, _) ->
<<>>;
to_binary([], _) ->
<<>>;
to_binary(Atom, undefined) when is_atom(Atom) ->
erlang:atom_to_binary(Atom);
to_binary(Atom, Encoding) when is_atom(Atom), is_atom(Encoding) ->
erlang:atom_to_binary(Atom, Encoding);
to_binary(Float, undefined) when is_float(Float) ->
erlang:float_to_binary(Float);
to_binary(Float, Options) when is_float(Float), is_list(Options) ->
erlang:float_to_binary(Float, Options);
to_binary(Int, undefined) when is_integer(Int) ->
erlang:integer_to_binary(Int);
to_binary(Int, Base) when is_integer(Int), is_integer(Base) ->
erlang:integer_to_binary(Int, Base);
to_binary(List, undefined) when is_list(List) ->
erlang:iolist_to_binary(List);
to_binary(Tuple, undefined) when is_tuple(Tuple) ->
to_binary(erlang:tuple_to_list(Tuple));
to_binary(PID, undefined) when is_pid(PID) ->
erlang:list_to_binary(erlang:pid_to_list(PID));
to_binary(Term, _) ->
erlang:iolist_to_binary(io_lib:format("~p", [Term])).
|
eda04fff5b9a3f2e9b66a78b5ce826416b6acac9a7e650d23429da17ceb25537 | jacekschae/learn-datomic-course-files | handlers.clj | (ns cheffy.recipe.handlers
(:require [cheffy.recipe.db :as recipe-db]
[cheffy.responses :as responses]
[ring.util.response :as rr])
(:import (java.util UUID)))
(defn list-all-recipes
[{:keys [env claims] :as _request}]
(let [account-id (:sub claims)]
(rr/response (recipe-db/find-all-recipes (:datomic env) {:account-id account-id}))
))
(defn create-recipe!
[{:keys [env claims parameters] :as _request}]
(let [recipe-id (UUID/randomUUID)
account-id (:sub claims)
recipe (:body parameters)]
(recipe-db/transact-recipe (:datomic env) (assoc recipe :recipe-id recipe-id :account-id account-id))
(rr/created (str responses/base-url "/recipes/" recipe-id) {:recipe-id (str recipe-id)})
))
(defn retrieve-recipe
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
recipe (recipe-db/find-recipe-by-id (:datomic env) {:recipe-id (UUID/fromString recipe-id)})]
(if recipe
(rr/response recipe)
(rr/not-found {:type "recipe-not-found"
:message "Recipe not found"
:data (str "recipe-id " recipe-id)}))))
(defn update-recipe!
[{:keys [env claims parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
account-id (:sub claims)
recipe (:body parameters)]
(recipe-db/transact-recipe (:datomic env) (assoc recipe :recipe-id (UUID/fromString recipe-id) :account-id account-id))
(rr/status 204)
))
(defn delete-recipe!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)]
(recipe-db/retract-recipe (:datomic env) {:recipe-id (UUID/fromString recipe-id)})
(rr/status 204)
))
(defn create-step!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
step (:body parameters)
step-id (str (UUID/randomUUID))]
(recipe-db/transact-step (:datomic env) (assoc step :recipe-id recipe-id
:step-id step-id))
(rr/created
(str responses/base-url "/recipes/" recipe-id)
{:step-id step-id})))
(defn update-step!
[{:keys [env parameters] :as _request}]
(let [step (:body parameters)
recipe-id (-> parameters :path :recipe-id)]
(recipe-db/transact-step (:datomic env) (assoc step :recipe-id recipe-id))
(rr/status 204)))
(defn delete-step!
[{:keys [env parameters] :as _request}]
(let [step (:body parameters)]
(recipe-db/retract-step (:datomic env) step)
(rr/status 204)))
(defn create-ingredient!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
ingredient (:body parameters)
ingredient-id (str (UUID/randomUUID))]
(recipe-db/transact-ingredient (:datomic env) (assoc ingredient :recipe-id recipe-id
:ingredient-id ingredient-id))
(rr/created
(str responses/base-url "/recipes/" recipe-id)
{:ingredient-id ingredient-id})))
(defn update-ingredient!
[{:keys [env parameters] :as _request}]
(let [ingredient (:body parameters)
recipe-id (-> parameters :path :recipe-id)]
(recipe-db/transact-ingredient (:datomic env) (assoc ingredient :recipe-id recipe-id))
(rr/status 204)))
(defn delete-ingredient!
[{:keys [env parameters] :as _request}]
(let [ingredient (:body parameters)]
(recipe-db/retract-ingredient (:datomic env) ingredient)
(rr/status 204)))
(defn favorite-recipe!
[{:keys [env claims parameters] :as _request}]
(let [account-id (:sub claims)
recipe-id (-> parameters :path :recipe-id)]
(recipe-db/favorite-recipe (:datomic env) {:recipe-id recipe-id
:account-id account-id})
(rr/response 204)))
(defn unfavorite-recipe!
[{:keys [env claims parameters] :as _request}]
(let [account-id (:sub claims)
recipe-id (-> parameters :path :recipe-id)]
(recipe-db/unfavorite-recipe (:datomic env) {:recipe-id recipe-id
:account-id account-id})
(rr/response 204))) | null | https://raw.githubusercontent.com/jacekschae/learn-datomic-course-files/c337e9efe3744705fe2aac786cf87a89995517b9/increments/36-favorite-counter-tests/src/main/cheffy/recipe/handlers.clj | clojure | (ns cheffy.recipe.handlers
(:require [cheffy.recipe.db :as recipe-db]
[cheffy.responses :as responses]
[ring.util.response :as rr])
(:import (java.util UUID)))
(defn list-all-recipes
[{:keys [env claims] :as _request}]
(let [account-id (:sub claims)]
(rr/response (recipe-db/find-all-recipes (:datomic env) {:account-id account-id}))
))
(defn create-recipe!
[{:keys [env claims parameters] :as _request}]
(let [recipe-id (UUID/randomUUID)
account-id (:sub claims)
recipe (:body parameters)]
(recipe-db/transact-recipe (:datomic env) (assoc recipe :recipe-id recipe-id :account-id account-id))
(rr/created (str responses/base-url "/recipes/" recipe-id) {:recipe-id (str recipe-id)})
))
(defn retrieve-recipe
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
recipe (recipe-db/find-recipe-by-id (:datomic env) {:recipe-id (UUID/fromString recipe-id)})]
(if recipe
(rr/response recipe)
(rr/not-found {:type "recipe-not-found"
:message "Recipe not found"
:data (str "recipe-id " recipe-id)}))))
(defn update-recipe!
[{:keys [env claims parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
account-id (:sub claims)
recipe (:body parameters)]
(recipe-db/transact-recipe (:datomic env) (assoc recipe :recipe-id (UUID/fromString recipe-id) :account-id account-id))
(rr/status 204)
))
(defn delete-recipe!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)]
(recipe-db/retract-recipe (:datomic env) {:recipe-id (UUID/fromString recipe-id)})
(rr/status 204)
))
(defn create-step!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
step (:body parameters)
step-id (str (UUID/randomUUID))]
(recipe-db/transact-step (:datomic env) (assoc step :recipe-id recipe-id
:step-id step-id))
(rr/created
(str responses/base-url "/recipes/" recipe-id)
{:step-id step-id})))
(defn update-step!
[{:keys [env parameters] :as _request}]
(let [step (:body parameters)
recipe-id (-> parameters :path :recipe-id)]
(recipe-db/transact-step (:datomic env) (assoc step :recipe-id recipe-id))
(rr/status 204)))
(defn delete-step!
[{:keys [env parameters] :as _request}]
(let [step (:body parameters)]
(recipe-db/retract-step (:datomic env) step)
(rr/status 204)))
(defn create-ingredient!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
ingredient (:body parameters)
ingredient-id (str (UUID/randomUUID))]
(recipe-db/transact-ingredient (:datomic env) (assoc ingredient :recipe-id recipe-id
:ingredient-id ingredient-id))
(rr/created
(str responses/base-url "/recipes/" recipe-id)
{:ingredient-id ingredient-id})))
(defn update-ingredient!
[{:keys [env parameters] :as _request}]
(let [ingredient (:body parameters)
recipe-id (-> parameters :path :recipe-id)]
(recipe-db/transact-ingredient (:datomic env) (assoc ingredient :recipe-id recipe-id))
(rr/status 204)))
(defn delete-ingredient!
[{:keys [env parameters] :as _request}]
(let [ingredient (:body parameters)]
(recipe-db/retract-ingredient (:datomic env) ingredient)
(rr/status 204)))
(defn favorite-recipe!
[{:keys [env claims parameters] :as _request}]
(let [account-id (:sub claims)
recipe-id (-> parameters :path :recipe-id)]
(recipe-db/favorite-recipe (:datomic env) {:recipe-id recipe-id
:account-id account-id})
(rr/response 204)))
(defn unfavorite-recipe!
[{:keys [env claims parameters] :as _request}]
(let [account-id (:sub claims)
recipe-id (-> parameters :path :recipe-id)]
(recipe-db/unfavorite-recipe (:datomic env) {:recipe-id recipe-id
:account-id account-id})
(rr/response 204))) | |
8750e445f3d03b961f37dbf41e5b6e4ac1e3cff09b101a3a5a26f93db8fad36c | ocamllabs/ocaml-modular-implicits | float_record.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2007 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
type t = float;;
let make f = f;;
let from t = t;;
type s = {f : t};;
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/basic-float/float_record.ml | ocaml | *********************************************************************
OCaml
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 2007 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
type t = float;;
let make f = f;;
let from t = t;;
type s = {f : t};;
|
d5fe25f3c3f1a19f971b2a77f4dca651e459189b034a7c6941c8175fe1f587e6 | backtracking/ocamlgraph | dGraphView.mli | (**************************************************************************)
(* *)
(* This file is part of OcamlGraph. *)
(* *)
Copyright ( C ) 2009 - 2010
CEA ( Commissariat à )
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 , with a linking exception .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
(* See the file ../LICENSE for more details. *)
(* *)
(* Authors: *)
( )
(* - Jean-Denis Koeck () *)
- ( )
(* *)
(**************************************************************************)
(** View classes.
Each optional function [delay_node], [delay_edge] and [delay_cluster] of
this module may be used to indicate whether an element must be displayed
instantaneously (if the function returns [false]) or may be delayed for
latter display (if the function returns [true]). By default, each function
always returns [false]. It may be set for returning [true] from time to
time, improving efficiency. *)
open DGraphViewItem
(** Graph widget derived from [GnoCanvas.canvas].
Support zooming and scrolling. *)
class type ['vertex, 'edge, 'cluster] view = object
inherit GnoCanvas.canvas
method model : ('vertex, 'edge, 'cluster) DGraphModel.abstract_model
* { 2 Getters }
method get_node : 'vertex -> 'vertex view_item
method get_edge : 'edge -> 'edge view_item
method get_cluster : 'cluster -> 'cluster view_item
* { 2 Iterators }
method iter_nodes: ('vertex view_item -> unit) -> unit
method iter_edges: ('vertex view_item -> 'vertex view_item -> unit) -> unit
method iter_edges_e: ('edge view_item -> unit) -> unit
method iter_clusters: ('cluster view_item -> unit) -> unit
method iter_succ: ('vertex view_item -> unit) -> 'vertex view_item -> unit
method iter_pred: ('vertex view_item -> unit) -> 'vertex view_item -> unit
method iter_succ_e: ('edge view_item -> unit) -> 'vertex view_item -> unit
method iter_pred_e: ('edge view_item -> unit) -> 'vertex view_item -> unit
method : is it really useful ?
method iter_associated_vertex:
('vertex view_item -> unit) -> 'vertex view_item -> unit
* { 2 Membership functions }
method mem_edge: 'vertex view_item -> 'vertex view_item -> bool
method find_edge: 'vertex view_item -> 'vertex view_item -> 'edge view_item
method src: 'edge view_item -> 'vertex view_item
method dst: 'edge view_item -> 'vertex view_item
* { 2 Zooming }
method zoom_factor : float
(** The current zoom factor.*)
method zoom_to : float -> unit
(** Set an absolute zoom factor.*)
method zoom_in : unit -> unit
(** Increase [zoom_factor] by [zoom_factor*zoom_padding].*)
method zoom_out : unit -> unit
(** Decrease [zoom_factor] by [zoom_factor*zoom_padding].*)
method adapt_zoom : unit -> unit
(** Zoom in order to view the whole graph (bird eye view). *)
method set_zoom_padding: float -> unit
* Set the zoom padding used by [ zoom_in ] and [ zoom_out ] .
It defaults to 0.1 .
It defaults to 0.1. *)
method center_node: 'vertex view_item -> unit
(** Center canvas on a node. *)
(** {2 Highlighting} *)
method connect_highlighting_event: unit -> unit
method highlight: ?color: int32 * int32 -> 'vertex view_item -> unit
* Change the color of the given vertex item .
May be cancelled by [ ] .
If [ color ] is [ primary , secondary ] , then
[ primary ] is used except if the current color is [ primary ] . In this
case , [ secondary ] is used .
May be cancelled by [dehighlight].
If [color] is [primary,secondary], then
[primary] is used except if the current color is [primary]. In this
case, [secondary] is used. *)
method dehighlight: 'vertex view_item -> unit
(** Cancel [highlight]. *)
end
module type S = sig
type vertex
type edge
type cluster
val view:
?aa:bool (** Anti-aliasing *) ->
?delay_node:(vertex -> bool) ->
?delay_edge:(edge -> bool) ->
?delay_cluster:(cluster -> bool) ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(GObj.widget -> unit) ->
?show:bool ->
(vertex, edge, cluster) DGraphModel.abstract_model ->
(vertex, edge, cluster) view
* View as a Gnome Canvas .
Support zooming and scrolling .
Support zooming and scrolling. *)
end
module Make(V: Sig.HASHABLE)(E: Sig.HASHABLE)(C: Sig.HASHABLE) :
S with type vertex = V.t and type edge = E.t and type cluster = C.t
| null | https://raw.githubusercontent.com/backtracking/ocamlgraph/1c028af097339ca8bc379436f7bd9477fa3a49cd/dgraph/dGraphView.mli | ocaml | ************************************************************************
This file is part of OcamlGraph.
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
See the file ../LICENSE for more details.
Authors:
- Jean-Denis Koeck ()
************************************************************************
* View classes.
Each optional function [delay_node], [delay_edge] and [delay_cluster] of
this module may be used to indicate whether an element must be displayed
instantaneously (if the function returns [false]) or may be delayed for
latter display (if the function returns [true]). By default, each function
always returns [false]. It may be set for returning [true] from time to
time, improving efficiency.
* Graph widget derived from [GnoCanvas.canvas].
Support zooming and scrolling.
* The current zoom factor.
* Set an absolute zoom factor.
* Increase [zoom_factor] by [zoom_factor*zoom_padding].
* Decrease [zoom_factor] by [zoom_factor*zoom_padding].
* Zoom in order to view the whole graph (bird eye view).
* Center canvas on a node.
* {2 Highlighting}
* Cancel [highlight].
* Anti-aliasing | Copyright ( C ) 2009 - 2010
CEA ( Commissariat à )
Lesser General Public License as published by the Free Software
Foundation , version 2.1 , with a linking exception .
( )
- ( )
open DGraphViewItem
class type ['vertex, 'edge, 'cluster] view = object
inherit GnoCanvas.canvas
method model : ('vertex, 'edge, 'cluster) DGraphModel.abstract_model
* { 2 Getters }
method get_node : 'vertex -> 'vertex view_item
method get_edge : 'edge -> 'edge view_item
method get_cluster : 'cluster -> 'cluster view_item
* { 2 Iterators }
method iter_nodes: ('vertex view_item -> unit) -> unit
method iter_edges: ('vertex view_item -> 'vertex view_item -> unit) -> unit
method iter_edges_e: ('edge view_item -> unit) -> unit
method iter_clusters: ('cluster view_item -> unit) -> unit
method iter_succ: ('vertex view_item -> unit) -> 'vertex view_item -> unit
method iter_pred: ('vertex view_item -> unit) -> 'vertex view_item -> unit
method iter_succ_e: ('edge view_item -> unit) -> 'vertex view_item -> unit
method iter_pred_e: ('edge view_item -> unit) -> 'vertex view_item -> unit
method : is it really useful ?
method iter_associated_vertex:
('vertex view_item -> unit) -> 'vertex view_item -> unit
* { 2 Membership functions }
method mem_edge: 'vertex view_item -> 'vertex view_item -> bool
method find_edge: 'vertex view_item -> 'vertex view_item -> 'edge view_item
method src: 'edge view_item -> 'vertex view_item
method dst: 'edge view_item -> 'vertex view_item
* { 2 Zooming }
method zoom_factor : float
method zoom_to : float -> unit
method zoom_in : unit -> unit
method zoom_out : unit -> unit
method adapt_zoom : unit -> unit
method set_zoom_padding: float -> unit
* Set the zoom padding used by [ zoom_in ] and [ zoom_out ] .
It defaults to 0.1 .
It defaults to 0.1. *)
method center_node: 'vertex view_item -> unit
method connect_highlighting_event: unit -> unit
method highlight: ?color: int32 * int32 -> 'vertex view_item -> unit
* Change the color of the given vertex item .
May be cancelled by [ ] .
If [ color ] is [ primary , secondary ] , then
[ primary ] is used except if the current color is [ primary ] . In this
case , [ secondary ] is used .
May be cancelled by [dehighlight].
If [color] is [primary,secondary], then
[primary] is used except if the current color is [primary]. In this
case, [secondary] is used. *)
method dehighlight: 'vertex view_item -> unit
end
module type S = sig
type vertex
type edge
type cluster
val view:
?delay_node:(vertex -> bool) ->
?delay_edge:(edge -> bool) ->
?delay_cluster:(cluster -> bool) ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(GObj.widget -> unit) ->
?show:bool ->
(vertex, edge, cluster) DGraphModel.abstract_model ->
(vertex, edge, cluster) view
* View as a Gnome Canvas .
Support zooming and scrolling .
Support zooming and scrolling. *)
end
module Make(V: Sig.HASHABLE)(E: Sig.HASHABLE)(C: Sig.HASHABLE) :
S with type vertex = V.t and type edge = E.t and type cluster = C.t
|
d7f7a554b0fba6b135973205e534ea3a2a26ad2de381426d1cd3a7588e54b12b | facebook/duckling | Tests.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.AmountOfMoney.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import qualified Duckling.AmountOfMoney.AR.Tests as AR
import qualified Duckling.AmountOfMoney.CA.Tests as CA
import qualified Duckling.AmountOfMoney.EN.Tests as EN
import qualified Duckling.AmountOfMoney.BG.Tests as BG
import qualified Duckling.AmountOfMoney.ES.Tests as ES
import qualified Duckling.AmountOfMoney.FR.Tests as FR
import qualified Duckling.AmountOfMoney.GA.Tests as GA
import qualified Duckling.AmountOfMoney.HE.Tests as HE
import qualified Duckling.AmountOfMoney.HR.Tests as HR
import qualified Duckling.AmountOfMoney.ID.Tests as ID
import qualified Duckling.AmountOfMoney.IT.Tests as IT
import qualified Duckling.AmountOfMoney.KA.Tests as KA
import qualified Duckling.AmountOfMoney.KO.Tests as KO
import qualified Duckling.AmountOfMoney.MN.Tests as MN
import qualified Duckling.AmountOfMoney.NB.Tests as NB
import qualified Duckling.AmountOfMoney.NL.Tests as NL
import qualified Duckling.AmountOfMoney.PT.Tests as PT
import qualified Duckling.AmountOfMoney.RO.Tests as RO
import qualified Duckling.AmountOfMoney.RU.Tests as RU
import qualified Duckling.AmountOfMoney.SV.Tests as SV
import qualified Duckling.AmountOfMoney.TR.Tests as TR
import qualified Duckling.AmountOfMoney.VI.Tests as VI
import qualified Duckling.AmountOfMoney.ZH.Tests as ZH
tests :: TestTree
tests = testGroup "AmountOfMoney Tests"
[ AR.tests
, BG.tests
, CA.tests
, EN.tests
, ES.tests
, FR.tests
, GA.tests
, HE.tests
, HR.tests
, ID.tests
, IT.tests
, KA.tests
, KO.tests
, MN.tests
, NB.tests
, NL.tests
, PT.tests
, RO.tests
, RU.tests
, SV.tests
, TR.tests
, VI.tests
, ZH.tests
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/AmountOfMoney/Tests.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.AmountOfMoney.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import qualified Duckling.AmountOfMoney.AR.Tests as AR
import qualified Duckling.AmountOfMoney.CA.Tests as CA
import qualified Duckling.AmountOfMoney.EN.Tests as EN
import qualified Duckling.AmountOfMoney.BG.Tests as BG
import qualified Duckling.AmountOfMoney.ES.Tests as ES
import qualified Duckling.AmountOfMoney.FR.Tests as FR
import qualified Duckling.AmountOfMoney.GA.Tests as GA
import qualified Duckling.AmountOfMoney.HE.Tests as HE
import qualified Duckling.AmountOfMoney.HR.Tests as HR
import qualified Duckling.AmountOfMoney.ID.Tests as ID
import qualified Duckling.AmountOfMoney.IT.Tests as IT
import qualified Duckling.AmountOfMoney.KA.Tests as KA
import qualified Duckling.AmountOfMoney.KO.Tests as KO
import qualified Duckling.AmountOfMoney.MN.Tests as MN
import qualified Duckling.AmountOfMoney.NB.Tests as NB
import qualified Duckling.AmountOfMoney.NL.Tests as NL
import qualified Duckling.AmountOfMoney.PT.Tests as PT
import qualified Duckling.AmountOfMoney.RO.Tests as RO
import qualified Duckling.AmountOfMoney.RU.Tests as RU
import qualified Duckling.AmountOfMoney.SV.Tests as SV
import qualified Duckling.AmountOfMoney.TR.Tests as TR
import qualified Duckling.AmountOfMoney.VI.Tests as VI
import qualified Duckling.AmountOfMoney.ZH.Tests as ZH
tests :: TestTree
tests = testGroup "AmountOfMoney Tests"
[ AR.tests
, BG.tests
, CA.tests
, EN.tests
, ES.tests
, FR.tests
, GA.tests
, HE.tests
, HR.tests
, ID.tests
, IT.tests
, KA.tests
, KO.tests
, MN.tests
, NB.tests
, NL.tests
, PT.tests
, RO.tests
, RU.tests
, SV.tests
, TR.tests
, VI.tests
, ZH.tests
]
|
d8ea6ad159d77b933f18faac2ed5e0a93954182ae97bc91a626dd9c0bc47a9c4 | ulfsauer0815/ghmm | Message.hs | {-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
| Rendering of GitHub events as Mattermost messages .
module Mattermost.Github.Message
( renderMessage
, renderMessage'
, messageTemplate
) where
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import Github.Api hiding (repository)
import Github.Event.Predicate
import Mattermost.Types
import Message.Markdown
-- ----------------------------------------------
| Render a GitHub ' EventPayload ' as a Mattermost ' MessagePayload ' .
--
-- Uses a message template for generic fields, see 'messageTemplate' and
-- 'renderMessage''.
renderMessage :: EventPayload -> MessagePayload
renderMessage = renderMessage' messageTemplate
| Render a GitHub ' EventPayload ' as a Mattermost ' MessagePayload ' using the
-- supplied message template.
renderMessage' :: MessagePayload -> EventPayload -> MessagePayload
renderMessage' message event
= case event of
PingEvent zen _hookId repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just zen
, attColor = Just "#000000"
}
]
}
where
text =
repoPrefix repository
<> "Ping"
PushEvent ref commits _headCommit compareUrl repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just commitsList
, attColor = Just "#CCCCCC"
}
]
}
where
commitsList = uln . itemize . map (firstLine . pcmMessage) $ commits
text =
let commitsText = (T.pack . show $ commitsLength) <> " commit" <> if commitsLength == 1 then "" else "s"
commitsLength = length commits
branch = optBranch (repDefault_branch repository) ref
in repoPrefix repository
<> link "Push" compareUrl <> ": " <> commitsText <> (tl " on " . codeblock) branch
PullRequestEvent action _ (PullRequest number htmlUrl _state title merged mergedBy prUser) repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just title
, attAuthor_name = Just $ usrLogin prUser
, attColor = Just color
, attFields = [
Field
{ fldShort = True
, fldTitle = Just "Action"
, fldValue = Just actionText
}
]
<> if wasJustMerged then [
Field
{ fldShort = True
, fldTitle = Just "Merged by"
, fldValue = usrLogin <$> mergedBy
}
]
else mempty
}
]
}
where
text = repoPrefix repository
<> link ("Pull Request" <> (tl " #" . T.pack . show) number) htmlUrl
actionText = if | wasJustMerged -> "merged"
| action == "synchronized" -> "sync"
| otherwise -> action
color = if | wasJustMerged -> "#6E5494"
| action == "opened"
|| action == "reopened" -> "#23A2FF"
| action == "closed" -> "#FF9999"
| otherwise -> "#99D4FF"
wasJustMerged = action == "closed" && fromMaybe False merged
StatusEvent _ state description (StatusCommit sha commitUrl commit) targetUrl repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = description
, attColor = Just $ if state == "success" then "#00FF00" else "#FF0000"
}
]
}
where
text =
let htmlUrl = fromEmpty commitUrl targetUrl
in repoPrefix repository
<> link ("Status (" <> shaify sha <> ")") htmlUrl <> ": " <> (firstLine . cmtMessage) commit
IssuesEvent action (Issue number _state title body htmlUrl user _) repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just body
, attAuthor_name = Just $ usrLogin user
, attColor = Just color
, attFields = [
Field
{ fldShort = True
, fldTitle = Just "Action"
, fldValue = Just action
}
]
}
]
}
where
text =
repoPrefix repository
<> link ("Issue #" <> (T.pack . show) number) htmlUrl <> tl ": " title
color = if | action == "opened"
|| action == "reopened" -> "#CC317C"
| action == "closed" -> "#6E5494"
| otherwise -> "#CC7AA2"
IssueCommentEvent action (Issue _number _state title _ _ _ _) (Comment commentHtmlUrl commentBody commentUser _) repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just $ blockquote commentBody
, attAuthor_name = Just $ usrLogin commentUser
, attColor = Just color
}
]
}
where
text =
let optAction = if action == "created" then "" else action
in repoPrefix repository
<> link "Comment" commentHtmlUrl <> (ml . italic) optAction <> tl ": " title
color = if | isClosingIssueComment event -> "#6E5494"
| otherwise -> "#FFD9B3"
PullRequestReviewEvent _action (Review rvHtmlUrl rvBody _state rvUser) (PullRequest number _ _prState title _merged _mergedBy _user) repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just $ blockquote rvBody
, attAuthor_name = Just $ usrLogin rvUser
, attColor = Just "#FFC080"
}
]
}
where
text =
repoPrefix repository
<> link ("Pull Request #" <> (T.pack . show) number <> " Review") rvHtmlUrl <> tl ": " title
PullRequestReviewCommentEvent action (Comment commentHtmlUrl commentBody commentUser _) (PullRequest number _ _state title _merged _mergedBy _user) repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just $ blockquote commentBody
, attAuthor_name = Just $ usrLogin commentUser
, attColor = Just "#FFD9B3"
}
]
}
where
text =
let optAction = if action == "created" then "" else italic action
in repoPrefix repository
<> link ("Pull Request #" <> (T.pack . show) number <> ml "Review Comment") commentHtmlUrl <> (ml . italic) optAction <> tl ": " title
where
optBranch defaultBranch ref =
if ref /= "refs/heads/" <> defaultBranch then lastSegment ref else ""
lastSegment = last . T.splitOn "/"
repoPrefix repo = "[" <> link (repName repo) (repHtml_url repo) <> "] "
firstLine = T.takeWhile (/= '\n')
shaify t = "#" <> T.take 7 t
fromEmpty x (Just "") = x
fromEmpty _ (Just y) = y
fromEmpty x Nothing = x
-- | Default Mattermost message template.
messageTemplate :: MessagePayload
messageTemplate = MessagePayload
{ mptText = Nothing
, mptUsername = Just "GitHub"
, mptIcon_url = Just ""
, mptChannel = Nothing
, mptAttachments = []
}
| null | https://raw.githubusercontent.com/ulfsauer0815/ghmm/fc81948316156c67f6af9fe08a8a49472e9a42b8/src/Mattermost/Github/Message.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
----------------------------------------------
Uses a message template for generic fields, see 'messageTemplate' and
'renderMessage''.
supplied message template.
| Default Mattermost message template. |
| Rendering of GitHub events as Mattermost messages .
module Mattermost.Github.Message
( renderMessage
, renderMessage'
, messageTemplate
) where
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import Github.Api hiding (repository)
import Github.Event.Predicate
import Mattermost.Types
import Message.Markdown
| Render a GitHub ' EventPayload ' as a Mattermost ' MessagePayload ' .
renderMessage :: EventPayload -> MessagePayload
renderMessage = renderMessage' messageTemplate
| Render a GitHub ' EventPayload ' as a Mattermost ' MessagePayload ' using the
renderMessage' :: MessagePayload -> EventPayload -> MessagePayload
renderMessage' message event
= case event of
PingEvent zen _hookId repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just zen
, attColor = Just "#000000"
}
]
}
where
text =
repoPrefix repository
<> "Ping"
PushEvent ref commits _headCommit compareUrl repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just commitsList
, attColor = Just "#CCCCCC"
}
]
}
where
commitsList = uln . itemize . map (firstLine . pcmMessage) $ commits
text =
let commitsText = (T.pack . show $ commitsLength) <> " commit" <> if commitsLength == 1 then "" else "s"
commitsLength = length commits
branch = optBranch (repDefault_branch repository) ref
in repoPrefix repository
<> link "Push" compareUrl <> ": " <> commitsText <> (tl " on " . codeblock) branch
PullRequestEvent action _ (PullRequest number htmlUrl _state title merged mergedBy prUser) repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just title
, attAuthor_name = Just $ usrLogin prUser
, attColor = Just color
, attFields = [
Field
{ fldShort = True
, fldTitle = Just "Action"
, fldValue = Just actionText
}
]
<> if wasJustMerged then [
Field
{ fldShort = True
, fldTitle = Just "Merged by"
, fldValue = usrLogin <$> mergedBy
}
]
else mempty
}
]
}
where
text = repoPrefix repository
<> link ("Pull Request" <> (tl " #" . T.pack . show) number) htmlUrl
actionText = if | wasJustMerged -> "merged"
| action == "synchronized" -> "sync"
| otherwise -> action
color = if | wasJustMerged -> "#6E5494"
| action == "opened"
|| action == "reopened" -> "#23A2FF"
| action == "closed" -> "#FF9999"
| otherwise -> "#99D4FF"
wasJustMerged = action == "closed" && fromMaybe False merged
StatusEvent _ state description (StatusCommit sha commitUrl commit) targetUrl repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = description
, attColor = Just $ if state == "success" then "#00FF00" else "#FF0000"
}
]
}
where
text =
let htmlUrl = fromEmpty commitUrl targetUrl
in repoPrefix repository
<> link ("Status (" <> shaify sha <> ")") htmlUrl <> ": " <> (firstLine . cmtMessage) commit
IssuesEvent action (Issue number _state title body htmlUrl user _) repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just body
, attAuthor_name = Just $ usrLogin user
, attColor = Just color
, attFields = [
Field
{ fldShort = True
, fldTitle = Just "Action"
, fldValue = Just action
}
]
}
]
}
where
text =
repoPrefix repository
<> link ("Issue #" <> (T.pack . show) number) htmlUrl <> tl ": " title
color = if | action == "opened"
|| action == "reopened" -> "#CC317C"
| action == "closed" -> "#6E5494"
| otherwise -> "#CC7AA2"
IssueCommentEvent action (Issue _number _state title _ _ _ _) (Comment commentHtmlUrl commentBody commentUser _) repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just $ blockquote commentBody
, attAuthor_name = Just $ usrLogin commentUser
, attColor = Just color
}
]
}
where
text =
let optAction = if action == "created" then "" else action
in repoPrefix repository
<> link "Comment" commentHtmlUrl <> (ml . italic) optAction <> tl ": " title
color = if | isClosingIssueComment event -> "#6E5494"
| otherwise -> "#FFD9B3"
PullRequestReviewEvent _action (Review rvHtmlUrl rvBody _state rvUser) (PullRequest number _ _prState title _merged _mergedBy _user) repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just $ blockquote rvBody
, attAuthor_name = Just $ usrLogin rvUser
, attColor = Just "#FFC080"
}
]
}
where
text =
repoPrefix repository
<> link ("Pull Request #" <> (T.pack . show) number <> " Review") rvHtmlUrl <> tl ": " title
PullRequestReviewCommentEvent action (Comment commentHtmlUrl commentBody commentUser _) (PullRequest number _ _state title _merged _mergedBy _user) repository ->
message
{ mptAttachments = [
attachment
{ attPretext = Just text
, attText = Just $ blockquote commentBody
, attAuthor_name = Just $ usrLogin commentUser
, attColor = Just "#FFD9B3"
}
]
}
where
text =
let optAction = if action == "created" then "" else italic action
in repoPrefix repository
<> link ("Pull Request #" <> (T.pack . show) number <> ml "Review Comment") commentHtmlUrl <> (ml . italic) optAction <> tl ": " title
where
optBranch defaultBranch ref =
if ref /= "refs/heads/" <> defaultBranch then lastSegment ref else ""
lastSegment = last . T.splitOn "/"
repoPrefix repo = "[" <> link (repName repo) (repHtml_url repo) <> "] "
firstLine = T.takeWhile (/= '\n')
shaify t = "#" <> T.take 7 t
fromEmpty x (Just "") = x
fromEmpty _ (Just y) = y
fromEmpty x Nothing = x
messageTemplate :: MessagePayload
messageTemplate = MessagePayload
{ mptText = Nothing
, mptUsername = Just "GitHub"
, mptIcon_url = Just ""
, mptChannel = Nothing
, mptAttachments = []
}
|
a333da2bde233a03440d8aba769016728c75424701156fe1707ec50d36db03b3 | softlab-ntua/bencherl | my_plugin_example.erl | Copyright ( C ) 2014 EDF R&D
This file is part of Sim - Diasca .
Sim - Diasca is free software : you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
Sim - Diasca 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 .
% If not, see </>.
Author : ( )
% This is a typical plugin example, to be re-used as a guide to develop actual
plugins .
%
-module(my_plugin_example).
-behaviour(sim_diasca_plugin).
-export([
on_simulator_start/2,
on_deployment_start/1,
on_deployment_stop/1,
on_technical_settings_available/2,
on_case_initialisation_start/1,
on_case_initialisation_stop/1,
on_simulation_start/1,
on_simulation_bootstrap_start/1,
on_simulation_bootstrap_stop/1,
on_simulation_wallclock_milestone_met/2,
on_simulation_tick_milestone_met/2,
on_simulation_stop/1,
on_result_gathering_start/1,
on_result_gathering_stop/1,
on_simulator_stop/1,
on_case_specific_event/3
]).
For the notify/1 macro :
-include("traces.hrl").
% For the technical_settings record:
-include("sim_diasca_plugin.hrl").
% Shorthand:
-type plug_data() :: sim_diasca_plugin:plugin_data().
% Implementation notes.
%
% This plugin is stateless: its state, as recorded by the plugin manager
( specified as the PluginData parameter ) , will be first ' undefined ' ( the
% default), then 'ok', and kept to this value.
% Callcack section, as requested by the 'sim_diasca_plugin' behaviour.
% Callback triggered as soon as the simulator is started (or almost, as basic
% services, including the trace one, are already up).
%
% This plugin may update these requested configuration changes, which may come
% from other plugins and may be in turn be changed by others.
% The on_technical_settings_available/2 callback could allow to check the
% effectiveness of this request (ex: if plugins requested incompatible changes).
%
-spec on_simulator_start( sim_diasca_plugin:configuration_changes(),
sim_diasca_plugin:plugin_data() ) ->
{ sim_diasca_plugin:configuration_changes(),
sim_diasca_plugin:plugin_data() }.
on_simulator_start( ConfigurationChanges, _PluginData ) ->
% One may look at the traces sent by the deployment agent(s) to check the
% actual number of sequencers:
notify( io_lib:format( "simulator started; keeping as are following "
"input configuration changes: ~p.",
[ ConfigurationChanges ] ) ),
{ ConfigurationChanges, ok }.
% As an example, one may use this code instead:
SchedulerCount = 2 ,
%notify( io_lib:format( "simulator started; changing configuration, "
% "requesting ~B schedulers.",
[ SchedulerCount ] ) ) ,
%NewConfigurationChanges = ConfigurationChanges#configuration_changes{
% compute_scheduler_count=SchedulerCount },
%{ NewConfigurationChanges, ok }.
% Callback triggered when the deployment phase starts.
%
-spec on_deployment_start( plug_data() ) -> plug_data().
on_deployment_start( _PluginData ) ->
notify( "deployment started" ),
ok.
% Callback triggered when the deployment phase stops.
%
-spec on_deployment_stop( plug_data() ) -> plug_data().
on_deployment_stop( _PluginData ) ->
notify( "deployment stopped" ),
ok.
% Callback triggered when the simulation technical settings are available,
% notably once the deployment phase is over.
%
-spec on_technical_settings_available( sim_diasca_plugin:technical_settings(),
plug_data() ) -> plug_data().
on_technical_settings_available(
#technical_settings{ computing_nodes=ComputingNodes,
cookie=Cookie },
_PluginData ) ->
NodeString = io_lib:format(
"cookie '~s' used for the ~B computing node(s):~s",
[ Cookie,
length( ComputingNodes ),
text_utils:atom_list_to_string( ComputingNodes ) ] ),
notify( "technical details available: " ++ NodeString ),
ok.
% Callback triggered when the creation of the initial state of the simulation
% starts.
%
-spec on_case_initialisation_start( plug_data() ) -> plug_data().
on_case_initialisation_start( _PluginData ) ->
notify( "case initialisation started" ),
ok.
% Callback triggered when the creation of the initial state of the simulation
% just finished.
%
-spec on_case_initialisation_stop( plug_data() ) -> plug_data().
on_case_initialisation_stop( _PluginData ) ->
notify( "case initialisation stopped" ),
ok.
% Callback triggered when the simulation is just started and must evaluate the
first diasca of all initial actors .
%
-spec on_simulation_bootstrap_start( plug_data() ) -> plug_data().
on_simulation_bootstrap_start( _PluginData ) ->
notify( "simulation bootstrap started" ),
ok.
Callback triggered when the evaluation of the first diasca of all initial
% actors is over.
%
-spec on_simulation_bootstrap_stop( plug_data() ) -> plug_data().
on_simulation_bootstrap_stop( _PluginData ) ->
notify( "simulation bootstrap stopped" ),
ok.
% Callback triggered when a simulation milestone is met in wallclock time,
% i.e. after some elapsed duration.
%
-spec on_simulation_wallclock_milestone_met( unit_utils:milliseconds(),
plug_data() ) -> plug_data().
on_simulation_wallclock_milestone_met( CurrentMillisecond, _PluginData ) ->
notify( io_lib:format( "simulation wall-clock milestone met, "
"after ~s; current wallclock time is ~s.",
[ text_utils:duration_to_string( CurrentMillisecond ),
basic_utils:get_textual_timestamp() ] ) ),
ok.
% Callback triggered when a simulation milestone is met in virtual time,
% i.e. when enough ticks have been evaluated.
%
-spec on_simulation_tick_milestone_met( class_TimeManager:tick_offset(),
plug_data() ) -> plug_data().
on_simulation_tick_milestone_met( TickOffset, _PluginData ) ->
notify( io_lib:format( "simulation tick milestone met at "
"tick offset #~B, while current "
"wall-clock time is ~s.",
[ TickOffset,
basic_utils:get_textual_timestamp() ] ) ),
ok.
Callback triggered when the simulation is started ( first tick , first diasca ) .
%
-spec on_simulation_start( plug_data() ) -> plug_data().
on_simulation_start( _PluginData ) ->
notify( "simulation started" ),
ok.
% Callback triggered when the simulation is stopped (an ending criterion was
% just met).
%
-spec on_simulation_stop( plug_data() ) -> plug_data().
on_simulation_stop( _PluginData ) ->
notify( "simulation stopped" ),
ok.
% Callback triggered when the results start being gathered, after simulation
% termination.
%
-spec on_result_gathering_start( plug_data() ) -> plug_data().
on_result_gathering_start( _PluginData ) ->
notify( "result gathering started" ),
ok.
% Callback triggered when the results have been gathered.
%
-spec on_result_gathering_stop( plug_data() ) -> plug_data().
on_result_gathering_stop( _PluginData ) ->
notify( "result gathering stopped" ),
ok.
% Callback triggered when the simulator execution stopped under normal
% circumstances (i.e. not crashing).
%
-spec on_simulator_stop( plug_data() ) -> plug_data().
on_simulator_stop( _PluginData ) ->
notify( "simulator stopped" ),
ok.
% Callback triggered when the simulator execution stopped under normal
% circumstances (i.e. not crashing).
%
-spec on_case_specific_event( sim_diasca_plugin:case_specific_event(),
sim_diasca_plugin:event_data(), plug_data() ) ->
plug_data().
on_case_specific_event( _CaseSpecificEvent, _EventData, _PluginData ) ->
% Currently disabled, as too verbose, and duplicating traces already sent
% from the simulation case:
%
notify ( io_lib : format ( " [ ~s ] ~s " , [ CaseSpecificEvent , EventData ] ) ) ,
ok.
% Helper section.
% Helper.
notify( _Message ) ->
% We can even use our dedicated trace sub-channel:
% Here we both output the message on the console and in our dedicated trace
% sub-channel:
%
% (no mute variable here: not wanting spurious matchings)
%
Parameters : Message , EmitterName , EmitterCategorization ,
MessageCategorization
%
%?notify_em( Message, "my_plugin_example", "Core.PluginManagement",
% "Uncategorized" ).
% Here we just send a (maskable) trace, no console output:
%?notify_info_em( Message, "my_plugin_example", "Core.PluginManagement",
% "Uncategorized" ),
ok.
| null | https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/sim-diasca/sim-diasca/src/core/src/plugins/tests/my_plugin_example.erl | erlang | it under the terms of the GNU Lesser General Public License as
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
If not, see </>.
This is a typical plugin example, to be re-used as a guide to develop actual
For the technical_settings record:
Shorthand:
Implementation notes.
This plugin is stateless: its state, as recorded by the plugin manager
default), then 'ok', and kept to this value.
Callcack section, as requested by the 'sim_diasca_plugin' behaviour.
Callback triggered as soon as the simulator is started (or almost, as basic
services, including the trace one, are already up).
This plugin may update these requested configuration changes, which may come
from other plugins and may be in turn be changed by others.
The on_technical_settings_available/2 callback could allow to check the
effectiveness of this request (ex: if plugins requested incompatible changes).
One may look at the traces sent by the deployment agent(s) to check the
actual number of sequencers:
As an example, one may use this code instead:
notify( io_lib:format( "simulator started; changing configuration, "
"requesting ~B schedulers.",
NewConfigurationChanges = ConfigurationChanges#configuration_changes{
compute_scheduler_count=SchedulerCount },
{ NewConfigurationChanges, ok }.
Callback triggered when the deployment phase starts.
Callback triggered when the deployment phase stops.
Callback triggered when the simulation technical settings are available,
notably once the deployment phase is over.
Callback triggered when the creation of the initial state of the simulation
starts.
Callback triggered when the creation of the initial state of the simulation
just finished.
Callback triggered when the simulation is just started and must evaluate the
actors is over.
Callback triggered when a simulation milestone is met in wallclock time,
i.e. after some elapsed duration.
Callback triggered when a simulation milestone is met in virtual time,
i.e. when enough ticks have been evaluated.
Callback triggered when the simulation is stopped (an ending criterion was
just met).
Callback triggered when the results start being gathered, after simulation
termination.
Callback triggered when the results have been gathered.
Callback triggered when the simulator execution stopped under normal
circumstances (i.e. not crashing).
Callback triggered when the simulator execution stopped under normal
circumstances (i.e. not crashing).
Currently disabled, as too verbose, and duplicating traces already sent
from the simulation case:
Helper section.
Helper.
We can even use our dedicated trace sub-channel:
Here we both output the message on the console and in our dedicated trace
sub-channel:
(no mute variable here: not wanting spurious matchings)
?notify_em( Message, "my_plugin_example", "Core.PluginManagement",
"Uncategorized" ).
Here we just send a (maskable) trace, no console output:
?notify_info_em( Message, "my_plugin_example", "Core.PluginManagement",
"Uncategorized" ), | Copyright ( C ) 2014 EDF R&D
This file is part of Sim - Diasca .
Sim - Diasca is free software : you can redistribute it and/or modify
published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
Sim - Diasca is distributed in the hope that it will be useful ,
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with .
Author : ( )
plugins .
-module(my_plugin_example).
-behaviour(sim_diasca_plugin).
-export([
on_simulator_start/2,
on_deployment_start/1,
on_deployment_stop/1,
on_technical_settings_available/2,
on_case_initialisation_start/1,
on_case_initialisation_stop/1,
on_simulation_start/1,
on_simulation_bootstrap_start/1,
on_simulation_bootstrap_stop/1,
on_simulation_wallclock_milestone_met/2,
on_simulation_tick_milestone_met/2,
on_simulation_stop/1,
on_result_gathering_start/1,
on_result_gathering_stop/1,
on_simulator_stop/1,
on_case_specific_event/3
]).
For the notify/1 macro :
-include("traces.hrl").
-include("sim_diasca_plugin.hrl").
-type plug_data() :: sim_diasca_plugin:plugin_data().
( specified as the PluginData parameter ) , will be first ' undefined ' ( the
-spec on_simulator_start( sim_diasca_plugin:configuration_changes(),
sim_diasca_plugin:plugin_data() ) ->
{ sim_diasca_plugin:configuration_changes(),
sim_diasca_plugin:plugin_data() }.
on_simulator_start( ConfigurationChanges, _PluginData ) ->
notify( io_lib:format( "simulator started; keeping as are following "
"input configuration changes: ~p.",
[ ConfigurationChanges ] ) ),
{ ConfigurationChanges, ok }.
SchedulerCount = 2 ,
[ SchedulerCount ] ) ) ,
-spec on_deployment_start( plug_data() ) -> plug_data().
on_deployment_start( _PluginData ) ->
notify( "deployment started" ),
ok.
-spec on_deployment_stop( plug_data() ) -> plug_data().
on_deployment_stop( _PluginData ) ->
notify( "deployment stopped" ),
ok.
-spec on_technical_settings_available( sim_diasca_plugin:technical_settings(),
plug_data() ) -> plug_data().
on_technical_settings_available(
#technical_settings{ computing_nodes=ComputingNodes,
cookie=Cookie },
_PluginData ) ->
NodeString = io_lib:format(
"cookie '~s' used for the ~B computing node(s):~s",
[ Cookie,
length( ComputingNodes ),
text_utils:atom_list_to_string( ComputingNodes ) ] ),
notify( "technical details available: " ++ NodeString ),
ok.
-spec on_case_initialisation_start( plug_data() ) -> plug_data().
on_case_initialisation_start( _PluginData ) ->
notify( "case initialisation started" ),
ok.
-spec on_case_initialisation_stop( plug_data() ) -> plug_data().
on_case_initialisation_stop( _PluginData ) ->
notify( "case initialisation stopped" ),
ok.
first diasca of all initial actors .
-spec on_simulation_bootstrap_start( plug_data() ) -> plug_data().
on_simulation_bootstrap_start( _PluginData ) ->
notify( "simulation bootstrap started" ),
ok.
Callback triggered when the evaluation of the first diasca of all initial
-spec on_simulation_bootstrap_stop( plug_data() ) -> plug_data().
on_simulation_bootstrap_stop( _PluginData ) ->
notify( "simulation bootstrap stopped" ),
ok.
-spec on_simulation_wallclock_milestone_met( unit_utils:milliseconds(),
plug_data() ) -> plug_data().
on_simulation_wallclock_milestone_met( CurrentMillisecond, _PluginData ) ->
notify( io_lib:format( "simulation wall-clock milestone met, "
"after ~s; current wallclock time is ~s.",
[ text_utils:duration_to_string( CurrentMillisecond ),
basic_utils:get_textual_timestamp() ] ) ),
ok.
-spec on_simulation_tick_milestone_met( class_TimeManager:tick_offset(),
plug_data() ) -> plug_data().
on_simulation_tick_milestone_met( TickOffset, _PluginData ) ->
notify( io_lib:format( "simulation tick milestone met at "
"tick offset #~B, while current "
"wall-clock time is ~s.",
[ TickOffset,
basic_utils:get_textual_timestamp() ] ) ),
ok.
Callback triggered when the simulation is started ( first tick , first diasca ) .
-spec on_simulation_start( plug_data() ) -> plug_data().
on_simulation_start( _PluginData ) ->
notify( "simulation started" ),
ok.
-spec on_simulation_stop( plug_data() ) -> plug_data().
on_simulation_stop( _PluginData ) ->
notify( "simulation stopped" ),
ok.
-spec on_result_gathering_start( plug_data() ) -> plug_data().
on_result_gathering_start( _PluginData ) ->
notify( "result gathering started" ),
ok.
-spec on_result_gathering_stop( plug_data() ) -> plug_data().
on_result_gathering_stop( _PluginData ) ->
notify( "result gathering stopped" ),
ok.
-spec on_simulator_stop( plug_data() ) -> plug_data().
on_simulator_stop( _PluginData ) ->
notify( "simulator stopped" ),
ok.
-spec on_case_specific_event( sim_diasca_plugin:case_specific_event(),
sim_diasca_plugin:event_data(), plug_data() ) ->
plug_data().
on_case_specific_event( _CaseSpecificEvent, _EventData, _PluginData ) ->
notify ( io_lib : format ( " [ ~s ] ~s " , [ CaseSpecificEvent , EventData ] ) ) ,
ok.
notify( _Message ) ->
Parameters : Message , EmitterName , EmitterCategorization ,
MessageCategorization
ok.
|
62a1a9a82600578147c645b52cf8f68794f7c040f1778e8451b2675ba5d46eec | DaMSL/K3 | Graph.hs | # LANGUAGE PatternGuards #
-- | Dependent type-manifestation using graph traversal.
--
-- This module defines an algorithm and supporting machinery to perform dependent type manifestation
-- on a consistent constraint set obtained from a successful typechecking run.
--
-- The algorithm picks types for type variables whilst respecting constraints between them.
-- Equivalent variables are naturally manifested identically, constrained variables are manifested
-- such that the manifest types still satisfy their constraints.
module Language.K3.TypeSystem.Manifestation.Graph where
import Control.Applicative
import Data.Functor.Identity
import Data.Maybe
import Data.Tuple (swap)
import qualified Data.Graph.Wrapper as G
import qualified Data.Map as M
import qualified Data.Set as S
import Language.K3.Core.Annotation
import Language.K3.Core.Common
import Language.K3.Core.Type
import Language.K3.TypeSystem.Data.Constraints
import Language.K3.TypeSystem.Data.Coproduct
import Language.K3.TypeSystem.Data.Types
import Language.K3.TypeSystem.Data.ConstraintSet
import Language.K3.TypeSystem.Data.Result
import Language.K3.TypeSystem.Manifestation.Data
-- | A graph containing a set of equivalent type variables at each vertex, and an edge from
-- supertypes to subtypes.
type ManifestGraph = G.Graph (S.Set UID) (BoundType, K3 Type, K3 Type)
| Construct a ManifestGraph from the result of typechecking .
--
-- This involves creating a sanitized version of the constraint set (containing only source
-- variables) and turning constraints into edges.
fromTypecheckResult :: TypecheckResult -> Maybe ManifestGraph
fromTypecheckResult result = do
(tVarMap, constraintSet) <- tcExprTypes result
boundsMap <- tcExprBounds result
lowerFunctionBounds <- fmap (S.map swap) $ M.lookup () $ indexAllTypesLowerBoundingAnyVars constraintSet
upperFunctionBounds <- M.lookup () $ indexAllTypesUpperBoundingAnyVars constraintSet
let polarityMap = deducePolarity (S.union lowerFunctionBounds upperFunctionBounds)
let narrowedConstraintMap = narrowAndReduce tVarMap (indexBoundingConstraintsByUVar constraintSet)
let consolidatedVertices = attachPayload polarityMap tVarMap boundsMap narrowedConstraintMap
let consolidatedEdges = map swap . S.toList . S.unions $ M.elems narrowedConstraintMap
return $ G.fromVerticesEdges consolidatedVertices consolidatedEdges
where
-- | Construct the payload for each set of equivalent type variables.
attachPayload pm tvm bm ncm =
[ (u, (p, lb, ub))
| u <- M.keys ncm
, let p = andBoundType $ catMaybes $ map (\k -> M.lookup k tvm >>= \k' -> M.lookup k' pm) $ S.toList u
, let Just (lb, ub) = M.lookup (S.findMin u) bm
]
andBoundType :: [BoundType] -> BoundType
andBoundType [] = UpperBound
andBoundType (LowerBound:_) = LowerBound
andBoundType (_:bs) = andBoundType bs
decideManifestation :: ManifestGraph -> M.Map (S.Set UID) (K3 Type)
decideManifestation g' = propagateChoice g' (G.topologicalSort g')
where
propagateChoice :: ManifestGraph -> [S.Set UID] -> M.Map (S.Set UID) (K3 Type)
propagateChoice g [] = M.empty
propagateChoice g (i:is) = M.insert i currentBound $ propagateChoice restrict is
where
currentPolarity = let (p, _, _) = G.vertex g i in p
currentBound = let (p, lb, ub) = G.vertex g i in if p == UpperBound then ub else lb
restrict = runIdentity $ G.traverseWithKey traverseF g
traverseF k (bt, lb, rb)
| k == i = pure (bt, lb, rb)
| k `elem` G.successors g i && currentPolarity == UpperBound = pure (bt, lb, rb)
| k `elem` G.successors g i && currentPolarity == LowerBound = pure (bt, lb, currentBound)
| otherwise = pure (bt, lb, rb)
-- | Given a constraint set and a set of UIDs of variables to care about, narrow the constraint set
-- down to only those variables, and reduce the constraints on those variables to only other
-- variables in the set.
narrowAndReduce :: M.Map UID AnyTVar -> M.Map UVar (S.Set Constraint)
-> M.Map (S.Set UID) (S.Set (S.Set UID, S.Set UID))
narrowAndReduce tVarMap cm = M.fromList
[ (uset, ncs)
| (atvar, uset) <- M.toList reverseMap
, let (Just wcs) = M.lookup (fromJust $ onlyUVar atvar) cm
, let ncs = S.fromList . catMaybes $ map sanitizeConstraint (S.toList wcs)
]
where
-- | A reverse mapping, from basic IDs to UIDs, for all the UIDs we care about.
reverseMap :: M.Map AnyTVar (S.Set UID)
reverseMap = collapseReverseMap tVarMap
-- | A generic map reversal function -- Turn a map from keys to values into a map from sets of
-- values sharing a common key, to that common key.
collapseReverseMap :: (Ord k, Ord v) => M.Map k v -> M.Map v (S.Set k)
collapseReverseMap = M.fromListWith S.union . map (fmap S.singleton . swap) . M.toList
| Turn a constraint into a pair of UID sets . Nothing for constraints we do n't care about .
sanitizeConstraint :: Constraint -> Maybe (S.Set UID, S.Set UID)
sanitizeConstraint (IntermediateConstraint (CRight u) (CRight v))
| Just uUID <- M.lookup (someVar u) reverseMap
, Just vUID <- M.lookup (someVar v) reverseMap = Just (uUID, vUID)
| otherwise = Nothing
sanitizeConstraint _ = Nothing
-- | Compute the preferred bound type for each variable occurring in a constraint set, based on its
-- appearance in positions of positive and negative polarities.
deducePolarity :: S.Set (AnyTVar, ShallowType) -> M.Map AnyTVar BoundType
deducePolarity bounds = assignUnionFind sinkBounds unionFind
where
-- | Get all subsets containing the given element.
getOccurs :: Ord a => a -> S.Set (S.Set a) -> S.Set (S.Set a)
getOccurs x = S.filter (S.member x)
-- | Collapse a set of subsets into a single subset.
collapseSet :: Ord a => S.Set (S.Set a) -> S.Set (S.Set a) -> S.Set (S.Set a)
collapseSet s ss = S.insert (flatten ss) $ S.difference s ss
-- | Add a single function constraint to the union find, merging sets as necessary.
addToUnionFind :: S.Set (S.Set Variance) -> (AnyTVar, ShallowType) -> S.Set (S.Set Variance)
addToUnionFind s (t, SFunction u v) = collapseSet union $ collapseSet counion s
where
union = S.unions [
S.singleton $ S.fromList [Covariant t, Contravariant $ someVar u],
getOccurs (Covariant t) s,
getOccurs (Contravariant $ someVar u) s
]
counion = S.unions [
S.singleton $ S.fromList [Covariant t, Covariant $ someVar v],
getOccurs (Covariant t) s,
getOccurs (Covariant $ someVar v) s
]
addToUnionFind s _ = s
-- | Deeply propagate a set of assignments through a union-find data structure.
assignUnionFind :: M.Map AnyTVar BoundType -> S.Set (S.Set Variance) -> M.Map AnyTVar BoundType
assignUnionFind m s
| S.null s = m
| otherwise = M.union m m''
where
(m', s') = M.foldlWithKey' propagateAssignments (M.empty, s) m
m'' = assignUnionFind m' s'
| propagate a set of assignments one step through a union find data structure .
propagateAssignments :: (M.Map AnyTVar BoundType, S.Set (S.Set Variance)) -> AnyTVar -> BoundType
-> (M.Map AnyTVar BoundType, S.Set (S.Set Variance))
propagateAssignments (m, s) t b = (M.union m newAssignments, S.difference s (S.union positive negative))
where
positive = getOccurs (Covariant t) s
negative = getOccurs (Contravariant t) s
newAssignments = M.fromList $
[ (q, flipFromVariance v b)
| v <- S.toList (flatten positive)
, S.null $ getVar v
, let q = S.findMin (getVar v)
] ++
[ (q, flipFromVariance v (flipBoundType b))
| v <- S.toList (flatten negative)
, S.null $ getVar v
, let q = S.findMin (getVar v)
]
-- | Alter a bound type depending on a variance position.
flipFromVariance :: Variance -> BoundType -> BoundType
flipFromVariance (Invariant k) _ = k
flipFromVariance (Covariant _) b = b
flipFromVariance (Contravariant _) b = flipBoundType b
-- | Compute the union find of a set of constraints.
unionFind :: S.Set (S.Set Variance)
unionFind = S.foldl' addToUnionFind S.empty bounds
-- | Get the variable corresponding to a variance.
getVar :: Variance -> S.Set AnyTVar
getVar (Invariant _) = S.empty
getVar (Covariant t) = S.singleton t
getVar (Contravariant t) = S.singleton t
| Compute the intial bounds to boostrap the assignment process .
sinkBounds :: M.Map AnyTVar BoundType
sinkBounds = M.fromList [(v, LowerBound) | v <- S.toList sinkVars]
-- | Sink variables are type variables which represent functions, but are themselves not used as
-- an argument or return type of a function. We generally want these to be positive.
sinkVars :: S.Set AnyTVar
sinkVars = S.difference functionVars subFunctionVars
functionVars :: S.Set AnyTVar
functionVars = S.map fst bounds
subFunctionVars :: S.Set AnyTVar
subFunctionVars = flatten $ S.map (getBoundVars . snd) bounds
getBoundVars :: ShallowType -> S.Set AnyTVar
getBoundVars (SFunction x y) = S.fromList $ map someVar [x, y]
getBoundVars _ = S.empty
-- TODO: Do I need Invariant?
data Variance
= Invariant BoundType
| Covariant AnyTVar
| Contravariant AnyTVar
deriving (Eq, Ord, Show)
-- | Union a set of sets.
flatten :: Ord a => S.Set (S.Set a) -> S.Set a
flatten = S.unions . S.toList
-- | Complement for bound types.
flipBoundType :: BoundType -> BoundType
flipBoundType LowerBound = UpperBound
flipBoundType UpperBound = LowerBound
| null | https://raw.githubusercontent.com/DaMSL/K3/51749157844e76ae79dba619116fc5ad9d685643/src/Language/K3/TypeSystem/Manifestation/Graph.hs | haskell | | Dependent type-manifestation using graph traversal.
This module defines an algorithm and supporting machinery to perform dependent type manifestation
on a consistent constraint set obtained from a successful typechecking run.
The algorithm picks types for type variables whilst respecting constraints between them.
Equivalent variables are naturally manifested identically, constrained variables are manifested
such that the manifest types still satisfy their constraints.
| A graph containing a set of equivalent type variables at each vertex, and an edge from
supertypes to subtypes.
This involves creating a sanitized version of the constraint set (containing only source
variables) and turning constraints into edges.
| Construct the payload for each set of equivalent type variables.
| Given a constraint set and a set of UIDs of variables to care about, narrow the constraint set
down to only those variables, and reduce the constraints on those variables to only other
variables in the set.
| A reverse mapping, from basic IDs to UIDs, for all the UIDs we care about.
| A generic map reversal function -- Turn a map from keys to values into a map from sets of
values sharing a common key, to that common key.
| Compute the preferred bound type for each variable occurring in a constraint set, based on its
appearance in positions of positive and negative polarities.
| Get all subsets containing the given element.
| Collapse a set of subsets into a single subset.
| Add a single function constraint to the union find, merging sets as necessary.
| Deeply propagate a set of assignments through a union-find data structure.
| Alter a bound type depending on a variance position.
| Compute the union find of a set of constraints.
| Get the variable corresponding to a variance.
| Sink variables are type variables which represent functions, but are themselves not used as
an argument or return type of a function. We generally want these to be positive.
TODO: Do I need Invariant?
| Union a set of sets.
| Complement for bound types. | # LANGUAGE PatternGuards #
module Language.K3.TypeSystem.Manifestation.Graph where
import Control.Applicative
import Data.Functor.Identity
import Data.Maybe
import Data.Tuple (swap)
import qualified Data.Graph.Wrapper as G
import qualified Data.Map as M
import qualified Data.Set as S
import Language.K3.Core.Annotation
import Language.K3.Core.Common
import Language.K3.Core.Type
import Language.K3.TypeSystem.Data.Constraints
import Language.K3.TypeSystem.Data.Coproduct
import Language.K3.TypeSystem.Data.Types
import Language.K3.TypeSystem.Data.ConstraintSet
import Language.K3.TypeSystem.Data.Result
import Language.K3.TypeSystem.Manifestation.Data
type ManifestGraph = G.Graph (S.Set UID) (BoundType, K3 Type, K3 Type)
| Construct a ManifestGraph from the result of typechecking .
fromTypecheckResult :: TypecheckResult -> Maybe ManifestGraph
fromTypecheckResult result = do
(tVarMap, constraintSet) <- tcExprTypes result
boundsMap <- tcExprBounds result
lowerFunctionBounds <- fmap (S.map swap) $ M.lookup () $ indexAllTypesLowerBoundingAnyVars constraintSet
upperFunctionBounds <- M.lookup () $ indexAllTypesUpperBoundingAnyVars constraintSet
let polarityMap = deducePolarity (S.union lowerFunctionBounds upperFunctionBounds)
let narrowedConstraintMap = narrowAndReduce tVarMap (indexBoundingConstraintsByUVar constraintSet)
let consolidatedVertices = attachPayload polarityMap tVarMap boundsMap narrowedConstraintMap
let consolidatedEdges = map swap . S.toList . S.unions $ M.elems narrowedConstraintMap
return $ G.fromVerticesEdges consolidatedVertices consolidatedEdges
where
attachPayload pm tvm bm ncm =
[ (u, (p, lb, ub))
| u <- M.keys ncm
, let p = andBoundType $ catMaybes $ map (\k -> M.lookup k tvm >>= \k' -> M.lookup k' pm) $ S.toList u
, let Just (lb, ub) = M.lookup (S.findMin u) bm
]
andBoundType :: [BoundType] -> BoundType
andBoundType [] = UpperBound
andBoundType (LowerBound:_) = LowerBound
andBoundType (_:bs) = andBoundType bs
decideManifestation :: ManifestGraph -> M.Map (S.Set UID) (K3 Type)
decideManifestation g' = propagateChoice g' (G.topologicalSort g')
where
propagateChoice :: ManifestGraph -> [S.Set UID] -> M.Map (S.Set UID) (K3 Type)
propagateChoice g [] = M.empty
propagateChoice g (i:is) = M.insert i currentBound $ propagateChoice restrict is
where
currentPolarity = let (p, _, _) = G.vertex g i in p
currentBound = let (p, lb, ub) = G.vertex g i in if p == UpperBound then ub else lb
restrict = runIdentity $ G.traverseWithKey traverseF g
traverseF k (bt, lb, rb)
| k == i = pure (bt, lb, rb)
| k `elem` G.successors g i && currentPolarity == UpperBound = pure (bt, lb, rb)
| k `elem` G.successors g i && currentPolarity == LowerBound = pure (bt, lb, currentBound)
| otherwise = pure (bt, lb, rb)
narrowAndReduce :: M.Map UID AnyTVar -> M.Map UVar (S.Set Constraint)
-> M.Map (S.Set UID) (S.Set (S.Set UID, S.Set UID))
narrowAndReduce tVarMap cm = M.fromList
[ (uset, ncs)
| (atvar, uset) <- M.toList reverseMap
, let (Just wcs) = M.lookup (fromJust $ onlyUVar atvar) cm
, let ncs = S.fromList . catMaybes $ map sanitizeConstraint (S.toList wcs)
]
where
reverseMap :: M.Map AnyTVar (S.Set UID)
reverseMap = collapseReverseMap tVarMap
collapseReverseMap :: (Ord k, Ord v) => M.Map k v -> M.Map v (S.Set k)
collapseReverseMap = M.fromListWith S.union . map (fmap S.singleton . swap) . M.toList
| Turn a constraint into a pair of UID sets . Nothing for constraints we do n't care about .
sanitizeConstraint :: Constraint -> Maybe (S.Set UID, S.Set UID)
sanitizeConstraint (IntermediateConstraint (CRight u) (CRight v))
| Just uUID <- M.lookup (someVar u) reverseMap
, Just vUID <- M.lookup (someVar v) reverseMap = Just (uUID, vUID)
| otherwise = Nothing
sanitizeConstraint _ = Nothing
deducePolarity :: S.Set (AnyTVar, ShallowType) -> M.Map AnyTVar BoundType
deducePolarity bounds = assignUnionFind sinkBounds unionFind
where
getOccurs :: Ord a => a -> S.Set (S.Set a) -> S.Set (S.Set a)
getOccurs x = S.filter (S.member x)
collapseSet :: Ord a => S.Set (S.Set a) -> S.Set (S.Set a) -> S.Set (S.Set a)
collapseSet s ss = S.insert (flatten ss) $ S.difference s ss
addToUnionFind :: S.Set (S.Set Variance) -> (AnyTVar, ShallowType) -> S.Set (S.Set Variance)
addToUnionFind s (t, SFunction u v) = collapseSet union $ collapseSet counion s
where
union = S.unions [
S.singleton $ S.fromList [Covariant t, Contravariant $ someVar u],
getOccurs (Covariant t) s,
getOccurs (Contravariant $ someVar u) s
]
counion = S.unions [
S.singleton $ S.fromList [Covariant t, Covariant $ someVar v],
getOccurs (Covariant t) s,
getOccurs (Covariant $ someVar v) s
]
addToUnionFind s _ = s
assignUnionFind :: M.Map AnyTVar BoundType -> S.Set (S.Set Variance) -> M.Map AnyTVar BoundType
assignUnionFind m s
| S.null s = m
| otherwise = M.union m m''
where
(m', s') = M.foldlWithKey' propagateAssignments (M.empty, s) m
m'' = assignUnionFind m' s'
| propagate a set of assignments one step through a union find data structure .
propagateAssignments :: (M.Map AnyTVar BoundType, S.Set (S.Set Variance)) -> AnyTVar -> BoundType
-> (M.Map AnyTVar BoundType, S.Set (S.Set Variance))
propagateAssignments (m, s) t b = (M.union m newAssignments, S.difference s (S.union positive negative))
where
positive = getOccurs (Covariant t) s
negative = getOccurs (Contravariant t) s
newAssignments = M.fromList $
[ (q, flipFromVariance v b)
| v <- S.toList (flatten positive)
, S.null $ getVar v
, let q = S.findMin (getVar v)
] ++
[ (q, flipFromVariance v (flipBoundType b))
| v <- S.toList (flatten negative)
, S.null $ getVar v
, let q = S.findMin (getVar v)
]
flipFromVariance :: Variance -> BoundType -> BoundType
flipFromVariance (Invariant k) _ = k
flipFromVariance (Covariant _) b = b
flipFromVariance (Contravariant _) b = flipBoundType b
unionFind :: S.Set (S.Set Variance)
unionFind = S.foldl' addToUnionFind S.empty bounds
getVar :: Variance -> S.Set AnyTVar
getVar (Invariant _) = S.empty
getVar (Covariant t) = S.singleton t
getVar (Contravariant t) = S.singleton t
| Compute the intial bounds to boostrap the assignment process .
sinkBounds :: M.Map AnyTVar BoundType
sinkBounds = M.fromList [(v, LowerBound) | v <- S.toList sinkVars]
sinkVars :: S.Set AnyTVar
sinkVars = S.difference functionVars subFunctionVars
functionVars :: S.Set AnyTVar
functionVars = S.map fst bounds
subFunctionVars :: S.Set AnyTVar
subFunctionVars = flatten $ S.map (getBoundVars . snd) bounds
getBoundVars :: ShallowType -> S.Set AnyTVar
getBoundVars (SFunction x y) = S.fromList $ map someVar [x, y]
getBoundVars _ = S.empty
data Variance
= Invariant BoundType
| Covariant AnyTVar
| Contravariant AnyTVar
deriving (Eq, Ord, Show)
flatten :: Ord a => S.Set (S.Set a) -> S.Set a
flatten = S.unions . S.toList
flipBoundType :: BoundType -> BoundType
flipBoundType LowerBound = UpperBound
flipBoundType UpperBound = LowerBound
|
06ea761ae86ebf7ed807dba32f871c3eed0af62dbc5901fe3e5cc27dc1ea167b | scicloj/notespace | run.clj | (ns scicloj.notespace.v4.run
(:require [scicloj.notespace.v4.read :as v4.read]
[scicloj.notespace.v4.view :as v4.view]
[scicloj.notespace.v4.frontend.change :as v4.frontend.change]
[scicloj.notespace.v4.frontend.engine :as v4.frontend.engine]
[scicloj.notespace.v4.events.pipeline :as v4.pipeline]))
(defn update-ns! [path]
(v4.pipeline/process-event
{:event/type :scicloj.notespace.v4.events.handle/buffer-update
:path path}))
(defn uuid [] (.toString (java.util.UUID/randomUUID)))
(defn run-ns! [path]
(update-ns! path)
(let [notes (->> path
slurp
v4.read/->safe-notes
(map (fn [note]
(assoc note
:value (->> note :form eval)
:status :evaluated)))
doall)]
(future
(Thread/sleep 200)
(v4.frontend.change/reset-frontend!
{:current-notes notes
:last-evaluated-note (last notes)
:messages []})
(println [:done path]))))
(comment
(update-ns! "dummy.clj")
(run-ns! "dummy.clj"))
| null | https://raw.githubusercontent.com/scicloj/notespace/1929f4d2b69c9e52f4ddb5581d10ecaaa29b3c69/src/scicloj/notespace/v4/run.clj | clojure | (ns scicloj.notespace.v4.run
(:require [scicloj.notespace.v4.read :as v4.read]
[scicloj.notespace.v4.view :as v4.view]
[scicloj.notespace.v4.frontend.change :as v4.frontend.change]
[scicloj.notespace.v4.frontend.engine :as v4.frontend.engine]
[scicloj.notespace.v4.events.pipeline :as v4.pipeline]))
(defn update-ns! [path]
(v4.pipeline/process-event
{:event/type :scicloj.notespace.v4.events.handle/buffer-update
:path path}))
(defn uuid [] (.toString (java.util.UUID/randomUUID)))
(defn run-ns! [path]
(update-ns! path)
(let [notes (->> path
slurp
v4.read/->safe-notes
(map (fn [note]
(assoc note
:value (->> note :form eval)
:status :evaluated)))
doall)]
(future
(Thread/sleep 200)
(v4.frontend.change/reset-frontend!
{:current-notes notes
:last-evaluated-note (last notes)
:messages []})
(println [:done path]))))
(comment
(update-ns! "dummy.clj")
(run-ns! "dummy.clj"))
| |
3c73e6188351bc3d2f0645e1c52427bbf5ad00fa7283343f01bacc09082b0240 | exoscale/vinyl | query_filter_test.clj | (ns exoscale.vinyl.query-filter-test
(:require [clojure.test :refer :all]
[exoscale.vinyl.query :as query]
[clojure.spec.alpha :as s]))
(deftest filter-types-test
(testing "Filter spec"
(is (s/valid? ::query/filter [:matches :a [:= :b 2]]))
(is (s/valid? ::query/filter [:nested :a [:= :b 2]]))
(is (s/valid? ::query/filter [:one-of-them :a [:= :b 2]]))
(is (s/valid? ::query/filter [:not= :a 1]))
(is (s/valid? ::query/filter [:= :a 1]))
(is (s/valid? ::query/filter [:in :a [1]]))
(is (s/valid? ::query/filter [:nil? :a]))
(is (s/valid? ::query/filter [:some? :a]))
(is (s/valid? ::query/filter [:and [:= :a 1]
[:= :b 2]]))
(is (s/valid? ::query/filter [:or [:= :a 1]
[:= :b 2]]))
(is (s/valid? ::query/filter [:not [:= :a 1]]))
(is (s/valid? ::query/filter [:starts-with? :a "1"]))
(is (s/valid? ::query/filter [:> :a 1]))
(is (s/valid? ::query/filter [:>= :a 1]))
(is (s/valid? ::query/filter [:< :a 1]))
(is (s/valid? ::query/filter [:<= :a 1]))))
| null | https://raw.githubusercontent.com/exoscale/vinyl/4ee9d40f9268abda731284bb020878fc350801fe/test/exoscale/vinyl/query_filter_test.clj | clojure | (ns exoscale.vinyl.query-filter-test
(:require [clojure.test :refer :all]
[exoscale.vinyl.query :as query]
[clojure.spec.alpha :as s]))
(deftest filter-types-test
(testing "Filter spec"
(is (s/valid? ::query/filter [:matches :a [:= :b 2]]))
(is (s/valid? ::query/filter [:nested :a [:= :b 2]]))
(is (s/valid? ::query/filter [:one-of-them :a [:= :b 2]]))
(is (s/valid? ::query/filter [:not= :a 1]))
(is (s/valid? ::query/filter [:= :a 1]))
(is (s/valid? ::query/filter [:in :a [1]]))
(is (s/valid? ::query/filter [:nil? :a]))
(is (s/valid? ::query/filter [:some? :a]))
(is (s/valid? ::query/filter [:and [:= :a 1]
[:= :b 2]]))
(is (s/valid? ::query/filter [:or [:= :a 1]
[:= :b 2]]))
(is (s/valid? ::query/filter [:not [:= :a 1]]))
(is (s/valid? ::query/filter [:starts-with? :a "1"]))
(is (s/valid? ::query/filter [:> :a 1]))
(is (s/valid? ::query/filter [:>= :a 1]))
(is (s/valid? ::query/filter [:< :a 1]))
(is (s/valid? ::query/filter [:<= :a 1]))))
| |
3e73715938effcee06bcec86e59becc6a8c2896007e1af0d9d028cdfc9b269ad | processone/ejabberd | extauth.erl | %%%-------------------------------------------------------------------
Created : 7 May 2018 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%-------------------------------------------------------------------
-module(extauth).
-ifndef(GEN_SERVER).
-define(GEN_SERVER, gen_server).
-endif.
-behaviour(?GEN_SERVER).
-define(CALL_TIMEOUT, timer:seconds(30)).
%% API
-export([start/1, stop/1, reload/1, start_link/2]).
-export([check_password/3, set_password/3, try_register/3, remove_user/2,
remove_user/3, user_exists/2, check_certificate/3]).
-export([prog_name/1, pool_name/1, worker_name/2, pool_size/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-include("logger.hrl").
-record(state, {port :: port(),
prog :: string(),
start_time :: integer(),
os_pid :: integer() | undefined}).
%%%===================================================================
%%% API
%%%===================================================================
start(Host) ->
extauth_sup:start(Host).
stop(Host) ->
extauth_sup:stop(Host).
reload(Host) ->
extauth_sup:reload(Host).
start_link(Name, Prog) ->
?GEN_SERVER:start_link({local, Name}, ?MODULE, [Prog], []).
check_password(User, Server, Password) ->
call_port(Server, [<<"auth">>, User, Server, Password]).
check_certificate(User, Server, Certificate) ->
call_port(Server, [<<"certauth">>, User, Server, Certificate]).
user_exists(User, Server) ->
call_port(Server, [<<"isuser">>, User, Server]).
set_password(User, Server, Password) ->
call_port(Server, [<<"setpass">>, User, Server, Password]).
try_register(User, Server, Password) ->
call_port(Server, [<<"tryregister">>, User, Server, Password]).
remove_user(User, Server) ->
call_port(Server, [<<"removeuser">>, User, Server]).
remove_user(User, Server, Password) ->
call_port(Server, [<<"removeuser3">>, User, Server, Password]).
-spec prog_name(binary()) -> string() | undefined.
prog_name(Host) ->
ejabberd_option:extauth_program(Host).
-spec pool_name(binary()) -> atom().
pool_name(Host) ->
case ejabberd_option:extauth_pool_name(Host) of
undefined ->
list_to_atom("extauth_pool_" ++ binary_to_list(Host));
Name ->
list_to_atom("extauth_pool_" ++ binary_to_list(Name))
end.
-spec worker_name(atom(), integer()) -> atom().
worker_name(Pool, N) ->
list_to_atom(atom_to_list(Pool) ++ "_" ++ integer_to_list(N)).
-spec pool_size(binary()) -> pos_integer().
pool_size(Host) ->
case ejabberd_option:extauth_pool_size(Host) of
undefined -> misc:logical_processors();
Size ->
Size
end.
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
init([Prog]) ->
process_flag(trap_exit, true),
{Port, OSPid} = start_port(Prog),
Time = curr_time(),
{ok, #state{port = Port, start_time = Time,
prog = Prog, os_pid = OSPid}}.
handle_call({cmd, Cmd, EndTime}, _From, State) ->
Timeout = EndTime - curr_time(),
if Timeout > 0 ->
Port = State#state.port,
port_command(Port, Cmd),
receive
{Port, {data, [0, N] = Data}} when N == 0; N == 1 ->
?DEBUG("Received response from external authentication "
"program: ~p", [Data]),
{reply, decode_bool(N), State};
{Port, Data} ->
?ERROR_MSG("Received unexpected response from external "
"authentication program '~ts': ~p "
"(port = ~p, pid = ~w)",
[State#state.prog, Data, Port, State#state.os_pid]),
{reply, {error, unexpected_response}, State};
{'EXIT', Port, Reason} ->
handle_info({'EXIT', Port, Reason}, State)
after Timeout ->
{stop, normal, State}
end;
true ->
{noreply, State}
end.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'EXIT', Port, _Reason}, #state{port = Port,
start_time = Time} = State) ->
case curr_time() - Time of
Diff when Diff < 1000 ->
?ERROR_MSG("Failed to start external authentication program '~ts'",
[State#state.prog]),
{stop, normal, State};
_ ->
?ERROR_MSG("External authentication program '~ts' has terminated "
"unexpectedly (pid=~w), restarting via supervisor...",
[State#state.prog, State#state.os_pid]),
{stop, normal, State}
end;
handle_info(Info, State) ->
?WARNING_MSG("Unexpected info: ~p", [Info]),
{noreply, State}.
terminate(_Reason, State) ->
catch port_close(State#state.port),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
-spec curr_time() -> non_neg_integer().
curr_time() ->
erlang:monotonic_time(millisecond).
-spec start_port(string()) -> {port(), integer() | undefined}.
start_port(Path) ->
Port = open_port({spawn, Path}, [{packet, 2}]),
link(Port),
case erlang:port_info(Port, os_pid) of
{os_pid, OSPid} ->
{Port, OSPid};
undefined ->
{Port, undefined}
end.
call_port(Server, Args) ->
call_port(Server, Args, ?CALL_TIMEOUT).
call_port(Server, Args, Timeout) ->
StartTime = erlang:monotonic_time(millisecond),
Pool = pool_name(Server),
PoolSize = pool_size(Server),
I = p1_rand:round_robin(PoolSize),
Cmd = str:join(Args, <<":">>),
do_call(Cmd, I, I + PoolSize, Pool, PoolSize,
StartTime + Timeout, StartTime).
do_call(_, Max, Max, _, _, _, _) ->
{error, disconnected};
do_call(Cmd, I, Max, Pool, PoolSize, EndTime, CurrTime) ->
Timeout = EndTime - CurrTime,
if Timeout > 0 ->
Proc = worker_name(Pool, (I rem PoolSize) + 1),
try ?GEN_SERVER:call(Proc, {cmd, Cmd, EndTime}, Timeout)
catch exit:{timeout, {?GEN_SERVER, call, _}} ->
{error, timeout};
exit:{_, {?GEN_SERVER, call, _}} ->
do_call(Cmd, I+1, Max, Pool, PoolSize, EndTime, curr_time())
end;
true ->
{error, timeout}
end.
decode_bool(0) -> false;
decode_bool(1) -> true.
| null | https://raw.githubusercontent.com/processone/ejabberd/c103182bc7e5b8a8ab123ce02d1959a54e939480/src/extauth.erl | erlang | -------------------------------------------------------------------
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
-------------------------------------------------------------------
API
===================================================================
API
===================================================================
===================================================================
gen_server callbacks
===================================================================
===================================================================
=================================================================== | Created : 7 May 2018 by < >
ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(extauth).
-ifndef(GEN_SERVER).
-define(GEN_SERVER, gen_server).
-endif.
-behaviour(?GEN_SERVER).
-define(CALL_TIMEOUT, timer:seconds(30)).
-export([start/1, stop/1, reload/1, start_link/2]).
-export([check_password/3, set_password/3, try_register/3, remove_user/2,
remove_user/3, user_exists/2, check_certificate/3]).
-export([prog_name/1, pool_name/1, worker_name/2, pool_size/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-include("logger.hrl").
-record(state, {port :: port(),
prog :: string(),
start_time :: integer(),
os_pid :: integer() | undefined}).
start(Host) ->
extauth_sup:start(Host).
stop(Host) ->
extauth_sup:stop(Host).
reload(Host) ->
extauth_sup:reload(Host).
start_link(Name, Prog) ->
?GEN_SERVER:start_link({local, Name}, ?MODULE, [Prog], []).
check_password(User, Server, Password) ->
call_port(Server, [<<"auth">>, User, Server, Password]).
check_certificate(User, Server, Certificate) ->
call_port(Server, [<<"certauth">>, User, Server, Certificate]).
user_exists(User, Server) ->
call_port(Server, [<<"isuser">>, User, Server]).
set_password(User, Server, Password) ->
call_port(Server, [<<"setpass">>, User, Server, Password]).
try_register(User, Server, Password) ->
call_port(Server, [<<"tryregister">>, User, Server, Password]).
remove_user(User, Server) ->
call_port(Server, [<<"removeuser">>, User, Server]).
remove_user(User, Server, Password) ->
call_port(Server, [<<"removeuser3">>, User, Server, Password]).
-spec prog_name(binary()) -> string() | undefined.
prog_name(Host) ->
ejabberd_option:extauth_program(Host).
-spec pool_name(binary()) -> atom().
pool_name(Host) ->
case ejabberd_option:extauth_pool_name(Host) of
undefined ->
list_to_atom("extauth_pool_" ++ binary_to_list(Host));
Name ->
list_to_atom("extauth_pool_" ++ binary_to_list(Name))
end.
-spec worker_name(atom(), integer()) -> atom().
worker_name(Pool, N) ->
list_to_atom(atom_to_list(Pool) ++ "_" ++ integer_to_list(N)).
-spec pool_size(binary()) -> pos_integer().
pool_size(Host) ->
case ejabberd_option:extauth_pool_size(Host) of
undefined -> misc:logical_processors();
Size ->
Size
end.
init([Prog]) ->
process_flag(trap_exit, true),
{Port, OSPid} = start_port(Prog),
Time = curr_time(),
{ok, #state{port = Port, start_time = Time,
prog = Prog, os_pid = OSPid}}.
handle_call({cmd, Cmd, EndTime}, _From, State) ->
Timeout = EndTime - curr_time(),
if Timeout > 0 ->
Port = State#state.port,
port_command(Port, Cmd),
receive
{Port, {data, [0, N] = Data}} when N == 0; N == 1 ->
?DEBUG("Received response from external authentication "
"program: ~p", [Data]),
{reply, decode_bool(N), State};
{Port, Data} ->
?ERROR_MSG("Received unexpected response from external "
"authentication program '~ts': ~p "
"(port = ~p, pid = ~w)",
[State#state.prog, Data, Port, State#state.os_pid]),
{reply, {error, unexpected_response}, State};
{'EXIT', Port, Reason} ->
handle_info({'EXIT', Port, Reason}, State)
after Timeout ->
{stop, normal, State}
end;
true ->
{noreply, State}
end.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'EXIT', Port, _Reason}, #state{port = Port,
start_time = Time} = State) ->
case curr_time() - Time of
Diff when Diff < 1000 ->
?ERROR_MSG("Failed to start external authentication program '~ts'",
[State#state.prog]),
{stop, normal, State};
_ ->
?ERROR_MSG("External authentication program '~ts' has terminated "
"unexpectedly (pid=~w), restarting via supervisor...",
[State#state.prog, State#state.os_pid]),
{stop, normal, State}
end;
handle_info(Info, State) ->
?WARNING_MSG("Unexpected info: ~p", [Info]),
{noreply, State}.
terminate(_Reason, State) ->
catch port_close(State#state.port),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
-spec curr_time() -> non_neg_integer().
curr_time() ->
erlang:monotonic_time(millisecond).
-spec start_port(string()) -> {port(), integer() | undefined}.
start_port(Path) ->
Port = open_port({spawn, Path}, [{packet, 2}]),
link(Port),
case erlang:port_info(Port, os_pid) of
{os_pid, OSPid} ->
{Port, OSPid};
undefined ->
{Port, undefined}
end.
call_port(Server, Args) ->
call_port(Server, Args, ?CALL_TIMEOUT).
call_port(Server, Args, Timeout) ->
StartTime = erlang:monotonic_time(millisecond),
Pool = pool_name(Server),
PoolSize = pool_size(Server),
I = p1_rand:round_robin(PoolSize),
Cmd = str:join(Args, <<":">>),
do_call(Cmd, I, I + PoolSize, Pool, PoolSize,
StartTime + Timeout, StartTime).
do_call(_, Max, Max, _, _, _, _) ->
{error, disconnected};
do_call(Cmd, I, Max, Pool, PoolSize, EndTime, CurrTime) ->
Timeout = EndTime - CurrTime,
if Timeout > 0 ->
Proc = worker_name(Pool, (I rem PoolSize) + 1),
try ?GEN_SERVER:call(Proc, {cmd, Cmd, EndTime}, Timeout)
catch exit:{timeout, {?GEN_SERVER, call, _}} ->
{error, timeout};
exit:{_, {?GEN_SERVER, call, _}} ->
do_call(Cmd, I+1, Max, Pool, PoolSize, EndTime, curr_time())
end;
true ->
{error, timeout}
end.
decode_bool(0) -> false;
decode_bool(1) -> true.
|
d3bf55b4c4a57bfaf755ef0b374599cbfa10e7f0b56129e474d4eb85bdf3c31c | pmembrey/molderl | molderl_eunit_tests.erl |
-module(molderl_eunit_tests).
-include_lib("eunit/include/eunit.hrl").
-include("molderl.hrl").
-include("molderl_tests.hrl").
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
start() ->
io:format(user,"Initiating tests...~n",[]),
file:delete("/tmp/foo"),
file:delete("/tmp/bar"),
file:delete("/tmp/baz"),
application:start(molderl),
[].
stop(_) ->
io:format(user,"Cleaning up...~n",[]),
application:stop(molderl).
instantiator(_) ->
FooPort = 7777,
BarPort = 8888,
BazPort = 9999,
FooRecPort = 7778,
BarRecPort = 8889,
BazRecPort = 10000,
{ok, [{LocalHostIP,_,_}|_]} = inet:getif(),
set up UDP multicast listen sockets
{ok, FooSocket} = gen_udp:open(FooPort, [binary, {reuseaddr, true}]),
inet:setopts(FooSocket, [{add_membership, {?MCAST_GROUP_IP, {127,0,0,1}}}]),
{ok, BarSocket} = gen_udp:open(BarPort, [binary, {reuseaddr, true}]),
inet:setopts(BarSocket, [{add_membership, {?MCAST_GROUP_IP, {127,0,0,1}}}]),
{ok, BazSocket} = gen_udp:open(BazPort, [binary, {reuseaddr, true}]),
inet:setopts(BazSocket, [{add_membership, {?MCAST_GROUP_IP, {127,0,0,1}}}]),
{ok, FooPid} = molderl:create_stream(foo,?MCAST_GROUP_IP,FooPort,FooRecPort,[{filename,"/tmp/foo"}]),
{ok, BarPid} = molderl:create_stream(bar,?MCAST_GROUP_IP,BarPort,BarRecPort,[{ipaddresstosendfrom,LocalHostIP},{filename,"/tmp/bar"}]),
{ok, BazPid} = molderl:create_stream(baz,?MCAST_GROUP_IP,BazPort,BazRecPort,[{filename,"/tmp/baz"},{timer,200}]),
ConflictAddr = molderl:create_stream(qux,?MCAST_GROUP_IP,BarPort,8890,[{ipaddresstosendfrom,LocalHostIP},{timer,100}]),
ConflictPort = molderl:create_stream(bar,?MCAST_GROUP_IP,4321,BarRecPort,[{ipaddresstosendfrom,LocalHostIP}]),
molderl:send_message(FooPid, <<"HelloWorld">>),
{ok, [{Seq1, Msg1}]} = receive_messages("foo", FooSocket, 500),
molderl:send_message(FooPid, <<"HelloWorld">>),
{ok, [{Seq2, Msg2}]} = receive_messages("foo", FooSocket, 500),
molderl:send_message(FooPid, <<"foo">>),
molderl:send_message(FooPid, <<"bar">>),
molderl:send_message(FooPid, <<"baz">>),
{ok, Msgs} = receive_messages("foo", FooSocket, 500),
molderl:send_message(FooPid, <<"foo">>),
molderl:send_message(BarPid, <<"bar">>),
molderl:send_message(BazPid, <<"baz">>),
molderl:send_message(FooPid, <<"foo">>),
molderl:send_message(BarPid, <<"bar">>),
molderl:send_message(BazPid, <<"baz">>),
{ok, BazMsgs} = receive_messages("baz", BazSocket, 500),
{ok, FooMsgs} = receive_messages("foo", FooSocket, 500),
{ok, BarMsgs} = receive_messages("bar", BarSocket, 500),
BigMsg = list_to_binary([random:uniform(100) || _ <- lists:seq(1, ?PACKET_SIZE-200)]),
molderl:send_message(BazPid, BigMsg),
{ok, [{_,ExpectedBigMsg}]} = receive_messages("baz", BazSocket, 500),
by now , stream is like this :
[ < < " HelloWorld " > > , < < " HelloWorld " > > , < < " foo " > > , < < " bar " > > , < < " baz " > > , < < " foo " > > , < < " foo " > > ]
% Recovery tests
% first send a broken recovery request, see if it breaks
SessionName = molderl_utils:gen_streamname("foo"),
BrokenRequest = <<SessionName/binary>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, BrokenRequest),
% using same port for streaming and recovery
Request1 = <<SessionName/binary, Seq1:64, 1:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request1),
{ok, [RecoveredMsg1]} = receive_messages("foo", FooSocket, 500),
Request2 = <<SessionName/binary, Seq2:64, 1:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request2),
{ok, [RecoveredMsg2]} = receive_messages("foo", FooSocket, 500),
test recovery multiple msgs
Seq3 = Seq2+1,
Request3 = <<SessionName/binary, Seq3:64, 3:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request3),
{ok, RecoveredMsgs3} = receive_messages("foo", FooSocket, 500),
% using different ports for streaming and recovery
QuxPort = 45678,
{ok, QuxSocket} = gen_udp:open(QuxPort, [binary, {reuseaddr, true}]),
gen_udp:send(QuxSocket, LocalHostIP, FooRecPort, Request1),
{ok, [RecoveredMsg4]} = receive_messages("foo", QuxSocket, 500),
gen_udp:send(QuxSocket, LocalHostIP, FooRecPort, Request2),
{ok, [RecoveredMsg5]} = receive_messages("foo", QuxSocket, 500),
test when requested sequence number > total number of msgs sent
Request6a = <<SessionName/binary, 100:64, 1:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request6a),
Result6a = receive_messages("foo", FooSocket, 500),
test when requested sequence number < = 0
Request6b = <<SessionName/binary, 0:64, 1:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request6b),
Result6b = receive_messages("foo", FooSocket, 500),
% test when requested count > max recovery count
Request6c = <<SessionName/binary, 1:64, 5000:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request6c),
Result6c = receive_messages("foo", FooSocket, 500),
test when requested sequence number + requested count > total number of msgs sent
Request7 = <<SessionName/binary, 6:64, 100:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request7),
{ok, RecoveredMsgs7} = receive_messages("foo", FooSocket, 500),
test when requested count is zero
Request8 = <<SessionName/binary, 2:64, 0:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request8),
Result8 = receive_messages("foo", FooSocket, 500),
% test when requested sequence number starts at very last message
Request9 = <<SessionName/binary, 7:64, 8:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request9),
{ok, RecoveredMsgs9} = receive_messages("foo", FooSocket, 500),
[
?_assertEqual({error, destination_address_already_in_use}, ConflictAddr),
?_assertEqual({error, recovery_port_already_in_use}, ConflictPort),
?_assertEqual(<<"HelloWorld">>, Msg1),
?_assertEqual(<<"HelloWorld">>, Msg2),
?_assertMatch([{_,<<"foo">>},{_,<<"bar">>},{_,<<"baz">>}], Msgs),
?_assertMatch([{_,<<"bar">>},{_,<<"bar">>}], BarMsgs),
?_assertMatch([{_,<<"baz">>},{_,<<"baz">>}], BazMsgs),
?_assertMatch([{_,<<"foo">>},{_,<<"foo">>}], FooMsgs),
?_assertEqual(BigMsg, ExpectedBigMsg),
?_assertEqual({Seq1, Msg1}, RecoveredMsg1),
?_assertEqual({Seq2, Msg2}, RecoveredMsg2),
?_assertEqual([{Seq3, <<"foo">>}, {Seq3+1, <<"bar">>}, {Seq3+2, <<"baz">>}], RecoveredMsgs3),
?_assertEqual({Seq1, Msg1}, RecoveredMsg4),
?_assertEqual({Seq2, Msg2}, RecoveredMsg5),
?_assertEqual({error, timeout}, Result6a),
?_assertEqual({error, timeout}, Result6b),
?_assertEqual({error, timeout}, Result6c),
?_assertEqual([{6, <<"foo">>}, {7, <<"foo">>}], RecoveredMsgs7),
?_assertEqual({error, timeout}, Result8),
?_assertEqual([{7, <<"foo">>}], RecoveredMsgs9)
].
molderl_test_() ->
{setup,
fun start/0,
fun stop/1,
fun instantiator/1}.
| null | https://raw.githubusercontent.com/pmembrey/molderl/10e9a6faeb73a0bc601ade5bd1ea1484957c33c3/test/molderl_eunit_tests.erl | erlang |
Recovery tests
first send a broken recovery request, see if it breaks
using same port for streaming and recovery
using different ports for streaming and recovery
test when requested count > max recovery count
test when requested sequence number starts at very last message |
-module(molderl_eunit_tests).
-include_lib("eunit/include/eunit.hrl").
-include("molderl.hrl").
-include("molderl_tests.hrl").
start() ->
io:format(user,"Initiating tests...~n",[]),
file:delete("/tmp/foo"),
file:delete("/tmp/bar"),
file:delete("/tmp/baz"),
application:start(molderl),
[].
stop(_) ->
io:format(user,"Cleaning up...~n",[]),
application:stop(molderl).
instantiator(_) ->
FooPort = 7777,
BarPort = 8888,
BazPort = 9999,
FooRecPort = 7778,
BarRecPort = 8889,
BazRecPort = 10000,
{ok, [{LocalHostIP,_,_}|_]} = inet:getif(),
set up UDP multicast listen sockets
{ok, FooSocket} = gen_udp:open(FooPort, [binary, {reuseaddr, true}]),
inet:setopts(FooSocket, [{add_membership, {?MCAST_GROUP_IP, {127,0,0,1}}}]),
{ok, BarSocket} = gen_udp:open(BarPort, [binary, {reuseaddr, true}]),
inet:setopts(BarSocket, [{add_membership, {?MCAST_GROUP_IP, {127,0,0,1}}}]),
{ok, BazSocket} = gen_udp:open(BazPort, [binary, {reuseaddr, true}]),
inet:setopts(BazSocket, [{add_membership, {?MCAST_GROUP_IP, {127,0,0,1}}}]),
{ok, FooPid} = molderl:create_stream(foo,?MCAST_GROUP_IP,FooPort,FooRecPort,[{filename,"/tmp/foo"}]),
{ok, BarPid} = molderl:create_stream(bar,?MCAST_GROUP_IP,BarPort,BarRecPort,[{ipaddresstosendfrom,LocalHostIP},{filename,"/tmp/bar"}]),
{ok, BazPid} = molderl:create_stream(baz,?MCAST_GROUP_IP,BazPort,BazRecPort,[{filename,"/tmp/baz"},{timer,200}]),
ConflictAddr = molderl:create_stream(qux,?MCAST_GROUP_IP,BarPort,8890,[{ipaddresstosendfrom,LocalHostIP},{timer,100}]),
ConflictPort = molderl:create_stream(bar,?MCAST_GROUP_IP,4321,BarRecPort,[{ipaddresstosendfrom,LocalHostIP}]),
molderl:send_message(FooPid, <<"HelloWorld">>),
{ok, [{Seq1, Msg1}]} = receive_messages("foo", FooSocket, 500),
molderl:send_message(FooPid, <<"HelloWorld">>),
{ok, [{Seq2, Msg2}]} = receive_messages("foo", FooSocket, 500),
molderl:send_message(FooPid, <<"foo">>),
molderl:send_message(FooPid, <<"bar">>),
molderl:send_message(FooPid, <<"baz">>),
{ok, Msgs} = receive_messages("foo", FooSocket, 500),
molderl:send_message(FooPid, <<"foo">>),
molderl:send_message(BarPid, <<"bar">>),
molderl:send_message(BazPid, <<"baz">>),
molderl:send_message(FooPid, <<"foo">>),
molderl:send_message(BarPid, <<"bar">>),
molderl:send_message(BazPid, <<"baz">>),
{ok, BazMsgs} = receive_messages("baz", BazSocket, 500),
{ok, FooMsgs} = receive_messages("foo", FooSocket, 500),
{ok, BarMsgs} = receive_messages("bar", BarSocket, 500),
BigMsg = list_to_binary([random:uniform(100) || _ <- lists:seq(1, ?PACKET_SIZE-200)]),
molderl:send_message(BazPid, BigMsg),
{ok, [{_,ExpectedBigMsg}]} = receive_messages("baz", BazSocket, 500),
by now , stream is like this :
[ < < " HelloWorld " > > , < < " HelloWorld " > > , < < " foo " > > , < < " bar " > > , < < " baz " > > , < < " foo " > > , < < " foo " > > ]
SessionName = molderl_utils:gen_streamname("foo"),
BrokenRequest = <<SessionName/binary>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, BrokenRequest),
Request1 = <<SessionName/binary, Seq1:64, 1:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request1),
{ok, [RecoveredMsg1]} = receive_messages("foo", FooSocket, 500),
Request2 = <<SessionName/binary, Seq2:64, 1:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request2),
{ok, [RecoveredMsg2]} = receive_messages("foo", FooSocket, 500),
test recovery multiple msgs
Seq3 = Seq2+1,
Request3 = <<SessionName/binary, Seq3:64, 3:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request3),
{ok, RecoveredMsgs3} = receive_messages("foo", FooSocket, 500),
QuxPort = 45678,
{ok, QuxSocket} = gen_udp:open(QuxPort, [binary, {reuseaddr, true}]),
gen_udp:send(QuxSocket, LocalHostIP, FooRecPort, Request1),
{ok, [RecoveredMsg4]} = receive_messages("foo", QuxSocket, 500),
gen_udp:send(QuxSocket, LocalHostIP, FooRecPort, Request2),
{ok, [RecoveredMsg5]} = receive_messages("foo", QuxSocket, 500),
test when requested sequence number > total number of msgs sent
Request6a = <<SessionName/binary, 100:64, 1:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request6a),
Result6a = receive_messages("foo", FooSocket, 500),
test when requested sequence number < = 0
Request6b = <<SessionName/binary, 0:64, 1:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request6b),
Result6b = receive_messages("foo", FooSocket, 500),
Request6c = <<SessionName/binary, 1:64, 5000:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request6c),
Result6c = receive_messages("foo", FooSocket, 500),
test when requested sequence number + requested count > total number of msgs sent
Request7 = <<SessionName/binary, 6:64, 100:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request7),
{ok, RecoveredMsgs7} = receive_messages("foo", FooSocket, 500),
test when requested count is zero
Request8 = <<SessionName/binary, 2:64, 0:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request8),
Result8 = receive_messages("foo", FooSocket, 500),
Request9 = <<SessionName/binary, 7:64, 8:16>>,
gen_udp:send(FooSocket, LocalHostIP, FooRecPort, Request9),
{ok, RecoveredMsgs9} = receive_messages("foo", FooSocket, 500),
[
?_assertEqual({error, destination_address_already_in_use}, ConflictAddr),
?_assertEqual({error, recovery_port_already_in_use}, ConflictPort),
?_assertEqual(<<"HelloWorld">>, Msg1),
?_assertEqual(<<"HelloWorld">>, Msg2),
?_assertMatch([{_,<<"foo">>},{_,<<"bar">>},{_,<<"baz">>}], Msgs),
?_assertMatch([{_,<<"bar">>},{_,<<"bar">>}], BarMsgs),
?_assertMatch([{_,<<"baz">>},{_,<<"baz">>}], BazMsgs),
?_assertMatch([{_,<<"foo">>},{_,<<"foo">>}], FooMsgs),
?_assertEqual(BigMsg, ExpectedBigMsg),
?_assertEqual({Seq1, Msg1}, RecoveredMsg1),
?_assertEqual({Seq2, Msg2}, RecoveredMsg2),
?_assertEqual([{Seq3, <<"foo">>}, {Seq3+1, <<"bar">>}, {Seq3+2, <<"baz">>}], RecoveredMsgs3),
?_assertEqual({Seq1, Msg1}, RecoveredMsg4),
?_assertEqual({Seq2, Msg2}, RecoveredMsg5),
?_assertEqual({error, timeout}, Result6a),
?_assertEqual({error, timeout}, Result6b),
?_assertEqual({error, timeout}, Result6c),
?_assertEqual([{6, <<"foo">>}, {7, <<"foo">>}], RecoveredMsgs7),
?_assertEqual({error, timeout}, Result8),
?_assertEqual([{7, <<"foo">>}], RecoveredMsgs9)
].
molderl_test_() ->
{setup,
fun start/0,
fun stop/1,
fun instantiator/1}.
|
3fb65deb742f87c7ad9040a19fc23b8595638d1cea3b25c62d053aa16e37dd29 | BoeingX/haskell-programming-from-first-principles | ParseDigitAndInteger.hs | module ParserCombinators.ChapterExercises.ParseDigitAndInteger where
import Control.Applicative
import Data.List
import Text.Trifecta
instance (Eq a) => Eq (Result a) where
Success a == Success b = a == b
Failure a == Failure b = True
_ == _ = False
parseDigit :: Parser Char
parseDigit = oneOf $ concatMap show [0..9]
readChar :: (Read a) => Char -> a
readChar a = read [a]
base10Integer :: Parser Integer
base10Integer = do
-- (<?>) give parser a name
-- See -0.12.9/docs/Text-Parser-Combinators.html
digits <- some parseDigit <?> "integer"
return $ (foldl1' (\acc x -> 10 * acc + x) . map readChar) digits
base10Integer' :: Parser Integer
base10Integer' = (char '+' >> base10Integer)
<|> (char '-' >> base10Integer >>= \x -> return (-x))
<|> base10Integer
| null | https://raw.githubusercontent.com/BoeingX/haskell-programming-from-first-principles/ffb637f536597f552a4e4567fee848ed27f3ba74/src/ParserCombinators/ChapterExercises/ParseDigitAndInteger.hs | haskell | (<?>) give parser a name
See -0.12.9/docs/Text-Parser-Combinators.html | module ParserCombinators.ChapterExercises.ParseDigitAndInteger where
import Control.Applicative
import Data.List
import Text.Trifecta
instance (Eq a) => Eq (Result a) where
Success a == Success b = a == b
Failure a == Failure b = True
_ == _ = False
parseDigit :: Parser Char
parseDigit = oneOf $ concatMap show [0..9]
readChar :: (Read a) => Char -> a
readChar a = read [a]
base10Integer :: Parser Integer
base10Integer = do
digits <- some parseDigit <?> "integer"
return $ (foldl1' (\acc x -> 10 * acc + x) . map readChar) digits
base10Integer' :: Parser Integer
base10Integer' = (char '+' >> base10Integer)
<|> (char '-' >> base10Integer >>= \x -> return (-x))
<|> base10Integer
|
68d794c6e9107efd666b1c12dec7ab5224fea66463ad8c2641be53591cce16d5 | haskell-game/tiny-games-hs | lambda-ray.hs | import Control.Concurrent; import System.Posix.Internals;w=100;q=0.4;n=min;c=cos
p=[(x/w*2-1,(y/20*2-1)*0.2)| y<-[0..20], x<-[0..w+1]];t=max 0;o=True;a=abs;s=sin
main=go 0;r t (x,y,z)=(x*c t - y*s t, x*s t + y*c t, z);v=sqrt;u _(1.02,_)= '\n'
u t(x,y)=m t 0(10*x,10*y,-5);b h w(x,y,z)=v(t(a x-w)**2+t(a y-h)**2+t(a z-q)**2)
go n=puts("\^[c\n"++map(u(n/6.3))p)>>threadDelay 100000>>go(n+1);h p@(x,y,z)=let
a=b 5q;l=(x+3,y,z);i|y>=0=a(r(-1)l)|o=9;j|y<0=a(r 1l)|o=9;k=a(r 1p)
c|y>0=a(r(-1)p)|o=9;m=b 5 2(r 1(x-6,y,z));g s=b 6 0.2 (r(pi/2)(x-1,y+s*q,z))
e=max m(n(g 1)(g(-1))) in n(n i j)(n e(n k c));m _ 20 _=' ';m t n(x,y,z)=let
a=x*c(t)-z*s t;b=x*s t+z*c t;nz=h(a,y,b+q)-h(a,y,b-q);ny=h(a,y+q,b)-h(a,y-q,b)
d=h(a,y,b);g|nz<0='o'|ny<0='>'|o='.';r|d<0.01=g|o=m t(n+1)(x,y,z+d);q=0.001in r
-- ^10 ------------------------------------------------------------------ 80> --
base-10 - 80 / lambda - ray ( tristanC )
- Play : $ ghc -O2 lambda-ray.hs & & ./lambda - ray
Copyright 2023 ,
SPDX - License - Identifier : CC - BY-4.0
- Play: $ ghc -O2 lambda-ray.hs && ./lambda-ray
Copyright 2023, Tristan de Cacqueray
SPDX-License-Identifier: CC-BY-4.0
-}
| null | https://raw.githubusercontent.com/haskell-game/tiny-games-hs/3ccee1a663ac93a3bd2a302a9c09c2f5c60306ac/base/lambda-ray/lambda-ray.hs | haskell | ^10 ------------------------------------------------------------------ 80> -- | import Control.Concurrent; import System.Posix.Internals;w=100;q=0.4;n=min;c=cos
p=[(x/w*2-1,(y/20*2-1)*0.2)| y<-[0..20], x<-[0..w+1]];t=max 0;o=True;a=abs;s=sin
main=go 0;r t (x,y,z)=(x*c t - y*s t, x*s t + y*c t, z);v=sqrt;u _(1.02,_)= '\n'
u t(x,y)=m t 0(10*x,10*y,-5);b h w(x,y,z)=v(t(a x-w)**2+t(a y-h)**2+t(a z-q)**2)
go n=puts("\^[c\n"++map(u(n/6.3))p)>>threadDelay 100000>>go(n+1);h p@(x,y,z)=let
a=b 5q;l=(x+3,y,z);i|y>=0=a(r(-1)l)|o=9;j|y<0=a(r 1l)|o=9;k=a(r 1p)
c|y>0=a(r(-1)p)|o=9;m=b 5 2(r 1(x-6,y,z));g s=b 6 0.2 (r(pi/2)(x-1,y+s*q,z))
e=max m(n(g 1)(g(-1))) in n(n i j)(n e(n k c));m _ 20 _=' ';m t n(x,y,z)=let
a=x*c(t)-z*s t;b=x*s t+z*c t;nz=h(a,y,b+q)-h(a,y,b-q);ny=h(a,y+q,b)-h(a,y-q,b)
d=h(a,y,b);g|nz<0='o'|ny<0='>'|o='.';r|d<0.01=g|o=m t(n+1)(x,y,z+d);q=0.001in r
base-10 - 80 / lambda - ray ( tristanC )
- Play : $ ghc -O2 lambda-ray.hs & & ./lambda - ray
Copyright 2023 ,
SPDX - License - Identifier : CC - BY-4.0
- Play: $ ghc -O2 lambda-ray.hs && ./lambda-ray
Copyright 2023, Tristan de Cacqueray
SPDX-License-Identifier: CC-BY-4.0
-}
|
2ed1d08f2eac37af2cff4e9a95e334aed50aa4934b8d1f4acf11ec6badc4702c | HaskellZhangSong/Introduction_to_Haskell_2ed_source | Iteratee.hs | # LANGUAGE DeriveFunctor #
import Data.Function (fix)
import Control.Monad
import qualified Control.Exception as Exc
import Control.Monad.IO.Class
import Control.Monad.Trans
data Stream a = Chunks [a] | EOF
deriving (Show, Eq,Functor)
instance Monoid (Stream a) where
mempty = Chunks mempty
mappend (Chunks xs) (Chunks ys) = Chunks (xs ++ ys)
mappend _ _ = EOF
instance Monad Stream where
return = Chunks . return
Chunks xs >>= f = mconcat (fmap f xs)
EOF >>= _ = EOF
instance Applicative Stream where
pure = return
(<*>) = ap
data Step a m b
= Continue (Stream a -> Iteratee a m b)
| Yield b (Stream a)
| Error Exc.SomeException
deriving Functor
newtype Iteratee a m b = Iteratee { runIteratee :: m (Step a m b)}
deriving Functor
instance Monad m => Monad (Iteratee a m) where
return x = yield x (Chunks [])
m0 >>= f = ($ m0) $ fix $
\bind m -> Iteratee $ runIteratee m >>= \r1 ->
case r1 of
Continue k -> return (Continue (bind . k))
Error err -> return (Error err)
Yield x (Chunks []) -> runIteratee (f x)
Yield x extra -> runIteratee (f x) >>= \r2 ->
case r2 of
Continue k -> runIteratee (k extra)
Error err -> return (Error err)
Yield x' _ -> return (Yield x' extra)
instance Monad m => Applicative (Iteratee a m) where
pure = return
(<*>) = ap
instance MonadTrans (Iteratee a) where
lift m = Iteratee (m >>= runIteratee . return)
instance MonadIO m => MonadIO (Iteratee a m) where
liftIO = lift . liftIO
returnI :: Monad m => Step a m b -> Iteratee a m b
returnI step = Iteratee (return step)
yield :: Monad m => b -> Stream a -> Iteratee a m b
yield x extra = returnI (Yield x extra)
continue :: Monad m => (Stream a -> Iteratee a m b) -> Iteratee a m b
continue k = returnI (Continue k)
enumEOF :: Monad m => Enumerator a m b
enumEOF (Yield x _) = yield x EOF
enumEOF (Error err) = returnI (Error err)
enumEOF (Continue k) = k EOF >>== check where
check (Continue _) = error "mEOF: divergent iteratee"
check s = enumEOF s
run :: Monad m => Iteratee a m b
-> m (Either Exc.SomeException b)
run i = do
mStep <- runIteratee $ enumEOF ==<< i
case mStep of
Error err -> return $ Left err
Yield x _ -> return $ Right x
Continue _ -> error "run: divergent iteratee"
run_ :: Monad m => Iteratee a m b -> m b
run_ i = run i >>= either Exc.throw return
type Enumerator a m b = Step a m b -> Iteratee a m b
enumList :: Monad m => Int -> [a] -> Enumerator a m b
enumList n = loop where
loop xs (Continue k) | not (null xs) = let
(s1, s2) = splitAt n xs
in k (Chunks s1) >>== loop s2
loop _ step = returnI step
type Enumeratee ao ai m b = Step ai m b -> Iteratee ao m (Step ai m b)
infixl 1 >>==
infixr 1 ==<<
infixr 0 $$
infixr 1 >==>
infixr 1 <==<
(>>==) :: Monad m
=> Iteratee a m b
-> (Step a m b -> Iteratee a' m b')
-> Iteratee a' m b'
i >>== f = Iteratee (runIteratee i >>= runIteratee . f)
(==<<) :: Monad m
=> (Step a m b -> Iteratee a' m b')
-> Iteratee a m b
-> Iteratee a' m b'
(==<<) = flip (>>==)
($$) :: Monad m
=> (Step a m b -> Iteratee a' m b')
-> Iteratee a m b
-> Iteratee a' m b'
($$) = (==<<)
(>==>) :: Monad m
=> Enumerator a m b
-> (Step a m b -> Iteratee a' m b')
-> Step a m b
-> Iteratee a' m b'
(>==>) e1 e2 s = e1 s >>== e2
(<==<) :: Monad m
=> (Step a m b -> Iteratee a' m b')
-> Enumerator a m b
-> Step a m b
-> Iteratee a' m b'
(<==<) = flip (>==>)
throwError :: (Monad m, Exc.Exception e) => e -> Iteratee a m b
throwError exc = returnI (Error (Exc.toException exc))
joinI :: Monad m => Iteratee a m (Step a' m b)-> Iteratee a m b
joinI outer = outer >>= check where
check (Continue k) = k EOF >>== \s -> case s of
Continue _ -> error "joinI: divergent iteratee"
_ -> check s
check (Yield x _) = return x
check (Error e) = throwError e
iterateeHead :: Monad m => Iteratee a m (Maybe a)
iterateeHead = continue loop
where
loop (Chunks []) = iterateeHead
loop (Chunks (x:xs)) = yield (Just x) (Chunks xs)
loop EOF = yield Nothing EOF
iterateeLength :: Monad m => Iteratee stream m Int
iterateeLength = continue (loop 0)
where
loop n (Chunks []) = iterateeLength
loop n (Chunks xs) = continue (loop (n + length xs))
loop n EOF = yield n EOF
iterateeSum :: Monad m => Iteratee Int m Int
iterateeSum = continue (step 0)
where
step n (Chunks []) = iterateeSum
step n (Chunks xs) = continue (step (n + sum xs))
step n EOF = yield n EOF
iterateeDrop :: Monad m => Int -> Iteratee a m ()
iterateeDrop n | n <= 0 = return ()
iterateeDrop n = continue (loop n) where
loop n' (Chunks xs) = iter where
len = length xs
iter = if len < n'
then iterateeDrop (n' - len)
else yield () (Chunks (drop n' xs))
loop _ EOF = yield () EOF
drop1keep1 :: Monad m => Iteratee s m (Maybe s)
drop1keep1 = iterateeDrop 1 >> iterateeHead
alternates :: Monad m => Iteratee s m [Maybe s]
alternates = replicateM 5 drop1keep1
checkYield :: Monad m =>
((Stream i -> Iteratee i m a) -> Iteratee o m (Step i m a)) ->
Enumeratee o i m a
checkYield _ y@(Yield x chunk) = return y
checkYield f (Continue k) = f k
iterateeMap :: Monad m => (o -> i) -> Enumeratee o i m a
iterateeMap f = checkYield $ continue . step where
step k EOF = yield (Continue k) EOF
step k (Chunks []) = continue $ step k
step k chunk = k (fmap f chunk) >>== iterateeMap f
(=$) :: Monad m => Enumeratee ao ai m b -> Iteratee ai m b -> Iteratee ao m b
enum =$ iter = joinI (enum ==<< iter)
| null | https://raw.githubusercontent.com/HaskellZhangSong/Introduction_to_Haskell_2ed_source/140c50fdccfe608fe499ecf2d8a3732f531173f5/C14/Iteratee.hs | haskell | # LANGUAGE DeriveFunctor #
import Data.Function (fix)
import Control.Monad
import qualified Control.Exception as Exc
import Control.Monad.IO.Class
import Control.Monad.Trans
data Stream a = Chunks [a] | EOF
deriving (Show, Eq,Functor)
instance Monoid (Stream a) where
mempty = Chunks mempty
mappend (Chunks xs) (Chunks ys) = Chunks (xs ++ ys)
mappend _ _ = EOF
instance Monad Stream where
return = Chunks . return
Chunks xs >>= f = mconcat (fmap f xs)
EOF >>= _ = EOF
instance Applicative Stream where
pure = return
(<*>) = ap
data Step a m b
= Continue (Stream a -> Iteratee a m b)
| Yield b (Stream a)
| Error Exc.SomeException
deriving Functor
newtype Iteratee a m b = Iteratee { runIteratee :: m (Step a m b)}
deriving Functor
instance Monad m => Monad (Iteratee a m) where
return x = yield x (Chunks [])
m0 >>= f = ($ m0) $ fix $
\bind m -> Iteratee $ runIteratee m >>= \r1 ->
case r1 of
Continue k -> return (Continue (bind . k))
Error err -> return (Error err)
Yield x (Chunks []) -> runIteratee (f x)
Yield x extra -> runIteratee (f x) >>= \r2 ->
case r2 of
Continue k -> runIteratee (k extra)
Error err -> return (Error err)
Yield x' _ -> return (Yield x' extra)
instance Monad m => Applicative (Iteratee a m) where
pure = return
(<*>) = ap
instance MonadTrans (Iteratee a) where
lift m = Iteratee (m >>= runIteratee . return)
instance MonadIO m => MonadIO (Iteratee a m) where
liftIO = lift . liftIO
returnI :: Monad m => Step a m b -> Iteratee a m b
returnI step = Iteratee (return step)
yield :: Monad m => b -> Stream a -> Iteratee a m b
yield x extra = returnI (Yield x extra)
continue :: Monad m => (Stream a -> Iteratee a m b) -> Iteratee a m b
continue k = returnI (Continue k)
enumEOF :: Monad m => Enumerator a m b
enumEOF (Yield x _) = yield x EOF
enumEOF (Error err) = returnI (Error err)
enumEOF (Continue k) = k EOF >>== check where
check (Continue _) = error "mEOF: divergent iteratee"
check s = enumEOF s
run :: Monad m => Iteratee a m b
-> m (Either Exc.SomeException b)
run i = do
mStep <- runIteratee $ enumEOF ==<< i
case mStep of
Error err -> return $ Left err
Yield x _ -> return $ Right x
Continue _ -> error "run: divergent iteratee"
run_ :: Monad m => Iteratee a m b -> m b
run_ i = run i >>= either Exc.throw return
type Enumerator a m b = Step a m b -> Iteratee a m b
enumList :: Monad m => Int -> [a] -> Enumerator a m b
enumList n = loop where
loop xs (Continue k) | not (null xs) = let
(s1, s2) = splitAt n xs
in k (Chunks s1) >>== loop s2
loop _ step = returnI step
type Enumeratee ao ai m b = Step ai m b -> Iteratee ao m (Step ai m b)
infixl 1 >>==
infixr 1 ==<<
infixr 0 $$
infixr 1 >==>
infixr 1 <==<
(>>==) :: Monad m
=> Iteratee a m b
-> (Step a m b -> Iteratee a' m b')
-> Iteratee a' m b'
i >>== f = Iteratee (runIteratee i >>= runIteratee . f)
(==<<) :: Monad m
=> (Step a m b -> Iteratee a' m b')
-> Iteratee a m b
-> Iteratee a' m b'
(==<<) = flip (>>==)
($$) :: Monad m
=> (Step a m b -> Iteratee a' m b')
-> Iteratee a m b
-> Iteratee a' m b'
($$) = (==<<)
(>==>) :: Monad m
=> Enumerator a m b
-> (Step a m b -> Iteratee a' m b')
-> Step a m b
-> Iteratee a' m b'
(>==>) e1 e2 s = e1 s >>== e2
(<==<) :: Monad m
=> (Step a m b -> Iteratee a' m b')
-> Enumerator a m b
-> Step a m b
-> Iteratee a' m b'
(<==<) = flip (>==>)
throwError :: (Monad m, Exc.Exception e) => e -> Iteratee a m b
throwError exc = returnI (Error (Exc.toException exc))
joinI :: Monad m => Iteratee a m (Step a' m b)-> Iteratee a m b
joinI outer = outer >>= check where
check (Continue k) = k EOF >>== \s -> case s of
Continue _ -> error "joinI: divergent iteratee"
_ -> check s
check (Yield x _) = return x
check (Error e) = throwError e
iterateeHead :: Monad m => Iteratee a m (Maybe a)
iterateeHead = continue loop
where
loop (Chunks []) = iterateeHead
loop (Chunks (x:xs)) = yield (Just x) (Chunks xs)
loop EOF = yield Nothing EOF
iterateeLength :: Monad m => Iteratee stream m Int
iterateeLength = continue (loop 0)
where
loop n (Chunks []) = iterateeLength
loop n (Chunks xs) = continue (loop (n + length xs))
loop n EOF = yield n EOF
iterateeSum :: Monad m => Iteratee Int m Int
iterateeSum = continue (step 0)
where
step n (Chunks []) = iterateeSum
step n (Chunks xs) = continue (step (n + sum xs))
step n EOF = yield n EOF
iterateeDrop :: Monad m => Int -> Iteratee a m ()
iterateeDrop n | n <= 0 = return ()
iterateeDrop n = continue (loop n) where
loop n' (Chunks xs) = iter where
len = length xs
iter = if len < n'
then iterateeDrop (n' - len)
else yield () (Chunks (drop n' xs))
loop _ EOF = yield () EOF
drop1keep1 :: Monad m => Iteratee s m (Maybe s)
drop1keep1 = iterateeDrop 1 >> iterateeHead
alternates :: Monad m => Iteratee s m [Maybe s]
alternates = replicateM 5 drop1keep1
checkYield :: Monad m =>
((Stream i -> Iteratee i m a) -> Iteratee o m (Step i m a)) ->
Enumeratee o i m a
checkYield _ y@(Yield x chunk) = return y
checkYield f (Continue k) = f k
iterateeMap :: Monad m => (o -> i) -> Enumeratee o i m a
iterateeMap f = checkYield $ continue . step where
step k EOF = yield (Continue k) EOF
step k (Chunks []) = continue $ step k
step k chunk = k (fmap f chunk) >>== iterateeMap f
(=$) :: Monad m => Enumeratee ao ai m b -> Iteratee ai m b -> Iteratee ao m b
enum =$ iter = joinI (enum ==<< iter)
| |
145a5d7a60225ec1f406ad3fca370b4d900b051d1d70ff3a4dcc35f96d4a998c | epicallan/hreq | SuccessSpec.hs | module Hreq.Pure.SuccessSpec (spec) where
import Data.Foldable
import Data.Proxy
import Test.Hspec
import Hreq.Client
import Hreq.Core.Client (RequestBody (..))
import Hreq.Pure.Util (TestState (..), TestUser (..), defaultResponse, runClientPure)
spec :: Spec
spec = describe "Hreq.SuccessSpec" successSpec
testUser :: TestUser
testUser = TestUser "Allan" 29
successSpec :: Spec
successSpec = do
let baseUrl = HttpDomain "example.com"
runClientPure' = runClientPure @'Default
describe "Works with request components" $ do
it "works with paths" $ do
let x = hreq @("hello" :> RawResponse GET) Empty
expected = RunClient (appendToPath "hello" defaultRequest) defaultResponse
runClientPure' baseUrl x `shouldBe` expected
it "works with request body" $ do
let x = hreq @(JsonBody TestUser :> RawResponse GET) (testUser :. Empty)
RunClient req _ = runClientPure' baseUrl x
Just (RequestBodyLBS body, _ ) = reqBody req
body `shouldBe` mediaEncode (Proxy @JSON) testUser
it "works with query flags" $ do
let x = hreq @("users" :> QueryFlag "male" :> QueryFlag "old" :> RawResponse GET) Empty
RunClient req _ = runClientPure @'Default baseUrl x
reqPath req `shouldBe` "/users"
toList (reqQueryString req) `shouldBe` [("male", Nothing), ("old", Nothing)]
it "works with capture" $ do
let x = hreq @(Capture String :> RawResponse GET) ("allan" :. Empty)
RunClient req _ = runClientPure @'Default baseUrl x
reqPath req `shouldBe` "/allan"
it "works with captureAll" $ do
let x = hreq @(CaptureAll String :> RawResponse GET) (["allan", "lukwago"] :. Empty)
RunClient req _ = runClientPure @'Default baseUrl x
reqPath req `shouldBe` "/allan/lukwago"
it "works with single query params" $ do
let x = hreq @(Param "name" String :> RawResponse GET) ("allan" :. Empty)
RunClient req _ = runClientPure @'Default baseUrl x
toList (reqQueryString req) `shouldBe` [("name", Just "allan")]
it "works with multi query params" $ do
let x = hreq @(Param "name" String :> Param "age" Int :> RawResponse GET) ("allan" :. 29 :. Empty)
RunClient req _ = runClientPure @'Default baseUrl x
toList (reqQueryString req) `shouldBe` [("name", Just "allan"), ("age", Just "29")]
it "works with multi query params as a list" $ do
let x = hreq @(Params '["name" := String, "age" := Int] :> RawResponse GET) ("allan" :. 29 :. Empty)
RunClient req _ = runClientPure @'Default baseUrl x
toList (reqQueryString req) `shouldBe` [("name", Just "allan"), ("age", Just "29")]
describe "Works with response components" $ do
it "works with single verb requests" $ do
let x = hreq @(RawResponse GET) Empty
expected = RunClient defaultRequest defaultResponse
runClientPure' baseUrl x `shouldBe` expected
it "works with JSON responses" $ do
let x = hreq @(GetJson TestUser) Empty
RunClient _ res = runClientPure @'Default baseUrl x
res `shouldBe` testUser
| null | https://raw.githubusercontent.com/epicallan/hreq/f12fcb9b9dd1ad903c6b36a8cf850edb213d4792/hreq-client/test/Hreq/Pure/SuccessSpec.hs | haskell | module Hreq.Pure.SuccessSpec (spec) where
import Data.Foldable
import Data.Proxy
import Test.Hspec
import Hreq.Client
import Hreq.Core.Client (RequestBody (..))
import Hreq.Pure.Util (TestState (..), TestUser (..), defaultResponse, runClientPure)
spec :: Spec
spec = describe "Hreq.SuccessSpec" successSpec
testUser :: TestUser
testUser = TestUser "Allan" 29
successSpec :: Spec
successSpec = do
let baseUrl = HttpDomain "example.com"
runClientPure' = runClientPure @'Default
describe "Works with request components" $ do
it "works with paths" $ do
let x = hreq @("hello" :> RawResponse GET) Empty
expected = RunClient (appendToPath "hello" defaultRequest) defaultResponse
runClientPure' baseUrl x `shouldBe` expected
it "works with request body" $ do
let x = hreq @(JsonBody TestUser :> RawResponse GET) (testUser :. Empty)
RunClient req _ = runClientPure' baseUrl x
Just (RequestBodyLBS body, _ ) = reqBody req
body `shouldBe` mediaEncode (Proxy @JSON) testUser
it "works with query flags" $ do
let x = hreq @("users" :> QueryFlag "male" :> QueryFlag "old" :> RawResponse GET) Empty
RunClient req _ = runClientPure @'Default baseUrl x
reqPath req `shouldBe` "/users"
toList (reqQueryString req) `shouldBe` [("male", Nothing), ("old", Nothing)]
it "works with capture" $ do
let x = hreq @(Capture String :> RawResponse GET) ("allan" :. Empty)
RunClient req _ = runClientPure @'Default baseUrl x
reqPath req `shouldBe` "/allan"
it "works with captureAll" $ do
let x = hreq @(CaptureAll String :> RawResponse GET) (["allan", "lukwago"] :. Empty)
RunClient req _ = runClientPure @'Default baseUrl x
reqPath req `shouldBe` "/allan/lukwago"
it "works with single query params" $ do
let x = hreq @(Param "name" String :> RawResponse GET) ("allan" :. Empty)
RunClient req _ = runClientPure @'Default baseUrl x
toList (reqQueryString req) `shouldBe` [("name", Just "allan")]
it "works with multi query params" $ do
let x = hreq @(Param "name" String :> Param "age" Int :> RawResponse GET) ("allan" :. 29 :. Empty)
RunClient req _ = runClientPure @'Default baseUrl x
toList (reqQueryString req) `shouldBe` [("name", Just "allan"), ("age", Just "29")]
it "works with multi query params as a list" $ do
let x = hreq @(Params '["name" := String, "age" := Int] :> RawResponse GET) ("allan" :. 29 :. Empty)
RunClient req _ = runClientPure @'Default baseUrl x
toList (reqQueryString req) `shouldBe` [("name", Just "allan"), ("age", Just "29")]
describe "Works with response components" $ do
it "works with single verb requests" $ do
let x = hreq @(RawResponse GET) Empty
expected = RunClient defaultRequest defaultResponse
runClientPure' baseUrl x `shouldBe` expected
it "works with JSON responses" $ do
let x = hreq @(GetJson TestUser) Empty
RunClient _ res = runClientPure @'Default baseUrl x
res `shouldBe` testUser
| |
a87f0f8928289d0388ad44c38dcbed76b3dd3b294eaa3fbebdf20bc1769ca2c2 | samply/blaze | resource_spec.clj | (ns blaze.db.impl.index.compartment.resource-spec
(:require
[blaze.byte-string-spec]
[blaze.coll.core-spec]
[blaze.db.impl.codec.spec]
[blaze.db.impl.index.compartment.resource :as cr]
[blaze.db.impl.iterators-spec]
[blaze.db.impl.search-param.spec]
[blaze.db.kv.spec]
[clojure.spec.alpha :as s]))
(s/fdef cr/resource-handles!
:args (s/cat :context :blaze.db.impl.batch-db/context
:compartment :blaze.db/compartment
:tid :blaze.db/tid
:start-id (s/? :blaze.db/id-byte-string))
:ret (s/coll-of :blaze.db/resource-handle :kind sequential?))
(s/fdef cr/index-entry
:args (s/cat :compartment :blaze.db/compartment
:tid :blaze.db/tid
:id :blaze.db/id-byte-string)
:ret :blaze.db.kv/put-entry)
| null | https://raw.githubusercontent.com/samply/blaze/e84c106b5ca235600c20ba74fe8a2295eb18f350/modules/db/test/blaze/db/impl/index/compartment/resource_spec.clj | clojure | (ns blaze.db.impl.index.compartment.resource-spec
(:require
[blaze.byte-string-spec]
[blaze.coll.core-spec]
[blaze.db.impl.codec.spec]
[blaze.db.impl.index.compartment.resource :as cr]
[blaze.db.impl.iterators-spec]
[blaze.db.impl.search-param.spec]
[blaze.db.kv.spec]
[clojure.spec.alpha :as s]))
(s/fdef cr/resource-handles!
:args (s/cat :context :blaze.db.impl.batch-db/context
:compartment :blaze.db/compartment
:tid :blaze.db/tid
:start-id (s/? :blaze.db/id-byte-string))
:ret (s/coll-of :blaze.db/resource-handle :kind sequential?))
(s/fdef cr/index-entry
:args (s/cat :compartment :blaze.db/compartment
:tid :blaze.db/tid
:id :blaze.db/id-byte-string)
:ret :blaze.db.kv/put-entry)
| |
1f2c8f8211df1883ea11842613ebbbc2c16c07f40306428c9a2f354b48c06d6a | MinaProtocol/mina | construction_parse_response.ml |
* This file has been generated by the OCamlClientCodegen generator for openapi - generator .
*
* Generated by : -generator.tech
*
* Schema Construction_parse_response.t : ConstructionParseResponse contains an array of operations that occur in a transaction blob . This should match the array of operations provided to ` /construction / preprocess ` and ` /construction / payloads ` .
* This file has been generated by the OCamlClientCodegen generator for openapi-generator.
*
* Generated by: -generator.tech
*
* Schema Construction_parse_response.t : ConstructionParseResponse contains an array of operations that occur in a transaction blob. This should match the array of operations provided to `/construction/preprocess` and `/construction/payloads`.
*)
type t =
{ operations : Operation.t list
; (* [DEPRECATED by `account_identifier_signers` in `v1.4.4`] All signers (addresses) of a particular transaction. If the transaction is unsigned, it should be empty. *)
signers : string list
; account_identifier_signers : Account_identifier.t list
; metadata : Yojson.Safe.t option [@default None]
}
[@@deriving yojson { strict = false }, show, eq]
(** ConstructionParseResponse contains an array of operations that occur in a transaction blob. This should match the array of operations provided to `/construction/preprocess` and `/construction/payloads`. *)
let create (operations : Operation.t list) : t =
{ operations; signers = []; account_identifier_signers = []; metadata = None }
| null | https://raw.githubusercontent.com/MinaProtocol/mina/a80b00221953c26ff158e7375a948b5fa9e7bd8b/src/lib/rosetta_models/construction_parse_response.ml | ocaml | [DEPRECATED by `account_identifier_signers` in `v1.4.4`] All signers (addresses) of a particular transaction. If the transaction is unsigned, it should be empty.
* ConstructionParseResponse contains an array of operations that occur in a transaction blob. This should match the array of operations provided to `/construction/preprocess` and `/construction/payloads`. |
* This file has been generated by the OCamlClientCodegen generator for openapi - generator .
*
* Generated by : -generator.tech
*
* Schema Construction_parse_response.t : ConstructionParseResponse contains an array of operations that occur in a transaction blob . This should match the array of operations provided to ` /construction / preprocess ` and ` /construction / payloads ` .
* This file has been generated by the OCamlClientCodegen generator for openapi-generator.
*
* Generated by: -generator.tech
*
* Schema Construction_parse_response.t : ConstructionParseResponse contains an array of operations that occur in a transaction blob. This should match the array of operations provided to `/construction/preprocess` and `/construction/payloads`.
*)
type t =
{ operations : Operation.t list
signers : string list
; account_identifier_signers : Account_identifier.t list
; metadata : Yojson.Safe.t option [@default None]
}
[@@deriving yojson { strict = false }, show, eq]
let create (operations : Operation.t list) : t =
{ operations; signers = []; account_identifier_signers = []; metadata = None }
|
1c6ca7653b6784071cd30bb7765a961ba145aa62770b6d9b970a5d9b949402b6 | pveber/biotk | sam.ml | open Core
module Seq = Caml.Seq
open Result.Monad_infix
let ( >>?~ )
(x : 'a option Or_error.t)
(f : 'a -> 'b Or_error.t)
: 'b option Or_error.t
=
let open Result.Monad_infix in
x >>= function
| None -> Ok None
| Some x -> f x >>| Option.some
(******************************************************************************)
(* Header Types *)
(******************************************************************************)
type header_item_tag = [
| `HD | `SQ | `RG | `PG | `CO
| `Other of string
] [@@deriving sexp]
type tag_value = string * string
[@@deriving sexp]
type sort_order = [ `Unknown | `Unsorted | `Query_name | `Coordinate ]
[@@deriving sexp]
type group_order = [ `None | `Query | `Reference ]
[@@deriving sexp]
type header_line = {
version : string;
sort_order : sort_order option;
group_order: group_order option;
} [@@deriving sexp]
type ref_seq = {
name : string;
length : int;
assembly : string option;
md5 : string option;
species : string option;
uri : string option;
} [@@deriving sexp]
type platform = [
| `Capillary | `LS454 | `Illumina | `Solid
| `Helicos | `Ion_Torrent | `Pac_Bio
] [@@deriving sexp]
type read_group = {
id : string;
seq_center : string option;
description : string option;
run_date : [`Date of string | `Time of string] option;
flow_order : string option;
key_seq : string option;
library : string option;
program : string option;
predicted_median_insert_size : int option;
platform : platform option;
platform_unit : string option;
sample : string option;
} [@@deriving sexp]
type program = {
id : string;
name : string option;
command_line : string option;
previous_id : string option;
description : string option;
version : string option;
} [@@deriving sexp]
type header_item = [
| `HD of header_line
| `SQ of ref_seq
| `RG of read_group
| `PG of program
| `CO of string
| `Other of string * tag_value list
] [@@deriving sexp]
type header = {
version : string option;
sort_order : sort_order option;
group_order : group_order option;
ref_seqs : ref_seq list;
read_groups : read_group list;
programs : program list;
comments : string list;
others : (string * tag_value list) list;
}
let empty_header = {
version = None;
sort_order = None;
group_order = None;
ref_seqs = [];
read_groups = [];
programs = [];
comments = [];
others = [];
}
(******************************************************************************)
(* Alignment Types *)
(******************************************************************************)
module Flags = struct
type t = int
[@@deriving sexp]
let of_int x =
if (0 <= x) && (x <= 65535) then
Ok x
else
error "flag out of range" x sexp_of_int
let flag_is_set s f = (f land s) <> 0
let has_multiple_segments = flag_is_set 0x1
let each_segment_properly_aligned = flag_is_set 0x2
let segment_unmapped = flag_is_set 0x4
let next_segment_unmapped = flag_is_set 0x8
let seq_is_reverse_complemented = flag_is_set 0x10
let next_seq_is_reverse_complemented = flag_is_set 0x20
let first_segment = flag_is_set 0x40
let last_segment = flag_is_set 0x80
let secondary_alignment = flag_is_set 0x100
let not_passing_quality_controls = flag_is_set 0x200
let pcr_or_optical_duplicate = flag_is_set 0x400
let supplementary_alignment = flag_is_set 0x800
end
type cigar_op = [
| `Alignment_match of int
| `Insertion of int
| `Deletion of int
| `Skipped of int
| `Soft_clipping of int
| `Hard_clipping of int
| `Padding of int
| `Seq_match of int
| `Seq_mismatch of int
] [@@deriving sexp]
type optional_field_value = [
| `A of char
| `i of Int64.t
| `f of float
| `Z of string
| `H of string
| `B of char * string list
] [@@deriving sexp]
type optional_field = {
tag : string;
value : optional_field_value
} [@@deriving sexp]
type rnext = [`Value of string | `Equal_to_RNAME]
[@@deriving sexp]
type alignment = {
qname : string option;
flags : Flags.t;
rname : string option;
pos : int option;
mapq : int option;
cigar : cigar_op list;
rnext : rnext option;
pnext : int option;
tlen : int option;
seq: string option;
qual: Phred_score.t list;
optional_fields : optional_field list;
} [@@deriving sexp]
(******************************************************************************)
Header Parsers and Constructors
(******************************************************************************)
let parse_header_version s =
let err =
error "invalid version" (`HD, s)
[%sexp_of: header_item_tag * string ]
in
match String.lsplit2 ~on:'.' s with
| None -> err
| Some (a,b) ->
if (String.for_all a ~f:Char.is_digit)
&& (String.for_all b ~f:Char.is_digit)
then
Ok s
else
err
let header_line ~version ?sort_order ?group_order () =
parse_header_version version >>| fun version ->
{version; sort_order; group_order}
let ref_seq
~name ~length
?assembly ?md5 ?species ?uri
()
=
let is_name_first_char_ok = function
| '!' .. ')' | '+' .. '<' | '>' .. '~' -> true
| _ -> false
in
let is_name_other_char_ok = function '!' .. '~' -> true | _ -> false in
(if (1 <= length) && (length <= 2147483647) then
Ok length
else
error "invalid reference sequence length" length sexp_of_int
) >>= fun length ->
(if (String.length name > 0)
&& (String.foldi name ~init:true ~f:(fun i accum c ->
accum && (
if i = 0 then is_name_first_char_ok c
else is_name_other_char_ok c
) ) )
then
Ok name
else
error "invalid ref seq name" name sexp_of_string
) >>= fun name ->
Ok {name; length; assembly; md5; species; uri}
let read_group
~id ?seq_center ?description ?run_date ?flow_order
?key_seq ?library ?program ?predicted_median_insert_size
?platform ?platform_unit ?sample
()
=
(match run_date with
| None -> Ok None
| Some run_date ->
try Ok (Some (`Date run_date))
with _ ->
try Ok (Some (`Time run_date))
with _ ->
error "invalid run date/time" run_date sexp_of_string
) >>= fun run_date ->
(match flow_order with
| None -> Ok None
| Some "" -> Or_error.error_string "invalid empty flow order"
| Some "*" -> Ok flow_order
| Some x ->
if String.for_all x ~f:(function
| 'A' | 'C' | 'M' | 'G' | 'R' | 'S' | 'V' | 'T' | 'W'| 'Y' | 'H'
| 'K' | 'D' | 'B' | 'N' -> true
| _ -> false
)
then
Ok flow_order
else
error "invalid flow order" x sexp_of_string
) >>| fun flow_order ->
{
id; seq_center; description; run_date; flow_order; key_seq;
library; program; predicted_median_insert_size;
platform; platform_unit; sample;
}
let header
?version ?sort_order ?group_order ?(ref_seqs=[]) ?(read_groups=[])
?(programs=[]) ?(comments=[]) ?(others=[])
()
=
[
(
match version with
| None -> None
| Some x -> match parse_header_version x with
| Error e -> Some e
| Ok _ -> None
);
(
if Option.is_some sort_order && Poly.(version = None) then
Some (Error.create
"sort order cannot be defined without version"
(sort_order, version)
[%sexp_of: sort_order option * string option ]
)
else
None
);
(
List.map ref_seqs ~f:(fun (x:ref_seq) -> x.name)
|> List.find_a_dup ~compare:String.compare
|> Option.map ~f:(fun name ->
Error.create "duplicate ref seq name" name sexp_of_string
)
);
]
|> List.filter_map ~f:Fn.id
|> function
| [] -> Ok {
version; sort_order; group_order; ref_seqs; read_groups;
programs; comments; others;
}
| errs -> Error (Error.of_list errs)
let parse_header_item_tag s =
let is_letter = function 'A' .. 'Z' | 'a' .. 'z' -> true | _ -> false in
match String.chop_prefix s ~prefix:"@" with
| None -> error "header item tag must begin with @" s sexp_of_string
| Some "HD" -> Ok `HD
| Some "SQ" -> Ok `SQ
| Some "RG" -> Ok `RG
| Some "PG" -> Ok `PG
| Some "CO" -> Ok `CO
| Some x ->
if (String.length x = 2)
&& (String.for_all x ~f:is_letter)
then
Ok (`Other x)
else
error "invalid header item tag" s sexp_of_string
let parse_tag_value s =
let parse_tag s =
if (String.length s = 2)
&& (match s.[0] with 'A' .. 'Z' | 'a' .. 'z' -> true | _ -> false)
&& (match s.[1] with
| 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' -> true
| _ -> false
)
then
Ok s
else
error "invalid tag" s sexp_of_string
in
let parse_value tag s =
if String.(s <> "")
&& (String.for_all s ~f:(function ' ' .. '~' -> true | _ -> false))
then
Ok s
else
error "tag has invalid value" (tag,s)
[%sexp_of: string * string ]
in
match String.lsplit2 s ~on:':' with
| None ->
error "tag-value not colon separated" s sexp_of_string
| Some (tag,value) ->
parse_tag tag >>= fun tag ->
parse_value tag value >>= fun value ->
Ok (tag, value)
(** Find all occurrences of [x'] in the association list [l]. *)
let find_all l x' =
let rec loop accum = function
| [] -> accum
| (x,y)::l ->
let accum = if Poly.(x = x') then y::accum else accum in
loop accum l
in
List.rev (loop [] l)
* Find exactly 1 occurrence [ x ] in association list [ l ] . Return
error if [ x ] is not defined exactly once .
error if [x] is not defined exactly once. *)
let find1 header_item_tag l x =
match find_all l x with
| [] ->
error "required tag not found" (header_item_tag, x)
[%sexp_of: header_item_tag * string ]
| y::[] -> Ok y
| ys ->
error "tag found multiple times" (header_item_tag, x, ys)
[%sexp_of: header_item_tag * string * string list ]
* Find 0 or 1 occurrence [ x ] in association list [ l ] . Return
error if [ x ] is defined more than once .
error if [x] is defined more than once. *)
let find01 header_item_tag l x =
match find_all l x with
| [] -> Ok None
| y::[] -> Ok (Some y)
| ys ->
error "tag found multiple times" (header_item_tag, x, ys)
[%sexp_of: header_item_tag * string * string list ]
(** Assert that [tvl] contains at most the given [tags]. *)
let assert_tags header_item_tag tvl tags =
let expected_tags = String.Set.of_list tags in
let got_tags = List.map tvl ~f:fst |> String.Set.of_list in
let unexpected_tags = Set.diff got_tags expected_tags in
if Set.length unexpected_tags = 0 then
Ok ()
else
error
"unexpected tag for given header item type"
(header_item_tag, unexpected_tags)
[%sexp_of: header_item_tag * String.Set.t ]
let parse_sort_order = function
| "unknown" -> Ok `Unknown
| "unsorted" -> Ok `Unsorted
| "queryname" -> Ok `Query_name
| "coordinate" -> Ok `Coordinate
| x -> error "invalid sort order" x sexp_of_string
let parse_group_order = function
| "none" -> Ok `None
| "query" -> Ok `Query
| "reference" -> Ok `Reference
| x -> error "invalid group order" x sexp_of_string
let parse_header_line tvl =
find1 `HD tvl "VN" >>= fun version ->
find01 `HD tvl "SO" >>?~
parse_sort_order >>= fun sort_order ->
find01 `HD tvl "GO" >>?~
parse_group_order >>= fun group_order ->
assert_tags `HD tvl ["VN"; "SO"; "GO"] >>= fun () ->
header_line ~version ?sort_order ?group_order ()
let parse_ref_seq tvl =
find1 `SQ tvl "SN" >>= fun name ->
find1 `SQ tvl "LN" >>= fun length ->
(try Ok (Int.of_string length)
with _ ->
error "invalid ref seq length" length sexp_of_string
) >>= fun length ->
find01 `SQ tvl "AS" >>= fun assembly ->
find01 `SQ tvl "M5" >>= fun md5 ->
find01 `SQ tvl "SP" >>= fun species ->
find01 `SQ tvl "UR" >>= fun uri ->
assert_tags `SQ tvl ["SN";"LN";"AS";"M5";"SP";"UR"] >>= fun () ->
ref_seq ~name ~length ?assembly ?md5 ?species ?uri ()
let parse_platform = function
| "CAPILLARY" -> Ok `Capillary
| "LS454" -> Ok `LS454
| "ILLUMINA" -> Ok `Illumina
| "SOLID" -> Ok `Solid
| "HELICOS" -> Ok `Helicos
| "IONTORRENT" -> Ok `Ion_Torrent
| "PACBIO" -> Ok `Pac_Bio
| x -> error "unknown platform" x sexp_of_string
let parse_read_group tvl =
find1 `RG tvl "ID" >>= fun id ->
find01 `RG tvl "CN" >>= fun seq_center ->
find01 `RG tvl "DS" >>= fun description ->
find01 `RG tvl "DT" >>= fun run_date ->
find01 `RG tvl "FO" >>= fun flow_order ->
find01 `RG tvl "KS" >>= fun key_seq ->
find01 `RG tvl "LB" >>= fun library ->
find01 `RG tvl "PG" >>= fun program ->
find01 `RG tvl "PI" >>?~ (fun predicted_median_insert_size ->
try Ok (Int.of_string predicted_median_insert_size)
with _ ->
error
"invalid predicted median insert size"
predicted_median_insert_size
sexp_of_string
) >>= fun predicted_median_insert_size ->
find01 `RG tvl "PL" >>?~
parse_platform >>= fun platform ->
find01 `RG tvl "PU" >>= fun platform_unit ->
find01 `RG tvl "SM" >>= fun sample ->
assert_tags `RG tvl
["ID";"CN";"DS";"DT";"FO";"KS";"LB";"PG";"PI";"PL";"PU";"SM"]
>>= fun () ->
read_group
~id ?seq_center ?description ?run_date ?flow_order ?key_seq
?library ?program ?predicted_median_insert_size
?platform ?platform_unit ?sample ()
let parse_program tvl =
find1 `PG tvl "ID" >>= fun id ->
find01 `PG tvl "PN" >>= fun name ->
find01 `PG tvl "CL" >>= fun command_line ->
find01 `PG tvl "PP" >>= fun previous_id ->
find01 `PG tvl "DS" >>= fun description ->
find01 `PG tvl "VN" >>= fun version ->
assert_tags `PG tvl ["ID";"PN";"CL";"PP";"DS";"VN"] >>| fun () ->
{id; name; command_line; previous_id; description; version}
let parse_header_item line =
let parse_data tag tvl = match tag with
| `HD -> parse_header_line tvl >>| fun x -> `HD x
| `SQ -> parse_ref_seq tvl >>| fun x -> `SQ x
| `RG -> parse_read_group tvl >>| fun x -> `RG x
| `PG -> parse_program tvl >>| fun x -> `PG x
| `Other tag -> Ok (`Other (tag,tvl))
| `CO -> assert false
in
match String.lsplit2 ~on:'\t' line with
| None ->
error "header line contains no tabs" line String.sexp_of_t
| Some (tag, data) ->
parse_header_item_tag tag >>= function
| `CO -> Ok (`CO data)
| tag ->
match String.split ~on:'\t' data with
| [] -> assert false
| ""::[] ->
error "header contains no data" tag sexp_of_header_item_tag
| tvl ->
List.map tvl ~f:parse_tag_value |> Result.all >>= fun tvl ->
parse_data tag tvl
let parse_header_gen src =
let open Let_syntax.Result in
let return ({version; sort_order; group_order; _} as x) maybe_al =
let ref_seqs = List.rev x.ref_seqs in
let read_groups = List.rev x.read_groups in
let programs = List.rev x.programs in
let comments = List.rev x.comments in
let others = List.rev x.others in
let+ header =
header
?version ?sort_order ?group_order ~ref_seqs ~read_groups
~programs ~comments ~others ()
in
header, maybe_al
in
let rec loop hdr =
match src () with
| None -> return hdr None
| Some line ->
if String.length line = 0 then
Or_error.error_string "invalid empty line"
else if Char.(line.[0] <> '@') then
return hdr (Some line)
else (
let* header_item = parse_header_item line in
match header_item with
| `HD ({version; sort_order; group_order} : header_line) -> (
match hdr.version with
| Some _ ->
Or_error.error_string "multiple @HD lines not allowed"
| None ->
loop {hdr with version = Some version; sort_order; group_order}
)
| `SQ x -> loop {hdr with ref_seqs = x::hdr.ref_seqs}
| `RG x -> loop {hdr with read_groups = x::hdr.read_groups}
| `PG x -> loop {hdr with programs = x::hdr.programs}
| `CO x -> loop {hdr with comments = x::hdr.comments}
| `Other x -> loop {hdr with others = x::hdr.others}
)
in
loop empty_header
let list_iterator xs =
let cursor = ref xs in
fun () ->
match !cursor with
| [] -> None
| h :: t -> cursor := t ; Some h
let parse_header buf =
let open Let_syntax.Result in
let lines = String.split_lines buf in
let src = list_iterator lines in
let+ header, _ = parse_header_gen src in
header
(******************************************************************************)
Alignment Parsers and Constructors
(******************************************************************************)
let alignment
?ref_seqs ?qname ~flags ?rname ?pos ?mapq ?(cigar=[])
?rnext ?pnext ?tlen ?seq ?(qual=[])
?(optional_fields=[])
()
=
[
(match ref_seqs, rname with
| (None,_) | (_,None) -> None
| Some ref_seqs, Some rname ->
if Set.mem ref_seqs rname then
None
else
Some (
Error.create
"RNAME not defined in any SQ line"
rname sexp_of_string
)
);
(match ref_seqs, rnext with
| (None,_) | (_,None) -> None
| Some _, Some `Equal_to_RNAME ->
error will already be detected in RNAME check above
| Some ref_seqs, Some (`Value rnext) ->
if Set.mem ref_seqs rnext then
None
else
Some (
Error.create
"RNEXT not defined in any SQ line"
rnext sexp_of_string
)
);
(match seq, qual with
| _, [] -> None
| None, _ ->
Some (Error.of_string "QUAL provided without SEQ")
| Some seq, _ ->
let s = String.length seq in
let q = List.length qual in
if s = q then
None
else
Some (Error.create
"SEQ and QUAL lengths differ"
(s, q) [%sexp_of: int * int ]
)
);
(
List.map optional_fields ~f:(fun x -> x.tag)
|> List.find_a_dup ~compare:String.compare
|> Option.map ~f:(fun dup ->
Error.create "TAG occurs more than once" dup sexp_of_string)
);
]
|> List.filter_map ~f:Fn.id
|> function
| [] -> Ok {
qname; flags; rname; pos; mapq; cigar;
rnext; pnext; tlen; seq; qual; optional_fields
}
| errs -> Error (Error.of_list errs)
let parse_int_range field lo hi s =
let out_of_range = sprintf "%s out of range" field in
let not_an_int = sprintf "%s not an int" field in
try
let n = Int.of_string s in
if (lo <= n) && (n <= hi) then
Ok n
else
error out_of_range (n,lo,hi) [%sexp_of: int * int * int ]
with _ ->
error not_an_int s sexp_of_string
* a string that can either by " * " or some other regexp , with
" * " denoting [ None ] . The given regexp [ re ] should include " * " as
one of the alternatives .
"*" denoting [None]. The given regexp [re] should include "*" as
one of the alternatives. *)
let parse_opt_string field re s =
if not (Re.execp re s) then
error (sprintf "invalid %s" field) s sexp_of_string
else
match s with
| "*" -> Ok None
| _ -> Ok (Some s)
let qname_re =
let open Re in
alt [
char '*';
repn (alt [rg '!' '?'; rg 'A' '~']) 1 (Some 255);
]
|> compile
let parse_qname s =
parse_opt_string "QNAME" qname_re s
let parse_flags s =
try Flags.of_int (Int.of_string s)
with _ ->
error "invalid FLAG" s sexp_of_string
let rname_re = Re.Perl.compile_pat "^\\*|[!-()+-<>-~][!-~]*$"
let parse_rname s =
parse_opt_string "RNAME" rname_re s
let parse_pos s =
parse_int_range "POS" 0 2147483647 s >>| function
| 0 -> None
| x -> Some x
let parse_mapq s =
parse_int_range "MAPQ" 0 255 s >>| function
| 255 -> None
| x -> Some x
let positive i =
let open Or_error in
if i > 0 then return i else error_string "positive argument expected for cigar operation"
let cigar_op_alignment_match i = Or_error.(positive i >>| fun i -> `Alignment_match i)
let cigar_op_insertion i = Or_error.(positive i >>| fun i -> `Insertion i)
let cigar_op_deletion i = Or_error.(positive i >>| fun i -> `Deletion i)
let cigar_op_skipped i = Or_error.(positive i >>| fun i -> `Skipped i)
let cigar_op_soft_clipping i = Or_error.(positive i >>| fun i -> `Soft_clipping i)
let cigar_op_hard_clipping i = Or_error.(positive i >>| fun i -> `Hard_clipping i)
let cigar_op_padding i = Or_error.(positive i >>| fun i -> `Padding i)
let cigar_op_seq_match i = Or_error.(positive i >>| fun i -> `Seq_match i)
let cigar_op_seq_mismatch i = Or_error.(positive i >>| fun i -> `Seq_mismatch i)
let parse_cigar text =
match text with
| "*" -> Ok []
| "" ->
error "invalid cigar string" text sexp_of_string
| _ ->
let ch = Scanf.Scanning.from_string text in
let rec loop accum =
if Scanf.Scanning.end_of_input ch then Ok accum
else
try
let n = Scanf.bscanf ch "%d" Fun.id in
let c = Scanf.bscanf ch "%c" Fun.id in
let x =
match c with
| 'M' -> cigar_op_alignment_match n
| 'I' -> cigar_op_insertion n
| 'D' -> cigar_op_deletion n
| 'N' -> cigar_op_skipped n
| 'S' -> cigar_op_soft_clipping n
| 'H' -> cigar_op_hard_clipping n
| 'P' -> cigar_op_padding n
| '=' -> cigar_op_seq_match n
| 'X' -> cigar_op_seq_mismatch n
| other -> Or_error.error "invalid cigar operation type" other Char.sexp_of_t
in
Or_error.tag x ~tag:"Sam.parse_cigar: invalid cigar string" >>= fun x ->
loop (x::accum)
with
_ ->
error "invalid cigar string" text sexp_of_string
in
loop [] >>| List.rev
let rnext_re = Re.Perl.compile_pat "^\\*|=|[!-()+-<>-~][!-~]*$"
let parse_rnext s =
if not (Re.execp rnext_re s) then
error "invalid RNEXT" s sexp_of_string
else
match s with
| "*" -> Ok None
| "=" -> Ok (Some `Equal_to_RNAME)
| _ -> Ok (Some (`Value s))
let parse_pnext s =
parse_int_range "PNEXT" 0 2147483647 s >>| function
| 0 -> None
| x -> Some x
let parse_tlen s =
parse_int_range "TLEN" ~-2147483647 2147483647 s >>| function
| 0 -> None
| x -> Some x
let seq_re = Re.Perl.compile_pat "^\\*|[A-Za-z=.]+$"
let parse_seq s =
parse_opt_string "SEQ" seq_re s
let parse_qual s =
match s with
| "" -> Or_error.error_string "invalid empty QUAL"
| "*" -> Ok []
| _ ->
String.to_list s
|> List.map ~f:(Phred_score.of_char ~offset:`Offset33)
|> Result.all
let opt_field_tag_re = Re.Perl.compile_pat "^[A-Za-z][A-Za-z0-9]$"
let opt_field_Z_re = Re.Perl.compile_pat "^[ !-~]+$"
let opt_field_H_re = Re.Perl.compile_pat "^[0-9A-F]+$"
let opt_field_int_re = Re.Perl.compile_pat "^-?[0-9]+$"
let opt_field_float_re = Re.Perl.compile_pat "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$"
let optional_field_value_err typ value =
error "invalid value" (typ,value) [%sexp_of: string * string ]
let optional_field_value_A value =
if List.mem ~equal:Char.equal ['!';'-';'~'] value
then optional_field_value_err "A" (Char.to_string value)
else Ok (`A value)
let optional_field_value_i i = `i i
let optional_field_value_f f = `f f
let optional_field_value_Z value =
if Re.execp opt_field_Z_re value then Ok (`Z value)
else optional_field_value_err "Z" value
let optional_field_value_H value =
if Re.execp opt_field_H_re value then Ok (`H value)
else optional_field_value_err "H" value
let optional_field_value_B elt_type elts =
let valid_args =
match elt_type with
| 'c' | 'C' | 's' | 'S' | 'i' | 'I' ->
List.for_all elts ~f:(Re.execp opt_field_int_re)
| 'f' ->
List.for_all elts ~f:(Re.execp opt_field_float_re)
| _ -> false
in
if valid_args then Ok (`B (elt_type, elts))
else error "invalid value" ("B", elt_type, elts) [%sexp_of: string * char * string list ]
let optional_field tag value =
if not (Re.execp opt_field_tag_re tag)
then error "invalid TAG" tag sexp_of_string
else Ok {tag; value}
let parse_optional_field_value s =
match String.lsplit2 s ~on:':' with
| None ->
error "missing TYPE in optional field" s sexp_of_string
| Some (typ,value) ->
match typ with
| "A" ->
if String.length value = 1 then optional_field_value_A value.[0]
else optional_field_value_err typ value
| "i" ->
(try
if not (Re.execp opt_field_int_re value) then failwith "" ;
matching the regular expression is not enough : the number could not fit in 64 bits
with _ -> optional_field_value_err typ value)
| "f" ->
(try
if not (Re.execp opt_field_float_re value) then failwith "" ;
Ok (optional_field_value_f (Float.of_string value)) (* matching the regular expression is not enough: the number could not fit in native floats *)
with _ -> optional_field_value_err typ value)
| "Z" -> optional_field_value_Z value
| "H" -> optional_field_value_H value
| "B" -> (
match String.split ~on:',' value with
| num_typ :: values ->
if String.length num_typ = 1 then
optional_field_value_B num_typ.[0] values
else
error "invalid array type" num_typ sexp_of_string
| _ -> assert false (* [String.split] cannot return an empty list *)
)
| _ -> error "invalid type" typ sexp_of_string
let parse_optional_field s =
match String.lsplit2 s ~on:':' with
| None ->
error "missing TAG in optional field" s sexp_of_string
| Some (tag,s) ->
parse_optional_field_value s >>= fun value ->
optional_field tag value
let parse_alignment ?ref_seqs line =
match String.split ~on:'\t' line with
| qname::flags::rname::pos::mapq::cigar::rnext
::pnext::tlen::seq::qual::optional_fields
-> (
parse_qname qname >>= fun qname ->
parse_flags flags >>= fun flags ->
parse_rname rname >>= fun rname ->
parse_pos pos >>= fun pos ->
parse_mapq mapq >>= fun mapq ->
parse_cigar cigar >>= fun cigar ->
parse_rnext rnext >>= fun rnext ->
parse_pnext pnext >>= fun pnext ->
parse_tlen tlen >>= fun tlen ->
parse_seq seq >>= fun seq ->
parse_qual qual >>= fun qual ->
List.map optional_fields ~f:parse_optional_field
|> Result.all
>>= fun optional_fields ->
alignment
?ref_seqs ?qname ~flags ?rname ?pos ?mapq ~cigar
?rnext ?pnext ?tlen ?seq ~qual ~optional_fields
()
)
| _ ->
Or_error.error_string "alignment line contains < 12 fields"
(******************************************************************************)
(* Header Printers *)
(******************************************************************************)
let print_header_item_tag = function
| `HD -> "@HD"
| `SQ -> "@SQ"
| `RG -> "@RG"
| `PG -> "@PG"
| `CO -> "@CO"
| `Other x -> sprintf "@%s" x
let print_tag_value (tag,value) = sprintf "%s:%s" tag value
let print_tag_value' = sprintf "%s:%s"
let print_header_version x = print_tag_value' "VN" x
let print_sort_order x =
print_tag_value' "SO"
(match x with
| `Unknown -> "unknown"
| `Unsorted -> "unsorted"
| `Query_name -> "queryname"
| `Coordinate -> "coordinate"
)
let print_group_order x =
print_tag_value' "GO"
(match x with
| `None -> "none"
| `Query -> "query"
| `Reference -> "reference"
)
let print_header_line ({version; sort_order; group_order} : header_line) =
sprintf "@HD\tVN:%s%s%s"
version
(match sort_order with
| None -> ""
| Some x -> sprintf "\t%s" (print_sort_order x)
)
(match group_order with
| None -> ""
| Some x -> sprintf "\t%s" (print_group_order x)
)
let print_ref_seq (x:ref_seq) =
sprintf "@SQ\tSN:%s\tLN:%d%s%s%s%s"
x.name
x.length
(match x.assembly with None -> "" | Some x -> sprintf "\tAS:%s" x)
(match x.md5 with None -> "" | Some x -> sprintf "\tM5:%s" x)
(match x.species with None -> "" | Some x -> sprintf "\tSP:%s" x)
(match x.uri with None -> "" | Some x -> sprintf "\tUR:%s" x)
let print_platform = function
| `Capillary -> "CAPILLARY"
| `LS454 -> "LS454"
| `Illumina -> "ILLUMINA"
| `Solid -> "SOLID"
| `Helicos -> "HELICOS"
| `Ion_Torrent -> "IONTORRENT"
| `Pac_Bio -> "PACBIO"
let print_read_group (x:read_group) =
let s tag value = match value with
| None -> ""
| Some x -> sprintf "\t%s:%s" tag x
in
sprintf "@RG\tID:%s%s%s%s%s%s%s%s%s%s%s%s"
x.id
(s "CN" x.seq_center)
(s "DS" x.description)
(s "DT" (Option.map x.run_date
~f:(function
| `Date x
| `Time x -> x) )
)
(s "FO" x.flow_order)
(s "KS" x.key_seq)
(s "LB" x.library)
(s "PG" x.program)
(s "PI" (Option.map x.predicted_median_insert_size ~f:Int.to_string))
(s "PL" (Option.map x.platform ~f:print_platform))
(s "PU" x.platform_unit)
(s "SM" x.sample)
let print_program (x:program) =
let s tag value = match value with
| None -> ""
| Some x -> sprintf "\t%s:%s" tag x
in
sprintf "@PG\tID:%s%s%s%s%s%s"
x.id
(s "PN" x.name)
(s "CL" x.command_line)
(s "PP" x.previous_id)
(s "DS" x.description)
(s "VN" x.version)
let print_other ((tag,l) : string * tag_value list) =
sprintf "@%s%s"
tag
(
List.map l ~f:(fun (x,y) -> sprintf "\t%s:%s" x y)
|> String.concat ~sep:""
)
(******************************************************************************)
(* Alignment Printers *)
(******************************************************************************)
let print_qname = function Some x -> x | None -> "*"
let print_flags = Int.to_string
let print_rname = function Some x -> x | None -> "*"
let print_pos = function Some x -> Int.to_string x | None -> "0"
let print_mapq = function Some x -> Int.to_string x | None -> "255"
let print_cigar_op = function
| `Alignment_match x -> sprintf "%dM" x
| `Insertion x -> sprintf "%dI" x
| `Deletion x -> sprintf "%dD" x
| `Skipped x -> sprintf "%dN" x
| `Soft_clipping x -> sprintf "%dS" x
| `Hard_clipping x -> sprintf "%dH" x
| `Padding x -> sprintf "%dP" x
| `Seq_match x -> sprintf "%d=" x
| `Seq_mismatch x -> sprintf "%dX" x
let print_cigar = function
| [] -> "*"
| cigar_ops ->
List.map cigar_ops ~f:print_cigar_op
|> String.concat ~sep:""
let print_rnext = function
| None -> "*"
| Some `Equal_to_RNAME -> "="
| Some (`Value x) -> x
let print_pnext = function Some x -> Int.to_string x | None -> "0"
let print_tlen = function Some x -> Int.to_string x | None -> "0"
let print_seq = function Some x -> x | None -> "*"
let print_qual = function
| [] -> "*"
| quals ->
List.map quals ~f:(fun x ->
ok_exn (Phred_score.to_char ~offset:`Offset33 x)
)
|> String.of_char_list
let print_optional_field (x:optional_field) =
let typ,value = match x.value with
| `A x -> 'A', Char.to_string x
| `i x -> 'i', Int64.to_string x
| `f x -> 'f', Float.to_string x
| `Z x -> 'Z', x
| `H x -> 'H', x
| `B (c,l) -> 'B', (String.concat ~sep:"," ((String.of_char c)::l))
in
sprintf "%s:%c:%s" x.tag typ value
let print_alignment a =
sprintf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s"
(print_qname a.qname)
(print_flags a.flags)
(print_rname a.rname)
(print_pos a.pos)
(print_mapq a.mapq)
(print_cigar a.cigar)
(print_rnext a.rnext)
(print_pnext a.pnext)
(print_tlen a.tlen)
(print_seq a.seq)
(print_qual a.qual)
(
List.map a.optional_fields ~f:print_optional_field
|> String.concat ~sep:"\t"
)
let read_header ic =
parse_header_gen (fun () -> In_channel.input_line ic)
let write_header oc (h : header) =
Option.iter h.version ~f:(fun version ->
Out_channel.output_string oc (print_header_line {version; sort_order=h.sort_order; group_order=h.group_order}) ;
Out_channel.output_char oc '\n'
) ;
List.iter h.ref_seqs ~f:(fun x ->
Out_channel.output_string oc (print_ref_seq x) ;
Out_channel.output_char oc '\n'
) ;
List.iter h.read_groups ~f:(fun x ->
Out_channel.output_string oc (print_read_group x) ;
Out_channel.output_char oc '\n'
) ;
List.iter h.programs ~f:(fun x ->
Out_channel.output_string oc (print_program x) ;
Out_channel.output_char oc '\n'
) ;
List.iter h.comments ~f:(fun x ->
Out_channel.output_string oc "@CO\t" ;
Out_channel.output_string oc x ;
Out_channel.output_char oc '\n'
) ;
List.iter h.others ~f:(fun x ->
Out_channel.output_string oc (print_other x) ;
Out_channel.output_char oc '\n'
)
let write_alignment oc a =
Out_channel.output_string oc (print_alignment a) ;
Out_channel.output_char oc '\n'
let write_file ?perm ?append file ?header alignments =
Out_channel.with_file ?perm ?append file ~f:(fun oc ->
Option.iter header ~f:(write_header oc) ;
Seq.iter (write_alignment oc) alignments
)
let fold fn ~init ~f =
let open Let_syntax.Result in
In_channel.with_file fn ~f:(fun ic ->
let* (header, maybe_next_line) = read_header ic in
let* init = init header in
match maybe_next_line with
| None -> Ok init
| Some line ->
let rec loop acc =
match In_channel.input_line ic with
| None -> Ok acc
| Some line -> process_line acc line
and process_line acc line =
let* alignment = parse_alignment line in
let* acc' = f acc alignment in
loop acc'
in
process_line init line
)
| null | https://raw.githubusercontent.com/pveber/biotk/422640d9303c90c43ecb4b679a8bf5867998119c/lib/sam.ml | ocaml | ****************************************************************************
Header Types
****************************************************************************
****************************************************************************
Alignment Types
****************************************************************************
****************************************************************************
****************************************************************************
* Find all occurrences of [x'] in the association list [l].
* Assert that [tvl] contains at most the given [tags].
****************************************************************************
****************************************************************************
matching the regular expression is not enough: the number could not fit in native floats
[String.split] cannot return an empty list
****************************************************************************
Header Printers
****************************************************************************
****************************************************************************
Alignment Printers
**************************************************************************** | open Core
module Seq = Caml.Seq
open Result.Monad_infix
let ( >>?~ )
(x : 'a option Or_error.t)
(f : 'a -> 'b Or_error.t)
: 'b option Or_error.t
=
let open Result.Monad_infix in
x >>= function
| None -> Ok None
| Some x -> f x >>| Option.some
type header_item_tag = [
| `HD | `SQ | `RG | `PG | `CO
| `Other of string
] [@@deriving sexp]
type tag_value = string * string
[@@deriving sexp]
type sort_order = [ `Unknown | `Unsorted | `Query_name | `Coordinate ]
[@@deriving sexp]
type group_order = [ `None | `Query | `Reference ]
[@@deriving sexp]
type header_line = {
version : string;
sort_order : sort_order option;
group_order: group_order option;
} [@@deriving sexp]
type ref_seq = {
name : string;
length : int;
assembly : string option;
md5 : string option;
species : string option;
uri : string option;
} [@@deriving sexp]
type platform = [
| `Capillary | `LS454 | `Illumina | `Solid
| `Helicos | `Ion_Torrent | `Pac_Bio
] [@@deriving sexp]
type read_group = {
id : string;
seq_center : string option;
description : string option;
run_date : [`Date of string | `Time of string] option;
flow_order : string option;
key_seq : string option;
library : string option;
program : string option;
predicted_median_insert_size : int option;
platform : platform option;
platform_unit : string option;
sample : string option;
} [@@deriving sexp]
type program = {
id : string;
name : string option;
command_line : string option;
previous_id : string option;
description : string option;
version : string option;
} [@@deriving sexp]
type header_item = [
| `HD of header_line
| `SQ of ref_seq
| `RG of read_group
| `PG of program
| `CO of string
| `Other of string * tag_value list
] [@@deriving sexp]
type header = {
version : string option;
sort_order : sort_order option;
group_order : group_order option;
ref_seqs : ref_seq list;
read_groups : read_group list;
programs : program list;
comments : string list;
others : (string * tag_value list) list;
}
let empty_header = {
version = None;
sort_order = None;
group_order = None;
ref_seqs = [];
read_groups = [];
programs = [];
comments = [];
others = [];
}
module Flags = struct
type t = int
[@@deriving sexp]
let of_int x =
if (0 <= x) && (x <= 65535) then
Ok x
else
error "flag out of range" x sexp_of_int
let flag_is_set s f = (f land s) <> 0
let has_multiple_segments = flag_is_set 0x1
let each_segment_properly_aligned = flag_is_set 0x2
let segment_unmapped = flag_is_set 0x4
let next_segment_unmapped = flag_is_set 0x8
let seq_is_reverse_complemented = flag_is_set 0x10
let next_seq_is_reverse_complemented = flag_is_set 0x20
let first_segment = flag_is_set 0x40
let last_segment = flag_is_set 0x80
let secondary_alignment = flag_is_set 0x100
let not_passing_quality_controls = flag_is_set 0x200
let pcr_or_optical_duplicate = flag_is_set 0x400
let supplementary_alignment = flag_is_set 0x800
end
type cigar_op = [
| `Alignment_match of int
| `Insertion of int
| `Deletion of int
| `Skipped of int
| `Soft_clipping of int
| `Hard_clipping of int
| `Padding of int
| `Seq_match of int
| `Seq_mismatch of int
] [@@deriving sexp]
type optional_field_value = [
| `A of char
| `i of Int64.t
| `f of float
| `Z of string
| `H of string
| `B of char * string list
] [@@deriving sexp]
type optional_field = {
tag : string;
value : optional_field_value
} [@@deriving sexp]
type rnext = [`Value of string | `Equal_to_RNAME]
[@@deriving sexp]
type alignment = {
qname : string option;
flags : Flags.t;
rname : string option;
pos : int option;
mapq : int option;
cigar : cigar_op list;
rnext : rnext option;
pnext : int option;
tlen : int option;
seq: string option;
qual: Phred_score.t list;
optional_fields : optional_field list;
} [@@deriving sexp]
Header Parsers and Constructors
let parse_header_version s =
let err =
error "invalid version" (`HD, s)
[%sexp_of: header_item_tag * string ]
in
match String.lsplit2 ~on:'.' s with
| None -> err
| Some (a,b) ->
if (String.for_all a ~f:Char.is_digit)
&& (String.for_all b ~f:Char.is_digit)
then
Ok s
else
err
let header_line ~version ?sort_order ?group_order () =
parse_header_version version >>| fun version ->
{version; sort_order; group_order}
let ref_seq
~name ~length
?assembly ?md5 ?species ?uri
()
=
let is_name_first_char_ok = function
| '!' .. ')' | '+' .. '<' | '>' .. '~' -> true
| _ -> false
in
let is_name_other_char_ok = function '!' .. '~' -> true | _ -> false in
(if (1 <= length) && (length <= 2147483647) then
Ok length
else
error "invalid reference sequence length" length sexp_of_int
) >>= fun length ->
(if (String.length name > 0)
&& (String.foldi name ~init:true ~f:(fun i accum c ->
accum && (
if i = 0 then is_name_first_char_ok c
else is_name_other_char_ok c
) ) )
then
Ok name
else
error "invalid ref seq name" name sexp_of_string
) >>= fun name ->
Ok {name; length; assembly; md5; species; uri}
let read_group
~id ?seq_center ?description ?run_date ?flow_order
?key_seq ?library ?program ?predicted_median_insert_size
?platform ?platform_unit ?sample
()
=
(match run_date with
| None -> Ok None
| Some run_date ->
try Ok (Some (`Date run_date))
with _ ->
try Ok (Some (`Time run_date))
with _ ->
error "invalid run date/time" run_date sexp_of_string
) >>= fun run_date ->
(match flow_order with
| None -> Ok None
| Some "" -> Or_error.error_string "invalid empty flow order"
| Some "*" -> Ok flow_order
| Some x ->
if String.for_all x ~f:(function
| 'A' | 'C' | 'M' | 'G' | 'R' | 'S' | 'V' | 'T' | 'W'| 'Y' | 'H'
| 'K' | 'D' | 'B' | 'N' -> true
| _ -> false
)
then
Ok flow_order
else
error "invalid flow order" x sexp_of_string
) >>| fun flow_order ->
{
id; seq_center; description; run_date; flow_order; key_seq;
library; program; predicted_median_insert_size;
platform; platform_unit; sample;
}
let header
?version ?sort_order ?group_order ?(ref_seqs=[]) ?(read_groups=[])
?(programs=[]) ?(comments=[]) ?(others=[])
()
=
[
(
match version with
| None -> None
| Some x -> match parse_header_version x with
| Error e -> Some e
| Ok _ -> None
);
(
if Option.is_some sort_order && Poly.(version = None) then
Some (Error.create
"sort order cannot be defined without version"
(sort_order, version)
[%sexp_of: sort_order option * string option ]
)
else
None
);
(
List.map ref_seqs ~f:(fun (x:ref_seq) -> x.name)
|> List.find_a_dup ~compare:String.compare
|> Option.map ~f:(fun name ->
Error.create "duplicate ref seq name" name sexp_of_string
)
);
]
|> List.filter_map ~f:Fn.id
|> function
| [] -> Ok {
version; sort_order; group_order; ref_seqs; read_groups;
programs; comments; others;
}
| errs -> Error (Error.of_list errs)
let parse_header_item_tag s =
let is_letter = function 'A' .. 'Z' | 'a' .. 'z' -> true | _ -> false in
match String.chop_prefix s ~prefix:"@" with
| None -> error "header item tag must begin with @" s sexp_of_string
| Some "HD" -> Ok `HD
| Some "SQ" -> Ok `SQ
| Some "RG" -> Ok `RG
| Some "PG" -> Ok `PG
| Some "CO" -> Ok `CO
| Some x ->
if (String.length x = 2)
&& (String.for_all x ~f:is_letter)
then
Ok (`Other x)
else
error "invalid header item tag" s sexp_of_string
let parse_tag_value s =
let parse_tag s =
if (String.length s = 2)
&& (match s.[0] with 'A' .. 'Z' | 'a' .. 'z' -> true | _ -> false)
&& (match s.[1] with
| 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' -> true
| _ -> false
)
then
Ok s
else
error "invalid tag" s sexp_of_string
in
let parse_value tag s =
if String.(s <> "")
&& (String.for_all s ~f:(function ' ' .. '~' -> true | _ -> false))
then
Ok s
else
error "tag has invalid value" (tag,s)
[%sexp_of: string * string ]
in
match String.lsplit2 s ~on:':' with
| None ->
error "tag-value not colon separated" s sexp_of_string
| Some (tag,value) ->
parse_tag tag >>= fun tag ->
parse_value tag value >>= fun value ->
Ok (tag, value)
let find_all l x' =
let rec loop accum = function
| [] -> accum
| (x,y)::l ->
let accum = if Poly.(x = x') then y::accum else accum in
loop accum l
in
List.rev (loop [] l)
* Find exactly 1 occurrence [ x ] in association list [ l ] . Return
error if [ x ] is not defined exactly once .
error if [x] is not defined exactly once. *)
let find1 header_item_tag l x =
match find_all l x with
| [] ->
error "required tag not found" (header_item_tag, x)
[%sexp_of: header_item_tag * string ]
| y::[] -> Ok y
| ys ->
error "tag found multiple times" (header_item_tag, x, ys)
[%sexp_of: header_item_tag * string * string list ]
* Find 0 or 1 occurrence [ x ] in association list [ l ] . Return
error if [ x ] is defined more than once .
error if [x] is defined more than once. *)
let find01 header_item_tag l x =
match find_all l x with
| [] -> Ok None
| y::[] -> Ok (Some y)
| ys ->
error "tag found multiple times" (header_item_tag, x, ys)
[%sexp_of: header_item_tag * string * string list ]
let assert_tags header_item_tag tvl tags =
let expected_tags = String.Set.of_list tags in
let got_tags = List.map tvl ~f:fst |> String.Set.of_list in
let unexpected_tags = Set.diff got_tags expected_tags in
if Set.length unexpected_tags = 0 then
Ok ()
else
error
"unexpected tag for given header item type"
(header_item_tag, unexpected_tags)
[%sexp_of: header_item_tag * String.Set.t ]
let parse_sort_order = function
| "unknown" -> Ok `Unknown
| "unsorted" -> Ok `Unsorted
| "queryname" -> Ok `Query_name
| "coordinate" -> Ok `Coordinate
| x -> error "invalid sort order" x sexp_of_string
let parse_group_order = function
| "none" -> Ok `None
| "query" -> Ok `Query
| "reference" -> Ok `Reference
| x -> error "invalid group order" x sexp_of_string
let parse_header_line tvl =
find1 `HD tvl "VN" >>= fun version ->
find01 `HD tvl "SO" >>?~
parse_sort_order >>= fun sort_order ->
find01 `HD tvl "GO" >>?~
parse_group_order >>= fun group_order ->
assert_tags `HD tvl ["VN"; "SO"; "GO"] >>= fun () ->
header_line ~version ?sort_order ?group_order ()
let parse_ref_seq tvl =
find1 `SQ tvl "SN" >>= fun name ->
find1 `SQ tvl "LN" >>= fun length ->
(try Ok (Int.of_string length)
with _ ->
error "invalid ref seq length" length sexp_of_string
) >>= fun length ->
find01 `SQ tvl "AS" >>= fun assembly ->
find01 `SQ tvl "M5" >>= fun md5 ->
find01 `SQ tvl "SP" >>= fun species ->
find01 `SQ tvl "UR" >>= fun uri ->
assert_tags `SQ tvl ["SN";"LN";"AS";"M5";"SP";"UR"] >>= fun () ->
ref_seq ~name ~length ?assembly ?md5 ?species ?uri ()
let parse_platform = function
| "CAPILLARY" -> Ok `Capillary
| "LS454" -> Ok `LS454
| "ILLUMINA" -> Ok `Illumina
| "SOLID" -> Ok `Solid
| "HELICOS" -> Ok `Helicos
| "IONTORRENT" -> Ok `Ion_Torrent
| "PACBIO" -> Ok `Pac_Bio
| x -> error "unknown platform" x sexp_of_string
let parse_read_group tvl =
find1 `RG tvl "ID" >>= fun id ->
find01 `RG tvl "CN" >>= fun seq_center ->
find01 `RG tvl "DS" >>= fun description ->
find01 `RG tvl "DT" >>= fun run_date ->
find01 `RG tvl "FO" >>= fun flow_order ->
find01 `RG tvl "KS" >>= fun key_seq ->
find01 `RG tvl "LB" >>= fun library ->
find01 `RG tvl "PG" >>= fun program ->
find01 `RG tvl "PI" >>?~ (fun predicted_median_insert_size ->
try Ok (Int.of_string predicted_median_insert_size)
with _ ->
error
"invalid predicted median insert size"
predicted_median_insert_size
sexp_of_string
) >>= fun predicted_median_insert_size ->
find01 `RG tvl "PL" >>?~
parse_platform >>= fun platform ->
find01 `RG tvl "PU" >>= fun platform_unit ->
find01 `RG tvl "SM" >>= fun sample ->
assert_tags `RG tvl
["ID";"CN";"DS";"DT";"FO";"KS";"LB";"PG";"PI";"PL";"PU";"SM"]
>>= fun () ->
read_group
~id ?seq_center ?description ?run_date ?flow_order ?key_seq
?library ?program ?predicted_median_insert_size
?platform ?platform_unit ?sample ()
let parse_program tvl =
find1 `PG tvl "ID" >>= fun id ->
find01 `PG tvl "PN" >>= fun name ->
find01 `PG tvl "CL" >>= fun command_line ->
find01 `PG tvl "PP" >>= fun previous_id ->
find01 `PG tvl "DS" >>= fun description ->
find01 `PG tvl "VN" >>= fun version ->
assert_tags `PG tvl ["ID";"PN";"CL";"PP";"DS";"VN"] >>| fun () ->
{id; name; command_line; previous_id; description; version}
let parse_header_item line =
let parse_data tag tvl = match tag with
| `HD -> parse_header_line tvl >>| fun x -> `HD x
| `SQ -> parse_ref_seq tvl >>| fun x -> `SQ x
| `RG -> parse_read_group tvl >>| fun x -> `RG x
| `PG -> parse_program tvl >>| fun x -> `PG x
| `Other tag -> Ok (`Other (tag,tvl))
| `CO -> assert false
in
match String.lsplit2 ~on:'\t' line with
| None ->
error "header line contains no tabs" line String.sexp_of_t
| Some (tag, data) ->
parse_header_item_tag tag >>= function
| `CO -> Ok (`CO data)
| tag ->
match String.split ~on:'\t' data with
| [] -> assert false
| ""::[] ->
error "header contains no data" tag sexp_of_header_item_tag
| tvl ->
List.map tvl ~f:parse_tag_value |> Result.all >>= fun tvl ->
parse_data tag tvl
let parse_header_gen src =
let open Let_syntax.Result in
let return ({version; sort_order; group_order; _} as x) maybe_al =
let ref_seqs = List.rev x.ref_seqs in
let read_groups = List.rev x.read_groups in
let programs = List.rev x.programs in
let comments = List.rev x.comments in
let others = List.rev x.others in
let+ header =
header
?version ?sort_order ?group_order ~ref_seqs ~read_groups
~programs ~comments ~others ()
in
header, maybe_al
in
let rec loop hdr =
match src () with
| None -> return hdr None
| Some line ->
if String.length line = 0 then
Or_error.error_string "invalid empty line"
else if Char.(line.[0] <> '@') then
return hdr (Some line)
else (
let* header_item = parse_header_item line in
match header_item with
| `HD ({version; sort_order; group_order} : header_line) -> (
match hdr.version with
| Some _ ->
Or_error.error_string "multiple @HD lines not allowed"
| None ->
loop {hdr with version = Some version; sort_order; group_order}
)
| `SQ x -> loop {hdr with ref_seqs = x::hdr.ref_seqs}
| `RG x -> loop {hdr with read_groups = x::hdr.read_groups}
| `PG x -> loop {hdr with programs = x::hdr.programs}
| `CO x -> loop {hdr with comments = x::hdr.comments}
| `Other x -> loop {hdr with others = x::hdr.others}
)
in
loop empty_header
let list_iterator xs =
let cursor = ref xs in
fun () ->
match !cursor with
| [] -> None
| h :: t -> cursor := t ; Some h
let parse_header buf =
let open Let_syntax.Result in
let lines = String.split_lines buf in
let src = list_iterator lines in
let+ header, _ = parse_header_gen src in
header
Alignment Parsers and Constructors
let alignment
?ref_seqs ?qname ~flags ?rname ?pos ?mapq ?(cigar=[])
?rnext ?pnext ?tlen ?seq ?(qual=[])
?(optional_fields=[])
()
=
[
(match ref_seqs, rname with
| (None,_) | (_,None) -> None
| Some ref_seqs, Some rname ->
if Set.mem ref_seqs rname then
None
else
Some (
Error.create
"RNAME not defined in any SQ line"
rname sexp_of_string
)
);
(match ref_seqs, rnext with
| (None,_) | (_,None) -> None
| Some _, Some `Equal_to_RNAME ->
error will already be detected in RNAME check above
| Some ref_seqs, Some (`Value rnext) ->
if Set.mem ref_seqs rnext then
None
else
Some (
Error.create
"RNEXT not defined in any SQ line"
rnext sexp_of_string
)
);
(match seq, qual with
| _, [] -> None
| None, _ ->
Some (Error.of_string "QUAL provided without SEQ")
| Some seq, _ ->
let s = String.length seq in
let q = List.length qual in
if s = q then
None
else
Some (Error.create
"SEQ and QUAL lengths differ"
(s, q) [%sexp_of: int * int ]
)
);
(
List.map optional_fields ~f:(fun x -> x.tag)
|> List.find_a_dup ~compare:String.compare
|> Option.map ~f:(fun dup ->
Error.create "TAG occurs more than once" dup sexp_of_string)
);
]
|> List.filter_map ~f:Fn.id
|> function
| [] -> Ok {
qname; flags; rname; pos; mapq; cigar;
rnext; pnext; tlen; seq; qual; optional_fields
}
| errs -> Error (Error.of_list errs)
let parse_int_range field lo hi s =
let out_of_range = sprintf "%s out of range" field in
let not_an_int = sprintf "%s not an int" field in
try
let n = Int.of_string s in
if (lo <= n) && (n <= hi) then
Ok n
else
error out_of_range (n,lo,hi) [%sexp_of: int * int * int ]
with _ ->
error not_an_int s sexp_of_string
* a string that can either by " * " or some other regexp , with
" * " denoting [ None ] . The given regexp [ re ] should include " * " as
one of the alternatives .
"*" denoting [None]. The given regexp [re] should include "*" as
one of the alternatives. *)
let parse_opt_string field re s =
if not (Re.execp re s) then
error (sprintf "invalid %s" field) s sexp_of_string
else
match s with
| "*" -> Ok None
| _ -> Ok (Some s)
let qname_re =
let open Re in
alt [
char '*';
repn (alt [rg '!' '?'; rg 'A' '~']) 1 (Some 255);
]
|> compile
let parse_qname s =
parse_opt_string "QNAME" qname_re s
let parse_flags s =
try Flags.of_int (Int.of_string s)
with _ ->
error "invalid FLAG" s sexp_of_string
let rname_re = Re.Perl.compile_pat "^\\*|[!-()+-<>-~][!-~]*$"
let parse_rname s =
parse_opt_string "RNAME" rname_re s
let parse_pos s =
parse_int_range "POS" 0 2147483647 s >>| function
| 0 -> None
| x -> Some x
let parse_mapq s =
parse_int_range "MAPQ" 0 255 s >>| function
| 255 -> None
| x -> Some x
let positive i =
let open Or_error in
if i > 0 then return i else error_string "positive argument expected for cigar operation"
let cigar_op_alignment_match i = Or_error.(positive i >>| fun i -> `Alignment_match i)
let cigar_op_insertion i = Or_error.(positive i >>| fun i -> `Insertion i)
let cigar_op_deletion i = Or_error.(positive i >>| fun i -> `Deletion i)
let cigar_op_skipped i = Or_error.(positive i >>| fun i -> `Skipped i)
let cigar_op_soft_clipping i = Or_error.(positive i >>| fun i -> `Soft_clipping i)
let cigar_op_hard_clipping i = Or_error.(positive i >>| fun i -> `Hard_clipping i)
let cigar_op_padding i = Or_error.(positive i >>| fun i -> `Padding i)
let cigar_op_seq_match i = Or_error.(positive i >>| fun i -> `Seq_match i)
let cigar_op_seq_mismatch i = Or_error.(positive i >>| fun i -> `Seq_mismatch i)
let parse_cigar text =
match text with
| "*" -> Ok []
| "" ->
error "invalid cigar string" text sexp_of_string
| _ ->
let ch = Scanf.Scanning.from_string text in
let rec loop accum =
if Scanf.Scanning.end_of_input ch then Ok accum
else
try
let n = Scanf.bscanf ch "%d" Fun.id in
let c = Scanf.bscanf ch "%c" Fun.id in
let x =
match c with
| 'M' -> cigar_op_alignment_match n
| 'I' -> cigar_op_insertion n
| 'D' -> cigar_op_deletion n
| 'N' -> cigar_op_skipped n
| 'S' -> cigar_op_soft_clipping n
| 'H' -> cigar_op_hard_clipping n
| 'P' -> cigar_op_padding n
| '=' -> cigar_op_seq_match n
| 'X' -> cigar_op_seq_mismatch n
| other -> Or_error.error "invalid cigar operation type" other Char.sexp_of_t
in
Or_error.tag x ~tag:"Sam.parse_cigar: invalid cigar string" >>= fun x ->
loop (x::accum)
with
_ ->
error "invalid cigar string" text sexp_of_string
in
loop [] >>| List.rev
let rnext_re = Re.Perl.compile_pat "^\\*|=|[!-()+-<>-~][!-~]*$"
let parse_rnext s =
if not (Re.execp rnext_re s) then
error "invalid RNEXT" s sexp_of_string
else
match s with
| "*" -> Ok None
| "=" -> Ok (Some `Equal_to_RNAME)
| _ -> Ok (Some (`Value s))
let parse_pnext s =
parse_int_range "PNEXT" 0 2147483647 s >>| function
| 0 -> None
| x -> Some x
let parse_tlen s =
parse_int_range "TLEN" ~-2147483647 2147483647 s >>| function
| 0 -> None
| x -> Some x
let seq_re = Re.Perl.compile_pat "^\\*|[A-Za-z=.]+$"
let parse_seq s =
parse_opt_string "SEQ" seq_re s
let parse_qual s =
match s with
| "" -> Or_error.error_string "invalid empty QUAL"
| "*" -> Ok []
| _ ->
String.to_list s
|> List.map ~f:(Phred_score.of_char ~offset:`Offset33)
|> Result.all
let opt_field_tag_re = Re.Perl.compile_pat "^[A-Za-z][A-Za-z0-9]$"
let opt_field_Z_re = Re.Perl.compile_pat "^[ !-~]+$"
let opt_field_H_re = Re.Perl.compile_pat "^[0-9A-F]+$"
let opt_field_int_re = Re.Perl.compile_pat "^-?[0-9]+$"
let opt_field_float_re = Re.Perl.compile_pat "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$"
let optional_field_value_err typ value =
error "invalid value" (typ,value) [%sexp_of: string * string ]
let optional_field_value_A value =
if List.mem ~equal:Char.equal ['!';'-';'~'] value
then optional_field_value_err "A" (Char.to_string value)
else Ok (`A value)
let optional_field_value_i i = `i i
let optional_field_value_f f = `f f
let optional_field_value_Z value =
if Re.execp opt_field_Z_re value then Ok (`Z value)
else optional_field_value_err "Z" value
let optional_field_value_H value =
if Re.execp opt_field_H_re value then Ok (`H value)
else optional_field_value_err "H" value
let optional_field_value_B elt_type elts =
let valid_args =
match elt_type with
| 'c' | 'C' | 's' | 'S' | 'i' | 'I' ->
List.for_all elts ~f:(Re.execp opt_field_int_re)
| 'f' ->
List.for_all elts ~f:(Re.execp opt_field_float_re)
| _ -> false
in
if valid_args then Ok (`B (elt_type, elts))
else error "invalid value" ("B", elt_type, elts) [%sexp_of: string * char * string list ]
let optional_field tag value =
if not (Re.execp opt_field_tag_re tag)
then error "invalid TAG" tag sexp_of_string
else Ok {tag; value}
let parse_optional_field_value s =
match String.lsplit2 s ~on:':' with
| None ->
error "missing TYPE in optional field" s sexp_of_string
| Some (typ,value) ->
match typ with
| "A" ->
if String.length value = 1 then optional_field_value_A value.[0]
else optional_field_value_err typ value
| "i" ->
(try
if not (Re.execp opt_field_int_re value) then failwith "" ;
matching the regular expression is not enough : the number could not fit in 64 bits
with _ -> optional_field_value_err typ value)
| "f" ->
(try
if not (Re.execp opt_field_float_re value) then failwith "" ;
with _ -> optional_field_value_err typ value)
| "Z" -> optional_field_value_Z value
| "H" -> optional_field_value_H value
| "B" -> (
match String.split ~on:',' value with
| num_typ :: values ->
if String.length num_typ = 1 then
optional_field_value_B num_typ.[0] values
else
error "invalid array type" num_typ sexp_of_string
)
| _ -> error "invalid type" typ sexp_of_string
let parse_optional_field s =
match String.lsplit2 s ~on:':' with
| None ->
error "missing TAG in optional field" s sexp_of_string
| Some (tag,s) ->
parse_optional_field_value s >>= fun value ->
optional_field tag value
let parse_alignment ?ref_seqs line =
match String.split ~on:'\t' line with
| qname::flags::rname::pos::mapq::cigar::rnext
::pnext::tlen::seq::qual::optional_fields
-> (
parse_qname qname >>= fun qname ->
parse_flags flags >>= fun flags ->
parse_rname rname >>= fun rname ->
parse_pos pos >>= fun pos ->
parse_mapq mapq >>= fun mapq ->
parse_cigar cigar >>= fun cigar ->
parse_rnext rnext >>= fun rnext ->
parse_pnext pnext >>= fun pnext ->
parse_tlen tlen >>= fun tlen ->
parse_seq seq >>= fun seq ->
parse_qual qual >>= fun qual ->
List.map optional_fields ~f:parse_optional_field
|> Result.all
>>= fun optional_fields ->
alignment
?ref_seqs ?qname ~flags ?rname ?pos ?mapq ~cigar
?rnext ?pnext ?tlen ?seq ~qual ~optional_fields
()
)
| _ ->
Or_error.error_string "alignment line contains < 12 fields"
let print_header_item_tag = function
| `HD -> "@HD"
| `SQ -> "@SQ"
| `RG -> "@RG"
| `PG -> "@PG"
| `CO -> "@CO"
| `Other x -> sprintf "@%s" x
let print_tag_value (tag,value) = sprintf "%s:%s" tag value
let print_tag_value' = sprintf "%s:%s"
let print_header_version x = print_tag_value' "VN" x
let print_sort_order x =
print_tag_value' "SO"
(match x with
| `Unknown -> "unknown"
| `Unsorted -> "unsorted"
| `Query_name -> "queryname"
| `Coordinate -> "coordinate"
)
let print_group_order x =
print_tag_value' "GO"
(match x with
| `None -> "none"
| `Query -> "query"
| `Reference -> "reference"
)
let print_header_line ({version; sort_order; group_order} : header_line) =
sprintf "@HD\tVN:%s%s%s"
version
(match sort_order with
| None -> ""
| Some x -> sprintf "\t%s" (print_sort_order x)
)
(match group_order with
| None -> ""
| Some x -> sprintf "\t%s" (print_group_order x)
)
let print_ref_seq (x:ref_seq) =
sprintf "@SQ\tSN:%s\tLN:%d%s%s%s%s"
x.name
x.length
(match x.assembly with None -> "" | Some x -> sprintf "\tAS:%s" x)
(match x.md5 with None -> "" | Some x -> sprintf "\tM5:%s" x)
(match x.species with None -> "" | Some x -> sprintf "\tSP:%s" x)
(match x.uri with None -> "" | Some x -> sprintf "\tUR:%s" x)
let print_platform = function
| `Capillary -> "CAPILLARY"
| `LS454 -> "LS454"
| `Illumina -> "ILLUMINA"
| `Solid -> "SOLID"
| `Helicos -> "HELICOS"
| `Ion_Torrent -> "IONTORRENT"
| `Pac_Bio -> "PACBIO"
let print_read_group (x:read_group) =
let s tag value = match value with
| None -> ""
| Some x -> sprintf "\t%s:%s" tag x
in
sprintf "@RG\tID:%s%s%s%s%s%s%s%s%s%s%s%s"
x.id
(s "CN" x.seq_center)
(s "DS" x.description)
(s "DT" (Option.map x.run_date
~f:(function
| `Date x
| `Time x -> x) )
)
(s "FO" x.flow_order)
(s "KS" x.key_seq)
(s "LB" x.library)
(s "PG" x.program)
(s "PI" (Option.map x.predicted_median_insert_size ~f:Int.to_string))
(s "PL" (Option.map x.platform ~f:print_platform))
(s "PU" x.platform_unit)
(s "SM" x.sample)
let print_program (x:program) =
let s tag value = match value with
| None -> ""
| Some x -> sprintf "\t%s:%s" tag x
in
sprintf "@PG\tID:%s%s%s%s%s%s"
x.id
(s "PN" x.name)
(s "CL" x.command_line)
(s "PP" x.previous_id)
(s "DS" x.description)
(s "VN" x.version)
let print_other ((tag,l) : string * tag_value list) =
sprintf "@%s%s"
tag
(
List.map l ~f:(fun (x,y) -> sprintf "\t%s:%s" x y)
|> String.concat ~sep:""
)
let print_qname = function Some x -> x | None -> "*"
let print_flags = Int.to_string
let print_rname = function Some x -> x | None -> "*"
let print_pos = function Some x -> Int.to_string x | None -> "0"
let print_mapq = function Some x -> Int.to_string x | None -> "255"
let print_cigar_op = function
| `Alignment_match x -> sprintf "%dM" x
| `Insertion x -> sprintf "%dI" x
| `Deletion x -> sprintf "%dD" x
| `Skipped x -> sprintf "%dN" x
| `Soft_clipping x -> sprintf "%dS" x
| `Hard_clipping x -> sprintf "%dH" x
| `Padding x -> sprintf "%dP" x
| `Seq_match x -> sprintf "%d=" x
| `Seq_mismatch x -> sprintf "%dX" x
let print_cigar = function
| [] -> "*"
| cigar_ops ->
List.map cigar_ops ~f:print_cigar_op
|> String.concat ~sep:""
let print_rnext = function
| None -> "*"
| Some `Equal_to_RNAME -> "="
| Some (`Value x) -> x
let print_pnext = function Some x -> Int.to_string x | None -> "0"
let print_tlen = function Some x -> Int.to_string x | None -> "0"
let print_seq = function Some x -> x | None -> "*"
let print_qual = function
| [] -> "*"
| quals ->
List.map quals ~f:(fun x ->
ok_exn (Phred_score.to_char ~offset:`Offset33 x)
)
|> String.of_char_list
let print_optional_field (x:optional_field) =
let typ,value = match x.value with
| `A x -> 'A', Char.to_string x
| `i x -> 'i', Int64.to_string x
| `f x -> 'f', Float.to_string x
| `Z x -> 'Z', x
| `H x -> 'H', x
| `B (c,l) -> 'B', (String.concat ~sep:"," ((String.of_char c)::l))
in
sprintf "%s:%c:%s" x.tag typ value
let print_alignment a =
sprintf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s"
(print_qname a.qname)
(print_flags a.flags)
(print_rname a.rname)
(print_pos a.pos)
(print_mapq a.mapq)
(print_cigar a.cigar)
(print_rnext a.rnext)
(print_pnext a.pnext)
(print_tlen a.tlen)
(print_seq a.seq)
(print_qual a.qual)
(
List.map a.optional_fields ~f:print_optional_field
|> String.concat ~sep:"\t"
)
let read_header ic =
parse_header_gen (fun () -> In_channel.input_line ic)
let write_header oc (h : header) =
Option.iter h.version ~f:(fun version ->
Out_channel.output_string oc (print_header_line {version; sort_order=h.sort_order; group_order=h.group_order}) ;
Out_channel.output_char oc '\n'
) ;
List.iter h.ref_seqs ~f:(fun x ->
Out_channel.output_string oc (print_ref_seq x) ;
Out_channel.output_char oc '\n'
) ;
List.iter h.read_groups ~f:(fun x ->
Out_channel.output_string oc (print_read_group x) ;
Out_channel.output_char oc '\n'
) ;
List.iter h.programs ~f:(fun x ->
Out_channel.output_string oc (print_program x) ;
Out_channel.output_char oc '\n'
) ;
List.iter h.comments ~f:(fun x ->
Out_channel.output_string oc "@CO\t" ;
Out_channel.output_string oc x ;
Out_channel.output_char oc '\n'
) ;
List.iter h.others ~f:(fun x ->
Out_channel.output_string oc (print_other x) ;
Out_channel.output_char oc '\n'
)
let write_alignment oc a =
Out_channel.output_string oc (print_alignment a) ;
Out_channel.output_char oc '\n'
let write_file ?perm ?append file ?header alignments =
Out_channel.with_file ?perm ?append file ~f:(fun oc ->
Option.iter header ~f:(write_header oc) ;
Seq.iter (write_alignment oc) alignments
)
let fold fn ~init ~f =
let open Let_syntax.Result in
In_channel.with_file fn ~f:(fun ic ->
let* (header, maybe_next_line) = read_header ic in
let* init = init header in
match maybe_next_line with
| None -> Ok init
| Some line ->
let rec loop acc =
match In_channel.input_line ic with
| None -> Ok acc
| Some line -> process_line acc line
and process_line acc line =
let* alignment = parse_alignment line in
let* acc' = f acc alignment in
loop acc'
in
process_line init line
)
|
a3eb032e6ceee806fec2c8ab8fcb1def1d5943020f0942d1c53335728cd71aef | falsetru/htdp | 33.4.3.scm | #lang racket
(define (sum xs) (foldr + 0 xs))
(define JANUS
(list #i31
#i2e+34
#i-1.2345678901235e+80
#i2749
#i-2939234
#i-2e+33
#i3.2e+270
#i17
#i-2.4e+270
#i4.2344294738446e+170
#i1
#i-8e+269
#i0
#i99))
(display (sum JANUS)) (newline)
(display (sum (reverse JANUS))) (newline)
(display (- (sum JANUS) (sum (reverse JANUS)))) (newline)
| null | https://raw.githubusercontent.com/falsetru/htdp/4cdad3b999f19b89ff4fa7561839cbcbaad274df/33/33.4.3.scm | scheme | #lang racket
(define (sum xs) (foldr + 0 xs))
(define JANUS
(list #i31
#i2e+34
#i-1.2345678901235e+80
#i2749
#i-2939234
#i-2e+33
#i3.2e+270
#i17
#i-2.4e+270
#i4.2344294738446e+170
#i1
#i-8e+269
#i0
#i99))
(display (sum JANUS)) (newline)
(display (sum (reverse JANUS))) (newline)
(display (- (sum JANUS) (sum (reverse JANUS)))) (newline)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.