_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 |
|---|---|---|---|---|---|---|---|---|
695972242f952910cb03f5b68aeaa80a1ee416e8c1b03836bf802393103ac56d | racket/typed-racket | module-plus.rkt | #lang typed/racket/base/shallow
;; Make sure defender runs in module+
(module u racket/base
(define b
(box "hello"))
(provide b))
(require/typed 'u (b (Boxof Integer)))
(module+ test
(require typed/rackunit)
(check-exn exn:fail:contract?
(lambda () (unbox b))))
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/shallow/module-plus.rkt | racket | Make sure defender runs in module+ | #lang typed/racket/base/shallow
(module u racket/base
(define b
(box "hello"))
(provide b))
(require/typed 'u (b (Boxof Integer)))
(module+ test
(require typed/rackunit)
(check-exn exn:fail:contract?
(lambda () (unbox b))))
|
abc60ba5a9b8532d46f196f40ac588887337d846105c72e4053fb83fb80ed933 | nvim-treesitter/nvim-treesitter | highlights.scm | (user) @namespace
(auth) @symbol
(gecos) @string
(home) @text.uri @constant
(shell) @text.uri @string.special
[
(gid)
(uid)
] @number
(separator) @punctuation.delimiter
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/3fe80dbecdf1fa88cf81a4d7b30ab0714f8c443a/queries/passwd/highlights.scm | scheme | (user) @namespace
(auth) @symbol
(gecos) @string
(home) @text.uri @constant
(shell) @text.uri @string.special
[
(gid)
(uid)
] @number
(separator) @punctuation.delimiter
| |
91201485dcdb777bc7fcbf739bf2b724f4cbe2792b0935aad57f21448f1e8794 | gergoerdi/clash-shake | F4PGA.hs | # LANGUAGE OverloadedStrings , RecordWildCards , TemplateHaskell #
module Clash.Shake.F4PGA
( xilinx7
, openFPGALoader
) where
import Clash.Shake
import qualified Clash.Shake.Xilinx as Xilinx
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import Development.Shake.Config
xilinx7 :: Xilinx.Board -> SynthRules
xilinx7 Xilinx.Board{ boardTarget = {..} } kit@ClashKit{..} outDir topName extraGenerated = do
let rootDir = joinPath . map (const "..") . splitPath $ outDir
let symbiflow' :: String -> [String] -> Action ()
symbiflow' tool args = cmd_ (EchoStdout False) (Cwd outDir) =<< toolchain "F4PGA" tool args
symbiflow :: String -> [String] -> Action ()
symbiflow tool args = cmd_ (EchoStdout False) =<< toolchain "F4PGA" tool args
outDir </> topName <.> "eblif" %> \out -> do
extraFiles <- findFiles <$> extraGenerated
srcs <- manifestSrcs
let verilogs = extraFiles ["//*.v"]
xdcs = extraFiles ["//*.xdc"]
need $ srcs <> verilogs <> xdcs
symbiflow' "symbiflow_synth" $
[ "-d", targetFamily
, "-p", Xilinx.targetPart target
, "-t", topName
] ++
[ "-v " <> rootDir </> src | src <- srcs <> verilogs ] ++
[ "-x " <> rootDir </> xdc | xdc <- xdcs ]
outDir <//> "*.net" %> \out -> do
let eblif = out -<.> "eblif"
need [eblif]
symbiflow' "symbiflow_pack" $
[ "-d", targetDevice <> "_test"
, "-e", takeFileName eblif
]
outDir <//> "*.place" %> \out -> do
let eblif = out -<.> "eblif"
net = out -<.> "net"
need [eblif, net]
symbiflow' "symbiflow_place" $
[ "-d", targetDevice <> "_test"
, "-P", Xilinx.targetPart target
, "-e", takeFileName eblif
, "-n", takeFileName net
]
outDir <//> "*.route" %> \out -> do
let eblif = out -<.> "eblif"
place = out -<.> "place"
need [eblif, place]
symbiflow' "symbiflow_route" $
[ "-d", targetDevice <> "_test"
, "-e", takeFileName eblif
]
outDir <//> "*.fasm" %> \out -> do
let eblif = out -<.> "eblif"
route = out -<.> "route"
need [eblif, route]
symbiflow' "symbiflow_write_fasm" $
[ "-d", targetDevice <> "_test"
, "-e", takeFileName eblif
]
outDir <//> "*.bit" %> \out -> do
let fasm = out -<.> "fasm"
need [fasm]
symbiflow "symbiflow_write_bitstream" $
[ "-d", targetFamily
, "-p", Xilinx.targetPart target
, "-f", fasm
, "-b", out
]
let bitfile = outDir </> topName <.> "bit"
return SynthKit
{ bitfile = bitfile
, phonies =
[ "upload" |> openFPGALoader ["-c", "digilent"] bitfile
]
}
openFPGALoader :: [String] -> FilePath -> Action ()
openFPGALoader args bitfile = do
need [bitfile]
cmd_ =<< toolchain "OPENFPGALOADER" "openFPGALoader" (args ++ [bitfile])
| null | https://raw.githubusercontent.com/gergoerdi/clash-shake/e7729b0c8bf1cdbe98dd9f204b3881f843b82490/src/Clash/Shake/F4PGA.hs | haskell | # LANGUAGE OverloadedStrings , RecordWildCards , TemplateHaskell #
module Clash.Shake.F4PGA
( xilinx7
, openFPGALoader
) where
import Clash.Shake
import qualified Clash.Shake.Xilinx as Xilinx
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import Development.Shake.Config
xilinx7 :: Xilinx.Board -> SynthRules
xilinx7 Xilinx.Board{ boardTarget = {..} } kit@ClashKit{..} outDir topName extraGenerated = do
let rootDir = joinPath . map (const "..") . splitPath $ outDir
let symbiflow' :: String -> [String] -> Action ()
symbiflow' tool args = cmd_ (EchoStdout False) (Cwd outDir) =<< toolchain "F4PGA" tool args
symbiflow :: String -> [String] -> Action ()
symbiflow tool args = cmd_ (EchoStdout False) =<< toolchain "F4PGA" tool args
outDir </> topName <.> "eblif" %> \out -> do
extraFiles <- findFiles <$> extraGenerated
srcs <- manifestSrcs
let verilogs = extraFiles ["//*.v"]
xdcs = extraFiles ["//*.xdc"]
need $ srcs <> verilogs <> xdcs
symbiflow' "symbiflow_synth" $
[ "-d", targetFamily
, "-p", Xilinx.targetPart target
, "-t", topName
] ++
[ "-v " <> rootDir </> src | src <- srcs <> verilogs ] ++
[ "-x " <> rootDir </> xdc | xdc <- xdcs ]
outDir <//> "*.net" %> \out -> do
let eblif = out -<.> "eblif"
need [eblif]
symbiflow' "symbiflow_pack" $
[ "-d", targetDevice <> "_test"
, "-e", takeFileName eblif
]
outDir <//> "*.place" %> \out -> do
let eblif = out -<.> "eblif"
net = out -<.> "net"
need [eblif, net]
symbiflow' "symbiflow_place" $
[ "-d", targetDevice <> "_test"
, "-P", Xilinx.targetPart target
, "-e", takeFileName eblif
, "-n", takeFileName net
]
outDir <//> "*.route" %> \out -> do
let eblif = out -<.> "eblif"
place = out -<.> "place"
need [eblif, place]
symbiflow' "symbiflow_route" $
[ "-d", targetDevice <> "_test"
, "-e", takeFileName eblif
]
outDir <//> "*.fasm" %> \out -> do
let eblif = out -<.> "eblif"
route = out -<.> "route"
need [eblif, route]
symbiflow' "symbiflow_write_fasm" $
[ "-d", targetDevice <> "_test"
, "-e", takeFileName eblif
]
outDir <//> "*.bit" %> \out -> do
let fasm = out -<.> "fasm"
need [fasm]
symbiflow "symbiflow_write_bitstream" $
[ "-d", targetFamily
, "-p", Xilinx.targetPart target
, "-f", fasm
, "-b", out
]
let bitfile = outDir </> topName <.> "bit"
return SynthKit
{ bitfile = bitfile
, phonies =
[ "upload" |> openFPGALoader ["-c", "digilent"] bitfile
]
}
openFPGALoader :: [String] -> FilePath -> Action ()
openFPGALoader args bitfile = do
need [bitfile]
cmd_ =<< toolchain "OPENFPGALOADER" "openFPGALoader" (args ++ [bitfile])
| |
7c916847401a1106a3ab466244b53752cd33ae12232cd06b06d2a8e7d4916c81 | hakaru-dev/hakaru | SubstBug.hs | {-# LANGUAGE TypeOperators
, DataKinds
#-}
module Tests.SubstBug where
import Data.Text (pack)
import Language.Hakaru.Syntax.ABT
import Language.Hakaru.Syntax.AST
import Language.Hakaru.Syntax.Prelude (pair)
import Language.Hakaru.Types.Sing
import Language.Hakaru.Types.DataKind
z :: Variable 'HInt
z = Variable (pack "z") 3 SInt
y :: Variable 'HReal
y = Variable (pack "y") 2 SReal
x :: Variable 'HReal
x = Variable (pack "x") 1 SReal
w :: Variable 'HInt
w = Variable (pack "w") 0 SInt
f0 :: TrivialABT Term '[] ('HReal ':-> HPair 'HReal 'HInt)
f0 = syn (Lam_ :$ bind x (pair (var y) (var w)) :* End)
-- Works
f1 :: TrivialABT Term '[] ('HReal ':-> HPair 'HReal 'HInt)
f1 = subst y (var x) f0
-- Crashes
f2 :: TrivialABT Term '[] ('HReal ':-> HPair 'HReal 'HInt)
f2 = subst w (var z) f1
-- Crashes
f3 :: TrivialABT Term '[] ('HReal ':-> HPair 'HReal 'HInt)
f3 = subst z (var w) f1
| What 's going on here ?
Consider an expression :
f0 = \ ( x::real ) - > ( ( y::real ) , ( w::int ) )
We want to substitute ( x::real ) for ( y::real ) in f0 .
Calling ( subst y x f0 ) will :
1 . Check ( y::real ) ( x::real ) , which is false .
2 . Check using varEq if ( x::real ) occurs in the set { x::real , y::real , w::int } .
This returns true , so a new variable ( z::real ) is generated .
The variable z is only guaranteed to be different from x , y , and . Return the expression :
f1 = \ ( z::real ) - > ( ( x::real ) , ( w::int ) )
Now we want to substitute ( z::int ) for ( w::int ) in f1 .
This is legal -- we could have had a variable ( z::int ) from a long time ago ,
and we are simply calling subst with it now .
Calling ( subst w z f1 ) will :
1 . Check ( w::int ) ( z::real ) , which is false .
2 . Check using varEq if ( z::int ) occurs in { z::real , x::real , w::int } .
This returns a VarEqTypeError while comparing ( z::int ) with ( z::real ) .
Ok that did n't work , whatever . Now we want to substitute ( w::int ) for ( z::int ) in f1 .
Calling ( subst z w f1 ) will :
1 . Check ( z::int ) ( z::real ) , which returns a VarEqTypeError .
Consider an expression:
f0 = \ (x::real) -> ( (y::real) , (w::int) )
We want to substitute (x::real) for (y::real) in f0.
Calling (subst y x f0) will:
1. Check varEq (y::real) (x::real), which is false.
2. Check using varEq if (x::real) occurs in the set {x::real, y::real, w::int}.
This returns true, so a new variable (z::real) is generated.
The variable z is only guaranteed to be different from x, y, and w.
3. Return the expression:
f1 = \ (z::real) -> ( (x::real) , (w::int) )
Now we want to substitute (z::int) for (w::int) in f1.
This is legal -- we could have had a variable (z::int) from a long time ago,
and we are simply calling subst with it now.
Calling (subst w z f1) will:
1. Check varEq (w::int) (z::real), which is false.
2. Check using varEq if (z::int) occurs in {z::real, x::real, w::int}.
This returns a VarEqTypeError while comparing (z::int) with (z::real).
Ok that didn't work, whatever. Now we want to substitute (w::int) for (z::int) in f1.
Calling (subst z w f1) will:
1. Check varEq (z::int) (z::real), which returns a VarEqTypeError.
-}
| null | https://raw.githubusercontent.com/hakaru-dev/hakaru/94157c89ea136c3b654a85cce51f19351245a490/haskell/Tests/SubstBug.hs | haskell | # LANGUAGE TypeOperators
, DataKinds
#
Works
Crashes
Crashes
we could have had a variable ( z::int ) from a long time ago ,
we could have had a variable (z::int) from a long time ago, |
module Tests.SubstBug where
import Data.Text (pack)
import Language.Hakaru.Syntax.ABT
import Language.Hakaru.Syntax.AST
import Language.Hakaru.Syntax.Prelude (pair)
import Language.Hakaru.Types.Sing
import Language.Hakaru.Types.DataKind
z :: Variable 'HInt
z = Variable (pack "z") 3 SInt
y :: Variable 'HReal
y = Variable (pack "y") 2 SReal
x :: Variable 'HReal
x = Variable (pack "x") 1 SReal
w :: Variable 'HInt
w = Variable (pack "w") 0 SInt
f0 :: TrivialABT Term '[] ('HReal ':-> HPair 'HReal 'HInt)
f0 = syn (Lam_ :$ bind x (pair (var y) (var w)) :* End)
f1 :: TrivialABT Term '[] ('HReal ':-> HPair 'HReal 'HInt)
f1 = subst y (var x) f0
f2 :: TrivialABT Term '[] ('HReal ':-> HPair 'HReal 'HInt)
f2 = subst w (var z) f1
f3 :: TrivialABT Term '[] ('HReal ':-> HPair 'HReal 'HInt)
f3 = subst z (var w) f1
| What 's going on here ?
Consider an expression :
f0 = \ ( x::real ) - > ( ( y::real ) , ( w::int ) )
We want to substitute ( x::real ) for ( y::real ) in f0 .
Calling ( subst y x f0 ) will :
1 . Check ( y::real ) ( x::real ) , which is false .
2 . Check using varEq if ( x::real ) occurs in the set { x::real , y::real , w::int } .
This returns true , so a new variable ( z::real ) is generated .
The variable z is only guaranteed to be different from x , y , and . Return the expression :
f1 = \ ( z::real ) - > ( ( x::real ) , ( w::int ) )
Now we want to substitute ( z::int ) for ( w::int ) in f1 .
and we are simply calling subst with it now .
Calling ( subst w z f1 ) will :
1 . Check ( w::int ) ( z::real ) , which is false .
2 . Check using varEq if ( z::int ) occurs in { z::real , x::real , w::int } .
This returns a VarEqTypeError while comparing ( z::int ) with ( z::real ) .
Ok that did n't work , whatever . Now we want to substitute ( w::int ) for ( z::int ) in f1 .
Calling ( subst z w f1 ) will :
1 . Check ( z::int ) ( z::real ) , which returns a VarEqTypeError .
Consider an expression:
f0 = \ (x::real) -> ( (y::real) , (w::int) )
We want to substitute (x::real) for (y::real) in f0.
Calling (subst y x f0) will:
1. Check varEq (y::real) (x::real), which is false.
2. Check using varEq if (x::real) occurs in the set {x::real, y::real, w::int}.
This returns true, so a new variable (z::real) is generated.
The variable z is only guaranteed to be different from x, y, and w.
3. Return the expression:
f1 = \ (z::real) -> ( (x::real) , (w::int) )
Now we want to substitute (z::int) for (w::int) in f1.
and we are simply calling subst with it now.
Calling (subst w z f1) will:
1. Check varEq (w::int) (z::real), which is false.
2. Check using varEq if (z::int) occurs in {z::real, x::real, w::int}.
This returns a VarEqTypeError while comparing (z::int) with (z::real).
Ok that didn't work, whatever. Now we want to substitute (w::int) for (z::int) in f1.
Calling (subst z w f1) will:
1. Check varEq (z::int) (z::real), which returns a VarEqTypeError.
-}
|
c6f8869fb783716ad1925233c2ef83951dfe9eb75345f618b087d26c5083e43f | turbopape/postagga | trainer_test.cljc | Copyright ( c ) 2017 < >
;;Distributed under the MIT License
(ns postagga.trainer-test
(:require [clojure.test :refer :all]
[clojure.data :refer [diff]]
[postagga.trainer :refer :all]))
(deftest process-annotated-sentence-test
(testing "process-annotated-sentence")
(is (= {:states #{}, :transitions {}, :emissions {}, :init-state nil} (process-annotated-sentence nil)))
(is (= {:states #{}, :transitions {}, :emissions {}, :init-state nil} (process-annotated-sentence [])))
(is (= {:states #{"P"}, :transitions {}, :emissions {["P" "Je"] 1}, :init-state "P"} (process-annotated-sentence [["Je" "P"]])))
(is (= {:states #{"P" "V"}, :transitions {["P" "V"] 1}, :emissions {["P" "Je"] 1 ["V" "Mange"] 1}, :init-state "P"} (process-annotated-sentence [["Je" "P"] ["Mange" "V"]])))
(is (= {:states #{"P" "V" "A"}, :transitions {["P" "V"] 1 ["V" "A"] 1}, :emissions {["P" "Je"] 1 ["V" "Mange"] 1 ["A" "Une"] 1}, :init-state "P"} (process-annotated-sentence [["Je" "P"] ["Mange" "V"] ["Une" "A"]])))
(is (= {:states #{"P"}, :transitions {["P" "P"] 1}, :emissions {["P" "Je"] 2}, :init-state "P"} (process-annotated-sentence [["Je" "P"] ["Je" "P"]])))
(is (= {:states #{"V" "N"}, :transitions {["V" "N"] 1}, :emissions {["V" "Montre"] 1 ["N" "Montre"] 1}, :init-state "V"} (process-annotated-sentence [["Montre" "V"] ["Montre" "N"]])))
(is (= {:states #{"P" "V" "N"}, :transitions {["P" "P"] 1 ["P" "V"] 1 ["V" "P"] 1 ["P" "N"] 1}, :emissions {["P" "Je"] 1 ["P" "Te"] 1 ["V" "Montre"] 1 ["P" "Ma"] 1 ["N" "Montre"] 1}, :init-state "P"} (process-annotated-sentence [["Je" "P"] ["Te" "P"] ["Montre" "V"] ["Ma" "P"] ["Montre" "N"]]))))
(deftest compute-matrix-row-probs-test
(testing "compute-matrix-row-probs")
(is (= {} (compute-matrix-row-probs nil nil)))
(is (= {} (compute-matrix-row-probs #{} nil)))
(is (= {} (compute-matrix-row-probs #{} {})))
(is (= {} (compute-matrix-row-probs nil {})))
(is (= {} (compute-matrix-row-probs #{"P"} {})))
(is (= {} (compute-matrix-row-probs #{} {["P" "P"] 2})))
(is (= {["P" "P"] 1.0} (compute-matrix-row-probs #{"P"} {["P" "P"] 2})))
(is (= {["P" "P"] 0.5 ["P" "V"] 0.5 ["V" "P"] 0.25 ["V" "V"] 0.75} (compute-matrix-row-probs #{"P" "V"} {["P" "P"] 1 ["P" "V"] 1 ["V" "P"] 1 ["V" "V"] 3}))))
(deftest train-test
(testing "train")
(is (= {:states #{} :transitions {} :emissions {} :init-probs {}} (train nil)))
(is (= {:states #{} :transitions {} :emissions {} :init-probs {}} (train [])))
(is (= {:states #{} :transitions {} :emissions {} :init-probs {}} (train [[]])))
(is (= {:states #{} :transitions {} :emissions {} :init-probs {}} (train [[[]]])))
(is (= {:states #{"P"} :transitions {} :emissions {["P" "Je"] 1.0} :init-probs {"P" 1.0}} (train [[["Je" "P"]]])))
(is (= {:states #{"P" "V"} :transitions {["P" "V"] 1.0} :emissions {["P" "Je"] 1.0 ["V" "Suis"] 1.0} :init-probs {"P" 1.0}} (train [[["Je" "P"]["Suis" "V"]]])))
(is (= {:states #{"P" "V" "A" "N"} :transitions {["P" "V"] 1.0 ["V" "A"] 1.0 ["A" "N"] 1.0} :emissions {["P" "Je"] 1.0 ["V" "Suis"] 1.0 ["A" "Une"] 1.0 ["N" "Mouche"] 1.0} :init-probs {"P" 1.0}} (train [[["Je" "P"]["Suis" "V"]["Une" "A"]["Mouche" "N"]]])))
(is (= {:states #{"P" "V" "A" "N"} :transitions {["P" "V"] 1.0 ["V" "A"] 1.0 ["A" "N"] 1.0} :emissions {["P" "Je"] 0.5 ["P" "Tu"] 0.5 ["V" "Suis"] 0.5 ["V" "Mange"] 0.5 ["A" "Une"] 0.5 ["A" "La"] 0.5 ["N" "Mouche"] 0.5 ["N" "Pomme"] 0.5} :init-probs {"P" 1.0}} (train [[["Je" "P"]["Suis" "V"]["Une" "A"]["Mouche" "N"]][["Tu" "P"]["Mange" "V"]["La" "A"]["Pomme" "N"]]]))))
| null | https://raw.githubusercontent.com/turbopape/postagga/a17a20942024be00800a15de7aeb7c0277023660/test/postagga/trainer_test.cljc | clojure | Distributed under the MIT License | Copyright ( c ) 2017 < >
(ns postagga.trainer-test
(:require [clojure.test :refer :all]
[clojure.data :refer [diff]]
[postagga.trainer :refer :all]))
(deftest process-annotated-sentence-test
(testing "process-annotated-sentence")
(is (= {:states #{}, :transitions {}, :emissions {}, :init-state nil} (process-annotated-sentence nil)))
(is (= {:states #{}, :transitions {}, :emissions {}, :init-state nil} (process-annotated-sentence [])))
(is (= {:states #{"P"}, :transitions {}, :emissions {["P" "Je"] 1}, :init-state "P"} (process-annotated-sentence [["Je" "P"]])))
(is (= {:states #{"P" "V"}, :transitions {["P" "V"] 1}, :emissions {["P" "Je"] 1 ["V" "Mange"] 1}, :init-state "P"} (process-annotated-sentence [["Je" "P"] ["Mange" "V"]])))
(is (= {:states #{"P" "V" "A"}, :transitions {["P" "V"] 1 ["V" "A"] 1}, :emissions {["P" "Je"] 1 ["V" "Mange"] 1 ["A" "Une"] 1}, :init-state "P"} (process-annotated-sentence [["Je" "P"] ["Mange" "V"] ["Une" "A"]])))
(is (= {:states #{"P"}, :transitions {["P" "P"] 1}, :emissions {["P" "Je"] 2}, :init-state "P"} (process-annotated-sentence [["Je" "P"] ["Je" "P"]])))
(is (= {:states #{"V" "N"}, :transitions {["V" "N"] 1}, :emissions {["V" "Montre"] 1 ["N" "Montre"] 1}, :init-state "V"} (process-annotated-sentence [["Montre" "V"] ["Montre" "N"]])))
(is (= {:states #{"P" "V" "N"}, :transitions {["P" "P"] 1 ["P" "V"] 1 ["V" "P"] 1 ["P" "N"] 1}, :emissions {["P" "Je"] 1 ["P" "Te"] 1 ["V" "Montre"] 1 ["P" "Ma"] 1 ["N" "Montre"] 1}, :init-state "P"} (process-annotated-sentence [["Je" "P"] ["Te" "P"] ["Montre" "V"] ["Ma" "P"] ["Montre" "N"]]))))
(deftest compute-matrix-row-probs-test
(testing "compute-matrix-row-probs")
(is (= {} (compute-matrix-row-probs nil nil)))
(is (= {} (compute-matrix-row-probs #{} nil)))
(is (= {} (compute-matrix-row-probs #{} {})))
(is (= {} (compute-matrix-row-probs nil {})))
(is (= {} (compute-matrix-row-probs #{"P"} {})))
(is (= {} (compute-matrix-row-probs #{} {["P" "P"] 2})))
(is (= {["P" "P"] 1.0} (compute-matrix-row-probs #{"P"} {["P" "P"] 2})))
(is (= {["P" "P"] 0.5 ["P" "V"] 0.5 ["V" "P"] 0.25 ["V" "V"] 0.75} (compute-matrix-row-probs #{"P" "V"} {["P" "P"] 1 ["P" "V"] 1 ["V" "P"] 1 ["V" "V"] 3}))))
(deftest train-test
(testing "train")
(is (= {:states #{} :transitions {} :emissions {} :init-probs {}} (train nil)))
(is (= {:states #{} :transitions {} :emissions {} :init-probs {}} (train [])))
(is (= {:states #{} :transitions {} :emissions {} :init-probs {}} (train [[]])))
(is (= {:states #{} :transitions {} :emissions {} :init-probs {}} (train [[[]]])))
(is (= {:states #{"P"} :transitions {} :emissions {["P" "Je"] 1.0} :init-probs {"P" 1.0}} (train [[["Je" "P"]]])))
(is (= {:states #{"P" "V"} :transitions {["P" "V"] 1.0} :emissions {["P" "Je"] 1.0 ["V" "Suis"] 1.0} :init-probs {"P" 1.0}} (train [[["Je" "P"]["Suis" "V"]]])))
(is (= {:states #{"P" "V" "A" "N"} :transitions {["P" "V"] 1.0 ["V" "A"] 1.0 ["A" "N"] 1.0} :emissions {["P" "Je"] 1.0 ["V" "Suis"] 1.0 ["A" "Une"] 1.0 ["N" "Mouche"] 1.0} :init-probs {"P" 1.0}} (train [[["Je" "P"]["Suis" "V"]["Une" "A"]["Mouche" "N"]]])))
(is (= {:states #{"P" "V" "A" "N"} :transitions {["P" "V"] 1.0 ["V" "A"] 1.0 ["A" "N"] 1.0} :emissions {["P" "Je"] 0.5 ["P" "Tu"] 0.5 ["V" "Suis"] 0.5 ["V" "Mange"] 0.5 ["A" "Une"] 0.5 ["A" "La"] 0.5 ["N" "Mouche"] 0.5 ["N" "Pomme"] 0.5} :init-probs {"P" 1.0}} (train [[["Je" "P"]["Suis" "V"]["Une" "A"]["Mouche" "N"]][["Tu" "P"]["Mange" "V"]["La" "A"]["Pomme" "N"]]]))))
|
2d3f245570fc1ac0b1c07120b229a67c25c8f9195483418d7d701f416214dfc1 | 8thlight/hyperion | connection_spec.clj | (ns hyperion.sql.connection-spec
(:require [speclj.core :refer :all]
[hyperion.sql :refer :all]
[hyperion.sql.connection :refer :all]))
(clojure.lang.RT/loadClassForName "org.sqlite.JDBC")
(describe "Connection Management"
(with connection-url "jdbc:sqlite::memory:")
(with connection-url-file "jdbc:sqlite:hyperion_clojure.sqlite")
(it "binds a connection"
(let [was-closed (atom false)]
(with-connection @connection-url
(reset! was-closed (.isClosed (connection))))
(should-not @was-closed)))
(it "uses the same connection when bound"
(let [first-connection (atom nil)
second-connection (atom nil)]
(with-connection @connection-url
(reset! first-connection (connection))
(with-connection @connection-url
(reset! second-connection (connection))))
(should= @first-connection @second-connection)))
(it "returns the result"
(should= 1 (with-connection @connection-url 1)))
(it "connects to multiple urls"
(let [first-valid (atom false)
second-valid (atom false)]
(with-connection @connection-url
(reset! first-valid (not (.isClosed (connection)))))
(with-connection @connection-url-file
(reset! second-valid (not (.isClosed (connection)))))
(should @first-valid)
(should @second-valid)))
)
| null | https://raw.githubusercontent.com/8thlight/hyperion/b1b8f60a5ef013da854e98319220b97920727865/sql/spec/hyperion/sql/connection_spec.clj | clojure | (ns hyperion.sql.connection-spec
(:require [speclj.core :refer :all]
[hyperion.sql :refer :all]
[hyperion.sql.connection :refer :all]))
(clojure.lang.RT/loadClassForName "org.sqlite.JDBC")
(describe "Connection Management"
(with connection-url "jdbc:sqlite::memory:")
(with connection-url-file "jdbc:sqlite:hyperion_clojure.sqlite")
(it "binds a connection"
(let [was-closed (atom false)]
(with-connection @connection-url
(reset! was-closed (.isClosed (connection))))
(should-not @was-closed)))
(it "uses the same connection when bound"
(let [first-connection (atom nil)
second-connection (atom nil)]
(with-connection @connection-url
(reset! first-connection (connection))
(with-connection @connection-url
(reset! second-connection (connection))))
(should= @first-connection @second-connection)))
(it "returns the result"
(should= 1 (with-connection @connection-url 1)))
(it "connects to multiple urls"
(let [first-valid (atom false)
second-valid (atom false)]
(with-connection @connection-url
(reset! first-valid (not (.isClosed (connection)))))
(with-connection @connection-url-file
(reset! second-valid (not (.isClosed (connection)))))
(should @first-valid)
(should @second-valid)))
)
| |
286d8263e5c30e6bd7d6c829e50405bd818f319d85bf3bda325789d6b6ea88d2 | nuprl/gradual-typing-performance | reader.rkt | #lang s-exp htdp/bsl/reader
lang/htdp-beginner
'()
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/htdp-lib/htdp/bsl/lang/reader.rkt | racket | #lang s-exp htdp/bsl/reader
lang/htdp-beginner
'()
| |
89382e929adea36404191cd2ffb261e2c8bc7c49ddfeda815adb6ca346d1157a | kostmo/circleci-failure-tracker | GitRev.hs | {-# LANGUAGE OverloadedStrings #-}
-- | This module is intentionally small so that
-- it can export a "smart constructor" to validate
SHA1s
module GitRev (GitSha1, validateSha1, sha1) where
import Control.Monad (when)
import Data.Char (isHexDigit)
import Data.Text (Text)
import qualified Data.Text as T
newtype GitSha1 = NewGitSha1 {
sha1 :: Text
} deriving Show
validateSha1 :: Text -> Either Text GitSha1
validateSha1 sha1_text = do
when (sha1_length /= 40) $
Left $ "Improper sha1 length of " <> T.pack (show sha1_length)
case maybe_non_hex_char of
Nothing -> Right $ NewGitSha1 lowercase_sha1
Just nonhex_char -> Left $ "Invalid hexadecimal digit: \"" <> T.singleton nonhex_char <> "\""
where
lowercase_sha1 = T.toLower sha1_text
sha1_length = T.length sha1_text
maybe_non_hex_char = T.find (not . isHexDigit) sha1_text
| null | https://raw.githubusercontent.com/kostmo/circleci-failure-tracker/393d10a72080bd527fdb159da6ebfea23fcd52d1/app/fetcher/src/GitRev.hs | haskell | # LANGUAGE OverloadedStrings #
| This module is intentionally small so that
it can export a "smart constructor" to validate |
SHA1s
module GitRev (GitSha1, validateSha1, sha1) where
import Control.Monad (when)
import Data.Char (isHexDigit)
import Data.Text (Text)
import qualified Data.Text as T
newtype GitSha1 = NewGitSha1 {
sha1 :: Text
} deriving Show
validateSha1 :: Text -> Either Text GitSha1
validateSha1 sha1_text = do
when (sha1_length /= 40) $
Left $ "Improper sha1 length of " <> T.pack (show sha1_length)
case maybe_non_hex_char of
Nothing -> Right $ NewGitSha1 lowercase_sha1
Just nonhex_char -> Left $ "Invalid hexadecimal digit: \"" <> T.singleton nonhex_char <> "\""
where
lowercase_sha1 = T.toLower sha1_text
sha1_length = T.length sha1_text
maybe_non_hex_char = T.find (not . isHexDigit) sha1_text
|
6d632ea3cc2ed7f7efd774add575731719f8448649f87e1c2c2a65c3b5be511f | google/ormolu | TypeFamily.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
-- | Rendering of data\/type families.
module Ormolu.Printer.Meat.Declaration.TypeFamily
( p_famDecl,
p_tyFamInstEqn,
)
where
import Control.Monad
import Data.Maybe (isNothing)
import GHC
import Ormolu.Printer.Combinators
import Ormolu.Printer.Meat.Common
import Ormolu.Printer.Meat.Type
import Ormolu.Utils
p_famDecl :: FamilyStyle -> FamilyDecl GhcPs -> R ()
p_famDecl style FamilyDecl {fdTyVars = HsQTvs {..}, ..} = do
mmeqs <- case fdInfo of
DataFamily -> Nothing <$ txt "data"
OpenTypeFamily -> Nothing <$ txt "type"
ClosedTypeFamily eqs -> Just eqs <$ txt "type"
txt $ case style of
Associated -> mempty
Free -> " family"
breakpoint
inci $ do
switchLayout (getLoc fdLName : (getLoc <$> hsq_explicit)) $
p_infixDefHelper
(isInfix fdFixity)
True
(p_rdrName fdLName)
(located' p_hsTyVarBndr <$> hsq_explicit)
let resultSig = p_familyResultSigL fdResultSig
unless (isNothing resultSig && isNothing fdInjectivityAnn) space
inci $ do
sequence_ resultSig
space
forM_ fdInjectivityAnn (located' p_injectivityAnn)
case mmeqs of
Nothing -> return ()
Just meqs -> do
inci $ do
breakpoint
txt "where"
case meqs of
Nothing -> do
space
txt ".."
Just eqs -> do
newline
sep newline (located' (inci . p_tyFamInstEqn)) eqs
p_famDecl _ FamilyDecl {fdTyVars = XLHsQTyVars {}} =
notImplemented "XLHsQTyVars"
p_famDecl _ (XFamilyDecl x) = noExtCon x
p_familyResultSigL ::
Located (FamilyResultSig GhcPs) ->
Maybe (R ())
p_familyResultSigL l =
case l of
L _ a -> case a of
NoSig NoExtField -> Nothing
KindSig NoExtField k -> Just $ do
breakpoint
txt "::"
space
located k p_hsType
TyVarSig NoExtField bndr -> Just $ do
equals
breakpoint
located bndr p_hsTyVarBndr
XFamilyResultSig x ->
noExtCon x
p_injectivityAnn :: InjectivityAnn GhcPs -> R ()
p_injectivityAnn (InjectivityAnn a bs) = do
txt "|"
space
p_rdrName a
space
txt "->"
space
sep space p_rdrName bs
p_tyFamInstEqn :: TyFamInstEqn GhcPs -> R ()
p_tyFamInstEqn HsIB {hsib_body = FamEqn {..}} = do
case feqn_bndrs of
Nothing -> return ()
Just bndrs -> do
p_forallBndrs ForallInvis p_hsTyVarBndr bndrs
breakpoint
inciIf (not $ null feqn_bndrs) $ do
let famLhsSpn = getLoc feqn_tycon : fmap (getLoc . typeArgToType) feqn_pats
switchLayout famLhsSpn $
p_infixDefHelper
(isInfix feqn_fixity)
True
(p_rdrName feqn_tycon)
(located' p_hsType . typeArgToType <$> feqn_pats)
space
equals
breakpoint
inci (located feqn_rhs p_hsType)
p_tyFamInstEqn HsIB {hsib_body = XFamEqn x} = noExtCon x
p_tyFamInstEqn (XHsImplicitBndrs x) = noExtCon x
----------------------------------------------------------------------------
-- Helpers
isInfix :: LexicalFixity -> Bool
isInfix = \case
Infix -> True
Prefix -> False
| null | https://raw.githubusercontent.com/google/ormolu/ffdf145bbdf917d54a3ef4951fc2655e35847ff0/src/Ormolu/Printer/Meat/Declaration/TypeFamily.hs | haskell | # LANGUAGE OverloadedStrings #
| Rendering of data\/type families.
--------------------------------------------------------------------------
Helpers | # LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
module Ormolu.Printer.Meat.Declaration.TypeFamily
( p_famDecl,
p_tyFamInstEqn,
)
where
import Control.Monad
import Data.Maybe (isNothing)
import GHC
import Ormolu.Printer.Combinators
import Ormolu.Printer.Meat.Common
import Ormolu.Printer.Meat.Type
import Ormolu.Utils
p_famDecl :: FamilyStyle -> FamilyDecl GhcPs -> R ()
p_famDecl style FamilyDecl {fdTyVars = HsQTvs {..}, ..} = do
mmeqs <- case fdInfo of
DataFamily -> Nothing <$ txt "data"
OpenTypeFamily -> Nothing <$ txt "type"
ClosedTypeFamily eqs -> Just eqs <$ txt "type"
txt $ case style of
Associated -> mempty
Free -> " family"
breakpoint
inci $ do
switchLayout (getLoc fdLName : (getLoc <$> hsq_explicit)) $
p_infixDefHelper
(isInfix fdFixity)
True
(p_rdrName fdLName)
(located' p_hsTyVarBndr <$> hsq_explicit)
let resultSig = p_familyResultSigL fdResultSig
unless (isNothing resultSig && isNothing fdInjectivityAnn) space
inci $ do
sequence_ resultSig
space
forM_ fdInjectivityAnn (located' p_injectivityAnn)
case mmeqs of
Nothing -> return ()
Just meqs -> do
inci $ do
breakpoint
txt "where"
case meqs of
Nothing -> do
space
txt ".."
Just eqs -> do
newline
sep newline (located' (inci . p_tyFamInstEqn)) eqs
p_famDecl _ FamilyDecl {fdTyVars = XLHsQTyVars {}} =
notImplemented "XLHsQTyVars"
p_famDecl _ (XFamilyDecl x) = noExtCon x
p_familyResultSigL ::
Located (FamilyResultSig GhcPs) ->
Maybe (R ())
p_familyResultSigL l =
case l of
L _ a -> case a of
NoSig NoExtField -> Nothing
KindSig NoExtField k -> Just $ do
breakpoint
txt "::"
space
located k p_hsType
TyVarSig NoExtField bndr -> Just $ do
equals
breakpoint
located bndr p_hsTyVarBndr
XFamilyResultSig x ->
noExtCon x
p_injectivityAnn :: InjectivityAnn GhcPs -> R ()
p_injectivityAnn (InjectivityAnn a bs) = do
txt "|"
space
p_rdrName a
space
txt "->"
space
sep space p_rdrName bs
p_tyFamInstEqn :: TyFamInstEqn GhcPs -> R ()
p_tyFamInstEqn HsIB {hsib_body = FamEqn {..}} = do
case feqn_bndrs of
Nothing -> return ()
Just bndrs -> do
p_forallBndrs ForallInvis p_hsTyVarBndr bndrs
breakpoint
inciIf (not $ null feqn_bndrs) $ do
let famLhsSpn = getLoc feqn_tycon : fmap (getLoc . typeArgToType) feqn_pats
switchLayout famLhsSpn $
p_infixDefHelper
(isInfix feqn_fixity)
True
(p_rdrName feqn_tycon)
(located' p_hsType . typeArgToType <$> feqn_pats)
space
equals
breakpoint
inci (located feqn_rhs p_hsType)
p_tyFamInstEqn HsIB {hsib_body = XFamEqn x} = noExtCon x
p_tyFamInstEqn (XHsImplicitBndrs x) = noExtCon x
isInfix :: LexicalFixity -> Bool
isInfix = \case
Infix -> True
Prefix -> False
|
adb53f2a166c3b6743c895d14dd16ac11288e9a8f258c05a907d2b864be8410c | alt-romes/ghengin | Device.hs | # LANGUAGE OverloadedLists #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE OverloadedRecordDot #
# LANGUAGE DataKinds #
# LANGUAGE RecordWildCards #
# LANGUAGE LambdaCase #
module Ghengin.Vulkan.Device where
import Data.Ord
import Data.Bits
import Data.Maybe
import Data.Word
import Data.ByteString (ByteString)
import Data.Vector (Vector)
import qualified Data.Vector as V
import qualified Data.List as L
import qualified Data.Set as S
import qualified Vulkan.CStruct.Extends as VkC
import qualified Vulkan as Vk
-- We create a logical device always with a graphics queue and a present queue
type GraphicsQueueFamily = Word32
type PresentQueueFamily = Word32
-- | Device rating function.
The return value is maybe a tuple with three items : the rating associated with the device ( higher is better ) , the graphics queue family and the present queue family
type DeviceRateFunction = (Vk.PhysicalDevice -> IO (Maybe (Int, GraphicsQueueFamily, PresentQueueFamily)))
data VulkanDevice = VulkanDevice { _physicalDevice :: Vk.PhysicalDevice
, _device :: Vk.Device
, _graphicsQueue :: Vk.Queue
, _presentQueue :: Vk.Queue
, _graphicsQueueFamily :: GraphicsQueueFamily
, _presentQueueFamily :: PresentQueueFamily
}
createVulkanDevice :: Vk.Instance
-> Vector ByteString -- ^ Validation Layers
-> Vector ByteString -- ^ Device Extensions
-> DeviceRateFunction
-> IO VulkanDevice
createVulkanDevice inst validationLayers deviceExtensions rateFn = do
(physicalDevice, graphicsQF, presentQF) <- pickPhysicalDevice inst rateFn
let
deviceCreateInfo = Vk.DeviceCreateInfo { next = ()
, flags = Vk.DeviceCreateFlags 0
, queueCreateInfos = (V.fromList . map (VkC.SomeStruct . deviceQueueCreateInfo) . S.toList) [graphicsQF, presentQF]
, enabledLayerNames = validationLayers
, enabledExtensionNames = deviceExtensions
, enabledFeatures = Nothing
}
deviceQueueCreateInfo ix = Vk.DeviceQueueCreateInfo { next = ()
, flags = Vk.DeviceQueueCreateFlagBits 0
, queueFamilyIndex = ix
-- For now all queues have same priority (there should only be one queue anyway?)
, queuePriorities = [1]
}
device <- Vk.createDevice physicalDevice deviceCreateInfo Nothing
graphicsQueue <- Vk.getDeviceQueue device graphicsQF 0
presentQueue <- Vk.getDeviceQueue device presentQF 0
pure $ VulkanDevice physicalDevice device graphicsQueue presentQueue graphicsQF presentQF
destroyVulkanDevice :: VulkanDevice -> IO ()
destroyVulkanDevice d = Vk.destroyDevice d._device Nothing
pickPhysicalDevice :: Vk.Instance
-> DeviceRateFunction
-> IO (Vk.PhysicalDevice, GraphicsQueueFamily, PresentQueueFamily)
pickPhysicalDevice inst rateFn = do
(_, dvs) <- Vk.enumeratePhysicalDevices inst
case dvs of
[] -> fail "Failed to find GPUs with Vulkan support!"
_ ->
L.sortOn (Down . fst) . V.toList . V.filter (isJust . fst) . (`V.zip` dvs) <$> traverse rateFn dvs >>= \case
(Just (_,graphicsQF,presentQF),device):_ -> pure (device, graphicsQF, presentQF)
(Nothing,_):_ -> fail "Impossible! Failed to find a suitable GPU!"
[] -> fail "Failed to find a suitable GPU!"
findMemoryType :: Word32 -> Vk.MemoryPropertyFlags -> Vk.PhysicalDevice -> IO Word32
findMemoryType typeFilter properties physicalDevice = do
memProperties <- Vk.getPhysicalDeviceMemoryProperties physicalDevice
pure $ V.head $ V.imapMaybe (\i t -> if ((typeFilter .&. (1 `unsafeShiftL` i)) /= 0) && ((t.propertyFlags .&. properties) == properties)
then pure (fromIntegral i) else Nothing) memProperties.memoryTypes
| null | https://raw.githubusercontent.com/alt-romes/ghengin/986ccc8b9ba3d597dcca4392fc88ff50ee7f1ce1/src/Ghengin/Vulkan/Device.hs | haskell | # LANGUAGE OverloadedStrings #
We create a logical device always with a graphics queue and a present queue
| Device rating function.
^ Validation Layers
^ Device Extensions
For now all queues have same priority (there should only be one queue anyway?) | # LANGUAGE OverloadedLists #
# LANGUAGE OverloadedRecordDot #
# LANGUAGE DataKinds #
# LANGUAGE RecordWildCards #
# LANGUAGE LambdaCase #
module Ghengin.Vulkan.Device where
import Data.Ord
import Data.Bits
import Data.Maybe
import Data.Word
import Data.ByteString (ByteString)
import Data.Vector (Vector)
import qualified Data.Vector as V
import qualified Data.List as L
import qualified Data.Set as S
import qualified Vulkan.CStruct.Extends as VkC
import qualified Vulkan as Vk
type GraphicsQueueFamily = Word32
type PresentQueueFamily = Word32
The return value is maybe a tuple with three items : the rating associated with the device ( higher is better ) , the graphics queue family and the present queue family
type DeviceRateFunction = (Vk.PhysicalDevice -> IO (Maybe (Int, GraphicsQueueFamily, PresentQueueFamily)))
data VulkanDevice = VulkanDevice { _physicalDevice :: Vk.PhysicalDevice
, _device :: Vk.Device
, _graphicsQueue :: Vk.Queue
, _presentQueue :: Vk.Queue
, _graphicsQueueFamily :: GraphicsQueueFamily
, _presentQueueFamily :: PresentQueueFamily
}
createVulkanDevice :: Vk.Instance
-> DeviceRateFunction
-> IO VulkanDevice
createVulkanDevice inst validationLayers deviceExtensions rateFn = do
(physicalDevice, graphicsQF, presentQF) <- pickPhysicalDevice inst rateFn
let
deviceCreateInfo = Vk.DeviceCreateInfo { next = ()
, flags = Vk.DeviceCreateFlags 0
, queueCreateInfos = (V.fromList . map (VkC.SomeStruct . deviceQueueCreateInfo) . S.toList) [graphicsQF, presentQF]
, enabledLayerNames = validationLayers
, enabledExtensionNames = deviceExtensions
, enabledFeatures = Nothing
}
deviceQueueCreateInfo ix = Vk.DeviceQueueCreateInfo { next = ()
, flags = Vk.DeviceQueueCreateFlagBits 0
, queueFamilyIndex = ix
, queuePriorities = [1]
}
device <- Vk.createDevice physicalDevice deviceCreateInfo Nothing
graphicsQueue <- Vk.getDeviceQueue device graphicsQF 0
presentQueue <- Vk.getDeviceQueue device presentQF 0
pure $ VulkanDevice physicalDevice device graphicsQueue presentQueue graphicsQF presentQF
destroyVulkanDevice :: VulkanDevice -> IO ()
destroyVulkanDevice d = Vk.destroyDevice d._device Nothing
pickPhysicalDevice :: Vk.Instance
-> DeviceRateFunction
-> IO (Vk.PhysicalDevice, GraphicsQueueFamily, PresentQueueFamily)
pickPhysicalDevice inst rateFn = do
(_, dvs) <- Vk.enumeratePhysicalDevices inst
case dvs of
[] -> fail "Failed to find GPUs with Vulkan support!"
_ ->
L.sortOn (Down . fst) . V.toList . V.filter (isJust . fst) . (`V.zip` dvs) <$> traverse rateFn dvs >>= \case
(Just (_,graphicsQF,presentQF),device):_ -> pure (device, graphicsQF, presentQF)
(Nothing,_):_ -> fail "Impossible! Failed to find a suitable GPU!"
[] -> fail "Failed to find a suitable GPU!"
findMemoryType :: Word32 -> Vk.MemoryPropertyFlags -> Vk.PhysicalDevice -> IO Word32
findMemoryType typeFilter properties physicalDevice = do
memProperties <- Vk.getPhysicalDeviceMemoryProperties physicalDevice
pure $ V.head $ V.imapMaybe (\i t -> if ((typeFilter .&. (1 `unsafeShiftL` i)) /= 0) && ((t.propertyFlags .&. properties) == properties)
then pure (fromIntegral i) else Nothing) memProperties.memoryTypes
|
5f9c7afb53708af03b82239b0272f717793a77f46fb2af4c68023b0599e2b88a | weavejester/codox | main.clj | (ns codox.main
"Main namespace for generating documentation"
(:use [codox.utils :only (add-source-paths)])
(:require [clojure.string :as str]
[clojure.java.shell :as shell]
[codox.reader.clojure :as clj]
[codox.reader.plaintext :as text]))
(defn- writer [{:keys [writer]}]
(let [writer-sym (or writer 'codox.writer.html/write-docs)
writer-ns (symbol (namespace writer-sym))]
(try
(require writer-ns)
(catch Exception e
(throw
(Exception. (str "Could not load codox writer " writer-ns) e))))
(if-let [writer (resolve writer-sym)]
writer
(throw
(Exception. (str "Could not resolve codox writer " writer-sym))))))
(defn- macro? [var]
(= (:type var) :macro))
(defn- read-macro-namespaces [paths read-opts]
(->> (clj/read-namespaces paths read-opts)
(map (fn [ns] (update-in ns [:publics] #(filter macro? %))))
(remove (comp empty? :publics))))
(defn- merge-namespaces [namespaces]
(for [[name namespaces] (group-by :name namespaces)]
(assoc (first namespaces) :publics (mapcat :publics namespaces))))
(defn- cljs-read-namespaces [paths read-opts]
require is here to allow Clojure 1.3 and 1.4 when not using ClojureScript
(require 'codox.reader.clojurescript)
(let [reader (find-var 'codox.reader.clojurescript/read-namespaces)]
(merge-namespaces
(concat (reader paths read-opts)
(read-macro-namespaces paths read-opts)))))
(def ^:private namespace-readers
{:clojure clj/read-namespaces
:clojurescript cljs-read-namespaces})
(defn- var-symbol [namespace var]
(symbol (name (:name namespace)) (name (:name var))))
(defn- remove-matching-vars [vars re namespace]
(remove (fn [var]
(when (and re (re-find re (name (:name var))))
(println "Excluding var" (var-symbol namespace var))
true))
vars))
(defn- remove-excluded-vars [namespaces exclude-vars]
(map #(update-in % [:publics] remove-matching-vars exclude-vars %) namespaces))
(defn- add-var-defaults [vars defaults]
(for [var vars]
(-> (merge defaults var)
(update-in [:members] add-var-defaults defaults))))
(defn- add-ns-defaults [namespaces defaults]
(for [namespace namespaces]
(-> (merge defaults namespace)
(update-in [:publics] add-var-defaults defaults))))
(defn- ns-matches? [{ns-name :name} pattern]
(cond
(instance? java.util.regex.Pattern pattern) (re-find pattern (str ns-name))
(string? pattern) (= pattern (str ns-name))
(symbol? pattern) (= pattern (symbol ns-name))))
(defn- filter-namespaces [namespaces ns-filters]
(if (and ns-filters (not= ns-filters :all))
(filter #(some (partial ns-matches? %) ns-filters) namespaces)
namespaces))
(defn- read-namespaces
[{:keys [language root-path source-paths namespaces metadata exclude-vars] :as opts}]
(let [reader (namespace-readers language)]
(-> (reader source-paths (select-keys opts [:exception-handler]))
(filter-namespaces namespaces)
(remove-excluded-vars exclude-vars)
(add-source-paths root-path source-paths)
(add-ns-defaults metadata))))
(defn- read-documents [{:keys [doc-paths doc-files] :or {doc-files :all}}]
(cond
(not= doc-files :all) (map text/read-file doc-files)
(seq doc-paths) (->> doc-paths
(apply text/read-documents)
(sort-by :name))))
(defn- git-commit [dir]
(let [{:keys [out exit] :as result} (shell/sh "git" "rev-parse" "HEAD" :dir dir)]
(when-not (zero? exit)
(throw (ex-info "Error getting git commit" result)))
(str/trim out)))
(def defaults
(let [root-path (System/getProperty "user.dir")]
{:language :clojure
:root-path root-path
:output-path "target/doc"
:source-paths ["src"]
:doc-paths ["doc"]
:doc-files :all
:namespaces :all
:exclude-vars #"^(map)?->\p{Upper}"
:metadata {}
:themes [:default]
:git-commit (delay (git-commit root-path))}))
(defn generate-docs
"Generate documentation from source files."
([]
(generate-docs {}))
([options]
(let [options (merge defaults options)
write-fn (writer options)
namespaces (read-namespaces options)
documents (read-documents options)]
(write-fn (assoc options
:namespaces namespaces
:documents documents)))))
| null | https://raw.githubusercontent.com/weavejester/codox/bc41c2bbc270f52bceba095e57be30de80b892e0/codox/src/codox/main.clj | clojure | (ns codox.main
"Main namespace for generating documentation"
(:use [codox.utils :only (add-source-paths)])
(:require [clojure.string :as str]
[clojure.java.shell :as shell]
[codox.reader.clojure :as clj]
[codox.reader.plaintext :as text]))
(defn- writer [{:keys [writer]}]
(let [writer-sym (or writer 'codox.writer.html/write-docs)
writer-ns (symbol (namespace writer-sym))]
(try
(require writer-ns)
(catch Exception e
(throw
(Exception. (str "Could not load codox writer " writer-ns) e))))
(if-let [writer (resolve writer-sym)]
writer
(throw
(Exception. (str "Could not resolve codox writer " writer-sym))))))
(defn- macro? [var]
(= (:type var) :macro))
(defn- read-macro-namespaces [paths read-opts]
(->> (clj/read-namespaces paths read-opts)
(map (fn [ns] (update-in ns [:publics] #(filter macro? %))))
(remove (comp empty? :publics))))
(defn- merge-namespaces [namespaces]
(for [[name namespaces] (group-by :name namespaces)]
(assoc (first namespaces) :publics (mapcat :publics namespaces))))
(defn- cljs-read-namespaces [paths read-opts]
require is here to allow Clojure 1.3 and 1.4 when not using ClojureScript
(require 'codox.reader.clojurescript)
(let [reader (find-var 'codox.reader.clojurescript/read-namespaces)]
(merge-namespaces
(concat (reader paths read-opts)
(read-macro-namespaces paths read-opts)))))
(def ^:private namespace-readers
{:clojure clj/read-namespaces
:clojurescript cljs-read-namespaces})
(defn- var-symbol [namespace var]
(symbol (name (:name namespace)) (name (:name var))))
(defn- remove-matching-vars [vars re namespace]
(remove (fn [var]
(when (and re (re-find re (name (:name var))))
(println "Excluding var" (var-symbol namespace var))
true))
vars))
(defn- remove-excluded-vars [namespaces exclude-vars]
(map #(update-in % [:publics] remove-matching-vars exclude-vars %) namespaces))
(defn- add-var-defaults [vars defaults]
(for [var vars]
(-> (merge defaults var)
(update-in [:members] add-var-defaults defaults))))
(defn- add-ns-defaults [namespaces defaults]
(for [namespace namespaces]
(-> (merge defaults namespace)
(update-in [:publics] add-var-defaults defaults))))
(defn- ns-matches? [{ns-name :name} pattern]
(cond
(instance? java.util.regex.Pattern pattern) (re-find pattern (str ns-name))
(string? pattern) (= pattern (str ns-name))
(symbol? pattern) (= pattern (symbol ns-name))))
(defn- filter-namespaces [namespaces ns-filters]
(if (and ns-filters (not= ns-filters :all))
(filter #(some (partial ns-matches? %) ns-filters) namespaces)
namespaces))
(defn- read-namespaces
[{:keys [language root-path source-paths namespaces metadata exclude-vars] :as opts}]
(let [reader (namespace-readers language)]
(-> (reader source-paths (select-keys opts [:exception-handler]))
(filter-namespaces namespaces)
(remove-excluded-vars exclude-vars)
(add-source-paths root-path source-paths)
(add-ns-defaults metadata))))
(defn- read-documents [{:keys [doc-paths doc-files] :or {doc-files :all}}]
(cond
(not= doc-files :all) (map text/read-file doc-files)
(seq doc-paths) (->> doc-paths
(apply text/read-documents)
(sort-by :name))))
(defn- git-commit [dir]
(let [{:keys [out exit] :as result} (shell/sh "git" "rev-parse" "HEAD" :dir dir)]
(when-not (zero? exit)
(throw (ex-info "Error getting git commit" result)))
(str/trim out)))
(def defaults
(let [root-path (System/getProperty "user.dir")]
{:language :clojure
:root-path root-path
:output-path "target/doc"
:source-paths ["src"]
:doc-paths ["doc"]
:doc-files :all
:namespaces :all
:exclude-vars #"^(map)?->\p{Upper}"
:metadata {}
:themes [:default]
:git-commit (delay (git-commit root-path))}))
(defn generate-docs
"Generate documentation from source files."
([]
(generate-docs {}))
([options]
(let [options (merge defaults options)
write-fn (writer options)
namespaces (read-namespaces options)
documents (read-documents options)]
(write-fn (assoc options
:namespaces namespaces
:documents documents)))))
| |
46e2b86c1b4822ee54954cc12e0e0d34babe0b6619807e0f0a6c6d48c418502a | racket/slideshow | code-pict.rkt | #lang racket/base
(require pict/code)
(provide (all-from-out pict/code))
| null | https://raw.githubusercontent.com/racket/slideshow/4588507e83e9aa859c6841e655b98417d46987e6/slideshow-lib/slideshow/code-pict.rkt | racket | #lang racket/base
(require pict/code)
(provide (all-from-out pict/code))
| |
fbebf7d22cb39ec14dc3970f5b988016a2bf5122235a5e7964358bdd92a9fd56 | Clojure2D/clojure2d-examples | color.clj | (ns rt4.color
(:require [clojure2d.color :as c]
[fastmath.vector :as v]
[fastmath.core :as m])
(:import [fastmath.vector Vec3 Vec4]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defn ->color
"Convert to clojure2d color, optionally divide by a given constant"
(^Vec4 [^double r ^double g ^double b] (->color (Vec3. r g b)))
([in] (-> in
(v/sqrt) ;; linear to gamma
(c/scale-up)))
([^double r ^double g ^double b ^long samples-per-pixel] (->color (Vec3. r g b) samples-per-pixel))
([in ^long samples-per-pixel] (-> in
(v/div samples-per-pixel)
(v/sqrt) ;; linear-to-gamma
(c/scale-up))))
(defn <-color
"Convert clojure2d color to a vec3"
^Vec3 [c]
(let [^Vec4 c (c/scale-down c)]
(Vec3. (.x c) (.y c) (.z c))))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/639db92fa509bd206726faf95607e8fb073e9f5e/src/rt4/color.clj | clojure | linear to gamma
linear-to-gamma | (ns rt4.color
(:require [clojure2d.color :as c]
[fastmath.vector :as v]
[fastmath.core :as m])
(:import [fastmath.vector Vec3 Vec4]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defn ->color
"Convert to clojure2d color, optionally divide by a given constant"
(^Vec4 [^double r ^double g ^double b] (->color (Vec3. r g b)))
([in] (-> in
(c/scale-up)))
([^double r ^double g ^double b ^long samples-per-pixel] (->color (Vec3. r g b) samples-per-pixel))
([in ^long samples-per-pixel] (-> in
(v/div samples-per-pixel)
(c/scale-up))))
(defn <-color
"Convert clojure2d color to a vec3"
^Vec3 [c]
(let [^Vec4 c (c/scale-down c)]
(Vec3. (.x c) (.y c) (.z c))))
|
299c1674f2d61e7cbcb3034bec6066ee493edf00eddb534b4ee2133b185e5ed1 | geophf/1HaskellADay | Solution.hs | # LANGUAGE OverloadedStrings , QuasiQuotes #
module Y2018.M04.D04.Solution where
-
So you have the data from the last two day 's exercises , let 's start storing
those data into a PostgreSQL database . Today 's exercise is to store just
the authors .
But there 's a catch : you have to consider you 're doing this as a daily upload .
So : are there authors already stored ? If so we do n't store them , if not , we
DO store them and get back the unique ID associated with those authors ( for
eventual storage in an article_author join table .
First , fetch all the authors already stored ( with , of course their unique ids )
-
So you have the data from the last two day's exercises, let's start storing
those data into a PostgreSQL database. Today's exercise is to store just
the authors.
But there's a catch: you have to consider you're doing this as a daily upload.
So: are there authors already stored? If so we don't store them, if not, we
DO store them and get back the unique ID associated with those authors (for
eventual storage in an article_author join table.
First, fetch all the authors already stored (with, of course their unique ids)
--}
import Control.Monad.State
import Data.Aeson
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Tuple (swap)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
we will use previous techniques for tables :
below imports available via 1HaskellADay git repository
import Data.LookupTable
import Data.MemoizingTable (MemoizingS, MemoizingTable(MT))
import qualified Data.MemoizingTable as MT
import Store.SQL.Util.Indexed
import Store.SQL.Util.LookupTable
import Y2018.M04.D02.Solution hiding (idx)
import Y2018.M04.D03.Solution
import Y2018.M04.D05.Solution -- looking forward in time, m'kay
1 . fetch the authors into a then convert that into a
-- table state
-
> > > arts
> > > ( Success arties ) = ( fromJSON json ) : : Result [ Article ]
> > > ci < - connectInfo " WPJ "
> > > conn < - connect
>>> json <- readJSON arts
>>> (Success arties) = (fromJSON json) :: Result [Article]
>>> ci <- connectInfo "WPJ"
>>> conn <- connect ci
--}
authorTableName :: String
authorTableName = "author"
lookupAuthors :: Connection -> IO LookupTable
lookupAuthors = flip lookupTable authorTableName
{--
>>> auths <- lookupAuthors conn
fromList []
--}
type MemoizedAuthors m = MemoizingS m Integer Author ()
lk2MS :: Monad m => LookupTable -> MemoizedAuthors m
lk2MS table = put (MT.start (map swap $ Map.toList table), Map.empty)
2 . from yesterday 's exercise , triage the authors into the memoizing table
addNewAuthors :: Monad m => [Author] -> MemoizedAuthors m
addNewAuthors = MT.triageM 5 -- because '5' is a nice number
3 . store the new memoizing table values into the author table
authorStmt :: Query
authorStmt = [sql|INSERT INTO author (author) VALUES (?) returning id|]
data AuthorVal = AV Author
instance ToRow AuthorVal where
toRow (AV x) = [toField x]
insertAuthors :: Connection -> MemoizedAuthors IO
insertAuthors conn = get >>= \(mt@(MT _ _ news), _) ->
let authors = Set.toList news
auths = map AV authors in
if null auths then return () else
lift ((returning conn authorStmt auths) :: IO [Index]) >>= \idxen ->
put (MT.update (zip (map idx idxen) authors) mt, Map.empty)
-
> > > execStateT ( addNewAuthors ( Map.elems $ authors arties ) > >
insertAuthors conn ) ( MT.start ( map swap $ Map.toList auths ) , Map.empty )
( MT { fromTable = fromList [ ( 1,"Ahmed H. Adam"),(2,"Jonathan Cristol " ) ] ,
readIndex = fromList [ ( " Ahmed H. Adam",1),("Jonathan Cristol",2 ) ] ,
newValues = fromList [ ] } , fromList [ ] )
> > > close conn
$ select * from author ;
i d author
--------------
1
>>> execStateT (addNewAuthors (Map.elems $ authors arties) >>
insertAuthors conn) (MT.start (map swap $ Map.toList auths), Map.empty)
(MT {fromTable = fromList [(1,"Ahmed H. Adam"),(2,"Jonathan Cristol")],
readIndex = fromList [("Ahmed H. Adam",1),("Jonathan Cristol",2)],
newValues = fromList []},fromList [])
>>> close conn
$ select * from author;
id author
--------------
1 Ahmed H. Adam
2 Jonathan Cristol
--}
and there we go for today ! Have at it !
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2018/M04/D04/Solution.hs | haskell | }
looking forward in time, m'kay
table state
}
-
>>> auths <- lookupAuthors conn
fromList []
-
because '5' is a nice number
------------
------------
} | # LANGUAGE OverloadedStrings , QuasiQuotes #
module Y2018.M04.D04.Solution where
-
So you have the data from the last two day 's exercises , let 's start storing
those data into a PostgreSQL database . Today 's exercise is to store just
the authors .
But there 's a catch : you have to consider you 're doing this as a daily upload .
So : are there authors already stored ? If so we do n't store them , if not , we
DO store them and get back the unique ID associated with those authors ( for
eventual storage in an article_author join table .
First , fetch all the authors already stored ( with , of course their unique ids )
-
So you have the data from the last two day's exercises, let's start storing
those data into a PostgreSQL database. Today's exercise is to store just
the authors.
But there's a catch: you have to consider you're doing this as a daily upload.
So: are there authors already stored? If so we don't store them, if not, we
DO store them and get back the unique ID associated with those authors (for
eventual storage in an article_author join table.
First, fetch all the authors already stored (with, of course their unique ids)
import Control.Monad.State
import Data.Aeson
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Tuple (swap)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
we will use previous techniques for tables :
below imports available via 1HaskellADay git repository
import Data.LookupTable
import Data.MemoizingTable (MemoizingS, MemoizingTable(MT))
import qualified Data.MemoizingTable as MT
import Store.SQL.Util.Indexed
import Store.SQL.Util.LookupTable
import Y2018.M04.D02.Solution hiding (idx)
import Y2018.M04.D03.Solution
1 . fetch the authors into a then convert that into a
-
> > > arts
> > > ( Success arties ) = ( fromJSON json ) : : Result [ Article ]
> > > ci < - connectInfo " WPJ "
> > > conn < - connect
>>> json <- readJSON arts
>>> (Success arties) = (fromJSON json) :: Result [Article]
>>> ci <- connectInfo "WPJ"
>>> conn <- connect ci
authorTableName :: String
authorTableName = "author"
lookupAuthors :: Connection -> IO LookupTable
lookupAuthors = flip lookupTable authorTableName
type MemoizedAuthors m = MemoizingS m Integer Author ()
lk2MS :: Monad m => LookupTable -> MemoizedAuthors m
lk2MS table = put (MT.start (map swap $ Map.toList table), Map.empty)
2 . from yesterday 's exercise , triage the authors into the memoizing table
addNewAuthors :: Monad m => [Author] -> MemoizedAuthors m
3 . store the new memoizing table values into the author table
authorStmt :: Query
authorStmt = [sql|INSERT INTO author (author) VALUES (?) returning id|]
data AuthorVal = AV Author
instance ToRow AuthorVal where
toRow (AV x) = [toField x]
insertAuthors :: Connection -> MemoizedAuthors IO
insertAuthors conn = get >>= \(mt@(MT _ _ news), _) ->
let authors = Set.toList news
auths = map AV authors in
if null auths then return () else
lift ((returning conn authorStmt auths) :: IO [Index]) >>= \idxen ->
put (MT.update (zip (map idx idxen) authors) mt, Map.empty)
-
> > > execStateT ( addNewAuthors ( Map.elems $ authors arties ) > >
insertAuthors conn ) ( MT.start ( map swap $ Map.toList auths ) , Map.empty )
( MT { fromTable = fromList [ ( 1,"Ahmed H. Adam"),(2,"Jonathan Cristol " ) ] ,
readIndex = fromList [ ( " Ahmed H. Adam",1),("Jonathan Cristol",2 ) ] ,
newValues = fromList [ ] } , fromList [ ] )
> > > close conn
$ select * from author ;
i d author
1
>>> execStateT (addNewAuthors (Map.elems $ authors arties) >>
insertAuthors conn) (MT.start (map swap $ Map.toList auths), Map.empty)
(MT {fromTable = fromList [(1,"Ahmed H. Adam"),(2,"Jonathan Cristol")],
readIndex = fromList [("Ahmed H. Adam",1),("Jonathan Cristol",2)],
newValues = fromList []},fromList [])
>>> close conn
$ select * from author;
id author
1 Ahmed H. Adam
2 Jonathan Cristol
and there we go for today ! Have at it !
|
65a862743202869285216170666f81597020d3310cd58a41728f852f4d247104 | Mathieu-Desrochers/Schemings | time.scm | (declare (unit time))
(foreign-declare "
#include <time.h>
// allocates a tm
struct tm* malloc_tm()
{
struct tm* tm = malloc(sizeof(struct tm));
if (tm != NULL)
{
tm->tm_sec = 0;
tm->tm_min = 0;
tm->tm_hour = 0;
tm->tm_mday = 1;
tm->tm_mon = 0;
tm->tm_year = 0;
}
return tm;
}
// gets the values pointed by a tm*
int tm_sec(struct tm* tm) { return tm->tm_sec; }
int tm_min(struct tm* tm) { return tm->tm_min; }
int tm_hour(struct tm* tm) { return tm->tm_hour; }
int tm_mday(struct tm* tm) { return tm->tm_mday; }
int tm_wday(struct tm* tm) { return tm->tm_wday; }
int tm_mon(struct tm* tm) { return tm->tm_mon; }
int tm_year(struct tm* tm) { return tm->tm_year; }
// sets the values pointed by a tm*
void tm_sec_set(struct tm* tm, int value) { tm->tm_sec = value; }
void tm_min_set(struct tm* tm, int value) { tm->tm_min = value; }
void tm_hour_set(struct tm* tm, int value) { tm->tm_hour = value; }
void tm_mday_set(struct tm* tm, int value) { tm->tm_mday = value; }
void tm_mon_set(struct tm* tm, int value) { tm->tm_mon = value; }
void tm_year_set(struct tm* tm, int value) { tm->tm_year = value; }
// frees a tm
void free_tm(struct tm* tm)
{
free(tm);
}
// wraps the gmtime_r function
struct tm* gmtime_r_wrapped(int64_t timer, struct tm* tm)
{
return gmtime_r(&timer, tm);
}
// wraps the strftime function
char* strftime_wrapped(const char* format, const struct tm* tm)
{
char* result = malloc(64 * sizeof(char));
int strftime_result = strftime(result, 64, format, tm);
if (strftime_result == 0)
{
free(result);
return NULL;
}
return result;
}
")
;; tm pointers definitions
(define-foreign-type tm "struct tm")
(define-foreign-type tm* (c-pointer tm))
;; tm pointers memory management
(define malloc-tm (foreign-lambda tm* "malloc_tm"))
(define free-tm (foreign-lambda void "free_tm" tm*))
returns the number of seconds since the epoch
(define time* (foreign-lambda integer64 "time" (c-pointer integer64)))
breaks down the number of seconds since epoch
(define gmtime-r (foreign-lambda tm* "gmtime_r_wrapped" integer64 tm*))
;; gets the parts of a broken down time
(define tm-sec (foreign-lambda int "tm_sec" tm*))
(define tm-min (foreign-lambda int "tm_min" tm*))
(define tm-hour (foreign-lambda int "tm_hour" tm*))
(define tm-mday (foreign-lambda int "tm_mday" tm*))
(define tm-wday (foreign-lambda int "tm_wday" tm*))
(define tm-mon (foreign-lambda int "tm_mon" tm*))
(define tm-year (foreign-lambda int "tm_year" tm*))
;; sets the parts of a broken down time
(define tm-sec-set! (foreign-lambda void "tm_sec_set" tm* int))
(define tm-min-set! (foreign-lambda void "tm_min_set" tm* int))
(define tm-hour-set! (foreign-lambda void "tm_hour_set" tm* int))
(define tm-mday-set! (foreign-lambda void "tm_mday_set" tm* int))
(define tm-mon-set! (foreign-lambda void "tm_mon_set" tm* int))
(define tm-year-set! (foreign-lambda void "tm_year_set" tm* int))
recombines the number of seconds since epoch
(define timegm (foreign-lambda integer64 "timegm" tm*))
;; format a broken down time
(define strftime (foreign-lambda c-string* "strftime_wrapped" (const c-string) (const tm*)))
;; parses a broken down time
(define strptime (foreign-lambda c-string "strptime" (const c-string) (const c-string) tm*))
| null | https://raw.githubusercontent.com/Mathieu-Desrochers/Schemings/a7c322ee37bf9f43b696c52fc290488aa2dcc238/sources/foreign-interfaces/time.scm | scheme |
}
}
}
}
}
}
}
}
}
}
}
}
}
tm pointers definitions
tm pointers memory management
gets the parts of a broken down time
sets the parts of a broken down time
format a broken down time
parses a broken down time | (declare (unit time))
(foreign-declare "
#include <time.h>
// allocates a tm
struct tm* malloc_tm()
{
if (tm != NULL)
{
}
}
// gets the values pointed by a tm*
// sets the values pointed by a tm*
// frees a tm
void free_tm(struct tm* tm)
{
}
// wraps the gmtime_r function
struct tm* gmtime_r_wrapped(int64_t timer, struct tm* tm)
{
}
// wraps the strftime function
char* strftime_wrapped(const char* format, const struct tm* tm)
{
if (strftime_result == 0)
{
}
}
")
(define-foreign-type tm "struct tm")
(define-foreign-type tm* (c-pointer tm))
(define malloc-tm (foreign-lambda tm* "malloc_tm"))
(define free-tm (foreign-lambda void "free_tm" tm*))
returns the number of seconds since the epoch
(define time* (foreign-lambda integer64 "time" (c-pointer integer64)))
breaks down the number of seconds since epoch
(define gmtime-r (foreign-lambda tm* "gmtime_r_wrapped" integer64 tm*))
(define tm-sec (foreign-lambda int "tm_sec" tm*))
(define tm-min (foreign-lambda int "tm_min" tm*))
(define tm-hour (foreign-lambda int "tm_hour" tm*))
(define tm-mday (foreign-lambda int "tm_mday" tm*))
(define tm-wday (foreign-lambda int "tm_wday" tm*))
(define tm-mon (foreign-lambda int "tm_mon" tm*))
(define tm-year (foreign-lambda int "tm_year" tm*))
(define tm-sec-set! (foreign-lambda void "tm_sec_set" tm* int))
(define tm-min-set! (foreign-lambda void "tm_min_set" tm* int))
(define tm-hour-set! (foreign-lambda void "tm_hour_set" tm* int))
(define tm-mday-set! (foreign-lambda void "tm_mday_set" tm* int))
(define tm-mon-set! (foreign-lambda void "tm_mon_set" tm* int))
(define tm-year-set! (foreign-lambda void "tm_year_set" tm* int))
recombines the number of seconds since epoch
(define timegm (foreign-lambda integer64 "timegm" tm*))
(define strftime (foreign-lambda c-string* "strftime_wrapped" (const c-string) (const tm*)))
(define strptime (foreign-lambda c-string "strptime" (const c-string) (const c-string) tm*))
|
10786b23f2d8aa4e93381d5387c1c537154959b693c1db95051b579723705250 | Soyn/sicp | Ex2.33.rkt | #lang racket
Ex 2.33
题干条件
(define (square x)
(* x x))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (my-map p sequence)
(accumulate (lambda (x y)
(cons (p x) y))
null sequence))
(define (my-append seq1 seq2)
(accumulate cons seq2 seq1))
(define (my-length sequence)
(accumulate (lambda(x y)
(+ 1 y))
0 sequence))
;test usage
(define x (list 1 2 3))
(define y (list 4 5 6))
(my-append x y)
(my-length x)
(my-map square x) | null | https://raw.githubusercontent.com/Soyn/sicp/d2aa6e3b053f6d4c8150ab1b033a18f61fca7e1b/CH2/CH2.2/Ex2.33.rkt | racket | test usage | #lang racket
Ex 2.33
题干条件
(define (square x)
(* x x))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (my-map p sequence)
(accumulate (lambda (x y)
(cons (p x) y))
null sequence))
(define (my-append seq1 seq2)
(accumulate cons seq2 seq1))
(define (my-length sequence)
(accumulate (lambda(x y)
(+ 1 y))
0 sequence))
(define x (list 1 2 3))
(define y (list 4 5 6))
(my-append x y)
(my-length x)
(my-map square x) |
6bf22faf852e0d6b8ee8e1c5ae4cfd7f0004ec64e3b171272fc7e331d9df22b4 | xmonad/xmonad-contrib | CycleSelectedLayouts.hs | -----------------------------------------------------------------------------
-- |
Module : XMonad . Actions . CycleSelectedLayouts
-- Description : Cycle through the given subset of layouts.
Copyright : ( c ) Roman Cheplyaka
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Roman Cheplyaka <>
-- Stability : unstable
-- Portability : unportable
--
-- This module allows to cycle through the given subset of layouts.
--
-----------------------------------------------------------------------------
module XMonad.Actions.CycleSelectedLayouts (
-- * Usage
-- $usage
cycleThroughLayouts) where
import XMonad
import XMonad.Prelude (elemIndex, fromMaybe)
import qualified XMonad.StackSet as S
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
> import XMonad
> import XMonad . Actions . CycleSelectedLayouts
--
> , ( ( modm , xK_t ) , cycleThroughLayouts [ " Tall " , " Mirror Tall " ] )
cycleToNext :: (Eq a) => [a] -> a -> Maybe a
cycleToNext lst a = do
-- not beautiful but simple and readable
ind <- elemIndex a lst
return $ lst !! if ind == length lst - 1 then 0 else ind+1
-- | If the current layout is in the list, cycle to the next layout. Otherwise,
apply the first layout from list .
cycleThroughLayouts :: [String] -> X ()
cycleThroughLayouts lst = do
winset <- gets windowset
let ld = description . S.layout . S.workspace . S.current $ winset
let newld = fromMaybe (head lst) (cycleToNext lst ld)
sendMessage $ JumpToLayout newld
| null | https://raw.githubusercontent.com/xmonad/xmonad-contrib/3058d1ca22d565b2fa93227fdde44d8626d6f75d/XMonad/Actions/CycleSelectedLayouts.hs | haskell | ---------------------------------------------------------------------------
|
Description : Cycle through the given subset of layouts.
License : BSD3-style (see LICENSE)
Maintainer : Roman Cheplyaka <>
Stability : unstable
Portability : unportable
This module allows to cycle through the given subset of layouts.
---------------------------------------------------------------------------
* Usage
$usage
$usage
You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
not beautiful but simple and readable
| If the current layout is in the list, cycle to the next layout. Otherwise, | Module : XMonad . Actions . CycleSelectedLayouts
Copyright : ( c ) Roman Cheplyaka
module XMonad.Actions.CycleSelectedLayouts (
cycleThroughLayouts) where
import XMonad
import XMonad.Prelude (elemIndex, fromMaybe)
import qualified XMonad.StackSet as S
> import XMonad
> import XMonad . Actions . CycleSelectedLayouts
> , ( ( modm , xK_t ) , cycleThroughLayouts [ " Tall " , " Mirror Tall " ] )
cycleToNext :: (Eq a) => [a] -> a -> Maybe a
cycleToNext lst a = do
ind <- elemIndex a lst
return $ lst !! if ind == length lst - 1 then 0 else ind+1
apply the first layout from list .
cycleThroughLayouts :: [String] -> X ()
cycleThroughLayouts lst = do
winset <- gets windowset
let ld = description . S.layout . S.workspace . S.current $ winset
let newld = fromMaybe (head lst) (cycleToNext lst ld)
sendMessage $ JumpToLayout newld
|
9eed46402ffb5044543bc2b2a674e0cb6db076a3e6ef4938c9311703dff491a3 | CardanoSolutions/ogmios | Babbage.hs | 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 /.
# LANGUAGE TypeApplications #
module Ogmios.Data.Json.Babbage where
import Ogmios.Data.Json.Prelude
import Cardano.Binary
( serialize'
)
import Cardano.Ledger.Crypto
( Crypto
)
import GHC.Records
( getField
)
import Ouroboros.Consensus.Cardano.Block
( BabbageEra
)
import Ouroboros.Consensus.Protocol.Praos
( Praos
)
import Ouroboros.Consensus.Shelley.Ledger.Block
( ShelleyBlock (..)
)
import Ouroboros.Consensus.Shelley.Protocol.Praos
()
import qualified Data.Map.Strict as Map
import qualified Ouroboros.Consensus.Protocol.Praos.Header as Praos
import qualified Cardano.Ledger.AuxiliaryData as Ledger
import qualified Cardano.Ledger.Block as Ledger
import qualified Cardano.Ledger.Core as Ledger
import qualified Cardano.Ledger.Era as Ledger
import qualified Cardano.Ledger.TxIn as Ledger
import qualified Cardano.Ledger.Shelley.API as Ledger.Shelley
import qualified Cardano.Ledger.Shelley.PParams as Ledger.Shelley
import qualified Cardano.Ledger.Alonzo.Data as Ledger.Alonzo
import qualified Cardano.Ledger.Alonzo.TxSeq as Ledger.Alonzo
import qualified Cardano.Ledger.Babbage.PParams as Ledger.Babbage
import qualified Cardano.Ledger.Babbage.Rules.Utxo as Ledger.Babbage
import qualified Cardano.Ledger.Babbage.Rules.Utxow as Ledger.Babbage
import qualified Cardano.Ledger.Babbage.Tx as Ledger.Babbage
import qualified Cardano.Ledger.Babbage.TxBody as Ledger.Babbage
import qualified Cardano.Ledger.Shelley.Rules.Ledger as Rules
import qualified Ogmios.Data.Json.Allegra as Allegra
import qualified Ogmios.Data.Json.Alonzo as Alonzo
import qualified Ogmios.Data.Json.Mary as Mary
import qualified Ogmios.Data.Json.Shelley as Shelley
encodeBlock
:: Crypto crypto
=> SerializationMode
-> ShelleyBlock (Praos crypto) (BabbageEra crypto)
-> Json
encodeBlock mode (ShelleyBlock (Ledger.Block blkHeader txs) headerHash) = encodeObject
[ ( "body"
, encodeFoldable (encodeTx mode) (Ledger.Alonzo.txSeqTxns txs)
)
, ( "header"
, encodeHeader mode blkHeader
)
, ( "headerHash"
, Shelley.encodeShelleyHash headerHash
)
]
encodeHeader
:: Crypto crypto
=> SerializationMode
-> Praos.Header crypto
-> Json
encodeHeader mode (Praos.Header hBody hSig) = encodeObjectWithMode mode
[ ( "blockHeight"
, encodeBlockNo (Praos.hbBlockNo hBody)
)
, ( "slot"
, encodeSlotNo (Praos.hbSlotNo hBody)
)
, ( "prevHash"
, Shelley.encodePrevHash (Praos.hbPrev hBody)
)
, ( "issuerVk"
, Shelley.encodeVKey (Praos.hbVk hBody)
)
, ( "issuerVrf"
, Shelley.encodeVerKeyVRF (Praos.hbVrfVk hBody)
)
, ( "blockSize"
, encodeWord32 (Praos.hbBodySize hBody)
)
, ( "blockHash"
, Shelley.encodeHash (Praos.hbBodyHash hBody)
)
]
[ ( "protocolVersion"
, Shelley.encodeProtVer (Praos.hbProtVer hBody)
)
, ( "opCert"
, Shelley.encodeOCert (Praos.hbOCert hBody)
)
, ( "signature"
, Shelley.encodeSignedKES hSig
)
, ( "vrfInput"
, Shelley.encodeCertifiedVRF (Praos.hbVrfRes hBody)
)
]
encodeUtxoFailure
:: Crypto crypto
=> Rules.PredicateFailure (Ledger.EraRule "UTXO" (BabbageEra crypto))
-> Json
encodeUtxoFailure = \case
Ledger.Babbage.FromAlonzoUtxoFail e ->
Alonzo.encodeUtxoFailure encodeUtxo encodeTxOut (\(Ledger.Babbage.TxOut addr _ _ _) -> addr) e
Ledger.Babbage.IncorrectTotalCollateralField computed declared ->
encodeObject
[ ( "totalCollateralMismatch"
, encodeObject
[ ( "computedFromDelta", encodeCoin computed )
, ( "declaredInField", encodeCoin declared )
]
)
]
Ledger.Babbage.BabbageOutputTooSmallUTxO outs ->
encodeObject
[ ( "outputTooSmall"
, encodeFoldable
(\(out, minimumValue) -> encodeObject
[ ( "output", encodeTxOut out )
, ( "minimumRequiredValue", encodeCoin minimumValue )
]
)
outs
)
]
encodeUtxowFailure
:: Crypto crypto
=> Rules.PredicateFailure (Ledger.EraRule "UTXOW" (BabbageEra crypto))
-> Json
encodeUtxowFailure = \case
Ledger.Babbage.MalformedReferenceScripts scripts ->
encodeObject
[ ( "malformedReferenceScripts"
, encodeFoldable Shelley.encodeScriptHash scripts
)
]
Ledger.Babbage.MalformedScriptWitnesses scripts ->
encodeObject
[ ( "malformedScriptWitnesses"
, encodeFoldable Shelley.encodeScriptHash scripts
)
]
Ledger.Babbage.FromAlonzoUtxowFail e ->
Alonzo.encodeUtxowPredicateFail encodeUtxoFailure e
Ledger.Babbage.UtxoFailure e ->
encodeUtxoFailure e
encodeLedgerFailure
:: Crypto crypto
=> Rules.PredicateFailure (Ledger.EraRule "LEDGER" (BabbageEra crypto))
-> Json
encodeLedgerFailure = \case
Rules.UtxowFailure e ->
encodeUtxowFailure e
Rules.DelegsFailure e ->
Shelley.encodeDelegsFailure e
encodeProposedPPUpdates
:: Crypto crypto
=> Ledger.Shelley.ProposedPPUpdates (BabbageEra crypto)
-> Json
encodeProposedPPUpdates (Ledger.Shelley.ProposedPPUpdates m) =
encodeMap Shelley.stringifyKeyHash (encodePParams' encodeStrictMaybe) m
encodePParams'
:: (forall a. (a -> Json) -> Ledger.Shelley.HKD f a -> Json)
-> Ledger.Babbage.PParams' f era
-> Json
encodePParams' encodeF x = encodeObject
[ ( "minFeeCoefficient"
, encodeF encodeNatural (Ledger.Babbage._minfeeA x)
)
, ( "minFeeConstant"
, encodeF encodeNatural (Ledger.Babbage._minfeeB x)
)
, ( "maxBlockBodySize"
, encodeF encodeNatural (Ledger.Babbage._maxBBSize x)
)
, ( "maxBlockHeaderSize"
, encodeF encodeNatural (Ledger.Babbage._maxBHSize x)
)
, ( "maxTxSize"
, encodeF encodeNatural (Ledger.Babbage._maxTxSize x)
)
, ( "stakeKeyDeposit"
, encodeF encodeCoin (Ledger.Babbage._keyDeposit x)
)
, ( "poolDeposit"
, encodeF encodeCoin (Ledger.Babbage._poolDeposit x)
)
, ( "poolRetirementEpochBound"
, encodeF encodeEpochNo (Ledger.Babbage._eMax x)
)
, ( "desiredNumberOfPools"
, encodeF encodeNatural (Ledger.Babbage._nOpt x)
)
, ( "poolInfluence"
, encodeF encodeNonNegativeInterval (Ledger.Babbage._a0 x)
)
, ( "monetaryExpansion"
, encodeF encodeUnitInterval (Ledger.Babbage._rho x)
)
, ( "treasuryExpansion"
, encodeF encodeUnitInterval (Ledger.Babbage._tau x)
)
, ( "protocolVersion"
, encodeF Shelley.encodeProtVer (Ledger.Babbage._protocolVersion x)
)
, ( "minPoolCost"
, encodeF encodeCoin (Ledger.Babbage._minPoolCost x)
)
, ( "coinsPerUtxoByte"
, encodeF encodeCoin (Ledger.Babbage._coinsPerUTxOByte x)
)
, ( "costModels"
, encodeF Alonzo.encodeCostModels (Ledger.Babbage._costmdls x)
)
, ( "prices"
, encodeF Alonzo.encodePrices (Ledger.Babbage._prices x)
)
, ( "maxExecutionUnitsPerTransaction"
, encodeF Alonzo.encodeExUnits (Ledger.Babbage._maxTxExUnits x)
)
, ( "maxExecutionUnitsPerBlock"
, encodeF Alonzo.encodeExUnits (Ledger.Babbage._maxBlockExUnits x)
)
, ( "maxValueSize"
, encodeF encodeNatural (Ledger.Babbage._maxValSize x)
)
, ( "collateralPercentage"
, encodeF encodeNatural (Ledger.Babbage._collateralPercentage x)
)
, ( "maxCollateralInputs"
, encodeF encodeNatural (Ledger.Babbage._maxCollateralInputs x)
)
]
encodeTx
:: forall crypto. Crypto crypto
=> SerializationMode
-> Ledger.Babbage.ValidatedTx (BabbageEra crypto)
-> Json
encodeTx mode x = encodeObjectWithMode mode
[ ( "id"
, Shelley.encodeTxId (Ledger.txid @(BabbageEra crypto) (Ledger.Babbage.body x))
)
, ( "body"
, encodeTxBody (Ledger.Babbage.body x)
)
, ( "metadata"
, (,) <$> fmap (("hash",) . Shelley.encodeAuxiliaryDataHash) (adHash (Ledger.Babbage.body x))
<*> fmap (("body",) . Alonzo.encodeAuxiliaryData) (Ledger.Babbage.auxiliaryData x)
& encodeStrictMaybe (\(a, b) -> encodeObject [a,b])
)
, ( "inputSource"
, Alonzo.encodeIsValid (Ledger.Babbage.isValid x)
)
]
[ ( "witness"
, Alonzo.encodeWitnessSet (Ledger.Babbage.wits x)
)
, ( "raw"
, encodeByteStringBase64 (serialize' x)
)
]
where
adHash :: Ledger.Babbage.TxBody era -> StrictMaybe (Ledger.AuxiliaryDataHash (Ledger.Crypto era))
adHash = getField @"adHash"
encodeTxBody
:: Crypto crypto
=> Ledger.Babbage.TxBody (BabbageEra crypto)
-> Json
encodeTxBody x = encodeObject
[ ( "inputs"
, encodeFoldable Shelley.encodeTxIn (Ledger.Babbage.inputs x)
)
, ( "collaterals"
, encodeFoldable Shelley.encodeTxIn (Ledger.Babbage.collateral x)
)
, ( "references"
, encodeFoldable Shelley.encodeTxIn (Ledger.Babbage.referenceInputs x)
)
, ( "collateralReturn"
, encodeStrictMaybe encodeTxOut (Ledger.Babbage.collateralReturn' x)
)
, ( "totalCollateral"
, encodeStrictMaybe encodeCoin (Ledger.Babbage.totalCollateral x)
)
, ( "outputs"
, encodeFoldable encodeTxOut (Ledger.Babbage.outputs' x)
)
, ( "certificates"
, encodeFoldable Shelley.encodeDCert (Ledger.Babbage.txcerts x)
)
, ( "withdrawals"
, Shelley.encodeWdrl (Ledger.Babbage.txwdrls x)
)
, ( "fee"
, encodeCoin (Ledger.Babbage.txfee x)
)
, ( "validityInterval"
, Allegra.encodeValidityInterval (Ledger.Babbage.txvldt x)
)
, ( "update"
, encodeStrictMaybe encodeUpdate (Ledger.Babbage.txUpdates x)
)
, ( "mint"
, Mary.encodeValue (Ledger.Babbage.mint x)
)
, ( "network"
, encodeStrictMaybe Shelley.encodeNetwork (Ledger.Babbage.txnetworkid x)
)
, ( "scriptIntegrityHash"
, encodeStrictMaybe Alonzo.encodeScriptIntegrityHash (Ledger.Babbage.scriptIntegrityHash x)
)
, ( "requiredExtraSignatures"
, encodeFoldable Shelley.encodeKeyHash (Ledger.Babbage.reqSignerHashes x)
)
]
encodeTxOut
:: Crypto crypto
=> Ledger.Babbage.TxOut (BabbageEra crypto)
-> Json
encodeTxOut (Ledger.Babbage.TxOut addr value datum script) = encodeObject
[ ( "address"
, Shelley.encodeAddress addr
)
, ( "value"
, Mary.encodeValue value
)
, ( "datumHash"
, case datum of
Ledger.Alonzo.NoDatum -> encodeNull
Ledger.Alonzo.DatumHash h -> Alonzo.encodeDataHash h
Ledger.Alonzo.Datum{} -> encodeNull
)
, ( "datum"
, case datum of
Ledger.Alonzo.NoDatum -> encodeNull
Ledger.Alonzo.DatumHash{} -> encodeNull
Ledger.Alonzo.Datum bin -> Alonzo.encodeBinaryData bin
)
, ( "script"
, encodeStrictMaybe Alonzo.encodeScript script
)
]
encodeUpdate
:: Crypto crypto
=> Ledger.Shelley.Update (BabbageEra crypto)
-> Json
encodeUpdate (Ledger.Shelley.Update update epoch) = encodeObject
[ ( "proposal"
, encodeProposedPPUpdates update
)
, ( "epoch"
, encodeEpochNo epoch
)
]
encodeUtxo
:: Crypto crypto
=> Ledger.Shelley.UTxO (BabbageEra crypto)
-> Json
encodeUtxo =
encodeList id . Map.foldrWithKey (\i o -> (:) (encodeIO i o)) [] . Ledger.Shelley.unUTxO
where
encodeIO = curry (encode2Tuple Shelley.encodeTxIn encodeTxOut)
encodeUtxoWithMode
:: Crypto crypto
=> SerializationMode
-> Ledger.Shelley.UTxO (BabbageEra crypto)
-> Json
encodeUtxoWithMode mode =
encodeListWithMode mode id . Map.foldrWithKey (\i o -> (:) (encodeIO i o)) [] . Ledger.Shelley.unUTxO
where
encodeIO = curry (encode2Tuple Shelley.encodeTxIn encodeTxOut)
| null | https://raw.githubusercontent.com/CardanoSolutions/ogmios/317c826d9d0388cb7efaf61a34085fc7c1b12b06/server/src/Ogmios/Data/Json/Babbage.hs | haskell | 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 /.
# LANGUAGE TypeApplications #
module Ogmios.Data.Json.Babbage where
import Ogmios.Data.Json.Prelude
import Cardano.Binary
( serialize'
)
import Cardano.Ledger.Crypto
( Crypto
)
import GHC.Records
( getField
)
import Ouroboros.Consensus.Cardano.Block
( BabbageEra
)
import Ouroboros.Consensus.Protocol.Praos
( Praos
)
import Ouroboros.Consensus.Shelley.Ledger.Block
( ShelleyBlock (..)
)
import Ouroboros.Consensus.Shelley.Protocol.Praos
()
import qualified Data.Map.Strict as Map
import qualified Ouroboros.Consensus.Protocol.Praos.Header as Praos
import qualified Cardano.Ledger.AuxiliaryData as Ledger
import qualified Cardano.Ledger.Block as Ledger
import qualified Cardano.Ledger.Core as Ledger
import qualified Cardano.Ledger.Era as Ledger
import qualified Cardano.Ledger.TxIn as Ledger
import qualified Cardano.Ledger.Shelley.API as Ledger.Shelley
import qualified Cardano.Ledger.Shelley.PParams as Ledger.Shelley
import qualified Cardano.Ledger.Alonzo.Data as Ledger.Alonzo
import qualified Cardano.Ledger.Alonzo.TxSeq as Ledger.Alonzo
import qualified Cardano.Ledger.Babbage.PParams as Ledger.Babbage
import qualified Cardano.Ledger.Babbage.Rules.Utxo as Ledger.Babbage
import qualified Cardano.Ledger.Babbage.Rules.Utxow as Ledger.Babbage
import qualified Cardano.Ledger.Babbage.Tx as Ledger.Babbage
import qualified Cardano.Ledger.Babbage.TxBody as Ledger.Babbage
import qualified Cardano.Ledger.Shelley.Rules.Ledger as Rules
import qualified Ogmios.Data.Json.Allegra as Allegra
import qualified Ogmios.Data.Json.Alonzo as Alonzo
import qualified Ogmios.Data.Json.Mary as Mary
import qualified Ogmios.Data.Json.Shelley as Shelley
encodeBlock
:: Crypto crypto
=> SerializationMode
-> ShelleyBlock (Praos crypto) (BabbageEra crypto)
-> Json
encodeBlock mode (ShelleyBlock (Ledger.Block blkHeader txs) headerHash) = encodeObject
[ ( "body"
, encodeFoldable (encodeTx mode) (Ledger.Alonzo.txSeqTxns txs)
)
, ( "header"
, encodeHeader mode blkHeader
)
, ( "headerHash"
, Shelley.encodeShelleyHash headerHash
)
]
encodeHeader
:: Crypto crypto
=> SerializationMode
-> Praos.Header crypto
-> Json
encodeHeader mode (Praos.Header hBody hSig) = encodeObjectWithMode mode
[ ( "blockHeight"
, encodeBlockNo (Praos.hbBlockNo hBody)
)
, ( "slot"
, encodeSlotNo (Praos.hbSlotNo hBody)
)
, ( "prevHash"
, Shelley.encodePrevHash (Praos.hbPrev hBody)
)
, ( "issuerVk"
, Shelley.encodeVKey (Praos.hbVk hBody)
)
, ( "issuerVrf"
, Shelley.encodeVerKeyVRF (Praos.hbVrfVk hBody)
)
, ( "blockSize"
, encodeWord32 (Praos.hbBodySize hBody)
)
, ( "blockHash"
, Shelley.encodeHash (Praos.hbBodyHash hBody)
)
]
[ ( "protocolVersion"
, Shelley.encodeProtVer (Praos.hbProtVer hBody)
)
, ( "opCert"
, Shelley.encodeOCert (Praos.hbOCert hBody)
)
, ( "signature"
, Shelley.encodeSignedKES hSig
)
, ( "vrfInput"
, Shelley.encodeCertifiedVRF (Praos.hbVrfRes hBody)
)
]
encodeUtxoFailure
:: Crypto crypto
=> Rules.PredicateFailure (Ledger.EraRule "UTXO" (BabbageEra crypto))
-> Json
encodeUtxoFailure = \case
Ledger.Babbage.FromAlonzoUtxoFail e ->
Alonzo.encodeUtxoFailure encodeUtxo encodeTxOut (\(Ledger.Babbage.TxOut addr _ _ _) -> addr) e
Ledger.Babbage.IncorrectTotalCollateralField computed declared ->
encodeObject
[ ( "totalCollateralMismatch"
, encodeObject
[ ( "computedFromDelta", encodeCoin computed )
, ( "declaredInField", encodeCoin declared )
]
)
]
Ledger.Babbage.BabbageOutputTooSmallUTxO outs ->
encodeObject
[ ( "outputTooSmall"
, encodeFoldable
(\(out, minimumValue) -> encodeObject
[ ( "output", encodeTxOut out )
, ( "minimumRequiredValue", encodeCoin minimumValue )
]
)
outs
)
]
encodeUtxowFailure
:: Crypto crypto
=> Rules.PredicateFailure (Ledger.EraRule "UTXOW" (BabbageEra crypto))
-> Json
encodeUtxowFailure = \case
Ledger.Babbage.MalformedReferenceScripts scripts ->
encodeObject
[ ( "malformedReferenceScripts"
, encodeFoldable Shelley.encodeScriptHash scripts
)
]
Ledger.Babbage.MalformedScriptWitnesses scripts ->
encodeObject
[ ( "malformedScriptWitnesses"
, encodeFoldable Shelley.encodeScriptHash scripts
)
]
Ledger.Babbage.FromAlonzoUtxowFail e ->
Alonzo.encodeUtxowPredicateFail encodeUtxoFailure e
Ledger.Babbage.UtxoFailure e ->
encodeUtxoFailure e
encodeLedgerFailure
:: Crypto crypto
=> Rules.PredicateFailure (Ledger.EraRule "LEDGER" (BabbageEra crypto))
-> Json
encodeLedgerFailure = \case
Rules.UtxowFailure e ->
encodeUtxowFailure e
Rules.DelegsFailure e ->
Shelley.encodeDelegsFailure e
encodeProposedPPUpdates
:: Crypto crypto
=> Ledger.Shelley.ProposedPPUpdates (BabbageEra crypto)
-> Json
encodeProposedPPUpdates (Ledger.Shelley.ProposedPPUpdates m) =
encodeMap Shelley.stringifyKeyHash (encodePParams' encodeStrictMaybe) m
encodePParams'
:: (forall a. (a -> Json) -> Ledger.Shelley.HKD f a -> Json)
-> Ledger.Babbage.PParams' f era
-> Json
encodePParams' encodeF x = encodeObject
[ ( "minFeeCoefficient"
, encodeF encodeNatural (Ledger.Babbage._minfeeA x)
)
, ( "minFeeConstant"
, encodeF encodeNatural (Ledger.Babbage._minfeeB x)
)
, ( "maxBlockBodySize"
, encodeF encodeNatural (Ledger.Babbage._maxBBSize x)
)
, ( "maxBlockHeaderSize"
, encodeF encodeNatural (Ledger.Babbage._maxBHSize x)
)
, ( "maxTxSize"
, encodeF encodeNatural (Ledger.Babbage._maxTxSize x)
)
, ( "stakeKeyDeposit"
, encodeF encodeCoin (Ledger.Babbage._keyDeposit x)
)
, ( "poolDeposit"
, encodeF encodeCoin (Ledger.Babbage._poolDeposit x)
)
, ( "poolRetirementEpochBound"
, encodeF encodeEpochNo (Ledger.Babbage._eMax x)
)
, ( "desiredNumberOfPools"
, encodeF encodeNatural (Ledger.Babbage._nOpt x)
)
, ( "poolInfluence"
, encodeF encodeNonNegativeInterval (Ledger.Babbage._a0 x)
)
, ( "monetaryExpansion"
, encodeF encodeUnitInterval (Ledger.Babbage._rho x)
)
, ( "treasuryExpansion"
, encodeF encodeUnitInterval (Ledger.Babbage._tau x)
)
, ( "protocolVersion"
, encodeF Shelley.encodeProtVer (Ledger.Babbage._protocolVersion x)
)
, ( "minPoolCost"
, encodeF encodeCoin (Ledger.Babbage._minPoolCost x)
)
, ( "coinsPerUtxoByte"
, encodeF encodeCoin (Ledger.Babbage._coinsPerUTxOByte x)
)
, ( "costModels"
, encodeF Alonzo.encodeCostModels (Ledger.Babbage._costmdls x)
)
, ( "prices"
, encodeF Alonzo.encodePrices (Ledger.Babbage._prices x)
)
, ( "maxExecutionUnitsPerTransaction"
, encodeF Alonzo.encodeExUnits (Ledger.Babbage._maxTxExUnits x)
)
, ( "maxExecutionUnitsPerBlock"
, encodeF Alonzo.encodeExUnits (Ledger.Babbage._maxBlockExUnits x)
)
, ( "maxValueSize"
, encodeF encodeNatural (Ledger.Babbage._maxValSize x)
)
, ( "collateralPercentage"
, encodeF encodeNatural (Ledger.Babbage._collateralPercentage x)
)
, ( "maxCollateralInputs"
, encodeF encodeNatural (Ledger.Babbage._maxCollateralInputs x)
)
]
encodeTx
:: forall crypto. Crypto crypto
=> SerializationMode
-> Ledger.Babbage.ValidatedTx (BabbageEra crypto)
-> Json
encodeTx mode x = encodeObjectWithMode mode
[ ( "id"
, Shelley.encodeTxId (Ledger.txid @(BabbageEra crypto) (Ledger.Babbage.body x))
)
, ( "body"
, encodeTxBody (Ledger.Babbage.body x)
)
, ( "metadata"
, (,) <$> fmap (("hash",) . Shelley.encodeAuxiliaryDataHash) (adHash (Ledger.Babbage.body x))
<*> fmap (("body",) . Alonzo.encodeAuxiliaryData) (Ledger.Babbage.auxiliaryData x)
& encodeStrictMaybe (\(a, b) -> encodeObject [a,b])
)
, ( "inputSource"
, Alonzo.encodeIsValid (Ledger.Babbage.isValid x)
)
]
[ ( "witness"
, Alonzo.encodeWitnessSet (Ledger.Babbage.wits x)
)
, ( "raw"
, encodeByteStringBase64 (serialize' x)
)
]
where
adHash :: Ledger.Babbage.TxBody era -> StrictMaybe (Ledger.AuxiliaryDataHash (Ledger.Crypto era))
adHash = getField @"adHash"
encodeTxBody
:: Crypto crypto
=> Ledger.Babbage.TxBody (BabbageEra crypto)
-> Json
encodeTxBody x = encodeObject
[ ( "inputs"
, encodeFoldable Shelley.encodeTxIn (Ledger.Babbage.inputs x)
)
, ( "collaterals"
, encodeFoldable Shelley.encodeTxIn (Ledger.Babbage.collateral x)
)
, ( "references"
, encodeFoldable Shelley.encodeTxIn (Ledger.Babbage.referenceInputs x)
)
, ( "collateralReturn"
, encodeStrictMaybe encodeTxOut (Ledger.Babbage.collateralReturn' x)
)
, ( "totalCollateral"
, encodeStrictMaybe encodeCoin (Ledger.Babbage.totalCollateral x)
)
, ( "outputs"
, encodeFoldable encodeTxOut (Ledger.Babbage.outputs' x)
)
, ( "certificates"
, encodeFoldable Shelley.encodeDCert (Ledger.Babbage.txcerts x)
)
, ( "withdrawals"
, Shelley.encodeWdrl (Ledger.Babbage.txwdrls x)
)
, ( "fee"
, encodeCoin (Ledger.Babbage.txfee x)
)
, ( "validityInterval"
, Allegra.encodeValidityInterval (Ledger.Babbage.txvldt x)
)
, ( "update"
, encodeStrictMaybe encodeUpdate (Ledger.Babbage.txUpdates x)
)
, ( "mint"
, Mary.encodeValue (Ledger.Babbage.mint x)
)
, ( "network"
, encodeStrictMaybe Shelley.encodeNetwork (Ledger.Babbage.txnetworkid x)
)
, ( "scriptIntegrityHash"
, encodeStrictMaybe Alonzo.encodeScriptIntegrityHash (Ledger.Babbage.scriptIntegrityHash x)
)
, ( "requiredExtraSignatures"
, encodeFoldable Shelley.encodeKeyHash (Ledger.Babbage.reqSignerHashes x)
)
]
encodeTxOut
:: Crypto crypto
=> Ledger.Babbage.TxOut (BabbageEra crypto)
-> Json
encodeTxOut (Ledger.Babbage.TxOut addr value datum script) = encodeObject
[ ( "address"
, Shelley.encodeAddress addr
)
, ( "value"
, Mary.encodeValue value
)
, ( "datumHash"
, case datum of
Ledger.Alonzo.NoDatum -> encodeNull
Ledger.Alonzo.DatumHash h -> Alonzo.encodeDataHash h
Ledger.Alonzo.Datum{} -> encodeNull
)
, ( "datum"
, case datum of
Ledger.Alonzo.NoDatum -> encodeNull
Ledger.Alonzo.DatumHash{} -> encodeNull
Ledger.Alonzo.Datum bin -> Alonzo.encodeBinaryData bin
)
, ( "script"
, encodeStrictMaybe Alonzo.encodeScript script
)
]
encodeUpdate
:: Crypto crypto
=> Ledger.Shelley.Update (BabbageEra crypto)
-> Json
encodeUpdate (Ledger.Shelley.Update update epoch) = encodeObject
[ ( "proposal"
, encodeProposedPPUpdates update
)
, ( "epoch"
, encodeEpochNo epoch
)
]
encodeUtxo
:: Crypto crypto
=> Ledger.Shelley.UTxO (BabbageEra crypto)
-> Json
encodeUtxo =
encodeList id . Map.foldrWithKey (\i o -> (:) (encodeIO i o)) [] . Ledger.Shelley.unUTxO
where
encodeIO = curry (encode2Tuple Shelley.encodeTxIn encodeTxOut)
encodeUtxoWithMode
:: Crypto crypto
=> SerializationMode
-> Ledger.Shelley.UTxO (BabbageEra crypto)
-> Json
encodeUtxoWithMode mode =
encodeListWithMode mode id . Map.foldrWithKey (\i o -> (:) (encodeIO i o)) [] . Ledger.Shelley.unUTxO
where
encodeIO = curry (encode2Tuple Shelley.encodeTxIn encodeTxOut)
| |
095cd2460d663995f66acdd28efc8295d0fcab61238d6b383e59c40814d791ff | broadinstitute/firecloud-ui | library_view.cljs | (ns broadfcui.page.workspace.summary.library-view
(:require
[dmohs.react :as react]
[broadfcui.common.links :as links]
[broadfcui.common.style :as style]
[broadfcui.components.collapse :refer [Collapse]]
[broadfcui.components.spinner :refer [spinner]]
[broadfcui.endpoints :as endpoints]
[broadfcui.page.workspace.summary.catalog.wizard :refer [CatalogWizard]]
[broadfcui.page.workspace.summary.library-utils :as library-utils]
[broadfcui.utils :as utils]
))
(def ^:private wizard-keys [:library-schema :workspace :workspace-id :request-refresh :can-share? :owner? :curator? :writer? :catalog-with-read?])
(react/defc LibraryView
{:render
(fn [{:keys [props state]}]
(let [{:keys [library-attributes library-schema]} props
wizard-properties (merge (select-keys props wizard-keys)
{:dismiss #(swap! state dissoc :showing-catalog-wizard?)})
orsp-id (:library:orsp library-attributes)]
[Collapse
{:style {:marginBottom "2rem"}
:title (style/create-section-header "Dataset Attributes")
:title-expand
(style/create-section-header
(links/create-internal {:style {:fontSize "0.8em" :fontWeight "normal" :marginLeft "1em"}
:onClick #(swap! state assoc :showing-catalog-wizard? true)}
"Edit..."))
:contents
[:div {:style {:marginTop "1rem" :fontSize "90%" :lineHeight 1.5}}
(when (:showing-catalog-wizard? @state)
[CatalogWizard wizard-properties])
(map (partial library-utils/render-property library-schema library-attributes) (-> library-schema :display :primary))
(when (:expanded? @state)
[:div {}
(map (partial library-utils/render-property library-schema library-attributes) (-> library-schema :display :secondary))
(if orsp-id
(cond
(:consent @state) (library-utils/render-consent orsp-id (:consent @state))
(:consent-error @state) (library-utils/render-consent-error orsp-id (:consent-error @state))
:else (library-utils/render-library-row (str "Retrieving information for " orsp-id) (spinner)))
(library-utils/render-consent-codes library-schema library-attributes))])
[:div {:style {:marginTop "0.5em"}}
(links/create-internal {:onClick #(swap! state update :expanded? not)}
(if (:expanded? @state) "Collapse" "See more attributes"))]]}]))
:component-did-mount
(fn [{:keys [props state]}]
(when-let [orsp-id (:library:orsp (:library-attributes props))]
(endpoints/get-consent
orsp-id
(fn [{:keys [success? get-parsed-response]}]
(swap! state assoc (if success? :consent :consent-error) (get-parsed-response))))))})
| null | https://raw.githubusercontent.com/broadinstitute/firecloud-ui/8eb077bc137ead105db5665a8fa47a7523145633/src/cljs/main/broadfcui/page/workspace/summary/library_view.cljs | clojure | (ns broadfcui.page.workspace.summary.library-view
(:require
[dmohs.react :as react]
[broadfcui.common.links :as links]
[broadfcui.common.style :as style]
[broadfcui.components.collapse :refer [Collapse]]
[broadfcui.components.spinner :refer [spinner]]
[broadfcui.endpoints :as endpoints]
[broadfcui.page.workspace.summary.catalog.wizard :refer [CatalogWizard]]
[broadfcui.page.workspace.summary.library-utils :as library-utils]
[broadfcui.utils :as utils]
))
(def ^:private wizard-keys [:library-schema :workspace :workspace-id :request-refresh :can-share? :owner? :curator? :writer? :catalog-with-read?])
(react/defc LibraryView
{:render
(fn [{:keys [props state]}]
(let [{:keys [library-attributes library-schema]} props
wizard-properties (merge (select-keys props wizard-keys)
{:dismiss #(swap! state dissoc :showing-catalog-wizard?)})
orsp-id (:library:orsp library-attributes)]
[Collapse
{:style {:marginBottom "2rem"}
:title (style/create-section-header "Dataset Attributes")
:title-expand
(style/create-section-header
(links/create-internal {:style {:fontSize "0.8em" :fontWeight "normal" :marginLeft "1em"}
:onClick #(swap! state assoc :showing-catalog-wizard? true)}
"Edit..."))
:contents
[:div {:style {:marginTop "1rem" :fontSize "90%" :lineHeight 1.5}}
(when (:showing-catalog-wizard? @state)
[CatalogWizard wizard-properties])
(map (partial library-utils/render-property library-schema library-attributes) (-> library-schema :display :primary))
(when (:expanded? @state)
[:div {}
(map (partial library-utils/render-property library-schema library-attributes) (-> library-schema :display :secondary))
(if orsp-id
(cond
(:consent @state) (library-utils/render-consent orsp-id (:consent @state))
(:consent-error @state) (library-utils/render-consent-error orsp-id (:consent-error @state))
:else (library-utils/render-library-row (str "Retrieving information for " orsp-id) (spinner)))
(library-utils/render-consent-codes library-schema library-attributes))])
[:div {:style {:marginTop "0.5em"}}
(links/create-internal {:onClick #(swap! state update :expanded? not)}
(if (:expanded? @state) "Collapse" "See more attributes"))]]}]))
:component-did-mount
(fn [{:keys [props state]}]
(when-let [orsp-id (:library:orsp (:library-attributes props))]
(endpoints/get-consent
orsp-id
(fn [{:keys [success? get-parsed-response]}]
(swap! state assoc (if success? :consent :consent-error) (get-parsed-response))))))})
| |
2ce378c1ffb8255ea29adc37b6616292eb4a8feb1995e8e47607f74b627df793 | avh4/elm-format | Extra.hs | module Shakefiles.Extra (phonyPrefix, forEach) where
import Development.Shake
import Data.List (stripPrefix)
phonyPrefix :: String -> (String -> Action ()) -> Rules ()
phonyPrefix prefix action =
phonys $ \s -> case stripPrefix prefix s of
Nothing -> Nothing
Just match -> Just (action match)
forEach :: Monad m => [a] -> (a -> m ()) -> m ()
forEach list f =
mapM_ f list
| null | https://raw.githubusercontent.com/avh4/elm-format/b670cb9dce2601d6b90504f94e947eeaad46e05d/Shakefile/src/Shakefiles/Extra.hs | haskell | module Shakefiles.Extra (phonyPrefix, forEach) where
import Development.Shake
import Data.List (stripPrefix)
phonyPrefix :: String -> (String -> Action ()) -> Rules ()
phonyPrefix prefix action =
phonys $ \s -> case stripPrefix prefix s of
Nothing -> Nothing
Just match -> Just (action match)
forEach :: Monad m => [a] -> (a -> m ()) -> m ()
forEach list f =
mapM_ f list
| |
10312d7aad45fd9c942849d35cfc222dd76c78f6e517d3b08c92955631efa8a7 | skogsbaer/HTF | Test1.hs | # OPTIONS_GHC -F -pgmF .. / .. /scripts / local - htfpp #
import "HTF" Test.Framework
#include "Foo.h"
foo :: Int -> Int
foo i = i + "Stefan"
main :: IO ()
main = return ()
| null | https://raw.githubusercontent.com/skogsbaer/HTF/a42450c89b7a3a3a50e381f36de3ac28faab2a16/tests/compile-errors/Test1.hs | haskell | # OPTIONS_GHC -F -pgmF .. / .. /scripts / local - htfpp #
import "HTF" Test.Framework
#include "Foo.h"
foo :: Int -> Int
foo i = i + "Stefan"
main :: IO ()
main = return ()
| |
270eaa5d1f49411014016cb1ff36378ec9ece036263bbda245e4597ebac23833 | clojure-interop/aws-api | AbstractAWSStepFunctionsAsync.clj | (ns com.amazonaws.services.stepfunctions.AbstractAWSStepFunctionsAsync
"Abstract implementation of AWSStepFunctionsAsync. Convenient method forms pass through to the corresponding
overload that takes a request object and an AsyncHandler, which throws an
UnsupportedOperationException."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.stepfunctions AbstractAWSStepFunctionsAsync]))
(defn untag-resource-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.UntagResourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UntagResource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.UntagResourceResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.UntagResourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.untagResourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.UntagResourceRequest request]
(-> this (.untagResourceAsync request))))
(defn update-state-machine-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.UpdateStateMachineRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateStateMachine operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.UpdateStateMachineResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.UpdateStateMachineRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateStateMachineAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.UpdateStateMachineRequest request]
(-> this (.updateStateMachineAsync request))))
(defn describe-activity-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DescribeActivityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeActivity operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DescribeActivityResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeActivityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeActivityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeActivityRequest request]
(-> this (.describeActivityAsync request))))
(defn create-state-machine-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.CreateStateMachineRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateStateMachine operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.CreateStateMachineResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.CreateStateMachineRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createStateMachineAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.CreateStateMachineRequest request]
(-> this (.createStateMachineAsync request))))
(defn list-activities-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.ListActivitiesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListActivities operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.ListActivitiesResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListActivitiesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listActivitiesAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListActivitiesRequest request]
(-> this (.listActivitiesAsync request))))
(defn get-execution-history-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.GetExecutionHistoryRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetExecutionHistory operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.GetExecutionHistoryResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.GetExecutionHistoryRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getExecutionHistoryAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.GetExecutionHistoryRequest request]
(-> this (.getExecutionHistoryAsync request))))
(defn describe-execution-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DescribeExecutionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeExecution operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DescribeExecutionResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeExecutionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeExecutionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeExecutionRequest request]
(-> this (.describeExecutionAsync request))))
(defn send-task-heartbeat-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.SendTaskHeartbeatRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the SendTaskHeartbeat operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.SendTaskHeartbeatResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskHeartbeatRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.sendTaskHeartbeatAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskHeartbeatRequest request]
(-> this (.sendTaskHeartbeatAsync request))))
(defn create-activity-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.CreateActivityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateActivity operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.CreateActivityResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.CreateActivityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createActivityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.CreateActivityRequest request]
(-> this (.createActivityAsync request))))
(defn send-task-success-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.SendTaskSuccessRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the SendTaskSuccess operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.SendTaskSuccessResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskSuccessRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.sendTaskSuccessAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskSuccessRequest request]
(-> this (.sendTaskSuccessAsync request))))
(defn list-executions-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.ListExecutionsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListExecutions operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.ListExecutionsResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListExecutionsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listExecutionsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListExecutionsRequest request]
(-> this (.listExecutionsAsync request))))
(defn start-execution-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.StartExecutionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the StartExecution operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.StartExecutionResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.StartExecutionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.startExecutionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.StartExecutionRequest request]
(-> this (.startExecutionAsync request))))
(defn get-activity-task-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.GetActivityTaskRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetActivityTask operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.GetActivityTaskResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.GetActivityTaskRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getActivityTaskAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.GetActivityTaskRequest request]
(-> this (.getActivityTaskAsync request))))
(defn send-task-failure-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.SendTaskFailureRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the SendTaskFailure operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.SendTaskFailureResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskFailureRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.sendTaskFailureAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskFailureRequest request]
(-> this (.sendTaskFailureAsync request))))
(defn delete-activity-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DeleteActivityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteActivity operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DeleteActivityResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DeleteActivityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteActivityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DeleteActivityRequest request]
(-> this (.deleteActivityAsync request))))
(defn describe-state-machine-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DescribeStateMachineRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeStateMachine operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DescribeStateMachineResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeStateMachineRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeStateMachineAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeStateMachineRequest request]
(-> this (.describeStateMachineAsync request))))
(defn list-tags-for-resource-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.ListTagsForResourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListTagsForResource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.ListTagsForResourceResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListTagsForResourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listTagsForResourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListTagsForResourceRequest request]
(-> this (.listTagsForResourceAsync request))))
(defn stop-execution-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.StopExecutionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the StopExecution operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.StopExecutionResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.StopExecutionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.stopExecutionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.StopExecutionRequest request]
(-> this (.stopExecutionAsync request))))
(defn delete-state-machine-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DeleteStateMachineRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteStateMachine operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DeleteStateMachineResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DeleteStateMachineRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteStateMachineAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DeleteStateMachineRequest request]
(-> this (.deleteStateMachineAsync request))))
(defn describe-state-machine-for-execution-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DescribeStateMachineForExecutionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeStateMachineForExecution operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DescribeStateMachineForExecutionResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeStateMachineForExecutionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeStateMachineForExecutionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeStateMachineForExecutionRequest request]
(-> this (.describeStateMachineForExecutionAsync request))))
(defn tag-resource-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.TagResourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the TagResource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.TagResourceResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.TagResourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.tagResourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.TagResourceRequest request]
(-> this (.tagResourceAsync request))))
(defn list-state-machines-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.ListStateMachinesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListStateMachines operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.ListStateMachinesResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListStateMachinesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listStateMachinesAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListStateMachinesRequest request]
(-> this (.listStateMachinesAsync request))))
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.stepfunctions/src/com/amazonaws/services/stepfunctions/AbstractAWSStepFunctionsAsync.clj | clojure | (ns com.amazonaws.services.stepfunctions.AbstractAWSStepFunctionsAsync
"Abstract implementation of AWSStepFunctionsAsync. Convenient method forms pass through to the corresponding
overload that takes a request object and an AsyncHandler, which throws an
UnsupportedOperationException."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.stepfunctions AbstractAWSStepFunctionsAsync]))
(defn untag-resource-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.UntagResourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UntagResource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.UntagResourceResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.UntagResourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.untagResourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.UntagResourceRequest request]
(-> this (.untagResourceAsync request))))
(defn update-state-machine-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.UpdateStateMachineRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateStateMachine operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.UpdateStateMachineResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.UpdateStateMachineRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateStateMachineAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.UpdateStateMachineRequest request]
(-> this (.updateStateMachineAsync request))))
(defn describe-activity-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DescribeActivityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeActivity operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DescribeActivityResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeActivityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeActivityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeActivityRequest request]
(-> this (.describeActivityAsync request))))
(defn create-state-machine-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.CreateStateMachineRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateStateMachine operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.CreateStateMachineResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.CreateStateMachineRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createStateMachineAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.CreateStateMachineRequest request]
(-> this (.createStateMachineAsync request))))
(defn list-activities-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.ListActivitiesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListActivities operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.ListActivitiesResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListActivitiesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listActivitiesAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListActivitiesRequest request]
(-> this (.listActivitiesAsync request))))
(defn get-execution-history-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.GetExecutionHistoryRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetExecutionHistory operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.GetExecutionHistoryResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.GetExecutionHistoryRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getExecutionHistoryAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.GetExecutionHistoryRequest request]
(-> this (.getExecutionHistoryAsync request))))
(defn describe-execution-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DescribeExecutionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeExecution operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DescribeExecutionResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeExecutionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeExecutionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeExecutionRequest request]
(-> this (.describeExecutionAsync request))))
(defn send-task-heartbeat-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.SendTaskHeartbeatRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the SendTaskHeartbeat operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.SendTaskHeartbeatResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskHeartbeatRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.sendTaskHeartbeatAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskHeartbeatRequest request]
(-> this (.sendTaskHeartbeatAsync request))))
(defn create-activity-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.CreateActivityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateActivity operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.CreateActivityResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.CreateActivityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createActivityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.CreateActivityRequest request]
(-> this (.createActivityAsync request))))
(defn send-task-success-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.SendTaskSuccessRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the SendTaskSuccess operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.SendTaskSuccessResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskSuccessRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.sendTaskSuccessAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskSuccessRequest request]
(-> this (.sendTaskSuccessAsync request))))
(defn list-executions-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.ListExecutionsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListExecutions operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.ListExecutionsResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListExecutionsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listExecutionsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListExecutionsRequest request]
(-> this (.listExecutionsAsync request))))
(defn start-execution-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.StartExecutionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the StartExecution operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.StartExecutionResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.StartExecutionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.startExecutionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.StartExecutionRequest request]
(-> this (.startExecutionAsync request))))
(defn get-activity-task-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.GetActivityTaskRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetActivityTask operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.GetActivityTaskResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.GetActivityTaskRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getActivityTaskAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.GetActivityTaskRequest request]
(-> this (.getActivityTaskAsync request))))
(defn send-task-failure-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.SendTaskFailureRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the SendTaskFailure operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.SendTaskFailureResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskFailureRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.sendTaskFailureAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.SendTaskFailureRequest request]
(-> this (.sendTaskFailureAsync request))))
(defn delete-activity-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DeleteActivityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteActivity operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DeleteActivityResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DeleteActivityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteActivityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DeleteActivityRequest request]
(-> this (.deleteActivityAsync request))))
(defn describe-state-machine-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DescribeStateMachineRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeStateMachine operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DescribeStateMachineResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeStateMachineRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeStateMachineAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeStateMachineRequest request]
(-> this (.describeStateMachineAsync request))))
(defn list-tags-for-resource-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.ListTagsForResourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListTagsForResource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.ListTagsForResourceResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListTagsForResourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listTagsForResourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListTagsForResourceRequest request]
(-> this (.listTagsForResourceAsync request))))
(defn stop-execution-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.StopExecutionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the StopExecution operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.StopExecutionResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.StopExecutionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.stopExecutionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.StopExecutionRequest request]
(-> this (.stopExecutionAsync request))))
(defn delete-state-machine-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DeleteStateMachineRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteStateMachine operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DeleteStateMachineResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DeleteStateMachineRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteStateMachineAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DeleteStateMachineRequest request]
(-> this (.deleteStateMachineAsync request))))
(defn describe-state-machine-for-execution-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.DescribeStateMachineForExecutionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeStateMachineForExecution operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.DescribeStateMachineForExecutionResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeStateMachineForExecutionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeStateMachineForExecutionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.DescribeStateMachineForExecutionRequest request]
(-> this (.describeStateMachineForExecutionAsync request))))
(defn tag-resource-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.TagResourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the TagResource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.TagResourceResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.TagResourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.tagResourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.TagResourceRequest request]
(-> this (.tagResourceAsync request))))
(defn list-state-machines-async
"Description copied from interface: AWSStepFunctionsAsync
request - `com.amazonaws.services.stepfunctions.model.ListStateMachinesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListStateMachines operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.stepfunctions.model.ListStateMachinesResult>`"
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListStateMachinesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listStateMachinesAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAWSStepFunctionsAsync this ^com.amazonaws.services.stepfunctions.model.ListStateMachinesRequest request]
(-> this (.listStateMachinesAsync request))))
| |
4b98e15e73dfeb1db2b959d9bd83f6e4abdbe85c90040a24d706f85375485e0a | marcoheisig/Typo | ntype-contagion.lisp | (in-package #:typo.ntype)
;;; The rules of numeric contagion are as follows:
;;;
;;; CLHS 12.1.4.1: When rationals and floats are combined by a numerical
function , the rational is first converted to a float of the same
;;; format.
;;;
;;; CLHS 12.1.4.4: The result of a numerical function is a float of the
;;; largest format among all the floating-point arguments to the function.
;;;
;;; CLHS 12.1.5.2: When a real and a complex are both part of a
computation , the real is first converted to a complex by providing an
imaginary part of 0 .
(defmethod ntype-contagion ((ntype1 ntype) (ntype2 ntype))
(primitive-ntype-contagion
(ntype-primitive-ntype ntype1)
(ntype-primitive-ntype ntype2)))
(defun ntype-contagion/slow (ntype1 ntype2)
(declare (ntype ntype1 ntype2))
(flet ((fail () (return-from ntype-contagion/slow (empty-ntype))))
(ntype-subtypecase ntype1
((not number) (fail))
(complex
(ntype-subtypecase ntype2
((not number) (fail))
(complex (complex-contagion ntype1 ntype2))
(float (complex-contagion ntype1 (complex-ntype-from-real-ntype ntype2)))
(real (complex-contagion ntype1 (complex-ntype-from-real-ntype ntype2)))
(t (type-specifier-ntype 'complex))))
(float
(ntype-subtypecase ntype2
((not number) (fail))
(complex (complex-contagion (complex-ntype-from-real-ntype ntype1) ntype2))
(float (float-contagion ntype1 ntype2))
(real (ntype-primitive-ntype ntype1))
(t (type-specifier-ntype 'number))))
(real
(ntype-subtypecase ntype2
((not number) (fail))
(complex (complex-contagion (complex-ntype-from-real-ntype ntype1) ntype2))
(float (ntype-primitive-ntype ntype2))
(real (values (ntype-union ntype1 ntype2)))
(t (type-specifier-ntype 'number))))
(t
(ntype-subtypecase ntype2
((not number) (fail))
(t (type-specifier-ntype 'number)))))))
(defun complex-ntype-from-real-ntype (real-ntype)
(assert (ntype-subtypep real-ntype (type-specifier-ntype 'real)))
(find-primitive-ntype `(complex ,(ntype-type-specifier real-ntype))))
(defun float-contagion (ntype1 ntype2)
(assert (ntype-subtypep ntype1 (type-specifier-ntype 'float)))
(assert (ntype-subtypep ntype2 (type-specifier-ntype 'float)))
(macrolet ((body ()
`(ntype-subtypecase ntype1
,@(loop for fp1 in *float-primitive-ntypes*
collect
`(,(primitive-ntype-type-specifier fp1)
(ntype-subtypecase ntype2
,@(loop for fp2 in *float-primitive-ntypes*
collect
`(,(primitive-ntype-type-specifier fp2)
,(if (> (primitive-ntype-bits fp1)
(primitive-ntype-bits fp2))
fp1 fp2)))
(t (type-specifier-ntype 'float)))))
(t (type-specifier-ntype 'float)))))
(body)))
(defun complex-contagion (ntype1 ntype2)
(assert (ntype-subtypep ntype1 (type-specifier-ntype 'complex)))
(assert (ntype-subtypep ntype2 (type-specifier-ntype 'complex)))
(flet ((part-ntype (ntype)
(trivia:match (ntype-type-specifier ntype)
((or 'complex (list 'complex))
(values (universal-ntype) t))
((list 'complex type-specifier)
(type-specifier-ntype type-specifier)))))
(values
(type-specifier-ntype
`(complex
,(ntype-type-specifier
(ntype-contagion/slow
(part-ntype ntype1)
(part-ntype ntype2))))))))
(let ((cache (make-array (list +primitive-ntype-limit+ +primitive-ntype-limit+)
:element-type 'ntype
:initial-element (universal-ntype))))
(loop for p1 across *primitive-ntypes* do
(loop for p2 across *primitive-ntypes* do
(setf (aref cache (ntype-index p1) (ntype-index p2))
(ntype-contagion/slow p1 p2))))
(defun primitive-ntype-contagion (p1 p2)
(declare (primitive-ntype p1 p2))
(aref cache (ntype-index p1) (ntype-index p2))))
| null | https://raw.githubusercontent.com/marcoheisig/Typo/a06eecdcee6994fb5731409fe75fad6b7c59d3a9/code/ntype/ntype-contagion.lisp | lisp | The rules of numeric contagion are as follows:
CLHS 12.1.4.1: When rationals and floats are combined by a numerical
format.
CLHS 12.1.4.4: The result of a numerical function is a float of the
largest format among all the floating-point arguments to the function.
CLHS 12.1.5.2: When a real and a complex are both part of a | (in-package #:typo.ntype)
function , the rational is first converted to a float of the same
computation , the real is first converted to a complex by providing an
imaginary part of 0 .
(defmethod ntype-contagion ((ntype1 ntype) (ntype2 ntype))
(primitive-ntype-contagion
(ntype-primitive-ntype ntype1)
(ntype-primitive-ntype ntype2)))
(defun ntype-contagion/slow (ntype1 ntype2)
(declare (ntype ntype1 ntype2))
(flet ((fail () (return-from ntype-contagion/slow (empty-ntype))))
(ntype-subtypecase ntype1
((not number) (fail))
(complex
(ntype-subtypecase ntype2
((not number) (fail))
(complex (complex-contagion ntype1 ntype2))
(float (complex-contagion ntype1 (complex-ntype-from-real-ntype ntype2)))
(real (complex-contagion ntype1 (complex-ntype-from-real-ntype ntype2)))
(t (type-specifier-ntype 'complex))))
(float
(ntype-subtypecase ntype2
((not number) (fail))
(complex (complex-contagion (complex-ntype-from-real-ntype ntype1) ntype2))
(float (float-contagion ntype1 ntype2))
(real (ntype-primitive-ntype ntype1))
(t (type-specifier-ntype 'number))))
(real
(ntype-subtypecase ntype2
((not number) (fail))
(complex (complex-contagion (complex-ntype-from-real-ntype ntype1) ntype2))
(float (ntype-primitive-ntype ntype2))
(real (values (ntype-union ntype1 ntype2)))
(t (type-specifier-ntype 'number))))
(t
(ntype-subtypecase ntype2
((not number) (fail))
(t (type-specifier-ntype 'number)))))))
(defun complex-ntype-from-real-ntype (real-ntype)
(assert (ntype-subtypep real-ntype (type-specifier-ntype 'real)))
(find-primitive-ntype `(complex ,(ntype-type-specifier real-ntype))))
(defun float-contagion (ntype1 ntype2)
(assert (ntype-subtypep ntype1 (type-specifier-ntype 'float)))
(assert (ntype-subtypep ntype2 (type-specifier-ntype 'float)))
(macrolet ((body ()
`(ntype-subtypecase ntype1
,@(loop for fp1 in *float-primitive-ntypes*
collect
`(,(primitive-ntype-type-specifier fp1)
(ntype-subtypecase ntype2
,@(loop for fp2 in *float-primitive-ntypes*
collect
`(,(primitive-ntype-type-specifier fp2)
,(if (> (primitive-ntype-bits fp1)
(primitive-ntype-bits fp2))
fp1 fp2)))
(t (type-specifier-ntype 'float)))))
(t (type-specifier-ntype 'float)))))
(body)))
(defun complex-contagion (ntype1 ntype2)
(assert (ntype-subtypep ntype1 (type-specifier-ntype 'complex)))
(assert (ntype-subtypep ntype2 (type-specifier-ntype 'complex)))
(flet ((part-ntype (ntype)
(trivia:match (ntype-type-specifier ntype)
((or 'complex (list 'complex))
(values (universal-ntype) t))
((list 'complex type-specifier)
(type-specifier-ntype type-specifier)))))
(values
(type-specifier-ntype
`(complex
,(ntype-type-specifier
(ntype-contagion/slow
(part-ntype ntype1)
(part-ntype ntype2))))))))
(let ((cache (make-array (list +primitive-ntype-limit+ +primitive-ntype-limit+)
:element-type 'ntype
:initial-element (universal-ntype))))
(loop for p1 across *primitive-ntypes* do
(loop for p2 across *primitive-ntypes* do
(setf (aref cache (ntype-index p1) (ntype-index p2))
(ntype-contagion/slow p1 p2))))
(defun primitive-ntype-contagion (p1 p2)
(declare (primitive-ntype p1 p2))
(aref cache (ntype-index p1) (ntype-index p2))))
|
7f9a30c8a1175a7fc65e427f05aee174d6aa5862cf88cc489aa6971ff150b319 | Factual/riffle | project.clj | (defproject factual/riffle-hadoop "0.1.0"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0-alpha3"]
[byte-transforms "0.1.3"]
[byte-streams "0.2.0-alpha4"]
[org.clojure/tools.cli "0.3.1"]
[factual/riffle "0.1.2"]
[org.clojure/tools.logging "0.3.1"]]
:profiles {:provided {:dependencies [[org.apache.hadoop/hadoop-client "2.2.0"]]}
:uberjar {:aot [riffle.hadoop.cli]}}
:main riffle.hadoop.cli
:java-source-paths ["src"]
:javac-options ["-target" "1.6" "-source" "1.6"])
| null | https://raw.githubusercontent.com/Factual/riffle/f102db1a96dd2de212d555154a231b76016c632a/riffle-hadoop/project.clj | clojure | (defproject factual/riffle-hadoop "0.1.0"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0-alpha3"]
[byte-transforms "0.1.3"]
[byte-streams "0.2.0-alpha4"]
[org.clojure/tools.cli "0.3.1"]
[factual/riffle "0.1.2"]
[org.clojure/tools.logging "0.3.1"]]
:profiles {:provided {:dependencies [[org.apache.hadoop/hadoop-client "2.2.0"]]}
:uberjar {:aot [riffle.hadoop.cli]}}
:main riffle.hadoop.cli
:java-source-paths ["src"]
:javac-options ["-target" "1.6" "-source" "1.6"])
| |
db63c79502cf4dd69ae6f1f241ff67fbee5364e1f5f1abed7b87b16295aa034f | herd/herdtools7 | AllBarrier.mli | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2010 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
* Union of relevant PPC , ARM , x86 barriers . Used by CAV12 model
type b =
| SYNC | LWSYNC | ISYNC | EIEIO (* PPC memory model barrier *)
| DSB | DMB | ISB (* ARM barrier *)
| DSBST | DMBST
| MFENCE | SFENCE | LFENCE (* X86 *)
module type S =
sig
Native arch barrier
val a_to_b : a -> b
val pp_isync : string
end
module No : functor(B:sig type a end) -> S with type a = B.a
| null | https://raw.githubusercontent.com/herd/herdtools7/c3b5079aed4bf9d92a5c7de04ef3638d6af0f8c0/herd/AllBarrier.mli | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
PPC memory model barrier
ARM barrier
X86 | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2010 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
* Union of relevant PPC , ARM , x86 barriers . Used by CAV12 model
type b =
| DSBST | DMBST
module type S =
sig
Native arch barrier
val a_to_b : a -> b
val pp_isync : string
end
module No : functor(B:sig type a end) -> S with type a = B.a
|
ef1c865cd5ee5662d6d06d4b4914c52c95f6bc0aa14e32a8f09d13d5fa7e122b | Bogdanp/racket-gui-easy | container.rkt | #lang racket/base
(require racket/class)
(provide
container%)
(define container%
(class object%
(init-field children)
(super-new)
(define deps-to-children (make-hash))
(for* ([c (in-list children)]
[d (in-list (send c dependencies))])
(hash-update! deps-to-children d (λ (cs) (cons c cs)) null))
(define/public (child-dependencies)
(hash-keys deps-to-children))
(define/public (update-children v what val)
(for ([c (in-list (hash-ref deps-to-children what null))])
(send c update (get-child v c) what val)))
(define/public (destroy-children v)
(for ([(c w) (in-hash (get-children-to-widgets v))])
(send c destroy w)
(remove-child v c))
(hash-clear! deps-to-children)
(hash-clear! (get-children-to-widgets v)))
(define/public (add-child v c w)
(hash-set! (get-children-to-widgets v) c w))
(define/public (get-child v c [default (lambda () (error 'get-child "child not found: ~e" c))])
(hash-ref (get-children-to-widgets v) c default))
(define/public (has-child? v c)
(hash-has-key? (get-children-to-widgets v) c))
(define/public (remove-child v c)
(hash-remove! (get-children-to-widgets v) c))
(define/private (get-children-to-widgets v)
(send v get-context! 'children-to-widgets make-hasheq))))
| null | https://raw.githubusercontent.com/Bogdanp/racket-gui-easy/5095d2fd921f025846620c2c1ae0722dc8cd7425/gui-easy-lib/gui/easy/private/view/container.rkt | racket | #lang racket/base
(require racket/class)
(provide
container%)
(define container%
(class object%
(init-field children)
(super-new)
(define deps-to-children (make-hash))
(for* ([c (in-list children)]
[d (in-list (send c dependencies))])
(hash-update! deps-to-children d (λ (cs) (cons c cs)) null))
(define/public (child-dependencies)
(hash-keys deps-to-children))
(define/public (update-children v what val)
(for ([c (in-list (hash-ref deps-to-children what null))])
(send c update (get-child v c) what val)))
(define/public (destroy-children v)
(for ([(c w) (in-hash (get-children-to-widgets v))])
(send c destroy w)
(remove-child v c))
(hash-clear! deps-to-children)
(hash-clear! (get-children-to-widgets v)))
(define/public (add-child v c w)
(hash-set! (get-children-to-widgets v) c w))
(define/public (get-child v c [default (lambda () (error 'get-child "child not found: ~e" c))])
(hash-ref (get-children-to-widgets v) c default))
(define/public (has-child? v c)
(hash-has-key? (get-children-to-widgets v) c))
(define/public (remove-child v c)
(hash-remove! (get-children-to-widgets v) c))
(define/private (get-children-to-widgets v)
(send v get-context! 'children-to-widgets make-hasheq))))
| |
4a93a3453baf618e1764ad4b1130fa097df9c667609fdeec2071693110e2cb4f | helins/kafka.clj | builder.clj | (ns dvlopt.kstreams.builder
"Kafka Streams high level API, rather functional.
Overview
========
This API revolves mainly around these abstractions :
Streams (`dvlopt.kstreams.stream`)
----------------------------------------
A stream represent a sequence of records which need to be somehow transformed (mapped, filtered, etc). It is distributed by partitions.
Often, some kind of aggregated values need to be computed. Fist, values must be grouped by key to form a grouped stream. It is as if the stream is
being divided into substreams, one for every key. Although useful, such a grouped stream does not have a notion of time. Hence, before applying any
aggregation, a grouped stream can be windowed if needed. For instance, if keys are user names and values are clicks, we can group the stream by key,
window per day, and then aggregate the values by counting the clicks. This would be for computing the number of clicks per user, per day.
Grouped streams, windowed or not, are intermediary representations. Aggregating values always result in a table.
Tables (`dvlopt.kstreams.table`)
--------------------------------------
A table associates a unique value to a key. For a given key, a new record represents an update. It can be created right away from a topic or be the
result of an aggregation. It is backed-up by a key-value state store. Such a table is distributed by partitions. Hence, in order to be able to query
alls keys, if needed, the application instances must be able to query each other. Typically, tables follow delete semantics (ie. a nil value for a
key removes this key from the table).
Akin to streams, tables can be re-grouped by another key. For instance, a table of users (keys) might be re-grouped into a table of countries (new keys,
each user belongs to a country). Each country now has a list of values (the values of all the user belonging to that country) and those can be aggregated
as well. The end result is naturally a new table.
Global tables
-------------
A regular table is distributed by partitions. A global one sources its data from all the partitions of a topic at the same time. It is fine and useful
as long as the data do not overwhelm a single instance of the Kafka Streams application.
Aggregating
===========
Values can be reduced by key. An aggregation is done much like in clojure itself : a reducing (fn [aggregated key value). Before processing the first record
of a key, a function is called for obtaining a seed (ie. first aggregated value). The value is aggregated against the seed, thus bootstrapping the
aggregation.
State and repartioning
======================
Just like in the low-level API, state stores are used for stateful operations. Those stores are typically created automatically and need not much more
else than serializers and deserializers as described in `dvlopt.kafka`.
Cf. `dvlopt.kstreams.store` for more about stores.
Any operation acting on the keys of the records typically result in a repartioning of data at some point, either right away or later. This means the library
will persist the new records in an internal topic named '$APPLICATION_ID-$NAME-repartition'. This is needed because the way keys are partioned is very important
for a lot of stateful operations such as joins. Operations which might lead to repartioning document this behavior. $NAME is either generated or given by the
:dvlotp.kstreams/repartition-name option when documented.
Joins and Co-partitioning
=========================
This API offers different kind of joining operations akin to SQL joins. For instance, a stream might be enriched by joining it with a table. Joins are
always based on the keys of the records, hence the involved topics need to be co-partitioned. It means they must share the same number of partitions as
well as the same partitioning strategy (eg. the default one). By doing so, the library can source records from the same partition numbers, in both joined
topics, and be confident that each corresponding partition holds the same keys.
It is the responsability of the user to garantee the same number of partitions otherwise an exception will be thrown. For instance, if needed, a stream
can be redirected to an adequate pre-created topic. It is easiest to use the default partitioning strategy. Other than that, a producer might decide the
partition number of the records it is sending. In Kafka Streams, the partition number can be decided when writing to a topic by using the
:dvlopt.kstreams/select-partition option. It is a function taking the total number of partitions of the topic a record is being sent to, as well as the
key and the value of this record.
All of this do not apply to joins with global tables as they sources data from all the available partitions."
{:author "Adam Helinski"}
(:require [dvlopt.kafka :as K]
[dvlopt.kafka.-interop :as K.-interop]
[dvlopt.kafka.-interop.java :as K.-interop.java]
[dvlopt.void :as void])
(:import java.util.Collection
java.util.regex.Pattern
(org.apache.kafka.streams StreamsBuilder
Topology)
(org.apache.kafka.streams.kstream GlobalKTable
KStream
KTable)))
;;;;;;;;;; Public
(defn builder
"A builder is used as a starting point for the high-level functional API (ie. this namespace).
When ready, it can go through `dvlopt.kstreams.topology/topology` in order to build an actual topology which can be augmented with the imperative
low-level API or used right away for making a Kafka Streams application."
^StreamsBuilder
[]
(StreamsBuilder.))
(defn stream
"Adds and returns a stream sourcing its data from a topic, a list of topics or a regular expression for topics.
This stream can be used with the `dvlopt.kstreams.stream` namespace.
A map of options may be given :
:dvlopt.kafka/deserializer.key
:dvlopt.kafka/deserializer.value
Cf. `dvlopt.kafka` for description of deserializers.
:dvlopt.kstreams/extract-timestamp
Function accepting the previous timestamp of the last record and a record, and returning
the timestamp chosen for the current record.
:dvlopt.kstreams/offset-reset
When a topic is consumed at first, it should start from the :earliest offset or the :latest."
(^KStream
[builder source]
(stream builder
source
nil))
(^KStream
[^StreamsBuilder builder source options]
(let [consumed (K.-interop.java/consumed options)]
(cond
(string? source) (.stream builder
^String source
consumed)
(coll? source) (.stream builder
^Collection source
consumed)
(K.-interop/regex? source) (.stream builder
^Pattern source
consumed)))))
(defn table
"Adds and returns a table which can be used with the `dvlopt.kstreams.table` namespace.
A map of options may be given :
:dvlopt.kafka/deserializer.key
:dvlopt.kafka/deserializer.value
:dvlopt.kafka/serializer.key
:dvlopt.kafka/serializer.value
Cf. `dvlopt.kafka` for description of serializers and deserializers.
:dvlopt.kstreams/extract-timestamp
:dvlopt.kstreams/offset-reset
Cf. `stream`
:dvlopt.kstreams.store/cache?
:dvlopt.kstreams.store/name
:dvlopt.kstreams.store/type
Cf. `dvlopt.kstreams.store`
The type is restricted to #{:kv.in-memory :kv.regular}.
Other options related to stores are not needed. No changelog topic is required because the table is created
directly from an original topic."
(^KTable
[builder topic]
(table builder
topic
nil))
(^KTable
[^StreamsBuilder builder topic options]
(.table builder
topic
(K.-interop.java/consumed options)
(K.-interop.java/materialized--kv options))))
(defn add-global-table
"Adds a global table which, unlike a regular one, will source its data from all the partitions of a topic at the
same time.
Cf. `table`"
(^GlobalKTable
[builder source]
(add-global-table builder
source
nil))
(^GlobalKTable
[^StreamsBuilder builder source options]
(.globalTable builder
source
(K.-interop.java/consumed options)
(K.-interop.java/materialized--kv options))))
(defn add-store
"Manually adds a state store.
Typically, stores are created automatically. However, this high-level API also offers a few operations akin to what
can be find in the low-level API. Those probably need an access to a manually created state store.
A map of options may be given, all options described in `dvlopt.kstreams.store`."
(^StreamsBuilder
[builder]
(add-store builder
nil))
(^StreamsBuilder
[^StreamsBuilder builder options]
(.addStateStore builder
(K.-interop.java/store-builder options))))
(defn add-global-store
"Adds a global state store just like `dvlopt.kstreams.topology/add-global-store`."
^StreamsBuilder
[^StreamsBuilder builder source-topic processor options]
(.addGlobalStore builder
(K.-interop.java/store-builder options)
source-topic
(K.-interop.java/consumed options)
(K.-interop.java/processor-supplier processor)))
| null | https://raw.githubusercontent.com/helins/kafka.clj/ecf688f1a8700491c2cd65bcfb19a3781aa4f575/src/dvlopt/kstreams/builder.clj | clojure | Public | (ns dvlopt.kstreams.builder
"Kafka Streams high level API, rather functional.
Overview
========
This API revolves mainly around these abstractions :
Streams (`dvlopt.kstreams.stream`)
----------------------------------------
A stream represent a sequence of records which need to be somehow transformed (mapped, filtered, etc). It is distributed by partitions.
Often, some kind of aggregated values need to be computed. Fist, values must be grouped by key to form a grouped stream. It is as if the stream is
being divided into substreams, one for every key. Although useful, such a grouped stream does not have a notion of time. Hence, before applying any
aggregation, a grouped stream can be windowed if needed. For instance, if keys are user names and values are clicks, we can group the stream by key,
window per day, and then aggregate the values by counting the clicks. This would be for computing the number of clicks per user, per day.
Grouped streams, windowed or not, are intermediary representations. Aggregating values always result in a table.
Tables (`dvlopt.kstreams.table`)
--------------------------------------
A table associates a unique value to a key. For a given key, a new record represents an update. It can be created right away from a topic or be the
result of an aggregation. It is backed-up by a key-value state store. Such a table is distributed by partitions. Hence, in order to be able to query
alls keys, if needed, the application instances must be able to query each other. Typically, tables follow delete semantics (ie. a nil value for a
key removes this key from the table).
Akin to streams, tables can be re-grouped by another key. For instance, a table of users (keys) might be re-grouped into a table of countries (new keys,
each user belongs to a country). Each country now has a list of values (the values of all the user belonging to that country) and those can be aggregated
as well. The end result is naturally a new table.
Global tables
-------------
A regular table is distributed by partitions. A global one sources its data from all the partitions of a topic at the same time. It is fine and useful
as long as the data do not overwhelm a single instance of the Kafka Streams application.
Aggregating
===========
Values can be reduced by key. An aggregation is done much like in clojure itself : a reducing (fn [aggregated key value). Before processing the first record
of a key, a function is called for obtaining a seed (ie. first aggregated value). The value is aggregated against the seed, thus bootstrapping the
aggregation.
State and repartioning
======================
Just like in the low-level API, state stores are used for stateful operations. Those stores are typically created automatically and need not much more
else than serializers and deserializers as described in `dvlopt.kafka`.
Cf. `dvlopt.kstreams.store` for more about stores.
Any operation acting on the keys of the records typically result in a repartioning of data at some point, either right away or later. This means the library
will persist the new records in an internal topic named '$APPLICATION_ID-$NAME-repartition'. This is needed because the way keys are partioned is very important
for a lot of stateful operations such as joins. Operations which might lead to repartioning document this behavior. $NAME is either generated or given by the
:dvlotp.kstreams/repartition-name option when documented.
Joins and Co-partitioning
=========================
This API offers different kind of joining operations akin to SQL joins. For instance, a stream might be enriched by joining it with a table. Joins are
always based on the keys of the records, hence the involved topics need to be co-partitioned. It means they must share the same number of partitions as
well as the same partitioning strategy (eg. the default one). By doing so, the library can source records from the same partition numbers, in both joined
topics, and be confident that each corresponding partition holds the same keys.
It is the responsability of the user to garantee the same number of partitions otherwise an exception will be thrown. For instance, if needed, a stream
can be redirected to an adequate pre-created topic. It is easiest to use the default partitioning strategy. Other than that, a producer might decide the
partition number of the records it is sending. In Kafka Streams, the partition number can be decided when writing to a topic by using the
:dvlopt.kstreams/select-partition option. It is a function taking the total number of partitions of the topic a record is being sent to, as well as the
key and the value of this record.
All of this do not apply to joins with global tables as they sources data from all the available partitions."
{:author "Adam Helinski"}
(:require [dvlopt.kafka :as K]
[dvlopt.kafka.-interop :as K.-interop]
[dvlopt.kafka.-interop.java :as K.-interop.java]
[dvlopt.void :as void])
(:import java.util.Collection
java.util.regex.Pattern
(org.apache.kafka.streams StreamsBuilder
Topology)
(org.apache.kafka.streams.kstream GlobalKTable
KStream
KTable)))
(defn builder
"A builder is used as a starting point for the high-level functional API (ie. this namespace).
When ready, it can go through `dvlopt.kstreams.topology/topology` in order to build an actual topology which can be augmented with the imperative
low-level API or used right away for making a Kafka Streams application."
^StreamsBuilder
[]
(StreamsBuilder.))
(defn stream
"Adds and returns a stream sourcing its data from a topic, a list of topics or a regular expression for topics.
This stream can be used with the `dvlopt.kstreams.stream` namespace.
A map of options may be given :
:dvlopt.kafka/deserializer.key
:dvlopt.kafka/deserializer.value
Cf. `dvlopt.kafka` for description of deserializers.
:dvlopt.kstreams/extract-timestamp
Function accepting the previous timestamp of the last record and a record, and returning
the timestamp chosen for the current record.
:dvlopt.kstreams/offset-reset
When a topic is consumed at first, it should start from the :earliest offset or the :latest."
(^KStream
[builder source]
(stream builder
source
nil))
(^KStream
[^StreamsBuilder builder source options]
(let [consumed (K.-interop.java/consumed options)]
(cond
(string? source) (.stream builder
^String source
consumed)
(coll? source) (.stream builder
^Collection source
consumed)
(K.-interop/regex? source) (.stream builder
^Pattern source
consumed)))))
(defn table
"Adds and returns a table which can be used with the `dvlopt.kstreams.table` namespace.
A map of options may be given :
:dvlopt.kafka/deserializer.key
:dvlopt.kafka/deserializer.value
:dvlopt.kafka/serializer.key
:dvlopt.kafka/serializer.value
Cf. `dvlopt.kafka` for description of serializers and deserializers.
:dvlopt.kstreams/extract-timestamp
:dvlopt.kstreams/offset-reset
Cf. `stream`
:dvlopt.kstreams.store/cache?
:dvlopt.kstreams.store/name
:dvlopt.kstreams.store/type
Cf. `dvlopt.kstreams.store`
The type is restricted to #{:kv.in-memory :kv.regular}.
Other options related to stores are not needed. No changelog topic is required because the table is created
directly from an original topic."
(^KTable
[builder topic]
(table builder
topic
nil))
(^KTable
[^StreamsBuilder builder topic options]
(.table builder
topic
(K.-interop.java/consumed options)
(K.-interop.java/materialized--kv options))))
(defn add-global-table
"Adds a global table which, unlike a regular one, will source its data from all the partitions of a topic at the
same time.
Cf. `table`"
(^GlobalKTable
[builder source]
(add-global-table builder
source
nil))
(^GlobalKTable
[^StreamsBuilder builder source options]
(.globalTable builder
source
(K.-interop.java/consumed options)
(K.-interop.java/materialized--kv options))))
(defn add-store
"Manually adds a state store.
Typically, stores are created automatically. However, this high-level API also offers a few operations akin to what
can be find in the low-level API. Those probably need an access to a manually created state store.
A map of options may be given, all options described in `dvlopt.kstreams.store`."
(^StreamsBuilder
[builder]
(add-store builder
nil))
(^StreamsBuilder
[^StreamsBuilder builder options]
(.addStateStore builder
(K.-interop.java/store-builder options))))
(defn add-global-store
"Adds a global state store just like `dvlopt.kstreams.topology/add-global-store`."
^StreamsBuilder
[^StreamsBuilder builder source-topic processor options]
(.addGlobalStore builder
(K.-interop.java/store-builder options)
source-topic
(K.-interop.java/consumed options)
(K.-interop.java/processor-supplier processor)))
|
e874c906cae317e2f2e63281b6d5a0e1d229d4837929fce57832ce650b072950 | lemmaandrew/CodingBatHaskell | zeroFront.hs | From
Return an array that contains the exact same numbers as the given array , but rearranged
so that all the zeros are grouped at the start of the array . The order of the non - zero
numbers does not matter . So { 1 , 0 , 0 , 1 } becomes { 0 , 0 , 1 , 1 } . You may modify and return
the given array or make a new array .
Return an array that contains the exact same numbers as the given array, but rearranged
so that all the zeros are grouped at the start of the array. The order of the non-zero
numbers does not matter. So {1, 0, 0, 1} becomes {0 ,0, 1, 1}. You may modify and return
the given array or make a new array.
-}
import Test.Hspec ( hspec, describe, it, shouldBe )
zeroFront :: [Int] -> [Int]
zeroFront nums = undefined
main :: IO ()
main = hspec $ describe "Tests:" $ do
it "[0,0,1,1]" $
zeroFront [1,0,0,1] `shouldBe` [0,0,1,1]
it "[0,0,1,1,1]" $
zeroFront [0,1,1,0,1] `shouldBe` [0,0,1,1,1]
it "[0,1]" $
zeroFront [1,0] `shouldBe` [0,1]
it "[0,1]" $
zeroFront [0,1] `shouldBe` [0,1]
it "[0,1,1,1]" $
zeroFront [1,1,1,0] `shouldBe` [0,1,1,1]
it "[2,2,2,2]" $
zeroFront [2,2,2,2] `shouldBe` [2,2,2,2]
it "[0,0,0,1]" $
zeroFront [0,0,1,0] `shouldBe` [0,0,0,1]
it "[0,0,0,(-1),(-1)]" $
zeroFront [(-1),0,0,(-1),0] `shouldBe` [0,0,0,(-1),(-1)]
it "[0,0,(-3),(-3)]" $
zeroFront [0,(-3),0,(-3)] `shouldBe` [0,0,(-3),(-3)]
it "[]" $
zeroFront [] `shouldBe` []
it "[0,0,9,9,9,9]" $
zeroFront [9,9,0,9,0,9] `shouldBe` [0,0,9,9,9,9]
| null | https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/Array-2/zeroFront.hs | haskell | From
Return an array that contains the exact same numbers as the given array , but rearranged
so that all the zeros are grouped at the start of the array . The order of the non - zero
numbers does not matter . So { 1 , 0 , 0 , 1 } becomes { 0 , 0 , 1 , 1 } . You may modify and return
the given array or make a new array .
Return an array that contains the exact same numbers as the given array, but rearranged
so that all the zeros are grouped at the start of the array. The order of the non-zero
numbers does not matter. So {1, 0, 0, 1} becomes {0 ,0, 1, 1}. You may modify and return
the given array or make a new array.
-}
import Test.Hspec ( hspec, describe, it, shouldBe )
zeroFront :: [Int] -> [Int]
zeroFront nums = undefined
main :: IO ()
main = hspec $ describe "Tests:" $ do
it "[0,0,1,1]" $
zeroFront [1,0,0,1] `shouldBe` [0,0,1,1]
it "[0,0,1,1,1]" $
zeroFront [0,1,1,0,1] `shouldBe` [0,0,1,1,1]
it "[0,1]" $
zeroFront [1,0] `shouldBe` [0,1]
it "[0,1]" $
zeroFront [0,1] `shouldBe` [0,1]
it "[0,1,1,1]" $
zeroFront [1,1,1,0] `shouldBe` [0,1,1,1]
it "[2,2,2,2]" $
zeroFront [2,2,2,2] `shouldBe` [2,2,2,2]
it "[0,0,0,1]" $
zeroFront [0,0,1,0] `shouldBe` [0,0,0,1]
it "[0,0,0,(-1),(-1)]" $
zeroFront [(-1),0,0,(-1),0] `shouldBe` [0,0,0,(-1),(-1)]
it "[0,0,(-3),(-3)]" $
zeroFront [0,(-3),0,(-3)] `shouldBe` [0,0,(-3),(-3)]
it "[]" $
zeroFront [] `shouldBe` []
it "[0,0,9,9,9,9]" $
zeroFront [9,9,0,9,0,9] `shouldBe` [0,0,9,9,9,9]
| |
27c5fd7618be100886bb149838abefd1d9612881a64555ff6fa17132e788d2c6 | LeventErkok/sbv | Bench.hs | -----------------------------------------------------------------------------
-- |
Module : . Bench . Bench
Copyright : ( c )
-- License : BSD3
-- Maintainer:
-- Stability : experimental
--
-- Assessing the overhead of calling solving examples via sbv vs individual solvers
-----------------------------------------------------------------------------
# OPTIONS_GHC -Wall -Werror -fno - warn - orphans #
{-# LANGUAGE CPP #-}
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
module BenchSuite.Bench.Bench
( run
, run'
, runWith
, runIOWith
, runIO
, runPure
, rGroup
, runBenchmark
, onConfig
, onDesc
, runner
, onProblem
, Runner(..)
, using
) where
import Control.DeepSeq (NFData (..), rwhnf)
import qualified Test.Tasty.Bench as B
import qualified Utils.SBVBenchFramework as U
-- | The type of the problem to benchmark. This allows us to operate on Runners
-- as values themselves yet still have a unified interface with gauge.
data Problem = forall a . U.Provable a => Problem a
| Similarly to Problem , BenchResult is boilerplate for a nice api
data BenchResult = forall a . (Show a, NFData a) => BenchResult a
-- | A runner is anything that allows the solver to solve, such as:
' Data . SBV.proveWith ' or ' Data . SBV.satWith ' . We utilize existential types to
-- lose type information and create a unified interface with gauge. We
-- require a runner in order to generate a 'Data.SBV.transcript' and then to run
-- the actual benchmark. We bundle this redundantly into a record so that the
-- benchmarks can be defined in each respective module, with the run function
that makes sense for that problem , and then redefined in ' SBVBench ' . This is
-- useful because problems that require 'Data.SBV.allSatWith' can lead to a lot
-- of variance in the benchmarking data. Single benchmark runners like
' Data . SBV.satWith ' and ' Data . SBV.proveWith ' work best .
data RunnerI = RunnerI { runI :: U.SMTConfig -> Problem -> IO BenchResult
, config :: U.SMTConfig
, description :: String
, problem :: Problem
}
-- | GADT to allow arbitrary nesting of runners. This copies criterion's design
-- so that we don't have to separate out runners that run a single benchmark
-- from runners that need to run several benchmarks
data Runner where
RBenchmark :: B.Benchmark -> Runner -- ^ a wrapper around tasty-bench benchmarks
Runner :: RunnerI -> Runner -- ^ a single run
RunnerGroup :: [Runner] -> Runner -- ^ a group of runs
-- | Convenience boilerplate functions, simply avoiding a lens dependency
using :: Runner -> (Runner -> Runner) -> Runner
using = flip ($)
# INLINE using #
-- | Set the runner function
runner :: (Show c, NFData c) =>
(forall a. U.Provable a => U.SMTConfig -> a -> IO c) -> Runner -> Runner
runner r' (Runner r@RunnerI{}) = Runner $ r{runI = toRun r'}
runner r' (RunnerGroup rs) = RunnerGroup $ runner r' <$> rs
runner _ x = x
# INLINE runner #
toRun :: (Show c, NFData c) =>
(forall a. U.Provable a => U.SMTConfig -> a -> IO c)
-> U.SMTConfig
-> Problem
-> IO BenchResult
toRun f c p = BenchResult <$> helper p
-- similar to helper in onProblem, this is lmap from profunctor land, i.e., we
-- curry with a config, then change the runner function from (a -> IO c), to
-- (Problem -> IO c)
where helper (Problem a) = f c a
# INLINE toRun #
onConfig :: (U.SMTConfig -> U.SMTConfig) -> RunnerI -> RunnerI
onConfig f r@RunnerI{..} = r{config = f config}
# INLINE onConfig #
onDesc :: (String -> String) -> RunnerI -> RunnerI
onDesc f r@RunnerI{..} = r{description = f description}
# INLINE onDesc #
onProblem :: (forall a. a -> a) -> RunnerI -> RunnerI
onProblem f r@RunnerI{..} = r{problem = helper problem}
where
-- helper function to avoid profunctor dependency, this is simply fmap, or
-- rmap for profunctor land
helper :: Problem -> Problem
helper (Problem p) = Problem $ f p
# INLINE onProblem #
-- | make a normal benchmark without the overhead comparison. Notice this is
just unpacking the Runner record
mkBenchmark :: RunnerI -> B.Benchmark
mkBenchmark RunnerI{..} = B.bench description . B.nfIO $! runI config problem
# INLINE mkBenchmark #
| Convert a Runner or a group of Runners to Benchmarks , this is an api level
-- function to convert the runners defined in each file to benchmarks which can
-- be run by gauge
runBenchmark :: Runner -> B.Benchmark
runBenchmark (Runner r@RunnerI{}) = mkBenchmark r
runBenchmark (RunnerGroup rs) = B.bgroup "" $ runBenchmark <$> rs
runBenchmark (RBenchmark b) = b
# INLINE runBenchmark #
| This is just a wrapper around the RunnerI constructor and serves as the main
-- entry point to make a runner for a user in case they need something custom.
run' :: (NFData b, Show b) =>
(forall a. U.Provable a => U.SMTConfig -> a -> IO b)
-> U.SMTConfig
-> String
-> Problem
-> Runner
run' r config description problem = Runner $ RunnerI{..}
where runI = toRun r
{-# INLINE run' #-}
-- | Convenience function for creating benchmarks that exposes a configuration
runWith :: U.Provable a => U.SMTConfig -> String -> a -> Runner
runWith c d p = run' U.satWith c d (Problem p)
# INLINE runWith #
-- | Main entry point for simple benchmarks. See 'mkRunner'' or 'mkRunnerWith'
-- for versions of this function that allows custom inputs. If you have some use
-- case that is not considered then you can simply overload the record fields.
run :: U.Provable a => String -> a -> Runner
run d p = runWith U.z3 d p `using` runner U.satWith
# INLINE run #
| Entry point for problems that return IO or to benchmark IO results
runIOWith :: NFData a => (a -> B.Benchmarkable) -> String -> a -> Runner
runIOWith f d = RBenchmark . B.bench d . f
# INLINE runIOWith #
| Benchmark an IO result of sbv , this could be codegen , return models , etc ..
See for a version which allows the consumer to select the
-- Benchmarkable injection function
runIO :: NFData a => String -> IO a -> Runner
runIO d = RBenchmark . B.bench d . B.nfIO -- . silence
# INLINE runIO #
-- | Benchmark an pure result
runPure :: NFData a => String -> (a -> b) -> a -> Runner
runPure d = (RBenchmark . B.bench d) .: B.whnf
where (.:) = (.).(.)
{-# INLINE runPure #-}
-- | create a runner group. Useful for benchmarks that need to run several
benchmarks . See ' BenchSuite . Puzzles . ' for an example .
rGroup :: [Runner] -> Runner
rGroup = RunnerGroup
# INLINE rGroup #
-- | Orphaned instances just for benchmarking
instance NFData U.AllSatResult where
rnf (U.AllSatResult a b c d results) =
rnf a `seq` rnf b `seq` rnf c `seq` rnf d `seq` rwhnf results
-- | Unwrap the existential type to make gauge happy
instance NFData BenchResult where rnf (BenchResult a) = rnf a
| null | https://raw.githubusercontent.com/LeventErkok/sbv/9cd3662cb6ae31a95b99570f91ae4639807dc1ab/SBVBenchSuite/BenchSuite/Bench/Bench.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD3
Maintainer:
Stability : experimental
Assessing the overhead of calling solving examples via sbv vs individual solvers
---------------------------------------------------------------------------
# LANGUAGE CPP #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
| The type of the problem to benchmark. This allows us to operate on Runners
as values themselves yet still have a unified interface with gauge.
| A runner is anything that allows the solver to solve, such as:
lose type information and create a unified interface with gauge. We
require a runner in order to generate a 'Data.SBV.transcript' and then to run
the actual benchmark. We bundle this redundantly into a record so that the
benchmarks can be defined in each respective module, with the run function
useful because problems that require 'Data.SBV.allSatWith' can lead to a lot
of variance in the benchmarking data. Single benchmark runners like
| GADT to allow arbitrary nesting of runners. This copies criterion's design
so that we don't have to separate out runners that run a single benchmark
from runners that need to run several benchmarks
^ a wrapper around tasty-bench benchmarks
^ a single run
^ a group of runs
| Convenience boilerplate functions, simply avoiding a lens dependency
| Set the runner function
similar to helper in onProblem, this is lmap from profunctor land, i.e., we
curry with a config, then change the runner function from (a -> IO c), to
(Problem -> IO c)
helper function to avoid profunctor dependency, this is simply fmap, or
rmap for profunctor land
| make a normal benchmark without the overhead comparison. Notice this is
function to convert the runners defined in each file to benchmarks which can
be run by gauge
entry point to make a runner for a user in case they need something custom.
# INLINE run' #
| Convenience function for creating benchmarks that exposes a configuration
| Main entry point for simple benchmarks. See 'mkRunner'' or 'mkRunnerWith'
for versions of this function that allows custom inputs. If you have some use
case that is not considered then you can simply overload the record fields.
Benchmarkable injection function
. silence
| Benchmark an pure result
# INLINE runPure #
| create a runner group. Useful for benchmarks that need to run several
| Orphaned instances just for benchmarking
| Unwrap the existential type to make gauge happy | Module : . Bench . Bench
Copyright : ( c )
# OPTIONS_GHC -Wall -Werror -fno - warn - orphans #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE RecordWildCards #
module BenchSuite.Bench.Bench
( run
, run'
, runWith
, runIOWith
, runIO
, runPure
, rGroup
, runBenchmark
, onConfig
, onDesc
, runner
, onProblem
, Runner(..)
, using
) where
import Control.DeepSeq (NFData (..), rwhnf)
import qualified Test.Tasty.Bench as B
import qualified Utils.SBVBenchFramework as U
data Problem = forall a . U.Provable a => Problem a
| Similarly to Problem , BenchResult is boilerplate for a nice api
data BenchResult = forall a . (Show a, NFData a) => BenchResult a
' Data . SBV.proveWith ' or ' Data . SBV.satWith ' . We utilize existential types to
that makes sense for that problem , and then redefined in ' SBVBench ' . This is
' Data . SBV.satWith ' and ' Data . SBV.proveWith ' work best .
data RunnerI = RunnerI { runI :: U.SMTConfig -> Problem -> IO BenchResult
, config :: U.SMTConfig
, description :: String
, problem :: Problem
}
data Runner where
using :: Runner -> (Runner -> Runner) -> Runner
using = flip ($)
# INLINE using #
runner :: (Show c, NFData c) =>
(forall a. U.Provable a => U.SMTConfig -> a -> IO c) -> Runner -> Runner
runner r' (Runner r@RunnerI{}) = Runner $ r{runI = toRun r'}
runner r' (RunnerGroup rs) = RunnerGroup $ runner r' <$> rs
runner _ x = x
# INLINE runner #
toRun :: (Show c, NFData c) =>
(forall a. U.Provable a => U.SMTConfig -> a -> IO c)
-> U.SMTConfig
-> Problem
-> IO BenchResult
toRun f c p = BenchResult <$> helper p
where helper (Problem a) = f c a
# INLINE toRun #
onConfig :: (U.SMTConfig -> U.SMTConfig) -> RunnerI -> RunnerI
onConfig f r@RunnerI{..} = r{config = f config}
# INLINE onConfig #
onDesc :: (String -> String) -> RunnerI -> RunnerI
onDesc f r@RunnerI{..} = r{description = f description}
# INLINE onDesc #
onProblem :: (forall a. a -> a) -> RunnerI -> RunnerI
onProblem f r@RunnerI{..} = r{problem = helper problem}
where
helper :: Problem -> Problem
helper (Problem p) = Problem $ f p
# INLINE onProblem #
just unpacking the Runner record
mkBenchmark :: RunnerI -> B.Benchmark
mkBenchmark RunnerI{..} = B.bench description . B.nfIO $! runI config problem
# INLINE mkBenchmark #
| Convert a Runner or a group of Runners to Benchmarks , this is an api level
runBenchmark :: Runner -> B.Benchmark
runBenchmark (Runner r@RunnerI{}) = mkBenchmark r
runBenchmark (RunnerGroup rs) = B.bgroup "" $ runBenchmark <$> rs
runBenchmark (RBenchmark b) = b
# INLINE runBenchmark #
| This is just a wrapper around the RunnerI constructor and serves as the main
run' :: (NFData b, Show b) =>
(forall a. U.Provable a => U.SMTConfig -> a -> IO b)
-> U.SMTConfig
-> String
-> Problem
-> Runner
run' r config description problem = Runner $ RunnerI{..}
where runI = toRun r
runWith :: U.Provable a => U.SMTConfig -> String -> a -> Runner
runWith c d p = run' U.satWith c d (Problem p)
# INLINE runWith #
run :: U.Provable a => String -> a -> Runner
run d p = runWith U.z3 d p `using` runner U.satWith
# INLINE run #
| Entry point for problems that return IO or to benchmark IO results
runIOWith :: NFData a => (a -> B.Benchmarkable) -> String -> a -> Runner
runIOWith f d = RBenchmark . B.bench d . f
# INLINE runIOWith #
| Benchmark an IO result of sbv , this could be codegen , return models , etc ..
See for a version which allows the consumer to select the
runIO :: NFData a => String -> IO a -> Runner
# INLINE runIO #
runPure :: NFData a => String -> (a -> b) -> a -> Runner
runPure d = (RBenchmark . B.bench d) .: B.whnf
where (.:) = (.).(.)
benchmarks . See ' BenchSuite . Puzzles . ' for an example .
rGroup :: [Runner] -> Runner
rGroup = RunnerGroup
# INLINE rGroup #
instance NFData U.AllSatResult where
rnf (U.AllSatResult a b c d results) =
rnf a `seq` rnf b `seq` rnf c `seq` rnf d `seq` rwhnf results
instance NFData BenchResult where rnf (BenchResult a) = rnf a
|
d657c70c1405d083c0edb101afa91fb1130563cbb1460e62b2c726c80c68d0e0 | janestreet/learn-ocaml-workshop | game.ml | open! Base
type t =
{ mutable snake : Snake.t
; mutable apple : Apple.t
; mutable game_state : Game_state.t
; height : int
; width : int
; amount_to_grow : int
}
[@@deriving sexp_of]
(* TODO: Implement [in_bounds]. *)
let in_bounds t { Position.row; col } =
col >= 0 && col < t.width && row >= 0 && row < t.height
;;
(* TODO: Implement [create].
Make sure that the game returned by [create] is in a valid state. In particular, we
should fail with the message "unable to create initial apple" if [Apple.create] is
unsuccessful, and "unable to create initial snake" if the initial snake is invalid
(i.e. goes off the board). *)
let create ~height ~width ~initial_snake_length ~amount_to_grow =
let snake = Snake.create ~length:initial_snake_length in
let apple = Apple.create ~height ~width ~invalid_locations:(Snake.locations snake) in
match apple with
| None -> failwith "unable to create initial apple"
| Some apple ->
let t = { snake; apple; game_state = In_progress; height; width; amount_to_grow } in
if List.exists (Snake.locations snake) ~f:(fun pos -> not (in_bounds t pos))
then failwith "unable to create initial snake"
else t
;;
let snake t = t.snake
let apple t = t.apple
let game_state t = t.game_state
(* TODO: Implement [set_direction]. *)
let set_direction t direction = t.snake <- Snake.set_direction t.snake direction
TODO : Implement [ step ] .
[ step ] should :
- move the snake forward one square
- check for collisions ( end the game with " Wall collision " or " Self collision " )
- if necessary :
-- consume apple
-- if apple can not be regenerated , win game ; otherwise , grow the snake
[step] should:
- move the snake forward one square
- check for collisions (end the game with "Wall collision" or "Self collision")
- if necessary:
-- consume apple
-- if apple cannot be regenerated, win game; otherwise, grow the snake *)
let maybe_consume_apple t head =
if not ([%compare.equal: Position.t] head (Apple.location t.apple))
then ()
else (
let snake = Snake.grow_over_next_steps t.snake t.amount_to_grow in
let apple =
Apple.create
~height:t.height
~width:t.width
~invalid_locations:(Snake.locations snake)
in
match apple with
| None -> t.game_state <- Win
| Some apple ->
t.snake <- snake;
t.apple <- apple)
;;
let step t =
match Snake.step t.snake with
| None -> t.game_state <- Game_over "Self collision"
| Some snake ->
t.snake <- snake;
let head = Snake.head_location snake in
if not (in_bounds t head)
then t.game_state <- Game_over "Wall collision"
else maybe_consume_apple t head
;;
module For_testing = struct
let create_apple_force_location_exn ~height ~width ~location =
let invalid_locations =
List.init height ~f:(fun row ->
List.init width ~f:(fun col -> { Position.row; col }))
|> List.concat
|> List.filter ~f:(fun pos -> not ([%compare.equal: Position.t] location pos))
in
match Apple.create ~height ~width ~invalid_locations with
| None -> failwith "[Apple.create] returned [None] when [Some _] was expected!"
| Some apple -> apple
;;
let create_apple_and_update_game_exn t ~apple_location =
let apple =
create_apple_force_location_exn
~height:t.height
~width:t.width
~location:apple_location
in
t.apple <- apple
;;
let create_game_with_apple_exn
~height
~width
~initial_snake_length
~amount_to_grow
~apple_location
=
let t = create ~height ~width ~initial_snake_length ~amount_to_grow in
create_apple_and_update_game_exn t ~apple_location;
t
;;
end
| null | https://raw.githubusercontent.com/janestreet/learn-ocaml-workshop/1ba9576b48b48a892644eb20c201c2c4aa643c32/solutions/snake/game.ml | ocaml | TODO: Implement [in_bounds].
TODO: Implement [create].
Make sure that the game returned by [create] is in a valid state. In particular, we
should fail with the message "unable to create initial apple" if [Apple.create] is
unsuccessful, and "unable to create initial snake" if the initial snake is invalid
(i.e. goes off the board).
TODO: Implement [set_direction]. | open! Base
type t =
{ mutable snake : Snake.t
; mutable apple : Apple.t
; mutable game_state : Game_state.t
; height : int
; width : int
; amount_to_grow : int
}
[@@deriving sexp_of]
let in_bounds t { Position.row; col } =
col >= 0 && col < t.width && row >= 0 && row < t.height
;;
let create ~height ~width ~initial_snake_length ~amount_to_grow =
let snake = Snake.create ~length:initial_snake_length in
let apple = Apple.create ~height ~width ~invalid_locations:(Snake.locations snake) in
match apple with
| None -> failwith "unable to create initial apple"
| Some apple ->
let t = { snake; apple; game_state = In_progress; height; width; amount_to_grow } in
if List.exists (Snake.locations snake) ~f:(fun pos -> not (in_bounds t pos))
then failwith "unable to create initial snake"
else t
;;
let snake t = t.snake
let apple t = t.apple
let game_state t = t.game_state
let set_direction t direction = t.snake <- Snake.set_direction t.snake direction
TODO : Implement [ step ] .
[ step ] should :
- move the snake forward one square
- check for collisions ( end the game with " Wall collision " or " Self collision " )
- if necessary :
-- consume apple
-- if apple can not be regenerated , win game ; otherwise , grow the snake
[step] should:
- move the snake forward one square
- check for collisions (end the game with "Wall collision" or "Self collision")
- if necessary:
-- consume apple
-- if apple cannot be regenerated, win game; otherwise, grow the snake *)
let maybe_consume_apple t head =
if not ([%compare.equal: Position.t] head (Apple.location t.apple))
then ()
else (
let snake = Snake.grow_over_next_steps t.snake t.amount_to_grow in
let apple =
Apple.create
~height:t.height
~width:t.width
~invalid_locations:(Snake.locations snake)
in
match apple with
| None -> t.game_state <- Win
| Some apple ->
t.snake <- snake;
t.apple <- apple)
;;
let step t =
match Snake.step t.snake with
| None -> t.game_state <- Game_over "Self collision"
| Some snake ->
t.snake <- snake;
let head = Snake.head_location snake in
if not (in_bounds t head)
then t.game_state <- Game_over "Wall collision"
else maybe_consume_apple t head
;;
module For_testing = struct
let create_apple_force_location_exn ~height ~width ~location =
let invalid_locations =
List.init height ~f:(fun row ->
List.init width ~f:(fun col -> { Position.row; col }))
|> List.concat
|> List.filter ~f:(fun pos -> not ([%compare.equal: Position.t] location pos))
in
match Apple.create ~height ~width ~invalid_locations with
| None -> failwith "[Apple.create] returned [None] when [Some _] was expected!"
| Some apple -> apple
;;
let create_apple_and_update_game_exn t ~apple_location =
let apple =
create_apple_force_location_exn
~height:t.height
~width:t.width
~location:apple_location
in
t.apple <- apple
;;
let create_game_with_apple_exn
~height
~width
~initial_snake_length
~amount_to_grow
~apple_location
=
let t = create ~height ~width ~initial_snake_length ~amount_to_grow in
create_apple_and_update_game_exn t ~apple_location;
t
;;
end
|
b033e812bd26c0a3bd7a56fd7b9601709db3c4b5f8017dcb6e9a9dd0de1748d4 | ndaniels/MRFy | PrefixMemo.hs | # LANGUAGE ScopedTypeVariables #
module PrefixMemo
( isoLawOfIndex
, listPrefixIso
, quickCheck
, goodLengthLaw
)
( isoLawOfIndex
, listPrefixIso
, quickCheck
, goodLengthLaw
)
-}
where
import Data.Array.IArray
import Data.List
import Data.MemoCombinators
import Test.QuickCheck
newtype N = N Int
deriving (Eq, Ord, Ix, Show)
prefixLengths :: [N]
prefixLengths = map N [1..]
data Numbered a = Numbered { the_number :: N, unNumbered :: a }
deriving (Show, Eq)
data Iso a b = Iso (a -> b) (b -> a)
insist :: Bool -> a -> a
insist True a = a
insist False _ = error "assertion failed"
numberByPrefix :: [a] -> [Numbered a]
numberByPrefix = reverse . zipWith Numbered prefixLengths . reverse
goodLengthLaw :: [a] -> Bool
goodLengthLaw as = goodLengths prefixes
where numbered = numberByPrefix as
prefixes = reverse $ tails numbered
i_of_prefix [] = N 0
i_of_prefix (Numbered n a : _) = n
goodLengths = all (\as -> i_of_prefix as == N (length as))
listPrefixIso :: forall a . [a] -> ([Numbered a], Iso [Numbered a] N)
-- prefix of length N is isomorphic to that number
listPrefixIso as = insist (goodLengths prefixes) $
( zipWith Numbered (map N [length as..1]) as
, Iso i_of_prefix prefix_of_i
)
where numbered = numberByPrefix as
prefixes = reverse $ tails numbered
memotable :: Array N [Numbered a]
memotable = listArray (N 0, N (length as)) prefixes
prefix_of_i i = memotable ! i
i_of_prefix [] = N 0
i_of_prefix (Numbered n a : _) = n
goodLengths = all (\as -> i_of_prefix as == N (length as))
isoLawOfIndex :: Eq a => [a] -> Bool
isoLawOfIndex as = all good [0..length as]
where good i = (i_of_list . list_of_i) (N i) == (N i)
(_, Iso i_of_list list_of_i) = listPrefixIso as
isoLawOfPrefix :: Eq a => [a] -> Bool
isoLawOfPrefix as = all good [0..length as]
where good i = (list_of_i . i_of_list) (drop i numbered) == drop i numbered
(_, Iso i_of_list list_of_i) = listPrefixIso as
numbered = numberByPrefix as
prefixMemo :: [Numbered a] -> ( [Numbered a]
, ([Numbered a] -> b) -> ([Numbered a] -> b)
)
prefixMemo nas = (nas', wrap list_of_i i_of_list (arrayRange (N 0, N (length nas))))
where (nas', Iso i_of_list list_of_i) = listPrefixIso $ map unNumbered nas
| null | https://raw.githubusercontent.com/ndaniels/MRFy/9b522d991a9bf98a6690f791dc92ad6fe675115c/PrefixMemo.hs | haskell | prefix of length N is isomorphic to that number | # LANGUAGE ScopedTypeVariables #
module PrefixMemo
( isoLawOfIndex
, listPrefixIso
, quickCheck
, goodLengthLaw
)
( isoLawOfIndex
, listPrefixIso
, quickCheck
, goodLengthLaw
)
-}
where
import Data.Array.IArray
import Data.List
import Data.MemoCombinators
import Test.QuickCheck
newtype N = N Int
deriving (Eq, Ord, Ix, Show)
prefixLengths :: [N]
prefixLengths = map N [1..]
data Numbered a = Numbered { the_number :: N, unNumbered :: a }
deriving (Show, Eq)
data Iso a b = Iso (a -> b) (b -> a)
insist :: Bool -> a -> a
insist True a = a
insist False _ = error "assertion failed"
numberByPrefix :: [a] -> [Numbered a]
numberByPrefix = reverse . zipWith Numbered prefixLengths . reverse
goodLengthLaw :: [a] -> Bool
goodLengthLaw as = goodLengths prefixes
where numbered = numberByPrefix as
prefixes = reverse $ tails numbered
i_of_prefix [] = N 0
i_of_prefix (Numbered n a : _) = n
goodLengths = all (\as -> i_of_prefix as == N (length as))
listPrefixIso :: forall a . [a] -> ([Numbered a], Iso [Numbered a] N)
listPrefixIso as = insist (goodLengths prefixes) $
( zipWith Numbered (map N [length as..1]) as
, Iso i_of_prefix prefix_of_i
)
where numbered = numberByPrefix as
prefixes = reverse $ tails numbered
memotable :: Array N [Numbered a]
memotable = listArray (N 0, N (length as)) prefixes
prefix_of_i i = memotable ! i
i_of_prefix [] = N 0
i_of_prefix (Numbered n a : _) = n
goodLengths = all (\as -> i_of_prefix as == N (length as))
isoLawOfIndex :: Eq a => [a] -> Bool
isoLawOfIndex as = all good [0..length as]
where good i = (i_of_list . list_of_i) (N i) == (N i)
(_, Iso i_of_list list_of_i) = listPrefixIso as
isoLawOfPrefix :: Eq a => [a] -> Bool
isoLawOfPrefix as = all good [0..length as]
where good i = (list_of_i . i_of_list) (drop i numbered) == drop i numbered
(_, Iso i_of_list list_of_i) = listPrefixIso as
numbered = numberByPrefix as
prefixMemo :: [Numbered a] -> ( [Numbered a]
, ([Numbered a] -> b) -> ([Numbered a] -> b)
)
prefixMemo nas = (nas', wrap list_of_i i_of_list (arrayRange (N 0, N (length nas))))
where (nas', Iso i_of_list list_of_i) = listPrefixIso $ map unNumbered nas
|
6b51c0d6cc816ade82ed12a8068670fb5ddcf6cb6f93695d764c51aa458b6f8e | softlab-ntua/bencherl | hashtable_test.erl | Copyright ( C ) 2003 - 2014
%
This file is part of the Ceylan Erlang library .
%
% This library is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License or
the GNU General Public License , as they are published by the Free Software
Foundation , either version 3 of these Licenses , or ( at your option )
% any later version.
% You can also redistribute it and/or modify it under the terms of the
Mozilla Public License , version 1.1 or later .
%
% This library is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License and the GNU General Public License
% for more details.
%
You should have received a copy of the GNU Lesser General Public
License , of the GNU General Public License and of the Mozilla Public License
% along with this library.
% If not, see </> and
% </>.
%
Author : ( )
% Unit tests for the generic hashtable implementation.
%
% See the hashtable.erl tested module.
%
-module(hashtable_test).
% Directly depends on the hashtable module.
% For run/0 export and al:
-include("test_facilities.hrl").
-define(MyFirstKey, 'MyFirstKey' ).
-define(MySecondKey, 'MySecondKey').
-define(MyThirdKey, 'MyThirdKey' ).
-spec run() -> no_return().
run() ->
test_facilities:start( ?MODULE ),
MyH1 = hashtable:new( 10 ),
true = hashtable:isEmpty( MyH1 ),
hashtable:display( "Vanilla table", MyH1 ),
MyH1Optimised = hashtable:optimise( MyH1 ),
hashtable:display( "Optimised table", MyH1Optimised ),
hashtable:display( MyH1 ),
MyH2 = hashtable:new( 4 ),
MyH3 = hashtable:addEntry( ?MyFirstKey, "MyFirstValue", MyH2 ),
false = hashtable:isEmpty( MyH3 ),
MyH4 = hashtable:addEntry( ?MySecondKey, [ 1, 2, 3 ], MyH3 ),
false = hashtable:isEmpty( MyH4 ),
hashtable:display( MyH4 ),
MyH4Size = hashtable:size( MyH4 ),
test_facilities:display( "Size of table '~s': ~B entries",
[ hashtable:toString( MyH4 ), MyH4Size ] ),
test_facilities:display( "Looking up for ~s: ~p", [ ?MyFirstKey,
hashtable:lookupEntry( ?MyFirstKey, MyH4 ) ] ),
{ value, "MyFirstValue" } = hashtable:lookupEntry( ?MyFirstKey, MyH4 ),
test_facilities:display( "Removing that entry." ),
MyH5 = hashtable:removeEntry( ?MyFirstKey, MyH4 ),
false = hashtable:isEmpty( MyH5 ),
test_facilities:display( "Extracting the same entry from "
"the same initial table." ),
{ "MyFirstValue", MyH5 } = hashtable:extractEntry( ?MyFirstKey, MyH4 ),
test_facilities:display( "Looking up for ~s: ~p", [ ?MyFirstKey,
hashtable:lookupEntry( ?MyFirstKey, MyH5 ) ] ),
hashtable_key_not_found = hashtable:lookupEntry( ?MyFirstKey, MyH5 ),
% removeEntry can also be used if the specified key is not here, will return
% an identical table.
hashtable:display( MyH5 ),
test_facilities:display( "Testing double key registering." ),
MyH6 = hashtable:addEntry( ?MySecondKey, anything, MyH5 ),
hashtable:display( MyH6 ),
test_facilities:display( "Enumerating the hashtable: ~p",
[ hashtable:enumerate( MyH4 ) ] ),
test_facilities:display( "Listing the hashtable keys: ~p",
[ hashtable:keys( MyH4 ) ] ),
test_facilities:display( "Listing the hashtable values: ~p",
[ hashtable:values( MyH4 ) ] ),
test_facilities:display( "Applying a fun to all values of "
"previous hashtable:" ),
FunValue = fun( V ) ->
io:format( " - hello value '~p'!~n", [ V ] ),
% Unchanged here:
V
end,
hashtable:mapOnValues( FunValue, MyH4 ),
test_facilities:display( "Applying a fun to all entries of "
"previous hashtable:" ),
FunEntry = fun( E={ K, V } ) ->
io:format( " - hello, key '~p' associated to value '~p'!~n",
[ K, V ] ),
% Unchanged here:
E
end,
hashtable:mapOnEntries( FunEntry, MyH4 ),
test_facilities:display( "Folding on the same initial hashtable to "
"count the number of entries." ),
FunCount = fun( _Entry, AccCount ) ->
AccCount + 1
end,
2 = hashtable:foldOnEntries( FunCount, _InitialCount=0, MyH4 ),
0 = hashtable:foldOnEntries( FunCount, _InitialCount=0, MyH1 ),
true = list_utils:unordered_compare( [ ?MyFirstKey, ?MySecondKey ],
hashtable:keys( MyH4 ) ),
MyH7 = hashtable:addEntry( ?MyThirdKey, 3, MyH6 ),
MyH8 should have { MySecondKey , [ 1,2,3 ] } and { ? , 3 } :
MyH8 = hashtable:merge( MyH4, MyH7 ),
test_facilities:display( "Merged table: ~s",
[ hashtable:toString( MyH8 ) ] ),
MyH9 = hashtable:optimise( MyH8 ),
hashtable:display( "Optimised merged table", MyH9 ),
Keys = [ ?MyFirstKey, ?MyThirdKey ],
test_facilities:display( "Listing the entries for keys ~p:~n ~p",
[ Keys, hashtable:selectEntries( Keys, MyH9 ) ] ),
test_facilities:stop().
| null | https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/sim-diasca/common/src/data-management/hashtable_test.erl | erlang |
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License or
any later version.
You can also redistribute it and/or modify it under the terms of the
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
for more details.
along with this library.
If not, see </> and
</>.
Unit tests for the generic hashtable implementation.
See the hashtable.erl tested module.
Directly depends on the hashtable module.
For run/0 export and al:
removeEntry can also be used if the specified key is not here, will return
an identical table.
Unchanged here:
Unchanged here: | Copyright ( C ) 2003 - 2014
This file is part of the Ceylan Erlang library .
the GNU General Public License , as they are published by the Free Software
Foundation , either version 3 of these Licenses , or ( at your option )
Mozilla Public License , version 1.1 or later .
GNU Lesser General Public License and the GNU General Public License
You should have received a copy of the GNU Lesser General Public
License , of the GNU General Public License and of the Mozilla Public License
Author : ( )
-module(hashtable_test).
-include("test_facilities.hrl").
-define(MyFirstKey, 'MyFirstKey' ).
-define(MySecondKey, 'MySecondKey').
-define(MyThirdKey, 'MyThirdKey' ).
-spec run() -> no_return().
run() ->
test_facilities:start( ?MODULE ),
MyH1 = hashtable:new( 10 ),
true = hashtable:isEmpty( MyH1 ),
hashtable:display( "Vanilla table", MyH1 ),
MyH1Optimised = hashtable:optimise( MyH1 ),
hashtable:display( "Optimised table", MyH1Optimised ),
hashtable:display( MyH1 ),
MyH2 = hashtable:new( 4 ),
MyH3 = hashtable:addEntry( ?MyFirstKey, "MyFirstValue", MyH2 ),
false = hashtable:isEmpty( MyH3 ),
MyH4 = hashtable:addEntry( ?MySecondKey, [ 1, 2, 3 ], MyH3 ),
false = hashtable:isEmpty( MyH4 ),
hashtable:display( MyH4 ),
MyH4Size = hashtable:size( MyH4 ),
test_facilities:display( "Size of table '~s': ~B entries",
[ hashtable:toString( MyH4 ), MyH4Size ] ),
test_facilities:display( "Looking up for ~s: ~p", [ ?MyFirstKey,
hashtable:lookupEntry( ?MyFirstKey, MyH4 ) ] ),
{ value, "MyFirstValue" } = hashtable:lookupEntry( ?MyFirstKey, MyH4 ),
test_facilities:display( "Removing that entry." ),
MyH5 = hashtable:removeEntry( ?MyFirstKey, MyH4 ),
false = hashtable:isEmpty( MyH5 ),
test_facilities:display( "Extracting the same entry from "
"the same initial table." ),
{ "MyFirstValue", MyH5 } = hashtable:extractEntry( ?MyFirstKey, MyH4 ),
test_facilities:display( "Looking up for ~s: ~p", [ ?MyFirstKey,
hashtable:lookupEntry( ?MyFirstKey, MyH5 ) ] ),
hashtable_key_not_found = hashtable:lookupEntry( ?MyFirstKey, MyH5 ),
hashtable:display( MyH5 ),
test_facilities:display( "Testing double key registering." ),
MyH6 = hashtable:addEntry( ?MySecondKey, anything, MyH5 ),
hashtable:display( MyH6 ),
test_facilities:display( "Enumerating the hashtable: ~p",
[ hashtable:enumerate( MyH4 ) ] ),
test_facilities:display( "Listing the hashtable keys: ~p",
[ hashtable:keys( MyH4 ) ] ),
test_facilities:display( "Listing the hashtable values: ~p",
[ hashtable:values( MyH4 ) ] ),
test_facilities:display( "Applying a fun to all values of "
"previous hashtable:" ),
FunValue = fun( V ) ->
io:format( " - hello value '~p'!~n", [ V ] ),
V
end,
hashtable:mapOnValues( FunValue, MyH4 ),
test_facilities:display( "Applying a fun to all entries of "
"previous hashtable:" ),
FunEntry = fun( E={ K, V } ) ->
io:format( " - hello, key '~p' associated to value '~p'!~n",
[ K, V ] ),
E
end,
hashtable:mapOnEntries( FunEntry, MyH4 ),
test_facilities:display( "Folding on the same initial hashtable to "
"count the number of entries." ),
FunCount = fun( _Entry, AccCount ) ->
AccCount + 1
end,
2 = hashtable:foldOnEntries( FunCount, _InitialCount=0, MyH4 ),
0 = hashtable:foldOnEntries( FunCount, _InitialCount=0, MyH1 ),
true = list_utils:unordered_compare( [ ?MyFirstKey, ?MySecondKey ],
hashtable:keys( MyH4 ) ),
MyH7 = hashtable:addEntry( ?MyThirdKey, 3, MyH6 ),
MyH8 should have { MySecondKey , [ 1,2,3 ] } and { ? , 3 } :
MyH8 = hashtable:merge( MyH4, MyH7 ),
test_facilities:display( "Merged table: ~s",
[ hashtable:toString( MyH8 ) ] ),
MyH9 = hashtable:optimise( MyH8 ),
hashtable:display( "Optimised merged table", MyH9 ),
Keys = [ ?MyFirstKey, ?MyThirdKey ],
test_facilities:display( "Listing the entries for keys ~p:~n ~p",
[ Keys, hashtable:selectEntries( Keys, MyH9 ) ] ),
test_facilities:stop().
|
4fac44ee3a90ec68c5253a3ddd79b8a52250a325db71b80fb4cd4adb8a94777a | GregoryTravis/rhythmr | Rc.hs | # LANGUAGE DeriveGeneric #
module Rc (rc, Rc(..)) where
import Data.Aeson
import Data.ByteString.Lazy.UTF8 as BLU (fromString)
import Data.Maybe
import GHC.Generics
import System.Directory (doesFileExist)
import System.IO
import System.IO.Unsafe (unsafePerformIO)
rcFile = ".rhythmrc"
data Rc = Rc { cacheDownloads :: Bool } deriving (Generic, Show)
defaultRc :: Rc
defaultRc = Rc { cacheDownloads = False }
instance FromJSON Rc
readRc :: IO Rc
readRc = do
b <- doesFileExist rcFile
if b then do rcString <- BLU.fromString <$> readFile rcFile
return $ fromJust $ decode rcString
else return defaultRc
rc = unsafePerformIO readRc
| null | https://raw.githubusercontent.com/GregoryTravis/rhythmr/55fd5b5af6a52da16b7d730c27fb408aa3c61538/src/Rc.hs | haskell | # LANGUAGE DeriveGeneric #
module Rc (rc, Rc(..)) where
import Data.Aeson
import Data.ByteString.Lazy.UTF8 as BLU (fromString)
import Data.Maybe
import GHC.Generics
import System.Directory (doesFileExist)
import System.IO
import System.IO.Unsafe (unsafePerformIO)
rcFile = ".rhythmrc"
data Rc = Rc { cacheDownloads :: Bool } deriving (Generic, Show)
defaultRc :: Rc
defaultRc = Rc { cacheDownloads = False }
instance FromJSON Rc
readRc :: IO Rc
readRc = do
b <- doesFileExist rcFile
if b then do rcString <- BLU.fromString <$> readFile rcFile
return $ fromJust $ decode rcString
else return defaultRc
rc = unsafePerformIO readRc
| |
a7c660b39ea6c43d6353f4fde836380aeb7bb5f21b64ecb1faa3102c78a741ce | jordanthayer/ocaml-search | vector_aseps.ml | * Sorts the focal list based on an estimate of true cost to go , found by
multiplying a weight vector over a set of features available at the given
node . Vector is typically gotten through offline regression . Search is
carried out in an A * epsilon like manner .
multiplying a weight vector over a set of features available at the given
node. Vector is typically gotten through offline regression. Search is
carried out in an A* epsilon like manner.
*)
open Vector_search
open Clamped_vector_search
let make_close_enough wt =
* Close enough predicate required by Geq.ml
(fun a b ->
(wt *. a.f) >= b.f)
let ordered_2 a b =
(** Ordering predicate based on node cost *)
a.cost < b.cost
(*************************************************************************)
let no_dups sface args =
(** Performs a search in domains where there are no duplicates.
[sface] is the domain's search interface
[vector] is a list of weights to be used *)
let bound = Search_args.get_float "Vector_aseps.no_dups" args 0
and vector = Search_args.get_float_array "Vector_aseps.no_dups"
(Array.sub args 1 ((Array.length args) - 1)) in
let search_interface = Search_interface.make
~node_expand:(wrap_expand sface.Search_interface.domain_expand
sface.Search_interface.hd
sface.Search_interface.rev_hd vector bound)
~goal_p:(wrap sface.Search_interface.goal_p)
~halt_on:sface.Search_interface.halt_on
~hash:sface.Search_interface.hash
~equals:sface.Search_interface.equals
sface.Search_interface.domain
(make_init sface.Search_interface.initial)
better_p
(Limit.make_default_logger (fun n -> n.f)
(wrap sface.Search_interface.get_sol_length))
in
Limit.unwrap_sol5 unwrap_sol
(Focal_search.search
search_interface
ordered_p
(make_close_enough bound)
ordered_2
better_p
setpos
getpos)
let dups sface args =
(** Performs a search in domains where there are no duplicates.
[sface] is the domain's search interface
[vector] is a list of weights to be used *)
let bound = Search_args.get_float "Vector_aseps.dups" args 0
and vector = Search_args.get_float_array "Vector_aseps.dups"
(Array.sub args 1 ((Array.length args) - 1)) in
let search_interface = Search_interface.make
~node_expand:(wrap_expand sface.Search_interface.domain_expand
sface.Search_interface.hd
sface.Search_interface.rev_hd vector bound)
~goal_p:(wrap sface.Search_interface.goal_p)
~halt_on:sface.Search_interface.halt_on
~key:(wrap sface.Search_interface.key)
~hash:sface.Search_interface.hash
~equals:sface.Search_interface.equals
sface.Search_interface.domain
(make_init sface.Search_interface.initial)
better_p
(Limit.make_default_logger (fun n -> n.f)
(wrap sface.Search_interface.get_sol_length)) in
Limit.unwrap_sol6 unwrap_sol
(Focal_search.search_dups
search_interface
ordered_p
(make_close_enough bound)
ordered_2
better_p
setpos
getpos)
EOF
| null | https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/search/adaptive/vector_aseps.ml | ocaml | * Ordering predicate based on node cost
***********************************************************************
* Performs a search in domains where there are no duplicates.
[sface] is the domain's search interface
[vector] is a list of weights to be used
* Performs a search in domains where there are no duplicates.
[sface] is the domain's search interface
[vector] is a list of weights to be used | * Sorts the focal list based on an estimate of true cost to go , found by
multiplying a weight vector over a set of features available at the given
node . Vector is typically gotten through offline regression . Search is
carried out in an A * epsilon like manner .
multiplying a weight vector over a set of features available at the given
node. Vector is typically gotten through offline regression. Search is
carried out in an A* epsilon like manner.
*)
open Vector_search
open Clamped_vector_search
let make_close_enough wt =
* Close enough predicate required by Geq.ml
(fun a b ->
(wt *. a.f) >= b.f)
let ordered_2 a b =
a.cost < b.cost
let no_dups sface args =
let bound = Search_args.get_float "Vector_aseps.no_dups" args 0
and vector = Search_args.get_float_array "Vector_aseps.no_dups"
(Array.sub args 1 ((Array.length args) - 1)) in
let search_interface = Search_interface.make
~node_expand:(wrap_expand sface.Search_interface.domain_expand
sface.Search_interface.hd
sface.Search_interface.rev_hd vector bound)
~goal_p:(wrap sface.Search_interface.goal_p)
~halt_on:sface.Search_interface.halt_on
~hash:sface.Search_interface.hash
~equals:sface.Search_interface.equals
sface.Search_interface.domain
(make_init sface.Search_interface.initial)
better_p
(Limit.make_default_logger (fun n -> n.f)
(wrap sface.Search_interface.get_sol_length))
in
Limit.unwrap_sol5 unwrap_sol
(Focal_search.search
search_interface
ordered_p
(make_close_enough bound)
ordered_2
better_p
setpos
getpos)
let dups sface args =
let bound = Search_args.get_float "Vector_aseps.dups" args 0
and vector = Search_args.get_float_array "Vector_aseps.dups"
(Array.sub args 1 ((Array.length args) - 1)) in
let search_interface = Search_interface.make
~node_expand:(wrap_expand sface.Search_interface.domain_expand
sface.Search_interface.hd
sface.Search_interface.rev_hd vector bound)
~goal_p:(wrap sface.Search_interface.goal_p)
~halt_on:sface.Search_interface.halt_on
~key:(wrap sface.Search_interface.key)
~hash:sface.Search_interface.hash
~equals:sface.Search_interface.equals
sface.Search_interface.domain
(make_init sface.Search_interface.initial)
better_p
(Limit.make_default_logger (fun n -> n.f)
(wrap sface.Search_interface.get_sol_length)) in
Limit.unwrap_sol6 unwrap_sol
(Focal_search.search_dups
search_interface
ordered_p
(make_close_enough bound)
ordered_2
better_p
setpos
getpos)
EOF
|
223d898c15084a5d056e08db6c47e5bc0fd85955e01cb9ffef947a2eb0abcb4f | CafeOBJ/cafeobj | convert.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*-
$ Header : /usr / local / cvsrep / cl - ppcre / convert.lisp , v 1.57 2009/09/17 19:17:31 edi Exp $
;;; Here the parse tree is converted into its internal representation
;;; using REGEX objects. At the same time some optimizations are
;;; already applied.
Copyright ( c ) 2002 - 2009 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
;;; The flags that represent the "ism" modifiers are always kept
together in a three - element list . We use the following macros to
;;; access individual elements.
(defmacro case-insensitive-mode-p (flags)
"Accessor macro to extract the first flag out of a three-element flag list."
`(first ,flags))
(defmacro multi-line-mode-p (flags)
"Accessor macro to extract the second flag out of a three-element flag list."
`(second ,flags))
(defmacro single-line-mode-p (flags)
"Accessor macro to extract the third flag out of a three-element flag list."
`(third ,flags))
(defun set-flag (token)
"Reads a flag token and sets or unsets the corresponding entry in
the special FLAGS list."
(declare #.*standard-optimize-settings*)
(declare (special flags))
(case token
((:case-insensitive-p)
(setf (case-insensitive-mode-p flags) t))
((:case-sensitive-p)
(setf (case-insensitive-mode-p flags) nil))
((:multi-line-mode-p)
(setf (multi-line-mode-p flags) t))
((:not-multi-line-mode-p)
(setf (multi-line-mode-p flags) nil))
((:single-line-mode-p)
(setf (single-line-mode-p flags) t))
((:not-single-line-mode-p)
(setf (single-line-mode-p flags) nil))
(otherwise
(signal-syntax-error "Unknown flag token ~A." token))))
(defgeneric resolve-property (property)
(:documentation "Resolves PROPERTY to a unary character test
function. PROPERTY can either be a function designator or it can be a
string which is resolved using *PROPERTY-RESOLVER*.")
(:method ((property-name string))
(funcall *property-resolver* property-name))
(:method ((function-name symbol))
function-name)
(:method ((test-function function))
test-function))
(defun convert-char-class-to-test-function (list invertedp case-insensitive-p)
"Combines all items in LIST into test function and returns a
logical-OR combination of these functions. Items can be single
characters, character ranges like \(:RANGE #\\A #\\E), or special
character classes like :DIGIT-CLASS. Does the right thing with
respect to case-\(in)sensitivity as specified by the special variable
FLAGS."
(declare #.*standard-optimize-settings*)
(declare (special flags))
(let ((test-functions
(loop for item in list
collect (cond ((characterp item)
rebind so closure captures the right one
(let ((this-char item))
(lambda (char)
(declare (character char this-char))
(char= char this-char))))
((symbolp item)
(case item
((:digit-class) #'digit-char-p)
((:non-digit-class) (complement* #'digit-char-p))
((:whitespace-char-class) #'whitespacep)
((:non-whitespace-char-class) (complement* #'whitespacep))
((:word-char-class) #'word-char-p)
((:non-word-char-class) (complement* #'word-char-p))
(otherwise
(signal-syntax-error "Unknown symbol ~A in character class." item))))
((and (consp item)
(eq (first item) :property))
(resolve-property (second item)))
((and (consp item)
(eq (first item) :inverted-property))
(complement* (resolve-property (second item))))
((and (consp item)
(eq (first item) :range))
(let ((from (second item))
(to (third item)))
(when (char> from to)
(signal-syntax-error "Invalid range from ~S to ~S in char-class." from to))
(lambda (char)
(declare (character char from to))
(char<= from char to))))
(t (signal-syntax-error "Unknown item ~A in char-class list." item))))))
(unless test-functions
(signal-syntax-error "Empty character class."))
(cond ((cdr test-functions)
(cond ((and invertedp case-insensitive-p)
(lambda (char)
(declare (character char))
(loop with both-case-p = (both-case-p char)
with char-down = (if both-case-p (char-downcase char) char)
with char-up = (if both-case-p (char-upcase char) nil)
for test-function in test-functions
never (or (funcall test-function char-down)
(and char-up (funcall test-function char-up))))))
(case-insensitive-p
(lambda (char)
(declare (character char))
(loop with both-case-p = (both-case-p char)
with char-down = (if both-case-p (char-downcase char) char)
with char-up = (if both-case-p (char-upcase char) nil)
for test-function in test-functions
thereis (or (funcall test-function char-down)
(and char-up (funcall test-function char-up))))))
(invertedp
(lambda (char)
(loop for test-function in test-functions
never (funcall test-function char))))
(t
(lambda (char)
(loop for test-function in test-functions
thereis (funcall test-function char))))))
there 's only one test - function
(t (let ((test-function (first test-functions)))
(cond ((and invertedp case-insensitive-p)
(lambda (char)
(declare (character char))
(not (or (funcall test-function (char-downcase char))
(and (both-case-p char)
(funcall test-function (char-upcase char)))))))
(case-insensitive-p
(lambda (char)
(declare (character char))
(or (funcall test-function (char-downcase char))
(and (both-case-p char)
(funcall test-function (char-upcase char))))))
(invertedp (complement* test-function))
(t test-function)))))))
(defun maybe-split-repetition (regex
greedyp
minimum
maximum
min-len
length
reg-seen)
"Splits a REPETITION object into a constant and a varying part if
applicable, i.e. something like
a{3,} -> a{3}a*
The arguments to this function correspond to the REPETITION slots of
the same name."
(declare #.*standard-optimize-settings*)
(declare (fixnum minimum)
(type (or fixnum null) maximum))
;; note the usage of COPY-REGEX here; we can't use the same REGEX
;; object in both REPETITIONS because they will have different
;; offsets
(when maximum
(when (zerop maximum)
;; trivial case: don't repeat at all
(return-from maybe-split-repetition
(make-instance 'void)))
(when (= 1 minimum maximum)
;; another trivial case: "repeat" exactly once
(return-from maybe-split-repetition
regex)))
first set up the constant part of the repetition
;; maybe that's all we need
(let ((constant-repetition (if (plusp minimum)
(make-instance 'repetition
:regex (copy-regex regex)
:greedyp greedyp
:minimum minimum
:maximum minimum
:min-len min-len
:len length
:contains-register-p reg-seen)
;; don't create garbage if minimum is 0
nil)))
(when (and maximum
(= maximum minimum))
(return-from maybe-split-repetition
no varying part needed because min =
constant-repetition))
;; now construct the varying part
(let ((varying-repetition
(make-instance 'repetition
:regex regex
:greedyp greedyp
:minimum 0
:maximum (if maximum (- maximum minimum) nil)
:min-len min-len
:len length
:contains-register-p reg-seen)))
(cond ((zerop minimum)
;; min = 0, no constant part needed
varying-repetition)
((= 1 minimum)
min = 1 , constant part needs no REPETITION wrapped around
(make-instance 'seq
:elements (list (copy-regex regex)
varying-repetition)))
(t
;; general case
(make-instance 'seq
:elements (list constant-repetition
varying-repetition)))))))
;; During the conversion of the parse tree we keep track of the start
;; of the parse tree in the special variable STARTS-WITH which'll
;; either hold a STR object or an EVERYTHING object. The latter is the
;; case if the regex starts with ".*" which implicitly anchors the
;; regex at the start (perhaps modulo #\Newline).
(defun maybe-accumulate (str)
"Accumulate STR into the special variable STARTS-WITH if
ACCUMULATE-START-P (also special) is true and STARTS-WITH is either
NIL or a STR object of the same case mode. Always returns NIL."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p starts-with))
(declare (ftype (function (t) fixnum) len))
(when accumulate-start-p
(etypecase starts-with
(str
STARTS - WITH already holds a STR , so we check if we can
;; concatenate
(cond ((eq (case-insensitive-p starts-with)
(case-insensitive-p str))
;; we modify STARTS-WITH in place
(setf (len starts-with)
(+ (len starts-with) (len str)))
note that we use SLOT - VALUE because the accessor
STR has a declared FTYPE which does n't fit here
(adjust-array (slot-value starts-with 'str)
(len starts-with)
:fill-pointer t)
(setf (subseq (slot-value starts-with 'str)
(- (len starts-with) (len str)))
(str str)
STR objects that are parts of STARTS - WITH
;; always have their SKIP slot set to true
;; because the SCAN function will take care of
;; them, i.e. the matcher can ignore them
(skip str) t))
(t (setq accumulate-start-p nil))))
(null
STARTS - WITH is still empty , so we create a new STR object
(setf starts-with
(make-instance 'str
:str ""
:case-insensitive-p (case-insensitive-p str))
INITIALIZE - INSTANCE will coerce the STR to a simple
;; string, so we have to fill it afterwards
(slot-value starts-with 'str)
(make-array (len str)
:initial-contents (str str)
:element-type 'character
:fill-pointer t
:adjustable t)
(len starts-with)
(len str)
;; see remark about SKIP above
(skip str) t))
(everything
;; STARTS-WITH already holds an EVERYTHING object - we can't
;; concatenate
(setq accumulate-start-p nil))))
nil)
(declaim (inline convert-aux))
(defun convert-aux (parse-tree)
"Converts the parse tree PARSE-TREE into a REGEX object and returns
it. Will also
- split and optimize repetitions,
- accumulate strings or EVERYTHING objects into the special variable
STARTS-WITH,
- keep track of all registers seen in the special variable REG-NUM,
- keep track of all named registers seen in the special variable REG-NAMES
- keep track of the highest backreference seen in the special
variable MAX-BACK-REF,
- maintain and adher to the currently applicable modifiers in the special
variable FLAGS, and
- maybe even wash your car..."
(declare #.*standard-optimize-settings*)
(if (consp parse-tree)
(convert-compound-parse-tree (first parse-tree) parse-tree)
(convert-simple-parse-tree parse-tree)))
(defgeneric convert-compound-parse-tree (token parse-tree &key)
(declare #.*standard-optimize-settings*)
(:documentation "Helper function for CONVERT-AUX which converts
parse trees which are conses and dispatches on TOKEN which is the
first element of the parse tree.")
(:method ((token t) parse-tree &key)
(signal-syntax-error "Unknown token ~A in parse-tree." token)))
(defmethod convert-compound-parse-tree ((token (eql :sequence)) parse-tree &key)
"The case for parse trees like \(:SEQUENCE {<regex>}*)."
(declare #.*standard-optimize-settings*)
(cond ((cddr parse-tree)
;; this is essentially like
( MAPCAR ' CONVERT - AUX ( REST PARSE - TREE ) )
;; but we don't cons a new list
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq :elements (rest parse-tree)))
(t (convert-aux (second parse-tree)))))
(defmethod convert-compound-parse-tree ((token (eql :group)) parse-tree &key)
"The case for parse trees like \(:GROUP {<regex>}*).
This is a syntactical construct equivalent to :SEQUENCE intended to
keep the effect of modifiers local."
(declare #.*standard-optimize-settings*)
(declare (special flags))
make a local copy of FLAGS and shadow the global value while we
;; descend into the enclosed regexes
(let ((flags (copy-list flags)))
(declare (special flags))
(cond ((cddr parse-tree)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq :elements (rest parse-tree)))
(t (convert-aux (second parse-tree))))))
(defmethod convert-compound-parse-tree ((token (eql :alternation)) parse-tree &key)
"The case for \(:ALTERNATION {<regex>}*)."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
;; we must stop accumulating objects into STARTS-WITH once we reach
;; an alternation
(setq accumulate-start-p nil)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'alternation :choices (rest parse-tree)))
(defmethod convert-compound-parse-tree ((token (eql :branch)) parse-tree &key)
"The case for \(:BRANCH <test> <regex>).
Here, <test> must be look-ahead, look-behind or number; if <regex> is
an alternation it must have one or two choices."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(let* ((test-candidate (second parse-tree))
(test (cond ((numberp test-candidate)
(when (zerop (the fixnum test-candidate))
(signal-syntax-error "Register 0 doesn't exist: ~S." parse-tree))
(1- (the fixnum test-candidate)))
(t (convert-aux test-candidate))))
(alternations (convert-aux (third parse-tree))))
(when (and (not (numberp test))
(not (typep test 'lookahead))
(not (typep test 'lookbehind)))
(signal-syntax-error "Branch test must be look-ahead, look-behind or number: ~S." parse-tree))
(typecase alternations
(alternation
(case (length (choices alternations))
((0)
(signal-syntax-error "No choices in branch: ~S." parse-tree))
((1)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))))
((2)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))
:else-regex (second
(choices alternations))))
(otherwise
(signal-syntax-error "Too much choices in branch: ~S." parse-tree))))
(t
(make-instance 'branch
:test test
:then-regex alternations)))))
(defmethod convert-compound-parse-tree ((token (eql :positive-lookahead)) parse-tree &key)
"The case for \(:POSITIVE-LOOKAHEAD <regex>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
;; keep the effect of modifiers local to the enclosed regex and stop
;; accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'lookahead
:regex (convert-aux (second parse-tree))
:positivep t)))
(defmethod convert-compound-parse-tree ((token (eql :negative-lookahead)) parse-tree &key)
"The case for \(:NEGATIVE-LOOKAHEAD <regex>)."
(declare #.*standard-optimize-settings*)
;; do the same as for positive look-aheads and just switch afterwards
(let ((regex (convert-compound-parse-tree :positive-lookahead parse-tree)))
(setf (slot-value regex 'positivep) nil)
regex))
(defmethod convert-compound-parse-tree ((token (eql :positive-lookbehind)) parse-tree &key)
"The case for \(:POSITIVE-LOOKBEHIND <regex>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
;; keep the effect of modifiers local to the enclosed regex and stop
;; accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(let* ((flags (copy-list flags))
(regex (convert-aux (second parse-tree)))
(len (regex-length regex)))
(declare (special flags))
;; lookbehind assertions must be of fixed length
(unless len
(signal-syntax-error "Variable length look-behind not implemented \(yet): ~S." parse-tree))
(make-instance 'lookbehind
:regex regex
:positivep t
:len len)))
(defmethod convert-compound-parse-tree ((token (eql :negative-lookbehind)) parse-tree &key)
"The case for \(:NEGATIVE-LOOKBEHIND <regex>)."
(declare #.*standard-optimize-settings*)
;; do the same as for positive look-behinds and just switch afterwards
(let ((regex (convert-compound-parse-tree :positive-lookbehind parse-tree)))
(setf (slot-value regex 'positivep) nil)
regex))
(defmethod convert-compound-parse-tree ((token (eql :greedy-repetition)) parse-tree &key (greedyp t))
"The case for \(:GREEDY-REPETITION|:NON-GREEDY-REPETITION <min> <max> <regex>).
This function is also used for the non-greedy case in which case it is
called with GREEDYP set to NIL as you would expect."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p starts-with))
;; remember the value of ACCUMULATE-START-P upon entering
(let ((local-accumulate-start-p accumulate-start-p))
(let ((minimum (second parse-tree))
(maximum (third parse-tree)))
(declare (fixnum minimum))
(declare (type (or null fixnum) maximum))
(unless (and maximum
(= 1 minimum maximum))
;; set ACCUMULATE-START-P to NIL for the rest of
;; the conversion because we can't continue to
;; accumulate inside as well as after a proper
;; repetition
(setq accumulate-start-p nil))
(let* (reg-seen
(regex (convert-aux (fourth parse-tree)))
(min-len (regex-min-length regex))
(length (regex-length regex)))
;; note that this declaration already applies to
the call to CONVERT - AUX above
(declare (special reg-seen))
(when (and local-accumulate-start-p
(not starts-with)
(zerop minimum)
(not maximum))
;; if this repetition is (equivalent to) ".*"
;; and if we're at the start of the regex we
remember it for ADVANCE - FN ( see the SCAN
;; function)
(setq starts-with (everythingp regex)))
(if (or (not reg-seen)
(not greedyp)
(not length)
(zerop length)
(and maximum (= minimum maximum)))
;; the repetition doesn't enclose a register, or
;; it's not greedy, or we can't determine it's
( inner ) length , or the length is zero , or the
;; number of repetitions is fixed; in all of
;; these cases we don't bother to optimize
(maybe-split-repetition regex
greedyp
minimum
maximum
min-len
length
reg-seen)
;; otherwise we make a transformation that looks
;; roughly like one of
;; <regex>* -> (?:<regex'>*<regex>)?
;; <regex>+ -> <regex'>*<regex>
;; where the trick is that as much as possible
;; registers from <regex> are removed in
;; <regex'>
(let* (reg-seen ; new instance for REMOVE-REGISTERS
(remove-registers-p t)
(inner-regex (remove-registers regex))
(inner-repetition
;; this is the "<regex'>" part
(maybe-split-repetition inner-regex
;; always greedy
t
reduce minimum by 1
;; unless it's already 0
(if (zerop minimum)
0
(1- minimum))
reduce maximum by 1
;; unless it's NIL
(and maximum
(1- maximum))
min-len
length
reg-seen))
(inner-seq
;; this is the "<regex'>*<regex>" part
(make-instance 'seq
:elements (list inner-repetition
regex))))
;; note that this declaration already applies
;; to the call to REMOVE-REGISTERS above
(declare (special remove-registers-p reg-seen))
wrap INNER - SEQ with a greedy
;; {0,1}-repetition (i.e. "?") if necessary
(if (plusp minimum)
inner-seq
(maybe-split-repetition inner-seq
t
0
1
min-len
nil
t))))))))
(defmethod convert-compound-parse-tree ((token (eql :non-greedy-repetition)) parse-tree &key)
"The case for \(:NON-GREEDY-REPETITION <min> <max> <regex>)."
(declare #.*standard-optimize-settings*)
just dispatch to the method above with explicitly set to NIL
(convert-compound-parse-tree :greedy-repetition parse-tree :greedyp nil))
(defmethod convert-compound-parse-tree ((token (eql :register)) parse-tree &key name)
"The case for \(:REGISTER <regex>). Also used for named registers
when NAME is not NIL."
(declare #.*standard-optimize-settings*)
(declare (special flags reg-num reg-names))
;; keep the effect of modifiers local to the enclosed regex; also,
assign the current value of REG - NUM to the corresponding slot of
the REGISTER object and increase this counter afterwards ; for
named register update REG - NAMES and set the corresponding name
slot of the REGISTER object too
(let ((flags (copy-list flags))
(stored-reg-num reg-num))
(declare (special flags reg-seen named-reg-seen))
(setq reg-seen t)
(when name (setq named-reg-seen t))
(incf (the fixnum reg-num))
(push name reg-names)
(make-instance 'register
:regex (convert-aux (if name (third parse-tree) (second parse-tree)))
:num stored-reg-num
:name name)))
(defmethod convert-compound-parse-tree ((token (eql :named-register)) parse-tree &key)
"The case for \(:NAMED-REGISTER <regex>)."
(declare #.*standard-optimize-settings*)
;; call the method above and use the :NAME keyword argument
(convert-compound-parse-tree :register parse-tree :name (copy-seq (second parse-tree))))
(defmethod convert-compound-parse-tree ((token (eql :filter)) parse-tree &key)
"The case for \(:FILTER <function> &optional <length>)."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
;; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(make-instance 'filter
:fn (second parse-tree)
:len (third parse-tree)))
(defmethod convert-compound-parse-tree ((token (eql :standalone)) parse-tree &key)
"The case for \(:STANDALONE <regex>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
;; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
;; keep the effect of modifiers local to the enclosed regex
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'standalone :regex (convert-aux (second parse-tree)))))
(defmethod convert-compound-parse-tree ((token (eql :back-reference)) parse-tree &key)
"The case for \(:BACK-REFERENCE <number>|<name>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p reg-num reg-names max-back-ref))
(let* ((backref-name (and (stringp (second parse-tree))
(second parse-tree)))
(referred-regs
(when backref-name
;; find which register corresponds to the given name
;; we have to deal with case where several registers share
;; the same name and collect their respective numbers
(loop for name in reg-names
for reg-index from 0
when (string= name backref-name)
;; NOTE: REG-NAMES stores register names in reversed
order REG - NUM contains number of ( any ) registers
;; seen so far; 1- will be done later
collect (- reg-num reg-index))))
;; store the register number for the simple case
(backref-number (or (first referred-regs) (second parse-tree))))
(declare (type (or fixnum null) backref-number))
(when (or (not (typep backref-number 'fixnum))
(<= backref-number 0))
(signal-syntax-error "Illegal back-reference: ~S." parse-tree))
stop accumulating into STARTS - WITH and increase MAX - BACK - REF if
;; necessary
(setq accumulate-start-p nil
max-back-ref (max (the fixnum max-back-ref)
backref-number))
(flet ((make-back-ref (backref-number)
(make-instance 'back-reference
;; we start counting from 0 internally
:num (1- backref-number)
:case-insensitive-p (case-insensitive-mode-p flags)
backref - name is NIL or string , safe to copy
:name (copy-seq backref-name))))
(cond
((cdr referred-regs)
;; several registers share the same name we will try to match
any of them , starting with the most recent first
;; alternation is used to accomplish matching
(make-instance 'alternation
:choices (loop
for reg-index in referred-regs
collect (make-back-ref reg-index))))
simple case - backref corresponds to only one register
(t
(make-back-ref backref-number))))))
(defmethod convert-compound-parse-tree ((token (eql :regex)) parse-tree &key)
"The case for \(:REGEX <string>)."
(declare #.*standard-optimize-settings*)
(convert-aux (parse-string (second parse-tree))))
(defmethod convert-compound-parse-tree ((token (eql :char-class)) parse-tree &key invertedp)
"The case for \(:CHAR-CLASS {<item>}*) where item is one of
- a character,
- a character range: \(:RANGE <char1> <char2>), or
- a special char class symbol like :DIGIT-CHAR-CLASS.
Also used for inverted char classes when INVERTEDP is true."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
(let ((test-function
(create-optimized-test-function
(convert-char-class-to-test-function (rest parse-tree)
invertedp
(case-insensitive-mode-p flags)))))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function test-function)))
(defmethod convert-compound-parse-tree ((token (eql :inverted-char-class)) parse-tree &key)
"The case for \(:INVERTED-CHAR-CLASS {<item>}*)."
(declare #.*standard-optimize-settings*)
;; just dispatch to the "real" method
(convert-compound-parse-tree :char-class parse-tree :invertedp t))
(defmethod convert-compound-parse-tree ((token (eql :property)) parse-tree &key)
"The case for \(:PROPERTY <name>) where <name> is a string."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (resolve-property (second parse-tree))))
(defmethod convert-compound-parse-tree ((token (eql :inverted-property)) parse-tree &key)
"The case for \(:INVERTED-PROPERTY <name>) where <name> is a string."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* (resolve-property (second parse-tree)))))
(defmethod convert-compound-parse-tree ((token (eql :flags)) parse-tree &key)
"The case for \(:FLAGS {<flag>}*) where flag is a modifier symbol
like :CASE-INSENSITIVE-P."
(declare #.*standard-optimize-settings*)
;; set/unset the flags corresponding to the symbols
following :
(mapc #'set-flag (rest parse-tree))
;; we're only interested in the side effect of
;; setting/unsetting the flags and turn this syntactical
;; construct into a VOID object which'll be optimized
;; away when creating the matcher
(make-instance 'void))
(defgeneric convert-simple-parse-tree (parse-tree)
(declare #.*standard-optimize-settings*)
(:documentation "Helper function for CONVERT-AUX which converts
parse trees which are atoms.")
(:method ((parse-tree (eql :void)))
(declare #.*standard-optimize-settings*)
(make-instance 'void))
(:method ((parse-tree (eql :word-boundary)))
(declare #.*standard-optimize-settings*)
(make-instance 'word-boundary :negatedp nil))
(:method ((parse-tree (eql :non-word-boundary)))
(declare #.*standard-optimize-settings*)
(make-instance 'word-boundary :negatedp t))
(:method ((parse-tree (eql :everything)))
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'everything :single-line-p (single-line-mode-p flags)))
(:method ((parse-tree (eql :digit-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function #'digit-char-p))
(:method ((parse-tree (eql :word-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function #'word-char-p))
(:method ((parse-tree (eql :whitespace-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function #'whitespacep))
(:method ((parse-tree (eql :non-digit-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* #'digit-char-p)))
(:method ((parse-tree (eql :non-word-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* #'word-char-p)))
(:method ((parse-tree (eql :non-whitespace-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* #'whitespacep)))
(:method ((parse-tree (eql :start-anchor)))
;; Perl's "^"
(declare #.*standard-optimize-settings*)
(declare (special flags))
(make-instance 'anchor :startp t :multi-line-p (multi-line-mode-p flags)))
(:method ((parse-tree (eql :end-anchor)))
;; Perl's "$"
(declare #.*standard-optimize-settings*)
(declare (special flags))
(make-instance 'anchor :startp nil :multi-line-p (multi-line-mode-p flags)))
(:method ((parse-tree (eql :modeless-start-anchor)))
;; Perl's "\A"
(declare #.*standard-optimize-settings*)
(make-instance 'anchor :startp t))
(:method ((parse-tree (eql :modeless-end-anchor)))
;; Perl's "$\Z"
(declare #.*standard-optimize-settings*)
(make-instance 'anchor :startp nil))
(:method ((parse-tree (eql :modeless-end-anchor-no-newline)))
;; Perl's "$\z"
(declare #.*standard-optimize-settings*)
(make-instance 'anchor :startp nil :no-newline-p t))
(:method ((parse-tree (eql :case-insensitive-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :case-sensitive-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :multi-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :not-multi-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :single-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :not-single-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void)))
(defmethod convert-simple-parse-tree ((parse-tree string))
(declare #.*standard-optimize-settings*)
(declare (special flags))
turn strings into STR objects and try to accumulate into
;; STARTS-WITH
(let ((str (make-instance 'str
:str parse-tree
:case-insensitive-p (case-insensitive-mode-p flags))))
(maybe-accumulate str)
str))
(defmethod convert-simple-parse-tree ((parse-tree character))
(declare #.*standard-optimize-settings*)
;; dispatch to the method for strings
(convert-simple-parse-tree (string parse-tree)))
(defmethod convert-simple-parse-tree (parse-tree)
"The default method - check if there's a translation."
(declare #.*standard-optimize-settings*)
(let ((translation (and (symbolp parse-tree) (parse-tree-synonym parse-tree))))
(if translation
(convert-aux (copy-tree translation))
(signal-syntax-error "Unknown token ~A in parse tree." parse-tree))))
(defun convert (parse-tree)
"Converts the parse tree PARSE-TREE into an equivalent REGEX object
and returns three values: the REGEX object, the number of registers
seen and an object the regex starts with which is either a STR object
or an EVERYTHING object \(if the regex starts with something like
\".*\") or NIL."
(declare #.*standard-optimize-settings*)
;; this function basically just initializes the special variables
and then calls CONVERT - AUX to do all the work
(let* ((flags (list nil nil nil))
(reg-num 0)
reg-names
named-reg-seen
(accumulate-start-p t)
starts-with
(max-back-ref 0)
(converted-parse-tree (convert-aux parse-tree)))
(declare (special flags reg-num reg-names named-reg-seen
accumulate-start-p starts-with max-back-ref))
;; make sure we don't reference registers which aren't there
(when (> (the fixnum max-back-ref)
(the fixnum reg-num))
(signal-syntax-error "Backreference to register ~A which has not been defined." max-back-ref))
(when (typep starts-with 'str)
(setf (slot-value starts-with 'str)
(coerce (slot-value starts-with 'str)
#+:lispworks 'lw:simple-text-string
#-:lispworks 'simple-string)))
(values converted-parse-tree reg-num starts-with
;; we can't simply use *ALLOW-NAMED-REGISTERS*
;; since parse-tree syntax ignores it
(when named-reg-seen
(nreverse reg-names)))))
| null | https://raw.githubusercontent.com/CafeOBJ/cafeobj/261e3a50407f568272321378df370e5cf7492aaf/cl-ppcre/convert.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*-
Here the parse tree is converted into its internal representation
using REGEX objects. At the same time some optimizations are
already applied.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The flags that represent the "ism" modifiers are always kept
access individual elements.
note the usage of COPY-REGEX here; we can't use the same REGEX
object in both REPETITIONS because they will have different
offsets
trivial case: don't repeat at all
another trivial case: "repeat" exactly once
maybe that's all we need
don't create garbage if minimum is 0
now construct the varying part
min = 0, no constant part needed
general case
During the conversion of the parse tree we keep track of the start
of the parse tree in the special variable STARTS-WITH which'll
either hold a STR object or an EVERYTHING object. The latter is the
case if the regex starts with ".*" which implicitly anchors the
regex at the start (perhaps modulo #\Newline).
concatenate
we modify STARTS-WITH in place
always have their SKIP slot set to true
because the SCAN function will take care of
them, i.e. the matcher can ignore them
string, so we have to fill it afterwards
see remark about SKIP above
STARTS-WITH already holds an EVERYTHING object - we can't
concatenate
this is essentially like
but we don't cons a new list
descend into the enclosed regexes
we must stop accumulating objects into STARTS-WITH once we reach
an alternation
if <regex> is
keep the effect of modifiers local to the enclosed regex and stop
accumulating into STARTS-WITH
do the same as for positive look-aheads and just switch afterwards
keep the effect of modifiers local to the enclosed regex and stop
accumulating into STARTS-WITH
lookbehind assertions must be of fixed length
do the same as for positive look-behinds and just switch afterwards
remember the value of ACCUMULATE-START-P upon entering
set ACCUMULATE-START-P to NIL for the rest of
the conversion because we can't continue to
accumulate inside as well as after a proper
repetition
note that this declaration already applies to
if this repetition is (equivalent to) ".*"
and if we're at the start of the regex we
function)
the repetition doesn't enclose a register, or
it's not greedy, or we can't determine it's
number of repetitions is fixed; in all of
these cases we don't bother to optimize
otherwise we make a transformation that looks
roughly like one of
<regex>* -> (?:<regex'>*<regex>)?
<regex>+ -> <regex'>*<regex>
where the trick is that as much as possible
registers from <regex> are removed in
<regex'>
new instance for REMOVE-REGISTERS
this is the "<regex'>" part
always greedy
unless it's already 0
unless it's NIL
this is the "<regex'>*<regex>" part
note that this declaration already applies
to the call to REMOVE-REGISTERS above
{0,1}-repetition (i.e. "?") if necessary
keep the effect of modifiers local to the enclosed regex; also,
for
call the method above and use the :NAME keyword argument
stop accumulating into STARTS-WITH
stop accumulating into STARTS-WITH
keep the effect of modifiers local to the enclosed regex
find which register corresponds to the given name
we have to deal with case where several registers share
the same name and collect their respective numbers
NOTE: REG-NAMES stores register names in reversed
seen so far; 1- will be done later
store the register number for the simple case
necessary
we start counting from 0 internally
several registers share the same name we will try to match
alternation is used to accomplish matching
just dispatch to the "real" method
set/unset the flags corresponding to the symbols
we're only interested in the side effect of
setting/unsetting the flags and turn this syntactical
construct into a VOID object which'll be optimized
away when creating the matcher
Perl's "^"
Perl's "$"
Perl's "\A"
Perl's "$\Z"
Perl's "$\z"
STARTS-WITH
dispatch to the method for strings
this function basically just initializes the special variables
make sure we don't reference registers which aren't there
we can't simply use *ALLOW-NAMED-REGISTERS*
since parse-tree syntax ignores it | $ Header : /usr / local / cvsrep / cl - ppcre / convert.lisp , v 1.57 2009/09/17 19:17:31 edi Exp $
Copyright ( c ) 2002 - 2009 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :cl-ppcre)
together in a three - element list . We use the following macros to
(defmacro case-insensitive-mode-p (flags)
"Accessor macro to extract the first flag out of a three-element flag list."
`(first ,flags))
(defmacro multi-line-mode-p (flags)
"Accessor macro to extract the second flag out of a three-element flag list."
`(second ,flags))
(defmacro single-line-mode-p (flags)
"Accessor macro to extract the third flag out of a three-element flag list."
`(third ,flags))
(defun set-flag (token)
"Reads a flag token and sets or unsets the corresponding entry in
the special FLAGS list."
(declare #.*standard-optimize-settings*)
(declare (special flags))
(case token
((:case-insensitive-p)
(setf (case-insensitive-mode-p flags) t))
((:case-sensitive-p)
(setf (case-insensitive-mode-p flags) nil))
((:multi-line-mode-p)
(setf (multi-line-mode-p flags) t))
((:not-multi-line-mode-p)
(setf (multi-line-mode-p flags) nil))
((:single-line-mode-p)
(setf (single-line-mode-p flags) t))
((:not-single-line-mode-p)
(setf (single-line-mode-p flags) nil))
(otherwise
(signal-syntax-error "Unknown flag token ~A." token))))
(defgeneric resolve-property (property)
(:documentation "Resolves PROPERTY to a unary character test
function. PROPERTY can either be a function designator or it can be a
string which is resolved using *PROPERTY-RESOLVER*.")
(:method ((property-name string))
(funcall *property-resolver* property-name))
(:method ((function-name symbol))
function-name)
(:method ((test-function function))
test-function))
(defun convert-char-class-to-test-function (list invertedp case-insensitive-p)
"Combines all items in LIST into test function and returns a
logical-OR combination of these functions. Items can be single
characters, character ranges like \(:RANGE #\\A #\\E), or special
character classes like :DIGIT-CLASS. Does the right thing with
respect to case-\(in)sensitivity as specified by the special variable
FLAGS."
(declare #.*standard-optimize-settings*)
(declare (special flags))
(let ((test-functions
(loop for item in list
collect (cond ((characterp item)
rebind so closure captures the right one
(let ((this-char item))
(lambda (char)
(declare (character char this-char))
(char= char this-char))))
((symbolp item)
(case item
((:digit-class) #'digit-char-p)
((:non-digit-class) (complement* #'digit-char-p))
((:whitespace-char-class) #'whitespacep)
((:non-whitespace-char-class) (complement* #'whitespacep))
((:word-char-class) #'word-char-p)
((:non-word-char-class) (complement* #'word-char-p))
(otherwise
(signal-syntax-error "Unknown symbol ~A in character class." item))))
((and (consp item)
(eq (first item) :property))
(resolve-property (second item)))
((and (consp item)
(eq (first item) :inverted-property))
(complement* (resolve-property (second item))))
((and (consp item)
(eq (first item) :range))
(let ((from (second item))
(to (third item)))
(when (char> from to)
(signal-syntax-error "Invalid range from ~S to ~S in char-class." from to))
(lambda (char)
(declare (character char from to))
(char<= from char to))))
(t (signal-syntax-error "Unknown item ~A in char-class list." item))))))
(unless test-functions
(signal-syntax-error "Empty character class."))
(cond ((cdr test-functions)
(cond ((and invertedp case-insensitive-p)
(lambda (char)
(declare (character char))
(loop with both-case-p = (both-case-p char)
with char-down = (if both-case-p (char-downcase char) char)
with char-up = (if both-case-p (char-upcase char) nil)
for test-function in test-functions
never (or (funcall test-function char-down)
(and char-up (funcall test-function char-up))))))
(case-insensitive-p
(lambda (char)
(declare (character char))
(loop with both-case-p = (both-case-p char)
with char-down = (if both-case-p (char-downcase char) char)
with char-up = (if both-case-p (char-upcase char) nil)
for test-function in test-functions
thereis (or (funcall test-function char-down)
(and char-up (funcall test-function char-up))))))
(invertedp
(lambda (char)
(loop for test-function in test-functions
never (funcall test-function char))))
(t
(lambda (char)
(loop for test-function in test-functions
thereis (funcall test-function char))))))
there 's only one test - function
(t (let ((test-function (first test-functions)))
(cond ((and invertedp case-insensitive-p)
(lambda (char)
(declare (character char))
(not (or (funcall test-function (char-downcase char))
(and (both-case-p char)
(funcall test-function (char-upcase char)))))))
(case-insensitive-p
(lambda (char)
(declare (character char))
(or (funcall test-function (char-downcase char))
(and (both-case-p char)
(funcall test-function (char-upcase char))))))
(invertedp (complement* test-function))
(t test-function)))))))
(defun maybe-split-repetition (regex
greedyp
minimum
maximum
min-len
length
reg-seen)
"Splits a REPETITION object into a constant and a varying part if
applicable, i.e. something like
a{3,} -> a{3}a*
The arguments to this function correspond to the REPETITION slots of
the same name."
(declare #.*standard-optimize-settings*)
(declare (fixnum minimum)
(type (or fixnum null) maximum))
(when maximum
(when (zerop maximum)
(return-from maybe-split-repetition
(make-instance 'void)))
(when (= 1 minimum maximum)
(return-from maybe-split-repetition
regex)))
first set up the constant part of the repetition
(let ((constant-repetition (if (plusp minimum)
(make-instance 'repetition
:regex (copy-regex regex)
:greedyp greedyp
:minimum minimum
:maximum minimum
:min-len min-len
:len length
:contains-register-p reg-seen)
nil)))
(when (and maximum
(= maximum minimum))
(return-from maybe-split-repetition
no varying part needed because min =
constant-repetition))
(let ((varying-repetition
(make-instance 'repetition
:regex regex
:greedyp greedyp
:minimum 0
:maximum (if maximum (- maximum minimum) nil)
:min-len min-len
:len length
:contains-register-p reg-seen)))
(cond ((zerop minimum)
varying-repetition)
((= 1 minimum)
min = 1 , constant part needs no REPETITION wrapped around
(make-instance 'seq
:elements (list (copy-regex regex)
varying-repetition)))
(t
(make-instance 'seq
:elements (list constant-repetition
varying-repetition)))))))
(defun maybe-accumulate (str)
"Accumulate STR into the special variable STARTS-WITH if
ACCUMULATE-START-P (also special) is true and STARTS-WITH is either
NIL or a STR object of the same case mode. Always returns NIL."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p starts-with))
(declare (ftype (function (t) fixnum) len))
(when accumulate-start-p
(etypecase starts-with
(str
STARTS - WITH already holds a STR , so we check if we can
(cond ((eq (case-insensitive-p starts-with)
(case-insensitive-p str))
(setf (len starts-with)
(+ (len starts-with) (len str)))
note that we use SLOT - VALUE because the accessor
STR has a declared FTYPE which does n't fit here
(adjust-array (slot-value starts-with 'str)
(len starts-with)
:fill-pointer t)
(setf (subseq (slot-value starts-with 'str)
(- (len starts-with) (len str)))
(str str)
STR objects that are parts of STARTS - WITH
(skip str) t))
(t (setq accumulate-start-p nil))))
(null
STARTS - WITH is still empty , so we create a new STR object
(setf starts-with
(make-instance 'str
:str ""
:case-insensitive-p (case-insensitive-p str))
INITIALIZE - INSTANCE will coerce the STR to a simple
(slot-value starts-with 'str)
(make-array (len str)
:initial-contents (str str)
:element-type 'character
:fill-pointer t
:adjustable t)
(len starts-with)
(len str)
(skip str) t))
(everything
(setq accumulate-start-p nil))))
nil)
(declaim (inline convert-aux))
(defun convert-aux (parse-tree)
"Converts the parse tree PARSE-TREE into a REGEX object and returns
it. Will also
- split and optimize repetitions,
- accumulate strings or EVERYTHING objects into the special variable
STARTS-WITH,
- keep track of all registers seen in the special variable REG-NUM,
- keep track of all named registers seen in the special variable REG-NAMES
- keep track of the highest backreference seen in the special
variable MAX-BACK-REF,
- maintain and adher to the currently applicable modifiers in the special
variable FLAGS, and
- maybe even wash your car..."
(declare #.*standard-optimize-settings*)
(if (consp parse-tree)
(convert-compound-parse-tree (first parse-tree) parse-tree)
(convert-simple-parse-tree parse-tree)))
(defgeneric convert-compound-parse-tree (token parse-tree &key)
(declare #.*standard-optimize-settings*)
(:documentation "Helper function for CONVERT-AUX which converts
parse trees which are conses and dispatches on TOKEN which is the
first element of the parse tree.")
(:method ((token t) parse-tree &key)
(signal-syntax-error "Unknown token ~A in parse-tree." token)))
(defmethod convert-compound-parse-tree ((token (eql :sequence)) parse-tree &key)
"The case for parse trees like \(:SEQUENCE {<regex>}*)."
(declare #.*standard-optimize-settings*)
(cond ((cddr parse-tree)
( MAPCAR ' CONVERT - AUX ( REST PARSE - TREE ) )
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq :elements (rest parse-tree)))
(t (convert-aux (second parse-tree)))))
(defmethod convert-compound-parse-tree ((token (eql :group)) parse-tree &key)
"The case for parse trees like \(:GROUP {<regex>}*).
This is a syntactical construct equivalent to :SEQUENCE intended to
keep the effect of modifiers local."
(declare #.*standard-optimize-settings*)
(declare (special flags))
make a local copy of FLAGS and shadow the global value while we
(let ((flags (copy-list flags)))
(declare (special flags))
(cond ((cddr parse-tree)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq :elements (rest parse-tree)))
(t (convert-aux (second parse-tree))))))
(defmethod convert-compound-parse-tree ((token (eql :alternation)) parse-tree &key)
"The case for \(:ALTERNATION {<regex>}*)."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'alternation :choices (rest parse-tree)))
(defmethod convert-compound-parse-tree ((token (eql :branch)) parse-tree &key)
"The case for \(:BRANCH <test> <regex>).
an alternation it must have one or two choices."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(let* ((test-candidate (second parse-tree))
(test (cond ((numberp test-candidate)
(when (zerop (the fixnum test-candidate))
(signal-syntax-error "Register 0 doesn't exist: ~S." parse-tree))
(1- (the fixnum test-candidate)))
(t (convert-aux test-candidate))))
(alternations (convert-aux (third parse-tree))))
(when (and (not (numberp test))
(not (typep test 'lookahead))
(not (typep test 'lookbehind)))
(signal-syntax-error "Branch test must be look-ahead, look-behind or number: ~S." parse-tree))
(typecase alternations
(alternation
(case (length (choices alternations))
((0)
(signal-syntax-error "No choices in branch: ~S." parse-tree))
((1)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))))
((2)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))
:else-regex (second
(choices alternations))))
(otherwise
(signal-syntax-error "Too much choices in branch: ~S." parse-tree))))
(t
(make-instance 'branch
:test test
:then-regex alternations)))))
(defmethod convert-compound-parse-tree ((token (eql :positive-lookahead)) parse-tree &key)
"The case for \(:POSITIVE-LOOKAHEAD <regex>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
(setq accumulate-start-p nil)
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'lookahead
:regex (convert-aux (second parse-tree))
:positivep t)))
(defmethod convert-compound-parse-tree ((token (eql :negative-lookahead)) parse-tree &key)
"The case for \(:NEGATIVE-LOOKAHEAD <regex>)."
(declare #.*standard-optimize-settings*)
(let ((regex (convert-compound-parse-tree :positive-lookahead parse-tree)))
(setf (slot-value regex 'positivep) nil)
regex))
(defmethod convert-compound-parse-tree ((token (eql :positive-lookbehind)) parse-tree &key)
"The case for \(:POSITIVE-LOOKBEHIND <regex>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
(setq accumulate-start-p nil)
(let* ((flags (copy-list flags))
(regex (convert-aux (second parse-tree)))
(len (regex-length regex)))
(declare (special flags))
(unless len
(signal-syntax-error "Variable length look-behind not implemented \(yet): ~S." parse-tree))
(make-instance 'lookbehind
:regex regex
:positivep t
:len len)))
(defmethod convert-compound-parse-tree ((token (eql :negative-lookbehind)) parse-tree &key)
"The case for \(:NEGATIVE-LOOKBEHIND <regex>)."
(declare #.*standard-optimize-settings*)
(let ((regex (convert-compound-parse-tree :positive-lookbehind parse-tree)))
(setf (slot-value regex 'positivep) nil)
regex))
(defmethod convert-compound-parse-tree ((token (eql :greedy-repetition)) parse-tree &key (greedyp t))
"The case for \(:GREEDY-REPETITION|:NON-GREEDY-REPETITION <min> <max> <regex>).
This function is also used for the non-greedy case in which case it is
called with GREEDYP set to NIL as you would expect."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p starts-with))
(let ((local-accumulate-start-p accumulate-start-p))
(let ((minimum (second parse-tree))
(maximum (third parse-tree)))
(declare (fixnum minimum))
(declare (type (or null fixnum) maximum))
(unless (and maximum
(= 1 minimum maximum))
(setq accumulate-start-p nil))
(let* (reg-seen
(regex (convert-aux (fourth parse-tree)))
(min-len (regex-min-length regex))
(length (regex-length regex)))
the call to CONVERT - AUX above
(declare (special reg-seen))
(when (and local-accumulate-start-p
(not starts-with)
(zerop minimum)
(not maximum))
remember it for ADVANCE - FN ( see the SCAN
(setq starts-with (everythingp regex)))
(if (or (not reg-seen)
(not greedyp)
(not length)
(zerop length)
(and maximum (= minimum maximum)))
( inner ) length , or the length is zero , or the
(maybe-split-repetition regex
greedyp
minimum
maximum
min-len
length
reg-seen)
(remove-registers-p t)
(inner-regex (remove-registers regex))
(inner-repetition
(maybe-split-repetition inner-regex
t
reduce minimum by 1
(if (zerop minimum)
0
(1- minimum))
reduce maximum by 1
(and maximum
(1- maximum))
min-len
length
reg-seen))
(inner-seq
(make-instance 'seq
:elements (list inner-repetition
regex))))
(declare (special remove-registers-p reg-seen))
wrap INNER - SEQ with a greedy
(if (plusp minimum)
inner-seq
(maybe-split-repetition inner-seq
t
0
1
min-len
nil
t))))))))
(defmethod convert-compound-parse-tree ((token (eql :non-greedy-repetition)) parse-tree &key)
"The case for \(:NON-GREEDY-REPETITION <min> <max> <regex>)."
(declare #.*standard-optimize-settings*)
just dispatch to the method above with explicitly set to NIL
(convert-compound-parse-tree :greedy-repetition parse-tree :greedyp nil))
(defmethod convert-compound-parse-tree ((token (eql :register)) parse-tree &key name)
"The case for \(:REGISTER <regex>). Also used for named registers
when NAME is not NIL."
(declare #.*standard-optimize-settings*)
(declare (special flags reg-num reg-names))
assign the current value of REG - NUM to the corresponding slot of
named register update REG - NAMES and set the corresponding name
slot of the REGISTER object too
(let ((flags (copy-list flags))
(stored-reg-num reg-num))
(declare (special flags reg-seen named-reg-seen))
(setq reg-seen t)
(when name (setq named-reg-seen t))
(incf (the fixnum reg-num))
(push name reg-names)
(make-instance 'register
:regex (convert-aux (if name (third parse-tree) (second parse-tree)))
:num stored-reg-num
:name name)))
(defmethod convert-compound-parse-tree ((token (eql :named-register)) parse-tree &key)
"The case for \(:NAMED-REGISTER <regex>)."
(declare #.*standard-optimize-settings*)
(convert-compound-parse-tree :register parse-tree :name (copy-seq (second parse-tree))))
(defmethod convert-compound-parse-tree ((token (eql :filter)) parse-tree &key)
"The case for \(:FILTER <function> &optional <length>)."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'filter
:fn (second parse-tree)
:len (third parse-tree)))
(defmethod convert-compound-parse-tree ((token (eql :standalone)) parse-tree &key)
"The case for \(:STANDALONE <regex>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
(setq accumulate-start-p nil)
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'standalone :regex (convert-aux (second parse-tree)))))
(defmethod convert-compound-parse-tree ((token (eql :back-reference)) parse-tree &key)
"The case for \(:BACK-REFERENCE <number>|<name>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p reg-num reg-names max-back-ref))
(let* ((backref-name (and (stringp (second parse-tree))
(second parse-tree)))
(referred-regs
(when backref-name
(loop for name in reg-names
for reg-index from 0
when (string= name backref-name)
order REG - NUM contains number of ( any ) registers
collect (- reg-num reg-index))))
(backref-number (or (first referred-regs) (second parse-tree))))
(declare (type (or fixnum null) backref-number))
(when (or (not (typep backref-number 'fixnum))
(<= backref-number 0))
(signal-syntax-error "Illegal back-reference: ~S." parse-tree))
stop accumulating into STARTS - WITH and increase MAX - BACK - REF if
(setq accumulate-start-p nil
max-back-ref (max (the fixnum max-back-ref)
backref-number))
(flet ((make-back-ref (backref-number)
(make-instance 'back-reference
:num (1- backref-number)
:case-insensitive-p (case-insensitive-mode-p flags)
backref - name is NIL or string , safe to copy
:name (copy-seq backref-name))))
(cond
((cdr referred-regs)
any of them , starting with the most recent first
(make-instance 'alternation
:choices (loop
for reg-index in referred-regs
collect (make-back-ref reg-index))))
simple case - backref corresponds to only one register
(t
(make-back-ref backref-number))))))
(defmethod convert-compound-parse-tree ((token (eql :regex)) parse-tree &key)
"The case for \(:REGEX <string>)."
(declare #.*standard-optimize-settings*)
(convert-aux (parse-string (second parse-tree))))
(defmethod convert-compound-parse-tree ((token (eql :char-class)) parse-tree &key invertedp)
"The case for \(:CHAR-CLASS {<item>}*) where item is one of
- a character,
- a character range: \(:RANGE <char1> <char2>), or
- a special char class symbol like :DIGIT-CHAR-CLASS.
Also used for inverted char classes when INVERTEDP is true."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
(let ((test-function
(create-optimized-test-function
(convert-char-class-to-test-function (rest parse-tree)
invertedp
(case-insensitive-mode-p flags)))))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function test-function)))
(defmethod convert-compound-parse-tree ((token (eql :inverted-char-class)) parse-tree &key)
"The case for \(:INVERTED-CHAR-CLASS {<item>}*)."
(declare #.*standard-optimize-settings*)
(convert-compound-parse-tree :char-class parse-tree :invertedp t))
(defmethod convert-compound-parse-tree ((token (eql :property)) parse-tree &key)
"The case for \(:PROPERTY <name>) where <name> is a string."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (resolve-property (second parse-tree))))
(defmethod convert-compound-parse-tree ((token (eql :inverted-property)) parse-tree &key)
"The case for \(:INVERTED-PROPERTY <name>) where <name> is a string."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* (resolve-property (second parse-tree)))))
(defmethod convert-compound-parse-tree ((token (eql :flags)) parse-tree &key)
"The case for \(:FLAGS {<flag>}*) where flag is a modifier symbol
like :CASE-INSENSITIVE-P."
(declare #.*standard-optimize-settings*)
following :
(mapc #'set-flag (rest parse-tree))
(make-instance 'void))
(defgeneric convert-simple-parse-tree (parse-tree)
(declare #.*standard-optimize-settings*)
(:documentation "Helper function for CONVERT-AUX which converts
parse trees which are atoms.")
(:method ((parse-tree (eql :void)))
(declare #.*standard-optimize-settings*)
(make-instance 'void))
(:method ((parse-tree (eql :word-boundary)))
(declare #.*standard-optimize-settings*)
(make-instance 'word-boundary :negatedp nil))
(:method ((parse-tree (eql :non-word-boundary)))
(declare #.*standard-optimize-settings*)
(make-instance 'word-boundary :negatedp t))
(:method ((parse-tree (eql :everything)))
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'everything :single-line-p (single-line-mode-p flags)))
(:method ((parse-tree (eql :digit-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function #'digit-char-p))
(:method ((parse-tree (eql :word-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function #'word-char-p))
(:method ((parse-tree (eql :whitespace-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function #'whitespacep))
(:method ((parse-tree (eql :non-digit-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* #'digit-char-p)))
(:method ((parse-tree (eql :non-word-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* #'word-char-p)))
(:method ((parse-tree (eql :non-whitespace-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* #'whitespacep)))
(:method ((parse-tree (eql :start-anchor)))
(declare #.*standard-optimize-settings*)
(declare (special flags))
(make-instance 'anchor :startp t :multi-line-p (multi-line-mode-p flags)))
(:method ((parse-tree (eql :end-anchor)))
(declare #.*standard-optimize-settings*)
(declare (special flags))
(make-instance 'anchor :startp nil :multi-line-p (multi-line-mode-p flags)))
(:method ((parse-tree (eql :modeless-start-anchor)))
(declare #.*standard-optimize-settings*)
(make-instance 'anchor :startp t))
(:method ((parse-tree (eql :modeless-end-anchor)))
(declare #.*standard-optimize-settings*)
(make-instance 'anchor :startp nil))
(:method ((parse-tree (eql :modeless-end-anchor-no-newline)))
(declare #.*standard-optimize-settings*)
(make-instance 'anchor :startp nil :no-newline-p t))
(:method ((parse-tree (eql :case-insensitive-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :case-sensitive-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :multi-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :not-multi-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :single-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :not-single-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void)))
(defmethod convert-simple-parse-tree ((parse-tree string))
(declare #.*standard-optimize-settings*)
(declare (special flags))
turn strings into STR objects and try to accumulate into
(let ((str (make-instance 'str
:str parse-tree
:case-insensitive-p (case-insensitive-mode-p flags))))
(maybe-accumulate str)
str))
(defmethod convert-simple-parse-tree ((parse-tree character))
(declare #.*standard-optimize-settings*)
(convert-simple-parse-tree (string parse-tree)))
(defmethod convert-simple-parse-tree (parse-tree)
"The default method - check if there's a translation."
(declare #.*standard-optimize-settings*)
(let ((translation (and (symbolp parse-tree) (parse-tree-synonym parse-tree))))
(if translation
(convert-aux (copy-tree translation))
(signal-syntax-error "Unknown token ~A in parse tree." parse-tree))))
(defun convert (parse-tree)
"Converts the parse tree PARSE-TREE into an equivalent REGEX object
and returns three values: the REGEX object, the number of registers
seen and an object the regex starts with which is either a STR object
or an EVERYTHING object \(if the regex starts with something like
\".*\") or NIL."
(declare #.*standard-optimize-settings*)
and then calls CONVERT - AUX to do all the work
(let* ((flags (list nil nil nil))
(reg-num 0)
reg-names
named-reg-seen
(accumulate-start-p t)
starts-with
(max-back-ref 0)
(converted-parse-tree (convert-aux parse-tree)))
(declare (special flags reg-num reg-names named-reg-seen
accumulate-start-p starts-with max-back-ref))
(when (> (the fixnum max-back-ref)
(the fixnum reg-num))
(signal-syntax-error "Backreference to register ~A which has not been defined." max-back-ref))
(when (typep starts-with 'str)
(setf (slot-value starts-with 'str)
(coerce (slot-value starts-with 'str)
#+:lispworks 'lw:simple-text-string
#-:lispworks 'simple-string)))
(values converted-parse-tree reg-num starts-with
(when named-reg-seen
(nreverse reg-names)))))
|
7e0d4602460d71169fc4bc3ab7fb247b40434ea18a191ce34226039c9543d879 | Rydgel/Clojure-Instagram-API | creds.clj | (ns instagram.creds
(:use
instagram.oauth)
(:import
(java.util Properties)))
(defn load-config-file
"This loads a config file from the classpath"
[file-name]
(let [file-reader (.. (Thread/currentThread)
(getContextClassLoader)
(getResourceAsStream file-name))
props (Properties.)]
(.load props file-reader)
(into {} props)))
(def ^:dynamic *config* (load-config-file "test.config"))
(defn assert-get
"Get the value from the config, otherwise throw an exception detailing the problem"
[key-name]
(or (get *config* key-name)
(throw (Exception. (format "Please define %s in the resources/test.config file" key-name)))))
Getting the properties from the test.config file
(def ^:dynamic *client-id* (assert-get "client.id"))
(def ^:dynamic *client-secret* (assert-get "client.secret"))
(def ^:dynamic *redirect-uri* (assert-get "client.redirect-uri"))
(def ^:dynamic *access-token* (assert-get "user.access-token"))
(defn make-test-creds
"Makes an Oauth structure that uses an app's credentials"
[]
(make-oauth-creds *client-id*
*client-secret*
*redirect-uri*))
(defn get-test-access-token
"Get the access token for the tests"
[]
*access-token*)
| null | https://raw.githubusercontent.com/Rydgel/Clojure-Instagram-API/f2de2c8b8c3b852bfbb2bca3c4d1a4252f1216bf/test/instagram/creds.clj | clojure | (ns instagram.creds
(:use
instagram.oauth)
(:import
(java.util Properties)))
(defn load-config-file
"This loads a config file from the classpath"
[file-name]
(let [file-reader (.. (Thread/currentThread)
(getContextClassLoader)
(getResourceAsStream file-name))
props (Properties.)]
(.load props file-reader)
(into {} props)))
(def ^:dynamic *config* (load-config-file "test.config"))
(defn assert-get
"Get the value from the config, otherwise throw an exception detailing the problem"
[key-name]
(or (get *config* key-name)
(throw (Exception. (format "Please define %s in the resources/test.config file" key-name)))))
Getting the properties from the test.config file
(def ^:dynamic *client-id* (assert-get "client.id"))
(def ^:dynamic *client-secret* (assert-get "client.secret"))
(def ^:dynamic *redirect-uri* (assert-get "client.redirect-uri"))
(def ^:dynamic *access-token* (assert-get "user.access-token"))
(defn make-test-creds
"Makes an Oauth structure that uses an app's credentials"
[]
(make-oauth-creds *client-id*
*client-secret*
*redirect-uri*))
(defn get-test-access-token
"Get the access token for the tests"
[]
*access-token*)
| |
b564f52509fbba7526a712aea2c4f3a56f05d54a15a15e91219ebfd9ea4c640a | ghc/packages-dph | Config.hs | -- | Top level hard-wired configuration flags.
TODO : This should be generated by the make system
module Data.Array.Parallel.Base.Config
( debugCritical
, debug
, tracePrimEnabled)
where
-- | Enable internal consistency checks for operations that could
-- corrupt the heap.
debugCritical :: Bool
debugCritical = False
-- | Enable internal consistency checks.
-- This is NOT implied by `debugCritical` above. If you want both
-- you need to set both to `True.`
debug :: Bool
debug = False
-- | Print tracing information for each flat array primitive to console.
-- The tracing hooks are in `dph-prim-par:Data.Array.Parallel.Unlifted`
tracePrimEnabled :: Bool
tracePrimEnabled = False
| null | https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-base/Data/Array/Parallel/Base/Config.hs | haskell | | Top level hard-wired configuration flags.
| Enable internal consistency checks for operations that could
corrupt the heap.
| Enable internal consistency checks.
This is NOT implied by `debugCritical` above. If you want both
you need to set both to `True.`
| Print tracing information for each flat array primitive to console.
The tracing hooks are in `dph-prim-par:Data.Array.Parallel.Unlifted` | TODO : This should be generated by the make system
module Data.Array.Parallel.Base.Config
( debugCritical
, debug
, tracePrimEnabled)
where
debugCritical :: Bool
debugCritical = False
debug :: Bool
debug = False
tracePrimEnabled :: Bool
tracePrimEnabled = False
|
9a61308a00f2f5c3d1af1a1827aa2fe92feb6527b9139dc737ab7da800177fb4 | srid/neuron | Open.hs | # LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
module Neuron.CLI.Open
( openLocallyGeneratedFile,
)
where
import Data.Some (foldSome)
import Neuron.CLI.Types (MonadApp, OpenCommand (..), getOutputDir)
import Neuron.Frontend.Route (routeHtmlPath)
import Relude
import System.Directory (doesFileExist)
import System.FilePath ((</>))
import System.Info (os)
import System.Posix.Process (executeFile)
openLocallyGeneratedFile :: (MonadIO m, MonadApp m, MonadFail m) => OpenCommand -> m ()
openLocallyGeneratedFile (OpenCommand route) = do
let relHtmlPath = routeHtmlPath `foldSome` route
opener = if os == "darwin" then "open" else "xdg-open"
htmlPath <- fmap (</> relHtmlPath) getOutputDir
liftIO (doesFileExist htmlPath) >>= \case
False -> do
fail "No generated HTML found. Try runing `neuron gen` first."
True -> do
liftIO $ executeFile opener True [htmlPath] Nothing
| null | https://raw.githubusercontent.com/srid/neuron/1f127b8343dbe05e057688988b289066df1cdedb/src/Neuron/CLI/Open.hs | haskell | # LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
module Neuron.CLI.Open
( openLocallyGeneratedFile,
)
where
import Data.Some (foldSome)
import Neuron.CLI.Types (MonadApp, OpenCommand (..), getOutputDir)
import Neuron.Frontend.Route (routeHtmlPath)
import Relude
import System.Directory (doesFileExist)
import System.FilePath ((</>))
import System.Info (os)
import System.Posix.Process (executeFile)
openLocallyGeneratedFile :: (MonadIO m, MonadApp m, MonadFail m) => OpenCommand -> m ()
openLocallyGeneratedFile (OpenCommand route) = do
let relHtmlPath = routeHtmlPath `foldSome` route
opener = if os == "darwin" then "open" else "xdg-open"
htmlPath <- fmap (</> relHtmlPath) getOutputDir
liftIO (doesFileExist htmlPath) >>= \case
False -> do
fail "No generated HTML found. Try runing `neuron gen` first."
True -> do
liftIO $ executeFile opener True [htmlPath] Nothing
| |
28d4677427c54507217f562d002919157d76d516c95f1b872ee7e4cc40fd3297 | smallhadroncollider/taskell | Card.hs | # LANGUAGE TemplateHaskell #
module Taskell.IO.HTTP.GitHub.Card
( MaybeCard(MaybeCard)
, maybeCardToTask
, content_url
) where
import ClassyPrelude
import Control.Lens (makeLenses, (^.))
import qualified Taskell.Data.Task as T (Task, new)
import Taskell.IO.HTTP.Aeson (deriveFromJSON)
import Taskell.IO.HTTP.GitHub.Utility (cleanUp)
data MaybeCard = MaybeCard
{ _note :: Maybe Text
, _content_url :: Maybe Text
} deriving (Eq, Show)
-- strip underscores from field labels
$(deriveFromJSON ''MaybeCard)
-- create lenses
$(makeLenses ''MaybeCard)
-- operations
maybeCardToTask :: MaybeCard -> Maybe T.Task
maybeCardToTask card = T.new . cleanUp <$> card ^. note
| null | https://raw.githubusercontent.com/smallhadroncollider/taskell/3c731476e9a58ede300cfa83aba412509b132a3e/src/Taskell/IO/HTTP/GitHub/Card.hs | haskell | strip underscores from field labels
create lenses
operations | # LANGUAGE TemplateHaskell #
module Taskell.IO.HTTP.GitHub.Card
( MaybeCard(MaybeCard)
, maybeCardToTask
, content_url
) where
import ClassyPrelude
import Control.Lens (makeLenses, (^.))
import qualified Taskell.Data.Task as T (Task, new)
import Taskell.IO.HTTP.Aeson (deriveFromJSON)
import Taskell.IO.HTTP.GitHub.Utility (cleanUp)
data MaybeCard = MaybeCard
{ _note :: Maybe Text
, _content_url :: Maybe Text
} deriving (Eq, Show)
$(deriveFromJSON ''MaybeCard)
$(makeLenses ''MaybeCard)
maybeCardToTask :: MaybeCard -> Maybe T.Task
maybeCardToTask card = T.new . cleanUp <$> card ^. note
|
2fe175f84ea07d15b0fd9361290e9b2748f8224e04b00301c31ffec3ee404074 | kappamodeler/kappa | experiment.mli | type dep = LESSER_TIME of float | RULE_FLAGS of (string list) | GREATER_TIME of float
type ast = Mult of ast * ast | Add of ast * ast | Div of ast * ast
| Val_float of float | Val_sol of string | Val_kin of string | Val_infinity
type test = Comp of ast*ast | Timeg of float | Timel of float
type ord = VAL of float | INF
(*test = fun fake_rules_indices -> bool*)
= [ ( flg_1,mult_1); ... ;(flg_n;mult_n ) ]
type perturbation = {dep_list: dep list;
test_unfun_list: test list;
test_list: ((int Mods2.StringMap.t) * Rule.Rule_of_int.t -> bool) list; (*rule_of_name,rules*)
modif: Mods2.IntSet.t * Mods2.IntSet.t * (int Mods2.StringMap.t) * Rule.Rule_of_int.t -> Mods2.IntSet.t * Mods2.IntSet.t * Rule.Rule_of_int.t ;
modif_unfun:string*ast;
test_str: string ;
modif_str:string}
type perturbation_unfun =
{dep_list_unfun: dep list;
test_unfun_list_unfun: test list;
modif_unfun_unfun: string*ast;
test_str_unfun: string ;
modif_str_unfun:string}
type t = {
fresh_pert:int;
name_dep: Mods2.IntSet.t Mods2.StringMap.t ; (*pert_dep: [obs_name -> {pert_indices}] *)
activate time_on : pert_id - > time
time_off: float Mods2.IntMap.t ; (*remove time_of: pert_id -> time*)
perturbations: perturbation Mods2.IntMap.t ; (*[pert_indice -> perturbation]*)
}
type t_unfun = {
fresh_pert_unfun:int;
name_dep_unfun: Mods2.IntSet.t Mods2.StringMap.t ; (*pert_dep: [obs_name -> {pert_indices}] *)
activate time_on : pert_id - > time
time_off_unfun: float Mods2.IntMap.t ; (*remove time_of: pert_id -> time*)
perturbations_unfun: perturbation_unfun Mods2.IntMap.t ; (*[pert_indice -> perturbation]*)
}
val unfun: t -> t_unfun
val empty: t
val string_of_perturbation: perturbation -> string
val print: t -> unit
val string_of_ast: ast -> string
val add: perturbation -> t -> t
val eval: float -> ast -> Rule.Rule_of_int.key Mods2.StringMap.t -> Rule.Rule_of_int.t -> ord
val greater: ord -> ord -> bool
val extract_dep: ast -> string list
val smaller: ord -> ord -> bool
| null | https://raw.githubusercontent.com/kappamodeler/kappa/de63d1857898b1fc3b7f112f1027768b851ce14d/simplx_rep/src/kappa/experiment.mli | ocaml | test = fun fake_rules_indices -> bool
rule_of_name,rules
pert_dep: [obs_name -> {pert_indices}]
remove time_of: pert_id -> time
[pert_indice -> perturbation]
pert_dep: [obs_name -> {pert_indices}]
remove time_of: pert_id -> time
[pert_indice -> perturbation] | type dep = LESSER_TIME of float | RULE_FLAGS of (string list) | GREATER_TIME of float
type ast = Mult of ast * ast | Add of ast * ast | Div of ast * ast
| Val_float of float | Val_sol of string | Val_kin of string | Val_infinity
type test = Comp of ast*ast | Timeg of float | Timel of float
type ord = VAL of float | INF
= [ ( flg_1,mult_1); ... ;(flg_n;mult_n ) ]
type perturbation = {dep_list: dep list;
test_unfun_list: test list;
modif: Mods2.IntSet.t * Mods2.IntSet.t * (int Mods2.StringMap.t) * Rule.Rule_of_int.t -> Mods2.IntSet.t * Mods2.IntSet.t * Rule.Rule_of_int.t ;
modif_unfun:string*ast;
test_str: string ;
modif_str:string}
type perturbation_unfun =
{dep_list_unfun: dep list;
test_unfun_list_unfun: test list;
modif_unfun_unfun: string*ast;
test_str_unfun: string ;
modif_str_unfun:string}
type t = {
fresh_pert:int;
activate time_on : pert_id - > time
}
type t_unfun = {
fresh_pert_unfun:int;
activate time_on : pert_id - > time
}
val unfun: t -> t_unfun
val empty: t
val string_of_perturbation: perturbation -> string
val print: t -> unit
val string_of_ast: ast -> string
val add: perturbation -> t -> t
val eval: float -> ast -> Rule.Rule_of_int.key Mods2.StringMap.t -> Rule.Rule_of_int.t -> ord
val greater: ord -> ord -> bool
val extract_dep: ast -> string list
val smaller: ord -> ord -> bool
|
991e6a265b0e8e1c0265de8939ba1eb9ed3b62a0eaa9380447343cf21aaf73ab | TheLortex/ocaml-maelstrom | unique_id.ml | open Maelstrom
let counter = ref 0
let node_id_to_int s =
(* format: "n1" *)
int_of_string (String.sub s 1 (String.length s - 1))
let rec find_ofs = function 0 -> 0 | n -> 1 + find_ofs (n / 2)
(* the goal is to generate globally unique IDs with full availability
even when the network is partioned. By encoding the worker id in
the ID it's possible to do that easily.*)
let () =
Eio_main.run @@ fun env ->
with_init ~stdout:env#stdout ~stdin:env#stdin @@ fun ms ->
Eio.traceln "init!";
let worker_id = node_id_to_int (node ms |> id_of_node) in
let max_worker_id =
nodes ms
|> List.map (fun v -> node_id_to_int (id_of_node v))
|> List.fold_left max 0
in
let offset = find_ofs max_worker_id + 1 in
let generate () =
incr counter;
(!counter lsl offset) + worker_id
in
with_handler ms "generate"
(fun _ ->
Ok (MessageBody.make ~type':"generate_ok" [ ("id", `Int (generate ())) ]))
(fun () -> wait_eof ms)
| null | https://raw.githubusercontent.com/TheLortex/ocaml-maelstrom/90cf1c335751d41fbf54dff7879f1d0a7b0d9735/bin/unique_id.ml | ocaml | format: "n1"
the goal is to generate globally unique IDs with full availability
even when the network is partioned. By encoding the worker id in
the ID it's possible to do that easily. | open Maelstrom
let counter = ref 0
let node_id_to_int s =
int_of_string (String.sub s 1 (String.length s - 1))
let rec find_ofs = function 0 -> 0 | n -> 1 + find_ofs (n / 2)
let () =
Eio_main.run @@ fun env ->
with_init ~stdout:env#stdout ~stdin:env#stdin @@ fun ms ->
Eio.traceln "init!";
let worker_id = node_id_to_int (node ms |> id_of_node) in
let max_worker_id =
nodes ms
|> List.map (fun v -> node_id_to_int (id_of_node v))
|> List.fold_left max 0
in
let offset = find_ofs max_worker_id + 1 in
let generate () =
incr counter;
(!counter lsl offset) + worker_id
in
with_handler ms "generate"
(fun _ ->
Ok (MessageBody.make ~type':"generate_ok" [ ("id", `Int (generate ())) ]))
(fun () -> wait_eof ms)
|
dc04cdba5216e82c0b71c4e63e38e87a871288a6174fb23cf8868046ce6866c1 | andrewzhurov/brawl-haus | events.clj | (ns brawl-haus.events
(:require [clj-time.core :as t]
[clj-time.coerce :as c]
[re-frame.events]
[re-frame.cofx]
[re-frame.fx]
[re-frame.std-interceptors]
[brawl-haus.data :as data]
[re-frame.core :as rf]
[brawl-haus.subs :as subs]
))
(declare drive)
(defn l [desc expr] (println desc expr) expr)
(defn location [state conn-id]
(get-in state [:users conn-id :location]))
(defn navigate [state conn-id location]
(assoc-in state [:users conn-id :location] location))
(defn gen-uuid [] (str (java.util.UUID/randomUUID)))
(defn now [] (java.util.Date.))
(def init-db {:open-races {}
:messages #{}
:subs #{}
:games {:sv {:locations {:station-location {:station {}}}}}})
(def db (atom init-db))
(defn calc-speed [typed-amount start finish]
(let [minutes-passed (/ (t/in-seconds (t/interval (c/from-date start)
(c/from-date finish)))
60)]
(int (/ typed-amount minutes-passed))))
(defn race-to-be [db]
(let [[[_ race]] (filter (fn [[_ {:keys [status]}]] (= :to-be status))
(get db :open-races))]
race))
(defn enter-race [db race-id conn-id]
(-> db
(assoc-in [:open-races race-id :participants conn-id] {})
(navigate conn-id {:location-id :race-panel
:params {:race-id race-id}})))
(defn ensure-race [db conn-id]
(if-not (race-to-be db)
(let [race-id (gen-uuid)
new-race {:id race-id
:participants {}
:status :to-be
:starts-at (-> (t/now) (t/plus (t/seconds 10)) (c/to-date))}]
(future (Thread/sleep 7000)
(swap! brawl-haus.events/db drive [:race/ready-set-go race-id] nil))
(assoc-in db [:open-races race-id] new-race))
db))
(rf/reg-fx
:later-evt
(fn [{:keys [ms evt] :as in}]
(l "later evt: " in)
(Thread/sleep ms)
(rf/dispatch evt)))
Space versus
(defn deep-merge [& vals]
(if (every? map? vals)
(apply merge-with deep-merge vals)
(last vals)))
(def ship-basic-power-hub
{:power-hub {:max 7
:generating 5}})
(def ship-basic-shields
{:systems {:shields {:max 4
:damaged 0
:in-use 0
:charge-time 3000
:powered-since []}}})
(def ship-basic-engines
{:systems {:engines {:max 3
:damaged 0
:in-use 0
:powered-since []}}})
(def ship-basic-weapons
{:systems {:weapons {:max 3
:damaged 0
:in-use 0
:powered-since []}}})
(def ship-burst-laser-2
{:systems {:weapons {:stuff {:burst-laser-2 {:id :burst-laser-2
:slot 1
:name "Burst Laser II"
:required-power 2
:damage 2
:charge-time 2000
:fire-time 500
:charging-since nil
:firing-since nil
:is-selected false}}}}})
(def weapon-basic-laser
{:id :basic-laser
:slot 1
:name "Basic Laser"
:required-power 1
:damage 1
:charge-time 3333
:fire-time 333
:charging-since nil
:firing-since nil
:is-selected false})
(def ship-basic-laser
{:systems {:weapons {:stuff {:basic-laser weapon-basic-laser}}}})
(def basic-ship
(deep-merge
ship-basic-power-hub
ship-basic-shields
ship-basic-engines
ship-basic-weapons
ship-basic-laser
{:cargo {:scrap 20}}))
(defn sv [db]
(get-in db [:games :sv]))
(defn deplete-power [system]
(let [rational-in-use (max (min (- (:max system) (:damaged system)) (:in-use system)) 0)]
(-> system
(assoc :in-use rational-in-use)
(assoc :powered-since (vec (take rational-in-use (:powered-since system)))))))
(defn turn-off-weapons [db ship-id]
(if (get-in db [:games :sv :ship ship-id :systems :weapons])
(update-in db [:games :sv :ship ship-id :systems :weapons :stuff]
(fn [stuff]
(into {} (map (fn [[id a-stuff]]
[id (merge a-stuff
{:charging-since nil
:firing-since nil
:is-selected false})]))
stuff)))
db))
(defn ensure [struct path val]
(update-in struct path #(if (nil? %) val %)))
(def events
(atom
{:drop-my-subs
(fn [db _ conn-id]
(update db :subs #(set (remove (fn [_ subber] (= subber conn-id)) %))))
:race/left-text
(fn [db [_ left-text] conn-id]
(let [is-finished (zero? (count left-text))
race-id (-> (location db conn-id) :params :race-id)
{:keys [race-text starts-at]} (get-in db [:open-races race-id])]
(assoc-in db
[:open-races race-id :participants conn-id]
{:left-chars (count left-text)
:speed (calc-speed (- (count race-text) (count left-text)) starts-at (now))})))
:hiccup-touch/attend
(fn [db _ conn-id]
(navigate db conn-id {:location-id :hiccup-touch}))
:ccc/attend
(fn [db _ conn-id]
(navigate db conn-id {:location-id :ccc-panel}))
:race/ready-set-go
(fn [db [_ race-id] _]
(update-in db [:open-races race-id]
merge {:status :began
:race-text (rand-nth data/long-texts)}))
:race/attend
(fn [current-db _ conn-id]
(let [db-with-race (ensure-race current-db conn-id)]
(enter-race db-with-race (:id (race-to-be db-with-race)) conn-id)))
:reunion/attend
(fn [db _ conn-id]
(navigate db conn-id {:location-id :reunion-panel}))
:chat/add-message
(fn [db [_ text] conn-id]
(update db :messages conj {:text text
:id (gen-uuid)
:sender conn-id
:received-at (now)}))
:chat/set-nick
(fn [db [_ nick] conn-id]
(assoc-in db [:users conn-id :nick] nick))
:subscribe
(fn [db [_ sub] conn-id]
(update db :subs (fn [old] (conj (set old) [sub conn-id]))))
:unsubscribe
(fn [db [_ sub] conn-id]
(update db :subs disj [sub conn-id]))
:conn/on-create
(fn [db [_ {:keys [conn-id conn]}]]
(let [anonymous-user {:nick (rand-nth data/names)
:conn-id conn-id
:conn conn}]
(-> db
(assoc-in [:users conn-id] anonymous-user)
(navigate conn-id {:location-id :home-panel}))))
:conn/on-close
(fn [db [_ conn-id]]
(-> db
(navigate conn-id {:location-id :quit})
(update-in [:users conn-id] dissoc :conn)))
:home/attend
(fn [db _ conn-id]
(navigate db conn-id {:location-id :home-panel}))
:sv/attend
(fn [db [_ {:keys [with-ship]}] conn-id]
(-> db
(navigate conn-id {:location-id :space-versus})
(ensure [:games :sv :ship conn-id] (merge (or with-ship basic-ship)
{:ship-id conn-id}))
(drive [:sv/jump (str (gen-uuid))] conn-id)))
:sv.system/power-up
(fn [db [_ system-id] conn-id]
(let [left-power (subs/left-power db conn-id)
{:keys [max damaged in-use]} (subs/system db conn-id system-id)]
(if (and (> left-power 0)
(> (- (- max damaged) in-use) 0))
(-> db
(update-in [:games :sv :ship conn-id :systems system-id :in-use] inc)
(update-in [:games :sv :ship conn-id :systems system-id :powered-since] conj (t/now)))
db)))
:sv.system/power-down
(fn [db [_ system-id] conn-id]
(let [db (update-in db [:games :sv :ship conn-id :systems system-id]
(fn [{:keys [in-use] :as system}]
(if (> in-use 0)
(-> system
(assoc :in-use (dec in-use))
(update :powered-since (comp vec butlast)))
system)))]
(if (= :weapons system-id)
(turn-off-weapons db conn-id)
db)))
:sv.weapon/power-up
(fn [db [_ stuff-id] conn-id]
(let [weapons-system (subs/system db conn-id :weapons)
consuming-power (->> weapons-system
:stuff
vals
(filter :charging-since)
(map :required-power)
(reduce +))]
(if (>= (- (:in-use weapons-system)
consuming-power)
(get-in weapons-system [:stuff stuff-id :required-power]))
(assoc-in db [:games :sv :ship conn-id :systems :weapons :stuff stuff-id :charging-since] (t/now))
db)))
:sv.weapon/power-down
(fn [db [_ stuff-id] conn-id]
(assoc-in db [:games :sv :ship conn-id :systems :weapons :stuff stuff-id :charging-since] nil))
:sv.weapon/hit
(fn [db [_ target-ship-id target-system-id] conn-id]
(reduce (fn [acc-db {:keys [id status damage]}]
(let [shields-ready? (= :ready (:status (subs/shield-readiness acc-db target-ship-id)))]
(if (= :selected status)
(cond-> acc-db
:fire
(assoc-in [:games :sv :ship conn-id :systems :weapons :stuff id :firing-since] (t/now))
:drop-selection
(assoc-in [:games :sv :ship conn-id :systems :weapons :stuff id :is-selected] false)
shields-ready?
(assoc-in [:games :sv :ship target-ship-id :systems :shields :last-absorption] (t/now))
(not shields-ready?)
(update-in [:games :sv :ship target-ship-id :systems target-system-id]
(fn [system]
(-> system
(update :damaged (fn [current-damage] (min (:max system) (+ current-damage damage))))
(assoc :last-hit-at (t/now))
(deplete-power))))
(and (not shields-ready?)
(= :weapons target-system-id))
(turn-off-weapons target-ship-id))
acc-db)))
db
(subs/weapons-readiness db conn-id)))
:sv.weapon/select
(fn [db [_ stuff-id] conn-id]
(if (= :ready (:status (subs/weapon-readiness db conn-id stuff-id)))
(assoc-in db [:games :sv :ship conn-id :systems :weapons :stuff stuff-id :is-selected] true)
db))
:sv.weapon/unselect
(fn [db [_ stuff-id] conn-id]
(assoc-in db [:games :sv :ship conn-id :systems :weapons :stuff stuff-id :is-selected] false))
:sv/jump
(fn [db [_ location-id] conn-id]
(-> db
(assoc-in [:games :sv :ship conn-id :location-id] (or location-id (gen-uuid)))
(turn-off-weapons conn-id)))
:sv.ship/loot
(fn [db [_ ship-id] conn-id]
(let [amount (get-in db [:games :sv :ship ship-id :cargo :scrap])]
(-> db
(assoc-in [:games :sv :ship ship-id :cargo :scrap] 0)
(update-in [:games :sv :ship conn-id :cargo :scrap] (fn [old] (+ (or old 0) amount))))))
:sv.store/purchase
(fn [db _ conn-id]
(if (>= (subs/derive db [:sv.cargo/scrap] conn-id) 40)
(-> db
(assoc-in [:games :sv :ship conn-id :systems :weapons :stuff :basic-laser2] (merge weapon-basic-laser
{:id :basic-laser2
:slot 2}))
(update-in [:games :sv :ship conn-id :cargo :scrap] - 40))
db))
:frozen-in-time/attend
(fn [db _ conn-id]
(navigate db conn-id {:location-id :frozen-in-time}))}))
(defn drive [db [evt-id :as evt] & params]
(if-let [evt-fn (get @events evt-id)]
(do (println "drive: " (pr-str evt) " " (pr-str params))
(apply evt-fn db evt params))
(println "!!No evt found:" (pr-str evt))))
(defn add-evt [id handler]
(swap! events assoc id handler))
| null | https://raw.githubusercontent.com/andrewzhurov/brawl-haus/7f560c3dcee7b242fda545d87c102471fdb21888/src/clj/brawl_haus/events.clj | clojure | (ns brawl-haus.events
(:require [clj-time.core :as t]
[clj-time.coerce :as c]
[re-frame.events]
[re-frame.cofx]
[re-frame.fx]
[re-frame.std-interceptors]
[brawl-haus.data :as data]
[re-frame.core :as rf]
[brawl-haus.subs :as subs]
))
(declare drive)
(defn l [desc expr] (println desc expr) expr)
(defn location [state conn-id]
(get-in state [:users conn-id :location]))
(defn navigate [state conn-id location]
(assoc-in state [:users conn-id :location] location))
(defn gen-uuid [] (str (java.util.UUID/randomUUID)))
(defn now [] (java.util.Date.))
(def init-db {:open-races {}
:messages #{}
:subs #{}
:games {:sv {:locations {:station-location {:station {}}}}}})
(def db (atom init-db))
(defn calc-speed [typed-amount start finish]
(let [minutes-passed (/ (t/in-seconds (t/interval (c/from-date start)
(c/from-date finish)))
60)]
(int (/ typed-amount minutes-passed))))
(defn race-to-be [db]
(let [[[_ race]] (filter (fn [[_ {:keys [status]}]] (= :to-be status))
(get db :open-races))]
race))
(defn enter-race [db race-id conn-id]
(-> db
(assoc-in [:open-races race-id :participants conn-id] {})
(navigate conn-id {:location-id :race-panel
:params {:race-id race-id}})))
(defn ensure-race [db conn-id]
(if-not (race-to-be db)
(let [race-id (gen-uuid)
new-race {:id race-id
:participants {}
:status :to-be
:starts-at (-> (t/now) (t/plus (t/seconds 10)) (c/to-date))}]
(future (Thread/sleep 7000)
(swap! brawl-haus.events/db drive [:race/ready-set-go race-id] nil))
(assoc-in db [:open-races race-id] new-race))
db))
(rf/reg-fx
:later-evt
(fn [{:keys [ms evt] :as in}]
(l "later evt: " in)
(Thread/sleep ms)
(rf/dispatch evt)))
Space versus
(defn deep-merge [& vals]
(if (every? map? vals)
(apply merge-with deep-merge vals)
(last vals)))
(def ship-basic-power-hub
{:power-hub {:max 7
:generating 5}})
(def ship-basic-shields
{:systems {:shields {:max 4
:damaged 0
:in-use 0
:charge-time 3000
:powered-since []}}})
(def ship-basic-engines
{:systems {:engines {:max 3
:damaged 0
:in-use 0
:powered-since []}}})
(def ship-basic-weapons
{:systems {:weapons {:max 3
:damaged 0
:in-use 0
:powered-since []}}})
(def ship-burst-laser-2
{:systems {:weapons {:stuff {:burst-laser-2 {:id :burst-laser-2
:slot 1
:name "Burst Laser II"
:required-power 2
:damage 2
:charge-time 2000
:fire-time 500
:charging-since nil
:firing-since nil
:is-selected false}}}}})
(def weapon-basic-laser
{:id :basic-laser
:slot 1
:name "Basic Laser"
:required-power 1
:damage 1
:charge-time 3333
:fire-time 333
:charging-since nil
:firing-since nil
:is-selected false})
(def ship-basic-laser
{:systems {:weapons {:stuff {:basic-laser weapon-basic-laser}}}})
(def basic-ship
(deep-merge
ship-basic-power-hub
ship-basic-shields
ship-basic-engines
ship-basic-weapons
ship-basic-laser
{:cargo {:scrap 20}}))
(defn sv [db]
(get-in db [:games :sv]))
(defn deplete-power [system]
(let [rational-in-use (max (min (- (:max system) (:damaged system)) (:in-use system)) 0)]
(-> system
(assoc :in-use rational-in-use)
(assoc :powered-since (vec (take rational-in-use (:powered-since system)))))))
(defn turn-off-weapons [db ship-id]
(if (get-in db [:games :sv :ship ship-id :systems :weapons])
(update-in db [:games :sv :ship ship-id :systems :weapons :stuff]
(fn [stuff]
(into {} (map (fn [[id a-stuff]]
[id (merge a-stuff
{:charging-since nil
:firing-since nil
:is-selected false})]))
stuff)))
db))
(defn ensure [struct path val]
(update-in struct path #(if (nil? %) val %)))
(def events
(atom
{:drop-my-subs
(fn [db _ conn-id]
(update db :subs #(set (remove (fn [_ subber] (= subber conn-id)) %))))
:race/left-text
(fn [db [_ left-text] conn-id]
(let [is-finished (zero? (count left-text))
race-id (-> (location db conn-id) :params :race-id)
{:keys [race-text starts-at]} (get-in db [:open-races race-id])]
(assoc-in db
[:open-races race-id :participants conn-id]
{:left-chars (count left-text)
:speed (calc-speed (- (count race-text) (count left-text)) starts-at (now))})))
:hiccup-touch/attend
(fn [db _ conn-id]
(navigate db conn-id {:location-id :hiccup-touch}))
:ccc/attend
(fn [db _ conn-id]
(navigate db conn-id {:location-id :ccc-panel}))
:race/ready-set-go
(fn [db [_ race-id] _]
(update-in db [:open-races race-id]
merge {:status :began
:race-text (rand-nth data/long-texts)}))
:race/attend
(fn [current-db _ conn-id]
(let [db-with-race (ensure-race current-db conn-id)]
(enter-race db-with-race (:id (race-to-be db-with-race)) conn-id)))
:reunion/attend
(fn [db _ conn-id]
(navigate db conn-id {:location-id :reunion-panel}))
:chat/add-message
(fn [db [_ text] conn-id]
(update db :messages conj {:text text
:id (gen-uuid)
:sender conn-id
:received-at (now)}))
:chat/set-nick
(fn [db [_ nick] conn-id]
(assoc-in db [:users conn-id :nick] nick))
:subscribe
(fn [db [_ sub] conn-id]
(update db :subs (fn [old] (conj (set old) [sub conn-id]))))
:unsubscribe
(fn [db [_ sub] conn-id]
(update db :subs disj [sub conn-id]))
:conn/on-create
(fn [db [_ {:keys [conn-id conn]}]]
(let [anonymous-user {:nick (rand-nth data/names)
:conn-id conn-id
:conn conn}]
(-> db
(assoc-in [:users conn-id] anonymous-user)
(navigate conn-id {:location-id :home-panel}))))
:conn/on-close
(fn [db [_ conn-id]]
(-> db
(navigate conn-id {:location-id :quit})
(update-in [:users conn-id] dissoc :conn)))
:home/attend
(fn [db _ conn-id]
(navigate db conn-id {:location-id :home-panel}))
:sv/attend
(fn [db [_ {:keys [with-ship]}] conn-id]
(-> db
(navigate conn-id {:location-id :space-versus})
(ensure [:games :sv :ship conn-id] (merge (or with-ship basic-ship)
{:ship-id conn-id}))
(drive [:sv/jump (str (gen-uuid))] conn-id)))
:sv.system/power-up
(fn [db [_ system-id] conn-id]
(let [left-power (subs/left-power db conn-id)
{:keys [max damaged in-use]} (subs/system db conn-id system-id)]
(if (and (> left-power 0)
(> (- (- max damaged) in-use) 0))
(-> db
(update-in [:games :sv :ship conn-id :systems system-id :in-use] inc)
(update-in [:games :sv :ship conn-id :systems system-id :powered-since] conj (t/now)))
db)))
:sv.system/power-down
(fn [db [_ system-id] conn-id]
(let [db (update-in db [:games :sv :ship conn-id :systems system-id]
(fn [{:keys [in-use] :as system}]
(if (> in-use 0)
(-> system
(assoc :in-use (dec in-use))
(update :powered-since (comp vec butlast)))
system)))]
(if (= :weapons system-id)
(turn-off-weapons db conn-id)
db)))
:sv.weapon/power-up
(fn [db [_ stuff-id] conn-id]
(let [weapons-system (subs/system db conn-id :weapons)
consuming-power (->> weapons-system
:stuff
vals
(filter :charging-since)
(map :required-power)
(reduce +))]
(if (>= (- (:in-use weapons-system)
consuming-power)
(get-in weapons-system [:stuff stuff-id :required-power]))
(assoc-in db [:games :sv :ship conn-id :systems :weapons :stuff stuff-id :charging-since] (t/now))
db)))
:sv.weapon/power-down
(fn [db [_ stuff-id] conn-id]
(assoc-in db [:games :sv :ship conn-id :systems :weapons :stuff stuff-id :charging-since] nil))
:sv.weapon/hit
(fn [db [_ target-ship-id target-system-id] conn-id]
(reduce (fn [acc-db {:keys [id status damage]}]
(let [shields-ready? (= :ready (:status (subs/shield-readiness acc-db target-ship-id)))]
(if (= :selected status)
(cond-> acc-db
:fire
(assoc-in [:games :sv :ship conn-id :systems :weapons :stuff id :firing-since] (t/now))
:drop-selection
(assoc-in [:games :sv :ship conn-id :systems :weapons :stuff id :is-selected] false)
shields-ready?
(assoc-in [:games :sv :ship target-ship-id :systems :shields :last-absorption] (t/now))
(not shields-ready?)
(update-in [:games :sv :ship target-ship-id :systems target-system-id]
(fn [system]
(-> system
(update :damaged (fn [current-damage] (min (:max system) (+ current-damage damage))))
(assoc :last-hit-at (t/now))
(deplete-power))))
(and (not shields-ready?)
(= :weapons target-system-id))
(turn-off-weapons target-ship-id))
acc-db)))
db
(subs/weapons-readiness db conn-id)))
:sv.weapon/select
(fn [db [_ stuff-id] conn-id]
(if (= :ready (:status (subs/weapon-readiness db conn-id stuff-id)))
(assoc-in db [:games :sv :ship conn-id :systems :weapons :stuff stuff-id :is-selected] true)
db))
:sv.weapon/unselect
(fn [db [_ stuff-id] conn-id]
(assoc-in db [:games :sv :ship conn-id :systems :weapons :stuff stuff-id :is-selected] false))
:sv/jump
(fn [db [_ location-id] conn-id]
(-> db
(assoc-in [:games :sv :ship conn-id :location-id] (or location-id (gen-uuid)))
(turn-off-weapons conn-id)))
:sv.ship/loot
(fn [db [_ ship-id] conn-id]
(let [amount (get-in db [:games :sv :ship ship-id :cargo :scrap])]
(-> db
(assoc-in [:games :sv :ship ship-id :cargo :scrap] 0)
(update-in [:games :sv :ship conn-id :cargo :scrap] (fn [old] (+ (or old 0) amount))))))
:sv.store/purchase
(fn [db _ conn-id]
(if (>= (subs/derive db [:sv.cargo/scrap] conn-id) 40)
(-> db
(assoc-in [:games :sv :ship conn-id :systems :weapons :stuff :basic-laser2] (merge weapon-basic-laser
{:id :basic-laser2
:slot 2}))
(update-in [:games :sv :ship conn-id :cargo :scrap] - 40))
db))
:frozen-in-time/attend
(fn [db _ conn-id]
(navigate db conn-id {:location-id :frozen-in-time}))}))
(defn drive [db [evt-id :as evt] & params]
(if-let [evt-fn (get @events evt-id)]
(do (println "drive: " (pr-str evt) " " (pr-str params))
(apply evt-fn db evt params))
(println "!!No evt found:" (pr-str evt))))
(defn add-evt [id handler]
(swap! events assoc id handler))
| |
a3588be3ad163d8a371dc06a53a49297300d4f5a78abab870a0edefff817ee79 | borgeby/jarl | schema_test.cljc | (ns jarl.config.schema-test
(:require #?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer [deftest testing is]])
[jarl.config.reader :as reader]
[jarl.config.schema :as schema]
[jarl.encoding.json :as json]
[jarl.runtime.environment :as environment]))
(deftest services-array-to-map-conversion-test
(testing "services array is converted to map"
(let [raw {"services"
[{"name" "foo" "url" ""}
{"name" "bar" "url" ""}]}
cfg (reader/json->config (json/write-str raw))
parsed (schema/parse cfg)]
(is (= parsed {:services
{:bar {:response-header-timeout-seconds 10
:tls {:system-ca-required false}
:type ""
:url ""}
:foo {:response-header-timeout-seconds 10
:tls {:system-ca-required false}
:type ""
:url ""}}})))))
(deftest from-string-to-config-test
(testing "full working config"
(let [raw {"services"
{"foo"
{"url" ""
"response_header_timeout_seconds" 5
"headers" {"X-Made-Up" "yes"
"accept-language" "en-US"}}
"bar"
{"url" ":8282"
"credentials"
{"bearer" {"token" "${TOKEN}"}}}}
"bundles"
{"foo"
{"service" "foo"
"resource" "/bundle.tar.gz"
"trigger" "manual"}
"bar"
{"service" "bar"}}
"labels"
{"region" "EU"
"namespace" "foobars"}}
cfg (with-redefs [environment/*env* {"TOKEN" "secret123"}] (reader/json->config (json/write-str raw)))
parsed (schema/parse cfg)]
(is (= parsed {:bundles {:bar {:polling {:max-delay-seconds 120
:min-delay-seconds 60}
:service "bar"
:trigger "periodic"}
:foo {:polling {:max-delay-seconds 120
:min-delay-seconds 60}
:resource "/bundle.tar.gz"
:service "foo"
:trigger "manual"}}
:labels {:namespace "foobars"
:region "EU"}
:services {:bar {:credentials {:bearer {:scheme "Bearer"
:token "secret123"}}
:response-header-timeout-seconds 10
:tls {:system-ca-required false}
:type ""
:url ":8282"}
:foo {:headers {"accept-language" "en-US"
"x-made-up" "yes"}
:response-header-timeout-seconds 5
:tls {:system-ca-required false}
:type ""
:url ""}}})))))
(deftest validation-test
(testing "simple valid"
(let [cfg (reader/json->config (json/write-str {"labels" {"foo" "bar"}}))
parsed (schema/parse cfg)]
(is (= (schema/validate parsed) {:valid true}))))
(testing "simple error"
(let [cfg (reader/json->config (json/write-str {"services" 1}))
parsed (schema/parse cfg)]
(is (= (schema/validate parsed) {:errors {:services ["invalid type"]}
:valid false})))))
(deftest empty-config-test
(testing "parsing empty config"
(let [parsed (schema/parse (reader/json->config (json/write-str {})))]
(is (= parsed {}))
(is (= (schema/validate parsed) {:valid true})))))
| null | https://raw.githubusercontent.com/borgeby/jarl/2659afc6c72afb961cb1e98b779beb2b0b5d79c6/core/src/test/cljc/jarl/config/schema_test.cljc | clojure | (ns jarl.config.schema-test
(:require #?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer [deftest testing is]])
[jarl.config.reader :as reader]
[jarl.config.schema :as schema]
[jarl.encoding.json :as json]
[jarl.runtime.environment :as environment]))
(deftest services-array-to-map-conversion-test
(testing "services array is converted to map"
(let [raw {"services"
[{"name" "foo" "url" ""}
{"name" "bar" "url" ""}]}
cfg (reader/json->config (json/write-str raw))
parsed (schema/parse cfg)]
(is (= parsed {:services
{:bar {:response-header-timeout-seconds 10
:tls {:system-ca-required false}
:type ""
:url ""}
:foo {:response-header-timeout-seconds 10
:tls {:system-ca-required false}
:type ""
:url ""}}})))))
(deftest from-string-to-config-test
(testing "full working config"
(let [raw {"services"
{"foo"
{"url" ""
"response_header_timeout_seconds" 5
"headers" {"X-Made-Up" "yes"
"accept-language" "en-US"}}
"bar"
{"url" ":8282"
"credentials"
{"bearer" {"token" "${TOKEN}"}}}}
"bundles"
{"foo"
{"service" "foo"
"resource" "/bundle.tar.gz"
"trigger" "manual"}
"bar"
{"service" "bar"}}
"labels"
{"region" "EU"
"namespace" "foobars"}}
cfg (with-redefs [environment/*env* {"TOKEN" "secret123"}] (reader/json->config (json/write-str raw)))
parsed (schema/parse cfg)]
(is (= parsed {:bundles {:bar {:polling {:max-delay-seconds 120
:min-delay-seconds 60}
:service "bar"
:trigger "periodic"}
:foo {:polling {:max-delay-seconds 120
:min-delay-seconds 60}
:resource "/bundle.tar.gz"
:service "foo"
:trigger "manual"}}
:labels {:namespace "foobars"
:region "EU"}
:services {:bar {:credentials {:bearer {:scheme "Bearer"
:token "secret123"}}
:response-header-timeout-seconds 10
:tls {:system-ca-required false}
:type ""
:url ":8282"}
:foo {:headers {"accept-language" "en-US"
"x-made-up" "yes"}
:response-header-timeout-seconds 5
:tls {:system-ca-required false}
:type ""
:url ""}}})))))
(deftest validation-test
(testing "simple valid"
(let [cfg (reader/json->config (json/write-str {"labels" {"foo" "bar"}}))
parsed (schema/parse cfg)]
(is (= (schema/validate parsed) {:valid true}))))
(testing "simple error"
(let [cfg (reader/json->config (json/write-str {"services" 1}))
parsed (schema/parse cfg)]
(is (= (schema/validate parsed) {:errors {:services ["invalid type"]}
:valid false})))))
(deftest empty-config-test
(testing "parsing empty config"
(let [parsed (schema/parse (reader/json->config (json/write-str {})))]
(is (= parsed {}))
(is (= (schema/validate parsed) {:valid true})))))
| |
25273749e9f1eec29f44210132876411d26a428869d2efcd87db307a94612d4d | fp-works/2019-winter-Haskell-school | JoinListBuffer.hs | module JoinListBuffer where
import Data.Monoid ()
import Buffer
import JoinList
import Scrabble
import Sized
-- ex4
-- to avoid orphan instance warning
newtype BufferJoinList = BufferJoinList { getJoinList :: JoinList (Score, Size) String }
-- for score and size, we trust that their values have been correctly calculated during construction
getJoinListScore :: JoinList (Score, Size) String -> Score
getJoinListScore = fst . tag
getJoinListSize :: JoinList (Score, Size) String -> Size
getJoinListSize = snd . tag
toLines :: JoinList (Score, Size) String -> [String]
toLines Empty = []
toLines (Single _ s) = [s]
toLines (Append _ j1 j2) = toLines j1 ++ toLines j2
jlToString :: JoinList (Score, Size) String -> String
jlToString = unlines . toLines
fromLines :: [String] -> JoinList (Score, Size) String
fromLines [] = Empty
fromLines [s] = Single ((scoreString s), 1) s
fromLines ls = let l = length ls
divide in half to create a balanced tree
in fromLines l1 +++ fromLines l2
stringToJL :: String -> JoinList (Score, Size) String
stringToJL = fromLines . lines
replaceLineJL :: Int -> String -> JoinList (Score, Size) String -> JoinList (Score, Size) String
replaceLineJL n l jl
| lenAfter == 0 || lenPre /= n = jl
| otherwise = pre +++ newL +++ post
where
pre = takeJ n jl
nAndAfter = dropJ n jl
lenPre = getSize . getJoinListSize $ pre
lenAfter = getSize . getJoinListSize $ nAndAfter
newL = fromLines [l]
post = dropJ 1 nAndAfter
instance Buffer BufferJoinList where
toString = jlToString . getJoinList
fromString = BufferJoinList . stringToJL
line n = indexJ n . getJoinList
replaceLine n l = BufferJoinList . replaceLineJL n l . getJoinList
numLines = getSize . getJoinListSize . getJoinList
value = getScore . getJoinListScore . getJoinList
| null | https://raw.githubusercontent.com/fp-works/2019-winter-Haskell-school/823b67f019b9e7bc0d3be36711c0cc7da4eba7d2/cis194/week7/zehua/src/JoinListBuffer.hs | haskell | ex4
to avoid orphan instance warning
for score and size, we trust that their values have been correctly calculated during construction | module JoinListBuffer where
import Data.Monoid ()
import Buffer
import JoinList
import Scrabble
import Sized
newtype BufferJoinList = BufferJoinList { getJoinList :: JoinList (Score, Size) String }
getJoinListScore :: JoinList (Score, Size) String -> Score
getJoinListScore = fst . tag
getJoinListSize :: JoinList (Score, Size) String -> Size
getJoinListSize = snd . tag
toLines :: JoinList (Score, Size) String -> [String]
toLines Empty = []
toLines (Single _ s) = [s]
toLines (Append _ j1 j2) = toLines j1 ++ toLines j2
jlToString :: JoinList (Score, Size) String -> String
jlToString = unlines . toLines
fromLines :: [String] -> JoinList (Score, Size) String
fromLines [] = Empty
fromLines [s] = Single ((scoreString s), 1) s
fromLines ls = let l = length ls
divide in half to create a balanced tree
in fromLines l1 +++ fromLines l2
stringToJL :: String -> JoinList (Score, Size) String
stringToJL = fromLines . lines
replaceLineJL :: Int -> String -> JoinList (Score, Size) String -> JoinList (Score, Size) String
replaceLineJL n l jl
| lenAfter == 0 || lenPre /= n = jl
| otherwise = pre +++ newL +++ post
where
pre = takeJ n jl
nAndAfter = dropJ n jl
lenPre = getSize . getJoinListSize $ pre
lenAfter = getSize . getJoinListSize $ nAndAfter
newL = fromLines [l]
post = dropJ 1 nAndAfter
instance Buffer BufferJoinList where
toString = jlToString . getJoinList
fromString = BufferJoinList . stringToJL
line n = indexJ n . getJoinList
replaceLine n l = BufferJoinList . replaceLineJL n l . getJoinList
numLines = getSize . getJoinListSize . getJoinList
value = getScore . getJoinListScore . getJoinList
|
eca9b1fc47b8c931762bdd8b2d88063014a4cd25ffdaf63cb0faf30a6f6d88f0 | coccinelle/coccinelle | pretty_print_popl.mli |
* This file is part of Coccinelle , licensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
val pretty_print : Ast_popl.sequence -> unit
val pretty_print_e : Ast_popl.element -> unit
| null | https://raw.githubusercontent.com/coccinelle/coccinelle/57cbff0c5768e22bb2d8c20e8dae74294515c6b3/popl/pretty_print_popl.mli | ocaml |
* This file is part of Coccinelle , licensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
val pretty_print : Ast_popl.sequence -> unit
val pretty_print_e : Ast_popl.element -> unit
| |
a6c36f268228802af5c1a55547bbe03d6555f598299abb0507516b8a9032826a | mauny/the-functional-approach-to-programming | graph.mli |
#open "MLgraph";;
#open "compatibility";;
#open "prelude";;
#open "sketches";;
#open "pictures";;
value fold : ('a -> 'b -> 'a * 'c) -> 'a -> 'b list -> 'a * 'c list;;
value try_find : ('a -> 'b) -> 'a list -> 'b;;
value nth : int -> 'a list -> 'a;;
value substituteNth : int -> (graph * pos -> graph * pos) -> (graph * pos) list -> (graph * pos) list;;
value sqr : float -> float;;
value pSub : point -> point -> point;;
value pAdd : point -> point -> point;;
value pi : float;;
value circlePoint : float -> float -> point;;
value pMult : point -> float -> point;;
value lengthOfLine : point * point -> float;;
value slopeOfLine : point * point -> float;;
value sketchGen : (string * option) list -> float -> sketch -> picture;;
value sketch : float -> sketch -> picture;;
value curvePos : point * point * point * point -> float -> point * float;;
value arrowFormGen : (string * option) list -> point * float -> string -> geom_element list list;;
value textGen : (string * option) list -> string -> picture;;
value text : string -> picture;;
value diagOfFrame : frame -> float;;
value blankSketch : (string * option) list -> sketch -> picture;;
value rectOfFrame : (string * option) list -> frame -> picture;;
value rectangleGen : (string * option) list -> picture -> picture;;
value rectangle : picture -> picture;;
value circOfFrame : (string * option) list -> frame -> picture;;
value circleGen : (string * option) list -> picture -> picture;;
value circle : picture -> picture;;
value ovalOfFrame : (string * option) list -> frame -> picture;;
value ovalGen : (string * option) list -> picture -> picture;;
value oval : picture -> picture;;
value linesOfPoints : (string * option) list -> point list -> ((string * option) list * geom_element list list) list;;
value curveOfPoints : (string * option) list -> (point * float) list -> ((string * option) list * geom_element list list) list;;
value symmetricCurvesOfPoints : (string * option) list -> point * (float * point) list -> ((string * option) list * geom_element list list) list;;
value hullOfPoints : (string * option) list -> point list -> ((string * option) list * geom_element list list) list;;
value degOfDir : dir -> float;;
value transformGraph : transformation -> graph -> graph;;
value graphPoint : string -> graph -> point;;
value graphLineLabel : float * float -> graph -> string -> point;;
value nodeGraph : string -> graph;;
value addLines : graph -> line list -> graph;;
value addPoints : (string * option) list -> graph -> (string * (string * float)) list -> graph;;
value polyGraph : string -> string list -> line list -> graph;;
value tabularGraph : string -> tabStyle -> tabPos list list -> line list -> graph;;
value linkGraphs : graph * string -> graph * string -> line list -> graph;;
value composeGraphs : graph * string * string -> graph * string * string -> line list -> graph;;
value insLineGen : (graph * pos) list -> (string * option) list * string * dir * string -> (graph * pos) list * line;;
value assembleGraphs : graph list -> string list -> ((string * option) list * string * dir * string) list -> graph;;
value pictOfLines : transformation -> float -> (string * option) list -> ((string * option) list * geom_element list list) list -> picture list;;
value skeletonOfGraphGen : (string * option) list -> transformation * float -> graph -> picture list;;
value graphGen : (string * option) list -> graph -> (string * picture) list -> picture;;
value graph : graph -> (string * picture) list -> picture;;
| null | https://raw.githubusercontent.com/mauny/the-functional-approach-to-programming/1ec8bed5d33d3a67bbd67d09afb3f5c3c8978838/cl-75/MLGRAPH.DIR/graph.mli | ocaml |
#open "MLgraph";;
#open "compatibility";;
#open "prelude";;
#open "sketches";;
#open "pictures";;
value fold : ('a -> 'b -> 'a * 'c) -> 'a -> 'b list -> 'a * 'c list;;
value try_find : ('a -> 'b) -> 'a list -> 'b;;
value nth : int -> 'a list -> 'a;;
value substituteNth : int -> (graph * pos -> graph * pos) -> (graph * pos) list -> (graph * pos) list;;
value sqr : float -> float;;
value pSub : point -> point -> point;;
value pAdd : point -> point -> point;;
value pi : float;;
value circlePoint : float -> float -> point;;
value pMult : point -> float -> point;;
value lengthOfLine : point * point -> float;;
value slopeOfLine : point * point -> float;;
value sketchGen : (string * option) list -> float -> sketch -> picture;;
value sketch : float -> sketch -> picture;;
value curvePos : point * point * point * point -> float -> point * float;;
value arrowFormGen : (string * option) list -> point * float -> string -> geom_element list list;;
value textGen : (string * option) list -> string -> picture;;
value text : string -> picture;;
value diagOfFrame : frame -> float;;
value blankSketch : (string * option) list -> sketch -> picture;;
value rectOfFrame : (string * option) list -> frame -> picture;;
value rectangleGen : (string * option) list -> picture -> picture;;
value rectangle : picture -> picture;;
value circOfFrame : (string * option) list -> frame -> picture;;
value circleGen : (string * option) list -> picture -> picture;;
value circle : picture -> picture;;
value ovalOfFrame : (string * option) list -> frame -> picture;;
value ovalGen : (string * option) list -> picture -> picture;;
value oval : picture -> picture;;
value linesOfPoints : (string * option) list -> point list -> ((string * option) list * geom_element list list) list;;
value curveOfPoints : (string * option) list -> (point * float) list -> ((string * option) list * geom_element list list) list;;
value symmetricCurvesOfPoints : (string * option) list -> point * (float * point) list -> ((string * option) list * geom_element list list) list;;
value hullOfPoints : (string * option) list -> point list -> ((string * option) list * geom_element list list) list;;
value degOfDir : dir -> float;;
value transformGraph : transformation -> graph -> graph;;
value graphPoint : string -> graph -> point;;
value graphLineLabel : float * float -> graph -> string -> point;;
value nodeGraph : string -> graph;;
value addLines : graph -> line list -> graph;;
value addPoints : (string * option) list -> graph -> (string * (string * float)) list -> graph;;
value polyGraph : string -> string list -> line list -> graph;;
value tabularGraph : string -> tabStyle -> tabPos list list -> line list -> graph;;
value linkGraphs : graph * string -> graph * string -> line list -> graph;;
value composeGraphs : graph * string * string -> graph * string * string -> line list -> graph;;
value insLineGen : (graph * pos) list -> (string * option) list * string * dir * string -> (graph * pos) list * line;;
value assembleGraphs : graph list -> string list -> ((string * option) list * string * dir * string) list -> graph;;
value pictOfLines : transformation -> float -> (string * option) list -> ((string * option) list * geom_element list list) list -> picture list;;
value skeletonOfGraphGen : (string * option) list -> transformation * float -> graph -> picture list;;
value graphGen : (string * option) list -> graph -> (string * picture) list -> picture;;
value graph : graph -> (string * picture) list -> picture;;
| |
a917c1ca75f79b8800756bbd6b6b6c52fed4216847d254032663083e94ed7231 | macourtney/Conjure | test_view_generator.clj | (ns conjure.script.generators.test-view-generator
(:use clojure.test
conjure.script.generators.view-generator)
(:require [conjure.view.util :as view-util]))
(deftest test-generate-standard-content
(is (generate-standard-content "views.test.show" "[:test]"))) | null | https://raw.githubusercontent.com/macourtney/Conjure/1d6cb22d321ea75af3a6abe2a5bc140ad36e20d1/conjure_script_view/test/conjure/script/generators/test_view_generator.clj | clojure | (ns conjure.script.generators.test-view-generator
(:use clojure.test
conjure.script.generators.view-generator)
(:require [conjure.view.util :as view-util]))
(deftest test-generate-standard-content
(is (generate-standard-content "views.test.show" "[:test]"))) | |
22af99b7cb2b34da0409741d2012b39af7708a78b60634553ec743f1e42a3e05 | uw-unsat/jitsynth | test-no-load.rkt | #lang rosette
(require "synthesis/compiler-query.rkt"
"genc/genc.rkt"
"common/options.rkt")
(require racket/system)
(define args (current-command-line-arguments))
(define dir (~a (vector-ref args 0)))
(define stp-file
(~a dir "/"
(cond
[(>= (vector-length args) 2)
(~a (vector-ref args 1) ".rkt")]
[else "stp.rkt"])))
(synth-compiler-parallel-with-timeout
stp-file
(list #f #t #t #t)
#:cache-dir "load-cchh-off")
(create-cfile
stp-file
#:cache-dir "load-cchh-off")
| null | https://raw.githubusercontent.com/uw-unsat/jitsynth/69529e18d4a8d4dace884bfde91aa26b549523fa/test-no-load.rkt | racket | #lang rosette
(require "synthesis/compiler-query.rkt"
"genc/genc.rkt"
"common/options.rkt")
(require racket/system)
(define args (current-command-line-arguments))
(define dir (~a (vector-ref args 0)))
(define stp-file
(~a dir "/"
(cond
[(>= (vector-length args) 2)
(~a (vector-ref args 1) ".rkt")]
[else "stp.rkt"])))
(synth-compiler-parallel-with-timeout
stp-file
(list #f #t #t #t)
#:cache-dir "load-cchh-off")
(create-cfile
stp-file
#:cache-dir "load-cchh-off")
| |
25c8f2951ecdced21022233bcbb93f03d98ce82a9dca69559b566b46afd130e0 | korya/efuns | twm.ml | (***********************************************************************)
(* *)
(* ____ *)
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
open Options
open Xlib
open Xtypes
open Gwml
open Stdconfig
open Twm_t
open Wob
let load file =
let ic = open_in file in
let lexbuf = Lexing.from_channel ic in
try
let tree = Twm_p.twmrc Twm_l.twmrc lexbuf in
close_in ic;
tree
with
e -> close_in ic; raise e
let cursors =
[
"X_cursor", XC.xc_x_cursor;
"arrow", XC.xc_arrow;
"based_arrow_down", XC.xc_based_arrow_down;
"based_arrow_up", XC.xc_based_arrow_up;
"boat", XC.xc_boat;
"bogosity", XC.xc_bogosity;
"bottom_left_corner", XC.xc_bottom_left_corner;
"bottom_right_corner", XC.xc_bottom_right_corner;
"bottom_side", XC.xc_bottom_side;
"bottom_tee", XC.xc_bottom_tee;
"box_spiral", XC.xc_box_spiral;
"center_ptr", XC.xc_center_ptr;
"circle", XC.xc_circle;
"clock", XC.xc_clock;
"coffee_mug", XC.xc_coffee_mug;
"cross", XC.xc_cross;
"cross_reverse", XC.xc_cross_reverse;
"crosshair", XC.xc_crosshair;
"diamond_cross", XC.xc_diamond_cross;
"dot", XC.xc_dot;
"dotbox", XC.xc_dotbox;
"double_arrow", XC.xc_double_arrow;
"draft_large", XC.xc_draft_large;
"draft_small", XC.xc_draft_small;
"draped_box", XC.xc_draped_box;
"exchange", XC.xc_exchange;
"fleur", XC.xc_fleur;
"gobbler", XC.xc_gobbler;
"gumby", XC.xc_gumby;
"hand1", XC.xc_hand1;
"hand2", XC.xc_hand2;
"heart", XC.xc_heart;
"icon", XC.xc_icon;
"iron_cross", XC.xc_iron_cross;
"left_ptr", XC.xc_left_ptr;
"left_side", XC.xc_left_side;
"left_tee", XC.xc_left_tee;
"leftbutton", XC.xc_leftbutton;
"ll_angle", XC.xc_ll_angle;
"lr_angle", XC.xc_lr_angle;
"man", XC.xc_man;
"middlebutton", XC.xc_middlebutton;
"mouse", XC.xc_mouse;
"pencil", XC.xc_pencil;
"pirate", XC.xc_pirate;
"plus", XC.xc_plus;
"question_arrow", XC.xc_question_arrow;
"right_ptr", XC.xc_right_ptr;
"right_side", XC.xc_right_side;
"right_tee", XC.xc_right_tee;
"rightbutton", XC.xc_rightbutton;
"rtl_logo", XC.xc_rtl_logo;
"sailboat", XC.xc_sailboat;
"sb_down_arrow", XC.xc_sb_down_arrow;
"sb_h_double_arrow", XC.xc_sb_h_double_arrow;
"sb_left_arrow", XC.xc_sb_left_arrow;
"sb_right_arrow", XC.xc_sb_right_arrow;
"sb_up_arrow", XC.xc_sb_up_arrow;
"sb_v_double_arrow", XC.xc_sb_v_double_arrow;
"shuttle", XC.xc_shuttle;
"sizing", XC.xc_sizing;
"spider", XC.xc_spider;
"spraycan", XC.xc_spraycan;
"star", XC.xc_star;
"target", XC.xc_target;
"tcross", XC.xc_tcross;
"top_left_arrow", XC.xc_top_left_arrow;
"top_left_corner", XC.xc_top_left_corner;
"top_right_corner", XC.xc_top_right_corner;
"top_side", XC.xc_top_side;
"top_tee", XC.xc_top_tee;
"trek", XC.xc_trek;
"ul_angle", XC.xc_ul_angle;
"umbrella", XC.xc_umbrella;
"ur_angle", XC.xc_ur_angle;
"watch", XC.xc_watch;
"xterm", XC.xc_xterm;
]
let newFontCursor name = FontCursor (List.assoc name cursors)
let twm_titlebar_width = ref 17
let twm_titlebar_border = ref 1
let twm_pixmap_offset = ref 2
let twm_bordercolor = Client.window_borderpixel
let twm_borderwidth = Client.window_borderwidth
let twm_TitleBackground = title_background
let twm_TitleForeground = title_foreground
let twm_MenuTitleForeground = menu_title_foreground
let twm_MenuTitleBackground = menu_title_background
let twm_FrameCursor = ref (newFontCursor "top_left_arrow")
let twm_TitleCursor = ref (newFontCursor "top_left_arrow")
let twm_IconCursor = ref (newFontCursor "top_left_arrow")
let twm_IconMgrCursor = ref (newFontCursor "top_left_arrow")
let twm_MoveCursor = ref (newFontCursor "fleur")
let twm_MenuCursor = ref (newFontCursor "sb_left_arrow")
let twm_ButtonCursor = ref (newFontCursor "hand2")
let twm_WaitCursor = ref (newFontCursor "watch")
let twm_SelectCursor = ref (newFontCursor "dot")
let twm_DestroyCursor = ref (newFontCursor "pirate")
let twm_WindowKeys = ref []
let twm_TitleKeys = ref []
let twm_IconKeys = ref []
let twm_RootKeys = ref []
let twm_FrameKeys = ref []
let twm_IconMgrKeys = ref []
let createResizePixmap s =
let scr = s.s_scr in
let h = !twm_titlebar_width - (!twm_titlebar_border+ !twm_pixmap_offset) * 2
in
let h = if h < 1 then 1 else h in
let pix = X.createPixmap display scr.scr_root h h 1 in
let gc = X.createGC display pix [GCforeground (id_to_pixel 0)] in
fillRectangle display pix gc 0 0 h h;
let lw = h / 16 in
let lw = if lw = 1 then 0 else lw in
X.changeGC display gc [GCforeground (id_to_pixel 1);
GCline_style LineSolid; GCcap_style CapButt; GCjoin_style JoinMiter;
GCline_width lw];
(* draw the resize button *)
let w = (h * 2) / 3 in
X.polyLine display pix gc Origin [w,0; w,w; 0,w];
let w = w / 2 in
X.polyLine display pix gc Origin [w,0; w,w; 0,w];
X.freeGC display gc;
pix
let createDotPixmap s =
let scr = s.s_scr in
let h = !twm_titlebar_width - !twm_titlebar_border * 2 in
let h = (h * 3) / 4 in
let h = if h < 1 then 1 else h in
let h = if h land 1 = 1 then h-1 else h in
let pix = X.createPixmap display scr.scr_root h h 1 in
let gc = X.createGC display pix
[GCforeground (id_to_pixel 0);
GCline_style LineSolid; GCcap_style CapRound; GCjoin_style JoinRound;
GCline_width (h/2)] in
(* draw the dot button *)
fillRectangle display pix gc 0 0 h h;
X.changeGC display gc [GCforeground (id_to_pixel 1)];
drawSegment display pix gc (h/2) (h/2) (h/2) (h/2);
X.freeGC display gc;
pix
let createMenuIcon s =
let height = 20 in
let scr = s.s_scr in
let h = height in
let w = h * 7 / 8 in
let h = if (h < 1) then 1 else h in
let w = if (w < 1) then 1 else w in
let pix = X.createPixmap display scr.scr_root w h 1 in
let gc = X.createGC display pix [GCforeground (id_to_pixel 0)] in
fillRectangle display pix gc 0 0 w h;
setForeground display gc (id_to_pixel 1);
let ix = 1 in
let iy = 1 in
let ih = h - iy * 2 in
let iw = w - ix * 2 in
let off = ih / 8 in
let mh = ih - off in
let mw = iw - off in
let bw = mh / 16 in
let bw = if (bw == 0 && mw > 2) then 1 else bw in
let tw = mw - bw * 2 in
let th = mh - bw * 2 in
fillRectangle display pix gc ix iy mw mh;
fillRectangle display pix gc (ix + iw - mw) (iy + ih - mh) mw mh;
setForeground display gc (id_to_pixel 0);
fillRectangle display pix gc (ix+bw) (iy+bw) tw th;
setForeground display gc (id_to_pixel 1);
let lw = tw / 2 in
let lw = if ((tw land 1) lxor (lw land 1)) <> 0 then lw + 1 else lw in
let lx = ix + bw + (tw - lw) / 2 in
let lh = th / 2 - bw in
let lh = if ((lh land 1) lxor ((th - bw) land 1)) <>0 then lh +1 else lh in
let ly = iy + bw + (th - bw - lh) / 2 in
let lines = 3 in
let lines = if (lh land 1) <> 0 && lh < 6 then lines-1 else lines in
let dly = lh / (lines - 1) in
let rec iter lines ly =
if lines > 0 then
let lines = lines - 1 in
fillRectangle display pix gc lx ly lw bw;
iter lines (ly + dly)
in
iter lines ly;
X.freeGC display gc;
pix
let dot_pixmap = FromFunction ("twm_dot_pixmap", fun sw ->
createDotPixmap sw.w_screen, noPixmap)
let resize_pixmap = FromFunction ("twm_resize_pixmap", fun sw ->
createResizePixmap sw.w_screen, noPixmap)
let menu_pixmap = FromFunction ("twm_menu_pixmap", fun sw ->
createMenuIcon sw.w_screen, noPixmap)
let twm_menu s () = try Hashtbl.find menus_table ("twmrc:"^s) with _ -> []
let twm_function s w =
try (Hashtbl.find funs_table ("twmrc:"^s)) w with _ -> ()
let delta_stop w =
if Wob.click w.w_screen <> DeltaMove then raise Exit
let ( old_x , old_y ) =
match ! Eloop.last_event with
KeyPressEvent e - > e. Xkey.x_root , e. Xkey.y_root
| KeyReleaseEvent e - > e. Xkey.x_root , e. Xkey.y_root
| ButtonPressEvent e - > e. Xbutton.x_root , e. Xbutton.y_root
| ButtonReleaseEvent e - > e. Xbutton.x_root , e. Xbutton.y_root
| MotionNotifyEvent e - > e. Xmotion.x_root , e. Xmotion.y_root
| EnterNotifyEvent e - > e. Xcrossing.x_root , e. Xcrossing.y_root
| LeaveNotifyEvent e - > e. Xcrossing.x_root , e. Xcrossing.y_root
| _ - > raise Exit
in
let qp = X.queryPointer display w.w_screen.s_scr.scr_root in
if abs(qp.qp_root_x - old_x ) > = ! delta_move_size ||
abs(qp.qp_root_y - old_y ) > = ! delta_move_size then ( ) else
raise Exit
match !Eloop.last_event with
KeyPressEvent e -> e.Xkey.x_root, e.Xkey.y_root
| KeyReleaseEvent e -> e.Xkey.x_root, e.Xkey.y_root
| ButtonPressEvent e -> e.Xbutton.x_root, e.Xbutton.y_root
| ButtonReleaseEvent e -> e.Xbutton.x_root, e.Xbutton.y_root
| MotionNotifyEvent e -> e.Xmotion.x_root, e.Xmotion.y_root
| EnterNotifyEvent e -> e.Xcrossing.x_root, e.Xcrossing.y_root
| LeaveNotifyEvent e -> e.Xcrossing.x_root, e.Xcrossing.y_root
| _ -> raise Exit
in
let qp = X.queryPointer display w.w_screen.s_scr.scr_root in
if abs(qp.qp_root_x - old_x) >= !delta_move_size ||
abs(qp.qp_root_y - old_y) >= !delta_move_size then () else
raise Exit
*)
(* If the current wob is associated with a client, find the associated client, else interact with user to select a window. *)
let twm_action f w =
match f with
| F_AUTORAISE -> ()
| F_BACKICONMGR -> ()
| F_BEEP -> X.bell display 3
| F_BOTTOMZOOM -> ()
| F_CIRCLEDOWN -> ()
| F_CIRCLEUP -> ()
| F_CUTFILE -> ()
| F_DEICONIFY -> ()
| F_DELETE -> Wob.send w.w_top WobDeleteWindow
| F_DELTASTOP -> delta_stop w
| F_DESTROY -> X.killClient display (window_to_id
((User.client_top w).w_oo#client.c_window))
| F_DOWNICONMGR -> ()
| F_FOCUS -> ()
| F_FORCEMOVE -> User.move (User.client_top w) true
| F_FORWICONMGR -> ()
| F_FULLZOOM -> ()
| F_HBZOOM -> ()
| F_HIDEICONMGR -> ()
| F_HORIZOOM -> ()
| F_HTZOOM -> ()
| F_HZOOM -> ()
| F_ICONIFY -> Wob.send (User.client_top w) (WobIconifyRequest true)
| F_IDENTIFY -> Wob.send (User.client_top w) (WobIconifyRequest true)
| F_LEFTICONMGR -> ()
| F_LEFTZOOM -> ()
| F_LOWER -> Wob.send (User.client_top w) WobLowerWindow
| F_MOVE -> User.move (User.client_top w) true
| F_NEXTICONMGR -> ()
| F_NOP -> ()
| F_PREVICONMGR -> ()
| F_QUIT -> Wob.exit_gwml ()
| F_RAISE -> Wob.send (User.client_top w) WobRaiseWindow
| F_RAISELOWER ->
X.configureWindow display (User.client_top w).w_window [CWStackMode Opposite]
| F_REFRESH -> ()
| F_RESIZE -> resize (User.client_top w) false
| F_RESTART -> restart ()
| F_RIGHTICONMGR -> ()
| F_RIGHTZOOM -> ()
| F_SAVEYOURSELF -> ()
| F_SHOWICONMGR -> ()
| F_SORTICONMGR -> ()
| F_TITLE -> ()
| F_TOPZOOM -> ()
| F_TWMRC -> restart ()
| F_UNFOCUS -> ()
| F_UPICONMGR -> ()
| F_VERSION -> ()
| F_VLZOOM -> ()
| F_VRZOOM -> ()
| F_WINREFRESH -> ()
| F_ZOOM -> ()
| F_SCROLLUP ->
let rw = w.w_top.w_parent in
let rg = rw.w_geometry in
!virtual_manager#move w 0 (-rg.height)
| F_SCROLLDOWN ->
let rw = w.w_top.w_parent in
let rg = rw.w_geometry in
!virtual_manager#move w 0 rg.height
| F_SCROLLLEFT ->
let rw = w.w_top.w_parent in
let rg = rw.w_geometry in
!virtual_manager#move w (-rg.width) 0
| F_SCROLLRIGHT ->
let rw = w.w_top.w_parent in
let rg = rw.w_geometry in
!virtual_manager#move w (rg.width) 0
| F_SCROLLHOME ->
let rw = w.w_top.w_parent in
let rg = rw.w_geometry in
let dx, dy = !virtual_manager#current_position w in
!virtual_manager#move w (-dx) (-dy)
let twm_saction f s w =
match f with
| F_COLORMAP -> ()
| F_CUT -> ()
| F_EXEC -> commandw s ()
| F_FILE -> ()
| F_FUNCTION -> twm_function s w
| F_MENU -> let _ = popup_menu w false (twm_menu s ()) in ()
| F_PRIORITY -> ()
| F_SOURCE -> ()
| F_WARPRING -> ()
| F_WARPTO -> ()
| F_WARPTOICONMGR -> ()
| F_WARPTOSCREEN -> ()
let twm_func list w =
let rec iter list =
match list with
[] -> ()
| (Action f) :: tail -> twm_action f w; iter tail
| (ActionString (f,s)) :: tail -> twm_saction f s w; iter tail
in
iter list
let keysym string =
try List.assoc string XK.name_to_keysym with
_ -> Printf.printf "Unkown key binding <%s>" string; print_newline ();
raise Not_found
let install_binding where key action grab =
let key =
key, (match action with
Action f -> twm_action f
| ActionString (f,s) -> twm_saction f s), grab
in
List.iter (fun context ->
match context with
| C_WINDOW -> twm_WindowKeys := key :: !twm_WindowKeys
| C_TITLE -> twm_TitleKeys := key :: !twm_TitleKeys
| C_ICON -> twm_IconKeys := key :: !twm_IconKeys
| C_ROOT -> twm_RootKeys := key :: !twm_RootKeys
| C_FRAME -> twm_FrameKeys := key :: !twm_FrameKeys
| C_ICONMGR -> twm_IconMgrKeys := key :: !twm_IconMgrKeys
| C_ALL ->
twm_WindowKeys := key :: !twm_WindowKeys;
twm_TitleKeys := key :: !twm_TitleKeys;
twm_IconKeys := key :: !twm_IconKeys;
twm_RootKeys := key :: !twm_RootKeys;
twm_FrameKeys := key :: !twm_FrameKeys;
twm_IconMgrKeys := key :: !twm_IconMgrKeys;
| C_NAME win -> ()
) where
let use tree =
List.iter (fun op ->
match op with
Error -> ()
| NoArg keyword ->
begin
match keyword with
F_AUTORELATIVERESIZE -> ()
| F_CLIENTBORDERWIDTH -> ()
| F_DECORATETRANSIENTS -> ()
| F_DONTMOVEOFF -> confine_move =:= true
| F_FORCEICONS -> ()
| F_INTERPOLATEMENUCOLORS -> ()
| F_NOBACKINGSTORE -> ()
| F_NOCASESENSITIVE -> ()
| F_NODEFAULTS -> ()
| F_NOGRABSERVER -> grab_server =:= false
| F_NOICONMANAGERS -> ()
| F_NOMENUSHADOWS -> ()
| F_NORAISEONWARP -> ()
| F_NORAISEONRESIZE -> ()
| F_NORAISEONMOVE -> ()
| F_NORAISEONDEICONIFY -> ()
| F_NOSAVEUNDERS -> ()
| F_NOTITLEFOCUS -> ()
| F_NOVERSION -> ()
| F_OPAQUEMOVE -> opaque_move =:= true
| F_RANDOMPLACEMENT -> ()
| F_RESTARTPREVIOUSSTATE -> ()
| F_SHOWICONMANAGER -> ()
| F_SORTICONMANAGER -> ()
| F_WARPUNMAPPED -> ()
| F_SHOWVIRTUALNAMES -> ()
end
| StringArg (skeyword,string) ->
begin
match skeyword with
F_ICONDIRECTORY -> ()
| F_ICONFONT -> icon_font =:= string
| F_ICONMANAGERFONT -> iconMgr_font =:= string
| F_MAXWINDOWSIZE -> ()
| F_MENUFONT -> menu_font =:= string
| F_RESIZEFONT -> resize_font =:= string
| F_TITLEFONT -> window_font =:= string
| F_UNKNOWNICON -> ()
| F_USEPPOSITION -> ()
| F_VIRTUALDESKTOP -> ()
end
| NumberArg (nkeyword,int) ->
begin
match nkeyword with
F_BORDERWIDTH -> ()
| F_BUTTONINDENT -> ()
| F_CONSTRAINEDMOVETIME -> ()
| F_FRAMEPADDING -> ()
| F_ICONBORDERWIDTH -> icon_borderwidth =:= int
| F_MOVEDELTA -> ()
| F_NPRIORITY -> ()
| F_TITLEBUTTONBORDERWIDTH -> ()
| F_TITLEPADDING -> ()
| F_XORVALUE -> ()
end
| AddIconRegion (string, dir1, dir2, i1, i2) -> ()
| IconMgrGeometry (string, option) -> ()
| ZoomCount int -> ()
| Pixmap_list strings -> ()
| Cursor_list cursors ->
List.iter (fun cursor ->
let where, cursor = match cursor with
NewFontCursor (where, name) -> where,newFontCursor name
| NewBitmapCursor (where, cursor, mask) ->
where, BitmapCursor (cursor,mask)
in
match where with
FrameCursor -> twm_FrameCursor := cursor
| TitleCursor -> twm_TitleCursor := cursor
| IconCursor -> twm_IconCursor := cursor
| IconMgrCursor -> twm_IconMgrCursor := cursor
| ButtonCursor -> twm_ButtonCursor := cursor
| MoveCursor -> twm_MoveCursor := cursor
| ResizeCursor -> User.twm_ResizeCursor := cursor
| WaitCursor -> twm_WaitCursor := cursor
| MenuCursor -> twm_MenuCursor := cursor
| SelectCursor -> twm_SelectCursor := cursor
| DestroyCursor -> twm_DestroyCursor := cursor
) cursors
| Sticky win_list -> ()
| IconifyByUnmapping win_list -> ()
| IconifyByUnmappingAll -> ()
| TitleButton (string, action, bool) -> ()
| ButtonMenu (int, string) ->
install_binding [C_ROOT] (Gwml.Button(int, 0))
(ActionString (F_MENU, string)) false
| ButtonAction (int, action) ->
install_binding [C_ROOT] (Gwml.Button(int, 0))
action false
| Key (string, mods, where, action) ->
(try
install_binding where (Gwml.Key(keysym string, mods)) action
(mods <> 0)
with _ -> ())
| Button (int, mods, where, action) ->
(try
install_binding where (Gwml.Button(int, mods)) action (mods <> 0)
with _ -> ())
| DontIconify win_list -> ()
| IconManagerNoShow win_list -> ()
| IconManagerNoShowAll -> ()
| IconManagerShow win_list -> ()
| IconMgrs iconms -> ()
| NoTitleHighlight win_list -> ()
| NoTitleHighlightAll -> ()
| NoHighlight win_list -> ()
| NoStackMode win_list -> ()
| NoTitlebar win_list -> ()
| NoHighlightAll -> ()
| NoStackModeAll -> ()
| NoTitlebarAll -> ()
| MakeTitle win_list -> ()
| StartIconified win_list -> ()
| AutoRaise win_list -> ()
| RootMenu (string, str_opt1, str_opt2, menus) ->
let menu = List.map (fun (name,action,_,_) ->
match action with
| ActionString (F_MENU,s) -> name, [
ItemPixmap (menu_pixmap, false)
],Menu (twm_menu s)
| Action F_TITLE -> name, [
ItemForeground (fun _ -> !!twm_MenuTitleForeground);
ItemBackground (fun _ -> !!twm_MenuTitleBackground)],
Function (fun w -> ());
| Action f -> name, [], Function (twm_action f)
| ActionString (f,s) -> name, [],Function (twm_saction f s)
) menus in
Hashtbl.add menus_table ("twmrc:"^string) menu
| RootFunction (string, fonction) ->
Hashtbl.add funs_table ("twmrc:"^string) (twm_func fonction)
| IconNames couples -> ()
| ColorList colors ->
List.iter (fun (clkeyword, name, specials) ->
match clkeyword with
F_BORDERCOLOR -> twm_bordercolor =:= name
| F_BORDERTILEBACKGROUND -> ()
| F_BORDERTILEFOREGROUND -> ()
| F_ICONBACKGROUND -> icon_background =:= name
| F_ICONBORDERCOLOR -> ()
| F_ICONFOREGROUND -> icon_foreground =:= name
| F_ICONMANAGERFOREGROUND -> iconMgr_foreground =:= name
| F_ICONMANAGERBACKGROUND -> iconMgr_background =:= name
| F_ICONMANAGERHIGHLIGHT -> ()
| F_TITLEFOREGROUND -> twm_TitleForeground =:= name
| F_TITLEBACKGROUND -> twm_TitleBackground =:= name
| F_DEFAULTBACKGROUND -> Wob.default_background =:= name
| F_DEFAULTFOREGROUND -> Wob.default_foreground =:= name
| F_MENUBACKGROUND -> menu_background =:= name
| F_MENUFOREGROUND -> menu_foreground =:= name
| F_MENUSHADOWCOLOR -> ()
| F_MENUTITLEBACKGROUND -> twm_MenuTitleBackground =:= name
| F_MENUTITLEFOREGROUND -> twm_MenuTitleForeground =:= name
| F_POINTERBACKGROUND -> ()
| F_POINTERFOREGROUND -> ()
| F_PANNERBACKGROUND -> panner_background =:= name
| F_PANNERFOREGROUND -> panner_foreground =:= name
| F_VIRTUALFOREGROUND -> ()
| F_VIRTUALBACKGROUND -> ()
) colors
| GrayscaleList colors -> ()
| Monochrome colors -> ()
| DefaultFunction action -> ()
| WindowFunction action -> ()
| WarpCursorList win_list -> ()
| WarpCursorAll -> ()
| WindowRingList win_list -> ()
| SaveColorList save_colors -> ()
| SqueezeTitleList squeezes -> ()
| SqueezeTitleAll -> ()
| DontSqueezeTitleList win_list -> ()
| DontSqueezeTitleAll -> ()
) tree
open Stddeco
let twm_hook w e =
match e with
WobInit ->
w#set_borderpixel !!twm_bordercolor;
w#set_borderwidth !!twm_borderwidth;
w#set_cursor !twm_FrameCursor;
| _ -> ()
let twm_window sw c =
let label =
let label =
(* if !editable_title then
(new c_ledit c :> Label.label) else
*)
Label.make c.c_name in
label#add_hook (name_update c label);
label#set_min_height (!twm_titlebar_width - !twm_titlebar_border * 2);
label#set_font !!window_font;
label#set_background !!twm_TitleBackground;
label#set_foreground !!twm_TitleForeground;
label#set_extensible_width 2;
label
in
let left_pixmap = Pixmap.make sw dot_pixmap in
left_pixmap#add_hook (fun e ->
match e with
WobButtonPress _ ->
Wob.send left_pixmap#wob.w_top (WobIconifyRequest true)
| _ -> ());
left_pixmap#set_mask (ButtonPressMask:: left_pixmap#mask);
left_pixmap#set_background !!twm_TitleBackground;
left_pixmap#set_cursor !twm_ButtonCursor;
left_pixmap#set_foreground !!twm_TitleForeground;
left_pixmap#set_borderpixel "white";
left_pixmap#set_borderwidth 1;
let right_pixmap = Pixmap.make sw resize_pixmap in
right_pixmap#add_hook (fun e ->
match e with
WobButtonPress _ ->
User.twm_resize left_pixmap#wob.w_top true
| _ -> ());
right_pixmap#set_mask (ButtonPressMask:: right_pixmap#mask);
right_pixmap#set_cursor !twm_ButtonCursor;
right_pixmap#set_background !!twm_TitleBackground;
right_pixmap#set_foreground !!twm_TitleForeground;
right_pixmap#set_borderwidth 1;
right_pixmap#set_borderpixel "white";
let middle = Null.make () in
middle#set_background !!twm_TitleBackground;
middle#set_mask (ButtonPressMask :: middle#mask);
middle#add_hook (fun e ->
let w = middle#wob in
match e with
WobButtonPress e when Wob.click w.w_screen = Double ->
let tw = w.w_top in
Wob.send tw (WobMessage "minimize")
| WobMessage "FocusIn" ->
middle#set_background !!twm_TitleForeground
| WobMessage "FocusOut" ->
middle#set_background !!twm_TitleBackground
| _ -> ());
middle#set_actions (convert_bindings !!title_actions);
label#set_mask (ButtonPressMask :: label#mask);
label#set_actions (convert_bindings !!title_actions);
let bar = Bar.make Horizontal [| Wob.desc left_pixmap;
Wob.desc label;Wob.desc middle; Wob.desc right_pixmap |]
in
bar#set_borderwidth !twm_titlebar_border;
bar#set_background !!twm_TitleBackground;
([twm_hook;c_hook c; icon_manager_hook c], None, None, Some (bar :> wob_desc) , None)
let install_bindings () =
Printf.printf "Twm.install_bindings: disabled ... ";
print_newline ()
(*
title_actions := !twm_TitleKeys;
screen_actions := !twm_RootKeys;
window_actions := !twm_WindowKeys;
*) | null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/gwml/twm.ml | ocaml | *********************************************************************
____
*********************************************************************
draw the resize button
draw the dot button
If the current wob is associated with a client, find the associated client, else interact with user to select a window.
if !editable_title then
(new c_ledit c :> Label.label) else
title_actions := !twm_TitleKeys;
screen_actions := !twm_RootKeys;
window_actions := !twm_WindowKeys;
| Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
open Options
open Xlib
open Xtypes
open Gwml
open Stdconfig
open Twm_t
open Wob
let load file =
let ic = open_in file in
let lexbuf = Lexing.from_channel ic in
try
let tree = Twm_p.twmrc Twm_l.twmrc lexbuf in
close_in ic;
tree
with
e -> close_in ic; raise e
let cursors =
[
"X_cursor", XC.xc_x_cursor;
"arrow", XC.xc_arrow;
"based_arrow_down", XC.xc_based_arrow_down;
"based_arrow_up", XC.xc_based_arrow_up;
"boat", XC.xc_boat;
"bogosity", XC.xc_bogosity;
"bottom_left_corner", XC.xc_bottom_left_corner;
"bottom_right_corner", XC.xc_bottom_right_corner;
"bottom_side", XC.xc_bottom_side;
"bottom_tee", XC.xc_bottom_tee;
"box_spiral", XC.xc_box_spiral;
"center_ptr", XC.xc_center_ptr;
"circle", XC.xc_circle;
"clock", XC.xc_clock;
"coffee_mug", XC.xc_coffee_mug;
"cross", XC.xc_cross;
"cross_reverse", XC.xc_cross_reverse;
"crosshair", XC.xc_crosshair;
"diamond_cross", XC.xc_diamond_cross;
"dot", XC.xc_dot;
"dotbox", XC.xc_dotbox;
"double_arrow", XC.xc_double_arrow;
"draft_large", XC.xc_draft_large;
"draft_small", XC.xc_draft_small;
"draped_box", XC.xc_draped_box;
"exchange", XC.xc_exchange;
"fleur", XC.xc_fleur;
"gobbler", XC.xc_gobbler;
"gumby", XC.xc_gumby;
"hand1", XC.xc_hand1;
"hand2", XC.xc_hand2;
"heart", XC.xc_heart;
"icon", XC.xc_icon;
"iron_cross", XC.xc_iron_cross;
"left_ptr", XC.xc_left_ptr;
"left_side", XC.xc_left_side;
"left_tee", XC.xc_left_tee;
"leftbutton", XC.xc_leftbutton;
"ll_angle", XC.xc_ll_angle;
"lr_angle", XC.xc_lr_angle;
"man", XC.xc_man;
"middlebutton", XC.xc_middlebutton;
"mouse", XC.xc_mouse;
"pencil", XC.xc_pencil;
"pirate", XC.xc_pirate;
"plus", XC.xc_plus;
"question_arrow", XC.xc_question_arrow;
"right_ptr", XC.xc_right_ptr;
"right_side", XC.xc_right_side;
"right_tee", XC.xc_right_tee;
"rightbutton", XC.xc_rightbutton;
"rtl_logo", XC.xc_rtl_logo;
"sailboat", XC.xc_sailboat;
"sb_down_arrow", XC.xc_sb_down_arrow;
"sb_h_double_arrow", XC.xc_sb_h_double_arrow;
"sb_left_arrow", XC.xc_sb_left_arrow;
"sb_right_arrow", XC.xc_sb_right_arrow;
"sb_up_arrow", XC.xc_sb_up_arrow;
"sb_v_double_arrow", XC.xc_sb_v_double_arrow;
"shuttle", XC.xc_shuttle;
"sizing", XC.xc_sizing;
"spider", XC.xc_spider;
"spraycan", XC.xc_spraycan;
"star", XC.xc_star;
"target", XC.xc_target;
"tcross", XC.xc_tcross;
"top_left_arrow", XC.xc_top_left_arrow;
"top_left_corner", XC.xc_top_left_corner;
"top_right_corner", XC.xc_top_right_corner;
"top_side", XC.xc_top_side;
"top_tee", XC.xc_top_tee;
"trek", XC.xc_trek;
"ul_angle", XC.xc_ul_angle;
"umbrella", XC.xc_umbrella;
"ur_angle", XC.xc_ur_angle;
"watch", XC.xc_watch;
"xterm", XC.xc_xterm;
]
let newFontCursor name = FontCursor (List.assoc name cursors)
let twm_titlebar_width = ref 17
let twm_titlebar_border = ref 1
let twm_pixmap_offset = ref 2
let twm_bordercolor = Client.window_borderpixel
let twm_borderwidth = Client.window_borderwidth
let twm_TitleBackground = title_background
let twm_TitleForeground = title_foreground
let twm_MenuTitleForeground = menu_title_foreground
let twm_MenuTitleBackground = menu_title_background
let twm_FrameCursor = ref (newFontCursor "top_left_arrow")
let twm_TitleCursor = ref (newFontCursor "top_left_arrow")
let twm_IconCursor = ref (newFontCursor "top_left_arrow")
let twm_IconMgrCursor = ref (newFontCursor "top_left_arrow")
let twm_MoveCursor = ref (newFontCursor "fleur")
let twm_MenuCursor = ref (newFontCursor "sb_left_arrow")
let twm_ButtonCursor = ref (newFontCursor "hand2")
let twm_WaitCursor = ref (newFontCursor "watch")
let twm_SelectCursor = ref (newFontCursor "dot")
let twm_DestroyCursor = ref (newFontCursor "pirate")
let twm_WindowKeys = ref []
let twm_TitleKeys = ref []
let twm_IconKeys = ref []
let twm_RootKeys = ref []
let twm_FrameKeys = ref []
let twm_IconMgrKeys = ref []
let createResizePixmap s =
let scr = s.s_scr in
let h = !twm_titlebar_width - (!twm_titlebar_border+ !twm_pixmap_offset) * 2
in
let h = if h < 1 then 1 else h in
let pix = X.createPixmap display scr.scr_root h h 1 in
let gc = X.createGC display pix [GCforeground (id_to_pixel 0)] in
fillRectangle display pix gc 0 0 h h;
let lw = h / 16 in
let lw = if lw = 1 then 0 else lw in
X.changeGC display gc [GCforeground (id_to_pixel 1);
GCline_style LineSolid; GCcap_style CapButt; GCjoin_style JoinMiter;
GCline_width lw];
let w = (h * 2) / 3 in
X.polyLine display pix gc Origin [w,0; w,w; 0,w];
let w = w / 2 in
X.polyLine display pix gc Origin [w,0; w,w; 0,w];
X.freeGC display gc;
pix
let createDotPixmap s =
let scr = s.s_scr in
let h = !twm_titlebar_width - !twm_titlebar_border * 2 in
let h = (h * 3) / 4 in
let h = if h < 1 then 1 else h in
let h = if h land 1 = 1 then h-1 else h in
let pix = X.createPixmap display scr.scr_root h h 1 in
let gc = X.createGC display pix
[GCforeground (id_to_pixel 0);
GCline_style LineSolid; GCcap_style CapRound; GCjoin_style JoinRound;
GCline_width (h/2)] in
fillRectangle display pix gc 0 0 h h;
X.changeGC display gc [GCforeground (id_to_pixel 1)];
drawSegment display pix gc (h/2) (h/2) (h/2) (h/2);
X.freeGC display gc;
pix
let createMenuIcon s =
let height = 20 in
let scr = s.s_scr in
let h = height in
let w = h * 7 / 8 in
let h = if (h < 1) then 1 else h in
let w = if (w < 1) then 1 else w in
let pix = X.createPixmap display scr.scr_root w h 1 in
let gc = X.createGC display pix [GCforeground (id_to_pixel 0)] in
fillRectangle display pix gc 0 0 w h;
setForeground display gc (id_to_pixel 1);
let ix = 1 in
let iy = 1 in
let ih = h - iy * 2 in
let iw = w - ix * 2 in
let off = ih / 8 in
let mh = ih - off in
let mw = iw - off in
let bw = mh / 16 in
let bw = if (bw == 0 && mw > 2) then 1 else bw in
let tw = mw - bw * 2 in
let th = mh - bw * 2 in
fillRectangle display pix gc ix iy mw mh;
fillRectangle display pix gc (ix + iw - mw) (iy + ih - mh) mw mh;
setForeground display gc (id_to_pixel 0);
fillRectangle display pix gc (ix+bw) (iy+bw) tw th;
setForeground display gc (id_to_pixel 1);
let lw = tw / 2 in
let lw = if ((tw land 1) lxor (lw land 1)) <> 0 then lw + 1 else lw in
let lx = ix + bw + (tw - lw) / 2 in
let lh = th / 2 - bw in
let lh = if ((lh land 1) lxor ((th - bw) land 1)) <>0 then lh +1 else lh in
let ly = iy + bw + (th - bw - lh) / 2 in
let lines = 3 in
let lines = if (lh land 1) <> 0 && lh < 6 then lines-1 else lines in
let dly = lh / (lines - 1) in
let rec iter lines ly =
if lines > 0 then
let lines = lines - 1 in
fillRectangle display pix gc lx ly lw bw;
iter lines (ly + dly)
in
iter lines ly;
X.freeGC display gc;
pix
let dot_pixmap = FromFunction ("twm_dot_pixmap", fun sw ->
createDotPixmap sw.w_screen, noPixmap)
let resize_pixmap = FromFunction ("twm_resize_pixmap", fun sw ->
createResizePixmap sw.w_screen, noPixmap)
let menu_pixmap = FromFunction ("twm_menu_pixmap", fun sw ->
createMenuIcon sw.w_screen, noPixmap)
let twm_menu s () = try Hashtbl.find menus_table ("twmrc:"^s) with _ -> []
let twm_function s w =
try (Hashtbl.find funs_table ("twmrc:"^s)) w with _ -> ()
let delta_stop w =
if Wob.click w.w_screen <> DeltaMove then raise Exit
let ( old_x , old_y ) =
match ! Eloop.last_event with
KeyPressEvent e - > e. Xkey.x_root , e. Xkey.y_root
| KeyReleaseEvent e - > e. Xkey.x_root , e. Xkey.y_root
| ButtonPressEvent e - > e. Xbutton.x_root , e. Xbutton.y_root
| ButtonReleaseEvent e - > e. Xbutton.x_root , e. Xbutton.y_root
| MotionNotifyEvent e - > e. Xmotion.x_root , e. Xmotion.y_root
| EnterNotifyEvent e - > e. Xcrossing.x_root , e. Xcrossing.y_root
| LeaveNotifyEvent e - > e. Xcrossing.x_root , e. Xcrossing.y_root
| _ - > raise Exit
in
let qp = X.queryPointer display w.w_screen.s_scr.scr_root in
if abs(qp.qp_root_x - old_x ) > = ! delta_move_size ||
abs(qp.qp_root_y - old_y ) > = ! delta_move_size then ( ) else
raise Exit
match !Eloop.last_event with
KeyPressEvent e -> e.Xkey.x_root, e.Xkey.y_root
| KeyReleaseEvent e -> e.Xkey.x_root, e.Xkey.y_root
| ButtonPressEvent e -> e.Xbutton.x_root, e.Xbutton.y_root
| ButtonReleaseEvent e -> e.Xbutton.x_root, e.Xbutton.y_root
| MotionNotifyEvent e -> e.Xmotion.x_root, e.Xmotion.y_root
| EnterNotifyEvent e -> e.Xcrossing.x_root, e.Xcrossing.y_root
| LeaveNotifyEvent e -> e.Xcrossing.x_root, e.Xcrossing.y_root
| _ -> raise Exit
in
let qp = X.queryPointer display w.w_screen.s_scr.scr_root in
if abs(qp.qp_root_x - old_x) >= !delta_move_size ||
abs(qp.qp_root_y - old_y) >= !delta_move_size then () else
raise Exit
*)
let twm_action f w =
match f with
| F_AUTORAISE -> ()
| F_BACKICONMGR -> ()
| F_BEEP -> X.bell display 3
| F_BOTTOMZOOM -> ()
| F_CIRCLEDOWN -> ()
| F_CIRCLEUP -> ()
| F_CUTFILE -> ()
| F_DEICONIFY -> ()
| F_DELETE -> Wob.send w.w_top WobDeleteWindow
| F_DELTASTOP -> delta_stop w
| F_DESTROY -> X.killClient display (window_to_id
((User.client_top w).w_oo#client.c_window))
| F_DOWNICONMGR -> ()
| F_FOCUS -> ()
| F_FORCEMOVE -> User.move (User.client_top w) true
| F_FORWICONMGR -> ()
| F_FULLZOOM -> ()
| F_HBZOOM -> ()
| F_HIDEICONMGR -> ()
| F_HORIZOOM -> ()
| F_HTZOOM -> ()
| F_HZOOM -> ()
| F_ICONIFY -> Wob.send (User.client_top w) (WobIconifyRequest true)
| F_IDENTIFY -> Wob.send (User.client_top w) (WobIconifyRequest true)
| F_LEFTICONMGR -> ()
| F_LEFTZOOM -> ()
| F_LOWER -> Wob.send (User.client_top w) WobLowerWindow
| F_MOVE -> User.move (User.client_top w) true
| F_NEXTICONMGR -> ()
| F_NOP -> ()
| F_PREVICONMGR -> ()
| F_QUIT -> Wob.exit_gwml ()
| F_RAISE -> Wob.send (User.client_top w) WobRaiseWindow
| F_RAISELOWER ->
X.configureWindow display (User.client_top w).w_window [CWStackMode Opposite]
| F_REFRESH -> ()
| F_RESIZE -> resize (User.client_top w) false
| F_RESTART -> restart ()
| F_RIGHTICONMGR -> ()
| F_RIGHTZOOM -> ()
| F_SAVEYOURSELF -> ()
| F_SHOWICONMGR -> ()
| F_SORTICONMGR -> ()
| F_TITLE -> ()
| F_TOPZOOM -> ()
| F_TWMRC -> restart ()
| F_UNFOCUS -> ()
| F_UPICONMGR -> ()
| F_VERSION -> ()
| F_VLZOOM -> ()
| F_VRZOOM -> ()
| F_WINREFRESH -> ()
| F_ZOOM -> ()
| F_SCROLLUP ->
let rw = w.w_top.w_parent in
let rg = rw.w_geometry in
!virtual_manager#move w 0 (-rg.height)
| F_SCROLLDOWN ->
let rw = w.w_top.w_parent in
let rg = rw.w_geometry in
!virtual_manager#move w 0 rg.height
| F_SCROLLLEFT ->
let rw = w.w_top.w_parent in
let rg = rw.w_geometry in
!virtual_manager#move w (-rg.width) 0
| F_SCROLLRIGHT ->
let rw = w.w_top.w_parent in
let rg = rw.w_geometry in
!virtual_manager#move w (rg.width) 0
| F_SCROLLHOME ->
let rw = w.w_top.w_parent in
let rg = rw.w_geometry in
let dx, dy = !virtual_manager#current_position w in
!virtual_manager#move w (-dx) (-dy)
let twm_saction f s w =
match f with
| F_COLORMAP -> ()
| F_CUT -> ()
| F_EXEC -> commandw s ()
| F_FILE -> ()
| F_FUNCTION -> twm_function s w
| F_MENU -> let _ = popup_menu w false (twm_menu s ()) in ()
| F_PRIORITY -> ()
| F_SOURCE -> ()
| F_WARPRING -> ()
| F_WARPTO -> ()
| F_WARPTOICONMGR -> ()
| F_WARPTOSCREEN -> ()
let twm_func list w =
let rec iter list =
match list with
[] -> ()
| (Action f) :: tail -> twm_action f w; iter tail
| (ActionString (f,s)) :: tail -> twm_saction f s w; iter tail
in
iter list
let keysym string =
try List.assoc string XK.name_to_keysym with
_ -> Printf.printf "Unkown key binding <%s>" string; print_newline ();
raise Not_found
let install_binding where key action grab =
let key =
key, (match action with
Action f -> twm_action f
| ActionString (f,s) -> twm_saction f s), grab
in
List.iter (fun context ->
match context with
| C_WINDOW -> twm_WindowKeys := key :: !twm_WindowKeys
| C_TITLE -> twm_TitleKeys := key :: !twm_TitleKeys
| C_ICON -> twm_IconKeys := key :: !twm_IconKeys
| C_ROOT -> twm_RootKeys := key :: !twm_RootKeys
| C_FRAME -> twm_FrameKeys := key :: !twm_FrameKeys
| C_ICONMGR -> twm_IconMgrKeys := key :: !twm_IconMgrKeys
| C_ALL ->
twm_WindowKeys := key :: !twm_WindowKeys;
twm_TitleKeys := key :: !twm_TitleKeys;
twm_IconKeys := key :: !twm_IconKeys;
twm_RootKeys := key :: !twm_RootKeys;
twm_FrameKeys := key :: !twm_FrameKeys;
twm_IconMgrKeys := key :: !twm_IconMgrKeys;
| C_NAME win -> ()
) where
let use tree =
List.iter (fun op ->
match op with
Error -> ()
| NoArg keyword ->
begin
match keyword with
F_AUTORELATIVERESIZE -> ()
| F_CLIENTBORDERWIDTH -> ()
| F_DECORATETRANSIENTS -> ()
| F_DONTMOVEOFF -> confine_move =:= true
| F_FORCEICONS -> ()
| F_INTERPOLATEMENUCOLORS -> ()
| F_NOBACKINGSTORE -> ()
| F_NOCASESENSITIVE -> ()
| F_NODEFAULTS -> ()
| F_NOGRABSERVER -> grab_server =:= false
| F_NOICONMANAGERS -> ()
| F_NOMENUSHADOWS -> ()
| F_NORAISEONWARP -> ()
| F_NORAISEONRESIZE -> ()
| F_NORAISEONMOVE -> ()
| F_NORAISEONDEICONIFY -> ()
| F_NOSAVEUNDERS -> ()
| F_NOTITLEFOCUS -> ()
| F_NOVERSION -> ()
| F_OPAQUEMOVE -> opaque_move =:= true
| F_RANDOMPLACEMENT -> ()
| F_RESTARTPREVIOUSSTATE -> ()
| F_SHOWICONMANAGER -> ()
| F_SORTICONMANAGER -> ()
| F_WARPUNMAPPED -> ()
| F_SHOWVIRTUALNAMES -> ()
end
| StringArg (skeyword,string) ->
begin
match skeyword with
F_ICONDIRECTORY -> ()
| F_ICONFONT -> icon_font =:= string
| F_ICONMANAGERFONT -> iconMgr_font =:= string
| F_MAXWINDOWSIZE -> ()
| F_MENUFONT -> menu_font =:= string
| F_RESIZEFONT -> resize_font =:= string
| F_TITLEFONT -> window_font =:= string
| F_UNKNOWNICON -> ()
| F_USEPPOSITION -> ()
| F_VIRTUALDESKTOP -> ()
end
| NumberArg (nkeyword,int) ->
begin
match nkeyword with
F_BORDERWIDTH -> ()
| F_BUTTONINDENT -> ()
| F_CONSTRAINEDMOVETIME -> ()
| F_FRAMEPADDING -> ()
| F_ICONBORDERWIDTH -> icon_borderwidth =:= int
| F_MOVEDELTA -> ()
| F_NPRIORITY -> ()
| F_TITLEBUTTONBORDERWIDTH -> ()
| F_TITLEPADDING -> ()
| F_XORVALUE -> ()
end
| AddIconRegion (string, dir1, dir2, i1, i2) -> ()
| IconMgrGeometry (string, option) -> ()
| ZoomCount int -> ()
| Pixmap_list strings -> ()
| Cursor_list cursors ->
List.iter (fun cursor ->
let where, cursor = match cursor with
NewFontCursor (where, name) -> where,newFontCursor name
| NewBitmapCursor (where, cursor, mask) ->
where, BitmapCursor (cursor,mask)
in
match where with
FrameCursor -> twm_FrameCursor := cursor
| TitleCursor -> twm_TitleCursor := cursor
| IconCursor -> twm_IconCursor := cursor
| IconMgrCursor -> twm_IconMgrCursor := cursor
| ButtonCursor -> twm_ButtonCursor := cursor
| MoveCursor -> twm_MoveCursor := cursor
| ResizeCursor -> User.twm_ResizeCursor := cursor
| WaitCursor -> twm_WaitCursor := cursor
| MenuCursor -> twm_MenuCursor := cursor
| SelectCursor -> twm_SelectCursor := cursor
| DestroyCursor -> twm_DestroyCursor := cursor
) cursors
| Sticky win_list -> ()
| IconifyByUnmapping win_list -> ()
| IconifyByUnmappingAll -> ()
| TitleButton (string, action, bool) -> ()
| ButtonMenu (int, string) ->
install_binding [C_ROOT] (Gwml.Button(int, 0))
(ActionString (F_MENU, string)) false
| ButtonAction (int, action) ->
install_binding [C_ROOT] (Gwml.Button(int, 0))
action false
| Key (string, mods, where, action) ->
(try
install_binding where (Gwml.Key(keysym string, mods)) action
(mods <> 0)
with _ -> ())
| Button (int, mods, where, action) ->
(try
install_binding where (Gwml.Button(int, mods)) action (mods <> 0)
with _ -> ())
| DontIconify win_list -> ()
| IconManagerNoShow win_list -> ()
| IconManagerNoShowAll -> ()
| IconManagerShow win_list -> ()
| IconMgrs iconms -> ()
| NoTitleHighlight win_list -> ()
| NoTitleHighlightAll -> ()
| NoHighlight win_list -> ()
| NoStackMode win_list -> ()
| NoTitlebar win_list -> ()
| NoHighlightAll -> ()
| NoStackModeAll -> ()
| NoTitlebarAll -> ()
| MakeTitle win_list -> ()
| StartIconified win_list -> ()
| AutoRaise win_list -> ()
| RootMenu (string, str_opt1, str_opt2, menus) ->
let menu = List.map (fun (name,action,_,_) ->
match action with
| ActionString (F_MENU,s) -> name, [
ItemPixmap (menu_pixmap, false)
],Menu (twm_menu s)
| Action F_TITLE -> name, [
ItemForeground (fun _ -> !!twm_MenuTitleForeground);
ItemBackground (fun _ -> !!twm_MenuTitleBackground)],
Function (fun w -> ());
| Action f -> name, [], Function (twm_action f)
| ActionString (f,s) -> name, [],Function (twm_saction f s)
) menus in
Hashtbl.add menus_table ("twmrc:"^string) menu
| RootFunction (string, fonction) ->
Hashtbl.add funs_table ("twmrc:"^string) (twm_func fonction)
| IconNames couples -> ()
| ColorList colors ->
List.iter (fun (clkeyword, name, specials) ->
match clkeyword with
F_BORDERCOLOR -> twm_bordercolor =:= name
| F_BORDERTILEBACKGROUND -> ()
| F_BORDERTILEFOREGROUND -> ()
| F_ICONBACKGROUND -> icon_background =:= name
| F_ICONBORDERCOLOR -> ()
| F_ICONFOREGROUND -> icon_foreground =:= name
| F_ICONMANAGERFOREGROUND -> iconMgr_foreground =:= name
| F_ICONMANAGERBACKGROUND -> iconMgr_background =:= name
| F_ICONMANAGERHIGHLIGHT -> ()
| F_TITLEFOREGROUND -> twm_TitleForeground =:= name
| F_TITLEBACKGROUND -> twm_TitleBackground =:= name
| F_DEFAULTBACKGROUND -> Wob.default_background =:= name
| F_DEFAULTFOREGROUND -> Wob.default_foreground =:= name
| F_MENUBACKGROUND -> menu_background =:= name
| F_MENUFOREGROUND -> menu_foreground =:= name
| F_MENUSHADOWCOLOR -> ()
| F_MENUTITLEBACKGROUND -> twm_MenuTitleBackground =:= name
| F_MENUTITLEFOREGROUND -> twm_MenuTitleForeground =:= name
| F_POINTERBACKGROUND -> ()
| F_POINTERFOREGROUND -> ()
| F_PANNERBACKGROUND -> panner_background =:= name
| F_PANNERFOREGROUND -> panner_foreground =:= name
| F_VIRTUALFOREGROUND -> ()
| F_VIRTUALBACKGROUND -> ()
) colors
| GrayscaleList colors -> ()
| Monochrome colors -> ()
| DefaultFunction action -> ()
| WindowFunction action -> ()
| WarpCursorList win_list -> ()
| WarpCursorAll -> ()
| WindowRingList win_list -> ()
| SaveColorList save_colors -> ()
| SqueezeTitleList squeezes -> ()
| SqueezeTitleAll -> ()
| DontSqueezeTitleList win_list -> ()
| DontSqueezeTitleAll -> ()
) tree
open Stddeco
let twm_hook w e =
match e with
WobInit ->
w#set_borderpixel !!twm_bordercolor;
w#set_borderwidth !!twm_borderwidth;
w#set_cursor !twm_FrameCursor;
| _ -> ()
let twm_window sw c =
let label =
let label =
Label.make c.c_name in
label#add_hook (name_update c label);
label#set_min_height (!twm_titlebar_width - !twm_titlebar_border * 2);
label#set_font !!window_font;
label#set_background !!twm_TitleBackground;
label#set_foreground !!twm_TitleForeground;
label#set_extensible_width 2;
label
in
let left_pixmap = Pixmap.make sw dot_pixmap in
left_pixmap#add_hook (fun e ->
match e with
WobButtonPress _ ->
Wob.send left_pixmap#wob.w_top (WobIconifyRequest true)
| _ -> ());
left_pixmap#set_mask (ButtonPressMask:: left_pixmap#mask);
left_pixmap#set_background !!twm_TitleBackground;
left_pixmap#set_cursor !twm_ButtonCursor;
left_pixmap#set_foreground !!twm_TitleForeground;
left_pixmap#set_borderpixel "white";
left_pixmap#set_borderwidth 1;
let right_pixmap = Pixmap.make sw resize_pixmap in
right_pixmap#add_hook (fun e ->
match e with
WobButtonPress _ ->
User.twm_resize left_pixmap#wob.w_top true
| _ -> ());
right_pixmap#set_mask (ButtonPressMask:: right_pixmap#mask);
right_pixmap#set_cursor !twm_ButtonCursor;
right_pixmap#set_background !!twm_TitleBackground;
right_pixmap#set_foreground !!twm_TitleForeground;
right_pixmap#set_borderwidth 1;
right_pixmap#set_borderpixel "white";
let middle = Null.make () in
middle#set_background !!twm_TitleBackground;
middle#set_mask (ButtonPressMask :: middle#mask);
middle#add_hook (fun e ->
let w = middle#wob in
match e with
WobButtonPress e when Wob.click w.w_screen = Double ->
let tw = w.w_top in
Wob.send tw (WobMessage "minimize")
| WobMessage "FocusIn" ->
middle#set_background !!twm_TitleForeground
| WobMessage "FocusOut" ->
middle#set_background !!twm_TitleBackground
| _ -> ());
middle#set_actions (convert_bindings !!title_actions);
label#set_mask (ButtonPressMask :: label#mask);
label#set_actions (convert_bindings !!title_actions);
let bar = Bar.make Horizontal [| Wob.desc left_pixmap;
Wob.desc label;Wob.desc middle; Wob.desc right_pixmap |]
in
bar#set_borderwidth !twm_titlebar_border;
bar#set_background !!twm_TitleBackground;
([twm_hook;c_hook c; icon_manager_hook c], None, None, Some (bar :> wob_desc) , None)
let install_bindings () =
Printf.printf "Twm.install_bindings: disabled ... ";
print_newline () |
1f059253deda5026ffd8d601005784d86340d95b0076ead61fdb3b5de8033604 | lspector/Clojush | mux_indexed.clj |
an example problem for clojush , a Push / PushGP system written in Clojure
, , 2010 - 2012
;;
;; This is code for multiplexer problems of various sizes, using integers
to index address and data bits ( which are Boolean values ) .
(ns clojush.problems.boolean.mux-indexed
(:use [clojush.pushgp.pushgp]
[clojush.pushstate]
[clojush.interpreter]
[clojush.random]
[clojure.math.numeric-tower]))
;; We store address bits in a vector on top of the auxiliary stack
;; and data bits in a vector under the address bits vector.
for 11 - mux use 3
for 11 - mux use 8
(defn valid-address-index
[n]
(mod (abs n) number-of-address-bits))
(defn valid-data-index
[n]
(mod (abs n) number-of-data-bits))
(define-registered a ;; push an address bit, indexed by an integer
(fn [state]
(if (:autoconstructing state)
state
(if (not (empty? (:integer state)))
(push-item (nth (first (:auxiliary state))
(valid-address-index (first (:integer state))))
:boolean
(pop-item :integer state))
state))))
(define-registered d ;; push a data bit, indexed by an integer
(fn [state]
(if (:autoconstructing state)
state
(if (not (empty? (:integer state)))
(push-item (nth (second (:auxiliary state))
(valid-data-index (first (:integer state))))
:boolean
(pop-item :integer state))
state))))
(defn int->bits-unmemoized
[i num-bits]
(let [conversion (Integer/toString i 2)]
(concat (repeat (- num-bits (count conversion)) false)
(map #(= \1 %) conversion))))
(def int->bits (memoize int->bits-unmemoized))
(defn bits->int-unmemoized
[bits]
(loop [remaining bits total 0]
(if (empty? remaining)
total
(recur (drop 1 remaining)
(+ total (* (if (first remaining) 1 0) (expt 2 (dec (count remaining)))))))))
(def bits->int (memoize bits->int-unmemoized))
(def argmap
{:error-function (fn [individual]
(let [total-num-bits (+ number-of-address-bits number-of-data-bits)]
(assoc individual
:errors
(doall
(for [i (range (expt 2 total-num-bits))]
(let [bits (int->bits i total-num-bits)
address-bits (vec (take number-of-address-bits bits))
data-bits (vec (drop number-of-address-bits bits))
state (run-push (:program individual)
(push-item address-bits :auxiliary
(push-item data-bits :auxiliary
(make-push-state))))
top-bool (top-item :boolean state)]
(if (= top-bool :no-stack-item)
1000000
(if (= top-bool (nth data-bits (bits->int address-bits)))
0
1))))))))
:atom-generators (concat
[(fn [] (lrand-int (+ number-of-address-bits number-of-data-bits)))]
'(a d exec_if boolean_and boolean_or boolean_not
boolean_dup boolean_swap boolean_pop boolean_rot
integer_add integer_sub integer_mult integer_div integer_mod
integer_dup integer_swap integer_pop integer_rot
))
:max-points 800
:max-genome-size-in-initial-program 200
:genetic-operator-probabilities {:uniform-close-mutation 0.1
:alternation 0.45
:uniform-mutation 0.45}
:parent-selection :tournament
})
| null | https://raw.githubusercontent.com/lspector/Clojush/685b991535607cf942ae1500557171a0739982c3/src/clojush/problems/boolean/mux_indexed.clj | clojure |
This is code for multiplexer problems of various sizes, using integers
We store address bits in a vector on top of the auxiliary stack
and data bits in a vector under the address bits vector.
push an address bit, indexed by an integer
push a data bit, indexed by an integer |
an example problem for clojush , a Push / PushGP system written in Clojure
, , 2010 - 2012
to index address and data bits ( which are Boolean values ) .
(ns clojush.problems.boolean.mux-indexed
(:use [clojush.pushgp.pushgp]
[clojush.pushstate]
[clojush.interpreter]
[clojush.random]
[clojure.math.numeric-tower]))
for 11 - mux use 3
for 11 - mux use 8
(defn valid-address-index
[n]
(mod (abs n) number-of-address-bits))
(defn valid-data-index
[n]
(mod (abs n) number-of-data-bits))
(fn [state]
(if (:autoconstructing state)
state
(if (not (empty? (:integer state)))
(push-item (nth (first (:auxiliary state))
(valid-address-index (first (:integer state))))
:boolean
(pop-item :integer state))
state))))
(fn [state]
(if (:autoconstructing state)
state
(if (not (empty? (:integer state)))
(push-item (nth (second (:auxiliary state))
(valid-data-index (first (:integer state))))
:boolean
(pop-item :integer state))
state))))
(defn int->bits-unmemoized
[i num-bits]
(let [conversion (Integer/toString i 2)]
(concat (repeat (- num-bits (count conversion)) false)
(map #(= \1 %) conversion))))
(def int->bits (memoize int->bits-unmemoized))
(defn bits->int-unmemoized
[bits]
(loop [remaining bits total 0]
(if (empty? remaining)
total
(recur (drop 1 remaining)
(+ total (* (if (first remaining) 1 0) (expt 2 (dec (count remaining)))))))))
(def bits->int (memoize bits->int-unmemoized))
(def argmap
{:error-function (fn [individual]
(let [total-num-bits (+ number-of-address-bits number-of-data-bits)]
(assoc individual
:errors
(doall
(for [i (range (expt 2 total-num-bits))]
(let [bits (int->bits i total-num-bits)
address-bits (vec (take number-of-address-bits bits))
data-bits (vec (drop number-of-address-bits bits))
state (run-push (:program individual)
(push-item address-bits :auxiliary
(push-item data-bits :auxiliary
(make-push-state))))
top-bool (top-item :boolean state)]
(if (= top-bool :no-stack-item)
1000000
(if (= top-bool (nth data-bits (bits->int address-bits)))
0
1))))))))
:atom-generators (concat
[(fn [] (lrand-int (+ number-of-address-bits number-of-data-bits)))]
'(a d exec_if boolean_and boolean_or boolean_not
boolean_dup boolean_swap boolean_pop boolean_rot
integer_add integer_sub integer_mult integer_div integer_mod
integer_dup integer_swap integer_pop integer_rot
))
:max-points 800
:max-genome-size-in-initial-program 200
:genetic-operator-probabilities {:uniform-close-mutation 0.1
:alternation 0.45
:uniform-mutation 0.45}
:parent-selection :tournament
})
|
a62c2e87ac340df9ac6ddcefc0b231255dfd6dee8d10cfacfade59ddc2b4c270 | softwarelanguageslab/maf | R5RS_gambit_perm9-4.scm | ; Changes:
* removed : 1
* added : 0
* swaps : 0
* negated predicates : 1
; * swapped branches: 0
* calls to i d fun : 1
(letrec ((permutations (lambda (x)
(let ((x x)
(perms (list x)))
(letrec ((P (lambda (n)
(if (> n 1)
(letrec ((__do_loop (lambda (j)
(if (zero? j)
(P (- n 1))
(begin
(P (- n 1))
(F n)
(__do_loop (- j 1)))))))
(__do_loop (- n 1)))
#f)))
(F (lambda (n)
(<change>
(set! x (revloop x n (list-tail x n)))
())
(set! perms (cons x perms))))
(revloop (lambda (x n y)
(if (<change> (zero? n) (not (zero? n)))
y
(revloop (cdr x) (- n 1) (cons (car x) y)))))
(list-tail (lambda (x n)
(if (zero? n) x (list-tail (cdr x) (- n 1))))))
(P (length x))
perms))))
(sumlists (lambda (x)
(letrec ((__do_loop (lambda (x sum)
(if (null? x)
sum
(__do_loop
(cdr x)
(letrec ((__do_loop (lambda (y sum)
(if (null? y)
sum
(__do_loop (cdr y) (+ sum (car y)))))))
(__do_loop (car x) sum)))))))
(__do_loop x 0))))
(one..n (lambda (n)
(letrec ((__do_loop (lambda (n p)
(<change>
(if (zero? n) p (__do_loop (- n 1) (cons n p)))
((lambda (x) x) (if (zero? n) p (__do_loop (- n 1) (cons n p))))))))
(__do_loop n ()))))
(factorial (lambda (n)
(if (= n 0) 1 (* n (factorial (- n 1)))))))
(= (sumlists (permutations (one..n 9))) (* (quotient (* 9 (+ 9 1)) 2) (factorial 9)))) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_gambit_perm9-4.scm | scheme | Changes:
* swapped branches: 0 | * removed : 1
* added : 0
* swaps : 0
* negated predicates : 1
* calls to i d fun : 1
(letrec ((permutations (lambda (x)
(let ((x x)
(perms (list x)))
(letrec ((P (lambda (n)
(if (> n 1)
(letrec ((__do_loop (lambda (j)
(if (zero? j)
(P (- n 1))
(begin
(P (- n 1))
(F n)
(__do_loop (- j 1)))))))
(__do_loop (- n 1)))
#f)))
(F (lambda (n)
(<change>
(set! x (revloop x n (list-tail x n)))
())
(set! perms (cons x perms))))
(revloop (lambda (x n y)
(if (<change> (zero? n) (not (zero? n)))
y
(revloop (cdr x) (- n 1) (cons (car x) y)))))
(list-tail (lambda (x n)
(if (zero? n) x (list-tail (cdr x) (- n 1))))))
(P (length x))
perms))))
(sumlists (lambda (x)
(letrec ((__do_loop (lambda (x sum)
(if (null? x)
sum
(__do_loop
(cdr x)
(letrec ((__do_loop (lambda (y sum)
(if (null? y)
sum
(__do_loop (cdr y) (+ sum (car y)))))))
(__do_loop (car x) sum)))))))
(__do_loop x 0))))
(one..n (lambda (n)
(letrec ((__do_loop (lambda (n p)
(<change>
(if (zero? n) p (__do_loop (- n 1) (cons n p)))
((lambda (x) x) (if (zero? n) p (__do_loop (- n 1) (cons n p))))))))
(__do_loop n ()))))
(factorial (lambda (n)
(if (= n 0) 1 (* n (factorial (- n 1)))))))
(= (sumlists (permutations (one..n 9))) (* (quotient (* 9 (+ 9 1)) 2) (factorial 9)))) |
fb30da1b2e8f0f41daa26eea1c27b830f09c65e6cfd403af74c9aa7319d1d3bc | RefactoringTools/HaRe | MultiFun1.expected.hs | module MultiFun1 where
Remove the second parameter from every equation for the function foo .
Remove the second parameter from every equation for the function foo.
-}
foo [] = []
foo xs = [1]
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/RmOneParameter/MultiFun1.expected.hs | haskell | module MultiFun1 where
Remove the second parameter from every equation for the function foo .
Remove the second parameter from every equation for the function foo.
-}
foo [] = []
foo xs = [1]
| |
c2c0e57e5d42ae34efac35eb1dca0f6869dd04a5c368b429f7f89834ae678b25 | mzp/coq-ruby | typeclasses_errors.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : typeclasses_errors.ml 11282 2008 - 07 - 28 11:51:53Z msozeau $ i
(*i*)
open Names
open Decl_kinds
open Term
open Sign
open Evd
open Environ
open Nametab
open Mod_subst
open Topconstr
open Util
open Libnames
(*i*)
type contexts = Parameters | Properties
type typeclass_error =
| NotAClass of constr
| UnboundMethod of global_reference * identifier located (* Class name, method *)
| NoInstance of identifier located * constr list
| UnsatisfiableConstraints of evar_defs * (evar_info * hole_kind) option
| MismatchedContextInstance of contexts * constr_expr list * rel_context (* found, expected *)
exception TypeClassError of env * typeclass_error
let typeclass_error env err = raise (TypeClassError (env, err))
let not_a_class env c = typeclass_error env (NotAClass c)
let unbound_method env cid id = typeclass_error env (UnboundMethod (cid, id))
let no_instance env id args = typeclass_error env (NoInstance (id, args))
let unsatisfiable_constraints env evd ev =
let evd = Evd.undefined_evars evd in
match ev with
| None ->
raise (TypeClassError (env, UnsatisfiableConstraints (evd, None)))
| Some ev ->
let evi = Evd.find (Evd.evars_of evd) ev in
let loc, kind = Evd.evar_source ev evd in
raise (Stdpp.Exc_located (loc, TypeClassError
(env, UnsatisfiableConstraints (evd, Some (evi, kind)))))
let mismatched_ctx_inst env c n m = typeclass_error env (MismatchedContextInstance (c, n, m))
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/pretyping/typeclasses_errors.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
Class name, method
found, expected | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : typeclasses_errors.ml 11282 2008 - 07 - 28 11:51:53Z msozeau $ i
open Names
open Decl_kinds
open Term
open Sign
open Evd
open Environ
open Nametab
open Mod_subst
open Topconstr
open Util
open Libnames
type contexts = Parameters | Properties
type typeclass_error =
| NotAClass of constr
| NoInstance of identifier located * constr list
| UnsatisfiableConstraints of evar_defs * (evar_info * hole_kind) option
exception TypeClassError of env * typeclass_error
let typeclass_error env err = raise (TypeClassError (env, err))
let not_a_class env c = typeclass_error env (NotAClass c)
let unbound_method env cid id = typeclass_error env (UnboundMethod (cid, id))
let no_instance env id args = typeclass_error env (NoInstance (id, args))
let unsatisfiable_constraints env evd ev =
let evd = Evd.undefined_evars evd in
match ev with
| None ->
raise (TypeClassError (env, UnsatisfiableConstraints (evd, None)))
| Some ev ->
let evi = Evd.find (Evd.evars_of evd) ev in
let loc, kind = Evd.evar_source ev evd in
raise (Stdpp.Exc_located (loc, TypeClassError
(env, UnsatisfiableConstraints (evd, Some (evi, kind)))))
let mismatched_ctx_inst env c n m = typeclass_error env (MismatchedContextInstance (c, n, m))
|
03bd25d7eb05ef287008e96d67e87f7025daea53786552ec6d0c40cd215f3a82 | squirrel-prover/squirrel-prover | theory.ml | open Utils
open Env
module SE = SystemExpr
module L = Location
type lsymb = string L.located
(*------------------------------------------------------------------*)
(** {2 Types} *)
type p_ty_i =
| P_message
| P_boolean
| P_index
| P_timestamp
| P_tbase of lsymb
| P_tvar of lsymb
type p_ty = p_ty_i L.located
let pp_p_ty_i fmt = function
| P_message -> Fmt.pf fmt "message"
| P_boolean -> Fmt.pf fmt "boolean"
| P_index -> Fmt.pf fmt "index"
| P_timestamp -> Fmt.pf fmt "timestamp"
| P_tbase s -> Fmt.pf fmt "%s" (L.unloc s)
| P_tvar s -> Fmt.pf fmt "'%s" (L.unloc s)
let pp_p_ty fmt pty = pp_p_ty_i fmt (L.unloc pty)
(*------------------------------------------------------------------*)
* binder
type bnd = lsymb * p_ty
* binders
type bnds = (lsymb * p_ty) list
(*------------------------------------------------------------------*)
* { 2 Terms }
type term_i =
| Tpat
TODO generalize
| Seq of bnds * term
| Find of bnds * term * term * term
| App of lsymb * term list
* An application of a symbol to some arguments which as not been
disambiguated yet ( it can be a name , a function symbol
application , a variable , ... )
[ App(f , t1 : : ... : : tn ) ] is [ f ( t1 , ... , tn ) ]
disambiguated yet (it can be a name, a function symbol
application, a variable, ...)
[App(f,t1 :: ... :: tn)] is [f (t1, ..., tn)] *)
| AppAt of lsymb * term list * term
(** An application of a symbol to some arguments, at a given
timestamp. As for [App _], the head function symbol has not been
disambiguated yet.
[AppAt(f,t1 :: ... :: tn,tau)] is [f (t1, ..., tn)@tau] *)
| ForAll of bnds * term
| Exists of bnds * term
and term = term_i L.located
(*------------------------------------------------------------------*)
let equal_p_ty t t' = match L.unloc t, L.unloc t' with
| P_message , P_message
| P_boolean , P_boolean
| P_index , P_index
| P_timestamp, P_timestamp -> true
| P_tbase b, P_tbase b' -> L.unloc b = L.unloc b'
| P_tvar v, P_tvar v' -> L.unloc v = L.unloc v'
| _, _ -> false
(*------------------------------------------------------------------*)
let equal_bnds l l' =
List.for_all2 (fun (s,k) (s',k') ->
L.unloc s = L.unloc s' && equal_p_ty k k'
) l l'
let rec equal t t' = match L.unloc t, L.unloc t' with
| Diff (a,b), Diff (a',b') ->
equal a a' && equal b b'
| Seq (l, a), Seq (l', a')
| ForAll (l, a), ForAll (l', a')
| Exists (l, a), Exists (l', a') ->
List.length l = List.length l' &&
equal_bnds l l' &&
equal a a'
| Find (l, a, b, c), Find (l', a', b', c') ->
List.length l = List.length l' &&
equal_bnds l l' &&
equals [a; b; c] [a'; b'; c']
| AppAt (s, ts, t), AppAt (s', ts', t') ->
L.unloc s = L.unloc s' &&
equals (t :: ts) (t' :: ts')
| App (s, ts), App (s', ts') ->
L.unloc s = L.unloc s' &&
equals ts ts'
| _ -> false
and equals l l' = List.for_all2 equal l l'
(*------------------------------------------------------------------*)
let var_i loc x : term_i = App (L.mk_loc loc x,[])
let var loc x : term = L.mk_loc loc (var_i loc x)
let var_of_lsymb s : term = var (L.loc s) (L.unloc s)
let destr_var = function
| App (v, []) -> Some v
| _ -> None
(*------------------------------------------------------------------*)
let pp_var_list ppf l =
let rec aux cur_vars (cur_type : p_ty_i) = function
| (v,vty) :: vs when L.unloc vty = cur_type ->
aux ((L.unloc v) :: cur_vars) cur_type vs
| vs ->
if cur_vars <> [] then begin
Fmt.list
~sep:(fun fmt () -> Fmt.pf fmt ",")
Fmt.string ppf (List.rev cur_vars) ;
Fmt.pf ppf ":%a" pp_p_ty_i cur_type ;
if vs <> [] then Fmt.pf ppf ",@,"
end ;
match vs with
| [] -> ()
| (v, vty) :: vs -> aux [L.unloc v] (L.unloc vty) vs
in
aux [] P_message l
let rec pp_term_i ppf t = match t with
| Tpat -> Fmt.pf ppf "_"
| Find (vs,c,t,e) ->
Fmt.pf ppf
"@[%a@ %a@ %a@ %a@ %a@ %a@ %a@ %a@]"
(Printer.kws `TermCondition) "try find"
pp_var_list vs
(Printer.kws `TermCondition) "such that"
pp_term c
(Printer.kws `TermCondition) "in"
pp_term t
(Printer.kws `TermCondition) "else"
pp_term e
| Diff (l,r) ->
Fmt.pf ppf "%a(%a,%a)"
(Printer.kws `TermDiff) "diff"
pp_term l
pp_term r
| App (f,[t1;t2]) when L.unloc f = "exp" ->
Fmt.pf ppf "%a^%a" pp_term t1 pp_term t2
| App (f,[i;t;e]) when L.unloc f = "if" ->
Fmt.pf ppf
"@[%a@ %a@ %a@ %a@ %a@ %a@]"
(Printer.kws `TermCondition) "if"
pp_term i
(Printer.kws `TermCondition) "then"
pp_term t
(Printer.kws `TermCondition) "else"
pp_term e
| App (f, [L.{ pl_desc = App (f1,[bl1;br1])};
L.{ pl_desc = App (f2,[br2;bl2])}])
when L.unloc f = "&&" && L.unloc f1 = "=>" && L.unloc f2 = "=>" &&
bl1 = bl2 && br1 = br2 ->
Fmt.pf ppf "@[<1>(%a@ <=>@ %a)@]"
pp_term bl1 pp_term br1
| App (f,[bl;br]) when Symbols.is_infix_str (L.unloc f) ->
Fmt.pf ppf "@[<1>(%a@ %s@ %a)@]"
pp_term bl (L.unloc f) pp_term br
| App (f,[b]) when L.unloc f = "not" ->
Fmt.pf ppf "not(@[%a@])" pp_term b
| App (f,[]) when L.unloc f = "true" -> Printer.kws `TermBool ppf "True"
| App (f,[]) when L.unloc f = "false" -> Printer.kws `TermBool ppf "False"
| App (f,terms) ->
Fmt.pf ppf "%s%a"
(L.unloc f)
(Utils.pp_list pp_term) terms
| AppAt (f,terms,ts) ->
Fmt.pf ppf "%s%a%a"
(L.unloc f)
(Utils.pp_list pp_term) terms
pp_ts ts
| Seq (vs, b) ->
Fmt.pf ppf "@[<hov 2>%a(%a->@,@[%a@])@]"
(Printer.kws `TermSeq) "seq"
pp_var_list vs
pp_term b
| ForAll (vs, b) ->
Fmt.pf ppf "@[%a (@[%a@]),@ %a@]"
(Printer.kws `TermQuantif) "forall"
pp_var_list vs
pp_term b
| Exists (vs, b) ->
Fmt.pf ppf "@[%a (@[%a@]),@ %a@]"
(Printer.kws `TermQuantif) "exists"
pp_var_list vs
pp_term b
and pp_ts ppf ts = Fmt.pf ppf "@%a" pp_term ts
and pp_term ppf t =
Fmt.pf ppf "%a" pp_term_i (L.unloc t)
let pp = pp_term
let pp_i = pp_term_i
(*------------------------------------------------------------------*)
* { 2 Higher - order terms }
(** For now, we need (and allow) almost no higher-order terms. *)
type hterm_i =
| Lambda of bnds * term
type hterm = hterm_i L.located
(*------------------------------------------------------------------*)
* { 2 Equivalence formulas }
type equiv = term list
type pquant = PForAll | PExists
type global_formula = global_formula_i Location.located
and global_formula_i =
| PEquiv of equiv
| PReach of term
| PImpl of global_formula * global_formula
| PAnd of global_formula * global_formula
| POr of global_formula * global_formula
| PQuant of pquant * bnds * global_formula
(*------------------------------------------------------------------*)
* { 2 Any term : local or global }
type any_term = Global of global_formula | Local of term
(*------------------------------------------------------------------*)
* { 2 Error handling }
type conversion_error_i =
| Arity_error of string*int*int
| Untyped_symbol of string
| Index_error of string*int*int
| Undefined of string
| UndefinedOfKind of string * Symbols.namespace
| Type_error of term_i * Type.ty
| Timestamp_expected of term_i
| Timestamp_unexpected of term_i
| Unsupported_ord of term_i
| String_expected of term_i
| Int_expected of term_i
| Tactic_type of string
| NotVar
| Assign_no_state of string
| BadNamespace of string * Symbols.namespace
| Freetyunivar
| UnknownTypeVar of string
| BadPty of Type.ty list
| BadInfixDecl
| PatNotAllowed
| ExplicitTSInProc
| UndefInSystem of SE.t
| MissingSystem
| BadProjInSubterm of Term.projs * Term.projs
type conversion_error = L.t * conversion_error_i
exception Conv of conversion_error
let conv_err loc e = raise (Conv (loc,e))
let pp_error_i ppf = function
| Arity_error (s,i,j) -> Fmt.pf ppf "Symbol %s used with arity %i, but \
defined with arity %i" s i j
| Untyped_symbol s -> Fmt.pf ppf "Symbol %s is not typed" s
| Index_error (s,i,j) -> Fmt.pf ppf "Symbol %s used with %i indices, but \
defined with %i indices" s i j
| Undefined s -> Fmt.pf ppf "symbol %s is undefined" s
| UndefinedOfKind (s,n) ->
Fmt.pf ppf "%a %s is undefined" Symbols.pp_namespace n s
| Type_error (s, ty) ->
Fmt.pf ppf "@[<hov 0>Term@;<1 2>@[%a@]@ is not of type @[%a@]@]" pp_i s Type.pp ty
| Timestamp_expected t ->
Fmt.pf ppf "The term %a must be given a timestamp" pp_i t
| Timestamp_unexpected t ->
Fmt.pf ppf "The term %a must not be given a timestamp" pp_i t
| Unsupported_ord t ->
Fmt.pf ppf
"comparison %a cannot be typed@ \
(operands have a type@ for which the comparison is allowed)"
pp_i t
| String_expected t ->
Fmt.pf ppf
"The term %a cannot be seen as a string"
pp_i t
| Int_expected t ->
Fmt.pf ppf
"The term %a cannot be seen as a int"
pp_i t
| Tactic_type s ->
Fmt.pf ppf "The tactic arguments could not be parsed: %s" s
| NotVar ->
Fmt.pf ppf "must be a variable"
| Assign_no_state s ->
Fmt.pf ppf "Only mutables can be assigned values, and the \
symbols %s is not a mutable" s
| BadNamespace (s,n) ->
Fmt.pf ppf "Kind error: %s has kind %a" s
Symbols.pp_namespace n
| Freetyunivar -> Fmt.pf ppf "some type variable(s) could not \
be instantiated"
| UnknownTypeVar ty ->
Fmt.pf ppf "undefined type variable %s" ty
| BadPty l ->
Fmt.pf ppf "type must be of type %a"
(Fmt.list ~sep:Fmt.comma Type.pp) l
| BadInfixDecl -> Fmt.pf ppf "bad infix symbol declaration"
| PatNotAllowed -> Fmt.pf ppf "pattern not allowed"
| ExplicitTSInProc ->
Fmt.pf ppf "macros cannot be written at explicit \
timestamps in procedure"
| UndefInSystem t ->
Fmt.pf ppf "action not defined in system @[%a@]"
SE.pp t
| MissingSystem ->
Fmt.pf ppf "missing system annotation"
| BadProjInSubterm (ps1, ps2) ->
Fmt.pf ppf "@[<v 2>invalid projection:@;missing projections: %a@;\
unknown projections: %a@]"
Term.pp_projs ps1
Term.pp_projs ps2
let pp_error pp_loc_err ppf (loc,e) =
Fmt.pf ppf "%a@[<hov 2>Conversion error:@, %a@]"
pp_loc_err loc
pp_error_i e
(*------------------------------------------------------------------*)
* { 2 Parsing types }
let parse_p_ty (env : Env.t) (pty : p_ty) : Type.ty =
match L.unloc pty with
| P_message -> Type.tmessage
| P_boolean -> Type.tboolean
| P_index -> Type.tindex
| P_timestamp -> Type.ttimestamp
| P_tvar tv_l ->
let tv =
try
List.find (fun tv' ->
let tv' = Type.ident_of_tvar tv' in
Ident.name tv' = L.unloc tv_l
) env.ty_vars
with Not_found ->
conv_err (L.loc tv_l) (UnknownTypeVar (L.unloc tv_l))
in
TVar tv
| P_tbase tb_l ->
let s = Symbols.BType.of_lsymb tb_l env.table in
Type.TBase (Symbols.to_string s) (* TODO: remove to_string *)
(*------------------------------------------------------------------*)
* { 2 Type checking }
let check_arity_i loc s (actual : int) (expected : int) =
if actual <> expected then
conv_err loc (Arity_error (s,actual,expected))
let check_arity (lsymb : lsymb) (actual : int) (expected : int) =
check_arity_i (L.loc lsymb) (L.unloc lsymb) actual expected
(** Type of a macro *)
type mtype = Type.ty list * Type.ty (* args, out *)
* Macro or function type
type mf_type = [`Fun of Type.ftype | `Macro of mtype]
let ftype_arity (fty : Type.ftype) =
fty.Type.fty_iarr + (List.length fty.Type.fty_args)
let mf_type_arity (ty : mf_type) =
match ty with
| `Fun ftype -> ftype_arity ftype
| `Macro (l,_) -> List.length l
(** Get the kind of a function or macro definition.
* In the latter case, the timestamp argument is not accounted for. *)
let function_kind table (f : lsymb) : mf_type =
let open Symbols in
match def_of_lsymb f table with
(* we should never encounter a situation where we
try to type a reserved symbol. *)
| Reserved _ -> assert false
| Exists d -> match d with
| Function (fty, _) -> `Fun fty
| Macro (Global (arity, ty)) ->
let targs = (List.init arity (fun _ -> Type.tindex)) in
`Macro (targs, ty)
| Macro (Input|Output|Frame) ->
(* FEATURE: subtypes*)
`Macro ([], Type.tmessage)
| Macro (Cond|Exec) ->
`Macro ([], Type.tboolean)
| _ -> conv_err (L.loc f) (Untyped_symbol (L.unloc f))
let check_state table (s : lsymb) n : Type.ty =
match Symbols.Macro.def_of_lsymb s table with
| Symbols.State (arity,ty) ->
check_arity s n arity ;
ty
| _ -> conv_err (L.loc s) (Assign_no_state (L.unloc s))
let check_name table (s : lsymb) n : Type.ftype =
let fty = (Symbols.Name.def_of_lsymb s table).n_fty in
let arity = List.length fty.fty_args in
if arity <> n then conv_err (L.loc s) (Index_error (L.unloc s,n,arity));
fty
let check_action (env : Env.t) (s : lsymb) (n : int) : unit =
let l,action = Action.find_symbol s env.table in
let arity = List.length l in
if arity <> n then conv_err (L.loc s) (Index_error (L.unloc s,n,arity));
try
let system = SE.to_compatible env.system.set in
ignore (SE.action_to_term env.table system action)
with _ -> conv_err (L.loc s) (UndefInSystem env.system.set)
(*------------------------------------------------------------------*)
(** Applications *)
(** Type of an application ([App _] or [AppAt _]) that has been
dis-ambiguated *)
type app_i =
| Name of lsymb * term list
(** A name, whose arguments will always be indices. *)
| Get of lsymb * Term.term option * term list
* [ Get ( s , ots , terms ) ] reads the contents of memory cell
* [ ( s , terms ) ] where [ terms ] are evaluated as indices .
* The second argument [ ots ] is for the optional timestamp at which the
* memory read is performed . This is used for the terms appearing in
* goals .
* [(s,terms)] where [terms] are evaluated as indices.
* The second argument [ots] is for the optional timestamp at which the
* memory read is performed. This is used for the terms appearing in
* goals. *)
| Fun of lsymb * term list * Term.term option
* Function symbol application ,
* where terms will be evaluated as indices or messages
* depending on the type of the function symbol .
* The third argument is an optional timestamp , used when
* writing meta - logic formulas but not in processes .
* where terms will be evaluated as indices or messages
* depending on the type of the function symbol.
* The third argument is an optional timestamp, used when
* writing meta-logic formulas but not in processes. *)
| Taction of lsymb * term list
| AVar of lsymb
and app = app_i L.located
let[@warning "-32"] pp_app_i ppf = function
| Taction (a,l) ->
Fmt.pf ppf "%s%a"
(L.unloc a)
(Utils.pp_list pp_term) l
| Fun (f,[t1;t2],ots) when L.unloc f="exp"->
Fmt.pf ppf "%a^%a" pp_term t1 pp_term t2
| Fun (f,terms,ots) ->
Fmt.pf ppf "%s%a%a"
(L.unloc f)
(Utils.pp_list pp_term) terms
(Fmt.option Term.pp) ots
| Name (n,terms) ->
Fmt.pf ppf "%a%a"
(* Pretty-printing names with nice colors
* is well worth violating the type system ;) *)
Term.pp_name (Obj.magic n)
(Utils.pp_list pp_term) terms
| Get (s,ots,terms) ->
Fmt.pf ppf "!%s%a%a"
(L.unloc s)
(Utils.pp_list pp_term) terms
(Fmt.option Term.pp) ots
| AVar s -> Fmt.pf ppf "%s" (L.unloc s)
(** Context of a application construction. *)
type app_cntxt =
| At of Term.term (* for explicit timestamp, e.g. [s@ts] *)
| MaybeAt of Term.term (* for potentially implicit timestamp,
e.g. [s] in a process parsing. *)
| NoTS (* when there is no timestamp, even implicit. *)
let is_at = function At _ -> true | _ -> false
let get_ts = function At ts | MaybeAt ts -> Some ts | _ -> None
let make_app_i table cntxt (lsymb : lsymb) (l : term list) : app_i =
let loc = L.loc lsymb in
let arity_error i =
conv_err loc (Arity_error (L.unloc lsymb, List.length l, i)) in
let ts_unexpected () =
conv_err loc (Timestamp_unexpected (App (lsymb,l))) in
match Symbols.def_of_lsymb lsymb table with
| Symbols.Reserved _ -> Fmt.epr "%s@." (L.unloc lsymb); assert false
| Symbols.Exists d ->
begin match d with
| Symbols.Function (ftype,fdef) ->
if is_at cntxt then ts_unexpected ();
let farity = ftype_arity ftype in
if List.length l <> farity then raise (arity_error farity) ;
Fun (lsymb,l,None)
| Symbols.Name ndef ->
if is_at cntxt then ts_unexpected ();
check_arity lsymb (List.length l) (List.length ndef.n_fty.fty_args) ;
Name (lsymb,l)
| Symbols.Macro (Symbols.State (arity,_)) ->
check_arity lsymb (List.length l) arity ;
Get (lsymb,get_ts cntxt,l)
| Symbols.Macro (Symbols.Global (arity,_)) ->
if List.length l <> arity then arity_error arity;
Fun (lsymb,l,get_ts cntxt)
| Symbols.Macro (Symbols.Input|Symbols.Output|Symbols.Cond|Symbols.Exec
|Symbols.Frame) ->
if cntxt = NoTS then
conv_err loc (Timestamp_expected (App (lsymb,l)));
if l <> [] then arity_error 0;
Fun (lsymb,[],get_ts cntxt)
| Symbols.Action arity ->
if arity <> List.length l then arity_error arity ;
Taction (lsymb,l)
| Symbols.Channel _
| Symbols.BType _
| Symbols.Process _
| Symbols.System _ ->
let s = L.unloc lsymb in
conv_err loc (BadNamespace (s,
oget(Symbols.get_namespace table s)))
end
| exception Symbols.SymbError (loc, Symbols.Unbound_identifier s) ->
(* By default we interpret s as a variable, but this is only
possible if it is not indexed. If that is not the case, the
user probably meant for this symbol to not be a variable,
hence we raise Unbound_identifier. We could also raise
Type_error because a variable is never of a sort that can be
applied to indices. *)
if l <> [] then
raise (Symbols.SymbError (loc, Symbols.Unbound_identifier s));
AVar lsymb
let make_app loc table cntxt (lsymb : lsymb) (l : term list) : app =
L.mk_loc loc (make_app_i table cntxt lsymb l)
(*------------------------------------------------------------------*)
* { 2 Substitution }
type esubst = ESubst : string * Term.term -> esubst
type subst = esubst list
(** Apply a partial substitution to a term.
* This is meant for formulas and local terms in processes,
* and does not support optional timestamps.
* TODO substitution does not avoid capture. *)
let subst t (s : (string * term_i) list) =
let rec aux_i = function
(* Variable *)
| App (x, []) as t ->
begin try
let ti = List.assoc (L.unloc x) s in
ti
with Not_found -> t
end
| Tpat -> Tpat
| App (s,l) -> App (s, List.map aux l)
| AppAt (s,l,ts) -> AppAt (s, List.map aux l, aux ts)
| Seq (vs,t) -> Seq (vs, aux t)
| ForAll (vs,f) -> ForAll (vs, aux f)
| Exists (vs,f) -> Exists (vs, aux f)
| Diff (l,r) -> Diff (aux l, aux r)
| Find (is,c,t,e) -> Find (is, aux c, aux t, aux e)
and aux t = L.mk_loc (L.loc t) (aux_i (L.unloc t))
in aux t
(*------------------------------------------------------------------*)
* { 2 Conversion contexts and states }
(** Conversion contexts.
- [InGoal]: converting a term in a goal (or tactic). All
timestamps must be explicitely given.
- [InProc (projs, ts)]: converting a term in a process at an implicit
timestamp [ts], with projections [projs]. *)
type conv_cntxt =
| InProc of Term.projs * Term.term
| InGoal
let is_in_proc = function InProc _ -> true | InGoal -> false
(** Exported conversion environments. *)
type conv_env = {
env : Env.t;
cntxt : conv_cntxt;
}
(** Internal conversion states, containing:
- all the fields of a [conv_env]
- free type variables
- a type unification environment
- a variable substitution *)
type conv_state = {
env : Env.t;
cntxt : conv_cntxt;
allow_pat : bool;
ty_env : Type.Infer.env;
}
let mk_state env cntxt allow_pat ty_env =
{ cntxt; env; allow_pat; ty_env; }
(*------------------------------------------------------------------*)
(** {2 Types} *)
let ty_error ty_env tm ty =
let ty = Type.Infer.norm ty_env ty in
Conv (L.loc tm, Type_error (L.unloc tm, ty))
let check_ty_leq state ~of_t (t_ty : Type.ty) (ty : Type.ty) : unit =
match Type.Infer.unify_leq state.ty_env t_ty ty with
| `Ok -> ()
| `Fail ->
raise (ty_error state.ty_env of_t ty)
let check_ty_eq state ( t_ty : Type.ty ) ( ty : ' b Type.ty ) : unit =
* match Type . Infer.unify_eq state.ty_env t_ty ty with
* | ` Ok - > ( )
* | ` Fail - > raise ( ty_error state.ty_env of_t ty )
* match Type.Infer.unify_eq state.ty_env t_ty ty with
* | `Ok -> ()
* | `Fail -> raise (ty_error state.ty_env of_t ty) *)
let check_term_ty state ~of_t (t : Term.term) (ty : Type.ty) : unit =
check_ty_leq state ~of_t (Term.ty ~ty_env:state.ty_env t) ty
(*------------------------------------------------------------------*)
* { 2 System projections }
(** check that projection alive at a given subterm w.r.t. projections
used in a diff operator application. *)
let check_system_projs loc (state : conv_state) (projs : Term.projs) : unit =
let current_projs =
match state.cntxt with
| InProc (ps, _) -> ps
| InGoal ->
if not (SE.is_fset state.env.system.set) then
conv_err loc MissingSystem;
let fset = SE.to_fset state.env.system.set in
SE.to_projs fset
in
let diff1 = List.diff current_projs projs
and diff2 = List.diff projs current_projs in
if diff1 <> [] || diff2 <> [] then
conv_err loc (BadProjInSubterm (diff1, diff2))
let proj_state (projs : Term.projs) (state : conv_state) : conv_state =
match state.cntxt with
| InProc (ps, ts) -> { state with cntxt = InProc ([Term.left_proj], ts) }
| InGoal -> { state with env = projs_set [Term.left_proj ] state.env }
(*------------------------------------------------------------------*)
* { 2 Conversion }
let convert_var
(state : conv_state)
(st : lsymb)
(ty : Type.ty)
: Term.term
=
try
let v = Vars.find state.env.vars (L.unloc st) in
let of_t = var_of_lsymb st in
check_ty_leq state ~of_t (Vars.ty v) ty;
Term.mk_var v
with
| Not_found -> conv_err (L.loc st) (Undefined (L.unloc st))
let convert_bnds (env : Env.t) (vars : (lsymb * Type.ty) list) =
let do1 (vars, v_acc) (vsymb, s) =
let vars, v = Vars.make `Shadow vars s (L.unloc vsymb) in
vars, v :: v_acc
in
let venv, v_acc = List.fold_left do1 (env.vars, []) vars in
{ env with vars = venv }, List.rev v_acc
let convert_p_bnds (env : Env.t) (vars : bnds) =
let vs = List.map (fun (v,s) -> v, parse_p_ty env s) vars in
convert_bnds env vs
let get_fun table lsymb =
match Symbols.Function.of_lsymb_opt lsymb table with
| Some n -> n
| None ->
conv_err (L.loc lsymb) (UndefinedOfKind (L.unloc lsymb, Symbols.NFunction))
let get_name table lsymb =
match Symbols.Name.of_lsymb_opt lsymb table with
| Some n -> n
| None ->
conv_err (L.loc lsymb) (UndefinedOfKind (L.unloc lsymb, Symbols.NName))
let get_action (env : Env.t) lsymb =
match Symbols.Action.of_lsymb_opt lsymb env.table with
| Some n -> n
| None ->
conv_err (L.loc lsymb) (UndefinedOfKind (L.unloc lsymb, Symbols.NAction))
let get_macro (env : Env.t) lsymb =
match Symbols.Macro.of_lsymb_opt lsymb env.table with
| Some n -> n
| None ->
conv_err (L.loc lsymb) (UndefinedOfKind (L.unloc lsymb, Symbols.NMacro))
(*------------------------------------------------------------------*)
internal function to Theory.ml
let rec convert
(state : conv_state)
(tm : term)
(ty : Type.ty)
: Term.term
=
let t = convert0 state tm ty in
check_term_ty state ~of_t:tm t ty;
t
and convert0
(state : conv_state)
(tm : term)
(ty : Type.ty) : Term.term
=
let loc = L.loc tm in
let conv ?(env=state.env) s t =
let state = { state with env } in
convert state t s in
let type_error () = raise (ty_error state.ty_env tm ty) in
match L.unloc tm with
| Tpat ->
if not state.allow_pat then
conv_err (L.loc tm) PatNotAllowed;
let _, p = Vars.make ~allow_pat:true `Approx state.env.vars ty "_" in
Term.mk_var p
(*------------------------------------------------------------------*)
(* particular cases for init and happens *)
| App ({ pl_desc = "init" },terms) ->
if terms <> [] then type_error ();
Term.mk_action Symbols.init_action []
(* happens distributes over its arguments *)
| App ({ pl_desc = "happens" },ts) ->
let atoms = List.map (fun t ->
Term.mk_happens (conv Type.Timestamp t)
) ts in
Term.mk_ands atoms
(* end of special cases *)
(*------------------------------------------------------------------*)
| App (f,terms) ->
if terms = [] && Vars.mem_s state.env.vars (L.unloc f)
then convert_var state f ty
(* otherwise build the application and convert it. *)
else
let app_cntxt = match state.cntxt with
| InGoal -> NoTS
| InProc (_, ts) -> MaybeAt ts in
conv_app state app_cntxt
(tm, make_app loc state.env.table app_cntxt f terms)
ty
| AppAt (f,terms,ts) ->
if is_in_proc state.cntxt then conv_err loc ExplicitTSInProc;
let app_cntxt = At (conv Type.Timestamp ts) in
conv_app state app_cntxt
(tm, make_app loc state.env.table app_cntxt f terms)
ty
| Diff (l,r) ->
check_system_projs loc state [Term.left_proj; Term.right_proj];
let statel = proj_state [Term.left_proj ] state in
let stater = proj_state [Term.right_proj] state in
Term.mk_diff [Term.left_proj , convert statel l ty;
Term.right_proj, convert stater r ty; ]
| Find (vs,c,t,e) ->
let env, is =
convert_p_bnds state.env vs
in
Vars.check_type_vars is [Type.tindex; Type.ttimestamp] type_error;
let c = conv ~env Type.tboolean c in
let t = conv ~env ty t in
let e = conv ty e in
Term.mk_find is c t e
| ForAll (vs,f) | Exists (vs,f) ->
let env, evs = convert_p_bnds state.env vs in
let f = conv ~env Type.tboolean f in
begin match L.unloc tm with
| ForAll _ -> Term.mk_forall evs f
| Exists _ -> Term.mk_exists evs f
| _ -> assert false
end
| Seq (vs,t) ->
let env, evs = convert_p_bnds state.env vs in
let tyv = Type.Infer.mk_univar state.ty_env in
let t = conv ~env (Type.TUnivar tyv) t in
let () =
Vars.check_type_vars evs [Type.tindex; Type.ttimestamp] type_error
in
Term.mk_seq0 ~simpl:false evs t
and conv_var state t ty =
match convert state t ty with
| Term.Var x -> x
| _ -> conv_err (L.loc t) NotVar
and conv_vars state ts tys = List.map2 (conv_var state) ts tys
(* The term [tm] in argument is here for error messages. *)
and conv_app
(state : conv_state)
(app_cntxt : app_cntxt)
((tm,app) : (term * app))
(ty : Type.ty)
: Term.term
=
(* We should have [make_app app = t].
[t] is here to have meaningful exceptions. *)
let loc = L.loc tm in
let t_i = L.unloc tm in
let conv ?(env=state.env) s t =
let state = { state with env } in
convert state t s in
let get_at ts_opt =
match ts_opt, get_ts app_cntxt with
| Some ts, _ -> ts
| None, Some ts -> ts
| None, None -> conv_err loc (Timestamp_expected (L.unloc tm))
in
let conv_fapp (f : lsymb) l ts_opt : Term.term =
let mfty = function_kind state.env.table f in
let () = check_arity f (List.length l) (mf_type_arity mfty) in
match Symbols.of_lsymb f state.env.table with
| Symbols.Wrapped (symb, Function (_,_)) ->
assert (ts_opt = None);
let fty = match mfty with `Fun x -> x | _ -> assert false in
(* refresh all type variables in [fty] *)
let fty_op = Type.open_ftype state.ty_env fty in
let l_indices, l_messages = List.takedrop fty_op.Type.fty_iarr l in
let indices =
List.map (fun x -> conv_var state x Type.tindex) l_indices
in
let rmessages =
List.fold_left2 (fun rmessages t ty ->
let t = conv ty t in
t :: rmessages
) [] l_messages fty_op.Type.fty_args
in
let messages = List.rev rmessages in
let t = Term.mk_fun0 (symb,indices) fty messages in
(* additional type check between the type of [t] and the output
type in [fty].
Note that [convert] checks that the type of [t] is a subtype
of [ty], hence we do not need to do it here. *)
check_term_ty state ~of_t:tm t fty_op.Type.fty_out;
t
(* FIXME: messy code *)
| Wrapped (s, Symbols.Macro macro) ->
let ty_args, ty_out =
match mfty with `Macro x -> x | _ -> assert false
in
begin match macro with
| Symbols.State _ -> assert false
| Symbols.Global _ ->
assert (List.for_all (fun x -> x = Type.tindex) ty_args);
let indices =
List.map (fun x ->
conv_var state x Type.tindex
) l
in
let ms = Term.mk_isymb s ty_out indices in
Term.mk_macro ms [] (get_at ts_opt)
| Input | Output | Frame ->
check_arity_i (L.loc f) "input" (List.length l) 0 ;
(* FEATURE: subtypes *)
let ms = Term.mk_isymb s ty_out [] in
Term.mk_macro ms [] (get_at ts_opt)
| Cond | Exec ->
check_arity_i (L.loc f) "cond" (List.length l) 0 ;
let ms = Term.mk_isymb s ty_out [] in
Term.mk_macro ms [] (get_at ts_opt)
end
| Wrapped (_, _) -> assert false
in
match L.unloc app with
| AVar s -> convert_var state s ty
| Fun (f,l,ts_opt) -> conv_fapp f l ts_opt
| Get (s,opt_ts,is) ->
let k = check_state state.env.table s (List.length is) in
let is = List.map (fun i -> conv_var state i Type.tindex) is in
let s = get_macro state.env s in
let ts =
match opt_ts with
| Some ts -> ts
| None -> conv_err loc (Timestamp_expected t_i)
in
let ms = Term.mk_isymb s k is in
Term.mk_macro ms [] ts
| Name (s, is) ->
let s_fty = check_name state.env.table s (List.length is) in
assert (s_fty.fty_iarr = 0 && s_fty.fty_vars = []);
let is = conv_vars state is s_fty.fty_args in
let ns = Term.mk_isymb (get_name state.env.table s) s_fty.fty_out is in
Term.mk_name ns
| Taction (a,is) ->
check_action state.env a (List.length is) ;
Term.mk_action
(get_action state.env a)
(List.map (fun x -> conv_var state x Type.tindex) is)
(*------------------------------------------------------------------*)
* convert HO terms
let conv_ht (state : conv_state) (t : hterm) : Type.hty * Term.hterm =
match L.unloc t with
| Lambda (bnds, t0) ->
let env, evs = convert_p_bnds state.env bnds in
let state = { state with env } in
let tyv = Type.Infer.mk_univar state.ty_env in
let ty = Type.TUnivar tyv in
let ht = Term.Lambda (evs, convert state t0 ty) in
let bnd_tys = List.map Vars.ty evs in
let hty = Type.Lambda (bnd_tys, ty) in
hty, ht
(*------------------------------------------------------------------*)
* { 2 Function declarations }
let mk_ftype iarr vars args out =
let mdflt ty = odflt Type.tmessage ty in
Type.mk_ftype iarr vars (List.map mdflt args) (mdflt out)
let declare_dh
(table : Symbols.table)
(h : Symbols.dh_hyp list)
?group_ty ?exp_ty
(gen : lsymb)
((exp, f_info) : lsymb * Symbols.symb_type)
(omult : (lsymb * Symbols.symb_type) option)
: Symbols.table =
let open Symbols in
let gen_fty = mk_ftype 0 [] [] group_ty in
let exp_fty = mk_ftype 0 [] [group_ty; exp_ty] group_ty in
let table, exp = Function.declare_exact table exp (exp_fty, Abstract f_info) in
let (table, af) = match omult with
| None -> (table, [exp])
| Some (mult, mf_info) ->
let mult_fty = mk_ftype 0 [] [exp_ty; exp_ty] exp_ty in
let (table, mult) =
Function.declare_exact table mult (mult_fty, Abstract mf_info)
in
(table, [exp; mult])
in
let data = AssociatedFunctions af in
fst (Function.declare_exact table ~data gen (gen_fty, DHgen h))
let declare_hash table ?index_arity ?m_ty ?k_ty ?h_ty s =
let index_arity = odflt 0 index_arity in
let ftype = mk_ftype index_arity [] [m_ty; k_ty] h_ty in
let def = ftype, Symbols.Hash in
fst (Symbols.Function.declare_exact table s def)
let declare_aenc table ?ptxt_ty ?ctxt_ty ?rnd_ty ?sk_ty ?pk_ty enc dec pk =
let open Symbols in
let dec_fty = mk_ftype 0 [] [ctxt_ty; sk_ty] ptxt_ty in
let enc_fty = mk_ftype 0 [] [ptxt_ty; rnd_ty; pk_ty] ctxt_ty in
let pk_fty = mk_ftype 0 [] [sk_ty] pk_ty in
let table, pk = Function.declare_exact table pk (pk_fty,PublicKey) in
let dec_data = AssociatedFunctions [Function.cast_of_string (L.unloc enc); pk] in
let table, dec = Function.declare_exact table dec ~data:dec_data (dec_fty,ADec) in
let data = AssociatedFunctions [dec; pk] in
fst (Function.declare_exact table enc ~data (enc_fty,AEnc))
let declare_senc table ?ptxt_ty ?ctxt_ty ?rnd_ty ?k_ty enc dec =
let open Symbols in
let data = AssociatedFunctions [Function.cast_of_string (L.unloc enc)] in
let dec_fty = mk_ftype 0 [] [ctxt_ty; k_ty] ptxt_ty in
let enc_fty = mk_ftype 0 [] [ptxt_ty; rnd_ty; k_ty] ctxt_ty in
let table, dec = Function.declare_exact table dec ~data (dec_fty,SDec) in
let data = AssociatedFunctions [dec] in
fst (Function.declare_exact table enc ~data (enc_fty,SEnc))
let declare_senc_joint_with_hash
table ?ptxt_ty ?ctxt_ty ?rnd_ty ?k_ty enc dec h =
let open Symbols in
let data = AssociatedFunctions [Function.cast_of_string (L.unloc enc);
get_fun table h] in
let dec_fty = mk_ftype 0 [] [ctxt_ty; k_ty] ptxt_ty in
let enc_fty = mk_ftype 0 [] [ptxt_ty; rnd_ty; k_ty] ctxt_ty in
let table, dec = Function.declare_exact table dec ~data (dec_fty,SDec) in
let data = AssociatedFunctions [dec] in
fst (Function.declare_exact table enc ~data (enc_fty,SEnc))
let declare_signature table
?m_ty ?sig_ty ?check_ty ?sk_ty ?pk_ty
sign checksign pk =
let open Symbols in
let sig_fty = mk_ftype 0 [] [m_ty; sk_ty] sig_ty in
let check_fty = mk_ftype 0 [] [sig_ty; pk_ty] check_ty in
let pk_fty = mk_ftype 0 [] [sk_ty] pk_ty in
let table,sign = Function.declare_exact table sign (sig_fty, Sign) in
let table,pk = Function.declare_exact table pk (pk_fty,PublicKey) in
let data = AssociatedFunctions [sign; pk] in
fst (Function.declare_exact table checksign ~data (check_fty,CheckSign))
let check_signature table checksign pk =
let def x = Symbols.Function.get_def x table in
let correct_type = match def checksign, def pk with
| (_,Symbols.CheckSign), (_,Symbols.PublicKey) -> true
| _ -> false
in
if correct_type then
match Symbols.Function.get_data checksign table with
| Symbols.AssociatedFunctions [sign; pk2] when pk2 = pk -> Some sign
| _ -> None
else None
let declare_name table s ndef =
fst (Symbols.Name.declare_exact table s ndef)
(*------------------------------------------------------------------*)
(** Sanity checks for a function symbol declaration. *)
let check_fun_symb
table
(ty_args : Type.tvar list) (in_tys : Type.ty list) (index_arity : int)
(s : lsymb) (f_info : Symbols.symb_type) : unit
=
match f_info with
| `Prefix -> ()
| `Infix side ->
if not (index_arity = 0) ||
not (List.length ty_args = 0) ||
not (List.length in_tys = 2) then
conv_err (L.loc s) BadInfixDecl
let declare_abstract
table ~index_arity ~ty_args ~in_tys ~out_ty
(s : lsymb) (f_info : Symbols.symb_type)
=
(* if we declare an infix symbol, run some sanity checks *)
check_fun_symb table ty_args in_tys index_arity s f_info;
let ftype = Type.mk_ftype index_arity ty_args in_tys out_ty in
fst (Symbols.Function.declare_exact table s (ftype, Symbols.Abstract f_info))
(*------------------------------------------------------------------*)
* { 2 Miscellaneous }
(** Empty *)
let empty loc = L.mk_loc loc (App (L.mk_loc loc "empty", []))
(*------------------------------------------------------------------*)
* { 2 Exported conversion and type - checking functions }
let convert_ht
?ty_env
?(pat=false)
(cenv : conv_env)
(ht0 : hterm)
: Type.hty * Term.hterm
=
let must_close, ty_env = match ty_env with
| None -> true, Type.Infer.mk_env ()
| Some ty_env -> false, ty_env
in
let state = mk_state cenv.env cenv.cntxt pat ty_env in
let hty, ht = conv_ht state ht0 in
if must_close then
begin
if not (Type.Infer.is_closed state.ty_env) then
conv_err (L.loc ht0) Freetyunivar;
let tysubst = Type.Infer.close ty_env in
Type.tsubst_ht tysubst hty, Term.tsubst_ht tysubst ht
end
else
Type.Infer.htnorm state.ty_env hty, ht
(*------------------------------------------------------------------*)
let check
(env : Env.t) ?(local=false) ?(pat=false)
(ty_env : Type.Infer.env)
(projs : Term.projs)
(t : term) (s : Type.ty)
: unit
=
let dummy_var s =
Term.mk_var (snd (Vars.make `Approx Vars.empty_env s "#dummy"))
in
let cntxt = if local then InProc (projs, (dummy_var Type.Timestamp)) else InGoal in
let state = mk_state env cntxt pat ty_env in
ignore (convert state t s)
* exported outside Theory.ml
let convert
?(ty : Type.ty option)
?(ty_env : Type.Infer.env option)
?(pat : bool = false)
(cenv : conv_env)
(tm : term)
: Term.term * Type.ty
=
let must_close, ty_env = match ty_env with
| None -> true, Type.Infer.mk_env ()
| Some ty_env -> false, ty_env
in
let ty = match ty with
| None -> Type.TUnivar (Type.Infer.mk_univar ty_env)
| Some ty -> ty
in
let state = mk_state cenv.env cenv.cntxt pat ty_env in
let t = convert state tm ty in
if must_close then
begin
if not (Type.Infer.is_closed state.ty_env) then
conv_err (L.loc tm) Freetyunivar;
let tysubst = Type.Infer.close ty_env in
Term.tsubst tysubst t, Type.tsubst tysubst ty
end
else
t, Type.Infer.norm ty_env ty
(*------------------------------------------------------------------*)
* { 2 Convert equiv formulas }
let convert_equiv cenv (e : equiv) =
let convert_el el : Term.term =
let t, _ = convert cenv el in
t
in
List.map convert_el e
let convert_global_formula (cenv : conv_env) (p : global_formula) =
let rec conve (cenv : conv_env) p =
let conve ?(env=cenv.env) p = conve { cenv with env } p in
match L.unloc p with
| PImpl (f1, f2) -> Equiv.Impl (conve f1, conve f2)
| PAnd (f1, f2) -> Equiv.And (conve f1, conve f2)
| POr (f1, f2) -> Equiv.Or (conve f1, conve f2)
| PEquiv e ->
begin match cenv.env.system with
| SE.{ pair = Some p } ->
let system = SE.{ set = (p :> SE.t) ; pair = None } in
let env = Env.update ~system cenv.env in
let cenv = { cenv with env } in
Equiv.Atom (Equiv.Equiv (convert_equiv cenv e))
| _ ->
conv_err (L.loc p) MissingSystem
end
| PReach f ->
let f, _ = convert ~ty:Type.tboolean cenv f in
Equiv.Atom (Equiv.Reach f)
| PQuant (q, bnds, e) ->
let env, evs = convert_p_bnds cenv.env bnds in
let e = conve ~env e in
let q = match q with
| PForAll -> Equiv.ForAll
| PExists -> Equiv.Exists
in
Equiv.mk_quant q evs e
in
conve cenv p
(*------------------------------------------------------------------*)
* { 2 Convert any }
let convert_any (cenv : conv_env) (p : any_term) : Equiv.any_form =
match p with
| Local p -> Local (fst (convert ~ty:Type.Boolean cenv p))
| Global p -> Global (convert_global_formula cenv p)
(*------------------------------------------------------------------*)
* { 2 State and substitution parsing }
let parse_subst (env : Env.t) (uvars : Vars.var list) (ts : term list)
: Term.subst =
let conv_env = { env; cntxt = InGoal; } in
let f t u =
let t, _ = convert ~ty:(Vars.ty u) conv_env t in
Term.ESubst (Term.mk_var u, t)
in
List.map2 f ts uvars
type Symbols.data += StateInit_data of Vars.var list * Term.term
let declare_state
(table : Symbols.table)
(s : lsymb)
(typed_args : bnds)
(pty : p_ty)
(t : term)
=
let ts_init = Term.mk_action Symbols.init_action [] in
let env = Env.init ~table () in
let conv_env = { env; cntxt = InProc ([], ts_init); } in
let env, indices = convert_p_bnds env typed_args in
let conv_env = { conv_env with env } in
List.iter2 (fun v (_, pty) ->
if not (Type.equal (Vars.ty v) Type.tindex) then
conv_err (L.loc pty) (BadPty [Type.tindex])
) indices typed_args;
(* parse the macro type *)
let ty = parse_p_ty env pty in
let t, _ = convert ~ty conv_env t in
let data = StateInit_data (indices,t) in
let table, _ =
Symbols.Macro.declare_exact table
s
~data
(Symbols.State (List.length typed_args,ty)) in
table
let get_init_states table : (Term.state * Term.term) list =
Symbols.Macro.fold (fun s def data acc ->
match (def,data) with
| ( Symbols.State (arity,kind), StateInit_data (l,t) ) ->
assert (Type.equal kind (Term.ty t));
let state = Term.mk_isymb s kind l in
(state,t) :: acc
| _ -> acc
) [] table
let find_app_terms t (names : string list) =
let rec aux (name : string) acc t = match L.unloc t with
| App (x',l) ->
let acc = if L.unloc x' = name then L.unloc x'::acc else acc in
aux_list name acc l
| AppAt (x',l,ts) ->
let acc = if L.unloc x' = name then L.unloc x'::acc else acc in
aux_list name acc (ts :: l)
| Exists (_,t')
| ForAll (_,t') -> aux name acc t'
| _ -> acc
and aux_list name acc l =
List.fold_left (aux name) acc l in
let acc = List.fold_left (fun acc name -> aux name acc t) [] names in
List.sort_uniq Stdlib.compare acc
(*------------------------------------------------------------------*)
* { 2 Apply arguments }
(** proof term *)
type p_pt = {
p_pt_head : lsymb;
p_pt_args : p_pt_arg list;
p_pt_loc : L.t;
}
(** proof term argument *)
and p_pt_arg =
| PT_term of term
| PT_sub of p_pt (* sub proof term *)
(*------------------------------------------------------------------*)
* { 2 Tests }
let () =
let mk x = L.mk_loc L._dummy x in
Checks.add_suite "Theory" [
"Declarations", `Quick,
begin fun () ->
ignore (declare_hash Symbols.builtins_table (mk "h") : Symbols.table);
let table = declare_hash Symbols.builtins_table (mk "h") in
Alcotest.check_raises
"h cannot be defined twice"
(Symbols.SymbError (L._dummy, Multiple_declarations "h"))
(fun () -> ignore (declare_hash table (mk "h") : Symbols.table)) ;
let table = declare_hash Symbols.builtins_table (mk "h") in
Alcotest.check_raises
"h cannot be defined twice"
(Symbols.SymbError (L._dummy, Multiple_declarations "h"))
(fun () -> ignore (declare_aenc table (mk "h") (mk "dec") (mk "pk")
: Symbols.table) )
end;
"Term building", `Quick,
begin fun () ->
let table = declare_hash Symbols.builtins_table (mk "h") in
ignore (make_app L._dummy table NoTS (mk "x") []) ;
Alcotest.check_raises
"hash function expects two arguments"
(Conv (L._dummy, Arity_error ("h",1,2)))
(fun () ->
ignore (make_app L._dummy table NoTS (mk "h") [mk (App (mk "x",[]))])) ;
ignore (make_app
L._dummy table NoTS (mk "h") [mk (App (mk "x",[]));
mk (App (mk "y",[]))])
end ;
"Type checking", `Quick,
begin fun () ->
let table =
declare_aenc Symbols.builtins_table (mk "e") (mk "dec") (mk "pk")
in
let table = declare_hash table (mk "h") in
let x = mk (App (mk "x", [])) in
let y = mk (App (mk "y", [])) in
let vars = Vars.empty_env in
let vars, _ = Vars.make `Approx vars Type.tmessage "x" in
let vars, _ = Vars.make `Approx vars Type.tmessage "y" in
let env = Env.init ~vars ~table () in
let t_i = App (mk "e", [mk (App (mk "h", [x;y]));x;y]) in
let t = mk t_i in
let ty_env = Type.Infer.mk_env () in
check env ty_env [] t Type.tmessage ;
Alcotest.check_raises
"message is not a boolean"
(Conv (L._dummy, Type_error (t_i, Type.tboolean)))
(fun () -> check env ty_env [] t Type.tboolean)
end
]
| null | https://raw.githubusercontent.com/squirrel-prover/squirrel-prover/12424c7a975a54953428866908071bdf9765f398/src/theory.ml | ocaml | ------------------------------------------------------------------
* {2 Types}
------------------------------------------------------------------
------------------------------------------------------------------
* An application of a symbol to some arguments, at a given
timestamp. As for [App _], the head function symbol has not been
disambiguated yet.
[AppAt(f,t1 :: ... :: tn,tau)] is [f (t1, ..., tn)@tau]
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
* For now, we need (and allow) almost no higher-order terms.
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
TODO: remove to_string
------------------------------------------------------------------
* Type of a macro
args, out
* Get the kind of a function or macro definition.
* In the latter case, the timestamp argument is not accounted for.
we should never encounter a situation where we
try to type a reserved symbol.
FEATURE: subtypes
------------------------------------------------------------------
* Applications
* Type of an application ([App _] or [AppAt _]) that has been
dis-ambiguated
* A name, whose arguments will always be indices.
Pretty-printing names with nice colors
* is well worth violating the type system ;)
* Context of a application construction.
for explicit timestamp, e.g. [s@ts]
for potentially implicit timestamp,
e.g. [s] in a process parsing.
when there is no timestamp, even implicit.
By default we interpret s as a variable, but this is only
possible if it is not indexed. If that is not the case, the
user probably meant for this symbol to not be a variable,
hence we raise Unbound_identifier. We could also raise
Type_error because a variable is never of a sort that can be
applied to indices.
------------------------------------------------------------------
* Apply a partial substitution to a term.
* This is meant for formulas and local terms in processes,
* and does not support optional timestamps.
* TODO substitution does not avoid capture.
Variable
------------------------------------------------------------------
* Conversion contexts.
- [InGoal]: converting a term in a goal (or tactic). All
timestamps must be explicitely given.
- [InProc (projs, ts)]: converting a term in a process at an implicit
timestamp [ts], with projections [projs].
* Exported conversion environments.
* Internal conversion states, containing:
- all the fields of a [conv_env]
- free type variables
- a type unification environment
- a variable substitution
------------------------------------------------------------------
* {2 Types}
------------------------------------------------------------------
* check that projection alive at a given subterm w.r.t. projections
used in a diff operator application.
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
particular cases for init and happens
happens distributes over its arguments
end of special cases
------------------------------------------------------------------
otherwise build the application and convert it.
The term [tm] in argument is here for error messages.
We should have [make_app app = t].
[t] is here to have meaningful exceptions.
refresh all type variables in [fty]
additional type check between the type of [t] and the output
type in [fty].
Note that [convert] checks that the type of [t] is a subtype
of [ty], hence we do not need to do it here.
FIXME: messy code
FEATURE: subtypes
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
* Sanity checks for a function symbol declaration.
if we declare an infix symbol, run some sanity checks
------------------------------------------------------------------
* Empty
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
parse the macro type
------------------------------------------------------------------
* proof term
* proof term argument
sub proof term
------------------------------------------------------------------ | open Utils
open Env
module SE = SystemExpr
module L = Location
type lsymb = string L.located
type p_ty_i =
| P_message
| P_boolean
| P_index
| P_timestamp
| P_tbase of lsymb
| P_tvar of lsymb
type p_ty = p_ty_i L.located
let pp_p_ty_i fmt = function
| P_message -> Fmt.pf fmt "message"
| P_boolean -> Fmt.pf fmt "boolean"
| P_index -> Fmt.pf fmt "index"
| P_timestamp -> Fmt.pf fmt "timestamp"
| P_tbase s -> Fmt.pf fmt "%s" (L.unloc s)
| P_tvar s -> Fmt.pf fmt "'%s" (L.unloc s)
let pp_p_ty fmt pty = pp_p_ty_i fmt (L.unloc pty)
* binder
type bnd = lsymb * p_ty
* binders
type bnds = (lsymb * p_ty) list
* { 2 Terms }
type term_i =
| Tpat
TODO generalize
| Seq of bnds * term
| Find of bnds * term * term * term
| App of lsymb * term list
* An application of a symbol to some arguments which as not been
disambiguated yet ( it can be a name , a function symbol
application , a variable , ... )
[ App(f , t1 : : ... : : tn ) ] is [ f ( t1 , ... , tn ) ]
disambiguated yet (it can be a name, a function symbol
application, a variable, ...)
[App(f,t1 :: ... :: tn)] is [f (t1, ..., tn)] *)
| AppAt of lsymb * term list * term
| ForAll of bnds * term
| Exists of bnds * term
and term = term_i L.located
let equal_p_ty t t' = match L.unloc t, L.unloc t' with
| P_message , P_message
| P_boolean , P_boolean
| P_index , P_index
| P_timestamp, P_timestamp -> true
| P_tbase b, P_tbase b' -> L.unloc b = L.unloc b'
| P_tvar v, P_tvar v' -> L.unloc v = L.unloc v'
| _, _ -> false
let equal_bnds l l' =
List.for_all2 (fun (s,k) (s',k') ->
L.unloc s = L.unloc s' && equal_p_ty k k'
) l l'
let rec equal t t' = match L.unloc t, L.unloc t' with
| Diff (a,b), Diff (a',b') ->
equal a a' && equal b b'
| Seq (l, a), Seq (l', a')
| ForAll (l, a), ForAll (l', a')
| Exists (l, a), Exists (l', a') ->
List.length l = List.length l' &&
equal_bnds l l' &&
equal a a'
| Find (l, a, b, c), Find (l', a', b', c') ->
List.length l = List.length l' &&
equal_bnds l l' &&
equals [a; b; c] [a'; b'; c']
| AppAt (s, ts, t), AppAt (s', ts', t') ->
L.unloc s = L.unloc s' &&
equals (t :: ts) (t' :: ts')
| App (s, ts), App (s', ts') ->
L.unloc s = L.unloc s' &&
equals ts ts'
| _ -> false
and equals l l' = List.for_all2 equal l l'
let var_i loc x : term_i = App (L.mk_loc loc x,[])
let var loc x : term = L.mk_loc loc (var_i loc x)
let var_of_lsymb s : term = var (L.loc s) (L.unloc s)
let destr_var = function
| App (v, []) -> Some v
| _ -> None
let pp_var_list ppf l =
let rec aux cur_vars (cur_type : p_ty_i) = function
| (v,vty) :: vs when L.unloc vty = cur_type ->
aux ((L.unloc v) :: cur_vars) cur_type vs
| vs ->
if cur_vars <> [] then begin
Fmt.list
~sep:(fun fmt () -> Fmt.pf fmt ",")
Fmt.string ppf (List.rev cur_vars) ;
Fmt.pf ppf ":%a" pp_p_ty_i cur_type ;
if vs <> [] then Fmt.pf ppf ",@,"
end ;
match vs with
| [] -> ()
| (v, vty) :: vs -> aux [L.unloc v] (L.unloc vty) vs
in
aux [] P_message l
let rec pp_term_i ppf t = match t with
| Tpat -> Fmt.pf ppf "_"
| Find (vs,c,t,e) ->
Fmt.pf ppf
"@[%a@ %a@ %a@ %a@ %a@ %a@ %a@ %a@]"
(Printer.kws `TermCondition) "try find"
pp_var_list vs
(Printer.kws `TermCondition) "such that"
pp_term c
(Printer.kws `TermCondition) "in"
pp_term t
(Printer.kws `TermCondition) "else"
pp_term e
| Diff (l,r) ->
Fmt.pf ppf "%a(%a,%a)"
(Printer.kws `TermDiff) "diff"
pp_term l
pp_term r
| App (f,[t1;t2]) when L.unloc f = "exp" ->
Fmt.pf ppf "%a^%a" pp_term t1 pp_term t2
| App (f,[i;t;e]) when L.unloc f = "if" ->
Fmt.pf ppf
"@[%a@ %a@ %a@ %a@ %a@ %a@]"
(Printer.kws `TermCondition) "if"
pp_term i
(Printer.kws `TermCondition) "then"
pp_term t
(Printer.kws `TermCondition) "else"
pp_term e
| App (f, [L.{ pl_desc = App (f1,[bl1;br1])};
L.{ pl_desc = App (f2,[br2;bl2])}])
when L.unloc f = "&&" && L.unloc f1 = "=>" && L.unloc f2 = "=>" &&
bl1 = bl2 && br1 = br2 ->
Fmt.pf ppf "@[<1>(%a@ <=>@ %a)@]"
pp_term bl1 pp_term br1
| App (f,[bl;br]) when Symbols.is_infix_str (L.unloc f) ->
Fmt.pf ppf "@[<1>(%a@ %s@ %a)@]"
pp_term bl (L.unloc f) pp_term br
| App (f,[b]) when L.unloc f = "not" ->
Fmt.pf ppf "not(@[%a@])" pp_term b
| App (f,[]) when L.unloc f = "true" -> Printer.kws `TermBool ppf "True"
| App (f,[]) when L.unloc f = "false" -> Printer.kws `TermBool ppf "False"
| App (f,terms) ->
Fmt.pf ppf "%s%a"
(L.unloc f)
(Utils.pp_list pp_term) terms
| AppAt (f,terms,ts) ->
Fmt.pf ppf "%s%a%a"
(L.unloc f)
(Utils.pp_list pp_term) terms
pp_ts ts
| Seq (vs, b) ->
Fmt.pf ppf "@[<hov 2>%a(%a->@,@[%a@])@]"
(Printer.kws `TermSeq) "seq"
pp_var_list vs
pp_term b
| ForAll (vs, b) ->
Fmt.pf ppf "@[%a (@[%a@]),@ %a@]"
(Printer.kws `TermQuantif) "forall"
pp_var_list vs
pp_term b
| Exists (vs, b) ->
Fmt.pf ppf "@[%a (@[%a@]),@ %a@]"
(Printer.kws `TermQuantif) "exists"
pp_var_list vs
pp_term b
and pp_ts ppf ts = Fmt.pf ppf "@%a" pp_term ts
and pp_term ppf t =
Fmt.pf ppf "%a" pp_term_i (L.unloc t)
let pp = pp_term
let pp_i = pp_term_i
* { 2 Higher - order terms }
type hterm_i =
| Lambda of bnds * term
type hterm = hterm_i L.located
* { 2 Equivalence formulas }
type equiv = term list
type pquant = PForAll | PExists
type global_formula = global_formula_i Location.located
and global_formula_i =
| PEquiv of equiv
| PReach of term
| PImpl of global_formula * global_formula
| PAnd of global_formula * global_formula
| POr of global_formula * global_formula
| PQuant of pquant * bnds * global_formula
* { 2 Any term : local or global }
type any_term = Global of global_formula | Local of term
* { 2 Error handling }
type conversion_error_i =
| Arity_error of string*int*int
| Untyped_symbol of string
| Index_error of string*int*int
| Undefined of string
| UndefinedOfKind of string * Symbols.namespace
| Type_error of term_i * Type.ty
| Timestamp_expected of term_i
| Timestamp_unexpected of term_i
| Unsupported_ord of term_i
| String_expected of term_i
| Int_expected of term_i
| Tactic_type of string
| NotVar
| Assign_no_state of string
| BadNamespace of string * Symbols.namespace
| Freetyunivar
| UnknownTypeVar of string
| BadPty of Type.ty list
| BadInfixDecl
| PatNotAllowed
| ExplicitTSInProc
| UndefInSystem of SE.t
| MissingSystem
| BadProjInSubterm of Term.projs * Term.projs
type conversion_error = L.t * conversion_error_i
exception Conv of conversion_error
let conv_err loc e = raise (Conv (loc,e))
let pp_error_i ppf = function
| Arity_error (s,i,j) -> Fmt.pf ppf "Symbol %s used with arity %i, but \
defined with arity %i" s i j
| Untyped_symbol s -> Fmt.pf ppf "Symbol %s is not typed" s
| Index_error (s,i,j) -> Fmt.pf ppf "Symbol %s used with %i indices, but \
defined with %i indices" s i j
| Undefined s -> Fmt.pf ppf "symbol %s is undefined" s
| UndefinedOfKind (s,n) ->
Fmt.pf ppf "%a %s is undefined" Symbols.pp_namespace n s
| Type_error (s, ty) ->
Fmt.pf ppf "@[<hov 0>Term@;<1 2>@[%a@]@ is not of type @[%a@]@]" pp_i s Type.pp ty
| Timestamp_expected t ->
Fmt.pf ppf "The term %a must be given a timestamp" pp_i t
| Timestamp_unexpected t ->
Fmt.pf ppf "The term %a must not be given a timestamp" pp_i t
| Unsupported_ord t ->
Fmt.pf ppf
"comparison %a cannot be typed@ \
(operands have a type@ for which the comparison is allowed)"
pp_i t
| String_expected t ->
Fmt.pf ppf
"The term %a cannot be seen as a string"
pp_i t
| Int_expected t ->
Fmt.pf ppf
"The term %a cannot be seen as a int"
pp_i t
| Tactic_type s ->
Fmt.pf ppf "The tactic arguments could not be parsed: %s" s
| NotVar ->
Fmt.pf ppf "must be a variable"
| Assign_no_state s ->
Fmt.pf ppf "Only mutables can be assigned values, and the \
symbols %s is not a mutable" s
| BadNamespace (s,n) ->
Fmt.pf ppf "Kind error: %s has kind %a" s
Symbols.pp_namespace n
| Freetyunivar -> Fmt.pf ppf "some type variable(s) could not \
be instantiated"
| UnknownTypeVar ty ->
Fmt.pf ppf "undefined type variable %s" ty
| BadPty l ->
Fmt.pf ppf "type must be of type %a"
(Fmt.list ~sep:Fmt.comma Type.pp) l
| BadInfixDecl -> Fmt.pf ppf "bad infix symbol declaration"
| PatNotAllowed -> Fmt.pf ppf "pattern not allowed"
| ExplicitTSInProc ->
Fmt.pf ppf "macros cannot be written at explicit \
timestamps in procedure"
| UndefInSystem t ->
Fmt.pf ppf "action not defined in system @[%a@]"
SE.pp t
| MissingSystem ->
Fmt.pf ppf "missing system annotation"
| BadProjInSubterm (ps1, ps2) ->
Fmt.pf ppf "@[<v 2>invalid projection:@;missing projections: %a@;\
unknown projections: %a@]"
Term.pp_projs ps1
Term.pp_projs ps2
let pp_error pp_loc_err ppf (loc,e) =
Fmt.pf ppf "%a@[<hov 2>Conversion error:@, %a@]"
pp_loc_err loc
pp_error_i e
* { 2 Parsing types }
let parse_p_ty (env : Env.t) (pty : p_ty) : Type.ty =
match L.unloc pty with
| P_message -> Type.tmessage
| P_boolean -> Type.tboolean
| P_index -> Type.tindex
| P_timestamp -> Type.ttimestamp
| P_tvar tv_l ->
let tv =
try
List.find (fun tv' ->
let tv' = Type.ident_of_tvar tv' in
Ident.name tv' = L.unloc tv_l
) env.ty_vars
with Not_found ->
conv_err (L.loc tv_l) (UnknownTypeVar (L.unloc tv_l))
in
TVar tv
| P_tbase tb_l ->
let s = Symbols.BType.of_lsymb tb_l env.table in
* { 2 Type checking }
let check_arity_i loc s (actual : int) (expected : int) =
if actual <> expected then
conv_err loc (Arity_error (s,actual,expected))
let check_arity (lsymb : lsymb) (actual : int) (expected : int) =
check_arity_i (L.loc lsymb) (L.unloc lsymb) actual expected
* Macro or function type
type mf_type = [`Fun of Type.ftype | `Macro of mtype]
let ftype_arity (fty : Type.ftype) =
fty.Type.fty_iarr + (List.length fty.Type.fty_args)
let mf_type_arity (ty : mf_type) =
match ty with
| `Fun ftype -> ftype_arity ftype
| `Macro (l,_) -> List.length l
let function_kind table (f : lsymb) : mf_type =
let open Symbols in
match def_of_lsymb f table with
| Reserved _ -> assert false
| Exists d -> match d with
| Function (fty, _) -> `Fun fty
| Macro (Global (arity, ty)) ->
let targs = (List.init arity (fun _ -> Type.tindex)) in
`Macro (targs, ty)
| Macro (Input|Output|Frame) ->
`Macro ([], Type.tmessage)
| Macro (Cond|Exec) ->
`Macro ([], Type.tboolean)
| _ -> conv_err (L.loc f) (Untyped_symbol (L.unloc f))
let check_state table (s : lsymb) n : Type.ty =
match Symbols.Macro.def_of_lsymb s table with
| Symbols.State (arity,ty) ->
check_arity s n arity ;
ty
| _ -> conv_err (L.loc s) (Assign_no_state (L.unloc s))
let check_name table (s : lsymb) n : Type.ftype =
let fty = (Symbols.Name.def_of_lsymb s table).n_fty in
let arity = List.length fty.fty_args in
if arity <> n then conv_err (L.loc s) (Index_error (L.unloc s,n,arity));
fty
let check_action (env : Env.t) (s : lsymb) (n : int) : unit =
let l,action = Action.find_symbol s env.table in
let arity = List.length l in
if arity <> n then conv_err (L.loc s) (Index_error (L.unloc s,n,arity));
try
let system = SE.to_compatible env.system.set in
ignore (SE.action_to_term env.table system action)
with _ -> conv_err (L.loc s) (UndefInSystem env.system.set)
type app_i =
| Name of lsymb * term list
| Get of lsymb * Term.term option * term list
* [ Get ( s , ots , terms ) ] reads the contents of memory cell
* [ ( s , terms ) ] where [ terms ] are evaluated as indices .
* The second argument [ ots ] is for the optional timestamp at which the
* memory read is performed . This is used for the terms appearing in
* goals .
* [(s,terms)] where [terms] are evaluated as indices.
* The second argument [ots] is for the optional timestamp at which the
* memory read is performed. This is used for the terms appearing in
* goals. *)
| Fun of lsymb * term list * Term.term option
* Function symbol application ,
* where terms will be evaluated as indices or messages
* depending on the type of the function symbol .
* The third argument is an optional timestamp , used when
* writing meta - logic formulas but not in processes .
* where terms will be evaluated as indices or messages
* depending on the type of the function symbol.
* The third argument is an optional timestamp, used when
* writing meta-logic formulas but not in processes. *)
| Taction of lsymb * term list
| AVar of lsymb
and app = app_i L.located
let[@warning "-32"] pp_app_i ppf = function
| Taction (a,l) ->
Fmt.pf ppf "%s%a"
(L.unloc a)
(Utils.pp_list pp_term) l
| Fun (f,[t1;t2],ots) when L.unloc f="exp"->
Fmt.pf ppf "%a^%a" pp_term t1 pp_term t2
| Fun (f,terms,ots) ->
Fmt.pf ppf "%s%a%a"
(L.unloc f)
(Utils.pp_list pp_term) terms
(Fmt.option Term.pp) ots
| Name (n,terms) ->
Fmt.pf ppf "%a%a"
Term.pp_name (Obj.magic n)
(Utils.pp_list pp_term) terms
| Get (s,ots,terms) ->
Fmt.pf ppf "!%s%a%a"
(L.unloc s)
(Utils.pp_list pp_term) terms
(Fmt.option Term.pp) ots
| AVar s -> Fmt.pf ppf "%s" (L.unloc s)
type app_cntxt =
let is_at = function At _ -> true | _ -> false
let get_ts = function At ts | MaybeAt ts -> Some ts | _ -> None
let make_app_i table cntxt (lsymb : lsymb) (l : term list) : app_i =
let loc = L.loc lsymb in
let arity_error i =
conv_err loc (Arity_error (L.unloc lsymb, List.length l, i)) in
let ts_unexpected () =
conv_err loc (Timestamp_unexpected (App (lsymb,l))) in
match Symbols.def_of_lsymb lsymb table with
| Symbols.Reserved _ -> Fmt.epr "%s@." (L.unloc lsymb); assert false
| Symbols.Exists d ->
begin match d with
| Symbols.Function (ftype,fdef) ->
if is_at cntxt then ts_unexpected ();
let farity = ftype_arity ftype in
if List.length l <> farity then raise (arity_error farity) ;
Fun (lsymb,l,None)
| Symbols.Name ndef ->
if is_at cntxt then ts_unexpected ();
check_arity lsymb (List.length l) (List.length ndef.n_fty.fty_args) ;
Name (lsymb,l)
| Symbols.Macro (Symbols.State (arity,_)) ->
check_arity lsymb (List.length l) arity ;
Get (lsymb,get_ts cntxt,l)
| Symbols.Macro (Symbols.Global (arity,_)) ->
if List.length l <> arity then arity_error arity;
Fun (lsymb,l,get_ts cntxt)
| Symbols.Macro (Symbols.Input|Symbols.Output|Symbols.Cond|Symbols.Exec
|Symbols.Frame) ->
if cntxt = NoTS then
conv_err loc (Timestamp_expected (App (lsymb,l)));
if l <> [] then arity_error 0;
Fun (lsymb,[],get_ts cntxt)
| Symbols.Action arity ->
if arity <> List.length l then arity_error arity ;
Taction (lsymb,l)
| Symbols.Channel _
| Symbols.BType _
| Symbols.Process _
| Symbols.System _ ->
let s = L.unloc lsymb in
conv_err loc (BadNamespace (s,
oget(Symbols.get_namespace table s)))
end
| exception Symbols.SymbError (loc, Symbols.Unbound_identifier s) ->
if l <> [] then
raise (Symbols.SymbError (loc, Symbols.Unbound_identifier s));
AVar lsymb
let make_app loc table cntxt (lsymb : lsymb) (l : term list) : app =
L.mk_loc loc (make_app_i table cntxt lsymb l)
* { 2 Substitution }
type esubst = ESubst : string * Term.term -> esubst
type subst = esubst list
let subst t (s : (string * term_i) list) =
let rec aux_i = function
| App (x, []) as t ->
begin try
let ti = List.assoc (L.unloc x) s in
ti
with Not_found -> t
end
| Tpat -> Tpat
| App (s,l) -> App (s, List.map aux l)
| AppAt (s,l,ts) -> AppAt (s, List.map aux l, aux ts)
| Seq (vs,t) -> Seq (vs, aux t)
| ForAll (vs,f) -> ForAll (vs, aux f)
| Exists (vs,f) -> Exists (vs, aux f)
| Diff (l,r) -> Diff (aux l, aux r)
| Find (is,c,t,e) -> Find (is, aux c, aux t, aux e)
and aux t = L.mk_loc (L.loc t) (aux_i (L.unloc t))
in aux t
* { 2 Conversion contexts and states }
type conv_cntxt =
| InProc of Term.projs * Term.term
| InGoal
let is_in_proc = function InProc _ -> true | InGoal -> false
type conv_env = {
env : Env.t;
cntxt : conv_cntxt;
}
type conv_state = {
env : Env.t;
cntxt : conv_cntxt;
allow_pat : bool;
ty_env : Type.Infer.env;
}
let mk_state env cntxt allow_pat ty_env =
{ cntxt; env; allow_pat; ty_env; }
let ty_error ty_env tm ty =
let ty = Type.Infer.norm ty_env ty in
Conv (L.loc tm, Type_error (L.unloc tm, ty))
let check_ty_leq state ~of_t (t_ty : Type.ty) (ty : Type.ty) : unit =
match Type.Infer.unify_leq state.ty_env t_ty ty with
| `Ok -> ()
| `Fail ->
raise (ty_error state.ty_env of_t ty)
let check_ty_eq state ( t_ty : Type.ty ) ( ty : ' b Type.ty ) : unit =
* match Type . Infer.unify_eq state.ty_env t_ty ty with
* | ` Ok - > ( )
* | ` Fail - > raise ( ty_error state.ty_env of_t ty )
* match Type.Infer.unify_eq state.ty_env t_ty ty with
* | `Ok -> ()
* | `Fail -> raise (ty_error state.ty_env of_t ty) *)
let check_term_ty state ~of_t (t : Term.term) (ty : Type.ty) : unit =
check_ty_leq state ~of_t (Term.ty ~ty_env:state.ty_env t) ty
* { 2 System projections }
let check_system_projs loc (state : conv_state) (projs : Term.projs) : unit =
let current_projs =
match state.cntxt with
| InProc (ps, _) -> ps
| InGoal ->
if not (SE.is_fset state.env.system.set) then
conv_err loc MissingSystem;
let fset = SE.to_fset state.env.system.set in
SE.to_projs fset
in
let diff1 = List.diff current_projs projs
and diff2 = List.diff projs current_projs in
if diff1 <> [] || diff2 <> [] then
conv_err loc (BadProjInSubterm (diff1, diff2))
let proj_state (projs : Term.projs) (state : conv_state) : conv_state =
match state.cntxt with
| InProc (ps, ts) -> { state with cntxt = InProc ([Term.left_proj], ts) }
| InGoal -> { state with env = projs_set [Term.left_proj ] state.env }
* { 2 Conversion }
let convert_var
(state : conv_state)
(st : lsymb)
(ty : Type.ty)
: Term.term
=
try
let v = Vars.find state.env.vars (L.unloc st) in
let of_t = var_of_lsymb st in
check_ty_leq state ~of_t (Vars.ty v) ty;
Term.mk_var v
with
| Not_found -> conv_err (L.loc st) (Undefined (L.unloc st))
let convert_bnds (env : Env.t) (vars : (lsymb * Type.ty) list) =
let do1 (vars, v_acc) (vsymb, s) =
let vars, v = Vars.make `Shadow vars s (L.unloc vsymb) in
vars, v :: v_acc
in
let venv, v_acc = List.fold_left do1 (env.vars, []) vars in
{ env with vars = venv }, List.rev v_acc
let convert_p_bnds (env : Env.t) (vars : bnds) =
let vs = List.map (fun (v,s) -> v, parse_p_ty env s) vars in
convert_bnds env vs
let get_fun table lsymb =
match Symbols.Function.of_lsymb_opt lsymb table with
| Some n -> n
| None ->
conv_err (L.loc lsymb) (UndefinedOfKind (L.unloc lsymb, Symbols.NFunction))
let get_name table lsymb =
match Symbols.Name.of_lsymb_opt lsymb table with
| Some n -> n
| None ->
conv_err (L.loc lsymb) (UndefinedOfKind (L.unloc lsymb, Symbols.NName))
let get_action (env : Env.t) lsymb =
match Symbols.Action.of_lsymb_opt lsymb env.table with
| Some n -> n
| None ->
conv_err (L.loc lsymb) (UndefinedOfKind (L.unloc lsymb, Symbols.NAction))
let get_macro (env : Env.t) lsymb =
match Symbols.Macro.of_lsymb_opt lsymb env.table with
| Some n -> n
| None ->
conv_err (L.loc lsymb) (UndefinedOfKind (L.unloc lsymb, Symbols.NMacro))
internal function to Theory.ml
let rec convert
(state : conv_state)
(tm : term)
(ty : Type.ty)
: Term.term
=
let t = convert0 state tm ty in
check_term_ty state ~of_t:tm t ty;
t
and convert0
(state : conv_state)
(tm : term)
(ty : Type.ty) : Term.term
=
let loc = L.loc tm in
let conv ?(env=state.env) s t =
let state = { state with env } in
convert state t s in
let type_error () = raise (ty_error state.ty_env tm ty) in
match L.unloc tm with
| Tpat ->
if not state.allow_pat then
conv_err (L.loc tm) PatNotAllowed;
let _, p = Vars.make ~allow_pat:true `Approx state.env.vars ty "_" in
Term.mk_var p
| App ({ pl_desc = "init" },terms) ->
if terms <> [] then type_error ();
Term.mk_action Symbols.init_action []
| App ({ pl_desc = "happens" },ts) ->
let atoms = List.map (fun t ->
Term.mk_happens (conv Type.Timestamp t)
) ts in
Term.mk_ands atoms
| App (f,terms) ->
if terms = [] && Vars.mem_s state.env.vars (L.unloc f)
then convert_var state f ty
else
let app_cntxt = match state.cntxt with
| InGoal -> NoTS
| InProc (_, ts) -> MaybeAt ts in
conv_app state app_cntxt
(tm, make_app loc state.env.table app_cntxt f terms)
ty
| AppAt (f,terms,ts) ->
if is_in_proc state.cntxt then conv_err loc ExplicitTSInProc;
let app_cntxt = At (conv Type.Timestamp ts) in
conv_app state app_cntxt
(tm, make_app loc state.env.table app_cntxt f terms)
ty
| Diff (l,r) ->
check_system_projs loc state [Term.left_proj; Term.right_proj];
let statel = proj_state [Term.left_proj ] state in
let stater = proj_state [Term.right_proj] state in
Term.mk_diff [Term.left_proj , convert statel l ty;
Term.right_proj, convert stater r ty; ]
| Find (vs,c,t,e) ->
let env, is =
convert_p_bnds state.env vs
in
Vars.check_type_vars is [Type.tindex; Type.ttimestamp] type_error;
let c = conv ~env Type.tboolean c in
let t = conv ~env ty t in
let e = conv ty e in
Term.mk_find is c t e
| ForAll (vs,f) | Exists (vs,f) ->
let env, evs = convert_p_bnds state.env vs in
let f = conv ~env Type.tboolean f in
begin match L.unloc tm with
| ForAll _ -> Term.mk_forall evs f
| Exists _ -> Term.mk_exists evs f
| _ -> assert false
end
| Seq (vs,t) ->
let env, evs = convert_p_bnds state.env vs in
let tyv = Type.Infer.mk_univar state.ty_env in
let t = conv ~env (Type.TUnivar tyv) t in
let () =
Vars.check_type_vars evs [Type.tindex; Type.ttimestamp] type_error
in
Term.mk_seq0 ~simpl:false evs t
and conv_var state t ty =
match convert state t ty with
| Term.Var x -> x
| _ -> conv_err (L.loc t) NotVar
and conv_vars state ts tys = List.map2 (conv_var state) ts tys
and conv_app
(state : conv_state)
(app_cntxt : app_cntxt)
((tm,app) : (term * app))
(ty : Type.ty)
: Term.term
=
let loc = L.loc tm in
let t_i = L.unloc tm in
let conv ?(env=state.env) s t =
let state = { state with env } in
convert state t s in
let get_at ts_opt =
match ts_opt, get_ts app_cntxt with
| Some ts, _ -> ts
| None, Some ts -> ts
| None, None -> conv_err loc (Timestamp_expected (L.unloc tm))
in
let conv_fapp (f : lsymb) l ts_opt : Term.term =
let mfty = function_kind state.env.table f in
let () = check_arity f (List.length l) (mf_type_arity mfty) in
match Symbols.of_lsymb f state.env.table with
| Symbols.Wrapped (symb, Function (_,_)) ->
assert (ts_opt = None);
let fty = match mfty with `Fun x -> x | _ -> assert false in
let fty_op = Type.open_ftype state.ty_env fty in
let l_indices, l_messages = List.takedrop fty_op.Type.fty_iarr l in
let indices =
List.map (fun x -> conv_var state x Type.tindex) l_indices
in
let rmessages =
List.fold_left2 (fun rmessages t ty ->
let t = conv ty t in
t :: rmessages
) [] l_messages fty_op.Type.fty_args
in
let messages = List.rev rmessages in
let t = Term.mk_fun0 (symb,indices) fty messages in
check_term_ty state ~of_t:tm t fty_op.Type.fty_out;
t
| Wrapped (s, Symbols.Macro macro) ->
let ty_args, ty_out =
match mfty with `Macro x -> x | _ -> assert false
in
begin match macro with
| Symbols.State _ -> assert false
| Symbols.Global _ ->
assert (List.for_all (fun x -> x = Type.tindex) ty_args);
let indices =
List.map (fun x ->
conv_var state x Type.tindex
) l
in
let ms = Term.mk_isymb s ty_out indices in
Term.mk_macro ms [] (get_at ts_opt)
| Input | Output | Frame ->
check_arity_i (L.loc f) "input" (List.length l) 0 ;
let ms = Term.mk_isymb s ty_out [] in
Term.mk_macro ms [] (get_at ts_opt)
| Cond | Exec ->
check_arity_i (L.loc f) "cond" (List.length l) 0 ;
let ms = Term.mk_isymb s ty_out [] in
Term.mk_macro ms [] (get_at ts_opt)
end
| Wrapped (_, _) -> assert false
in
match L.unloc app with
| AVar s -> convert_var state s ty
| Fun (f,l,ts_opt) -> conv_fapp f l ts_opt
| Get (s,opt_ts,is) ->
let k = check_state state.env.table s (List.length is) in
let is = List.map (fun i -> conv_var state i Type.tindex) is in
let s = get_macro state.env s in
let ts =
match opt_ts with
| Some ts -> ts
| None -> conv_err loc (Timestamp_expected t_i)
in
let ms = Term.mk_isymb s k is in
Term.mk_macro ms [] ts
| Name (s, is) ->
let s_fty = check_name state.env.table s (List.length is) in
assert (s_fty.fty_iarr = 0 && s_fty.fty_vars = []);
let is = conv_vars state is s_fty.fty_args in
let ns = Term.mk_isymb (get_name state.env.table s) s_fty.fty_out is in
Term.mk_name ns
| Taction (a,is) ->
check_action state.env a (List.length is) ;
Term.mk_action
(get_action state.env a)
(List.map (fun x -> conv_var state x Type.tindex) is)
* convert HO terms
let conv_ht (state : conv_state) (t : hterm) : Type.hty * Term.hterm =
match L.unloc t with
| Lambda (bnds, t0) ->
let env, evs = convert_p_bnds state.env bnds in
let state = { state with env } in
let tyv = Type.Infer.mk_univar state.ty_env in
let ty = Type.TUnivar tyv in
let ht = Term.Lambda (evs, convert state t0 ty) in
let bnd_tys = List.map Vars.ty evs in
let hty = Type.Lambda (bnd_tys, ty) in
hty, ht
* { 2 Function declarations }
let mk_ftype iarr vars args out =
let mdflt ty = odflt Type.tmessage ty in
Type.mk_ftype iarr vars (List.map mdflt args) (mdflt out)
let declare_dh
(table : Symbols.table)
(h : Symbols.dh_hyp list)
?group_ty ?exp_ty
(gen : lsymb)
((exp, f_info) : lsymb * Symbols.symb_type)
(omult : (lsymb * Symbols.symb_type) option)
: Symbols.table =
let open Symbols in
let gen_fty = mk_ftype 0 [] [] group_ty in
let exp_fty = mk_ftype 0 [] [group_ty; exp_ty] group_ty in
let table, exp = Function.declare_exact table exp (exp_fty, Abstract f_info) in
let (table, af) = match omult with
| None -> (table, [exp])
| Some (mult, mf_info) ->
let mult_fty = mk_ftype 0 [] [exp_ty; exp_ty] exp_ty in
let (table, mult) =
Function.declare_exact table mult (mult_fty, Abstract mf_info)
in
(table, [exp; mult])
in
let data = AssociatedFunctions af in
fst (Function.declare_exact table ~data gen (gen_fty, DHgen h))
let declare_hash table ?index_arity ?m_ty ?k_ty ?h_ty s =
let index_arity = odflt 0 index_arity in
let ftype = mk_ftype index_arity [] [m_ty; k_ty] h_ty in
let def = ftype, Symbols.Hash in
fst (Symbols.Function.declare_exact table s def)
let declare_aenc table ?ptxt_ty ?ctxt_ty ?rnd_ty ?sk_ty ?pk_ty enc dec pk =
let open Symbols in
let dec_fty = mk_ftype 0 [] [ctxt_ty; sk_ty] ptxt_ty in
let enc_fty = mk_ftype 0 [] [ptxt_ty; rnd_ty; pk_ty] ctxt_ty in
let pk_fty = mk_ftype 0 [] [sk_ty] pk_ty in
let table, pk = Function.declare_exact table pk (pk_fty,PublicKey) in
let dec_data = AssociatedFunctions [Function.cast_of_string (L.unloc enc); pk] in
let table, dec = Function.declare_exact table dec ~data:dec_data (dec_fty,ADec) in
let data = AssociatedFunctions [dec; pk] in
fst (Function.declare_exact table enc ~data (enc_fty,AEnc))
let declare_senc table ?ptxt_ty ?ctxt_ty ?rnd_ty ?k_ty enc dec =
let open Symbols in
let data = AssociatedFunctions [Function.cast_of_string (L.unloc enc)] in
let dec_fty = mk_ftype 0 [] [ctxt_ty; k_ty] ptxt_ty in
let enc_fty = mk_ftype 0 [] [ptxt_ty; rnd_ty; k_ty] ctxt_ty in
let table, dec = Function.declare_exact table dec ~data (dec_fty,SDec) in
let data = AssociatedFunctions [dec] in
fst (Function.declare_exact table enc ~data (enc_fty,SEnc))
let declare_senc_joint_with_hash
table ?ptxt_ty ?ctxt_ty ?rnd_ty ?k_ty enc dec h =
let open Symbols in
let data = AssociatedFunctions [Function.cast_of_string (L.unloc enc);
get_fun table h] in
let dec_fty = mk_ftype 0 [] [ctxt_ty; k_ty] ptxt_ty in
let enc_fty = mk_ftype 0 [] [ptxt_ty; rnd_ty; k_ty] ctxt_ty in
let table, dec = Function.declare_exact table dec ~data (dec_fty,SDec) in
let data = AssociatedFunctions [dec] in
fst (Function.declare_exact table enc ~data (enc_fty,SEnc))
let declare_signature table
?m_ty ?sig_ty ?check_ty ?sk_ty ?pk_ty
sign checksign pk =
let open Symbols in
let sig_fty = mk_ftype 0 [] [m_ty; sk_ty] sig_ty in
let check_fty = mk_ftype 0 [] [sig_ty; pk_ty] check_ty in
let pk_fty = mk_ftype 0 [] [sk_ty] pk_ty in
let table,sign = Function.declare_exact table sign (sig_fty, Sign) in
let table,pk = Function.declare_exact table pk (pk_fty,PublicKey) in
let data = AssociatedFunctions [sign; pk] in
fst (Function.declare_exact table checksign ~data (check_fty,CheckSign))
let check_signature table checksign pk =
let def x = Symbols.Function.get_def x table in
let correct_type = match def checksign, def pk with
| (_,Symbols.CheckSign), (_,Symbols.PublicKey) -> true
| _ -> false
in
if correct_type then
match Symbols.Function.get_data checksign table with
| Symbols.AssociatedFunctions [sign; pk2] when pk2 = pk -> Some sign
| _ -> None
else None
let declare_name table s ndef =
fst (Symbols.Name.declare_exact table s ndef)
let check_fun_symb
table
(ty_args : Type.tvar list) (in_tys : Type.ty list) (index_arity : int)
(s : lsymb) (f_info : Symbols.symb_type) : unit
=
match f_info with
| `Prefix -> ()
| `Infix side ->
if not (index_arity = 0) ||
not (List.length ty_args = 0) ||
not (List.length in_tys = 2) then
conv_err (L.loc s) BadInfixDecl
let declare_abstract
table ~index_arity ~ty_args ~in_tys ~out_ty
(s : lsymb) (f_info : Symbols.symb_type)
=
check_fun_symb table ty_args in_tys index_arity s f_info;
let ftype = Type.mk_ftype index_arity ty_args in_tys out_ty in
fst (Symbols.Function.declare_exact table s (ftype, Symbols.Abstract f_info))
* { 2 Miscellaneous }
let empty loc = L.mk_loc loc (App (L.mk_loc loc "empty", []))
* { 2 Exported conversion and type - checking functions }
let convert_ht
?ty_env
?(pat=false)
(cenv : conv_env)
(ht0 : hterm)
: Type.hty * Term.hterm
=
let must_close, ty_env = match ty_env with
| None -> true, Type.Infer.mk_env ()
| Some ty_env -> false, ty_env
in
let state = mk_state cenv.env cenv.cntxt pat ty_env in
let hty, ht = conv_ht state ht0 in
if must_close then
begin
if not (Type.Infer.is_closed state.ty_env) then
conv_err (L.loc ht0) Freetyunivar;
let tysubst = Type.Infer.close ty_env in
Type.tsubst_ht tysubst hty, Term.tsubst_ht tysubst ht
end
else
Type.Infer.htnorm state.ty_env hty, ht
let check
(env : Env.t) ?(local=false) ?(pat=false)
(ty_env : Type.Infer.env)
(projs : Term.projs)
(t : term) (s : Type.ty)
: unit
=
let dummy_var s =
Term.mk_var (snd (Vars.make `Approx Vars.empty_env s "#dummy"))
in
let cntxt = if local then InProc (projs, (dummy_var Type.Timestamp)) else InGoal in
let state = mk_state env cntxt pat ty_env in
ignore (convert state t s)
* exported outside Theory.ml
let convert
?(ty : Type.ty option)
?(ty_env : Type.Infer.env option)
?(pat : bool = false)
(cenv : conv_env)
(tm : term)
: Term.term * Type.ty
=
let must_close, ty_env = match ty_env with
| None -> true, Type.Infer.mk_env ()
| Some ty_env -> false, ty_env
in
let ty = match ty with
| None -> Type.TUnivar (Type.Infer.mk_univar ty_env)
| Some ty -> ty
in
let state = mk_state cenv.env cenv.cntxt pat ty_env in
let t = convert state tm ty in
if must_close then
begin
if not (Type.Infer.is_closed state.ty_env) then
conv_err (L.loc tm) Freetyunivar;
let tysubst = Type.Infer.close ty_env in
Term.tsubst tysubst t, Type.tsubst tysubst ty
end
else
t, Type.Infer.norm ty_env ty
* { 2 Convert equiv formulas }
let convert_equiv cenv (e : equiv) =
let convert_el el : Term.term =
let t, _ = convert cenv el in
t
in
List.map convert_el e
let convert_global_formula (cenv : conv_env) (p : global_formula) =
let rec conve (cenv : conv_env) p =
let conve ?(env=cenv.env) p = conve { cenv with env } p in
match L.unloc p with
| PImpl (f1, f2) -> Equiv.Impl (conve f1, conve f2)
| PAnd (f1, f2) -> Equiv.And (conve f1, conve f2)
| POr (f1, f2) -> Equiv.Or (conve f1, conve f2)
| PEquiv e ->
begin match cenv.env.system with
| SE.{ pair = Some p } ->
let system = SE.{ set = (p :> SE.t) ; pair = None } in
let env = Env.update ~system cenv.env in
let cenv = { cenv with env } in
Equiv.Atom (Equiv.Equiv (convert_equiv cenv e))
| _ ->
conv_err (L.loc p) MissingSystem
end
| PReach f ->
let f, _ = convert ~ty:Type.tboolean cenv f in
Equiv.Atom (Equiv.Reach f)
| PQuant (q, bnds, e) ->
let env, evs = convert_p_bnds cenv.env bnds in
let e = conve ~env e in
let q = match q with
| PForAll -> Equiv.ForAll
| PExists -> Equiv.Exists
in
Equiv.mk_quant q evs e
in
conve cenv p
* { 2 Convert any }
let convert_any (cenv : conv_env) (p : any_term) : Equiv.any_form =
match p with
| Local p -> Local (fst (convert ~ty:Type.Boolean cenv p))
| Global p -> Global (convert_global_formula cenv p)
* { 2 State and substitution parsing }
let parse_subst (env : Env.t) (uvars : Vars.var list) (ts : term list)
: Term.subst =
let conv_env = { env; cntxt = InGoal; } in
let f t u =
let t, _ = convert ~ty:(Vars.ty u) conv_env t in
Term.ESubst (Term.mk_var u, t)
in
List.map2 f ts uvars
type Symbols.data += StateInit_data of Vars.var list * Term.term
let declare_state
(table : Symbols.table)
(s : lsymb)
(typed_args : bnds)
(pty : p_ty)
(t : term)
=
let ts_init = Term.mk_action Symbols.init_action [] in
let env = Env.init ~table () in
let conv_env = { env; cntxt = InProc ([], ts_init); } in
let env, indices = convert_p_bnds env typed_args in
let conv_env = { conv_env with env } in
List.iter2 (fun v (_, pty) ->
if not (Type.equal (Vars.ty v) Type.tindex) then
conv_err (L.loc pty) (BadPty [Type.tindex])
) indices typed_args;
let ty = parse_p_ty env pty in
let t, _ = convert ~ty conv_env t in
let data = StateInit_data (indices,t) in
let table, _ =
Symbols.Macro.declare_exact table
s
~data
(Symbols.State (List.length typed_args,ty)) in
table
let get_init_states table : (Term.state * Term.term) list =
Symbols.Macro.fold (fun s def data acc ->
match (def,data) with
| ( Symbols.State (arity,kind), StateInit_data (l,t) ) ->
assert (Type.equal kind (Term.ty t));
let state = Term.mk_isymb s kind l in
(state,t) :: acc
| _ -> acc
) [] table
let find_app_terms t (names : string list) =
let rec aux (name : string) acc t = match L.unloc t with
| App (x',l) ->
let acc = if L.unloc x' = name then L.unloc x'::acc else acc in
aux_list name acc l
| AppAt (x',l,ts) ->
let acc = if L.unloc x' = name then L.unloc x'::acc else acc in
aux_list name acc (ts :: l)
| Exists (_,t')
| ForAll (_,t') -> aux name acc t'
| _ -> acc
and aux_list name acc l =
List.fold_left (aux name) acc l in
let acc = List.fold_left (fun acc name -> aux name acc t) [] names in
List.sort_uniq Stdlib.compare acc
* { 2 Apply arguments }
type p_pt = {
p_pt_head : lsymb;
p_pt_args : p_pt_arg list;
p_pt_loc : L.t;
}
and p_pt_arg =
| PT_term of term
* { 2 Tests }
let () =
let mk x = L.mk_loc L._dummy x in
Checks.add_suite "Theory" [
"Declarations", `Quick,
begin fun () ->
ignore (declare_hash Symbols.builtins_table (mk "h") : Symbols.table);
let table = declare_hash Symbols.builtins_table (mk "h") in
Alcotest.check_raises
"h cannot be defined twice"
(Symbols.SymbError (L._dummy, Multiple_declarations "h"))
(fun () -> ignore (declare_hash table (mk "h") : Symbols.table)) ;
let table = declare_hash Symbols.builtins_table (mk "h") in
Alcotest.check_raises
"h cannot be defined twice"
(Symbols.SymbError (L._dummy, Multiple_declarations "h"))
(fun () -> ignore (declare_aenc table (mk "h") (mk "dec") (mk "pk")
: Symbols.table) )
end;
"Term building", `Quick,
begin fun () ->
let table = declare_hash Symbols.builtins_table (mk "h") in
ignore (make_app L._dummy table NoTS (mk "x") []) ;
Alcotest.check_raises
"hash function expects two arguments"
(Conv (L._dummy, Arity_error ("h",1,2)))
(fun () ->
ignore (make_app L._dummy table NoTS (mk "h") [mk (App (mk "x",[]))])) ;
ignore (make_app
L._dummy table NoTS (mk "h") [mk (App (mk "x",[]));
mk (App (mk "y",[]))])
end ;
"Type checking", `Quick,
begin fun () ->
let table =
declare_aenc Symbols.builtins_table (mk "e") (mk "dec") (mk "pk")
in
let table = declare_hash table (mk "h") in
let x = mk (App (mk "x", [])) in
let y = mk (App (mk "y", [])) in
let vars = Vars.empty_env in
let vars, _ = Vars.make `Approx vars Type.tmessage "x" in
let vars, _ = Vars.make `Approx vars Type.tmessage "y" in
let env = Env.init ~vars ~table () in
let t_i = App (mk "e", [mk (App (mk "h", [x;y]));x;y]) in
let t = mk t_i in
let ty_env = Type.Infer.mk_env () in
check env ty_env [] t Type.tmessage ;
Alcotest.check_raises
"message is not a boolean"
(Conv (L._dummy, Type_error (t_i, Type.tboolean)))
(fun () -> check env ty_env [] t Type.tboolean)
end
]
|
7725a9b31bbd6b500abd420bbc30f1f39430e72377ab3f59546e600170a6ce3e | mzp/scheme-abc | sexpTest.ml | open Base
open Node
open Sexp
open OUnit
let pos x n a b =
{(Node.ghost x) with
Node.filename = "<string>";
lineno = n;
start_pos = a;
end_pos = b}
let of_tokens tokens =
Sexp.of_stream @@ Stream.of_list tokens
let ok sexp tokens =
let sexp' =
of_tokens tokens in
OUnit.assert_equal
sexp
sexp'
let node x =
pos x 1 2 3
let int n =
Int (node n)
let string s =
String (node s)
let bool b =
Bool (node b)
let float f =
Float (node f)
let symbol s =
Symbol (node s)
let list l =
List (node l)
let t_int n =
node (Genlex.Int n)
let t_float n =
node (Genlex.Float n)
let t_str str =
node (Genlex.String str)
let t_char c =
node (Genlex.String c)
let t_ident s =
node (Genlex.Ident s)
let t_kwd s =
node (Genlex.Kwd s)
let _ =
("sexp.ml" >::: [
"pos" >::
(fun () ->
assert_equal
[List (pos [Symbol (pos "a" 5 1 2);
Symbol (pos "b" 5 3 4);
Symbol (pos "c" 5 5 6)] 5 0 7)] @@
of_tokens [
pos (Genlex.Kwd "(") 5 0 1;
pos (Genlex.Ident "a") 5 1 2;
pos (Genlex.Ident "b") 5 3 4;
pos (Genlex.Ident "c") 5 5 6;
pos (Genlex.Kwd ")") 5 6 7;
]);
"empty" >::
(fun () ->
ok [] []);
"int" >::
(fun () ->
ok [int 42] [t_int 42];
ok [int ~-42] [t_int (~-42)]);
"bool" >::
(fun () ->
ok [bool true] [t_kwd "true"];
ok [bool false] [t_kwd "false"]);
"float" >::
(fun () ->
ok [float 42.1] [t_float (42.1)]);
"string" >::
(fun () ->
ok [string ""] [t_str ""];
ok [string "foo"] [t_str "foo"];
ok [string "foo\"x"] [t_str "foo\"x"];
ok [string "foo\""] [t_str "foo\""]);
"symbol" >::
(fun () ->
ok [symbol "."] [t_ident "."]);
"call" >::
(fun () ->
ok [list [symbol "+"; int 1; int 2]]
[t_kwd "(";
t_ident "+"; t_int 1; t_int 2;
t_kwd ")"];
ok [list [symbol "print"; string "hello"]]
[t_kwd "(";
t_ident "print"; t_str "hello";
t_kwd ")"]);
"bracket" >::
(fun () ->
ok [list [symbol "print"; string "hello"]]
[t_kwd "[";
t_ident "print"; t_str "hello";
t_kwd "]"]);
"quote" >::
(fun () ->
ok [list [symbol "quote"; symbol "hello"]]
[t_kwd "(";
t_ident "quote"; t_ident "hello";
t_kwd ")"];
ok [list [symbol "quote"; symbol "hello"]]
[t_kwd "'"; t_ident "hello"])
]) +> run_test_tt_main
| null | https://raw.githubusercontent.com/mzp/scheme-abc/2cb541159bcc32ae4d033793dea6e6828566d503/scm/parser/sexpTest.ml | ocaml | open Base
open Node
open Sexp
open OUnit
let pos x n a b =
{(Node.ghost x) with
Node.filename = "<string>";
lineno = n;
start_pos = a;
end_pos = b}
let of_tokens tokens =
Sexp.of_stream @@ Stream.of_list tokens
let ok sexp tokens =
let sexp' =
of_tokens tokens in
OUnit.assert_equal
sexp
sexp'
let node x =
pos x 1 2 3
let int n =
Int (node n)
let string s =
String (node s)
let bool b =
Bool (node b)
let float f =
Float (node f)
let symbol s =
Symbol (node s)
let list l =
List (node l)
let t_int n =
node (Genlex.Int n)
let t_float n =
node (Genlex.Float n)
let t_str str =
node (Genlex.String str)
let t_char c =
node (Genlex.String c)
let t_ident s =
node (Genlex.Ident s)
let t_kwd s =
node (Genlex.Kwd s)
let _ =
("sexp.ml" >::: [
"pos" >::
(fun () ->
assert_equal
[List (pos [Symbol (pos "a" 5 1 2);
Symbol (pos "b" 5 3 4);
Symbol (pos "c" 5 5 6)] 5 0 7)] @@
of_tokens [
pos (Genlex.Kwd "(") 5 0 1;
pos (Genlex.Ident "a") 5 1 2;
pos (Genlex.Ident "b") 5 3 4;
pos (Genlex.Ident "c") 5 5 6;
pos (Genlex.Kwd ")") 5 6 7;
]);
"empty" >::
(fun () ->
ok [] []);
"int" >::
(fun () ->
ok [int 42] [t_int 42];
ok [int ~-42] [t_int (~-42)]);
"bool" >::
(fun () ->
ok [bool true] [t_kwd "true"];
ok [bool false] [t_kwd "false"]);
"float" >::
(fun () ->
ok [float 42.1] [t_float (42.1)]);
"string" >::
(fun () ->
ok [string ""] [t_str ""];
ok [string "foo"] [t_str "foo"];
ok [string "foo\"x"] [t_str "foo\"x"];
ok [string "foo\""] [t_str "foo\""]);
"symbol" >::
(fun () ->
ok [symbol "."] [t_ident "."]);
"call" >::
(fun () ->
ok [list [symbol "+"; int 1; int 2]]
[t_kwd "(";
t_ident "+"; t_int 1; t_int 2;
t_kwd ")"];
ok [list [symbol "print"; string "hello"]]
[t_kwd "(";
t_ident "print"; t_str "hello";
t_kwd ")"]);
"bracket" >::
(fun () ->
ok [list [symbol "print"; string "hello"]]
[t_kwd "[";
t_ident "print"; t_str "hello";
t_kwd "]"]);
"quote" >::
(fun () ->
ok [list [symbol "quote"; symbol "hello"]]
[t_kwd "(";
t_ident "quote"; t_ident "hello";
t_kwd ")"];
ok [list [symbol "quote"; symbol "hello"]]
[t_kwd "'"; t_ident "hello"])
]) +> run_test_tt_main
| |
c5a7a35aedc45019b5a4815aa77713dfe43b847eb25253f247d941b8c7c71e39 | MaximGB/TetrisRF | next_panel.cljs | (ns tetrisrf.views.next-panel
(:require [re-frame.core :as rf]
[tetrisrf.views.game-field :refer [game-field]]))
(defn next-panel [next-field-sub]
[:div.next-field.fluid.ui.labeled.big.input
[:div.ui.label.big "Next"]
[:div.field-frame
[game-field next-field-sub]]])
| null | https://raw.githubusercontent.com/MaximGB/TetrisRF/19a91c145a27e8819efebcc9f4e86bbfc15c8d7f/src/tetrisrf/views/next_panel.cljs | clojure | (ns tetrisrf.views.next-panel
(:require [re-frame.core :as rf]
[tetrisrf.views.game-field :refer [game-field]]))
(defn next-panel [next-field-sub]
[:div.next-field.fluid.ui.labeled.big.input
[:div.ui.label.big "Next"]
[:div.field-frame
[game-field next-field-sub]]])
| |
548e317f525f076c954bc44ca364d2dc015e5920f5da0a744a09c0526590a9e9 | txyyss/Project-Euler | Euler053.hs | There are exactly ten ways of selecting three from five , 12345 :
123 , 124 , 125 , 134 , 135 , 145 , 234 , 235 , 245 , and 345
In combinatorics , we use the notation , 5C3 = 10 .
-- In general,
nCr = n ! / r!(nr ) !
where r < = n , n ! = n(n1) ... 321 , and 0 ! = 1 . It is not until n =
23 , that a value exceeds one - million : 23C10 = 1144066 .
How many , not necessarily distinct , values of nCr , for 1 < = n < =
100 , are greater than one - million ?
module Euler053 where
binomial :: Integral a => a -> a -> a
binomial n r = product [(n-r+1)..n] `div` product [2..r]
exceed :: Integral a => a -> Int
exceed n = length . filter (>1000000) $ map (binomial n) [0..n]
result053 = sum $ map exceed [1..100]
| null | https://raw.githubusercontent.com/txyyss/Project-Euler/d2f41dad429013868445c1c9c1c270b951550ee9/Euler053.hs | haskell | In general, | There are exactly ten ways of selecting three from five , 12345 :
123 , 124 , 125 , 134 , 135 , 145 , 234 , 235 , 245 , and 345
In combinatorics , we use the notation , 5C3 = 10 .
nCr = n ! / r!(nr ) !
where r < = n , n ! = n(n1) ... 321 , and 0 ! = 1 . It is not until n =
23 , that a value exceeds one - million : 23C10 = 1144066 .
How many , not necessarily distinct , values of nCr , for 1 < = n < =
100 , are greater than one - million ?
module Euler053 where
binomial :: Integral a => a -> a -> a
binomial n r = product [(n-r+1)..n] `div` product [2..r]
exceed :: Integral a => a -> Int
exceed n = length . filter (>1000000) $ map (binomial n) [0..n]
result053 = sum $ map exceed [1..100]
|
9bdedc3b56f9419adf9dcbafd662f15b61b8ada5b5efff635de5a9370540ac43 | bennn/dissertation | quad-types.rkt | #lang typed/racket/base
(provide
BoxQuad
RunQuad
SpacerQuad
DocQuad
Optical-KernQuad
PieceQuad
WordQuad
Word-BreakQuad
PageQuad
Page-BreakQuad
ColumnQuad
Column-BreakQuad
LineQuad
BlockQuad
Block-BreakQuad
;; --
page-break?
column-break?
block-break?
word-break?
column?
line?
run?
word?
optical-kern?
spacer?
nonnegative-flonum?
)
;; -----------------------------------------------------------------------------
(require "core-types.rkt")
;; =============================================================================
(define-type BoxQuad (List* 'box QuadAttrs QuadList))
(define-type RunQuad (List* 'run QuadAttrs QuadList))
(define-type SpacerQuad (List* 'spacer QuadAttrs QuadList))
(define-type DocQuad (List* 'doc QuadAttrs QuadList))
(define-type Optical-KernQuad (List* 'optical-kern QuadAttrs QuadList))
(define-type PieceQuad (List* 'piece QuadAttrs GroupQuadList))
(define-type WordQuad (List* 'word QuadAttrs QuadList))
(define-type Word-BreakQuad (List* 'word-break QuadAttrs QuadList))
(define-type PageQuad (List* 'page QuadAttrs GroupQuadList))
(define-type Page-BreakQuad (List* 'page-break QuadAttrs QuadList))
(define-type ColumnQuad (List* 'column QuadAttrs GroupQuadList))
(define-type Column-BreakQuad (List* 'column-break QuadAttrs QuadList))
(define-type LineQuad (List* 'line QuadAttrs GroupQuadList))
(define-type BlockQuad (List* 'block QuadAttrs QuadList))
(define-type Block-BreakQuad (List* 'block-break QuadAttrs QuadList))
(define-syntax-rule (make-QL-pred QL? sym)
(lambda (x)
(and (pair? x)
(let ((a (car x))
(b (cdr x)))
(and (symbol? a)
(eq? a sym)
(pair? b)
(let ((aa (car b))
(bb (cdr b)))
(and (QuadAttrs? aa)
(QL? bb))))))))
(define-syntax-rule (make-quad-list-pred sym)
(make-QL-pred QuadList? sym))
(define-syntax-rule (make-group-list-pred sym)
(make-QL-pred GroupQuadList? sym))
(: page-break? (-> Any Boolean : Page-BreakQuad))
(define page-break? (make-quad-list-pred 'page-break))
(: column-break? (-> Any Boolean : Column-BreakQuad))
(define column-break? (make-quad-list-pred 'column-break))
(: block-break? (-> Any Boolean : Block-BreakQuad))
(define block-break? (make-quad-list-pred 'block-break))
(: word-break? (-> Any Boolean : Word-BreakQuad))
(define word-break? (make-quad-list-pred 'word-break))
(: column? (-> Any Boolean : ColumnQuad))
(define column? (make-group-list-pred 'column))
(: line? (-> Any Boolean : LineQuad))
(define line? (make-group-list-pred 'line))
(: word? (-> Any Boolean : WordQuad))
(define word? (make-quad-list-pred 'word))
(: run? (-> Any Boolean : RunQuad))
(define run? (make-quad-list-pred 'run))
(: spacer? (-> Any Boolean : SpacerQuad))
(define spacer? (make-quad-list-pred 'spacer))
(: optical-kern? (-> Any Boolean : Optical-KernQuad))
(define optical-kern? (make-quad-list-pred 'optical-kern))
(: nonnegative-flonum? (-> Any Boolean : #:+ Nonnegative-Flonum))
(define (nonnegative-flonum? x)
(and (flonum? x) (<= 0 x)))
| null | https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/dissertation/scrbl/jfp-2019/benchmarks/quadT/base/quad-types.rkt | racket | --
-----------------------------------------------------------------------------
============================================================================= | #lang typed/racket/base
(provide
BoxQuad
RunQuad
SpacerQuad
DocQuad
Optical-KernQuad
PieceQuad
WordQuad
Word-BreakQuad
PageQuad
Page-BreakQuad
ColumnQuad
Column-BreakQuad
LineQuad
BlockQuad
Block-BreakQuad
page-break?
column-break?
block-break?
word-break?
column?
line?
run?
word?
optical-kern?
spacer?
nonnegative-flonum?
)
(require "core-types.rkt")
(define-type BoxQuad (List* 'box QuadAttrs QuadList))
(define-type RunQuad (List* 'run QuadAttrs QuadList))
(define-type SpacerQuad (List* 'spacer QuadAttrs QuadList))
(define-type DocQuad (List* 'doc QuadAttrs QuadList))
(define-type Optical-KernQuad (List* 'optical-kern QuadAttrs QuadList))
(define-type PieceQuad (List* 'piece QuadAttrs GroupQuadList))
(define-type WordQuad (List* 'word QuadAttrs QuadList))
(define-type Word-BreakQuad (List* 'word-break QuadAttrs QuadList))
(define-type PageQuad (List* 'page QuadAttrs GroupQuadList))
(define-type Page-BreakQuad (List* 'page-break QuadAttrs QuadList))
(define-type ColumnQuad (List* 'column QuadAttrs GroupQuadList))
(define-type Column-BreakQuad (List* 'column-break QuadAttrs QuadList))
(define-type LineQuad (List* 'line QuadAttrs GroupQuadList))
(define-type BlockQuad (List* 'block QuadAttrs QuadList))
(define-type Block-BreakQuad (List* 'block-break QuadAttrs QuadList))
(define-syntax-rule (make-QL-pred QL? sym)
(lambda (x)
(and (pair? x)
(let ((a (car x))
(b (cdr x)))
(and (symbol? a)
(eq? a sym)
(pair? b)
(let ((aa (car b))
(bb (cdr b)))
(and (QuadAttrs? aa)
(QL? bb))))))))
(define-syntax-rule (make-quad-list-pred sym)
(make-QL-pred QuadList? sym))
(define-syntax-rule (make-group-list-pred sym)
(make-QL-pred GroupQuadList? sym))
(: page-break? (-> Any Boolean : Page-BreakQuad))
(define page-break? (make-quad-list-pred 'page-break))
(: column-break? (-> Any Boolean : Column-BreakQuad))
(define column-break? (make-quad-list-pred 'column-break))
(: block-break? (-> Any Boolean : Block-BreakQuad))
(define block-break? (make-quad-list-pred 'block-break))
(: word-break? (-> Any Boolean : Word-BreakQuad))
(define word-break? (make-quad-list-pred 'word-break))
(: column? (-> Any Boolean : ColumnQuad))
(define column? (make-group-list-pred 'column))
(: line? (-> Any Boolean : LineQuad))
(define line? (make-group-list-pred 'line))
(: word? (-> Any Boolean : WordQuad))
(define word? (make-quad-list-pred 'word))
(: run? (-> Any Boolean : RunQuad))
(define run? (make-quad-list-pred 'run))
(: spacer? (-> Any Boolean : SpacerQuad))
(define spacer? (make-quad-list-pred 'spacer))
(: optical-kern? (-> Any Boolean : Optical-KernQuad))
(define optical-kern? (make-quad-list-pred 'optical-kern))
(: nonnegative-flonum? (-> Any Boolean : #:+ Nonnegative-Flonum))
(define (nonnegative-flonum? x)
(and (flonum? x) (<= 0 x)))
|
15b269539836b85d86129e0544a141864406f40d2748d131a5b08f695cce7f20 | Storkle/clj-forex | map.clj | (clojure.core/use 'nstools.ns)
(ns+ forex.module.indicator.map
(:clone clj.core)
(:use forex.module.indicator.util)
(:use forex.util.emacs
[clj-time.core :exclude [extend start]]
[clj-time.coerce]
forex.util.spawn
forex.util.core
forex.util.log
forex.util.general
forex.module.account.utils
forex.module.error)
(:require clojure.contrib.core
[forex.backend.mql.socket-service :as backend])
(:require [forex.module.error :as s]))
(defn- itime
([] (itime 0))
([j & e]
{:pre [(integer? j)]}
(let [{:keys [symbol period i]} (env-dispatch e true)]
(receive-indicator (format "iTime %s %s %s" symbol period
(+ j (or i 0)))
3))))
(def *max* 1000)
(def *now* (now-seconds))
(defonce *indicators* (atom {}))
(defn clear []
(var-root-set #'*indicators* (atom {})))
(defn update-time []
(awhen (receive (format "TimeCurrent"))
(var-root-set #'*now* it))
*now*)
(defn indicator-protocol
"retrieve protocol string needed for indicator"
[{:keys [name param mode symbol
period from max to min]
:or {max *max*
mode 0
from *now* to 0 min 1
symbol (env :symbol)
period (env :period)}}]
{:pre [(string? name)
(env? {:symbol symbol :period period})
(>=? max 0)
(>=? mode 0)
(>=? from 0)
(>=? to 0)
(>=? max min)]}
(format "%s %s %s %s %s %s %s %s %s"
name symbol period mode from to min max
(apply str (interpose " " (mklst param)))))
(defn indicator-vector
"retrieve indicator vector from socket service"
[{:keys [max] :or {max *max*} :as this}
&
[{:keys [retries] :or {retries 3}}
proto]]
{:pre [(or (nil? proto) (string? proto))]}
(if (= max 0)
[]
(receive-indicator (or proto (indicator-protocol this)) retries)))
;;TODO: handle situation where multiple pids get it?? - not too important, actually
(defn add-pid [this return]
(swap! *indicators*
merge {(:id this)
(merge this {:pid (conj (:pid this)
(self))})})
return)
(defn indicator-vector-memoize
"retrieve indicator vector from storage or from socket service if does not exist.
Add current pid to indicator also. Returns indicator vector"
([args] (indicator-vector-memoize args @*env*))
([{:keys [name param mode from] :or {from *now* mode 0 param nil}} e]
(let [{:keys [symbol period] :as e} e
id [symbol period name param mode]
val (get @*indicators* id)]
(aif val
(add-pid it (subv (:vec it) (or (:i e) 0) []))
(let [indicator
{:name name :id id :pid #{(self)}
:param param :mode mode :symbol symbol
:period period :from from
:max *max* :to 0}
ret (indicator-vector indicator)]
(aif ret
(do
(swap! *indicators* assoc id
(merge indicator {:vec ret}))
ret)
(throwf it)))))))
(defn indicator-vector1-memoize [index & args]
(nth (apply indicator-vector-memoize args) index 0))
| null | https://raw.githubusercontent.com/Storkle/clj-forex/1800b982037b821732b9df1e2e5ea1eda70f941f/src/forex/module/indicator/map.clj | clojure | TODO: handle situation where multiple pids get it?? - not too important, actually | (clojure.core/use 'nstools.ns)
(ns+ forex.module.indicator.map
(:clone clj.core)
(:use forex.module.indicator.util)
(:use forex.util.emacs
[clj-time.core :exclude [extend start]]
[clj-time.coerce]
forex.util.spawn
forex.util.core
forex.util.log
forex.util.general
forex.module.account.utils
forex.module.error)
(:require clojure.contrib.core
[forex.backend.mql.socket-service :as backend])
(:require [forex.module.error :as s]))
(defn- itime
([] (itime 0))
([j & e]
{:pre [(integer? j)]}
(let [{:keys [symbol period i]} (env-dispatch e true)]
(receive-indicator (format "iTime %s %s %s" symbol period
(+ j (or i 0)))
3))))
(def *max* 1000)
(def *now* (now-seconds))
(defonce *indicators* (atom {}))
(defn clear []
(var-root-set #'*indicators* (atom {})))
(defn update-time []
(awhen (receive (format "TimeCurrent"))
(var-root-set #'*now* it))
*now*)
(defn indicator-protocol
"retrieve protocol string needed for indicator"
[{:keys [name param mode symbol
period from max to min]
:or {max *max*
mode 0
from *now* to 0 min 1
symbol (env :symbol)
period (env :period)}}]
{:pre [(string? name)
(env? {:symbol symbol :period period})
(>=? max 0)
(>=? mode 0)
(>=? from 0)
(>=? to 0)
(>=? max min)]}
(format "%s %s %s %s %s %s %s %s %s"
name symbol period mode from to min max
(apply str (interpose " " (mklst param)))))
(defn indicator-vector
"retrieve indicator vector from socket service"
[{:keys [max] :or {max *max*} :as this}
&
[{:keys [retries] :or {retries 3}}
proto]]
{:pre [(or (nil? proto) (string? proto))]}
(if (= max 0)
[]
(receive-indicator (or proto (indicator-protocol this)) retries)))
(defn add-pid [this return]
(swap! *indicators*
merge {(:id this)
(merge this {:pid (conj (:pid this)
(self))})})
return)
(defn indicator-vector-memoize
"retrieve indicator vector from storage or from socket service if does not exist.
Add current pid to indicator also. Returns indicator vector"
([args] (indicator-vector-memoize args @*env*))
([{:keys [name param mode from] :or {from *now* mode 0 param nil}} e]
(let [{:keys [symbol period] :as e} e
id [symbol period name param mode]
val (get @*indicators* id)]
(aif val
(add-pid it (subv (:vec it) (or (:i e) 0) []))
(let [indicator
{:name name :id id :pid #{(self)}
:param param :mode mode :symbol symbol
:period period :from from
:max *max* :to 0}
ret (indicator-vector indicator)]
(aif ret
(do
(swap! *indicators* assoc id
(merge indicator {:vec ret}))
ret)
(throwf it)))))))
(defn indicator-vector1-memoize [index & args]
(nth (apply indicator-vector-memoize args) index 0))
|
841d042cdd94ac9a28f83cdaf462d96d38a9abad2a98f6722185c0286d0a15bc | Airtnp/Notes | subtying.hs | -- ref: /~bcpierce/tapl/checkers/fullfsub/syntax.ml
-- TODO: the error handling is shit. Try replace everything by Either Type/Term Error
-- TODO: add Kind system
Fullformsub is the ultra in TAPL : /~bcpierce/tapl/checkers/fullfomsub/
import Data.Maybe
import Data.List
import Control.Exception
import System.IO.Unsafe
data Kind =
KnStar
| KnArr Kind Kind
data Type =
TyVar Int Int
| TyId String
| TyTop
| TyBot
| TyArr Type Type
| TyRecord [(String, Type)]
| TyVariant [(String, Type)]
| TyRef Type -- invariant subtyping
| TyString
| TyUnit
| TyFloat
| TyNat
| TyBool
forall X < : T. ( better TyAll String Kind Type )
exist X < : T. ( better )
| TySource Type -- covariant subtyping
| TySink Type
deriving(Eq, Show)
TyAbs String Kind Type
TyApp Type Type -- Type operations
data Term =
TmVar Int Int -- Γ⊢a
| TmAbs String Type Term -- Γ⊢x:T.t1 (T->)
| TmApp Term Term -- Γ⊢M N
| TmTrue
| TmFalse
| TmString String
| TmUnit
| TmFloat Float
| TmIf Term Term Term
| TmRecord [(String, Term)]
| TmProj Term String -- record <-> proj
| TmCase Term [(String, (String, Term))]
| TmTag String Term Type
let x = t1 in t2 = = = ( \x : T1 t2 ) t1 = = = [ x - > t1]t2
fix \x : T1 t2 = = = [ x - > fix \x : T1 t2]t2
| TmAscribe Term Type -- as
| TmTimesFloat Term Term
| TmTAbs String Type Term -- type application t[T]
| TmTApp Term Type -- type abstraction (\lambda X.t) # X:type
| TmZero
| TmSucc Term
| TmPred Term
| TmIsZero Term
| TmInert Type
| TmPack Type Term Type -- {*T, t} as T
| TmUnpack String String Term Term -- let {X, x} = t1 in t2
| TmRef Term
| TmDeref Term
| TmAssign Term Term
| TmError
| TmTry Term Term
| TmLoc Int
deriving(Eq, Show)
TmUpdate Term String Term
data Binding =
NameBinding
| TyVarBinding Type -- \Gamma, x : T
| VarBinding Type
| TyAbbBinding Type -- Or TyAbbBinding Type (Maybe Kind) \Gamma, X
| TmAbbBinding Term (Maybe Type)
deriving(Eq, Show)
type Context = [(String, Binding)]
data Command =
Eval Term
| Bind String Binding
| SomeBind String String Term
-- Context
addBinding :: Context -> String -> Binding -> Context
addBinding ctx x bind = (x, bind) : ctx
addName :: Context -> String -> Context
addName ctx x = addBinding ctx x NameBinding
isNameBound :: Context -> String -> Bool
isNameBound ctx x = case ctx of
[] -> False
y:ys -> if x == (fst y) then True else isNameBound ys x
pkFreshVarName :: Context -> String -> (String, Context)
pkFreshVarName ctx x =
let x' = mkFreshVarName ctx x in
(x', addBinding ctx x' NameBinding)
mkFreshVarName :: Context -> String -> String
mkFreshVarName [] x = x
mkFreshVarName ctx@(c:cs) x
| x == (fst c) = mkFreshVarName ctx (x ++ "'")
| otherwise = mkFreshVarName cs x
indexToName :: Context -> Int -> String
indexToName ctx i
| length ctx > i = fst $ ctx !! i
| otherwise = undefined
nameToIndex :: Context -> String -> Int
nameToIndex ctx x = case ctx of
[] -> undefined
y:ys -> if x == (fst y) then 0 else (+) 1 $ nameToIndex ctx x
-- Shifting
instance where
tyMap onvar c tyT = walk c tyT where
walk c tyT = case tyT of
TyVar x n -> onvar c x n
TyId b -> TyId b
TyArr tyT1 tyT2 -> TyArr (walk c tyT1) (walk c tyT2)
TyTop -> TyTop
TyBot -> TyBot
TyBool -> TyBool
TyRecord fs -> TyRecord $ map (\lty -> (fst lty, walk c $ snd lty)) fs
TyVariant fs -> TyVariant $ map (\lty -> (fst lty, walk c $ snd lty)) fs
TyString -> TyString
TyUnit -> TyUnit
TyFloat -> TyFloat
TyAll tyX tyT1 tyT2 -> TyAll tyX (walk c tyT1) (walk c tyT2)
TyNat -> TyNat
TySome tyX tyT1 tyT2 -> TySome tyX (walk c tyT1) (walk c tyT2)
TyRef tyT1 -> TyRef (walk c tyT1)
TySource tyT1 -> TySource (walk c tyT1)
TySink tyT1 -> TySink (walk c tyT1)
tmMap onvar ontype c t = walk c t where
walk c t = case t of
TmInert tyT -> TmInert $ ontype c tyT
TmVar x n -> onvar c x n
TmAbs x tyT1 t2 -> TmAbs x (ontype c tyT1) (walk (c+1) t2)
TmApp t1 t2 -> TmApp (walk c t1) (walk c t2)
TmTrue -> TmTrue
TmFalse -> TmFalse
TmIf t1 t2 t3 -> TmIf (walk c t1) (walk c t2) (walk c t3)
TmProj t1 l -> TmProj (walk c t1) l
TmRecord fs -> TmRecord $ map (\lt -> (fst lt, walk c $ snd lt)) fs
TmLet x t1 t2 -> TmLet x (walk c t1) (walk (c+1) t2)
TmFix t1 -> TmFix (walk c t1)
TmString x -> TmString x
TmUnit -> TmUnit
TmAscribe t1 tyT1 -> TmAscribe (walk c t1) (ontype c tyT1)
TmFloat x -> TmFloat x
TmTimesFloat t1 t2 -> TmTimesFloat (walk c t1) (walk c t2)
TmTAbs tyX tyT1 t2 -> TmTAbs tyX (ontype c tyT1) (walk (c+1) t2)
TmTApp t1 tyT2 -> TmTApp (walk c t1) (ontype c tyT2)
TmZero -> TmZero
TmSucc t1 -> TmSucc (walk c t1)
TmPred t1 -> TmPred (walk c t1)
TmIsZero t1 -> TmIsZero (walk c t1)
TmPack tyT1 t2 tyT3 -> TmPack (ontype c tyT1) (walk c t2) (ontype c tyT3)
TmUnpack tyX x t1 t2 -> TmUnpack tyX x (walk c t1) (walk (c+2) t2)
TmTag l t1 tyT -> TmTag l (walk c t1) (ontype c tyT)
TmCase t cases -> TmCase (walk c t) (map (\(li, (xi, ti)) -> (li, (xi, walk (c+1) ti))) cases)
TmLoc l -> TmLoc l
TmRef t1 -> TmRef (walk c t1)
TmDeref t1 -> TmDeref (walk c t1)
TmAssign t1 t2 -> TmAssign (walk c t1) (walk c t2)
TmError -> TmError
TmTry t1 t2 -> TmTry (walk c t1) (walk c t2)
typeShiftAbove d c tyT =
tyMap
(\c x n -> if x >= c then TyVar (x+d) (n+d) else TyVar x (n+d))
c tyT
[ ↑d , c]t
termShiftAbove d c t =
tmMap
(\c' x n -> if x >= c' then TmVar (x+d) (n+d) else TmVar x (n+d))
(typeShiftAbove d)
c t
typeShift d tyT = typeShiftAbove d 0 tyT
termShift d t = termShiftAbove d 0 t
bindingShift d bind = case bind of
NameBinding -> NameBinding
TyVarBinding tyS -> TyVarBinding (typeShift d tyS)
VarBinding tyT -> VarBinding (typeShift d tyT)
TyAbbBinding tyT -> TyAbbBinding (typeShift d tyT)
TmAbbBinding t tyT_opt ->
let tyT_opt' = case tyT_opt of
Nothing -> Nothing
Just tyT -> Just (typeShift d tyT)
in TmAbbBinding (termShift d t) tyT_opt'
-- Substitution
-- [j -> s]t
termSubst j s t =
tmMap
(\j x n -> if x == j then termShift j s else TmVar x n)
(\j tyT -> tyT)
j t
typeSubst tyS j tyT =
tyMap
(\j x n -> if x == j then typeShift j tyS else TyVar x n)
j tyT
termSubstTop s t =
termShift (-1) (termSubst 0 (termShift 1 s) t)
typeSubstTop tyS tyT =
typeShift (-1) (typeSubst (typeShift 1 tyS) 0 tyT)
tyTermSubst tyS j t =
tmMap
(\c x n -> TmVar x n)
(\j tyT -> typeSubst tyS j tyT)
j t
tyTermSubstTop tyS t =
termShift (-1) (tyTermSubst (typeShift 1 tyS) 0 t)
-- Context
getBinding ctx i
| length ctx > i = let bind = snd $ ctx !! i
in bindingShift (i + 1) bind
| otherwise = undefined
getTypeFromContext ctx i =
case getBinding ctx i of
VarBinding tyT -> tyT
TmAbbBinding _ (Just tyT) -> tyT
TmAbbBinding _ Nothing -> undefined
_ -> undefined
-- Print
small t = case t of
TmVar _ _ -> True
_ -> False
-- TODO: printType / printTerm
-- Evaluation
isNumericVal ctx t = case t of
TmZero -> True
TmSucc t1 -> isNumericVal ctx t1
_ -> False
isVal ctx t = case t of
TmTrue -> True
TmFalse -> True
TmString _ -> True
TmUnit -> True
TmFloat _ -> True
TmLoc _ -> True
t | isNumericVal ctx t -> True
TmAbs _ _ _ -> True
TmRecord fs -> all (\(l,ti) -> isVal ctx ti) fs
TmPack _ v1 _ -> isVal ctx v1
TmTAbs _ _ _ -> True
_ -> False
type Store = [Term]
extendStore store v = (length store, store ++ [v])
lookupLoc store l = store !! l
updateStore store n v = f (n, store) where
f s = case s of
(0, v':rest) -> v:rest
(n, v':rest) -> v':f(n-1, rest)
_ -> error "updateStore: bad index"
shiftStore i store = map (\t -> termShift i t) store
eval1 ctx store t = case t of
TmIf TmTrue t2 t3 -> (t2, store)
TmIf TmFalse t2 t3 -> (t3, store)
TmIf t1 t2 t3 -> let (t1', store') = eval1 ctx store t1 in
(TmIf t1' t2 t3, store')
TmRecord fs ->
let evalField l = case l of
[] -> (error "No Rule Applies")
(l, vi):rest
| isVal ctx vi -> let (rest', store') = evalField rest in
((l, vi):rest', store')
| otherwise -> let (ti', store') = eval1 ctx store vi in
((l, ti'):rest, store')
in let (fs', store') = evalField fs in
(TmRecord fs', store')
TmProj (TmRecord fs) l
| isVal ctx (TmRecord fs) -> let rd = filter (\(li, ti) -> li == l) fs in
if rd == [] then (error "No Rule Applies") else (snd $ rd !! 0, store)
TmProj t1 l -> let (t1', store') = eval1 ctx store t1 in
(TmProj t1' l, store')
TmLet x v1 t2
| isVal ctx v1 -> (termSubstTop v1 t2, store)
| otherwise -> let (t1', store') = eval1 ctx store v1 in
(TmLet x t1' t2, store')
TmFix v1
| isVal ctx v1 -> case v1 of
TmAbs _ _ t12 -> (termSubstTop (TmFix v1) t12, store)
_ -> (error "No Rule Applies")
| otherwise -> let (t1', store') = eval1 ctx store v1 in
(TmFix t1', store')
TmTag l t1 tyT -> let (t1', store') = eval1 ctx store t1 in
(TmTag l t1' tyT, store')
TmCase (TmTag li v11 tyT) branches
| isVal ctx v11 -> let rd = filter (\(li', (xi, ti)) -> li == li') branches in
if rd == [] then (error "No Rule Applies") else (termSubstTop v11 $ snd $ snd (rd !! 0), store)
TmCase t1 branches -> let (t1', store') = eval1 ctx store t1 in
(TmCase t1' branches, store')
TmAscribe v1 tyT
| isVal ctx v1 -> (v1, store)
| otherwise -> let (t1', store') = eval1 ctx store v1 in
(TmAscribe t1' tyT, store')
TmVar n _ -> case getBinding ctx n of
TmAbbBinding t _ -> (t, store)
_ -> (error "No Rule Applies")
TmRef t1
| isVal ctx t1 -> let (l, store') = extendStore store t1 in
(TmLoc l, store')
| otherwise -> let (t1', store') = eval1 ctx store t1 in
(TmRef t1', store')
TmDeref t1
| isVal ctx t1 -> case t1 of
TmLoc l -> (lookupLoc store l, store)
_ -> (error "No Rule Applies")
| otherwise -> let (t1', store') = eval1 ctx store t1 in
(TmDeref t1', store')
TmAssign t1 t2
| (isVal ctx t1) && (isVal ctx t2) -> case t1 of
TmLoc l -> (TmUnit, updateStore store l t2)
_ -> (error "No Rule Applies")
| not (isVal ctx t1) -> let (t1', store') = eval1 ctx store t1 in
(TmAssign t1' t2, store')
| not (isVal ctx t2) -> let (t2', store') = eval1 ctx store t2 in
(TmAssign t1 t2', store')
TmError -> (error "Error Encountered")
TmTimesFloat (TmFloat f1) (TmFloat f2) -> (TmFloat (f1*f2), store)
TmTimesFloat (TmFloat f1) t2 -> let (t2', store') = eval1 ctx store t2 in
(TmTimesFloat (TmFloat f1) t2', store')
TmTimesFloat t1 t2 -> let (t1', store') = eval1 ctx store t1 in
(TmTimesFloat t1' t2, store')
TmSucc t1 -> let (t1', store') = eval1 ctx store t1 in
(TmSucc t1', store')
TmPred t1 -> let (t1', store') = eval1 ctx store t1 in
(TmPred t1', store')
TmIsZero TmZero -> (TmTrue, store)
TmIsZero (TmSucc nv1)
| isNumericVal ctx nv1 -> (TmFalse, store)
TmIsZero t1 -> let (t1', store') = eval1 ctx store t1 in
(TmIsZero t1', store')
TmTApp (TmTAbs x _ t11) tyT2 -> (tyTermSubstTop tyT2 t11, store)
TmTApp t1 tyT2 -> let (t1', store') = eval1 ctx store t1 in
(TmTApp t1' tyT2, store')
TmApp (TmAbs x tyT11 t12) v2
| isVal ctx v2 -> (termSubstTop v2 t12, store)
TmApp v1 t2
| isVal ctx v1 -> let (t2', store') = eval1 ctx store t2 in
(TmApp v1 t2', store')
TmApp t1 t2 -> let (t1', store') = eval1 ctx store t2 in
(TmApp t1' t2, store')
TmPack tyT1 t2 tyT3 -> let (t2', store') = eval1 ctx store t2 in
(TmPack tyT1 t2' tyT3, store')
TmUnpack _ _ (TmPack tyT11 v12 _) t2
| isVal ctx v12 -> (tyTermSubstTop tyT11 (termSubstTop (termShift 1 v12) t2), store)
TmUnpack tyX x t1 t2 -> let (t1', store') = eval1 ctx store t1 in
(TmUnpack tyX x t1' t2, store')
-- By process and perservation theorem
evalPre ctx store t = unsafePerformIO $ catch
(evaluate $ eval1 ctx store t)
returnTs
where
returnTs :: SomeException -> IO (Term, Store)
returnTs err = return (t, store)
eval ctx store t = let (t', store') = evalPre ctx store t in
if (t', store') == (t, store)
then (t, store)
else evalPre ctx store' t'
evalBinding ctx store b = case b of
TmAbbBinding t tyT -> let (t', store') = eval ctx store t in
(TmAbbBinding t' tyT, store')
bind -> (bind, store)
\Gamma |- S ⇑ T ( )
TyVar i _ -> case getBinding ctx i of
TyVarBinding tyT -> tyT
_ -> (error "No Rule Applies")
_ -> (error "No Rule Applies")
isTyAbb ctx i = case getBinding ctx i of
TyAbbBinding tyT -> True
_ -> False
getTyAbb ctx i = case getBinding ctx i of
TyAbbBinding tyT -> tyT
_ -> (error "No Rule Applies")
computeTy ctx tyT = case tyT of
TyVar i _ | isTyAbb ctx i -> getTyAbb ctx i
_ -> (error "No Rule Applies")
-- That's all bad
simplifyTy1 :: Context -> Type -> Type
simplifyTy1 ctx tyT = unsafePerformIO $ catch
(evaluate (computeTy ctx tyT))
returnTy
where
returnTy :: SomeException -> IO Type
returnTy err = return tyT
simplifyTy ctx tyT = let tyT' = simplifyTy1 ctx tyT in
if tyT' == tyT then tyT else simplifyTy1 ctx tyT'
tyEqv ctx tyS tyT =
let tyS' = simplifyTy ctx tyS
tyT' = simplifyTy ctx tyT
in case (tyS', tyT') of
(TyTop, TyTop) -> True
(TyBot, TyBot) -> True
(TyArr tyS1 tyS2, TyArr tyT1 tyT2) ->
(tyEqv ctx tyS1 tyT1) && (tyEqv ctx tyS2 tyT2)
(TyString, TyString) -> True
(TyId b1, TyId b2) -> b1 == b2
(TyFloat, TyFloat) -> True
(TyUnit, TyUnit) -> True
(TyRef tyT1, TyRef tyT2) -> tyEqv ctx tyT1 tyT2
(TySource tyT1, TySource tyT2) -> tyEqv ctx tyT1 tyT2
(TySink tyT1, TySink tyT2) -> tyEqv ctx tyT1 tyT2
(TyVar i _, _) | isTyAbb ctx i -> tyEqv ctx (getTyAbb ctx i) tyT'
(_, TyVar i _) | isTyAbb ctx i -> tyEqv ctx tyS' (getTyAbb ctx i)
(TyBool, TyBool) -> True
(TyNat, TyNat) -> True
(TyRecord fs1, TyRecord fs2) -> (length fs1 == length fs2) &&
all id (map
(\(li2, tyTi2) -> let rd = filter (\(li1, tyTi1) -> li2 == li1) fs1
in if length rd == 0 then False else tyEqv ctx (snd $ rd !! 0) tyTi2
)
fs2)
(TyAll tyX1 tyS1 tyS2, TyAll _ tyT1 tyT2) -> let ctx' = addName ctx tyX1 in
(tyEqv ctx tyS1 tyT1) && (tyEqv ctx' tyS2 tyT2)
(TyVariant fs1, TyVariant fs2) -> (length fs1 == length fs2) &&
all id (map
(\(li2, tyTi2) -> let rd = filter (\(li1, tyTi1) -> li2 == li1) fs1
in if length rd == 0 then False else tyEqv ctx (snd $ rd !! 0) tyTi2
)
fs2)
_ -> False
subtype ctx tyS tyT = tyEqv ctx tyS tyT ||
let tyS' = simplifyTy ctx tyS
tyT' = simplifyTy ctx tyT
in case (tyS', tyT') of
-- T <: Top
(_, TyTop) -> True
-- Bot <: T
(TyBot, _) -> True
-- (->) a as contravariant operatior
(TyArr tyS1 tyS2, TyArr tyT1 tyT2) ->
(subtype ctx tyT1 tyS1) && (subtype ctx tyS2 tyT2)
-- {l:r} <: {l':r'}
(TyRecord fS, TyRecord fT) ->
all id (map
(\(li, tyTi) -> let rd = filter (\(li1, tyTi1) -> li == li1) fS
in if length rd == 0 then False else subtype ctx (snd $ rd !! 0) tyTi)
fT
)
(TyVariant fS, TyVariant fT) ->
all id (map
(\(li, tyTi) -> let rd = filter (\(li1, tyTi1) -> li == li1) fS
in if length rd == 0 then False else subtype ctx (snd $ rd !! 0) tyTi)
fT
)
(TyVar _ _, _) -> subtype ctx (promote ctx tyS') tyT'
(TyAll tyX1 tyS1 tyS2, TyAll _ tyT1 tyT2) ->
(subtype ctx tyS1 tyT1 && subtype ctx tyT1 tyS1) &&
let ctx' = addBinding ctx tyX1 (TyVarBinding tyT1) in
subtype ctx' tyS2 tyT2
(TyRef tyT1, TyRef tyT2) -> (subtype ctx tyT1 tyT2) && (subtype ctx tyT2 tyT1)
(TyRef tyT1, TySource tyT2) -> subtype ctx tyT1 tyT2
(TySource tyT1, TySource tyT2) -> subtype ctx tyT1 tyT2
(TyRef tyT1, TySink tyT2) -> subtype ctx tyT2 tyT1
(TySink tyT1, TySink tyT2) -> subtype ctx tyT2 tyT1
_ -> False
join ctx tyS tyT =
if subtype ctx tyS tyT then tyT else
if subtype ctx tyT tyS then tyS else
let tyS' = simplifyTy ctx tyS
tyT' = simplifyTy ctx tyT
in case (tyS', tyT') of
(TyRecord fS, TyRecord fT) ->
let labelsS = map (\(li, t) -> li) fS
labelsT = map (\(li, t) -> li) fT
commonLabels = filter (\li -> elem li labelsT) labelsS
commonFields = map (\li -> (li, join ctx (fromJust $ lookup li fS) (fromJust $ lookup li fT))) commonLabels
in TyRecord commonFields
(TyAll tyX tyS1 tyS2, TyAll _ tyT1 tyT2) ->
if not $ (subtype ctx tyS1 tyT1) && (subtype ctx tyT1 tyS1)
then TyTop
else let ctx' = addBinding ctx tyX (TyVarBinding tyT1) in
TyAll tyX tyS1 (join ctx' tyT1 tyT2)
(TyArr tyS1 tyS2, TyArr tyT1 tyT2) ->
TyArr (meet ctx tyS1 tyT1) (join ctx tyS2 tyT2)
(TyRef tyT1, TyRef tyT2) ->
if (subtype ctx tyT1 tyT2) && (subtype ctx tyT2 tyT1)
then TyRef tyT1
else TySource (join ctx tyT1 tyT2) -- why incomplete
(TySource tyT1, TySource tyT2) -> TySource (join ctx tyT1 tyT2)
(TyRef tyT1, TySource tyT2) -> TySource (join ctx tyT1 tyT2)
(TySource tyT1, TyRef tyT2) -> TySource (join ctx tyT1 tyT2)
(TySink tyT1, TySink tyT2) -> TySink (meet ctx tyT1 tyT2)
(TyRef tyT1, TySink tyT2) -> TySink (meet ctx tyT1 tyT2)
(TySink tyT1, TyRef tyT2) -> TySink (meet ctx tyT1 tyT2)
_ -> TyTop
meet ctx tyS tyT =
if subtype ctx tyS tyT then tyS else
if subtype ctx tyT tyS then tyT else
let tyS' = simplifyTy ctx tyS
tyT' = simplifyTy ctx tyT
in case (tyS', tyT') of
(TyRecord fS, TyRecord fT) ->
let labelsS = map (\(li, t) -> li) fS
labelsT = map (\(li, t) -> li) fT
allLabels = union labelsS labelsT
allFields = map (\li ->
if (elem li labelsS) && (elem li labelsT)
then (li, meet ctx (fromJust $ lookup li fS) (fromJust $ lookup li fT))
else if elem li labelsS
then (li, fromJust $ lookup li fS)
else (li, fromJust $ lookup li fT)
) allLabels
in TyRecord allFields
(TyAll tyX tyS1 tyS2, TyAll _ tyT1 tyT2) ->
if not $ (subtype ctx tyS1 tyT1) && (subtype ctx tyT1 tyS1)
then error "Not Found"
else let ctx' = addBinding ctx tyX (TyVarBinding tyT1) in
TyAll tyX tyS1 (meet ctx' tyT1 tyT2)
(TyArr tyS1 tyS2, TyArr tyT1 tyT2) ->
TyArr (join ctx tyS1 tyT1) (meet ctx tyS2 tyT2)
(TyRef tyT1, TyRef tyT2) ->
if (subtype ctx tyT1 tyT2) && (subtype ctx tyT2 tyT1)
then TyRef tyT1
else TySource (meet ctx tyT1 tyT2) -- why incomplete
(TySource tyT1, TySource tyT2) -> TySource (meet ctx tyT1 tyT2)
(TyRef tyT1, TySource tyT2) -> TySource (meet ctx tyT1 tyT2)
(TySource tyT1, TyRef tyT2) -> TySource (meet ctx tyT1 tyT2)
(TySink tyT1, TySink tyT2) -> TySink (join ctx tyT1 tyT2)
(TyRef tyT1, TySink tyT2) -> TySink (join ctx tyT1 tyT2)
(TySink tyT1, TyRef tyT2) -> TySink (join ctx tyT1 tyT2)
_ -> TyBot
-- Typing
lcst1 ctx tyS = unsafePerformIO $ catch
(evaluate $ promote ctx tyS)
returnTy
where
returnTy :: SomeException -> IO Type
returnTy err = return tyS
lcst ctx tyS = let tyS' = lcst1 ctx tyS in
if tyS' == tyS
then tyS
else lcst1 ctx tyS
typeOf ctx t = case t of
TmInert tyT -> tyT
TmVar i _ -> getTypeFromContext ctx i
TmAbs x tyT1 t2 -> let ctx' = addBinding ctx x (VarBinding tyT1)
tyT2 = typeOf ctx' t2
in TyArr tyT1 (typeShift (-1) tyT2)
TmApp t1 t2 -> let tyT1 = typeOf ctx t1
tyT2 = typeOf ctx t2
in case lcst ctx tyT1 of
TyArr tyT11 tyT12 ->
if subtype ctx tyT2 tyT11 then tyT12 else (error "Parameter type mismatch")
TyBot -> TyBot
_ -> (error "Arrow type expected")
TmTrue -> TyBool
TmFalse -> TyBool
TmIf t1 t2 t3 -> if subtype ctx (typeOf ctx t1) TyBool
then join ctx (typeOf ctx t2) (typeOf ctx t3)
else (error "Guard of conditional not a boolean")
TmLet x t1 t2 -> let tyT1 = typeOf ctx t1
ctx' = addBinding ctx x (VarBinding tyT1)
in typeShift (-1) (typeOf ctx' t2)
TmRecord fs -> let ftys = map (\(li, ti) -> (li, typeOf ctx ti)) fs in
TyRecord ftys
TmProj t1 l -> case lcst ctx (typeOf ctx t1) of
TyRecord ftys -> case lookup l ftys of
Just tys -> tys
Nothing -> (error $ "Label " ++ l ++ " not found")
TyBot -> TyBot
_ -> (error "Expected record type")
TmCase t cases -> case lcst ctx (typeOf ctx t) of
TyVariant ftys -> let _ = map (\(li, (xi, ti)) -> case lookup li ftys of
Just _ -> ()
Nothing -> (error $ "Label " ++ li ++ " not in type")
) cases
casetys = map (\(li, (xi, ti)) -> case lookup li ftys of
Nothing -> undefined -- impossible!
Just tyTi -> let ctx' = addBinding ctx xi (VarBinding tyTi) in
typeShift (-1) (typeOf ctx' ti)
) cases
in foldl (join ctx) TyBot casetys
TyBot -> TyBot
_ -> (error "Expected variant type")
TmFix t1 -> let tyT1 = typeOf ctx t1 in
case lcst ctx tyT1 of
TyArr tyT11 tyT12 -> if subtype ctx tyT12 tyT11
then tyT12
else (error "Result of body not compatible with domain")
TyBot -> TyBot
_ -> (error "Arrow type expected")
TmTag li ti tyT -> case simplifyTy ctx tyT of
TyVariant ftys -> let tyTiExpected = lookup li ftys
tyTi = typeOf ctx ti
in case tyTiExpected of
Nothing -> (error $ "Label " ++ li ++ " not found")
Just tyTie -> if subtype ctx tyTi tyTie
then tyT
else (error "Field does not have expected type")
TmAscribe t1 tyT -> if subtype ctx (typeOf ctx t1) tyT
then tyT
else (error "Body of as-term does not have the expected type")
TmString _ -> TyString
TmUnit -> TyUnit
TmRef t1 -> TyRef (typeOf ctx t1)
TmLoc l -> (error "Locations are not supposed to occur in source programs")
TmDeref t1 -> case lcst ctx (typeOf ctx t1) of
TyRef tyT1 -> tyT1
TyBot -> TyBot
TySource tyT1 -> tyT1
_ -> (error "Argument of ! is not a Ref or Source")
TmAssign t1 t2 -> case lcst ctx (typeOf ctx t1) of
TyRef tyT1 -> if subtype ctx (typeOf ctx t2) tyT1
then TyUnit
else (error "Arguments of := are incompatible")
TyBot -> let _ = typeOf ctx t2 in TyBot
TySink tyT1 -> if subtype ctx (typeOf ctx t2) tyT1
then TyUnit
else (error "Arguments of := are incompatible")
_ -> (error "Argument of := is not a Ref or Sink")
TmError -> TyBot
TmFloat _ -> TyFloat
TmTimesFloat t1 t2 -> if (subtype ctx (typeOf ctx t1) TyFloat) && (subtype ctx (typeOf ctx t2) TyFloat)
then TyFloat
else (error "Argument of *f is not a float") -- consider number <: float ?
TmTAbs tyX tyT1 t2 -> let ctx' = addBinding ctx tyX (TyVarBinding tyT1)
tyT2 = typeOf ctx t2
in TyAll tyX tyT1 tyT2
TmTApp t1 tyT2 -> let tyT1 = typeOf ctx t1 in
case lcst ctx tyT1 of
TyAll _ tyT11 tyT12 -> if not $ subtype ctx tyT2 tyT11
then (error "Type parameter type mismatch")
else typeSubstTop tyT2 tyT12
_ -> (error "Universal type expected")
TmTry t1 t2 -> join ctx (typeOf ctx t1) (typeOf ctx t2)
TmZero -> TyNat
TmSucc t1 -> if subtype ctx (typeOf ctx t1) TyNat
then TyNat
else (error "Argument of succ is not a number")
TmPred t1 -> if subtype ctx (typeOf ctx t1) TyNat
then TyNat
else (error "Argument of pred is not a number")
TmIsZero t1 -> if subtype ctx (typeOf ctx t1) TyNat
then TyBool
else (error "Argument of iszero is not a number")
TmPack tyT1 t2 tyT -> case simplifyTy ctx tyT of
TySome tyY tyBound tyT2 -> if not $ subtype ctx tyT1 tyBound
then (error "Hidden type not a subtype of bound")
else let tyU = typeOf ctx t2
tyU' = typeSubstTop tyT1 tyT2
in if subtype ctx tyU tyU'
then tyT
else (error "Doesn't match declared type")
_ -> (error "Existential type expected")
TmUnpack tyX x t1 t2 -> let tyT1 = typeOf ctx t1 in
case lcst ctx tyT1 of
TySome tyT tyBound tyT11 -> let ctx' = addBinding ctx tyX (TyVarBinding tyBound)
ctx'' = addBinding ctx' x (VarBinding tyT11)
tyT2 = typeOf ctx'' t2
in typeShift (-2) tyT2
_ -> (error "Existential type expected") | null | https://raw.githubusercontent.com/Airtnp/Notes/d0d2677d0316f24fd5681516b4f38daa7f7269ab/Books/subtying.hs | haskell | ref: /~bcpierce/tapl/checkers/fullfsub/syntax.ml
TODO: the error handling is shit. Try replace everything by Either Type/Term Error
TODO: add Kind system
invariant subtyping
covariant subtyping
Type operations
Γ⊢a
Γ⊢x:T.t1 (T->)
Γ⊢M N
record <-> proj
as
type application t[T]
type abstraction (\lambda X.t) # X:type
{*T, t} as T
let {X, x} = t1 in t2
\Gamma, x : T
Or TyAbbBinding Type (Maybe Kind) \Gamma, X
Context
Shifting
Substitution
[j -> s]t
Context
Print
TODO: printType / printTerm
Evaluation
By process and perservation theorem
That's all bad
T <: Top
Bot <: T
(->) a as contravariant operatior
{l:r} <: {l':r'}
why incomplete
why incomplete
Typing
impossible!
consider number <: float ? | Fullformsub is the ultra in TAPL : /~bcpierce/tapl/checkers/fullfomsub/
import Data.Maybe
import Data.List
import Control.Exception
import System.IO.Unsafe
data Kind =
KnStar
| KnArr Kind Kind
data Type =
TyVar Int Int
| TyId String
| TyTop
| TyBot
| TyArr Type Type
| TyRecord [(String, Type)]
| TyVariant [(String, Type)]
| TyString
| TyUnit
| TyFloat
| TyNat
| TyBool
forall X < : T. ( better TyAll String Kind Type )
exist X < : T. ( better )
| TySink Type
deriving(Eq, Show)
TyAbs String Kind Type
data Term =
| TmTrue
| TmFalse
| TmString String
| TmUnit
| TmFloat Float
| TmIf Term Term Term
| TmRecord [(String, Term)]
| TmCase Term [(String, (String, Term))]
| TmTag String Term Type
let x = t1 in t2 = = = ( \x : T1 t2 ) t1 = = = [ x - > t1]t2
fix \x : T1 t2 = = = [ x - > fix \x : T1 t2]t2
| TmTimesFloat Term Term
| TmZero
| TmSucc Term
| TmPred Term
| TmIsZero Term
| TmInert Type
| TmRef Term
| TmDeref Term
| TmAssign Term Term
| TmError
| TmTry Term Term
| TmLoc Int
deriving(Eq, Show)
TmUpdate Term String Term
data Binding =
NameBinding
| VarBinding Type
| TmAbbBinding Term (Maybe Type)
deriving(Eq, Show)
type Context = [(String, Binding)]
data Command =
Eval Term
| Bind String Binding
| SomeBind String String Term
addBinding :: Context -> String -> Binding -> Context
addBinding ctx x bind = (x, bind) : ctx
addName :: Context -> String -> Context
addName ctx x = addBinding ctx x NameBinding
isNameBound :: Context -> String -> Bool
isNameBound ctx x = case ctx of
[] -> False
y:ys -> if x == (fst y) then True else isNameBound ys x
pkFreshVarName :: Context -> String -> (String, Context)
pkFreshVarName ctx x =
let x' = mkFreshVarName ctx x in
(x', addBinding ctx x' NameBinding)
mkFreshVarName :: Context -> String -> String
mkFreshVarName [] x = x
mkFreshVarName ctx@(c:cs) x
| x == (fst c) = mkFreshVarName ctx (x ++ "'")
| otherwise = mkFreshVarName cs x
indexToName :: Context -> Int -> String
indexToName ctx i
| length ctx > i = fst $ ctx !! i
| otherwise = undefined
nameToIndex :: Context -> String -> Int
nameToIndex ctx x = case ctx of
[] -> undefined
y:ys -> if x == (fst y) then 0 else (+) 1 $ nameToIndex ctx x
instance where
tyMap onvar c tyT = walk c tyT where
walk c tyT = case tyT of
TyVar x n -> onvar c x n
TyId b -> TyId b
TyArr tyT1 tyT2 -> TyArr (walk c tyT1) (walk c tyT2)
TyTop -> TyTop
TyBot -> TyBot
TyBool -> TyBool
TyRecord fs -> TyRecord $ map (\lty -> (fst lty, walk c $ snd lty)) fs
TyVariant fs -> TyVariant $ map (\lty -> (fst lty, walk c $ snd lty)) fs
TyString -> TyString
TyUnit -> TyUnit
TyFloat -> TyFloat
TyAll tyX tyT1 tyT2 -> TyAll tyX (walk c tyT1) (walk c tyT2)
TyNat -> TyNat
TySome tyX tyT1 tyT2 -> TySome tyX (walk c tyT1) (walk c tyT2)
TyRef tyT1 -> TyRef (walk c tyT1)
TySource tyT1 -> TySource (walk c tyT1)
TySink tyT1 -> TySink (walk c tyT1)
tmMap onvar ontype c t = walk c t where
walk c t = case t of
TmInert tyT -> TmInert $ ontype c tyT
TmVar x n -> onvar c x n
TmAbs x tyT1 t2 -> TmAbs x (ontype c tyT1) (walk (c+1) t2)
TmApp t1 t2 -> TmApp (walk c t1) (walk c t2)
TmTrue -> TmTrue
TmFalse -> TmFalse
TmIf t1 t2 t3 -> TmIf (walk c t1) (walk c t2) (walk c t3)
TmProj t1 l -> TmProj (walk c t1) l
TmRecord fs -> TmRecord $ map (\lt -> (fst lt, walk c $ snd lt)) fs
TmLet x t1 t2 -> TmLet x (walk c t1) (walk (c+1) t2)
TmFix t1 -> TmFix (walk c t1)
TmString x -> TmString x
TmUnit -> TmUnit
TmAscribe t1 tyT1 -> TmAscribe (walk c t1) (ontype c tyT1)
TmFloat x -> TmFloat x
TmTimesFloat t1 t2 -> TmTimesFloat (walk c t1) (walk c t2)
TmTAbs tyX tyT1 t2 -> TmTAbs tyX (ontype c tyT1) (walk (c+1) t2)
TmTApp t1 tyT2 -> TmTApp (walk c t1) (ontype c tyT2)
TmZero -> TmZero
TmSucc t1 -> TmSucc (walk c t1)
TmPred t1 -> TmPred (walk c t1)
TmIsZero t1 -> TmIsZero (walk c t1)
TmPack tyT1 t2 tyT3 -> TmPack (ontype c tyT1) (walk c t2) (ontype c tyT3)
TmUnpack tyX x t1 t2 -> TmUnpack tyX x (walk c t1) (walk (c+2) t2)
TmTag l t1 tyT -> TmTag l (walk c t1) (ontype c tyT)
TmCase t cases -> TmCase (walk c t) (map (\(li, (xi, ti)) -> (li, (xi, walk (c+1) ti))) cases)
TmLoc l -> TmLoc l
TmRef t1 -> TmRef (walk c t1)
TmDeref t1 -> TmDeref (walk c t1)
TmAssign t1 t2 -> TmAssign (walk c t1) (walk c t2)
TmError -> TmError
TmTry t1 t2 -> TmTry (walk c t1) (walk c t2)
typeShiftAbove d c tyT =
tyMap
(\c x n -> if x >= c then TyVar (x+d) (n+d) else TyVar x (n+d))
c tyT
[ ↑d , c]t
termShiftAbove d c t =
tmMap
(\c' x n -> if x >= c' then TmVar (x+d) (n+d) else TmVar x (n+d))
(typeShiftAbove d)
c t
typeShift d tyT = typeShiftAbove d 0 tyT
termShift d t = termShiftAbove d 0 t
bindingShift d bind = case bind of
NameBinding -> NameBinding
TyVarBinding tyS -> TyVarBinding (typeShift d tyS)
VarBinding tyT -> VarBinding (typeShift d tyT)
TyAbbBinding tyT -> TyAbbBinding (typeShift d tyT)
TmAbbBinding t tyT_opt ->
let tyT_opt' = case tyT_opt of
Nothing -> Nothing
Just tyT -> Just (typeShift d tyT)
in TmAbbBinding (termShift d t) tyT_opt'
termSubst j s t =
tmMap
(\j x n -> if x == j then termShift j s else TmVar x n)
(\j tyT -> tyT)
j t
typeSubst tyS j tyT =
tyMap
(\j x n -> if x == j then typeShift j tyS else TyVar x n)
j tyT
termSubstTop s t =
termShift (-1) (termSubst 0 (termShift 1 s) t)
typeSubstTop tyS tyT =
typeShift (-1) (typeSubst (typeShift 1 tyS) 0 tyT)
tyTermSubst tyS j t =
tmMap
(\c x n -> TmVar x n)
(\j tyT -> typeSubst tyS j tyT)
j t
tyTermSubstTop tyS t =
termShift (-1) (tyTermSubst (typeShift 1 tyS) 0 t)
getBinding ctx i
| length ctx > i = let bind = snd $ ctx !! i
in bindingShift (i + 1) bind
| otherwise = undefined
getTypeFromContext ctx i =
case getBinding ctx i of
VarBinding tyT -> tyT
TmAbbBinding _ (Just tyT) -> tyT
TmAbbBinding _ Nothing -> undefined
_ -> undefined
small t = case t of
TmVar _ _ -> True
_ -> False
isNumericVal ctx t = case t of
TmZero -> True
TmSucc t1 -> isNumericVal ctx t1
_ -> False
isVal ctx t = case t of
TmTrue -> True
TmFalse -> True
TmString _ -> True
TmUnit -> True
TmFloat _ -> True
TmLoc _ -> True
t | isNumericVal ctx t -> True
TmAbs _ _ _ -> True
TmRecord fs -> all (\(l,ti) -> isVal ctx ti) fs
TmPack _ v1 _ -> isVal ctx v1
TmTAbs _ _ _ -> True
_ -> False
type Store = [Term]
extendStore store v = (length store, store ++ [v])
lookupLoc store l = store !! l
updateStore store n v = f (n, store) where
f s = case s of
(0, v':rest) -> v:rest
(n, v':rest) -> v':f(n-1, rest)
_ -> error "updateStore: bad index"
shiftStore i store = map (\t -> termShift i t) store
eval1 ctx store t = case t of
TmIf TmTrue t2 t3 -> (t2, store)
TmIf TmFalse t2 t3 -> (t3, store)
TmIf t1 t2 t3 -> let (t1', store') = eval1 ctx store t1 in
(TmIf t1' t2 t3, store')
TmRecord fs ->
let evalField l = case l of
[] -> (error "No Rule Applies")
(l, vi):rest
| isVal ctx vi -> let (rest', store') = evalField rest in
((l, vi):rest', store')
| otherwise -> let (ti', store') = eval1 ctx store vi in
((l, ti'):rest, store')
in let (fs', store') = evalField fs in
(TmRecord fs', store')
TmProj (TmRecord fs) l
| isVal ctx (TmRecord fs) -> let rd = filter (\(li, ti) -> li == l) fs in
if rd == [] then (error "No Rule Applies") else (snd $ rd !! 0, store)
TmProj t1 l -> let (t1', store') = eval1 ctx store t1 in
(TmProj t1' l, store')
TmLet x v1 t2
| isVal ctx v1 -> (termSubstTop v1 t2, store)
| otherwise -> let (t1', store') = eval1 ctx store v1 in
(TmLet x t1' t2, store')
TmFix v1
| isVal ctx v1 -> case v1 of
TmAbs _ _ t12 -> (termSubstTop (TmFix v1) t12, store)
_ -> (error "No Rule Applies")
| otherwise -> let (t1', store') = eval1 ctx store v1 in
(TmFix t1', store')
TmTag l t1 tyT -> let (t1', store') = eval1 ctx store t1 in
(TmTag l t1' tyT, store')
TmCase (TmTag li v11 tyT) branches
| isVal ctx v11 -> let rd = filter (\(li', (xi, ti)) -> li == li') branches in
if rd == [] then (error "No Rule Applies") else (termSubstTop v11 $ snd $ snd (rd !! 0), store)
TmCase t1 branches -> let (t1', store') = eval1 ctx store t1 in
(TmCase t1' branches, store')
TmAscribe v1 tyT
| isVal ctx v1 -> (v1, store)
| otherwise -> let (t1', store') = eval1 ctx store v1 in
(TmAscribe t1' tyT, store')
TmVar n _ -> case getBinding ctx n of
TmAbbBinding t _ -> (t, store)
_ -> (error "No Rule Applies")
TmRef t1
| isVal ctx t1 -> let (l, store') = extendStore store t1 in
(TmLoc l, store')
| otherwise -> let (t1', store') = eval1 ctx store t1 in
(TmRef t1', store')
TmDeref t1
| isVal ctx t1 -> case t1 of
TmLoc l -> (lookupLoc store l, store)
_ -> (error "No Rule Applies")
| otherwise -> let (t1', store') = eval1 ctx store t1 in
(TmDeref t1', store')
TmAssign t1 t2
| (isVal ctx t1) && (isVal ctx t2) -> case t1 of
TmLoc l -> (TmUnit, updateStore store l t2)
_ -> (error "No Rule Applies")
| not (isVal ctx t1) -> let (t1', store') = eval1 ctx store t1 in
(TmAssign t1' t2, store')
| not (isVal ctx t2) -> let (t2', store') = eval1 ctx store t2 in
(TmAssign t1 t2', store')
TmError -> (error "Error Encountered")
TmTimesFloat (TmFloat f1) (TmFloat f2) -> (TmFloat (f1*f2), store)
TmTimesFloat (TmFloat f1) t2 -> let (t2', store') = eval1 ctx store t2 in
(TmTimesFloat (TmFloat f1) t2', store')
TmTimesFloat t1 t2 -> let (t1', store') = eval1 ctx store t1 in
(TmTimesFloat t1' t2, store')
TmSucc t1 -> let (t1', store') = eval1 ctx store t1 in
(TmSucc t1', store')
TmPred t1 -> let (t1', store') = eval1 ctx store t1 in
(TmPred t1', store')
TmIsZero TmZero -> (TmTrue, store)
TmIsZero (TmSucc nv1)
| isNumericVal ctx nv1 -> (TmFalse, store)
TmIsZero t1 -> let (t1', store') = eval1 ctx store t1 in
(TmIsZero t1', store')
TmTApp (TmTAbs x _ t11) tyT2 -> (tyTermSubstTop tyT2 t11, store)
TmTApp t1 tyT2 -> let (t1', store') = eval1 ctx store t1 in
(TmTApp t1' tyT2, store')
TmApp (TmAbs x tyT11 t12) v2
| isVal ctx v2 -> (termSubstTop v2 t12, store)
TmApp v1 t2
| isVal ctx v1 -> let (t2', store') = eval1 ctx store t2 in
(TmApp v1 t2', store')
TmApp t1 t2 -> let (t1', store') = eval1 ctx store t2 in
(TmApp t1' t2, store')
TmPack tyT1 t2 tyT3 -> let (t2', store') = eval1 ctx store t2 in
(TmPack tyT1 t2' tyT3, store')
TmUnpack _ _ (TmPack tyT11 v12 _) t2
| isVal ctx v12 -> (tyTermSubstTop tyT11 (termSubstTop (termShift 1 v12) t2), store)
TmUnpack tyX x t1 t2 -> let (t1', store') = eval1 ctx store t1 in
(TmUnpack tyX x t1' t2, store')
evalPre ctx store t = unsafePerformIO $ catch
(evaluate $ eval1 ctx store t)
returnTs
where
returnTs :: SomeException -> IO (Term, Store)
returnTs err = return (t, store)
eval ctx store t = let (t', store') = evalPre ctx store t in
if (t', store') == (t, store)
then (t, store)
else evalPre ctx store' t'
evalBinding ctx store b = case b of
TmAbbBinding t tyT -> let (t', store') = eval ctx store t in
(TmAbbBinding t' tyT, store')
bind -> (bind, store)
\Gamma |- S ⇑ T ( )
TyVar i _ -> case getBinding ctx i of
TyVarBinding tyT -> tyT
_ -> (error "No Rule Applies")
_ -> (error "No Rule Applies")
isTyAbb ctx i = case getBinding ctx i of
TyAbbBinding tyT -> True
_ -> False
getTyAbb ctx i = case getBinding ctx i of
TyAbbBinding tyT -> tyT
_ -> (error "No Rule Applies")
computeTy ctx tyT = case tyT of
TyVar i _ | isTyAbb ctx i -> getTyAbb ctx i
_ -> (error "No Rule Applies")
simplifyTy1 :: Context -> Type -> Type
simplifyTy1 ctx tyT = unsafePerformIO $ catch
(evaluate (computeTy ctx tyT))
returnTy
where
returnTy :: SomeException -> IO Type
returnTy err = return tyT
simplifyTy ctx tyT = let tyT' = simplifyTy1 ctx tyT in
if tyT' == tyT then tyT else simplifyTy1 ctx tyT'
tyEqv ctx tyS tyT =
let tyS' = simplifyTy ctx tyS
tyT' = simplifyTy ctx tyT
in case (tyS', tyT') of
(TyTop, TyTop) -> True
(TyBot, TyBot) -> True
(TyArr tyS1 tyS2, TyArr tyT1 tyT2) ->
(tyEqv ctx tyS1 tyT1) && (tyEqv ctx tyS2 tyT2)
(TyString, TyString) -> True
(TyId b1, TyId b2) -> b1 == b2
(TyFloat, TyFloat) -> True
(TyUnit, TyUnit) -> True
(TyRef tyT1, TyRef tyT2) -> tyEqv ctx tyT1 tyT2
(TySource tyT1, TySource tyT2) -> tyEqv ctx tyT1 tyT2
(TySink tyT1, TySink tyT2) -> tyEqv ctx tyT1 tyT2
(TyVar i _, _) | isTyAbb ctx i -> tyEqv ctx (getTyAbb ctx i) tyT'
(_, TyVar i _) | isTyAbb ctx i -> tyEqv ctx tyS' (getTyAbb ctx i)
(TyBool, TyBool) -> True
(TyNat, TyNat) -> True
(TyRecord fs1, TyRecord fs2) -> (length fs1 == length fs2) &&
all id (map
(\(li2, tyTi2) -> let rd = filter (\(li1, tyTi1) -> li2 == li1) fs1
in if length rd == 0 then False else tyEqv ctx (snd $ rd !! 0) tyTi2
)
fs2)
(TyAll tyX1 tyS1 tyS2, TyAll _ tyT1 tyT2) -> let ctx' = addName ctx tyX1 in
(tyEqv ctx tyS1 tyT1) && (tyEqv ctx' tyS2 tyT2)
(TyVariant fs1, TyVariant fs2) -> (length fs1 == length fs2) &&
all id (map
(\(li2, tyTi2) -> let rd = filter (\(li1, tyTi1) -> li2 == li1) fs1
in if length rd == 0 then False else tyEqv ctx (snd $ rd !! 0) tyTi2
)
fs2)
_ -> False
subtype ctx tyS tyT = tyEqv ctx tyS tyT ||
let tyS' = simplifyTy ctx tyS
tyT' = simplifyTy ctx tyT
in case (tyS', tyT') of
(_, TyTop) -> True
(TyBot, _) -> True
(TyArr tyS1 tyS2, TyArr tyT1 tyT2) ->
(subtype ctx tyT1 tyS1) && (subtype ctx tyS2 tyT2)
(TyRecord fS, TyRecord fT) ->
all id (map
(\(li, tyTi) -> let rd = filter (\(li1, tyTi1) -> li == li1) fS
in if length rd == 0 then False else subtype ctx (snd $ rd !! 0) tyTi)
fT
)
(TyVariant fS, TyVariant fT) ->
all id (map
(\(li, tyTi) -> let rd = filter (\(li1, tyTi1) -> li == li1) fS
in if length rd == 0 then False else subtype ctx (snd $ rd !! 0) tyTi)
fT
)
(TyVar _ _, _) -> subtype ctx (promote ctx tyS') tyT'
(TyAll tyX1 tyS1 tyS2, TyAll _ tyT1 tyT2) ->
(subtype ctx tyS1 tyT1 && subtype ctx tyT1 tyS1) &&
let ctx' = addBinding ctx tyX1 (TyVarBinding tyT1) in
subtype ctx' tyS2 tyT2
(TyRef tyT1, TyRef tyT2) -> (subtype ctx tyT1 tyT2) && (subtype ctx tyT2 tyT1)
(TyRef tyT1, TySource tyT2) -> subtype ctx tyT1 tyT2
(TySource tyT1, TySource tyT2) -> subtype ctx tyT1 tyT2
(TyRef tyT1, TySink tyT2) -> subtype ctx tyT2 tyT1
(TySink tyT1, TySink tyT2) -> subtype ctx tyT2 tyT1
_ -> False
join ctx tyS tyT =
if subtype ctx tyS tyT then tyT else
if subtype ctx tyT tyS then tyS else
let tyS' = simplifyTy ctx tyS
tyT' = simplifyTy ctx tyT
in case (tyS', tyT') of
(TyRecord fS, TyRecord fT) ->
let labelsS = map (\(li, t) -> li) fS
labelsT = map (\(li, t) -> li) fT
commonLabels = filter (\li -> elem li labelsT) labelsS
commonFields = map (\li -> (li, join ctx (fromJust $ lookup li fS) (fromJust $ lookup li fT))) commonLabels
in TyRecord commonFields
(TyAll tyX tyS1 tyS2, TyAll _ tyT1 tyT2) ->
if not $ (subtype ctx tyS1 tyT1) && (subtype ctx tyT1 tyS1)
then TyTop
else let ctx' = addBinding ctx tyX (TyVarBinding tyT1) in
TyAll tyX tyS1 (join ctx' tyT1 tyT2)
(TyArr tyS1 tyS2, TyArr tyT1 tyT2) ->
TyArr (meet ctx tyS1 tyT1) (join ctx tyS2 tyT2)
(TyRef tyT1, TyRef tyT2) ->
if (subtype ctx tyT1 tyT2) && (subtype ctx tyT2 tyT1)
then TyRef tyT1
(TySource tyT1, TySource tyT2) -> TySource (join ctx tyT1 tyT2)
(TyRef tyT1, TySource tyT2) -> TySource (join ctx tyT1 tyT2)
(TySource tyT1, TyRef tyT2) -> TySource (join ctx tyT1 tyT2)
(TySink tyT1, TySink tyT2) -> TySink (meet ctx tyT1 tyT2)
(TyRef tyT1, TySink tyT2) -> TySink (meet ctx tyT1 tyT2)
(TySink tyT1, TyRef tyT2) -> TySink (meet ctx tyT1 tyT2)
_ -> TyTop
meet ctx tyS tyT =
if subtype ctx tyS tyT then tyS else
if subtype ctx tyT tyS then tyT else
let tyS' = simplifyTy ctx tyS
tyT' = simplifyTy ctx tyT
in case (tyS', tyT') of
(TyRecord fS, TyRecord fT) ->
let labelsS = map (\(li, t) -> li) fS
labelsT = map (\(li, t) -> li) fT
allLabels = union labelsS labelsT
allFields = map (\li ->
if (elem li labelsS) && (elem li labelsT)
then (li, meet ctx (fromJust $ lookup li fS) (fromJust $ lookup li fT))
else if elem li labelsS
then (li, fromJust $ lookup li fS)
else (li, fromJust $ lookup li fT)
) allLabels
in TyRecord allFields
(TyAll tyX tyS1 tyS2, TyAll _ tyT1 tyT2) ->
if not $ (subtype ctx tyS1 tyT1) && (subtype ctx tyT1 tyS1)
then error "Not Found"
else let ctx' = addBinding ctx tyX (TyVarBinding tyT1) in
TyAll tyX tyS1 (meet ctx' tyT1 tyT2)
(TyArr tyS1 tyS2, TyArr tyT1 tyT2) ->
TyArr (join ctx tyS1 tyT1) (meet ctx tyS2 tyT2)
(TyRef tyT1, TyRef tyT2) ->
if (subtype ctx tyT1 tyT2) && (subtype ctx tyT2 tyT1)
then TyRef tyT1
(TySource tyT1, TySource tyT2) -> TySource (meet ctx tyT1 tyT2)
(TyRef tyT1, TySource tyT2) -> TySource (meet ctx tyT1 tyT2)
(TySource tyT1, TyRef tyT2) -> TySource (meet ctx tyT1 tyT2)
(TySink tyT1, TySink tyT2) -> TySink (join ctx tyT1 tyT2)
(TyRef tyT1, TySink tyT2) -> TySink (join ctx tyT1 tyT2)
(TySink tyT1, TyRef tyT2) -> TySink (join ctx tyT1 tyT2)
_ -> TyBot
lcst1 ctx tyS = unsafePerformIO $ catch
(evaluate $ promote ctx tyS)
returnTy
where
returnTy :: SomeException -> IO Type
returnTy err = return tyS
lcst ctx tyS = let tyS' = lcst1 ctx tyS in
if tyS' == tyS
then tyS
else lcst1 ctx tyS
typeOf ctx t = case t of
TmInert tyT -> tyT
TmVar i _ -> getTypeFromContext ctx i
TmAbs x tyT1 t2 -> let ctx' = addBinding ctx x (VarBinding tyT1)
tyT2 = typeOf ctx' t2
in TyArr tyT1 (typeShift (-1) tyT2)
TmApp t1 t2 -> let tyT1 = typeOf ctx t1
tyT2 = typeOf ctx t2
in case lcst ctx tyT1 of
TyArr tyT11 tyT12 ->
if subtype ctx tyT2 tyT11 then tyT12 else (error "Parameter type mismatch")
TyBot -> TyBot
_ -> (error "Arrow type expected")
TmTrue -> TyBool
TmFalse -> TyBool
TmIf t1 t2 t3 -> if subtype ctx (typeOf ctx t1) TyBool
then join ctx (typeOf ctx t2) (typeOf ctx t3)
else (error "Guard of conditional not a boolean")
TmLet x t1 t2 -> let tyT1 = typeOf ctx t1
ctx' = addBinding ctx x (VarBinding tyT1)
in typeShift (-1) (typeOf ctx' t2)
TmRecord fs -> let ftys = map (\(li, ti) -> (li, typeOf ctx ti)) fs in
TyRecord ftys
TmProj t1 l -> case lcst ctx (typeOf ctx t1) of
TyRecord ftys -> case lookup l ftys of
Just tys -> tys
Nothing -> (error $ "Label " ++ l ++ " not found")
TyBot -> TyBot
_ -> (error "Expected record type")
TmCase t cases -> case lcst ctx (typeOf ctx t) of
TyVariant ftys -> let _ = map (\(li, (xi, ti)) -> case lookup li ftys of
Just _ -> ()
Nothing -> (error $ "Label " ++ li ++ " not in type")
) cases
casetys = map (\(li, (xi, ti)) -> case lookup li ftys of
Just tyTi -> let ctx' = addBinding ctx xi (VarBinding tyTi) in
typeShift (-1) (typeOf ctx' ti)
) cases
in foldl (join ctx) TyBot casetys
TyBot -> TyBot
_ -> (error "Expected variant type")
TmFix t1 -> let tyT1 = typeOf ctx t1 in
case lcst ctx tyT1 of
TyArr tyT11 tyT12 -> if subtype ctx tyT12 tyT11
then tyT12
else (error "Result of body not compatible with domain")
TyBot -> TyBot
_ -> (error "Arrow type expected")
TmTag li ti tyT -> case simplifyTy ctx tyT of
TyVariant ftys -> let tyTiExpected = lookup li ftys
tyTi = typeOf ctx ti
in case tyTiExpected of
Nothing -> (error $ "Label " ++ li ++ " not found")
Just tyTie -> if subtype ctx tyTi tyTie
then tyT
else (error "Field does not have expected type")
TmAscribe t1 tyT -> if subtype ctx (typeOf ctx t1) tyT
then tyT
else (error "Body of as-term does not have the expected type")
TmString _ -> TyString
TmUnit -> TyUnit
TmRef t1 -> TyRef (typeOf ctx t1)
TmLoc l -> (error "Locations are not supposed to occur in source programs")
TmDeref t1 -> case lcst ctx (typeOf ctx t1) of
TyRef tyT1 -> tyT1
TyBot -> TyBot
TySource tyT1 -> tyT1
_ -> (error "Argument of ! is not a Ref or Source")
TmAssign t1 t2 -> case lcst ctx (typeOf ctx t1) of
TyRef tyT1 -> if subtype ctx (typeOf ctx t2) tyT1
then TyUnit
else (error "Arguments of := are incompatible")
TyBot -> let _ = typeOf ctx t2 in TyBot
TySink tyT1 -> if subtype ctx (typeOf ctx t2) tyT1
then TyUnit
else (error "Arguments of := are incompatible")
_ -> (error "Argument of := is not a Ref or Sink")
TmError -> TyBot
TmFloat _ -> TyFloat
TmTimesFloat t1 t2 -> if (subtype ctx (typeOf ctx t1) TyFloat) && (subtype ctx (typeOf ctx t2) TyFloat)
then TyFloat
TmTAbs tyX tyT1 t2 -> let ctx' = addBinding ctx tyX (TyVarBinding tyT1)
tyT2 = typeOf ctx t2
in TyAll tyX tyT1 tyT2
TmTApp t1 tyT2 -> let tyT1 = typeOf ctx t1 in
case lcst ctx tyT1 of
TyAll _ tyT11 tyT12 -> if not $ subtype ctx tyT2 tyT11
then (error "Type parameter type mismatch")
else typeSubstTop tyT2 tyT12
_ -> (error "Universal type expected")
TmTry t1 t2 -> join ctx (typeOf ctx t1) (typeOf ctx t2)
TmZero -> TyNat
TmSucc t1 -> if subtype ctx (typeOf ctx t1) TyNat
then TyNat
else (error "Argument of succ is not a number")
TmPred t1 -> if subtype ctx (typeOf ctx t1) TyNat
then TyNat
else (error "Argument of pred is not a number")
TmIsZero t1 -> if subtype ctx (typeOf ctx t1) TyNat
then TyBool
else (error "Argument of iszero is not a number")
TmPack tyT1 t2 tyT -> case simplifyTy ctx tyT of
TySome tyY tyBound tyT2 -> if not $ subtype ctx tyT1 tyBound
then (error "Hidden type not a subtype of bound")
else let tyU = typeOf ctx t2
tyU' = typeSubstTop tyT1 tyT2
in if subtype ctx tyU tyU'
then tyT
else (error "Doesn't match declared type")
_ -> (error "Existential type expected")
TmUnpack tyX x t1 t2 -> let tyT1 = typeOf ctx t1 in
case lcst ctx tyT1 of
TySome tyT tyBound tyT11 -> let ctx' = addBinding ctx tyX (TyVarBinding tyBound)
ctx'' = addBinding ctx' x (VarBinding tyT11)
tyT2 = typeOf ctx'' t2
in typeShift (-2) tyT2
_ -> (error "Existential type expected") |
9ac28ca8f857aed22685b7fb51210317478600d1b8c9af7038d172d51cc3139b | drathier/elm-offline | Args.hs | module Terminal.Args
( simple
, Interface(..)
, Summary(..)
, complex
, Flags, noFlags, flags, (|--)
, Flag, flag, onOff
, Parser(..)
, Args, noArgs, required, optional, zeroOrMore, oneOrMore, oneOf
, require0, require1, require2, require3, require4, require5
, RequiredArgs, args, exactly, (!), (?), (...)
)
where
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified System.Directory as Dir
import qualified System.Environment as Env
import qualified System.Exit as Exit
import qualified System.FilePath as FP
import System.FilePath ((</>))
import System.IO (hPutStr, hPutStrLn, stdout)
import qualified Text.PrettyPrint.ANSI.Leijen as P
import qualified Text.Read as Read
import qualified Elm.Compiler as Compiler
import qualified Elm.Package as Pkg
import Terminal.Args.Internal
import qualified Terminal.Args.Chomp as Chomp
import qualified Terminal.Args.Error as Error
-- GET
simple :: String -> P.Doc -> Args args -> Flags flags -> (args -> flags -> IO ()) -> IO ()
simple details example args_ flags_ callback =
do argStrings <- Env.getArgs
case argStrings of
["--version"] ->
do hPutStrLn stdout (Pkg.versionToString Compiler.version)
Exit.exitSuccess
chunks ->
if elem "--help" chunks then
Error.exitWithHelp Nothing details example args_ flags_
else
case snd $ Chomp.chomp Nothing chunks args_ flags_ of
Right (argsValue, flagValue) ->
callback argsValue flagValue
Left err ->
Error.exitWithError err
complex :: P.Doc -> P.Doc -> [Interface] -> IO ()
complex intro outro interfaces =
do argStrings <- Env.getArgs
case argStrings of
[] ->
Error.exitWithOverview intro outro interfaces
["--help"] ->
Error.exitWithOverview intro outro interfaces
["--version"] ->
do hPutStrLn stdout (Pkg.versionToString Compiler.version)
Exit.exitSuccess
command : chunks ->
do case List.find (\iface -> toName iface == command) interfaces of
Nothing ->
Error.exitWithUnknown command (map toName interfaces)
Just (Interface _ _ details example args_ flags_ callback) ->
if elem "--help" chunks then
Error.exitWithHelp (Just command) details example args_ flags_
else
case snd $ Chomp.chomp Nothing chunks args_ flags_ of
Right (argsValue, flagValue) ->
callback argsValue flagValue
Left err ->
Error.exitWithError err
-- AUTO-COMPLETE
_maybeAutoComplete :: [String] -> (Int -> [String] -> IO [String]) -> IO ()
_maybeAutoComplete argStrings getSuggestions =
if length argStrings /= 3 then
return ()
else
do maybeLine <- Env.lookupEnv "COMP_LINE"
case maybeLine of
Nothing ->
return ()
Just line ->
do (index, chunks) <- getCompIndex line
suggestions <- getSuggestions index chunks
hPutStr stdout (unlines suggestions)
Exit.exitFailure
getCompIndex :: String -> IO (Int, [String])
getCompIndex line =
do maybePoint <- Env.lookupEnv "COMP_POINT"
case Read.readMaybe =<< maybePoint of
Nothing ->
do let chunks = words line
return (length chunks, chunks)
Just point ->
let
groups = List.groupBy grouper (zip line [0..])
rawChunks = drop 1 (filter (all (not . isSpace . fst)) groups)
in
return
( findIndex 1 point rawChunks
, map (map fst) rawChunks
)
grouper :: (Char, Int) -> (Char, Int) -> Bool
grouper (c1, _) (c2, _) =
isSpace c1 == isSpace c2
isSpace :: Char -> Bool
isSpace char =
char == ' ' || char == '\t' || char == '\n'
findIndex :: Int -> Int -> [[(Char,Int)]] -> Int
findIndex index point chunks =
case chunks of
[] ->
index
chunk:cs ->
let
lo = snd (head chunk)
hi = snd (last chunk)
in
if point < lo then
0
else if point <= hi + 1 then
index
else
findIndex (index + 1) point cs
_complexSuggest :: [Interface] -> Int -> [String] -> IO [String]
_complexSuggest interfaces index strings =
case strings of
[] ->
return (map toName interfaces)
command : chunks ->
if index == 1 then
return (filter (List.isPrefixOf command) (map toName interfaces))
else
case List.find (\iface -> toName iface == command) interfaces of
Nothing ->
return []
Just (Interface _ _ _ _ args_ flags_ _) ->
fst $ Chomp.chomp (Just (index-1)) chunks args_ flags_
{-|-}
noFlags :: Flags ()
noFlags =
FDone ()
{-|-}
flags :: a -> Flags a
flags =
FDone
{-|-}
(|--) :: Flags (a -> b) -> Flag a -> Flags b
(|--) =
FMore
-- FLAG
{-|-}
flag :: String -> Parser a -> String -> Flag (Maybe a)
flag =
Flag
{-|-}
onOff :: String -> String -> Flag Bool
onOff =
OnOff
-- FANCY ARGS
{-|-}
args :: a -> RequiredArgs a
args =
Done
{-|-}
exactly :: RequiredArgs a -> Args a
exactly requiredArgs =
Args [Exactly requiredArgs]
{-|-}
(!) :: RequiredArgs (a -> b) -> Parser a -> RequiredArgs b
(!) =
Required
{-|-}
(?) :: RequiredArgs (Maybe a -> b) -> Parser a -> Args b
(?) requiredArgs optionalArg =
Args [Optional requiredArgs optionalArg]
{-|-}
(...) :: RequiredArgs ([a] -> b) -> Parser a -> Args b
(...) requiredArgs repeatedArg =
Args [Multiple requiredArgs repeatedArg]
{-|-}
oneOf :: [Args a] -> Args a
oneOf listOfArgs =
Args (concatMap (\(Args a) -> a) listOfArgs)
-- SIMPLE ARGS
{-|-}
noArgs :: Args ()
noArgs =
exactly (args ())
{-|-}
required :: Parser a -> Args a
required parser =
require1 id parser
{-|-}
optional :: Parser a -> Args (Maybe a)
optional parser =
args id ? parser
{-|-}
zeroOrMore :: Parser a -> Args [a]
zeroOrMore parser =
args id ... parser
{-|-}
oneOrMore :: Parser a -> Args (a, [a])
oneOrMore parser =
args (,) ! parser ... parser
{-|-}
require0 :: args -> Args args
require0 value =
exactly (args value)
{-|-}
require1 :: (a -> args) -> Parser a -> Args args
require1 func a =
exactly (args func ! a)
{-|-}
require2 :: (a -> b -> args) -> Parser a -> Parser b -> Args args
require2 func a b =
exactly (args func ! a ! b)
{-|-}
require3 :: (a -> b -> c -> args) -> Parser a -> Parser b -> Parser c -> Args args
require3 func a b c =
exactly (args func ! a ! b ! c)
{-|-}
require4 :: (a -> b -> c -> d -> args) -> Parser a -> Parser b -> Parser c -> Parser d -> Args args
require4 func a b c d =
exactly (args func ! a ! b ! c ! d)
{-|-}
require5 :: (a -> b -> c -> d -> e -> args) -> Parser a -> Parser b -> Parser c -> Parser d -> Parser e -> Args args
require5 func a b c d e =
exactly (args func ! a ! b ! c ! d ! e)
-- SUGGEST FILES
| Helper for creating custom ` Parser ` values . It will suggest directories and
file names :
suggestFiles [ ] -- suggests any file
suggestFiles [ " elm " ] -- suggests only .elm files
suggestFiles [ " js","html " ] -- suggests only .js and .html files
Notice that you can limit the suggestion by the file extension ! If you need
something more elaborate , you can implement a function like this yourself that
does whatever you need !
file names:
suggestFiles [] -- suggests any file
suggestFiles ["elm"] -- suggests only .elm files
suggestFiles ["js","html"] -- suggests only .js and .html files
Notice that you can limit the suggestion by the file extension! If you need
something more elaborate, you can implement a function like this yourself that
does whatever you need!
-}
_suggestFiles :: [String] -> String -> IO [String]
_suggestFiles extensions string =
let
(dir, start) =
FP.splitFileName string
in
do content <- Dir.getDirectoryContents dir
Maybe.catMaybes
<$> traverse (isPossibleSuggestion extensions start dir) content
isPossibleSuggestion :: [String] -> String -> FilePath -> FilePath -> IO (Maybe FilePath)
isPossibleSuggestion extensions start dir path =
if List.isPrefixOf start path then
do isDir <- Dir.doesDirectoryExist (dir </> path)
return $
if isDir then
Just (path ++ "/")
else if isOkayExtension path extensions then
Just path
else
Nothing
else
return Nothing
isOkayExtension :: FilePath -> [String] -> Bool
isOkayExtension path extensions =
null extensions || elem (FP.takeExtension path) extensions
| null | https://raw.githubusercontent.com/drathier/elm-offline/f562198cac29f4cda15b69fde7e66edde89b34fa/ui/terminal/src/Terminal/Args.hs | haskell | )
GET
AUTO-COMPLETE
|
|
|
) :: Flags (a -> b) -> Flag a -> Flags b
) =
FLAG
|
|
FANCY ARGS
|
|
|
|
|
|
SIMPLE ARGS
|
|
|
|
|
|
|
|
|
|
|
SUGGEST FILES
suggests any file
suggests only .elm files
suggests only .js and .html files
suggests any file
suggests only .elm files
suggests only .js and .html files | module Terminal.Args
( simple
, Interface(..)
, Summary(..)
, complex
, Flag, flag, onOff
, Parser(..)
, Args, noArgs, required, optional, zeroOrMore, oneOrMore, oneOf
, require0, require1, require2, require3, require4, require5
, RequiredArgs, args, exactly, (!), (?), (...)
)
where
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified System.Directory as Dir
import qualified System.Environment as Env
import qualified System.Exit as Exit
import qualified System.FilePath as FP
import System.FilePath ((</>))
import System.IO (hPutStr, hPutStrLn, stdout)
import qualified Text.PrettyPrint.ANSI.Leijen as P
import qualified Text.Read as Read
import qualified Elm.Compiler as Compiler
import qualified Elm.Package as Pkg
import Terminal.Args.Internal
import qualified Terminal.Args.Chomp as Chomp
import qualified Terminal.Args.Error as Error
simple :: String -> P.Doc -> Args args -> Flags flags -> (args -> flags -> IO ()) -> IO ()
simple details example args_ flags_ callback =
do argStrings <- Env.getArgs
case argStrings of
["--version"] ->
do hPutStrLn stdout (Pkg.versionToString Compiler.version)
Exit.exitSuccess
chunks ->
if elem "--help" chunks then
Error.exitWithHelp Nothing details example args_ flags_
else
case snd $ Chomp.chomp Nothing chunks args_ flags_ of
Right (argsValue, flagValue) ->
callback argsValue flagValue
Left err ->
Error.exitWithError err
complex :: P.Doc -> P.Doc -> [Interface] -> IO ()
complex intro outro interfaces =
do argStrings <- Env.getArgs
case argStrings of
[] ->
Error.exitWithOverview intro outro interfaces
["--help"] ->
Error.exitWithOverview intro outro interfaces
["--version"] ->
do hPutStrLn stdout (Pkg.versionToString Compiler.version)
Exit.exitSuccess
command : chunks ->
do case List.find (\iface -> toName iface == command) interfaces of
Nothing ->
Error.exitWithUnknown command (map toName interfaces)
Just (Interface _ _ details example args_ flags_ callback) ->
if elem "--help" chunks then
Error.exitWithHelp (Just command) details example args_ flags_
else
case snd $ Chomp.chomp Nothing chunks args_ flags_ of
Right (argsValue, flagValue) ->
callback argsValue flagValue
Left err ->
Error.exitWithError err
_maybeAutoComplete :: [String] -> (Int -> [String] -> IO [String]) -> IO ()
_maybeAutoComplete argStrings getSuggestions =
if length argStrings /= 3 then
return ()
else
do maybeLine <- Env.lookupEnv "COMP_LINE"
case maybeLine of
Nothing ->
return ()
Just line ->
do (index, chunks) <- getCompIndex line
suggestions <- getSuggestions index chunks
hPutStr stdout (unlines suggestions)
Exit.exitFailure
getCompIndex :: String -> IO (Int, [String])
getCompIndex line =
do maybePoint <- Env.lookupEnv "COMP_POINT"
case Read.readMaybe =<< maybePoint of
Nothing ->
do let chunks = words line
return (length chunks, chunks)
Just point ->
let
groups = List.groupBy grouper (zip line [0..])
rawChunks = drop 1 (filter (all (not . isSpace . fst)) groups)
in
return
( findIndex 1 point rawChunks
, map (map fst) rawChunks
)
grouper :: (Char, Int) -> (Char, Int) -> Bool
grouper (c1, _) (c2, _) =
isSpace c1 == isSpace c2
isSpace :: Char -> Bool
isSpace char =
char == ' ' || char == '\t' || char == '\n'
findIndex :: Int -> Int -> [[(Char,Int)]] -> Int
findIndex index point chunks =
case chunks of
[] ->
index
chunk:cs ->
let
lo = snd (head chunk)
hi = snd (last chunk)
in
if point < lo then
0
else if point <= hi + 1 then
index
else
findIndex (index + 1) point cs
_complexSuggest :: [Interface] -> Int -> [String] -> IO [String]
_complexSuggest interfaces index strings =
case strings of
[] ->
return (map toName interfaces)
command : chunks ->
if index == 1 then
return (filter (List.isPrefixOf command) (map toName interfaces))
else
case List.find (\iface -> toName iface == command) interfaces of
Nothing ->
return []
Just (Interface _ _ _ _ args_ flags_ _) ->
fst $ Chomp.chomp (Just (index-1)) chunks args_ flags_
noFlags :: Flags ()
noFlags =
FDone ()
flags :: a -> Flags a
flags =
FDone
FMore
flag :: String -> Parser a -> String -> Flag (Maybe a)
flag =
Flag
onOff :: String -> String -> Flag Bool
onOff =
OnOff
args :: a -> RequiredArgs a
args =
Done
exactly :: RequiredArgs a -> Args a
exactly requiredArgs =
Args [Exactly requiredArgs]
(!) :: RequiredArgs (a -> b) -> Parser a -> RequiredArgs b
(!) =
Required
(?) :: RequiredArgs (Maybe a -> b) -> Parser a -> Args b
(?) requiredArgs optionalArg =
Args [Optional requiredArgs optionalArg]
(...) :: RequiredArgs ([a] -> b) -> Parser a -> Args b
(...) requiredArgs repeatedArg =
Args [Multiple requiredArgs repeatedArg]
oneOf :: [Args a] -> Args a
oneOf listOfArgs =
Args (concatMap (\(Args a) -> a) listOfArgs)
noArgs :: Args ()
noArgs =
exactly (args ())
required :: Parser a -> Args a
required parser =
require1 id parser
optional :: Parser a -> Args (Maybe a)
optional parser =
args id ? parser
zeroOrMore :: Parser a -> Args [a]
zeroOrMore parser =
args id ... parser
oneOrMore :: Parser a -> Args (a, [a])
oneOrMore parser =
args (,) ! parser ... parser
require0 :: args -> Args args
require0 value =
exactly (args value)
require1 :: (a -> args) -> Parser a -> Args args
require1 func a =
exactly (args func ! a)
require2 :: (a -> b -> args) -> Parser a -> Parser b -> Args args
require2 func a b =
exactly (args func ! a ! b)
require3 :: (a -> b -> c -> args) -> Parser a -> Parser b -> Parser c -> Args args
require3 func a b c =
exactly (args func ! a ! b ! c)
require4 :: (a -> b -> c -> d -> args) -> Parser a -> Parser b -> Parser c -> Parser d -> Args args
require4 func a b c d =
exactly (args func ! a ! b ! c ! d)
require5 :: (a -> b -> c -> d -> e -> args) -> Parser a -> Parser b -> Parser c -> Parser d -> Parser e -> Args args
require5 func a b c d e =
exactly (args func ! a ! b ! c ! d ! e)
| Helper for creating custom ` Parser ` values . It will suggest directories and
file names :
Notice that you can limit the suggestion by the file extension ! If you need
something more elaborate , you can implement a function like this yourself that
does whatever you need !
file names:
Notice that you can limit the suggestion by the file extension! If you need
something more elaborate, you can implement a function like this yourself that
does whatever you need!
-}
_suggestFiles :: [String] -> String -> IO [String]
_suggestFiles extensions string =
let
(dir, start) =
FP.splitFileName string
in
do content <- Dir.getDirectoryContents dir
Maybe.catMaybes
<$> traverse (isPossibleSuggestion extensions start dir) content
isPossibleSuggestion :: [String] -> String -> FilePath -> FilePath -> IO (Maybe FilePath)
isPossibleSuggestion extensions start dir path =
if List.isPrefixOf start path then
do isDir <- Dir.doesDirectoryExist (dir </> path)
return $
if isDir then
Just (path ++ "/")
else if isOkayExtension path extensions then
Just path
else
Nothing
else
return Nothing
isOkayExtension :: FilePath -> [String] -> Bool
isOkayExtension path extensions =
null extensions || elem (FP.takeExtension path) extensions
|
ca6e4f704d5bd333c56a6000265d19934914a44f0ba806b78c10712a154deffb | AccelerationNet/buildnode | buildnode.lisp | (in-package :net.acceleration.buildnode)
(cl-interpol:enable-interpol-syntax)
;;;; Common string util, stoplen from adwutils
(defparameter +common-white-space-trimbag+
'(#\space #\newline #\return #\tab
#\u00A0 ;; this is #\no-break_space
))
(defun trim-whitespace (s)
(string-trim +common-white-space-trimbag+ s))
(defmacro trim-and-nullify! (&rest places)
`(setf
,@(iter (for p in places)
(collect p) (collect `(trim-and-nullify ,p)))))
(defun trim-and-nullify (s)
"trims the whitespace from a string returning nil
if trimming produces an empty string or the string 'nil' "
(typecase s
(null nil)
(list (mapcar #'trim-and-nullify s))
(string
(let ((s (trim-whitespace s)))
(cond ((zerop (length s)) nil)
((string-equal s "nil") nil)
(T s))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar *document* ()
"A variable that holds the current document that is being built. see
with-document.")
(defmacro eval-always (&body body)
`(eval-when (:compile-toplevel :load-toplevel :execute),@body))
(defun flatten-children (kids &optional (doc *document*))
"Handles flattening nested lists and vectors of nodes
into a single flat list of children
"
(iter (for kid in (alexandria:ensure-list kids))
(typecase kid
(string (collecting (if doc
(dom:create-text-node doc kid)
kid)))
((or dom:element dom:node) (collecting kid))
(list (nconcing (flatten-children kid doc)))
(vector (nconcing
(flatten-children
(iter (for sub-kid in-sequence kid) (collect sub-kid))
doc)))
(T (collecting (let ((it (princ-to-string kid)))
(if doc
(dom:create-text-node doc it)
it)))))))
(defun %merge-conts (&rest conts)
"Takes many continuations and makes a single continuation that
iterates through each of the arguments in turn"
(setf conts (remove-if #'null conts))
(when conts
(lambda ()
(let ((rest (rest conts)))
(multiple-value-bind (item new-cont) (funcall (first conts))
(when new-cont (push new-cont rest))
(values item (when rest
(apply #'%merge-conts rest))))))))
(defun %walk-dom-cont (tree)
"calls this on a dom tree (or tree list) and you get back
a node and a continuation function.
repeated calls to the continuation each return the next node
and the next walker continuation
"
(typecase tree
(null nil)
((or vector list)
(when (plusp (length tree))
(multiple-value-bind (item cont) (%walk-dom-cont (elt tree 0) )
(values
item (%merge-conts
cont (lambda () (%walk-dom-cont (subseq tree 1))))))))
(dom:document (%walk-dom-cont (dom:child-nodes tree)))
(dom:text tree)
(dom:element
(values
tree
(when (> (length (dom:child-nodes tree)) 0)
(lambda () (%walk-dom-cont (dom:child-nodes tree) )))))))
(defun depth-first-nodes (tree)
"get a list of the nodes in a depth first traversal of the dom trees"
(iter
(with cont = (lambda () (%walk-dom-cont tree)))
(if cont
(multiple-value-bind (item new-cont) (funcall cont)
(when item (collect item))
(setf cont new-cont))
(terminate))))
(iterate:defmacro-driver (FOR node in-dom tree)
"A driver that will walk over every node in a set of dom trees"
(let ((kwd (if generate 'generate 'for))
(cont (gensym "CONT-"))
(new-cont (gensym "NEW-CONT-"))
(genned-node (gensym "GENNED-NODE-")))
`(progn
(with ,cont = (lambda () (%walk-dom-cont ,tree)))
(,kwd ,node next
(if (null ,cont)
(terminate)
(multiple-value-bind (,genned-node ,new-cont) (funcall ,cont)
(setf ,cont ,new-cont)
,genned-node)))
(unless ,node (next-iteration)))))
(iterate:defmacro-driver (FOR parent in-dom-parents node)
"A driver that will return each parent node up from a starting node
until we get to a null parent"
(let ((kwd (if generate 'generate 'for)))
`(progn
;; (with ,cont = (lambda () (%walk-dom-cont ,tree)))
(,kwd ,parent next
(if (first-iteration-p)
(dom:parent-node ,node)
(if (null ,parent)
(terminate)
(dom:parent-node ,parent))))
(unless ,parent (next-iteration)))))
(iterate:defmacro-driver (FOR kid in-dom-children nodes)
"iterates over the children of a dom node as per flatten-children"
(let ((kwd (if generate 'generate 'for))
(nl (gensym "NL-")))
`(progn
(with ,nl =
(flatten-children
(typecase ,nodes
((or dom:element dom:document) (dom:child-nodes ,nodes))
((or list vector) ,nodes))))
(,kwd ,kid in ,nl))))
(defun xmls-to-dom-snippet ( sxml &key
(namespace ""))
"Given a snippet of xmls, return a new dom snippet of that content"
(etypecase sxml
(string sxml)
(list (destructuring-bind (tagname attrs . kids) sxml
(create-complete-element
*document* namespace
tagname
(iter (for (k v) in attrs) (collect k) (collect v))
(loop for node in kids
collecting
(xmls-to-dom-snippet node :namespace namespace)))))))
(defparameter *xhtml1-transitional-extid*
(let ((xhtml1-transitional.dtd
(asdf:system-relative-pathname
:buildnode "src/xhtml1-transitional.dtd")))
(cxml:make-extid
"-//W3C//DTD XHTML 1.0 Transitional//EN"
(puri:uri
(cl-ppcre:regex-replace-all
" "
#?|file://${xhtml1-transitional.dtd}|
"%20")))))
(defgeneric text-of-dom-snippet (el &optional splice stream)
(:documentation
"get all of the textnodes of a dom:element and return that string
with splice between each character")
(:method (el &optional splice stream)
(flet ((body (s)
(iter
(with has-written = nil )
(for node in-dom el)
(when (dom:text-node-p node)
(when (and has-written splice)
(princ splice s))
(princ (dom:data node) s)
(setf has-written T)
))))
(if stream
(body stream)
(with-output-to-string (stream)
(body stream))))))
(defun join-text (text &key delimiter)
"Like joins trees of lists strings and dom nodes into a single string possibly with a delimiter
ignores nil and empty string"
(collectors:with-string-builder-output
(%collect :delimiter delimiter)
(labels ((collect (s)
(typecase s
(null)
(list (collector s))
((or string number symbol) (%collect s))
(dom:node (%collect (buildnode:text-of-dom-snippet s)))))
(collector (items)
(mapcar #'collect (alexandria:ensure-list items))))
(collector text))))
(defclass scoped-dom-builder (rune-dom::dom-builder)
()
(:documentation
"A dom builder that builds inside of another dom-node"))
(defmethod sax:start-document ((db scoped-dom-builder)))
(defmethod sax:end-document ((db scoped-dom-builder))
(rune-dom::document db))
(defmethod sax:unescaped ((builder scoped-dom-builder) data)
I have no idea how to handle unescaped content in a dom ( which is
;; probably why this was not implemented on dom-builder)
;; we will just make a text node of it for now :/
;; other thoughts would be a processing instruction or something
(buildnode:add-children
(first (rune-dom::element-stack builder))
(dom:create-text-node *document* data))
(values))
;;;; I think we might be able to use this as a dom-builder for a more efficient
;;;; version of the inner-html function
(defun make-scoped-dom-builder (node)
"Returns a new scoped dom builder, scoped to the passed in node.
Nodes built with this builder will be added to the passed in node"
(let ((builder (make-instance 'scoped-dom-builder)))
(setf (rune-dom::document builder) (etypecase node
(dom:document node)
(dom:node (dom:owner-document node)))
(rune-dom::element-stack builder) (list node))
builder))
(defclass html-whitespace-remover (cxml:sax-proxy)
()
(:documentation "a stream filter to remove nodes that are entirely whitespace"))
(defmethod sax:characters ((handler html-whitespace-remover) data)
(unless (every #'cxml::white-space-rune-p (cxml::rod data)) (call-next-method)))
(defun insert-html-string (string &key
(tag "div")
(namespace-uri "")
(dtd nil)
(remove-whitespace? t))
"Parses a string containing a well formed html snippet
into dom nodes inside of a newly created node.
(Based loosely around the idea of setting the javascript innerHTML property)
Will wrap the input in a tag (which is neccessary from CXMLs perspective)
can validate the html against a DTD if one is passed, can use
*xhtml1-transitional-extid* for example.
"
(handler-bind ((warning #'(lambda (condition)
(declare (ignore condition))
(muffle-warning))))
(let ((node (dom:create-element *document* tag)))
(cxml:parse #?|<${tag} xmlns="${ namespace-uri }">${string}</${tag}>|
(if remove-whitespace?
(make-instance 'html-whitespace-remover
:chained-handler (make-scoped-dom-builder node))
(make-scoped-dom-builder node))
:dtd dtd)
(dom:first-child node))))
(defun inner-html (string &optional (tag "div")
(namespace-uri "")
(dtd nil)
(remove-whitespace? t))
(insert-html-string
string :tag tag :namespace-uri namespace-uri :dtd dtd
:remove-whitespace? remove-whitespace?))
(defun document-of (el)
"Returns the document of a given node (or the document if passed in)"
(if (typep el 'rune-dom::document)
el
(dom:owner-document el)))
(defun add-children (elem &rest kids
&aux
(list? (listp elem))
(doc (document-of (if list? (first elem) elem)))
(elem-list (alexandria:ensure-list elem)))
"adds some kids to an element and return that element
alias for append-nodes"
(iter (for kid in (flatten-children kids doc))
(when list?
(setf kid (dom:clone-node kid T)))
(iter (for e in elem-list)
(dom:append-child e kid)))
elem)
(defun insert-children (elem idx &rest kids)
" insert a bunch of dom-nodes (kids) to the location specified
alias for insert-nodes"
(setf kids (flatten-children kids (document-of elem)))
(if (<= (length (dom:child-nodes elem)) idx )
(apply #'add-children elem kids)
(let ((after (elt (dom:child-nodes elem) idx)))
(iter (for k in kids)
(dom:insert-before elem k after))))
elem)
(defun append-nodes (to-location &rest chillins)
"appends a bunch of dom-nodes (chillins) to the location specified
alias of add-children"
(apply #'add-children to-location chillins))
(defun insert-nodes (to-location index &rest chillins)
"insert a bunch of dom-nodes (chillins) to the location specified
alias of insert-children"
(apply #'insert-children to-location index chillins))
(defvar *html-compatibility-mode* nil)
(defvar *cdata-script-blocks* T "Should script blocks have a cdata?")
(defvar *namespace-prefix-map*
'(("" . "xul")
("" . "xhtml")))
(defun get-prefix (namespace &optional (namespace-prefix-map
*namespace-prefix-map*))
(when namespace-prefix-map
(the (or null string)
(cdr (assoc namespace namespace-prefix-map :test #'string=)))))
(defun get-namespace-from-prefix (prefix &optional (namespace-prefix-map
*namespace-prefix-map*))
(when namespace-prefix-map
(the (or null string)
(car (find prefix namespace-prefix-map :key #'cdr :test #'string=)))))
(defun calc-complete-tagname (namespace base-tag namespace-prefix-map)
(let ((prefix
(and namespace-prefix-map
(not (cxml::split-qname base-tag)) ;not already a prefix
(let ((prefix (get-prefix namespace namespace-prefix-map)))
;;found the given namespace in the map
(when (and prefix (> (length (the string prefix)) 0))
prefix)))))
(if prefix
#?"${prefix}:${base-tag}"
base-tag)))
(defun prepare-attribute-name (attribute)
"Prepares an attribute name for output to html by coercing to strings"
(etypecase attribute
(symbol (coerce (string-downcase attribute)
'(simple-array character (*))))
(string attribute)))
(defun prepare-attribute-value (value)
"prepares a value for html out put by coercing to a string"
(typecase value
(string value)
(symbol (string-downcase (symbol-name value)))
(T (princ-to-string value))))
(defun attribute-uri (attribute)
(typecase attribute
(symbol nil)
(string
(let ((list (cl-ppcre:split ":" attribute)))
(case (length list)
(2 (get-namespace-from-prefix (first list)))
((0 1) nil)
(T (error "Couldnt parse attribute-name ~a into prefix and name" attribute)))))))
(defgeneric get-attribute (elem attribute)
(:documentation
"Gets the value of an attribute on an element
if the attribute does not exist return nil
")
(:method (elem attribute)
(when elem
(let ((args (list elem
(attribute-uri attribute)
(prepare-attribute-name attribute))))
(when (apply #'dom:has-attribute-ns args)
(apply #'dom:get-attribute-ns args))))))
(defgeneric set-attribute (elem attribute value)
(:documentation "Sets an attribute and passes the elem through, returns the elem. If value is nil, removes the attribute")
(:method (elem attribute value)
(iter
(with attr = (prepare-attribute-name attribute))
(for e in (alexandria:ensure-list elem))
(if value
(dom:set-attribute-ns e (attribute-uri attribute)
attr (prepare-attribute-value value))
(alexandria:when-let ((it (dom:get-attribute-node e attr)))
(dom:remove-attribute-node e it))))
elem))
(defgeneric remove-attribute (elem attribute)
(:documentation
"removes an attribute and passes the elem through, returns the elem
If the attribute does not exist, simply skip it
")
(:method (elem attribute)
;; throws errors to remove attributes that dont exist
;; dont care about that
(iter (for e in (alexandria:ensure-list elem))
(let ((uri (attribute-uri attribute))
(name (prepare-attribute-name attribute)))
(when (dom:has-attribute-ns e uri name)
(dom:remove-attribute-ns e uri name))))
elem))
(defun remove-attributes (elem &rest attributes)
"removes an attribute and passes the elem through, returns the elem"
(iter (for attr in attributes)
(remove-attribute elem attr))
elem)
(defgeneric css-classes ( o )
(:documentation
"Returns a list of css classes (space separated names in the 'class' attribute)")
(:method (o)
(etypecase o
(null)
(string (split-sequence:split-sequence #\space o :remove-empty-subseqs t))
(dom:element (css-classes (get-attribute o :class))))))
(defun add-css-class-helper (&rest new-classes)
(sort
(remove-duplicates
(collectors:with-appender-output (them)
(labels ((%help (it)
(typecase it
(null nil)
(string
(trim-and-nullify! it)
(when it
(them (cl-ppcre:split #?r"\s+" it))))
(list (mapc #'%help it)))))
(%help new-classes)))
:test #'string=)
#'string-lessp))
(defgeneric add-css-class (element new-class)
(:documentation
"Adds a new css class to the element and returns the element")
(:method ((el dom:element) new-class)
(trim-and-nullify! new-class)
(when new-class
(set-attribute
el :class
(format nil "~{~a~^ ~}"
(add-css-class-helper (get-attribute el :class) new-class))))
el))
(defgeneric add-css-classes (comp &rest classes)
(:method (comp &rest classes)
(declare (dynamic-extent classes))
(add-css-class comp classes)
comp))
(defgeneric remove-css-class (el new-class)
(:documentation "Removes a css class from the elements and returns the element")
(:method ((el dom:element) new-class)
(let* ((class-string (get-attribute el :class))
(regex #?r"(?:$|^|\s)*${new-class}(?:$|^|\s)*")
(new-class-string (trim-and-nullify (cl-ppcre:regex-replace-all regex class-string " "))))
(if new-class-string
(set-attribute el :class new-class-string)
(remove-attribute el :class))
el)))
(defgeneric remove-css-classes ( comp &rest classes)
(:method (comp &rest classes)
(declare (dynamic-extent classes))
(iter (for class in classes) (remove-css-class comp class))
comp))
(defun push-new-attribute (elem attribute value)
"if the attribute is not on the element then put it there with the specified value,
returns the elem and whether or not the attribute was set"
(values elem
(when (null (get-attribute elem attribute))
(set-attribute elem attribute value)
T)))
(defun push-new-attributes (elem &rest attribute-p-list)
"for each attribute in the plist push-new into the attributes list of the elem, returns the elem"
(iter (for (attr val) on attribute-p-list by #'cddr)
(push-new-attribute elem attr val))
elem)
(defun set-attributes (elem &rest attribute-p-list)
"set-attribute for each attribute specified in the plist, returns the elem"
(iter (for (attr val) on attribute-p-list by #'cddr)
(set-attribute elem attr val))
elem)
(defun create-complete-element (document namespace tagname attributes children
&optional
(namespace-prefix-map *namespace-prefix-map*))
"Creates an xml element out of all the necessary components.
If the tagname does not contain a prefix, then one is added based on the namespace-prefix map."
(declare (type list attributes))
;;if we don't already have a prefix and we do find one in the map.
(let* ((tagname (if namespace-prefix-map
(calc-complete-tagname namespace tagname namespace-prefix-map)
tagname))
(elem (dom:create-element-ns document namespace tagname)))
(when (oddp (length attributes))
(error "Incomplete attribute-value list. Odd number of elements in ~a" attributes))
(apply #'set-attributes elem attributes)
;;append the children to the element.
(append-nodes elem children)
elem))
(defun write-normalized-document-to-sink (document stream-sink)
"writes a cxml:dom document to the given stream-sink,
passing the document through a namespace normalizer first, and
possibly a html-compatibility-sink if *html-compatibility-mode* is set"
(dom-walk
(cxml:make-namespace-normalizer stream-sink)
document
:include-doctype :canonical-notations))
HACK to make CHTML output html5 style doctypes
(defclass html5-capable-character-output-sink (chtml::sink)
())
(defun html5-capable-character-output-sink (stream &key canonical indentation encoding)
(declare (ignore canonical indentation))
(let ((encoding (or encoding "UTF-8"))
(ystream #+rune-is-character
(chtml::make-character-stream-ystream stream)
#-rune-is-character
(chtml::make-character-stream-ystream/utf8 stream)
))
(setf (chtml::ystream-encoding ystream)
(runes:find-output-encoding encoding))
(make-instance 'html5-capable-character-output-sink
:ystream ystream
:encoding encoding)))
(defmethod hax:start-document ((sink html5-capable-character-output-sink) name public-id system-id)
(closure-html::sink-write-rod #"<!DOCTYPE " sink)
(closure-html::sink-write-rod name sink)
(cond
((plusp (length public-id))
(closure-html::sink-write-rod #" PUBLIC \"" sink)
(closure-html::unparse-string public-id sink)
(closure-html::sink-write-rod #"\" \"" sink)
(closure-html::unparse-string system-id sink)
(closure-html::sink-write-rod #"\"" sink))
((plusp (length system-id))
(closure-html::sink-write-rod #" SYSTEM \"" sink)
(closure-html::unparse-string system-id sink)
(closure-html::sink-write-rod #"\"" sink)))
(closure-html::sink-write-rod #">" sink)
(closure-html::sink-write-rune #/U+000A sink))
(defun make-output-sink (stream &key canonical indentation (char-p T))
(apply
(cond
((and char-p *html-compatibility-mode*)
#'html5-capable-character-output-sink)
((and (not char-p) *html-compatibility-mode*)
#'chtml:make-octet-stream-sink)
((and char-p (not *html-compatibility-mode*))
#'cxml:make-character-stream-sink)
((and (not char-p) (not *html-compatibility-mode*))
#'cxml:make-octet-stream-sink))
stream
(unless *html-compatibility-mode*
(list :canonical canonical :indentation indentation))))
(defun write-document-to-character-stream (document char-stream)
"writes a cxml:dom document to a character stream"
(let ((sink (make-output-sink char-stream)))
(write-normalized-document-to-sink document sink)))
(defun write-document-to-octet-stream (document octet-stream)
"writes a cxml:dom document to a character stream"
(let ((sink (make-output-sink octet-stream :char-p nil)))
(write-normalized-document-to-sink document sink)))
(defgeneric html-output? (doc)
(:method (doc)
(let ((dt (dom:doctype doc)))
(or *html-compatibility-mode*
(and
dt
(string-equal "html" (dom:name dt))
(not (search "xhtml" (dom:system-id dt) :test #'string-equal)))))))
(defun write-document (document &optional (out-stream *standard-output*))
"Write the document to the designated out-stream, or *standard-ouput* by default."
(let ((*html-compatibility-mode* (html-output? document)))
(case (stream-element-type out-stream)
('character (write-document-to-character-stream document out-stream))
(otherwise (write-document-to-octet-stream document out-stream)))))
(defmacro with-document (&body chillins)
"(with-document ( a bunch of child nodes of the document )) --> cxml:dom document
Creates an environment in which the special variable *document* is available
a document is necessary to create dom nodes and the document the nodes end up on
must be the document on which they were created. At the end of the form, the
complete document is returned"
`(let ((*document* (cxml-dom:create-document)))
(append-nodes *document* ,@chillins)
*document*))
(defmacro with-document-to-file (filename &body chillins)
"Creates a document block with-document upon which to add the chillins (southern for children).
When the document is complete, it is written out to the specified file."
`(write-doc-to-file (with-document ,@chillins) ,filename))
(defun write-doc-to-file (doc filename)
"Binary write-out a document. will create/overwrite any existing file named the same."
(let ((filename (merge-pathnames filename)) )
(with-open-stream (fd (open filename :direction :output :element-type '(unsigned-byte 8)
:if-does-not-exist :create
:if-exists :supersede))
(write-document doc fd))
(values doc filename)))
(defun document-to-string (doc)
"Return a string representation of a document."
(with-output-to-string (fd)
(write-document doc fd)))
(defmacro with-xhtml-document (&body chillins)
"(with-xhtml-document ( a bunch of child nodes of the document )) --> cxml:dom document
Creates an environment in which the special variable *document* is available
a document is necessary to create dom nodes and the document the nodes end up on
must be the document on which they were created. At the end of the form, the
complete document is returned.
This sets the doctype to be xhtml transitional."
`(let ((*cdata-script-blocks* T)
(*document* (dom:create-document
'rune-dom:implementation
nil nil
(dom:create-document-type
'rune-dom:implementation
"html"
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"-transitional.dtd"))))
(append-nodes *document* ,@chillins)
*document*))
(defmacro with-xhtml-frameset-document (&body chillins)
"(with-xhtml-document ( a bunch of child nodes of the document )) --> cxml:dom document
Creates an environment in which the special variable *document* is available
a document is necessary to create dom nodes and the document the nodes end up on
must be the document on which they were created. At the end of the form, the
complete document is returned.
This sets the doctype to be xhtml transitional."
`(let ((*document* (dom:create-document
'rune-dom:implementation
nil nil
(dom:create-document-type
'rune-dom:implementation
"html"
"-//W3C//DTD XHTML 1.0 Frameset//EN"
"-frameset.dtd"))))
(append-nodes *document* ,@chillins)
*document*))
(defmacro with-xhtml-document-to-file (filename &body chillins)
"Creates a document block with-document upon which to add the chillins (southern for children). When the document is complete, it is written out to the specified file."
`(write-doc-to-file (with-xhtml-document ,@chillins) ,filename))
(defmacro with-html-document-to-file ((filename) &body body)
"Creates an html-document, writes out the results to filename"
`(let ((*html-compatibility-mode* T))
(write-doc-to-file (with-html-document ,@body)
,filename)))
(defmacro with-html-document (&body body)
"(with-html-document ( a bunch of child nodes of the document )) --> cxml:dom document
Creates an environment in which the special variable *document* is available
a document is necessary to create dom nodes and the document the nodes end up on
must be the document on which they were created. At the end of the form, the
complete document is returned.
This sets the doctype to be html 4.01 strict."
`(let ((*namespace-prefix-map* nil)
(*document* (dom:create-document
'rune-dom:implementation
nil nil
(dom:create-document-type
'rune-dom:implementation
"html"
"-//W3C//DTD HTML 4.01//EN"
"")
))
(*html-compatibility-mode* T)
(*cdata-script-blocks* nil))
(declare (special *document*))
(append-nodes *document* ,@body)
*document*))
(defmacro with-html5-document-to-file ((filename) &body body)
"Creates an html-document, writes out the results to filename"
`(let ((*html-compatibility-mode* T))
(write-doc-to-file (with-html5-document ,@body)
,filename)))
(defmacro with-html5-document (&body body)
"(with-html5-document ( a bunch of child nodes of the document )) --> cxml:dom document
Creates an environment in which the special variable *document* is available
a document is necessary to create dom nodes and the document the nodes end up on
must be the document on which they were created. At the end of the form, the
complete document is returned.
This sets the doctype to be html5 compatible <!DOCTYPE html>."
`(let ((*namespace-prefix-map* nil)
(*document* (dom:create-document
'rune-dom:implementation
nil nil
(dom:create-document-type
'rune-dom:implementation
"html"
nil
nil)
))
(*html-compatibility-mode* T)
(*cdata-script-blocks* nil))
(declare (special *document*))
(append-nodes *document* ,@body)
*document*))
(defmacro with-html-document-to-string (() &body body)
"trys to output a string containing all "
`(let ((*html-compatibility-mode* T))
(document-to-string (with-html-document ,@body))))
(defmacro with-html5-document-to-string (() &body body)
"trys to output a string containing all "
`(let ((*html-compatibility-mode* T))
(document-to-string (with-html5-document ,@body))))
(defgeneric remove-all-children (el)
(:method ((it dom:element))
;; should be a touch faster than removing one at a time
(iter (for n in-dom-children it)
(setf (slot-value n 'rune-dom::parent) nil))
(setf (slot-value it 'rune-dom::children) (rune-dom::make-node-list))
it))
(defvar *snippet-output-stream* nil)
(defun %enstream (stream content-fn)
(let* ((old-out-stream *snippet-output-stream*)
(*snippet-output-stream* (or stream (make-string-output-stream )))
(result (multiple-value-list (funcall content-fn))))
(cond
(stream (apply #'values result))
(old-out-stream
(write-string (get-output-stream-string *snippet-output-stream*) old-out-stream))
(t (get-output-stream-string *snippet-output-stream*)))))
(defun %buffer-xml-output (stream sink body-fn)
(let ((cxml::*sink* (or sink (make-character-stream-sink stream)))
(cxml::*current-element* nil)
(cxml::*unparse-namespace-bindings* cxml::*initial-namespace-bindings*)
(cxml::*current-namespace-bindings* nil))
(setf (cxml::sink-omit-xml-declaration-p cxml::*sink*) T)
(sax:start-document cxml::*sink*)
(funcall body-fn)
(sax:end-document cxml::*sink*)))
(defmacro buffer-xml-output ((&optional stream sink) &body body)
"buffers out sax:events to a sting
xml parameters like <param:foo param:type=\"string\"><div>bar</div></param:foo>
are requested to be strings (presumably for string processing)
"
(let ((content `(lambda () (%buffer-xml-output *snippet-output-stream* ,sink (lambda () ,@body)))))
`(%enstream ,stream ,content)))
(defmacro %with-snippet ((type &optional stream sink) &body body)
"helper to define with-html-snippet and with-xhtml-snippet"
(assert (member type '(with-html-document with-html5-document with-xhtml-document)))
(alexandria:with-unique-names (result)
`(let ((*html-compatibility-mode*
',(member type '(with-html-document with-html5-document) ))
,result)
(,type
(progn
(setf
,result
(multiple-value-list
(buffer-xml-output (,stream ,sink)
(let ((content (flatten-children (progn ,@body))))
(iter (for n in content)
(buildnode::dom-walk cxml::*sink* n))))))
nil))
(apply #'values ,result))))
(defmacro with-html-snippet ((&optional stream sink) &body body)
"builds a little piece of html-dom and renders that to a string / stream"
`(%with-snippet (with-html-document ,stream ,sink) ,@body))
(defmacro with-html5-snippet ((&optional stream sink) &body body)
"builds a little piece of html-dom and renders that to a string / stream"
`(%with-snippet (with-html5-document ,stream ,sink) ,@body))
(defmacro with-xhtml-snippet ((&optional stream sink) &body body)
"builds a little piece of xhtml-dom and renders that to a string / stream"
`(%with-snippet (with-xhtml-document ,stream ,sink) ,@body))
| null | https://raw.githubusercontent.com/AccelerationNet/buildnode/c614ead94d00795c1a862f344d45aef52e568e2b/src/buildnode.lisp | lisp | Common string util, stoplen from adwutils
this is #\no-break_space
(with ,cont = (lambda () (%walk-dom-cont ,tree)))
probably why this was not implemented on dom-builder)
we will just make a text node of it for now :/
other thoughts would be a processing instruction or something
I think we might be able to use this as a dom-builder for a more efficient
version of the inner-html function
not already a prefix
found the given namespace in the map
throws errors to remove attributes that dont exist
dont care about that
if we don't already have a prefix and we do find one in the map.
append the children to the element.
should be a touch faster than removing one at a time | (in-package :net.acceleration.buildnode)
(cl-interpol:enable-interpol-syntax)
(defparameter +common-white-space-trimbag+
'(#\space #\newline #\return #\tab
))
(defun trim-whitespace (s)
(string-trim +common-white-space-trimbag+ s))
(defmacro trim-and-nullify! (&rest places)
`(setf
,@(iter (for p in places)
(collect p) (collect `(trim-and-nullify ,p)))))
(defun trim-and-nullify (s)
"trims the whitespace from a string returning nil
if trimming produces an empty string or the string 'nil' "
(typecase s
(null nil)
(list (mapcar #'trim-and-nullify s))
(string
(let ((s (trim-whitespace s)))
(cond ((zerop (length s)) nil)
((string-equal s "nil") nil)
(T s))))))
(defvar *document* ()
"A variable that holds the current document that is being built. see
with-document.")
(defmacro eval-always (&body body)
`(eval-when (:compile-toplevel :load-toplevel :execute),@body))
(defun flatten-children (kids &optional (doc *document*))
"Handles flattening nested lists and vectors of nodes
into a single flat list of children
"
(iter (for kid in (alexandria:ensure-list kids))
(typecase kid
(string (collecting (if doc
(dom:create-text-node doc kid)
kid)))
((or dom:element dom:node) (collecting kid))
(list (nconcing (flatten-children kid doc)))
(vector (nconcing
(flatten-children
(iter (for sub-kid in-sequence kid) (collect sub-kid))
doc)))
(T (collecting (let ((it (princ-to-string kid)))
(if doc
(dom:create-text-node doc it)
it)))))))
(defun %merge-conts (&rest conts)
"Takes many continuations and makes a single continuation that
iterates through each of the arguments in turn"
(setf conts (remove-if #'null conts))
(when conts
(lambda ()
(let ((rest (rest conts)))
(multiple-value-bind (item new-cont) (funcall (first conts))
(when new-cont (push new-cont rest))
(values item (when rest
(apply #'%merge-conts rest))))))))
(defun %walk-dom-cont (tree)
"calls this on a dom tree (or tree list) and you get back
a node and a continuation function.
repeated calls to the continuation each return the next node
and the next walker continuation
"
(typecase tree
(null nil)
((or vector list)
(when (plusp (length tree))
(multiple-value-bind (item cont) (%walk-dom-cont (elt tree 0) )
(values
item (%merge-conts
cont (lambda () (%walk-dom-cont (subseq tree 1))))))))
(dom:document (%walk-dom-cont (dom:child-nodes tree)))
(dom:text tree)
(dom:element
(values
tree
(when (> (length (dom:child-nodes tree)) 0)
(lambda () (%walk-dom-cont (dom:child-nodes tree) )))))))
(defun depth-first-nodes (tree)
"get a list of the nodes in a depth first traversal of the dom trees"
(iter
(with cont = (lambda () (%walk-dom-cont tree)))
(if cont
(multiple-value-bind (item new-cont) (funcall cont)
(when item (collect item))
(setf cont new-cont))
(terminate))))
(iterate:defmacro-driver (FOR node in-dom tree)
"A driver that will walk over every node in a set of dom trees"
(let ((kwd (if generate 'generate 'for))
(cont (gensym "CONT-"))
(new-cont (gensym "NEW-CONT-"))
(genned-node (gensym "GENNED-NODE-")))
`(progn
(with ,cont = (lambda () (%walk-dom-cont ,tree)))
(,kwd ,node next
(if (null ,cont)
(terminate)
(multiple-value-bind (,genned-node ,new-cont) (funcall ,cont)
(setf ,cont ,new-cont)
,genned-node)))
(unless ,node (next-iteration)))))
(iterate:defmacro-driver (FOR parent in-dom-parents node)
"A driver that will return each parent node up from a starting node
until we get to a null parent"
(let ((kwd (if generate 'generate 'for)))
`(progn
(,kwd ,parent next
(if (first-iteration-p)
(dom:parent-node ,node)
(if (null ,parent)
(terminate)
(dom:parent-node ,parent))))
(unless ,parent (next-iteration)))))
(iterate:defmacro-driver (FOR kid in-dom-children nodes)
"iterates over the children of a dom node as per flatten-children"
(let ((kwd (if generate 'generate 'for))
(nl (gensym "NL-")))
`(progn
(with ,nl =
(flatten-children
(typecase ,nodes
((or dom:element dom:document) (dom:child-nodes ,nodes))
((or list vector) ,nodes))))
(,kwd ,kid in ,nl))))
(defun xmls-to-dom-snippet ( sxml &key
(namespace ""))
"Given a snippet of xmls, return a new dom snippet of that content"
(etypecase sxml
(string sxml)
(list (destructuring-bind (tagname attrs . kids) sxml
(create-complete-element
*document* namespace
tagname
(iter (for (k v) in attrs) (collect k) (collect v))
(loop for node in kids
collecting
(xmls-to-dom-snippet node :namespace namespace)))))))
(defparameter *xhtml1-transitional-extid*
(let ((xhtml1-transitional.dtd
(asdf:system-relative-pathname
:buildnode "src/xhtml1-transitional.dtd")))
(cxml:make-extid
"-//W3C//DTD XHTML 1.0 Transitional//EN"
(puri:uri
(cl-ppcre:regex-replace-all
" "
#?|file://${xhtml1-transitional.dtd}|
"%20")))))
(defgeneric text-of-dom-snippet (el &optional splice stream)
(:documentation
"get all of the textnodes of a dom:element and return that string
with splice between each character")
(:method (el &optional splice stream)
(flet ((body (s)
(iter
(with has-written = nil )
(for node in-dom el)
(when (dom:text-node-p node)
(when (and has-written splice)
(princ splice s))
(princ (dom:data node) s)
(setf has-written T)
))))
(if stream
(body stream)
(with-output-to-string (stream)
(body stream))))))
(defun join-text (text &key delimiter)
"Like joins trees of lists strings and dom nodes into a single string possibly with a delimiter
ignores nil and empty string"
(collectors:with-string-builder-output
(%collect :delimiter delimiter)
(labels ((collect (s)
(typecase s
(null)
(list (collector s))
((or string number symbol) (%collect s))
(dom:node (%collect (buildnode:text-of-dom-snippet s)))))
(collector (items)
(mapcar #'collect (alexandria:ensure-list items))))
(collector text))))
(defclass scoped-dom-builder (rune-dom::dom-builder)
()
(:documentation
"A dom builder that builds inside of another dom-node"))
(defmethod sax:start-document ((db scoped-dom-builder)))
(defmethod sax:end-document ((db scoped-dom-builder))
(rune-dom::document db))
(defmethod sax:unescaped ((builder scoped-dom-builder) data)
I have no idea how to handle unescaped content in a dom ( which is
(buildnode:add-children
(first (rune-dom::element-stack builder))
(dom:create-text-node *document* data))
(values))
(defun make-scoped-dom-builder (node)
"Returns a new scoped dom builder, scoped to the passed in node.
Nodes built with this builder will be added to the passed in node"
(let ((builder (make-instance 'scoped-dom-builder)))
(setf (rune-dom::document builder) (etypecase node
(dom:document node)
(dom:node (dom:owner-document node)))
(rune-dom::element-stack builder) (list node))
builder))
(defclass html-whitespace-remover (cxml:sax-proxy)
()
(:documentation "a stream filter to remove nodes that are entirely whitespace"))
(defmethod sax:characters ((handler html-whitespace-remover) data)
(unless (every #'cxml::white-space-rune-p (cxml::rod data)) (call-next-method)))
(defun insert-html-string (string &key
(tag "div")
(namespace-uri "")
(dtd nil)
(remove-whitespace? t))
"Parses a string containing a well formed html snippet
into dom nodes inside of a newly created node.
(Based loosely around the idea of setting the javascript innerHTML property)
Will wrap the input in a tag (which is neccessary from CXMLs perspective)
can validate the html against a DTD if one is passed, can use
*xhtml1-transitional-extid* for example.
"
(handler-bind ((warning #'(lambda (condition)
(declare (ignore condition))
(muffle-warning))))
(let ((node (dom:create-element *document* tag)))
(cxml:parse #?|<${tag} xmlns="${ namespace-uri }">${string}</${tag}>|
(if remove-whitespace?
(make-instance 'html-whitespace-remover
:chained-handler (make-scoped-dom-builder node))
(make-scoped-dom-builder node))
:dtd dtd)
(dom:first-child node))))
(defun inner-html (string &optional (tag "div")
(namespace-uri "")
(dtd nil)
(remove-whitespace? t))
(insert-html-string
string :tag tag :namespace-uri namespace-uri :dtd dtd
:remove-whitespace? remove-whitespace?))
(defun document-of (el)
"Returns the document of a given node (or the document if passed in)"
(if (typep el 'rune-dom::document)
el
(dom:owner-document el)))
(defun add-children (elem &rest kids
&aux
(list? (listp elem))
(doc (document-of (if list? (first elem) elem)))
(elem-list (alexandria:ensure-list elem)))
"adds some kids to an element and return that element
alias for append-nodes"
(iter (for kid in (flatten-children kids doc))
(when list?
(setf kid (dom:clone-node kid T)))
(iter (for e in elem-list)
(dom:append-child e kid)))
elem)
(defun insert-children (elem idx &rest kids)
" insert a bunch of dom-nodes (kids) to the location specified
alias for insert-nodes"
(setf kids (flatten-children kids (document-of elem)))
(if (<= (length (dom:child-nodes elem)) idx )
(apply #'add-children elem kids)
(let ((after (elt (dom:child-nodes elem) idx)))
(iter (for k in kids)
(dom:insert-before elem k after))))
elem)
(defun append-nodes (to-location &rest chillins)
"appends a bunch of dom-nodes (chillins) to the location specified
alias of add-children"
(apply #'add-children to-location chillins))
(defun insert-nodes (to-location index &rest chillins)
"insert a bunch of dom-nodes (chillins) to the location specified
alias of insert-children"
(apply #'insert-children to-location index chillins))
(defvar *html-compatibility-mode* nil)
(defvar *cdata-script-blocks* T "Should script blocks have a cdata?")
(defvar *namespace-prefix-map*
'(("" . "xul")
("" . "xhtml")))
(defun get-prefix (namespace &optional (namespace-prefix-map
*namespace-prefix-map*))
(when namespace-prefix-map
(the (or null string)
(cdr (assoc namespace namespace-prefix-map :test #'string=)))))
(defun get-namespace-from-prefix (prefix &optional (namespace-prefix-map
*namespace-prefix-map*))
(when namespace-prefix-map
(the (or null string)
(car (find prefix namespace-prefix-map :key #'cdr :test #'string=)))))
(defun calc-complete-tagname (namespace base-tag namespace-prefix-map)
(let ((prefix
(and namespace-prefix-map
(let ((prefix (get-prefix namespace namespace-prefix-map)))
(when (and prefix (> (length (the string prefix)) 0))
prefix)))))
(if prefix
#?"${prefix}:${base-tag}"
base-tag)))
(defun prepare-attribute-name (attribute)
"Prepares an attribute name for output to html by coercing to strings"
(etypecase attribute
(symbol (coerce (string-downcase attribute)
'(simple-array character (*))))
(string attribute)))
(defun prepare-attribute-value (value)
"prepares a value for html out put by coercing to a string"
(typecase value
(string value)
(symbol (string-downcase (symbol-name value)))
(T (princ-to-string value))))
(defun attribute-uri (attribute)
(typecase attribute
(symbol nil)
(string
(let ((list (cl-ppcre:split ":" attribute)))
(case (length list)
(2 (get-namespace-from-prefix (first list)))
((0 1) nil)
(T (error "Couldnt parse attribute-name ~a into prefix and name" attribute)))))))
(defgeneric get-attribute (elem attribute)
(:documentation
"Gets the value of an attribute on an element
if the attribute does not exist return nil
")
(:method (elem attribute)
(when elem
(let ((args (list elem
(attribute-uri attribute)
(prepare-attribute-name attribute))))
(when (apply #'dom:has-attribute-ns args)
(apply #'dom:get-attribute-ns args))))))
(defgeneric set-attribute (elem attribute value)
(:documentation "Sets an attribute and passes the elem through, returns the elem. If value is nil, removes the attribute")
(:method (elem attribute value)
(iter
(with attr = (prepare-attribute-name attribute))
(for e in (alexandria:ensure-list elem))
(if value
(dom:set-attribute-ns e (attribute-uri attribute)
attr (prepare-attribute-value value))
(alexandria:when-let ((it (dom:get-attribute-node e attr)))
(dom:remove-attribute-node e it))))
elem))
(defgeneric remove-attribute (elem attribute)
(:documentation
"removes an attribute and passes the elem through, returns the elem
If the attribute does not exist, simply skip it
")
(:method (elem attribute)
(iter (for e in (alexandria:ensure-list elem))
(let ((uri (attribute-uri attribute))
(name (prepare-attribute-name attribute)))
(when (dom:has-attribute-ns e uri name)
(dom:remove-attribute-ns e uri name))))
elem))
(defun remove-attributes (elem &rest attributes)
"removes an attribute and passes the elem through, returns the elem"
(iter (for attr in attributes)
(remove-attribute elem attr))
elem)
(defgeneric css-classes ( o )
(:documentation
"Returns a list of css classes (space separated names in the 'class' attribute)")
(:method (o)
(etypecase o
(null)
(string (split-sequence:split-sequence #\space o :remove-empty-subseqs t))
(dom:element (css-classes (get-attribute o :class))))))
(defun add-css-class-helper (&rest new-classes)
(sort
(remove-duplicates
(collectors:with-appender-output (them)
(labels ((%help (it)
(typecase it
(null nil)
(string
(trim-and-nullify! it)
(when it
(them (cl-ppcre:split #?r"\s+" it))))
(list (mapc #'%help it)))))
(%help new-classes)))
:test #'string=)
#'string-lessp))
(defgeneric add-css-class (element new-class)
(:documentation
"Adds a new css class to the element and returns the element")
(:method ((el dom:element) new-class)
(trim-and-nullify! new-class)
(when new-class
(set-attribute
el :class
(format nil "~{~a~^ ~}"
(add-css-class-helper (get-attribute el :class) new-class))))
el))
(defgeneric add-css-classes (comp &rest classes)
(:method (comp &rest classes)
(declare (dynamic-extent classes))
(add-css-class comp classes)
comp))
(defgeneric remove-css-class (el new-class)
(:documentation "Removes a css class from the elements and returns the element")
(:method ((el dom:element) new-class)
(let* ((class-string (get-attribute el :class))
(regex #?r"(?:$|^|\s)*${new-class}(?:$|^|\s)*")
(new-class-string (trim-and-nullify (cl-ppcre:regex-replace-all regex class-string " "))))
(if new-class-string
(set-attribute el :class new-class-string)
(remove-attribute el :class))
el)))
(defgeneric remove-css-classes ( comp &rest classes)
(:method (comp &rest classes)
(declare (dynamic-extent classes))
(iter (for class in classes) (remove-css-class comp class))
comp))
(defun push-new-attribute (elem attribute value)
"if the attribute is not on the element then put it there with the specified value,
returns the elem and whether or not the attribute was set"
(values elem
(when (null (get-attribute elem attribute))
(set-attribute elem attribute value)
T)))
(defun push-new-attributes (elem &rest attribute-p-list)
"for each attribute in the plist push-new into the attributes list of the elem, returns the elem"
(iter (for (attr val) on attribute-p-list by #'cddr)
(push-new-attribute elem attr val))
elem)
(defun set-attributes (elem &rest attribute-p-list)
"set-attribute for each attribute specified in the plist, returns the elem"
(iter (for (attr val) on attribute-p-list by #'cddr)
(set-attribute elem attr val))
elem)
(defun create-complete-element (document namespace tagname attributes children
&optional
(namespace-prefix-map *namespace-prefix-map*))
"Creates an xml element out of all the necessary components.
If the tagname does not contain a prefix, then one is added based on the namespace-prefix map."
(declare (type list attributes))
(let* ((tagname (if namespace-prefix-map
(calc-complete-tagname namespace tagname namespace-prefix-map)
tagname))
(elem (dom:create-element-ns document namespace tagname)))
(when (oddp (length attributes))
(error "Incomplete attribute-value list. Odd number of elements in ~a" attributes))
(apply #'set-attributes elem attributes)
(append-nodes elem children)
elem))
(defun write-normalized-document-to-sink (document stream-sink)
"writes a cxml:dom document to the given stream-sink,
passing the document through a namespace normalizer first, and
possibly a html-compatibility-sink if *html-compatibility-mode* is set"
(dom-walk
(cxml:make-namespace-normalizer stream-sink)
document
:include-doctype :canonical-notations))
HACK to make CHTML output html5 style doctypes
(defclass html5-capable-character-output-sink (chtml::sink)
())
(defun html5-capable-character-output-sink (stream &key canonical indentation encoding)
(declare (ignore canonical indentation))
(let ((encoding (or encoding "UTF-8"))
(ystream #+rune-is-character
(chtml::make-character-stream-ystream stream)
#-rune-is-character
(chtml::make-character-stream-ystream/utf8 stream)
))
(setf (chtml::ystream-encoding ystream)
(runes:find-output-encoding encoding))
(make-instance 'html5-capable-character-output-sink
:ystream ystream
:encoding encoding)))
(defmethod hax:start-document ((sink html5-capable-character-output-sink) name public-id system-id)
(closure-html::sink-write-rod #"<!DOCTYPE " sink)
(closure-html::sink-write-rod name sink)
(cond
((plusp (length public-id))
(closure-html::sink-write-rod #" PUBLIC \"" sink)
(closure-html::unparse-string public-id sink)
(closure-html::sink-write-rod #"\" \"" sink)
(closure-html::unparse-string system-id sink)
(closure-html::sink-write-rod #"\"" sink))
((plusp (length system-id))
(closure-html::sink-write-rod #" SYSTEM \"" sink)
(closure-html::unparse-string system-id sink)
(closure-html::sink-write-rod #"\"" sink)))
(closure-html::sink-write-rod #">" sink)
(closure-html::sink-write-rune #/U+000A sink))
(defun make-output-sink (stream &key canonical indentation (char-p T))
(apply
(cond
((and char-p *html-compatibility-mode*)
#'html5-capable-character-output-sink)
((and (not char-p) *html-compatibility-mode*)
#'chtml:make-octet-stream-sink)
((and char-p (not *html-compatibility-mode*))
#'cxml:make-character-stream-sink)
((and (not char-p) (not *html-compatibility-mode*))
#'cxml:make-octet-stream-sink))
stream
(unless *html-compatibility-mode*
(list :canonical canonical :indentation indentation))))
(defun write-document-to-character-stream (document char-stream)
"writes a cxml:dom document to a character stream"
(let ((sink (make-output-sink char-stream)))
(write-normalized-document-to-sink document sink)))
(defun write-document-to-octet-stream (document octet-stream)
"writes a cxml:dom document to a character stream"
(let ((sink (make-output-sink octet-stream :char-p nil)))
(write-normalized-document-to-sink document sink)))
(defgeneric html-output? (doc)
(:method (doc)
(let ((dt (dom:doctype doc)))
(or *html-compatibility-mode*
(and
dt
(string-equal "html" (dom:name dt))
(not (search "xhtml" (dom:system-id dt) :test #'string-equal)))))))
(defun write-document (document &optional (out-stream *standard-output*))
"Write the document to the designated out-stream, or *standard-ouput* by default."
(let ((*html-compatibility-mode* (html-output? document)))
(case (stream-element-type out-stream)
('character (write-document-to-character-stream document out-stream))
(otherwise (write-document-to-octet-stream document out-stream)))))
(defmacro with-document (&body chillins)
"(with-document ( a bunch of child nodes of the document )) --> cxml:dom document
Creates an environment in which the special variable *document* is available
a document is necessary to create dom nodes and the document the nodes end up on
must be the document on which they were created. At the end of the form, the
complete document is returned"
`(let ((*document* (cxml-dom:create-document)))
(append-nodes *document* ,@chillins)
*document*))
(defmacro with-document-to-file (filename &body chillins)
"Creates a document block with-document upon which to add the chillins (southern for children).
When the document is complete, it is written out to the specified file."
`(write-doc-to-file (with-document ,@chillins) ,filename))
(defun write-doc-to-file (doc filename)
"Binary write-out a document. will create/overwrite any existing file named the same."
(let ((filename (merge-pathnames filename)) )
(with-open-stream (fd (open filename :direction :output :element-type '(unsigned-byte 8)
:if-does-not-exist :create
:if-exists :supersede))
(write-document doc fd))
(values doc filename)))
(defun document-to-string (doc)
"Return a string representation of a document."
(with-output-to-string (fd)
(write-document doc fd)))
(defmacro with-xhtml-document (&body chillins)
"(with-xhtml-document ( a bunch of child nodes of the document )) --> cxml:dom document
Creates an environment in which the special variable *document* is available
a document is necessary to create dom nodes and the document the nodes end up on
must be the document on which they were created. At the end of the form, the
complete document is returned.
This sets the doctype to be xhtml transitional."
`(let ((*cdata-script-blocks* T)
(*document* (dom:create-document
'rune-dom:implementation
nil nil
(dom:create-document-type
'rune-dom:implementation
"html"
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"-transitional.dtd"))))
(append-nodes *document* ,@chillins)
*document*))
(defmacro with-xhtml-frameset-document (&body chillins)
"(with-xhtml-document ( a bunch of child nodes of the document )) --> cxml:dom document
Creates an environment in which the special variable *document* is available
a document is necessary to create dom nodes and the document the nodes end up on
must be the document on which they were created. At the end of the form, the
complete document is returned.
This sets the doctype to be xhtml transitional."
`(let ((*document* (dom:create-document
'rune-dom:implementation
nil nil
(dom:create-document-type
'rune-dom:implementation
"html"
"-//W3C//DTD XHTML 1.0 Frameset//EN"
"-frameset.dtd"))))
(append-nodes *document* ,@chillins)
*document*))
(defmacro with-xhtml-document-to-file (filename &body chillins)
"Creates a document block with-document upon which to add the chillins (southern for children). When the document is complete, it is written out to the specified file."
`(write-doc-to-file (with-xhtml-document ,@chillins) ,filename))
(defmacro with-html-document-to-file ((filename) &body body)
"Creates an html-document, writes out the results to filename"
`(let ((*html-compatibility-mode* T))
(write-doc-to-file (with-html-document ,@body)
,filename)))
(defmacro with-html-document (&body body)
"(with-html-document ( a bunch of child nodes of the document )) --> cxml:dom document
Creates an environment in which the special variable *document* is available
a document is necessary to create dom nodes and the document the nodes end up on
must be the document on which they were created. At the end of the form, the
complete document is returned.
This sets the doctype to be html 4.01 strict."
`(let ((*namespace-prefix-map* nil)
(*document* (dom:create-document
'rune-dom:implementation
nil nil
(dom:create-document-type
'rune-dom:implementation
"html"
"-//W3C//DTD HTML 4.01//EN"
"")
))
(*html-compatibility-mode* T)
(*cdata-script-blocks* nil))
(declare (special *document*))
(append-nodes *document* ,@body)
*document*))
(defmacro with-html5-document-to-file ((filename) &body body)
"Creates an html-document, writes out the results to filename"
`(let ((*html-compatibility-mode* T))
(write-doc-to-file (with-html5-document ,@body)
,filename)))
(defmacro with-html5-document (&body body)
"(with-html5-document ( a bunch of child nodes of the document )) --> cxml:dom document
Creates an environment in which the special variable *document* is available
a document is necessary to create dom nodes and the document the nodes end up on
must be the document on which they were created. At the end of the form, the
complete document is returned.
This sets the doctype to be html5 compatible <!DOCTYPE html>."
`(let ((*namespace-prefix-map* nil)
(*document* (dom:create-document
'rune-dom:implementation
nil nil
(dom:create-document-type
'rune-dom:implementation
"html"
nil
nil)
))
(*html-compatibility-mode* T)
(*cdata-script-blocks* nil))
(declare (special *document*))
(append-nodes *document* ,@body)
*document*))
(defmacro with-html-document-to-string (() &body body)
"trys to output a string containing all "
`(let ((*html-compatibility-mode* T))
(document-to-string (with-html-document ,@body))))
(defmacro with-html5-document-to-string (() &body body)
"trys to output a string containing all "
`(let ((*html-compatibility-mode* T))
(document-to-string (with-html5-document ,@body))))
(defgeneric remove-all-children (el)
(:method ((it dom:element))
(iter (for n in-dom-children it)
(setf (slot-value n 'rune-dom::parent) nil))
(setf (slot-value it 'rune-dom::children) (rune-dom::make-node-list))
it))
(defvar *snippet-output-stream* nil)
(defun %enstream (stream content-fn)
(let* ((old-out-stream *snippet-output-stream*)
(*snippet-output-stream* (or stream (make-string-output-stream )))
(result (multiple-value-list (funcall content-fn))))
(cond
(stream (apply #'values result))
(old-out-stream
(write-string (get-output-stream-string *snippet-output-stream*) old-out-stream))
(t (get-output-stream-string *snippet-output-stream*)))))
(defun %buffer-xml-output (stream sink body-fn)
(let ((cxml::*sink* (or sink (make-character-stream-sink stream)))
(cxml::*current-element* nil)
(cxml::*unparse-namespace-bindings* cxml::*initial-namespace-bindings*)
(cxml::*current-namespace-bindings* nil))
(setf (cxml::sink-omit-xml-declaration-p cxml::*sink*) T)
(sax:start-document cxml::*sink*)
(funcall body-fn)
(sax:end-document cxml::*sink*)))
(defmacro buffer-xml-output ((&optional stream sink) &body body)
"buffers out sax:events to a sting
xml parameters like <param:foo param:type=\"string\"><div>bar</div></param:foo>
are requested to be strings (presumably for string processing)
"
(let ((content `(lambda () (%buffer-xml-output *snippet-output-stream* ,sink (lambda () ,@body)))))
`(%enstream ,stream ,content)))
(defmacro %with-snippet ((type &optional stream sink) &body body)
"helper to define with-html-snippet and with-xhtml-snippet"
(assert (member type '(with-html-document with-html5-document with-xhtml-document)))
(alexandria:with-unique-names (result)
`(let ((*html-compatibility-mode*
',(member type '(with-html-document with-html5-document) ))
,result)
(,type
(progn
(setf
,result
(multiple-value-list
(buffer-xml-output (,stream ,sink)
(let ((content (flatten-children (progn ,@body))))
(iter (for n in content)
(buildnode::dom-walk cxml::*sink* n))))))
nil))
(apply #'values ,result))))
(defmacro with-html-snippet ((&optional stream sink) &body body)
"builds a little piece of html-dom and renders that to a string / stream"
`(%with-snippet (with-html-document ,stream ,sink) ,@body))
(defmacro with-html5-snippet ((&optional stream sink) &body body)
"builds a little piece of html-dom and renders that to a string / stream"
`(%with-snippet (with-html5-document ,stream ,sink) ,@body))
(defmacro with-xhtml-snippet ((&optional stream sink) &body body)
"builds a little piece of xhtml-dom and renders that to a string / stream"
`(%with-snippet (with-xhtml-document ,stream ,sink) ,@body))
|
fb61aef66f5b126ad0598439f65995818a48d515d9b478fcc7bde974b1f216d0 | nextjournal/advent-of-clerk | day_18.clj | # 🎄 Advent of Clerk : Day 18
(ns advent-of-clerk.day-18
(:require [nextjournal.clerk :as clerk])) | null | https://raw.githubusercontent.com/nextjournal/advent-of-clerk/9f358c9f13995f591981a26fc3683dea574933b1/src/advent_of_clerk/day_18.clj | clojure | # 🎄 Advent of Clerk : Day 18
(ns advent-of-clerk.day-18
(:require [nextjournal.clerk :as clerk])) | |
a506b8d37de7c3f735467c9d13765ec233dcc056232a93750371196076a7bbdb | skanev/playground | 14.scm | SICP exercise 5.14
;
; Measure the number of pushes and the maximum stack depth required to compute
; n! for various small values of n using the factorial machine shown in figure
5.11 . From your data determine formulas in terms of n for the total number
; of push operations and the maximum stack depth used in computing n! for any
n > 1 . Note that each of these is a linear function of n and is thus
determined by two constants . In order to get the statistics printed , you
; will have to augment the factorial machine with instructions to initialize
; the stack and print the statistics. You may want to also modify the machine
; so that it repeatedly reads a value for n, computes the factorial, and
prints the result ( as we did for the GCD machine in figure 5.4 ) , so that you
; will not have to repeatedly invoke get-register-contents,
; set-register-contents!, and start.
; The results are:
;
Running 1 ! : ( total - pushes = 0 maximum - depth = 0 )
Running 2 ! : ( total - pushes = 2 maximum - depth = 2 )
Running 3 ! : ( total - pushes = 4 maximum - depth = 4 )
Running 4 ! : ( total - pushes = 6 maximum - depth = 6 )
Running 5 ! : ( total - pushes = 8 maximum - depth = 8)
Running 6 ! : ( total - pushes = 10 maximum - depth = 10 )
Running 7 ! : ( total - pushes = 12 maximum - depth = 12 )
Running 8 ! : ( total - pushes = 14 maximum - depth = 14 )
Running 9 ! : ( total - pushes = 16 maximum - depth = 16 )
;
This implies that for computing n ! , there are in total 2(n - 1 ) pushes . This
; number is equal to the maximum depth too.
(load-relative "tests/helpers/simulator.scm")
; The modified procedures:
(define (make-stack)
(let ((s '())
(number-pushes 0)
(max-depth 0)
(current-depth 0))
(define (push x)
(set! s (cons x s))
(set! number-pushes (+ 1 number-pushes))
(set! current-depth (+ 1 current-depth))
(set! max-depth (max current-depth max-depth)))
(define (pop)
(if (null? s)
(error "Empty stack -- POP")
(let ((top (car s)))
(set! s (cdr s))
(set! current-depth (- current-depth 1))
top)))
(define (initialize)
(set! s '())
(set! number-pushes 0)
(set! max-depth 0)
(set! current-depth 0)
'done)
(define (print-statistics)
(display (list 'total-pushes '= number-pushes
'maximum-depth '= max-depth))
(newline))
(define (dispatch message)
(cond ((eq? message 'push) push)
((eq? message 'pop) (pop))
((eq? message 'initialize) (initialize))
((eq? message 'print-statistics) (print-statistics))
(else (error "Unknown request -- STACK" message))))
dispatch))
(define (make-new-machine)
(let ((pc (make-register 'pc))
(flag (make-register 'flag))
(stack (make-stack))
(the-instruction-sequence '()))
(let ((the-ops (list (list 'initialize-stack
(lambda () (stack 'initialize)))
(list 'print-stack-statistics
(lambda () (stack 'print-statistics)))))
(register-table (list (list 'pc pc) (list 'flag flag))))
(define (allocate-register name)
(if (assoc name register-table)
(error "Multiply defined register: " name)
(set! register-table (cons (list name (make-register name))
register-table)))
'register-allocated)
(define (lookup-register name)
(let ((val (assoc name register-table)))
(if val
(cadr val)
(error "Unknown register: " name))))
(define (execute)
(let ((insts (get-contents pc)))
(if (null? insts)
'done
(begin
((instruction-execution-proc (car insts)))
(execute)))))
(define (dispatch message)
(cond ((eq? message 'start)
(set-contents! pc the-instruction-sequence)
(execute))
((eq? message 'install-instruction-sequence)
(lambda (seq) (set! the-instruction-sequence seq)))
((eq? message 'allocate-register) allocate-register)
((eq? message 'get-register) lookup-register)
((eq? message 'install-operations)
(lambda (ops) (set! the-ops (append the-ops ops))))
((eq? message 'stack) stack)
((eq? message 'operations) the-ops)
(else (error "Unknown request -- MACHINE" message))))
dispatch)))
(define factorial-machine
(make-machine
'(n val continue)
(list (list '= =) (list '- -) (list '* *))
'(
(perform (op initialize-stack))
(assign continue (label fact-done))
fact-loop
(test (op =) (reg n) (const 1))
(branch (label base-case))
(save continue)
(save n)
(assign n (op -) (reg n) (const 1))
(assign continue (label after-fact))
(goto (label fact-loop))
after-fact
(restore n)
(restore continue)
(assign val (op *) (reg n) (reg val))
(goto (reg continue))
base-case
(assign val (const 1))
(goto (reg continue))
fact-done
(perform (op print-stack-statistics)))))
(define (measure-factorial n)
(set-register-contents! factorial-machine 'n n)
(display "Running ")
(display n)
(display "!: ")
(start factorial-machine))
(for ([n (in-range 1 10)])
(measure-factorial n))
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/05/14.scm | scheme |
Measure the number of pushes and the maximum stack depth required to compute
n! for various small values of n using the factorial machine shown in figure
of push operations and the maximum stack depth used in computing n! for any
will have to augment the factorial machine with instructions to initialize
the stack and print the statistics. You may want to also modify the machine
so that it repeatedly reads a value for n, computes the factorial, and
will not have to repeatedly invoke get-register-contents,
set-register-contents!, and start.
The results are:
number is equal to the maximum depth too.
The modified procedures: | SICP exercise 5.14
5.11 . From your data determine formulas in terms of n for the total number
n > 1 . Note that each of these is a linear function of n and is thus
determined by two constants . In order to get the statistics printed , you
prints the result ( as we did for the GCD machine in figure 5.4 ) , so that you
Running 1 ! : ( total - pushes = 0 maximum - depth = 0 )
Running 2 ! : ( total - pushes = 2 maximum - depth = 2 )
Running 3 ! : ( total - pushes = 4 maximum - depth = 4 )
Running 4 ! : ( total - pushes = 6 maximum - depth = 6 )
Running 5 ! : ( total - pushes = 8 maximum - depth = 8)
Running 6 ! : ( total - pushes = 10 maximum - depth = 10 )
Running 7 ! : ( total - pushes = 12 maximum - depth = 12 )
Running 8 ! : ( total - pushes = 14 maximum - depth = 14 )
Running 9 ! : ( total - pushes = 16 maximum - depth = 16 )
This implies that for computing n ! , there are in total 2(n - 1 ) pushes . This
(load-relative "tests/helpers/simulator.scm")
(define (make-stack)
(let ((s '())
(number-pushes 0)
(max-depth 0)
(current-depth 0))
(define (push x)
(set! s (cons x s))
(set! number-pushes (+ 1 number-pushes))
(set! current-depth (+ 1 current-depth))
(set! max-depth (max current-depth max-depth)))
(define (pop)
(if (null? s)
(error "Empty stack -- POP")
(let ((top (car s)))
(set! s (cdr s))
(set! current-depth (- current-depth 1))
top)))
(define (initialize)
(set! s '())
(set! number-pushes 0)
(set! max-depth 0)
(set! current-depth 0)
'done)
(define (print-statistics)
(display (list 'total-pushes '= number-pushes
'maximum-depth '= max-depth))
(newline))
(define (dispatch message)
(cond ((eq? message 'push) push)
((eq? message 'pop) (pop))
((eq? message 'initialize) (initialize))
((eq? message 'print-statistics) (print-statistics))
(else (error "Unknown request -- STACK" message))))
dispatch))
(define (make-new-machine)
(let ((pc (make-register 'pc))
(flag (make-register 'flag))
(stack (make-stack))
(the-instruction-sequence '()))
(let ((the-ops (list (list 'initialize-stack
(lambda () (stack 'initialize)))
(list 'print-stack-statistics
(lambda () (stack 'print-statistics)))))
(register-table (list (list 'pc pc) (list 'flag flag))))
(define (allocate-register name)
(if (assoc name register-table)
(error "Multiply defined register: " name)
(set! register-table (cons (list name (make-register name))
register-table)))
'register-allocated)
(define (lookup-register name)
(let ((val (assoc name register-table)))
(if val
(cadr val)
(error "Unknown register: " name))))
(define (execute)
(let ((insts (get-contents pc)))
(if (null? insts)
'done
(begin
((instruction-execution-proc (car insts)))
(execute)))))
(define (dispatch message)
(cond ((eq? message 'start)
(set-contents! pc the-instruction-sequence)
(execute))
((eq? message 'install-instruction-sequence)
(lambda (seq) (set! the-instruction-sequence seq)))
((eq? message 'allocate-register) allocate-register)
((eq? message 'get-register) lookup-register)
((eq? message 'install-operations)
(lambda (ops) (set! the-ops (append the-ops ops))))
((eq? message 'stack) stack)
((eq? message 'operations) the-ops)
(else (error "Unknown request -- MACHINE" message))))
dispatch)))
(define factorial-machine
(make-machine
'(n val continue)
(list (list '= =) (list '- -) (list '* *))
'(
(perform (op initialize-stack))
(assign continue (label fact-done))
fact-loop
(test (op =) (reg n) (const 1))
(branch (label base-case))
(save continue)
(save n)
(assign n (op -) (reg n) (const 1))
(assign continue (label after-fact))
(goto (label fact-loop))
after-fact
(restore n)
(restore continue)
(assign val (op *) (reg n) (reg val))
(goto (reg continue))
base-case
(assign val (const 1))
(goto (reg continue))
fact-done
(perform (op print-stack-statistics)))))
(define (measure-factorial n)
(set-register-contents! factorial-machine 'n n)
(display "Running ")
(display n)
(display "!: ")
(start factorial-machine))
(for ([n (in-range 1 10)])
(measure-factorial n))
|
ad1a4e71a824a3b59ff3fabbff01b2eb1639353c4718ffc9924ffe582441383c | lokke-org/lokke | invoke.scm | Copyright ( C ) 2019 - 2020 < >
SPDX - License - Identifier : LGPL-2.1 - or - later OR EPL-1.0 +
(define-module (lokke base invoke)
#:use-module ((guile) #:select ((apply . %scm-apply)))
#:use-module (oop goops)
#:export (invoke)
#:replace (apply)
#:duplicates (merge-generics replace warn-override-core warn last))
FIXME : this base case will be clobbered later by ( lokke base collection )
(define apply %scm-apply)
(define-generic apply)
(define-method (invoke (f <procedure>) . args)
(apply f args))
(define-method (invoke (f <generic>) . args)
(apply f args))
(define pws-class (class-of (make-procedure-with-setter identity identity)))
(define-method (invoke (f pws-class) . args)
(apply f args))
;; FIXME: do we want this?
(define parameter-class (class-of (make-parameter #f)))
(define-method (invoke (f parameter-class) . args)
(apply f args))
| null | https://raw.githubusercontent.com/lokke-org/lokke/a6616b3de60b62d787bf9b98206f8ad9eeb10844/mod/lokke/base/invoke.scm | scheme | FIXME: do we want this? | Copyright ( C ) 2019 - 2020 < >
SPDX - License - Identifier : LGPL-2.1 - or - later OR EPL-1.0 +
(define-module (lokke base invoke)
#:use-module ((guile) #:select ((apply . %scm-apply)))
#:use-module (oop goops)
#:export (invoke)
#:replace (apply)
#:duplicates (merge-generics replace warn-override-core warn last))
FIXME : this base case will be clobbered later by ( lokke base collection )
(define apply %scm-apply)
(define-generic apply)
(define-method (invoke (f <procedure>) . args)
(apply f args))
(define-method (invoke (f <generic>) . args)
(apply f args))
(define pws-class (class-of (make-procedure-with-setter identity identity)))
(define-method (invoke (f pws-class) . args)
(apply f args))
(define parameter-class (class-of (make-parameter #f)))
(define-method (invoke (f parameter-class) . args)
(apply f args))
|
d590041fcce11187b7e0b853a5bbef27f38969bbad9c67ca299fdd7df8277037 | jbclements/RSound | interactive-drr-frequency-response.rkt | #lang racket
(require "../frequency-response.rkt"
"../filter.rkt"
"../filter-typed.rkt"
racket/flonum
rackunit
plot)
100 - pole comb
(define (poly1 z)
(/ 1 (- 1 (* 0.95 (expt z -100)))))
(module+ main
(printf "100-pole comb filter, 0 up to Nyquist:\n")
;; show the whole range:
(response-plot poly1
0.0 ; min-freq
22050.0) ; max-freq
(printf "100-pole comb filter, 10K up to 11K:\n")
show the range from 10 K to 11 K :
(response-plot poly1
10000 ; min-freq
11000) ; max-freq
(printf "a single zero at 1:\n")
a single zero at 1 :
(response-plot (lambda (z) (- 1 (expt z -1))) 0 22050)
(printf "a single zero at 1:\n")
the same thing , using poles&zeros :
(response-plot (poles&zeros->poly '() '(1)) 0 22050)
(printf "one pole, two zeros:\n")
modeling a single pole and two zeros .
(response-plot (lambda (z)
(let ([a -0.28]
[b 0.57])
(/ (- 1 (expt z -2))
1
(+ 1
(* -2 a (expt z -1))
(* (+ (* a a) (* b b)) (expt z -2))))))
0
22050)
(printf "one pole, two zeros:\n")
the same thing , using poles&zeros :
(response-plot (poles&zeros->poly '(-0.28+0.57i -0.28-0.57i) '(1 -1))
0
22050)
(printf "poles on a vertical line, zeros at i and -i:\n")
(response-plot (poles&zeros->poly '(0.5 0.5+0.5i 0.5-0.5i) '(0+i 0-i))
0
22050)
(printf "I think this is a set of chebyshev coefficients...:\n")
(response-plot (coefficient-sets->poly
'(1.0 0.0 0.0 0.0 0.0 0.0)
'(1.0 -3.826392 5.516636 -3.5511127 0.861025))
0
22050)
(define (flvector->list flv)
(for/list ([v (in-flvector flv)]) v))
(lpf-coefficients 0.1)
(lpf-coefficients 0.01)
(response-plot
(coefficient-sets->poly
'(1 4 6 4 1)
'(1 -3.932065224332497 5.808146644839259 -3.8196712238297166 0.9436069610061315))
0 22050)
(lpf-response-plot 0.1 0 22050)
(lpf-response-plot 0.01 0 22050)
;; this one shows that lpf-sig is doing something sane:
this graph should have steep rolloff at about 3000 Hz ,
;; and should have 0 db gain at 0 Hz.
(let ()
(define-values (f i g) (lpf-sig 0.5))
(printf "fir terms: ~s\n" (flvector->list f))
(printf "iir terms: ~s\n" (flvector->list i))
(printf "gain: ~s\n" g)
(response-plot
(coefficient-sets->poly
(map (lambda (x) (* x g)) '(1 4 6 4 1))
(cons 1.0 (map (lambda (x) (- x ))(flvector->list i))))
0
22050))
;; okay, let's see if these filters are actually doing what they're supposed to.
(define reference-s-poles-500
(list
-0.0099444612+0.0700835358i
-0.0240080532+0.0290295510i
-0.0240080532-0.0290295510i
-0.0099444612-0.0700835358i)
)
(define reference-s-poles-1000
(list
-0.0199142092+0.1403452799i
-0.0480771539+0.0581329184i
-0.0480771539-0.0581329184i
-0.0199142092-0.1403452799i
)
)
(define reference-s-poles-11025
(list
-0.2790719918+1.9667583290i
-0.6737393875+0.8146579738i
-0.6737393875-0.8146579738i
-0.2790719918-1.9667583290i
))
(define reference-s-poles-1500
(list
-0.0299347885+0.2109652578i
-0.0722689725+0.0873846710i
-0.0722689725-0.0873846710i
-0.0299347885-0.2109652578i))
(define reference-s-poles-1000-bigripple
(list
-0.0087239785+0.1335251798i
-0.0210615472+0.0553079404i
-0.0210615472-0.0553079404i
-0.0087239785-0.1335251798i
))
(define (cplx->xy p)
(vector (real-part p) (imag-part p)))
(plot
(mix
(points
(map (lambda (cplx)
(vector (real-part cplx) (imag-part cplx)))
reference-s-poles-500))
(points
(map (lambda (cplx)
(vector (real-part cplx) (imag-part cplx)))
reference-s-poles-1000))
(points
(map (lambda (cplx)
(vector (real-part cplx) (imag-part cplx)))
reference-s-poles-1500))
(points
(map (lambda (cplx)
(vector (real-part cplx) (imag-part cplx)))
reference-s-poles-11025)
#:color "blue")
(points
(map (lambda (cplx)
(define multiplied (* 11.025 1.3 0.1425 cplx))
(vector (real-part multiplied) (imag-part multiplied)))
chebyshev-s-poles)
#:color "red")
)
#:x-min -3
#:x-max 3
#:y-min -3
#:y-max 3)
(define reference-z-poles-1000
(map s-space->z-space reference-s-poles-1000))
(define reference-z-poles-11025
(map s-space->z-space reference-s-poles-11025))
(define reference-z-poles-direct-1000
(list
0.9707680768+0.1369305667i
0.9514791950+0.0553910679i
0.9514791950-0.0553910679i
0.9707680768-0.1369305667i
))
(define reference-z-poles-direct-11025
(list
0.0059565954+0.8681048776i
0.3689458180+0.4171022170i
0.3689458180-0.4171022170i
0.0059565954-0.8681048776i
))
(plot
(mix
(points
(map cplx->xy reference-z-poles-direct-1000))
(points
(map cplx->xy reference-z-poles-1000)
#:color "red")
(parametric
(lambda (t)
(vector (cos t) (sin t)))
0
(* 2 pi)))
#:x-min -1
#:x-max 1
#:y-min -1
#:y-max 1
)
( lpf - response - plot 0.142 0 22050 # : db # f )
( lpf - response - plot 1.0 # ; ( * 2 pi 0.25 ) 0 22050 # : db # f )
(lpf-response-plot 0.8 0 22050 #:db #f)
(define coeff (roots->coefficients reference-z-poles-11025))
(define fir-terms (map (lambda (x) (/ x 16.0))(list 1.0 4.0 6.0 4.0 1.0)))
(define iir-terms coeff)
(define fun
(coefficient-sets->poly
fir-terms
iir-terms))
(response-plot fun 0 22050)
(plot (function
(lambda (omega)
(* 2 (tan (/ omega 2)))))
#:x-min (- pi)
#:x-max pi
#:y-max 50
#:y-min -50))
| null | https://raw.githubusercontent.com/jbclements/RSound/c699db1ffae4cf0185c46bdc059d7879d40614ce/rsound/test/interactive-drr-frequency-response.rkt | racket | show the whole range:
min-freq
max-freq
min-freq
max-freq
this one shows that lpf-sig is doing something sane:
and should have 0 db gain at 0 Hz.
okay, let's see if these filters are actually doing what they're supposed to.
( * 2 pi 0.25 ) 0 22050 # : db # f ) | #lang racket
(require "../frequency-response.rkt"
"../filter.rkt"
"../filter-typed.rkt"
racket/flonum
rackunit
plot)
100 - pole comb
(define (poly1 z)
(/ 1 (- 1 (* 0.95 (expt z -100)))))
(module+ main
(printf "100-pole comb filter, 0 up to Nyquist:\n")
(response-plot poly1
(printf "100-pole comb filter, 10K up to 11K:\n")
show the range from 10 K to 11 K :
(response-plot poly1
(printf "a single zero at 1:\n")
a single zero at 1 :
(response-plot (lambda (z) (- 1 (expt z -1))) 0 22050)
(printf "a single zero at 1:\n")
the same thing , using poles&zeros :
(response-plot (poles&zeros->poly '() '(1)) 0 22050)
(printf "one pole, two zeros:\n")
modeling a single pole and two zeros .
(response-plot (lambda (z)
(let ([a -0.28]
[b 0.57])
(/ (- 1 (expt z -2))
1
(+ 1
(* -2 a (expt z -1))
(* (+ (* a a) (* b b)) (expt z -2))))))
0
22050)
(printf "one pole, two zeros:\n")
the same thing , using poles&zeros :
(response-plot (poles&zeros->poly '(-0.28+0.57i -0.28-0.57i) '(1 -1))
0
22050)
(printf "poles on a vertical line, zeros at i and -i:\n")
(response-plot (poles&zeros->poly '(0.5 0.5+0.5i 0.5-0.5i) '(0+i 0-i))
0
22050)
(printf "I think this is a set of chebyshev coefficients...:\n")
(response-plot (coefficient-sets->poly
'(1.0 0.0 0.0 0.0 0.0 0.0)
'(1.0 -3.826392 5.516636 -3.5511127 0.861025))
0
22050)
(define (flvector->list flv)
(for/list ([v (in-flvector flv)]) v))
(lpf-coefficients 0.1)
(lpf-coefficients 0.01)
(response-plot
(coefficient-sets->poly
'(1 4 6 4 1)
'(1 -3.932065224332497 5.808146644839259 -3.8196712238297166 0.9436069610061315))
0 22050)
(lpf-response-plot 0.1 0 22050)
(lpf-response-plot 0.01 0 22050)
this graph should have steep rolloff at about 3000 Hz ,
(let ()
(define-values (f i g) (lpf-sig 0.5))
(printf "fir terms: ~s\n" (flvector->list f))
(printf "iir terms: ~s\n" (flvector->list i))
(printf "gain: ~s\n" g)
(response-plot
(coefficient-sets->poly
(map (lambda (x) (* x g)) '(1 4 6 4 1))
(cons 1.0 (map (lambda (x) (- x ))(flvector->list i))))
0
22050))
(define reference-s-poles-500
(list
-0.0099444612+0.0700835358i
-0.0240080532+0.0290295510i
-0.0240080532-0.0290295510i
-0.0099444612-0.0700835358i)
)
(define reference-s-poles-1000
(list
-0.0199142092+0.1403452799i
-0.0480771539+0.0581329184i
-0.0480771539-0.0581329184i
-0.0199142092-0.1403452799i
)
)
(define reference-s-poles-11025
(list
-0.2790719918+1.9667583290i
-0.6737393875+0.8146579738i
-0.6737393875-0.8146579738i
-0.2790719918-1.9667583290i
))
(define reference-s-poles-1500
(list
-0.0299347885+0.2109652578i
-0.0722689725+0.0873846710i
-0.0722689725-0.0873846710i
-0.0299347885-0.2109652578i))
(define reference-s-poles-1000-bigripple
(list
-0.0087239785+0.1335251798i
-0.0210615472+0.0553079404i
-0.0210615472-0.0553079404i
-0.0087239785-0.1335251798i
))
(define (cplx->xy p)
(vector (real-part p) (imag-part p)))
(plot
(mix
(points
(map (lambda (cplx)
(vector (real-part cplx) (imag-part cplx)))
reference-s-poles-500))
(points
(map (lambda (cplx)
(vector (real-part cplx) (imag-part cplx)))
reference-s-poles-1000))
(points
(map (lambda (cplx)
(vector (real-part cplx) (imag-part cplx)))
reference-s-poles-1500))
(points
(map (lambda (cplx)
(vector (real-part cplx) (imag-part cplx)))
reference-s-poles-11025)
#:color "blue")
(points
(map (lambda (cplx)
(define multiplied (* 11.025 1.3 0.1425 cplx))
(vector (real-part multiplied) (imag-part multiplied)))
chebyshev-s-poles)
#:color "red")
)
#:x-min -3
#:x-max 3
#:y-min -3
#:y-max 3)
(define reference-z-poles-1000
(map s-space->z-space reference-s-poles-1000))
(define reference-z-poles-11025
(map s-space->z-space reference-s-poles-11025))
(define reference-z-poles-direct-1000
(list
0.9707680768+0.1369305667i
0.9514791950+0.0553910679i
0.9514791950-0.0553910679i
0.9707680768-0.1369305667i
))
(define reference-z-poles-direct-11025
(list
0.0059565954+0.8681048776i
0.3689458180+0.4171022170i
0.3689458180-0.4171022170i
0.0059565954-0.8681048776i
))
(plot
(mix
(points
(map cplx->xy reference-z-poles-direct-1000))
(points
(map cplx->xy reference-z-poles-1000)
#:color "red")
(parametric
(lambda (t)
(vector (cos t) (sin t)))
0
(* 2 pi)))
#:x-min -1
#:x-max 1
#:y-min -1
#:y-max 1
)
( lpf - response - plot 0.142 0 22050 # : db # f )
(lpf-response-plot 0.8 0 22050 #:db #f)
(define coeff (roots->coefficients reference-z-poles-11025))
(define fir-terms (map (lambda (x) (/ x 16.0))(list 1.0 4.0 6.0 4.0 1.0)))
(define iir-terms coeff)
(define fun
(coefficient-sets->poly
fir-terms
iir-terms))
(response-plot fun 0 22050)
(plot (function
(lambda (omega)
(* 2 (tan (/ omega 2)))))
#:x-min (- pi)
#:x-max pi
#:y-max 50
#:y-min -50))
|
dff850556139092f3379c8fea9baedb9776847df7f5f17c8f5c5e28e44529cb8 | hyperfiddle/rcf | analyzer_test.clj | (ns hyperfiddle.rcf.analyzer-test
(:require [hyperfiddle.rcf.analyzer :as ana]
[clojure.test :as t :refer [deftest are testing]]))
(defn roundtrip
([form] (roundtrip (ana/empty-env) form))
([env form] (ana/emit (ana/analyze env form))))
(deftest roundtrips
(testing "hf.analyzer should parse and unparse clojure code transparently."
(are [x y] (= y x)
(roundtrip 1) '1
(roundtrip '1) 1
(roundtrip ''1) ''1
(roundtrip :ns/a) :ns/a
(roundtrip '(inc 1)) '(inc 1)
(roundtrip [1]) [1]
(roundtrip #{1}) #{1}
(roundtrip ()) ()
(roundtrip '(1)) '(1)
(roundtrip {:a 1}) {:a 1}
(roundtrip '(do 1)) '(do 1)
(roundtrip '(do (def a 1) a)) '(do (def a 1) a)
(roundtrip '((def a identity) 1)) '((def a identity) 1)
(-> (roundtrip '(def ^:macro a 1))
(second) (meta))
{:macro true}
(roundtrip '(if true a b)) '(if true a b)
(roundtrip '(if true a)) '(if true a nil)
(roundtrip '(let [a 1
b 2] a)) '(let [a 1, b 2] a)
(roundtrip '(loop* [a 1] (recur a))) '(loop* [a 1] (do (recur a)))
(roundtrip '(fn* [])) '(fn* ([] (do)))
(roundtrip '(fn* f [])) '(fn* f ([] (do)))
(roundtrip '(fn* [a] a)) '(fn* ([a] (do a)))
(roundtrip '(fn* ([a] a) ([a b] a))) '(fn* ([a] (do a)) ([a b] (do a)))
(roundtrip '(fn [a] a)) '(fn [a] a)
(roundtrip '(fn f [])) '(fn f [])
(roundtrip '(letfn* [foo (fn* foo ([a] (inc a)))] 1)) '(letfn* [foo (fn* foo ([a] (do (inc a))))] (do 1))
(roundtrip '(try 1)) '(try (do 1))
(roundtrip '(try 1 (catch Err e# 2))) '(try (do 1) (catch Err e# (do 2)))
(roundtrip '(try 1 (catch Err e# 2)
(catch Err2 e# 3)
(finally 4)))
'(try (do 1) (catch Err e# (do 2)) (catch Err2 e# (do 3)) (finally 4))
)))
(comment
(ana/analyze (ana/empty-env) '(do 1))
) | null | https://raw.githubusercontent.com/hyperfiddle/rcf/89ce7b01091a0b74036e5130b3e9202c27b61439/test/hyperfiddle/rcf/analyzer_test.clj | clojure | (ns hyperfiddle.rcf.analyzer-test
(:require [hyperfiddle.rcf.analyzer :as ana]
[clojure.test :as t :refer [deftest are testing]]))
(defn roundtrip
([form] (roundtrip (ana/empty-env) form))
([env form] (ana/emit (ana/analyze env form))))
(deftest roundtrips
(testing "hf.analyzer should parse and unparse clojure code transparently."
(are [x y] (= y x)
(roundtrip 1) '1
(roundtrip '1) 1
(roundtrip ''1) ''1
(roundtrip :ns/a) :ns/a
(roundtrip '(inc 1)) '(inc 1)
(roundtrip [1]) [1]
(roundtrip #{1}) #{1}
(roundtrip ()) ()
(roundtrip '(1)) '(1)
(roundtrip {:a 1}) {:a 1}
(roundtrip '(do 1)) '(do 1)
(roundtrip '(do (def a 1) a)) '(do (def a 1) a)
(roundtrip '((def a identity) 1)) '((def a identity) 1)
(-> (roundtrip '(def ^:macro a 1))
(second) (meta))
{:macro true}
(roundtrip '(if true a b)) '(if true a b)
(roundtrip '(if true a)) '(if true a nil)
(roundtrip '(let [a 1
b 2] a)) '(let [a 1, b 2] a)
(roundtrip '(loop* [a 1] (recur a))) '(loop* [a 1] (do (recur a)))
(roundtrip '(fn* [])) '(fn* ([] (do)))
(roundtrip '(fn* f [])) '(fn* f ([] (do)))
(roundtrip '(fn* [a] a)) '(fn* ([a] (do a)))
(roundtrip '(fn* ([a] a) ([a b] a))) '(fn* ([a] (do a)) ([a b] (do a)))
(roundtrip '(fn [a] a)) '(fn [a] a)
(roundtrip '(fn f [])) '(fn f [])
(roundtrip '(letfn* [foo (fn* foo ([a] (inc a)))] 1)) '(letfn* [foo (fn* foo ([a] (do (inc a))))] (do 1))
(roundtrip '(try 1)) '(try (do 1))
(roundtrip '(try 1 (catch Err e# 2))) '(try (do 1) (catch Err e# (do 2)))
(roundtrip '(try 1 (catch Err e# 2)
(catch Err2 e# 3)
(finally 4)))
'(try (do 1) (catch Err e# (do 2)) (catch Err2 e# (do 3)) (finally 4))
)))
(comment
(ana/analyze (ana/empty-env) '(do 1))
) | |
d269e2ae954005ceaafc53716f48bc45a54413b78d58bf386a1a974d552baa95 | jlouis/graphql-erlang | dungeon_type.erl | -module(dungeon_type).
-include("dungeon.hrl").
-export([execute/1]).
execute(#monster{}) -> {ok, 'Monster'};
execute(#dice{}) -> {ok, 'Dice'};
execute(kraken) -> {error, kraken};
execute(X) ->
case dungeon:unwrap(X) of
{Ty, _} -> object_type(Ty)
end.
object_type(room) -> {ok, 'Room'};
object_type(dice) -> {ok, 'Dice'};
object_type(monster) -> {ok, 'Monster'};
object_type(item) -> {ok, 'Item'};
object_type(_) ->
{error, unknown}.
| null | https://raw.githubusercontent.com/jlouis/graphql-erlang/4fd356294c2acea42a024366bc5a64661e4862d7/test/dungeon_type.erl | erlang | -module(dungeon_type).
-include("dungeon.hrl").
-export([execute/1]).
execute(#monster{}) -> {ok, 'Monster'};
execute(#dice{}) -> {ok, 'Dice'};
execute(kraken) -> {error, kraken};
execute(X) ->
case dungeon:unwrap(X) of
{Ty, _} -> object_type(Ty)
end.
object_type(room) -> {ok, 'Room'};
object_type(dice) -> {ok, 'Dice'};
object_type(monster) -> {ok, 'Monster'};
object_type(item) -> {ok, 'Item'};
object_type(_) ->
{error, unknown}.
| |
d1bb46a30148f52897156561c118cfd0aede1cc3e10805a8850bfc9c07422e28 | brendanhay/gogol | Cancel.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . . Organizations . Operations . Cancel
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
Starts asynchronous cancellation on a long - running operation . The server makes a best effort to cancel the operation , but success is not guaranteed . If the server doesn\'t support this method , it returns @google.rpc . Code . UNIMPLEMENTED@. Clients can use Operations . GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation . On successful cancellation , the operation is not deleted ; instead , it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1 , corresponding to @Code . CANCELLED@.
--
-- /See:/ < Security Command Center API Reference> for @securitycenter.organizations.operations.cancel@.
module Gogol.SecurityCenter.Organizations.Operations.Cancel
( -- * Resource
SecurityCenterOrganizationsOperationsCancelResource,
-- ** Constructing a Request
SecurityCenterOrganizationsOperationsCancel (..),
newSecurityCenterOrganizationsOperationsCancel,
)
where
import qualified Gogol.Prelude as Core
import Gogol.SecurityCenter.Types
-- | A resource alias for @securitycenter.organizations.operations.cancel@ method which the
-- 'SecurityCenterOrganizationsOperationsCancel' request conforms to.
type SecurityCenterOrganizationsOperationsCancelResource =
"v1p1beta1"
Core.:> Core.CaptureMode "name" "cancel" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Post '[Core.JSON] Empty
| Starts asynchronous cancellation on a long - running operation . The server makes a best effort to cancel the operation , but success is not guaranteed . If the server doesn\'t support this method , it returns @google.rpc . Code . UNIMPLEMENTED@. Clients can use Operations . GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation . On successful cancellation , the operation is not deleted ; instead , it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1 , corresponding to @Code . CANCELLED@.
--
-- /See:/ 'newSecurityCenterOrganizationsOperationsCancel' smart constructor.
data SecurityCenterOrganizationsOperationsCancel = SecurityCenterOrganizationsOperationsCancel
{ -- | V1 error format.
xgafv :: (Core.Maybe Xgafv),
-- | OAuth access token.
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
-- | The name of the operation resource to be cancelled.
name :: Core.Text,
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'SecurityCenterOrganizationsOperationsCancel' with the minimum fields required to make a request.
newSecurityCenterOrganizationsOperationsCancel ::
-- | The name of the operation resource to be cancelled. See 'name'.
Core.Text ->
SecurityCenterOrganizationsOperationsCancel
newSecurityCenterOrganizationsOperationsCancel name =
SecurityCenterOrganizationsOperationsCancel
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
name = name,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
SecurityCenterOrganizationsOperationsCancel
where
type
Rs SecurityCenterOrganizationsOperationsCancel =
Empty
type
Scopes
SecurityCenterOrganizationsOperationsCancel =
'[CloudPlatform'FullControl]
requestClient
SecurityCenterOrganizationsOperationsCancel {..} =
go
name
xgafv
accessToken
callback
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
securityCenterService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
SecurityCenterOrganizationsOperationsCancelResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-securitycenter/gen/Gogol/SecurityCenter/Organizations/Operations/Cancel.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
/See:/ < Security Command Center API Reference> for @securitycenter.organizations.operations.cancel@.
* Resource
** Constructing a Request
| A resource alias for @securitycenter.organizations.operations.cancel@ method which the
'SecurityCenterOrganizationsOperationsCancel' request conforms to.
/See:/ 'newSecurityCenterOrganizationsOperationsCancel' smart constructor.
| V1 error format.
| OAuth access token.
| The name of the operation resource to be cancelled.
| Upload protocol for media (e.g. \"raw\", \"multipart\").
| Creates a value of 'SecurityCenterOrganizationsOperationsCancel' with the minimum fields required to make a request.
| The name of the operation resource to be cancelled. See 'name'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . . Organizations . Operations . Cancel
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
Starts asynchronous cancellation on a long - running operation . The server makes a best effort to cancel the operation , but success is not guaranteed . If the server doesn\'t support this method , it returns @google.rpc . Code . UNIMPLEMENTED@. Clients can use Operations . GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation . On successful cancellation , the operation is not deleted ; instead , it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1 , corresponding to @Code . CANCELLED@.
module Gogol.SecurityCenter.Organizations.Operations.Cancel
SecurityCenterOrganizationsOperationsCancelResource,
SecurityCenterOrganizationsOperationsCancel (..),
newSecurityCenterOrganizationsOperationsCancel,
)
where
import qualified Gogol.Prelude as Core
import Gogol.SecurityCenter.Types
type SecurityCenterOrganizationsOperationsCancelResource =
"v1p1beta1"
Core.:> Core.CaptureMode "name" "cancel" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Post '[Core.JSON] Empty
| Starts asynchronous cancellation on a long - running operation . The server makes a best effort to cancel the operation , but success is not guaranteed . If the server doesn\'t support this method , it returns @google.rpc . Code . UNIMPLEMENTED@. Clients can use Operations . GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation . On successful cancellation , the operation is not deleted ; instead , it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1 , corresponding to @Code . CANCELLED@.
data SecurityCenterOrganizationsOperationsCancel = SecurityCenterOrganizationsOperationsCancel
xgafv :: (Core.Maybe Xgafv),
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
name :: Core.Text,
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newSecurityCenterOrganizationsOperationsCancel ::
Core.Text ->
SecurityCenterOrganizationsOperationsCancel
newSecurityCenterOrganizationsOperationsCancel name =
SecurityCenterOrganizationsOperationsCancel
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
name = name,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
SecurityCenterOrganizationsOperationsCancel
where
type
Rs SecurityCenterOrganizationsOperationsCancel =
Empty
type
Scopes
SecurityCenterOrganizationsOperationsCancel =
'[CloudPlatform'FullControl]
requestClient
SecurityCenterOrganizationsOperationsCancel {..} =
go
name
xgafv
accessToken
callback
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
securityCenterService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
SecurityCenterOrganizationsOperationsCancelResource
)
Core.mempty
|
b9154d46a11080feb499a3840dce00b590a3c25cda79520f10bbec68d0e81975 | parapluu/Concuerror | test.erl | -module(test).
-export([scenarios/0]).
-export([t_simple_reg/0, t_simple_reg_or_locate/0, t_reg_or_locate2/0]).
-export([test1/0, test2/0, test3/0, test4/0]).
-concuerror_options_forced(
[ {after_timeout, 1000}
, {treat_as_normal, shutdown}
, {ignore_error, deadlock}
]).
-include_lib("eunit/include/eunit.hrl").
scenarios() ->
[{T, inf, dpor} ||
T <- [t_simple_reg, t_simple_reg_or_locate, t_reg_or_locate2]].
t_simple_reg() ->
gproc_sup:start_link([]),
?assert(gproc:reg({n,l,name}) =:= true),
?assert(gproc:where({n,l,name}) =:= self()),
?assert(gproc:unreg({n,l,name}) =:= true),
?assert(gproc:where({n,l,name}) =:= undefined).
t_simple_reg_or_locate() ->
P = self(),
gproc_sup:start_link([]),
?assertMatch({P, undefined}, gproc:reg_or_locate({n,l,name})),
?assertMatch(P, gproc:where({n,l,name})),
?assertMatch({P, my_val}, gproc:reg_or_locate({n,l,name2}, my_val)),
?assertMatch(my_val, gproc:get_value({n,l,name2})).
t_reg_or_locate2() ->
P = self(),
gproc_sup:start_link([]),
{P1,R1} = spawn_monitor(fun() ->
Ref = erlang:monitor(process, P),
gproc:reg({n,l,foo}, the_value),
P ! {self(), ok},
receive
{'DOWN',Ref,_,_,_} -> ok
end
end),
receive {P1, ok} -> ok end,
?assertMatch({P1, the_value}, gproc:reg_or_locate({n,l,foo})),
exit(P1, kill),
receive
{'DOWN',R1,_,_,_} ->
ok
end.
test1() ->
Self = self(),
gproc_sup:start_link([]),
true = gproc:reg({n,l,name}),
Self = gproc:where({n,l,name}),
true = gproc:unreg({n,l,name}),
undefined = gproc:where({n,l,name}).
test2() ->
P = self(),
gproc_sup:start_link([]),
{P, undefined} = gproc:reg_or_locate({n,l,name}),
P = gproc:where({n,l,name}),
{P, my_val} = gproc:reg_or_locate({n,l,name2}, my_val),
my_val = gproc:get_value({n,l,name2}).
test3() ->
gproc_sup:start_link([]),
gproc_chain(1) ! {token, []},
receive
{token, L} ->
true = lists:member(true, L)
end.
test3(N) ->
gproc_sup:start_link([]),
gproc_chain(N) ! {token, []},
receive
{token, L} ->
true = lists:member(true, L)
end,
receive after infinity -> ok end.
test4() ->
gproc_sup:start_link([]),
true = gproc:reg({n,l,name}),
gproc_chain(3) ! {token, []},
receive
{token, L} ->
false = lists:member(true, L)
end.
gproc_chain(N) ->
gproc_chain(N, self()).
gproc_chain(0, Last) -> Last;
gproc_chain(N, Link) ->
gproc_chain(N-1, spawn(fun() -> gproc_chain_member(Link) end)).
gproc_chain_member(Link) ->
R =
try gproc:reg({n,l,name}) of
_ -> true
catch
_:_ -> false
end,
receive
{token, L} ->
Link ! {token, [R|L]}
end.
pub_sub() ->
gproc_sup:start_link([]),
spawn_workers(3) ! token,
receive token -> ok end,
gproc:send({p,l,worker}, event1),
gproc : send({p , l , worker } , ) ,
receive after infinity -> ok end.
spawn_workers(N) ->
spawn_workers(N, self()).
spawn_workers(0, Link) -> Link;
spawn_workers(N, Link) ->
spawn_workers(N-1, spawn(fun() -> worker(Link) end)).
worker(Link) ->
gproc:reg({p, l, worker}),
receive token -> Link ! token end,
receive
event1 -> ok
%% E1 ->
%% receive
%% E2 ->
%% {event1, event2} = {E1, E2}
%% end
end.
| null | https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests-real/suites/gproc/test.erl | erlang | E1 ->
receive
E2 ->
{event1, event2} = {E1, E2}
end | -module(test).
-export([scenarios/0]).
-export([t_simple_reg/0, t_simple_reg_or_locate/0, t_reg_or_locate2/0]).
-export([test1/0, test2/0, test3/0, test4/0]).
-concuerror_options_forced(
[ {after_timeout, 1000}
, {treat_as_normal, shutdown}
, {ignore_error, deadlock}
]).
-include_lib("eunit/include/eunit.hrl").
scenarios() ->
[{T, inf, dpor} ||
T <- [t_simple_reg, t_simple_reg_or_locate, t_reg_or_locate2]].
t_simple_reg() ->
gproc_sup:start_link([]),
?assert(gproc:reg({n,l,name}) =:= true),
?assert(gproc:where({n,l,name}) =:= self()),
?assert(gproc:unreg({n,l,name}) =:= true),
?assert(gproc:where({n,l,name}) =:= undefined).
t_simple_reg_or_locate() ->
P = self(),
gproc_sup:start_link([]),
?assertMatch({P, undefined}, gproc:reg_or_locate({n,l,name})),
?assertMatch(P, gproc:where({n,l,name})),
?assertMatch({P, my_val}, gproc:reg_or_locate({n,l,name2}, my_val)),
?assertMatch(my_val, gproc:get_value({n,l,name2})).
t_reg_or_locate2() ->
P = self(),
gproc_sup:start_link([]),
{P1,R1} = spawn_monitor(fun() ->
Ref = erlang:monitor(process, P),
gproc:reg({n,l,foo}, the_value),
P ! {self(), ok},
receive
{'DOWN',Ref,_,_,_} -> ok
end
end),
receive {P1, ok} -> ok end,
?assertMatch({P1, the_value}, gproc:reg_or_locate({n,l,foo})),
exit(P1, kill),
receive
{'DOWN',R1,_,_,_} ->
ok
end.
test1() ->
Self = self(),
gproc_sup:start_link([]),
true = gproc:reg({n,l,name}),
Self = gproc:where({n,l,name}),
true = gproc:unreg({n,l,name}),
undefined = gproc:where({n,l,name}).
test2() ->
P = self(),
gproc_sup:start_link([]),
{P, undefined} = gproc:reg_or_locate({n,l,name}),
P = gproc:where({n,l,name}),
{P, my_val} = gproc:reg_or_locate({n,l,name2}, my_val),
my_val = gproc:get_value({n,l,name2}).
test3() ->
gproc_sup:start_link([]),
gproc_chain(1) ! {token, []},
receive
{token, L} ->
true = lists:member(true, L)
end.
test3(N) ->
gproc_sup:start_link([]),
gproc_chain(N) ! {token, []},
receive
{token, L} ->
true = lists:member(true, L)
end,
receive after infinity -> ok end.
test4() ->
gproc_sup:start_link([]),
true = gproc:reg({n,l,name}),
gproc_chain(3) ! {token, []},
receive
{token, L} ->
false = lists:member(true, L)
end.
gproc_chain(N) ->
gproc_chain(N, self()).
gproc_chain(0, Last) -> Last;
gproc_chain(N, Link) ->
gproc_chain(N-1, spawn(fun() -> gproc_chain_member(Link) end)).
gproc_chain_member(Link) ->
R =
try gproc:reg({n,l,name}) of
_ -> true
catch
_:_ -> false
end,
receive
{token, L} ->
Link ! {token, [R|L]}
end.
pub_sub() ->
gproc_sup:start_link([]),
spawn_workers(3) ! token,
receive token -> ok end,
gproc:send({p,l,worker}, event1),
gproc : send({p , l , worker } , ) ,
receive after infinity -> ok end.
spawn_workers(N) ->
spawn_workers(N, self()).
spawn_workers(0, Link) -> Link;
spawn_workers(N, Link) ->
spawn_workers(N-1, spawn(fun() -> worker(Link) end)).
worker(Link) ->
gproc:reg({p, l, worker}),
receive token -> Link ! token end,
receive
event1 -> ok
end.
|
bf94a1a7c8a35a557f5b0feb23e560910b0e7dca2a02d8febe9760962372f7e8 | exoscale/clojure-kubernetes-client | v1_pod_condition.clj | (ns clojure-kubernetes-client.specs.v1-pod-condition
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
)
(:import (java.io File)))
(declare v1-pod-condition-data v1-pod-condition)
(def v1-pod-condition-data
{
(ds/opt :lastProbeTime) inst?
(ds/opt :lastTransitionTime) inst?
(ds/opt :message) string?
(ds/opt :reason) string?
(ds/req :status) string?
(ds/req :type) string?
})
(def v1-pod-condition
(ds/spec
{:name ::v1-pod-condition
:spec v1-pod-condition-data}))
| null | https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_pod_condition.clj | clojure | (ns clojure-kubernetes-client.specs.v1-pod-condition
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
)
(:import (java.io File)))
(declare v1-pod-condition-data v1-pod-condition)
(def v1-pod-condition-data
{
(ds/opt :lastProbeTime) inst?
(ds/opt :lastTransitionTime) inst?
(ds/opt :message) string?
(ds/opt :reason) string?
(ds/req :status) string?
(ds/req :type) string?
})
(def v1-pod-condition
(ds/spec
{:name ::v1-pod-condition
:spec v1-pod-condition-data}))
| |
5d37fe0889ca066014bafb78cba3965c4ac735e7901698924c72e6ef51b9dd58 | donaldsonjw/bigloo | function.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / cigloo / Translate / function.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Tue Nov 28 09:49:40 1995 * /
* Last change : Sun Dec 30 09:11:05 2007 ( serrano ) * /
;* ------------------------------------------------------------- */
;* The function definition and declaration translation. */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module translate_function
(include "Parser/coord.sch"
"Translate/ast.sch"
"Translate/type.sch"
"Translate/function.sch")
(import engine_param
translate_type
translate_decl
translate_tspec
translate_eval
translate_ident
tools_speek
tools_error)
(export (translate-function-definition <ast>)
(translate-function-declaration <decl> <spec> <para-list>)
(translate-function-declarations)
(detect-struct-or-union <type>)
(parameter-type-list->types <ptl>)))
;*---------------------------------------------------------------------*/
;* *fun-decl-list* ... */
;*---------------------------------------------------------------------*/
(define *fun-decl-list* '())
;*---------------------------------------------------------------------*/
;* translate-function-declaration ... */
;* ------------------------------------------------------------- */
;* Function declaration are delayed (in order to wait for */
;* the function declaration), then this function just store */
;* in a list the function declaration. */
;*---------------------------------------------------------------------*/
(define (translate-function-declaration decl spec para-list)
(let ((fun-decl (fun-decl decl spec para-list)))
(set! *fun-decl-list* (cons fun-decl *fun-decl-list*))))
;*---------------------------------------------------------------------*/
;* translate-function-declarations ... */
;*---------------------------------------------------------------------*/
(define (translate-function-declarations)
(define (do-translate-function-declaration fd)
(let* ((decl (fun-decl-decl fd))
(spec (fun-decl-spec fd))
(para-list (fun-decl-para-list fd))
(tspec (type-spec-of-decl-spec spec))
(type (type+decl->type (tspec->type tspec) decl))
(f-ident (get-decl-ident decl))
(f-id (ident-id f-ident)))
(verbose 2
"do-translate-function-declaration: " #\Newline
" decl: " decl #\Newline
" spec: " spec #\Newline)
[assert check (type) (function-t? type)]
(let ((sf-id (string->symbol (string-upcase f-id))))
(if (not (getprop sf-id 'fun-processed))
(begin
(putprop! sf-id 'fun-processed #t)
(verbose 1 " " f-id #\Newline)
(fprin *oport* " ("
(if *macro-function* "macro " "")
(ident->ident f-id) "::"
(type-id (function-t-to type))
" ")
(add-eval-function!
f-id
(translate-parameter
f-ident
(list 'parameter-type-list para-list)
#f))
(fprint *oport* " \"" f-id "\")"))))))
(for-each do-translate-function-declaration (reverse *fun-decl-list*))
(set! *fun-decl-list* '()))
;*---------------------------------------------------------------------*/
;* translate-function-definition ... */
;*---------------------------------------------------------------------*/
(define (translate-function-definition ast)
(let* ((fun-decl (fun-def-decl ast))
(fun-ident (get-decl-ident fun-decl))
(fun-para-decl (get-decl-para-decl fun-decl))
(fun-id (ident-id fun-ident))
(sfun-id (string->symbol (string-upcase fun-id)))
(fun-body (fun-def-body ast)))
(if (not fun-para-decl)
(error/ast fun-id "incorrect function definition" fun-ident)
(begin
(verbose 1 " " fun-id)
(let ((sspec (storage-class-spec-of-decl-spec
(fun-def-decl-spec ast))))
;; we check the correctness of the storage class specifier
;; and we check if we skip this definition
(cond
((not (correct-storage-class-spec? sspec))
;; it is not correct
(error/ast (storage-class-spec-value (car sspec))
"multiple storage classes in declaration"
(car sspec)))
((or (fun-def-processed? ast)
(getprop sfun-id 'fun-processed))
(verbose 1 " (already done)" #\Newline)
#unspecified)
((and (pair? sspec)
(case (storage-class-spec-value (car sspec))
((static)
#t)
(else
#f)))
;; we ignore this definition
(verbose 1 " (ignored because "
(storage-class-spec-value (car sspec))
#\) #\Newline)
#unspecified)
(else
(putprop! sfun-id 'fun-processed #t)
(fun-def-processed?-set! ast #t)
(let ((tspec (type-spec-of-decl-spec
(fun-def-decl-spec ast))))
(verbose 1 #\Newline)
(display " (" *oport*)
(if *macro-function* "macro " "")
(let ((type (type+decl->type (tspec->type tspec)
fun-decl)))
[assert check (type) (function-t? type)]
(begin
(display (ident->ident fun-id) *oport*)
(display "::" *oport*)
(display (type-id (function-t-to type)) *oport*)
(display #\space *oport*)
(add-eval-function!
fun-id
(translate-parameter fun-ident
fun-para-decl
fun-body))
(display " \"" *oport*)
(display fun-id *oport*)
(display #\" *oport*))
(fprint *oport* #\)))))))))))
;*---------------------------------------------------------------------*/
;* translate-parameter ... */
;*---------------------------------------------------------------------*/
(define (translate-parameter fun-ident para-decl body)
(match-case para-decl
((parameter-identifier-list ?list)
(translate-para-id fun-ident list body))
((parameter-type-list ?list)
(translate-para-type list))
(else
(error "internal-error" "translate-parameter" para-decl))))
;*---------------------------------------------------------------------*/
;* translate-para-id ... */
;*---------------------------------------------------------------------*/
(define (translate-para-id fun-ident ident-list body)
(verbose 3 "translate-para-id: " #\Newline)
(verbose 3 "para-decl: " ident-list #\Newline)
(verbose 3 "body : " body #\Newline)
;; we compute from body a list of `(id . type);
(let ((id-types (let loop ((body body)
(res '()))
(cond
((null? body)
res)
((not (declare? (car body)))
res)
(else
(let* ((declare (car body))
(spec (declare-spec declare))
(idcl (declare-init-decl-list declare))
(decl (match-case idcl
((?decl . ?-)
decl)
(?decl
decl)))
(tspec (type-spec-of-decl-spec spec))
(ident (get-decl-ident decl))
(id (ident-id ident))
(type (type+decl->type (tspec->type tspec)
decl)))
(loop (cdr body)
(cons (cons id type)
res))))))))
(map (lambda (ident)
(let ((cell (assoc (ident-id ident) id-types)))
(if (not (pair? cell))
(error/ast (ident-id fun-ident)
"missing argument types"
fun-ident)
(cdr cell))))
ident-list)))
;*---------------------------------------------------------------------*/
;* detect-struct-or-union ... */
;*---------------------------------------------------------------------*/
(define (detect-struct-or-union type)
(type-case type
((typedef-t)
(detect-struct-or-union (typedef-t-alias type)))
((struct-t)
(warning "detect-struct-or-union:"
"type `" (type-c-name type)
"' used as function parameter or return type"))
(else
#t)))
;*---------------------------------------------------------------------*/
;* string-end=? ... */
;*---------------------------------------------------------------------*/
(define (string-end=? string suff)
(and (string? suff)
(string? string)
(let ((sufflen (string-length suff))
(strlen (string-length string)))
(and (string? string)
(>= strlen sufflen)
(string=? (substring string (- strlen sufflen) strlen) suff)))))
;*---------------------------------------------------------------------*/
;* fix-abstract-array-type ... */
;*---------------------------------------------------------------------*/
(define (fix-abstract-array-type type0)
(or
(let loop ((type type0))
(type-case type
((typedef-t) (loop (typedef-t-alias type)))
((array-t)
;; If its an abstract array return a pointer to
;; the element type.
(and (string-end=? (type-id type) "array")
(make-ptr-to (array-t-type type))))
(else #f)))
type0))
;*---------------------------------------------------------------------*/
;* parameter-type-list->types ... */
;*---------------------------------------------------------------------*/
(define (parameter-type-list->types list)
(define (translate-one-para-decl p-decl previous)
(if (not (para-decl? p-decl))
(if (eq? p-decl '...)
(if (not (type? previous))
(error "parameter-type-list->types"
"incorrect paremeter-type-list"
(list))
(make-... previous))
(begin
(if (ast? p-decl)
(error/ast 'parameter-type-list->types
"Unknow expression"
p-decl)
(error 'parameter-type-list->types
"Unknow expression"
p-decl))))
(let ((tspec (para-decl-type-spec-list p-decl))
(decl (para-decl-decl p-decl)))
(if tspec
(let ((type (tspec->type tspec)))
(type+decl->type type decl))
(let* ((tspec (t-name-type-spec-list
(para-decl-type-name p-decl)))
(adecl (t-name-adecl (para-decl-type-name p-decl)))
(type (tspec->type tspec)))
(type+adecl->type type adecl))))))
(let loop ((list list)
(previous #f)
(res '()))
(if (null? list)
(reverse! res)
(let ((type (translate-one-para-decl (car list) previous)))
(detect-struct-or-union type)
(set! type (fix-abstract-array-type type))
(loop (cdr list)
type
(cons type res))))))
;*---------------------------------------------------------------------*/
;* translate-para-type ... */
;*---------------------------------------------------------------------*/
(define (translate-para-type list)
(let ((ptl (parameter-type-list->types list)))
(let ((par-list (if (and (pair? ptl)
(null? (cdr ptl))
(or (eq? (type-id (car ptl)) 'void)
(string=? (type-id (car ptl)) "void")))
;; this is the special case for no argument
;; prototyping
'()
(map type-id ptl))))
(display par-list *oport*)
par-list)))
| null | https://raw.githubusercontent.com/donaldsonjw/bigloo/a4d06e409d0004e159ce92b9908719510a18aed5/cigloo/Translate/function.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* The function definition and declaration translation. */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *fun-decl-list* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* translate-function-declaration ... */
* ------------------------------------------------------------- */
* Function declaration are delayed (in order to wait for */
* the function declaration), then this function just store */
* in a list the function declaration. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* translate-function-declarations ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* translate-function-definition ... */
*---------------------------------------------------------------------*/
we check the correctness of the storage class specifier
and we check if we skip this definition
it is not correct
we ignore this definition
*---------------------------------------------------------------------*/
* translate-parameter ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* translate-para-id ... */
*---------------------------------------------------------------------*/
we compute from body a list of `(id . type);
*---------------------------------------------------------------------*/
* detect-struct-or-union ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* string-end=? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* fix-abstract-array-type ... */
*---------------------------------------------------------------------*/
If its an abstract array return a pointer to
the element type.
*---------------------------------------------------------------------*/
* parameter-type-list->types ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* translate-para-type ... */
*---------------------------------------------------------------------*/
this is the special case for no argument
prototyping | * serrano / prgm / project / bigloo / cigloo / Translate / function.scm * /
* Author : * /
* Creation : Tue Nov 28 09:49:40 1995 * /
* Last change : Sun Dec 30 09:11:05 2007 ( serrano ) * /
(module translate_function
(include "Parser/coord.sch"
"Translate/ast.sch"
"Translate/type.sch"
"Translate/function.sch")
(import engine_param
translate_type
translate_decl
translate_tspec
translate_eval
translate_ident
tools_speek
tools_error)
(export (translate-function-definition <ast>)
(translate-function-declaration <decl> <spec> <para-list>)
(translate-function-declarations)
(detect-struct-or-union <type>)
(parameter-type-list->types <ptl>)))
(define *fun-decl-list* '())
(define (translate-function-declaration decl spec para-list)
(let ((fun-decl (fun-decl decl spec para-list)))
(set! *fun-decl-list* (cons fun-decl *fun-decl-list*))))
(define (translate-function-declarations)
(define (do-translate-function-declaration fd)
(let* ((decl (fun-decl-decl fd))
(spec (fun-decl-spec fd))
(para-list (fun-decl-para-list fd))
(tspec (type-spec-of-decl-spec spec))
(type (type+decl->type (tspec->type tspec) decl))
(f-ident (get-decl-ident decl))
(f-id (ident-id f-ident)))
(verbose 2
"do-translate-function-declaration: " #\Newline
" decl: " decl #\Newline
" spec: " spec #\Newline)
[assert check (type) (function-t? type)]
(let ((sf-id (string->symbol (string-upcase f-id))))
(if (not (getprop sf-id 'fun-processed))
(begin
(putprop! sf-id 'fun-processed #t)
(verbose 1 " " f-id #\Newline)
(fprin *oport* " ("
(if *macro-function* "macro " "")
(ident->ident f-id) "::"
(type-id (function-t-to type))
" ")
(add-eval-function!
f-id
(translate-parameter
f-ident
(list 'parameter-type-list para-list)
#f))
(fprint *oport* " \"" f-id "\")"))))))
(for-each do-translate-function-declaration (reverse *fun-decl-list*))
(set! *fun-decl-list* '()))
(define (translate-function-definition ast)
(let* ((fun-decl (fun-def-decl ast))
(fun-ident (get-decl-ident fun-decl))
(fun-para-decl (get-decl-para-decl fun-decl))
(fun-id (ident-id fun-ident))
(sfun-id (string->symbol (string-upcase fun-id)))
(fun-body (fun-def-body ast)))
(if (not fun-para-decl)
(error/ast fun-id "incorrect function definition" fun-ident)
(begin
(verbose 1 " " fun-id)
(let ((sspec (storage-class-spec-of-decl-spec
(fun-def-decl-spec ast))))
(cond
((not (correct-storage-class-spec? sspec))
(error/ast (storage-class-spec-value (car sspec))
"multiple storage classes in declaration"
(car sspec)))
((or (fun-def-processed? ast)
(getprop sfun-id 'fun-processed))
(verbose 1 " (already done)" #\Newline)
#unspecified)
((and (pair? sspec)
(case (storage-class-spec-value (car sspec))
((static)
#t)
(else
#f)))
(verbose 1 " (ignored because "
(storage-class-spec-value (car sspec))
#\) #\Newline)
#unspecified)
(else
(putprop! sfun-id 'fun-processed #t)
(fun-def-processed?-set! ast #t)
(let ((tspec (type-spec-of-decl-spec
(fun-def-decl-spec ast))))
(verbose 1 #\Newline)
(display " (" *oport*)
(if *macro-function* "macro " "")
(let ((type (type+decl->type (tspec->type tspec)
fun-decl)))
[assert check (type) (function-t? type)]
(begin
(display (ident->ident fun-id) *oport*)
(display "::" *oport*)
(display (type-id (function-t-to type)) *oport*)
(display #\space *oport*)
(add-eval-function!
fun-id
(translate-parameter fun-ident
fun-para-decl
fun-body))
(display " \"" *oport*)
(display fun-id *oport*)
(display #\" *oport*))
(fprint *oport* #\)))))))))))
(define (translate-parameter fun-ident para-decl body)
(match-case para-decl
((parameter-identifier-list ?list)
(translate-para-id fun-ident list body))
((parameter-type-list ?list)
(translate-para-type list))
(else
(error "internal-error" "translate-parameter" para-decl))))
(define (translate-para-id fun-ident ident-list body)
(verbose 3 "translate-para-id: " #\Newline)
(verbose 3 "para-decl: " ident-list #\Newline)
(verbose 3 "body : " body #\Newline)
(let ((id-types (let loop ((body body)
(res '()))
(cond
((null? body)
res)
((not (declare? (car body)))
res)
(else
(let* ((declare (car body))
(spec (declare-spec declare))
(idcl (declare-init-decl-list declare))
(decl (match-case idcl
((?decl . ?-)
decl)
(?decl
decl)))
(tspec (type-spec-of-decl-spec spec))
(ident (get-decl-ident decl))
(id (ident-id ident))
(type (type+decl->type (tspec->type tspec)
decl)))
(loop (cdr body)
(cons (cons id type)
res))))))))
(map (lambda (ident)
(let ((cell (assoc (ident-id ident) id-types)))
(if (not (pair? cell))
(error/ast (ident-id fun-ident)
"missing argument types"
fun-ident)
(cdr cell))))
ident-list)))
(define (detect-struct-or-union type)
(type-case type
((typedef-t)
(detect-struct-or-union (typedef-t-alias type)))
((struct-t)
(warning "detect-struct-or-union:"
"type `" (type-c-name type)
"' used as function parameter or return type"))
(else
#t)))
(define (string-end=? string suff)
(and (string? suff)
(string? string)
(let ((sufflen (string-length suff))
(strlen (string-length string)))
(and (string? string)
(>= strlen sufflen)
(string=? (substring string (- strlen sufflen) strlen) suff)))))
(define (fix-abstract-array-type type0)
(or
(let loop ((type type0))
(type-case type
((typedef-t) (loop (typedef-t-alias type)))
((array-t)
(and (string-end=? (type-id type) "array")
(make-ptr-to (array-t-type type))))
(else #f)))
type0))
(define (parameter-type-list->types list)
(define (translate-one-para-decl p-decl previous)
(if (not (para-decl? p-decl))
(if (eq? p-decl '...)
(if (not (type? previous))
(error "parameter-type-list->types"
"incorrect paremeter-type-list"
(list))
(make-... previous))
(begin
(if (ast? p-decl)
(error/ast 'parameter-type-list->types
"Unknow expression"
p-decl)
(error 'parameter-type-list->types
"Unknow expression"
p-decl))))
(let ((tspec (para-decl-type-spec-list p-decl))
(decl (para-decl-decl p-decl)))
(if tspec
(let ((type (tspec->type tspec)))
(type+decl->type type decl))
(let* ((tspec (t-name-type-spec-list
(para-decl-type-name p-decl)))
(adecl (t-name-adecl (para-decl-type-name p-decl)))
(type (tspec->type tspec)))
(type+adecl->type type adecl))))))
(let loop ((list list)
(previous #f)
(res '()))
(if (null? list)
(reverse! res)
(let ((type (translate-one-para-decl (car list) previous)))
(detect-struct-or-union type)
(set! type (fix-abstract-array-type type))
(loop (cdr list)
type
(cons type res))))))
(define (translate-para-type list)
(let ((ptl (parameter-type-list->types list)))
(let ((par-list (if (and (pair? ptl)
(null? (cdr ptl))
(or (eq? (type-id (car ptl)) 'void)
(string=? (type-id (car ptl)) "void")))
'()
(map type-id ptl))))
(display par-list *oport*)
par-list)))
|
06bd9fc569b3511561c99115045763178c7af7e7b11863a49e5a6703a97c6d14 | schemeorg-community/index.scheme.org | srfi.78.scm | (((name . "check")
(signature
syntax-rules
(=>)
((_ expr (=> equal) expected))
((_ expr => expected)))
(subsigs (equal (value procedure?))))
((name . "check-ec")
(signature
syntax-rules
(=>)
((_ qualifier ... expr (=> equal) expected (argument ...)))
((_ qualifier ... expr => expected (argument ...)))
((_ qualifier ... expr (=> equal) expected))
((_ qualifier ... expr => expected)))
(subsigs
(qualifier
(pattern
generator
(if test)
(not test)
(and test ...)
(or test ...)
(begin command ... expression)
(nested qualifier ...)))
(equal (value procedure?))
(generator (value generator-macro))))
((name . "check-report") (signature lambda () undefined))
((name . "check-reset!") (signature lambda () undefined))
((name . "check-passed?")
(signature lambda ((integer? expected-total-count)) boolean?)))
| null | https://raw.githubusercontent.com/schemeorg-community/index.scheme.org/32e1afcfe423a158ac8ce014f5c0b8399d12a1ea/types/srfi.78.scm | scheme | (((name . "check")
(signature
syntax-rules
(=>)
((_ expr (=> equal) expected))
((_ expr => expected)))
(subsigs (equal (value procedure?))))
((name . "check-ec")
(signature
syntax-rules
(=>)
((_ qualifier ... expr (=> equal) expected (argument ...)))
((_ qualifier ... expr => expected (argument ...)))
((_ qualifier ... expr (=> equal) expected))
((_ qualifier ... expr => expected)))
(subsigs
(qualifier
(pattern
generator
(if test)
(not test)
(and test ...)
(or test ...)
(begin command ... expression)
(nested qualifier ...)))
(equal (value procedure?))
(generator (value generator-macro))))
((name . "check-report") (signature lambda () undefined))
((name . "check-reset!") (signature lambda () undefined))
((name . "check-passed?")
(signature lambda ((integer? expected-total-count)) boolean?)))
| |
2bb053a7fec05a1f1eb9283897203d90d7b1ea9018096a112bfde31cb2c8efca | grammarly/omniconf | core_test.clj | (ns omniconf.core-test
(:require [omniconf.core :as cfg]
[clojure.java.io :as io]
[clojure.test :refer :all]))
(cfg/enable-functions-as-defaults)
(cfg/define
{:help {:description "prints this help message"
:help-name "my-script"
:help-description "description of the whole script"}
:boolean-option {:description "can be either true or false"
:type :boolean}
:string-option {:type :string
:description "this option's value is taken as is"}
:integer-option {:type :number
:description "parsed as integer"}
:edn-option {:type :edn
:description "read as EDN structure"
:default '(1 2)}
:file-option {:type :file
:description "read as filename"}
:directory-option {:type :directory
:description "read as directory name"}
:option-with-default {:parser cfg/parse-number
:default 1024
:description "has a default value"}
:required-option {:type :string
:required true
:description "must have a value before call to `verify`, otherwise fails"}
:conditional-option {:parser identity
:required (fn [] (= (cfg/get :option-with-default) 2048))
:description "must have a value if a condition applies"}
:option-from-set {:type :keyword
:one-of #{:foo :bar :baz nil}
:description "value must be a member of the provided list"}
:option-from-set-with-nil {:type :keyword
:one-of #{:foo :bar nil}
:description "value must be a member of the provided list, but not required"}
:existing-file-option {:parser cfg/parse-filename
:verifier cfg/verify-file-exists
:description "file should exist"}
:nonempty-dir-option {:parser cfg/parse-filename
:verifier cfg/verify-directory-non-empty
:description "directory must have files"}
:delayed-option {:type :number
:delayed-transform (fn [v] (+ v 5))
:description "has a custom transform that is called the first time the option is read"}
:renamed-option {:type :boolean
:env-name "MY_OPTION"
:opt-name "custom-option"
:prop-name "property-custom-option"
:description "has custom names for different sources"}
:secret-option {:type :string
:secret true}
:conf-file {:type :file
:verifier cfg/verify-file-exists
:description "it is idiomatic to provide a configuration file just as another option"}
:nested-option {:description "has child options"
:default {:first "alpha"}
:nested {:first {:description "nested option one"
:type :string}
:second {:description "nested option two"
:type :number
:default 70}
:file {:description "nested file option"
:type :file}
:more {:nested {:one {:type :string
:default "one"}
:two {:type :string}}}}}
:nested-default-fn {:nested {:width {:type :number
:default 10}
:height {:type :number
:default 20}
:area {:type :number
:default #(* (cfg/get :nested-default-fn :width)
(cfg/get :nested-default-fn :height))}}}
:delayed-nested {:nested {:delayed {:default "foo"
:delayed-transform #(str % "bar")}}}})
(defn check-basic-options []
(is (nil? (cfg/verify :silent true)))
(is (= true (cfg/get :boolean-option)))
(is (= "bar" (cfg/get :string-option)))
(is (= 42 (cfg/get :integer-option)))
(is (= '(1 2 3) (cfg/get :edn-option)))
(is (= (java.io.File. "build.boot") (cfg/get :file-option)))
(is (= (java.io.File. "test/") (cfg/get :directory-option)))
(is (= 2048 (cfg/get :option-with-default)))
(is (= :baz (cfg/get :option-from-set)))
(is (= nil (cfg/get :option-from-set-with-nil)))
(is (= 15 (cfg/get :delayed-option)))
(is (= true (cfg/get :renamed-option)))
(is (= {:first "alpha", :more {:two "two"}, :second 70} (cfg/get :nested-option)))
(is (= "alpha" (cfg/get :nested-option :first)))
(is (= 70 (cfg/get :nested-option :second)))
(is (= {:two "two"} (cfg/get :nested-option :more)))
(is (= "two" (cfg/get :nested-option :more :two))))
(deftest basic-options-cmd
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/populate-from-cmd
["--required-option" "foo" "--string-option" "bar"
"--integer-option" "42" "--edn-option" "^:concat (3)" "--file-option" "build.boot"
"--directory-option" "test" "--option-with-default" "2048"
"--conditional-option" "dummy" "--option-from-set" "baz"
"--delayed-option" "10" "--custom-option" "--nested-option.more" "{}"
"--nested-option.more.two" "two" "--boolean-option"])
(check-basic-options))
(deftest basic-options-prop
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(System/setProperty "required-option" "foo")
(System/setProperty "string-option" "bar")
(System/setProperty "integer-option" "42")
(System/setProperty "edn-option" "^:concat (3)")
(System/setProperty "file-option" "build.boot")
(System/setProperty "directory-option" "test")
(System/setProperty "option-with-default" "2048")
(System/setProperty "conditional-option" "dummy")
(System/setProperty "option-from-set" "baz")
(System/setProperty "delayed-option" "10")
(System/setProperty "property-custom-option" "true")
(System/setProperty "nested-option.more" "{}")
(System/setProperty "nested-option.more.two" "two")
(System/setProperty "boolean-option" "true")
(cfg/populate-from-properties)
(check-basic-options))
(deftest basic-options-map
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/populate-from-map {:nested-option {:more {}}})
;; Hack because setting from map doesn't allow overriding whole nested maps.
(cfg/set :nested-option :more {})
(cfg/populate-from-map {:required-option "foo"
:string-option "bar"
:integer-option 42
:edn-option "^:concat (3)"
:file-option "build.boot"
:directory-option "test"
:option-with-default 2048
:conditional-option "dummy"
:option-from-set "baz"
:delayed-option 10
:renamed-option true
:nested-option {:more {:two "two"}}
:boolean-option true})
(check-basic-options))
(deftest basic-options-file
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
;; Hack because setting from file doesn't allow overriding whole nested maps.
(cfg/set :nested-option :more {})
(cfg/populate-from-file "test/omniconf/test-config.edn")
(check-basic-options))
(deftest extended-functionality
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/populate-from-cmd
["--required-option" "foo" "--string-option" "bar"
"--integer-option" "42" "--file-option" "build.boot"
"--directory-option" "test" "--option-with-default" "2048"
"--conditional-option" "dummy" "--option-from-set" "baz"
"--delayed-option" "10" "--custom-option" "--nested-option.more" "{}"
"--nested-option.more.two" "two" "--boolean-option"])
(testing "fine-so-far"
(is (nil? (cfg/verify :silent true))))
(testing "required"
(cfg/set :required-option nil)
(is (thrown? Exception (cfg/verify)))
(cfg/set :required-option "foo"))
(testing "one-of"
(cfg/set :option-from-set :bar)
(is (nil? (cfg/verify :silent true)))
(cfg/set :option-from-set :notbar)
(is (thrown? Exception (cfg/verify)))
(cfg/set :option-from-set :bar))
(testing "conditional-required"
(cfg/set :option-with-default 2048)
(cfg/set :conditional-option "foo")
(is (nil? (cfg/verify :silent true)))
(cfg/set :conditional-option nil)
(is (thrown? Exception (cfg/verify)))
(cfg/set :option-with-default 1024)
(is (nil? (cfg/verify :silent true))))
(testing "delayed transform works for nested values"
(is (= "foobar" (cfg/get :delayed-nested :delayed))))
(testing "secret"
(cfg/set :secret-option "very-sensitive-data")
(is (= -1 (.indexOf (with-out-str (cfg/verify)) "very-sensitive-data"))))
(testing "verify-file-exists"
(cfg/set :existing-file-option (io/file "nada.clj"))
(is (thrown? Exception (cfg/verify)))
(cfg/set :existing-file-option (io/file "build.boot")))
(testing "verify-nonempty-dir"
(.mkdirs (io/file "target" "_empty_"))
(cfg/set :nonempty-dir-option (io/file "target" "_empty_"))
(is (thrown? Exception (cfg/verify)))
(cfg/set :nonempty-dir-option (io/file "test")))
(testing "populate-from-opts"
(is (thrown? Exception (cfg/populate-from-cmd ["--string-option" "bar" "baz"]))))
(testing "print-cli-help"
(is (not= "" (with-out-str (#'cfg/print-cli-help)))))
(testing "with-options"
(cfg/with-options [option-with-default]
(is (= 1024 option-with-default))))
(testing "populate-from-env"
(cfg/populate-from-env)
(cfg/verify :silent true))
(testing "populate-from-file"
(cfg/populate-from-file "test/omniconf/test-config.edn")
(cfg/verify :silent true))
(testing "parsing sanity-check"
(is (thrown? Exception (cfg/populate-from-cmd ["--nested-option" "foo"])))
(is (thrown? Exception (cfg/populate-from-cmd ["--integer-option" "garbage"]))))
(testing "default functions"
(is (= {:area 200, :height 20, :width 10} (cfg/get :nested-default-fn)))
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/populate-from-file "test/omniconf/test-config.edn")
(cfg/populate-from-map {:nested-default-fn {:width 100 :height 200}})
(cfg/verify)
(is (= {:area 20000, :height 200, :width 100} (cfg/get :nested-default-fn)))
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/populate-from-file "test/omniconf/test-config.edn")
(cfg/populate-from-map {:nested-default-fn {:width 100 :height 200 :area 42}})
(cfg/verify)
(is (= {:area 42, :height 200, :width 100} (cfg/get :nested-default-fn))))
)
| null | https://raw.githubusercontent.com/grammarly/omniconf/588e9e9200509f7c6afe1ff5f2bddad7bab5b0a4/test/omniconf/core_test.clj | clojure | Hack because setting from map doesn't allow overriding whole nested maps.
Hack because setting from file doesn't allow overriding whole nested maps. | (ns omniconf.core-test
(:require [omniconf.core :as cfg]
[clojure.java.io :as io]
[clojure.test :refer :all]))
(cfg/enable-functions-as-defaults)
(cfg/define
{:help {:description "prints this help message"
:help-name "my-script"
:help-description "description of the whole script"}
:boolean-option {:description "can be either true or false"
:type :boolean}
:string-option {:type :string
:description "this option's value is taken as is"}
:integer-option {:type :number
:description "parsed as integer"}
:edn-option {:type :edn
:description "read as EDN structure"
:default '(1 2)}
:file-option {:type :file
:description "read as filename"}
:directory-option {:type :directory
:description "read as directory name"}
:option-with-default {:parser cfg/parse-number
:default 1024
:description "has a default value"}
:required-option {:type :string
:required true
:description "must have a value before call to `verify`, otherwise fails"}
:conditional-option {:parser identity
:required (fn [] (= (cfg/get :option-with-default) 2048))
:description "must have a value if a condition applies"}
:option-from-set {:type :keyword
:one-of #{:foo :bar :baz nil}
:description "value must be a member of the provided list"}
:option-from-set-with-nil {:type :keyword
:one-of #{:foo :bar nil}
:description "value must be a member of the provided list, but not required"}
:existing-file-option {:parser cfg/parse-filename
:verifier cfg/verify-file-exists
:description "file should exist"}
:nonempty-dir-option {:parser cfg/parse-filename
:verifier cfg/verify-directory-non-empty
:description "directory must have files"}
:delayed-option {:type :number
:delayed-transform (fn [v] (+ v 5))
:description "has a custom transform that is called the first time the option is read"}
:renamed-option {:type :boolean
:env-name "MY_OPTION"
:opt-name "custom-option"
:prop-name "property-custom-option"
:description "has custom names for different sources"}
:secret-option {:type :string
:secret true}
:conf-file {:type :file
:verifier cfg/verify-file-exists
:description "it is idiomatic to provide a configuration file just as another option"}
:nested-option {:description "has child options"
:default {:first "alpha"}
:nested {:first {:description "nested option one"
:type :string}
:second {:description "nested option two"
:type :number
:default 70}
:file {:description "nested file option"
:type :file}
:more {:nested {:one {:type :string
:default "one"}
:two {:type :string}}}}}
:nested-default-fn {:nested {:width {:type :number
:default 10}
:height {:type :number
:default 20}
:area {:type :number
:default #(* (cfg/get :nested-default-fn :width)
(cfg/get :nested-default-fn :height))}}}
:delayed-nested {:nested {:delayed {:default "foo"
:delayed-transform #(str % "bar")}}}})
(defn check-basic-options []
(is (nil? (cfg/verify :silent true)))
(is (= true (cfg/get :boolean-option)))
(is (= "bar" (cfg/get :string-option)))
(is (= 42 (cfg/get :integer-option)))
(is (= '(1 2 3) (cfg/get :edn-option)))
(is (= (java.io.File. "build.boot") (cfg/get :file-option)))
(is (= (java.io.File. "test/") (cfg/get :directory-option)))
(is (= 2048 (cfg/get :option-with-default)))
(is (= :baz (cfg/get :option-from-set)))
(is (= nil (cfg/get :option-from-set-with-nil)))
(is (= 15 (cfg/get :delayed-option)))
(is (= true (cfg/get :renamed-option)))
(is (= {:first "alpha", :more {:two "two"}, :second 70} (cfg/get :nested-option)))
(is (= "alpha" (cfg/get :nested-option :first)))
(is (= 70 (cfg/get :nested-option :second)))
(is (= {:two "two"} (cfg/get :nested-option :more)))
(is (= "two" (cfg/get :nested-option :more :two))))
(deftest basic-options-cmd
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/populate-from-cmd
["--required-option" "foo" "--string-option" "bar"
"--integer-option" "42" "--edn-option" "^:concat (3)" "--file-option" "build.boot"
"--directory-option" "test" "--option-with-default" "2048"
"--conditional-option" "dummy" "--option-from-set" "baz"
"--delayed-option" "10" "--custom-option" "--nested-option.more" "{}"
"--nested-option.more.two" "two" "--boolean-option"])
(check-basic-options))
(deftest basic-options-prop
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(System/setProperty "required-option" "foo")
(System/setProperty "string-option" "bar")
(System/setProperty "integer-option" "42")
(System/setProperty "edn-option" "^:concat (3)")
(System/setProperty "file-option" "build.boot")
(System/setProperty "directory-option" "test")
(System/setProperty "option-with-default" "2048")
(System/setProperty "conditional-option" "dummy")
(System/setProperty "option-from-set" "baz")
(System/setProperty "delayed-option" "10")
(System/setProperty "property-custom-option" "true")
(System/setProperty "nested-option.more" "{}")
(System/setProperty "nested-option.more.two" "two")
(System/setProperty "boolean-option" "true")
(cfg/populate-from-properties)
(check-basic-options))
(deftest basic-options-map
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/populate-from-map {:nested-option {:more {}}})
(cfg/set :nested-option :more {})
(cfg/populate-from-map {:required-option "foo"
:string-option "bar"
:integer-option 42
:edn-option "^:concat (3)"
:file-option "build.boot"
:directory-option "test"
:option-with-default 2048
:conditional-option "dummy"
:option-from-set "baz"
:delayed-option 10
:renamed-option true
:nested-option {:more {:two "two"}}
:boolean-option true})
(check-basic-options))
(deftest basic-options-file
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/set :nested-option :more {})
(cfg/populate-from-file "test/omniconf/test-config.edn")
(check-basic-options))
(deftest extended-functionality
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/populate-from-cmd
["--required-option" "foo" "--string-option" "bar"
"--integer-option" "42" "--file-option" "build.boot"
"--directory-option" "test" "--option-with-default" "2048"
"--conditional-option" "dummy" "--option-from-set" "baz"
"--delayed-option" "10" "--custom-option" "--nested-option.more" "{}"
"--nested-option.more.two" "two" "--boolean-option"])
(testing "fine-so-far"
(is (nil? (cfg/verify :silent true))))
(testing "required"
(cfg/set :required-option nil)
(is (thrown? Exception (cfg/verify)))
(cfg/set :required-option "foo"))
(testing "one-of"
(cfg/set :option-from-set :bar)
(is (nil? (cfg/verify :silent true)))
(cfg/set :option-from-set :notbar)
(is (thrown? Exception (cfg/verify)))
(cfg/set :option-from-set :bar))
(testing "conditional-required"
(cfg/set :option-with-default 2048)
(cfg/set :conditional-option "foo")
(is (nil? (cfg/verify :silent true)))
(cfg/set :conditional-option nil)
(is (thrown? Exception (cfg/verify)))
(cfg/set :option-with-default 1024)
(is (nil? (cfg/verify :silent true))))
(testing "delayed transform works for nested values"
(is (= "foobar" (cfg/get :delayed-nested :delayed))))
(testing "secret"
(cfg/set :secret-option "very-sensitive-data")
(is (= -1 (.indexOf (with-out-str (cfg/verify)) "very-sensitive-data"))))
(testing "verify-file-exists"
(cfg/set :existing-file-option (io/file "nada.clj"))
(is (thrown? Exception (cfg/verify)))
(cfg/set :existing-file-option (io/file "build.boot")))
(testing "verify-nonempty-dir"
(.mkdirs (io/file "target" "_empty_"))
(cfg/set :nonempty-dir-option (io/file "target" "_empty_"))
(is (thrown? Exception (cfg/verify)))
(cfg/set :nonempty-dir-option (io/file "test")))
(testing "populate-from-opts"
(is (thrown? Exception (cfg/populate-from-cmd ["--string-option" "bar" "baz"]))))
(testing "print-cli-help"
(is (not= "" (with-out-str (#'cfg/print-cli-help)))))
(testing "with-options"
(cfg/with-options [option-with-default]
(is (= 1024 option-with-default))))
(testing "populate-from-env"
(cfg/populate-from-env)
(cfg/verify :silent true))
(testing "populate-from-file"
(cfg/populate-from-file "test/omniconf/test-config.edn")
(cfg/verify :silent true))
(testing "parsing sanity-check"
(is (thrown? Exception (cfg/populate-from-cmd ["--nested-option" "foo"])))
(is (thrown? Exception (cfg/populate-from-cmd ["--integer-option" "garbage"]))))
(testing "default functions"
(is (= {:area 200, :height 20, :width 10} (cfg/get :nested-default-fn)))
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/populate-from-file "test/omniconf/test-config.edn")
(cfg/populate-from-map {:nested-default-fn {:width 100 :height 200}})
(cfg/verify)
(is (= {:area 20000, :height 200, :width 100} (cfg/get :nested-default-fn)))
(reset! @#'cfg/config-values (sorted-map))
(#'cfg/fill-default-values)
(cfg/populate-from-file "test/omniconf/test-config.edn")
(cfg/populate-from-map {:nested-default-fn {:width 100 :height 200 :area 42}})
(cfg/verify)
(is (= {:area 42, :height 200, :width 100} (cfg/get :nested-default-fn))))
)
|
dd92dd11a187814c04f00d4dcf13bb20c42922a7204917a8db15ae734327dfeb | fission-codes/fission | Natural.hs | # OPTIONS_GHC -fno - warn - orphans #
# OPTIONS_GHC -fno - warn - missing - methods #
module Network.IPFS.Internal.Orphanage.Natural () where
import System.Envy
import Network.IPFS.Prelude
instance Display Natural where
display nat = display (fromIntegral nat :: Integer)
instance Var Natural where
fromVar = readMaybe
| null | https://raw.githubusercontent.com/fission-codes/fission/fb76d255f06ea73187c9b787bd207c3778e1b559/ipfs/library/Network/IPFS/Internal/Orphanage/Natural.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
# OPTIONS_GHC -fno - warn - missing - methods #
module Network.IPFS.Internal.Orphanage.Natural () where
import System.Envy
import Network.IPFS.Prelude
instance Display Natural where
display nat = display (fromIntegral nat :: Integer)
instance Var Natural where
fromVar = readMaybe
| |
1717f2939395d06d84174fb4b9d682935310f87e734dd46c9cfb38366fc84621 | facebookarchive/duckling_old | measure.clj | (
;; Distance
; latent distance
"number as distance"
(dim :number)
{:dim :distance
:latent true
:value (:value %1)}
"<latent dist> km"
[(dim :distance) #"(?i)k(ilo)?m?([eéè]tre)?s?"]
(-> %1
(dissoc :latent)
(merge {:unit "kilometre"
:normalized {:value (* 1000 (-> %1 :value))
:unit "metre"}}))
"<dist> meters"
[(dim :distance) #"(?i)m([eéè]tres?)?"]
(-> %1
(dissoc :latent)
(merge {:unit "metre"}))
"<dist> centimeters"
[(dim :distance) #"(?i)cm|centimetres?"]
(-> %1
(dissoc :latent)
(merge {:unit "centimetre"
:normalized {:value (* 0.01 (-> %1 :value))
:unit "metre"}}))
"<dist> miles"
[(dim :distance) #"(?i)miles?"]
(-> %1
(dissoc :latent)
(merge {:unit "mile"
:normalized {:value (* 1609 (-> %1 :value))
:unit "metre"}}))
;; volume
; latent volume
"number as volume"
(dim :number)
{:dim :volume
:latent true
:value (:value %1)}
"<latent vol> ml"
[(dim :volume) #"(?i)m(l|illilitres?)"]
(-> %1
(dissoc :latent)
(merge {:unit "millilitre"
:normalized {:value (* 0.001 (-> %1 :value))
:unit "litre"}}))
"<vol> hectoliters"
[(dim :volume) #"(?i)hectolitres?"]
(-> %1
(dissoc :latent)
(merge {:unit "hectolitre"
:normalized {:value (* 100 (-> %1 :value))
:unit "litre"}}))
"<vol> liters"
[(dim :volume) #"(?i)l(itres?)?"]
(-> %1
(dissoc :latent)
(merge {:unit "litre"}))
"half liter"
[#"(?i)demi( |-)?litre"]
(-> %1
(dissoc :latent)
(merge {:unit "litre"
:value 0.5}))
"<latent vol> gallon"
[(dim :volume) #"(?i)gal(l?ons?)?"]
(-> %1
(dissoc :latent)
(merge {:unit "gallon"
:normalized {:value (* 3.785 (-> %1 :value))
:unit "litre"}}))
;; Quantity
three teaspoons
"<number> <units>"
[(dim :number) (dim :leven-unit)]
{:dim :quantity
:value (:value %1)
:unit (:value %2)
:form :no-product}
; a pound
"a <unit>"
[#"(?i)an?" (dim :leven-unit)]
{:dim :quantity
:value 1
:unit (:value %2)
:form :no-product}
3 pounds of flour
"<quantity> of product"
[(dim :quantity #(= :no-product (:form %))) #"(?i)de" (dim :leven-product)]
(-> %1
(assoc :product (:value %3))
(dissoc :form))
2 apples
"<number> product"
[(dim :number) (dim :leven-product)]
{:dim :quantity
:value (:value %1)
:product (:value %2)}
; an apple
"a <product>"
[#"(?i)une?" (dim :leven-product)]
{:dim :quantity
:value 1
:product (:value %2)}
for corpus
"tasse"
#"tasses?"
{:dim :leven-unit :value "tasse"}
"café"
#"caf[eé]"
{:dim :leven-product :value "café"}
"cuillere a soupe"
#"cuill?[eè]res? à soupe?"
{:dim :leven-unit :value "cuillère à soupe"}
"sucre"
#"sucre"
{:dim :leven-product :value "sucre"}
) | null | https://raw.githubusercontent.com/facebookarchive/duckling_old/bf5bb9758c36313b56e136a28ba401696eeff10b/resources/languages/fr/rules/measure.clj | clojure | Distance
latent distance
volume
latent volume
Quantity
a pound
an apple | (
"number as distance"
(dim :number)
{:dim :distance
:latent true
:value (:value %1)}
"<latent dist> km"
[(dim :distance) #"(?i)k(ilo)?m?([eéè]tre)?s?"]
(-> %1
(dissoc :latent)
(merge {:unit "kilometre"
:normalized {:value (* 1000 (-> %1 :value))
:unit "metre"}}))
"<dist> meters"
[(dim :distance) #"(?i)m([eéè]tres?)?"]
(-> %1
(dissoc :latent)
(merge {:unit "metre"}))
"<dist> centimeters"
[(dim :distance) #"(?i)cm|centimetres?"]
(-> %1
(dissoc :latent)
(merge {:unit "centimetre"
:normalized {:value (* 0.01 (-> %1 :value))
:unit "metre"}}))
"<dist> miles"
[(dim :distance) #"(?i)miles?"]
(-> %1
(dissoc :latent)
(merge {:unit "mile"
:normalized {:value (* 1609 (-> %1 :value))
:unit "metre"}}))
"number as volume"
(dim :number)
{:dim :volume
:latent true
:value (:value %1)}
"<latent vol> ml"
[(dim :volume) #"(?i)m(l|illilitres?)"]
(-> %1
(dissoc :latent)
(merge {:unit "millilitre"
:normalized {:value (* 0.001 (-> %1 :value))
:unit "litre"}}))
"<vol> hectoliters"
[(dim :volume) #"(?i)hectolitres?"]
(-> %1
(dissoc :latent)
(merge {:unit "hectolitre"
:normalized {:value (* 100 (-> %1 :value))
:unit "litre"}}))
"<vol> liters"
[(dim :volume) #"(?i)l(itres?)?"]
(-> %1
(dissoc :latent)
(merge {:unit "litre"}))
"half liter"
[#"(?i)demi( |-)?litre"]
(-> %1
(dissoc :latent)
(merge {:unit "litre"
:value 0.5}))
"<latent vol> gallon"
[(dim :volume) #"(?i)gal(l?ons?)?"]
(-> %1
(dissoc :latent)
(merge {:unit "gallon"
:normalized {:value (* 3.785 (-> %1 :value))
:unit "litre"}}))
three teaspoons
"<number> <units>"
[(dim :number) (dim :leven-unit)]
{:dim :quantity
:value (:value %1)
:unit (:value %2)
:form :no-product}
"a <unit>"
[#"(?i)an?" (dim :leven-unit)]
{:dim :quantity
:value 1
:unit (:value %2)
:form :no-product}
3 pounds of flour
"<quantity> of product"
[(dim :quantity #(= :no-product (:form %))) #"(?i)de" (dim :leven-product)]
(-> %1
(assoc :product (:value %3))
(dissoc :form))
2 apples
"<number> product"
[(dim :number) (dim :leven-product)]
{:dim :quantity
:value (:value %1)
:product (:value %2)}
"a <product>"
[#"(?i)une?" (dim :leven-product)]
{:dim :quantity
:value 1
:product (:value %2)}
for corpus
"tasse"
#"tasses?"
{:dim :leven-unit :value "tasse"}
"café"
#"caf[eé]"
{:dim :leven-product :value "café"}
"cuillere a soupe"
#"cuill?[eè]res? à soupe?"
{:dim :leven-unit :value "cuillère à soupe"}
"sucre"
#"sucre"
{:dim :leven-product :value "sucre"}
) |
139dc49e4eddeebbfe8fe6f0695a972e0470b78a1ecfba217fd247b562308ece | softlab-ntua/bencherl | deployment_firewall_restriction_test.erl | Copyright ( C ) 2008 - 2014 EDF R&D
This file is part of Sim - Diasca .
Sim - Diasca is free software : you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
Sim - Diasca is distributed in the hope that it will be useful ,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with .
% If not, see </>.
Author : ( )
Overall unit test of the Sim - Diasca management of firewall restrictions .
%
-module(deployment_firewall_restriction_test).
% For all facilities common to all tests:
-include("test_constructs.hrl").
% Runs a distributed simulation (of course if relevant computing hosts are
% specified).
%
-spec run() -> no_return().
run() ->
?test_start,
Default simulation settings ( 50Hz , batch reproducible ) are used , except
% for the name:
SimulationSettings = #simulation_settings{
simulation_name = "Test of the management of firewall restrictions"
},
% Default deployment settings (unavailable nodes allowed, on-the-fly
% generation of the deployment package requested), but computing
% hosts are specified (to be updated depending on your environment):
% (note that localhost is implied)
% Here we request the deployment package to be created:
DeploymentSettings = #deployment_settings{
computing_hosts =
{ use_host_file_otherwise_local, "sim-diasca-host-candidates.txt" },
perform_initial_node_cleanup = true,
firewall_restrictions = [
% Uncomment next line and modify accordingly
common / GNUmakevars.inc to test the change in EPMD
% port:
%{ epmd_port, 4000 },
{ tcp_restricted_range,
{ _MinPort=30000, _MaxPort=35000 } }
]
},
?test_warning( "By default this test will not use an alternate EPMD port, "
"as the overall engine settings have to be changed accordingly "
"for this test to succeed." ),
% Default load balancing settings (round-robin placement heuristic):
LoadBalancingSettings = #load_balancing_settings{},
?test_info_fmt( "This test will deploy a distributed simulation"
" based on computing hosts specified as ~p.",
[ DeploymentSettings#deployment_settings.computing_hosts ] ),
% Directly created on the user node:
DeploymentManagerPid = sim_diasca:init( SimulationSettings,
DeploymentSettings, LoadBalancingSettings ),
?test_info( "Here we do not create any actor, "
"thus the simulation will stop immediately." ),
DeploymentManagerPid ! { getRootTimeManager, [], self() },
RootTimeManagerPid = test_receive(),
?test_info( "Starting simulation." ),
RootTimeManagerPid ! { start, [ _StopTick=120, self() ] },
% Waits until simulation is finished:
receive
simulation_stopped ->
?test_info( "Simulation stopped spontaneously." )
end,
?test_info( "Requesting textual timings (second)." ),
sim_diasca:shutdown(),
?test_stop.
| null | https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/sim-diasca/sim-diasca/src/core/src/scheduling/tests/deployment_firewall_restriction_test.erl | erlang | it under the terms of the GNU Lesser General Public License as
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
If not, see </>.
For all facilities common to all tests:
Runs a distributed simulation (of course if relevant computing hosts are
specified).
for the name:
Default deployment settings (unavailable nodes allowed, on-the-fly
generation of the deployment package requested), but computing
hosts are specified (to be updated depending on your environment):
(note that localhost is implied)
Here we request the deployment package to be created:
Uncomment next line and modify accordingly
port:
{ epmd_port, 4000 },
Default load balancing settings (round-robin placement heuristic):
Directly created on the user node:
Waits until simulation is finished: | Copyright ( C ) 2008 - 2014 EDF R&D
This file is part of Sim - Diasca .
Sim - Diasca is free software : you can redistribute it and/or modify
published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
Sim - Diasca is distributed in the hope that it will be useful ,
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with .
Author : ( )
Overall unit test of the Sim - Diasca management of firewall restrictions .
-module(deployment_firewall_restriction_test).
-include("test_constructs.hrl").
-spec run() -> no_return().
run() ->
?test_start,
Default simulation settings ( 50Hz , batch reproducible ) are used , except
SimulationSettings = #simulation_settings{
simulation_name = "Test of the management of firewall restrictions"
},
DeploymentSettings = #deployment_settings{
computing_hosts =
{ use_host_file_otherwise_local, "sim-diasca-host-candidates.txt" },
perform_initial_node_cleanup = true,
firewall_restrictions = [
common / GNUmakevars.inc to test the change in EPMD
{ tcp_restricted_range,
{ _MinPort=30000, _MaxPort=35000 } }
]
},
?test_warning( "By default this test will not use an alternate EPMD port, "
"as the overall engine settings have to be changed accordingly "
"for this test to succeed." ),
LoadBalancingSettings = #load_balancing_settings{},
?test_info_fmt( "This test will deploy a distributed simulation"
" based on computing hosts specified as ~p.",
[ DeploymentSettings#deployment_settings.computing_hosts ] ),
DeploymentManagerPid = sim_diasca:init( SimulationSettings,
DeploymentSettings, LoadBalancingSettings ),
?test_info( "Here we do not create any actor, "
"thus the simulation will stop immediately." ),
DeploymentManagerPid ! { getRootTimeManager, [], self() },
RootTimeManagerPid = test_receive(),
?test_info( "Starting simulation." ),
RootTimeManagerPid ! { start, [ _StopTick=120, self() ] },
receive
simulation_stopped ->
?test_info( "Simulation stopped spontaneously." )
end,
?test_info( "Requesting textual timings (second)." ),
sim_diasca:shutdown(),
?test_stop.
|
3f9147ddd556f5e26e931544743b2c34d3125d280439b1335fbdbcc485351596 | geoffder/dometyl-keyboard | snapper.ml | open OSCADml
let () =
let f i =
let n = Filename.(chop_extension @@ basename Sys.argv.(i + 1)) ^ ".png" in
let f e = Printf.printf "Failed to take snapshot %s:\n%s\n%!" n e in
Export.(
snapshot
~colorscheme:TomorrowNight
~size:(1000, 1000)
~view:[ Axes; Scales ]
n
Sys.argv.(i + 1))
|> Result.iter_error f
in
List.init (Array.length Sys.argv - 1) (Thread.create f) |> List.iter Thread.join
| null | https://raw.githubusercontent.com/geoffder/dometyl-keyboard/12ea44abf3e52de9a3b4624c8349457e7b770cb4/dune_helpers/snapper.ml | ocaml | open OSCADml
let () =
let f i =
let n = Filename.(chop_extension @@ basename Sys.argv.(i + 1)) ^ ".png" in
let f e = Printf.printf "Failed to take snapshot %s:\n%s\n%!" n e in
Export.(
snapshot
~colorscheme:TomorrowNight
~size:(1000, 1000)
~view:[ Axes; Scales ]
n
Sys.argv.(i + 1))
|> Result.iter_error f
in
List.init (Array.length Sys.argv - 1) (Thread.create f) |> List.iter Thread.join
| |
c52a22fab09f40cac951c09d7d763fff1a20610a17f8c6278b89d81b68382f54 | facundoolano/advenjure | verb_map.cljc | (ns advenjure.verb-map
(:require [advenjure.verbs :as verbs]
#?(:cljs [xregexp])))
(defn expand-verb
"Creates a map of command regexes to handler for the given verb spec."
[{:keys [commands handler]}]
(let [patterns (map #(str "^" % "$") commands)]
(zipmap patterns (repeat handler))))
(def default-map (apply merge (map expand-verb verbs/verbs)))
use a sorted version to extract the longest possible form first
(defn sort-verbs [verb-map] (reverse (sort-by count (keys verb-map))))
(def msort-verbs (memoize sort-verbs))
(def regexp #?(:clj re-pattern :cljs js/XRegExp))
(defn match-verb [text verb]
(let [[head & tokens :as full] (re-find (regexp verb) text)]
(cond
(and (not (nil? full)) (not (coll? full))) [verb '()] ;single match, no params
(not-empty head) [verb tokens]))) ; match with params
(defn find-verb
"Return [verb tokens] if there's a proper verb at the beginning of text."
[verb-map text]
(some (partial match-verb text) (msort-verbs verb-map)))
| null | https://raw.githubusercontent.com/facundoolano/advenjure/2f05fdae9439ab8830753cc5ef378be66b7db6ef/src/advenjure/verb_map.cljc | clojure | single match, no params
match with params | (ns advenjure.verb-map
(:require [advenjure.verbs :as verbs]
#?(:cljs [xregexp])))
(defn expand-verb
"Creates a map of command regexes to handler for the given verb spec."
[{:keys [commands handler]}]
(let [patterns (map #(str "^" % "$") commands)]
(zipmap patterns (repeat handler))))
(def default-map (apply merge (map expand-verb verbs/verbs)))
use a sorted version to extract the longest possible form first
(defn sort-verbs [verb-map] (reverse (sort-by count (keys verb-map))))
(def msort-verbs (memoize sort-verbs))
(def regexp #?(:clj re-pattern :cljs js/XRegExp))
(defn match-verb [text verb]
(let [[head & tokens :as full] (re-find (regexp verb) text)]
(cond
(defn find-verb
"Return [verb tokens] if there's a proper verb at the beginning of text."
[verb-map text]
(some (partial match-verb text) (msort-verbs verb-map)))
|
7a84be47757f7d816c1c826e7e0f9c83c3392cde6df43c47d0d903ebf8417dbc | 0xfei/mnesia_redis | mnesis_help.erl | -module(mnesis_help).
%% API
-export([
lower_binary/1, find_number/2, pattern_match/2,
binary_to_number/1, number_to_binary/1,
join_list/2, calc_index/2,
add_elements/3, remove_elements/3,
add_hash/2, remove_hash/3,
add_orddict/4, del_orddict/4,
list_find_low/4, list_find_high/4,
add_key_expire/3, get_expire_time/2, del_expire_time/2]
).
-define(EXPIRE_KEY, expire).
-define(LIMIT_MAX, 999999).
< < " ABC " > > - > < < " abc " > >
-spec lower_binary(Data::binary()) -> New::binary().
lower_binary(Data) ->
lower_binary(Data, <<>>).
lower_binary(<<>>, Binary) ->
Binary;
lower_binary(<<H:8, Left/binary>>, Binary) when H >= $A andalso H =< $Z ->
T = H - $A + $a,
lower_binary(Left, <<Binary/binary, T:8>>);
lower_binary(<<H:8, Left/binary>>, Binary) ->
lower_binary(Left, <<Binary/binary, H:8>>).
find_number < < " " > > - > { 123 , Binary }
-spec find_number(Data::binary(), Initialize::integer()) ->
{Number::integer(), Bin::binary()}.
find_number(<<Num/integer, Data/binary>>, Now) when Num >= $0 andalso Num =< $9 ->
find_number(Data, Now*10+Num-$0);
find_number(<<$\r, $\n, Data/binary>>, Now) ->
{Now, Data}.
pattern_match , only 1 * now
-spec pattern_match(M::binary(), P::binary()) -> true | false.
pattern_match(M, P) ->
int_match(M, P).
int_match(<<>>, <<>>) ->
true;
int_match(_L1, <<$*>>) ->
true;
int_match(L1, L2 = <<$*, _L2/binary>>) ->
list_match(
lists:reverse(binary_to_list(L1)),
lists:reverse(binary_to_list(L2))
);
int_match(<<_H:8, L1/binary>>, <<H:8, L2/binary>>) when H == $? ->
int_match(L1, L2);
int_match(<<H:8, L1/binary>>, <<H:8, L2/binary>>) ->
int_match(L1, L2);
int_match(_L1, _L2) ->
false.
list_match([], []) ->
true;
list_match([H|T], [H|T2]) ->
list_match(T, T2);
list_match([_H|T], [H|T2]) when H == $? ->
list_match(T, T2);
list_match(_L1, [H|_L2]) when H == $* ->
true;
list_match(_, _) ->
false.
%% join_list
-spec join_list(L1::list(), L2::list()) -> L3::list().
join_list(L1, L2) ->
join_list_internal(lists:reverse(L1), L2).
join_list_internal([], L2) ->
L2;
join_list_internal([H|L1], L2) ->
join_list_internal(L1, [H|L2]).
%% calc_index
%% using with try
-spec calc_index(Offset::binary(), M::integer()) -> Index::integer().
calc_index(Offset, M) ->
I = binary_to_integer(Offset),
if
I < 0 andalso I + M >= 0 ->
M + I + 1;
I >= 0 andalso I < M ->
I + 1;
true ->
throw("Too long")
end.
%% list_find_low
list_find_low(_List, _Value, S, E) when S > E ->
S;
list_find_low(List, Value, S, E) ->
Mid = (S + E + 1) div 2,
{Score, _Bin, _Key} = lists:nth(Mid, List),
if
Score >= Value -> list_find_low(List, Value, S, Mid-1);
true -> list_find_low(List, Value, Mid+1, E)
end.
%% list_find_high
list_find_high(_List, _Value, S, E) when S > E ->
E;
list_find_high(List, Value, S, E) ->
Mid = (S + E + 1) div 2,
{Score, _Bin, _Key} = lists:nth(Mid, List),
if
Score =< Value -> list_find_high(List, Value, Mid+1, E);
true -> list_find_high(List, Value, S, Mid-1)
end.
%% binary_to_number
-spec binary_to_number(B::binary()) -> integer() | float() .
binary_to_number(B) ->
try
binary_to_integer(B)
catch _:_ ->
binary_to_float(B)
end.
%% number_to_binary
-spec number_to_binary(B::integer() | float()) -> binary().
number_to_binary(B) ->
try
integer_to_binary(B)
catch _:_ ->
float_to_binary(B)
end.
%% insert sets
-spec add_elements(E::list(), Set::sets:set(), N::integer()) ->
NSet::sets:set().
add_elements([], Set, N) ->
{N, Set};
add_elements([H|T], Set, N) ->
case sets:is_element(H, Set) of
true ->
add_elements(T, Set, N);
_ ->
add_elements(T, sets:add_element(H, Set), N+1)
end.
%% remove sets
-spec remove_elements(E::list(), Set::sets:set(), N::integer()) ->
NSet::sets:set().
remove_elements([], Set, N) ->
{N, Set};
remove_elements([H|T], Set, N) ->
case sets:is_element(H, Set) of
true ->
remove_elements(T, sets:del_element(H, Set), N+1);
_ ->
remove_elements(T, Set, N)
end.
%% add multi hash
-spec add_hash(E::list(), Map::#{}) -> NMap::#{}.
add_hash([], Map) ->
Map;
add_hash([K, V|Left], Map) ->
add_hash(Left, maps:put(K, V, Map)).
%% remove hash
-spec remove_hash(E::list(), Set::#{}, N::integer()) ->
NSet::#{}.
remove_hash([], Map, N) ->
{N, Map};
remove_hash([H|T], Map, N) ->
case maps:is_key(H, Map) of
true ->
remove_hash(T, maps:remove(H, Map), N+1);
_ ->
remove_hash(T, Map, N)
end.
%% add orddict
-spec add_orddict(E::list(), Set::ordsets:set(), Dict::dict:dict(), N::integer()) ->
{C::integer(), NewSet::ordsets:set(), NewDict::dict:dict()}.
add_orddict([], Set, Dict, N) ->
{N, Set, Dict};
add_orddict([Score, Key|Left], Set, Dict, N) ->
case dict:find(Key, Dict) of
{ok, Value} ->
add_orddict(
Left,
ordsets:add_element({binary_to_number(Score), Score, Key},
ordsets:del_element({binary_to_number(Value), Value, Key}, Set)),
dict:store(Key, Score, Dict),
N);
_ ->
add_orddict(
Left,
ordsets:add_element({binary_to_number(Score), Score, Key}, Set),
dict:store(Key, Score, Dict),
N+1)
end.
%% del orddict
-spec del_orddict(E::list(), Set::ordsets:set(), Dict::dict:dict(), N::integer()) ->
{C::integer(), NewSet::ordsets:set(), NewDict::dict:dict()}.
del_orddict([], Set, Dict, N) ->
{N, Set, Dict};
del_orddict([Key|Left], Set, Dict, N) ->
case dict:find(Key, Dict) of
{ok, Value} ->
del_orddict(
Left,
ordsets:del_element({binary_to_number(Value), Value, Key}, Set),
dict:erase(Key, Dict),
N+1);
_ ->
del_orddict(
Left,
Set,
Dict,
N)
end.
%% expire key manage
-spec get_expire_time(Db::atom(), Key::binary()) -> integer().
get_expire_time(Database, Key) ->
case mnesis_opt:read({Database, ?EXPIRE_KEY}) of
[{Database, ?EXPIRE_KEY, {_Set, Dict}}] ->
case dict:find(Key, Dict) of
{ok, ExpTime} ->
Now = erlang:system_time(1),
if
ExpTime =< Now ->
mnesis_server:remove(Database, Key),
-2;
true ->
ExpTime - Now
end;
_ ->
-1
end;
_ ->
-1
end.
-spec add_key_expire(Db::atom(), Key::binary(), Sec::binary()) -> 0 | 1.
add_key_expire(Database, Key, BinSec) ->
Seconds = erlang:system_time(1) + binary_to_integer(BinSec),
case mnesis_opt:read({Database, ?EXPIRE_KEY}) of
[{Database, ?EXPIRE_KEY, {_Set, _Dict}}] ->
mnesis_server:insert(Database, Key, Seconds),
1;
[] ->
mnesis_opt:write({Database, ?EXPIRE_KEY, {ordsets:new(), dict:new()}}),
mnesis_server:insert(Database, Key, Seconds),
1;
_ ->
0
end.
-spec del_expire_time(Db::atom(), Key::binary()) -> integer().
del_expire_time(Database, Key) ->
case mnesis_opt:read({Database, ?EXPIRE_KEY}) of
[{Database, ?EXPIRE_KEY, {_Set, Dict}}] ->
case dict:find(Key, Dict) of
{ok, _ExpTime} ->
mnesis_server:clear(Database, Key),
1;
_ ->
0
end;
_ ->
0
end.
| null | https://raw.githubusercontent.com/0xfei/mnesia_redis/9353dfbcfc8c5197b6907c94cdfa4abf13d5f0c8/src/mnesis_help.erl | erlang | API
join_list
calc_index
using with try
list_find_low
list_find_high
binary_to_number
number_to_binary
insert sets
remove sets
add multi hash
remove hash
add orddict
del orddict
expire key manage | -module(mnesis_help).
-export([
lower_binary/1, find_number/2, pattern_match/2,
binary_to_number/1, number_to_binary/1,
join_list/2, calc_index/2,
add_elements/3, remove_elements/3,
add_hash/2, remove_hash/3,
add_orddict/4, del_orddict/4,
list_find_low/4, list_find_high/4,
add_key_expire/3, get_expire_time/2, del_expire_time/2]
).
-define(EXPIRE_KEY, expire).
-define(LIMIT_MAX, 999999).
< < " ABC " > > - > < < " abc " > >
-spec lower_binary(Data::binary()) -> New::binary().
lower_binary(Data) ->
lower_binary(Data, <<>>).
lower_binary(<<>>, Binary) ->
Binary;
lower_binary(<<H:8, Left/binary>>, Binary) when H >= $A andalso H =< $Z ->
T = H - $A + $a,
lower_binary(Left, <<Binary/binary, T:8>>);
lower_binary(<<H:8, Left/binary>>, Binary) ->
lower_binary(Left, <<Binary/binary, H:8>>).
find_number < < " " > > - > { 123 , Binary }
-spec find_number(Data::binary(), Initialize::integer()) ->
{Number::integer(), Bin::binary()}.
find_number(<<Num/integer, Data/binary>>, Now) when Num >= $0 andalso Num =< $9 ->
find_number(Data, Now*10+Num-$0);
find_number(<<$\r, $\n, Data/binary>>, Now) ->
{Now, Data}.
pattern_match , only 1 * now
-spec pattern_match(M::binary(), P::binary()) -> true | false.
pattern_match(M, P) ->
int_match(M, P).
int_match(<<>>, <<>>) ->
true;
int_match(_L1, <<$*>>) ->
true;
int_match(L1, L2 = <<$*, _L2/binary>>) ->
list_match(
lists:reverse(binary_to_list(L1)),
lists:reverse(binary_to_list(L2))
);
int_match(<<_H:8, L1/binary>>, <<H:8, L2/binary>>) when H == $? ->
int_match(L1, L2);
int_match(<<H:8, L1/binary>>, <<H:8, L2/binary>>) ->
int_match(L1, L2);
int_match(_L1, _L2) ->
false.
list_match([], []) ->
true;
list_match([H|T], [H|T2]) ->
list_match(T, T2);
list_match([_H|T], [H|T2]) when H == $? ->
list_match(T, T2);
list_match(_L1, [H|_L2]) when H == $* ->
true;
list_match(_, _) ->
false.
-spec join_list(L1::list(), L2::list()) -> L3::list().
join_list(L1, L2) ->
join_list_internal(lists:reverse(L1), L2).
join_list_internal([], L2) ->
L2;
join_list_internal([H|L1], L2) ->
join_list_internal(L1, [H|L2]).
-spec calc_index(Offset::binary(), M::integer()) -> Index::integer().
calc_index(Offset, M) ->
I = binary_to_integer(Offset),
if
I < 0 andalso I + M >= 0 ->
M + I + 1;
I >= 0 andalso I < M ->
I + 1;
true ->
throw("Too long")
end.
list_find_low(_List, _Value, S, E) when S > E ->
S;
list_find_low(List, Value, S, E) ->
Mid = (S + E + 1) div 2,
{Score, _Bin, _Key} = lists:nth(Mid, List),
if
Score >= Value -> list_find_low(List, Value, S, Mid-1);
true -> list_find_low(List, Value, Mid+1, E)
end.
list_find_high(_List, _Value, S, E) when S > E ->
E;
list_find_high(List, Value, S, E) ->
Mid = (S + E + 1) div 2,
{Score, _Bin, _Key} = lists:nth(Mid, List),
if
Score =< Value -> list_find_high(List, Value, Mid+1, E);
true -> list_find_high(List, Value, S, Mid-1)
end.
-spec binary_to_number(B::binary()) -> integer() | float() .
binary_to_number(B) ->
try
binary_to_integer(B)
catch _:_ ->
binary_to_float(B)
end.
-spec number_to_binary(B::integer() | float()) -> binary().
number_to_binary(B) ->
try
integer_to_binary(B)
catch _:_ ->
float_to_binary(B)
end.
-spec add_elements(E::list(), Set::sets:set(), N::integer()) ->
NSet::sets:set().
add_elements([], Set, N) ->
{N, Set};
add_elements([H|T], Set, N) ->
case sets:is_element(H, Set) of
true ->
add_elements(T, Set, N);
_ ->
add_elements(T, sets:add_element(H, Set), N+1)
end.
-spec remove_elements(E::list(), Set::sets:set(), N::integer()) ->
NSet::sets:set().
remove_elements([], Set, N) ->
{N, Set};
remove_elements([H|T], Set, N) ->
case sets:is_element(H, Set) of
true ->
remove_elements(T, sets:del_element(H, Set), N+1);
_ ->
remove_elements(T, Set, N)
end.
-spec add_hash(E::list(), Map::#{}) -> NMap::#{}.
add_hash([], Map) ->
Map;
add_hash([K, V|Left], Map) ->
add_hash(Left, maps:put(K, V, Map)).
-spec remove_hash(E::list(), Set::#{}, N::integer()) ->
NSet::#{}.
remove_hash([], Map, N) ->
{N, Map};
remove_hash([H|T], Map, N) ->
case maps:is_key(H, Map) of
true ->
remove_hash(T, maps:remove(H, Map), N+1);
_ ->
remove_hash(T, Map, N)
end.
-spec add_orddict(E::list(), Set::ordsets:set(), Dict::dict:dict(), N::integer()) ->
{C::integer(), NewSet::ordsets:set(), NewDict::dict:dict()}.
add_orddict([], Set, Dict, N) ->
{N, Set, Dict};
add_orddict([Score, Key|Left], Set, Dict, N) ->
case dict:find(Key, Dict) of
{ok, Value} ->
add_orddict(
Left,
ordsets:add_element({binary_to_number(Score), Score, Key},
ordsets:del_element({binary_to_number(Value), Value, Key}, Set)),
dict:store(Key, Score, Dict),
N);
_ ->
add_orddict(
Left,
ordsets:add_element({binary_to_number(Score), Score, Key}, Set),
dict:store(Key, Score, Dict),
N+1)
end.
-spec del_orddict(E::list(), Set::ordsets:set(), Dict::dict:dict(), N::integer()) ->
{C::integer(), NewSet::ordsets:set(), NewDict::dict:dict()}.
del_orddict([], Set, Dict, N) ->
{N, Set, Dict};
del_orddict([Key|Left], Set, Dict, N) ->
case dict:find(Key, Dict) of
{ok, Value} ->
del_orddict(
Left,
ordsets:del_element({binary_to_number(Value), Value, Key}, Set),
dict:erase(Key, Dict),
N+1);
_ ->
del_orddict(
Left,
Set,
Dict,
N)
end.
-spec get_expire_time(Db::atom(), Key::binary()) -> integer().
get_expire_time(Database, Key) ->
case mnesis_opt:read({Database, ?EXPIRE_KEY}) of
[{Database, ?EXPIRE_KEY, {_Set, Dict}}] ->
case dict:find(Key, Dict) of
{ok, ExpTime} ->
Now = erlang:system_time(1),
if
ExpTime =< Now ->
mnesis_server:remove(Database, Key),
-2;
true ->
ExpTime - Now
end;
_ ->
-1
end;
_ ->
-1
end.
-spec add_key_expire(Db::atom(), Key::binary(), Sec::binary()) -> 0 | 1.
add_key_expire(Database, Key, BinSec) ->
Seconds = erlang:system_time(1) + binary_to_integer(BinSec),
case mnesis_opt:read({Database, ?EXPIRE_KEY}) of
[{Database, ?EXPIRE_KEY, {_Set, _Dict}}] ->
mnesis_server:insert(Database, Key, Seconds),
1;
[] ->
mnesis_opt:write({Database, ?EXPIRE_KEY, {ordsets:new(), dict:new()}}),
mnesis_server:insert(Database, Key, Seconds),
1;
_ ->
0
end.
-spec del_expire_time(Db::atom(), Key::binary()) -> integer().
del_expire_time(Database, Key) ->
case mnesis_opt:read({Database, ?EXPIRE_KEY}) of
[{Database, ?EXPIRE_KEY, {_Set, Dict}}] ->
case dict:find(Key, Dict) of
{ok, _ExpTime} ->
mnesis_server:clear(Database, Key),
1;
_ ->
0
end;
_ ->
0
end.
|
24c204c83b8ae0a74ff0500b3ab996c647af720ff6de10f70200b5caef8fffe3 | fujita-y/ypsilon | %3a64.scm | #!nobacktrace
(library (srfi :64)
(export test-begin
test-end
test-group
test-group-with-cleanup
test-skip
test-expect-fail
test-match-name
test-match-nth
test-match-all
test-match-any
test-assert
test-eqv
test-eq
test-equal
test-approximate
test-error
test-read-eval-string
test-apply
test-with-runner
test-exit
test-runner-null
test-runner?
test-runner-reset
test-result-alist
test-result-alist!
test-result-ref
test-result-set!
test-result-remove
test-result-clear
test-runner-pass-count
test-runner-fail-count
test-runner-xpass-count
test-runner-xfail-count
test-runner-skip-count
test-runner-test-name
test-runner-group-path
test-runner-group-stack
test-runner-aux-value
test-runner-aux-value!
test-result-kind
test-passed?
test-runner-on-test-begin
test-runner-on-test-begin!
test-runner-on-test-end
test-runner-on-test-end!
test-runner-on-group-begin
test-runner-on-group-begin!
test-runner-on-group-end
test-runner-on-group-end!
test-runner-on-final
test-runner-on-final!
test-runner-on-bad-count
test-runner-on-bad-count!
test-runner-on-bad-end-name
test-runner-on-bad-end-name!
test-runner-factory
test-runner-create
test-runner-current
test-runner-get
test-runner-simple
test-on-group-begin-simple
test-on-group-end-simple
test-on-final-simple
test-on-test-begin-simple
test-on-test-end-simple
test-on-bad-count-simple
test-on-bad-end-name-simple)
(import (srfi srfi-64)))
| null | https://raw.githubusercontent.com/fujita-y/ypsilon/44260d99e24000f9847e79c94826c3d9b76872c2/sitelib/srfi/%253a64.scm | scheme | #!nobacktrace
(library (srfi :64)
(export test-begin
test-end
test-group
test-group-with-cleanup
test-skip
test-expect-fail
test-match-name
test-match-nth
test-match-all
test-match-any
test-assert
test-eqv
test-eq
test-equal
test-approximate
test-error
test-read-eval-string
test-apply
test-with-runner
test-exit
test-runner-null
test-runner?
test-runner-reset
test-result-alist
test-result-alist!
test-result-ref
test-result-set!
test-result-remove
test-result-clear
test-runner-pass-count
test-runner-fail-count
test-runner-xpass-count
test-runner-xfail-count
test-runner-skip-count
test-runner-test-name
test-runner-group-path
test-runner-group-stack
test-runner-aux-value
test-runner-aux-value!
test-result-kind
test-passed?
test-runner-on-test-begin
test-runner-on-test-begin!
test-runner-on-test-end
test-runner-on-test-end!
test-runner-on-group-begin
test-runner-on-group-begin!
test-runner-on-group-end
test-runner-on-group-end!
test-runner-on-final
test-runner-on-final!
test-runner-on-bad-count
test-runner-on-bad-count!
test-runner-on-bad-end-name
test-runner-on-bad-end-name!
test-runner-factory
test-runner-create
test-runner-current
test-runner-get
test-runner-simple
test-on-group-begin-simple
test-on-group-end-simple
test-on-final-simple
test-on-test-begin-simple
test-on-test-end-simple
test-on-bad-count-simple
test-on-bad-end-name-simple)
(import (srfi srfi-64)))
| |
5583138ec3f2833a809ab4f8f86da033afb491582a274c073eb9f78014117a68 | ocamllabs/ocaml-modular-implicits | pi_num.ml | (*************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Estime , INRIA Rocquencourt
(* *)
Copyright 2008 Institut National de Recherche en Informatique et
(* en Automatique. All rights reserved. This file is distributed *)
under the terms of the Q Public License version 1.0 .
(* *)
(*************************************************************************)
Pi digits computed with the sreaming algorithm given on pages 4 , 6
& 7 of " Unbounded Spigot Algorithms for the Digits of Pi " , , August 2004 .
& 7 of "Unbounded Spigot Algorithms for the Digits of Pi", Jeremy
Gibbons, August 2004. *)
open Printf;;
open Num;;
let zero = num_of_int 0
and one = num_of_int 1
and three = num_of_int 3
and four = num_of_int 4
and ten = num_of_int 10
and neg_ten = num_of_int(-10)
;;
Linear Fractional Transformation
module LFT = struct
let floor_ev (q, r, s, t) x = quo_num (q */ x +/ r) (s */ x +/ t);;
let unit = (one, zero, zero, one);;
let comp (q, r, s, t) (q', r', s', t') =
(q */ q' +/ r */ s', q */ r' +/ r */ t',
s */ q' +/ t */ s', s */ r' +/ t */ t')
;;
end
;;
let next z = LFT.floor_ev z three
and safe z n = (n =/ LFT.floor_ev z four)
and prod z n = LFT.comp (ten, neg_ten */ n, zero, one) z
and cons z k =
let den = 2 * k + 1 in
LFT.comp z (num_of_int k, num_of_int(2 * den), zero, num_of_int den)
;;
let rec digit k z n row col =
if n > 0 then
let y = next z in
if safe z y then
if col = 10 then (
let row = row + 10 in
printf "\t:%i\n%s" row (string_of_num y);
digit k (prod z y) (n-1) row 1
)
else (
print_string(string_of_num y);
digit k (prod z y) (n-1) row (col + 1)
)
else digit (k + 1) (cons z k) n row col
else
printf "%*s\t:%i\n" (10 - col) "" (row + col)
;;
let digits n = digit 1 LFT.unit n 0 0
;;
let usage () =
prerr_endline "Usage: pi_num <number of digits to compute for pi>";
exit 2
;;
let main () =
let args = Sys.argv in
if Array.length args <> 2 then usage () else
digits (int_of_string Sys.argv.(1))
;;
main ()
;;
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/lib-num-2/pi_num.ml | ocaml | ***********************************************************************
OCaml
en Automatique. All rights reserved. This file is distributed
*********************************************************************** | , projet Estime , INRIA Rocquencourt
Copyright 2008 Institut National de Recherche en Informatique et
under the terms of the Q Public License version 1.0 .
Pi digits computed with the sreaming algorithm given on pages 4 , 6
& 7 of " Unbounded Spigot Algorithms for the Digits of Pi " , , August 2004 .
& 7 of "Unbounded Spigot Algorithms for the Digits of Pi", Jeremy
Gibbons, August 2004. *)
open Printf;;
open Num;;
let zero = num_of_int 0
and one = num_of_int 1
and three = num_of_int 3
and four = num_of_int 4
and ten = num_of_int 10
and neg_ten = num_of_int(-10)
;;
Linear Fractional Transformation
module LFT = struct
let floor_ev (q, r, s, t) x = quo_num (q */ x +/ r) (s */ x +/ t);;
let unit = (one, zero, zero, one);;
let comp (q, r, s, t) (q', r', s', t') =
(q */ q' +/ r */ s', q */ r' +/ r */ t',
s */ q' +/ t */ s', s */ r' +/ t */ t')
;;
end
;;
let next z = LFT.floor_ev z three
and safe z n = (n =/ LFT.floor_ev z four)
and prod z n = LFT.comp (ten, neg_ten */ n, zero, one) z
and cons z k =
let den = 2 * k + 1 in
LFT.comp z (num_of_int k, num_of_int(2 * den), zero, num_of_int den)
;;
let rec digit k z n row col =
if n > 0 then
let y = next z in
if safe z y then
if col = 10 then (
let row = row + 10 in
printf "\t:%i\n%s" row (string_of_num y);
digit k (prod z y) (n-1) row 1
)
else (
print_string(string_of_num y);
digit k (prod z y) (n-1) row (col + 1)
)
else digit (k + 1) (cons z k) n row col
else
printf "%*s\t:%i\n" (10 - col) "" (row + col)
;;
let digits n = digit 1 LFT.unit n 0 0
;;
let usage () =
prerr_endline "Usage: pi_num <number of digits to compute for pi>";
exit 2
;;
let main () =
let args = Sys.argv in
if Array.length args <> 2 then usage () else
digits (int_of_string Sys.argv.(1))
;;
main ()
;;
|
de7abe384cf89c76c72a9b0e168bda3c5bcf789b1265f46c31c86a28d9e25e91 | HaskellForCats/HaskellForCats | devel.hs | {-# LANGUAGE PackageImports #-}
import "yogsothoth" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings defaultSettings
{ settingsPort = port
} app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "yesod-devel/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
| null | https://raw.githubusercontent.com/HaskellForCats/HaskellForCats/2d7a15c0cdaa262c157bbf37af6e72067bc279bc/yogsothoth/devel.hs | haskell | # LANGUAGE PackageImports # | import "yogsothoth" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings defaultSettings
{ settingsPort = port
} app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "yesod-devel/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
|
15822b359da0f21a2fcee06df017154b48422279bb877c7096006a57999cc1ae | Lysxia/twentyseven | Extra.hs | # LANGUAGE TypeFamilies , TypeOperators , TemplateHaskell #
module Data.Tuple.Extra where
import Control.Monad ( forM )
import Data.Tuple.Template ( decTupleCons )
class TupleCons b where
type (:|) a b :: *
(|:|) :: a -> b -> a :| b
split :: a :| b -> (a, b)
forM [3 .. 10] decTupleCons
newtype Tuple1 a = Tuple1 a
deriving (Eq, Ord, Show)
instance TupleCons (Tuple1 a) where
type (:|) b (Tuple1 a) = (b, a)
{-# INLINE (|:|) #-}
a |:| Tuple1 b = (a, b)
# INLINE split #
split (a, b) = (a, Tuple1 b)
| null | https://raw.githubusercontent.com/Lysxia/twentyseven/bfcd3ddcf938bc6db933a364d331877b0fd1257e/src/Data/Tuple/Extra.hs | haskell | # INLINE (|:|) # | # LANGUAGE TypeFamilies , TypeOperators , TemplateHaskell #
module Data.Tuple.Extra where
import Control.Monad ( forM )
import Data.Tuple.Template ( decTupleCons )
class TupleCons b where
type (:|) a b :: *
(|:|) :: a -> b -> a :| b
split :: a :| b -> (a, b)
forM [3 .. 10] decTupleCons
newtype Tuple1 a = Tuple1 a
deriving (Eq, Ord, Show)
instance TupleCons (Tuple1 a) where
type (:|) b (Tuple1 a) = (b, a)
a |:| Tuple1 b = (a, b)
# INLINE split #
split (a, b) = (a, Tuple1 b)
|
1f81fb1dc5710fe35ec6103769e3b98f6bc692728ed05275e9f76029a896b45f | brendanhay/credentials | Options.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : Credentials.CLI.Options
Copyright : ( c ) 2015 - 2016
License : Mozilla Public License , v. 2.0 .
Maintainer : < >
-- Stability : provisional
Portability : non - portable ( GHC extensions )
--
module Credentials.CLI.Options where
import Credentials.CLI.Types
import Data.Bifunctor
import Data.List (foldl')
import Data.Maybe (isJust)
import Network.AWS.Data
import Network.AWS.Data.Text
import Options.Applicative hiding (optional)
import Options.Applicative.Help hiding (string)
import qualified Data.Text as Text
import qualified Options.Applicative as Opt
data Fact
= Required
| Optional
| Default
-- | Setup an option with formatted help text.
describe :: Text -- ^ The options' description.
-> Maybe Doc -- ^ The help body (title/footer in tabular).
-> Fact
-> Mod OptionFields a
describe title body r = helpDoc . Just $ wrap title <> doc <> line
where
doc | Just b <- body = pad (maybe b (b .$.) foot)
| otherwise = maybe mempty pad foot
foot = case r of
Required -> Just ("This is" <+> bold "required.")
Optional -> Just ("This is" <+> bold "optional.")
Default -> Nothing
pad = mappend line . indent 2
-- | Setup a tabular list of possible values for an option,
-- a default value, and an auto-completer.
completes :: ToText a
=> Text -- ^ The options' description.
-> Text -- ^ A title for the values.
-> [(a, String)] -- ^ Possible values and their documentation.
-> Maybe a -- ^ A default value.
-> Maybe Text -- ^ Footer contents.
-> Mod OptionFields a
completes title note xs x foot = doc <> completeWith (map fst ys)
where
doc = defaults title note ys x foot
ys = map (first string) xs
-- | Construct a tabular representation displaying the default values,
without using ToText for the tabular values .
defaults :: ToText a
=> Text
-> Text
-> [(String, String)]
-> Maybe a
-> Maybe Text
-> Mod OptionFields a
defaults title note xs x foot =
describe title (Just doc) Default <> maybe mempty value x
where
doc = maybe table (table .$.) (wrap <$> foot)
table = wrap note
.$. indent 2 rows
$$$ ( case x of
Nothing -> mempty
Just y -> "Defaults to " <> bold (text (string y)) <> "."
)
($$$) | isJust x = (.$.)
| otherwise = mappend
len = maximum (map (length . fst) xs)
rows | [r] <- xs = f r
| r:rs <- xs = foldl' (.$.) (f r) (map f rs)
| otherwise = mempty
where
f (k, v) = "-" <+> bold (text k) <+> indent (len - length k) ts
where
ts | null v = mempty
| otherwise = tupled [text v]
require :: (Fact -> a) -> a
require f = f Required
optional :: Alternative f => (Fact -> f a) -> f (Maybe a)
optional f = Opt.optional (f Optional)
textOption :: FromText a => Mod OptionFields a -> Parser a
textOption = option (eitherReader (fromText . Text.pack))
wrap :: Text -> Doc
wrap = extractChunk . paragraph . Text.unpack
| null | https://raw.githubusercontent.com/brendanhay/credentials/4cba2c238b7d99712ee6745748864134096a106b/credentials-cli/src/Credentials/CLI/Options.hs | haskell | # LANGUAGE OverloadedStrings #
|
Module : Credentials.CLI.Options
Stability : provisional
| Setup an option with formatted help text.
^ The options' description.
^ The help body (title/footer in tabular).
| Setup a tabular list of possible values for an option,
a default value, and an auto-completer.
^ The options' description.
^ A title for the values.
^ Possible values and their documentation.
^ A default value.
^ Footer contents.
| Construct a tabular representation displaying the default values, |
Copyright : ( c ) 2015 - 2016
License : Mozilla Public License , v. 2.0 .
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Credentials.CLI.Options where
import Credentials.CLI.Types
import Data.Bifunctor
import Data.List (foldl')
import Data.Maybe (isJust)
import Network.AWS.Data
import Network.AWS.Data.Text
import Options.Applicative hiding (optional)
import Options.Applicative.Help hiding (string)
import qualified Data.Text as Text
import qualified Options.Applicative as Opt
data Fact
= Required
| Optional
| Default
-> Fact
-> Mod OptionFields a
describe title body r = helpDoc . Just $ wrap title <> doc <> line
where
doc | Just b <- body = pad (maybe b (b .$.) foot)
| otherwise = maybe mempty pad foot
foot = case r of
Required -> Just ("This is" <+> bold "required.")
Optional -> Just ("This is" <+> bold "optional.")
Default -> Nothing
pad = mappend line . indent 2
completes :: ToText a
-> Mod OptionFields a
completes title note xs x foot = doc <> completeWith (map fst ys)
where
doc = defaults title note ys x foot
ys = map (first string) xs
without using ToText for the tabular values .
defaults :: ToText a
=> Text
-> Text
-> [(String, String)]
-> Maybe a
-> Maybe Text
-> Mod OptionFields a
defaults title note xs x foot =
describe title (Just doc) Default <> maybe mempty value x
where
doc = maybe table (table .$.) (wrap <$> foot)
table = wrap note
.$. indent 2 rows
$$$ ( case x of
Nothing -> mempty
Just y -> "Defaults to " <> bold (text (string y)) <> "."
)
($$$) | isJust x = (.$.)
| otherwise = mappend
len = maximum (map (length . fst) xs)
rows | [r] <- xs = f r
| r:rs <- xs = foldl' (.$.) (f r) (map f rs)
| otherwise = mempty
where
f (k, v) = "-" <+> bold (text k) <+> indent (len - length k) ts
where
ts | null v = mempty
| otherwise = tupled [text v]
require :: (Fact -> a) -> a
require f = f Required
optional :: Alternative f => (Fact -> f a) -> f (Maybe a)
optional f = Opt.optional (f Optional)
textOption :: FromText a => Mod OptionFields a -> Parser a
textOption = option (eitherReader (fromText . Text.pack))
wrap :: Text -> Doc
wrap = extractChunk . paragraph . Text.unpack
|
b2946aa2372572226a2012ea935833b4356b88efe382d7e98e4c69f18907385e | dwysocki/hidden-markov-music | init.clj | (ns hidden-markov-music.model.init
(:require [hidden-markov-music.hmm :as hmm]
[hidden-markov-music.util :as util]
[clojure.tools.cli :refer [parse-opts]]
[clojure.string :as string]))
(def usage
(util/usage-descriptor
(->> ["Usage: hidden-markov-music init [<options>] <mode>"
""
"Initialize a hidden Markov model with an alphabet read from stdin."
"Alphabet must contain one unique observation symbol per line."
"Mode may either be 'random' or 'uniform', and determines whether"
"the probabilities are initialized randomly or uniformly."]
(string/join \newline))))
(def cli-options
[["-s" "--states N"
"Number of hidden states (required)"
:parse-fn util/parse-int
:validate [#(< % 0x10000) "Must be an integer between 0 and 65536"]]
["-h" "--help"]])
(defn main
[args]
(let [{:keys [options arguments summary errors]}
(parse-opts args cli-options)]
(cond
(:help options)
(util/exit 0 (usage summary))
(not= 1 (count arguments))
(util/exit 1 (usage summary))
(nil? (:states options))
(util/exit 1 (usage summary))
errors
(util/exit 1 (util/error-msg errors)))
(with-open [rdr (clojure.java.io/reader *in*)]
(let [alphabet (-> rdr
; create a seq out of the lines of the alphabet
line-seq
; built a set from that seq
set
; add nil to that set, which represents end-of-song
(conj nil))
states (range (:states options))
mode (first arguments)
init-fn (case mode
"random" hmm/random-LogHMM
"uniform" hmm/uniform-LogHMM
(util/exit 1 (str mode " is not a valid mode")))
model (init-fn states alphabet)]
(if (hmm/valid-hmm? model)
(do (pr (into {} model))
(println))
(util/exit 1 "Invalid model trained"))))))
| null | https://raw.githubusercontent.com/dwysocki/hidden-markov-music/5601e17dd582d0a73be16fe98fec099296303c95/src/hidden_markov_music/model/init.clj | clojure | create a seq out of the lines of the alphabet
built a set from that seq
add nil to that set, which represents end-of-song | (ns hidden-markov-music.model.init
(:require [hidden-markov-music.hmm :as hmm]
[hidden-markov-music.util :as util]
[clojure.tools.cli :refer [parse-opts]]
[clojure.string :as string]))
(def usage
(util/usage-descriptor
(->> ["Usage: hidden-markov-music init [<options>] <mode>"
""
"Initialize a hidden Markov model with an alphabet read from stdin."
"Alphabet must contain one unique observation symbol per line."
"Mode may either be 'random' or 'uniform', and determines whether"
"the probabilities are initialized randomly or uniformly."]
(string/join \newline))))
(def cli-options
[["-s" "--states N"
"Number of hidden states (required)"
:parse-fn util/parse-int
:validate [#(< % 0x10000) "Must be an integer between 0 and 65536"]]
["-h" "--help"]])
(defn main
[args]
(let [{:keys [options arguments summary errors]}
(parse-opts args cli-options)]
(cond
(:help options)
(util/exit 0 (usage summary))
(not= 1 (count arguments))
(util/exit 1 (usage summary))
(nil? (:states options))
(util/exit 1 (usage summary))
errors
(util/exit 1 (util/error-msg errors)))
(with-open [rdr (clojure.java.io/reader *in*)]
(let [alphabet (-> rdr
line-seq
set
(conj nil))
states (range (:states options))
mode (first arguments)
init-fn (case mode
"random" hmm/random-LogHMM
"uniform" hmm/uniform-LogHMM
(util/exit 1 (str mode " is not a valid mode")))
model (init-fn states alphabet)]
(if (hmm/valid-hmm? model)
(do (pr (into {} model))
(println))
(util/exit 1 "Invalid model trained"))))))
|
c7a4d627719d5360a276b3ba671d3cfe70b95e8fe4caf073521aea731205afd7 | CarlWright/NGerlguten | erlguten.erl | %%==========================================================================
Copyright ( C ) 2003
%%
%% Permission is hereby granted, free of charge, to any person obtaining a
%% copy of this software and associated documentation files (the
" Software " ) , to deal in the Software without restriction , including
%% without limitation the rights to use, copy, modify, merge, publish,
distribute , sublicense , and/or sell copies of the Software , and to permit
persons to whom the Software is furnished to do so , subject to the
%% following conditions:
%%
%% The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software .
%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS
%% OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
%% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
%% NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR
%% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
%% USE OR OTHER DEALINGS IN THE SOFTWARE.
%%
Authors : < >
%% Purpose: Main program
%%==========================================================================
-module(erlguten).
-export([batch/1, get_tag_schema/2, parse_flow/1]).
-export([test/0,bug/0]).
-import(lists, [map/2]).
-include("../include/eg.hrl").
test() -> format("../test/template testing/test1.map").
bug() -> format("../test/template testing/test2.map").
batch([X]) ->
format(atom_to_list(X)).
format(File) ->
V = eg_xml_lite:parse_file(File),
%io:format("read:~p~n",[V]),
Out = filename:rootname(File) ++ ".pdf",
case V of
{error, _W} ->
io:format("Error in source(~s):~p~n",[File, V]),
exit(1);
[{pi,_},{xml,{data, [{"page", N}], Templates}}] ->
Page = list_to_integer(N),
io:format("Data starts on page:~p~n",[Page]),
PDF = eg_pdf:new(),
Env = #env{page=Page, pdf=PDF, dict=dict:new()},
loop(Templates, Env),
{Serialised, _PageNo} = eg_pdf:export(PDF),
file:write_file(Out,[Serialised]),
io:format("Created a file called:~p~n",[Out]),
eg_pdf:delete(PDF);
_ ->
io:format("bad XML - must begin \"<?xml ...\n<flow \n"),
exit(1)
end.
loop([{template,Args,Data}|T], Env) ->
io:format("tempate Args=~p~n",[Args]),
Template= get_template_name(Args),
io:format("Template:~p~n",[Template]),
Env1 = Env#env{template=Template},
io:format("tempate data=~p~n",[Data]),
Env2 = instanciate_template(Template, Env1),
Env3 = format_boxes(Data, Env2),
loop(T, Env3);
loop([], Env) ->
Env.
format_boxes([{comment, _Args} | T], Env) -> % ignore comment boxes
format_boxes(T, Env);
format_boxes([{Box, _Args, Data} | T], Env) ->
Env1 = initialise_box(Box, Env),
%% loop over the paragraphs in the Box
Dict = Env1#env.dict,
Template = Env1#env.template,
Env2 = format_paragraphs(Data, dict:fetch({Template,Box},Dict), Env1),
format_boxes(T, Env2);
format_boxes([], E) ->
E.
initialise_box(Box, E) ->
#env{dict=Dict, page=Page, pdf=PDF, template=Template}=E,
Dict1 = dict:store({free,Page,Box}, 1, Dict),
B = Template:box(E, Template, Box),
#box{x=XX,y=YY,leading=Lead, width=Width, lines=Lines} = B,
eg_pdf_lib:draw_box(PDF, XX, YY,Width, Lead,Lines),
Env1 = E#env{dict=Dict1, currentBox=Box},
%% initialse the tagMap
initialise_tagMap(Template, Box, Env1).
format_paragraphs([{ParaTag,Args,Data}|T], Box, Env) ->
Template = Env#env.template,
case (catch Template:handler(Box, ParaTag, Args, Data, Env)) of
{'EXIT', Why} ->
io:format("oops ~w: ~w ~w Args=~p Data=~p~n",[Template,Box,
ParaTag,
Args,Data]),
io:format("Why=~p~n",[Why]),
exit(1);
Env1 ->
format_paragraphs(T, Box, Env1)
end;
format_paragraphs([], _Box, E) ->
E.
initialise_tagMap(Template, Box, E) ->
Object = "get a value for this",
Ts = case (catch Template:tagMap(E, Template, Box, Object)) of
{'EXIT', _Why} ->
io:format("error in tagmap for ~p:~p~n",
[Template,Box]),
io:format("using default~n"),
default_tagmap();
L -> L
end,
PDF = E#env.pdf,
TagMap = map(fun(I) ->
io:format("Tagmap entry=~p~n",[I]),
eg_pdf:ensure_font_gets_loaded(PDF, I#tagMap.font),
#tagMap{font=F, size=Psize, color=Color,
voff=V, break=Break, name=N} = I,
{N, eg_richText:mk_face(F, Psize, Break, Color, V)}
end, Ts),
E#env{tagMap=TagMap}.
default_tagmap() ->
[#tagMap{name=default,font="Times-Roman",size=11},
#tagMap{name=em,font="Times-Italic", size=11},
#tagMap{name=code,font="Courier",size=11,break=false}].
instanciate_template(Template, E) ->
#env{dict=Dict, page = Page, pdf = _PDF} = E,
case dict:find(Key = {initialised, Page, Template}, Dict) of
error ->
io:format("calling first instantiation Page:~p "
"Template: ~p ~n", [Page, Template]),
Env2 = Template:on_instanciation(E),
Dict2 = Env2#env.dict,
Env2#env{dict= dict:store(Key, true, Dict2) };
_ ->
E
end.
%% This isn't used anywhere in the source code.
get_tag_schema(Tag, [H|T]) ->
case H of
Tag -> H;
_ -> get_tag_schema(Tag, T)
end;
get_tag_schema(Tag, []) ->
exit({missing,tag,Tag}).
%% This isn't used anywhere in the source code.
parse_flow([ {"galley", F}, {"name", _Tag}]) ->
case eg_xml_lite:parse_file(F) of
{error, E} ->
io:format("Error in galley(~p):~p~n",[F, E]),
exit(1);
_L ->
%G = parse_galley(F, L),
%get_box(Tag, G)
true
end.
get_template_name([{"name", N}]) ->
M = lists:map(fun(X) -> case X of
$: -> $_;
_ -> X end
end, N),
list_to_atom(M).
| null | https://raw.githubusercontent.com/CarlWright/NGerlguten/3c87f2e3a44ae9069f9379933b99c0feb8262d66/lib/ngerlguten/src/erlguten.erl | erlang | ==========================================================================
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
without limitation the rights to use, copy, modify, merge, publish,
following conditions:
The above copyright notice and this permission notice shall be included
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
Purpose: Main program
==========================================================================
io:format("read:~p~n",[V]),
ignore comment boxes
loop over the paragraphs in the Box
initialse the tagMap
This isn't used anywhere in the source code.
This isn't used anywhere in the source code.
G = parse_galley(F, L),
get_box(Tag, G) | Copyright ( C ) 2003
" Software " ) , to deal in the Software without restriction , including
distribute , sublicense , and/or sell copies of the Software , and to permit
persons to whom the Software is furnished to do so , subject to the
in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS
DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR
Authors : < >
-module(erlguten).
-export([batch/1, get_tag_schema/2, parse_flow/1]).
-export([test/0,bug/0]).
-import(lists, [map/2]).
-include("../include/eg.hrl").
test() -> format("../test/template testing/test1.map").
bug() -> format("../test/template testing/test2.map").
batch([X]) ->
format(atom_to_list(X)).
format(File) ->
V = eg_xml_lite:parse_file(File),
Out = filename:rootname(File) ++ ".pdf",
case V of
{error, _W} ->
io:format("Error in source(~s):~p~n",[File, V]),
exit(1);
[{pi,_},{xml,{data, [{"page", N}], Templates}}] ->
Page = list_to_integer(N),
io:format("Data starts on page:~p~n",[Page]),
PDF = eg_pdf:new(),
Env = #env{page=Page, pdf=PDF, dict=dict:new()},
loop(Templates, Env),
{Serialised, _PageNo} = eg_pdf:export(PDF),
file:write_file(Out,[Serialised]),
io:format("Created a file called:~p~n",[Out]),
eg_pdf:delete(PDF);
_ ->
io:format("bad XML - must begin \"<?xml ...\n<flow \n"),
exit(1)
end.
loop([{template,Args,Data}|T], Env) ->
io:format("tempate Args=~p~n",[Args]),
Template= get_template_name(Args),
io:format("Template:~p~n",[Template]),
Env1 = Env#env{template=Template},
io:format("tempate data=~p~n",[Data]),
Env2 = instanciate_template(Template, Env1),
Env3 = format_boxes(Data, Env2),
loop(T, Env3);
loop([], Env) ->
Env.
format_boxes(T, Env);
format_boxes([{Box, _Args, Data} | T], Env) ->
Env1 = initialise_box(Box, Env),
Dict = Env1#env.dict,
Template = Env1#env.template,
Env2 = format_paragraphs(Data, dict:fetch({Template,Box},Dict), Env1),
format_boxes(T, Env2);
format_boxes([], E) ->
E.
initialise_box(Box, E) ->
#env{dict=Dict, page=Page, pdf=PDF, template=Template}=E,
Dict1 = dict:store({free,Page,Box}, 1, Dict),
B = Template:box(E, Template, Box),
#box{x=XX,y=YY,leading=Lead, width=Width, lines=Lines} = B,
eg_pdf_lib:draw_box(PDF, XX, YY,Width, Lead,Lines),
Env1 = E#env{dict=Dict1, currentBox=Box},
initialise_tagMap(Template, Box, Env1).
format_paragraphs([{ParaTag,Args,Data}|T], Box, Env) ->
Template = Env#env.template,
case (catch Template:handler(Box, ParaTag, Args, Data, Env)) of
{'EXIT', Why} ->
io:format("oops ~w: ~w ~w Args=~p Data=~p~n",[Template,Box,
ParaTag,
Args,Data]),
io:format("Why=~p~n",[Why]),
exit(1);
Env1 ->
format_paragraphs(T, Box, Env1)
end;
format_paragraphs([], _Box, E) ->
E.
initialise_tagMap(Template, Box, E) ->
Object = "get a value for this",
Ts = case (catch Template:tagMap(E, Template, Box, Object)) of
{'EXIT', _Why} ->
io:format("error in tagmap for ~p:~p~n",
[Template,Box]),
io:format("using default~n"),
default_tagmap();
L -> L
end,
PDF = E#env.pdf,
TagMap = map(fun(I) ->
io:format("Tagmap entry=~p~n",[I]),
eg_pdf:ensure_font_gets_loaded(PDF, I#tagMap.font),
#tagMap{font=F, size=Psize, color=Color,
voff=V, break=Break, name=N} = I,
{N, eg_richText:mk_face(F, Psize, Break, Color, V)}
end, Ts),
E#env{tagMap=TagMap}.
default_tagmap() ->
[#tagMap{name=default,font="Times-Roman",size=11},
#tagMap{name=em,font="Times-Italic", size=11},
#tagMap{name=code,font="Courier",size=11,break=false}].
instanciate_template(Template, E) ->
#env{dict=Dict, page = Page, pdf = _PDF} = E,
case dict:find(Key = {initialised, Page, Template}, Dict) of
error ->
io:format("calling first instantiation Page:~p "
"Template: ~p ~n", [Page, Template]),
Env2 = Template:on_instanciation(E),
Dict2 = Env2#env.dict,
Env2#env{dict= dict:store(Key, true, Dict2) };
_ ->
E
end.
get_tag_schema(Tag, [H|T]) ->
case H of
Tag -> H;
_ -> get_tag_schema(Tag, T)
end;
get_tag_schema(Tag, []) ->
exit({missing,tag,Tag}).
parse_flow([ {"galley", F}, {"name", _Tag}]) ->
case eg_xml_lite:parse_file(F) of
{error, E} ->
io:format("Error in galley(~p):~p~n",[F, E]),
exit(1);
_L ->
true
end.
get_template_name([{"name", N}]) ->
M = lists:map(fun(X) -> case X of
$: -> $_;
_ -> X end
end, N),
list_to_atom(M).
|
36111ce728617ea950e443f6f1b1c11ae45f9fbc0a19f94cdf2e9caea7a07d4b | apache/couchdb-mango | mango_httpd_handlers.erl | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
use this file except in compliance with the License . You may obtain a copy of
% the License at
%
% -2.0
%
% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
% License for the specific language governing permissions and limitations under
% the License.
-module(mango_httpd_handlers).
-export([url_handler/1, db_handler/1, design_handler/1]).
url_handler(_) -> no_match.
db_handler(<<"_index">>) -> fun mango_httpd:handle_req/2;
db_handler(<<"_explain">>) -> fun mango_httpd:handle_req/2;
db_handler(<<"_find">>) -> fun mango_httpd:handle_req/2;
db_handler(_) -> no_match.
design_handler(_) -> no_match.
| null | https://raw.githubusercontent.com/apache/couchdb-mango/312e2c45535913c190cdef51f6ea65066ccd89dc/src/mango_httpd_handlers.erl | erlang | the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License. | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
use this file except in compliance with the License . You may obtain a copy of
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(mango_httpd_handlers).
-export([url_handler/1, db_handler/1, design_handler/1]).
url_handler(_) -> no_match.
db_handler(<<"_index">>) -> fun mango_httpd:handle_req/2;
db_handler(<<"_explain">>) -> fun mango_httpd:handle_req/2;
db_handler(<<"_find">>) -> fun mango_httpd:handle_req/2;
db_handler(_) -> no_match.
design_handler(_) -> no_match.
|
345e9eda005a311a32c7d88520e3c24318d62028e33fcc822319d344f83a4830 | ddmcdonald/sparser | display-ontology.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
copyright ( c ) 2016 - 2021 -- all rights reserved
;;;
;;; File: "display-ontology"
;;; Module: interface/grammar/
Version : October 2021
Adapted 10/22/16 from MAB 's code for Trips .
(in-package :sparser)
;;;-------------------------------------
;;; words with multiple interpretations
;;;-------------------------------------
#| (write-multi-cat-data :descriptor "fire"
:file-location "Sparser/code/s/grammar/tests/"
:file-name "multi-category-words.lisp") |#
(defun write-multi-cat-data (&key descriptor reference-system
file-location file-name)
"Parameters modeled on save-subcat-tree-to-file.
This function manages the stream. It calls the function
just below to access the data and populate the stream/file"
(unless reference-system
(setq reference-system :sparser))
(unless file-location
(setq file-location "Sparser/code/s/grammar/tests/"))
(unless file-name
(setq file-name "multi-category-words.lisp"))
(let* ((file-string (string-append file-location file-name))
(pathname (asdf:system-relative-pathname reference-system file-string)))
(with-open-file (stream pathname
:direction :output
:if-exists :supersede)
(format stream ";; multi-categories for word in ~a
~a~% "
descriptor (date-&-time-as-formatted-string))
(export-multi-category-records stream))))
(defun export-multi-category-records (stream)
"Given the set of 'truly multi-category words', which is
a sorted list of words, look up their records (a least two
since each different category will have a record) and write
to a stream an expression that summarizes them in a form intended
for people to read"
(loop for word in (collect-multi-categories)
do (progn
(format stream "~&~%")
(form-for-multi-category word stream))))
(defun form-for-multi-category (word stream)
"Returns an expression that describes the records created
for this word by record-multi-cfr in terms that are useful
for people deciding what to do this them."
(let ((records (get-multi-cfr-data word)))
(format stream "~&(~s" (word-pname word))
(loop for record in records
as category = (wmr-category record)
as logical-pathname = (wmr-location record)
do (format stream "~% ~a ;~a"
(cat-name category)
(namestring logical-pathname)))
(format stream "~&)")))
;;;--------------------------
;;; Org files for categories
;;;--------------------------
(defun write-cat-org (category stream indent)
"Iterate through the subcategories of category and write
the lines to stream. This is the fixed point for writing
a full taxonomy -- doing the display of its input category
and applying recursively to its subccategories.
Keeps track of what categories have already been displayed,
announces any cases it finds, and keeps us from getting loops.
Note that unlike display-categories-below, this enumeration
does not limit either the depth or breadth of its walk."
(write-org-tree-cat-line category stream indent)
(if (gethash category *category-was-displayed*)
(format stream " ** already diplayed ~a" category)
(else
(setf (gethash category *category-was-displayed*) t)
(let ((subs (subcategories-of category)))
(when subs
(loop for s in subs
do (write-cat-org s stream (+ 2 indent))))))))
(defun write-org-tree-cat-line (category stream indent)
"Write the line for one category to the stream.
If the category defines any variables (slots), include them
in the output, e.g.
+ 1 endurant vars: {number, quantifier}
The indent(ation) provides a visual index so it is easy to
tell what depth you are looking at as well as how large to
make the left margin intentation."
(let* ((variables (cat-slots category))
(var-names (when variables
(loop for v in variables
collect (var-name v)))))
(format stream "~%~VT+ ~d ~a ~@[vars: {~{~A~^, ~}}~]"
indent ;; provides an index
(round indent 2)
(string-downcase (cat-symbol category))
var-names)))
(defun display-cat-org (cat-name &optional (stream *standard-output*))
"Intended for just looking at a small section of the category
taxonomy in the REPL using the org format and indentation."
(clrhash *category-was-displayed*)
(write-cat-org (category-named cat-name :error-if-nil) stream 0))
(defun save-subcat-tree-to-file (category-name
&key reference-system file-location file-name)
"Using write-cat-org, write the subcategory tree from the specified
category on down to a file. By default the file will be in the
categories subdirectory of the sparser documentation directory.
The filename is based on the current script, though if the category
is not top it will be appended to the filename, e.g.
~/sparser/Sparser/documentation/categories/blocks-world-linguistic.org "
(let ((category (category-named category-name :error-if-nil)))
(unless reference-system
(setq reference-system :sparser))
(unless file-location
(setq file-location "Sparser/documentation/categories/"))
(unless file-name
(setq file-name
(if (eq category-name 'top)
(string-append (string-downcase (pname script)) ".org")
(string-append (string-downcase (pname script)) "-"
(string-downcase (pname (cat-name category)))
".org"))))
(let* ((file-string (string-append file-location file-name))
(pathname (asdf:system-relative-pathname reference-system file-string)))
(with-open-file (stream pathname
:direction :output
:if-exists :supersede)
(format stream "-*-org-*~
~%#+TITLE: ~a~
~%#+DATE: ~a~%"
(format nil "Subcategory tree for the ~a configuration" script)
(date-&-time-as-formatted-string))
(clrhash *category-was-displayed*)
(write-cat-org category stream 0)
pathname))))
= = = = = = = Earlier version written by for doing this with TRIPS
#|(display-with-subcs category::top t ) --> stash on a variable, tree
(write-as-org-tree tree :reference-system :sparser)
|#
(defun write-as-org-tree (tree &key reference-system)
"Takes a sexp tree like that produced by (display-with-subcs category::top t)
and asdf system to define where to save the file. This defaults to :trips-ont-viewer
which is r3/code/TRIPS-upper-ont/. Not the best but it will do."
(unless reference-system
(setq reference-system :trips-ont-viewer))
(let* ((script (script))
(filename (string-append (string-downcase (symbol-name script)) ".org"))
(pathname
(asdf::system-relative-pathname reference-system filename)))
(with-open-file (stream pathname
:direction :output :if-exists :supersede)
(format stream "-*-org-*-~
~%#+DATE: ~a~%"
(date-&-time-as-formatted-string))
(recursive-write-org-lines stream tree 0))))
(defun recursive-write-org-lines (stream tree indent) ;; lang map)
"Recursively walks down an sexpr (tree) that encode the super/sub class relationships
and writes the incantation for rendering that as a file to be interpreted in org-mode.
Eg.
+ 2 KR::ORGANISM
+ 3 KR::SPECIES
+ 4 KR::HUMAN "
(flet ((write-tree-ln (cat vars)
(format stream "~%~VT+ ~d ~s ~@[vars: {~{~A~^, ~}}~]" ;; ~@[~80T=> ~s~]"
indent (round indent 2) cat vars)))
(when tree
(let* ((cat (car tree))
(subs nil)
(vars nil))
(cond ((eq (second tree) :variables)
(setf vars (third tree)
subs (cdddr tree)))
(t (setf vars nil
subs (cdr tree))))
;; Fixed multi-word preposition problem by redesigning their names qua categories
(write-tree-ln cat vars)
(dolist (subt subs)
(recursive-write-org-lines stream subt (+ 2 indent) #|lang map|#))))))
| null | https://raw.githubusercontent.com/ddmcdonald/sparser/f1ab378ceab5523014e504e7a2e71d25e5e773b7/Sparser/code/s/interface/grammar/display-ontology.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
File: "display-ontology"
Module: interface/grammar/
-------------------------------------
words with multiple interpretations
-------------------------------------
(write-multi-cat-data :descriptor "fire"
:file-location "Sparser/code/s/grammar/tests/"
:file-name "multi-category-words.lisp")
multi-categories for word in ~a
--------------------------
Org files for categories
--------------------------
provides an index
(display-with-subcs category::top t ) --> stash on a variable, tree
(write-as-org-tree tree :reference-system :sparser)
lang map)
~@[~80T=> ~s~]"
Fixed multi-word preposition problem by redesigning their names qua categories
lang map | copyright ( c ) 2016 - 2021 -- all rights reserved
Version : October 2021
Adapted 10/22/16 from MAB 's code for Trips .
(in-package :sparser)
(defun write-multi-cat-data (&key descriptor reference-system
file-location file-name)
"Parameters modeled on save-subcat-tree-to-file.
This function manages the stream. It calls the function
just below to access the data and populate the stream/file"
(unless reference-system
(setq reference-system :sparser))
(unless file-location
(setq file-location "Sparser/code/s/grammar/tests/"))
(unless file-name
(setq file-name "multi-category-words.lisp"))
(let* ((file-string (string-append file-location file-name))
(pathname (asdf:system-relative-pathname reference-system file-string)))
(with-open-file (stream pathname
:direction :output
:if-exists :supersede)
~a~% "
descriptor (date-&-time-as-formatted-string))
(export-multi-category-records stream))))
(defun export-multi-category-records (stream)
"Given the set of 'truly multi-category words', which is
a sorted list of words, look up their records (a least two
since each different category will have a record) and write
to a stream an expression that summarizes them in a form intended
for people to read"
(loop for word in (collect-multi-categories)
do (progn
(format stream "~&~%")
(form-for-multi-category word stream))))
(defun form-for-multi-category (word stream)
"Returns an expression that describes the records created
for this word by record-multi-cfr in terms that are useful
for people deciding what to do this them."
(let ((records (get-multi-cfr-data word)))
(format stream "~&(~s" (word-pname word))
(loop for record in records
as category = (wmr-category record)
as logical-pathname = (wmr-location record)
do (format stream "~% ~a ;~a"
(cat-name category)
(namestring logical-pathname)))
(format stream "~&)")))
(defun write-cat-org (category stream indent)
"Iterate through the subcategories of category and write
the lines to stream. This is the fixed point for writing
a full taxonomy -- doing the display of its input category
and applying recursively to its subccategories.
Keeps track of what categories have already been displayed,
announces any cases it finds, and keeps us from getting loops.
Note that unlike display-categories-below, this enumeration
does not limit either the depth or breadth of its walk."
(write-org-tree-cat-line category stream indent)
(if (gethash category *category-was-displayed*)
(format stream " ** already diplayed ~a" category)
(else
(setf (gethash category *category-was-displayed*) t)
(let ((subs (subcategories-of category)))
(when subs
(loop for s in subs
do (write-cat-org s stream (+ 2 indent))))))))
(defun write-org-tree-cat-line (category stream indent)
"Write the line for one category to the stream.
If the category defines any variables (slots), include them
in the output, e.g.
+ 1 endurant vars: {number, quantifier}
The indent(ation) provides a visual index so it is easy to
tell what depth you are looking at as well as how large to
make the left margin intentation."
(let* ((variables (cat-slots category))
(var-names (when variables
(loop for v in variables
collect (var-name v)))))
(format stream "~%~VT+ ~d ~a ~@[vars: {~{~A~^, ~}}~]"
(round indent 2)
(string-downcase (cat-symbol category))
var-names)))
(defun display-cat-org (cat-name &optional (stream *standard-output*))
"Intended for just looking at a small section of the category
taxonomy in the REPL using the org format and indentation."
(clrhash *category-was-displayed*)
(write-cat-org (category-named cat-name :error-if-nil) stream 0))
(defun save-subcat-tree-to-file (category-name
&key reference-system file-location file-name)
"Using write-cat-org, write the subcategory tree from the specified
category on down to a file. By default the file will be in the
categories subdirectory of the sparser documentation directory.
The filename is based on the current script, though if the category
is not top it will be appended to the filename, e.g.
~/sparser/Sparser/documentation/categories/blocks-world-linguistic.org "
(let ((category (category-named category-name :error-if-nil)))
(unless reference-system
(setq reference-system :sparser))
(unless file-location
(setq file-location "Sparser/documentation/categories/"))
(unless file-name
(setq file-name
(if (eq category-name 'top)
(string-append (string-downcase (pname script)) ".org")
(string-append (string-downcase (pname script)) "-"
(string-downcase (pname (cat-name category)))
".org"))))
(let* ((file-string (string-append file-location file-name))
(pathname (asdf:system-relative-pathname reference-system file-string)))
(with-open-file (stream pathname
:direction :output
:if-exists :supersede)
(format stream "-*-org-*~
~%#+TITLE: ~a~
~%#+DATE: ~a~%"
(format nil "Subcategory tree for the ~a configuration" script)
(date-&-time-as-formatted-string))
(clrhash *category-was-displayed*)
(write-cat-org category stream 0)
pathname))))
= = = = = = = Earlier version written by for doing this with TRIPS
(defun write-as-org-tree (tree &key reference-system)
"Takes a sexp tree like that produced by (display-with-subcs category::top t)
and asdf system to define where to save the file. This defaults to :trips-ont-viewer
which is r3/code/TRIPS-upper-ont/. Not the best but it will do."
(unless reference-system
(setq reference-system :trips-ont-viewer))
(let* ((script (script))
(filename (string-append (string-downcase (symbol-name script)) ".org"))
(pathname
(asdf::system-relative-pathname reference-system filename)))
(with-open-file (stream pathname
:direction :output :if-exists :supersede)
(format stream "-*-org-*-~
~%#+DATE: ~a~%"
(date-&-time-as-formatted-string))
(recursive-write-org-lines stream tree 0))))
"Recursively walks down an sexpr (tree) that encode the super/sub class relationships
and writes the incantation for rendering that as a file to be interpreted in org-mode.
Eg.
+ 2 KR::ORGANISM
+ 3 KR::SPECIES
+ 4 KR::HUMAN "
(flet ((write-tree-ln (cat vars)
indent (round indent 2) cat vars)))
(when tree
(let* ((cat (car tree))
(subs nil)
(vars nil))
(cond ((eq (second tree) :variables)
(setf vars (third tree)
subs (cdddr tree)))
(t (setf vars nil
subs (cdr tree))))
(write-tree-ln cat vars)
(dolist (subt subs)
|
131527f695421d4aae720c946358cd4c679343a080949e7571729dbe4ada3d6a | tomprimozic/type-systems | core.ml | open Expr
open Infer
let core =
let core_ref = ref Env.empty in
let assume name ty_str =
let ty = Parser.ty_forall_eof Lexer.token (Lexing.from_string ty_str) in
core_ref := Env.extend !core_ref name ty
in
assume "head" "forall[a] list[a] -> a" ;
assume "tail" "forall[a] list[a] -> list[a]" ;
assume "nil" "forall[a] list[a]" ;
assume "cons" "forall[a] (a, list[a]) -> list[a]" ;
assume "cons_curry" "forall[a] a -> list[a] -> list[a]" ;
assume "map" "forall[a b] (a -> b, list[a]) -> list[b]" ;
assume "map_curry" "forall[a b] (a -> b) -> list[a] -> list[b]" ;
assume "one" "int" ;
assume "zero" "int" ;
assume "succ" "int -> int" ;
assume "plus" "(int, int) -> int" ;
assume "sum" "list[int] -> int" ;
assume "eq" "forall[a] (a, a) -> bool" ;
assume "eq_curry" "forall[a] a -> a -> bool" ;
assume "not" "bool -> bool" ;
assume "true" "bool" ;
assume "false" "bool" ;
assume "pair" "forall[a b] (a, b) -> pair[a, b]" ;
assume "pair_curry" "forall[a b] a -> b -> pair[a, b]" ;
assume "first" "forall[a b] pair[a, b] -> a" ;
assume "second" "forall[a b] pair[a, b] -> b" ;
assume "id" "forall[a] a -> a" ;
assume "const" "forall[a b] a -> b -> a" ;
assume "apply" "forall[a b] (a -> b, a) -> b" ;
assume "apply_curry" "forall[a b] (a -> b) -> a -> b" ;
assume "choose" "forall[a] (a, a) -> a" ;
assume "choose_curry" "forall[a] a -> a -> a" ;
assume "duplicate" "forall[a] a -> pair[a, a]" ;
assume "dynamic_to_dynamic" "? -> ?" ;
assume "dynamic_to_int" "? -> int" ;
assume "int_to_dynamic" "int -> ?" ;
assume "dynamic" "?" ;
assume "test" "(? -> int, int -> ?) -> int" ;
assume "test_curry" "(? -> int) -> (int -> ?) -> int" ;
!core_ref
| null | https://raw.githubusercontent.com/tomprimozic/type-systems/4403586a897ee94cb8f0de039aeee8ef1ecef968/gradual_typing/core.ml | ocaml | open Expr
open Infer
let core =
let core_ref = ref Env.empty in
let assume name ty_str =
let ty = Parser.ty_forall_eof Lexer.token (Lexing.from_string ty_str) in
core_ref := Env.extend !core_ref name ty
in
assume "head" "forall[a] list[a] -> a" ;
assume "tail" "forall[a] list[a] -> list[a]" ;
assume "nil" "forall[a] list[a]" ;
assume "cons" "forall[a] (a, list[a]) -> list[a]" ;
assume "cons_curry" "forall[a] a -> list[a] -> list[a]" ;
assume "map" "forall[a b] (a -> b, list[a]) -> list[b]" ;
assume "map_curry" "forall[a b] (a -> b) -> list[a] -> list[b]" ;
assume "one" "int" ;
assume "zero" "int" ;
assume "succ" "int -> int" ;
assume "plus" "(int, int) -> int" ;
assume "sum" "list[int] -> int" ;
assume "eq" "forall[a] (a, a) -> bool" ;
assume "eq_curry" "forall[a] a -> a -> bool" ;
assume "not" "bool -> bool" ;
assume "true" "bool" ;
assume "false" "bool" ;
assume "pair" "forall[a b] (a, b) -> pair[a, b]" ;
assume "pair_curry" "forall[a b] a -> b -> pair[a, b]" ;
assume "first" "forall[a b] pair[a, b] -> a" ;
assume "second" "forall[a b] pair[a, b] -> b" ;
assume "id" "forall[a] a -> a" ;
assume "const" "forall[a b] a -> b -> a" ;
assume "apply" "forall[a b] (a -> b, a) -> b" ;
assume "apply_curry" "forall[a b] (a -> b) -> a -> b" ;
assume "choose" "forall[a] (a, a) -> a" ;
assume "choose_curry" "forall[a] a -> a -> a" ;
assume "duplicate" "forall[a] a -> pair[a, a]" ;
assume "dynamic_to_dynamic" "? -> ?" ;
assume "dynamic_to_int" "? -> int" ;
assume "int_to_dynamic" "int -> ?" ;
assume "dynamic" "?" ;
assume "test" "(? -> int, int -> ?) -> int" ;
assume "test_curry" "(? -> int) -> (int -> ?) -> int" ;
!core_ref
| |
64d79739a729a1f3b0464f01834126d5bfe74a6b3ea15fe61a9bec3efb03bb0f | TerrorJack/ghc-alter | QSemN.hs | {-# LANGUAGE Safe #-}
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.QSemN
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : experimental
-- Portability : non-portable (concurrency)
--
-- Quantity semaphores in which each thread may wait for an arbitrary
-- \"amount\".
--
-----------------------------------------------------------------------------
module Control.Concurrent.QSemN
* General
QSemN, -- abstract
newQSemN, -- :: Int -> IO QSemN
waitQSemN, -- :: QSemN -> Int -> IO ()
signalQSemN -- :: QSemN -> Int -> IO ()
) where
import Control.Concurrent.MVar ( MVar, newEmptyMVar, takeMVar, tryTakeMVar
, putMVar, newMVar
, tryPutMVar, isEmptyMVar)
import Control.Exception
import Data.Maybe
-- | 'QSemN' is a quantity semaphore in which the resource is aqcuired
-- and released in units of one. It provides guaranteed FIFO ordering
-- for satisfying blocked `waitQSemN` calls.
--
-- The pattern
--
> bracket _ ( waitQSemN n ) ( signalQSemN n ) ( ... )
--
-- is safe; it never loses any of the resource.
--
data QSemN = QSemN !(MVar (Int, [(Int, MVar ())], [(Int, MVar ())]))
-- The semaphore state (i, xs, ys):
--
-- i is the current resource value
--
-- (xs,ys) is the queue of blocked threads, where the queue is
-- given by xs ++ reverse ys. We can enqueue new blocked threads
-- by consing onto ys, and dequeue by removing from the head of xs.
--
A blocked thread is represented by an empty ( MVar ( ) ) . To unblock
the thread , we put ( ) into the MVar .
--
A thread can dequeue itself by also putting ( ) into the MVar , which
-- it must do if it receives an exception while blocked in waitQSemN.
-- This means that when unblocking a thread in signalQSemN we must
first check whether the MVar is already full ; the MVar lock on the
semaphore itself resolves race conditions between signalQSemN and a
-- thread attempting to dequeue itself.
-- |Build a new 'QSemN' with a supplied initial quantity.
-- The initial quantity must be at least 0.
newQSemN :: Int -> IO QSemN
newQSemN initial
| initial < 0 = fail "newQSemN: Initial quantity must be non-negative"
| otherwise = do
sem <- newMVar (initial, [], [])
return (QSemN sem)
-- |Wait for the specified quantity to become available
waitQSemN :: QSemN -> Int -> IO ()
waitQSemN (QSemN m) sz =
mask_ $ do
(i,b1,b2) <- takeMVar m
let z = i-sz
if z < 0
then do
b <- newEmptyMVar
putMVar m (i, b1, (sz,b):b2)
wait b
else do
putMVar m (z, b1, b2)
return ()
where
wait b = do
takeMVar b `onException`
(uninterruptibleMask_ $ do -- Note [signal uninterruptible]
(i,b1,b2) <- takeMVar m
r <- tryTakeMVar b
r' <- if isJust r
then signal sz (i,b1,b2)
else do putMVar b (); return (i,b1,b2)
putMVar m r')
-- |Signal that a given quantity is now available from the 'QSemN'.
signalQSemN :: QSemN -> Int -> IO ()
signalQSemN (QSemN m) sz = uninterruptibleMask_ $ do
r <- takeMVar m
r' <- signal sz r
putMVar m r'
signal :: Int
-> (Int,[(Int,MVar ())],[(Int,MVar ())])
-> IO (Int,[(Int,MVar ())],[(Int,MVar ())])
signal sz0 (i,a1,a2) = loop (sz0 + i) a1 a2
where
loop 0 bs b2 = return (0, bs, b2)
loop sz [] [] = return (sz, [], [])
loop sz [] b2 = loop sz (reverse b2) []
loop sz ((j,b):bs) b2
| j > sz = do
r <- isEmptyMVar b
if r then return (sz, (j,b):bs, b2)
else loop sz bs b2
| otherwise = do
r <- tryPutMVar b ()
if r then loop (sz-j) bs b2
else loop sz bs b2
| null | https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/Control/Concurrent/QSemN.hs | haskell | # LANGUAGE Safe #
# LANGUAGE BangPatterns #
# OPTIONS_GHC -funbox-strict-fields #
---------------------------------------------------------------------------
|
Module : Control.Concurrent.QSemN
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable (concurrency)
Quantity semaphores in which each thread may wait for an arbitrary
\"amount\".
---------------------------------------------------------------------------
abstract
:: Int -> IO QSemN
:: QSemN -> Int -> IO ()
:: QSemN -> Int -> IO ()
| 'QSemN' is a quantity semaphore in which the resource is aqcuired
and released in units of one. It provides guaranteed FIFO ordering
for satisfying blocked `waitQSemN` calls.
The pattern
is safe; it never loses any of the resource.
The semaphore state (i, xs, ys):
i is the current resource value
(xs,ys) is the queue of blocked threads, where the queue is
given by xs ++ reverse ys. We can enqueue new blocked threads
by consing onto ys, and dequeue by removing from the head of xs.
it must do if it receives an exception while blocked in waitQSemN.
This means that when unblocking a thread in signalQSemN we must
thread attempting to dequeue itself.
|Build a new 'QSemN' with a supplied initial quantity.
The initial quantity must be at least 0.
|Wait for the specified quantity to become available
Note [signal uninterruptible]
|Signal that a given quantity is now available from the 'QSemN'. |
Copyright : ( c ) The University of Glasgow 2001
module Control.Concurrent.QSemN
* General
) where
import Control.Concurrent.MVar ( MVar, newEmptyMVar, takeMVar, tryTakeMVar
, putMVar, newMVar
, tryPutMVar, isEmptyMVar)
import Control.Exception
import Data.Maybe
> bracket _ ( waitQSemN n ) ( signalQSemN n ) ( ... )
data QSemN = QSemN !(MVar (Int, [(Int, MVar ())], [(Int, MVar ())]))
A blocked thread is represented by an empty ( MVar ( ) ) . To unblock
the thread , we put ( ) into the MVar .
A thread can dequeue itself by also putting ( ) into the MVar , which
first check whether the MVar is already full ; the MVar lock on the
semaphore itself resolves race conditions between signalQSemN and a
newQSemN :: Int -> IO QSemN
newQSemN initial
| initial < 0 = fail "newQSemN: Initial quantity must be non-negative"
| otherwise = do
sem <- newMVar (initial, [], [])
return (QSemN sem)
waitQSemN :: QSemN -> Int -> IO ()
waitQSemN (QSemN m) sz =
mask_ $ do
(i,b1,b2) <- takeMVar m
let z = i-sz
if z < 0
then do
b <- newEmptyMVar
putMVar m (i, b1, (sz,b):b2)
wait b
else do
putMVar m (z, b1, b2)
return ()
where
wait b = do
takeMVar b `onException`
(i,b1,b2) <- takeMVar m
r <- tryTakeMVar b
r' <- if isJust r
then signal sz (i,b1,b2)
else do putMVar b (); return (i,b1,b2)
putMVar m r')
signalQSemN :: QSemN -> Int -> IO ()
signalQSemN (QSemN m) sz = uninterruptibleMask_ $ do
r <- takeMVar m
r' <- signal sz r
putMVar m r'
signal :: Int
-> (Int,[(Int,MVar ())],[(Int,MVar ())])
-> IO (Int,[(Int,MVar ())],[(Int,MVar ())])
signal sz0 (i,a1,a2) = loop (sz0 + i) a1 a2
where
loop 0 bs b2 = return (0, bs, b2)
loop sz [] [] = return (sz, [], [])
loop sz [] b2 = loop sz (reverse b2) []
loop sz ((j,b):bs) b2
| j > sz = do
r <- isEmptyMVar b
if r then return (sz, (j,b):bs, b2)
else loop sz bs b2
| otherwise = do
r <- tryPutMVar b ()
if r then loop (sz-j) bs b2
else loop sz bs b2
|
673be396ef2b22417ec7e8113a8ddbaa68b94a9dc7f6882e4151a57ed4600145 | SRI-CSL/f3d | sysdef-lisp-extensions.lisp | (in-package :cl-user)
(defvar config::weak-eval-cache nil)
(st:define-system :lisp-extensions
:required-systems '(common-symbols ev-pathnames lcl)
:files `("lx-pkg.lisp"
"custom.lisp"
"colors.lisp" ; Not the best place, but see file for issues.
"file-property-list.lisp" ; this probably should move to system-tool
"lisp-extensions.lisp"
"pathname-extensions.lisp" ; would like to eliminate this
"struct-class.lisp"
,@(if config::weak-eval-cache
`("weak-eval-cache.lisp"
;; swank-weak-hash-table.lisp is broken with recent slime/swank versions
#+never ,@(when (find-package :swank)
'("swank-weak-hash-table.lisp"))
)
'("eval-cache.lisp"))
"lisp-io.lisp"
"universal-time.lisp"
"clos-tools.lisp"
"binary-search.lisp"
))
| null | https://raw.githubusercontent.com/SRI-CSL/f3d/93285f582198bfbab33ca96ff71efda539b1bec7/f3d-core/lx/sysdef-lisp-extensions.lisp | lisp | Not the best place, but see file for issues.
this probably should move to system-tool
would like to eliminate this
swank-weak-hash-table.lisp is broken with recent slime/swank versions | (in-package :cl-user)
(defvar config::weak-eval-cache nil)
(st:define-system :lisp-extensions
:required-systems '(common-symbols ev-pathnames lcl)
:files `("lx-pkg.lisp"
"custom.lisp"
"lisp-extensions.lisp"
"struct-class.lisp"
,@(if config::weak-eval-cache
`("weak-eval-cache.lisp"
#+never ,@(when (find-package :swank)
'("swank-weak-hash-table.lisp"))
)
'("eval-cache.lisp"))
"lisp-io.lisp"
"universal-time.lisp"
"clos-tools.lisp"
"binary-search.lisp"
))
|
ec64d126787c11045453c5bfdda2fdb62f5f09449cef632ed3617ee67c143799 | jeffshrager/biobike | table-data-utils.lisp | ;;; -*- mode: Lisp; Syntax: Common-Lisp; Package: bioutils; -*-
;;; Author: JP Massar.
(in-package :bioutils)
(defvar *td*)
(defparameter *test-table3-data*
(make-array
'(4 9)
:initial-contents
CODE NAME SSN LEVEL0 R1 R2
'(("a" "Fred" "62-055" 1.0 2.0 -3.0 50.0e-2 23 "the big man")
("v" "Wilma" "37-999" 2.05 3.0 17.0 0.50 24 "his wife")
("c" "Barney" "12-171" 3.0 4.0 5.0 0 89 "his friend")
("d" "Dino" "37-999" 11.0 21.0 31.0 0.005e2 10 "his dog")
)))
(defun ltt2 ()
(setq *td*
(let ((*warn-on-data-coercion* nil))
(read-table-data
(cl-user:translate-simple-lp "biol:Bioutils;test-table.txt")
:name 'flintsones
:n-doc-lines 2
:n-posthdr-lines 4
:n-predata-fields 3
:n-postdata-fields 2
:other-rdrfuncs `((:name ,#'(lambda (x) (bio::frame-fnamed x t))))
:global-data-type 'single-float
:missing-value 17.0
:key-columns '(1 2 7)
))))
Lispworks hack to compare scalar single floats ( which are actually
;;; double floats) to single floats in arrays (which, if the element type
;;; of the array is 'single-float, are really single floats)
(defun vsf-equiv (v1 v2)
(let ((sfv1 (make-array 1 :element-type 'single-float))
(sfv2 (make-array 1 :element-type 'single-float)))
(and (= (length v1) (length v2))
(every #'(lambda (x y)
(setf (aref sfv1 0) x)
(setf (aref sfv2 0) y)
(= (aref sfv1 0) (aref sfv2 0)))
v1 v2
))))
| null | https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/Biotests/table-data-utils.lisp | lisp | -*- mode: Lisp; Syntax: Common-Lisp; Package: bioutils; -*-
Author: JP Massar.
double floats) to single floats in arrays (which, if the element type
of the array is 'single-float, are really single floats) |
(in-package :bioutils)
(defvar *td*)
(defparameter *test-table3-data*
(make-array
'(4 9)
:initial-contents
CODE NAME SSN LEVEL0 R1 R2
'(("a" "Fred" "62-055" 1.0 2.0 -3.0 50.0e-2 23 "the big man")
("v" "Wilma" "37-999" 2.05 3.0 17.0 0.50 24 "his wife")
("c" "Barney" "12-171" 3.0 4.0 5.0 0 89 "his friend")
("d" "Dino" "37-999" 11.0 21.0 31.0 0.005e2 10 "his dog")
)))
(defun ltt2 ()
(setq *td*
(let ((*warn-on-data-coercion* nil))
(read-table-data
(cl-user:translate-simple-lp "biol:Bioutils;test-table.txt")
:name 'flintsones
:n-doc-lines 2
:n-posthdr-lines 4
:n-predata-fields 3
:n-postdata-fields 2
:other-rdrfuncs `((:name ,#'(lambda (x) (bio::frame-fnamed x t))))
:global-data-type 'single-float
:missing-value 17.0
:key-columns '(1 2 7)
))))
Lispworks hack to compare scalar single floats ( which are actually
(defun vsf-equiv (v1 v2)
(let ((sfv1 (make-array 1 :element-type 'single-float))
(sfv2 (make-array 1 :element-type 'single-float)))
(and (= (length v1) (length v2))
(every #'(lambda (x y)
(setf (aref sfv1 0) x)
(setf (aref sfv2 0) y)
(= (aref sfv1 0) (aref sfv2 0)))
v1 v2
))))
|
1f4ed46b55e466fe38505a8199f9fdf417d1b9355f3af6159f7cdfeb806e4acd | Opetushallitus/aipal | kayttaja.clj | Copyright ( c ) 2013 The Finnish National Board of Education - Opetushallitus
;;
This program is free software : Licensed under the EUPL , Version 1.1 or - as
soon as they will be approved by the European Commission - subsequent versions
of the EUPL ( the " Licence " ) ;
;;
;; You may not use this work except in compliance with the Licence.
;; You may obtain a copy of the Licence at: /
;;
;; 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
European Union Public Licence for more details .
(ns aipal.arkisto.kayttaja
(:require [korma.core :as sql]
[korma.db :as db]
[clojure.tools.logging :as log]
[oph.korma.common :refer [select-unique select-unique-or-nil update-unique]]
[aipal.integraatio.sql.korma :as taulut]
[oph.common.util.util :refer [sisaltaako-kentat?]]
[aipal.infra.kayttaja :refer [*kayttaja*]]
[aipal.infra.kayttaja.vakiot
:refer [jarjestelma-oid integraatio-uid integraatio-oid
konversio-oid vastaaja-oid]]))
(defn hae
"Hakee käyttäjätunnuksen perusteella."
[oid]
(select-unique-or-nil taulut/kayttaja (sql/where {:oid oid})))
(defn hae-voimassaoleva [uid]
(select-unique-or-nil taulut/kayttaja (sql/where {(sql/sqlfn lower :uid) (sql/sqlfn lower uid), :voimassa true})))
(defn olemassa? [k]
(boolean (hae (:oid k))))
(defn ^:integration-api paivita!
"Päivittää käyttäjätaulun uusilla käyttäjillä kt."
[kt]
{:pre [(= (:uid *kayttaja*) integraatio-uid)]}
(db/transaction
Merkitään nykyiset
(log/debug "Merkitään olemassaolevat käyttäjät ei-voimassaoleviksi")
(sql/update taulut/kayttaja
(sql/set-fields {:voimassa false})
(sql/where {:luotu_kayttaja [= (:oid *kayttaja*)]}))
(doseq [k kt]
(log/debug "Päivitetään käyttäjä" (pr-str k))
(if (olemassa? k)
voimassaolevaksi
(do
(log/debug "Käyttäjä on jo olemassa, päivitetään tiedot")
(update-unique taulut/kayttaja
(sql/set-fields (assoc k :voimassa true))
(sql/where {:oid [= (:oid k)]})))
;; Lisätään uusi käyttäjä
(do
(log/debug "Luodaan uusi käyttäjä")
(sql/insert taulut/kayttaja (sql/values k)))))))
(defn hae-impersonoitava-termilla
"Hakee impersonoitavia käyttäjiä termillä"
[termi]
(for [kayttaja (sql/select taulut/kayttaja
(sql/fields :oid :uid :etunimi :sukunimi)
(sql/where (and
(sql/sqlfn "not exists"
(sql/subselect taulut/rooli_organisaatio
(sql/fields :rooli_organisaatio_id)
(sql/where {:rooli "YLLAPITAJA"
:kayttaja :kayttaja.oid})))
{:oid [not-in [jarjestelma-oid konversio-oid integraatio-oid vastaaja-oid]]
:voimassa true})))
:when (sisaltaako-kentat? kayttaja [:etunimi :sukunimi] termi)]
{:nimi (str (:etunimi kayttaja) " " (:sukunimi kayttaja) " (" (:uid kayttaja) ")")
:oid (:oid kayttaja)}))
(defn ^:integration-api paivita-kayttaja!
"Päivittää tai lisää käyttäjän"
[k]
(log/debug "Päivitetään käyttäjä" (pr-str k))
(if (olemassa? k)
voimassaolevaksi
(do
(log/debug "Käyttäjä on jo olemassa, päivitetään tiedot")
(update-unique taulut/kayttaja
(sql/set-fields k)
(sql/where {:oid [= (:oid k)]})))
;; Lisätään uusi käyttäjä
(do
(log/debug "Luodaan uusi käyttäjä")
(sql/insert taulut/kayttaja (sql/values k)))))
| null | https://raw.githubusercontent.com/Opetushallitus/aipal/767bd14ec7153dc97fdf688443b9687cdb70082f/aipal/src/clj/aipal/arkisto/kayttaja.clj | clojure |
You may not use this work except in compliance with the Licence.
You may obtain a copy of the Licence at: /
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
Lisätään uusi käyttäjä
Lisätään uusi käyttäjä | Copyright ( c ) 2013 The Finnish National Board of Education - Opetushallitus
This program is free software : Licensed under the EUPL , Version 1.1 or - as
soon as they will be approved by the European Commission - subsequent versions
European Union Public Licence for more details .
(ns aipal.arkisto.kayttaja
(:require [korma.core :as sql]
[korma.db :as db]
[clojure.tools.logging :as log]
[oph.korma.common :refer [select-unique select-unique-or-nil update-unique]]
[aipal.integraatio.sql.korma :as taulut]
[oph.common.util.util :refer [sisaltaako-kentat?]]
[aipal.infra.kayttaja :refer [*kayttaja*]]
[aipal.infra.kayttaja.vakiot
:refer [jarjestelma-oid integraatio-uid integraatio-oid
konversio-oid vastaaja-oid]]))
(defn hae
"Hakee käyttäjätunnuksen perusteella."
[oid]
(select-unique-or-nil taulut/kayttaja (sql/where {:oid oid})))
(defn hae-voimassaoleva [uid]
(select-unique-or-nil taulut/kayttaja (sql/where {(sql/sqlfn lower :uid) (sql/sqlfn lower uid), :voimassa true})))
(defn olemassa? [k]
(boolean (hae (:oid k))))
(defn ^:integration-api paivita!
"Päivittää käyttäjätaulun uusilla käyttäjillä kt."
[kt]
{:pre [(= (:uid *kayttaja*) integraatio-uid)]}
(db/transaction
Merkitään nykyiset
(log/debug "Merkitään olemassaolevat käyttäjät ei-voimassaoleviksi")
(sql/update taulut/kayttaja
(sql/set-fields {:voimassa false})
(sql/where {:luotu_kayttaja [= (:oid *kayttaja*)]}))
(doseq [k kt]
(log/debug "Päivitetään käyttäjä" (pr-str k))
(if (olemassa? k)
voimassaolevaksi
(do
(log/debug "Käyttäjä on jo olemassa, päivitetään tiedot")
(update-unique taulut/kayttaja
(sql/set-fields (assoc k :voimassa true))
(sql/where {:oid [= (:oid k)]})))
(do
(log/debug "Luodaan uusi käyttäjä")
(sql/insert taulut/kayttaja (sql/values k)))))))
(defn hae-impersonoitava-termilla
"Hakee impersonoitavia käyttäjiä termillä"
[termi]
(for [kayttaja (sql/select taulut/kayttaja
(sql/fields :oid :uid :etunimi :sukunimi)
(sql/where (and
(sql/sqlfn "not exists"
(sql/subselect taulut/rooli_organisaatio
(sql/fields :rooli_organisaatio_id)
(sql/where {:rooli "YLLAPITAJA"
:kayttaja :kayttaja.oid})))
{:oid [not-in [jarjestelma-oid konversio-oid integraatio-oid vastaaja-oid]]
:voimassa true})))
:when (sisaltaako-kentat? kayttaja [:etunimi :sukunimi] termi)]
{:nimi (str (:etunimi kayttaja) " " (:sukunimi kayttaja) " (" (:uid kayttaja) ")")
:oid (:oid kayttaja)}))
(defn ^:integration-api paivita-kayttaja!
"Päivittää tai lisää käyttäjän"
[k]
(log/debug "Päivitetään käyttäjä" (pr-str k))
(if (olemassa? k)
voimassaolevaksi
(do
(log/debug "Käyttäjä on jo olemassa, päivitetään tiedot")
(update-unique taulut/kayttaja
(sql/set-fields k)
(sql/where {:oid [= (:oid k)]})))
(do
(log/debug "Luodaan uusi käyttäjä")
(sql/insert taulut/kayttaja (sql/values k)))))
|
29a98da12b36b4ac0761fa91ddea93f6d52acc1ba347be6afc9b88acf015d9ed | FranklinChen/hugs98-plus-Sep2006 | Validate.hs | -- | Validate a document against a dtd.
module Text.XML.HaXml.Validate
( validate
, partialValidate
) where
import Text.XML.HaXml.Types
import Text.XML.HaXml.Combinators (multi,tag,iffind,literal,none,o)
import Text.XML.HaXml.XmlContent (attr2str)
import Maybe (fromMaybe,isNothing,fromJust)
import List (intersperse,nub,(\\))
import Char (isSpace)
#if __GLASGOW_HASKELL__ >= 604 || __NHC__ >= 118 || defined(__HUGS__)
emulate older finite map interface using Data . Map , if it is available
import qualified Data.Map as Map
type FiniteMap a b = Map.Map a b
listToFM :: Ord a => [(a,b)] -> FiniteMap a b
listToFM = Map.fromList
lookupFM :: Ord a => FiniteMap a b -> a -> Maybe b
lookupFM = flip Map.lookup
#elif __GLASGOW_HASKELL__ >= 504 || __NHC__ > 114
-- real finite map, if it is available
import Data.FiniteMap
#else
-- otherwise, a very simple and inefficient implementation of a finite map
type FiniteMap a b = [(a,b)]
listToFM :: Eq a => [(a,b)] -> FiniteMap a b
listToFM = id
lookupFM :: Eq a => FiniteMap a b -> a -> Maybe b
lookupFM fm k = lookup k fm
#endif
gather appropriate information out of the DTD
data SimpleDTD = SimpleDTD
{ elements :: FiniteMap Name ContentSpec -- content model of elem
, attributes :: FiniteMap (Name,Name) AttType -- type of (elem,attr)
, required :: FiniteMap Name [Name] -- required attributes of elem
, ids :: [(Name,Name)] -- all (element,attr) with ID type
, idrefs :: [(Name,Name)] -- all (element,attr) with IDREF type
}
simplifyDTD :: DocTypeDecl -> SimpleDTD
simplifyDTD (DTD _ _ decls) =
SimpleDTD
{ elements = listToFM [ (name,content)
| Element (ElementDecl name content) <- decls ]
, attributes = listToFM [ ((elem,attr),typ)
| AttList (AttListDecl elem attdefs) <- decls
, AttDef attr typ _ <- attdefs ]
, required = listToFM [ (elem, [ attr
| AttDef attr _ REQUIRED <- attdefs ])
| AttList (AttListDecl elem attdefs) <- decls ]
, ids = [ (elem,attr)
| Element (ElementDecl elem _) <- decls
, AttList (AttListDecl name attdefs) <- decls
, elem == name
, AttDef attr (TokenizedType ID) _ <- attdefs ]
, idrefs = [] -- not implemented
}
-- simple auxiliary to avoid lots of if-then-else with empty else clauses.
gives :: Bool -> a -> [a]
True `gives` x = [x]
False `gives` _ = []
| ' validate ' takes a DTD and a tagged element , and returns a list of
errors in the document with respect to its DTD .
--
If you have several documents to validate against a single DTD ,
then you will gain efficiency by freezing - in the DTD through partial
-- application, e.g. @checkMyDTD = validate myDTD@.
validate :: DocTypeDecl -> Element i -> [String]
validate dtd' elem = root dtd' elem ++ partialValidate dtd' elem
where
root (DTD name _ _) (Elem name' _ _) =
(name/=name') `gives` ("Document type should be <"++name
++"> but appears to be <"++name'++">.")
-- | 'partialValidate' is like validate, except that it does not check that
the element type matches that of the DTD 's root element .
partialValidate :: DocTypeDecl -> Element i -> [String]
partialValidate dtd' elem = valid elem ++ checkIDs elem
where
dtd = simplifyDTD dtd'
valid (Elem name attrs contents) =
is the element defined in the ?
let spec = lookupFM (elements dtd) name in
(isNothing spec) `gives` ("Element <"++name++"> not known.")
-- is each attribute mentioned only once?
++ (let dups = duplicates (map fst attrs) in
not (null dups) `gives`
("Element <"++name++"> has duplicate attributes: "
++concat (intersperse "," dups)++"."))
-- does each attribute belong to this element? value is in range?
++ concatMap (checkAttr name) attrs
-- are all required attributes present?
++ concatMap (checkRequired name attrs)
(fromMaybe [] (lookupFM (required dtd) name))
-- are its children in a permissible sequence?
++ checkContentSpec name (fromMaybe ANY spec) contents
-- now recursively check the element children
++ concatMap valid [ elem | CElem elem _ <- contents ]
checkAttr elem (attr, val) =
let typ = lookupFM (attributes dtd) (elem,attr)
attval = attr2str val in
if isNothing typ then ["Attribute \""++attr
++"\" not known for element <"++elem++">."]
else
case fromJust typ of
EnumeratedType e ->
case e of
Enumeration es ->
(not (attval `Prelude.elem` es)) `gives`
("Value \""++attval++"\" of attribute \""
++attr++"\" in element <"++elem
++"> is not in the required enumeration range: "
++unwords es)
_ -> []
_ -> []
checkRequired elem attrs req =
(not (req `Prelude.elem` map fst attrs)) `gives`
("Element <"++elem++"> requires the attribute \""++req
++"\" but it is missing.")
checkContentSpec elem ANY _ = []
checkContentSpec elem EMPTY [] = []
checkContentSpec elem EMPTY (_:_) =
["Element <"++elem++"> is not empty but should be."]
checkContentSpec elem (Mixed PCDATA) cs = concatMap (checkMixed elem []) cs
checkContentSpec elem (Mixed (PCDATAplus names)) cs =
concatMap (checkMixed elem names) cs
checkContentSpec elem (ContentSpec cp) cs = excludeText elem cs ++
(let (errs,rest) = checkCP elem cp (flatten cs) in
case rest of [] -> errs
_ -> errs++["Element <"++elem++"> contains extra "
++"elements beyond its content spec."])
checkMixed elem permitted (CElem (Elem name _ _) _)
| not (name `Prelude.elem` permitted) =
["Element <"++elem++"> contains an element <"++name
++"> but should not."]
checkMixed elem permitted _ = []
flatten (CElem (Elem name _ _) _: cs) = name: flatten cs
flatten (_: cs) = flatten cs
flatten [] = []
excludeText elem (CElem _ _: cs) = excludeText elem cs
excludeText elem (CMisc _ _: cs) = excludeText elem cs
excludeText elem (CString _ s _: cs) | all isSpace s = excludeText elem cs
excludeText elem (_: cs) =
["Element <"++elem++"> contains text/references but should not."]
excludeText elem [] = []
-- This is a little parser really. Returns any errors, plus the remainder
-- of the input string.
checkCP :: Name -> CP -> [Name] -> ([String],[Name])
checkCP elem cp@(TagName n None) [] = (cpError elem cp, [])
checkCP elem cp@(TagName n None) (n':ns)
| n==n' = ([], ns)
| otherwise = (cpError elem cp, n':ns)
checkCP elem cp@(TagName n Query) [] = ([],[])
checkCP elem cp@(TagName n Query) (n':ns)
| n==n' = ([], ns)
| otherwise = ([], n':ns)
checkCP elem cp@(TagName n Star) [] = ([],[])
checkCP elem cp@(TagName n Star) (n':ns)
| n==n' = checkCP elem (TagName n Star) ns
| otherwise = ([], n':ns)
checkCP elem cp@(TagName n Plus) [] = (cpError elem cp, [])
checkCP elem cp@(TagName n Plus) (n':ns)
| n==n' = checkCP elem (TagName n Star) ns
| otherwise = (cpError elem cp, n':ns)
omit this clause , to permit ( a?|b ? ) as a valid but empty choice
-- checkCP elem cp@(Choice cps None) [] = (cpError elem cp, [])
checkCP elem cp@(Choice cps None) ns =
let next = choice elem ns cps in
if null next then (cpError elem cp, ns)
choose the first alternative with no errors
checkCP elem cp@(Choice cps Query) [] = ([],[])
checkCP elem cp@(Choice cps Query) ns =
let next = choice elem ns cps in
if null next then ([],ns)
else ([], head next)
checkCP elem cp@(Choice cps Star) [] = ([],[])
checkCP elem cp@(Choice cps Star) ns =
let next = choice elem ns cps in
if null next then ([],ns)
else checkCP elem (Choice cps Star) (head next)
checkCP elem cp@(Choice cps Plus) [] = (cpError elem cp, [])
checkCP elem cp@(Choice cps Plus) ns =
let next = choice elem ns cps in
if null next then (cpError elem cp, ns)
else checkCP elem (Choice cps Star) (head next)
-- omit this clause, to permit (a?,b?) as a valid but empty sequence
checkCP elem ) [ ] = ( cpError elem cp , [ ] )
checkCP elem cp@(Seq cps None) ns =
let (errs,next) = sequence elem ns cps in
if null errs then ([],next)
else (cpError elem cp++errs, ns)
checkCP elem cp@(Seq cps Query) [] = ([],[])
checkCP elem cp@(Seq cps Query) ns =
let (errs,next) = sequence elem ns cps in
if null errs then ([],next)
else ([], ns)
checkCP elem cp@(Seq cps Star) [] = ([],[])
checkCP elem cp@(Seq cps Star) ns =
let (errs,next) = sequence elem ns cps in
if null errs then checkCP elem (Seq cps Star) next
else ([], ns)
checkCP elem cp@(Seq cps Plus) [] = (cpError elem cp, [])
checkCP elem cp@(Seq cps Plus) ns =
let (errs,next) = sequence elem ns cps in
if null errs then checkCP elem (Seq cps Star) next
else (cpError elem cp++errs, ns)
choice elem ns cps = -- return only those parses that don't give any errors
[ rem | ([],rem) <- map (\cp-> checkCP elem (definite cp) ns) cps ]
where definite (TagName n Query) = TagName n None
definite (Choice cps Query) = Choice cps None
definite (Seq cps Query) = Seq cps None
definite (TagName n Star) = TagName n Plus
definite (Choice cps Star) = Choice cps Plus
definite (Seq cps Star) = Seq cps Plus
definite x = x
sequence elem ns cps = -- accumulate errors down the sequence
foldl (\(es,ns) cp-> let (es',ns') = checkCP elem cp ns
in (es++es', ns'))
([],ns) cps
checkIDs elem =
let celem = CElem elem undefined
showAttr a = iffind a literal none
idElems = concatMap (\(name,at)-> multi (showAttr at `o` tag name)
celem)
(ids dtd)
badIds = duplicates (map (\(CString _ s _)->s) idElems)
in not (null badIds) `gives`
("These attribute values of type ID are not unique: "
++concat (intersperse "," badIds)++".")
cpError :: Name -> CP -> [String]
cpError elem cp =
["Element <"++elem++"> should contain "++display cp++" but does not."]
display :: CP -> String
display (TagName name mod) = name ++ modifier mod
display (Choice cps mod) = "(" ++ concat (intersperse "|" (map display cps))
++ ")" ++ modifier mod
display (Seq cps mod) = "(" ++ concat (intersperse "," (map display cps))
++ ")" ++ modifier mod
modifier :: Modifier -> String
modifier None = ""
modifier Query = "?"
modifier Star = "*"
modifier Plus = "+"
duplicates :: Eq a => [a] -> [a]
duplicates xs = xs \\ (nub xs)
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/HaXml/src/Text/XML/HaXml/Validate.hs | haskell | | Validate a document against a dtd.
real finite map, if it is available
otherwise, a very simple and inefficient implementation of a finite map
content model of elem
type of (elem,attr)
required attributes of elem
all (element,attr) with ID type
all (element,attr) with IDREF type
not implemented
simple auxiliary to avoid lots of if-then-else with empty else clauses.
application, e.g. @checkMyDTD = validate myDTD@.
| 'partialValidate' is like validate, except that it does not check that
is each attribute mentioned only once?
does each attribute belong to this element? value is in range?
are all required attributes present?
are its children in a permissible sequence?
now recursively check the element children
This is a little parser really. Returns any errors, plus the remainder
of the input string.
checkCP elem cp@(Choice cps None) [] = (cpError elem cp, [])
omit this clause, to permit (a?,b?) as a valid but empty sequence
return only those parses that don't give any errors
accumulate errors down the sequence | module Text.XML.HaXml.Validate
( validate
, partialValidate
) where
import Text.XML.HaXml.Types
import Text.XML.HaXml.Combinators (multi,tag,iffind,literal,none,o)
import Text.XML.HaXml.XmlContent (attr2str)
import Maybe (fromMaybe,isNothing,fromJust)
import List (intersperse,nub,(\\))
import Char (isSpace)
#if __GLASGOW_HASKELL__ >= 604 || __NHC__ >= 118 || defined(__HUGS__)
emulate older finite map interface using Data . Map , if it is available
import qualified Data.Map as Map
type FiniteMap a b = Map.Map a b
listToFM :: Ord a => [(a,b)] -> FiniteMap a b
listToFM = Map.fromList
lookupFM :: Ord a => FiniteMap a b -> a -> Maybe b
lookupFM = flip Map.lookup
#elif __GLASGOW_HASKELL__ >= 504 || __NHC__ > 114
import Data.FiniteMap
#else
type FiniteMap a b = [(a,b)]
listToFM :: Eq a => [(a,b)] -> FiniteMap a b
listToFM = id
lookupFM :: Eq a => FiniteMap a b -> a -> Maybe b
lookupFM fm k = lookup k fm
#endif
gather appropriate information out of the DTD
data SimpleDTD = SimpleDTD
}
simplifyDTD :: DocTypeDecl -> SimpleDTD
simplifyDTD (DTD _ _ decls) =
SimpleDTD
{ elements = listToFM [ (name,content)
| Element (ElementDecl name content) <- decls ]
, attributes = listToFM [ ((elem,attr),typ)
| AttList (AttListDecl elem attdefs) <- decls
, AttDef attr typ _ <- attdefs ]
, required = listToFM [ (elem, [ attr
| AttDef attr _ REQUIRED <- attdefs ])
| AttList (AttListDecl elem attdefs) <- decls ]
, ids = [ (elem,attr)
| Element (ElementDecl elem _) <- decls
, AttList (AttListDecl name attdefs) <- decls
, elem == name
, AttDef attr (TokenizedType ID) _ <- attdefs ]
}
gives :: Bool -> a -> [a]
True `gives` x = [x]
False `gives` _ = []
| ' validate ' takes a DTD and a tagged element , and returns a list of
errors in the document with respect to its DTD .
If you have several documents to validate against a single DTD ,
then you will gain efficiency by freezing - in the DTD through partial
validate :: DocTypeDecl -> Element i -> [String]
validate dtd' elem = root dtd' elem ++ partialValidate dtd' elem
where
root (DTD name _ _) (Elem name' _ _) =
(name/=name') `gives` ("Document type should be <"++name
++"> but appears to be <"++name'++">.")
the element type matches that of the DTD 's root element .
partialValidate :: DocTypeDecl -> Element i -> [String]
partialValidate dtd' elem = valid elem ++ checkIDs elem
where
dtd = simplifyDTD dtd'
valid (Elem name attrs contents) =
is the element defined in the ?
let spec = lookupFM (elements dtd) name in
(isNothing spec) `gives` ("Element <"++name++"> not known.")
++ (let dups = duplicates (map fst attrs) in
not (null dups) `gives`
("Element <"++name++"> has duplicate attributes: "
++concat (intersperse "," dups)++"."))
++ concatMap (checkAttr name) attrs
++ concatMap (checkRequired name attrs)
(fromMaybe [] (lookupFM (required dtd) name))
++ checkContentSpec name (fromMaybe ANY spec) contents
++ concatMap valid [ elem | CElem elem _ <- contents ]
checkAttr elem (attr, val) =
let typ = lookupFM (attributes dtd) (elem,attr)
attval = attr2str val in
if isNothing typ then ["Attribute \""++attr
++"\" not known for element <"++elem++">."]
else
case fromJust typ of
EnumeratedType e ->
case e of
Enumeration es ->
(not (attval `Prelude.elem` es)) `gives`
("Value \""++attval++"\" of attribute \""
++attr++"\" in element <"++elem
++"> is not in the required enumeration range: "
++unwords es)
_ -> []
_ -> []
checkRequired elem attrs req =
(not (req `Prelude.elem` map fst attrs)) `gives`
("Element <"++elem++"> requires the attribute \""++req
++"\" but it is missing.")
checkContentSpec elem ANY _ = []
checkContentSpec elem EMPTY [] = []
checkContentSpec elem EMPTY (_:_) =
["Element <"++elem++"> is not empty but should be."]
checkContentSpec elem (Mixed PCDATA) cs = concatMap (checkMixed elem []) cs
checkContentSpec elem (Mixed (PCDATAplus names)) cs =
concatMap (checkMixed elem names) cs
checkContentSpec elem (ContentSpec cp) cs = excludeText elem cs ++
(let (errs,rest) = checkCP elem cp (flatten cs) in
case rest of [] -> errs
_ -> errs++["Element <"++elem++"> contains extra "
++"elements beyond its content spec."])
checkMixed elem permitted (CElem (Elem name _ _) _)
| not (name `Prelude.elem` permitted) =
["Element <"++elem++"> contains an element <"++name
++"> but should not."]
checkMixed elem permitted _ = []
flatten (CElem (Elem name _ _) _: cs) = name: flatten cs
flatten (_: cs) = flatten cs
flatten [] = []
excludeText elem (CElem _ _: cs) = excludeText elem cs
excludeText elem (CMisc _ _: cs) = excludeText elem cs
excludeText elem (CString _ s _: cs) | all isSpace s = excludeText elem cs
excludeText elem (_: cs) =
["Element <"++elem++"> contains text/references but should not."]
excludeText elem [] = []
checkCP :: Name -> CP -> [Name] -> ([String],[Name])
checkCP elem cp@(TagName n None) [] = (cpError elem cp, [])
checkCP elem cp@(TagName n None) (n':ns)
| n==n' = ([], ns)
| otherwise = (cpError elem cp, n':ns)
checkCP elem cp@(TagName n Query) [] = ([],[])
checkCP elem cp@(TagName n Query) (n':ns)
| n==n' = ([], ns)
| otherwise = ([], n':ns)
checkCP elem cp@(TagName n Star) [] = ([],[])
checkCP elem cp@(TagName n Star) (n':ns)
| n==n' = checkCP elem (TagName n Star) ns
| otherwise = ([], n':ns)
checkCP elem cp@(TagName n Plus) [] = (cpError elem cp, [])
checkCP elem cp@(TagName n Plus) (n':ns)
| n==n' = checkCP elem (TagName n Star) ns
| otherwise = (cpError elem cp, n':ns)
omit this clause , to permit ( a?|b ? ) as a valid but empty choice
checkCP elem cp@(Choice cps None) ns =
let next = choice elem ns cps in
if null next then (cpError elem cp, ns)
choose the first alternative with no errors
checkCP elem cp@(Choice cps Query) [] = ([],[])
checkCP elem cp@(Choice cps Query) ns =
let next = choice elem ns cps in
if null next then ([],ns)
else ([], head next)
checkCP elem cp@(Choice cps Star) [] = ([],[])
checkCP elem cp@(Choice cps Star) ns =
let next = choice elem ns cps in
if null next then ([],ns)
else checkCP elem (Choice cps Star) (head next)
checkCP elem cp@(Choice cps Plus) [] = (cpError elem cp, [])
checkCP elem cp@(Choice cps Plus) ns =
let next = choice elem ns cps in
if null next then (cpError elem cp, ns)
else checkCP elem (Choice cps Star) (head next)
checkCP elem ) [ ] = ( cpError elem cp , [ ] )
checkCP elem cp@(Seq cps None) ns =
let (errs,next) = sequence elem ns cps in
if null errs then ([],next)
else (cpError elem cp++errs, ns)
checkCP elem cp@(Seq cps Query) [] = ([],[])
checkCP elem cp@(Seq cps Query) ns =
let (errs,next) = sequence elem ns cps in
if null errs then ([],next)
else ([], ns)
checkCP elem cp@(Seq cps Star) [] = ([],[])
checkCP elem cp@(Seq cps Star) ns =
let (errs,next) = sequence elem ns cps in
if null errs then checkCP elem (Seq cps Star) next
else ([], ns)
checkCP elem cp@(Seq cps Plus) [] = (cpError elem cp, [])
checkCP elem cp@(Seq cps Plus) ns =
let (errs,next) = sequence elem ns cps in
if null errs then checkCP elem (Seq cps Star) next
else (cpError elem cp++errs, ns)
[ rem | ([],rem) <- map (\cp-> checkCP elem (definite cp) ns) cps ]
where definite (TagName n Query) = TagName n None
definite (Choice cps Query) = Choice cps None
definite (Seq cps Query) = Seq cps None
definite (TagName n Star) = TagName n Plus
definite (Choice cps Star) = Choice cps Plus
definite (Seq cps Star) = Seq cps Plus
definite x = x
foldl (\(es,ns) cp-> let (es',ns') = checkCP elem cp ns
in (es++es', ns'))
([],ns) cps
checkIDs elem =
let celem = CElem elem undefined
showAttr a = iffind a literal none
idElems = concatMap (\(name,at)-> multi (showAttr at `o` tag name)
celem)
(ids dtd)
badIds = duplicates (map (\(CString _ s _)->s) idElems)
in not (null badIds) `gives`
("These attribute values of type ID are not unique: "
++concat (intersperse "," badIds)++".")
cpError :: Name -> CP -> [String]
cpError elem cp =
["Element <"++elem++"> should contain "++display cp++" but does not."]
display :: CP -> String
display (TagName name mod) = name ++ modifier mod
display (Choice cps mod) = "(" ++ concat (intersperse "|" (map display cps))
++ ")" ++ modifier mod
display (Seq cps mod) = "(" ++ concat (intersperse "," (map display cps))
++ ")" ++ modifier mod
modifier :: Modifier -> String
modifier None = ""
modifier Query = "?"
modifier Star = "*"
modifier Plus = "+"
duplicates :: Eq a => [a] -> [a]
duplicates xs = xs \\ (nub xs)
|
a3dc7747b028152f7d7bcbccb5d2a1a39be1cf4e47196bc154d7d788a825361d | haskell/haskell-ide-engine | TypeMap.hs | # LANGUAGE TupleSections #
# LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE LambdaCase #
module Haskell.Ide.Engine.TypeMap where
import qualified Data.IntervalMap.FingerTree as IM
import qualified GHC
import GHC ( TypecheckedModule, GhcMonad )
import Bag
import BasicTypes
import Data.Data as Data
import Control.Monad.IO.Class
import Control.Applicative
import Data.Maybe
import qualified TcHsSyn
import qualified CoreUtils
import qualified Type
import qualified Desugar
import qualified Haskell.Ide.Engine.Compat as Compat
import Haskell.Ide.Engine.ArtifactMap
-- | Generate a mapping from an Interval to types.
-- Intervals may overlap and return more specific results.
genTypeMap :: GHC.GhcMonad m => TypecheckedModule -> m TypeMap
genTypeMap tm = do
let typecheckedSource = GHC.tm_typechecked_source tm
everythingInTypecheckedSourceM typecheckedSource
everythingInTypecheckedSourceM
:: GhcMonad m => GHC.TypecheckedSource -> m TypeMap
everythingInTypecheckedSourceM xs = bs
where
bs = foldBag (liftA2 IM.union) processBind (return IM.empty) xs
processBind :: GhcMonad m => GHC.LHsBindLR Compat.GhcTc Compat.GhcTc -> m TypeMap
processBind x@(GHC.L (GHC.RealSrcSpan spn) b) =
case b of
Compat.FunBindGen t fmatches ->
case GHC.mg_origin fmatches of
Generated -> return IM.empty
FromSource -> do
im <- types fmatches
return $ IM.singleton (rspToInt spn) t `IM.union` im
Compat.AbsBinds bs -> everythingInTypecheckedSourceM bs
_ -> types x
processBind _ = return IM.empty
-- | Obtain details map for types.
types :: forall m a . (GhcMonad m, Data a) => a -> m TypeMap
types = everythingButTypeM @GHC.Id (ty `combineM` fun `combineM` funBind)
where
ty :: forall a' . (Data a') => a' -> m TypeMap
ty term = case cast term of
(Just lhsExprGhc@(GHC.L (GHC.RealSrcSpan spn) _)) ->
getType lhsExprGhc >>= \case
Nothing -> return IM.empty
Just (_, typ) -> return (IM.singleton (rspToInt spn) typ)
_ -> return IM.empty
fun :: forall a' . (Data a') => a' -> m TypeMap
fun term = case cast term of
(Just (GHC.L (GHC.RealSrcSpan spn) hsPatType)) ->
return (IM.singleton (rspToInt spn) (TcHsSyn.hsPatType hsPatType))
_ -> return IM.empty
funBind :: forall a' . (Data a') => a' -> m TypeMap
funBind term = case cast term of
(Just (GHC.L (GHC.RealSrcSpan spn) (Compat.FunBindType t))) ->
return (IM.singleton (rspToInt spn) t)
_ -> return IM.empty
| Combine two queries into one using alternative combinator .
combineM
:: (forall a . (Monad m, Data a) => a -> m TypeMap)
-> (forall a . (Monad m, Data a) => a -> m TypeMap)
-> (forall a . (Monad m, Data a) => a -> m TypeMap)
combineM f g x = do
a <- f x
b <- g x
return (a `IM.union` b)
-- | Variation of "everything" that does not recurse into children of type t
requires AllowAmbiguousTypes
everythingButTypeM
:: forall t m
. (Typeable t)
=> (forall a . (Monad m, Data a) => a -> m TypeMap)
-> (forall a . (Monad m, Data a) => a -> m TypeMap)
everythingButTypeM f = everythingButM $ (,) <$> f <*> isType @t
-- | Returns true if a == t.
requires AllowAmbiguousTypes
isType :: forall a b . (Typeable a, Typeable b) => b -> Bool
isType _ = isJust $ eqT @a @b
-- | Variation of "everything" with an added stop condition
-- Just like 'everything', this is stolen from SYB package.
everythingButM
:: forall m . (forall a . (Monad m, Data a) => a -> (m TypeMap, Bool))
-> (forall a . (Monad m, Data a) => a -> m TypeMap)
everythingButM f x = do
let (v, stop) = f x
if stop
then v
else Data.gmapQr
(\e acc -> do
e' <- e
a <- acc
return (e' `IM.union` a)
)
v
(everythingButM f)
x
-- | Attempts to get the type for expressions in a lazy and cost saving way.
-- Avoids costly desugaring of Expressions and only obtains the type at the leaf of an expression.
--
Implementation is taken from : HieAst.hs < / ghc / ghc / blob/1f5cc9dc8aeeafa439d6d12c3c4565ada524b926 / compiler / hieFile / HieAst.hs >
Slightly adapted to work for the supported GHC versions 8.2.1 - 8.6.4
--
See # 16233 < / ghc / ghc / issues/16233 >
getType
:: GhcMonad m => GHC.LHsExpr Compat.GhcTc -> m (Maybe (GHC.SrcSpan, Type.Type))
getType e@(GHC.L spn e') =
-- Some expression forms have their type immediately available
let
tyOpt = case e' of
Compat.HsOverLitType t -> Just t
Compat.HsLitType t -> Just t
Compat.HsLamType t -> Just t
Compat.HsLamCaseType t -> Just t
Compat.HsCaseType t -> Just t
Compat.ExplicitListType t -> Just t
Compat.ExplicitSumType t -> Just t
Compat.HsMultiIfType t -> Just t
_ -> Nothing
in case tyOpt of
Just t -> return $ Just (spn ,t)
Nothing
| skipDesugaring e' -> pure Nothing
| otherwise -> do
hsc_env <- GHC.getSession
(_, mbe) <- liftIO $ Desugar.deSugarExpr hsc_env e
let res = (spn, ) . CoreUtils.exprType <$> mbe
pure res
where
-- | Skip desugaring of these expressions for performance reasons.
--
See impact on output ( esp . missing type annotations or links )
before marking more things here as ' False ' . See impact on
-- performance before marking more things as 'True'.
skipDesugaring :: GHC.HsExpr a -> Bool
skipDesugaring expression = case expression of
GHC.HsVar{} -> False
GHC.HsUnboundVar{} -> False
GHC.HsConLikeOut{} -> False
GHC.HsRecFld{} -> False
GHC.HsOverLabel{} -> False
GHC.HsIPVar{} -> False
GHC.HsWrap{} -> False
_ -> True
| null | https://raw.githubusercontent.com/haskell/haskell-ide-engine/d84b84322ccac81bf4963983d55cc4e6e98ad418/hie-plugin-api/Haskell/Ide/Engine/TypeMap.hs | haskell | # LANGUAGE RankNTypes #
| Generate a mapping from an Interval to types.
Intervals may overlap and return more specific results.
| Obtain details map for types.
| Variation of "everything" that does not recurse into children of type t
| Returns true if a == t.
| Variation of "everything" with an added stop condition
Just like 'everything', this is stolen from SYB package.
| Attempts to get the type for expressions in a lazy and cost saving way.
Avoids costly desugaring of Expressions and only obtains the type at the leaf of an expression.
Some expression forms have their type immediately available
| Skip desugaring of these expressions for performance reasons.
performance before marking more things as 'True'. | # LANGUAGE TupleSections #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE LambdaCase #
module Haskell.Ide.Engine.TypeMap where
import qualified Data.IntervalMap.FingerTree as IM
import qualified GHC
import GHC ( TypecheckedModule, GhcMonad )
import Bag
import BasicTypes
import Data.Data as Data
import Control.Monad.IO.Class
import Control.Applicative
import Data.Maybe
import qualified TcHsSyn
import qualified CoreUtils
import qualified Type
import qualified Desugar
import qualified Haskell.Ide.Engine.Compat as Compat
import Haskell.Ide.Engine.ArtifactMap
genTypeMap :: GHC.GhcMonad m => TypecheckedModule -> m TypeMap
genTypeMap tm = do
let typecheckedSource = GHC.tm_typechecked_source tm
everythingInTypecheckedSourceM typecheckedSource
everythingInTypecheckedSourceM
:: GhcMonad m => GHC.TypecheckedSource -> m TypeMap
everythingInTypecheckedSourceM xs = bs
where
bs = foldBag (liftA2 IM.union) processBind (return IM.empty) xs
processBind :: GhcMonad m => GHC.LHsBindLR Compat.GhcTc Compat.GhcTc -> m TypeMap
processBind x@(GHC.L (GHC.RealSrcSpan spn) b) =
case b of
Compat.FunBindGen t fmatches ->
case GHC.mg_origin fmatches of
Generated -> return IM.empty
FromSource -> do
im <- types fmatches
return $ IM.singleton (rspToInt spn) t `IM.union` im
Compat.AbsBinds bs -> everythingInTypecheckedSourceM bs
_ -> types x
processBind _ = return IM.empty
types :: forall m a . (GhcMonad m, Data a) => a -> m TypeMap
types = everythingButTypeM @GHC.Id (ty `combineM` fun `combineM` funBind)
where
ty :: forall a' . (Data a') => a' -> m TypeMap
ty term = case cast term of
(Just lhsExprGhc@(GHC.L (GHC.RealSrcSpan spn) _)) ->
getType lhsExprGhc >>= \case
Nothing -> return IM.empty
Just (_, typ) -> return (IM.singleton (rspToInt spn) typ)
_ -> return IM.empty
fun :: forall a' . (Data a') => a' -> m TypeMap
fun term = case cast term of
(Just (GHC.L (GHC.RealSrcSpan spn) hsPatType)) ->
return (IM.singleton (rspToInt spn) (TcHsSyn.hsPatType hsPatType))
_ -> return IM.empty
funBind :: forall a' . (Data a') => a' -> m TypeMap
funBind term = case cast term of
(Just (GHC.L (GHC.RealSrcSpan spn) (Compat.FunBindType t))) ->
return (IM.singleton (rspToInt spn) t)
_ -> return IM.empty
| Combine two queries into one using alternative combinator .
combineM
:: (forall a . (Monad m, Data a) => a -> m TypeMap)
-> (forall a . (Monad m, Data a) => a -> m TypeMap)
-> (forall a . (Monad m, Data a) => a -> m TypeMap)
combineM f g x = do
a <- f x
b <- g x
return (a `IM.union` b)
requires AllowAmbiguousTypes
everythingButTypeM
:: forall t m
. (Typeable t)
=> (forall a . (Monad m, Data a) => a -> m TypeMap)
-> (forall a . (Monad m, Data a) => a -> m TypeMap)
everythingButTypeM f = everythingButM $ (,) <$> f <*> isType @t
requires AllowAmbiguousTypes
isType :: forall a b . (Typeable a, Typeable b) => b -> Bool
isType _ = isJust $ eqT @a @b
everythingButM
:: forall m . (forall a . (Monad m, Data a) => a -> (m TypeMap, Bool))
-> (forall a . (Monad m, Data a) => a -> m TypeMap)
everythingButM f x = do
let (v, stop) = f x
if stop
then v
else Data.gmapQr
(\e acc -> do
e' <- e
a <- acc
return (e' `IM.union` a)
)
v
(everythingButM f)
x
Implementation is taken from : HieAst.hs < / ghc / ghc / blob/1f5cc9dc8aeeafa439d6d12c3c4565ada524b926 / compiler / hieFile / HieAst.hs >
Slightly adapted to work for the supported GHC versions 8.2.1 - 8.6.4
See # 16233 < / ghc / ghc / issues/16233 >
getType
:: GhcMonad m => GHC.LHsExpr Compat.GhcTc -> m (Maybe (GHC.SrcSpan, Type.Type))
getType e@(GHC.L spn e') =
let
tyOpt = case e' of
Compat.HsOverLitType t -> Just t
Compat.HsLitType t -> Just t
Compat.HsLamType t -> Just t
Compat.HsLamCaseType t -> Just t
Compat.HsCaseType t -> Just t
Compat.ExplicitListType t -> Just t
Compat.ExplicitSumType t -> Just t
Compat.HsMultiIfType t -> Just t
_ -> Nothing
in case tyOpt of
Just t -> return $ Just (spn ,t)
Nothing
| skipDesugaring e' -> pure Nothing
| otherwise -> do
hsc_env <- GHC.getSession
(_, mbe) <- liftIO $ Desugar.deSugarExpr hsc_env e
let res = (spn, ) . CoreUtils.exprType <$> mbe
pure res
where
See impact on output ( esp . missing type annotations or links )
before marking more things here as ' False ' . See impact on
skipDesugaring :: GHC.HsExpr a -> Bool
skipDesugaring expression = case expression of
GHC.HsVar{} -> False
GHC.HsUnboundVar{} -> False
GHC.HsConLikeOut{} -> False
GHC.HsRecFld{} -> False
GHC.HsOverLabel{} -> False
GHC.HsIPVar{} -> False
GHC.HsWrap{} -> False
_ -> True
|
0f0f347b9cd771340d6deacea3ed99cef189580bc0bf159752fa93941a483276 | crategus/cl-cffi-gtk | gdk-demo.lisp | (defpackage :gdk-demo
(:use :gtk :gdk :gdk-pixbuf :gobject :glib :cairo :cffi :common-lisp)
(:export #:demo-put-pixel))
(in-package :gdk-demo)
(defun rel-path (filename)
(let ((system-path (asdf:system-source-directory :gtk-example)))
(princ-to-string (merge-pathnames filename system-path))))
2020 - 11 - 21
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/22156e3e2356f71a67231d9868abcab3582356f3/demo/gdk-demo/gdk-demo.lisp | lisp | (defpackage :gdk-demo
(:use :gtk :gdk :gdk-pixbuf :gobject :glib :cairo :cffi :common-lisp)
(:export #:demo-put-pixel))
(in-package :gdk-demo)
(defun rel-path (filename)
(let ((system-path (asdf:system-source-directory :gtk-example)))
(princ-to-string (merge-pathnames filename system-path))))
2020 - 11 - 21
| |
eb4a63ac455fa464e8bf842850487526d7f7518dc25b57df64434c539c7b332e | rvantonder/hack_parallel | marshal_tools.mli | *
* Copyright ( c ) 2015 , Facebook , Inc.
* All rights reserved .
*
* This source code is licensed under the BSD - style license found in the
* LICENSE file in the root directory of this source tree . An additional grant
* of patent rights can be found in the PATENTS file in the same directory .
*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*)
exception Invalid_Int_Size_Exception
exception Payload_Size_Too_Large_Exception
exception Malformed_Preamble_Exception
exception Writing_Preamble_Exception
exception Writing_Payload_Exception
exception Reading_Preamble_Exception
exception Reading_Payload_Exception
type remote_exception_data = {
message : string;
stack : string;
}
val to_fd_with_preamble: Unix.file_descr -> 'a -> unit
val from_fd_with_preamble: Unix.file_descr -> 'a
| null | https://raw.githubusercontent.com/rvantonder/hack_parallel/c9d0714785adc100345835c1989f7c657e01f629/src/utils/marshal_tools.mli | ocaml | *
* Copyright ( c ) 2015 , Facebook , Inc.
* All rights reserved .
*
* This source code is licensed under the BSD - style license found in the
* LICENSE file in the root directory of this source tree . An additional grant
* of patent rights can be found in the PATENTS file in the same directory .
*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*)
exception Invalid_Int_Size_Exception
exception Payload_Size_Too_Large_Exception
exception Malformed_Preamble_Exception
exception Writing_Preamble_Exception
exception Writing_Payload_Exception
exception Reading_Preamble_Exception
exception Reading_Payload_Exception
type remote_exception_data = {
message : string;
stack : string;
}
val to_fd_with_preamble: Unix.file_descr -> 'a -> unit
val from_fd_with_preamble: Unix.file_descr -> 'a
| |
56ca03452ca7fa4a2a4f3ef022e2283eabaa30380f5a102b72b11e99757bf009 | lemmaandrew/CodingBatHaskell | allStar.hs | From
Given a string , compute recursively a new string where all the adjacent chars are
now separated by a " .
Given a string, compute recursively a new string where all the adjacent chars are
now separated by a \"*\".
-}
import Test.Hspec ( hspec, describe, it, shouldBe )
allStar :: String -> String
allStar str = undefined
main :: IO ()
main = hspec $ describe "Tests:" $ do
it "\"h*e*l*l*o\"" $
allStar "hello" `shouldBe` "h*e*l*l*o"
it "\"a*b*c\"" $
allStar "abc" `shouldBe` "a*b*c"
it "\"a*b\"" $
allStar "ab" `shouldBe` "a*b"
it "\"a\"" $
allStar "a" `shouldBe` "a"
it "\"\"" $
allStar "" `shouldBe` ""
it "\"3*.*1*4\"" $
allStar "3.14" `shouldBe` "3*.*1*4"
it "\"C*h*o*c*o*l*a*t*e\"" $
allStar "Chocolate" `shouldBe` "C*h*o*c*o*l*a*t*e"
it "\"1*2*3*4\"" $
allStar "1234" `shouldBe` "1*2*3*4"
| null | https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/Recursion-1/allStar.hs | haskell | From
Given a string , compute recursively a new string where all the adjacent chars are
now separated by a " .
Given a string, compute recursively a new string where all the adjacent chars are
now separated by a \"*\".
-}
import Test.Hspec ( hspec, describe, it, shouldBe )
allStar :: String -> String
allStar str = undefined
main :: IO ()
main = hspec $ describe "Tests:" $ do
it "\"h*e*l*l*o\"" $
allStar "hello" `shouldBe` "h*e*l*l*o"
it "\"a*b*c\"" $
allStar "abc" `shouldBe` "a*b*c"
it "\"a*b\"" $
allStar "ab" `shouldBe` "a*b"
it "\"a\"" $
allStar "a" `shouldBe` "a"
it "\"\"" $
allStar "" `shouldBe` ""
it "\"3*.*1*4\"" $
allStar "3.14" `shouldBe` "3*.*1*4"
it "\"C*h*o*c*o*l*a*t*e\"" $
allStar "Chocolate" `shouldBe` "C*h*o*c*o*l*a*t*e"
it "\"1*2*3*4\"" $
allStar "1234" `shouldBe` "1*2*3*4"
| |
a7b319f6c0a2ad5352a23635374dca18b5556b8a2d2b268d2ce40ad19bed6dbd | samrushing/irken-compiler | scheduler.scm | ;; -*- Mode: Irken -*-
(require "doom/kqueue.scm")
(require "doom/timeq.scm")
;; XXX there's a strong argument here for using vectors rather than a
map for the pending events , since all unixen maintain a strict fd
;; limit (FD_SETSIZE). will revisit this for performance tuning.
;; [I'll probably try that when I do epoll for linux]
;; XXX we will need a priority queue.
for each EVFILT , we have separate map of ident=>continuation
(define (make-poller)
{ kqfd = (kqueue/kqueue)
runnable = (queue/make)
nwait = 0 ;; how many events are waiting?
filters = (make-vector EVFILT_SYSCOUNT (tree/empty))
ievents = (make-changelist 1000)
oevents = (make-changelist 1000)
})
(define the-poller (make-poller))
;; store the thread-id and current exc handler along with the continuation.
(define (poller/enqueue k)
(queue/add! the-poller.runnable (:tuple *thread-id* *the-exception-handler* k)))
(define (poller/enqueue* thread-id exc-handler k)
(queue/add! the-poller.runnable (:tuple thread-id exc-handler k)))
(define (protect thunk thread-id)
;; (printf "starting thread " (int thread-id) "\n")
(try
(begin
(set! *thread-id* thread-id)
(thunk))
except
EXN
-> (begin
(printf "unhandled exception in thread: " (int thread-id) "\n")
(print-exception EXN))
))
(define next-thread-id
(let ((thread-counter 1))
(lambda ()
(let ((val thread-counter))
(inc! thread-counter)
val))))
(define *thread-id* 0)
(defmacro debugf
(debugf x ...)
-> (printf (bold "[" (int *thread-id*) "] ") x ...)
)
TODO : since this code is using getcc / putcc directly , it 's possible
;; that it's not type-safe around coro switch boundaries. look into
;; this.
(define (poller/fork thunk)
(poller/enqueue (getcc))
(protect thunk (next-thread-id))
(poller/dispatch))
(define (poller/yield)
(poller/enqueue (getcc))
(poller/dispatch))
(define (poller/dispatch)
(match (queue/pop! the-poller.runnable) with
(maybe:yes save)
-> (poller/restore save)
(maybe:no)
-> (poller/wait-and-schedule)))
(define (poller/make-save k)
(:tuple *thread-id* *the-exception-handler* k))
(define (poller/schedule save)
(queue/add! the-poller.runnable save))
(define poller/restore
(:tuple thread-id exn-handler k)
-> (begin
;; (debugf "restoring " (int thread-id) "\n")
(set! *the-exception-handler* exn-handler)
(set! *thread-id* thread-id)
(putcc k #u)))
;; these funs know that EVFILT values are consecutive small negative ints
;; here's a question: is this an abuse of macros? Does it make the code
harder or easier to read ? I think this is related to ' setf ' in CL -
;; since the target of set! can't be a funcall.
(defmacro kfilt (kfilt f) -> the-poller.filters[(- f)])
(define (poller/lookup-event ident filter)
(tree/member (kfilt filter) int-cmp ident))
(define (poller/add-event ident filter k)
(inc! the-poller.nwait)
(tree/insert! (kfilt filter)
int-cmp ident
(poller/make-save k)))
(define (poller/delete-event ident filter)
(when (tree/delete!? (kfilt filter) int-cmp ident)
(dec! the-poller.nwait)))
;; put the current thread to sleep while waiting for the kevent (ident, filter).
(define (poller/wait-for ident filter)
(let ((k (getcc)))
(when (= filter EVFILT_WRITE)
(printf (ansi red (int ident))))
(match (poller/lookup-event ident filter) with
(maybe:no)
-> (begin
(add-kevent the-poller.ievents ident filter EV_ADDONE)
(poller/add-event ident filter k)
(poller/dispatch)
#u
)
(maybe:yes _) -> (raise (:PollerEventAlreadyPresent ident filter))
)))
(define (poller/wait-for-read fd)
(poller/wait-for fd EVFILT_READ))
(define (poller/wait-for-write fd)
(poller/wait-for fd EVFILT_WRITE))
(define (poller/forget fd)
(poller/delete-event fd EVFILT_READ)
(poller/delete-event fd EVFILT_WRITE)
)
(define poller/enqueue-waiting-thread
(:kev ident filter)
-> (match (poller/lookup-event ident filter) with
(maybe:yes (:tuple thread-id exc-handler k))
-> (begin
(when (= filter EVFILT_WRITE)
(printf (ansi blue (int ident)))
(for-map k v (kfilt filter)
(printf (ansi yellow (int k)))))
(poller/delete-event ident filter)
(when (= filter EVFILT_WRITE)
(for-map k v (kfilt filter)
(printf (ansi cyan (int k)))))
(poller/enqueue* thread-id exc-handler k))
(maybe:no)
-> (begin
(printf "poller: no such event: " (int ident) " " (int filter) "\n")
(printf " keys for that filter: " (join int->string " " (tree/keys (kfilt filter))) "\n")
(raise (:PollerNoSuchEvent ident filter)))
))
(define (poller/wait-and-schedule)
;; all the runnable threads have done their bit, now throw it to kevent().
(when (and (eq? the-timeq (tree:empty)) (= the-poller.nwait 0))
(debugf "no more events, exiting.\n")
(%exit #f 1))
(let ((timeout (timeq/time-to-next))
(n (syscall (kevent the-poller.kqfd the-poller.ievents the-poller.oevents timeout))))
(set! the-poller.ievents.index 0)
(for-range i n
(poller/enqueue-waiting-thread
(get-kevent the-poller.oevents i)))
(timeq/schedule)
(poller/dispatch)
))
| null | https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/doom/scheduler.scm | scheme | -*- Mode: Irken -*-
XXX there's a strong argument here for using vectors rather than a
limit (FD_SETSIZE). will revisit this for performance tuning.
[I'll probably try that when I do epoll for linux]
XXX we will need a priority queue.
how many events are waiting?
store the thread-id and current exc handler along with the continuation.
(printf "starting thread " (int thread-id) "\n")
that it's not type-safe around coro switch boundaries. look into
this.
(debugf "restoring " (int thread-id) "\n")
these funs know that EVFILT values are consecutive small negative ints
here's a question: is this an abuse of macros? Does it make the code
since the target of set! can't be a funcall.
put the current thread to sleep while waiting for the kevent (ident, filter).
all the runnable threads have done their bit, now throw it to kevent(). |
(require "doom/kqueue.scm")
(require "doom/timeq.scm")
map for the pending events , since all unixen maintain a strict fd
for each EVFILT , we have separate map of ident=>continuation
(define (make-poller)
{ kqfd = (kqueue/kqueue)
runnable = (queue/make)
filters = (make-vector EVFILT_SYSCOUNT (tree/empty))
ievents = (make-changelist 1000)
oevents = (make-changelist 1000)
})
(define the-poller (make-poller))
(define (poller/enqueue k)
(queue/add! the-poller.runnable (:tuple *thread-id* *the-exception-handler* k)))
(define (poller/enqueue* thread-id exc-handler k)
(queue/add! the-poller.runnable (:tuple thread-id exc-handler k)))
(define (protect thunk thread-id)
(try
(begin
(set! *thread-id* thread-id)
(thunk))
except
EXN
-> (begin
(printf "unhandled exception in thread: " (int thread-id) "\n")
(print-exception EXN))
))
(define next-thread-id
(let ((thread-counter 1))
(lambda ()
(let ((val thread-counter))
(inc! thread-counter)
val))))
(define *thread-id* 0)
(defmacro debugf
(debugf x ...)
-> (printf (bold "[" (int *thread-id*) "] ") x ...)
)
TODO : since this code is using getcc / putcc directly , it 's possible
(define (poller/fork thunk)
(poller/enqueue (getcc))
(protect thunk (next-thread-id))
(poller/dispatch))
(define (poller/yield)
(poller/enqueue (getcc))
(poller/dispatch))
(define (poller/dispatch)
(match (queue/pop! the-poller.runnable) with
(maybe:yes save)
-> (poller/restore save)
(maybe:no)
-> (poller/wait-and-schedule)))
(define (poller/make-save k)
(:tuple *thread-id* *the-exception-handler* k))
(define (poller/schedule save)
(queue/add! the-poller.runnable save))
(define poller/restore
(:tuple thread-id exn-handler k)
-> (begin
(set! *the-exception-handler* exn-handler)
(set! *thread-id* thread-id)
(putcc k #u)))
harder or easier to read ? I think this is related to ' setf ' in CL -
(defmacro kfilt (kfilt f) -> the-poller.filters[(- f)])
(define (poller/lookup-event ident filter)
(tree/member (kfilt filter) int-cmp ident))
(define (poller/add-event ident filter k)
(inc! the-poller.nwait)
(tree/insert! (kfilt filter)
int-cmp ident
(poller/make-save k)))
(define (poller/delete-event ident filter)
(when (tree/delete!? (kfilt filter) int-cmp ident)
(dec! the-poller.nwait)))
(define (poller/wait-for ident filter)
(let ((k (getcc)))
(when (= filter EVFILT_WRITE)
(printf (ansi red (int ident))))
(match (poller/lookup-event ident filter) with
(maybe:no)
-> (begin
(add-kevent the-poller.ievents ident filter EV_ADDONE)
(poller/add-event ident filter k)
(poller/dispatch)
#u
)
(maybe:yes _) -> (raise (:PollerEventAlreadyPresent ident filter))
)))
(define (poller/wait-for-read fd)
(poller/wait-for fd EVFILT_READ))
(define (poller/wait-for-write fd)
(poller/wait-for fd EVFILT_WRITE))
(define (poller/forget fd)
(poller/delete-event fd EVFILT_READ)
(poller/delete-event fd EVFILT_WRITE)
)
(define poller/enqueue-waiting-thread
(:kev ident filter)
-> (match (poller/lookup-event ident filter) with
(maybe:yes (:tuple thread-id exc-handler k))
-> (begin
(when (= filter EVFILT_WRITE)
(printf (ansi blue (int ident)))
(for-map k v (kfilt filter)
(printf (ansi yellow (int k)))))
(poller/delete-event ident filter)
(when (= filter EVFILT_WRITE)
(for-map k v (kfilt filter)
(printf (ansi cyan (int k)))))
(poller/enqueue* thread-id exc-handler k))
(maybe:no)
-> (begin
(printf "poller: no such event: " (int ident) " " (int filter) "\n")
(printf " keys for that filter: " (join int->string " " (tree/keys (kfilt filter))) "\n")
(raise (:PollerNoSuchEvent ident filter)))
))
(define (poller/wait-and-schedule)
(when (and (eq? the-timeq (tree:empty)) (= the-poller.nwait 0))
(debugf "no more events, exiting.\n")
(%exit #f 1))
(let ((timeout (timeq/time-to-next))
(n (syscall (kevent the-poller.kqfd the-poller.ievents the-poller.oevents timeout))))
(set! the-poller.ievents.index 0)
(for-range i n
(poller/enqueue-waiting-thread
(get-kevent the-poller.oevents i)))
(timeq/schedule)
(poller/dispatch)
))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.