_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
|
---|---|---|---|---|---|---|---|---|
75c4320b06ffed2f005dba55f7a3c4ee678d4fa496b9fa0a119ecc29292d1262 | boxer-project/boxer-sunrise | run-tests.lisp | (require "asdf")
(require "uiop")
Sometimes does n't seem to load the initialization file when running from
;; the command line, in which case this could be uncommented.
;; (load "~/quicklisp/setup.lisp")
(ql:quickload "prove-asdf")
(ql:quickload "cl-ppcre")
(ql:quickload "prove")
(ql:quickload :cl-fad)
(ql:quickload :log4cl)
(ql:quickload :drakma)
(ql:quickload :cl-json)
(ql:quickload :zpng)
(ql:quickload :qbase64)
(ql:quickload :html-entities)
(ql:quickload :md5)
(ql:quickload :quri)
(ql:quickload :alexandria)
(ql:quickload :trivial-garbage)
(ql:quickload :cffi)
(ql:quickload :zip)
(defvar *boxer-project-dir* (make-pathname :directory (pathname-directory *load-truename*)))
(pushnew
(cl-fad:merge-pathnames-as-directory *boxer-project-dir* "data/boxersunrise.app/Contents/Frameworks/")
cffi:*foreign-library-directories* :test #'equal)
(setf asdf:*central-registry*
(list* '*default-pathname-defaults*
*boxer-project-dir*
asdf:*central-registry*))
(ql:quickload :cl-freetype2)
;; This turns off the terminal color sequences and simplifies the characters in the
output so they display well in the listener .
(setf prove:*enable-colors* nil)
(setf prove::*default-reporter* :tap)
#+lispworks (load (example-file "opengl/examples/load"))
(setf *features* (cons :opengl *features*))
(setf *features* (cons :freetype-fonts *features*))
(asdf:test-system :boxer-sunrise :reporter :list)
| null | https://raw.githubusercontent.com/boxer-project/boxer-sunrise/55acd3aa603aa1724593a048e3a4552f1894801d/run-tests.lisp | lisp | the command line, in which case this could be uncommented.
(load "~/quicklisp/setup.lisp")
This turns off the terminal color sequences and simplifies the characters in the | (require "asdf")
(require "uiop")
Sometimes does n't seem to load the initialization file when running from
(ql:quickload "prove-asdf")
(ql:quickload "cl-ppcre")
(ql:quickload "prove")
(ql:quickload :cl-fad)
(ql:quickload :log4cl)
(ql:quickload :drakma)
(ql:quickload :cl-json)
(ql:quickload :zpng)
(ql:quickload :qbase64)
(ql:quickload :html-entities)
(ql:quickload :md5)
(ql:quickload :quri)
(ql:quickload :alexandria)
(ql:quickload :trivial-garbage)
(ql:quickload :cffi)
(ql:quickload :zip)
(defvar *boxer-project-dir* (make-pathname :directory (pathname-directory *load-truename*)))
(pushnew
(cl-fad:merge-pathnames-as-directory *boxer-project-dir* "data/boxersunrise.app/Contents/Frameworks/")
cffi:*foreign-library-directories* :test #'equal)
(setf asdf:*central-registry*
(list* '*default-pathname-defaults*
*boxer-project-dir*
asdf:*central-registry*))
(ql:quickload :cl-freetype2)
output so they display well in the listener .
(setf prove:*enable-colors* nil)
(setf prove::*default-reporter* :tap)
#+lispworks (load (example-file "opengl/examples/load"))
(setf *features* (cons :opengl *features*))
(setf *features* (cons :freetype-fonts *features*))
(asdf:test-system :boxer-sunrise :reporter :list)
|
39916036a43cc4745f3f80ba4682b70bbbf9fe55d0a58e9774936f7c6f329f08 | m1kal/charbel | core.cljs | (ns charbel-cljs.core
(:require [charbel.core :refer [module-from-string build]]
[reagent.core :as r]
[reagent.dom :as d]))
(def example
(str
"(module delay_line\n {:clocks [[clk]] :parameters [WIDTH 32]}\n"
" [[:in data WIDTH] [:in valid 1]\n [:out data_o WIDTH] [:out valid_o 1]]\n"
" (register data_d data)\n (register valid_d (init 0 valid))\n"
" (assign valid_o valid_d)\n (assign data_o data_d))"))
(defonce input-form (r/atom example))
(def output-form (r/atom "<empty>"))
(def postprocess (r/atom true))
(defn main []
[:div {:style {:background-color "rgb(200,240,200)" :width 1280 :padding-left 20 :padding-top 1 :padding-bottom 20}}
[:h1 "Charbel online"]
[:div "Write synthesizable FPGA code using Clojure syntax. The code is translated to SystemVerilog."]
[:div "Project source code:" [:a {:href ""} ""] "."]
[:h4 "Write your code below"]
[:table
[:tbody
[:tr
[:td {:style {:vertical-align "top"}}
[:textarea
{:id "i" :style {:width 600 :height 400} :value @input-form
:on-change #(reset! input-form (.-value (.-target %)))}]]
[:td
{:style {:position "relative" :left 30 :width 600
:vertical-align "top" :background-color "rgb(200,220,220)"}}
[:pre @output-form]]]
[:tr
[:td
[:div
[:button
{:id "run" :on-click #(reset! output-form (build (module-from-string @input-form) @postprocess))}
"Convert"]]
[:div
[:input {:type "checkbox" :checked @postprocess :on-click #(swap! postprocess not)}]
"Generate `default_nettype and `max (if necessary)."]]
[:td ""]]]]])
(defn mount-root []
(d/render [main] (.getElementById js/document "main")))
(defn init! []
(mount-root))
(init!)
| null | https://raw.githubusercontent.com/m1kal/charbel/967d617f3c4e85c66670236baee29aede4936b6b/docs/src/charbel_cljs/core.cljs | clojure | (ns charbel-cljs.core
(:require [charbel.core :refer [module-from-string build]]
[reagent.core :as r]
[reagent.dom :as d]))
(def example
(str
"(module delay_line\n {:clocks [[clk]] :parameters [WIDTH 32]}\n"
" [[:in data WIDTH] [:in valid 1]\n [:out data_o WIDTH] [:out valid_o 1]]\n"
" (register data_d data)\n (register valid_d (init 0 valid))\n"
" (assign valid_o valid_d)\n (assign data_o data_d))"))
(defonce input-form (r/atom example))
(def output-form (r/atom "<empty>"))
(def postprocess (r/atom true))
(defn main []
[:div {:style {:background-color "rgb(200,240,200)" :width 1280 :padding-left 20 :padding-top 1 :padding-bottom 20}}
[:h1 "Charbel online"]
[:div "Write synthesizable FPGA code using Clojure syntax. The code is translated to SystemVerilog."]
[:div "Project source code:" [:a {:href ""} ""] "."]
[:h4 "Write your code below"]
[:table
[:tbody
[:tr
[:td {:style {:vertical-align "top"}}
[:textarea
{:id "i" :style {:width 600 :height 400} :value @input-form
:on-change #(reset! input-form (.-value (.-target %)))}]]
[:td
{:style {:position "relative" :left 30 :width 600
:vertical-align "top" :background-color "rgb(200,220,220)"}}
[:pre @output-form]]]
[:tr
[:td
[:div
[:button
{:id "run" :on-click #(reset! output-form (build (module-from-string @input-form) @postprocess))}
"Convert"]]
[:div
[:input {:type "checkbox" :checked @postprocess :on-click #(swap! postprocess not)}]
"Generate `default_nettype and `max (if necessary)."]]
[:td ""]]]]])
(defn mount-root []
(d/render [main] (.getElementById js/document "main")))
(defn init! []
(mount-root))
(init!)
|
|
7b75eb057d05174af7d5855dc5990db28c5a11a2cba09d947f12b440b9e0e098 | darrenldl/ProVerif-ATP | termslinks.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2018 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2018 *
* *
*************************************************************)
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 ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
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 (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
val equal_terms_with_links : Types.term -> Types.term -> bool
val equal_facts_with_links : Types.fact -> Types.fact -> bool
val equal_closed_terms : Types.term -> Types.term -> bool
val equal_tags : Types.label -> Types.label -> bool
val equal_constra : Types.constraints list list -> Types.constraints list list -> bool
val match_terms : Types.term -> Types.term -> unit
| null | https://raw.githubusercontent.com/darrenldl/ProVerif-ATP/7af6cfb9e0550ecdb072c471e15b8f22b07408bd/proverif2.00/src/termslinks.mli | ocaml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2018 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2018 *
* *
*************************************************************)
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 ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
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 (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
val equal_terms_with_links : Types.term -> Types.term -> bool
val equal_facts_with_links : Types.fact -> Types.fact -> bool
val equal_closed_terms : Types.term -> Types.term -> bool
val equal_tags : Types.label -> Types.label -> bool
val equal_constra : Types.constraints list list -> Types.constraints list list -> bool
val match_terms : Types.term -> Types.term -> unit
|
|
6ba2e56913a2276c1de5fce5488e52d5dee3f45cddb873b87d4a59d54c56b805 | conjure-cp/conjure | options.hs |
data FlagKind = On | OnOff | Default Int [Int] | Ignore
deriving (Eq, Show)
allFlags :: [(String, FlagKind)]
allFlags =
[ ( "case-merge" , On )
, ( "cse" , On )
, ( "dicts-strict" , OnOff )
, ( "do-eta-reduction" , On )
, ( "do-lambda-eta-expansion" , OnOff )
, ( "eager-blackholing" , OnOff )
, ( "enable-rewrite-rules" , On )
, ( "vectorise" , Ignore )
, ( "avoid-vect" , Ignore )
, ( "excess-precision" , OnOff )
, ( "float-in" , On )
, ( "full-laziness" , On )
, ( "fun-to-thunk" , OnOff )
, ( "ignore-asserts" , OnOff )
, ( "ignore-interface-pragmas" , OnOff )
, ( "loopification" , OnOff )
, ( "late-dmd-anal" , OnOff )
, ( "liberate-case" , OnOff )
, ( "liberate-case-threshold" , Default 200 [100,200..1000] )
, ( "max-relevant-bindings" , Ignore )
, ( "max-simplifier-iterations" , Default undefined [] )
, ( "max-worker-args" , Default 10 [10,20,100] )
, ( "no-opt-coercion" , OnOff )
, ( "no-pre-inlining" , OnOff )
, ( "no-state-hack" , OnOff )
, ( "pedantic-bottoms" , OnOff )
, ( "omit-interface-pragmas" , OnOff )
, ( "simplifier-phases" , Default 2 [1,2..10] )
, ( "simpl-tick-factor" , Default 100 [] )
, ( "spec-constr" , OnOff )
, ( "spec-constr-threshold" , Default 200 [] )
, ( "spec-constr-count" , Default 3 [] )
, ( "specialise" , On )
, ( "strictness" , On )
, ( "strictness-before" , Ignore )
, ( "static-argument-transformation" , OnOff )
, ( "unbox-strict-fields" , OnOff )
, ( "unbox-small-strict-fields" , OnOff )
, ( "unfolding-creation-threshold" , Ignore )
, ( "unfolding-fun-discount" , Ignore )
, ( "unfolding-keeness-factor" , Ignore )
, ( "unfolding-use-threshold" , Ignore )
]
main :: IO ()
main = do
let allOptions
= [ map (++f) ["-f", "-fno-"] | (f, OnOff) <- allFlags ]
++ [ [ "-f" ++ f ] | (f, On) <- allFlags ]
mapM_ print $ sequence allOptions
| null | https://raw.githubusercontent.com/conjure-cp/conjure/dd5a27df138af2ccbbb970274c2b8f22ac6b26a0/etc/dev/ghc-optimisation-flags/options.hs | haskell |
data FlagKind = On | OnOff | Default Int [Int] | Ignore
deriving (Eq, Show)
allFlags :: [(String, FlagKind)]
allFlags =
[ ( "case-merge" , On )
, ( "cse" , On )
, ( "dicts-strict" , OnOff )
, ( "do-eta-reduction" , On )
, ( "do-lambda-eta-expansion" , OnOff )
, ( "eager-blackholing" , OnOff )
, ( "enable-rewrite-rules" , On )
, ( "vectorise" , Ignore )
, ( "avoid-vect" , Ignore )
, ( "excess-precision" , OnOff )
, ( "float-in" , On )
, ( "full-laziness" , On )
, ( "fun-to-thunk" , OnOff )
, ( "ignore-asserts" , OnOff )
, ( "ignore-interface-pragmas" , OnOff )
, ( "loopification" , OnOff )
, ( "late-dmd-anal" , OnOff )
, ( "liberate-case" , OnOff )
, ( "liberate-case-threshold" , Default 200 [100,200..1000] )
, ( "max-relevant-bindings" , Ignore )
, ( "max-simplifier-iterations" , Default undefined [] )
, ( "max-worker-args" , Default 10 [10,20,100] )
, ( "no-opt-coercion" , OnOff )
, ( "no-pre-inlining" , OnOff )
, ( "no-state-hack" , OnOff )
, ( "pedantic-bottoms" , OnOff )
, ( "omit-interface-pragmas" , OnOff )
, ( "simplifier-phases" , Default 2 [1,2..10] )
, ( "simpl-tick-factor" , Default 100 [] )
, ( "spec-constr" , OnOff )
, ( "spec-constr-threshold" , Default 200 [] )
, ( "spec-constr-count" , Default 3 [] )
, ( "specialise" , On )
, ( "strictness" , On )
, ( "strictness-before" , Ignore )
, ( "static-argument-transformation" , OnOff )
, ( "unbox-strict-fields" , OnOff )
, ( "unbox-small-strict-fields" , OnOff )
, ( "unfolding-creation-threshold" , Ignore )
, ( "unfolding-fun-discount" , Ignore )
, ( "unfolding-keeness-factor" , Ignore )
, ( "unfolding-use-threshold" , Ignore )
]
main :: IO ()
main = do
let allOptions
= [ map (++f) ["-f", "-fno-"] | (f, OnOff) <- allFlags ]
++ [ [ "-f" ++ f ] | (f, On) <- allFlags ]
mapM_ print $ sequence allOptions
|
|
e485c33b6a0d2fd49a9cf56368c86a525e82668da14bc14a090ac7c33f79b032 | haskell-perf/graphs | Abstract.hs | module BenchGraph.Render.Abstract
(
printAbstract
, printQuick
, average
)
where
import Data.List (find, sortBy)
import Text.Printf (printf)
import Control.Monad (unless)
import Data.Bitraversable (bisequence)
import Control.Applicative ((<|>))
import BenchGraph.Named
import BenchGraph.Render.Types
import BenchGraph.Render.Common (average, getSimples)
-- | Will print an abstract, comparing libraries by their average time
printAbstract :: String -- ^ A comparative (like "faster")
-> Grouped [Named Double] -- ^ The actual data
-> IO ()
printAbstract comparative = printMap comparative . fmap reverse . rearrange . removeNaN . getComparison Nothing . getSimples
printQuick :: String -- ^ To compare with
-> Grouped [Named Double] -- ^ data
-> IO ()
printQuick name = printQuickMap . removeNaN . getComparison (Just name) . getSimples
printQuickMap :: Named [Named Double] -> IO ()
printQuickMap (_,(_,x):_) = putStrLn $ printf "%.2f" x ++ " (" ++ fancy ++ ")"
where
fancy
| x < 0.9 = "good"
| x >= 0.9 && x <= 1.1 = "OK"
| otherwise = "bad"
printQuickMap _ = putStrLn "ERROR"
removeNaN :: Named [Named Double] -> Named [Named Double]
removeNaN = fmap (filter (not . isNaN . snd))
-- | Sort the results, plus put the worst lib for comparison
rearrange :: Named [Named Double] -> Named [Named Double]
rearrange na@(n,arr) =
if not $ null arr
then if db >= 1
then (n,sorted)
else rearrange (n',(n,recip db) : map (fmap (recip db *)) (tail sorted))
else na
where
sorted = sortBy compare1 arr
(n',db) = head sorted
printMap :: String -> Named [Named Double] -> IO ()
printMap superlative (ref,res) = unless (null res) $ do
putStrLn $ unlines ["\nABSTRACT:","(Based on an average of the ratio between largest benchmarks)"]
mapM_ (\(name,av) -> putStrLn $ unwords [" *",name,"was",printf "%.2f" av,"times",superlative,"than",ref]) res
putStrLn ""
| The first Name given is the reference name for comparison , the others are the comparison themselves
getComparison :: Maybe String -> [[Named Double]] -> Named [Named Double]
getComparison mref grp = case mref <|> getRef grp of
Nothing -> ("",[])
Just ref -> let refinedRef = ref
start = map fst $ filter (\(n,_) -> n /= ref) $ head grp
in (refinedRef, map (\x -> (x,getComparison' grp refinedRef x)) start)
| Return a " reference " : A library for there is a non-0 value
getRef :: [[Named Double]] -> Maybe String
getRef [] = Nothing
getRef (x:xs) = maybe (getRef xs) (Just . fst) $ find (\(_,y) -> y /= 0) x
getComparison' :: [[Named Double]] -> String -> String -> Double
getComparison' grp ref todo = average $ map (\lst ->
maybe 0 (uncurry (/)) $ bisequence (lookup ref lst,lookup todo lst))
grp
| null | https://raw.githubusercontent.com/haskell-perf/graphs/d2e53fb424b01bb51d5733cc40fd62abb2740430/src/BenchGraph/Render/Abstract.hs | haskell | | Will print an abstract, comparing libraries by their average time
^ A comparative (like "faster")
^ The actual data
^ To compare with
^ data
| Sort the results, plus put the worst lib for comparison | module BenchGraph.Render.Abstract
(
printAbstract
, printQuick
, average
)
where
import Data.List (find, sortBy)
import Text.Printf (printf)
import Control.Monad (unless)
import Data.Bitraversable (bisequence)
import Control.Applicative ((<|>))
import BenchGraph.Named
import BenchGraph.Render.Types
import BenchGraph.Render.Common (average, getSimples)
-> IO ()
printAbstract comparative = printMap comparative . fmap reverse . rearrange . removeNaN . getComparison Nothing . getSimples
-> IO ()
printQuick name = printQuickMap . removeNaN . getComparison (Just name) . getSimples
printQuickMap :: Named [Named Double] -> IO ()
printQuickMap (_,(_,x):_) = putStrLn $ printf "%.2f" x ++ " (" ++ fancy ++ ")"
where
fancy
| x < 0.9 = "good"
| x >= 0.9 && x <= 1.1 = "OK"
| otherwise = "bad"
printQuickMap _ = putStrLn "ERROR"
removeNaN :: Named [Named Double] -> Named [Named Double]
removeNaN = fmap (filter (not . isNaN . snd))
rearrange :: Named [Named Double] -> Named [Named Double]
rearrange na@(n,arr) =
if not $ null arr
then if db >= 1
then (n,sorted)
else rearrange (n',(n,recip db) : map (fmap (recip db *)) (tail sorted))
else na
where
sorted = sortBy compare1 arr
(n',db) = head sorted
printMap :: String -> Named [Named Double] -> IO ()
printMap superlative (ref,res) = unless (null res) $ do
putStrLn $ unlines ["\nABSTRACT:","(Based on an average of the ratio between largest benchmarks)"]
mapM_ (\(name,av) -> putStrLn $ unwords [" *",name,"was",printf "%.2f" av,"times",superlative,"than",ref]) res
putStrLn ""
| The first Name given is the reference name for comparison , the others are the comparison themselves
getComparison :: Maybe String -> [[Named Double]] -> Named [Named Double]
getComparison mref grp = case mref <|> getRef grp of
Nothing -> ("",[])
Just ref -> let refinedRef = ref
start = map fst $ filter (\(n,_) -> n /= ref) $ head grp
in (refinedRef, map (\x -> (x,getComparison' grp refinedRef x)) start)
| Return a " reference " : A library for there is a non-0 value
getRef :: [[Named Double]] -> Maybe String
getRef [] = Nothing
getRef (x:xs) = maybe (getRef xs) (Just . fst) $ find (\(_,y) -> y /= 0) x
getComparison' :: [[Named Double]] -> String -> String -> Double
getComparison' grp ref todo = average $ map (\lst ->
maybe 0 (uncurry (/)) $ bisequence (lookup ref lst,lookup todo lst))
grp
|
00463afe94485aca688af5026fdcd2cf4a68e375fb6f4b668a79b3a2cdf4ca5b | hbr/fmlib | fmlib_parse.mli | (** Parsing Library *)
(** {1 Documentation}
{{!page-parse} Introduction to Combinator Parsing}
*)
(** {1 API} *)
module Character = Character
module Token_parser = Token_parser
module Parse_with_lexer = Parse_with_lexer
module Generic = Generic
module Position = Position
module Located = Located
module Indent = Indent
module Error_reporter = Error_reporter
module Interfaces = Interfaces
| null | https://raw.githubusercontent.com/hbr/fmlib/45ee4d2c76a19ef44557c554de30ec57d94bb9e5/src/parse/fmlib_parse.mli | ocaml | * Parsing Library
* {1 Documentation}
{{!page-parse} Introduction to Combinator Parsing}
* {1 API} |
module Character = Character
module Token_parser = Token_parser
module Parse_with_lexer = Parse_with_lexer
module Generic = Generic
module Position = Position
module Located = Located
module Indent = Indent
module Error_reporter = Error_reporter
module Interfaces = Interfaces
|
e841bf2587c8d685c8dd35edfd1df8d8c5dcab457cd1e170cd99a58ce9352a4b | ghc/testsuite | T1835.hs | # LANGUAGE TemplateHaskell , FlexibleInstances ,
MultiParamTypeClasses , TypeSynonymInstances #
MultiParamTypeClasses, TypeSynonymInstances #-}
module Main where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
class Eq a => MyClass a
data Foo = Foo deriving Eq
instance MyClass Foo
data Bar = Bar
deriving Eq
type Baz = Bar
instance MyClass Baz
data Quux a = Quux a deriving Eq
data Quux2 a = Quux2 a deriving Eq
instance Eq a => MyClass (Quux a)
instance Ord a => MyClass (Quux2 a)
class MyClass2 a b
instance MyClass2 Int Bool
$(return [])
main = do
putStrLn $(do { info <- reify ''MyClass; lift (pprint info) })
print $(isInstance ''Eq [ConT ''Foo] >>= lift)
print $(isInstance ''MyClass [ConT ''Foo] >>= lift)
print $ not $(isInstance ''Show [ConT ''Foo] >>= lift)
this one
print $(isInstance ''MyClass [ConT ''Baz] >>= lift)
this one
this one
print $(isInstance ''MyClass2 [ConT ''Int, ConT ''Bool] >>= lift)
print $(isInstance ''MyClass2 [ConT ''Bool, ConT ''Bool] >>= lift)
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/th/T1835.hs | haskell | # LANGUAGE TemplateHaskell , FlexibleInstances ,
MultiParamTypeClasses , TypeSynonymInstances #
MultiParamTypeClasses, TypeSynonymInstances #-}
module Main where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
class Eq a => MyClass a
data Foo = Foo deriving Eq
instance MyClass Foo
data Bar = Bar
deriving Eq
type Baz = Bar
instance MyClass Baz
data Quux a = Quux a deriving Eq
data Quux2 a = Quux2 a deriving Eq
instance Eq a => MyClass (Quux a)
instance Ord a => MyClass (Quux2 a)
class MyClass2 a b
instance MyClass2 Int Bool
$(return [])
main = do
putStrLn $(do { info <- reify ''MyClass; lift (pprint info) })
print $(isInstance ''Eq [ConT ''Foo] >>= lift)
print $(isInstance ''MyClass [ConT ''Foo] >>= lift)
print $ not $(isInstance ''Show [ConT ''Foo] >>= lift)
this one
print $(isInstance ''MyClass [ConT ''Baz] >>= lift)
this one
this one
print $(isInstance ''MyClass2 [ConT ''Int, ConT ''Bool] >>= lift)
print $(isInstance ''MyClass2 [ConT ''Bool, ConT ''Bool] >>= lift)
|
|
5aa258be72d2f81ab29033d0f0c3020092db0a7c7ba75e96411ee5af5d97417c | district0x/cljs-orbitdb | eventlog.cljs | (ns orbitdb.eventlog
(:require [orbitdb.signatures :as signatures]))
(defn eventlog
"Creates and opens an eventlog database.
Takes an OrbitDB instance and a map with:
`:name` (string): the database name
or
`:address` (string): and IPFS address of an existing eventlog database,
`:opts`: a map of options (see `create-database`)
Returns a js/Promise resolving to the instance of the database."
[^js orbitdb-instance {:keys [name address opts]
:or {opts {}}}]
(.eventlog orbitdb-instance (or address name) (clj->js opts)))
(def add-event
"`(add-event database-instance data & [opts])`
Returns a js/Promise that resolves to the hash of the entry (string)."
signatures/add-event)
(def get-event
"`(get-event database-instance hash)`
Takes an OrbitDB instance and a hash of the entry (string).
Returns a map with the contents of that entry."
signatures/get-event)
(def iterator
"`(iterator database-instance opts)`
Returns an Array of Objects based on the map of options:
`:gt` (string): Greater than, takes an item's hash.
`:gte` (string): Greater than or equal to, takes an item's hash.
`:lt` (string): Less than, takes an item's hash.
`:lte` (string): Less than or equal to, takes an item's hash value.
`:limit` (integer): Limiting the entries of result, defaults to 1, and -1 means all items.
`:reverse` (boolean): If set to true will result in reversing the result."
signatures/iterator)
(def collect
"`(collect iterator)`
Takes an iterator as the argument and evaluates it, returns a vector of results."
signatures/collect)
| null | https://raw.githubusercontent.com/district0x/cljs-orbitdb/9928bf877c66c926a7f0bec086e8c7755240d15c/src/orbitdb/eventlog.cljs | clojure | (ns orbitdb.eventlog
(:require [orbitdb.signatures :as signatures]))
(defn eventlog
"Creates and opens an eventlog database.
Takes an OrbitDB instance and a map with:
`:name` (string): the database name
or
`:address` (string): and IPFS address of an existing eventlog database,
`:opts`: a map of options (see `create-database`)
Returns a js/Promise resolving to the instance of the database."
[^js orbitdb-instance {:keys [name address opts]
:or {opts {}}}]
(.eventlog orbitdb-instance (or address name) (clj->js opts)))
(def add-event
"`(add-event database-instance data & [opts])`
Returns a js/Promise that resolves to the hash of the entry (string)."
signatures/add-event)
(def get-event
"`(get-event database-instance hash)`
Takes an OrbitDB instance and a hash of the entry (string).
Returns a map with the contents of that entry."
signatures/get-event)
(def iterator
"`(iterator database-instance opts)`
Returns an Array of Objects based on the map of options:
`:gt` (string): Greater than, takes an item's hash.
`:gte` (string): Greater than or equal to, takes an item's hash.
`:lt` (string): Less than, takes an item's hash.
`:lte` (string): Less than or equal to, takes an item's hash value.
`:limit` (integer): Limiting the entries of result, defaults to 1, and -1 means all items.
`:reverse` (boolean): If set to true will result in reversing the result."
signatures/iterator)
(def collect
"`(collect iterator)`
Takes an iterator as the argument and evaluates it, returns a vector of results."
signatures/collect)
|
|
46ec51a8e7f0241bc0b2e5398bea502b61f24a6814feb2c9ecfa7d95b2b0aa76 | yapsterapp/er-cassandra | vector.cljc | (ns er-cassandra.util.vector)
(defn coerce
[obj]
(cond
(nil? obj) nil
(vector? obj) obj
(sequential? obj) (vec obj)
:else [obj]))
| null | https://raw.githubusercontent.com/yapsterapp/er-cassandra/1d059f47bdf8654c7a4dd6f0759f1a114fdeba81/src/er_cassandra/util/vector.cljc | clojure | (ns er-cassandra.util.vector)
(defn coerce
[obj]
(cond
(nil? obj) nil
(vector? obj) obj
(sequential? obj) (vec obj)
:else [obj]))
|
|
6d45b5fff3b8ff8473547f252ad9a2d3a28877a3bf67104f7b104b589a4b69ce | incoherentsoftware/defect-process | TutorialSetup.hs | module Level.Room.Trigger.All.TutorialSetup
( mkTutorialSetupTrigger
) where
import Control.Monad.IO.Class (MonadIO)
import Data.Functor ((<&>))
import Enemy.Types
import Level.Room.ArenaWalls.EnemySpawn
import Level.Room.Item.Pickup.All.GunItemPickups
import Level.Room.Item.RefreshStation
import Level.Room.Trigger
import Level.Room.Trigger.All.TutorialInstructions
import Level.Room.Trigger.All.TutorialListener
import Level.Room.Trigger.Util
import Level.Room.Tutorial.SandbagAir
import Level.Room.Tutorial.SandbagGround
import Level.Room.Util
import Msg
import Player.EquipmentInfo
import Util
freeRevolverPickupPos = Pos2 967.0 3370.0 :: Pos2
refreshStationPos = Pos2 563.0 3370.0 :: Pos2
sandbagGroundPos = Pos2 1239.0 3372.0 :: Pos2
sandbagAirPos = roomArenaWallsEnemySpawnOffset (Pos2 1553.0 3370.0) FlyingEnemy :: Pos2
mkTutorialSetupTrigger :: MonadIO m => m RoomTrigger
mkTutorialSetupTrigger = do
trigger <- mkRoomTrigger
return $ (trigger :: RoomTrigger) {_think = thinkSpawnNeededEquipment}
readIsPlayerGunTypesEmpty :: MsgsRead ThinkLevelMsgsPhase m => m Bool
readIsPlayerGunTypesEmpty = null . _gunTypes <$> readPlayerEquipmentInfo
thinkSpawnNeededEquipment :: (MonadIO m, MsgsRead ThinkLevelMsgsPhase m) => RoomTriggerThink m
thinkSpawnNeededEquipment _ trigger = readIsPlayerGunTypesEmpty <&> \case
False -> [updateTriggerThinkMessage (thinkFinishSetup False) trigger]
True ->
[ mkMsg $ RoomMsgAddItemM (mkFreeRevolverItemPickup tutorialRoomType freeRevolverPickupPos)
, updateTriggerThinkMessage (thinkFinishSetup True) trigger
]
thinkFinishSetup :: (MonadIO m, MsgsRead ThinkLevelMsgsPhase m) => Bool -> RoomTriggerThink m
thinkFinishSetup isGivenFreeRevolver _ trigger = readIsPlayerGunTypesEmpty <&> \case
True -> []
False ->
[ mkMsg $ RoomMsgAddItemM (mkRefreshStation refreshStationPos)
, mkMsg $ EnemyMsgAddM (mkSandbagGround sandbagGroundPos LeftDir)
, mkMsg $ EnemyMsgAddM (mkSandbagAir sandbagAirPos LeftDir)
, mkMsg $ RoomMsgAddTriggerM (mkTutorialInstructionsTrigger isGivenFreeRevolver)
, mkMsg $ RoomMsgAddTriggerM mkTutorialListenerTrigger
, removeTriggerMessage trigger
]
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/c39ce1f742d32a0ffcde82c03bf872adeb7d9162/src/Level/Room/Trigger/All/TutorialSetup.hs | haskell | module Level.Room.Trigger.All.TutorialSetup
( mkTutorialSetupTrigger
) where
import Control.Monad.IO.Class (MonadIO)
import Data.Functor ((<&>))
import Enemy.Types
import Level.Room.ArenaWalls.EnemySpawn
import Level.Room.Item.Pickup.All.GunItemPickups
import Level.Room.Item.RefreshStation
import Level.Room.Trigger
import Level.Room.Trigger.All.TutorialInstructions
import Level.Room.Trigger.All.TutorialListener
import Level.Room.Trigger.Util
import Level.Room.Tutorial.SandbagAir
import Level.Room.Tutorial.SandbagGround
import Level.Room.Util
import Msg
import Player.EquipmentInfo
import Util
freeRevolverPickupPos = Pos2 967.0 3370.0 :: Pos2
refreshStationPos = Pos2 563.0 3370.0 :: Pos2
sandbagGroundPos = Pos2 1239.0 3372.0 :: Pos2
sandbagAirPos = roomArenaWallsEnemySpawnOffset (Pos2 1553.0 3370.0) FlyingEnemy :: Pos2
mkTutorialSetupTrigger :: MonadIO m => m RoomTrigger
mkTutorialSetupTrigger = do
trigger <- mkRoomTrigger
return $ (trigger :: RoomTrigger) {_think = thinkSpawnNeededEquipment}
readIsPlayerGunTypesEmpty :: MsgsRead ThinkLevelMsgsPhase m => m Bool
readIsPlayerGunTypesEmpty = null . _gunTypes <$> readPlayerEquipmentInfo
thinkSpawnNeededEquipment :: (MonadIO m, MsgsRead ThinkLevelMsgsPhase m) => RoomTriggerThink m
thinkSpawnNeededEquipment _ trigger = readIsPlayerGunTypesEmpty <&> \case
False -> [updateTriggerThinkMessage (thinkFinishSetup False) trigger]
True ->
[ mkMsg $ RoomMsgAddItemM (mkFreeRevolverItemPickup tutorialRoomType freeRevolverPickupPos)
, updateTriggerThinkMessage (thinkFinishSetup True) trigger
]
thinkFinishSetup :: (MonadIO m, MsgsRead ThinkLevelMsgsPhase m) => Bool -> RoomTriggerThink m
thinkFinishSetup isGivenFreeRevolver _ trigger = readIsPlayerGunTypesEmpty <&> \case
True -> []
False ->
[ mkMsg $ RoomMsgAddItemM (mkRefreshStation refreshStationPos)
, mkMsg $ EnemyMsgAddM (mkSandbagGround sandbagGroundPos LeftDir)
, mkMsg $ EnemyMsgAddM (mkSandbagAir sandbagAirPos LeftDir)
, mkMsg $ RoomMsgAddTriggerM (mkTutorialInstructionsTrigger isGivenFreeRevolver)
, mkMsg $ RoomMsgAddTriggerM mkTutorialListenerTrigger
, removeTriggerMessage trigger
]
|
|
e61e587bea278cffd843a9f4bfae801c9d349fd91615bfccba508705ab483241 | pfdietz/ansi-test | file-namestring.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sat Sep 11 07:40:47 2004
;;;; Contains: Tests for FILE-NAMESTRING
(deftest file-namestring.1
(let* ((vals (multiple-value-list
(file-namestring "file-namestring.txt")))
(s (first vals)))
(if (and (null (cdr vals))
(stringp s)
(equal (file-namestring s) s))
:good
vals))
:good)
(deftest file-namestring.2
(do-special-strings
(s "file-namestring.txt" nil)
(let ((ns (file-namestring s)))
(assert (stringp ns))
(assert (string= (file-namestring ns) ns))))
nil)
(deftest file-namestring.3
(let* ((name "file-namestring.txt")
(pn (merge-pathnames (pathname name)))
(name2 (with-open-file (s pn :direction :input)
(file-namestring s)))
(name3 (file-namestring pn)))
(or (equalt name2 name3) (list name2 name3)))
t)
;;; Error tests
(deftest file-namestring.error.1
(signals-error (file-namestring) program-error)
t)
(deftest file-namestring.error.2
(signals-error (file-namestring "file-namestring.txt" nil)
program-error)
t)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/pathnames/file-namestring.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests for FILE-NAMESTRING
Error tests | Author :
Created : Sat Sep 11 07:40:47 2004
(deftest file-namestring.1
(let* ((vals (multiple-value-list
(file-namestring "file-namestring.txt")))
(s (first vals)))
(if (and (null (cdr vals))
(stringp s)
(equal (file-namestring s) s))
:good
vals))
:good)
(deftest file-namestring.2
(do-special-strings
(s "file-namestring.txt" nil)
(let ((ns (file-namestring s)))
(assert (stringp ns))
(assert (string= (file-namestring ns) ns))))
nil)
(deftest file-namestring.3
(let* ((name "file-namestring.txt")
(pn (merge-pathnames (pathname name)))
(name2 (with-open-file (s pn :direction :input)
(file-namestring s)))
(name3 (file-namestring pn)))
(or (equalt name2 name3) (list name2 name3)))
t)
(deftest file-namestring.error.1
(signals-error (file-namestring) program-error)
t)
(deftest file-namestring.error.2
(signals-error (file-namestring "file-namestring.txt" nil)
program-error)
t)
|
91165330e04fcd79ca8f93c94e56b199d31a5edf91290489b36cffb0ddf060bb | smallmelon/sdzmmo | lib_mon.erl | %%%-----------------------------------
%%% @Module : lib_mon
@Author : xyao
%%% @Email :
@Created : 2010.05.08
%%% @Description: 怪物
%%%-----------------------------------
-module(lib_mon).
-include("common.hrl").
-include("record.hrl").
-export(
[
get_name_by_mon_id/1,
get_scene_by_mon_id/1
]
).
%% 获取MON当前场景信息
get_scene_by_mon_id(MonId) ->
case ets:match(?ETS_MON, #ets_mon{mid = MonId, scene = '$1', x = '$2', y = '$3', _ = '_'}) of
[] -> 0;
[[Scene, X, Y]|_] -> [Scene, X, Y]
end.
%% 获取mon名称用mon数据库id
get_name_by_mon_id(MonId)->
case data_mon:get(MonId) of
[] -> <<"">>;
Mon -> Mon#ets_mon.name
end.
| null | https://raw.githubusercontent.com/smallmelon/sdzmmo/254ff430481de474527c0e96202c63fb0d2c29d2/src/lib/lib_mon.erl | erlang | -----------------------------------
@Module : lib_mon
@Email :
@Description: 怪物
-----------------------------------
获取MON当前场景信息
获取mon名称用mon数据库id
| @Author : xyao
@Created : 2010.05.08
-module(lib_mon).
-include("common.hrl").
-include("record.hrl").
-export(
[
get_name_by_mon_id/1,
get_scene_by_mon_id/1
]
).
get_scene_by_mon_id(MonId) ->
case ets:match(?ETS_MON, #ets_mon{mid = MonId, scene = '$1', x = '$2', y = '$3', _ = '_'}) of
[] -> 0;
[[Scene, X, Y]|_] -> [Scene, X, Y]
end.
get_name_by_mon_id(MonId)->
case data_mon:get(MonId) of
[] -> <<"">>;
Mon -> Mon#ets_mon.name
end.
|
d2ff81b7d49c74ca4954aa284253c617bc71f1e03a4b34cc05c85b2b918094da | sonian/carica | core.clj | (ns carica.test.core
(:require [carica.core :refer :all]
[clojure.test :refer :all]
[clojure.tools.logging.impl :refer [write!]]
[clojure.java.io :as io]))
(deftest config-test
(testing "config"
(testing "should offer a map of settings"
(is (map? (config :nested-one-clj)))
(testing "with the ability to get at nested values"
(is (= "test-clj" (config :nested-one-clj :test-clj)))))
(testing "should merge all maps on the classpath"
(is (= true (config :from-test)))
(is (= true (config :from-etc)))
(testing "but the first on the classpath should win"
(is (= "test" (config :merged-val)))))
(testing "should be overridden with override-config"
(with-redefs [config (override-config
{:nested-multi-json {:test-json {:test-json 21}
:hello :world}})]
(is (= :world (config :nested-multi-json :hello)))
(is (= 21 (config :nested-multi-json :test-json :test-json)))))
(testing "even if it's all made up"
(with-redefs [config (override-config :common :apply :hash-map)]
(is (= :hash-map (config :common :apply)))))
(testing "should return nil and warn if a key isn't found"
(let [called (atom false)]
(with-redefs [write! (fn [& _] (do (reset! called true) nil))]
(is (nil? (config :test-multi-clj :non-existent-key)))
(is @called))))
(testing "should return nil and not warn if a key has a nil value"
(let [called (atom false)]
(with-redefs [write! (fn [& _] (do (reset! called true) nil))]
(is (nil? (config :nil-val)))
(is (not @called)))))))
(deftest test-dynamic-config
(testing "config should be dynamic, for runtime repl overrides"
(is (.isDynamic #'config)))
(testing "also, it should work when rebound"
;; this is the same test as 'should be overridden with
;; override-config' above, only rewritten to use binding
(binding [config (override-config
{:nested-multi-json {:test-json {:test-json 21}
:hello :world}})]
(is (= :world (config :nested-multi-json :hello)))
(is (= 21 (config :nested-multi-json :test-json :test-json))))
(binding [config (override-config :common :apply :hash-map)]
(is (= :hash-map (config :common :apply))))))
(deftest test-json-config
(is (= 42 (config :json-only :nested))))
(deftest test-jar-json-config-loading
;; make sure we get the missing jar exception, not the exception
;; that comes from calling `file` on a jar: URL
(is (thrown? java.io.IOException
(load-config (java.net.URL. "jar:file!/bar.json")))))
(deftest nested-config-redefs-are-okay
(with-redefs [config (override-config :foo {:baz 42 :quux :x})]
(with-redefs [config (override-config :foo {:quux :y})]
(is (= (config :foo) {:baz 42 :quux :y})))))
(deftest nested-missing-keys-are-acceptable
(with-redefs [write! (fn [& _] nil)]
(is (not (config :nested-multi-clj :missing :missing :missing :missing)))))
(deftest nil-resources-are-handled
(is (= (get-configs [(resources "config.clj")])
(get-configs [nil (resources "config.clj") nil [nil nil]]))))
(deftest test-edn-config
(is (= "test-edn" (config :test-edn))))
(deftest test-config-embedded-in-jar
(let [jar (-> "uberjared.jar" io/resource str)
url (java.net.URL. (str "jar:" jar "!/config.edn"))
cfg (configurer [url])]
(is (= true (cfg :jar-resource)))))
(deftest test-configurer-with-other-io-types
(let [config (configurer ["test/config.edn"])]
(is (= "test-edn" (config :test-edn))))
(let [config (configurer [(io/file "test/config.edn")])]
(is (= "test-edn" (config :test-edn)))))
(deftest test-configurer-closes-its-stream
(let [config (configurer ["test/config.edn"] [])]
(try
(dotimes [_ 100000]
(config :test-edn))
(catch java.io.IOException e
(is false "should close input stream")))))
(deftest test-clj-vs-edn
(with-redefs [write! (fn [& _] nil)]
(let [edn-config (configurer (resources "edn-reader-config.edn") [])
clj-config (configurer (resources "config.clj") [])]
(is (= '(quote [a b c]) (clj-config :quoted-vectors-work)))
(is (= 42 (clj-config :read-eval-works)))
;; quoted vectors in edn aren't read as one might expect. They
end up as a map like { : foo } and throw an error . Carica
;; catches the error and sends a warning to the log.
(is (thrown-with-msg? Exception #"^error reading config.*"
(edn-config :quoted-vectors-fail))))))
| null | https://raw.githubusercontent.com/sonian/carica/d91ad15f7478ef267bce7383fca5788fd9033a96/test/carica/test/core.clj | clojure | this is the same test as 'should be overridden with
override-config' above, only rewritten to use binding
make sure we get the missing jar exception, not the exception
that comes from calling `file` on a jar: URL
quoted vectors in edn aren't read as one might expect. They
catches the error and sends a warning to the log. | (ns carica.test.core
(:require [carica.core :refer :all]
[clojure.test :refer :all]
[clojure.tools.logging.impl :refer [write!]]
[clojure.java.io :as io]))
(deftest config-test
(testing "config"
(testing "should offer a map of settings"
(is (map? (config :nested-one-clj)))
(testing "with the ability to get at nested values"
(is (= "test-clj" (config :nested-one-clj :test-clj)))))
(testing "should merge all maps on the classpath"
(is (= true (config :from-test)))
(is (= true (config :from-etc)))
(testing "but the first on the classpath should win"
(is (= "test" (config :merged-val)))))
(testing "should be overridden with override-config"
(with-redefs [config (override-config
{:nested-multi-json {:test-json {:test-json 21}
:hello :world}})]
(is (= :world (config :nested-multi-json :hello)))
(is (= 21 (config :nested-multi-json :test-json :test-json)))))
(testing "even if it's all made up"
(with-redefs [config (override-config :common :apply :hash-map)]
(is (= :hash-map (config :common :apply)))))
(testing "should return nil and warn if a key isn't found"
(let [called (atom false)]
(with-redefs [write! (fn [& _] (do (reset! called true) nil))]
(is (nil? (config :test-multi-clj :non-existent-key)))
(is @called))))
(testing "should return nil and not warn if a key has a nil value"
(let [called (atom false)]
(with-redefs [write! (fn [& _] (do (reset! called true) nil))]
(is (nil? (config :nil-val)))
(is (not @called)))))))
(deftest test-dynamic-config
(testing "config should be dynamic, for runtime repl overrides"
(is (.isDynamic #'config)))
(testing "also, it should work when rebound"
(binding [config (override-config
{:nested-multi-json {:test-json {:test-json 21}
:hello :world}})]
(is (= :world (config :nested-multi-json :hello)))
(is (= 21 (config :nested-multi-json :test-json :test-json))))
(binding [config (override-config :common :apply :hash-map)]
(is (= :hash-map (config :common :apply))))))
(deftest test-json-config
(is (= 42 (config :json-only :nested))))
(deftest test-jar-json-config-loading
(is (thrown? java.io.IOException
(load-config (java.net.URL. "jar:file!/bar.json")))))
(deftest nested-config-redefs-are-okay
(with-redefs [config (override-config :foo {:baz 42 :quux :x})]
(with-redefs [config (override-config :foo {:quux :y})]
(is (= (config :foo) {:baz 42 :quux :y})))))
(deftest nested-missing-keys-are-acceptable
(with-redefs [write! (fn [& _] nil)]
(is (not (config :nested-multi-clj :missing :missing :missing :missing)))))
(deftest nil-resources-are-handled
(is (= (get-configs [(resources "config.clj")])
(get-configs [nil (resources "config.clj") nil [nil nil]]))))
(deftest test-edn-config
(is (= "test-edn" (config :test-edn))))
(deftest test-config-embedded-in-jar
(let [jar (-> "uberjared.jar" io/resource str)
url (java.net.URL. (str "jar:" jar "!/config.edn"))
cfg (configurer [url])]
(is (= true (cfg :jar-resource)))))
(deftest test-configurer-with-other-io-types
(let [config (configurer ["test/config.edn"])]
(is (= "test-edn" (config :test-edn))))
(let [config (configurer [(io/file "test/config.edn")])]
(is (= "test-edn" (config :test-edn)))))
(deftest test-configurer-closes-its-stream
(let [config (configurer ["test/config.edn"] [])]
(try
(dotimes [_ 100000]
(config :test-edn))
(catch java.io.IOException e
(is false "should close input stream")))))
(deftest test-clj-vs-edn
(with-redefs [write! (fn [& _] nil)]
(let [edn-config (configurer (resources "edn-reader-config.edn") [])
clj-config (configurer (resources "config.clj") [])]
(is (= '(quote [a b c]) (clj-config :quoted-vectors-work)))
(is (= 42 (clj-config :read-eval-works)))
end up as a map like { : foo } and throw an error . Carica
(is (thrown-with-msg? Exception #"^error reading config.*"
(edn-config :quoted-vectors-fail))))))
|
48fdb884eac30aae2060b3bb6c1f4ef7bf71dc9249ed8d3168817057224d7f97 | fendor/hsimport | SymbolTest7.hs | module Test where
import Foo.Bar
import Foo.Bar.Blub
import Ugah.Argh
import qualified Control.Monad as M
f :: Int -> Int
f = (+ 3)
| null | https://raw.githubusercontent.com/fendor/hsimport/9be9918b06545cfd7282e4db08c2b88f1d8162cd/tests/inputFiles/SymbolTest7.hs | haskell | module Test where
import Foo.Bar
import Foo.Bar.Blub
import Ugah.Argh
import qualified Control.Monad as M
f :: Int -> Int
f = (+ 3)
|
|
583b62e3d569b6481b590558bfe01373d7e21ab6708d73ce412a5c212da203d3 | flyingmachine/pegthing | core_test.clj | (ns pegthing.core-test
(:require [clojure.test :refer :all]
[pegthing.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/flyingmachine/pegthing/c5d62f44a229964a0fa25b1fec0ceab2651fb436/test/pegthing/core_test.clj | clojure | (ns pegthing.core-test
(:require [clojure.test :refer :all]
[pegthing.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
|
|
31d28e1053b0c943821d13a2b7b29927d853c240a4e57e7ae9ad0aa2c88524b1 | jacobobryant/platypub | sites.clj | (ns com.platypub.feat.sites
(:require [com.biffweb :as biff :refer [q]]
[com.platypub.middleware :as mid]
[com.platypub.netlify :as netlify]
[com.platypub.ui :as ui]
[com.platypub.util :as util]
[clj-http.client :as http]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.logging :as log]
[xtdb.api :as xt]
[ring.middleware.anti-forgery :as anti-forgery]
[ring.util.io :as ring-io]
[ring.util.mime-type :as mime]
[lambdaisland.uri :as uri]
[babashka.fs :as fs]))
(defn edit-site [{:keys [site params] :as sys}]
(biff/submit-tx sys
[(into
{:db/doc-type :site
:xt/id (:xt/id site)
:db/op :update
:site/title (:title params)
:site/url (:url params)
:site/theme (:theme params)}
(util/params->custom-fields sys))])
{:status 303
:headers {"location" (util/make-url "sites" (:xt/id site))}})
(defn new-site [{:keys [session] :as req}]
(let [id (random-uuid)
{:keys [ssl_url
name
site_id]} (:body (netlify/create! req))]
(biff/submit-tx req
[{:db/doc-type :site
:xt/id id
:site/user (:uid session)
:site/url ssl_url
:site/title name
:site/theme "default"
:site/netlify-id site_id}])
{:status 303
:headers {"location" (str "/sites/" id)}}))
(defn delete-site [{:keys [path-params biff/db site] :as req}]
(netlify/delete! req {:site-id (:site/netlify-id site)})
(biff/submit-tx req
[{:xt/id (:xt/id site)
:db/op :delete}])
{:status 303
:headers {"location" "/sites"}})
(defn export [sys]
{:status 200
:headers {"content-type" "application/edn"
"content-disposition" "attachment; filename=\"input.edn\""}
:body (pr-str (util/get-render-opts sys))})
(defn generate! [{:keys [biff/db dir site params] :as sys}]
(let [render-opts (util/get-render-opts sys)
theme (:site/theme site)
theme-last-modified (->> (file-seq (io/file "themes" theme))
(filter #(.isFile %))
(map ring-io/last-modified-date)
(apply max-key inst-ms))
_hash (str (hash [render-opts theme-last-modified]))]
(when (or (:force params)
(not= (biff/catchall (slurp (io/file dir "_hash"))) _hash))
;; preinstall npm deps
(when (and (:com.platypub/copy-theme-npm-deps sys)
(.exists (io/file "themes" theme "package.json"))
(not (.exists (io/file "themes" theme "node_modules"))))
(biff/sh "npm" "install" :dir (str (io/file "themes" theme))))
;; copy theme code to new directory
(if (fs/which "rsync")
(do (io/make-parents dir)
(biff/sh "rsync" "-a" "--delete"
(str (io/file "themes" theme) "/")
(str dir "/"))
(fs/delete-tree (str dir "/public")))
(do (fs/delete-tree (str dir))
(io/make-parents dir)
(fs/copy-tree (str (io/file "themes" theme)) (str dir) {:copy-attributes true})))
;; install npm deps in new directory
(when-not (:com.platypub/copy-theme-npm-deps sys)
(fs/delete-tree (str dir "/node_modules"))
(when (.exists (io/file dir "package.json"))
(biff/sh "npm" "install" :dir (str dir))))
;; render
(spit (io/file dir "input.edn") (pr-str render-opts))
(some->> (util/run-theme-cmd (:site.config/render-site site ["./render-site"]) dir)
((juxt :out :err))
(keep not-empty)
(run! #(log/info %)))
(spit (io/file dir "_hash") _hash))))
(defn preview [{:keys [biff/db path-params params site] :as sys}]
(let [dir (io/file "storage/previews" (str (:xt/id site)))
_ (generate! (assoc sys :dir dir))
path (or (:path params) "/")
file (->> (file-seq (io/file dir "public"))
(filter (fn [file]
(and (.isFile file)
(= (str/replace (subs (.getPath file) (count (str dir "/public")))
#"/index.html$"
"/")
path))))
first)
rewrite-url (fn [href]
(let [url (uri/join (:site/url site) path href)]
(if (str/starts-with? (str url) (:site/url site))
(str "/sites/" (:xt/id site) "/preview?"
(uri/map->query-string {:path (:path url)}))
href)))
[mime body] (cond
(some-> file (.getPath) (str/ends-with? ".html"))
["text/html"
(str/replace (slurp file)
#"(href|src)=\"([^\"]+)\""
(fn [[_ attr href]]
(str attr "=\"" (rewrite-url href) "\"")))]
(some-> file (.getPath) (str/ends-with? ".css"))
["text/css"
(str/replace (slurp file)
#"url\(([^\)]+)\)"
(fn [[_ href]]
(str "url(" (rewrite-url href) ")")))])]
(cond
body {:status 200
:headers {"content-type" mime}
:body body}
file (util/serve-static-file file)
:else {:status 404
:headers {"content-type" "text/html"}
:body "<h1>Not found.</h1>"})))
(defn publish [{:keys [biff/db path-params site] :as sys}]
(let [dir (io/file "storage/deploys" (str (random-uuid)))]
(generate! (assoc sys :dir dir))
(netlify/deploy! {:api-key (util/get-secret sys :netlify/api-key)
:site-id (:site/netlify-id site)
:dir (str dir)})
(fs/delete-tree (str dir))
{:status 303
:headers {"location" "/sites"}}))
(defn custom-config [{:keys [path-params biff/db user site params] :as sys}]
(let [{:keys [theme]} params
site (if (contains? (set (util/installed-themes)) theme)
(merge (xt/entity db (:xt/id site))
(util/select-ns-as
(biff/catchall
(edn/read-string
(slurp (str "themes/" theme "/config.edn"))))
nil
'site.config))
site)]
[:div#custom-config
(for [k (:site.config/site-fields site)]
(list
(ui/custom-field sys k)
[:.h-3]))]))
(defn edit-site-page [{:keys [path-params biff/db user site] :as sys}]
(ui/nav-page
(merge sys
{:base/head [[:script (biff/unsafe (slurp (io/resource "darkmode.js")))]]
:current :sites})
[:.bg-gray-100.dark:bg-stone-800.dark:text-gray-50.flex-grow
[:.max-w-screen-sm
(biff/form
{:id "edit"
:action (str "/sites/" (:xt/id site))
:class '[flex flex-col flex-grow]}
(ui/text-input {:id "netlify-id" :label "Netlify ID" :value (:site/netlify-id site) :disabled true})
[:.h-3]
(ui/text-input {:id "url" :label "URL" :value (:site/url site)})
[:.h-3]
(ui/text-input {:id "title" :label "Title" :value (:site/title site)})
[:.h-3]
(ui/select {:id "theme"
:name "theme"
:label "Theme"
:value (:site/theme site)
:options (for [t (util/installed-themes)]
{:label t :value t})
:default (:site/theme site)
:hx-trigger "change"
:hx-get (str "/sites/" (:xt/id site) "/custom-config")
:hx-target "#custom-config"
:hx-swap "outerHTML"})
[:.h-3]
(custom-config sys)
[:.h-4]
[:button.btn.w-full {:type "submit"} "Save"])
[:.h-3]
(biff/form
{:onSubmit "return confirm('Delete site?')"
:method "POST"
:action (str "/sites/" (:xt/id site) "/delete")}
[:button.text-red-600.hover:text-red-700 {:type "submit"} "Delete"])
[:.h-6]]]))
(defn site-list-item [{:keys [site/title
site/url
xt/id
site.config/items]}]
[:.flex.items-center.mb-4
[:div
[:div [:a.link.text-lg {:href (str "/sites/" id)}
(or (not-empty (str/trim title)) "[No title]")]
[:span.md:hidden
" " biff/emdash " "
(util/join
", "
(for [{:keys [slug label]} items]
[:a.link.text-lg {:href (util/make-url "site" id slug)}
(str label "s")]))]]
[:.text-sm.text-stone-600.dark:text-stone-300
[:a.hover:underline {:href url :target "_blank"} "View"]
ui/interpunct
[:a.hover:underline {:href (str "/sites/" id "/preview?path=/")
:target "_blank"}
"Preview"]
ui/interpunct
[:a.hover:underline {:href (str "/sites/" id "/preview?force=true&path=/")
:target "_blank"}
"Force refresh"]
ui/interpunct
(biff/form
{:method "POST"
:action (str "/sites/" id "/publish")
:class "inline-block"}
[:button.hover:underline {:type "submit"} "Publish"])
ui/interpunct
[:a.hover:underline {:href (str "/sites/" id "/export")
:target "_blank"}
"Export"]]]])
(defn sites-page [{:keys [sites] :as sys}]
(ui/nav-page
(merge sys {:current :sites})
(biff/form
{:action "/sites"}
(when (nil? (util/get-secret sys :netlify/api-key))
[:p "You need to enter a Netlify API key"])
[:button.btn {:type "submit"
:disabled (nil? (util/get-secret sys :netlify/api-key))} "New site"])
[:.h-6]
(->> sites
(sort-by :site/title)
(map site-list-item))))
(def features
{:routes ["" {:middleware [mid/wrap-signed-in]}
["/sites" {:get sites-page
:post new-site}]
["/sites/:site-id"
["" {:get edit-site-page
:post edit-site}]
["/custom-config" {:get custom-config}]
["/delete" {:post delete-site}]
["/publish" {:post publish}]
["/preview" {:get preview}]
["/export" {:get export}]]]})
| null | https://raw.githubusercontent.com/jacobobryant/platypub/59e915d9ac5c0d30c873d7d85df79c26c0e7df58/src/com/platypub/feat/sites.clj | clojure | preinstall npm deps
copy theme code to new directory
install npm deps in new directory
render | (ns com.platypub.feat.sites
(:require [com.biffweb :as biff :refer [q]]
[com.platypub.middleware :as mid]
[com.platypub.netlify :as netlify]
[com.platypub.ui :as ui]
[com.platypub.util :as util]
[clj-http.client :as http]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.logging :as log]
[xtdb.api :as xt]
[ring.middleware.anti-forgery :as anti-forgery]
[ring.util.io :as ring-io]
[ring.util.mime-type :as mime]
[lambdaisland.uri :as uri]
[babashka.fs :as fs]))
(defn edit-site [{:keys [site params] :as sys}]
(biff/submit-tx sys
[(into
{:db/doc-type :site
:xt/id (:xt/id site)
:db/op :update
:site/title (:title params)
:site/url (:url params)
:site/theme (:theme params)}
(util/params->custom-fields sys))])
{:status 303
:headers {"location" (util/make-url "sites" (:xt/id site))}})
(defn new-site [{:keys [session] :as req}]
(let [id (random-uuid)
{:keys [ssl_url
name
site_id]} (:body (netlify/create! req))]
(biff/submit-tx req
[{:db/doc-type :site
:xt/id id
:site/user (:uid session)
:site/url ssl_url
:site/title name
:site/theme "default"
:site/netlify-id site_id}])
{:status 303
:headers {"location" (str "/sites/" id)}}))
(defn delete-site [{:keys [path-params biff/db site] :as req}]
(netlify/delete! req {:site-id (:site/netlify-id site)})
(biff/submit-tx req
[{:xt/id (:xt/id site)
:db/op :delete}])
{:status 303
:headers {"location" "/sites"}})
(defn export [sys]
{:status 200
:headers {"content-type" "application/edn"
"content-disposition" "attachment; filename=\"input.edn\""}
:body (pr-str (util/get-render-opts sys))})
(defn generate! [{:keys [biff/db dir site params] :as sys}]
(let [render-opts (util/get-render-opts sys)
theme (:site/theme site)
theme-last-modified (->> (file-seq (io/file "themes" theme))
(filter #(.isFile %))
(map ring-io/last-modified-date)
(apply max-key inst-ms))
_hash (str (hash [render-opts theme-last-modified]))]
(when (or (:force params)
(not= (biff/catchall (slurp (io/file dir "_hash"))) _hash))
(when (and (:com.platypub/copy-theme-npm-deps sys)
(.exists (io/file "themes" theme "package.json"))
(not (.exists (io/file "themes" theme "node_modules"))))
(biff/sh "npm" "install" :dir (str (io/file "themes" theme))))
(if (fs/which "rsync")
(do (io/make-parents dir)
(biff/sh "rsync" "-a" "--delete"
(str (io/file "themes" theme) "/")
(str dir "/"))
(fs/delete-tree (str dir "/public")))
(do (fs/delete-tree (str dir))
(io/make-parents dir)
(fs/copy-tree (str (io/file "themes" theme)) (str dir) {:copy-attributes true})))
(when-not (:com.platypub/copy-theme-npm-deps sys)
(fs/delete-tree (str dir "/node_modules"))
(when (.exists (io/file dir "package.json"))
(biff/sh "npm" "install" :dir (str dir))))
(spit (io/file dir "input.edn") (pr-str render-opts))
(some->> (util/run-theme-cmd (:site.config/render-site site ["./render-site"]) dir)
((juxt :out :err))
(keep not-empty)
(run! #(log/info %)))
(spit (io/file dir "_hash") _hash))))
(defn preview [{:keys [biff/db path-params params site] :as sys}]
(let [dir (io/file "storage/previews" (str (:xt/id site)))
_ (generate! (assoc sys :dir dir))
path (or (:path params) "/")
file (->> (file-seq (io/file dir "public"))
(filter (fn [file]
(and (.isFile file)
(= (str/replace (subs (.getPath file) (count (str dir "/public")))
#"/index.html$"
"/")
path))))
first)
rewrite-url (fn [href]
(let [url (uri/join (:site/url site) path href)]
(if (str/starts-with? (str url) (:site/url site))
(str "/sites/" (:xt/id site) "/preview?"
(uri/map->query-string {:path (:path url)}))
href)))
[mime body] (cond
(some-> file (.getPath) (str/ends-with? ".html"))
["text/html"
(str/replace (slurp file)
#"(href|src)=\"([^\"]+)\""
(fn [[_ attr href]]
(str attr "=\"" (rewrite-url href) "\"")))]
(some-> file (.getPath) (str/ends-with? ".css"))
["text/css"
(str/replace (slurp file)
#"url\(([^\)]+)\)"
(fn [[_ href]]
(str "url(" (rewrite-url href) ")")))])]
(cond
body {:status 200
:headers {"content-type" mime}
:body body}
file (util/serve-static-file file)
:else {:status 404
:headers {"content-type" "text/html"}
:body "<h1>Not found.</h1>"})))
(defn publish [{:keys [biff/db path-params site] :as sys}]
(let [dir (io/file "storage/deploys" (str (random-uuid)))]
(generate! (assoc sys :dir dir))
(netlify/deploy! {:api-key (util/get-secret sys :netlify/api-key)
:site-id (:site/netlify-id site)
:dir (str dir)})
(fs/delete-tree (str dir))
{:status 303
:headers {"location" "/sites"}}))
(defn custom-config [{:keys [path-params biff/db user site params] :as sys}]
(let [{:keys [theme]} params
site (if (contains? (set (util/installed-themes)) theme)
(merge (xt/entity db (:xt/id site))
(util/select-ns-as
(biff/catchall
(edn/read-string
(slurp (str "themes/" theme "/config.edn"))))
nil
'site.config))
site)]
[:div#custom-config
(for [k (:site.config/site-fields site)]
(list
(ui/custom-field sys k)
[:.h-3]))]))
(defn edit-site-page [{:keys [path-params biff/db user site] :as sys}]
(ui/nav-page
(merge sys
{:base/head [[:script (biff/unsafe (slurp (io/resource "darkmode.js")))]]
:current :sites})
[:.bg-gray-100.dark:bg-stone-800.dark:text-gray-50.flex-grow
[:.max-w-screen-sm
(biff/form
{:id "edit"
:action (str "/sites/" (:xt/id site))
:class '[flex flex-col flex-grow]}
(ui/text-input {:id "netlify-id" :label "Netlify ID" :value (:site/netlify-id site) :disabled true})
[:.h-3]
(ui/text-input {:id "url" :label "URL" :value (:site/url site)})
[:.h-3]
(ui/text-input {:id "title" :label "Title" :value (:site/title site)})
[:.h-3]
(ui/select {:id "theme"
:name "theme"
:label "Theme"
:value (:site/theme site)
:options (for [t (util/installed-themes)]
{:label t :value t})
:default (:site/theme site)
:hx-trigger "change"
:hx-get (str "/sites/" (:xt/id site) "/custom-config")
:hx-target "#custom-config"
:hx-swap "outerHTML"})
[:.h-3]
(custom-config sys)
[:.h-4]
[:button.btn.w-full {:type "submit"} "Save"])
[:.h-3]
(biff/form
{:onSubmit "return confirm('Delete site?')"
:method "POST"
:action (str "/sites/" (:xt/id site) "/delete")}
[:button.text-red-600.hover:text-red-700 {:type "submit"} "Delete"])
[:.h-6]]]))
(defn site-list-item [{:keys [site/title
site/url
xt/id
site.config/items]}]
[:.flex.items-center.mb-4
[:div
[:div [:a.link.text-lg {:href (str "/sites/" id)}
(or (not-empty (str/trim title)) "[No title]")]
[:span.md:hidden
" " biff/emdash " "
(util/join
", "
(for [{:keys [slug label]} items]
[:a.link.text-lg {:href (util/make-url "site" id slug)}
(str label "s")]))]]
[:.text-sm.text-stone-600.dark:text-stone-300
[:a.hover:underline {:href url :target "_blank"} "View"]
ui/interpunct
[:a.hover:underline {:href (str "/sites/" id "/preview?path=/")
:target "_blank"}
"Preview"]
ui/interpunct
[:a.hover:underline {:href (str "/sites/" id "/preview?force=true&path=/")
:target "_blank"}
"Force refresh"]
ui/interpunct
(biff/form
{:method "POST"
:action (str "/sites/" id "/publish")
:class "inline-block"}
[:button.hover:underline {:type "submit"} "Publish"])
ui/interpunct
[:a.hover:underline {:href (str "/sites/" id "/export")
:target "_blank"}
"Export"]]]])
(defn sites-page [{:keys [sites] :as sys}]
(ui/nav-page
(merge sys {:current :sites})
(biff/form
{:action "/sites"}
(when (nil? (util/get-secret sys :netlify/api-key))
[:p "You need to enter a Netlify API key"])
[:button.btn {:type "submit"
:disabled (nil? (util/get-secret sys :netlify/api-key))} "New site"])
[:.h-6]
(->> sites
(sort-by :site/title)
(map site-list-item))))
(def features
{:routes ["" {:middleware [mid/wrap-signed-in]}
["/sites" {:get sites-page
:post new-site}]
["/sites/:site-id"
["" {:get edit-site-page
:post edit-site}]
["/custom-config" {:get custom-config}]
["/delete" {:post delete-site}]
["/publish" {:post publish}]
["/preview" {:get preview}]
["/export" {:get export}]]]})
|
be2af92bcae4bc81c6fe6c001ed8a0c9db588a1cbb2e4cb60ffe4403fd3f029a | lillo/compiler-course-unipi | fun_cfa.ml | (**
Type representing the label associated to each sub-expression
*)
type label = int
[@@deriving show, eq, ord]
*
To make our analysis precise , we usually assume that bound variables
are distinct . To achieve that we represent a variable as an identifier and a unique
label . Thus , the pair ( name , i d ) are unique inside the expression to analyze .
Actually , i d is the declaration site , i.e. , the label of the program point where the variable is declared .
For example , { name="x";id=5 } denotes the variables x declared in the program point 5 .
To make our analysis precise, we usually assume that bound variables
are distinct. To achieve that we represent a variable as an identifier and a unique
label. Thus, the pair (name, id) are unique inside the expression to analyze.
Actually, id is the declaration site, i.e., the label of the program point where the variable is declared.
For example, {name="x";id=5} denotes the variables x declared in the program point 5.
*)
type var = { name : string ; id : label }
[@@deriving show, eq, ord]
(**
An annotated expression is made of a term and of a unique label
*)
type aexpr = { t : term ; l : label }
[@@deriving show]
and term =
| CstI of int
| CstB of bool
| Var of var
| Let of var * aexpr * aexpr
| Prim of string * aexpr * aexpr
| If of aexpr * aexpr * aexpr
( f , x , fBody , letBody )
| Call of aexpr * aexpr
[@@deriving show]
*
[ to_aexpr e ] returns an annotated version of
[to_aexpr e] returns an annotated version of e.
*)
let to_aexpr (e : Fun.expr) : aexpr =
let counter = ref(0) in (* counter to generated unique labels *)
let next_label () = incr counter; !counter in (* returns a new label *)
let mk_aexpr t = { t = t ; l = next_label ()} in (* helper to build an annotated expression from a term *)
(* tail recursive helper function to carry out the annotation.
env is an enrivonment storing for each variable the corresponding unique id.
*)
let rec transform env = function
| Fun.CstI(i) -> CstI(i) |> mk_aexpr
| Fun.CstB(b) -> CstB(b) |> mk_aexpr
| Fun.Var(id) -> Var({name = id; id = Fun.lookup env id }) |> mk_aexpr
| Fun.Let(x, e1, e2) ->
let ae1 = transform env e1 in
let var_id = next_label() in
let ae2 = transform ((x, var_id)::env) e2 in
Let({name = x; id = var_id}, ae1, ae2) |> mk_aexpr
| Fun.Prim(op, e1, e2) ->
let ae1 = transform env e1 in
let ae2 = transform env e2 in
Prim(op, ae1, ae2) |> mk_aexpr
| Fun.If(e1, e2, e3) ->
let ae1 = transform env e1 in
let ae2 = transform env e2 in
let ae3 = transform env e3 in
If(ae1, ae2, ae3) |> mk_aexpr
| Fun.Letfun(f, x, _, body, exp) ->
let fvar = { name = f; id = next_label () } in
let xvar = { name = x; id = next_label () } in
let abody = transform ((fvar.name, fvar.id)::(xvar.name, xvar.id)::env) body in
let aexp = transform ((fvar.name, fvar.id)::env) exp in
Letfun(fvar, xvar, abody, aexp) |> mk_aexpr
| Fun.Call(e1, e2) ->
let ae1 = transform env e1 in
let ae2 = transform env e2 in
Call(ae1, ae2) |> mk_aexpr
in
transform [] e
type cvar = IdVar of var [ @printer fun fmt v - > Format.fprintf fmt " r(%s:%d ) " v.name v.id ]
| CacheVar of label [ @printer fun fmt c - > Format.fprintf fmt " C(%d ) " c ]
[ @@deriving show { with_path = false } , eq , ord ]
type token = var
[ @@deriving show , eq , ord ]
type cvar = IdVar of var [@printer fun fmt v -> Format.fprintf fmt "r(%s:%d)" v.name v.id]
| CacheVar of label [@printer fun fmt c -> Format.fprintf fmt "C(%d)" c]
[@@deriving show{ with_path = false }, eq, ord]
type token = var
[@@deriving show, eq, ord]
*)
* Our solver is parametric on the type of variables .
The module Var defines a type t that express both cache entries and environment entries .
The module Var defines a type t that express both cache entries and environment entries.
*)
module Var =
struct
type t =
(* IdVar(v) is a variable representing the entry in the environment for the identifier v *)
| IdVar of var [@printer fun fmt v -> Format.fprintf fmt "r(%s:%d)" v.name v.id]
(* CacheVar(l) is a variable representing the entry in the cache for the label l *)
| CacheVar of label [@printer fun fmt c -> Format.fprintf fmt "C(%d)" c]
[@@deriving show{ with_path = false }, eq, ord]
end
(** Our solver is parametric on the type of tokens.
The module Token defines a type t that represent the name and the definition site of a function.
*)
module Token =
struct
type t = var
[@@deriving show, eq, ord]
end
* Solver is an instantiation of the CFA solver for the language fun
module Solver = Cfa_solver.Make(Token)(Var)
(** [lambdas e] returns a list of the all function definition occurring in e *)
let lambdas e =
let rec f_aux e acc =
match e.t with
| CstI(_)
| CstB(_)
| Var(_) -> acc
| Let(_, e1, e2)
| Prim(_, e1, e2)
| Call(e1, e2) -> acc |> f_aux e1 |> f_aux e2
| If(e1, e2, e3) -> acc |> f_aux e1 |> f_aux e2 |> f_aux e3
| Letfun(f, x, body, exp) ->
(f,x,body)::acc |> f_aux body |> f_aux exp
in
f_aux e []
* [ constrs_of_aexpr ae ] returns the CFA constraints for the annotated expression ae .
let constrs_of_aexpr aexp =
let lambda_star = lambdas aexp in
let open Solver in
let rec f_aux e acc =
match e.t with
| CstI(_)
| CstB(_) -> acc
| Var(v) -> (IdVar(v) @< CacheVar(e.l)) :: acc
| Prim(_, e1, e2) -> acc |> f_aux e1 |> f_aux e2
| Let(x, e1, e2) ->
let acc' = (CacheVar(e1.l) @< IdVar(x)) :: (CacheVar(e2.l) @< CacheVar(e.l)) :: acc in
acc' |> f_aux e1 |> f_aux e2
| If(e1, e2, e3) ->
let acc' = (CacheVar(e2.l) @< CacheVar(e.l)) :: (CacheVar(e3.l) @< CacheVar(e.l)) :: acc in
acc' |> f_aux e1 |> f_aux e2 |> f_aux e3
| Letfun(f, x, body, exp) ->
let acc' = (f @^ IdVar(f)) :: (CacheVar(exp.l) @< CacheVar(e.l)) :: acc in
acc' |> f_aux body |> f_aux exp
| Call(e1, e2) ->
let acc' = List.fold_left (fun cs (f,x,e') ->
((f @^ CacheVar(e1.l)) @~~> (CacheVar(e2.l) @< IdVar(x))) ::
((f @^ CacheVar(e1.l)) @~~> (CacheVar(e'.l) @< CacheVar(e.l))) :: cs
) acc lambda_star
in
acc' |> f_aux e1 |> f_aux e2
in
f_aux aexp []
| null | https://raw.githubusercontent.com/lillo/compiler-course-unipi/1a5e909da6a2cc79e6f80645cd24fb5ff285be54/semantic-analysis-material/code/fun-cfa/fun_cfa.ml | ocaml | *
Type representing the label associated to each sub-expression
*
An annotated expression is made of a term and of a unique label
counter to generated unique labels
returns a new label
helper to build an annotated expression from a term
tail recursive helper function to carry out the annotation.
env is an enrivonment storing for each variable the corresponding unique id.
IdVar(v) is a variable representing the entry in the environment for the identifier v
CacheVar(l) is a variable representing the entry in the cache for the label l
* Our solver is parametric on the type of tokens.
The module Token defines a type t that represent the name and the definition site of a function.
* [lambdas e] returns a list of the all function definition occurring in e | type label = int
[@@deriving show, eq, ord]
*
To make our analysis precise , we usually assume that bound variables
are distinct . To achieve that we represent a variable as an identifier and a unique
label . Thus , the pair ( name , i d ) are unique inside the expression to analyze .
Actually , i d is the declaration site , i.e. , the label of the program point where the variable is declared .
For example , { name="x";id=5 } denotes the variables x declared in the program point 5 .
To make our analysis precise, we usually assume that bound variables
are distinct. To achieve that we represent a variable as an identifier and a unique
label. Thus, the pair (name, id) are unique inside the expression to analyze.
Actually, id is the declaration site, i.e., the label of the program point where the variable is declared.
For example, {name="x";id=5} denotes the variables x declared in the program point 5.
*)
type var = { name : string ; id : label }
[@@deriving show, eq, ord]
type aexpr = { t : term ; l : label }
[@@deriving show]
and term =
| CstI of int
| CstB of bool
| Var of var
| Let of var * aexpr * aexpr
| Prim of string * aexpr * aexpr
| If of aexpr * aexpr * aexpr
( f , x , fBody , letBody )
| Call of aexpr * aexpr
[@@deriving show]
*
[ to_aexpr e ] returns an annotated version of
[to_aexpr e] returns an annotated version of e.
*)
let to_aexpr (e : Fun.expr) : aexpr =
let rec transform env = function
| Fun.CstI(i) -> CstI(i) |> mk_aexpr
| Fun.CstB(b) -> CstB(b) |> mk_aexpr
| Fun.Var(id) -> Var({name = id; id = Fun.lookup env id }) |> mk_aexpr
| Fun.Let(x, e1, e2) ->
let ae1 = transform env e1 in
let var_id = next_label() in
let ae2 = transform ((x, var_id)::env) e2 in
Let({name = x; id = var_id}, ae1, ae2) |> mk_aexpr
| Fun.Prim(op, e1, e2) ->
let ae1 = transform env e1 in
let ae2 = transform env e2 in
Prim(op, ae1, ae2) |> mk_aexpr
| Fun.If(e1, e2, e3) ->
let ae1 = transform env e1 in
let ae2 = transform env e2 in
let ae3 = transform env e3 in
If(ae1, ae2, ae3) |> mk_aexpr
| Fun.Letfun(f, x, _, body, exp) ->
let fvar = { name = f; id = next_label () } in
let xvar = { name = x; id = next_label () } in
let abody = transform ((fvar.name, fvar.id)::(xvar.name, xvar.id)::env) body in
let aexp = transform ((fvar.name, fvar.id)::env) exp in
Letfun(fvar, xvar, abody, aexp) |> mk_aexpr
| Fun.Call(e1, e2) ->
let ae1 = transform env e1 in
let ae2 = transform env e2 in
Call(ae1, ae2) |> mk_aexpr
in
transform [] e
type cvar = IdVar of var [ @printer fun fmt v - > Format.fprintf fmt " r(%s:%d ) " v.name v.id ]
| CacheVar of label [ @printer fun fmt c - > Format.fprintf fmt " C(%d ) " c ]
[ @@deriving show { with_path = false } , eq , ord ]
type token = var
[ @@deriving show , eq , ord ]
type cvar = IdVar of var [@printer fun fmt v -> Format.fprintf fmt "r(%s:%d)" v.name v.id]
| CacheVar of label [@printer fun fmt c -> Format.fprintf fmt "C(%d)" c]
[@@deriving show{ with_path = false }, eq, ord]
type token = var
[@@deriving show, eq, ord]
*)
* Our solver is parametric on the type of variables .
The module Var defines a type t that express both cache entries and environment entries .
The module Var defines a type t that express both cache entries and environment entries.
*)
module Var =
struct
type t =
| IdVar of var [@printer fun fmt v -> Format.fprintf fmt "r(%s:%d)" v.name v.id]
| CacheVar of label [@printer fun fmt c -> Format.fprintf fmt "C(%d)" c]
[@@deriving show{ with_path = false }, eq, ord]
end
module Token =
struct
type t = var
[@@deriving show, eq, ord]
end
* Solver is an instantiation of the CFA solver for the language fun
module Solver = Cfa_solver.Make(Token)(Var)
let lambdas e =
let rec f_aux e acc =
match e.t with
| CstI(_)
| CstB(_)
| Var(_) -> acc
| Let(_, e1, e2)
| Prim(_, e1, e2)
| Call(e1, e2) -> acc |> f_aux e1 |> f_aux e2
| If(e1, e2, e3) -> acc |> f_aux e1 |> f_aux e2 |> f_aux e3
| Letfun(f, x, body, exp) ->
(f,x,body)::acc |> f_aux body |> f_aux exp
in
f_aux e []
* [ constrs_of_aexpr ae ] returns the CFA constraints for the annotated expression ae .
let constrs_of_aexpr aexp =
let lambda_star = lambdas aexp in
let open Solver in
let rec f_aux e acc =
match e.t with
| CstI(_)
| CstB(_) -> acc
| Var(v) -> (IdVar(v) @< CacheVar(e.l)) :: acc
| Prim(_, e1, e2) -> acc |> f_aux e1 |> f_aux e2
| Let(x, e1, e2) ->
let acc' = (CacheVar(e1.l) @< IdVar(x)) :: (CacheVar(e2.l) @< CacheVar(e.l)) :: acc in
acc' |> f_aux e1 |> f_aux e2
| If(e1, e2, e3) ->
let acc' = (CacheVar(e2.l) @< CacheVar(e.l)) :: (CacheVar(e3.l) @< CacheVar(e.l)) :: acc in
acc' |> f_aux e1 |> f_aux e2 |> f_aux e3
| Letfun(f, x, body, exp) ->
let acc' = (f @^ IdVar(f)) :: (CacheVar(exp.l) @< CacheVar(e.l)) :: acc in
acc' |> f_aux body |> f_aux exp
| Call(e1, e2) ->
let acc' = List.fold_left (fun cs (f,x,e') ->
((f @^ CacheVar(e1.l)) @~~> (CacheVar(e2.l) @< IdVar(x))) ::
((f @^ CacheVar(e1.l)) @~~> (CacheVar(e'.l) @< CacheVar(e.l))) :: cs
) acc lambda_star
in
acc' |> f_aux e1 |> f_aux e2
in
f_aux aexp []
|
2f00f88c0e6397a526f9fe3309a0c9b25e75ae7792877aa0f62160b7cfdc0d06 | karlhof26/gimp-scheme | random-br-strokes.scm | ;; random.scm -*-scheme-*-
;; Use a brush to paint to paint random pixels a nominated number
;; of times to produce a "random" pattern.
;;
;; Version 2.0
;;
;;
;;
;; This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 3
of the License , or ( at your option ) any later version .
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (script-fu-random-br-strokes
img drw
margin
brush
brushsize
color
iterations)
(let* (
(x1 0)
(y1 0)
(ctr 0)
(x2 (car (gimp-image-width img)))
(y2 (car (gimp-image-height img)))
(*randompoint* (cons-array 2 'double))
(drw-width 0)
(drw-height 0)
)
; define drawable area for the algorithm
(set! x1 (+ x1 margin))
(set! x2 (- x2 margin))
(set! y1 (+ y1 margin))
(set! y2 (- y2 margin))
(set! drw-width (- x2 x1))
(set! drw-height (- y2 y1))
(gimp-context-push)
(gimp-image-undo-group-start img)
(gimp-context-set-foreground color)
(gimp-context-set-brush (car brush))
(gimp-context-set-brush-size brushsize)
(gimp-context-set-opacity (car (cdr brush)))
(gimp-context-set-paint-mode (car (cdr (cdr (cdr brush)))))
(gimp-context-set-brush-hardness 1.00)
(gimp-context-set-brush-aspect-ratio 1.60)
(gimp-context-set-dynamics "Dynamics Off")
(gimp-progress-set-text "Rendering Random brush strokes")
(while (< ctr iterations)
(set! ctr (+ ctr 1))
(aset *randompoint* 0 (+ x1 (rand drw-width )))
(aset *randompoint* 1 (+ y1 (rand drw-height)))
(gimp-pencil drw 2 *randompoint*)
)
(gimp-image-undo-group-end img)
(gimp-displays-flush)
(gimp-context-pop)
)
)
(script-fu-register "script-fu-random-br-strokes"
"Random Points using brush"
"Draws a specified number of random points using a nominated brush in pencil mode. \nfile:random-br-strokes.scm"
"karlhof26"
"Charles Cave"
"March 2020"
"RGB* INDEXED* GRAY*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-ADJUSTMENT "Margin (pixels)" '(0 0 100 1 6 0 0)
SF-BRUSH "Brush" '("Circle (01)" 100 1 0)
SF-ADJUSTMENT "Brush size" '(10 1 100 1 1 0 0)
SF-COLOR "Color" "black"
SF-ADJUSTMENT "Iterations" '(150 1 10000 10 100 0 0)
)
(script-fu-menu-register "script-fu-random-br-strokes"
"<Image>/Script-Fu2/Artistic")
;end of script | null | https://raw.githubusercontent.com/karlhof26/gimp-scheme/a8de87a29db39337929b22eb4f81345f91765f55/random-br-strokes.scm | scheme | random.scm -*-scheme-*-
Use a brush to paint to paint random pixels a nominated number
of times to produce a "random" pattern.
Version 2.0
This program is free software; you can redistribute it and/or
either version 3
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
define drawable area for the algorithm
end of script | modify it under the terms of the GNU General Public License
of the License , or ( at your option ) any later version .
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
(define (script-fu-random-br-strokes
img drw
margin
brush
brushsize
color
iterations)
(let* (
(x1 0)
(y1 0)
(ctr 0)
(x2 (car (gimp-image-width img)))
(y2 (car (gimp-image-height img)))
(*randompoint* (cons-array 2 'double))
(drw-width 0)
(drw-height 0)
)
(set! x1 (+ x1 margin))
(set! x2 (- x2 margin))
(set! y1 (+ y1 margin))
(set! y2 (- y2 margin))
(set! drw-width (- x2 x1))
(set! drw-height (- y2 y1))
(gimp-context-push)
(gimp-image-undo-group-start img)
(gimp-context-set-foreground color)
(gimp-context-set-brush (car brush))
(gimp-context-set-brush-size brushsize)
(gimp-context-set-opacity (car (cdr brush)))
(gimp-context-set-paint-mode (car (cdr (cdr (cdr brush)))))
(gimp-context-set-brush-hardness 1.00)
(gimp-context-set-brush-aspect-ratio 1.60)
(gimp-context-set-dynamics "Dynamics Off")
(gimp-progress-set-text "Rendering Random brush strokes")
(while (< ctr iterations)
(set! ctr (+ ctr 1))
(aset *randompoint* 0 (+ x1 (rand drw-width )))
(aset *randompoint* 1 (+ y1 (rand drw-height)))
(gimp-pencil drw 2 *randompoint*)
)
(gimp-image-undo-group-end img)
(gimp-displays-flush)
(gimp-context-pop)
)
)
(script-fu-register "script-fu-random-br-strokes"
"Random Points using brush"
"Draws a specified number of random points using a nominated brush in pencil mode. \nfile:random-br-strokes.scm"
"karlhof26"
"Charles Cave"
"March 2020"
"RGB* INDEXED* GRAY*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-ADJUSTMENT "Margin (pixels)" '(0 0 100 1 6 0 0)
SF-BRUSH "Brush" '("Circle (01)" 100 1 0)
SF-ADJUSTMENT "Brush size" '(10 1 100 1 1 0 0)
SF-COLOR "Color" "black"
SF-ADJUSTMENT "Iterations" '(150 1 10000 10 100 0 0)
)
(script-fu-menu-register "script-fu-random-br-strokes"
"<Image>/Script-Fu2/Artistic")
|
f2ffa4053c6fe7cacefbc93a3f77dc79256f9e8229b084b71ab101d5551f5e48 | eudoxia0/cmacro | macro.lisp | (in-package :cl-user)
(defpackage cmacro.macro
(:use :cl :anaphora)
(:import-from :trivial-types
:proper-list)
(:export :<macro-case>
:case-match
:case-template
:case-toplevel-template
:<macro>
:macro-name
:macro-cases))
(in-package :cmacro.macro)
(defclass <macro-case> ()
((match :reader case-match
:initarg :match)
(template :reader case-template
:initarg :template)
(toplevel-template :reader case-toplevel-template
:initarg :toplevel-template)))
(defclass <macro> ()
((name :reader macro-name
:initarg :name
:type string)
(cases :reader macro-cases
:initarg :cases
:type (proper-list <macro-case))))
| null | https://raw.githubusercontent.com/eudoxia0/cmacro/c1f419564a21c878ab62a54c2c45ee07d2968242/src/macro.lisp | lisp | (in-package :cl-user)
(defpackage cmacro.macro
(:use :cl :anaphora)
(:import-from :trivial-types
:proper-list)
(:export :<macro-case>
:case-match
:case-template
:case-toplevel-template
:<macro>
:macro-name
:macro-cases))
(in-package :cmacro.macro)
(defclass <macro-case> ()
((match :reader case-match
:initarg :match)
(template :reader case-template
:initarg :template)
(toplevel-template :reader case-toplevel-template
:initarg :toplevel-template)))
(defclass <macro> ()
((name :reader macro-name
:initarg :name
:type string)
(cases :reader macro-cases
:initarg :cases
:type (proper-list <macro-case))))
|
|
2ea079558d76c663bc68eeaa441b52f907adced9f379929f5965db4c8bfffb27 | input-output-hk/ouroboros-network | ClientState.hs | # LANGUAGE BangPatterns #
{-# LANGUAGE DeriveFunctor #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
# LANGUAGE RecordWildCards #
module Ouroboros.Network.BlockFetch.ClientState
( FetchClientContext (..)
, FetchClientPolicy (..)
, FetchClientStateVars (..)
, newFetchClientStateVars
, readFetchClientState
, PeerFetchStatus (..)
, IsIdle (..)
, PeerFetchInFlight (..)
, initialPeerFetchInFlight
, FetchRequest (..)
, addNewFetchRequest
, acknowledgeFetchRequest
, startedFetchBatch
, completeBlockDownload
, completeFetchBatch
, rejectedFetchBatch
, TraceFetchClientState (..)
, TraceLabelPeer (..)
, ChainRange (..)
-- * Ancillary
, FromConsensus (..)
, WhetherReceivingTentativeBlocks (..)
) where
import Data.List (foldl')
import Data.Maybe (mapMaybe)
import Data.Semigroup (Last (..))
import Data.Set (Set)
import qualified Data.Set as Set
import Control.Concurrent.Class.MonadSTM.Strict
import Control.Exception (assert)
import Control.Monad (when)
import Control.Monad.Class.MonadTime
import Control.Tracer (Tracer, traceWith)
import Network.Mux.Trace (TraceLabelPeer (..))
import Ouroboros.Network.AnchoredFragment (AnchoredFragment)
import qualified Ouroboros.Network.AnchoredFragment as AF
import Ouroboros.Network.Block (HasHeader, MaxSlotNo (..), Point,
blockPoint)
import Ouroboros.Network.BlockFetch.ConsensusInterface
(FromConsensus (..), WhetherReceivingTentativeBlocks (..))
import Ouroboros.Network.BlockFetch.DeltaQ
(PeerFetchInFlightLimits (..), PeerGSV, SizeInBytes,
calculatePeerFetchInFlightLimits)
import Ouroboros.Network.ControlMessage (ControlMessageSTM,
timeoutWithControlMessage)
import Ouroboros.Network.Point (withOriginToMaybe)
import Ouroboros.Network.Protocol.BlockFetch.Type (ChainRange (..))
-- | The context that is passed into the block fetch protocol client when it
-- is started.
--
data FetchClientContext header block m =
FetchClientContext {
fetchClientCtxTracer :: Tracer m (TraceFetchClientState header),
fetchClientCtxPolicy :: FetchClientPolicy header block m,
fetchClientCtxStateVars :: FetchClientStateVars m header
}
-- | The policy used by the fetch clients. It is set by the central block fetch
-- logic, and passed to them via the 'FetchClientRegistry'.
--
data FetchClientPolicy header block m =
FetchClientPolicy {
blockFetchSize :: header -> SizeInBytes,
blockMatchesHeader :: header -> block -> Bool,
addFetchedBlock :: Point block -> block -> m (),
blockForgeUTCTime :: FromConsensus block -> STM m UTCTime
}
-- | A set of variables shared between the block fetch logic thread and each
-- thread executing the client side of the block fetch protocol. That is, these
-- are the shared variables per peer. The 'FetchClientRegistry' contains the
-- mapping of these for all peers.
--
-- The variables are used for communicating from the protocol thread to the
-- decision making thread the status of things with that peer. And in the other
-- direction one shared variable is for providing new fetch requests.
--
data FetchClientStateVars m header =
FetchClientStateVars {
-- | The current status of communication with the peer. It is written
-- by the protocol thread and monitored and read by the decision logic
-- thread. Changes in this state trigger re-evaluation of fetch
-- decisions.
--
fetchClientStatusVar :: StrictTVar m (PeerFetchStatus header),
-- | The current number of requests in-flight and the amount of data
-- in-flight with the peer. It is written by the protocol thread and
-- read by the decision logic thread. This is used in fetch decisions
-- but changes here do not trigger re-evaluation of fetch decisions.
--
fetchClientInFlightVar :: StrictTVar m (PeerFetchInFlight header),
-- | The shared variable used to communicate fetch requests to the thread
-- running the block fetch protocol. Fetch requests are posted by the
-- decision logic thread. The protocol thread accepts the requests and
-- acts on them, updating the in-flight stats. While this is a 'TMVar',
it is not used as a one - place queue : the requests can be updated
-- before being accepted.
--
fetchClientRequestVar :: TFetchRequestVar m header
}
newFetchClientStateVars :: MonadSTM m => STM m (FetchClientStateVars m header)
newFetchClientStateVars = do
fetchClientInFlightVar <- newTVar initialPeerFetchInFlight
fetchClientStatusVar <- newTVar (PeerFetchStatusReady Set.empty IsIdle)
fetchClientRequestVar <- newTFetchRequestVar
return FetchClientStateVars {..}
readFetchClientState :: MonadSTM m
=> FetchClientStateVars m header
-> STM m (PeerFetchStatus header,
PeerFetchInFlight header,
FetchClientStateVars m header)
readFetchClientState vars@FetchClientStateVars{..} =
(,,) <$> readTVar fetchClientStatusVar
<*> readTVar fetchClientInFlightVar
<*> pure vars
-- | The status of the block fetch communication with a peer. This is maintained
-- by fetch protocol threads and used in the block fetch decision making logic.
-- Changes in this status trigger re-evaluation of fetch decisions.
--
data PeerFetchStatus header =
-- | Communication with the peer has failed. This is a temporary status
-- that may occur during the process of shutting down the thread that
-- runs the block fetch protocol. The peer will promptly be removed from
-- the peer registry and so will not be considered at all.
--
PeerFetchStatusShutdown
-- | The peer is in a potentially-temporary state in which it has not
-- responded to us within a certain expected time limit. This is not
-- a hard protocol timeout where the whole connection will be abandoned,
-- it is simply a reply that has taken longer than expected. This status
-- is used to trigger re-evaluating which peer to ask for blocks from,
-- so that we can swiftly ask other peers for blocks if one unexpectedly
-- responds too slowly
--
-- Peers in this state may later return to normal states if communication
-- resumes, or they may eventually hit a hard timeout and fail.
--
| PeerFetchStatusAberrant
-- | Communication with the peer is in a normal state, and the peer is
-- considered too busy to accept new requests. Changing from this state
-- to the ready state is used to trigger re-evaluating fetch decisions
-- and may eventually result in new fetch requests. This state is used
-- as part of a policy to batch new requests: instead of switching to
-- the ready state the moment there is tiny bit of capacity available,
-- the state is changed once the capacity reaches a certain threshold.
--
| PeerFetchStatusBusy
-- | Communication with the peer is in a normal state, and the peer is
-- considered ready to accept new requests.
--
The ' Set ' is the blocks in flight .
| PeerFetchStatusReady (Set (Point header)) IsIdle
deriving (Eq, Show)
-- | Whether this mini protocol instance is in the @Idle@ State
--
data IsIdle = IsIdle | IsNotIdle
deriving (Eq, Show)
idleIf :: Bool -> IsIdle
idleIf b = if b then IsIdle else IsNotIdle
-- | The number of requests in-flight and the amount of data in-flight with a
-- peer. This is maintained by fetch protocol threads and used in the block
-- fetch decision making logic.
--
data PeerFetchInFlight header = PeerFetchInFlight {
-- | The number of block fetch requests that are currently in-flight.
-- This is the number of /requests/ not the number of blocks. Each
-- request is for a range of blocks.
--
-- We track this because there is a fixed maximum number of outstanding
-- requests that the protocol allows.
--
peerFetchReqsInFlight :: !Word,
-- | The sum of the byte count of blocks expected from all in-flight
-- fetch requests. This is a close approximation of the amount of data
-- we expect to receive, assuming no failures.
--
-- We track this because we pipeline fetch requests and we want to keep
-- some but not too much data in flight at once.
--
peerFetchBytesInFlight :: !SizeInBytes,
-- | The points for the set of blocks that are currently in-flight.
-- Note that since requests are for ranges of blocks this does not
-- correspond to the number of requests in flight.
--
-- We track this because as part of the decision for which blocks to
-- fetch from which peers we take into account what blocks are already
-- in-flight with peers.
--
peerFetchBlocksInFlight :: Set (Point header),
-- | The maximum slot of a block that /has ever been/ in flight for
-- this peer.
--
-- We track this to more efficiently remove blocks that are already
-- in-flight from the candidate fragments: blocks with a slot number
-- higher than this one do not have to be filtered out.
peerFetchMaxSlotNo :: !MaxSlotNo
}
deriving (Eq, Show)
initialPeerFetchInFlight :: PeerFetchInFlight header
initialPeerFetchInFlight =
PeerFetchInFlight {
peerFetchReqsInFlight = 0,
peerFetchBytesInFlight = 0,
peerFetchBlocksInFlight = Set.empty,
peerFetchMaxSlotNo = NoMaxSlotNo
}
-- | Update the 'PeerFetchInFlight' in-flight tracking numbers.
--
-- Note that it takes both the existing \"old\" request, the \"added\" request
and resulting \"merged\ " request . The relationship between the three is
-- @old <> added = merged@.
--
addHeadersInFlight :: HasHeader header
=> (header -> SizeInBytes)
-> Maybe (FetchRequest header) -- ^ The old request (if any).
-> FetchRequest header -- ^ The added request.
-> FetchRequest header -- ^ The merged request.
-> PeerFetchInFlight header
-> PeerFetchInFlight header
addHeadersInFlight blockFetchSize oldReq addedReq mergedReq inflight =
-- This assertion checks the pre-condition 'addNewFetchRequest' that all
-- requested blocks are new. This is true irrespective of fetch-request
-- command merging.
assert (and [ blockPoint header `Set.notMember` peerFetchBlocksInFlight inflight
| fragment <- fetchRequestFragments addedReq
, header <- AF.toOldestFirst fragment ]) $
PeerFetchInFlight {
-- Fetch request merging makes the update of the number of in-flight
requests rather subtle . See the ' FetchRequest ' semigroup instance
-- documentation for details. The upshot is that we have to look at the
-- /difference/ in the number of fragments for the old request
-- (if any) and merged request.
peerFetchReqsInFlight = peerFetchReqsInFlight inflight
+ numFetchReqs mergedReq
- maybe 0 numFetchReqs oldReq,
-- For the bytes and blocks in flight however we can rely on the
-- pre-condition that is asserted above.
peerFetchBytesInFlight = peerFetchBytesInFlight inflight
+ sum [ blockFetchSize header
| fragment <- fetchRequestFragments addedReq
, header <- AF.toOldestFirst fragment ],
peerFetchBlocksInFlight = peerFetchBlocksInFlight inflight
`Set.union` Set.fromList
[ blockPoint header
| fragment <- fetchRequestFragments addedReq
, header <- AF.toOldestFirst fragment ],
peerFetchMaxSlotNo = peerFetchMaxSlotNo inflight
`max` fetchRequestMaxSlotNo addedReq
}
where
numFetchReqs :: FetchRequest header -> Word
numFetchReqs = fromIntegral . length . fetchRequestFragments
deleteHeaderInFlight :: HasHeader header
=> (header -> SizeInBytes)
-> header
-> PeerFetchInFlight header
-> PeerFetchInFlight header
deleteHeaderInFlight blockFetchSize header inflight =
assert (peerFetchBytesInFlight inflight >= blockFetchSize header) $
assert (blockPoint header `Set.member` peerFetchBlocksInFlight inflight) $
inflight {
peerFetchBytesInFlight = peerFetchBytesInFlight inflight
- blockFetchSize header,
peerFetchBlocksInFlight = blockPoint header
`Set.delete` peerFetchBlocksInFlight inflight
}
deleteHeadersInFlight :: HasHeader header
=> (header -> SizeInBytes)
-> [header]
-> PeerFetchInFlight header
-> PeerFetchInFlight header
deleteHeadersInFlight blockFetchSize headers inflight =
-- Reusing 'deleteHeaderInFlight' rather than a direct impl still
-- gives us O(n log m) which is fine
foldl' (flip (deleteHeaderInFlight blockFetchSize)) inflight headers
newtype FetchRequest header =
FetchRequest { fetchRequestFragments :: [AnchoredFragment header] }
deriving Show
-- | We sometimes have the opportunity to merge fetch request fragments to
-- reduce the number of separate range request messages that we send. We send
one message per fragment . It is better to send fewer requests for bigger
-- ranges, rather than lots of requests for small ranges.
--
-- We never expect fetch requests to overlap (ie have blocks in common) but we
do expect a common case that requests will \"touch\ " so that two ranges
-- could be merged into a single contiguous range.
--
-- This semigroup instance implements this merging when possible, otherwise the
two lists of fragments are just appended .
--
-- A consequence of merging and sending fewer request messages is that tracking
-- the number of requests in-flight a bit more subtle. To track this accurately
-- we have to look at the /old request/ as well a the updated request after any
-- merging. We meed to account for the /difference/ in the number of fragments
-- in the existing request (if any) and in new request.
--
instance HasHeader header => Semigroup (FetchRequest header) where
FetchRequest afs@(_:_) <> FetchRequest bfs@(_:_)
| Just f <- AF.join (last afs) (head bfs)
= FetchRequest (init afs ++ f : tail bfs)
FetchRequest afs <> FetchRequest bfs
= FetchRequest (afs ++ bfs)
fetchRequestMaxSlotNo :: HasHeader header => FetchRequest header -> MaxSlotNo
fetchRequestMaxSlotNo (FetchRequest afs) =
foldl' max NoMaxSlotNo $ map MaxSlotNo $
mapMaybe (withOriginToMaybe . AF.headSlot) afs
-- | Tracing types for the various events that change the state
-- (i.e. 'FetchClientStateVars') for a block fetch client.
--
-- Note that while these are all state changes, the 'AddedFetchRequest' occurs
-- in the decision thread while the other state changes occur in the block
-- fetch client threads.
--
data TraceFetchClientState header =
-- | The block fetch decision thread has added a new fetch instruction
consisting of one or more individual request ranges .
--
AddedFetchRequest
(FetchRequest header)
(PeerFetchInFlight header)
PeerFetchInFlightLimits
(PeerFetchStatus header)
-- | Mark the point when the fetch client picks up the request added
-- by the block fetch decision thread. Note that this event can happen
-- fewer times than the 'AddedFetchRequest' due to fetch request merging.
--
| AcknowledgedFetchRequest
(FetchRequest header)
-- | Mark the point when fetch request for a fragment is actually sent
-- over the wire.
| SendFetchRequest
(AnchoredFragment header)
PeerGSV
| the start of receiving a streaming batch of blocks . This will
be followed by one or more ' CompletedBlockFetch ' and a final
-- 'CompletedFetchBatch'.
--
| StartedFetchBatch
(ChainRange (Point header))
(PeerFetchInFlight header)
PeerFetchInFlightLimits
(PeerFetchStatus header)
-- | Mark the completion of of receiving a single block within a
-- streaming batch of blocks.
--
| CompletedBlockFetch
(Point header)
(PeerFetchInFlight header)
PeerFetchInFlightLimits
(PeerFetchStatus header)
NominalDiffTime
SizeInBytes
-- | Mark the successful end of receiving a streaming batch of blocks
--
| CompletedFetchBatch
(ChainRange (Point header))
(PeerFetchInFlight header)
PeerFetchInFlightLimits
(PeerFetchStatus header)
-- | If the other peer rejects our request then we have this event
-- instead of 'StartedFetchBatch' and 'CompletedFetchBatch'.
--
| RejectedFetchBatch
(ChainRange (Point header))
(PeerFetchInFlight header)
PeerFetchInFlightLimits
(PeerFetchStatus header)
-- | The client is terminating. Log the number of outstanding
-- requests.
--
| ClientTerminating Int
deriving Show
-- | Add a new fetch request for a single peer. This is used by the fetch
-- decision logic thread to add new fetch requests.
--
-- We have as a pre-condition that all requested blocks are new, i.e. none
-- should appear in the existing 'peerFetchBlocksInFlight'. This is a
-- relatively easy precondition to satisfy since the decision logic can filter
-- its requests based on this in-flight blocks state, and this operation is the
-- only operation that grows the in-flight blocks, and is only used by the
-- fetch decision logic thread.
--
addNewFetchRequest :: (MonadSTM m, HasHeader header)
=> Tracer m (TraceFetchClientState header)
-> (header -> SizeInBytes)
-> FetchRequest header
-> PeerGSV
-> FetchClientStateVars m header
-> m (PeerFetchStatus header)
addNewFetchRequest tracer blockFetchSize addedReq gsvs
FetchClientStateVars{
fetchClientRequestVar,
fetchClientInFlightVar,
fetchClientStatusVar
} = do
(inflight', currentStatus') <- atomically $ do
-- Add a new fetch request, or extend or merge with the existing
-- unacknowledged one.
--
-- Fetch request merging makes the update of the in-flight stats subtle.
See the ' FetchRequest ' semigroup instance documentation for details .
-- The upshot is that our in-flight stats update is based on the existing
-- \"old\" request (if any), the \"added\" one and the resulting
-- \"merged\" one.
--
oldReq <- peekTFetchRequestVar fetchClientRequestVar
mergedReq <- writeTFetchRequestVar fetchClientRequestVar
addedReq gsvs inflightlimits
-- Update our in-flight stats
inflight <- readTVar fetchClientInFlightVar
let !inflight' = addHeadersInFlight blockFetchSize
oldReq addedReq mergedReq
inflight
writeTVar fetchClientInFlightVar inflight'
-- Set the peer status to busy if it went over the high watermark.
currentStatus' <- updateCurrentStatus
(busyIfOverHighWatermark inflightlimits)
fetchClientStatusVar
inflight'
--TODO: think about status aberrant
return (inflight', currentStatus')
traceWith tracer $
AddedFetchRequest
addedReq
inflight' inflightlimits
currentStatus'
return currentStatus'
where
inflightlimits = calculatePeerFetchInFlightLimits gsvs
--TODO: if recalculating the limits here is expensive we can pass them
-- along with the fetch request and the gsvs
-- | This is used by the fetch client threads.
--
acknowledgeFetchRequest :: MonadSTM m
=> Tracer m (TraceFetchClientState header)
-> ControlMessageSTM m
-> FetchClientStateVars m header
-> m (Maybe
( FetchRequest header
, PeerGSV
, PeerFetchInFlightLimits ))
acknowledgeFetchRequest tracer controlMessageSTM FetchClientStateVars {fetchClientRequestVar} = do
result <-
timeoutWithControlMessage controlMessageSTM (takeTFetchRequestVar fetchClientRequestVar)
case result of
Nothing -> return result
Just (request, _, _) -> do
traceWith tracer (AcknowledgedFetchRequest request)
return result
startedFetchBatch :: MonadSTM m
=> Tracer m (TraceFetchClientState header)
-> PeerFetchInFlightLimits
-> ChainRange (Point header)
-> FetchClientStateVars m header
-> m ()
startedFetchBatch tracer inflightlimits range
FetchClientStateVars {
fetchClientInFlightVar,
fetchClientStatusVar
} = do
(inflight, currentStatus) <-
atomically $ (,) <$> readTVar fetchClientInFlightVar
<*> readTVar fetchClientStatusVar
traceWith tracer $
StartedFetchBatch
range
inflight inflightlimits
currentStatus
completeBlockDownload :: (MonadSTM m, HasHeader header)
=> Tracer m (TraceFetchClientState header)
-> (header -> SizeInBytes)
-> PeerFetchInFlightLimits
-> header
-> NominalDiffTime
-> FetchClientStateVars m header
-> m ()
completeBlockDownload tracer blockFetchSize inflightlimits header blockDelay
FetchClientStateVars {
fetchClientInFlightVar,
fetchClientStatusVar
} = do
(inflight', currentStatus') <- atomically $ do
inflight <- readTVar fetchClientInFlightVar
let !inflight' = deleteHeaderInFlight blockFetchSize header inflight
writeTVar fetchClientInFlightVar inflight'
-- Set our status to ready if we're under the low watermark.
currentStatus' <- updateCurrentStatus
(readyIfUnderLowWatermark inflightlimits)
fetchClientStatusVar
inflight'
-- TODO: when do we reset the status from PeerFetchStatusAberrant
-- to PeerFetchStatusReady/Busy?
return (inflight', currentStatus')
traceWith tracer $
CompletedBlockFetch
(blockPoint header)
inflight' inflightlimits
currentStatus'
blockDelay
(blockFetchSize header)
completeFetchBatch :: MonadSTM m
=> Tracer m (TraceFetchClientState header)
-> PeerFetchInFlightLimits
-> ChainRange (Point header)
-> FetchClientStateVars m header
-> m ()
completeFetchBatch tracer inflightlimits range
FetchClientStateVars {
fetchClientInFlightVar,
fetchClientStatusVar
} = do
(inflight, currentStatus) <- atomically $ do
inflight <- readTVar fetchClientInFlightVar
let !inflight' =
assert (if peerFetchReqsInFlight inflight == 1
then peerFetchBytesInFlight inflight == 0
&& Set.null (peerFetchBlocksInFlight inflight)
else True)
inflight {
peerFetchReqsInFlight = peerFetchReqsInFlight inflight - 1
}
writeTVar fetchClientInFlightVar inflight'
currentStatus' <- readTVar fetchClientStatusVar >>= \case
PeerFetchStatusReady bs IsNotIdle
| Set.null bs
&& 0 == peerFetchReqsInFlight inflight'
-> let status = PeerFetchStatusReady Set.empty IsIdle
in status <$ writeTVar fetchClientStatusVar status
currentStatus -> pure currentStatus
return (inflight', currentStatus')
traceWith tracer $
CompletedFetchBatch
range
inflight inflightlimits
currentStatus
rejectedFetchBatch :: (MonadSTM m, HasHeader header)
=> Tracer m (TraceFetchClientState header)
-> (header -> SizeInBytes)
-> PeerFetchInFlightLimits
-> ChainRange (Point header)
-> [header]
-> FetchClientStateVars m header
-> m ()
rejectedFetchBatch tracer blockFetchSize inflightlimits range headers
FetchClientStateVars {
fetchClientInFlightVar,
fetchClientStatusVar
} = do
(inflight', currentStatus') <- atomically $ do
inflight <- readTVar fetchClientInFlightVar
let !inflight' =
(deleteHeadersInFlight blockFetchSize headers inflight) {
peerFetchReqsInFlight = peerFetchReqsInFlight inflight - 1
}
writeTVar fetchClientInFlightVar inflight'
-- Set our status to ready if we're under the low watermark.
currentStatus' <- updateCurrentStatus
(readyIfUnderLowWatermark inflightlimits)
fetchClientStatusVar
inflight'
-- TODO: when do we reset the status from PeerFetchStatusAberrant
-- to PeerFetchStatusReady/Busy?
return (inflight', currentStatus')
traceWith tracer $
RejectedFetchBatch
range
inflight' inflightlimits
currentStatus'
| Given a ' PeerFetchInFlight ' update the ' PeerFetchStatus ' accordingly .
This can be used with one of two policies :
--
-- * 'busyIfOverHighWatermark'
* ' readyIfUnderLowWatermark '
--
updateCurrentStatus :: (MonadSTM m, HasHeader header)
=> (PeerFetchInFlight header -> PeerFetchStatus header)
-> StrictTVar m (PeerFetchStatus header)
-> PeerFetchInFlight header
-> STM m (PeerFetchStatus header)
updateCurrentStatus decideCurrentStatus fetchClientStatusVar inflight = do
let currentStatus' = decideCurrentStatus inflight
-- Only update the variable if it changed, to avoid spurious wakeups.
currentStatus <- readTVar fetchClientStatusVar
when (currentStatus' /= currentStatus) $
writeTVar fetchClientStatusVar currentStatus'
return currentStatus'
-- | Return 'PeerFetchStatusBusy' if we're now over the high watermark.
--
busyIfOverHighWatermark :: PeerFetchInFlightLimits
-> PeerFetchInFlight header
-> PeerFetchStatus header
busyIfOverHighWatermark inflightlimits inflight
| peerFetchBytesInFlight inflight >= inFlightBytesHighWatermark inflightlimits
= PeerFetchStatusBusy
| otherwise
= PeerFetchStatusReady
(peerFetchBlocksInFlight inflight)
(idleIf (0 == peerFetchReqsInFlight inflight))
-- | Return 'PeerFetchStatusReady' if we're now under the low watermark.
--
readyIfUnderLowWatermark :: PeerFetchInFlightLimits
-> PeerFetchInFlight header
-> PeerFetchStatus header
readyIfUnderLowWatermark inflightlimits inflight
| peerFetchBytesInFlight inflight <= inFlightBytesLowWatermark inflightlimits
= PeerFetchStatusReady
(peerFetchBlocksInFlight inflight)
(idleIf (0 == peerFetchReqsInFlight inflight))
| otherwise
= PeerFetchStatusBusy
--
STM TFetchRequestVar
--
-- | The 'TFetchRequestVar' is a 'TMergeVar' for communicating the
' FetchRequest 's from the logic thread to a fetch client thread .
--
-- The pattern is that the logic thread determines a current request and this
-- is written to the var with 'writeTMergeVar'. The fetch client thread uses
' takeTMergeVar ' , which blocks until a value is available . On the other hand ,
-- 'writeTMergeVar' never blocks, if a value is already present then it
-- overwrites it. This makes sense for the fetch requests because if a fetch
-- client has not accepted the request yet then we can replace it with the
-- request based on the more recent state.
--
type TFetchRequestVar m header =
TMergeVar m (FetchRequest header,
Last PeerGSV,
Last PeerFetchInFlightLimits)
newTFetchRequestVar :: MonadSTM m => STM m (TFetchRequestVar m header)
newTFetchRequestVar = newTMergeVar
| Write to the underlying ' TMergeVar ' and return the updated ' FetchRequest '
--
writeTFetchRequestVar :: (MonadSTM m, HasHeader header)
=> TFetchRequestVar m header
-> FetchRequest header
-> PeerGSV
-> PeerFetchInFlightLimits
-> STM m (FetchRequest header)
writeTFetchRequestVar v r g l = do
(r', _, _) <- writeTMergeVar v (r, Last g, Last l)
return r'
peekTFetchRequestVar :: MonadSTM m
=> TFetchRequestVar m header
-> STM m (Maybe (FetchRequest header))
peekTFetchRequestVar v = fmap (\(x, _, _) -> x) <$> tryReadTMergeVar v
takeTFetchRequestVar :: MonadSTM m
=> TFetchRequestVar m header
-> STM m (FetchRequest header,
PeerGSV,
PeerFetchInFlightLimits)
takeTFetchRequestVar v = (\(r,g,l) -> (r, getLast g, getLast l))
<$> takeTMergeVar v
--
STM TMergeVar mini - abstraction
--
-- | The 'TMergeVar' is like a 'TMVar' in that we take it, leaving it empty.
-- Unlike an ordinary 'TMVar' with a blocking \'put\' operation, it has a
-- non-blocking combiing write operation: if a value is already present then
-- the values are combined using the 'Semigroup' operator.
--
This is used much like a ' TMVar ' as a one - place queue between threads but
-- with the property that we can \"improve\" the current value (if any).
--
newtype TMergeVar m a = TMergeVar (StrictTMVar m a)
newTMergeVar :: MonadSTM m => STM m (TMergeVar m a)
newTMergeVar = TMergeVar <$> newEmptyTMVar
-- | Merge the current value with the given one and store it, return the updated
-- value.
--
writeTMergeVar :: (MonadSTM m, Semigroup a) => TMergeVar m a -> a -> STM m a
writeTMergeVar (TMergeVar v) x = do
mx0 <- tryTakeTMVar v
case mx0 of
Nothing -> x <$ putTMVar v x
Just x0 -> x' <$ putTMVar v x' where !x' = x0 <> x
takeTMergeVar :: MonadSTM m => TMergeVar m a -> STM m a
takeTMergeVar (TMergeVar v) = takeTMVar v
tryReadTMergeVar :: MonadSTM m
=> TMergeVar m a
-> STM m (Maybe a)
tryReadTMergeVar (TMergeVar v) = tryReadTMVar v
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/2793b6993c8f6ed158f432055fa4ef581acdb661/ouroboros-network/src/Ouroboros/Network/BlockFetch/ClientState.hs | haskell | # LANGUAGE DeriveFunctor #
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
* Ancillary
| The context that is passed into the block fetch protocol client when it
is started.
| The policy used by the fetch clients. It is set by the central block fetch
logic, and passed to them via the 'FetchClientRegistry'.
| A set of variables shared between the block fetch logic thread and each
thread executing the client side of the block fetch protocol. That is, these
are the shared variables per peer. The 'FetchClientRegistry' contains the
mapping of these for all peers.
The variables are used for communicating from the protocol thread to the
decision making thread the status of things with that peer. And in the other
direction one shared variable is for providing new fetch requests.
| The current status of communication with the peer. It is written
by the protocol thread and monitored and read by the decision logic
thread. Changes in this state trigger re-evaluation of fetch
decisions.
| The current number of requests in-flight and the amount of data
in-flight with the peer. It is written by the protocol thread and
read by the decision logic thread. This is used in fetch decisions
but changes here do not trigger re-evaluation of fetch decisions.
| The shared variable used to communicate fetch requests to the thread
running the block fetch protocol. Fetch requests are posted by the
decision logic thread. The protocol thread accepts the requests and
acts on them, updating the in-flight stats. While this is a 'TMVar',
before being accepted.
| The status of the block fetch communication with a peer. This is maintained
by fetch protocol threads and used in the block fetch decision making logic.
Changes in this status trigger re-evaluation of fetch decisions.
| Communication with the peer has failed. This is a temporary status
that may occur during the process of shutting down the thread that
runs the block fetch protocol. The peer will promptly be removed from
the peer registry and so will not be considered at all.
| The peer is in a potentially-temporary state in which it has not
responded to us within a certain expected time limit. This is not
a hard protocol timeout where the whole connection will be abandoned,
it is simply a reply that has taken longer than expected. This status
is used to trigger re-evaluating which peer to ask for blocks from,
so that we can swiftly ask other peers for blocks if one unexpectedly
responds too slowly
Peers in this state may later return to normal states if communication
resumes, or they may eventually hit a hard timeout and fail.
| Communication with the peer is in a normal state, and the peer is
considered too busy to accept new requests. Changing from this state
to the ready state is used to trigger re-evaluating fetch decisions
and may eventually result in new fetch requests. This state is used
as part of a policy to batch new requests: instead of switching to
the ready state the moment there is tiny bit of capacity available,
the state is changed once the capacity reaches a certain threshold.
| Communication with the peer is in a normal state, and the peer is
considered ready to accept new requests.
| Whether this mini protocol instance is in the @Idle@ State
| The number of requests in-flight and the amount of data in-flight with a
peer. This is maintained by fetch protocol threads and used in the block
fetch decision making logic.
| The number of block fetch requests that are currently in-flight.
This is the number of /requests/ not the number of blocks. Each
request is for a range of blocks.
We track this because there is a fixed maximum number of outstanding
requests that the protocol allows.
| The sum of the byte count of blocks expected from all in-flight
fetch requests. This is a close approximation of the amount of data
we expect to receive, assuming no failures.
We track this because we pipeline fetch requests and we want to keep
some but not too much data in flight at once.
| The points for the set of blocks that are currently in-flight.
Note that since requests are for ranges of blocks this does not
correspond to the number of requests in flight.
We track this because as part of the decision for which blocks to
fetch from which peers we take into account what blocks are already
in-flight with peers.
| The maximum slot of a block that /has ever been/ in flight for
this peer.
We track this to more efficiently remove blocks that are already
in-flight from the candidate fragments: blocks with a slot number
higher than this one do not have to be filtered out.
| Update the 'PeerFetchInFlight' in-flight tracking numbers.
Note that it takes both the existing \"old\" request, the \"added\" request
@old <> added = merged@.
^ The old request (if any).
^ The added request.
^ The merged request.
This assertion checks the pre-condition 'addNewFetchRequest' that all
requested blocks are new. This is true irrespective of fetch-request
command merging.
Fetch request merging makes the update of the number of in-flight
documentation for details. The upshot is that we have to look at the
/difference/ in the number of fragments for the old request
(if any) and merged request.
For the bytes and blocks in flight however we can rely on the
pre-condition that is asserted above.
Reusing 'deleteHeaderInFlight' rather than a direct impl still
gives us O(n log m) which is fine
| We sometimes have the opportunity to merge fetch request fragments to
reduce the number of separate range request messages that we send. We send
ranges, rather than lots of requests for small ranges.
We never expect fetch requests to overlap (ie have blocks in common) but we
could be merged into a single contiguous range.
This semigroup instance implements this merging when possible, otherwise the
A consequence of merging and sending fewer request messages is that tracking
the number of requests in-flight a bit more subtle. To track this accurately
we have to look at the /old request/ as well a the updated request after any
merging. We meed to account for the /difference/ in the number of fragments
in the existing request (if any) and in new request.
| Tracing types for the various events that change the state
(i.e. 'FetchClientStateVars') for a block fetch client.
Note that while these are all state changes, the 'AddedFetchRequest' occurs
in the decision thread while the other state changes occur in the block
fetch client threads.
| The block fetch decision thread has added a new fetch instruction
| Mark the point when the fetch client picks up the request added
by the block fetch decision thread. Note that this event can happen
fewer times than the 'AddedFetchRequest' due to fetch request merging.
| Mark the point when fetch request for a fragment is actually sent
over the wire.
'CompletedFetchBatch'.
| Mark the completion of of receiving a single block within a
streaming batch of blocks.
| Mark the successful end of receiving a streaming batch of blocks
| If the other peer rejects our request then we have this event
instead of 'StartedFetchBatch' and 'CompletedFetchBatch'.
| The client is terminating. Log the number of outstanding
requests.
| Add a new fetch request for a single peer. This is used by the fetch
decision logic thread to add new fetch requests.
We have as a pre-condition that all requested blocks are new, i.e. none
should appear in the existing 'peerFetchBlocksInFlight'. This is a
relatively easy precondition to satisfy since the decision logic can filter
its requests based on this in-flight blocks state, and this operation is the
only operation that grows the in-flight blocks, and is only used by the
fetch decision logic thread.
Add a new fetch request, or extend or merge with the existing
unacknowledged one.
Fetch request merging makes the update of the in-flight stats subtle.
The upshot is that our in-flight stats update is based on the existing
\"old\" request (if any), the \"added\" one and the resulting
\"merged\" one.
Update our in-flight stats
Set the peer status to busy if it went over the high watermark.
TODO: think about status aberrant
TODO: if recalculating the limits here is expensive we can pass them
along with the fetch request and the gsvs
| This is used by the fetch client threads.
Set our status to ready if we're under the low watermark.
TODO: when do we reset the status from PeerFetchStatusAberrant
to PeerFetchStatusReady/Busy?
Set our status to ready if we're under the low watermark.
TODO: when do we reset the status from PeerFetchStatusAberrant
to PeerFetchStatusReady/Busy?
* 'busyIfOverHighWatermark'
Only update the variable if it changed, to avoid spurious wakeups.
| Return 'PeerFetchStatusBusy' if we're now over the high watermark.
| Return 'PeerFetchStatusReady' if we're now under the low watermark.
| The 'TFetchRequestVar' is a 'TMergeVar' for communicating the
The pattern is that the logic thread determines a current request and this
is written to the var with 'writeTMergeVar'. The fetch client thread uses
'writeTMergeVar' never blocks, if a value is already present then it
overwrites it. This makes sense for the fetch requests because if a fetch
client has not accepted the request yet then we can replace it with the
request based on the more recent state.
| The 'TMergeVar' is like a 'TMVar' in that we take it, leaving it empty.
Unlike an ordinary 'TMVar' with a blocking \'put\' operation, it has a
non-blocking combiing write operation: if a value is already present then
the values are combined using the 'Semigroup' operator.
with the property that we can \"improve\" the current value (if any).
| Merge the current value with the given one and store it, return the updated
value.
| # LANGUAGE BangPatterns #
# LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
module Ouroboros.Network.BlockFetch.ClientState
( FetchClientContext (..)
, FetchClientPolicy (..)
, FetchClientStateVars (..)
, newFetchClientStateVars
, readFetchClientState
, PeerFetchStatus (..)
, IsIdle (..)
, PeerFetchInFlight (..)
, initialPeerFetchInFlight
, FetchRequest (..)
, addNewFetchRequest
, acknowledgeFetchRequest
, startedFetchBatch
, completeBlockDownload
, completeFetchBatch
, rejectedFetchBatch
, TraceFetchClientState (..)
, TraceLabelPeer (..)
, ChainRange (..)
, FromConsensus (..)
, WhetherReceivingTentativeBlocks (..)
) where
import Data.List (foldl')
import Data.Maybe (mapMaybe)
import Data.Semigroup (Last (..))
import Data.Set (Set)
import qualified Data.Set as Set
import Control.Concurrent.Class.MonadSTM.Strict
import Control.Exception (assert)
import Control.Monad (when)
import Control.Monad.Class.MonadTime
import Control.Tracer (Tracer, traceWith)
import Network.Mux.Trace (TraceLabelPeer (..))
import Ouroboros.Network.AnchoredFragment (AnchoredFragment)
import qualified Ouroboros.Network.AnchoredFragment as AF
import Ouroboros.Network.Block (HasHeader, MaxSlotNo (..), Point,
blockPoint)
import Ouroboros.Network.BlockFetch.ConsensusInterface
(FromConsensus (..), WhetherReceivingTentativeBlocks (..))
import Ouroboros.Network.BlockFetch.DeltaQ
(PeerFetchInFlightLimits (..), PeerGSV, SizeInBytes,
calculatePeerFetchInFlightLimits)
import Ouroboros.Network.ControlMessage (ControlMessageSTM,
timeoutWithControlMessage)
import Ouroboros.Network.Point (withOriginToMaybe)
import Ouroboros.Network.Protocol.BlockFetch.Type (ChainRange (..))
data FetchClientContext header block m =
FetchClientContext {
fetchClientCtxTracer :: Tracer m (TraceFetchClientState header),
fetchClientCtxPolicy :: FetchClientPolicy header block m,
fetchClientCtxStateVars :: FetchClientStateVars m header
}
data FetchClientPolicy header block m =
FetchClientPolicy {
blockFetchSize :: header -> SizeInBytes,
blockMatchesHeader :: header -> block -> Bool,
addFetchedBlock :: Point block -> block -> m (),
blockForgeUTCTime :: FromConsensus block -> STM m UTCTime
}
data FetchClientStateVars m header =
FetchClientStateVars {
fetchClientStatusVar :: StrictTVar m (PeerFetchStatus header),
fetchClientInFlightVar :: StrictTVar m (PeerFetchInFlight header),
it is not used as a one - place queue : the requests can be updated
fetchClientRequestVar :: TFetchRequestVar m header
}
newFetchClientStateVars :: MonadSTM m => STM m (FetchClientStateVars m header)
newFetchClientStateVars = do
fetchClientInFlightVar <- newTVar initialPeerFetchInFlight
fetchClientStatusVar <- newTVar (PeerFetchStatusReady Set.empty IsIdle)
fetchClientRequestVar <- newTFetchRequestVar
return FetchClientStateVars {..}
readFetchClientState :: MonadSTM m
=> FetchClientStateVars m header
-> STM m (PeerFetchStatus header,
PeerFetchInFlight header,
FetchClientStateVars m header)
readFetchClientState vars@FetchClientStateVars{..} =
(,,) <$> readTVar fetchClientStatusVar
<*> readTVar fetchClientInFlightVar
<*> pure vars
data PeerFetchStatus header =
PeerFetchStatusShutdown
| PeerFetchStatusAberrant
| PeerFetchStatusBusy
The ' Set ' is the blocks in flight .
| PeerFetchStatusReady (Set (Point header)) IsIdle
deriving (Eq, Show)
data IsIdle = IsIdle | IsNotIdle
deriving (Eq, Show)
idleIf :: Bool -> IsIdle
idleIf b = if b then IsIdle else IsNotIdle
data PeerFetchInFlight header = PeerFetchInFlight {
peerFetchReqsInFlight :: !Word,
peerFetchBytesInFlight :: !SizeInBytes,
peerFetchBlocksInFlight :: Set (Point header),
peerFetchMaxSlotNo :: !MaxSlotNo
}
deriving (Eq, Show)
initialPeerFetchInFlight :: PeerFetchInFlight header
initialPeerFetchInFlight =
PeerFetchInFlight {
peerFetchReqsInFlight = 0,
peerFetchBytesInFlight = 0,
peerFetchBlocksInFlight = Set.empty,
peerFetchMaxSlotNo = NoMaxSlotNo
}
and resulting \"merged\ " request . The relationship between the three is
addHeadersInFlight :: HasHeader header
=> (header -> SizeInBytes)
-> PeerFetchInFlight header
-> PeerFetchInFlight header
addHeadersInFlight blockFetchSize oldReq addedReq mergedReq inflight =
assert (and [ blockPoint header `Set.notMember` peerFetchBlocksInFlight inflight
| fragment <- fetchRequestFragments addedReq
, header <- AF.toOldestFirst fragment ]) $
PeerFetchInFlight {
requests rather subtle . See the ' FetchRequest ' semigroup instance
peerFetchReqsInFlight = peerFetchReqsInFlight inflight
+ numFetchReqs mergedReq
- maybe 0 numFetchReqs oldReq,
peerFetchBytesInFlight = peerFetchBytesInFlight inflight
+ sum [ blockFetchSize header
| fragment <- fetchRequestFragments addedReq
, header <- AF.toOldestFirst fragment ],
peerFetchBlocksInFlight = peerFetchBlocksInFlight inflight
`Set.union` Set.fromList
[ blockPoint header
| fragment <- fetchRequestFragments addedReq
, header <- AF.toOldestFirst fragment ],
peerFetchMaxSlotNo = peerFetchMaxSlotNo inflight
`max` fetchRequestMaxSlotNo addedReq
}
where
numFetchReqs :: FetchRequest header -> Word
numFetchReqs = fromIntegral . length . fetchRequestFragments
deleteHeaderInFlight :: HasHeader header
=> (header -> SizeInBytes)
-> header
-> PeerFetchInFlight header
-> PeerFetchInFlight header
deleteHeaderInFlight blockFetchSize header inflight =
assert (peerFetchBytesInFlight inflight >= blockFetchSize header) $
assert (blockPoint header `Set.member` peerFetchBlocksInFlight inflight) $
inflight {
peerFetchBytesInFlight = peerFetchBytesInFlight inflight
- blockFetchSize header,
peerFetchBlocksInFlight = blockPoint header
`Set.delete` peerFetchBlocksInFlight inflight
}
deleteHeadersInFlight :: HasHeader header
=> (header -> SizeInBytes)
-> [header]
-> PeerFetchInFlight header
-> PeerFetchInFlight header
deleteHeadersInFlight blockFetchSize headers inflight =
foldl' (flip (deleteHeaderInFlight blockFetchSize)) inflight headers
newtype FetchRequest header =
FetchRequest { fetchRequestFragments :: [AnchoredFragment header] }
deriving Show
one message per fragment . It is better to send fewer requests for bigger
do expect a common case that requests will \"touch\ " so that two ranges
two lists of fragments are just appended .
instance HasHeader header => Semigroup (FetchRequest header) where
FetchRequest afs@(_:_) <> FetchRequest bfs@(_:_)
| Just f <- AF.join (last afs) (head bfs)
= FetchRequest (init afs ++ f : tail bfs)
FetchRequest afs <> FetchRequest bfs
= FetchRequest (afs ++ bfs)
fetchRequestMaxSlotNo :: HasHeader header => FetchRequest header -> MaxSlotNo
fetchRequestMaxSlotNo (FetchRequest afs) =
foldl' max NoMaxSlotNo $ map MaxSlotNo $
mapMaybe (withOriginToMaybe . AF.headSlot) afs
data TraceFetchClientState header =
consisting of one or more individual request ranges .
AddedFetchRequest
(FetchRequest header)
(PeerFetchInFlight header)
PeerFetchInFlightLimits
(PeerFetchStatus header)
| AcknowledgedFetchRequest
(FetchRequest header)
| SendFetchRequest
(AnchoredFragment header)
PeerGSV
| the start of receiving a streaming batch of blocks . This will
be followed by one or more ' CompletedBlockFetch ' and a final
| StartedFetchBatch
(ChainRange (Point header))
(PeerFetchInFlight header)
PeerFetchInFlightLimits
(PeerFetchStatus header)
| CompletedBlockFetch
(Point header)
(PeerFetchInFlight header)
PeerFetchInFlightLimits
(PeerFetchStatus header)
NominalDiffTime
SizeInBytes
| CompletedFetchBatch
(ChainRange (Point header))
(PeerFetchInFlight header)
PeerFetchInFlightLimits
(PeerFetchStatus header)
| RejectedFetchBatch
(ChainRange (Point header))
(PeerFetchInFlight header)
PeerFetchInFlightLimits
(PeerFetchStatus header)
| ClientTerminating Int
deriving Show
addNewFetchRequest :: (MonadSTM m, HasHeader header)
=> Tracer m (TraceFetchClientState header)
-> (header -> SizeInBytes)
-> FetchRequest header
-> PeerGSV
-> FetchClientStateVars m header
-> m (PeerFetchStatus header)
addNewFetchRequest tracer blockFetchSize addedReq gsvs
FetchClientStateVars{
fetchClientRequestVar,
fetchClientInFlightVar,
fetchClientStatusVar
} = do
(inflight', currentStatus') <- atomically $ do
See the ' FetchRequest ' semigroup instance documentation for details .
oldReq <- peekTFetchRequestVar fetchClientRequestVar
mergedReq <- writeTFetchRequestVar fetchClientRequestVar
addedReq gsvs inflightlimits
inflight <- readTVar fetchClientInFlightVar
let !inflight' = addHeadersInFlight blockFetchSize
oldReq addedReq mergedReq
inflight
writeTVar fetchClientInFlightVar inflight'
currentStatus' <- updateCurrentStatus
(busyIfOverHighWatermark inflightlimits)
fetchClientStatusVar
inflight'
return (inflight', currentStatus')
traceWith tracer $
AddedFetchRequest
addedReq
inflight' inflightlimits
currentStatus'
return currentStatus'
where
inflightlimits = calculatePeerFetchInFlightLimits gsvs
acknowledgeFetchRequest :: MonadSTM m
=> Tracer m (TraceFetchClientState header)
-> ControlMessageSTM m
-> FetchClientStateVars m header
-> m (Maybe
( FetchRequest header
, PeerGSV
, PeerFetchInFlightLimits ))
acknowledgeFetchRequest tracer controlMessageSTM FetchClientStateVars {fetchClientRequestVar} = do
result <-
timeoutWithControlMessage controlMessageSTM (takeTFetchRequestVar fetchClientRequestVar)
case result of
Nothing -> return result
Just (request, _, _) -> do
traceWith tracer (AcknowledgedFetchRequest request)
return result
startedFetchBatch :: MonadSTM m
=> Tracer m (TraceFetchClientState header)
-> PeerFetchInFlightLimits
-> ChainRange (Point header)
-> FetchClientStateVars m header
-> m ()
startedFetchBatch tracer inflightlimits range
FetchClientStateVars {
fetchClientInFlightVar,
fetchClientStatusVar
} = do
(inflight, currentStatus) <-
atomically $ (,) <$> readTVar fetchClientInFlightVar
<*> readTVar fetchClientStatusVar
traceWith tracer $
StartedFetchBatch
range
inflight inflightlimits
currentStatus
completeBlockDownload :: (MonadSTM m, HasHeader header)
=> Tracer m (TraceFetchClientState header)
-> (header -> SizeInBytes)
-> PeerFetchInFlightLimits
-> header
-> NominalDiffTime
-> FetchClientStateVars m header
-> m ()
completeBlockDownload tracer blockFetchSize inflightlimits header blockDelay
FetchClientStateVars {
fetchClientInFlightVar,
fetchClientStatusVar
} = do
(inflight', currentStatus') <- atomically $ do
inflight <- readTVar fetchClientInFlightVar
let !inflight' = deleteHeaderInFlight blockFetchSize header inflight
writeTVar fetchClientInFlightVar inflight'
currentStatus' <- updateCurrentStatus
(readyIfUnderLowWatermark inflightlimits)
fetchClientStatusVar
inflight'
return (inflight', currentStatus')
traceWith tracer $
CompletedBlockFetch
(blockPoint header)
inflight' inflightlimits
currentStatus'
blockDelay
(blockFetchSize header)
completeFetchBatch :: MonadSTM m
=> Tracer m (TraceFetchClientState header)
-> PeerFetchInFlightLimits
-> ChainRange (Point header)
-> FetchClientStateVars m header
-> m ()
completeFetchBatch tracer inflightlimits range
FetchClientStateVars {
fetchClientInFlightVar,
fetchClientStatusVar
} = do
(inflight, currentStatus) <- atomically $ do
inflight <- readTVar fetchClientInFlightVar
let !inflight' =
assert (if peerFetchReqsInFlight inflight == 1
then peerFetchBytesInFlight inflight == 0
&& Set.null (peerFetchBlocksInFlight inflight)
else True)
inflight {
peerFetchReqsInFlight = peerFetchReqsInFlight inflight - 1
}
writeTVar fetchClientInFlightVar inflight'
currentStatus' <- readTVar fetchClientStatusVar >>= \case
PeerFetchStatusReady bs IsNotIdle
| Set.null bs
&& 0 == peerFetchReqsInFlight inflight'
-> let status = PeerFetchStatusReady Set.empty IsIdle
in status <$ writeTVar fetchClientStatusVar status
currentStatus -> pure currentStatus
return (inflight', currentStatus')
traceWith tracer $
CompletedFetchBatch
range
inflight inflightlimits
currentStatus
rejectedFetchBatch :: (MonadSTM m, HasHeader header)
=> Tracer m (TraceFetchClientState header)
-> (header -> SizeInBytes)
-> PeerFetchInFlightLimits
-> ChainRange (Point header)
-> [header]
-> FetchClientStateVars m header
-> m ()
rejectedFetchBatch tracer blockFetchSize inflightlimits range headers
FetchClientStateVars {
fetchClientInFlightVar,
fetchClientStatusVar
} = do
(inflight', currentStatus') <- atomically $ do
inflight <- readTVar fetchClientInFlightVar
let !inflight' =
(deleteHeadersInFlight blockFetchSize headers inflight) {
peerFetchReqsInFlight = peerFetchReqsInFlight inflight - 1
}
writeTVar fetchClientInFlightVar inflight'
currentStatus' <- updateCurrentStatus
(readyIfUnderLowWatermark inflightlimits)
fetchClientStatusVar
inflight'
return (inflight', currentStatus')
traceWith tracer $
RejectedFetchBatch
range
inflight' inflightlimits
currentStatus'
| Given a ' PeerFetchInFlight ' update the ' PeerFetchStatus ' accordingly .
This can be used with one of two policies :
* ' readyIfUnderLowWatermark '
updateCurrentStatus :: (MonadSTM m, HasHeader header)
=> (PeerFetchInFlight header -> PeerFetchStatus header)
-> StrictTVar m (PeerFetchStatus header)
-> PeerFetchInFlight header
-> STM m (PeerFetchStatus header)
updateCurrentStatus decideCurrentStatus fetchClientStatusVar inflight = do
let currentStatus' = decideCurrentStatus inflight
currentStatus <- readTVar fetchClientStatusVar
when (currentStatus' /= currentStatus) $
writeTVar fetchClientStatusVar currentStatus'
return currentStatus'
busyIfOverHighWatermark :: PeerFetchInFlightLimits
-> PeerFetchInFlight header
-> PeerFetchStatus header
busyIfOverHighWatermark inflightlimits inflight
| peerFetchBytesInFlight inflight >= inFlightBytesHighWatermark inflightlimits
= PeerFetchStatusBusy
| otherwise
= PeerFetchStatusReady
(peerFetchBlocksInFlight inflight)
(idleIf (0 == peerFetchReqsInFlight inflight))
readyIfUnderLowWatermark :: PeerFetchInFlightLimits
-> PeerFetchInFlight header
-> PeerFetchStatus header
readyIfUnderLowWatermark inflightlimits inflight
| peerFetchBytesInFlight inflight <= inFlightBytesLowWatermark inflightlimits
= PeerFetchStatusReady
(peerFetchBlocksInFlight inflight)
(idleIf (0 == peerFetchReqsInFlight inflight))
| otherwise
= PeerFetchStatusBusy
STM TFetchRequestVar
' FetchRequest 's from the logic thread to a fetch client thread .
' takeTMergeVar ' , which blocks until a value is available . On the other hand ,
type TFetchRequestVar m header =
TMergeVar m (FetchRequest header,
Last PeerGSV,
Last PeerFetchInFlightLimits)
newTFetchRequestVar :: MonadSTM m => STM m (TFetchRequestVar m header)
newTFetchRequestVar = newTMergeVar
| Write to the underlying ' TMergeVar ' and return the updated ' FetchRequest '
writeTFetchRequestVar :: (MonadSTM m, HasHeader header)
=> TFetchRequestVar m header
-> FetchRequest header
-> PeerGSV
-> PeerFetchInFlightLimits
-> STM m (FetchRequest header)
writeTFetchRequestVar v r g l = do
(r', _, _) <- writeTMergeVar v (r, Last g, Last l)
return r'
peekTFetchRequestVar :: MonadSTM m
=> TFetchRequestVar m header
-> STM m (Maybe (FetchRequest header))
peekTFetchRequestVar v = fmap (\(x, _, _) -> x) <$> tryReadTMergeVar v
takeTFetchRequestVar :: MonadSTM m
=> TFetchRequestVar m header
-> STM m (FetchRequest header,
PeerGSV,
PeerFetchInFlightLimits)
takeTFetchRequestVar v = (\(r,g,l) -> (r, getLast g, getLast l))
<$> takeTMergeVar v
STM TMergeVar mini - abstraction
This is used much like a ' TMVar ' as a one - place queue between threads but
newtype TMergeVar m a = TMergeVar (StrictTMVar m a)
newTMergeVar :: MonadSTM m => STM m (TMergeVar m a)
newTMergeVar = TMergeVar <$> newEmptyTMVar
writeTMergeVar :: (MonadSTM m, Semigroup a) => TMergeVar m a -> a -> STM m a
writeTMergeVar (TMergeVar v) x = do
mx0 <- tryTakeTMVar v
case mx0 of
Nothing -> x <$ putTMVar v x
Just x0 -> x' <$ putTMVar v x' where !x' = x0 <> x
takeTMergeVar :: MonadSTM m => TMergeVar m a -> STM m a
takeTMergeVar (TMergeVar v) = takeTMVar v
tryReadTMergeVar :: MonadSTM m
=> TMergeVar m a
-> STM m (Maybe a)
tryReadTMergeVar (TMergeVar v) = tryReadTMVar v
|
59aeb076e618d1566fbe4a5a1738703f95a2be680ac5f38bf76dcd83df956afa | racket/eopl | environments.rkt | #lang eopl
;; builds environment interface, using data structures defined in
;; data-structures.rkt.
(require "data-structures.rkt")
(provide init-env empty-env extend-env apply-env)
;;;;;;;;;;;;;;;; initial environment ;;;;;;;;;;;;;;;;
;; init-env : () -> Env
usage : ( init - env ) = [ i=1 , v=5 , x=10 ]
;; (init-env) builds an environment in which i is bound to the
expressed value 1 , v is bound to the expressed value 5 , and x is
bound to the expressed value 10 .
Page : 69
(define init-env
(lambda ()
(extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))))
;;;;;;;;;;;;;;;; environment constructors and observers ;;;;;;;;;;;;;;;;
(define empty-env
(lambda ()
(empty-env-record)))
(define empty-env?
(lambda (x)
(empty-env-record? x)))
(define extend-env
(lambda (sym val old-env)
(extended-env-record sym val old-env)))
(define apply-env
(lambda (env search-sym)
(if (empty-env? env)
(eopl:error 'apply-env "No binding for ~s" search-sym)
(let ((sym (extended-env-record->sym env))
(val (extended-env-record->val env))
(old-env (extended-env-record->old-env env)))
(if (eqv? search-sym sym)
val
(apply-env old-env search-sym))))))
| null | https://raw.githubusercontent.com/racket/eopl/43575d6e95dc34ca6e49b305180f696565e16e0f/tests/chapter3/proc-lang/ds-rep/environments.rkt | racket | builds environment interface, using data structures defined in
data-structures.rkt.
initial environment ;;;;;;;;;;;;;;;;
init-env : () -> Env
(init-env) builds an environment in which i is bound to the
environment constructors and observers ;;;;;;;;;;;;;;;; | #lang eopl
(require "data-structures.rkt")
(provide init-env empty-env extend-env apply-env)
usage : ( init - env ) = [ i=1 , v=5 , x=10 ]
expressed value 1 , v is bound to the expressed value 5 , and x is
bound to the expressed value 10 .
Page : 69
(define init-env
(lambda ()
(extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))))
(define empty-env
(lambda ()
(empty-env-record)))
(define empty-env?
(lambda (x)
(empty-env-record? x)))
(define extend-env
(lambda (sym val old-env)
(extended-env-record sym val old-env)))
(define apply-env
(lambda (env search-sym)
(if (empty-env? env)
(eopl:error 'apply-env "No binding for ~s" search-sym)
(let ((sym (extended-env-record->sym env))
(val (extended-env-record->val env))
(old-env (extended-env-record->old-env env)))
(if (eqv? search-sym sym)
val
(apply-env old-env search-sym))))))
|
184b4b0e356a11a27add7e7a5fb05ccc498c7c893ce3d66cef58669fa1aa1cd5 | weblocks-framework/weblocks | yui-panel.lisp |
(in-package :weblocks)
(export '(yui-panel panel-on-close panel-on-end-drag))
(defwidget yui-panel (yui-widget)
((on-close :type function :accessor panel-on-close :initarg :on-close :initform (constantly t))
(on-end-drag :type function :accessor panel-on-end-drag :initarg :on-end-drag :initform (constantly t)))
(:default-initargs :modules '("dragdrop" "container") :class-name |:YAHOO.widget.:Panel|))
(defmethod render-widget-body ((widget yui-panel) &rest args)
(declare (ignore args))
(send-script
(ps* `(with-lazy-loaded-modules (,(yui-modules widget) ,@(yui-loader-args widget))
(setf (global-variable ,(yui-widget-variable widget))
(new (,(yui-class-name widget) ,(yui-target-id widget)
(keywords-to-object ,(yui-component-config widget)))))
((@ (global-variable ,(yui-widget-variable widget)) render))
( console.log , ( format nil " rendered widget ~A. " ( yui - widget - variable widget ) ) )
))))
(defmethod with-widget-header ((widget yui-panel) body-fn &rest args)
(apply body-fn widget args))
| null | https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/contrib/lpolzer/yui/yui-panel.lisp | lisp |
(in-package :weblocks)
(export '(yui-panel panel-on-close panel-on-end-drag))
(defwidget yui-panel (yui-widget)
((on-close :type function :accessor panel-on-close :initarg :on-close :initform (constantly t))
(on-end-drag :type function :accessor panel-on-end-drag :initarg :on-end-drag :initform (constantly t)))
(:default-initargs :modules '("dragdrop" "container") :class-name |:YAHOO.widget.:Panel|))
(defmethod render-widget-body ((widget yui-panel) &rest args)
(declare (ignore args))
(send-script
(ps* `(with-lazy-loaded-modules (,(yui-modules widget) ,@(yui-loader-args widget))
(setf (global-variable ,(yui-widget-variable widget))
(new (,(yui-class-name widget) ,(yui-target-id widget)
(keywords-to-object ,(yui-component-config widget)))))
((@ (global-variable ,(yui-widget-variable widget)) render))
( console.log , ( format nil " rendered widget ~A. " ( yui - widget - variable widget ) ) )
))))
(defmethod with-widget-header ((widget yui-panel) body-fn &rest args)
(apply body-fn widget args))
|
|
104850d0ee49f091f4ab95ce6b00363ce5df914e7f1a193b154ece3dbda1cbde | jrh13/hol-light | examples.ml | (* ---------------------------------------------------------------------- *)
(* Paper *)
(* ---------------------------------------------------------------------- *)
---------------------------- Chebychev -----------------------------
time REAL_QELIM_CONV
`!x. --(&1) <= x /\ x <= &1 ==>
-- (&1) <= &2 * x pow 2 - &1 /\ &2 * x pow 2 - &1 <= &1`;;
DATE ------- HOL --------
5/20 4.92
5/22 4.67
DATE ------- HOL --------
5/20 4.92
5/22 4.67
*)
time REAL_QELIM_CONV
`!x. --(&1) <= x /\ x <= &1 ==>
-- (&1) <= &4 * x pow 3 - &3 * x /\ &4 * x pow 3 - &3 * x <= &1`;;
DATE ------- HOL --------
5/20 14.38
5/22 13.65
DATE ------- HOL --------
5/20 14.38
5/22 13.65
*)
time REAL_QELIM_CONV
`&1 < &2 /\ (!x. &1 < x ==> &1 < x pow 2) /\
(!x y. &1 < x /\ &1 < y ==> &1 < x * (&1 + &2 * y))`;;
DATE ------- HOL --------
5/22 23.61
DATE ------- HOL --------
5/22 23.61
*)
time REAL_QELIM_CONV
`&0 <= b /\ &0 <= c /\ &0 < a * c ==> ?u. &0 < u /\ u * (u * c - a * c) -
(u * a * c - (a pow 2 * c + b)) < a pow 2 * c + b`;;
DATE ------- HOL --------
5/22 8.78
DATE ------- HOL --------
5/22 8.78
*)
(* ------------------------------------------------------------------------- *)
(* Examples. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x^4 + x^2 + 1 = 0 > > ; ;
0.01
let fm = ` ? x. x pow 4 + x pow 2 + & 1 = & 0 ` ; ;
let vars = [ ]
time real_qelim <<exists x. x^4 + x^2 + 1 = 0>>;;
0.01
let fm = `?x. x pow 4 + x pow 2 + &1 = &0`;;
let vars = []
*)
time REAL_QELIM_CONV `?x. x pow 4 + x pow 2 + &1 = &0`;;
DATE ------- HOL --------
4/29/2005 3.19
5/19 2.2
5/20 1.96
5/22 1.53
DATE ------- HOL --------
4/29/2005 3.19
5/19 2.2
5/20 1.96
5/22 1.53
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x^3 - x^2 + x - 1 = 0 > > ; ;
0.01
time real_qelim <<exists x. x^3 - x^2 + x - 1 = 0>>;;
0.01
*)
time REAL_QELIM_CONV `?x. x pow 3 - x pow 2 + x - &1 = &0`;;
DATE ------- HOL --------
4/29/2005 3.83
5/22/2005 1.69
DATE ------- HOL --------
4/29/2005 3.83
5/22/2005 1.69
*)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < exists x y. x^3 - x^2 + x - 1 = 0 /\
y^3 - y^2 + y - 1 = 0 /\ ~(x = y ) > > ; ;
0.23
time real_qelim
<<exists x y. x^3 - x^2 + x - 1 = 0 /\
y^3 - y^2 + y - 1 = 0 /\ ~(x = y)>>;;
0.23
*)
time REAL_QELIM_CONV
`?x y. (x pow 3 - x pow 2 + x - &1 = &0) /\
(y pow 3 - y pow 2 + y - &1 = &0) /\ ~(x = y)`;;
DATE ------- HOL -------- Factor
4/29/2005 682.85 3000
5/17/2005 345.27
5/22 269
DATE ------- HOL -------- Factor
4/29/2005 682.85 3000
5/17/2005 345.27
5/22 269
*)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall a f k. ( forall e. k < e = = > f < a * e ) = = > f < = a * k > > ; ;
0.02
time real_qelim
<<forall a f k. (forall e. k < e ==> f < a * e) ==> f <= a * k>>;;
0.02
*)
time REAL_QELIM_CONV
`!a f k. (!e. k < e ==> f < a * e) ==> f <= a * k`;;
DATE ------- HOL -------- Factor
4/29/2005 20.91 1000
5/15/2005 17.98
5/17/2005 15.12
5/18/2005 12.87
5/22 12.09
DATE ------- HOL -------- Factor
4/29/2005 20.91 1000
5/15/2005 17.98
5/17/2005 15.12
5/18/2005 12.87
5/22 12.09
*)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < exists x. a * x^2 + b * x + c = 0 > > ; ;
0.01
time real_qelim
<<exists x. a * x^2 + b * x + c = 0>>;;
0.01
*)
time REAL_QELIM_CONV
`?x. a * x pow 2 + b * x + c = &0`;;
DATE ------- HOL -------- Factor
4/29/2005 10.99 1000
5/17/2005 6.42
5/18 5.39
5/22 4.74
DATE ------- HOL -------- Factor
4/29/2005 10.99 1000
5/17/2005 6.42
5/18 5.39
5/22 4.74
*)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall a b c. ( exists x. a * x^2 + b * x + c = 0 ) < = >
b^2 > = 4 * a * c > > ; ;
0.51
time real_qelim
<<forall a b c. (exists x. a * x^2 + b * x + c = 0) <=>
b^2 >= 4 * a * c>>;;
0.51
*)
time REAL_QELIM_CONV
`!a b c. (?x. a * x pow 2 + b * x + c = &0) <=>
b pow 2 >= &4 * a * c`;;
DATE ------- HOL -------- Factor
4/29/2005 1200.99 2400
5/17 878.25
DATE ------- HOL -------- Factor
4/29/2005 1200.99 2400
5/17 878.25
*)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall a b c. ( exists x. a * x^2 + b * x + c = 0 ) < = >
a = 0 /\ ( ~(b = 0 ) \/ c = 0 ) \/
~(a = 0 ) /\ b^2 > = 4 * a * c > > ; ;
0.51
time real_qelim
<<forall a b c. (exists x. a * x^2 + b * x + c = 0) <=>
a = 0 /\ (~(b = 0) \/ c = 0) \/
~(a = 0) /\ b^2 >= 4 * a * c>>;;
0.51
*)
time REAL_QELIM_CONV
`!a b c. (?x. a * x pow 2 + b * x + c = &0) <=>
(a = &0) /\ (~(b = &0) \/ (c = &0)) \/
~(a = &0) /\ b pow 2 >= &4 * a * c`;;
DATE ------- HOL -------- Factor
4/29/2005 1173.9 2400
5/17 848.4
5/20 816
1095 during depot update
DATE ------- HOL -------- Factor
4/29/2005 1173.9 2400
5/17 848.4
5/20 816
1095 during depot update
*)
time real_qelim < < exists x. 0 < = x /\ x < = 1 /\ ( r * r * x * x - r * ( 1 + r ) * x + ( 1 + r ) = 0 )
/\ ~(2 * r * x = 1 + r ) > >
time real_qelim <<exists x. 0 <= x /\ x <= 1 /\ (r * r * x * x - r * (1 + r) * x + (1 + r) = 0)
/\ ~(2 * r * x = 1 + r)>>
*)
time REAL_QELIM_CONV
`?x. &0 <= x /\ x <= &1 /\ (r pow 2 * x pow 2 - r * (&1 + r) * x + (&1 + r) = &0)
/\ ~(&2 * r * x = &1 + r)`;;
DATE ------- HOL -------- Factor
5/20/2005 19021 1460
4000 line output
DATE ------- HOL -------- Factor
5/20/2005 19021 1460
4000 line output
*)
(* ------------------------------------------------------------------------- *)
(* Termination ordering for group theory completion. *)
(* ------------------------------------------------------------------------- *)
(* ------------------------------------------------------------------------- *)
(* Left this out *)
(* ------------------------------------------------------------------------- *)
(* ------------------------------------------------------------------------- *)
(* This one works better using DNF. *)
(* ------------------------------------------------------------------------- *)
(* ------------------------------------------------------------------------- *)
(* And this *)
(* ------------------------------------------------------------------------- *)
(* ------------------------------------------------------------------------- *)
Linear examples .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x - 1 > 0 > > ; ;
0
time real_qelim <<exists x. x - 1 > 0>>;;
0
*)
time REAL_QELIM_CONV `?x. x - &1 > &0`;;
DATE ------- HOL
4/29/2005 .56
DATE ------- HOL
4/29/2005 .56
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. 3 - x > 0 /\ x - 1 > 0 > > ; ;
0
time real_qelim <<exists x. 3 - x > 0 /\ x - 1 > 0>>;;
0
*)
time REAL_QELIM_CONV `?x. &3 - x > &0 /\ x - &1 > &0`;;
DATE ------- HOL
4/29/2005 1.66
DATE ------- HOL
4/29/2005 1.66
*)
(* ------------------------------------------------------------------------- *)
Quadratics .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x^2 = 0 > > ; ;
0
time real_qelim <<exists x. x^2 = 0>>;;
0
*)
time REAL_QELIM_CONV `?x. x pow 2 = &0`;;
DATE ------- HOL
4/29/2005 1.12
DATE ------- HOL
4/29/2005 1.12
*)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x. x^2 + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 + &1 = &0`;;
DATE ------- HOL
4/29/2005 1.11
DATE ------- HOL
4/29/2005 1.11
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists = 0 > > ; ;
time real_qelim <<exists x. x^2 - 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 - &1 = &0`;;
DATE ------- HOL
4/29/2005 1.54
DATE ------- HOL
4/29/2005 1.54
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists * x + 1 = 0 > > ; ;
time real_qelim <<exists x. x^2 - 2 * x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 - &2 * x + &1 = &0`;;
DATE ------- HOL
4/29/2005 1.21
DATE ------- HOL
4/29/2005 1.21
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists * x + 1 = 0 > > ; ;
time real_qelim <<exists x. x^2 - 3 * x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 - &3 * x + &1 = &0`;;
DATE ------- HOL
4/29/2005 1.75
DATE ------- HOL
4/29/2005 1.75
*)
(* ------------------------------------------------------------------------- *)
Cubics .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x. x^3 - 1 > 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 3 - &1 > &0`;;
DATE ------- HOL
4/29/2005 1.96
DATE ------- HOL
4/29/2005 1.96
*)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x. x^3 - 3 * x^2 + 3 * x - 1 > 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 3 - &3 * x pow 2 + &3 * x - &1 > &0`;;
DATE ------- HOL
4/29/2005 1.97
DATE ------- HOL
4/29/2005 1.97
*)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x. x^3 - 4 * x^2 + 5 * x - 2 > 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 3 - &4 * x pow 2 + &5 * x - &2 > &0`;;
DATE ------- HOL
4/29/2005 4.89
DATE ------- HOL
4/29/2005 4.89
*)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x. x^3 - 6 * x^2 + 11 * x - 6 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 3 - &6 * x pow 2 + &11 * x - &6 = &0`;;
DATE ------- HOL
4/29/2005 4.17
DATE ------- HOL
4/29/2005 4.17
*)
(* ------------------------------------------------------------------------- *)
(* Quartics. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x^4 - 1 > 0 > > ; ;
time real_qelim <<exists x. x^4 - 1 > 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 - &1 > &0`;;
DATE ------- HOL
4/29/2005 3.07
DATE ------- HOL
4/29/2005 3.07
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x^4 + 1 > 0 > > ; ;
time real_qelim <<exists x. x^4 + 1 > 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 + &1 > &0`;;
DATE ------- HOL
4/29/2005 2.47
DATE ------- HOL
4/29/2005 2.47
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x^4 = 0 > > ; ;
time real_qelim <<exists x. x^4 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 = &0`;;
DATE ------- HOL
4/29/2005 2.48
DATE ------- HOL
4/29/2005 2.48
*)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x. x^4 - x^3 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 - x pow 3 = &0`;;
DATE ------- HOL
4/29/2005 1.76
DATE ------- HOL
4/29/2005 1.76
*)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x. x^4 - x^2 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 - x pow 2 = &0`;;
DATE ------- HOL
4/29/2005 2.16
DATE ------- HOL
4/29/2005 2.16
*)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x. x^4 - 2 * x^2 + 2 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 - &2 * x pow 2 + &2 = &0`;;
DATE ------- HOL
4/29/2005 6.87
5/16/2005 5.22
DATE ------- HOL
4/29/2005 6.87
5/16/2005 5.22
*)
(* ------------------------------------------------------------------------- *)
Quintics .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < exists * x^4 + 85 * x^3 - 225 * x^2 + 274 * x - 120 = 0 > > ; ;
0.03
print_timers ( )
time real_qelim
<<exists x. x^5 - 15 * x^4 + 85 * x^3 - 225 * x^2 + 274 * x - 120 = 0>>;;
0.03
print_timers()
*)
time REAL_QELIM_CONV
`?x. x pow 5 - &15 * x pow 4 + &85 * x pow 3 - &225 * x pow 2 + &274 * x - &120 = &0`;;
DATE ------- HOL -------- Factor
4/29/2005 65.64 2500
5/15/2005 55.93
5/16/2005 47.72
DATE ------- HOL -------- Factor
4/29/2005 65.64 2500
5/15/2005 55.93
5/16/2005 47.72
*)
(* ------------------------------------------------------------------------- *)
(* Sextics(?) *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x.
x^6 - 21 * + 175 * x^4 - 735 * x^3 + 1624 * x^2 - 1764 * x + 720 = 0 > > ; ;
0.15
time real_qelim <<exists x.
x^6 - 21 * x^5 + 175 * x^4 - 735 * x^3 + 1624 * x^2 - 1764 * x + 720 = 0>>;;
0.15
*)
time REAL_QELIM_CONV `?x.
x pow 6 - &21 * x pow 5 + &175 * x pow 4 - &735 * x pow 3 + &1624 * x pow 2 - &1764 * x + &720 = &0`;;
`?x. x pow 5 - &15 * x pow 4 + &85 * x pow 3 - &225 * x pow 2 + &274 * x - &120 = &0`;;
DATE ------- HOL -------- Factor
4/29/2005 1400.4 10000
DATE ------- HOL -------- Factor
4/29/2005 1400.4 10000
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x.
x^6 - 12 * + 56 * x^4 - 130 * x^3 + 159 * x^2 - 98 * x + 24 = 0 > > ; ;
7.54
time real_qelim <<exists x.
x^6 - 12 * x^5 + 56 * x^4 - 130 * x^3 + 159 * x^2 - 98 * x + 24 = 0>>;;
7.54
*)
(* NOT YET *)
time REAL_QELIM_CONV ` ? x.
x pow 6 - & 12 * x pow 5 + & 56 * x pow 4 - & 130 * x pow 3 + & 159 * x pow 2 - & 98 * x + & 24 = & 0 ` ; ;
time REAL_QELIM_CONV `?x.
x pow 6 - &12 * x pow 5 + &56 * x pow 4 - &130 * x pow 3 + &159 * x pow 2 - &98 * x + &24 = &0`;;
*)
(* ------------------------------------------------------------------------- *)
(* Multiple polynomials. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x^2 + 2 > 0 /\ x^3 - 11 = 0 /\ x + 131 > = 0 > > ; ;
time real_qelim <<exists x. x^2 + 2 > 0 /\ x^3 - 11 = 0 /\ x + 131 >= 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 + &2 > &0 /\ (x pow 3 - &11 = &0) /\ x + &131 >= &0`;;
DATE ------- HOL
4/29/2005 13.1
DATE ------- HOL
4/29/2005 13.1
*)
(* ------------------------------------------------------------------------- *)
(* With more variables. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x. a * x^2 + b * x + c = 0>>;;
*)
time REAL_QELIM_CONV `?x. a * x pow 2 + b * x + c = &0`;;
DATE ------- HOL
4/29/2005 10.94
DATE ------- HOL
4/29/2005 10.94
*)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x. a * x^3 + b * x^2 + c * x + d = 0>>;;
*)
time REAL_QELIM_CONV `?x. a * x pow 3 + b * x pow 2 + c * x + d = &0`;;
DATE ------- HOL
4/29/2005 269.17
DATE ------- HOL
4/29/2005 269.17
*)
(* ------------------------------------------------------------------------- *)
Constraint solving .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x1 x2 . x1 ^ 2 + x2 ^ 2 - u1 < = 0 /\ x1 ^ 2 - u2 > 0 > > ; ;
time real_qelim <<exists x1 x2. x1^2 + x2^2 - u1 <= 0 /\ x1^2 - u2 > 0>>;;
*)
time REAL_QELIM_CONV `?x1 x2. x1 pow 2 + x2 pow 2 - u1 <= &0 /\ x1 pow 2 - u2 > &0`;;
DATE ------- HOL
4/29/2005 89.97
DATE ------- HOL
4/29/2005 89.97
*)
(* ------------------------------------------------------------------------- *)
(* Huet & Oppen (interpretation of group theory). *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<forall x y. x > 0 /\ y > 0 ==> x * (1 + 2 * y) > 0>>;;
*)
time REAL_QELIM_CONV `!x y. x > &0 /\ y > &0 ==> x * (&1 + &2 * y) > &0`;;
DATE ------- HOL
4/29/2005 5.03
DATE ------- HOL
4/29/2005 5.03
*)
(* ------------------------------------------------------------------------- *)
(* Other examples. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists + 1 = 0 > > ; ;
time real_qelim <<exists x. x^2 - x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 - x + &1 = &0`;;
DATE ------- HOL
4/29/2005 1.19
DATE ------- HOL
4/29/2005 1.19
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists * x + 1 = 0 > > ; ;
time real_qelim <<exists x. x^2 - 3 * x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 - &3 * x + &1 = &0`;;
DATE ------- HOL
4/29/2005 1.65
DATE ------- HOL
4/29/2005 1.65
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x > 6 /\ ( x^2 - 3 * x + 1 = 0 ) > > ; ;
time real_qelim <<exists x. x > 6 /\ (x^2 - 3 * x + 1 = 0)>>;;
*)
time REAL_QELIM_CONV `?x. x > &6 /\ (x pow 2 - &3 * x + &1 = &0)`;;
DATE ------- HOL
4/29/2005 3.63
DATE ------- HOL
4/29/2005 3.63
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. 7 * x^2 - 5 * x + 3 > 0 /\
x^2 - 3 * x + 1 = 0 > > ; ;
time real_qelim <<exists x. 7 * x^2 - 5 * x + 3 > 0 /\
x^2 - 3 * x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. &7 * x pow 2 - &5 * x + &3 > &0 /\
(x pow 2 - &3 * x + &1 = &0)`;;
DATE ------- HOL
4/29/2005 8.62
DATE ------- HOL
4/29/2005 8.62
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. 11 * x^3 - 7 * x^2 - 2 * x + 1 = 0 /\
7 * x^2 - 5 * x + 3 > 0 /\
x^2 - 8 * x + 1 = 0 > > ; ;
time real_qelim <<exists x. 11 * x^3 - 7 * x^2 - 2 * x + 1 = 0 /\
7 * x^2 - 5 * x + 3 > 0 /\
x^2 - 8 * x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. (&11 * x pow 3 - &7 * x pow 2 - &2 * x + &1 = &0) /\
&7 * x pow 2 - &5 * x + &3 > &0 /\
(x pow 2 - &8 * x + &1 = &0)`;;
DATE ------- HOL
4/29/2005 221.4
DATE ------- HOL
4/29/2005 221.4
*)
(* ------------------------------------------------------------------------- *)
Quadratic inequality from Liska and
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall x. -(1 ) < = x /\ x < = 1 = = >
C * ( x - 1 ) * ( 4 * x * a * C - x * C - 4 * a * C + C - 2 ) > = 0 > > ; ;
time real_qelim
<<forall x. -(1) <= x /\ x <= 1 ==>
C * (x - 1) * (4 * x * a * C - x * C - 4 * a * C + C - 2) >= 0>>;;
*)
time REAL_QELIM_CONV
`!x. -- &1 <= x /\ x <= &1 ==>
C * (x - &1) * (&4 * x * a * C - x * C - &4 * a * C + C - &2) >= &0`;;
DATE ------- HOL
4/29/2005 1493
DATE ------- HOL
4/29/2005 1493
*)
(* ------------------------------------------------------------------------- *)
Metal - milling example from Loos and
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<exists x y. 0 < x /\
y < 0 /\
x * r - x * t + t = q * x - s * x + s /\
x * b - x * d + d = a * y - c * y + c>>;;
*)
time REAL_QELIM_CONV
`?x y. &0 < x /\
y < &0 /\
(x * r - x * t + t = q * x - s * x + s) /\
(x * b - x * d + d = a * y - c * y + c)`;;
(* ------------------------------------------------------------------------- *)
Linear example from and
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < exists r. 0 < r /\
r < 1 /\
0 < ( 1 - 3 * r ) * ( a^2 + b^2 ) + 2 * a * r /\
( 2 - 3 * r ) * ( a^2 + b^2 ) + 4 * a * r - 2 * a - r < 0 > > ; ;
time real_qelim
<<exists r. 0 < r /\
r < 1 /\
0 < (1 - 3 * r) * (a^2 + b^2) + 2 * a * r /\
(2 - 3 * r) * (a^2 + b^2) + 4 * a * r - 2 * a - r < 0>>;;
*)
time REAL_QELIM_CONV
`?r. &0 < r /\
r < &1 /\
&0 < (&1 - &3 * r) * (a pow 2 + b pow 2) + &2 * a * r /\
(&2 - &3 * r) * (a pow 2 + b pow 2) + &4 * a * r - &2 * a - r < &0`;;
(* ------------------------------------------------------------------------- *)
# 4
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<forall x y. (1 - t) * x <= (1 + t) * y /\ (1 - t) * y <= (1 + t) * x
==> 0 <= y>>;;
*)
time REAL_QELIM_CONV
`!x y. (&1 - t) * x <= (&1 + t) * y /\ (&1 - t) * y <= (&1 + t) * x
==> &0 <= y`;;
DATE ------- HOL
4/29/2005 893
DATE ------- HOL
4/29/2005 893
*)
(* ------------------------------------------------------------------------- *)
Some examples from " Real Quantifier Elimination in practice " .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x2 . x1 ^ 2 + x2 ^ 2 < = u1 /\ x1 ^ 2 > u2 > > ; ;
time real_qelim <<exists x2. x1^2 + x2^2 <= u1 /\ x1^2 > u2>>;;
*)
time REAL_QELIM_CONV `?x2. x1 pow 2 + x2 pow 2 <= u1 /\ x1 pow 2 > u2`;;
DATE ------- HOL
4/29/2005 4
DATE ------- HOL
4/29/2005 4
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x1 x2 . x1 ^ 2 + x2 ^ 2 < = u1 /\ x1 ^ 2 > u2 > > ; ;
time real_qelim <<exists x1 x2. x1^2 + x2^2 <= u1 /\ x1^2 > u2>>;;
*)
time REAL_QELIM_CONV `?x1 x2. x1 pow 2 + x2 pow 2 <= u1 /\ x1 pow 2 > u2`;;
DATE ------- HOL
4/29/2005 90
DATE ------- HOL
4/29/2005 90
*)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall x1 x2 . x1 + x2 < = 2 /\ x1 < = 1 /\ x1 > = 0 /\ x2 > = 0
= = > 3 * ( x1 + 3 * x2 ^ 2 + 2 ) < = 8 * ( 2 * x1 + x2 + 1 ) > > ; ;
time real_qelim
<<forall x1 x2. x1 + x2 <= 2 /\ x1 <= 1 /\ x1 >= 0 /\ x2 >= 0
==> 3 * (x1 + 3 * x2^2 + 2) <= 8 * (2 * x1 + x2 + 1)>>;;
*)
time REAL_QELIM_CONV
`!x1 x2. x1 + x2 <= &2 /\ x1 <= &1 /\ x1 >= &0 /\ x2 >= &0
==> &3 * (x1 + &3 * x2 pow 2 + &2) <= &8 * (&2 * x1 + x2 + &1)`;;
DATE ------- HOL
4/29/2005 18430
DATE ------- HOL
4/29/2005 18430
*)
(* ------------------------------------------------------------------------- *)
From Collins & Johnson 's " Sign variation ... " article .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists r. 0 < r /\ r < 1 /\
( 1 - 3 * r ) * ( a^2 + b^2 ) + 2 * a * r > 0 /\
( 2 - 3 * r ) * ( a^2 + b^2 ) + 4 * a * r - 2 * a - r < 0 > > ; ;
time real_qelim <<exists r. 0 < r /\ r < 1 /\
(1 - 3 * r) * (a^2 + b^2) + 2 * a * r > 0 /\
(2 - 3 * r) * (a^2 + b^2) + 4 * a * r - 2 * a - r < 0>>;;
*)
time REAL_QELIM_CONV `?r. &0 < r /\ r < &1 /\
(&1 - &3 * r) * (a pow 2 + b pow 2) + &2 * a * r > &0 /\
(&2 - &3 * r) * (a pow 2 + b pow 2) + &4 * a * r - &2 * a - r < &0`;;
DATE ------- HOL
4/29/2005 4595.11
DATE ------- HOL
4/29/2005 4595.11
*)
(* ------------------------------------------------------------------------- *)
From " Parallel implementation of CAD " article .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. forall y. x^2 + y^2 > 1 /\ x * y > = 1 > > ; ;
time real_qelim <<exists x. forall y. x^2 + y^2 > 1 /\ x * y >= 1>>;;
*)
time REAL_QELIM_CONV `?x. !y. x pow 2 + y pow 2 > &1 /\ x * y >= &1`;;
DATE ------- HOL
4/29/2005 89.51
DATE ------- HOL
4/29/2005 89.51
*)
(* ------------------------------------------------------------------------- *)
(* Other misc examples. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x y. x^2 + y^2 = 1 = = > 2 * x * y < = 1 > > ; ;
time real_qelim <<forall x y. x^2 + y^2 = 1 ==> 2 * x * y <= 1>>;;
*)
time REAL_QELIM_CONV `!x y. (x pow 2 + y pow 2 = &1) ==> &2 * x * y <= &1`;;
DATE ------- HOL
4/29/2005 83.02
DATE ------- HOL
4/29/2005 83.02
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x y. x^2 + y^2 = 1 = = > 2 * x * y < 1 > > ; ;
time real_qelim <<forall x y. x^2 + y^2 = 1 ==> 2 * x * y < 1>>;;
*)
time REAL_QELIM_CONV `!x y. (x pow 2 + y pow 2 = &1) ==> &2 * x * y < &1`;;
DATE ------- HOL
4/29/2005 83.7
DATE ------- HOL
4/29/2005 83.7
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x y. x * y > 0 < = > x > 0 /\ y > 0 \/ x < 0 /\ y < 0 > > ; ;
time real_qelim <<forall x y. x * y > 0 <=> x > 0 /\ y > 0 \/ x < 0 /\ y < 0>>;;
*)
time REAL_QELIM_CONV `!x y. x * y > &0 <=> x > &0 /\ y > &0 \/ x < &0 /\ y < &0`;;
DATE ------- HOL
4/29/2005 27.4
DATE ------- HOL
4/29/2005 27.4
*)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<exists x y. x > y /\ x^2 < y^2>>;;
*)
time REAL_QELIM_CONV `?x y. x > y /\ x pow 2 < y pow 2`;;
DATE ------- HOL
4/29/2005 1.19
DATE ------- HOL
4/29/2005 1.19
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x y. x < y = = > exists < z /\ z < y > > ; ;
time real_qelim <<forall x y. x < y ==> exists z. x < z /\ z < y>>;;
*)
time REAL_QELIM_CONV `!x y. x < y ==> ?z. x < z /\ z < y`;;
DATE ------- HOL
4/29/2005 3.8
DATE ------- HOL
4/29/2005 3.8
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x. 0 < x < = > exists y. x * y^2 = 1 > > ; ;
time real_qelim <<forall x. 0 < x <=> exists y. x * y^2 = 1>>;;
*)
time REAL_QELIM_CONV `!x. &0 < x <=> ?y. x * y pow 2 = &1`;;
DATE ------- HOL
4/29/2005 3.76
DATE ------- HOL
4/29/2005 3.76
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x. 0 < = x < = > exists y. x * y^2 = 1 > > ; ;
time real_qelim <<forall x. 0 <= x <=> exists y. x * y^2 = 1>>;;
*)
time REAL_QELIM_CONV `!x. &0 <= x <=> ?y. x * y pow 2 = &1`;;
DATE ------- HOL
4/29/2005 4.38
DATE ------- HOL
4/29/2005 4.38
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x. 0 < = x < = > exists y. x = y^2 > > ; ;
time real_qelim <<forall x. 0 <= x <=> exists y. x = y^2>>;;
*)
time REAL_QELIM_CONV `!x. &0 <= x <=> ?y. x = y pow 2`;;
DATE ------- HOL
4/29/2005 4.38
DATE ------- HOL
4/29/2005 4.38
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x y. 0 < x /\ x < y = = > exists < z^2 /\ z^2 < y > > ; ;
time real_qelim <<forall x y. 0 < x /\ x < y ==> exists z. x < z^2 /\ z^2 < y>>;;
*)
time REAL_QELIM_CONV `!x y. &0 < x /\ x < y ==> ?z. x < z pow 2 /\ z pow 2 < y`;;
DATE ------- HOL
4/29/2005 93.1
DATE ------- HOL
4/29/2005 93.1
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x y. x < y = = > exists < z^2 /\ z^2 < y > > ; ;
time real_qelim <<forall x y. x < y ==> exists z. x < z^2 /\ z^2 < y>>;;
*)
time REAL_QELIM_CONV `!x y. x < y ==> ?z. x < z pow 2 /\ z pow 2 < y`;;
DATE ------- HOL
4/29/2005 93.22
DATE ------- HOL
4/29/2005 93.22
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x y. x^2 + y^2 = 0 = = > x = 0 /\ y = 0 > > ; ;
time real_qelim <<forall x y. x^2 + y^2 = 0 ==> x = 0 /\ y = 0>>;;
*)
time REAL_QELIM_CONV `!x y. (x pow 2 + y pow 2 = &0) ==> (x = &0) /\ (y = &0)`;;
DATE ------- HOL
4/29/2005 17.21
DATE ------- HOL
4/29/2005 17.21
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x y z. x^2 + y^2 + z^2 = 0 = = > x = 0 /\ y = 0 /\ z = 0 > > ; ;
time real_qelim <<forall x y z. x^2 + y^2 + z^2 = 0 ==> x = 0 /\ y = 0 /\ z = 0>>;;
*)
time REAL_QELIM_CONV `!x y z. (x pow 2 + y pow 2 + z pow 2 = &0) ==> (x = &0) /\ (y = &0) /\ (z = &0)`;;
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall w x y + x^2 + y^2 + z^2 = 0
= = > w = 0 /\ x = 0 /\ y = 0 /\ z = 0 > > ; ;
time real_qelim <<forall w x y z. w^2 + x^2 + y^2 + z^2 = 0
==> w = 0 /\ x = 0 /\ y = 0 /\ z = 0>>;;
*)
time REAL_QELIM_CONV `!w x y z. (w pow 2 + x pow 2 + y pow 2 + z pow 2 = &0)
==> (w = &0) /\ (x = &0) /\ (y = &0) /\ (z = &0)`;;
DATE ------- HOL
4/29/2005 596
DATE ------- HOL
4/29/2005 596
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall 2 = = > forall x. ~(x^2 + a*x + 1 = 0 ) > > ; ;
time real_qelim <<forall a. a^2 = 2 ==> forall x. ~(x^2 + a*x + 1 = 0)>>;;
*)
time REAL_QELIM_CONV `!a. (a pow 2 = &2) ==> !x. ~(x pow 2 + a*x + &1 = &0)`;;
DATE ------- HOL
4/29/2005 8.7
DATE ------- HOL
4/29/2005 8.7
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall 2 = = > forall x. ~(x^2 - a*x + 1 = 0 ) > > ; ;
time real_qelim <<forall a. a^2 = 2 ==> forall x. ~(x^2 - a*x + 1 = 0)>>;;
*)
time REAL_QELIM_CONV `!a. (a pow 2 = &2) ==> !x. ~(x pow 2 - a*x + &1 = &0)`;;
DATE ------- HOL
4/29/2005 8.82
DATE ------- HOL
4/29/2005 8.82
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x y. x^2 = 2 /\ y^2 = 3 = = > ( x * y)^2 = 6 > > ; ;
time real_qelim <<forall x y. x^2 = 2 /\ y^2 = 3 ==> (x * y)^2 = 6>>;;
*)
time REAL_QELIM_CONV `!x y. (x pow 2 = &2) /\ (y pow 2 = &3) ==> ((x * y) pow 2 = &6)`;;
DATE ------- HOL
4/29/2005 48.59
DATE ------- HOL
4/29/2005 48.59
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x. exists y. x^2 = y^3 > > ; ;
time real_qelim <<forall x. exists y. x^2 = y^3>>;;
*)
time REAL_QELIM_CONV `!x. ?y. x pow 2 = y pow 3`;;
DATE ------- HOL
4/29/2005 6.93
DATE ------- HOL
4/29/2005 6.93
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x. exists y. x^3 = y^2 > > ; ;
time real_qelim <<forall x. exists y. x^3 = y^2>>;;
*)
time REAL_QELIM_CONV `!x. ?y. x pow 3 = y pow 2`;;
DATE ------- HOL
4/29/2005 5.76
DATE ------- HOL
4/29/2005 5.76
*)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<forall a b c.
(a * x^2 + b * x + c = 0) /\
(a * y^2 + b * y + c = 0) /\
~(x = y)
==> (a * (x + y) + b = 0)>>;;
*)
time REAL_QELIM_CONV
`!a b c.
(a * x pow 2 + b * x + c = &0) /\
(a * y pow 2 + b * y + c = &0) /\
~(x = y)
==> (a * (x + y) + b = &0)`;;
DATE ------- HOL
4/29/2005 76.5
DATE ------- HOL
4/29/2005 76.5
*)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall .
( y_1 = 2 * y_3 ) /\
( y_2 = 2 * y_4 ) /\
( y_1 * y_3 = y_2 * y_4 )
= = > ( y_1 ^ 2 = y_2 ^ 2 ) > > ; ;
time real_qelim
<<forall y_1 y_2 y_3 y_4.
(y_1 = 2 * y_3) /\
(y_2 = 2 * y_4) /\
(y_1 * y_3 = y_2 * y_4)
==> (y_1^2 = y_2^2)>>;;
*)
time REAL_QELIM_CONV
`!y_1 y_2 y_3 y_4.
(y_1 = &2 * y_3) /\
(y_2 = &2 * y_4) /\
(y_1 * y_3 = y_2 * y_4)
==> (y_1 pow 2 = y_2 pow 2)`;;
time real_qelim < < forall x. x^2 < 1 < = > x^4 < 1 > > ; ;
time real_qelim <<forall x. x^2 < 1 <=> x^4 < 1>>;;
*)
DATE ------- HOL
4/29/2005 1327
DATE ------- HOL
4/29/2005 1327
*)
(* ------------------------------------------------------------------------- *)
(* Counting roots. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x^3 - x^2 + x - 1 = 0 > > ; ;
time real_qelim <<exists x. x^3 - x^2 + x - 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 3 - x pow 2 + x - &1 = &0`;;
DATE ------- HOL
4/29/2005 3.8
DATE ------- HOL
4/29/2005 3.8
*)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < exists x y. x^3 - x^2 + x - 1 = 0 /\ y^3 - y^2 + y - 1 = 0 /\ ~(x = y ) > > ; ;
time real_qelim
<<exists x y. x^3 - x^2 + x - 1 = 0 /\ y^3 - y^2 + y - 1 = 0 /\ ~(x = y)>>;;
*)
time REAL_QELIM_CONV
`?x y. (x pow 3 - x pow 2 + x - &1 = &0) /\ (y pow 3 - y pow 2 + y - &1 = &0) /\ ~(x = y)`;;
DATE ------- HOL
4/29/2005 670
DATE ------- HOL
4/29/2005 670
*)
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x. x^4 + x^2 - 2 = 0 > > ; ;
time real_qelim <<exists x. x^4 + x^2 - 2 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 + x pow 2 - &2 = &0`;;
DATE ------- HOL
4/29/2005 4.9
DATE ------- HOL
4/29/2005 4.9
*)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < exists x y. x^4 + x^2 - 2 = 0 /\ y^4 + y^2 - 2 = 0 /\ ~(x = y ) > > ; ;
time real_qelim
<<exists x y. x^4 + x^2 - 2 = 0 /\ y^4 + y^2 - 2 = 0 /\ ~(x = y)>>;;
*)
time REAL_QELIM_CONV
`?x y. x pow 4 + x pow 2 - &2 = &0 /\ y pow 4 + y pow 2 - &2 = &0 /\ ~(x = y)`;;
(* --------------------------------- --------------------------------- *)
time real_qelim
< < exists x y. x^3 + x^2 - x - 1 = 0 /\ y^3 + y^2 - y - 1 = 0 /\ ~(x = y ) > > ; ;
time real_qelim
<<exists x y. x^3 + x^2 - x - 1 = 0 /\ y^3 + y^2 - y - 1 = 0 /\ ~(x = y)>>;;
*)
time REAL_QELIM_CONV
`?x y. (x pow 3 + x pow 2 - x - &1 = &0) /\ (y pow 3 + y pow 2 - y - &1 = &0) /\ ~(x = y)`;;
(* --------------------------------- --------------------------------- *)
time real_qelim < < exists x y z. x^3 + x^2 - x - 1 = 0 /\
y^3 + y^2 - y - 1 = 0 /\
z^3 + z^2 - z - 1 = 0 /\ ~(x = y ) /\ ~(x = z ) > > ; ;
time real_qelim <<exists x y z. x^3 + x^2 - x - 1 = 0 /\
y^3 + y^2 - y - 1 = 0 /\
z^3 + z^2 - z - 1 = 0 /\ ~(x = y) /\ ~(x = z)>>;;
*)
time REAL_QELIM_CONV `?x y z. (x pow 3 + x pow 2 - x - &1 = &0) /\
(y pow 3 + y pow 2 - y - &1 = &0) /\
(z pow 3 + z pow 2 - z - &1 = &0) /\ ~(x = y) /\ ~(x = z)`;;
(* ------------------------------------------------------------------------- *)
(* Existence of tangents, so to speak. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall x y. exists s = 1 /\ s * x + c * y = 0 > > ; ;
time real_qelim
<<forall x y. exists s c. s^2 + c^2 = 1 /\ s * x + c * y = 0>>;;
*)
time REAL_QELIM_CONV
`!x y. ?s c. (s pow 2 + c pow 2 = &1) /\ s * x + c * y = &0`;;
(* ------------------------------------------------------------------------- *)
(* Another useful thing (componentwise ==> normwise accuracy etc.) *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall x y. ( x + y)^2 < = 2 * ( x^2 + y^2 ) > > ; ;
time real_qelim <<forall x y. (x + y)^2 <= 2 * (x^2 + y^2)>>;;
*)
time REAL_QELIM_CONV `!x y. (x + y) pow 2 <= &2 * (x pow 2 + y pow 2)`;;
(* ------------------------------------------------------------------------- *)
(* Some related quantifier elimination problems. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim <<forall x y. (x + y)^2 <= c * (x^2 + y^2)>>;;
*)
time REAL_QELIM_CONV `!x y. (x + y) pow 2 <= c * (x pow 2 + y pow 2)`;;
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall c. ( forall x y. ( x + y)^2 < = c * ( x^2 + y^2 ) ) < = > 2 < = c > > ; ;
time real_qelim
<<forall c. (forall x y. (x + y)^2 <= c * (x^2 + y^2)) <=> 2 <= c>>;;
*)
time REAL_QELIM_CONV
`!c. (!x y. (x + y) pow 2 <= c * (x pow 2 + y pow 2)) <=> &2 <= c`;;
(* --------------------------------- --------------------------------- *)
time real_qelim < < forall a b. a * b * c < = > ; ;
time real_qelim <<forall a b. a * b * c <= a^2 + b^2>>;;
*)
time REAL_QELIM_CONV `!a b. a * b * c <= a pow 2 + b pow 2`;;
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall c. ( forall a b. a * b * c < = b^2 ) < = > c^2 < = 4 > > ; ;
time real_qelim
<<forall c. (forall a b. a * b * c <= a^2 + b^2) <=> c^2 <= 4>>;;
*)
time REAL_QELIM_CONV
`!c. (!a b. a * b * c <= a pow 2 + b pow 2) <=> c pow 2 <= &4`;;
(* ------------------------------------------------------------------------- *)
Tedious lemmas I once proved manually in HOL .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<forall a b c. 0 < a /\ 0 < b /\ 0 < c
==> 0 < a * b /\ 0 < a * c /\ 0 < b * c>>;;
*)
time REAL_QELIM_CONV
`!a b c. &0 < a /\ &0 < b /\ &0 < c
==> &0 < a * b /\ &0 < a * c /\ &0 < b * c`;;
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<forall a b c. a * b > 0 ==> (c * a < 0 <=> c * b < 0)>>;;
*)
time REAL_QELIM_CONV
`!a b c. a * b > &0 ==> (c * a < &0 <=> c * b < &0)`;;
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<forall a b c. a * b > 0 ==> (a * c < 0 <=> b * c < 0)>>;;
*)
time REAL_QELIM_CONV
`!a b c. a * b > &0 ==> (a * c < &0 <=> b * c < &0)`;;
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<forall a b. a < 0 ==> (a * b > 0 <=> b < 0)>>;;
*)
time REAL_QELIM_CONV
`!a b. a < &0 ==> (a * b > &0 <=> b < &0)`;;
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<forall a b c. a * b < 0 /\ ~(c = 0) ==> (c * a < 0 <=> ~(c * b < 0))>>;;
*)
time REAL_QELIM_CONV
`!a b c. a * b < &0 /\ ~(c = &0) ==> (c * a < &0 <=> ~(c * b < &0))`;;
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall a b. a * b < 0 < = > a > 0 /\ b < 0 \/ a < 0 /\ b > 0 > > ; ;
time real_qelim
<<forall a b. a * b < 0 <=> a > 0 /\ b < 0 \/ a < 0 /\ b > 0>>;;
*)
time REAL_QELIM_CONV
`!a b. a * b < &0 <=> a > &0 /\ b < &0 \/ a < &0 /\ b > &0`;;
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall a b. a * b < = 0 < = > a > = 0 /\ b < = 0 \/ a < = 0 /\ b > = 0 > > ; ;
time real_qelim
<<forall a b. a * b <= 0 <=> a >= 0 /\ b <= 0 \/ a <= 0 /\ b >= 0>>;;
*)
time REAL_QELIM_CONV
`!a b. a * b <= &0 <=> a >= &0 /\ b <= &0 \/ a <= &0 /\ b >= &0`;;
(* ------------------------------------------------------------------------- *)
Vaguely connected with reductions for arithmetic .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<forall a b. ~(a <= b) <=> forall d. d <= b ==> d < a>>;;
*)
time REAL_QELIM_CONV
`!a b. ~(a <= b) <=> !d. d <= b ==> d < a`;;
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<forall a b. ~(a <= b) <=> forall d. d <= b ==> ~(d = a)>>;;
*)
time REAL_QELIM_CONV
`!a b. ~(a <= b) <=> !d. d <= b ==> ~(d = a)`;;
(* --------------------------------- --------------------------------- *)
(*
time real_qelim
<<forall a b. ~(a < b) <=> forall d. d < b ==> d < a>>;;
*)
time REAL_QELIM_CONV
`!a b. ~(a < b) <=> !d. d < b ==> d < a`;;
(* ------------------------------------------------------------------------- *)
(* Another nice problem. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall x y. x^2 + y^2 = 1 = = > ( x + y)^2 < = 2 > > ; ;
time real_qelim
<<forall x y. x^2 + y^2 = 1 ==> (x + y)^2 <= 2>>;;
*)
time REAL_QELIM_CONV
`!x y. (x pow 2 + y pow 2 = &1) ==> (x + y) pow 2 <= &2`;;
(* ------------------------------------------------------------------------- *)
Some variants / intermediate steps in Cauchy - Schwartz inequality .
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall x y. 2 * x * y < = x^2 + y^2 > > ; ;
time real_qelim
<<forall x y. 2 * x * y <= x^2 + y^2>>;;
*)
time REAL_QELIM_CONV
`!x y. &2 * x * y <= x pow 2 + y pow 2`;;
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall a b c d. 2 * a * b * c * d < = a^2 * b^2 + c^2 * d^2 > > ; ;
time real_qelim
<<forall a b c d. 2 * a * b * c * d <= a^2 * b^2 + c^2 * d^2>>;;
*)
time REAL_QELIM_CONV
`!a b c d. &2 * a * b * c * d <= a pow 2 * b pow 2 + c pow 2 * d pow 2`;;
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall x1 x2 y1 y2 .
( x1 * y1 + x2 * y2)^2 < = ( x1 ^ 2 + x2 ^ 2 ) * ( y1 ^ 2 + y2 ^ 2 ) > > ; ;
time real_qelim
<<forall x1 x2 y1 y2.
(x1 * y1 + x2 * y2)^2 <= (x1^2 + x2^2) * (y1^2 + y2^2)>>;;
*)
time REAL_QELIM_CONV
`!x1 x2 y1 y2.
(x1 * y1 + x2 * y2) pow 2 <= (x1 pow 2 + x2 pow 2) * (y1 pow 2 + y2 pow 2)`;;
(* ------------------------------------------------------------------------- *)
(* The determinant example works OK here too. *)
(* ------------------------------------------------------------------------- *)
(* --------------------------------- --------------------------------- *)
time real_qelim
< < exists w x y z. ( a * w + b * y = 1 ) /\
( a * x + b * z = 0 ) /\
( c * w + d * y = 0 ) /\
( c * x + d * z = 1 ) > > ; ;
time real_qelim
<<exists w x y z. (a * w + b * y = 1) /\
(a * x + b * z = 0) /\
(c * w + d * y = 0) /\
(c * x + d * z = 1)>>;;
*)
time REAL_QELIM_CONV
`?w x y z. (a * w + b * y = &1) /\
(a * x + b * z = &0) /\
(c * w + d * y = &0) /\
(c * x + d * z = &1)`;;
(* --------------------------------- --------------------------------- *)
time real_qelim
< < forall a b c d.
( exists w x y z. ( a * w + b * y = 1 ) /\
( a * x + b * z = 0 ) /\
( c * w + d * y = 0 ) /\
( c * x + d * z = 1 ) )
< = > ~(a * d = b * c ) > > ; ;
time real_qelim
<<forall a b c d.
(exists w x y z. (a * w + b * y = 1) /\
(a * x + b * z = 0) /\
(c * w + d * y = 0) /\
(c * x + d * z = 1))
<=> ~(a * d = b * c)>>;;
*)
time REAL_QELIM_CONV
`!a b c d.
(?w x y z. (a * w + b * y = &1) /\
(a * x + b * z = &0) /\
(c * w + d * y = &0) /\
(c * x + d * z = &1))
<=> ~(a * d = b * c)`;;
(* ------------------------------------------------------------------------- *)
From applying .
(* ------------------------------------------------------------------------- *)
let th = prove
(`&0 <= c' /\ &0 <= c /\ &0 < h * c'
==> (?u. &0 < u /\
(!v. &0 < v /\ v <= u
==> v * (v * (h * h * c' + c) - h * c') - (v * h * c' - c') <
c'))`,
W(fun (asl,w) -> MAP_EVERY (fun v -> SPEC_TAC(v,v)) (frees w)) THEN
CONV_TAC REAL_QELIM_CONV);;
(* ------------------------------------------------------------------------- *)
Two notions of parallelism .
(* ------------------------------------------------------------------------- *)
time REAL_QELIM_CONV
`!x1 x2 y1 y2. (?c. (x2 = c * x1) /\ (y2 = c * y1)) <=>
(x1 = &0 /\ y1 = &0 ==> x2 = &0 /\ y2 = &0) /\
x1 * y2 = x2 * y1`;;
(* ------------------------------------------------------------------------- *)
From ( takes about 300 seconds ) .
(* ------------------------------------------------------------------------- *)
time REAL_QELIM_CONV
`!x. &0 <= x /\ x <= &1
==> &0 < &1 - x + x pow 2 / &2 - x pow 3 / &6 /\
&1 <= (&1 + x + x pow 2) *
(&1 - x + x pow 2 / &2 - x pow 3 / &6)`;;
(* ------------------------------------------------------------------------- *)
(* A natural simplification of "limit of a product" result. *)
Takes about 450 seconds .
(* ------------------------------------------------------------------------- *)
* * Would actually like to get rid of abs internally and state it like this :
time REAL_QELIM_CONV
` ! x y e. & 0 < e = = > ? d. & 0 < d /\ ) * ( y + d ) - x * y ) < e ` ; ;
* * *
time REAL_QELIM_CONV
`!x y e. &0 < e ==> ?d. &0 < d /\ abs((x + d) * (y + d) - x * y) < e`;;
****)
time REAL_QELIM_CONV
`!x y e. &0 < e ==> ?d. &0 < d /\ (x + d) * (y + d) - x * y < e /\
x * y - (x + d) * (y + d) < e`;;
| null | https://raw.githubusercontent.com/jrh13/hol-light/d125b0ae73e546a63ed458a7891f4e14ae0409e2/Rqe/examples.ml | ocaml | ----------------------------------------------------------------------
Paper
----------------------------------------------------------------------
-------------------------------------------------------------------------
Examples.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
Termination ordering for group theory completion.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Left this out
-------------------------------------------------------------------------
-------------------------------------------------------------------------
This one works better using DNF.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
And this
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
time real_qelim <<exists x. x^2 + 1 = 0>>;;
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
time real_qelim <<exists x. x^3 - 1 > 0>>;;
--------------------------------- ---------------------------------
time real_qelim <<exists x. x^3 - 3 * x^2 + 3 * x - 1 > 0>>;;
--------------------------------- ---------------------------------
time real_qelim <<exists x. x^3 - 4 * x^2 + 5 * x - 2 > 0>>;;
--------------------------------- ---------------------------------
time real_qelim <<exists x. x^3 - 6 * x^2 + 11 * x - 6 = 0>>;;
-------------------------------------------------------------------------
Quartics.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
time real_qelim <<exists x. x^4 - x^3 = 0>>;;
--------------------------------- ---------------------------------
time real_qelim <<exists x. x^4 - x^2 = 0>>;;
--------------------------------- ---------------------------------
time real_qelim <<exists x. x^4 - 2 * x^2 + 2 = 0>>;;
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
Sextics(?)
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
NOT YET
-------------------------------------------------------------------------
Multiple polynomials.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
With more variables.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
time real_qelim <<exists x. a * x^2 + b * x + c = 0>>;;
--------------------------------- ---------------------------------
time real_qelim <<exists x. a * x^3 + b * x^2 + c * x + d = 0>>;;
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
Huet & Oppen (interpretation of group theory).
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
time real_qelim <<forall x y. x > 0 /\ y > 0 ==> x * (1 + 2 * y) > 0>>;;
-------------------------------------------------------------------------
Other examples.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
time real_qelim
<<exists x y. 0 < x /\
y < 0 /\
x * r - x * t + t = q * x - s * x + s /\
x * b - x * d + d = a * y - c * y + c>>;;
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
time real_qelim
<<forall x y. (1 - t) * x <= (1 + t) * y /\ (1 - t) * y <= (1 + t) * x
==> 0 <= y>>;;
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
Other misc examples.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
time real_qelim <<exists x y. x > y /\ x^2 < y^2>>;;
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
time real_qelim
<<forall a b c.
(a * x^2 + b * x + c = 0) /\
(a * y^2 + b * y + c = 0) /\
~(x = y)
==> (a * (x + y) + b = 0)>>;;
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
Counting roots.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
Existence of tangents, so to speak.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
Another useful thing (componentwise ==> normwise accuracy etc.)
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
Some related quantifier elimination problems.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
time real_qelim <<forall x y. (x + y)^2 <= c * (x^2 + y^2)>>;;
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
time real_qelim
<<forall a b c. 0 < a /\ 0 < b /\ 0 < c
==> 0 < a * b /\ 0 < a * c /\ 0 < b * c>>;;
--------------------------------- ---------------------------------
time real_qelim
<<forall a b c. a * b > 0 ==> (c * a < 0 <=> c * b < 0)>>;;
--------------------------------- ---------------------------------
time real_qelim
<<forall a b c. a * b > 0 ==> (a * c < 0 <=> b * c < 0)>>;;
--------------------------------- ---------------------------------
time real_qelim
<<forall a b. a < 0 ==> (a * b > 0 <=> b < 0)>>;;
--------------------------------- ---------------------------------
time real_qelim
<<forall a b c. a * b < 0 /\ ~(c = 0) ==> (c * a < 0 <=> ~(c * b < 0))>>;;
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
time real_qelim
<<forall a b. ~(a <= b) <=> forall d. d <= b ==> d < a>>;;
--------------------------------- ---------------------------------
time real_qelim
<<forall a b. ~(a <= b) <=> forall d. d <= b ==> ~(d = a)>>;;
--------------------------------- ---------------------------------
time real_qelim
<<forall a b. ~(a < b) <=> forall d. d < b ==> d < a>>;;
-------------------------------------------------------------------------
Another nice problem.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
The determinant example works OK here too.
-------------------------------------------------------------------------
--------------------------------- ---------------------------------
--------------------------------- ---------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
A natural simplification of "limit of a product" result.
------------------------------------------------------------------------- |
---------------------------- Chebychev -----------------------------
time REAL_QELIM_CONV
`!x. --(&1) <= x /\ x <= &1 ==>
-- (&1) <= &2 * x pow 2 - &1 /\ &2 * x pow 2 - &1 <= &1`;;
DATE ------- HOL --------
5/20 4.92
5/22 4.67
DATE ------- HOL --------
5/20 4.92
5/22 4.67
*)
time REAL_QELIM_CONV
`!x. --(&1) <= x /\ x <= &1 ==>
-- (&1) <= &4 * x pow 3 - &3 * x /\ &4 * x pow 3 - &3 * x <= &1`;;
DATE ------- HOL --------
5/20 14.38
5/22 13.65
DATE ------- HOL --------
5/20 14.38
5/22 13.65
*)
time REAL_QELIM_CONV
`&1 < &2 /\ (!x. &1 < x ==> &1 < x pow 2) /\
(!x y. &1 < x /\ &1 < y ==> &1 < x * (&1 + &2 * y))`;;
DATE ------- HOL --------
5/22 23.61
DATE ------- HOL --------
5/22 23.61
*)
time REAL_QELIM_CONV
`&0 <= b /\ &0 <= c /\ &0 < a * c ==> ?u. &0 < u /\ u * (u * c - a * c) -
(u * a * c - (a pow 2 * c + b)) < a pow 2 * c + b`;;
DATE ------- HOL --------
5/22 8.78
DATE ------- HOL --------
5/22 8.78
*)
time real_qelim < < exists x. x^4 + x^2 + 1 = 0 > > ; ;
0.01
let fm = ` ? x. x pow 4 + x pow 2 + & 1 = & 0 ` ; ;
let vars = [ ]
time real_qelim <<exists x. x^4 + x^2 + 1 = 0>>;;
0.01
let fm = `?x. x pow 4 + x pow 2 + &1 = &0`;;
let vars = []
*)
time REAL_QELIM_CONV `?x. x pow 4 + x pow 2 + &1 = &0`;;
DATE ------- HOL --------
4/29/2005 3.19
5/19 2.2
5/20 1.96
5/22 1.53
DATE ------- HOL --------
4/29/2005 3.19
5/19 2.2
5/20 1.96
5/22 1.53
*)
time real_qelim < < exists x. x^3 - x^2 + x - 1 = 0 > > ; ;
0.01
time real_qelim <<exists x. x^3 - x^2 + x - 1 = 0>>;;
0.01
*)
time REAL_QELIM_CONV `?x. x pow 3 - x pow 2 + x - &1 = &0`;;
DATE ------- HOL --------
4/29/2005 3.83
5/22/2005 1.69
DATE ------- HOL --------
4/29/2005 3.83
5/22/2005 1.69
*)
time real_qelim
< < exists x y. x^3 - x^2 + x - 1 = 0 /\
y^3 - y^2 + y - 1 = 0 /\ ~(x = y ) > > ; ;
0.23
time real_qelim
<<exists x y. x^3 - x^2 + x - 1 = 0 /\
y^3 - y^2 + y - 1 = 0 /\ ~(x = y)>>;;
0.23
*)
time REAL_QELIM_CONV
`?x y. (x pow 3 - x pow 2 + x - &1 = &0) /\
(y pow 3 - y pow 2 + y - &1 = &0) /\ ~(x = y)`;;
DATE ------- HOL -------- Factor
4/29/2005 682.85 3000
5/17/2005 345.27
5/22 269
DATE ------- HOL -------- Factor
4/29/2005 682.85 3000
5/17/2005 345.27
5/22 269
*)
time real_qelim
< < forall a f k. ( forall e. k < e = = > f < a * e ) = = > f < = a * k > > ; ;
0.02
time real_qelim
<<forall a f k. (forall e. k < e ==> f < a * e) ==> f <= a * k>>;;
0.02
*)
time REAL_QELIM_CONV
`!a f k. (!e. k < e ==> f < a * e) ==> f <= a * k`;;
DATE ------- HOL -------- Factor
4/29/2005 20.91 1000
5/15/2005 17.98
5/17/2005 15.12
5/18/2005 12.87
5/22 12.09
DATE ------- HOL -------- Factor
4/29/2005 20.91 1000
5/15/2005 17.98
5/17/2005 15.12
5/18/2005 12.87
5/22 12.09
*)
time real_qelim
< < exists x. a * x^2 + b * x + c = 0 > > ; ;
0.01
time real_qelim
<<exists x. a * x^2 + b * x + c = 0>>;;
0.01
*)
time REAL_QELIM_CONV
`?x. a * x pow 2 + b * x + c = &0`;;
DATE ------- HOL -------- Factor
4/29/2005 10.99 1000
5/17/2005 6.42
5/18 5.39
5/22 4.74
DATE ------- HOL -------- Factor
4/29/2005 10.99 1000
5/17/2005 6.42
5/18 5.39
5/22 4.74
*)
time real_qelim
< < forall a b c. ( exists x. a * x^2 + b * x + c = 0 ) < = >
b^2 > = 4 * a * c > > ; ;
0.51
time real_qelim
<<forall a b c. (exists x. a * x^2 + b * x + c = 0) <=>
b^2 >= 4 * a * c>>;;
0.51
*)
time REAL_QELIM_CONV
`!a b c. (?x. a * x pow 2 + b * x + c = &0) <=>
b pow 2 >= &4 * a * c`;;
DATE ------- HOL -------- Factor
4/29/2005 1200.99 2400
5/17 878.25
DATE ------- HOL -------- Factor
4/29/2005 1200.99 2400
5/17 878.25
*)
time real_qelim
< < forall a b c. ( exists x. a * x^2 + b * x + c = 0 ) < = >
a = 0 /\ ( ~(b = 0 ) \/ c = 0 ) \/
~(a = 0 ) /\ b^2 > = 4 * a * c > > ; ;
0.51
time real_qelim
<<forall a b c. (exists x. a * x^2 + b * x + c = 0) <=>
a = 0 /\ (~(b = 0) \/ c = 0) \/
~(a = 0) /\ b^2 >= 4 * a * c>>;;
0.51
*)
time REAL_QELIM_CONV
`!a b c. (?x. a * x pow 2 + b * x + c = &0) <=>
(a = &0) /\ (~(b = &0) \/ (c = &0)) \/
~(a = &0) /\ b pow 2 >= &4 * a * c`;;
DATE ------- HOL -------- Factor
4/29/2005 1173.9 2400
5/17 848.4
5/20 816
1095 during depot update
DATE ------- HOL -------- Factor
4/29/2005 1173.9 2400
5/17 848.4
5/20 816
1095 during depot update
*)
time real_qelim < < exists x. 0 < = x /\ x < = 1 /\ ( r * r * x * x - r * ( 1 + r ) * x + ( 1 + r ) = 0 )
/\ ~(2 * r * x = 1 + r ) > >
time real_qelim <<exists x. 0 <= x /\ x <= 1 /\ (r * r * x * x - r * (1 + r) * x + (1 + r) = 0)
/\ ~(2 * r * x = 1 + r)>>
*)
time REAL_QELIM_CONV
`?x. &0 <= x /\ x <= &1 /\ (r pow 2 * x pow 2 - r * (&1 + r) * x + (&1 + r) = &0)
/\ ~(&2 * r * x = &1 + r)`;;
DATE ------- HOL -------- Factor
5/20/2005 19021 1460
4000 line output
DATE ------- HOL -------- Factor
5/20/2005 19021 1460
4000 line output
*)
Linear examples .
time real_qelim < < exists x. x - 1 > 0 > > ; ;
0
time real_qelim <<exists x. x - 1 > 0>>;;
0
*)
time REAL_QELIM_CONV `?x. x - &1 > &0`;;
DATE ------- HOL
4/29/2005 .56
DATE ------- HOL
4/29/2005 .56
*)
time real_qelim < < exists x. 3 - x > 0 /\ x - 1 > 0 > > ; ;
0
time real_qelim <<exists x. 3 - x > 0 /\ x - 1 > 0>>;;
0
*)
time REAL_QELIM_CONV `?x. &3 - x > &0 /\ x - &1 > &0`;;
DATE ------- HOL
4/29/2005 1.66
DATE ------- HOL
4/29/2005 1.66
*)
Quadratics .
time real_qelim < < exists x. x^2 = 0 > > ; ;
0
time real_qelim <<exists x. x^2 = 0>>;;
0
*)
time REAL_QELIM_CONV `?x. x pow 2 = &0`;;
DATE ------- HOL
4/29/2005 1.12
DATE ------- HOL
4/29/2005 1.12
*)
time REAL_QELIM_CONV `?x. x pow 2 + &1 = &0`;;
DATE ------- HOL
4/29/2005 1.11
DATE ------- HOL
4/29/2005 1.11
*)
time real_qelim < < exists = 0 > > ; ;
time real_qelim <<exists x. x^2 - 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 - &1 = &0`;;
DATE ------- HOL
4/29/2005 1.54
DATE ------- HOL
4/29/2005 1.54
*)
time real_qelim < < exists * x + 1 = 0 > > ; ;
time real_qelim <<exists x. x^2 - 2 * x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 - &2 * x + &1 = &0`;;
DATE ------- HOL
4/29/2005 1.21
DATE ------- HOL
4/29/2005 1.21
*)
time real_qelim < < exists * x + 1 = 0 > > ; ;
time real_qelim <<exists x. x^2 - 3 * x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 - &3 * x + &1 = &0`;;
DATE ------- HOL
4/29/2005 1.75
DATE ------- HOL
4/29/2005 1.75
*)
Cubics .
time REAL_QELIM_CONV `?x. x pow 3 - &1 > &0`;;
DATE ------- HOL
4/29/2005 1.96
DATE ------- HOL
4/29/2005 1.96
*)
time REAL_QELIM_CONV `?x. x pow 3 - &3 * x pow 2 + &3 * x - &1 > &0`;;
DATE ------- HOL
4/29/2005 1.97
DATE ------- HOL
4/29/2005 1.97
*)
time REAL_QELIM_CONV `?x. x pow 3 - &4 * x pow 2 + &5 * x - &2 > &0`;;
DATE ------- HOL
4/29/2005 4.89
DATE ------- HOL
4/29/2005 4.89
*)
time REAL_QELIM_CONV `?x. x pow 3 - &6 * x pow 2 + &11 * x - &6 = &0`;;
DATE ------- HOL
4/29/2005 4.17
DATE ------- HOL
4/29/2005 4.17
*)
time real_qelim < < exists x. x^4 - 1 > 0 > > ; ;
time real_qelim <<exists x. x^4 - 1 > 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 - &1 > &0`;;
DATE ------- HOL
4/29/2005 3.07
DATE ------- HOL
4/29/2005 3.07
*)
time real_qelim < < exists x. x^4 + 1 > 0 > > ; ;
time real_qelim <<exists x. x^4 + 1 > 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 + &1 > &0`;;
DATE ------- HOL
4/29/2005 2.47
DATE ------- HOL
4/29/2005 2.47
*)
time real_qelim < < exists x. x^4 = 0 > > ; ;
time real_qelim <<exists x. x^4 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 = &0`;;
DATE ------- HOL
4/29/2005 2.48
DATE ------- HOL
4/29/2005 2.48
*)
time REAL_QELIM_CONV `?x. x pow 4 - x pow 3 = &0`;;
DATE ------- HOL
4/29/2005 1.76
DATE ------- HOL
4/29/2005 1.76
*)
time REAL_QELIM_CONV `?x. x pow 4 - x pow 2 = &0`;;
DATE ------- HOL
4/29/2005 2.16
DATE ------- HOL
4/29/2005 2.16
*)
time REAL_QELIM_CONV `?x. x pow 4 - &2 * x pow 2 + &2 = &0`;;
DATE ------- HOL
4/29/2005 6.87
5/16/2005 5.22
DATE ------- HOL
4/29/2005 6.87
5/16/2005 5.22
*)
Quintics .
time real_qelim
< < exists * x^4 + 85 * x^3 - 225 * x^2 + 274 * x - 120 = 0 > > ; ;
0.03
print_timers ( )
time real_qelim
<<exists x. x^5 - 15 * x^4 + 85 * x^3 - 225 * x^2 + 274 * x - 120 = 0>>;;
0.03
print_timers()
*)
time REAL_QELIM_CONV
`?x. x pow 5 - &15 * x pow 4 + &85 * x pow 3 - &225 * x pow 2 + &274 * x - &120 = &0`;;
DATE ------- HOL -------- Factor
4/29/2005 65.64 2500
5/15/2005 55.93
5/16/2005 47.72
DATE ------- HOL -------- Factor
4/29/2005 65.64 2500
5/15/2005 55.93
5/16/2005 47.72
*)
time real_qelim < < exists x.
x^6 - 21 * + 175 * x^4 - 735 * x^3 + 1624 * x^2 - 1764 * x + 720 = 0 > > ; ;
0.15
time real_qelim <<exists x.
x^6 - 21 * x^5 + 175 * x^4 - 735 * x^3 + 1624 * x^2 - 1764 * x + 720 = 0>>;;
0.15
*)
time REAL_QELIM_CONV `?x.
x pow 6 - &21 * x pow 5 + &175 * x pow 4 - &735 * x pow 3 + &1624 * x pow 2 - &1764 * x + &720 = &0`;;
`?x. x pow 5 - &15 * x pow 4 + &85 * x pow 3 - &225 * x pow 2 + &274 * x - &120 = &0`;;
DATE ------- HOL -------- Factor
4/29/2005 1400.4 10000
DATE ------- HOL -------- Factor
4/29/2005 1400.4 10000
*)
time real_qelim < < exists x.
x^6 - 12 * + 56 * x^4 - 130 * x^3 + 159 * x^2 - 98 * x + 24 = 0 > > ; ;
7.54
time real_qelim <<exists x.
x^6 - 12 * x^5 + 56 * x^4 - 130 * x^3 + 159 * x^2 - 98 * x + 24 = 0>>;;
7.54
*)
time REAL_QELIM_CONV ` ? x.
x pow 6 - & 12 * x pow 5 + & 56 * x pow 4 - & 130 * x pow 3 + & 159 * x pow 2 - & 98 * x + & 24 = & 0 ` ; ;
time REAL_QELIM_CONV `?x.
x pow 6 - &12 * x pow 5 + &56 * x pow 4 - &130 * x pow 3 + &159 * x pow 2 - &98 * x + &24 = &0`;;
*)
time real_qelim < < exists x. x^2 + 2 > 0 /\ x^3 - 11 = 0 /\ x + 131 > = 0 > > ; ;
time real_qelim <<exists x. x^2 + 2 > 0 /\ x^3 - 11 = 0 /\ x + 131 >= 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 + &2 > &0 /\ (x pow 3 - &11 = &0) /\ x + &131 >= &0`;;
DATE ------- HOL
4/29/2005 13.1
DATE ------- HOL
4/29/2005 13.1
*)
time REAL_QELIM_CONV `?x. a * x pow 2 + b * x + c = &0`;;
DATE ------- HOL
4/29/2005 10.94
DATE ------- HOL
4/29/2005 10.94
*)
time REAL_QELIM_CONV `?x. a * x pow 3 + b * x pow 2 + c * x + d = &0`;;
DATE ------- HOL
4/29/2005 269.17
DATE ------- HOL
4/29/2005 269.17
*)
Constraint solving .
time real_qelim < < exists x1 x2 . x1 ^ 2 + x2 ^ 2 - u1 < = 0 /\ x1 ^ 2 - u2 > 0 > > ; ;
time real_qelim <<exists x1 x2. x1^2 + x2^2 - u1 <= 0 /\ x1^2 - u2 > 0>>;;
*)
time REAL_QELIM_CONV `?x1 x2. x1 pow 2 + x2 pow 2 - u1 <= &0 /\ x1 pow 2 - u2 > &0`;;
DATE ------- HOL
4/29/2005 89.97
DATE ------- HOL
4/29/2005 89.97
*)
time REAL_QELIM_CONV `!x y. x > &0 /\ y > &0 ==> x * (&1 + &2 * y) > &0`;;
DATE ------- HOL
4/29/2005 5.03
DATE ------- HOL
4/29/2005 5.03
*)
time real_qelim < < exists + 1 = 0 > > ; ;
time real_qelim <<exists x. x^2 - x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 - x + &1 = &0`;;
DATE ------- HOL
4/29/2005 1.19
DATE ------- HOL
4/29/2005 1.19
*)
time real_qelim < < exists * x + 1 = 0 > > ; ;
time real_qelim <<exists x. x^2 - 3 * x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 2 - &3 * x + &1 = &0`;;
DATE ------- HOL
4/29/2005 1.65
DATE ------- HOL
4/29/2005 1.65
*)
time real_qelim < < exists x. x > 6 /\ ( x^2 - 3 * x + 1 = 0 ) > > ; ;
time real_qelim <<exists x. x > 6 /\ (x^2 - 3 * x + 1 = 0)>>;;
*)
time REAL_QELIM_CONV `?x. x > &6 /\ (x pow 2 - &3 * x + &1 = &0)`;;
DATE ------- HOL
4/29/2005 3.63
DATE ------- HOL
4/29/2005 3.63
*)
time real_qelim < < exists x. 7 * x^2 - 5 * x + 3 > 0 /\
x^2 - 3 * x + 1 = 0 > > ; ;
time real_qelim <<exists x. 7 * x^2 - 5 * x + 3 > 0 /\
x^2 - 3 * x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. &7 * x pow 2 - &5 * x + &3 > &0 /\
(x pow 2 - &3 * x + &1 = &0)`;;
DATE ------- HOL
4/29/2005 8.62
DATE ------- HOL
4/29/2005 8.62
*)
time real_qelim < < exists x. 11 * x^3 - 7 * x^2 - 2 * x + 1 = 0 /\
7 * x^2 - 5 * x + 3 > 0 /\
x^2 - 8 * x + 1 = 0 > > ; ;
time real_qelim <<exists x. 11 * x^3 - 7 * x^2 - 2 * x + 1 = 0 /\
7 * x^2 - 5 * x + 3 > 0 /\
x^2 - 8 * x + 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. (&11 * x pow 3 - &7 * x pow 2 - &2 * x + &1 = &0) /\
&7 * x pow 2 - &5 * x + &3 > &0 /\
(x pow 2 - &8 * x + &1 = &0)`;;
DATE ------- HOL
4/29/2005 221.4
DATE ------- HOL
4/29/2005 221.4
*)
Quadratic inequality from Liska and
time real_qelim
< < forall x. -(1 ) < = x /\ x < = 1 = = >
C * ( x - 1 ) * ( 4 * x * a * C - x * C - 4 * a * C + C - 2 ) > = 0 > > ; ;
time real_qelim
<<forall x. -(1) <= x /\ x <= 1 ==>
C * (x - 1) * (4 * x * a * C - x * C - 4 * a * C + C - 2) >= 0>>;;
*)
time REAL_QELIM_CONV
`!x. -- &1 <= x /\ x <= &1 ==>
C * (x - &1) * (&4 * x * a * C - x * C - &4 * a * C + C - &2) >= &0`;;
DATE ------- HOL
4/29/2005 1493
DATE ------- HOL
4/29/2005 1493
*)
Metal - milling example from Loos and
time REAL_QELIM_CONV
`?x y. &0 < x /\
y < &0 /\
(x * r - x * t + t = q * x - s * x + s) /\
(x * b - x * d + d = a * y - c * y + c)`;;
Linear example from and
time real_qelim
< < exists r. 0 < r /\
r < 1 /\
0 < ( 1 - 3 * r ) * ( a^2 + b^2 ) + 2 * a * r /\
( 2 - 3 * r ) * ( a^2 + b^2 ) + 4 * a * r - 2 * a - r < 0 > > ; ;
time real_qelim
<<exists r. 0 < r /\
r < 1 /\
0 < (1 - 3 * r) * (a^2 + b^2) + 2 * a * r /\
(2 - 3 * r) * (a^2 + b^2) + 4 * a * r - 2 * a - r < 0>>;;
*)
time REAL_QELIM_CONV
`?r. &0 < r /\
r < &1 /\
&0 < (&1 - &3 * r) * (a pow 2 + b pow 2) + &2 * a * r /\
(&2 - &3 * r) * (a pow 2 + b pow 2) + &4 * a * r - &2 * a - r < &0`;;
# 4
time REAL_QELIM_CONV
`!x y. (&1 - t) * x <= (&1 + t) * y /\ (&1 - t) * y <= (&1 + t) * x
==> &0 <= y`;;
DATE ------- HOL
4/29/2005 893
DATE ------- HOL
4/29/2005 893
*)
Some examples from " Real Quantifier Elimination in practice " .
time real_qelim < < exists x2 . x1 ^ 2 + x2 ^ 2 < = u1 /\ x1 ^ 2 > u2 > > ; ;
time real_qelim <<exists x2. x1^2 + x2^2 <= u1 /\ x1^2 > u2>>;;
*)
time REAL_QELIM_CONV `?x2. x1 pow 2 + x2 pow 2 <= u1 /\ x1 pow 2 > u2`;;
DATE ------- HOL
4/29/2005 4
DATE ------- HOL
4/29/2005 4
*)
time real_qelim < < exists x1 x2 . x1 ^ 2 + x2 ^ 2 < = u1 /\ x1 ^ 2 > u2 > > ; ;
time real_qelim <<exists x1 x2. x1^2 + x2^2 <= u1 /\ x1^2 > u2>>;;
*)
time REAL_QELIM_CONV `?x1 x2. x1 pow 2 + x2 pow 2 <= u1 /\ x1 pow 2 > u2`;;
DATE ------- HOL
4/29/2005 90
DATE ------- HOL
4/29/2005 90
*)
time real_qelim
< < forall x1 x2 . x1 + x2 < = 2 /\ x1 < = 1 /\ x1 > = 0 /\ x2 > = 0
= = > 3 * ( x1 + 3 * x2 ^ 2 + 2 ) < = 8 * ( 2 * x1 + x2 + 1 ) > > ; ;
time real_qelim
<<forall x1 x2. x1 + x2 <= 2 /\ x1 <= 1 /\ x1 >= 0 /\ x2 >= 0
==> 3 * (x1 + 3 * x2^2 + 2) <= 8 * (2 * x1 + x2 + 1)>>;;
*)
time REAL_QELIM_CONV
`!x1 x2. x1 + x2 <= &2 /\ x1 <= &1 /\ x1 >= &0 /\ x2 >= &0
==> &3 * (x1 + &3 * x2 pow 2 + &2) <= &8 * (&2 * x1 + x2 + &1)`;;
DATE ------- HOL
4/29/2005 18430
DATE ------- HOL
4/29/2005 18430
*)
From Collins & Johnson 's " Sign variation ... " article .
time real_qelim < < exists r. 0 < r /\ r < 1 /\
( 1 - 3 * r ) * ( a^2 + b^2 ) + 2 * a * r > 0 /\
( 2 - 3 * r ) * ( a^2 + b^2 ) + 4 * a * r - 2 * a - r < 0 > > ; ;
time real_qelim <<exists r. 0 < r /\ r < 1 /\
(1 - 3 * r) * (a^2 + b^2) + 2 * a * r > 0 /\
(2 - 3 * r) * (a^2 + b^2) + 4 * a * r - 2 * a - r < 0>>;;
*)
time REAL_QELIM_CONV `?r. &0 < r /\ r < &1 /\
(&1 - &3 * r) * (a pow 2 + b pow 2) + &2 * a * r > &0 /\
(&2 - &3 * r) * (a pow 2 + b pow 2) + &4 * a * r - &2 * a - r < &0`;;
DATE ------- HOL
4/29/2005 4595.11
DATE ------- HOL
4/29/2005 4595.11
*)
From " Parallel implementation of CAD " article .
time real_qelim < < exists x. forall y. x^2 + y^2 > 1 /\ x * y > = 1 > > ; ;
time real_qelim <<exists x. forall y. x^2 + y^2 > 1 /\ x * y >= 1>>;;
*)
time REAL_QELIM_CONV `?x. !y. x pow 2 + y pow 2 > &1 /\ x * y >= &1`;;
DATE ------- HOL
4/29/2005 89.51
DATE ------- HOL
4/29/2005 89.51
*)
time real_qelim < < forall x y. x^2 + y^2 = 1 = = > 2 * x * y < = 1 > > ; ;
time real_qelim <<forall x y. x^2 + y^2 = 1 ==> 2 * x * y <= 1>>;;
*)
time REAL_QELIM_CONV `!x y. (x pow 2 + y pow 2 = &1) ==> &2 * x * y <= &1`;;
DATE ------- HOL
4/29/2005 83.02
DATE ------- HOL
4/29/2005 83.02
*)
time real_qelim < < forall x y. x^2 + y^2 = 1 = = > 2 * x * y < 1 > > ; ;
time real_qelim <<forall x y. x^2 + y^2 = 1 ==> 2 * x * y < 1>>;;
*)
time REAL_QELIM_CONV `!x y. (x pow 2 + y pow 2 = &1) ==> &2 * x * y < &1`;;
DATE ------- HOL
4/29/2005 83.7
DATE ------- HOL
4/29/2005 83.7
*)
time real_qelim < < forall x y. x * y > 0 < = > x > 0 /\ y > 0 \/ x < 0 /\ y < 0 > > ; ;
time real_qelim <<forall x y. x * y > 0 <=> x > 0 /\ y > 0 \/ x < 0 /\ y < 0>>;;
*)
time REAL_QELIM_CONV `!x y. x * y > &0 <=> x > &0 /\ y > &0 \/ x < &0 /\ y < &0`;;
DATE ------- HOL
4/29/2005 27.4
DATE ------- HOL
4/29/2005 27.4
*)
time REAL_QELIM_CONV `?x y. x > y /\ x pow 2 < y pow 2`;;
DATE ------- HOL
4/29/2005 1.19
DATE ------- HOL
4/29/2005 1.19
*)
time real_qelim < < forall x y. x < y = = > exists < z /\ z < y > > ; ;
time real_qelim <<forall x y. x < y ==> exists z. x < z /\ z < y>>;;
*)
time REAL_QELIM_CONV `!x y. x < y ==> ?z. x < z /\ z < y`;;
DATE ------- HOL
4/29/2005 3.8
DATE ------- HOL
4/29/2005 3.8
*)
time real_qelim < < forall x. 0 < x < = > exists y. x * y^2 = 1 > > ; ;
time real_qelim <<forall x. 0 < x <=> exists y. x * y^2 = 1>>;;
*)
time REAL_QELIM_CONV `!x. &0 < x <=> ?y. x * y pow 2 = &1`;;
DATE ------- HOL
4/29/2005 3.76
DATE ------- HOL
4/29/2005 3.76
*)
time real_qelim < < forall x. 0 < = x < = > exists y. x * y^2 = 1 > > ; ;
time real_qelim <<forall x. 0 <= x <=> exists y. x * y^2 = 1>>;;
*)
time REAL_QELIM_CONV `!x. &0 <= x <=> ?y. x * y pow 2 = &1`;;
DATE ------- HOL
4/29/2005 4.38
DATE ------- HOL
4/29/2005 4.38
*)
time real_qelim < < forall x. 0 < = x < = > exists y. x = y^2 > > ; ;
time real_qelim <<forall x. 0 <= x <=> exists y. x = y^2>>;;
*)
time REAL_QELIM_CONV `!x. &0 <= x <=> ?y. x = y pow 2`;;
DATE ------- HOL
4/29/2005 4.38
DATE ------- HOL
4/29/2005 4.38
*)
time real_qelim < < forall x y. 0 < x /\ x < y = = > exists < z^2 /\ z^2 < y > > ; ;
time real_qelim <<forall x y. 0 < x /\ x < y ==> exists z. x < z^2 /\ z^2 < y>>;;
*)
time REAL_QELIM_CONV `!x y. &0 < x /\ x < y ==> ?z. x < z pow 2 /\ z pow 2 < y`;;
DATE ------- HOL
4/29/2005 93.1
DATE ------- HOL
4/29/2005 93.1
*)
time real_qelim < < forall x y. x < y = = > exists < z^2 /\ z^2 < y > > ; ;
time real_qelim <<forall x y. x < y ==> exists z. x < z^2 /\ z^2 < y>>;;
*)
time REAL_QELIM_CONV `!x y. x < y ==> ?z. x < z pow 2 /\ z pow 2 < y`;;
DATE ------- HOL
4/29/2005 93.22
DATE ------- HOL
4/29/2005 93.22
*)
time real_qelim < < forall x y. x^2 + y^2 = 0 = = > x = 0 /\ y = 0 > > ; ;
time real_qelim <<forall x y. x^2 + y^2 = 0 ==> x = 0 /\ y = 0>>;;
*)
time REAL_QELIM_CONV `!x y. (x pow 2 + y pow 2 = &0) ==> (x = &0) /\ (y = &0)`;;
DATE ------- HOL
4/29/2005 17.21
DATE ------- HOL
4/29/2005 17.21
*)
time real_qelim < < forall x y z. x^2 + y^2 + z^2 = 0 = = > x = 0 /\ y = 0 /\ z = 0 > > ; ;
time real_qelim <<forall x y z. x^2 + y^2 + z^2 = 0 ==> x = 0 /\ y = 0 /\ z = 0>>;;
*)
time REAL_QELIM_CONV `!x y z. (x pow 2 + y pow 2 + z pow 2 = &0) ==> (x = &0) /\ (y = &0) /\ (z = &0)`;;
time real_qelim < < forall w x y + x^2 + y^2 + z^2 = 0
= = > w = 0 /\ x = 0 /\ y = 0 /\ z = 0 > > ; ;
time real_qelim <<forall w x y z. w^2 + x^2 + y^2 + z^2 = 0
==> w = 0 /\ x = 0 /\ y = 0 /\ z = 0>>;;
*)
time REAL_QELIM_CONV `!w x y z. (w pow 2 + x pow 2 + y pow 2 + z pow 2 = &0)
==> (w = &0) /\ (x = &0) /\ (y = &0) /\ (z = &0)`;;
DATE ------- HOL
4/29/2005 596
DATE ------- HOL
4/29/2005 596
*)
time real_qelim < < forall 2 = = > forall x. ~(x^2 + a*x + 1 = 0 ) > > ; ;
time real_qelim <<forall a. a^2 = 2 ==> forall x. ~(x^2 + a*x + 1 = 0)>>;;
*)
time REAL_QELIM_CONV `!a. (a pow 2 = &2) ==> !x. ~(x pow 2 + a*x + &1 = &0)`;;
DATE ------- HOL
4/29/2005 8.7
DATE ------- HOL
4/29/2005 8.7
*)
time real_qelim < < forall 2 = = > forall x. ~(x^2 - a*x + 1 = 0 ) > > ; ;
time real_qelim <<forall a. a^2 = 2 ==> forall x. ~(x^2 - a*x + 1 = 0)>>;;
*)
time REAL_QELIM_CONV `!a. (a pow 2 = &2) ==> !x. ~(x pow 2 - a*x + &1 = &0)`;;
DATE ------- HOL
4/29/2005 8.82
DATE ------- HOL
4/29/2005 8.82
*)
time real_qelim < < forall x y. x^2 = 2 /\ y^2 = 3 = = > ( x * y)^2 = 6 > > ; ;
time real_qelim <<forall x y. x^2 = 2 /\ y^2 = 3 ==> (x * y)^2 = 6>>;;
*)
time REAL_QELIM_CONV `!x y. (x pow 2 = &2) /\ (y pow 2 = &3) ==> ((x * y) pow 2 = &6)`;;
DATE ------- HOL
4/29/2005 48.59
DATE ------- HOL
4/29/2005 48.59
*)
time real_qelim < < forall x. exists y. x^2 = y^3 > > ; ;
time real_qelim <<forall x. exists y. x^2 = y^3>>;;
*)
time REAL_QELIM_CONV `!x. ?y. x pow 2 = y pow 3`;;
DATE ------- HOL
4/29/2005 6.93
DATE ------- HOL
4/29/2005 6.93
*)
time real_qelim < < forall x. exists y. x^3 = y^2 > > ; ;
time real_qelim <<forall x. exists y. x^3 = y^2>>;;
*)
time REAL_QELIM_CONV `!x. ?y. x pow 3 = y pow 2`;;
DATE ------- HOL
4/29/2005 5.76
DATE ------- HOL
4/29/2005 5.76
*)
time REAL_QELIM_CONV
`!a b c.
(a * x pow 2 + b * x + c = &0) /\
(a * y pow 2 + b * y + c = &0) /\
~(x = y)
==> (a * (x + y) + b = &0)`;;
DATE ------- HOL
4/29/2005 76.5
DATE ------- HOL
4/29/2005 76.5
*)
time real_qelim
< < forall .
( y_1 = 2 * y_3 ) /\
( y_2 = 2 * y_4 ) /\
( y_1 * y_3 = y_2 * y_4 )
= = > ( y_1 ^ 2 = y_2 ^ 2 ) > > ; ;
time real_qelim
<<forall y_1 y_2 y_3 y_4.
(y_1 = 2 * y_3) /\
(y_2 = 2 * y_4) /\
(y_1 * y_3 = y_2 * y_4)
==> (y_1^2 = y_2^2)>>;;
*)
time REAL_QELIM_CONV
`!y_1 y_2 y_3 y_4.
(y_1 = &2 * y_3) /\
(y_2 = &2 * y_4) /\
(y_1 * y_3 = y_2 * y_4)
==> (y_1 pow 2 = y_2 pow 2)`;;
time real_qelim < < forall x. x^2 < 1 < = > x^4 < 1 > > ; ;
time real_qelim <<forall x. x^2 < 1 <=> x^4 < 1>>;;
*)
DATE ------- HOL
4/29/2005 1327
DATE ------- HOL
4/29/2005 1327
*)
time real_qelim < < exists x. x^3 - x^2 + x - 1 = 0 > > ; ;
time real_qelim <<exists x. x^3 - x^2 + x - 1 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 3 - x pow 2 + x - &1 = &0`;;
DATE ------- HOL
4/29/2005 3.8
DATE ------- HOL
4/29/2005 3.8
*)
time real_qelim
< < exists x y. x^3 - x^2 + x - 1 = 0 /\ y^3 - y^2 + y - 1 = 0 /\ ~(x = y ) > > ; ;
time real_qelim
<<exists x y. x^3 - x^2 + x - 1 = 0 /\ y^3 - y^2 + y - 1 = 0 /\ ~(x = y)>>;;
*)
time REAL_QELIM_CONV
`?x y. (x pow 3 - x pow 2 + x - &1 = &0) /\ (y pow 3 - y pow 2 + y - &1 = &0) /\ ~(x = y)`;;
DATE ------- HOL
4/29/2005 670
DATE ------- HOL
4/29/2005 670
*)
time real_qelim < < exists x. x^4 + x^2 - 2 = 0 > > ; ;
time real_qelim <<exists x. x^4 + x^2 - 2 = 0>>;;
*)
time REAL_QELIM_CONV `?x. x pow 4 + x pow 2 - &2 = &0`;;
DATE ------- HOL
4/29/2005 4.9
DATE ------- HOL
4/29/2005 4.9
*)
time real_qelim
< < exists x y. x^4 + x^2 - 2 = 0 /\ y^4 + y^2 - 2 = 0 /\ ~(x = y ) > > ; ;
time real_qelim
<<exists x y. x^4 + x^2 - 2 = 0 /\ y^4 + y^2 - 2 = 0 /\ ~(x = y)>>;;
*)
time REAL_QELIM_CONV
`?x y. x pow 4 + x pow 2 - &2 = &0 /\ y pow 4 + y pow 2 - &2 = &0 /\ ~(x = y)`;;
time real_qelim
< < exists x y. x^3 + x^2 - x - 1 = 0 /\ y^3 + y^2 - y - 1 = 0 /\ ~(x = y ) > > ; ;
time real_qelim
<<exists x y. x^3 + x^2 - x - 1 = 0 /\ y^3 + y^2 - y - 1 = 0 /\ ~(x = y)>>;;
*)
time REAL_QELIM_CONV
`?x y. (x pow 3 + x pow 2 - x - &1 = &0) /\ (y pow 3 + y pow 2 - y - &1 = &0) /\ ~(x = y)`;;
time real_qelim < < exists x y z. x^3 + x^2 - x - 1 = 0 /\
y^3 + y^2 - y - 1 = 0 /\
z^3 + z^2 - z - 1 = 0 /\ ~(x = y ) /\ ~(x = z ) > > ; ;
time real_qelim <<exists x y z. x^3 + x^2 - x - 1 = 0 /\
y^3 + y^2 - y - 1 = 0 /\
z^3 + z^2 - z - 1 = 0 /\ ~(x = y) /\ ~(x = z)>>;;
*)
time REAL_QELIM_CONV `?x y z. (x pow 3 + x pow 2 - x - &1 = &0) /\
(y pow 3 + y pow 2 - y - &1 = &0) /\
(z pow 3 + z pow 2 - z - &1 = &0) /\ ~(x = y) /\ ~(x = z)`;;
time real_qelim
< < forall x y. exists s = 1 /\ s * x + c * y = 0 > > ; ;
time real_qelim
<<forall x y. exists s c. s^2 + c^2 = 1 /\ s * x + c * y = 0>>;;
*)
time REAL_QELIM_CONV
`!x y. ?s c. (s pow 2 + c pow 2 = &1) /\ s * x + c * y = &0`;;
time real_qelim < < forall x y. ( x + y)^2 < = 2 * ( x^2 + y^2 ) > > ; ;
time real_qelim <<forall x y. (x + y)^2 <= 2 * (x^2 + y^2)>>;;
*)
time REAL_QELIM_CONV `!x y. (x + y) pow 2 <= &2 * (x pow 2 + y pow 2)`;;
time REAL_QELIM_CONV `!x y. (x + y) pow 2 <= c * (x pow 2 + y pow 2)`;;
time real_qelim
< < forall c. ( forall x y. ( x + y)^2 < = c * ( x^2 + y^2 ) ) < = > 2 < = c > > ; ;
time real_qelim
<<forall c. (forall x y. (x + y)^2 <= c * (x^2 + y^2)) <=> 2 <= c>>;;
*)
time REAL_QELIM_CONV
`!c. (!x y. (x + y) pow 2 <= c * (x pow 2 + y pow 2)) <=> &2 <= c`;;
time real_qelim < < forall a b. a * b * c < = > ; ;
time real_qelim <<forall a b. a * b * c <= a^2 + b^2>>;;
*)
time REAL_QELIM_CONV `!a b. a * b * c <= a pow 2 + b pow 2`;;
time real_qelim
< < forall c. ( forall a b. a * b * c < = b^2 ) < = > c^2 < = 4 > > ; ;
time real_qelim
<<forall c. (forall a b. a * b * c <= a^2 + b^2) <=> c^2 <= 4>>;;
*)
time REAL_QELIM_CONV
`!c. (!a b. a * b * c <= a pow 2 + b pow 2) <=> c pow 2 <= &4`;;
Tedious lemmas I once proved manually in HOL .
time REAL_QELIM_CONV
`!a b c. &0 < a /\ &0 < b /\ &0 < c
==> &0 < a * b /\ &0 < a * c /\ &0 < b * c`;;
time REAL_QELIM_CONV
`!a b c. a * b > &0 ==> (c * a < &0 <=> c * b < &0)`;;
time REAL_QELIM_CONV
`!a b c. a * b > &0 ==> (a * c < &0 <=> b * c < &0)`;;
time REAL_QELIM_CONV
`!a b. a < &0 ==> (a * b > &0 <=> b < &0)`;;
time REAL_QELIM_CONV
`!a b c. a * b < &0 /\ ~(c = &0) ==> (c * a < &0 <=> ~(c * b < &0))`;;
time real_qelim
< < forall a b. a * b < 0 < = > a > 0 /\ b < 0 \/ a < 0 /\ b > 0 > > ; ;
time real_qelim
<<forall a b. a * b < 0 <=> a > 0 /\ b < 0 \/ a < 0 /\ b > 0>>;;
*)
time REAL_QELIM_CONV
`!a b. a * b < &0 <=> a > &0 /\ b < &0 \/ a < &0 /\ b > &0`;;
time real_qelim
< < forall a b. a * b < = 0 < = > a > = 0 /\ b < = 0 \/ a < = 0 /\ b > = 0 > > ; ;
time real_qelim
<<forall a b. a * b <= 0 <=> a >= 0 /\ b <= 0 \/ a <= 0 /\ b >= 0>>;;
*)
time REAL_QELIM_CONV
`!a b. a * b <= &0 <=> a >= &0 /\ b <= &0 \/ a <= &0 /\ b >= &0`;;
Vaguely connected with reductions for arithmetic .
time REAL_QELIM_CONV
`!a b. ~(a <= b) <=> !d. d <= b ==> d < a`;;
time REAL_QELIM_CONV
`!a b. ~(a <= b) <=> !d. d <= b ==> ~(d = a)`;;
time REAL_QELIM_CONV
`!a b. ~(a < b) <=> !d. d < b ==> d < a`;;
time real_qelim
< < forall x y. x^2 + y^2 = 1 = = > ( x + y)^2 < = 2 > > ; ;
time real_qelim
<<forall x y. x^2 + y^2 = 1 ==> (x + y)^2 <= 2>>;;
*)
time REAL_QELIM_CONV
`!x y. (x pow 2 + y pow 2 = &1) ==> (x + y) pow 2 <= &2`;;
Some variants / intermediate steps in Cauchy - Schwartz inequality .
time real_qelim
< < forall x y. 2 * x * y < = x^2 + y^2 > > ; ;
time real_qelim
<<forall x y. 2 * x * y <= x^2 + y^2>>;;
*)
time REAL_QELIM_CONV
`!x y. &2 * x * y <= x pow 2 + y pow 2`;;
time real_qelim
< < forall a b c d. 2 * a * b * c * d < = a^2 * b^2 + c^2 * d^2 > > ; ;
time real_qelim
<<forall a b c d. 2 * a * b * c * d <= a^2 * b^2 + c^2 * d^2>>;;
*)
time REAL_QELIM_CONV
`!a b c d. &2 * a * b * c * d <= a pow 2 * b pow 2 + c pow 2 * d pow 2`;;
time real_qelim
< < forall x1 x2 y1 y2 .
( x1 * y1 + x2 * y2)^2 < = ( x1 ^ 2 + x2 ^ 2 ) * ( y1 ^ 2 + y2 ^ 2 ) > > ; ;
time real_qelim
<<forall x1 x2 y1 y2.
(x1 * y1 + x2 * y2)^2 <= (x1^2 + x2^2) * (y1^2 + y2^2)>>;;
*)
time REAL_QELIM_CONV
`!x1 x2 y1 y2.
(x1 * y1 + x2 * y2) pow 2 <= (x1 pow 2 + x2 pow 2) * (y1 pow 2 + y2 pow 2)`;;
time real_qelim
< < exists w x y z. ( a * w + b * y = 1 ) /\
( a * x + b * z = 0 ) /\
( c * w + d * y = 0 ) /\
( c * x + d * z = 1 ) > > ; ;
time real_qelim
<<exists w x y z. (a * w + b * y = 1) /\
(a * x + b * z = 0) /\
(c * w + d * y = 0) /\
(c * x + d * z = 1)>>;;
*)
time REAL_QELIM_CONV
`?w x y z. (a * w + b * y = &1) /\
(a * x + b * z = &0) /\
(c * w + d * y = &0) /\
(c * x + d * z = &1)`;;
time real_qelim
< < forall a b c d.
( exists w x y z. ( a * w + b * y = 1 ) /\
( a * x + b * z = 0 ) /\
( c * w + d * y = 0 ) /\
( c * x + d * z = 1 ) )
< = > ~(a * d = b * c ) > > ; ;
time real_qelim
<<forall a b c d.
(exists w x y z. (a * w + b * y = 1) /\
(a * x + b * z = 0) /\
(c * w + d * y = 0) /\
(c * x + d * z = 1))
<=> ~(a * d = b * c)>>;;
*)
time REAL_QELIM_CONV
`!a b c d.
(?w x y z. (a * w + b * y = &1) /\
(a * x + b * z = &0) /\
(c * w + d * y = &0) /\
(c * x + d * z = &1))
<=> ~(a * d = b * c)`;;
From applying .
let th = prove
(`&0 <= c' /\ &0 <= c /\ &0 < h * c'
==> (?u. &0 < u /\
(!v. &0 < v /\ v <= u
==> v * (v * (h * h * c' + c) - h * c') - (v * h * c' - c') <
c'))`,
W(fun (asl,w) -> MAP_EVERY (fun v -> SPEC_TAC(v,v)) (frees w)) THEN
CONV_TAC REAL_QELIM_CONV);;
Two notions of parallelism .
time REAL_QELIM_CONV
`!x1 x2 y1 y2. (?c. (x2 = c * x1) /\ (y2 = c * y1)) <=>
(x1 = &0 /\ y1 = &0 ==> x2 = &0 /\ y2 = &0) /\
x1 * y2 = x2 * y1`;;
From ( takes about 300 seconds ) .
time REAL_QELIM_CONV
`!x. &0 <= x /\ x <= &1
==> &0 < &1 - x + x pow 2 / &2 - x pow 3 / &6 /\
&1 <= (&1 + x + x pow 2) *
(&1 - x + x pow 2 / &2 - x pow 3 / &6)`;;
Takes about 450 seconds .
* * Would actually like to get rid of abs internally and state it like this :
time REAL_QELIM_CONV
` ! x y e. & 0 < e = = > ? d. & 0 < d /\ ) * ( y + d ) - x * y ) < e ` ; ;
* * *
time REAL_QELIM_CONV
`!x y e. &0 < e ==> ?d. &0 < d /\ abs((x + d) * (y + d) - x * y) < e`;;
****)
time REAL_QELIM_CONV
`!x y e. &0 < e ==> ?d. &0 < d /\ (x + d) * (y + d) - x * y < e /\
x * y - (x + d) * (y + d) < e`;;
|
a2a6e3426bfb1c2e9e046ec5e76722a50d597ddd88a3ccfc251088700f1215a6 | ccqpein/Github-API-CL | api-doc-test.lisp | (defpackage #:api-doc-test
(:use #:CL #:lisp-unit)
(:import-from #:github-api-doc
#:api-doc
#:make-call-parameters
#:make-call-url))
(in-package #:api-doc-test)
(define-test coerce-parameter-type-test
(assert-equal "" (github-api-doc::coerce-parameter-type "" "string"))
(assert-equal "aa" (github-api-doc::coerce-parameter-type "aa" "string"))
;; from (read-line) or keywords
(assert-equal "" (github-api-doc::coerce-parameter-type "" "boolean"))
(assert-equal "false" (github-api-doc::coerce-parameter-type "false" "boolean"))
(assert-equal "true" (github-api-doc::coerce-parameter-type "true" "boolean"))
;; from keyword
(assert-equal 1 (github-api-doc::coerce-parameter-type 1 "integer"))
;; from (read-line)
(assert-equal 12 (github-api-doc::coerce-parameter-type "12" "integer"))
(assert-equal "" (github-api-doc::coerce-parameter-type "" "integer")) ;; empty (read-line)
)
(define-test make-call-parameters-test
(let ((api-doc (make-instance 'api-doc
:api "POST /user/repos"
:parameters '(("name" "string")
("private" "boolean")
("team_id" "integer")))))
;; fake input from repl
(assert-equal "?name=aa&private=true&team_id=1"
(with-input-from-string (*standard-input* "aa
true
1")
(make-call-parameters api-doc)))
;; input by keywords, ignore wrong parameters
(assert-equal "?private=true"
(make-call-parameters api-doc :username "aa" :private "true" :integer 1))
;; input by keywords
(assert-equal "?name=aa&private=true&team_id=1"
(make-call-parameters api-doc :name "aa" :private "true" :team_id 1))
))
(define-test make-call-url-test
(let ((api-doc (make-instance 'api-doc
:api "GET /user/:repo/:aaa/:id")))
(assert-equal ""
(with-input-from-string (*standard-input* "aa
bb
3")
(make-call-url api-doc)))
(assert-equal ""
(make-call-url api-doc :repo "aa" :aaa "bb" :id 3))))
(let ((*print-errors* t)
(*print-failures* t))
(run-tests :all :api-doc-test))
| null | https://raw.githubusercontent.com/ccqpein/Github-API-CL/dfee2e9e0ca81af0d64365d1724da8205017c637/api-doc-test.lisp | lisp | from (read-line) or keywords
from keyword
from (read-line)
empty (read-line)
fake input from repl
input by keywords, ignore wrong parameters
input by keywords | (defpackage #:api-doc-test
(:use #:CL #:lisp-unit)
(:import-from #:github-api-doc
#:api-doc
#:make-call-parameters
#:make-call-url))
(in-package #:api-doc-test)
(define-test coerce-parameter-type-test
(assert-equal "" (github-api-doc::coerce-parameter-type "" "string"))
(assert-equal "aa" (github-api-doc::coerce-parameter-type "aa" "string"))
(assert-equal "" (github-api-doc::coerce-parameter-type "" "boolean"))
(assert-equal "false" (github-api-doc::coerce-parameter-type "false" "boolean"))
(assert-equal "true" (github-api-doc::coerce-parameter-type "true" "boolean"))
(assert-equal 1 (github-api-doc::coerce-parameter-type 1 "integer"))
(assert-equal 12 (github-api-doc::coerce-parameter-type "12" "integer"))
)
(define-test make-call-parameters-test
(let ((api-doc (make-instance 'api-doc
:api "POST /user/repos"
:parameters '(("name" "string")
("private" "boolean")
("team_id" "integer")))))
(assert-equal "?name=aa&private=true&team_id=1"
(with-input-from-string (*standard-input* "aa
true
1")
(make-call-parameters api-doc)))
(assert-equal "?private=true"
(make-call-parameters api-doc :username "aa" :private "true" :integer 1))
(assert-equal "?name=aa&private=true&team_id=1"
(make-call-parameters api-doc :name "aa" :private "true" :team_id 1))
))
(define-test make-call-url-test
(let ((api-doc (make-instance 'api-doc
:api "GET /user/:repo/:aaa/:id")))
(assert-equal ""
(with-input-from-string (*standard-input* "aa
bb
3")
(make-call-url api-doc)))
(assert-equal ""
(make-call-url api-doc :repo "aa" :aaa "bb" :id 3))))
(let ((*print-errors* t)
(*print-failures* t))
(run-tests :all :api-doc-test))
|
6506eee3c8176dde7a5f6e2f93f7bde60d1921c9c96d4f3a6e85b1ba862af284 | cyverse-archive/DiscoveryEnvironmentBackend | es_if.clj | (ns infosquito.es-if)
(defprotocol Indexes
(delete [_ index type id]
"Maps to clojurewerkz.elastisch.rest.document/delete")
(exists? [_ index]
"Maps to clojurewerkz.elastisch.rest.index/exists?")
(put [_ index type id doc-map]
"Maps to clojurewerkz.elastisch.rest.document/put")
(put-bulk [_ index type docs]
"Bulk indexes a bunch of documents")
(search-all-types [_ index params]
"Maps to clojurewerkz.elastisch.rest.document/search-all-types"))
| null | https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/Infosquito/src/infosquito/es_if.clj | clojure | (ns infosquito.es-if)
(defprotocol Indexes
(delete [_ index type id]
"Maps to clojurewerkz.elastisch.rest.document/delete")
(exists? [_ index]
"Maps to clojurewerkz.elastisch.rest.index/exists?")
(put [_ index type id doc-map]
"Maps to clojurewerkz.elastisch.rest.document/put")
(put-bulk [_ index type docs]
"Bulk indexes a bunch of documents")
(search-all-types [_ index params]
"Maps to clojurewerkz.elastisch.rest.document/search-all-types"))
|
|
86c8dbe4d59a97546155170dffb8d2ce9b5655f8388ae3feee8b6010aa93a6c6 | hpyhacking/openpoker | op_exch.erl | -module(op_exch).
-behaviour(gen_server).
-export([behaviour_info/1]).
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2, code_change/3]).
-export([start_link/3, stop/1, stop/2, cast/2, call/2]).
-include("openpoker.hrl").
behaviour_info(callbacks) -> [
{id, 0},
{init, 2},
{stop, 1},
{dispatch, 2},
{call, 2}
].
%%%
%%% client
%%%
start_link(Module, Conf, Mods) ->
Id = Module:id(),
Pid = gen_server:start_link({global, {Module, Id}}, op_exch, [Module, Id, Conf, Mods], []),
start_logger(Pid, Id).
start_logger(R = {ok, Pid}, Id) ->
LogGames = op_common:get_env(log_games, []),
case lists:member(Id, LogGames) of
true ->
op_exch_event_logger:add_handler(Pid);
false ->
ok
end,
R.
stop(Pid) when is_pid(Pid) ->
gen_server:cast(Pid, stop).
stop(Module, Id) when is_number(Id) ->
gen_server:cast({global, {Module, Id}}, stop).
call(Exch, Event) ->
gen_server:call(Exch, Event).
cast(Exch, Event) ->
gen_server:cast(Exch, Event).
%%%
%%% callback
%%%
init([Module, Id, Conf, Mods]) ->
process_flag(trap_exit, true),
Ctx = Module:init(Id, Conf),
Data = #exch{
id = Id,
module = Module,
mods = Mods,
stack = Mods,
ctx = Ctx,
conf = Conf
},
case init(?UNDEF, Data) of
{stop, _, NewData} ->
{stop, NewData};
{noreply, NewData} ->
{ok, NewData}
end.
handle_cast(stop, Data) ->
{stop, normal, Data};
handle_cast(Msg, Data = #exch{stack = Stack, ctx = Ctx, state = State}) ->
{Mod, _} = hd(Stack),
op_exch_event:cast([{mod, Mod}, {state, State}, {msg, Msg}]),
%io:format("==========================================~n"),
%io:format("msg: ~p~n", [Msg]),
case advance(Mod:State(Msg, Ctx), Msg, Data) of
R = {noreply, #exch{stack = NewStack, state = NewState}} ->
{NewMod, _} = hd(NewStack),
op_exch_event:cast([{next_mod, NewMod}, {next_state, NewState}, {msg, Msg}]),
R;
R = {stop, normal, _} ->
R
end.
handle_call(Msg, _From, Data = #exch{module = Module, ctx = Context}) ->
{ok, Result, NewContext} = Module:call(Msg, Context),
{reply, Result, Data#exch{ctx = NewContext}}.
terminate(normal, #exch{module = Module, ctx = Ctx}) ->
Module:stop(Ctx);
terminate(_, #exch{module = Module, ctx = Ctx}) ->
Module:stop(Ctx).
handle_info(Msg, Data) ->
handle_cast(Msg, Data).
code_change(_OldVsn, Data, _Extra) ->
{ok, Data}.
%%%
%%% private
%%%
init(Msg, Data = #exch{ stack = [{Mod, Params}|_], ctx = Ctx }) ->
op_exch_event:init(Mod, Msg),
advance(Mod:start(Params, Ctx), Msg, Data#exch{ state = ?UNDEF }).
%% continue current state
advance({continue, Ctx}, _Msg, Data = #exch{}) ->
{noreply, Data#exch{ ctx = Ctx }};
%% next new state
advance({next, State, Ctx}, _Msg, Data) ->
{noreply, Data#exch{ state = State, ctx = Ctx }};
%% skip mod process, post to Module:dispatch.
advance({skip, Ctx}, Msg, Data = #exch{stack = Stack, module = Module}) ->
{Mod, _} = hd(Stack),
op_exch_event:advance([{mod, Mod}, {state, Data#exch.state}, {skip, Msg}]),
case Mod:dispatch(Msg, Ctx) of
ok ->
{noreply, Data#exch{ ctx = Module:dispatch(Msg, Ctx) }};
skip ->
{noreply, Data}
end;
%%
advance({stop, Ctx}, _Msg, Data = #exch{ stack = [_] }) ->
{stop, normal, Data#exch{ ctx = Ctx, stack = [] }};
%% stop current mod, init next mod
advance({stop, Ctx}, Msg, Data = #exch{ stack = [_|T] }) ->
init(Msg, Data#exch{ ctx = Ctx, stack = T });
%% repeat current mod, re init mod
advance({repeat, Ctx}, Msg, Data = #exch{}) ->
init(Msg, Data#exch{ ctx = Ctx });
goto first mod
advance({goto, top, Ctx}, Msg, Data = #exch{mods = Mods}) ->
init(Msg, Data#exch{ ctx = Ctx, stack = Mods});
%% goto specil mod
advance({goto, Mod, Ctx}, Msg, Data = #exch{stack = Stack}) ->
init(Msg, Data#exch{ ctx = Ctx, stack = trim_stack(Mod, Stack) }).
trim_stack(_Mod, L = [{_LastMod, _}]) -> L;
trim_stack(Mod, L = [{H, _}|_]) when Mod == H -> L;
trim_stack(Mod, [_|T]) -> trim_stack(Mod, T).
| null | https://raw.githubusercontent.com/hpyhacking/openpoker/643193c94f34096cdcfcd610bdb1f18e7bf1e45e/src/op_exch.erl | erlang |
client
callback
io:format("==========================================~n"),
io:format("msg: ~p~n", [Msg]),
private
continue current state
next new state
skip mod process, post to Module:dispatch.
stop current mod, init next mod
repeat current mod, re init mod
goto specil mod | -module(op_exch).
-behaviour(gen_server).
-export([behaviour_info/1]).
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2, code_change/3]).
-export([start_link/3, stop/1, stop/2, cast/2, call/2]).
-include("openpoker.hrl").
behaviour_info(callbacks) -> [
{id, 0},
{init, 2},
{stop, 1},
{dispatch, 2},
{call, 2}
].
start_link(Module, Conf, Mods) ->
Id = Module:id(),
Pid = gen_server:start_link({global, {Module, Id}}, op_exch, [Module, Id, Conf, Mods], []),
start_logger(Pid, Id).
start_logger(R = {ok, Pid}, Id) ->
LogGames = op_common:get_env(log_games, []),
case lists:member(Id, LogGames) of
true ->
op_exch_event_logger:add_handler(Pid);
false ->
ok
end,
R.
stop(Pid) when is_pid(Pid) ->
gen_server:cast(Pid, stop).
stop(Module, Id) when is_number(Id) ->
gen_server:cast({global, {Module, Id}}, stop).
call(Exch, Event) ->
gen_server:call(Exch, Event).
cast(Exch, Event) ->
gen_server:cast(Exch, Event).
init([Module, Id, Conf, Mods]) ->
process_flag(trap_exit, true),
Ctx = Module:init(Id, Conf),
Data = #exch{
id = Id,
module = Module,
mods = Mods,
stack = Mods,
ctx = Ctx,
conf = Conf
},
case init(?UNDEF, Data) of
{stop, _, NewData} ->
{stop, NewData};
{noreply, NewData} ->
{ok, NewData}
end.
handle_cast(stop, Data) ->
{stop, normal, Data};
handle_cast(Msg, Data = #exch{stack = Stack, ctx = Ctx, state = State}) ->
{Mod, _} = hd(Stack),
op_exch_event:cast([{mod, Mod}, {state, State}, {msg, Msg}]),
case advance(Mod:State(Msg, Ctx), Msg, Data) of
R = {noreply, #exch{stack = NewStack, state = NewState}} ->
{NewMod, _} = hd(NewStack),
op_exch_event:cast([{next_mod, NewMod}, {next_state, NewState}, {msg, Msg}]),
R;
R = {stop, normal, _} ->
R
end.
handle_call(Msg, _From, Data = #exch{module = Module, ctx = Context}) ->
{ok, Result, NewContext} = Module:call(Msg, Context),
{reply, Result, Data#exch{ctx = NewContext}}.
terminate(normal, #exch{module = Module, ctx = Ctx}) ->
Module:stop(Ctx);
terminate(_, #exch{module = Module, ctx = Ctx}) ->
Module:stop(Ctx).
handle_info(Msg, Data) ->
handle_cast(Msg, Data).
code_change(_OldVsn, Data, _Extra) ->
{ok, Data}.
init(Msg, Data = #exch{ stack = [{Mod, Params}|_], ctx = Ctx }) ->
op_exch_event:init(Mod, Msg),
advance(Mod:start(Params, Ctx), Msg, Data#exch{ state = ?UNDEF }).
advance({continue, Ctx}, _Msg, Data = #exch{}) ->
{noreply, Data#exch{ ctx = Ctx }};
advance({next, State, Ctx}, _Msg, Data) ->
{noreply, Data#exch{ state = State, ctx = Ctx }};
advance({skip, Ctx}, Msg, Data = #exch{stack = Stack, module = Module}) ->
{Mod, _} = hd(Stack),
op_exch_event:advance([{mod, Mod}, {state, Data#exch.state}, {skip, Msg}]),
case Mod:dispatch(Msg, Ctx) of
ok ->
{noreply, Data#exch{ ctx = Module:dispatch(Msg, Ctx) }};
skip ->
{noreply, Data}
end;
advance({stop, Ctx}, _Msg, Data = #exch{ stack = [_] }) ->
{stop, normal, Data#exch{ ctx = Ctx, stack = [] }};
advance({stop, Ctx}, Msg, Data = #exch{ stack = [_|T] }) ->
init(Msg, Data#exch{ ctx = Ctx, stack = T });
advance({repeat, Ctx}, Msg, Data = #exch{}) ->
init(Msg, Data#exch{ ctx = Ctx });
goto first mod
advance({goto, top, Ctx}, Msg, Data = #exch{mods = Mods}) ->
init(Msg, Data#exch{ ctx = Ctx, stack = Mods});
advance({goto, Mod, Ctx}, Msg, Data = #exch{stack = Stack}) ->
init(Msg, Data#exch{ ctx = Ctx, stack = trim_stack(Mod, Stack) }).
trim_stack(_Mod, L = [{_LastMod, _}]) -> L;
trim_stack(Mod, L = [{H, _}|_]) when Mod == H -> L;
trim_stack(Mod, [_|T]) -> trim_stack(Mod, T).
|
9130bab95e98099ba04877f08014929e119beaae9414bae4f55244a8f754df5f | ocaml-community/obus | nm_device.mli |
* nm_device.mli
* -------------
* Copyright : ( c ) 2010 , < >
* 2010 , < >
* Licence : BSD3
*
* This file is a part of obus , an ocaml implementation of D - Bus .
* nm_device.mli
* -------------
* Copyright : (c) 2010, Pierre Chambart <>
* 2010, Jeremie Dimino <>
* Licence : BSD3
*
* This file is a part of obus, an ocaml implementation of D-Bus.
*)
(** NetworkManager devices *)
include OBus_proxy.Private
* { 6 Common interface }
(** {8 Types} *)
type state =
[ `Unknown
(** The device is in an unknown state. *)
| `Unmanaged
(** The device is not managed by NetworkManager. *)
| `Unavailable
(** The device cannot be used (carrier off, rfkill, etc) *)
| `Disconnected
(** The device is not connected. *)
| `Prepare
(** The device is preparing to connect. *)
| `Config
(** The device is being configured. *)
| `Need_auth
(** The device is awaiting secrets necessary to continue connection. *)
| `Ip_config
(** The IP settings of the device are being requested and configured. *)
| `Activated
(** The device is active. *)
| `Failed
(** The device is in a failure state following an attempt to activate it. *) ]
type state_reason =
[ `Unknown
(** The reason for the device state change is unknown. *)
| `None
(** The state change is normal. *)
| `Now_managed
(** The device is now managed. *)
| `Now_unmanaged
(** The device is no longer managed. *)
| `Config_failed
(** The device could not be readied for configuration. *)
| `Config_unavailable
(** IP configuration could not be reserved (no available address, timeout, etc). *)
| `Config_expired
(** The IP configuration is no longer valid. *)
| `No_secrets
(** Secrets were required, but not provided. *)
| `Supplicant_disconnect
* The 802.1X supplicant disconnected from the access point or authentication server .
| `Supplicant_config_failed
* Configuration of the 802.1X supplicant failed .
| `Supplicant_failed
* The 802.1X supplicant quit or failed unexpectedly .
| `Supplicant_timeout
* The 802.1X supplicant took too long to authenticate .
| `Ppp_start_failed
* The PPP service failed to start within the allowed time .
| `Ppp_disconnect
* The PPP service disconnected unexpectedly .
| `Ppp_failed
* The PPP service quit or failed unexpectedly .
| `Dhcp_start_failed
(** The DHCP service failed to start within the allowed time. *)
| `Dhcp_error
(** The DHCP service reported an unexpected error. *)
| `Dhcp_failed
* The DHCP service quit or failed unexpectedly .
| `Shared_start_failed
(** The shared connection service failed to start. *)
| `Shared_failed
(** The shared connection service quit or failed unexpectedly. *)
| `Autoip_start_failed
* The AutoIP service failed to start .
| `Autoip_error
* The AutoIP service reported an unexpected error .
| `Autoip_failed
* The AutoIP service quit or failed unexpectedly .
| `Modem_busy
(** Dialing failed because the line was busy. *)
| `Modem_no_dial_tone
(** Dialing failed because there was no dial tone. *)
| `Modem_no_carrier
(** Dialing failed because there was carrier. *)
| `Modem_dial_timeout
(** Dialing timed out. *)
| `Modem_dial_failed
(** Dialing failed. *)
| `Modem_init_failed
(** Modem initialization failed. *)
| `Gsm_apn_failed
* Failed to select the specified GSM APN .
| `Gsm_registration_not_searching
(** Not searching for networks. *)
| `Gsm_registration_denied
(** Network registration was denied. *)
| `Gsm_registration_timeout
(** Network registration timed out. *)
| `Gsm_registration_failed
(** Failed to register with the requested GSM network. *)
| `Gsm_pin_check_failed
(** PIN check failed. *)
| `Firmware_missing
(** Necessary firmware for the device may be missing. *)
| `Removed
(** The device was removed. *)
| `Sleeping
(** NetworkManager went to sleep. *)
| `Connection_removed
(** The device's active connection was removed or disappeared. *)
| `User_requested
(** A user or client requested the disconnection. *)
| `Carrier
(** The device's carrier/link changed. *)
| `Connection_assumed
(** The device's existing connection was assumed. *)
| `Supplicant_available
* The 802.1x supplicant is now available .
type typ =
[ `Unknown
(** The device type is unknown. *)
| `Ethernet
(** The device is wired Ethernet device. *)
| `Wifi
* The device is an 802.11 WiFi device .
| `Gsm
* The device is a GSM - based cellular WAN device .
| `Cdma
* The device is a CDMA / IS-95 - based cellular WAN device .
type capability =
[ `Nm_supported
(** The device is supported by NetworkManager. *)
| `Carrier_detect
(** The device supports carrier detection. *) ]
(** {8 Methods} *)
val disconnect : t -> unit Lwt.t
(** {8 Signals} *)
val state_changed : t -> (state * state * state_reason) OBus_signal.t
* { 8 Properties }
val udi : t -> string OBus_property.r
val interface : t -> string OBus_property.r
val driver : t -> string OBus_property.r
val capabilities : t -> capability list OBus_property.r
val ip4_address : t -> int32 OBus_property.r
val state : t -> state OBus_property.r
val ip4_config : t -> Nm_ip4_config.t OBus_property.r
val dhcp4_config : t -> Nm_dhcp4_config.t OBus_property.r
val ip6_config : t -> Nm_ip6_config.t OBus_property.r
val managed : t -> bool OBus_property.r
val device_type : t -> typ OBus_property.r
val properties : t -> OBus_property.group
* { 6 Specific device interfaces }
module Bluetooth : sig
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
val hw_address : t -> string OBus_property.r
val name : t -> string OBus_property.r
val bt_capabilities : t -> int OBus_property.r
val properties : t -> OBus_property.group
end
module Cdma : sig
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
end
module Gsm : sig
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
end
module Olpc_mesh : sig
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
val hw_address : OBus_proxy.t -> (string, [ `readable ]) OBus_property.t
val companion : OBus_proxy.t -> (OBus_proxy.t, [ `readable ]) OBus_property.t
val active_channel : OBus_proxy.t -> (int, [ `readable ]) OBus_property.t
val properties : t -> OBus_property.group
end
module Serial : sig
val ppp_stats : t -> (int * int) OBus_signal.t
end
module Wired : sig
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
val hw_address : t -> string OBus_property.r
val speed : t -> int OBus_property.r
val carrier : t -> bool OBus_property.r
val properties : t -> OBus_property.group
end
module Wireless : sig
type wireless_capability =
[ `Cipher_wep40
* The device supports the 40 - bit WEP cipher .
| `Cipher_wep104
* The device supports the 104 - bit WEP cipher .
| `Cipher_tkip
(** The device supports the TKIP cipher. *)
| `Cipher_ccmp
* The device supports the CCMP cipher .
| `Wpa
(** The device supports the WPA encryption/authentication protocol. *)
| `Rsn
* The device supports the RSN encryption / authentication protocol .
type wifi_mode =
[ `Unknown
(** Mode is unknown. *)
| `Adhoc
(** Uncoordinated network without central infrastructure. *)
| `Infra
* Coordinated network with one or more central controllers .
val get_access_points : t -> Nm_access_point.t list Lwt.t
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
val access_point_added : t -> Nm_access_point.t OBus_signal.t
val access_point_removed : t -> Nm_access_point.t OBus_signal.t
val hw_address : t -> string OBus_property.r
val mode : t -> int OBus_property.r
val bitrate : t -> int OBus_property.r
val active_access_point : t -> OBus_proxy.t OBus_property.r
val wireless_capabilities : t -> int OBus_property.r
val properties : t -> OBus_property.group
end
| null | https://raw.githubusercontent.com/ocaml-community/obus/8d38ee6750587ae6519644630b75d53a0a011acd/bindings/network-manager/nm_device.mli | ocaml | * NetworkManager devices
* {8 Types}
* The device is in an unknown state.
* The device is not managed by NetworkManager.
* The device cannot be used (carrier off, rfkill, etc)
* The device is not connected.
* The device is preparing to connect.
* The device is being configured.
* The device is awaiting secrets necessary to continue connection.
* The IP settings of the device are being requested and configured.
* The device is active.
* The device is in a failure state following an attempt to activate it.
* The reason for the device state change is unknown.
* The state change is normal.
* The device is now managed.
* The device is no longer managed.
* The device could not be readied for configuration.
* IP configuration could not be reserved (no available address, timeout, etc).
* The IP configuration is no longer valid.
* Secrets were required, but not provided.
* The DHCP service failed to start within the allowed time.
* The DHCP service reported an unexpected error.
* The shared connection service failed to start.
* The shared connection service quit or failed unexpectedly.
* Dialing failed because the line was busy.
* Dialing failed because there was no dial tone.
* Dialing failed because there was carrier.
* Dialing timed out.
* Dialing failed.
* Modem initialization failed.
* Not searching for networks.
* Network registration was denied.
* Network registration timed out.
* Failed to register with the requested GSM network.
* PIN check failed.
* Necessary firmware for the device may be missing.
* The device was removed.
* NetworkManager went to sleep.
* The device's active connection was removed or disappeared.
* A user or client requested the disconnection.
* The device's carrier/link changed.
* The device's existing connection was assumed.
* The device type is unknown.
* The device is wired Ethernet device.
* The device is supported by NetworkManager.
* The device supports carrier detection.
* {8 Methods}
* {8 Signals}
* The device supports the TKIP cipher.
* The device supports the WPA encryption/authentication protocol.
* Mode is unknown.
* Uncoordinated network without central infrastructure. |
* nm_device.mli
* -------------
* Copyright : ( c ) 2010 , < >
* 2010 , < >
* Licence : BSD3
*
* This file is a part of obus , an ocaml implementation of D - Bus .
* nm_device.mli
* -------------
* Copyright : (c) 2010, Pierre Chambart <>
* 2010, Jeremie Dimino <>
* Licence : BSD3
*
* This file is a part of obus, an ocaml implementation of D-Bus.
*)
include OBus_proxy.Private
* { 6 Common interface }
type state =
[ `Unknown
| `Unmanaged
| `Unavailable
| `Disconnected
| `Prepare
| `Config
| `Need_auth
| `Ip_config
| `Activated
| `Failed
type state_reason =
[ `Unknown
| `None
| `Now_managed
| `Now_unmanaged
| `Config_failed
| `Config_unavailable
| `Config_expired
| `No_secrets
| `Supplicant_disconnect
* The 802.1X supplicant disconnected from the access point or authentication server .
| `Supplicant_config_failed
* Configuration of the 802.1X supplicant failed .
| `Supplicant_failed
* The 802.1X supplicant quit or failed unexpectedly .
| `Supplicant_timeout
* The 802.1X supplicant took too long to authenticate .
| `Ppp_start_failed
* The PPP service failed to start within the allowed time .
| `Ppp_disconnect
* The PPP service disconnected unexpectedly .
| `Ppp_failed
* The PPP service quit or failed unexpectedly .
| `Dhcp_start_failed
| `Dhcp_error
| `Dhcp_failed
* The DHCP service quit or failed unexpectedly .
| `Shared_start_failed
| `Shared_failed
| `Autoip_start_failed
* The AutoIP service failed to start .
| `Autoip_error
* The AutoIP service reported an unexpected error .
| `Autoip_failed
* The AutoIP service quit or failed unexpectedly .
| `Modem_busy
| `Modem_no_dial_tone
| `Modem_no_carrier
| `Modem_dial_timeout
| `Modem_dial_failed
| `Modem_init_failed
| `Gsm_apn_failed
* Failed to select the specified GSM APN .
| `Gsm_registration_not_searching
| `Gsm_registration_denied
| `Gsm_registration_timeout
| `Gsm_registration_failed
| `Gsm_pin_check_failed
| `Firmware_missing
| `Removed
| `Sleeping
| `Connection_removed
| `User_requested
| `Carrier
| `Connection_assumed
| `Supplicant_available
* The 802.1x supplicant is now available .
type typ =
[ `Unknown
| `Ethernet
| `Wifi
* The device is an 802.11 WiFi device .
| `Gsm
* The device is a GSM - based cellular WAN device .
| `Cdma
* The device is a CDMA / IS-95 - based cellular WAN device .
type capability =
[ `Nm_supported
| `Carrier_detect
val disconnect : t -> unit Lwt.t
val state_changed : t -> (state * state * state_reason) OBus_signal.t
* { 8 Properties }
val udi : t -> string OBus_property.r
val interface : t -> string OBus_property.r
val driver : t -> string OBus_property.r
val capabilities : t -> capability list OBus_property.r
val ip4_address : t -> int32 OBus_property.r
val state : t -> state OBus_property.r
val ip4_config : t -> Nm_ip4_config.t OBus_property.r
val dhcp4_config : t -> Nm_dhcp4_config.t OBus_property.r
val ip6_config : t -> Nm_ip6_config.t OBus_property.r
val managed : t -> bool OBus_property.r
val device_type : t -> typ OBus_property.r
val properties : t -> OBus_property.group
* { 6 Specific device interfaces }
module Bluetooth : sig
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
val hw_address : t -> string OBus_property.r
val name : t -> string OBus_property.r
val bt_capabilities : t -> int OBus_property.r
val properties : t -> OBus_property.group
end
module Cdma : sig
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
end
module Gsm : sig
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
end
module Olpc_mesh : sig
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
val hw_address : OBus_proxy.t -> (string, [ `readable ]) OBus_property.t
val companion : OBus_proxy.t -> (OBus_proxy.t, [ `readable ]) OBus_property.t
val active_channel : OBus_proxy.t -> (int, [ `readable ]) OBus_property.t
val properties : t -> OBus_property.group
end
module Serial : sig
val ppp_stats : t -> (int * int) OBus_signal.t
end
module Wired : sig
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
val hw_address : t -> string OBus_property.r
val speed : t -> int OBus_property.r
val carrier : t -> bool OBus_property.r
val properties : t -> OBus_property.group
end
module Wireless : sig
type wireless_capability =
[ `Cipher_wep40
* The device supports the 40 - bit WEP cipher .
| `Cipher_wep104
* The device supports the 104 - bit WEP cipher .
| `Cipher_tkip
| `Cipher_ccmp
* The device supports the CCMP cipher .
| `Wpa
| `Rsn
* The device supports the RSN encryption / authentication protocol .
type wifi_mode =
[ `Unknown
| `Adhoc
| `Infra
* Coordinated network with one or more central controllers .
val get_access_points : t -> Nm_access_point.t list Lwt.t
val properties_changed : t -> (string * OBus_value.V.single) list OBus_signal.t
val access_point_added : t -> Nm_access_point.t OBus_signal.t
val access_point_removed : t -> Nm_access_point.t OBus_signal.t
val hw_address : t -> string OBus_property.r
val mode : t -> int OBus_property.r
val bitrate : t -> int OBus_property.r
val active_access_point : t -> OBus_proxy.t OBus_property.r
val wireless_capabilities : t -> int OBus_property.r
val properties : t -> OBus_property.group
end
|
84a3702a1037fb66d2e1a17de1b2f5abb71a2e562de9a639ef816bd0003b54e4 | kawasima/jagrid | layout.clj | (ns jagrid.example.layout
(:use [hiccup core page element]))
(defn view-layout [options & content]
(html5
[:head
[:meta {:charset "utf-8"}]
[:title (:title options)]
(include-css
"-1/css/simplex/bootstrap.min.css"
""
"example.css")
[:link#jagrid-css {:href "../css/jagrid.css" :rel "stylesheet" :type "text/css"}]
(include-js
""
"../js/jagrid.js")]
[:body
[:div.navbar.navbar-default.navbar-fixed-top
[:div.container
[:div.navbar-header
[:a.navbar-brand {:href "index.html"} "jagrid"]]]]
[:div.container
[:div.form-group
[:label "Theme"]
[:select#theme.form-control {:name "theme"}
[:option {:value ""} "Default (Excel 2010)"]
[:option {:value "excel2000"} "Excel 2000"]
[:option {:value "lotus123"} "Lotus 1-2-3"]]]
content]
(javascript-tag "
hljs.initHighlightingOnLoad();
document.getElementById('theme').addEventListener('change', function(e) {
var filename = (e.target.value != '') ? '-' + e.target.value : '';
document.getElementById('jagrid-css')
.setAttribute('href', '../css/jagrid' + filename + '.css');
});
")]))
| null | https://raw.githubusercontent.com/kawasima/jagrid/524b351c47ba2648f96ce8ef5ee431d0eb594d28/src/jagrid/example/layout.clj | clojure | (ns jagrid.example.layout
(:use [hiccup core page element]))
(defn view-layout [options & content]
(html5
[:head
[:meta {:charset "utf-8"}]
[:title (:title options)]
(include-css
"-1/css/simplex/bootstrap.min.css"
""
"example.css")
[:link#jagrid-css {:href "../css/jagrid.css" :rel "stylesheet" :type "text/css"}]
(include-js
""
"../js/jagrid.js")]
[:body
[:div.navbar.navbar-default.navbar-fixed-top
[:div.container
[:div.navbar-header
[:a.navbar-brand {:href "index.html"} "jagrid"]]]]
[:div.container
[:div.form-group
[:label "Theme"]
[:select#theme.form-control {:name "theme"}
[:option {:value ""} "Default (Excel 2010)"]
[:option {:value "excel2000"} "Excel 2000"]
[:option {:value "lotus123"} "Lotus 1-2-3"]]]
content]
(javascript-tag "
document.getElementById('theme').addEventListener('change', function(e) {
document.getElementById('jagrid-css')
")]))
|
|
f8f2cc3c8798820516f12a4c34c546a9ee7507e90140dc9a7eba083e74d2bd0c | xtdb/core2 | user.clj | (ns user
(:require [clojure.java.io :as io]
[clojure.tools.namespace.repl :as ctn]
core2.edn
[core2.util :as util]
[time-literals.read-write :as time-literals])
(:import java.io.File))
(alter-var-root #'*warn-on-reflection* (constantly true))
(ctn/disable-reload!)
(util/install-uncaught-exception-handler!)
(apply ctn/set-refresh-dirs (cons (io/file "src/test/clojure")
(for [^File dir (concat (.listFiles (io/file "."))
(.listFiles (io/file "modules")))
:when (and (.isDirectory dir)
(.exists (io/file dir "deps.edn")))
sub-dir #{"src/main/clojure" "src/test/clojure"}]
(io/file dir sub-dir))))
#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]}
(defn reset []
(ctn/refresh))
#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]}
(defn dev []
(require 'dev)
(in-ns 'dev))
(time-literals/print-time-literals-clj!)
| null | https://raw.githubusercontent.com/xtdb/core2/5546a6c215631fbe4e5e67a2beb11e023dd01f11/src/dev/clojure/user.clj | clojure | (ns user
(:require [clojure.java.io :as io]
[clojure.tools.namespace.repl :as ctn]
core2.edn
[core2.util :as util]
[time-literals.read-write :as time-literals])
(:import java.io.File))
(alter-var-root #'*warn-on-reflection* (constantly true))
(ctn/disable-reload!)
(util/install-uncaught-exception-handler!)
(apply ctn/set-refresh-dirs (cons (io/file "src/test/clojure")
(for [^File dir (concat (.listFiles (io/file "."))
(.listFiles (io/file "modules")))
:when (and (.isDirectory dir)
(.exists (io/file dir "deps.edn")))
sub-dir #{"src/main/clojure" "src/test/clojure"}]
(io/file dir sub-dir))))
#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]}
(defn reset []
(ctn/refresh))
#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]}
(defn dev []
(require 'dev)
(in-ns 'dev))
(time-literals/print-time-literals-clj!)
|
|
ae33d886b0c2441feea8c391cef8f468c260a11944cf7e01f5ba81d0dc2df34b | mvr/at | AbelianCategoryProperties.hs | module AbelianCategoryProperties where
import Data.Proxy
import Test.Hspec
import Test.QuickCheck
import Math.ValueCategory
import Math.ValueCategory.Abelian
import Math.ValueCategory.Additive
spec ::
forall c.
( AbelianCategory c,
Eq c,
Eq (Arrow c),
Show c,
Show (Arrow c),
Arbitrary c,
Arbitrary (Arrow c)
) =>
Proxy c ->
Spec
spec p = do
describe "kernel" $ do
it "has domain kernelObject" $
property $
\(f :: Arrow c) -> domain (kernel f) == kernelObject f
it "has codomain the domain of f" $
property $
\(f :: Arrow c) -> codomain (kernel f) == domain f
it "composes with f to zero" $
property $
\(f :: Arrow c) -> isZeroArrow (f <> kernel f)
describe "kernelObject" $ do
it "of identity is zero" $
property $
\(a :: c) -> kernelObject (vid a) == zero
it "of zero map is domain" $
property $
\(a :: c, b) -> kernelObject (zeroArrow a b) == a
describe "kernelMorphism" $ do
it "induced by identity is identity" $
property $
\(l :: Arrow c) -> kernelArrow l l (vid $ domain l) == vid (kernelObject l)
describe "cokernel" $ do
it "has domain the codomain of f" $
property $
\(f :: Arrow c) -> domain (cokernel f) == codomain f
it "has codomain cokernelObject" $
property $
\(f :: Arrow c) -> codomain (cokernel f) == cokernelObject f
it "composes with f to zero" $
property $
\(f :: Arrow c) -> isZeroArrow (cokernel f <> f)
describe "cokernelObject" $ do
it "of identity is zero" $
property $
\(a :: c) -> cokernelObject (vid a) == zero
it "of zero map is codomain" $
property $
\(a :: c, b) -> cokernelObject (zeroArrow a b) == b
describe "cokernelMorphism" $ do
it "induced by identity is identity" $
property $
\(l :: Arrow c) -> cokernelArrow l l (vid $ codomain l) == vid (cokernelObject l)
describe "imageObject" $ do
it "of identity is itself" $
property $
\(a :: c) -> imageObject (vid a) == a
it "of zero map is zero" $
property $
\(a :: c, b) -> imageObject (zeroArrow a b) == zero
describe "image == coimage" $ do
it "is true" $
property $
\(f :: Arrow c) -> imageObject f == coimageObject f
| null | https://raw.githubusercontent.com/mvr/at/f08b25ee2d83f761fd288a66f05dad1943879db1/test/AbelianCategoryProperties.hs | haskell | module AbelianCategoryProperties where
import Data.Proxy
import Test.Hspec
import Test.QuickCheck
import Math.ValueCategory
import Math.ValueCategory.Abelian
import Math.ValueCategory.Additive
spec ::
forall c.
( AbelianCategory c,
Eq c,
Eq (Arrow c),
Show c,
Show (Arrow c),
Arbitrary c,
Arbitrary (Arrow c)
) =>
Proxy c ->
Spec
spec p = do
describe "kernel" $ do
it "has domain kernelObject" $
property $
\(f :: Arrow c) -> domain (kernel f) == kernelObject f
it "has codomain the domain of f" $
property $
\(f :: Arrow c) -> codomain (kernel f) == domain f
it "composes with f to zero" $
property $
\(f :: Arrow c) -> isZeroArrow (f <> kernel f)
describe "kernelObject" $ do
it "of identity is zero" $
property $
\(a :: c) -> kernelObject (vid a) == zero
it "of zero map is domain" $
property $
\(a :: c, b) -> kernelObject (zeroArrow a b) == a
describe "kernelMorphism" $ do
it "induced by identity is identity" $
property $
\(l :: Arrow c) -> kernelArrow l l (vid $ domain l) == vid (kernelObject l)
describe "cokernel" $ do
it "has domain the codomain of f" $
property $
\(f :: Arrow c) -> domain (cokernel f) == codomain f
it "has codomain cokernelObject" $
property $
\(f :: Arrow c) -> codomain (cokernel f) == cokernelObject f
it "composes with f to zero" $
property $
\(f :: Arrow c) -> isZeroArrow (cokernel f <> f)
describe "cokernelObject" $ do
it "of identity is zero" $
property $
\(a :: c) -> cokernelObject (vid a) == zero
it "of zero map is codomain" $
property $
\(a :: c, b) -> cokernelObject (zeroArrow a b) == b
describe "cokernelMorphism" $ do
it "induced by identity is identity" $
property $
\(l :: Arrow c) -> cokernelArrow l l (vid $ codomain l) == vid (cokernelObject l)
describe "imageObject" $ do
it "of identity is itself" $
property $
\(a :: c) -> imageObject (vid a) == a
it "of zero map is zero" $
property $
\(a :: c, b) -> imageObject (zeroArrow a b) == zero
describe "image == coimage" $ do
it "is true" $
property $
\(f :: Arrow c) -> imageObject f == coimageObject f
|
|
f214e4bfa092e743b31921d89465903ce0ae643c923eb6127b76219415eeb33c | ndmitchell/catch | ReqEq.hs |
module ReqEq(
equalReq, equalReqs,
enumerateReqs
) where
import Req
import Path
import PathCtor
import PathCtorEq
import Data.List
import Data.Maybe
import Data.Proposition
import Yhc.Core
import General
import Debug.Trace
equalReq :: Req -> Req -> Bool
equalReq (Req a1 b1@(PathCtor core _ _)) (Req a2 b2) = a1 == a2 && equalPathCtor core b1 b2
equalReq a b = a == b
equalReqs :: Reqs -> Reqs -> Bool
trace ( show ( a , b , normalise core $ enumerateReqs a , normalise core $ enumerateReqs b , res ) ) res
where
res = equalValue core (enumerateReqs a) (enumerateReqs b)
PathCtor core _ _ = reqPath $ head $ propAll a ++ propAll b
enumerateReqs :: Reqs -> [Val]
enumerateReqs x = enumeratePathCtorProp $ (propFold folder x :: PropSimple PathCtor)
where
folder = PropFold {foldOr = propOrs, foldAnd = propAnds, foldNot = propNot, foldLit = f}
PathCtor core _ _ = reqPath $ head $ propAll x
core2 = core{coreDatas = newData : coreDatas core}
newData = CoreData "#" [] [CoreCtor "#" [("",Just ('#' : show i)) | i <- [0..arity-1]]]
f (Req a (PathCtor _ (Path path) ctors)) = propLit $ PathCtor core2 (Path (p:path)) ctors
where p = PathAtom $ '#' : (show $ fromJust $ findIndex (== a) vars)
arity = length vars
vars = snub $ map reqExpr $ propAll x
| null | https://raw.githubusercontent.com/ndmitchell/catch/5d834416a27b4df3f7ce7830c4757d4505aaf96e/analyse/ReqEq.hs | haskell |
module ReqEq(
equalReq, equalReqs,
enumerateReqs
) where
import Req
import Path
import PathCtor
import PathCtorEq
import Data.List
import Data.Maybe
import Data.Proposition
import Yhc.Core
import General
import Debug.Trace
equalReq :: Req -> Req -> Bool
equalReq (Req a1 b1@(PathCtor core _ _)) (Req a2 b2) = a1 == a2 && equalPathCtor core b1 b2
equalReq a b = a == b
equalReqs :: Reqs -> Reqs -> Bool
trace ( show ( a , b , normalise core $ enumerateReqs a , normalise core $ enumerateReqs b , res ) ) res
where
res = equalValue core (enumerateReqs a) (enumerateReqs b)
PathCtor core _ _ = reqPath $ head $ propAll a ++ propAll b
enumerateReqs :: Reqs -> [Val]
enumerateReqs x = enumeratePathCtorProp $ (propFold folder x :: PropSimple PathCtor)
where
folder = PropFold {foldOr = propOrs, foldAnd = propAnds, foldNot = propNot, foldLit = f}
PathCtor core _ _ = reqPath $ head $ propAll x
core2 = core{coreDatas = newData : coreDatas core}
newData = CoreData "#" [] [CoreCtor "#" [("",Just ('#' : show i)) | i <- [0..arity-1]]]
f (Req a (PathCtor _ (Path path) ctors)) = propLit $ PathCtor core2 (Path (p:path)) ctors
where p = PathAtom $ '#' : (show $ fromJust $ findIndex (== a) vars)
arity = length vars
vars = snub $ map reqExpr $ propAll x
|
|
66e2ce0f9f2f3543fc90477b4e9bb0fc675212ea465dcd69592a8b3df1035126 | pirapira/coq2rust | conv_oracle.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Names
type oracle
val empty : oracle
* Order on section paths for unfolding .
If [ oracle_order kn1 kn2 ] is true , then unfold kn1 first .
Note : the oracle does not introduce incompleteness , it only
tries to postpone unfolding of " opaque " constants .
If [oracle_order kn1 kn2] is true, then unfold kn1 first.
Note: the oracle does not introduce incompleteness, it only
tries to postpone unfolding of "opaque" constants. *)
val oracle_order : oracle -> bool -> constant tableKey -> constant tableKey -> bool
(** Priority for the expansion of constant in the conversion test.
* Higher levels means that the expansion is less prioritary.
* (And Expand stands for -oo, and Opaque +oo.)
* The default value (transparent constants) is [Level 0].
*)
type level = Expand | Level of int | Opaque
val transparent : level
(** Check whether a level is transparent *)
val is_transparent : level -> bool
val get_strategy : oracle -> constant tableKey -> level
(** Sets the level of a constant.
* Level of RelKey constant cannot be set. *)
val set_strategy : oracle -> constant tableKey -> level -> oracle
(** Fold over the non-transparent levels of the oracle. Order unspecified. *)
val fold_strategy : (constant tableKey -> level -> 'a -> 'a) -> oracle -> 'a -> 'a
val get_transp_state : oracle -> transparent_state
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/kernel/conv_oracle.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* Priority for the expansion of constant in the conversion test.
* Higher levels means that the expansion is less prioritary.
* (And Expand stands for -oo, and Opaque +oo.)
* The default value (transparent constants) is [Level 0].
* Check whether a level is transparent
* Sets the level of a constant.
* Level of RelKey constant cannot be set.
* Fold over the non-transparent levels of the oracle. Order unspecified. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
type oracle
val empty : oracle
* Order on section paths for unfolding .
If [ oracle_order kn1 kn2 ] is true , then unfold kn1 first .
Note : the oracle does not introduce incompleteness , it only
tries to postpone unfolding of " opaque " constants .
If [oracle_order kn1 kn2] is true, then unfold kn1 first.
Note: the oracle does not introduce incompleteness, it only
tries to postpone unfolding of "opaque" constants. *)
val oracle_order : oracle -> bool -> constant tableKey -> constant tableKey -> bool
type level = Expand | Level of int | Opaque
val transparent : level
val is_transparent : level -> bool
val get_strategy : oracle -> constant tableKey -> level
val set_strategy : oracle -> constant tableKey -> level -> oracle
val fold_strategy : (constant tableKey -> level -> 'a -> 'a) -> oracle -> 'a -> 'a
val get_transp_state : oracle -> transparent_state
|
32c9e0fd2a5ddd300838537bf400c71b1f7d6f17094a787632e4098c12c7d817 | evturn/haskellbook | 11.08-for-example.hs | 1 .
What is the type of data constructor ` MakeExample ` ? What happens if you
-- query the type of `Example`?
data Example = MakeExample deriving Show
-- Answer: Nullary. You can query the type of a data constructor but
-- it makes no sense to query the type of a type constructor since itself
-- is a type.
2 . What happens if you query the info on ` Example ` and can you determine
-- what typeclass instances are defined for it?
-- Answer: The definition is printed along with the instances it has.
3 .
-- What gets printed in the REPL if you make a new datatype like `Example`
but with a single type argument added to ` MakeExample ` ?
data Example' = MakeExample' Int deriving Show
Answer : MakeExample ' : : Int - > Example '
| null | https://raw.githubusercontent.com/evturn/haskellbook/3d310d0ddd4221ffc5b9fd7ec6476b2a0731274a/11/11.08-for-example.hs | haskell | query the type of `Example`?
Answer: Nullary. You can query the type of a data constructor but
it makes no sense to query the type of a type constructor since itself
is a type.
what typeclass instances are defined for it?
Answer: The definition is printed along with the instances it has.
What gets printed in the REPL if you make a new datatype like `Example` | 1 .
What is the type of data constructor ` MakeExample ` ? What happens if you
data Example = MakeExample deriving Show
2 . What happens if you query the info on ` Example ` and can you determine
3 .
but with a single type argument added to ` MakeExample ` ?
data Example' = MakeExample' Int deriving Show
Answer : MakeExample ' : : Int - > Example '
|
48b652fa67e53db34fe85649cf0c500db420032745ad121059af0993accf522f | hemmi/coq2scala | cbv.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Util
open Pp
open Term
open Names
open Environ
open Univ
open Evd
open Conv_oracle
open Closure
open Esubst
(**** Call by value reduction ****)
The type of terms with closure . The meaning of the constructors and
* the invariants of this datatype are the following :
* VAL(k , c ) represents the constr c with a delayed shift of k. c must be
* in normal form and neutral ( i.e. not a lambda , a construct or a
* ( co)fix , because they may produce redexes by applying them ,
* or putting them in a case )
* STACK(k , v , ) represents an irreductible value [ v ] in the stack [ stk ] .
* [ k ] is a delayed shift to be applied to both the value and
* the stack .
* CBN(t , S ) is the term [ S]t . It is used to delay evaluation . For
* instance products are evaluated only when actually needed
* ( CBN strategy ) .
* LAM(n , a , b , S ) is the term [ : a]b ) where [ a ] is a list of bindings and
* [ n ] is the length of [ a ] . the environment [ S ] is propagated
* only when the abstraction is applied , and then we use the rule
* ( [ : a]b ) c ) -- > [ S.c]b
* This corresponds to the usual strategy of weak reduction
* FIXP(op , bd , S , args ) is the fixpoint ( Fix or Cofix ) of bodies bd under
* the bindings S , and then applied to args . Here again ,
* weak reduction .
* CONSTR(c , args ) is the constructor [ c ] applied to [ args ] .
*
* the invariants of this datatype are the following:
* VAL(k,c) represents the constr c with a delayed shift of k. c must be
* in normal form and neutral (i.e. not a lambda, a construct or a
* (co)fix, because they may produce redexes by applying them,
* or putting them in a case)
* STACK(k,v,stk) represents an irreductible value [v] in the stack [stk].
* [k] is a delayed shift to be applied to both the value and
* the stack.
* CBN(t,S) is the term [S]t. It is used to delay evaluation. For
* instance products are evaluated only when actually needed
* (CBN strategy).
* LAM(n,a,b,S) is the term [S]([x:a]b) where [a] is a list of bindings and
* [n] is the length of [a]. the environment [S] is propagated
* only when the abstraction is applied, and then we use the rule
* ([S]([x:a]b) c) --> [S.c]b
* This corresponds to the usual strategy of weak reduction
* FIXP(op,bd,S,args) is the fixpoint (Fix or Cofix) of bodies bd under
* the bindings S, and then applied to args. Here again,
* weak reduction.
* CONSTR(c,args) is the constructor [c] applied to [args].
*
*)
type cbv_value =
| VAL of int * constr
| STACK of int * cbv_value * cbv_stack
| CBN of constr * cbv_value subs
| LAM of int * (name * constr) list * constr * cbv_value subs
| FIXP of fixpoint * cbv_value subs * cbv_value array
| COFIXP of cofixpoint * cbv_value subs * cbv_value array
| CONSTR of constructor * cbv_value array
type of terms with a hole . This hole can appear only under App or Case .
* TOP means the term is considered without context
* APP(v , stk ) means the term is applied to v , and then the context stk
* ( v.0 is the first argument ) .
* this corresponds to the application stack of the KAM .
* The members of l are values : we evaluate arguments before
calling the function .
* CASE(t , br , pat , S , ) means the term is in a case ( which is himself in stk
* t is the type of the case and br are the branches , all of them under
* the subs S , pat is information on the patterns of the Case
* ( Weak reduction : we propagate the sub only when the selected branch
* is determined )
*
* Important remark : the APPs should be collapsed :
* ( APP ( ... ) ) ) forbidden
* TOP means the term is considered without context
* APP(v,stk) means the term is applied to v, and then the context stk
* (v.0 is the first argument).
* this corresponds to the application stack of the KAM.
* The members of l are values: we evaluate arguments before
calling the function.
* CASE(t,br,pat,S,stk) means the term is in a case (which is himself in stk
* t is the type of the case and br are the branches, all of them under
* the subs S, pat is information on the patterns of the Case
* (Weak reduction: we propagate the sub only when the selected branch
* is determined)
*
* Important remark: the APPs should be collapsed:
* (APP (l,(APP ...))) forbidden
*)
and cbv_stack =
| TOP
| APP of cbv_value array * cbv_stack
| CASE of constr * constr array * case_info * cbv_value subs * cbv_stack
les vars pourraient ,
cela permet de retarder les lift : utile ? ?
cela permet de retarder les lift: utile ?? *)
(* relocation of a value; used when a value stored in a context is expanded
* in a larger context. e.g. [%k (S.t)](k+1) --> [^k]t (t is shifted of k)
*)
let rec shift_value n = function
| VAL (k,t) -> VAL (k+n,t)
| STACK(k,v,stk) -> STACK(k+n,v,stk)
| CBN (t,s) -> CBN(t,subs_shft(n,s))
| LAM (nlams,ctxt,b,s) -> LAM (nlams,ctxt,b,subs_shft (n,s))
| FIXP (fix,s,args) ->
FIXP (fix,subs_shft (n,s), Array.map (shift_value n) args)
| COFIXP (cofix,s,args) ->
COFIXP (cofix,subs_shft (n,s), Array.map (shift_value n) args)
| CONSTR (c,args) ->
CONSTR (c, Array.map (shift_value n) args)
let shift_value n v =
if n = 0 then v else shift_value n v
Contracts a fixpoint : given a fixpoint and a bindings ,
* returns the corresponding fixpoint body , and the bindings in which
* it should be evaluated : its first variables are the fixpoint bodies
* ( S , ( fix Fi { F0 : = T0 .. Fn-1 : = Tn-1 } ) )
* - > ( S. [ S]F0 . [ S]F1 ... . [ S]Fn-1 , Ti )
* returns the corresponding fixpoint body, and the bindings in which
* it should be evaluated: its first variables are the fixpoint bodies
* (S, (fix Fi {F0 := T0 .. Fn-1 := Tn-1}))
* -> (S. [S]F0 . [S]F1 ... . [S]Fn-1, Ti)
*)
let contract_fixp env ((reci,i),(_,_,bds as bodies)) =
let make_body j = FIXP(((reci,j),bodies), env, [||]) in
let n = Array.length bds in
subs_cons(Array.init n make_body, env), bds.(i)
let contract_cofixp env (i,(_,_,bds as bodies)) =
let make_body j = COFIXP((j,bodies), env, [||]) in
let n = Array.length bds in
subs_cons(Array.init n make_body, env), bds.(i)
let make_constr_ref n = function
| RelKey p -> mkRel (n+p)
| VarKey id -> mkVar id
| ConstKey cst -> mkConst cst
(* Adds an application list. Collapse APPs! *)
let stack_app appl stack =
if Array.length appl = 0 then stack else
match stack with
| APP(args,stk) -> APP(Array.append appl args,stk)
| _ -> APP(appl, stack)
let rec stack_concat stk1 stk2 =
match stk1 with
TOP -> stk2
| APP(v,stk1') -> APP(v,stack_concat stk1' stk2)
| CASE(c,b,i,s,stk1') -> CASE(c,b,i,s,stack_concat stk1' stk2)
(* merge stacks when there is no shifts in between *)
let mkSTACK = function
v, TOP -> v
| STACK(0,v0,stk0), stk -> STACK(0,v0,stack_concat stk0 stk)
| v,stk -> STACK(0,v,stk)
Change : zeta reduction can not be avoided in CBV
open RedFlags
let red_set_ref flags = function
| RelKey _ -> red_set flags fDELTA
| VarKey id -> red_set flags (fVAR id)
| ConstKey sp -> red_set flags (fCONST sp)
(* Transfer application lists from a value to the stack
* useful because fixpoints may be totally applied in several times.
* On the other hand, irreductible atoms absorb the full stack.
*)
let strip_appl head stack =
match head with
| FIXP (fix,env,app) -> (FIXP(fix,env,[||]), stack_app app stack)
| COFIXP (cofix,env,app) -> (COFIXP(cofix,env,[||]), stack_app app stack)
| CONSTR (c,app) -> (CONSTR(c,[||]), stack_app app stack)
| _ -> (head, stack)
(* Tests if fixpoint reduction is possible. *)
let fixp_reducible flgs ((reci,i),_) stk =
if red_set flgs fIOTA then
match stk with
| APP(appl,_) ->
Array.length appl > reci.(i) &&
(match appl.(reci.(i)) with
CONSTR _ -> true
| _ -> false)
| _ -> false
else
false
let cofixp_reducible flgs _ stk =
if red_set flgs fIOTA then
match stk with
| (CASE _ | APP(_,CASE _)) -> true
| _ -> false
else
false
The main recursive functions
*
* Go under applications and cases ( pushed in the stack ) , expand head
* constants or substitued , and try to make appear a
* constructor , a lambda or a fixp in the head . If not , it is a value
* and is completely computed here . The head redexes are NOT reduced :
* the function returns the pair of a cbv_value and its stack . *
* Invariant : if the result of is CONSTR or ( CO)FIXP , it last
* argument is [ ] . Because we must put all the applied terms in the
* stack .
*
* Go under applications and cases (pushed in the stack), expand head
* constants or substitued de Bruijn, and try to make appear a
* constructor, a lambda or a fixp in the head. If not, it is a value
* and is completely computed here. The head redexes are NOT reduced:
* the function returns the pair of a cbv_value and its stack. *
* Invariant: if the result of norm_head is CONSTR or (CO)FIXP, it last
* argument is []. Because we must put all the applied terms in the
* stack. *)
let rec norm_head info env t stack =
(* no reduction under binders *)
match kind_of_term t with
(* stack grows (remove casts) *)
Applied terms are normalized immediately ;
they could be computed when getting out of the stack
they could be computed when getting out of the stack *)
let nargs = Array.map (cbv_stack_term info TOP env) args in
norm_head info env head (stack_app nargs stack)
| Case (ci,p,c,v) -> norm_head info env c (CASE(p,v,ci,env,stack))
| Cast (ct,_,_) -> norm_head info env ct stack
constants , axioms
* the first pattern is CRUCIAL , n=0 happens very often :
* when reducing closed terms , n is always 0
* the first pattern is CRUCIAL, n=0 happens very often:
* when reducing closed terms, n is always 0 *)
| Rel i ->
(match expand_rel i env with
| Inl (0,v) -> strip_appl v stack
| Inl (n,v) -> strip_appl (shift_value n v) stack
| Inr (n,None) -> (VAL(0, mkRel n), stack)
| Inr (n,Some p) -> norm_head_ref (n-p) info env stack (RelKey p))
| Var id -> norm_head_ref 0 info env stack (VarKey id)
| Const sp -> norm_head_ref 0 info env stack (ConstKey sp)
| LetIn (_, b, _, c) ->
(* zeta means letin are contracted; delta without zeta means we *)
(* allow bindings but leave let's in place *)
if red_set (info_flags info) fZETA then
New rule : for Cbv , Delta does not apply to locally bound variables
or red_set ( info_flags info ) fDELTA
or red_set (info_flags info) fDELTA
*)
let env' = subs_cons ([|cbv_stack_term info TOP env b|],env) in
norm_head info env' c stack
else
une coupure commutative ?
| Evar ev ->
(match evar_value info ev with
Some c -> norm_head info env c stack
| None -> (VAL(0, t), stack))
(* non-neutral cases *)
| Lambda _ ->
let ctxt,b = decompose_lam t in
(LAM(List.length ctxt, List.rev ctxt,b,env), stack)
| Fix fix -> (FIXP(fix,env,[||]), stack)
| CoFix cofix -> (COFIXP(cofix,env,[||]), stack)
| Construct c -> (CONSTR(c, [||]), stack)
(* neutral cases *)
| (Sort _ | Meta _ | Ind _) -> (VAL(0, t), stack)
| Prod _ -> (CBN(t,env), stack)
and norm_head_ref k info env stack normt =
if red_set_ref (info_flags info) normt then
match ref_value_cache info normt with
| Some body -> strip_appl (shift_value k body) stack
| None -> (VAL(0,make_constr_ref k normt),stack)
else (VAL(0,make_constr_ref k normt),stack)
cbv_stack_term performs weak reduction on constr t under the subs
* env , with context stack , i.e. ( [ env]t stack ) . First computes weak
* head normal form of t and checks if a redex appears with the stack .
* If so , recursive call to reach the real head normal form . If not ,
* we build a value .
* env, with context stack, i.e. ([env]t stack). First computes weak
* head normal form of t and checks if a redex appears with the stack.
* If so, recursive call to reach the real head normal form. If not,
* we build a value.
*)
and cbv_stack_term info stack env t =
match norm_head info env t stack with
(* a lambda meets an application -> BETA *)
| (LAM (nlams,ctxt,b,env), APP (args, stk))
when red_set (info_flags info) fBETA ->
let nargs = Array.length args in
if nargs == nlams then
cbv_stack_term info stk (subs_cons(args,env)) b
else if nlams < nargs then
let env' = subs_cons(Array.sub args 0 nlams, env) in
let eargs = Array.sub args nlams (nargs-nlams) in
cbv_stack_term info (APP(eargs,stk)) env' b
else
let ctxt' = list_skipn nargs ctxt in
LAM(nlams-nargs,ctxt', b, subs_cons(args,env))
a Fix applied enough - > IOTA
| (FIXP(fix,env,[||]), stk)
when fixp_reducible (info_flags info) fix stk ->
let (envf,redfix) = contract_fixp env fix in
cbv_stack_term info stk envf redfix
constructor guard satisfied or Cofix in a Case - > IOTA
| (COFIXP(cofix,env,[||]), stk)
when cofixp_reducible (info_flags info) cofix stk->
let (envf,redfix) = contract_cofixp env cofix in
cbv_stack_term info stk envf redfix
constructor in a Case - > IOTA
| (CONSTR((sp,n),[||]), APP(args,CASE(_,br,ci,env,stk)))
when red_set (info_flags info) fIOTA ->
let cargs =
Array.sub args ci.ci_npar (Array.length args - ci.ci_npar) in
cbv_stack_term info (stack_app cargs stk) env br.(n-1)
constructor of arity 0 in a Case - > IOTA
| (CONSTR((_,n),[||]), CASE(_,br,_,env,stk))
when red_set (info_flags info) fIOTA ->
cbv_stack_term info stk env br.(n-1)
(* may be reduced later by application *)
| (FIXP(fix,env,[||]), APP(appl,TOP)) -> FIXP(fix,env,appl)
| (COFIXP(cofix,env,[||]), APP(appl,TOP)) -> COFIXP(cofix,env,appl)
| (CONSTR(c,[||]), APP(appl,TOP)) -> CONSTR(c,appl)
(* definitely a value *)
| (head,stk) -> mkSTACK(head, stk)
(* When we are sure t will never produce a redex with its stack, we
* normalize (even under binders) the applied terms and we build the
* final term
*)
let rec apply_stack info t = function
| TOP -> t
| APP (args,st) ->
apply_stack info (mkApp(t,Array.map (cbv_norm_value info) args)) st
| CASE (ty,br,ci,env,st) ->
apply_stack info
(mkCase (ci, cbv_norm_term info env ty, t,
Array.map (cbv_norm_term info env) br))
st
(* performs the reduction on a constr, and returns a constr *)
and cbv_norm_term info env t =
(* reduction under binders *)
cbv_norm_value info (cbv_stack_term info TOP env t)
(* reduction of a cbv_value to a constr *)
and cbv_norm_value info = function (* reduction under binders *)
| VAL (n,t) -> lift n t
| STACK (0,v,stk) ->
apply_stack info (cbv_norm_value info v) stk
| STACK (n,v,stk) ->
lift n (apply_stack info (cbv_norm_value info v) stk)
| CBN(t,env) ->
map_constr_with_binders subs_lift (cbv_norm_term info) env t
| LAM (n,ctxt,b,env) ->
let nctxt =
list_map_i (fun i (x,ty) ->
(x,cbv_norm_term info (subs_liftn i env) ty)) 0 ctxt in
compose_lam (List.rev nctxt) (cbv_norm_term info (subs_liftn n env) b)
| FIXP ((lij,(names,lty,bds)),env,args) ->
mkApp
(mkFix (lij,
(names,
Array.map (cbv_norm_term info env) lty,
Array.map (cbv_norm_term info
(subs_liftn (Array.length lty) env)) bds)),
Array.map (cbv_norm_value info) args)
| COFIXP ((j,(names,lty,bds)),env,args) ->
mkApp
(mkCoFix (j,
(names,Array.map (cbv_norm_term info env) lty,
Array.map (cbv_norm_term info
(subs_liftn (Array.length lty) env)) bds)),
Array.map (cbv_norm_value info) args)
| CONSTR (c,args) ->
mkApp(mkConstruct c, Array.map (cbv_norm_value info) args)
(* with profiling *)
let cbv_norm infos constr =
with_stats (lazy (cbv_norm_term infos (subs_id 0) constr))
type cbv_infos = cbv_value infos
constant bodies are normalized at the first expansion
let create_cbv_infos flgs env sigma =
create
(fun old_info c -> cbv_stack_term old_info TOP (subs_id 0) c)
flgs
env
(Reductionops.safe_evar_value sigma)
| null | https://raw.githubusercontent.com/hemmi/coq2scala/d10f441c18146933a99bf2088116bd213ac3648d/coq-8.4pl2/pretyping/cbv.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
*** Call by value reduction ***
relocation of a value; used when a value stored in a context is expanded
* in a larger context. e.g. [%k (S.t)](k+1) --> [^k]t (t is shifted of k)
Adds an application list. Collapse APPs!
merge stacks when there is no shifts in between
Transfer application lists from a value to the stack
* useful because fixpoints may be totally applied in several times.
* On the other hand, irreductible atoms absorb the full stack.
Tests if fixpoint reduction is possible.
no reduction under binders
stack grows (remove casts)
zeta means letin are contracted; delta without zeta means we
allow bindings but leave let's in place
non-neutral cases
neutral cases
a lambda meets an application -> BETA
may be reduced later by application
definitely a value
When we are sure t will never produce a redex with its stack, we
* normalize (even under binders) the applied terms and we build the
* final term
performs the reduction on a constr, and returns a constr
reduction under binders
reduction of a cbv_value to a constr
reduction under binders
with profiling | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Util
open Pp
open Term
open Names
open Environ
open Univ
open Evd
open Conv_oracle
open Closure
open Esubst
The type of terms with closure . The meaning of the constructors and
* the invariants of this datatype are the following :
* VAL(k , c ) represents the constr c with a delayed shift of k. c must be
* in normal form and neutral ( i.e. not a lambda , a construct or a
* ( co)fix , because they may produce redexes by applying them ,
* or putting them in a case )
* STACK(k , v , ) represents an irreductible value [ v ] in the stack [ stk ] .
* [ k ] is a delayed shift to be applied to both the value and
* the stack .
* CBN(t , S ) is the term [ S]t . It is used to delay evaluation . For
* instance products are evaluated only when actually needed
* ( CBN strategy ) .
* LAM(n , a , b , S ) is the term [ : a]b ) where [ a ] is a list of bindings and
* [ n ] is the length of [ a ] . the environment [ S ] is propagated
* only when the abstraction is applied , and then we use the rule
* ( [ : a]b ) c ) -- > [ S.c]b
* This corresponds to the usual strategy of weak reduction
* FIXP(op , bd , S , args ) is the fixpoint ( Fix or Cofix ) of bodies bd under
* the bindings S , and then applied to args . Here again ,
* weak reduction .
* CONSTR(c , args ) is the constructor [ c ] applied to [ args ] .
*
* the invariants of this datatype are the following:
* VAL(k,c) represents the constr c with a delayed shift of k. c must be
* in normal form and neutral (i.e. not a lambda, a construct or a
* (co)fix, because they may produce redexes by applying them,
* or putting them in a case)
* STACK(k,v,stk) represents an irreductible value [v] in the stack [stk].
* [k] is a delayed shift to be applied to both the value and
* the stack.
* CBN(t,S) is the term [S]t. It is used to delay evaluation. For
* instance products are evaluated only when actually needed
* (CBN strategy).
* LAM(n,a,b,S) is the term [S]([x:a]b) where [a] is a list of bindings and
* [n] is the length of [a]. the environment [S] is propagated
* only when the abstraction is applied, and then we use the rule
* ([S]([x:a]b) c) --> [S.c]b
* This corresponds to the usual strategy of weak reduction
* FIXP(op,bd,S,args) is the fixpoint (Fix or Cofix) of bodies bd under
* the bindings S, and then applied to args. Here again,
* weak reduction.
* CONSTR(c,args) is the constructor [c] applied to [args].
*
*)
type cbv_value =
| VAL of int * constr
| STACK of int * cbv_value * cbv_stack
| CBN of constr * cbv_value subs
| LAM of int * (name * constr) list * constr * cbv_value subs
| FIXP of fixpoint * cbv_value subs * cbv_value array
| COFIXP of cofixpoint * cbv_value subs * cbv_value array
| CONSTR of constructor * cbv_value array
type of terms with a hole . This hole can appear only under App or Case .
* TOP means the term is considered without context
* APP(v , stk ) means the term is applied to v , and then the context stk
* ( v.0 is the first argument ) .
* this corresponds to the application stack of the KAM .
* The members of l are values : we evaluate arguments before
calling the function .
* CASE(t , br , pat , S , ) means the term is in a case ( which is himself in stk
* t is the type of the case and br are the branches , all of them under
* the subs S , pat is information on the patterns of the Case
* ( Weak reduction : we propagate the sub only when the selected branch
* is determined )
*
* Important remark : the APPs should be collapsed :
* ( APP ( ... ) ) ) forbidden
* TOP means the term is considered without context
* APP(v,stk) means the term is applied to v, and then the context stk
* (v.0 is the first argument).
* this corresponds to the application stack of the KAM.
* The members of l are values: we evaluate arguments before
calling the function.
* CASE(t,br,pat,S,stk) means the term is in a case (which is himself in stk
* t is the type of the case and br are the branches, all of them under
* the subs S, pat is information on the patterns of the Case
* (Weak reduction: we propagate the sub only when the selected branch
* is determined)
*
* Important remark: the APPs should be collapsed:
* (APP (l,(APP ...))) forbidden
*)
and cbv_stack =
| TOP
| APP of cbv_value array * cbv_stack
| CASE of constr * constr array * case_info * cbv_value subs * cbv_stack
les vars pourraient ,
cela permet de retarder les lift : utile ? ?
cela permet de retarder les lift: utile ?? *)
let rec shift_value n = function
| VAL (k,t) -> VAL (k+n,t)
| STACK(k,v,stk) -> STACK(k+n,v,stk)
| CBN (t,s) -> CBN(t,subs_shft(n,s))
| LAM (nlams,ctxt,b,s) -> LAM (nlams,ctxt,b,subs_shft (n,s))
| FIXP (fix,s,args) ->
FIXP (fix,subs_shft (n,s), Array.map (shift_value n) args)
| COFIXP (cofix,s,args) ->
COFIXP (cofix,subs_shft (n,s), Array.map (shift_value n) args)
| CONSTR (c,args) ->
CONSTR (c, Array.map (shift_value n) args)
let shift_value n v =
if n = 0 then v else shift_value n v
Contracts a fixpoint : given a fixpoint and a bindings ,
* returns the corresponding fixpoint body , and the bindings in which
* it should be evaluated : its first variables are the fixpoint bodies
* ( S , ( fix Fi { F0 : = T0 .. Fn-1 : = Tn-1 } ) )
* - > ( S. [ S]F0 . [ S]F1 ... . [ S]Fn-1 , Ti )
* returns the corresponding fixpoint body, and the bindings in which
* it should be evaluated: its first variables are the fixpoint bodies
* (S, (fix Fi {F0 := T0 .. Fn-1 := Tn-1}))
* -> (S. [S]F0 . [S]F1 ... . [S]Fn-1, Ti)
*)
let contract_fixp env ((reci,i),(_,_,bds as bodies)) =
let make_body j = FIXP(((reci,j),bodies), env, [||]) in
let n = Array.length bds in
subs_cons(Array.init n make_body, env), bds.(i)
let contract_cofixp env (i,(_,_,bds as bodies)) =
let make_body j = COFIXP((j,bodies), env, [||]) in
let n = Array.length bds in
subs_cons(Array.init n make_body, env), bds.(i)
let make_constr_ref n = function
| RelKey p -> mkRel (n+p)
| VarKey id -> mkVar id
| ConstKey cst -> mkConst cst
let stack_app appl stack =
if Array.length appl = 0 then stack else
match stack with
| APP(args,stk) -> APP(Array.append appl args,stk)
| _ -> APP(appl, stack)
let rec stack_concat stk1 stk2 =
match stk1 with
TOP -> stk2
| APP(v,stk1') -> APP(v,stack_concat stk1' stk2)
| CASE(c,b,i,s,stk1') -> CASE(c,b,i,s,stack_concat stk1' stk2)
let mkSTACK = function
v, TOP -> v
| STACK(0,v0,stk0), stk -> STACK(0,v0,stack_concat stk0 stk)
| v,stk -> STACK(0,v,stk)
Change : zeta reduction can not be avoided in CBV
open RedFlags
let red_set_ref flags = function
| RelKey _ -> red_set flags fDELTA
| VarKey id -> red_set flags (fVAR id)
| ConstKey sp -> red_set flags (fCONST sp)
let strip_appl head stack =
match head with
| FIXP (fix,env,app) -> (FIXP(fix,env,[||]), stack_app app stack)
| COFIXP (cofix,env,app) -> (COFIXP(cofix,env,[||]), stack_app app stack)
| CONSTR (c,app) -> (CONSTR(c,[||]), stack_app app stack)
| _ -> (head, stack)
let fixp_reducible flgs ((reci,i),_) stk =
if red_set flgs fIOTA then
match stk with
| APP(appl,_) ->
Array.length appl > reci.(i) &&
(match appl.(reci.(i)) with
CONSTR _ -> true
| _ -> false)
| _ -> false
else
false
let cofixp_reducible flgs _ stk =
if red_set flgs fIOTA then
match stk with
| (CASE _ | APP(_,CASE _)) -> true
| _ -> false
else
false
The main recursive functions
*
* Go under applications and cases ( pushed in the stack ) , expand head
* constants or substitued , and try to make appear a
* constructor , a lambda or a fixp in the head . If not , it is a value
* and is completely computed here . The head redexes are NOT reduced :
* the function returns the pair of a cbv_value and its stack . *
* Invariant : if the result of is CONSTR or ( CO)FIXP , it last
* argument is [ ] . Because we must put all the applied terms in the
* stack .
*
* Go under applications and cases (pushed in the stack), expand head
* constants or substitued de Bruijn, and try to make appear a
* constructor, a lambda or a fixp in the head. If not, it is a value
* and is completely computed here. The head redexes are NOT reduced:
* the function returns the pair of a cbv_value and its stack. *
* Invariant: if the result of norm_head is CONSTR or (CO)FIXP, it last
* argument is []. Because we must put all the applied terms in the
* stack. *)
let rec norm_head info env t stack =
match kind_of_term t with
Applied terms are normalized immediately ;
they could be computed when getting out of the stack
they could be computed when getting out of the stack *)
let nargs = Array.map (cbv_stack_term info TOP env) args in
norm_head info env head (stack_app nargs stack)
| Case (ci,p,c,v) -> norm_head info env c (CASE(p,v,ci,env,stack))
| Cast (ct,_,_) -> norm_head info env ct stack
constants , axioms
* the first pattern is CRUCIAL , n=0 happens very often :
* when reducing closed terms , n is always 0
* the first pattern is CRUCIAL, n=0 happens very often:
* when reducing closed terms, n is always 0 *)
| Rel i ->
(match expand_rel i env with
| Inl (0,v) -> strip_appl v stack
| Inl (n,v) -> strip_appl (shift_value n v) stack
| Inr (n,None) -> (VAL(0, mkRel n), stack)
| Inr (n,Some p) -> norm_head_ref (n-p) info env stack (RelKey p))
| Var id -> norm_head_ref 0 info env stack (VarKey id)
| Const sp -> norm_head_ref 0 info env stack (ConstKey sp)
| LetIn (_, b, _, c) ->
if red_set (info_flags info) fZETA then
New rule : for Cbv , Delta does not apply to locally bound variables
or red_set ( info_flags info ) fDELTA
or red_set (info_flags info) fDELTA
*)
let env' = subs_cons ([|cbv_stack_term info TOP env b|],env) in
norm_head info env' c stack
else
une coupure commutative ?
| Evar ev ->
(match evar_value info ev with
Some c -> norm_head info env c stack
| None -> (VAL(0, t), stack))
| Lambda _ ->
let ctxt,b = decompose_lam t in
(LAM(List.length ctxt, List.rev ctxt,b,env), stack)
| Fix fix -> (FIXP(fix,env,[||]), stack)
| CoFix cofix -> (COFIXP(cofix,env,[||]), stack)
| Construct c -> (CONSTR(c, [||]), stack)
| (Sort _ | Meta _ | Ind _) -> (VAL(0, t), stack)
| Prod _ -> (CBN(t,env), stack)
and norm_head_ref k info env stack normt =
if red_set_ref (info_flags info) normt then
match ref_value_cache info normt with
| Some body -> strip_appl (shift_value k body) stack
| None -> (VAL(0,make_constr_ref k normt),stack)
else (VAL(0,make_constr_ref k normt),stack)
cbv_stack_term performs weak reduction on constr t under the subs
* env , with context stack , i.e. ( [ env]t stack ) . First computes weak
* head normal form of t and checks if a redex appears with the stack .
* If so , recursive call to reach the real head normal form . If not ,
* we build a value .
* env, with context stack, i.e. ([env]t stack). First computes weak
* head normal form of t and checks if a redex appears with the stack.
* If so, recursive call to reach the real head normal form. If not,
* we build a value.
*)
and cbv_stack_term info stack env t =
match norm_head info env t stack with
| (LAM (nlams,ctxt,b,env), APP (args, stk))
when red_set (info_flags info) fBETA ->
let nargs = Array.length args in
if nargs == nlams then
cbv_stack_term info stk (subs_cons(args,env)) b
else if nlams < nargs then
let env' = subs_cons(Array.sub args 0 nlams, env) in
let eargs = Array.sub args nlams (nargs-nlams) in
cbv_stack_term info (APP(eargs,stk)) env' b
else
let ctxt' = list_skipn nargs ctxt in
LAM(nlams-nargs,ctxt', b, subs_cons(args,env))
a Fix applied enough - > IOTA
| (FIXP(fix,env,[||]), stk)
when fixp_reducible (info_flags info) fix stk ->
let (envf,redfix) = contract_fixp env fix in
cbv_stack_term info stk envf redfix
constructor guard satisfied or Cofix in a Case - > IOTA
| (COFIXP(cofix,env,[||]), stk)
when cofixp_reducible (info_flags info) cofix stk->
let (envf,redfix) = contract_cofixp env cofix in
cbv_stack_term info stk envf redfix
constructor in a Case - > IOTA
| (CONSTR((sp,n),[||]), APP(args,CASE(_,br,ci,env,stk)))
when red_set (info_flags info) fIOTA ->
let cargs =
Array.sub args ci.ci_npar (Array.length args - ci.ci_npar) in
cbv_stack_term info (stack_app cargs stk) env br.(n-1)
constructor of arity 0 in a Case - > IOTA
| (CONSTR((_,n),[||]), CASE(_,br,_,env,stk))
when red_set (info_flags info) fIOTA ->
cbv_stack_term info stk env br.(n-1)
| (FIXP(fix,env,[||]), APP(appl,TOP)) -> FIXP(fix,env,appl)
| (COFIXP(cofix,env,[||]), APP(appl,TOP)) -> COFIXP(cofix,env,appl)
| (CONSTR(c,[||]), APP(appl,TOP)) -> CONSTR(c,appl)
| (head,stk) -> mkSTACK(head, stk)
let rec apply_stack info t = function
| TOP -> t
| APP (args,st) ->
apply_stack info (mkApp(t,Array.map (cbv_norm_value info) args)) st
| CASE (ty,br,ci,env,st) ->
apply_stack info
(mkCase (ci, cbv_norm_term info env ty, t,
Array.map (cbv_norm_term info env) br))
st
and cbv_norm_term info env t =
cbv_norm_value info (cbv_stack_term info TOP env t)
| VAL (n,t) -> lift n t
| STACK (0,v,stk) ->
apply_stack info (cbv_norm_value info v) stk
| STACK (n,v,stk) ->
lift n (apply_stack info (cbv_norm_value info v) stk)
| CBN(t,env) ->
map_constr_with_binders subs_lift (cbv_norm_term info) env t
| LAM (n,ctxt,b,env) ->
let nctxt =
list_map_i (fun i (x,ty) ->
(x,cbv_norm_term info (subs_liftn i env) ty)) 0 ctxt in
compose_lam (List.rev nctxt) (cbv_norm_term info (subs_liftn n env) b)
| FIXP ((lij,(names,lty,bds)),env,args) ->
mkApp
(mkFix (lij,
(names,
Array.map (cbv_norm_term info env) lty,
Array.map (cbv_norm_term info
(subs_liftn (Array.length lty) env)) bds)),
Array.map (cbv_norm_value info) args)
| COFIXP ((j,(names,lty,bds)),env,args) ->
mkApp
(mkCoFix (j,
(names,Array.map (cbv_norm_term info env) lty,
Array.map (cbv_norm_term info
(subs_liftn (Array.length lty) env)) bds)),
Array.map (cbv_norm_value info) args)
| CONSTR (c,args) ->
mkApp(mkConstruct c, Array.map (cbv_norm_value info) args)
let cbv_norm infos constr =
with_stats (lazy (cbv_norm_term infos (subs_id 0) constr))
type cbv_infos = cbv_value infos
constant bodies are normalized at the first expansion
let create_cbv_infos flgs env sigma =
create
(fun old_info c -> cbv_stack_term old_info TOP (subs_id 0) c)
flgs
env
(Reductionops.safe_evar_value sigma)
|
bdcddf7e6c2770b835e1c08f432919846605cb6b1bdfe4c8b25b542c598a2208 | mangpo/greenthumb | simulator-rosette.rkt | #lang s-exp rosette
(require "simulator.rkt")
(provide simulator-rosette%)
(define simulator-rosette%
(class simulator%
(super-new)))
| null | https://raw.githubusercontent.com/mangpo/greenthumb/7a8626205879af8c788f9927eeff643f4ddc5cde/simulator-rosette.rkt | racket | #lang s-exp rosette
(require "simulator.rkt")
(provide simulator-rosette%)
(define simulator-rosette%
(class simulator%
(super-new)))
|
|
47f20ef4df410a74c33ea05d5e02b6e2223fe3b477c3fb4dda134382124c4d58 | WhatsApp/eqwalizer | as_pat.erl | Copyright ( c ) Meta Platforms , Inc. and affiliates . All rights reserved .
%%%
This source code is licensed under the Apache 2.0 license found in
%%% the LICENSE file in the root directory of this source tree.
-module(as_pat).
-compile([export_all, nowarn_export_all]).
-record(box_a, {a :: atom()}).
-record(box_b, {b :: binary()}).
-record(box_n, {n :: number()}).
-type abn() :: atom() | binary() | number().
-type box() :: #box_a{}
| #box_b{}
| #box_n{}.
-spec box_a(atom()) -> #box_a{}.
box_a(A) -> #box_a{a = A}.
-spec unbox_a(#box_a{}) -> atom().
unbox_a(#box_a{a = A}) -> A.
-spec box_n(number()) -> #box_n{}.
box_n(N) -> #box_n{n = N}.
-spec unbox_n(#box_n{}) -> number().
unbox_n(#box_n{n = N}) -> N.
-spec box_b(binary()) -> #box_b{}.
box_b(B) -> #box_b{b = B}.
-spec unbox_b(#box_b{}) -> binary().
unbox_b({b, B}) -> B.
-spec unbox(box()) -> abn().
unbox(#box_a{a = A}) -> A;
unbox(#box_b{b = B}) -> B;
unbox(#box_n{n = N}) -> N.
-spec unboxL(box()) -> abn().
unboxL(BA = #box_a{}) -> unbox_a(BA);
unboxL(BB = #box_b{}) -> unbox_b(BB);
unboxL(BN = #box_n{}) -> unbox_n(BN).
-spec unboxL_neg(box()) -> abn().
unboxL_neg(BA = #box_a{}) -> unbox_a(BA);
unboxL_neg(BB = #box_b{}) -> unbox_b(BB);
unboxL_neg(BN = #box_n{}) -> unbox_a(BN).
-spec unboxR(box()) -> abn().
unboxR(#box_a{} = BA) -> unbox_a(BA);
unboxR(#box_b{} = BB) -> unbox_b(BB);
unboxR(#box_n{} = BN) -> unbox_n(BN).
-spec unboxR_neg(box()) -> abn().
unboxR_neg(#box_a{} = BA) -> unbox_a(BA);
unboxR_neg(#box_b{} = BB) -> unbox_b(BB);
unboxR_neg(#box_n{} = BN) -> unbox_b(BN).
| null | https://raw.githubusercontent.com/WhatsApp/eqwalizer/9935940d71ef65c7bf7a9dfad77d89c0006c288e/eqwalizer/test_projects/check/src/as_pat.erl | erlang |
the LICENSE file in the root directory of this source tree. | Copyright ( c ) Meta Platforms , Inc. and affiliates . All rights reserved .
This source code is licensed under the Apache 2.0 license found in
-module(as_pat).
-compile([export_all, nowarn_export_all]).
-record(box_a, {a :: atom()}).
-record(box_b, {b :: binary()}).
-record(box_n, {n :: number()}).
-type abn() :: atom() | binary() | number().
-type box() :: #box_a{}
| #box_b{}
| #box_n{}.
-spec box_a(atom()) -> #box_a{}.
box_a(A) -> #box_a{a = A}.
-spec unbox_a(#box_a{}) -> atom().
unbox_a(#box_a{a = A}) -> A.
-spec box_n(number()) -> #box_n{}.
box_n(N) -> #box_n{n = N}.
-spec unbox_n(#box_n{}) -> number().
unbox_n(#box_n{n = N}) -> N.
-spec box_b(binary()) -> #box_b{}.
box_b(B) -> #box_b{b = B}.
-spec unbox_b(#box_b{}) -> binary().
unbox_b({b, B}) -> B.
-spec unbox(box()) -> abn().
unbox(#box_a{a = A}) -> A;
unbox(#box_b{b = B}) -> B;
unbox(#box_n{n = N}) -> N.
-spec unboxL(box()) -> abn().
unboxL(BA = #box_a{}) -> unbox_a(BA);
unboxL(BB = #box_b{}) -> unbox_b(BB);
unboxL(BN = #box_n{}) -> unbox_n(BN).
-spec unboxL_neg(box()) -> abn().
unboxL_neg(BA = #box_a{}) -> unbox_a(BA);
unboxL_neg(BB = #box_b{}) -> unbox_b(BB);
unboxL_neg(BN = #box_n{}) -> unbox_a(BN).
-spec unboxR(box()) -> abn().
unboxR(#box_a{} = BA) -> unbox_a(BA);
unboxR(#box_b{} = BB) -> unbox_b(BB);
unboxR(#box_n{} = BN) -> unbox_n(BN).
-spec unboxR_neg(box()) -> abn().
unboxR_neg(#box_a{} = BA) -> unbox_a(BA);
unboxR_neg(#box_b{} = BB) -> unbox_b(BB);
unboxR_neg(#box_n{} = BN) -> unbox_b(BN).
|
1d87016fe9a848083a646015bc7bb7f372f073eac1e156ca341b2d9a49b38578 | ocaml-flambda/flambda-backend | flambda_kind.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, OCamlPro
and ,
(* *)
(* Copyright 2017--2019 OCamlPro SAS *)
Copyright 2017 - -2019 Jane Street Group LLC
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
* Kinds and subkinds of Flambda types .
module Naked_number_kind : sig
type t =
| Naked_immediate
| Naked_float
| Naked_int32
| Naked_int64
| Naked_nativeint
val print : Format.formatter -> t -> unit
end
(** The kinds themselves. *)
type t = private
| Value (** OCaml values, either immediates or pointers. *)
| Naked_number of Naked_number_kind.t
(** The kind of unboxed numbers and untagged immediates. *)
| Region
* Values which have been introduced by Flambda and are never accessible
at the source language level ( for example sets of closures ) .
at the source language level (for example sets of closures). *)
| Rec_info
(** Recursion depths of identifiers. Like [Region], not accessible at the
source level, but also not accessible at run time. *)
type kind = t
(** Constructors for the various kinds. *)
val value : t
val naked_number : Naked_number_kind.t -> t
val naked_immediate : t
val naked_float : t
val naked_int32 : t
val naked_int64 : t
val naked_nativeint : t
val region : t
val rec_info : t
val is_value : t -> bool
val is_naked_float : t -> bool
include Container_types.S with type t := t
module Standard_int : sig
* " Standard " because these correspond to the usual representations of tagged
immediates , 32 - bit , 64 - bit and native integers as expected by the
operations in [ Flambda_primitive ] .
immediates, 32-bit, 64-bit and native integers as expected by the
operations in [Flambda_primitive]. *)
type t =
| Tagged_immediate
| Naked_immediate
| Naked_int32
| Naked_int64
| Naked_nativeint
val to_kind : t -> kind
val print_lowercase : Format.formatter -> t -> unit
include Container_types.S with type t := t
end
module Standard_int_or_float : sig
(** The same as [Standard_int], but also permitting naked floats. *)
type t =
| Tagged_immediate
| Naked_immediate
| Naked_float
| Naked_int32
| Naked_int64
| Naked_nativeint
val to_kind : t -> kind
val print_lowercase : Format.formatter -> t -> unit
include Container_types.S with type t := t
end
module Boxable_number : sig
(** These kinds are those of the numbers for which a tailored boxed
representation exists. *)
type t =
| Naked_float
| Naked_int32
| Naked_int64
| Naked_nativeint
val unboxed_kind : t -> kind
val primitive_kind : t -> Primitive.boxed_integer
val print_lowercase : Format.formatter -> t -> unit
val print_lowercase_short : Format.formatter -> t -> unit
include Container_types.S with type t := t
end
module With_subkind : sig
module Subkind : sig
type t =
| Anything
| Boxed_float
| Boxed_int32
| Boxed_int64
| Boxed_nativeint
| Tagged_immediate
| Variant of
{ consts : Targetint_31_63.Set.t;
non_consts : t list Tag.Scannable.Map.t
}
| Float_block of { num_fields : int }
| Float_array
| Immediate_array
| Value_array
| Generic_array
include Container_types.S with type t := t
end
type kind = t
type t
val create : kind -> Subkind.t -> t
val kind : t -> kind
val subkind : t -> Subkind.t
val has_useful_subkind_info : t -> bool
val any_value : t
val naked_immediate : t
val naked_float : t
val naked_int32 : t
val naked_int64 : t
val naked_nativeint : t
val region : t
val boxed_float : t
val boxed_int32 : t
val boxed_int64 : t
val boxed_nativeint : t
val tagged_immediate : t
val rec_info : t
val float_array : t
val immediate_array : t
val value_array : t
val generic_array : t
val block : Tag.t -> t list -> t
val float_block : num_fields:int -> t
val of_naked_number_kind : Naked_number_kind.t -> t
val from_lambda_value_kind : Lambda.value_kind -> t
val from_lambda : Lambda.layout -> t
val compatible : t -> when_used_at:t -> bool
val erase_subkind : t -> t
include Container_types.S with type t := t
end
| null | https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/23c793d6e94fa6ec43a61783df7cbfd50239536b/middle_end/flambda2/kinds/flambda_kind.mli | ocaml | ************************************************************************
OCaml
Copyright 2017--2019 OCamlPro SAS
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* The kinds themselves.
* OCaml values, either immediates or pointers.
* The kind of unboxed numbers and untagged immediates.
* Recursion depths of identifiers. Like [Region], not accessible at the
source level, but also not accessible at run time.
* Constructors for the various kinds.
* The same as [Standard_int], but also permitting naked floats.
* These kinds are those of the numbers for which a tailored boxed
representation exists. | , OCamlPro
and ,
Copyright 2017 - -2019 Jane Street Group LLC
the GNU Lesser General Public License version 2.1 , with the
* Kinds and subkinds of Flambda types .
module Naked_number_kind : sig
type t =
| Naked_immediate
| Naked_float
| Naked_int32
| Naked_int64
| Naked_nativeint
val print : Format.formatter -> t -> unit
end
type t = private
| Naked_number of Naked_number_kind.t
| Region
* Values which have been introduced by Flambda and are never accessible
at the source language level ( for example sets of closures ) .
at the source language level (for example sets of closures). *)
| Rec_info
type kind = t
val value : t
val naked_number : Naked_number_kind.t -> t
val naked_immediate : t
val naked_float : t
val naked_int32 : t
val naked_int64 : t
val naked_nativeint : t
val region : t
val rec_info : t
val is_value : t -> bool
val is_naked_float : t -> bool
include Container_types.S with type t := t
module Standard_int : sig
* " Standard " because these correspond to the usual representations of tagged
immediates , 32 - bit , 64 - bit and native integers as expected by the
operations in [ Flambda_primitive ] .
immediates, 32-bit, 64-bit and native integers as expected by the
operations in [Flambda_primitive]. *)
type t =
| Tagged_immediate
| Naked_immediate
| Naked_int32
| Naked_int64
| Naked_nativeint
val to_kind : t -> kind
val print_lowercase : Format.formatter -> t -> unit
include Container_types.S with type t := t
end
module Standard_int_or_float : sig
type t =
| Tagged_immediate
| Naked_immediate
| Naked_float
| Naked_int32
| Naked_int64
| Naked_nativeint
val to_kind : t -> kind
val print_lowercase : Format.formatter -> t -> unit
include Container_types.S with type t := t
end
module Boxable_number : sig
type t =
| Naked_float
| Naked_int32
| Naked_int64
| Naked_nativeint
val unboxed_kind : t -> kind
val primitive_kind : t -> Primitive.boxed_integer
val print_lowercase : Format.formatter -> t -> unit
val print_lowercase_short : Format.formatter -> t -> unit
include Container_types.S with type t := t
end
module With_subkind : sig
module Subkind : sig
type t =
| Anything
| Boxed_float
| Boxed_int32
| Boxed_int64
| Boxed_nativeint
| Tagged_immediate
| Variant of
{ consts : Targetint_31_63.Set.t;
non_consts : t list Tag.Scannable.Map.t
}
| Float_block of { num_fields : int }
| Float_array
| Immediate_array
| Value_array
| Generic_array
include Container_types.S with type t := t
end
type kind = t
type t
val create : kind -> Subkind.t -> t
val kind : t -> kind
val subkind : t -> Subkind.t
val has_useful_subkind_info : t -> bool
val any_value : t
val naked_immediate : t
val naked_float : t
val naked_int32 : t
val naked_int64 : t
val naked_nativeint : t
val region : t
val boxed_float : t
val boxed_int32 : t
val boxed_int64 : t
val boxed_nativeint : t
val tagged_immediate : t
val rec_info : t
val float_array : t
val immediate_array : t
val value_array : t
val generic_array : t
val block : Tag.t -> t list -> t
val float_block : num_fields:int -> t
val of_naked_number_kind : Naked_number_kind.t -> t
val from_lambda_value_kind : Lambda.value_kind -> t
val from_lambda : Lambda.layout -> t
val compatible : t -> when_used_at:t -> bool
val erase_subkind : t -> t
include Container_types.S with type t := t
end
|
e327050d15fc7de1dc73b716daa160019f698a7856a663a2b7ed4c156dd6f456 | storm-framework/storm | Updates.hs | {-# LANGUAGE GADTs #-}
{-@ LIQUID "--no-pattern-inline" @-}
module Storm.Updates
( assign
, updateWhere
, combine
)
where
import Control.Monad.Reader
import Database.Persist ( PersistRecordBackend
, PersistField
)
import qualified Database.Persist as Persist
import Storm.Core
import Storm.Filters
import Storm.Infrastructure
{-@
data Update user record < visibility :: Entity record -> user -> Bool
, update :: Entity record -> Bool
, capabilities :: Entity record -> Bool
, policy :: Entity record -> Entity record -> user -> Bool
> = Update _ @-}
data Update user record = Update [Persist.Update record]
{-@ data variance Update invariant invariant invariant invariant invariant invariant @-}
-- For some reason the type is not exported if we use `=.`
{-@ ignore assign @-}
@
assume assign : : forall < policy : : Entity record - > user - > Bool
, selector : : Entity record - > typ - > Bool
, flippedselector : : typ - > Entity record - > Bool
, r : : typ - > Bool
, update : : Entity record - > Bool
, : : typ - > Bool
, updatepolicy : : Entity record - > Entity record - > user - > Bool
, capability : : Entity record - > Bool
> .
{ row : : ( Entity record )
, value : : < r >
, field : : > ) | field = = value }
|- { v:(Entity < flippedselector field > record ) | True } < : { v:(Entity < update > record ) | True }
}
EntityFieldWrapper < policy , selector , flippedselector , capability , updatepolicy > user record typ < r >
- > Update < policy , update , capability , updatepolicy > user record
@
assume assign :: forall < policy :: Entity record -> user -> Bool
, selector :: Entity record -> typ -> Bool
, flippedselector :: typ -> Entity record -> Bool
, r :: typ -> Bool
, update :: Entity record -> Bool
, fieldref :: typ -> Bool
, updatepolicy :: Entity record -> Entity record -> user -> Bool
, capability :: Entity record -> Bool
>.
{ row :: (Entity record)
, value :: typ<r>
, field :: {field:(typ<selector row>) | field == value}
|- {v:(Entity <flippedselector field> record) | True} <: {v:(Entity <update> record) | True}
}
EntityFieldWrapper<policy, selector, flippedselector, capability, updatepolicy> user record typ
-> typ<r>
-> Update<policy, update, capability, updatepolicy> user record
@-}
assign :: PersistField typ => EntityFieldWrapper user record typ -> typ -> Update user record
assign (EntityFieldWrapper field) val = Update [field Persist.=. val]
-- TODO: It's probably important to make sure multiple updates to the same field don't happen at once
{-@ ignore combine @-}
@
assume combine : : forall < : : Entity record - > user - > Bool
, : : Entity record - > user - > Bool
, visibility : : Entity record - > user - > Bool
, update1 : : Entity record - > Bool
, : : Entity record - > Bool
, update : : Entity record - > Bool
, cap1 : : Entity record - > Bool
, cap2 : : Entity record - > Bool
, cap : : Entity record - > Bool
, : : Entity record - > Entity record - > user - > Bool
, : : Entity record - > Entity record - > user - > Bool
, policy : : Entity record - > Entity record - > user - > Bool
> .
{ row : : ( Entity < update > record )
|- { v:(user < row > ) | True } < : { v:(user < visibility row > ) | True }
}
{ row : : ( Entity < update > record )
|- { v:(user < row > ) | True } < : { v:(user < visibility row > ) | True }
}
{ { v : ( Entity < update > record ) | True } < : { v : ( Entity < update1 > record ) | True } }
{ { v : ( Entity < update > record ) | True } < : { v : ( Entity < update2 > record ) | True } }
{ row1 : : ( Entity < update1 > record )
, row2 : : ( Entity < update2 > record )
|- { v:(Entity record ) | v = = row1 & & v = = row2 } < : { v:(Entity < update > record ) | True }
}
{ { v : ( Entity < cap > record ) | True } < : { v : ( Entity < cap1 > record ) | True } }
{ { v : ( Entity < cap > record ) | True } < : { v : ( Entity < cap2 > record ) | True } }
{ row1 : : ( Entity < cap1 > record )
, row2 : : ( Entity < cap2 > record )
|- { v:(Entity record ) | v = = row1 & & v = = row2 } < : { v:(Entity < cap > record ) | True }
}
{ old : : Entity record
, new : : Entity record
|- { v : ( user < policy old new > ) | True } < : { v : ( user < policy1 old new > ) | True }
}
{ old : : Entity record , new : : Entity record
|- { v : ( user < policy old new > ) | True } < : { v : ( user < policy2 old new > ) | True }
}
{ old : : Entity record
, new : : Entity record
, user1 : : ( user < policy1 old new > )
, : : ( user < policy2 old new > )
|- { v:(user ) | v = = user1 & & v = = user2 } < : { v:(user < policy old new > ) | True }
}
Update < visibility1 , update1 , cap1 , policy1 > user record
- > Update , update2 , cap2 , policy2 > user record
- > Update < visibility , update , cap , policy > user record
@
assume combine :: forall < visibility1 :: Entity record -> user -> Bool
, visibility2 :: Entity record -> user -> Bool
, visibility :: Entity record -> user -> Bool
, update1 :: Entity record -> Bool
, update2 :: Entity record -> Bool
, update :: Entity record -> Bool
, cap1 :: Entity record -> Bool
, cap2 :: Entity record -> Bool
, cap :: Entity record -> Bool
, policy1 :: Entity record -> Entity record -> user -> Bool
, policy2 :: Entity record -> Entity record -> user -> Bool
, policy :: Entity record -> Entity record -> user -> Bool
>.
{ row :: (Entity<update> record)
|- {v:(user<visibility1 row>) | True} <: {v:(user<visibility row>) | True}
}
{ row :: (Entity<update> record)
|- {v:(user<visibility2 row>) | True} <: {v:(user<visibility row>) | True}
}
{ {v: (Entity<update> record) | True } <: {v: (Entity<update1> record) | True}}
{ {v: (Entity<update> record) | True } <: {v: (Entity<update2> record) | True}}
{ row1 :: (Entity<update1> record)
, row2 :: (Entity<update2> record)
|- {v:(Entity record) | v == row1 && v == row2} <: {v:(Entity<update> record) | True}
}
{ {v: (Entity<cap> record) | True} <: {v: (Entity<cap1> record) | True} }
{ {v: (Entity<cap> record) | True} <: {v: (Entity<cap2> record) | True} }
{ row1 :: (Entity<cap1> record)
, row2 :: (Entity<cap2> record)
|- {v:(Entity record) | v == row1 && v == row2} <: {v:(Entity<cap> record) | True}
}
{ old :: Entity record
, new :: Entity record
|- {v: (user<policy old new>) | True } <: {v: (user<policy1 old new>) | True}
}
{ old :: Entity record , new :: Entity record
|- {v: (user<policy old new>) | True } <: {v: (user<policy2 old new>) | True}
}
{ old :: Entity record
, new :: Entity record
, user1 :: (user<policy1 old new>)
, user2 :: (user<policy2 old new>)
|- {v:(user) | v == user1 && v == user2} <: {v:(user<policy old new>) | True}
}
Update<visibility1, update1, cap1, policy1> user record
-> Update<visibility2, update2, cap2, policy2> user record
-> Update<visibility, update, cap, policy> user record
@-}
combine :: Update user record -> Update user record -> Update user record
combine (Update us1) (Update us2) = Update (us1 ++ us2)
-- TODO: Figure out what to do with the key
{-@ ignore updateWhere @-}
@
assume updateWhere : : forall < visibility : : Entity record - > user - > Bool
, update : : Entity record - > Bool
, audience : : user - > Bool
, capabilities : : Entity record - > Bool
, updatepolicy : : Entity record - > Entity record - > user - > Bool
, querypolicy : : Entity record - > user - > Bool
, filter : : Entity record - > Bool
, level : : user - > Bool
> .
{ old : : ( Entity < filter > record )
, new : : ( Entity < update > record )
, user : : { v : ( user < updatepolicy old new > ) | v = = currentUser 0 }
|- { v:(Entity record ) | v = = old } < : { v:(Entity < capabilities > record ) | True }
}
{ old : : ( Entity < filter > record )
, new : : { v : ( Entity < update > record ) | entityKey old = = entityKey v }
|- { v:(user < visibility new > ) | True } < : { v:(user < audience > ) | True }
}
{ row : : ( Entity < filter > record )
|- { v:(user < level > ) | True } < : { v:(user < querypolicy row > ) | True }
}
Filter < querypolicy , filter > user record
- > Update < visibility , update , capabilities , updatepolicy > user record
- > TaggedT < level , audience > user m ( )
@
assume updateWhere :: forall < visibility :: Entity record -> user -> Bool
, update :: Entity record -> Bool
, audience :: user -> Bool
, capabilities :: Entity record -> Bool
, updatepolicy :: Entity record -> Entity record -> user -> Bool
, querypolicy :: Entity record -> user -> Bool
, filter :: Entity record -> Bool
, level :: user -> Bool
>.
{ old :: (Entity<filter> record)
, new :: (Entity<update> record)
, user :: {v: (user<updatepolicy old new>) | v == currentUser 0}
|- {v:(Entity record) | v == old} <: {v:(Entity<capabilities> record) | True}
}
{ old :: (Entity<filter> record)
, new :: {v: (Entity<update> record) | entityKey old == entityKey v}
|- {v:(user<visibility new>) | True} <: {v:(user<audience>) | True}
}
{ row :: (Entity<filter> record)
|- {v:(user<level>) | True} <: {v:(user<querypolicy row>) | True}
}
Filter<querypolicy, filter> user record
-> Update<visibility, update, capabilities, updatepolicy> user record
-> TaggedT<level, audience> user m ()
@-}
updateWhere
:: ( MonadTIO m
, Persist.PersistQueryWrite backend
, Persist.PersistRecordBackend record backend
, MonadReader backend m
)
=> Filter user record
-> Update user record
-> TaggedT user m ()
updateWhere (Filter filters) (Update up) = do
backend <- ask
liftTIO (TIO $ runReaderT (Persist.updateWhere filters up) backend)
| null | https://raw.githubusercontent.com/storm-framework/storm/f746ff1bf4876ac55618224b41a1271db291608a/src/Storm/Updates.hs | haskell | # LANGUAGE GADTs #
@ LIQUID "--no-pattern-inline" @
@
data Update user record < visibility :: Entity record -> user -> Bool
, update :: Entity record -> Bool
, capabilities :: Entity record -> Bool
, policy :: Entity record -> Entity record -> user -> Bool
> = Update _ @
@ data variance Update invariant invariant invariant invariant invariant invariant @
For some reason the type is not exported if we use `=.`
@ ignore assign @
TODO: It's probably important to make sure multiple updates to the same field don't happen at once
@ ignore combine @
TODO: Figure out what to do with the key
@ ignore updateWhere @ |
module Storm.Updates
( assign
, updateWhere
, combine
)
where
import Control.Monad.Reader
import Database.Persist ( PersistRecordBackend
, PersistField
)
import qualified Database.Persist as Persist
import Storm.Core
import Storm.Filters
import Storm.Infrastructure
data Update user record = Update [Persist.Update record]
@
assume assign : : forall < policy : : Entity record - > user - > Bool
, selector : : Entity record - > typ - > Bool
, flippedselector : : typ - > Entity record - > Bool
, r : : typ - > Bool
, update : : Entity record - > Bool
, : : typ - > Bool
, updatepolicy : : Entity record - > Entity record - > user - > Bool
, capability : : Entity record - > Bool
> .
{ row : : ( Entity record )
, value : : < r >
, field : : > ) | field = = value }
|- { v:(Entity < flippedselector field > record ) | True } < : { v:(Entity < update > record ) | True }
}
EntityFieldWrapper < policy , selector , flippedselector , capability , updatepolicy > user record typ < r >
- > Update < policy , update , capability , updatepolicy > user record
@
assume assign :: forall < policy :: Entity record -> user -> Bool
, selector :: Entity record -> typ -> Bool
, flippedselector :: typ -> Entity record -> Bool
, r :: typ -> Bool
, update :: Entity record -> Bool
, fieldref :: typ -> Bool
, updatepolicy :: Entity record -> Entity record -> user -> Bool
, capability :: Entity record -> Bool
>.
{ row :: (Entity record)
, value :: typ<r>
, field :: {field:(typ<selector row>) | field == value}
|- {v:(Entity <flippedselector field> record) | True} <: {v:(Entity <update> record) | True}
}
EntityFieldWrapper<policy, selector, flippedselector, capability, updatepolicy> user record typ
-> typ<r>
-> Update<policy, update, capability, updatepolicy> user record
@-}
assign :: PersistField typ => EntityFieldWrapper user record typ -> typ -> Update user record
assign (EntityFieldWrapper field) val = Update [field Persist.=. val]
@
assume combine : : forall < : : Entity record - > user - > Bool
, : : Entity record - > user - > Bool
, visibility : : Entity record - > user - > Bool
, update1 : : Entity record - > Bool
, : : Entity record - > Bool
, update : : Entity record - > Bool
, cap1 : : Entity record - > Bool
, cap2 : : Entity record - > Bool
, cap : : Entity record - > Bool
, : : Entity record - > Entity record - > user - > Bool
, : : Entity record - > Entity record - > user - > Bool
, policy : : Entity record - > Entity record - > user - > Bool
> .
{ row : : ( Entity < update > record )
|- { v:(user < row > ) | True } < : { v:(user < visibility row > ) | True }
}
{ row : : ( Entity < update > record )
|- { v:(user < row > ) | True } < : { v:(user < visibility row > ) | True }
}
{ { v : ( Entity < update > record ) | True } < : { v : ( Entity < update1 > record ) | True } }
{ { v : ( Entity < update > record ) | True } < : { v : ( Entity < update2 > record ) | True } }
{ row1 : : ( Entity < update1 > record )
, row2 : : ( Entity < update2 > record )
|- { v:(Entity record ) | v = = row1 & & v = = row2 } < : { v:(Entity < update > record ) | True }
}
{ { v : ( Entity < cap > record ) | True } < : { v : ( Entity < cap1 > record ) | True } }
{ { v : ( Entity < cap > record ) | True } < : { v : ( Entity < cap2 > record ) | True } }
{ row1 : : ( Entity < cap1 > record )
, row2 : : ( Entity < cap2 > record )
|- { v:(Entity record ) | v = = row1 & & v = = row2 } < : { v:(Entity < cap > record ) | True }
}
{ old : : Entity record
, new : : Entity record
|- { v : ( user < policy old new > ) | True } < : { v : ( user < policy1 old new > ) | True }
}
{ old : : Entity record , new : : Entity record
|- { v : ( user < policy old new > ) | True } < : { v : ( user < policy2 old new > ) | True }
}
{ old : : Entity record
, new : : Entity record
, user1 : : ( user < policy1 old new > )
, : : ( user < policy2 old new > )
|- { v:(user ) | v = = user1 & & v = = user2 } < : { v:(user < policy old new > ) | True }
}
Update < visibility1 , update1 , cap1 , policy1 > user record
- > Update , update2 , cap2 , policy2 > user record
- > Update < visibility , update , cap , policy > user record
@
assume combine :: forall < visibility1 :: Entity record -> user -> Bool
, visibility2 :: Entity record -> user -> Bool
, visibility :: Entity record -> user -> Bool
, update1 :: Entity record -> Bool
, update2 :: Entity record -> Bool
, update :: Entity record -> Bool
, cap1 :: Entity record -> Bool
, cap2 :: Entity record -> Bool
, cap :: Entity record -> Bool
, policy1 :: Entity record -> Entity record -> user -> Bool
, policy2 :: Entity record -> Entity record -> user -> Bool
, policy :: Entity record -> Entity record -> user -> Bool
>.
{ row :: (Entity<update> record)
|- {v:(user<visibility1 row>) | True} <: {v:(user<visibility row>) | True}
}
{ row :: (Entity<update> record)
|- {v:(user<visibility2 row>) | True} <: {v:(user<visibility row>) | True}
}
{ {v: (Entity<update> record) | True } <: {v: (Entity<update1> record) | True}}
{ {v: (Entity<update> record) | True } <: {v: (Entity<update2> record) | True}}
{ row1 :: (Entity<update1> record)
, row2 :: (Entity<update2> record)
|- {v:(Entity record) | v == row1 && v == row2} <: {v:(Entity<update> record) | True}
}
{ {v: (Entity<cap> record) | True} <: {v: (Entity<cap1> record) | True} }
{ {v: (Entity<cap> record) | True} <: {v: (Entity<cap2> record) | True} }
{ row1 :: (Entity<cap1> record)
, row2 :: (Entity<cap2> record)
|- {v:(Entity record) | v == row1 && v == row2} <: {v:(Entity<cap> record) | True}
}
{ old :: Entity record
, new :: Entity record
|- {v: (user<policy old new>) | True } <: {v: (user<policy1 old new>) | True}
}
{ old :: Entity record , new :: Entity record
|- {v: (user<policy old new>) | True } <: {v: (user<policy2 old new>) | True}
}
{ old :: Entity record
, new :: Entity record
, user1 :: (user<policy1 old new>)
, user2 :: (user<policy2 old new>)
|- {v:(user) | v == user1 && v == user2} <: {v:(user<policy old new>) | True}
}
Update<visibility1, update1, cap1, policy1> user record
-> Update<visibility2, update2, cap2, policy2> user record
-> Update<visibility, update, cap, policy> user record
@-}
combine :: Update user record -> Update user record -> Update user record
combine (Update us1) (Update us2) = Update (us1 ++ us2)
@
assume updateWhere : : forall < visibility : : Entity record - > user - > Bool
, update : : Entity record - > Bool
, audience : : user - > Bool
, capabilities : : Entity record - > Bool
, updatepolicy : : Entity record - > Entity record - > user - > Bool
, querypolicy : : Entity record - > user - > Bool
, filter : : Entity record - > Bool
, level : : user - > Bool
> .
{ old : : ( Entity < filter > record )
, new : : ( Entity < update > record )
, user : : { v : ( user < updatepolicy old new > ) | v = = currentUser 0 }
|- { v:(Entity record ) | v = = old } < : { v:(Entity < capabilities > record ) | True }
}
{ old : : ( Entity < filter > record )
, new : : { v : ( Entity < update > record ) | entityKey old = = entityKey v }
|- { v:(user < visibility new > ) | True } < : { v:(user < audience > ) | True }
}
{ row : : ( Entity < filter > record )
|- { v:(user < level > ) | True } < : { v:(user < querypolicy row > ) | True }
}
Filter < querypolicy , filter > user record
- > Update < visibility , update , capabilities , updatepolicy > user record
- > TaggedT < level , audience > user m ( )
@
assume updateWhere :: forall < visibility :: Entity record -> user -> Bool
, update :: Entity record -> Bool
, audience :: user -> Bool
, capabilities :: Entity record -> Bool
, updatepolicy :: Entity record -> Entity record -> user -> Bool
, querypolicy :: Entity record -> user -> Bool
, filter :: Entity record -> Bool
, level :: user -> Bool
>.
{ old :: (Entity<filter> record)
, new :: (Entity<update> record)
, user :: {v: (user<updatepolicy old new>) | v == currentUser 0}
|- {v:(Entity record) | v == old} <: {v:(Entity<capabilities> record) | True}
}
{ old :: (Entity<filter> record)
, new :: {v: (Entity<update> record) | entityKey old == entityKey v}
|- {v:(user<visibility new>) | True} <: {v:(user<audience>) | True}
}
{ row :: (Entity<filter> record)
|- {v:(user<level>) | True} <: {v:(user<querypolicy row>) | True}
}
Filter<querypolicy, filter> user record
-> Update<visibility, update, capabilities, updatepolicy> user record
-> TaggedT<level, audience> user m ()
@-}
updateWhere
:: ( MonadTIO m
, Persist.PersistQueryWrite backend
, Persist.PersistRecordBackend record backend
, MonadReader backend m
)
=> Filter user record
-> Update user record
-> TaggedT user m ()
updateWhere (Filter filters) (Update up) = do
backend <- ask
liftTIO (TIO $ runReaderT (Persist.updateWhere filters up) backend)
|
39587cfc7619e6106154754f66e76d20700654d8b53a848420347bff6c5cf7d4 | macchiato-framework/macchiato-core | node_middleware.cljs | (ns macchiato.test.middleware.node-middleware
(:require
[macchiato.middleware.node-middleware :refer [wrap-node-middleware]]
[cljs.test :refer-macros [is deftest testing]]))
(defn fake-node-middleware
"Sets properties in the req and res js objects."
[node-req node-res next]
(aset node-req "user" "john")
(aset node-res "param" "value")
(next))
(defn error-node-middleware
"Calls next with an error."
[node-req node-res next]
(next (js/Error "something went wrong!")))
(defn echo [req res raise] (res req))
(deftest node-middleware-modify-request-response
(let [node-req (js-obj)
node-res (js-obj)
req {:node/request node-req
:node/response node-res}
res identity
error-handler (fn [err] (aset node-res "error" (.-message err)))
wrapped-echo (-> echo (wrap-node-middleware fake-node-middleware))
result (wrapped-echo req res error-handler)]
(is (= nil (aget (:node/response req) "error")))
(is (= "john" (aget (:node/request req) "user")))
(is (= "value" (aget (:node/response req) "param")))
(is (= req result))))
(deftest node-middleware-map-request-properties
(let [node-req (js-obj)
node-res (js-obj)
req {:node/request node-req
:node/response node-res}
res identity
error-handler (fn [err] (aset node-res "error" (.-message err)))
wrapped-echo (-> echo (wrap-node-middleware fake-node-middleware :req-map {:user "user" :other "user"}))
result (wrapped-echo req res error-handler)]
(is (= nil (aget (:node/response req) "error")))
(is (= "john" (:user result)))
(is (= "john" (:other result)))))
(deftest node-middleware-raise-error
(let [node-req (js-obj)
node-res (js-obj)
req {:node/request node-req
:node/response node-res}
res identity
error-handler (fn [err] (aset node-res "error" (.-message err)))
wrapped-echo (-> echo (wrap-node-middleware error-node-middleware))
result (wrapped-echo req res error-handler)]
(is (= "something went wrong!" (aget (:node/response req) "error")))))
| null | https://raw.githubusercontent.com/macchiato-framework/macchiato-core/14eac3dbc561927ee61b6127f30ef0b0269b2af6/test/macchiato/test/middleware/node_middleware.cljs | clojure | (ns macchiato.test.middleware.node-middleware
(:require
[macchiato.middleware.node-middleware :refer [wrap-node-middleware]]
[cljs.test :refer-macros [is deftest testing]]))
(defn fake-node-middleware
"Sets properties in the req and res js objects."
[node-req node-res next]
(aset node-req "user" "john")
(aset node-res "param" "value")
(next))
(defn error-node-middleware
"Calls next with an error."
[node-req node-res next]
(next (js/Error "something went wrong!")))
(defn echo [req res raise] (res req))
(deftest node-middleware-modify-request-response
(let [node-req (js-obj)
node-res (js-obj)
req {:node/request node-req
:node/response node-res}
res identity
error-handler (fn [err] (aset node-res "error" (.-message err)))
wrapped-echo (-> echo (wrap-node-middleware fake-node-middleware))
result (wrapped-echo req res error-handler)]
(is (= nil (aget (:node/response req) "error")))
(is (= "john" (aget (:node/request req) "user")))
(is (= "value" (aget (:node/response req) "param")))
(is (= req result))))
(deftest node-middleware-map-request-properties
(let [node-req (js-obj)
node-res (js-obj)
req {:node/request node-req
:node/response node-res}
res identity
error-handler (fn [err] (aset node-res "error" (.-message err)))
wrapped-echo (-> echo (wrap-node-middleware fake-node-middleware :req-map {:user "user" :other "user"}))
result (wrapped-echo req res error-handler)]
(is (= nil (aget (:node/response req) "error")))
(is (= "john" (:user result)))
(is (= "john" (:other result)))))
(deftest node-middleware-raise-error
(let [node-req (js-obj)
node-res (js-obj)
req {:node/request node-req
:node/response node-res}
res identity
error-handler (fn [err] (aset node-res "error" (.-message err)))
wrapped-echo (-> echo (wrap-node-middleware error-node-middleware))
result (wrapped-echo req res error-handler)]
(is (= "something went wrong!" (aget (:node/response req) "error")))))
|
|
14dc6e5a92c15d1a2026ccb1a984c545cb59da1b7cc6a90591244ea27ba813f1 | arttuka/reagent-material-ui | vape_free_two_tone.cljs | (ns reagent-mui.icons.vape-free-two-tone
"Imports @mui/icons-material/VapeFreeTwoTone as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def vape-free-two-tone (create-svg-icon [(e "circle" #js {"cx" "10.5", "cy" "17.5", "r" ".5", "opacity" ".3"}) (e "path" #js {"d" "M2 16.5h1c1.33 0 2.71-.18 4-.5v3c-1.29-.32-2.67-.5-4-.5H2v-2zM16.17 19H8v-3h5.17L1.39 4.22 2.8 2.81l18.38 18.38-1.41 1.41-3.6-3.6zm2.66-3H22v3h-.17l-3-3zM11 17.5c0-.28-.22-.5-.5-.5s-.5.22-.5.5.22.5.5.5.5-.22.5-.5zm11-4.74V15h-1.5v-2.23c0-2.24-1.76-4.07-4-4.07V7.2c1.02 0 1.85-.83 1.85-1.85S17.52 3.5 16.5 3.5V2c1.85 0 3.35 1.5 3.35 3.35 0 .93-.38 1.77-1 2.38 1.87.89 3.15 2.81 3.15 5.03zM11.15 8.32V8.3c0-1.85 1.5-3.35 3.35-3.35v1.5c-1.02 0-1.85.73-1.85 1.75s.83 2 1.85 2h1.53c1.87 0 3.47 1.35 3.47 3.16V15H18v-1.3c0-1.31-.92-2.05-1.97-2.05h-1.55l-3.33-3.33z"})]
"VapeFreeTwoTone"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/c7cd0d7c661ab9df5b0aed0213a6653a9a3f28ea/src/icons/reagent_mui/icons/vape_free_two_tone.cljs | clojure | (ns reagent-mui.icons.vape-free-two-tone
"Imports @mui/icons-material/VapeFreeTwoTone as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def vape-free-two-tone (create-svg-icon [(e "circle" #js {"cx" "10.5", "cy" "17.5", "r" ".5", "opacity" ".3"}) (e "path" #js {"d" "M2 16.5h1c1.33 0 2.71-.18 4-.5v3c-1.29-.32-2.67-.5-4-.5H2v-2zM16.17 19H8v-3h5.17L1.39 4.22 2.8 2.81l18.38 18.38-1.41 1.41-3.6-3.6zm2.66-3H22v3h-.17l-3-3zM11 17.5c0-.28-.22-.5-.5-.5s-.5.22-.5.5.22.5.5.5.5-.22.5-.5zm11-4.74V15h-1.5v-2.23c0-2.24-1.76-4.07-4-4.07V7.2c1.02 0 1.85-.83 1.85-1.85S17.52 3.5 16.5 3.5V2c1.85 0 3.35 1.5 3.35 3.35 0 .93-.38 1.77-1 2.38 1.87.89 3.15 2.81 3.15 5.03zM11.15 8.32V8.3c0-1.85 1.5-3.35 3.35-3.35v1.5c-1.02 0-1.85.73-1.85 1.75s.83 2 1.85 2h1.53c1.87 0 3.47 1.35 3.47 3.16V15H18v-1.3c0-1.31-.92-2.05-1.97-2.05h-1.55l-3.33-3.33z"})]
"VapeFreeTwoTone"))
|
|
e2d1538b38dac8bd88021d2db2ab7faf8516f3000b92a61ae5ecbcc680812169 | vrnithinkumar/ETC | env_solver.erl | -module(env_solver).
-export([solve_envs/2]).
-spec solve_envs(hm:env(), hm:env()) -> hm:env().
solve_envs(Env1, Env2) ->
Env1.
we have to take the two env and solve the type_var_bindings .
| null | https://raw.githubusercontent.com/vrnithinkumar/ETC/5e5806975fe96a902dab830a0c8caadc5d61e62b/src/env_solver.erl | erlang | -module(env_solver).
-export([solve_envs/2]).
-spec solve_envs(hm:env(), hm:env()) -> hm:env().
solve_envs(Env1, Env2) ->
Env1.
we have to take the two env and solve the type_var_bindings .
|
|
23fb2f99398e1b9be8dd33febda019b0feecebdd59e9578ca4aa873f46cfdaa4 | screenshotbot/screenshotbot-oss | auto-cleanup.lisp | ;;;; Copyright 2018-Present Modern Interpreters Inc.
;;;;
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(defpackage :screenshotbot/model/auto-cleanup
(:use #:cl)
(:import-from #:bknr.datastore
#:class-instances)
(:import-from #:bknr.datastore
#:delete-object)
(:import-from #:util/cron
#:def-cron)
(:local-nicknames (#:a #:alexandria))
(:export
#:register-auto-cleanup))
(in-package :screenshotbot/model/auto-cleanup)
(defvar *cleanups* nil)
(defclass cleanup ()
((type :initarg :type
:reader cleanup-type)
(timestamp :initarg :timestamp
:reader cleanup-timestamp)
(age :initarg :age
:reader cleanup-age)))
(defun register-auto-cleanup (obj &key (timestamp (error "must provide timestamp function"))
(age 30))
(setf (a:assoc-value *cleanups* obj)
(make-instance 'cleanup
:type obj
:timestamp timestamp
:age age)))
(defun process-cleanup (cleanup)
(let ((threshold (- (get-universal-time) (* 24 3600 (cleanup-age cleanup))))
(objs (class-instances (cleanup-type cleanup))))
(dolist (obj objs)
(when (< (funcall (cleanup-timestamp cleanup) obj)
threshold)
(log:info "Auto-deleting: ~s" obj)
(delete-object obj)))))
(defun dispatch-cleanups ()
(loop for (nil . cleanup) in *cleanups* do
(process-cleanup cleanup)))
(def-cron dispatch-cleanups (:minute 23 :hour 1)
(dispatch-cleanups))
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/7d884c485b2693945578ab19bc5ea45ff654b437/src/screenshotbot/model/auto-cleanup.lisp | lisp | Copyright 2018-Present Modern Interpreters Inc.
| This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(defpackage :screenshotbot/model/auto-cleanup
(:use #:cl)
(:import-from #:bknr.datastore
#:class-instances)
(:import-from #:bknr.datastore
#:delete-object)
(:import-from #:util/cron
#:def-cron)
(:local-nicknames (#:a #:alexandria))
(:export
#:register-auto-cleanup))
(in-package :screenshotbot/model/auto-cleanup)
(defvar *cleanups* nil)
(defclass cleanup ()
((type :initarg :type
:reader cleanup-type)
(timestamp :initarg :timestamp
:reader cleanup-timestamp)
(age :initarg :age
:reader cleanup-age)))
(defun register-auto-cleanup (obj &key (timestamp (error "must provide timestamp function"))
(age 30))
(setf (a:assoc-value *cleanups* obj)
(make-instance 'cleanup
:type obj
:timestamp timestamp
:age age)))
(defun process-cleanup (cleanup)
(let ((threshold (- (get-universal-time) (* 24 3600 (cleanup-age cleanup))))
(objs (class-instances (cleanup-type cleanup))))
(dolist (obj objs)
(when (< (funcall (cleanup-timestamp cleanup) obj)
threshold)
(log:info "Auto-deleting: ~s" obj)
(delete-object obj)))))
(defun dispatch-cleanups ()
(loop for (nil . cleanup) in *cleanups* do
(process-cleanup cleanup)))
(def-cron dispatch-cleanups (:minute 23 :hour 1)
(dispatch-cleanups))
|
cc3c965f851060133c29e111f6c243afeb9b0aff02c74e45b6a2db5ad14c867c | lvaruzza/cl-randist | binomial.lisp | (in-package :randist)
(declaim (optimize (speed 3) (safety 1) (debug 0)))
;; /* The binomial distribution has the form,
prob(k ) = n!/(k!(n - k ) ! ) * p^k ( 1 - p)^(n - k ) for k = 0 , 1 , ... , n
This is the algorithm from Knuth * /
;; /* Default binomial generator is now in binomial_tpe.c */
;; unsigned int
gsl_ran_binomial_knuth ( const gsl_rng * r , double p , unsigned int n )
;; {
unsigned int i , a , b , k = 0 ;
while ( n > 10 ) / * This parameter is tunable * /
;; {
;; double X;
;; a = 1 + (n / 2);
b = 1 + n - a ;
;; X = gsl_ran_beta (r, (double) a, (double) b);
;; if (X >= p)
;; {
;; n = a - 1;
;; p /= X;
;; }
;; else
;; {
;; k += a;
n = b - 1 ;
p = ( ) / ( 1 - X ) ;
;; }
;; }
for ( i = 0 ; i < n ; i++ )
;; {
;; double u = gsl_rng_uniform (r);
;; if (u < p)
;
;; }
;; return k;
;; }
(declaim (ftype (function (double-float integer) integer) random-binomial))
(defun random-binomial (p n)
"The binomial distribution has the form,
prob(k) = n!/(k!(n-k)!) * p^k (1-p)^(n-k) for k = 0, 1, ..., n
This is the algorithm from Knuth"
(let ((a 0) (b 0) (k 0)
(X 0d0)
(p p) (n n))
;; (declaim (integer i a b k)
;; (double-float X))
(declare (type integer n a b k)
(type double-float p X))
(tagbody
start
(when (<= n 10)
(go end))
(setf a (+ 1 (floor n 2)))
(setf b (+ 1 (- n a)))
(setf X (random-beta (coerce a 'double-float)
(coerce b 'double-float)))
(if (>= X p)
(progn
(setf n (- a 1))
(setf p (/ p X)))
(progn
(incf k a)
(setf n (- b 1))
(setf p (/ (- p X) (- 1d0 X)))))
(go start)
end)
(loop
for i of-type integer from 0 to (- n 1)
for u of-type double-float = (random-uniform)
when (< u p)
do (incf k))
k))
| null | https://raw.githubusercontent.com/lvaruzza/cl-randist/413204fa2b9e7f0431c0bc45367304af937494ff/binomial.lisp | lisp | /* The binomial distribution has the form,
/* Default binomial generator is now in binomial_tpe.c */
unsigned int
{
{
double X;
a = 1 + (n / 2);
X = gsl_ran_beta (r, (double) a, (double) b);
if (X >= p)
{
n = a - 1;
p /= X;
}
else
{
k += a;
}
}
i < n ; i++ )
{
double u = gsl_rng_uniform (r);
if (u < p)
}
return k;
}
(declaim (integer i a b k)
(double-float X)) | (in-package :randist)
(declaim (optimize (speed 3) (safety 1) (debug 0)))
prob(k ) = n!/(k!(n - k ) ! ) * p^k ( 1 - p)^(n - k ) for k = 0 , 1 , ... , n
This is the algorithm from Knuth * /
gsl_ran_binomial_knuth ( const gsl_rng * r , double p , unsigned int n )
while ( n > 10 ) / * This parameter is tunable * /
(declaim (ftype (function (double-float integer) integer) random-binomial))
(defun random-binomial (p n)
"The binomial distribution has the form,
prob(k) = n!/(k!(n-k)!) * p^k (1-p)^(n-k) for k = 0, 1, ..., n
This is the algorithm from Knuth"
(let ((a 0) (b 0) (k 0)
(X 0d0)
(p p) (n n))
(declare (type integer n a b k)
(type double-float p X))
(tagbody
start
(when (<= n 10)
(go end))
(setf a (+ 1 (floor n 2)))
(setf b (+ 1 (- n a)))
(setf X (random-beta (coerce a 'double-float)
(coerce b 'double-float)))
(if (>= X p)
(progn
(setf n (- a 1))
(setf p (/ p X)))
(progn
(incf k a)
(setf n (- b 1))
(setf p (/ (- p X) (- 1d0 X)))))
(go start)
end)
(loop
for i of-type integer from 0 to (- n 1)
for u of-type double-float = (random-uniform)
when (< u p)
do (incf k))
k))
|
e3f4b429d56be476025dace93a18738a1ba5cebdc26f455213bc6c7e0cad425f | avsm/eeww | bench_condition.ml | open Eio.Std
A publisher keeps updating a counter and signalling a condition .
Two consumers read the counter whenever they get a signal .
The producer stops after signalling [ target ] , and the consumers stop after seeing it .
Two consumers read the counter whenever they get a signal.
The producer stops after signalling [target], and the consumers stop after seeing it. *)
let n_iters = 100
let target = 100000
let run_publisher cond v =
for i = 1 to target do
Atomic.set v i;
(* traceln "set %d" i; *)
Eio.Condition.broadcast cond
done
let run_consumer cond v =
try
while true do
Fiber.both
(fun () -> Eio.Condition.await_no_mutex cond)
(fun () ->
let current = Atomic.get v in
(* traceln "saw %d" current; *)
if current = target then raise Exit
)
done
with Exit -> ()
let run_bench ?domain_mgr ~clock () =
let cond = Eio.Condition.create () in
let v = Atomic.make 0 in
let run_consumer () =
match domain_mgr with
| Some dm -> Eio.Domain_manager.run dm (fun () -> run_consumer cond v)
| None -> run_consumer cond v
in
Gc.full_major ();
let _minor0, prom0, _major0 = Gc.counters () in
let t0 = Eio.Time.now clock in
for _ = 1 to n_iters do
Fiber.all [
run_consumer;
run_consumer;
(fun () -> run_publisher cond v);
];
done;
let t1 = Eio.Time.now clock in
let time_total = t1 -. t0 in
let time_per_iter = time_total /. float n_iters in
let _minor1, prom1, _major1 = Gc.counters () in
let prom = prom1 -. prom0 in
Printf.printf "%11b, %7.2f, %13.4f\n%!" (domain_mgr <> None) (1e3 *. time_per_iter) (prom /. float n_iters)
let main ~domain_mgr ~clock =
Printf.printf "use_domains, ms/iter, promoted/iter\n%!";
run_bench ~clock ();
run_bench ~domain_mgr ~clock ()
let () =
Eio_main.run @@ fun env ->
main
~domain_mgr:(Eio.Stdenv.domain_mgr env)
~clock:(Eio.Stdenv.clock env)
| null | https://raw.githubusercontent.com/avsm/eeww/ab64c5391b67fb3f5b1d3de5e0a5a5cb4c80207b/lib/eio/bench/bench_condition.ml | ocaml | traceln "set %d" i;
traceln "saw %d" current; | open Eio.Std
A publisher keeps updating a counter and signalling a condition .
Two consumers read the counter whenever they get a signal .
The producer stops after signalling [ target ] , and the consumers stop after seeing it .
Two consumers read the counter whenever they get a signal.
The producer stops after signalling [target], and the consumers stop after seeing it. *)
let n_iters = 100
let target = 100000
let run_publisher cond v =
for i = 1 to target do
Atomic.set v i;
Eio.Condition.broadcast cond
done
let run_consumer cond v =
try
while true do
Fiber.both
(fun () -> Eio.Condition.await_no_mutex cond)
(fun () ->
let current = Atomic.get v in
if current = target then raise Exit
)
done
with Exit -> ()
let run_bench ?domain_mgr ~clock () =
let cond = Eio.Condition.create () in
let v = Atomic.make 0 in
let run_consumer () =
match domain_mgr with
| Some dm -> Eio.Domain_manager.run dm (fun () -> run_consumer cond v)
| None -> run_consumer cond v
in
Gc.full_major ();
let _minor0, prom0, _major0 = Gc.counters () in
let t0 = Eio.Time.now clock in
for _ = 1 to n_iters do
Fiber.all [
run_consumer;
run_consumer;
(fun () -> run_publisher cond v);
];
done;
let t1 = Eio.Time.now clock in
let time_total = t1 -. t0 in
let time_per_iter = time_total /. float n_iters in
let _minor1, prom1, _major1 = Gc.counters () in
let prom = prom1 -. prom0 in
Printf.printf "%11b, %7.2f, %13.4f\n%!" (domain_mgr <> None) (1e3 *. time_per_iter) (prom /. float n_iters)
let main ~domain_mgr ~clock =
Printf.printf "use_domains, ms/iter, promoted/iter\n%!";
run_bench ~clock ();
run_bench ~domain_mgr ~clock ()
let () =
Eio_main.run @@ fun env ->
main
~domain_mgr:(Eio.Stdenv.domain_mgr env)
~clock:(Eio.Stdenv.clock env)
|
5e82bde0f4e49bf29afac5fd9bf1562532aa16507381c8392a8a545bb880209f | goldfirere/units | Combinators.hs | Data / Metrology / Combinators.hs
The units Package
Copyright ( c ) 2013
This file defines combinators to build more complex units and dimensions from simpler ones .
The units Package
Copyright (c) 2013 Richard Eisenberg
This file defines combinators to build more complex units and dimensions from simpler ones.
-}
# LANGUAGE TypeOperators , TypeFamilies , UndecidableInstances ,
ScopedTypeVariables , DataKinds , FlexibleInstances ,
ConstraintKinds , CPP #
ScopedTypeVariables, DataKinds, FlexibleInstances,
ConstraintKinds, CPP #-}
#if __GLASGOW_HASKELL__ >= 711
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
#endif
module Data.Metrology.Combinators where
import Data.Singletons ( SingI, sing )
import Data.Metrology.Dimensions
import Data.Metrology.Units
import Data.Metrology.Factor
import Data.Metrology.Z
import Data.Type.Equality
import Data.Metrology.LCSU
infixl 7 :*
| Multiply two units to get another unit .
-- For example: @type MetersSquared = Meter :* Meter@
data u1 :* u2 = u1 :* u2
instance (Dimension d1, Dimension d2) => Dimension (d1 :* d2) where
type DimFactorsOf (d1 :* d2)
= Normalize ((DimFactorsOf d1) @+ (DimFactorsOf d2))
instance (Unit u1, Unit u2) => Unit (u1 :* u2) where
-- we override the default conversion lookup behavior
type BaseUnit (u1 :* u2) = Canonical
type DimOfUnit (u1 :* u2) = DimOfUnit u1 :* DimOfUnit u2
conversionRatio _ = undefined -- this should never be called
type UnitFactorsOf (u1 :* u2)
= Normalize ((UnitFactorsOf u1) @+ (UnitFactorsOf u2))
canonicalConvRatio _ = canonicalConvRatio (undefined :: u1) *
canonicalConvRatio (undefined :: u2)
type instance DefaultUnitOfDim (d1 :* d2) =
DefaultUnitOfDim d1 :* DefaultUnitOfDim d2
instance (Show u1, Show u2) => Show (u1 :* u2) where
show _ = show (undefined :: u1) ++ " " ++ show (undefined :: u2)
infixl 7 :/
| Divide two units to get another unit
data u1 :/ u2 = u1 :/ u2
instance (Dimension d1, Dimension d2) => Dimension (d1 :/ d2) where
type DimFactorsOf (d1 :/ d2)
= Normalize ((DimFactorsOf d1) @- (DimFactorsOf d2))
instance (Unit u1, Unit u2) => Unit (u1 :/ u2) where
type BaseUnit (u1 :/ u2) = Canonical
type DimOfUnit (u1 :/ u2) = DimOfUnit u1 :/ DimOfUnit u2
conversionRatio _ = undefined -- this should never be called
type UnitFactorsOf (u1 :/ u2)
= Normalize ((UnitFactorsOf u1) @- (UnitFactorsOf u2))
canonicalConvRatio _ = canonicalConvRatio (undefined :: u1) /
canonicalConvRatio (undefined :: u2)
type instance DefaultUnitOfDim (d1 :/ d2) =
DefaultUnitOfDim d1 :/ DefaultUnitOfDim d2
instance (Show u1, Show u2) => Show (u1 :/ u2) where
show _ = show (undefined :: u1) ++ "/" ++ show (undefined :: u2)
infixr 8 :^
-- | Raise a unit to a power, known at compile time
data unit :^ (power :: Z) = unit :^ Sing power
instance Dimension dim => Dimension (dim :^ power) where
type DimFactorsOf (dim :^ power)
= Normalize ((DimFactorsOf dim) @* power)
instance (Unit unit, SingI power) => Unit (unit :^ power) where
type BaseUnit (unit :^ power) = Canonical
type DimOfUnit (unit :^ power) = DimOfUnit unit :^ power
conversionRatio _ = undefined
type UnitFactorsOf (unit :^ power)
= Normalize ((UnitFactorsOf unit) @* power)
canonicalConvRatio _ = canonicalConvRatio (undefined :: unit) ^^ (szToInt (sing :: Sing power))
type instance DefaultUnitOfDim (d :^ z) = DefaultUnitOfDim d :^ z
instance (Show u1, SingI power) => Show (u1 :^ (power :: Z)) where
show _ = show (undefined :: u1) ++ "^" ++ show (szToInt (sing :: Sing power))
infixr 9 :@
-- | Multiply a conversion ratio by some constant. Used for defining prefixes.
data prefix :@ unit = prefix :@ unit
-- | A class for user-defined prefixes
class UnitPrefix prefix where
-- | This should return the desired multiplier for the prefix being defined.
This function must /not/ inspect its argument .
multiplier :: Fractional f => prefix -> f
instance ( (unit == Canonical) ~ False
, Unit unit
, UnitPrefix prefix ) => Unit (prefix :@ unit) where
type BaseUnit (prefix :@ unit) = unit
conversionRatio _ = multiplier (undefined :: prefix)
instance (Show prefix, Show unit) => Show (prefix :@ unit) where
show _ = show (undefined :: prefix) ++ show (undefined :: unit)
| null | https://raw.githubusercontent.com/goldfirere/units/4941c3b4325783ad3c5b6486231f395279d8511e/units/Data/Metrology/Combinators.hs | haskell | # OPTIONS_GHC -Wno-redundant-constraints #
For example: @type MetersSquared = Meter :* Meter@
we override the default conversion lookup behavior
this should never be called
this should never be called
| Raise a unit to a power, known at compile time
| Multiply a conversion ratio by some constant. Used for defining prefixes.
| A class for user-defined prefixes
| This should return the desired multiplier for the prefix being defined. | Data / Metrology / Combinators.hs
The units Package
Copyright ( c ) 2013
This file defines combinators to build more complex units and dimensions from simpler ones .
The units Package
Copyright (c) 2013 Richard Eisenberg
This file defines combinators to build more complex units and dimensions from simpler ones.
-}
# LANGUAGE TypeOperators , TypeFamilies , UndecidableInstances ,
ScopedTypeVariables , DataKinds , FlexibleInstances ,
ConstraintKinds , CPP #
ScopedTypeVariables, DataKinds, FlexibleInstances,
ConstraintKinds, CPP #-}
#if __GLASGOW_HASKELL__ >= 711
#endif
module Data.Metrology.Combinators where
import Data.Singletons ( SingI, sing )
import Data.Metrology.Dimensions
import Data.Metrology.Units
import Data.Metrology.Factor
import Data.Metrology.Z
import Data.Type.Equality
import Data.Metrology.LCSU
infixl 7 :*
| Multiply two units to get another unit .
data u1 :* u2 = u1 :* u2
instance (Dimension d1, Dimension d2) => Dimension (d1 :* d2) where
type DimFactorsOf (d1 :* d2)
= Normalize ((DimFactorsOf d1) @+ (DimFactorsOf d2))
instance (Unit u1, Unit u2) => Unit (u1 :* u2) where
type BaseUnit (u1 :* u2) = Canonical
type DimOfUnit (u1 :* u2) = DimOfUnit u1 :* DimOfUnit u2
type UnitFactorsOf (u1 :* u2)
= Normalize ((UnitFactorsOf u1) @+ (UnitFactorsOf u2))
canonicalConvRatio _ = canonicalConvRatio (undefined :: u1) *
canonicalConvRatio (undefined :: u2)
type instance DefaultUnitOfDim (d1 :* d2) =
DefaultUnitOfDim d1 :* DefaultUnitOfDim d2
instance (Show u1, Show u2) => Show (u1 :* u2) where
show _ = show (undefined :: u1) ++ " " ++ show (undefined :: u2)
infixl 7 :/
| Divide two units to get another unit
data u1 :/ u2 = u1 :/ u2
instance (Dimension d1, Dimension d2) => Dimension (d1 :/ d2) where
type DimFactorsOf (d1 :/ d2)
= Normalize ((DimFactorsOf d1) @- (DimFactorsOf d2))
instance (Unit u1, Unit u2) => Unit (u1 :/ u2) where
type BaseUnit (u1 :/ u2) = Canonical
type DimOfUnit (u1 :/ u2) = DimOfUnit u1 :/ DimOfUnit u2
type UnitFactorsOf (u1 :/ u2)
= Normalize ((UnitFactorsOf u1) @- (UnitFactorsOf u2))
canonicalConvRatio _ = canonicalConvRatio (undefined :: u1) /
canonicalConvRatio (undefined :: u2)
type instance DefaultUnitOfDim (d1 :/ d2) =
DefaultUnitOfDim d1 :/ DefaultUnitOfDim d2
instance (Show u1, Show u2) => Show (u1 :/ u2) where
show _ = show (undefined :: u1) ++ "/" ++ show (undefined :: u2)
infixr 8 :^
data unit :^ (power :: Z) = unit :^ Sing power
instance Dimension dim => Dimension (dim :^ power) where
type DimFactorsOf (dim :^ power)
= Normalize ((DimFactorsOf dim) @* power)
instance (Unit unit, SingI power) => Unit (unit :^ power) where
type BaseUnit (unit :^ power) = Canonical
type DimOfUnit (unit :^ power) = DimOfUnit unit :^ power
conversionRatio _ = undefined
type UnitFactorsOf (unit :^ power)
= Normalize ((UnitFactorsOf unit) @* power)
canonicalConvRatio _ = canonicalConvRatio (undefined :: unit) ^^ (szToInt (sing :: Sing power))
type instance DefaultUnitOfDim (d :^ z) = DefaultUnitOfDim d :^ z
instance (Show u1, SingI power) => Show (u1 :^ (power :: Z)) where
show _ = show (undefined :: u1) ++ "^" ++ show (szToInt (sing :: Sing power))
infixr 9 :@
data prefix :@ unit = prefix :@ unit
class UnitPrefix prefix where
This function must /not/ inspect its argument .
multiplier :: Fractional f => prefix -> f
instance ( (unit == Canonical) ~ False
, Unit unit
, UnitPrefix prefix ) => Unit (prefix :@ unit) where
type BaseUnit (prefix :@ unit) = unit
conversionRatio _ = multiplier (undefined :: prefix)
instance (Show prefix, Show unit) => Show (prefix :@ unit) where
show _ = show (undefined :: prefix) ++ show (undefined :: unit)
|
91fd507903d1b4f5ed979a1c771ae2047b93d1ac4827ecdb5e1509e773c53693 | janestreet/sexp | main_json.mli | open! Core
val of_json_command : Command.t
val to_json_command : Command.t
| null | https://raw.githubusercontent.com/janestreet/sexp/0bf688bb9935b540a712c8f5429caa50b5ee45c3/bin/main_json.mli | ocaml | open! Core
val of_json_command : Command.t
val to_json_command : Command.t
|
|
fbfdb7fc9c0eb3a25b1c7bbc50e0c5eca354923de10a0033a2277f9009bcae02 | ghc/packages-dph | Tuple.hs | module Data.Array.Parallel.Prelude.Tuple (
tup2, tup3, tup4
) where
import Data.Array.Parallel.Lifted.Closure
import Data.Array.Parallel.Lifted.PArray
import Data.Array.Parallel.PArray.PDataInstances
tup2 :: (PA a, PA b) => a :-> b :-> (a,b)
# INLINE tup2 #
tup2 = closure2 (,) zipPA#
tup3 :: (PA a, PA b, PA c) => a :-> b :-> c :-> (a,b,c)
# INLINE tup3 #
tup3 = closure3 (,,) zip3PA#
tup4 :: (PA a, PA b, PA c, PA d) => a :-> b :-> c :-> d :-> (a,b,c,d)
# INLINE tup4 #
tup4 = closure4 (,,,) zip4PA#
| null | https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-lifted-copy/Data/Array/Parallel/Prelude/Tuple.hs | haskell | module Data.Array.Parallel.Prelude.Tuple (
tup2, tup3, tup4
) where
import Data.Array.Parallel.Lifted.Closure
import Data.Array.Parallel.Lifted.PArray
import Data.Array.Parallel.PArray.PDataInstances
tup2 :: (PA a, PA b) => a :-> b :-> (a,b)
# INLINE tup2 #
tup2 = closure2 (,) zipPA#
tup3 :: (PA a, PA b, PA c) => a :-> b :-> c :-> (a,b,c)
# INLINE tup3 #
tup3 = closure3 (,,) zip3PA#
tup4 :: (PA a, PA b, PA c, PA d) => a :-> b :-> c :-> d :-> (a,b,c,d)
# INLINE tup4 #
tup4 = closure4 (,,,) zip4PA#
|
|
e5cda051728680505fb2f07944aa918ed6fbccb82832a4801352046f175b54cb | semperos/clj-webdriver | core_actions.clj | (in-ns 'webdriver.core)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Functions for Actions Class ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO: test coverage
(defmacro ->build-composite-action
"Create a composite chain of actions, then call `.build()`. This does **not** execute the actions; it simply sets up an 'action chain' which can later by executed using `.perform()`.
Unless you need to wait to execute your composite actions, you should prefer `->actions` to this macro."
[driver & body]
`(let [acts# (doto (Actions. (.webdriver ~driver))
~@body)]
(.build acts#)))
;; TODO: test coverage
(defmacro ->actions
[driver & body]
`(let [act# (Actions. (.webdriver ~driver))]
(doto act#
~@body
.perform)
~driver))
;; e.g.
Action dragAndDrop = builder.clickAndHold(someElement )
;; .moveToElement(otherElement)
;; .release(otherElement)
( )
| null | https://raw.githubusercontent.com/semperos/clj-webdriver/508eb95cb6ad8a5838ff0772b2a5852dc802dde1/src/webdriver/core_actions.clj | clojure |
Functions for Actions Class ;;
TODO: test coverage
it simply sets up an 'action chain' which can later by executed using `.perform()`.
TODO: test coverage
e.g.
.moveToElement(otherElement)
.release(otherElement) | (in-ns 'webdriver.core)
(defmacro ->build-composite-action
Unless you need to wait to execute your composite actions, you should prefer `->actions` to this macro."
[driver & body]
`(let [acts# (doto (Actions. (.webdriver ~driver))
~@body)]
(.build acts#)))
(defmacro ->actions
[driver & body]
`(let [act# (Actions. (.webdriver ~driver))]
(doto act#
~@body
.perform)
~driver))
Action dragAndDrop = builder.clickAndHold(someElement )
( )
|
5b98ccd82243eae4debf3f2f420344a1c9e8ebbe8fe94f90875207417e10af0d | cdfa/frugel | Scout.hs | module Scout
( module Scout.Node
, module Scout.Program
, module Scout.Evaluation
, module Scout.Error
, module Control.Limited
, module Scout.PrettyPrinting
, module Scout.Unbound
, module Scout.Truncatable
) where
import Control.Limited
import Scout.Error
import Scout.Evaluation
import Scout.Node hiding ( EvaluationOutput(..) )
import Scout.PrettyPrinting
import Scout.Program
import Scout.Truncatable
import Scout.Unbound
| null | https://raw.githubusercontent.com/cdfa/frugel/d412673d8925a6f9eaad4e043cbd8fa46ed50aa2/scout-src/Scout.hs | haskell | module Scout
( module Scout.Node
, module Scout.Program
, module Scout.Evaluation
, module Scout.Error
, module Control.Limited
, module Scout.PrettyPrinting
, module Scout.Unbound
, module Scout.Truncatable
) where
import Control.Limited
import Scout.Error
import Scout.Evaluation
import Scout.Node hiding ( EvaluationOutput(..) )
import Scout.PrettyPrinting
import Scout.Program
import Scout.Truncatable
import Scout.Unbound
|
|
89be8c6ba16f70a643d1fe5d87c03d1d5e6a590edd47a0f56fb96a4b2728deac | melisgl/lassie | assemble.lisp | (in-package :lassie.assembler)
Interface
(defgeneric assemble-co-occurrence-matrix (assembler lister)
(:documentation "Assemble MATRIX and remember how to perform the
same kind of activity on subsequent calls to ASSEMBLE-TERM-VECTOR and
ASSEMBLE-DOCUMENT-VECTOR."))
(defgeneric assemble-term-vector (assembler lister)
(:documentation "Iterate over documents of LISTER and assemble a
term vector in the same way as the matrix was assembled previously."))
(defgeneric assemble-document-vector (assembler lister)
(:documentation "Iterate over terms of LISTER and assemble a
document vector in the same way as the matrix was assembled
previously."))
;;;
(defclass lsa-assembler ()
((n-terms :initarg :n-terms :reader n-terms)
(n-documents :initarg :n-documents :reader n-documents))
(:documentation "The standard assembler that adds ..."))
(defun make-lsa-assembler (&key n-terms n-documents)
(make-instance 'lsa-assembler :n-terms n-terms :n-documents n-documents))
(defmethod print-object :around ((assembler lsa-assembler) stream)
(if *print-readably*
(format stream "#.~S"
`(make-lsa-assembler :n-terms ,(n-terms assembler)
:n-documents ,(n-documents assembler)))
(call-next-method)))
(defun incf-and-maybe-grow (matrix delta &rest indices)
(assert (adjustable-array-p matrix))
(unless (every #'< indices (array-dimensions matrix))
(adjust-array matrix
(mapcar (lambda (i d)
(if (< i d)
d
(print (max (1+ i) (* 2 d)))))
indices (array-dimensions matrix))
:initial-element 0.0))
(incf (apply #'aref matrix indices) delta))
(defmethod assemble-co-occurrence-matrix ((assembler lsa-assembler) lister)
(let ((matrix (make-array '(0 0) :element-type 'single-float
:initial-element 0.0 :adjustable t))
(max-row -1)
(max-column -1))
(funcall lister (lambda (row column &optional (delta 1.0))
(setf max-row (max row max-row))
(setf max-column (max column max-column))
(incf-and-maybe-grow matrix delta row column)))
(setf (slot-value assembler 'n-terms) (1+ max-row))
(setf (slot-value assembler 'n-documents) (1+ max-column))
We are going to work with this matrix a lot , make a new one
;; that's not adjustable.
(let ((m (make-array (list (1+ max-row) (1+ max-column))
:element-type 'single-float)))
(dotimes (row (1+ max-row))
(dotimes (column (1+ max-column))
(setf (aref m row column) (aref matrix row column))))
m)))
(defun assemble-occurence-vector (lister size)
"Return a vector of SIZE whose elements represent the frequency with
which their indices were listed by LISTER."
(let ((v (make-array size :element-type 'single-float :initial-element 0.0)))
(funcall lister (lambda (index &optional (delta 1.0))
(incf (aref v index) delta)))
v))
(defmethod assemble-term-vector ((assembler lsa-assembler) lister)
(declare (ignore lister))
(error "Don't know how to assemble term vectors. Giving up."))
(defmethod assemble-document-vector ((assembler lsa-assembler) lister)
(assemble-occurence-vector lister (n-terms assembler)))
;;;
(defclass ri-term-assembler (lsa-assembler)
()
(:documentation "Terms are random indexed, documents are not."))
(defun make-ri-term-assembler ()
(make-instance 'ri-term-assembler))
(defmethod print-object :around ((assembler ri-term-assembler) stream)
(if *print-readably*
(format stream "#.~S" '(make-ri-term-assembler))
(call-next-method)))
(defmethod assemble-co-occurrence-matrix ((assembler ri-term-assembler) lister)
(call-next-method
assembler
(lassie::compose-mappers
lister
(lambda (fn rows column)
(loop with l = (/ (length rows) 2)
for i below (* l 2)
for weight = (if (< i l) 1.0 -1.0)
do (funcall fn (aref rows i) column weight))))))
(defmethod assemble-document-vector ((assembler ri-term-assembler) lister)
(assemble-occurence-vector
(lassie::compose-mappers
lister
(lambda (fn rows)
(loop with l = (/ (length rows) 2)
for i below (* l 2)
for weight = (if (< i l) 1.0 -1.0)
do (funcall fn (aref rows i) weight))))
(n-terms assembler)))
| null | https://raw.githubusercontent.com/melisgl/lassie/209b3435596090bc249a43ca7072a38f62a70d41/assemble.lisp | lisp |
that's not adjustable.
| (in-package :lassie.assembler)
Interface
(defgeneric assemble-co-occurrence-matrix (assembler lister)
(:documentation "Assemble MATRIX and remember how to perform the
same kind of activity on subsequent calls to ASSEMBLE-TERM-VECTOR and
ASSEMBLE-DOCUMENT-VECTOR."))
(defgeneric assemble-term-vector (assembler lister)
(:documentation "Iterate over documents of LISTER and assemble a
term vector in the same way as the matrix was assembled previously."))
(defgeneric assemble-document-vector (assembler lister)
(:documentation "Iterate over terms of LISTER and assemble a
document vector in the same way as the matrix was assembled
previously."))
(defclass lsa-assembler ()
((n-terms :initarg :n-terms :reader n-terms)
(n-documents :initarg :n-documents :reader n-documents))
(:documentation "The standard assembler that adds ..."))
(defun make-lsa-assembler (&key n-terms n-documents)
(make-instance 'lsa-assembler :n-terms n-terms :n-documents n-documents))
(defmethod print-object :around ((assembler lsa-assembler) stream)
(if *print-readably*
(format stream "#.~S"
`(make-lsa-assembler :n-terms ,(n-terms assembler)
:n-documents ,(n-documents assembler)))
(call-next-method)))
(defun incf-and-maybe-grow (matrix delta &rest indices)
(assert (adjustable-array-p matrix))
(unless (every #'< indices (array-dimensions matrix))
(adjust-array matrix
(mapcar (lambda (i d)
(if (< i d)
d
(print (max (1+ i) (* 2 d)))))
indices (array-dimensions matrix))
:initial-element 0.0))
(incf (apply #'aref matrix indices) delta))
(defmethod assemble-co-occurrence-matrix ((assembler lsa-assembler) lister)
(let ((matrix (make-array '(0 0) :element-type 'single-float
:initial-element 0.0 :adjustable t))
(max-row -1)
(max-column -1))
(funcall lister (lambda (row column &optional (delta 1.0))
(setf max-row (max row max-row))
(setf max-column (max column max-column))
(incf-and-maybe-grow matrix delta row column)))
(setf (slot-value assembler 'n-terms) (1+ max-row))
(setf (slot-value assembler 'n-documents) (1+ max-column))
We are going to work with this matrix a lot , make a new one
(let ((m (make-array (list (1+ max-row) (1+ max-column))
:element-type 'single-float)))
(dotimes (row (1+ max-row))
(dotimes (column (1+ max-column))
(setf (aref m row column) (aref matrix row column))))
m)))
(defun assemble-occurence-vector (lister size)
"Return a vector of SIZE whose elements represent the frequency with
which their indices were listed by LISTER."
(let ((v (make-array size :element-type 'single-float :initial-element 0.0)))
(funcall lister (lambda (index &optional (delta 1.0))
(incf (aref v index) delta)))
v))
(defmethod assemble-term-vector ((assembler lsa-assembler) lister)
(declare (ignore lister))
(error "Don't know how to assemble term vectors. Giving up."))
(defmethod assemble-document-vector ((assembler lsa-assembler) lister)
(assemble-occurence-vector lister (n-terms assembler)))
(defclass ri-term-assembler (lsa-assembler)
()
(:documentation "Terms are random indexed, documents are not."))
(defun make-ri-term-assembler ()
(make-instance 'ri-term-assembler))
(defmethod print-object :around ((assembler ri-term-assembler) stream)
(if *print-readably*
(format stream "#.~S" '(make-ri-term-assembler))
(call-next-method)))
(defmethod assemble-co-occurrence-matrix ((assembler ri-term-assembler) lister)
(call-next-method
assembler
(lassie::compose-mappers
lister
(lambda (fn rows column)
(loop with l = (/ (length rows) 2)
for i below (* l 2)
for weight = (if (< i l) 1.0 -1.0)
do (funcall fn (aref rows i) column weight))))))
(defmethod assemble-document-vector ((assembler ri-term-assembler) lister)
(assemble-occurence-vector
(lassie::compose-mappers
lister
(lambda (fn rows)
(loop with l = (/ (length rows) 2)
for i below (* l 2)
for weight = (if (< i l) 1.0 -1.0)
do (funcall fn (aref rows i) weight))))
(n-terms assembler)))
|
993d73eb7ccd0a5cf8df02d858c558ec7789035af5498beb9190a67e32ce5a00 | karlhof26/gimp-scheme | Antique Metal_02a.scm | Antique Metal rel 0.03
Created by Graechan
; You will need to install GMIC to run this Scipt
; GMIC can be downloaded from
Thanks to Draconian for his Antique - metal tutorial
; that I followed to write this script.
; Comments directed to
;
License :
; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
To view a copy of the GNU General Public License
; visit:
;
;
; ------------
;| Change Log |
; ------------
Rel 0.01 - Initial Release
Rel 0.02 - Added text options Justify , Letter Spacing , Line Spacing and option controls for ' Drop Shadow ' ' Grunge ' ' Vignette ' ' Frame '
; Rel 0.03 - Bugfix for typo in script
Rel 0.04 - Update by karlhof26 to remove Gmic dependency and messages on 27/02/2022
;
(define (script-fu-antique-metal-logo
text
justify
letter-spacing
line-spacing
font-in
font-size
grow
ds-apply
ds-offset
ds-blur
opacity
bev-width
depth
metal
apply-grunge
grunge-color
grunge-opacity
apply-vignette
apply-frame
vig-size
frame-in
conserve)
(let* (
(image (car (gimp-image-new 256 256 RGB)))
(border (/ font-size 4))
(font (if (> (string-length font-in) 0) font-in (car (gimp-context-get-font))))
(text-layer (car (gimp-text-fontname image -1 0 0 text border TRUE font-size PIXELS font)))
(justify (cond ((= justify 0) 2)
((= justify 1) 0)
((= justify 2) 1)))
(width (car (gimp-drawable-width text-layer)))
(height (car (gimp-drawable-height text-layer)))
(text-channel 0)
(bkg-layer 0)
(inner-shadow 0)
(inner-glow 0)
(inner-shadow-mask 0)
(inner-glow-mask 0)
(overlay-mode 0)
(add-shadow TRUE)
(add-canvas TRUE)
(add-mottling TRUE)
(nominal-burn-size 30)
(inner-bevel-layer 0)
(azimuth 135)
(elevation 35)
(postblur 3.0)
(texture-layer 0)
(red (car grunge-color))
(green (cadr grunge-color))
(blue (caddr grunge-color))
(frame-layer 0)
(frame frame-in)
)
(gimp-context-push)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
;;;;adjust text
(gimp-text-layer-set-justification text-layer justify)
(gimp-text-layer-set-letter-spacing text-layer letter-spacing)
(gimp-text-layer-set-line-spacing text-layer line-spacing)
(gimp-image-resize-to-layers image)
;;;;set the text clolor
(gimp-context-set-foreground '(0 0 0))
(gimp-selection-layer-alpha text-layer)
(gimp-drawable-edit-fill text-layer FILL-FOREGROUND)
( gimp - message " line 103 " )
;;;;Expand the font if needed
(if (> grow 0)
(begin
(gimp-message "line 108 - grow")
(gimp-selection-layer-alpha text-layer)
(gimp-edit-clear text-layer)
(gimp-selection-grow image grow)
(gimp-context-set-foreground '(0 0 0))
(gimp-drawable-edit-fill text-layer FILL-FOREGROUND)
)
)
(gimp-selection-none image)
(gimp-display-new image)
(gimp-image-undo-group-start image)
( gimp - message " line 120 " )
(gimp-progress-pulse)
(script-fu-antique-metal-alpha
image
text-layer
metal
ds-apply
ds-offset
ds-blur
opacity
bev-width
depth
apply-grunge
grunge-color
grunge-opacity
apply-vignette
apply-frame
vig-size
frame
TRUE ; Was F
conserve)
(gimp-image-undo-group-end image)
(gimp-context-pop)
( gimp - message " good end line 137 " )
(gimp-progress-pulse)
)
)
(script-fu-register "script-fu-antique-metal-logo"
"Antique Metal Logo"
"Antque metal logo with optional metal types. \nfile:Antique Metal_02a.scm"
"Graechan"
"Graechan - "
"Aug 2012"
""
SF-TEXT "Text" "Gimp"
SF-OPTION "Justify" '("Centered" "Left" "Right")
SF-ADJUSTMENT "Letter Spacing" '(0 -100 100 1 5 0 0)
SF-ADJUSTMENT "Line Spacing" '(0 -100 100 1 5 0 0)
SF-FONT "Font" "JasmineUPC Bold"
SF-ADJUSTMENT "Font size (pixels)" '(350 100 1000 1 10 0 1)
SF-ADJUSTMENT "Expand the Font if needed" '(0 0 10 1 1 0 1)
SF-TOGGLE "Apply Drop Shadow" TRUE
SF-ADJUSTMENT "Drop shadow offset" '(10 0 100 1 10 0 1)
SF-ADJUSTMENT "Drop shadow blur radius" '(30 0 255 1 10 0 1)
SF-ADJUSTMENT "Inner Shadow and Glow Opacity" '(70 0 100 1 10 0 0)
SF-ADJUSTMENT "Bevel Width" '(10 1 100 1 10 0 0)
SF-ADJUSTMENT "Bevel Depth" '(3 1 60 1 10 0 0)
SF-OPTION "Metal Finish Type" '("Iron" "Gold" "Silver" "Copper" "Bronze" "Brass")
SF-TOGGLE "Apply Grunge background" TRUE
SF-COLOR "Background Grunge Color" '(153 153 184)
SF-ADJUSTMENT "Background Grunge Darkness" '(70 0 100 1 10 0 0)
SF-TOGGLE "Apply Vignette" TRUE
SF-TOGGLE "Apply Frame" TRUE
SF-ADJUSTMENT "Background Vignette Size" '(5 0 50 1 5 0 0)
SF-ADJUSTMENT "Frame Size %" '(5 0 20 1 5 0 0)
SF-TOGGLE "Keep the Layers" TRUE
)
(script-fu-menu-register "script-fu-antique-metal-logo" "<Image>/Script-Fu/Logos")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (script-fu-antique-metal-alpha image drawable
metal
ds-apply
ds-offset
ds-blur
opacity
bev-width
depth
apply-grunge
grunge-color
grunge-opacity
apply-vignette
apply-frame
vig-size
frame-in
keep-selection-in
conserve)
(let* (
(image-layer (car (gimp-image-get-active-layer image)))
(width (car (gimp-image-width image)))
(height (car (gimp-image-height image)))
(alpha (car (gimp-drawable-has-alpha image-layer)))
(sel (car (gimp-selection-is-empty image)))
(layer-name (car (gimp-drawable-get-name image-layer)))
(keep-selection keep-selection-in)
(text "Antique Metal")
(selection-channel 0)
(bkg-layer 0)
(inner-shadow 0)
(inner-glow 0)
(inner-shadow-mask 0)
(inner-glow-mask 0)
(overlay-mode 0)
(add-shadow TRUE)
(add-canvas TRUE)
(add-mottling TRUE)
(nominal-burn-size 30)
(inner-bevel-layer 0)
(azimuth 135)
(elevation 35)
(postblur 3.0)
(texture-layer 0)
(red (car grunge-color))
(green (cadr grunge-color))
(blue (caddr grunge-color))
(frame-layer 0)
(frame frame-in)
(offset-x 0)
(offset-y 0)
(offsets 0)
(metal-layer 0)
)
( gimp - message " line 239 " )
(gimp-progress-update 0.10)
(gimp-context-push)
(gimp-image-undo-group-start image)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
(if (= alpha FALSE) (gimp-layer-add-alpha image-layer))
check that a selection was made if not make one
(if (= sel TRUE) (set! keep-selection FALSE))
(if (= sel TRUE) (gimp-selection-layer-alpha image-layer))
(gimp-selection-invert image)
(gimp-edit-clear image-layer)
(gimp-selection-invert image)
( gimp - message " line 256 " )
(gimp-progress-update 0.15)
;;;;create selection-channel
(gimp-selection-save image)
(set! selection-channel (car (gimp-image-get-active-drawable image)))
(gimp-channel-set-opacity selection-channel 100)
(gimp-drawable-set-name selection-channel "selection-channel")
(gimp-image-set-active-layer image image-layer)
(gimp-selection-none image)
;;;;create the background layer
(set! bkg-layer (car (gimp-layer-new image width height RGBA-IMAGE "Background" 100 LAYER-MODE-NORMAL-LEGACY)))
was 0 1
( gimp - message " line 269 " )
(if (= apply-grunge TRUE)
(begin
( gimp - message " line 273 " )
;(gimp-message "going to the antique metal background")
(the-antique-metal-background image bkg-layer grunge-color grunge-opacity)
(set! bkg-layer (car (gimp-image-get-active-layer image)))
(set! bkg-layer (car (gimp-image-merge-down image bkg-layer EXPAND-AS-NECESSARY)))
(gimp-drawable-set-name bkg-layer "Background")
)
)
( gimp - message " line 281 " )
(gimp-progress-update 0.20)
;;;;fill image with grey
(gimp-selection-load selection-channel)
(gimp-context-set-foreground '(123 123 123))
(gimp-drawable-edit-fill image-layer FILL-FOREGROUND)
(set! width (car (gimp-image-width image)))
(set! height (car (gimp-image-height image)))
(gimp-selection-none image)
(gimp-layer-resize-to-image-size bkg-layer)
(gimp-layer-resize-to-image-size image-layer)
( gimp - message " line 293 " )
;;;;create inner-shadow and inner-glow layers
(set! inner-shadow (car (gimp-layer-copy image-layer TRUE)))
(gimp-image-insert-layer image inner-shadow 0 -1)
(gimp-drawable-set-name inner-shadow "Inner shadow")
(gimp-layer-set-mode inner-shadow LAYER-MODE-MULTIPLY-LEGACY)
(gimp-layer-set-opacity inner-shadow opacity)
(gimp-progress-update 0.25)
( gimp - message " line 303 " )
(set! inner-glow (car (gimp-layer-copy image-layer TRUE)))
(gimp-image-insert-layer image inner-glow 0 -1)
(gimp-drawable-set-name inner-glow "Inner glow")
(gimp-layer-set-mode inner-glow LAYER-MODE-MULTIPLY-LEGACY)
(gimp-layer-set-opacity inner-glow opacity)
;;;;create the inner shadow
(gimp-image-set-active-layer image inner-shadow)
(gimp-drawable-set-visible inner-shadow TRUE)
( gimp - message " line 313 " )
(gimp-progress-update 0.30)
(set! inner-shadow-mask (car (gimp-layer-create-mask inner-shadow ADD-MASK-ALPHA)))
(gimp-layer-add-mask inner-shadow inner-shadow-mask)
(gimp-layer-set-edit-mask inner-shadow FALSE)
(gimp-selection-load selection-channel)
(gimp-selection-shrink image (* bev-width 1.5))
(gimp-selection-invert image)
(gimp-context-set-foreground '(99 78 56))
( gimp - message " line 324 " )
was LAYER - MODE - NORMAL opacity 15.0 TRUE 0 0
(gimp-selection-none image)
(plug-in-gauss-rle RUN-NONINTERACTIVE image inner-shadow (* bev-width 3) TRUE TRUE)
( gimp - message " line 329 " )
;;;;create the inner glow
(gimp-image-set-active-layer image inner-glow)
(gimp-drawable-set-visible inner-glow TRUE)
(gimp-selection-load selection-channel)
(gimp-edit-clear inner-glow)
(set! inner-glow-mask (car (gimp-layer-create-mask inner-glow ADD-MASK-SELECTION)))
(gimp-layer-add-mask inner-glow inner-glow-mask)
(gimp-layer-set-edit-mask inner-glow FALSE)
( gimp - message " line 340 " )
(gimp-progress-update 0.40)
(gimp-selection-shrink image bev-width)
(gimp-selection-invert image)
(gimp-context-set-foreground '(120 100 80))
was FG - BUCKET - FILL NORMAL - MODE opacity 15.0 TRUE 0 0
(gimp-selection-none image)
( gimp - message " line 348 " )
(plug-in-gauss-rle RUN-NONINTERACTIVE image inner-glow (* bev-width 2) TRUE TRUE)
(gimp-image-raise-layer-to-top image bkg-layer)
(set! image-layer (car (gimp-image-merge-visible-layers image EXPAND-AS-NECESSARY)))
(if (= apply-grunge FALSE)
(begin
( gimp - message " line 355 " )
(gimp-selection-load selection-channel)
(gimp-selection-translate image -3 -2)
(gimp-selection-invert image)
(gimp-edit-clear image-layer)
(gimp-selection-none image)
)
)
(gimp-drawable-set-name image-layer text)
( gimp - message " line 364 " )
(gimp-progress-update 0.50)
;;;;Add new layer with Bevel
(gimp-selection-load selection-channel)
(set! inner-bevel-layer (car (gimp-layer-new image width height RGBA-IMAGE "Inner bevel" 100 LAYER-MODE-NORMAL)))
(gimp-image-insert-layer image inner-bevel-layer 0 -1)
(gimp-image-set-active-layer image inner-bevel-layer)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
( gimp - message " line 373 " )
(gimp-drawable-edit-fill inner-bevel-layer FILL-FOREGROUND)
(gimp-selection-shrink image 1)
(gimp-selection-feather image bev-width)
(gimp-selection-shrink image (- (/ bev-width 2) 1))
( gimp - message " line 379 " )
(gimp-progress-update 0.60)
(gimp-drawable-edit-fill inner-bevel-layer FILL-BACKGROUND)
(gimp-selection-all image)
( gimp - message " line 383 " )
(if (= ds-apply TRUE) (gimp-invert inner-bevel-layer))
(plug-in-emboss RUN-NONINTERACTIVE image inner-bevel-layer azimuth elevation depth 1);Emboss
;;;;gloss the bevel-layer
( gimp - curves - spline inner - bevel - layer 0 18 # ( 0 0 32 158 62 30 96 223 126 96 159 255 189 160 222 255 255 255 ) )
(gimp-drawable-curves-spline inner-bevel-layer HISTOGRAM-VALUE 18 #(0.0 0.0 0.15 0.7 0.23 0.145 0.38 0.88 0.5 0.38 0.88 1.0 0.75 0.65 0.92 1.0 1.0 1.0))
(plug-in-gauss-rle RUN-NONINTERACTIVE image inner-bevel-layer postblur 1 1)
( gimp - message " line 392 " )
(gimp-progress-update 0.70)
;;;;Clean up the layers
(gimp-selection-load selection-channel)
(gimp-selection-invert image)
(gimp-edit-clear inner-bevel-layer)
;;;;create the texture-layer
(set! texture-layer (car (gimp-layer-new image width height RGBA-IMAGE "Texture" 100 LAYER-MODE-NORMAL)))
(gimp-image-insert-layer image texture-layer 0 -1)
(gimp-selection-load selection-channel)
(gimp-context-set-foreground '(123 123 123))
(gimp-drawable-edit-fill texture-layer FILL-FOREGROUND)
( gimp - progress - update 0.81 )
( gimp - message " line 407 " )
drawing using G'MIC .
;(gimp-message "whirl start")
(if (defined? 'plug-in-gmic-qt) ; (defined? 'gimp-context-set-brush-size)
(begin
( gimp - message " line413 " )
(plug-in-gmic-qt 1 image texture-layer 1 0
(string-append
"-v - " ; To have a silent output. Remove it to display errors from the G'MIC interpreter on stderr.
"-fx_draw_whirl "
"74.70"
)
)
)
(begin
( gimp - message " No whirl Gmic is required ( from http;//gmic.eu ) " )
(plug-in-hsv-noise 1 image texture-layer 1 4 16 (rand 200))
)
)
( gimp - message " line 429 " )
(gimp-progress-update 0.85)
(plug-in-mblur 1 image texture-layer 0 4 90 (/ width 2) (/ height 2))
( gimp - curves - spline texture - layer 0 18 # ( 0 255 31 0 62 255 91 0 127 255 159 0 190 255 223 0 255 255 ) )
(gimp-drawable-curves-spline texture-layer 0 18 #(0.0 1.0 0.12 0.0 0.24 1.0 0.35 0.0 0.5 1.0 0.61 0.0 0.74 1.0 0.87 0.0 1.0 1.0))
(plug-in-unsharp-mask 1 image texture-layer 10 1 0)
(gimp-selection-none image)
;(gimp-image-remove-channel image selection-channel)
(plug-in-bump-map 1 image inner-bevel-layer texture-layer 135 45 5 0 0 0 0 TRUE FALSE 2)
(gimp-image-remove-layer image texture-layer)
( gimp - message " line 440 " )
(gimp-progress-update 0.87)
was ( gimp - color - balance inner - bevel - layer 0 TRUE 40 0 0);shadows
(gimp-drawable-color-balance inner-bevel-layer TRANSFER-SHADOWS TRUE 50 0 0);shadows
(gimp-selection-load selection-channel)
(gimp-selection-translate image -3 -2)
(gimp-selection-invert image)
(gimp-edit-clear inner-bevel-layer)
(gimp-selection-none image)
(if (= ds-apply TRUE)
(begin
(script-fu-drop-shadow image inner-bevel-layer ds-offset ds-offset 30 '(0 0 0) 100 FALSE)
)
)
(set! image-layer (car (gimp-image-merge-visible-layers image 1)))
(gimp-drawable-set-name image-layer text)
( gimp - message " line 458 " )
(gimp-progress-update 0.90)
was 1 1 grunge - color 0
(set! image-layer (car (gimp-image-merge-visible-layers image 1)))
(gimp-drawable-set-name image-layer text)
;;;;set the different metal types
was COLOR - MODE
(gimp-image-insert-layer image metal-layer 0 -1)
(gimp-selection-load selection-channel)
(gimp-progress-update 0.92)
(if (= metal 1) (gimp-context-set-foreground '(253 208 23)));gold
(if (= metal 2)
(begin
(gimp-layer-set-mode metal-layer LAYER-MODE-GRAIN-MERGE-LEGACY)
(gimp-context-set-foreground '(192 192 192))
)
);silver
copper was 183 115 51
(if (= metal 4) (gimp-context-set-foreground '(140 120 83)));bronze
(if (= metal 5) (gimp-context-set-foreground '(181 166 66)));brass
(if (> metal 0)
(begin
(gimp-drawable-edit-fill metal-layer FILL-FOREGROUND)
)
)
(gimp-progress-update 0.94)
(set! image-layer (car (gimp-image-merge-down image metal-layer EXPAND-AS-NECESSARY)))
;(if (> metal 0)
; (begin
; (gimp-message "off to shine")
( the - antique - metal - shine image image - layer 8 50 TRUE TRUE )
; ; was F for conserve(last one)
; )
;)
(set! image-layer (car (gimp-image-get-active-layer image)))
(gimp-selection-none image)
( gimp - message " line 502 " )
(if (= frame 0)
(begin
( gimp - message " frame already zero " )
)
(begin
( gimp - message " frame above zero " )
)
)
(if (= apply-vignette FALSE)
(begin
;(gimp-message "apply vignette is FALSE")
(set! vig-size 0)
)
)
(if (= apply-frame FALSE)
(begin
;(gimp-message "apply vignettre is FALSE")
(set! frame 0)
)
)
(if (and (> vig-size 0) (= frame 0))
(begin
( gimp - message " size with zero frame " )
was 0.1
)
)
(gimp-progress-update 0.96)
( gimp - message " line 536 " )
(if (> frame 0)
(begin
( gimp - message " line 539 " )
;;;; Render Picture Frame using G'MIC.
;(gimp-message "frame start")
;(gimp-message (number->string frame))
(if (defined? 'plug-in-gmic-qt)
(begin
(plug-in-gmic-qt 1 image image-layer 1 0
(string-append
"-v - " ; To have a silent output. Remove it to display errors from the G'MIC interpreter on stderr.
"-fx_frame_painting "
(number->string frame) ",0.4,1.5,"
(number->string red) ","
(number->string green) ","
(number->string blue) ","
(number->string vig-size) ",400,98.5,62.61,6.2,0.5,117517,1")
was 98.5,70.61,6.2,0.5,123456,1
(set! image-layer (car (gimp-image-get-active-layer image)))
(gimp-drawable-set-name image-layer text)
(set! frame-layer (car (gimp-layer-new image width height RGBA-IMAGE "Frame" 100 LAYER-MODE-NORMAL-LEGACY)))
(gimp-image-insert-layer image frame-layer 0 -1)
removed by karlhof26 as it gives error
(set! frame-layer (car (gimp-image-merge-down image frame-layer EXPAND-AS-NECESSARY)))
;(gimp-message "frame end")
)
(begin
(gimp-message "no Gmic means - Frame using color")
(set! frame-layer (car (gimp-layer-new image width height RGBA-IMAGE "Frame" 100 LAYER-MODE-NORMAL-LEGACY)))
(gimp-image-insert-layer image frame-layer 0 -1)
(script-fu-addborder image frame-layer (* (/ frame 100) width) (* (/ frame 100) height) grunge-color (* frame 3))
)
)
)
)
(gimp-progress-update 0.98)
(if (and (> vig-size 0) (= apply-frame FALSE))
(gimp-drawable-set-name frame-layer "Vignette")
)
(if (= apply-frame TRUE) (gimp-drawable-set-name frame-layer "Frame"))
(if (and (> vig-size 0) (= apply-frame TRUE))
(gimp-drawable-set-name frame-layer "Frame with Vignette")
)
(if (= frame-in 0) (plug-in-autocrop 1 image image-layer))
(gimp-progress-update 0.97)
removed by karlhof26 - no need for it
;(gimp-image-set-active-layer image image-layer)
( plug - in - autocrop - layer 1 image image - layer )
;(set! offset-x (car (gimp-drawable-offsets image-layer)))
( set ! offset - y ( cadr ( gimp - drawable - offsets image - layer ) ) )
;(gimp-drawable-offset selection-channel TRUE 0 offset-x offset-y)
( gimp - message " line 540 " )
;
;;;;scale image to its original size and re-load selection
( gimp - image - scale - full image width height 2 )
;(gimp-selection-load selection-channel)
( gimp - message " line 539 " )
;
;(if (or (> vig-size 0) (> frame-in 0))
; (begin
; (gimp-image-lower-layer image image-layer)
; )
;)
;;;;finish the script
(if (= conserve FALSE)
(begin
(if (or (> vig-size 0) (= apply-frame TRUE))
(begin
(set! image-layer (car (gimp-image-merge-down image frame-layer EXPAND-AS-NECESSARY)))
)
)
)
)
(gimp-progress-update 1.0)
( gimp - message " line 622 " )
(gimp-drawable-set-name image-layer text)
(if (= keep-selection FALSE)
(begin
(gimp-selection-none image)
)
)
(if (= conserve FALSE)
(gimp-image-remove-channel image selection-channel)
)
(if (and (= conserve FALSE) (= alpha FALSE))
(begin
(gimp-layer-flatten image-layer)
)
)
;(gimp-message "Good finish OK")
(gimp-displays-flush)
(gimp-image-undo-group-end image)
(gimp-context-pop)
)
)
(script-fu-register "script-fu-antique-metal-alpha"
"Antique Metal Alpha"
"Creates an antique metal finish on an alpha image. \nfile:Antique Metal_02a.scm"
"Graechan"
"Graechan - "
"Aug 2012"
"RGB*"
SF-IMAGE "image" 0
SF-DRAWABLE "drawable" 0
SF-OPTION "Metal Finish Type" '("Iron" "Gold" "Silver" "Copper" "Bronze" "Brass")
SF-TOGGLE "Apply Drop Shadow" TRUE
SF-ADJUSTMENT "Drop shadow offset" '(10 0 100 1 10 0 1)
SF-ADJUSTMENT "Drop shadow blur radius" '(30 0 255 1 10 0 1)
SF-ADJUSTMENT "Inner Shadow and Glow Opacity" '(70 0 100 1 10 0 0)
SF-ADJUSTMENT "Bevel Width" '(10 1 100 1 10 0 0)
SF-ADJUSTMENT "Bevel Depth" '(3 1 60 1 10 0 0)
SF-TOGGLE "Apply Grunge background" TRUE
SF-COLOR "Background Grunge Color" '(153 153 186)
SF-ADJUSTMENT "Background Grunge Darkness" '(70 0 100 1 10 0 0)
SF-TOGGLE "Apply Vignette" TRUE
SF-TOGGLE "Apply Frame" TRUE
SF-ADJUSTMENT "Background Vignette Size" '(5 0 50 1 5 0 0)
SF-ADJUSTMENT "Frame Size" '(5 0 25 .1 5 1 0)
SF-TOGGLE "Keep selection" FALSE
SF-TOGGLE "Keep the Layers" FALSE
)
(script-fu-menu-register "script-fu-antique-metal-alpha" "<Image>/Script-Fu/Alpha-to-Logo")
(define (the-antique-metal-background image drawable
grunge-color
opacity)
(let* (
(image-layer (car (gimp-image-get-active-layer image)))
(width (car (gimp-image-width image)))
(height (car (gimp-image-height image)))
(paper-layer 0)
(mottle-layer 0)
(nominal-burn-size 30)
(burn-size 0)
)
;(gimp-message "inside metal background")
(set! burn-size (/ (* nominal-burn-size (max width height 1))))
(gimp-context-push)
(gimp-image-undo-group-start image)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
( gimp - message " line 690 " )
(set! paper-layer (car (gimp-layer-new image width height RGBA-IMAGE "Paper Layer" 100 LAYER-MODE-NORMAL)))
(gimp-image-insert-layer image paper-layer 0 -1)
(gimp-context-set-background grunge-color)
(gimp-drawable-edit-fill paper-layer FILL-BACKGROUND)
(plug-in-apply-canvas RUN-NONINTERACTIVE image paper-layer 0 1)
(set! mottle-layer (car (gimp-layer-new image width height RGBA-IMAGE "Mottle Layer" opacity 21)))
(gimp-image-insert-layer image mottle-layer 0 -1)
(plug-in-solid-noise RUN-NONINTERACTIVE image mottle-layer 0 0 (rand 65536) 1 2 2)
(set! paper-layer (car (gimp-image-merge-down image mottle-layer CLIP-TO-IMAGE)))
(plug-in-spread 1 image paper-layer 5 5)
( gimp - message " line 703 " )
;(gimp-message "end background")
(gimp-displays-flush)
(gimp-image-undo-group-end image)
(gimp-context-pop)
)
)
(define (the-antique-metal-shine image drawable
shadow-size
shadow-opacity
keep-selection-in
conserve)
(let* (
(image-layer (car (gimp-image-get-active-layer image)))
(width (car (gimp-image-width image)))
(height (car (gimp-image-height image)))
(sel (car (gimp-selection-is-empty image)))
(alpha (car (gimp-drawable-has-alpha image-layer)))
(keep-selection keep-selection-in)
(layer-name (car (gimp-drawable-get-name image-layer)))
(img-layer 0)
(img-channel 0)
(bkg-layer 0)
(shadow-layer 0)
(tmp-layer 0)
)
;(gimp-message "inside metal shine")
(gimp-context-push)
;;(gimp-image-undo-group-start image)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
( gimp - message " line 740 " )
(if (= alpha FALSE)
(gimp-layer-add-alpha image-layer)
)
(if (= sel TRUE)
(begin
(set! keep-selection FALSE)
(gimp-selection-layer-alpha image-layer)
)
)
(if (= sel TRUE) (gimp-selection-layer-alpha image-layer))
(set! img-layer (car (gimp-layer-new image width height RGBA-IMAGE "img-layer" 100 LAYER-MODE-NORMAL-LEGACY)))
(gimp-image-insert-layer image img-layer 0 -1)
(gimp-drawable-fill img-layer FILL-BACKGROUND)
(gimp-drawable-edit-fill img-layer FILL-FOREGROUND)
;;;;create channel
(gimp-selection-save image)
(set! img-channel (car (gimp-image-get-active-drawable image)))
was 100
(gimp-drawable-set-name img-channel "img-channel")
(gimp-image-set-active-layer image img-layer)
(gimp-drawable-set-name image-layer "Original Image")
( gimp - message " line 767 " )
;;;;create the background layer
(set! bkg-layer (car (gimp-layer-new image width height RGBA-IMAGE "Background" 100 LAYER-MODE-NORMAL-LEGACY)))
(gimp-image-insert-layer image bkg-layer 0 1)
;;;;apply the image effects
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
(plug-in-gauss-rle2 RUN-NONINTERACTIVE image img-layer 12 12)
(plug-in-emboss RUN-NONINTERACTIVE image img-layer 225 84 10 TRUE)
(gimp-selection-invert image)
(gimp-edit-clear img-layer)
( gimp - message " line 780 " )
(gimp-selection-invert image)
(plug-in-gauss-rle2 RUN-NONINTERACTIVE image img-channel 15 15)
(plug-in-blur RUN-NONINTERACTIVE image img-layer)
(gimp-image-set-active-layer image bkg-layer)
(plug-in-displace RUN-NONINTERACTIVE image bkg-layer 8 8 TRUE TRUE img-channel img-channel 2)
;(gimp-image-remove-layer image bkg-layer)
( gimp - message " line 789 " )
;;;;create the shadow
;(if (> shadow-size 0)
; (begin
( gimp - message " line 721 " )
; ;;was (script-fu-drop-shadow image img-layer shadow-size shadow-size shadow-size '(0 0 0) shadow-opacity FALSE)
( script - fu - drop - shadow image img - layer shadow - size shadow - size 3 ' ( 0 0 0 ) shadow - opacity TRUE )
( set ! tmp - layer ( car ( gimp - layer - new image width height RGBA - IMAGE " temp " 100 LAYER - MODE - NORMAL ) ) )
( gimp - image - insert - layer image tmp - layer 0 -1 )
; (gimp-image-raise-layer image tmp-layer)
; ; ( gimp - image - merge - down image tmp - layer CLIP - TO - IMAGE )
; (set! shadow-layer (car (gimp-image-get-active-drawable image)))
; (gimp-image-lower-layer image shadow-layer)
;
; )
;)
;(if (= conserve FALSE)
; (begin
( set ! ( car ( gimp - image - merge - down image img - layer EXPAND - AS - NECESSARY ) ) )
( set ! ( car ( gimp - image - merge - down image img - layer EXPAND - AS - NECESSARY ) ) )
; (gimp-drawable-set-name img-layer layer-name)
; )
;)
;
; (if (= keep-selection FALSE) (gimp-selection-none image))
; (gimp-image-remove-channel image img-channel)
; (if (and (= conserve FALSE) (= alpha FALSE) (gimp-layer-flatten img-layer)))
;;(gimp-image-undo-group-end image)
;(gimp-context-pop)
;(gimp-display-new image)
(gimp-displays-flush)
;(gimp-message "end shine")
)
)
; end of script | null | https://raw.githubusercontent.com/karlhof26/gimp-scheme/b97e730eed6a133af34a9ce32fa04d07cca4e5ab/Antique%20Metal_02a.scm | scheme | You will need to install GMIC to run this Scipt
GMIC can be downloaded from
that I followed to write this script.
Comments directed to
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
visit:
------------
| Change Log |
------------
Rel 0.03 - Bugfix for typo in script
adjust text
set the text clolor
Expand the font if needed
Was F
create selection-channel
create the background layer
(gimp-message "going to the antique metal background")
fill image with grey
create inner-shadow and inner-glow layers
create the inner shadow
create the inner glow
Add new layer with Bevel
Emboss
gloss the bevel-layer
Clean up the layers
create the texture-layer
(gimp-message "whirl start")
(defined? 'gimp-context-set-brush-size)
To have a silent output. Remove it to display errors from the G'MIC interpreter on stderr.
(gimp-image-remove-channel image selection-channel)
shadows
shadows
set the different metal types
gold
silver
bronze
brass
(if (> metal 0)
(begin
(gimp-message "off to shine")
; was F for conserve(last one)
)
)
(gimp-message "apply vignette is FALSE")
(gimp-message "apply vignettre is FALSE")
Render Picture Frame using G'MIC.
(gimp-message "frame start")
(gimp-message (number->string frame))
To have a silent output. Remove it to display errors from the G'MIC interpreter on stderr.
(gimp-message "frame end")
(gimp-image-set-active-layer image image-layer)
(set! offset-x (car (gimp-drawable-offsets image-layer)))
(gimp-drawable-offset selection-channel TRUE 0 offset-x offset-y)
scale image to its original size and re-load selection
(gimp-selection-load selection-channel)
(if (or (> vig-size 0) (> frame-in 0))
(begin
(gimp-image-lower-layer image image-layer)
)
)
finish the script
(gimp-message "Good finish OK")
(gimp-message "inside metal background")
(gimp-message "end background")
(gimp-message "inside metal shine")
(gimp-image-undo-group-start image)
create channel
create the background layer
apply the image effects
(gimp-image-remove-layer image bkg-layer)
create the shadow
(if (> shadow-size 0)
(begin
;;was (script-fu-drop-shadow image img-layer shadow-size shadow-size shadow-size '(0 0 0) shadow-opacity FALSE)
(gimp-image-raise-layer image tmp-layer)
; ( gimp - image - merge - down image tmp - layer CLIP - TO - IMAGE )
(set! shadow-layer (car (gimp-image-get-active-drawable image)))
(gimp-image-lower-layer image shadow-layer)
)
)
(if (= conserve FALSE)
(begin
(gimp-drawable-set-name img-layer layer-name)
)
)
(if (= keep-selection FALSE) (gimp-selection-none image))
(gimp-image-remove-channel image img-channel)
(if (and (= conserve FALSE) (= alpha FALSE) (gimp-layer-flatten img-layer)))
(gimp-image-undo-group-end image)
(gimp-context-pop)
(gimp-display-new image)
(gimp-message "end shine")
end of script | Antique Metal rel 0.03
Created by Graechan
Thanks to Draconian for his Antique - metal tutorial
License :
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
To view a copy of the GNU General Public License
Rel 0.01 - Initial Release
Rel 0.02 - Added text options Justify , Letter Spacing , Line Spacing and option controls for ' Drop Shadow ' ' Grunge ' ' Vignette ' ' Frame '
Rel 0.04 - Update by karlhof26 to remove Gmic dependency and messages on 27/02/2022
(define (script-fu-antique-metal-logo
text
justify
letter-spacing
line-spacing
font-in
font-size
grow
ds-apply
ds-offset
ds-blur
opacity
bev-width
depth
metal
apply-grunge
grunge-color
grunge-opacity
apply-vignette
apply-frame
vig-size
frame-in
conserve)
(let* (
(image (car (gimp-image-new 256 256 RGB)))
(border (/ font-size 4))
(font (if (> (string-length font-in) 0) font-in (car (gimp-context-get-font))))
(text-layer (car (gimp-text-fontname image -1 0 0 text border TRUE font-size PIXELS font)))
(justify (cond ((= justify 0) 2)
((= justify 1) 0)
((= justify 2) 1)))
(width (car (gimp-drawable-width text-layer)))
(height (car (gimp-drawable-height text-layer)))
(text-channel 0)
(bkg-layer 0)
(inner-shadow 0)
(inner-glow 0)
(inner-shadow-mask 0)
(inner-glow-mask 0)
(overlay-mode 0)
(add-shadow TRUE)
(add-canvas TRUE)
(add-mottling TRUE)
(nominal-burn-size 30)
(inner-bevel-layer 0)
(azimuth 135)
(elevation 35)
(postblur 3.0)
(texture-layer 0)
(red (car grunge-color))
(green (cadr grunge-color))
(blue (caddr grunge-color))
(frame-layer 0)
(frame frame-in)
)
(gimp-context-push)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
(gimp-text-layer-set-justification text-layer justify)
(gimp-text-layer-set-letter-spacing text-layer letter-spacing)
(gimp-text-layer-set-line-spacing text-layer line-spacing)
(gimp-image-resize-to-layers image)
(gimp-context-set-foreground '(0 0 0))
(gimp-selection-layer-alpha text-layer)
(gimp-drawable-edit-fill text-layer FILL-FOREGROUND)
( gimp - message " line 103 " )
(if (> grow 0)
(begin
(gimp-message "line 108 - grow")
(gimp-selection-layer-alpha text-layer)
(gimp-edit-clear text-layer)
(gimp-selection-grow image grow)
(gimp-context-set-foreground '(0 0 0))
(gimp-drawable-edit-fill text-layer FILL-FOREGROUND)
)
)
(gimp-selection-none image)
(gimp-display-new image)
(gimp-image-undo-group-start image)
( gimp - message " line 120 " )
(gimp-progress-pulse)
(script-fu-antique-metal-alpha
image
text-layer
metal
ds-apply
ds-offset
ds-blur
opacity
bev-width
depth
apply-grunge
grunge-color
grunge-opacity
apply-vignette
apply-frame
vig-size
frame
conserve)
(gimp-image-undo-group-end image)
(gimp-context-pop)
( gimp - message " good end line 137 " )
(gimp-progress-pulse)
)
)
(script-fu-register "script-fu-antique-metal-logo"
"Antique Metal Logo"
"Antque metal logo with optional metal types. \nfile:Antique Metal_02a.scm"
"Graechan"
"Graechan - "
"Aug 2012"
""
SF-TEXT "Text" "Gimp"
SF-OPTION "Justify" '("Centered" "Left" "Right")
SF-ADJUSTMENT "Letter Spacing" '(0 -100 100 1 5 0 0)
SF-ADJUSTMENT "Line Spacing" '(0 -100 100 1 5 0 0)
SF-FONT "Font" "JasmineUPC Bold"
SF-ADJUSTMENT "Font size (pixels)" '(350 100 1000 1 10 0 1)
SF-ADJUSTMENT "Expand the Font if needed" '(0 0 10 1 1 0 1)
SF-TOGGLE "Apply Drop Shadow" TRUE
SF-ADJUSTMENT "Drop shadow offset" '(10 0 100 1 10 0 1)
SF-ADJUSTMENT "Drop shadow blur radius" '(30 0 255 1 10 0 1)
SF-ADJUSTMENT "Inner Shadow and Glow Opacity" '(70 0 100 1 10 0 0)
SF-ADJUSTMENT "Bevel Width" '(10 1 100 1 10 0 0)
SF-ADJUSTMENT "Bevel Depth" '(3 1 60 1 10 0 0)
SF-OPTION "Metal Finish Type" '("Iron" "Gold" "Silver" "Copper" "Bronze" "Brass")
SF-TOGGLE "Apply Grunge background" TRUE
SF-COLOR "Background Grunge Color" '(153 153 184)
SF-ADJUSTMENT "Background Grunge Darkness" '(70 0 100 1 10 0 0)
SF-TOGGLE "Apply Vignette" TRUE
SF-TOGGLE "Apply Frame" TRUE
SF-ADJUSTMENT "Background Vignette Size" '(5 0 50 1 5 0 0)
SF-ADJUSTMENT "Frame Size %" '(5 0 20 1 5 0 0)
SF-TOGGLE "Keep the Layers" TRUE
)
(script-fu-menu-register "script-fu-antique-metal-logo" "<Image>/Script-Fu/Logos")
(define (script-fu-antique-metal-alpha image drawable
metal
ds-apply
ds-offset
ds-blur
opacity
bev-width
depth
apply-grunge
grunge-color
grunge-opacity
apply-vignette
apply-frame
vig-size
frame-in
keep-selection-in
conserve)
(let* (
(image-layer (car (gimp-image-get-active-layer image)))
(width (car (gimp-image-width image)))
(height (car (gimp-image-height image)))
(alpha (car (gimp-drawable-has-alpha image-layer)))
(sel (car (gimp-selection-is-empty image)))
(layer-name (car (gimp-drawable-get-name image-layer)))
(keep-selection keep-selection-in)
(text "Antique Metal")
(selection-channel 0)
(bkg-layer 0)
(inner-shadow 0)
(inner-glow 0)
(inner-shadow-mask 0)
(inner-glow-mask 0)
(overlay-mode 0)
(add-shadow TRUE)
(add-canvas TRUE)
(add-mottling TRUE)
(nominal-burn-size 30)
(inner-bevel-layer 0)
(azimuth 135)
(elevation 35)
(postblur 3.0)
(texture-layer 0)
(red (car grunge-color))
(green (cadr grunge-color))
(blue (caddr grunge-color))
(frame-layer 0)
(frame frame-in)
(offset-x 0)
(offset-y 0)
(offsets 0)
(metal-layer 0)
)
( gimp - message " line 239 " )
(gimp-progress-update 0.10)
(gimp-context-push)
(gimp-image-undo-group-start image)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
(if (= alpha FALSE) (gimp-layer-add-alpha image-layer))
check that a selection was made if not make one
(if (= sel TRUE) (set! keep-selection FALSE))
(if (= sel TRUE) (gimp-selection-layer-alpha image-layer))
(gimp-selection-invert image)
(gimp-edit-clear image-layer)
(gimp-selection-invert image)
( gimp - message " line 256 " )
(gimp-progress-update 0.15)
(gimp-selection-save image)
(set! selection-channel (car (gimp-image-get-active-drawable image)))
(gimp-channel-set-opacity selection-channel 100)
(gimp-drawable-set-name selection-channel "selection-channel")
(gimp-image-set-active-layer image image-layer)
(gimp-selection-none image)
(set! bkg-layer (car (gimp-layer-new image width height RGBA-IMAGE "Background" 100 LAYER-MODE-NORMAL-LEGACY)))
was 0 1
( gimp - message " line 269 " )
(if (= apply-grunge TRUE)
(begin
( gimp - message " line 273 " )
(the-antique-metal-background image bkg-layer grunge-color grunge-opacity)
(set! bkg-layer (car (gimp-image-get-active-layer image)))
(set! bkg-layer (car (gimp-image-merge-down image bkg-layer EXPAND-AS-NECESSARY)))
(gimp-drawable-set-name bkg-layer "Background")
)
)
( gimp - message " line 281 " )
(gimp-progress-update 0.20)
(gimp-selection-load selection-channel)
(gimp-context-set-foreground '(123 123 123))
(gimp-drawable-edit-fill image-layer FILL-FOREGROUND)
(set! width (car (gimp-image-width image)))
(set! height (car (gimp-image-height image)))
(gimp-selection-none image)
(gimp-layer-resize-to-image-size bkg-layer)
(gimp-layer-resize-to-image-size image-layer)
( gimp - message " line 293 " )
(set! inner-shadow (car (gimp-layer-copy image-layer TRUE)))
(gimp-image-insert-layer image inner-shadow 0 -1)
(gimp-drawable-set-name inner-shadow "Inner shadow")
(gimp-layer-set-mode inner-shadow LAYER-MODE-MULTIPLY-LEGACY)
(gimp-layer-set-opacity inner-shadow opacity)
(gimp-progress-update 0.25)
( gimp - message " line 303 " )
(set! inner-glow (car (gimp-layer-copy image-layer TRUE)))
(gimp-image-insert-layer image inner-glow 0 -1)
(gimp-drawable-set-name inner-glow "Inner glow")
(gimp-layer-set-mode inner-glow LAYER-MODE-MULTIPLY-LEGACY)
(gimp-layer-set-opacity inner-glow opacity)
(gimp-image-set-active-layer image inner-shadow)
(gimp-drawable-set-visible inner-shadow TRUE)
( gimp - message " line 313 " )
(gimp-progress-update 0.30)
(set! inner-shadow-mask (car (gimp-layer-create-mask inner-shadow ADD-MASK-ALPHA)))
(gimp-layer-add-mask inner-shadow inner-shadow-mask)
(gimp-layer-set-edit-mask inner-shadow FALSE)
(gimp-selection-load selection-channel)
(gimp-selection-shrink image (* bev-width 1.5))
(gimp-selection-invert image)
(gimp-context-set-foreground '(99 78 56))
( gimp - message " line 324 " )
was LAYER - MODE - NORMAL opacity 15.0 TRUE 0 0
(gimp-selection-none image)
(plug-in-gauss-rle RUN-NONINTERACTIVE image inner-shadow (* bev-width 3) TRUE TRUE)
( gimp - message " line 329 " )
(gimp-image-set-active-layer image inner-glow)
(gimp-drawable-set-visible inner-glow TRUE)
(gimp-selection-load selection-channel)
(gimp-edit-clear inner-glow)
(set! inner-glow-mask (car (gimp-layer-create-mask inner-glow ADD-MASK-SELECTION)))
(gimp-layer-add-mask inner-glow inner-glow-mask)
(gimp-layer-set-edit-mask inner-glow FALSE)
( gimp - message " line 340 " )
(gimp-progress-update 0.40)
(gimp-selection-shrink image bev-width)
(gimp-selection-invert image)
(gimp-context-set-foreground '(120 100 80))
was FG - BUCKET - FILL NORMAL - MODE opacity 15.0 TRUE 0 0
(gimp-selection-none image)
( gimp - message " line 348 " )
(plug-in-gauss-rle RUN-NONINTERACTIVE image inner-glow (* bev-width 2) TRUE TRUE)
(gimp-image-raise-layer-to-top image bkg-layer)
(set! image-layer (car (gimp-image-merge-visible-layers image EXPAND-AS-NECESSARY)))
(if (= apply-grunge FALSE)
(begin
( gimp - message " line 355 " )
(gimp-selection-load selection-channel)
(gimp-selection-translate image -3 -2)
(gimp-selection-invert image)
(gimp-edit-clear image-layer)
(gimp-selection-none image)
)
)
(gimp-drawable-set-name image-layer text)
( gimp - message " line 364 " )
(gimp-progress-update 0.50)
(gimp-selection-load selection-channel)
(set! inner-bevel-layer (car (gimp-layer-new image width height RGBA-IMAGE "Inner bevel" 100 LAYER-MODE-NORMAL)))
(gimp-image-insert-layer image inner-bevel-layer 0 -1)
(gimp-image-set-active-layer image inner-bevel-layer)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
( gimp - message " line 373 " )
(gimp-drawable-edit-fill inner-bevel-layer FILL-FOREGROUND)
(gimp-selection-shrink image 1)
(gimp-selection-feather image bev-width)
(gimp-selection-shrink image (- (/ bev-width 2) 1))
( gimp - message " line 379 " )
(gimp-progress-update 0.60)
(gimp-drawable-edit-fill inner-bevel-layer FILL-BACKGROUND)
(gimp-selection-all image)
( gimp - message " line 383 " )
(if (= ds-apply TRUE) (gimp-invert inner-bevel-layer))
( gimp - curves - spline inner - bevel - layer 0 18 # ( 0 0 32 158 62 30 96 223 126 96 159 255 189 160 222 255 255 255 ) )
(gimp-drawable-curves-spline inner-bevel-layer HISTOGRAM-VALUE 18 #(0.0 0.0 0.15 0.7 0.23 0.145 0.38 0.88 0.5 0.38 0.88 1.0 0.75 0.65 0.92 1.0 1.0 1.0))
(plug-in-gauss-rle RUN-NONINTERACTIVE image inner-bevel-layer postblur 1 1)
( gimp - message " line 392 " )
(gimp-progress-update 0.70)
(gimp-selection-load selection-channel)
(gimp-selection-invert image)
(gimp-edit-clear inner-bevel-layer)
(set! texture-layer (car (gimp-layer-new image width height RGBA-IMAGE "Texture" 100 LAYER-MODE-NORMAL)))
(gimp-image-insert-layer image texture-layer 0 -1)
(gimp-selection-load selection-channel)
(gimp-context-set-foreground '(123 123 123))
(gimp-drawable-edit-fill texture-layer FILL-FOREGROUND)
( gimp - progress - update 0.81 )
( gimp - message " line 407 " )
drawing using G'MIC .
(begin
( gimp - message " line413 " )
(plug-in-gmic-qt 1 image texture-layer 1 0
(string-append
"-fx_draw_whirl "
"74.70"
)
)
)
(begin
( gimp - message " No whirl Gmic is required ( from http;//gmic.eu ) " )
(plug-in-hsv-noise 1 image texture-layer 1 4 16 (rand 200))
)
)
( gimp - message " line 429 " )
(gimp-progress-update 0.85)
(plug-in-mblur 1 image texture-layer 0 4 90 (/ width 2) (/ height 2))
( gimp - curves - spline texture - layer 0 18 # ( 0 255 31 0 62 255 91 0 127 255 159 0 190 255 223 0 255 255 ) )
(gimp-drawable-curves-spline texture-layer 0 18 #(0.0 1.0 0.12 0.0 0.24 1.0 0.35 0.0 0.5 1.0 0.61 0.0 0.74 1.0 0.87 0.0 1.0 1.0))
(plug-in-unsharp-mask 1 image texture-layer 10 1 0)
(gimp-selection-none image)
(plug-in-bump-map 1 image inner-bevel-layer texture-layer 135 45 5 0 0 0 0 TRUE FALSE 2)
(gimp-image-remove-layer image texture-layer)
( gimp - message " line 440 " )
(gimp-progress-update 0.87)
(gimp-selection-load selection-channel)
(gimp-selection-translate image -3 -2)
(gimp-selection-invert image)
(gimp-edit-clear inner-bevel-layer)
(gimp-selection-none image)
(if (= ds-apply TRUE)
(begin
(script-fu-drop-shadow image inner-bevel-layer ds-offset ds-offset 30 '(0 0 0) 100 FALSE)
)
)
(set! image-layer (car (gimp-image-merge-visible-layers image 1)))
(gimp-drawable-set-name image-layer text)
( gimp - message " line 458 " )
(gimp-progress-update 0.90)
was 1 1 grunge - color 0
(set! image-layer (car (gimp-image-merge-visible-layers image 1)))
(gimp-drawable-set-name image-layer text)
was COLOR - MODE
(gimp-image-insert-layer image metal-layer 0 -1)
(gimp-selection-load selection-channel)
(gimp-progress-update 0.92)
(if (= metal 2)
(begin
(gimp-layer-set-mode metal-layer LAYER-MODE-GRAIN-MERGE-LEGACY)
(gimp-context-set-foreground '(192 192 192))
)
copper was 183 115 51
(if (> metal 0)
(begin
(gimp-drawable-edit-fill metal-layer FILL-FOREGROUND)
)
)
(gimp-progress-update 0.94)
(set! image-layer (car (gimp-image-merge-down image metal-layer EXPAND-AS-NECESSARY)))
( the - antique - metal - shine image image - layer 8 50 TRUE TRUE )
(set! image-layer (car (gimp-image-get-active-layer image)))
(gimp-selection-none image)
( gimp - message " line 502 " )
(if (= frame 0)
(begin
( gimp - message " frame already zero " )
)
(begin
( gimp - message " frame above zero " )
)
)
(if (= apply-vignette FALSE)
(begin
(set! vig-size 0)
)
)
(if (= apply-frame FALSE)
(begin
(set! frame 0)
)
)
(if (and (> vig-size 0) (= frame 0))
(begin
( gimp - message " size with zero frame " )
was 0.1
)
)
(gimp-progress-update 0.96)
( gimp - message " line 536 " )
(if (> frame 0)
(begin
( gimp - message " line 539 " )
(if (defined? 'plug-in-gmic-qt)
(begin
(plug-in-gmic-qt 1 image image-layer 1 0
(string-append
"-fx_frame_painting "
(number->string frame) ",0.4,1.5,"
(number->string red) ","
(number->string green) ","
(number->string blue) ","
(number->string vig-size) ",400,98.5,62.61,6.2,0.5,117517,1")
was 98.5,70.61,6.2,0.5,123456,1
(set! image-layer (car (gimp-image-get-active-layer image)))
(gimp-drawable-set-name image-layer text)
(set! frame-layer (car (gimp-layer-new image width height RGBA-IMAGE "Frame" 100 LAYER-MODE-NORMAL-LEGACY)))
(gimp-image-insert-layer image frame-layer 0 -1)
removed by karlhof26 as it gives error
(set! frame-layer (car (gimp-image-merge-down image frame-layer EXPAND-AS-NECESSARY)))
)
(begin
(gimp-message "no Gmic means - Frame using color")
(set! frame-layer (car (gimp-layer-new image width height RGBA-IMAGE "Frame" 100 LAYER-MODE-NORMAL-LEGACY)))
(gimp-image-insert-layer image frame-layer 0 -1)
(script-fu-addborder image frame-layer (* (/ frame 100) width) (* (/ frame 100) height) grunge-color (* frame 3))
)
)
)
)
(gimp-progress-update 0.98)
(if (and (> vig-size 0) (= apply-frame FALSE))
(gimp-drawable-set-name frame-layer "Vignette")
)
(if (= apply-frame TRUE) (gimp-drawable-set-name frame-layer "Frame"))
(if (and (> vig-size 0) (= apply-frame TRUE))
(gimp-drawable-set-name frame-layer "Frame with Vignette")
)
(if (= frame-in 0) (plug-in-autocrop 1 image image-layer))
(gimp-progress-update 0.97)
removed by karlhof26 - no need for it
( plug - in - autocrop - layer 1 image image - layer )
( set ! offset - y ( cadr ( gimp - drawable - offsets image - layer ) ) )
( gimp - message " line 540 " )
( gimp - image - scale - full image width height 2 )
( gimp - message " line 539 " )
(if (= conserve FALSE)
(begin
(if (or (> vig-size 0) (= apply-frame TRUE))
(begin
(set! image-layer (car (gimp-image-merge-down image frame-layer EXPAND-AS-NECESSARY)))
)
)
)
)
(gimp-progress-update 1.0)
( gimp - message " line 622 " )
(gimp-drawable-set-name image-layer text)
(if (= keep-selection FALSE)
(begin
(gimp-selection-none image)
)
)
(if (= conserve FALSE)
(gimp-image-remove-channel image selection-channel)
)
(if (and (= conserve FALSE) (= alpha FALSE))
(begin
(gimp-layer-flatten image-layer)
)
)
(gimp-displays-flush)
(gimp-image-undo-group-end image)
(gimp-context-pop)
)
)
(script-fu-register "script-fu-antique-metal-alpha"
"Antique Metal Alpha"
"Creates an antique metal finish on an alpha image. \nfile:Antique Metal_02a.scm"
"Graechan"
"Graechan - "
"Aug 2012"
"RGB*"
SF-IMAGE "image" 0
SF-DRAWABLE "drawable" 0
SF-OPTION "Metal Finish Type" '("Iron" "Gold" "Silver" "Copper" "Bronze" "Brass")
SF-TOGGLE "Apply Drop Shadow" TRUE
SF-ADJUSTMENT "Drop shadow offset" '(10 0 100 1 10 0 1)
SF-ADJUSTMENT "Drop shadow blur radius" '(30 0 255 1 10 0 1)
SF-ADJUSTMENT "Inner Shadow and Glow Opacity" '(70 0 100 1 10 0 0)
SF-ADJUSTMENT "Bevel Width" '(10 1 100 1 10 0 0)
SF-ADJUSTMENT "Bevel Depth" '(3 1 60 1 10 0 0)
SF-TOGGLE "Apply Grunge background" TRUE
SF-COLOR "Background Grunge Color" '(153 153 186)
SF-ADJUSTMENT "Background Grunge Darkness" '(70 0 100 1 10 0 0)
SF-TOGGLE "Apply Vignette" TRUE
SF-TOGGLE "Apply Frame" TRUE
SF-ADJUSTMENT "Background Vignette Size" '(5 0 50 1 5 0 0)
SF-ADJUSTMENT "Frame Size" '(5 0 25 .1 5 1 0)
SF-TOGGLE "Keep selection" FALSE
SF-TOGGLE "Keep the Layers" FALSE
)
(script-fu-menu-register "script-fu-antique-metal-alpha" "<Image>/Script-Fu/Alpha-to-Logo")
(define (the-antique-metal-background image drawable
grunge-color
opacity)
(let* (
(image-layer (car (gimp-image-get-active-layer image)))
(width (car (gimp-image-width image)))
(height (car (gimp-image-height image)))
(paper-layer 0)
(mottle-layer 0)
(nominal-burn-size 30)
(burn-size 0)
)
(set! burn-size (/ (* nominal-burn-size (max width height 1))))
(gimp-context-push)
(gimp-image-undo-group-start image)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
( gimp - message " line 690 " )
(set! paper-layer (car (gimp-layer-new image width height RGBA-IMAGE "Paper Layer" 100 LAYER-MODE-NORMAL)))
(gimp-image-insert-layer image paper-layer 0 -1)
(gimp-context-set-background grunge-color)
(gimp-drawable-edit-fill paper-layer FILL-BACKGROUND)
(plug-in-apply-canvas RUN-NONINTERACTIVE image paper-layer 0 1)
(set! mottle-layer (car (gimp-layer-new image width height RGBA-IMAGE "Mottle Layer" opacity 21)))
(gimp-image-insert-layer image mottle-layer 0 -1)
(plug-in-solid-noise RUN-NONINTERACTIVE image mottle-layer 0 0 (rand 65536) 1 2 2)
(set! paper-layer (car (gimp-image-merge-down image mottle-layer CLIP-TO-IMAGE)))
(plug-in-spread 1 image paper-layer 5 5)
( gimp - message " line 703 " )
(gimp-displays-flush)
(gimp-image-undo-group-end image)
(gimp-context-pop)
)
)
(define (the-antique-metal-shine image drawable
shadow-size
shadow-opacity
keep-selection-in
conserve)
(let* (
(image-layer (car (gimp-image-get-active-layer image)))
(width (car (gimp-image-width image)))
(height (car (gimp-image-height image)))
(sel (car (gimp-selection-is-empty image)))
(alpha (car (gimp-drawable-has-alpha image-layer)))
(keep-selection keep-selection-in)
(layer-name (car (gimp-drawable-get-name image-layer)))
(img-layer 0)
(img-channel 0)
(bkg-layer 0)
(shadow-layer 0)
(tmp-layer 0)
)
(gimp-context-push)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
( gimp - message " line 740 " )
(if (= alpha FALSE)
(gimp-layer-add-alpha image-layer)
)
(if (= sel TRUE)
(begin
(set! keep-selection FALSE)
(gimp-selection-layer-alpha image-layer)
)
)
(if (= sel TRUE) (gimp-selection-layer-alpha image-layer))
(set! img-layer (car (gimp-layer-new image width height RGBA-IMAGE "img-layer" 100 LAYER-MODE-NORMAL-LEGACY)))
(gimp-image-insert-layer image img-layer 0 -1)
(gimp-drawable-fill img-layer FILL-BACKGROUND)
(gimp-drawable-edit-fill img-layer FILL-FOREGROUND)
(gimp-selection-save image)
(set! img-channel (car (gimp-image-get-active-drawable image)))
was 100
(gimp-drawable-set-name img-channel "img-channel")
(gimp-image-set-active-layer image img-layer)
(gimp-drawable-set-name image-layer "Original Image")
( gimp - message " line 767 " )
(set! bkg-layer (car (gimp-layer-new image width height RGBA-IMAGE "Background" 100 LAYER-MODE-NORMAL-LEGACY)))
(gimp-image-insert-layer image bkg-layer 0 1)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(255 255 255))
(plug-in-gauss-rle2 RUN-NONINTERACTIVE image img-layer 12 12)
(plug-in-emboss RUN-NONINTERACTIVE image img-layer 225 84 10 TRUE)
(gimp-selection-invert image)
(gimp-edit-clear img-layer)
( gimp - message " line 780 " )
(gimp-selection-invert image)
(plug-in-gauss-rle2 RUN-NONINTERACTIVE image img-channel 15 15)
(plug-in-blur RUN-NONINTERACTIVE image img-layer)
(gimp-image-set-active-layer image bkg-layer)
(plug-in-displace RUN-NONINTERACTIVE image bkg-layer 8 8 TRUE TRUE img-channel img-channel 2)
( gimp - message " line 789 " )
( gimp - message " line 721 " )
( script - fu - drop - shadow image img - layer shadow - size shadow - size 3 ' ( 0 0 0 ) shadow - opacity TRUE )
( set ! tmp - layer ( car ( gimp - layer - new image width height RGBA - IMAGE " temp " 100 LAYER - MODE - NORMAL ) ) )
( gimp - image - insert - layer image tmp - layer 0 -1 )
( set ! ( car ( gimp - image - merge - down image img - layer EXPAND - AS - NECESSARY ) ) )
( set ! ( car ( gimp - image - merge - down image img - layer EXPAND - AS - NECESSARY ) ) )
(gimp-displays-flush)
)
)
|
2b68a1514c550228597380e182090c681553ef9b1199ea0e4452a38e06381a5a | novaframework/nova | nova_cors_plugin.erl | -module(nova_cors_plugin).
-behaviour(nova_plugin).
-export([
pre_request/2,
post_request/2,
plugin_info/0
]).
%%--------------------------------------------------------------------
%% @doc
%% Pre-request callback
%% @end
%%--------------------------------------------------------------------
-spec pre_request(Req :: cowboy_req:req(), Options :: map()) ->
{ok, Req0 :: cowboy_req:req()}.
pre_request(Req, Options) ->
ParsedOptions = nova_plugin_utilities:parse_options(Options),
ReqWithOptions = set_headers(Req, ParsedOptions),
continue(ReqWithOptions).
%%--------------------------------------------------------------------
%% @doc
%% Post-request callback
%% @end
%%--------------------------------------------------------------------
-spec post_request(Req :: cowboy_req:req(), Options :: map()) ->
{ok, Req0 :: cowboy_req:req()}.
post_request(Req, _) ->
{ok, Req}.
%%--------------------------------------------------------------------
%% @doc
%% nova_plugin callback. Returns information about the plugin.
%% @end
%%--------------------------------------------------------------------
-spec plugin_info() -> {Title :: binary(),
Version :: binary(),
Author :: binary(),
Description :: binary(),
Options :: [{Key :: atom(), OptionDescription :: binary()}]}.
plugin_info() ->
{
<<"nova_cors_plugin">>,
<<"0.2.0">>,
<<"Nova team <">>,
<<"Add CORS headers to request">>,
[
{
allow_origins,
<<"Specifies which origins to insert into Access-Control-Allow-Origin">>
}
]}.
%%%%%%%%%%%%%%%%%%%%%%
%% Private functions
%%%%%%%%%%%%%%%%%%%%%%
continue(#{method := <<"OPTIONS">>} = Req) ->
Reply = cowboy_req:reply(200, Req),
{stop, Reply};
continue(Req) ->
{ok, Req}.
set_headers(Req, []) -> Req;
set_headers(Req, [{allow_origins, Origins}|T]) ->
CorsReq = add_cors_headers(Req, Origins),
set_headers(CorsReq, T);
set_headers(Req, [_H|T]) ->
set_headers(Req, T).
add_cors_headers(Req, Origins) ->
OriginsReq = cowboy_req:set_resp_header(
<<"Access-Control-Allow-Origin">>, Origins, Req),
HeadersReq = cowboy_req:set_resp_header(
<<"Access-Control-Allow-Headers">>, <<"*">>, OriginsReq),
cowboy_req:set_resp_header(
<<"Access-Control-Allow-Methods">>, <<"*">>, HeadersReq).
| null | https://raw.githubusercontent.com/novaframework/nova/481120d112b4243c43995eadb4fdf3552d7dfd55/src/plugins/nova_cors_plugin.erl | erlang | --------------------------------------------------------------------
@doc
Pre-request callback
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Post-request callback
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
nova_plugin callback. Returns information about the plugin.
@end
--------------------------------------------------------------------
Private functions
| -module(nova_cors_plugin).
-behaviour(nova_plugin).
-export([
pre_request/2,
post_request/2,
plugin_info/0
]).
-spec pre_request(Req :: cowboy_req:req(), Options :: map()) ->
{ok, Req0 :: cowboy_req:req()}.
pre_request(Req, Options) ->
ParsedOptions = nova_plugin_utilities:parse_options(Options),
ReqWithOptions = set_headers(Req, ParsedOptions),
continue(ReqWithOptions).
-spec post_request(Req :: cowboy_req:req(), Options :: map()) ->
{ok, Req0 :: cowboy_req:req()}.
post_request(Req, _) ->
{ok, Req}.
-spec plugin_info() -> {Title :: binary(),
Version :: binary(),
Author :: binary(),
Description :: binary(),
Options :: [{Key :: atom(), OptionDescription :: binary()}]}.
plugin_info() ->
{
<<"nova_cors_plugin">>,
<<"0.2.0">>,
<<"Nova team <">>,
<<"Add CORS headers to request">>,
[
{
allow_origins,
<<"Specifies which origins to insert into Access-Control-Allow-Origin">>
}
]}.
continue(#{method := <<"OPTIONS">>} = Req) ->
Reply = cowboy_req:reply(200, Req),
{stop, Reply};
continue(Req) ->
{ok, Req}.
set_headers(Req, []) -> Req;
set_headers(Req, [{allow_origins, Origins}|T]) ->
CorsReq = add_cors_headers(Req, Origins),
set_headers(CorsReq, T);
set_headers(Req, [_H|T]) ->
set_headers(Req, T).
add_cors_headers(Req, Origins) ->
OriginsReq = cowboy_req:set_resp_header(
<<"Access-Control-Allow-Origin">>, Origins, Req),
HeadersReq = cowboy_req:set_resp_header(
<<"Access-Control-Allow-Headers">>, <<"*">>, OriginsReq),
cowboy_req:set_resp_header(
<<"Access-Control-Allow-Methods">>, <<"*">>, HeadersReq).
|
a810aebada3e5475b520c982141e49e5ff2bdd5a71d3470da34cd584d7501f98 | exercism/erlang | run_length_encoding_tests.erl | Generated with ' v0.2.0 '
%% Revision 1 of the exercises generator was used
%% -specifications/raw/a7576988aa2dafb38544c041c104603d39ac41bc/exercises/run-length-encoding/canonical-data.json
%% This file is automatically generated from the exercises canonical data.
-module(run_length_encoding_tests).
-include_lib("erl_exercism/include/exercism.hrl").
-include_lib("eunit/include/eunit.hrl").
'1_empty_string_test_'() ->
{"empty string",
?_assertEqual([], run_length_encoding:encode([]))}.
'2_single_characters_only_are_encoded_without_count_test_'() ->
{"single characters only are encoded without "
"count",
?_assertEqual("XYZ",
run_length_encoding:encode("XYZ"))}.
'3_string_with_no_single_characters_test_'() ->
{"string with no single characters",
?_assertEqual("2A3B4C",
run_length_encoding:encode("AABBBCCCC"))}.
'4_single_characters_mixed_with_repeated_characters_test_'() ->
{"single characters mixed with repeated "
"characters",
?_assertEqual("12WB12W3B24WB",
run_length_encoding:encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWW"
"WWWWWWWB"))}.
'5_multiple_whitespace_mixed_in_string_test_'() ->
{"multiple whitespace mixed in string",
?_assertEqual("2 hs2q q2w2 ",
run_length_encoding:encode(" hsqq qww "))}.
'6_lowercase_characters_test_'() ->
{"lowercase characters",
?_assertEqual("2a3b4c",
run_length_encoding:encode("aabbbcccc"))}.
'7_empty_string_test_'() ->
{"empty string",
?_assertEqual([], run_length_encoding:decode([]))}.
'8_single_characters_only_test_'() ->
{"single characters only",
?_assertEqual("XYZ",
run_length_encoding:decode("XYZ"))}.
'9_string_with_no_single_characters_test_'() ->
{"string with no single characters",
?_assertEqual("AABBBCCCC",
run_length_encoding:decode("2A3B4C"))}.
'10_single_characters_with_repeated_characters_test_'() ->
{"single characters with repeated characters",
?_assertEqual("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWW"
"WWWWWWWB",
run_length_encoding:decode("12WB12W3B24WB"))}.
'11_multiple_whitespace_mixed_in_string_test_'() ->
{"multiple whitespace mixed in string",
?_assertEqual(" hsqq qww ",
run_length_encoding:decode("2 hs2q q2w2 "))}.
'12_lowercase_string_test_'() ->
{"lowercase string",
?_assertEqual("aabbbcccc",
run_length_encoding:decode("2a3b4c"))}.
'13_encode_followed_by_decode_gives_original_string_test_'() ->
{"encode followed by decode gives original "
"string",
?_assertEqual("zzz ZZ zZ",
run_length_encoding:decode(run_length_encoding:encode("zzz ZZ zZ")))}.
| null | https://raw.githubusercontent.com/exercism/erlang/57ac2707dae643682950715e74eb271f732e2100/exercises/practice/run-length-encoding/test/run_length_encoding_tests.erl | erlang | Revision 1 of the exercises generator was used
-specifications/raw/a7576988aa2dafb38544c041c104603d39ac41bc/exercises/run-length-encoding/canonical-data.json
This file is automatically generated from the exercises canonical data. | Generated with ' v0.2.0 '
-module(run_length_encoding_tests).
-include_lib("erl_exercism/include/exercism.hrl").
-include_lib("eunit/include/eunit.hrl").
'1_empty_string_test_'() ->
{"empty string",
?_assertEqual([], run_length_encoding:encode([]))}.
'2_single_characters_only_are_encoded_without_count_test_'() ->
{"single characters only are encoded without "
"count",
?_assertEqual("XYZ",
run_length_encoding:encode("XYZ"))}.
'3_string_with_no_single_characters_test_'() ->
{"string with no single characters",
?_assertEqual("2A3B4C",
run_length_encoding:encode("AABBBCCCC"))}.
'4_single_characters_mixed_with_repeated_characters_test_'() ->
{"single characters mixed with repeated "
"characters",
?_assertEqual("12WB12W3B24WB",
run_length_encoding:encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWW"
"WWWWWWWB"))}.
'5_multiple_whitespace_mixed_in_string_test_'() ->
{"multiple whitespace mixed in string",
?_assertEqual("2 hs2q q2w2 ",
run_length_encoding:encode(" hsqq qww "))}.
'6_lowercase_characters_test_'() ->
{"lowercase characters",
?_assertEqual("2a3b4c",
run_length_encoding:encode("aabbbcccc"))}.
'7_empty_string_test_'() ->
{"empty string",
?_assertEqual([], run_length_encoding:decode([]))}.
'8_single_characters_only_test_'() ->
{"single characters only",
?_assertEqual("XYZ",
run_length_encoding:decode("XYZ"))}.
'9_string_with_no_single_characters_test_'() ->
{"string with no single characters",
?_assertEqual("AABBBCCCC",
run_length_encoding:decode("2A3B4C"))}.
'10_single_characters_with_repeated_characters_test_'() ->
{"single characters with repeated characters",
?_assertEqual("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWW"
"WWWWWWWB",
run_length_encoding:decode("12WB12W3B24WB"))}.
'11_multiple_whitespace_mixed_in_string_test_'() ->
{"multiple whitespace mixed in string",
?_assertEqual(" hsqq qww ",
run_length_encoding:decode("2 hs2q q2w2 "))}.
'12_lowercase_string_test_'() ->
{"lowercase string",
?_assertEqual("aabbbcccc",
run_length_encoding:decode("2a3b4c"))}.
'13_encode_followed_by_decode_gives_original_string_test_'() ->
{"encode followed by decode gives original "
"string",
?_assertEqual("zzz ZZ zZ",
run_length_encoding:decode(run_length_encoding:encode("zzz ZZ zZ")))}.
|
29e2080151ac080325d0922a4d1d9e8e2e2564879524772864b74189839bcd28 | mpickering/apply-refact | Structure16.hs | foo = case v of _ | False -> x | null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Structure16.hs | haskell | foo = case v of _ | False -> x |
|
fc1dc6236ad69d383802b36e71c250f36c2527c83ab5bfb91d3d0694e9ec3441 | ruricolist/serapeum | clos.lisp | (in-package :serapeum.tests)
(def-suite clos :in serapeum)
(in-suite clos)
(defclass clos-example ()
((slot1 :initarg :slot1
:reader clos-example-slot)))
(defmethods clos-example (self slot1)
(declare (symbol slot1))
(:method clos-example-1 (self)
slot1))
(defmethods clos-example (self (slot slot1))
(declare (symbol slot))
(:method clos-example-2 (self)
slot))
(defmethods clos-example (self (slot #'clos-example-slot))
(declare (symbol slot))
(:method clos-example-3 (self)
slot))
(test defmethods
(let ((object (make 'clos-example :slot1 'x)))
(is (eql 'x (clos-example-1 object)))
(is (eql 'x (clos-example-2 object)))
(is (eql 'x (clos-example-3 object)))))
(defclass has-no-slots () ())
(defclass has-count-slot ()
((count)))
(defclass has-foo-slot ()
((foo :initarg :foo)))
(defclass has-foo-slot/default ()
((foo :initarg :foo)))
(defmethod slot-unbound
((class t)
(instance has-foo-slot/default)
(slot-name (eql 'foo)))
(setf (slot-value instance 'foo) :foo))
(test slot-value-safe
(is (equal '(nil nil nil)
(multiple-value-list
(slot-value-safe (make 'has-no-slots) 'foo))))
(is (equal '(0 nil nil)
(multiple-value-list
(slot-value-safe (make 'has-no-slots) 'foo 0))))
(is (equal '(nil nil t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot) 'foo))))
(is (equal '(0 nil t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot) 'foo 0))))
(is (equal '(nil t t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot :foo nil)
'foo))))
(is (equal '(:foo t t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot :foo :foo)
'foo))))
(is (equal '(:foo t t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot/default :foo :foo)
'foo))))
(is (equal '(:foo nil t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot/default)
'foo)))))
(test setf-slot-value-safe
(let ((c (make 'has-count-slot)))
(incf (slot-value-safe c 'count 0))
(is (eql (slot-value c 'count) 1))))
(defclass a-foo () ())
(defun make-foo () (make 'a-foo))
#+sbcl
(test reject-implausible-function
(signals warning
(compile nil '(lambda () (first (make-foo))))))
(defgeneric ctx-fn (x &key keyword)
(:method-combination standard/context)
(:method :context ((x t) &key (keyword nil keyword-supplied?))
(list* keyword keyword-supplied? (call-next-method)))
(:method ((x number) &key (keyword 'other))
(list x keyword)))
(defgeneric ard-fn (x &key keyword)
(:method :around ((x t) &key (keyword nil keyword-supplied?))
(list* keyword keyword-supplied? (call-next-method)))
(:method ((x number) &key (keyword 'other))
(list x keyword)))
(test context-keyword-defaults
(is (equal* (ctx-fn 1) (ard-fn 1) '(list other nil 1 other)))
(is (equal* (ctx-fn 1 :keyword 'given)
(ard-fn 1 :keyword 'given)
'(list given t 1 given))))
(test find-class-safe
(is (null (find-class-safe 'this-class-does-not-exist))))
| null | https://raw.githubusercontent.com/ruricolist/serapeum/2e0007535d1b237a3ed457986afb37f545d1990a/tests/clos.lisp | lisp | (in-package :serapeum.tests)
(def-suite clos :in serapeum)
(in-suite clos)
(defclass clos-example ()
((slot1 :initarg :slot1
:reader clos-example-slot)))
(defmethods clos-example (self slot1)
(declare (symbol slot1))
(:method clos-example-1 (self)
slot1))
(defmethods clos-example (self (slot slot1))
(declare (symbol slot))
(:method clos-example-2 (self)
slot))
(defmethods clos-example (self (slot #'clos-example-slot))
(declare (symbol slot))
(:method clos-example-3 (self)
slot))
(test defmethods
(let ((object (make 'clos-example :slot1 'x)))
(is (eql 'x (clos-example-1 object)))
(is (eql 'x (clos-example-2 object)))
(is (eql 'x (clos-example-3 object)))))
(defclass has-no-slots () ())
(defclass has-count-slot ()
((count)))
(defclass has-foo-slot ()
((foo :initarg :foo)))
(defclass has-foo-slot/default ()
((foo :initarg :foo)))
(defmethod slot-unbound
((class t)
(instance has-foo-slot/default)
(slot-name (eql 'foo)))
(setf (slot-value instance 'foo) :foo))
(test slot-value-safe
(is (equal '(nil nil nil)
(multiple-value-list
(slot-value-safe (make 'has-no-slots) 'foo))))
(is (equal '(0 nil nil)
(multiple-value-list
(slot-value-safe (make 'has-no-slots) 'foo 0))))
(is (equal '(nil nil t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot) 'foo))))
(is (equal '(0 nil t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot) 'foo 0))))
(is (equal '(nil t t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot :foo nil)
'foo))))
(is (equal '(:foo t t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot :foo :foo)
'foo))))
(is (equal '(:foo t t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot/default :foo :foo)
'foo))))
(is (equal '(:foo nil t)
(multiple-value-list
(slot-value-safe (make 'has-foo-slot/default)
'foo)))))
(test setf-slot-value-safe
(let ((c (make 'has-count-slot)))
(incf (slot-value-safe c 'count 0))
(is (eql (slot-value c 'count) 1))))
(defclass a-foo () ())
(defun make-foo () (make 'a-foo))
#+sbcl
(test reject-implausible-function
(signals warning
(compile nil '(lambda () (first (make-foo))))))
(defgeneric ctx-fn (x &key keyword)
(:method-combination standard/context)
(:method :context ((x t) &key (keyword nil keyword-supplied?))
(list* keyword keyword-supplied? (call-next-method)))
(:method ((x number) &key (keyword 'other))
(list x keyword)))
(defgeneric ard-fn (x &key keyword)
(:method :around ((x t) &key (keyword nil keyword-supplied?))
(list* keyword keyword-supplied? (call-next-method)))
(:method ((x number) &key (keyword 'other))
(list x keyword)))
(test context-keyword-defaults
(is (equal* (ctx-fn 1) (ard-fn 1) '(list other nil 1 other)))
(is (equal* (ctx-fn 1 :keyword 'given)
(ard-fn 1 :keyword 'given)
'(list given t 1 given))))
(test find-class-safe
(is (null (find-class-safe 'this-class-does-not-exist))))
|
|
e0753fd78417c1c13e5552aef5e35cf84fcb094afde78092702d8140a049d59c | CommonDoc/common-doc | nodes.lisp | (in-package :common-doc)
(make-document "My Document"
:children
(list
(make-section (list (make-text "Introduction"))
:children
(list
(make-paragraph
(list (make-text "...")))))))
COMMON-DOC> (dump my-doc)
document
section
paragraph
text-node
"..."
CL-USER> (in-package :common-doc)
#<PACKAGE "COMMON-DOC">
COMMON-DOC> (text (make-text "Hello, world!"))
"Hello, world!"
COMMON-DOC> (children (make-paragraph
(list (make-text "This is ")
(make-text "a test"))))
(#<TEXT-NODE text: This is > #<TEXT-NODE text: a test>)
COMMON-DOC> (children (make-paragraph (list (make-text "This is ") (make-text "a test"))))
(#<TEXT-NODE text: This is > #<TEXT-NODE text: a test>)
COMMON-DOC> (make-code-block "lisp" (list (make-text "(progn ...)")))
#<CODE-BLOCK children: TEXT-NODE>
COMMON-DOC> (language *)
"lisp"
COMMON-DOC> (children **)
(#<TEXT-NODE text: (progn ...)>)
| null | https://raw.githubusercontent.com/CommonDoc/common-doc/66cabe67241449a1c0e2cbdc955a60c9439869e6/docs/nodes.lisp | lisp | (in-package :common-doc)
(make-document "My Document"
:children
(list
(make-section (list (make-text "Introduction"))
:children
(list
(make-paragraph
(list (make-text "...")))))))
COMMON-DOC> (dump my-doc)
document
section
paragraph
text-node
"..."
CL-USER> (in-package :common-doc)
#<PACKAGE "COMMON-DOC">
COMMON-DOC> (text (make-text "Hello, world!"))
"Hello, world!"
COMMON-DOC> (children (make-paragraph
(list (make-text "This is ")
(make-text "a test"))))
(#<TEXT-NODE text: This is > #<TEXT-NODE text: a test>)
COMMON-DOC> (children (make-paragraph (list (make-text "This is ") (make-text "a test"))))
(#<TEXT-NODE text: This is > #<TEXT-NODE text: a test>)
COMMON-DOC> (make-code-block "lisp" (list (make-text "(progn ...)")))
#<CODE-BLOCK children: TEXT-NODE>
COMMON-DOC> (language *)
"lisp"
COMMON-DOC> (children **)
(#<TEXT-NODE text: (progn ...)>)
|
|
76be21080faa884eaf72648319b0287ed53f9f279ed5f235e98443421de3f4e3 | malthe/bs-virtualdom | virtualdom_types.ml | open Virtualdom_events
type ('a, 'b) handler = 'a Dom.event_like -> 'b option
type 'a t =
Attached of 'a vnode
| Attribute of string option * string * string
| Component : (
('b -> 'c t) *
(('c -> unit) -> 'c -> 'a) *
'b *
('c t * EventSet.t * EventSet.t) option
) -> 'a t
| ClassName of string
| Detached of
string option * string *
(Dom.element -> 'a option) option *
(Dom.element -> Dom.element -> unit) option *
'a t array
| EventListener : EventSet.t * bool * ('event, 'a) handler -> 'a t
| Index of (Js.Dict.key * 'a t) array
| Property of string * string
| RemoveTransition of string option * 'a t array * bool
| Skip
| Style of string * string * bool
| Text of Dom.text option * string
| Thunk : ('c * ('c -> 'a t) *
('a t * EventSet.t * EventSet.t) option
) -> 'a t
| Wedge of ('a t array * (EventSet.t * EventSet.t) option)
and 'a vnode = {
element : Dom.element;
namespace : string option;
selector : string;
directives : 'a t array;
detached : 'a t option;
enabledEvents : EventSet.t;
passiveEvents : EventSet.t;
onRemove : (Dom.element -> Dom.element -> unit) option;
}
type ('a, 'b) listener =
?passive:bool -> ('b -> 'a option) -> 'a t
| null | https://raw.githubusercontent.com/malthe/bs-virtualdom/ed57fa83b6b5258218de4fafb03dd2a7b3e12565/src/virtualdom_types.ml | ocaml | open Virtualdom_events
type ('a, 'b) handler = 'a Dom.event_like -> 'b option
type 'a t =
Attached of 'a vnode
| Attribute of string option * string * string
| Component : (
('b -> 'c t) *
(('c -> unit) -> 'c -> 'a) *
'b *
('c t * EventSet.t * EventSet.t) option
) -> 'a t
| ClassName of string
| Detached of
string option * string *
(Dom.element -> 'a option) option *
(Dom.element -> Dom.element -> unit) option *
'a t array
| EventListener : EventSet.t * bool * ('event, 'a) handler -> 'a t
| Index of (Js.Dict.key * 'a t) array
| Property of string * string
| RemoveTransition of string option * 'a t array * bool
| Skip
| Style of string * string * bool
| Text of Dom.text option * string
| Thunk : ('c * ('c -> 'a t) *
('a t * EventSet.t * EventSet.t) option
) -> 'a t
| Wedge of ('a t array * (EventSet.t * EventSet.t) option)
and 'a vnode = {
element : Dom.element;
namespace : string option;
selector : string;
directives : 'a t array;
detached : 'a t option;
enabledEvents : EventSet.t;
passiveEvents : EventSet.t;
onRemove : (Dom.element -> Dom.element -> unit) option;
}
type ('a, 'b) listener =
?passive:bool -> ('b -> 'a option) -> 'a t
|
|
01ecd6f8a56b555593a7ca31535929263b61019a5f331d3a0c2a79159653911d | softwarelanguageslab/maf | R5RS_gambit_mazefun-2.scm | ; Changes:
* removed : 0
* added : 1
* swaps : 0
* negated predicates : 1
* swapped branches : 1
* calls to i d fun : 8
(letrec ((foldr (lambda (f base lst)
(letrec ((foldr-aux (lambda (lst)
(if (null? lst)
base
(f (car lst) (foldr-aux (cdr lst)))))))
(foldr-aux lst))))
(foldl (lambda (f base lst)
(<change>
(letrec ((foldl-aux (lambda (base lst)
(if (null? lst)
base
(foldl-aux (f base (car lst)) (cdr lst))))))
(foldl-aux base lst))
((lambda (x) x)
(letrec ((foldl-aux (lambda (base lst)
(if (null? lst)
base
(foldl-aux (f base (car lst)) (cdr lst))))))
(<change>
(foldl-aux base lst)
((lambda (x) x) (foldl-aux base lst))))))))
(for (lambda (lo hi f)
(<change>
(letrec ((for-aux (lambda (lo)
(if (< lo hi)
(cons (f lo) (for-aux (+ lo 1)))
()))))
(for-aux lo))
((lambda (x) x)
(letrec ((for-aux (lambda (lo)
(if (< lo hi)
(cons (f lo) (for-aux (+ lo 1)))
()))))
(for-aux lo))))))
(concat (lambda (lists)
(foldr append () lists)))
(list-read (lambda (lst i)
(if (= i 0)
(car lst)
(list-read (cdr lst) (- i 1)))))
(list-write (lambda (lst i val)
(if (= i 0)
(cons val (cdr lst))
(cons (car lst) (list-write (cdr lst) (- i 1) val)))))
(list-remove-pos (lambda (lst i)
(if (= i 0)
(cdr lst)
(cons (car lst) (list-remove-pos (cdr lst) (- i 1))))))
(duplicates? (lambda (lst)
(if (null? lst)
#f
(let ((__or_res (member (car lst) (cdr lst))))
(if __or_res __or_res (duplicates? (cdr lst)))))))
(make-matrix (lambda (n m init)
(for 0 n (lambda (i) (for 0 m (lambda (j) (init i j)))))))
(matrix-read (lambda (mat i j)
(<change>
(list-read (list-read mat i) j)
((lambda (x) x) (list-read (list-read mat i) j)))))
(matrix-write (lambda (mat i j val)
(<change>
()
i)
(list-write mat i (list-write (list-read mat i) j val))))
(matrix-size (lambda (mat)
(cons (length mat) (length (car mat)))))
(matrix-map (lambda (f mat)
(map (lambda (lst) (map f lst)) mat)))
(initial-random 0)
(next-random (lambda (current-random)
(remainder (+ (* current-random 3581) 12751) 131072)))
(shuffle (lambda (lst)
(shuffle-aux lst initial-random)))
(shuffle-aux (lambda (lst current-random)
(<change>
(if (null? lst)
()
(let ((new-random (next-random current-random)))
(let ((i (modulo new-random (length lst))))
(cons (list-read lst i) (shuffle-aux (list-remove-pos lst i) new-random)))))
((lambda (x) x)
(if (null? lst)
()
(let ((new-random (next-random current-random)))
(let ((i (modulo new-random (length lst))))
(cons (list-read lst i) (shuffle-aux (list-remove-pos lst i) new-random)))))))))
(make-maze (lambda (n m)
(if (not (if (odd? n) (odd? m) #f))
'error
(let ((cave (make-matrix
n
m
(lambda (i j)
(if (if (<change> (even? i) (not (even? i))) (even? j) #f)
(cons i j)
#f))))
(possible-holes (concat
(for
0
n
(lambda (i)
(<change>
(concat (for 0 m (lambda (j) (if (equal? (even? i) (even? j)) () (list (cons i j))))))
((lambda (x) x)
(concat (for 0 m (lambda (j) (if (equal? (even? i) (even? j)) () (list (cons i j)))))))))))))
(cave-to-maze (pierce-randomly (shuffle possible-holes) cave))))))
(cave-to-maze (lambda (cave)
(matrix-map (lambda (x) (if x (<change> '_ '*) (<change> '* '_))) cave)))
(pierce (lambda (pos cave)
(let ((i (car pos))
(j (cdr pos)))
(matrix-write cave i j pos))))
(pierce-randomly (lambda (possible-holes cave)
(if (null? possible-holes)
cave
(let ((hole (car possible-holes)))
(<change>
(pierce-randomly (cdr possible-holes) (try-to-pierce hole cave))
((lambda (x) x) (pierce-randomly (cdr possible-holes) (try-to-pierce hole cave))))))))
(try-to-pierce (lambda (pos cave)
(let ((i (car pos))
(j (cdr pos)))
(let ((ncs (neighboring-cavities pos cave)))
(if (duplicates? (map (lambda (nc) (matrix-read cave (car nc) (cdr nc))) ncs))
cave
(pierce pos (foldl (lambda (c nc) (change-cavity c nc pos)) cave ncs)))))))
(change-cavity (lambda (cave pos new-cavity-id)
(let ((i (car pos))
(j (cdr pos)))
(<change>
(change-cavity-aux cave pos new-cavity-id (matrix-read cave i j))
((lambda (x) x) (change-cavity-aux cave pos new-cavity-id (matrix-read cave i j)))))))
(change-cavity-aux (lambda (cave pos new-cavity-id old-cavity-id)
(let ((i (car pos))
(j (cdr pos)))
(let ((cavity-id (matrix-read cave i j)))
(if (equal? cavity-id old-cavity-id)
(foldl
(lambda (c nc)
(change-cavity-aux c nc new-cavity-id old-cavity-id))
(matrix-write cave i j new-cavity-id)
(neighboring-cavities pos cave))
cave)))))
(neighboring-cavities (lambda (pos cave)
(let ((size (matrix-size cave)))
(let ((n (car size))
(m (cdr size)))
(let ((i (car pos))
(j (cdr pos)))
(append
(if (if (> i 0) (matrix-read cave (- i 1) j) #f)
(list (cons (- i 1) j))
())
(append
(if (if (< i (- n 1)) (matrix-read cave (+ i 1) j) #f)
(list (cons (+ i 1) j))
())
(append
(if (if (> j 0) (matrix-read cave i (- j 1)) #f)
(list (cons i (- j 1)))
())
(if (if (< j (- m 1)) (matrix-read cave i (+ j 1)) #f)
(list (cons i (+ j 1)))
())))))))))
(expected-result (__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '* ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons '* (__toplevel_cons '* (__toplevel_cons '* (__toplevel_cons '* ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '* ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ ())))))))))))
())))))))))))))
(equal? (make-maze 11 11) expected-result)) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_gambit_mazefun-2.scm | scheme | Changes: | * removed : 0
* added : 1
* swaps : 0
* negated predicates : 1
* swapped branches : 1
* calls to i d fun : 8
(letrec ((foldr (lambda (f base lst)
(letrec ((foldr-aux (lambda (lst)
(if (null? lst)
base
(f (car lst) (foldr-aux (cdr lst)))))))
(foldr-aux lst))))
(foldl (lambda (f base lst)
(<change>
(letrec ((foldl-aux (lambda (base lst)
(if (null? lst)
base
(foldl-aux (f base (car lst)) (cdr lst))))))
(foldl-aux base lst))
((lambda (x) x)
(letrec ((foldl-aux (lambda (base lst)
(if (null? lst)
base
(foldl-aux (f base (car lst)) (cdr lst))))))
(<change>
(foldl-aux base lst)
((lambda (x) x) (foldl-aux base lst))))))))
(for (lambda (lo hi f)
(<change>
(letrec ((for-aux (lambda (lo)
(if (< lo hi)
(cons (f lo) (for-aux (+ lo 1)))
()))))
(for-aux lo))
((lambda (x) x)
(letrec ((for-aux (lambda (lo)
(if (< lo hi)
(cons (f lo) (for-aux (+ lo 1)))
()))))
(for-aux lo))))))
(concat (lambda (lists)
(foldr append () lists)))
(list-read (lambda (lst i)
(if (= i 0)
(car lst)
(list-read (cdr lst) (- i 1)))))
(list-write (lambda (lst i val)
(if (= i 0)
(cons val (cdr lst))
(cons (car lst) (list-write (cdr lst) (- i 1) val)))))
(list-remove-pos (lambda (lst i)
(if (= i 0)
(cdr lst)
(cons (car lst) (list-remove-pos (cdr lst) (- i 1))))))
(duplicates? (lambda (lst)
(if (null? lst)
#f
(let ((__or_res (member (car lst) (cdr lst))))
(if __or_res __or_res (duplicates? (cdr lst)))))))
(make-matrix (lambda (n m init)
(for 0 n (lambda (i) (for 0 m (lambda (j) (init i j)))))))
(matrix-read (lambda (mat i j)
(<change>
(list-read (list-read mat i) j)
((lambda (x) x) (list-read (list-read mat i) j)))))
(matrix-write (lambda (mat i j val)
(<change>
()
i)
(list-write mat i (list-write (list-read mat i) j val))))
(matrix-size (lambda (mat)
(cons (length mat) (length (car mat)))))
(matrix-map (lambda (f mat)
(map (lambda (lst) (map f lst)) mat)))
(initial-random 0)
(next-random (lambda (current-random)
(remainder (+ (* current-random 3581) 12751) 131072)))
(shuffle (lambda (lst)
(shuffle-aux lst initial-random)))
(shuffle-aux (lambda (lst current-random)
(<change>
(if (null? lst)
()
(let ((new-random (next-random current-random)))
(let ((i (modulo new-random (length lst))))
(cons (list-read lst i) (shuffle-aux (list-remove-pos lst i) new-random)))))
((lambda (x) x)
(if (null? lst)
()
(let ((new-random (next-random current-random)))
(let ((i (modulo new-random (length lst))))
(cons (list-read lst i) (shuffle-aux (list-remove-pos lst i) new-random)))))))))
(make-maze (lambda (n m)
(if (not (if (odd? n) (odd? m) #f))
'error
(let ((cave (make-matrix
n
m
(lambda (i j)
(if (if (<change> (even? i) (not (even? i))) (even? j) #f)
(cons i j)
#f))))
(possible-holes (concat
(for
0
n
(lambda (i)
(<change>
(concat (for 0 m (lambda (j) (if (equal? (even? i) (even? j)) () (list (cons i j))))))
((lambda (x) x)
(concat (for 0 m (lambda (j) (if (equal? (even? i) (even? j)) () (list (cons i j)))))))))))))
(cave-to-maze (pierce-randomly (shuffle possible-holes) cave))))))
(cave-to-maze (lambda (cave)
(matrix-map (lambda (x) (if x (<change> '_ '*) (<change> '* '_))) cave)))
(pierce (lambda (pos cave)
(let ((i (car pos))
(j (cdr pos)))
(matrix-write cave i j pos))))
(pierce-randomly (lambda (possible-holes cave)
(if (null? possible-holes)
cave
(let ((hole (car possible-holes)))
(<change>
(pierce-randomly (cdr possible-holes) (try-to-pierce hole cave))
((lambda (x) x) (pierce-randomly (cdr possible-holes) (try-to-pierce hole cave))))))))
(try-to-pierce (lambda (pos cave)
(let ((i (car pos))
(j (cdr pos)))
(let ((ncs (neighboring-cavities pos cave)))
(if (duplicates? (map (lambda (nc) (matrix-read cave (car nc) (cdr nc))) ncs))
cave
(pierce pos (foldl (lambda (c nc) (change-cavity c nc pos)) cave ncs)))))))
(change-cavity (lambda (cave pos new-cavity-id)
(let ((i (car pos))
(j (cdr pos)))
(<change>
(change-cavity-aux cave pos new-cavity-id (matrix-read cave i j))
((lambda (x) x) (change-cavity-aux cave pos new-cavity-id (matrix-read cave i j)))))))
(change-cavity-aux (lambda (cave pos new-cavity-id old-cavity-id)
(let ((i (car pos))
(j (cdr pos)))
(let ((cavity-id (matrix-read cave i j)))
(if (equal? cavity-id old-cavity-id)
(foldl
(lambda (c nc)
(change-cavity-aux c nc new-cavity-id old-cavity-id))
(matrix-write cave i j new-cavity-id)
(neighboring-cavities pos cave))
cave)))))
(neighboring-cavities (lambda (pos cave)
(let ((size (matrix-size cave)))
(let ((n (car size))
(m (cdr size)))
(let ((i (car pos))
(j (cdr pos)))
(append
(if (if (> i 0) (matrix-read cave (- i 1) j) #f)
(list (cons (- i 1) j))
())
(append
(if (if (< i (- n 1)) (matrix-read cave (+ i 1) j) #f)
(list (cons (+ i 1) j))
())
(append
(if (if (> j 0) (matrix-read cave i (- j 1)) #f)
(list (cons i (- j 1)))
())
(if (if (< j (- m 1)) (matrix-read cave i (+ j 1)) #f)
(list (cons i (+ j 1)))
())))))))))
(expected-result (__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '* ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons '* (__toplevel_cons '* (__toplevel_cons '* (__toplevel_cons '* ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons
'*
(__toplevel_cons '* (__toplevel_cons '_ (__toplevel_cons '* (__toplevel_cons '* ())))))))))))
(__toplevel_cons
(__toplevel_cons
'_
(__toplevel_cons
'*
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons
'_
(__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ (__toplevel_cons '_ ())))))))))))
())))))))))))))
(equal? (make-maze 11 11) expected-result)) |
ec88415257857ae131e46751919c1852481b51f9d1fe494beb41b4405a267824 | aarkerio/ZentaurLMS | users_test.clj | (ns zentaur.models.users-test
"Business logic in models test"
(:require [clojure.test :as ct]
[zentaur.factories.user-factory :as ufac]
[zentaur.db.core :as db]
[zentaur.models.users :as mu]))
;; (deftest ^:business-logic eg-tests (is (= 1 1)))
( defn destroy [ i d ]
( let [ int - id ( Integer / parseInt i d ) ]
;; (db/delete-post! {:id int-id})))
;; (ct/deftest create
;; (ct/testing "With valid input"
;; (ct/testing "it should returns an empty map"
( ct / is (= 1 ( mu / create ( ftime / build : admin { : fname " " } ) ) ) ) ) ) )
( ct/ run - tests )
| null | https://raw.githubusercontent.com/aarkerio/ZentaurLMS/adb43fb879b88d6a35f7f556cb225f7930d524f9/test/clj/zentaur/models/users_test.clj | clojure | (deftest ^:business-logic eg-tests (is (= 1 1)))
(db/delete-post! {:id int-id})))
(ct/deftest create
(ct/testing "With valid input"
(ct/testing "it should returns an empty map" | (ns zentaur.models.users-test
"Business logic in models test"
(:require [clojure.test :as ct]
[zentaur.factories.user-factory :as ufac]
[zentaur.db.core :as db]
[zentaur.models.users :as mu]))
( defn destroy [ i d ]
( let [ int - id ( Integer / parseInt i d ) ]
( ct / is (= 1 ( mu / create ( ftime / build : admin { : fname " " } ) ) ) ) ) ) )
( ct/ run - tests )
|
d6fcf424a89766166fcef80013f41e4e4b1f5f494d982e5e75be7156afc0d763 | Stratus3D/programming_erlang_exercises | lib_tester_db.erl | %%%-------------------------------------------------------------------
%%% Heavily inspired by
%%% -erlang-chapter-23/blob/7434c2eedce8b93b41ef4c68dd1690cbca5c8374/lib_tester_db.erl
%%%-------------------------------------------------------------------
-module(lib_tester_db).
%% API
-export([init/2, get_state/0, update_state/1]).
-define(TABLE, state).
%%%===================================================================
%%% API
%%%===================================================================
init(Nodes, Fields) ->
ok = mnesia:start(),
case mnesia:wait_for_tables([?TABLE], 1000) of
ok ->
io:format("Loaded tables~n"),
ok;
{timeout, _Time} ->
io:format("Creating tables...~n"),
mnesia:stop(),
ok = mnesia:delete_schema(Nodes),
ok = mnesia:create_schema(Nodes),
{_, _} = rpc:multicall(Nodes, application,start,[mnesia]),
{atomic, ok} = mnesia:create_table(?TABLE, [{disc_copies, Nodes}, {record_name, state}, {attributes, Fields}, {type, ordered_set}]),
io:format("Created mnesia table on ~p nodes~n", [Nodes]),
ok
end.
get_state() ->
{atomic, Result} = mnesia:transaction(fun() ->
case mnesia:read(?TABLE, mnesia:first(?TABLE)) of
[State|_] -> State;
[] -> false
end
end),
Result.
update_state(NewState) ->
ID = element(2, NewState),
{atomic, Result} = mnesia:transaction(fun() ->
ok = mnesia:delete(?TABLE, ID, sticky_write),
mnesia:write(?TABLE, NewState, sticky_write)
end),
Result.
| null | https://raw.githubusercontent.com/Stratus3D/programming_erlang_exercises/e4fd01024812059d338facc20f551e7dff4dac7e/chapter_23/exercise_5/src/lib_tester_db.erl | erlang | -------------------------------------------------------------------
Heavily inspired by
-erlang-chapter-23/blob/7434c2eedce8b93b41ef4c68dd1690cbca5c8374/lib_tester_db.erl
-------------------------------------------------------------------
API
===================================================================
API
=================================================================== | -module(lib_tester_db).
-export([init/2, get_state/0, update_state/1]).
-define(TABLE, state).
init(Nodes, Fields) ->
ok = mnesia:start(),
case mnesia:wait_for_tables([?TABLE], 1000) of
ok ->
io:format("Loaded tables~n"),
ok;
{timeout, _Time} ->
io:format("Creating tables...~n"),
mnesia:stop(),
ok = mnesia:delete_schema(Nodes),
ok = mnesia:create_schema(Nodes),
{_, _} = rpc:multicall(Nodes, application,start,[mnesia]),
{atomic, ok} = mnesia:create_table(?TABLE, [{disc_copies, Nodes}, {record_name, state}, {attributes, Fields}, {type, ordered_set}]),
io:format("Created mnesia table on ~p nodes~n", [Nodes]),
ok
end.
get_state() ->
{atomic, Result} = mnesia:transaction(fun() ->
case mnesia:read(?TABLE, mnesia:first(?TABLE)) of
[State|_] -> State;
[] -> false
end
end),
Result.
update_state(NewState) ->
ID = element(2, NewState),
{atomic, Result} = mnesia:transaction(fun() ->
ok = mnesia:delete(?TABLE, ID, sticky_write),
mnesia:write(?TABLE, NewState, sticky_write)
end),
Result.
|
4ce20f3462defc912578fd58a366921ecdfbd974e4cd13eab4af7067f2f5c9df | OCamlPro/operf-macro | build.ml | #!/usr/bin/env ocaml
#directory "pkg"
#use "topkg.ml"
let () =
Pkg.describe "operf-macro" ~builder:`OCamlbuild [
Pkg.lib "pkg/META";
Pkg.lib ~exts:Exts.module_library "lib/macroperf";
Pkg.bin ~dst:"operf-macro" ~auto:true "src/macrorun";
Pkg.bin ~auto:true "src/injector";
Pkg.man ~dst:"man1/operf-macro.1" "operf-macro.1"
]
| null | https://raw.githubusercontent.com/OCamlPro/operf-macro/0701292ef2a77bb8e151e804fd25899e3403fbb9/pkg/build.ml | ocaml | #!/usr/bin/env ocaml
#directory "pkg"
#use "topkg.ml"
let () =
Pkg.describe "operf-macro" ~builder:`OCamlbuild [
Pkg.lib "pkg/META";
Pkg.lib ~exts:Exts.module_library "lib/macroperf";
Pkg.bin ~dst:"operf-macro" ~auto:true "src/macrorun";
Pkg.bin ~auto:true "src/injector";
Pkg.man ~dst:"man1/operf-macro.1" "operf-macro.1"
]
|
|
b02b24efe2b188cb887c1ca9db7c49a7e64e76b240e03dbf7657266421959743 | yrashk/erlang | ssh_sftp.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2005 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%
%%% Description: SFTP protocol front-end
-module(ssh_sftp).
-behaviour(ssh_channel).
-include_lib("kernel/include/file.hrl").
-include("ssh.hrl").
-include("ssh_xfer.hrl").
%% API
-export([start_channel/1, start_channel/2, start_channel/3, stop_channel/1]).
-export([open/3, opendir/2, close/2, readdir/2, pread/4, read/3,
open/4, opendir/3, close/3, readdir/3, pread/5, read/4,
apread/4, aread/3, pwrite/4, write/3, apwrite/4, awrite/3,
pwrite/5, write/4,
position/3, real_path/2, read_file_info/2, get_file_info/2,
position/4, real_path/3, read_file_info/3, get_file_info/3,
write_file_info/3, read_link_info/2, read_link/2, make_symlink/3,
write_file_info/4, read_link_info/3, read_link/3, make_symlink/4,
rename/3, delete/2, make_dir/2, del_dir/2, send_window/1,
rename/4, delete/3, make_dir/3, del_dir/3, send_window/2,
recv_window/1, list_dir/2, read_file/2, write_file/3,
recv_window/2, list_dir/3, read_file/3, write_file/4]).
%% Deprecated
-export([connect/1, connect/2, connect/3, stop/1]).
-deprecated({connect, 1, next_major_release}).
-deprecated({connect, 2, next_major_release}).
-deprecated({connect, 3, next_major_release}).
-deprecated({stop, 1, next_major_release}).
%% ssh_channel callbacks
-export([init/1, handle_call/3, handle_msg/2, handle_ssh_msg/2, terminate/2]).
TODO : Should be placed elsewhere ssh_sftpd should not call functions in ssh_sftp !
-export([info_to_attr/1, attr_to_info/1]).
-record(state,
{
xf,
rep_buf = <<>>,
req_id,
req_list = [], %% {ReqId, Fun}
inf %% list of fileinf
}).
-record(fileinf,
{
handle,
offset,
size,
mode
}).
-define(FILEOP_TIMEOUT, infinity).
-define(NEXT_REQID(S),
S#state { req_id = (S#state.req_id + 1) band 16#ffffffff}).
-define(XF(S), S#state.xf).
-define(REQID(S), S#state.req_id).
%%====================================================================
%% API
%%====================================================================
start_channel(Cm) when is_pid(Cm) ->
start_channel(Cm, []);
start_channel(Host) when is_list(Host) ->
start_channel(Host, []).
start_channel(Cm, Opts) when is_pid(Cm) ->
Timeout = proplists:get_value(timeout, Opts, infinity),
case ssh_xfer:attach(Cm, []) of
{ok, ChannelId, Cm} ->
{ok, Pid} = ssh_channel:start(Cm, ChannelId,
?MODULE, [Cm, ChannelId, Timeout]),
case wait_for_version_negotiation(Pid, Timeout) of
ok ->
{ok, Pid};
TimeOut ->
TimeOut
end;
Error ->
Error
end;
start_channel(Host, Opts) ->
start_channel(Host, 22, Opts).
start_channel(Host, Port, Opts) ->
Timeout = proplists:get_value(timeout, Opts, infinity),
case ssh_xfer:connect(Host, Port, proplists:delete(timeout, Opts)) of
{ok, ChannelId, Cm} ->
{ok, Pid} = ssh_channel:start(Cm, ChannelId, ?MODULE, [Cm,
ChannelId, Timeout]),
case wait_for_version_negotiation(Pid, Timeout) of
ok ->
{ok, Pid, Cm};
TimeOut ->
TimeOut
end;
Error ->
Error
end.
stop_channel(Pid) ->
case process_info(Pid, [trap_exit]) of
[{trap_exit, Bool}] ->
process_flag(trap_exit, true),
link(Pid),
exit(Pid, ssh_sftp_stop_channel),
receive
{'EXIT', Pid, normal} ->
ok
after 5000 ->
exit(Pid, kill),
receive
{'EXIT', Pid, killed} ->
ok
end
end,
process_flag(trap_exit, Bool),
ok;
undefined ->
ok
end.
wait_for_version_negotiation(Pid, Timeout) ->
call(Pid, wait_for_version_negotiation, Timeout).
open(Pid, File, Mode) ->
open(Pid, File, Mode, ?FILEOP_TIMEOUT).
open(Pid, File, Mode, FileOpTimeout) ->
call(Pid, {open, false, File, Mode}, FileOpTimeout).
opendir(Pid, Path) ->
opendir(Pid, Path, ?FILEOP_TIMEOUT).
opendir(Pid, Path, FileOpTimeout) ->
call(Pid, {opendir, false, Path}, FileOpTimeout).
close(Pid, Handle) ->
close(Pid, Handle, ?FILEOP_TIMEOUT).
close(Pid, Handle, FileOpTimeout) ->
call(Pid, {close,false,Handle}, FileOpTimeout).
readdir(Pid,Handle) ->
readdir(Pid,Handle, ?FILEOP_TIMEOUT).
readdir(Pid,Handle, FileOpTimeout) ->
call(Pid, {readdir,false,Handle}, FileOpTimeout).
pread(Pid, Handle, Offset, Len) ->
pread(Pid, Handle, Offset, Len, ?FILEOP_TIMEOUT).
pread(Pid, Handle, Offset, Len, FileOpTimeout) ->
call(Pid, {pread,false,Handle, Offset, Len}, FileOpTimeout).
read(Pid, Handle, Len) ->
read(Pid, Handle, Len, ?FILEOP_TIMEOUT).
read(Pid, Handle, Len, FileOpTimeout) ->
call(Pid, {read,false,Handle, Len}, FileOpTimeout).
TODO this ought to be a cast ! Is so in all practial meaning
%% even if it is obscure!
apread(Pid, Handle, Offset, Len) ->
call(Pid, {pread,true,Handle, Offset, Len}, infinity).
TODO this ought to be a cast !
aread(Pid, Handle, Len) ->
call(Pid, {read,true,Handle, Len}, infinity).
pwrite(Pid, Handle, Offset, Data) ->
pwrite(Pid, Handle, Offset, Data, ?FILEOP_TIMEOUT).
pwrite(Pid, Handle, Offset, Data, FileOpTimeout) ->
call(Pid, {pwrite,false,Handle,Offset,Data}, FileOpTimeout).
write(Pid, Handle, Data) ->
write(Pid, Handle, Data, ?FILEOP_TIMEOUT).
write(Pid, Handle, Data, FileOpTimeout) ->
call(Pid, {write,false,Handle,Data}, FileOpTimeout).
TODO this ought to be a cast ! Is so in all practial meaning
%% even if it is obscure!
apwrite(Pid, Handle, Offset, Data) ->
call(Pid, {pwrite,true,Handle,Offset,Data}, infinity).
TODO this ought to be a cast ! Is so in all practial meaning
%% even if it is obscure!
awrite(Pid, Handle, Data) ->
call(Pid, {write,true,Handle,Data}, infinity).
position(Pid, Handle, Pos) ->
position(Pid, Handle, Pos, ?FILEOP_TIMEOUT).
position(Pid, Handle, Pos, FileOpTimeout) ->
call(Pid, {position, Handle, Pos}, FileOpTimeout).
real_path(Pid, Path) ->
real_path(Pid, Path, ?FILEOP_TIMEOUT).
real_path(Pid, Path, FileOpTimeout) ->
call(Pid, {real_path, false, Path}, FileOpTimeout).
read_file_info(Pid, Name) ->
read_file_info(Pid, Name, ?FILEOP_TIMEOUT).
read_file_info(Pid, Name, FileOpTimeout) ->
call(Pid, {read_file_info,false,Name}, FileOpTimeout).
get_file_info(Pid, Handle) ->
get_file_info(Pid, Handle, ?FILEOP_TIMEOUT).
get_file_info(Pid, Handle, FileOpTimeout) ->
call(Pid, {get_file_info,false,Handle}, FileOpTimeout).
write_file_info(Pid, Name, Info) ->
write_file_info(Pid, Name, Info, ?FILEOP_TIMEOUT).
write_file_info(Pid, Name, Info, FileOpTimeout) ->
call(Pid, {write_file_info,false,Name, Info}, FileOpTimeout).
read_link_info(Pid, Name) ->
read_link_info(Pid, Name, ?FILEOP_TIMEOUT).
read_link_info(Pid, Name, FileOpTimeout) ->
call(Pid, {read_link_info,false,Name}, FileOpTimeout).
read_link(Pid, LinkName) ->
read_link(Pid, LinkName, ?FILEOP_TIMEOUT).
read_link(Pid, LinkName, FileOpTimeout) ->
case call(Pid, {read_link,false,LinkName}, FileOpTimeout) of
{ok, [{Name, _Attrs}]} ->
{ok, Name};
ErrMsg ->
ErrMsg
end.
make_symlink(Pid, Name, Target) ->
make_symlink(Pid, Name, Target, ?FILEOP_TIMEOUT).
make_symlink(Pid, Name, Target, FileOpTimeout) ->
call(Pid, {make_symlink,false, Name, Target}, FileOpTimeout).
rename(Pid, FromFile, ToFile) ->
rename(Pid, FromFile, ToFile, ?FILEOP_TIMEOUT).
rename(Pid, FromFile, ToFile, FileOpTimeout) ->
call(Pid, {rename,false,FromFile, ToFile}, FileOpTimeout).
delete(Pid, Name) ->
delete(Pid, Name, ?FILEOP_TIMEOUT).
delete(Pid, Name, FileOpTimeout) ->
call(Pid, {delete,false,Name}, FileOpTimeout).
make_dir(Pid, Name) ->
make_dir(Pid, Name, ?FILEOP_TIMEOUT).
make_dir(Pid, Name, FileOpTimeout) ->
call(Pid, {make_dir,false,Name}, FileOpTimeout).
del_dir(Pid, Name) ->
del_dir(Pid, Name, ?FILEOP_TIMEOUT).
del_dir(Pid, Name, FileOpTimeout) ->
call(Pid, {del_dir,false,Name}, FileOpTimeout).
%% TODO : send_window and recv_window - Really needed? Not documented!
%% internal use maybe should be handled in other way!
send_window(Pid) ->
send_window(Pid, ?FILEOP_TIMEOUT).
send_window(Pid, FileOpTimeout) ->
call(Pid, send_window, FileOpTimeout).
recv_window(Pid) ->
recv_window(Pid, ?FILEOP_TIMEOUT).
recv_window(Pid, FileOpTimeout) ->
call(Pid, recv_window, FileOpTimeout).
list_dir(Pid, Name) ->
list_dir(Pid, Name, ?FILEOP_TIMEOUT).
list_dir(Pid, Name, FileOpTimeout) ->
case opendir(Pid, Name, FileOpTimeout) of
{ok,Handle} ->
Res = do_list_dir(Pid, Handle, FileOpTimeout, []),
close(Pid, Handle, FileOpTimeout),
case Res of
{ok, List} ->
NList = lists:foldl(fun({Nm, _Info},Acc) ->
[Nm|Acc] end,
[], List),
{ok,NList};
Error -> Error
end;
Error ->
Error
end.
do_list_dir(Pid, Handle, FileOpTimeout, Acc) ->
case readdir(Pid, Handle, FileOpTimeout) of
{ok, Names} ->
do_list_dir(Pid, Handle, FileOpTimeout, Acc ++ Names);
eof ->
{ok, Acc};
Error ->
Error
end.
read_file(Pid, Name) ->
read_file(Pid, Name, ?FILEOP_TIMEOUT).
read_file(Pid, Name, FileOpTimeout) ->
case open(Pid, Name, [read, binary], FileOpTimeout) of
{ok, Handle} ->
{ok,{_WindowSz,PacketSz}} = recv_window(Pid, FileOpTimeout),
Res = read_file_loop(Pid, Handle, PacketSz, FileOpTimeout, []),
close(Pid, Handle),
Res;
Error ->
Error
end.
read_file_loop(Pid, Handle, PacketSz, FileOpTimeout, Acc) ->
case read(Pid, Handle, PacketSz, FileOpTimeout) of
{ok, Data} ->
read_file_loop(Pid, Handle, PacketSz, FileOpTimeout, [Data|Acc]);
eof ->
{ok, list_to_binary(lists:reverse(Acc))};
Error ->
Error
end.
write_file(Pid, Name, List) ->
write_file(Pid, Name, List, ?FILEOP_TIMEOUT).
write_file(Pid, Name, List, FileOpTimeout) when is_list(List) ->
write_file(Pid, Name, list_to_binary(List), FileOpTimeout);
write_file(Pid, Name, Bin, FileOpTimeout) ->
case open(Pid, Name, [write, binary], FileOpTimeout) of
{ok, Handle} ->
{ok,{_Window,Packet}} = send_window(Pid, FileOpTimeout),
Res = write_file_loop(Pid, Handle, 0, Bin, size(Bin), Packet,
FileOpTimeout),
close(Pid, Handle, FileOpTimeout),
Res;
Error ->
Error
end.
write_file_loop(_Pid, _Handle, _Pos, _Bin, 0, _PacketSz,_FileOpTimeout) ->
ok;
write_file_loop(Pid, Handle, Pos, Bin, Remain, PacketSz, FileOpTimeout) ->
if Remain >= PacketSz ->
<<_:Pos/binary, Data:PacketSz/binary, _/binary>> = Bin,
case write(Pid, Handle, Data, FileOpTimeout) of
ok ->
write_file_loop(Pid, Handle,
Pos+PacketSz, Bin, Remain-PacketSz,
PacketSz, FileOpTimeout);
Error ->
Error
end;
true ->
<<_:Pos/binary, Data/binary>> = Bin,
write(Pid, Handle, Data, FileOpTimeout)
end.
%%====================================================================
SSh channel callbacks
%%====================================================================
%%--------------------------------------------------------------------
%% Function: init(Args) -> {ok, State}
%%
%% Description:
%%--------------------------------------------------------------------
init([Cm, ChannelId, Timeout]) ->
erlang:monitor(process, Cm),
case ssh_connection:subsystem(Cm, ChannelId, "sftp", Timeout) of
success ->
Xf = #ssh_xfer{cm = Cm,
channel = ChannelId},
{ok, #state{xf = Xf,
req_id = 0,
rep_buf = <<>>,
inf = new_inf()}};
failure ->
{stop, {error, "server failed to start sftp subsystem"}};
Error ->
{stop, Error}
end.
%%--------------------------------------------------------------------
Function : handle_call/3
%% Description: Handling call messages
%% Returns: {reply, Reply, State} |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} | (terminate/2 is called)
%% {stop, Reason, State} (terminate/2 is called)
%%--------------------------------------------------------------------
handle_call({{timeout, infinity}, wait_for_version_negotiation}, From,
#state{xf = #ssh_xfer{vsn = undefined} = Xf} = State) ->
{noreply, State#state{xf = Xf#ssh_xfer{vsn = From}}};
handle_call({{timeout, Timeout}, wait_for_version_negotiation}, From,
#state{xf = #ssh_xfer{vsn = undefined} = Xf} = State) ->
timer:send_after(Timeout, {timeout, undefined, From}),
{noreply, State#state{xf = Xf#ssh_xfer{vsn = From}}};
handle_call({_, wait_for_version_negotiation}, _, State) ->
{reply, ok, State};
handle_call({{timeout, infinity}, Msg}, From, State) ->
do_handle_call(Msg, From, State);
handle_call({{timeout, Timeout}, Msg}, From, #state{req_id = Id} = State) ->
timer:send_after(Timeout, {timeout, Id, From}),
do_handle_call(Msg, From, State).
do_handle_call({open, Async,FileName,Mode}, From, #state{xf = XF} = State) ->
{Access,Flags,Attrs} = open_mode(XF#ssh_xfer.vsn, Mode),
ReqID = State#state.req_id,
ssh_xfer:open(XF, ReqID, FileName, Access, Flags, Attrs),
case Async of
true ->
{reply, {async,ReqID},
update_request_info(ReqID, State,
fun({ok,Handle},State1) ->
open2(ReqID,FileName,Handle,Mode,Async,
From,State1);
(Rep,State1) ->
async_reply(ReqID, Rep, From, State1)
end)};
false ->
{noreply,
update_request_info(ReqID, State,
fun({ok,Handle},State1) ->
open2(ReqID,FileName,Handle,Mode,Async,
From,State1);
(Rep,State1) ->
sync_reply(Rep, From, State1)
end)}
end;
do_handle_call({opendir,Async,Path}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:opendir(?XF(State), ReqID, Path),
make_reply(ReqID, Async, From, State);
do_handle_call({readdir,Async,Handle}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:readdir(?XF(State), ReqID, Handle),
make_reply(ReqID, Async, From, State);
do_handle_call({close,_Async,Handle}, From, State) ->
%% wait until all operations on handle are done
case get_size(Handle, State) of
undefined ->
ReqID = State#state.req_id,
ssh_xfer:close(?XF(State), ReqID, Handle),
make_reply_post(ReqID, false, From, State,
fun(Rep, State1) ->
{Rep, erase_handle(Handle, State1)}
end);
_ ->
case lseek_position(Handle, cur, State) of
{ok,_} ->
ReqID = State#state.req_id,
ssh_xfer:close(?XF(State), ReqID, Handle),
make_reply_post(ReqID, false, From, State,
fun(Rep, State1) ->
{Rep, erase_handle(Handle, State1)}
end);
Error ->
{reply, Error, State}
end
end;
do_handle_call({pread,Async,Handle,At,Length}, From, State) ->
case lseek_position(Handle, At, State) of
{ok,Offset} ->
ReqID = State#state.req_id,
ssh_xfer:read(?XF(State),ReqID,Handle,Offset,Length),
%% To get multiple async read to work we must update the offset
%% before the operation begins
State1 = update_offset(Handle, Offset+Length, State),
make_reply_post(ReqID,Async,From,State1,
fun({ok,Data}, State2) ->
case get_mode(Handle, State2) of
binary -> {{ok,Data}, State2};
text ->
{{ok,binary_to_list(Data)}, State2}
end;
(Rep, State2) ->
{Rep, State2}
end);
Error ->
{reply, Error, State}
end;
do_handle_call({read,Async,Handle,Length}, From, State) ->
case lseek_position(Handle, cur, State) of
{ok,Offset} ->
ReqID = State#state.req_id,
ssh_xfer:read(?XF(State),ReqID,Handle,Offset,Length),
%% To get multiple async read to work we must update the offset
%% before the operation begins
State1 = update_offset(Handle, Offset+Length, State),
make_reply_post(ReqID,Async,From,State1,
fun({ok,Data}, State2) ->
case get_mode(Handle, State2) of
binary -> {{ok,Data}, State2};
text ->
{{ok,binary_to_list(Data)}, State2}
end;
(Rep, State2) -> {Rep, State2}
end);
Error ->
{reply, Error, State}
end;
do_handle_call({pwrite,Async,Handle,At,Data0}, From, State) ->
case lseek_position(Handle, At, State) of
{ok,Offset} ->
Data = if
is_binary(Data0) ->
Data0;
is_list(Data0) ->
list_to_binary(Data0)
end,
ReqID = State#state.req_id,
Size = size(Data),
ssh_xfer:write(?XF(State),ReqID,Handle,Offset,Data),
State1 = update_size(Handle, Offset+Size, State),
make_reply(ReqID, Async, From, State1);
Error ->
{reply, Error, State}
end;
do_handle_call({write,Async,Handle,Data0}, From, State) ->
case lseek_position(Handle, cur, State) of
{ok,Offset} ->
Data = if
is_binary(Data0) ->
Data0;
is_list(Data0) ->
list_to_binary(Data0)
end,
ReqID = State#state.req_id,
Size = size(Data),
ssh_xfer:write(?XF(State),ReqID,Handle,Offset,Data),
State1 = update_offset(Handle, Offset+Size, State),
make_reply(ReqID, Async, From, State1);
Error ->
{reply, Error, State}
end;
do_handle_call({position,Handle,At}, _From, State) ->
%% We could make this auto sync when all request to Handle is done?
case lseek_position(Handle, At, State) of
{ok,Offset} ->
{reply, {ok, Offset}, update_offset(Handle, Offset, State)};
Error ->
{reply, Error, State}
end;
do_handle_call({rename,Async,FromFile,ToFile}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:rename(?XF(State),ReqID,FromFile,ToFile,[overwrite]),
make_reply(ReqID, Async, From, State);
do_handle_call({delete,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:remove(?XF(State), ReqID, Name),
make_reply(ReqID, Async, From, State);
do_handle_call({make_dir,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:mkdir(?XF(State), ReqID, Name,
#ssh_xfer_attr{ type = directory }),
make_reply(ReqID, Async, From, State);
do_handle_call({del_dir,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:rmdir(?XF(State), ReqID, Name),
make_reply(ReqID, Async, From, State);
do_handle_call({real_path,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:realpath(?XF(State), ReqID, Name),
make_reply(ReqID, Async, From, State);
do_handle_call({read_file_info,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:stat(?XF(State), ReqID, Name, all),
make_reply(ReqID, Async, From, State);
do_handle_call({get_file_info,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:fstat(?XF(State), ReqID, Name, all),
make_reply(ReqID, Async, From, State);
do_handle_call({read_link_info,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:lstat(?XF(State), ReqID, Name, all),
make_reply(ReqID, Async, From, State);
do_handle_call({read_link,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:readlink(?XF(State), ReqID, Name),
make_reply(ReqID, Async, From, State);
do_handle_call({make_symlink, Async, Path, TargetPath}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:symlink(?XF(State), ReqID, Path, TargetPath),
make_reply(ReqID, Async, From, State);
do_handle_call({write_file_info,Async,Name,Info}, From, State) ->
ReqID = State#state.req_id,
A = info_to_attr(Info),
ssh_xfer:setstat(?XF(State), ReqID, Name, A),
make_reply(ReqID, Async, From, State);
%% TODO: Do we really want this format? Function send_window
%% is not documented and seems to be used only inernaly!
%% It is backwards compatible for now.
do_handle_call(send_window, _From, State) ->
XF = State#state.xf,
[{send_window,{{win_size, Size0},{packet_size, Size1}}}] =
ssh:channel_info(XF#ssh_xfer.cm, XF#ssh_xfer.channel, [send_window]),
{reply, {ok, {Size0, Size1}}, State};
%% TODO: Do we really want this format? Function recv_window
%% is not documented and seems to be used only inernaly!
%% It is backwards compatible for now.
do_handle_call(recv_window, _From, State) ->
XF = State#state.xf,
[{recv_window,{{win_size, Size0},{packet_size, Size1}}}] =
ssh:channel_info(XF#ssh_xfer.cm, XF#ssh_xfer.channel, [recv_window]),
{reply, {ok, {Size0, Size1}}, State};
%% Backwards compatible
do_handle_call(stop, _From, State) ->
{stop, shutdown, ok, State};
do_handle_call(Call, _From, State) ->
{reply, {error, bad_call, Call, State}, State}.
%%--------------------------------------------------------------------
Function : ) - > { ok , State } | { stop , ChannelId , State }
%%
%% Description: Handles channel messages
%%--------------------------------------------------------------------
handle_ssh_msg({ssh_cm, _ConnectionManager,
{data, _ChannelId, 0, Data}}, #state{rep_buf = Data0} =
State0) ->
State = handle_reply(State0, <<Data0/binary,Data/binary>>),
{ok, State};
handle_ssh_msg({ssh_cm, _ConnectionManager,
{data, _ChannelId, 1, Data}}, State) ->
error_logger:format("ssh: STDERR: ~s\n", [binary_to_list(Data)]),
{ok, State};
handle_ssh_msg({ssh_cm, _ConnectionManager, {eof, _ChannelId}}, State) ->
{ok, State};
handle_ssh_msg({ssh_cm, _, {signal, _, _}}, State) ->
Ignore signals according to RFC 4254 section 6.9 .
{ok, State};
handle_ssh_msg({ssh_cm, _, {exit_signal, ChannelId, _, Error, _}},
State0) ->
State = reply_all(State0, {error, Error}),
{stop, ChannelId, State};
handle_ssh_msg({ssh_cm, _, {exit_status, ChannelId, Status}}, State0) ->
State = reply_all(State0, {error, {exit_status, Status}}),
{stop, ChannelId, State}.
%%--------------------------------------------------------------------
Function : handle_msg(Args ) - > { ok , State } | { stop , ChannelId , State }
%%
%% Description: Handles channel messages
%%--------------------------------------------------------------------
handle_msg({ssh_channel_up, _, _}, #state{xf = Xf} = State) ->
ssh_xfer:protocol_version_request(Xf),
{ok, State};
%% Version negotiation timed out
handle_msg({timeout, undefined, From},
#state{xf = #ssh_xfer{channel = ChannelId}} = State) ->
ssh_channel:reply(From, {error, timeout}),
{stop, ChannelId, State};
handle_msg({timeout, Id, From}, #state{req_list = ReqList0} = State) ->
case lists:keysearch(Id, 1, ReqList0) of
false ->
{ok, State};
_ ->
ReqList = lists:keydelete(Id, 1, ReqList0),
ssh_channel:reply(From, {error, timeout}),
{ok, State#state{req_list = ReqList}}
end;
Connection manager goes down
handle_msg({'DOWN', _Ref, _Type, _Process, _},
#state{xf = #ssh_xfer{channel = ChannelId}} = State) ->
{stop, ChannelId, State};
%% Stopped by user
handle_msg({'EXIT', _, ssh_sftp_stop_channel},
#state{xf = #ssh_xfer{channel = ChannelId}} = State) ->
{stop, ChannelId, State};
handle_msg(_, State) ->
{ok, State}.
%%--------------------------------------------------------------------
%% Function: terminate(Reason, State) -> void()
%% Description: Called when the channel process is terminated
%%--------------------------------------------------------------------
%% Backwards compatible
terminate(shutdown, #state{xf = #ssh_xfer{cm = Cm}} = State) ->
reply_all(State, {error, closed}),
ssh:close(Cm);
terminate(_Reason, State) ->
reply_all(State, {error, closed}).
%%====================================================================
Internal functions
%%====================================================================
call(Pid, Msg, TimeOut) ->
ssh_channel:call(Pid, {{timeout, TimeOut}, Msg}, infinity).
handle_reply(State, <<?UINT32(Len),Reply:Len/binary,Rest/binary>>) ->
do_handle_reply(State, Reply, Rest);
handle_reply(State, Data) ->
State#state{rep_buf = Data}.
do_handle_reply(#state{xf = Xf} = State,
<<?SSH_FXP_VERSION, ?UINT32(Version), BinExt/binary>>, Rest) ->
Ext = ssh_xfer:decode_ext(BinExt),
case Xf#ssh_xfer.vsn of
undefined ->
ok;
From ->
ssh_channel:reply(From, ok)
end,
State#state{xf = Xf#ssh_xfer{vsn = Version, ext = Ext}, rep_buf = Rest};
do_handle_reply(State0, Data, Rest) ->
case catch ssh_xfer:xf_reply(?XF(State0), Data) of
{'EXIT', _Reason} ->
handle_reply(State0, Rest);
XfReply ->
State = handle_req_reply(State0, XfReply),
handle_reply(State, Rest)
end.
handle_req_reply(State0, {_, ReqID, _} = XfReply) ->
case lists:keysearch(ReqID, 1, State0#state.req_list) of
false ->
State0;
{value,{_,Fun}} ->
List = lists:keydelete(ReqID, 1, State0#state.req_list),
State1 = State0#state { req_list = List },
case catch Fun(xreply(XfReply),State1) of
{'EXIT', _} ->
State1;
State ->
State
end
end.
xreply({handle,_,H}) -> {ok, H};
xreply({data,_,Data}) -> {ok, Data};
xreply({name,_,Names}) -> {ok, Names};
xreply({attrs, _, A}) -> {ok, attr_to_info(A)};
xreply({extended_reply,_,X}) -> {ok, X};
xreply({status,_,{ok, _Err, _Lang, _Rep}}) -> ok;
xreply({status,_,{eof, _Err, _Lang, _Rep}}) -> eof;
xreply({status,_,{Stat, _Err, _Lang, _Rep}}) -> {error, Stat};
xreply({Code, _, Reply}) -> {Code, Reply}.
update_request_info(ReqID, State, Fun) ->
List = [{ReqID,Fun} | State#state.req_list],
ID = (State#state.req_id + 1) band 16#ffffffff,
State#state { req_list = List, req_id = ID }.
async_reply(ReqID, Reply, _From={To,_}, State) ->
To ! {async_reply, ReqID, Reply},
State.
sync_reply(Reply, From, State) ->
catch (ssh_channel:reply(From, Reply)),
State.
open2(OrigReqID,FileName,Handle,Mode,Async,From,State) ->
I0 = State#state.inf,
FileMode = case lists:member(binary, Mode) orelse lists:member(raw, Mode) of
true -> binary;
false -> text
end,
I1 = add_new_handle(Handle, FileMode, I0),
State0 = State#state{inf = I1},
ReqID = State0#state.req_id,
ssh_xfer:stat(State0#state.xf, ReqID, FileName, [size]),
case Async of
true ->
update_request_info(ReqID, State0,
fun({ok,FI},State1) ->
Size = FI#file_info.size,
State2 = if is_integer(Size) ->
put_size(Handle, Size, State1);
true ->
State1
end,
async_reply(OrigReqID, {ok,Handle}, From, State2);
(_, State1) ->
async_reply(OrigReqID, {ok,Handle}, From, State1)
end);
false ->
update_request_info(ReqID, State0,
fun({ok,FI},State1) ->
Size = FI#file_info.size,
State2 = if is_integer(Size) ->
put_size(Handle, Size, State1);
true ->
State1
end,
sync_reply({ok,Handle}, From, State2);
(_, State1) ->
sync_reply({ok,Handle}, From, State1)
end)
end.
reply_all(State, Reply) ->
List = State#state.req_list,
lists:foreach(fun({_ReqID,Fun}) ->
catch Fun(Reply,State)
end, List),
State#state {req_list = []}.
make_reply(ReqID, true, From, State) ->
{reply, {async, ReqID},
update_request_info(ReqID, State,
fun(Reply,State1) ->
async_reply(ReqID,Reply,From,State1)
end)};
make_reply(ReqID, false, From, State) ->
{noreply,
update_request_info(ReqID, State,
fun(Reply,State1) ->
sync_reply(Reply, From, State1)
end)}.
make_reply_post(ReqID, true, From, State, PostFun) ->
{reply, {async, ReqID},
update_request_info(ReqID, State,
fun(Reply,State1) ->
case catch PostFun(Reply, State1) of
{'EXIT',_} ->
async_reply(ReqID,Reply, From, State1);
{Reply1, State2} ->
async_reply(ReqID,Reply1, From, State2)
end
end)};
make_reply_post(ReqID, false, From, State, PostFun) ->
{noreply,
update_request_info(ReqID, State,
fun(Reply,State1) ->
case catch PostFun(Reply, State1) of
{'EXIT',_} ->
sync_reply(Reply, From, State1);
{Reply1, State2} ->
sync_reply(Reply1, From, State2)
end
end)}.
%% convert: file_info -> ssh_xfer_attr
info_to_attr(I) when is_record(I, file_info) ->
#ssh_xfer_attr { permissions = I#file_info.mode,
size = I#file_info.size,
type = I#file_info.type,
owner = I#file_info.uid,
group = I#file_info.gid,
atime = datetime_to_unix(I#file_info.atime),
mtime = datetime_to_unix(I#file_info.mtime),
createtime = datetime_to_unix(I#file_info.ctime)}.
%% convert: ssh_xfer_attr -> file_info
attr_to_info(A) when is_record(A, ssh_xfer_attr) ->
#file_info{
size = A#ssh_xfer_attr.size,
type = A#ssh_xfer_attr.type,
access = read_write, %% FIXME: read/write/read_write/none
atime = unix_to_datetime(A#ssh_xfer_attr.atime),
mtime = unix_to_datetime(A#ssh_xfer_attr.mtime),
ctime = unix_to_datetime(A#ssh_xfer_attr.createtime),
mode = A#ssh_xfer_attr.permissions,
links = 1,
major_device = 0,
minor_device = 0,
inode = 0,
uid = A#ssh_xfer_attr.owner,
gid = A#ssh_xfer_attr.group}.
Added workaround for sftp timestam problem . ( Timestamps should be
%% in UTC but they where not) . The workaround uses a deprecated
%% function i calandar. This will work as expected most of the time
%% but has problems for the same reason as
%% calendar:local_time_to_universal_time/1. We consider it better that
%% the timestamps work as expected most of the time instead of none of
the time . the file - api will be updated so that we can
%% solve this problem in a better way in the future.
unix_to_datetime(undefined) ->
undefined;
unix_to_datetime(UTCSecs) ->
UTCDateTime =
calendar:gregorian_seconds_to_datetime(UTCSecs + 62167219200),
erlang:universaltime_to_localtime(UTCDateTime).
datetime_to_unix(undefined) ->
undefined;
datetime_to_unix(LocalDateTime) ->
UTCDateTime = erlang:localtime_to_universaltime(LocalDateTime),
calendar:datetime_to_gregorian_seconds(UTCDateTime) - 62167219200.
open_mode(Vsn,Modes) when Vsn >= 5 ->
open_mode5(Modes);
open_mode(_Vsn, Modes) ->
open_mode3(Modes).
open_mode5(Modes) ->
A = #ssh_xfer_attr{type = regular},
{Fl, Ac} = case {lists:member(write, Modes),
lists:member(read, Modes),
lists:member(append, Modes)} of
{_, _, true} ->
{[append_data],
[read_attributes,
append_data, write_attributes]};
{true, false, false} ->
{[create_truncate],
[write_data, write_attributes]};
{true, true, _} ->
{[open_or_create],
[read_data, read_attributes,
write_data, write_attributes]};
{false, true, _} ->
{[open_existing],
[read_data, read_attributes]}
end,
{Ac, Fl, A}.
open_mode3(Modes) ->
A = #ssh_xfer_attr{type = regular},
Fl = case {lists:member(write, Modes),
lists:member(read, Modes),
lists:member(append, Modes)} of
{_, _, true} ->
[append];
{true, false, false} ->
[write, creat, trunc];
{true, true, _} ->
[read, write];
{false, true, _} ->
[read]
end,
{[], Fl, A}.
%% accessors for inf dict
new_inf() -> dict:new().
add_new_handle(Handle, FileMode, Inf) ->
dict:store(Handle, #fileinf{offset=0, size=0, mode=FileMode}, Inf).
update_size(Handle, NewSize, State) ->
OldSize = get_size(Handle, State),
if NewSize > OldSize ->
put_size(Handle, NewSize, State);
true ->
State
end.
set_offset(Handle , NewOffset ) - >
put({offset , Handle } , NewOffset ) .
update_offset(Handle, NewOffset, State0) ->
State1 = put_offset(Handle, NewOffset, State0),
update_size(Handle, NewOffset, State1).
%% access size and offset for handle
put_size(Handle, Size, State) ->
Inf0 = State#state.inf,
case dict:find(Handle, Inf0) of
{ok, FI} ->
State#state{inf=dict:store(Handle, FI#fileinf{size=Size}, Inf0)};
_ ->
State#state{inf=dict:store(Handle, #fileinf{size=Size,offset=0},
Inf0)}
end.
put_offset(Handle, Offset, State) ->
Inf0 = State#state.inf,
case dict:find(Handle, Inf0) of
{ok, FI} ->
State#state{inf=dict:store(Handle, FI#fileinf{offset=Offset},
Inf0)};
_ ->
State#state{inf=dict:store(Handle, #fileinf{size=Offset,
offset=Offset}, Inf0)}
end.
get_size(Handle, State) ->
case dict:find(Handle, State#state.inf) of
{ok, FI} ->
FI#fileinf.size;
_ ->
undefined
end.
%% get_offset(Handle, State) ->
%% {ok, FI} = dict:find(Handle, State#state.inf),
%% FI#fileinf.offset.
get_mode(Handle, State) ->
case dict:find(Handle, State#state.inf) of
{ok, FI} ->
FI#fileinf.mode;
_ ->
undefined
end.
erase_handle(Handle, State) ->
FI = dict:erase(Handle, State#state.inf),
State#state{inf = FI}.
%%
Caluclate a integer offset
%%
lseek_position(Handle, Pos, State) ->
case dict:find(Handle, State#state.inf) of
{ok, #fileinf{offset=O, size=S}} ->
lseek_pos(Pos, O, S);
_ ->
{error, einval}
end.
lseek_pos(_Pos, undefined, _) ->
{error, einval};
lseek_pos(Pos, _CurOffset, _CurSize)
when is_integer(Pos) andalso 0 =< Pos andalso Pos < ?SSH_FILEXFER_LARGEFILESIZE ->
{ok,Pos};
lseek_pos(bof, _CurOffset, _CurSize) ->
{ok,0};
lseek_pos(cur, CurOffset, _CurSize) ->
{ok,CurOffset};
lseek_pos(eof, _CurOffset, CurSize) ->
{ok,CurSize};
lseek_pos({bof, Offset}, _CurOffset, _CurSize)
when is_integer(Offset) andalso 0 =< Offset andalso Offset < ?SSH_FILEXFER_LARGEFILESIZE ->
{ok, Offset};
lseek_pos({cur, Offset}, CurOffset, _CurSize)
when is_integer(Offset) andalso -(?SSH_FILEXFER_LARGEFILESIZE) =< Offset andalso
Offset < ?SSH_FILEXFER_LARGEFILESIZE ->
NewOffset = CurOffset + Offset,
if NewOffset < 0 ->
{ok, 0};
true ->
{ok, NewOffset}
end;
lseek_pos({eof, Offset}, _CurOffset, CurSize)
when is_integer(Offset) andalso -(?SSH_FILEXFER_LARGEFILESIZE) =< Offset andalso
Offset < ?SSH_FILEXFER_LARGEFILESIZE ->
NewOffset = CurSize + Offset,
if NewOffset < 0 ->
{ok, 0};
true ->
{ok, NewOffset}
end;
lseek_pos(_, _, _) ->
{error, einval}.
%%%%%% Deprecated %%%%
connect(Cm) when is_pid(Cm) ->
connect(Cm, []);
connect(Host) when is_list(Host) ->
connect(Host, []).
connect(Cm, Opts) when is_pid(Cm) ->
Timeout = proplists:get_value(timeout, Opts, infinity),
case ssh_xfer:attach(Cm, []) of
{ok, ChannelId, Cm} ->
ssh_channel:start(Cm, ChannelId, ?MODULE, [Cm, ChannelId,
Timeout]);
Error ->
Error
end;
connect(Host, Opts) ->
connect(Host, 22, Opts).
connect(Host, Port, Opts) ->
Timeout = proplists:get_value(timeout, Opts, infinity),
case ssh_xfer:connect(Host, Port, proplists:delete(timeout, Opts)) of
{ok, ChannelId, Cm} ->
ssh_channel:start(Cm, ChannelId, ?MODULE, [Cm,
ChannelId, Timeout]);
Error ->
Error
end.
stop(Pid) ->
call(Pid, stop, infinity).
| null | https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/ssh/src/ssh_sftp.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
Description: SFTP protocol front-end
API
Deprecated
ssh_channel callbacks
{ReqId, Fun}
list of fileinf
====================================================================
API
====================================================================
even if it is obscure!
even if it is obscure!
even if it is obscure!
TODO : send_window and recv_window - Really needed? Not documented!
internal use maybe should be handled in other way!
====================================================================
====================================================================
--------------------------------------------------------------------
Function: init(Args) -> {ok, State}
Description:
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Handling call messages
Returns: {reply, Reply, State} |
{stop, Reason, Reply, State} | (terminate/2 is called)
{stop, Reason, State} (terminate/2 is called)
--------------------------------------------------------------------
wait until all operations on handle are done
To get multiple async read to work we must update the offset
before the operation begins
To get multiple async read to work we must update the offset
before the operation begins
We could make this auto sync when all request to Handle is done?
TODO: Do we really want this format? Function send_window
is not documented and seems to be used only inernaly!
It is backwards compatible for now.
TODO: Do we really want this format? Function recv_window
is not documented and seems to be used only inernaly!
It is backwards compatible for now.
Backwards compatible
--------------------------------------------------------------------
Description: Handles channel messages
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Handles channel messages
--------------------------------------------------------------------
Version negotiation timed out
Stopped by user
--------------------------------------------------------------------
Function: terminate(Reason, State) -> void()
Description: Called when the channel process is terminated
--------------------------------------------------------------------
Backwards compatible
====================================================================
====================================================================
convert: file_info -> ssh_xfer_attr
convert: ssh_xfer_attr -> file_info
FIXME: read/write/read_write/none
in UTC but they where not) . The workaround uses a deprecated
function i calandar. This will work as expected most of the time
but has problems for the same reason as
calendar:local_time_to_universal_time/1. We consider it better that
the timestamps work as expected most of the time instead of none of
solve this problem in a better way in the future.
accessors for inf dict
access size and offset for handle
get_offset(Handle, State) ->
{ok, FI} = dict:find(Handle, State#state.inf),
FI#fileinf.offset.
Deprecated %%%% | Copyright Ericsson AB 2005 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(ssh_sftp).
-behaviour(ssh_channel).
-include_lib("kernel/include/file.hrl").
-include("ssh.hrl").
-include("ssh_xfer.hrl").
-export([start_channel/1, start_channel/2, start_channel/3, stop_channel/1]).
-export([open/3, opendir/2, close/2, readdir/2, pread/4, read/3,
open/4, opendir/3, close/3, readdir/3, pread/5, read/4,
apread/4, aread/3, pwrite/4, write/3, apwrite/4, awrite/3,
pwrite/5, write/4,
position/3, real_path/2, read_file_info/2, get_file_info/2,
position/4, real_path/3, read_file_info/3, get_file_info/3,
write_file_info/3, read_link_info/2, read_link/2, make_symlink/3,
write_file_info/4, read_link_info/3, read_link/3, make_symlink/4,
rename/3, delete/2, make_dir/2, del_dir/2, send_window/1,
rename/4, delete/3, make_dir/3, del_dir/3, send_window/2,
recv_window/1, list_dir/2, read_file/2, write_file/3,
recv_window/2, list_dir/3, read_file/3, write_file/4]).
-export([connect/1, connect/2, connect/3, stop/1]).
-deprecated({connect, 1, next_major_release}).
-deprecated({connect, 2, next_major_release}).
-deprecated({connect, 3, next_major_release}).
-deprecated({stop, 1, next_major_release}).
-export([init/1, handle_call/3, handle_msg/2, handle_ssh_msg/2, terminate/2]).
TODO : Should be placed elsewhere ssh_sftpd should not call functions in ssh_sftp !
-export([info_to_attr/1, attr_to_info/1]).
-record(state,
{
xf,
rep_buf = <<>>,
req_id,
}).
-record(fileinf,
{
handle,
offset,
size,
mode
}).
-define(FILEOP_TIMEOUT, infinity).
-define(NEXT_REQID(S),
S#state { req_id = (S#state.req_id + 1) band 16#ffffffff}).
-define(XF(S), S#state.xf).
-define(REQID(S), S#state.req_id).
start_channel(Cm) when is_pid(Cm) ->
start_channel(Cm, []);
start_channel(Host) when is_list(Host) ->
start_channel(Host, []).
start_channel(Cm, Opts) when is_pid(Cm) ->
Timeout = proplists:get_value(timeout, Opts, infinity),
case ssh_xfer:attach(Cm, []) of
{ok, ChannelId, Cm} ->
{ok, Pid} = ssh_channel:start(Cm, ChannelId,
?MODULE, [Cm, ChannelId, Timeout]),
case wait_for_version_negotiation(Pid, Timeout) of
ok ->
{ok, Pid};
TimeOut ->
TimeOut
end;
Error ->
Error
end;
start_channel(Host, Opts) ->
start_channel(Host, 22, Opts).
start_channel(Host, Port, Opts) ->
Timeout = proplists:get_value(timeout, Opts, infinity),
case ssh_xfer:connect(Host, Port, proplists:delete(timeout, Opts)) of
{ok, ChannelId, Cm} ->
{ok, Pid} = ssh_channel:start(Cm, ChannelId, ?MODULE, [Cm,
ChannelId, Timeout]),
case wait_for_version_negotiation(Pid, Timeout) of
ok ->
{ok, Pid, Cm};
TimeOut ->
TimeOut
end;
Error ->
Error
end.
stop_channel(Pid) ->
case process_info(Pid, [trap_exit]) of
[{trap_exit, Bool}] ->
process_flag(trap_exit, true),
link(Pid),
exit(Pid, ssh_sftp_stop_channel),
receive
{'EXIT', Pid, normal} ->
ok
after 5000 ->
exit(Pid, kill),
receive
{'EXIT', Pid, killed} ->
ok
end
end,
process_flag(trap_exit, Bool),
ok;
undefined ->
ok
end.
wait_for_version_negotiation(Pid, Timeout) ->
call(Pid, wait_for_version_negotiation, Timeout).
open(Pid, File, Mode) ->
open(Pid, File, Mode, ?FILEOP_TIMEOUT).
open(Pid, File, Mode, FileOpTimeout) ->
call(Pid, {open, false, File, Mode}, FileOpTimeout).
opendir(Pid, Path) ->
opendir(Pid, Path, ?FILEOP_TIMEOUT).
opendir(Pid, Path, FileOpTimeout) ->
call(Pid, {opendir, false, Path}, FileOpTimeout).
close(Pid, Handle) ->
close(Pid, Handle, ?FILEOP_TIMEOUT).
close(Pid, Handle, FileOpTimeout) ->
call(Pid, {close,false,Handle}, FileOpTimeout).
readdir(Pid,Handle) ->
readdir(Pid,Handle, ?FILEOP_TIMEOUT).
readdir(Pid,Handle, FileOpTimeout) ->
call(Pid, {readdir,false,Handle}, FileOpTimeout).
pread(Pid, Handle, Offset, Len) ->
pread(Pid, Handle, Offset, Len, ?FILEOP_TIMEOUT).
pread(Pid, Handle, Offset, Len, FileOpTimeout) ->
call(Pid, {pread,false,Handle, Offset, Len}, FileOpTimeout).
read(Pid, Handle, Len) ->
read(Pid, Handle, Len, ?FILEOP_TIMEOUT).
read(Pid, Handle, Len, FileOpTimeout) ->
call(Pid, {read,false,Handle, Len}, FileOpTimeout).
TODO this ought to be a cast ! Is so in all practial meaning
apread(Pid, Handle, Offset, Len) ->
call(Pid, {pread,true,Handle, Offset, Len}, infinity).
TODO this ought to be a cast !
aread(Pid, Handle, Len) ->
call(Pid, {read,true,Handle, Len}, infinity).
pwrite(Pid, Handle, Offset, Data) ->
pwrite(Pid, Handle, Offset, Data, ?FILEOP_TIMEOUT).
pwrite(Pid, Handle, Offset, Data, FileOpTimeout) ->
call(Pid, {pwrite,false,Handle,Offset,Data}, FileOpTimeout).
write(Pid, Handle, Data) ->
write(Pid, Handle, Data, ?FILEOP_TIMEOUT).
write(Pid, Handle, Data, FileOpTimeout) ->
call(Pid, {write,false,Handle,Data}, FileOpTimeout).
TODO this ought to be a cast ! Is so in all practial meaning
apwrite(Pid, Handle, Offset, Data) ->
call(Pid, {pwrite,true,Handle,Offset,Data}, infinity).
TODO this ought to be a cast ! Is so in all practial meaning
awrite(Pid, Handle, Data) ->
call(Pid, {write,true,Handle,Data}, infinity).
position(Pid, Handle, Pos) ->
position(Pid, Handle, Pos, ?FILEOP_TIMEOUT).
position(Pid, Handle, Pos, FileOpTimeout) ->
call(Pid, {position, Handle, Pos}, FileOpTimeout).
real_path(Pid, Path) ->
real_path(Pid, Path, ?FILEOP_TIMEOUT).
real_path(Pid, Path, FileOpTimeout) ->
call(Pid, {real_path, false, Path}, FileOpTimeout).
read_file_info(Pid, Name) ->
read_file_info(Pid, Name, ?FILEOP_TIMEOUT).
read_file_info(Pid, Name, FileOpTimeout) ->
call(Pid, {read_file_info,false,Name}, FileOpTimeout).
get_file_info(Pid, Handle) ->
get_file_info(Pid, Handle, ?FILEOP_TIMEOUT).
get_file_info(Pid, Handle, FileOpTimeout) ->
call(Pid, {get_file_info,false,Handle}, FileOpTimeout).
write_file_info(Pid, Name, Info) ->
write_file_info(Pid, Name, Info, ?FILEOP_TIMEOUT).
write_file_info(Pid, Name, Info, FileOpTimeout) ->
call(Pid, {write_file_info,false,Name, Info}, FileOpTimeout).
read_link_info(Pid, Name) ->
read_link_info(Pid, Name, ?FILEOP_TIMEOUT).
read_link_info(Pid, Name, FileOpTimeout) ->
call(Pid, {read_link_info,false,Name}, FileOpTimeout).
read_link(Pid, LinkName) ->
read_link(Pid, LinkName, ?FILEOP_TIMEOUT).
read_link(Pid, LinkName, FileOpTimeout) ->
case call(Pid, {read_link,false,LinkName}, FileOpTimeout) of
{ok, [{Name, _Attrs}]} ->
{ok, Name};
ErrMsg ->
ErrMsg
end.
make_symlink(Pid, Name, Target) ->
make_symlink(Pid, Name, Target, ?FILEOP_TIMEOUT).
make_symlink(Pid, Name, Target, FileOpTimeout) ->
call(Pid, {make_symlink,false, Name, Target}, FileOpTimeout).
rename(Pid, FromFile, ToFile) ->
rename(Pid, FromFile, ToFile, ?FILEOP_TIMEOUT).
rename(Pid, FromFile, ToFile, FileOpTimeout) ->
call(Pid, {rename,false,FromFile, ToFile}, FileOpTimeout).
delete(Pid, Name) ->
delete(Pid, Name, ?FILEOP_TIMEOUT).
delete(Pid, Name, FileOpTimeout) ->
call(Pid, {delete,false,Name}, FileOpTimeout).
make_dir(Pid, Name) ->
make_dir(Pid, Name, ?FILEOP_TIMEOUT).
make_dir(Pid, Name, FileOpTimeout) ->
call(Pid, {make_dir,false,Name}, FileOpTimeout).
del_dir(Pid, Name) ->
del_dir(Pid, Name, ?FILEOP_TIMEOUT).
del_dir(Pid, Name, FileOpTimeout) ->
call(Pid, {del_dir,false,Name}, FileOpTimeout).
send_window(Pid) ->
send_window(Pid, ?FILEOP_TIMEOUT).
send_window(Pid, FileOpTimeout) ->
call(Pid, send_window, FileOpTimeout).
recv_window(Pid) ->
recv_window(Pid, ?FILEOP_TIMEOUT).
recv_window(Pid, FileOpTimeout) ->
call(Pid, recv_window, FileOpTimeout).
list_dir(Pid, Name) ->
list_dir(Pid, Name, ?FILEOP_TIMEOUT).
list_dir(Pid, Name, FileOpTimeout) ->
case opendir(Pid, Name, FileOpTimeout) of
{ok,Handle} ->
Res = do_list_dir(Pid, Handle, FileOpTimeout, []),
close(Pid, Handle, FileOpTimeout),
case Res of
{ok, List} ->
NList = lists:foldl(fun({Nm, _Info},Acc) ->
[Nm|Acc] end,
[], List),
{ok,NList};
Error -> Error
end;
Error ->
Error
end.
do_list_dir(Pid, Handle, FileOpTimeout, Acc) ->
case readdir(Pid, Handle, FileOpTimeout) of
{ok, Names} ->
do_list_dir(Pid, Handle, FileOpTimeout, Acc ++ Names);
eof ->
{ok, Acc};
Error ->
Error
end.
read_file(Pid, Name) ->
read_file(Pid, Name, ?FILEOP_TIMEOUT).
read_file(Pid, Name, FileOpTimeout) ->
case open(Pid, Name, [read, binary], FileOpTimeout) of
{ok, Handle} ->
{ok,{_WindowSz,PacketSz}} = recv_window(Pid, FileOpTimeout),
Res = read_file_loop(Pid, Handle, PacketSz, FileOpTimeout, []),
close(Pid, Handle),
Res;
Error ->
Error
end.
read_file_loop(Pid, Handle, PacketSz, FileOpTimeout, Acc) ->
case read(Pid, Handle, PacketSz, FileOpTimeout) of
{ok, Data} ->
read_file_loop(Pid, Handle, PacketSz, FileOpTimeout, [Data|Acc]);
eof ->
{ok, list_to_binary(lists:reverse(Acc))};
Error ->
Error
end.
write_file(Pid, Name, List) ->
write_file(Pid, Name, List, ?FILEOP_TIMEOUT).
write_file(Pid, Name, List, FileOpTimeout) when is_list(List) ->
write_file(Pid, Name, list_to_binary(List), FileOpTimeout);
write_file(Pid, Name, Bin, FileOpTimeout) ->
case open(Pid, Name, [write, binary], FileOpTimeout) of
{ok, Handle} ->
{ok,{_Window,Packet}} = send_window(Pid, FileOpTimeout),
Res = write_file_loop(Pid, Handle, 0, Bin, size(Bin), Packet,
FileOpTimeout),
close(Pid, Handle, FileOpTimeout),
Res;
Error ->
Error
end.
write_file_loop(_Pid, _Handle, _Pos, _Bin, 0, _PacketSz,_FileOpTimeout) ->
ok;
write_file_loop(Pid, Handle, Pos, Bin, Remain, PacketSz, FileOpTimeout) ->
if Remain >= PacketSz ->
<<_:Pos/binary, Data:PacketSz/binary, _/binary>> = Bin,
case write(Pid, Handle, Data, FileOpTimeout) of
ok ->
write_file_loop(Pid, Handle,
Pos+PacketSz, Bin, Remain-PacketSz,
PacketSz, FileOpTimeout);
Error ->
Error
end;
true ->
<<_:Pos/binary, Data/binary>> = Bin,
write(Pid, Handle, Data, FileOpTimeout)
end.
SSh channel callbacks
init([Cm, ChannelId, Timeout]) ->
erlang:monitor(process, Cm),
case ssh_connection:subsystem(Cm, ChannelId, "sftp", Timeout) of
success ->
Xf = #ssh_xfer{cm = Cm,
channel = ChannelId},
{ok, #state{xf = Xf,
req_id = 0,
rep_buf = <<>>,
inf = new_inf()}};
failure ->
{stop, {error, "server failed to start sftp subsystem"}};
Error ->
{stop, Error}
end.
Function : handle_call/3
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call({{timeout, infinity}, wait_for_version_negotiation}, From,
#state{xf = #ssh_xfer{vsn = undefined} = Xf} = State) ->
{noreply, State#state{xf = Xf#ssh_xfer{vsn = From}}};
handle_call({{timeout, Timeout}, wait_for_version_negotiation}, From,
#state{xf = #ssh_xfer{vsn = undefined} = Xf} = State) ->
timer:send_after(Timeout, {timeout, undefined, From}),
{noreply, State#state{xf = Xf#ssh_xfer{vsn = From}}};
handle_call({_, wait_for_version_negotiation}, _, State) ->
{reply, ok, State};
handle_call({{timeout, infinity}, Msg}, From, State) ->
do_handle_call(Msg, From, State);
handle_call({{timeout, Timeout}, Msg}, From, #state{req_id = Id} = State) ->
timer:send_after(Timeout, {timeout, Id, From}),
do_handle_call(Msg, From, State).
do_handle_call({open, Async,FileName,Mode}, From, #state{xf = XF} = State) ->
{Access,Flags,Attrs} = open_mode(XF#ssh_xfer.vsn, Mode),
ReqID = State#state.req_id,
ssh_xfer:open(XF, ReqID, FileName, Access, Flags, Attrs),
case Async of
true ->
{reply, {async,ReqID},
update_request_info(ReqID, State,
fun({ok,Handle},State1) ->
open2(ReqID,FileName,Handle,Mode,Async,
From,State1);
(Rep,State1) ->
async_reply(ReqID, Rep, From, State1)
end)};
false ->
{noreply,
update_request_info(ReqID, State,
fun({ok,Handle},State1) ->
open2(ReqID,FileName,Handle,Mode,Async,
From,State1);
(Rep,State1) ->
sync_reply(Rep, From, State1)
end)}
end;
do_handle_call({opendir,Async,Path}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:opendir(?XF(State), ReqID, Path),
make_reply(ReqID, Async, From, State);
do_handle_call({readdir,Async,Handle}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:readdir(?XF(State), ReqID, Handle),
make_reply(ReqID, Async, From, State);
do_handle_call({close,_Async,Handle}, From, State) ->
case get_size(Handle, State) of
undefined ->
ReqID = State#state.req_id,
ssh_xfer:close(?XF(State), ReqID, Handle),
make_reply_post(ReqID, false, From, State,
fun(Rep, State1) ->
{Rep, erase_handle(Handle, State1)}
end);
_ ->
case lseek_position(Handle, cur, State) of
{ok,_} ->
ReqID = State#state.req_id,
ssh_xfer:close(?XF(State), ReqID, Handle),
make_reply_post(ReqID, false, From, State,
fun(Rep, State1) ->
{Rep, erase_handle(Handle, State1)}
end);
Error ->
{reply, Error, State}
end
end;
do_handle_call({pread,Async,Handle,At,Length}, From, State) ->
case lseek_position(Handle, At, State) of
{ok,Offset} ->
ReqID = State#state.req_id,
ssh_xfer:read(?XF(State),ReqID,Handle,Offset,Length),
State1 = update_offset(Handle, Offset+Length, State),
make_reply_post(ReqID,Async,From,State1,
fun({ok,Data}, State2) ->
case get_mode(Handle, State2) of
binary -> {{ok,Data}, State2};
text ->
{{ok,binary_to_list(Data)}, State2}
end;
(Rep, State2) ->
{Rep, State2}
end);
Error ->
{reply, Error, State}
end;
do_handle_call({read,Async,Handle,Length}, From, State) ->
case lseek_position(Handle, cur, State) of
{ok,Offset} ->
ReqID = State#state.req_id,
ssh_xfer:read(?XF(State),ReqID,Handle,Offset,Length),
State1 = update_offset(Handle, Offset+Length, State),
make_reply_post(ReqID,Async,From,State1,
fun({ok,Data}, State2) ->
case get_mode(Handle, State2) of
binary -> {{ok,Data}, State2};
text ->
{{ok,binary_to_list(Data)}, State2}
end;
(Rep, State2) -> {Rep, State2}
end);
Error ->
{reply, Error, State}
end;
do_handle_call({pwrite,Async,Handle,At,Data0}, From, State) ->
case lseek_position(Handle, At, State) of
{ok,Offset} ->
Data = if
is_binary(Data0) ->
Data0;
is_list(Data0) ->
list_to_binary(Data0)
end,
ReqID = State#state.req_id,
Size = size(Data),
ssh_xfer:write(?XF(State),ReqID,Handle,Offset,Data),
State1 = update_size(Handle, Offset+Size, State),
make_reply(ReqID, Async, From, State1);
Error ->
{reply, Error, State}
end;
do_handle_call({write,Async,Handle,Data0}, From, State) ->
case lseek_position(Handle, cur, State) of
{ok,Offset} ->
Data = if
is_binary(Data0) ->
Data0;
is_list(Data0) ->
list_to_binary(Data0)
end,
ReqID = State#state.req_id,
Size = size(Data),
ssh_xfer:write(?XF(State),ReqID,Handle,Offset,Data),
State1 = update_offset(Handle, Offset+Size, State),
make_reply(ReqID, Async, From, State1);
Error ->
{reply, Error, State}
end;
do_handle_call({position,Handle,At}, _From, State) ->
case lseek_position(Handle, At, State) of
{ok,Offset} ->
{reply, {ok, Offset}, update_offset(Handle, Offset, State)};
Error ->
{reply, Error, State}
end;
do_handle_call({rename,Async,FromFile,ToFile}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:rename(?XF(State),ReqID,FromFile,ToFile,[overwrite]),
make_reply(ReqID, Async, From, State);
do_handle_call({delete,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:remove(?XF(State), ReqID, Name),
make_reply(ReqID, Async, From, State);
do_handle_call({make_dir,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:mkdir(?XF(State), ReqID, Name,
#ssh_xfer_attr{ type = directory }),
make_reply(ReqID, Async, From, State);
do_handle_call({del_dir,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:rmdir(?XF(State), ReqID, Name),
make_reply(ReqID, Async, From, State);
do_handle_call({real_path,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:realpath(?XF(State), ReqID, Name),
make_reply(ReqID, Async, From, State);
do_handle_call({read_file_info,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:stat(?XF(State), ReqID, Name, all),
make_reply(ReqID, Async, From, State);
do_handle_call({get_file_info,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:fstat(?XF(State), ReqID, Name, all),
make_reply(ReqID, Async, From, State);
do_handle_call({read_link_info,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:lstat(?XF(State), ReqID, Name, all),
make_reply(ReqID, Async, From, State);
do_handle_call({read_link,Async,Name}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:readlink(?XF(State), ReqID, Name),
make_reply(ReqID, Async, From, State);
do_handle_call({make_symlink, Async, Path, TargetPath}, From, State) ->
ReqID = State#state.req_id,
ssh_xfer:symlink(?XF(State), ReqID, Path, TargetPath),
make_reply(ReqID, Async, From, State);
do_handle_call({write_file_info,Async,Name,Info}, From, State) ->
ReqID = State#state.req_id,
A = info_to_attr(Info),
ssh_xfer:setstat(?XF(State), ReqID, Name, A),
make_reply(ReqID, Async, From, State);
do_handle_call(send_window, _From, State) ->
XF = State#state.xf,
[{send_window,{{win_size, Size0},{packet_size, Size1}}}] =
ssh:channel_info(XF#ssh_xfer.cm, XF#ssh_xfer.channel, [send_window]),
{reply, {ok, {Size0, Size1}}, State};
do_handle_call(recv_window, _From, State) ->
XF = State#state.xf,
[{recv_window,{{win_size, Size0},{packet_size, Size1}}}] =
ssh:channel_info(XF#ssh_xfer.cm, XF#ssh_xfer.channel, [recv_window]),
{reply, {ok, {Size0, Size1}}, State};
do_handle_call(stop, _From, State) ->
{stop, shutdown, ok, State};
do_handle_call(Call, _From, State) ->
{reply, {error, bad_call, Call, State}, State}.
Function : ) - > { ok , State } | { stop , ChannelId , State }
handle_ssh_msg({ssh_cm, _ConnectionManager,
{data, _ChannelId, 0, Data}}, #state{rep_buf = Data0} =
State0) ->
State = handle_reply(State0, <<Data0/binary,Data/binary>>),
{ok, State};
handle_ssh_msg({ssh_cm, _ConnectionManager,
{data, _ChannelId, 1, Data}}, State) ->
error_logger:format("ssh: STDERR: ~s\n", [binary_to_list(Data)]),
{ok, State};
handle_ssh_msg({ssh_cm, _ConnectionManager, {eof, _ChannelId}}, State) ->
{ok, State};
handle_ssh_msg({ssh_cm, _, {signal, _, _}}, State) ->
Ignore signals according to RFC 4254 section 6.9 .
{ok, State};
handle_ssh_msg({ssh_cm, _, {exit_signal, ChannelId, _, Error, _}},
State0) ->
State = reply_all(State0, {error, Error}),
{stop, ChannelId, State};
handle_ssh_msg({ssh_cm, _, {exit_status, ChannelId, Status}}, State0) ->
State = reply_all(State0, {error, {exit_status, Status}}),
{stop, ChannelId, State}.
Function : handle_msg(Args ) - > { ok , State } | { stop , ChannelId , State }
handle_msg({ssh_channel_up, _, _}, #state{xf = Xf} = State) ->
ssh_xfer:protocol_version_request(Xf),
{ok, State};
handle_msg({timeout, undefined, From},
#state{xf = #ssh_xfer{channel = ChannelId}} = State) ->
ssh_channel:reply(From, {error, timeout}),
{stop, ChannelId, State};
handle_msg({timeout, Id, From}, #state{req_list = ReqList0} = State) ->
case lists:keysearch(Id, 1, ReqList0) of
false ->
{ok, State};
_ ->
ReqList = lists:keydelete(Id, 1, ReqList0),
ssh_channel:reply(From, {error, timeout}),
{ok, State#state{req_list = ReqList}}
end;
Connection manager goes down
handle_msg({'DOWN', _Ref, _Type, _Process, _},
#state{xf = #ssh_xfer{channel = ChannelId}} = State) ->
{stop, ChannelId, State};
handle_msg({'EXIT', _, ssh_sftp_stop_channel},
#state{xf = #ssh_xfer{channel = ChannelId}} = State) ->
{stop, ChannelId, State};
handle_msg(_, State) ->
{ok, State}.
terminate(shutdown, #state{xf = #ssh_xfer{cm = Cm}} = State) ->
reply_all(State, {error, closed}),
ssh:close(Cm);
terminate(_Reason, State) ->
reply_all(State, {error, closed}).
Internal functions
call(Pid, Msg, TimeOut) ->
ssh_channel:call(Pid, {{timeout, TimeOut}, Msg}, infinity).
handle_reply(State, <<?UINT32(Len),Reply:Len/binary,Rest/binary>>) ->
do_handle_reply(State, Reply, Rest);
handle_reply(State, Data) ->
State#state{rep_buf = Data}.
do_handle_reply(#state{xf = Xf} = State,
<<?SSH_FXP_VERSION, ?UINT32(Version), BinExt/binary>>, Rest) ->
Ext = ssh_xfer:decode_ext(BinExt),
case Xf#ssh_xfer.vsn of
undefined ->
ok;
From ->
ssh_channel:reply(From, ok)
end,
State#state{xf = Xf#ssh_xfer{vsn = Version, ext = Ext}, rep_buf = Rest};
do_handle_reply(State0, Data, Rest) ->
case catch ssh_xfer:xf_reply(?XF(State0), Data) of
{'EXIT', _Reason} ->
handle_reply(State0, Rest);
XfReply ->
State = handle_req_reply(State0, XfReply),
handle_reply(State, Rest)
end.
handle_req_reply(State0, {_, ReqID, _} = XfReply) ->
case lists:keysearch(ReqID, 1, State0#state.req_list) of
false ->
State0;
{value,{_,Fun}} ->
List = lists:keydelete(ReqID, 1, State0#state.req_list),
State1 = State0#state { req_list = List },
case catch Fun(xreply(XfReply),State1) of
{'EXIT', _} ->
State1;
State ->
State
end
end.
xreply({handle,_,H}) -> {ok, H};
xreply({data,_,Data}) -> {ok, Data};
xreply({name,_,Names}) -> {ok, Names};
xreply({attrs, _, A}) -> {ok, attr_to_info(A)};
xreply({extended_reply,_,X}) -> {ok, X};
xreply({status,_,{ok, _Err, _Lang, _Rep}}) -> ok;
xreply({status,_,{eof, _Err, _Lang, _Rep}}) -> eof;
xreply({status,_,{Stat, _Err, _Lang, _Rep}}) -> {error, Stat};
xreply({Code, _, Reply}) -> {Code, Reply}.
update_request_info(ReqID, State, Fun) ->
List = [{ReqID,Fun} | State#state.req_list],
ID = (State#state.req_id + 1) band 16#ffffffff,
State#state { req_list = List, req_id = ID }.
async_reply(ReqID, Reply, _From={To,_}, State) ->
To ! {async_reply, ReqID, Reply},
State.
sync_reply(Reply, From, State) ->
catch (ssh_channel:reply(From, Reply)),
State.
open2(OrigReqID,FileName,Handle,Mode,Async,From,State) ->
I0 = State#state.inf,
FileMode = case lists:member(binary, Mode) orelse lists:member(raw, Mode) of
true -> binary;
false -> text
end,
I1 = add_new_handle(Handle, FileMode, I0),
State0 = State#state{inf = I1},
ReqID = State0#state.req_id,
ssh_xfer:stat(State0#state.xf, ReqID, FileName, [size]),
case Async of
true ->
update_request_info(ReqID, State0,
fun({ok,FI},State1) ->
Size = FI#file_info.size,
State2 = if is_integer(Size) ->
put_size(Handle, Size, State1);
true ->
State1
end,
async_reply(OrigReqID, {ok,Handle}, From, State2);
(_, State1) ->
async_reply(OrigReqID, {ok,Handle}, From, State1)
end);
false ->
update_request_info(ReqID, State0,
fun({ok,FI},State1) ->
Size = FI#file_info.size,
State2 = if is_integer(Size) ->
put_size(Handle, Size, State1);
true ->
State1
end,
sync_reply({ok,Handle}, From, State2);
(_, State1) ->
sync_reply({ok,Handle}, From, State1)
end)
end.
reply_all(State, Reply) ->
List = State#state.req_list,
lists:foreach(fun({_ReqID,Fun}) ->
catch Fun(Reply,State)
end, List),
State#state {req_list = []}.
make_reply(ReqID, true, From, State) ->
{reply, {async, ReqID},
update_request_info(ReqID, State,
fun(Reply,State1) ->
async_reply(ReqID,Reply,From,State1)
end)};
make_reply(ReqID, false, From, State) ->
{noreply,
update_request_info(ReqID, State,
fun(Reply,State1) ->
sync_reply(Reply, From, State1)
end)}.
make_reply_post(ReqID, true, From, State, PostFun) ->
{reply, {async, ReqID},
update_request_info(ReqID, State,
fun(Reply,State1) ->
case catch PostFun(Reply, State1) of
{'EXIT',_} ->
async_reply(ReqID,Reply, From, State1);
{Reply1, State2} ->
async_reply(ReqID,Reply1, From, State2)
end
end)};
make_reply_post(ReqID, false, From, State, PostFun) ->
{noreply,
update_request_info(ReqID, State,
fun(Reply,State1) ->
case catch PostFun(Reply, State1) of
{'EXIT',_} ->
sync_reply(Reply, From, State1);
{Reply1, State2} ->
sync_reply(Reply1, From, State2)
end
end)}.
info_to_attr(I) when is_record(I, file_info) ->
#ssh_xfer_attr { permissions = I#file_info.mode,
size = I#file_info.size,
type = I#file_info.type,
owner = I#file_info.uid,
group = I#file_info.gid,
atime = datetime_to_unix(I#file_info.atime),
mtime = datetime_to_unix(I#file_info.mtime),
createtime = datetime_to_unix(I#file_info.ctime)}.
attr_to_info(A) when is_record(A, ssh_xfer_attr) ->
#file_info{
size = A#ssh_xfer_attr.size,
type = A#ssh_xfer_attr.type,
atime = unix_to_datetime(A#ssh_xfer_attr.atime),
mtime = unix_to_datetime(A#ssh_xfer_attr.mtime),
ctime = unix_to_datetime(A#ssh_xfer_attr.createtime),
mode = A#ssh_xfer_attr.permissions,
links = 1,
major_device = 0,
minor_device = 0,
inode = 0,
uid = A#ssh_xfer_attr.owner,
gid = A#ssh_xfer_attr.group}.
Added workaround for sftp timestam problem . ( Timestamps should be
the time . the file - api will be updated so that we can
unix_to_datetime(undefined) ->
undefined;
unix_to_datetime(UTCSecs) ->
UTCDateTime =
calendar:gregorian_seconds_to_datetime(UTCSecs + 62167219200),
erlang:universaltime_to_localtime(UTCDateTime).
datetime_to_unix(undefined) ->
undefined;
datetime_to_unix(LocalDateTime) ->
UTCDateTime = erlang:localtime_to_universaltime(LocalDateTime),
calendar:datetime_to_gregorian_seconds(UTCDateTime) - 62167219200.
open_mode(Vsn,Modes) when Vsn >= 5 ->
open_mode5(Modes);
open_mode(_Vsn, Modes) ->
open_mode3(Modes).
open_mode5(Modes) ->
A = #ssh_xfer_attr{type = regular},
{Fl, Ac} = case {lists:member(write, Modes),
lists:member(read, Modes),
lists:member(append, Modes)} of
{_, _, true} ->
{[append_data],
[read_attributes,
append_data, write_attributes]};
{true, false, false} ->
{[create_truncate],
[write_data, write_attributes]};
{true, true, _} ->
{[open_or_create],
[read_data, read_attributes,
write_data, write_attributes]};
{false, true, _} ->
{[open_existing],
[read_data, read_attributes]}
end,
{Ac, Fl, A}.
open_mode3(Modes) ->
A = #ssh_xfer_attr{type = regular},
Fl = case {lists:member(write, Modes),
lists:member(read, Modes),
lists:member(append, Modes)} of
{_, _, true} ->
[append];
{true, false, false} ->
[write, creat, trunc];
{true, true, _} ->
[read, write];
{false, true, _} ->
[read]
end,
{[], Fl, A}.
new_inf() -> dict:new().
add_new_handle(Handle, FileMode, Inf) ->
dict:store(Handle, #fileinf{offset=0, size=0, mode=FileMode}, Inf).
update_size(Handle, NewSize, State) ->
OldSize = get_size(Handle, State),
if NewSize > OldSize ->
put_size(Handle, NewSize, State);
true ->
State
end.
set_offset(Handle , NewOffset ) - >
put({offset , Handle } , NewOffset ) .
update_offset(Handle, NewOffset, State0) ->
State1 = put_offset(Handle, NewOffset, State0),
update_size(Handle, NewOffset, State1).
put_size(Handle, Size, State) ->
Inf0 = State#state.inf,
case dict:find(Handle, Inf0) of
{ok, FI} ->
State#state{inf=dict:store(Handle, FI#fileinf{size=Size}, Inf0)};
_ ->
State#state{inf=dict:store(Handle, #fileinf{size=Size,offset=0},
Inf0)}
end.
put_offset(Handle, Offset, State) ->
Inf0 = State#state.inf,
case dict:find(Handle, Inf0) of
{ok, FI} ->
State#state{inf=dict:store(Handle, FI#fileinf{offset=Offset},
Inf0)};
_ ->
State#state{inf=dict:store(Handle, #fileinf{size=Offset,
offset=Offset}, Inf0)}
end.
get_size(Handle, State) ->
case dict:find(Handle, State#state.inf) of
{ok, FI} ->
FI#fileinf.size;
_ ->
undefined
end.
get_mode(Handle, State) ->
case dict:find(Handle, State#state.inf) of
{ok, FI} ->
FI#fileinf.mode;
_ ->
undefined
end.
erase_handle(Handle, State) ->
FI = dict:erase(Handle, State#state.inf),
State#state{inf = FI}.
Caluclate a integer offset
lseek_position(Handle, Pos, State) ->
case dict:find(Handle, State#state.inf) of
{ok, #fileinf{offset=O, size=S}} ->
lseek_pos(Pos, O, S);
_ ->
{error, einval}
end.
lseek_pos(_Pos, undefined, _) ->
{error, einval};
lseek_pos(Pos, _CurOffset, _CurSize)
when is_integer(Pos) andalso 0 =< Pos andalso Pos < ?SSH_FILEXFER_LARGEFILESIZE ->
{ok,Pos};
lseek_pos(bof, _CurOffset, _CurSize) ->
{ok,0};
lseek_pos(cur, CurOffset, _CurSize) ->
{ok,CurOffset};
lseek_pos(eof, _CurOffset, CurSize) ->
{ok,CurSize};
lseek_pos({bof, Offset}, _CurOffset, _CurSize)
when is_integer(Offset) andalso 0 =< Offset andalso Offset < ?SSH_FILEXFER_LARGEFILESIZE ->
{ok, Offset};
lseek_pos({cur, Offset}, CurOffset, _CurSize)
when is_integer(Offset) andalso -(?SSH_FILEXFER_LARGEFILESIZE) =< Offset andalso
Offset < ?SSH_FILEXFER_LARGEFILESIZE ->
NewOffset = CurOffset + Offset,
if NewOffset < 0 ->
{ok, 0};
true ->
{ok, NewOffset}
end;
lseek_pos({eof, Offset}, _CurOffset, CurSize)
when is_integer(Offset) andalso -(?SSH_FILEXFER_LARGEFILESIZE) =< Offset andalso
Offset < ?SSH_FILEXFER_LARGEFILESIZE ->
NewOffset = CurSize + Offset,
if NewOffset < 0 ->
{ok, 0};
true ->
{ok, NewOffset}
end;
lseek_pos(_, _, _) ->
{error, einval}.
connect(Cm) when is_pid(Cm) ->
connect(Cm, []);
connect(Host) when is_list(Host) ->
connect(Host, []).
connect(Cm, Opts) when is_pid(Cm) ->
Timeout = proplists:get_value(timeout, Opts, infinity),
case ssh_xfer:attach(Cm, []) of
{ok, ChannelId, Cm} ->
ssh_channel:start(Cm, ChannelId, ?MODULE, [Cm, ChannelId,
Timeout]);
Error ->
Error
end;
connect(Host, Opts) ->
connect(Host, 22, Opts).
connect(Host, Port, Opts) ->
Timeout = proplists:get_value(timeout, Opts, infinity),
case ssh_xfer:connect(Host, Port, proplists:delete(timeout, Opts)) of
{ok, ChannelId, Cm} ->
ssh_channel:start(Cm, ChannelId, ?MODULE, [Cm,
ChannelId, Timeout]);
Error ->
Error
end.
stop(Pid) ->
call(Pid, stop, infinity).
|
8032210fb71d76714838a6a53b5230edc005fc3b3c82a27a256335bcc59cd3ee | netguy204/clojure-gl | particle.clj | (ns clojure-gl.particle
(:use (clojure-gl primitive)))
(defn random-between [min max]
(let [range (- max min)
rand (Math/random)]
(+ min (* rand range))))
(defn random-angle []
(random-between 0 360))
(defn fire-particle [pt]
{:center pt
:rotation (random-angle)
:scale (random-between 0.1 0.2)
:spin-rate (random-between -18.0 18.0)
:scale-rate (random-between 0.1 1.0)
:time 0
:max-time (random-between 0.25 8.25)})
(defn normalized-time [particle]
(/ (particle :time) (particle :max-time)))
(defn exp-to-one [v]
(Math/exp (- v 1)))
(defn exp-alpha [particle]
(let [offset (normalized-time particle)]
(- 1 (exp-to-one offset))))
(defn updated-value [obj property delta-property dt]
(+ (obj property) (* (obj delta-property) dt)))
(defn update-particle [particle dt]
(let [new-time (+ (particle :time) dt)]
(if (< new-time (particle :max-time))
(conj particle
{:rotation (updated-value particle :rotation :spin-rate dt)
:scale (updated-value particle :scale :scale-rate dt)
:time new-time}))))
| null | https://raw.githubusercontent.com/netguy204/clojure-gl/055f73baf1af0149191f3574ad82f35017c532fc/src/clojure_gl/particle.clj | clojure | (ns clojure-gl.particle
(:use (clojure-gl primitive)))
(defn random-between [min max]
(let [range (- max min)
rand (Math/random)]
(+ min (* rand range))))
(defn random-angle []
(random-between 0 360))
(defn fire-particle [pt]
{:center pt
:rotation (random-angle)
:scale (random-between 0.1 0.2)
:spin-rate (random-between -18.0 18.0)
:scale-rate (random-between 0.1 1.0)
:time 0
:max-time (random-between 0.25 8.25)})
(defn normalized-time [particle]
(/ (particle :time) (particle :max-time)))
(defn exp-to-one [v]
(Math/exp (- v 1)))
(defn exp-alpha [particle]
(let [offset (normalized-time particle)]
(- 1 (exp-to-one offset))))
(defn updated-value [obj property delta-property dt]
(+ (obj property) (* (obj delta-property) dt)))
(defn update-particle [particle dt]
(let [new-time (+ (particle :time) dt)]
(if (< new-time (particle :max-time))
(conj particle
{:rotation (updated-value particle :rotation :spin-rate dt)
:scale (updated-value particle :scale :scale-rate dt)
:time new-time}))))
|
|
9453238ab789735f13b39d3b87bc6eae68d414582c0d76dfe6281ae53e547420 | carotene/carotene | carotene_api_authorization.erl | -module(carotene_api_authorization).
-export([authorize/1]).
-include_lib("eunit/include/eunit.hrl").
authorize(Ip) ->
case application:get_env(carotene, restrict_api_access_to) of
undefined -> true;
{ok, Ip} -> true;
_SomeIp -> false
end.
| null | https://raw.githubusercontent.com/carotene/carotene/963ecad344ec1c318c173ad828a5af3c000ddbfc/src/carotene_api_authorization.erl | erlang | -module(carotene_api_authorization).
-export([authorize/1]).
-include_lib("eunit/include/eunit.hrl").
authorize(Ip) ->
case application:get_env(carotene, restrict_api_access_to) of
undefined -> true;
{ok, Ip} -> true;
_SomeIp -> false
end.
|
|
354cd6a5b75b9e2725d2d306f160bb2a9cb7cb0650e2f0966a402e53c5fc7977 | helvm/helma | Symbol.hs | module HelVM.HelMA.Automata.BrainFuck.Common.Symbol (
inc,
compare0,
def,
next,
prev,
toInteger,
fromChar,
toChar,
Symbol,
) where
import Data.Default (Default)
import qualified Data.Default as Default
import qualified Relude.Extra as Extra
inc :: Symbol e => e -> e -> e
inc = flip (+)
compare0 :: Integer -> Ordering
compare0 = compare 0
--
def :: Symbol e => e
def = Default.def
next :: Symbol e => e -> e
next = Extra.next
prev :: Symbol e => e -> e
prev = Extra.prev
class (Bounded e , Default e , Enum e , Eq e , Integral e , Show e) => Symbol e where
-- toInteger :: e -> Integer
fromChar :: Char -> e
toChar :: e -> Char
--
instance Symbol Int where
-- toInteger = fromIntegral
fromChar = ord
toChar = chr
instance Symbol Word where
-- toInteger = fromIntegral
fromChar = fromIntegral . ord
toChar = chr . fromIntegral
instance Symbol Int8 where
-- toInteger = fromIntegral
fromChar = fromIntegral . ord
toChar = chr . normalizeMod . fromIntegral
instance Symbol Word8 where
-- toInteger = fromIntegral
fromChar = fromIntegral . ord
toChar = chr . fromIntegral
instance Symbol Int16 where
-- toInteger = fromIntegral
fromChar = fromIntegral . ord
toChar = chr . normalizeMod . fromIntegral
instance Symbol Word16 where
-- toInteger = fromIntegral
fromChar = fromIntegral . ord
toChar = chr . fromIntegral
instance Symbol Int32 where
-- toInteger = fromIntegral
fromChar = fromIntegral . ord
toChar = chr . normalizeMod . fromIntegral
instance Symbol Word32 where
-- toInteger = fromIntegral
fromChar = fromIntegral . ord
toChar = chr . fromIntegral
instance Symbol Int64 where
-- toInteger = fromIntegral
fromChar = fromIntegral . ord
toChar = chr . normalizeMod . fromIntegral
instance Symbol Word64 where
-- toInteger = fromIntegral
fromChar = fromIntegral . ord
toChar = chr . fromIntegral
--
countSymbols :: (Integral e) => e
countSymbols = 256
modifyMod :: (Integral e) => (e -> e) -> e -> e
modifyMod f i = f (i + countSymbols) `mod` countSymbols
normalizeMod :: (Integral e) => e -> e
normalizeMod = modifyMod id
| null | https://raw.githubusercontent.com/helvm/helma/b837ddc28308f3fe9bf506dbe68e2b42a142248c/hs/src/HelVM/HelMA/Automata/BrainFuck/Common/Symbol.hs | haskell |
toInteger :: e -> Integer
toInteger = fromIntegral
toInteger = fromIntegral
toInteger = fromIntegral
toInteger = fromIntegral
toInteger = fromIntegral
toInteger = fromIntegral
toInteger = fromIntegral
toInteger = fromIntegral
toInteger = fromIntegral
toInteger = fromIntegral
| module HelVM.HelMA.Automata.BrainFuck.Common.Symbol (
inc,
compare0,
def,
next,
prev,
toInteger,
fromChar,
toChar,
Symbol,
) where
import Data.Default (Default)
import qualified Data.Default as Default
import qualified Relude.Extra as Extra
inc :: Symbol e => e -> e -> e
inc = flip (+)
compare0 :: Integer -> Ordering
compare0 = compare 0
def :: Symbol e => e
def = Default.def
next :: Symbol e => e -> e
next = Extra.next
prev :: Symbol e => e -> e
prev = Extra.prev
class (Bounded e , Default e , Enum e , Eq e , Integral e , Show e) => Symbol e where
fromChar :: Char -> e
toChar :: e -> Char
instance Symbol Int where
fromChar = ord
toChar = chr
instance Symbol Word where
fromChar = fromIntegral . ord
toChar = chr . fromIntegral
instance Symbol Int8 where
fromChar = fromIntegral . ord
toChar = chr . normalizeMod . fromIntegral
instance Symbol Word8 where
fromChar = fromIntegral . ord
toChar = chr . fromIntegral
instance Symbol Int16 where
fromChar = fromIntegral . ord
toChar = chr . normalizeMod . fromIntegral
instance Symbol Word16 where
fromChar = fromIntegral . ord
toChar = chr . fromIntegral
instance Symbol Int32 where
fromChar = fromIntegral . ord
toChar = chr . normalizeMod . fromIntegral
instance Symbol Word32 where
fromChar = fromIntegral . ord
toChar = chr . fromIntegral
instance Symbol Int64 where
fromChar = fromIntegral . ord
toChar = chr . normalizeMod . fromIntegral
instance Symbol Word64 where
fromChar = fromIntegral . ord
toChar = chr . fromIntegral
countSymbols :: (Integral e) => e
countSymbols = 256
modifyMod :: (Integral e) => (e -> e) -> e -> e
modifyMod f i = f (i + countSymbols) `mod` countSymbols
normalizeMod :: (Integral e) => e -> e
normalizeMod = modifyMod id
|
7520e077e2bf65cbc2bf0a6cc62135f4e7b7389031d818e784f4c63ef706a97d | tschady/advent-of-code | d12_test.clj | (ns aoc.2015.d12-test
(:require [aoc.2015.d12 :as sut]
[clojure.test :refer :all]))
(deftest part-1-examples
(are [output input] (= output (sut/part-1 input))
6 "[1,2,3]"
6 "{\"a\":2, \"b\":4}"
3 "[[[3]]]"
3 "{\"a\":{\"b\":4},\"c\":-1}"
0 "{\"a\":[-1,1]}"
0 "[-1,{\"a\":1}]"
0 "[]"
0 "{}"))
(deftest part-2-examples
(are [output input] (= output (sut/part-2 input))
6 "[1,2,3]"
4 "[1,{\"c\":\"red\",\"b\":2},3]"
0 "{\"d\":\"red\",\"e\":[1,2,3,4],\"f\":5}"
6 "[1,\"red\",5]"))
(deftest challenge
(is (= 119433 (sut/part-1 sut/input)))
(is (= 68466 (sut/part-2 sut/input))))
| null | https://raw.githubusercontent.com/tschady/advent-of-code/1e4a95ef580c3bf635837eff52aa998b0acfc666/test/aoc/2015/d12_test.clj | clojure | (ns aoc.2015.d12-test
(:require [aoc.2015.d12 :as sut]
[clojure.test :refer :all]))
(deftest part-1-examples
(are [output input] (= output (sut/part-1 input))
6 "[1,2,3]"
6 "{\"a\":2, \"b\":4}"
3 "[[[3]]]"
3 "{\"a\":{\"b\":4},\"c\":-1}"
0 "{\"a\":[-1,1]}"
0 "[-1,{\"a\":1}]"
0 "[]"
0 "{}"))
(deftest part-2-examples
(are [output input] (= output (sut/part-2 input))
6 "[1,2,3]"
4 "[1,{\"c\":\"red\",\"b\":2},3]"
0 "{\"d\":\"red\",\"e\":[1,2,3,4],\"f\":5}"
6 "[1,\"red\",5]"))
(deftest challenge
(is (= 119433 (sut/part-1 sut/input)))
(is (= 68466 (sut/part-2 sut/input))))
|
|
3fc497540dfa3e71469e6e5d1bcc99374268d11f209227b6d5a5f533e4496b0f | yetibot/core | util.clj | (ns yetibot.core.util
(:require
[clojure.string :as s]
[cemerick.url :refer [url]]))
(defn filter-nil-vals
"Takes a map and returns all of its non-nil values"
[m]
(into {} (remove (comp nil? second) m)))
(defn map-to-strs
"takes a hash-map and parses it to a map-like sequence"
[m]
(map (fn [[k v]] (str (name k) ": " v)) m))
(def env
(let [e (into {} (System/getenv))]
(zipmap (map keyword (keys e)) (vals e))))
(defn make-config
^{:deprecated "0.1.0"}
[required-keys] (into {} (map (fn [k] [k (env k)]) required-keys)))
(defn conf-valid?
^{:deprecated "0.1.0"}
[c] (every? identity (vals c)))
(defmacro ensure-config
^{:deprecated "0.1.0"}
[& body]
`(when (every? identity ~'config)
~@body))
(defn psuedo-format
"DEPRECATED: use yetibot.core.util.format/pseudo-format instead
Similar to clojure.core/format, except it only supports %s, and it will
replace all occurances of %s with the single arg. If there is no %s found, it
appends the arg to the end of the string instead."
^{:deprecated "0.1.0"}
[s arg]
(if (re-find #"\%s" s)
(s/replace s "%s" arg)
(str s " " arg)))
(defn indices
"Indices of elements of a collection matching pred"
[pred coll]
(keep-indexed #(when (pred %2) %1) coll))
;;; collection parsing
; helpers for all collection cmds
(defn ensure-items-collection
"Ensures items is a collection. If not but is a string, will split on newlines,
else will return nil"
[items]
(cond
(map? items) (map-to-strs items)
(coll? items) items
(instance? String items) (s/split items #"\n")
:else nil))
(comment
(ensure-items-collection '(1 2 3))
(ensure-items-collection [1 2 3])
(ensure-items-collection {"one" 1 "two" 2})
(ensure-items-collection "one: 1\ntwo: 2")
(ensure-items-collection 123)
)
(defn ensure-items-seqential
"Ensures items is Sequential. If it's not, such as a map, it will transform it
to a sequence of k: v strings."
[items]
(cond
(sequential? items) items
(map? items) (map-to-strs items)
:else (seq items)))
(comment
(ensure-items-seqential `(1 2 3))
(ensure-items-seqential #{1 2 3})
(ensure-items-seqential {"one" 1 "two" 2})
)
; keys / vals helpers
(defn map-like?
"determines if collection is a hash-map or map-like;
map-like is when every collection item has a ':' delimiter"
[items]
(or (map? items)
(every? #(re-find #".+:.+" %) items)))
(comment
(map-like? {:easy 1})
(map-like? ["key1:value1" "key2:value2"])
(map-like? '("key1:value1" "key2:value2"))
(map-like? ["is" "not" "map" "like"])
)
(defn split-kvs
"if collection is map-like?, split into a nested list [[k v]] instead
of a map so as to maintain the order, else return nil"
[items]
(cond
(map? items) (map vector (keys items) (vals items))
(map-like? items) (map #(s/split % #":") items)
:else nil))
(comment
(split-kvs {:easy 1 :to "see"})
(split-kvs ["key1:value1" "key2:value2"])
(split-kvs ["is" "not" "map" "like"])
)
(defn split-kvs-with
"if collection is map-like?, accepts a function to map over the
split keys from `split-kvs`, else returns original collection"
[f items]
(if-let [kvs (split-kvs items)]
(map (comp s/trim f) kvs)
items))
(comment
(split-kvs-with first {"first" "is first" "second" "is second"})
(split-kvs-with first ["is" "not" "map" "like"])
)
;; image detection
(def image-pattern #"\.(png|jpe?g|gif|webp|svg)$")
(defn image?
"Simple utility to detect if a URL represents an image purely by looking at
the file extension (i.e. not too smart)."
[possible-url]
(try
(let [{:keys [query path]} (url possible-url)]
(or
(re-find image-pattern path)
we indicate images from are jpgs by tossing a & t=.jpg on it
(= ".jpg" (get query "t"))))
(catch Exception _
false)))
(comment
(image? "")
(image? "")
(image? "")
) | null | https://raw.githubusercontent.com/yetibot/core/e35cc772622e91aec3ad7f411a99fff09acbd3f9/src/yetibot/core/util.clj | clojure | collection parsing
helpers for all collection cmds
keys / vals helpers
image detection | (ns yetibot.core.util
(:require
[clojure.string :as s]
[cemerick.url :refer [url]]))
(defn filter-nil-vals
"Takes a map and returns all of its non-nil values"
[m]
(into {} (remove (comp nil? second) m)))
(defn map-to-strs
"takes a hash-map and parses it to a map-like sequence"
[m]
(map (fn [[k v]] (str (name k) ": " v)) m))
(def env
(let [e (into {} (System/getenv))]
(zipmap (map keyword (keys e)) (vals e))))
(defn make-config
^{:deprecated "0.1.0"}
[required-keys] (into {} (map (fn [k] [k (env k)]) required-keys)))
(defn conf-valid?
^{:deprecated "0.1.0"}
[c] (every? identity (vals c)))
(defmacro ensure-config
^{:deprecated "0.1.0"}
[& body]
`(when (every? identity ~'config)
~@body))
(defn psuedo-format
"DEPRECATED: use yetibot.core.util.format/pseudo-format instead
Similar to clojure.core/format, except it only supports %s, and it will
replace all occurances of %s with the single arg. If there is no %s found, it
appends the arg to the end of the string instead."
^{:deprecated "0.1.0"}
[s arg]
(if (re-find #"\%s" s)
(s/replace s "%s" arg)
(str s " " arg)))
(defn indices
"Indices of elements of a collection matching pred"
[pred coll]
(keep-indexed #(when (pred %2) %1) coll))
(defn ensure-items-collection
"Ensures items is a collection. If not but is a string, will split on newlines,
else will return nil"
[items]
(cond
(map? items) (map-to-strs items)
(coll? items) items
(instance? String items) (s/split items #"\n")
:else nil))
(comment
(ensure-items-collection '(1 2 3))
(ensure-items-collection [1 2 3])
(ensure-items-collection {"one" 1 "two" 2})
(ensure-items-collection "one: 1\ntwo: 2")
(ensure-items-collection 123)
)
(defn ensure-items-seqential
"Ensures items is Sequential. If it's not, such as a map, it will transform it
to a sequence of k: v strings."
[items]
(cond
(sequential? items) items
(map? items) (map-to-strs items)
:else (seq items)))
(comment
(ensure-items-seqential `(1 2 3))
(ensure-items-seqential #{1 2 3})
(ensure-items-seqential {"one" 1 "two" 2})
)
(defn map-like?
map-like is when every collection item has a ':' delimiter"
[items]
(or (map? items)
(every? #(re-find #".+:.+" %) items)))
(comment
(map-like? {:easy 1})
(map-like? ["key1:value1" "key2:value2"])
(map-like? '("key1:value1" "key2:value2"))
(map-like? ["is" "not" "map" "like"])
)
(defn split-kvs
"if collection is map-like?, split into a nested list [[k v]] instead
of a map so as to maintain the order, else return nil"
[items]
(cond
(map? items) (map vector (keys items) (vals items))
(map-like? items) (map #(s/split % #":") items)
:else nil))
(comment
(split-kvs {:easy 1 :to "see"})
(split-kvs ["key1:value1" "key2:value2"])
(split-kvs ["is" "not" "map" "like"])
)
(defn split-kvs-with
"if collection is map-like?, accepts a function to map over the
split keys from `split-kvs`, else returns original collection"
[f items]
(if-let [kvs (split-kvs items)]
(map (comp s/trim f) kvs)
items))
(comment
(split-kvs-with first {"first" "is first" "second" "is second"})
(split-kvs-with first ["is" "not" "map" "like"])
)
(def image-pattern #"\.(png|jpe?g|gif|webp|svg)$")
(defn image?
"Simple utility to detect if a URL represents an image purely by looking at
the file extension (i.e. not too smart)."
[possible-url]
(try
(let [{:keys [query path]} (url possible-url)]
(or
(re-find image-pattern path)
we indicate images from are jpgs by tossing a & t=.jpg on it
(= ".jpg" (get query "t"))))
(catch Exception _
false)))
(comment
(image? "")
(image? "")
(image? "")
) |
971d364eb609ae76c24736dc7b19ed7f0940adf6450243e1e0ccc8d5c173e121 | spechub/Hets | GtkProverGUI.hs | |
Module : ./GUI / GtkProverGUI.hs
Description : Gtk GUI for the prover
Copyright : ( c ) , Uni Bremen 2008
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
This module provides a GUI for the prover .
Module : ./GUI/GtkProverGUI.hs
Description : Gtk GUI for the prover
Copyright : (c) Thiemo Wiedemeyer, Uni Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
This module provides a GUI for the prover.
-}
module GUI.GtkProverGUI ( showProverGUI ) where
import Graphics.UI.Gtk
import GUI.GtkUtils
import qualified GUI.Glade.ProverGUI as ProverGUI
not implemented in Gtk
import Common.AS_Annotation as AS_Anno
import qualified Common.Doc as Pretty
import Common.Result
import qualified Common.OrderedMap as OMap
import Common.ExtSign
import Common.GtkGoal
import Common.Utils
import Control.Concurrent.MVar
import Proofs.AbstractState
import Logic.Comorphism
import Logic.Logic
import Logic.Prover
import qualified Comorphisms.KnownProvers as KnownProvers
import Static.GTheory
import qualified Data.Map as Map
import Data.List
import Data.Maybe (fromMaybe, isJust )
data GProver = GProver
{ pName :: String
, comorphism :: [AnyComorphism]
, selected :: Int }
ProverGUI
-- | Displays the consistency checker window
showProverGUI :: ProofActions -- ^ record of possible GUI actions
-> String -- ^ theory name
-> String -- ^ warning information
-> G_theory -- ^ theory
-> KnownProvers.KnownProversMap -- ^ map of known provers
-> [(G_prover, AnyComorphism)]
-- ^ list of suitable comorphisms to provers for sublogic of G_theory
-> IO (Result G_theory)
showProverGUI prGuiAcs thName warn th knownProvers comorphList = do
initState <- recalculateSublogicF prGuiAcs
(initialState thName th knownProvers)
{ comorphismsToProvers = comorphList }
state <- newMVar initState
wait <- newEmptyMVar
postGUIAsync $ do
builder <- getGTKBuilder ProverGUI.get
-- get objects
window <- builderGetObject builder castToWindow "ProverGUI"
-- buttons at buttom
btnShowTheory <- builderGetObject builder castToButton "btnShowTheory"
btnShowSelectedTheory <- builderGetObject builder castToButton "btnShowSelected"
btnClose <- builderGetObject builder castToButton "btnClose"
-- goals view
trvGoals <- builderGetObject builder castToTreeView "trvGoals"
btnGoalsAll <- builderGetObject builder castToButton "btnGoalsAll"
btnGoalsNone <- builderGetObject builder castToButton "btnGoalsNone"
btnGoalsInvert <- builderGetObject builder castToButton "btnGoalsInvert"
btnGoalsSelectOpen <- builderGetObject builder castToButton "btnGoalsSelectOpen"
-- axioms view
trvAxioms <- builderGetObject builder castToTreeView "trvAxioms"
btnAxiomsAll <- builderGetObject builder castToButton "btnAxiomsAll"
btnAxiomsNone <- builderGetObject builder castToButton "btnAxiomsNone"
btnAxiomsInvert <- builderGetObject builder castToButton "btnAxiomsInvert"
btnAxiomsFormer <- builderGetObject builder castToButton "btnAxiomsFormer"
-- theorems view
trvTheorems <- builderGetObject builder castToTreeView "trvTheorems"
btnTheoremsAll <- builderGetObject builder castToButton "btnTheoremsAll"
btnTheoremsNone <- builderGetObject builder castToButton "btnTheoremsNone"
btnTheoremsInvert <- builderGetObject builder castToButton "btnTheoremsInvert"
-- status
btnDisplay <- builderGetObject builder castToButton "btnDisplay"
btnProofDetails <- builderGetObject builder castToButton "btnProofDetails"
btnProve <- builderGetObject builder castToButton "btnProve"
cbComorphism <- builderGetObject builder castToComboBox "cbComorphism"
lblSublogic <- builderGetObject builder castToLabel "lblSublogic"
-- prover
trvProvers <- builderGetObject builder castToTreeView "trvProvers"
windowSetTitle window $ "Prove: " ++ thName
-- set list data
listProvers <- setListData trvProvers pName []
listGoals <- setListData trvGoals showGoal $ toGoals initState
listAxioms <- setListData trvAxioms id $ toAxioms initState
listTheorems <- setListData trvTheorems id $ selectedGoals initState
-- setup comorphism combobox
comboBoxSetModelText cbComorphism
shC <- after cbComorphism changed $ modifyMVar_ state
$ setSelectedComorphism trvProvers listProvers cbComorphism
-- setup provers list
shP <- setListSelectorSingle trvProvers $ modifyMVar_ state
$ setSelectedProver trvProvers listProvers cbComorphism shC
-- setup axioms list
shA <- setListSelectorMultiple trvAxioms btnAxiomsAll btnAxiomsNone
btnAxiomsInvert $ modifyMVar_ state
$ setSelectedAxioms trvAxioms listAxioms
onClicked btnAxiomsFormer $ do
signalBlock shA
sel <- treeViewGetSelection trvAxioms
treeSelectionSelectAll sel
rs <- treeSelectionGetSelectedRows sel
mapM_ ( \ ~p@(row : []) -> do
i <- listStoreGetValue listAxioms row
(if wasATheorem initState (stripPrefixAxiom i)
then treeSelectionUnselectPath else treeSelectionSelectPath) sel p) rs
signalUnblock shA
modifyMVar_ state $ setSelectedAxioms trvAxioms listAxioms
-- setup theorems list
setListSelectorMultiple trvTheorems btnTheoremsAll btnTheoremsNone
btnTheoremsInvert $ modifyMVar_ state
$ setSelectedTheorems trvTheorems listTheorems
let noProver = [ toWidget btnProve
, toWidget cbComorphism
, toWidget lblSublogic ]
noAxiom = [ toWidget btnAxiomsAll
, toWidget btnAxiomsNone
, toWidget btnAxiomsInvert
, toWidget btnAxiomsFormer ]
noTheory = [ toWidget btnTheoremsAll
, toWidget btnTheoremsNone
, toWidget btnTheoremsInvert ]
noGoal = [ toWidget btnGoalsAll
, toWidget btnGoalsNone
, toWidget btnGoalsInvert
, toWidget btnGoalsSelectOpen ]
prove = [toWidget window]
update s' = do
signalBlock shP
s <- setSelectedProver trvProvers listProvers cbComorphism shC
=<< updateProver trvProvers listProvers
=<< updateSublogic lblSublogic prGuiAcs knownProvers
=<< setSelectedGoals trvGoals listGoals s'
signalUnblock shP
activate noProver
(isJust (selectedProver s) && not (null $ selectedGoals s))
return s
hasGoals = not . null $ selectedGoals initState
activate noGoal hasGoals
activate noAxiom (not . null $ includedAxioms initState)
activate noTheory hasGoals
-- setup goal list
shG <- setListSelectorMultiple trvGoals btnGoalsAll btnGoalsNone
btnGoalsInvert $ modifyMVar_ state update
onClicked btnGoalsSelectOpen $ do
signalBlock shG
sel <- treeViewGetSelection trvGoals
treeSelectionSelectAll sel
rs <- treeSelectionGetSelectedRows sel
mapM_ ( \ ~p@(row : []) -> do
g <- listStoreGetValue listGoals row
(if gStatus g `elem` [GOpen, GTimeout]
then treeSelectionSelectPath else treeSelectionUnselectPath) sel p) rs
signalUnblock shG
modifyMVar_ state update
-- button bindings
onClicked btnClose $ widgetDestroy window
onClicked btnShowTheory $ displayTheoryWithWarning "Theory" thName warn th
onClicked btnShowSelectedTheory $ readMVar state >>=
displayTheoryWithWarning "Selected Theory" thName warn . selectedTheory
onClicked btnDisplay $ readMVar state >>= displayGoals
onClicked btnProofDetails $ forkIO_ $ readMVar state >>= doShowProofDetails
onClicked btnProve $ do
modifyMVar_ state update
s' <- takeMVar state
activate prove False
forkIOWithPostProcessing (proveF prGuiAcs s')
$ \ (Result ds ms) -> do
s <- case ms of
Nothing -> errorDialog "Error" (showRelDiags 2 ds) >> return s'
Just res -> return res
activate prove True
signalBlock shG
updateGoals trvGoals listGoals s
signalUnblock shG
putMVar state =<< update s { proverRunning = False
, accDiags = accDiags s ++ ds }
onDestroy window $ putMVar wait ()
selectAllRows trvTheorems
selectAllRows trvAxioms
selectAllRows trvGoals
widgetShow window
_ <- takeMVar wait
s <- takeMVar state
return Result
{ diags = accDiags s
, maybeResult = Just $ currentTheory s }
-- | Called whenever the button "Display" is clicked.
displayGoals :: ProofState -> IO ()
displayGoals s = case currentTheory s of
G_theory lid1 _ (ExtSign sig1 _) _ sens1 _ -> do
let thName = theoryName s
goalsText = show . Pretty.vsep
. map (print_named lid1 . AS_Anno.mapNamed (simplify_sen lid1 sig1))
. toNamedList $ filterMapWithList (selectedGoals s) sens1
textView ("Selected Goals from Theory " ++ thName) goalsText
$ Just (thName ++ "-goals.txt")
updateComorphism :: TreeView -> ListStore GProver -> ComboBox
-> ConnectId ComboBox -> IO ()
updateComorphism view list cbComorphism sh = do
signalBlock sh
model <- comboBoxGetModelText cbComorphism
listStoreClear model
mfinder <- getSelectedSingle view list
case mfinder of
Just (_, f) -> do
mapM_ (comboBoxAppendText cbComorphism) $ expand f
comboBoxSetActive cbComorphism $ selected f
Nothing -> return ()
signalUnblock sh
expand :: GProver -> [ComboBoxText]
expand = toComboBoxText . comorphism
setSelectedComorphism :: TreeView -> ListStore GProver -> ComboBox -> ProofState
-> IO ProofState
setSelectedComorphism view list cbComorphism s = do
mfinder <- getSelectedSingle view list
case mfinder of
Just (i, f) -> do
sel <- comboBoxGetActive cbComorphism
let nf = f { selected = sel }
listStoreSetValue list i nf
return $ setGProver nf s
Nothing -> return s
setGProver :: GProver -> ProofState -> ProofState
setGProver f s =
let pn = pName f
c = comorphism f !! selected f
in s
{ selectedProver = Just pn
, proversMap = Map.insert pn [c] $ proversMap s}
updateSublogic :: Label -> ProofActions
-> KnownProvers.KnownProversMap -> ProofState
-> IO ProofState
updateSublogic lbl prGuiAcs knownProvers s' = do
s <- recalculateSublogicF prGuiAcs s'
{ proversMap = Map.unionWith (++) (proversMap s') knownProvers }
labelSetLabel lbl $ show $ sublogicOfTheory s
return s
updateProver :: TreeView -> ListStore GProver -> ProofState
-> IO ProofState
updateProver trvProvers listProvers s = do
let new = toProvers s
old <- listStoreToList listProvers
let prvs = map (\ p -> case find ((pName p ==) . pName) old of
Nothing -> p
Just p' -> let oldC = comorphism p' !! selected p' in
p { selected = fromMaybe 0 $ elemIndex oldC $ comorphism p }
) new
updateListData listProvers prvs
case selectedProver s of
Just p -> case findIndex ((p ==) . pName) prvs of
Just i -> do
sel <- treeViewGetSelection trvProvers
treeSelectionSelectPath sel [i]
Nothing -> selectFirst trvProvers
Nothing -> selectFirst trvProvers
return s
updateGoals :: TreeView -> ListStore Goal -> ProofState -> IO ()
updateGoals trvGoals listGoals s = do
let ng = toGoals s
sel <- getSelectedMultiple trvGoals listGoals
updateListData listGoals ng
selector <- treeViewGetSelection trvGoals
mapM_ (\ (_, Goal { gName = n }) -> treeSelectionSelectPath selector
[fromMaybe (error "Goal not found!") $ findIndex ((n ==) . gName) ng]
) sel
setSelectedGoals :: TreeView -> ListStore Goal -> ProofState
-> IO ProofState
setSelectedGoals trvGoals listGoals s = do
goals <- getSelectedMultiple trvGoals listGoals
return s { selectedGoals = map (gName . snd) goals }
setSelectedAxioms :: TreeView -> ListStore String -> ProofState
-> IO ProofState
setSelectedAxioms axs listAxs s = do
axioms <- getSelectedMultiple axs listAxs
return s { includedAxioms = map (stripPrefixAxiom . snd) axioms }
setSelectedTheorems :: TreeView -> ListStore String -> ProofState
-> IO ProofState
setSelectedTheorems ths listThs s = do
theorems <- getSelectedMultiple ths listThs
return s { includedTheorems = map snd theorems }
stripPrefixAxiom :: String -> String
stripPrefixAxiom a = tryToStripPrefix "(Th) " a
| Called whenever a prover is selected from the " Pick Theorem Prover " list .
setSelectedProver :: TreeView -> ListStore GProver -> ComboBox
-> ConnectId ComboBox -> ProofState
-> IO ProofState
setSelectedProver trvProvers listProvers cbComorphism shC s = do
mprover <- getSelectedSingle trvProvers listProvers
updateComorphism trvProvers listProvers cbComorphism shC
return $ case mprover of
Nothing -> s { selectedProver = Nothing }
Just (_, gp) -> setGProver gp s
wasATheorem :: ProofState -> String -> Bool
wasATheorem st i = case currentTheory st of
G_theory _ _ _ _ sens _ -> maybe False wasTheorem $ OMap.lookup i sens
toGoals :: ProofState -> [Goal]
toGoals = sort . map toGtkGoal . getGoals
toProvers :: ProofState -> [GProver]
toProvers = Map.elems . foldr (\ (p', c) m ->
let n = getProverName p'
p = Map.findWithDefault (GProver n [] 0) n m in
Map.insert n (p { comorphism = c : comorphism p}) m
) Map.empty . comorphismsToProvers
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/GUI/GtkProverGUI.hs | haskell | | Displays the consistency checker window
^ record of possible GUI actions
^ theory name
^ warning information
^ theory
^ map of known provers
^ list of suitable comorphisms to provers for sublogic of G_theory
get objects
buttons at buttom
goals view
axioms view
theorems view
status
prover
set list data
setup comorphism combobox
setup provers list
setup axioms list
setup theorems list
setup goal list
button bindings
| Called whenever the button "Display" is clicked. | |
Module : ./GUI / GtkProverGUI.hs
Description : Gtk GUI for the prover
Copyright : ( c ) , Uni Bremen 2008
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
This module provides a GUI for the prover .
Module : ./GUI/GtkProverGUI.hs
Description : Gtk GUI for the prover
Copyright : (c) Thiemo Wiedemeyer, Uni Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
This module provides a GUI for the prover.
-}
module GUI.GtkProverGUI ( showProverGUI ) where
import Graphics.UI.Gtk
import GUI.GtkUtils
import qualified GUI.Glade.ProverGUI as ProverGUI
not implemented in Gtk
import Common.AS_Annotation as AS_Anno
import qualified Common.Doc as Pretty
import Common.Result
import qualified Common.OrderedMap as OMap
import Common.ExtSign
import Common.GtkGoal
import Common.Utils
import Control.Concurrent.MVar
import Proofs.AbstractState
import Logic.Comorphism
import Logic.Logic
import Logic.Prover
import qualified Comorphisms.KnownProvers as KnownProvers
import Static.GTheory
import qualified Data.Map as Map
import Data.List
import Data.Maybe (fromMaybe, isJust )
data GProver = GProver
{ pName :: String
, comorphism :: [AnyComorphism]
, selected :: Int }
ProverGUI
-> [(G_prover, AnyComorphism)]
-> IO (Result G_theory)
showProverGUI prGuiAcs thName warn th knownProvers comorphList = do
initState <- recalculateSublogicF prGuiAcs
(initialState thName th knownProvers)
{ comorphismsToProvers = comorphList }
state <- newMVar initState
wait <- newEmptyMVar
postGUIAsync $ do
builder <- getGTKBuilder ProverGUI.get
window <- builderGetObject builder castToWindow "ProverGUI"
btnShowTheory <- builderGetObject builder castToButton "btnShowTheory"
btnShowSelectedTheory <- builderGetObject builder castToButton "btnShowSelected"
btnClose <- builderGetObject builder castToButton "btnClose"
trvGoals <- builderGetObject builder castToTreeView "trvGoals"
btnGoalsAll <- builderGetObject builder castToButton "btnGoalsAll"
btnGoalsNone <- builderGetObject builder castToButton "btnGoalsNone"
btnGoalsInvert <- builderGetObject builder castToButton "btnGoalsInvert"
btnGoalsSelectOpen <- builderGetObject builder castToButton "btnGoalsSelectOpen"
trvAxioms <- builderGetObject builder castToTreeView "trvAxioms"
btnAxiomsAll <- builderGetObject builder castToButton "btnAxiomsAll"
btnAxiomsNone <- builderGetObject builder castToButton "btnAxiomsNone"
btnAxiomsInvert <- builderGetObject builder castToButton "btnAxiomsInvert"
btnAxiomsFormer <- builderGetObject builder castToButton "btnAxiomsFormer"
trvTheorems <- builderGetObject builder castToTreeView "trvTheorems"
btnTheoremsAll <- builderGetObject builder castToButton "btnTheoremsAll"
btnTheoremsNone <- builderGetObject builder castToButton "btnTheoremsNone"
btnTheoremsInvert <- builderGetObject builder castToButton "btnTheoremsInvert"
btnDisplay <- builderGetObject builder castToButton "btnDisplay"
btnProofDetails <- builderGetObject builder castToButton "btnProofDetails"
btnProve <- builderGetObject builder castToButton "btnProve"
cbComorphism <- builderGetObject builder castToComboBox "cbComorphism"
lblSublogic <- builderGetObject builder castToLabel "lblSublogic"
trvProvers <- builderGetObject builder castToTreeView "trvProvers"
windowSetTitle window $ "Prove: " ++ thName
listProvers <- setListData trvProvers pName []
listGoals <- setListData trvGoals showGoal $ toGoals initState
listAxioms <- setListData trvAxioms id $ toAxioms initState
listTheorems <- setListData trvTheorems id $ selectedGoals initState
comboBoxSetModelText cbComorphism
shC <- after cbComorphism changed $ modifyMVar_ state
$ setSelectedComorphism trvProvers listProvers cbComorphism
shP <- setListSelectorSingle trvProvers $ modifyMVar_ state
$ setSelectedProver trvProvers listProvers cbComorphism shC
shA <- setListSelectorMultiple trvAxioms btnAxiomsAll btnAxiomsNone
btnAxiomsInvert $ modifyMVar_ state
$ setSelectedAxioms trvAxioms listAxioms
onClicked btnAxiomsFormer $ do
signalBlock shA
sel <- treeViewGetSelection trvAxioms
treeSelectionSelectAll sel
rs <- treeSelectionGetSelectedRows sel
mapM_ ( \ ~p@(row : []) -> do
i <- listStoreGetValue listAxioms row
(if wasATheorem initState (stripPrefixAxiom i)
then treeSelectionUnselectPath else treeSelectionSelectPath) sel p) rs
signalUnblock shA
modifyMVar_ state $ setSelectedAxioms trvAxioms listAxioms
setListSelectorMultiple trvTheorems btnTheoremsAll btnTheoremsNone
btnTheoremsInvert $ modifyMVar_ state
$ setSelectedTheorems trvTheorems listTheorems
let noProver = [ toWidget btnProve
, toWidget cbComorphism
, toWidget lblSublogic ]
noAxiom = [ toWidget btnAxiomsAll
, toWidget btnAxiomsNone
, toWidget btnAxiomsInvert
, toWidget btnAxiomsFormer ]
noTheory = [ toWidget btnTheoremsAll
, toWidget btnTheoremsNone
, toWidget btnTheoremsInvert ]
noGoal = [ toWidget btnGoalsAll
, toWidget btnGoalsNone
, toWidget btnGoalsInvert
, toWidget btnGoalsSelectOpen ]
prove = [toWidget window]
update s' = do
signalBlock shP
s <- setSelectedProver trvProvers listProvers cbComorphism shC
=<< updateProver trvProvers listProvers
=<< updateSublogic lblSublogic prGuiAcs knownProvers
=<< setSelectedGoals trvGoals listGoals s'
signalUnblock shP
activate noProver
(isJust (selectedProver s) && not (null $ selectedGoals s))
return s
hasGoals = not . null $ selectedGoals initState
activate noGoal hasGoals
activate noAxiom (not . null $ includedAxioms initState)
activate noTheory hasGoals
shG <- setListSelectorMultiple trvGoals btnGoalsAll btnGoalsNone
btnGoalsInvert $ modifyMVar_ state update
onClicked btnGoalsSelectOpen $ do
signalBlock shG
sel <- treeViewGetSelection trvGoals
treeSelectionSelectAll sel
rs <- treeSelectionGetSelectedRows sel
mapM_ ( \ ~p@(row : []) -> do
g <- listStoreGetValue listGoals row
(if gStatus g `elem` [GOpen, GTimeout]
then treeSelectionSelectPath else treeSelectionUnselectPath) sel p) rs
signalUnblock shG
modifyMVar_ state update
onClicked btnClose $ widgetDestroy window
onClicked btnShowTheory $ displayTheoryWithWarning "Theory" thName warn th
onClicked btnShowSelectedTheory $ readMVar state >>=
displayTheoryWithWarning "Selected Theory" thName warn . selectedTheory
onClicked btnDisplay $ readMVar state >>= displayGoals
onClicked btnProofDetails $ forkIO_ $ readMVar state >>= doShowProofDetails
onClicked btnProve $ do
modifyMVar_ state update
s' <- takeMVar state
activate prove False
forkIOWithPostProcessing (proveF prGuiAcs s')
$ \ (Result ds ms) -> do
s <- case ms of
Nothing -> errorDialog "Error" (showRelDiags 2 ds) >> return s'
Just res -> return res
activate prove True
signalBlock shG
updateGoals trvGoals listGoals s
signalUnblock shG
putMVar state =<< update s { proverRunning = False
, accDiags = accDiags s ++ ds }
onDestroy window $ putMVar wait ()
selectAllRows trvTheorems
selectAllRows trvAxioms
selectAllRows trvGoals
widgetShow window
_ <- takeMVar wait
s <- takeMVar state
return Result
{ diags = accDiags s
, maybeResult = Just $ currentTheory s }
displayGoals :: ProofState -> IO ()
displayGoals s = case currentTheory s of
G_theory lid1 _ (ExtSign sig1 _) _ sens1 _ -> do
let thName = theoryName s
goalsText = show . Pretty.vsep
. map (print_named lid1 . AS_Anno.mapNamed (simplify_sen lid1 sig1))
. toNamedList $ filterMapWithList (selectedGoals s) sens1
textView ("Selected Goals from Theory " ++ thName) goalsText
$ Just (thName ++ "-goals.txt")
updateComorphism :: TreeView -> ListStore GProver -> ComboBox
-> ConnectId ComboBox -> IO ()
updateComorphism view list cbComorphism sh = do
signalBlock sh
model <- comboBoxGetModelText cbComorphism
listStoreClear model
mfinder <- getSelectedSingle view list
case mfinder of
Just (_, f) -> do
mapM_ (comboBoxAppendText cbComorphism) $ expand f
comboBoxSetActive cbComorphism $ selected f
Nothing -> return ()
signalUnblock sh
expand :: GProver -> [ComboBoxText]
expand = toComboBoxText . comorphism
setSelectedComorphism :: TreeView -> ListStore GProver -> ComboBox -> ProofState
-> IO ProofState
setSelectedComorphism view list cbComorphism s = do
mfinder <- getSelectedSingle view list
case mfinder of
Just (i, f) -> do
sel <- comboBoxGetActive cbComorphism
let nf = f { selected = sel }
listStoreSetValue list i nf
return $ setGProver nf s
Nothing -> return s
setGProver :: GProver -> ProofState -> ProofState
setGProver f s =
let pn = pName f
c = comorphism f !! selected f
in s
{ selectedProver = Just pn
, proversMap = Map.insert pn [c] $ proversMap s}
updateSublogic :: Label -> ProofActions
-> KnownProvers.KnownProversMap -> ProofState
-> IO ProofState
updateSublogic lbl prGuiAcs knownProvers s' = do
s <- recalculateSublogicF prGuiAcs s'
{ proversMap = Map.unionWith (++) (proversMap s') knownProvers }
labelSetLabel lbl $ show $ sublogicOfTheory s
return s
updateProver :: TreeView -> ListStore GProver -> ProofState
-> IO ProofState
updateProver trvProvers listProvers s = do
let new = toProvers s
old <- listStoreToList listProvers
let prvs = map (\ p -> case find ((pName p ==) . pName) old of
Nothing -> p
Just p' -> let oldC = comorphism p' !! selected p' in
p { selected = fromMaybe 0 $ elemIndex oldC $ comorphism p }
) new
updateListData listProvers prvs
case selectedProver s of
Just p -> case findIndex ((p ==) . pName) prvs of
Just i -> do
sel <- treeViewGetSelection trvProvers
treeSelectionSelectPath sel [i]
Nothing -> selectFirst trvProvers
Nothing -> selectFirst trvProvers
return s
updateGoals :: TreeView -> ListStore Goal -> ProofState -> IO ()
updateGoals trvGoals listGoals s = do
let ng = toGoals s
sel <- getSelectedMultiple trvGoals listGoals
updateListData listGoals ng
selector <- treeViewGetSelection trvGoals
mapM_ (\ (_, Goal { gName = n }) -> treeSelectionSelectPath selector
[fromMaybe (error "Goal not found!") $ findIndex ((n ==) . gName) ng]
) sel
setSelectedGoals :: TreeView -> ListStore Goal -> ProofState
-> IO ProofState
setSelectedGoals trvGoals listGoals s = do
goals <- getSelectedMultiple trvGoals listGoals
return s { selectedGoals = map (gName . snd) goals }
setSelectedAxioms :: TreeView -> ListStore String -> ProofState
-> IO ProofState
setSelectedAxioms axs listAxs s = do
axioms <- getSelectedMultiple axs listAxs
return s { includedAxioms = map (stripPrefixAxiom . snd) axioms }
setSelectedTheorems :: TreeView -> ListStore String -> ProofState
-> IO ProofState
setSelectedTheorems ths listThs s = do
theorems <- getSelectedMultiple ths listThs
return s { includedTheorems = map snd theorems }
stripPrefixAxiom :: String -> String
stripPrefixAxiom a = tryToStripPrefix "(Th) " a
| Called whenever a prover is selected from the " Pick Theorem Prover " list .
setSelectedProver :: TreeView -> ListStore GProver -> ComboBox
-> ConnectId ComboBox -> ProofState
-> IO ProofState
setSelectedProver trvProvers listProvers cbComorphism shC s = do
mprover <- getSelectedSingle trvProvers listProvers
updateComorphism trvProvers listProvers cbComorphism shC
return $ case mprover of
Nothing -> s { selectedProver = Nothing }
Just (_, gp) -> setGProver gp s
wasATheorem :: ProofState -> String -> Bool
wasATheorem st i = case currentTheory st of
G_theory _ _ _ _ sens _ -> maybe False wasTheorem $ OMap.lookup i sens
toGoals :: ProofState -> [Goal]
toGoals = sort . map toGtkGoal . getGoals
toProvers :: ProofState -> [GProver]
toProvers = Map.elems . foldr (\ (p', c) m ->
let n = getProverName p'
p = Map.findWithDefault (GProver n [] 0) n m in
Map.insert n (p { comorphism = c : comorphism p}) m
) Map.empty . comorphismsToProvers
|
fcc2d1243e0b1696daf541e98f9efae43c2b2dbfe108a11c08a1115392fca595 | pNre/Hera | module_air_quality.ml | open Async
open Core
open Error_handler
type city = { name : string } [@@deriving of_jsonaf] [@@jsonaf.allow_extra_fields]
type data =
{ city : city
; dominentpol : string
; aqi : int
}
[@@deriving of_jsonaf] [@@jsonaf.allow_extra_fields]
type response =
{ status : string
; data : data
}
[@@deriving of_jsonaf] [@@jsonaf.allow_extra_fields]
let api_token = lazy (Sys.getenv_exn "AQI_TOKEN")
let uri path =
let token = Lazy.force api_token in
Uri.make ~scheme:"https" ~host:"api.waqi.info" ~path ~query:[ "token", [ token ] ] ()
;;
let string_of_aqi = function
| x when x <= 50 -> "Good"
| x when x <= 100 -> "Moderate"
| x when x <= 150 -> "Unhealthy-ish"
| x when x <= 200 -> "*Unhealthy*"
| x when x <= 300 -> "*Very Unhealthy*"
| _ -> "*Hazardous, RUN*"
;;
let description_of_concern = function
| "p2" -> "pm2.5"
| "p1" -> "pm10"
| "o3" -> "Ozone, O3"
| "n2" -> "Nitrogen dioxide, NO2"
| "s2" -> "Sulfur dioxide, SO2"
| "co" -> "Carbon monoxide, CO"
| x -> x
;;
let handle_success chat_id body =
let result =
Result.try_with (fun () -> body |> Jsonaf.of_string |> response_of_jsonaf)
in
match result with
| Ok { status = _; data } ->
let main = data.dominentpol in
let aqi = data.aqi in
let text =
sprintf
"Air quality in %s\nAQI: *%d*, *%s*\nMain pollutant: *%s*"
data.city.name
aqi
(string_of_aqi aqi)
(description_of_concern main)
in
Telegram.send_message_don't_wait ~chat_id ~text ()
| Error err -> handle_module_error chat_id (`Exn err)
;;
let get_air_quality ~chat_id ~city =
Http.request `GET (uri ("/feed/" ^ Uri.pct_encode ~component:`Path city)) ()
>>=? (fun (_, body) -> Http.string_of_body body >>| Result.return)
>>> function
| Ok body -> handle_success chat_id body
| Error err -> handle_module_error chat_id err
;;
(* Bot module *)
let register () = ()
let help () = "*Air quality*\n`aq [city] [state] [country]`"
let on_update update =
match Telegram.parse_update update with
| `Command ("aq", [ city ], chat_id, _) ->
get_air_quality ~chat_id ~city;
true
| _ -> false
;;
| null | https://raw.githubusercontent.com/pNre/Hera/f3928380eb94a61637f0459818f9cec650ee8220/hera/module_air_quality/module_air_quality.ml | ocaml | Bot module | open Async
open Core
open Error_handler
type city = { name : string } [@@deriving of_jsonaf] [@@jsonaf.allow_extra_fields]
type data =
{ city : city
; dominentpol : string
; aqi : int
}
[@@deriving of_jsonaf] [@@jsonaf.allow_extra_fields]
type response =
{ status : string
; data : data
}
[@@deriving of_jsonaf] [@@jsonaf.allow_extra_fields]
let api_token = lazy (Sys.getenv_exn "AQI_TOKEN")
let uri path =
let token = Lazy.force api_token in
Uri.make ~scheme:"https" ~host:"api.waqi.info" ~path ~query:[ "token", [ token ] ] ()
;;
let string_of_aqi = function
| x when x <= 50 -> "Good"
| x when x <= 100 -> "Moderate"
| x when x <= 150 -> "Unhealthy-ish"
| x when x <= 200 -> "*Unhealthy*"
| x when x <= 300 -> "*Very Unhealthy*"
| _ -> "*Hazardous, RUN*"
;;
let description_of_concern = function
| "p2" -> "pm2.5"
| "p1" -> "pm10"
| "o3" -> "Ozone, O3"
| "n2" -> "Nitrogen dioxide, NO2"
| "s2" -> "Sulfur dioxide, SO2"
| "co" -> "Carbon monoxide, CO"
| x -> x
;;
let handle_success chat_id body =
let result =
Result.try_with (fun () -> body |> Jsonaf.of_string |> response_of_jsonaf)
in
match result with
| Ok { status = _; data } ->
let main = data.dominentpol in
let aqi = data.aqi in
let text =
sprintf
"Air quality in %s\nAQI: *%d*, *%s*\nMain pollutant: *%s*"
data.city.name
aqi
(string_of_aqi aqi)
(description_of_concern main)
in
Telegram.send_message_don't_wait ~chat_id ~text ()
| Error err -> handle_module_error chat_id (`Exn err)
;;
let get_air_quality ~chat_id ~city =
Http.request `GET (uri ("/feed/" ^ Uri.pct_encode ~component:`Path city)) ()
>>=? (fun (_, body) -> Http.string_of_body body >>| Result.return)
>>> function
| Ok body -> handle_success chat_id body
| Error err -> handle_module_error chat_id err
;;
let register () = ()
let help () = "*Air quality*\n`aq [city] [state] [country]`"
let on_update update =
match Telegram.parse_update update with
| `Command ("aq", [ city ], chat_id, _) ->
get_air_quality ~chat_id ~city;
true
| _ -> false
;;
|
1021fc9eeca10e026e7ff95b9a59082c3ab6030b1301aac7b72205659ccc7015 | OCamlPro/freeton_wallet | commandSwitchCreate.ml | (**************************************************************************)
(* *)
Copyright ( c ) 2021 OCamlPro 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. *)
(* *)
(* *)
(**************************************************************************)
open Ezcmd.V2
open EZCMD.TYPES
open Types
let action ~switch ~url ~image ~force ?(toolchain="") () =
match switch with
| None ->
Error.raise
"You must specify the name of the switch to create"
| Some net_name ->
let config = Config.config () in
if List.exists (fun net -> net.net_name = net_name )
config.networks then
Error.raise "Network %S already exists" net_name ;
let add_network ?(net_keys=[]) ?(net_deployer="deployer") node =
let net = {
net_name ;
net_nodes = [ node ] ;
current_node = node.node_name ;
current_account = None ;
net_keys ;
net_deployer ;
net_toolchain = toolchain;
} in
config.networks <- config.networks @ [ net ];
config.current_network <- net_name ;
config.modified <- true
in
match url, EzString.chop_prefix ~prefix:"sandbox" net_name with
| Some node_url, None ->
add_network {
node_name = "node" ;
node_url ;
node_local = None ;
}
| Some _node_url, Some _ ->
Error.raise "sandbox network %S URL cannot be specified" net_name
| None, None ->
List.iter (fun net ->
if net_name = net.net_name then begin
config.networks <- config.networks @ [ net ] ;
config.current_network <- net_name ;
config.modified <- true ;
end
) Config.known_networks ;
if not config.modified then
Error.raise
"New network %S must either be sandboxed 'sandboxN', remote (--url) or known (%s)"
net_name
(String.concat ", "
( List.map (fun net -> net.net_name ) Config.known_networks ))
| None, Some n ->
let n = int_of_string n in
let local_port = 7080+n in
let node_local = { local_port } in
let container = CommandNodeStart.container_of_node node_local in
let docker_start () =
Misc.call [
"docker"; "create";
"--name"; container ;
"-e" ; "USER_AGREEMENT=yes" ;
Printf.sprintf "-p%d:80" local_port ;
image
];
in
begin
try
docker_start ()
with exn ->
if force then begin
Misc.call [ "docker" ; "rm" ; container ];
docker_start ()
end
else
raise exn
end;
add_network
~net_keys:Config.sandbox_keys
~net_deployer:"user1"
{
node_name = "node" ;
node_url = Printf.sprintf ":%d" local_port ;
node_local = Some node_local;
}
let cmd =
let switch = ref None in
let url = ref None in
let toolchain = ref None in
let image = ref "tonlabs/local-node" in
let force = ref false in
EZCMD.sub
"switch create"
(fun () ->
action
~switch:!switch
~url:!url
~image:!image
?toolchain:!toolchain
~force:!force
()
)
~args: (
[
[], Arg.Anon (0, fun s -> switch := Some s),
EZCMD.info ~docv:"NETWORK" "Name of network switch to create" ;
[ "url" ], Arg.String ( fun s -> url := Some s ),
EZCMD.info ~docv:"URL" "URL of the default node in this network" ;
[ "image" ], Arg.String ( fun s -> image := s ),
EZCMD.info ~docv:"DOCKER" "Docker image to use for sandboxes" ;
[ "force" ], Arg.Set force,
EZCMD.info "Force switch creation, killing docker container if needed" ;
[ "toolchain" ], Arg.String ( fun s -> toolchain := Some s ),
EZCMD.info ~docv:"TOOLCHAIN" "Toolchain to use" ;
] )
~doc: "Create a new switch for an existing network, or create a sandbox local network"
~man:[
`S "DESCRIPTION";
`Blocks [
`P "This command is used to create new switches, either for \
existing remote networks (mainnet, testnet, etc.) by \
providing their URL with --url, or to create new local \
networks running TONOS SE (such switches must be called \
'sandboxNN' where NN is a number). Each switch includes \
its own set of accounts and nodes.";
`P "When a new switch is created, it immediately becomes the \
current switch."
];
`S "EXAMPLES";
`Blocks [
`P "Display current network and other existing networks:";
`Pre {|$ ft switch list|};
`P "Change current network to an existing network NETWORK:";
`Pre {|$ ft switch to NETWORK|};
`P "Create a new network with name NETWORK and url URL, and switch to that network:";
`Pre {|$ ft switch create NETWORK --url URL|};
`P "Removing a created network:";
`Pre {|$ ft switch remove NETWORK|};
];
`S "SANDBOXING";
`Blocks [
`P "As a specific feature, ft can create networks based on TONOS SE to run on the local computer. Such networks are automatically created by naming the network 'sandboxN` where N is a number. The corresponding node will run on port 7080+N.";
`P "Example of session (create network, start node, give user1 1000 TONs):";
`Pre {|$ ft switch create sandbox1|};
`Pre {|$ ft node start|};
`Pre {|$ ft node give user1 --amount 1000|};
`P "When a local network is created, it is initialized with:";
`I ("1.", "An account 'giver' corresponding to the Giver contract holding 5 billion TONS");
`I ("2.", "A set of 10 accounts 'user0' to 'user9'. These accounts always have the same secret keys, so it is possible to define test scripts that will work on different instances of local networks.");
`P "The 10 accounts are not deployed, but it is possible to use 'ft node give ACCOUNT' to automatically deploy the account."
];
]
| null | https://raw.githubusercontent.com/OCamlPro/freeton_wallet/fd9a1edf51aa7c187b40aef8e0c8186a44209890/src/freeton_wallet_lib/commandSwitchCreate.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.
************************************************************************ | Copyright ( c ) 2021 OCamlPro SAS
Public License version 2.1 , with the special exception on linking
open Ezcmd.V2
open EZCMD.TYPES
open Types
let action ~switch ~url ~image ~force ?(toolchain="") () =
match switch with
| None ->
Error.raise
"You must specify the name of the switch to create"
| Some net_name ->
let config = Config.config () in
if List.exists (fun net -> net.net_name = net_name )
config.networks then
Error.raise "Network %S already exists" net_name ;
let add_network ?(net_keys=[]) ?(net_deployer="deployer") node =
let net = {
net_name ;
net_nodes = [ node ] ;
current_node = node.node_name ;
current_account = None ;
net_keys ;
net_deployer ;
net_toolchain = toolchain;
} in
config.networks <- config.networks @ [ net ];
config.current_network <- net_name ;
config.modified <- true
in
match url, EzString.chop_prefix ~prefix:"sandbox" net_name with
| Some node_url, None ->
add_network {
node_name = "node" ;
node_url ;
node_local = None ;
}
| Some _node_url, Some _ ->
Error.raise "sandbox network %S URL cannot be specified" net_name
| None, None ->
List.iter (fun net ->
if net_name = net.net_name then begin
config.networks <- config.networks @ [ net ] ;
config.current_network <- net_name ;
config.modified <- true ;
end
) Config.known_networks ;
if not config.modified then
Error.raise
"New network %S must either be sandboxed 'sandboxN', remote (--url) or known (%s)"
net_name
(String.concat ", "
( List.map (fun net -> net.net_name ) Config.known_networks ))
| None, Some n ->
let n = int_of_string n in
let local_port = 7080+n in
let node_local = { local_port } in
let container = CommandNodeStart.container_of_node node_local in
let docker_start () =
Misc.call [
"docker"; "create";
"--name"; container ;
"-e" ; "USER_AGREEMENT=yes" ;
Printf.sprintf "-p%d:80" local_port ;
image
];
in
begin
try
docker_start ()
with exn ->
if force then begin
Misc.call [ "docker" ; "rm" ; container ];
docker_start ()
end
else
raise exn
end;
add_network
~net_keys:Config.sandbox_keys
~net_deployer:"user1"
{
node_name = "node" ;
node_url = Printf.sprintf ":%d" local_port ;
node_local = Some node_local;
}
let cmd =
let switch = ref None in
let url = ref None in
let toolchain = ref None in
let image = ref "tonlabs/local-node" in
let force = ref false in
EZCMD.sub
"switch create"
(fun () ->
action
~switch:!switch
~url:!url
~image:!image
?toolchain:!toolchain
~force:!force
()
)
~args: (
[
[], Arg.Anon (0, fun s -> switch := Some s),
EZCMD.info ~docv:"NETWORK" "Name of network switch to create" ;
[ "url" ], Arg.String ( fun s -> url := Some s ),
EZCMD.info ~docv:"URL" "URL of the default node in this network" ;
[ "image" ], Arg.String ( fun s -> image := s ),
EZCMD.info ~docv:"DOCKER" "Docker image to use for sandboxes" ;
[ "force" ], Arg.Set force,
EZCMD.info "Force switch creation, killing docker container if needed" ;
[ "toolchain" ], Arg.String ( fun s -> toolchain := Some s ),
EZCMD.info ~docv:"TOOLCHAIN" "Toolchain to use" ;
] )
~doc: "Create a new switch for an existing network, or create a sandbox local network"
~man:[
`S "DESCRIPTION";
`Blocks [
`P "This command is used to create new switches, either for \
existing remote networks (mainnet, testnet, etc.) by \
providing their URL with --url, or to create new local \
networks running TONOS SE (such switches must be called \
'sandboxNN' where NN is a number). Each switch includes \
its own set of accounts and nodes.";
`P "When a new switch is created, it immediately becomes the \
current switch."
];
`S "EXAMPLES";
`Blocks [
`P "Display current network and other existing networks:";
`Pre {|$ ft switch list|};
`P "Change current network to an existing network NETWORK:";
`Pre {|$ ft switch to NETWORK|};
`P "Create a new network with name NETWORK and url URL, and switch to that network:";
`Pre {|$ ft switch create NETWORK --url URL|};
`P "Removing a created network:";
`Pre {|$ ft switch remove NETWORK|};
];
`S "SANDBOXING";
`Blocks [
`P "As a specific feature, ft can create networks based on TONOS SE to run on the local computer. Such networks are automatically created by naming the network 'sandboxN` where N is a number. The corresponding node will run on port 7080+N.";
`P "Example of session (create network, start node, give user1 1000 TONs):";
`Pre {|$ ft switch create sandbox1|};
`Pre {|$ ft node start|};
`Pre {|$ ft node give user1 --amount 1000|};
`P "When a local network is created, it is initialized with:";
`I ("1.", "An account 'giver' corresponding to the Giver contract holding 5 billion TONS");
`I ("2.", "A set of 10 accounts 'user0' to 'user9'. These accounts always have the same secret keys, so it is possible to define test scripts that will work on different instances of local networks.");
`P "The 10 accounts are not deployed, but it is possible to use 'ft node give ACCOUNT' to automatically deploy the account."
];
]
|
07ea560a381be95ffacf22ca61b7b4e54735aeeb89eab671fed1c60ee48a1d67 | semilin/layoup | rnst02.lisp |
(MAKE-LAYOUT :NAME "rnst02" :MATRIX
(APPLY #'KEY-MATRIX '("xblmvgpuo," "rnstdyceai" "zhjkqwf;'."))
:SHIFT-MATRIX NIL :KEYBOARD NIL) | null | https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/rnst02.lisp | lisp |
(MAKE-LAYOUT :NAME "rnst02" :MATRIX
(APPLY #'KEY-MATRIX '("xblmvgpuo," "rnstdyceai" "zhjkqwf;'."))
:SHIFT-MATRIX NIL :KEYBOARD NIL) |
|
de2e56c4a8824171aca59874b094d9c1836eed02839b462f14628c922f690ee8 | tov/dssl2 | rte.rkt | #lang racket/base
(provide current-dssl-test-points
setup-rte)
(require (only-in racket/port
relocate-input-port)
"parser.rkt"
"printer.rkt")
(define current-dssl-test-points
(make-parameter #t))
(define (setup-rte)
(global-port-print-handler
(λ (value port) (dssl-print value port)))
(current-read-interaction
(λ (src in)
(let loop ()
(define-values (line column position) (port-next-location in))
(define the-line (read-line in))
(cond
[(eof-object? the-line)
the-line]
[(regexp-match #rx"^ *$" the-line)
(loop)]
[else
(define line-port (open-input-string the-line))
(port-count-lines! line-port)
(define relocated
(relocate-input-port line-port line column position
#true #:name src))
(parse-dssl2 src relocated #t)])))))
| null | https://raw.githubusercontent.com/tov/dssl2/105d18069465781bd9b87466f8336d5ce9e9a0f3/private/rte.rkt | racket | #lang racket/base
(provide current-dssl-test-points
setup-rte)
(require (only-in racket/port
relocate-input-port)
"parser.rkt"
"printer.rkt")
(define current-dssl-test-points
(make-parameter #t))
(define (setup-rte)
(global-port-print-handler
(λ (value port) (dssl-print value port)))
(current-read-interaction
(λ (src in)
(let loop ()
(define-values (line column position) (port-next-location in))
(define the-line (read-line in))
(cond
[(eof-object? the-line)
the-line]
[(regexp-match #rx"^ *$" the-line)
(loop)]
[else
(define line-port (open-input-string the-line))
(port-count-lines! line-port)
(define relocated
(relocate-input-port line-port line column position
#true #:name src))
(parse-dssl2 src relocated #t)])))))
|
|
ee1d298daf2adfa645c0b16deb3fbcad7841f8ef19ea7c52c63f2df664924dda | awakesecurity/hocker | Image.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
-----------------------------------------------------------------------------
-- |
-- Module : Data.Docker.Image
Copyright : ( C ) 2016 Awake Networks
-- License : Apache-2.0
Maintainer : Awake Networks < >
-- Stability : stable
----------------------------------------------------------------------------
module Tests.Data.Docker.Image where
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as C8L
import Data.Docker.Image.Types
import Data.HashMap.Strict as H
import Test.Tasty
import Test.Tasty.HUnit
import Hocker.Lib
-----------------------------------------------------------------------------
--
unitTests = testGroup "V1.2 Image Tests"
[ testCase "ImageManifest golden encoding" testImageManifestGoldenEncoding
, testCase "ImageManifest two-way encoding" testImageManifestTwoWayEncoding
, testCase "ImageRepositories golden encoding" testImageRepositoriesGoldenEncoding
, testCase "ImageRepositories two-way encoding" testImageRepositoriesTwoWayEncoding
]
-----------------------------------------------------------------------------
-- TESTS
testImageManifestGoldenEncoding =
let goldenStr = "[{\"Config\":\"3e83c23dba6a16cd936a3dc044df71b26706c5a4c28181bc3ca4a4af9f5f38ee.json\",\"Layers\":[\"10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9/layer.tar\"],\"RepoTags\":[\"library/debian:jessie\"]}]"
imgManifest = [ImageManifest
"3e83c23dba6a16cd936a3dc044df71b26706c5a4c28181bc3ca4a4af9f5f38ee.json"
[ "library/debian:jessie" ]
[ "10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9/layer.tar" ]
]
in (Hocker.Lib.encodeCanonical imgManifest) @?= (C8L.pack goldenStr)
testImageManifestTwoWayEncoding =
let imgManifest = [ImageManifest
"3e83c23dba6a16cd936a3dc044df71b26706c5a4c28181bc3ca4a4af9f5f38ee.json"
[ "library/debian:jessie" ]
[ "10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9/layer.tar" ]
]
encoded = Hocker.Lib.encodeCanonical imgManifest
in decode encoded @?= (Just imgManifest)
testImageRepositoriesGoldenEncoding =
let goldenStr = "{\"library/debian\":{\"jessie\":\"10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9\"}}"
imgRepos = ImageRepositories
[ImageRepo
"library/debian"
(H.singleton
"jessie"
"10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9")]
in (Hocker.Lib.encodeCanonical imgRepos) @?= (C8L.pack goldenStr)
testImageRepositoriesTwoWayEncoding =
let imgRepos = ImageRepositories
[ImageRepo
"library/debian"
(H.singleton
"jessie"
"10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9")]
encoded = Hocker.Lib.encodeCanonical imgRepos
in decode encoded @?= (Just imgRepos)
| null | https://raw.githubusercontent.com/awakesecurity/hocker/4610befce9881e85925e96ebf464e925fae67164/test/Tests/Data/Docker/Image.hs | haskell | # LANGUAGE OverloadedStrings #
---------------------------------------------------------------------------
|
Module : Data.Docker.Image
License : Apache-2.0
Stability : stable
--------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
TESTS | # LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
Copyright : ( C ) 2016 Awake Networks
Maintainer : Awake Networks < >
module Tests.Data.Docker.Image where
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as C8L
import Data.Docker.Image.Types
import Data.HashMap.Strict as H
import Test.Tasty
import Test.Tasty.HUnit
import Hocker.Lib
unitTests = testGroup "V1.2 Image Tests"
[ testCase "ImageManifest golden encoding" testImageManifestGoldenEncoding
, testCase "ImageManifest two-way encoding" testImageManifestTwoWayEncoding
, testCase "ImageRepositories golden encoding" testImageRepositoriesGoldenEncoding
, testCase "ImageRepositories two-way encoding" testImageRepositoriesTwoWayEncoding
]
testImageManifestGoldenEncoding =
let goldenStr = "[{\"Config\":\"3e83c23dba6a16cd936a3dc044df71b26706c5a4c28181bc3ca4a4af9f5f38ee.json\",\"Layers\":[\"10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9/layer.tar\"],\"RepoTags\":[\"library/debian:jessie\"]}]"
imgManifest = [ImageManifest
"3e83c23dba6a16cd936a3dc044df71b26706c5a4c28181bc3ca4a4af9f5f38ee.json"
[ "library/debian:jessie" ]
[ "10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9/layer.tar" ]
]
in (Hocker.Lib.encodeCanonical imgManifest) @?= (C8L.pack goldenStr)
testImageManifestTwoWayEncoding =
let imgManifest = [ImageManifest
"3e83c23dba6a16cd936a3dc044df71b26706c5a4c28181bc3ca4a4af9f5f38ee.json"
[ "library/debian:jessie" ]
[ "10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9/layer.tar" ]
]
encoded = Hocker.Lib.encodeCanonical imgManifest
in decode encoded @?= (Just imgManifest)
testImageRepositoriesGoldenEncoding =
let goldenStr = "{\"library/debian\":{\"jessie\":\"10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9\"}}"
imgRepos = ImageRepositories
[ImageRepo
"library/debian"
(H.singleton
"jessie"
"10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9")]
in (Hocker.Lib.encodeCanonical imgRepos) @?= (C8L.pack goldenStr)
testImageRepositoriesTwoWayEncoding =
let imgRepos = ImageRepositories
[ImageRepo
"library/debian"
(H.singleton
"jessie"
"10a267c67f423630f3afe5e04bbbc93d578861ddcc54283526222f3ad5e895b9")]
encoded = Hocker.Lib.encodeCanonical imgRepos
in decode encoded @?= (Just imgRepos)
|
9140b5a44f2ae31c5e40f2bc8459f7c15e70fb9fafdb5a3e554d90a10c32ec6d | Frama-C/Frama-C-snapshot | wpStrategy.ml | (**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2019
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
let dkey = Wp_parameters.register_category "strategy" (* debugging key *)
let debug fmt = Wp_parameters.debug ~dkey fmt
open Cil_types
open LogicUsage
(* -------------------------------------------------------------------------- *)
(** An annotation can be used for different purpose. *)
type annot_kind =
annotation is an hypothesis ,
but not a goal ( see ) : A = > ...
but not a goal (see Aboth) : A => ...*)
annotation is a goal ,
but not an hypothesis ( see ): A /\ ...
but not an hypothesis (see Aboth): A /\ ...*)
| Aboth of bool
(* annotation can be used as both hypothesis and goal :
- with true : considered as both : A /\ A=>..
- with false : we just want to use it as hyp right now. *)
| AcutB of bool
(* annotation is use as a cut :
- with true (A is also a goal) -> A (+ proof obligation A => ...)
- with false (A is an hyp only) -> True (+ proof obligation A => ...) *)
| AcallHyp of kernel_function
(* annotation is a called function property to consider as an Hyp.
* The pre are not here but in AcallPre since they can also
* be considered as goals. *)
| AcallPre of bool * kernel_function
(* annotation is a called function precondition :
to be considered as hyp, and goal if bool=true *)
(* -------------------------------------------------------------------------- *)
--- Annotations for one program point . ---
(* -------------------------------------------------------------------------- *)
module ForCall = Kernel_function.Map
* Some elements can be used as both and Goal : because of the selection
* mechanism , we need to add a boolean [ as_goal ] to tell if the element is to be
* considered as a goal . If [ false ] , the element can still be used as hypothesis .
* mechanism, we need to add a boolean [as_goal] to tell if the element is to be
* considered as a goal. If [false], the element can still be used as hypothesis.
*)
type annots = {
p_hyp : WpPropId.pred_info list;
p_goal : WpPropId.pred_info list;
p_both : (bool * WpPropId.pred_info) list;
p_cut : (bool * WpPropId.pred_info) list;
call_hyp : WpPropId.pred_info list ForCall.t; (* post and pre *)
call_pre : (bool * WpPropId.pred_info) list ForCall.t; (* goal only *)
call_asgn : WpPropId.assigns_full_info ForCall.t;
a_goal : WpPropId.assigns_full_info;
a_hyp : WpPropId.assigns_full_info;
a_call : WpPropId.assigns_full_info; (* dynamic calls *)
}
type t_annots = { has_asgn_goal : bool; has_prop_goal : bool; info: annots }
(* --- Add annotations --- *)
let empty_acc =
let a = {
p_hyp = []; p_goal = []; p_both = []; p_cut = [];
call_hyp = ForCall.empty;
call_pre = ForCall.empty;
call_asgn = ForCall.empty;
a_goal = WpPropId.empty_assigns_info;
a_hyp = WpPropId.empty_assigns_info;
a_call = WpPropId.empty_assigns_info;
} in
{ has_asgn_goal = false; has_prop_goal = false; info = a; }
let normalize id ?assumes labels p =
try
let p = NormAtLabels.preproc_annot labels p in
match assumes with
| None -> Some p
| Some a ->
let a = Logic_const.pat(a,Logic_const.pre_label) in
let a = NormAtLabels.(preproc_annot labels_fct_pre a) in
Some(Logic_const.pimplies(a,p))
with e ->
let pid = WpPropId.get_propid id in
NormAtLabels.catch_label_error e pid "annotation" ;
None
let add_prop acc kind id p =
let get_p = match p with None -> None
| Some p -> Some(WpPropId.mk_pred_info id p) in
let add_hyp l = match get_p with None -> l | Some p -> p::l in
let add_goal l = match get_p with None -> l | Some p -> p::l in
let add_both goal l =
match get_p with
| None -> l
| Some p -> (goal, p)::l
in
let add_hyp_call fct calls =
let l = try ForCall.find fct calls with Not_found -> [] in
ForCall.add fct (add_hyp l) calls in
let add_both_call fct goal calls =
let l = try ForCall.find fct calls with Not_found -> [] in
ForCall.add fct (add_both goal l) calls in
let info = acc.info in
let goal, info = match kind with
| Ahyp ->
false, { info with p_hyp = add_hyp info.p_hyp }
| Agoal ->
true, { info with p_goal = add_goal info.p_goal }
| Aboth goal ->
goal, { info with p_both = add_both goal info.p_both }
| AcutB goal ->
goal, { info with p_cut = add_both goal info.p_cut }
| AcallHyp fct ->
false, { info with call_hyp = add_hyp_call fct info.call_hyp }
| AcallPre (goal,fct) ->
goal, { info with call_pre = add_both_call fct goal info.call_pre }
in let acc = { acc with info = info } in
if goal then { acc with has_prop_goal = true} else acc
(* -------------------------------------------------------------------------- *)
(* adding some specific properties. *)
let add_prop_fct_pre_bhv acc kind kf bhv =
let norm_pred pred =
let p = Logic_const.pred_of_id_pred pred in
Logic_const.(pat (p,pre_label))
in
let requires = Logic_const.pands (List.map norm_pred bhv.b_requires) in
let assumes = Logic_const.pands (List.map norm_pred bhv.b_assumes) in
let precond = Logic_const.pimplies (assumes, requires) in
let precond_id = Logic_const.new_predicate precond in
let id = WpPropId.mk_pre_id kf Kglobal bhv precond_id in
let labels = NormAtLabels.labels_fct_pre in
let p = normalize id labels precond in
add_prop acc kind id p
let add_prop_fct_pre acc kind kf bhv ~assumes pre =
let id = WpPropId.mk_pre_id kf Kglobal bhv pre in
let labels = NormAtLabels.labels_fct_pre in
let p = Logic_const.pred_of_id_pred pre in
let p = Logic_const.(pat (p,pre_label)) in
let p = normalize id ?assumes labels p in
add_prop acc kind id p
let add_prop_fct_post acc kind kf bhv tkind post =
let id = WpPropId.mk_fct_post_id kf bhv (tkind, post) in
let labels = NormAtLabels.labels_fct_post in
let p = Logic_const.pred_of_id_pred post in
let p = normalize id labels p in
add_prop acc kind id p
let add_prop_fct_bhv_pre acc kind kf bhv ~impl_assumes =
let assumes =
if impl_assumes then Some (Ast_info.behavior_assumes bhv) else None
in
let add acc p = add_prop_fct_pre acc kind kf bhv ~assumes p in
let acc = List.fold_left add acc bhv.b_requires in
if impl_assumes then acc
else List.fold_left add acc bhv.b_assumes
let add_prop_stmt_pre acc kind kf s bhv ~assumes pre =
let id = WpPropId.mk_pre_id kf (Kstmt s) bhv pre in
let labels = NormAtLabels.labels_stmt_pre ~kf s in
let p = Logic_const.pred_of_id_pred pre in
let p = normalize id labels ?assumes p in
add_prop acc kind id p
let add_prop_stmt_bhv_requires acc kind kf s bhv ~with_assumes =
let assumes =
if with_assumes then Some (Ast_info.behavior_assumes bhv) else None
in let add acc pre =
add_prop_stmt_pre acc kind kf s bhv ~assumes pre
in List.fold_left add acc bhv.b_requires
* Process the stmt spec precondition as an hypothesis for external properties .
* Add [ assumes = > requires ] for all the behaviors .
* Add [assumes => requires] for all the behaviors. *)
let add_prop_stmt_spec_pre acc kind kf s spec =
let add_bhv_pre acc bhv =
add_prop_stmt_bhv_requires acc kind kf s bhv ~with_assumes:true
in List.fold_left add_bhv_pre acc spec.spec_behavior
let add_prop_stmt_post acc kind kf s bhv tkind l_post ~assumes post =
let id = WpPropId.mk_stmt_post_id kf s bhv (tkind, post) in
let labels = NormAtLabels.labels_stmt_post ~kf s l_post in
let p = Logic_const.pred_of_id_pred post in
let p = normalize id labels ?assumes p in
add_prop acc kind id p
let add_prop_call_pre acc kind id ~assumes pre =
let labels = NormAtLabels.labels_fct_pre in
let p = Logic_const.pred_of_id_pred pre in
(* assumes can be normalized in the same time *)
let p = Logic_const.pimplies (assumes, p) in
let p = normalize id labels p in
add_prop acc kind id p
let add_prop_call_post acc kind called_kf bhv tkind ~assumes post =
let id = WpPropId.mk_fct_post_id called_kf bhv (tkind, post) in
let labels = NormAtLabels.labels_fct_post in
let p = Logic_const.pred_of_id_pred post in
let p = normalize id labels ~assumes p in
add_prop acc kind id p
let add_prop_assert acc kind kf s ca p =
let id = WpPropId.mk_assert_id kf s ca in
let labels = NormAtLabels.labels_assert_before ~kf s in
let p = normalize id labels p in
add_prop acc kind id p
let add_prop_loop_inv acc kind s ~established id p =
let labels = NormAtLabels.labels_loop_inv ~established s in
let p = normalize id labels p in
add_prop acc kind id p
(** apply [f_normal] on the [Normal] postconditions,
* [f_exits] on the [Exits] postconditions, and warn on the others. *)
let fold_bhv_post_cond ~warn f_normal f_exits acc b =
let add (p_acc, e_acc) ((termination_kind, pe) as e) =
match termination_kind with
| Normal -> f_normal p_acc pe, e_acc
| Exits -> p_acc, f_exits e_acc pe
HANDLED by an ASSERT from CIL
TODO
begin
if warn then
Wp_parameters.warning
"Abrupt statement termination property ignored:@, %a"
Printer.pp_post_cond e;
p_acc, e_acc
end
in List.fold_left add acc b.b_post_cond
(* -------------------------------------------------------------------------- *)
let add_assigns acc kind id a_desc =
let take_assigns () =
debug "take %a %a" WpPropId.pp_propid id WpPropId.pp_assigns_desc a_desc;
WpPropId.mk_assigns_info id a_desc
in
let take_assigns_call fct info =
let asgn = take_assigns () in
{ info with call_asgn = ForCall.add fct asgn info.call_asgn }
in
let info = acc.info in
let goal, info = match kind with
| Ahyp -> false, {info with a_hyp = take_assigns ()}
| AcallHyp fct -> false, take_assigns_call fct info
| Agoal -> true, {info with a_goal = take_assigns ()}
| _ -> Wp_parameters.fatal "Assigns prop can only be Hyp or Goal"
in let acc = { acc with info = info } in
if goal then { acc with has_asgn_goal = true} else acc
let add_assigns_any acc kind asgn =
let take_call fct asgn info =
{ info with call_asgn = ForCall.add fct asgn info.call_asgn } in
match kind with
| Ahyp -> {acc with info = { acc.info with a_hyp = asgn}}
| AcallHyp fct -> {acc with info = take_call fct asgn acc.info}
| _ -> Wp_parameters.fatal "Assigns Any prop can only be Hyp"
let assigns_upper_bound spec =
let bhvs = spec.spec_behavior in
let upper a b =
match a, b.b_assigns with
| None, Writes a when Cil.is_default_behavior b ->
Some (b,a) (* default behavior always applies. *)
WritesAny U X - > WritesAny
| Some (b,_), _ when Cil.is_default_behavior b ->
a (* default behavior prevails over other behaviors. *)
| Some _, WritesAny ->
No default behavior and one behavior assigns everything .
| Some(b,a1), Writes a2 -> Some (b,a1 @ a2)
(* take the whole list of assigns. *)
in
match bhvs with
| [] -> None
| bhv::bhvs ->
[ VP 2011 - 02 - 04 ] Note that if there is no default and each
behavior has a proper assigns clause we put dependencies only
to the assigns of a more or less randomly selected behavior ,
but the datatypes above ca n't handle anything better .
behavior has a proper assigns clause we put dependencies only
to the assigns of a more or less randomly selected behavior,
but the datatypes above can't handle anything better. *)
let acc =
match bhv.b_assigns with
WritesAny -> None
| Writes a -> Some(bhv,a)
in
List.fold_left upper acc bhvs
[ VP 2011 - 02 - 04 ] These two functions below mix all the assigns of
a function regardless of the behavior . At least now that we take
WritesAny as soon as at least one behavior has no assigns clause ,
this is correct , but still imprecise . Needs refactoring of t_annots to
go further , though .
[ AP 2011 - 03 - 11 ] I think that the merge of all assigns properties
is intended because we are using it as an hypothesis to skip the statement
or the function call .
a function regardless of the behavior. At least now that we take
WritesAny as soon as at least one behavior has no assigns clause,
this is correct, but still imprecise. Needs refactoring of t_annots to
go further, though.
[AP 2011-03-11] I think that the merge of all assigns properties
is intended because we are using it as an hypothesis to skip the statement
or the function call.
*)
let add_stmt_spec_assigns_hyp acc kf s l_post spec =
match assigns_upper_bound spec with
| None ->
add_assigns_any acc Ahyp
(WpPropId.mk_stmt_any_assigns_info s)
| Some(bhv, assigns) ->
(* We are always using the spec covering all possible parent behaviors. *)
let id = WpPropId.mk_stmt_assigns_id kf s [] bhv assigns in
match id with
| None -> add_assigns_any acc Ahyp
(WpPropId.mk_stmt_any_assigns_info s)
| Some id ->
let labels = NormAtLabels.labels_stmt_assigns ~kf s l_post in
let assigns = NormAtLabels.preproc_assigns labels assigns in
let a_desc = WpPropId.mk_stmt_assigns_desc s assigns in
add_assigns acc Ahyp id a_desc
let add_call_assigns_any acc s =
let asgn = WpPropId.mk_stmt_any_assigns_info s in
{acc with info = { acc.info with a_call = asgn }}
let add_call_assigns_hyp acc kf_caller s ~called_kf l_post spec_opt =
match spec_opt with
| None ->
let pid = WpPropId.mk_stmt_any_assigns_info s in
add_assigns_any acc (AcallHyp called_kf) pid
| Some spec ->
match assigns_upper_bound spec with
| None ->
let asgn = WpPropId.mk_stmt_any_assigns_info s in
add_assigns_any acc (AcallHyp called_kf) asgn
| Some(bhv, assigns) ->
(* we're taking assigns from a function contract.
They're not subject to any active behavior. *)
let id = WpPropId.mk_stmt_assigns_id kf_caller s [] bhv assigns in
match id with
| None ->
let asgn = WpPropId.mk_stmt_any_assigns_info s in
add_assigns_any acc (AcallHyp called_kf) asgn
| Some pid ->
let kf = kf_caller in
let labels = NormAtLabels.labels_stmt_assigns ~kf s l_post in
let assigns = NormAtLabels.preproc_assigns labels assigns in
let a_desc = WpPropId.mk_stmt_assigns_desc s assigns in
add_assigns acc (AcallHyp called_kf) pid a_desc
[ VP 2011 - 01 - 28 ] following old behavior , not sure it is correct :
why should we give to add_assigns the assigns with unnormalized labels ?
[ AP 2011 - 03 - 11 ] to answer VP question , the source assigns are only used to
build an identifier for the property which is use later to update its status
and dependencies so we need to have the original one .
why should we give to add_assigns the assigns with unnormalized labels?
[AP 2011-03-11] to answer VP question, the source assigns are only used to
build an identifier for the property which is use later to update its status
and dependencies so we need to have the original one.
*)
let add_loop_assigns_hyp acc kf s asgn_opt = match asgn_opt with
| None ->
let asgn = WpPropId.mk_loop_any_assigns_info s in
add_assigns_any acc Ahyp asgn
| Some (ca, assigns) ->
let id = WpPropId.mk_loop_assigns_id kf s ca assigns in
match id with
| None ->
let asgn = WpPropId.mk_loop_any_assigns_info s in
add_assigns_any acc Ahyp asgn
| Some id ->
let labels = NormAtLabels.labels_loop_assigns s in
let assigns' = NormAtLabels.preproc_assigns labels assigns in
let a_desc = WpPropId.mk_loop_assigns_desc s assigns' in
add_assigns acc Ahyp id a_desc
let add_fct_bhv_assigns_hyp acc kf tkind b = match b.b_assigns with
| WritesAny ->
let id = WpPropId.mk_kf_any_assigns_info () in
add_assigns_any acc Ahyp id
| Writes assigns ->
let id = WpPropId.mk_fct_assigns_id kf b tkind assigns in
match id with
| None ->
let id = WpPropId.mk_kf_any_assigns_info () in
add_assigns_any acc Ahyp id
| Some id ->
let labels = NormAtLabels.labels_fct_assigns in
let assigns' = NormAtLabels.preproc_assigns labels assigns in
let a_desc = WpPropId.mk_kf_assigns_desc assigns' in
add_assigns acc Ahyp id a_desc
(* --- Get annotations --- *)
let get_goal_only annots = annots.info.p_goal
let get_hyp_only annots = annots.info.p_hyp
let filter_both l =
let add (h_acc, g_acc) (goal, p) =
p::h_acc, if goal then p::g_acc else g_acc
in List.fold_left add ([], []) l
let get_both_hyp_goals annots = filter_both annots.info.p_both
let get_call_hyp annots fct =
try ForCall.find fct annots.info.call_hyp
with Not_found -> []
let get_call_pre annots fct =
try filter_both (ForCall.find fct annots.info.call_pre)
with Not_found -> [],[]
let get_call_asgn annots = function
| None -> annots.info.a_call
| Some fct ->
try ForCall.find fct annots.info.call_asgn
with Not_found -> WpPropId.empty_assigns_info
let get_cut annots = annots.info.p_cut
let get_asgn_hyp annots = annots.info.a_hyp
let get_asgn_goal annots = annots.info.a_goal
(* --- Print annotations --- *)
let pp_annots fmt acc =
let acc = acc.info in
let pp_pred k b p =
Format.fprintf fmt "%s%s: %a@."
k (if b then "" else " (h)") WpPropId.pp_pred_of_pred_info p
in
let pp_pred_list k l = List.iter (fun p -> pp_pred k true p) l in
let pp_pred_b_list k l = List.iter (fun (b, p) -> pp_pred k b p) l in
begin
pp_pred_list "H" acc.p_hyp;
pp_pred_list "G" acc.p_goal;
pp_pred_b_list "H+G" acc.p_both;
pp_pred_b_list "C" acc.p_cut;
ForCall.iter
(fun kf hs ->
let name = "CallHyp:" ^ (Kernel_function.get_name kf) in
pp_pred_list name hs)
acc.call_hyp;
ForCall.iter
(fun kf bhs ->
let name = "CallPre:" ^ (Kernel_function.get_name kf) in
pp_pred_b_list name bhs)
acc.call_pre;
ForCall.iter
(fun kf asgn ->
let name = "CallAsgn:" ^ (Kernel_function.get_name kf) in
WpPropId.pp_assign_info name fmt asgn)
acc.call_asgn;
WpPropId.pp_assign_info "DC" fmt acc.a_call;
WpPropId.pp_assign_info "HA" fmt acc.a_hyp;
WpPropId.pp_assign_info "GA" fmt acc.a_goal;
end
let merge_calls f call1 call2 =
ForCall.merge
(fun _fct a b -> match a,b with
| None,c | c,None -> c
| Some a,Some b -> Some (f a b)
) call1 call2
(* TODO: it should be possible to do without this, but needs a big refactoring*)
let merge_acc acc1 acc2 =
{
p_hyp = acc1.p_hyp @ acc2.p_hyp;
p_goal = acc1.p_goal @ acc2.p_goal;
p_both = acc1.p_both @ acc2.p_both;
p_cut = acc1.p_cut @ acc2.p_cut;
call_hyp = merge_calls (@) acc1.call_hyp acc2.call_hyp;
call_pre = merge_calls (@) acc1.call_pre acc2.call_pre;
call_asgn = merge_calls WpPropId.merge_assign_info acc1.call_asgn acc2.call_asgn;
a_goal = WpPropId.merge_assign_info acc1.a_goal acc2.a_goal;
a_hyp = WpPropId.merge_assign_info acc1.a_hyp acc2.a_hyp;
a_call = WpPropId.merge_assign_info acc1.a_call acc2.a_call;
}
(* -------------------------------------------------------------------------- *)
(* --- Annotation table --- *)
(* -------------------------------------------------------------------------- *)
* This is an where some predicates are stored on CFG edges .
* On each edge , we store hypotheses and goals .
* On each edge, we store hypotheses and goals.
*)
module Hannots = Cil2cfg.HE (struct type t = annots end)
type annots_tbl = {
tbl_annots : Hannots.t;
mutable tbl_axioms : WpPropId.axiom_info list;
mutable tbl_has_prop_goal : bool;
mutable tbl_has_asgn_goal : bool;
}
let create_tbl () = {
tbl_annots = Hannots.create 7;
tbl_axioms = [];
tbl_has_prop_goal = false;
tbl_has_asgn_goal = false;
}
let add_on_edges tbl new_acc edges =
if new_acc.has_prop_goal then tbl.tbl_has_prop_goal <- true;
if new_acc.has_asgn_goal then tbl.tbl_has_asgn_goal <- true;
let add_on_edge e =
let acc =
try
let acc = Hannots.find tbl.tbl_annots e in
merge_acc new_acc.info acc
with Not_found -> new_acc.info
in Hannots.replace tbl.tbl_annots e acc;
in List.iter add_on_edge edges
let add_node_annots tbl cfg v (before, (post, exits)) =
debug "[add_node_annots] on %a@." Cil2cfg.pp_node v;
add_on_edges tbl before (Cil2cfg.get_pre_edges cfg v);
if post <> empty_acc then
begin
let edges_after = Cil2cfg.get_post_edges cfg v in
if edges_after = []
then (* unreachable (see [process_unreached_annots]) *) ()
else add_on_edges tbl post edges_after
end;
if exits <> empty_acc then
begin
let edges_exits = Cil2cfg.get_exit_edges cfg v in
if edges_exits = []
then (* unreachable (see [process_unreached_annots]) *) ()
else add_on_edges tbl exits edges_exits
end
let add_loop_annots tbl cfg vloop ~entry ~back ~core =
debug "[add_loop_annots] on %a@."Cil2cfg.pp_node vloop;
let edges_to_head = Cil2cfg.succ_e cfg vloop in
debug "[add_loop_annots] %d edges_to_head" (List.length edges_to_head);
let edges_to_loop = Cil2cfg.pred_e cfg vloop in
debug "[add_loop_annots] %d edges_to_loop" (List.length edges_to_loop);
let back_edges, entry_edges =
List.partition Cil2cfg.is_back_edge edges_to_loop
in
debug "[add_loop_annots] %d back_edges + %d entry_edges"
(List.length back_edges) (List.length entry_edges);
add_on_edges tbl entry entry_edges;
debug "[add_loop_annots on entry_edges ok]@.";
add_on_edges tbl back back_edges;
debug "[add_loop_annots on back_edges ok]@.";
add_on_edges tbl core edges_to_head;
debug "[add_loop_annots on edges_to_head ok]@."
let add_axiom tbl lemma =
try
(* Labels does not need normalization *)
let axiom = WpPropId.mk_axiom_info lemma in
debug "take %a@." WpPropId.pp_axiom_info axiom;
tbl.tbl_axioms <- axiom::tbl.tbl_axioms
with e ->
NormAtLabels.catch_label_error e ("axiom "^lemma.lem_name) "axiom"
let add_all_axioms tbl =
let rec do_g g =
match g with
| Daxiomatic (_ax_name, globs,_,_) -> do_globs globs
| Dlemma (name,_,_,_,_,_,_) ->
let lem = LogicUsage.logic_lemma name in
add_axiom tbl lem
| _ -> ()
and do_globs globs = List.iter do_g globs in
Annotations.iter_global (fun _ -> do_g)
let get_annots tbl e =
TODO clean : this is not very nice !
let info = Hannots.find tbl.tbl_annots e in { empty_acc with info = info}
with Not_found -> empty_acc
(* -------------------------------------------------------------------------- *)
(* --- Strategy --- *)
(* -------------------------------------------------------------------------- *)
type strategy_for_froms = {
get_pre : unit -> t_annots;
more_vars : logic_var list
}
type strategy_kind =
| SKannots (* normal mode for annotations *)
| SKfroms of strategy_for_froms
(* an object of this type is the only access to annotations
* from the rest of the application.
* The idea is to be able to tune which properties to use for a computation. *)
type strategy = {
desc : string ;
cfg : Cil2cfg.t;
behavior_name : string option ;
strategy_kind : strategy_kind;
annots : annots_tbl;
}
let get_kf s = Cil2cfg.cfg_kf s.cfg
let get_bhv s = s.behavior_name
let is_default_behavior s =
match s.behavior_name with None -> true | Some _ -> false
let mk_strategy desc cfg bhv_name kind tbl = {
desc = desc; cfg = cfg; behavior_name = bhv_name;
strategy_kind = kind; annots = tbl;
}
let cfg_of_strategy strat = strat.cfg
let behavior_name_of_strategy strat = strat.behavior_name
let global_axioms strat = strat.annots.tbl_axioms
let strategy_kind strat = strat.strategy_kind
let strategy_has_prop_goal strat = strat.annots.tbl_has_prop_goal
let strategy_has_asgn_goal strat = strat.annots.tbl_has_asgn_goal
let get_annots strat = get_annots strat.annots
let pp_info_of_strategy fmt strat =
Format.fprintf fmt "@[%s@]" strat.desc
(* -------------------------------------------------------------------------- *)
(* --- Helpers --- *)
(* -------------------------------------------------------------------------- *)
let is_main_init kf =
if Kernel.LibEntry.get () then false
else
let is_main =
try
let main, _ = Globals.entry_point () in
Kernel_function.equal kf main
with Globals.No_such_entry_point _ -> false
in
debug "'%a' is %sthe main entry point@."
Kernel_function.pretty kf (if is_main then "" else "NOT ");
is_main
let isInitConst () = Wp_parameters.Init.get ()
let isGlobalInitConst var =
var.vglob && var.vstorage <> Extern && Cil.typeHasQualifier "const" var.vtype
let mk_variant_properties kf s ca v =
let vpos_id = WpPropId.mk_var_pos_id kf s ca in
let vdecr_id = WpPropId.mk_var_decr_id kf s ca in
let loc = v.term_loc in
let lcurr = Clabels.to_logic (Clabels.loop_current s) in
let vcurr = Logic_const.tat ~loc (v, lcurr) in
let zero = Cil.lzero ~loc () in
let vpos = Logic_const.prel ~loc (Rle, zero, vcurr) in
let vdecr = Logic_const.prel ~loc (Rlt, v, vcurr) in
(vpos_id, vpos), (vdecr_id, vdecr)
(* -------------------------------------------------------------------------- *)
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/wp/wpStrategy.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
debugging key
--------------------------------------------------------------------------
* An annotation can be used for different purpose.
annotation can be used as both hypothesis and goal :
- with true : considered as both : A /\ A=>..
- with false : we just want to use it as hyp right now.
annotation is use as a cut :
- with true (A is also a goal) -> A (+ proof obligation A => ...)
- with false (A is an hyp only) -> True (+ proof obligation A => ...)
annotation is a called function property to consider as an Hyp.
* The pre are not here but in AcallPre since they can also
* be considered as goals.
annotation is a called function precondition :
to be considered as hyp, and goal if bool=true
--------------------------------------------------------------------------
--------------------------------------------------------------------------
post and pre
goal only
dynamic calls
--- Add annotations ---
--------------------------------------------------------------------------
adding some specific properties.
assumes can be normalized in the same time
* apply [f_normal] on the [Normal] postconditions,
* [f_exits] on the [Exits] postconditions, and warn on the others.
--------------------------------------------------------------------------
default behavior always applies.
default behavior prevails over other behaviors.
take the whole list of assigns.
We are always using the spec covering all possible parent behaviors.
we're taking assigns from a function contract.
They're not subject to any active behavior.
--- Get annotations ---
--- Print annotations ---
TODO: it should be possible to do without this, but needs a big refactoring
--------------------------------------------------------------------------
--- Annotation table ---
--------------------------------------------------------------------------
unreachable (see [process_unreached_annots])
unreachable (see [process_unreached_annots])
Labels does not need normalization
--------------------------------------------------------------------------
--- Strategy ---
--------------------------------------------------------------------------
normal mode for annotations
an object of this type is the only access to annotations
* from the rest of the application.
* The idea is to be able to tune which properties to use for a computation.
--------------------------------------------------------------------------
--- Helpers ---
--------------------------------------------------------------------------
-------------------------------------------------------------------------- | This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2019
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
let debug fmt = Wp_parameters.debug ~dkey fmt
open Cil_types
open LogicUsage
type annot_kind =
annotation is an hypothesis ,
but not a goal ( see ) : A = > ...
but not a goal (see Aboth) : A => ...*)
annotation is a goal ,
but not an hypothesis ( see ): A /\ ...
but not an hypothesis (see Aboth): A /\ ...*)
| Aboth of bool
| AcutB of bool
| AcallHyp of kernel_function
| AcallPre of bool * kernel_function
--- Annotations for one program point . ---
module ForCall = Kernel_function.Map
* Some elements can be used as both and Goal : because of the selection
* mechanism , we need to add a boolean [ as_goal ] to tell if the element is to be
* considered as a goal . If [ false ] , the element can still be used as hypothesis .
* mechanism, we need to add a boolean [as_goal] to tell if the element is to be
* considered as a goal. If [false], the element can still be used as hypothesis.
*)
type annots = {
p_hyp : WpPropId.pred_info list;
p_goal : WpPropId.pred_info list;
p_both : (bool * WpPropId.pred_info) list;
p_cut : (bool * WpPropId.pred_info) list;
call_asgn : WpPropId.assigns_full_info ForCall.t;
a_goal : WpPropId.assigns_full_info;
a_hyp : WpPropId.assigns_full_info;
}
type t_annots = { has_asgn_goal : bool; has_prop_goal : bool; info: annots }
let empty_acc =
let a = {
p_hyp = []; p_goal = []; p_both = []; p_cut = [];
call_hyp = ForCall.empty;
call_pre = ForCall.empty;
call_asgn = ForCall.empty;
a_goal = WpPropId.empty_assigns_info;
a_hyp = WpPropId.empty_assigns_info;
a_call = WpPropId.empty_assigns_info;
} in
{ has_asgn_goal = false; has_prop_goal = false; info = a; }
let normalize id ?assumes labels p =
try
let p = NormAtLabels.preproc_annot labels p in
match assumes with
| None -> Some p
| Some a ->
let a = Logic_const.pat(a,Logic_const.pre_label) in
let a = NormAtLabels.(preproc_annot labels_fct_pre a) in
Some(Logic_const.pimplies(a,p))
with e ->
let pid = WpPropId.get_propid id in
NormAtLabels.catch_label_error e pid "annotation" ;
None
let add_prop acc kind id p =
let get_p = match p with None -> None
| Some p -> Some(WpPropId.mk_pred_info id p) in
let add_hyp l = match get_p with None -> l | Some p -> p::l in
let add_goal l = match get_p with None -> l | Some p -> p::l in
let add_both goal l =
match get_p with
| None -> l
| Some p -> (goal, p)::l
in
let add_hyp_call fct calls =
let l = try ForCall.find fct calls with Not_found -> [] in
ForCall.add fct (add_hyp l) calls in
let add_both_call fct goal calls =
let l = try ForCall.find fct calls with Not_found -> [] in
ForCall.add fct (add_both goal l) calls in
let info = acc.info in
let goal, info = match kind with
| Ahyp ->
false, { info with p_hyp = add_hyp info.p_hyp }
| Agoal ->
true, { info with p_goal = add_goal info.p_goal }
| Aboth goal ->
goal, { info with p_both = add_both goal info.p_both }
| AcutB goal ->
goal, { info with p_cut = add_both goal info.p_cut }
| AcallHyp fct ->
false, { info with call_hyp = add_hyp_call fct info.call_hyp }
| AcallPre (goal,fct) ->
goal, { info with call_pre = add_both_call fct goal info.call_pre }
in let acc = { acc with info = info } in
if goal then { acc with has_prop_goal = true} else acc
let add_prop_fct_pre_bhv acc kind kf bhv =
let norm_pred pred =
let p = Logic_const.pred_of_id_pred pred in
Logic_const.(pat (p,pre_label))
in
let requires = Logic_const.pands (List.map norm_pred bhv.b_requires) in
let assumes = Logic_const.pands (List.map norm_pred bhv.b_assumes) in
let precond = Logic_const.pimplies (assumes, requires) in
let precond_id = Logic_const.new_predicate precond in
let id = WpPropId.mk_pre_id kf Kglobal bhv precond_id in
let labels = NormAtLabels.labels_fct_pre in
let p = normalize id labels precond in
add_prop acc kind id p
let add_prop_fct_pre acc kind kf bhv ~assumes pre =
let id = WpPropId.mk_pre_id kf Kglobal bhv pre in
let labels = NormAtLabels.labels_fct_pre in
let p = Logic_const.pred_of_id_pred pre in
let p = Logic_const.(pat (p,pre_label)) in
let p = normalize id ?assumes labels p in
add_prop acc kind id p
let add_prop_fct_post acc kind kf bhv tkind post =
let id = WpPropId.mk_fct_post_id kf bhv (tkind, post) in
let labels = NormAtLabels.labels_fct_post in
let p = Logic_const.pred_of_id_pred post in
let p = normalize id labels p in
add_prop acc kind id p
let add_prop_fct_bhv_pre acc kind kf bhv ~impl_assumes =
let assumes =
if impl_assumes then Some (Ast_info.behavior_assumes bhv) else None
in
let add acc p = add_prop_fct_pre acc kind kf bhv ~assumes p in
let acc = List.fold_left add acc bhv.b_requires in
if impl_assumes then acc
else List.fold_left add acc bhv.b_assumes
let add_prop_stmt_pre acc kind kf s bhv ~assumes pre =
let id = WpPropId.mk_pre_id kf (Kstmt s) bhv pre in
let labels = NormAtLabels.labels_stmt_pre ~kf s in
let p = Logic_const.pred_of_id_pred pre in
let p = normalize id labels ?assumes p in
add_prop acc kind id p
let add_prop_stmt_bhv_requires acc kind kf s bhv ~with_assumes =
let assumes =
if with_assumes then Some (Ast_info.behavior_assumes bhv) else None
in let add acc pre =
add_prop_stmt_pre acc kind kf s bhv ~assumes pre
in List.fold_left add acc bhv.b_requires
* Process the stmt spec precondition as an hypothesis for external properties .
* Add [ assumes = > requires ] for all the behaviors .
* Add [assumes => requires] for all the behaviors. *)
let add_prop_stmt_spec_pre acc kind kf s spec =
let add_bhv_pre acc bhv =
add_prop_stmt_bhv_requires acc kind kf s bhv ~with_assumes:true
in List.fold_left add_bhv_pre acc spec.spec_behavior
let add_prop_stmt_post acc kind kf s bhv tkind l_post ~assumes post =
let id = WpPropId.mk_stmt_post_id kf s bhv (tkind, post) in
let labels = NormAtLabels.labels_stmt_post ~kf s l_post in
let p = Logic_const.pred_of_id_pred post in
let p = normalize id labels ?assumes p in
add_prop acc kind id p
let add_prop_call_pre acc kind id ~assumes pre =
let labels = NormAtLabels.labels_fct_pre in
let p = Logic_const.pred_of_id_pred pre in
let p = Logic_const.pimplies (assumes, p) in
let p = normalize id labels p in
add_prop acc kind id p
let add_prop_call_post acc kind called_kf bhv tkind ~assumes post =
let id = WpPropId.mk_fct_post_id called_kf bhv (tkind, post) in
let labels = NormAtLabels.labels_fct_post in
let p = Logic_const.pred_of_id_pred post in
let p = normalize id labels ~assumes p in
add_prop acc kind id p
let add_prop_assert acc kind kf s ca p =
let id = WpPropId.mk_assert_id kf s ca in
let labels = NormAtLabels.labels_assert_before ~kf s in
let p = normalize id labels p in
add_prop acc kind id p
let add_prop_loop_inv acc kind s ~established id p =
let labels = NormAtLabels.labels_loop_inv ~established s in
let p = normalize id labels p in
add_prop acc kind id p
let fold_bhv_post_cond ~warn f_normal f_exits acc b =
let add (p_acc, e_acc) ((termination_kind, pe) as e) =
match termination_kind with
| Normal -> f_normal p_acc pe, e_acc
| Exits -> p_acc, f_exits e_acc pe
HANDLED by an ASSERT from CIL
TODO
begin
if warn then
Wp_parameters.warning
"Abrupt statement termination property ignored:@, %a"
Printer.pp_post_cond e;
p_acc, e_acc
end
in List.fold_left add acc b.b_post_cond
let add_assigns acc kind id a_desc =
let take_assigns () =
debug "take %a %a" WpPropId.pp_propid id WpPropId.pp_assigns_desc a_desc;
WpPropId.mk_assigns_info id a_desc
in
let take_assigns_call fct info =
let asgn = take_assigns () in
{ info with call_asgn = ForCall.add fct asgn info.call_asgn }
in
let info = acc.info in
let goal, info = match kind with
| Ahyp -> false, {info with a_hyp = take_assigns ()}
| AcallHyp fct -> false, take_assigns_call fct info
| Agoal -> true, {info with a_goal = take_assigns ()}
| _ -> Wp_parameters.fatal "Assigns prop can only be Hyp or Goal"
in let acc = { acc with info = info } in
if goal then { acc with has_asgn_goal = true} else acc
let add_assigns_any acc kind asgn =
let take_call fct asgn info =
{ info with call_asgn = ForCall.add fct asgn info.call_asgn } in
match kind with
| Ahyp -> {acc with info = { acc.info with a_hyp = asgn}}
| AcallHyp fct -> {acc with info = take_call fct asgn acc.info}
| _ -> Wp_parameters.fatal "Assigns Any prop can only be Hyp"
let assigns_upper_bound spec =
let bhvs = spec.spec_behavior in
let upper a b =
match a, b.b_assigns with
| None, Writes a when Cil.is_default_behavior b ->
WritesAny U X - > WritesAny
| Some (b,_), _ when Cil.is_default_behavior b ->
| Some _, WritesAny ->
No default behavior and one behavior assigns everything .
| Some(b,a1), Writes a2 -> Some (b,a1 @ a2)
in
match bhvs with
| [] -> None
| bhv::bhvs ->
[ VP 2011 - 02 - 04 ] Note that if there is no default and each
behavior has a proper assigns clause we put dependencies only
to the assigns of a more or less randomly selected behavior ,
but the datatypes above ca n't handle anything better .
behavior has a proper assigns clause we put dependencies only
to the assigns of a more or less randomly selected behavior,
but the datatypes above can't handle anything better. *)
let acc =
match bhv.b_assigns with
WritesAny -> None
| Writes a -> Some(bhv,a)
in
List.fold_left upper acc bhvs
[ VP 2011 - 02 - 04 ] These two functions below mix all the assigns of
a function regardless of the behavior . At least now that we take
WritesAny as soon as at least one behavior has no assigns clause ,
this is correct , but still imprecise . Needs refactoring of t_annots to
go further , though .
[ AP 2011 - 03 - 11 ] I think that the merge of all assigns properties
is intended because we are using it as an hypothesis to skip the statement
or the function call .
a function regardless of the behavior. At least now that we take
WritesAny as soon as at least one behavior has no assigns clause,
this is correct, but still imprecise. Needs refactoring of t_annots to
go further, though.
[AP 2011-03-11] I think that the merge of all assigns properties
is intended because we are using it as an hypothesis to skip the statement
or the function call.
*)
let add_stmt_spec_assigns_hyp acc kf s l_post spec =
match assigns_upper_bound spec with
| None ->
add_assigns_any acc Ahyp
(WpPropId.mk_stmt_any_assigns_info s)
| Some(bhv, assigns) ->
let id = WpPropId.mk_stmt_assigns_id kf s [] bhv assigns in
match id with
| None -> add_assigns_any acc Ahyp
(WpPropId.mk_stmt_any_assigns_info s)
| Some id ->
let labels = NormAtLabels.labels_stmt_assigns ~kf s l_post in
let assigns = NormAtLabels.preproc_assigns labels assigns in
let a_desc = WpPropId.mk_stmt_assigns_desc s assigns in
add_assigns acc Ahyp id a_desc
let add_call_assigns_any acc s =
let asgn = WpPropId.mk_stmt_any_assigns_info s in
{acc with info = { acc.info with a_call = asgn }}
let add_call_assigns_hyp acc kf_caller s ~called_kf l_post spec_opt =
match spec_opt with
| None ->
let pid = WpPropId.mk_stmt_any_assigns_info s in
add_assigns_any acc (AcallHyp called_kf) pid
| Some spec ->
match assigns_upper_bound spec with
| None ->
let asgn = WpPropId.mk_stmt_any_assigns_info s in
add_assigns_any acc (AcallHyp called_kf) asgn
| Some(bhv, assigns) ->
let id = WpPropId.mk_stmt_assigns_id kf_caller s [] bhv assigns in
match id with
| None ->
let asgn = WpPropId.mk_stmt_any_assigns_info s in
add_assigns_any acc (AcallHyp called_kf) asgn
| Some pid ->
let kf = kf_caller in
let labels = NormAtLabels.labels_stmt_assigns ~kf s l_post in
let assigns = NormAtLabels.preproc_assigns labels assigns in
let a_desc = WpPropId.mk_stmt_assigns_desc s assigns in
add_assigns acc (AcallHyp called_kf) pid a_desc
[ VP 2011 - 01 - 28 ] following old behavior , not sure it is correct :
why should we give to add_assigns the assigns with unnormalized labels ?
[ AP 2011 - 03 - 11 ] to answer VP question , the source assigns are only used to
build an identifier for the property which is use later to update its status
and dependencies so we need to have the original one .
why should we give to add_assigns the assigns with unnormalized labels?
[AP 2011-03-11] to answer VP question, the source assigns are only used to
build an identifier for the property which is use later to update its status
and dependencies so we need to have the original one.
*)
let add_loop_assigns_hyp acc kf s asgn_opt = match asgn_opt with
| None ->
let asgn = WpPropId.mk_loop_any_assigns_info s in
add_assigns_any acc Ahyp asgn
| Some (ca, assigns) ->
let id = WpPropId.mk_loop_assigns_id kf s ca assigns in
match id with
| None ->
let asgn = WpPropId.mk_loop_any_assigns_info s in
add_assigns_any acc Ahyp asgn
| Some id ->
let labels = NormAtLabels.labels_loop_assigns s in
let assigns' = NormAtLabels.preproc_assigns labels assigns in
let a_desc = WpPropId.mk_loop_assigns_desc s assigns' in
add_assigns acc Ahyp id a_desc
let add_fct_bhv_assigns_hyp acc kf tkind b = match b.b_assigns with
| WritesAny ->
let id = WpPropId.mk_kf_any_assigns_info () in
add_assigns_any acc Ahyp id
| Writes assigns ->
let id = WpPropId.mk_fct_assigns_id kf b tkind assigns in
match id with
| None ->
let id = WpPropId.mk_kf_any_assigns_info () in
add_assigns_any acc Ahyp id
| Some id ->
let labels = NormAtLabels.labels_fct_assigns in
let assigns' = NormAtLabels.preproc_assigns labels assigns in
let a_desc = WpPropId.mk_kf_assigns_desc assigns' in
add_assigns acc Ahyp id a_desc
let get_goal_only annots = annots.info.p_goal
let get_hyp_only annots = annots.info.p_hyp
let filter_both l =
let add (h_acc, g_acc) (goal, p) =
p::h_acc, if goal then p::g_acc else g_acc
in List.fold_left add ([], []) l
let get_both_hyp_goals annots = filter_both annots.info.p_both
let get_call_hyp annots fct =
try ForCall.find fct annots.info.call_hyp
with Not_found -> []
let get_call_pre annots fct =
try filter_both (ForCall.find fct annots.info.call_pre)
with Not_found -> [],[]
let get_call_asgn annots = function
| None -> annots.info.a_call
| Some fct ->
try ForCall.find fct annots.info.call_asgn
with Not_found -> WpPropId.empty_assigns_info
let get_cut annots = annots.info.p_cut
let get_asgn_hyp annots = annots.info.a_hyp
let get_asgn_goal annots = annots.info.a_goal
let pp_annots fmt acc =
let acc = acc.info in
let pp_pred k b p =
Format.fprintf fmt "%s%s: %a@."
k (if b then "" else " (h)") WpPropId.pp_pred_of_pred_info p
in
let pp_pred_list k l = List.iter (fun p -> pp_pred k true p) l in
let pp_pred_b_list k l = List.iter (fun (b, p) -> pp_pred k b p) l in
begin
pp_pred_list "H" acc.p_hyp;
pp_pred_list "G" acc.p_goal;
pp_pred_b_list "H+G" acc.p_both;
pp_pred_b_list "C" acc.p_cut;
ForCall.iter
(fun kf hs ->
let name = "CallHyp:" ^ (Kernel_function.get_name kf) in
pp_pred_list name hs)
acc.call_hyp;
ForCall.iter
(fun kf bhs ->
let name = "CallPre:" ^ (Kernel_function.get_name kf) in
pp_pred_b_list name bhs)
acc.call_pre;
ForCall.iter
(fun kf asgn ->
let name = "CallAsgn:" ^ (Kernel_function.get_name kf) in
WpPropId.pp_assign_info name fmt asgn)
acc.call_asgn;
WpPropId.pp_assign_info "DC" fmt acc.a_call;
WpPropId.pp_assign_info "HA" fmt acc.a_hyp;
WpPropId.pp_assign_info "GA" fmt acc.a_goal;
end
let merge_calls f call1 call2 =
ForCall.merge
(fun _fct a b -> match a,b with
| None,c | c,None -> c
| Some a,Some b -> Some (f a b)
) call1 call2
let merge_acc acc1 acc2 =
{
p_hyp = acc1.p_hyp @ acc2.p_hyp;
p_goal = acc1.p_goal @ acc2.p_goal;
p_both = acc1.p_both @ acc2.p_both;
p_cut = acc1.p_cut @ acc2.p_cut;
call_hyp = merge_calls (@) acc1.call_hyp acc2.call_hyp;
call_pre = merge_calls (@) acc1.call_pre acc2.call_pre;
call_asgn = merge_calls WpPropId.merge_assign_info acc1.call_asgn acc2.call_asgn;
a_goal = WpPropId.merge_assign_info acc1.a_goal acc2.a_goal;
a_hyp = WpPropId.merge_assign_info acc1.a_hyp acc2.a_hyp;
a_call = WpPropId.merge_assign_info acc1.a_call acc2.a_call;
}
* This is an where some predicates are stored on CFG edges .
* On each edge , we store hypotheses and goals .
* On each edge, we store hypotheses and goals.
*)
module Hannots = Cil2cfg.HE (struct type t = annots end)
type annots_tbl = {
tbl_annots : Hannots.t;
mutable tbl_axioms : WpPropId.axiom_info list;
mutable tbl_has_prop_goal : bool;
mutable tbl_has_asgn_goal : bool;
}
let create_tbl () = {
tbl_annots = Hannots.create 7;
tbl_axioms = [];
tbl_has_prop_goal = false;
tbl_has_asgn_goal = false;
}
let add_on_edges tbl new_acc edges =
if new_acc.has_prop_goal then tbl.tbl_has_prop_goal <- true;
if new_acc.has_asgn_goal then tbl.tbl_has_asgn_goal <- true;
let add_on_edge e =
let acc =
try
let acc = Hannots.find tbl.tbl_annots e in
merge_acc new_acc.info acc
with Not_found -> new_acc.info
in Hannots.replace tbl.tbl_annots e acc;
in List.iter add_on_edge edges
let add_node_annots tbl cfg v (before, (post, exits)) =
debug "[add_node_annots] on %a@." Cil2cfg.pp_node v;
add_on_edges tbl before (Cil2cfg.get_pre_edges cfg v);
if post <> empty_acc then
begin
let edges_after = Cil2cfg.get_post_edges cfg v in
if edges_after = []
else add_on_edges tbl post edges_after
end;
if exits <> empty_acc then
begin
let edges_exits = Cil2cfg.get_exit_edges cfg v in
if edges_exits = []
else add_on_edges tbl exits edges_exits
end
let add_loop_annots tbl cfg vloop ~entry ~back ~core =
debug "[add_loop_annots] on %a@."Cil2cfg.pp_node vloop;
let edges_to_head = Cil2cfg.succ_e cfg vloop in
debug "[add_loop_annots] %d edges_to_head" (List.length edges_to_head);
let edges_to_loop = Cil2cfg.pred_e cfg vloop in
debug "[add_loop_annots] %d edges_to_loop" (List.length edges_to_loop);
let back_edges, entry_edges =
List.partition Cil2cfg.is_back_edge edges_to_loop
in
debug "[add_loop_annots] %d back_edges + %d entry_edges"
(List.length back_edges) (List.length entry_edges);
add_on_edges tbl entry entry_edges;
debug "[add_loop_annots on entry_edges ok]@.";
add_on_edges tbl back back_edges;
debug "[add_loop_annots on back_edges ok]@.";
add_on_edges tbl core edges_to_head;
debug "[add_loop_annots on edges_to_head ok]@."
let add_axiom tbl lemma =
try
let axiom = WpPropId.mk_axiom_info lemma in
debug "take %a@." WpPropId.pp_axiom_info axiom;
tbl.tbl_axioms <- axiom::tbl.tbl_axioms
with e ->
NormAtLabels.catch_label_error e ("axiom "^lemma.lem_name) "axiom"
let add_all_axioms tbl =
let rec do_g g =
match g with
| Daxiomatic (_ax_name, globs,_,_) -> do_globs globs
| Dlemma (name,_,_,_,_,_,_) ->
let lem = LogicUsage.logic_lemma name in
add_axiom tbl lem
| _ -> ()
and do_globs globs = List.iter do_g globs in
Annotations.iter_global (fun _ -> do_g)
let get_annots tbl e =
TODO clean : this is not very nice !
let info = Hannots.find tbl.tbl_annots e in { empty_acc with info = info}
with Not_found -> empty_acc
type strategy_for_froms = {
get_pre : unit -> t_annots;
more_vars : logic_var list
}
type strategy_kind =
| SKfroms of strategy_for_froms
type strategy = {
desc : string ;
cfg : Cil2cfg.t;
behavior_name : string option ;
strategy_kind : strategy_kind;
annots : annots_tbl;
}
let get_kf s = Cil2cfg.cfg_kf s.cfg
let get_bhv s = s.behavior_name
let is_default_behavior s =
match s.behavior_name with None -> true | Some _ -> false
let mk_strategy desc cfg bhv_name kind tbl = {
desc = desc; cfg = cfg; behavior_name = bhv_name;
strategy_kind = kind; annots = tbl;
}
let cfg_of_strategy strat = strat.cfg
let behavior_name_of_strategy strat = strat.behavior_name
let global_axioms strat = strat.annots.tbl_axioms
let strategy_kind strat = strat.strategy_kind
let strategy_has_prop_goal strat = strat.annots.tbl_has_prop_goal
let strategy_has_asgn_goal strat = strat.annots.tbl_has_asgn_goal
let get_annots strat = get_annots strat.annots
let pp_info_of_strategy fmt strat =
Format.fprintf fmt "@[%s@]" strat.desc
let is_main_init kf =
if Kernel.LibEntry.get () then false
else
let is_main =
try
let main, _ = Globals.entry_point () in
Kernel_function.equal kf main
with Globals.No_such_entry_point _ -> false
in
debug "'%a' is %sthe main entry point@."
Kernel_function.pretty kf (if is_main then "" else "NOT ");
is_main
let isInitConst () = Wp_parameters.Init.get ()
let isGlobalInitConst var =
var.vglob && var.vstorage <> Extern && Cil.typeHasQualifier "const" var.vtype
let mk_variant_properties kf s ca v =
let vpos_id = WpPropId.mk_var_pos_id kf s ca in
let vdecr_id = WpPropId.mk_var_decr_id kf s ca in
let loc = v.term_loc in
let lcurr = Clabels.to_logic (Clabels.loop_current s) in
let vcurr = Logic_const.tat ~loc (v, lcurr) in
let zero = Cil.lzero ~loc () in
let vpos = Logic_const.prel ~loc (Rle, zero, vcurr) in
let vdecr = Logic_const.prel ~loc (Rlt, v, vcurr) in
(vpos_id, vpos), (vdecr_id, vdecr)
|
e6de1d1d59c6b5d645d0f9a459d38656f05389d6604127d6e39885d11049b37f | irfn/clojure-ocr | string_ops.clj | (ns test.string-ops
(:use clojure.test)
(:use string-ops))
(deftest test-lines
(are [description split-lines some-text] (= split-lines (lines some-text))
"splitting lines" [" _ _ _ _ _ _ _",
"| _| _||_||_ |_ ||_||_|",
"||_ _| | _||_| ||_| _|"] " _ _ _ _ _ _ _\n| _| _||_||_ |_ ||_||_|\n||_ _| | _||_| ||_| _|"))
(deftest test-tip
(is (= "t" (tip "tip"))))
(deftest test-tail
(is (= "ail" (tail "tail"))))
| null | https://raw.githubusercontent.com/irfn/clojure-ocr/c89da89031379a9c0367c68884caf4fcb40bb2da/test/test/string_ops.clj | clojure | (ns test.string-ops
(:use clojure.test)
(:use string-ops))
(deftest test-lines
(are [description split-lines some-text] (= split-lines (lines some-text))
"splitting lines" [" _ _ _ _ _ _ _",
"| _| _||_||_ |_ ||_||_|",
"||_ _| | _||_| ||_| _|"] " _ _ _ _ _ _ _\n| _| _||_||_ |_ ||_||_|\n||_ _| | _||_| ||_| _|"))
(deftest test-tip
(is (= "t" (tip "tip"))))
(deftest test-tail
(is (= "ail" (tail "tail"))))
|
|
d40d917b53457df77c70a8fc573bf8fc3b60c884ba2b10558c2087cc9ccf9e25 | edalorzo/learning-clojure | chapter04.clj | (ns learn.chapter04
(:require [clojure.algo.generic.math-functions :as math :refer :all]))
(defn ad-hoc-type-name [thing]
(condp = (type thing)
java.lang.String "String"
clojure.lang.PersistentVector "Vector"))
(def type-name-implementations
{java.lang.String (fn [thing] "String")
clojure.lang.PersistentVector (fn [thing] "Vector")})
(defn open-ad-hoc-type-name [thing]
(let [dispatch-value (type thing)]
(if-let [implementation (get type-name-implementations dispatch-value)]
(implementation thing)
(throw (IllegalArgumentException. (str "No implementation found for " dispatch-value))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; POLYMORPHISM AND MULTIMETHODS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def example-user {:login "rob" :referrer "mint.com" :salary 100000})
(defn fee-amount
"Calculates the fee you pay to affiliates based on their annual salary"
[percentage user]
(with-precision 16 :rounding HALF_EVEN
(* 0.01M percentage (:salary user))))
(comment
(defn affiliate-fee
"Calculates the fee for an affiliate user based on their referrer and annual salary"
[user]
;;this is an example of close dispatch
;;where the referrer is the dispatch criteria
;;the problem is that adding referrers requires code changes
(case (:referrer user)
"google.com" (fee-amount 0.01M user)
"mint.com" (fee-amount 0.03M user)
(fee-amount 0.02M user))))
;;MULTIMETHODS TO THE RESCUE!
(comment
multimethod defines dispatch criteria
(defmulti affiliate-fee
(fn [user] (:referrer user))) ;;this is equivalent to just using :referrer
;; implementation of the multimethod
(defmethod affiliate-fee "mint.com"
[user] (fee-amount 0.03M user))
(defmethod affiliate-fee "google.com"
[user] (fee-amount 0.01M user))
(defmethod affiliate-fee :default
[user] (fee-amount 0.02M user)))
;;the default method can also be defined in the dispatch
(defmulti affiliate-fee :referrer :default "*")
(defmethod affiliate-fee "mint.com"
[user] (fee-amount 0.03M user))
(defmethod affiliate-fee "google.com"
[user] (fee-amount 0.01M user))
(defmethod affiliate-fee "*"
[user] (fee-amount 0.02M user))
;;MULTIPLE DISPATCH
(def user-1 {:login "rob" :referrer "mint.com" :salary 100000 :rating :rating/bronze})
(def user-2 {:login "gordon" :referrer "mint.com" :salary 80000 :rating :rating/silver})
(def user-3 {:login "kyle" :referrer "google.com" :salary 90000 :rating :rating/gold})
(def user-4 {:login "celeste" :referrer "yahoo.com" :salary 70000 :rating :rating/platinum})
;-----------------------------------------------------
; Affiliate Profit Rating Fee (% of salary)
;-----------------------------------------------------
mint.com Bronze 0.03
mint.com Silver 0.04
mint.com Gold / Platinum 0.05
google.com Gold / Platinum 0.03
;-----------------------------------------------------
(comment)
;; the fee category will be our new dispatch function
(defn fee-category [user]
[(:referrer user) (:rating user)])
(defmulti profit-based-affiliate-fee fee-category)
(defmethod profit-based-affiliate-fee ["mint.com" :rating/bronze]
[user] (fee-amount 0.03M user))
(defmethod profit-based-affiliate-fee ["mint.com" :rating/silver]
[user] (fee-amount 0.04M user))
notice that these two methods are the same thing
;; this looks like ad hoc polymorphism
a hint that these two are the same
;; perhaps this a job for subtype polymorphism
(defmethod profit-based-affiliate-fee ["mint.com" :rating/gold]
[user] (fee-amount 0.05M user))
(defmethod profit-based-affiliate-fee ["mint.com" :rating/platinum]
[user] (fee-amount 0.05M user))
notice that these two other methods are the same thing
;; this looks like ad hoc polymorphism
a hint that these two are the same
;; perhaps this a job for subtype polymorphism
(defmethod profit-based-affiliate-fee ["google.com" :rating/gold]
[user] (fee-amount 0.03M user))
(defmethod profit-based-affiliate-fee ["google.com" :rating/platinum]
[user] (fee-amount 0.03M user))
(defmethod profit-based-affiliate-fee :default
[user] (fee-amount 0.02M user))
MULTIPLE DISPATCH AND SUBTYPE POLYMORPHISM
;
┌ ─ ─ ─ ─ ─ ─ ─ ─
; │ Profit │
; │ Rating │
; └────────┘
; ^
; |
; +------------+------------+
; | |
┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐
; │ Basic │ │Premier │
─ ─ ─ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ─ ─ ─ ┘
; ^ ^
; | |
; +------+-----+ +-----+------+
; | | | |
┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐
│ Bronze │ │ Silver │ │ Gold │ │ Platinum │
─ ─ ─ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ─ ─ ─ ─ ┘ └ ─ ─ ─ ─ ─ ─ ─ ─ ┘
USING DERIVE TO CREATE THE HIERARCHY
;; derive x from y (i.e. x is a kind of y)
(derive :rating/bronze :rating/basic)
(derive :rating/silver :rating/basic)
(derive :rating/gold :rating/premier)
(derive :rating/platinum :rating/premier)
(derive :rating/basic :rating/ANY)
(derive :rating/premier :rating/ANY)
(isa? :rating/bronze :rating/basic) ;;yields true
(parents :rating/god) ;;yields :rating/premier
(ancestors :rating/bronze) ;; yields #{:rating/ANY :rating/basic}
(descendants :rating/basic) ;;yields #{:rating/bronze :rating/silver}
(defmulti greet-user :rating)
(defmethod greet-user :rating/basic
[user] (str "Hello " (:login user) "."))
(defmethod greet-user :rating/premier
[user] (str "Welcome, " (:login user) ", valued affiliate member!"))
(comment
;;if now we do this, we can see the the multimethod criteria
;;takes into accout the hierarchical aspect to determine dispatch method
(map c4/greet-user [c4/user-1 c4/user-2 c4/user-3 c4/user-4]))
;; the fee category will be our new dispatch function
(defn fee-category [user]
[(:referrer user) (:rating user)])
(defmulti profit-based-affiliate-fee fee-category)
(defmethod profit-based-affiliate-fee ["mint.com" :rating/bronze]
[user] (fee-amount 0.03M user))
(defmethod profit-based-affiliate-fee ["mint.com" :rating/silver]
[user] (fee-amount 0.04M user))
(defmethod profit-based-affiliate-fee ["mint.com" :rating/premier]
[user] (fee-amount 0.05M user))
(defmethod profit-based-affiliate-fee ["google.com" :rating/premier]
[user] (fee-amount 0.03M user))
(comment
;;this default would not work now
(defmethod profit-based-affiliate-fee :default
[user] (fee-amount 0.02M user)))
(defmulti size-up (fn [observer observed]
[(:rating observer) (:rating observed)]))
(defmethod size-up [:rating/platinum :rating/ANY]
[_ observed] (str (:login observed) " seems scrawny."))
(defmethod size-up [:rating/ANY :rating/platinum]
[_ observed] (str (:login observed) " shimmers with unearthly light."))
(comment
;;the following invocation would cause ambiguties unless we use a prefer method
(size-up {:rating :rating/platinum} user-4)
prefer the first dispatch over the second one
(prefer-method size-up [:rating/ANY :rating/platinum]
[:rating/platinum :rating/ANY]))
(comment
since the clojure generic math function uses multimethods for its definitions
;; I can take their pow function that works on doubles and make an implementation
;; that works on longs, and voila, it now works pefectly
(defmethod math/pow [java.lang.Long java.lang.Long]
[x y] (long (Math/pow x y)))
;;just testing imports and dependencies
(defn my-pow [x y]
(math/pow x y)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; USER-DEFINED HIERARCHIES
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def my-hierarchy (make-hierarchy))
(derive my-hierarchy :a :letter) ;; Meaning :a is a :letter
(def my-hierarchy
(-> my-hierarchy
(derive :a :letter)
(derive :b :letter)
(derive :c :letter)))
(isa? my-hierarchy :a :letter) ;;yields true
(isa? my-hierarchy :d :letter) ;;yields false
(parents my-hierarchy :a) ;; yields #{:letter}
(descendants my-hierarchy :letter) ;;yields #{:a :b :c}
(defmulti letter? identity :hierarchy #'my-hierarchy)
(defmethod letter? :letter
[_] true)
| null | https://raw.githubusercontent.com/edalorzo/learning-clojure/b5db63d8e783767a85af19ccb8dbf4d4e0f53d62/src/learn/chapter04.clj | clojure |
POLYMORPHISM AND MULTIMETHODS
this is an example of close dispatch
where the referrer is the dispatch criteria
the problem is that adding referrers requires code changes
MULTIMETHODS TO THE RESCUE!
this is equivalent to just using :referrer
implementation of the multimethod
the default method can also be defined in the dispatch
MULTIPLE DISPATCH
-----------------------------------------------------
Affiliate Profit Rating Fee (% of salary)
-----------------------------------------------------
-----------------------------------------------------
the fee category will be our new dispatch function
this looks like ad hoc polymorphism
perhaps this a job for subtype polymorphism
this looks like ad hoc polymorphism
perhaps this a job for subtype polymorphism
│ Profit │
│ Rating │
└────────┘
^
|
+------------+------------+
| |
│ Basic │ │Premier │
^ ^
| |
+------+-----+ +-----+------+
| | | |
derive x from y (i.e. x is a kind of y)
yields true
yields :rating/premier
yields #{:rating/ANY :rating/basic}
yields #{:rating/bronze :rating/silver}
if now we do this, we can see the the multimethod criteria
takes into accout the hierarchical aspect to determine dispatch method
the fee category will be our new dispatch function
this default would not work now
the following invocation would cause ambiguties unless we use a prefer method
I can take their pow function that works on doubles and make an implementation
that works on longs, and voila, it now works pefectly
just testing imports and dependencies
USER-DEFINED HIERARCHIES
Meaning :a is a :letter
yields true
yields false
yields #{:letter}
yields #{:a :b :c} | (ns learn.chapter04
(:require [clojure.algo.generic.math-functions :as math :refer :all]))
(defn ad-hoc-type-name [thing]
(condp = (type thing)
java.lang.String "String"
clojure.lang.PersistentVector "Vector"))
(def type-name-implementations
{java.lang.String (fn [thing] "String")
clojure.lang.PersistentVector (fn [thing] "Vector")})
(defn open-ad-hoc-type-name [thing]
(let [dispatch-value (type thing)]
(if-let [implementation (get type-name-implementations dispatch-value)]
(implementation thing)
(throw (IllegalArgumentException. (str "No implementation found for " dispatch-value))))))
(def example-user {:login "rob" :referrer "mint.com" :salary 100000})
(defn fee-amount
"Calculates the fee you pay to affiliates based on their annual salary"
[percentage user]
(with-precision 16 :rounding HALF_EVEN
(* 0.01M percentage (:salary user))))
(comment
(defn affiliate-fee
"Calculates the fee for an affiliate user based on their referrer and annual salary"
[user]
(case (:referrer user)
"google.com" (fee-amount 0.01M user)
"mint.com" (fee-amount 0.03M user)
(fee-amount 0.02M user))))
(comment
multimethod defines dispatch criteria
(defmulti affiliate-fee
(defmethod affiliate-fee "mint.com"
[user] (fee-amount 0.03M user))
(defmethod affiliate-fee "google.com"
[user] (fee-amount 0.01M user))
(defmethod affiliate-fee :default
[user] (fee-amount 0.02M user)))
(defmulti affiliate-fee :referrer :default "*")
(defmethod affiliate-fee "mint.com"
[user] (fee-amount 0.03M user))
(defmethod affiliate-fee "google.com"
[user] (fee-amount 0.01M user))
(defmethod affiliate-fee "*"
[user] (fee-amount 0.02M user))
(def user-1 {:login "rob" :referrer "mint.com" :salary 100000 :rating :rating/bronze})
(def user-2 {:login "gordon" :referrer "mint.com" :salary 80000 :rating :rating/silver})
(def user-3 {:login "kyle" :referrer "google.com" :salary 90000 :rating :rating/gold})
(def user-4 {:login "celeste" :referrer "yahoo.com" :salary 70000 :rating :rating/platinum})
mint.com Bronze 0.03
mint.com Silver 0.04
mint.com Gold / Platinum 0.05
google.com Gold / Platinum 0.03
(comment)
(defn fee-category [user]
[(:referrer user) (:rating user)])
(defmulti profit-based-affiliate-fee fee-category)
(defmethod profit-based-affiliate-fee ["mint.com" :rating/bronze]
[user] (fee-amount 0.03M user))
(defmethod profit-based-affiliate-fee ["mint.com" :rating/silver]
[user] (fee-amount 0.04M user))
notice that these two methods are the same thing
a hint that these two are the same
(defmethod profit-based-affiliate-fee ["mint.com" :rating/gold]
[user] (fee-amount 0.05M user))
(defmethod profit-based-affiliate-fee ["mint.com" :rating/platinum]
[user] (fee-amount 0.05M user))
notice that these two other methods are the same thing
a hint that these two are the same
(defmethod profit-based-affiliate-fee ["google.com" :rating/gold]
[user] (fee-amount 0.03M user))
(defmethod profit-based-affiliate-fee ["google.com" :rating/platinum]
[user] (fee-amount 0.03M user))
(defmethod profit-based-affiliate-fee :default
[user] (fee-amount 0.02M user))
MULTIPLE DISPATCH AND SUBTYPE POLYMORPHISM
┌ ─ ─ ─ ─ ─ ─ ─ ─
┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐
─ ─ ─ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ─ ─ ─ ┘
┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐
│ Bronze │ │ Silver │ │ Gold │ │ Platinum │
─ ─ ─ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ─ ─ ─ ─ ┘ └ ─ ─ ─ ─ ─ ─ ─ ─ ┘
USING DERIVE TO CREATE THE HIERARCHY
(derive :rating/bronze :rating/basic)
(derive :rating/silver :rating/basic)
(derive :rating/gold :rating/premier)
(derive :rating/platinum :rating/premier)
(derive :rating/basic :rating/ANY)
(derive :rating/premier :rating/ANY)
(defmulti greet-user :rating)
(defmethod greet-user :rating/basic
[user] (str "Hello " (:login user) "."))
(defmethod greet-user :rating/premier
[user] (str "Welcome, " (:login user) ", valued affiliate member!"))
(comment
(map c4/greet-user [c4/user-1 c4/user-2 c4/user-3 c4/user-4]))
(defn fee-category [user]
[(:referrer user) (:rating user)])
(defmulti profit-based-affiliate-fee fee-category)
(defmethod profit-based-affiliate-fee ["mint.com" :rating/bronze]
[user] (fee-amount 0.03M user))
(defmethod profit-based-affiliate-fee ["mint.com" :rating/silver]
[user] (fee-amount 0.04M user))
(defmethod profit-based-affiliate-fee ["mint.com" :rating/premier]
[user] (fee-amount 0.05M user))
(defmethod profit-based-affiliate-fee ["google.com" :rating/premier]
[user] (fee-amount 0.03M user))
(comment
(defmethod profit-based-affiliate-fee :default
[user] (fee-amount 0.02M user)))
(defmulti size-up (fn [observer observed]
[(:rating observer) (:rating observed)]))
(defmethod size-up [:rating/platinum :rating/ANY]
[_ observed] (str (:login observed) " seems scrawny."))
(defmethod size-up [:rating/ANY :rating/platinum]
[_ observed] (str (:login observed) " shimmers with unearthly light."))
(comment
(size-up {:rating :rating/platinum} user-4)
prefer the first dispatch over the second one
(prefer-method size-up [:rating/ANY :rating/platinum]
[:rating/platinum :rating/ANY]))
(comment
since the clojure generic math function uses multimethods for its definitions
(defmethod math/pow [java.lang.Long java.lang.Long]
[x y] (long (Math/pow x y)))
(defn my-pow [x y]
(math/pow x y)))
(def my-hierarchy (make-hierarchy))
(def my-hierarchy
(-> my-hierarchy
(derive :a :letter)
(derive :b :letter)
(derive :c :letter)))
(defmulti letter? identity :hierarchy #'my-hierarchy)
(defmethod letter? :letter
[_] true)
|
9fcd30c757cb5ec8b1c98d1890bb054f97b789fa9b1c1164d8f8596cca3d4a27 | TakaiKinoko/Cornell_CS3110_OCaml | 04bstDict.ml | * 4 . binary search tree dictionary
Write a module BstDict that implements the Dictionary module type using the tree type .
Write a module BstDict that implements the Dictionary module type using the tree type.*)
module type Dictionary = sig
type ('k, 'v) t
val empty : ('k, 'v) t
val insert : 'k -> 'v -> ('k, 'v) t -> ('k, 'v) t
val lookup : 'k -> ('k, 'v) t -> 'v
end
type ('k, 'v) tree = Leaf | Node of ('k * 'v) * ('k, 'v) tree * ('k, 'v) tree
* a BstDict that takes keys of primitive types
module BstDict : Dictionary = struct
type ('k, 'v) t = Leaf | Node of ('k * 'v) * ('k, 'v) t * ('k, 'v) t (** tricky!! *)
let empty = Leaf
let rec insert k v t = match t with
| Leaf -> Node((k,v), Leaf, Leaf)
| Node((k1,v1), l, r) ->
if k = k1 then Node((k1,v), l, r)
else if Pervasives.compare k k1 <0 then Node((k1,v1), insert k v l, r)
else Node((k1,v1), l, insert k v r)
let rec lookup k t = match t with
| Leaf -> failwith "Not found"
| Node((k1,v1), l, r) ->
if k = k1 then v1
else if Pervasives.compare k k1 <0 then lookup k l
else lookup k r
end
(** tests *)
open BstDict
let d = empty |> insert 3 "apple" |> insert 1 "grapes" |> insert 2 "kiwi" |> insert 4 "pineapple"
let () =
print_endline(lookup 1 d);
print_endline(lookup 2 d);
print_endline(lookup 3 d);
print_endline(lookup 4 d)
* SOL2 : writing a functor that turns a Tree module into a Dictionary , where is an OrderedType that wrapes around tree type
module type OrderedTree = sig
type ( ' k , ' v ) t
type ( ' k , ' v ) tree = Leaf | Node of ( ' k * ' v ) * ( ' k , ' v ) tree * ( ' k , ' v ) tree ( * * note when to use asteriks , and when " , "
module type OrderedTree = sig
type ('k, 'v) t
type ('k, 'v) tree = Leaf | Node of ('k * 'v) * ('k, 'v) tree * ('k, 'v) tree (** note when to use asteriks, and when "," *)
val compare : 'k -> 'v -> ('k, 'v) tree -> int
end
module BstTree = struct
type ('k, 'v) t
type ('k, 'v) tree = Leaf | Node of ('k * 'v) * ('k, 'v) tree * ('k, 'v) tree (** note when to use asteriks, and when "," *)
let compare k v tree =
match tree with
| Leaf -> failwith "Empty tree"
| Node ((k1, v1), l, r) -> Pervasives.compare k k1
end
module Make_BstDict(T: OrderedTree) : Dictionary = struct
type ('k, 'v) t = ('k,) T.tree
type
end
*) | null | https://raw.githubusercontent.com/TakaiKinoko/Cornell_CS3110_OCaml/0a830bc50a5e39f010074dc289161426294cad1d/Chap5_Modules/08exercises/04bstDict.ml | ocaml | * tricky!!
* tests
* note when to use asteriks, and when ","
* note when to use asteriks, and when "," | * 4 . binary search tree dictionary
Write a module BstDict that implements the Dictionary module type using the tree type .
Write a module BstDict that implements the Dictionary module type using the tree type.*)
module type Dictionary = sig
type ('k, 'v) t
val empty : ('k, 'v) t
val insert : 'k -> 'v -> ('k, 'v) t -> ('k, 'v) t
val lookup : 'k -> ('k, 'v) t -> 'v
end
type ('k, 'v) tree = Leaf | Node of ('k * 'v) * ('k, 'v) tree * ('k, 'v) tree
* a BstDict that takes keys of primitive types
module BstDict : Dictionary = struct
let empty = Leaf
let rec insert k v t = match t with
| Leaf -> Node((k,v), Leaf, Leaf)
| Node((k1,v1), l, r) ->
if k = k1 then Node((k1,v), l, r)
else if Pervasives.compare k k1 <0 then Node((k1,v1), insert k v l, r)
else Node((k1,v1), l, insert k v r)
let rec lookup k t = match t with
| Leaf -> failwith "Not found"
| Node((k1,v1), l, r) ->
if k = k1 then v1
else if Pervasives.compare k k1 <0 then lookup k l
else lookup k r
end
open BstDict
let d = empty |> insert 3 "apple" |> insert 1 "grapes" |> insert 2 "kiwi" |> insert 4 "pineapple"
let () =
print_endline(lookup 1 d);
print_endline(lookup 2 d);
print_endline(lookup 3 d);
print_endline(lookup 4 d)
* SOL2 : writing a functor that turns a Tree module into a Dictionary , where is an OrderedType that wrapes around tree type
module type OrderedTree = sig
type ( ' k , ' v ) t
type ( ' k , ' v ) tree = Leaf | Node of ( ' k * ' v ) * ( ' k , ' v ) tree * ( ' k , ' v ) tree ( * * note when to use asteriks , and when " , "
module type OrderedTree = sig
type ('k, 'v) t
val compare : 'k -> 'v -> ('k, 'v) tree -> int
end
module BstTree = struct
type ('k, 'v) t
let compare k v tree =
match tree with
| Leaf -> failwith "Empty tree"
| Node ((k1, v1), l, r) -> Pervasives.compare k k1
end
module Make_BstDict(T: OrderedTree) : Dictionary = struct
type ('k, 'v) t = ('k,) T.tree
type
end
*) |
224826aa6820c0b8262804e41baf0975157f1f7e19ace5ec96fadb3ae1d199ef | ddmcdonald/sparser | session.lisp | ;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: SPARSER -*-
Copyright ( c ) 2016 - 2022 SIFT LLC . All Rights Reserved .
;;;
;;; File: "session"
;;; Module: "init;"
Version : January 2022
(in-package :sparser)
Finalize the load .
(when *load-the-grammar*
(when *include-model-facilities*
(load-delayed-dossiers)
;; This call announces the # of individuals in all the defined categories
;; that have instances (see *referential-categories*)
(postprocess-grammar-indexes)
;;---------- the very last thing to do ----------
(declare-all-existing-individuals-permanent)))
;; Final session setup.
(setup-session-globals/parser)
(setup-session-globals/grammar)
(stop-timer '*time-to-load-everything*)
(report-time-to-load-system)
(when cl-user::location-of-text-corpora
(push :full-corpus *features*))
(eval-when (:load-toplevel :execute)
(setq *sparser-loaded* t))
;; Finally, print a salutation to the REPL.
(format t "~%Welcome to the Sparser natural language analysis system.~
~%Copyright (c) David D. McDonald 1991-2005,2010-2022.~
~%Distributed under the Eclipse Public License.~
~%~
~%Type (in-package :sparser) to use Sparser symbols directly.~
~%~%")
| null | https://raw.githubusercontent.com/ddmcdonald/sparser/da94d1bbbed289859ddfcb6d352bced66054a939/Sparser/code/s/init/session.lisp | lisp | -*- Mode: LISP; Syntax: Common-Lisp; Package: SPARSER -*-
File: "session"
Module: "init;"
This call announces the # of individuals in all the defined categories
that have instances (see *referential-categories*)
---------- the very last thing to do ----------
Final session setup.
Finally, print a salutation to the REPL. | Copyright ( c ) 2016 - 2022 SIFT LLC . All Rights Reserved .
Version : January 2022
(in-package :sparser)
Finalize the load .
(when *load-the-grammar*
(when *include-model-facilities*
(load-delayed-dossiers)
(postprocess-grammar-indexes)
(declare-all-existing-individuals-permanent)))
(setup-session-globals/parser)
(setup-session-globals/grammar)
(stop-timer '*time-to-load-everything*)
(report-time-to-load-system)
(when cl-user::location-of-text-corpora
(push :full-corpus *features*))
(eval-when (:load-toplevel :execute)
(setq *sparser-loaded* t))
(format t "~%Welcome to the Sparser natural language analysis system.~
~%Copyright (c) David D. McDonald 1991-2005,2010-2022.~
~%Distributed under the Eclipse Public License.~
~%~
~%Type (in-package :sparser) to use Sparser symbols directly.~
~%~%")
|
f0279569e69d2229bf09cbce984432b6538a3e800b3f270c3d1ef561de84576f | msakai/toysolver | CongruenceClosure.hs | # LANGUAGE TemplateHaskell #
# OPTIONS_GHC -Wall #
module Test.CongruenceClosure (ccTestGroup) where
import Control.Monad
import Control.Monad.State
import Data.Array
import Data.Graph
import qualified Data.Tree as Tree
import qualified Data.IntSet as IntSet
import qualified Data.Set as Set
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Tasty.HUnit
import Test.Tasty.TH
import qualified Test.QuickCheck.Monadic as QM
import ToySolver.EUF.CongruenceClosure
import qualified ToySolver.EUF.EUFSolver as EUF
------------------------------------------------------------------------
-- Test cases
case_Example_1 :: Assertion
case_Example_1 = do
solver <- newSolver
a <- newFSym solver
b <- newFSym solver
c <- newFSym solver
d <- newFSym solver
merge solver (TApp a []) (TApp c [])
ret <- areCongruent solver (TApp a [TApp b []]) (TApp c [TApp d []])
ret @?= False
merge solver (TApp b []) (TApp d [])
ret <- areCongruent solver (TApp a [TApp b []]) (TApp c [TApp d []])
ret @?= True
case_Example_1_FlatTerm :: Assertion
case_Example_1_FlatTerm = do
solver <- newSolver
a <- newFSym solver
b <- newFSym solver
c <- newFSym solver
d <- newFSym solver
mergeFlatTerm solver (FTConst a) c
ret <- areCongruentFlatTerm solver (FTApp a b) (FTApp c d)
ret @?= False
mergeFlatTerm solver (FTConst b) d
ret <- areCongruentFlatTerm solver (FTApp a b) (FTApp c d)
ret @?= True
case_Example_2 :: Assertion
case_Example_2 = do
solver <- newSolver
a <- newConst solver
b <- newConst solver
c <- newConst solver
f <- newFun solver
g <- newFun solver
h <- newFun solver
merge solver (f b) c
merge solver (f c) a
merge solver (g a) (h a a)
ret <- areCongruent solver (g b) (h c b)
ret @?= False
merge solver b c
ret <- areCongruent solver (g b) (h c b)
ret @?= True
case_NO2007_Example_11 :: Assertion
case_NO2007_Example_11 = do
solver <- newSolver
replicateM_ 15 $ newFSym solver
let xs = [(1,8),(7,2),(3,13),(7,1),(6,7),(6,7),(9,5),(9,3),(14,11),(10,4),(12,9),(4,11),(10,7)]
forM_ (zip [0..] xs) $ \(i,(a,b)) -> mergeFlatTerm' solver (FTConst a) b (Just i)
m <- explainConst solver 1 4
fmap (Set.fromList . map (xs!!) . IntSet.toList) m @?= Just (Set.fromList [(7,1), (10,4), (10,7)])
f(g , h)=d , c = d , , d)=a , e = c , e = b , b = h
case_NO2007_Example_16 :: Assertion
case_NO2007_Example_16 = do
solver <- newSolver
a <- newFSym solver
b <- newFSym solver
c <- newFSym solver
d <- newFSym solver
e <- newFSym solver
g <- newFSym solver
h <- newFSym solver
mergeFlatTerm' solver (FTApp g h) d (Just 0)
mergeFlatTerm' solver (FTConst c) d (Just 1)
mergeFlatTerm' solver (FTApp g d) a (Just 2)
mergeFlatTerm' solver (FTConst e) c (Just 3)
mergeFlatTerm' solver (FTConst e) b (Just 4)
mergeFlatTerm' solver (FTConst b) h (Just 5)
m <- explainConst solver a b
m @?= Just (IntSet.fromList [1,3,4,5,0,2])
-- d = c = e = b = h
a = f(g , d ) = f(g , h ) = d = c = e = b
case_backtracking_1 :: Assertion
case_backtracking_1 = do
solver <- newSolver
a1 <- newFSym solver
a2 <- newFSym solver
b1 <- newFSym solver
b2 <- newFSym solver
mergeFlatTerm solver (FTConst a1) b1
pushBacktrackPoint solver
mergeFlatTerm solver (FTConst a2) b2
ret <- areCongruentFlatTerm solver (FTApp a1 a2) (FTApp b1 b2)
ret @?= True
popBacktrackPoint solver
ret <- areCongruentFlatTerm solver (FTConst a2) (FTConst b2)
ret @?= False
ret <- areCongruentFlatTerm solver (FTApp a1 a2) (FTApp b1 b2)
ret @?= False
pushBacktrackPoint solver
ret <- areCongruentFlatTerm solver (FTConst a2) (FTConst b2)
ret @?= False
ret <- areCongruentFlatTerm solver (FTApp a1 a2) (FTApp b1 b2)
ret @?= False
popBacktrackPoint solver
case_backtracking_preserve_definition :: Assertion
case_backtracking_preserve_definition = do
solver <- newSolver
a1 <- newFSym solver
a2 <- newFSym solver
b1 <- newFSym solver
b2 <- newFSym solver
pushBacktrackPoint solver
a <- flatTermToFSym solver (FTApp a1 a2)
b <- flatTermToFSym solver (FTApp b1 b2)
popBacktrackPoint solver
c <- newFSym solver
mergeFlatTerm solver (FTApp a1 a2) c
mergeFlatTerm solver (FTApp b1 b2) c
ret <- areCongruentFlatTerm solver (FTConst a) (FTConst b)
ret @?= True
prop_components :: Property
prop_components = QM.monadicIO $ do
nv <- QM.pick $ choose (1, 10)
ne <- QM.pick $ choose (1, 100)
edges <- QM.pick $ replicateM ne $ do
s <- choose (0,nv-1)
t <- choose (0,nv-1)
return (s,t)
let g = buildG (0,nv-1) edges
repr = array (0,nv-1) [(c, Tree.rootLabel comp) | comp <- components g, c <- Tree.flatten comp]
solver <- QM.run $ newSolver
QM.run $ do
replicateM_ nv $ newFSym solver
forM_ edges $ \(s,t) -> mergeFlatTerm solver (FTConst s) t
forM_ [0..(nv-1)] $ \c ->
forM_ [0..(nv-1)] $ \d -> do
b <- QM.run $ areCongruentFlatTerm solver (FTConst c) (FTConst d)
QM.assert $ b == (repr ! c == repr ! d)
case_fsymToTerm_termToSym :: Assertion
case_fsymToTerm_termToSym = do
solver <- newSolver
f <- liftM (\f x y -> TApp f [x,y]) $ newFSym solver
g <- liftM (\f x -> TApp f [x]) $ newFSym solver
a <- newConst solver
let t = f (g a) (g (g a))
c <- termToFSym solver t
t2 <- fsymToTerm solver c
t2 @?= t
case_getModel_test1 :: Assertion
case_getModel_test1 = do
solver <- newSolver
a <- newConst solver
b <- newConst solver
c <- newConst solver
_d <- newConst solver
f <- newFun solver
g <- newFun solver
h <- newFun solver
merge solver (f b) c
merge solver (f c) a
merge solver (g a) (h a a)
m1 <- getModel solver
(eval m1 (f b) == eval m1 c) @?= True
(eval m1 (f c) == eval m1 a) @?= True
(eval m1 (g a) == eval m1 (h a a)) @?= True
(eval m1 (f b) == eval m1 (f c)) @?= False
merge solver b c
m2 <- getModel solver
(eval m2 (f b) == eval m2 c) @?= True
(eval m2 (f c) == eval m2 a) @?= True
(eval m2 (g a) == eval m2 (h a a)) @?= True
(eval m2 (f b) == eval m2 (f c)) @?= True
(eval m2 (g b) == eval m2 (g c)) @?= True
case_EUF_getModel_test1 :: Assertion
case_EUF_getModel_test1 = do
solver <- EUF.newSolver
0
1
2
3
4
5
EUF.assertEqual solver (f b) c
EUF.assertEqual solver (f c) a
EUF.assertEqual solver (g a) (h a a)
True <- EUF.check solver
m1 <- EUF.getModel solver
(eval m1 (g b) == eval m1 (h c b)) @?= True
EUF.assertNotEqual solver (g b) (h c b)
True <- EUF.check solver
m2 <- EUF.getModel solver
(eval m2 (g b) == eval m2 (h c b)) @?= False
prop_getModel_eval_1 :: Property
prop_getModel_eval_1 = QM.monadicIO $ do
solver <- QM.run newSolver
a <- QM.run $ newConst solver
b <- QM.run $ newConst solver
c <- QM.run $ newConst solver
f <- QM.run $ newFun solver
g <- QM.run $ newFun solver
h <- QM.run $ newFun solver
let genExpr :: Gen Term
genExpr = evalStateT genExpr' 10
genExpr' :: StateT Int Gen Term
genExpr' = do
budget <- get
modify (subtract 1)
join $ lift $ elements $ concat $
[ map return [a,b,c]
, [ liftM f genExpr' | budget >= 2 ]
, [ liftM g genExpr' | budget >= 2 ]
, [ liftM2 h genExpr' genExpr' | budget >= 3 ]
]
es <- QM.pick $ do
n <- choose (0, 20)
replicateM n $ do
lhs <- genExpr
rhs <- genExpr
return (lhs,rhs)
join $ QM.run $ do
forM_ es $ \(lhs,rhs) ->
merge solver lhs rhs
m <- getModel solver
return $
forM_ es $ \(lhs,rhs) -> do
QM.assert (eval m lhs == eval m rhs)
prop_getModel_eval_2 :: Property
prop_getModel_eval_2 = QM.monadicIO $ do
solver <- QM.run newSolver
a <- QM.run $ newConst solver
b <- QM.run $ newConst solver
c <- QM.run $ newConst solver
f <- QM.run $ newFun solver
g <- QM.run $ newFun solver
h <- QM.run $ newFun solver
let genExpr :: Gen Term
genExpr = evalStateT genExpr' 10
genExpr' :: StateT Int Gen Term
genExpr' = do
budget <- get
modify (subtract 1)
join $ lift $ elements $ concat $
[ map return [a,b,c]
, [ liftM f genExpr' | budget >= 2 ]
, [ liftM g genExpr' | budget >= 2 ]
, [ liftM2 h genExpr' genExpr' | budget >= 3 ]
]
es <- QM.pick $ do
n <- choose (0, 20)
replicateM n $ do
lhs <- genExpr
rhs <- genExpr
return (lhs,rhs)
(lhs,rhs) <- QM.pick $ do
lhs <- genExpr
rhs <- genExpr
return (lhs,rhs)
join $ QM.run $ do
forM_ es $ \(lhs,rhs) -> do
merge solver lhs rhs
b <- areCongruent solver lhs rhs
if b then do
m <- getModel solver
return $ QM.assert (eval m lhs == eval m rhs)
else
return $ return ()
------------------------------------------------------------------------
-- Test harness
ccTestGroup :: TestTree
ccTestGroup = $(testGroupGenerator)
| null | https://raw.githubusercontent.com/msakai/toysolver/6233d130d3dcea32fa34c26feebd151f546dea85/test/Test/CongruenceClosure.hs | haskell | ----------------------------------------------------------------------
Test cases
d = c = e = b = h
----------------------------------------------------------------------
Test harness | # LANGUAGE TemplateHaskell #
# OPTIONS_GHC -Wall #
module Test.CongruenceClosure (ccTestGroup) where
import Control.Monad
import Control.Monad.State
import Data.Array
import Data.Graph
import qualified Data.Tree as Tree
import qualified Data.IntSet as IntSet
import qualified Data.Set as Set
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Tasty.HUnit
import Test.Tasty.TH
import qualified Test.QuickCheck.Monadic as QM
import ToySolver.EUF.CongruenceClosure
import qualified ToySolver.EUF.EUFSolver as EUF
case_Example_1 :: Assertion
case_Example_1 = do
solver <- newSolver
a <- newFSym solver
b <- newFSym solver
c <- newFSym solver
d <- newFSym solver
merge solver (TApp a []) (TApp c [])
ret <- areCongruent solver (TApp a [TApp b []]) (TApp c [TApp d []])
ret @?= False
merge solver (TApp b []) (TApp d [])
ret <- areCongruent solver (TApp a [TApp b []]) (TApp c [TApp d []])
ret @?= True
case_Example_1_FlatTerm :: Assertion
case_Example_1_FlatTerm = do
solver <- newSolver
a <- newFSym solver
b <- newFSym solver
c <- newFSym solver
d <- newFSym solver
mergeFlatTerm solver (FTConst a) c
ret <- areCongruentFlatTerm solver (FTApp a b) (FTApp c d)
ret @?= False
mergeFlatTerm solver (FTConst b) d
ret <- areCongruentFlatTerm solver (FTApp a b) (FTApp c d)
ret @?= True
case_Example_2 :: Assertion
case_Example_2 = do
solver <- newSolver
a <- newConst solver
b <- newConst solver
c <- newConst solver
f <- newFun solver
g <- newFun solver
h <- newFun solver
merge solver (f b) c
merge solver (f c) a
merge solver (g a) (h a a)
ret <- areCongruent solver (g b) (h c b)
ret @?= False
merge solver b c
ret <- areCongruent solver (g b) (h c b)
ret @?= True
case_NO2007_Example_11 :: Assertion
case_NO2007_Example_11 = do
solver <- newSolver
replicateM_ 15 $ newFSym solver
let xs = [(1,8),(7,2),(3,13),(7,1),(6,7),(6,7),(9,5),(9,3),(14,11),(10,4),(12,9),(4,11),(10,7)]
forM_ (zip [0..] xs) $ \(i,(a,b)) -> mergeFlatTerm' solver (FTConst a) b (Just i)
m <- explainConst solver 1 4
fmap (Set.fromList . map (xs!!) . IntSet.toList) m @?= Just (Set.fromList [(7,1), (10,4), (10,7)])
f(g , h)=d , c = d , , d)=a , e = c , e = b , b = h
case_NO2007_Example_16 :: Assertion
case_NO2007_Example_16 = do
solver <- newSolver
a <- newFSym solver
b <- newFSym solver
c <- newFSym solver
d <- newFSym solver
e <- newFSym solver
g <- newFSym solver
h <- newFSym solver
mergeFlatTerm' solver (FTApp g h) d (Just 0)
mergeFlatTerm' solver (FTConst c) d (Just 1)
mergeFlatTerm' solver (FTApp g d) a (Just 2)
mergeFlatTerm' solver (FTConst e) c (Just 3)
mergeFlatTerm' solver (FTConst e) b (Just 4)
mergeFlatTerm' solver (FTConst b) h (Just 5)
m <- explainConst solver a b
m @?= Just (IntSet.fromList [1,3,4,5,0,2])
a = f(g , d ) = f(g , h ) = d = c = e = b
case_backtracking_1 :: Assertion
case_backtracking_1 = do
solver <- newSolver
a1 <- newFSym solver
a2 <- newFSym solver
b1 <- newFSym solver
b2 <- newFSym solver
mergeFlatTerm solver (FTConst a1) b1
pushBacktrackPoint solver
mergeFlatTerm solver (FTConst a2) b2
ret <- areCongruentFlatTerm solver (FTApp a1 a2) (FTApp b1 b2)
ret @?= True
popBacktrackPoint solver
ret <- areCongruentFlatTerm solver (FTConst a2) (FTConst b2)
ret @?= False
ret <- areCongruentFlatTerm solver (FTApp a1 a2) (FTApp b1 b2)
ret @?= False
pushBacktrackPoint solver
ret <- areCongruentFlatTerm solver (FTConst a2) (FTConst b2)
ret @?= False
ret <- areCongruentFlatTerm solver (FTApp a1 a2) (FTApp b1 b2)
ret @?= False
popBacktrackPoint solver
case_backtracking_preserve_definition :: Assertion
case_backtracking_preserve_definition = do
solver <- newSolver
a1 <- newFSym solver
a2 <- newFSym solver
b1 <- newFSym solver
b2 <- newFSym solver
pushBacktrackPoint solver
a <- flatTermToFSym solver (FTApp a1 a2)
b <- flatTermToFSym solver (FTApp b1 b2)
popBacktrackPoint solver
c <- newFSym solver
mergeFlatTerm solver (FTApp a1 a2) c
mergeFlatTerm solver (FTApp b1 b2) c
ret <- areCongruentFlatTerm solver (FTConst a) (FTConst b)
ret @?= True
prop_components :: Property
prop_components = QM.monadicIO $ do
nv <- QM.pick $ choose (1, 10)
ne <- QM.pick $ choose (1, 100)
edges <- QM.pick $ replicateM ne $ do
s <- choose (0,nv-1)
t <- choose (0,nv-1)
return (s,t)
let g = buildG (0,nv-1) edges
repr = array (0,nv-1) [(c, Tree.rootLabel comp) | comp <- components g, c <- Tree.flatten comp]
solver <- QM.run $ newSolver
QM.run $ do
replicateM_ nv $ newFSym solver
forM_ edges $ \(s,t) -> mergeFlatTerm solver (FTConst s) t
forM_ [0..(nv-1)] $ \c ->
forM_ [0..(nv-1)] $ \d -> do
b <- QM.run $ areCongruentFlatTerm solver (FTConst c) (FTConst d)
QM.assert $ b == (repr ! c == repr ! d)
case_fsymToTerm_termToSym :: Assertion
case_fsymToTerm_termToSym = do
solver <- newSolver
f <- liftM (\f x y -> TApp f [x,y]) $ newFSym solver
g <- liftM (\f x -> TApp f [x]) $ newFSym solver
a <- newConst solver
let t = f (g a) (g (g a))
c <- termToFSym solver t
t2 <- fsymToTerm solver c
t2 @?= t
case_getModel_test1 :: Assertion
case_getModel_test1 = do
solver <- newSolver
a <- newConst solver
b <- newConst solver
c <- newConst solver
_d <- newConst solver
f <- newFun solver
g <- newFun solver
h <- newFun solver
merge solver (f b) c
merge solver (f c) a
merge solver (g a) (h a a)
m1 <- getModel solver
(eval m1 (f b) == eval m1 c) @?= True
(eval m1 (f c) == eval m1 a) @?= True
(eval m1 (g a) == eval m1 (h a a)) @?= True
(eval m1 (f b) == eval m1 (f c)) @?= False
merge solver b c
m2 <- getModel solver
(eval m2 (f b) == eval m2 c) @?= True
(eval m2 (f c) == eval m2 a) @?= True
(eval m2 (g a) == eval m2 (h a a)) @?= True
(eval m2 (f b) == eval m2 (f c)) @?= True
(eval m2 (g b) == eval m2 (g c)) @?= True
case_EUF_getModel_test1 :: Assertion
case_EUF_getModel_test1 = do
solver <- EUF.newSolver
0
1
2
3
4
5
EUF.assertEqual solver (f b) c
EUF.assertEqual solver (f c) a
EUF.assertEqual solver (g a) (h a a)
True <- EUF.check solver
m1 <- EUF.getModel solver
(eval m1 (g b) == eval m1 (h c b)) @?= True
EUF.assertNotEqual solver (g b) (h c b)
True <- EUF.check solver
m2 <- EUF.getModel solver
(eval m2 (g b) == eval m2 (h c b)) @?= False
prop_getModel_eval_1 :: Property
prop_getModel_eval_1 = QM.monadicIO $ do
solver <- QM.run newSolver
a <- QM.run $ newConst solver
b <- QM.run $ newConst solver
c <- QM.run $ newConst solver
f <- QM.run $ newFun solver
g <- QM.run $ newFun solver
h <- QM.run $ newFun solver
let genExpr :: Gen Term
genExpr = evalStateT genExpr' 10
genExpr' :: StateT Int Gen Term
genExpr' = do
budget <- get
modify (subtract 1)
join $ lift $ elements $ concat $
[ map return [a,b,c]
, [ liftM f genExpr' | budget >= 2 ]
, [ liftM g genExpr' | budget >= 2 ]
, [ liftM2 h genExpr' genExpr' | budget >= 3 ]
]
es <- QM.pick $ do
n <- choose (0, 20)
replicateM n $ do
lhs <- genExpr
rhs <- genExpr
return (lhs,rhs)
join $ QM.run $ do
forM_ es $ \(lhs,rhs) ->
merge solver lhs rhs
m <- getModel solver
return $
forM_ es $ \(lhs,rhs) -> do
QM.assert (eval m lhs == eval m rhs)
prop_getModel_eval_2 :: Property
prop_getModel_eval_2 = QM.monadicIO $ do
solver <- QM.run newSolver
a <- QM.run $ newConst solver
b <- QM.run $ newConst solver
c <- QM.run $ newConst solver
f <- QM.run $ newFun solver
g <- QM.run $ newFun solver
h <- QM.run $ newFun solver
let genExpr :: Gen Term
genExpr = evalStateT genExpr' 10
genExpr' :: StateT Int Gen Term
genExpr' = do
budget <- get
modify (subtract 1)
join $ lift $ elements $ concat $
[ map return [a,b,c]
, [ liftM f genExpr' | budget >= 2 ]
, [ liftM g genExpr' | budget >= 2 ]
, [ liftM2 h genExpr' genExpr' | budget >= 3 ]
]
es <- QM.pick $ do
n <- choose (0, 20)
replicateM n $ do
lhs <- genExpr
rhs <- genExpr
return (lhs,rhs)
(lhs,rhs) <- QM.pick $ do
lhs <- genExpr
rhs <- genExpr
return (lhs,rhs)
join $ QM.run $ do
forM_ es $ \(lhs,rhs) -> do
merge solver lhs rhs
b <- areCongruent solver lhs rhs
if b then do
m <- getModel solver
return $ QM.assert (eval m lhs == eval m rhs)
else
return $ return ()
ccTestGroup :: TestTree
ccTestGroup = $(testGroupGenerator)
|
1b70f36bba15cf7d761955e063ea68ba05fc68e76c308cabc597db1b494beb5a | cracauer/sbcl-ita | backtrace.impure.lisp | ;;;; This file is for testing backtraces, using test machinery which
might have side effects ( e.g. executing DEFUN ) .
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
While most of SBCL is derived from the CMU CL system , the test
;;;; files (like this one) were written from scratch after the fork
from CMU CL .
;;;;
;;;; This software is in the public domain and is provided with
;;;; absolutely no warranty. See the COPYING and CREDITS files for
;;;; more information.
(cl:in-package :cl-user)
;;; The following objects should be EQUALP to the respective markers
;;; produced by the backtrace machinery.
(defvar *unused-argument*
(sb-debug::make-unprintable-object "unused argument"))
(defvar *unavailable-argument*
(sb-debug::make-unprintable-object "unavailable argument"))
(defvar *unavailable-lambda-list*
(sb-debug::make-unprintable-object "unavailable lambda list"))
;;; TEST-FUNCTION is called and has to signal an error at which point
;;; the backtrace will be captured.
;;;
;;; If DETAILS is true, the returned backtrace description is of the
;;; form:
;;;
( ( ( NAME1 . ARGS1 ) INFO1 )
( ( NAME2 . ) INFO2 )
;;; ...)
;;;
;;; Otherwise it is of the form
;;;
( ( NAME1 . ARGS1 )
( NAME2 . )
;;; ...)
;;;
(defun call-with-backtrace (cont test-function &key details)
(flet ((capture-it (condition)
(let (backtrace)
(sb-debug::map-backtrace
(lambda (frame)
(multiple-value-bind (name args info)
(sb-debug::frame-call frame)
(push (if details
(list (cons name args) info)
(cons name args))
backtrace))))
(funcall cont (nreverse backtrace) condition))))
(handler-bind ((error #'capture-it))
(funcall test-function))))
Check the backtrace FRAMES against the list of frame
;;; specifications EXPECTED signaling an error if they do not match.
;;;
;;; If DETAILS is true, EXPECTED is a list with elements of the form
;;;
;;; ((FUNCTION ARGS) INFO)
;;;
;;; Otherwise elements are of the form
;;;
;;; (FUNCTION ARGS)
;;;
;;; ARGS is a list of expected argument values, but can also contain
;;; the following symbols
;;;
& REST The corresponding frame in FRAMES can contain an arbitrary
;;; number of arguments starting at the corresponding
;;; position.
;;;
? The corresponding frame in FRAMES can have an arbitrary
;;; argument at the corresponding position.
(defun check-backtrace (frames expected &key details)
(labels ((args-equal (want actual)
(cond ((eq want *unavailable-lambda-list*)
(equalp want actual))
((eq '&rest (car want))
t)
((endp want)
(endp actual))
((or (eq '? (car want)) (equal (car want) (car actual)))
(args-equal (cdr want) (cdr actual)))
((typep (car want) 'sb-impl::unprintable-object)
(equalp (car want) (car actual)))
(t
nil)))
(fail (datum &rest arguments)
(return-from check-backtrace
(values nil (sb-kernel:coerce-to-condition
datum arguments 'simple-error 'error)))))
(mapc (lambda (frame spec)
(unless (cond
((not spec)
t)
(details
(and (args-equal (car spec)
(car frame))
(equal (cdr spec) (cdr frame))))
(t
(and (equal (car spec) (car frame))
(args-equal (cdr spec) (cdr frame)))))
(fail "~@<Unexpected frame during ~
~:[non-detailed~:;detailed~] check: wanted ~S, got ~
~S~@:>"
details spec frame)))
frames expected))
t)
;;; Check for backtraces generally being correct. Ensure that the
;;; actual backtrace finishes (doesn't signal any errors on its own),
;;; and that it contains the frames we expect, doesn't contain any
;;; "bogus stack frame"s, and contains the appropriate toplevel call
;;; and hasn't been cut off anywhere.
;;;
;;; See CHECK-BACKTRACE for an explanation of the structure
;;; EXPECTED-FRAMES.
(defun verify-backtrace (test-function expected-frames &key details)
(labels ((find-frame (function-name frames)
(member function-name frames
:key (if details #'caar #'car)
:test #'equal))
(fail (datum &rest arguments)
(return-from verify-backtrace
(values nil (sb-kernel:coerce-to-condition
datum arguments 'simple-error 'error)))))
(call-with-backtrace
(lambda (backtrace condition)
(declare (ignore condition))
(let* ((test-function-name (if details
(caaar expected-frames)
(caar expected-frames)))
(frames (or (find-frame test-function-name backtrace)
(fail "~@<~S (expected name ~S) not found in ~
backtrace:~@:_~S~@:>"
test-function test-function-name backtrace))))
;; Check that we have all the frames we wanted.
(multiple-value-bind (successp condition)
(check-backtrace frames expected-frames :details details)
(unless successp (fail condition)))
;; Make sure the backtrace isn't stunted in any way.
;; (Depends on running in the main thread.) FIXME: On Windows
we get two extra foreign frames below regular frames .
(unless (find-frame 'sb-impl::toplevel-init frames)
(fail "~@<Backtrace stunted:~@:_~S~@:>" backtrace)))
(return-from verify-backtrace t))
test-function :details details)))
(defun assert-backtrace (test-function expected-frames &key details)
(multiple-value-bind (successp condition)
(verify-backtrace test-function expected-frames :details details)
(or successp (error condition))))
(defvar *p* (namestring *load-truename*))
(defvar *undefined-function-frame*
'("undefined function"))
(defun oops ()
(error "oops"))
;;; Test for "undefined function" (undefined_tramp) working properly.
;;; Try it with and without tail call elimination, since they can have
;;; different effects. (Specifically, if undefined_tramp is incorrect
;;; a stunted stack can result from the tail call variant.)
(flet ((optimized ()
(declare (optimize (speed 2) (debug 1))) ; tail call elimination
(#:undefined-function 42))
(not-optimized ()
(declare (optimize (speed 1) (debug 3))) ; no tail call elimination
(#:undefined-function 42))
(test (fun)
(declare (optimize (speed 1) (debug 3))) ; no tail call elimination
(funcall fun)))
(with-test (:name (:backtrace :undefined-function :bug-346)
:skipped-on :interpreter
Failures on SPARC , and probably HPPA are due to
;; not having a full and valid stack frame for the
;; undefined function frame. See PPC
;; undefined_tramp for details.
:fails-on '(or :sparc))
(assert-backtrace
(lambda () (test #'optimized))
(list *undefined-function-frame*
(list `(flet test :in ,*p*) #'optimized))))
bug 353 : This test fails at least most of the time for x86 / linux
ca . 0.8.20.16 . -- WHN
(with-test (:name (:backtrace :undefined-function :bug-353)
:skipped-on :interpreter)
(assert-backtrace
(lambda () (test #'not-optimized))
(list *undefined-function-frame*
(list `(flet not-optimized :in ,*p*))
(list `(flet test :in ,*p*) #'not-optimized)))))
(with-test (:name (:backtrace :interrupted-condition-wait)
:skipped-on '(not :sb-thread))
(let ((m (sb-thread:make-mutex))
(q (sb-thread:make-waitqueue)))
(assert-backtrace
(lambda ()
(sb-thread:with-mutex (m)
(handler-bind ((timeout (lambda (condition)
(declare (ignore condition))
(error "foo"))))
(with-timeout 0.1
(sb-thread:condition-wait q m)))))
`((sb-thread:condition-wait ,q ,m :timeout nil)))))
Division by zero was a common error on PPC . It depended on the
return function either being before INTEGER-/-INTEGER in memory ,
;;; or more than MOST-POSITIVE-FIXNUM bytes ahead. It also depends on
INTEGER-/-INTEGER calling SIGNED - TRUNCATE . I believe
says that the Sparc backend ( at least for CMUCL ) inlines this , so
if SBCL does the same this test is probably not good for the
Sparc .
;;;
;;; Disabling tail call elimination on this will probably ensure that
;;; the return value (to the flet or the enclosing top level form) is
;;; more than MOST-POSITIVE-FIXNUM with the current spaces on OS X.
;;; Enabling it might catch other problems, so do it anyway.
(flet ((optimized ()
(declare (optimize (speed 2) (debug 1))) ; tail call elimination
(/ 42 0))
(not-optimized ()
(declare (optimize (speed 1) (debug 3))) ; no tail call elimination
(/ 42 0))
(test (fun)
(declare (optimize (speed 1) (debug 3))) ; no tail call elimination
(funcall fun)))
(with-test (:name (:backtrace :divide-by-zero :bug-346)
:skipped-on :interpreter)
(assert-backtrace (lambda () (test #'optimized))
`((/ 42 &rest)
((flet test :in ,*p*) ,#'optimized))))
(with-test (:name (:backtrace :divide-by-zero :bug-356)
:skipped-on :interpreter)
(assert-backtrace (lambda () (test #'not-optimized))
`((/ 42 &rest)
((flet not-optimized :in ,*p*))
((flet test :in ,*p*) ,#'not-optimized)))))
(defun throw-test ()
(throw 'no-such-tag t))
(with-test (:name (:backtrace :throw :no-such-tag)
:fails-on '(and :sparc :linux))
(assert-backtrace #'throw-test '((throw-test))))
(funcall (checked-compile
'(lambda ()
(defun bug-308926 (x)
(let ((v "foo"))
(flet ((bar (z)
(oops v z)
(oops z v)))
(bar x)
(bar v)))))
:allow-style-warnings t))
(with-test (:name (:backtrace :bug-308926) :skipped-on :interpreter)
(assert-backtrace (lambda () (bug-308926 13))
'(((flet bar :in bug-308926) 13)
(bug-308926 &rest t))))
;;; Test backtrace through assembly routines
;;; :bug-800343
(macrolet ((test (predicate fun
&optional (two-arg
(find-symbol (format nil "TWO-ARG-~A" fun)
"SB-KERNEL")))
(let ((test-name (make-symbol (format nil "TEST-~A" fun))))
`(flet ((,test-name (x y)
;; make sure it's not in tail position
(list (,fun x y))))
(with-test (:name (:backtrace :bug-800343 ,fun)
:skipped-on :interpreter)
(assert-backtrace
(lambda ()
(eval `(funcall ,#',test-name 42 t)))
'((,two-arg 42 t)
#+(or x86 x86-64)
,@(and predicate
`((,(find-symbol (format nil "GENERIC-~A" fun) "SB-VM"))))
((flet ,test-name :in ,*p*) 42 t)))))))
(test-predicates (&rest functions)
`(progn ,@(mapcar (lambda (function)
`(test t ,@(sb-int:ensure-list function)))
functions)))
(test-functions (&rest functions)
`(progn ,@(mapcar (lambda (function)
`(test nil ,@(sb-int:ensure-list function)))
functions))))
(test-predicates = < >)
(test-functions + - * /
gcd lcm
(logand sb-kernel:two-arg-and)
(logior sb-kernel:two-arg-ior)
(logxor sb-kernel:two-arg-xor)))
;;; test entry point handling in backtraces
(with-test (:name (:backtrace :xep-too-many-arguments)
:skipped-on :interpreter)
;; CHECKED-COMPILE avoids STYLE-WARNING noise.
(assert-backtrace (checked-compile '(lambda () (oops 1 2 3 4 5 6))
:allow-style-warnings t)
'((oops ? ? ? ? ? ?))))
(defmacro defbt (n ll &body body)
;; WTF is this? This is a way to make these tests not depend so much on the
details of LOAD / EVAL . Around 1.0.57 we changed % SIMPLE - EVAL to be
;; slightly smarter, which meant that things which used to have xeps
;; suddently had tl-xeps, etc. This takes care of that.
`(funcall
(checked-compile
'(lambda ()
(progn
;; normal debug info
(defun ,(intern (format nil "BT.~A.1" n)) ,ll
,@body)
;; no arguments saved
(defun ,(intern (format nil "BT.~A.2" n)) ,ll
(declare (optimize (debug 1) (speed 3)))
,@body)
;; no lambda-list saved
(defun ,(intern (format nil "BT.~A.3" n)) ,ll
(declare (optimize (debug 0)))
,@body)))
:allow-style-warnings t)))
(defbt 1 (&key key)
(list key))
(defbt 2 (x)
(list x))
(defbt 3 (&key (key (oops)))
(list key))
;;; ERROR instead of OOPS so that tail call elimination doesn't happen
(defbt 4 (&optional opt)
(list (error "error")))
(defbt 5 (&optional (opt (oops)))
(list opt))
(defbt 6 (&optional (opt nil opt-p))
(declare (ignore opt))
(list (error "error ~A" opt-p))) ; use OPT-P
(defbt 7 (&key (key nil key-p))
(declare (ignore key))
(list (error "error ~A" key-p))) ; use KEY-P
(defun bug-354 (x)
(error "XEPs in backtraces: ~S" x))
(with-test (:name (:backtrace :bug-354))
(assert (not (verify-backtrace (lambda () (bug-354 354))
'((bug-354 354)
(((bug-354 &rest) (:tl :external)) 354)))))
(assert-backtrace (lambda () (bug-354 354)) '((bug-354 354))))
;;; FIXME: This test really should be broken into smaller pieces
(with-test (:name (:backtrace :tl-xep))
(assert-backtrace #'namestring '(((namestring) (:tl :external))) :details t)
(assert-backtrace #'namestring '((namestring))))
(with-test (:name (:backtrace :more-processor))
;; CHECKED-COMPILE avoids STYLE-WARNING noise.
(assert-backtrace (checked-compile '(lambda () (bt.1.1 :key))
:allow-style-warnings t)
'(((bt.1.1 :key) (:more :optional)))
:details t)
(assert-backtrace (checked-compile '(lambda () (bt.1.2 :key))
:allow-style-warnings t)
'(((bt.1.2 ?) (:more :optional)))
:details t)
(assert-backtrace (lambda () (bt.1.3 :key))
`(((bt.1.3 . ,*unavailable-lambda-list*) (:more :optional)))
:details t)
(assert-backtrace (checked-compile '(lambda () (bt.1.1 :key))
:allow-style-warnings t)
'((bt.1.1 :key)))
(assert-backtrace (checked-compile '(lambda () (bt.1.2 :key))
:allow-style-warnings t)
'((bt.1.2 &rest)))
(assert-backtrace (lambda () (bt.1.3 :key))
'((bt.1.3 &rest))))
(with-test (:name (:backtrace :xep))
(assert-backtrace #'bt.2.1 '(((bt.2.1) (:external))) :details t)
(assert-backtrace #'bt.2.2 '(((bt.2.2) (:external))) :details t)
(assert-backtrace #'bt.2.3 `(((bt.2.3) (:external))) :details t)
(assert-backtrace #'bt.2.1 '((bt.2.1)))
(assert-backtrace #'bt.2.2 '((bt.2.2)))
(assert-backtrace #'bt.2.3 `((bt.2.3))))
;;; This test is somewhat deceptively named. Due to confusion in debug
;;; naming these functions used to have sb-c::varargs-entry debug
;;; names for their main lambda.
(with-test (:name (:backtrace :varargs-entry))
(assert-backtrace #'bt.3.1 '((bt.3.1 :key nil)))
(assert-backtrace #'bt.3.2 '((bt.3.2 :key ?)))
(assert-backtrace #'bt.3.3 `((bt.3.3 . ,*unavailable-lambda-list*)))
(assert-backtrace #'bt.3.1 '((bt.3.1 :key nil)))
(assert-backtrace #'bt.3.2 '((bt.3.2 :key ?)))
(assert-backtrace #'bt.3.3 `((bt.3.3 . ,*unavailable-lambda-list*))))
;;; This test is somewhat deceptively named. Due to confusion in debug naming
;;; these functions used to have sb-c::hairy-args-processor debug names for
;;; their main lambda.
(with-test (:name (:backtrace :hairy-args-processor))
(assert-backtrace #'bt.4.1 '((bt.4.1 ?)))
(assert-backtrace #'bt.4.2 '((bt.4.2 ?)))
(assert-backtrace #'bt.4.3 `((bt.4.3 . ,*unavailable-lambda-list*)))
(assert-backtrace #'bt.4.1 '((bt.4.1 ?)))
(assert-backtrace #'bt.4.2 '((bt.4.2 ?)))
(assert-backtrace #'bt.4.3 `((bt.4.3 . ,*unavailable-lambda-list*))))
(with-test (:name (:backtrace :optional-processor))
(assert-backtrace #'bt.5.1 '(((bt.5.1) (:optional))) :details t)
(assert-backtrace #'bt.5.2 '(((bt.5.2) (:optional))) :details t)
(assert-backtrace #'bt.5.3 `(((bt.5.3 . ,*unavailable-lambda-list*) (:optional)))
:details t)
(assert-backtrace #'bt.5.1 '((bt.5.1)))
(assert-backtrace #'bt.5.2 '((bt.5.2)))
(assert-backtrace #'bt.5.3 `((bt.5.3 . ,*unavailable-lambda-list*))))
(with-test (:name (:backtrace :unused-optinoal-with-supplied-p :bug-1498644))
(assert-backtrace (lambda () (bt.6.1 :opt))
`(((bt.6.1 ,*unused-argument*) ()))
:details t)
(assert-backtrace (lambda () (bt.6.2 :opt))
`(((bt.6.2 ,*unused-argument*) ()))
:details t)
(assert-backtrace (lambda () (bt.6.3 :opt))
`(((bt.6.3 . ,*unavailable-lambda-list*) ()))
:details t)
(assert-backtrace (lambda () (bt.6.1 :opt))
`((bt.6.1 ,*unused-argument*)))
(assert-backtrace (lambda () (bt.6.2 :opt))
`((bt.6.2 ,*unused-argument*)))
(assert-backtrace (lambda () (bt.6.3 :opt))
`((bt.6.3 . ,*unavailable-lambda-list*))))
(with-test (:name (:backtrace :unused-key-with-supplied-p))
(assert-backtrace (lambda () (bt.7.1 :key :value))
`(((bt.7.1 :key ,*unused-argument*) ()))
:details t)
(assert-backtrace (lambda () (bt.7.2 :key :value))
`(((bt.7.2 :key ,*unused-argument*) ()))
:details t)
(assert-backtrace (lambda () (bt.7.3 :key :value))
`(((bt.7.3 . ,*unavailable-lambda-list*) ()))
:details t)
(assert-backtrace (lambda () (bt.7.1 :key :value))
`((bt.7.1 :key ,*unused-argument*)))
(assert-backtrace (lambda () (bt.7.2 :key :value))
`((bt.7.2 :key ,*unused-argument*)))
(assert-backtrace (lambda () (bt.7.3 :key :value))
`((bt.7.3 . ,*unavailable-lambda-list*))))
(defvar *compile-nil-error*
(checked-compile '(lambda (x)
(cons (when x (error "oops")) nil))))
(defvar *compile-nil-non-tc*
(checked-compile '(lambda (y)
(cons (funcall *compile-nil-error* y) nil))))
(with-test (:name (:backtrace compile nil))
(assert-backtrace (lambda () (funcall *compile-nil-non-tc* 13))
`(((lambda (x) :in ,*p*) 13)
((lambda (y) :in ,*p*) 13))))
(with-test (:name (:backtrace :clos-slot-typecheckfun-named))
(assert-backtrace
(checked-compile
`(lambda ()
(locally (declare (optimize safety))
(defclass clos-typecheck-test ()
((slot :type fixnum)))
(setf (slot-value (make-instance 'clos-typecheck-test) 'slot) t))))
'(((sb-pcl::slot-typecheck fixnum) t))))
(with-test (:name (:backtrace :clos-emf-named))
(assert-backtrace
(checked-compile
`(lambda ()
(progn
(defgeneric clos-emf-named-test (x)
(:method ((x symbol)) x)
(:method :before (x) (assert x)))
(clos-emf-named-test nil)))
:allow-style-warnings t)
'(((sb-pcl::emf clos-emf-named-test) ? ? nil))))
(with-test (:name (:backtrace :bug-310173))
(flet ((make-fun (n)
(let* ((names '(a b))
(req (loop repeat n collect (pop names))))
(checked-compile
`(lambda (,@req &rest rest)
(let ((* *)) ; no tail-call
(apply '/ ,@req rest)))))))
(assert-backtrace (lambda ()
(funcall (make-fun 0) 10 11 0))
`((sb-kernel:two-arg-/ 10/11 0)
(/ 10 11 0)
((lambda (&rest rest) :in ,*p*) 10 11 0)))
(assert-backtrace (lambda ()
(funcall (make-fun 1) 10 11 0))
`((sb-kernel:two-arg-/ 10/11 0)
(/ 10 11 0)
((lambda (a &rest rest) :in ,*p*) 10 11 0)))
(assert-backtrace (lambda ()
(funcall (make-fun 2) 10 11 0))
`((sb-kernel:two-arg-/ 10/11 0)
(/ 10 11 0)
((lambda (a b &rest rest) :in ,*p*) 10 11 0)))))
(defgeneric gf-dispatch-test/gf (x y)
(:method (x y)
(+ x y)))
(defun gf-dispatch-test/f (z)
(gf-dispatch-test/gf z))
(with-test (:name (:backtrace :gf-dispatch))
;; Fill the cache
(gf-dispatch-test/gf 1 1)
;; Wrong argument count
(assert-backtrace (lambda () (gf-dispatch-test/f 42))
'(((sb-pcl::gf-dispatch gf-dispatch-test/gf) 42))))
(with-test (:name (:backtrace :local-tail-call))
(assert-backtrace
(lambda () (funcall (compile nil `(sb-int:named-lambda test ()
(signal 'error)
(flet ((tail ()))
(declare (notinline tail))
(tail))))))
'((test))))
(defun fact (n) (if (zerop n) (error "nope") (* n (fact (1- n)))))
#+sb-fasteval
(with-test (:name (:backtrace :interpreted-factorial)
:skipped-on '(not :interpreter))
(assert-backtrace
(lambda () (fact 5))
'((fact 0)
(sb-interpreter::2-arg-* &rest)
(fact 1)
(sb-interpreter::2-arg-* &rest)
(fact 2)
(sb-interpreter::2-arg-* &rest)
(fact 3)
(sb-interpreter::2-arg-* &rest)
(fact 4)
(sb-interpreter::2-arg-* &rest)
(fact 5))))
| null | https://raw.githubusercontent.com/cracauer/sbcl-ita/f85a8cf0d1fb6e8c7b258e898b7af3233713e0b9/tests/backtrace.impure.lisp | lisp | This file is for testing backtraces, using test machinery which
more information.
files (like this one) were written from scratch after the fork
This software is in the public domain and is provided with
absolutely no warranty. See the COPYING and CREDITS files for
more information.
The following objects should be EQUALP to the respective markers
produced by the backtrace machinery.
TEST-FUNCTION is called and has to signal an error at which point
the backtrace will be captured.
If DETAILS is true, the returned backtrace description is of the
form:
...)
Otherwise it is of the form
...)
specifications EXPECTED signaling an error if they do not match.
If DETAILS is true, EXPECTED is a list with elements of the form
((FUNCTION ARGS) INFO)
Otherwise elements are of the form
(FUNCTION ARGS)
ARGS is a list of expected argument values, but can also contain
the following symbols
number of arguments starting at the corresponding
position.
argument at the corresponding position.
detailed~] check: wanted ~S, got ~
Check for backtraces generally being correct. Ensure that the
actual backtrace finishes (doesn't signal any errors on its own),
and that it contains the frames we expect, doesn't contain any
"bogus stack frame"s, and contains the appropriate toplevel call
and hasn't been cut off anywhere.
See CHECK-BACKTRACE for an explanation of the structure
EXPECTED-FRAMES.
Check that we have all the frames we wanted.
Make sure the backtrace isn't stunted in any way.
(Depends on running in the main thread.) FIXME: On Windows
Test for "undefined function" (undefined_tramp) working properly.
Try it with and without tail call elimination, since they can have
different effects. (Specifically, if undefined_tramp is incorrect
a stunted stack can result from the tail call variant.)
tail call elimination
no tail call elimination
no tail call elimination
not having a full and valid stack frame for the
undefined function frame. See PPC
undefined_tramp for details.
or more than MOST-POSITIVE-FIXNUM bytes ahead. It also depends on
Disabling tail call elimination on this will probably ensure that
the return value (to the flet or the enclosing top level form) is
more than MOST-POSITIVE-FIXNUM with the current spaces on OS X.
Enabling it might catch other problems, so do it anyway.
tail call elimination
no tail call elimination
no tail call elimination
Test backtrace through assembly routines
:bug-800343
make sure it's not in tail position
test entry point handling in backtraces
CHECKED-COMPILE avoids STYLE-WARNING noise.
WTF is this? This is a way to make these tests not depend so much on the
slightly smarter, which meant that things which used to have xeps
suddently had tl-xeps, etc. This takes care of that.
normal debug info
no arguments saved
no lambda-list saved
ERROR instead of OOPS so that tail call elimination doesn't happen
use OPT-P
use KEY-P
FIXME: This test really should be broken into smaller pieces
CHECKED-COMPILE avoids STYLE-WARNING noise.
This test is somewhat deceptively named. Due to confusion in debug
naming these functions used to have sb-c::varargs-entry debug
names for their main lambda.
This test is somewhat deceptively named. Due to confusion in debug naming
these functions used to have sb-c::hairy-args-processor debug names for
their main lambda.
no tail-call
Fill the cache
Wrong argument count | might have side effects ( e.g. executing DEFUN ) .
This software is part of the SBCL system . See the README file for
While most of SBCL is derived from the CMU CL system , the test
from CMU CL .
(cl:in-package :cl-user)
(defvar *unused-argument*
(sb-debug::make-unprintable-object "unused argument"))
(defvar *unavailable-argument*
(sb-debug::make-unprintable-object "unavailable argument"))
(defvar *unavailable-lambda-list*
(sb-debug::make-unprintable-object "unavailable lambda list"))
( ( ( NAME1 . ARGS1 ) INFO1 )
( ( NAME2 . ) INFO2 )
( ( NAME1 . ARGS1 )
( NAME2 . )
(defun call-with-backtrace (cont test-function &key details)
(flet ((capture-it (condition)
(let (backtrace)
(sb-debug::map-backtrace
(lambda (frame)
(multiple-value-bind (name args info)
(sb-debug::frame-call frame)
(push (if details
(list (cons name args) info)
(cons name args))
backtrace))))
(funcall cont (nreverse backtrace) condition))))
(handler-bind ((error #'capture-it))
(funcall test-function))))
Check the backtrace FRAMES against the list of frame
& REST The corresponding frame in FRAMES can contain an arbitrary
? The corresponding frame in FRAMES can have an arbitrary
(defun check-backtrace (frames expected &key details)
(labels ((args-equal (want actual)
(cond ((eq want *unavailable-lambda-list*)
(equalp want actual))
((eq '&rest (car want))
t)
((endp want)
(endp actual))
((or (eq '? (car want)) (equal (car want) (car actual)))
(args-equal (cdr want) (cdr actual)))
((typep (car want) 'sb-impl::unprintable-object)
(equalp (car want) (car actual)))
(t
nil)))
(fail (datum &rest arguments)
(return-from check-backtrace
(values nil (sb-kernel:coerce-to-condition
datum arguments 'simple-error 'error)))))
(mapc (lambda (frame spec)
(unless (cond
((not spec)
t)
(details
(and (args-equal (car spec)
(car frame))
(equal (cdr spec) (cdr frame))))
(t
(and (equal (car spec) (car frame))
(args-equal (cdr spec) (cdr frame)))))
(fail "~@<Unexpected frame during ~
~S~@:>"
details spec frame)))
frames expected))
t)
(defun verify-backtrace (test-function expected-frames &key details)
(labels ((find-frame (function-name frames)
(member function-name frames
:key (if details #'caar #'car)
:test #'equal))
(fail (datum &rest arguments)
(return-from verify-backtrace
(values nil (sb-kernel:coerce-to-condition
datum arguments 'simple-error 'error)))))
(call-with-backtrace
(lambda (backtrace condition)
(declare (ignore condition))
(let* ((test-function-name (if details
(caaar expected-frames)
(caar expected-frames)))
(frames (or (find-frame test-function-name backtrace)
(fail "~@<~S (expected name ~S) not found in ~
backtrace:~@:_~S~@:>"
test-function test-function-name backtrace))))
(multiple-value-bind (successp condition)
(check-backtrace frames expected-frames :details details)
(unless successp (fail condition)))
we get two extra foreign frames below regular frames .
(unless (find-frame 'sb-impl::toplevel-init frames)
(fail "~@<Backtrace stunted:~@:_~S~@:>" backtrace)))
(return-from verify-backtrace t))
test-function :details details)))
(defun assert-backtrace (test-function expected-frames &key details)
(multiple-value-bind (successp condition)
(verify-backtrace test-function expected-frames :details details)
(or successp (error condition))))
(defvar *p* (namestring *load-truename*))
(defvar *undefined-function-frame*
'("undefined function"))
(defun oops ()
(error "oops"))
(flet ((optimized ()
(#:undefined-function 42))
(not-optimized ()
(#:undefined-function 42))
(test (fun)
(funcall fun)))
(with-test (:name (:backtrace :undefined-function :bug-346)
:skipped-on :interpreter
Failures on SPARC , and probably HPPA are due to
:fails-on '(or :sparc))
(assert-backtrace
(lambda () (test #'optimized))
(list *undefined-function-frame*
(list `(flet test :in ,*p*) #'optimized))))
bug 353 : This test fails at least most of the time for x86 / linux
ca . 0.8.20.16 . -- WHN
(with-test (:name (:backtrace :undefined-function :bug-353)
:skipped-on :interpreter)
(assert-backtrace
(lambda () (test #'not-optimized))
(list *undefined-function-frame*
(list `(flet not-optimized :in ,*p*))
(list `(flet test :in ,*p*) #'not-optimized)))))
(with-test (:name (:backtrace :interrupted-condition-wait)
:skipped-on '(not :sb-thread))
(let ((m (sb-thread:make-mutex))
(q (sb-thread:make-waitqueue)))
(assert-backtrace
(lambda ()
(sb-thread:with-mutex (m)
(handler-bind ((timeout (lambda (condition)
(declare (ignore condition))
(error "foo"))))
(with-timeout 0.1
(sb-thread:condition-wait q m)))))
`((sb-thread:condition-wait ,q ,m :timeout nil)))))
Division by zero was a common error on PPC . It depended on the
return function either being before INTEGER-/-INTEGER in memory ,
INTEGER-/-INTEGER calling SIGNED - TRUNCATE . I believe
says that the Sparc backend ( at least for CMUCL ) inlines this , so
if SBCL does the same this test is probably not good for the
Sparc .
(flet ((optimized ()
(/ 42 0))
(not-optimized ()
(/ 42 0))
(test (fun)
(funcall fun)))
(with-test (:name (:backtrace :divide-by-zero :bug-346)
:skipped-on :interpreter)
(assert-backtrace (lambda () (test #'optimized))
`((/ 42 &rest)
((flet test :in ,*p*) ,#'optimized))))
(with-test (:name (:backtrace :divide-by-zero :bug-356)
:skipped-on :interpreter)
(assert-backtrace (lambda () (test #'not-optimized))
`((/ 42 &rest)
((flet not-optimized :in ,*p*))
((flet test :in ,*p*) ,#'not-optimized)))))
(defun throw-test ()
(throw 'no-such-tag t))
(with-test (:name (:backtrace :throw :no-such-tag)
:fails-on '(and :sparc :linux))
(assert-backtrace #'throw-test '((throw-test))))
(funcall (checked-compile
'(lambda ()
(defun bug-308926 (x)
(let ((v "foo"))
(flet ((bar (z)
(oops v z)
(oops z v)))
(bar x)
(bar v)))))
:allow-style-warnings t))
(with-test (:name (:backtrace :bug-308926) :skipped-on :interpreter)
(assert-backtrace (lambda () (bug-308926 13))
'(((flet bar :in bug-308926) 13)
(bug-308926 &rest t))))
(macrolet ((test (predicate fun
&optional (two-arg
(find-symbol (format nil "TWO-ARG-~A" fun)
"SB-KERNEL")))
(let ((test-name (make-symbol (format nil "TEST-~A" fun))))
`(flet ((,test-name (x y)
(list (,fun x y))))
(with-test (:name (:backtrace :bug-800343 ,fun)
:skipped-on :interpreter)
(assert-backtrace
(lambda ()
(eval `(funcall ,#',test-name 42 t)))
'((,two-arg 42 t)
#+(or x86 x86-64)
,@(and predicate
`((,(find-symbol (format nil "GENERIC-~A" fun) "SB-VM"))))
((flet ,test-name :in ,*p*) 42 t)))))))
(test-predicates (&rest functions)
`(progn ,@(mapcar (lambda (function)
`(test t ,@(sb-int:ensure-list function)))
functions)))
(test-functions (&rest functions)
`(progn ,@(mapcar (lambda (function)
`(test nil ,@(sb-int:ensure-list function)))
functions))))
(test-predicates = < >)
(test-functions + - * /
gcd lcm
(logand sb-kernel:two-arg-and)
(logior sb-kernel:two-arg-ior)
(logxor sb-kernel:two-arg-xor)))
(with-test (:name (:backtrace :xep-too-many-arguments)
:skipped-on :interpreter)
(assert-backtrace (checked-compile '(lambda () (oops 1 2 3 4 5 6))
:allow-style-warnings t)
'((oops ? ? ? ? ? ?))))
(defmacro defbt (n ll &body body)
details of LOAD / EVAL . Around 1.0.57 we changed % SIMPLE - EVAL to be
`(funcall
(checked-compile
'(lambda ()
(progn
(defun ,(intern (format nil "BT.~A.1" n)) ,ll
,@body)
(defun ,(intern (format nil "BT.~A.2" n)) ,ll
(declare (optimize (debug 1) (speed 3)))
,@body)
(defun ,(intern (format nil "BT.~A.3" n)) ,ll
(declare (optimize (debug 0)))
,@body)))
:allow-style-warnings t)))
(defbt 1 (&key key)
(list key))
(defbt 2 (x)
(list x))
(defbt 3 (&key (key (oops)))
(list key))
(defbt 4 (&optional opt)
(list (error "error")))
(defbt 5 (&optional (opt (oops)))
(list opt))
(defbt 6 (&optional (opt nil opt-p))
(declare (ignore opt))
(defbt 7 (&key (key nil key-p))
(declare (ignore key))
(defun bug-354 (x)
(error "XEPs in backtraces: ~S" x))
(with-test (:name (:backtrace :bug-354))
(assert (not (verify-backtrace (lambda () (bug-354 354))
'((bug-354 354)
(((bug-354 &rest) (:tl :external)) 354)))))
(assert-backtrace (lambda () (bug-354 354)) '((bug-354 354))))
(with-test (:name (:backtrace :tl-xep))
(assert-backtrace #'namestring '(((namestring) (:tl :external))) :details t)
(assert-backtrace #'namestring '((namestring))))
(with-test (:name (:backtrace :more-processor))
(assert-backtrace (checked-compile '(lambda () (bt.1.1 :key))
:allow-style-warnings t)
'(((bt.1.1 :key) (:more :optional)))
:details t)
(assert-backtrace (checked-compile '(lambda () (bt.1.2 :key))
:allow-style-warnings t)
'(((bt.1.2 ?) (:more :optional)))
:details t)
(assert-backtrace (lambda () (bt.1.3 :key))
`(((bt.1.3 . ,*unavailable-lambda-list*) (:more :optional)))
:details t)
(assert-backtrace (checked-compile '(lambda () (bt.1.1 :key))
:allow-style-warnings t)
'((bt.1.1 :key)))
(assert-backtrace (checked-compile '(lambda () (bt.1.2 :key))
:allow-style-warnings t)
'((bt.1.2 &rest)))
(assert-backtrace (lambda () (bt.1.3 :key))
'((bt.1.3 &rest))))
(with-test (:name (:backtrace :xep))
(assert-backtrace #'bt.2.1 '(((bt.2.1) (:external))) :details t)
(assert-backtrace #'bt.2.2 '(((bt.2.2) (:external))) :details t)
(assert-backtrace #'bt.2.3 `(((bt.2.3) (:external))) :details t)
(assert-backtrace #'bt.2.1 '((bt.2.1)))
(assert-backtrace #'bt.2.2 '((bt.2.2)))
(assert-backtrace #'bt.2.3 `((bt.2.3))))
(with-test (:name (:backtrace :varargs-entry))
(assert-backtrace #'bt.3.1 '((bt.3.1 :key nil)))
(assert-backtrace #'bt.3.2 '((bt.3.2 :key ?)))
(assert-backtrace #'bt.3.3 `((bt.3.3 . ,*unavailable-lambda-list*)))
(assert-backtrace #'bt.3.1 '((bt.3.1 :key nil)))
(assert-backtrace #'bt.3.2 '((bt.3.2 :key ?)))
(assert-backtrace #'bt.3.3 `((bt.3.3 . ,*unavailable-lambda-list*))))
(with-test (:name (:backtrace :hairy-args-processor))
(assert-backtrace #'bt.4.1 '((bt.4.1 ?)))
(assert-backtrace #'bt.4.2 '((bt.4.2 ?)))
(assert-backtrace #'bt.4.3 `((bt.4.3 . ,*unavailable-lambda-list*)))
(assert-backtrace #'bt.4.1 '((bt.4.1 ?)))
(assert-backtrace #'bt.4.2 '((bt.4.2 ?)))
(assert-backtrace #'bt.4.3 `((bt.4.3 . ,*unavailable-lambda-list*))))
(with-test (:name (:backtrace :optional-processor))
(assert-backtrace #'bt.5.1 '(((bt.5.1) (:optional))) :details t)
(assert-backtrace #'bt.5.2 '(((bt.5.2) (:optional))) :details t)
(assert-backtrace #'bt.5.3 `(((bt.5.3 . ,*unavailable-lambda-list*) (:optional)))
:details t)
(assert-backtrace #'bt.5.1 '((bt.5.1)))
(assert-backtrace #'bt.5.2 '((bt.5.2)))
(assert-backtrace #'bt.5.3 `((bt.5.3 . ,*unavailable-lambda-list*))))
(with-test (:name (:backtrace :unused-optinoal-with-supplied-p :bug-1498644))
(assert-backtrace (lambda () (bt.6.1 :opt))
`(((bt.6.1 ,*unused-argument*) ()))
:details t)
(assert-backtrace (lambda () (bt.6.2 :opt))
`(((bt.6.2 ,*unused-argument*) ()))
:details t)
(assert-backtrace (lambda () (bt.6.3 :opt))
`(((bt.6.3 . ,*unavailable-lambda-list*) ()))
:details t)
(assert-backtrace (lambda () (bt.6.1 :opt))
`((bt.6.1 ,*unused-argument*)))
(assert-backtrace (lambda () (bt.6.2 :opt))
`((bt.6.2 ,*unused-argument*)))
(assert-backtrace (lambda () (bt.6.3 :opt))
`((bt.6.3 . ,*unavailable-lambda-list*))))
(with-test (:name (:backtrace :unused-key-with-supplied-p))
(assert-backtrace (lambda () (bt.7.1 :key :value))
`(((bt.7.1 :key ,*unused-argument*) ()))
:details t)
(assert-backtrace (lambda () (bt.7.2 :key :value))
`(((bt.7.2 :key ,*unused-argument*) ()))
:details t)
(assert-backtrace (lambda () (bt.7.3 :key :value))
`(((bt.7.3 . ,*unavailable-lambda-list*) ()))
:details t)
(assert-backtrace (lambda () (bt.7.1 :key :value))
`((bt.7.1 :key ,*unused-argument*)))
(assert-backtrace (lambda () (bt.7.2 :key :value))
`((bt.7.2 :key ,*unused-argument*)))
(assert-backtrace (lambda () (bt.7.3 :key :value))
`((bt.7.3 . ,*unavailable-lambda-list*))))
(defvar *compile-nil-error*
(checked-compile '(lambda (x)
(cons (when x (error "oops")) nil))))
(defvar *compile-nil-non-tc*
(checked-compile '(lambda (y)
(cons (funcall *compile-nil-error* y) nil))))
(with-test (:name (:backtrace compile nil))
(assert-backtrace (lambda () (funcall *compile-nil-non-tc* 13))
`(((lambda (x) :in ,*p*) 13)
((lambda (y) :in ,*p*) 13))))
(with-test (:name (:backtrace :clos-slot-typecheckfun-named))
(assert-backtrace
(checked-compile
`(lambda ()
(locally (declare (optimize safety))
(defclass clos-typecheck-test ()
((slot :type fixnum)))
(setf (slot-value (make-instance 'clos-typecheck-test) 'slot) t))))
'(((sb-pcl::slot-typecheck fixnum) t))))
(with-test (:name (:backtrace :clos-emf-named))
(assert-backtrace
(checked-compile
`(lambda ()
(progn
(defgeneric clos-emf-named-test (x)
(:method ((x symbol)) x)
(:method :before (x) (assert x)))
(clos-emf-named-test nil)))
:allow-style-warnings t)
'(((sb-pcl::emf clos-emf-named-test) ? ? nil))))
(with-test (:name (:backtrace :bug-310173))
(flet ((make-fun (n)
(let* ((names '(a b))
(req (loop repeat n collect (pop names))))
(checked-compile
`(lambda (,@req &rest rest)
(apply '/ ,@req rest)))))))
(assert-backtrace (lambda ()
(funcall (make-fun 0) 10 11 0))
`((sb-kernel:two-arg-/ 10/11 0)
(/ 10 11 0)
((lambda (&rest rest) :in ,*p*) 10 11 0)))
(assert-backtrace (lambda ()
(funcall (make-fun 1) 10 11 0))
`((sb-kernel:two-arg-/ 10/11 0)
(/ 10 11 0)
((lambda (a &rest rest) :in ,*p*) 10 11 0)))
(assert-backtrace (lambda ()
(funcall (make-fun 2) 10 11 0))
`((sb-kernel:two-arg-/ 10/11 0)
(/ 10 11 0)
((lambda (a b &rest rest) :in ,*p*) 10 11 0)))))
(defgeneric gf-dispatch-test/gf (x y)
(:method (x y)
(+ x y)))
(defun gf-dispatch-test/f (z)
(gf-dispatch-test/gf z))
(with-test (:name (:backtrace :gf-dispatch))
(gf-dispatch-test/gf 1 1)
(assert-backtrace (lambda () (gf-dispatch-test/f 42))
'(((sb-pcl::gf-dispatch gf-dispatch-test/gf) 42))))
(with-test (:name (:backtrace :local-tail-call))
(assert-backtrace
(lambda () (funcall (compile nil `(sb-int:named-lambda test ()
(signal 'error)
(flet ((tail ()))
(declare (notinline tail))
(tail))))))
'((test))))
(defun fact (n) (if (zerop n) (error "nope") (* n (fact (1- n)))))
#+sb-fasteval
(with-test (:name (:backtrace :interpreted-factorial)
:skipped-on '(not :interpreter))
(assert-backtrace
(lambda () (fact 5))
'((fact 0)
(sb-interpreter::2-arg-* &rest)
(fact 1)
(sb-interpreter::2-arg-* &rest)
(fact 2)
(sb-interpreter::2-arg-* &rest)
(fact 3)
(sb-interpreter::2-arg-* &rest)
(fact 4)
(sb-interpreter::2-arg-* &rest)
(fact 5))))
|
a8d36b7a3063c8bcf3ce097bfd72357f718d1b909eebeddb92412e9478ff9cef | ocaml-multicore/eio | sched.ml |
* Copyright ( C ) 2023
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (C) 2023 Thomas Leonard
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module Suspended = Eio_utils.Suspended
module Zzz = Eio_utils.Zzz
module Lf_queue = Eio_utils.Lf_queue
module Fiber_context = Eio.Private.Fiber_context
module Ctf = Eio.Private.Ctf
module Rcfd = Eio_unix.Private.Rcfd
module Poll = Iomux.Poll
type exit = [`Exit_scheduler]
let system_thread = Ctf.mint_id ()
(* The type of items in the run queue. *)
type runnable =
Reminder to check for IO
| Thread : 'a Suspended.t * 'a -> runnable (* Resume a fiber with a result value *)
| Failed_thread : 'a Suspended.t * exn -> runnable (* Resume a fiber with an exception *)
For each FD we track which fibers are waiting for it to become readable / writeable .
type fd_event_waiters = {
read : unit Suspended.t Lwt_dllist.t;
write : unit Suspended.t Lwt_dllist.t;
}
type t = {
(* The queue of runnable fibers ready to be resumed. Note: other domains can also add work items here. *)
run_q : runnable Lf_queue.t;
poll : Poll.t;
mutable poll_maxi : int; (* The highest index ever used in [poll]. *)
fd_map : (Unix.file_descr, fd_event_waiters) Hashtbl.t;
(* When adding to [run_q] from another domain, this domain may be sleeping and so won't see the event.
In that case, [need_wakeup = true] and you must signal using [eventfd]. *)
eventfd : Rcfd.t; (* For sending events. *)
eventfd_r : Unix.file_descr; (* For reading events. *)
Exit when this is zero and [ run_q ] and [ sleep_q ] are empty .
(* If [false], the main thread will check [run_q] before sleeping again
(possibly because an event has been or will be sent to [eventfd]).
It can therefore be set to [false] in either of these cases:
- By the receiving thread because it will check [run_q] before sleeping, or
- By the sending thread because it will signal the main thread later *)
need_wakeup : bool Atomic.t;
sleep_q: Zzz.t; (* Fibers waiting for timers. *)
}
(* The message to send to [eventfd] (any character would do). *)
let wake_buffer = Bytes.of_string "!"
This can be called from any systhread ( including ones not running Eio ) ,
and also from signal handlers or GC finalizers . It must not take any locks .
and also from signal handlers or GC finalizers. It must not take any locks. *)
let wakeup t =
Atomic.set t.need_wakeup false; (* [t] will check [run_q] after getting the event below *)
Rcfd.use t.eventfd
~if_closed:ignore (* Domain has shut down (presumably after handling the event) *)
(fun fd ->
(* This can fail if the pipe is full, but then a wake up is pending anyway. *)
ignore (Unix.single_write fd wake_buffer 0 1 : int);
)
Safe to call from anywhere ( other systhreads , domains , signal handlers , GC finalizers )
let enqueue_thread t k x =
Lf_queue.push t.run_q (Thread (k, x));
if Atomic.get t.need_wakeup then wakeup t
Safe to call from anywhere ( other systhreads , domains , signal handlers , GC finalizers )
let enqueue_failed_thread t k ex =
Lf_queue.push t.run_q (Failed_thread (k, ex));
if Atomic.get t.need_wakeup then wakeup t
Can only be called from our own domain , so no need to check for wakeup .
let enqueue_at_head t k =
Lf_queue.push_head t.run_q (Thread (k, ()))
let get_waiters t fd =
match Hashtbl.find_opt t.fd_map fd with
| Some x -> x
| None ->
let x = { read = Lwt_dllist.create (); write = Lwt_dllist.create () } in
Hashtbl.add t.fd_map fd x;
x
(* The OS told us that the event pipe is ready. Remove events. *)
let clear_event_fd t =
Read up to 8 events at a time
let got = Unix.read t.eventfd_r buf 0 (Bytes.length buf) in
assert (got > 0)
(* Update [t.poll]'s entry for [fd] to match [waiters]. *)
let update t waiters fd =
let fdi = Iomux.Util.fd_of_unix fd in
let flags =
match not (Lwt_dllist.is_empty waiters.read),
not (Lwt_dllist.is_empty waiters.write) with
| false, false -> Poll.Flags.empty
| true, false -> Poll.Flags.pollin
| false, true -> Poll.Flags.pollout
| true, true -> Poll.Flags.(pollin + pollout)
in
if flags = Poll.Flags.empty then (
Poll.invalidate_index t.poll fdi;
(* Try to find the new maxi, go back on index until we find the next
used slot, -1 means none in use. *)
let rec lower_maxi = function
| -1 -> t.poll_maxi <- -1
| index ->
if Poll.((get_fd t.poll index) <> invalid_fd) then
t.poll_maxi <- index
else
lower_maxi (pred index)
in
if fdi = t.poll_maxi then
lower_maxi (pred fdi);
Hashtbl.remove t.fd_map fd
) else (
Poll.set_index t.poll fdi fd flags;
if fdi > t.poll_maxi then
t.poll_maxi <- fdi
)
let resume t node =
t.active_ops <- t.active_ops - 1;
let k : unit Suspended.t = Lwt_dllist.get node in
Fiber_context.clear_cancel_fn k.fiber;
enqueue_thread t k ()
(* Called when poll indicates that an event we requested for [fd] is ready. *)
let ready t _index fd revents =
if fd == t.eventfd_r then (
clear_event_fd t
(* The scheduler will now look at the run queue again and notice any new items. *)
) else (
let waiters = Hashtbl.find t.fd_map fd in
let pending = Lwt_dllist.create () in
if Poll.Flags.(mem revents (pollout + pollhup + pollerr)) then
Lwt_dllist.transfer_l waiters.write pending;
if Poll.Flags.(mem revents (pollin + pollhup + pollerr)) then
Lwt_dllist.transfer_l waiters.read pending;
(* If pending has things, it means we modified the waiters, refresh our view *)
if not (Lwt_dllist.is_empty pending) then
update t waiters fd;
Lwt_dllist.iter_node_r (resume t) pending
)
Switch control to the next ready continuation .
If none is ready , wait until we get an event to wake one and then switch .
Returns only if there is nothing to do and no active operations .
If none is ready, wait until we get an event to wake one and then switch.
Returns only if there is nothing to do and no active operations. *)
let rec next t : [`Exit_scheduler] =
Wakeup any paused fibers
match Lf_queue.pop t.run_q with
| None -> assert false (* We should always have an IO job, at least *)
| Some Thread (k, v) -> (* We already have a runnable task *)
Fiber_context.clear_cancel_fn k.fiber;
Suspended.continue k v
| Some Failed_thread (k, ex) ->
Fiber_context.clear_cancel_fn k.fiber;
Suspended.discontinue k ex
Note : be sure to re - inject the IO task before continuing !
(* This is not a fair scheduler: timers always run before all other IO *)
let now = Mtime_clock.now () in
match Zzz.pop ~now t.sleep_q with
| `Due k ->
Re - inject IO job in the run queue
Suspended.continue k () (* A sleeping task is now due *)
| `Wait_until _ | `Nothing as next_due ->
let timeout =
match next_due with
| `Wait_until time ->
let time = Mtime.to_uint64_ns time in
let now = Mtime.to_uint64_ns now in
let diff_ns = Int64.sub time now in
Poll.Nanoseconds diff_ns
| `Nothing -> Poll.Infinite
in
if timeout = Infinite && t.active_ops = 0 then (
(* Nothing further can happen at this point. *)
Lf_queue.close t.run_q; (* Just to catch bugs if something tries to enqueue later *)
`Exit_scheduler
) else (
Atomic.set t.need_wakeup true;
if Lf_queue.is_empty t.run_q then (
(* At this point we're not going to check [run_q] again before sleeping.
If [need_wakeup] is still [true], this is fine because we don't promise to do that.
If [need_wakeup = false], a wake-up event will arrive and wake us up soon. *)
Ctf.(note_hiatus Wait_for_work);
let nready =
try Poll.ppoll_or_poll t.poll (t.poll_maxi + 1) timeout
with Unix.Unix_error (Unix.EINTR, _, "") -> 0
in
Ctf.note_resume system_thread;
Atomic.set t.need_wakeup false;
Re - inject IO job in the run queue
Poll.iter_ready t.poll nready (ready t);
next t
) else (
(* Someone added a new job while we were setting [need_wakeup] to [true].
They might or might not have seen that, so we can't be sure they'll send an event. *)
Atomic.set t.need_wakeup false;
Re - inject IO job in the run queue
next t
)
)
let with_sched fn =
let run_q = Lf_queue.create () in
Lf_queue.push run_q IO;
let sleep_q = Zzz.create () in
let eventfd_r, eventfd_w = Unix.pipe ~cloexec:true () in
Unix.set_nonblock eventfd_r;
Unix.set_nonblock eventfd_w;
let eventfd = Rcfd.make eventfd_w in
let cleanup () =
Unix.close eventfd_r;
let was_open = Rcfd.close eventfd in
assert was_open
in
let poll = Poll.create () in
let fd_map = Hashtbl.create 10 in
let t = { run_q; poll; poll_maxi = (-1); fd_map; eventfd; eventfd_r;
active_ops = 0; need_wakeup = Atomic.make false; sleep_q } in
let eventfd_ri = Iomux.Util.fd_of_unix eventfd_r in
Poll.set_index t.poll eventfd_ri eventfd_r Poll.Flags.pollin;
if eventfd_ri > t.poll_maxi then
t.poll_maxi <- eventfd_ri;
match fn t with
| x -> cleanup (); x
| exception ex ->
let bt = Printexc.get_raw_backtrace () in
cleanup ();
Printexc.raise_with_backtrace ex bt
let await_readable t (k : unit Suspended.t) fd =
match Fiber_context.get_error k.fiber with
| Some e -> Suspended.discontinue k e
| None ->
t.active_ops <- t.active_ops + 1;
let waiters = get_waiters t fd in
let was_empty = Lwt_dllist.is_empty waiters.read in
let node = Lwt_dllist.add_l k waiters.read in
if was_empty then update t waiters fd;
Fiber_context.set_cancel_fn k.fiber (fun ex ->
Lwt_dllist.remove node;
t.active_ops <- t.active_ops - 1;
enqueue_failed_thread t k ex
);
next t
let await_writable t (k : unit Suspended.t) fd =
match Fiber_context.get_error k.fiber with
| Some e -> Suspended.discontinue k e
| None ->
t.active_ops <- t.active_ops + 1;
let waiters = get_waiters t fd in
let was_empty = Lwt_dllist.is_empty waiters.write in
let node = Lwt_dllist.add_l k waiters.write in
if was_empty then update t waiters fd;
Fiber_context.set_cancel_fn k.fiber (fun ex ->
Lwt_dllist.remove node;
t.active_ops <- t.active_ops - 1;
enqueue_failed_thread t k ex
);
next t
let get_enqueue t k = function
| Ok v -> enqueue_thread t k v
| Error ex -> enqueue_failed_thread t k ex
let await_timeout t (k : unit Suspended.t) time =
match Fiber_context.get_error k.fiber with
| Some e -> Suspended.discontinue k e
| None ->
let node = Zzz.add t.sleep_q time k in
Fiber_context.set_cancel_fn k.fiber (fun ex ->
Zzz.remove t.sleep_q node;
enqueue_failed_thread t k ex
);
next t
let with_op t fn x =
t.active_ops <- t.active_ops + 1;
match fn x with
| r ->
t.active_ops <- t.active_ops - 1;
r
| exception ex ->
t.active_ops <- t.active_ops - 1;
raise ex
[@@@alert "-unstable"]
type _ Effect.t += Enter : (t -> 'a Eio_utils.Suspended.t -> [`Exit_scheduler]) -> 'a Effect.t
let enter fn = Effect.perform (Enter fn)
let run ~extra_effects t main x =
let rec fork ~new_fiber:fiber fn =
let open Effect.Deep in
Ctf.note_switch (Fiber_context.tid fiber);
match_with fn ()
{ retc = (fun () -> Fiber_context.destroy fiber; next t);
exnc = (fun ex ->
Fiber_context.destroy fiber;
Printexc.raise_with_backtrace ex (Printexc.get_raw_backtrace ())
);
effc = fun (type a) (e : a Effect.t) ->
match e with
| Enter fn -> Some (fun k ->
match Fiber_context.get_error fiber with
| Some e -> discontinue k e
| None -> fn t { Suspended.k; fiber }
)
| Eio.Private.Effects.Get_context -> Some (fun k -> continue k fiber)
| Eio.Private.Effects.Suspend f -> Some (fun k ->
let k = { Suspended.k; fiber } in
let enqueue = get_enqueue t k in
f fiber enqueue;
next t
)
| Eio.Private.Effects.Fork (new_fiber, f) -> Some (fun k ->
let k = { Suspended.k; fiber } in
enqueue_at_head t k;
fork ~new_fiber f
)
| Eio_unix.Private.Await_readable fd -> Some (fun k ->
await_readable t { Suspended.k; fiber } fd
)
| Eio_unix.Private.Await_writable fd -> Some (fun k ->
await_writable t { Suspended.k; fiber } fd
)
| e -> extra_effects.Effect.Deep.effc e
}
in
let result = ref None in
let `Exit_scheduler =
let new_fiber = Fiber_context.make_root () in
fork ~new_fiber (fun () ->
result := Some (with_op t main x);
)
in
match !result with
| Some x -> x
| None -> failwith "BUG in scheduler: deadlock detected"
| null | https://raw.githubusercontent.com/ocaml-multicore/eio/146d246f233fcf9b9d78b939da8e050c72d7be1c/lib_eio_posix/sched.ml | ocaml | The type of items in the run queue.
Resume a fiber with a result value
Resume a fiber with an exception
The queue of runnable fibers ready to be resumed. Note: other domains can also add work items here.
The highest index ever used in [poll].
When adding to [run_q] from another domain, this domain may be sleeping and so won't see the event.
In that case, [need_wakeup = true] and you must signal using [eventfd].
For sending events.
For reading events.
If [false], the main thread will check [run_q] before sleeping again
(possibly because an event has been or will be sent to [eventfd]).
It can therefore be set to [false] in either of these cases:
- By the receiving thread because it will check [run_q] before sleeping, or
- By the sending thread because it will signal the main thread later
Fibers waiting for timers.
The message to send to [eventfd] (any character would do).
[t] will check [run_q] after getting the event below
Domain has shut down (presumably after handling the event)
This can fail if the pipe is full, but then a wake up is pending anyway.
The OS told us that the event pipe is ready. Remove events.
Update [t.poll]'s entry for [fd] to match [waiters].
Try to find the new maxi, go back on index until we find the next
used slot, -1 means none in use.
Called when poll indicates that an event we requested for [fd] is ready.
The scheduler will now look at the run queue again and notice any new items.
If pending has things, it means we modified the waiters, refresh our view
We should always have an IO job, at least
We already have a runnable task
This is not a fair scheduler: timers always run before all other IO
A sleeping task is now due
Nothing further can happen at this point.
Just to catch bugs if something tries to enqueue later
At this point we're not going to check [run_q] again before sleeping.
If [need_wakeup] is still [true], this is fine because we don't promise to do that.
If [need_wakeup = false], a wake-up event will arrive and wake us up soon.
Someone added a new job while we were setting [need_wakeup] to [true].
They might or might not have seen that, so we can't be sure they'll send an event. |
* Copyright ( C ) 2023
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (C) 2023 Thomas Leonard
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module Suspended = Eio_utils.Suspended
module Zzz = Eio_utils.Zzz
module Lf_queue = Eio_utils.Lf_queue
module Fiber_context = Eio.Private.Fiber_context
module Ctf = Eio.Private.Ctf
module Rcfd = Eio_unix.Private.Rcfd
module Poll = Iomux.Poll
type exit = [`Exit_scheduler]
let system_thread = Ctf.mint_id ()
type runnable =
Reminder to check for IO
For each FD we track which fibers are waiting for it to become readable / writeable .
type fd_event_waiters = {
read : unit Suspended.t Lwt_dllist.t;
write : unit Suspended.t Lwt_dllist.t;
}
type t = {
run_q : runnable Lf_queue.t;
poll : Poll.t;
fd_map : (Unix.file_descr, fd_event_waiters) Hashtbl.t;
Exit when this is zero and [ run_q ] and [ sleep_q ] are empty .
need_wakeup : bool Atomic.t;
}
let wake_buffer = Bytes.of_string "!"
This can be called from any systhread ( including ones not running Eio ) ,
and also from signal handlers or GC finalizers . It must not take any locks .
and also from signal handlers or GC finalizers. It must not take any locks. *)
let wakeup t =
Rcfd.use t.eventfd
(fun fd ->
ignore (Unix.single_write fd wake_buffer 0 1 : int);
)
Safe to call from anywhere ( other systhreads , domains , signal handlers , GC finalizers )
let enqueue_thread t k x =
Lf_queue.push t.run_q (Thread (k, x));
if Atomic.get t.need_wakeup then wakeup t
Safe to call from anywhere ( other systhreads , domains , signal handlers , GC finalizers )
let enqueue_failed_thread t k ex =
Lf_queue.push t.run_q (Failed_thread (k, ex));
if Atomic.get t.need_wakeup then wakeup t
Can only be called from our own domain , so no need to check for wakeup .
let enqueue_at_head t k =
Lf_queue.push_head t.run_q (Thread (k, ()))
let get_waiters t fd =
match Hashtbl.find_opt t.fd_map fd with
| Some x -> x
| None ->
let x = { read = Lwt_dllist.create (); write = Lwt_dllist.create () } in
Hashtbl.add t.fd_map fd x;
x
let clear_event_fd t =
Read up to 8 events at a time
let got = Unix.read t.eventfd_r buf 0 (Bytes.length buf) in
assert (got > 0)
let update t waiters fd =
let fdi = Iomux.Util.fd_of_unix fd in
let flags =
match not (Lwt_dllist.is_empty waiters.read),
not (Lwt_dllist.is_empty waiters.write) with
| false, false -> Poll.Flags.empty
| true, false -> Poll.Flags.pollin
| false, true -> Poll.Flags.pollout
| true, true -> Poll.Flags.(pollin + pollout)
in
if flags = Poll.Flags.empty then (
Poll.invalidate_index t.poll fdi;
let rec lower_maxi = function
| -1 -> t.poll_maxi <- -1
| index ->
if Poll.((get_fd t.poll index) <> invalid_fd) then
t.poll_maxi <- index
else
lower_maxi (pred index)
in
if fdi = t.poll_maxi then
lower_maxi (pred fdi);
Hashtbl.remove t.fd_map fd
) else (
Poll.set_index t.poll fdi fd flags;
if fdi > t.poll_maxi then
t.poll_maxi <- fdi
)
let resume t node =
t.active_ops <- t.active_ops - 1;
let k : unit Suspended.t = Lwt_dllist.get node in
Fiber_context.clear_cancel_fn k.fiber;
enqueue_thread t k ()
let ready t _index fd revents =
if fd == t.eventfd_r then (
clear_event_fd t
) else (
let waiters = Hashtbl.find t.fd_map fd in
let pending = Lwt_dllist.create () in
if Poll.Flags.(mem revents (pollout + pollhup + pollerr)) then
Lwt_dllist.transfer_l waiters.write pending;
if Poll.Flags.(mem revents (pollin + pollhup + pollerr)) then
Lwt_dllist.transfer_l waiters.read pending;
if not (Lwt_dllist.is_empty pending) then
update t waiters fd;
Lwt_dllist.iter_node_r (resume t) pending
)
Switch control to the next ready continuation .
If none is ready , wait until we get an event to wake one and then switch .
Returns only if there is nothing to do and no active operations .
If none is ready, wait until we get an event to wake one and then switch.
Returns only if there is nothing to do and no active operations. *)
let rec next t : [`Exit_scheduler] =
Wakeup any paused fibers
match Lf_queue.pop t.run_q with
Fiber_context.clear_cancel_fn k.fiber;
Suspended.continue k v
| Some Failed_thread (k, ex) ->
Fiber_context.clear_cancel_fn k.fiber;
Suspended.discontinue k ex
Note : be sure to re - inject the IO task before continuing !
let now = Mtime_clock.now () in
match Zzz.pop ~now t.sleep_q with
| `Due k ->
Re - inject IO job in the run queue
| `Wait_until _ | `Nothing as next_due ->
let timeout =
match next_due with
| `Wait_until time ->
let time = Mtime.to_uint64_ns time in
let now = Mtime.to_uint64_ns now in
let diff_ns = Int64.sub time now in
Poll.Nanoseconds diff_ns
| `Nothing -> Poll.Infinite
in
if timeout = Infinite && t.active_ops = 0 then (
`Exit_scheduler
) else (
Atomic.set t.need_wakeup true;
if Lf_queue.is_empty t.run_q then (
Ctf.(note_hiatus Wait_for_work);
let nready =
try Poll.ppoll_or_poll t.poll (t.poll_maxi + 1) timeout
with Unix.Unix_error (Unix.EINTR, _, "") -> 0
in
Ctf.note_resume system_thread;
Atomic.set t.need_wakeup false;
Re - inject IO job in the run queue
Poll.iter_ready t.poll nready (ready t);
next t
) else (
Atomic.set t.need_wakeup false;
Re - inject IO job in the run queue
next t
)
)
let with_sched fn =
let run_q = Lf_queue.create () in
Lf_queue.push run_q IO;
let sleep_q = Zzz.create () in
let eventfd_r, eventfd_w = Unix.pipe ~cloexec:true () in
Unix.set_nonblock eventfd_r;
Unix.set_nonblock eventfd_w;
let eventfd = Rcfd.make eventfd_w in
let cleanup () =
Unix.close eventfd_r;
let was_open = Rcfd.close eventfd in
assert was_open
in
let poll = Poll.create () in
let fd_map = Hashtbl.create 10 in
let t = { run_q; poll; poll_maxi = (-1); fd_map; eventfd; eventfd_r;
active_ops = 0; need_wakeup = Atomic.make false; sleep_q } in
let eventfd_ri = Iomux.Util.fd_of_unix eventfd_r in
Poll.set_index t.poll eventfd_ri eventfd_r Poll.Flags.pollin;
if eventfd_ri > t.poll_maxi then
t.poll_maxi <- eventfd_ri;
match fn t with
| x -> cleanup (); x
| exception ex ->
let bt = Printexc.get_raw_backtrace () in
cleanup ();
Printexc.raise_with_backtrace ex bt
let await_readable t (k : unit Suspended.t) fd =
match Fiber_context.get_error k.fiber with
| Some e -> Suspended.discontinue k e
| None ->
t.active_ops <- t.active_ops + 1;
let waiters = get_waiters t fd in
let was_empty = Lwt_dllist.is_empty waiters.read in
let node = Lwt_dllist.add_l k waiters.read in
if was_empty then update t waiters fd;
Fiber_context.set_cancel_fn k.fiber (fun ex ->
Lwt_dllist.remove node;
t.active_ops <- t.active_ops - 1;
enqueue_failed_thread t k ex
);
next t
let await_writable t (k : unit Suspended.t) fd =
match Fiber_context.get_error k.fiber with
| Some e -> Suspended.discontinue k e
| None ->
t.active_ops <- t.active_ops + 1;
let waiters = get_waiters t fd in
let was_empty = Lwt_dllist.is_empty waiters.write in
let node = Lwt_dllist.add_l k waiters.write in
if was_empty then update t waiters fd;
Fiber_context.set_cancel_fn k.fiber (fun ex ->
Lwt_dllist.remove node;
t.active_ops <- t.active_ops - 1;
enqueue_failed_thread t k ex
);
next t
let get_enqueue t k = function
| Ok v -> enqueue_thread t k v
| Error ex -> enqueue_failed_thread t k ex
let await_timeout t (k : unit Suspended.t) time =
match Fiber_context.get_error k.fiber with
| Some e -> Suspended.discontinue k e
| None ->
let node = Zzz.add t.sleep_q time k in
Fiber_context.set_cancel_fn k.fiber (fun ex ->
Zzz.remove t.sleep_q node;
enqueue_failed_thread t k ex
);
next t
let with_op t fn x =
t.active_ops <- t.active_ops + 1;
match fn x with
| r ->
t.active_ops <- t.active_ops - 1;
r
| exception ex ->
t.active_ops <- t.active_ops - 1;
raise ex
[@@@alert "-unstable"]
type _ Effect.t += Enter : (t -> 'a Eio_utils.Suspended.t -> [`Exit_scheduler]) -> 'a Effect.t
let enter fn = Effect.perform (Enter fn)
let run ~extra_effects t main x =
let rec fork ~new_fiber:fiber fn =
let open Effect.Deep in
Ctf.note_switch (Fiber_context.tid fiber);
match_with fn ()
{ retc = (fun () -> Fiber_context.destroy fiber; next t);
exnc = (fun ex ->
Fiber_context.destroy fiber;
Printexc.raise_with_backtrace ex (Printexc.get_raw_backtrace ())
);
effc = fun (type a) (e : a Effect.t) ->
match e with
| Enter fn -> Some (fun k ->
match Fiber_context.get_error fiber with
| Some e -> discontinue k e
| None -> fn t { Suspended.k; fiber }
)
| Eio.Private.Effects.Get_context -> Some (fun k -> continue k fiber)
| Eio.Private.Effects.Suspend f -> Some (fun k ->
let k = { Suspended.k; fiber } in
let enqueue = get_enqueue t k in
f fiber enqueue;
next t
)
| Eio.Private.Effects.Fork (new_fiber, f) -> Some (fun k ->
let k = { Suspended.k; fiber } in
enqueue_at_head t k;
fork ~new_fiber f
)
| Eio_unix.Private.Await_readable fd -> Some (fun k ->
await_readable t { Suspended.k; fiber } fd
)
| Eio_unix.Private.Await_writable fd -> Some (fun k ->
await_writable t { Suspended.k; fiber } fd
)
| e -> extra_effects.Effect.Deep.effc e
}
in
let result = ref None in
let `Exit_scheduler =
let new_fiber = Fiber_context.make_root () in
fork ~new_fiber (fun () ->
result := Some (with_op t main x);
)
in
match !result with
| Some x -> x
| None -> failwith "BUG in scheduler: deadlock detected"
|
13b7b638d2aed6a952e98edb24045822d59726d3c742cf88b7a46abbbcc3139d | gonimo/gonimo | Internal.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecursiveDo #-}
# LANGUAGE ScopedTypeVariables #
module Gonimo.Client.Invite.Internal where
import Control.Lens
import Control.Monad
import Control.Monad.Fix (MonadFix)
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy as BL
import Data.Default (Default (..))
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text.Encoding as T
import Language.Javascript.JSaddle
import Network.HTTP.Types (urlEncode)
import Reflex.Dom.Core
import qualified Gonimo.Client.Environment as Env
import qualified Gonimo.SocketAPI as API
import Gonimo.SocketAPI.Types (FamilyId, InvitationId)
import qualified Gonimo.SocketAPI.Types as API
invitationQueryParam :: Text
invitationQueryParam = "acceptInvitation"
data Config t
= Config { _configResponse :: Event t API.ServerResponse
, _configSelectedFamily :: Dynamic t FamilyId
, _configAuthenticated :: Event t ()
, _configCreateInvitation :: Event t ()
}
data Invite t
= Invite { _invitation :: Dynamic t (Maybe (InvitationId, API.Invitation))
, _request :: Event t [ API.ServerRequest ]
, _uiGoBack :: Event t ()
, _uiDone :: Event t()
}
data InvitationSent
= SentWhatsApp
| SentTelegram
| SentCopy
| SentRefresh
| SentEmail
| SentShare
type HasModel model = Env.HasEnvironment model
invite :: forall model t m. (MonadHold t m, MonadFix m, Reflex t, HasModel model)
=> model t -> Config t -> m (Invite t)
invite model config = mdo
let
currentSelected = current (config^.configSelectedFamily)
createOnAuth = push (\() -> do
cInv <- sample $ current inv
case cInv of
Nothing -> pure $ Just ()
Just _ -> pure Nothing
) (config^.configAuthenticated)
createInvReq
= (:[]) . API.ReqCreateInvitation
<$> leftmost [ updated (config^.configSelectedFamily)
, tag currentSelected (config^.configCreateInvitation)
, tag currentSelected createOnAuth
]
invEv = push (\res -> case res of
API.ResCreatedInvitation invTuple -> pure $ Just invTuple
_ -> pure Nothing
) (config^.configResponse)
inv <- holdDyn Nothing $ Just <$> invEv
pure Invite { _invitation = inv
, _request = createInvReq
, _uiGoBack = never
, _uiDone = never
}
getBaseLink :: HasModel model => model t -> Text
getBaseLink model = model ^. Env.httpProtocol <> model ^. Env.frontendHost <> model ^. Env.frontendPath
makeInvitationLink :: Text -> API.Invitation -> Text
makeInvitationLink baseURL inv =
let
encodedSecret = T.decodeUtf8 . urlEncode True . BL.toStrict . Aeson.encode . API.invitationSecret $ inv
in
baseURL <> "?" <> invitationQueryParam <> "=" <> encodedSecret
-- Not used currently :
encodeURIComponent : : ( ToJSVal i , o , MonadIO m ) = > i - > MaybeT m o
encodeURIComponent = do
-- jsVal <- liftIO $ toJSVal val
-- let jsOut = jsEncodeURIComponent jsVal
-- MaybeT . liftIO $ fromJSVal jsOut
-- foreign import javascript unsafe
" encodeURIComponent $ 1 "
-- jsEncodeURIComponent :: JSVal -> JSVal
instance Reflex t => Default (Invite t) where
def = Invite { _invitation = constDyn Nothing
, _request = never
, _uiGoBack = never
, _uiDone = never
}
inviteSwitchPromptlyDyn :: Reflex t => Dynamic t (Invite t) -> Invite t
inviteSwitchPromptlyDyn dynInvite
= Invite { _invitation = join (_invitation <$> dynInvite)
, _request = switchPromptlyDyn (_request <$> dynInvite)
, _uiGoBack = switchPromptlyDyn (_uiGoBack <$> dynInvite)
, _uiDone = switchPromptlyDyn (_uiDone <$> dynInvite)
}
-- Lenses for Config t:
configResponse :: Lens' (Config t) (Event t API.ServerResponse)
configResponse f config' = (\configResponse' -> config' { _configResponse = configResponse' }) <$> f (_configResponse config')
configSelectedFamily :: Lens' (Config t) (Dynamic t FamilyId)
configSelectedFamily f config' = (\configSelectedFamily' -> config' { _configSelectedFamily = configSelectedFamily' }) <$> f (_configSelectedFamily config')
configAuthenticated :: Lens' (Config t) (Event t ())
configAuthenticated f config' = (\configAuthenticated' -> config' { _configAuthenticated = configAuthenticated' }) <$> f (_configAuthenticated config')
configCreateInvitation :: Lens' (Config t) (Event t ())
configCreateInvitation f config' = (\configCreateInvitation' -> config' { _configCreateInvitation = configCreateInvitation' }) <$> f (_configCreateInvitation config')
-- Lenses for Invite t:
invitation :: Lens' (Invite t) (Dynamic t (Maybe (InvitationId, API.Invitation)))
invitation f invite' = (\invitation' -> invite' { _invitation = invitation' }) <$> f (_invitation invite')
request :: Lens' (Invite t) (Event t [ API.ServerRequest ])
request f invite' = (\request' -> invite' { _request = request' }) <$> f (_request invite')
uiGoBack :: Lens' (Invite t) (Event t ())
uiGoBack f invite' = (\uiGoBack' -> invite' { _uiGoBack = uiGoBack' }) <$> f (_uiGoBack invite')
uiDone :: Lens' (Invite t) (Event t ())
uiDone f invite' = (\uiDone' -> invite' { _uiDone = uiDone' }) <$> f (_uiDone invite')
-- Browser capabilities
shareLink :: (MonadJSM m, MonadPlus m, MonadJSM m') => m (Text -> m' ())
shareLink = do
nav <- liftJSM $ jsg ("navigator" :: Text)
win <- liftJSM $ jsg ("window" :: Text)
mNativeShare <- liftJSM $ maybeNullOrUndefined =<< nav ! ("share" :: Text)
mAndroidShare <- liftJSM $ maybeNullOrUndefined =<< win ! ("nativeHost" :: Text)
case (mNativeShare, mAndroidShare) of
(Just _share, _) ->
let shareFunc linkUrl = void $ liftJSM $ do
url <- obj
(url <# ("url" :: Text)) linkUrl
nav ^. js1 ("share" :: Text) url
in pure shareFunc
(_, Just share) ->
let shareFunc linkUrl = void $ liftJSM $
share ^. js1 ("share" :: Text) linkUrl
in pure shareFunc
_ -> mzero
| null | https://raw.githubusercontent.com/gonimo/gonimo/f4072db9e56f0c853a9f07e048e254eaa671283b/front/src/Gonimo/Client/Invite/Internal.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
# LANGUAGE RecursiveDo #
Not used currently :
jsVal <- liftIO $ toJSVal val
let jsOut = jsEncodeURIComponent jsVal
MaybeT . liftIO $ fromJSVal jsOut
foreign import javascript unsafe
jsEncodeURIComponent :: JSVal -> JSVal
Lenses for Config t:
Lenses for Invite t:
Browser capabilities | # LANGUAGE ScopedTypeVariables #
module Gonimo.Client.Invite.Internal where
import Control.Lens
import Control.Monad
import Control.Monad.Fix (MonadFix)
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy as BL
import Data.Default (Default (..))
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text.Encoding as T
import Language.Javascript.JSaddle
import Network.HTTP.Types (urlEncode)
import Reflex.Dom.Core
import qualified Gonimo.Client.Environment as Env
import qualified Gonimo.SocketAPI as API
import Gonimo.SocketAPI.Types (FamilyId, InvitationId)
import qualified Gonimo.SocketAPI.Types as API
invitationQueryParam :: Text
invitationQueryParam = "acceptInvitation"
data Config t
= Config { _configResponse :: Event t API.ServerResponse
, _configSelectedFamily :: Dynamic t FamilyId
, _configAuthenticated :: Event t ()
, _configCreateInvitation :: Event t ()
}
data Invite t
= Invite { _invitation :: Dynamic t (Maybe (InvitationId, API.Invitation))
, _request :: Event t [ API.ServerRequest ]
, _uiGoBack :: Event t ()
, _uiDone :: Event t()
}
data InvitationSent
= SentWhatsApp
| SentTelegram
| SentCopy
| SentRefresh
| SentEmail
| SentShare
type HasModel model = Env.HasEnvironment model
invite :: forall model t m. (MonadHold t m, MonadFix m, Reflex t, HasModel model)
=> model t -> Config t -> m (Invite t)
invite model config = mdo
let
currentSelected = current (config^.configSelectedFamily)
createOnAuth = push (\() -> do
cInv <- sample $ current inv
case cInv of
Nothing -> pure $ Just ()
Just _ -> pure Nothing
) (config^.configAuthenticated)
createInvReq
= (:[]) . API.ReqCreateInvitation
<$> leftmost [ updated (config^.configSelectedFamily)
, tag currentSelected (config^.configCreateInvitation)
, tag currentSelected createOnAuth
]
invEv = push (\res -> case res of
API.ResCreatedInvitation invTuple -> pure $ Just invTuple
_ -> pure Nothing
) (config^.configResponse)
inv <- holdDyn Nothing $ Just <$> invEv
pure Invite { _invitation = inv
, _request = createInvReq
, _uiGoBack = never
, _uiDone = never
}
getBaseLink :: HasModel model => model t -> Text
getBaseLink model = model ^. Env.httpProtocol <> model ^. Env.frontendHost <> model ^. Env.frontendPath
makeInvitationLink :: Text -> API.Invitation -> Text
makeInvitationLink baseURL inv =
let
encodedSecret = T.decodeUtf8 . urlEncode True . BL.toStrict . Aeson.encode . API.invitationSecret $ inv
in
baseURL <> "?" <> invitationQueryParam <> "=" <> encodedSecret
encodeURIComponent : : ( ToJSVal i , o , MonadIO m ) = > i - > MaybeT m o
encodeURIComponent = do
" encodeURIComponent $ 1 "
instance Reflex t => Default (Invite t) where
def = Invite { _invitation = constDyn Nothing
, _request = never
, _uiGoBack = never
, _uiDone = never
}
inviteSwitchPromptlyDyn :: Reflex t => Dynamic t (Invite t) -> Invite t
inviteSwitchPromptlyDyn dynInvite
= Invite { _invitation = join (_invitation <$> dynInvite)
, _request = switchPromptlyDyn (_request <$> dynInvite)
, _uiGoBack = switchPromptlyDyn (_uiGoBack <$> dynInvite)
, _uiDone = switchPromptlyDyn (_uiDone <$> dynInvite)
}
configResponse :: Lens' (Config t) (Event t API.ServerResponse)
configResponse f config' = (\configResponse' -> config' { _configResponse = configResponse' }) <$> f (_configResponse config')
configSelectedFamily :: Lens' (Config t) (Dynamic t FamilyId)
configSelectedFamily f config' = (\configSelectedFamily' -> config' { _configSelectedFamily = configSelectedFamily' }) <$> f (_configSelectedFamily config')
configAuthenticated :: Lens' (Config t) (Event t ())
configAuthenticated f config' = (\configAuthenticated' -> config' { _configAuthenticated = configAuthenticated' }) <$> f (_configAuthenticated config')
configCreateInvitation :: Lens' (Config t) (Event t ())
configCreateInvitation f config' = (\configCreateInvitation' -> config' { _configCreateInvitation = configCreateInvitation' }) <$> f (_configCreateInvitation config')
invitation :: Lens' (Invite t) (Dynamic t (Maybe (InvitationId, API.Invitation)))
invitation f invite' = (\invitation' -> invite' { _invitation = invitation' }) <$> f (_invitation invite')
request :: Lens' (Invite t) (Event t [ API.ServerRequest ])
request f invite' = (\request' -> invite' { _request = request' }) <$> f (_request invite')
uiGoBack :: Lens' (Invite t) (Event t ())
uiGoBack f invite' = (\uiGoBack' -> invite' { _uiGoBack = uiGoBack' }) <$> f (_uiGoBack invite')
uiDone :: Lens' (Invite t) (Event t ())
uiDone f invite' = (\uiDone' -> invite' { _uiDone = uiDone' }) <$> f (_uiDone invite')
shareLink :: (MonadJSM m, MonadPlus m, MonadJSM m') => m (Text -> m' ())
shareLink = do
nav <- liftJSM $ jsg ("navigator" :: Text)
win <- liftJSM $ jsg ("window" :: Text)
mNativeShare <- liftJSM $ maybeNullOrUndefined =<< nav ! ("share" :: Text)
mAndroidShare <- liftJSM $ maybeNullOrUndefined =<< win ! ("nativeHost" :: Text)
case (mNativeShare, mAndroidShare) of
(Just _share, _) ->
let shareFunc linkUrl = void $ liftJSM $ do
url <- obj
(url <# ("url" :: Text)) linkUrl
nav ^. js1 ("share" :: Text) url
in pure shareFunc
(_, Just share) ->
let shareFunc linkUrl = void $ liftJSM $
share ^. js1 ("share" :: Text) linkUrl
in pure shareFunc
_ -> mzero
|
accd08ba3935f1af634951bbc18586813ca2a9efb7b9d8102e9baf0318a8c96f | GaloisInc/surveyor | Extension.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
-- | State extensions for the brick UI
module Surveyor.Brick.Extension (
BrickUIState(..),
BrickUIExtension(..),
BrickUIEvent(..),
updateMinibufferCompletions,
-- * Lenses
minibufferL,
minibufferG,
echoAreaL,
functionSelectorL,
functionSelectorG,
blockSelectorL,
blockSelectorG,
blockViewersL,
blockViewerG,
functionViewersL,
functionViewerG,
symbolicExecutionStateL,
symbolicExecutionStateG
) where
import Control.Lens ( (^.), (&), (%~) )
import qualified Control.Lens as L
import qualified Control.NF as NF
import Data.Kind ( Type )
import qualified Data.Map.Strict as Map
import qualified Data.Parameterized.Map as MapF
import qualified Data.Parameterized.Nonce as PN
import qualified Data.Text as T
import qualified Data.Vector as V
import GHC.Generics ( Generic )
import qualified Prettyprinter as PP
import qualified Surveyor.Core as C
import qualified Brick.Widget.Minibuffer as MBW
import qualified Surveyor.Brick.EchoArea as SBEA
import Surveyor.Brick.Names ( Names(..) )
import qualified Surveyor.Brick.Widget.BlockSelector as BS
import qualified Surveyor.Brick.Widget.BlockViewer as BV
import qualified Surveyor.Brick.Widget.FunctionSelector as FS
import qualified Surveyor.Brick.Widget.FunctionViewer as FV
import qualified Surveyor.Brick.Widget.Minibuffer as MB
import qualified Surveyor.Brick.Widget.SymbolicExecution as SEM
| Extra UI extensions for the Brick UI
--
-- This differs from 'BrickUIState' in that it is not parameterized by the
-- architecture (@arch@). That is important, as there is not always an active
-- architecture. Objects in this extension state can always be available (e.g.,
-- the minibuffer).
data BrickUIExtension s =
BrickUIExtension { sMinibuffer :: !(MB.Minibuffer (C.SurveyorCommand s (C.S BrickUIExtension BrickUIState)) T.Text Names)
-- ^ The persistent state of the minibuffer
, sEchoArea :: SBEA.EchoArea
}
deriving (Generic)
| State specific to the Brick UI
--
-- This is mostly storage for widgets
data BrickUIState arch s =
BrickUIState { sFunctionSelector :: !(FS.FunctionSelector arch s)
-- ^ Functions available in the function selector
, sBlockSelector :: !(BS.BlockSelector arch s)
, sBlockViewers :: !(MapF.MapF (C.IRRepr arch) (BV.BlockViewer arch s))
, sFunctionViewer :: !(MapF.MapF (C.IRRepr arch) (FV.FunctionViewer arch s))
, sSymbolicExecutionState :: !(Map.Map (C.SessionID s) (SEM.SymbolicExecutionManager (C.Events s (C.S BrickUIExtension BrickUIState)) arch s))
}
deriving (Generic)
L.makeLensesFor
[ ("sMinibuffer", "minibufferL")
, ("sEchoArea", "echoAreaL")
]
''BrickUIExtension
L.makeLensesFor
[ ("sFunctionSelector", "functionSelectorL")
, ("sBlockSelector", "blockSelectorL")
, ("sBlockViewers", "blockViewersL")
, ("sFunctionViewer", "functionViewersL")
, ("sSymbolicExecutionState", "symbolicExecutionStateL") ]
''BrickUIState
type instance C.EventExtension (C.S BrickUIExtension BrickUIState) = BrickUIEvent
| Events specific to the Brick UI
--
-- Note that it isn't parameterized by the @st@ type like the base event because
-- we can actually mention the full state type here, so it doesn't need to be a
-- parameter.
data BrickUIEvent s (st :: Type -> Type -> Type) where
ShowSummary :: BrickUIEvent s st
ShowDiagnostics :: BrickUIEvent s st
OpenMinibuffer :: BrickUIEvent s st
ShowSymbolicExecution :: BrickUIEvent s st
-- | Display a transient message to the user
EchoText :: !(PP.Doc ()) -> BrickUIEvent s st
-- | A message sent by the system (after a time delay) to reset the transient
-- message area
ResetEchoArea :: BrickUIEvent s st
ListBlocks :: PN.Nonce s arch -> [C.Block arch s] -> BrickUIEvent s st
ListFunctions :: PN.Nonce s arch -> [C.FunctionHandle arch s] -> BrickUIEvent s st
FindFunctionsContaining :: PN.Nonce s arch -> Maybe (C.Address arch s) -> BrickUIEvent s st
FindBlockContaining :: PN.Nonce s arch -> C.Address arch s -> BrickUIEvent s st
PromptValueName :: PN.Nonce s arch -> BrickUIEvent s st
instance C.ToEvent s (C.S BrickUIExtension BrickUIState) BrickUIEvent where
toEvent = C.ExtensionEvent
updateMinibufferCompletions :: (C.Events s (C.S BrickUIExtension BrickUIState) -> IO ())
-> PN.Nonce s arch
-> (T.Text -> V.Vector T.Text -> IO ())
updateMinibufferCompletions emitEvent archNonce = \t matches -> do
let stateTransformer matches' state
| mb <- state ^. C.lUIExtension . minibufferL
, MBW.activeCompletionTarget mb == Just t =
state & C.lUIExtension . minibufferL %~ MBW.setCompletions matches'
| otherwise = state
emitEvent (C.AsyncStateUpdate archNonce (NF.nf matches) stateTransformer)
minibufferG :: L.Getter (BrickUIExtension s) (MB.Minibuffer (C.SurveyorCommand s (C.S BrickUIExtension BrickUIState)) T.Text Names)
minibufferG = L.to (^. minibufferL)
functionSelectorG :: L.Getter (C.ArchState BrickUIState arch s) (FS.FunctionSelector arch s)
functionSelectorG = L.to (^. C.lUIState . functionSelectorL)
blockSelectorG :: L.Getter (C.ArchState BrickUIState arch s) (BS.BlockSelector arch s)
blockSelectorG = L.to (^. C.lUIState . blockSelectorL)
blockViewerG :: C.IRRepr arch ir -> L.Getter (C.ArchState BrickUIState arch s) (Maybe (BV.BlockViewer arch s ir))
blockViewerG rep = L.to (\as -> MapF.lookup rep (as ^. C.lUIState . blockViewersL))
functionViewerG :: C.IRRepr arch ir -> L.Getter (C.ArchState BrickUIState arch s) (Maybe (FV.FunctionViewer arch s ir))
functionViewerG rep = L.to (\as -> MapF.lookup rep (as ^. C.lUIState . functionViewersL))
symbolicExecutionStateG :: L.Getter (C.ArchState BrickUIState arch s) (Map.Map (C.SessionID s) (SEM.SymbolicExecutionManager (C.Events s (C.S BrickUIExtension BrickUIState)) arch s))
symbolicExecutionStateG = L.to (^. C.lUIState . symbolicExecutionStateL)
| null | https://raw.githubusercontent.com/GaloisInc/surveyor/96b6748d811bc2ab9ef330307a324bd00e04819f/surveyor-brick/src/Surveyor/Brick/Extension.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE RankNTypes #
| State extensions for the brick UI
* Lenses
This differs from 'BrickUIState' in that it is not parameterized by the
architecture (@arch@). That is important, as there is not always an active
architecture. Objects in this extension state can always be available (e.g.,
the minibuffer).
^ The persistent state of the minibuffer
This is mostly storage for widgets
^ Functions available in the function selector
Note that it isn't parameterized by the @st@ type like the base event because
we can actually mention the full state type here, so it doesn't need to be a
parameter.
| Display a transient message to the user
| A message sent by the system (after a time delay) to reset the transient
message area | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Surveyor.Brick.Extension (
BrickUIState(..),
BrickUIExtension(..),
BrickUIEvent(..),
updateMinibufferCompletions,
minibufferL,
minibufferG,
echoAreaL,
functionSelectorL,
functionSelectorG,
blockSelectorL,
blockSelectorG,
blockViewersL,
blockViewerG,
functionViewersL,
functionViewerG,
symbolicExecutionStateL,
symbolicExecutionStateG
) where
import Control.Lens ( (^.), (&), (%~) )
import qualified Control.Lens as L
import qualified Control.NF as NF
import Data.Kind ( Type )
import qualified Data.Map.Strict as Map
import qualified Data.Parameterized.Map as MapF
import qualified Data.Parameterized.Nonce as PN
import qualified Data.Text as T
import qualified Data.Vector as V
import GHC.Generics ( Generic )
import qualified Prettyprinter as PP
import qualified Surveyor.Core as C
import qualified Brick.Widget.Minibuffer as MBW
import qualified Surveyor.Brick.EchoArea as SBEA
import Surveyor.Brick.Names ( Names(..) )
import qualified Surveyor.Brick.Widget.BlockSelector as BS
import qualified Surveyor.Brick.Widget.BlockViewer as BV
import qualified Surveyor.Brick.Widget.FunctionSelector as FS
import qualified Surveyor.Brick.Widget.FunctionViewer as FV
import qualified Surveyor.Brick.Widget.Minibuffer as MB
import qualified Surveyor.Brick.Widget.SymbolicExecution as SEM
| Extra UI extensions for the Brick UI
data BrickUIExtension s =
BrickUIExtension { sMinibuffer :: !(MB.Minibuffer (C.SurveyorCommand s (C.S BrickUIExtension BrickUIState)) T.Text Names)
, sEchoArea :: SBEA.EchoArea
}
deriving (Generic)
| State specific to the Brick UI
data BrickUIState arch s =
BrickUIState { sFunctionSelector :: !(FS.FunctionSelector arch s)
, sBlockSelector :: !(BS.BlockSelector arch s)
, sBlockViewers :: !(MapF.MapF (C.IRRepr arch) (BV.BlockViewer arch s))
, sFunctionViewer :: !(MapF.MapF (C.IRRepr arch) (FV.FunctionViewer arch s))
, sSymbolicExecutionState :: !(Map.Map (C.SessionID s) (SEM.SymbolicExecutionManager (C.Events s (C.S BrickUIExtension BrickUIState)) arch s))
}
deriving (Generic)
L.makeLensesFor
[ ("sMinibuffer", "minibufferL")
, ("sEchoArea", "echoAreaL")
]
''BrickUIExtension
L.makeLensesFor
[ ("sFunctionSelector", "functionSelectorL")
, ("sBlockSelector", "blockSelectorL")
, ("sBlockViewers", "blockViewersL")
, ("sFunctionViewer", "functionViewersL")
, ("sSymbolicExecutionState", "symbolicExecutionStateL") ]
''BrickUIState
type instance C.EventExtension (C.S BrickUIExtension BrickUIState) = BrickUIEvent
| Events specific to the Brick UI
data BrickUIEvent s (st :: Type -> Type -> Type) where
ShowSummary :: BrickUIEvent s st
ShowDiagnostics :: BrickUIEvent s st
OpenMinibuffer :: BrickUIEvent s st
ShowSymbolicExecution :: BrickUIEvent s st
EchoText :: !(PP.Doc ()) -> BrickUIEvent s st
ResetEchoArea :: BrickUIEvent s st
ListBlocks :: PN.Nonce s arch -> [C.Block arch s] -> BrickUIEvent s st
ListFunctions :: PN.Nonce s arch -> [C.FunctionHandle arch s] -> BrickUIEvent s st
FindFunctionsContaining :: PN.Nonce s arch -> Maybe (C.Address arch s) -> BrickUIEvent s st
FindBlockContaining :: PN.Nonce s arch -> C.Address arch s -> BrickUIEvent s st
PromptValueName :: PN.Nonce s arch -> BrickUIEvent s st
instance C.ToEvent s (C.S BrickUIExtension BrickUIState) BrickUIEvent where
toEvent = C.ExtensionEvent
updateMinibufferCompletions :: (C.Events s (C.S BrickUIExtension BrickUIState) -> IO ())
-> PN.Nonce s arch
-> (T.Text -> V.Vector T.Text -> IO ())
updateMinibufferCompletions emitEvent archNonce = \t matches -> do
let stateTransformer matches' state
| mb <- state ^. C.lUIExtension . minibufferL
, MBW.activeCompletionTarget mb == Just t =
state & C.lUIExtension . minibufferL %~ MBW.setCompletions matches'
| otherwise = state
emitEvent (C.AsyncStateUpdate archNonce (NF.nf matches) stateTransformer)
minibufferG :: L.Getter (BrickUIExtension s) (MB.Minibuffer (C.SurveyorCommand s (C.S BrickUIExtension BrickUIState)) T.Text Names)
minibufferG = L.to (^. minibufferL)
functionSelectorG :: L.Getter (C.ArchState BrickUIState arch s) (FS.FunctionSelector arch s)
functionSelectorG = L.to (^. C.lUIState . functionSelectorL)
blockSelectorG :: L.Getter (C.ArchState BrickUIState arch s) (BS.BlockSelector arch s)
blockSelectorG = L.to (^. C.lUIState . blockSelectorL)
blockViewerG :: C.IRRepr arch ir -> L.Getter (C.ArchState BrickUIState arch s) (Maybe (BV.BlockViewer arch s ir))
blockViewerG rep = L.to (\as -> MapF.lookup rep (as ^. C.lUIState . blockViewersL))
functionViewerG :: C.IRRepr arch ir -> L.Getter (C.ArchState BrickUIState arch s) (Maybe (FV.FunctionViewer arch s ir))
functionViewerG rep = L.to (\as -> MapF.lookup rep (as ^. C.lUIState . functionViewersL))
symbolicExecutionStateG :: L.Getter (C.ArchState BrickUIState arch s) (Map.Map (C.SessionID s) (SEM.SymbolicExecutionManager (C.Events s (C.S BrickUIExtension BrickUIState)) arch s))
symbolicExecutionStateG = L.to (^. C.lUIState . symbolicExecutionStateL)
|
08cd796ffa40d872dfa41eaa0fd631d5d2eea19cd605864f4a454c36317c8f28 | BranchTaken/Hemlock | test_div_mod.ml | open! Basis.Rudiments
open! Basis
open Zint
let test () =
let rec test_pairs = function
| [] -> ()
| (x, y) :: pairs' -> begin
let quotient = x / y in
let remainder = x % y in
File.Fmt.stdout
|> fmt ~alt:true ~radix:Radix.Hex x
|> Fmt.fmt " /,% "
|> fmt ~alt:true ~radix:Radix.Hex y
|> Fmt.fmt " -> "
|> fmt ~alt:true ~radix:Radix.Hex quotient
|> Fmt.fmt ", "
|> fmt ~alt:true ~radix:Radix.Hex remainder
|> Fmt.fmt "\n"
|> ignore;
assert (x = (y * quotient + remainder));
assert (x >= y || remainder = x);
test_pairs pairs'
end
in
let pairs = [
< 1
(of_string "0", of_string "1");
(of_string "1", of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
(of_string "0xfffe", of_string "0xffff");
(of_string "0xffff_fffe", of_string "0xffff_ffff");
(of_string "0xffff_ffff_ffff_fffe", of_string "0xffff_ffff_ffff_ffff");
(of_string "0xf_ffff_ffff_ffff_fffe", of_string "0xf_ffff_ffff_ffff_ffff");
(of_string "0xffff_ffff_ffff_ffff_fffe",
of_string "0xffff_ffff_ffff_ffff_ffff");
(of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe",
of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe",
of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
Single - digit ( base 2 ^ 32 ) divisor .
(of_string "1", of_string "1");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "1");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "2");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "3");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "7");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "0xffff");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "0xffff_ffff");
Multi - digit ( base 2 ^ 32 ) divisor .
(of_string "0x1_0000_0000", of_string "0x1_0000_0000");
(of_string "0x1_ffff_ffff", of_string "0x1_0000_0000");
(of_string "0x2_ffff_ffff", of_string "0x1_0000_0000");
(of_string "0xffff_ffff_ffff_ffff", of_string "0xffff_ffff_ffff_ffff");
(of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
(of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "0xffff_ffff_ffff_ffff");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
] in
test_pairs pairs
let _ = test ()
| null | https://raw.githubusercontent.com/BranchTaken/Hemlock/a07e362d66319108c1478a4cbebab765c1808b1a/bootstrap/test/basis/zint/test_div_mod.ml | ocaml | open! Basis.Rudiments
open! Basis
open Zint
let test () =
let rec test_pairs = function
| [] -> ()
| (x, y) :: pairs' -> begin
let quotient = x / y in
let remainder = x % y in
File.Fmt.stdout
|> fmt ~alt:true ~radix:Radix.Hex x
|> Fmt.fmt " /,% "
|> fmt ~alt:true ~radix:Radix.Hex y
|> Fmt.fmt " -> "
|> fmt ~alt:true ~radix:Radix.Hex quotient
|> Fmt.fmt ", "
|> fmt ~alt:true ~radix:Radix.Hex remainder
|> Fmt.fmt "\n"
|> ignore;
assert (x = (y * quotient + remainder));
assert (x >= y || remainder = x);
test_pairs pairs'
end
in
let pairs = [
< 1
(of_string "0", of_string "1");
(of_string "1", of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
(of_string "0xfffe", of_string "0xffff");
(of_string "0xffff_fffe", of_string "0xffff_ffff");
(of_string "0xffff_ffff_ffff_fffe", of_string "0xffff_ffff_ffff_ffff");
(of_string "0xf_ffff_ffff_ffff_fffe", of_string "0xf_ffff_ffff_ffff_ffff");
(of_string "0xffff_ffff_ffff_ffff_fffe",
of_string "0xffff_ffff_ffff_ffff_ffff");
(of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe",
of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe",
of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
Single - digit ( base 2 ^ 32 ) divisor .
(of_string "1", of_string "1");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "1");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "2");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "3");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "7");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "0xffff");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "0xffff_ffff");
Multi - digit ( base 2 ^ 32 ) divisor .
(of_string "0x1_0000_0000", of_string "0x1_0000_0000");
(of_string "0x1_ffff_ffff", of_string "0x1_0000_0000");
(of_string "0x2_ffff_ffff", of_string "0x1_0000_0000");
(of_string "0xffff_ffff_ffff_ffff", of_string "0xffff_ffff_ffff_ffff");
(of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
(of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "0xffff_ffff_ffff_ffff");
(of_string
"0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff",
of_string "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff");
] in
test_pairs pairs
let _ = test ()
|
|
477afc5754fb0c3769ce751fce3da505a8acde1e7a2b552314fb028d159e9465 | janestreet/hardcaml | test_nand.ml | (* Build adder circuits using NAND as the base gate. Demonstrates the use of the
[Comb.Make_primitives] functor. *)
open! Import
module Make_nand_gates (X : sig
module Bits : Comb.S
val nand : Bits.t -> Bits.t -> Bits.t
end) : Comb.Gates with type t = X.Bits.t = struct
include X.Bits
let ( ~: ) a = X.nand a a
let ( &: ) a b = ~:(X.nand a b)
let ( |: ) a b = X.nand ~:a ~:b
let ( ^: ) a b =
let c = X.nand a b in
X.nand (X.nand a c) (X.nand b c)
;;
end
module Bits_nand = Comb.Make (Comb.Make_primitives (Make_nand_gates (struct
module Bits = Bits
let nand a b = Bits.(~:(a &: b))
end)))
let%expect_test "3 bit adder, bits" =
for a = 0 to 7 do
print_s
[%message
""
~_:
(List.init 8 ~f:(fun b -> Bits_nand.(of_int ~width:3 a +: of_int ~width:3 b))
: Bits.t list)]
done;
[%expect
{|
(000 001 010 011 100 101 110 111)
(001 010 011 100 101 110 111 000)
(010 011 100 101 110 111 000 001)
(011 100 101 110 111 000 001 010)
(100 101 110 111 000 001 010 011)
(101 110 111 000 001 010 011 100)
(110 111 000 001 010 011 100 101)
(111 000 001 010 011 100 101 110) |}]
;;
module Asic_nand = Comb.Make (Comb.Make_primitives (Make_nand_gates (struct
module Bits = Signal
let nand a b =
assert (Bits.width a = Bits.width b);
Map.find_exn
(Instantiation.create
()
~name:"nand"
~inputs:[ "a", a; "b", b ]
~outputs:[ "c", Bits.width a ])
"c"
;;
end)))
let%expect_test "3 bit adder, ASIC style, verilog" =
let open Signal in
let a, b = input "a" 3, input "b" 3 in
let c = output "c" Asic_nand.(a +: b) in
let circuit = Circuit.create_exn ~name:"adder_nand" [ c ] in
Rtl.print Verilog circuit;
[%expect
{|
module adder_nand (
b,
a,
c
);
input [2:0] b;
input [2:0] a;
output [2:0] c;
/* signal declarations */
wire _54;
wire _1;
wire _56;
wire _2;
wire _59;
wire _3;
wire _62;
wire _4;
wire _64;
wire _5;
wire _66;
wire _6;
wire _68;
wire _7;
wire _70;
wire _8;
wire _72;
wire _9;
wire _74;
wire _10;
wire _77;
wire _11;
wire _80;
wire _12;
wire _82;
wire _13;
wire _84;
wire _14;
wire _86;
wire _15;
wire _88;
wire _16;
wire _90;
wire _17;
wire _92;
wire _18;
wire _94;
wire _19;
wire _96;
wire _20;
wire _98;
wire _21;
wire _100;
wire _22;
wire _102;
wire _23;
wire _52 = 1'b0;
wire _104;
wire _24;
wire _106;
wire _25;
wire _108;
wire _26;
wire _57;
wire _60;
wire _110;
wire _27;
wire _112;
wire _28;
wire _114;
wire _29;
wire _116;
wire _30;
wire _118;
wire _31;
wire _120;
wire _32;
wire _122;
wire _33;
wire _124;
wire _34;
wire _126;
wire _35;
wire _75;
wire _78;
wire _128;
wire _36;
wire _130;
wire _37;
wire _132;
wire _38;
wire _134;
wire _39;
wire _136;
wire _40;
wire _138;
wire _41;
wire _140;
wire _42;
wire _143;
wire _43;
wire _141;
wire _146;
wire _45;
wire _144;
wire _148;
wire _47;
wire _150;
wire _48;
wire _152;
wire _49;
wire _154;
wire _50;
wire [2:0] _155;
/* logic */
nand
the_nand
( .a(_52), .b(_2), .c(_54) );
assign _1 = _54;
nand
the_nand_0
( .a(_6), .b(_52), .c(_56) );
assign _2 = _56;
nand
the_nand_1
( .a(_57), .b(_4), .c(_59) );
assign _3 = _59;
nand
the_nand_2
( .a(_60), .b(_57), .c(_62) );
assign _4 = _62;
nand
the_nand_3
( .a(_60), .b(_4), .c(_64) );
assign _5 = _64;
nand
the_nand_4
( .a(_5), .b(_3), .c(_66) );
assign _6 = _66;
nand
the_nand_5
( .a(_6), .b(_2), .c(_68) );
assign _7 = _68;
nand
the_nand_6
( .a(_7), .b(_1), .c(_70) );
assign _8 = _70;
nand
the_nand_7
( .a(_32), .b(_10), .c(_72) );
assign _9 = _72;
nand
the_nand_8
( .a(_14), .b(_32), .c(_74) );
assign _10 = _74;
nand
the_nand_9
( .a(_75), .b(_12), .c(_77) );
assign _11 = _77;
nand
the_nand_10
( .a(_78), .b(_75), .c(_80) );
assign _12 = _80;
nand
the_nand_11
( .a(_78), .b(_12), .c(_82) );
assign _13 = _82;
nand
the_nand_12
( .a(_13), .b(_11), .c(_84) );
assign _14 = _84;
nand
the_nand_13
( .a(_14), .b(_10), .c(_86) );
assign _15 = _86;
nand
the_nand_14
( .a(_15), .b(_9), .c(_88) );
assign _16 = _88;
nand
the_nand_15
( .a(_41), .b(_42), .c(_90) );
assign _17 = _90;
nand
the_nand_16
( .a(_32), .b(_78), .c(_92) );
assign _18 = _92;
nand
the_nand_17
( .a(_18), .b(_18), .c(_94) );
assign _19 = _94;
nand
the_nand_18
( .a(_19), .b(_19), .c(_96) );
assign _20 = _96;
nand
the_nand_19
( .a(_52), .b(_60), .c(_98) );
assign _21 = _98;
nand
the_nand_20
( .a(_21), .b(_21), .c(_100) );
assign _22 = _100;
nand
the_nand_21
( .a(_22), .b(_22), .c(_102) );
assign _23 = _102;
nand
the_nand_22
( .a(_57), .b(_52), .c(_104) );
assign _24 = _104;
nand
the_nand_23
( .a(_24), .b(_24), .c(_106) );
assign _25 = _106;
nand
the_nand_24
( .a(_25), .b(_25), .c(_108) );
assign _26 = _108;
assign _57 = b[0:0];
assign _60 = a[0:0];
nand
the_nand_25
( .a(_60), .b(_57), .c(_110) );
assign _27 = _110;
nand
the_nand_26
( .a(_27), .b(_27), .c(_112) );
assign _28 = _112;
nand
the_nand_27
( .a(_28), .b(_28), .c(_114) );
assign _29 = _114;
nand
the_nand_28
( .a(_29), .b(_26), .c(_116) );
assign _30 = _116;
nand
the_nand_29
( .a(_30), .b(_30), .c(_118) );
assign _31 = _118;
nand
the_nand_30
( .a(_31), .b(_23), .c(_120) );
assign _32 = _120;
nand
the_nand_31
( .a(_75), .b(_32), .c(_122) );
assign _33 = _122;
nand
the_nand_32
( .a(_33), .b(_33), .c(_124) );
assign _34 = _124;
nand
the_nand_33
( .a(_34), .b(_34), .c(_126) );
assign _35 = _126;
assign _75 = b[1:1];
assign _78 = a[1:1];
nand
the_nand_34
( .a(_78), .b(_75), .c(_128) );
assign _36 = _128;
nand
the_nand_35
( .a(_36), .b(_36), .c(_130) );
assign _37 = _130;
nand
the_nand_36
( .a(_37), .b(_37), .c(_132) );
assign _38 = _132;
nand
the_nand_37
( .a(_38), .b(_35), .c(_134) );
assign _39 = _134;
nand
the_nand_38
( .a(_39), .b(_39), .c(_136) );
assign _40 = _136;
nand
the_nand_39
( .a(_40), .b(_20), .c(_138) );
assign _41 = _138;
nand
the_nand_40
( .a(_48), .b(_41), .c(_140) );
assign _42 = _140;
nand
the_nand_41
( .a(_141), .b(_45), .c(_143) );
assign _43 = _143;
assign _141 = b[2:2];
nand
the_nand_42
( .a(_144), .b(_141), .c(_146) );
assign _45 = _146;
assign _144 = a[2:2];
nand
the_nand_43
( .a(_144), .b(_45), .c(_148) );
assign _47 = _148;
nand
the_nand_44
( .a(_47), .b(_43), .c(_150) );
assign _48 = _150;
nand
the_nand_45
( .a(_48), .b(_42), .c(_152) );
assign _49 = _152;
nand
the_nand_46
( .a(_49), .b(_17), .c(_154) );
assign _50 = _154;
assign _155 = { _50, _16, _8 };
/* aliases */
/* output assignments */
assign c = _155;
endmodule |}]
;;
module Fpga_nand = Comb.Make (Comb.Make_primitives (Make_nand_gates (struct
module Bits = Signal
open Signal
let nand_lut a b =
Map.find_exn
(Instantiation.create
()
~name:"LUT2"
~parameters:[ Parameter.create ~name:"INIT" ~value:(String "1110") ]
~inputs:[ "I", a @: b ]
~outputs:[ "O", 1 ])
"O"
;;
let nand a b =
assert (width a = width b);
concat_msb (List.map2_exn (bits_msb a) (bits_msb b) ~f:nand_lut)
;;
end)))
let%expect_test "3 bit adder, FPGA style, verilog" =
(* Not sayin' this is an efficient way to go about this... *)
let open Signal in
let a, b = input "a" 3, input "b" 3 in
let c = output "c" Fpga_nand.(a +: b) in
let circuit = Circuit.create_exn ~name:"adder_nand" [ c ] in
Rtl.print Verilog circuit;
[%expect
{|
module adder_nand (
b,
a,
c
);
input [2:0] b;
input [2:0] a;
output [2:0] c;
/* signal declarations */
wire [1:0] _53;
wire _55;
wire _1;
wire [1:0] _56;
wire _58;
wire _2;
wire [1:0] _60;
wire _62;
wire _3;
wire [1:0] _64;
wire _66;
wire _4;
wire [1:0] _67;
wire _69;
wire _5;
wire [1:0] _70;
wire _72;
wire _6;
wire [1:0] _73;
wire _75;
wire _7;
wire [1:0] _76;
wire _78;
wire _8;
wire [1:0] _79;
wire _81;
wire _9;
wire [1:0] _82;
wire _84;
wire _10;
wire [1:0] _86;
wire _88;
wire _11;
wire [1:0] _90;
wire _92;
wire _12;
wire [1:0] _93;
wire _95;
wire _13;
wire [1:0] _96;
wire _98;
wire _14;
wire [1:0] _99;
wire _101;
wire _15;
wire [1:0] _102;
wire _104;
wire _16;
wire [1:0] _105;
wire _107;
wire _17;
wire [1:0] _108;
wire _110;
wire _18;
wire [1:0] _111;
wire _113;
wire _19;
wire [1:0] _114;
wire _116;
wire _20;
wire [1:0] _117;
wire _119;
wire _21;
wire [1:0] _120;
wire _122;
wire _22;
wire [1:0] _123;
wire _125;
wire _23;
wire _52 = 1'b0;
wire [1:0] _126;
wire _128;
wire _24;
wire [1:0] _129;
wire _131;
wire _25;
wire [1:0] _132;
wire _134;
wire _26;
wire _59;
wire _63;
wire [1:0] _135;
wire _137;
wire _27;
wire [1:0] _138;
wire _140;
wire _28;
wire [1:0] _141;
wire _143;
wire _29;
wire [1:0] _144;
wire _146;
wire _30;
wire [1:0] _147;
wire _149;
wire _31;
wire [1:0] _150;
wire _152;
wire _32;
wire [1:0] _153;
wire _155;
wire _33;
wire [1:0] _156;
wire _158;
wire _34;
wire [1:0] _159;
wire _161;
wire _35;
wire _85;
wire _89;
wire [1:0] _162;
wire _164;
wire _36;
wire [1:0] _165;
wire _167;
wire _37;
wire [1:0] _168;
wire _170;
wire _38;
wire [1:0] _171;
wire _173;
wire _39;
wire [1:0] _174;
wire _176;
wire _40;
wire [1:0] _177;
wire _179;
wire _41;
wire [1:0] _180;
wire _182;
wire _42;
wire [1:0] _184;
wire _186;
wire _43;
wire _183;
wire [1:0] _188;
wire _190;
wire _45;
wire _187;
wire [1:0] _191;
wire _193;
wire _47;
wire [1:0] _194;
wire _196;
wire _48;
wire [1:0] _197;
wire _199;
wire _49;
wire [1:0] _200;
wire _202;
wire _50;
wire [2:0] _203;
/* logic */
assign _53 = { _52, _2 };
LUT2
#( .INIT("1110") )
the_LUT2
( .I(_53), .O(_55) );
assign _1 = _55;
assign _56 = { _6, _52 };
LUT2
#( .INIT("1110") )
the_LUT2_0
( .I(_56), .O(_58) );
assign _2 = _58;
assign _60 = { _59, _4 };
LUT2
#( .INIT("1110") )
the_LUT2_1
( .I(_60), .O(_62) );
assign _3 = _62;
assign _64 = { _63, _59 };
LUT2
#( .INIT("1110") )
the_LUT2_2
( .I(_64), .O(_66) );
assign _4 = _66;
assign _67 = { _63, _4 };
LUT2
#( .INIT("1110") )
the_LUT2_3
( .I(_67), .O(_69) );
assign _5 = _69;
assign _70 = { _5, _3 };
LUT2
#( .INIT("1110") )
the_LUT2_4
( .I(_70), .O(_72) );
assign _6 = _72;
assign _73 = { _6, _2 };
LUT2
#( .INIT("1110") )
the_LUT2_5
( .I(_73), .O(_75) );
assign _7 = _75;
assign _76 = { _7, _1 };
LUT2
#( .INIT("1110") )
the_LUT2_6
( .I(_76), .O(_78) );
assign _8 = _78;
assign _79 = { _32, _10 };
LUT2
#( .INIT("1110") )
the_LUT2_7
( .I(_79), .O(_81) );
assign _9 = _81;
assign _82 = { _14, _32 };
LUT2
#( .INIT("1110") )
the_LUT2_8
( .I(_82), .O(_84) );
assign _10 = _84;
assign _86 = { _85, _12 };
LUT2
#( .INIT("1110") )
the_LUT2_9
( .I(_86), .O(_88) );
assign _11 = _88;
assign _90 = { _89, _85 };
LUT2
#( .INIT("1110") )
the_LUT2_10
( .I(_90), .O(_92) );
assign _12 = _92;
assign _93 = { _89, _12 };
LUT2
#( .INIT("1110") )
the_LUT2_11
( .I(_93), .O(_95) );
assign _13 = _95;
assign _96 = { _13, _11 };
LUT2
#( .INIT("1110") )
the_LUT2_12
( .I(_96), .O(_98) );
assign _14 = _98;
assign _99 = { _14, _10 };
LUT2
#( .INIT("1110") )
the_LUT2_13
( .I(_99), .O(_101) );
assign _15 = _101;
assign _102 = { _15, _9 };
LUT2
#( .INIT("1110") )
the_LUT2_14
( .I(_102), .O(_104) );
assign _16 = _104;
assign _105 = { _41, _42 };
LUT2
#( .INIT("1110") )
the_LUT2_15
( .I(_105), .O(_107) );
assign _17 = _107;
assign _108 = { _32, _89 };
LUT2
#( .INIT("1110") )
the_LUT2_16
( .I(_108), .O(_110) );
assign _18 = _110;
assign _111 = { _18, _18 };
LUT2
#( .INIT("1110") )
the_LUT2_17
( .I(_111), .O(_113) );
assign _19 = _113;
assign _114 = { _19, _19 };
LUT2
#( .INIT("1110") )
the_LUT2_18
( .I(_114), .O(_116) );
assign _20 = _116;
assign _117 = { _52, _63 };
LUT2
#( .INIT("1110") )
the_LUT2_19
( .I(_117), .O(_119) );
assign _21 = _119;
assign _120 = { _21, _21 };
LUT2
#( .INIT("1110") )
the_LUT2_20
( .I(_120), .O(_122) );
assign _22 = _122;
assign _123 = { _22, _22 };
LUT2
#( .INIT("1110") )
the_LUT2_21
( .I(_123), .O(_125) );
assign _23 = _125;
assign _126 = { _59, _52 };
LUT2
#( .INIT("1110") )
the_LUT2_22
( .I(_126), .O(_128) );
assign _24 = _128;
assign _129 = { _24, _24 };
LUT2
#( .INIT("1110") )
the_LUT2_23
( .I(_129), .O(_131) );
assign _25 = _131;
assign _132 = { _25, _25 };
LUT2
#( .INIT("1110") )
the_LUT2_24
( .I(_132), .O(_134) );
assign _26 = _134;
assign _59 = b[0:0];
assign _63 = a[0:0];
assign _135 = { _63, _59 };
LUT2
#( .INIT("1110") )
the_LUT2_25
( .I(_135), .O(_137) );
assign _27 = _137;
assign _138 = { _27, _27 };
LUT2
#( .INIT("1110") )
the_LUT2_26
( .I(_138), .O(_140) );
assign _28 = _140;
assign _141 = { _28, _28 };
LUT2
#( .INIT("1110") )
the_LUT2_27
( .I(_141), .O(_143) );
assign _29 = _143;
assign _144 = { _29, _26 };
LUT2
#( .INIT("1110") )
the_LUT2_28
( .I(_144), .O(_146) );
assign _30 = _146;
assign _147 = { _30, _30 };
LUT2
#( .INIT("1110") )
the_LUT2_29
( .I(_147), .O(_149) );
assign _31 = _149;
assign _150 = { _31, _23 };
LUT2
#( .INIT("1110") )
the_LUT2_30
( .I(_150), .O(_152) );
assign _32 = _152;
assign _153 = { _85, _32 };
LUT2
#( .INIT("1110") )
the_LUT2_31
( .I(_153), .O(_155) );
assign _33 = _155;
assign _156 = { _33, _33 };
LUT2
#( .INIT("1110") )
the_LUT2_32
( .I(_156), .O(_158) );
assign _34 = _158;
assign _159 = { _34, _34 };
LUT2
#( .INIT("1110") )
the_LUT2_33
( .I(_159), .O(_161) );
assign _35 = _161;
assign _85 = b[1:1];
assign _89 = a[1:1];
assign _162 = { _89, _85 };
LUT2
#( .INIT("1110") )
the_LUT2_34
( .I(_162), .O(_164) );
assign _36 = _164;
assign _165 = { _36, _36 };
LUT2
#( .INIT("1110") )
the_LUT2_35
( .I(_165), .O(_167) );
assign _37 = _167;
assign _168 = { _37, _37 };
LUT2
#( .INIT("1110") )
the_LUT2_36
( .I(_168), .O(_170) );
assign _38 = _170;
assign _171 = { _38, _35 };
LUT2
#( .INIT("1110") )
the_LUT2_37
( .I(_171), .O(_173) );
assign _39 = _173;
assign _174 = { _39, _39 };
LUT2
#( .INIT("1110") )
the_LUT2_38
( .I(_174), .O(_176) );
assign _40 = _176;
assign _177 = { _40, _20 };
LUT2
#( .INIT("1110") )
the_LUT2_39
( .I(_177), .O(_179) );
assign _41 = _179;
assign _180 = { _48, _41 };
LUT2
#( .INIT("1110") )
the_LUT2_40
( .I(_180), .O(_182) );
assign _42 = _182;
assign _184 = { _183, _45 };
LUT2
#( .INIT("1110") )
the_LUT2_41
( .I(_184), .O(_186) );
assign _43 = _186;
assign _183 = b[2:2];
assign _188 = { _187, _183 };
LUT2
#( .INIT("1110") )
the_LUT2_42
( .I(_188), .O(_190) );
assign _45 = _190;
assign _187 = a[2:2];
assign _191 = { _187, _45 };
LUT2
#( .INIT("1110") )
the_LUT2_43
( .I(_191), .O(_193) );
assign _47 = _193;
assign _194 = { _47, _43 };
LUT2
#( .INIT("1110") )
the_LUT2_44
( .I(_194), .O(_196) );
assign _48 = _196;
assign _197 = { _48, _42 };
LUT2
#( .INIT("1110") )
the_LUT2_45
( .I(_197), .O(_199) );
assign _49 = _199;
assign _200 = { _49, _17 };
LUT2
#( .INIT("1110") )
the_LUT2_46
( .I(_200), .O(_202) );
assign _50 = _202;
assign _203 = { _50, _16, _8 };
/* aliases */
/* output assignments */
assign c = _203;
endmodule |}]
;;
| null | https://raw.githubusercontent.com/janestreet/hardcaml/1cdb35da263479bb4149c0f5550462163b7439d1/test/lib/test_nand.ml | ocaml | Build adder circuits using NAND as the base gate. Demonstrates the use of the
[Comb.Make_primitives] functor.
Not sayin' this is an efficient way to go about this... |
open! Import
module Make_nand_gates (X : sig
module Bits : Comb.S
val nand : Bits.t -> Bits.t -> Bits.t
end) : Comb.Gates with type t = X.Bits.t = struct
include X.Bits
let ( ~: ) a = X.nand a a
let ( &: ) a b = ~:(X.nand a b)
let ( |: ) a b = X.nand ~:a ~:b
let ( ^: ) a b =
let c = X.nand a b in
X.nand (X.nand a c) (X.nand b c)
;;
end
module Bits_nand = Comb.Make (Comb.Make_primitives (Make_nand_gates (struct
module Bits = Bits
let nand a b = Bits.(~:(a &: b))
end)))
let%expect_test "3 bit adder, bits" =
for a = 0 to 7 do
print_s
[%message
""
~_:
(List.init 8 ~f:(fun b -> Bits_nand.(of_int ~width:3 a +: of_int ~width:3 b))
: Bits.t list)]
done;
[%expect
{|
(000 001 010 011 100 101 110 111)
(001 010 011 100 101 110 111 000)
(010 011 100 101 110 111 000 001)
(011 100 101 110 111 000 001 010)
(100 101 110 111 000 001 010 011)
(101 110 111 000 001 010 011 100)
(110 111 000 001 010 011 100 101)
(111 000 001 010 011 100 101 110) |}]
;;
module Asic_nand = Comb.Make (Comb.Make_primitives (Make_nand_gates (struct
module Bits = Signal
let nand a b =
assert (Bits.width a = Bits.width b);
Map.find_exn
(Instantiation.create
()
~name:"nand"
~inputs:[ "a", a; "b", b ]
~outputs:[ "c", Bits.width a ])
"c"
;;
end)))
let%expect_test "3 bit adder, ASIC style, verilog" =
let open Signal in
let a, b = input "a" 3, input "b" 3 in
let c = output "c" Asic_nand.(a +: b) in
let circuit = Circuit.create_exn ~name:"adder_nand" [ c ] in
Rtl.print Verilog circuit;
[%expect
{|
module adder_nand (
b,
a,
c
);
input [2:0] b;
input [2:0] a;
output [2:0] c;
/* signal declarations */
wire _54;
wire _1;
wire _56;
wire _2;
wire _59;
wire _3;
wire _62;
wire _4;
wire _64;
wire _5;
wire _66;
wire _6;
wire _68;
wire _7;
wire _70;
wire _8;
wire _72;
wire _9;
wire _74;
wire _10;
wire _77;
wire _11;
wire _80;
wire _12;
wire _82;
wire _13;
wire _84;
wire _14;
wire _86;
wire _15;
wire _88;
wire _16;
wire _90;
wire _17;
wire _92;
wire _18;
wire _94;
wire _19;
wire _96;
wire _20;
wire _98;
wire _21;
wire _100;
wire _22;
wire _102;
wire _23;
wire _52 = 1'b0;
wire _104;
wire _24;
wire _106;
wire _25;
wire _108;
wire _26;
wire _57;
wire _60;
wire _110;
wire _27;
wire _112;
wire _28;
wire _114;
wire _29;
wire _116;
wire _30;
wire _118;
wire _31;
wire _120;
wire _32;
wire _122;
wire _33;
wire _124;
wire _34;
wire _126;
wire _35;
wire _75;
wire _78;
wire _128;
wire _36;
wire _130;
wire _37;
wire _132;
wire _38;
wire _134;
wire _39;
wire _136;
wire _40;
wire _138;
wire _41;
wire _140;
wire _42;
wire _143;
wire _43;
wire _141;
wire _146;
wire _45;
wire _144;
wire _148;
wire _47;
wire _150;
wire _48;
wire _152;
wire _49;
wire _154;
wire _50;
wire [2:0] _155;
/* logic */
nand
the_nand
( .a(_52), .b(_2), .c(_54) );
assign _1 = _54;
nand
the_nand_0
( .a(_6), .b(_52), .c(_56) );
assign _2 = _56;
nand
the_nand_1
( .a(_57), .b(_4), .c(_59) );
assign _3 = _59;
nand
the_nand_2
( .a(_60), .b(_57), .c(_62) );
assign _4 = _62;
nand
the_nand_3
( .a(_60), .b(_4), .c(_64) );
assign _5 = _64;
nand
the_nand_4
( .a(_5), .b(_3), .c(_66) );
assign _6 = _66;
nand
the_nand_5
( .a(_6), .b(_2), .c(_68) );
assign _7 = _68;
nand
the_nand_6
( .a(_7), .b(_1), .c(_70) );
assign _8 = _70;
nand
the_nand_7
( .a(_32), .b(_10), .c(_72) );
assign _9 = _72;
nand
the_nand_8
( .a(_14), .b(_32), .c(_74) );
assign _10 = _74;
nand
the_nand_9
( .a(_75), .b(_12), .c(_77) );
assign _11 = _77;
nand
the_nand_10
( .a(_78), .b(_75), .c(_80) );
assign _12 = _80;
nand
the_nand_11
( .a(_78), .b(_12), .c(_82) );
assign _13 = _82;
nand
the_nand_12
( .a(_13), .b(_11), .c(_84) );
assign _14 = _84;
nand
the_nand_13
( .a(_14), .b(_10), .c(_86) );
assign _15 = _86;
nand
the_nand_14
( .a(_15), .b(_9), .c(_88) );
assign _16 = _88;
nand
the_nand_15
( .a(_41), .b(_42), .c(_90) );
assign _17 = _90;
nand
the_nand_16
( .a(_32), .b(_78), .c(_92) );
assign _18 = _92;
nand
the_nand_17
( .a(_18), .b(_18), .c(_94) );
assign _19 = _94;
nand
the_nand_18
( .a(_19), .b(_19), .c(_96) );
assign _20 = _96;
nand
the_nand_19
( .a(_52), .b(_60), .c(_98) );
assign _21 = _98;
nand
the_nand_20
( .a(_21), .b(_21), .c(_100) );
assign _22 = _100;
nand
the_nand_21
( .a(_22), .b(_22), .c(_102) );
assign _23 = _102;
nand
the_nand_22
( .a(_57), .b(_52), .c(_104) );
assign _24 = _104;
nand
the_nand_23
( .a(_24), .b(_24), .c(_106) );
assign _25 = _106;
nand
the_nand_24
( .a(_25), .b(_25), .c(_108) );
assign _26 = _108;
assign _57 = b[0:0];
assign _60 = a[0:0];
nand
the_nand_25
( .a(_60), .b(_57), .c(_110) );
assign _27 = _110;
nand
the_nand_26
( .a(_27), .b(_27), .c(_112) );
assign _28 = _112;
nand
the_nand_27
( .a(_28), .b(_28), .c(_114) );
assign _29 = _114;
nand
the_nand_28
( .a(_29), .b(_26), .c(_116) );
assign _30 = _116;
nand
the_nand_29
( .a(_30), .b(_30), .c(_118) );
assign _31 = _118;
nand
the_nand_30
( .a(_31), .b(_23), .c(_120) );
assign _32 = _120;
nand
the_nand_31
( .a(_75), .b(_32), .c(_122) );
assign _33 = _122;
nand
the_nand_32
( .a(_33), .b(_33), .c(_124) );
assign _34 = _124;
nand
the_nand_33
( .a(_34), .b(_34), .c(_126) );
assign _35 = _126;
assign _75 = b[1:1];
assign _78 = a[1:1];
nand
the_nand_34
( .a(_78), .b(_75), .c(_128) );
assign _36 = _128;
nand
the_nand_35
( .a(_36), .b(_36), .c(_130) );
assign _37 = _130;
nand
the_nand_36
( .a(_37), .b(_37), .c(_132) );
assign _38 = _132;
nand
the_nand_37
( .a(_38), .b(_35), .c(_134) );
assign _39 = _134;
nand
the_nand_38
( .a(_39), .b(_39), .c(_136) );
assign _40 = _136;
nand
the_nand_39
( .a(_40), .b(_20), .c(_138) );
assign _41 = _138;
nand
the_nand_40
( .a(_48), .b(_41), .c(_140) );
assign _42 = _140;
nand
the_nand_41
( .a(_141), .b(_45), .c(_143) );
assign _43 = _143;
assign _141 = b[2:2];
nand
the_nand_42
( .a(_144), .b(_141), .c(_146) );
assign _45 = _146;
assign _144 = a[2:2];
nand
the_nand_43
( .a(_144), .b(_45), .c(_148) );
assign _47 = _148;
nand
the_nand_44
( .a(_47), .b(_43), .c(_150) );
assign _48 = _150;
nand
the_nand_45
( .a(_48), .b(_42), .c(_152) );
assign _49 = _152;
nand
the_nand_46
( .a(_49), .b(_17), .c(_154) );
assign _50 = _154;
assign _155 = { _50, _16, _8 };
/* aliases */
/* output assignments */
assign c = _155;
endmodule |}]
;;
module Fpga_nand = Comb.Make (Comb.Make_primitives (Make_nand_gates (struct
module Bits = Signal
open Signal
let nand_lut a b =
Map.find_exn
(Instantiation.create
()
~name:"LUT2"
~parameters:[ Parameter.create ~name:"INIT" ~value:(String "1110") ]
~inputs:[ "I", a @: b ]
~outputs:[ "O", 1 ])
"O"
;;
let nand a b =
assert (width a = width b);
concat_msb (List.map2_exn (bits_msb a) (bits_msb b) ~f:nand_lut)
;;
end)))
let%expect_test "3 bit adder, FPGA style, verilog" =
let open Signal in
let a, b = input "a" 3, input "b" 3 in
let c = output "c" Fpga_nand.(a +: b) in
let circuit = Circuit.create_exn ~name:"adder_nand" [ c ] in
Rtl.print Verilog circuit;
[%expect
{|
module adder_nand (
b,
a,
c
);
input [2:0] b;
input [2:0] a;
output [2:0] c;
/* signal declarations */
wire [1:0] _53;
wire _55;
wire _1;
wire [1:0] _56;
wire _58;
wire _2;
wire [1:0] _60;
wire _62;
wire _3;
wire [1:0] _64;
wire _66;
wire _4;
wire [1:0] _67;
wire _69;
wire _5;
wire [1:0] _70;
wire _72;
wire _6;
wire [1:0] _73;
wire _75;
wire _7;
wire [1:0] _76;
wire _78;
wire _8;
wire [1:0] _79;
wire _81;
wire _9;
wire [1:0] _82;
wire _84;
wire _10;
wire [1:0] _86;
wire _88;
wire _11;
wire [1:0] _90;
wire _92;
wire _12;
wire [1:0] _93;
wire _95;
wire _13;
wire [1:0] _96;
wire _98;
wire _14;
wire [1:0] _99;
wire _101;
wire _15;
wire [1:0] _102;
wire _104;
wire _16;
wire [1:0] _105;
wire _107;
wire _17;
wire [1:0] _108;
wire _110;
wire _18;
wire [1:0] _111;
wire _113;
wire _19;
wire [1:0] _114;
wire _116;
wire _20;
wire [1:0] _117;
wire _119;
wire _21;
wire [1:0] _120;
wire _122;
wire _22;
wire [1:0] _123;
wire _125;
wire _23;
wire _52 = 1'b0;
wire [1:0] _126;
wire _128;
wire _24;
wire [1:0] _129;
wire _131;
wire _25;
wire [1:0] _132;
wire _134;
wire _26;
wire _59;
wire _63;
wire [1:0] _135;
wire _137;
wire _27;
wire [1:0] _138;
wire _140;
wire _28;
wire [1:0] _141;
wire _143;
wire _29;
wire [1:0] _144;
wire _146;
wire _30;
wire [1:0] _147;
wire _149;
wire _31;
wire [1:0] _150;
wire _152;
wire _32;
wire [1:0] _153;
wire _155;
wire _33;
wire [1:0] _156;
wire _158;
wire _34;
wire [1:0] _159;
wire _161;
wire _35;
wire _85;
wire _89;
wire [1:0] _162;
wire _164;
wire _36;
wire [1:0] _165;
wire _167;
wire _37;
wire [1:0] _168;
wire _170;
wire _38;
wire [1:0] _171;
wire _173;
wire _39;
wire [1:0] _174;
wire _176;
wire _40;
wire [1:0] _177;
wire _179;
wire _41;
wire [1:0] _180;
wire _182;
wire _42;
wire [1:0] _184;
wire _186;
wire _43;
wire _183;
wire [1:0] _188;
wire _190;
wire _45;
wire _187;
wire [1:0] _191;
wire _193;
wire _47;
wire [1:0] _194;
wire _196;
wire _48;
wire [1:0] _197;
wire _199;
wire _49;
wire [1:0] _200;
wire _202;
wire _50;
wire [2:0] _203;
/* logic */
assign _53 = { _52, _2 };
LUT2
#( .INIT("1110") )
the_LUT2
( .I(_53), .O(_55) );
assign _1 = _55;
assign _56 = { _6, _52 };
LUT2
#( .INIT("1110") )
the_LUT2_0
( .I(_56), .O(_58) );
assign _2 = _58;
assign _60 = { _59, _4 };
LUT2
#( .INIT("1110") )
the_LUT2_1
( .I(_60), .O(_62) );
assign _3 = _62;
assign _64 = { _63, _59 };
LUT2
#( .INIT("1110") )
the_LUT2_2
( .I(_64), .O(_66) );
assign _4 = _66;
assign _67 = { _63, _4 };
LUT2
#( .INIT("1110") )
the_LUT2_3
( .I(_67), .O(_69) );
assign _5 = _69;
assign _70 = { _5, _3 };
LUT2
#( .INIT("1110") )
the_LUT2_4
( .I(_70), .O(_72) );
assign _6 = _72;
assign _73 = { _6, _2 };
LUT2
#( .INIT("1110") )
the_LUT2_5
( .I(_73), .O(_75) );
assign _7 = _75;
assign _76 = { _7, _1 };
LUT2
#( .INIT("1110") )
the_LUT2_6
( .I(_76), .O(_78) );
assign _8 = _78;
assign _79 = { _32, _10 };
LUT2
#( .INIT("1110") )
the_LUT2_7
( .I(_79), .O(_81) );
assign _9 = _81;
assign _82 = { _14, _32 };
LUT2
#( .INIT("1110") )
the_LUT2_8
( .I(_82), .O(_84) );
assign _10 = _84;
assign _86 = { _85, _12 };
LUT2
#( .INIT("1110") )
the_LUT2_9
( .I(_86), .O(_88) );
assign _11 = _88;
assign _90 = { _89, _85 };
LUT2
#( .INIT("1110") )
the_LUT2_10
( .I(_90), .O(_92) );
assign _12 = _92;
assign _93 = { _89, _12 };
LUT2
#( .INIT("1110") )
the_LUT2_11
( .I(_93), .O(_95) );
assign _13 = _95;
assign _96 = { _13, _11 };
LUT2
#( .INIT("1110") )
the_LUT2_12
( .I(_96), .O(_98) );
assign _14 = _98;
assign _99 = { _14, _10 };
LUT2
#( .INIT("1110") )
the_LUT2_13
( .I(_99), .O(_101) );
assign _15 = _101;
assign _102 = { _15, _9 };
LUT2
#( .INIT("1110") )
the_LUT2_14
( .I(_102), .O(_104) );
assign _16 = _104;
assign _105 = { _41, _42 };
LUT2
#( .INIT("1110") )
the_LUT2_15
( .I(_105), .O(_107) );
assign _17 = _107;
assign _108 = { _32, _89 };
LUT2
#( .INIT("1110") )
the_LUT2_16
( .I(_108), .O(_110) );
assign _18 = _110;
assign _111 = { _18, _18 };
LUT2
#( .INIT("1110") )
the_LUT2_17
( .I(_111), .O(_113) );
assign _19 = _113;
assign _114 = { _19, _19 };
LUT2
#( .INIT("1110") )
the_LUT2_18
( .I(_114), .O(_116) );
assign _20 = _116;
assign _117 = { _52, _63 };
LUT2
#( .INIT("1110") )
the_LUT2_19
( .I(_117), .O(_119) );
assign _21 = _119;
assign _120 = { _21, _21 };
LUT2
#( .INIT("1110") )
the_LUT2_20
( .I(_120), .O(_122) );
assign _22 = _122;
assign _123 = { _22, _22 };
LUT2
#( .INIT("1110") )
the_LUT2_21
( .I(_123), .O(_125) );
assign _23 = _125;
assign _126 = { _59, _52 };
LUT2
#( .INIT("1110") )
the_LUT2_22
( .I(_126), .O(_128) );
assign _24 = _128;
assign _129 = { _24, _24 };
LUT2
#( .INIT("1110") )
the_LUT2_23
( .I(_129), .O(_131) );
assign _25 = _131;
assign _132 = { _25, _25 };
LUT2
#( .INIT("1110") )
the_LUT2_24
( .I(_132), .O(_134) );
assign _26 = _134;
assign _59 = b[0:0];
assign _63 = a[0:0];
assign _135 = { _63, _59 };
LUT2
#( .INIT("1110") )
the_LUT2_25
( .I(_135), .O(_137) );
assign _27 = _137;
assign _138 = { _27, _27 };
LUT2
#( .INIT("1110") )
the_LUT2_26
( .I(_138), .O(_140) );
assign _28 = _140;
assign _141 = { _28, _28 };
LUT2
#( .INIT("1110") )
the_LUT2_27
( .I(_141), .O(_143) );
assign _29 = _143;
assign _144 = { _29, _26 };
LUT2
#( .INIT("1110") )
the_LUT2_28
( .I(_144), .O(_146) );
assign _30 = _146;
assign _147 = { _30, _30 };
LUT2
#( .INIT("1110") )
the_LUT2_29
( .I(_147), .O(_149) );
assign _31 = _149;
assign _150 = { _31, _23 };
LUT2
#( .INIT("1110") )
the_LUT2_30
( .I(_150), .O(_152) );
assign _32 = _152;
assign _153 = { _85, _32 };
LUT2
#( .INIT("1110") )
the_LUT2_31
( .I(_153), .O(_155) );
assign _33 = _155;
assign _156 = { _33, _33 };
LUT2
#( .INIT("1110") )
the_LUT2_32
( .I(_156), .O(_158) );
assign _34 = _158;
assign _159 = { _34, _34 };
LUT2
#( .INIT("1110") )
the_LUT2_33
( .I(_159), .O(_161) );
assign _35 = _161;
assign _85 = b[1:1];
assign _89 = a[1:1];
assign _162 = { _89, _85 };
LUT2
#( .INIT("1110") )
the_LUT2_34
( .I(_162), .O(_164) );
assign _36 = _164;
assign _165 = { _36, _36 };
LUT2
#( .INIT("1110") )
the_LUT2_35
( .I(_165), .O(_167) );
assign _37 = _167;
assign _168 = { _37, _37 };
LUT2
#( .INIT("1110") )
the_LUT2_36
( .I(_168), .O(_170) );
assign _38 = _170;
assign _171 = { _38, _35 };
LUT2
#( .INIT("1110") )
the_LUT2_37
( .I(_171), .O(_173) );
assign _39 = _173;
assign _174 = { _39, _39 };
LUT2
#( .INIT("1110") )
the_LUT2_38
( .I(_174), .O(_176) );
assign _40 = _176;
assign _177 = { _40, _20 };
LUT2
#( .INIT("1110") )
the_LUT2_39
( .I(_177), .O(_179) );
assign _41 = _179;
assign _180 = { _48, _41 };
LUT2
#( .INIT("1110") )
the_LUT2_40
( .I(_180), .O(_182) );
assign _42 = _182;
assign _184 = { _183, _45 };
LUT2
#( .INIT("1110") )
the_LUT2_41
( .I(_184), .O(_186) );
assign _43 = _186;
assign _183 = b[2:2];
assign _188 = { _187, _183 };
LUT2
#( .INIT("1110") )
the_LUT2_42
( .I(_188), .O(_190) );
assign _45 = _190;
assign _187 = a[2:2];
assign _191 = { _187, _45 };
LUT2
#( .INIT("1110") )
the_LUT2_43
( .I(_191), .O(_193) );
assign _47 = _193;
assign _194 = { _47, _43 };
LUT2
#( .INIT("1110") )
the_LUT2_44
( .I(_194), .O(_196) );
assign _48 = _196;
assign _197 = { _48, _42 };
LUT2
#( .INIT("1110") )
the_LUT2_45
( .I(_197), .O(_199) );
assign _49 = _199;
assign _200 = { _49, _17 };
LUT2
#( .INIT("1110") )
the_LUT2_46
( .I(_200), .O(_202) );
assign _50 = _202;
assign _203 = { _50, _16, _8 };
/* aliases */
/* output assignments */
assign c = _203;
endmodule |}]
;;
|
a4fa7275ef6a12a8083c047e271ffb0018f0d9f2125214e6ef8ce80c275678bd | rumblesan/improviz | PostProcessing.hs | # LANGUAGE TemplateHaskell #
module Gfx.PostProcessing
( createPostProcessing
, renderPostProcessing
, usePostProcessing
, deletePostProcessing
, createTextDisplaybuffer
, deleteSavebuffer
, filterVars
, PostProcessingConfig(..)
, Savebuffer(..)
, AnimationStyle(..)
) where
import Configuration.Shaders
import Control.Monad.State.Strict
import Data.Either ( partitionEithers )
import qualified Data.Map.Strict as M
import Graphics.Rendering.OpenGL as GL
import Lens.Simple ( (^.)
, makeLenses
, use
, uses
)
import qualified Util.SettingMap as SM
import Foreign.Marshal.Array ( withArray )
import Foreign.Ptr ( nullPtr )
import Foreign.Storable ( sizeOf )
import Data.FileEmbed ( embedStringFile )
import Gfx.LoadShaders ( ShaderInfo(..)
, ShaderSource(..)
, loadShaders
)
import Gfx.OpenGL ( valueToUniform )
import Gfx.Shaders ( getAttribLoc
, getUniformLoc
)
import Gfx.VertexBuffers ( VBO
, createVBO
, deleteVBO
, drawVBO
, setAttribPointer
)
import Language.Ast ( Value )
import Logging ( logError
, logInfo
)
data AnimationStyle
= NormalStyle
| UserFilter String
deriving (Eq, Show)
type PostProcessing v = StateT PostProcessingConfig IO v
runPostProcessing :: PostProcessingConfig -> PostProcessing v -> IO v
runPostProcessing post f = evalStateT f post
-- Simple Framebuffer with a texture that can be rendered to and then drawn out to a quad
data Savebuffer = Savebuffer FramebufferObject
TextureObject
TextureObject
Program
VBO
instance Show Savebuffer where
show _ = "Savebuffer"
data PostFilter = PostFilter FramebufferObject
TextureObject
TextureObject
PostProcessingShader
VBO
data PostProcessingShader = PostProcessingShader
{ ppName :: String
, ppProgram :: GL.Program
, ppUniforms :: [(String, GL.VariableType, GL.UniformLocation)]
, ppAttributes :: [(String, GL.VariableType, GL.AttribLocation)]
}
deriving (Show, Eq)
type FilterVars = SM.SettingMap String Value
data PostProcessingConfig = PostProcessingConfig
{ _input :: Savebuffer
, _output :: Savebuffer
, _userFilters :: M.Map String PostFilter
, _filterVars :: FilterVars
}
makeLenses ''PostProcessingConfig
instance Show PostProcessingConfig where
show _ = "PostProcessingConfig"
loadPostProcessingShader :: ShaderData -> IO PostProcessingShader
loadPostProcessingShader (ShaderData name vertShader fragShader) = do
program <- loadShaders
[ ShaderInfo GL.VertexShader (StringSource vertShader)
, ShaderInfo GL.FragmentShader (StringSource fragShader)
]
GL.currentProgram $= Just program
uniformInfo <- GL.get $ GL.activeUniforms program
uniforms <- mapM (getUniformLoc program) uniformInfo
attribInfo <- GL.get $ GL.activeAttribs program
attributes <- mapM (getAttribLoc program) attribInfo
return $ PostProcessingShader name program uniforms attributes
-- 2D positions and texture coordinates
-- brittany-disable-next-binding
ordinaryQuadVertices :: [GLfloat]
ordinaryQuadVertices = [ -1, 1, 0, 1 -- v1
, 1, 1, 1, 1 -- v2
, -1, -1, 0, 0 -- v3
, -1, -1, 0, 0 -- v4
, 1, 1, 1, 1 -- v5
v6
]
-- brittany-disable-next-binding
textQuadVertices :: [GLfloat]
textQuadVertices = [ -1, 1, 0, 0 -- v1
, 1, 1, 1, 0 -- v2
, -1, -1, 0, 1 -- v3
, -1, -1, 0, 1 -- v4
, 1, 1, 1, 0 -- v5
v6
]
createQuadVBO :: [GLfloat] -> IO VBO
createQuadVBO quadVertices =
let vertexSize = fromIntegral $ sizeOf (head quadVertices)
posVSize = 2
texVSize = 2
firstPosIndex = 0
firstTexIndex = posVSize * vertexSize
vPosition = AttribLocation 0
vTexCoord = AttribLocation 1
numVertices = fromIntegral $ length quadVertices
size = fromIntegral (numVertices * vertexSize)
stride = fromIntegral ((posVSize + texVSize) * vertexSize)
numArrIdx = 6
quadConfig = do
withArray quadVertices
$ \ptr -> GL.bufferData ArrayBuffer $= (size, ptr, StaticDraw)
setAttribPointer vPosition posVSize stride firstPosIndex
setAttribPointer vTexCoord texVSize stride firstTexIndex
in createVBO [quadConfig] Triangles firstPosIndex numArrIdx
create2DTexture :: GLint -> GLint -> IO TextureObject
create2DTexture width height = do
text <- genObjectName
GL.textureBinding GL.Texture2D $= Just text
GL.textureFilter GL.Texture2D $= ((GL.Linear', Nothing), GL.Linear')
let pd = PixelData RGBA UnsignedByte nullPtr
GL.texImage2D Texture2D NoProxy 0 RGBA' (TextureSize2D width height) 0 pd
GL.textureBinding Texture2D $= Nothing
return text
createDepthbuffer :: GLint -> GLint -> IO TextureObject
createDepthbuffer width height = do
depth <- genObjectName
GL.textureBinding Texture2D $= Just depth
GL.textureFilter GL.Texture2D $= ((GL.Linear', Nothing), GL.Linear')
let pd = PixelData DepthComponent UnsignedByte nullPtr
GL.texImage2D Texture2D
NoProxy
0
DepthComponent24
(TextureSize2D width height)
0
pd
GL.framebufferTexture2D Framebuffer DepthAttachment Texture2D depth 0
GL.textureBinding Texture2D $= Nothing
return depth
createPostProcessing :: [FilePath] -> Int -> Int -> IO PostProcessingConfig
createPostProcessing filterDirectories w h =
let width = fromIntegral w
height = fromIntegral h
in do
inputBuffer <- createSaveBuffer
width
height
ordinaryQuadVertices
$(embedStringFile "src/assets/shaders/savebuffer.vert")
$(embedStringFile "src/assets/shaders/savebuffer.frag")
outputBuffer <- createSaveBuffer
width
height
ordinaryQuadVertices
$(embedStringFile "src/assets/shaders/savebuffer.vert")
$(embedStringFile "src/assets/shaders/savebuffer.frag")
(loadedFilters, varDefaults) <- loadFilterDirectories filterDirectories
userFilters <- mapM (createPostProcessingFilter width height ordinaryQuadVertices) loadedFilters
return $ PostProcessingConfig inputBuffer outputBuffer userFilters varDefaults
deletePostProcessing :: PostProcessingConfig -> IO ()
deletePostProcessing post = do
deleteSavebuffer $ post ^. input
deleteSavebuffer $ post ^. output
mapM_ deletePostFilter $ post ^. userFilters
createTextDisplaybuffer :: GLint -> GLint -> IO Savebuffer
createTextDisplaybuffer width height =
createSaveBuffer
width
height
textQuadVertices
$(embedStringFile "src/assets/shaders/savebuffer.vert")
$(embedStringFile "src/assets/shaders/savebuffer.frag")
createSaveBuffer
:: GLint -> GLint -> [GLfloat] -> String -> String -> IO Savebuffer
createSaveBuffer width height vertices vertShader fragShader = do
fbo <- genObjectName
GL.bindFramebuffer Framebuffer $= fbo
text <- create2DTexture width height
GL.framebufferTexture2D Framebuffer (ColorAttachment 0) Texture2D text 0
depth <- createDepthbuffer width height
qvbo <- createQuadVBO vertices
program <- loadShaders
[ ShaderInfo VertexShader (StringSource vertShader)
, ShaderInfo FragmentShader (StringSource fragShader)
]
return $ Savebuffer fbo text depth program qvbo
deleteSavebuffer :: Savebuffer -> IO ()
deleteSavebuffer (Savebuffer sbfbo sbtext sbdepth sbprogram sbvbo) = do
deleteObjectName sbtext
deleteObjectName sbdepth
deleteObjectName sbprogram
deleteVBO sbvbo
deleteObjectName sbfbo
deletePostFilter :: PostFilter -> IO ()
deletePostFilter (PostFilter mfbo mtext depth shader mbvbo) = do
deleteObjectName mtext
deleteObjectName depth
deleteObjectName (ppProgram shader)
deleteVBO mbvbo
deleteObjectName mfbo
createPostProcessingFilter
:: GLint -> GLint -> [GLfloat] -> PostProcessingShader -> IO PostFilter
createPostProcessingFilter width height vertices shader = do
fbo <- genObjectName
bindFramebuffer Framebuffer $= fbo
text <- create2DTexture width height
framebufferTexture2D Framebuffer (ColorAttachment 0) Texture2D text 0
depth <- createDepthbuffer width height
qvbo <- createQuadVBO vertices
return $ PostFilter fbo text depth shader qvbo
usePostProcessing :: PostProcessingConfig -> IO ()
usePostProcessing post = runPostProcessing post usePostProcessingST
usePostProcessingST :: PostProcessing ()
usePostProcessingST = do
(Savebuffer fbo _ _ _ _) <- use input
liftIO $ bindFramebuffer Framebuffer $= fbo
renderPostProcessing
:: PostProcessingConfig -> FilterVars -> AnimationStyle -> IO ()
renderPostProcessing post postVars animStyle =
runPostProcessing post (renderPostProcessingST postVars animStyle)
renderPostProcessingST :: FilterVars -> AnimationStyle -> PostProcessing ()
renderPostProcessingST postVars animStyle = do
outbuffer@(Savebuffer outFBO previousFrame _ _ _) <- use output
liftIO $ do
depthFunc $= Nothing
bindFramebuffer Framebuffer $= outFBO
case animStyle of
NormalStyle -> use input >>= renderSavebuffer
UserFilter name -> do
maybeFilter <- uses userFilters (M.lookup name)
case maybeFilter of
Nothing -> use input >>= renderSavebuffer
Just filterBuffer -> renderPostProcessingFilter postVars filterBuffer
liftIO (bindFramebuffer Framebuffer $= defaultFramebufferObject)
renderSavebuffer outbuffer
renderSavebuffer :: Savebuffer -> PostProcessing ()
renderSavebuffer (Savebuffer _ text _ program quadVBO) = liftIO $ do
currentProgram $= Just program
activeTexture $= TextureUnit 0
textureBinding Texture2D $= Just text
drawVBO quadVBO
setUniform
:: FilterVars
-> (String, GL.VariableType, UniformLocation)
-> PostProcessing ()
setUniform _ ("texFramebuffer", _, uniformLoc) = do
(Savebuffer _ sceneFrame _ _ _) <- use input
liftIO $ do
activeTexture $= TextureUnit 0
textureBinding Texture2D $= Just sceneFrame
uniform uniformLoc $= TextureUnit 0
setUniform _ ("lastFrame", _, uniformLoc) = do
(Savebuffer _ lastFrame _ _ _) <- use output
liftIO $ do
activeTexture $= TextureUnit 1
textureBinding Texture2D $= Just lastFrame
uniform uniformLoc $= TextureUnit 1
setUniform _ ("depth", _, uniformLoc) = do
(Savebuffer _ _ depth _ _) <- use input
liftIO $ do
activeTexture $= TextureUnit 2
textureBinding Texture2D $= Just depth
uniform uniformLoc $= TextureUnit 2
setUniform filterVars (name, uniformType, uniformLoc) = do
let filtVar = filterVars ^. SM.value name
liftIO $ case filtVar of
Nothing -> logError $ name ++ " is not a known uniform"
Just v -> valueToUniform v uniformType uniformLoc
renderPostProcessingFilter :: FilterVars -> PostFilter -> PostProcessing ()
renderPostProcessingFilter postVars (PostFilter _ _ _ shader quadVBO) = do
liftIO (currentProgram $= (Just $ ppProgram shader))
mapM_ (setUniform postVars) (ppUniforms shader)
liftIO $ drawVBO quadVBO
loadFilterDirectories
:: [FilePath] -> IO (M.Map String PostProcessingShader, FilterVars)
loadFilterDirectories folders = do
loadedFolders <- mapM loadShaderFolder folders
let (folderLoadingErrs, parsedShaders) =
partitionEithers $ concat $ fmap fst loadedFolders
mapM_ logError folderLoadingErrs
loadedFilters <- mapM loadPostProcessingShader parsedShaders
--let (shaderLoadingErrs, ppShaders) = partitionEithers loadedFilters
mapM _ logError shaderLoadingErrs
let varDefaults = concat $ fmap snd loadedFolders
logInfo
$ "Loaded "
++ show (length varDefaults)
++ " post processing defaults"
logInfo
$ "Loaded "
++ show (length loadedFilters)
++ " post processing filter files"
return
$ ( M.fromList $ (\ps -> (ppName ps, ps)) <$> loadedFilters
, SM.create varDefaults
)
| null | https://raw.githubusercontent.com/rumblesan/improviz/08cf33f0ff197e1914135743273cd471f60924c6/src/Gfx/PostProcessing.hs | haskell | Simple Framebuffer with a texture that can be rendered to and then drawn out to a quad
2D positions and texture coordinates
brittany-disable-next-binding
v1
v2
v3
v4
v5
brittany-disable-next-binding
v1
v2
v3
v4
v5
let (shaderLoadingErrs, ppShaders) = partitionEithers loadedFilters | # LANGUAGE TemplateHaskell #
module Gfx.PostProcessing
( createPostProcessing
, renderPostProcessing
, usePostProcessing
, deletePostProcessing
, createTextDisplaybuffer
, deleteSavebuffer
, filterVars
, PostProcessingConfig(..)
, Savebuffer(..)
, AnimationStyle(..)
) where
import Configuration.Shaders
import Control.Monad.State.Strict
import Data.Either ( partitionEithers )
import qualified Data.Map.Strict as M
import Graphics.Rendering.OpenGL as GL
import Lens.Simple ( (^.)
, makeLenses
, use
, uses
)
import qualified Util.SettingMap as SM
import Foreign.Marshal.Array ( withArray )
import Foreign.Ptr ( nullPtr )
import Foreign.Storable ( sizeOf )
import Data.FileEmbed ( embedStringFile )
import Gfx.LoadShaders ( ShaderInfo(..)
, ShaderSource(..)
, loadShaders
)
import Gfx.OpenGL ( valueToUniform )
import Gfx.Shaders ( getAttribLoc
, getUniformLoc
)
import Gfx.VertexBuffers ( VBO
, createVBO
, deleteVBO
, drawVBO
, setAttribPointer
)
import Language.Ast ( Value )
import Logging ( logError
, logInfo
)
data AnimationStyle
= NormalStyle
| UserFilter String
deriving (Eq, Show)
type PostProcessing v = StateT PostProcessingConfig IO v
runPostProcessing :: PostProcessingConfig -> PostProcessing v -> IO v
runPostProcessing post f = evalStateT f post
data Savebuffer = Savebuffer FramebufferObject
TextureObject
TextureObject
Program
VBO
instance Show Savebuffer where
show _ = "Savebuffer"
data PostFilter = PostFilter FramebufferObject
TextureObject
TextureObject
PostProcessingShader
VBO
data PostProcessingShader = PostProcessingShader
{ ppName :: String
, ppProgram :: GL.Program
, ppUniforms :: [(String, GL.VariableType, GL.UniformLocation)]
, ppAttributes :: [(String, GL.VariableType, GL.AttribLocation)]
}
deriving (Show, Eq)
type FilterVars = SM.SettingMap String Value
data PostProcessingConfig = PostProcessingConfig
{ _input :: Savebuffer
, _output :: Savebuffer
, _userFilters :: M.Map String PostFilter
, _filterVars :: FilterVars
}
makeLenses ''PostProcessingConfig
instance Show PostProcessingConfig where
show _ = "PostProcessingConfig"
loadPostProcessingShader :: ShaderData -> IO PostProcessingShader
loadPostProcessingShader (ShaderData name vertShader fragShader) = do
program <- loadShaders
[ ShaderInfo GL.VertexShader (StringSource vertShader)
, ShaderInfo GL.FragmentShader (StringSource fragShader)
]
GL.currentProgram $= Just program
uniformInfo <- GL.get $ GL.activeUniforms program
uniforms <- mapM (getUniformLoc program) uniformInfo
attribInfo <- GL.get $ GL.activeAttribs program
attributes <- mapM (getAttribLoc program) attribInfo
return $ PostProcessingShader name program uniforms attributes
ordinaryQuadVertices :: [GLfloat]
v6
]
textQuadVertices :: [GLfloat]
v6
]
createQuadVBO :: [GLfloat] -> IO VBO
createQuadVBO quadVertices =
let vertexSize = fromIntegral $ sizeOf (head quadVertices)
posVSize = 2
texVSize = 2
firstPosIndex = 0
firstTexIndex = posVSize * vertexSize
vPosition = AttribLocation 0
vTexCoord = AttribLocation 1
numVertices = fromIntegral $ length quadVertices
size = fromIntegral (numVertices * vertexSize)
stride = fromIntegral ((posVSize + texVSize) * vertexSize)
numArrIdx = 6
quadConfig = do
withArray quadVertices
$ \ptr -> GL.bufferData ArrayBuffer $= (size, ptr, StaticDraw)
setAttribPointer vPosition posVSize stride firstPosIndex
setAttribPointer vTexCoord texVSize stride firstTexIndex
in createVBO [quadConfig] Triangles firstPosIndex numArrIdx
create2DTexture :: GLint -> GLint -> IO TextureObject
create2DTexture width height = do
text <- genObjectName
GL.textureBinding GL.Texture2D $= Just text
GL.textureFilter GL.Texture2D $= ((GL.Linear', Nothing), GL.Linear')
let pd = PixelData RGBA UnsignedByte nullPtr
GL.texImage2D Texture2D NoProxy 0 RGBA' (TextureSize2D width height) 0 pd
GL.textureBinding Texture2D $= Nothing
return text
createDepthbuffer :: GLint -> GLint -> IO TextureObject
createDepthbuffer width height = do
depth <- genObjectName
GL.textureBinding Texture2D $= Just depth
GL.textureFilter GL.Texture2D $= ((GL.Linear', Nothing), GL.Linear')
let pd = PixelData DepthComponent UnsignedByte nullPtr
GL.texImage2D Texture2D
NoProxy
0
DepthComponent24
(TextureSize2D width height)
0
pd
GL.framebufferTexture2D Framebuffer DepthAttachment Texture2D depth 0
GL.textureBinding Texture2D $= Nothing
return depth
createPostProcessing :: [FilePath] -> Int -> Int -> IO PostProcessingConfig
createPostProcessing filterDirectories w h =
let width = fromIntegral w
height = fromIntegral h
in do
inputBuffer <- createSaveBuffer
width
height
ordinaryQuadVertices
$(embedStringFile "src/assets/shaders/savebuffer.vert")
$(embedStringFile "src/assets/shaders/savebuffer.frag")
outputBuffer <- createSaveBuffer
width
height
ordinaryQuadVertices
$(embedStringFile "src/assets/shaders/savebuffer.vert")
$(embedStringFile "src/assets/shaders/savebuffer.frag")
(loadedFilters, varDefaults) <- loadFilterDirectories filterDirectories
userFilters <- mapM (createPostProcessingFilter width height ordinaryQuadVertices) loadedFilters
return $ PostProcessingConfig inputBuffer outputBuffer userFilters varDefaults
deletePostProcessing :: PostProcessingConfig -> IO ()
deletePostProcessing post = do
deleteSavebuffer $ post ^. input
deleteSavebuffer $ post ^. output
mapM_ deletePostFilter $ post ^. userFilters
createTextDisplaybuffer :: GLint -> GLint -> IO Savebuffer
createTextDisplaybuffer width height =
createSaveBuffer
width
height
textQuadVertices
$(embedStringFile "src/assets/shaders/savebuffer.vert")
$(embedStringFile "src/assets/shaders/savebuffer.frag")
createSaveBuffer
:: GLint -> GLint -> [GLfloat] -> String -> String -> IO Savebuffer
createSaveBuffer width height vertices vertShader fragShader = do
fbo <- genObjectName
GL.bindFramebuffer Framebuffer $= fbo
text <- create2DTexture width height
GL.framebufferTexture2D Framebuffer (ColorAttachment 0) Texture2D text 0
depth <- createDepthbuffer width height
qvbo <- createQuadVBO vertices
program <- loadShaders
[ ShaderInfo VertexShader (StringSource vertShader)
, ShaderInfo FragmentShader (StringSource fragShader)
]
return $ Savebuffer fbo text depth program qvbo
deleteSavebuffer :: Savebuffer -> IO ()
deleteSavebuffer (Savebuffer sbfbo sbtext sbdepth sbprogram sbvbo) = do
deleteObjectName sbtext
deleteObjectName sbdepth
deleteObjectName sbprogram
deleteVBO sbvbo
deleteObjectName sbfbo
deletePostFilter :: PostFilter -> IO ()
deletePostFilter (PostFilter mfbo mtext depth shader mbvbo) = do
deleteObjectName mtext
deleteObjectName depth
deleteObjectName (ppProgram shader)
deleteVBO mbvbo
deleteObjectName mfbo
createPostProcessingFilter
:: GLint -> GLint -> [GLfloat] -> PostProcessingShader -> IO PostFilter
createPostProcessingFilter width height vertices shader = do
fbo <- genObjectName
bindFramebuffer Framebuffer $= fbo
text <- create2DTexture width height
framebufferTexture2D Framebuffer (ColorAttachment 0) Texture2D text 0
depth <- createDepthbuffer width height
qvbo <- createQuadVBO vertices
return $ PostFilter fbo text depth shader qvbo
usePostProcessing :: PostProcessingConfig -> IO ()
usePostProcessing post = runPostProcessing post usePostProcessingST
usePostProcessingST :: PostProcessing ()
usePostProcessingST = do
(Savebuffer fbo _ _ _ _) <- use input
liftIO $ bindFramebuffer Framebuffer $= fbo
renderPostProcessing
:: PostProcessingConfig -> FilterVars -> AnimationStyle -> IO ()
renderPostProcessing post postVars animStyle =
runPostProcessing post (renderPostProcessingST postVars animStyle)
renderPostProcessingST :: FilterVars -> AnimationStyle -> PostProcessing ()
renderPostProcessingST postVars animStyle = do
outbuffer@(Savebuffer outFBO previousFrame _ _ _) <- use output
liftIO $ do
depthFunc $= Nothing
bindFramebuffer Framebuffer $= outFBO
case animStyle of
NormalStyle -> use input >>= renderSavebuffer
UserFilter name -> do
maybeFilter <- uses userFilters (M.lookup name)
case maybeFilter of
Nothing -> use input >>= renderSavebuffer
Just filterBuffer -> renderPostProcessingFilter postVars filterBuffer
liftIO (bindFramebuffer Framebuffer $= defaultFramebufferObject)
renderSavebuffer outbuffer
renderSavebuffer :: Savebuffer -> PostProcessing ()
renderSavebuffer (Savebuffer _ text _ program quadVBO) = liftIO $ do
currentProgram $= Just program
activeTexture $= TextureUnit 0
textureBinding Texture2D $= Just text
drawVBO quadVBO
setUniform
:: FilterVars
-> (String, GL.VariableType, UniformLocation)
-> PostProcessing ()
setUniform _ ("texFramebuffer", _, uniformLoc) = do
(Savebuffer _ sceneFrame _ _ _) <- use input
liftIO $ do
activeTexture $= TextureUnit 0
textureBinding Texture2D $= Just sceneFrame
uniform uniformLoc $= TextureUnit 0
setUniform _ ("lastFrame", _, uniformLoc) = do
(Savebuffer _ lastFrame _ _ _) <- use output
liftIO $ do
activeTexture $= TextureUnit 1
textureBinding Texture2D $= Just lastFrame
uniform uniformLoc $= TextureUnit 1
setUniform _ ("depth", _, uniformLoc) = do
(Savebuffer _ _ depth _ _) <- use input
liftIO $ do
activeTexture $= TextureUnit 2
textureBinding Texture2D $= Just depth
uniform uniformLoc $= TextureUnit 2
setUniform filterVars (name, uniformType, uniformLoc) = do
let filtVar = filterVars ^. SM.value name
liftIO $ case filtVar of
Nothing -> logError $ name ++ " is not a known uniform"
Just v -> valueToUniform v uniformType uniformLoc
renderPostProcessingFilter :: FilterVars -> PostFilter -> PostProcessing ()
renderPostProcessingFilter postVars (PostFilter _ _ _ shader quadVBO) = do
liftIO (currentProgram $= (Just $ ppProgram shader))
mapM_ (setUniform postVars) (ppUniforms shader)
liftIO $ drawVBO quadVBO
loadFilterDirectories
:: [FilePath] -> IO (M.Map String PostProcessingShader, FilterVars)
loadFilterDirectories folders = do
loadedFolders <- mapM loadShaderFolder folders
let (folderLoadingErrs, parsedShaders) =
partitionEithers $ concat $ fmap fst loadedFolders
mapM_ logError folderLoadingErrs
loadedFilters <- mapM loadPostProcessingShader parsedShaders
mapM _ logError shaderLoadingErrs
let varDefaults = concat $ fmap snd loadedFolders
logInfo
$ "Loaded "
++ show (length varDefaults)
++ " post processing defaults"
logInfo
$ "Loaded "
++ show (length loadedFilters)
++ " post processing filter files"
return
$ ( M.fromList $ (\ps -> (ppName ps, ps)) <$> loadedFilters
, SM.create varDefaults
)
|
02c0b312d2c08c8a3c3608fd7e41d1bf543d659b4e73ff8896734a461d469c2c | cram-code/cram_core | offline-task.lisp | ;;;
Copyright ( c ) 2009 - 2010
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT 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 :cram-execution-trace)
When saving a TASK - TREE , we do n't save the real TASK objects , but only the
;;; information we really need in offline knowledge. At the time of writing
;;; this is only the name of the status fluent and the result. So while
;;; reloading we create some fake objects that only support the part of the
;;; task / fluent API that we need. This might not be the most beautiful
;;; solution, but for now it works.
(defclass offline-fluent ()
((cpl-impl:name :initarg :name :reader cpl-impl:name
:type symbol)))
(defclass offline-task ()
((cpl-impl:status :initarg :status :reader cpl-impl:status
:type offline-fluent)
(cpl-impl:result :initarg :result :reader cpl-impl:result
:type (or list (member nil) condition)))) | null | https://raw.githubusercontent.com/cram-code/cram_core/984046abe2ec9e25b63e52007ed3b857c3d9a13c/cram_execution_trace/src/offline-task.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.
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.
information we really need in offline knowledge. At the time of writing
this is only the name of the status fluent and the result. So while
reloading we create some fake objects that only support the part of the
task / fluent API that we need. This might not be the most beautiful
solution, but for now it works. | Copyright ( c ) 2009 - 2010
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 :cram-execution-trace)
When saving a TASK - TREE , we do n't save the real TASK objects , but only the
(defclass offline-fluent ()
((cpl-impl:name :initarg :name :reader cpl-impl:name
:type symbol)))
(defclass offline-task ()
((cpl-impl:status :initarg :status :reader cpl-impl:status
:type offline-fluent)
(cpl-impl:result :initarg :result :reader cpl-impl:result
:type (or list (member nil) condition)))) |
b0d5ea6f28fec22c3b88d428436ba5c29dcbbd3fc15a287393179838be8d11ef | alt-romes/slfl | final-6-1.hs | newMArray :: Int -> (MArray a -o !b) -o b;
write :: MArray a -o (Int * a) -> MArray a;
freeze :: MArray a -o !(Array a);
foldl :: (a -o b -o a) -> a -o (List b) -o a;
synth array :: Int -> List (!(Int * a)) -> Array a | using (foldl) | depth 3;
| null | https://raw.githubusercontent.com/alt-romes/slfl/4956fcce8ff2ca7622799fe0715c118b568b74eb/STLLC/bench/final-6-1.hs | haskell | newMArray :: Int -> (MArray a -o !b) -o b;
write :: MArray a -o (Int * a) -> MArray a;
freeze :: MArray a -o !(Array a);
foldl :: (a -o b -o a) -> a -o (List b) -o a;
synth array :: Int -> List (!(Int * a)) -> Array a | using (foldl) | depth 3;
|
|
991d4a6a3f42af4e01056091d03329cd375b896f21e0035d070cf447ee6ad8e4 | eponai/sulolive | store.cljc | (ns eponai.common.ui.store
(:require
[eponai.common.ui.elements.css :as css]
[eponai.common.ui.chat :as chat]
[eponai.common.ui.common :as common]
[eponai.common.ui.product :as item]
[eponai.common.ui.stream :as stream]
[eponai.common.ui.om-quill :as quill]
[eponai.common.ui.router :as router]
[eponai.common.format :as f]
[eponai.client.routes :as routes]
[eponai.common.ui.dom :as dom]
[om.next :as om :refer [defui]]
[taoensso.timbre :refer [debug]]
[eponai.common.ui.elements.menu :as menu]
[eponai.common.ui.elements.grid :as grid]
[eponai.web.ui.photo :as photo]
[eponai.web.social :as social]
[eponai.common.photos :as photos]
[eponai.common.mixpanel :as mixpanel]
[eponai.common.ui.elements.callout :as callout]
[eponai.web.ui.button :as button]
#?(:cljs [eponai.web.firebase :as firebase])
[eponai.common.shared :as shared]
[eponai.common.ui.product :as product]
[eponai.common.database :as db]
[eponai.client.auth :as client.auth]
[eponai.web.ui.content-item :as ci]
[eponai.common :as c]))
(defn about-section [component]
(let [{:query/keys [store]} (om/props component)
{:store.profile/keys [description name]} (:store/profile store)]
(grid/row-column
nil
(dom/div
(css/callout)
(quill/->QuillRenderer {:html (f/bytes->str description)})))))
(defn policies-section [component]
(let [{:query/keys [store]} (om/props component)
{:store.profile/keys [return-policy]} (:store/profile store)
{shipping-policy :shipping/policy} (:store/shipping store)]
(grid/row-column
nil
(dom/div
(css/callout)
(dom/p nil (dom/strong nil "Returns"))
(quill/->QuillRenderer {:html (f/bytes->str return-policy)}))
(dom/div
(css/callout)
(dom/p nil (dom/strong nil "Shipping"))
(quill/->QuillRenderer {:html (f/bytes->str shipping-policy)})))))
(defn videos-section [component]
(let [{:query/keys [store-vods current-route store]} (om/props component)
{:keys [route route-params query-params]} current-route]
(grid/row
(grid/columns-in-row {:small 2 :medium 3})
(map (fn [vod]
(grid/column
nil
(ci/->StoreVod (om/computed vod
{:href (routes/store-url store :store route-params (assoc query-params :vod-timestamp (:vod/timestamp vod)))}))))
store-vods))))
(defn store-not-found [component]
(let [{:query/keys [store featured-stores]} (om/props component)]
[
(grid/row-column
(css/add-class :store-not-found (css/text-align :center))
(dom/div (css/add-classes [:not-found-code])
(dom/p (css/add-class :stat) "404"))
(dom/h1 nil "Store not found")
(dom/div (css/add-class :empty-container)
(dom/p (css/add-class :shoutout) "Oops, that store doesn't seem to exist."))
(button/store-navigation-default
{:href (routes/url :live)}
(dom/span nil "Browse stores")))
(grid/row-column
nil
(dom/hr nil)
(dom/div
(css/add-class :section-title)
(dom/h3 nil "New stores")))
(grid/row
(grid/columns-in-row {:small 2 :medium 5})
(map (fn [store]
(let [store-name (get-in store [:store/profile :store.profile/name])]
(grid/column
nil
(dom/div
(->> (css/add-class :content-item)
(css/add-class :stream-item))
(dom/a
{:href (routes/url :store {:store-id (:db/id store)})}
(photo/store-photo store {:transformation :transformation/thumbnail-large}))
(dom/div
(->> (css/add-class :text)
(css/add-class :header))
(dom/a {:href (routes/url :store {:store-id (:db/id store)})}
(dom/strong nil store-name)))))))
(take 5 featured-stores)))
]))
(defn store-url [store-id]
#?(:cljs (str js/window.location.origin (routes/url :store {:store-id store-id}))
:clj nil))
(defui Store
static om/IQuery
(query [_]
[
{:proxy/chat (om/get-query chat/StreamChat)}
{:query/store [:db/id
{:store/locality [:sulo-locality/path]}
{:store/sections [:store.section/label :store.section/path :db/id]}
:store/visitor-count
:store/username
{:store/geolocation [:geolocation/title]}
:store/not-found?
{:store/status [:status/type]}
{:stream/_store [:stream/state :stream/title]}
{:store/profile [:store.profile/name
:store.profile/description
:store.profile/tagline
:store.profile/return-policy
{:store.profile/photo [:photo/path :photo/id]}
{:store.profile/cover [:photo/path :photo/id]}]}
{:store/owners [{:store.owner/user [:user/online?]}]}
{:store/shipping [:shipping/policy]}]}
{:query/featured-items [:db/id
:store.item/name
:store.item/price
:store.item/created-at
{:store.item/photos [{:store.item.photo/photo [:photo/path :photo/id]}
:store.item.photo/index]}
{:store/_items [{:store/profile [:store.profile/name]}]}]}
{:query/featured-stores [:db/id
{:store/profile [:store.profile/name
{:store.profile/photo [:photo/path :photo/id]}]}
:store/created-at
:store/featured
{:store/items [:db/id {:store.item/photos [{:store.item.photo/photo [:photo/path :photo/id]}
:store.item.photo/index]}]}]}
{:query/store-vods (om/get-query ci/StoreVod)}
{:query/store-items (om/get-query ci/ProductItem)}
:query/current-route])
Object
(initLocalState [this]
{:selected-navigation :all-items})
(render [this]
(let [{:keys [fullscreen? ] :as st} (om/get-state this)
{:query/keys [store store-items current-route] :as props} (om/props this)
{:store/keys [profile visitor-count owners geolocation]
stream :stream/_store} store
{:store.profile/keys [photo cover tagline description]
store-name :store.profile/name} profile
stream (first stream)
is-live? (= :stream.state/live (:stream/state stream))
{:keys [route route-params query-params]} current-route
vod-timestamp (-> query-params :vod-timestamp c/parse-long-safe)
is-vod? (some? vod-timestamp)
show-chat? (:show-chat? st true)
store-status (get-in store [:store/status :status/type])
store-owner-online? (-> owners :store.owner/user :user/online?)
selected-navigation (:nav query-params)]
(debug "Store vods: " (:query/store-vods props))
(dom/div
{:id "sulo-store"}
(if (:store/not-found? store)
(store-not-found this)
[
(dom/h1 (css/show-for-sr) store-name)
(when (or (nil? store-status)
(= :status.type/closed store-status))
(callout/callout-small
(->> (css/text-align :center {:id "store-closed-banner"})
(css/add-classes [:alert :store-closed]))
(dom/div (css/add-class :sl-tooltip)
(dom/h3
(css/add-class :closed)
(dom/strong nil "Closed - "))
(dom/span (css/add-class :sl-tooltip-text)
"Only you can see your store. Customers who try to view your store will see a not found page."))
(dom/a {:href (routes/url :store-dashboard/profile#options route-params)}
(dom/span nil "Go to options"))))
(grid/row
(->> (grid/columns-in-row {:small 1})
(css/add-class :collapse)
(css/add-class :expanded))
(grid/column
(grid/column-order {:small 3 :medium 1})
(dom/div
(cond->> (css/add-class :stream-container)
show-chat?
(css/add-class :sulo-show-chat)
fullscreen?
(css/add-class :fullscreen))
(cond
(or is-live? is-vod?)
[
(stream/->Stream (om/computed {:stream stream}
{:stream-title (:stream/title stream)
:widescreen? true
:store store
:vod-timestamp vod-timestamp
:on-fullscreen-change #(om/update-state! this assoc :fullscreen? %)}))
(chat/->StreamChat (om/computed (:proxy/chat props)
{:on-toggle-chat (fn [show?]
(om/update-state! this assoc :show-chat? show?))
:is-vod? is-vod?
:store store
:stream-overlay? true
:visitor-count visitor-count
:show? show-chat?
:store-online-status store-owner-online?}))]
(some? cover)
(photo/store-cover store {:alt (str store-name " cover photo")}))))
(grid/column
(->> (grid/column-order {:small 1 :medium 3})
(css/add-class :store-container))
(grid/row
(->> (css/align :middle)
(css/align :center))
(grid/column
(grid/column-size {:small 12 :medium 2})
(photo/store-photo store {:transformation :transformation/thumbnail}))
(grid/column
(css/add-class :shrink)
(dom/p nil
(dom/strong nil store-name)
(when (not-empty (:geolocation/title geolocation))
[(dom/br nil)
(dom/small nil (:geolocation/title geolocation))])
(when (not-empty tagline)
[(dom/br nil)
(dom/i (css/add-class :tagline) tagline)])))
(grid/column
(->> (grid/column-size {:small 12 :medium 4 :large 3})
(css/text-align :center)
(css/add-class :follow-section))
(dom/div nil
(common/follow-button nil)
;(common/contact-button nil)
)))
))
(grid/row
(css/add-class :collapse)
(grid/column
(css/add-class :store-submenu)
(let [store-url (store-url (:store-id route-params))]
(menu/horizontal
(->> (css/align :right)
(css/add-class :share-menu))
(menu/item
nil
(social/share-button {:on-click #(mixpanel/track "Share on social media" {:platform "facebook"
:object "store"})
:platform :social/facebook
:href store-url}))
(menu/item
nil
(social/share-button {:on-click #(mixpanel/track "Share on social media" {:platform "twitter"
:object "store"})
:platform :social/twitter
:description (:store.profile/name profile)
:href store-url}))
(menu/item
nil
(social/share-button {:on-click #(mixpanel/track "Share on social media" {:platform "pinterest"
:object "store"})
:platform :social/pinterest
:href store-url
:description (:store.profile/name profile)
:media (photos/transform (:photo/id (:store.profile/photo profile))
:transformation/thumbnail)}))
))))
(dom/div
{:id "shop"}
(grid/row
(->> (css/add-class :collapse)
(css/add-class :menu-container))
(grid/column
nil
(menu/horizontal
(css/add-class :navigation)
(menu/item (cond->> (css/add-class :about)
(= selected-navigation "videos")
(css/add-class ::css/is-active))
(dom/a {:href (routes/store-url store :store route-params (assoc query-params :nav "videos"))}
(dom/span nil "Videos")))
(menu/item (cond->> (css/add-class :about)
(= selected-navigation "about")
(css/add-class ::css/is-active))
(dom/a {:href (routes/store-url store :store route-params (assoc query-params :nav "about"))}
(dom/span nil "About")))
(menu/item (cond->> (css/add-class :about)
(= selected-navigation "policies")
(css/add-class ::css/is-active))
(dom/a {:href (routes/store-url store :store route-params (assoc query-params :nav "policies"))}
(dom/span nil "Policies")))
(menu/item (when (and (= route :store) (nil? selected-navigation))
(css/add-class ::css/is-active))
(dom/a {:href (routes/store-url store :store route-params (dissoc query-params :nav))}
(dom/span nil "All Items")))
(map-indexed
(fn [i s]
(let [{:store.section/keys [label]} s
is-active? (and (= route :store) (= selected-navigation (str (:db/id s))))]
(menu/item
(cond->> {:key (+ 10 i)}
is-active?
(css/add-class ::css/is-active))
(dom/a
{:href (routes/store-url store :store route-params (assoc query-params :nav (:db/id s)))}
(dom/span nil label)))))
(:store/sections store)))))
(cond (= selected-navigation "about")
(about-section this)
(= selected-navigation "videos")
(videos-section this)
(= selected-navigation "policies")
(policies-section this)
:else
(let [selected-section (c/parse-long-safe selected-navigation)
products (sort-by :store.item/index
(if (and (= route :store) (number? selected-section))
(filter #(= (get-in % [:store.item/section :db/id]) selected-section) store-items)
store-items))]
(grid/products products
(fn [p]
(ci/->ProductItem (om/computed p
{:current-route current-route
:show-caption? true})))))))])))))
(def ->Store (om/factory Store))
(router/register-component :store Store) | null | https://raw.githubusercontent.com/eponai/sulolive/7a70701bbd3df6bbb92682679dcedb53f8822c18/src/eponai/common/ui/store.cljc | clojure | (common/contact-button nil) | (ns eponai.common.ui.store
(:require
[eponai.common.ui.elements.css :as css]
[eponai.common.ui.chat :as chat]
[eponai.common.ui.common :as common]
[eponai.common.ui.product :as item]
[eponai.common.ui.stream :as stream]
[eponai.common.ui.om-quill :as quill]
[eponai.common.ui.router :as router]
[eponai.common.format :as f]
[eponai.client.routes :as routes]
[eponai.common.ui.dom :as dom]
[om.next :as om :refer [defui]]
[taoensso.timbre :refer [debug]]
[eponai.common.ui.elements.menu :as menu]
[eponai.common.ui.elements.grid :as grid]
[eponai.web.ui.photo :as photo]
[eponai.web.social :as social]
[eponai.common.photos :as photos]
[eponai.common.mixpanel :as mixpanel]
[eponai.common.ui.elements.callout :as callout]
[eponai.web.ui.button :as button]
#?(:cljs [eponai.web.firebase :as firebase])
[eponai.common.shared :as shared]
[eponai.common.ui.product :as product]
[eponai.common.database :as db]
[eponai.client.auth :as client.auth]
[eponai.web.ui.content-item :as ci]
[eponai.common :as c]))
(defn about-section [component]
(let [{:query/keys [store]} (om/props component)
{:store.profile/keys [description name]} (:store/profile store)]
(grid/row-column
nil
(dom/div
(css/callout)
(quill/->QuillRenderer {:html (f/bytes->str description)})))))
(defn policies-section [component]
(let [{:query/keys [store]} (om/props component)
{:store.profile/keys [return-policy]} (:store/profile store)
{shipping-policy :shipping/policy} (:store/shipping store)]
(grid/row-column
nil
(dom/div
(css/callout)
(dom/p nil (dom/strong nil "Returns"))
(quill/->QuillRenderer {:html (f/bytes->str return-policy)}))
(dom/div
(css/callout)
(dom/p nil (dom/strong nil "Shipping"))
(quill/->QuillRenderer {:html (f/bytes->str shipping-policy)})))))
(defn videos-section [component]
(let [{:query/keys [store-vods current-route store]} (om/props component)
{:keys [route route-params query-params]} current-route]
(grid/row
(grid/columns-in-row {:small 2 :medium 3})
(map (fn [vod]
(grid/column
nil
(ci/->StoreVod (om/computed vod
{:href (routes/store-url store :store route-params (assoc query-params :vod-timestamp (:vod/timestamp vod)))}))))
store-vods))))
(defn store-not-found [component]
(let [{:query/keys [store featured-stores]} (om/props component)]
[
(grid/row-column
(css/add-class :store-not-found (css/text-align :center))
(dom/div (css/add-classes [:not-found-code])
(dom/p (css/add-class :stat) "404"))
(dom/h1 nil "Store not found")
(dom/div (css/add-class :empty-container)
(dom/p (css/add-class :shoutout) "Oops, that store doesn't seem to exist."))
(button/store-navigation-default
{:href (routes/url :live)}
(dom/span nil "Browse stores")))
(grid/row-column
nil
(dom/hr nil)
(dom/div
(css/add-class :section-title)
(dom/h3 nil "New stores")))
(grid/row
(grid/columns-in-row {:small 2 :medium 5})
(map (fn [store]
(let [store-name (get-in store [:store/profile :store.profile/name])]
(grid/column
nil
(dom/div
(->> (css/add-class :content-item)
(css/add-class :stream-item))
(dom/a
{:href (routes/url :store {:store-id (:db/id store)})}
(photo/store-photo store {:transformation :transformation/thumbnail-large}))
(dom/div
(->> (css/add-class :text)
(css/add-class :header))
(dom/a {:href (routes/url :store {:store-id (:db/id store)})}
(dom/strong nil store-name)))))))
(take 5 featured-stores)))
]))
(defn store-url [store-id]
#?(:cljs (str js/window.location.origin (routes/url :store {:store-id store-id}))
:clj nil))
(defui Store
static om/IQuery
(query [_]
[
{:proxy/chat (om/get-query chat/StreamChat)}
{:query/store [:db/id
{:store/locality [:sulo-locality/path]}
{:store/sections [:store.section/label :store.section/path :db/id]}
:store/visitor-count
:store/username
{:store/geolocation [:geolocation/title]}
:store/not-found?
{:store/status [:status/type]}
{:stream/_store [:stream/state :stream/title]}
{:store/profile [:store.profile/name
:store.profile/description
:store.profile/tagline
:store.profile/return-policy
{:store.profile/photo [:photo/path :photo/id]}
{:store.profile/cover [:photo/path :photo/id]}]}
{:store/owners [{:store.owner/user [:user/online?]}]}
{:store/shipping [:shipping/policy]}]}
{:query/featured-items [:db/id
:store.item/name
:store.item/price
:store.item/created-at
{:store.item/photos [{:store.item.photo/photo [:photo/path :photo/id]}
:store.item.photo/index]}
{:store/_items [{:store/profile [:store.profile/name]}]}]}
{:query/featured-stores [:db/id
{:store/profile [:store.profile/name
{:store.profile/photo [:photo/path :photo/id]}]}
:store/created-at
:store/featured
{:store/items [:db/id {:store.item/photos [{:store.item.photo/photo [:photo/path :photo/id]}
:store.item.photo/index]}]}]}
{:query/store-vods (om/get-query ci/StoreVod)}
{:query/store-items (om/get-query ci/ProductItem)}
:query/current-route])
Object
(initLocalState [this]
{:selected-navigation :all-items})
(render [this]
(let [{:keys [fullscreen? ] :as st} (om/get-state this)
{:query/keys [store store-items current-route] :as props} (om/props this)
{:store/keys [profile visitor-count owners geolocation]
stream :stream/_store} store
{:store.profile/keys [photo cover tagline description]
store-name :store.profile/name} profile
stream (first stream)
is-live? (= :stream.state/live (:stream/state stream))
{:keys [route route-params query-params]} current-route
vod-timestamp (-> query-params :vod-timestamp c/parse-long-safe)
is-vod? (some? vod-timestamp)
show-chat? (:show-chat? st true)
store-status (get-in store [:store/status :status/type])
store-owner-online? (-> owners :store.owner/user :user/online?)
selected-navigation (:nav query-params)]
(debug "Store vods: " (:query/store-vods props))
(dom/div
{:id "sulo-store"}
(if (:store/not-found? store)
(store-not-found this)
[
(dom/h1 (css/show-for-sr) store-name)
(when (or (nil? store-status)
(= :status.type/closed store-status))
(callout/callout-small
(->> (css/text-align :center {:id "store-closed-banner"})
(css/add-classes [:alert :store-closed]))
(dom/div (css/add-class :sl-tooltip)
(dom/h3
(css/add-class :closed)
(dom/strong nil "Closed - "))
(dom/span (css/add-class :sl-tooltip-text)
"Only you can see your store. Customers who try to view your store will see a not found page."))
(dom/a {:href (routes/url :store-dashboard/profile#options route-params)}
(dom/span nil "Go to options"))))
(grid/row
(->> (grid/columns-in-row {:small 1})
(css/add-class :collapse)
(css/add-class :expanded))
(grid/column
(grid/column-order {:small 3 :medium 1})
(dom/div
(cond->> (css/add-class :stream-container)
show-chat?
(css/add-class :sulo-show-chat)
fullscreen?
(css/add-class :fullscreen))
(cond
(or is-live? is-vod?)
[
(stream/->Stream (om/computed {:stream stream}
{:stream-title (:stream/title stream)
:widescreen? true
:store store
:vod-timestamp vod-timestamp
:on-fullscreen-change #(om/update-state! this assoc :fullscreen? %)}))
(chat/->StreamChat (om/computed (:proxy/chat props)
{:on-toggle-chat (fn [show?]
(om/update-state! this assoc :show-chat? show?))
:is-vod? is-vod?
:store store
:stream-overlay? true
:visitor-count visitor-count
:show? show-chat?
:store-online-status store-owner-online?}))]
(some? cover)
(photo/store-cover store {:alt (str store-name " cover photo")}))))
(grid/column
(->> (grid/column-order {:small 1 :medium 3})
(css/add-class :store-container))
(grid/row
(->> (css/align :middle)
(css/align :center))
(grid/column
(grid/column-size {:small 12 :medium 2})
(photo/store-photo store {:transformation :transformation/thumbnail}))
(grid/column
(css/add-class :shrink)
(dom/p nil
(dom/strong nil store-name)
(when (not-empty (:geolocation/title geolocation))
[(dom/br nil)
(dom/small nil (:geolocation/title geolocation))])
(when (not-empty tagline)
[(dom/br nil)
(dom/i (css/add-class :tagline) tagline)])))
(grid/column
(->> (grid/column-size {:small 12 :medium 4 :large 3})
(css/text-align :center)
(css/add-class :follow-section))
(dom/div nil
(common/follow-button nil)
)))
))
(grid/row
(css/add-class :collapse)
(grid/column
(css/add-class :store-submenu)
(let [store-url (store-url (:store-id route-params))]
(menu/horizontal
(->> (css/align :right)
(css/add-class :share-menu))
(menu/item
nil
(social/share-button {:on-click #(mixpanel/track "Share on social media" {:platform "facebook"
:object "store"})
:platform :social/facebook
:href store-url}))
(menu/item
nil
(social/share-button {:on-click #(mixpanel/track "Share on social media" {:platform "twitter"
:object "store"})
:platform :social/twitter
:description (:store.profile/name profile)
:href store-url}))
(menu/item
nil
(social/share-button {:on-click #(mixpanel/track "Share on social media" {:platform "pinterest"
:object "store"})
:platform :social/pinterest
:href store-url
:description (:store.profile/name profile)
:media (photos/transform (:photo/id (:store.profile/photo profile))
:transformation/thumbnail)}))
))))
(dom/div
{:id "shop"}
(grid/row
(->> (css/add-class :collapse)
(css/add-class :menu-container))
(grid/column
nil
(menu/horizontal
(css/add-class :navigation)
(menu/item (cond->> (css/add-class :about)
(= selected-navigation "videos")
(css/add-class ::css/is-active))
(dom/a {:href (routes/store-url store :store route-params (assoc query-params :nav "videos"))}
(dom/span nil "Videos")))
(menu/item (cond->> (css/add-class :about)
(= selected-navigation "about")
(css/add-class ::css/is-active))
(dom/a {:href (routes/store-url store :store route-params (assoc query-params :nav "about"))}
(dom/span nil "About")))
(menu/item (cond->> (css/add-class :about)
(= selected-navigation "policies")
(css/add-class ::css/is-active))
(dom/a {:href (routes/store-url store :store route-params (assoc query-params :nav "policies"))}
(dom/span nil "Policies")))
(menu/item (when (and (= route :store) (nil? selected-navigation))
(css/add-class ::css/is-active))
(dom/a {:href (routes/store-url store :store route-params (dissoc query-params :nav))}
(dom/span nil "All Items")))
(map-indexed
(fn [i s]
(let [{:store.section/keys [label]} s
is-active? (and (= route :store) (= selected-navigation (str (:db/id s))))]
(menu/item
(cond->> {:key (+ 10 i)}
is-active?
(css/add-class ::css/is-active))
(dom/a
{:href (routes/store-url store :store route-params (assoc query-params :nav (:db/id s)))}
(dom/span nil label)))))
(:store/sections store)))))
(cond (= selected-navigation "about")
(about-section this)
(= selected-navigation "videos")
(videos-section this)
(= selected-navigation "policies")
(policies-section this)
:else
(let [selected-section (c/parse-long-safe selected-navigation)
products (sort-by :store.item/index
(if (and (= route :store) (number? selected-section))
(filter #(= (get-in % [:store.item/section :db/id]) selected-section) store-items)
store-items))]
(grid/products products
(fn [p]
(ci/->ProductItem (om/computed p
{:current-route current-route
:show-caption? true})))))))])))))
(def ->Store (om/factory Store))
(router/register-component :store Store) |
16161747e1166f9d2c340405944e5df0f6fd9f4902d3fc9577ff50301c59233f | haguenau/wyrd | tmkContainer.ml | open TmkStruct
(****************************************************************************************
* La classe Container
****************************************************************************************)
let real_class_container = Class.create "Container" [TmkWidget.real_class_widget]
class virtual container = object (self)
inherit TmkWidget.widget as super
val mutable redrawing_children = ([] : TmkWidget.widget list)
method is_container = true
method queue_redraw () =
if not need_redraw then (
super#queue_redraw ();
redrawing_children <- [];
List.iter (fun c -> c#queue_redraw ()) (self#children ())
)
method redraw_register (w : TmkWidget.widget) =
if not need_redraw then (
redrawing_children <- w :: redrawing_children;
try self#parent#redraw_register self#coerce
with Not_found ->
Queue.add self#redraw_deliver self#terminal#event_queue
)
method redraw_deliver () =
if geometry.Geom.w > 0 && geometry.Geom.h > 0 then (
if need_redraw then
super#redraw_deliver ()
else (
List.iter (fun c -> c#redraw_deliver ()) redrawing_children;
redrawing_children <- []
)
)
method add w =
self#signal_add_descendant#emit w
method remove w =
TmkWidget.full_tree_do_post
(fun d -> self#signal_remove_descendant#emit d)
(w :> TmkWidget.widget)
method class_map w =
super#class_map w;
List.iter (fun c -> c#signal_map#emit w) (self#children ())
method class_set_state s =
super#class_set_state s;
List.iter (fun c -> c#signal_set_state#emit s) (self#children ())
method class_draw () =
super#class_draw ();
List.iter (fun c -> c#signal_draw#emit ()) (self#children ())
method class_add_descendant (w : TmkWidget.widget) =
try
self#parent#signal_add_descendant#emit w
with Not_found -> assert false
method class_remove_descendant (w : TmkWidget.widget) =
try
self#parent#signal_remove_descendant#emit w
with Not_found -> assert false
end
(****************************************************************************************
* La classe Bin
****************************************************************************************)
let real_class_bin = Class.create "Bin" [real_class_container]
class virtual bin = object (self)
inherit container as super
val mutable child : TmkWidget.widget option = None
method children () = match child with
| Some w -> [w]
| None -> []
method add (w : TmkWidget.widget) =
match child with
| Some _ -> failwith "bin has already a child"
| None ->
child <- Some w;
self#signal_add_descendant#emit w
method remove w =
match child with
| Some c when c == w ->
super#remove w;
child <- None
| _ -> raise Not_found
end
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* La classe utilitaire Toplevel
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* La classe utilitaire Toplevel
****************************************************************************************)
let real_class_toplevel = Class.create "Toplevel" []
class virtual toplevel (term : TmkWidget.terminal) = object (self)
val mutable focus = (None : TmkWidget.widget option)
method toplevel_pass = function
| Toplevel.Give_focus (w : TmkWidget.widget) ->
assert w#can_focus;
let f = match focus with
| None -> assert false
| Some f -> f in
f#signal_lost_focus#emit ();
w#signal_got_focus#emit ();
focus <- Some w
method set_cursor c =
term#set_cursor c
method class_add_descendant (w : TmkWidget.widget) =
if w#can_focus then (
match focus with
| Some _ -> ()
| None -> focus <- Some w
);
term#queue_resize ()
method class_remove_descendant (w : TmkWidget.widget) =
let () = match focus with
| Some f when f == w ->
focus <- TmkWidget.find_first_focusable w self#coerce;
(match focus with
| Some f -> w#signal_got_focus#emit ()
| None -> ())
| _ -> () in
term#queue_resize ()
method class_toplevel_event = function
| Toplevel.Activate ->
let () = match focus with
| None -> ()
| Some w -> w#signal_got_focus#emit () in
()
| Toplevel.Desactivate -> ()
| Toplevel.Key k ->
let () = match focus with
| None -> ()
| Some w -> ignore (w#signal_key_event#emit k) in
()
end
(****************************************************************************************
* La classe Window
****************************************************************************************)
let real_class_window = Class.create "Window" [real_class_bin; real_class_toplevel]
class window (term : TmkWidget.terminal) = object (self)
inherit bin as super
inherit toplevel term as super_toplevel
val mutable child_size = (0,0)
val mutable child_scroll = false
val mutable child_window = TmkArea.null_window
val child_geometry = Geom.null ()
val mutable left_glue = 0
val mutable right_glue = 0
val mutable top_glue = 0
val mutable bottom_glue = 0
method real_class = real_class_window
method parent = raise Not_found
method terminal = term
method set_glue l r t b =
if l < 0 || r < 0 || t < 0 || b < 0 || l + r > 100 || t + b > 100 then
invalid_arg "Window#set_glue";
left_glue <- l;
right_glue <- r;
top_glue <- t;
bottom_glue <- b
method set_cursor ((x,y) as c) =
child_window#set_center x y;
super_toplevel#set_cursor (child_window#real_position c)
method class_map w =
super#class_map w;
child_window <- w;
let s = self#signal_get_size#emit (0,0) in
child_size <- s
method class_get_size t =
match child with
| None -> t
| Some c -> c#signal_get_size#emit t
method class_set_geometry g =
super#class_set_geometry g;
match child with
| None -> ()
| Some c ->
let (w, h) = child_size in
let center g1 g2 ew iw =
if iw > ew then
(0, ew, iw)
else
let gt = g1 + g2 in
let gc = 100 - gt in
let rw = iw + gc * (ew - iw) / 100 in
let rx = if gt = 0 then 0 else g1 * (ew - rw) / gt in
(rx, rw, rw) in
let (vx, vw, cw) = center left_glue right_glue geometry.Geom.w w
and (vy, vh, ch) = center top_glue bottom_glue geometry.Geom.h h in
let cs = w > geometry.Geom.w || h > geometry.Geom.h in
let cg = if cs then (
if child_scroll then (
child_window#set_view vx vy vw vh;
child_window#resize cw ch
) else (
let pad = Curses.newpad ch cw in
child_window <- new TmkArea.pad pad cw ch;
child_window#set_view vx vy vw vh;
c#signal_map#emit child_window
);
(0, 0, cw, ch)
) else (
if child_scroll then (
child_window#destroy ();
child_window <- window_info;
c#signal_map#emit child_window
);
(vx, vy, cw, ch)
) in
Geom.record cg child_geometry;
c#signal_set_geometry#emit cg;
child_scroll <- cs
method class_draw () =
Curses.wattrset child_window#window attribute;
let y = child_geometry.Geom.y in
for i = y to y + child_geometry.Geom.h - 1 do
ignore (Curses.wmove child_window#window i child_geometry.Geom.x);
Curses.whline child_window#window (32 lor attribute)
child_geometry.Geom.w
done;
super#class_draw ()
initializer
term#add_toplevel self#coerce;
attributes.(0) <- Curses.A.standout;
attribute <- Curses.A.standout
end
| null | https://raw.githubusercontent.com/haguenau/wyrd/490ce39ad9ecf36969eb74b9f882f85a1ef14ba3/curses/tmk/tmkContainer.ml | ocaml | ***************************************************************************************
* La classe Container
***************************************************************************************
***************************************************************************************
* La classe Bin
***************************************************************************************
***************************************************************************************
* La classe Window
*************************************************************************************** | open TmkStruct
let real_class_container = Class.create "Container" [TmkWidget.real_class_widget]
class virtual container = object (self)
inherit TmkWidget.widget as super
val mutable redrawing_children = ([] : TmkWidget.widget list)
method is_container = true
method queue_redraw () =
if not need_redraw then (
super#queue_redraw ();
redrawing_children <- [];
List.iter (fun c -> c#queue_redraw ()) (self#children ())
)
method redraw_register (w : TmkWidget.widget) =
if not need_redraw then (
redrawing_children <- w :: redrawing_children;
try self#parent#redraw_register self#coerce
with Not_found ->
Queue.add self#redraw_deliver self#terminal#event_queue
)
method redraw_deliver () =
if geometry.Geom.w > 0 && geometry.Geom.h > 0 then (
if need_redraw then
super#redraw_deliver ()
else (
List.iter (fun c -> c#redraw_deliver ()) redrawing_children;
redrawing_children <- []
)
)
method add w =
self#signal_add_descendant#emit w
method remove w =
TmkWidget.full_tree_do_post
(fun d -> self#signal_remove_descendant#emit d)
(w :> TmkWidget.widget)
method class_map w =
super#class_map w;
List.iter (fun c -> c#signal_map#emit w) (self#children ())
method class_set_state s =
super#class_set_state s;
List.iter (fun c -> c#signal_set_state#emit s) (self#children ())
method class_draw () =
super#class_draw ();
List.iter (fun c -> c#signal_draw#emit ()) (self#children ())
method class_add_descendant (w : TmkWidget.widget) =
try
self#parent#signal_add_descendant#emit w
with Not_found -> assert false
method class_remove_descendant (w : TmkWidget.widget) =
try
self#parent#signal_remove_descendant#emit w
with Not_found -> assert false
end
let real_class_bin = Class.create "Bin" [real_class_container]
class virtual bin = object (self)
inherit container as super
val mutable child : TmkWidget.widget option = None
method children () = match child with
| Some w -> [w]
| None -> []
method add (w : TmkWidget.widget) =
match child with
| Some _ -> failwith "bin has already a child"
| None ->
child <- Some w;
self#signal_add_descendant#emit w
method remove w =
match child with
| Some c when c == w ->
super#remove w;
child <- None
| _ -> raise Not_found
end
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* La classe utilitaire Toplevel
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* La classe utilitaire Toplevel
****************************************************************************************)
let real_class_toplevel = Class.create "Toplevel" []
class virtual toplevel (term : TmkWidget.terminal) = object (self)
val mutable focus = (None : TmkWidget.widget option)
method toplevel_pass = function
| Toplevel.Give_focus (w : TmkWidget.widget) ->
assert w#can_focus;
let f = match focus with
| None -> assert false
| Some f -> f in
f#signal_lost_focus#emit ();
w#signal_got_focus#emit ();
focus <- Some w
method set_cursor c =
term#set_cursor c
method class_add_descendant (w : TmkWidget.widget) =
if w#can_focus then (
match focus with
| Some _ -> ()
| None -> focus <- Some w
);
term#queue_resize ()
method class_remove_descendant (w : TmkWidget.widget) =
let () = match focus with
| Some f when f == w ->
focus <- TmkWidget.find_first_focusable w self#coerce;
(match focus with
| Some f -> w#signal_got_focus#emit ()
| None -> ())
| _ -> () in
term#queue_resize ()
method class_toplevel_event = function
| Toplevel.Activate ->
let () = match focus with
| None -> ()
| Some w -> w#signal_got_focus#emit () in
()
| Toplevel.Desactivate -> ()
| Toplevel.Key k ->
let () = match focus with
| None -> ()
| Some w -> ignore (w#signal_key_event#emit k) in
()
end
let real_class_window = Class.create "Window" [real_class_bin; real_class_toplevel]
class window (term : TmkWidget.terminal) = object (self)
inherit bin as super
inherit toplevel term as super_toplevel
val mutable child_size = (0,0)
val mutable child_scroll = false
val mutable child_window = TmkArea.null_window
val child_geometry = Geom.null ()
val mutable left_glue = 0
val mutable right_glue = 0
val mutable top_glue = 0
val mutable bottom_glue = 0
method real_class = real_class_window
method parent = raise Not_found
method terminal = term
method set_glue l r t b =
if l < 0 || r < 0 || t < 0 || b < 0 || l + r > 100 || t + b > 100 then
invalid_arg "Window#set_glue";
left_glue <- l;
right_glue <- r;
top_glue <- t;
bottom_glue <- b
method set_cursor ((x,y) as c) =
child_window#set_center x y;
super_toplevel#set_cursor (child_window#real_position c)
method class_map w =
super#class_map w;
child_window <- w;
let s = self#signal_get_size#emit (0,0) in
child_size <- s
method class_get_size t =
match child with
| None -> t
| Some c -> c#signal_get_size#emit t
method class_set_geometry g =
super#class_set_geometry g;
match child with
| None -> ()
| Some c ->
let (w, h) = child_size in
let center g1 g2 ew iw =
if iw > ew then
(0, ew, iw)
else
let gt = g1 + g2 in
let gc = 100 - gt in
let rw = iw + gc * (ew - iw) / 100 in
let rx = if gt = 0 then 0 else g1 * (ew - rw) / gt in
(rx, rw, rw) in
let (vx, vw, cw) = center left_glue right_glue geometry.Geom.w w
and (vy, vh, ch) = center top_glue bottom_glue geometry.Geom.h h in
let cs = w > geometry.Geom.w || h > geometry.Geom.h in
let cg = if cs then (
if child_scroll then (
child_window#set_view vx vy vw vh;
child_window#resize cw ch
) else (
let pad = Curses.newpad ch cw in
child_window <- new TmkArea.pad pad cw ch;
child_window#set_view vx vy vw vh;
c#signal_map#emit child_window
);
(0, 0, cw, ch)
) else (
if child_scroll then (
child_window#destroy ();
child_window <- window_info;
c#signal_map#emit child_window
);
(vx, vy, cw, ch)
) in
Geom.record cg child_geometry;
c#signal_set_geometry#emit cg;
child_scroll <- cs
method class_draw () =
Curses.wattrset child_window#window attribute;
let y = child_geometry.Geom.y in
for i = y to y + child_geometry.Geom.h - 1 do
ignore (Curses.wmove child_window#window i child_geometry.Geom.x);
Curses.whline child_window#window (32 lor attribute)
child_geometry.Geom.w
done;
super#class_draw ()
initializer
term#add_toplevel self#coerce;
attributes.(0) <- Curses.A.standout;
attribute <- Curses.A.standout
end
|
cd9a188115feb412530b53a8a18bcc1ee3c54e25b5442a17223f497ce2e93f09 | esl/MongooseIM | router_SUITE.erl | -module(router_SUITE).
-compile([export_all, nowarn_export_all]).
-include_lib("exml/include/exml.hrl").
-include_lib("eunit/include/eunit.hrl").
-include("mongoose.hrl").
%% ---------------------------------------------------------------
%% Common Test callbacks
%% ---------------------------------------------------------------
all() ->
[
{group, routing},
{group, schema}
].
groups() ->
[
{routing, [], [
basic_routing,
do_not_reroute_errors
]},
{schema, [], [
update_tables_hidden_components,
update_tables_hidden_components_idempotent
]}
].
init_per_suite(C) ->
{ok, _} = application:ensure_all_started(jid),
ok = mnesia:create_schema([node()]),
ok = mnesia:start(),
{ok, _} = application:ensure_all_started(exometer_core),
C.
end_per_suite(_C) ->
meck:unload(),
mnesia:stop(),
mnesia:delete_schema([node()]),
application:stop(exometer_core),
ok.
init_per_group(routing, Config) ->
mongoose_config:set_opt(routing_modules, [xmpp_router_a, xmpp_router_b, xmpp_router_c]),
gen_hook:start_link(),
ejabberd_router:start_link(),
Config;
init_per_group(schema, Config) ->
remove_component_tables(),
Config.
end_per_group(routing, _Config) ->
mongoose_config:unset_opt(routing_modules);
end_per_group(schema, _Config) ->
ok.
init_per_testcase(_CaseName, Config) ->
Config.
end_per_testcase(HiddenComponent, _Config)
when HiddenComponent == update_tables_hidden_components;
HiddenComponent == update_tables_hidden_components_idempotent ->
remove_component_tables();
end_per_testcase(_CaseName, _Config) ->
ok.
%% ---------------------------------------------------------------
%% Test cases
%% ---------------------------------------------------------------
basic_routing(_C) ->
module ' a ' drops message 1 , routes message 2 , passes on everything else
setup_routing_module(xmpp_router_a, 1, 2),
module ' b ' drops message 3 , routes message 4 , passes on everything else
setup_routing_module(xmpp_router_b, 3, 4),
%% module 'c' routes everything
setup_routing_module(xmpp_router_c, none, all),
send messages from 1 to 5
lists:map(fun(I) -> route(msg(I)) end, [1,2,3,4,5]),
meck:validate(xmpp_router_a),
meck:unload(xmpp_router_a),
meck:validate(xmpp_router_b),
meck:unload(xmpp_router_b),
meck:validate(xmpp_router_c),
meck:unload(xmpp_router_c),
we know that 1 and 3 should be dropped , and 2 , 4 and 5 handled by a , b and c respectively
verify([{a, 2}, {b, 4}, {c, 5}]),
ok.
%% This test makes sure that if we try to respond to an error message by routing error message
we do not enter an infinite loop ; it has been fixed in d3941e33453c95ca78561144182712cc4f1d6c72
%% without the fix this tests gets stuck in a loop.
do_not_reroute_errors(_) ->
From = <<"ja@localhost">>,
To = <<"ty@localhost">>,
Stanza = #xmlel{name = <<"iq">>,
attrs = [{<<"from">>, From}, {<<"to">>, To}, {<<"type">>, <<"get">>} ]
},
Acc = mongoose_acc:new(#{ location => ?LOCATION,
lserver => <<"localhost">>,
host_type => <<"localhost">>,
element => Stanza }),
meck:new(xmpp_router_a, [non_strict]),
meck:expect(xmpp_router_a, filter,
fun(From0, To0, Acc0, Packet0) -> {From0, To0, Acc0, Packet0} end),
meck:expect(xmpp_router_a, route, fun resend_as_error/4),
ejabberd_router:route(From, To, Acc, Stanza),
ok.
update_tables_hidden_components(_C) ->
%% Tables as of b076e4a62a8b21188245f13c42f9cfd93e06e6b7
create_component_tables([domain, handler, node]),
ejabberd_router:update_tables(),
%% Local table is removed and the distributed one has a new list of attributes
false = lists:member(external_component, mnesia:system_info(tables)),
[domain, handler, node, is_hidden] = mnesia:table_info(external_component_global, attributes).
update_tables_hidden_components_idempotent(_C) ->
AttrsWithHidden = [domain, handler, node, is_hidden],
create_component_tables(AttrsWithHidden),
ejabberd_router:update_tables(),
%% Local table is not removed and the attribute list of the distributed one is not changed
true = lists:member(external_component, mnesia:system_info(tables)),
AttrsWithHidden = mnesia:table_info(external_component_global, attributes).
%% ---------------------------------------------------------------
%% Helpers
%% ---------------------------------------------------------------
setup_routing_module(Name, PacketToDrop, PacketToRoute) ->
meck:new(Name, [non_strict]),
meck:expect(Name, filter,
fun(From, To, Acc, Packet) ->
case msg_to_id(Packet) of
PacketToDrop -> drop;
_ -> {From, To, Acc, Packet}
end
end),
meck:expect(Name, route,
make_routing_fun(Name, PacketToRoute)),
ok.
make_routing_fun(Name, all) ->
Self = self(),
Marker = list_to_atom([lists:last(atom_to_list(Name))]),
fun(_From, _To, Acc, Packet) ->
Self ! {Marker, Packet},
{done, Acc}
end;
make_routing_fun(Name, PacketToRoute) ->
Self = self(),
Marker = list_to_atom([lists:last(atom_to_list(Name))]),
fun(From, To, Acc, Packet) ->
case msg_to_id(Packet) of
PacketToRoute ->
Self ! {Marker, Packet},
{done, Acc};
_ -> {From, To, Acc, Packet}
end
end.
msg(I) ->
IBin = integer_to_binary(I),
#xmlel{ name = <<"message">>,
children = [
#xmlel{ name = <<"body">>,
children = [#xmlcdata{ content = IBin }] }
] }.
msg_to_id(Msg) ->
binary_to_integer(exml_query:path(Msg, [{element, <<"body">>}, cdata])).
route(I) ->
FromJID = jid:from_binary(<<"ala@localhost">>),
ToJID = jid:from_binary(<<"bob@localhost">>),
Acc = mongoose_acc:new(#{ location => ?LOCATION,
lserver => <<"localhost">>,
host_type => <<"localhost">>,
element => I,
from_jid => FromJID,
to_jid => ToJID }),
#{} = ejabberd_router:route(FromJID, ToJID, Acc, I).
verify(L) ->
receive
{RouterID, XML} ->
X = msg_to_id(XML),
ct:pal("{RouterID, X, L}: ~p", [{RouterID, X, L}]),
Item = {RouterID, X},
?assert(lists:member(Item, L)),
verify(lists:delete(Item, L))
after 1000 ->
?assertEqual(L, []),
ct:pal("all messages routed correctly")
end.
create_component_tables(AttrList) ->
{atomic, ok} =
mnesia:create_table(external_component,
[{attributes, AttrList},
{local_content, true}]),
{atomic, ok} =
mnesia:create_table(external_component_global,
[{attributes, AttrList},
{type, bag},
{record_name, external_component}]).
remove_component_tables() ->
mnesia:delete_table(external_component),
mnesia:delete_table(external_component_global).
resend_as_error(From0, To0, Acc0, Packet0) ->
{Acc1, Packet1} = jlib:make_error_reply(Acc0, Packet0, #xmlel{}),
Acc2 = ejabberd_router:route(To0, From0, Acc1, Packet1),
{done, Acc2}.
| null | https://raw.githubusercontent.com/esl/MongooseIM/64d10a08d8e4700027734ec49ce4c4014b41b34b/test/router_SUITE.erl | erlang | ---------------------------------------------------------------
Common Test callbacks
---------------------------------------------------------------
---------------------------------------------------------------
Test cases
---------------------------------------------------------------
module 'c' routes everything
This test makes sure that if we try to respond to an error message by routing error message
without the fix this tests gets stuck in a loop.
Tables as of b076e4a62a8b21188245f13c42f9cfd93e06e6b7
Local table is removed and the distributed one has a new list of attributes
Local table is not removed and the attribute list of the distributed one is not changed
---------------------------------------------------------------
Helpers
--------------------------------------------------------------- | -module(router_SUITE).
-compile([export_all, nowarn_export_all]).
-include_lib("exml/include/exml.hrl").
-include_lib("eunit/include/eunit.hrl").
-include("mongoose.hrl").
all() ->
[
{group, routing},
{group, schema}
].
groups() ->
[
{routing, [], [
basic_routing,
do_not_reroute_errors
]},
{schema, [], [
update_tables_hidden_components,
update_tables_hidden_components_idempotent
]}
].
init_per_suite(C) ->
{ok, _} = application:ensure_all_started(jid),
ok = mnesia:create_schema([node()]),
ok = mnesia:start(),
{ok, _} = application:ensure_all_started(exometer_core),
C.
end_per_suite(_C) ->
meck:unload(),
mnesia:stop(),
mnesia:delete_schema([node()]),
application:stop(exometer_core),
ok.
init_per_group(routing, Config) ->
mongoose_config:set_opt(routing_modules, [xmpp_router_a, xmpp_router_b, xmpp_router_c]),
gen_hook:start_link(),
ejabberd_router:start_link(),
Config;
init_per_group(schema, Config) ->
remove_component_tables(),
Config.
end_per_group(routing, _Config) ->
mongoose_config:unset_opt(routing_modules);
end_per_group(schema, _Config) ->
ok.
init_per_testcase(_CaseName, Config) ->
Config.
end_per_testcase(HiddenComponent, _Config)
when HiddenComponent == update_tables_hidden_components;
HiddenComponent == update_tables_hidden_components_idempotent ->
remove_component_tables();
end_per_testcase(_CaseName, _Config) ->
ok.
basic_routing(_C) ->
module ' a ' drops message 1 , routes message 2 , passes on everything else
setup_routing_module(xmpp_router_a, 1, 2),
module ' b ' drops message 3 , routes message 4 , passes on everything else
setup_routing_module(xmpp_router_b, 3, 4),
setup_routing_module(xmpp_router_c, none, all),
send messages from 1 to 5
lists:map(fun(I) -> route(msg(I)) end, [1,2,3,4,5]),
meck:validate(xmpp_router_a),
meck:unload(xmpp_router_a),
meck:validate(xmpp_router_b),
meck:unload(xmpp_router_b),
meck:validate(xmpp_router_c),
meck:unload(xmpp_router_c),
we know that 1 and 3 should be dropped , and 2 , 4 and 5 handled by a , b and c respectively
verify([{a, 2}, {b, 4}, {c, 5}]),
ok.
we do not enter an infinite loop ; it has been fixed in d3941e33453c95ca78561144182712cc4f1d6c72
do_not_reroute_errors(_) ->
From = <<"ja@localhost">>,
To = <<"ty@localhost">>,
Stanza = #xmlel{name = <<"iq">>,
attrs = [{<<"from">>, From}, {<<"to">>, To}, {<<"type">>, <<"get">>} ]
},
Acc = mongoose_acc:new(#{ location => ?LOCATION,
lserver => <<"localhost">>,
host_type => <<"localhost">>,
element => Stanza }),
meck:new(xmpp_router_a, [non_strict]),
meck:expect(xmpp_router_a, filter,
fun(From0, To0, Acc0, Packet0) -> {From0, To0, Acc0, Packet0} end),
meck:expect(xmpp_router_a, route, fun resend_as_error/4),
ejabberd_router:route(From, To, Acc, Stanza),
ok.
update_tables_hidden_components(_C) ->
create_component_tables([domain, handler, node]),
ejabberd_router:update_tables(),
false = lists:member(external_component, mnesia:system_info(tables)),
[domain, handler, node, is_hidden] = mnesia:table_info(external_component_global, attributes).
update_tables_hidden_components_idempotent(_C) ->
AttrsWithHidden = [domain, handler, node, is_hidden],
create_component_tables(AttrsWithHidden),
ejabberd_router:update_tables(),
true = lists:member(external_component, mnesia:system_info(tables)),
AttrsWithHidden = mnesia:table_info(external_component_global, attributes).
setup_routing_module(Name, PacketToDrop, PacketToRoute) ->
meck:new(Name, [non_strict]),
meck:expect(Name, filter,
fun(From, To, Acc, Packet) ->
case msg_to_id(Packet) of
PacketToDrop -> drop;
_ -> {From, To, Acc, Packet}
end
end),
meck:expect(Name, route,
make_routing_fun(Name, PacketToRoute)),
ok.
make_routing_fun(Name, all) ->
Self = self(),
Marker = list_to_atom([lists:last(atom_to_list(Name))]),
fun(_From, _To, Acc, Packet) ->
Self ! {Marker, Packet},
{done, Acc}
end;
make_routing_fun(Name, PacketToRoute) ->
Self = self(),
Marker = list_to_atom([lists:last(atom_to_list(Name))]),
fun(From, To, Acc, Packet) ->
case msg_to_id(Packet) of
PacketToRoute ->
Self ! {Marker, Packet},
{done, Acc};
_ -> {From, To, Acc, Packet}
end
end.
msg(I) ->
IBin = integer_to_binary(I),
#xmlel{ name = <<"message">>,
children = [
#xmlel{ name = <<"body">>,
children = [#xmlcdata{ content = IBin }] }
] }.
msg_to_id(Msg) ->
binary_to_integer(exml_query:path(Msg, [{element, <<"body">>}, cdata])).
route(I) ->
FromJID = jid:from_binary(<<"ala@localhost">>),
ToJID = jid:from_binary(<<"bob@localhost">>),
Acc = mongoose_acc:new(#{ location => ?LOCATION,
lserver => <<"localhost">>,
host_type => <<"localhost">>,
element => I,
from_jid => FromJID,
to_jid => ToJID }),
#{} = ejabberd_router:route(FromJID, ToJID, Acc, I).
verify(L) ->
receive
{RouterID, XML} ->
X = msg_to_id(XML),
ct:pal("{RouterID, X, L}: ~p", [{RouterID, X, L}]),
Item = {RouterID, X},
?assert(lists:member(Item, L)),
verify(lists:delete(Item, L))
after 1000 ->
?assertEqual(L, []),
ct:pal("all messages routed correctly")
end.
create_component_tables(AttrList) ->
{atomic, ok} =
mnesia:create_table(external_component,
[{attributes, AttrList},
{local_content, true}]),
{atomic, ok} =
mnesia:create_table(external_component_global,
[{attributes, AttrList},
{type, bag},
{record_name, external_component}]).
remove_component_tables() ->
mnesia:delete_table(external_component),
mnesia:delete_table(external_component_global).
resend_as_error(From0, To0, Acc0, Packet0) ->
{Acc1, Packet1} = jlib:make_error_reply(Acc0, Packet0, #xmlel{}),
Acc2 = ejabberd_router:route(To0, From0, Acc1, Packet1),
{done, Acc2}.
|
23c4631d5f6b30b7a8eeee2e96f459dbf82b0da1442abc357c96b51a01221b9a | elm-lang/elm-package | Fetch.hs | {-# LANGUAGE OverloadedStrings #-}
module Install.Fetch (everything) where
import Control.Concurrent (forkIO)
import qualified Control.Concurrent.Chan as Chan
import Control.Concurrent.ParallelIO.Local (withPool, parallel)
import Control.Monad.Except (liftIO, throwError)
import qualified Codec.Archive.Zip as Zip
import qualified Data.List as List
import Data.Monoid ((<>))
import qualified Data.Text as Text
import GHC.IO.Handle (hIsTerminalDevice)
import qualified Network.HTTP.Client as Client
import System.Directory
( createDirectoryIfMissing, doesDirectoryExist
, getDirectoryContents, renameDirectory
)
import System.FilePath ((</>))
import System.IO (stdout)
import Text.PrettyPrint.ANSI.Leijen
( Doc, (<+>), displayIO, green, plain, red, renderPretty, text )
import qualified Elm.Package as Pkg
import qualified Elm.Package.Paths as Path
import qualified CommandLine.Helpers as Cmd
import qualified Manager
import qualified Reporting.Error as Error
import qualified Utils.Http as Http
-- PARALLEL FETCHING
everything :: [(Pkg.Name, Pkg.Version)] -> Manager.Manager ()
everything packages =
if null packages then return () else everythingHelp packages
everythingHelp :: [(Pkg.Name, Pkg.Version)] -> Manager.Manager ()
everythingHelp packages =
Cmd.inDir Path.packagesDirectory $
do eithers <- liftIO $ do
startMessage (length packages)
isTerminal <- hIsTerminalDevice stdout
resultChan <- Chan.newChan
forkIO (printLoop isTerminal resultChan)
withPool 4 $ \pool ->
parallel pool (map (prettyFetch resultChan) packages)
case sequence eithers of
Right _ ->
liftIO $ putStrLn ""
Left err ->
throwError err
data Result =
Result
{ _name :: Pkg.Name
, _vsn :: Pkg.Version
, _either :: Either Error.Error ()
}
printLoop :: Bool -> Chan.Chan Result -> IO ()
printLoop isTerminal resultChan =
do result <- Chan.readChan resultChan
let doc = toDoc result
displayIO stdout $ renderPretty 1 80 $
if isTerminal then doc else plain doc
printLoop isTerminal resultChan
prettyFetch :: Chan.Chan Result -> (Pkg.Name, Pkg.Version) -> IO (Either Error.Error ())
prettyFetch printChan (name, version) =
do either <- Manager.run $ fetch name version
Chan.writeChan printChan (Result name version either)
return either
startMessage :: Int -> IO ()
startMessage n =
if n > 0 then
putStrLn "Starting downloads...\n"
else
return ()
toDoc :: Result -> Doc
toDoc (Result name version either) =
let
nameDoc =
text $ Pkg.toString name
versionDoc =
text $ Pkg.versionToString version
bullet =
case either of
Right _ ->
green (text "●")
Left _ ->
red (text "✗")
in
text " " <> bullet <+> nameDoc <+> versionDoc <> text "\n"
-- FETCH A PACKAGE
fetch :: Pkg.Name -> Pkg.Version -> Manager.Manager ()
fetch name@(Pkg.Name user project) version =
ifNotExists name version $
do Http.send (toZipballUrl name version) extract
files <- liftIO $ getDirectoryContents "."
case List.find (List.isPrefixOf (Text.unpack (user <> "-" <> project))) files of
Nothing ->
throwError $ Error.ZipDownloadFailed name version
Just dir ->
liftIO $ do
let home = Pkg.toFilePath name
createDirectoryIfMissing True home
renameDirectory dir (home </> Pkg.versionToString version)
toZipballUrl :: Pkg.Name -> Pkg.Version -> String
toZipballUrl name version =
"/" ++ Pkg.toUrl name
++ "/zipball/" ++ Pkg.versionToString version ++ "/"
ifNotExists :: Pkg.Name -> Pkg.Version -> Manager.Manager () -> Manager.Manager ()
ifNotExists name version task =
do let dir = Pkg.toFilePath name </> Pkg.versionToString version
exists <- liftIO $ doesDirectoryExist dir
if exists then return () else task
extract :: Client.Request -> Client.Manager -> IO ()
extract request manager =
do response <- Client.httpLbs request manager
let archive = Zip.toArchive (Client.responseBody response)
Zip.extractFilesFromArchive [] archive
| null | https://raw.githubusercontent.com/elm-lang/elm-package/2076638d812d9dea641e6e695951495f523bb98f/src/Install/Fetch.hs | haskell | # LANGUAGE OverloadedStrings #
PARALLEL FETCHING
FETCH A PACKAGE | module Install.Fetch (everything) where
import Control.Concurrent (forkIO)
import qualified Control.Concurrent.Chan as Chan
import Control.Concurrent.ParallelIO.Local (withPool, parallel)
import Control.Monad.Except (liftIO, throwError)
import qualified Codec.Archive.Zip as Zip
import qualified Data.List as List
import Data.Monoid ((<>))
import qualified Data.Text as Text
import GHC.IO.Handle (hIsTerminalDevice)
import qualified Network.HTTP.Client as Client
import System.Directory
( createDirectoryIfMissing, doesDirectoryExist
, getDirectoryContents, renameDirectory
)
import System.FilePath ((</>))
import System.IO (stdout)
import Text.PrettyPrint.ANSI.Leijen
( Doc, (<+>), displayIO, green, plain, red, renderPretty, text )
import qualified Elm.Package as Pkg
import qualified Elm.Package.Paths as Path
import qualified CommandLine.Helpers as Cmd
import qualified Manager
import qualified Reporting.Error as Error
import qualified Utils.Http as Http
everything :: [(Pkg.Name, Pkg.Version)] -> Manager.Manager ()
everything packages =
if null packages then return () else everythingHelp packages
everythingHelp :: [(Pkg.Name, Pkg.Version)] -> Manager.Manager ()
everythingHelp packages =
Cmd.inDir Path.packagesDirectory $
do eithers <- liftIO $ do
startMessage (length packages)
isTerminal <- hIsTerminalDevice stdout
resultChan <- Chan.newChan
forkIO (printLoop isTerminal resultChan)
withPool 4 $ \pool ->
parallel pool (map (prettyFetch resultChan) packages)
case sequence eithers of
Right _ ->
liftIO $ putStrLn ""
Left err ->
throwError err
data Result =
Result
{ _name :: Pkg.Name
, _vsn :: Pkg.Version
, _either :: Either Error.Error ()
}
printLoop :: Bool -> Chan.Chan Result -> IO ()
printLoop isTerminal resultChan =
do result <- Chan.readChan resultChan
let doc = toDoc result
displayIO stdout $ renderPretty 1 80 $
if isTerminal then doc else plain doc
printLoop isTerminal resultChan
prettyFetch :: Chan.Chan Result -> (Pkg.Name, Pkg.Version) -> IO (Either Error.Error ())
prettyFetch printChan (name, version) =
do either <- Manager.run $ fetch name version
Chan.writeChan printChan (Result name version either)
return either
startMessage :: Int -> IO ()
startMessage n =
if n > 0 then
putStrLn "Starting downloads...\n"
else
return ()
toDoc :: Result -> Doc
toDoc (Result name version either) =
let
nameDoc =
text $ Pkg.toString name
versionDoc =
text $ Pkg.versionToString version
bullet =
case either of
Right _ ->
green (text "●")
Left _ ->
red (text "✗")
in
text " " <> bullet <+> nameDoc <+> versionDoc <> text "\n"
fetch :: Pkg.Name -> Pkg.Version -> Manager.Manager ()
fetch name@(Pkg.Name user project) version =
ifNotExists name version $
do Http.send (toZipballUrl name version) extract
files <- liftIO $ getDirectoryContents "."
case List.find (List.isPrefixOf (Text.unpack (user <> "-" <> project))) files of
Nothing ->
throwError $ Error.ZipDownloadFailed name version
Just dir ->
liftIO $ do
let home = Pkg.toFilePath name
createDirectoryIfMissing True home
renameDirectory dir (home </> Pkg.versionToString version)
toZipballUrl :: Pkg.Name -> Pkg.Version -> String
toZipballUrl name version =
"/" ++ Pkg.toUrl name
++ "/zipball/" ++ Pkg.versionToString version ++ "/"
ifNotExists :: Pkg.Name -> Pkg.Version -> Manager.Manager () -> Manager.Manager ()
ifNotExists name version task =
do let dir = Pkg.toFilePath name </> Pkg.versionToString version
exists <- liftIO $ doesDirectoryExist dir
if exists then return () else task
extract :: Client.Request -> Client.Manager -> IO ()
extract request manager =
do response <- Client.httpLbs request manager
let archive = Zip.toArchive (Client.responseBody response)
Zip.extractFilesFromArchive [] archive
|
5d2f1a2eba6fbc6535dadf19511e692adde3de27eea59ee63e6fc05df33df46b | input-output-hk/cardano-wallet-legacy | TxMetaStorage.hs | {-# LANGUAGE RankNTypes #-}
module TxMetaStorage
( spec
) where
import Universum
import Control.Concurrent.Async
import Control.Exception.Safe (bracket)
import qualified Data.List.NonEmpty as NonEmpty
import Formatting (bprint, (%))
import qualified Formatting as F
import Formatting.Buildable (build)
import Serokell.Util.Text (listJsonIndent, pairF)
import Test.Hspec (Spec, describe, it, shouldBe, shouldReturn)
import Test.QuickCheck (Arbitrary, Gen, arbitrary, vectorOf,
withMaxSuccess)
import Test.QuickCheck.Monadic (monadicIO, pick, run)
import Cardano.Wallet.Kernel.DB.TxMeta
import Pos.Chain.Txp (TxId)
import qualified Pos.Core as Core
# ANN module ( " HLint : ignore Reduce duplication " : : Text ) #
spec :: Spec
spec = do
describe "synchronization" $ do
it "synchronized with 2 write workers and no-ops" $ withMaxSuccess 5 $ monadicIO $ do
-- beware of the big data.
metas <- pick (genMetas 2000)
let (meta0, meta1) = splitAt (div 2000 2) metas
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWriteWithNoOp meta0 hdl
t1 <- async $ threadWriteWithNoOp meta1 hdl
traverse_ wait [t0, t1]
it "synchronized with 2 write workers and no-ops: correct count" $ withMaxSuccess 5 $ monadicIO $ do
-- beware of the big data.
metas <- pick (genMetas 200)
let (meta0, meta1) = splitAt (div 200 2) metas
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWriteWithNoOp meta0 hdl
t1 <- async $ threadWriteWithNoOp meta1 hdl
traverse_ wait [t0, t1]
(ls, _count) <- getTxMetas hdl (Offset 0) (Limit 300) Everything Nothing NoFilterOp NoFilterOp Nothing
length ls `shouldBe` 200
it "synchronized with 2 write workers" $ withMaxSuccess 5 $ monadicIO $ do
-- beware of the big data.
metas <- pick (genMetas 2000)
let (meta0, meta1) = splitAt (div 2000 2) metas
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWrite meta0 hdl
t1 <- async $ threadWrite meta1 hdl
traverse_ wait [t0, t1]
it "synchronized with 2 write workers: correct count" $ withMaxSuccess 5 $ monadicIO $ do
-- beware of the big data.
metas <- pick (genMetas 200)
let (meta0, meta1) = splitAt (div 200 2) metas
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWrite meta0 hdl
t1 <- async $ threadWrite meta1 hdl
traverse_ wait [t0, t1]
(ls, _count) <- getTxMetas hdl (Offset 0) (Limit 300) Everything Nothing NoFilterOp NoFilterOp Nothing
length ls `shouldBe` 200
it "synchronized 1 write and 1 read workers" $ withMaxSuccess 5 $ monadicIO $ do
-- beware of the big data.
metas <- pick (genMetas 2000)
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWriteWithNoOp metas hdl
t1 <- async $ threadRead 2000 hdl
traverse_ wait [t0, t1]
it "synchronized 1 write and 1 read workers: correct count" $ withMaxSuccess 5 $ monadicIO $ do
-- beware of the big data.
metas <- pick (genMetas 200)
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWriteWithNoOp metas hdl
t1 <- async $ threadRead 200 hdl
traverse_ wait [t0, t1]
(ls, _count) <- getTxMetas hdl (Offset 0) (Limit 300) Everything Nothing NoFilterOp NoFilterOp Nothing
length ls `shouldBe` 200
-- | Handy combinator which yields a fresh database to work with on each spec.
withTemporaryDb :: forall m a. (MonadIO m, MonadMask m) => (MetaDBHandle -> m a) -> m a
withTemporaryDb action = bracket acquire release action
where
acquire :: m MetaDBHandle
acquire = liftIO $ do
db <- openMetaDB ":memory:"
migrateMetaDB db
return db
release :: MetaDBHandle -> m ()
release = liftIO . closeMetaDB
-- | Synthetic @newtype@ used to generate unique inputs as part of
-- 'genMetas'. The reason why it is necessary is because the stock implementation
of ' ' would of course declare two tuples equal if their elements are .
-- However, this is too \"strong\" for our 'uniqueElements' generator.
newtype Input = Input { getInput :: (TxId, Word32, Core.Address, Core.Coin) }
deriving (Show)
-- | Eq is defined on the primary keys of Inputs.
instance Eq Input where
(Input (id1, ix1, _, _)) == (Input (id2, ix2, _, _)) = (id1, ix1) == (id2, ix2)
| This ensures that Inputs generated for the same Tx from getMetas , do not
-- double spend as they don`t use the same output.
instance Ord Input where
compare (Input (id1, ix1, _, _)) (Input (id2, ix2, _, _)) = compare (id1, ix1) (id2, ix2)
instance Arbitrary Input where
arbitrary = Input <$> arbitrary
instance Buildable Input where
build (Input (a, b, c, d)) =
bprint ("(" % F.build % ", " % F.build % ", " % F.build % ", " % F.build % ")")
a b c d
instance Buildable (Int, Input) where
build b = bprint pairF b
instance Buildable [Input] where
build = bprint (listJsonIndent 4)
newtype Output = Output { getOutput :: (Core.Address, Core.Coin) }
instance Arbitrary Output where
arbitrary = Output <$> arbitrary
| Handy generator which make sure we are generating ' TxMeta ' which all
-- have distinct txids and valid Inputs.
This gives the promise that all @size@ number of TxMeta can succesfully be
-- inserted in an empty db, with no violation.
genMetas :: Int -> Gen [TxMeta]
genMetas size = do
txids <- uniqueElements size
(metas1 :: [TxMeta]) <- vectorOf size genMeta
let metas = (\(txid, m) -> m{_txMetaId = txid}) <$> zip (NonEmpty.toList txids) metas1
return metas
| Generator for an arbitrary ' TxMeta ' with valid Inputs .
-- This gives the promise that it can succesfully be inserted in an empty db,
-- with no violation.
genMeta :: Gen (TxMeta)
genMeta = TxMeta
<$> arbitrary
<*> arbitrary
<*> (fmap getInput <$> uniqueElements 2)
<*> (fmap getOutput . NonEmpty.fromList <$> vectorOf 2 arbitrary)
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
threadRead :: Int -> MetaDBHandle -> IO ()
threadRead times hdl = do
let getNoFilters = getTxMetas hdl (Offset 0) (Limit 100) Everything Nothing NoFilterOp NoFilterOp Nothing
replicateM_ times getNoFilters
threadWrite :: [TxMeta] -> MetaDBHandle -> IO ()
threadWrite metas hdl = do
let f meta = do
putTxMetaT hdl meta `shouldReturn` Tx
mapM_ f metas
here we try to add the same tx 2 times . The second must fail , but without crashing
-- anything, as this is a no-op.
threadWriteWithNoOp :: [TxMeta] -> MetaDBHandle -> IO ()
threadWriteWithNoOp metas hdl = do
let f meta = do
putTxMetaT hdl meta `shouldReturn` Tx
putTxMetaT hdl meta `shouldReturn` No
mapM_ f metas
| null | https://raw.githubusercontent.com/input-output-hk/cardano-wallet-legacy/143e6d0dac0b28b3274600c6c49ec87e42ec9f37/test/nightly/TxMetaStorage.hs | haskell | # LANGUAGE RankNTypes #
beware of the big data.
beware of the big data.
beware of the big data.
beware of the big data.
beware of the big data.
beware of the big data.
| Handy combinator which yields a fresh database to work with on each spec.
| Synthetic @newtype@ used to generate unique inputs as part of
'genMetas'. The reason why it is necessary is because the stock implementation
However, this is too \"strong\" for our 'uniqueElements' generator.
| Eq is defined on the primary keys of Inputs.
double spend as they don`t use the same output.
have distinct txids and valid Inputs.
inserted in an empty db, with no violation.
This gives the promise that it can succesfully be inserted in an empty db,
with no violation.
anything, as this is a no-op. |
module TxMetaStorage
( spec
) where
import Universum
import Control.Concurrent.Async
import Control.Exception.Safe (bracket)
import qualified Data.List.NonEmpty as NonEmpty
import Formatting (bprint, (%))
import qualified Formatting as F
import Formatting.Buildable (build)
import Serokell.Util.Text (listJsonIndent, pairF)
import Test.Hspec (Spec, describe, it, shouldBe, shouldReturn)
import Test.QuickCheck (Arbitrary, Gen, arbitrary, vectorOf,
withMaxSuccess)
import Test.QuickCheck.Monadic (monadicIO, pick, run)
import Cardano.Wallet.Kernel.DB.TxMeta
import Pos.Chain.Txp (TxId)
import qualified Pos.Core as Core
# ANN module ( " HLint : ignore Reduce duplication " : : Text ) #
spec :: Spec
spec = do
describe "synchronization" $ do
it "synchronized with 2 write workers and no-ops" $ withMaxSuccess 5 $ monadicIO $ do
metas <- pick (genMetas 2000)
let (meta0, meta1) = splitAt (div 2000 2) metas
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWriteWithNoOp meta0 hdl
t1 <- async $ threadWriteWithNoOp meta1 hdl
traverse_ wait [t0, t1]
it "synchronized with 2 write workers and no-ops: correct count" $ withMaxSuccess 5 $ monadicIO $ do
metas <- pick (genMetas 200)
let (meta0, meta1) = splitAt (div 200 2) metas
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWriteWithNoOp meta0 hdl
t1 <- async $ threadWriteWithNoOp meta1 hdl
traverse_ wait [t0, t1]
(ls, _count) <- getTxMetas hdl (Offset 0) (Limit 300) Everything Nothing NoFilterOp NoFilterOp Nothing
length ls `shouldBe` 200
it "synchronized with 2 write workers" $ withMaxSuccess 5 $ monadicIO $ do
metas <- pick (genMetas 2000)
let (meta0, meta1) = splitAt (div 2000 2) metas
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWrite meta0 hdl
t1 <- async $ threadWrite meta1 hdl
traverse_ wait [t0, t1]
it "synchronized with 2 write workers: correct count" $ withMaxSuccess 5 $ monadicIO $ do
metas <- pick (genMetas 200)
let (meta0, meta1) = splitAt (div 200 2) metas
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWrite meta0 hdl
t1 <- async $ threadWrite meta1 hdl
traverse_ wait [t0, t1]
(ls, _count) <- getTxMetas hdl (Offset 0) (Limit 300) Everything Nothing NoFilterOp NoFilterOp Nothing
length ls `shouldBe` 200
it "synchronized 1 write and 1 read workers" $ withMaxSuccess 5 $ monadicIO $ do
metas <- pick (genMetas 2000)
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWriteWithNoOp metas hdl
t1 <- async $ threadRead 2000 hdl
traverse_ wait [t0, t1]
it "synchronized 1 write and 1 read workers: correct count" $ withMaxSuccess 5 $ monadicIO $ do
metas <- pick (genMetas 200)
run $ withTemporaryDb $ \hdl -> do
t0 <- async $ threadWriteWithNoOp metas hdl
t1 <- async $ threadRead 200 hdl
traverse_ wait [t0, t1]
(ls, _count) <- getTxMetas hdl (Offset 0) (Limit 300) Everything Nothing NoFilterOp NoFilterOp Nothing
length ls `shouldBe` 200
withTemporaryDb :: forall m a. (MonadIO m, MonadMask m) => (MetaDBHandle -> m a) -> m a
withTemporaryDb action = bracket acquire release action
where
acquire :: m MetaDBHandle
acquire = liftIO $ do
db <- openMetaDB ":memory:"
migrateMetaDB db
return db
release :: MetaDBHandle -> m ()
release = liftIO . closeMetaDB
of ' ' would of course declare two tuples equal if their elements are .
newtype Input = Input { getInput :: (TxId, Word32, Core.Address, Core.Coin) }
deriving (Show)
instance Eq Input where
(Input (id1, ix1, _, _)) == (Input (id2, ix2, _, _)) = (id1, ix1) == (id2, ix2)
| This ensures that Inputs generated for the same Tx from getMetas , do not
instance Ord Input where
compare (Input (id1, ix1, _, _)) (Input (id2, ix2, _, _)) = compare (id1, ix1) (id2, ix2)
instance Arbitrary Input where
arbitrary = Input <$> arbitrary
instance Buildable Input where
build (Input (a, b, c, d)) =
bprint ("(" % F.build % ", " % F.build % ", " % F.build % ", " % F.build % ")")
a b c d
instance Buildable (Int, Input) where
build b = bprint pairF b
instance Buildable [Input] where
build = bprint (listJsonIndent 4)
newtype Output = Output { getOutput :: (Core.Address, Core.Coin) }
instance Arbitrary Output where
arbitrary = Output <$> arbitrary
| Handy generator which make sure we are generating ' TxMeta ' which all
This gives the promise that all @size@ number of TxMeta can succesfully be
genMetas :: Int -> Gen [TxMeta]
genMetas size = do
txids <- uniqueElements size
(metas1 :: [TxMeta]) <- vectorOf size genMeta
let metas = (\(txid, m) -> m{_txMetaId = txid}) <$> zip (NonEmpty.toList txids) metas1
return metas
| Generator for an arbitrary ' TxMeta ' with valid Inputs .
genMeta :: Gen (TxMeta)
genMeta = TxMeta
<$> arbitrary
<*> arbitrary
<*> (fmap getInput <$> uniqueElements 2)
<*> (fmap getOutput . NonEmpty.fromList <$> vectorOf 2 arbitrary)
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
threadRead :: Int -> MetaDBHandle -> IO ()
threadRead times hdl = do
let getNoFilters = getTxMetas hdl (Offset 0) (Limit 100) Everything Nothing NoFilterOp NoFilterOp Nothing
replicateM_ times getNoFilters
threadWrite :: [TxMeta] -> MetaDBHandle -> IO ()
threadWrite metas hdl = do
let f meta = do
putTxMetaT hdl meta `shouldReturn` Tx
mapM_ f metas
here we try to add the same tx 2 times . The second must fail , but without crashing
threadWriteWithNoOp :: [TxMeta] -> MetaDBHandle -> IO ()
threadWriteWithNoOp metas hdl = do
let f meta = do
putTxMetaT hdl meta `shouldReturn` Tx
putTxMetaT hdl meta `shouldReturn` No
mapM_ f metas
|
091be6b2cebb4c379969ee4473613f2a078f25749579f8a67276cef973b33789 | ReedOei/CMips | Types.hs | {-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE StandaloneDeriving #
module Types where
import Control.Lens (makeLenses, (^.), set, over)
import Data.Map (Map)
import qualified Data.Map as Map
import CLanguage
import MIPSLanguage
import Util
data Invariant = InvariantExpr CExpression -- Either an expression that is true
| InvariantAnnotation Annotation String -- Or an annotation for a particular variable
deriving (Show, Eq)
data Parent = FileParent CFile
| ElementParent CElement
| StatementParent CStatement
| ExprParent CExpression
deriving (Show, Eq)
class Parentable a where
makeParent :: a -> Parent
data Warning where
Warning :: forall t. PrettyPrint t => Context t -> String -> Warning
data Context t = Context
{ _parents :: [Parent]
, _funcName :: Maybe String
, _invariants :: [Invariant]
, _val :: t }
makeLenses ''Context
instance Show Warning where
show (Warning context message) =
case context ^. funcName of
Nothing -> prettyPrint (context ^. val) ++ ": " ++ message
Just fname -> fname ++ ": " ++ prettyPrint (context ^. val) ++ ": " ++ message
deriving instance Show t => Show (Context t)
deriving instance Eq t => Eq (Context t)
emptyContext = Context [] Nothing []
data CompileOptions = CompileOptions
{ _optimizeLevel :: Int
, _useInlining :: Bool }
deriving Show
makeLenses ''CompileOptions
defaultCompileOptions = CompileOptions 1 True
-- Name, type, value
-- e.g.:
-- str: .asciiz "hello world"
temp : .space 8
data DataElement = DataElement String String String
deriving Show
-- Things to store in the data/kdata sections
data Data = Data [DataElement] [DataElement]
deriving Show
-- Contains:
-- Map function names to labels.
-- List of labels that have been used.
data Global = Global
{ _labels :: [String]
, _funcs :: Map String (String, String)
, _curFunc :: String }
deriving Show
makeLenses ''Global
-- Contains:
-- Amount of stack space used.
-- Map of registers to variable names.
data Local = Local
{ _stack :: Int
, _registers :: Map String String
, _stackLocs :: Map String String }
deriving Show
makeLenses ''Local
data Environment = Environment
{ _file :: CFile
, _dataSections :: Data
, _global :: Global
, _local :: Local
, _compiled :: Map String [MIPSInstruction] -- The compiled assembly for all functions that have been compiled so far.
, _warnings :: [Warning]
, _compileOptions :: CompileOptions }
deriving Show
makeLenses ''Environment
defaultContext file = Context [FileParent file] Nothing []
class Enumerable t where
enumElement :: Context CElement -> [Context t]
enumStatement :: Context CStatement -> [Context t]
enumExpr :: Context CExpression -> [Context t]
enumFile :: CFile -> [Context t]
enumFile file@(CFile _ elements) = concatMap (enumElement . defaultContext file) elements
| null | https://raw.githubusercontent.com/ReedOei/CMips/daae33aeba31d0f4b0a97fab206b2726566d5ee4/src/Types.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE GADTs #
Either an expression that is true
Or an annotation for a particular variable
Name, type, value
e.g.:
str: .asciiz "hello world"
Things to store in the data/kdata sections
Contains:
Map function names to labels.
List of labels that have been used.
Contains:
Amount of stack space used.
Map of registers to variable names.
The compiled assembly for all functions that have been compiled so far. | # LANGUAGE TemplateHaskell #
# LANGUAGE StandaloneDeriving #
module Types where
import Control.Lens (makeLenses, (^.), set, over)
import Data.Map (Map)
import qualified Data.Map as Map
import CLanguage
import MIPSLanguage
import Util
deriving (Show, Eq)
data Parent = FileParent CFile
| ElementParent CElement
| StatementParent CStatement
| ExprParent CExpression
deriving (Show, Eq)
class Parentable a where
makeParent :: a -> Parent
data Warning where
Warning :: forall t. PrettyPrint t => Context t -> String -> Warning
data Context t = Context
{ _parents :: [Parent]
, _funcName :: Maybe String
, _invariants :: [Invariant]
, _val :: t }
makeLenses ''Context
instance Show Warning where
show (Warning context message) =
case context ^. funcName of
Nothing -> prettyPrint (context ^. val) ++ ": " ++ message
Just fname -> fname ++ ": " ++ prettyPrint (context ^. val) ++ ": " ++ message
deriving instance Show t => Show (Context t)
deriving instance Eq t => Eq (Context t)
emptyContext = Context [] Nothing []
data CompileOptions = CompileOptions
{ _optimizeLevel :: Int
, _useInlining :: Bool }
deriving Show
makeLenses ''CompileOptions
defaultCompileOptions = CompileOptions 1 True
temp : .space 8
data DataElement = DataElement String String String
deriving Show
data Data = Data [DataElement] [DataElement]
deriving Show
data Global = Global
{ _labels :: [String]
, _funcs :: Map String (String, String)
, _curFunc :: String }
deriving Show
makeLenses ''Global
data Local = Local
{ _stack :: Int
, _registers :: Map String String
, _stackLocs :: Map String String }
deriving Show
makeLenses ''Local
data Environment = Environment
{ _file :: CFile
, _dataSections :: Data
, _global :: Global
, _local :: Local
, _warnings :: [Warning]
, _compileOptions :: CompileOptions }
deriving Show
makeLenses ''Environment
defaultContext file = Context [FileParent file] Nothing []
class Enumerable t where
enumElement :: Context CElement -> [Context t]
enumStatement :: Context CStatement -> [Context t]
enumExpr :: Context CExpression -> [Context t]
enumFile :: CFile -> [Context t]
enumFile file@(CFile _ elements) = concatMap (enumElement . defaultContext file) elements
|
9158c2d5f920b632842aa8a8eb47193c8813fe271bc76a25dc780a4f475e083f | LeventErkok/hArduino | Blink.hs | -------------------------------------------------------------------------------
-- |
Module : System . Hardware . Arduino . SamplePrograms . Blink
Copyright : ( c )
-- License : BSD3
-- Maintainer :
-- Stability : experimental
--
-- The /hello world/ of the arduino world, blinking the led.
-------------------------------------------------------------------------------
module System.Hardware.Arduino.SamplePrograms.Blink where
import Control.Monad (forever)
import System.Hardware.Arduino
| Blink the led connected to port 13 on the Arduino UNO board .
--
-- Note that you do not need any other components to run this example: Just hook
up your Arduino to the computer and make sure StandardFirmata is running on it .
However , you can connect a LED between and GND if you want to blink an
-- external led as well, as depicted below:
--
-- <<>>
blink :: IO ()
blink = withArduino False "/dev/cu.usbmodemFD131" $ do
let led = digital 13
setPinMode led OUTPUT
forever $ do digitalWrite led True
delay 1000
digitalWrite led False
delay 1000
| null | https://raw.githubusercontent.com/LeventErkok/hArduino/ee04988ad9ef3d4384d7ce7a8670518ce8b0a34c/System/Hardware/Arduino/SamplePrograms/Blink.hs | haskell | -----------------------------------------------------------------------------
|
License : BSD3
Maintainer :
Stability : experimental
The /hello world/ of the arduino world, blinking the led.
-----------------------------------------------------------------------------
Note that you do not need any other components to run this example: Just hook
external led as well, as depicted below:
<<>> | Module : System . Hardware . Arduino . SamplePrograms . Blink
Copyright : ( c )
module System.Hardware.Arduino.SamplePrograms.Blink where
import Control.Monad (forever)
import System.Hardware.Arduino
| Blink the led connected to port 13 on the Arduino UNO board .
up your Arduino to the computer and make sure StandardFirmata is running on it .
However , you can connect a LED between and GND if you want to blink an
blink :: IO ()
blink = withArduino False "/dev/cu.usbmodemFD131" $ do
let led = digital 13
setPinMode led OUTPUT
forever $ do digitalWrite led True
delay 1000
digitalWrite led False
delay 1000
|
1678781f769e751a339900faa6529e0505732f83ebda6ae0f7dcfea474b9b6b7 | kryonix/pg_cuckoo | GPrint.hs | |
Module : GPrint
Description : Generic printer implementation
Copyright : < >
License : AllRightsReserved
Maintainer :
This is the place where magic happens ¯\_(ツ)_/¯
Module : GPrint
Description : Generic printer implementation
Copyright : © Denis Hirn <>
License : AllRightsReserved
Maintainer : Denis Hirn
This is the place where magic happens ¯\_(ツ)_/¯
-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE DefaultSignatures #
module Database.PgCuckoo.GPrint
( GPrint(..)
, GPrint1(..)
) where
import GHC.Generics
import Data.List
import Data.String.Utils
-- | Implementation of a generic record printer
-- With these classes and instances we just have to define
our records properly and derive { Generic , } .
The generic method will then create the query - tree
-- format automagically.
defaultgprint :: (Generic a, GPrint1 (Rep a)) => a -> String
defaultgprint = gprint1 . from
class GPrint a where
gprint :: a -> String
default gprint :: (Generic a, GPrint1 (Rep a)) => a -> String
gprint = defaultgprint
class GPrint1 a where
gprint1 :: a p -> String
instance (GPrint a) => GPrint [a] where
gprint [] = "<>"
gprint xs = "(" ++ (intercalate " " $ map gprint xs) ++ ")"
instance (GPrint a) => GPrint (Maybe a) where
gprint Nothing = "<>"
gprint (Just x) = gprint x
instance {-# OVERLAPS #-} GPrint String where
gprint x = replace " " "\\ " x
instance GPrint Integer where
gprint x = show x
instance GPrint Double where
gprint x = show x
instance GPrint Bool where
gprint True = "true"
gprint False = "false"
-- | Fallback instance when no GPrint1 instance is defined
instance {-# OVERLAPPABLE #-} (GPrint a) => GPrint1 (K1 i a) where
gprint1 (K1 x) = gprint x
DataType name , we 're going to ignore this and just pass through
instance (GPrint1 f, Datatype c) => GPrint1 (M1 D c f) where
gprint1 m@(M1 x) = gprint1 x
-- Constructor name, we want to use this as the node type
instance (GPrint1 f, Constructor c) => GPrint1 (M1 C c f) where
gprint1 m@(M1 x) = case conName m of
"GenericPlan" -> gprint1 x
"GenericRangeExPre" -> gprint1 x
"GenericRangeExPost" -> gprint1 x
c -> "{" ++ takeWhile (/= '_') c ++ " " ++ gprint1 x ++ "}"
-- Selector name, those are gonna be our fields
instance (GPrint1 f, Selector s) => GPrint1 (M1 S s f) where
gprint1 m@(M1 x) = sel ++ gprint1 x
where
sel = case selName m of
"" -> ""
"genericPlan" -> ""
"genericRangeExPre" -> ""
"genericRangeExPost" -> ""
e -> ":" ++ dropWhile (== '_') e ++ " "
instance (GPrint1 a, GPrint1 b) => GPrint1 (a :*: b) where
gprint1 (a :*: b) = gprint1 a ++ " " ++ gprint1 b
instance (GPrint1 a, GPrint1 b) => GPrint1 (a :+: b) where
gprint1 (L1 x) = gprint1 x
gprint1 (R1 x) = gprint1 x
| null | https://raw.githubusercontent.com/kryonix/pg_cuckoo/755e3199b4831d99e716637fbbebbe794a9a7104/PgCuckoo/src/Database/PgCuckoo/GPrint.hs | haskell | # LANGUAGE TypeOperators #
| Implementation of a generic record printer
With these classes and instances we just have to define
format automagically.
# OVERLAPS #
| Fallback instance when no GPrint1 instance is defined
# OVERLAPPABLE #
Constructor name, we want to use this as the node type
Selector name, those are gonna be our fields | |
Module : GPrint
Description : Generic printer implementation
Copyright : < >
License : AllRightsReserved
Maintainer :
This is the place where magic happens ¯\_(ツ)_/¯
Module : GPrint
Description : Generic printer implementation
Copyright : © Denis Hirn <>
License : AllRightsReserved
Maintainer : Denis Hirn
This is the place where magic happens ¯\_(ツ)_/¯
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE DefaultSignatures #
module Database.PgCuckoo.GPrint
( GPrint(..)
, GPrint1(..)
) where
import GHC.Generics
import Data.List
import Data.String.Utils
our records properly and derive { Generic , } .
The generic method will then create the query - tree
defaultgprint :: (Generic a, GPrint1 (Rep a)) => a -> String
defaultgprint = gprint1 . from
class GPrint a where
gprint :: a -> String
default gprint :: (Generic a, GPrint1 (Rep a)) => a -> String
gprint = defaultgprint
class GPrint1 a where
gprint1 :: a p -> String
instance (GPrint a) => GPrint [a] where
gprint [] = "<>"
gprint xs = "(" ++ (intercalate " " $ map gprint xs) ++ ")"
instance (GPrint a) => GPrint (Maybe a) where
gprint Nothing = "<>"
gprint (Just x) = gprint x
gprint x = replace " " "\\ " x
instance GPrint Integer where
gprint x = show x
instance GPrint Double where
gprint x = show x
instance GPrint Bool where
gprint True = "true"
gprint False = "false"
gprint1 (K1 x) = gprint x
DataType name , we 're going to ignore this and just pass through
instance (GPrint1 f, Datatype c) => GPrint1 (M1 D c f) where
gprint1 m@(M1 x) = gprint1 x
instance (GPrint1 f, Constructor c) => GPrint1 (M1 C c f) where
gprint1 m@(M1 x) = case conName m of
"GenericPlan" -> gprint1 x
"GenericRangeExPre" -> gprint1 x
"GenericRangeExPost" -> gprint1 x
c -> "{" ++ takeWhile (/= '_') c ++ " " ++ gprint1 x ++ "}"
instance (GPrint1 f, Selector s) => GPrint1 (M1 S s f) where
gprint1 m@(M1 x) = sel ++ gprint1 x
where
sel = case selName m of
"" -> ""
"genericPlan" -> ""
"genericRangeExPre" -> ""
"genericRangeExPost" -> ""
e -> ":" ++ dropWhile (== '_') e ++ " "
instance (GPrint1 a, GPrint1 b) => GPrint1 (a :*: b) where
gprint1 (a :*: b) = gprint1 a ++ " " ++ gprint1 b
instance (GPrint1 a, GPrint1 b) => GPrint1 (a :+: b) where
gprint1 (L1 x) = gprint1 x
gprint1 (R1 x) = gprint1 x
|
2c8e078d384ae0377ddcc5b043e0dc5d12594ff93dccd59f5122892d24137a36 | lsrcz/grisette | Union.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveLift #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE Trustworthy #
# LANGUAGE TypeFamilies #
-- |
Module : . Core . Data . Union
Copyright : ( c ) 2021 - 2023
-- License : BSD-3-Clause (see the LICENSE file)
--
-- Maintainer :
-- Stability : Experimental
Portability : GHC only
module Grisette.Core.Data.Union
( -- * The union data structure.
| Please consider using ' . Core . Control . Monad . UnionM ' instead .
Union (..),
ifWithLeftMost,
ifWithStrategy,
fullReconstruct,
)
where
import Control.DeepSeq
import Data.Functor.Classes
import Data.Hashable
import GHC.Generics
import Grisette.Core.Data.Class.Bool
import Grisette.Core.Data.Class.Mergeable
import Grisette.Core.Data.Class.SimpleMergeable
import Grisette.Core.Data.Class.Solvable
import {-# SOURCE #-} Grisette.IR.SymPrim.Data.SymPrim
import Language.Haskell.TH.Syntax
-- | The default union implementation.
data Union a
= -- | A single value
Single a
| -- | A if value
If
a
-- ^ Cached leftmost value
!Bool
-- ^ Is merged invariant already maintained?
!SymBool
-- ^ If condition
(Union a)
-- ^ True branch
(Union a)
-- ^ False branch
deriving (Generic, Eq, Lift, Generic1)
instance Eq1 Union where
liftEq e (Single a) (Single b) = e a b
liftEq e (If l1 i1 c1 t1 f1) (If l2 i2 c2 t2 f2) =
e l1 l2 && i1 == i2 && c1 == c2 && liftEq e t1 t2 && liftEq e f1 f2
liftEq _ _ _ = False
instance (NFData a) => NFData (Union a) where
rnf = rnf1
instance NFData1 Union where
liftRnf _a (Single a) = _a a
liftRnf _a (If a bo b l r) = _a a `seq` rnf bo `seq` rnf b `seq` liftRnf _a l `seq` liftRnf _a r
-- | Build 'If' with leftmost cache correctly maintained.
--
-- Usually you should never directly try to build a 'If' with its constructor.
ifWithLeftMost :: Bool -> SymBool -> Union a -> Union a -> Union a
ifWithLeftMost _ (Con c) t f
| c = t
| otherwise = f
ifWithLeftMost inv cond t f = If (leftMost t) inv cond t f
# INLINE ifWithLeftMost #
instance UnionPrjOp Union where
singleView (Single a) = Just a
singleView _ = Nothing
# INLINE singleView #
ifView (If _ _ cond ifTrue ifFalse) = Just (cond, ifTrue, ifFalse)
ifView _ = Nothing
# INLINE ifView #
leftMost (Single a) = a
leftMost (If a _ _ _ _) = a
# INLINE leftMost #
instance (Mergeable a) => Mergeable (Union a) where
rootStrategy = SimpleStrategy $ ifWithStrategy rootStrategy
# INLINE rootStrategy #
instance Mergeable1 Union where
liftRootStrategy ms = SimpleStrategy $ ifWithStrategy ms
# INLINE liftRootStrategy #
instance (Mergeable a) => SimpleMergeable (Union a) where
mrgIte = mrgIf
instance SimpleMergeable1 Union where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
instance UnionLike Union where
mergeWithStrategy = fullReconstruct
# INLINE mergeWithStrategy #
single = Single
# INLINE single #
unionIf = ifWithLeftMost False
# INLINE unionIf #
mrgIfWithStrategy = ifWithStrategy
# INLINE mrgIfWithStrategy #
mrgSingleWithStrategy _ = Single
# INLINE mrgSingleWithStrategy #
instance Show1 Union where
liftShowsPrec sp _ i (Single a) = showsUnaryWith sp "Single" i a
liftShowsPrec sp sl i (If _ _ cond t f) =
showParen (i > 10) $
showString "If" . showChar ' ' . showsPrec 11 cond . showChar ' ' . sp1 11 t . showChar ' ' . sp1 11 f
where
sp1 = liftShowsPrec sp sl
instance (Show a) => Show (Union a) where
showsPrec = showsPrec1
instance (Hashable a) => Hashable (Union a) where
s `hashWithSalt` (Single a) = s `hashWithSalt` (0 :: Int) `hashWithSalt` a
s `hashWithSalt` (If _ _ c l r) = s `hashWithSalt` (1 :: Int) `hashWithSalt` c `hashWithSalt` l `hashWithSalt` r
instance AllSyms a => AllSyms (Union a) where
allSymsS (Single v) = allSymsS v
allSymsS (If _ _ c t f) = \l -> SomeSym c : (allSymsS t . allSymsS f $ l)
-- | Fully reconstruct a 'Union' to maintain the merged invariant.
fullReconstruct :: MergingStrategy a -> Union a -> Union a
fullReconstruct strategy (If _ False cond t f) =
ifWithStrategyInv strategy cond (fullReconstruct strategy t) (fullReconstruct strategy f)
fullReconstruct _ u = u
# INLINE fullReconstruct #
-- | Use a specific strategy to build a 'If' value.
--
-- The merged invariant will be maintained in the result.
ifWithStrategy ::
MergingStrategy a ->
SymBool ->
Union a ->
Union a ->
Union a
ifWithStrategy strategy cond t@(If _ False _ _ _) f = ifWithStrategy strategy cond (fullReconstruct strategy t) f
ifWithStrategy strategy cond t f@(If _ False _ _ _) = ifWithStrategy strategy cond t (fullReconstruct strategy f)
ifWithStrategy strategy cond t f = ifWithStrategyInv strategy cond t f
# INLINE ifWithStrategy #
ifWithStrategyInv ::
MergingStrategy a ->
SymBool ->
Union a ->
Union a ->
Union a
ifWithStrategyInv _ (Con v) t f
| v = t
| otherwise = f
ifWithStrategyInv strategy cond (If _ True condTrue tt _) f
| cond == condTrue = ifWithStrategyInv strategy cond tt f
-- {| nots cond == condTrue || cond == nots condTrue = ifWithStrategyInv strategy cond ft f
ifWithStrategyInv strategy cond t (If _ True condFalse _ ff)
| cond == condFalse = ifWithStrategyInv strategy cond t ff
-- {| nots cond == condTrue || cond == nots condTrue = ifWithStrategyInv strategy cond t tf -- buggy here condTrue
ifWithStrategyInv (SimpleStrategy m) cond (Single l) (Single r) = Single $ m cond l r
ifWithStrategyInv strategy@(SortedStrategy idxFun substrategy) cond ifTrue ifFalse = case (ifTrue, ifFalse) of
(Single _, Single _) -> ssIf cond ifTrue ifFalse
(Single _, If {}) -> sgIf cond ifTrue ifFalse
(If {}, Single _) -> gsIf cond ifTrue ifFalse
_ -> ggIf cond ifTrue ifFalse
where
ssIf cond' ifTrue' ifFalse'
| idxt < idxf = ifWithLeftMost True cond' ifTrue' ifFalse'
| idxt == idxf = ifWithStrategyInv (substrategy idxt) cond' ifTrue' ifFalse'
| otherwise = ifWithLeftMost True (nots cond') ifFalse' ifTrue'
where
idxt = idxFun $ leftMost ifTrue'
idxf = idxFun $ leftMost ifFalse'
# INLINE ssIf #
sgIf cond' ifTrue' ifFalse'@(If _ True condf ft ff)
| idxft == idxff = ssIf cond' ifTrue' ifFalse'
| idxt < idxft = ifWithLeftMost True cond' ifTrue' ifFalse'
| idxt == idxft = ifWithLeftMost True (cond' ||~ condf) (ifWithStrategyInv (substrategy idxt) cond' ifTrue' ft) ff
| otherwise = ifWithLeftMost True (nots cond' &&~ condf) ft (ifWithStrategyInv strategy cond' ifTrue' ff)
where
idxft = idxFun $ leftMost ft
idxff = idxFun $ leftMost ff
idxt = idxFun $ leftMost ifTrue'
sgIf _ _ _ = undefined
# INLINE sgIf #
gsIf cond' ifTrue'@(If _ True condt tt tf) ifFalse'
| idxtt == idxtf = ssIf cond' ifTrue' ifFalse'
| idxtt < idxf = ifWithLeftMost True (cond' &&~ condt) tt $ ifWithStrategyInv strategy cond' tf ifFalse'
| idxtt == idxf = ifWithLeftMost True (nots cond' ||~ condt) (ifWithStrategyInv (substrategy idxf) cond' tt ifFalse') tf
| otherwise = ifWithLeftMost True (nots cond') ifFalse' ifTrue'
where
idxtt = idxFun $ leftMost tt
idxtf = idxFun $ leftMost tf
idxf = idxFun $ leftMost ifFalse'
gsIf _ _ _ = undefined
# INLINE gsIf #
ggIf cond' ifTrue'@(If _ True condt tt tf) ifFalse'@(If _ True condf ft ff)
| idxtt == idxtf = sgIf cond' ifTrue' ifFalse'
| idxft == idxff = gsIf cond' ifTrue' ifFalse'
| idxtt < idxft = ifWithLeftMost True (cond' &&~ condt) tt $ ifWithStrategyInv strategy cond' tf ifFalse'
| idxtt == idxft =
let newCond = ites cond' condt condf
newIfTrue = ifWithStrategyInv (substrategy idxtt) cond' tt ft
newIfFalse = ifWithStrategyInv strategy cond' tf ff
in ifWithLeftMost True newCond newIfTrue newIfFalse
| otherwise = ifWithLeftMost True (nots cond' &&~ condf) ft $ ifWithStrategyInv strategy cond' ifTrue' ff
where
idxtt = idxFun $ leftMost tt
idxtf = idxFun $ leftMost tf
idxft = idxFun $ leftMost ft
idxff = idxFun $ leftMost ff
ggIf _ _ _ = undefined
# INLINE ggIf #
ifWithStrategyInv NoStrategy cond ifTrue ifFalse = ifWithLeftMost True cond ifTrue ifFalse
ifWithStrategyInv _ _ _ _ = error "Invariant violated"
# INLINE ifWithStrategyInv #
| null | https://raw.githubusercontent.com/lsrcz/grisette/b8d6079ce5c44975bfa5dfba214a9f5874b93214/src/Grisette/Core/Data/Union.hs | haskell | # LANGUAGE DeriveLift #
|
License : BSD-3-Clause (see the LICENSE file)
Maintainer :
Stability : Experimental
* The union data structure.
# SOURCE #
| The default union implementation.
| A single value
| A if value
^ Cached leftmost value
^ Is merged invariant already maintained?
^ If condition
^ True branch
^ False branch
| Build 'If' with leftmost cache correctly maintained.
Usually you should never directly try to build a 'If' with its constructor.
| Fully reconstruct a 'Union' to maintain the merged invariant.
| Use a specific strategy to build a 'If' value.
The merged invariant will be maintained in the result.
{| nots cond == condTrue || cond == nots condTrue = ifWithStrategyInv strategy cond ft f
{| nots cond == condTrue || cond == nots condTrue = ifWithStrategyInv strategy cond t tf -- buggy here condTrue | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE Trustworthy #
# LANGUAGE TypeFamilies #
Module : . Core . Data . Union
Copyright : ( c ) 2021 - 2023
Portability : GHC only
module Grisette.Core.Data.Union
| Please consider using ' . Core . Control . Monad . UnionM ' instead .
Union (..),
ifWithLeftMost,
ifWithStrategy,
fullReconstruct,
)
where
import Control.DeepSeq
import Data.Functor.Classes
import Data.Hashable
import GHC.Generics
import Grisette.Core.Data.Class.Bool
import Grisette.Core.Data.Class.Mergeable
import Grisette.Core.Data.Class.SimpleMergeable
import Grisette.Core.Data.Class.Solvable
import Language.Haskell.TH.Syntax
data Union a
Single a
If
a
!Bool
!SymBool
(Union a)
(Union a)
deriving (Generic, Eq, Lift, Generic1)
instance Eq1 Union where
liftEq e (Single a) (Single b) = e a b
liftEq e (If l1 i1 c1 t1 f1) (If l2 i2 c2 t2 f2) =
e l1 l2 && i1 == i2 && c1 == c2 && liftEq e t1 t2 && liftEq e f1 f2
liftEq _ _ _ = False
instance (NFData a) => NFData (Union a) where
rnf = rnf1
instance NFData1 Union where
liftRnf _a (Single a) = _a a
liftRnf _a (If a bo b l r) = _a a `seq` rnf bo `seq` rnf b `seq` liftRnf _a l `seq` liftRnf _a r
ifWithLeftMost :: Bool -> SymBool -> Union a -> Union a -> Union a
ifWithLeftMost _ (Con c) t f
| c = t
| otherwise = f
ifWithLeftMost inv cond t f = If (leftMost t) inv cond t f
# INLINE ifWithLeftMost #
instance UnionPrjOp Union where
singleView (Single a) = Just a
singleView _ = Nothing
# INLINE singleView #
ifView (If _ _ cond ifTrue ifFalse) = Just (cond, ifTrue, ifFalse)
ifView _ = Nothing
# INLINE ifView #
leftMost (Single a) = a
leftMost (If a _ _ _ _) = a
# INLINE leftMost #
instance (Mergeable a) => Mergeable (Union a) where
rootStrategy = SimpleStrategy $ ifWithStrategy rootStrategy
# INLINE rootStrategy #
instance Mergeable1 Union where
liftRootStrategy ms = SimpleStrategy $ ifWithStrategy ms
# INLINE liftRootStrategy #
instance (Mergeable a) => SimpleMergeable (Union a) where
mrgIte = mrgIf
instance SimpleMergeable1 Union where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
instance UnionLike Union where
mergeWithStrategy = fullReconstruct
# INLINE mergeWithStrategy #
single = Single
# INLINE single #
unionIf = ifWithLeftMost False
# INLINE unionIf #
mrgIfWithStrategy = ifWithStrategy
# INLINE mrgIfWithStrategy #
mrgSingleWithStrategy _ = Single
# INLINE mrgSingleWithStrategy #
instance Show1 Union where
liftShowsPrec sp _ i (Single a) = showsUnaryWith sp "Single" i a
liftShowsPrec sp sl i (If _ _ cond t f) =
showParen (i > 10) $
showString "If" . showChar ' ' . showsPrec 11 cond . showChar ' ' . sp1 11 t . showChar ' ' . sp1 11 f
where
sp1 = liftShowsPrec sp sl
instance (Show a) => Show (Union a) where
showsPrec = showsPrec1
instance (Hashable a) => Hashable (Union a) where
s `hashWithSalt` (Single a) = s `hashWithSalt` (0 :: Int) `hashWithSalt` a
s `hashWithSalt` (If _ _ c l r) = s `hashWithSalt` (1 :: Int) `hashWithSalt` c `hashWithSalt` l `hashWithSalt` r
instance AllSyms a => AllSyms (Union a) where
allSymsS (Single v) = allSymsS v
allSymsS (If _ _ c t f) = \l -> SomeSym c : (allSymsS t . allSymsS f $ l)
fullReconstruct :: MergingStrategy a -> Union a -> Union a
fullReconstruct strategy (If _ False cond t f) =
ifWithStrategyInv strategy cond (fullReconstruct strategy t) (fullReconstruct strategy f)
fullReconstruct _ u = u
# INLINE fullReconstruct #
ifWithStrategy ::
MergingStrategy a ->
SymBool ->
Union a ->
Union a ->
Union a
ifWithStrategy strategy cond t@(If _ False _ _ _) f = ifWithStrategy strategy cond (fullReconstruct strategy t) f
ifWithStrategy strategy cond t f@(If _ False _ _ _) = ifWithStrategy strategy cond t (fullReconstruct strategy f)
ifWithStrategy strategy cond t f = ifWithStrategyInv strategy cond t f
# INLINE ifWithStrategy #
ifWithStrategyInv ::
MergingStrategy a ->
SymBool ->
Union a ->
Union a ->
Union a
ifWithStrategyInv _ (Con v) t f
| v = t
| otherwise = f
ifWithStrategyInv strategy cond (If _ True condTrue tt _) f
| cond == condTrue = ifWithStrategyInv strategy cond tt f
ifWithStrategyInv strategy cond t (If _ True condFalse _ ff)
| cond == condFalse = ifWithStrategyInv strategy cond t ff
ifWithStrategyInv (SimpleStrategy m) cond (Single l) (Single r) = Single $ m cond l r
ifWithStrategyInv strategy@(SortedStrategy idxFun substrategy) cond ifTrue ifFalse = case (ifTrue, ifFalse) of
(Single _, Single _) -> ssIf cond ifTrue ifFalse
(Single _, If {}) -> sgIf cond ifTrue ifFalse
(If {}, Single _) -> gsIf cond ifTrue ifFalse
_ -> ggIf cond ifTrue ifFalse
where
ssIf cond' ifTrue' ifFalse'
| idxt < idxf = ifWithLeftMost True cond' ifTrue' ifFalse'
| idxt == idxf = ifWithStrategyInv (substrategy idxt) cond' ifTrue' ifFalse'
| otherwise = ifWithLeftMost True (nots cond') ifFalse' ifTrue'
where
idxt = idxFun $ leftMost ifTrue'
idxf = idxFun $ leftMost ifFalse'
# INLINE ssIf #
sgIf cond' ifTrue' ifFalse'@(If _ True condf ft ff)
| idxft == idxff = ssIf cond' ifTrue' ifFalse'
| idxt < idxft = ifWithLeftMost True cond' ifTrue' ifFalse'
| idxt == idxft = ifWithLeftMost True (cond' ||~ condf) (ifWithStrategyInv (substrategy idxt) cond' ifTrue' ft) ff
| otherwise = ifWithLeftMost True (nots cond' &&~ condf) ft (ifWithStrategyInv strategy cond' ifTrue' ff)
where
idxft = idxFun $ leftMost ft
idxff = idxFun $ leftMost ff
idxt = idxFun $ leftMost ifTrue'
sgIf _ _ _ = undefined
# INLINE sgIf #
gsIf cond' ifTrue'@(If _ True condt tt tf) ifFalse'
| idxtt == idxtf = ssIf cond' ifTrue' ifFalse'
| idxtt < idxf = ifWithLeftMost True (cond' &&~ condt) tt $ ifWithStrategyInv strategy cond' tf ifFalse'
| idxtt == idxf = ifWithLeftMost True (nots cond' ||~ condt) (ifWithStrategyInv (substrategy idxf) cond' tt ifFalse') tf
| otherwise = ifWithLeftMost True (nots cond') ifFalse' ifTrue'
where
idxtt = idxFun $ leftMost tt
idxtf = idxFun $ leftMost tf
idxf = idxFun $ leftMost ifFalse'
gsIf _ _ _ = undefined
# INLINE gsIf #
ggIf cond' ifTrue'@(If _ True condt tt tf) ifFalse'@(If _ True condf ft ff)
| idxtt == idxtf = sgIf cond' ifTrue' ifFalse'
| idxft == idxff = gsIf cond' ifTrue' ifFalse'
| idxtt < idxft = ifWithLeftMost True (cond' &&~ condt) tt $ ifWithStrategyInv strategy cond' tf ifFalse'
| idxtt == idxft =
let newCond = ites cond' condt condf
newIfTrue = ifWithStrategyInv (substrategy idxtt) cond' tt ft
newIfFalse = ifWithStrategyInv strategy cond' tf ff
in ifWithLeftMost True newCond newIfTrue newIfFalse
| otherwise = ifWithLeftMost True (nots cond' &&~ condf) ft $ ifWithStrategyInv strategy cond' ifTrue' ff
where
idxtt = idxFun $ leftMost tt
idxtf = idxFun $ leftMost tf
idxft = idxFun $ leftMost ft
idxff = idxFun $ leftMost ff
ggIf _ _ _ = undefined
# INLINE ggIf #
ifWithStrategyInv NoStrategy cond ifTrue ifFalse = ifWithLeftMost True cond ifTrue ifFalse
ifWithStrategyInv _ _ _ _ = error "Invariant violated"
# INLINE ifWithStrategyInv #
|
5a1a8bfc0fd76973711e906f169a41c2075a4b4146c3491dd9ce06ce07c02580 | aupiff/boustro | Typography.hs | # LANGUAGE ExistentialQuantification #
{-# LANGUAGE OverloadedStrings #-}
module Typography
( measureLineHeight
, PageEvent(..)
, ViewDimensions(..)
, processedWords
, typesetPage
) where
import Control.Monad
import Data.JSString.Text
import Data.List (intersperse)
import Data.Maybe
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified JavaScript.JQuery as JQ hiding (filter, not)
import Prelude hiding (Word)
import Text.Hyphenation
import Server
import Debug.Trace
data PageEvent = NextPage | PrevPage | Resize | Start deriving (Show, Eq)
data ViewDimensions = ViewDimensions { fullWidth :: Int
, viewWidth :: Double
, viewHeight :: Double
, lineHeight :: Double
}
type Word = Item T.Text Double
type Txt = [Word]
type Line = [Word]
type Paragraph = [Line]
fold1 :: forall a b. (a -> b -> b) -> (a -> b) -> [a] -> Maybe b
fold1 _ _ [] = Nothing
fold1 _ g [x] = Just $ g x
fold1 f g (x:xs) = f x <$> fold1 f g xs
minWith :: forall a b. Ord b => (a -> b) -> [a] -> Maybe a
minWith f = fold1 choice id
where choice a b
| f a < f b = a
| otherwise = b
width :: Line -> Double
width l = sum (map itemWidth l)
-- bring this back in case of issues
-- where hyphenWidth = case last l of
-- (Penalty w _ _ _) -> w
-- _ -> 0
lineWaste :: Double -> Line -> Double
lineWaste textWidth l = numSpaces * weighting (spaceSize / numSpaces - spaceWidth) + hyphenPenalty + hyphenHeadPenalty
where spaceSize = textWidth - width l
numSpaces :: Double
numSpaces = fromIntegral . length $ filter itemIsBox l
-- penalize placing hyphen at end of line
hyphenPenalty = if itemIsPenalty (last l) then 10 else 0 -- what number should I use here?
-- I just need to see what wastes look like generally
disallow hyphens first
hyphenHeadPenalty = if itemIsPenalty (head l) then 1000000 else 0
weighting x -- too close is worse than too far apart : TODO This seems backwards to me
| x < 0 = x ^ (2 :: Int) -- spaces larger than optimal width
| otherwise = 3 * x ^ (2 :: Int) -- spaces smaller than optimal width
-- Write quickcheck properties for this
par1' :: Double -> Txt -> Paragraph
par1' textWidth = parLines . fromMaybe (trace "par1 minWith" ([], 0, 0)) . minWith waste
. fromMaybe (trace "par1' fold1" []) . fold1 step start
where
step :: Word -> [(Paragraph, Double, Double)] -> [(Paragraph, Double, Double)]
step w ps = let origin = (new w (fromMaybe (error $ "par1' step" ++ show ps) $ minWith waste ps) : map (glue w) ps)
result = filter fitH origin
in if null result then traceShow origin [fromMaybe (head origin) (minWith waste origin)] else result
start :: Word -> [(Paragraph, Double, Double)]
start w = [([[w]], itemWidth w, 0.0)]
new w ([l], _, 0) = ([w]:[l], itemWidth w, 0.0)
new w p@(ls, _, _) = ([w]:ls, itemWidth w, waste p)
-- TODO what is this 1/n about? space width? change this
glue w (l:ls, n, m) = ((w:l):ls, itemWidth w + n, m)
parLines (ls, _, _) = ls
widthHead (_, n, _) = n
wasteTail (_, _, m) = m
linwHead = lineWaste textWidth . head . parLines
waste ([_], _, _) = 0
waste p = linwHead p + wasteTail p
fitH p = widthHead p <= textWidth
typesetPage :: (ViewDimensions, ((Int, Int), PageEvent)) -> IO (Int, Int)
typesetPage ((ViewDimensions _ textWidth viewHeight lineH), ((0, wordsOnPage), PrevPage)) = return (0, wordsOnPage)
typesetPage ((ViewDimensions _ textWidth viewHeight lineH), ((wordNumber, wordsOnPage), pageEvent))
| pageEvent == NextPage && length processedWords == wordNumber + wordsOnPage = return (wordNumber, wordsOnPage)
| otherwise = do
3 is margin - bottom TODO remove this magic number
lineSpacing = (textHeight - fromIntegral linesPerPage * lineH) / (fromIntegral linesPerPage - 1)
numWords = round $ 30 * (textWidth / 700) * fromIntegral linesPerPage
textHeight = viewHeight * 0.9
wordNumber' <- case pageEvent of
NextPage -> return $ wordNumber + wordsOnPage
Start -> return 0
Resize -> return wordNumber
PrevPage -> do let boxify = wordsWithWidths . take numWords . reverse
boxesMeasure <- boxify $ take wordNumber processedWords
let parMeasure = take linesPerPage $ par1' textWidth boxesMeasure
wordsOnPageMeasure = sum $ map length parMeasure
return $ max 0 $ wordNumber - wordsOnPageMeasure
boxes <- wordsWithWidths . take numWords . drop wordNumber' $ processedWords
let par = take linesPerPage $ par1' textWidth boxes
wordsOnPage' = sum $ map length par
ls <- mapM (renderLine lineH textWidth lineSpacing) par
boustroLines <- boustro ls
-- Should I be applying this style every time? Definitely on window change
-- dim, so maybe it's not so bad.
textArea <- (JQ.empty >=> widthCss) =<< JQ.select "#boustro"
mapM_ (`JQ.appendJQuery` textArea) boustroLines
return (wordNumber', wordsOnPage')
where widthCss = JQ.setCss "width" (textToJSString . T.pack $ show textWidth)
wordsWithWidths :: [String] -> IO [Word]
wordsWithWidths inputWords = do
-- creating a temporary div specifically to measure the width of every element
scratchArea <- JQ.empty =<< JQ.select "#scratch-area"
mapM (\x -> do let t = T.pack x
jq <- toItem t
_ <- jq `JQ.appendJQuery` scratchArea
jqWidth <- JQ.getInnerWidth jq
return $ toItem' t jqWidth
) inputWords
where toItem' :: T.Text -> Double -> Word
toItem' "-" w = hyphen w "-"
toItem' " " _ = space spaceWidth
toItem' str w = Box w str
boustro :: [JQ.JQuery] -> IO [JQ.JQuery]
boustro [] = return []
boustro [l] = return [l]
boustro (l:l2:ls) = do ho <- reverseLine l2
fi <- boustro ls
return (l : ho : fi)
measureLineHeight :: IO Double
measureLineHeight = do
scratchArea <- JQ.empty =<< JQ.select "#scratch-area"
quux <- JQ.select ("<span>" <> textToJSString "Hail qQuuXX!" <> "</span>")
_ <- quux `JQ.appendJQuery` scratchArea
JQ.getInnerHeight quux
-- can this be a monoid?
data Item a b = Box b a -- Box w_i
Spring w_i y_i z_i
| Penalty b b Bool a -- Penalty w_i p_i f_i
instance Show b => Show (Item a b) where
show (Box w _) = "Box " ++ show w
show (Spring w _ _) = "Spring " ++ show w
show (Penalty w _ _ _) = "Penalty " ++ show w
all hypens are flagged penality items because we do n't want two hyphens in
-- a row
itemWidth :: Num b => Item a b -> b
itemWidth (Box w _) = w
itemWidth (Spring w _ _) = w
itemWidth ( Penalty w _ _ _ ) = w
itemWidth Penalty{} = 0
itemWidth' :: Num b => Item a b -> b
itemWidth' (Box w _) = w
itemWidth' (Spring w _ _) = w
itemWidth' (Penalty w _ _ _) = w
toItem :: T.Text -> IO JQ.JQuery
toItem "-" = JQ.select "<span>-</span>"
toItem " " = assignCssWidth spaceWidth =<< JQ.select "<span> </span>"
toItem str = JQ.select ("<span>" <> textToJSString str <> "</span>")
itemElement :: Word -> IO JQ.JQuery
itemElement (Box _ e) = JQ.select ("<span>" <> textToJSString e <> "</span>")
itemElement Spring{} = JQ.select "<span> </span>"
itemElement Penalty{} = JQ.select "<span>-</span>"
itemIsSpace :: forall t s . Item t s -> Bool
itemIsSpace Spring{} = True
itemIsSpace _ = False
itemIsBox :: forall t s . Item t s -> Bool
itemIsBox Box{} = True
itemIsBox _ = False
itemIsPenalty :: forall t s . Item t s -> Bool
itemIsPenalty Penalty{} = True
itemIsPenalty _ = False
spaceWidth :: Double
spaceWidth = 6
space :: Double -> Word
space w = Spring w 3 2
TODO rename this
assignCssWidth :: Double -> JQ.JQuery -> IO JQ.JQuery
assignCssWidth txtWidth =
JQ.setCss "display" "inline-block"
<=< JQ.setCss "width" (textToJSString . T.pack $ show txtWidth)
hyphen :: Double -> T.Text -> Word
hyphen hyphenWidth = Penalty hyphenWidth penaltyValue False
where penaltyValue = undefined -- TODO I may not end up using this
renderLine :: Double -> Double -> Double -> [Word] -> IO JQ.JQuery
renderLine lineH textW lineSpacing ls = do
lineDiv <- JQ.select "<div class='line'></div>"
>>= JQ.setCss "width" (textToJSString . T.pack $ show textW)
>>= JQ.setCss "height" (textToJSString . T.pack $ show lineH)
>>= JQ.setCss "white-space" "nowrap"
>>= JQ.setCss "margin-bottom" ((textToJSString . T.pack . show $ lineSpacing) <> "px")
let nls = foldr dehyphen [] ls
numSpaces = fromIntegral (length $ filter itemIsSpace nls)
spaceSize = realToFrac $ (textW - sum (fmap itemWidth' nls)) / numSpaces
nls' = map (\x -> case x of
(Spring _ a b) -> Spring spaceSize a b
_ -> x) nls
mapM_ ((`JQ.appendJQuery` lineDiv) <=< toJQueryWithWidth) nls'
return lineDiv
where
toJQueryWithWidth i = assignCssWidth (itemWidth' i) =<< itemElement i
dehyphen :: Word -> [Word] -> [Word]
dehyphen n [] = [n]
dehyphen n@(Box{}) p =
let sp = space 0
in case head p of
Box{} -> n : sp : p
Penalty{} -> case tail p of
(Box{}:_) -> n : tail p
_ -> n : p
dehyphen n@(Penalty{}) p = n : p
dehyphen _ p = p
reverseLine :: JQ.JQuery -> IO JQ.JQuery
reverseLine = JQ.setCss "-moz-transform" "scaleX(-1)" <=<
JQ.setCss "-o-transform" "scaleX(-1)" <=<
JQ.setCss "-webkit-transform" "scaleX(-1)" <=<
JQ.setCss "transform" "scaleX(-1)" <=<
JQ.setCss "filter" "FlipH" <=<
JQ.setCss "-ms-filter" "\"FlipH\""
hyphenString :: String
hyphenString = "-"
nonBreakingHypenString :: Char
nonBreakingHypenString = '‑'
emdash :: Char
emdash = '—'
preprocess :: String -> [String]
preprocess = prepareText
where
insertHyphens x
| nonBreakingHypenString `elem` x = [x]
| otherwise = intersperse hyphenString $ hyphenate english_US x
insertPilcrows = concatMap (\x -> if x == '\n' then " ¶ " else [x])
prepareText = concatMap insertHyphens . words . replace . insertPilcrows
replace = map (\x -> if x == '-' || x == emdash then nonBreakingHypenString else x)
processedWords :: [String]
processedWords = preprocess contextText
| null | https://raw.githubusercontent.com/aupiff/boustro/9ed0d3c9f5f8f66680810e0fb2d249cd71b7a65b/frontend/src/Typography.hs | haskell | # LANGUAGE OverloadedStrings #
bring this back in case of issues
where hyphenWidth = case last l of
(Penalty w _ _ _) -> w
_ -> 0
penalize placing hyphen at end of line
what number should I use here?
I just need to see what wastes look like generally
too close is worse than too far apart : TODO This seems backwards to me
spaces larger than optimal width
spaces smaller than optimal width
Write quickcheck properties for this
TODO what is this 1/n about? space width? change this
Should I be applying this style every time? Definitely on window change
dim, so maybe it's not so bad.
creating a temporary div specifically to measure the width of every element
can this be a monoid?
Box w_i
Penalty w_i p_i f_i
a row
TODO I may not end up using this | # LANGUAGE ExistentialQuantification #
module Typography
( measureLineHeight
, PageEvent(..)
, ViewDimensions(..)
, processedWords
, typesetPage
) where
import Control.Monad
import Data.JSString.Text
import Data.List (intersperse)
import Data.Maybe
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified JavaScript.JQuery as JQ hiding (filter, not)
import Prelude hiding (Word)
import Text.Hyphenation
import Server
import Debug.Trace
data PageEvent = NextPage | PrevPage | Resize | Start deriving (Show, Eq)
data ViewDimensions = ViewDimensions { fullWidth :: Int
, viewWidth :: Double
, viewHeight :: Double
, lineHeight :: Double
}
type Word = Item T.Text Double
type Txt = [Word]
type Line = [Word]
type Paragraph = [Line]
fold1 :: forall a b. (a -> b -> b) -> (a -> b) -> [a] -> Maybe b
fold1 _ _ [] = Nothing
fold1 _ g [x] = Just $ g x
fold1 f g (x:xs) = f x <$> fold1 f g xs
minWith :: forall a b. Ord b => (a -> b) -> [a] -> Maybe a
minWith f = fold1 choice id
where choice a b
| f a < f b = a
| otherwise = b
width :: Line -> Double
width l = sum (map itemWidth l)
lineWaste :: Double -> Line -> Double
lineWaste textWidth l = numSpaces * weighting (spaceSize / numSpaces - spaceWidth) + hyphenPenalty + hyphenHeadPenalty
where spaceSize = textWidth - width l
numSpaces :: Double
numSpaces = fromIntegral . length $ filter itemIsBox l
disallow hyphens first
hyphenHeadPenalty = if itemIsPenalty (head l) then 1000000 else 0
par1' :: Double -> Txt -> Paragraph
par1' textWidth = parLines . fromMaybe (trace "par1 minWith" ([], 0, 0)) . minWith waste
. fromMaybe (trace "par1' fold1" []) . fold1 step start
where
step :: Word -> [(Paragraph, Double, Double)] -> [(Paragraph, Double, Double)]
step w ps = let origin = (new w (fromMaybe (error $ "par1' step" ++ show ps) $ minWith waste ps) : map (glue w) ps)
result = filter fitH origin
in if null result then traceShow origin [fromMaybe (head origin) (minWith waste origin)] else result
start :: Word -> [(Paragraph, Double, Double)]
start w = [([[w]], itemWidth w, 0.0)]
new w ([l], _, 0) = ([w]:[l], itemWidth w, 0.0)
new w p@(ls, _, _) = ([w]:ls, itemWidth w, waste p)
glue w (l:ls, n, m) = ((w:l):ls, itemWidth w + n, m)
parLines (ls, _, _) = ls
widthHead (_, n, _) = n
wasteTail (_, _, m) = m
linwHead = lineWaste textWidth . head . parLines
waste ([_], _, _) = 0
waste p = linwHead p + wasteTail p
fitH p = widthHead p <= textWidth
typesetPage :: (ViewDimensions, ((Int, Int), PageEvent)) -> IO (Int, Int)
typesetPage ((ViewDimensions _ textWidth viewHeight lineH), ((0, wordsOnPage), PrevPage)) = return (0, wordsOnPage)
typesetPage ((ViewDimensions _ textWidth viewHeight lineH), ((wordNumber, wordsOnPage), pageEvent))
| pageEvent == NextPage && length processedWords == wordNumber + wordsOnPage = return (wordNumber, wordsOnPage)
| otherwise = do
3 is margin - bottom TODO remove this magic number
lineSpacing = (textHeight - fromIntegral linesPerPage * lineH) / (fromIntegral linesPerPage - 1)
numWords = round $ 30 * (textWidth / 700) * fromIntegral linesPerPage
textHeight = viewHeight * 0.9
wordNumber' <- case pageEvent of
NextPage -> return $ wordNumber + wordsOnPage
Start -> return 0
Resize -> return wordNumber
PrevPage -> do let boxify = wordsWithWidths . take numWords . reverse
boxesMeasure <- boxify $ take wordNumber processedWords
let parMeasure = take linesPerPage $ par1' textWidth boxesMeasure
wordsOnPageMeasure = sum $ map length parMeasure
return $ max 0 $ wordNumber - wordsOnPageMeasure
boxes <- wordsWithWidths . take numWords . drop wordNumber' $ processedWords
let par = take linesPerPage $ par1' textWidth boxes
wordsOnPage' = sum $ map length par
ls <- mapM (renderLine lineH textWidth lineSpacing) par
boustroLines <- boustro ls
textArea <- (JQ.empty >=> widthCss) =<< JQ.select "#boustro"
mapM_ (`JQ.appendJQuery` textArea) boustroLines
return (wordNumber', wordsOnPage')
where widthCss = JQ.setCss "width" (textToJSString . T.pack $ show textWidth)
wordsWithWidths :: [String] -> IO [Word]
wordsWithWidths inputWords = do
scratchArea <- JQ.empty =<< JQ.select "#scratch-area"
mapM (\x -> do let t = T.pack x
jq <- toItem t
_ <- jq `JQ.appendJQuery` scratchArea
jqWidth <- JQ.getInnerWidth jq
return $ toItem' t jqWidth
) inputWords
where toItem' :: T.Text -> Double -> Word
toItem' "-" w = hyphen w "-"
toItem' " " _ = space spaceWidth
toItem' str w = Box w str
boustro :: [JQ.JQuery] -> IO [JQ.JQuery]
boustro [] = return []
boustro [l] = return [l]
boustro (l:l2:ls) = do ho <- reverseLine l2
fi <- boustro ls
return (l : ho : fi)
measureLineHeight :: IO Double
measureLineHeight = do
scratchArea <- JQ.empty =<< JQ.select "#scratch-area"
quux <- JQ.select ("<span>" <> textToJSString "Hail qQuuXX!" <> "</span>")
_ <- quux `JQ.appendJQuery` scratchArea
JQ.getInnerHeight quux
Spring w_i y_i z_i
instance Show b => Show (Item a b) where
show (Box w _) = "Box " ++ show w
show (Spring w _ _) = "Spring " ++ show w
show (Penalty w _ _ _) = "Penalty " ++ show w
all hypens are flagged penality items because we do n't want two hyphens in
itemWidth :: Num b => Item a b -> b
itemWidth (Box w _) = w
itemWidth (Spring w _ _) = w
itemWidth ( Penalty w _ _ _ ) = w
itemWidth Penalty{} = 0
itemWidth' :: Num b => Item a b -> b
itemWidth' (Box w _) = w
itemWidth' (Spring w _ _) = w
itemWidth' (Penalty w _ _ _) = w
toItem :: T.Text -> IO JQ.JQuery
toItem "-" = JQ.select "<span>-</span>"
toItem " " = assignCssWidth spaceWidth =<< JQ.select "<span> </span>"
toItem str = JQ.select ("<span>" <> textToJSString str <> "</span>")
itemElement :: Word -> IO JQ.JQuery
itemElement (Box _ e) = JQ.select ("<span>" <> textToJSString e <> "</span>")
itemElement Spring{} = JQ.select "<span> </span>"
itemElement Penalty{} = JQ.select "<span>-</span>"
itemIsSpace :: forall t s . Item t s -> Bool
itemIsSpace Spring{} = True
itemIsSpace _ = False
itemIsBox :: forall t s . Item t s -> Bool
itemIsBox Box{} = True
itemIsBox _ = False
itemIsPenalty :: forall t s . Item t s -> Bool
itemIsPenalty Penalty{} = True
itemIsPenalty _ = False
spaceWidth :: Double
spaceWidth = 6
space :: Double -> Word
space w = Spring w 3 2
TODO rename this
assignCssWidth :: Double -> JQ.JQuery -> IO JQ.JQuery
assignCssWidth txtWidth =
JQ.setCss "display" "inline-block"
<=< JQ.setCss "width" (textToJSString . T.pack $ show txtWidth)
hyphen :: Double -> T.Text -> Word
hyphen hyphenWidth = Penalty hyphenWidth penaltyValue False
renderLine :: Double -> Double -> Double -> [Word] -> IO JQ.JQuery
renderLine lineH textW lineSpacing ls = do
lineDiv <- JQ.select "<div class='line'></div>"
>>= JQ.setCss "width" (textToJSString . T.pack $ show textW)
>>= JQ.setCss "height" (textToJSString . T.pack $ show lineH)
>>= JQ.setCss "white-space" "nowrap"
>>= JQ.setCss "margin-bottom" ((textToJSString . T.pack . show $ lineSpacing) <> "px")
let nls = foldr dehyphen [] ls
numSpaces = fromIntegral (length $ filter itemIsSpace nls)
spaceSize = realToFrac $ (textW - sum (fmap itemWidth' nls)) / numSpaces
nls' = map (\x -> case x of
(Spring _ a b) -> Spring spaceSize a b
_ -> x) nls
mapM_ ((`JQ.appendJQuery` lineDiv) <=< toJQueryWithWidth) nls'
return lineDiv
where
toJQueryWithWidth i = assignCssWidth (itemWidth' i) =<< itemElement i
dehyphen :: Word -> [Word] -> [Word]
dehyphen n [] = [n]
dehyphen n@(Box{}) p =
let sp = space 0
in case head p of
Box{} -> n : sp : p
Penalty{} -> case tail p of
(Box{}:_) -> n : tail p
_ -> n : p
dehyphen n@(Penalty{}) p = n : p
dehyphen _ p = p
reverseLine :: JQ.JQuery -> IO JQ.JQuery
reverseLine = JQ.setCss "-moz-transform" "scaleX(-1)" <=<
JQ.setCss "-o-transform" "scaleX(-1)" <=<
JQ.setCss "-webkit-transform" "scaleX(-1)" <=<
JQ.setCss "transform" "scaleX(-1)" <=<
JQ.setCss "filter" "FlipH" <=<
JQ.setCss "-ms-filter" "\"FlipH\""
hyphenString :: String
hyphenString = "-"
nonBreakingHypenString :: Char
nonBreakingHypenString = '‑'
emdash :: Char
emdash = '—'
preprocess :: String -> [String]
preprocess = prepareText
where
insertHyphens x
| nonBreakingHypenString `elem` x = [x]
| otherwise = intersperse hyphenString $ hyphenate english_US x
insertPilcrows = concatMap (\x -> if x == '\n' then " ¶ " else [x])
prepareText = concatMap insertHyphens . words . replace . insertPilcrows
replace = map (\x -> if x == '-' || x == emdash then nonBreakingHypenString else x)
processedWords :: [String]
processedWords = preprocess contextText
|
ceaef499ba104eb38c670f620308202944706c5ab7bc2789c7391f05b38f3bd0 | jwiegley/notes | Rcf.hs | | Return e ( Euler 's constant )
foreign import ccall "Z3_rcf_mk_e" c'Z3_rcf_mk_e
:: C'Z3_context -> IO C'Z3_rcf_num
foreign import ccall "&Z3_rcf_mk_e" p'Z3_rcf_mk_e
:: FunPtr (C'Z3_context -> IO C'Z3_rcf_num)
# LINE 25 " Z3 / Base / C / Rcf.hsc " #
| Return a new infinitesimal that is smaller than all elements in the Z3 field .
foreign import ccall "Z3_rcf_mk_infinitesimal" c'Z3_rcf_mk_infinitesimal
:: C'Z3_context -> IO C'Z3_rcf_num
foreign import ccall "&Z3_rcf_mk_infinitesimal" p'Z3_rcf_mk_infinitesimal
:: FunPtr (C'Z3_context -> IO C'Z3_rcf_num)
# LINE 28 " Z3 / Base / C / Rcf.hsc " #
| Store in roots the roots of the polynomial
The output vector roots must have size \c n.
It returns the number of roots of the polynomial .
\pre The input polynomial is not the zero polynomial .
The output vector \c roots must have size \c n.
It returns the number of roots of the polynomial.
\pre The input polynomial is not the zero polynomial. -}
foreign import ccall "Z3_rcf_mk_roots" c'Z3_rcf_mk_roots
:: C'Z3_context -> CUInt -> Ptr C'Z3_rcf_num -> Ptr C'Z3_rcf_num -> IO ()
foreign import ccall "&Z3_rcf_mk_roots" p'Z3_rcf_mk_roots
:: FunPtr (C'Z3_context -> CUInt -> Ptr C'Z3_rcf_num -> Ptr C'Z3_rcf_num -> IO ())
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/ffb7de3739ffedee21af401d7c8e2181/Rcf.hs | haskell | | Return e ( Euler 's constant )
foreign import ccall "Z3_rcf_mk_e" c'Z3_rcf_mk_e
:: C'Z3_context -> IO C'Z3_rcf_num
foreign import ccall "&Z3_rcf_mk_e" p'Z3_rcf_mk_e
:: FunPtr (C'Z3_context -> IO C'Z3_rcf_num)
# LINE 25 " Z3 / Base / C / Rcf.hsc " #
| Return a new infinitesimal that is smaller than all elements in the Z3 field .
foreign import ccall "Z3_rcf_mk_infinitesimal" c'Z3_rcf_mk_infinitesimal
:: C'Z3_context -> IO C'Z3_rcf_num
foreign import ccall "&Z3_rcf_mk_infinitesimal" p'Z3_rcf_mk_infinitesimal
:: FunPtr (C'Z3_context -> IO C'Z3_rcf_num)
# LINE 28 " Z3 / Base / C / Rcf.hsc " #
| Store in roots the roots of the polynomial
The output vector roots must have size \c n.
It returns the number of roots of the polynomial .
\pre The input polynomial is not the zero polynomial .
The output vector \c roots must have size \c n.
It returns the number of roots of the polynomial.
\pre The input polynomial is not the zero polynomial. -}
foreign import ccall "Z3_rcf_mk_roots" c'Z3_rcf_mk_roots
:: C'Z3_context -> CUInt -> Ptr C'Z3_rcf_num -> Ptr C'Z3_rcf_num -> IO ()
foreign import ccall "&Z3_rcf_mk_roots" p'Z3_rcf_mk_roots
:: FunPtr (C'Z3_context -> CUInt -> Ptr C'Z3_rcf_num -> Ptr C'Z3_rcf_num -> IO ())
|
|
0a5258af4936cf2f6d422ab029c1c7bad5c9fc347513354b3d37cb1bba435556 | pepe/two-in-shadows | events.cljs | (ns two-in-shadows.client.events
(:require [potok.core :as ptk]
[beicon.core :as rx]
[goog.json :as json]
[com.rpl.specter :as S]
[rxhttp.browser :as http]))
(defrecord FadeLoading []
ptk/UpdateEvent
(update [_ state] (S/setval :ui/loading :fade state)))
(defrecord HideLoading []
ptk/UpdateEvent
(update [_ state] (S/setval :ui/loading S/NONE state)))
(def fading
(rx/concat
(rx/delay 250 (rx/just (->FadeLoading)))
(rx/delay 750 (rx/just (->HideLoading)))))
(defrecord ShowLoading []
ptk/UpdateEvent
(update [_ state] (S/setval :ui/loading true state)))
(defrecord SaveGreeting [response]
ptk/UpdateEvent
(update [_ state]
(let [{body :body} response
greeting (js->clj (json/parse body) :keywordize-keys true)]
(S/setval :ui/greeting greeting state)))
ptk/WatchEvent
(watch [_ state _] fading))
(defrecord GetGreeting []
ptk/WatchEvent
(watch [_ state _]
(rx/concat
(rx/just (->ShowLoading))
(rx/map ->SaveGreeting
(http/send! {:method :get
:url (str (:api/url state) "greeting")
:headers {:content-type "application/json"}})))))
(defn get-greeting
"Gets the greeting from server"
[store]
(ptk/emit! store (->GetGreeting)))
;; >>>>>>>
(defonce store
(ptk/store {:state {:api/url ":8270/"}}))
| null | https://raw.githubusercontent.com/pepe/two-in-shadows/b49a484cf1cc1a9a2e0a5ffb358acfe0f56d895c/src/two_in_shadows/client/events.cljs | clojure | >>>>>>> | (ns two-in-shadows.client.events
(:require [potok.core :as ptk]
[beicon.core :as rx]
[goog.json :as json]
[com.rpl.specter :as S]
[rxhttp.browser :as http]))
(defrecord FadeLoading []
ptk/UpdateEvent
(update [_ state] (S/setval :ui/loading :fade state)))
(defrecord HideLoading []
ptk/UpdateEvent
(update [_ state] (S/setval :ui/loading S/NONE state)))
(def fading
(rx/concat
(rx/delay 250 (rx/just (->FadeLoading)))
(rx/delay 750 (rx/just (->HideLoading)))))
(defrecord ShowLoading []
ptk/UpdateEvent
(update [_ state] (S/setval :ui/loading true state)))
(defrecord SaveGreeting [response]
ptk/UpdateEvent
(update [_ state]
(let [{body :body} response
greeting (js->clj (json/parse body) :keywordize-keys true)]
(S/setval :ui/greeting greeting state)))
ptk/WatchEvent
(watch [_ state _] fading))
(defrecord GetGreeting []
ptk/WatchEvent
(watch [_ state _]
(rx/concat
(rx/just (->ShowLoading))
(rx/map ->SaveGreeting
(http/send! {:method :get
:url (str (:api/url state) "greeting")
:headers {:content-type "application/json"}})))))
(defn get-greeting
"Gets the greeting from server"
[store]
(ptk/emit! store (->GetGreeting)))
(defonce store
(ptk/store {:state {:api/url ":8270/"}}))
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.